8 Commits

Author SHA1 Message Date
72ac29a620 Adds github actions.
Some checks failed
Java CI with Gradle / build (push) Has been cancelled
2026-10-22 18:34:15 -07:00
7135acbfed Updates docs. 2026-10-10 22:57:27 -07:00
4bc838cbe7 Reorganizes docs.
Some checks failed
Java CI with Gradle / build (push) Has been cancelled
2026-09-28 00:16:28 -07:00
8a37231777 Adds tests to workflow.
Some checks failed
Java CI with Gradle / build (push) Has been cancelled
2026-09-28 00:08:57 -07:00
17f394f9d3 Adds build status badge.
Some checks failed
Java CI with Gradle / build (push) Has been cancelled
2026-09-28 00:02:59 -07:00
7800db9243 Updates spotless and adds a license header. 2026-09-27 02:29:39 -07:00
d7cea52164 Updates spotless and the formatting settings. 2026-09-27 02:18:53 -07:00
4a600308a1 Fixes spotless errors.
Some checks failed
Java CI with Gradle / build (push) Has been cancelled
2026-09-27 02:05:43 -07:00
34 changed files with 1543 additions and 1084 deletions

View File

@@ -24,3 +24,7 @@ MODRINTH_LOADERS=paper
MODRINTH_VERSION_TYPE=
MODRINTH_DEPENDENCIES=
MODRINTH_FILE=
# Sync project body/README to Modrinth during publish (true/false)
MODRINTH_SYNC_BODY=true
MODRINTH_DESCRIPTION_FILE=docs/modrinth-description.md

View File

@@ -2,9 +2,10 @@ name: Java CI with Gradle
on:
push:
branches: [ "develop" ]
branches: [ "main", "develop" ]
tags: [ "v*" ]
pull_request:
branches: [ "develop" ]
branches: [ "main", "develop" ]
jobs:
build:
@@ -14,6 +15,8 @@ jobs:
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
- name: Set up JDK 25
uses: actions/setup-java@v6
@@ -25,7 +28,21 @@ jobs:
uses: gradle/actions/setup-gradle@v5
with:
gradle-version: '9.8.0'
cache-read-only: ${{ github.ref != 'refs/heads/develop' }}
cache-read-only: ${{ github.ref != 'refs/heads/develop' && github.ref != 'refs/heads/main' }}
- name: Run Unit Tests
run: ./gradlew test
- name: Upload Test Report
if: always()
uses: actions/upload-artifact@v7
with:
name: ScoreKeeper-test-report
path: |
build/reports/tests/test
build/test-results/test
if-no-files-found: ignore
retention-days: 14
- name: Build with Gradle Wrapper
run: ./tools/build-plugin.sh

