Skip to content

Conversation

@marcusquinn
Copy link
Owner

@marcusquinn marcusquinn commented Feb 9, 2026

Summary

  • Add trap 'rm -f "$var"' RETURN cleanup for all remaining mktemp usages that lacked trap protection
  • Prevents temp file leaks on unexpected exits, early returns, or errors
  • Covers 12 additional files missed by the initial pass (loop-common.sh, quality-fix.sh, ralph-loop-helper.sh, site-crawler-helper.sh, verify-run-helper.sh, test-supervisor-state-machine.sh, and 6 archive scripts)
  • Combined with the first commit, all ~90 mktemp usages across the codebase now have trap cleanup

Changes

Active scripts (7 files):

  • loop-common.sh — 3 locations (receipt tracking, attempt tracking, task blocking)
  • quality-fix.sh — 3 locations (return statement fixer, positional params, string analysis)
  • ralph-loop-helper.sh — 1 location (iteration increment)
  • site-crawler-helper.sh — 1 location (queue processing)
  • verify-run-helper.sh — 1 location (verify status update)

Test files (1 file):

  • test-supervisor-state-machine.sh — consolidated EXIT trap to cover all 4 mktemp -d dirs

Archive scripts (6 files):

  • _archive/add-missing-returns.sh, fix-common-strings.sh, fix-s131-default-cases.sh, fix-sc2155-simple.sh, fix-shellcheck-critical.sh, fix-string-literals.sh

Verification

  • All modified files pass bash -n syntax check
  • Trap pattern uses single quotes (avoids SC2064 shellcheck warning)
  • Uses RETURN for function-scoped cleanup, EXIT for script-level cleanup

Summary by CodeRabbit

  • Chores
    • Improved resource cleanup in shell scripts by adding automatic temporary file removal on function exit across multiple scripts, ensuring no leftover temporary files and reducing potential resource leaks.

Add trap EXIT/RETURN cleanup for mktemp files to prevent temp file
leaks on unexpected exits. Scripts modified:
- supervisor-helper.sh (4 locations)
- setup.sh (3 locations)
- aidevops.sh, cron-helper.sh, matrix-dispatch-helper.sh
- add-skill-helper.sh, full-loop-helper.sh, objective-runner-helper.sh
- coderabbit-collector-helper.sh, coderabbit-task-creator-helper.sh
- schema-validator-helper.sh, sops-helper.sh, agent-test-helper.sh
Complete trap EXIT/RETURN cleanup coverage for all mktemp usages.
Previous commit covered 14 scripts; this adds traps to 12 more files
that were missed — loop-common.sh, quality-fix.sh, ralph-loop-helper.sh,
site-crawler-helper.sh, verify-run-helper.sh, test-supervisor-state-machine.sh,
and 6 archive scripts.
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 9, 2026

Walkthrough

This PR systematically adds RETURN traps across 24 shell scripts to ensure temporary files created via mktemp are automatically removed on function exit. The changes apply to archive scripts, helper scripts, main entry points, and test files, totaling 50 lines of cleanup logic additions.

Changes

Cohort / File(s) Summary
Archive Script Cleanup Traps
.agents/scripts/_archive/add-missing-returns.sh, fix-common-strings.sh, fix-s131-default-cases.sh, fix-sc2155-simple.sh, fix-shellcheck-critical.sh, fix-string-literals.sh
Added trap 'rm -f "$temp_file"' RETURN to ensure temporary files are cleaned up on function exit across multiple fix and analysis functions.
Helper Scripts - Single Trap
.agents/scripts/add-skill-helper.sh, agent-test-helper.sh, full-loop-helper.sh, objective-runner-helper.sh, ralph-loop-helper.sh, schema-validator-helper.sh, site-crawler-helper.sh, sops-helper.sh, verify-run-helper.sh
Each function now registers a cleanup trap for its temporary file(s) on RETURN, ensuring automatic deletion regardless of exit conditions.
Helper Scripts - Multi-Function Traps
.agents/scripts/coderabbit-collector-helper.sh, coderabbit-task-creator-helper.sh, cron-helper.sh, loop-common.sh, matrix-dispatch-helper.sh, supervisor-helper.sh
Added cleanup traps across 2–5 functions per script to remove temporary files (jq filters, SQL files, state files, probe files, logs) on RETURN.
Main Scripts and Test
aidevops.sh, setup.sh, tests/test-supervisor-state-machine.sh
Added cleanup traps across multiple functions in entry-point scripts and test setup; setup.sh includes 13 new trap lines across various utility functions; EXIT trap added to test script for comprehensive directory cleanup.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

Poem

🧹 Temporary files, now with guaranteed grace,
RETURN traps clean every scattered place,
Mktemp's children shall linger no more—
Zero debt maintained, quality at core! ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: adding trap cleanup for mktemp temporary files across multiple scripts to prevent resource leaks.
Docstring Coverage ✅ Passed Docstring coverage is 93.88% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/t135.9

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist
Copy link

Summary of Changes

Hello @marcusquinn, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the robustness and reliability of the codebase by implementing comprehensive temporary file cleanup across numerous shell scripts. By systematically adding trap commands to ensure mktemp generated files are removed under various exit conditions, it mitigates the risk of resource leaks and maintains a cleaner system state. This completes a broader effort to secure all temporary file operations.

Highlights

  • Comprehensive Temporary File Cleanup: Added trap 'rm -f "$var"' RETURN cleanup for all remaining mktemp usages that previously lacked trap protection.
  • Leak Prevention: Ensures temporary files are reliably removed on unexpected exits, early returns, or errors, preventing resource leaks.
  • Expanded Coverage: This change covers 12 additional files, including 7 active scripts, 1 test file, and 6 archive scripts, which were missed in an initial pass.
  • Full Codebase Protection: With this update, all approximately 90 mktemp usages across the entire codebase now benefit from robust trap cleanup mechanisms.
  • Best Practice Adherence: The implementation uses RETURN for function-scoped cleanup and EXIT for script-level cleanup, and employs single quotes to avoid ShellCheck warnings (SC2064).
Changelog
  • .agents/scripts/_archive/add-missing-returns.sh
    • Implemented RETURN trap for temp_file to ensure its removal.
  • .agents/scripts/_archive/fix-common-strings.sh
    • Added RETURN trap for temp_file to guarantee cleanup.
  • .agents/scripts/_archive/fix-s131-default-cases.sh
    • Ensured temp_file is removed on function return with a RETURN trap.
  • .agents/scripts/_archive/fix-sc2155-simple.sh
    • Applied RETURN trap for temp_file to prevent leaks.
  • .agents/scripts/_archive/fix-shellcheck-critical.sh
    • Added RETURN traps for temp_file in both fix_sc2155_in_file and fix_sc2181_in_file functions.
  • .agents/scripts/add-skill-helper.sh
    • Introduced RETURN trap for tmp_file to ensure proper cleanup.
  • .agents/scripts/agent-test-helper.sh
    • Added a RETURN trap to remove stderr_file and raw_output temporary files.
  • .agents/scripts/coderabbit-collector-helper.sh
    • Implemented RETURN traps for jq_filter_file and sql_file in both collect_reviews and collect_comments functions.
  • .agents/scripts/coderabbit-task-creator-helper.sh
    • Added RETURN traps for tmp_file in scan_db_findings and scan_pulse_findings, and for tmp_create in cmd_create.
  • .agents/scripts/cron-helper.sh
    • Applied RETURN traps for temp_file in cmd_add, cmd_remove, cmd_pause, and cmd_resume functions.
  • .agents/scripts/full-loop-helper.sh
    • Ensured tmp_file cleanup with a RETURN trap.
  • .agents/scripts/loop-common.sh
    • Added RETURN traps for temp_file in loop_set_state, loop_add_receipt, loop_track_attempt, and loop_block_task functions.
  • .agents/scripts/matrix-dispatch-helper.sh
    • Implemented RETURN traps for temp_file in cmd_setup, cmd_map, and cmd_unmap functions.
  • .agents/scripts/objective-runner-helper.sh
    • Added a RETURN trap for temp_file to ensure its removal.
  • .agents/scripts/quality-fix.sh
    • Introduced RETURN traps for temp_file in fix_return_statements and fix_positional_parameters, and for constants_file in analyze_string_literals.
  • .agents/scripts/ralph-loop-helper.sh
    • Ensured temp_file cleanup with a RETURN trap.
  • .agents/scripts/schema-validator-helper.sh
    • Added RETURN traps for tmp in two instances within the install_deps function.
  • .agents/scripts/site-crawler-helper.sh
    • Implemented a RETURN trap for new_queue to ensure its removal.
  • .agents/scripts/sops-helper.sh
    • Added a RETURN trap for tmp_deb to clean up downloaded temporary files.
  • .agents/scripts/supervisor-helper.sh
    • Applied RETURN traps for probe_tmpfile in two check_model_health sections.
    • Added RETURN trap for log_tail_file in extract_log_metadata.
    • Implemented RETURN trap for temp_file in populate_verify_queue.
    • Ensured tmp_file cleanup with a RETURN trap in generate_verify_entry.
  • .agents/scripts/verify-run-helper.sh
    • Ensured tmp_file cleanup with a RETURN trap.
  • setup.sh
    • Added RETURN traps for tmp_file in cleanup_deprecated_paths.
    • Implemented RETURN traps for tmp_config in cleanup_deprecated_mcps, disable_ondemand_mcps, setup_google_analytics_mcp (two locations), and update_mcp_paths_in_opencode.
    • Added RETURN trap for tmp_fix in validate_opencode_config.
    • Introduced rm -rf RETURN trap for the tmp_preserve directory in deploy_aidevops_agents.
    • Applied RETURN traps for tmp_file in deploy_aidevops_agents (second instance) and add_opencode_plugin (two instances).
    • Ensured temp_file cleanup with a RETURN trap in inject_agents_reference.
  • tests/test-supervisor-state-machine.sh
    • Consolidated the EXIT trap to include WORKTREE_TEST_DIR, TEST_DIR, VERIFY_TEST_DIR, and CLAIM_TEST_DIR for comprehensive directory cleanup.
Activity
  • The author has systematically added trap commands to ensure temporary files created with mktemp are properly cleaned up across the codebase.
  • This pull request completes a broader effort, addressing 12 files that were missed in an earlier pass, bringing the total coverage to approximately 90 mktemp usages.
  • The implementation adheres to best practices by using RETURN for function-scoped cleanup and EXIT for script-level cleanup, and single quotes to avoid ShellCheck warnings.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@sonarqubecloud
Copy link

sonarqubecloud bot commented Feb 9, 2026

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request is a great initiative to improve the robustness of the scripts by ensuring temporary files are always cleaned up, adhering to the repository's style guide (line 33: 'Temp files must have trap cleanup (RETURN or EXIT)'). The changes are consistent and correctly use trap with RETURN for function-scoped cleanup and EXIT for script-scoped cleanup. I've found a few minor areas for improvement:

  • In several files, an explicit rm command remains after a trap was added, making the rm redundant.
  • In the test script test-supervisor-state-machine.sh, multiple trap ... EXIT commands are defined, where only the last one will be active. Consolidating them into a single trap at the top of the script would be cleaner.

My detailed comments provide suggestions to address these points. Overall, this is a solid and valuable contribution.

tmp_file=$(mktemp)
trap 'rm -f "$tmp_file"' RETURN
jq --arg name "$name" '.skills = [.skills[] | select(.name != $name)]' "$SKILL_SOURCES" > "$tmp_file" && mv "$tmp_file" "$SKILL_SOURCES"
rm -f "$tmp_file"

Choose a reason for hiding this comment

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

medium

The explicit rm -f "$tmp_file" is now redundant. The trap you've added on line 439 will handle the cleanup of the temporary file automatically when the register_skill function exits, regardless of success or failure. You can safely remove this line.

tmp=$(mktemp)
trap 'rm -f "$tmp"' RETURN
jq '. + {"type": "module"}' "$TOOL_DIR/package.json" > "$tmp" && mv "$tmp" "$TOOL_DIR/package.json"
rm -f "$tmp"

Choose a reason for hiding this comment

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

medium

The explicit rm -f "$tmp" is now redundant. The trap you've added on line 64 will handle the cleanup of the temporary file automatically when the install_deps function exits. You can safely remove this line.

trap 'rm -f "$tmp_deb"' RETURN
curl -fsSL "$latest_url" -o "$tmp_deb"
sudo dpkg -i "$tmp_deb"
rm -f "$tmp_deb"

Choose a reason for hiding this comment

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

medium

The explicit rm -f "$tmp_deb" is now redundant. The trap you've added on line 107 will handle the cleanup of the temporary file automatically when the cmd_install function exits. You can safely remove this line.


# Test: run_verify_checks with a real VERIFY.md
VERIFY_TEST_DIR=$(mktemp -d)
trap 'rm -rf "$WORKTREE_TEST_DIR" "$TEST_DIR" "$VERIFY_TEST_DIR" "$CLAIM_TEST_DIR"' EXIT

Choose a reason for hiding this comment

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

medium

While this trap correctly covers all temporary directories, the previous trap commands on lines 59 and 1046 are still present in the file. Each new trap command for the EXIT signal overwrites the previous one, making the earlier ones dead code. To avoid confusion and improve maintainability, you should remove the now-redundant traps on lines 59 and 1046, leaving only this consolidated one. Ideally, this single trap should be placed at the top of the script to ensure it's defined once before any temporary directories are created.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In @.agents/scripts/supervisor-helper.sh:
- Around line 3367-3369: The RETURN trap for cleaning up mktemp (e.g.,
probe_tmpfile created before running ("${probe_cmd[@]}" > "$probe_tmpfile" 2>&1)
&) is clobbering existing RETURN traps and will fail with set -u when the temp
var goes out of scope; fix by saving the previous RETURN trap (e.g.,
prev_trap=$(trap -p RETURN)), installing a new RETURN trap that removes the temp
file and then restores/evaluates the saved prev_trap (or clears it if empty),
and ensure this pattern is applied to every mktemp/trap pair
(probe_tmpfile/probe_cmd and the other mktemp uses noted) so the original RETURN
trap is preserved/restored after cleanup.

In `@setup.sh`:
- Line 2590: The RETURN trap for deploy_aidevops_agents currently gets
overwritten (trap 'rm -rf "$tmp_preserve"' RETURN then later trap 'rm -rf
"$tmp_file"' RETURN), which can leak tmp files if an early return occurs; fix by
creating a single cleanup function (e.g., cleanup_deploy_aidevops_agents) that
removes both "$tmp_preserve" and "$tmp_file" safely (checking for non-empty
variables and existence), set one trap 'trap cleanup_deploy_aidevops_agents
RETURN', and remove the separate inline trap calls so all temporary-file cleanup
is centralized and cannot be silently replaced.
🧹 Nitpick comments (2)
.agents/scripts/site-crawler-helper.sh (1)

478-486: Trap set inside a loop — works but is subtly fragile.

Because trap '...' RETURN is function-scoped (not loop-iteration-scoped), each iteration overwrites the previous trap. This is safe today because:

  1. $new_queue resolves at trap-fire time (single quotes) → targets the latest file.
  2. Each iteration's file is consumed by mv on line 486, so the trap is effectively a no-op at function return.
  3. No other RETURN trap exists in crawl_with_crawl4ai.

If a second mktemp + trap were added to this function in the future, one cleanup would be silently lost. Consider noting this with a brief comment for the next maintainer.

aidevops.sh (1)

1486-1490: Second trap … RETURN silently replaces the first within cmd_upgrade_planning.

Bash only keeps one handler per signal per scope. Line 1553's trap overwrites Line 1488's trap, so if the function were to exit after Line 1553 without hitting the explicit rm -f on Line 1570, only $plans_content_file would be cleaned up — $tasks_file cleanup would be lost.

In the current code flow this is safe because $tasks_file is explicitly removed on Line 1505 before the second trap is set. However, the pattern is fragile: any future edit that reorders these blocks or adds an early return between them could silently leak a temp file.

A more robust approach is to accumulate both files in the second trap:

♻️ Combine both cleanups into a single trap

At Line 1488, keep the original trap:

                tasks_file=$(mktemp)
                trap 'rm -f "$tasks_file"' RETURN

At Line 1553, extend the trap to cover both files:

                plans_content_file=$(mktemp)
-               trap 'rm -f "$plans_content_file"' RETURN
+               trap 'rm -f "$tasks_file" "$plans_content_file"' RETURN

rm -f on an already-deleted file is a harmless no-op, so this is safe even when $tasks_file was cleaned up earlier on Line 1505.

Also applies to: 1551-1554

Comment on lines 3367 to 3369
probe_tmpfile=$(mktemp)
trap 'rm -f "$probe_tmpfile"' RETURN
("${probe_cmd[@]}" > "$probe_tmpfile" 2>&1) &
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Avoid leaking RETURN traps (can break set -u on later returns)

These trap 'rm -f "$tmp"' RETURN lines persist beyond the function, clobber any existing RETURN traps and, with set -u, will later error when the local temp var is out of scope. That can hard-exit the supervisor unexpectedly. Please chain/restore the prior RETURN trap (or clear it) in each block. Apply the same pattern to all newly added mktemp traps.

✅ Suggested pattern (chain + restore the previous RETURN trap)
-            probe_tmpfile=$(mktemp)
-            trap 'rm -f "$probe_tmpfile"' RETURN
+            local _prev_return_trap
+            _prev_return_trap=$(trap -p RETURN)
+            probe_tmpfile=$(mktemp)
+            trap 'rm -f "$probe_tmpfile"; eval "$_prev_return_trap"' RETURN
@@
-            probe_result=$(cat "$probe_tmpfile" 2>/dev/null || true)
-            rm -f "$probe_tmpfile"
+            probe_result=$(cat "$probe_tmpfile" 2>/dev/null || true)
+            rm -f "$probe_tmpfile"
+            eval "$_prev_return_trap"

Also applies to: 3397-3399, 4374-4376, 7412-7414, 7947-7949

🤖 Prompt for AI Agents
In @.agents/scripts/supervisor-helper.sh around lines 3367 - 3369, The RETURN
trap for cleaning up mktemp (e.g., probe_tmpfile created before running
("${probe_cmd[@]}" > "$probe_tmpfile" 2>&1) &) is clobbering existing RETURN
traps and will fail with set -u when the temp var goes out of scope; fix by
saving the previous RETURN trap (e.g., prev_trap=$(trap -p RETURN)), installing
a new RETURN trap that removes the temp file and then restores/evaluates the
saved prev_trap (or clears it if empty), and ensure this pattern is applied to
every mktemp/trap pair (probe_tmpfile/probe_cmd and the other mktemp uses noted)
so the original RETURN trap is preserved/restored after cleanup.

print_info "Clean mode: removing stale files from $target_dir (preserving ${preserved_dirs[*]})"
local tmp_preserve
tmp_preserve="$(mktemp -d)"
trap 'rm -rf "$tmp_preserve"' RETURN
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Second RETURN trap silently replaces the first in deploy_aidevops_agents.

In bash, trap ... RETURN replaces the previous RETURN trap — it does not stack. Line 2590 sets cleanup for $tmp_preserve, and line 2683 overwrites it with cleanup for $tmp_file. This is safe today because $tmp_preserve is explicitly removed at line 2615 before the second trap is set. However, it's fragile — a future refactor inserting code between lines 2590–2615 that causes an early return after the second trap is set would silently leak $tmp_preserve.

Consider consolidating into a single trap that covers both, or using an explicit cleanup function.

💡 One approach: accumulate cleanup in a helper
+    # Track all temp paths for cleanup
+    local -a _tmp_cleanup=()
+    trap 'rm -rf "${_tmp_cleanup[@]}"' RETURN
+
     ...
         local tmp_preserve
         tmp_preserve="$(mktemp -d)"
-        trap 'rm -rf "$tmp_preserve"' RETURN
+        _tmp_cleanup+=("$tmp_preserve")
     ...
             local tmp_file
             tmp_file=$(mktemp)
-            trap 'rm -f "$tmp_file"' RETURN
+            _tmp_cleanup+=("$tmp_file")

Also applies to: 2683-2683

🤖 Prompt for AI Agents
In `@setup.sh` at line 2590, The RETURN trap for deploy_aidevops_agents currently
gets overwritten (trap 'rm -rf "$tmp_preserve"' RETURN then later trap 'rm -rf
"$tmp_file"' RETURN), which can leak tmp files if an early return occurs; fix by
creating a single cleanup function (e.g., cleanup_deploy_aidevops_agents) that
removes both "$tmp_preserve" and "$tmp_file" safely (checking for non-empty
variables and existence), set one trap 'trap cleanup_deploy_aidevops_agents
RETURN', and remove the separate inline trap calls so all temporary-file cleanup
is centralized and cannot be silently replaced.

@marcusquinn
Copy link
Owner Author

Closing: duplicate of PR #800 which was already merged. The RETURN trap clobbering feedback from CodeRabbit is valid and should be addressed in a follow-up task.

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