diff --git a/AGENTS.md b/AGENTS.md index bf22653a951..6cdd7b30d7e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -78,6 +78,8 @@ config/wedge-alarm optional away-mode wedge-alarm active-alert directives; LOCA config/watched-tools.json optional list of the tools this home depends on, read by the update check armed with bin/fm-tool-update-check.sh; LOCAL, gitignored, firstmate-maintained but human-editable, and NOT inherited by secondmate homes; see docs/configuration.md "Watched tool updates" config/x-mode.env generated Relay watcher cadence; LOCAL, gitignored; source before arming watcher when present data/ personal fleet records; LOCAL, gitignored as a whole + firstmate.identity persistent human-friendly name for this exact Firstmate home; bin/fm-identity-lib.sh owns the record + crew-identities/ persistent callsign bindings and historical non-rebinding records for this home's tasks; bin/fm-identity-lib.sh owns the records backlog.md task queue, dependencies, history captain.md this home's domain-local captain preferences and working style; LOCAL, gitignored, canonical even if harness memory mirrors it, and updated with inspect-then-update captain-shared.md main-authoritative shared captain preferences propagated read-only to secondmate homes; LOCAL, gitignored, owned by secondmate-provisioning @@ -300,10 +302,10 @@ The spawn must resolve a genuine isolated task worktree distinct from the primar After spawning, confirm the worker is processing the brief, handle any trust dialog through `harness-adapters`, and record ship or scout work as under way. 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. +Address workers by callsign in captain-facing language and steer one with short single-line messages through `fm-send`; exact task IDs remain the internal identity, and `bin/fm-identity-lib.sh` owns unambiguous names-first resolution. 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). `fm-send` is the data plane for text the worker should read; never use its key or text paths for interrupt, exit, or other lifecycle control, because routing-marked lifecycle text becomes chat the worker reasons about instead of executing. -Drive a worker's lifecycle through `bin/fm-control.sh interrupt|exit|relaunch`, which owns the per-runtime mechanics, verifies each action, and never tears down or discards anything ([`docs/agent-control.md`](docs/agent-control.md)). +Drive a worker's lifecycle through `bin/fm-control.sh interrupt|exit|relaunch`, which owns the per-runtime mechanics, verifies each action, and never tears down or discards anything ([`docs/agent-control.md`](docs/agent-control.md)). Codex ship conversation continuity is opt-in only through `exit --resumable` and `relaunch --resume --note `; ordinary lifecycle calls remain disposable, and no caller may substitute `--last`, a label, cwd recency, or a terminal UUID scan for the exact recorded session binding. 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`. diff --git a/bin/fm-bearings-snapshot.sh b/bin/fm-bearings-snapshot.sh index c64f4226dbb..de39a66a936 100755 --- a/bin/fm-bearings-snapshot.sh +++ b/bin/fm-bearings-snapshot.sh @@ -111,10 +111,10 @@ usage: fm-bearings-snapshot.sh [--json] [--include-prs] [--fields ] Compact bearings projection over fm-fleet-snapshot.sh. TOON by default. Default is LOCAL-ONLY (no network); --include-prs is the only path that fetches. -Default fields: schema, home, generated, prs, in_flight{id,kind,state,doing}, +Default fields: schema, home, generated, prs, in_flight{id,callsign,kind,state,doing}, secondmates{id,state,doing,provenance,freshness,age_seconds,contradiction,reason}, - decisions_open{id,key,verb,summary,owner}, landed{id,what,artifact,owner}, - gates{id,title,blocked_by,reason,owner}, reports{id,path}, recorded_prs{id,url}, + decisions_open{id,key,verb,summary,owner}, landed{id,callsign,what,artifact,owner}, + gates{id,title,blocked_by,reason,owner}, reports{id,callsign,path}, recorded_prs{id,url}, unhealthy_endpoints{...} (only when non-empty), omitted{surface,reveal}. landed merges this home's Done with registered secondmate homes' Done, bounded by a per-home cap (FM_BEARINGS_LANDED_PER_HOME) and an overall cap (FM_BEARINGS_LANDED), @@ -319,13 +319,15 @@ MODEL=$(printf '%s' "$SNAP" | jq \ | $groups[] | select(length > $i) | .[$i]][:$n]; + (.identities // []) as $identities + | def callsign_for($id): ([ $identities[] | select(.id == $id) | .callsign ][0] // $id); ($fields | split(",") | map(gsub("^\\s+|\\s+$"; "")) | map(select(. != ""))) as $fl | (($fl | index("bodies")) != null) as $f_bodies | (($fl | index("paths")) != null) as $f_paths | (($fl | index("actions")) != null) as $f_actions | (($fl | index("endpoints")) != null) as $f_endpoints | ([ .backlog.records[] | select(.state == "done" and .structured and .hold_kind != "captain") - | {id, title, pr_url, report_path, local_note, completion, home:"(main)", home_id:"(main)"} ]) as $main_done + | {id, callsign:callsign_for(.id), title, pr_url, report_path, local_note, completion, home:"(main)", home_id:"(main)"} ]) as $main_done | ((.secondmate_landed.records) // []) as $mate_done | ($main_done + $mate_done) as $all_landed_rows | ([ $all_landed_rows | group_by(.home_id)[] @@ -383,7 +385,7 @@ MODEL=$(printf '%s' "$SNAP" | jq \ | select(.kind != "secondmate") | select(.backlog.current_role != "program") | select(.backlog.current_role != "held" or .current_state.state == "working") - | {id, kind, + | {id, callsign:(.callsign // callsign_for(.id)), kind, state: .current_state.state, doing: ((.current_state.detail // "") as $d | (if $d != "" then $d else (.hints.last_event_text // "") end) | trunc(90)) @@ -441,7 +443,7 @@ MODEL=$(printf '%s' "$SNAP" | jq \ | ([ .scout_reports[] | . as $r | select(($all_reports == 1) or (($rel_ids | index($r.id)) != null)) - | {id, path} ]) as $reports_all + | {id, callsign:callsign_for(.id), path} ]) as $reports_all | ([ .tasks[] | select(.kind != "secondmate" and .pr.url != null and .pr.source == "meta") | {id, url:.pr.url} ]) as $recorded_prs_all | . as $snap | { @@ -452,7 +454,7 @@ MODEL=$(printf '%s' "$SNAP" | jq \ in_flight: (if $all_in_flight == 1 then $in_flight_all else $in_flight_all[:$in_flight_n] end), secondmates: (if $all_secondmates == 1 then $secondmates_all else $secondmates_all[:$secondmates_n] end), decisions_open: (if $all_decisions == 1 then $decisions_all else $decisions_all[:$decisions_n] end), - landed: ($done | map({id, what:(.title | trunc(70)), + landed: ($done | map({id, callsign:(.callsign // callsign_for(.id)), what:(.title | trunc(70)), artifact:(.pr_url // .report_path // .local_note // "-"),owner:.home_id})), gates: (if $all_queued == 1 then $gates_all else $gates_all[:$gates_n] end), reports: (if $all_reports == 1 then $reports_all else $reports_all[:$reports_n] end), diff --git a/bin/fm-control.sh b/bin/fm-control.sh index 7121a02e9ba..a21c45df25b 100755 --- a/bin/fm-control.sh +++ b/bin/fm-control.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # fm-control.sh - the CONTROL PLANE for a firstmate-owned agent: allowlisted -# lifecycle verbs addressed to an exact task id. +# lifecycle verbs addressed to an exact task id or persistent callsign. # # Usage: fm-control.sh interrupt # fm-control.sh exit [--resumable] @@ -65,12 +65,10 @@ # exit/relaunch, fresh spawn, scouts, secondmates, and every other harness keep # the disposable brief-plus-note behavior above. # -# Targeting is EXACT: only a bare task id with a state/.meta record in -# THIS home is accepted, and the record must pass the shared endpoint-identity -# validation (bin/fm-backend.sh's fm_backend_validate_task_endpoint). A legacy -# fm- label, an explicit session:window endpoint, and a bare window name -# are all refused - a lifecycle command delivered to the wrong endpoint is far -# worse than a loud refusal. +# Targeting is EXACT: a persistent callsign resolves through the home-owned +# identity registry to exactly one task id before endpoint validation. A bare +# task id remains supported. Missing, ambiguous, archived-only, conflicting, +# explicit session:window, and bare window targets are refused. # # A remotely placed secondmate is refused by name: its agent runs on another # host, so no postcondition this plane verifies could be read for it here. @@ -131,6 +129,8 @@ DATA="${FM_DATA_OVERRIDE:-$FM_HOME/data}" # shellcheck source=bin/fm-backend.sh . "$SCRIPT_DIR/fm-backend.sh" +# shellcheck source=bin/fm-identity-lib.sh +. "$SCRIPT_DIR/fm-identity-lib.sh" # shellcheck source=bin/fm-busy-lib.sh . "$SCRIPT_DIR/fm-busy-lib.sh" # shellcheck source=bin/fm-control-lib.sh @@ -179,10 +179,21 @@ VERB=${2:-} [ -n "$RAW_ID" ] && [ -n "$VERB" ] || { usage >&2; exit 2; } shift 2 +case "$RAW_ID" in + *:*) die "'$RAW_ID' is an explicit backend endpoint; fm-control accepts a callsign or exact task id only, so a lifecycle command can never land on an endpoint this home does not own" ;; + fm-*) + if [ -f "$STATE/${RAW_ID#fm-}.meta" ]; then + die "'$RAW_ID' is a legacy window label, not a callsign or exact task id; pass the exact task id '${RAW_ID#fm-}' or that task's callsign" + fi + ;; +esac +ID=$(fm_identity_resolve_selector "$STATE" "$RAW_ID") || exit 1 +CALLSIGN=$(fm_identity_display_callsign "$ID") + if ! fm_control_verb_allowed "$VERB"; then { if [ "$VERB" = resume ]; then - echo "error: 'resume' is not a control verb: resuming an exited agent is not deterministic across the verified adapters (codex and grok need a session id printed at exit, opencode continues the most recent session for the cwd, and claude, pi, pi-signed, and kimi have no verified pane-resume contract). Use 'relaunch', which carries the brief plus a progress note into a fresh agent on any adapter." + echo "error: resume resolved $CALLSIGN ($ID), but exact-thread resume is not installed for this task. Use 'relaunch' for a fresh replacement, or the resumable-crewmate command when that opt-in capability owns the recorded harness session." else echo "error: '$VERB' is not a control verb" fi @@ -262,15 +273,16 @@ case "$NEW_EFFORT" in *) die "--effort must be one of low, medium, high, xhigh, max" ;; esac -# --- exact task-id resolution ---------------------------------------------- +# --- exact task identity resolution ---------------------------------------- -case "$RAW_ID" in - *:*) die "'$RAW_ID' is an explicit backend endpoint; fm-control accepts an exact task id only, so a lifecycle command can never land on an endpoint this home does not own" ;; -esac -if ! fm_task_id_creation_valid "$RAW_ID"; then - die "'$RAW_ID' is not a valid task id" +if ! fm_task_id_creation_valid "$ID"; then + die "resolved task id '$ID' is invalid" +fi +if [ ! -f "$(fm_identity_task_record "$ID")" ]; then + fm_identity_ensure_task_from_meta "$STATE/$ID.meta" "$ID" 1 >/dev/null \ + || die "legacy task $ID could not receive a persistent callsign" + CALLSIGN=$(fm_identity_display_callsign "$ID") fi -ID=$RAW_ID CONTROL_LOCK="$STATE/.control-$ID.lock" trap control_cleanup EXIT fm_lock_try_acquire "$CONTROL_LOCK" \ @@ -278,14 +290,7 @@ fm_lock_try_acquire "$CONTROL_LOCK" \ CONTROL_LOCK_HELD=1 META="$STATE/$ID.meta" if [ ! -f "$META" ]; then - case "$RAW_ID" in - fm-*) - if [ -f "$STATE/${RAW_ID#fm-}.meta" ]; then - die "'$RAW_ID' is a window label, not a task id; pass the exact task id '${RAW_ID#fm-}'" - fi - ;; - esac - die "no task '$ID' in $STATE (fm-control resolves an exact task id only)" + die "no active task for $CALLSIGN ($ID) in $STATE" fi # A remotely placed secondmate records its endpoint on ANOTHER host, so every @@ -1056,9 +1061,9 @@ do_relaunch() { RELAUNCH_ACTIVE=0 rm -f "$RELAUNCH_RESUME_ATTEMPT" if [ "$RESUME_RELAUNCH" = 1 ]; then - echo "resumed $ID session=$RELAUNCH_RESUME_SESSION harness=codex model=$TARGET_MODEL effort=$TARGET_EFFORT backend=$BACKEND endpoint=$T worktree=$WT" + echo "resumed $CALLSIGN ($ID) session=$RELAUNCH_RESUME_SESSION harness=codex model=$TARGET_MODEL effort=$TARGET_EFFORT backend=$BACKEND endpoint=$T worktree=$WT" else - echo "relaunched $ID harness=$TARGET_HARNESS from=$PRIOR_RECORDED_HARNESS model=$TARGET_MODEL effort=$TARGET_EFFORT backend=$BACKEND endpoint=$T worktree=$WT" + echo "relaunched $CALLSIGN ($ID) harness=$TARGET_HARNESS from=$PRIOR_RECORDED_HARNESS model=$TARGET_MODEL effort=$TARGET_EFFORT backend=$BACKEND endpoint=$T worktree=$WT" fi } @@ -1079,7 +1084,7 @@ case "$VERB" in *) die "task $ID's endpoint reads '$state' rather than a positively classified state; refusing to send a lifecycle key into an unattributed endpoint" ;; esac proof=$(do_interrupt) - echo "interrupt-delivered $ID harness=$HARNESS backend=$BACKEND verified=$proof" + echo "interrupt-delivered $CALLSIGN ($ID) harness=$HARNESS backend=$BACKEND verified=$proof" ;; exit) if [ "$RESUMABLE_EXIT" = 1 ]; then @@ -1091,7 +1096,7 @@ case "$VERB" in || die "task $ID stopped, but its prior Codex session binding could not be retired safely" fi fi - echo "$result $ID harness=$HARNESS backend=$BACKEND endpoint=$T worktree=$WT" + echo "$result $CALLSIGN ($ID) harness=$HARNESS backend=$BACKEND endpoint=$T worktree=$WT" ;; relaunch) do_relaunch diff --git a/bin/fm-crew-state.sh b/bin/fm-crew-state.sh index df627b487f2..8e60e70e5f7 100755 --- a/bin/fm-crew-state.sh +++ b/bin/fm-crew-state.sh @@ -16,7 +16,7 @@ # fixed mapping logic, no heuristics and no LLM. Output is one stable, parseable, # token-tight line firstmate can read every heartbeat: # -# state: · source: · +# state: · source: · · identity: () # # Logic, in order: # 1. Resolve worktree + backend target + kind from state/.meta. A meta @@ -50,7 +50,8 @@ # recorded backend's pane busy state, then the status log's last line only # when its verb maps to a recognized run-state. Decision-only events such as # `resolved` never become current state or detail. -# 5. Missing meta or torn-down worktree: report unknown · none. If no run is +# 5. A missing selector refuses before state inspection. A torn-down worktree +# with a still-present task record reports unknown · none. If no run is # attributed to this crew, a dead endpoint also reports unknown · none rather # than trusting a stale status log. # @@ -67,6 +68,8 @@ STATE="${FM_STATE_OVERRIDE:-$FM_HOME/state}" . "$SCRIPT_DIR/fm-tmux-lib.sh" # shellcheck source=bin/fm-backend.sh . "$SCRIPT_DIR/fm-backend.sh" +# shellcheck source=bin/fm-identity-lib.sh +. "$SCRIPT_DIR/fm-identity-lib.sh" # shellcheck source=bin/fm-classify-lib.sh . "$SCRIPT_DIR/fm-classify-lib.sh" # shellcheck source=bin/fm-busy-lib.sh @@ -74,8 +77,14 @@ STATE="${FM_STATE_OVERRIDE:-$FM_HOME/state}" # shellcheck source=bin/fm-nm-run-lib.sh . "$SCRIPT_DIR/fm-nm-run-lib.sh" -ID=${1:-} -[ -n "$ID" ] || { echo "usage: fm-crew-state.sh " >&2; exit 2; } +RAW_SELECTOR=${1:-} +[ -n "$RAW_SELECTOR" ] || { echo "usage: fm-crew-state.sh " >&2; exit 2; } +set +e +ID=$(fm_identity_resolve_selector "$STATE" "$RAW_SELECTOR") +IDENTITY_RC=$? +set -u +[ "$IDENTITY_RC" -eq 0 ] || exit 1 +CALLSIGN=$(fm_identity_display_callsign "$ID") META="$STATE/$ID.meta" LOG="$STATE/$ID.status" @@ -93,6 +102,7 @@ SEP=' · ' emit() { # [detail] local line="state: $1${SEP}source: $2" [ -n "${3:-}" ] && line="$line${SEP}$3" + line="$line${SEP}identity: $CALLSIGN ($ID)" printf '%s\n' "$line" exit 0 } diff --git a/bin/fm-fleet-snapshot.sh b/bin/fm-fleet-snapshot.sh index c257d110be5..88201987eaf 100755 --- a/bin/fm-fleet-snapshot.sh +++ b/bin/fm-fleet-snapshot.sh @@ -42,6 +42,9 @@ # endpoint.exists is the cheap backend endpoint-presence read. # endpoint.agent_alive is populated for secondmates only, where it is useful # return-channel supervision data; other tasks use "not_checked". +# identities[]: one read-only id/callsign/status projection for every structured +# backlog, live-task, or report id. Persisted records win; legacy unnamed ids +# receive the same deterministic migration-compatible display fallback. # scout_reports[]: present data//report.md pointers. # main_inventory: {valid,reason,orphan_in_flight[],unstructured_current_count} - # main-home current-inventory checks shared with secondmate_home_summary_json @@ -146,6 +149,9 @@ validate_positive_bound FM_SNAPSHOT_REGISTRY_TIMEOUT "$FM_SNAPSHOT_REGISTRY_TIME # shellcheck source=bin/fm-backend.sh # shellcheck disable=SC1091 . "$SCRIPT_DIR/fm-backend.sh" +# shellcheck source=bin/fm-identity-lib.sh +# shellcheck disable=SC1091 +. "$SCRIPT_DIR/fm-identity-lib.sh" # shellcheck source=bin/fm-classify-lib.sh # shellcheck disable=SC1091 . "$SCRIPT_DIR/fm-classify-lib.sh" @@ -238,7 +244,11 @@ crew_state_json() { # state=${rest%%"$sep"source: *} rest=${rest#*"$sep"source: } case "$rest" in - *"$sep"*) source=${rest%%"$sep"*}; detail=${rest#*"$sep"} ;; + *"$sep"*) + source=${rest%%"$sep"*} + detail=${rest#*"$sep"} + case "$detail" in *"$sep"identity:\ *) detail=${detail%"$sep"identity:*} ;; esac + ;; *) source=$rest ;; esac ;; @@ -425,7 +435,7 @@ backlog_json() { # [] - defaults to this home's $BACKLOG } task_json_lines() { - local meta id kind harness mode yolo project worktree home projects backend target status_log report_path + local meta id callsign kind harness mode yolo project worktree home projects backend target status_log report_path local remote_host remote_root remote_state remote_rc remote_home_present local pr pr_source event_json current_json endpoint_exists agent_alive meta_json status_json report_json worktree_json home_json local last_event_raw current_state current_source pending_decision blocked_event report_present=0 pr_from_status @@ -434,6 +444,7 @@ task_json_lines() { for meta in "$STATE"/*.meta; do [ -e "$meta" ] || continue id=$(basename "$meta" .meta) + callsign=$(fm_identity_display_callsign "$id") kind=$(meta_value "$meta" kind) [ -n "$kind" ] || kind=ship harness=$(meta_value "$meta" harness) @@ -554,6 +565,7 @@ task_json_lines() { jq -n \ --arg id "$id" \ + --arg callsign "$callsign" \ --arg kind "$kind" \ --arg harness "$harness" \ --arg mode "$mode" \ @@ -584,6 +596,7 @@ task_json_lines() { --argjson report_present "$(bool_json "$report_present")" \ '{ id:$id, + callsign:$callsign, kind:$kind, harness:($harness // ""), mode:($mode // ""), @@ -615,12 +628,12 @@ task_json_lines() { }, actions:( if $kind == "secondmate" then - {send:"bin/fm-send.sh fm-\($id) \u0027\u0027", + {send:"bin/fm-send.sh \($callsign) \u0027\u0027", watch:"read status/doc return channel; do not routinely fm-peek a secondmate for answers", return_channel_note:"Secondmate answers come back through status/doc paths after a marked fm-send request."} else - {watch:"bin/fm-peek.sh fm-\($id)", - steer:"bin/fm-send.sh fm-\($id) \u0027\u0027", + {watch:"bin/fm-peek.sh \($callsign)", + steer:"bin/fm-send.sh \($callsign) \u0027\u0027", return_channel_note:null} end) }' @@ -728,11 +741,11 @@ secondmate_home_summary_json() { # | select($work.current_role != "program") | $tasks[] | select(.id == $work.id and .current_state.state == "working") - | {id,kind,state:.current_state.state,source:.current_state.source, + | {id,callsign,kind,state:.current_state.state,source:.current_state.source, doing:((.current_state.detail // "") | trunc(120))} ]) as $active_all | ($captain_holds_all + ([ $tasks[] as $t | ($t.hints.open_decisions // [])[] - | {id:$t.id,key,verb,summary:(.summary | trunc(160)),reason:null,source:"status"} ])) as $decisions_all + | {id:$t.id,callsign:$t.callsign,key,verb,summary:(.summary | trunc(160)),reason:null,source:"status"} ])) as $decisions_all | ([ $queued_all[] | select((.unresolved_blocker_ids | length) > 0 or (.hold_reason != null and .hold_kind != null)) | {id:(.id | trunc(120)),title:(.title | trunc(90)), @@ -789,7 +802,7 @@ secondmate_home_summary_json() { # repo:((.repo // null) | if . == null then null else trunc(120) end), kind:((.kind // null) | if . == null then null else trunc(40) end)}][:$queued_n]), landed:(if $landed_n == 0 then $landed_all else $landed_all[:$landed_n] end), - endpoints:([$tasks[] | {id,state:.current_state.state,source:.current_state.source, + endpoints:([$tasks[] | {id,callsign,state:.current_state.state,source:.current_state.source, endpoint:(.endpoint + {target:((.endpoint.target // null) | if . == null then null else trunc(240) end)})}][:$child_n]), counts:{ active_children:($active_all | length), @@ -1373,6 +1386,24 @@ scout_report_lines() { | jq -s 'sort_by(.id)' } +identity_projection_json() { # + local id record callsign status + jq -nr --argjson backlog "$1" --argjson tasks "$2" --argjson reports "$3" ' + ([ $backlog.records[]? | select(.structured == true) | .id ] + + [ $tasks[]?.id ] + [ $reports[]?.id ]) | unique[]' \ + | while IFS= read -r id; do + fm_identity_task_id_valid "$id" || continue + record=$(fm_identity_task_record "$id") + callsign=$(fm_identity_display_callsign "$id") + status=legacy + if fm_identity_record_core_valid "$record" "$id" 2>/dev/null; then + status=$(fm_identity_record_value "$record" status) + fi + jq -n --arg id "$id" --arg callsign "$callsign" --arg status "$status" \ + '{id:$id,callsign:$callsign,status:$status}' + done | jq -s 'sort_by(.id)' +} + BACKLOG_JSON=$(backlog_json) || { echo "fm-fleet-snapshot: backlog read failed" >&2; exit 1; } TASKS_JSON=$(task_json_lines) || { echo "fm-fleet-snapshot: task snapshot failed" >&2; exit 1; } @@ -1383,16 +1414,30 @@ if [ "$OUTPUT_MODE" = secondmate-home-summary ]; then fi SCOUT_REPORTS_JSON=$(scout_report_lines) +IDENTITIES_JSON=$(identity_projection_json "$BACKLOG_JSON" "$TASKS_JSON" "$SCOUT_REPORTS_JSON") \ + || { echo "fm-fleet-snapshot: identity projection failed" >&2; exit 1; } MAIN_INVENTORY_JSON=$(main_inventory_json "$BACKLOG_JSON" "$TASKS_JSON") \ || { echo "fm-fleet-snapshot: main inventory summary failed" >&2; exit 1; } SECONDMATE_CURRENT_JSON=$(secondmate_current_json "$TASKS_JSON") \ || { echo "fm-fleet-snapshot: registered secondmate aggregation failed" >&2; exit 1; } SECONDMATE_LANDED_JSON=$(secondmate_landed_from_current_json "$SECONDMATE_CURRENT_JSON") \ || { echo "fm-fleet-snapshot: secondmate landed projection failed" >&2; exit 1; } +FIRSTMATE_NAME_SOURCE=deterministic-fallback +FIRSTMATE_NAME=$(fm_identity_choose_home_name) +if [ -f "$FM_IDENTITY_HOME_RECORD" ] && [ ! -L "$FM_IDENTITY_HOME_RECORD" ] \ + && [ "$(fm_identity_record_value "$FM_IDENTITY_HOME_RECORD" home 2>/dev/null || true)" = "$(fm_identity_home_path)" ]; then + persisted_name=$(fm_identity_record_value "$FM_IDENTITY_HOME_RECORD" name 2>/dev/null || true) + if fm_identity_validate_name "$persisted_name" >/dev/null 2>&1; then + FIRSTMATE_NAME=$persisted_name + FIRSTMATE_NAME_SOURCE=persisted + fi +fi jq -n \ --arg generated "$SNAPSHOT_NOW" \ --arg fm_home "$FM_HOME" \ + --arg firstmate_name "$FIRSTMATE_NAME" \ + --arg firstmate_name_source "$FIRSTMATE_NAME_SOURCE" \ --arg fm_root "$FM_ROOT" \ --arg state "$STATE" \ --arg data "$DATA" \ @@ -1400,6 +1445,7 @@ jq -n \ --arg projects "$PROJECTS" \ --argjson backlog "$BACKLOG_JSON" \ --argjson tasks "$TASKS_JSON" \ + --argjson identities "$IDENTITIES_JSON" \ --argjson main_inventory "$MAIN_INVENTORY_JSON" \ --argjson scout_reports "$SCOUT_REPORTS_JSON" \ --argjson secondmate_current "$SECONDMATE_CURRENT_JSON" \ @@ -1411,8 +1457,10 @@ jq -n \ schema:"fm-fleet-snapshot.v1", generated:$generated, fm_home:$fm_home, + firstmate:{name:$firstmate_name,source:$firstmate_name_source}, roots:{fm_root:$fm_root,state:$state,data:$data,config:$config,projects:$projects}, backlog:$backlog, + identities:$identities, tasks:($tasks | map(. + {backlog:backlog_by_id(.id)})), main_inventory:$main_inventory, scout_reports:($scout_reports | map(. + {kind:report_kind(.id)})), diff --git a/bin/fm-fleet-view.sh b/bin/fm-fleet-view.sh index 909c792b294..18784ff398b 100755 --- a/bin/fm-fleet-view.sh +++ b/bin/fm-fleet-view.sh @@ -51,7 +51,7 @@ printf '%s\n' "$SNAPSHOT" | jq -r ' if $t.kind == "secondmate" then "\($t.actions.send) - \($t.actions.watch)" else $t.actions.watch end; def task_row($t): - "| \($t.id) | \($t.current_state.state) / \($t.current_state.source) | \($t.kind) | \(dash($t.backlog.repo // $t.project)) | \($t.backend) | \(endpoint_of($t)) | \(artifact($t)) | \(path_of($t)) | \(action_of($t)) |"; + "| \($t.callsign) (\($t.id)) | \($t.current_state.state) / \($t.current_state.source) | \($t.kind) | \(dash($t.backlog.repo // $t.project)) | \($t.backend) | \(endpoint_of($t)) | \(artifact($t)) | \(path_of($t)) | \(action_of($t)) |"; def blocker($r): if ($r.blocked_by // "") == "" then "-" elif ($r.blocked_reason // "") == "" then $r.blocked_by @@ -62,13 +62,14 @@ printf '%s\n' "$SNAPSHOT" | jq -r ' "# Fleet View", "", "Schema: \(.schema)", + "Firstmate: \(.firstmate.name)", "Home: \(.fm_home)", "", "## Under Way", (if (.tasks | length) == 0 then "No live task metadata found." else - "| ID | Current | Kind | Repo/Project | Backend | Endpoint | Artifact | Path | Watch / return channel |", + "| Callsign (task ID) | Current | Kind | Repo/Project | Backend | Endpoint | Artifact | Path | Watch / return channel |", "| --- | --- | --- | --- | --- | --- | --- | --- | --- |", (.tasks[] | task_row(.)) end), diff --git a/bin/fm-identity-lib.sh b/bin/fm-identity-lib.sh new file mode 100755 index 00000000000..88aca5c4105 --- /dev/null +++ b/bin/fm-identity-lib.sh @@ -0,0 +1,967 @@ +#!/usr/bin/env bash +# Shared persistent human identity for one Firstmate home and its tasks. +# +# data/firstmate.identity owns the home's human-friendly name. +# data/crew-identities/.identity owns a task's callsign binding and is +# retained after teardown as the historical non-rebinding tombstone. +# Task ids remain the internal identity. Callsigns are case-insensitive selectors +# within exactly one canonical FM_HOME and never replace backend endpoint checks. +# +# A fresh spawn reserves its callsign before creating an endpoint, then publishes +# the exact worktree/backend/endpoint binding before launching the agent. A retry +# of the same interrupted provisioning reuses that reservation. An archived task +# id is never silently reused for a fresh task. +# +# Records are line-oriented key=value files. Values must contain no control +# characters. Repeated retired_callsign= lines preserve every prior task name so +# none can be assigned again. Known harness conversation metadata is copied as +# harness_session_id= when available; endpoint_session_id= separately records the +# tmux or Herdr container session. Unknown future meta fields remain untouched. + +FM_IDENTITY_LIB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +FM_IDENTITY_DEFAULT_ROOT="$(cd "$FM_IDENTITY_LIB_DIR/.." && pwd)" +FM_ROOT="${FM_ROOT_OVERRIDE:-${FM_ROOT:-$FM_IDENTITY_DEFAULT_ROOT}}" +FM_HOME="${FM_HOME:-${FM_ROOT_OVERRIDE:-$FM_ROOT}}" +FM_IDENTITY_STATE="${FM_STATE_OVERRIDE:-${STATE:-$FM_HOME/state}}" +FM_IDENTITY_HOME="${FM_IDENTITY_HOME_OVERRIDE:-$FM_HOME}" +if [ -n "${FM_STATE_OVERRIDE:-}" ] && [ -z "${FM_IDENTITY_HOME_OVERRIDE:-}" ] \ + && [ "${FM_STATE_OVERRIDE##*/}" = state ]; then + # Test/recovery callers routinely redirect only state/. Treat its parent as + # the logical home for identity too, so an isolated lifecycle probe cannot + # leak durable callsigns into the code checkout's private data directory. + FM_IDENTITY_HOME=${FM_STATE_OVERRIDE%/state} +fi +if [ -n "${FM_DATA_OVERRIDE:-}" ]; then + FM_IDENTITY_DATA=$FM_DATA_OVERRIDE +elif [ -n "${FM_STATE_OVERRIDE:-}" ] && [ "${FM_STATE_OVERRIDE##*/}" = state ]; then + FM_IDENTITY_DATA=${FM_STATE_OVERRIDE%/state}/data +else + FM_IDENTITY_DATA=${DATA:-$FM_IDENTITY_HOME/data} +fi +FM_IDENTITY_DIR="$FM_IDENTITY_DATA/crew-identities" +FM_IDENTITY_HOME_RECORD="$FM_IDENTITY_DATA/firstmate.identity" +FM_IDENTITY_LOCK="$FM_IDENTITY_DATA/.identity.lock" + +FM_IDENTITY_CALLSIGN_POOL="Ada Bell Burnell Carson Curie Darwin Edison Euler Faraday Franklin Galileo Hamilton Hedy Hopper Joule Kepler Lamarr Lovelace Maxwell Mendeleev Newton Noether Pascal Raman Sagan Tesla Turing Verne Watt Wilkins" +FM_IDENTITY_HOME_POOL="Aurora Beagle Calypso Discovery Endeavour Horizon Intrepid Nautilus Odyssey Polaris Resolute Venture Voyager" + +fm_identity_error() { + printf 'error: %s\n' "$*" >&2 +} + +fm_identity_now() { + printf '%s\n' "${FM_IDENTITY_NOW:-$(date -u +%Y-%m-%dT%H:%M:%SZ)}" +} + +fm_identity_canonical_dir() { # + (cd "$1" 2>/dev/null && pwd -P) +} + +fm_identity_home_path() { + fm_identity_canonical_dir "$FM_IDENTITY_HOME" +} + +fm_identity_fold() { + local value=$1 folded= char i LC_ALL=C + for ((i = 0; i < ${#value}; i++)); do + char=${value:i:1} + case "$char" in + A) char=a ;; B) char=b ;; C) char=c ;; D) char=d ;; E) char=e ;; + F) char=f ;; G) char=g ;; H) char=h ;; I) char=i ;; J) char=j ;; + K) char=k ;; L) char=l ;; M) char=m ;; N) char=n ;; O) char=o ;; + P) char=p ;; Q) char=q ;; R) char=r ;; S) char=s ;; T) char=t ;; + U) char=u ;; V) char=v ;; W) char=w ;; X) char=x ;; Y) char=y ;; + Z) char=z ;; + esac + folded=$folded$char + done + printf '%s' "$folded" +} + +fm_identity_value_safe() { + case "$1" in + *$'\n'*|*$'\r'*|*$'\t'*|'') return 1 ;; + esac +} + +fm_identity_name_valid() { # + local name=${1:-} + [ "${#name}" -ge 2 ] && [ "${#name}" -le 32 ] || return 1 + case "$name" in + [A-Za-z]* ) ;; + *) return 1 ;; + esac + case "$name" in *[!A-Za-z0-9-]*|*-|*--) return 1 ;; esac +} + +fm_identity_task_id_valid() { # + local id=${1:-} LC_ALL=C + [ "${#id}" -le 64 ] || return 1 + case "$id" in ''|.*|*[!A-Za-z0-9._-]*) return 1 ;; esac +} + +fm_identity_name_reserved() { # + local folded + folded=$(fm_identity_fold "$1") + case "$folded" in + captain|firstmate|first-mate|mate|crew|crewmate|secondmate|second-mate|scout|ship|default|unknown|unnamed|archived|active|provisioning|fm-*) return 0 ;; + esac + return 1 +} + +fm_identity_validate_name() { # + fm_identity_name_valid "$1" || { + fm_identity_error "callsign '$1' must be 2-32 characters, start with a letter, and contain only letters, digits, or single hyphens" + return 1 + } + fm_identity_name_reserved "$1" && { + fm_identity_error "callsign '$1' is reserved" + return 1 + } + return 0 +} + +fm_identity_record_value() { # + local record=$1 key=$2 count=0 value= line + [ -f "$record" ] && [ ! -L "$record" ] || return 1 + while IFS= read -r line || [ -n "$line" ]; do + case "$line" in + "$key="*) count=$((count + 1)); value=${line#*=} ;; + esac + done < "$record" + [ "$count" -eq 1 ] || return 1 + fm_identity_value_safe "$value" || return 1 + printf '%s' "$value" +} + +fm_identity_task_record() { # + fm_identity_task_id_valid "$1" || return 1 + printf '%s/%s.identity' "$FM_IDENTITY_DIR" "$1" +} + +fm_identity_source_lock_helpers() { + declare -F fm_lock_acquire_wait >/dev/null 2>&1 && return 0 + # shellcheck source=bin/fm-wake-lib.sh + . "$FM_IDENTITY_LIB_DIR/fm-wake-lib.sh" +} + +fm_identity_prepare_dirs() { + mkdir -p "$FM_IDENTITY_DATA" || return 1 + if [ -e "$FM_IDENTITY_DIR" ] || [ -L "$FM_IDENTITY_DIR" ]; then + [ -d "$FM_IDENTITY_DIR" ] && [ ! -L "$FM_IDENTITY_DIR" ] || { + fm_identity_error "identity registry '$FM_IDENTITY_DIR' is not a real directory" + return 1 + } + else + mkdir "$FM_IDENTITY_DIR" || return 1 + fi + chmod 700 "$FM_IDENTITY_DIR" || return 1 +} + +fm_identity_lock_acquire() { + fm_identity_prepare_dirs || return 1 + fm_identity_source_lock_helpers || return 1 + fm_lock_acquire_wait "$FM_IDENTITY_LOCK" +} + +fm_identity_lock_release() { + fm_lock_release "$FM_IDENTITY_LOCK" +} + +fm_identity_checksum() { + local value=$1 i code sum=5381 LC_ALL=C + for ((i = 0; i < ${#value}; i++)); do + printf -v code '%d' "'${value:i:1}" + sum=$(((sum * 33 + code) % 2147483647)) + done + printf '%s' "$sum" +} + +fm_identity_pool_at() { # + local pool=$1 wanted=$2 item i=0 + for item in $pool; do + [ "$i" -eq "$wanted" ] && { printf '%s' "$item"; return 0; } + i=$((i + 1)) + done + return 1 +} + +fm_identity_pool_size() { # + local pool=$1 item n=0 + for item in $pool; do n=$((n + 1)); done + printf '%s' "$n" +} + +fm_identity_all_names() { + local record + if [ -f "$FM_IDENTITY_HOME_RECORD" ] && [ ! -L "$FM_IDENTITY_HOME_RECORD" ]; then + sed -n -e 's/^name=//p' -e 's/^previous_name=//p' "$FM_IDENTITY_HOME_RECORD" + fi + for record in "$FM_IDENTITY_DIR"/*.identity; do + [ -f "$record" ] && [ ! -L "$record" ] || continue + sed -n -e 's/^callsign=//p' -e 's/^retired_callsign=//p' "$record" + done +} + +fm_identity_human_name_matches_any() { # [record-to-ignore] + local wanted ignore=${2:-} record value line + wanted=$(fm_identity_fold "$1") + if [ "$FM_IDENTITY_HOME_RECORD" != "$ignore" ] && [ -f "$FM_IDENTITY_HOME_RECORD" ]; then + while IFS= read -r line || [ -n "$line" ]; do + case "$line" in name=*|previous_name=*) value=${line#*=} ;; *) continue ;; esac + [ "$(fm_identity_fold "$value")" = "$wanted" ] && return 0 + done < "$FM_IDENTITY_HOME_RECORD" + fi + for record in "$FM_IDENTITY_DIR"/*.identity; do + [ -f "$record" ] && [ ! -L "$record" ] || continue + [ "$record" = "$ignore" ] && continue + while IFS= read -r line || [ -n "$line" ]; do + case "$line" in callsign=*|retired_callsign=*) value=${line#*=} ;; *) continue ;; esac + [ "$(fm_identity_fold "$value")" = "$wanted" ] && return 0 + done < "$record" + done + return 1 +} + +fm_identity_name_matches_any() { # [record-to-ignore] + local wanted ignore=${2:-} id_path id + wanted=$(fm_identity_fold "$1") + fm_identity_human_name_matches_any "$1" "$ignore" && return 0 + for id_path in "$FM_IDENTITY_DIR"/*.identity "$FM_IDENTITY_STATE"/*.meta; do + [ -e "$id_path" ] || continue + id=${id_path##*/} + id=${id%.identity} + id=${id%.meta} + [ "$(fm_identity_fold "$id")" = "$wanted" ] && return 0 + done + return 1 +} + +fm_identity_choose_home_name() { + local home checksum size index name suffix=2 + home=$(fm_identity_home_path) || return 1 + checksum=$(fm_identity_checksum "$home") || return 1 + size=$(fm_identity_pool_size "$FM_IDENTITY_HOME_POOL") + index=$((checksum % size)) + name=$(fm_identity_pool_at "$FM_IDENTITY_HOME_POOL" "$index") || return 1 + while fm_identity_name_matches_any "$name"; do + case "$name" in *-[0-9]*) name=${name%-*}-$suffix ;; *) name=$name-$suffix ;; esac + suffix=$((suffix + 1)) + done + printf '%s' "$name" +} + +fm_identity_choose_fresh_callsign() { # + local id=$1 home checksum size start offset index candidate suffix=2 + home=$(fm_identity_home_path) || return 1 + checksum=$(fm_identity_checksum "$home:$id") || return 1 + size=$(fm_identity_pool_size "$FM_IDENTITY_CALLSIGN_POOL") + start=$((checksum % size)) + offset=0 + while [ "$offset" -lt "$size" ]; do + index=$(((start + offset) % size)) + candidate=$(fm_identity_pool_at "$FM_IDENTITY_CALLSIGN_POOL" "$index") || return 1 + if [ "$(fm_identity_fold "$candidate")" != "$(fm_identity_fold "$id")" ] \ + && ! fm_identity_name_matches_any "$candidate"; then + printf '%s' "$candidate" + return 0 + fi + offset=$((offset + 1)) + done + candidate=$(fm_identity_pool_at "$FM_IDENTITY_CALLSIGN_POOL" "$start") || return 1 + while [ "$(fm_identity_fold "$candidate-$suffix")" = "$(fm_identity_fold "$id")" ] \ + || fm_identity_name_matches_any "$candidate-$suffix"; do + suffix=$((suffix + 1)) + done + printf '%s-%s' "$candidate" "$suffix" +} + +fm_identity_legacy_callsign() { # , deterministic read-only fallback + local id=$1 home checksum size base tag + home=$(fm_identity_home_path 2>/dev/null || printf '%s' "$FM_IDENTITY_HOME") + checksum=$(fm_identity_checksum "$home:$id:legacy") || return 1 + size=$(fm_identity_pool_size "$FM_IDENTITY_CALLSIGN_POOL") + base=$(fm_identity_pool_at "$FM_IDENTITY_CALLSIGN_POOL" "$((checksum % size))") || return 1 + tag=$((checksum % 100000)) + if [ "$(fm_identity_fold "$base-L$tag")" = "$(fm_identity_fold "$id")" ]; then + tag="${tag}1" + fi + printf '%s-L%s' "$base" "$tag" +} + +fm_identity_write_home_record() { # [previous-name-lines-file] + local name=$1 created=$2 previous_file=${3:-} home tmp + home=$(fm_identity_home_path) || return 1 + tmp=$(mktemp "$FM_IDENTITY_DATA/.firstmate.identity.XXXXXXXX") || return 1 + { + printf 'schema=fm-firstmate-identity.v1\n' + printf 'home=%s\n' "$home" + printf 'name=%s\n' "$name" + printf 'created_at=%s\n' "$created" + printf 'updated_at=%s\n' "$(fm_identity_now)" + [ -n "$previous_file" ] && [ -f "$previous_file" ] && cat "$previous_file" + true + } > "$tmp" || { rm -f "$tmp"; return 1; } + chmod 600 "$tmp" 2>/dev/null || { rm -f "$tmp"; return 1; } + mv -f "$tmp" "$FM_IDENTITY_HOME_RECORD" +} + +fm_identity_ensure_home_locked() { + local home name created schema recorded_home + home=$(fm_identity_home_path) || { fm_identity_error "Firstmate home '$FM_IDENTITY_HOME' is not a readable directory"; return 1; } + if [ -e "$FM_IDENTITY_HOME_RECORD" ] || [ -L "$FM_IDENTITY_HOME_RECORD" ]; then + schema=$(fm_identity_record_value "$FM_IDENTITY_HOME_RECORD" schema 2>/dev/null || true) + recorded_home=$(fm_identity_record_value "$FM_IDENTITY_HOME_RECORD" home 2>/dev/null || true) + name=$(fm_identity_record_value "$FM_IDENTITY_HOME_RECORD" name 2>/dev/null || true) + if [ "$schema" != fm-firstmate-identity.v1 ] || [ "$recorded_home" != "$home" ] \ + || ! fm_identity_validate_name "$name" >/dev/null 2>&1 \ + || fm_identity_name_matches_any "$name" "$FM_IDENTITY_HOME_RECORD"; then + fm_identity_error "Firstmate identity record '$FM_IDENTITY_HOME_RECORD' is malformed or belongs to another home; refusing to guess" + return 1 + fi + printf '%s' "$name" + return 0 + fi + name=$(fm_identity_choose_home_name) || return 1 + created=$(fm_identity_now) + fm_identity_write_home_record "$name" "$created" || return 1 + printf '%s' "$name" +} + +fm_identity_ensure_home() { + local name + fm_identity_lock_acquire || return 1 + name=$(fm_identity_ensure_home_locked) || { fm_identity_lock_release; return 1; } + fm_identity_lock_release + printf '%s' "$name" +} + +fm_identity_meta_value() { # + local meta=$1 key=$2 line value= + [ -f "$meta" ] && [ ! -L "$meta" ] || return 0 + while IFS= read -r line || [ -n "$line" ]; do + case "$line" in "$key="*) value=${line#*=} ;; esac + done < "$meta" + printf '%s' "$value" +} + +fm_identity_backend_of_meta() { + local remote + remote=$(fm_identity_meta_value "$1" remote_host) + if [ -n "$remote" ]; then + fm_identity_meta_value "$1" remote_backend + return + fi + if declare -F fm_backend_of_meta >/dev/null 2>&1; then + fm_backend_of_meta "$1" + else + local backend + backend=$(fm_identity_meta_value "$1" backend) + printf '%s' "${backend:-tmux}" + fi +} + +fm_identity_target_of_meta() { + local remote + remote=$(fm_identity_meta_value "$1" remote_host) + if [ -n "$remote" ]; then + fm_identity_meta_value "$1" remote_target + return + fi + if declare -F fm_backend_target_of_meta >/dev/null 2>&1; then + fm_backend_target_of_meta "$1" + else + local terminal window + terminal=$(fm_identity_meta_value "$1" terminal) + window=$(fm_identity_meta_value "$1" window) + printf '%s' "${terminal:-$window}" + fi +} + +fm_identity_worktree_of_meta() { + local value + value=$(fm_identity_meta_value "$1" worktree) + [ -n "$value" ] || return 1 + fm_identity_canonical_dir "$value" 2>/dev/null || printf '%s' "$value" +} + +fm_identity_endpoint_session_of_meta() { + local meta=$1 backend target remote + remote=$(fm_identity_meta_value "$meta" remote_host) + if [ -n "$remote" ]; then + fm_identity_meta_value "$meta" remote_herdr_session + return + fi + backend=$(fm_identity_backend_of_meta "$meta") + case "$backend" in + herdr) fm_identity_meta_value "$meta" herdr_session ;; + tmux) + target=$(fm_identity_target_of_meta "$meta") + case "$target" in *:*) printf '%s' "${target%%:*}" ;; esac + ;; + *) return 0 ;; + esac +} + +fm_identity_harness_session_of_meta() { + local meta=$1 key value found= + for key in harness_session_id codex_session_id codex_thread_id thread_id session_id; do + value=$(fm_identity_meta_value "$meta" "$key") + [ -n "$value" ] || continue + fm_identity_value_safe "$value" || return 1 + if [ -n "$found" ] && [ "$found" != "$value" ]; then + fm_identity_error "task metadata carries conflicting harness thread/session identifiers" + return 1 + fi + found=$value + done + printf '%s' "$found" +} + +fm_identity_validate_meta_endpoint_ownership() { # + local meta=$1 id=$2 remote binding backend target + remote=$(fm_identity_meta_value "$meta" remote_host) + if [ -n "$remote" ]; then + binding=$(fm_identity_meta_value "$meta" endpoint_task_id) + backend=$(fm_identity_meta_value "$meta" remote_backend) + target=$(fm_identity_meta_value "$meta" remote_target) + [ "$binding" = "$id" ] && [ -n "$backend" ] && [ -n "$target" ] \ + && fm_identity_value_safe "$backend" && fm_identity_value_safe "$target" + return + fi + declare -F fm_backend_validate_task_endpoint >/dev/null 2>&1 || { + fm_identity_error "shared backend endpoint validation is unavailable for task $id" + return 1 + } + fm_backend_validate_task_endpoint "$meta" "$id" >/dev/null 2>&1 +} + +fm_identity_write_task_record() { # [retired-file] + local record=$1 id=$2 callsign=$3 status=$4 meta=$5 created=$6 retired_file=${7:-} + local home worktree= backend= endpoint= endpoint_session= harness_session= spawn_gen= value tmp + fm_identity_task_id_valid "$id" && fm_identity_validate_name "$callsign" >/dev/null 2>&1 || return 1 + home=$(fm_identity_home_path) || return 1 + if [ -n "$meta" ]; then + [ -f "$meta" ] && [ ! -L "$meta" ] || return 1 + fm_identity_validate_meta_endpoint_ownership "$meta" "$id" || return 1 + worktree=$(fm_identity_worktree_of_meta "$meta") || return 1 + backend=$(fm_identity_backend_of_meta "$meta") + endpoint=$(fm_identity_target_of_meta "$meta") + endpoint_session=$(fm_identity_endpoint_session_of_meta "$meta") + harness_session=$(fm_identity_harness_session_of_meta "$meta") || return 1 + spawn_gen=$(fm_identity_meta_value "$meta" spawn_gen) + fm_identity_value_safe "$worktree" && fm_identity_value_safe "$backend" \ + && fm_identity_value_safe "$endpoint" || return 1 + for value in "$endpoint_session" "$harness_session" "$spawn_gen"; do + [ -z "$value" ] || fm_identity_value_safe "$value" || return 1 + done + fi + tmp=$(mktemp "$FM_IDENTITY_DIR/.$id.identity.XXXXXXXX") || return 1 + { + printf 'schema=fm-crew-identity.v1\n' + printf 'home=%s\n' "$home" + printf 'task_id=%s\n' "$id" + printf 'callsign=%s\n' "$callsign" + printf 'status=%s\n' "$status" + printf 'worktree=%s\n' "$worktree" + printf 'backend=%s\n' "$backend" + printf 'endpoint=%s\n' "$endpoint" + printf 'endpoint_session_id=%s\n' "$endpoint_session" + printf 'harness_session_id=%s\n' "$harness_session" + printf 'spawn_gen=%s\n' "$spawn_gen" + printf 'created_at=%s\n' "$created" + printf 'updated_at=%s\n' "$(fm_identity_now)" + [ -n "$retired_file" ] && [ -f "$retired_file" ] && cat "$retired_file" + true + } > "$tmp" || { rm -f "$tmp"; return 1; } + chmod 600 "$tmp" 2>/dev/null || { rm -f "$tmp"; return 1; } + mv -f "$tmp" "$record" +} + +fm_identity_record_core_valid() { # + local record=$1 id=$2 schema home task callsign status expected_home + expected_home=$(fm_identity_home_path) || return 1 + schema=$(fm_identity_record_value "$record" schema 2>/dev/null || true) + home=$(fm_identity_record_value "$record" home 2>/dev/null || true) + task=$(fm_identity_record_value "$record" task_id 2>/dev/null || true) + callsign=$(fm_identity_record_value "$record" callsign 2>/dev/null || true) + status=$(fm_identity_record_value "$record" status 2>/dev/null || true) + [ "$schema" = fm-crew-identity.v1 ] && [ "$home" = "$expected_home" ] \ + && [ "$task" = "$id" ] && fm_identity_validate_name "$callsign" >/dev/null 2>&1 \ + && case "$status" in provisioning|active|archived) true ;; *) false ;; esac +} + +fm_identity_reserve_fresh_task() { # + local id=$1 record callsign created status + fm_identity_task_id_valid "$id" || { fm_identity_error "task id '$id' is invalid for a persistent callsign binding"; return 1; } + record=$(fm_identity_task_record "$id") + fm_identity_lock_acquire || return 1 + # Reserve home and task identity under one critical section. This keeps a + # direct pre-session-start spawn atomic without adding a second lifecycle + # lock round trip to every ordinary spawn. + fm_identity_ensure_home_locked >/dev/null || { fm_identity_lock_release; return 1; } + if [ -e "$record" ] || [ -L "$record" ]; then + if ! fm_identity_record_core_valid "$record" "$id"; then + fm_identity_lock_release + fm_identity_error "identity record for task $id is malformed or unsafe; refusing a fresh assignment" + return 1 + fi + status=$(fm_identity_record_value "$record" status) + callsign=$(fm_identity_record_value "$record" callsign) + if [ "$status" = provisioning ] && [ ! -e "$FM_IDENTITY_STATE/$id.meta" ]; then + fm_identity_lock_release + printf '%s' "$callsign" + return 0 + fi + fm_identity_lock_release + if [ "$status" = archived ]; then + fm_identity_error "task id '$id' is historical callsign $callsign; use a new task id for a fresh crewmate" + else + fm_identity_error "task '$id' already owns callsign $callsign; refusing a second fresh assignment" + fi + return 1 + fi + if fm_identity_human_name_matches_any "$id"; then + fm_identity_lock_release + fm_identity_error "task id '$id' collides with an active or historical human name in this Firstmate home" + return 1 + fi + callsign=$(fm_identity_choose_fresh_callsign "$id") || { fm_identity_lock_release; return 1; } + created=$(fm_identity_now) + fm_identity_write_task_record "$record" "$id" "$callsign" provisioning "" "$created" \ + || { fm_identity_lock_release; return 1; } + fm_identity_lock_release + printf '%s' "$callsign" +} + +fm_identity_activate_reserved_task_from_meta() { # + local meta=$1 id=$2 record callsign status created retired line + fm_identity_task_id_valid "$id" || return 1 + record=$(fm_identity_task_record "$id") || return 1 + fm_identity_record_core_valid "$record" "$id" || { + fm_identity_error "reserved identity record for task $id is malformed or unsafe" + return 1 + } + status=$(fm_identity_record_value "$record" status) + callsign=$(fm_identity_record_value "$record" callsign) + [ "$status" = provisioning ] || { + fm_identity_error "task $id is not a fresh provisioning; refusing lock-free activation of $callsign" + return 1 + } + created=$(fm_identity_record_value "$record" created_at 2>/dev/null || fm_identity_now) + retired=$(mktemp "${TMPDIR:-/tmp}/fm-identity-retired.XXXXXXXX") || return 1 + while IFS= read -r line || [ -n "$line" ]; do + case "$line" in retired_callsign=*) printf '%s\n' "$line" ;; esac + done < "$record" > "$retired" + if ! fm_identity_write_task_record "$record" "$id" "$callsign" active "$meta" "$created" "$retired"; then + rm -f "$retired" + return 1 + fi + rm -f "$retired" + printf '%s' "$callsign" +} + +fm_identity_ensure_task_from_meta() { # [legacy|rebind] + local meta=$1 id=$2 mode=${3:-0} legacy=0 record callsign status created retired old_worktree new_worktree target + case "$mode" in 1|legacy|rebind) legacy=1 ;; esac + fm_identity_task_id_valid "$id" || { fm_identity_error "task id '$id' is invalid for a persistent callsign binding"; return 1; } + record=$(fm_identity_task_record "$id") + fm_identity_lock_acquire || return 1 + if [ -e "$record" ] || [ -L "$record" ]; then + if ! fm_identity_record_core_valid "$record" "$id"; then + fm_identity_lock_release + fm_identity_error "identity record for task $id is malformed or belongs to another home; refusing to guess" + return 1 + fi + status=$(fm_identity_record_value "$record" status) + callsign=$(fm_identity_record_value "$record" callsign) + created=$(fm_identity_record_value "$record" created_at 2>/dev/null || fm_identity_now) + if [ "$status" = archived ]; then + fm_identity_lock_release + fm_identity_error "task $id is archived as $callsign; refusing to reactivate a historical identity" + return 1 + fi + if [ "$status" = active ]; then + old_worktree=$(fm_identity_record_value "$record" worktree 2>/dev/null || true) + new_worktree=$(fm_identity_worktree_of_meta "$meta" 2>/dev/null || true) + if [ -n "$old_worktree" ] && [ "$old_worktree" != "$new_worktree" ]; then + fm_identity_lock_release + fm_identity_error "task $id's callsign $callsign is bound to worktree '$old_worktree', not '$new_worktree'; refusing to rebind it" + return 1 + fi + if [ "$mode" != rebind ]; then + if ! fm_identity_validate_active_binding "$record" "$meta" "$id"; then + fm_identity_lock_release + fm_identity_error "task $id's callsign $callsign conflicts with its recorded endpoint or session identity; only an explicit relaunch/resume continuation may update that binding" + return 1 + fi + fm_identity_lock_release + printf '%s' "$callsign" + return 0 + fi + fi + else + if fm_identity_human_name_matches_any "$id"; then + fm_identity_lock_release + fm_identity_error "task id '$id' collides with an active or historical human name in this Firstmate home" + return 1 + fi + if [ "$legacy" = 1 ]; then + callsign=$(fm_identity_legacy_callsign "$id") || { fm_identity_lock_release; return 1; } + if fm_identity_name_matches_any "$callsign"; then + callsign=$(fm_identity_choose_fresh_callsign "$id") || { fm_identity_lock_release; return 1; } + fi + else + callsign=$(fm_identity_choose_fresh_callsign "$id") || { fm_identity_lock_release; return 1; } + fi + created=$(fm_identity_now) + fi + retired=$(mktemp "${TMPDIR:-/tmp}/fm-identity-retired.XXXXXXXX") || { fm_identity_lock_release; return 1; } + [ -f "$record" ] && grep '^retired_callsign=' "$record" > "$retired" 2>/dev/null || true + new_worktree=$(fm_identity_worktree_of_meta "$meta" 2>/dev/null || true) + target=$(fm_identity_target_of_meta "$meta") + if [ "$legacy" = 1 ] && { [ -z "$new_worktree" ] || [ -z "$target" ]; }; then + if ! fm_identity_write_task_record "$record" "$id" "$callsign" provisioning "" "$created" "$retired"; then + rm -f "$retired" + fm_identity_lock_release + fm_identity_error "could not reserve the migration-compatible callsign for incomplete legacy task $id" + return 1 + fi + rm -f "$retired" + fm_identity_lock_release + printf '%s' "$callsign" + return 0 + fi + if ! fm_identity_write_task_record "$record" "$id" "$callsign" active "$meta" "$created" "$retired"; then + rm -f "$retired" + fm_identity_lock_release + fm_identity_error "could not publish the exact identity binding for task $id" + return 1 + fi + rm -f "$retired" + fm_identity_lock_release + printf '%s' "$callsign" +} + +fm_identity_ensure_legacy_archive() { # + local id=$1 record callsign created + record=$(fm_identity_task_record "$id") + fm_identity_lock_acquire || return 1 + if [ -e "$record" ] || [ -L "$record" ]; then + fm_identity_record_core_valid "$record" "$id" || { + fm_identity_lock_release + fm_identity_error "legacy identity record for task $id is malformed; refusing migration" + return 1 + } + callsign=$(fm_identity_record_value "$record" callsign) + fm_identity_lock_release + printf '%s' "$callsign" + return 0 + fi + callsign=$(fm_identity_legacy_callsign "$id") || { fm_identity_lock_release; return 1; } + if fm_identity_name_matches_any "$callsign"; then + callsign=$(fm_identity_choose_fresh_callsign "$id") || { fm_identity_lock_release; return 1; } + fi + created=$(fm_identity_now) + fm_identity_write_task_record "$record" "$id" "$callsign" archived "" "$created" \ + || { fm_identity_lock_release; return 1; } + fm_identity_lock_release + printf '%s' "$callsign" +} + +fm_identity_archive_task() { # + local meta=$1 id=$2 record callsign created retired status + record=$(fm_identity_task_record "$id") + [ -f "$record" ] || fm_identity_ensure_task_from_meta "$meta" "$id" 1 >/dev/null || return 1 + fm_identity_lock_acquire || return 1 + fm_identity_record_core_valid "$record" "$id" || { + fm_identity_lock_release + fm_identity_error "identity record for task $id is unsafe; retaining task metadata instead of losing name history" + return 1 + } + callsign=$(fm_identity_record_value "$record" callsign) + status=$(fm_identity_record_value "$record" status) + if [ "$status" = active ] && ! fm_identity_validate_active_binding "$record" "$meta" "$id"; then + fm_identity_lock_release + fm_identity_error "task $id's callsign binding conflicts with its cleanup metadata; refusing historical rebinding" + return 1 + fi + created=$(fm_identity_record_value "$record" created_at 2>/dev/null || fm_identity_now) + retired=$(mktemp "${TMPDIR:-/tmp}/fm-identity-retired.XXXXXXXX") || { fm_identity_lock_release; return 1; } + grep '^retired_callsign=' "$record" > "$retired" 2>/dev/null || true + fm_identity_write_task_record "$record" "$id" "$callsign" archived "$meta" "$created" "$retired" \ + || { rm -f "$retired"; fm_identity_lock_release; return 1; } + rm -f "$retired" + fm_identity_lock_release + printf '%s' "$callsign" +} + +fm_identity_display_callsign() { # + local id=$1 record callsign + record=$(fm_identity_task_record "$id") + if fm_identity_record_core_valid "$record" "$id" 2>/dev/null; then + callsign=$(fm_identity_record_value "$record" callsign) + printf '%s' "$callsign" + else + fm_identity_legacy_callsign "$id" + fi +} + +fm_identity_validate_active_binding() { # + local record=$1 meta=$2 id=$3 status worktree backend endpoint endpoint_session harness_session spawn_gen + local expected_worktree expected_backend expected_endpoint expected_endpoint_session expected_harness_session expected_spawn_gen + fm_identity_record_core_valid "$record" "$id" || return 1 + fm_identity_validate_meta_endpoint_ownership "$meta" "$id" || return 1 + status=$(fm_identity_record_value "$record" status) + [ "$status" = active ] || return 1 + worktree=$(fm_identity_record_value "$record" worktree 2>/dev/null || true) + backend=$(fm_identity_record_value "$record" backend 2>/dev/null || true) + endpoint=$(fm_identity_record_value "$record" endpoint 2>/dev/null || true) + endpoint_session=$(fm_identity_record_value "$record" endpoint_session_id 2>/dev/null || true) + harness_session=$(fm_identity_record_value "$record" harness_session_id 2>/dev/null || true) + spawn_gen=$(fm_identity_record_value "$record" spawn_gen 2>/dev/null || true) + expected_worktree=$(fm_identity_worktree_of_meta "$meta") || return 1 + expected_backend=$(fm_identity_backend_of_meta "$meta") + expected_endpoint=$(fm_identity_target_of_meta "$meta") + expected_endpoint_session=$(fm_identity_endpoint_session_of_meta "$meta") + expected_harness_session=$(fm_identity_harness_session_of_meta "$meta") || return 1 + expected_spawn_gen=$(fm_identity_meta_value "$meta" spawn_gen) + [ "$worktree" = "$expected_worktree" ] && [ "$backend" = "$expected_backend" ] \ + && [ "$endpoint" = "$expected_endpoint" ] \ + && [ "$endpoint_session" = "$expected_endpoint_session" ] \ + && [ "$harness_session" = "$expected_harness_session" ] \ + && [ "$spawn_gen" = "$expected_spawn_gen" ] +} + +fm_identity_selector_conflicts_with_other_record() { # + local raw=$1 resolved_id=$2 wanted record id value + wanted=$(fm_identity_fold "$raw") + for record in "$FM_IDENTITY_DIR"/*.identity; do + [ -f "$record" ] && [ ! -L "$record" ] || continue + id=${record##*/}; id=${id%.identity} + [ "$id" = "$resolved_id" ] && continue + while IFS= read -r value; do + [ "$(fm_identity_fold "$value")" = "$wanted" ] && return 0 + done < <(sed -n -e 's/^callsign=//p' -e 's/^retired_callsign=//p' "$record") + done + return 1 +} + +fm_identity_exact_task_record_routes() { # + local record=$1 meta=$2 id=$3 status key + fm_identity_record_core_valid "$record" "$id" || return 1 + status=$(fm_identity_record_value "$record" status) || return 1 + case "$status" in + active) fm_identity_validate_active_binding "$record" "$meta" "$id" ;; + provisioning) + # Legacy metadata may not yet carry a worktree or endpoint. Its reserved + # fallback callsign is deliberately not routable, but an exact task-id + # selector remains deterministic and keeps the pre-feature data-plane + # compatibility. Only the canonical empty provisioning shape qualifies. + for key in worktree backend endpoint endpoint_session_id harness_session_id spawn_gen; do + [ "$(grep -c "^$key=$" "$record" 2>/dev/null || true)" -eq 1 ] || return 1 + done + ;; + *) return 1 ;; + esac +} + +fm_identity_resolve_selector() { # + local state=$1 raw=$2 id record callsign status current_count=0 retired_count=0 match_id= match_record= + if ! fm_identity_task_id_valid "$raw"; then + fm_identity_error "selector '$raw' is unsafe; use a callsign or exact task id from this Firstmate home" + return 2 + fi + id=$raw + if [ -f "$state/$id.meta" ]; then + if fm_identity_selector_conflicts_with_other_record "$raw" "$id"; then + fm_identity_error "selector '$raw' conflicts with another task's current or historical callsign; refusing to guess" + return 2 + fi + record=$(fm_identity_task_record "$id") + if [ -e "$record" ] || [ -L "$record" ]; then + fm_identity_exact_task_record_routes "$record" "$state/$id.meta" "$id" || { + fm_identity_error "task '$id' has conflicting or unsafe callsign identity; refusing to route" + return 2 + } + fi + printf '%s' "$id" + return 0 + fi + case "$raw" in + fm-*) + id=${raw#fm-} + if [ -f "$state/$id.meta" ]; then + if fm_identity_selector_conflicts_with_other_record "$raw" "$id"; then + fm_identity_error "selector '$raw' conflicts with another task's current or historical callsign; refusing to guess" + return 2 + fi + record=$(fm_identity_task_record "$id") + if [ -e "$record" ] || [ -L "$record" ]; then + fm_identity_exact_task_record_routes "$record" "$state/$id.meta" "$id" || { + fm_identity_error "task '$id' has conflicting or unsafe callsign identity; refusing to route" + return 2 + } + fi + printf '%s' "$id" + return 0 + fi + ;; + esac + for record in "$FM_IDENTITY_DIR"/*.identity; do + [ -f "$record" ] && [ ! -L "$record" ] || continue + id=${record##*/}; id=${id%.identity} + if ! fm_identity_record_core_valid "$record" "$id"; then + if grep -qi "^callsign=$raw$\|^retired_callsign=$raw$" "$record" 2>/dev/null; then + fm_identity_error "callsign '$raw' matches a malformed identity record; refusing to guess" + return 2 + fi + continue + fi + callsign=$(fm_identity_record_value "$record" callsign) + if [ "$(fm_identity_fold "$callsign")" = "$(fm_identity_fold "$raw")" ]; then + current_count=$((current_count + 1)); match_id=$id; match_record=$record + fi + while IFS= read -r callsign; do + if [ "$(fm_identity_fold "$callsign")" = "$(fm_identity_fold "$raw")" ]; then + retired_count=$((retired_count + 1)) + fi + done < <(sed -n 's/^retired_callsign=//p' "$record") + done + if [ "$current_count" -gt 1 ]; then + fm_identity_error "callsign '$raw' is ambiguous across $current_count identity records; refusing to guess" + return 2 + fi + if [ "$current_count" -eq 1 ] && [ "$retired_count" -gt 0 ]; then + fm_identity_error "callsign '$raw' conflicts with historical name history; refusing to rebind or guess" + return 2 + fi + if [ "$current_count" -eq 0 ]; then + if [ "$retired_count" -gt 0 ]; then + fm_identity_error "callsign '$raw' is historical after a rename and cannot be rebound or routed" + return 5 + else + fm_identity_error "no callsign or task '$raw' exists in this Firstmate home" + return 3 + fi + fi + status=$(fm_identity_record_value "$match_record" status) + if [ "$status" = archived ] || [ ! -f "$state/$match_id.meta" ]; then + fm_identity_error "callsign '$raw' is archived-only for task $match_id; no live task can be routed" + return 4 + fi + if [ "$status" != active ] || ! fm_identity_validate_active_binding "$match_record" "$state/$match_id.meta" "$match_id"; then + fm_identity_error "callsign '$raw' has conflicting or unsafe active identity; refusing to route" + return 2 + fi + printf '%s' "$match_id" +} + +fm_identity_rename_task() { # + local state=$1 selector=$2 new=$3 id record old created retired meta + fm_identity_validate_name "$new" || return 1 + id=$(fm_identity_resolve_selector "$state" "$selector") || return 1 + meta="$state/$id.meta" + record=$(fm_identity_task_record "$id") + if [ ! -f "$record" ]; then + fm_identity_ensure_task_from_meta "$meta" "$id" legacy >/dev/null || { + fm_identity_error "legacy task $id could not receive a persistent callsign before rename" + return 1 + } + fi + fm_identity_lock_acquire || return 1 + fm_identity_validate_active_binding "$record" "$meta" "$id" || { + fm_identity_lock_release + fm_identity_error "task $id changed while its rename was being prepared; retry after reconciling it" + return 1 + } + old=$(fm_identity_record_value "$record" callsign) + if [ "$old" = "$new" ]; then + fm_identity_lock_release + printf '%s\t%s' "$old" "$id" + return 0 + fi + if [ "$(fm_identity_fold "$old")" = "$(fm_identity_fold "$new")" ]; then + created=$(fm_identity_record_value "$record" created_at 2>/dev/null || fm_identity_now) + retired=$(mktemp "${TMPDIR:-/tmp}/fm-identity-retired.XXXXXXXX") || { fm_identity_lock_release; return 1; } + grep '^retired_callsign=' "$record" > "$retired" 2>/dev/null || true + fm_identity_write_task_record "$record" "$id" "$new" active "$meta" "$created" "$retired" \ + || { rm -f "$retired"; fm_identity_lock_release; return 1; } + rm -f "$retired" + fm_identity_lock_release + printf '%s\t%s' "$new" "$id" + return 0 + fi + if fm_identity_name_matches_any "$new"; then + fm_identity_lock_release + fm_identity_error "callsign '$new' is already active, historical, or reserved by this home's Firstmate identity" + return 1 + fi + created=$(fm_identity_record_value "$record" created_at 2>/dev/null || fm_identity_now) + retired=$(mktemp "${TMPDIR:-/tmp}/fm-identity-retired.XXXXXXXX") || { fm_identity_lock_release; return 1; } + grep '^retired_callsign=' "$record" > "$retired" 2>/dev/null || true + printf 'retired_callsign=%s\n' "$old" >> "$retired" + fm_identity_write_task_record "$record" "$id" "$new" active "$meta" "$created" "$retired" \ + || { rm -f "$retired"; fm_identity_lock_release; return 1; } + rm -f "$retired" + fm_identity_lock_release + printf '%s\t%s' "$new" "$id" +} + +fm_identity_rename_home() { # + local new=$1 old created previous + fm_identity_validate_name "$new" || return 1 + fm_identity_ensure_home >/dev/null || return 1 + fm_identity_lock_acquire || return 1 + old=$(fm_identity_record_value "$FM_IDENTITY_HOME_RECORD" name) || { fm_identity_lock_release; return 1; } + if [ "$(fm_identity_fold "$old")" = "$(fm_identity_fold "$new")" ]; then + fm_identity_lock_release + printf '%s' "$new" + return 0 + fi + if fm_identity_name_matches_any "$new"; then + fm_identity_lock_release + fm_identity_error "name '$new' is already active or historical in this Firstmate home" + return 1 + fi + created=$(fm_identity_record_value "$FM_IDENTITY_HOME_RECORD" created_at 2>/dev/null || fm_identity_now) + previous=$(mktemp "${TMPDIR:-/tmp}/fm-identity-previous.XXXXXXXX") || { fm_identity_lock_release; return 1; } + grep '^previous_name=' "$FM_IDENTITY_HOME_RECORD" > "$previous" 2>/dev/null || true + printf 'previous_name=%s\n' "$old" >> "$previous" + fm_identity_write_home_record "$new" "$created" "$previous" \ + || { rm -f "$previous"; fm_identity_lock_release; return 1; } + rm -f "$previous" + fm_identity_lock_release + printf '%s' "$new" +} + +fm_identity_migrate_home() { + local meta id status + fm_identity_ensure_home >/dev/null || return 1 + for meta in "$FM_IDENTITY_STATE"/*.meta; do + [ -f "$meta" ] && [ ! -L "$meta" ] || continue + id=${meta##*/}; id=${id%.meta} + fm_identity_ensure_task_from_meta "$meta" "$id" 1 >/dev/null || return 1 + done + for status in "$FM_IDENTITY_STATE"/*.status; do + [ -f "$status" ] && [ ! -L "$status" ] || continue + id=${status##*/}; id=${id%.status} + [ -f "$FM_IDENTITY_STATE/$id.meta" ] && continue + fm_identity_ensure_legacy_archive "$id" >/dev/null || return 1 + done +} + +fm_identity_history() { + local record id callsign status + for record in "$FM_IDENTITY_DIR"/*.identity; do + [ -f "$record" ] && [ ! -L "$record" ] || continue + id=${record##*/}; id=${id%.identity} + fm_identity_record_core_valid "$record" "$id" || { + printf 'UNSAFE\t%s\t%s\n' "$id" "$record" + continue + } + callsign=$(fm_identity_record_value "$record" callsign) + status=$(fm_identity_record_value "$record" status) + printf '%s\t%s\t%s\n' "$callsign" "$id" "$status" + done | LC_ALL=C sort -f +} diff --git a/bin/fm-name.sh b/bin/fm-name.sh new file mode 100755 index 00000000000..d85278bcb46 --- /dev/null +++ b/bin/fm-name.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# Inspect and rename persistent Firstmate and task identities. +# +# Usage: +# fm-name.sh home +# fm-name.sh rename-home +# fm-name.sh rename +# fm-name.sh resolve +# fm-name.sh history +# +# Output keeps names first while retaining the exact task id in parentheses. +# resolve and rename accept callsigns case-insensitively within the explicit +# FM_HOME. Missing, ambiguous, archived-only, historical, conflicting, or unsafe +# matches refuse instead of guessing. +set -eu + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +FM_ROOT="${FM_ROOT_OVERRIDE:-$(cd "$SCRIPT_DIR/.." && pwd)}" + +usage() { + sed -n '2,12p' "$0" | sed 's/^# \{0,1\}//' +} + +case "${1:-}" in -h|--help|help|'') usage; exit 0 ;; esac + +if [ -z "${FM_HOME+x}" ] || [ -z "${FM_HOME:-}" ]; then + echo "error: FM_HOME is not set; fm-name refuses to resolve an identity without an explicit Firstmate home" >&2 + exit 1 +fi +[ -d "$FM_HOME" ] || { echo "error: FM_HOME '$FM_HOME' is not a directory" >&2; exit 1; } +STATE="${FM_STATE_OVERRIDE:-$FM_HOME/state}" +DATA="${FM_DATA_OVERRIDE:-$FM_HOME/data}" +mkdir -p "$STATE" "$DATA" + +# shellcheck source=bin/fm-backend.sh +. "$SCRIPT_DIR/fm-backend.sh" +# shellcheck source=bin/fm-identity-lib.sh +. "$SCRIPT_DIR/fm-identity-lib.sh" + +command=$1 +shift +case "$command" in + home) + [ "$#" -eq 0 ] || { usage >&2; exit 2; } + name=$(fm_identity_ensure_home) + printf '%s (Firstmate home)\n' "$name" + ;; + rename-home) + [ "$#" -eq 1 ] || { usage >&2; exit 2; } + name=$(fm_identity_rename_home "$1") + printf '%s (Firstmate home)\n' "$name" + ;; + rename) + [ "$#" -eq 2 ] || { usage >&2; exit 2; } + result=$(fm_identity_rename_task "$STATE" "$1" "$2") + callsign=${result%%$'\t'*} + id=${result#*$'\t'} + printf '%s (%s)\n' "$callsign" "$id" + ;; + resolve) + [ "$#" -eq 1 ] || { usage >&2; exit 2; } + id=$(fm_identity_resolve_selector "$STATE" "$1") + callsign=$(fm_identity_display_callsign "$id") + printf '%s (%s)\n' "$callsign" "$id" + ;; + history) + [ "$#" -eq 0 ] || { usage >&2; exit 2; } + fm_identity_history | while IFS=$'\t' read -r callsign id status; do + if [ "$callsign" = UNSAFE ]; then + printf 'UNSAFE (%s) %s\n' "$id" "$status" + else + printf '%s (%s) %s\n' "$callsign" "$id" "$status" + fi + done + ;; + *) usage >&2; exit 2 ;; +esac diff --git a/bin/fm-peek.sh b/bin/fm-peek.sh index e3156f66ed4..f95a057c7ce 100755 --- a/bin/fm-peek.sh +++ b/bin/fm-peek.sh @@ -1,8 +1,8 @@ #!/usr/bin/env bash # Print the tail of a crewmate endpoint (bounded, for cheap diagnosis). # Usage: fm-peek.sh [lines=40] -# may be an exact task id, a legacy fm- task label resolved -# through this home's state/.meta, or an explicit backend target. +# may be a persistent callsign, an exact task id, a legacy fm- +# task label resolved through this home's state/.meta, or an explicit backend target. # A selector whose meta records remote_host= is a remote secondmate: its pane # lives on that host, so the capture routes over fm-on.sh to the host-local # capture (fm-remote-secondmate-control.sh), clamped to that command's @@ -17,13 +17,26 @@ STATE="${FM_STATE_OVERRIDE:-$FM_HOME/state}" # shellcheck source=bin/fm-backend.sh . "$SCRIPT_DIR/fm-backend.sh" +# shellcheck source=bin/fm-identity-lib.sh +. "$SCRIPT_DIR/fm-identity-lib.sh" "$SCRIPT_DIR/fm-guard.sh" || true RAW_TARGET=$1 N=${2:-40} - -REMOTE_META=$(fm_backend_meta_for_selector "$RAW_TARGET" "$STATE" 2>/dev/null || true) +TARGET_SELECTOR=$RAW_TARGET +case "$RAW_TARGET" in + *:*) ;; + *) + if RESOLVED_ID=$(fm_identity_resolve_selector "$STATE" "$RAW_TARGET"); then + TARGET_SELECTOR=$RESOLVED_ID + else + exit 1 + fi + ;; +esac + +REMOTE_META=$(fm_backend_meta_for_selector "$TARGET_SELECTOR" "$STATE" 2>/dev/null || true) if [ -n "$REMOTE_META" ] && [ -n "$(fm_meta_get "$REMOTE_META" remote_host)" ]; then REMOTE_ID=${REMOTE_META##*/} REMOTE_ID=${REMOTE_ID%.meta} @@ -38,9 +51,9 @@ if [ -n "$REMOTE_META" ] && [ -n "$(fm_meta_get "$REMOTE_META" remote_host)" ]; exit 0 fi -T=$(fm_backend_resolve_selector "$RAW_TARGET" "$STATE") +T=$(fm_backend_resolve_selector "$TARGET_SELECTOR" "$STATE") -BACKEND=$(fm_backend_of_selector "$RAW_TARGET" "$T" "$STATE") -EXPECTED_LABEL=$(fm_backend_expected_label_of_selector "$RAW_TARGET" "$STATE") +BACKEND=$(fm_backend_of_selector "$TARGET_SELECTOR" "$T" "$STATE") +EXPECTED_LABEL=$(fm_backend_expected_label_of_selector "$TARGET_SELECTOR" "$STATE") fm_backend_capture "$BACKEND" "$T" "$N" "$EXPECTED_LABEL" diff --git a/bin/fm-send.sh b/bin/fm-send.sh index 512df6245c7..30f1337ffd0 100755 --- a/bin/fm-send.sh +++ b/bin/fm-send.sh @@ -1,9 +1,9 @@ #!/usr/bin/env bash # Send one line of literal text to a crewmate endpoint, then Enter. # 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 +# may be a persistent callsign, 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 # tmux window search, because a "successful" send to the wrong endpoint is # worse than a loud failure. # Special keys instead of text: fm-send.sh --key Enter @@ -131,6 +131,8 @@ fi # shellcheck source=bin/fm-backend.sh . "$SCRIPT_DIR/fm-backend.sh" +# shellcheck source=bin/fm-identity-lib.sh +. "$SCRIPT_DIR/fm-identity-lib.sh" # shellcheck source=bin/fm-control-lib.sh . "$SCRIPT_DIR/fm-control-lib.sh" # shellcheck source=bin/fm-marker-lib.sh @@ -222,7 +224,7 @@ fm_send_count_colons() { # } fm_send_resolve_target() { # - local raw=$1 meta pane_meta target backend assumed colons id session hint + local raw=$1 meta pane_meta target backend assumed colons id resolved_id session hint identity_rc identity_record identity_status RESOLVED_TARGET="" TARGET_BACKEND="" @@ -234,6 +236,33 @@ fm_send_resolve_target() { # RESOLUTION_TRIED="" meta=$(fm_backend_meta_for_selector "$raw" "$STATE" 2>/dev/null || true) + [ -z "$meta" ] || id=$(fm_send_id_from_meta "$meta") + case "$raw" in + *:*) ;; # Preserve the verified explicit-endpoint compatibility path below. + *) + if [ -z "$meta" ]; then + set +e + id=$(fm_identity_resolve_selector "$STATE" "$raw") + identity_rc=$? + set -e + case "$identity_rc" in + 0) meta="$STATE/$id.meta" ;; + *) return 1 ;; + esac + else + resolved_id=$(fm_identity_resolve_selector "$STATE" "$raw") || return 1 + [ "$resolved_id" = "$id" ] || { + fm_identity_error "selector '$raw' resolved to task $resolved_id but backend metadata selected task $id; refusing to guess" + return 1 + } + fi + identity_record=$(fm_identity_task_record "$id") + identity_status=$(fm_identity_record_value "$identity_record" status 2>/dev/null || true) + if [ "$identity_status" != active ]; then + fm_identity_ensure_task_from_meta "$meta" "$id" legacy >/dev/null || return 1 + fi + ;; + esac if [ -n "$meta" ]; then if [ -n "$(fm_meta_get "$meta" remote_host)" ]; then id=$(fm_send_id_from_meta "$meta") @@ -242,7 +271,7 @@ fm_send_resolve_target() { # TARGET_META=$meta TARGET_HARNESS=$(fm_meta_get "$meta" harness) EXPECTED_LABEL="fm-$id" - TARGET_SELECTOR=1 + case "$raw" in *:*) ;; *) TARGET_SELECTOR=1 ;; esac TARGET_REMOTE_ID=$id RESOLUTION_TRIED="meta=$meta; placement=remote" return 0 @@ -258,8 +287,8 @@ fm_send_resolve_target() { # TARGET_BACKEND=$backend TARGET_META=$meta TARGET_HARNESS=$(fm_meta_get "$meta" harness) - EXPECTED_LABEL=$(fm_backend_expected_label_of_selector "$raw" "$STATE") - TARGET_SELECTOR=1 + EXPECTED_LABEL="fm-$id" + case "$raw" in *:*) ;; *) TARGET_SELECTOR=1 ;; esac return 0 fi diff --git a/bin/fm-session-start.sh b/bin/fm-session-start.sh index a0383e46810..cd9a1a6b471 100755 --- a/bin/fm-session-start.sh +++ b/bin/fm-session-start.sh @@ -325,6 +325,8 @@ PRIMARY_HARNESS=$("$SCRIPT_DIR/fm-harness.sh" 2>/dev/null || printf unknown) # shellcheck source=bin/fm-backend.sh . "$SCRIPT_DIR/fm-backend.sh" +# shellcheck source=bin/fm-identity-lib.sh +. "$SCRIPT_DIR/fm-identity-lib.sh" # shellcheck source=bin/fm-tasks-axi-lib.sh . "$SCRIPT_DIR/fm-tasks-axi-lib.sh" # shellcheck source=bin/fm-public-followup-lib.sh @@ -643,6 +645,9 @@ REBUILDING_SESSION_PID=$(fm_harness_ancestry_pid 2>/dev/null || true) print_agents_refresh_if_required "$REBUILDING_SESSION_PID" if [ "$READ_ONLY" -eq 0 ]; then + if ! fm_identity_migrate_home; then + printf 'IDENTITY: persistent home/task name migration failed; names-first routing will refuse unsafe records until repaired.\n' >&2 + fi if [ "$REEMIT" -eq 0 ]; then rm -f "$COMPLETION_FILE" 2>/dev/null || true fi @@ -787,13 +792,23 @@ stage fleet-state section "FLEET STATE" print_backlog_compact "$DATA/backlog.md" "data/backlog.md" +subsection "Firstmate identity" +if [ -f "$FM_IDENTITY_HOME_RECORD" ] && [ ! -L "$FM_IDENTITY_HOME_RECORD" ]; then + firstmate_name=$(fm_identity_record_value "$FM_IDENTITY_HOME_RECORD" name 2>/dev/null || true) + [ -n "$firstmate_name" ] && printf '%s (Firstmate home)\n' "$firstmate_name" \ + || printf 'UNSAFE - malformed persistent Firstmate identity record\n' +else + printf '%s (deterministic fallback; read-only session did not persist it)\n' "$(fm_identity_choose_home_name)" +fi + subsection "Work under way (state/*.meta)" META_FOUND=0 for meta in "$STATE"/*.meta; do [ -f "$meta" ] || continue META_FOUND=1 id=$(basename "$meta" .meta) - printf '\n--- %s ---\n' "$id" + callsign=$(fm_identity_display_callsign "$id") + printf '\n--- %s (%s) ---\n' "$callsign" "$id" cat "$meta" window=$(fm_meta_get "$meta" window) @@ -825,7 +840,8 @@ for status in "$STATE"/*.status; do id=$(basename "$status" .status) [ -f "$STATE/$id.meta" ] && continue ORPHAN_STATUS_FOUND=1 - printf '\n--- %s ---\n' "$id" + callsign=$(fm_identity_display_callsign "$id") + printf '\n--- %s (%s) ---\n' "$callsign" "$id" print_status_tail "$status" done [ "$ORPHAN_STATUS_FOUND" -eq 1 ] || printf '(none)\n' diff --git a/bin/fm-spawn.sh b/bin/fm-spawn.sh index 01b0e77ca6b..7ec476cab31 100755 --- a/bin/fm-spawn.sh +++ b/bin/fm-spawn.sh @@ -256,6 +256,8 @@ SUB_HOME_MARKER=".fm-secondmate-home" . "$SCRIPT_DIR/fm-config-inherit-lib.sh" # shellcheck source=bin/fm-backend.sh . "$SCRIPT_DIR/fm-backend.sh" +# shellcheck source=bin/fm-identity-lib.sh +. "$SCRIPT_DIR/fm-identity-lib.sh" # shellcheck source=bin/fm-control-lib.sh . "$SCRIPT_DIR/fm-control-lib.sh" # shellcheck source=bin/fm-codex-session-lib.sh @@ -524,6 +526,21 @@ spawn_remote_secondmate() { return 1 fi fi + if [ ! -f "$(fm_identity_task_record "$id")" ]; then + if [ -f "$meta" ]; then + CALLSIGN=$(fm_identity_ensure_task_from_meta "$meta" "$id" legacy) || { + fm_lock_release "$registry_lock" || true + fm_lock_release "$SPAWN_TASK_LOCK" || true + return 1 + } + else + CALLSIGN=$(fm_identity_reserve_fresh_task "$id") || { + fm_lock_release "$registry_lock" || true + fm_lock_release "$SPAWN_TASK_LOCK" || true + return 1 + } + fi + fi # Gate the host before anything is published or transferred, so a host that # cannot hold a durable Herdr endpoint refuses here rather than half-way # through a launch. This is also the readiness gate every liveness relaunch @@ -659,6 +676,17 @@ spawn_remote_secondmate() { [ -z "$remote_recorded_traceparent" ] || echo "traceparent=$remote_recorded_traceparent" } > "$tmp" mv -f -- "$tmp" "$meta" + CALLSIGN=$(fm_identity_ensure_task_from_meta "$meta" "$id" rebind) || { + echo "error: remote secondmate $id launched, but its persistent callsign binding could not be published; endpoint metadata is preserved" >&2 + if [ "$SPAWN_TASK_SET_LOCK_HELD" = 1 ]; then + SPAWN_TASK_SET_LOCK_HELD=0 + fm_lock_release "$SPAWN_TASK_SET_LOCK" || true + fi + fm_lock_release "$remote_lock" || true + fm_lock_release "$registry_lock" || true + fm_lock_release "$SPAWN_TASK_LOCK" || true + return 1 + } if [ "$SPAWN_TASK_SET_LOCK_HELD" = 1 ]; then SPAWN_TASK_SET_LOCK_HELD=0 fm_lock_release "$SPAWN_TASK_SET_LOCK" @@ -670,7 +698,7 @@ spawn_remote_secondmate() { echo "error: remote secondmate $id launched, but its reply source could not be armed; endpoint metadata is preserved" >&2 return 1 fi - echo "spawned $id harness=$harness kind=secondmate mode=secondmate yolo=off window=remote:$id worktree=$home remote=$host backend=$remote_backend" + echo "spawned $CALLSIGN ($id) harness=$harness kind=secondmate mode=secondmate yolo=off window=remote:$id worktree=$home remote=$host backend=$remote_backend" return 0 } @@ -1009,6 +1037,22 @@ if ! fm_lock_try_acquire "$SPAWN_TASK_LOCK"; then exit 1 fi SPAWN_TASK_LOCK_HELD=1 +CALLSIGN= +IDENTITY_FRESH_RESERVED=0 +IDENTITY_REBIND_ALLOWED=0 +if [ "$RELAUNCH" -eq 0 ]; then + if [ "$KIND" = secondmate ] && [ -f "$STATE/$ID.meta" ]; then + # Bootstrap's established secondmate recovery path predates --relaunch and + # intentionally invokes an ordinary --secondmate spawn against the durable + # task record. It is a continuation, not a fresh task: validate/adopt the + # existing binding now and publish its replacement endpoint below. + CALLSIGN=$(fm_identity_ensure_task_from_meta "$STATE/$ID.meta" "$ID" 1) || exit 1 + IDENTITY_REBIND_ALLOWED=1 + else + CALLSIGN=$(fm_identity_reserve_fresh_task "$ID") || exit 1 + IDENTITY_FRESH_RESERVED=1 + fi +fi PROJ= ARG3= FIRSTMATE_HOME= @@ -2761,6 +2805,13 @@ if [ "$RELAUNCH" -eq 1 ]; then fm_lock_release "$SPAWN_META_LOCK" SPAWN_META_LOCK_HELD=0 fi +if [ "$IDENTITY_FRESH_RESERVED" = 1 ]; then + CALLSIGN=$(fm_identity_activate_reserved_task_from_meta "$STATE/$ID.meta" "$ID") || exit 1 +elif [ "$RELAUNCH" = 1 ] || [ "$IDENTITY_REBIND_ALLOWED" = 1 ]; then + CALLSIGN=$(fm_identity_ensure_task_from_meta "$STATE/$ID.meta" "$ID" rebind) || exit 1 +else + CALLSIGN=$(fm_identity_ensure_task_from_meta "$STATE/$ID.meta" "$ID") || exit 1 +fi if [ "$SPAWN_TASK_SET_LOCK_HELD" = 1 ]; then # The record is published, so this task is now part of the set a teardown # enumerates and locks per task. The set lock is only needed across that @@ -2932,4 +2983,4 @@ fi SPAWN_DELIVERY= [ -z "$MODE" ] || SPAWN_DELIVERY=" mode=$MODE yolo=$YOLO" -echo "spawned $ID harness=$HARNESS kind=$KIND$SPAWN_DELIVERY window=$META_WINDOW worktree=$WT" +echo "spawned $CALLSIGN ($ID) harness=$HARNESS kind=$KIND$SPAWN_DELIVERY window=$META_WINDOW worktree=$WT" diff --git a/bin/fm-teardown.sh b/bin/fm-teardown.sh index 4b706570b1a..e6b14163c23 100755 --- a/bin/fm-teardown.sh +++ b/bin/fm-teardown.sh @@ -148,6 +148,8 @@ SUB_HOME_PARENT_MARKER=".fm-secondmate-parent" . "$SCRIPT_DIR/fm-tasks-axi-lib.sh" # shellcheck source=bin/fm-backend.sh . "$SCRIPT_DIR/fm-backend.sh" +# shellcheck source=bin/fm-identity-lib.sh +. "$SCRIPT_DIR/fm-identity-lib.sh" # shellcheck source=bin/fm-control-lib.sh . "$SCRIPT_DIR/fm-control-lib.sh" # shellcheck source=bin/fm-codex-session-lib.sh @@ -2439,6 +2441,15 @@ fi # pruned code root. Best effort - a sweep failure never blocks this teardown. "$SCRIPT_DIR/fm-remote-job-reap-orphans.sh" >&2 || true +# Publish or validate the task's durable callsign only after every cleanup +# prerequisite above has passed, but before returning its worktree or closing +# its endpoint. A malformed/conflicting identity therefore refuses while all +# recoverable task state is still intact; final retirement below only flips +# this already-validated binding to its historical tombstone. +ARCHIVED_CALLSIGN=$(fm_identity_ensure_task_from_meta "$META" "$ID" 1) || { + echo "error: task $ID's persistent callsign could not be validated; nothing was changed" >&2 + exit 1 +} # Best-effort: drop the local task branch so the shared repo does not accumulate refs. if [ "$BACKEND" = orca ] && [ "$KIND" != secondmate ]; then if [ "$ORCA_PATH_MATCH_VERIFIED" != 1 ]; then @@ -2574,6 +2585,10 @@ fm_codex_session_retire "$STATE" "$ID" || { echo "error: exact Codex session binding for $ID could not be retired safely; retaining task metadata" >&2 exit 1 } +ARCHIVED_CALLSIGN=$(fm_identity_archive_task "$META" "$ID") || { + echo "error: task $ID cleanup reached record retirement, but its callsign history could not be archived; retaining task metadata for a safe retry" >&2 + exit 1 +} rm -f "$STATE/$ID.turn-ended" "$STATE/$ID.meta" \ "$STATE/$ID.pi-ext.ts" "$STATE/$ID.grok-turnend-token" \ "$STATE/$ID.kimi-turnend-token" "$STATE/$ID.muse-session" \ @@ -2586,5 +2601,5 @@ META_LOCK_HELD=0 if [ "$KIND" != scout ] && [ "$KIND" != secondmate ] && [ "$MODE" != local-only ]; then "$FM_ROOT/bin/fm-fleet-sync.sh" "$PROJ" || true fi -echo "teardown $ID complete (window $T, worktree $WT)" +echo "teardown $ARCHIVED_CALLSIGN ($ID) complete (window $T, worktree $WT)" backlog_refresh_reminder diff --git a/bin/fm-test-run.sh b/bin/fm-test-run.sh index bffe8656a07..0c1a125ea74 100755 --- a/bin/fm-test-run.sh +++ b/bin/fm-test-run.sh @@ -200,7 +200,7 @@ family_for_basename() { fm-herdr-submit-confirm-live-e2e.test.sh) printf '%s\n' live-harness-optin ;; - fm-backend-herdr.test.sh|fm-backend-tmux-smoke.test.sh|fm-backend.test.sh|\ + fm-backend-herdr.test.sh|fm-backend-tmux-smoke.test.sh|fm-backend.test.sh|fm-identity.test.sh|\ fm-tmux-agent-liveness.test.sh|\ fm-codex-session.test.sh|fm-control.test.sh|fm-control-relaunch.test.sh|\ fm-herdr-session-cleanup.test.sh|fm-send-resolve-key.test.sh|fm-send-strict.test.sh|fm-spawn-batch.test.sh|\ @@ -1005,6 +1005,12 @@ families_for_changed_path() { printf '%s\n' pure-contract-unit printf '%s\n' live-harness-optin ;; + bin/fm-identity-lib.sh|bin/fm-name.sh) + printf '%s\n' backend-dispatch + printf '%s\n' snapshot-bearings + printf '%s\n' session-bootstrap + printf '%s\n' pr-forge + ;; bin/fm-spawn.sh|bin/fm-send.sh|bin/fm-harness.sh|\ bin/fm-peek.sh|bin/fm-composer*) printf '%s\n' backend-dispatch diff --git a/docs/agent-control.md b/docs/agent-control.md index d9513d1dfd8..5578cfaaa5e 100644 --- a/docs/agent-control.md +++ b/docs/agent-control.md @@ -5,7 +5,7 @@ Firstmate talks to a running agent two ways, and they are not the same channel. The **data plane** is [`bin/fm-send.sh`](../bin/fm-send.sh): conversational text for the agent to read. For a `kind=secondmate` target it always prepends the from-firstmate routing marker, because a secondmate is itself a firstmate and its reply must come back through the status path rather than a chat nobody reads. -The **control plane** is [`bin/fm-control.sh`](../bin/fm-control.sh): allowlisted lifecycle verbs addressed to an exact task id. +The **control plane** is [`bin/fm-control.sh`](../bin/fm-control.sh): allowlisted lifecycle verbs addressed names-first by persistent callsign or by exact task id. The split exists because the data plane's marking is exactly right for a message and exactly wrong for a lifecycle command. A routing-marked `/quit` arrives as ordinary chat - `[fm-from-firstmate] /quit` - which the agent reasons about instead of executing. @@ -52,8 +52,8 @@ Ordinary `relaunch` remains the portable disposable path on every adapter, using Codex ship tasks have one explicit opt-in specialization on the existing verbs: ```sh -FM_HOME= bin/fm-control.sh exit --resumable -FM_HOME= bin/fm-control.sh relaunch --resume --note '' +FM_HOME= bin/fm-control.sh exit --resumable +FM_HOME= bin/fm-control.sh relaunch --resume --note '' ``` Fresh spawn, ordinary exit, ordinary relaunch, scouts, secondmates, non-Codex harnesses, and harness switching keep their existing disposable behavior. @@ -112,8 +112,9 @@ Switching harness is therefore one ordinary relaunch rather than a separate mech ## Fail-closed boundaries - Targeting is exact. - Only a bare task id with a `state/.meta` record in this home is accepted, and that record must pass the shared endpoint-identity validation. - A legacy `fm-` window label, an explicit `session:window` endpoint, and a record whose `endpoint_task_id` names another task are all refused. + A persistent callsign must resolve through `bin/fm-identity-lib.sh` to exactly one active task record in this home, and an exact task id remains supported. + The resolved task record must pass the shared endpoint-identity validation. + A legacy `fm-` window label, bare window name, explicit backend target, missing name, ambiguous name, archived-only name, historical name, conflicting record, and a record whose `endpoint_task_id` names another task are all refused. - A remotely placed secondmate is refused by name. Its agent runs on another host, so none of the postconditions this plane verifies could be read for it here; local endpoint validation would refuse the record regardless, because `window=remote:` can never match a local backend's required shape. Drive that lifecycle on its own host and reconcile it through the secondmate recovery path. diff --git a/docs/configuration.md b/docs/configuration.md index c9d0d293a52..5ad85838f81 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -10,7 +10,7 @@ The shared orchestrator behavior lives in [`AGENTS.md`](../AGENTS.md) - edit it This section is the single owner of the top-level operational-home layout; producer script headers and their help own exact child-file fields and mutation contracts. The tracked code root contains the shared instruction, skill, documentation, workflow, and `bin/` surfaces, while each effective `FM_HOME` contains private operational directories. -`data/` holds durable private fleet records such as the project and secondmate registries, captain preferences, optional shared captain preferences, learnings, backlog, briefs, and scout reports. +`data/` holds durable private fleet records such as the Firstmate and crew identity records, project and secondmate registries, captain preferences, optional shared captain preferences, learnings, backlog, briefs, and scout reports. `state/` holds runtime records such as task metadata, append-only status events, endpoint signals, watcher and wake-queue coordination, inactive terminal-outcome receipts under `state/terminal-outcomes/`, away-mode state, generated Relay artifacts, private secondmate config-reread generations with their retry and quarantine state, and parent-owned secondmate pending-reply records under `state/pending-replies/` (`bin/fm-pending-reply-lib.sh`). `config/` holds local gitignored operating choices, and `projects/` holds the local project clones that Firstmate reads but changes only through the narrow guarded and concrete captain-approved exceptions in `AGENTS.md`. @@ -73,12 +73,14 @@ A herdr task additionally records `herdr_session=`, `herdr_workspace_id=`, `herd A zellij task additionally records `zellij_session=`, `zellij_tab_id=`, and `zellij_pane_id=`. An Orca task additionally records `orca_worktree_id=` and `terminal=`, with `window=fm-` kept as the shared firstmate alias. A cmux task additionally records `cmux_workspace_id=` and `cmux_surface_id=`. -Task selectors for `fm-peek.sh`, `fm-send.sh`, and `fm-crew-state.sh` resolve centrally through `fm_backend_resolve_selector`. -A selector containing `:` is passed through as an explicit backend endpoint escape hatch. -Otherwise an exact task id matching `state/.meta` wins before the legacy `fm-` label fallback, so task ids that themselves start with `fm-` route to their own metadata instead of being stripped. +Task selectors for `fm-peek.sh`, `fm-send.sh`, `fm-control.sh`, and `fm-crew-state.sh` first resolve a callsign or exact task id through the shared identity contract in `bin/fm-identity-lib.sh`, then resolve the recorded backend endpoint through `fm_backend_resolve_selector`. +The identity step is scoped to the canonical `FM_HOME` and accepts a callsign only when one active, structurally valid record binds it to one exact task metadata file. +Missing, ambiguous, archived-only, historical-after-rename, home-conflicting, worktree-conflicting, and endpoint-conflicting names refuse instead of falling through to a guessed task. +An exact task id remains supported, while the legacy `fm-` label remains a compatibility selector only on data-plane reads and sends and is not accepted by lifecycle control. +A selector containing `:` remains an explicit backend endpoint escape hatch for data-plane tools only and never becomes a callsign or lifecycle target. A metadata-routed selector returns the recorded backend target (`terminal=` for Orca, otherwise `window=`), and matching explicit targets can still recover the recorded backend when metadata contains the same endpoint. -Only metadata-routed task selectors carry secondmate-marker and Codex-harness context; explicit endpoint escape hatches do not. -These five sentences are the single owner of the task-selector vocabulary; backend guides and other documents point here instead of restating the resolution order. +Only metadata-routed task selectors carry secondmate-marker and harness context, while explicit endpoint escape hatches do not. +This paragraph is the operator-facing owner of the task-selector vocabulary, while the identity library header owns exact persistence, validation, migration, and lookup mechanics. `fm-teardown.sh ` takes a task id directly and validates the complete metadata-only endpoint identity before any runtime dispatch or cleanup mutation. Missing, empty, duplicate, malformed, backend-inconsistent, or task-mismatched endpoint records are preserved and refused. Legacy tmux metadata remains cleanup-compatible when its exact window name is `fm-`; opaque non-tmux endpoints require their recorded `endpoint_task_id=` binding. @@ -96,6 +98,17 @@ The caller-facing label remains `fm-`, but the actual cmux workspace title i Test cleanup must use the guarded path in [`docs/cmux-backend.md`](cmux-backend.md#current-operation-and-safety), never enumerate-and-close every workspace. `config/backend` is inherited into secondmate homes under the primary-authoritative contract owned by [`secondmate-provisioning`](../.agents/skills/secondmate-provisioning/SKILL.md). +## Persistent human identity (data/firstmate.identity / data/crew-identities/) + +Each canonical Firstmate home persists one human-friendly name in `data/firstmate.identity` and one immutable task-to-callsign history under `data/crew-identities/`. +A fresh spawn reserves a deterministic unused callsign before endpoint creation and publishes the exact canonical home, task id, worktree, backend, endpoint, backend session, spawn incarnation, and known harness thread or session id before the agent launches. +Relaunch and a future exact-thread resume update the same task binding without changing its callsign, while a genuinely fresh task must use a new task id and receives a new callsign. +Teardown archives rather than deletes the task identity record, and every retired callsign from an explicit rename remains reserved permanently within that home. +Locked session start creates the home identity and migrates active or archived legacy task records with deterministic fallback callsigns, while read-only views calculate a clearly sourced fallback without mutating the home. +Use `bin/fm-name.sh home`, `bin/fm-name.sh rename-home `, `bin/fm-name.sh rename `, `bin/fm-name.sh resolve `, and `bin/fm-name.sh history` with an explicit `FM_HOME`. +Names are case-insensitive for uniqueness and routing, and reserved names, task-id collisions, active collisions, retired collisions, malformed records, and unsafe binding conflicts are refused. +The header and executable functions in `bin/fm-identity-lib.sh` are the single owner of record fields, atomic mutation, automatic naming, non-rebinding, and migration mechanics. + ## Away-mode supervisor backend (FM_SUPERVISOR_BACKEND / FM_SUPERVISOR_TARGET) The `/afk` sub-supervisor injects escalation digests into firstmate's own pane independently of where new task endpoints are spawned. diff --git a/tests/fm-backend-orca.test.sh b/tests/fm-backend-orca.test.sh index 4870a2e0469..a2b486513f6 100755 --- a/tests/fm-backend-orca.test.sh +++ b/tests/fm-backend-orca.test.sh @@ -509,7 +509,7 @@ test_spawn_writes_orca_metadata_and_launches_harness() { FM_PROJECTS_OVERRIDE="$TMP_ROOT/unused-projects" FM_SPAWN_NO_GUARD=1 \ "$ROOT/bin/fm-spawn.sh" "$id" "$proj" claude --mode no-mistakes --yolo off --backend orca 2>&1 ) expect_code 0 $? "fm-spawn.sh --backend orca should succeed with fake Orca"$'\n'"$out" - assert_contains "$out" "spawned $id harness=claude kind=ship mode=no-mistakes yolo=off window=fm-$id worktree=$wt" \ + assert_contains "$out" "($id) harness=claude kind=ship mode=no-mistakes yolo=off window=fm-$id worktree=$wt" \ "spawn output missing Orca window/worktree summary" assert_grep "backend=orca" "$state/$id.meta" "meta missing backend=orca" assert_grep "window=fm-$id" "$state/$id.meta" "meta missing stable Orca window alias" diff --git a/tests/fm-bearings-snapshot.test.sh b/tests/fm-bearings-snapshot.test.sh index 3ff7722216c..dcd55d5ec2f 100755 --- a/tests/fm-bearings-snapshot.test.sh +++ b/tests/fm-bearings-snapshot.test.sh @@ -880,6 +880,28 @@ EOF pass "repeated snapshots keep the same current landed baseline and ignore prior reports" } +test_callsigns_accompany_live_results_and_history() { + local home fakebin json done_callsign + home=$(make_home callsign-projection); write_fixture "$home" + fakebin=$(make_fakebin "$home") + FM_HOME="$home" FM_ROOT_OVERRIDE="$ROOT" "$ROOT/bin/fm-name.sh" rename ship-task Mariner >/dev/null \ + || fail "could not seed live ship callsign" + FM_HOME="$home" FM_ROOT_OVERRIDE="$ROOT" "$ROOT/bin/fm-name.sh" rename scout-x Pathfinder >/dev/null \ + || fail "could not seed scout callsign" + done_callsign=$(FM_HOME="$home" FM_ROOT_OVERRIDE="$ROOT" bash -c ' + . "$FM_ROOT_OVERRIDE/bin/fm-backend.sh" + . "$FM_ROOT_OVERRIDE/bin/fm-identity-lib.sh" + fm_identity_ensure_legacy_archive done-a + ') + json=$(run "$home" "$fakebin" --json --all-landed --all-reports) + printf '%s' "$json" | jq -e --arg done "$done_callsign" ' + (.in_flight | any(.[]; .id == "ship-task" and .callsign == "Mariner")) + and (.reports | any(.[]; .id == "scout-x" and .callsign == "Pathfinder")) + and (.landed | any(.[]; .id == "done-a" and .callsign == $done)) + ' >/dev/null || fail "Bearings omitted callsigns from live work, results, or landed history: $json" + pass "Bearings shows callsigns beside task ids in live work, results, and history" +} + test_default_is_bounded_and_local_only() { local home fakebin toon json home=$(make_home bounded); write_fixture "$home" @@ -1953,6 +1975,7 @@ test_parent_evidence_reconciles_by_verb_and_key test_nonprogressing_child_states_are_explicit test_registry_unavailability_and_bounds_are_explicit test_current_landed_baseline_is_repeatable_and_prior_report_independent +test_callsigns_accompany_live_results_and_history test_default_is_bounded_and_local_only test_toon_json_parity test_landed_includes_secondmate_home_merges diff --git a/tests/fm-control-relaunch.test.sh b/tests/fm-control-relaunch.test.sh index 26e63f82774..d4271c45749 100755 --- a/tests/fm-control-relaunch.test.sh +++ b/tests/fm-control-relaunch.test.sh @@ -275,7 +275,8 @@ test_same_harness_relaunch_keeps_identity_and_reuses_the_endpoint() { printf 'busy_gen=%s\n' "$gen_before" >> "$dir/home/state/rl1.meta" out=$(run_control "$dir" rl1 relaunch --note "stopped mid-refactor"); rc=$? expect_code 0 "$rc" "a same-harness relaunch should succeed"$'\n'"$out" - assert_contains "$out" "relaunched rl1 harness=claude from=claude" "the outcome should name the transition" + assert_contains "$out" "relaunched" "the outcome should name the transition" + assert_contains "$out" "(rl1) harness=claude from=claude" "the outcome should retain the task id beside its callsign" [ "$(meta_field "$dir" rl1 window)" = "fmses:fm-rl1" ] \ || fail "the endpoint must be reused, not recreated" [ "$(meta_field "$dir" rl1 worktree)" = "$dir/wt" ] \ @@ -293,7 +294,7 @@ test_same_harness_relaunch_keeps_identity_and_reuses_the_endpoint() { } test_codex_exact_session_resume_and_ordinary_switch_retire_binding() { - local dir out rc old_gen new_gen side owner + local dir out rc old_gen new_gen side owner callsign dir=$(new_case codex-resume rl31) add_ship_task "$dir" rl31 codex printf 'spawn_gen=spawn-rl31-initial\n' >> "$dir/home/state/rl31.meta" @@ -309,11 +310,13 @@ test_codex_exact_session_resume_and_ordinary_switch_retire_binding() { owner="$dir/home/state/codex-sessions/$CODEX_SESSION_ID.owner" [ "$(grep '^state=' "$side")" = state=parked ] || fail "the exact task binding should be parked" cmp -s "$side" "$owner" || fail "the task binding and global exact-session owner must be byte-identical" + callsign=$(sed -n 's/^callsign=//p' "$dir/home/data/crew-identities/rl31.identity") + [ -n "$callsign" ] || fail "resumable task did not retain a persistent callsign" - out=$(run_control "$dir" rl31 relaunch --resume --note "continue exact session"); rc=$? - expect_code 0 "$rc" "exact Codex resume should succeed in the same endpoint"$'\n'"$out" - assert_contains "$out" "resumed rl31 session=$CODEX_SESSION_ID" \ - "the result should name the exact resumed session" + out=$(run_control "$dir" "$callsign" relaunch --resume --note "continue exact session"); rc=$? + expect_code 0 "$rc" "callsign-selected exact Codex resume should succeed in the same endpoint"$'\n'"$out" + assert_contains "$out" "resumed $callsign (rl31) session=$CODEX_SESSION_ID" \ + "the result should name the callsign, task, and exact resumed session" assert_grep "codex resume" "$dir/fake/literal" \ "the launch should use Codex's exact resume subcommand" assert_grep "$CODEX_SESSION_ID" "$dir/fake/literal" \ @@ -1004,7 +1007,7 @@ test_spawn_relaunch_without_a_harness_reuses_the_recorded_one() { out=$(run_spawn "$dir" rl21 --relaunch) [ "$(meta_field "$dir" rl21 harness)" = claude ] \ || fail "fm-spawn --relaunch without --harness must reuse the recorded harness, got '$(meta_field "$dir" rl21 harness)'" - assert_contains "$out" "spawned rl21 harness=claude" "the launch should report the recorded harness" + assert_contains "$out" "(rl21) harness=claude" "the launch should report the callsign, task id, and recorded harness" pass "fm-spawn --relaunch: with no explicit harness it reuses the task's recorded one, never the crew default" } diff --git a/tests/fm-control.test.sh b/tests/fm-control.test.sh index 0daef79c97c..f1e66d24eb5 100755 --- a/tests/fm-control.test.sh +++ b/tests/fm-control.test.sh @@ -231,7 +231,7 @@ test_exit_types_each_harness_verified_command() { IFS=$'\t' read -r expected key repeat clear <<< "$(verified_adapter_contract "$harness")" [ "$(literals "$dir")" = "$expected" ] \ || fail "exit on $harness should type exactly '$expected', got: $(literals "$dir")" - assert_contains "$out" "stopped t1 harness=$harness" "exit should report the stop for $harness" + assert_contains "$out" "(t1) harness=$harness" "exit should report the callsign and stop for $harness" done pass "fm-control exit: every verified harness gets its own verified exit command" } @@ -303,7 +303,7 @@ test_prefixed_recorded_harness_reaches_each_control_verb() { expect_code 0 "$rc" "exit should resolve a prefixed recorded harness"$'\n'"$out" [ "$(literals "$dir")" = /exit ] \ || fail "a grok-prefixed task should receive grok's exit command" - assert_contains "$out" "stopped t1 harness=grok" \ + assert_contains "$out" "(t1) harness=grok" \ "exit should report the verified adapter that supplied its mechanics" pass "fm-control: prefixed recorded harnesses reach interrupt and exit mechanics" } @@ -475,10 +475,25 @@ test_unknown_task_is_refused() { add_task "$dir" t1 claude out=$(run_control "$dir" t2 exit); rc=$? expect_code 1 "$rc" "an unknown task should refuse" - assert_contains "$out" "no task 't2'" "the refusal should name the missing task" + assert_contains "$out" "no callsign or task 't2'" "the refusal should name the missing selector" pass "fm-control: an unrecorded task id is refused" } +test_callsign_routes_to_one_exact_task() { + local dir out rc renamed + dir=$(new_case callsign) + add_task "$dir" t1 claude + renamed=$(env FM_HOME="$dir/home" "$ROOT/bin/fm-name.sh" rename t1 Hopper 2>&1) \ + || fail "assigning an explicit callsign should succeed: $renamed" + alive_as "$dir" claude + out=$(run_control "$dir" Hopper exit); rc=$? + expect_code 0 "$rc" "a callsign should route to its exact task"$'\n'"$out" + assert_contains "$out" "Hopper (t1)" "control output should lead with the callsign and retain the task id" + [ "$(literals "$dir")" = /exit ] \ + || fail "the callsign should deliver exactly one verified exit command" + pass "fm-control: a callsign routes to one exact task" +} + test_record_bound_to_another_task_is_refused() { local dir out rc dir=$(new_case foreign) @@ -597,8 +612,10 @@ test_resume_is_refused_with_its_reason() { add_task "$dir" t1 claude out=$(run_control "$dir" t1 resume); rc=$? expect_code 2 "$rc" "resume should be refused" - assert_contains "$out" "not deterministic across the verified adapters" \ - "the refusal should explain why resume is excluded" + assert_contains "$out" "resume resolved" \ + "resume refusal should prove names-first resolution happened before capability gating" + assert_contains "$out" "exact-thread resume is not installed for this task" \ + "the refusal should name the task-scoped capability boundary" assert_contains "$out" "relaunch" "the refusal should point at the deterministic alternative" pass "fm-control: resume is refused with the determinism reason and the alternative" } @@ -623,7 +640,8 @@ test_already_stopped_exit_is_idempotent() { alive_as "$dir" zsh out=$(run_control "$dir" t1 exit); rc=$? expect_code 0 "$rc" "exiting an already-stopped agent should succeed" - assert_contains "$out" "already-stopped t1" "the outcome should say it was already stopped" + assert_contains "$out" "already-stopped" "the outcome should say it was already stopped" + assert_contains "$out" "(t1)" "the already-stopped outcome should retain the exact task id" [ -z "$(literals "$dir")" ] || fail "an already-stopped agent must not be sent an exit command" pass "fm-control exit: an already-stopped agent is idempotent success with no bytes sent" } @@ -766,7 +784,7 @@ test_exit_accepts_agent_stopped_by_busy_interrupt() { printf 'busy_gen=%s\n' "$gen" >> "$dir/home/state/t1.meta" out=$(FM_FAKE_INTERRUPT_STOPS_AGENT=1 run_control "$dir" t1 exit); rc=$? expect_code 0 "$rc" "exit should accept a busy agent stopped by interrupt"$'\n'"$out" - assert_contains "$out" "stopped t1 harness=claude" \ + assert_contains "$out" "(t1) harness=claude" \ "the authoritative gone-state should complete exit successfully" [ "$(keys_sent "$dir")" = Escape ] \ || fail "exit should deliver the busy agent's interrupt sequence" @@ -884,6 +902,7 @@ test_state_verified_backends_are_exactly_tmux_and_herdr test_window_label_is_refused_with_the_exact_id test_explicit_endpoint_is_refused test_unknown_task_is_refused +test_callsign_routes_to_one_exact_task test_record_bound_to_another_task_is_refused test_remote_secondmate_is_refused_by_placement test_interrupt_and_exit_lock_before_task_state_resolution diff --git a/tests/fm-crew-state.test.sh b/tests/fm-crew-state.test.sh index 602b3e5cfc3..fa522be6218 100755 --- a/tests/fm-crew-state.test.sh +++ b/tests/fm-crew-state.test.sh @@ -18,7 +18,7 @@ # (g) no run + semantic idle falls to the status-log verb -> status-log # (h) dead pane: no run -> unknown/none; with a run -> run-step (not the shell) # (i) kind=scout skips the run lookup -> pane/status-log -# (j) torn-down worktree / missing meta -> unknown/none +# (j) torn-down worktree -> unknown/none; missing task -> refusal # (k) crew_is_provably_working end-to-end over the REAL helper (not a canned # fake fm-crew-state.sh verdict): cross-branch attribution via the runs # list -> absorbed; genuinely no run anywhere + idle pane -> surfaced. @@ -1254,11 +1254,10 @@ test_missing_meta() { local d; d=$(new_case nometa) make_fakebin "$d" >/dev/null local out rc - out=$(run_crew_state "$d" ghost-z); rc=$? - expect_code 0 "$rc" "missing meta exits 0" - assert_contains "$out" "state: unknown" "missing meta -> unknown" - assert_contains "$out" "source: none" "missing meta -> none source" - pass "missing meta is handled gracefully" + out=$(run_crew_state "$d" ghost-z 2>&1); rc=$? + expect_code 1 "$rc" "missing task refuses" + assert_contains "$out" "no callsign or task 'ghost-z' exists" "missing task refusal is explicit" + pass "missing task id or callsign refuses instead of guessing" } # (k) crew_is_provably_working end-to-end over the REAL fm-crew-state.sh (not a diff --git a/tests/fm-fleet-snapshot-view.test.sh b/tests/fm-fleet-snapshot-view.test.sh index a4dd1500834..ca81af210f3 100755 --- a/tests/fm-fleet-snapshot-view.test.sh +++ b/tests/fm-fleet-snapshot-view.test.sh @@ -571,7 +571,7 @@ EOF and .paths.report.present == true ' >/dev/null || fail "bold task did not join to override-backed backlog and report" view=$(PATH="$fakebin:$PATH" FM_HOME="$home" FM_DATA_OVERRIDE="$data" FM_PROJECTS_OVERRIDE="$projects" "$VIEW") - assert_contains "$view" "| bold-task | done / status-log | scout | alpha | tmux | present | $data/bold-task/report.md" \ + assert_contains "$view" "(bold-task) | done / status-log | scout | alpha | tmux | present | $data/bold-task/report.md" \ "view should render bold in-flight row from snapshot" assert_contains "$view" "| blocked-reason | Blocked Reason | beta | ship | queued-comma - waits on queued-comma | - |" \ "view should render blocked reason without title metadata" @@ -588,15 +588,17 @@ test_view_renders_snapshot() { write_fixture "$home" fakebin=$(make_fakebin "$home") view=$(PATH="$fakebin:$PATH" FM_HOME="$home" "$VIEW") - assert_contains "$view" "| ship-task | working / pane | ship | alpha | tmux | present | https://github.com/kunchenguid/firstmate/pull/9" \ + assert_contains "$view" "(ship-task) | working / pane | ship | alpha | tmux | present | https://github.com/kunchenguid/firstmate/pull/9" \ "view should render ship row from snapshot" assert_contains "$view" "| queued-task | Queued Task | alpha | ship | ship-task | -" \ "view should render queued backlog row" assert_contains "$view" "| done-task | Done Task | alpha | ship | - | https://github.com/kunchenguid/firstmate/pull/7 |" \ "view should render done backlog row" - assert_contains "$view" "bin/fm-send.sh fm-secondmate-task" \ - "view should show secondmate send guidance" - assert_contains "$view" "| secondmate-task | working / status-log | secondmate | $home/secondmate-home | tmux | present / alive |" \ + assert_contains "$view" "bin/fm-send.sh " \ + "view should show names-first secondmate send guidance" + assert_contains "$view" "'' - read status/doc return channel" \ + "view should retain the secondmate return-channel guidance" + assert_contains "$view" "(secondmate-task) | working / status-log | secondmate | $home/secondmate-home | tmux | present / alive |" \ "view should show secondmate endpoint agent liveness" assert_not_contains "$view" "fm-peek.sh fm-secondmate-task" \ "view must not tell firstmate to routinely peek secondmates" @@ -617,9 +619,9 @@ test_view_renders_dead_secondmate_agent_status() { printf 'working: watching delegated scope\n' > "$home/state/dead-secondmate.status" fakebin=$(make_fakebin "$home") view=$(PATH="$fakebin:$PATH" FM_HOME="$home" "$VIEW") - assert_contains "$view" "| dead-secondmate | unknown / none | secondmate | $home/secondmate-home | tmux | present / dead |" \ + assert_contains "$view" "(dead-secondmate) | unknown / none | secondmate | $home/secondmate-home | tmux | present / dead |" \ "view should distinguish a present secondmate endpoint from a dead agent" - assert_contains "$view" "| dead-secondmate | unknown / none | secondmate | $home/secondmate-home | tmux | present / dead | - | $home/secondmate-home (absent) |" \ + assert_contains "$view" "(dead-secondmate) | unknown / none | secondmate | $home/secondmate-home | tmux | present / dead | - | $home/secondmate-home (absent) |" \ "view should show a recorded missing secondmate home path" pass "fleet view renders secondmate agent liveness" } diff --git a/tests/fm-gate-refuse.test.sh b/tests/fm-gate-refuse.test.sh index 6f258ae751a..6796400ebfd 100755 --- a/tests/fm-gate-refuse.test.sh +++ b/tests/fm-gate-refuse.test.sh @@ -194,7 +194,7 @@ test_spawn_refuses_and_admits() { # no-regression: neutral cwd, marker UNSET, genuine isolated worktree. out=$(run_spawn "$NORMAL_CWD" "$home" spawn-ok "$proj" "$wt" "$fakebin"); rc=$? expect_code 0 "$rc" "spawn: a normal session must still spawn" - assert_contains "$out" "spawned spawn-ok" "spawn: normal launch should report success" + assert_contains "$out" "(spawn-ok)" "spawn: normal launch should report success" assert_not_contains "$out" "$ENV_MSG" "spawn: normal launch must not print the gate refusal" assert_not_contains "$out" "$PATH_MSG" "spawn: normal launch must not print the backstop refusal" assert_present "$home/state/spawn-ok.meta" "spawn: normal launch should record meta" diff --git a/tests/fm-grok-harness.test.sh b/tests/fm-grok-harness.test.sh index 957c0f1c772..9b4bd071ab6 100755 --- a/tests/fm-grok-harness.test.sh +++ b/tests/fm-grok-harness.test.sh @@ -65,7 +65,7 @@ EOF out=$(run_grok_spawn "$home" "$proj" "$wt" "$fakebin" "$grok_home" "$id") status=$? expect_code 0 "$status" "grok spawn should succeed" - assert_contains "$out" "spawned $id harness=grok" "grok spawn did not report success" + assert_contains "$out" "($id) harness=grok" "grok spawn did not report success" hook="$grok_home/hooks/fm-turn-end.sh" assert_present "$hook" "grok hook script was not installed" diff --git a/tests/fm-identity.test.sh b/tests/fm-identity.test.sh new file mode 100755 index 00000000000..b424b69c99b --- /dev/null +++ b/tests/fm-identity.test.sh @@ -0,0 +1,237 @@ +#!/usr/bin/env bash +# Focused behavior contract for persistent home/task names. Exercises the shared +# public identity library plus the operator-facing fm-name/fm-send surfaces over +# private tmux- and Herdr-shaped task records. No live backend is contacted. +set -eu + +# shellcheck source=tests/lib.sh +. "$(dirname "${BASH_SOURCE[0]}")/lib.sh" + +TMP_ROOT=$(fm_test_tmproot fm-identity) +HOME_DIR="$TMP_ROOT/home" +STATE="$HOME_DIR/state" +DATA="$HOME_DIR/data" +WT="$TMP_ROOT/worktree" +FAKEBIN="$TMP_ROOT/fakebin" +SEND_LOG="$TMP_ROOT/send.log" +mkdir -p "$STATE" "$DATA" "$WT" "$FAKEBIN" +trap 'rm -rf "$TMP_ROOT"' EXIT + +export FM_HOME="$HOME_DIR" +export FM_ROOT_OVERRIDE="$ROOT" +export FM_STATE_OVERRIDE="$STATE" +export FM_DATA_OVERRIDE="$DATA" + +# shellcheck source=bin/fm-backend.sh +. "$ROOT/bin/fm-backend.sh" +# shellcheck source=bin/fm-identity-lib.sh +. "$ROOT/bin/fm-identity-lib.sh" + +fail() { printf 'not ok - %s\n' "$*" >&2; exit 1; } +pass() { printf 'ok - %s\n' "$*"; } +field() { fm_identity_record_value "$1" "$2"; } + +write_tmux_meta() { # [thread] + local id=$1 target=$2 thread=${3:-} + { + printf 'window=%s\n' "$target" + printf 'worktree=%s\n' "$WT" + printf 'project=%s\n' "$TMP_ROOT/project" + printf 'harness=codex\nkind=ship\n' + printf 'spawn_gen=gen-%s\n' "$id" + [ -z "$thread" ] || printf 'codex_session_id=%s\n' "$thread" + } > "$STATE/$id.meta" +} + +write_herdr_meta() { # [thread] + local id=$1 target=$2 thread=${3:-} + { + printf 'window=%s\n' "$target" + printf 'terminal=%s\n' "$target" + printf 'worktree=%s\n' "$WT" + printf 'project=%s\n' "$TMP_ROOT/project" + printf 'harness=codex\nkind=ship\nbackend=herdr\n' + printf 'endpoint_task_id=%s\n' "$id" + printf 'spawn_gen=gen-%s\n' "$id" + printf 'herdr_session=%s\n' "${target%%:*}" + printf 'herdr_workspace_id=workspace-%s\n' "$id" + printf 'herdr_tab_id=tab-%s\n' "$id" + printf 'herdr_pane_id=%s\n' "${target#*:}" + [ -z "$thread" ] || printf 'codex_session_id=%s\n' "$thread" + } > "$STATE/$id.meta" +} + +HOME_NAME=$(fm_identity_ensure_home) +[ -n "$HOME_NAME" ] || fail "home name was not assigned" +[ "$(fm_identity_ensure_home)" = "$HOME_NAME" ] || fail "home name changed across reads" +[ "$(field "$DATA/firstmate.identity" home)" = "$(cd "$HOME_DIR" && pwd -P)" ] \ + || fail "home identity did not bind the canonical Firstmate home" +pass "one deterministic human name persists for the Firstmate home" + +CALL_A=$(fm_identity_reserve_fresh_task task-a) +write_tmux_meta task-a fm-home:fm-task-a thread-a +[ "$(fm_identity_ensure_task_from_meta "$STATE/task-a.meta" task-a)" = "$CALL_A" ] \ + || fail "tmux activation changed the reserved callsign" +REC_A=$(fm_identity_task_record task-a) +[ "$(field "$REC_A" task_id)" = task-a ] || fail "task id binding missing" +[ "$(field "$REC_A" home)" = "$(cd "$HOME_DIR" && pwd -P)" ] || fail "home binding missing" +[ "$(field "$REC_A" worktree)" = "$(cd "$WT" && pwd -P)" ] || fail "canonical worktree binding missing" +[ "$(field "$REC_A" backend)" = tmux ] || fail "tmux backend binding missing" +[ "$(field "$REC_A" endpoint)" = fm-home:fm-task-a ] || fail "tmux endpoint binding missing" +[ "$(field "$REC_A" endpoint_session_id)" = fm-home ] || fail "tmux session binding missing" +[ "$(field "$REC_A" harness_session_id)" = thread-a ] || fail "exact harness thread binding missing" +[ "$(field "$REC_A" spawn_gen)" = gen-task-a ] || fail "spawn incarnation binding missing" +pass "fresh tmux task publishes its full one-to-one identity binding" + +CALL_B=$(fm_identity_reserve_fresh_task task-b) +[ "$CALL_A" != "$CALL_B" ] || fail "fresh tasks received the same callsign" +write_herdr_meta task-b fm-lab:pane-b +[ "$(fm_identity_ensure_task_from_meta "$STATE/task-b.meta" task-b)" = "$CALL_B" ] \ + || fail "Herdr activation changed the reserved callsign" +REC_B=$(fm_identity_task_record task-b) +[ "$(field "$REC_B" backend)" = herdr ] || fail "Herdr backend binding missing" +[ "$(field "$REC_B" endpoint)" = fm-lab:pane-b ] || fail "Herdr endpoint binding missing" +[ "$(field "$REC_B" endpoint_session_id)" = fm-lab ] || fail "Herdr session binding missing" +pass "automatic callsigns are unique and backend-neutral" + +RENAMED_HOME=$(FM_HOME="$HOME_DIR" "$ROOT/bin/fm-name.sh" rename-home Harbor) +[ "$RENAMED_HOME" = "Harbor (Firstmate home)" ] || fail "home rename was not persisted names-first" +[ "$(field "$DATA/firstmate.identity" name)" = Harbor ] || fail "home rename did not update the durable record" +if FM_HOME="$HOME_DIR" "$ROOT/bin/fm-name.sh" rename "$CALL_B" Harbor >/dev/null 2>&1; then + fail "task rename collided with the Firstmate home name" +fi +pass "explicit Firstmate-home rename shares collision-safe history with task callsigns" + +EXPLICIT_A=Hopper +[ "$CALL_A" != Hopper ] || EXPLICIT_A=HopperOne +NAME_OUT=$(FM_HOME="$HOME_DIR" "$ROOT/bin/fm-name.sh" rename "$CALL_A" "$EXPLICIT_A") +[ "$NAME_OUT" = "$EXPLICIT_A (task-a)" ] || fail "rename was not names-first: $NAME_OUT" +[ "$(FM_HOME="$HOME_DIR" "$ROOT/bin/fm-name.sh" resolve "$(fm_identity_fold "$EXPLICIT_A")")" = "$EXPLICIT_A (task-a)" ] \ + || fail "case-insensitive callsign resolution failed" +if FM_HOME="$HOME_DIR" "$ROOT/bin/fm-name.sh" rename "$CALL_B" "$EXPLICIT_A" >/dev/null 2>&1; then + fail "rename silently collided with an active callsign" +fi +if FM_HOME="$HOME_DIR" "$ROOT/bin/fm-name.sh" rename "$CALL_B" captain >/dev/null 2>&1; then + fail "rename accepted a reserved name" +fi +if FM_HOME="$HOME_DIR" "$ROOT/bin/fm-name.sh" rename "$CALL_B" task-a >/dev/null 2>&1; then + fail "rename collided with an existing task id" +fi +if fm_identity_reserve_fresh_task "$(printf '%s' "$EXPLICIT_A" | tr '[:upper:]' '[:lower:]')" >/dev/null 2>&1; then + fail "fresh task id collided with an existing callsign" +fi +if FM_HOME="$HOME_DIR" "$ROOT/bin/fm-name.sh" resolve "$CALL_A" >/dev/null 2>&1; then + fail "retired callsign remained routable after rename" +fi +pass "explicit rename validates active, task-id, reserved, and historical collisions" + +CASE_ONLY=$(printf '%s' "$EXPLICIT_A" | tr '[:upper:]' '[:lower:]') +NAME_OUT=$(FM_HOME="$HOME_DIR" "$ROOT/bin/fm-name.sh" rename "$EXPLICIT_A" "$CASE_ONLY") +[ "$NAME_OUT" = "$CASE_ONLY (task-a)" ] || fail "case-only rename did not report the persisted spelling" +[ "$(field "$REC_A" callsign)" = "$CASE_ONLY" ] || fail "case-only rename was not persisted" +EXPLICIT_A=$CASE_ONLY +pass "case-only rename persists the requested spelling" + +# Process/pane loss does not mutate identity. A replacement endpoint and exact +# thread resume update the binding in place without changing the callsign. +[ "$(fm_identity_resolve_selector "$STATE" "$EXPLICIT_A")" = task-a ] || fail "callsign vanished after simulated process exit" +write_tmux_meta task-a fm-home-restarted:fm-task-a thread-a +[ "$(fm_identity_ensure_task_from_meta "$STATE/task-a.meta" task-a rebind)" = "$EXPLICIT_A" ] \ + || fail "tmux restart changed the callsign" +[ "$(field "$REC_A" endpoint)" = fm-home-restarted:fm-task-a ] || fail "relaunch endpoint was not updated" +[ "$(field "$REC_A" harness_session_id)" = thread-a ] || fail "exact-thread resume id was not preserved" +write_herdr_meta task-b fm-lab:pane-b-restarted thread-b +[ "$(fm_identity_ensure_task_from_meta "$STATE/task-b.meta" task-b rebind)" = "$CALL_B" ] \ + || fail "Herdr restart changed the callsign" +[ "$(field "$REC_B" endpoint)" = fm-lab:pane-b-restarted ] || fail "Herdr replacement endpoint was not updated" +[ "$(field "$REC_B" harness_session_id)" = thread-b ] || fail "Herdr exact-thread id was not recorded" +pass "tmux/Herdr restart, relaunch, and exact-thread resume preserve callsigns" + +CALL_C=$(fm_identity_reserve_fresh_task task-c) +[ "$CALL_C" != "$EXPLICIT_A" ] && [ "$CALL_C" != "$CALL_B" ] || fail "fresh task reused a current callsign" +pass "fresh tasks remain distinct from resumed tasks" + +# Direct names-first follow-up routing reaches the exact bound tmux endpoint. +cat > "$FAKEBIN/tmux" <<'SH' +#!/usr/bin/env bash +set -u +case "${1:-}" in + display-message) + case "$*" in *cursor_y*) printf '1\n' ;; *) printf '%%identity-pane\n' ;; esac ;; + capture-pane) printf '╭────╮\n│ │\n╰────╯\n' ;; + send-keys) printf '%s\n' "$*" >> "$FM_IDENTITY_SEND_LOG" ;; +esac +SH +chmod +x "$FAKEBIN/tmux" +: > "$SEND_LOG" +FM_IDENTITY_SEND_LOG="$SEND_LOG" PATH="$FAKEBIN:$PATH" \ + FM_SEND_SETTLE=0 FM_HOME="$HOME_DIR" "$ROOT/bin/fm-send.sh" "$EXPLICIT_A" "status please" >/dev/null \ + || fail "names-first direct follow-up routing failed" +grep -q 'fm-home-restarted:fm-task-a' "$SEND_LOG" || fail "callsign follow-up did not route to the exact bound endpoint" +pass "names-first follow-up routes to exactly one task" + +# Conflicting session identities fail closed without replacing the good record. +cp "$REC_A" "$TMP_ROOT/record-before-conflict" +cat >> "$STATE/task-a.meta" <<'EOF' +thread_id=thread-conflict +EOF +if fm_identity_ensure_task_from_meta "$STATE/task-a.meta" task-a rebind >/dev/null 2>&1; then + fail "conflicting exact-thread identifiers were accepted" +fi +cmp -s "$REC_A" "$TMP_ROOT/record-before-conflict" || fail "failed relaunch rewrote the prior identity" +write_tmux_meta task-a fm-home-restarted:fm-task-a thread-a +pass "conflicting or unsafe relaunch identity refuses without rebinding" + +write_tmux_meta unsafe-legacy fm-home:fm-other +if fm_identity_ensure_task_from_meta "$STATE/unsafe-legacy.meta" unsafe-legacy legacy >/dev/null 2>&1; then + fail "legacy identity activation accepted another task's tmux endpoint" +fi +[ ! -e "$(fm_identity_task_record unsafe-legacy)" ] || fail "unsafe legacy activation published an identity record" +rm -f "$STATE/unsafe-legacy.meta" +pass "legacy activation validates endpoint ownership before publishing a callsign" + +fm_identity_archive_task "$STATE/task-b.meta" task-b >/dev/null +rm -f "$STATE/task-b.meta" +if fm_identity_resolve_selector "$STATE" "$CALL_B" >/dev/null 2>&1; then + fail "archived-only callsign resolved as live" +fi +FM_HOME="$HOME_DIR" "$ROOT/bin/fm-name.sh" history | grep -q "^$CALL_B (task-b) archived$" \ + || fail "cleanup history omitted archived names-first identity" +if fm_identity_reserve_fresh_task task-b >/dev/null 2>&1; then + fail "archived task id was silently rebound" +fi +pass "cleanup retains history and active/historical callsigns never silently rebind" + +# Migration gives complete legacy tasks active fallback bindings, incomplete +# records provisioning fallbacks, and status-only history archived tombstones. +write_tmux_meta legacy-live fm-home:fm-legacy-live +printf 'kind=ship\n' > "$STATE/legacy-incomplete.meta" +printf 'done: old task\n' > "$STATE/legacy-gone.status" +fm_identity_migrate_home +LEGACY_LIVE=$(fm_identity_display_callsign legacy-live) +case "$LEGACY_LIVE" in *-L[0-9]*) : ;; *) fail "legacy task did not receive deterministic fallback: $LEGACY_LIVE" ;; esac +[ "$(field "$(fm_identity_task_record legacy-live)" status)" = active ] || fail "complete legacy task was not activated" +[ "$(field "$(fm_identity_task_record legacy-incomplete)" status)" = provisioning ] || fail "incomplete legacy task was guessed active" +[ "$(field "$(fm_identity_task_record legacy-gone)" status)" = archived ] || fail "legacy history did not migrate to a tombstone" +LEGACY_RENAMED=$(FM_HOME="$HOME_DIR" "$ROOT/bin/fm-name.sh" rename legacy-live LegacyOne) +[ "$LEGACY_RENAMED" = "LegacyOne (legacy-live)" ] || fail "migrated legacy task could not be explicitly renamed" +pass "legacy unnamed tasks migrate deterministically and support explicit rename without endpoint guesses" + +# Deliberately corrupt two private fixtures to prove ambiguous and task-id/name +# conflicts refuse; restore them immediately so later history stays valid. +cp "$REC_B" "$TMP_ROOT/record-b-safe" +sed "s/^callsign=.*/callsign=$EXPLICIT_A/" "$REC_B" > "$REC_B.tmp" && mv "$REC_B.tmp" "$REC_B" +if fm_identity_resolve_selector "$STATE" "$EXPLICIT_A" >/dev/null 2>&1; then + fail "ambiguous duplicate callsign was guessed" +fi +cp "$TMP_ROOT/record-b-safe" "$REC_B" +cp "$(fm_identity_task_record legacy-live)" "$TMP_ROOT/legacy-safe" +sed 's/^callsign=.*/callsign=task-a/' "$(fm_identity_task_record legacy-live)" > "$TMP_ROOT/legacy-conflict" +cp "$TMP_ROOT/legacy-conflict" "$(fm_identity_task_record legacy-live)" +if fm_identity_resolve_selector "$STATE" task-a >/dev/null 2>&1; then + fail "task-id/current-name conflict was guessed" +fi +cp "$TMP_ROOT/legacy-safe" "$(fm_identity_task_record legacy-live)" +pass "missing, ambiguous, archived-only, conflicting, and unsafe selectors fail closed" + +printf 'ok - persistent human identity behavior\n' diff --git a/tests/fm-kimi-harness.test.sh b/tests/fm-kimi-harness.test.sh index 768ee79991e..7b7595bb7e6 100755 --- a/tests/fm-kimi-harness.test.sh +++ b/tests/fm-kimi-harness.test.sh @@ -195,7 +195,7 @@ test_kimi_launch_then_send_is_verified() { --model kimi-code/k3 --effort high) rc=$? expect_code 0 "$rc" "verified kimi launch-then-send should succeed" - assert_contains "$out" "spawned $id harness=kimi" "kimi spawn did not report success" + assert_contains "$out" "($id) harness=kimi" "kimi spawn did not report success" launch=$(cat "$CASE_DIR/launch.log") [ "$launch" = "env -u CURSOR_AGENT -u CURSOR_INVOKED_AS '$FAKEBIN_DIR/kimi' --model 'kimi-code/k3' --auto" ] \ diff --git a/tests/fm-muse-harness.test.sh b/tests/fm-muse-harness.test.sh index 83a0747458b..fd68df1690f 100755 --- a/tests/fm-muse-harness.test.sh +++ b/tests/fm-muse-harness.test.sh @@ -229,7 +229,7 @@ EOF out=$(run_muse_spawn "$home" "$proj" "$wt" "$fakebin" "$id" --mode no-mistakes --yolo off) status=$? expect_code 0 "$status" "muse spawn should succeed" - assert_contains "$out" "spawned $id harness=muse" "muse spawn did not report success" + assert_contains "$out" "($id) harness=muse" "muse spawn did not report success" launch=$(cat "$home/launch.log") # --yolo is what makes a crewmate pane viable at all: without it muse holds diff --git a/tests/fm-send-strict.test.sh b/tests/fm-send-strict.test.sh index 0634dd9e0d9..7cc380b7c3b 100755 --- a/tests/fm-send-strict.test.sh +++ b/tests/fm-send-strict.test.sh @@ -127,9 +127,7 @@ test_unresolvable_target_does_not_tmux_fallback() { PATH="$fb:$PATH" FM_HOME="$home" FM_ROOT_OVERRIDE="$home" FM_TMUX_LOG="$log" FM_FAKE_TMUX_WINDOW=lost-target FM_SEND_SETTLE=0 \ "$SEND" lost-target "hello" >/dev/null 2>"$err"; rc=$? [ "$rc" -ne 0 ] || fail "unresolvable target should fail" - assert_contains "$(cat "$err")" "not resolvable" "unresolvable diagnostic should be loud" - assert_contains "$(cat "$err")" "metadata window/terminal lookup" "unresolvable diagnostic should name the attempted lookup" - assert_contains "$(cat "$err")" "backend=none" "unresolvable diagnostic should name that no backend was assumed" + assert_contains "$(cat "$err")" "no callsign or task 'lost-target'" "unresolvable diagnostic should be names-first and loud" [ ! -s "$log" ] || fail "unresolvable target fell through to tmux send"$'\n'"$(cat "$log")" pass "fm-send strict: unresolvable selectors do not fall back to tmux" } diff --git a/tests/fm-session-start.test.sh b/tests/fm-session-start.test.sh index 9f1cedbc6ec..946e5881e80 100755 --- a/tests/fm-session-start.test.sh +++ b/tests/fm-session-start.test.sh @@ -961,7 +961,7 @@ EOF context_line=$(printf '%s\n' "$out" | grep -n '^CONTEXT$' | head -1 | cut -d: -f1) fleet_line=$(printf '%s\n' "$out" | grep -n '^FLEET STATE$' | head -1 | cut -d: -f1) next_line=$(printf '%s\n' "$out" | grep -n '^NEXT STEP$' | head -1 | cut -d: -f1) - inventory_line=$(printf '%s\n' "$out" | grep -n '^--- task-a ---$' | head -1 | cut -d: -f1) + inventory_line=$(printf '%s\n' "$out" | grep -n '^--- [A-Za-z][A-Za-z0-9-]* (task-a) ---$' | head -1 | cut -d: -f1) if [ -z "$lock_line" ] || [ -z "$boot_line" ] || [ -z "$wake_line" ] \ || [ -z "$read_once_line" ] || [ -z "$context_line" ] || [ -z "$fleet_line" ] \ diff --git a/tests/fm-spawn-dispatch-profile.test.sh b/tests/fm-spawn-dispatch-profile.test.sh index d1f1effb41a..70a2065d5f9 100755 --- a/tests/fm-spawn-dispatch-profile.test.sh +++ b/tests/fm-spawn-dispatch-profile.test.sh @@ -161,7 +161,7 @@ test_no_profile_keeps_claude_profile_defaults() { out=$(run_ship_spawn "$HOME_DIR" "$WT_DIR" "$FAKEBIN_DIR" "$LAUNCH_LOG" "$id" "$PROJ_DIR") status=$? expect_code 0 "$status" "claude spawn without profile flags should succeed" - assert_contains "$out" "spawned $id harness=claude" "spawn did not report claude" + assert_contains "$out" "($id) harness=claude" "spawn did not report claude beside its callsign binding" assert_meta_profile "$HOME_DIR/state/$id.meta" claude default default launch=$(cat "$LAUNCH_LOG") @@ -376,7 +376,7 @@ test_active_dispatch_profile_allows_explicit_harness() { "$id" "$PROJ_DIR" --harness codex --model gpt-5 --effort high) status=$? expect_code 0 "$status" "explicit harness should satisfy active dispatch-profile requirement" - assert_contains "$out" "spawned $id harness=codex" "spawn did not report explicit codex harness" + assert_contains "$out" "($id) harness=codex" "spawn did not report explicit codex harness" assert_meta_profile "$HOME_DIR/state/$id.meta" codex gpt-5 high launch=$(cat "$LAUNCH_LOG") assert_contains "$launch" "codex --model 'gpt-5' -c 'model_reasoning_effort=\"high\"' --dangerously-bypass-approvals-and-sandbox" \ @@ -395,7 +395,7 @@ test_active_dispatch_profile_allows_positional_harness() { "$id" "$PROJ_DIR" codex --model gpt-5 --effort high) status=$? expect_code 0 "$status" "positional harness should satisfy active dispatch-profile requirement" - assert_contains "$out" "spawned $id harness=codex" "spawn did not report positional codex harness" + assert_contains "$out" "($id) harness=codex" "spawn did not report positional codex harness" assert_meta_profile "$HOME_DIR/state/$id.meta" codex gpt-5 high pass "active crew-dispatch profile allows the legacy positional harness form" } @@ -411,7 +411,7 @@ test_active_dispatch_profile_allows_raw_launch_command() { "$id" "$PROJ_DIR" "custom-agent --flag") status=$? expect_code 0 "$status" "raw launch command should satisfy active dispatch-profile requirement" - assert_contains "$out" "spawned $id harness=custom-agent" "spawn did not report raw command harness" + assert_contains "$out" "($id) harness=custom-agent" "spawn did not report raw command harness" assert_meta_profile "$HOME_DIR/state/$id.meta" custom-agent default default launch=$(cat "$LAUNCH_LOG") [ "$launch" = "custom-agent --flag" ] || fail "raw launch command changed"$'\n'"actual: $launch" @@ -642,7 +642,7 @@ test_pi_signed_threads_shared_pi_profile_and_preserves_identity() { --model openai-codex/gpt-5.6-sol --effort max) status=$? expect_code 0 "$status" "pi-signed spawn with max effort should succeed" - assert_contains "$out" "spawned $id harness=pi-signed" "pi-signed spawn did not preserve its visible identity" + assert_contains "$out" "($id) harness=pi-signed" "pi-signed spawn did not preserve its visible identity" assert_meta_profile "$HOME_DIR/state/$id.meta" pi-signed openai-codex/gpt-5.6-sol max launch=$(cat "$LAUNCH_LOG") assert_contains "$launch" "FM_PI_HARNESS=pi-signed '$FAKEBIN_DIR/pi-signed' --tui-mode regular --model 'openai-codex/gpt-5.6-sol' --thinking 'max' -e" \ @@ -731,7 +731,7 @@ test_pi_signed_persistent_secondmate_uses_pi_extensions_and_identity() { out=$(run_spawn "$HOME_DIR" "$WT_DIR" "$FAKEBIN_DIR" "$LAUNCH_LOG" "$id" "$sm" --secondmate) status=$? expect_code 0 "$status" "pi-signed persistent secondmate spawn should succeed" - assert_contains "$out" "spawned $id harness=pi-signed kind=secondmate" \ + assert_contains "$out" "($id) harness=pi-signed kind=secondmate" \ "pi-signed secondmate spawn did not preserve its runtime identity" assert_meta_profile "$HOME_DIR/state/$id.meta" pi-signed default default launch=$(cat "$LAUNCH_LOG") @@ -752,8 +752,8 @@ test_batch_forwards_shared_profile_flags() { "$id1=$PROJ_DIR" "$id2=$PROJ_DIR" --harness codex --model gpt-5 --effort high) status=$? expect_code 0 "$status" "batch spawn with shared profile flags should succeed" - assert_contains "$out" "spawned $id1 harness=codex" "first batch task did not use shared harness" - assert_contains "$out" "spawned $id2 harness=codex" "second batch task did not use shared harness" + assert_contains "$out" "($id1) harness=codex" "first batch task did not use shared harness" + assert_contains "$out" "($id2) harness=codex" "second batch task did not use shared harness" assert_meta_profile "$HOME_DIR/state/$id1.meta" codex gpt-5 high assert_meta_profile "$HOME_DIR/state/$id2.meta" codex gpt-5 high pass "batch dispatch forwards shared --harness, --model, and --effort to every pair" @@ -820,7 +820,7 @@ test_active_dispatch_profile_does_not_block_secondmate_launch() { out=$(run_spawn "$HOME_DIR" "$WT_DIR" "$FAKEBIN_DIR" "$LAUNCH_LOG" "$id" "$sm" --secondmate) status=$? expect_code 0 "$status" "secondmate spawn should be exempt from the dispatch-profile explicit harness requirement" - assert_contains "$out" "spawned $id harness=codex kind=secondmate" "secondmate launch did not use secondmate harness resolution" + assert_contains "$out" "($id) harness=codex kind=secondmate" "secondmate launch did not use secondmate harness resolution" assert_grep "kind=secondmate" "$HOME_DIR/state/$id.meta" "secondmate meta missing kind=secondmate" assert_meta_profile "$HOME_DIR/state/$id.meta" codex default default pass "active crew-dispatch profile does not block secondmate launches" diff --git a/tests/fm-spawn-pool-base-freshen.test.sh b/tests/fm-spawn-pool-base-freshen.test.sh index 8827e679d6f..e7c0ec68925 100755 --- a/tests/fm-spawn-pool-base-freshen.test.sh +++ b/tests/fm-spawn-pool-base-freshen.test.sh @@ -85,7 +85,7 @@ run_spawn() { } test_stale_pool_base_refreshes_before_branching() { - local rec id out status current branch_head + local rec id out status current branch_head identity callsign first_callsign id='pool-current-base-r1' rec=$(make_case current-base "$id") read_case_record "$rec" @@ -93,7 +93,17 @@ test_stale_pool_base_refreshes_before_branching() { out=$(run_spawn "$id" --mode no-mistakes --yolo off) status=$? expect_code 0 "$status" "spawn should refresh a stale pooled worktree" - assert_contains "$out" "spawned $id" "spawn did not report success" + assert_contains "$out" "($id)" "spawn did not report its callsign beside the task id" + identity="$HOME_DIR/data/crew-identities/$id.identity" + [ -f "$identity" ] || fail "fresh spawn did not persist its required callsign binding" + [ "$(sed -n 's/^task_id=//p' "$identity")" = "$id" ] || fail "spawn identity lost its exact task id" + [ "$(sed -n 's/^status=//p' "$identity")" = active ] || fail "spawn identity was not activated before launch" + [ "$(sed -n 's/^worktree=//p' "$identity")" = "$(cd "$POOL_DIR" && pwd -P)" ] \ + || fail "spawn identity did not bind the canonical worktree" + callsign=$(sed -n 's/^callsign=//p' "$identity") + [ -n "$callsign" ] && assert_contains "$out" "$callsign ($id)" \ + "spawn result was not names-first" + first_callsign=$callsign current=$(git -C "$POOL_DIR" rev-parse origin/main) branch_head=$(git -C "$POOL_DIR" rev-parse HEAD) [ "$branch_head" = "$current" ] || fail "spawn left the pooled worktree on stale history" @@ -110,6 +120,10 @@ test_stale_pool_base_refreshes_before_branching() { out=$(run_spawn "$id" --mode no-mistakes --yolo off) status=$? expect_code 0 "$status" "repeating the base refresh should be idempotent" + identity="$HOME_DIR/data/crew-identities/$id.identity" + callsign=$(sed -n 's/^callsign=//p' "$identity") + [ -n "$callsign" ] && [ "$callsign" != "$first_callsign" ] \ + || fail "two fresh spawns in one home did not receive unique callsigns" [ "$(git -C "$POOL_DIR" rev-parse HEAD)" = "$current" ] \ || fail "an idempotent repeat moved the pool away from current origin/main" diff --git a/tests/fm-spawn-worktree-settle.test.sh b/tests/fm-spawn-worktree-settle.test.sh index 66f3c837aff..90da90cf7cb 100755 --- a/tests/fm-spawn-worktree-settle.test.sh +++ b/tests/fm-spawn-worktree-settle.test.sh @@ -112,7 +112,7 @@ test_single_stale_first_read_is_not_accepted() { out=$(run_settle_spawn "$id") status=$? expect_code 0 "$status" "spawn should succeed once the pane settles" - assert_contains "$out" "spawned $id" "spawn did not report success" + assert_contains "$out" "($id) harness=codex" "spawn did not report its callsign beside the task id" assert_grep "worktree=$WT_DIR" "$HOME_DIR/state/$id.meta" \ "meta did not record the settled worktree" assert_no_grep "worktree=$STALE_DIR" "$HOME_DIR/state/$id.meta" \ @@ -124,20 +124,18 @@ test_single_stale_first_read_is_not_accepted() { # costs the loop's existing one-second inter-poll sleep to confirm - not an # extra full cycle on top of that. test_already_settled_pane_costs_one_confirm_sleep() { - local rec id out status start end elapsed + local rec id out status reads id=settle-already-settled-z2 rec=$(make_settle_case settle-already-settled "$id" 0) read_settle_record "$rec" - start=$(date +%s) out=$(run_settle_spawn "$id") status=$? - end=$(date +%s) - elapsed=$((end - start)) expect_code 0 "$status" "spawn should succeed when the pane is already settled" assert_grep "worktree=$WT_DIR" "$HOME_DIR/state/$id.meta" \ "meta did not record the already-settled worktree" - [ "$elapsed" -le 5 ] || fail "already-settled pane took ${elapsed}s to confirm - expected close to the single inter-poll sleep" + reads=$(cat "$COUNTFILE") + [ "$reads" -eq 2 ] || fail "already-settled pane took $reads polls to confirm - expected the initial read plus one confirmation read" pass "an already-settled pane confirms via the existing inter-poll sleep, not an extra full cycle" } diff --git a/tests/fm-tangle-guard.test.sh b/tests/fm-tangle-guard.test.sh index 64aabe6400e..64e886bd92f 100755 --- a/tests/fm-tangle-guard.test.sh +++ b/tests/fm-tangle-guard.test.sh @@ -210,7 +210,7 @@ test_spawn_isolation_abort() { # Proceed: the pane resolves to a genuine, isolated worktree. out=$(run_spawn "$home" ok-isolated-ff6 "$proj" "$TMP_ROOT/spawn-wt" "$fakebin"); status=$? expect_code 0 "$status" "spawn into a genuine isolated worktree should succeed" - assert_contains "$out" "spawned ok-isolated-ff6" "isolated spawn did not report success" + assert_contains "$out" "(ok-isolated-ff6)" "isolated spawn did not report success" assert_not_contains "$out" "did not yield an isolated worktree" "isolated spawn wrongly tripped the guard" pass "fm-spawn: aborts unless the resolved worktree is a genuine, isolated worktree" } @@ -279,7 +279,7 @@ test_spawn_tmux_window_construction() { out=$(run_spawn_record "$home" rec-win-gg7 "$proj" "$wt" "$fakebin" "$rec"); status=$? expect_code 0 "$status" "spawn into a genuine worktree should succeed" - assert_contains "$out" "spawned rec-win-gg7" "recording spawn did not report success" + assert_contains "$out" "(rec-win-gg7)" "recording spawn did not report success" # Bug 1 fix: append-form window creation (trailing colon on the session target). assert_grep "new-window -dP -F #{window_id} -t firstmate: -n fm-rec-win-gg7" "$rec" \ diff --git a/tests/fm-teardown.test.sh b/tests/fm-teardown.test.sh index ea054654ab4..cbd0da1c6d8 100755 --- a/tests/fm-teardown.test.sh +++ b/tests/fm-teardown.test.sh @@ -1535,7 +1535,7 @@ SH if [ "$(git -C "$case_dir/wt" rev-parse --abbrev-ref HEAD 2>/dev/null)" != "fm/task-x1" ]; then : > "$release"; fail "herdr-orphan-refusal: the contended refusal dropped the task branch before refusing" fi - if grep -q "teardown task-x1 complete" "$case_dir/stdout"; then + if grep -q "(task-x1) complete" "$case_dir/stdout"; then : > "$release"; fail "herdr-orphan-refusal: refusal still reported cleanup complete" fi if grep -q "^pane close" "$log"; then @@ -1551,7 +1551,7 @@ SH [ -s "$thlog" ] || fail "herdr-orphan-refusal: the successful retry never returned the isolated copy" [ ! -e "$case_dir/state/task-x1.meta" ] || fail "herdr-orphan-refusal: the successful retry left the metadata behind" [ ! -e "$case_dir/state/task-x1.status" ] || fail "herdr-orphan-refusal: the successful retry left the status record behind" - grep -q "teardown task-x1 complete" "$case_dir/stdout2" \ + grep -q "(task-x1) complete" "$case_dir/stdout2" \ || fail "herdr-orphan-refusal: the successful retry did not report completion" pass "herdr flat teardown refuses before returning the isolated copy under lock contention and the retry completes cleanly" } diff --git a/tests/fm-trace-context-spawn.test.sh b/tests/fm-trace-context-spawn.test.sh index 61c88dc3b64..0b7164e1b99 100755 --- a/tests/fm-trace-context-spawn.test.sh +++ b/tests/fm-trace-context-spawn.test.sh @@ -244,7 +244,7 @@ test_enabled_records_and_injects_identical_carrier_before_launch() { out=$(run_spawn "$HOME_DIR" "$WT_DIR" "$FAKEBIN_DIR" "$LAUNCH_LOG" "$CASE_ID" "$PROJ_DIR") status=$? expect_code 0 "$status" "enabled trace-context spawn should succeed" - assert_contains "$out" "spawned $CASE_ID" "enabled spawn should report success" + assert_contains "$out" "($CASE_ID)" "enabled spawn should report success" meta="$HOME_DIR/state/$CASE_ID.meta" mtp=$(meta_traceparent "$meta") @@ -271,7 +271,7 @@ test_disabled_writes_and_injects_neither() { out=$(run_spawn "$HOME_DIR" "$WT_DIR" "$FAKEBIN_DIR" "$LAUNCH_LOG" "$CASE_ID" "$PROJ_DIR") status=$? expect_code 0 "$status" "default-off spawn should succeed" - assert_contains "$out" "spawned $CASE_ID" "default-off spawn should report success" + assert_contains "$out" "($CASE_ID)" "default-off spawn should report success" meta="$HOME_DIR/state/$CASE_ID.meta" # Anchored regex checks (the assert_grep helpers are fixed-string). @@ -292,7 +292,7 @@ test_failed_delivery_omits_metadata_and_still_launches() { run_spawn "$HOME_DIR" "$WT_DIR" "$FAKEBIN_DIR" "$LAUNCH_LOG" "$CASE_ID" "$PROJ_DIR") status=$? expect_code 0 "$status" "failed traceparent delivery must not abort spawn" - assert_contains "$out" "spawned $CASE_ID" "spawn should report success after failed traceparent delivery" + assert_contains "$out" "($CASE_ID)" "spawn should report success after failed traceparent delivery" meta="$HOME_DIR/state/$CASE_ID.meta" ! grep -q '^traceparent=' "$meta" \ @@ -332,7 +332,7 @@ test_failed_metadata_append_unsets_carrier_and_still_launches() { run_spawn "$HOME_DIR" "$WT_DIR" "$FAKEBIN_DIR" "$LAUNCH_LOG" "$CASE_ID" "$PROJ_DIR") status=$? expect_code 0 "$status" "failed traceparent metadata append must not abort spawn" - assert_contains "$out" "spawned $CASE_ID" "spawn should report success after failed metadata append" + assert_contains "$out" "($CASE_ID)" "spawn should report success after failed metadata append" meta="$HOME_DIR/state/$CASE_ID.meta" ! grep -q '^traceparent=' "$meta" \ @@ -388,7 +388,7 @@ test_relaunch_reuses_recorded_carrier() { out=$(run_spawn "$HOME_DIR" "$WT_DIR" "$FAKEBIN_DIR" "$LAUNCH_LOG" "$CASE_ID" "$PROJ_DIR") status=$? expect_code 0 "$status" "first trace-context spawn should succeed" - assert_contains "$out" "spawned $CASE_ID" "first spawn should report success" + assert_contains "$out" "($CASE_ID)" "first spawn should report success" first=$(meta_traceparent "$meta") fm_trace_context_valid "$first" || fail "first spawn must record a valid carrier (got '$first')" @@ -398,7 +398,7 @@ test_relaunch_reuses_recorded_carrier() { out=$(run_spawn "$HOME_DIR" "$WT_DIR" "$FAKEBIN_DIR" "$LAUNCH_LOG" "$CASE_ID" "$PROJ_DIR") status=$? expect_code 0 "$status" "relaunch spawn should succeed" - assert_contains "$out" "spawned $CASE_ID" "relaunch spawn should report success" + assert_contains "$out" "($CASE_ID)" "relaunch spawn should report success" second=$(meta_traceparent "$meta") injected=$(injected_traceparent "$LAUNCH_LOG") [ "$second" = "$first" ] || fail "relaunch must reuse the recorded carrier in meta (first='$first' second='$second')" @@ -415,7 +415,7 @@ test_session_start_freezes_env_override_and_ignores_later_edits() { out=$(run_spawn_tc on "$HOME_DIR" "$WT_DIR" "$FAKEBIN_DIR" "$LAUNCH_LOG" "$CASE_ID" "$PROJ_DIR") status=$? expect_code 0 "$status" "env-off spawn should succeed" - assert_contains "$out" "spawned $CASE_ID" "env-off spawn should report success" + assert_contains "$out" "($CASE_ID)" "env-off spawn should report success" meta="$HOME_DIR/state/$CASE_ID.meta" ! grep -q '^traceparent=' "$meta" || fail "session-frozen off must ignore a later FM_TRACE_CONTEXT=on" ! grep -q '^export TRACEPARENT=' "$LAUNCH_LOG" || fail "session-frozen off must remain disabled after launch-time edits" @@ -506,11 +506,11 @@ test_two_routed_tasks_through_one_secondmate_root_distinct_traces() { out=$(TRACEPARENT="$sm_tp" run_spawn "$sm" "$wt_a" "$fakebin" "$log_a" "$id_a" "$proj_a") status=$? expect_code 0 "$status" "routed task A spawn should succeed" - assert_contains "$out" "spawned $id_a" "routed task A spawn should report success" + assert_contains "$out" "($id_a)" "routed task A spawn should report success" out=$(TRACEPARENT="$sm_tp" run_spawn "$sm" "$wt_b" "$fakebin" "$log_b" "$id_b" "$proj_b") status=$? expect_code 0 "$status" "routed task B spawn should succeed" - assert_contains "$out" "spawned $id_b" "routed task B spawn should report success" + assert_contains "$out" "($id_b)" "routed task B spawn should report success" tp_a=$(meta_traceparent "$sm/state/$id_a.meta") tp_b=$(meta_traceparent "$sm/state/$id_b.meta")