Skip to content

Claude/plan v3 deployment vp mpw - #136

Merged
gamblecodezcom merged 20 commits into
mainfrom
claude/plan-v3-deployment-VPMpw
Mar 4, 2026
Merged

Claude/plan v3 deployment vp mpw#136
gamblecodezcom merged 20 commits into
mainfrom
claude/plan-v3-deployment-VPMpw

Conversation

@gamblecodezcom

@gamblecodezcom gamblecodezcom commented Mar 4, 2026

Copy link
Copy Markdown
Owner

User description

Summary by Sourcery

Remove unused admin promo keyboard and harden production restart and deploy notification behavior.

Bug Fixes:

  • Delete dead adminKeyboard() promo keyboard function that no longer has any callers.

Enhancements:

  • Improve prod-run.sh restart logic to fall back to manual kill and nohup start when systemctl restart fails.
  • Relax disown usage in prod-run.sh to avoid errors when nohup backgrounding fails.
  • Simplify Telegram admin deploy notification to send a plain-text health summary without Markdown parsing issues.

Documentation:

  • Update functionality map and audit history to document new backend/rate limiting modules, systemd unit, and latest audit results.
  • Refresh TODO list metadata and mark the removed adminKeyboard() as a resolved bug.

CodeAnt-AI Description

Remove legacy admin promo keyboard and make deploy/restart behavior more robust and observable

What Changed

  • Deleted an unused admin promo keyboard function that had no callers (removes legacy dead-code from the UI codebase)
  • If systemctl restart fails during deployment, the script now kills the old process and restarts the bot with nohup as a fallback so the bot is started reliably
  • Background start uses a tolerant disown to avoid script errors when backgrounding fails
  • Telegram deploy notifications now send a plain-text health summary (URL-encoded) instead of Markdown, avoiding rendering/parsing issues with log or env content
  • Documentation and audit notes updated with the new audit timestamp, added backend/rate-limiter/service entries, and recorded the removed dead function

Impact

✅ Fewer failed restarts during deployments
✅ Clearer deploy notifications to admins (no Markdown rendering errors)
✅ Reduced legacy dead-code reported in audits

💡 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

  • Bug Fixes

    • Removed unused admin keyboard functionality.
    • Improved Markdown text escaping for message formatting.
  • Chores

    • Updated audit documentation with completion status.
    • Enhanced deployment script reliability and health reporting.

…urity, 23 Block 1 fixes

Menu lifecycle overhaul:
- replyMenu() TTL auto-vanish via ttlMs parameter
- clearStaleMenuIds() on startup (24h threshold)
- mainMenuSentAt / adminMenuSentAt timestamps on user schema
- sendHelpMenu() fixed: bare ctx.reply() → replyMenu() (panel stacking bug)
- replaceCallbackPanel() fallback now tracks message ID in user state
- Admin mode toggle double-fire fixed

Feature upgrades:
- User giveaway list: sendUserGiveawaysPage() 5/page + 2-min auto-vanish
- Admin giveaway panel: activeGiveawaysKeyboard(page) 5/page pagination
- pmenu_referral sub-menu with share deep-link button
- Admin stats: active window indicator + Refresh button
- Admin health panel: inline memory/errors/users/persist-age/uptime
- Broadcast builder: Preview button sends to admin DM before mass send

Block 1 security & logic fixes:
- getStartAppLink(): encodeURIComponent + regex whitelist
- referralShareHTML(): escapeHtml() on code param
- unwrapTelegramUrl(): safe fallback, scheme whitelist, www.t.me support
- getDiscordLink(): null when not configured (no hardcoded fallback)
- evaluatePendingActionTimeout(): >= boundary, NaN guard, no createdAt mutation
- getPlayLink(): legacy user.playMode fallback restored
- Weighted winner pool: splice-after-pick guarantees termination
- deploy_status + logs: exec() → execFile() (no shell spawn)
- SSHV: rejects null bytes, backticks, $( and ${ before exec
- Startup env warnings: ADMIN_IDS, TELEGRAM_CHANNEL_ID, TELEGRAM_GROUP_ID

Centralized helpers: computeParticipantWeight(), getRealGiveaways(), isNewUserPromoEligible()

Metrics: added runewager_menu_stale_recoveries, pending_actions_timed_out, uptime_seconds

load_tooltips.sh: full rewrite — atomic write, --push/--pull flags, parameterized REPO_DIR,
  HTML-safe tooltips, --dry-run mode, permission checks, guarded git ops

Tests: readdirSync wrapped in try/catch; isCatchAllRegexPattern expanded;
  extractCommandHandlerNames supports let/var/no-semicolon

Infrastructure: pre-deploy-checks gate 3b (menu symbols), CHANGELOG.md created,
  package.json bumped to 3.0.0

All 60 tests pass. node --check clean.

https://claude.ai/code/session_01VijmtzjN63WZJy5gYgJAKs
… during PR merges

Restores 12 categories of codex changes that were incorrectly overwritten by
"current" (main) when resolving merge conflicts across 6 merge commits.

Security / TLS hardening (index.js):
- Restore resolveTlsCertPathIfAllowed(): multi-directory fallback for TLS certs
  (PROJECT_DIR, certs/, /etc/ssl, /etc/letsencrypt) — was collapsed to PROJECT_DIR only
- Restore isHealthTlsEnabled() to use resolveTlsCertPathIfAllowed()
- Restore requestHealthPayload(): centralized HTTP/HTTPS health fetcher with
  dynamic protocol detection — was inlined with hardcoded https in two places
- Update /health command to use requestHealthPayload() (shows protocol label)
- Update pamenu_tools_health to use requestHealthPayload()
- Update startHealthServer() TLS cert read to use resolveTlsCertPathIfAllowed()

Command injection protection (index.js):
- commandNeedsConfirmation(): restore pipe-to-bash/zsh detection,
  destructive-cmd-piped pattern, redirect pattern — main simplified to only catch "sh"
- commandBlocked(): restore explicit pipe-to-shell blocker pattern

Race condition fixes (index.js):
- deleteEphemeralBonusPrompt(): restore runUserMutation guards for safe
  read-delete-write of ephemeralBonusMsgId/ChatId
- sendEphemeralBonusPrompt(): restore guards (claimedPromo check, active promo lookup),
  per-user dynamic promo lookup via getActivePromoCodeForUser() (was hardcoded
  promoStore.code), "I Have Claimed" callback button, mutation-safe writes
- Add promo_confirm_claimed_next callback handler (button was added, handler missing)

Deploy/runtime hardening (deploy.sh, prod-run.sh, runewager.service):
- deploy.sh: restore data/backups/ mkdir, chown -R APP_NAME, chmod 0750/0640/0600
  permission hardening after npm install
- prod-run.sh: restore chmod 0750 for data/data/backups/logs dirs,
  chmod 0640 for log+session files, chown -R to service user after dir creation
- runewager.service: add UMask=0077 (prevents world-readable files from service)

.gitignore:
- Restore legacy root-level data file patterns: users.json, giveaways.json,
  promo.json, env.json, analytics*.json (pre-data/ directory structure)

All 60 tests pass. node --check clean.

https://claude.ai/code/session_01VijmtzjN63WZJy5gYgJAKs
- TDZ fix: move pendingActionsTimedOut/menuStaleRecoveries declarations
  before evaluatePendingActionTimeout to eliminate temporal dead-zone risk
- Timeout boundary: revert < to <= so age exactly equal to 15m is NOT
  expired — aligns with /testall check and unit test expectations
- /logs line count: clamp to [1, 200] (adds Math.max(1,...) lower bound
  to reject negative/zero values from user input)
- Health panel: fix _errorRate.windowErrors → _errorRate.count (field
  did not exist; .count is the correct field on _errorRate object)
- /logs fallback: add execFile('tail') fallback when journalctl errors
  with no output (non-systemd systems); uses BOT_LOG_FILE env or default
- executeSshvCommand: fix comment — said "spawn" but code uses exec();
  updated to accurately describe exec with shell:true (admin-only)
- load_tooltips.sh: remove || true that defeated diff --cached check,
  causing .gitignore changes to never be committed on --push

All 60 tests pass. node --check clean.

https://claude.ai/code/session_01VijmtzjN63WZJy5gYgJAKs
## Helpful Tooltips (was Content Drops)
- Rename all UI strings: Content Drops → Helpful Tooltips throughout
- New settings panel: interval, silent mode, Link Channel/Group
- Target group linking via forwarded message (saves name + ID)
- Dashboard footer shows real group name + ID
- "Show all Helpful Tooltips (N)" button with dynamic count
- Inline button builder: [Label - URL] && [Label2 - URL2] syntax
  - Multiple buttons per row with &&, new line = new row
  - [Open Bot] shorthand for standard Open Bot button
  - Full URL + label validation before save
- postTipToConfiguredTarget uses silentMode flag + parsed buttons
- tipsStore extended with targetGroupTitle and silentMode fields

## Giveaway v3.0+
- Extracted buildGiveawayAnnouncementText + buildGiveawayAnnouncementKeyboard helpers
- scheduleGiveawayRefresh: auto-refresh at 25%, 50%, 75% of duration + re-pin
- scheduleGiveawayReminders overhauled: 10m, 5m, 1min, 30sec, 10→1 countdown
- HTML results format: @handle, SC WON, (2x boost applied), DM tip
- Full admin winner report per winner: TG handle, display name, RW username, prize, boost
- "View Results in Group" deep-link button in admin report
- Winner DMs include SC amount, boost status, RW username
- DM failure tracking with summary count
- giveawayPreflightCheck: validates group linked, warns on missing pin permission
- gwizStart calls preflight before wizard begins

## Scripts
- generate_tooltips.sh: extracts DEFAULT_TIPS_LIST from index.js → data/tooltips.json (atomic, idempotent)
- add_tooltip.sh: appends placeholder tooltip entry, outputs new ID
- deploy.sh: step 3b auto-runs generate_tooltips.sh before service start
- prod-run.sh: step 6b auto-runs generate_tooltips.sh before bot launch

## /testall
- Added Helpful Tooltips System checks (tipsStore shape, count, interval, target, parser)
- Added Giveaway Extended checks (helpers defined, preflight defined)

## Docs
- RUNEWAGER_FUNCTIONALITY_MAP.md: full v3.0+ sync with flowcharts

All 60 tests pass. node --check clean.

https://claude.ai/code/session_01VijmtzjN63WZJy5gYgJAKs
… linking

- Group command guard middleware: bot.use() intercepts all commands in
  group/supergroup chats and redirects to DM with a deep-link button.
  Passthrough commands with own group logic: link, linkrunewager, giveaway,
  start_giveaway, admin. Suppresses handler execution for all others.

- Onboarding progress bar: onboardingProgressBar(step) renders ●●○○○
  Step N of 5 — Label. showOnboardingPrompt() prepends a Markdown progress
  header (auto-deletes after 8s) before each step-specific prompt.

- Onboarding completion card: shown once (user.onboarding.completionCardShown
  flag) when user reaches the main menu after completing all 5 steps.
  Includes feature summary and Open Menu button.

- Admin System Tools: added 🔗 Group Linking button to
  adminSystemToolsKeyboard() with admin_sys_group_linking action handler
  (renders group linking panel with back-to-system-tools navigation).

- Schema: completionCardShown added to onboarding default + migration guard.
- Map: RUNEWAGER_FUNCTIONALITY_MAP.md fully updated; todolist.md updated.
- All 60 tests pass, node --check clean.

https://claude.ai/code/session_01VijmtzjN63WZJy5gYgJAKs
…ates

PR #112 review fixes (sourcery-ai):
- R1: tips_cmd_import_batch now uses await_tip_import_batch pending type
  with dedicated JSON-array router handler; proper MarkdownV2 prompt
- R2: generate_tooltips.sh fixes command substitution pollution; use
  RUNEWAGER_APP env var instead of process.argv[1] (undefined in node -)
- R3: add_tooltip.sh fixes shell injection; TOOLTIP_TEXT passed via
  TOOLTIP_TEXT_ENV env var, heredoc uses <<'EOF', process.argv[2] for file
- R4: extend catchAllCases array with (.|\n)*, (.|\n)+, (\.|[\s\S])*;
  add post-whitespace-strip forms to CATCH_ALL_CORES set
- R5: extractCommandHandlerNames test now covers let/var declarations and
  no-semicolon forms (CMD_FOUR/eta, CMD_FIVE/theta)
- R6: RUNEWAGER_FUNCTIONALITY_MAP.md typo "auto-deletes 8s" → "after 8s"

Codebase audit duplicate removal:
- A1: remove dead buildGiveawayAnnouncementText(giveaway, remainingStr)
  at ~12533; keep dynamic version at ~13795
- A2: remove simplified buildGiveawayAnnouncementKeyboard at ~13817
  (wrong tgw_participants_ callback); restore full 5-row version
- A3+A4: remove first duplicate bot.action registrations for
  admin_cat_system and admin_cat_support (identical bodies)

All 60 tests pass, node --check clean, bash -n clean on both scripts.

https://claude.ai/code/session_01VijmtzjN63WZJy5gYgJAKs
Resolved conflicts in favour of our branch (HEAD) for:
- index.js: keep await_tip_import_batch router + handler, keep A1/A2
  duplicate-function removal, keep Content Drops branding from main
- add_tooltip.sh / generate_tooltips.sh: keep env-var injection fixes
- test/smoke.test.js: keep extended catchAllCases + extractCommand fixtures
- RUNEWAGER_FUNCTIONALITY_MAP.md / todolist.md: keep our updated content

Incoming from origin/main: claude-pr-results-20260228_193756Z.md

https://claude.ai/code/session_01VijmtzjN63WZJy5gYgJAKs
…ry bot start

Every script that starts/restarts the bot now follows the same safe sequence:
  1. git pull origin main (fetch + reset --hard)
  2. generate_tooltips.sh (extracts DEFAULT_TIPS_LIST → data/tooltips.json)
  3. kill any process blocking PORT (default 3000)
  4. start/restart bot

Changes per file:
- prod-run.sh: add step 9c — free_port_if_conflicted() BEFORE step 10 restart
  (port-kill was already present in God-Mode Heal but fired after, not before)
- deploy.sh: add step 3c — inline lsof/fuser port-kill before systemctl start
- start.sh: add git fetch+reset, generate_tooltips, port-kill, stale-PID kill
  before bot launch; replace refuse-on-duplicate with kill-and-continue
- dev-run.sh: add git fetch+reset (best-effort), generate_tooltips, port-kill
  before exec node
- scripts/rollback.sh: add generate_tooltips after npm ci (refreshes from
  rolled-back index.js), add lsof/fuser port-kill before service start
  (no git pull — rollback intentionally targets an older commit)

https://claude.ai/code/session_01VijmtzjN63WZJy5gYgJAKs
- Escape Markdown special chars in runewagerUsername to prevent parse failures
- Add explicit smoke-test assertions for (.|)* and (.|)+ catch-all forms
- Strip inline comments from .env PORT values in deploy.sh, dev-run.sh, start.sh
  (e.g. PORT=3000 # dev now correctly yields 3000)
- Fix showOnboardingPrompt JSDoc: steps documented as 1–4 → 1–5 (matches impl)
- Upgrade all port-block kill loops to SIGTERM-first then SIGKILL after 2s grace
- Add path + shape validation to generate_tooltips.sh Node extraction block
  (validates RUNEWAGER_APP is absolute .js path; checks array literal size/shape)

https://claude.ai/code/session_01VijmtzjN63WZJy5gYgJAKs
- Create docs/INDEX.md: exhaustive cross-reference of all 95 commands,
  266 action handlers, and 50+ pending action types mapped to feature docs
- Create docs/features/ with 15 per-feature .md files covering every
  bot subsystem (onboarding, menus, giveaway, bonus, promos, tooltips,
  referral, SSHV, deploy, user lookup, group linking, bug reports,
  announcements, misc)
- Create docs/TODO_FUNCTIONALITY_UPGRADE.md with 14 open stale-menu
  and missing-handler items (walkthrough dead-end, clearOldMenus gaps,
  missing tip_view handler, language stub, broadcastFailedUsers cap)
- Update RUNEWAGER_FUNCTIONALITY_MAP.md section 26 with full docs/ table
  and mandate for future Claude sessions to consult docs/INDEX.md first

Future sessions: read docs/INDEX.md → feature .md → index.js (if needed)

https://claude.ai/code/session_01VijmtzjN63WZJy5gYgJAKs
… path validation

- index.js: keep MarkdownV2 escaping for runewagerUsername (security fix)
- generate_tooltips.sh: keep path validation (absolute .js, no traversal)
- start.sh / dev-run.sh / scripts/rollback.sh: keep SIGTERM→SIGKILL two-step
- start.sh: keep inline comment stripping in PORT parse
- test/smoke.test.js: keep (.|)* and (.|)+ catch-all cases

https://claude.ai/code/session_01VijmtzjN63WZJy5gYgJAKs
PR review comment fixes:
- add_tooltip.sh: validate list is Array, filter non-finite IDs before
  computing maxId; throw fast on malformed tooltips.json
- docs/12-group-linking.md: fix entry points table — admin System Tools
  uses admin_sys_group_linking, not admin_cat_system
- docs/15-misc-commands.md: remove ⚠️ walkthrough dead-end note (resolved)

T-01 — Walkthrough system hardened:
- sendWalkthroughStep(): clearOldMenus() before every step send
- Back button disabled on step 1 (first step)
- Next replaced with Finish button on last step (step 35)
- walk_done on last step: sets started=false, fires walkthrough_completed
  analytics, answerCbQuery with success toast, returns to main menu
- New doc: docs/features/16-walkthrough.md

T-02 — clearOldMenus() added to 5 missing locations:
- sendOnboardingReferralPrompt()
- renderSshvConsole()
- renderGroupLinkingTools()
- tips_cmd_edit handler
- tips_cmd_remove handler
(sendGiveawayListPage already used replyMenu() — no change needed)

T-03 — Tooltip view flow implemented:
- tipsDashboardKeyboard(): "👁 View Tooltip" button added (row 4)
- tips_cmd_view handler: clearOldMenus + tipSelectKeyboard('tip_view')
- tip_view_{id} handler: preview card with Prev/Next tip navigation,
  Edit / Toggle / Delete buttons, Back to List, Admin Menu

T-15 — Broadcast failure logging made reliable:
- Removed 500-item cap from broadcastFailedUsers push and load
- Every failure logged via adminLog('broadcast_failure', ...) to
  data/admin-events.log — no silent drops
- /broadcast_failed: chunked output (30/chunk, up to 90 inline);
  overflow note points to log file
- High-failure-rate warning: >20% failure rate sends ⚠️ DM to ADMIN_IDS

Merge conflicts resolved (PRs #112-114):
- index.js: keep MarkdownV2 escaping for runewagerUsername
- generate_tooltips.sh: keep path validation (absolute .js, no traversal)
- start.sh/dev-run.sh/rollback.sh: keep SIGTERM→SIGKILL two-step
- test/smoke.test.js: keep (.|)* and (.|)+ catch-all test cases

Tests: 60/60 pass | node --check: clean | bash -n: all scripts OK

https://claude.ai/code/session_01VijmtzjN63WZJy5gYgJAKs
Three changes addressing remaining PR #115 review feedback:

1. generate_tooltips.sh — skip guard to preserve runtime tips
   - Skip regeneration if data/tooltips.json already has entries.
   - Prevents admin-added tooltips (broadcast every 4h via bot) from
     being overwritten on every restart or deploy.
   - Add --force flag to override the guard when intentional reset is needed.
   - --dry-run still works regardless of the guard.

2. scripts/helpers/free_port.sh — shared SIGTERM→SIGKILL helper
   - Extracts duplicated port-freeing logic (lsof/fuser, SIGTERM→SIGKILL)
     from start.sh, dev-run.sh, deploy.sh, and scripts/rollback.sh into a
     single reusable helper (sourceable or callable directly).
   - Reduces drift: future tweaks to kill strategy happen in one place.

3. start.sh / dev-run.sh — RUNEWAGER_AUTO_UPDATE gate
   - git fetch + reset --hard origin/main is now conditional on
     RUNEWAGER_AUTO_UPDATE env var (default 1 in prod start.sh,
     default 0 in dev-run.sh).
   - Prevents silent discard of local/staging uncommitted changes.
   - Documented in .env.example.

https://claude.ai/code/session_01VijmtzjN63WZJy5gYgJAKs
1. generate_tooltips.sh — normalize APP_DIR to absolute path
   Move helper function definitions (info/warn/error) before variable
   assignments so error() is available at init time.  Normalize
   RUNEWAGER_DIR → APP_DIR via cd+pwd immediately after assignment so the
   Node.js absolute-path validation (requires '/'-prefixed path) never
   fails when a caller passes a relative RUNEWAGER_DIR.

2. scripts/helpers/free_port.sh — re-query port before SIGKILL
   Extract discovery into _query_port_pids() helper.  After the SIGTERM
   grace period, re-query the port for survivors and only SIGKILL PIDs
   that are still listening — guards against killing an unrelated process
   that reused a PID during the 2 s sleep window.

3. dev-run.sh — read RUNEWAGER_AUTO_UPDATE from .env as fallback
   Parse RUNEWAGER_AUTO_UPDATE from .env before the auto-update guard so
   the flag works even when .env values have not been exported into the
   calling shell.  Use explicit if/else instead of chained && || for the
   destructive git reset --hard command.

4. start.sh — same .env-read fix + explicit if/else for git reset
   Same pattern as dev-run.sh: resolve RUNEWAGER_AUTO_UPDATE from env
   then .env (default 1 for prod), replace the chained git &&/|| with an
   explicit if/else block.

https://claude.ai/code/session_01VijmtzjN63WZJy5gYgJAKs
1. generate_tooltips.sh — case-based arg parser
   Replace the for-loop [[]] checks with a case statement that rejects
   unknown flags (e.g. --froce typo) with a clear error and non-zero exit.

2. generate_tooltips.sh — env-var file paths in Node.js invocations
   The three inline node -e calls that interpolated $TOOLTIPS_FILE /
   $TMP_FILE directly into single-quoted JS strings were fragile for paths
   containing quotes or special characters.  All three now pass the path
   via a dedicated env var (TOOLTIPS_FILE_PATH or VALIDATE_FILE) and read
   process.env inside the script, matching the existing RUNEWAGER_APP pattern.

3. dev-run.sh — non-fatal free_port.sh invocation
   free_port.sh can exit non-zero on benign errors (no lsof/fuser, race
   after SIGTERM) which would abort dev-run.sh under set -eu.  Added
   || echo WARN fallback to mirror the same non-fatal pattern used for the
   tooltip script invocation directly above.

https://claude.ai/code/session_01VijmtzjN63WZJy5gYgJAKs
1. generate_tooltips.sh — trap for TMP_FILE cleanup
   Register 'trap rm -f TMP_FILE EXIT INT TERM' immediately before the
   atomic write section so the temp file is always removed on any exit
   (error, signal, or normal completion).  After a successful mv the path
   no longer exists, so the trap is a safe no-op on the happy path.

2. dev-run.sh — default to merge --ff-only; gate reset --hard behind opt-in
   Auto-update now runs 'git fetch + merge --ff-only' (non-destructive).
   'git reset --hard origin/main' is only executed when RUNEWAGER_FORCE_RESET=1
   is set in the environment or .env, satisfying the "confirm destructive
   operations" guideline.  Fast-forward failure emits a clear warning
   pointing the user to RUNEWAGER_FORCE_RESET.
   Documented in .env.example.

https://claude.ai/code/session_01VijmtzjN63WZJy5gYgJAKs
- Merged main branch: telegramSafe.js, rateLimiter.js, backend.js,
  runewager-endpoint.service, prod-run.sh rewrite, runewager_redeploy.sh,
  rw_cpu_guard.sh
- Removed dead code: legacy adminKeyboard() function (JSDoc + body,
  ~32 lines) — no callers, belonged to removed /admin_menu command
- RUNEWAGER_FUNCTIONALITY_MAP.md: updated last-audited date, added new
  module entries (telegramSafe, rateLimiter, backend, service, scripts),
  added 2026-03-04 audit log entry
- todolist.md: updated last-updated date, added fixed adminKeyboard entry
- All 60 tests pass post-fix

https://claude.ai/code/session_01VijmtzjN63WZJy5gYgJAKs
…mode

Three code-review fixes:

1. Section 10 (Safe restart): `|| true` swallowed systemctl failures and
   left the bot stopped. Replaced with `if ! systemctl restart ...; then`
   block that falls back to manual kill + nohup when systemd fails.

2. Bare `disown` (non-systemd path, L506): with `set -euo pipefail` a
   failed `disown` (no job control in non-interactive shells) aborted the
   script before post-start health checks and Telegram reporting ran.
   Fixed: `disown || true` in both the fallback and non-systemd paths.

3. Telegram notification: removed `parse_mode=Markdown` (unescaped log
   content and env values can break Markdown rendering / cause truncation).
   Switched to plain text with `--data-urlencode` so special chars in
   the message are safe without manual escaping. Removed unused `_REPORT`
   variable (log tail was computed but never injected into the message).

60/60 tests pass.

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

codeant-ai Bot commented Mar 4, 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 4, 2026

Copy link
Copy Markdown

Reviewer's Guide

Cleans up a dead admin promo keyboard helper, hardens the production restart script with a systemd failure fallback and safer disown usage, and updates audit/documentation metadata to reflect the latest /runewager-audit pass and new backend/runtime components.

Sequence diagram for deploy restart and Telegram notification

sequenceDiagram
    actor Admin
    participant prod_run_sh
    participant systemd
    participant NodeProcess
    participant TelegramAPI

    Admin->>prod_run_sh: Execute prod-run.sh
    prod_run_sh->>prod_run_sh: Detect existing PID
    alt systemd available and service file exists
        prod_run_sh->>systemd: restart APP_NAME.service
        alt systemd restart succeeds
            systemd-->>prod_run_sh: Service restarted
        else systemd restart fails
            prod_run_sh->>prod_run_sh: Log warning and fallback
            prod_run_sh->>NodeProcess: kill existing PID (if any)
            prod_run_sh->>NodeProcess: start via nohup node index.js
            prod_run_sh->>prod_run_sh: disown with failure ignored
        end
    else systemd not available or service file missing
        prod_run_sh->>NodeProcess: kill existing PID (if any)
        prod_run_sh->>NodeProcess: start via nohup node index.js
        prod_run_sh->>prod_run_sh: disown with failure ignored
    end

    prod_run_sh->>prod_run_sh: Sleep and refresh PID, run health checks

    prod_run_sh->>prod_run_sh: Build plain text _MSG without parse_mode
    loop For each admin id
        prod_run_sh->>TelegramAPI: sendMessage(chat_id, text) via URL-encoded POST
        TelegramAPI-->>prod_run_sh: HTTP response (ignored on failure)
    end
Loading

Class diagram for removal of legacy adminKeyboard helper

classDiagram
    class index_js {
        <<module>>
        +linkPrefKeyboard()
        %% adminKeyboard() removed as dead code
    }
Loading

Flow diagram for updated prod-run.sh restart logic

flowchart TD
    A[Start prod-run restart section] --> B{Existing PID found}
    B -- yes --> C[Log: Safe restart of running bot]
    B -- no --> D{systemctl available and service file exists}

    C --> D

    D -- yes --> E{systemctl restart APP_NAME.service succeeds}
    D -- no --> H[Kill existing PID if present]

    E -- yes --> I[Continue after restart]
    E -- no --> F[Log warning: systemctl restart failed]

    F --> G[Kill existing PID if present]
    G --> J[Sleep 1s]
    J --> K[Start bot via nohup node index.js]
    K --> L[disown with failure ignored]
    L --> I

    D -- no --> H
    H --> M[Start bot via nohup node index.js]
    M --> N[disown with failure ignored]
    N --> I

    I --> O[Sleep 3s and refresh PID]
    O --> P[Continue to health checks and notifications]
Loading

File-Level Changes

Change Details Files
Remove unused legacy admin promo keyboard helper from the main bot file.
  • Delete the JSDoc block describing the admin promo keyboard helper.
  • Remove the admin promo keyboard function that built the inline promo management keyboard, which had no remaining callers.
index.js
Improve robustness and observability of the prod-run deployment script.
  • Wrap systemd restart in a conditional and, on failure, fall back to manually killing the existing PID (if present) and starting the bot via nohup, logging a warning and confirmation message.
  • Ensure disown is invoked with `
Refresh documentation and TODO metadata to reflect the latest audit results and new runtime components.
  • Update the functionality map audit stamp to 2026-03-04 with notes from the /runewager-audit pass and mention that there were zero critical issues and zero warnings after fixes.
  • Document new internal modules and scripts such as telegramSafe.js, rateLimiter.js, backend.js, the expanded scripts set, and the runewager-endpoint systemd unit in the functionality map.
  • Append new audit history entries describing the 2026-03-04 merge of main (backend/rate-limiter/telegramSafe/prod-run/scripts) and the /runewager-audit findings, including the removal of the dead adminKeyboard function and test status.
  • Update todolist.md’s last-updated line to 2026-03-04 and add a completed BUG item documenting the dead adminKeyboard function removal and its context.
RUNEWAGER_FUNCTIONALITY_MAP.md
todolist.md

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

@coderabbitai

coderabbitai Bot commented Mar 4, 2026

Copy link
Copy Markdown

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 27e2dfcf-fafa-4758-8125-43387f3aacac

📥 Commits

Reviewing files that changed from the base of the PR and between aa3ad03 and f0bcd13.

📒 Files selected for processing (4)
  • RUNEWAGER_FUNCTIONALITY_MAP.md
  • index.js
  • prod-run.sh
  • todolist.md

📝 Walkthrough

Walkthrough

This PR documents v3.1 audit completion (0 critical issues, 1 warning resolved), removes the legacy adminKeyboard() function from index.js, hardens the production restart script with fallback logic for failed systemd restarts, and converts admin notifications from Markdown to plain-text URL-encoded format.

Changes

Cohort / File(s) Summary
Audit & Documentation
RUNEWAGER_FUNCTIONALITY_MAP.md, todolist.md
Updated audit metadata to 2026-03-04 with 0 critical/warning findings post-fix. Added entries for new modules (telegramSafe.js, rateLimiter.js, backend.js) and systemd service. Documented dead code removal (adminKeyboard) and escapeMarkdownV2 issues in bug list.
Code Cleanup
index.js
Removed public adminKeyboard() function (32 lines) which returned inline keyboard for admin promo controls with no remaining callers.
Deployment Hardening
prod-run.sh
Enhanced systemd restart with fallback to nohup/disown on failure. Updated admin notifications and health reporting from Markdown parse_mode to plain-text URL-encoded format using data-urlencode. Added PID re-detection after restart and structured health status messaging.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

codex, size:XL

Poem

🐰 A keyboard retired, its keys now at rest,
The audit's complete—v3.1 is the best!
When restarts should stumble, we'll fallback with grace,
Plain messages flowing at a rollicking pace! 🚀

✨ 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/plan-v3-deployment-VPMpw

Tip

Try Coding Plans. Let us write the prompt for your AI agent so you can ship faster (with fewer bugs).
Share your feedback on Discord.


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:S This PR changes 10-29 lines, ignoring generated files label Mar 4, 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 reviewed your changes and they look great!


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.

@gamblecodezcom
gamblecodezcom merged commit 939ab4d into main Mar 4, 2026
5 of 6 checks passed
@gamblecodezcom
gamblecodezcom deleted the claude/plan-v3-deployment-VPMpw branch March 4, 2026 15:18
@codeant-ai

codeant-ai Bot commented Mar 4, 2026

Copy link
Copy Markdown

Nitpicks 🔍

🔒 No security issues identified
⚡ Recommended areas for review

  • Restart fallback race
    If systemctl restart fails, the fallback kills the original PID and immediately starts a nohup process.
    If systemctl partially started a new process in the meantime (or the PID has changed), this can kill the wrong process
    or leave a stray process/listener bound to the port. The fallback also doesn't re-check or free the bound port before starting.

  • Node binary path
    The nohup fallback launches node directly. That may pick a different node binary than the systemd ExecStart (or be missing from PATH).
    Use a resolved node path (same runtime used to generate systemd unit) to avoid inconsistent binaries/versions at runtime.

Comment thread prod-run.sh
# Telegram admin notification (plain text — no parse_mode to avoid Markdown rendering issues
# with unescaped log content or special chars in env values)
_ADMIN_IDS="$(read_env_value ADMIN_IDS || true)"
_BOT_TOKEN="$(read_env_value TELEGRAM_BOT_TOKEN || true)"

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 deploy-complete Telegram notification only reads the legacy TELEGRAM_BOT_TOKEN from .env and ignores the canonical BOT_TOKEN (and any exported BOT_TOKEN env var), so on setups that follow the documented convention of using BOT_TOKEN only, the health summary message will never be sent even though the bot runs correctly. [logic error]

Severity Level: Major ⚠️
- ⚠️ prod-run.sh post-deploy Telegram summary skipped with BOT_TOKEN-only.
- ⚠️ Ops lose automatic health summary after each deployment.
Suggested change
_BOT_TOKEN="$(read_env_value TELEGRAM_BOT_TOKEN || true)"
# Prefer canonical BOT_TOKEN (env or .env), fall back to legacy TELEGRAM_BOT_TOKEN alias
_BOT_TOKEN="${BOT_TOKEN:-$(read_env_value BOT_TOKEN || read_env_value TELEGRAM_BOT_TOKEN || true)}"
Steps of Reproduction ✅
1. Configure the bot using the documented canonical token: in `/workspace/Runewager/.env`,
set `BOT_TOKEN=...` and `ADMIN_IDS=...` while leaving `TELEGRAM_BOT_TOKEN` unset or empty
(README recommends `BOT_TOKEN` at `README.md:15` and `.env.example` declares `BOT_TOKEN`
as the canonical name at `CLAUDE_FIX_PR.md:2474`).

2. Start the bot normally (e.g., via systemd using the unit generated by `prod-run.sh`)
and confirm it runs: `index.js:14` defines `const BOT_TOKEN = process.env.BOT_TOKEN ||
process.env.TELEGRAM_BOT_TOKEN;`, so with only `BOT_TOKEN` set the application starts
successfully and serves the health endpoint.

3. Run the deployment runner `prod-run.sh` from `/workspace/Runewager` as intended for
production deployments; it performs the restart and post-start health check (section 10
and 11, `prod-run.sh:496-553`), and the health check succeeds so the script reaches the
Telegram notification block at `prod-run.sh:556-569`.

4. In that notification block, `_ADMIN_IDS` is populated from `.env`, but `_BOT_TOKEN` is
set only via `read_env_value TELEGRAM_BOT_TOKEN` (`prod-run.sh:558-559`), which returns
empty when `TELEGRAM_BOT_TOKEN` is not configured; the condition `[[ -n "$_BOT_TOKEN" &&
-n "$_ADMIN_IDS" ]]` at `prod-run.sh:560` fails, so the `curl` loop at
`prod-run.sh:563-567` never executes and no "Deploy complete" Telegram messages are sent,
despite the bot and health checks working correctly with `BOT_TOKEN`.
Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** prod-run.sh
**Line:** 559:559
**Comment:**
	*Logic Error: The deploy-complete Telegram notification only reads the legacy `TELEGRAM_BOT_TOKEN` from `.env` and ignores the canonical `BOT_TOKEN` (and any exported `BOT_TOKEN` env var), so on setups that follow the documented convention of using `BOT_TOKEN` only, the health summary message will never be sent even though the bot runs correctly.

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 Mar 4, 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:S This PR changes 10-29 lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants