Skip to content

fix(bin): retire a task's process-event sources during teardown - #48

Merged
twilwa merged 5 commits into
mainfrom
fm/fm-teardown-retire-lavish-source
Oct 28, 2026
Merged

twilwa merged 5 commits into
mainfrom
fm/fm-teardown-retire-lavish-source

Conversation

@twilwa

@twilwa twilwa commented Oct 28, 2026 •

Copy link
Copy Markdown
Owner

Intent

Reported by the research second mate on 2026-10-06: bin/fm-teardown.sh does not retire a torn-down worker's crew-hosted Lavish process-event source, so the source stays registered under a dead task owner and reconcile keeps relaunching it (seen with a GTM board source in the research home, and consistent with the platform mate's board note). Fix: teardown retires the task's registered process-event sources through bin/fm-procevent.sh retire with the owner-matched guard, refusing when retirement is uncertain, with a colocated test.

What Changed

  • bin/fm-teardown.sh now retires every process-event source registered as task-owned by the task being torn down. It does this through fm-procevent.sh retire <id> --if-owner <task-id>, using the new bin/fm-teardown-procevent-lib.sh. Teardown runs this retirement twice: once after the landed-work check and before any destructive cleanup, and again after the endpoint closes, just before the task record is removed, so it catches sources registered during cleanup. If a retirement is refused (for example, an unacknowledged pending round, an unsafe registry, or a source whose ownership can't be read), teardown exits and keeps the task record. --force does not skip this step.
  • fm-procevent.sh retire --if-owner now accepts a task id as well as an extension registration token. A task id matches only a registration whose canonical header is kind=task-owned with owner_task=<task-id> (new fm_procevent_task_registration_owned_locked in bin/fm-procevent-lib.sh). Any other owner is still refused.
  • New tests tests/fm-procevent-retire-task.test.sh and tests/fm-teardown-procevent.test.sh are added to the changed-path families in bin/fm-test-run.sh. The fake bin/ fixtures in tests/fm-gotmp.test.sh now link the new teardown library. docs/configuration.md documents that teardown retires a task's sources.

🤖 Generated with Claude Code

Risk Assessment

✅ Low: Teardown now retires the task's sources through fm-procevent.sh retire --if-owner <task-id>. Retirement runs once before destructive cleanup and again just before the task record is removed. Ownership is checked against the registration header (adapter, kind and owner_task lines) while the source lock is held. When retirement is blocked or uncertain, teardown refuses and keeps the task record, which fails safe. Extension-token retirement behaves as before, and I found no reachable path that retires another owner's source or leaves a source registered under a dead owner.

Testing

I ran the two new colocated test scripts (all 7 cases pass, including both late-source cases). I then drove the real fm-procevent.sh and fm-teardown.sh end to end in disposable lab homes with a private tmux server. With the fix, teardown retired worker-a's registered and listening board and killed its listener. Reconcile then relaunched nothing. worker-b's board was untouched. With an unacknowledged round open, teardown refused by name, kept worker-b's record and kept the source. After the owner acknowledged the round, a retry succeeded. The same flow on the base commit left gtm-board registered as task:worker-a/listening with its listener still running after a successful teardown, which reproduces the report. Live wrong-owner and invalid-owner retire calls were refused and left the source intact. The late-registration race during endpoint close was covered only by colocated tests, not live, so it is marked untested. I removed every lab home and killed the leftover processes from the base run. The worktree is clean.

  • Live validation: ✅ go - 6 of 7 scenarios driven live against the product
Scenario Result Live Evidence
Tearing down a worker that owns a listening Lavish board retires that board: fm-procevent.sh list no longer shows it, its listener process is gone, and reconcile relaunches nothing ✅ pass live live-fixed.log: after fm-teardown.sh worker-a --force the list shows only other-board, reconcile reports started=0, and the gtm-board sleep child is gone
Regression reproduction: on the base commit the same teardown leaves the board registered under the dead task with its listener still running ✅ pass live live-base.log lines B44-B57: gtm-board is still task:worker-a/listening after teardown and after reconcile, and both listener children are alive
Teardown of worker-a does not retire a board owned by another task (worker-b) ✅ pass live live-fixed.log: other-board stays task:worker-b/listening and its listener stays alive after worker-a teardown
Adversarial: teardown with an unacknowledged captured round on the task's board refuses, names the source and reason, keeps the task record and the source ✅ pass live live-fixed.log: rc=1, 'cannot retire process-event source other-board for task worker-b; retaining task record: ... unacknowledged'. worker-b.meta and other-board round-open 1 remain
After the owner acknowledges the round, rerunning teardown succeeds and leaves no sources ✅ pass live live-fixed.log retry section: handled other-board 1, then teardown worker-b complete, then 'no sources registered'
Adversarial: retire --if-owner with a different task id or an invalid id refuses and keeps the source; the matching owner retires it ✅ pass live live-wrong-owner.log
A source the worker registers while its endpoint is being closed is retired by the final pass, and a refusal there keeps the task record ⏸️ untested no The prior payload did not establish a live result for this scenario. It was covered only by the colocated tests/fm-teardown-procevent.test.sh late-pending and late-source cases (colocated-tests.log),…
Evidence: Live driver script (lab home + private tmux + real register-task/reconcile/teardown)

Source: Live driver script (lab home + private tmux + real register-task/reconcile/teardown)

#!/usr/bin/env bash
# Live driver: real fm-procevent.sh register-task/reconcile + real fm-teardown.sh
# in a disposable lab home with a private tmux server. Usage: <bin-dir> <label>
set -u
BIN=$1; LABEL=$2
WT=~/.no-mistakes/worktrees/8be14fbb8fb5/01M60WN55QWJCQ5H69TC4F25WM
LAB=$(mktemp -d "${TMPDIR:-/tmp}/fm-lab.XXXXXX"); rmdir "$LAB"
"$WT/bin/fm-lab-home.sh" create "$LAB" >/dev/null
chmod 700 "$LAB" "$LAB/state"
export TMUX_TMPDIR=$("$WT/bin/fm-lab-home.sh" tmux-dir "$LAB")
unset TMUX FM_ROOT_OVERRIDE FM_STATE_OVERRIDE FM_DATA_OVERRIDE FM_CONFIG_OVERRIDE FM_PROJECTS_OVERRIDE
export FM_HOME=$LAB FM_PROCEVENT_CLAIM_ROOT=$LAB/claims
cleanup() { tmux kill-server 2>/dev/null; "$WT/bin/fm-lab-home.sh" teardown "$LAB" >/dev/null 2>&1; pkill -f "$LAB" 2>/dev/null; rm -rf "$LAB"; }
trap cleanup EXIT
say() { printf '\n$ %s\n' "$*"; }
run() { say "$*"; "$@" 2>&1; echo "[rc=$?]"; }
mkmeta() {  # <task>
  printf '%s\n' kind=scout backend=tmux "window=fm-lab:fm-$1" "endpoint_task_id=$1" \
    "worktree=$LAB/missing-$1" "project=$LAB/missing-project" > "$LAB/state/$1.meta"
  tmux new-window -d -t fm-lab: -n "fm-$1" "sleep 900"
}
echo "== [$LABEL] bin=$BIN lab=$LAB"
tmux new-session -d -s fm-lab -n idle "sleep 900"
mkmeta worker-a; mkmeta worker-b
# Crew-hosted Lavish-style long-poll listeners owned by each worker.
run "$BIN/fm-procevent.sh" register-task lavish gtm-board worker-a -- /bin/sleep 6017
run "$BIN/fm-procevent.sh" register-task lavish other-board worker-b -- /bin/sleep 6017
run "$BIN/fm-procevent.sh" reconcile
run "$BIN/fm-procevent.sh" list
say "live listener children: ps -eo pid,args | grep '/bin/sleep 6017$'"; ps -eo pid,args | grep '/bin/sleep 6017$' | grep -v grep
run tmux list-windows -t fm-lab -F '#W'
run "$BIN/fm-teardown.sh" worker-a --force
run ls "$LAB/state"
run "$BIN/fm-procevent.sh" list
run "$BIN/fm-procevent.sh" reconcile
run "$BIN/fm-procevent.sh" list
sleep 2; say "live listener children after teardown+reconcile: ps -eo pid,args | grep '/bin/sleep 6017$'"; ps -eo pid,args | grep '/bin/sleep 6017$' | grep -v grep
run tmux list-windows -t fm-lab -F '#W'

[ "$LABEL" = base ] && exit 0
echo; echo "== [$LABEL] adversarial: pending captured round on worker-b's board"
# Re-register worker-b listener as one that completes with feedback (a real captured round).
run "$BIN/fm-procevent.sh" retire other-board --if-owner worker-b
run "$BIN/fm-procevent.sh" register-task lavish other-board worker-b -- /bin/sh -c 'echo "{\"feedback\":\"please fix\"}"'
run "$BIN/fm-procevent.sh" reconcile
sleep 3
run "$BIN/fm-procevent.sh" list
run "$BIN/fm-teardown.sh" worker-b --force
run ls "$LAB/state"
run "$BIN/fm-procevent.sh" list

echo; echo "== [$LABEL] retry after the owner acknowledges the round"
run ls "$LAB/state/procevent-inbox"
run "$BIN/fm-procevent.sh" handled other-board 1
run "$BIN/fm-teardown.sh" worker-b --force
run ls "$LAB/state"
run "$BIN/fm-procevent.sh" list
Evidence: Fixed: teardown retires own board, spares other task, refuses on open round, succeeds after ack

Source: Fixed: teardown retires own board, spares other task, refuses on open round, succeeds after ack

== [fixed] bin=<wt>/bin lab=/tmp/fm-lab.dUR4Eg

$ <wt>/bin/fm-procevent.sh register-task lavish gtm-board worker-a -- /bin/sleep 6017
registered: gtm-board (lavish, task=worker-a)
[rc=0]

$ <wt>/bin/fm-procevent.sh register-task lavish other-board worker-b -- /bin/sleep 6017
registered: other-board (lavish, task=worker-b)
[rc=0]

$ <wt>/bin/fm-procevent.sh reconcile
reconciled: published=0 started=2 stopped=0 uncertain=0 failed=0
[rc=0]

$ <wt>/bin/fm-procevent.sh list
SOURCE                       ADAPTER      OWNER      PENDING
gtm-board                    lavish       task:worker-a/listening 0
other-board                  lavish       task:worker-b/listening 0
[rc=0]

$ live listener children: ps -eo pid,args | grep '/bin/sleep 6017$'
4134969 /bin/sleep 6017
4135126 /bin/sleep 6017

$ tmux list-windows -t fm-lab -F #W
idle
fm-worker-a
fm-worker-b
[rc=0]

$ <wt>/bin/fm-teardown.sh worker-a --force
fm-gate-refuse: gate agent lifecycle permitted only against lab home /tmp/fm-lab.dUR4Eg
teardown worker-a complete (window fm-lab:fm-worker-a, worktree /tmp/fm-lab.dUR4Eg/missing-worker-a)
Backlog: worker-a just finished (this home keeps no markdown backlog at /tmp/fm-lab.dUR4Eg/data/backlog.md). Update /tmp/fm-lab.dUR4Eg/data/backlog.md - move worker-a to Done, keep Done to the 10 most recent, then re-scan Queued and dispatch only work whose blockers are gone and date is due.
[rc=0]

$ ls /tmp/fm-lab.dUR4Eg/state
home-summary.json
procevent
terminal-outcomes
worker-b.meta
[rc=0]

$ <wt>/bin/fm-procevent.sh list
SOURCE                       ADAPTER      OWNER      PENDING
other-board                  lavish       task:worker-b/listening 0
[rc=0]

$ <wt>/bin/fm-procevent.sh reconcile
reconciled: published=0 started=0 stopped=0 uncertain=0 failed=0
[rc=0]

$ <wt>/bin/fm-procevent.sh list
SOURCE                       ADAPTER      OWNER      PENDING
other-board                  lavish       task:worker-b/listening 0
[rc=0]

$ live listener children after teardown+reconcile: ps -eo pid,args | grep '/bin/sleep 6017$'
4135126 /bin/sleep 6017

$ tmux list-windows -t fm-lab -F #W
idle
fm-worker-b
[rc=0]

== [fixed] adversarial: pending captured round on worker-b's board

$ <wt>/bin/fm-procevent.sh retire other-board --if-owner worker-b
retired: other-board
[rc=0]

$ <wt>/bin/fm-procevent.sh register-task lavish other-board worker-b -- /bin/sh -c echo "{\"feedback\":\"please fix\"}"
registered: other-board (lavish, task=worker-b)
[rc=0]

$ <wt>/bin/fm-procevent.sh reconcile
reconciled: published=0 started=1 stopped=0 uncertain=0 failed=0
[rc=0]

$ <wt>/bin/fm-procevent.sh list
SOURCE                       ADAPTER      OWNER      PENDING
other-board                  lavish       task:worker-b/round-open 1
[rc=0]

$ <wt>/bin/fm-teardown.sh worker-b --force
fm-gate-refuse: gate agent lifecycle permitted only against lab home /tmp/fm-lab.dUR4Eg
WARNING: watcher still down (same stale episode; last beat: never, grace 300s) - full banner already printed this episode.
error: cannot retire process-event source other-board for task worker-b; retaining task record: error: cannot retire task-owned source other-board while a captured round for task worker-b is unacknowledged; acknowledge it with bin/fm-procevent.sh handled other-board <sequence>
[rc=1]

$ ls /tmp/fm-lab.dUR4Eg/state
home-summary.json
procevent
procevent-inbox
terminal-outcomes
worker-b.inbox
worker-b.meta
[rc=0]

$ <wt>/bin/fm-procevent.sh list
SOURCE                       ADAPTER      OWNER      PENDING
other-board                  lavish       task:worker-b/round-open 1
[rc=0]

== [fixed] retry after the owner acknowledges the round

$ ls /tmp/fm-lab.dUR4Eg/state/procevent-inbox
other-board.1.adapter
other-board.1.owner-task
other-board.1.result
[rc=0]

$ <wt>/bin/fm-procevent.sh handled other-board 1
handled: other-board 1
[rc=0]

$ <wt>/bin/fm-teardown.sh worker-b --force
fm-gate-refuse: gate agent lifecycle permitted only against lab home /tmp/fm-lab.dUR4Eg
WARNING: watcher still down (same stale episode; last beat: never, grace 300s) - full banner already printed this episode.
teardown worker-b complete (window fm-lab:fm-worker-b, worktree /tmp/fm-lab.dUR4Eg/missing-worker-b)
Backlog: worker-b just finished (this home keeps no markdown backlog at /tmp/fm-lab.dUR4Eg/data/backlog.md). Update /tmp/fm-lab.dUR4Eg/data/backlog.md - move worker-b to Done, keep Done to the 10 most recent, then re-scan Queued and dispatch only work whose blockers are gone and date is due.
[rc=0]

$ ls /tmp/fm-lab.dUR4Eg/state
home-summary.json
procevent
procevent-inbox
terminal-outcomes
[rc=0]

$ <wt>/bin/fm-procevent.sh list
no sources registered
[rc=0]
Evidence: Base commit: bug reproduced (gtm-board still task:worker-a/listening after teardown)

Source: Base commit: bug reproduced (gtm-board still task:worker-a/listening after teardown)

$ fm-teardown.sh worker-a --force -> teardown worker-a complete [rc=0] $ fm-procevent.sh list gtm-board lavish task:worker-a/listening 0 other-board lavish task:worker-b/listening 0 (listener /bin/sleep 6017 for gtm-board still running)

== [base] bin=<base>/bin lab=/tmp/fm-lab.19lgle

$ <base>/bin/fm-procevent.sh register-task lavish gtm-board worker-a -- /bin/sleep 6017
registered: gtm-board (lavish, task=worker-a)
[rc=0]

$ <base>/bin/fm-procevent.sh register-task lavish other-board worker-b -- /bin/sleep 6017
registered: other-board (lavish, task=worker-b)
[rc=0]

$ <base>/bin/fm-procevent.sh reconcile
reconciled: published=0 started=2 stopped=0 uncertain=0 failed=0
[rc=0]

$ <base>/bin/fm-procevent.sh list
SOURCE                       ADAPTER      OWNER      PENDING
gtm-board                    lavish       task:worker-a/listening 0
other-board                  lavish       task:worker-b/listening 0
[rc=0]

$ live listener children: ps -eo pid,args | grep '/bin/sleep 6017$'
4157880 /bin/sleep 6017
4157936 /bin/sleep 6017

$ tmux list-windows -t fm-lab -F #W
idle
fm-worker-a
fm-worker-b
[rc=0]

$ <base>/bin/fm-teardown.sh worker-a --force
fm-gate-refuse: gate agent lifecycle permitted only against lab home /tmp/fm-lab.19lgle
teardown worker-a complete (window fm-lab:fm-worker-a, worktree /tmp/fm-lab.19lgle/missing-worker-a)
Backlog: worker-a just finished (this home keeps no markdown backlog at /tmp/fm-lab.19lgle/data/backlog.md). Update /tmp/fm-lab.19lgle/data/backlog.md - move worker-a to Done, keep Done to the 10 most recent, then re-scan Queued and dispatch only work whose blockers are gone and date is due.
[rc=0]

$ ls /tmp/fm-lab.19lgle/state
home-summary.json
procevent
terminal-outcomes
worker-b.meta
[rc=0]

$ <base>/bin/fm-procevent.sh list
SOURCE                       ADAPTER      OWNER      PENDING
gtm-board                    lavish       task:worker-a/listening 0
other-board                  lavish       task:worker-b/listening 0
[rc=0]

$ <base>/bin/fm-procevent.sh reconcile
reconciled: published=0 started=0 stopped=0 uncertain=0 failed=0
[rc=0]

$ <base>/bin/fm-procevent.sh list
SOURCE                       ADAPTER      OWNER      PENDING
gtm-board                    lavish       task:worker-a/listening 0
other-board                  lavish       task:worker-b/listening 0
[rc=0]

$ live listener children after teardown+reconcile: ps -eo pid,args | grep '/bin/sleep 6017$'
4157880 /bin/sleep 6017
4157936 /bin/sleep 6017

$ tmux list-windows -t fm-lab -F #W
idle
fm-worker-b
[rc=0]
Evidence: Live retire --if-owner guard: wrong owner and invalid id refused, matching owner retires

Source: Live retire --if-owner guard: wrong owner and invalid id refused, matching owner retires

$ bin/fm-procevent.sh register-task lavish gtm-board worker-a -- /bin/true
registered: gtm-board (lavish, task=worker-a)
[rc=0]
$ bin/fm-procevent.sh retire gtm-board --if-owner worker-b
error: source registration does not match the expected owner: gtm-board
[rc=1]
$ bin/fm-procevent.sh retire gtm-board --if-owner bad id!
error: registration owner must be an extension token or task id
[rc=1]
$ bin/fm-procevent.sh list
SOURCE                       ADAPTER      OWNER      PENDING
gtm-board                    lavish       task:worker-a/dead 0
[rc=0]
$ bin/fm-procevent.sh retire gtm-board --if-owner worker-a
retired: gtm-board
[rc=0]
$ bin/fm-procevent.sh list
no sources registered
[rc=0]
Evidence: Colocated focused tests

Source: Colocated focused tests

FM_TEST_BEGIN 2026-10-28T09:17:43Z tests/fm-teardown-procevent.test.sh family=unclassified expected_gate_skip=none
ok - teardown retains task records and explains source retirement refusals
ok - teardown retires only its own task process-event sources
ok - teardown without registered process-event sources is unaffected
ok - late-source retirement refusal retains the task record after endpoint closure
ok - teardown retires sources registered after the early pass and before endpoint closure
FM_TEST_END 2026-10-28T09:18:15Z tests/fm-teardown-procevent.test.sh exit=0 duration_ms=32428 gate_skip=false
FM_TEST_BEGIN 2026-10-28T09:18:15Z tests/fm-procevent-retire-task.test.sh family=unclassified expected_gate_skip=none
ok - matching task owner retires its process-event source
ok - a different task owner cannot retire a process-event source
FM_TEST_END 2026-10-28T09:18:18Z tests/fm-procevent-retire-task.test.sh exit=0 duration_ms=2120 gate_skip=false
FM_TEST_SUMMARY total=2 failed=0 skipped_gate=0 duration_ms=34763
FM_TEST_SUMMARY_FAMILY family=unclassified count=2 duration_ms=34548 failed=0
FM_TEST_SLOWEST rank=1 script=tests/fm-teardown-procevent.test.sh duration_ms=32428
FM_TEST_SLOWEST rank=2 script=tests/fm-procevent-retire-task.test.sh duration_ms=2120
FM_TEST_LISTENERS found=0

real	0m34.913s
user	0m8.895s
sys	0m27.104s

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 6 of 7 scenarios driven live against the product
Scenario Result Live Evidence
Tearing down a worker that owns a listening Lavish board retires that board: fm-procevent.sh list no longer shows it, its listener process is gone, and reconcile relaunches nothing ✅ pass live live-fixed.log: after fm-teardown.sh worker-a --force the list shows only other-board, reconcile reports started=0, and the gtm-board sleep child is gone
Regression reproduction: on the base commit the same teardown leaves the board registered under the dead task with its listener still running ✅ pass live live-base.log lines B44-B57: gtm-board is still task:worker-a/listening after teardown and after reconcile, and both listener children are alive
Teardown of worker-a does not retire a board owned by another task (worker-b) ✅ pass live live-fixed.log: other-board stays task:worker-b/listening and its listener stays alive after worker-a teardown
Adversarial: teardown with an unacknowledged captured round on the task's board refuses, names the source and reason, keeps the task record and the source ✅ pass live live-fixed.log: rc=1, 'cannot retire process-event source other-board for task worker-b; retaining task record: ... unacknowledged'. worker-b.meta and other-board round-open 1 remain
After the owner acknowledges the round, rerunning teardown succeeds and leaves no sources ✅ pass live live-fixed.log retry section: handled other-board 1, then teardown worker-b complete, then 'no sources registered'
Adversarial: retire --if-owner with a different task id or an invalid id refuses and keeps the source; the matching owner retires it ✅ pass live live-wrong-owner.log
A source the worker registers while its endpoint is being closed is retired by the final pass, and a refusal there keeps the task record ⏸️ untested no The prior payload did not establish a live result for this scenario. It was covered only by the colocated tests/fm-teardown-procevent.test.sh late-pending and late-source cases (colocated-tests.log),…
  • bash bin/fm-test-run.sh tests/fm-teardown-procevent.test.sh tests/fm-procevent-retire-task.test.sh (all 7 cases ok)
  • live-teardown-procevent.sh &lt;worktree&gt;/bin fixed: disposable bin/fm-lab-home.sh lab home with a private tmux server and real worker windows. It runs real fm-procevent.sh register-task lavish for gtm-board (worker-a) and other-board (worker-b), then reconcile (starts 2 real runners), then fm-teardown.sh worker-a --force, then list, reconcile and a ps check of the listener children
  • Same driver, adversarial section: worker-b's board is re-registered as a listener that completes, giving a real captured round (round-open 1). Then fm-teardown.sh worker-b --force is checked for refusal, then fm-procevent.sh handled other-board 1, then teardown is retried
  • live-teardown-procevent.sh &lt;base-archive&gt;/bin base: the same lab flow on git archive 40429373 reproduces the bug
  • Live fm-procevent.sh retire gtm-board --if-owner worker-b / --if-owner &#39;bad id!&#39; / --if-owner worker-a in a lab home
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

Summary by Sourcery

Retire task-owned process-event sources during teardown so dead workers cannot leave listeners that reconciliation relaunches.

Bug Fixes:

  • Ensure task teardown retires all process-event sources owned by the task, preventing dead-task sources and their listeners from being relaunched by reconciliation.

Enhancements:

  • Extend guarded process-event retirement to accept and validate task ownership in addition to extension registration tokens.
  • Make teardown fail safely and retain the task record when source retirement is refused or ownership cannot be verified, while performing a final retirement pass after endpoint closure.
  • Document task-owned process-event retirement and add focused coverage for ownership guards, refusal handling, and late registrations.

Documentation:

  • Document that task teardown retires owned process-event sources and refuses to remove the task when retirement is unsafe.

Tests:

  • Add focused tests covering task-owner retirement and teardown handling of owned, foreign, pending, and late-registered process-event sources.

@sourcery-ai

sourcery-ai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Teardown now retires a task's process-event registrations through owner-checked retirement before cleanup, refusing safely when retirement is uncertain; task-ID ownership validation, regression tests, test mappings, and documentation accompany the change.

Sequence diagram for safe task teardown and process-event retirement

sequenceDiagram
    actor Operator
    participant Teardown as fm-teardown.sh
    participant Retirement as fm-teardown-procevent-lib.sh
    participant Procevent as fm-procevent.sh
    participant Registry as ProcessEventRegistry

    Operator->>Teardown: teardown(task-id, --force)
    Teardown->>Retirement: teardown_retire_process_events(state, task-id, script-dir)
    Retirement->>Registry: enumerate task-owned sources
    loop each matching source
        Retirement->>Procevent: retire(source-id, --if-owner, task-id)
        Procevent->>Registry: validate canonical kind and owner_task
        alt ownership and retirement are valid
            Procevent-->>Retirement: success
        else pending round, uncertain state, or mismatch
            Procevent-->>Retirement: refusal with reason
            Retirement-->>Teardown: failure, retain task record
            Teardown-->>Operator: teardown refused
        end
    end
    Retirement-->>Teardown: all sources retired
    Teardown->>Teardown: destructive cleanup
    Teardown-->>Operator: teardown complete
Loading

Sequence diagram for owner-checked process-event retirement

sequenceDiagram
    participant Caller
    participant Procevent as fm-procevent.sh
    participant Registry as ProcessEventRegistry

    Caller->>Procevent: retire(source-id, --if-owner, task-id)
    Procevent->>Procevent: fm_pr_task_id_valid(task-id)
    Procevent->>Registry: load canonical adapter, kind, owner_task header
    alt kind=task-owned and owner_task matches task-id
        Procevent->>Registry: retire source and stop runner
        Procevent-->>Caller: success
    else different owner or malformed registration
        Procevent-->>Caller: refuse source registration mismatch
        Registry-->>Caller: source remains registered
    end
Loading

File-Level Changes

Change Details Files
Retire task-owned process-event registrations before destructive task teardown.
  • Load the new teardown helper through the required-source guard.
  • Enumerate registrations owned by the task and retire each through the guarded CLI path.
  • Stop teardown and retain the task record when ownership, registry safety, or retirement state is uncertain; force does not bypass the check.
bin/fm-teardown.sh
bin/fm-teardown-procevent-lib.sh
Extend conditional process-event retirement to validate task ownership canonically.
  • Accept task IDs in addition to extension registration tokens for --if-owner.
  • Match task ownership against the registration header's adapter, kind, and owner_task fields rather than argv.
  • Preserve refusal behavior for wrong or malformed owners and maintain extension-token validation.
bin/fm-procevent.sh
bin/fm-procevent-lib.sh
Add regression coverage and test selection for task retirement behavior.
  • Cover matching and wrong-task owners for direct retirement.
  • Cover teardown refusal with pending rounds, selective retirement, and no-source compatibility.
  • Map the new tests to relevant changed scripts.
tests/fm-procevent-retire-task.test.sh
tests/fm-teardown-procevent.test.sh
bin/fm-test-run.sh
Document the teardown lifecycle guarantee for task-owned sources.
  • Explain that teardown retires task-owned sources even with --force.
  • Document that uncertain or refused retirement preserves the task record.
docs/configuration.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 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-10-28T07:26:46.455443Z 4454ffc PR opened
ℹ️ 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.

@sourcery-ai sourcery-ai 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.

Hey - I've found 2 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="bin/fm-teardown-procevent-lib.sh" line_range="14" />
<code_context>
+    echo "error: cannot enumerate process-event sources for task $task: unsafe registry $reg" >&2
+    return 1
+  fi
+  for rec in "$reg"/*.source; do
+    [ -e "$rec" ] || [ -L "$rec" ] || continue
+    id=${rec##*/}; id=${id%.source}
</code_context>
<issue_to_address>
**Listeners outlive removed tasks**

When a task-owned source is published after teardown expands the registry glob and before it removes the task record, `teardown_retire_process_events` never visits the new source, and teardown removes the task record while the registration remains; reconciliation can then relaunch its listener for a dead task.

Serialize task-owned registration with teardown’s task-record lock, and ensure teardown retires all task-owned registrations before removing the task record.
</issue_to_address>

### Comment 2
<location path="bin/fm-teardown.sh" line_range="3792" />
<code_context>
   fi
 fi

+teardown_retire_process_events "$STATE" "$ID" "$SCRIPT_DIR" || exit 1
+
 # A Herdr close may reposition shared workspace order, so the whole
</code_context>
<issue_to_address>
**Refused teardown loses listeners**

When a later preflight refuses, or a later source retirement is refused after an earlier source was retired, `teardown_retire_process_events` removes listeners before teardown completes, then teardown retains the task record after refusing; the still-live task loses process-event monitoring, and a retry cannot restore the retired sources.

Make source retirement transactional: run refusal checks first and restore already-retired sources if any retirement fails.

Also at `bin/fm-teardown-procevent-lib.sh:24-27`.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread bin/fm-teardown-procevent-lib.sh Resolved
Comment thread bin/fm-teardown.sh Resolved
… PR. Teardown now requires and sources bin/fm-teardown-procevent-lib.sh at startup. tests/fm-gotmp.test.sh builds a selective fake bin/ for real teardown and did not link that new library, so teardown refused at startup and the test failed with "teardown exited non-zero with a valid tasktmp". Invariant: every fake bin/ fixture that runs the real fm-teardown.sh must provide each library teardown requires at startup. Only tests/fm-gotmp.test.sh builds such a selective fixture, and it does so twice. Fix: link fm-teardown-procevent-lib.sh in both fixtures. Verified locally: tests/fm-gotmp.test.sh passes all 3 cases, tests/fm-teardown-procevent.test.sh passes and shellcheck is clean. ci-1 (Behavior portable serial 1) was not caused by this PR. The failing case was test_report_without_acknowledgement_hands_the_wake_to_main in tests/fm-supervision-host.test.sh. The CI log shows the host did the right thing: it recorded the turn as failed with unacked=1 and handed the wake to main. It just finished about 30s after starting, which is past the test's wait, inside a suite that ran 25 minutes on CI. bin/fm-supervision-host.sh and that test never use teardown or procevent code, and the test file is untouched by this PR. Run alone locally on this branch, that test passes. No code change for ci-1
@twilwa twilwa changed the title fix(bin): retire a torn-down task's process-event sources during teardown fix(bin): retire a task's process-event sources during teardown Oct 28, 2026
@twilwa

twilwa commented Oct 28, 2026

Copy link
Copy Markdown
Owner Author

Review disposition for head 1c9bfb4

  • Sourcery High (listeners outlive removed tasks): addressed with a second guarded retirement pass after endpoint closure, immediately before record removal, plus a late-source regression.
  • Sourcery Medium (refused teardown loses listeners): rejected; the early pass runs only after every finished-work preflight, so a later refusal is transient on a finished task and a retry re-enumerates with the record retained.
  • Codex: no findings.
  • no-mistakes run 01M60N98BW20QK5TY6ZP3ERVY2 (claude-opus-5-5): revalidated 1c9bfb4 with no findings; 24 checks green.

Merging under the standing firstmate-PR authority.

@twilwa
twilwa merged commit 1ea2633 into main Oct 28, 2026
26 checks passed
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.

1 participant