168
.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,168 @@
name: Release
on:
workflow_dispatch:
inputs:
tag:
description: 'Git tag to release (e.g., v1.0.0)'
required: true
type: string
permissions:
contents: write
jobs:
prepare-release:
name: Validate Tag & Prepare Release Branch
runs-on: ubuntu-latest
outputs:
tag_commit: ${{ steps.validate.outputs.tag_commit }}
tag_name: ${{ steps.validate.outputs.tag_name }}
release_branch: ${{ steps.validate.outputs.release_branch }}
version_name: ${{ steps.validate.outputs.version_name }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
token: ${{ secrets.GITHUB_TOKEN }}
- name: Configure Git identity
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
- name: Validate Tag, Develop, Main, and Create Release Branch
id: validate
run: |
TAG="${{ github.event.inputs.tag }}"
echo "Target tag: $TAG"
# Fetch remote branches and tags
git fetch origin develop:develop main:main --tags
# 1. Verify tag exists
if ! git rev-parse -q --verify "refs/tags/$TAG" > /dev/null; then
echo "::error::Tag '$TAG' does not exist in the repository."
exit 1
fi
TAG_COMMIT=$(git rev-list -n 1 "$TAG")
echo "Tag '$TAG' points to commit: $TAG_COMMIT"
# 2. Verify tag commit is in develop branch
if ! git merge-base --is-ancestor "$TAG_COMMIT" origin/develop; then
echo "::error::Tag '$TAG' (commit $TAG_COMMIT) is not in the develop branch."
exit 1
fi
echo "Confirmed: Tag '$TAG' is in develop branch."
# 3. Verify tag commit is in main, or fast-forward merge it to main
if git merge-base --is-ancestor "$TAG_COMMIT" origin/main; then
echo "Confirmed: Tag '$TAG' is already in main branch."
else
echo "Tag '$TAG' is not in main. Attempting fast-forward only merge..."
git checkout main
if ! git merge --ff-only "$TAG_COMMIT"; then
echo "::error::Tag '$TAG' cannot be fast-forward merged into main."
exit 1
fi
git push origin main
echo "Successfully fast-forward merged '$TAG' into main."
fi
# 4. Create and push the release/v* branch from the tag commit
RELEASE_BRANCH="release/${TAG}"
echo "Creating release branch '$RELEASE_BRANCH' from commit $TAG_COMMIT..."
git checkout -B "$RELEASE_BRANCH" "$TAG_COMMIT"
git push -u origin "$RELEASE_BRANCH" --force
VERSION_NAME="${TAG#v}"
echo "tag_commit=$TAG_COMMIT" >> $GITHUB_OUTPUT
echo "tag_name=$TAG" >> $GITHUB_OUTPUT
echo "release_branch=$RELEASE_BRANCH" >> $GITHUB_OUTPUT
echo "version_name=$VERSION_NAME" >> $GITHUB_OUTPUT
scorekeeper-release:
name: Build, Test & Publish Release
needs: prepare-release
runs-on: ubuntu-latest
steps:
- name: Checkout release commit
uses: actions/checkout@v4
with:
ref: ${{ needs.prepare-release.outputs.tag_commit }}
fetch-depth: 0
- name: Ensure tag ref is checked out
run: |
git checkout -q "refs/tags/${{ needs.prepare-release.outputs.tag_name }}"
- name: Validate Modrinth Credentials
id: check_credentials
run: |
if [ -z "${{ secrets.MODRINTH_TOKEN }}" ]; then
echo "::warning::Modrinth release token was not provided. Release will not be published to Modrinth."
echo "::error::Missing MODRINTH_TOKEN secret. Please configure MODRINTH_TOKEN in repository secrets."
exit 1
fi
- name: Set up JDK 25
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '25'
- name: Setup Gradle 9.8.0
uses: gradle/actions/setup-gradle@v4
with:
gradle-version: '9.8.0'
- name: Make Gradle wrapper executable
run: chmod +x gradlew
- name: Run Unit Tests
run: ./gradlew test
- name: Upload Test Report
if: always()
uses: actions/upload-artifact@v4
with:
name: ScoreKeeper-test-report-${{ needs.prepare-release.outputs.tag_name }}
path: |
build/reports/tests/test
build/test-results/test
if-no-files-found: ignore
retention-days: 14
- name: Build ScoreKeeper Plugin Jar
run: ./tools/build-plugin.sh
- name: Upload Release Jar
if: success()
uses: actions/upload-artifact@v4
with:
name: ScoreKeeper-${{ needs.prepare-release.outputs.version_name }}
path: build/libs/*.jar
if-no-files-found: error
retention-days: 14
- name: Publish to Modrinth & Update Description
env:
MODRINTH_TOKEN: ${{ secrets.MODRINTH_TOKEN }}
MODRINTH_VERSION: ${{ needs.prepare-release.outputs.version_name }}
TAG: ${{ needs.prepare-release.outputs.tag_name }}
run: |
chmod +x ./tools/publish-modrinth.sh
./tools/publish-modrinth.sh
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.prepare-release.outputs.tag_name }}
name: ScoreKeeper ${{ needs.prepare-release.outputs.tag_name }}
files: build/libs/*.jar
generate_release_notes: true

90
AGENTS.md Normal file
View File

@@ -0,0 +1,90 @@
# Score Keeper: Shared Working Rules
These rules apply to agents and human contributors. Start with
[CONTRIBUTING.md](CONTRIBUTING.md) for setup, tasks, server safety, and release
procedures; [README.md](README.md) is the user-facing behavior reference.
## Quick orientation
- Java 25, Gradle 9.8.0 wrapper, Paper 26.2/26.3 only; no Bukkit/Spigot target.
- [ScoreKeeperPlugin.java](src/main/java/com/majinnaibu/minecraft/plugins/scorekeeper/ScoreKeeperPlugin.java)
owns lifecycle, buckets, UUID-keyed scores, YAML persistence, archives,
reporting, and scheduled high-score runs.
- [ScoreBucket.java](src/main/java/com/majinnaibu/minecraft/plugins/scorekeeper/ScoreBucket.java)
validates immutable definitions; [ScoreReporting.java](src/main/java/com/majinnaibu/minecraft/plugins/scorekeeper/ScoreReporting.java)
defines audiences. [commands/](src/main/java/com/majinnaibu/minecraft/plugins/scorekeeper/commands/)
contains eight executors wired in `onEnable` and
[plugin.yml](src/main/resources/plugin.yml).
- [CONTRIBUTING.md](CONTRIBUTING.md#project-overview-and-source-map) owns the source
map and architecture overview. Consult the [domain reference](docs/domain-score-tracking.md)
or [integration reference](docs/plugin-integration-and-event-wiring.md) only when
the task needs their detail. There are no built-in gameplay listeners or registered API service.
## Change discipline
- Inspect the source and current diff before editing. Preserve unrelated work;
make scoped, complete changes and document intentional behavior changes.
- Use **Score Keeper** in human-facing prose/display text. Keep `ScoreKeeper`
for repository URLs, plugin ID/data folder, Gradle/artifact names, and Java
symbols. Preserve scraper identifiers exactly as currently stored in
[project-description.json](docs/project-description.json).
Ask before renaming existing files or changing these integration identifiers.
- Follow existing Java patterns, Adventure components, UUID identity, and
plugin logging. Use Spotless rather than hand-formatting Java; preserve the
[AGPL header](config/license-header.txt). Do not add silent error recovery or
success messages for failed operations.
- Keep state and Paper API calls on the main thread. Do not introduce async
map access; marshal asynchronous results through Paper's synchronous scheduler.
- Wire command/API changes across executors, manifest, lifecycle, reporting,
persistence, and documentation as applicable. Preserve existing public overloads
and legacy YAML loading unless a migration is explicitly agreed.
- Preserve documented quirks until intentionally changed: unguarded score
mutations, signed integer arithmetic, lazy score entries, case-sensitive bucket
IDs, shutdown-only saves, and run snapshot restoration. Do not "fix" these as
incidental cleanup.
- Prefer existing helpers and dependencies. Do not introduce a service layer,
test harness, runtime dependency, or supported platform without a task need.
- Edit source, not generated `build/`, `bin/`, or `.gradle/` files. Never read,
expose, or commit `.env` credentials, server player data, or publishing tokens.
## Validation
- With JDK 25/JAVA_HOME configured, use `./gradlew spotlessCheck build` for Java
changes (`.\gradlew.bat` on Windows). For macOS/Linux bootstrapping, use
`./tools/build-plugin.sh spotlessCheck`. Run narrower relevant tasks when enough.
- `./gradlew spotlessApply` applies Java style; review the resulting diff and
avoid unrelated formatting churn.
- There are currently **no Java test sources/dependencies**; `test` is
`NO-SOURCE`, and no `integrationTest` task exists. Never claim a build proves
behavior or claim JUnit coverage. When tests are added, keep normal tests
server-free; real Paper integration tests should be explicit/opt-in.
- Use [human-tests.md](docs/human-tests.md) for affected runtime scenarios and
pre-release testing. Report checks actually run and any remaining unverified
behavior. For docs-only work, check relative links and metadata instead of building.
## Documentation and operational safety
- Keep [README.md](README.md), [Modrinth description](docs/modrinth-description.md),
[project-description.md](docs/project-description.md), and
[project-description.json](docs/project-description.json) aligned with source.
Validate the JSON as a slug-keyed object against
[projects.schema.json](docs/projects.schema.json). Keep manual scenarios
separate from automated coverage claims.
- When updating [project-description.json](docs/project-description.json),
preserve the existing top-level project key, `id`, `title`, `docId`, and all
image URLs (`image.url` and `headerImage.url`, when present). These are fixed
in the consuming project; routine metadata updates must not reset them.
Preserve a null or absent `headerImage` as well. Image paths such as
`/projects/score-keeper/logo.png` are relative to the consuming project's
root, not this repository: do not resolve them locally, rewrite them as
repository URLs, or replace them with generated/remote image URLs.
Change these protected fields only when the user explicitly requests it.
- New project plans belong in [docs/](docs/); use checkboxes for actionable
work only. [Modernize.md](docs/Modernize.md) supersedes the historical `.cursor`
plan/rules. Planning/documentation tasks should not opportunistically implement
the plan's code changes.
- Do not run server start/stop, deploy, restore, tagging, or publishing operations
without explicit authorization. Bash start/stop currently match all local
Java `paper-*.jar` processes; restore replaces archived top-level items.
PowerShell start/stop can force termination. Prefer a clean console `stop`
and inspect exact server paths/processes on isolated test machines.

View File

@@ -1,156 +1,295 @@
# Contributing to ScoreKeeper
**TODO:** Add info about the various gradle tasks.
# Contributing to Score Keeper
Thank you for your interest in contributing to the ScoreKeeper plugin! This guide will help you set up your development environment and follow best practices for working with the project.
**Start here to work on Score Keeper.** This guide covers the project structure,
setup, validation, and publishing. The display name is **Score Keeper**; the
repository, Gradle project, plugin ID, and jar basename remain `ScoreKeeper`.
# Getting Started
Pick a folder to hold your minecraft server and this project I'm going to use `$HOME/Projects`. My Minecraft server will be in `$HOME/Projects/MCServer` and this project will be in `$HOME/Projects/ScoreKeeper`.
## Your first contribution
Setup our project folder.
1. Read [the project overview](#project-overview-and-source-map) below.
Consult [README.md](README.md) if you need user-facing commands and behavior.
2. Read [AGENTS.md](AGENTS.md) once for the shared rules humans and agents follow.
This guide owns onboarding; that file owns change discipline and safety rules.
3. Follow [prerequisites and checkout](#prerequisites-and-checkout) to build.
4. Make a scoped change, then use [build and validation tasks](#build-format-and-validation-tasks).
Set up a local Paper server only if the affected behavior needs runtime testing.
5. Run the relevant [manual checks](docs/human-tests.md) and report what you verified.
You do **not** need to read every document before starting. Use these deeper
references when your task needs them:
- [Domain reference](docs/domain-score-tracking.md): score rules, YAML layout,
archives, and ranking.
- [Integration reference](docs/plugin-integration-and-event-wiring.md): detailed
command/lifecycle wiring and API usage, especially for companion-plugin authors.
- [Modernization plan](docs/Modernize.md) and [TODO.md](TODO.md): planned work,
not additional onboarding requirements.
The old `.cursor` plan and rules are historical context, not the current setup
or validation procedure. In particular, the Maven migration is already complete.
## Project overview and source map
Score Keeper is a command-driven Paper scoring engine: named buckets hold
UUID-keyed integer scores with custom units, initial values, and reporting.
It provides eight commands, score archives, high-score runs, and a public Java
API. Gameplay events do not award scores automatically; companion plugins can
provide that behavior.
| Source | Responsibility |
| --- | --- |
| [ScoreKeeperPlugin.java](src/main/java/com/majinnaibu/minecraft/plugins/scorekeeper/ScoreKeeperPlugin.java) | Entry point, state, public API, persistence, reporting, ranking, and run completion |
| [ScoreBucket.java](src/main/java/com/majinnaibu/minecraft/plugins/scorekeeper/ScoreBucket.java) | Immutable bucket definition and validation |
| [ScoreReporting.java](src/main/java/com/majinnaibu/minecraft/plugins/scorekeeper/ScoreReporting.java) | Reporting policy enum and parsing |
| [commands/](src/main/java/com/majinnaibu/minecraft/plugins/scorekeeper/commands/) | Eight executors: arguments, online targets, selected permission guards, and messages |
| [plugin.yml](src/main/resources/plugin.yml) | Plugin identity, entry point, API version, command declarations, and admin permission |
| [tools/](tools/) / [PowerShell helpers](tools/powershell/) | Developer/server/release tooling; platform differences are documented below |
| [.env.example](.env.example) | Bash helper configuration template, not plugin configuration |
### Architecture in one minute
```text
Paper command -> executor parses/checks permissions/resolves online target
-> ScoreKeeperPlugin selects bucket and updates UUID-keyed state
-> bucket reporting OR run reporting and target completion
onEnable -> wire commands -> initialize points -> load scores and archives
-> check existing runs -> schedule synchronous checks every 20 ticks
onDisable -> save scores.yml (version 3) and archives.yml
```
Most behavior lives in the entry-point class; there is no separate service layer,
custom scoring event API, ServicesManager registration, or standalone API artifact.
State uses nested `LinkedHashMap` collections and is not thread-safe. Keep state
and Paper API calls on the main thread.
There is no plugin `config.yml`: commands/API create buckets and policies,
which are stored in the plugin's data files. Do not edit generated `build/`,
`bin/`, or `.gradle/` outputs.
### Behavior to understand before changing it
- Scores, assignments, active runs, and archives save **on disable**, not every
mutation. Crashes can lose recent changes; the two YAML writes are not a transaction.
Loading supports legacy flat UUID scores but is not comprehensive schema validation.
- Score get/add/subtract/reset and archive-list are unguarded; players can modify
any online player's score. Archive creation, bucket administration, and run
management require `scorekeeper.admin`; self bucket selection is open.
- Named targets are online-only. `/score-get` reads the target's active bucket,
lazily creates an entry at its initial value, and shows only the numeric score.
An explicit bucket argument is pending SK-13; the API already has that overload.
- Amounts are signed Java integers; negatives are allowed and overflow wraps.
Bucket IDs are case-sensitive.
- `until-disabled` runs are saved/resumed across clean restarts, not ended by
disable. Reset runs restore the pre-run snapshot. Results are announced/logged,
not automatically archived; stop a run before archiving its bucket.
The [domain reference](docs/domain-score-tracking.md) explains these rules in
detail. Treat changes to them as deliberate behavior changes, not incidental cleanup.
## Prerequisites and checkout
The project targets **Paper 26.2 and 26.3 only**, compiles against
`io.papermc.paper:paper-api:26.2.build.129-stable`, and uses **Java 25** and the
**Gradle 9.8.0 wrapper**. Bukkit and Spigot servers are not supported.
Install Git and a JDK 25, and set `JAVA_HOME` to the JDK root (not its `bin`
directory). Confirm `java -version` and `javac -version` report 25. The Gradle
toolchain resolver can download the compile JDK, but Gradle itself still needs
a compatible JVM to start. Automatic local JDK detection is disabled in
[gradle.properties](gradle.properties); `JAVA_HOME` is the configured discovery source.
**Linux, macOS, and WSL**
```bash
PROJECTS_DIR="$HOME/Projects"
MINECRAFT_SERVER_PATH="$PROJECTS_DIR/MCServer"
# Use Paper 26.2 or 26.3 only. The project helper scripts resolve the configured Paper build.
MINECRAFT_SERVER_DOWNLOAD_URI=""
MINECRAFT_SERVER_JAR="paper-26.2-129.jar"
mkdir -p "$MINECRAFT_SERVER_PATH"
# Keep this shell open we will use these variables later.
```
**Windows**
```powershell
$projectsDir="$HOME\Projects"
$minecraftServerDir="$projectsDir\MCServer"
# Use Paper 26.2 or 26.3 only. The project helper scripts resolve the configured Paper build.
$minecraftServerDownloadUri=""
$minecraftServerJar="paper-26.2-129.jar"
New-Item -Type Directory $projectsDir
New-Item -Type Directory $minecraftServerDir
# Keep this shell open we will use these variables later.
```
## Install the JDK
**Linux / WSL**
```bash
apt install openjdk-25-jdk
```
**macOS**
```zsh
brew install --cask microsoft-openjdk@25
```
**Windows**
From Powershell
```powershell
winget install --id Microsoft.OpenJDK.25 --source winget
```
## Setup a PaperMC Server
**Linux, macOS, and WSL**
```bash
# You're probably still here, but if not go to the server dir.
cd "$MINECRAFT_SERVER_PATH"
curl -O "$MINECRAFT_SERVER_DOWNLOAD_URI"
java -jar "$MINECRAFT_SERVER_JAR"
nano eula.txt # Change eula=false to eula=true, then save and exit.
java -jar "$MINECRAFT_SERVER_JAR"
```
**Windows**
```powershell
# You're probably still here, but if not go to the server dir.
Set-Location $minecraftServerDir
Invoke-WebRequest -Uri $minecraftServerDownloadUri -OutFile (Split-Path $minecraftServerDownloadUri -Leaf)
java -jar $minecraftServerJar
notepad eula.txt
# Change eula=false to eula=true, then save and close the file.
java -jar $minecraftServerJar
```
If you get windows security popups about java with the little java dude allow them. It's because the server is listening on the network. Now you should have the server running and be dropped at a prompt like `> `. Type `stop` and hit enter to kill the server. You can also try CTRL + C.
## Get the Code
**Linux, macOS, and WSL**
```bash
cd "$PROJECTS_DIR"
git clone https://github.com/headhunter45/ScoreKeeper.git
code ScoreKeeper
cd ScoreKeeper
./gradlew spotlessCheck build
```
```powershell
Set-Location $projectsDir
git clone https://github.com/headhunter45/ScoreKeeper.git
# Then to open VSCode
code ScoreKeeper
```
On Windows, use `.\gradlew.bat spotlessCheck build` from PowerShell instead.
No globally installed Gradle or Maven is required.
## Building the Plugin
This should download the preferred version of our build tool (gradle) and use it to build the project. Among other intermediate files it will create `build/libs/ScoreKeeper-${Version}.jar`. This is the plugin jar that you copy to the minecraft server to install the plugin. From now on you will use the utility scripts in `tools\powershell\*.ps1` or `tools/bash/*.sh` to build and deploy the plugin to our test server.
On macOS/Linux, [tools/build-plugin.sh](tools/build-plugin.sh) is an alternative:
it downloads/caches Temurin 25 under `.gradle/user-home/jdks`, sets `JAVA_HOME`
for that invocation, and runs `build`. It accepts additional Gradle arguments:
**Linux, macOS, and WSL**
```bash
./gradlew build
./tools/build-plugin.sh spotlessCheck
```
**Windows**
```powershell
.\gradlew.bat build
```
That JDK selection is local to the script; it does not configure Java for your
terminal, IDE, Paper server, or later direct wrapper invocations.
## Using the Utility Scripts
Our scripts depend on two environment variables. You can set them each time you open a shell or set them once for every shell your user opens. The variables are `MINECRAFT_SERVER_PATH` and `MINECRAFT_SERVER_JAR`. They are used by the scripts to know where the server is so they can control it and deploy the plugin.
## Build, format, and validation tasks
**Linux, macOS, and WSL**
Run these from the repository root, using the Windows wrapper where applicable.
| Command | Purpose |
| --- | --- |
| `./gradlew build` | Compile, package, and run configured checks, including Spotless and `test`. |
| `./gradlew assemble` | Package without running the full check lifecycle. |
| `./gradlew spotlessCheck` | Verify Java formatting, imports, and license headers. |
| `./gradlew spotlessApply` | Apply the configured Java formatting; inspect the diff afterward. |
| `./gradlew test` | Run the default test task; currently there are no test sources/dependencies, so this is `NO-SOURCE`. |
| `./gradlew javadoc` | Generate Java API documentation. |
| `./gradlew properties --property version` | Inspect the Git-derived version. |
| `./gradlew publishToMavenLocal` | Publish the Java component to your local Maven repository for companion-plugin development. |
Build configuration lives in [build.gradle](build.gradle) (Groovy DSL), with
`java-library` and `maven-publish`. Paper is a `compileOnly` dependency supplied
by the server; no third-party runtime dependencies are bundled.
Spotless 8.10.3 uses google-java-format 1.36.1, import cleanup/order, and
[the license header](config/license-header.txt). The wrapper version/checksum
are pinned in [wrapper properties](gradle/wrapper/gradle-wrapper.properties);
the Foojay toolchain resolver is configured in [settings.gradle](settings.gradle).
The plugin artifact is `build/libs/ScoreKeeper-<version>.jar`. Versioning uses
`org.danilopianini.git-sensitive-semantic-versioning` version 7.0.24, a minimum
project version of `0.2.1`, and `v`-prefixed tags. Do not hardcode a release
version in the manifest:
[plugin.yml](src/main/resources/plugin.yml) expands `${version}` during resource processing.
There is **no behavioral automated coverage yet** and no `integrationTest` task.
The test infrastructure and coverage are pending SK-08 through SK-12 in
[TODO.md](TODO.md). A successful build is not proof that in-game behavior works.
For code changes, run the smallest relevant existing checks, then exercise the
affected scenarios in [human-tests.md](docs/human-tests.md). Documentation-only
changes need link/metadata checks, not a Paper server.
CI in [gradle.yml](.github/workflows/gradle.yml) runs for pushes and pull requests
to `main` and `develop`, and any `v*` tags. Manual releases are handled via
[release.yml](.github/workflows/release.yml). It invokes `test`, builds with the
Bash helper, and uploads jar artifacts (test reports only if present). It does
not start Paper or verify the two-version runtime compatibility claim.
## Local Paper server: macOS, Linux, or WSL
The Bash server/deploy/backup/restore/publish scripts read a root `.env`:
To set them for the current session run these commands. To set for every new session add these commands to your `.bashrc` or `.zshrc` file.
```bash
MINECRAFT_SERVER_PATH="$HOME/Projects/MCServer"
MINECRAFT_SERVER_JAR="paper-26.2-129.jar"
cp .env.example .env
```
**Windows**
Edit it using [the example](.env.example) as the configuration reference:
- `PAPER_VERSION`, `PAPER_BUILD`, and `MINECRAFT_SERVER_JAR` must agree.
The example pins `26.2`, build `129`, and `paper-26.2-129.jar`. To test 26.3,
select a build for that version or clear both build and jar values to resolve
the latest stable build.
- `MINECRAFT_SERVER_PATH` and `MINECRAFT_BACKUP_PATH` accept project-relative
paths, absolute paths, or `~/` paths. Defaults in the example are `./server`
and `./backups`.
- Values are literal `KEY=value` data, not shell code. Matching outer quotes
are removed, but `$HOME`, variable references, and command substitutions are
**not expanded**. Existing nonempty exported environment variables take precedence.
- Keep `.env` and publishing credentials out of Git.
For server startup, install `curl`, `jq`, `java` (Java 25), and `shasum`.
[start-server.sh](tools/start-server.sh) downloads missing Paper jars via the
Fill v3 API, verifies the supplied SHA-256 checksum, and runs Java in the
foreground with `--nogui`. It does not open a management GUI.
**Process safety:** the Bash start helper calls the stop helper, which matches
all Java processes running `paper-*.jar`, not just the configured server.
Backup/restore helpers also check for any such running server. Do not use these
helpers on a shared host without inspecting the processes and intended paths.
The safest stop is `stop` in your own server console; do not rely on forced
termination to save plugin data.
On an isolated development machine:
```bash
./tools/build-plugin.sh
./tools/deploy-plugin.sh
./tools/start-server.sh
```
Read and accept Minecraft's EULA before setting `eula=true` in the server's
`eula.txt`. The first launch exits until this is done; rerun the start helper
after accepting it. Use the matching Minecraft Java Edition client and connect
to `localhost` (or the server host's address). For WSL, run the client on Windows.
To redeploy, stop the server cleanly, build, copy the jar, and restart. Both
deploy helpers select the newest jar and **only warn** about stale sources;
they do not rebuild or reject stale artifacts. Remove older Score Keeper jars
from the test server's `plugins` directory so only the intended version loads.
### Backup and restore
[backup-server.sh](tools/backup-server.sh) archives plugins, config, world
directories containing `level.dat`, and top-level settings into a timestamped
`.tar.bz2`. Stop the server first; `--force` permits a potentially inconsistent
live backup. Generated Paper remapping caches and world session locks are excluded.
[restore-server.sh](tools/restore-server.sh) defaults to the newest backup,
asks for confirmation, and takes a pre-restore backup unless `--no-backup` is
specified. It **replaces** top-level items present in the archive. Inspect the
archive and resolved paths first, and use only a disposable/test server.
## Windows / PowerShell
The PowerShell helpers are not equivalent to the Bash server tooling: they do
not parse `.env`, download Paper, or provide backup/restore/publishing helpers.
Install JDK 25, obtain a Paper 26.2 or 26.3 server jar from
[Paper downloads](https://papermc.io/downloads/paper), and configure it manually.
Start it once, read/accept the EULA, and then launch it again.
Set real absolute paths in the current PowerShell session:
To set them for a single session run these commands.
```powershell
$env:MINECRAFT_SERVER_PATH = "$HOME\Projects\MCServer"
$env:MINECRAFT_SERVER_JAR = "paper-26.2-129.jar"
.\tools\powershell\Build-Plugin.ps1
.\tools\powershell\Deploy-Plugin.ps1
Set-Location $env:MINECRAFT_SERVER_PATH
java -jar $env:MINECRAFT_SERVER_JAR --nogui
```
If you want them available in all of your powershell sessions you can set them permanently like this.
```powershell
[Environment]::SetEnvironmentVariable("MINECRAFT_SERVER_PATH", "$HOME\Projects\MCServer", "User")
[Environment]::SetEnvironmentVariable("MINECRAFT_SERVER_JAR", "paper-26.2-129.jar", "User")
```
Use your actual downloaded jar filename. Build uses the wrapper and your
configured Java environment. The legacy PowerShell start/stop helpers attempt
to discover Java processes by command line and forcibly terminate matches.
Prefer starting Java explicitly and typing `stop` in its console for reliable
shutdown and persistence.
### Start-Server.ps1 and start-server.sh
Run `tools\powershell\Start-Server.ps1` or `tools/bash/start-server.sh` to start the server and open a GUI to manage it.
## Publishing
### Stop-Server.ps1 and stop-server.sh
Run `tools\powershell\Stop-Server.ps1` or `tools/bash/stop-server.sh` to stop the server. You can also safely close the GUI.
[tools/publish-local.sh](tools/publish-local.sh) bootstraps a local JDK like the
build helper, then runs `publishToMavenLocal`. Coordinates are
`com.majinnaibu.minecraft.plugins:ScoreKeeper:<version>`.
### Build-Plugin.ps1 and build-plugin.sh
Run `tools\powershell\Build-Plugin.ps1` or `tools/bash/build-plugin.sh` to build the plugin. This builds the plugin in `build/libs` as a jar named `ScoreKeeper-${VERSION}.jar`. To install the plugin manually you can copy this to `$env:MINECRAFT_SERVER_PATH\plugins` or `$MINECRAFT_SERVER_PATH/plugins` and restart the server.
[tools/publish-modrinth.sh](tools/publish-modrinth.sh) uploads a jar version to
Modrinth. Run it **only when intentionally publishing**, after validation:
### Deploy-Plugin.ps1 and deploy-plugin.sh
Run `tools\powershell\Deploy-Plugin.ps1` or `tools/bash/deploy-plugin.sh` to copy the plugin to the server plugins directory. This checks if the built plugin is up to date with the source code. If it is, then the script copies the plugin to the plugins directory to install it. To use the new plugin restart the server.
1. Decide whether this is a tagged stable release or a development build.
For a stable release, tag the approved commit with `v<version>` and rebuild
from that tag; inspect Gradle's resulting version and jar metadata.
2. Configure `.env` with `MODRINTH_TOKEN`, project ID, game versions, and loaders.
Defaults advertise Paper `26.2,26.3` and the `paper` loader; test both before
publishing that compatibility claim.
3. Build the intended artifact. Optionally set `MODRINTH_FILE` to its exact path;
otherwise the newest non-`-all.jar` jar is selected.
4. Run the publisher with JDK 25 available to the wrapper. It checks the jar's
manifest version against Gradle, derives changelog notes from commits unless
overridden, and infers `beta` for versions containing `-`, otherwise `release`.
`MODRINTH_VERSION_TYPE` can override this with `alpha`, `beta`, or `release`;
`MODRINTH_DEPENDENCIES`, if supplied, must be a JSON array.
# Setting up the Minecraft Client
- **macOS / Linux:**
- Download and install the official Minecraft Launcher from [minecraft.net](https://www.minecraft.net/en-us/download).
- Log in with your Mojang/Microsoft account and launch the Java Edition client.
- **Windows / WSL (Windows Subsystem for Linux):**
- For best performance, run the Minecraft client directly under Windows, not inside WSL.
- Download and install the official Minecraft Launcher for Windows from [minecraft.net](https://www.minecraft.net/en-us/download).
- Use WSL for server and plugin development, and connect to your test server from the Windows client.
The publisher needs `curl`, `jq`, and `unzip`; it creates a version, **not** an
update to the hosted project description. Keep [modrinth-description.md](docs/modrinth-description.md)
and [modrinth.json](docs/modrinth.json) current and update the hosted description
separately when releasing.
# Connecting the Client to Your Server
- Start your Paper server (see above).
- In the Minecraft client, add a new server with the address:
- `localhost` (if running both client and server on the same machine)
- Or use your machine's IP address if connecting across devices.
## Documentation and scraper metadata
# Notes
- Always use the provided scripts and environment variables for consistent server management.
Keep [README.md](README.md), [modrinth-description.md](docs/modrinth-description.md),
[project-description.md](docs/project-description.md), and
[project-description.json](docs/project-description.json) consistent with implemented
features. Do not present planned work or manual checks as completed coverage.
The scraper JSON must validate against [projects.schema.json](docs/projects.schema.json).
It is a **slug-keyed object**, currently `{ "score-keeper": { ... } }`, not a
single unwrapped project. Follow [AGENTS.md](AGENTS.md#documentation-and-operational-safety):
the existing key, `id`, `title`, `docId`, and image URLs are fixed in the
consuming project and must remain unchanged during routine metadata updates.
Image paths are relative to that project's root, not this repository.
Preserve the route, repository links, and filenames unless the consumer contract
is intentionally changed. Use "Score Keeper" in descriptive prose.

View File

@@ -1,49 +0,0 @@
**ScoreKeeper Plugin**
ScoreKeeper tracks player scores in configurable buckets. Use it for event points, competitions, or other server-side scoring systems, and integrate it with other plugins through the public API.
## Commands
Players can omit an optional player name to target themselves. Console and RCON must provide a player name for score get/add/subtract/reset commands.
* `/score-get [playerName]` - Displays the target player's score in their active bucket.
* `/score-add <amount>` - Adds an amount to your score in your active bucket.
* `/score-add <playerName> <amount>` - Adds an amount to the target player's score.
* `/score-subtract <amount>` - Subtracts an amount from your score in your active bucket.
* `/score-subtract <playerName> <amount>` - Subtracts an amount from the target player's score.
* `/score-reset [playerName]` - Resets the target player's active-bucket score to that bucket's initial value.
* `/score-archive` - Archives and resets your score in your active bucket.
* `/score-archive <playerName>` - Archives and resets the target player's score in their active bucket.
* `/score-archive all` - Archives and resets scores in every bucket.
* `/score-archive bucket <bucketId>` - Archives and resets every score in one bucket.
* `/score-archive-list` - Lists saved archive IDs, newest first.
* `/score-archive-list <archiveId>` - Displays the saved scores in one archive.
* `/score-bucket` - Displays your active bucket.
* `/score-bucket <bucketId>` - Switches your active bucket.
* `/score-bucket create <id> <singular> <plural> <initialValue> [reporting]` - Creates a bucket. Reporting can be `admin`, `global`, `player`, or `none` (default).
* `/score-bucket <playerName> <bucketId>` - Switches a player's active bucket.
* `/score-bucket all <bucketId>` - Changes the server's default bucket and clears individual bucket assignments.
* `/score-run start <bucketId> <topN> <reset:true|false> target <score>` - Starts a run that ends when a score reaches the target.
* `/score-run start <bucketId> <topN> <reset:true|false> duration <time>` - Starts a timed run. Use a positive number and lowercase `s`, `m`, `h`, `d`, or `w`, such as `4h`.
* `/score-run start <bucketId> <topN> <reset:true|false> until-disabled` - Starts a run with no automatic end.
* `/score-run stop <bucketId>` - Ends an active run.
## Permissions
The `scorekeeper.admin` permission (default: operators) is required for archive commands, bucket creation/administration, and high-score run management. Score get/add/subtract/reset and archive-list commands currently have no permission checks; add, subtract, and reset can target any online player.
## Features
* Create score buckets with custom singular/plural labels, initial values, and reporting policies.
* Reporting can notify operators/admins, everyone online, only the scored player, or nobody.
* Start target-score, timed, or until-disabled high-score runs with configurable top-N standings and optional score resets.
* Archive player, bucket, or all-bucket scores; archived scores reset to their bucket's initial value.
* Persist bucket definitions, assignments, scores, active runs, and archives in the plugin's data folder.
## API
Other plugins can create buckets with `createBucket(id, singular, plural, initialValue, reporting)`, use bucket-aware score methods, and start or stop high-score runs with `startTargetScoreRun`, `startTimedScoreRun`, `startUntilDisabledScoreRun`, and `stopHighScoreRun`.
## Compatibility
Built exclusively for Paper 26.2 and 26.3 with the Paper API and Adventure APIs. Bukkit and Spigot servers are not supported.

View File

@@ -1,23 +0,0 @@
{
"id": "scorekeeper",
"title": "ScoreKeeper",
"description": "A reusable Paper 26.2/26.3 scoring engine with named buckets, custom reporting, persistent archives, high-score runs, player commands, and a public API for companion plugins.",
"docId": "ScoreKeeper",
"image": {
"url": "https://image.pollinations.ai/prompt/pixel%20art%20Minecraft%20server%20scoreboard%20with%20a%20glowing%20diamond%20and%20number%20counters%2C%20clean%20square%20game%20plugin%20thumbnail%2C%20no%20text",
"alt": "Pixel art scoreboard with a diamond for the ScoreKeeper Minecraft plugin",
"prompt": "Pixel art Minecraft server scoreboard with a glowing diamond and number counters, clean square game plugin thumbnail, no text",
"width": 1024,
"height": 1024,
"backgroundClassName": "bg-surface"
},
"url": "/projects/scorekeeper",
"tags": [],
"source": {
"type": "",
"url": ""
},
"feedback": {
"url": ""
}
}

View File

@@ -1,12 +0,0 @@
# ScoreKeeper
ScoreKeeper is a reusable scoring engine for Paper 26.2 and 26.3. It gives events, competitions, and companion plugins a shared language for points: named buckets can have custom singular/plural labels, initial values, reporting policies, archives, and high-score runs.
The plugin is both a player-facing command system and an extension point. Administrators can start target-based, timed, or manually stopped score runs, while other plugins can create buckets, award points, archive results, and build richer game loops through the public API. Scores, assignments, runs, and archives persist across server restarts. Bukkit and Spigot servers are not supported.
## Engineering Notes
- Built with Gradle and Java 25 for modern Paper.
- Uses UUID-based player identity and YAML-backed persistence.
- Includes server-free JUnit coverage for domain rules, commands, reporting, archives, and lifecycle behavior.
- Designed as the scoring foundation used by companion plugins such as MobScores.

View File

@@ -1,280 +0,0 @@
# ScoreKeeper — Project Reference
> **For a developer joining the team cold.** Read top-to-bottom in ~8 minutes;
> you'll know where to look and what's real vs. planned on day one.
---
## 1. What is ScoreKeeper?
ScoreKeeper is a **Paper Minecraft plugin** (Java 25, Paper/Adventure APIs) that manages player
score tracking. It exposes five in-game/console commands (`/score-get`, `/score-add`,
`/score-subtract`, `/score-reset`, `/score-archive`) for manual score manipulation — no events,
no timers, no automation.
**State of the project:** live in-memory scores work today; the \"high-score table\" advertised
in the README name and `/score-archive` description is **not implemented**. Persistence, ranking,
and scoring formulas are all **future scope**. See §4 for the gap between *what exists* and
*what is planned*.
---
## 2. Tech Stack & Build
| Item | Value |
|------|-------|
| Language | Java 21 (Gradle auto-downloads toolchain) |
| Runtime target | Paper 26.2 and 26.3 |
| Build tool | Gradle 8.14.3 (`gradlew`) |
| Linting | Spotless (`googleJavaFormat()` + license header from `config/license-header.txt`) |
| Versioning | `org.danilopianini.git-sensitive-semantic-versioning`; minimum version `0.2.1`; reads `vX.Y.Z` tags |
| External deps | **None at runtime.** The Paper API is `compileOnly` only. |
| CI/release entry point | Run `./gradlew spotlessCheck build`, tag the release commit (for example, `git tag -a v0.2.2 -m "Release v0.2.2"`), then rebuild to produce the stable release artifact |
### Build quickly
```bash
./gradlew build # compiles, runs tests (none yet)
./gradlew spotlessApply # format to project style
./gradlew assemble # produces jar in build/libs/
```
Drop the resulting jar onto a Paper server's `plugins/` directory.
---
## 3. Architecture Overview
### Directory layout
```
├── src/main/java/com/majinnaibu/minecraft/plugins/scorekeeper/
│ ├── ScoreKeeperPlugin.java ← entry point, onEnable/onDisable, score CRUD core
│ └── commands/
│ ├── ScoreGetCommand.java → /score-get [player]
│ ├── ScoreAddCommand.java → /score-add [player] <amount>
│ ├── ScoreSubtractCommand.java → /score-subtract [player] <amount>
│ ├── ScoreResetCommand.java → /score-reset [player]
│ └── ScoreArchiveCommand.java → /score-archive [player] (stub)
├── src/main/resources/
│ └── plugin.yml ← command manifest + main-class declare
├── tools/bash/ & tools/powershell/ ← dev helper scripts
├── config/license-header.txt ← Spotless license header
├── build.gradle ← Gradle build config (above)
├── gradle.properties ← version, group coordinates
├── CONTRIBUTING.md ← dev env setup
└── README.md ← user-facing command reference + notes
```
### Data flow (text diagram)
```
ADMIN / CONSOLE / RCON ──▶ types a /score-* command
│
▼
┌──────────────────────┐
│ 5× Score*Command.java│ executors parse args,
│ resolves target │ resolvePlayerExact(name) (online-only)
└──────────┬───────────┘
│ calls
▼
┌──────────────────────────────┐
│ ScoreKeeperPlugin │
│ │
│ addScore / subtractScore │ read-modify-write
│ resetScore / setScore │
│ getScore (read) │
│ archiveScore (STUB — no-op) │
└──────────┬───────────────────┘
│
▼
HashMap<UUID, Integer> ← in RAM only
_playerScores ← ScoreKeeperPlugin:38
```
**Key architectural facts:**
- **Single class owns everything.** `ScoreKeeperPlugin` holds the scores map, score CRUD
methods, logging helpers (logWarning/logInfo/logError), and the Adventure component builder
for chat color. There is no service layer or boundary separation.
- **No event listeners.** Zero `@EventHandler`/`Listener` registrations across the codebase.
Game events (join, death, kill) do not affect scores. Only manual commands change state.
- **No scheduler or tick logic.** No periodic tasks, no countdowns, no automated scoring.
- **No permission nodes.** Every command is available to every sender (player, console, RCON).
### File: ScoreKeeperPlugin.java (`ScoreKeeperPlugin`)
- `main` class in `plugin.yml` (Paper plugin entry point)
- `HashMap<UUID, Integer> _playerScores` at line 38 — the sole score store
- `onEnable()` (line 52): wires five command executors, logs \"load not implemented\" warning
- `onDisable()` (line 46): logs \"save not implemented\" warning — scores lost on shutdown
- Score CRUD methods: `addScore`, `subtractScore`, `resetScore`, `setScore`, `getScore`,
`archiveScore` (lines 67–91, 76–86, 72–74)
- Private helpers: `getPlayerScore(Player)` (get-or-create at 0), `setPlayerScore(Player,int)`
---
## 4. Domain Model & Scoring Logic
### 4.1 What exists today (REAL — in code)
| Aspect | Detail | Source |
|--------|--------|--------|
| Score model | Single `int` per player, keyed by UUID | `ScoreKeeperPlugin:38` |
| Storage container | `HashMap<UUID, Integer>` on plugin instance | same file |
| Default value | `0` — lazy-created on first map access | `getPlayerScore:100-106` |
| Live only | **No persistence.** Scores erased on server restart | `onEnable:59`, `onDisable:47` |
| Scoring direction | Any integer (negatives allowed, no floor) | add/subtract are raw `+`/`-` |
| Recording method | Manual commands only — `/score-add`, `/score-subtract` | command executors |
| Auto-scoring | **None** — no events, no timers | proven by grep across src/ |
| Permissions | **None declared.** All commands open to all senders | `plugin.yml`, no permission guard in code |
### 4.2 Open Score Lifecycle (what exists + what is planned)
```
Stage 1. First access — getPlayerScore() auto-creates key at 0 [REAL]
2. Admin runs /score-add player N or /score-subtract [REAL]
3. Player accumulates points over the session [REAL]
4. Read via /score-get (read-only, lazily registers) [REAL]
5. Server restart — scores LOST on shutdown [REAL]
6. Intended: /score-archive freezes score → table [GAP ✓ not built]
7. Intended: high-score table display command [GAP ✓ not built]
```
### 4.3 The "high-score table" — status
| Feature | Status | Details |
|---------|--------|---------|
| `/score-archive` | **Stub** | Command prints \"archive command unimplemented\"; `archiveScore()` method only logs, never writes a table or resets the player's score |
| Persistence (save) | **Not built** | `onDisable()` is a TODO stub — map discarded at shutdown |
| Persistence (load) | **Not built** | `onEnable()` is a TODO stub — map always starts empty `{}` |
| Sorting / ranking | **Not coded** | No sort, no tie-breaking, no entry cap, no decay logic exists |
| Scoring formulas | **Not coded** | Scores are plain integer accumulators (`Σ(adds) − Σ(subtracts)`) |
**Design decisions to be made (none answered by code today):**
- Storage format for the table (YAML per Bukkit convention; JSON? SQLite?)
- What an entry looks like (name + score + timestamp? name is not stored with score today)
- Sort order and tie-breaking strategy
- Max entries / leaderboard cap
- Whether `/score-archive` also resets the live score (README says it does)
---
## 5. Plugin Integration & Reference Table
### 5.1 Command → Handler → Effect on score data
| Trigger | Usage | Handler | Effect |
|---------|-------|---------|--------|
| `/score-get [player]` | Self or other | `ScoreGetCommand.java:38-84`, delegated to `getScore → getPlayerScore` | **Read-only.** Returns integer. Lazily creates entry at `0` if unseen. |
| `/score-add [player] <N>` | Self (omit name) or target others | `ScoreAddCommand.java` | `score += N`. Amount must parse as int. No direction validation (negative N still adds). |
| `/score-subtract [player] <N>` | Same | `ScoreSubtractCommand.java` | `score -= N`. No minimum clamping; negatives freely produced. |
| `/score-reset [player]` | Same | `ScoreResetCommand.java` | `score = 0`. Key created at `0` if absent. |
| `/score-archive [player]` | Same | `ScoreArchiveCommand.java` | **No-op.** Prints \"archive command unimplemented\". Does NOT call the `archiveScore()` method. |
### 5.2 Shared behavior details
Every executor follows this pattern:
1. Parse arguments — if `split.length == 1` and sender is a player, target = self (RCON/console
requires an explicit `<playerName>` or prints usage).
2. Resolve target player via `server.getPlayerExact(name)` — **exact, case-sensitive, online-only.**
3. Call the corresponding `ScoreKeeperPlugin` method.
4. Echo color-coded result; return `true`.
### 5.3 Inter-plugin / public API surface
`ScoreKeeperPlugin` exposes these public methods that other plugins *could* call if they hold a reference
(but there is **no formal service registration**):
| Method | Visibility | Called by commands? | Notes |
|--------|------------|---------------------|-------|
| `addScore(Player, int)` | `public` | Yes (`/score-add`) | Read-modify-write on `_playerScores` |
| `subtractScore(Player, int)` | `public` | Yes (`/score-subtract`) | Same pattern |
| `getScore(Player)` | `public` | Yes (`/score-get`) | Wrapper around `getPlayerScore` |
| `setScore(Player, int)` | `public` | **No** | Internal write path only; not hooked to any command |
| `resetScore(Player)` | `public` | Yes (`/score-reset`) | Sets to `0` |
| `archiveScore(Player)` | `public` | **No** | Only logs a warning; never called by the archive command |
### 5.4 Concurrency note
The map is a plain `HashMap`. Safe because Paper dispatches commands on the server's single main
thread — but it is **not safe for off-thread use**. Any future event-driven scoring that runs
asynchronously could corrupt state via non-atomic read-modify-write.
---
## 6. Configuration Reference
| File | Format | Purpose |
|------|--------|---------|
| `plugin.yml` | YAML (Bukkit manifest) | Declares main class, api-version, five commands + descriptions/usage strings |
| `build.gradle` | Gradle Kotlin (Groovy DSL) | Dependencies, task config, release/spotless settings |
| `gradle.properties` | Properties | Project version and group coordinates (for Maven publishing) |
| **No `config.yml`** | — | ScoreKeeper has **no player-editable configuration**. |
| **No `permissions:` block** | — | No permission nodes declared; all commands are open. Plans say \"permissions coming after archive works.\" |
---
## 7. Running & Testing Locally
### Build
```bash
./gradlew assemble # produces ScoreKeeper.jar in build/libs/
```
### Run locally (Paper server)
1. Download Paper 26.2 or 26.3 from `https://papermc.io`
2. Copy the built jar into `plugins/`
3. Start the server, verify onEnable logs:
```
[ScoreKeeper] ScoreKeeper version X.Y.Z is enabled.
[ScoreKeeper] Unable to load scores from file. This feature is not implemented yet.
```
### Commands (in-game or via RCON/console)
| Test scenario | Command | Expected output |
|--------------|---------|-----------------|
| Check own score | `/score-get` | \"Your score is 0\" (creates entry at 0) |
| Add points to self | `/score-add 10` | \"You gained 10 points! Now have 10.\" |
| Subtract from self | `/score-subtract 5` | \"You lost 5 points! Now have 5.\" |
| Check another player | `/score-get PlayerName` | \"PlayerName's score is N.\" (must be online) |
| Reset own score | `/score-reset` | \"Your score has been reset to 0.\" |
| Archive (stub) | `/score-archive` | \"archive command unimplemented\" |
### Tests
- **No unit/integration tests exist yet.** `./gradlew test` runs an empty suite. Consider
adding tests for `ScoreKeeperPlugin`'s private `Player` score state mocking in a future task.
---
## 8. Where to Look First
| I want to understand… | Go to |
|----------------------|-------|
| The entire live data model | `ScoreKeeperPlugin:38` — one `HashMap<UUID, Integer>` field |
| How scores change (write path) | `addScore(/:67-70)`, `subtractScore(/:88-91)`, `setPlayerScore(/:108-110)` |
| How a player is looked up | `getPlayerExact(name)` online only — see any `*Command.java` line ~50 |
| First-time-player behavior | `getPlayerScore(/:100-106)` — auto-inserts `0` on first access |
| High-score / archive table | **Does not exist.** See `archiveScore(/:72-74)` stub; design decisions in §4.3 |
| Persistence (save/load) | `onDisable(/:47)`, `onEnable(/:59)` — both TODO, nothing writes to disk |
| What's declared/intended but not wired | `plugin.yml:18-20` (`/score-archive`), `README.md:11` and README notes |
| Command implementations | `commands/Score*Command.java` (all 5 handlers) |
| Build/runtime config | `build.gradle`, `plugin.yml`, `gradle.properties` |
| Dev env / CONTRIBUTING | `CONTRIBUTING.md` |
---
## Appendix: Risk Summary
| # | Issue | Impact | Section |
|---|-------|--------|---------|
| 1 | **Data loss on restart** — no save/load implemented | Every server boot wipes all scores (§4.1) | §4.1 |
| 2 | **No permissions** — any player can self-add points | Integrity of scoring is unenforceable today (§5.2) | §5.2 |
| 3 | **Race condition on add/subtract** — non-atomic read-modify-write on plain `HashMap` | Corrupt state if future event-driven scoring runs async (§5.4) | §5.4 |
| 4 | **No `int` overflow safety** — Java wrapping semantics apply | Undetectable score corruption near ±2.1 billion | §4.1 |
| 5 | **Name lookups online-only & case-sensitive** | Can't target offline players; \"Alice\" ≠ \"alice\" (§5.2) | §5.2 |

113
README.md
View File

@@ -1,12 +1,41 @@
# ScoreKeeper Plugin
# Score Keeper
ScoreKeeper supports Paper 26.2 and 26.3 only. Bukkit and Spigot servers are not supported.
[![Java CI with Gradle](https://github.com/headhunter45/ScoreKeeper/actions/workflows/gradle.yml/badge.svg)](https://github.com/headhunter45/ScoreKeeper/actions/workflows/gradle.yml)
Score Keeper tracks player scores in named buckets for server events, competitions,
and companion plugins. Buckets support custom units, initial values, reporting,
archives, and target-based or timed high-score runs. Gameplay does not award points
automatically: use commands or another plugin calling the public API.
Supports **Paper 26.2 and 26.3 only**, with **Java 25**. Bukkit and Spigot servers
are not supported. The display name is Score Keeper; the repository and installed
plugin identifier remain `ScoreKeeper`.
## Installation
1. Obtain a plugin jar from [Modrinth](https://modrinth.com/plugin/scorekeeper)
or build it using [CONTRIBUTING.md](CONTRIBUTING.md).
2. Stop your Paper server cleanly. Back up existing plugin data.
3. Put `ScoreKeeper-<version>.jar` in the server's `plugins` directory, removing
older Score Keeper jars so only one version loads.
4. Start the server and verify the plugin enables without errors.
Scores, bucket definitions, reporting, player assignments, and active runs load
from `plugins/ScoreKeeper/scores.yml`; archives load from
`plugins/ScoreKeeper/archives.yml`. Both are saved **on plugin disable/clean
shutdown**, not after every command. Crashes or forced termination can lose
changes since the last successful save. Do not edit these files while running.
## Running
### Commands
For commands with an optional player name, players can omit it to target themselves. Console and RCON must provide a player name for score get/add/subtract/reset commands.
For commands with an optional player name, players can omit it to target themselves.
Named targets must be online. Console and RCON must provide a player name for
score get/add/subtract/reset; archive also supports `all` and `bucket` scopes.
Bucket IDs are case-sensitive and allow letters, numbers, `_`, and `-`.
Command-created singular/plural labels each occupy one argument.
Add/subtract accept signed 32-bit integers, including zero and negative amounts.
* `/score-get [playerName]` - Displays the target player's score in their active bucket.
* `/score-add <amount>` - Adds an amount to your score in your active bucket.
@@ -25,22 +54,82 @@ For commands with an optional player name, players can omit it to target themsel
* `/score-bucket create <id> <singular> <plural> <initialValue> [reporting]` - Creates a bucket. Reporting is `admin`, `global`, `player`, or `none` and defaults to `none`.
* `/score-bucket <playerName> <bucketId>` - Switches a player's active bucket.
* `/score-bucket all <bucketId>` - Changes the server's default bucket and clears individual bucket assignments.
* `/score-run start <bucketId> <topN> <reset:true|false> target <score>` - Starts a run that ends when a score reaches the target.
* `/score-run start <bucketId> <topN> <reset:true|false> duration <time>` - Starts a timed run. Use a positive number followed by lowercase `s`, `m`, `h`, `d`, or `w` (for example, `4h`).
* `/score-run start <bucketId> <topN> <reset:true|false> until-disabled` - Starts a run with no automatic end.
* `/score-run start <bucketId> <topN> <true|false> target <score>` - Starts a run that ends when a score reaches the target.
* `/score-run start <bucketId> <topN> <true|false> duration <time>` - Starts a timed run. Use a positive number followed by lowercase `s`, `m`, `h`, `d`, or `w` (for example, `4h`).
* `/score-run start <bucketId> <topN> <true|false> until-disabled` - Starts a run with no automatic end, including across clean restarts.
* `/score-run stop <bucketId>` - Ends an active run.
The `scorekeeper.admin` permission (default: operators) is required for archive commands, bucket creation/administration, and high-score run management. Score get/add/subtract/reset and archive-list commands currently have no permission checks; add, subtract, and reset can target any online player.
The reset argument for a run is the literal `true` or `false`, not `reset:true`.
Top N must be at least 1. For example:
```text
/score-bucket create event point points 0 player
/score-bucket event
/score-run start event 3 true duration 4h
/score-add 10
/score-get
/score-run stop event
/score-archive bucket event
```
### Permissions
The `scorekeeper.admin` permission (default: operators) is required for
`score-archive`, bucket creation, switching another player/all players, and run
management. Viewing/selecting your own bucket requires no admin permission.
Score get/add/subtract/reset and archive-list currently have no permission
checks; add, subtract, and reset can target **any online player**. Restrict command
access externally if that is inappropriate for your server's scoring rules.
### Reporting, runs, and archives
When a player's active bucket changes, they are told the bucket name and their current score with its singular or plural unit.
Bucket reporting defaults to `none`; `admin` notifies operators and score admins, `global` notifies all online players, and `player` notifies only the scored player. Other plugins can create buckets with `createBucket(id, singular, plural, initialValue, reporting)` and use the bucket-aware score methods. Existing score methods operate on the player's active bucket. Bucket definitions, reporting policies, assignments, and scores are saved in `plugins/ScoreKeeper/scores.yml`; archives are saved separately in `plugins/ScoreKeeper/archives.yml`.
Bucket reporting defaults to `none`; `admin` notifies operators and score admins
and logs the change, `global` notifies all online players, and `player` notifies
only the scored player. Only changed values produce reports. With `none`, a
successful add/subtract/reset can be silent; use `/score-get` to inspect the
numeric score. Scores can go negative and arithmetic overflow is not checked.
Other plugins can start runs with `startTargetScoreRun`, `startTimedScoreRun`, or `startUntilDisabledScoreRun`, and end one with `stopHighScoreRun`. During a run, players receive their own score changes, while changes by current top-`n` players are reported globally. Finished runs publish a deterministic score-ordered table and each online player's place; reset runs restore the pre-run bucket scores.
Each bucket can have one active run. During it, players receive their own score
changes regardless of the bucket reporting policy; changes by players in the
top N after the update are reported globally. Rankings include all recorded
bucket entries, even offline players. Ties sort by case-insensitive name, then UUID,
and have consecutive places. Finished runs announce/log the top-N table and each
online player's place. Reset runs restore the pre-run bucket scores; non-reset
runs leave earned scores intact. Timed runs use wall-clock time, including time
offline. An existing target can end a non-reset run immediately.
Run results are not automatically archived. Stop the run before archiving its
bucket. Archives snapshot the selected recorded scores and reset them to the
bucket initial value; they become durable at clean shutdown.
## Plugin API
Other plugins can create buckets with
`createBucket(id, singular, plural, initialValue, ScoreReporting)` and use
bucket-aware score methods. Existing no-bucket methods use the player's active
bucket. Runs use `startTargetScoreRun`, `startTimedScoreRun`,
`startUntilDisabledScoreRun`, and `stopHighScoreRun`.
Declare a dependency on plugin ID `ScoreKeeper`, obtain the enabled
`ScoreKeeperPlugin` instance, and call it on Paper's main thread. There is no
separate service registration or automatic gameplay integration. See
[plugin integration and event wiring](docs/plugin-integration-and-event-wiring.md)
for setup, overloads, and failure handling.
## Development
See [CONTRIBUTING.md](CONTRIBUTING.md) for development environment setup instructions.
Start with [CONTRIBUTING.md](CONTRIBUTING.md) and the shared rules in
[AGENTS.md](AGENTS.md). The project uses Gradle 9.8.0, Java 25 toolchains, and
Spotless. The compile toolchain can be downloaded automatically, but the wrapper
still needs a compatible JVM to start.
Tooling note:
* Gradle is configured with Java Toolchains and will automatically download an appropriate JDK when needed during builds.
There are currently no automated Java tests; a passing build does not exercise
plugin behavior. Use [human-tests.md](docs/human-tests.md) before releases.
See [the contributor guide's project overview](CONTRIBUTING.md#project-overview-and-source-map) for architecture and
[the modernization plan](docs/Modernize.md) for remaining work.
## License
Score Keeper is licensed under the [GNU AGPL v3 or later](LICENSE).

35
TODO.md
View File

@@ -1,17 +1,22 @@
## Tasks
# Score Keeper Tasks
**Done** means implemented in source, not validated by automated behavioral tests.
**Ready** means not yet implemented. See [docs/Modernize.md](docs/Modernize.md)
for the broader roadmap and [docs/human-tests.md](docs/human-tests.md) for manual
pre-release validation.
| ID | Status | Title |
|:-----:|:--------:|:------|
| SK-01 | Done | Save scores between server launches. |
| SK-02 | Done | Allow tracking scores by bucket. An admin or other plugin should be able to create types of scores with named other than points. { id: "Bread", singular: "loaf", plural: "loaves", initialValue: 0 } Each player's score will be tracked in a bucket by id. Players may be all switched to a bucket or individually switched. |\
| SK-03 | Done | Add optional score reporting to buckets with these four values. { id: "Bread", singular: "loaf", plural: "loaves", initialValue: 0, reporting:"admin|global|player|none" } admin means ops/admin only, global means everyone on the server, player means only tell the player, and none means don't report changes.
| SK-04 | Done | Tell a player when their bucket changes. Something like "You are now tracking ${id}. You have ${score} ${plural or singular depending in score}." |
| SK-05 | Done | Enable high score runs for a bucket. Admins or pugins should be able to start a run on a certain kind of score. The top n (configurable) players will have their scores reported globally for this bucket and the individual player will have their score reported to them when it changes. Scores will be optionally reset to their initialValue with the old score for this bucket saved. High score runs will have a lifetime of a target high score, a time like 4 hours or 1 week, or until-disabled. When the high score run is finished all players will be messaged a table with the top n places and their scores along with the individual user's place and score. The scores will be reset to their previous values if they were reset to their initialValue at the beginning otherwise they will be left alone. |
| SK-06 | Done | Score archiving. Scores either all or within a given bucket should be able to be archived and reset to their initial value. The archived scores should be able to be listed via a command. |
| SK-07 | Done | Replace 'net.researchgate.release' with org.danilopianini.git-sensitive-semantic-versioning' for our versioning in our build.gradle file. Turn org.gradle.configuration-cache back on after this. Our current version is 0.2.1-SNAPSHOT. Use that as our default or 0.2.1 and tag the commit to update to 0.2.2. |
| SK-08 | Ready | Add JUnit 5 test infrastructure and keep the default Gradle `test` task server-free. Use an in-memory Paper test harness such as MockBukkit for plugin lifecycle and Bukkit/Paper behavior; use Mockito only for narrow API boundaries where a harness is unnecessary. |
| SK-09 | Ready | Add fast unit tests for score and bucket rules: bucket validation and duplicate IDs, initial values, UUID-isolated scores, default and per-player bucket selection, and add/subtract/reset behavior. Keep domain rules independent of a running Minecraft server. |
| SK-10 | Ready | Test YAML persistence and archives using temporary plugin data directories: score/bucket/assignment round trips, active-run state, archive contents and resets, legacy score loading, and malformed or unknown stored entries. |
| SK-11 | Ready | Test command validation and dispatch, reporting policies and messages, bucket-switch messages, and high-score run ranking/lifecycle (top-N ordering, ties, target/duration/manual finish, and score restoration). Use a controllable clock and in-memory scheduler where needed. |
| SK-12 | Ready | Add a separate Gradle `integrationTest` source set/task only for behavior that needs a real Paper server, such as loading the built plugin jar, verifying actual command registration/dispatch, and persistence across a server restart. Run it only when explicitly requested; keep it out of the normal `test` and `build` tasks. |
| SK-13 | Ready | Add a an option to `/score-get` to get the score for a specific bucket. |
| --- | --- | --- |
| SK-01 | Done | Save scores between clean server launches using enable-time load and disable-time save. Crash-safe/periodic persistence is still future work. |
| SK-02 | Done | Track independent UUID-keyed scores by named bucket with singular/plural units and initial values; support default and individual assignments. |
| SK-03 | Done | Add per-bucket `admin`, `global`, `player`, and `none` reporting policies. |
| SK-04 | Done | Notify affected online players when their active bucket changes, including current score and units. |
| SK-05 | Done | Implement target-score, timed, and manually stopped bucket runs with configurable top N, optional initial reset/snapshot restoration, global leader reporting, and final personal standings. Active runs persist across clean restarts. |
| SK-06 | Done | Archive player, bucket, or all-bucket scores and reset live entries to initial values; list archive IDs and contents. |
| SK-07 | Done | Replace the release plugin with Git-sensitive semantic versioning (minimum `0.2.1`, `v` tag prefix) and re-enable Gradle configuration cache. Versions are Git-derived, not a hardcoded snapshot. |
| SK-08 | Ready | Add JUnit 5 test infrastructure and keep the default Gradle `test` task server-free. Use a compatible in-memory Paper harness such as MockBukkit; use Mockito only for narrow boundaries where a harness is unnecessary. |
| SK-09 | Ready | Add fast score/bucket tests: validation and duplicates, initial values, UUID isolation, lazy entries, default/per-player selection, and signed add/subtract/reset behavior. |
| SK-10 | Ready | Test YAML round trips, assignments, active runs/snapshots, archive contents/resets, legacy loading, and malformed/unknown entries using temporary data directories. |
| SK-11 | Ready | Test command validation/dispatch/permissions, reporting/messages, bucket switches, ranking/ties, top-N thresholds, target/duration/manual completion, and restoration. Use controllable time/scheduling where needed. |
| SK-12 | Ready | Add a separate opt-in `integrationTest` source set/task for real Paper loading, command dispatch, companion API wiring, and restart persistence. Keep it outside normal `test`/`build`. |
| SK-13 | Ready | Add an option to `/score-get` for a specific bucket, preserving current optional-player syntax. |

View File

@@ -1,12 +1,12 @@
plugins {
id 'com.diffplug.spotless' version '6.22.0'
id 'com.diffplug.spotless' version '8.10.3'
id 'java-library'
id 'maven-publish'
id 'org.danilopianini.git-sensitive-semantic-versioning' version '7.0.24'
}
group = 'com.majinnaibu.minecraft.plugins'
description = "ScoreKeeper"
description = "Score Keeper"
gitSemVer {
minimumVersion.set('0.2.1')
@@ -70,7 +70,7 @@ repositories {
spotless {
java {
googleJavaFormat('1.27.0')
googleJavaFormat('1.36.1')
importOrder 'java', 'javax', 'com', 'net', 'org', ''
licenseHeaderFile 'config/license-header.txt'
target 'src/**/*.java'

View File

@@ -1,17 +1,17 @@
/*
This file is part of ScoreKeeper.
This file is part of Score Keeper.
ScoreKeeper is free software: you can redistribute it and/or modify
Score Keeper is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ScoreKeeper is distributed in the hope that it will be useful,
Score Keeper is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ScoreKeeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
along with Score Keeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
*/

128
docs/Modernize.md Normal file
View File

@@ -0,0 +1,128 @@
# Score Keeper Modernization Plan
Current baseline: October 2026. This replaces
[the historical Cursor plan](../.cursor/plans/Modernize.md) as the maintained
roadmap. It is a plan, not authorization to change runtime behavior or publish.
Read [CONTRIBUTING.md](../CONTRIBUTING.md) and [AGENTS.md](../AGENTS.md) first.
## Baseline: already implemented
The old Maven/Java 17/older Minecraft migration is no longer pending.
| Area | Current implementation |
| --- | --- |
| Build | Gradle 9.8.0 wrapper, Java 25 toolchain, Foojay resolver, configuration cache, Spotless |
| Paper target | API `26.2.build.129-stable`, manifest API `26.2`, documented Paper 26.2/26.3 support |
| Identity and messaging | UUID-based scores, Paper/Adventure messages, plugin logger, online `getPlayerExact` lookup |
| Domain | Named buckets, initial values, four reporting policies, default/individual assignments |
| Persistence | Version-3 scores YAML, archives YAML, legacy flat UUID score loading, shutdown save/enable load |
| Competitions | Target/timed/manual runs, scheduled checks, top-N rankings, score snapshots/restoration |
| Tooling | Bash build/deploy/server/backup/restore/local and Modrinth publishing; legacy PowerShell subset |
| Documentation | Contributor entry point, shared agent rules, current domain/integration references, manual release checklist, schema-shaped project metadata |
Implemented is not the same as verified on every advertised server version.
There are no automated Java tests yet; the CI `test` task is currently `NO-SOURCE`.
There is no real-server integration task and no automatic publishing workflow.
## Phase 1: reliable regression coverage (SK-08 through SK-11)
These are prerequisites for changing persistence, permissions, arithmetic, or
run behavior. Keep the default test task server-free.
- [ ] Add JUnit 5 infrastructure and an in-memory Paper harness compatible with
the current Java/Paper API (for example, MockBukkit if compatible). Use Mockito
only for narrow boundaries where a harness is unnecessary; verify compatibility
before choosing/pinning dependencies.
- [ ] Cover bucket ID/label/reporting validation, duplicates, initial values,
UUID isolation, lazy reads, active/default selection, all-player assignment
clearing, and signed add/subtract/reset semantics.
- [ ] Cover YAML round trips in temporary data directories: buckets, scores,
assignments, runs/snapshots, archives, and legacy flat scores. Include invalid
UUIDs, unknown buckets, malformed values, and empty archive buckets.
- [ ] Cover all eight command executors: sender/self/online-target resolution,
literal reset booleans, duration units/overflow, usage/errors, and existing
permission boundaries.
- [ ] Verify Adventure reporting audiences, changed-vs-unchanged scores, unit
labels, self/other bucket notices, and no duplicate run change notifications.
- [ ] Introduce a small controllable clock/scheduler seam where necessary for
deterministic run tests; avoid a wholesale architecture rewrite.
- [ ] Verify descending/name/UUID run ties, archive UUID ties, offline/unranked
entries, top-N boundaries, immediate targets, duration expiration, manual stop,
resumed runs, and exact pre-run score restoration (including new run entrants).
- [ ] Make CI produce real test reports and fail on these regressions once tests
exist; do not mistake missing reports for tested coverage.
## Phase 2: explicit real-server validation (SK-12)
- [ ] Add an opt-in `integrationTest` source set/task only for behavior requiring
actual Paper. Keep it out of normal `test`/`build`, use disposable directories,
and own/stop only the processes it starts.
- [ ] Load the built jar on both Paper 26.2 and 26.3 with Java 25; verify real
command registration/dispatch, Adventure output, scheduler completion, API
integration/load order, and persistence across clean restarts.
- [ ] Run [human-tests.md](human-tests.md) on both versions before release.
Record artifact version, Paper build, Java version, observations, and logs.
- [ ] Review startup/runtime deprecation warnings and unsupported API calls
found by builds/runtime tests; update compatibility claims only with evidence.
Do not broaden support to Spigot, Bukkit, Folia, or future Paper versions by
documentation changes alone.
## Phase 3: persistence and correctness hardening
Choose behavior changes explicitly and add regression tests first.
- [ ] Design safe periodic/dirty-state saves or explicit saves so crashes do not
lose all changes since shutdown. Decide save cadence and I/O threading while
snapshotting mutable state on the main thread.
- [ ] Design atomic replacement/recovery and consistency between score resets
and archives across the two YAML files. Preserve or migrate legacy data, and
ensure save failures are visible to administrators/callers.
- [ ] Define validation rules for malformed YAML rather than relying on defaulting
getters. Cover invalid integer types, assignments, missing archive fields,
empty snapshots, and recovery without overwriting good data.
- [ ] Decide whether integer overflow should fail, clamp, or use a wider score
type. Preserve negative-score use cases and provide an explicit data/API
migration if the type changes.
- [ ] Review the misleading `until-disabled` mode name: document current
resume-across-disable behavior until any new end-on-disable mode is deliberately
designed. Do not silently rename the command or change saved lifetime values.
## Phase 4: command and integration ergonomics
- [ ] Design permission nodes/defaults for score get/add/subtract/reset and archive
listing; define self-vs-other access and a migration strategy before restricting
currently open commands.
- [ ] Implement SK-13: explicit bucket selection for `/score-get`, with unambiguous
syntax, validation, help, docs, and tests. Preserve existing optional-player usage.
- [ ] Align manifest/executor help with supported archive scopes, reporting
arguments, and literal reset booleans; consider tab completion as a separate
tested improvement.
- [ ] Evaluate a smaller API/domain boundary only where needed for tested
behavior or companion integration. Retain public overload compatibility and
avoid unnecessary service abstractions.
## Phase 5: safer developer and release tooling
- [ ] Scope Bash start/stop/backup/restore process checks to the configured server
or a verified owned PID; never stop another project's Paper process.
- [ ] Verify the bootstrap helpers select an actual Java 25 JDK, not merely the
first cached Java executable, and document supported hosts.
- [ ] Bring PowerShell setup/configuration/process management to deliberate
parity with Bash or clearly retain a reduced supported surface. Prefer graceful
shutdown over forced termination.
- [ ] Make deployment select/verify the intended artifact and version instead of
relying only on newest modification time and a stale-source warning.
- [ ] Add lightweight local-link and JSON Schema checks for docs/metadata to CI,
keeping the scraper's slug-keyed contract and existing filenames.
- [ ] Rehearse a tagged release: rebuild after tagging, verify manifest/version,
run manual checks, review changelog and compatibility, upload deliberately, and
update hosted Modrinth description separately.
## Completion criteria
A modernization item is done only when its behavior and failure modes have
appropriate tests or recorded manual evidence, directly related docs are current,
and existing data/API contracts are preserved or explicitly migrated. Use
[TODO.md](../TODO.md) for SK feature/task status; this plan organizes the broader
work and must not mark unchecked tests or future infrastructure as implemented.

View File

@@ -1,365 +1,182 @@
# ScoreKeeper — Score-Tracking & "High-Score Table" Domain Analysis
# Score Keeper - Score-Tracking Domain
> **Scope of this document:** the domain logic that tracks player scores and (intended) the
> high-score table. Written for a new team member who must understand the scoring system
> *without opening the source*. Every claim below is traced to a file/line so it can be
> re-verified.
>
> **Bottom line up front (read this first):** ScoreKeeper currently tracks **live scores
> only, in memory, for the running server session**. It has **no persistence** and **no
> high-score table**. The high-score table is *described as a planned feature* in the
> README and is where the `/score-archive` command is *intended* to land scores, but
> **that code path is an unimplemented stub today.** There is no sorting, no tie-breaking,
> no entry cap, no decay, and no scoring formula/weighting anywhere in the codebase.
> This is a greenfield/early-stage domain — the write-up documents the *real* state and
> flags the gap, because documenting features that don't exist as if they did would mislead
> the next engineer.
This documents implemented behavior in
[ScoreKeeperPlugin.java](../src/main/java/com/majinnaibu/minecraft/plugins/scorekeeper/ScoreKeeperPlugin.java),
[ScoreBucket.java](../src/main/java/com/majinnaibu/minecraft/plugins/scorekeeper/ScoreBucket.java),
and [ScoreReporting.java](../src/main/java/com/majinnaibu/minecraft/plugins/scorekeeper/ScoreReporting.java).
For command syntax see [README.md](../README.md); for runtime wiring see
[the integration reference](plugin-integration-and-event-wiring.md).
---
## Buckets and live scores
## 0. How to read the rest of this doc against the task's four questions
- A bucket has an immutable ID, singular label, plural label, initial integer
value, and reporting policy. IDs match `[A-Za-z0-9_-]+`, are case-sensitive,
and must be unique. Labels must be nonblank; reporting cannot be null.
- A fresh server has `points` (`point`/`points`, initial value `0`, reporting `none`).
Loading bucket data restores this bucket if it is missing.
- `_bucketScores` maps bucket ID to `UUID -> int`. Players can have independent
scores in multiple buckets. Names are not used as identity keys.
- The server default bucket and optional UUID-specific assignments determine a
player's active bucket. Selecting the default removes their override.
`switchAllPlayers` changes the default and clears **all** assignments,
including offline players' assignments, without deleting scores.
- `getScore` lazily registers a missing score at the bucket's initial value.
Joining alone does not create an entry. Reads therefore affect who appears
in a later archive or run ranking.
- Add/subtract perform ordinary Java integer arithmetic. Zero/negative amounts
are allowed, scores can be negative, and overflow wraps. There are no bonuses,
weighting, decay, or automatic gameplay scoring.
- Reset writes the bucket initial value, not necessarily zero. Existing
no-bucket API methods use the active bucket; explicit-bucket overloads do not
change the player's assignment.
The task asks for (1) the score-entry data model + persistence format, (2) how scores are
recorded, (3) the high-score-table algorithm, and (4) scoring formulas/weighting.
For each question the answer is: **the mechanism that exists vs. the mechanism the project
intends**, so readers never conflate the two.
## Reporting and bucket changes
| # | Question | Short answer |
|---|----------|--------------|
| 1 | Score-entry data model & persistence | Live score = `UUID -> int` in a `HashMap`. **No persistence** (load/save are `TODO` stubs). |
| 2 | How scores are recorded | **Manual, event-free:** the *administrator* runs a command. No game events, no timers. |
| 3 | High-score-table algorithm | **Not implemented.** No sort/tie-break/cap/decay. Only an aspirational `/score-archive`. |
| 4 | Scoring formulas / weighting | **None.** Scores are plain integer accumulators; no weighting, no decay, no bonuses. |
For a changed value written through `setScore`, outside a run:
---
| Policy | Audience |
| --- | --- |
| `none` (default) | Nobody |
| `player` | Scored player |
| `global` | All online players |
| `admin` | Online operators or holders of `scorekeeper.admin`, plus the server log |
## 1. The score-entry data model & persistence *(task Q1)*
Writing the same value sends no score-change report. Commands that change scores
do not independently promise success messages; inspect `/score-get` when reporting
is `none`. A bucket change tells an affected online player the ID and current score.
Unit formatting uses the singular label for exactly `1`, plural otherwise.
`/score-get` itself displays only the number, without bucket or unit labels.
### 1.1 What a "score entry" actually is (current reality)
Run reporting overrides the bucket policy. Archive resets and run start/restore
directly update maps and do not send ordinary per-score change reports.
The entire live-score domain is **one field** in the plugin's entry-point class:
## High-score runs
- **File:** `src/main/java/com/majinnaibu/minecraft/plugins/scorekeeper/ScoreKeeperPlugin.java:38`
- **Declaration:** `private final HashMap<UUID, Integer> _playerScores = new HashMap<UUID, Integer>();`
Each bucket can have at most one active run; different buckets may run concurrently.
Top N must be at least one. There are three lifetime modes:
That is the whole model:
- **Target score:** finishes when any recorded score reaches/exceeds the target.
With reset enabled, the target must exceed the initial value. Without reset,
existing scores can finish a run immediately when it starts.
- **Duration:** a positive duration, stored as an absolute epoch-millisecond
expiration. Time offline counts toward expiration.
- **Until disabled:** no automatic end; stop explicitly. Plugin disable saves the
run rather than finishing it, so it resumes on restart.
| Aspect | Value |
|--------|-------|
| Record shape | A single `Integer` (the score), keyed by a player's `UUID`. |
| Key type | `java.util.UUID` — the player's `UniqueId`, *not* the name string. |
| Value type | `int` (Java `Integer`), autoboxed into the map. |
| Container | one `java.util.HashMap` on the plugin instance. |
| Uniqueness | one entry per `UUID`. A player can have exactly one live score at a time. |
| Default for a new player | `0` — see §3.1 ("first-time player" edge case). |
Starting with reset enabled snapshots existing bucket entries and sets them to
the initial value. During the run, a changed score is always reported to its
player. If that player is in the top N **after the change**, the report is sent
to all other online players too, once per recipient.
There is **no `Score`/`ScoreEntry`/`PlayerStats` value class**, no timestamp, no
name stored alongside the score (name is looked up from the live server only — see §2.3),
and no secondary index.
Completion is checked immediately at start/load, synchronously every 20 ticks,
and on a changed target-run score. Manual stop also completes the run.
The scheduled check uses wall-clock time; under server lag it need not fire at
an exact real-time second.
### 1.2 Persistence format: **none exists**
### Ranking and results
Persistence is *intended* but *not built*. Three concrete stubs prove this:
Rankings include all recorded entries in that bucket, including offline players
and entries read/created before the run. The order is:
1. **On disable (server stop):** `ScoreKeeperPlugin.java:46-49` `onDisable()` logs
*"Unable to save scores to file. This feature is not implemented yet."* — the map
is **discarded** on shutdown; nothing is written.
2. **On enable (server start):** `ScoreKeeperPlugin.java:59-60` `onEnable()` logs
*"Unable to load scores from file. This feature is not implemented yet."* — the map
always starts **empty** `{}` every server start.
3. **Archive:** `ScoreKeeperPlugin.java:72-74` `archiveScore(Player)` logs
*"Unable to archive score for <name>."* and returns — the "save to high-score table"
action is a no-op.
1. Descending score.
2. Case-insensitive player name, using Paper's offline-player lookup.
3. UUID string to break remaining ties.
So there is **no SQLite, no JSON, no YAML, no flat file, no config.yml**. The only file on
disk that concerns scores is `plugin.yml` (the command manifest — it lists the commands but
stores no scores). A grep of the whole tree for `sql / json / yaml / saveResource /
YamlConfiguration / File / Files. / Gson / Jackson` finds **zero hits** other than the
TODO/log strings.
Unknown/blank names fall back to the UUID string. Ties have distinct consecutive
places, not shared ranks. Top N limits display/reporting, not stored entries.
Every online player receives the final top-N table and their own full-ranking
place/score, or an unranked result at the initial value. The final table is logged.
**Persistence format today = "in RAM only, lost on server restart."**
With reset enabled, completion replaces the bucket map with its pre-run snapshot.
Players first recorded during the run are removed from that map and get the initial
value on their next read. Personal results refer to the finished run, not restored
scores. Without reset, earned scores remain. Run completion does **not** create a
score archive.
> Implication for a new engineer: any "who's the top player" question answered *across
> restarts* is impossible today. Scores reset to the map being empty on every server boot.
## Archives
---
Player, single-bucket, and all-bucket archives create immutable snapshots with a
random UUID ID, scope text, epoch-millisecond creation time, and nested
`bucket ID -> UUID -> int` scores. A player archive uses their active bucket;
bucket/all archives include all recorded entries, even offline players.
## 2. How scores are recorded *(task Q2)*
Live archived entries reset to their respective initial values. Archiving fails
before changing any scores if a selected bucket has an active run; stop the run
first. Archives do not cap or prune entries.
### 2.1 The recording model is **manual and command-driven — no events, no timers**
[ScoreArchiveListCommand.java](../src/main/java/com/majinnaibu/minecraft/plugins/scorekeeper/commands/ScoreArchiveListCommand.java)
lists archives newest first. Within an archive, scores display descending with
UUID-string tie-breaking (not the run's name tie-break). Names and unit labels are
resolved at display time, not captured in the snapshot; missing bucket definitions
use the generic unit `scores`.
Scores move only when an administrator (or console/RCON) **types a command**. There is:
## Persistence
- **No** `implements Listener`, no `@EventHandler`, no `registerEvents(...)`, no
`getServer().getPluginManager().registerEvents(...)`.
- **No** scheduler: no `getScheduler()`, no `runTask`, no `Timer`.
- **No** automatic hook to game events (e.g. a player killing a mob or reaching a goal
awards points automatically — *nothing like that exists*).
Both files live in `plugins/ScoreKeeper/`. Loading occurs on enable and saving
on disable. There is no periodic autosave or immediate archive write despite
the command's "Saved score archive" acknowledgement; a crash can lose recent
state. Back up only after a successful clean shutdown.
A grep for `EventListener|@EventHandler|Listener|Scheduler|runTask` across `src/` returns
**zero**.
### `scores.yml` (currently writes version 3)
So "scoring" happens **on demand**, by a person, via one of the four mutating commands:
| Command | Effect on the map | Source |
|---------|-------------------|--------|
| `/score-add [player] <amount>` | `score += amount` | `ScoreKeeperPlugin.addScore` `:67-70` |
| `/score-subtract [player] <amount>` | `score -= amount` | `ScoreKeeperPlugin.subtractScore` `:88-91` |
| `/score-reset [player]` | `score = 0` | `ScoreKeeperPlugin.resetScore` `:80-82` |
| `/score-archive [player]` | **intended** to snapshot to a high-score table and reset to 0; **actually a no-op** | `ScoreKeeperPlugin.archiveScore` `:72-74` |
`/score-get [player]` is read-only (returns the score, §2.4).
### 2.2 The add/subtract primitives (the only real "write" path)
Both funnel through one private setter:
```
addScore(player, n) -> old = getPlayerScore(player); setPlayerScore(player, old + n) :67-70
subtractScore(player,n)-> old = getPlayerScore(player); setPlayerScore(player, old - n) :88-91
setScore(player, s) -> setPlayerScore(player, s) :84-86
resetScore(player) -> setPlayerScore(player, 0) :80-82
setPlayerScore(p, v) -> _playerScores.put(p.getUniqueId(), v) :108-110
```yaml
version: 3
default-bucket: points
buckets:
points:
singular: point
plural: points
initial-value: 0
reporting: none
scores:
"00000000-0000-0000-0000-000000000001": 10
player-buckets:
"00000000-0000-0000-0000-000000000002": points
high-score-runs:
points:
top-n: 3
reset-scores: true
lifetime: duration
target-score: 0
expires-at: 1800000000000
previous-scores:
"00000000-0000-0000-0000-000000000001": 25
```
Notes a new engineer must internalize:
This illustrates field shapes, not a file to install unchanged. Overrides equal
to the default bucket are normally omitted. Saved lifetime strings are
`target_score`, `duration`, and `until_disabled`. The loader reads structure,
not a version-dispatch migration table.
- **Read-modify-write.** `addScore`/`subtractScore` read the current value, compute, write
back in two map operations. (There is no concurrency control — see §5 risks.)
- **`int` math.** Values are Java `int`; a score can go **negative** (there is no floor at
0 — `/score-subtract 50` on a 10-score yields `-40`), and can overflow `int` only after
`~2.1e9` points, which is not a practical concern.
- **No validation of the direction.** The only validation is *syntactic*: the amount must
parse as an integer (see §2.3).
If `buckets` is absent, the loader treats top-level UUID/integer entries as legacy
`points` scores. Invalid bucket definitions/UUIDs/runs are skipped with warnings;
invalid reporting falls back to `none`, and an unknown default falls back to
`points`. Unknown bucket assignments are ignored. Bukkit YAML getters supply
defaults for some missing/wrongly typed values: do not assume every malformed
value is rejected or logged.
### 2.3 Command surface (who/what is allowed to record a score)
### `archives.yml`
Every command executor lives in `src/main/java/.../scorekeeper/commands/` and shares one
shape: parse args, resolve the target player, call the `ScoreKeeperPlugin` method, return
`true` (consumed). Two behavioral details matter:
- **Self-target default:** if a *player* runs a command and omits the name, they target
*themselves*: `targetPlayer = (Player) sender`. (e.g. `ScoreGetCommand.java:44`,
`ScoreAddCommand.java:48`, `ScoreResetCommand.java:47-49`.)
- **RCON/console path:** if the sender is **not** a player (console/RCON), a player name
is **required** — omitting it prints usage instead of acting
(`ScoreGetCommand.java:46-48`, `ScoreAddCommand.java:45-47`,
`ScoreResetCommand.java:44-46`).
- **Name resolution:** `getServer().getPlayerExact(name)` — **exact, case-sensitive**
lookup by the *currently online* name (`ScoreGetCommand.java:50`,
`ScoreAddCommand.java:57`, `ScoreResetCommand.java:50`). A name that is not online
yields `null` → "Can't find a player with that name". Note the *map key is a UUID*, but
*lookup by name only works while that player is online* — you cannot change an offline
player's score by name today.
- **No permission nodes anywhere.** `plugin.yml` declares no `permission:`/`permissions:`
and the code checks none. The README's note ("the commands aside from get are intended
for admins … Permissions support is coming") is **intent, not enforcement** — a vanilla
player can run `/score-add` today.
### 2.4 Reading a score (`/score-get`)
`ScoreGetCommand.java:38-84` → `ScoreKeeperPlugin.getScore(player)` → `getPlayerScore(player)`
(`ScoreKeeperPlugin.java:76-78, 100-106`). It returns the live integer (0 for a known-but-
unwritten player, which also *materializes* a 0 entry, see §3.1). Output formatting
("Your score is N" vs. "PLAYER's score is N") depends only on whether the sender is the
target or not — it carries no ranking or table.
---
## 3. The high-score-table algorithm *(task Q3)*
### 3.1 What exists: **nothing. It is aspirational.**
There is **no high-score table, no ranking structure, no sort, no tie-break rule, no max
entry count, and no decay/rotation** anywhere in the codebase. The task's premise ("the
high-score table") reflects the **product intent** in the README, not the **code**. Concretely:
- The README (`README.md:11`) says `/score-archive` *"Saves the player's score to a
'High Scores' table and resets their current score to 0."*
- The manifest (`plugin.yml:18-20`) declares `/score-archive` with that very description.
- But the command is a stub: `ScoreArchiveCommand.java:37-39` (`onCommand` body) replies
*"archive command unimplemented"*, and the underlying `archiveScore`
(`ScoreKeeperPlugin.java:72-74`) only logs and returns — it neither writes a table nor
resets anything.
Therefore the "algorithm" is: **no-op.** A new engineer asked to "implement the high-score
table" is starting from zero; the design questions in §3.2 are **open**, not answered by code.
### 3.2 Open design questions the table must settle (no code today decides these)
Since no implementation exists, these are *decisions to be made*, recorded here so the
implementation task doesn't reinvent the debate:
- **Storage/persistence format.** The load/save TODOs (`:47`, `:59`) say "to file";
`plugin.yml`/Bukkit convention favors YAML (`YamlConfiguration`), but JSON/SQLite are all
viable. **Unchosen.** Persisting to `data/` via `getDataFolder()` is the idiomatic Bukkit
path.
- **What an entry is.** Today a live score is just `{uuid -> int}`. A high-score entry
likely needs **player name + score + (timestamp?) + (date earned?)**. Name is *not*
currently stored with the score, so a durable table must capture the name at archive
time (a UUID-only entry can't render a leaderboard without the name being resolvable).
- **Sorting / ordering.** Almost certainly **descending by score**.
- **Tie-breaking.** Undefined. Candidate rules: by *score only*; by *earliest* archived
first (stable, time-ordered); by *name* (alphabetical); or "first to reach that score."
- **Max entries / cap.** Undefined. A leaderboard needs a cap (e.g. top 10 / top 30);
today there is no cap because there is no table.
- **Decay / rotation / time window.** None, and none described in docs — so the safe
default is **"scores are permanent, no decay."**
- **Reset semantics on archive.** README promises archive *resets to 0* *and* records.
`ScoreArchiveCommand` must decide: does archiving also reset? Does it allow multi-entries
(a player appearing more than once) or one row per player? All open.
### 3.3 Full lifecycle of a score: creation → (intended) display on the high-score table
This is the acceptance-criterion walk-through. Each stage is marked **[REAL]** (in code now)
or **[GAP]** (intended, not built).
1. **Player joins / acts** — a score *doesn't* exist yet. First interaction with the map is
lazy (see stage 4a). **[REAL]**
2. **Admin records a score** — `admin: /score-add Alice 10`. Parsed in `ScoreAddCommand`,
routed to `addScore`. The first time this runs for Alice, `getPlayerScore` **creates**
her entry at 0 and returns it; then `10` is written. **[REAL]**
3. **Score accumulates** — later `/score-add Alice 5` → 15; `/score-subtract Alice 2` → 13;
`/score-reset Alice` → 0. All in the in-memory map, live only. **[REAL]**
4. **Read** — `/score-get Alice` → "Alice's score is 13". No ranking shown. **[REAL]**
5. **Server restart** — `onDisable` *cannot* save (stub), `onEnable` *cannot* load (stub);
the map is **lost**. Alice's 13 is gone; every score starts empty again. **[REAL] —
this is the current data-loss reality.**
6. **Intended: archive to the high-score table** — `admin: /score-archive Alice` should
freeze Alice's 13 into a durable, sorted leaderboard and reset her live score to 0, so
it survives restarts. **[GAP]** — currently returns "archive command unimplemented".
7. **Intended: display on the high-score table** — a command (not yet built) renders the
capped, sorted list. **[GAP]** — no such command, no structure to render.
**Edge cases (explicitly, per the acceptance criteria):**
- **First-time player / first write.** A player has no map entry until `getPlayerScore` is
called, which **inserts `0` on first access** (`ScoreKeeperPlugin.java:100-106`). So a
first `/score-add X 10` yields **10, not** `10 - 0` ambiguity, and a first `/score-subtract
X 3` yields **−3** (no minimum-0 clamp). A first `/score-get X` returns **0** and
*materializes* the entry at 0. This `get-or-create-0` behavior is the de-facto "first-time
player" rule. **[REAL]**
- **Ties.** **Undefined** because no table exists. When the table is built, decide a
tie-break (§3.2). No code today can observe or sort ties — `HashMap` gives no order. **[GAP]**
- **Table full.** **Undefined** because no cap exists. When a cap is introduced, decide
what happens to the displaced entry: drop it, or "rotate" it into overflow. No code
today enforces a maximum. **[GAP]**
- **Offline / unknown name.** `getPlayerExact(name)` returns `null` for anyone not
currently online or any misspelling → the command prints "Can't find a player with that
name" and changes nothing. You **cannot** archive or reset an *offline* player by name
today; by-UUID writes (if a future table stores names+UUIDs) would fix that. **[REAL]**
- **Negative / large scores.** No clamp; negatives allowed, `int` overflow only near
~2.1 billion. **[REAL]**
- **Double-spawn / relogin.** Keyed by `UUID`, **not name**, so a name change or two
players sharing a name can't collide on the *live* map; but a *name* is never stored,
so a future table that only persists the UUID can later fail to render a name.
---
## 4. Scoring formulas & weighting *(task Q4)*
**None.** There is:
- No formula, no multiplier, no combo/bonus/streak logic.
- No weighting between action types.
- No time-based decay or "points per game" normalization.
Scores are **pure integer accumulators**: `score = Σ(adds) − Σ(subtracts)` over the session,
resettable to 0 by `/score-reset` (intended: on `/score-archive`). The only "arithmetic" in
the code is the `+`/`−` in `addScore`/`subtractScore` and the `0` floor written by
`resetScore`. `int` semantics apply (wrapping overflow; no checked arithmetic). Any
formula/weighting is a **future-design** decision, not encoded today.
---
## 5. Data-flow diagram (text)
```
ADMINISTRATOR / CONSOLE / RCON (no game events, no scheduler, no auto-scoring)
│ types a command
▼
┌─────────────────────────────┐
│ command executors │ commands/Score*Command.java
│ parse args + resolve player│ getPlayerExact(name) ── must be ONLINE (name→UUID)
│ (self-target if player) │ no permission checks
└──────────────┬──────────────┘
│ calls
▼
┌───────────────────────────────────────────────┐
│ ScoreKeeperPlugin (entry point; plugin.yml main)│
│ │
│ addScore / subtractScore / resetScore / setScore │ read-modify-write on...
│ getScore (read) archiveScore (STUB)│
└──────────────┬───────────────────────┬──────────┘
│ read-modify-write │ (intended: snapshot→table, reset 0)
▼ ▼
live map: HashMap<UUID, int> ╳ NOT IMPLEMENTED
"score entry = one int per UUID" high-score table:
default 0, no clamp, in RAM only ─ no structure, no sort,
│ ─ no persistence,
├─ READ: /score-get → "N" ─ no cap/decay
│
└─ LIFECYCLE:
onEnable : load from file → TODO (stays {} ; lost on restart)
onDisable : save to file → TODO (map discarded at shutdown)
PERSISTENCE: none │ SCORE FORMULA: none │ EVENTS/TIMERS: none │
PERMISSIONS: none │ HIGH-SCORE TABLE: aspirational stub only
```yaml
archives:
"00000000-0000-0000-0000-000000000003":
scope: bucket points
created-at: 1800000000000
buckets:
points:
scores:
"00000000-0000-0000-0000-000000000001": 10
```
---
This file has no explicit format version. Empty bucket score maps may be omitted
on serialization because only individual score entries are written.
The two files are saved separately; there is no cross-file transaction or atomic
replacement guarantee. Save I/O errors use the plugin logger. Never edit live
data while the server is running: shutdown can overwrite it.
## 6. Quick reference — "where to look first"
## Validation status
| I want to understand… | Go to |
|-----------------------|-------|
| The entire live data model | `ScoreKeeperPlugin.java:38` (one `HashMap<UUID,Integer>`) |
| How a score changes | `addScore`/`subtractScore`/`resetScore`/`setScore` `:67-91` |
| How a score is read | `getScore` `:76-78` → `getPlayerScore` `:100-106` (note get-or-create-0) |
| The "high-score table" | **Doesn't exist** — see `archiveScore` stub `:72-74`; design open in §3.2 |
| Persistence (save/load) | `onDisable` `:46-49`, `onEnable` `:59-60` — both `TODO`, not built |
| Command behaviors | `commands/Score*Command.java` (self-target default; RCON requires a name; exact online-name lookup) |
| What's declared/intended but not wired | `plugin.yml:18-20` (`/score-archive`), `README.md:11`, `README.md` notes |
| Build/runtime target | `build.gradle` (paper-api 1.21.7, Java 21), `plugin.yml` (`api-version: 1.21`) |
---
## 7. Risks a new engineer should know (correctness gaps in the *current* live domain)
These are real, not future-work — flagging because the doc's job is to prevent a new
developer from assuming the system is more mature than it is:
1. **Data loss on restart.** No save/load (`:47`, `:59`). Every server boot wipes all
scores. Any "leaderboard across sessions" is broken by design.
2. **No permissions.** Anyplayer can self-add points. README says this is by intent
("coming after I get archive to work") but it is not enforced.
3. **Race condition on add/subtract.** `read → compute → write` is not atomic and the
`HashMap` is not thread-safe; concurrent command executions could lose an update.
(Low likelihood today since commands are serial on one thread, but it's a latent bug for
any async/event-driven scoring that gets added.)
4. **No minimum-0 / no validation of amount sign.** Subtracts produce negatives freely.
5. **Name lookups are online-only & exact.** Can't target offline players by name;
case-sensitive; "Alice" ≠ "alice".
6. **No high-score table.** The flagship advertised feature (`/score-archive` → "High
Scores" table) is a no-op; a new engineer must not expect ranking/persistence to work.
---
## 8. Summary for the synthesizer (`Project.md` § "domain model & scoring logic")
Distilled, code-grounded, and honest:
- **Model:** one `int` per player `UUID`, held in `ScoreKeeperPlugin._playerScores`
(`HashMap`), default `0`.
- **Recording:** manual, admin-driven commands; **no events/timers**; no permission guard.
- **Persistence:** **none** — load/save are `TODO`; scores are lost on restart.
- **High-score table:** **does not exist** — `/score-archive` is a stub; sorting/tie-break/
cap/decay are **undecided design items** (listed in §3.2).
- **Formula/weighting:** **none** — plain `int` accumulation.
- **Lifecycle:** create-on-first-access (0) → add/subtract/reset (live only) → read via
`/score-get` → *intended* archive+reset + table display **not built** → lost on restart.
- **Edge cases:** first-time/first-write ⇒ 0-or-delta, no floor; ties/table-full ⇒ undefined
(no table yet); offline/unknown name ⇒ "can't find", unchanged.
Everything below the "high-score table" line of the README is **future work**, and the
write-up's job is to make that boundary explicit so the next team member isn't misled.
These are source-level behavior descriptions, not claims of passing automated
tests. Pending coverage is tracked in [TODO.md](../TODO.md). Before release,
use [human-tests.md](human-tests.md), particularly ranking ties, empty buckets,
restoration, malformed data, and restart/upgrade cases.

72
docs/human-tests.md Normal file
View File

@@ -0,0 +1,72 @@
# Score Keeper Human Testing
Use this manual pre-release checklist on disposable Paper 26.2 and 26.3 servers
(test both before advertising both). Score Keeper stores data in its plugin folder
and interacts with players, command senders, and scheduled runs; a passing build
alone does not verify these workflows. These are test scenarios, not passing results.
See [CONTRIBUTING.md](../CONTRIBUTING.md) for setup and helper-script safety, and
[the domain reference](domain-score-tracking.md) for expected behavior.
## Test Setup
- Use Java 25 and a backed-up test server. Keep the server log available throughout testing.
- Use at least three test players for rankings: an operator, a non-operator with `scorekeeper.admin`, and an ordinary player. Use a console or RCON session for non-player sender cases.
- Before each run, preserve `plugins/ScoreKeeper/scores.yml` and `archives.yml`, or use a fresh test server. Archive, reset, and bucket-wide commands intentionally change scores.
- Record plugin artifact/version, Paper version/build, Java version, command sender, arguments, expected and observed messages, and score values before and after each operation. Save pass/fail notes and relevant logs outside player data committed to the repo.
- Ensure only the intended Score Keeper jar is installed. Stop with `stop` in the server console so disable-time saves run. Do not use helper scripts that can stop other Paper processes on a shared host.
## Human Checklist
### Startup and score commands
- Start Paper and confirm Score Keeper enables, registers every documented command, and loads existing data without errors.
- As a player, run `/score-get`, `/score-add 10`, `/score-subtract 3`, and `/score-reset`; inspect `/score-get` after each mutation. Repeat with console/RCON, supplying a player name where required. Missing targets from non-player senders must produce usage, not self-scoring.
- Try zero and negative amounts: they are valid signed integers (for example, adding `-3` decreases the score). Try missing/non-numeric/out-of-range amounts: these should produce usage/errors without changing scores. At integer boundaries, record the current wrapping behavior; there is no overflow guard.
- Target offline/unknown names and supply extra arguments; verify errors/usage without unrelated changes. Confirm gameplay such as mob kills does not award points unless a companion plugin is installed.
- Use two players to verify each player's score is independent. Change a player's Minecraft name if practical, then confirm their score remains associated with their UUID.
- Check singular/plural labels at 1, 0, negative, and multiple values in reporting, bucket-change, and run/archive messages. `/score-get` only displays a number; it does not show bucket/units.
### Buckets and reporting
- Create a test bucket with a nonzero initial value and distinctive singular/plural labels, for example `/score-bucket create Bread loaf loaves 5 player`. Verify invalid/duplicate IDs, invalid initial values, and unknown reporting policies produce errors. IDs are case-sensitive; command labels each occupy one argument. Use a companion-plugin API test if checking blank/null labels that cannot be supplied naturally as command arguments.
- Switch one player to the bucket, add and subtract points, and confirm other players remain in their own active bucket. Switch back and verify the original score is unchanged.
- Change the server-wide default with `/score-bucket all <bucketId>`. Confirm individual assignments are cleared, online players receive the appropriate change notice, and new players use the new default.
- For each reporting policy (`none`, `player`, `admin`, `global`), change a score and verify exactly the intended audience receives the report. Test with an operator, a `scorekeeper.admin` player, an ordinary player, and the scored player.
- Exercise authorized/unauthorized bucket creation and switching another/all players: these require `scorekeeper.admin`. An ordinary player must still be able to view/select their own bucket. Selecting the already-active bucket should not produce a bucket-change notice.
- Set reporting to `none` and verify a successful add/subtract/reset can be silent. Writing the same score should not send a change report under any policy. `admin` reports should also reach the server log.
- Note that the README says score get/add/subtract/reset currently have no permission checks and can target any online player. Confirm that exposure is acceptable for the server before enabling these commands publicly.
### Archives
- Archive one player's active-bucket score as an admin, then inspect `/score-archive-list` and `/score-archive-list <archiveId>`. Confirm the snapshot value/bucket and the live score returns to that bucket's initial value. Ordinary players must be denied archive creation but can list/view archives.
- Repeat for `/score-archive bucket <bucketId>` and `/score-archive all`. Confirm only the selected bucket or all buckets are archived and reset as requested.
- Check archive IDs are listed newest first, then restart and confirm archives and their contents remain available.
- Try an unknown archive ID or bucket ID and verify a useful failure without unrelated scores being changed.
- Include recorded offline players and ties: entries sort descending by score then UUID, not run-style name ties. Check empty bucket archives before/after restart and record any omitted empty bucket sections.
- Attempt player/bucket/all archiving while a selected bucket has an active run. It must fail before changing any selected scores; stop the run and retry. Archive resets should not send normal per-score reporting.
### High-score runs
- Start target/timed runs with at least three players. Use literal booleans, for example `/score-run start Bread 2 true duration 10s`. Top N must be at least 1. Reject invalid booleans, zero/negative/overflowing duration, uppercase time suffixes, unknown buckets, and duplicate runs.
- A reset target must exceed the initial value. Without reset, a pre-existing score at/above the target may finish immediately; verify this rather than assuming every start remains active.
- Change scores for players inside and outside the current top-N. Verify individual score-change messages and global reporting for current top-N players match the run behavior.
- End runs by reaching the target, expiration, and `/score-run stop`. Also start an `until-disabled` run and stop it manually.
- Check descending score, case-insensitive name then UUID tie-breaking, distinct consecutive places for ties, each online player's place, unranked players, and the top-N cutoff. Include recorded offline players; top N limits display, not stored entries.
- With reset enabled, verify scores begin at the initial value and pre-run entries are restored exactly. A player first recorded during the run should return to the initial value on the next read after completion. With reset disabled, scores remain as earned. Final personal results must show run scores, not restored scores.
- Restart cleanly while a run is active. Confirm snapshots survive, timed expiration includes time offline, overdue runs finish on enable, and `until-disabled` resumes until explicitly stopped. Confirm completion happens once and no automatic archive is created.
- Run two buckets concurrently and confirm independent completion/restoration. Observe timed completion under lag: checks run every 20 ticks, not at an exact wall-clock second.
### Persistence and upgrades
- Restart after changing scores, bucket definitions, reporting policies, the default bucket, and per-player bucket assignments. Verify all values and assignments persist.
- Test a clean data folder and copies of older files, including flat top-level UUID scores (loaded into `points`). Verify default/reporting fallbacks and invalid UUID/bucket/run warnings. For malformed types/unknown assignments, record actual getter defaults/ignored values; current loading is not comprehensive validation.
- Check `scores.yml` version 3 and the archive fields after a clean shutdown. Both files save only on disable, not each mutation. On an explicitly authorized disposable server, compare a forced crash with the last clean save: loss of recent changes is a known limitation, not successful durability.
- If using a companion plugin, verify `depend: [ScoreKeeper]` load order, main-thread awards into an explicit bucket, and visible failure when Score Keeper is absent/disabled. Verify no unintended active-bucket switch.
## Automated Coverage
There are currently no Java test sources or test dependencies in this project,
and no integration-test source set. Gradle `test` is `NO-SOURCE` and does not
exercise Score Keeper behavior. Scenarios remain unverified until actually
tested; SK-08 through SK-12 in [TODO.md](../TODO.md) and
[the modernization plan](Modernize.md) describe pending automated coverage.

View File

@@ -0,0 +1,95 @@
**Score Keeper**
Score Keeper tracks player scores in configurable buckets. Use it for event points,
competitions, or other server-side scoring systems, and integrate it with other
plugins through the public API. Points are awarded by commands or companion
plugins, not by built-in gameplay event listeners.
## Installation
Requires Java 25 and Paper 26.2 or 26.3. Stop your server cleanly, back up plugin
data, and place the downloaded jar in `plugins`, removing older Score Keeper jars.
Restart and check the server log. The installed plugin ID and data folder remain
`ScoreKeeper`; the display name is Score Keeper.
## Commands
Players can omit an optional player name to target themselves. Named targets must
be online. Console and RCON must provide a player name for score get/add/subtract/reset;
archive also accepts `all` and `bucket` scopes. Add/subtract accept signed 32-bit
integers, including zero and negative amounts. Bucket IDs are case-sensitive and
allow letters, numbers, `_`, and `-`; each command-created unit label is one argument.
* `/score-get [playerName]` - Displays the target player's score in their active bucket.
* `/score-add <amount>` - Adds an amount to your score in your active bucket.
* `/score-add <playerName> <amount>` - Adds an amount to the target player's score.
* `/score-subtract <amount>` - Subtracts an amount from your score in your active bucket.
* `/score-subtract <playerName> <amount>` - Subtracts an amount from the target player's score.
* `/score-reset [playerName]` - Resets the target player's active-bucket score to that bucket's initial value.
* `/score-archive` - Archives and resets your score in your active bucket.
* `/score-archive <playerName>` - Archives and resets the target player's score in their active bucket.
* `/score-archive all` - Archives and resets scores in every bucket.
* `/score-archive bucket <bucketId>` - Archives and resets every score in one bucket.
* `/score-archive-list` - Lists saved archive IDs, newest first.
* `/score-archive-list <archiveId>` - Displays the saved scores in one archive.
* `/score-bucket` - Displays your active bucket.
* `/score-bucket <bucketId>` - Switches your active bucket.
* `/score-bucket create <id> <singular> <plural> <initialValue> [reporting]` - Creates a bucket. Reporting can be `admin`, `global`, `player`, or `none` (default).
* `/score-bucket <playerName> <bucketId>` - Switches a player's active bucket.
* `/score-bucket all <bucketId>` - Changes the server's default bucket and clears individual bucket assignments.
* `/score-run start <bucketId> <topN> <true|false> target <score>` - Starts a run that ends when a score reaches the target.
* `/score-run start <bucketId> <topN> <true|false> duration <time>` - Starts a timed run. Use a positive number and lowercase `s`, `m`, `h`, `d`, or `w`, such as `4h`.
* `/score-run start <bucketId> <topN> <true|false> until-disabled` - Starts a run with no automatic end, including across clean restarts.
* `/score-run stop <bucketId>` - Ends an active run.
## Permissions
The `scorekeeper.admin` permission (default: operators) is required for
`score-archive`, bucket creation, switching another player/all players, and run
management. Viewing/selecting your own bucket is open. Score get/add/subtract/reset
and archive-list have no permission checks; add, subtract, and reset can target
**any online player**. Restrict access externally if this does not fit your server.
## Features
* Create score buckets with custom singular/plural labels, initial values, and reporting policies.
* Reporting can notify operators/admins, everyone online, only the scored player, or nobody.
* Start target-score, timed, or until-disabled high-score runs with configurable top-N standings and optional score resets.
* Archive player, bucket, or all-bucket scores; archived scores reset to their bucket's initial value.
* Persist bucket definitions, assignments, scores, active runs, and archives in the plugin's data folder.
Reporting defaults to `none`, so successful score mutations can be silent; use
`/score-get` to inspect the number. Changed scores use singular units for exactly
1, plural otherwise. Scores may be negative and overflow is not checked.
Runs require top N of at least 1 and a literal `true`/`false` reset argument.
For example, `/score-run start points 3 true duration 4h`. Run reporting overrides
the bucket policy: the scored player always receives changes, and current top-N
players' changes are reported globally. Rankings include all recorded bucket
entries, even offline players; ties use case-insensitive name then UUID and
consecutive places. Final results include each online player's place. Reset runs
restore previous scores, while non-reset runs keep earned scores. Timed runs use
wall-clock time, including time offline; an existing target can finish a non-reset
run immediately.
Stop a run before archiving its bucket. Final run results are announced/logged,
not automatically archived. Archives and live state are saved to
`plugins/ScoreKeeper/archives.yml` and `scores.yml` **on clean shutdown/plugin
disable**, not after every command. Crashes can lose changes since the last save.
Do not edit data files while the server is running.
## API
Other plugins can create buckets with
`createBucket(id, singular, plural, initialValue, ScoreReporting)`, use bucket-aware
score methods, and manage runs with `startTargetScoreRun`, `startTimedScoreRun`,
`startUntilDisabledScoreRun`, and `stopHighScoreRun`. Declare a dependency on
`ScoreKeeper` and call the enabled plugin API on Paper's main thread.
See the [integration reference](https://github.com/headhunter45/ScoreKeeper/blob/develop/docs/plugin-integration-and-event-wiring.md).
## Compatibility
Built exclusively for Paper 26.2 and 26.3 with the Paper API and Adventure APIs. Bukkit and Spigot servers are not supported.
Source and development instructions are in the
[repository](https://github.com/headhunter45/ScoreKeeper). Licensed under GNU AGPL v3 or later.

View File

@@ -1,7 +1,7 @@
{
"name": "Score Keeper",
"url": "https://modrinth.com/plugin/scorekeeper",
"summary": "Track player scores in configurable buckets with custom reporting, high-score runs, and archives. Includes in-game commands and an API for other plugins.",
"summary": "A Paper scoring engine with configurable buckets, reporting, high-score runs, shutdown-persisted archives, commands, and a companion-plugin API.",
"visibility": "public",
"links": {
"issueTracker": "https://github.com/headhunter45/ScoreKeeper/issues",

View File

@@ -1,166 +1,136 @@
# ScoreKeeper — Plugin Integration & Event/Command Reference
# Score Keeper - Plugin Integration and Event Wiring
> Analysis for the ScoreKeeper codebase. Scope: how the plugin hooks into the
> Minecraft (Paper) server runtime — event listeners, command registrations,
> scheduled/tick logic, and inter-plugin/API surface — with a table mapping each
> trigger → handler class → effect on score data.
>
> Platform: **Paper** (`io.papermc.paper:paper-api:1.21.7-R0.1-SNAPSHOT`), Java 21,
> Gradle. Main class: `com.majinnaibu.minecraft.plugins.scorekeeper.ScoreKeeperPlugin`.
New Score Keeper contributors should start with
[CONTRIBUTING.md](../CONTRIBUTING.md), which covers architecture, setup, and validation.
This is an optional detailed reference for runtime wiring and companion-plugin
authors, not a second onboarding guide. [domain-score-tracking.md](domain-score-tracking.md)
describes state and [README.md](../README.md) gives full command syntax.
---
## Paper lifecycle
## 1. TL;DR for a new developer
The entry point is
[ScoreKeeperPlugin](../src/main/java/com/majinnaibu/minecraft/plugins/scorekeeper/ScoreKeeperPlugin.java),
declared in [plugin.yml](../src/main/resources/plugin.yml) under the plugin ID
`ScoreKeeper`. Compilation targets Paper `26.2.build.129-stable` on Java 25;
supported server versions are Paper 26.2 and 26.3.
ScoreKeeper is almost entirely **command-driven**. It registers **no Bukkit event
listeners**, declares **no `@EventHandler` methods, no `Listener` implementations,
and calls `getPluginManager().registerEvents(...)` nowhere**. It also schedules
**no timed tasks** (no `BukkitScheduler`/`BukkitRunnable`/tick logic).
| Trigger | Handler / effect |
| --- | --- |
| Plugin enable | Register eight executors, initialize `points`, load scores/archives, check existing runs, schedule synchronous checks every 20 ticks |
| Scheduled check | `checkHighScoreRuns`: finish expired duration runs or runs whose target is reached |
| Plugin disable | Serialize bucket definitions, scores, assignments, active runs/snapshots, and archives to two YAML files |
| Minecraft join/quit/death/kill | No built-in listeners or automatic score awards |
| Companion-plugin API call | Perform requested score/bucket/archive/run operation |
The only things that touch score state are **five console/chat commands**
(`score-get`, `score-add`, `score-subtract`, `score-reset`, `score-archive`).
Score state lives in an **in-memory `HashMap<UUID, Integer>`** and is **not
persisted** — `onEnable`/`onDisable` have `TODO` stubs, so data is lost on restart.
There are no `Listener` implementations, `@EventHandler` methods, custom scoring
events, or event registrations. The scheduler manages runs, not gameplay scoring.
Expired saved runs finish during enable; `until-disabled` runs persist and resume.
There is a **`highscore` / high-score table in the project name and the task
prompt, but no such command or logic exists yet** — it is unimplemented.
## Command wiring
---
Each manifest command is explicitly wired in `onEnable` using `getCommand` and
`setExecutor`. A missing declaration fails startup via `Objects.requireNonNull`.
## 2. Event listeners (Bukkit/Adventure)
Handlers are in [commands/](../src/main/java/com/majinnaibu/minecraft/plugins/scorekeeper/commands/).
**None.** The plugin listens to no server events. Confirmed by absence of any of:
`@EventHandler`, `implements Listener`, `registerEvents(`, `PlayerJoinEvent`,
`PlayerQuitEvent`, `PlayerDeathEvent`, or any other event import/registration.
| Command | Executor | Delegation / effect | Permission |
| --- | --- | --- | --- |
| `score-get` | `ScoreGetCommand` | `getScore`, active bucket, lazy entry creation | None |
| `score-add` | `ScoreAddCommand` | `addScore`, signed integer addition | None |
| `score-subtract` | `ScoreSubtractCommand` | `subtractScore`, signed integer subtraction | None |
| `score-reset` | `ScoreResetCommand` | `resetScore`, active bucket initial value | None |
| `score-archive` | `ScoreArchiveCommand` | `archivePlayerScore`, `archiveBucketScores`, or `archiveAllScores` | `scorekeeper.admin` |
| `score-archive-list` | `ScoreArchiveListCommand` | `getScoreArchives` or `getScoreArchive` | None |
| `score-bucket` | `ScoreBucketCommand` | View/select own bucket, create bucket, switch another/all players | Admin for create/other/all; none for self |
| `score-run` | `ScoreRunCommand` | Start target/timed/manual run, or stop it | `scorekeeper.admin` |
| Server event | Handler | Effect on score data |
|---|---|---|
| PlayerJoin | *none* | none |
| PlayerQuit | *none* | none |
| PlayerDeath | *none* | none |
| (all other Bukkit events) | *none* | none |
| Custom/plugin-injected events | *none* | none |
`scorekeeper.admin` defaults to operators in the manifest. Guards are implemented
inside selected executors, not per-command manifest permission fields. Public API
calls do not enforce sender permissions; the caller must enforce its own policy.
**Implication:** nothing about a player's score changes as a result of gameplay
events (joining, quitting, dying, scoring points in-game, etc.). The only way
score data changes is through the commands in §3.
Named player targets use Paper's `getPlayerExact` and must be online. Players
may omit the optional name to target themselves; non-player senders have no
self context. Console/RCON can use archive `all`/`bucket` forms without a player.
Bucket IDs are case-sensitive even though command keywords such as `all` are not.
---
Parse/validation failures are returned as Adventure usage/error messages.
Handlers consume commands by returning `true`. Score mutation commands rely on
bucket/run reporting instead of unconditional success messages; the default
`none` policy can make a successful mutation silent.
## 3. Command registrations & permissions
## Companion-plugin integration
Commands are declared in `src/main/resources/plugin.yml` (no `aliases`, no
`permissions:` block, and no per-command `permission:` — so **every command is
available to every sender with no permission gating**). Each is wired to an
executor in `ScoreKeeperPlugin.onEnable()`.
Score Keeper declares no plugin dependencies of its own. A companion that requires
it should compile against the matching jar as a provided/compile-only dependency,
and declare `depend: [ScoreKeeper]` in its own Bukkit-style manifest so it loads
after Score Keeper. For optional integration, use `softdepend` and handle absence
or disabled state explicitly.
Argument-resolution idiom shared by every handler:
`boolean rcon = !(sender instanceof Player);` — an RCON caller has no self
context, so the "target = self" shortcut is unavailable and a `<playerName>`
must be supplied.
There is no ServicesManager registration or standalone API module. Obtain the
enabled plugin by ID and check its type, for example during the companion's enable:
`<playerName>` is resolved with `server.getPlayerExact(name)` — an **exact,
case-sensitive lookup of currently-online players only**. Score operations
therefore apply to **online players**, and an unknown/offline name yields a
"Can't find a player with that name" error (except where noted).
```java
Plugin candidate = getServer().getPluginManager().getPlugin("ScoreKeeper");
if (!(candidate instanceof ScoreKeeperPlugin scoreKeeper) || !candidate.isEnabled()) {
getLogger().severe("Score Keeper is required but is not enabled.");
getServer().getPluginManager().disablePlugin(this);
return;
}
```
### Reference table — command → handler class → effect on score data
Imports for this example are `org.bukkit.plugin.Plugin` and
`com.majinnaibu.minecraft.plugins.scorekeeper.ScoreKeeperPlugin`. Keep the
reference for your integration lifecycle, not as a global singleton.
Do not shade a second copy of Score Keeper into the companion jar.
| Trigger (command) | Usage | Handler class | Delegates to | Effect on score data |
|---|---|---|---|---|
| `score-get` | `/score-get [player]` | `ScoreGetCommand` | `ScoreKeeperPlugin.getScore(Player)` → `getPlayerScore` | **Read only.** Returns the player's current score. Side effect: lazily registers the player at `0` if unseen. No persistent change. |
| `score-add` | `/score-add [player] <amount>` | `ScoreAddCommand` | `ScoreKeeperPlugin.addScore(Player,int)` | `score = old + amount` (integer `amount` in `[1..]`). |
| `score-subtract` | `/score-subtract [player] <amount>` | `ScoreSubtractCommand` | `ScoreKeeperPlugin.subtractScore(Player,int)` | `score = old - amount` (can go negative). |
| `score-reset` | `/score-reset [player]` | `ScoreResetCommand` | `ScoreKeeperPlugin.resetScore(Player)` | `score = 0` (writes 0; key created if absent). |
| `score-archive` | `/score-archive [player]` | `ScoreArchiveCommand` | *nothing* | **No state change.** Handler prints `"archive command unimplemented"`. It does **not** call `ScoreKeeperPlugin.archiveScore(...)` — see §5. |
### Public operations
### Command behaviour details
| Area | Methods |
| --- | --- |
| Bucket definition | `createBucket(id, singular, plural, initialValue[, ScoreReporting])`, `getBucket(id)`, `getBuckets()` |
| Active selection | `getPlayerBucket(Player)`, `switchPlayerBucket(Player, id)`, `switchAllPlayers(id)` |
| Score CRUD | `getScore(Player[, id])`, `setScore(Player[, id], score)`, `addScore(Player[, id], amount)`, `subtractScore(Player[, id], amount)`, `resetScore(Player[, id])` |
| Archives | `archivePlayerScore(Player)`, `archiveBucketScores(id)`, `archiveAllScores()`, `getScoreArchives()`, `getScoreArchive(archiveId)` |
| Compatibility wrapper | `archiveScore(Player)` delegates to player archive creation but discards the returned ID |
| Runs | `startTargetScoreRun(id, topN, resetScores, targetScore)`, `startTimedScoreRun(id, topN, resetScores, Duration)`, `startUntilDisabledScoreRun(id, topN, resetScores)`, `stopHighScoreRun(id)`, `hasActiveHighScoreRun(id)` |
| Messaging/logging | `sendMessage(CommandSender, Component)`, `logInfo`, `logWarning`, `logError` |
- **Sender vs. target.** Single-arg form means "operate on the invoking player"
(`split.length == 1` → `targetPlayer = sender`). Two-arg form means
`<playerName> <amount>` (add/subtract) or `<playerName>` (get/reset). For an
RCON sender, the single-arg form is treated as missing a target and prints
usage instead.
- **Amount parsing.** `score-add`/`score-subtract` require an integer
`amount`; a non-integer prints `"amount must be an integer"`.
- **Error/usage messaging.** `echoError` (red) and `echoUsage` (colour-coded)
differ between player and RCON call sites (`/score-add` vs `score-add`).
All handlers `return true` (command handled).
- **Permissions.** None declared → no operator/permission requirement; any
player or RCON can run them.
The bracket notation above describes overloads, not literal Java syntax.
`getBucket` and `getScoreArchive` return null when unknown; mutating/score methods
validate bucket existence and throw `IllegalArgumentException` for invalid
operations. Do not swallow errors or report success after a failure.
Bucket maps and archive snapshots exposed by getters are immutable copies/views.
---
Example explicit-bucket award, with imports for `ScoreReporting` and `Player`:
## 4. Scheduled tasks / tick-based logic
```java
if (scoreKeeper.getBucket("event") == null) {
scoreKeeper.createBucket("event", "point", "points", 0, ScoreReporting.PLAYER);
}
scoreKeeper.addScore(player, "event", 10);
```
**None.** Confirmed by absence of `getScheduler()`, `runTask`,
`BukkitRunnable`, `BukkitTask`, `scheduleSync*`, or any periodic/repeating
logic. ScoreKeeper runs no background or tick-driven work.
Only create a shared bucket if its existing definition meets your integration's
requirements; duplicate creation throws. Explicit-bucket scoring does not switch
the player's active bucket.
---
### Threading and ownership
## 5. Inter-plugin dependencies & API exposure
All calls touching state, players, or reporting must execute on Paper's main
server thread. The plugin's `LinkedHashMap` state and read-modify-write operations
are not synchronized. Marshal asynchronous event/work results to a synchronous
Paper task before calling this API. Score Keeper does not provide Folia/region
scheduler support.
- **Declared dependencies:** plugin.yml has no `depend`, `softdepend`, `load`,
or `load-before` → **no declared inter-plugin coupling**.
- **Build dependency:** the only third-party dependency is
`io.papermc.paper:paper-api` (marked `compileOnly`, and explicitly ignored as a
snapshot by the release plugin). No other plugin/API is referenced.
- **Public API surface.** `ScoreKeeperPlugin` is a plain `JavaPlugin` exposing
`public` methods that other plugins *could* call if they hold a reference:
- `void addScore(Player, int)`
- `void subtractScore(Player, int)`
- `int getScore(Player)`
- `void setScore(Player, int)` — **public but used by no command** (internal
write path; the only writer not reachable via a command).
- `void resetScore(Player)`
- `void archiveScore(Player)` — **public but called by nothing**; it only logs
a warning. The `/score-archive` command does **not** invoke it.
- `void sendMessage(CommandSender, Component)`, `logInfo/logWarning/logError`
- **No formal service registration.** There is no `registerService`/`asService`
(ServiceLoader), no dedicated API artifact, and no `api:` block in plugin.yml.
Exposure is by **public method surface only** — informal and not discoverable
by other plugins.
- **Persistence (unimplemented).** `onEnable` logs a warning that load-from-file
is unimplemented; `onDisable` logs that save-to-file is unimplemented. The
`HashMap<UUID,Integer>` is the sole state store and is **forgotten on restart**.
Do not mutate private maps or write the YAML files from another plugin.
Use the API so reporting, validation, target completion, and snapshots remain
consistent. API calls change in-memory state; durability is deferred until
Score Keeper disables successfully.
---
## Verification
## 6. Lifecycle
| Hook | What it does |
|---|---|
| `onEnable()` | Wires the five `score-*` command executors; logs the "load not implemented" warning and an enable log line. |
| `onDisable()` | Logs the "save not implemented" warning. **All in-memory scores are lost on shutdown.** |
---
## 7. State model (quick reference)
- **Store:** `private HashMap<UUID,Integer> _playerScores` on `ScoreKeeperPlugin`
(one map field for the whole plugin).
- **Keying:** by `Player.getUniqueId()` (UUID), so scores are per-player and
survive name changes *within a single server run*; lost on restart.
- **Lazy init:** any read (including `get`/`score-get`) auto-creates the key at `0`.
- **Writers:** `addScore`, `subtractScore`, `resetScore`, `setScore`, all funneled
through `setPlayerScore(player, value)`.
- **Concurrency:** plain `HashMap`; safe today only because command dispatch
runs on the server's main thread. Not thread-safe for off-thread use.
---
## 8. "Which server trigger causes which state change" — summary
| Trigger | State change |
|---|---|
| `/score-add [player] <amount>` | `_playerScores[uuid] += amount` |
| `/score-subtract [player] <amount>` | `_playerScores[uuid] -= amount` |
| `/score-reset [player]` | `_playerScores[uuid] = 0` |
| `/score-get [player]` | none (reads; lazily registers at 0) |
| `/score-archive [player]` | none (not implemented) |
| Any Minecraft/Bukkit event (join/quit/death/etc.) | **none — no listeners exist** |
| Server tick / scheduled task | **none — no scheduler exists** |
| Server enable | no data change (registration + log only) |
| Server disable | in-memory scores discarded (no persistence) |
| `addScore`/`subtractScore`/`setScore`/`archiveScore` via the public API | same table where called; only reachable by code holding a plugin reference, not by in-game events or commands (except add/subtract/reset which do have commands) |
There is currently no automated plugin harness or real-server test task.
Validate load ordering, command dispatch, messages, run scheduler behavior, and
clean-restart persistence on disposable Paper servers using
[human-tests.md](human-tests.md). Do not assume a successful compilation verifies
companion load order or runtime API compatibility.

View File

@@ -0,0 +1,48 @@
{
"score-keeper": {
"id": "score-keeper",
"title": "Score Keeper",
"description": "A Paper 26.2/26.3 scoring engine with named buckets, custom reporting, shutdown-persisted scores and archives, high-score runs, player commands, and a main-thread API for companion plugins.",
"docId": "Score-Keeper",
"headerImage": null,
"platforms": [
{
"name": "Paper",
"info": "Paper 26.2 and 26.3; Java 25 required. Bukkit and Spigot servers are not supported.",
"links": [
{
"label": "Download on Modrinth",
"url": "https://modrinth.com/plugin/scorekeeper"
}
]
}
],
"image": {
"url": "/projects/score-keeper/logo.png",
"alt": "Score Keeper Minecraft plugin logo",
"width": 1024,
"height": 1024,
"backgroundClassName": "bg-surface"
},
"url": "/projects/score-keeper",
"tags": ["Open-Source", "Game", "Minecraft", "Java"],
"source": {
"type": "github",
"url": "https://github.com/headhunter45/ScoreKeeper"
},
"feedback": {
"type": "github-issues",
"url": "https://github.com/headhunter45/ScoreKeeper/issues"
},
"features": [
"Named score buckets with custom units, initial values, and reporting policies",
"UUID-keyed integer scores with default and per-player bucket selection",
"Player, bucket, and all-bucket archives with score resets",
"Target-score, timed, and manually stopped high-score runs with top-N results",
"Optional pre-run score snapshots and restoration",
"YAML persistence on clean shutdown",
"Player commands and a main-thread API for companion plugins"
],
"technology": ["Java 25", "Paper API", "Adventure", "Gradle", "YAML"]
}
}

View File

@@ -0,0 +1,31 @@
# Score Keeper
Score Keeper is a reusable scoring engine for Paper 26.2 and 26.3. It gives events,
competitions, and companion plugins a shared language for points: named buckets
can have custom singular/plural labels, initial values, reporting policies,
archives, and high-score runs.
The plugin is both a player-facing command system and an extension point.
Administrators can start target-based, timed, or manually stopped score runs,
while other plugins can create buckets, award points, archive results, and build
richer game loops through the public API. Gameplay does not automatically award
scores. Scores, assignments, active runs, and archives persist across clean server
restarts through shutdown saves. Bukkit and Spigot servers are not supported.
Run standings include deterministic tie-breaking, top-N announcements, personal
places, and optional restoration of pre-run scores. Separate archives snapshot
player, bucket, or all-bucket scores and reset the live values.
## Engineering Notes
- Built with Gradle and Java 25 for modern Paper.
- Uses UUID-based player identity and YAML-backed persistence.
- Exposes a main-thread Java API for companion plugins; no service registration or built-in gameplay listeners.
- Has no automated Java test coverage yet; manual pre-release scenarios are documented, with test infrastructure planned.
- Uses the display name "Score Keeper" while retaining `ScoreKeeper` as the repository and plugin identifier.
- Licensed under GNU AGPL v3 or later.
Score get/add/subtract/reset commands currently have no permission checks and can
target online players; archive, bucket administration, and run management use
`scorekeeper.admin`. Saves happen on disable, not every mutation, so crashes may
lose recent state.

114
docs/projects.schema.json Normal file
View File

@@ -0,0 +1,114 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Projects",
"description": "Project metadata keyed by the project route slug.",
"type": "object",
"patternProperties": {
"^[a-z0-9]+(?:-[a-z0-9]+)*$": { "$ref": "#/definitions/project" }
},
"additionalProperties": false,
"definitions": {
"image": {
"type": "object",
"required": ["url", "width", "height"],
"properties": {
"url": {
"type": "string",
"description": "Public asset path or remote image URL. A blank header image URL falls back to image.",
"pattern": "^(\\s*|/[^/].*|https?://.+)$"
},
"alt": { "type": "string" },
"prompt": { "type": "string" },
"name": { "type": "string" },
"width": { "type": "integer", "minimum": 1 },
"height": { "type": "integer", "minimum": 1 },
"backgroundClassName": { "type": "string" }
},
"additionalProperties": false
},
"projectLink": {
"type": "object",
"required": ["url"],
"properties": {
"type": { "type": "string" },
"url": { "type": "string", "pattern": "^(\\s*|https?://.+)$" }
},
"additionalProperties": false
},
"platform": {
"type": "object",
"required": ["name"],
"properties": {
"name": { "type": "string", "pattern": "\\S" },
"info": { "type": "string" },
"links": {
"type": "array",
"items": {
"type": "object",
"required": ["label", "url"],
"properties": {
"label": { "type": "string", "pattern": "\\S" },
"url": {
"type": "string",
"format": "uri",
"pattern": "^https?://.+"
}
},
"additionalProperties": false
}
}
},
"additionalProperties": false
},
"project": {
"type": "object",
"required": ["id", "title", "description", "tags"],
"properties": {
"id": { "type": "string", "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" },
"title": { "type": "string", "pattern": "\\S" },
"description": { "type": "string", "pattern": "\\S" },
"docId": { "type": "string", "minLength": 1 },
"image": { "$ref": "#/definitions/image" },
"headerImage": {
"description": "Optional detail-page logo override. Omit, set to null, or use a blank URL to fall back to image. Listing cards continue to use image.",
"anyOf": [{ "$ref": "#/definitions/image" }, { "type": "null" }]
},
"status": { "type": "string" },
"platforms": {
"type": "array",
"items": { "$ref": "#/definitions/platform" }
},
"url": {
"type": "string",
"pattern": "^/projects/[a-z0-9]+(?:-[a-z0-9]+)*$"
},
"tags": {
"type": "array",
"items": { "type": "string", "minLength": 1 },
"uniqueItems": true
},
"source": {
"allOf": [
{ "$ref": "#/definitions/projectLink" },
{ "required": ["type"] }
]
},
"feedback": { "$ref": "#/definitions/projectLink" },
"repository": {
"type": "string",
"format": "uri",
"pattern": "^https?://.+"
},
"features": {
"type": "array",
"items": { "type": "string", "minLength": 1 }
},
"technology": {
"type": "array",
"items": { "type": "string", "minLength": 1 }
}
},
"additionalProperties": false
}
}
}

View File

@@ -1,18 +1,18 @@
/*
This file is part of ScoreKeeper.
This file is part of Score Keeper.
ScoreKeeper is free software: you can redistribute it and/or modify
Score Keeper is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ScoreKeeper is distributed in the hope that it will be useful,
Score Keeper is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ScoreKeeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
along with Score Keeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
*/
package com.majinnaibu.minecraft.plugins.scorekeeper;

View File

@@ -1,18 +1,18 @@
/*
This file is part of ScoreKeeper.
This file is part of Score Keeper.
ScoreKeeper is free software: you can redistribute it and/or modify
Score Keeper is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ScoreKeeper is distributed in the hope that it will be useful,
Score Keeper is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ScoreKeeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
along with Score Keeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
*/
package com.majinnaibu.minecraft.plugins.scorekeeper;
@@ -56,10 +56,10 @@ public class ScoreKeeperPlugin extends JavaPlugin {
private final Map<String, HighScoreRun> _highScoreRuns = new LinkedHashMap<>();
private final Map<String, ScoreArchive> _scoreArchives = new LinkedHashMap<>();
private String _defaultBucketId = "points";
public final String _logPrefix = "[ScoreKeeper] ";
public final String _logPrefix = "[Score Keeper] ";
public final Component _messagePrefix =
Component.text("[")
.append(Component.text("ScoreKeeper").color(NamedTextColor.AQUA))
.append(Component.text("Score Keeper").color(NamedTextColor.AQUA))
.append(Component.text("] ").color(NamedTextColor.WHITE));
@Override
@@ -103,10 +103,12 @@ public class ScoreKeeperPlugin extends JavaPlugin {
public void onEnable() {
Objects.requireNonNull(getCommand("score-get")).setExecutor(new ScoreGetCommand(this));
Objects.requireNonNull(getCommand("score-add")).setExecutor(new ScoreAddCommand(this));
Objects.requireNonNull(getCommand("score-subtract")).setExecutor(new ScoreSubtractCommand(this));
Objects.requireNonNull(getCommand("score-subtract"))
.setExecutor(new ScoreSubtractCommand(this));
Objects.requireNonNull(getCommand("score-reset")).setExecutor(new ScoreResetCommand(this));
Objects.requireNonNull(getCommand("score-archive")).setExecutor(new ScoreArchiveCommand(this));
Objects.requireNonNull(getCommand("score-archive-list")).setExecutor(new ScoreArchiveListCommand(this));
Objects.requireNonNull(getCommand("score-archive-list"))
.setExecutor(new ScoreArchiveListCommand(this));
Objects.requireNonNull(getCommand("score-bucket")).setExecutor(new ScoreBucketCommand(this));
Objects.requireNonNull(getCommand("score-run")).setExecutor(new ScoreRunCommand(this));
@@ -711,7 +713,8 @@ public class ScoreKeeperPlugin extends JavaPlugin {
} else if (reporting == ScoreReporting.ADMIN) {
logInfo(text);
for (Player recipient : getServer().getOnlinePlayers()) {
if (Objects.requireNonNull(recipient).isOp() || recipient.hasPermission("scorekeeper.admin")) {
if (Objects.requireNonNull(recipient).isOp()
|| recipient.hasPermission("scorekeeper.admin")) {
sendMessage(recipient, message);
}
}

View File

@@ -1,18 +1,18 @@
/*
This file is part of ScoreKeeper.
This file is part of Score Keeper.
ScoreKeeper is free software: you can redistribute it and/or modify
Score Keeper is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ScoreKeeper is distributed in the hope that it will be useful,
Score Keeper is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ScoreKeeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
along with Score Keeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
*/
package com.majinnaibu.minecraft.plugins.scorekeeper;

View File

@@ -1,29 +1,29 @@
/*
This file is part of ScoreKeeper.
This file is part of Score Keeper.
ScoreKeeper is free software: you can redistribute it and/or modify
Score Keeper is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ScoreKeeper is distributed in the hope that it will be useful,
Score Keeper is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ScoreKeeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
along with Score Keeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
*/
package com.majinnaibu.minecraft.plugins.scorekeeper.commands;
import java.util.Objects;
import com.majinnaibu.minecraft.plugins.scorekeeper.ScoreKeeperPlugin;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import java.util.Objects;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
@@ -78,7 +78,8 @@ public class ScoreAddCommand implements CommandExecutor {
}
private void echoError(CommandSender sender, boolean rcon, String string) {
_plugin.sendMessage(sender, Component.text(Objects.requireNonNull(string)).color(NamedTextColor.RED));
_plugin.sendMessage(
sender, Component.text(Objects.requireNonNull(string)).color(NamedTextColor.RED));
}
private void echoUsage(CommandSender sender, boolean rcon) {

View File

@@ -1,29 +1,29 @@
/*
This file is part of ScoreKeeper.
This file is part of Score Keeper.
ScoreKeeper is free software: you can redistribute it and/or modify
Score Keeper is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ScoreKeeper is distributed in the hope that it will be useful,
Score Keeper is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ScoreKeeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
along with Score Keeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
*/
package com.majinnaibu.minecraft.plugins.scorekeeper.commands;
import java.util.Objects;
import com.majinnaibu.minecraft.plugins.scorekeeper.ScoreKeeperPlugin;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import java.util.Objects;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
@@ -70,7 +70,8 @@ public class ScoreArchiveCommand implements CommandExecutor {
}
private void sendError(CommandSender sender, String message) {
_plugin.sendMessage(sender, Component.text(Objects.requireNonNull(message)).color(NamedTextColor.RED));
_plugin.sendMessage(
sender, Component.text(Objects.requireNonNull(message)).color(NamedTextColor.RED));
}
private void sendUsage(CommandSender sender) {

View File

@@ -1,18 +1,18 @@
/*
This file is part of ScoreKeeper.
This file is part of Score Keeper.
ScoreKeeper is free software: you can redistribute it and/or modify
Score Keeper is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ScoreKeeper is distributed in the hope that it will be useful,
Score Keeper is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ScoreKeeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
along with Score Keeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
*/
package com.majinnaibu.minecraft.plugins.scorekeeper.commands;

View File

@@ -1,22 +1,24 @@
/*
This file is part of ScoreKeeper.
This file is part of Score Keeper.
ScoreKeeper is free software: you can redistribute it and/or modify
Score Keeper is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ScoreKeeper is distributed in the hope that it will be useful,
Score Keeper is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ScoreKeeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
along with Score Keeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
*/
package com.majinnaibu.minecraft.plugins.scorekeeper.commands;
import java.util.Objects;
import com.majinnaibu.minecraft.plugins.scorekeeper.ScoreBucket;
import com.majinnaibu.minecraft.plugins.scorekeeper.ScoreKeeperPlugin;
import com.majinnaibu.minecraft.plugins.scorekeeper.ScoreReporting;
@@ -24,8 +26,6 @@ import com.majinnaibu.minecraft.plugins.scorekeeper.ScoreReporting;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import java.util.Objects;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
@@ -123,7 +123,8 @@ public class ScoreBucketCommand implements CommandExecutor {
}
private void sendError(CommandSender sender, String message) {
_plugin.sendMessage(sender, Component.text(Objects.requireNonNull(message)).color(NamedTextColor.RED));
_plugin.sendMessage(
sender, Component.text(Objects.requireNonNull(message)).color(NamedTextColor.RED));
}
private void sendUsage(CommandSender sender) {

View File

@@ -1,29 +1,29 @@
/*
This file is part of ScoreKeeper.
This file is part of Score Keeper.
ScoreKeeper is free software: you can redistribute it and/or modify
Score Keeper is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ScoreKeeper is distributed in the hope that it will be useful,
Score Keeper is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ScoreKeeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
along with Score Keeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
*/
package com.majinnaibu.minecraft.plugins.scorekeeper.commands;
import java.util.Objects;
import com.majinnaibu.minecraft.plugins.scorekeeper.ScoreKeeperPlugin;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import java.util.Objects;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
@@ -86,7 +86,8 @@ public class ScoreGetCommand implements CommandExecutor {
}
private void echoError(CommandSender sender, boolean rcon, String string) {
_plugin.sendMessage(sender, Component.text(Objects.requireNonNull(string)).color(NamedTextColor.RED));
_plugin.sendMessage(
sender, Component.text(Objects.requireNonNull(string)).color(NamedTextColor.RED));
}
private void echoUsage(CommandSender sender, boolean rcon) {

View File

@@ -1,29 +1,29 @@
/*
This file is part of ScoreKeeper.
This file is part of Score Keeper.
ScoreKeeper is free software: you can redistribute it and/or modify
Score Keeper is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ScoreKeeper is distributed in the hope that it will be useful,
Score Keeper is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ScoreKeeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
along with Score Keeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
*/
package com.majinnaibu.minecraft.plugins.scorekeeper.commands;
import java.util.Objects;
import com.majinnaibu.minecraft.plugins.scorekeeper.ScoreKeeperPlugin;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import java.util.Objects;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
@@ -64,7 +64,8 @@ public class ScoreResetCommand implements CommandExecutor {
}
private void echoError(CommandSender sender, boolean rcon, String string) {
_plugin.sendMessage(sender, Component.text(Objects.requireNonNull(string)).color(NamedTextColor.RED));
_plugin.sendMessage(
sender, Component.text(Objects.requireNonNull(string)).color(NamedTextColor.RED));
}
private void echoUsage(CommandSender sender, boolean rcon) {

View File

@@ -1,18 +1,18 @@
/*
This file is part of ScoreKeeper.
This file is part of Score Keeper.
ScoreKeeper is free software: you can redistribute it and/or modify
Score Keeper is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ScoreKeeper is distributed in the hope that it will be useful,
Score Keeper is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ScoreKeeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
along with Score Keeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
*/
package com.majinnaibu.minecraft.plugins.scorekeeper.commands;
@@ -110,7 +110,8 @@ public class ScoreRunCommand implements CommandExecutor {
}
private void sendError(CommandSender sender, String message) {
_plugin.sendMessage(sender, Component.text(Objects.requireNonNull(message)).color(NamedTextColor.RED));
_plugin.sendMessage(
sender, Component.text(Objects.requireNonNull(message)).color(NamedTextColor.RED));
}
private void sendUsage(CommandSender sender) {

View File

@@ -1,29 +1,29 @@
/*
This file is part of ScoreKeeper.
This file is part of Score Keeper.
ScoreKeeper is free software: you can redistribute it and/or modify
Score Keeper is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ScoreKeeper is distributed in the hope that it will be useful,
Score Keeper is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ScoreKeeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
along with Score Keeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
*/
package com.majinnaibu.minecraft.plugins.scorekeeper.commands;
import java.util.Objects;
import com.majinnaibu.minecraft.plugins.scorekeeper.ScoreKeeperPlugin;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import java.util.Objects;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
@@ -78,7 +78,8 @@ public class ScoreSubtractCommand implements CommandExecutor {
}
private void echoError(CommandSender sender, boolean rcon, String string) {
_plugin.sendMessage(sender, Component.text(Objects.requireNonNull(string)).color(NamedTextColor.RED));
_plugin.sendMessage(
sender, Component.text(Objects.requireNonNull(string)).color(NamedTextColor.RED));
}
private void echoUsage(CommandSender sender, boolean rcon) {

View File

@@ -4,10 +4,6 @@ set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
if [[ ! -r "$PROJECT_ROOT/.env" ]]; then
echo "Error: $PROJECT_ROOT/.env is missing or unreadable. Copy .env.example to .env and set its values." >&2
exit 1
fi
load_project_env() {
local env_line env_key env_value first_char last_char
while IFS= read -r env_line || [[ -n "$env_line" ]]; do
@@ -36,23 +32,27 @@ load_project_env() {
fi
done < "$PROJECT_ROOT/.env"
}
load_project_env
# Required env:
# MODRINTH_TOKEN
# MODRINTH_PROJECT_ID (project ID or slug)
# MODRINTH_GAME_VERSIONS (optional comma-separated list; defaults to 1.21 through 1.21.7)
# MODRINTH_LOADERS (optional, comma-separated, default paper)
# MODRINTH_CHANGELOG (optional)
# Optional:
# MODRINTH_DEPENDENCIES (optional JSON array or a single JSON string)
# MODRINTH_FILE (optional path to the jar; defaults to build/libs/*.jar)
if [[ -r "$PROJECT_ROOT/.env" ]]; then
load_project_env
elif [[ -z "${MODRINTH_TOKEN:-}" ]]; then
echo "Error: $PROJECT_ROOT/.env is missing or unreadable and MODRINTH_TOKEN is not set. Copy .env.example to .env and set its values." >&2
exit 1
fi
MODRINTH_TOKEN="${MODRINTH_TOKEN:-}"
MODRINTH_PROJECT_ID="${MODRINTH_PROJECT_ID:-5NYwxysp}"
MODRINTH_VERSION="${MODRINTH_VERSION:-${VERSION:-}}"
if [[ -z "$MODRINTH_VERSION" ]]; then
MODRINTH_VERSION=$(
"$PROJECT_ROOT/gradlew" -q -p "$PROJECT_ROOT" properties --property version \
| sed -n 's/^version: //p'
)
fi
generate_changelog() {
local current_tag previous_tag range commits
current_tag=$(git -C "$PROJECT_ROOT" describe --tags --exact-match HEAD 2>/dev/null || true)
current_tag="${TAG:-$(git -C "$PROJECT_ROOT" describe --tags --exact-match HEAD 2>/dev/null || true)}"
if [[ -n "$current_tag" ]]; then
previous_tag=$(git -C "$PROJECT_ROOT" describe --tags --abbrev=0 "${current_tag}^" 2>/dev/null || true)
range="${previous_tag:+$previous_tag..}$current_tag"
@@ -66,17 +66,19 @@ generate_changelog() {
fi
printf '%s\n\n%s\n' "## What's Changed" "$commits"
}
MODRINTH_CHANGELOG="${MODRINTH_CHANGELOG:-$(generate_changelog)}"
MODRINTH_GAME_VERSIONS="${MODRINTH_GAME_VERSIONS:-26.2,26.3}"
MODRINTH_LOADERS="${MODRINTH_LOADERS:-paper}"
MODRINTH_VERSION_TYPE="${MODRINTH_VERSION_TYPE:-}"
MODRINTH_FILE="${MODRINTH_FILE:-}"
MODRINTH_DEPENDENCIES="${MODRINTH_DEPENDENCIES:-}"
MODRINTH_SYNC_BODY="${MODRINTH_SYNC_BODY:-true}"
MODRINTH_DESCRIPTION_FILE="${MODRINTH_DESCRIPTION_FILE:-$PROJECT_ROOT/docs/modrinth-description.md}"
if [[ ! -f "$MODRINTH_DESCRIPTION_FILE" ]]; then
MODRINTH_DESCRIPTION_FILE="$PROJECT_ROOT/README.md"
fi
MODRINTH_VERSION=$(
"$PROJECT_ROOT/gradlew" -q -p "$PROJECT_ROOT" properties --property version \
| sed -n 's/^version: //p'
)
if [[ -z "$MODRINTH_VERSION" ]]; then
echo "Error: could not determine the project version from Gradle." >&2
exit 1
@@ -92,16 +94,17 @@ case "$MODRINTH_VERSION_TYPE" in
release|beta|alpha) ;;
*) echo "Error: MODRINTH_VERSION_TYPE must be release, beta, or alpha." >&2; exit 1 ;;
esac
MODRINTH_VERSION_NAME="ScoreKeeper $MODRINTH_VERSION"
MODRINTH_VERSION_NAME="Score Keeper $MODRINTH_VERSION"
if [[ -n "$MODRINTH_FILE" && "$MODRINTH_FILE" != /* ]]; then
MODRINTH_FILE="$PROJECT_ROOT/$MODRINTH_FILE"
fi
if [[ -z "$MODRINTH_TOKEN" ]]; then
echo "Error: MODRINTH_TOKEN is not set in $PROJECT_ROOT/.env" >&2
echo "Error: MODRINTH_TOKEN is not set (check $PROJECT_ROOT/.env or environment variable)." >&2
exit 1
fi
if [[ -z "$MODRINTH_FILE" ]]; then
MODRINTH_FILE=$(ls -t "$PROJECT_ROOT"/build/libs/*.jar 2>/dev/null | grep -v -- '-all\.jar$' | head -n1 || true)
fi
@@ -167,3 +170,26 @@ if [[ "$HTTP_STATUS" != 2?? ]]; then
exit 1
fi
printf '%s\n' "$HTTP_BODY" | jq .
if [[ "$MODRINTH_SYNC_BODY" == "true" && -f "$MODRINTH_DESCRIPTION_FILE" ]]; then
echo "Syncing project description to Modrinth from $MODRINTH_DESCRIPTION_FILE..."
BODY_CONTENT=$(cat "$MODRINTH_DESCRIPTION_FILE")
PATCH_DATA=$(jq -cn --arg body "$BODY_CONTENT" '{body: $body}')
PATCH_RESPONSE=$(curl -sS -w $'\n%{http_code}' \
-X PATCH "https://api.modrinth.com/v2/project/$MODRINTH_PROJECT_ID" \
-H "Authorization: $MODRINTH_TOKEN" \
-H "Content-Type: application/json" \
-d "$PATCH_DATA")
PATCH_STATUS="${PATCH_RESPONSE##*$'\n'}"
PATCH_BODY="${PATCH_RESPONSE%$'\n'*}"
if [[ "$PATCH_STATUS" != 2?? ]]; then
echo "Warning: Modrinth project description update returned HTTP $PATCH_STATUS:" >&2
if ! printf '%s\n' "$PATCH_BODY" | jq -r '.description // .error // .' >&2; then
printf '%s\n' "$PATCH_BODY" >&2
fi
else
echo "Successfully updated Modrinth project description."
fi
fi