From 6c206edd235e81872f67f0e6434283cc854ce246 Mon Sep 17 00:00:00 2001 From: Kun Chen <3233006+kunchenguid@users.noreply.github.com> Date: Thu, 6 Aug 2026 15:49:14 -0700 Subject: [PATCH 01/14] feat(send): close answered decisions at answer time via --resolve-key (#1842) A captain decision opened by a keyed needs-decision:/blocked: status line orphaned as permanently open whenever the answer kicked off work: the worker's next event is working [key=] in a different key namespace, so no resolved [key=] ever landed and the OPEN DECISIONS fold kept listing the answered decision forever. Remove the writer-dependency at its source: the answering firstmate already holds the decision key when it sends the answer, so fm-send's new --resolve-key flag (repeatable) appends the closing resolved line to this home's own state/.status after the submit is confirmed. The close is a local ledger append for crewmates, local secondmates, and remote secondmates alike - a remote mate's escalations reach this ledger through the parent-replies ingest, so only the answer message crosses the transport. Safety: each named key must currently be open per the authoritative status_open_decisions fold or fm-send refuses before sending; a failed or unconfirmed send never closes a key; an append failure after a delivered answer exits nonzero with the manual close command so the decision re-surfaces instead of silently vanishing; a send without the flag closes nothing, and working:/done: still never clear a captain decision. Complementary fixes: the wake-drain OPEN DECISIONS section prints the answer-with-close command hint at the moment of use; brief scaffolds separate resolved's two duties (keyed-phase end vs decision closure) and state that a done:/working: line never closes a decision even when the answer started that work, keeping worker self-close for blockers that clear without a firstmate reply; AGENTS.md and docs/architecture.md carry the one-line pointers to the fm-send contract. --- AGENTS.md | 3 +- bin/fm-brief.sh | 9 +- bin/fm-classify-lib.sh | 4 + bin/fm-send.sh | 127 ++++++- bin/fm-test-run.sh | 2 +- bin/fm-wake-drain.sh | 5 + docs/architecture.md | 1 + tests/fm-brief.test.sh | 4 +- tests/fm-send-resolve-key.test.sh | 407 +++++++++++++++++++++ tests/fm-wake-drain-open-decisions.test.sh | 2 + 10 files changed, 557 insertions(+), 7 deletions(-) create mode 100755 tests/fm-send-resolve-key.test.sh diff --git a/AGENTS.md b/AGENTS.md index 7547155a593..8d13eeb0b61 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -281,6 +281,7 @@ After spawning, confirm the worker is processing the brief, handle any trust dia A persistent secondmate is recorded in the secondmate registry and runtime state, never as a backlog work item. Steer a worker with short single-line messages through fail-closed `fm-send`; put long instructions in a file. +When a steer answers an open keyed decision or blocker, pass `fm-send`'s `--resolve-key` so the answer itself closes that decision record at answer time, identically for local and remote workers (contract: `bin/fm-send.sh` header). A secondmate's routed reply returns through status or a document pointer, not by firstmate peeking into its chat. For the parent-owned correlation, recovery, and escalation contract on marked secondmate requests, see `bin/fm-pending-reply-lib.sh`. Supervise all live work under section 8. @@ -324,7 +325,7 @@ Apart from that single supported abort, do not hand-edit, commit, restart, or st Once ownership is settled, validate exactly once against that final head so no obsolete or intermediate head is ever treated as authoritative. An ask-user finding returns as `needs-decision`; firstmate decides only when the configured authority permits, otherwise escalates to the captain. -Send the same worker one exact decision naming the decision key, step, action, affected finding IDs, instructions where needed, and exact response command. +Send the same worker one exact decision naming the decision key, step, action, affected finding IDs, instructions where needed, and exact response command, passing `--resolve-key` so the worker's open decision record closes at answer time. Require the matching `resolved` event, forbid `--yes`, and require the worker to process every synchronous return until completion or a genuinely new escalation. Resume fleet supervision immediately after the decision lands. diff --git a/bin/fm-brief.sh b/bin/fm-brief.sh index 79f835e342d..a873c840517 100755 --- a/bin/fm-brief.sh +++ b/bin/fm-brief.sh @@ -245,7 +245,8 @@ Never append \`working:\` merely to acknowledge receipt or announce that a marke When a routed-work phase has a supervisor-actionable material change worth reporting under the rule above, give that reported phase a stable key. If its first reportable event is \`working [key=]: {material phase}\`, use the same key on its later \`$PAUSED_VERB\`, \`done\`, \`failed\`, \`needs-decision\`, or \`blocked\` event so the earlier working phase is superseded. When a keyed phase ends without another reportable state, append \`resolved [key=]: {why it is no longer active}\`. -When a decision you escalated is answered or a blocker clears and your domain resumes, append \`resolved: {how it was decided or unblocked}\` (keyed with \`[key=]\` if you opened it with one) so it is durably closed instead of resurfacing behind later unrelated events. +\`resolved\` separately closes an escalated decision or blocker, and only a \`resolved\` line carrying that decision's exact key closes it: a later \`done\` or \`working\` event never does, even when the answer is what started that work. +The main firstmate's answer normally writes that closing line at answer time; when a blocker or wait clears WITHOUT an answer from the main firstmate, append \`resolved: {how it cleared}\` yourself (keyed with \`[key=]\` if you opened it with one) as your domain resumes. Routine internal supervision, heartbeats, retries, and crewmate churn stay inside your own home and must not touch that status file. # Definition of done @@ -329,7 +330,8 @@ The report is the only thing that survives, so anything worth keeping must be in 5. If you hit the same obstacle twice, append \`blocked: {why}\` and stop; firstmate will help. 6. If a decision belongs to a human (product choices, destructive actions), append \`needs-decision: {summary of options}\` and stop. Firstmate will reply with the decision. - When firstmate replies or a blocker clears and you resume, append \`resolved: {how it was decided or unblocked}\` (add the same \`[key=]\` if you opened it with one) so the decision or blocker is durably closed and does not keep resurfacing. + A decision or blocker you opened stays open until a \`resolved\` line carrying its exact key lands; a later \`done:\` or \`working:\` line never closes it, even when the answer is what started that work. + Firstmate's reply normally writes that closing line at answer time; when a blocker or wait clears WITHOUT a firstmate reply, append \`resolved: {how it cleared}\` yourself (same \`[key=]\` if you opened it with one) as you resume. 7. Never stop, restart, or update the shared \`no-mistakes\` daemon - it is one instance serving every lane/home, so restarting it kills other lanes' in-flight pipeline runs. On ANY no-mistakes daemon error, append \`blocked: {the daemon error}\` and stop; only firstmate manages the daemon. @@ -444,7 +446,8 @@ $RULE1 5. If you hit the same obstacle twice, append \`blocked: {why}\` and stop; firstmate will help. 6. If a decision belongs above the implementation worker (product choices, destructive actions, ask-user findings), append \`needs-decision: {summary of options}\` and stop. Firstmate will apply the configured authority and reply with the decision. - When firstmate replies or a blocker clears and you resume, append \`resolved: {how it was decided or unblocked}\` (add the same \`[key=]\` if you opened it with one) so the decision or blocker is durably closed and does not keep resurfacing. + A decision or blocker you opened stays open until a \`resolved\` line carrying its exact key lands; a later \`done:\` or \`working:\` line never closes it, even when the answer is what started that work. + Firstmate's reply normally writes that closing line at answer time; when a blocker or wait clears WITHOUT a firstmate reply, append \`resolved: {how it cleared}\` yourself (same \`[key=]\` if you opened it with one) as you resume. 7. Never stop, restart, or update the shared \`no-mistakes\` daemon - it is one instance serving every lane/home, so restarting it kills other lanes' in-flight pipeline runs. On ANY no-mistakes daemon error, append \`blocked: {the daemon error}\` and stop; only firstmate manages the daemon. diff --git a/bin/fm-classify-lib.sh b/bin/fm-classify-lib.sh index 5284208cefc..07863b0e369 100755 --- a/bin/fm-classify-lib.sh +++ b/bin/fm-classify-lib.sh @@ -154,6 +154,10 @@ status_is_paused_or_captain_held() { # # line OPENS a keyed decision, and only an explicit resolution or a verified # captain-held backlog transfer referencing that key CLOSES it; a later unrelated # terminal line never clears an open captain decision. +# Who WRITES the closing line is owned elsewhere: the answering firstmate closes +# at answer time through fm-send's --resolve-key (bin/fm-send.sh header), and a +# worker self-closes only a blocker that cleared without an answer (bin/fm-brief.sh +# rule 6), so closure never depends on a busy worker's discipline. # # Decision key grammar (backward-compatible with the existing ": " # format): an OPTIONAL "[key=]" token sits between the verb and the colon, diff --git a/bin/fm-send.sh b/bin/fm-send.sh index 25ed2a0876c..41f72f43229 100755 --- a/bin/fm-send.sh +++ b/bin/fm-send.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # Send one line of literal text to a crewmate endpoint, then Enter. -# Usage: fm-send.sh +# Usage: fm-send.sh [--resolve-key ]... # may be an exact task id, a legacy fm- task label resolved # through this home's state/.meta, or an explicit well-formed backend # target. fm-send refuses unresolved guesses rather than falling back to a @@ -37,6 +37,28 @@ # re-sending a recovery request for an already-open expectation so a second # record is not created. Direct unmarked captain input never creates one. # +# Decision closure (answerer-closes): pass --resolve-key (repeatable, +# before the message) when this send answers an open keyed needs-decision: or +# blocked: record in the target task's state/.status. After the submit is +# confirmed, fm-send itself appends the closing +# "resolved [key=]: answered: " line to that status file, +# so the captain-facing OPEN DECISIONS record closes at answer time and never +# depends on the busy worker writing a matching resolved line. The close is a +# LOCAL append for every target kind - crewmate, scout, local secondmate, and +# remote secondmate alike - because the open-decision ledger fm-wake-drain +# folds lives in this home's own state dir (a remote mate's escalations reach +# it through the parent-replies ingest); only the answer message crosses the +# backend or remote transport. Each named key must currently be open in that +# ledger per status_open_decisions (bin/fm-classify-lib.sh) or fm-send refuses +# before sending, so a mistyped key cannot deliver an answer while silently +# orphaning the decision. A failed or unconfirmed send never closes a key; a +# delivered answer whose closing append fails exits nonzero with the exact +# manual close command, leaving the decision open to re-surface (the safe +# direction). A send without the flag never closes anything: a routine steer, +# working:, or done: event still cannot clear a captain decision. The flag is +# refused with --key, with an explicit backend target (no task ledger in this +# home), and with an empty message. +# # After a successful text submit fm-send pauses FM_SEND_SETTLE seconds (default 1, # 0 disables) before returning: submit confirmation only proves the text was # accepted, but the harness needs a beat to spin up the turn before its busy @@ -75,6 +97,10 @@ fi . "$SCRIPT_DIR/fm-marker-lib.sh" # shellcheck source=bin/fm-pending-reply-lib.sh . "$SCRIPT_DIR/fm-pending-reply-lib.sh" +# shellcheck source=bin/fm-classify-lib.sh +. "$SCRIPT_DIR/fm-classify-lib.sh" +# shellcheck source=bin/fm-line-cap-lib.sh +. "$SCRIPT_DIR/fm-line-cap-lib.sh" FM_GUARD_CONTINUE_LINE='This is a supervision warning only; the requested message WILL still be sent.' "$SCRIPT_DIR/fm-guard.sh" || true @@ -255,6 +281,41 @@ fm_send_resolve_target "$RAW_TARGET" || exit 1 T=$RESOLVED_TARGET shift +# Collect --resolve-key flags (answerer-closes; see the header contract). They +# must precede --key or the message text; everything after the last flag is the +# message exactly as before, so ordinary sends are byte-identical. +RESOLVE_KEYS= +fm_send_add_resolve_key() { # + local k=$1 + case "$k" in + ''|*[!A-Za-z0-9._-]*) + echo "error: --resolve-key '$k' is not a valid decision key (allowed: A-Z a-z 0-9 . _ -)" >&2 + return 1 + ;; + esac + case " $RESOLVE_KEYS " in + *" $k "*) + echo "error: duplicate --resolve-key '$k'" >&2 + return 1 + ;; + esac + RESOLVE_KEYS="${RESOLVE_KEYS}${RESOLVE_KEYS:+ }$k" +} +while :; do + case "${1:-}" in + --resolve-key) + [ $# -ge 2 ] || { echo "error: --resolve-key requires a key" >&2; exit 1; } + fm_send_add_resolve_key "$2" || exit 1 + shift 2 + ;; + --resolve-key=*) + fm_send_add_resolve_key "${1#--resolve-key=}" || exit 1 + shift + ;; + *) break ;; + esac +done + if [ "$TARGET_BACKEND" != remote ]; then fm_backend_validate "$TARGET_BACKEND" || exit 1 fi @@ -273,6 +334,56 @@ if [ -n "$TARGET_SELECTOR" ] && [ -n "$TARGET_META" ] && [ "$(fm_meta_get "$TARG TARGET_TASK_ID=$(fm_send_id_from_meta "$TARGET_META") fi +# Validate the answerer-closes request before any durable mutation or send: the +# target must have a task ledger in THIS home, the send must carry an answer +# message, and every named key must be open right now in that ledger per the +# ONE authoritative fold (status_open_decisions). Refusing here, before the +# send, is what keeps a mistyped key loud instead of delivering an answer that +# silently leaves its decision open. +RESOLVE_STATUS_FILE= +if [ -n "$RESOLVE_KEYS" ]; then + if [ -z "$TARGET_SELECTOR" ] || [ -z "$TARGET_META" ]; then + echo "error: --resolve-key needs a task selector resolved through this home's metadata; an explicit backend target has no decision ledger here" >&2 + exit 1 + fi + if [ "${1:-}" = "--key" ]; then + echo "error: --resolve-key cannot accompany --key; answering a decision requires a text answer" >&2 + exit 1 + fi + if [ -z "$*" ]; then + echo "error: --resolve-key requires a nonempty answer message" >&2 + exit 1 + fi + RESOLVE_TASK_ID=$(fm_send_id_from_meta "$TARGET_META") + RESOLVE_STATUS_FILE="$STATE/$RESOLVE_TASK_ID.status" + resolve_open_set=$(status_open_decisions "$RESOLVE_STATUS_FILE") + for k in $RESOLVE_KEYS; do + case "$resolve_open_set" in + "$k"$'\t'*|*$'\n'"$k"$'\t'*) ;; + *) + echo "error: --resolve-key '$k': no open decision or blocker with that key in $RESOLVE_STATUS_FILE (already closed, mistyped, or transferred). Re-check the OPEN DECISIONS listing, then resend without that key or with the right one; nothing was sent." >&2 + exit 1 + ;; + esac + done +fi + +# Close each answered decision in this home's ledger, only after delivery is +# fully confirmed. An append failure exits nonzero with the manual close +# command; the decision then stays open and re-surfaces, never silently lost. +fm_send_close_resolved_keys() { # + local note=$1 k line + note=$(printf '%s' "$note" | tr '\n\r\t' ' ' | LC_ALL=C tr -d '\000-\037\177') + for k in $RESOLVE_KEYS; do + line="resolved [key=$k]: answered: $note" + fm_cap_line_var "$line" + if ! printf '%s\n' "$FM_LINE_CAP_LINE" >> "$RESOLVE_STATUS_FILE"; then + echo "error: the answer was delivered to $T, but decision key '$k' could not be closed in $RESOLVE_STATUS_FILE. Close it manually with: echo 'resolved [key=$k]: ' >> $RESOLVE_STATUS_FILE - do not resend the answer." >&2 + return 1 + fi + done +} + # Resolve the target's harness from its meta (recorded by fm-spawn), used only to # scope the codex `$` popup-settle below. A task selector carries # meta; an explicit backend-target escape hatch has none, so its harness is @@ -286,6 +397,12 @@ fi # error with the attempted resolution attached. if [ "${1:-}" = "--key" ]; then + case "$*" in + *--resolve-key*) + echo "error: --resolve-key cannot accompany --key; answering a decision requires a text answer" >&2 + exit 1 + ;; + esac key=$2 semantic_key=$(fm_send_normalize_key "$key") if [ "$TARGET_BACKEND" = remote ]; then @@ -301,6 +418,9 @@ if [ "${1:-}" = "--key" ]; then fm_send_record_interrupt "$semantic_key" || exit 1 else MESSAGE=$* + # The pre-marker answer text, kept for the closing resolved note so the + # durable ledger records the plain answer without marker or corr bytes. + RESOLVE_ANSWER_TEXT=$MESSAGE if [ "$MARK_FROM_FIRSTMATE" = 1 ]; then # Reuse an existing correlation id for recovery resends; otherwise create a # durable parent expectation before delivery. Transport success never @@ -403,6 +523,11 @@ else exit 1 fi fi + # Delivery is fully confirmed: close each answered decision in this home's + # ledger (answerer-closes; see the header contract). + if [ -n "$RESOLVE_KEYS" ]; then + fm_send_close_resolved_keys "$RESOLVE_ANSWER_TEXT" || exit 1 + fi # Submit landed with exact empty. Confirmation only proves the text was # accepted; the harness still needs a beat to spin up the # turn before its busy footer shows. Pause so an immediate peek catches the diff --git a/bin/fm-test-run.sh b/bin/fm-test-run.sh index 0aeb32e6e8c..2b3e21ba744 100755 --- a/bin/fm-test-run.sh +++ b/bin/fm-test-run.sh @@ -190,7 +190,7 @@ family_for_basename() { ;; fm-backend-herdr.test.sh|fm-backend-tmux-smoke.test.sh|fm-backend.test.sh|\ fm-tmux-agent-liveness.test.sh|\ - fm-herdr-session-cleanup.test.sh|fm-send-strict.test.sh|fm-spawn-batch.test.sh|\ + fm-herdr-session-cleanup.test.sh|fm-send-resolve-key.test.sh|fm-send-strict.test.sh|fm-spawn-batch.test.sh|\ fm-spawn-dispatch-profile.test.sh|\ fm-trace-context-spawn.test.sh|fm-spawn-worktree-settle.test.sh|\ fm-teardown-endpoint-safety.test.sh) diff --git a/bin/fm-wake-drain.sh b/bin/fm-wake-drain.sh index a7ad47082a0..0807bb80f82 100755 --- a/bin/fm-wake-drain.sh +++ b/bin/fm-wake-drain.sh @@ -79,6 +79,11 @@ EOF if [ "$omitted" -gt 0 ]; then printf 'OPEN DECISIONS: %d more omitted (byte cap)\n' "$omitted" fi + # Answerer-closes hint, printed at exactly the moment an answer gets written: + # the send that answers a listed decision also closes it, so closure never + # depends on the busy worker writing a matching resolved line (contract: + # bin/fm-send.sh header). + printf "OPEN DECISIONS: close one by answering it: bin/fm-send.sh --resolve-key ''\n" } # shellcheck disable=SC2317,SC2329 # Invoked by trap handlers below. diff --git a/docs/architecture.md b/docs/architecture.md index c20b321c6ef..00f4b6979a7 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -30,6 +30,7 @@ Routine watcher polling, supervision no-ops, elapsed waiting time, and absorbed A declared external wait trades that silence for one bounded recheck per pause window, so a forgotten pause cannot remain invisible indefinitely. Crew status files are append-only wake-event logs, not current-state fields. Because of that, a per-wake read of only the latest line can bury an earlier still-open `needs-decision`/`blocked` under later unrelated appends; `fm-wake-drain.sh` prints a separate, fleet-wide OPEN DECISIONS section on every drain (including the empty-queue path session-start relies on), built through `fm-classify-lib.sh`'s cursor-backed incremental scan using the authoritative `status_open_decisions` fold semantics so the buried decision keeps surfacing until it is explicitly resolved while each drain reads only new status-log appends. +The explicit resolution is written by the actor that answers, not the busy worker: `fm-send`'s `--resolve-key` appends the closing `resolved` line to this home's own copy of the ledger at answer time, which covers crewmates, local secondmates, and remote secondmates identically because a remote mate's escalations reach that local copy through the parent-replies ingest and only the answer message itself crosses the transport. `bin/fm-crew-state.sh ` is the cheap current-state read for an actionable heartbeat review: it attributes a no-mistakes run, active or terminal, only when it matches the crew's branch and current code identity, then keeps that run-step authoritative even if the pane has closed. The script header owns the exact run-head ancestry rules. During no-mistakes' `ci` monitor phase, it also reads the ci step log tail because `axi status` reports both "still waiting on checks" and "checks green, waiting on merge" as `ci,running`. diff --git a/tests/fm-brief.test.sh b/tests/fm-brief.test.sh index 0e139133ad2..a348e2d345e 100755 --- a/tests/fm-brief.test.sh +++ b/tests/fm-brief.test.sh @@ -663,8 +663,10 @@ test_pause_verb_override_renders_all_brief_scaffolds() { # shellcheck disable=SC2016 # Literal backticks and braces must remain unexpanded. assert_no_grep '`paused: {why}`' "$brief" \ "$kind brief still instructs the default paused status" - assert_grep 'or a blocker clears' "$brief" \ + assert_grep 'a blocker or wait clears' "$brief" \ "$kind brief did not require durable resolution when a blocker clears" + assert_grep 'even when the answer is what started that work' "$brief" \ + "$kind brief did not warn that an answer-started done/working never closes a decision" done pass "fm-brief.sh: custom pause verb renders in every scaffold" } diff --git a/tests/fm-send-resolve-key.test.sh b/tests/fm-send-resolve-key.test.sh new file mode 100755 index 00000000000..75a8d6661c5 --- /dev/null +++ b/tests/fm-send-resolve-key.test.sh @@ -0,0 +1,407 @@ +#!/usr/bin/env bash +# fm-send answerer-closes (--resolve-key) behavior. +# +# A captain decision opened by a keyed needs-decision:/blocked: status line +# historically stayed open forever when the answer kicked off work: the worker's +# next line is working [key=], never resolved [key=]. +# fm-send's --resolve-key removes that writer-dependency at its source: the +# ANSWERING firstmate closes the decision in this home's own ledger at answer +# time. These tests drive the real fm-send executable over stubbed transports +# and assert closure through the real consumer (fm-wake-drain.sh's OPEN +# DECISIONS section), never through source text: +# 1. An answer send closes the open decision, including the answer-starts-work +# scenario where the worker never writes a matching resolved line. +# 2. A routine steer without the flag never closes anything, and a working:/ +# done: line still cannot clear a captain decision. +# 3. A key that is not open refuses BEFORE anything is sent (mistype safety). +# 4. A failed or unconfirmed send never closes a key. +# 5. A local secondmate answer is marked+corr'd yet closes the same way, and +# the closing line carries the plain answer, not marker or corr bytes. +# 6. A remote secondmate answer differs only at the transport layer: the +# message crosses the stubbed ssh transport while the close is the same +# local ledger append; a failed transport closes nothing. +# 7. Flag misuse (--key, empty message, explicit backend target) refuses. +set -u + +# shellcheck source=tests/lib.sh +. "$(dirname "${BASH_SOURCE[0]}")/lib.sh" +# shellcheck source=/dev/null +. "$ROOT/bin/fm-marker-lib.sh" + +SEND="$ROOT/bin/fm-send.sh" +DRAIN="$ROOT/bin/fm-wake-drain.sh" + +TMP_ROOT=$(fm_test_tmproot fm-send-resolve-key) + +# Stub tmux: logs literal typed text to FM_SEND_LOG and lets the submit path +# reach a clean "empty" verdict (numeric cursor_y, empty bordered composer). +# FM_FAKE_TMUX_SEND_FAIL=1 makes send-keys fail so the delivery-failure leg can +# assert that a failed send closes nothing. +make_stubs() { # -> echoes fakebin dir + local dir=$1 fb="$1/fakebin" + mkdir -p "$fb" + cat > "$fb/tmux" <<'SH' +#!/usr/bin/env bash +set -u +case "${1:-}" in + send-keys) + [ "${FM_FAKE_TMUX_SEND_FAIL:-0}" = 1 ] && exit 1 + shift + literal=0 + while [ $# -gt 0 ]; do + case "$1" in + -t) shift 2 ;; + -l) literal=1; shift ;; + *) break ;; + esac + done + if [ "$literal" = 1 ]; then + printf '%s' "${1:-}" >> "$FM_SEND_LOG" + fi + exit 0 ;; + display-message) + for a in "$@"; do case "$a" in *cursor_y*) printf '1\n'; exit 0 ;; esac; done + printf 'fakepane\n'; exit 0 ;; + capture-pane) printf '╭────╮\n│ │\n╰────╯\n'; exit 0 ;; + list-windows) exit 0 ;; +esac +exit 0 +SH + chmod +x "$fb/tmux" + cat > "$fb/sleep" <<'SH' +#!/usr/bin/env bash +exit 0 +SH + chmod +x "$fb/sleep" + # Stub ssh transport for the remote-secondmate legs, selected via FM_SSH_BIN. + # Records the full remote invocation and exits FM_FAKE_SSH_RC (default 0). + cat > "$fb/fake-ssh" <<'SH' +#!/usr/bin/env bash +cat > /dev/null +printf '%s\n' "$*" >> "$FM_SSH_LOG" +exit "${FM_FAKE_SSH_RC:-0}" +SH + chmod +x "$fb/fake-ssh" + printf '%s\n' "$fb" +} + +# run_send : run the real fm-send +# with the stubs on PATH against the given home. Guard noise goes to stderr, +# captured per test when the diagnostic matters. +run_send() { + local fb=$1 home=$2 log=$3; shift 3 + : > "$log" + env PATH="$fb:$PATH" \ + FM_ROOT_OVERRIDE="$home" FM_HOME="$home" FM_SEND_LOG="$log" FM_SEND_SETTLE=0 \ + "$SEND" "$@" 2>/dev/null +} + +setup_home() { # -> echoes a fresh home dir with an empty state/ + local home="$TMP_ROOT/$1-$RANDOM" + mkdir -p "$home/state" + printf '%s\n' "$home" +} + +drain_out() { # + FM_STATE_OVERRIDE="$1/state" "$DRAIN" 2>/dev/null +} + +test_answer_send_closes_open_decision() { + local dir fb log home rc out + dir="$TMP_ROOT/closes"; mkdir -p "$dir" + fb=$(make_stubs "$dir"); log="$dir/send.log" + home=$(setup_home closes) + fm_write_meta "$home/state/t1.meta" "window=sess:fm-t1" "kind=ship" + printf 'needs-decision [key=api-shape]: pick REST or RPC\n' > "$home/state/t1.status" + printf 'working: kept busy on an unrelated stream\n' >> "$home/state/t1.status" + + out=$(drain_out "$home") + printf '%s' "$out" | grep -F '[key=api-shape]' >/dev/null \ + || fail "precondition: the buried decision should list as open before the answer" + + run_send "$fb" "$home" "$log" t1 --resolve-key api-shape "go with REST"; rc=$? + expect_code 0 "$rc" "an answer send with --resolve-key should succeed" + assert_contains "$(cat "$log")" "go with REST" "the answer text should reach the worker" + grep -F 'resolved [key=api-shape]: answered: go with REST' "$home/state/t1.status" >/dev/null \ + || fail "fm-send did not append the closing resolved line:"$'\n'"$(cat "$home/state/t1.status")" + + out=$(drain_out "$home") + if printf '%s' "$out" | grep -F 'OPEN DECISIONS' >/dev/null; then + fail "the answered decision still lists as open: $out" + fi + pass "fm-send --resolve-key: the answer send itself closes the open decision" +} + +test_answer_starts_work_never_orphans() { + local dir fb log home rc out + dir="$TMP_ROOT/starts-work"; mkdir -p "$dir" + fb=$(make_stubs "$dir"); log="$dir/send.log" + home=$(setup_home starts-work) + fm_write_meta "$home/state/t2.meta" "window=sess:fm-t2" "kind=ship" + printf 'needs-decision [key=rollout]: big-bang or phased\n' > "$home/state/t2.status" + + run_send "$fb" "$home" "$log" t2 --resolve-key rollout "phased, gate each region"; rc=$? + expect_code 0 "$rc" "the rollout answer send should succeed" + # The forensic scenario: the answer starts a workstream, so the worker's next + # events use a DIFFERENT key namespace and it never writes + # resolved [key=rollout] itself. + printf 'working [key=phased-impl]: building region gates\n' >> "$home/state/t2.status" + printf 'done [key=phased-impl]: PR up\n' >> "$home/state/t2.status" + + out=$(drain_out "$home") + if printf '%s' "$out" | grep -F 'OPEN DECISIONS' >/dev/null; then + fail "the answered decision orphaned after the answer started work: $out" + fi + pass "fm-send --resolve-key: an answer that starts a workstream leaves no orphaned decision" +} + +test_routine_steer_never_closes() { + local dir fb log home rc out + dir="$TMP_ROOT/routine"; mkdir -p "$dir" + fb=$(make_stubs "$dir"); log="$dir/send.log" + home=$(setup_home routine) + fm_write_meta "$home/state/t3.meta" "window=sess:fm-t3" "kind=ship" + printf 'needs-decision [key=schema]: split or embed\n' > "$home/state/t3.status" + + run_send "$fb" "$home" "$log" t3 "unrelated nudge, keep going"; rc=$? + expect_code 0 "$rc" "a routine steer should still succeed" + printf 'working: resumed\n' >> "$home/state/t3.status" + printf 'done: unrelated milestone\n' >> "$home/state/t3.status" + + if grep -F 'resolved' "$home/state/t3.status" >/dev/null; then + fail "a routine steer wrote a resolved line: $(cat "$home/state/t3.status")" + fi + out=$(drain_out "$home") + printf '%s' "$out" | grep -F '[key=schema]' >/dev/null \ + || fail "a routine steer (or later working/done lines) cleared an unanswered captain decision: $out" + pass "fm-send: a send without --resolve-key never closes a decision, and working/done still cannot" +} + +test_not_open_key_refuses_before_send() { + local dir fb log home err rc out + dir="$TMP_ROOT/not-open"; mkdir -p "$dir" + fb=$(make_stubs "$dir"); log="$dir/send.log"; err="$dir/send.err" + home=$(setup_home not-open) + fm_write_meta "$home/state/t4.meta" "window=sess:fm-t4" "kind=ship" + printf 'needs-decision [key=real-key]: choose\n' > "$home/state/t4.status" + + : > "$log" + env PATH="$fb:$PATH" \ + FM_ROOT_OVERRIDE="$home" FM_HOME="$home" FM_SEND_LOG="$log" FM_SEND_SETTLE=0 \ + "$SEND" t4 --resolve-key mistyped "the answer" >/dev/null 2>"$err"; rc=$? + [ "$rc" -ne 0 ] || fail "a not-open key should refuse" + assert_contains "$(cat "$err")" "--resolve-key 'mistyped'" "the refusal should name the bad key" + assert_contains "$(cat "$err")" "nothing was sent" "the refusal should state nothing was sent" + [ ! -s "$log" ] || fail "a refused answer still typed text: $(cat "$log")" + if grep -F 'resolved' "$home/state/t4.status" >/dev/null; then + fail "a refused answer still closed something: $(cat "$home/state/t4.status")" + fi + out=$(drain_out "$home") + printf '%s' "$out" | grep -F '[key=real-key]' >/dev/null \ + || fail "the real decision disappeared after a refused answer: $out" + pass "fm-send --resolve-key: a key that is not open refuses loudly before anything is sent" +} + +test_failed_send_does_not_close() { + local dir fb log home rc out + dir="$TMP_ROOT/send-fail"; mkdir -p "$dir" + fb=$(make_stubs "$dir"); log="$dir/send.log" + home=$(setup_home send-fail) + fm_write_meta "$home/state/t5.meta" "window=sess:fm-t5" "kind=ship" + printf 'blocked [key=creds]: need the deploy token\n' > "$home/state/t5.status" + + : > "$log" + env PATH="$fb:$PATH" FM_FAKE_TMUX_SEND_FAIL=1 \ + FM_ROOT_OVERRIDE="$home" FM_HOME="$home" FM_SEND_LOG="$log" FM_SEND_SETTLE=0 \ + "$SEND" t5 --resolve-key creds "token is in the vault now" >/dev/null 2>&1; rc=$? + [ "$rc" -ne 0 ] || fail "a failed backend send should exit nonzero" + if grep -F 'resolved' "$home/state/t5.status" >/dev/null; then + fail "a failed send still closed the decision: $(cat "$home/state/t5.status")" + fi + out=$(drain_out "$home") + printf '%s' "$out" | grep -F '[key=creds]' >/dev/null \ + || fail "the blocker vanished after a failed send: $out" + pass "fm-send --resolve-key: a failed send never closes the decision" +} + +test_multiple_keys_close_together() { + local dir fb log home rc out + dir="$TMP_ROOT/multi"; mkdir -p "$dir" + fb=$(make_stubs "$dir"); log="$dir/send.log" + home=$(setup_home multi) + fm_write_meta "$home/state/t6.meta" "window=sess:fm-t6" "kind=ship" + { + printf 'needs-decision [key=k1]: first\n' + printf 'blocked [key=k2]: second\n' + printf 'needs-decision [key=k3]: third, unanswered\n' + } > "$home/state/t6.status" + + run_send "$fb" "$home" "$log" t6 --resolve-key k1 --resolve-key k2 \ + "one answer covering both"; rc=$? + expect_code 0 "$rc" "an answer resolving two keys should succeed" + out=$(drain_out "$home") + printf '%s' "$out" | grep -F '[key=k3]' >/dev/null \ + || fail "the unanswered third decision must stay open: $out" + if printf '%s' "$out" | grep -E '\[key=k1\]|\[key=k2\]' >/dev/null; then + fail "an answered key is still open after a multi-key answer: $out" + fi + pass "fm-send --resolve-key: one answer closes each named key and only those" +} + +test_local_secondmate_answer_marked_and_closed() { + local dir fb log home rc got out closing + dir="$TMP_ROOT/sm"; mkdir -p "$dir" + fb=$(make_stubs "$dir"); log="$dir/send.log" + home=$(setup_home sm) + fm_write_secondmate_meta "$home/state/domain.meta" "$home" "sess:fm-domain" + printf 'needs-decision [key=fleet-split]: shard by team or by repo\n' > "$home/state/domain.status" + + run_send "$fb" "$home" "$log" fm-domain --resolve-key fleet-split "shard by team"; rc=$? + expect_code 0 "$rc" "a secondmate answer send should succeed" + got=$(cat "$log") + case "$got" in + "$FM_FROMFIRST_MARK"corr=*) : ;; + *) fail "the secondmate answer lost its from-firstmate marker/corr framing" ;; + esac + closing=$(grep -F 'resolved [key=fleet-split]' "$home/state/domain.status" || true) + [ -n "$closing" ] || fail "the secondmate decision was not closed: $(cat "$home/state/domain.status")" + case "$closing" in + *corr=*) fail "the closing line leaked the corr token: $closing" ;; + esac + case "$closing" in + *"$FM_FROMFIRST_SEPARATOR"*) fail "the closing line leaked marker bytes" ;; + esac + assert_contains "$closing" "shard by team" "the closing line should carry the plain answer" + out=$(drain_out "$home") + if printf '%s' "$out" | grep -F 'OPEN DECISIONS' >/dev/null; then + fail "the answered secondmate decision still lists as open: $out" + fi + pass "fm-send --resolve-key: a marked local-secondmate answer closes with the plain answer text" +} + +# Remote secondmate: the answer crosses the (stubbed) ssh transport through the +# real fm-on.sh + registry route, while the close is the SAME local ledger +# append as every other target kind - the transport is the only difference. +setup_remote_home() { # -> echoes home dir with remote meta + registry + local home + home=$(setup_home "$1") + mkdir -p "$home/data" + fm_write_meta "$home/state/rsm.meta" \ + "window=fm-remote:w1:p1" \ + "endpoint_task_id=rsm" \ + "harness=claude" \ + "kind=secondmate" \ + "mode=secondmate" \ + "yolo=off" \ + "remote_host=remote-mac" \ + "remote_root=/remote/root" \ + "remote_backend=herdr" \ + "remote_herdr_session=fm-remote" \ + "remote_target=fm-remote:w1:p1" + cat > "$home/data/secondmates.md" < "$ssh_log" + home=$(setup_remote_home remote-ok) + printf 'needs-decision [key=upgrade-window]: tonight or the weekend\n' > "$home/state/rsm.status" + + : > "$log" + env PATH="$fb:$PATH" \ + FM_ROOT_OVERRIDE="$ROOT" FM_HOME="$home" FM_SEND_LOG="$log" FM_SEND_SETTLE=0 \ + FM_SSH_BIN="$fb/fake-ssh" FM_SSH_LOG="$ssh_log" FM_FAKE_SSH_RC=0 \ + "$SEND" rsm --resolve-key upgrade-window "the weekend, freeze Friday" >/dev/null 2>&1; rc=$? + expect_code 0 "$rc" "a remote secondmate answer send should succeed" + assert_grep 'fm-remote-entrypoint.sh' "$ssh_log" \ + "the answer message should cross the remote transport" + grep -F 'resolved [key=upgrade-window]: answered: the weekend, freeze Friday' "$home/state/rsm.status" >/dev/null \ + || fail "the remote answer did not close the local ledger: $(cat "$home/state/rsm.status")" + out=$(drain_out "$home") + if printf '%s' "$out" | grep -F 'OPEN DECISIONS' >/dev/null; then + fail "the answered remote-secondmate decision still lists as open: $out" + fi + pass "fm-send --resolve-key: a remote-secondmate answer closes the same local ledger, transport-only difference" +} + +test_remote_transport_failure_does_not_close() { + local dir fb log home ssh_log rc out + dir="$TMP_ROOT/remote-fail"; mkdir -p "$dir" + fb=$(make_stubs "$dir"); log="$dir/send.log"; ssh_log="$dir/ssh.log"; : > "$ssh_log" + home=$(setup_remote_home remote-fail) + printf 'blocked [key=quota]: remote host is out of runway\n' > "$home/state/rsm.status" + + : > "$log" + env PATH="$fb:$PATH" \ + FM_ROOT_OVERRIDE="$ROOT" FM_HOME="$home" FM_SEND_LOG="$log" FM_SEND_SETTLE=0 \ + FM_SSH_BIN="$fb/fake-ssh" FM_SSH_LOG="$ssh_log" FM_FAKE_SSH_RC=1 \ + "$SEND" rsm --resolve-key quota "quota refreshed, resume" >/dev/null 2>&1; rc=$? + [ "$rc" -ne 0 ] || fail "a failed remote transport should exit nonzero" + if grep -F 'resolved' "$home/state/rsm.status" >/dev/null; then + fail "a failed remote send still closed the decision: $(cat "$home/state/rsm.status")" + fi + out=$(drain_out "$home") + printf '%s' "$out" | grep -F '[key=quota]' >/dev/null \ + || fail "the remote blocker vanished after a failed transport: $out" + pass "fm-send --resolve-key: a failed remote transport never closes the decision" +} + +test_flag_misuse_refuses() { + local dir fb log home err rc + dir="$TMP_ROOT/misuse"; mkdir -p "$dir" + fb=$(make_stubs "$dir"); log="$dir/send.log"; err="$dir/send.err" + home=$(setup_home misuse) + fm_write_meta "$home/state/t7.meta" "window=sess:fm-t7" "kind=ship" + printf 'needs-decision [key=k]: choose\n' > "$home/state/t7.status" + + # --resolve-key with --key (both orders) is refused: an answer is text. + : > "$log" + env PATH="$fb:$PATH" FM_ROOT_OVERRIDE="$home" FM_HOME="$home" FM_SEND_LOG="$log" FM_SEND_SETTLE=0 \ + "$SEND" t7 --resolve-key k --key Enter >/dev/null 2>"$err"; rc=$? + [ "$rc" -ne 0 ] || fail "--resolve-key before --key should refuse" + assert_contains "$(cat "$err")" "cannot accompany --key" "the --key refusal should be explicit" + : > "$log" + env PATH="$fb:$PATH" FM_ROOT_OVERRIDE="$home" FM_HOME="$home" FM_SEND_LOG="$log" FM_SEND_SETTLE=0 \ + "$SEND" t7 --key Enter --resolve-key k >/dev/null 2>"$err"; rc=$? + [ "$rc" -ne 0 ] || fail "--resolve-key after --key should refuse instead of being silently dropped" + assert_contains "$(cat "$err")" "cannot accompany --key" "the trailing --resolve-key refusal should be explicit" + + # An empty answer message is refused. + env PATH="$fb:$PATH" FM_ROOT_OVERRIDE="$home" FM_HOME="$home" FM_SEND_LOG="$log" FM_SEND_SETTLE=0 \ + "$SEND" t7 --resolve-key k >/dev/null 2>"$err"; rc=$? + [ "$rc" -ne 0 ] || fail "an empty answer message should refuse" + assert_contains "$(cat "$err")" "nonempty answer message" "the empty-message refusal should be explicit" + + # An explicit backend target has no task ledger in this home. + env PATH="$fb:$PATH" FM_ROOT_OVERRIDE="$home" FM_HOME="$home" FM_SEND_LOG="$log" FM_SEND_SETTLE=0 \ + "$SEND" sess:elsewhere --resolve-key k "answer" >/dev/null 2>"$err"; rc=$? + [ "$rc" -ne 0 ] || fail "an explicit backend target should refuse --resolve-key" + assert_contains "$(cat "$err")" "no decision ledger" "the explicit-target refusal should be explicit" + + # A malformed key is refused before anything else. + env PATH="$fb:$PATH" FM_ROOT_OVERRIDE="$home" FM_HOME="$home" FM_SEND_LOG="$log" FM_SEND_SETTLE=0 \ + "$SEND" t7 --resolve-key 'bad key!' "answer" >/dev/null 2>"$err"; rc=$? + [ "$rc" -ne 0 ] || fail "a malformed key should refuse" + assert_contains "$(cat "$err")" "not a valid decision key" "the malformed-key refusal should be explicit" + + [ ! -s "$log" ] || fail "a refused misuse still typed text: $(cat "$log")" + if grep -F 'resolved' "$home/state/t7.status" >/dev/null; then + fail "a refused misuse still closed something: $(cat "$home/state/t7.status")" + fi + pass "fm-send --resolve-key: --key, empty message, explicit targets, and malformed keys refuse loudly" +} + +test_answer_send_closes_open_decision +test_answer_starts_work_never_orphans +test_routine_steer_never_closes +test_not_open_key_refuses_before_send +test_failed_send_does_not_close +test_multiple_keys_close_together +test_local_secondmate_answer_marked_and_closed +test_remote_secondmate_answer_closes_locally +test_remote_transport_failure_does_not_close +test_flag_misuse_refuses diff --git a/tests/fm-wake-drain-open-decisions.test.sh b/tests/fm-wake-drain-open-decisions.test.sh index bd69a0141cc..c290954884e 100755 --- a/tests/fm-wake-drain-open-decisions.test.sh +++ b/tests/fm-wake-drain-open-decisions.test.sh @@ -32,6 +32,8 @@ test_buried_decision_still_surfaces() { grep -F 'OPEN DECISIONS' "$out" >/dev/null || fail "buried decision produced no OPEN DECISIONS section" grep -F 'task1' "$out" | grep -F '[key=api-shape]' | grep -F 'pick REST or RPC' >/dev/null \ || fail "buried needs-decision was not surfaced with its task, key, and note" + grep -F "close one by answering it: bin/fm-send.sh --resolve-key " "$out" >/dev/null \ + || fail "open section is missing the answerer-closes hint" pass "a needs-decision buried under later routine/other-key lines still reports as open" } From fb368dcc6380bfba5b4ba35722106692f3e789b3 Mon Sep 17 00:00:00 2001 From: Kun Chen <3233006+kunchenguid@users.noreply.github.com> Date: Thu, 6 Aug 2026 17:36:45 -0700 Subject: [PATCH 02/14] fix(bin): seed remote secondmates from supplied origins (#1836) * feat(secondmate): seed a remote home from a supplied project origin Remote seeding required a local projects/ clone purely to read `git remote get-url origin` into the provisioning manifest, so setting up a remote second mate forced disposable clones and no-mistakes inits in the primary home for projects that home has no reason to hold. Firstmate now resolves the origin itself and names it as =. The seed validates and transports what it is given, and the receiving host re-validates it rather than trusting the sender; bin/fm-project-origin-lib.sh is the single owner of which URLs are accepted, refusing executable remote-helper transports, option-shaped values, and unusable spellings at both ends. A bare still reads an already-present clone's origin, so nothing that works today has to change. Registry consistency is unchanged: an unregistered or local-only project is still refused. A remote seed therefore creates nothing in the primary home beyond the route, the charter, and its launch record. The lifecycle test now seeds a registered project the primary has never cloned and asserts the primary project tree is byte-identical afterwards, alongside refusals for a missing origin, an unsafe origin, a local-only project, and an unregistered project. * no-mistakes(review): Clarify project origin documentation ownership * no-mistakes(document): Document supplied-origin remote seeding contract * feat(secondmate): accept project origins from any host or forge Firstmate is a shared template, so a project origin must be able to name any host: GitHub Enterprise on a private domain, GitLab hosted or self-hosted, Bitbucket, Gitea, Codeberg, sr.ht, a bare IP, an SSH config alias, or a plain server nobody else has heard of. The validator already decided on structure rather than on a forge allowlist, and this makes that guarantee explicit and closes the two gaps that a host-agnostic rule exposed: - a bracketed IPv6 literal in the scp-like form is now accepted, so a host reachable only by address is not excluded - a "/../" traversal inside a local or file: origin is now refused, because that names a path on the cloning host's own filesystem The library is the single owner of the accepted forms, and its header says plainly that there is no host, domain, or forge allowlist and there must never be one. The skill keeps its distinct agent-operating lines (the agent resolves and supplies the origin; a remote seed creates nothing in the primary home beyond the route, the charter, and its launch record) and points at the library for URL acceptance and at the operator doc for the rest. The lifecycle test now drives Bitbucket, a self-hosted enterprise domain, a self-hosted GitLab over ssh with a port, and a bare scp-like custom host through the real seed, manifest, transport, and remote provisioning path in one seed, asserting each URL reaches git unchanged and each clone carries its own origin's content. The unit matrix leads with non-GitHub hosts for the same reason. * no-mistakes(review): Validate project origin authorities safely * no-mistakes: apply CI fixes * no-mistakes: apply CI fixes --- .../skills/secondmate-provisioning/SKILL.md | 8 +- bin/fm-project-origin-lib.sh | 180 ++++++++++++++++ bin/fm-remote-home-provision.sh | 14 +- bin/fm-remote-home-seed.sh | 48 ++++- docs/architecture.md | 3 +- docs/configuration.md | 2 +- docs/remote-secondmates.md | 18 +- docs/scripts.md | 1 + tests/fm-backend.test.sh | 45 ++-- tests/fm-project-origin.test.sh | 110 ++++++++++ ...fm-remote-secondmate-lifecycle-e2e.test.sh | 198 ++++++++++++++++++ 11 files changed, 579 insertions(+), 48 deletions(-) create mode 100644 bin/fm-project-origin-lib.sh create mode 100755 tests/fm-project-origin.test.sh diff --git a/.agents/skills/secondmate-provisioning/SKILL.md b/.agents/skills/secondmate-provisioning/SKILL.md index 12b90bed3ab..10a94bc8e74 100644 --- a/.agents/skills/secondmate-provisioning/SKILL.md +++ b/.agents/skills/secondmate-provisioning/SKILL.md @@ -69,11 +69,13 @@ bin/fm-home-seed.sh {...|--no-projects} Provision a whole remote home through its configured SSH host with: ```sh -bin/fm-remote-home-seed.sh {...|--no-projects} +bin/fm-remote-home-seed.sh {[=]...|--no-projects} ``` -The remote command transfers a bounded charter and project-origin manifest, then the remote host clones its own Firstmate home and project origins. -It never copies a project tree or the primary process environment. +You resolve each project's origin yourself - from the captain, the project registry, a clone that exists elsewhere, `gh-axi`, or an explicit paste - and name it as `=`; the seed validates and transports what you supply. +A remote seed therefore creates nothing in this home beyond the route, the charter brief, and a launch record once it is launched: never clone a project into `projects/`, initialize no-mistakes here, or run a fleet sync just to seed a remote secondmate. +A bare `` remains a convenience for a project this home already has cloned, whose configured origin is read instead. +[`docs/remote-secondmates.md`](../../../docs/remote-secondmates.md#provision-a-route) owns the rest of the operator contract, and [`bin/fm-project-origin-lib.sh`](../../../bin/fm-project-origin-lib.sh) owns the accepted origin forms. Pass `--no-projects` in the project position to seed the project-less home described above; the same mutual-exclusion and fail-loud-on-omission rules apply. It may only seed a home with no project clones or project-registry entries, and refuses conversion of populated homes without changing them. `-` durably leases a fresh firstmate worktree via `treehouse get --lease` under the secondmate id. diff --git a/bin/fm-project-origin-lib.sh b/bin/fm-project-origin-lib.sh new file mode 100644 index 00000000000..6cdd44c429d --- /dev/null +++ b/bin/fm-project-origin-lib.sh @@ -0,0 +1,180 @@ +#!/usr/bin/env bash +# Validate a project origin URL that one home hands to another. +# +# Firstmate supplies a project's origin instead of discovering it from a local +# clone, and the receiving host re-validates whatever reached it, so this file +# is the single owner of which origins are accepted. Nothing here discovers an +# origin, so no caller has to create a local clone just to learn one. It is +# sourced by both the sending parent (bin/fm-remote-home-seed.sh) and the +# receiving host (bin/fm-remote-home-provision.sh), so an unsafe value is +# refused at each end rather than trusted because the other end already looked +# at it. +# +# Validation is STRUCTURE AND SAFETY ONLY, never the forge or the domain. +# Firstmate is a shared template, so any host must be able to serve a project: +# GitHub, GitHub Enterprise on a private domain, GitLab hosted or self-hosted, +# Bitbucket, Gitea, Codeberg, sr.ht, a bare IP, an SSH config alias, or a plain +# server nobody else has heard of. There is no host, domain, or forge allowlist +# here, and there must never be one. +# +# Accepted forms: +# https://[userinfo@]host[:port]/path, http://…, ssh://…, git://… +# a non-option-shaped plain host or bracketed +# IPv6 literal, an optional numeric port, and +# any path +# file:///path a repository this host can reach as a file +# [user@]host:path scp-like syntax; host may be a name, an SSH +# config alias, an IPv4 address, or a bracketed +# IPv6 literal such as [2001:db8::1] +# /absolute/path a repository on the cloning host's filesystem +# +# Refused: +# remote-helper transports such as "ext::", which git executes as a +# command whenever the cloning host's protocol configuration permits it, and +# the sending home cannot see that configuration +# any other unknown scheme +# option-shaped values a later command line could absorb as a flag +# whitespace and control characters, including embedded newlines +# relative paths, which resolve against whatever directory git happens to +# be in on the other machine +# "/../" traversal inside a local or file: path +fm_project_origin_safe() { # ; 0 when the URL is an accepted clone URL + local url=${1-} rest authority userpart hostpart port inner host path + + case $url in + '' | -*) return 1 ;; + esac + case $url in + *[[:space:]]* | *[[:cntrl:]]*) return 1 ;; + esac + + case $url in + https://?* | http://?* | ssh://?* | git://?*) + rest=${url#*://} + authority=${rest%%/*} + case $authority in + '') return 1 ;; + esac + + hostpart=$authority + case $authority in + *@*) + userpart=${authority%@*} + hostpart=${authority##*@} + case $userpart in + '' | -* | *'['* | *']'*) return 1 ;; + esac + ;; + esac + + case $hostpart in + '['*) + case $hostpart in + *']'*) ;; + *) return 1 ;; + esac + host=${hostpart%%']'*}']' + port=${hostpart#"$host"} + inner=${host#'['} + inner=${inner%']'} + case $inner in + *:*) ;; + *) return 1 ;; + esac + case $inner in + *[!0-9A-Fa-f:.%]*) return 1 ;; + esac + case $port in + '') ;; + :?*) + port=${port#:} + case $port in + *[!0-9]*) return 1 ;; + esac + ;; + *) return 1 ;; + esac + ;; + *) + case $hostpart in + *'['* | *']'*) return 1 ;; + esac + host=${hostpart%%:*} + case $host in + '' | -* | *[!A-Za-z0-9._-]*) return 1 ;; + esac + if [[ $hostpart == *:* ]]; then + port=${hostpart#*:} + case $port in + '' | *[!0-9]*) return 1 ;; + esac + fi + ;; + esac + return 0 + ;; + file:///?*) + case "/${url#file://}/" in + */../*) return 1 ;; + esac + return 0 + ;; + /?*) + case "/$url/" in + */../*) return 1 ;; + esac + return 0 + ;; + *://*) return 1 ;; + esac + + # scp-like [user@]host:path. Strip the user only when its "@" really precedes + # the host, so a path that merely contains "@" keeps its own colon boundary. + rest=$url + case $url in + *@*) + userpart=${url%%@*} + case $userpart in + *:*) ;; + *) rest=${url#*@} ;; + esac + ;; + esac + + case $rest in + '['*) + hostpart=${rest%%']'*}']' + path=${rest#"$hostpart"} + case $path in + :?*) path=${path#:} ;; + *) return 1 ;; + esac + inner=${hostpart#'['} + inner=${inner%']'} + # A bracketed host is only meaningful as an IPv6 literal, so require its + # colon rather than accepting brackets around an arbitrary string. + case $inner in + *:*) ;; + *) return 1 ;; + esac + case $inner in + *[!0-9A-Fa-f:.%]*) return 1 ;; + esac + return 0 + ;; + esac + + case $rest in + *:*) ;; + *) return 1 ;; + esac + host=${rest%%:*} + path=${rest#*:} + case $host in + '' | -* | *[!A-Za-z0-9._-]*) return 1 ;; + esac + case $path in + '' | :*) return 1 ;; + esac + return 0 +} diff --git a/bin/fm-remote-home-provision.sh b/bin/fm-remote-home-provision.sh index 252e17e97fd..8f733d6d3c4 100755 --- a/bin/fm-remote-home-provision.sh +++ b/bin/fm-remote-home-provision.sh @@ -5,10 +5,12 @@ # fm-remote-home-provision.sh < manifest # # Manifest schema fm-remote-home-provision.v1 carries a base64 charter, the -# base64 parent SSH alias, and one base64 project record per line. The remote -# code root is cloned into an absent home, project origins are cloned on this -# host, the project registry and charter are published, the durable -# .fm-secondmate-parent record names this home's route to its parent as +# base64 parent SSH alias, and one base64 project record per line. Each project +# record's origin is the URL the parent resolved and named, so this host clones +# from it and re-validates it through bin/fm-project-origin-lib.sh instead of +# trusting the sender. The remote code root is cloned into an absent home, +# project origins are cloned on this host, the project registry and charter are +# published, the durable .fm-secondmate-parent record names this home's route to its parent as # "remote" - read by bin/fm-teardown.sh's cleanup gate so a delegated public # reply promise, which the subsystem can only carry on the parent's own # filesystem, is never mistaken for one this child could hold - and the @@ -22,6 +24,9 @@ FM_ROOT="${FM_ROOT_OVERRIDE:-$(cd "$SCRIPT_DIR/.." && pwd)}" FM_HOME=${FM_HOME:?FM_HOME is required} MAX_MANIFEST_BYTES=1048576 +# shellcheck source=bin/fm-project-origin-lib.sh +. "$SCRIPT_DIR/fm-project-origin-lib.sh" + die() { printf 'error: %s\n' "$1" >&2; exit 1; } base64_decode_to() { @@ -213,6 +218,7 @@ EOF MODE=$(cat "$TMP/mode") safe_id "$NAME" || die "project name is unsafe: $NAME" [ -n "$ORIGIN" ] || die "project $NAME has no origin" + fm_project_origin_safe "$ORIGIN" || die "project $NAME origin is not an accepted clone URL: $ORIGIN" case "$MODE" in no-mistakes|direct-PR) ;; *) die "project $NAME has unsupported remote mode: $MODE" ;; esac case "$REGISTRY_LINE" in "- $NAME "*) ;; *) die "project $NAME registry line is malformed" ;; esac DEST="$FM_HOME/projects/$NAME" diff --git a/bin/fm-remote-home-seed.sh b/bin/fm-remote-home-seed.sh index f89c9ee8aa3..a679851cbc4 100755 --- a/bin/fm-remote-home-seed.sh +++ b/bin/fm-remote-home-seed.sh @@ -2,7 +2,7 @@ # Register and provision a whole secondmate home on an SSH-reachable host. # # Usage: -# fm-remote-home-seed.sh {...|--no-projects} +# fm-remote-home-seed.sh {[=]...|--no-projects} # # The SSH alias must already reach a host whose non-interactive PATH exposes the # fixed fm-remote-entrypoint.sh from . The command records the @@ -10,6 +10,16 @@ # fm-remote-doctor.sh readiness before touching it, sends a bounded provisioning # manifest through fm-on.sh, and lets the remote host clone its own Firstmate # home and project origins. No project tree or secret environment is copied. +# +# Each project needs an origin the remote account can clone. Firstmate resolves +# that origin and names it as =, so seeding never requires +# a clone of that project in this home; a bare is accepted only when +# this home already has projects/, whose origin is then read instead. +# bin/fm-project-origin-lib.sh owns which URLs are accepted, and this home's +# data/projects.md still owns the project's registered delivery mode, so an +# unregistered or local-only project is refused rather than provisioned. +# Seeding writes nothing under projects/ and needs no fleet sync first. +# # Known provisioning failure rolls the registry back. SSH status 255 preserves # the route and any newly scaffolded brief because completion is unknown and a same-route rerun converges. set -eu @@ -31,9 +41,11 @@ MAX_MANIFEST_BYTES=1048576 . "$SCRIPT_DIR/fm-wake-lib.sh" # shellcheck source=bin/fm-remote-readiness-lib.sh . "$SCRIPT_DIR/fm-remote-readiness-lib.sh" +# shellcheck source=bin/fm-project-origin-lib.sh +. "$SCRIPT_DIR/fm-project-origin-lib.sh" die() { printf 'error: %s\n' "$1" >&2; exit 1; } -usage() { sed -n '2,14p' "$0" | sed 's/^# \{0,1\}//'; exit 2; } +usage() { sed -n '2,21p' "$0" | sed 's/^# \{0,1\}//'; exit 2; } encode() { base64 | tr -d '\n'; } safe_id() { case "$1" in ''|*[!A-Za-z0-9._-]*) return 1 ;; esac; } @@ -69,12 +81,21 @@ case "$REMOTE_ROOT/" in "$REMOTE_HOME/"*) die "remote code root must not be insi NO_PROJECTS=0 PROJECT_NAMES=() +PROJECT_ORIGINS=() for arg in "$@"; do if [ "$arg" = --no-projects ]; then NO_PROJECTS=1 else - safe_id "$arg" || die "invalid project name: $arg" - PROJECT_NAMES+=("$arg") + name=${arg%%=*} + origin= + case "$arg" in *=*) origin=${arg#*=} ;; esac + safe_id "$name" || die "invalid project name: $name" + case "$arg" in + *=*) fm_project_origin_safe "$origin" \ + || die "project $name origin is not an accepted clone URL: $origin" ;; + esac + PROJECT_NAMES+=("$name") + PROJECT_ORIGINS+=("$origin") fi done if [ "$NO_PROJECTS" -eq 1 ]; then @@ -135,9 +156,10 @@ done < "$BRIEF" > "$TMP/charter.remote" PROJECTS_CSV= : > "$TMP/project.records" +PROJECT_INDEX=0 for project in "${PROJECT_NAMES[@]}"; do - SRC="$PROJECTS/$project" - [ -d "$SRC/.git" ] || die "project clone is unavailable: $SRC" + ORIGIN=${PROJECT_ORIGINS[$PROJECT_INDEX]} + PROJECT_INDEX=$((PROJECT_INDEX + 1)) MODE_LINE=$(FM_HOME="$FM_HOME" FM_DATA_OVERRIDE="$DATA" "$SCRIPT_DIR/fm-project-mode.sh" "$project") read -r MODE _ </dev/null || true) - [ -n "$ORIGIN" ] || die "project $project has no origin remote" - REGISTRY_LINE=$(awk -v p="$project" '$1 == "-" && $2 == p { print; exit }' "$DATA/projects.md") + # An origin named on the command line is authoritative. Reading one from a + # clone this home happens to have is only a convenience for the already-cloned + # case; it is never a reason to create one. + if [ -z "$ORIGIN" ] && [ -d "$PROJECTS/$project/.git" ]; then + ORIGIN=$(git -C "$PROJECTS/$project" remote get-url origin 2>/dev/null || true) + fi + [ -n "$ORIGIN" ] \ + || die "project $project has no origin; pass $project= so the remote host can clone it" + fm_project_origin_safe "$ORIGIN" \ + || die "project $project origin is not an accepted clone URL: $ORIGIN" + REGISTRY_LINE=$(awk -v p="$project" '$1 == "-" && $2 == p { print; exit }' "$DATA/projects.md" 2>/dev/null || true) [ -n "$REGISTRY_LINE" ] || die "project $project has no registry record" NAME_B64=$(printf '%s' "$project" | encode) ORIGIN_B64=$(printf '%s' "$ORIGIN" | encode) diff --git a/docs/architecture.md b/docs/architecture.md index 00f4b6979a7..60ee3a50208 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -177,9 +177,8 @@ That keeps spawn launch compatible across claude, codex, opencode, pi, pi-signed `data/secondmates.md` records persistent secondmates with natural-language scopes, project clone lists, and home paths. A local route points directly at its home, while a remote route adds an SSH alias and remote Firstmate code root so the entire home and all of its child work stay on that host. Remote placement pins the remote second-mate agent to Herdr while leaving the remote home's worker backend selection independent, and every non-doctor primary-to-remote `fm-on` command runs through the remote account's Firstmate-owned job worker rather than its SSH process or a Herdr pane. -[`remote-secondmates.md`](remote-secondmates.md) owns current setup, transport, relay, failure, and retirement behavior. +[`remote-secondmates.md`](remote-secondmates.md) owns current setup, supplied-origin provisioning, transport, relay, failure, and retirement behavior. `fm-home-seed.sh` provisions a local isolated home, clones the listed PR-based projects into it, initializes newly cloned `no-mistakes` projects, copies the charter to `data/charter.md`, and `fm-spawn.sh --secondmate` launches it through the same session-provider and status-file path as any direct report. -`fm-remote-home-seed.sh` sends a bounded charter and origin manifest through the generic transport so the remote host clones and provisions its own home and projects. For a domain whose subject is the firstmate repo itself, a deliberate `--no-projects` seed creates a project-less home whose crews take pooled worktrees of that repo instead of separate clones. The signal cannot be mixed with project names or omitted accidentally, and a populated home cannot be converted in place; the full seed contract is in [configuration.md](configuration.md#secondmate-routes-datasecondmatesmd). Herdr secondmate and child placement follows the launcher-binding contract in [Watching and task containers](herdr-backend.md#watching-and-task-containers). diff --git a/docs/configuration.md b/docs/configuration.md index bea06cb8d0b..bddb3bd4a38 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -169,7 +169,7 @@ A remote route adds `host:` and `root:` before the existing fields and places th Use `fm-home-seed.sh validate` to check the complete operational registry contract documented by the command itself. The main first mate routes by reading those scopes with judgment; the project list is provisioning data, not exclusive ownership. Use `fm-home-seed.sh - {...|--no-projects}` to lease a fresh local firstmate worktree for the secondmate home. -Use `fm-remote-home-seed.sh {...|--no-projects}` to provision a whole home on an SSH-reachable host. +For remote provisioning, including supplied project origins, follow [Remote second mates](remote-secondmates.md#provision-a-route). Use the deliberate `--no-projects` signal only for a firstmate-repo domain that needs no separate project clones. It cannot be combined with a project list, and omitting both still fails loudly. A project-less seed requires no existing project clones or `data/projects.md` entries in the home, so it refuses a populated-home conversion without changing that home. diff --git a/docs/remote-secondmates.md b/docs/remote-secondmates.md index fc804929e52..521b4e941b9 100644 --- a/docs/remote-secondmates.md +++ b/docs/remote-secondmates.md @@ -36,7 +36,7 @@ The worker runs one staged job at a time and preempts a running reply long-poll `bin/fm-remote-job-lib.sh` owns that preemption contract, and a preempted poll is indistinguishable from one whose wait window closed with no data, so the re-armed poll loses nothing. Linux uses the same queue and worker protocol without the Aqua-session requirement. The remote account must provide the required toolchain, the selected worker runtime, the selected session backend, and credentials that work on that host. -Project origin URLs recorded by the primary must be reachable from the remote account because projects are cloned on that host rather than copied from the primary. +The origin URL named for each project must be reachable from the remote account because projects are cloned on that host rather than copied from the primary. ## Non-interactive tool contract @@ -115,12 +115,22 @@ A file at `~/.local/bin/fm-remote-entrypoint.sh` that is not Firstmate's own sym Create and fill the normal secondmate charter first, then run: ```sh -bin/fm-remote-home-seed.sh {...|--no-projects} +bin/fm-remote-home-seed.sh {[=]...|--no-projects} ``` `` is the remote Firstmate code clone that supplies tracked scripts. `` is a separate absolute path for the persistent secondmate home and must not overlap the code root. + +Name each project's origin as `=`. +Resolve the concrete origin from the captain, the project registry, an existing clone anywhere, the forge, or an explicit paste rather than imposing one URL template. +Seeding a project this machine has never cloned needs no clone under `projects/`, no `no-mistakes` initialization here, and no fleet sync first. +A bare `` is still accepted when this machine happens to have `projects/`, whose configured origin is then read instead of being retyped. +[`bin/fm-project-origin-lib.sh`](../bin/fm-project-origin-lib.sh) owns which URLs are accepted; it decides on structure and safety alone, so no forge, domain, or host is privileged and a self-hosted server works exactly as a hosted one does. +The primary validates every resolved origin before transport, and the receiving host validates it again before cloning. +The project's registered delivery mode still comes from this machine's `data/projects.md`, so an unregistered or `local-only` project is refused rather than provisioned. + The seed records `host:`, `root:`, and `home:` in `data/secondmates.md`, gates the host on readiness, sends a bounded manifest, and lets the remote host clone its own Firstmate home and project origins. +In the primary home, its durable registration effects are limited to that route and the charter brief under `data/`; launch records are created only when the secondmate is launched. Readiness starts with a read-only check; when that check reports a gap, it runs `--fix` and then a second read-only check whose verdict decides, so the operator never has to run the repair by hand and a repair is never trusted on its own word. A host that stays red prints the doctor's remaining gaps and their operator steps, restores the registry, and creates nothing on the remote host. It does not copy project trees or the primary process environment. @@ -207,12 +217,14 @@ No generic remote delete or write surface exists: remote writes are confined to ## Verification -The portable tests use the real entrypoint protocol, real git repositories, a deterministic SSH boundary, a stateful host-local Herdr CLI fixture, and a controlled account fixture for the readiness gate: +The portable tests use the real entrypoint protocol, real git repositories, a deterministic SSH boundary, a stateful host-local Herdr CLI fixture, and a controlled account fixture for the readiness gate. +The lifecycle test covers seeding a registered project that this machine has never cloned, asserts that the local project tree is unchanged afterwards, and carries Bitbucket, self-hosted, and scp-like origins through to the remote clone: ```sh bin/fm-test-run.sh tests/fm-on.test.sh bin/fm-test-run.sh tests/fm-remote-job.test.sh bin/fm-test-run.sh tests/fm-remote-doctor.test.sh +bin/fm-test-run.sh tests/fm-project-origin.test.sh bin/fm-test-run.sh tests/fm-remote-reply.test.sh bin/fm-test-run.sh tests/fm-remote-backlog-handoff.test.sh bin/fm-test-run.sh tests/fm-remote-secondmate-lifecycle-e2e.test.sh diff --git a/docs/scripts.md b/docs/scripts.md index 63f496d9fa7..2d2d789461d 100644 --- a/docs/scripts.md +++ b/docs/scripts.md @@ -46,6 +46,7 @@ The shared no-mistakes gate refusal for fleet lifecycle entrypoints is summarize | `fm-home-seed.sh` | Transactionally provision a local secondmate home and maintain `data/secondmates.md` | | `fm-remote-home-seed.sh` | Register and provision a whole secondmate home on an SSH-reachable host | | `fm-remote-readiness-lib.sh` | Shared remote second-mate readiness gate: check and, when needed, repair then re-check through `fm-remote-doctor.sh` | +| [`fm-project-origin-lib.sh`](../bin/fm-project-origin-lib.sh) | Accepted origin-form owner shared by both remote provisioning boundaries | | `fm-spawn.sh` | Spawn crewmates, scouts, `id=repo` batches, and secondmates on the resolved harness and runtime backend | | `fm-backend.sh` | Runtime-backend selection, meta helpers, selector resolution, and operation dispatch | | `fm-backend-hometag-lib.sh` | Shared per-installation home-tag derivation for zellij tab and cmux workspace titles | diff --git a/tests/fm-backend.test.sh b/tests/fm-backend.test.sh index f42f7f71989..ae7e9ce5465 100755 --- a/tests/fm-backend.test.sh +++ b/tests/fm-backend.test.sh @@ -128,22 +128,20 @@ resolve_permissive_tmux_kill_ref() { # --- shared: a pre-refactor bin/ shim -------------------------------------- # # build_old_bin echoes a directory whose bin/ subdir holds the PRE-REFACTOR -# fm-send.sh, fm-peek.sh, fm-watch.sh, fm-spawn.sh, fm-teardown.sh, and any -# changed source-library dependency (all extracted from BASE_REF), plus copies -# of every OTHER sibling script those five entrypoints source, so those copies are exactly -# what BASE_REF would have used too. Copies keep BASH_SOURCE-based sibling -# resolution inside the synthetic tree on both macOS and Linux; symlinks make -# that resolution shell/platform-dependent. FM_ROOT_OVERRIDE pointed at this dir's -# root makes "$FM_ROOT/bin/fm-project-mode.sh" (etc.) resolve correctly. -# fm-backend.sh (and its bin/backends/ adapters) is the dispatcher every one -# of the five REFACTORED scripts sources; it must be a real, reachable file in -# the old bin/ too or `. "$SCRIPT_DIR/fm-backend.sh"` aborts under set -eu - -# hence the dispatcher is a copied sibling, while the tmux adapter is extracted -# from BASE_REF so conformance tests retain the exact historical behavior even -# when this branch changes tmux dispatch semantics. -OLD_BIN_UNCHANGED_SIBLINGS="fm-gate-refuse-lib.sh fm-guard.sh fm-lock-lib.sh fm-tasks-axi-lib.sh fm-pr-lib.sh fm-tangle-lib.sh fm-tmux-lib.sh fm-composer-lib.sh fm-wake-lib.sh fm-classify-lib.sh fm-supervision-lib.sh fm-ff-lib.sh fm-config-inherit-lib.sh fm-project-mode.sh fm-harness.sh fm-crew-state.sh fm-nm-run-lib.sh fm-decision-hold.sh fm-backend.sh fm-operational-input.sh fm-public-followup-lib.sh fm-secondmate-registry-lib.sh fm-secondmate-parent-lib.sh fm-x-lib.sh" -# A pull-request merge may add a new main-only dependency that the branch's older baseline does not have yet. -OLD_BIN_OPTIONAL_SIBLINGS="fm-pending-reply-lib.sh" +# fm-send.sh, fm-peek.sh, fm-watch.sh, fm-spawn.sh, fm-teardown.sh, and +# fm-marker-lib.sh, all extracted from BASE_REF, laid over a whole copy of this +# checkout's bin/ tree. +# Every one of those entrypoints resolves its dependencies as +# `. "$SCRIPT_DIR/"` under set -eu, so one sibling missing from the +# synthetic tree aborts the old script during its sourcing prologue, before it +# parses a single argument. +# Copies keep BASH_SOURCE-based sibling resolution inside the synthetic tree on +# both macOS and Linux; symlinks make that resolution shell/platform-dependent. +# FM_ROOT_OVERRIDE pointed at this dir's root makes +# "$FM_ROOT/bin/fm-project-mode.sh" (etc.) resolve correctly. +# Only the refactored entrypoints and the bin/backends/tmux.sh adapter are +# extracted from BASE_REF, so conformance tests retain the exact historical +# behavior even when this branch changes tmux dispatch semantics. OLD_BIN_REFACTORED="fm-send.sh fm-peek.sh fm-watch.sh fm-spawn.sh fm-teardown.sh fm-marker-lib.sh" build_old_bin() { # -> echoes root dir (root/bin/