Skip to content

Claude/update prod runner script lq2g s - #69

Merged
gamblecodezcom merged 16 commits into
mainfrom
claude/update-prod-runner-script-Lq2gS
Feb 23, 2026
Merged

Claude/update prod runner script lq2g s#69
gamblecodezcom merged 16 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

    • Automated weekly disk space protection to clean up logs, cache, and temporary files, preventing storage issues.
  • Chores

    • Enhanced deployment process with improved health monitoring, error recovery, and notifications.
    • Improved deployment reliability with robust SSH connection handling and authentication fallback options.

CodeAnt-AI Description

Add admin tools, user helpers, weekly maintenance and safer VPS deploys

What Changed

  • Administrators can pause/resume giveaways, pick winners with a cryptographic seed, scan eligibility across users, approve/unapprove groups, view an admin activity log, and run funnel and Discord verification reports.
  • Broadcasts now record permanently failed users and include a retry command; weekly auto-DM reminders and a weekly referral boost DM are sent to eligible users.
  • Users get new self-service commands: personalized giveaway feed, private giveaway history, "Am I eligible?" checks, a Fix-My-Account wizard, a daily streak check-in with XP and badges, referral boost meter, and an in-DM support portal that files a ticket to admins.
  • Promo system gained a configurable per-user cooldown and a promocheck command that shows exact eligibility and remaining cooldown time.
  • Runtime state persists and restores new fields (approved groups, archived referral boosts, broadcast failures, giveaway paused state and winning seeds, user streaks, language, unreachable flag, giveaway history, support tickets) so behavior survives restarts.
  • Weekly disk-protect maintenance script added and installed by prod-run to compress/delete old logs, vacuum journal, clear npm cache/temp files, and remove old runtime snapshots.
  • VPS deploy script and GitHub workflow now send deploy notifications, attempt SSH key then password fallback, perform pre/post health snapshots, try recovery restarts on deploy failures, avoid leaving the service down on npm errors, and only skip deploy when service is active and code matches.

Impact

✅ Clearer giveaway control for admins
✅ Fewer failed broadcasts left unresolved
✅ Shorter recovery time after failed deploys

💡 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 16 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
@codeant-ai

codeant-ai Bot commented Feb 23, 2026

Copy link
Copy Markdown

CodeAnt AI is reviewing your PR.

@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 df45796 and 24cb46b.

📒 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 introduces enhanced deployment automation with multi-step workflows, Telegram notifications, SSH key-first with password fallback mechanism, and robust error recovery. It also adds a new weekly disk space protection system with automated log rotation, compression, and cleanup operations.

Changes

Cohort / File(s) Summary
Deployment Workflow Enhancement
.github/workflows/deploy.yml
Expanded CI/CD pipeline with Telegram notifications at pre-deploy and post-deploy stages, SSH configuration with key persistence and fallback to password authentication, inline multi-step deploy script replacing simple deploy.sh call, explicit health checks with 30-second delay post-deployment, and improved rollback handling with status messaging.
Deploy Script Improvements
deploy.sh
Added service state tracking via _SERVICE_STOPPED flag, environment variable loading from .env file, conditional skip logic when repo is up-to-date and service is active, enhanced error handling with line number reporting and conditional service recovery, dependency installation refactoring (npm ci vs npm install), and improved admin notifications for deployment outcomes.
Cron Job Setup
prod-run.sh
Added conditional block to register weekly disk-space protection cron job running at 03:00 Sunday, with duplicate-entry detection and append-based installation to crontab.
Disk Space Protection
scripts/disk-protect.sh
New executable script providing automated disk management: log rotation/compression (>1 day old), deletion of aged logs, journal vacuum, npm cache clearing, temporary file cleanup, snapshot deletion, and critical file safety checks with disk usage reporting.

Sequence Diagram

