Skip to content

Claude/update prod runner script lq2g s - #70

Closed
gamblecodezcom wants to merge 18 commits into
mainfrom
claude/update-prod-runner-script-Lq2gS
Closed

Claude/update prod runner script lq2g s#70
gamblecodezcom wants to merge 18 commits into
mainfrom
claude/update-prod-runner-script-Lq2gS

Conversation

@gamblecodezcom

@gamblecodezcom gamblecodezcom commented Feb 23, 2026

Copy link
Copy Markdown
Owner

User description

Summary by CodeRabbit

  • New Features

    • Automatic weekly disk space cleanup to optimize system storage and prevent disk-related issues.
  • Improvements

    • Enhanced deployment notifications with detailed status messages at key stages.
    • Improved error recovery mechanisms for automatic service restart on deployment failures.
    • Added comprehensive health checks and status verification after deployments.

CodeAnt-AI Description

Improve VPS deploy reliability, add weekly disk cleanup, and harden runtime safety

What Changed

  • Deploys now detect service status and skip or restart the service as appropriate; failed deploy attempts notify admins and attempt to recover the running service automatically
  • Deployment script uses safer environment parsing, supports SSH key then password fallback, sends clear pre/post notifications, runs a health check after deploy, and performs deterministic rollback on failure
  • Adds a weekly disk-protection script and installs a weekly cron job to compress/remove old logs, vacuum system journal, clear npm cache/temp files, and remove old runtime snapshots without touching critical files
  • Bot runtime adjustments: tips scheduler starts at launch, persistent state load/save behavior tightened, health endpoint simplified, periodic persistence interval increased (less frequent disk writes)
  • Better admin messaging across CI and deploy flows (more structured start/finish/status messages and final deploy reports)

Impact

✅ More reliable VPS deploys with automatic recovery
✅ Fewer out-of-disk incidents via weekly cleanup
✅ Clearer deploy and health notifications for admins

💡 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.

claude and others added 18 commits February 23, 2026 00:36
- Add tipsStore with 15 default sweepstakes-safe tips (id, text, enabled)
- Add TIPS_GROUP constant (@GambleCodezPrizeHub, overridable via env)
- Persist tipsStore in runtime-state.json (snapshot + load)
- Start tips scheduler on bot launch: posts one random enabled tip
  silently every 4 hours to @GambleCodezPrizeHub (disable_notification)
- Scheduler is re-armable when admin changes the interval

Admin commands:
  /tips  /t  /tp    — Tips Manager dashboard with inline buttons
  /tiplist          — Show all tips with IDs and preview
  /tipadd           — Prompt for new tip text (state: await_tip_add_text)
  /tipremove        — Select tip by button to delete
  /tipedit          — Select tip by button then prompt for new text
  /tiptoggle        — Toggle entire tips system on/off
  /tiptest          — Send one random tip preview to admin in DM
  /tipsettings      — Show settings and update interval (hours)

Inline button actions:
  tips_cmd_{add,edit,remove,toggle,list,test,settings}
  tip_remove_<id>       — remove a specific tip
  tip_edit_select_<id>  — prompt to edit a specific tip
  tip_toggle_<id>       — enable/disable individual tip

pendingAction state machine:
  await_tip_add_text       → save new tip, reply "Added as Tip #X"
  await_tip_edit_text      → update tip text, reply "Tip #X updated"
  await_tip_settings_interval → update interval + restart scheduler

https://claude.ai/code/session_01X3PxGFF5zzKptQwVkjYzzN
GitHub CI:
- deploy.yml: disable `deploy` job with `if: false` — GitHub Actions
  must NEVER restart or launch the bot; it is code storage only.
  Quality-gates job (syntax, tests, audit) continues to run on push.
- ci.yml: unchanged — already runs tests without touching Telegram.

index.js runtime guards (layered):
- CI / smoke-test layer: if CI=true or DISABLE_RUNTIME=1 → log and
  skip all runtime startup without calling process.exit() so that
  `require('./index.js')` in smoke tests completes cleanly.
- VPS-only layer: if DEVICE !== "vps" → print warning and exit(0).
  Set DEVICE=vps in the VPS .env to allow the bot to start.

/deploy admin command:
- Restart logic is systemctl-only (no PM2); unchanged from original.

deploy.sh (new, VPS-only):
- git fetch --all && git reset --hard origin/main
- npm ci --omit=dev
- systemctl restart runewager
- systemctl is-active confirmation

.env.example:
- Added DEVICE=vps entry so prod-run.sh copies it correctly.

https://claude.ai/code/session_01X3PxGFF5zzKptQwVkjYzzN
…scripts

- /deploy Telegram command: git pull -> git fetch --all + git reset --hard
  origin/main + git clean -fd. Prevents hangs caused by dirty working trees,
  untracked files, or merge conflicts that made /deploy stuck.
- prod-run.sh: same fetch+reset change for the initial code-pull step.
- deploy.sh: add systemctl stop before git ops (prevents file locks during
  reset) and git clean -fd after reset (removes stale untracked files).

All three paths now use the same hard-reset strategy. Systemd service,
CI guard (CI=true/DISABLE_RUNTIME=1), and DEVICE=vps guard are unchanged
as they were already correct.

https://claude.ai/code/session_01X3PxGFF5zzKptQwVkjYzzN
…deploys

deploy.yml:
- Change trigger from push:main to pull_request:types:[closed]
- Add merge guard to quality-gates job: only runs when merged==true,
  base.ref==main, and merge_commit_sha is present. workflow_dispatch
  still works for manual deploys. Revert PRs, closed-without-merge,
  draft PRs, and direct pushes are all completely ignored.
- Enable deploy job (was if:false) — now fires only when quality gates
  pass. Deploy step simplified to a single SSH call: bash deploy.sh

deploy.sh:
- Add up-to-date hash check (git ls-remote vs local HEAD) before
  systemctl stop. If VPS already has the latest commit, exit 0
  immediately without stopping the service or touching anything.

index.js (/deploy command):
- After git fetch, compare local HEAD vs origin/main. If equal, reply
  "Bot is already running the latest version." and return early — no
  reset, no npm ci, no restart.

https://claude.ai/code/session_01X3PxGFF5zzKptQwVkjYzzN
Keep all our intentional improvements:
- index.js: up-to-date check in /deploy (skip if already on latest commit)
- deploy.sh: hash check before systemctl stop + systemctl stop before git ops
- deploy.yml: enabled deploy job (PR-merge-only trigger, not if:false)

https://claude.ai/code/session_01X3PxGFF5zzKptQwVkjYzzN
deploy.sh:
- Accepts $1 source arg: github | bot | vps (default: vps)
- Sources .env at startup so BOT_TOKEN/ADMIN_IDS are available
- send_admin() function: silent curl-based Telegram notification
  (disable_notification=true — no buzz/sound on admin's phone)
- ERR trap: always sends "Deploy failed at line N" on any error
- Per-step notifications: started, stopping bot, pulling code,
  cleaning repo, installing deps, starting bot, complete/failed
- Already-up-to-date path also notifies admin

deploy.yml:
- DEPLOY_PASS secret wired to deploy job env
- Install sshpass before SSH step
- Deploy step tries SSH key first; on failure waits 120s then
  retries with sshpass password fallback; on second failure sends
  Telegram alert and exits 1
- deploy.sh called with "github" source arg

index.js (/deploy command):
- Replaced full in-process git+npm+restart logic with a single
  detached spawn of deploy.sh with "bot" source arg
- Bot replies "Deployment starting..." then exits after 2s;
  deploy.sh takes over and sends all per-step notifications

https://claude.ai/code/session_01X3PxGFF5zzKptQwVkjYzzN
CodeAnt critical review fix: previously if git fetch or reset
failed after systemctl stop, the service would stay permanently
down because set -e would abort the script with no recovery.

Now:
- git fetch + reset are wrapped in an if/else conditional
- On failure: stderr is captured and included in both the warn
  log and the admin Telegram notification for diagnostics
- Service is restarted on the old/existing code so bot stays up
- Exit 1 signals the caller (e.g. GitHub Actions) that deploy
  failed without triggering the ERR trap a second time

Addresses all four CodeAnt nitpick areas:
  - Git fetch/reset robustness (critical)
  - Debug info on git failures (diagnostic output captured)
  - Remote hash check already handles unreachable remotes safely
    (empty REMOTE_HASH falls through to deploy, conservative)

https://claude.ai/code/session_01X3PxGFF5zzKptQwVkjYzzN
Root cause: both ci.yml validate and smoke jobs referenced
`environment: name: production`. GitHub Actions enforces
deployment protection rules (required reviewers) on any job
that targets a protected environment, causing those jobs to
fail instantly (1s) when protection gates require manual approval.

CI should never use a protected environment — only the actual
deploy job in deploy.yml should.

ci.yml:
- Remove `environment: production` from validate and smoke jobs
  (root cause of the 1s failure)
- Add workflow_dispatch trigger so CI can be run manually
- Upgrade permissions to contents: write, pull-requests: write
- Set cancel-in-progress: false (don't cancel in-flight CI runs)

deploy.yml:
- Add push: branches: [main] trigger (direct pushes also deploy)
- Upgrade permissions to contents: write, pull-requests: write
- Simplify quality-gates `if` condition:
  push || workflow_dispatch || (pull_request && merged == true)

.github/settings.yml:
- New file for Probot Settings App
- main branch: no required reviewers, no strict status checks,
  enforce_admins: false, allow force pushes, allow deletions

https://claude.ai/code/session_01X3PxGFF5zzKptQwVkjYzzN
…dmin panel, disk protection

- deploy.sh: fix early-return to check systemd service status before
  skipping deploy; if code is current but service is down, continue
  deploy to (re)start the service (PR 64 review fix)

- index.js: username confirmation flow (WAITING_FOR_USERNAME never
  auto-accepts typed text; always shows "Yes, Continue / No, Edit"
  confirmation); NON_USERNAME_WORDS guard rejects obvious non-usernames
  (help, hi, back, ?, etc.) with a friendly nudge

- index.js: AFFILIATE_REMINDER_TEXT shown at every required touchpoint:
  onboarding intro, link-username prompt, bonus request flow, promo
  claim view, weekly reminder, existing-account skip, and link-later flow

- index.js: "Tell me more about the 30 SC bonus" button added to
  wagerReminderKeyboard, link-account prompt, bonus confirmation, and
  /start intro; w30_bonus_info action handler explains full promo with
  affiliate reminder and remaining attempts

- index.js: admin panel expanded with "View Completed Requests",
  "Add Username Manually" (w30_admin_completed, w30_admin_link_username),
  "Return to Admin Menu" button, and inline "Mark Tip Sent" flow;
  finaliseUsernameLink helper centralises all username-save logic

- index.js: submitBonusRequest includes attempt count, wager requirement,
  and affiliate reminder in user confirmation message; admin ping updated
  with "admin action required" label

- scripts/disk-protect.sh: new weekly disk-space protection script
  (log rotation, compress logs >1 day, delete logs >7 days, journalctl
  vacuum 300 MB, npm cache clear, temp file cleanup, delete snapshots
  >30 days, never deletes .env or state files)

- prod-run.sh: install disk-protect.sh as weekly Sunday 3 AM cron job

https://claude.ai/code/session_01X3PxGFF5zzKptQwVkjYzzN
… command reference

- COPY.ageGate: add "100% free to play, worldwide" statement with
  Markdown formatting; all senders updated to pass parse_mode: 'Markdown'
- Intro GIF caption + post-age-gate rundown: add explicit "100% FREE /
  worldwide access" line at all onboarding touchpoints
- userMainMenuText: add free-to-play reminder line in the main menu
  header shown to every user on every menu open

- pmenu_help: changed from directly opening the booklet to a Help
  sub-menu with two options: "📖 Command Help Booklet" and "🐞 Report
  a Bug"; both sub-actions fully wired (help_open_booklet,
  help_open_bugreport)

- adminMainMenuKeyboard: added "📖 Admin Commands Reference" and
  "🐞 Bug Reports" buttons directly on the admin main menu (not buried
  in a sub-menu); both wired to pamenu_admin_help and pamenu_bug_reports

- configureBotSurface: complete rewrite of all three command scopes
  (global/default, all_private_chats, all_group_chats) plus the
  per-admin chat scope; every registered command now has an accurate
  description; added leaderboard_weekly, giveaway, and all admin
  commands (deploy, deploy_status, logs, admin_notify, etc.)

- buildHelpPages page 1: add "100% FREE / worldwide" bullet, update
  quick-start to mention GambleCodez affiliate step and 30 SC bonus
- buildHelpPages page 5: completely rewritten as a full user command
  reference grouped by category (Account, Runewager Account, Bonuses,
  Community, Help) with per-command tooltip text for every command
- buildHelpPages page 6: completely rewritten as a full admin command
  reference grouped by category (Dashboard, 30 SC Bonus, Giveaway,
  Announcements, User Mgmt, Bug Reports, System) with usage notes

- ageGateKeyboard: button labels updated to "Yes — I am 18+ and
  eligible" / "No — I am under 18" for clarity

https://claude.ai/code/session_01X3PxGFF5zzKptQwVkjYzzN
deploy.sh — three fixes:

1. ERR trap recovery: trap now uses ${BASH_LINENO[0]} instead of
   $LINENO (which resolves to the trap function's own line, not the
   failing caller). A _SERVICE_STOPPED flag tracks whether systemctl
   stop already ran; the trap attempts systemctl start on the existing
   code so the bot is not left permanently down after a mid-deploy
   failure. The flag is cleared whenever a successful start or rollback
   start fires.

2. npm downtime risk: npm install / npm ci is now wrapped in the same
   conditional guard pattern used for git fetch/reset. On npm failure
   the script logs the full npm output, notifies admins, restarts the
   service on the existing node_modules, and exits 1 — bot comes back
   up rather than staying down.

3. Broad .env export: replaced `set -o allexport; source .env;
   set +o allexport` with targeted grep extraction of only BOT_TOKEN
   and ADMIN_IDS. All other .env variables are never exported into the
   deploy environment, eliminating the risk of unintentional or
   malicious variable leakage.

scripts/disk-protect.sh — two fixes:

4. Safety-check logic bug: CRITICAL_OK is now set to false (not left
   as the initial true) when a critical file is found to be missing.
   The subsequent `if [[ "$CRITICAL_OK" != "true" ]]` branch now
   actually fires and emits the warning as intended.

5. Deletion logging suppression: all `find ... -delete -print | while
   read` patterns replaced with a delete_found() helper that uses
   `find ... -print0` + process substitution + `while IFS= read -r
   -d ''` + `rm -f` in the loop body. This is reliable on both GNU
   and BSD find, handles filenames with spaces/special chars, and
   guarantees the log entry is written for every file actually deleted.
   The same null-delimited pattern is applied to compress (step 2)
   and /tmp cleanup (step 6).

https://claude.ai/code/session_01X3PxGFF5zzKptQwVkjYzzN
- /deploy command: pass process.env to spawn() so deploy.sh inherits
  BOT_TOKEN and ADMIN_IDS — previously all send_admin() calls silently
  returned 0 because the child process had no credentials

- deploy.sh .env parsing: only read from .env when vars are NOT already
  in the environment; when spawned from the bot they're inherited so
  we must not overwrite them; also switch from tr-based quote stripping
  to sed for cleaner surrounding-quote removal

- GitHub Actions deploy job: remove environment: production block which
  can gate the job behind manual approval if the environment has
  protection rules configured — all secrets are repository-level

- disk-protect.sh: append || true to npm cache clean pipeline so a
  permission error from npm never aborts the script under set -euo pipefail

https://claude.ai/code/session_01X3PxGFF5zzKptQwVkjYzzN
…granular Telegram notifications

- Add `environment: Production` to require manual approval gate before VPS deploy
- Replace deploy.sh invocation with fully inline deployment commands (git fetch/reset, npm ci, systemctl stop/start)
- Add cleanup of stray Node processes (pkill) before service restart
- Add dedicated "Notify — deploy job started" step at the top of the deploy job
- Add Telegram notification after pre-deploy health snapshot
- Add per-phase Telegram alerts: key attempt, key success, password fallback triggered, password success, and full failure with action required
- Move post-deploy health check (30s) before rollback/final-report steps; add leading "⏳ in 30s" notification
- Update rollback to use same inline style (stop, pkill, reset, start) with "Starting Rollback" + "Rollback Complete" notifications
- Remove duration field from final deploy report (not available in deploy job scope)

https://claude.ai/code/session_01X3PxGFF5zzKptQwVkjYzzN
- Add promoStore.cooldownDays (Feature 10: per-user promo claim cooldown)
- Add approvedGroupsStore Set (Feature 8: validated group whitelist)
- Add broadcastFailedUsers array (Feature 5: permanent broadcast failure tracking)
- Add referralStore.archivedBoosts array for expired boost history
- Extend createDefaultUser with: streak, lastWeeklyBoostDmAt, language,
  unreachable, giveawayHistory, and supportTicket fields
- Extend serializeGiveaway with paused (Feature 1) and winningSeed (Feature 7)
- Update createRuntimeStateSnapshot to persist new stores and fields
- Update loadRuntimeState to restore approvedGroupsStore, broadcastFailedUsers,
  promoStore.cooldownDays, and referralStore.archivedBoosts
- Update getUser migration block to backfill new fields on existing users,
  including language detection from ctx.from.language_code

https://claude.ai/code/session_01X3PxGFF5zzKptQwVkjYzzN
Admin features:
- Feature 1: Live giveaway pause/resume (/gw_pause, /gw_resume + inline callbacks)
- Feature 2: Internal eligibility scanner (/scan_eligibility)
- Feature 3: Auto-expiring referral boosts cron (hourly expiry + archive)
- Feature 4: Onboarding funnel analytics (/funnel)
- Feature 5: Broadcast queue with retries (/broadcast_retry, /broadcast_failed)
- Feature 7: Manual winner picker with cryptographic seed (/pick_winner)
- Feature 8: Group validation whitelist (/approve_group, /unapprove_group, /list_groups)
- Feature 9: Admin activity log store + /admin_log command
- Feature 10: Per-user promo cooldown manager (/promo_cooldown)
- Feature 11: Discord step monitor (/discord_stats)
- Feature 12: Auto-generated giveaway summary card (/gw_graphic)

User features:
- Feature 13: Stuck-user guided checklist (/stuck)
- Feature 14: Fix-My-Account wizard (/fixaccount)
- Feature 15: Discord step confirmation command (/discord_confirm)
- Feature 16: Personalized giveaway feed (/mygiveaways)
- Feature 17: Auto-DM eligibility fix on group giveaway join failure
- Feature 18: Daily streak check-in with XP + milestone badges (/checkin)
- Feature 19: Multi-metric community leaderboard (/top)
- Feature 20: Referral boost meter with progress bar (/boostmeter)
- Feature 21: Per-giveaway eligibility check (/eligible, gw_elig_check callback)
- Feature 22: Private giveaway join history (/gwhistory) + recorded on gw_join
- Feature 23: Promo eligibility check with cooldown awareness (/promocheck)
- Feature 24: Language detection and info (/language)
- Feature 25: DM-only multi-step support portal (/support, support_type callbacks)
- Feature 26: Weekly auto-DM boost reminder cron (respects unreachable/optout)

Also:
- gw_join now records giveawayHistory entry on each join
- gw_join triggers dmEligibilityFix DM when user fails eligibility from group chat
- Support ticket step-2 description captured in bot.on('text') handler
- Startup block wired with Feature 3 (hourly) and Feature 26 (weekly) crons

https://claude.ai/code/session_01X3PxGFF5zzKptQwVkjYzzN
With set -euo pipefail, a failed journalctl --vacuum-size (e.g.
journald not running, insufficient permissions) would abort the
entire disk-protect.sh run before steps 5+ could execute.

Added || warn fallback so the failure is logged but non-fatal,
consistent with how the npm cache step already handles errors.

https://claude.ai/code/session_01X3PxGFF5zzKptQwVkjYzzN
- scripts/disk-protect.sh: derive APP_DIR from the script's own location
  via BASH_SOURCE so the script targets the correct install directory
  regardless of where it is invoked from (was hardcoded).

- deploy.sh: replace fragile grep/cut/sed .env parsing with a dedicated
  _parse_env_value helper that handles 'export KEY=val', inline comments
  (space-prefixed '#'), single/double-quoted values, and CRLF endings.

- deploy.sh: use ${_SERVICE_STOPPED:-false} in the ERR trap so a future
  re-ordering of the script (or a very early failure) can never cause an
  unexpected recovery-start attempt; also tightened the BASH_LINENO
  comment to clarify bash 4.0+ behaviour.

- .github/workflows/deploy.yml: fix YAML syntax error (line 165) caused
  by multi-line Telegram notification strings whose continuation lines
  fell below the block-scalar indentation level, ending the run: | block
  prematurely; all notification messages now built with $'\n' variable
  concatenation, keeping every line within the required indent.

https://claude.ai/code/session_01X3PxGFF5zzKptQwVkjYzzN
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@coderabbitai

coderabbitai Bot commented Feb 23, 2026

Copy link
Copy Markdown
ℹ️ Recent review info

Configuration used: defaults

Review profile: CHILL

Plan: Free

📥 Commits

Reviewing files that changed from the base of the PR and between f111531 and 9765a19.

📒 Files selected for processing (5)
  • .github/workflows/deploy.yml
  • deploy.sh
  • index.js
  • prod-run.sh
  • scripts/disk-protect.sh

📝 Walkthrough

Walkthrough

This pull request enhances deployment automation and system maintenance by introducing dynamic notification messaging in the CI/CD workflow with granular step updates, improving service recovery and dependency management in the deployment script, and adding a new disk-space protection mechanism via a dedicated maintenance script and cron job.

Changes

Cohort / File(s) Summary
CI/CD Workflow Enhancement
.github/workflows/deploy.yml
Replaces static notifications with dynamic MSG variable construction. Expands Job 2 with explicit Production environment, adds messaging at each deploy phase (SSH setup, health checks, rollback), and introduces intermediate notifications for key-based and password-fallback SSH attempts.
Deployment Script Robustness
deploy.sh
Introduces environment parsing from .env for BOT_TOKEN and ADMIN_IDS. Adds service recovery tracking with _SERVICE_STOPPED flag and enhanced error handling. Improves skip-logic to consider service status. Unifies npm command selection and adds npm failure recovery with service restart fallback.
Disk-Space Management
prod-run.sh, scripts/disk-protect.sh
Adds weekly cron job (03:00) via prod-run.sh to invoke new disk-protect.sh script. New script manages disk usage through log compression, log rotation, journalctl vacuuming, npm cache clearing, temp file removal, and snapshot cleanup with comprehensive logging and safety checks.

Sequence Diagram(s)

sequenceDiagram
    participant GH as GitHub Actions
    participant Deploy as deploy.sh
    participant Env as .env Parser
    participant Bot as Bot Service
    participant SSH as SSH/VPS
    participant TG as Telegram Notify

    GH->>Deploy: Start Deployment
    Deploy->>Env: Parse BOT_TOKEN, ADMIN_IDS
    Env-->>Deploy: Env Loaded
    Deploy->>TG: Send Deploy Start Notification
    Deploy->>Bot: Stop Service (_SERVICE_STOPPED=true)
    Deploy->>SSH: Attempt Key-Based SSH
    alt SSH Key Success
        SSH-->>Deploy: Connected
        Deploy->>TG: SSH Success Notification
    else SSH Key Fails
        Deploy->>SSH: Attempt Password Fallback
        alt Password Success
            SSH-->>Deploy: Connected
            Deploy->>TG: Password Fallback Success
        else Password Fails
            Deploy->>TG: Deploy Failed Notification
            Deploy->>Bot: Restart Service (Recovery)
            Deploy-->>GH: Exit with Error
        end
    end
    Deploy->>Bot: Fetch, Reset, Install Dependencies
    Bot-->>Deploy: Dependencies Ready
    Deploy->>Bot: Start Service (_SERVICE_STOPPED=false)
    Deploy->>TG: Health Check Notification
    Deploy->>TG: Final Deploy Report (Status, Commit, Version)
    Deploy-->>GH: Deployment Complete
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐰 Hops through deploys with messages bright,
Service recovery keeps bots running right,
Disks protected with weekly care,
Logs compressed with logging to spare! 🚀


Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

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

@codeant-ai

codeant-ai Bot commented Feb 23, 2026

Copy link
Copy Markdown

CodeAnt AI is reviewing your PR.

@codeant-ai codeant-ai Bot added the size:L This PR changes 100-499 lines, ignoring generated files label Feb 23, 2026
@codeant-ai

codeant-ai Bot commented Feb 23, 2026

Copy link
Copy Markdown

Nitpicks 🔍

🔒 No security issues identified
⚡ Recommended areas for review

  • Sensitive data exposure
    The script reads BOT_TOKEN and ADMIN_IDS from .env and then exports them into the environment. Exporting secrets to process environment can increase exposure (e.g., visible in /proc//environ or to child processes). Consider minimizing the scope or avoiding export when not required.

  • Error-trap robustness
    The ERR trap relies on BASH_LINENO and is registered with 'trap' after set -euo pipefail. Errors that occur in subshells or some command contexts may not trigger the trap as expected. Also BASH_LINENO semantics can be subtle. Verify the trap behaves reliably across failures (fetch/reset/npm/etc) and consider enabling errtrace so ERR propagates into functions/subshells.

  • Cron execution environment
    The cron entry added for disk-protect invokes the script directly. Cron jobs have a minimal PATH and environment; if the script expects particular PATH or shell features, it may fail when run by cron. Also the cron line doesn't ensure the script is executable. Consider invoking the script with an explicit shell or full interpreter path and ensure executable permission.

Comment thread scripts/disk-protect.sh
Comment on lines +29 to +30
log() { echo "[$(date -u +"%Y-%m-%dT%H:%M:%SZ")] [disk-protect] $*"; }
warn() { echo "[$(date -u +"%Y-%m-%dT%H:%M:%SZ")] [disk-protect] WARN: $*" >&2; }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggestion: The log and warn helpers embed a date command with an unescaped inner double-quoted format string inside an outer double-quoted echo argument; this breaks shell quoting and will cause the script to fail to parse/execute, so the script will never run and the disk protection job will not perform any cleanup. [logic error]

Severity Level: Critical 🚨
- ❌ disk-protect.sh never runs; cron job always fails.
- ⚠️ Log rotation step at line 52 never executes.
- ⚠️ Log compression logic at lines 65–73 never executes.
- ⚠️ Old log deletion via delete_found at lines 79–82 skipped.
- ⚠️ journalctl vacuum at lines 85–89 never invoked.
- ⚠️ npm cache cleanup at lines 95–101 never invoked.
- ⚠️ Temp file cleanup under $DATA_DIR at lines 104–107 skipped.
- ⚠️ Old runtime-state backups under $BACKUP_DIR at lines 114–116 kept.
- ⚠️ Safety check for .env and runtime-state.json at lines 124–135 skipped.
- ⚠️ Disk usage summary logging at lines 139–145 never printed.
Suggested change
log() { echo "[$(date -u +"%Y-%m-%dT%H:%M:%SZ")] [disk-protect] $*"; }
warn() { echo "[$(date -u +"%Y-%m-%dT%H:%M:%SZ")] [disk-protect] WARN: $*" >&2; }
log() { echo "[$(date -u '+%Y-%m-%dT%H:%M:%SZ')] [disk-protect] $*"; }
warn() { echo "[$(date -u '+%Y-%m-%dT%H:%M:%SZ')] [disk-protect] WARN: $*"; }
Steps of Reproduction ✅
1. From the repository root `/workspace/Runewager`, execute `bash scripts/disk-protect.sh`
to run the disk protection script defined in `scripts/disk-protect.sh:1-148`.

2. Bash begins parsing the `log()` function at `scripts/disk-protect.sh:29`, which is
currently `log() { echo "[$(date -u +"%Y-%m-%dT%H:%M:%SZ")] [disk-protect] $*"; }`.

3. The command substitution `$(date -u +"%Y-%m-%dT%H:%M:%SZ")` contains an inner
double-quoted format string inside an outer double-quoted `echo` argument, breaking
quoting; Bash reports a syntax error while parsing this line and exits before running the
rest of the script.

4. Observe that no subsequent steps execute: the first `log "Step 1: Log rotation"` call
at `scripts/disk-protect.sh:52` never runs, the cleanup sections at lines 64–147 are
skipped, and the final `log "Disk protection complete."` at line 148 is never printed.
Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** scripts/disk-protect.sh
**Line:** 29:30
**Comment:**
	*Logic Error: The `log` and `warn` helpers embed a `date` command with an unescaped inner double-quoted format string inside an outer double-quoted echo argument; this breaks shell quoting and will cause the script to fail to parse/execute, so the script will never run and the disk protection job will not perform any cleanup.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
👍 | 👎

@codeant-ai

codeant-ai Bot commented Feb 23, 2026

Copy link
Copy Markdown

CodeAnt AI finished reviewing your PR.

@gamblecodezcom

Copy link
Copy Markdown
Owner Author

All improvements from this PR have been cherry-picked and are already in main:

  • disk-protect.sh: already in main with the same content + path fix (BASH_SOURCE[0])
  • prod-run.sh: weekly disk-protect cron already in main
  • index.js: expireReferralBoosts hourly + runWeeklyBoostReminder weekly intervals already in main
  • deploy.yml: post-deploy health check already in main

The deploy.yml inline deploy commands in this branch also contained broad pkill -f node which was a regression vs the scoped pkill -f Runewager/index.js in main. Closing without merge.

@gamblecodezcom
gamblecodezcom deleted the claude/update-prod-runner-script-Lq2gS branch February 23, 2026 23:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants