Skip to content

Claude/update prod runner script lq2g s - #65

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

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

  • Chores

    • Updated repository governance settings and CI/CD configurations.
    • Enhanced workflow triggers and permissions for improved automation control.
  • New Features

    • Added administrative notification system for deployment events and errors.
    • Implemented password-based authentication fallback for deployment operations.
  • Bug Fixes

    • Improved error handling and recovery mechanisms during deployment processes.
    • Added pre-deployment validation to prevent redundant operations.

CodeAnt-AI Description

Move in-bot deployment to a detached VPS script and add safer, notified deploys

What Changed

  • The /deploy command no longer performs git/npm/restart steps itself; it triggers a detached deploy.sh and exits so the bot process is not restarted by GitHub or the bot.
  • Added deploy.sh with: pre-check to skip if already up-to-date, stop-before-update to avoid file locks, guarded git fetch/reset (rolls back to starting the old service on failure), dependency install, service start, error trap, and silent Telegram admin notifications at every step.
  • GitHub workflow and CI changes: reworked deploy workflow to run only after successful quality gates and valid merges, added SSH password fallback for VPS deploys, adjusted permissions and concurrency behavior, and added repository settings sync.

Impact

✅ Fewer accidental bot restarts from GitHub or in-app deploys
✅ Clearer silent admin notifications during each deploy step
✅ Shorter downtime by stopping service before updates and restoring old service on git failures

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

- 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
@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

Caution

Review failed

The pull request is closed.

📝 Walkthrough

Walkthrough

The changes refactor the deployment pipeline from in-process bot operations to an external deploy.sh script, updates CI/CD workflows with new triggers and gating logic, and adds repository governance configuration. The deploy.sh script introduces Telegram notifications, error handling, pre-deploy checks, and SSH password fallback for VPS deployment.

Changes

Cohort / File(s) Summary
Repository Configuration
.github/settings.yml
Adds Probot Settings App configuration enabling issue tracking, disabling projects/wiki/downloads, configuring main as default branch, and setting permissive branch protection rules.
CI/CD Workflows
.github/workflows/ci.yml, .github/workflows/deploy.yml
CI workflow gains manual trigger and adjusted concurrency settings. Deploy workflow adds PR-based triggers, introduces quality-gate gating logic, implements SSH with password fallback, and delegates deployment to external script.
Deployment Scripts
deploy.sh, index.js
Introduces new deploy.sh script with source detection, environment loading, Telegram admin notifications, error trapping, pre-deploy validation, and improved dependency handling. Refactors index.js to delegate deployment work to deploy.sh via detached subprocess instead of in-process git/npm operations.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 A script takes flight, deployment dreams shine bright,
Telegram whispers when things go right,
Fallback plans nested like burrows deep,
One bot's labor now deploy.sh will keep! 🚀


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.

@gamblecodezcom
gamblecodezcom merged commit 6b1c232 into main Feb 23, 2026
4 of 9 checks passed
@gamblecodezcom
gamblecodezcom deleted the claude/update-prod-runner-script-Lq2gS branch February 23, 2026 03:04
@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

Sequence Diagram

The PR changes the in-bot /deploy command to persist state and delegate the full deployment process to a detached deploy.sh on the VPS. The script then performs stop → update → install → start steps and sends silent Telegram notifications to admins at start and completion.

sequenceDiagram
    participant Admin
    participant Bot
    participant VPS
    participant SystemD
    participant TelegramAPI

    Admin->>Bot: /deploy (admin-only)
    Bot->>Bot: persist runtime state + reply "Deployment starting"
    Bot->>VPS: spawn detached deploy.sh (source: /deploy) and exit
    VPS->>SystemD: stop runewager service
    VPS->>VPS: fetch+reset origin/main → npm ci → start service
    VPS->>TelegramAPI: send_admin "🔄 Deploy started"
    VPS->>TelegramAPI: send_admin "✅ Deploy complete — bot running"
Loading

Generated by CodeAnt AI

@codeant-ai

codeant-ai Bot commented Feb 23, 2026

Copy link
Copy Markdown

Nitpicks 🔍

🔒 No security issues identified
⚡ Recommended areas for review

  • Token exposure risk
    The script embeds BOT_TOKEN in the curl URL. That token can appear in the system process list (ps) while curl runs, which is a sensitive-information exposure risk. Consider approaches that avoid placing secrets directly in the command line.

  • Deploy-skip condition edge case
    The pre-check compares remote HEAD (via git ls-remote) with local git rev-parse HEAD. If the local repo is on a different branch, detached, or otherwise not what you expect, this may give false positives/negatives. Consider ensuring the checked ref matches the branch you intend to deploy (e.g., compare origin/main with the local refs/remotes/origin/main or fetch first).

  • Error context missing
    The trap handler _on_error is only passed the line number. It doesn't include the failing command or exit code, which makes post-mortem triage harder. Also the trap is only set for ERR; commands that exit non-zero in subshells or signal-triggered exits may not provide enough context.

  • Silent notification fallback
    send_admin returns silently (0) when BOT_TOKEN or ADMIN_IDS are not set. If notifications are expected, a missing configuration will produce no alerts and the deployer won't know. Consider logging a visible warning when notifications are disabled.

Comment thread deploy.sh
Comment on lines +92 to +94
say "Already running latest code ($(git rev-parse --short HEAD)) — skipping deploy."
send_admin "✅ Bot is already running the latest version (commit: $(git rev-parse --short HEAD))."
exit 0

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 early-return logic that skips deployment when the local and remote commits match never checks whether the systemd service is actually running, so if the service is down but the code is up to date, running this script (e.g., via a manual VPS call) will immediately exit without restarting the service, leaving the bot offline while reporting that everything is already up to date. [logic error]

Severity Level: Major ⚠️
- ❌ Deploy script skips restarting inactive runewager.service.
- ❌ Admins receive success message while bot remains offline.
- ⚠️ Manual VPS recovery via deploy.sh becomes unreliable.
- ⚠️ Git-based deploy workflows may not self-heal downtime.
Suggested change
say "Already running latest code ($(git rev-parse --short HEAD)) — skipping deploy."
send_admin "✅ Bot is already running the latest version (commit: $(git rev-parse --short HEAD))."
exit 0
ACTIVE="unknown"
if command -v systemctl >/dev/null 2>&1; then
ACTIVE="$(systemctl is-active "${APP_NAME}.service" 2>/dev/null || echo unknown)"
fi
if [[ "$ACTIVE" == "active" ]]; then
say "Already running latest code ($(git rev-parse --short HEAD)) — skipping deploy."
send_admin "✅ Bot is already running the latest version (commit: $(git rev-parse --short HEAD))."
exit 0
else
warn "Code is up to date but service status is: $ACTIVE — continuing deploy to (re)start service."
send_admin "ℹ️ Code is up to date but service status is: $ACTIVE — continuing deploy to (re)start service."
fi
Steps of Reproduction ✅
1. On the VPS, ensure the bot code is already at the same commit as origin/main by running
`git rev-parse HEAD` in `/var/www/html/Runewager` and confirming it matches `git ls-remote
origin -h refs/heads/main` (logic used in `deploy.sh:89-90`).

2. Stop the bot service manually with `sudo systemctl stop runewager.service` and verify
it is down using `systemctl is-active runewager.service` which should return `inactive` or
`failed` (service name confirmed in `deploy.sh:162-173` and `runewager.service` unit
file).

3. Trigger the deployment script, e.g. via SSH with `bash
/var/www/html/Runewager/deploy.sh vps` (usage documented at `deploy.sh:5-11`; same script
is also invoked from the `/deploy` command in `index.js:23-47`).

4. Observe that `deploy.sh` exits via the early-return block at `deploy.sh:91-95`
printing/sending "Already running latest code — skipping deploy." and never reaching the
service start logic at `deploy.sh:160-167`; rerun `systemctl is-active runewager.service`
to confirm the service remains inactive and the bot is still offline despite the "latest
version" message.
Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** deploy.sh
**Line:** 92:94
**Comment:**
	*Logic Error: The early-return logic that skips deployment when the local and remote commits match never checks whether the systemd service is actually running, so if the service is down but the code is up to date, running this script (e.g., via a manual VPS call) will immediately exit without restarting the service, leaving the bot offline while reporting that everything is already up to date.

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: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