sequenceDiagram
    participant GH as GitHub Actions
    participant VPS as VPS Server
    participant Svc as Service
    participant TG as Telegram
    
    GH->>TG: Pre-deploy notification
    GH->>VPS: Attempt SSH with deploy key
    alt SSH Key Success
        VPS->>TG: SSH key attempt logged
        VPS->>VPS: Fetch latest main, reset
        VPS->>Svc: Stop service
        VPS->>VPS: Install dependencies
        VPS->>Svc: Start service
        VPS->>TG: Deploy success via key
    else SSH Key Fails
        VPS->>TG: Key auth failed
        GH->>VPS: Retry via sshpass (password)
        VPS->>TG: Password auth success/failure
    end
    VPS->>VPS: Wait 30 seconds
    VPS->>Svc: Health check (curl local service)
    VPS->>TG: Health status report
    GH->>TG: Final deploy report with status, commit, version
    
    opt Rollback on Failure
        VPS->>Svc: Stop service
        VPS->>Svc: Restart previous version
        VPS->>TG: Rollback notification
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐰 A tale of deployment cheer,
With SSH keys and crons so clear,
Telegram whispers as we deploy,
Disk space freed with disk-protect's joy,
Fallback paths when all else fails,
Your infrastructure never derails! 🚀


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 added the size:XL This PR changes 500-999 lines, ignoring generated files label Feb 23, 2026
@gamblecodezcom
gamblecodezcom merged commit 7eb3238 into main Feb 23, 2026
3 of 5 checks passed
@gamblecodezcom
gamblecodezcom deleted the claude/update-prod-runner-script-Lq2gS branch February 23, 2026 17:53
@codeant-ai

codeant-ai Bot commented Feb 23, 2026

Copy link
Copy Markdown

Nitpicks 🔍

🔒 No security issues identified
⚡ Recommended areas for review

  • Fragile .env parsing
    The new logic extracts BOT_TOKEN and ADMIN_IDS from .env using grep/cut/sed. This approach can fail for exported lines (e.g. export BOT_TOKEN=...), keys containing = or inline comments, multi-line values, or values including spaces. It may also inadvertently expose or mishandle quoting. Consider a safer, more robust parser or a guarded source approach.

  • Error-trap / recovery edge cases
    The ERR trap now attempts a recovery start if _SERVICE_STOPPED is true. Verify that _SERVICE_STOPPED is always set correctly in all failure paths (including early failures), and that recovery won't run on systems without systemd. Also confirm that using BASH_LINENO[0] provides the expected failing line in all bash versions/environments the script runs on.

Comment thread scripts/disk-protect.sh

set -euo pipefail

APP_DIR="${APP_DIR:-/var/www/html/Runewager}"

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 script hardcodes APP_DIR to /var/www/html/Runewager, so when it is invoked from a different install directory (for example, a non-standard deployment path where prod-run.sh still points to its own scripts/disk-protect.sh), it will clean and check the wrong logs/ and data/ directories, which is a logic/Integration bug; instead, derive the default from the script's actual location (while still allowing an explicit APP_DIR override). [logic error]

Severity Level: Critical 🚨
- ❌ Nonstandard deployments have their logs/data never cleaned.
- ❌ Script may clean a different instance under /var/www/html.
- ⚠️ Disk protection reliability depends on matching hardcoded path.
Suggested change
APP_DIR="${APP_DIR:-/var/www/html/Runewager}"
APP_DIR="${APP_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
Steps of Reproduction ✅
1. Deploy the Runewager project to a non-standard directory, for example `/opt/runewager`,
so that `prod-run.sh` itself resides at `/opt/runewager/prod-run.sh` (see project
directory resolution at `/workspace/Runewager/prod-run.sh:16-23`).

2. Run `/opt/runewager/prod-run.sh` as intended; it sets `PROJECT_DIR` to the directory
containing `prod-run.sh` and then installs the weekly cron line
`DISK_PROTECT_SCRIPT="${PROJECT_DIR}/scripts/disk-protect.sh"` at
`/workspace/Runewager/prod-run.sh:271-277`, resulting in a cron job like `0 3 * * 0
/opt/runewager/scripts/disk-protect.sh >> /opt/runewager/logs/disk-protect.log 2>&1`.

3. Ensure no `APP_DIR` environment variable is set in the crontab (the installed line in
`prod-run.sh:271-277` does not export it), which is the default behavior when following
the documented flow.

4. When the cron job runs `/opt/runewager/scripts/disk-protect.sh`, the script computes
`APP_DIR="${APP_DIR:-/var/www/html/Runewager}"` at
`/workspace/Runewager/scripts/disk-protect.sh:14`, so it operates on
`/var/www/html/Runewager/logs` and `/var/www/html/Runewager/data` instead of the actual
deployment at `/opt/runewager/logs` and `/opt/runewager/data`, meaning the real instance's
logs and data are never cleaned while potentially touching an entirely different
installation if that path exists.
Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** scripts/disk-protect.sh
**Line:** 14:14
**Comment:**
	*Logic Error: The script hardcodes `APP_DIR` to `/var/www/html/Runewager`, so when it is invoked from a different install directory (for example, a non-standard deployment path where `prod-run.sh` still points to its own `scripts/disk-protect.sh`), it will clean and check the wrong `logs/` and `data/` directories, which is a logic/Integration bug; instead, derive the default from the script's actual location (while still allowing an explicit `APP_DIR` override).

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.
👍 | 👎

Comment thread scripts/disk-protect.sh
if command -v journalctl >/dev/null 2>&1; then
journalctl --vacuum-size="${JOURNAL_VACUUM_MB}M" 2>&1 | grep -v "^$" | while IFS= read -r line; do
log " [journal] $line"
done

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: Because the script uses set -euo pipefail, any non-zero exit status from the journalctl --vacuum-size pipeline (for example if journald is disabled or permissions are insufficient) will cause the entire disk-protect run to abort, preventing later cleanup steps from executing even though this is intended to be a best-effort maintenance operation; guard the pipeline with an || fallback to treat failures as non-fatal and optionally log a warning. [possible bug]

Severity Level: Major ⚠️
- ❌ disk-protect aborts when journalctl vacuum lacks permission.
- ⚠️ npm cache, temp files, snapshots never cleaned on such runs.
- ⚠️ Safety check for .env/runtime-state.json is completely skipped.
Suggested change
done
done || warn " journalctl vacuum failed (non-fatal)"
Steps of Reproduction ✅
1. Run the production setup script `prod-run.sh` as a non-root user on a system where
`journalctl` exists but `journalctl --vacuum-size=…` requires elevated privileges (see
`/workspace/Runewager/prod-run.sh:1-9`).

2. `prod-run.sh` installs a weekly cron job pointing to
`DISK_PROTECT_SCRIPT="${PROJECT_DIR}/scripts/disk-protect.sh"` at
`/workspace/Runewager/prod-run.sh:271-277`, without wrapping it in any additional error
handling.

3. When cron (or the same non-root user manually) executes
`/workspace/Runewager/scripts/disk-protect.sh`, the script starts with `set -euo pipefail`
at `scripts/disk-protect.sh:12` and progresses through Steps 1–3 successfully.

4. At `scripts/disk-protect.sh:85-89`, the guarded block `if command -v journalctl …; then
journalctl --vacuum-size="${JOURNAL_VACUUM_MB}M" 2>&1 | grep -v "^$" | while …; done`
runs; `journalctl --vacuum-size` exits non-zero due to insufficient permissions, and
because of `set -euo pipefail` this non-zero pipeline status causes the entire script to
abort immediately, so subsequent Steps 5–9 (npm cache cleanup, temp file cleanup, snapshot
pruning, safety check, disk usage summary at `scripts/disk-protect.sh:95-148`) never
execute.
Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** scripts/disk-protect.sh
**Line:** 89:89
**Comment:**
	*Possible Bug: Because the script uses `set -euo pipefail`, any non-zero exit status from the `journalctl --vacuum-size` pipeline (for example if journald is disabled or permissions are insufficient) will cause the entire disk-protect run to abort, preventing later cleanup steps from executing even though this is intended to be a best-effort maintenance operation; guard the pipeline with an `||` fallback to treat failures as non-fatal and optionally log a warning.

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.

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

Labels

size:XL This PR changes 500-999 lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants