Skip to content

fix(ops): three targeted fixes — MarkdownV2 escaping, CPU tracer args… - #119

Merged
gamblecodezcom merged 1 commit into
mainfrom
claude/cpu-guard-script-DnD8u
Mar 1, 2026
Merged

fix(ops): three targeted fixes — MarkdownV2 escaping, CPU tracer args…#119
gamblecodezcom merged 1 commit into
mainfrom
claude/cpu-guard-script-DnD8u

Conversation

@gamblecodezcom

@gamblecodezcom gamblecodezcom commented Mar 1, 2026

Copy link
Copy Markdown
Owner

User description

…, jq fallback

rw_cpu_guard.sh:

  • Add escape_md_v2() helper: escapes all 20 MarkdownV2 special characters (backslash processed first to prevent double-escaping)
  • tg_alert(): escape the full composed text (prefix + caller message) via escape_md_v2() before sending; switch parse_mode Markdown → MarkdownV2; raw ${short_cmd} can no longer break message formatting or leak syntax
  • CPU tracer: switch ps format 'cmd' → 'args' so the full executable path and every argument are captured; combined with the existing $5..$NF loop this gives a complete, delimiter-safe command string in every CSV row

runewager_redeploy.sh:

  • _health_check pretty-print cascade: python3 -m json.tool → jq . → raw; diagnostics never fail when neither pretty-printer is installed

https://claude.ai/code/session_01WpEqAiDbpqnBywMjYXJHf4

Summary by Sourcery

Improve robustness of operational scripts for CPU alerting and deployment health checks.

Bug Fixes:

  • Ensure Telegram alerts from rw_cpu_guard escape MarkdownV2 syntax correctly and use the MarkdownV2 parse mode to prevent formatting breakage or injection by arbitrary message content.
  • Adjust the CPU tracer in rw_cpu_guard to capture full command paths and arguments reliably by using ps args output, avoiding truncation and delimiter issues in the CSV trace.
  • Make the runewager_redeploy health check pretty-print JSON responses via a python3-then-jq fallback chain, degrading to raw output without failing when neither tool is available.

CodeAnt-AI Description

Fix Telegram alert formatting, capture full process commands in CPU traces, and reliably pretty-print health check output

What Changed

  • Telegram alerts now escape all MarkdownV2 characters and use MarkdownV2, preventing alert text from breaking formatting or injecting markup
  • CPU tracer writes the full executable path and every argument into the CSV trace so commands and their arguments are never truncated or split incorrectly
  • Health check output is pretty-printed when possible: try python3, then jq, and fall back to raw output so diagnostics never fail if pretty-printers are missing

Impact

✅ Safer Telegram alerts (no broken or malformed messages)
✅ Complete CPU command traces for accurate forensics
✅ Clearer health diagnostics even without formatting tools

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

Summary by CodeRabbit

  • Chores
    • Improved health check output formatting with pretty-printing support when available
    • Enhanced Telegram alert message formatting and special character sanitization
    • Improved forensics data collection to capture complete command paths and arguments

…, jq fallback

rw_cpu_guard.sh:
- Add escape_md_v2() helper: escapes all 20 MarkdownV2 special characters
  (backslash processed first to prevent double-escaping)
- tg_alert(): escape the full composed text (prefix + caller message) via
  escape_md_v2() before sending; switch parse_mode Markdown → MarkdownV2;
  raw ${short_cmd} can no longer break message formatting or leak syntax
- CPU tracer: switch ps format 'cmd' → 'args' so the full executable path
  and every argument are captured; combined with the existing $5..$NF loop
  this gives a complete, delimiter-safe command string in every CSV row

runewager_redeploy.sh:
- _health_check pretty-print cascade: python3 -m json.tool → jq . → raw;
  diagnostics never fail when neither pretty-printer is installed

https://claude.ai/code/session_01WpEqAiDbpqnBywMjYXJHf4
@codeant-ai

codeant-ai Bot commented Mar 1, 2026

Copy link
Copy Markdown

CodeAnt AI is reviewing your PR.


Thanks for using CodeAnt! 🎉

We're free for open-source projects. if you're enjoying it, help us grow by sharing.

Share on X ·
Reddit ·
LinkedIn

@sourcery-ai

sourcery-ai Bot commented Mar 1, 2026

Copy link
Copy Markdown

Reviewer's Guide

Updates the CPU guard and redeploy scripts to make Telegram alerts safe under MarkdownV2, improve CPU forensics command capture, and make health-check payload pretty-printing degrade gracefully across available tools.

Sequence diagram for updated Telegram MarkdownV2 alert flow

sequenceDiagram
    actor Admin
    participant rw_cpu_guard
    participant TelegramAPI

    Admin->>rw_cpu_guard: triggers tg_alert(msg)
    rw_cpu_guard->>rw_cpu_guard: escape_md_v2("🛡 [rw_cpu_guard] " + msg)
    rw_cpu_guard->>rw_cpu_guard: set safe_text
    rw_cpu_guard->>rw_cpu_guard: check TG_BOT_TOKEN and TG_ADMIN_IDS
    rw_cpu_guard->>rw_cpu_guard: enforce _ALERT_COOLDOWN
    loop for each id in TG_ADMIN_IDS
        rw_cpu_guard->>TelegramAPI: POST sendMessage
        TelegramAPI-->>rw_cpu_guard: 200 OK or error
    end
    rw_cpu_guard-->>Admin: alert sent using MarkdownV2
Loading

Flow diagram for CPU tracer command capture with args

flowchart TD
    A[start _run_forensics CPU tracer] --> B[Create trace CSV with header]
    B --> C[Start 1 second sampling loop]
    C --> D[ps -eo pid,ppid,pcpu,pmem,args --sort=-pcpu]
    D --> E[Filter processes with pcpu > 15]
    E --> F[Join fields 5..NF into cmd string]
    F --> G[Replace commas in cmd with semicolons]
    G --> H[Write timestamp,pid,ppid,cpu%,mem%,cmd to trace CSV]
    H --> I{More samples?}
    I -->|Yes| C
    I -->|No| J[End CPU tracer]
Loading

Flow diagram for health_check pretty-print cascade

flowchart TD
    A[start _health_check] --> B[curl HEAD to HEALTH_URL]
    B --> C{http_code == 200?}
    C -->|No| D[warn Bot not healthy]
    D --> E[end]
    C -->|Yes| F[ok Bot healthy]
    F --> G[curl GET HEALTH_URL into _payload]
    G --> H{python3 available?}
    H -->|Yes| I[Pretty-print via python3 -m json.tool]
    I --> J{python3 pretty-print succeeded?}
    J -->|Yes| K[Indent and show first 20 lines]
    J -->|No| L[Indent and show raw first 20 lines]
    K --> E
    L --> E
    H -->|No| M{jq available?}
    M -->|Yes| N[Pretty-print via jq .]
    N --> O{jq pretty-print succeeded?}
    O -->|Yes| P[Indent and show first 20 lines]
    O -->|No| Q[Indent and show raw first 20 lines]
    P --> E
    Q --> E
    M -->|No| R[Indent and show raw first 20 lines]
    R --> E[end]
Loading

File-Level Changes

Change Details Files
Harden Telegram alerts by properly escaping MarkdownV2 and updating parse_mode so arbitrary command text cannot break formatting.
  • Introduce an escape_md_v2() helper that escapes all Telegram MarkdownV2 special characters in the correct order, ensuring backslashes are handled first.
  • Update tg_alert() to build the full alert string, escape it with escape_md_v2(), and send that value to Telegram.
  • Switch Telegram sendMessage parse_mode from Markdown to MarkdownV2 to match the escaping strategy and avoid formatting/syntax leakage from ${msg}.
scripts/rw_cpu_guard.sh
Improve CPU tracer forensics so each CSV row contains the complete command and arguments without truncation.
  • Change ps invocation in _run_forensics() from field 'cmd' to 'args' to capture the full executable path and all arguments.
  • Preserve the existing awk loop that joins fields 5..NF into a single string and replaces commas with semicolons, ensuring delimiter-safe CSV output even for commands with spaces or commas.
scripts/rw_cpu_guard.sh
Make the redeploy health check’s JSON pretty-printing degrade gracefully across python3, jq, or raw output so diagnostics never fail due to missing tools.
  • Modify _health_check() to attempt pretty-printing the health payload with python3 -m json.tool first, falling back to jq . if python3 is unavailable, and finally to raw output if neither is installed.
  • Ensure each pretty-print step is wrapped so that failures fall back to plain head -20 output with indentation rather than causing the health check to error.
scripts/runewager_redeploy.sh

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

@gamblecodezcom
gamblecodezcom merged commit eedb1c3 into main Mar 1, 2026
4 of 5 checks passed
@gamblecodezcom
gamblecodezcom deleted the claude/cpu-guard-script-DnD8u branch March 1, 2026 12:44
@coderabbitai

coderabbitai Bot commented Mar 1, 2026

Copy link
Copy Markdown

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6969f89 and 31a43b1.

📒 Files selected for processing (2)
  • scripts/runewager_redeploy.sh
  • scripts/rw_cpu_guard.sh

📝 Walkthrough

Walkthrough

The PR enhances two shell scripts: adding JSON pretty-printing with cascading format tool fallbacks to health check output in runewager_redeploy.sh, and improving Telegram message safety through MarkdownV2 escaping while capturing full command arguments in forensics data collection within rw_cpu_guard.sh.

Changes

Cohort / File(s) Summary
Health Check Output Enhancement
scripts/runewager_redeploy.sh
Adds JSON pretty-printing to health check responses with cascading format tools: python3's json.tool → jq → raw fallback. Preserves existing line-limit and prefix behavior.
Telegram Message Safety & Forensics
scripts/rw_cpu_guard.sh
Introduces escape_md_v2 function to sanitize MarkdownV2 special characters for Telegram messages. Updates tg_alert to escape message text before sending. Enhances forensics data collection by capturing full command arguments via ps args field and updating awk reconstruction logic.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

size:XS

Poem

🐰 A rabbit's ode to safer scripts:

Pretty JSON, formatted with care,
Telegram messages now escape with flair,
Commands now captured in their full glory,
Each safeguard a chapter in our deployment story! 🎉

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch claude/cpu-guard-script-DnD8u

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.

@codeant-ai codeant-ai Bot added the size:M This PR changes 30-99 lines, ignoring generated files label Mar 1, 2026

@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 1 issue, and left some high level feedback:

  • In the CPU tracer, the CSV header still says cmd while the data now comes from args; consider updating the header label to match the new field for clarity and downstream parsing.
  • The _health_check pretty-printing logic repeats the same echo ... | head -20 | sed 's/^/ /' fallback in multiple branches; consider extracting that into a small helper to reduce duplication and make the cascade easier to follow.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In the CPU tracer, the CSV header still says `cmd` while the data now comes from `args`; consider updating the header label to match the new field for clarity and downstream parsing.
- The `_health_check` pretty-printing logic repeats the same `echo ... | head -20 | sed 's/^/    /'` fallback in multiple branches; consider extracting that into a small helper to reduce duplication and make the cascade easier to follow.

## Individual Comments

### Comment 1
<location path="scripts/runewager_redeploy.sh" line_range="257-258" />
<code_context>
             local _payload; _payload=$(curl -sS --max-time 3 "$HEALTH_URL" 2>/dev/null)
             if command -v python3 >/dev/null 2>&1; then
-                echo "$_payload" | python3 -m json.tool 2>/dev/null | head -20 | sed 's/^/    /' || echo "$_payload" | head -20 | sed 's/^/    /'
+                echo "$_payload" | python3 -m json.tool 2>/dev/null | head -20 | sed 's/^/    /' \
+                    || echo "$_payload" | head -20 | sed 's/^/    /'
+            elif command -v jq >/dev/null 2>&1; then
+                echo "$_payload" | jq . 2>/dev/null | head -20 | sed 's/^/    /' \
</code_context>
<issue_to_address>
**issue (bug_risk):** The pretty-print fallback on JSON-tool failure probably never triggers because the pipeline exit status is dominated by `sed`.

Because this is in a pipeline, the exit code comes from the last command (`sed`), so the `|| echo "$_payload" ...` fallback will almost never run even if `python3 -m json.tool` fails or outputs nothing. The same applies to the `jq` branch.

To make the fallback work on parse failure, either capture the `json.tool` output and branch explicitly:

```bash
if ! _formatted=$(printf '%s' "$_payload" | python3 -m json.tool 2>/dev/null); then
    printf '%s
' "$_payload" | head -20 | sed 's/^/    /'
else
    printf '%s
' "_formatted" | head -20 | sed 's/^/    /'
fi
```

or enable `set -o pipefail` so the pipeline fails when `python3`/`jq` fail, and keep the `||` form.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +257 to +258
echo "$_payload" | python3 -m json.tool 2>/dev/null | head -20 | sed 's/^/ /' \
|| echo "$_payload" | head -20 | sed 's/^/ /'

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

issue (bug_risk): The pretty-print fallback on JSON-tool failure probably never triggers because the pipeline exit status is dominated by sed.

Because this is in a pipeline, the exit code comes from the last command (sed), so the || echo "$_payload" ... fallback will almost never run even if python3 -m json.tool fails or outputs nothing. The same applies to the jq branch.

To make the fallback work on parse failure, either capture the json.tool output and branch explicitly:

if ! _formatted=$(printf '%s' "$_payload" | python3 -m json.tool 2>/dev/null); then
    printf '%s
' "$_payload" | head -20 | sed 's/^/    /'
else
    printf '%s
' "_formatted" | head -20 | sed 's/^/    /'
fi

or enable set -o pipefail so the pipeline fails when python3/jq fail, and keep the || form.

@codeant-ai

codeant-ai Bot commented Mar 1, 2026

Copy link
Copy Markdown

Nitpicks 🔍

🔒 No security issues identified
⚡ Recommended areas for review

  • PS args truncation
    The forensics tracer switched ps output to args to capture full commandlines, but ps can still truncate output depending on width. Ensure the ps invocation won't truncate long cmdlines (or document/handle that), and that the CSV joining/escaping remains robust for arbitrary args.

  • Telegram message handling
    tg_alert() now escapes the combined prefix+message and switches parse_mode to MarkdownV2. Confirm that the escaping plus --data-urlencode works as intended (no double-escaping) and that parse_mode is always accepted. Also validate behavior for very long messages and embedded newlines.

  • Pretty-print fallback
    Added a python3 → jq → raw cascade to pretty-print the health JSON. Verify the order is intended, and that non-JSON payloads fall back cleanly; consider consolidating the duplicated fallback echo logic to avoid subtle inconsistencies.

@codeant-ai

codeant-ai Bot commented Mar 1, 2026

Copy link
Copy Markdown

CodeAnt AI finished reviewing your PR.

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

Labels

size:M This PR changes 30-99 lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants