Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ state/ runtime records and signals; gitignored
<id>.pr-poll-registration private transactional provenance record binding the task, canonical metadata identity, sidecar, and static poll publication
<id>.pr-poll-retirement private identity-bound crash-recovery receipt for one exact validated merged result; removed after its poll artifacts retire
<id>.pr-poll-merge-notified canonical PR identity of the last merge outcome delivered for this task; bin/fm-pr-lib.sh owns the marker format and identity mechanics, while bin/fm-merge-outcome-lib.sh owns locked publication, duplicate suppression, and replacement
<id>.pr-poll-git-tip private best-effort cache of the last-seen destination-branch tip for bin/fm-pr-poll.sh's git-based primary landed-work test; not part of the tamper-evident poll chain, safe to delete (forces one full re-evaluation)
branch-outcomes.jsonl .branch-outcomes-cursor Pi supervision-branch durable outcome store and its read cursor; bin/fm-branch-outcome.sh owns the format
branch-session/ .branch-session .branch-mirror-cursor the branch's persistent conversation, its pointer, and the dialog-mirror cursor; extension-owned (docs/pi-supervision-branch.md)
.branch-eligible-rows .branch-eligible-owner .main-eligible-rows per-actor wake-row claims and branch-owner evidence; docs/watcher-continuity.md owns the acknowledgement contract
Expand Down Expand Up @@ -366,7 +367,7 @@ The worker reports the PR when CI first becomes green rather than waiting for me
### PR ready, landing, and teardown

For PR-based ship tasks, the ready signal depends on mode: `no-mistakes` reports `done: PR <url> checks green` after CI is green, while `direct-PR` reports `done: PR <url>` after opening the PR.
Run `bin/fm-pr-check.sh <id> <PR url>` - it records `pr=` and the forge's `pr_head=` when available in the task's meta and arms the watcher's merge poll.
Run `bin/fm-pr-check.sh <id> <PR url>` - it records `pr=` and, when available, the forge's `pr_head=` and the pull request's `pr_dest=` in the task's meta and arms the watcher's merge poll.
Tell the captain the PR's full URL, always the complete `https://...` link rather than a bare `#number`, a concise outcome summary, and the no-mistakes risk level when applicable.
A captain instruction to merge is explicit authority; `yolo` is the only standing routine merge authority.
For any custom `state/<id>.check.sh` you write yourself, keep it an ordinary single-link mode-`0700` file, print one line only when firstmate should wake, print nothing otherwise, finish before `FM_CHECK_TIMEOUT`, then bind its current bytes with `bin/fm-check-register.sh <id>` before the watcher may execute it.
Expand Down
77 changes: 65 additions & 12 deletions bin/fm-pr-check.sh
Original file line number Diff line number Diff line change
@@ -1,11 +1,32 @@
#!/usr/bin/env bash
# Record a PR-ready task: store one validated canonical pr=<url> and the forge's
# exact pr_head=<sha> when available, then atomically arm a static merge poll.
# The watcher check source is byte-for-byte bin/fm-pr-poll.sh; task and PR data
# live only in a private sidecar and are never interpolated into shell source.
# A GitHub pull request URL and a GitLab merge request URL are both accepted,
# including a merge request on a self-hosted GitLab instance.
# Usage: fm-pr-check.sh <task-id> <pr-url>
# Record a PR-ready task: store one validated canonical pr=<url>, the forge's
# exact pr_head=<sha> when available, and the pull request's destination
# branch as pr_dest=<name> when known, then atomically arm a static merge
# poll. The watcher check source is byte-for-byte bin/fm-pr-poll.sh; task and
# PR data live only in a private sidecar and are never interpolated into
# shell source. A GitHub pull request URL, a GitLab merge request URL
# (including on a self-hosted instance), and a Bitbucket Cloud pull request
# URL are all accepted; bin/fm-pr-lib.sh owns the exact URL grammars.
#
# pr_dest is what lets bin/fm-pr-poll.sh's git-based landed-work test compare
# against the PULL REQUEST'S destination instead of always assuming the
# repository's default branch - most pull requests target the default branch,
# but one that does not would otherwise be judged against the wrong branch
# forever. It is read from the optional third argument when
# the caller already knows it, else auto-derived from the forge (GitHub's gh
# CLI exposes baseRefName as a selectable field); GitLab records none, for the
# same reason it records no pr_head (below); Bitbucket has no CLI at all, so a
# Bitbucket task needs the third argument to get a destination narrower than
# the default branch. Either source is revalidated with
# `git check-ref-format --branch` before being recorded, and a missing
# destination is not an error: every consumer defaults to the default branch
# when none is recorded, matching prior behavior. The one exception is a
# re-arm of the exact same pr= URL with no destination supplied this call
# (for example bin/fm-pr-merge.sh's internal re-arm before merging): that
# keeps the previously recorded pr_dest instead of wiping it, since nothing
# about the pull request's destination changed. A re-arm for a different URL
# still gets no carried-over destination.
# Usage: fm-pr-check.sh <task-id> <pr-url> [dest-branch]
set -eu

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
Expand All @@ -18,16 +39,21 @@ STATE="${FM_STATE_OVERRIDE:-$FM_HOME/state}"
# shellcheck source=bin/fm-wake-lib.sh
. "$SCRIPT_DIR/fm-wake-lib.sh"

if [ "$#" -ne 2 ]; then
if [ "$#" -lt 2 ] || [ "$#" -gt 3 ]; then
echo "error: invalid PR check request" >&2
exit 2
fi
ID=$1
RAW_URL=$2
RAW_DEST=${3-}
if ! fm_pr_task_id_valid "$ID" || ! fm_pr_url_parse "$RAW_URL"; then
echo "error: invalid PR check request" >&2
exit 2
fi
if [ -n "$RAW_DEST" ] && ! git check-ref-format --branch "$RAW_DEST" >/dev/null 2>&1; then
echo "error: invalid PR check request" >&2
exit 2
fi
URL=$FM_PR_URL
PROVIDER=$FM_PR_PROVIDER
HOST=$FM_PR_HOST
Expand Down Expand Up @@ -64,6 +90,13 @@ fi
"$SCRIPT_DIR/fm-pr-check-migrate.sh" --checks-safe || exit 1
"$FM_ROOT/bin/fm-guard.sh" || true

# A stale destination-tip cache from a prior arm of this task (bin/fm-pr-poll.sh
# owns its format and lifecycle) must not survive a re-arm: it holds no
# security-sensitive data, so removing it is best-effort, but leaving it behind
# could let the new poll's very first evaluation skip itself on a coincidental
# tip match against the previous PR's destination.
rm -f -- "$STATE/$ID.pr-poll-git-tip" 2>/dev/null || true

# pr_head is recorded only when the forge's CLI can supply it. gh exposes the
# head commit as a selectable field; plain glab exposes it only inside its JSON
# output, which would need a JSON processor firstmate does not require, so a
Expand All @@ -73,12 +106,24 @@ fi
# bin/fm-review-diff.sh resolves the head from the remote when none is recorded.
# bin/fm-pr-merge.sh reads a GitLab head live at merge time for the same reason,
# and treats a recorded value that disagrees as stale rather than authoritative.
# pr_dest is auto-derived here in the same call for the same provider (gh
# exposes baseRefName alongside headRefOid), for the same reason: GitLab would
# need jq to read it out of glab's JSON output, so a GitLab task records none
# and its git-based landed-work test falls back to the default branch.
WT=$(grep '^worktree=' "$META" | tail -1 | cut -d= -f2- || true)
PR_HEAD=
PR_DEST=$RAW_DEST
if [ "$PROVIDER" = github ] && [ -n "$WT" ] && [ -d "$WT" ] && command -v gh >/dev/null 2>&1; then
if REMOTE_HEAD=$(cd "$WT" && gh pr view "$URL" --json headRefOid -q .headRefOid 2>/dev/null) \
&& fm_pr_head_valid "$REMOTE_HEAD"; then
PR_HEAD=$REMOTE_HEAD
if REMOTE_VIEW=$(cd "$WT" && gh pr view "$URL" --json headRefOid,baseRefName \
-q '.headRefOid + "\t" + .baseRefName' 2>/dev/null); then
REMOTE_HEAD=${REMOTE_VIEW%%$'\t'*}
REMOTE_DEST=${REMOTE_VIEW#*$'\t'}
if [ "$REMOTE_HEAD" != "$REMOTE_VIEW" ]; then
fm_pr_head_valid "$REMOTE_HEAD" && PR_HEAD=$REMOTE_HEAD
if [ -z "$PR_DEST" ] && git check-ref-format --branch "$REMOTE_DEST" >/dev/null 2>&1; then
PR_DEST=$REMOTE_DEST
fi
fi
fi
fi

Expand Down Expand Up @@ -107,14 +152,22 @@ META_DEVICE=$(fm_pr_file_device "$META") || exit 1
STATE_DEVICE=$(fm_pr_file_device "$STATE") || exit 1
[ "$META_DEVICE" = "$STATE_DEVICE" ] || { echo "error: task metadata is unavailable" >&2; exit 1; }
META_TMP=$(mktemp "$STATE/.fm-pr-meta.XXXXXX") || exit 1
EXISTING_PR=
EXISTING_DEST=
while IFS= read -r line || [ -n "$line" ]; do
case "$line" in
pr=*|pr_head=*) ;;
pr=*) EXISTING_PR=${line#pr=} ;;
pr_head=*) ;;
pr_dest=*) EXISTING_DEST=${line#pr_dest=} ;;
*) printf '%s\n' "$line" >> "$META_TMP" || exit 1 ;;
esac
done < "$META"
if [ -z "$PR_DEST" ] && [ -n "$EXISTING_DEST" ] && [ "$EXISTING_PR" = "$URL" ]; then
PR_DEST=$EXISTING_DEST
fi
printf 'pr=%s\n' "$URL" >> "$META_TMP" || exit 1
[ -z "$PR_HEAD" ] || printf 'pr_head=%s\n' "$PR_HEAD" >> "$META_TMP" || exit 1
[ -z "$PR_DEST" ] || printf 'pr_dest=%s\n' "$PR_DEST" >> "$META_TMP" || exit 1
chmod 0600 "$META_TMP" || exit 1
fm_pr_private_file_valid "$META_TMP" 600 "$STATE_DEVICE" || exit 1
fm_pr_metadata_identity_parse "$META_TMP" || exit 1
Expand Down
85 changes: 69 additions & 16 deletions bin/fm-pr-lib.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,20 @@
# constructing task paths or performing any side effect.
#
# The stored identity is provider-tagged: provider, url, host, path, number.
# "path" is the full project path, which is owner/repository on GitHub and an
# arbitrarily nested group/subgroup/project namespace on GitLab. A GitLab
# project can sit at any depth, so no owner/repository pair can address one and
# the sidecar carries the whole path instead. GitLab also runs on self-hosted
# instances, so the host is part of that identity rather than a constant. Every
# consumer re-derives the identity from the stored URL and refuses any record
# whose parts do not reconstruct that exact URL.
# "path" is the full project path, which is owner/repository on GitHub and
# Bitbucket Cloud and an arbitrarily nested group/subgroup/project namespace on
# GitLab. A GitLab project can sit at any depth, so no owner/repository pair
# can address one and the sidecar carries the whole path instead. GitLab also
# runs on self-hosted instances, so the host is part of that identity rather
# than a constant; Bitbucket Cloud's host is the fixed bitbucket.org, the same
# way GitHub's is the fixed github.com. Every consumer re-derives the identity
# from the stored URL and refuses any record whose parts do not reconstruct
# that exact URL.
#
# Bitbucket has no forge CLI integration here: bin/fm-pr-poll.sh detects a
# Bitbucket merge through the git-based landed-work test only (bin/fm-pr-lib.sh
# and bin/fm-pr-poll.sh's own headers own that test), never through a forge API
# call, so arming a Bitbucket watch needs no additional tool on PATH.
#
# A validated exact merged result is retired through a private receipt only
# after its durable wake is appended.
Expand Down Expand Up @@ -74,6 +81,7 @@ FM_PR_POLL_SNAPSHOT_DATA_IDENTITY=
FM_PR_POLL_SNAPSHOT_CHECK_IDENTITY=
FM_PR_POLL_SNAPSHOT_REG_HASH=
FM_PR_POLL_SNAPSHOT_REG_IDENTITY=
FM_PR_POLL_SNAPSHOT_DEST=
FM_PR_RETIRE_ID=
FM_PR_RETIRE_PROVIDER=
FM_PR_RETIRE_URL=
Expand Down Expand Up @@ -112,16 +120,17 @@ fm_task_id_creation_valid() {
# GitLab serves self-hosted instances, so the host is part of the identity
# rather than a constant. It is accepted only as a lowercase DNS name with no
# userinfo, port, or trailing dot, which keeps one canonical spelling per MR.
# github.com is refused here even though its shape is otherwise valid: it is
# GitHub's own host and never a GitLab instance, so a URL like
# https://github.com/o/r/-/merge_requests/1 (a typo'd or spoofed GitHub URL)
# would otherwise be armed as a GitLab watch that can never succeed.
# github.com and bitbucket.org are refused here even though their shape is
# otherwise valid: each is another forge's own fixed host and never a GitLab
# instance, so a URL like https://github.com/o/r/-/merge_requests/1 (a typo'd
# or spoofed URL) would otherwise be armed as a GitLab watch that can never
# succeed.
fm_pr_gitlab_host_valid() {
local host=${1-} label
local LC_ALL=C
local -a labels
[ "${#host}" -ge 1 ] && [ "${#host}" -le 253 ] || return 1
[ "$host" != github.com ] || return 1
[ "$host" != github.com ] && [ "$host" != bitbucket.org ] || return 1
case "$host" in
.*|*.|*..*|*[!a-z0-9.-]*) return 1 ;;
esac
Expand Down Expand Up @@ -149,13 +158,24 @@ fm_pr_gitlab_path_valid() {
IFS=/ read -ra segments <<< "$path"
[ "${#segments[@]}" -ge 2 ] && [ "${#segments[@]}" -le 20 ] || return 1
for segment in "${segments[@]}"; do
[ "${#segment}" -ge 1 ] && [ "${#segment}" -le 255 ] || return 1
case "$segment" in
.|..|-*|*.git|*.atom|*[!A-Za-z0-9._-]*) return 1 ;;
esac
fm_pr_path_segment_valid "$segment" || return 1
done
}

# Shared per-segment shape used by both GitLab's namespace and Bitbucket
# Cloud's fixed workspace/repository pair: alnum, dot, hyphen, underscore, no
# leading hyphen, and no ".git"/".atom" suffix, which a real slug never needs
# and which would otherwise let a crafted segment look like a different kind
# of reference.
fm_pr_path_segment_valid() {
local segment=${1-}
local LC_ALL=C
[ "${#segment}" -ge 1 ] && [ "${#segment}" -le 255 ] || return 1
case "$segment" in
.|..|-*|*.git|*.atom|*[!A-Za-z0-9._-]*) return 1 ;;
esac
}

# Parse a canonical PR or MR URL into the provider-tagged identity. Validation
# is strict and per provider: the GitHub username and repository rules are
# unchanged, and GitLab gets its own host and namespace rules rather than a
Expand Down Expand Up @@ -191,6 +211,20 @@ fm_pr_url_parse() {
FM_PR_NUMBER=${BASH_REMATCH[3]}
return 0
fi
# Bitbucket Cloud has a fixed host and a flat workspace/repository pair, with
# no nested namespace and no self-hosted variant to address, so both segments
# share GitLab's per-segment shape rather than GitHub's username rule.
pattern='^https://bitbucket\.org/([A-Za-z0-9._-]{1,255})/([A-Za-z0-9._-]{1,255})/pull-requests/([1-9][0-9]*)$'
if [[ "$raw" =~ $pattern ]]; then
fm_pr_path_segment_valid "${BASH_REMATCH[1]}" || return 1
fm_pr_path_segment_valid "${BASH_REMATCH[2]}" || return 1
FM_PR_PROVIDER=bitbucket
FM_PR_URL=$raw
FM_PR_HOST=bitbucket.org
FM_PR_PATH="${BASH_REMATCH[1]}/${BASH_REMATCH[2]}"
FM_PR_NUMBER=${BASH_REMATCH[3]}
return 0
fi
# The path class contains "/" and "-", so this match is greedy to the last
# "/-/merge_requests/". Any earlier separator therefore lands inside the
# captured path, where the reserved "-" segment is refused.
Expand Down Expand Up @@ -292,6 +326,7 @@ fm_pr_metadata_identity_parse() {
FM_PR_META_HOST=
FM_PR_META_PATH=
FM_PR_META_NUMBER=
FM_PR_META_DEST=
[ -f "$file" ] && [ ! -L "$file" ] || return 1
[ "$(fm_pr_file_link_count "$file")" = 1 ] || return 1
while IFS= read -r line || [ -n "$line" ]; do
Expand All @@ -315,6 +350,16 @@ fm_pr_metadata_identity_parse() {
fm_pr_head_valid "$value" || post_pr_invalid=1
fi
;;
pr_dest=*)
if [ "$seen_pr" -eq 1 ]; then
value=${line#pr_dest=}
if git check-ref-format --branch "$value" >/dev/null 2>&1; then
FM_PR_META_DEST=$value
else
post_pr_invalid=1
fi
fi
;;
x_request=*|x_request_ts=*|x_followups=*|x_platform=*|x_reply_max_chars=*)
;;
*)
Expand Down Expand Up @@ -625,6 +670,14 @@ fm_pr_poll_snapshot_capture() {
FM_PR_POLL_SNAPSHOT_REG_HASH=$(fm_pr_sha256 "$registration") || return 1
FM_PR_POLL_SNAPSHOT_REG_IDENTITY=$(fm_pr_file_identity "$registration") || return 1
FM_PR_POLL_SNAPSHOT_ID=$id
# The recorded destination is enrichment, not part of the tamper-evident
# identity above: fm_pr_poll_artifacts_valid's trailing call to
# fm_pr_metadata_identity_parse already re-read and validated it from the
# task's own metadata, so it is captured here purely so bin/fm-watch.sh can
# pass a validated branch name to the git-based landed-work test in
# bin/fm-pr-poll.sh, never to gate a merge verdict on its own.
# shellcheck disable=SC2034
FM_PR_POLL_SNAPSHOT_DEST=$FM_PR_META_DEST
FM_PR_POLL_SNAPSHOT_PROVIDER=$FM_PR_DATA_PROVIDER
FM_PR_POLL_SNAPSHOT_URL=$FM_PR_DATA_URL
FM_PR_POLL_SNAPSHOT_HOST=$FM_PR_DATA_HOST
Expand Down
Loading