reconFTW is a tool designed to perform automated recon on a target domain by running the best set of tools to perform scanning and finding out vulnerabilities
id: 01-05 phase: 01 plan: 05 type: execute wave: 3 depends_on: [] requirements: [RESIL-03] gap_closure: true closes_gaps: [CR-02, CR-03] files_modified:
- lib/parallel.sh
autonomous: true
must_haves:
truths:
- "Setting
PARALLEL_JOB_TIMEOUT_SECONDS=600under--quiet(OUTPUT_VERBOSITY=0) terminates any parallel_funcs child that exceeds 600s — the verbosity gate atlib/parallel.sh:469and:579is decoupled from the timeout-enforcement gate, so CI runs (the documented primary use case perreconftw.cfg:317) get timeout enforcement (closes CR-02 / SC3 defect #1)" - "On timeout kill, the actual external tool process (puredns, massdns, dnsx, ffuf, axiom-scan, etc.) terminates — not just the parallel_funcs wrapper subshell.
_timeout_kill_jobwalks the process tree of the wrapper PID via apgrep -P-based recursive child kill (with a process-group kill fallback) so the entire job hierarchy is signaled, not just$!(closes CR-03 / SC3 defect #2)" - "Heartbeat snapshots (the UI side of the loop) are STILL gated on
OUTPUT_VERBOSITY >= 1— only the timeout-enforcement check and the kill mechanism are decoupled. Under--quietthe loop runs but emits no heartbeat lines, exactly mirroring the user's intent (quiet = no UI noise, NOT quiet = no timeout enforcement)." - "Two-loop symmetry preserved: both the batch-flush heartbeat at
lib/parallel.sh:467-506(post-edit line numbers will shift) AND the final-wait heartbeat atlib/parallel.sh:577-616get the decoupled gate AND the kill-tree behavior. No regression of the existing two-loop discipline established by Plan 01-03." - "macOS/BSD compatibility maintained:
pgrep -Pis available on both BSD and GNU procps (CLAUDE.md §macOS compatibility). No reliance onsetsid(Linux-only) or GNU-ps-only flags. Fallback path uses portableps -p $pid -o pgid=cross-checked withpgrep -Pwalk so a missing-pgrephost gracefully degrades to wrapper-only kill (the current pre-patch behavior) rather than failing the run." - "Default
PARALLEL_JOB_TIMEOUT_SECONDS=0is preserved (locked by D-11); the feature remains opt-in and backwards-compatible. No CI deadline becomes more aggressive by default." code_landmarks: - "Decoupled gate at
lib/parallel.sh:469: split the compound condition[[ ${PARALLEL_MODE} == true ]] && [[ ${OUTPUT_VERBOSITY:-1} -ge 1 ]] && [[ $hb =~ ^[0-9]+$ ]] && ((hb > 0))into two booleans —_loop_active(true if PARALLEL_MODE=true AND hb is a positive integer) AND a separate inner_verbose_progress(true if OUTPUT_VERBOSITY >= 1) that gates ONLY the_parallel_snapshotcall. Read_to=${PARALLEL_JOB_TIMEOUT_SECONDS:-0}once outside the loop; the loop runs when_loop_active && (_verbose_progress || _to > 0). Heartbeat snapshots fire only when_verbose_progress=true." - "Same decoupled gate at
lib/parallel.sh:579(final-wait heartbeat) — two-loop symmetry is mandatory per PATTERNS.md." - "
_timeout_kill_jobbody atlib/parallel.sh:53-77: replace the singlekill -TERM $pid/kill -KILL $pidpair with a_kill_treehelper that walks descendants viapgrep -Pand signals each leaf (and the root). The persistence writes (.status_<fn>=FAIL,.status_reason_<fn>=timeout) and thelog_jsoncall remain unchanged — only the kill mechanism is replaced." - "New private helper
_kill_tree(or equivalent inlined logic) declared above_timeout_kill_job(after_throttle_jobsat :42 and before_timeout_kill_jobat :53). Usesfunction _kill_tree() {form per CONVENTIONS.md §Function Naming (project-wide rule)." - "Optional process-group fallback at
lib/parallel.sh:432-438(the wrapper-subshell spawn site): consider launching the wrapper as a job in its own process group via the existingset +mtoggling. Note however thatstart()atmodules/modes.sh:16explicitly disables job control (set +m 2>/dev/null || true); resurrecting job control just for this corner case is intrusive. PREFER thepgrep -Pwalk in_kill_treeover the pgid approach — fewer side effects, noset -mflip needed." behavioral_checks: - "Smoke 1 (CR-02 reproduction — timeout fires under --quiet): set
PARALLEL_JOB_TIMEOUT_SECONDS=2,PARALLEL_KILL_GRACE_SECONDS=1,PARALLEL_HEARTBEAT_SECONDS=1,OUTPUT_VERBOSITY=0(the--quietmode). Runparallel_funcs 1 my_slow_funcwherefunction my_slow_func() { sleep 30; }. Within ~5 seconds the job MUST be killed;.status_my_slow_funcMUST containFAIL;.status_reason_my_slow_funcMUST containtimeout. With the pre-patch code (verbosity-gated loop) the same setup runssleep 30to completion without killing it — verify the wallclock difference is the smoke signal." - "Smoke 2 (CR-03 reproduction — inner tool dies too): set
PARALLEL_JOB_TIMEOUT_SECONDS=2,PARALLEL_KILL_GRACE_SECONDS=1,OUTPUT_VERBOSITY=1. Definefunction my_slow_func() { sleep 30 & local inner=$!; echo $inner > /tmp/inner.pid; wait; }. Runparallel_funcs 1 my_slow_func. After ~5s, both the wrapper subshell ANDcat /tmp/inner.pid | xargs -I{} kill -0 {} 2>/dev/nullMUST return non-zero (innersleep 30is dead). With the pre-patch code the inner sleep keeps running as an orphan to PID 1 — verify withps -p $(cat /tmp/inner.pid) -o stat= 2>/dev/nullreturning empty post-patch." - "Smoke 3 (heartbeat UI still gated on verbosity): set
PARALLEL_JOB_TIMEOUT_SECONDS=0(disabled — backwards-compat baseline),OUTPUT_VERBOSITY=0,PARALLEL_HEARTBEAT_SECONDS=1. Run aparallel_funcs 1 normal_funcwherefunction normal_func() { sleep 5; }. The function MUST complete to natural exit (no kill); the console MUST NOT print any heartbeat lines under verbosity 0. Same setup withOUTPUT_VERBOSITY=1MUST print heartbeat snapshots. This proves the UI gate is unchanged while only the timeout-enforcement gate was decoupled." - "Smoke 4 (default-disabled backwards compat):
PARALLEL_JOB_TIMEOUT_SECONDS=0(the shipped default),OUTPUT_VERBOSITY=1. Runparallel_funcs 1 normal_func. Behavior MUST be identical to pre-patch — no kill, no FAIL persistence, just heartbeats and natural completion." - "Smoke 5 (two-loop symmetry — final-wait path also gets the decoupled gate and kill-tree): set
PARALLEL_MAX_JOBS=2,PARALLEL_JOB_TIMEOUT_SECONDS=2,OUTPUT_VERBOSITY=0. Submit a 3-function batch where only the 3rd function is slow (sleeps 30). The first 2 functions trigger the batch-flush loop (handled by the modified batch-flush heartbeat); the 3rd function falls into the final-wait loop. The 3rd function MUST be killed by the final-wait loop's timeout enforcement — verify via the.status_slow_3=FAIL,.status_reason_slow_3=timeoutfiles." - "Smoke 6 (macOS pgrep-P availability):
command -v pgrep && pgrep -P $$ >/dev/null; echo $?returns 0 on both Linux and macOS (BSD). If the executor's host happens to lackpgrep(extremely rare), the fallback path falls through to wrapper-only kill (the pre-patch behavior) — this is acceptable degradation per CLAUDE.md §macOS compatibility." - "Smoke 7 (bats baseline holds):
bats tests/unit/reports 246/246 PASS — no regressions from the lib/parallel.sh changes. No new tests added in this phase (Phase 4 / TEST-01 explicitly covers parallel_funcs timeout-kill coverage per CONTEXT.md)."
- "Setting
Close the two compound defects that make Plan 01-03's `PARALLEL_JOB_TIMEOUT_SECONDS` enforcement silently disabled under `--quiet` (CR-02) and ineffective at stopping the underlying tool (CR-03). Both fixes live in `lib/parallel.sh` and share the same change site, so they are bundled into one plan rather than artificially split.
Purpose: 01-VERIFICATION.md marked SC3 PARTIAL with two compound defects.
- CR-02 (Gap B): The timeout-kill check sits inside
if [[ ${PARALLEL_MODE} == true ]] && [[ ${OUTPUT_VERBOSITY:-1} -ge 1 ]] ...atlib/parallel.sh:469and:579. Under--quiet(OUTPUT_VERBOSITY=0) the entire while-loop is skipped — no timeout-kill runs. The cfg comment atreconftw.cfg:314-317explicitly recommendsPARALLEL_JOB_TIMEOUT_SECONDS=600for CI, and CI runs are precisely where--quietis used → the feature is silently disabled in its documented primary use case. - CR-03 (Gap C):
_timeout_kill_jobatlib/parallel.sh:53-77signals the wrapper subshell PID stored inbatch_pids[$idx](the$!of the(...) >$log_file &at:438). SIGTERM to a Bash subshell does NOT auto-propagate to its children. Verified empirically: the wrapper dies butsleep 30(acting as a stand-in for puredns/dnsx/ffuf) keeps running orphaned to PID 1. On axiom-distributed runs the remote workers also keep going because the localaxiom-scanwrapper is the orphan path.
Both defects undermine SC3's headline guarantee ("terminates any single parallel_funcs child exceeding 10 minutes via kill -TERM, allowing the batch to continue") — the BATCH does continue, but the actual TOOL doesn't terminate. This plan closes both.
Output:
lib/parallel.sh: decoupled gate at the two heartbeat-loop entry conditions (:469and:579). The loop runs when (timeout is enabled) OR (verbosity wants UI). Heartbeat snapshots fire only on the verbosity arm; timeout enforcement fires unconditionally inside the loop body.lib/parallel.sh: new private helper_kill_tree(declared above_timeout_kill_jobnear the existing_throttle_jobsat :33-42) that walks the process tree viapgrep -Pand signals each descendant. Falls back to wrapper-only kill ifpgrepis unavailable (CLAUDE.md macOS compatibility).lib/parallel.sh:_timeout_kill_jobbody updated to call_kill_tree $pid TERM, poll up toPARALLEL_KILL_GRACE_SECONDS, then_kill_tree $pid KILLif still alive. The persistence writes (FAIL + reason=timeout) andlog_jsoncall remain unchanged — only the kill mechanism is replaced.reconftw.cfg: NO changes (the existing comment at:317is already accurate post-fix; D-11 default0and D-13 grace10remain locked).
No new tests; Phase 4 (TEST-01) covers parallel_funcs timeout-kill regression coverage per CONTEXT.md §Claude's Discretion.
@$HOME/.claude/get-shit-done/workflows/execute-plan.md @$HOME/.claude/get-shit-done/templates/summary.md @.planning/PROJECT.md @.planning/ROADMAP.md @.planning/STATE.md @.planning/phases/01-resilient-resume-timeout-safety/01-CONTEXT.md @.planning/phases/01-resilient-resume-timeout-safety/01-PATTERNS.md @.planning/phases/01-resilient-resume-timeout-safety/01-VERIFICATION.md @.planning/phases/01-resilient-resume-timeout-safety/01-REVIEW.md @.planning/phases/01-resilient-resume-timeout-safety/01-03-SUMMARY.md @.planning/codebase/CONVENTIONS.mdFrom lib/parallel.sh (post-Plan-01-03 state):
- Source guard at
:6:[[ -n "$_PARALLEL_SH_LOADED" ]] && return 0. UNCHANGED. _throttle_jobs()at:33-42. Sibling style for new_kill_treehelper. Uses barename() {form (pre-dates CONVENTIONS.md rule — see Plan 01-03's DOCS-01 followup note for context)._timeout_kill_job()at:53-77. Current body useskill -TERM "$pid"/kill -KILL "$pid"against the single wrapper PID. THIS is what gets refactored to use_kill_tree. The function uses canonicalfunction name() {form per CONVENTIONS.md._parallel_live_break()at:79-83. UNCHANGED. New_kill_treehelper inserts BETWEEN_throttle_jobs(closes at :42) and_timeout_kill_job(opens at :53).- Batch-flush heartbeat loop at
:467-506. Current gate at:469:if [[ "${PARALLEL_MODE:-true}" == "true" ]] && [[ "${OUTPUT_VERBOSITY:-1}" -ge 1 ]] && [[ "$hb" =~ ^[0-9]+$ ]] && ((hb > 0)); then. The timeout-enforcement block is inside this gatedifat:481-486(added by Plan 01-03). THIS gate gets decoupled. - Final-wait heartbeat loop at
:577-616. Identical structure to batch-flush; same gate at:579. Same insertion: decouple the verbosity check from the timeout-enforcement check. - Wrapper-subshell spawn site at
:432-438:(...) >"$log_file" 2>&1 &; batch_pids+=("$!"). UNCHANGED — the pgid approach was rejected (see code_landmarks above) becauseset +matmodules/modes.sh:16deliberately disables job control. The_kill_treewalk operates against the existing wrapper PID.
From modules/modes.sh:
start()at:16:set +m 2>/dev/null || true. This explicitly disables job control globally, which is why the process-group approach was rejected. The_kill_treerecursive walk is the portable approach.
From CLAUDE.md §macOS compatibility:
- macOS Homebrew Bash is required (
bash4.3+);pgrepfrom procps (Linux) and fromprocps-ng(or BSD-nativepgrepon macOS) both support-P <ppid>. POSIX-portable enough for reconftw's supported targets.psflag differences (-o pgid=on BSD vso pgid=on GNU) are sidestepped by usingpgrep -P(which is universal for the "list children of PID" use case).
Existing (post-Plan-01-03 state — actual line numbers may have shifted slightly but the structure is intact):
```
# Heartbeat while long-running jobs are executing, to avoid "stuck" perception.
local hb="${PARALLEL_HEARTBEAT_SECONDS:-20}"
if [[ "${PARALLEL_MODE:-true}" == "true" ]] && [[ "${OUTPUT_VERBOSITY:-1}" -ge 1 ]] && [[ "$hb" =~ ^[0-9]+$ ]] && ((hb > 0)); then
local last_hb now alive hb_active_list job_dur dur_fmt queue_count batch_elapsed hb_done_count
...
while :; do
...
for idx in "${!batch_pids[@]}"; do
if kill -0 "${batch_pids[$idx]}" 2>/dev/null; then
alive=1
job_dur=$((now - batch_starts[$idx]))
# Timeout enforcement (RESIL-03 / D-11..D-14)
local _to="${PARALLEL_JOB_TIMEOUT_SECONDS:-0}"
if [[ "$_to" =~ ^[0-9]+$ ]] && (( _to > 0 )) && (( job_dur > _to )); then
_timeout_kill_job "${batch_pids[$idx]}" "${batch_funcs[$idx]}" "$job_dur"
fi
...
fi
done
((alive == 0)) && break
if ((now - last_hb >= hb)); then
...
_parallel_snapshot ...
last_hb=$now
fi
sleep 1
done
fi
```
Rewrite the entry-gate block. The new structure: read `_to` and `_verbose_progress` ONCE before the loop entry (hoisted out of the hot inner loop per CR-related WR-02 advisory in 01-REVIEW.md §IN-02 micro-optimization, which is a clean co-fix here), then enter the loop when `_to > 0 OR _verbose_progress=true`:
```
# Heartbeat while long-running jobs are executing, to avoid "stuck" perception.
# Loop runs when EITHER timeout enforcement is active OR verbose progress is on;
# snapshots fire only when verbose progress is on. Decoupled per CR-02 fix so
# PARALLEL_JOB_TIMEOUT_SECONDS works under --quiet (the documented CI scenario at
# reconftw.cfg:317).
local hb="${PARALLEL_HEARTBEAT_SECONDS:-20}"
local _to="${PARALLEL_JOB_TIMEOUT_SECONDS:-0}"
[[ "$_to" =~ ^[0-9]+$ ]] || _to=0
local _verbose_progress=false
[[ "${PARALLEL_MODE:-true}" == "true" ]] && [[ "${OUTPUT_VERBOSITY:-1}" -ge 1 ]] && _verbose_progress=true
local _loop_active=false
[[ "${PARALLEL_MODE:-true}" == "true" ]] && [[ "$hb" =~ ^[0-9]+$ ]] && ((hb > 0)) && _loop_active=true
if [[ "$_loop_active" == "true" ]] && { [[ "$_verbose_progress" == "true" ]] || (( _to > 0 )); }; then
local last_hb now alive hb_active_list job_dur dur_fmt queue_count batch_elapsed hb_done_count
last_hb=$(date +%s)
while :; do
alive=0
hb_done_count=0
hb_active_list=""
now=$(date +%s)
for idx in "${!batch_pids[@]}"; do
if kill -0 "${batch_pids[$idx]}" 2>/dev/null; then
alive=1
job_dur=$((now - batch_starts[$idx]))
# Timeout enforcement (RESIL-03 / D-11..D-14): fires regardless of
# verbosity (CR-02 fix). Uses hoisted _to from outer scope.
if (( _to > 0 )) && (( job_dur > _to )); then
_timeout_kill_job "${batch_pids[$idx]}" "${batch_funcs[$idx]}" "$job_dur"
fi
dur_fmt=$(format_duration "$job_dur")
if [[ -z "$hb_active_list" ]]; then
hb_active_list="${batch_funcs[$idx]} ${dur_fmt}"
else
hb_active_list="${hb_active_list}, ${batch_funcs[$idx]} ${dur_fmt}"
fi
else
hb_done_count=$((hb_done_count + 1))
fi
done
((alive == 0)) && break
if [[ "$_verbose_progress" == "true" ]] && ((now - last_hb >= hb)); then
queue_count=$((total_funcs - queued_count))
batch_elapsed=$((now - batch_start_ts))
_parallel_snapshot "${hb_active_list:-none}" "$done_list" "$queue_count" "$hb_done_count" "${#batch_pids[@]}" "$batch_elapsed"
last_hb=$now
fi
sleep 1
done
fi
```
Key changes:
1. `_to`, `_verbose_progress`, `_loop_active` declared and computed ONCE outside the inner loop (was per-iteration before — IN-02 micro-fix folded in).
2. The loop-entry condition is now `_loop_active AND (_verbose_progress OR _to > 0)`.
3. The timeout-enforcement `if` inside the loop body drops the `[[ "$_to" =~ ^[0-9]+$ ]]` regex check (already validated outside the loop) and is no longer behind any verbosity gate.
4. The `_parallel_snapshot` call is now wrapped in an explicit `if [[ "$_verbose_progress" == "true" ]] && ...; then` — heartbeat UI fires only when verbosity wants it; timeout still fires unconditionally.
DO NOT remove the `[[ "${PARALLEL_MODE:-true}" == "true" ]]` part of the gate — disabling parallel mode entirely should still bypass both the timeout-enforcement AND the snapshots (no batch is running, no PID to kill, no UI to show). The `_loop_active` boolean captures this.
DO NOT remove the `[[ "$hb" =~ ^[0-9]+$ ]] && ((hb > 0))` check — if heartbeat is misconfigured to a non-positive value, the loop's `sleep 1` cadence would still work, but the `last_hb`/`now - last_hb >= hb` math becomes meaningless. Acknowledging the WR-05 concern from 01-REVIEW.md: per-the-advisory, document this in the new comment block above the gate (added in this task). Honour the existing semantic that `PARALLEL_HEARTBEAT_SECONDS=0` disables the loop entirely. If a future user sets both `PARALLEL_HEARTBEAT_SECONDS=0` AND `PARALLEL_JOB_TIMEOUT_SECONDS=600`, the timeout enforcement is also disabled — this is the existing behavior; WR-05 in 01-REVIEW.md flagged it as a documentation concern, not a blocking gap. Add an inline comment near the `_loop_active` declaration: `# NB: PARALLEL_HEARTBEAT_SECONDS=0 disables the loop entirely, which also disables timeout enforcement. WR-05 documented this; resolve in Phase 5 DOCS-01 if it surfaces in practice.`
Step B — Apply the IDENTICAL refactor to the FINAL-WAIT heartbeat loop at `lib/parallel.sh:577-616`. The structure is character-for-character the same as the batch-flush loop above; the same hoisted-locals + decoupled gate + unconditional timeout check + verbosity-gated snapshot pattern goes in. Two-loop symmetry is mandatory per Plan 01-03's established pattern (and the 01-PATTERNS.md §"Two-loop symmetry" entry).
DO NOT introduce subtle differences between the two loops (different gate ordering, different boolean name, different comment wording). The grep-based acceptance criteria below check that both loops have the same shape.
Step C — Verify NO other gates need decoupling. Search the rest of `lib/parallel.sh` for any other `OUTPUT_VERBOSITY`-gated block that contains a timeout reference: `grep -n 'OUTPUT_VERBOSITY' lib/parallel.sh` and inspect each match. The only matches that gate timeout enforcement are the two heartbeat loops. Other matches (`_parallel_should_show_started`, `_parallel_should_show_finished`, the per-mode rendering branches in `_parallel_emit_job_output`) are UI-only and stay verbosity-gated as designed.
bash -n /Users/six2dez/Tools/reconftw/lib/parallel.sh && shellcheck -s bash --severity=error /Users/six2dez/Tools/reconftw/lib/parallel.sh
- The compound verbosity-AND-timeout-AND-everything gate at the old `:469` is GONE: `grep -cE '"\${PARALLEL_MODE:-true}" == "true" \]\] && \[\[ "\${OUTPUT_VERBOSITY:-1}" -ge 1 \]\] && \[\[ "\$hb" =~' /Users/six2dez/Tools/reconftw/lib/parallel.sh` returns 0 (the all-in-one compound gate is replaced by the hoisted-booleans pattern).
- `_to`, `_verbose_progress`, `_loop_active` locals appear: `grep -c 'local _to="\${PARALLEL_JOB_TIMEOUT_SECONDS:-0}"' /Users/six2dez/Tools/reconftw/lib/parallel.sh` returns exactly 2 (one per loop — two-loop symmetry); `grep -c 'local _verbose_progress=false' /Users/six2dez/Tools/reconftw/lib/parallel.sh` returns exactly 2; `grep -c 'local _loop_active=false' /Users/six2dez/Tools/reconftw/lib/parallel.sh` returns exactly 2.
- The new compound gate fires the loop when `_loop_active && (_verbose_progress || _to > 0)`: `grep -cE 'if \[\[ "\$_loop_active" == "true" \]\] && \{ \[\[ "\$_verbose_progress" == "true" \]\] \|\| \(\( _to > 0 \)\); \};' /Users/six2dez/Tools/reconftw/lib/parallel.sh` returns exactly 2.
- Timeout-enforcement check inside the loop body no longer references verbosity (it's now unconditional inside the loop): `awk '/if \[\[ "\$_loop_active"/,/^[[:space:]]+fi[[:space:]]*$/' /Users/six2dez/Tools/reconftw/lib/parallel.sh | grep -c '(( _to > 0 )) && (( job_dur > _to ))'` returns >=2 (one per loop; awk range matches both).
- `_parallel_snapshot` call is wrapped in a verbosity guard: `grep -cE 'if \[\[ "\$_verbose_progress" == "true" \]\] && \(\(now - last_hb >= hb\)\); then' /Users/six2dez/Tools/reconftw/lib/parallel.sh` returns exactly 2.
- The CR-02 explanatory comment is present: `grep -c 'CR-02 fix' /Users/six2dez/Tools/reconftw/lib/parallel.sh` returns >=2 (one per loop).
- The WR-05 documentation note is present: `grep -c 'WR-05' /Users/six2dez/Tools/reconftw/lib/parallel.sh` returns >=2 (one per loop) OR a single shared upstream comment block that both loops reference.
- No other `OUTPUT_VERBOSITY`-gated block was inadvertently modified: `grep -n 'OUTPUT_VERBOSITY' lib/parallel.sh` shows the existing UI-only branches (e.g., `_parallel_should_show_started`, the rendering branches in `_parallel_emit_job_output`) unchanged. Spot-check via `grep -c '_parallel_should_show_started' /Users/six2dez/Tools/reconftw/lib/parallel.sh` returns the same count as pre-patch.
- Two-loop symmetry holds — the same patterns appear in both loops: the four key patterns (`local _to=...`, `local _verbose_progress=false`, `local _loop_active=false`, the decoupled compound gate) each return exactly 2 occurrences as asserted above.
- `bash -n lib/parallel.sh` exits 0.
- `shellcheck -s bash --severity=error lib/parallel.sh` exits 0 (no NEW error-level findings vs baseline).
- Behavior smoke (CR-02 reproduction): write `/tmp/quiet_timeout.sh` that sources `./reconftw.sh --source-only`, defines `function my_slow_func() { sleep 30; }`, sets `called_fn_dir=$(mktemp -d) PARALLEL_JOB_TIMEOUT_SECONDS=2 PARALLEL_KILL_GRACE_SECONDS=1 PARALLEL_HEARTBEAT_SECONDS=1 PARALLEL_MODE=true OUTPUT_VERBOSITY=0`, then runs `time parallel_funcs 1 my_slow_func`. The job MUST be killed within ~5 seconds (pre-patch: 30+ seconds because the loop never runs under verbosity 0). Verify `cat $called_fn_dir/.status_my_slow_func` shows `FAIL` and `cat $called_fn_dir/.status_reason_my_slow_func` shows `timeout`. The console MUST NOT show heartbeat lines (verbosity 0).
- Behavior smoke (verbosity-1 unchanged): same script but with `OUTPUT_VERBOSITY=1`. Behavior identical to Plan 01-03 baseline — job killed within ~5s, FAIL+timeout persisted, AND heartbeat lines visible on console. The verbose path is unchanged.
- Behavior smoke (default-disabled): same script with `PARALLEL_JOB_TIMEOUT_SECONDS=0` (the shipped default) and any verbosity. Job MUST run to natural completion (no kill) regardless of verbosity — backwards compatibility holds.
- bats baseline: `bats tests/unit/` reports 246/246 PASS.
Both heartbeat loops at `lib/parallel.sh:467-506` (batch-flush) and `:577-616` (final-wait) now have the decoupled gate — hoisted `_to`/`_verbose_progress`/`_loop_active` locals, loop entry on `_loop_active && (_verbose_progress || _to > 0)`, unconditional timeout-enforcement inside the loop body, verbosity-gated `_parallel_snapshot`. CR-02 explanatory comment and WR-05 documentation note present. Two-loop symmetry preserved. Behavior smokes confirm timeout fires under `--quiet` and heartbeats stay verbosity-gated. `bash -n` and `shellcheck` clean; 246/246 bats pass.
Task 2: Add `_kill_tree` helper and refactor `_timeout_kill_job` to walk the process tree
lib/parallel.sh
- lib/parallel.sh (full body of `_timeout_kill_job` at :53-77 — note the current `kill -TERM "$pid"` / poll-loop / `kill -KILL "$pid"` sequence that this task replaces; also note the `_throttle_jobs` helper at :33-42 for sibling-style positioning of the new `_kill_tree`)
- .planning/phases/01-resilient-resume-timeout-safety/01-VERIFICATION.md (CR-03 missing item: "Use a process-group kill (`kill -TERM -- -`) or a recursive child kill (`pgrep -P` walk) so the actual tool process and any axiom-distributed children are signaled, not just the wrapper.")
- .planning/phases/01-resilient-resume-timeout-safety/01-REVIEW.md (CR-03 — exact `_kill_tree` recursive walk recommendation: "_kill_tree() { local parent=$1 sig=$2; local child; for child in $(pgrep -P $parent 2>/dev/null); do _kill_tree $child $sig; done; kill -$sig $parent 2>/dev/null || true; }")
- .planning/codebase/CONVENTIONS.md (Function Naming: `function name() {` form for new code; Underscore-prefix-private helpers)
- CLAUDE.md (Constraints: macOS Homebrew Bash 4+; pgrep available on both Linux procps and BSD/macOS; setsid is Linux-only and NOT used here)
- modules/modes.sh :16 (`set +m 2>/dev/null || true` — job control deliberately disabled; this is why the pgid approach was rejected in favor of the `pgrep -P` walk)
Step A — Add the new `_kill_tree` helper to `lib/parallel.sh`. Insert it IMMEDIATELY AFTER the existing `_throttle_jobs` function (which closes at `:42`) and IMMEDIATELY BEFORE the existing comment block above `_timeout_kill_job` (which currently starts at `:44`). Declare using canonical `function _kill_tree() {` form per CONVENTIONS.md.
The exact insertion:
```
# Recursively signal a process and all its descendants. Used by
# _timeout_kill_job to kill the actual external tool (puredns, dnsx, ffuf,
# axiom-scan, etc.) inside the parallel_funcs wrapper subshell, not just
# the wrapper itself (CR-03 fix). Walks the process tree via `pgrep -P`
# which is available on both Linux (procps) and macOS (BSD pgrep). If
# pgrep is missing on the host, the walk degrades gracefully to a
# wrapper-only kill (matches pre-patch behavior) so the run does not fail.
# Process-group kill via `kill -- -<pgid>` was rejected because start() at
# modules/modes.sh:16 explicitly disables job control (`set +m`), so the
# wrapper subshell does not get its own pgid; flipping `set -m` for one
# corner case is intrusive across the codebase.
function _kill_tree() {
local parent="$1" sig="${2:-TERM}"
local child
# Recurse into children first so deeper leaves get signaled before the
# parent — protects against a parent re-spawning children on signal.
if command -v pgrep >/dev/null 2>&1; then
for child in $(pgrep -P "$parent" 2>/dev/null); do
_kill_tree "$child" "$sig"
done
fi
kill "-$sig" "$parent" 2>/dev/null || true
}
```
Notes on the recursion order: children-first-then-parent is the standard Unix idiom for tree kills — signaling the parent last gives any deeper descendants a chance to be cleaned up first, and a SIGTERM-then-SIGKILL pattern in the caller (`_timeout_kill_job`) handles the parent's own tool process. The `command -v pgrep` guard ensures graceful degradation if the host happens to lack `pgrep` (extremely rare; CLAUDE.md targets reconftw-supported environments where `pgrep` is universally available, but defense in depth is cheap).
Step B — Refactor `_timeout_kill_job` at `lib/parallel.sh:53-77`. The current body's kill sequence:
```
# D-13: TERM first, then KILL after grace seconds for tools that ignore TERM.
kill -TERM "$pid" 2>/dev/null || true
local i
for ((i=0; i<grace; i++)); do
kill -0 "$pid" 2>/dev/null || break
sleep 1
done
kill -KILL "$pid" 2>/dev/null || true
```
Replace with:
```
# D-13: TERM first, then KILL after grace seconds for tools that ignore TERM.
# CR-03 fix: kill the entire process tree under the wrapper PID so the actual
# external tool (puredns, dnsx, ffuf, axiom-scan, etc.) terminates — not just
# the wrapper subshell. Pre-patch behavior signaled only $pid (the wrapper),
# leaving the tool orphaned to PID 1 and continuing past the timeout.
_kill_tree "$pid" TERM
local i
for ((i=0; i<grace; i++)); do
kill -0 "$pid" 2>/dev/null || break
sleep 1
done
_kill_tree "$pid" KILL
```
Key changes:
1. `kill -TERM "$pid"` becomes `_kill_tree "$pid" TERM` — signals the wrapper AND all descendants.
2. `kill -KILL "$pid"` becomes `_kill_tree "$pid" KILL` — same.
3. The poll loop using `kill -0 "$pid"` is UNCHANGED — it still checks the wrapper PID specifically (not the descendants), which is the correct gate: once the wrapper exits, the parallel_funcs `wait` returns and the parallel batch progresses. The descendants are killed inside the tree walk; their reaping is the kernel's job.
4. The persistence writes (`.status_<fn>=FAIL`, `.status_reason_<fn>=timeout`) and the `log_json` call are UNCHANGED. Only the kill mechanism is replaced.
DO NOT modify the function signature (`_timeout_kill_job <pid> <func_name> <duration_sec>`). DO NOT modify the `local pid="$1" func_name="$2" duration_sec="$3"` line. DO NOT modify the `local grace="${PARALLEL_KILL_GRACE_SECONDS:-10}"` line or its integer guard. DO NOT add new helper parameters — `_kill_tree` is a fixed-arity helper that operates on `pid + sig`; the caller wraps it.
Step C — Verify the helper integrates cleanly. After both edits land, the file should parse with `bash -n`, pass `shellcheck`, and the existing call sites of `_timeout_kill_job` (two of them, inside the two heartbeat loops modified in Task 1) should remain UNCHANGED. The change is hidden behind the helper boundary — callers see the same signature.
Behavior risk: `pgrep -P` returns children at the time of the call. If new children are spawned between the call and the actual kill, those new descendants will not be signaled. For reconftw's use case (kill a tool that has stalled), this is acceptable — a stalled tool is not spawning children. If concurrent spawning becomes an issue in future, the tree walk can be repeated inside the grace loop; for v1 the one-shot walk is sufficient.
macOS sanity check: `pgrep -P <pid>` is POSIX-portable. macOS (BSD) supports `pgrep` from at least 10.8 onwards; reconftw's macOS target via Homebrew Bash is well within that range.
bash -n /Users/six2dez/Tools/reconftw/lib/parallel.sh && shellcheck -s bash --severity=error /Users/six2dez/Tools/reconftw/lib/parallel.sh
- `_kill_tree` helper declared with canonical form: `grep -cE '^function _kill_tree\(\) \{' /Users/six2dez/Tools/reconftw/lib/parallel.sh` returns exactly 1.
- The recursive walk via `pgrep -P` is present inside `_kill_tree`: `awk '/^function _kill_tree\(\) \{/,/^}/' /Users/six2dez/Tools/reconftw/lib/parallel.sh | grep -c 'pgrep -P "\$parent"'` returns >=1.
- The graceful-degradation `command -v pgrep` guard is present: `awk '/^function _kill_tree\(\) \{/,/^}/' /Users/six2dez/Tools/reconftw/lib/parallel.sh | grep -c 'command -v pgrep'` returns >=1.
- The parent `kill` is called LAST (children-first-then-parent ordering): `awk '/^function _kill_tree\(\) \{/,/^}/' /Users/six2dez/Tools/reconftw/lib/parallel.sh | awk '/pgrep -P "\$parent"/{p=NR} /kill "-\$sig" "\$parent"/{c=NR} END{print (p && c && p/dev/null || break'` returns exactly 1.
- The persistence writes are UNCHANGED: `awk '/^function _timeout_kill_job\(\) \{/,/^}/' /Users/six2dez/Tools/reconftw/lib/parallel.sh | grep -c 'printf "FAIL\\\\n" >"\${called_fn_dir}/\.status_\${func_name}"'` returns >=1 (the existing FAIL persistence) and `grep -c 'printf "timeout\\\\n" >"\${called_fn_dir}/\.status_reason_\${func_name}"'` returns >=1. (Note: double-escaping in `grep` can be finicky; `grep -F` fixed-string mode is acceptable for verification — the existing `01-03-SUMMARY.md` notes this exact issue.)
- The `log_json` call is UNCHANGED: `awk '/^function _timeout_kill_job\(\) \{/,/^}/' /Users/six2dez/Tools/reconftw/lib/parallel.sh | grep -c 'log_json "ERROR" "\${func_name}" "Job timed out" "reason=timeout"'` returns >=1.
- The CR-03 explanatory comment is present inside `_timeout_kill_job`: `awk '/^function _timeout_kill_job\(\) \{/,/^}/' /Users/six2dez/Tools/reconftw/lib/parallel.sh | grep -c 'CR-03 fix'` returns >=1.
- The `_kill_tree` helper's docstring mentions the rejected pgid approach: `awk '/^function _kill_tree\(\) \{/{f=1} f && /^}/{exit} 1' /Users/six2dez/Tools/reconftw/lib/parallel.sh | head -20 | grep -cE 'set \+m|Process-group kill.*rejected|pgid'` returns >=1 (one or more references to why the pgid approach was not used).
- Call sites of `_timeout_kill_job` are UNCHANGED (still 2 occurrences, one per heartbeat loop): `grep -c '_timeout_kill_job "\${batch_pids\[\$idx\]}" "\${batch_funcs\[\$idx\]}" "\$job_dur"' /Users/six2dez/Tools/reconftw/lib/parallel.sh` returns exactly 2.
- `bash -n lib/parallel.sh` exits 0.
- `shellcheck -s bash --severity=error lib/parallel.sh` exits 0 (no NEW error-level findings).
- Behavior smoke (CR-03 reproduction — inner tool dies): write `/tmp/inner_kill.sh` that (1) sources `./reconftw.sh --source-only`, (2) defines `function my_slow_func() { sleep 30 & local inner=$!; echo $inner > /tmp/inner.pid; wait; }`, (3) sets `called_fn_dir=$(mktemp -d) PARALLEL_JOB_TIMEOUT_SECONDS=2 PARALLEL_KILL_GRACE_SECONDS=1 PARALLEL_HEARTBEAT_SECONDS=1 PARALLEL_MODE=true OUTPUT_VERBOSITY=1`, (4) runs `parallel_funcs 1 my_slow_func`. After ~5s the wrapper PID is dead AND `kill -0 $(cat /tmp/inner.pid) 2>/dev/null` returns non-zero (inner process also dead). With the pre-patch code the inner `sleep 30` would survive as an orphan; post-patch it's reaped within the grace window. Confirm with `ps -p $(cat /tmp/inner.pid) -o stat= 2>/dev/null` returning empty.
- Behavior smoke (multi-level tree — exercises the recursion): same script but `function my_slow_func() { ( sleep 30 ) & local inner=$!; echo $inner > /tmp/inner.pid; wait; }` (note the extra subshell wrapping the sleep). After timeout, both the inner subshell PID AND its `sleep 30` child must be dead. The recursive `_kill_tree` walks two levels deep.
- Behavior smoke (pgrep-missing graceful degradation): in a controlled env, temporarily mask `pgrep` (e.g., `function pgrep() { return 1; }`) and run the smoke. The `_kill_tree` falls back to wrapper-only kill (matches pre-patch behavior); the wrapper dies but the inner `sleep 30` may survive. This is acceptable degradation — log the pre-patch wallclock difference to confirm the fallback path was exercised. (This smoke is informational; the acceptance criterion is that the run does not error out — `bash -c './lib/parallel.sh ...'` exits 0.)
- bats baseline: `bats tests/unit/` reports 246/246 PASS.
`_kill_tree` helper added between `_throttle_jobs` and `_timeout_kill_job` with `function _kill_tree() {` canonical form, `pgrep -P` recursive walk, children-first-then-parent ordering, and `command -v pgrep` graceful-degradation guard. `_timeout_kill_job` body now calls `_kill_tree $pid TERM` and `_kill_tree $pid KILL` instead of the bare `kill` against the wrapper PID. The persistence writes, `log_json` call, and `kill -0` poll are UNCHANGED. Call sites of `_timeout_kill_job` are UNCHANGED (still 2). CR-03 smoke reproduction (inner `sleep 30` dies along with the wrapper) passes. `bash -n` and `shellcheck` clean; 246/246 bats pass.
- `bash -n lib/parallel.sh` → exit 0.
- `shellcheck -s bash --severity=error lib/parallel.sh` → exit 0 (no NEW error-level findings vs baseline).
- `bats tests/unit/` → 246/246 PASS (no new tests in this phase per CONTEXT.md §Claude's Discretion).
- `bats tests/security/` → no regressions.
- Behavioral smokes (composed Task 1 + Task 2):
1. **CR-02 reproduction (timeout fires under --quiet)**: set `PARALLEL_JOB_TIMEOUT_SECONDS=2 OUTPUT_VERBOSITY=0`, run `parallel_funcs 1 my_slow_func` where the function sleeps 30. Within ~5s the job is killed, `.status_my_slow_func=FAIL`, `.status_reason_my_slow_func=timeout`. Pre-patch the same setup runs the full 30s without killing it.
2. **CR-03 reproduction (inner tool dies)**: same setup but with verbosity 1 and a slow function that backgrounds an inner `sleep 30` and captures its PID. After ~5s both the wrapper AND the inner PID are dead. Pre-patch only the wrapper dies; the inner sleep orphans to PID 1.
3. **Heartbeat-UI still verbosity-gated (regression check)**: with `PARALLEL_JOB_TIMEOUT_SECONDS=0 OUTPUT_VERBOSITY=0`, the loop runs only when needed (or not at all); no heartbeat snapshots on the console. With `OUTPUT_VERBOSITY=1` the heartbeats appear as before. Proves the gate is decoupled, not removed.
4. **Default-disabled backwards compat**: `PARALLEL_JOB_TIMEOUT_SECONDS=0` (the shipped default), any verbosity — `normal_func` runs to natural completion, no kill, no FAIL, no orphans.
5. **Two-loop symmetry**: a 3-function batch with `PARALLEL_MAX_JOBS=2` where only the 3rd function is slow exercises the final-wait loop's timeout path. The 3rd function gets killed by the final-wait loop's modified gate.
- Pattern-level checks:
6. `grep -c 'local _to="\${PARALLEL_JOB_TIMEOUT_SECONDS:-0}"' lib/parallel.sh` returns 2 (both heartbeat loops hoist `_to` to the outer scope).
7. `grep -c 'CR-02 fix' lib/parallel.sh` returns >=2; `grep -c 'CR-03 fix' lib/parallel.sh` returns >=1.
8. `_kill_tree` is positioned between `_throttle_jobs` and `_timeout_kill_job`; uses `pgrep -P` recursive walk; signals children first then parent; falls back gracefully when `pgrep` is missing.
- Gaps B and C from `01-VERIFICATION.md` are closed: SC3 transitions PARTIAL → VERIFIED. `PARALLEL_JOB_TIMEOUT_SECONDS` enforcement runs under `--quiet` (CR-02 fix), and the kill signals the entire process tree under the wrapper PID — not just the wrapper itself (CR-03 fix).
- Default `PARALLEL_JOB_TIMEOUT_SECONDS=0` is preserved (D-11 locked); the feature remains opt-in and backwards-compatible.
- Heartbeat-snapshot UI remains gated on `OUTPUT_VERBOSITY >= 1` — only the timeout-enforcement and kill mechanism are decoupled. Verbosity 0 still gets a quiet console exactly as the user requested.
- Two-loop symmetry preserved: the batch-flush and final-wait heartbeat loops have identical structure post-fix (verified by grep counts returning exactly 2 for each key pattern).
- macOS compatibility holds: `pgrep -P` is available on both Linux procps and BSD/macOS pgrep; `setsid` (Linux-only) is NOT used; the rejected pgid approach is documented inside the `_kill_tree` helper's docstring.
- No bats tests added (Phase 4 / TEST-01 owns parallel_funcs timeout-kill coverage); the 246/246 baseline holds.
- Call sites of `_timeout_kill_job` remain UNCHANGED — only the helper's internal kill mechanism is replaced. The change is transparent to the surrounding `parallel_funcs` logic.