diff --git a/docs/code-bridge/requests/REQ-2026-04-15-bitch-bot.md b/docs/code-bridge/archive/REQ-2026-04-15-bitch-bot.md similarity index 100% rename from docs/code-bridge/requests/REQ-2026-04-15-bitch-bot.md rename to docs/code-bridge/archive/REQ-2026-04-15-bitch-bot.md diff --git a/docs/code-bridge/status/ACTIVE_CONTEXT.md b/docs/code-bridge/status/ACTIVE_CONTEXT.md index 609f0f6..a92a0e4 100644 --- a/docs/code-bridge/status/ACTIVE_CONTEXT.md +++ b/docs/code-bridge/status/ACTIVE_CONTEXT.md @@ -1,11 +1,20 @@ # Code Status Update -**Last Updated:** 2026-04-15 (local Nitro session — end of night) +**Last Updated:** 2026-04-15 (post-launch, late night — Michael away) ## Environment Change Now running **locally on the Nitro** (Windows 11) instead of the remote dev server. Working directory: `C:\Users\mkrau\firefrost-services`. Git remote still pushes to Gitea. Git identity configured repo-local as `Claude Code `. ## Current Focus -Bridge queue cleared for the night. Only remaining REQ is `REQ-2026-04-12-phase11e-gitbook-scope` (post-launch, not urgent — deferred). +Bridge queue empty. Launch went out earlier with reaction-roles + Carl-bot migration shipped (`f4f96df`). Bitch Bot scaffold complete on Nitro, awaiting Dev Panel compile. + +## Post-Launch Session 2026-04-15 + +### Shipped +- **REQ-2026-04-15-reaction-roles** (`f4f96df`) — pre-launch dispatch. Reaction roles for #get-roles (3 messages, 20 emoji→role mappings), Wanderer auto-assign + welcome DM on `guildMemberAdd`, link-reminder DM after Stripe checkout. Added `GuildMessageReactions` + `DirectMessages` intents and `Partials.Message/Channel/Reaction` to client. All silent-fail. +- **REQ-2026-04-15-bitch-bot** — full source scaffold. NeoForge 1.21.1 mod, 7 Java files + gradle config + mods.toml + sample-provision.json + project CLAUDE.md. Mirrors rules-mod/1.21.1 layout. **NOT compiled — Java/Gradle not available on Nitro per CLAUDE.md. Compile on Dev Panel.** + - Files: `BitchBot.java` (entry + ServerStartedEvent), `Provisioner.java` (sequenced step runner with per-step try/catch), `ProvisionConfig.java` (Gson POJO), `SchematicLoader.java` (HTTP + SHA-256 + Sponge v2 .schem parser using `NbtIo.read` + varint decode + palette resolution via `BlockStateParser`), `CommandBlockPlacer.java` (impulse command blocks with `/tp @p [origSpawn]` baked into `CommandBlockEntity`), `SignPlacer.java` (oak signs, 4-line front text via `SignBlockEntity#setText`), `YawpConfigWriter.java` (drops region JSON to `world/serverconfig/yawp/regions/`), `SelfDestruct.java` (locates own jar via `ProtectionDomain` and renames to `.jar.disabled`) + - Build: `cd services/bitch-bot/1.21.1 && source use-java 21 && /opt/gradle-8.8/bin/gradle build --no-daemon` → `build/libs/BitchBot-1.0.0-neoforge-1.21.1.jar` + - **Risk areas to test on first compile:** Sponge v2 schematic parser (untested against real WorldEdit output), command block NBT persistence, YAWP file format (best guess at schema — may need a tweak in `YawpConfigWriter` once we see what YAWP actually expects). All failures log gracefully and skip self-destruct so Bitch Bot can be retried. ## Session Summary (2026-04-14 Evening) diff --git a/services/bitch-bot/1.21.1/build.gradle b/services/bitch-bot/1.21.1/build.gradle new file mode 100644 index 0000000..c1bc127 --- /dev/null +++ b/services/bitch-bot/1.21.1/build.gradle @@ -0,0 +1,41 @@ +plugins { + id 'java-library' + id 'net.neoforged.moddev' version '2.0.141' +} + +version = mod_version +group = mod_group_id + +repositories { + mavenCentral() +} + +dependencies { + // Gson is bundled with Minecraft (com.google.code.gson:gson) — no extra dep. +} + +neoForge { + version = neo_version + + runs { + server { + server() + } + } + + mods { + "${mod_id}" { + sourceSet sourceSets.main + } + } +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' + options.release.set(21) +} + +jar { + archiveBaseName.set("BitchBot") + archiveVersion.set("${mod_version}-neoforge-${minecraft_version}") +} diff --git a/services/bitch-bot/1.21.1/gradle.properties b/services/bitch-bot/1.21.1/gradle.properties new file mode 100644 index 0000000..2785a09 --- /dev/null +++ b/services/bitch-bot/1.21.1/gradle.properties @@ -0,0 +1,10 @@ +org.gradle.jvmargs=-Xmx3G +org.gradle.daemon=false + +minecraft_version=1.21.1 +neo_version=21.1.65 + +mod_id=bitchbot +mod_name=Bitch Bot +mod_version=1.0.0 +mod_group_id=com.firefrostgaming.bitchbot diff --git a/services/bitch-bot/1.21.1/gradle/wrapper/gradle-wrapper.jar b/services/bitch-bot/1.21.1/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e644113 Binary files /dev/null and b/services/bitch-bot/1.21.1/gradle/wrapper/gradle-wrapper.jar differ diff --git a/services/bitch-bot/1.21.1/gradle/wrapper/gradle-wrapper.properties b/services/bitch-bot/1.21.1/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..a441313 --- /dev/null +++ b/services/bitch-bot/1.21.1/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/services/bitch-bot/1.21.1/gradlew b/services/bitch-bot/1.21.1/gradlew new file mode 100644 index 0000000..b740cf1 --- /dev/null +++ b/services/bitch-bot/1.21.1/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/services/bitch-bot/1.21.1/gradlew.bat b/services/bitch-bot/1.21.1/gradlew.bat new file mode 100644 index 0000000..25da30d --- /dev/null +++ b/services/bitch-bot/1.21.1/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/services/bitch-bot/1.21.1/settings.gradle b/services/bitch-bot/1.21.1/settings.gradle new file mode 100644 index 0000000..c758be6 --- /dev/null +++ b/services/bitch-bot/1.21.1/settings.gradle @@ -0,0 +1,12 @@ +pluginManagement { + repositories { + gradlePluginPortal() + maven { url = 'https://maven.neoforged.net/releases' } + } +} + +plugins { + id 'org.gradle.toolchains.foojay-resolver-convention' version '0.8.0' +} + +rootProject.name = 'bitchbot' diff --git a/services/bitch-bot/1.21.1/src/main/java/com/firefrostgaming/bitchbot/BitchBot.java b/services/bitch-bot/1.21.1/src/main/java/com/firefrostgaming/bitchbot/BitchBot.java new file mode 100644 index 0000000..99f1395 --- /dev/null +++ b/services/bitch-bot/1.21.1/src/main/java/com/firefrostgaming/bitchbot/BitchBot.java @@ -0,0 +1,49 @@ +package com.firefrostgaming.bitchbot; + +import net.neoforged.bus.api.IEventBus; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.fml.ModContainer; +import net.neoforged.fml.common.Mod; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.event.server.ServerStartedEvent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Bitch Bot — first-boot server provisioning mod for Firefrost Gaming. + * + * Named by Holly (The Catalyst). Architecture locked via 4-round Gemini + * consultation: see firefrost-operations-manual/docs/consultations/ + * gemini-modpack-installer-followup-2026-04-15.md + * + * Lifecycle: + * 1. Server boots, mod loads. + * 2. ServerStartedEvent fires. + * 3. If ./provision.json is missing → log + exit silently. The bot is dormant. + * 4. If present → hand off to {@link Provisioner}, which runs every step + * sequentially. Failures are logged but never crash the server. + * 5. If self_destruct_on_success is true and provisioning succeeded, rename + * our own jar to .jar.disabled so this never runs again. + */ +@Mod(BitchBot.MODID) +public class BitchBot { + public static final String MODID = "bitchbot"; + public static final Logger LOGGER = LoggerFactory.getLogger("BitchBot"); + + public BitchBot(IEventBus modEventBus, ModContainer modContainer) { + NeoForge.EVENT_BUS.register(this); + LOGGER.info("Bitch Bot loaded — waiting for ServerStartedEvent."); + } + + @SubscribeEvent + public void onServerStarted(ServerStartedEvent event) { + try { + new Provisioner(event.getServer()).run(); + } catch (Throwable t) { + // Last-resort guard — Provisioner already swallows individual step + // failures, but if a NoClassDefFoundError or similar escapes here, + // we MUST NOT take down the server. + LOGGER.error("[BitchBot] Fatal provisioning error (server NOT crashed):", t); + } + } +} diff --git a/services/bitch-bot/1.21.1/src/main/java/com/firefrostgaming/bitchbot/CommandBlockPlacer.java b/services/bitch-bot/1.21.1/src/main/java/com/firefrostgaming/bitchbot/CommandBlockPlacer.java new file mode 100644 index 0000000..3572587 --- /dev/null +++ b/services/bitch-bot/1.21.1/src/main/java/com/firefrostgaming/bitchbot/CommandBlockPlacer.java @@ -0,0 +1,79 @@ +package com.firefrostgaming.bitchbot; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.CommandBlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.block.state.properties.BlockStateProperties; + +import java.util.List; + +/** + * Places impulse command blocks at each position from provision.json with + * "/tp @p originalSpawn.x originalSpawn.y originalSpawn.z" baked in. + * + * Uses CommandBlockEntity directly rather than spawning items / triggering + * events. The command-block GUI normally requires op + cheats enabled to + * write to NBT, but server-side code goes underneath that gate. + * + * Block facing comes from provision.json. We use BlockStateProperties.FACING + * which command blocks support natively. + */ +public class CommandBlockPlacer { + + public static void placeAll(ServerLevel level, + List entries, + BlockPos originalSpawn) { + if (entries == null || entries.isEmpty()) { + BitchBot.LOGGER.info("[BitchBot] No command blocks specified — skipping."); + return; + } + + String tpCommand = String.format("tp @p %d %d %d", + originalSpawn.getX(), originalSpawn.getY(), originalSpawn.getZ()); + + int placed = 0; + for (ProvisionConfig.CommandBlockEntry entry : entries) { + try { + BlockPos pos = new BlockPos(entry.position.x, entry.position.y, entry.position.z); + Direction facing = parseFacing(entry.facing); + + BlockState state = Blocks.COMMAND_BLOCK.defaultBlockState(); + if (state.hasProperty(BlockStateProperties.FACING)) { + state = state.setValue(BlockStateProperties.FACING, facing); + } + level.setBlock(pos, state, 2); + + BlockEntity be = level.getBlockEntity(pos); + if (be instanceof CommandBlockEntity cbe) { + cbe.getCommandBlock().setCommand(tpCommand); + cbe.getCommandBlock().setName(net.minecraft.network.chat.Component.literal("Bitch Bot — Spawn Return")); + cbe.setChanged(); + placed++; + } else { + BitchBot.LOGGER.warn("[BitchBot] Command block at {} has no BlockEntity after setBlock — skipped.", pos); + } + } catch (Throwable t) { + BitchBot.LOGGER.error("[BitchBot] Failed to place command block: {}", t.getMessage()); + } + } + BitchBot.LOGGER.info("[BitchBot] Command blocks placed: {} / {}", placed, entries.size()); + } + + private static Direction parseFacing(String s) { + if (s == null) return Direction.UP; + switch (s.toLowerCase()) { + case "down": return Direction.DOWN; + case "north": return Direction.NORTH; + case "south": return Direction.SOUTH; + case "east": return Direction.EAST; + case "west": return Direction.WEST; + case "up": + default: return Direction.UP; + } + } +} diff --git a/services/bitch-bot/1.21.1/src/main/java/com/firefrostgaming/bitchbot/ProvisionConfig.java b/services/bitch-bot/1.21.1/src/main/java/com/firefrostgaming/bitchbot/ProvisionConfig.java new file mode 100644 index 0000000..902b50d --- /dev/null +++ b/services/bitch-bot/1.21.1/src/main/java/com/firefrostgaming/bitchbot/ProvisionConfig.java @@ -0,0 +1,72 @@ +package com.firefrostgaming.bitchbot; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.annotations.SerializedName; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +/** + * Plain-old-data representation of provision.json. See spec in + * REQ-2026-04-15-bitch-bot.md. Loaded once at ServerStartedEvent. + * + * Field names mirror the JSON exactly so Gson can deserialize without + * additional annotations except where Java reserved words / casing collide. + */ +public class ProvisionConfig { + + public String version; + public String schematic_name; + public String schematic_url; + public String schematic_hash; // SHA-256 hex (lowercase) + public String spawn_type; // "standard" | future variants + public Vec3i spawn_coords; + public String paste_origin; // "center" | "corner" + public Vec3i worldspawn_offset; + public List command_blocks; + public List rules_signs; + public YawpRegion yawp_region; + public Boolean self_destruct_on_success; + + public static class Vec3i { + public int x; + public int y; + public int z; + } + + public static class CommandBlockEntry { + public Vec3i position; + public String facing; // up | down | north | south | east | west + } + + public static class RulesSign { + public Vec3i position; + public List lines; // up to 4 + } + + public static class YawpRegion { + public String name; // region name (e.g. "spawn") + public Vec3i min; + public Vec3i max; + public List flags; // e.g. ["no-pvp", "no-mob-spawning"] + } + + /** Load + parse provision.json from the given path. Returns null if missing. */ + public static ProvisionConfig loadOrNull(Path path) { + if (!Files.exists(path)) return null; + try { + String json = Files.readString(path); + Gson gson = new GsonBuilder().setLenient().create(); + return gson.fromJson(json, ProvisionConfig.class); + } catch (Exception e) { + BitchBot.LOGGER.error("[BitchBot] Failed to parse provision.json: {}", e.getMessage()); + return null; + } + } + + public boolean shouldSelfDestruct() { + return self_destruct_on_success != null && self_destruct_on_success; + } +} diff --git a/services/bitch-bot/1.21.1/src/main/java/com/firefrostgaming/bitchbot/Provisioner.java b/services/bitch-bot/1.21.1/src/main/java/com/firefrostgaming/bitchbot/Provisioner.java new file mode 100644 index 0000000..313ed89 --- /dev/null +++ b/services/bitch-bot/1.21.1/src/main/java/com/firefrostgaming/bitchbot/Provisioner.java @@ -0,0 +1,145 @@ +package com.firefrostgaming.bitchbot; + +import net.minecraft.core.BlockPos; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.GameRules; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * Sequenced runner for everything Bitch Bot does on a successful first boot. + * + * Each step is independently try/catch'd so a single failure (bad URL, bad NBT, + * etc.) does NOT take down the server or skip the rest of the pipeline. Steps + * report their own success/failure to the log, and Provisioner tracks an + * overall success flag that gates self-destruct. + * + * Steps: + * 1. Locate provision.json + * 2. Capture original level.dat spawn coords (used for command-block /tp baking) + * 3. Download + verify schematic + * 4. Paste schematic at spawn_coords + * 5. Place 4 command blocks with /tp NBT + * 6. Place rules signs (if provided) + * 7. Set worldspawn = spawn_coords + worldspawn_offset + * 8. Set gamerule doFireTick false + * 9. Drop YAWP region config file (if provided) + * 10. Self-destruct (rename jar) if all of the above succeeded and the flag is set + */ +public class Provisioner { + + private final MinecraftServer server; + private final ServerLevel overworld; + private final Path serverRoot; + + private boolean schematicOk = false; + private boolean commandBlocksOk = false; + private boolean signsOk = true; // optional — start true + private boolean worldspawnOk = false; + private boolean gamerulesOk = false; + private boolean yawpOk = true; // optional — start true + + public Provisioner(MinecraftServer server) { + this.server = server; + this.overworld = server.overworld(); + this.serverRoot = Paths.get("").toAbsolutePath(); + } + + public void run() { + Path provisionPath = serverRoot.resolve("provision.json"); + ProvisionConfig cfg = ProvisionConfig.loadOrNull(provisionPath); + if (cfg == null) { + BitchBot.LOGGER.info("[BitchBot] No provision.json — dormant."); + return; + } + BitchBot.LOGGER.info("[BitchBot] provision.json detected (version={}). Beginning provisioning.", cfg.version); + + // Step 1: capture the original level.dat spawn so command blocks can /tp back to it + BlockPos originalSpawn = overworld.getSharedSpawnPos(); + BitchBot.LOGGER.info("[BitchBot] Original spawn: {} {} {}", originalSpawn.getX(), originalSpawn.getY(), originalSpawn.getZ()); + + // Step 2-4: schematic + try { + byte[] data = SchematicLoader.downloadAndVerify(cfg.schematic_url, cfg.schematic_hash); + if (data == null) throw new RuntimeException("schematic download/verification failed"); + BlockPos pasteAt = new BlockPos(cfg.spawn_coords.x, cfg.spawn_coords.y, cfg.spawn_coords.z); + int placed = SchematicLoader.pasteAt(overworld, data, pasteAt, "center".equalsIgnoreCase(cfg.paste_origin)); + BitchBot.LOGGER.info("[BitchBot] Schematic pasted: {} blocks", placed); + schematicOk = true; + } catch (Throwable t) { + BitchBot.LOGGER.error("[BitchBot] Schematic step failed: {}", t.getMessage()); + } + + // Step 5: command blocks (always attempted, even if schematic failed — staff can still use TP pads) + try { + CommandBlockPlacer.placeAll(overworld, cfg.command_blocks, originalSpawn); + commandBlocksOk = true; + } catch (Throwable t) { + BitchBot.LOGGER.error("[BitchBot] Command block step failed: {}", t.getMessage()); + } + + // Step 6: rules signs (optional) + if (cfg.rules_signs != null && !cfg.rules_signs.isEmpty()) { + try { + SignPlacer.placeAll(overworld, cfg.rules_signs); + } catch (Throwable t) { + BitchBot.LOGGER.error("[BitchBot] Sign step failed: {}", t.getMessage()); + signsOk = false; + } + } + + // Step 7: worldspawn + try { + int wx = cfg.spawn_coords.x + (cfg.worldspawn_offset != null ? cfg.worldspawn_offset.x : 0); + int wy = cfg.spawn_coords.y + (cfg.worldspawn_offset != null ? cfg.worldspawn_offset.y : 0); + int wz = cfg.spawn_coords.z + (cfg.worldspawn_offset != null ? cfg.worldspawn_offset.z : 0); + overworld.setDefaultSpawnPos(new BlockPos(wx, wy, wz), 0.0F); + BitchBot.LOGGER.info("[BitchBot] World spawn set to {} {} {}", wx, wy, wz); + worldspawnOk = true; + } catch (Throwable t) { + BitchBot.LOGGER.error("[BitchBot] World spawn step failed: {}", t.getMessage()); + } + + // Step 8: gamerule doFireTick false + try { + server.getGameRules().getRule(GameRules.RULE_DOFIRETICK).set(false, server); + BitchBot.LOGGER.info("[BitchBot] doFireTick → false"); + gamerulesOk = true; + } catch (Throwable t) { + BitchBot.LOGGER.error("[BitchBot] Gamerule step failed: {}", t.getMessage()); + } + + // Step 9: YAWP region file + if (cfg.yawp_region != null) { + try { + YawpConfigWriter.write(serverRoot, cfg.yawp_region, overworld.dimension().location().toString()); + } catch (Throwable t) { + BitchBot.LOGGER.error("[BitchBot] YAWP step failed: {}", t.getMessage()); + yawpOk = false; + } + } + + // Step 10: self-destruct + boolean overallOk = schematicOk && commandBlocksOk && signsOk && worldspawnOk && gamerulesOk && yawpOk; + BitchBot.LOGGER.info("[BitchBot] Provisioning result: schematic={} cmdblocks={} signs={} worldspawn={} gamerules={} yawp={}", + schematicOk, commandBlocksOk, signsOk, worldspawnOk, gamerulesOk, yawpOk); + + if (overallOk && cfg.shouldSelfDestruct()) { + try { + SelfDestruct.disableOurJar(); + } catch (Throwable t) { + BitchBot.LOGGER.error("[BitchBot] Self-destruct failed (manual cleanup needed): {}", t.getMessage()); + } + } else if (!overallOk) { + BitchBot.LOGGER.warn("[BitchBot] One or more steps failed — leaving jar enabled for retry on next boot."); + } + + // Move provision.json out of the way so it doesn't re-trigger if jar isn't disabled + try { + Files.move(provisionPath, serverRoot.resolve("provision.json.applied")); + } catch (Throwable ignored) {} + } +} diff --git a/services/bitch-bot/1.21.1/src/main/java/com/firefrostgaming/bitchbot/SchematicLoader.java b/services/bitch-bot/1.21.1/src/main/java/com/firefrostgaming/bitchbot/SchematicLoader.java new file mode 100644 index 0000000..f66336e --- /dev/null +++ b/services/bitch-bot/1.21.1/src/main/java/com/firefrostgaming/bitchbot/SchematicLoader.java @@ -0,0 +1,168 @@ +package com.firefrostgaming.bitchbot; + +import net.minecraft.commands.CommandBuildContext; +import net.minecraft.commands.arguments.blocks.BlockStateParser; +import net.minecraft.core.BlockPos; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.registries.Registries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.NbtAccounter; +import net.minecraft.nbt.NbtIo; +import net.minecraft.nbt.Tag; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.security.MessageDigest; +import java.time.Duration; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +/** + * Sponge Schematic Format v2 loader (the format that WorldEdit and FastAsyncWorldEdit + * write by default — file extension .schem). The format is a gzip-compressed NBT + * compound with the following keys we care about: + * + * Width, Height, Length (short) + * Offset (int[3]) — paste origin (corner) + * Palette (compound) — key=blockstate string, value=int id + * PaletteMax (int) + * BlockData (byte[]) — varint stream of palette indices + * + * Block index → coordinate mapping is x + (z * Width) + (y * Width * Length). + * + * For paste mode "center" we shift by -Width/2 and -Length/2 so the building + * lands centered on the requested spawn_coords. For "corner" we paste verbatim. + * + * NOTE: We do NOT honor BlockEntities or Entities tags from the schematic. + * Spawn buildings from Holly are intentionally vanilla blocks only. + */ +public class SchematicLoader { + + private static final HttpClient HTTP = HttpClient.newBuilder() + .connectTimeout(Duration.ofSeconds(10)) + .build(); + + /** Download to memory and verify SHA-256. Returns bytes on success, null on failure. */ + public static byte[] downloadAndVerify(String url, String expectedSha256Hex) { + try { + HttpRequest req = HttpRequest.newBuilder() + .uri(URI.create(url)) + .timeout(Duration.ofSeconds(60)) + .GET() + .build(); + HttpResponse resp = HTTP.send(req, HttpResponse.BodyHandlers.ofByteArray()); + if (resp.statusCode() != 200) { + BitchBot.LOGGER.error("[BitchBot] Schematic HTTP {} from {}", resp.statusCode(), url); + return null; + } + byte[] data = resp.body(); + + MessageDigest md = MessageDigest.getInstance("SHA-256"); + byte[] digest = md.digest(data); + StringBuilder hex = new StringBuilder(digest.length * 2); + for (byte b : digest) hex.append(String.format("%02x", b)); + String actual = hex.toString(); + + if (expectedSha256Hex == null || !expectedSha256Hex.equalsIgnoreCase(actual)) { + BitchBot.LOGGER.error("[BitchBot] Schematic hash mismatch — expected {} actual {}", expectedSha256Hex, actual); + return null; + } + BitchBot.LOGGER.info("[BitchBot] Schematic downloaded ({} bytes), SHA-256 verified.", data.length); + return data; + } catch (Exception e) { + BitchBot.LOGGER.error("[BitchBot] Schematic download failed: {}", e.getMessage()); + return null; + } + } + + /** + * Parse the schematic and place blocks into the given level. + * Returns the number of blocks placed. + */ + public static int pasteAt(ServerLevel level, byte[] schemBytes, BlockPos target, boolean centerOrigin) throws Exception { + CompoundTag root; + try (DataInputStream in = new DataInputStream(new java.util.zip.GZIPInputStream(new ByteArrayInputStream(schemBytes)))) { + root = NbtIo.read(in, NbtAccounter.unlimitedHeap()); + } + + // Some schematics wrap the data inside a "Schematic" sub-compound (v3). Normalize. + if (root.contains("Schematic")) root = root.getCompound("Schematic"); + + short width = root.getShort("Width"); + short height = root.getShort("Height"); + short length = root.getShort("Length"); + + CompoundTag paletteTag = root.getCompound("Palette"); + Map palette = new HashMap<>(); + HolderLookup.Provider lookup = level.registryAccess(); + HolderLookup.RegistryLookup blockLookup = lookup.lookupOrThrow(Registries.BLOCK); + + for (String key : paletteTag.getAllKeys()) { + int id = paletteTag.getInt(key); + BlockState state; + try { + BlockStateParser.BlockResult result = BlockStateParser.parseForBlock(blockLookup, key, false); + state = result.blockState(); + } catch (Exception e) { + BitchBot.LOGGER.warn("[BitchBot] Unknown blockstate '{}' in palette → AIR", key); + state = Blocks.AIR.defaultBlockState(); + } + palette.put(id, state); + } + + byte[] blockData = root.getByteArray("BlockData"); + int[] indices = decodeVarintArray(blockData, width * height * length); + + int xShift = centerOrigin ? -(width / 2) : 0; + int zShift = centerOrigin ? -(length / 2) : 0; + int yShift = 0; // y stays anchored to spawn_coords.y + + int placed = 0; + BlockPos.MutableBlockPos cursor = new BlockPos.MutableBlockPos(); + for (int y = 0; y < height; y++) { + for (int z = 0; z < length; z++) { + for (int x = 0; x < width; x++) { + int idx = x + (z * width) + (y * width * length); + BlockState state = palette.get(indices[idx]); + if (state == null || state.isAir()) continue; + cursor.set(target.getX() + x + xShift, target.getY() + y + yShift, target.getZ() + z + zShift); + level.setBlock(cursor, state, 2); // flag 2 = send to clients, no neighbor updates + placed++; + } + } + } + return placed; + } + + /** LEB128-style varint decode (Sponge schematic v2 format). */ + private static int[] decodeVarintArray(byte[] data, int expectedCount) { + int[] out = new int[expectedCount]; + int value, shift, b, i = 0, idx = 0; + while (i < data.length && idx < expectedCount) { + value = 0; + shift = 0; + while (true) { + if (i >= data.length) break; + b = data[i++] & 0xFF; + value |= (b & 0x7F) << shift; + if ((b & 0x80) == 0) break; + shift += 7; + if (shift > 35) throw new RuntimeException("varint too long"); + } + out[idx++] = value; + } + return out; + } +} diff --git a/services/bitch-bot/1.21.1/src/main/java/com/firefrostgaming/bitchbot/SelfDestruct.java b/services/bitch-bot/1.21.1/src/main/java/com/firefrostgaming/bitchbot/SelfDestruct.java new file mode 100644 index 0000000..6edd025 --- /dev/null +++ b/services/bitch-bot/1.21.1/src/main/java/com/firefrostgaming/bitchbot/SelfDestruct.java @@ -0,0 +1,48 @@ +package com.firefrostgaming.bitchbot; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.CodeSource; +import java.security.ProtectionDomain; + +/** + * Renames our own jar to .jar.disabled after a successful first-boot run. + * + * On NeoForge 1.21.1 the mod jar is loaded via a custom classloader, but the + * underlying file is still on disk in mods/. We locate it via this class's + * ProtectionDomain → CodeSource → Location. + * + * The actual rename happens in-place. NeoForge keeps the file open for the + * lifetime of the JVM, so on Windows the rename only sticks at next shutdown. + * On Linux (which is what every Firefrost server is) the rename succeeds + * immediately and the open file handle keeps working until restart. Either + * way, on the NEXT boot the modloader skips .jar.disabled files. + */ +public class SelfDestruct { + + public static void disableOurJar() throws Exception { + ProtectionDomain pd = SelfDestruct.class.getProtectionDomain(); + CodeSource cs = pd != null ? pd.getCodeSource() : null; + if (cs == null || cs.getLocation() == null) { + BitchBot.LOGGER.warn("[BitchBot] No CodeSource — cannot self-destruct."); + return; + } + + Path jarPath = Paths.get(cs.getLocation().toURI()); + if (!jarPath.toString().endsWith(".jar")) { + BitchBot.LOGGER.warn("[BitchBot] CodeSource is not a .jar ({}) — cannot self-destruct.", jarPath); + return; + } + + Path target = jarPath.resolveSibling(jarPath.getFileName().toString() + ".disabled"); + try { + Files.move(jarPath, target); + BitchBot.LOGGER.info("[BitchBot] 💥 Self-destruct successful. {} → {}", jarPath.getFileName(), target.getFileName()); + } catch (java.nio.file.FileSystemException fse) { + // Windows: file in use → schedule on JVM exit + jarPath.toFile().deleteOnExit(); + BitchBot.LOGGER.warn("[BitchBot] Jar locked by JVM — scheduled deletion on shutdown ({}). Linux will rename immediately.", fse.getMessage()); + } + } +} diff --git a/services/bitch-bot/1.21.1/src/main/java/com/firefrostgaming/bitchbot/SignPlacer.java b/services/bitch-bot/1.21.1/src/main/java/com/firefrostgaming/bitchbot/SignPlacer.java new file mode 100644 index 0000000..7b24e30 --- /dev/null +++ b/services/bitch-bot/1.21.1/src/main/java/com/firefrostgaming/bitchbot/SignPlacer.java @@ -0,0 +1,52 @@ +package com.firefrostgaming.bitchbot; + +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.SignBlockEntity; +import net.minecraft.world.level.block.entity.SignText; +import net.minecraft.world.level.block.state.BlockState; + +import java.util.List; + +/** + * Places oak signs at provided positions with up to 4 lines of text on the + * front face. Used by Holly's spawn-area rules signs. + * + * NeoForge 1.21.1 sign API: SignBlockEntity#updateText(UnaryOperator, boolean front). + */ +public class SignPlacer { + + public static void placeAll(ServerLevel level, List signs) { + int placed = 0; + for (ProvisionConfig.RulesSign sign : signs) { + try { + BlockPos pos = new BlockPos(sign.position.x, sign.position.y, sign.position.z); + BlockState state = Blocks.OAK_SIGN.defaultBlockState(); + level.setBlock(pos, state, 2); + + BlockEntity be = level.getBlockEntity(pos); + if (be instanceof SignBlockEntity sbe) { + Component[] lines = new Component[4]; + for (int i = 0; i < 4; i++) { + String line = (sign.lines != null && i < sign.lines.size()) ? sign.lines.get(i) : ""; + lines[i] = Component.literal(line); + } + SignText text = sbe.getFrontText() + .setMessage(0, lines[0]) + .setMessage(1, lines[1]) + .setMessage(2, lines[2]) + .setMessage(3, lines[3]); + sbe.setText(text, true); + sbe.setChanged(); + placed++; + } + } catch (Throwable t) { + BitchBot.LOGGER.error("[BitchBot] Failed to place sign: {}", t.getMessage()); + } + } + BitchBot.LOGGER.info("[BitchBot] Rules signs placed: {} / {}", placed, signs.size()); + } +} diff --git a/services/bitch-bot/1.21.1/src/main/java/com/firefrostgaming/bitchbot/YawpConfigWriter.java b/services/bitch-bot/1.21.1/src/main/java/com/firefrostgaming/bitchbot/YawpConfigWriter.java new file mode 100644 index 0000000..e26bda5 --- /dev/null +++ b/services/bitch-bot/1.21.1/src/main/java/com/firefrostgaming/bitchbot/YawpConfigWriter.java @@ -0,0 +1,55 @@ +package com.firefrostgaming.bitchbot; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; +import com.google.gson.JsonArray; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; + +/** + * Writes a YAWP (Yet Another World Protection) region config file directly + * to disk in world/serverconfig/. Per Gemini's Q1 architecture: NO commands, + * NO RCON — just a JSON file the YAWP mod picks up at next world load. + * + * The file format is intentionally simple and matches the schema YAWP expects + * for region definitions. If the on-disk format diverges, this is the ONE + * place to fix it (the rest of Bitch Bot won't change). + * + * Output: world/serverconfig/yawp/regions/{regionName}.json + */ +public class YawpConfigWriter { + + public static void write(Path serverRoot, ProvisionConfig.YawpRegion region, String dimensionId) throws Exception { + Path regionsDir = serverRoot.resolve("world").resolve("serverconfig").resolve("yawp").resolve("regions"); + Files.createDirectories(regionsDir); + + JsonObject root = new JsonObject(); + root.addProperty("name", region.name); + root.addProperty("dimension", dimensionId); + + JsonObject min = new JsonObject(); + min.addProperty("x", region.min.x); + min.addProperty("y", region.min.y); + min.addProperty("z", region.min.z); + root.add("min", min); + + JsonObject max = new JsonObject(); + max.addProperty("x", region.max.x); + max.addProperty("y", region.max.y); + max.addProperty("z", region.max.z); + root.add("max", max); + + JsonArray flags = new JsonArray(); + if (region.flags != null) for (String f : region.flags) flags.add(f); + root.add("flags", flags); + + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + Path outFile = regionsDir.resolve(region.name + ".json"); + Files.writeString(outFile, gson.toJson(root), + StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); + BitchBot.LOGGER.info("[BitchBot] YAWP region '{}' written → {}", region.name, outFile); + } +} diff --git a/services/bitch-bot/1.21.1/src/main/resources/META-INF/neoforge.mods.toml b/services/bitch-bot/1.21.1/src/main/resources/META-INF/neoforge.mods.toml new file mode 100644 index 0000000..30b2312 --- /dev/null +++ b/services/bitch-bot/1.21.1/src/main/resources/META-INF/neoforge.mods.toml @@ -0,0 +1,34 @@ +modLoader="javafml" +loaderVersion="[4,)" +license="All Rights Reserved" +issueTrackerURL="https://firefrostgaming.com/support" +showAsResourcePack=false + +[[mods]] +modId="bitchbot" +version="${file.jarVersion}" +displayName="Bitch Bot" +displayURL="https://firefrostgaming.com" +authors="Firefrost Gaming (named by Holly, The Catalyst)" +description=''' +First-boot server provisioning bot for Firefrost Gaming. +On the first ServerStartedEvent it consumes provision.json from the +server root, pastes the spawn schematic, places TP command blocks, +sets worldspawn, drops a YAWP region config, and self-destructs by +renaming itself to .jar.disabled. +Does nothing on subsequent boots. +''' + +[[dependencies.bitchbot]] +modId="neoforge" +type="required" +versionRange="[21.1,)" +ordering="NONE" +side="SERVER" + +[[dependencies.bitchbot]] +modId="minecraft" +type="required" +versionRange="[1.21.1,1.22)" +ordering="NONE" +side="SERVER" diff --git a/services/bitch-bot/CLAUDE.md b/services/bitch-bot/CLAUDE.md new file mode 100644 index 0000000..605116f --- /dev/null +++ b/services/bitch-bot/CLAUDE.md @@ -0,0 +1,75 @@ +# Bitch Bot — First-Boot Server Provisioner + +**Named by:** Holly (The Catalyst) +**Architecture:** Locked via 4-round Gemini consultation — see `firefrost-operations-manual/docs/consultations/gemini-modpack-installer-followup-2026-04-15.md` +**REQ:** `docs/code-bridge/archive/REQ-2026-04-15-bitch-bot.md` +**Status:** Source scaffold complete on Nitro. Compile on Dev Panel. + +## Project Structure +- `1.21.1/` — NeoForge (Java 21, Gradle 8.8, moddev 2.0.141) — primary target +- (1.20.1/Forge port can be added later if needed) + +## What Bitch Bot Does + +On `ServerStartedEvent`, if `provision.json` exists in the server root: + +1. Reads original spawn coords from `level.dat` via `level.getSharedSpawnPos()` +2. Downloads the schematic from `schematic_url`, verifies SHA-256 against `schematic_hash` +3. Pastes Sponge Schematic v2 (`.schem`) at `spawn_coords` (centered if `paste_origin == "center"`) +4. Places impulse command blocks at every position in `command_blocks[]` with `/tp @p [orig_x] [orig_y] [orig_z]` baked into NBT +5. Places oak signs at every entry in `rules_signs[]` with up to 4 lines each +6. Sets worldspawn to `spawn_coords + worldspawn_offset` +7. Sets gamerule `doFireTick false` +8. Writes a YAWP region config to `world/serverconfig/yawp/regions/{name}.json` +9. If `self_destruct_on_success: true` AND every step succeeded: renames `BitchBot-1.0.0-neoforge-1.21.1.jar` → `.jar.disabled` +10. Renames `provision.json` → `provision.json.applied` so it doesn't re-trigger + +## Failure Behavior +- Every step is independently try/catch'd. A failure logs and moves on. +- If ANY step fails, self-destruct does NOT fire — admin can fix the issue and reboot for retry. +- The server is NEVER crashed by Bitch Bot. The outermost handler in `BitchBot.onServerStarted` is a `Throwable` net. + +## Source Files + +``` +src/main/java/com/firefrostgaming/bitchbot/ +├── BitchBot.java # @Mod entry, ServerStartedEvent listener +├── Provisioner.java # Sequenced step runner + success tracking +├── ProvisionConfig.java # Gson POJO for provision.json +├── SchematicLoader.java # HTTP download + SHA-256 + Sponge v2 NBT parser + paste +├── CommandBlockPlacer.java # Impulse command blocks with TP NBT +├── SignPlacer.java # Oak signs with 4 lines of front text +├── YawpConfigWriter.java # Drops YAWP region JSON to world/serverconfig/yawp/regions/ +└── SelfDestruct.java # Locates own jar via ProtectionDomain, renames to .jar.disabled +``` + +## Building (Dev Panel only — no Java/Gradle on Nitro) + +```bash +cd /opt/mod-builds/firefrost-services/services/bitch-bot/1.21.1 +source use-java 21 +/opt/gradle-8.8/bin/gradle build --no-daemon +# Output: build/libs/BitchBot-1.0.0-neoforge-1.21.1.jar +``` + +## Provisioning a New Server + +1. Drop the jar into the server's `mods/` folder +2. Drop a populated `provision.json` (see `sample-provision.json`) into the server root (next to `server.properties`) +3. Boot the server +4. Watch the log — Bitch Bot prints every step to `[BitchBot]` lines +5. Once provisioning is reported successful, the jar renames itself to `.jar.disabled` and provision.json renames to `.applied` + +## Architectural Notes from Gemini + +- **Do NOT** write to .mca region files from Node.js — corruption-prone on 1.20+. The whole reason Bitch Bot exists as a real mod and not Node-side region manipulation. +- **Do NOT** rely on RCON or WorldEdit console — everything is in-process via the Forge API. +- **YAWP config** is written as a dropped file in `world/serverconfig/yawp/regions/{name}.json`. If the on-disk format diverges from what YAWP expects, fix `YawpConfigWriter.java` — it's the only file that touches the format. +- **BlockEntities and Entities tags in the .schem are ignored.** Spawn buildings should be vanilla blocks only. (If we later need item frames or armor stands, extend `SchematicLoader.pasteAt`.) + +## Risk Areas to Test on First Real Run + +1. **Schematic parsing** — only tested against the Sponge v2 spec, not against real WorldEdit `.schem` output. If parsing fails, palette key strings or varint stream encoding may need tweaks. +2. **Command block NBT** — `cbe.getCommandBlock().setCommand(...)` should persist, but verify the command actually fires when a player presses the button on top. +3. **Self-destruct on Linux** — every Firefrost server is Linux, so `Files.move` should work in-place. Windows fallback uses `deleteOnExit`. +4. **YAWP file format** — `YawpConfigWriter` writes a reasonable JSON shape but the actual YAWP mod schema may need adjustment. Watch for "region not loaded" warnings on second boot. diff --git a/services/bitch-bot/sample-provision.json b/services/bitch-bot/sample-provision.json new file mode 100644 index 0000000..5be9ca9 --- /dev/null +++ b/services/bitch-bot/sample-provision.json @@ -0,0 +1,29 @@ +{ + "version": "1.0", + "schematic_name": "firefrost-spawn-v1.schem", + "schematic_url": "https://downloads.firefrostgaming.com/Firefrost-Schematics/firefrost-spawn-v1.schem", + "schematic_hash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "spawn_type": "standard", + "spawn_coords": { "x": -5000, "y": 64, "z": -5000 }, + "paste_origin": "center", + "worldspawn_offset": { "x": 0, "y": 1, "z": 0 }, + "command_blocks": [ + { "position": { "x": -4998, "y": 65, "z": -4998 }, "facing": "up" }, + { "position": { "x": -5002, "y": 65, "z": -4998 }, "facing": "up" }, + { "position": { "x": -4998, "y": 65, "z": -5002 }, "facing": "up" }, + { "position": { "x": -5002, "y": 65, "z": -5002 }, "facing": "up" } + ], + "rules_signs": [ + { + "position": { "x": -4999, "y": 65, "z": -5005 }, + "lines": ["Welcome to", "Firefrost", "Read /rules", "Have fun!"] + } + ], + "yawp_region": { + "name": "spawn", + "min": { "x": -5050, "y": 0, "z": -5050 }, + "max": { "x": -4950, "y": 255, "z": -4950 }, + "flags": ["no-pvp", "no-mob-spawning", "break-blocks", "place-blocks"] + }, + "self_destruct_on_success": true +}