From fade3b18e0330cf66da0c9f37888d6c9dea44d9d Mon Sep 17 00:00:00 2001 From: jatmn Date: Sun, 6 Dec 2026 12:09:46 -0800 Subject: [PATCH 1/6] Check toolchain and service pins in CI instead of agent prose. AGENTS.md no longer has to repeat the audit expiry, Dependabot wording, or the service-boundary script name. Those facts are enforced by the workflow files and scripts/check-pinned-facts.sh. Co-authored-by: Cursor --- docs/CI.md | 2 +- scripts/check-pinned-facts.sh | 169 ++++++++++++++++++++++ scripts/ci-preflight.sh | 4 +- scripts/dependabot-config-test.sh | 10 +- scripts/public-install-acceptance-test.sh | 2 +- scripts/select-checks-test.sh | 5 +- scripts/select-checks.sh | 6 +- 7 files changed, 182 insertions(+), 16 deletions(-) create mode 100755 scripts/check-pinned-facts.sh diff --git a/docs/CI.md b/docs/CI.md index c5ec1b2a0..b44995bed 100644 --- a/docs/CI.md +++ b/docs/CI.md @@ -22,7 +22,7 @@ commit's checks. New commits and reopened PRs still run affected checks. | Touched surface | Checks | |---|---| -| Documentation or sample configuration | Contracts, plus `runner-tests` for `AGENTS.md` and `docs/CI.md` because the audit-expiry self-check reads them | +| Documentation or sample configuration | Contracts. `docs/CI.md` also runs `runner-tests` because the audit-expiry self-check reads that file for the enforced date | | Frontend | Frontend and the default-feature API checks that embed the generated UI (`api-embed-clippy`, `api-test`, `api-build`); the API built without the UI cannot observe these files | | API or bot | That service, integration, boundaries, formatting, scoped Dylint and supply chain, plus the API, updater and remote database groups for bot changes | | Shared root source or migrations | Core plus bot/API/updater/integration consumers and remote databases | diff --git a/scripts/check-pinned-facts.sh b/scripts/check-pinned-facts.sh new file mode 100755 index 000000000..6bcef2f1b --- /dev/null +++ b/scripts/check-pinned-facts.sh @@ -0,0 +1,169 @@ +#!/usr/bin/env bash +# Executable stand-in for agent-doc claims that are facts about this tree: +# the Rust pin, which process migrates, and production dependency edges. +# Operator manuals are not the source of these facts. +set -euo pipefail + +root="$(cd "$(dirname "$0")/.." && pwd)" + +fail() { + echo "check-pinned-facts: $*" >&2 + exit 1 +} + +section_matches() { + local file="$1" + local section="$2" + local pattern="$3" + awk -v section="$section" ' + $0 == section { grab = 1; next } + grab && /^\[/ { exit } + grab { print } + ' "$file" | grep -Eq -- "$pattern" +} + +require_section() { + local file="$1" + local section="$2" + local pattern="$3" + local message="$4" + section_matches "$file" "$section" "$pattern" || fail "$message" +} + +forbid_section() { + local file="$1" + local section="$2" + local pattern="$3" + local message="$4" + if section_matches "$file" "$section" "$pattern"; then + fail "$message" + fi +} + +impl_body() { + local file="$1" + local name="$2" + awk -v name="$name" ' + $0 ~ "^impl " name " " { grab = 1 } + grab && seen && /^impl / { exit } + grab { print; seen = 1 } + ' "$file" +} + +self_test() { + local tmp impl_file + tmp="$(mktemp)" + cat >"$tmp" <<'EOF' +[dependencies] +anyhow = "1" +[dev-dependencies] +serenity = "1" +jmodguard-runtime = { path = "runtime" } +EOF + if section_matches "$tmp" "[dependencies]" '^serenity[[:space:]]*='; then + fail "self-test: dev-dependencies leaked into [dependencies]" + fi + section_matches "$tmp" "[dev-dependencies]" '^serenity[[:space:]]*=' \ + || fail "self-test: missed serenity in [dev-dependencies]" + if section_matches "$tmp" "[dev-dependencies]" '^jmodguard[[:space:]]*='; then + fail "self-test: jmodguard-runtime matched as jmodguard" + fi + + impl_file="$(mktemp)" + cat >"$impl_file" <<'EOF' +impl BotProcessConfig { + pub fn db_open_options(&self) -> DbOpenOptions { + self.db.open_options(&self.bot, true) + } +} +impl ApiProcessConfig { + pub fn db_open_options(&self) -> DbOpenOptions { + self.db.open_options(&self.bot, false) + } +} +impl DbConfig { + fn open_options(&self, bot: &BotConfig, migrate: bool) -> DbOpenOptions { + DbOpenOptions { migrate, read_only: !migrate } + } +} +EOF + impl_body "$impl_file" BotProcessConfig | grep -Fq 'open_options(&self.bot, true)' \ + || fail "self-test: missed bot migrate flag" + if impl_body "$impl_file" BotProcessConfig | grep -Fq 'open_options(&self.bot, false)'; then + fail "self-test: bot impl included the API flag" + fi + impl_body "$impl_file" ApiProcessConfig | grep -Fq 'open_options(&self.bot, false)' \ + || fail "self-test: missed API migrate flag" + rm -f "$tmp" "$impl_file" +} + +check_tree() { + local channel msrv versions version dockerfile line body + channel="$(awk -F'"' '/^channel = / { print $2; exit }' "$root/rust-toolchain.toml")" + [[ "$channel" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || fail "rust-toolchain channel must be X.Y.Z, found: ${channel:-empty}" + msrv="${channel%.*}" + + versions="$(grep -E '^rust-version = "' "$root/Cargo.toml" || true)" + [[ -n "$versions" ]] || fail "Cargo.toml has no rust-version pin" + while IFS= read -r line; do + version="$(printf '%s\n' "$line" | sed -E 's/.*"([^"]+)".*/\1/')" + [[ "$version" == "$msrv" ]] || fail "Cargo.toml rust-version ${version} must be ${msrv} (from channel ${channel})" + done <<<"$versions" + + for dockerfile in Dockerfile.bot Dockerfile.api; do + line="$(grep -E '^FROM rust:' "$root/$dockerfile" | head -n 1 || true)" + [[ -n "$line" ]] || fail "$dockerfile is missing FROM rust" + case "$line" in + "FROM rust:${channel}-"*) ;; + *) fail "$dockerfile must use rust:${channel}, found: $line" ;; + esac + grep -Fxq 'ENV JMODGUARD_REQUIRE_REMOTE_DB=1' "$root/$dockerfile" \ + || fail "$dockerfile must set JMODGUARD_REQUIRE_REMOTE_DB=1" + done + + body="$(impl_body "$root/src/config.rs" BotProcessConfig)" + [[ "$body" == *'open_options(&self.bot, true)'* ]] \ + || fail "BotProcessConfig::db_open_options must migrate (open_options true)" + [[ "$body" != *'open_options(&self.bot, false)'* ]] \ + || fail "BotProcessConfig::db_open_options must not pass migrate false" + body="$(impl_body "$root/src/config.rs" ApiProcessConfig)" + [[ "$body" == *'open_options(&self.bot, false)'* ]] \ + || fail "ApiProcessConfig::db_open_options must not migrate (open_options false)" + [[ "$body" != *'open_options(&self.bot, true)'* ]] \ + || fail "ApiProcessConfig::db_open_options must not pass migrate true" + + forbid_section "$root/Cargo.toml" "[dependencies]" '^serenity[[:space:]]*=' \ + "root production dependencies must not include serenity" + forbid_section "$root/Cargo.toml" "[dependencies]" '^jmodguard-bot[[:space:]]*=' \ + "root production dependencies must not include jmodguard-bot" + forbid_section "$root/Cargo.toml" "[dependencies]" '^jmodguard-api[[:space:]]*=' \ + "root production dependencies must not include jmodguard-api" + + require_section "$root/crates/bot/Cargo.toml" "[dependencies]" '^serenity[[:space:]]*=' \ + "bot production dependencies must include serenity" + forbid_section "$root/crates/bot/Cargo.toml" "[dependencies]" '^jmodguard-api[[:space:]]*=' \ + "bot production dependencies must not include jmodguard-api" + + forbid_section "$root/crates/api/Cargo.toml" "[dependencies]" '^serenity[[:space:]]*=' \ + "API production dependencies must not include serenity" + forbid_section "$root/crates/api/Cargo.toml" "[dependencies]" '^jmodguard-bot[[:space:]]*=' \ + "API production dependencies must not include jmodguard-bot" + require_section "$root/crates/api/Cargo.toml" "[dependencies]" 'memory-store' \ + "API sessions must keep the tower-sessions memory-store feature" + + forbid_section "$root/crates/runtime/Cargo.toml" "[dependencies]" '^jmodguard[[:space:]]*=' \ + "runtime must not depend on the data crate" + forbid_section "$root/crates/runtime/Cargo.toml" "[dependencies]" '^jmodguard-bot[[:space:]]*=' \ + "runtime must not depend on the bot" + forbid_section "$root/crates/runtime/Cargo.toml" "[dependencies]" '^jmodguard-api[[:space:]]*=' \ + "runtime must not depend on the API" + forbid_section "$root/crates/runtime/Cargo.toml" "[dependencies]" '^serenity[[:space:]]*=' \ + "runtime must not depend on serenity" + + [[ -n "$(awk -F'"' '/^tag = / { print $2; exit }' "$root/dylint.toml")" ]] \ + || fail "dylint.toml must pin a library tag" +} + +self_test +check_tree +echo "check-pinned-facts: ok" diff --git a/scripts/ci-preflight.sh b/scripts/ci-preflight.sh index 01b525ff1..667a1e4b2 100755 --- a/scripts/ci-preflight.sh +++ b/scripts/ci-preflight.sh @@ -390,7 +390,6 @@ if [ "${1:-}" = "--audit-expiry-self-check" ]; then [ -n "$rustsec_expiry" ] || fail 'real audit-expiries must list RUSTSEC-2026-0258' data_lines="$(grep -cE '^RUSTSEC-' "$real_expiries" || true)" [ "$data_lines" = 1 ] || fail 'audit-expiries must contain exactly one advisory line' - grep -F "$rustsec_expiry" "$self_root/AGENTS.md" >/dev/null || fail 'AGENTS.md must document the enforced expiry' grep -F "$rustsec_expiry" "$self_root/docs/CI.md" >/dev/null || fail 'docs/CI.md must document the enforced expiry' grep -F "$rustsec_expiry" "$self_root/.cargo/audit.toml" >/dev/null || fail 'audit.toml must document the enforced expiry' day_before="$(TZ=UTC date -u -d "${rustsec_expiry}T00:00:00Z - 1 day" +%Y-%m-%d)" @@ -1019,6 +1018,9 @@ if should_run boundaries; then fi if should_run contracts; then + echo 'ci-preflight: bash scripts/check-pinned-facts.sh' + bash scripts/check-pinned-facts.sh + echo 'ci-preflight: bash scripts/public-install-acceptance-test.sh' bash scripts/public-install-acceptance-test.sh diff --git a/scripts/dependabot-config-test.sh b/scripts/dependabot-config-test.sh index bd25362f9..c475214f0 100755 --- a/scripts/dependabot-config-test.sh +++ b/scripts/dependabot-config-test.sh @@ -46,7 +46,6 @@ yaml=".github/dependabot.yml" development="development.md" ci="docs/CI.md" deploy="docs/DEPLOY-BUNNY.md" -agents="AGENTS.md" preflight="scripts/ci-preflight.sh" for needle in \ @@ -119,7 +118,7 @@ require_contains "$socket_workflow" 'group: socket-scan-${{ github.ref }}' require_contains "$socket_workflow" "cancel-in-progress: true" # The exact ref-based group above cancels superseded scans. github.sha is valid # in the diff's head binding and must not be banned throughout the workflow. -for doc in AGENTS.md development.md docs/CI.md docs/DEPLOY-BUNNY.md docs/PULLFROG.md; do +for doc in development.md docs/CI.md docs/DEPLOY-BUNNY.md docs/PULLFROG.md; do require_contains "$doc" "SOCKET_SECURITY_API_KEY" require_contains "$doc" "not stored in git." require_contains "$doc" "uploads discovered Cargo and npm manifests outside ignored paths to Socket" @@ -138,7 +137,7 @@ do require_contains "$yaml" "$needle" done -for path in "$development" "$ci" "$deploy" "$agents"; do +for path in "$development" "$ci" "$deploy"; do require_contains "$path" "Dependabot" done @@ -156,15 +155,10 @@ require_contains "$deploy" "standard GitHub-hosted runners" require_contains "$deploy" "Dependabot on self-hosted runners" require_absent "$deploy" "still use GitHub-hosted" require_absent "$deploy" "This repository has no GitHub Actions jobs" -require_contains "$agents" "bash scripts/dependabot-config-test.sh" -require_contains "$agents" "Dependabot on self-hosted runners" -require_contains "$agents" "24 hours" -require_contains "$agents" "no GitHub Actions self-hosted" require_contains "$preflight" "bash scripts/dependabot-config-test.sh" require_contains "$preflight" "Shared selected GitHub Actions check groups" require_contains "$preflight" "Dependabot Updates dynamic workflows are not CI" require_contains "$preflight" "npm audit --prefix tools/eslint --audit-level=high" -require_contains "$agents" "npm audit --prefix tools/eslint --audit-level=high" require_contains "$ci" "npm audit --prefix tools/eslint --audit-level=high" require_contains "$development" "five open version-update PRs per ecosystem" diff --git a/scripts/public-install-acceptance-test.sh b/scripts/public-install-acceptance-test.sh index 114d7cea6..9638598dc 100755 --- a/scripts/public-install-acceptance-test.sh +++ b/scripts/public-install-acceptance-test.sh @@ -263,6 +263,6 @@ require_contains .github/workflows/publish.yml "googleapis/release-please-action require_contains .github/workflows/ci.yml "bash scripts/ci-preflight.sh" require_contains docs/RELEASES.md "Release Please action" require_contains docs/CI.md "bash scripts/publish-image-test.sh" -require_contains AGENTS.md "bash scripts/check-service-boundaries.sh" +require_contains scripts/ci-preflight.sh "bash scripts/check-pinned-facts.sh" echo 'public-install-acceptance-test: ok' diff --git a/scripts/select-checks-test.sh b/scripts/select-checks-test.sh index 8cfcb4482..7029bcd12 100644 --- a/scripts/select-checks-test.sh +++ b/scripts/select-checks-test.sh @@ -48,7 +48,8 @@ all="contracts frontend fmt dylint $api_groups $bot_groups runtime updater core expect "contracts" docs/INSTALL.md expect "contracts" README.md expect "contracts" config.example.toml -expect_each "contracts runner-tests" AGENTS.md docs/CI.md +expect "contracts" AGENTS.md +expect "contracts runner-tests" docs/CI.md # Browser files reach Rust only through the default embed-ui feature, so they # skip the API built without it. A real API change still runs both halves once, # and integration subsumes the standalone default-feature API/bot builds. @@ -83,7 +84,7 @@ expect "contracts remote-database supply-chain" scripts/ci-remote-database.sh expect "contracts boundaries supply-chain" scripts/check-service-boundaries.sh expect_each "contracts pullfrog" \ scripts/pullfrog-command-check.mjs scripts/pullfrog-command-check.test.mjs .github/workflows/pullfrog.yml .github/dependabot.yml -expect_each "contracts" scripts/public-install-acceptance-test.sh scripts/dependabot-config-test.sh .githooks/pre-push scripts/install-git-hooks.sh +expect_each "contracts" scripts/public-install-acceptance-test.sh scripts/dependabot-config-test.sh scripts/check-pinned-facts.sh .githooks/pre-push scripts/install-git-hooks.sh # The runner regression suites follow their own inputs, not application code. expect "contracts runner-tests supply-chain" scripts/ci-ensure-cargo-tool.sh expect "contracts frontend runner-tests" scripts/ci-frontend-node-timeout.sh diff --git a/scripts/select-checks.sh b/scripts/select-checks.sh index bcdcfc97e..d7a567ef2 100644 --- a/scripts/select-checks.sh +++ b/scripts/select-checks.sh @@ -236,8 +236,8 @@ classify() { add runner-tests return ;; - AGENTS.md|docs/CI.md) - # The runner's audit-expiry self-check verifies both documents. + docs/CI.md) + # The audit-expiry self-check reads this file for the enforced date. add runner-tests return ;; @@ -293,7 +293,7 @@ classify() { add boundaries return ;; - scripts/public-install-acceptance-test.sh|scripts/dependabot-config-test.sh|.githooks/*|scripts/install-git-hooks.sh) + scripts/public-install-acceptance-test.sh|scripts/dependabot-config-test.sh|scripts/check-pinned-facts.sh|.githooks/*|scripts/install-git-hooks.sh) add contracts return ;; From 3d2fe415858a2f4f25382a73c309c8b882815fb0 Mon Sep 17 00:00:00 2001 From: jatmn Date: Sun, 6 Dec 2026 12:10:37 -0800 Subject: [PATCH 2/6] Reduce the agent prompt to the repository identity and the local gate. Co-authored-by: Cursor --- .github/copilot-instructions.md | 29 +- AGENTS.md | 577 +------------------------------- 2 files changed, 5 insertions(+), 601 deletions(-) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 584a1b28c..d5756999a 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -1,28 +1,3 @@ -# Copilot code review instructions for jModGuard +# Copilot review notes -Copilot is a backup reviewer here, requested manually only when Sourcery can't review. It is advisory: PR Reviewer and Pullfrog form the merge gate. See `AGENTS.md` for the full contracts. - -## Layout -- `src/`: the shared `jmodguard` data and config crate. `src/db.rs` is the local/remote libSQL pool and data-layer facade, and it runs its own database runtimes. `src/db/` holds bootstrap/migrations, configuration, settings, moderation and tests. `src/db_compat.rs` has remote deadlines and rollback, and `src/tenant.rs` holds tenant stores. -- `crates/bot`: the Discord gateway bot (Serenity). It handles automod, commands, action and nickname workers, and is the only role that migrates. -- `crates/api`: the axum WebUI/API. It never migrates and dispatches through the queue, not the bot token. -- `crates/updater`: the in-app updater. `src/launcher_child.rs` is the launcher child side. -- `crates/runtime`: process primitives (health, cgroup). It must not import root data, Serenity, or bot/API state. -- `crates/integration-tests`: cross-service tests. `migrations/`, `frontend/` and `docs/` round it out. - -## Hard rules (flag any break as P1) -- The bot must always be able to moderate. No change may block or disable bans, kicks, timeouts, deletes or automod enforcement. -- The in-app updater never runs schema migrations. Schema changes use the durable bot/API paired protocol, and recovery after the migration fence is forward-only. -- Never display or estimate host-wide memory; reading MemTotal solely to detect an unbounded cgroup limit is allowed. Use the process's or container's own limits only. -- Keep the service boundaries. Bot and API dependency graphs stay independent, the API never migrates, and API work never takes unscoped queue or moderation access. -- Never run core migrations or defaults on a guild store. Credentials stay in process config, never in catalog rows. - -## Rust conventions -- Code must pass Clippy with `-D warnings`. No `unwrap()`/`expect()` in runtime paths (tests are fine). -- Every behavior change needs a test at the smallest reliable boundary that proves it. - -## How to review -- Stay within the PR's stated scope. Don't ask for unrelated refactors. -- Report only real bugs, contract breaks, security issues, data loss, and missing tests for changed behavior. Skip style nits and formatting. -- Start each finding with a priority: **P1** for a bug, data loss, security issue, or hard-rule break; **P2** for a likely bug or a missing test; **P3** for a minor but real issue. -- Never comment on Release Please PRs (`chore(main): release …`) or on `CHANGELOG.md` / `.release-please-manifest.json` changes. +Report behavioral bugs, data loss, and security issues in the diff. Formatting and service boundaries are enforced in CI. diff --git a/AGENTS.md b/AGENTS.md index 5b1fbb31e..1231507e9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,576 +1,5 @@ -# jModGuard — agent notes +# jModGuard -Contributor-oriented build and design invariants for the public jModGuard repo. -Deploy topology for Bunny: `docs/DEPLOY-BUNNY.md`. Public install: `docs/INSTALL.md`. -Upgrades: `docs/UPGRADE.md`. +Discord moderation bot (`crates/bot`) and dashboard API (`crates/api`) on the shared `jmodguard` library. -## Incremental overhaul - -The first compatible foundation is integrated here. See `docs/OVERHAUL.md` for scope. -The workspace has independent `crates/bot` and `crates/api` services, shared root -`jmodguard` data/configuration and `crates/runtime` process primitives. Do not import the root data crate, Serenity or bot/API state -into runtime. Root data must not depend on either service; production bot and -API dependency graphs must remain independent. Cross-service tests live in -`crates/integration-tests`; API dev-dependencies also exercise the HTTP-to-worker handoff. -The existing bot/API state/config invariants below describe current code; replace them deliberately as their overhaul -slice is implemented, with corresponding regression coverage. - -Owner Administration uses the existing WebUI and API session. -Guild dashboard View as… is a read-only preview -tab on the API. No live provider testing or deployment is part of the current local -implementation. -Bot/API configuration remains available. The current baseline requires a fresh database -or the recognized `jmodguard-core-1` family; see `docs/DATABASE-BASELINE.md`. Preserve -family/version checks before bootstrap writes. Never adopt an unmarked old database. - -The old general message archive and member/user activity collection are retired. -The separate rolling guild-store snapshot records only eligible human messages for -configured edit/delete logs and expires at most 24 hours after original creation. The bounded member directory is a separate -current-membership and retained-ban feature; see `docs/MEMBERS.md`. It never -records general activity. See `docs/LOGGING-DATA.md`. Historical archive tables -and helpers remain removed. Basic reports use the last retained observation, -with explicit gaps and bounded delivery; they never reconstruct Discord history. -When the guild store cannot supply that observation, they use the bounded -process-only memory cache of the same eligible messages (same expiry, no attachment bytes). -Message-edit reports require Discord's `edited_timestamp`; -embed/GIF/unfurl/reply/flag refreshes and the bot's own messages are not edits. Each -report is that one event. Leave logs may use bounded join timestamps already received -with messages. The separate paced directory importer may list the roster; basic -report delivery never does. Ban/unban display may use bounded recent audit -lookup inside report admission; a gateway ban may use the same bounded lookup -under the report concurrency limit after saving its row. Neither establishes -durable case-source identity. -General Serenity message caching stays disabled. Keep selected moderation -records and moderation-plan summaries; routine plan/dry-run/log/delete observations do -not create durable audit rows. Internal retention fields remain transitional with no -collection effect. Unsupported databases are refused without changing application rows. - -Bot and API construct distinct runtime state: `state::BotState` and `web::state::ApiState`. -Keep OAuth/display caches in `web`; keep automod, compiled guild configs, cooldowns, -log-delivery limits and slash synchronization in bot state. The API reads configuration -from the DB directly and maintains only its version observation/read floor. -`BotState` accepts `BotProcessConfig` (no dashboard fields); `ApiState` accepts -`ApiProcessConfig`. Keep the full loader adapter private. Bot parsing/environment -application must not retain OAuth config; API loading must retain its CORS/public-origin -checks. Only the bot config retains a Discord bot token; the API retains OAuth credentials. -Common bot/log settings and DB privileges remain transitional. Production dependencies -are separated by package; the API has no Serenity/Gateway/cache dependency. -Process `db_open_options()` fixes the migration role: bot true, API false. Tracing takes -only `LogConfig`. See `docs/ARCHITECTURE.md`; this is not an OS secret boundary. - -The API admits typed administrative actions and the bot dispatches them; see -`docs/BOT-ACTIONS.md`. Require fresh permissions, page membership and stable request keys. Keep claim identity checks, -monotonic replay fencing, bounded cleanup and direct log-config supersession atomic. -Queue history is operational metadata, separate from retained moderation audit records. -The service-boundary guard rejects unscoped API queue access and API bot-token dispatch. `action_worker` consumes claims once, rechecks fresh bot -membership and actor permissions, and distinguishes failed validation from uncertain -mutation outcomes. Reuse the bot HTTP client; no additional client/cache. One bot task polls and cleans -bounded batches, with skipped missed ticks. Worker limits/timers are bot-only config. Worker completion must use finish_dispatched_bot_action: -local log changes check expiry inside the primary transaction; known remote unban results -may be recorded late. Failed receipts or shutdown must never automatically resend Discord. -Dashboard cancel may clear unstarted (`pending`/`claimed`) work and stuck log-channel -`running`/`uncertain` rows; it must not treat a running unban as never dispatched. - -The bot records its own membership observations; see `docs/ENROLLMENTS.md`. They now -bind queue storage, the nickname outbox and API configuration scope. -Positive repair must stay bounded, use the existing bot HTTP/identity, never fetch a -member roster or infer removal from omissions/errors. The separate Members sync -worker has an explicit paced roster contract; enrollment repair does not use it. -Missing/outage Gateway context -cannot retire an observation. Healthy matching joins write no rows/receipts; resuming a -dormant request in that exact membership is a mutation with recovery receipts. No -configuration version changes on observations. -Only BotProcessConfig loads enrollment repair controls; API ignores their TOML/env values. - -Queue membership changes invalidate old work atomically. Preserve delayed receipt creation -for matching/stale observation no-ops. Dashboard queue callers must use captured -`*_enrolled_*` scope helpers, not guild-ID helpers that resolve membership at execution. -Keep old uncertain outcomes separate from newer membership config writes. Admission is -not success: the browser retains keys after lost responses and exposes receipt states. - -The API uses captured configuration operations; see `docs/CONFIGURATION-SCOPES.md`. -Require fresh Discord permission then primary active membership before guild access. -Loaded configuration supplies a membership token; require it for guild configuration edits -and separately for a selected copy source. Never silently refresh/rebind an old browser edit. -Keep request/target and copy source/destination checks in the mutation transaction; scope -objects confer no user/owner permission. Global targets through guild paths retain the guild -check; explicit guild-0 routes remain independently owner-only. Preserve settings/read floors, -nickname/checksum/version and validate-before-replace semantics. Empty captured settings -patches verify using a primary read without mutation receipts. Ban/unban/log-channel actions -use the queue. Moderation event/ban/statistics GET routes also require loaded page membership -and captured primary reads; see `docs/MODERATION-READS.md`. Keep the API guard against -unscoped moderation helpers. These reads create no receipts or version changes. Web, API, and status reads use a -deferred primary snapshot and do not take the writer lock. A timed-out API write that may still hold that lock releases it with one short rollback, including when the deadline fires during BEGIN and this process does not yet hold the transaction. That release runs on the database runtime, because the remote client sends stream close only when a runtime is current. Do not send that rollback when the provider has already closed the stream. Dropping the database call, including when a caller stops waiting, releases that connection and any writer lock the same way. Individual configuration GET reads also require page -membership and captured primary snapshots, preserving the config-version read floor. Keep -guild/global layers together, badword inheritance and guild-only log-channel mappings; explicit -global context remains owner-only. The WebUI/config-parts bundle verifies membership then -reads those collections in one SQL statement: Bunny Database interactive transactions cannot -survive a per-table Hrana round-trip loop. Targeted rule/command/template reads must not load the -entire configuration bundle. Complete tenant isolation and replica coordination remain separate work. - -The guild-store catalog and `TenantRuntime` now route live isolated tenant data for the -bot and API; see `docs/TENANT-RUNTIME.md` and `docs/GUILD-STORES.md`. Catalog rows remain -nonsecret. Credentials stay in process configuration. Never run core migrations/defaults on a guild -store or adopt a foreign/unmarked schema. `jmodguard-guild-1` is at version 25. Ban recovery uses immutable opaque attempt tags, -never reason-text equality. Keep tags out of case API JSON and human reasons. Identity, -placement and membership checks share the data transaction. A successful snapshot check -never authorizes a later write. -Stable/Nightly image publication uses Release Please plus scheduled GitHub Actions Nightlies; -see `docs/RELEASES.md`. Nightly IDs never enter the Release Please baseline and -must not move `latest`. -Library contracts for membership, cases, history, sources and evidence remain as -documented in their TENANT/CASE pages. Runtime routing, selected-case recording, -authorized serving and live guild erasure are described in `docs/TENANT-RUNTIME.md`. -Identity/placement/membership checks must share the data transaction, including empty/no-op -paths. Keep per-membership edit revisions and closure atomic with mappings; never rebind or -reopen a closed scope automatically. Initial binding is trusted lifecycle work, not -permission checking. A successful snapshot check never authorizes a later write. Cloned -backups can retain the same identity/revision. Persisted core `guild_write_fences` must continue blocking writes and erasure after an upgrade. Bunny credential hot-reload remains pending. - -Version3 adds inactive selected cases/text evidence; see `docs/TENANT-CASES.md`. Reuse -captured scope checks with data; preserve immutable source/payload retry semantics, bounded -record/page inputs and payload-free replay markers after explicit removal. Closed-scope -cleanup must stay bounded and refuse active memberships. Never infer success, fetch arbitrary -evidence URLs, expire cases by age or expose removal without its backend permission. Selected -moderation outcomes now also write guild-store cases; core warn/ban mirrors remain. - -Version4 adds owned append-only case history; see `docs/CASE-HISTORY.md`. Preserve original -facts, stable entry retries and per-case sequence order. Version 25 per-user deletion -requests (`docs/DELETION-REQUESTS.md`) are the only redaction path: one transaction-scoped -grant per case or user, keeping action/outcome/time/source, never a standing exception. Count/byte admission must share the -append transaction; reads page IDs and bound single payloads. Parent removal/closed purge -must remove owned history atomically without foreign-key PRAGMA reliance. Budgets are trusted -explicit inputs; no new runtime defaults, permissions or automatic effective-outcome fold. - -Version5 adds explicit application/audit source associations; see `docs/CASE-SOURCES.md`. -Require an already-bound anchor and reject conflicts; never infer matches or merge cases. -Preserve original facts and both source replay keys after removal, including late explicit -links to removed parents. Closed cleanup removes owned keys atomically. Bot-owned -Ban/Unban/Kick now link Discord audit entries from the same process dispatch using that -application identity. Unmarked gateway cases and foreign audit actions other than Ban/Unban stay -application-only; foreign Ban/Unban audit entries use their exact Discord audit ID as source. -Deferred matched pairs stay quarantined for that same 30s/4096 window so a later -same-subject dispatch cannot reuse those halves; expired pending links stay application-only. - -Version6 adds the inactive evidence ownership journal; see `docs/CASE-EVIDENCE.md`. -Reserve before object writes, preserve stable identity/byte admission, and never acknowledge -capture settlement while a write can still arrive. Removal cancels/hides metadata immediately; -closed cancellation is batched. Parent purge refuses unacknowledged evidence. Jobs are snapshots, -not leases or provider proof. Authorized serving of available objects is now -implemented; exact-image spam retains hash-only evidence. The API serves authorized journal-available objects -and does not perform that Discord re-fetch. -Private evidence and operator-managed backup resources must remain separate. - -The opt-in Unix local evidence backend uses real bounded streaming and durable receipts; -see `docs/LOCAL-EVIDENCE.md`. Hold its stable OS resource lock through I/O and SQL settlement, -even if the async waiter is cancelled. Reload exact journal identity, never accept raw object -keys or retry an existing reservation's source. Keep the evidence root private/dedicated; -only verified file absence can acknowledge cleanup. Local advisory locks require cooperating -writers and trusted parents; they do not establish remote PUT completion or restore fencing. -Bot and API open this backend through tenant runtime for authorized serving of available -objects. Exact-image spam retains hash-only evidence; the API does not perform that Discord re-fetch. - -The opt-in Bunny evidence adapter uses guild schema7 single-use attempts and durable201 -acceptance before readback/settlement; see `docs/BUNNY-EVIDENCE.md`. Preserve immutable scoped -binding, checksum scrubbing and blocked unresolved PUTs. Never use timeout/early404/matching -bytes as acceptance, retry a PUT, follow redirects or accept arbitrary endpoints. Resource -markers do not prove zone privacy; operator checks, provider resolution and runtime authority -remain before activation. Core is at migration 0020. Local HTTP/SQL fixtures -must not be reported as live Bunny proof or measured resource usage. - -The attachment and repeated-text rules now use bounded Gateway exact-image and -exact-trimmed-text paths, in test or delete-and-ban mode; see `docs/IMAGE-SPAM.md`. -Never restore the count-only trigger or route matches into the generic punishment -executor. Exact image spam also recognizes matching image attachment metadata -in two channels within 10 seconds (bounded by the rule window), using the same -rule scope and action. Require an exact common distinct-hash set for byte matches -or exact trimmed text across channels. Preserve original observation time, -invalidation and replay guards, and work and metadata bounds without a background -task queue. Test reports are Discord -logs only, with no SQL cases. Enforcement rechecks membership/exemptions, deletes -matched messages and bans with truthful separate outcomes. Automod bans use -the saved Discord deletion window and sweep the matching tracked Gateway IDs -across channels. Enforcement records selected case text (hashes, message IDs or -trimmed excerpts). Exact-image spam retains hashes and safe case metadata, with -no attachment byte capture. Operator-managed guild-local known-bad digests use the existing -configuration version and bot writer control path. Process image budgets belong -only to bot config. -Owner-selected image updates use the existing WebUI/API; see `docs/BUNNY-UPDATES.md`. -Core or guild schema changes require the durable bot/API paired protocol. Preserve -the existing update-control tables/meta across future migrations, exact runtime schema -labels, separate migration-origin metadata, and selected-source protocol-3 launcher -capability/minimum labels. Bump launcher capability for updater fixes; raise the -application minimum only for a required dependency. Enforce the minimum using the -executing launcher, never historical installed metadata. Launchers must read durable selections -before spawning applications; maintenance OAuth control must not construct ApiState or -open tenant stores. After the irreversible migration fence, recovery is forward-only. -One container per role is required; heartbeat expiry never proves a child stopped. -Public installation requires no private ops repository. AWS is EC2 plus SQLite or -libSQL, not RDS. See `docs/INSTALL.md`. - -## Commands - -Before a local default-feature API build, run `npm ci --ignore-scripts --prefix tools/webui` -and `npm run build --prefix tools/webui`. Rebuild after frontend/build-input changes. -Generated assets and third-party source must not be committed. Local preflight -and publication build these assets automatically. - -For launcher review commands with a 120-second cap, run these as two separate -commands from the repository root. Give the build its own budget and let it -finish before running another Cargo command against the same target directory. - -```bash -mkdir -p .tmp && bash crates/updater/review-launcher-tests.sh build > .tmp/launcher-harness.path -bash crates/updater/review-launcher-tests.sh run "$(cat .tmp/launcher-harness.path)" .tmp/launcher-review.log -``` - -The timed step runs the compiled harness on four threads and streams panics, -including test names, to the console and the log as they happen. Its 110-second -deadline covers the harness and log streaming. Git ignores the files under `.tmp/`. - -For ordinary PRs, the local gate before pushing is focused: the regression for the -changed behavior, the tests of the code you edited (`cargo test -p ` -or the relevant Node test file), `cargo fmt --check`, and Clippy `-D warnings` for -each changed package. Then push and let **CI passed** run the complete affected -plan; it is the merge gate. Record commands, results, and simulated boundaries in -the PR. See `development.md` for examples. -Do not run `bash scripts/ci-preflight.sh --affected` as a routine pre-push step. -CI runs the selected groups as parallel jobs in about 10 minutes; the script runs -the same groups one after another on one machine, which takes about 30 minutes -or more when shared source or the bot changes. It always checks the whole diff -since the base, so rerunning it after a follow-up commit repeats work for code -that did not change. Use it only to reproduce a CI failure locally or when CI -cannot run. -After a follow-up edit (for example, a review repair), rerun only the tests and -lints for the code that edit touched, push, and let CI recheck the PR. Do not -repeat broad validation for each edit, commit, or push. -Run the full Linux preflight (`bash scripts/ci-preflight.sh`, no `--only`) before -submitting changes to CI orchestration, toolchains, workspace-wide dependency/build -configuration, or when affected scope cannot be established; `--affected` selects -it by itself for CI orchestration and unclassified paths. It also remains -available for an explicit complete check; see `docs/CI.md`. Do not run it for an -ordinary change. -The Publish workflow calls the same checks before publishing verified images; an -ordinary main push may instead reuse its merged PR's successful CI run on the identical -tree (`scripts/reuse-pr-validation.sh`, see `docs/CI.md`). Pullfrog -retains its owner-command workflow (`docs/PULLFROG.md`); Socket Security remains -a separate manifest scan (`.github/workflows/socket.yml`). Set the -repository Actions secret `SOCKET_SECURITY_API_KEY` to a Socket API key before -relying on the scan. A missing secret skips the scan and does not fail the job, and the key is not stored in git. -The scan uploads discovered Cargo and npm manifests outside ignored paths to Socket, including workspace and member `Cargo.toml` files, `Cargo.lock`, and `tools/eslint/package.json` and its lockfile. It may comment on a pull request with the GitHub Actions token. -A new blocking alert can fail this check only when Socket compares a pull request change that touches a supported manifest. Push and full-report scans do not fail for alerts. Socket API errors do not fail this check. The CI passed check remains the merge gate. -After enabling the key, let a scan run on `main` before relying on pull request comparisons; without a main baseline, Socket may treat existing dependencies as newly added. - -```bash -bash scripts/ci-preflight.sh --affected # reproduce CI's selected groups locally (serial, slow) -bash scripts/ci-preflight.sh # full suite -# For a PR whose base is not main: -# bash scripts/ci-preflight.sh --affected --base origin/ -# Optional local hooks: staged whitespace at commit, contracts at push. -# Worktree-local core.hooksPath (.githooks); does not chain previous hook dirs: -# bash scripts/install-git-hooks.sh -# bash scripts/install-git-hooks.sh --base origin/ -``` - -The full script runs lockfile verification, `cargo fmt --check`, -`bash scripts/dylint-test.sh` and `bash scripts/dylint.sh` (the Trail of Bits -general lints pinned in `dylint.toml`), -whitespace `git diff --check`, the publisher/release contract tests -(`bash scripts/publish-image-test.sh`), Clippy `-D warnings` on -`--all-targets` (plus API `--no-default-features --all-targets`), workspace and -no-default-features API tests, service boundaries (`bash scripts/check-service-boundaries.sh`), public-install acceptance -(`bash scripts/public-install-acceptance-test.sh`), the Dependabot config contract -(`bash scripts/dependabot-config-test.sh`), host ESLint for the browser pages -(`bash scripts/require-host-eslint-node.sh`, then `npm ci --ignore-scripts --prefix tools/eslint`, -then `npm audit --prefix tools/eslint --audit-level=high`, -then `bash tools/eslint-web-selftest.sh`; Node `^20.19.0`, `^22.13.0`, or `>=24` per -`tools/eslint/package.json` `engines`), -frontend Node tests, -independent `jmodguard-bot` / `jmodguard-api` builds, then `dual_process_smoke` -with `--ignored` (that test launches those binaries; the ordinary -workspace run already covers the two in-process cases), the API build without default features, -`cargo deny check bans licenses sources`, and -`cargo audit` (fail-closed when `JMODGUARD_AUDIT_FAIL_CLOSED=1`; pull requests -and ordinary main pushes ignore reported CVE advisories but still fail when -`cargo audit` cannot run). `npm audit --prefix tools/eslint --audit-level=high` -always fails the `frontend` group on a high or critical advisory and on an -advisory-endpoint failure. There is no fail-open switch for cargo-audit; the only -cargo-audit ignore is `RUSTSEC-2026-0258` in `.cargo/audit.toml` (see #349). -Its UTC expiry is in `.cargo/audit-expiries` (2027-04-15); every ignored -advisory needs an expiry line there. Any other unfixable transitive advisory is -handled by pinning or dropping that package. GitHub-hosted Dependabot Updates dynamic workflows -are not CI; do not add `.github/workflows` for them. Keep **Dependabot on self-hosted runners** disabled. This repository has no GitHub Actions self-hosted -runners; otherwise jobs queue on a `dependabot` label and GitHub cancels -them after 24 hours. Do not register leftover Proxmox GHA runners or label -any runner `dependabot`. -Remote libSQL tests stay in the GitHub Actions `remote-database` job. - -```bash -# or: ./scripts/smoke-dual-process.sh -``` - -Local dual-process: - -```bash -cargo run -p jmodguard-bot # migrates DB; Discord gateway -cargo run -p jmodguard-api # waits ~30s locally / ~6m remote for bot migrate, then serves HTTP -``` - -## Test quality and regression evidence - -Before implementing a fix, identify the accepted behavior, a credible failure, -and an independent expected result. Extend existing cases where useful. For -regressions, demonstrate failure before the fix and success afterward when feasible; -confirm the failure reaches the intended assertion rather than unrelated setup. - -Use the smallest reliable test boundary for that failure, adding broader evidence -when the risk crosses components. State which dependencies and processes are real: -two service states in one process do not prove executable startup; a Node VM with a -simulated DOM does not prove browser behavior; local SQLite or HTTP fixtures do not -prove remote libSQL, Discord, or Bunny acceptance. Exercise the actual production -owner rather than having a mock supply the effect the test claims to verify. - -Preserve useful unit, integration, static-boundary, and smoke tests. Before removing -or consolidating coverage, identify the exact remaining cases, assertions, and CI -routes, or explain which requirement is obsolete. Shared or parameterized cases can -protect several entry points; neither test counts nor an E2E-only policy is the goal. -Follow the local validation policy and relevant separate remote-database gates above; -report unrun checks and simulated boundaries explicitly. These principles do not -authorize live provider calls or require a Codex skill to contribute. - -## Version pins (verified) - -- Dylint **6.4.0** — `dylint.toml` pins selected `examples/general` lints at tag `v6.4.0`. GitHub Actions sets `JMODGUARD_CI_PREFIX` to `$HOME/.cache/jmodguard-ci` in `scripts/ci-setup.sh` and caches that tree for pinned dylint, deny, and audit tools plus prebuilt lint libraries. `scripts/dylint.sh` uses `$JMODGUARD_CI_PREFIX/dylint-6.4.0` when `cargo install --list --root` shows 6.4.0 for both `cargo-dylint` and `dylint-link`, and prebuilt libs under `$JMODGUARD_CI_PREFIX/dylint-libs/` when the key matches and `cargo dylint --help` lists `--no-metadata`; local preflight defaults the same prefix under `$HOME/.cache/jmodguard-ci` when unset. `scripts/ci-dylint-libs.sh` publishes that pinned layout (tools from the dylint install root, prebuilt libs from the metadata build under the library key `dylint.sh` records before building) after each dylint run, so hosted cache hits skip the per-run install and library build; it fails the run, writing nothing, instead of leaving an incomplete layout for the cache to save, and it is the only writer of `dylint-libs`, which `dylint.sh` only reads. Otherwise it installs from source and builds from metadata, then runs `cargo check --all-targets` for the affected packages selected by GitHub Actions (the full workspace for local preflight and global changes) under **nightly-2026-08-20** (the lint libraries' toolchain at that tag). Clippy, `cargo test`, and image builds still use **1.100.0** from `rust-toolchain.toml`. -- Rust **1.100.0** — `rust-toolchain.toml`, the CI toolchain, and - `Dockerfile.{bot,api}` (`rust:1.100.0-trixie` linux/amd64 digest) - must stay aligned. `Cargo.toml` `rust-version = "1.100"`. Do not float the CI toolchain on `stable`. CI and image publishing use - GitHub Actions; see `docs/CI.md`. Keep CI workflow changes aligned with `docs/CI.md`. -- serenity **0.12.5** — see `docs/RESEARCH.md` for the breaking 0.12.5 API - changes (EventHandler signatures, `!Send` CacheRef, Timestamp newtype, - `CommandInteraction` rename, `GuildId::set_commands`). -- libsql version requirement in [Cargo.toml](Cargo.toml) and resolved version - in [Cargo.lock](Cargo.lock) (`core`, `remote`; remote HTTPS uses in-tree - rustls 0.23 with libsql's `tls` feature disabled; `libsql-sqlite3-parser` is - git-patched from branch `vendor/libsql-sqlite3-parser-0.13.1` (rev - `f2391d6`) for GHSA-8m95-fffc-h4c5; CI/Docker `cargo fetch` uses - `GITHUB_TOKEN`), - axum 0.8, tower-sessions 0.14, reqwest 0.13, edition 2024. - -## Invariants to respect - -- Never hold a serenity cache ref (`cache.guild()`, `cache.user()`) across - `.await` — clone owned data first (CacheRef is `!Send`). -- `Db::with_conn` closures are `Send + 'static`: pass owned `String`s, never - borrowed `&str`. -- Automod state must stay bounded: prune buckets, keep lookups O(1) - per-message (per-(guild,user) buckets), no full-map scans. -- All user-visible strings flow through the template renderer - (`src/templates.rs`) — no hardcoded chat messages in behaviors. -- Config writers bump durable `config_version` and replace its revision token - in the DB layer (same - transaction as the write); bot call sites still call `app.invalidate_configs()` - for same-process freshness. API writers need no compiled-cache invalidation; DB writes - advance their read floor. Both bot and API poll `config_version` for - cross-process invalidation. Command registry writers (commands table / - command copies) also bump `slash_registry_version` and replace its revision - token; the bot peeks that - every tick (independently of `config_version`) and re-syncs Discord slash - commands for cached guilds when it advances, committing the observed - version only after a successful sync pass (failed guilds retry next poll; - retries are limited to the failure set so one bad guild cannot re-POST all - guilds every tick). Empty guild cache defers without invalidating. A failed - guild that leaves the cache keeps the observation pending; retry it when it - returns, then commit only after every failed guild syncs successfully. - `BotState::new` primes both version baselines; `ApiState::new` primes its config - observation. The first poll has no unobserved window (never use a “skip first - observation” sentinel). Serialize API observation/primary reconciliation and preserve - the DB write-generation check against concurrent local writes. -- Runtime moderation writers (events/warns/bans) must **not** bump - `config_version`. -- Global WebUI routes (`guild_id=0`) and body `scope: "global"` require - `bot.owner_id` == logged-in user. Owner and administration routes that only - check that identity use the session user id and do not fetch the Discord - guild list. -- Guild-scoped WebUI authorization (`guild_scope` for real guild ids) always - checks a session/token-bound successful Discord guild snapshot before `can_manage` - (#653): reused up to `GUILD_AUTH_CACHE_TTL` (4 min), refreshed in the background - (one request per login) after about 2 min, at most `GUILD_AUTH_MAX_STALE` (5 min) - only on rate limits, then fail closed. The bot records gateway role, member and - owner changes as `meta` access marks under a monotonic `access_epoch` - (`src/db/access_marks.rs`); a snapshot whose epoch predates a mark for that guild, - or for that user in it, is refetched before use, and an unreadable mark denies. - Callers pass the guilds they decide on (`require_auth_for_guilds`). Keep the bot's - mark retention longer than `GUILD_AUTH_MAX_STALE`. The guild display cache is - **display-only** (`/api/me`). While Discord is rate-limiting that user, display - may keep serving the last good list. Never authorize mutations from the display - cache (post-demotion access window). -- `AuthCtx` from `guild_scope(0)` is the session owner only and has no guild - list. Any secondary Discord guild check (e.g. `copy_config` source) must use - `authorize_manage_guild` / `require_auth_for_guilds` naming that guild — never `auth.can_manage` - on that context. -- WebUI access roles (`guild_tenant_settings.access_roles`) map Discord roles to - `dashboard` (read-only), `moderator` (dashboard plus deletion requests) or - `settings` for one guild. Deletion requests also admit Discord moderation - permissions (`MODERATOR_BITS`) for that section only; the bot rechecks. `guild_scope` stays Manage - Server; a route opts a lower level in with `guild_scope_at` / `authorize_guild`. - Command edits (plans can grant roles), copy, member-sync actions, case notes, - case removal, role mappings, global and owner routes never accept a role level. Roles come from the user's OAuth token - (`guilds.members.read`), reused at most `MEMBER_ROLES_TTL` or until a newer access - mark, and fail closed. The - bot independently accepts a settings role only for single-guild configuration - ops (`settings_role_scope`) and log-channel actions, from its own member data. -- Badword delete is exact-scope: guild admins delete only their guild's rows; - global rows require owner. All denials return the same `"badword not found"` - (never distinguish missing / cross-guild / non-owner global). -- Badwords copy is **validate-then-replace**: build the enforceable replacement - set first; only then DELETE destination and INSERT. If the source has rows - but none compile, **refuse** (error) and leave destination unchanged — never - DELETE-then-filter. Empty source clears destination (intentional). - `compile_user_regex` is the single gate for add / copy / cache load / tester. -- Select service packages explicitly: `-p jmodguard-bot` or `-p jmodguard-api`. - API default `embed-ui` includes built `dist/frontend/` for local use; API - `--no-default-features` builds JSON/OAuth for Bunny. There is no root `web` feature. - Keep embedding paths relative to the new API source. Bot never needs dashboard features. - Bare Cargo commands select all workspace packages; production builds must use `-p`. -- Sessions use `MemoryStore` intentionally for a **single** API process; lost on - restart. Cookie name is `jmodguard_session` (Magic Container sticky - sessions must use that name). Shared session store is a future - multi-replica concern. Discord - OAuth CSRF (`state`) and `return_to` are browser cookies so a restart - between `/login` and `/oauth/callback` does not fail the handshake. - Those cookies are host-only on `web.base_url`; a split-origin SPA still - sends the user through that hostname for login and callback. - Successful `/oauth/callback` rotates the session id. API JSON responses - set `Cache-Control: private, no-store`, `CDN-Cache-Control: no-store`, - and `Vary: Cookie`. The SPA bootstraps with `POST /api/me` so a CDN that - cached `GET /api/me` cannot keep a signed-in workspace without a live - session. It loads guild configuration with `POST /api/guilds/{id}/config` - so a cached GET settings document cannot populate a writable UI. It reads - bot-action receipts with `POST /api/guilds/{id}/actions` and one log-channel - mapping with `POST /api/guilds/{id}/logchannels/{event}` so a cached GET - cannot leave a finished log-channel save marked queued. Dashboard - counts, the audit log, bans, case lists, a case, and its evidence list - use the same POST read. Case history stays GET because POST on that - path adds a note. Discord - snowflake fields on the WebUI (log channels, rule/command allowlists, - case-removal roles, plan role steps) stay decimal strings — never JS - `Number`. Bunny API-path edge rules must also **Override Cache Time = 0** - (plus Bypass Perma-Cache); Bypass Perma-Cache alone is not enough. -- Cross-origin CDN SPA is not the Bunny topology. Bunny serves `frontend/` - from Storage and proxies `/api`, `/login`, `/oauth`, `/privacy`, `/terms`, - and `/api/legal/style.css` to a private API container (same origin; no CORS). - `web.cors_origins` / `JMODGUARD_CORS_ORIGINS` exist only for a split-origin - experiment. - `https` `web.base_url` is the public CDN hostname. CORS validation - runs through `ApiProcessConfig::load` only. A public bind (`0.0.0.0`) must also pass - `validate_public_base_url` (`JMODGUARD_WEB_BASE_URL` https, not localhost). - Operators must set the CDN origin themselves; Magic Container hostnames - are not a stable class this check can reject. -- Container images set `JMODGUARD_REQUIRE_REMOTE_DB=1`. Missing remote DB - credentials must fail startup, not open local SQLite. Unset it only for an - intentional local-SQLite container run. Runtime user is UID 10001. Env - `JMODGUARD_DB_POOL_SIZE` (minimum 2) overrides `db.pool_size` when set - (environment wins over `config.toml`, same as other `JMODGUARD_*` keys). - Container deploys typically have no toml, so set the env var there. -- Bot `JMODGUARD_HEALTH_BIND` (images: `0.0.0.0:8080`) and API `GET`/`HEAD` - `/health` are unauthenticated process liveness probes (`ok`, no database). - Bind and accept them **before** opening the database. On the API public - bind, only `/health` returns 200 until axum takes over (database open, - ApiState primary-version prime, router build); `/api` returns JSON 503 - `{"error":"not ready"}` and `Retry-After`, and `/login` / `/oauth` return - HTML 503 that refreshes in place. Do not put session middleware on - `/health`. If the env var is set, bind failure is fatal. -- Discord snowflake IDs on the WebUI wire are **strings** (never JS `Number`). - Audit-event `data` blobs stringify integers above JS `Number.MAX_SAFE_INTEGER` - at write and on read (legacy rows). `WarnRow` / `BanRow` / - `EventRow` / `BadwordView` snowflake fields use the same string serde. -- Bot nickname: WebUI empty field, `!setname` with no args / `clear` / `-`, and - `/setname` with the optional `name` omitted all clear the Discord nickname and - persist `bot_name=""`. Settings and a nickname outbox row commit atomically with a - random request ID, captured nickname and current membership ID. Only the bot drains - it, checking the stored request before/after a bounded own-member Discord read. - Acknowledgment/retry/failure must match the complete request and active membership. - Never adopt old or unbound jobs on rejoin. A fresh save or explicit Re-sync submits - replacement work; missing enrollment leaves it dormant. Matching observations may - resume only same-membership dormant work, preserving terminal errors and healthy - no-op receipt behavior. Retirement/replacement invalidates jobs atomically; missing - Gateway context must not mutate jobs through a separate guild-only lifecycle helper. - No initial nickname edit is created on join. Nicknames remain guild-only. Final - DB checks cannot recall a Discord request already sent. One bot process holds - the writer lease; the API opens the database read-only and sends changes to - that process. A replacement does not act until it holds the lease. -- `guild_settings` rows are **partial overrides** (field-level merge: guild → - global → config terminal defaults from `bot.default_prefix` / - `bot.retention_days`). Joining a server does **not** insert a settings row. - `!prefix` / `!setname` / WebUI settings patch only the changed fields. - WebUI/API `null` on a field clears that override (inherit parent); omitted - fields are left unchanged (`de_settings_patch_field` — default Option nesting - would treat JSON `null` as omitted). Empty prefix in the WebUI - clears an existing override (`null`); empty bot nickname still means - clear-to-empty. - Empty prefix values are rejected by `patch_settings`. Bot migrate-open - rewrites legacy settings blobs (including global) to parent-relative - overrides without deleting ambiguous complete default blobs, clears corrupt JSON, - and bumps `config_version` when rows change. Runtime reads ignore corrupt rows - so inheritance remains available, but durable repair is bot-owned; restart the - bot to run it. Heal is skipped on bot open when - `meta.settings_heal_generation` + `meta.settings_heal_checksum` match the - current `guild_settings` table (fast-path; checksum is a stable FNV-1a so - bot and API agree across process restarts); bump `SETTINGS_HEAL_GENERATION` - in code when heal logic or the checksum algorithm changes to force one full - re-pass. Every committed `guild_settings` mutation (patch, copy settings, - test upsert, heal) calls - `refresh_settings_heal_checksum_conn` so the fast-path stays accurate. -- The historical retention field remains internal, with no live collection or purge - task and no UI/API control. `bot.retention_days` / `bot.default_prefix` are synced - into durable `meta.settings_terminal_defaults` on bot migrate-open (bot is - authority) and read from that meta row on every settings resolve (not cached - at process open) as the final fallback when neither guild nor global sets a - field — shared by `get_settings` / config cache so bot and - API cannot diverge. The API refuses to open until that meta row and the - bot-written bootstrap-complete marker exist (start the bot first). -- Cross-process config lag up to `config_poll_secs` after a successful baseline - is expected (not a bug). -- Log channel IDs are Discord-guild-scoped and are **not** copied between - servers (copy skips them with `skipped_logchannels`). -- Log files are per-process: `jmodguard-bot.log` / `jmodguard-api.log` under - `log.directory`. -- Slash registration: `GuildId::set_commands(http, Vec)`, - responses via `Builder::execute` (`use serenity::builder::Builder;`). - -## Layout - -``` -src/lib.rs shared library -crates/bot/src/main.rs -crates/api/src/main.rs -src/config.rs typed bot/API config loaders + shared env/DB selection -src/db.rs local/remote libSQL pool + public data-layer facade -src/db/bootstrap.rs migrations/startup fencing/versioning/settings heal -src/db/configuration.rs config CRUD + resolved snapshots -src/db/settings.rs inherited settings reads/writes -src/db/nickname_jobs.rs durable Discord nickname reconciliation jobs -src/db/bot_actions.rs action queue storage -src/bot_actions.rs typed action payloads and storage limits -crates/bot/src/action_worker.rs bot dispatch library (worker parameters in bot_actions) -src/db/moderation.rs selected moderation records and statistics -src/db/tests.rs database unit and regression tests -src/db_compat.rs synchronous facade + remote deadlines/rollback -src/remote_https.rs rustls 0.23 HTTPS connector for remote libSQL (hyper 0.14) -crates/bot/src/discord.rs Discord REST helpers (nickname retries) -crates/bot/src/nickname_worker.rs membership/request-checked nickname dispatch -crates/runtime/src/health.rs process-local GET/HEAD /health listener (bot; API bind until axum) -src/defaults.rs seeded rules/commands/templates -src/types.rs serde models (RuleDef/CommandDef/Behavior/PlanStep) -crates/bot/src/state.rs BotState + compiled config cache + version poll -crates/api/src/web/state.rs ApiState + config read observation -crates/api/src/web/oauth.rs dashboard OAuth client and identity models -crates/bot/src/automod.rs rule engine + action executor -crates/bot/src/handlers.rs gateway events -crates/bot/src/commands/ engine, behaviors, plans -crates/api/src/web/ axum API + OAuth (API embed-ui serves built dist/frontend/ locally) -frontend/ admin SPA (Bunny Storage/CDN from public artifacts; local: embedded in API; Mantine bundled at build time) -migrations/ v0.2.0 schema and later migration steps -Dockerfile.bot / Dockerfile.api -docs/ SETUP, INSTALL, DEPLOY-BUNNY, DEPLOY-AWS, COST, UPGRADE, ARCHITECTURE, … -``` +Match the existing types and tests. For an ordinary change, run the focused test, `cargo fmt --check`, and Clippy `-D warnings` on the packages you edited. CI is the merge gate. From b22a79a4543b3efcabb5b0175c94fa5768c5a18e Mon Sep 17 00:00:00 2001 From: jatmn Date: Sun, 6 Dec 2026 12:44:38 -0800 Subject: [PATCH 3/6] Lock the log-channel copy skip in CI instead of agent prose. Agents asked to copy guild log channels deleted the Rust test that already forbids it. The contracts check now fails if that refusal or its test disappears. Co-authored-by: Cursor --- scripts/check-pinned-facts.sh | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/scripts/check-pinned-facts.sh b/scripts/check-pinned-facts.sh index 6bcef2f1b..7696b1c06 100755 --- a/scripts/check-pinned-facts.sh +++ b/scripts/check-pinned-facts.sh @@ -162,6 +162,19 @@ check_tree() { [[ -n "$(awk -F'"' '/^tag = / { print $2; exit }' "$root/dylint.toml")" ]] \ || fail "dylint.toml must pin a library tag" + + # Log-channel ids are guild-scoped. This stays in CI because agents asked to + # copy them delete the Rust test that already locks the skip. + grep -Fq 'fn copy_logchannels_skips_cross_guild' "$root/src/db/tests.rs" \ + || fail "tests must keep copy_logchannels_skips_cross_guild" + grep -Fq 'must not copy foreign channel ids' "$root/src/db/tests.rs" \ + || fail "log-channel copy test must still forbid foreign channel ids" + grep -Fq 'log channel IDs are server-specific and cannot be copied' "$root/src/db/configuration.rs" \ + || fail "a logchannels-only copy across guilds must still be refused" + grep -Fq 'channel IDs are not portable across Discord servers' "$root/src/db/configuration.rs" \ + || fail "cross-guild logchannels copy must still skip" + grep -Fq 'result.skipped_logchannels = true' "$root/src/db/configuration.rs" \ + || fail "skipped log-channel copies must still be reported" } self_test From 7c67b1803e3a9ea062accc09b932a2f4b2817319 Mon Sep 17 00:00:00 2001 From: jatmn Date: Sun, 6 Dec 2026 13:42:47 -0800 Subject: [PATCH 4/6] Make the new contracts check match what the fixtures and images actually do. The preflight stand-ins never included the new script, so the contracts group exited before its assertions. The script also treated a builder-stage env, a sibling method, an unpinned image, and a grep -q pipeline as proof. Co-authored-by: Cursor --- development.md | 2 +- scripts/check-pinned-facts.sh | 168 ++++++++++++++++++++++++---------- scripts/ci-preflight-test.sh | 2 +- scripts/ci-workflow-test.mjs | 2 +- 4 files changed, 124 insertions(+), 50 deletions(-) diff --git a/development.md b/development.md index df45f14f1..c338c4923 100644 --- a/development.md +++ b/development.md @@ -30,7 +30,7 @@ cargo test --locked -p jmodguard-bot dry_run_known_spam_does_not_displace_a_live cargo clippy --locked -p jmodguard-bot --all-targets -- -D warnings cargo fmt --check # The API has two feature modes; lint both when you change it. The default -# mode embeds the WebUI, so build it first (see AGENTS.md Commands): +# mode embeds the WebUI, so build it first (see docs/SETUP.md): cargo clippy --locked -p jmodguard-api --all-targets -- -D warnings cargo clippy --locked -p jmodguard-api --no-default-features --all-targets -- -D warnings # Documentation or sample configuration: diff --git a/scripts/check-pinned-facts.sh b/scripts/check-pinned-facts.sh index 7696b1c06..055ccbce0 100755 --- a/scripts/check-pinned-facts.sh +++ b/scripts/check-pinned-facts.sh @@ -11,15 +11,25 @@ fail() { exit 1 } -section_matches() { +section_body() { local file="$1" local section="$2" - local pattern="$3" awk -v section="$section" ' $0 == section { grab = 1; next } grab && /^\[/ { exit } grab { print } - ' "$file" | grep -Eq -- "$pattern" + ' "$file" +} + +# grep -q in a pipefail pipeline returns success before awk finishes, so a +# large section makes awk die with SIGPIPE and the match is reported missing. +section_matches() { + local file="$1" + local section="$2" + local pattern="$3" + local body + body="$(section_body "$file" "$section")" || return 1 + printf '%s\n' "$body" | grep -E -- "$pattern" >/dev/null } require_section() { @@ -50,6 +60,43 @@ impl_body() { ' "$file" } +# Only the named method counts. A sibling in the same impl that still has the +# old call must not make a rewritten db_open_options look correct. +method_contains() { + local file="$1" + local impl="$2" + local method="$3" + local needle="$4" + local impl_text method_text + impl_text="$(impl_body "$file" "$impl")" + [[ -n "$impl_text" ]] || return 1 + method_text="$(printf '%s\n' "$impl_text" | awk -v method="$method" ' + $0 ~ "^[[:space:]]*(pub(\\([^)]*\\))?[[:space:]]+)?fn " method "\\(" { grab = 1 } + grab { print } + grab && /^[[:space:]]*}[[:space:]]*$/ { exit } + ')" + [[ "$method_text" == *"$needle"* ]] +} + +final_stage() { + awk ' + /^FROM / { stage = ""; has = 1 } + has { stage = stage $0 ORS } + END { printf "%s", stage } + ' "$1" +} + +# The last assignment in the runtime stage is the one the container keeps. +final_stage_sets_remote_db() { + local stage last + stage="$(final_stage "$1")" + last="$(printf '%s\n' "$stage" | awk ' + $0 ~ /^ENV JMODGUARD_REQUIRE_REMOTE_DB=/ { value = $0 } + END { print value } + ')" + [[ "$last" == "ENV JMODGUARD_REQUIRE_REMOTE_DB=1" ]] +} + self_test() { local tmp impl_file tmp="$(mktemp)" @@ -68,37 +115,72 @@ EOF if section_matches "$tmp" "[dev-dependencies]" '^jmodguard[[:space:]]*='; then fail "self-test: jmodguard-runtime matched as jmodguard" fi + { + echo '[dependencies]' + echo 'serenity = "1"' + i=0 + while [ "$i" -lt 20000 ]; do + echo "crate${i} = \"1\"" + i=$((i + 1)) + done + echo '[dev-dependencies]' + } >"$tmp" + section_matches "$tmp" "[dependencies]" '^serenity[[:space:]]*=' \ + || fail "self-test: a large section hid a real dependency match" impl_file="$(mktemp)" cat >"$impl_file" <<'EOF' impl BotProcessConfig { - pub fn db_open_options(&self) -> DbOpenOptions { + pub fn note(&self) { self.db.open_options(&self.bot, true) } -} -impl ApiProcessConfig { pub fn db_open_options(&self) -> DbOpenOptions { self.db.open_options(&self.bot, false) } } -impl DbConfig { - fn open_options(&self, bot: &BotConfig, migrate: bool) -> DbOpenOptions { - DbOpenOptions { migrate, read_only: !migrate } +impl ApiProcessConfig { + pub fn note(&self) { + self.db.open_options(&self.bot, false) + } + pub fn db_open_options(&self) -> DbOpenOptions { + self.db.open_options(&self.bot, true) } } EOF - impl_body "$impl_file" BotProcessConfig | grep -Fq 'open_options(&self.bot, true)' \ - || fail "self-test: missed bot migrate flag" - if impl_body "$impl_file" BotProcessConfig | grep -Fq 'open_options(&self.bot, false)'; then - fail "self-test: bot impl included the API flag" + if method_contains "$impl_file" BotProcessConfig db_open_options 'open_options(&self.bot, true)'; then + fail "self-test: a sibling method satisfied the bot migrate check" + fi + method_contains "$impl_file" BotProcessConfig db_open_options 'open_options(&self.bot, false)' \ + || fail "self-test: missed the bot db_open_options flag" + if method_contains "$impl_file" ApiProcessConfig db_open_options 'open_options(&self.bot, false)'; then + fail "self-test: a sibling method satisfied the API migrate check" fi - impl_body "$impl_file" ApiProcessConfig | grep -Fq 'open_options(&self.bot, false)' \ - || fail "self-test: missed API migrate flag" + method_contains "$impl_file" ApiProcessConfig db_open_options 'open_options(&self.bot, true)' \ + || fail "self-test: missed the API db_open_options flag" + + cat >"$impl_file" <<'EOF' +FROM rust:1.100.0-trixie@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa AS builder +ENV JMODGUARD_REQUIRE_REMOTE_DB=1 +FROM debian:trixie-slim +ENV OTHER=1 +EOF + if final_stage_sets_remote_db "$impl_file"; then + fail "self-test: builder-only remote DB setting counted for the runtime stage" + fi + cat >"$impl_file" <<'EOF' +FROM rust:1.100.0-trixie AS builder +ENV JMODGUARD_REQUIRE_REMOTE_DB=1 +FROM debian:trixie-slim +ENV JMODGUARD_REQUIRE_REMOTE_DB=0 +ENV JMODGUARD_REQUIRE_REMOTE_DB=1 +EOF + final_stage_sets_remote_db "$impl_file" \ + || fail "self-test: the last runtime assignment must win" rm -f "$tmp" "$impl_file" } check_tree() { - local channel msrv versions version dockerfile line body + local channel channel_re msrv versions version dockerfile tag channel="$(awk -F'"' '/^channel = / { print $2; exit }' "$root/rust-toolchain.toml")" [[ "$channel" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || fail "rust-toolchain channel must be X.Y.Z, found: ${channel:-empty}" msrv="${channel%.*}" @@ -110,27 +192,31 @@ check_tree() { [[ "$version" == "$msrv" ]] || fail "Cargo.toml rust-version ${version} must be ${msrv} (from channel ${channel})" done <<<"$versions" + local bot_from api_from + bot_from="$(awk '/^FROM rust:/ { print; exit }' "$root/Dockerfile.bot")" + api_from="$(awk '/^FROM rust:/ { print; exit }' "$root/Dockerfile.api")" + [[ "$bot_from" == "FROM rust:${channel}-"*@sha256:* ]] \ + || fail "Dockerfile.bot builder must pin rust:${channel} by digest, found: ${bot_from:-missing}" + channel_re="${channel//./\\.}" + [[ "$bot_from" =~ ^FROM\ rust:${channel_re}-[^@[:space:]]+@sha256:[0-9a-f]{64}([[:space:]]+AS[[:space:]].+)?$ ]] \ + || fail "Dockerfile.bot builder digest is not a full sha256 pin: $bot_from" + [[ "$api_from" == "$bot_from" ]] \ + || fail "Dockerfile.api builder must use the same pinned image as Dockerfile.bot" for dockerfile in Dockerfile.bot Dockerfile.api; do - line="$(grep -E '^FROM rust:' "$root/$dockerfile" | head -n 1 || true)" - [[ -n "$line" ]] || fail "$dockerfile is missing FROM rust" - case "$line" in - "FROM rust:${channel}-"*) ;; - *) fail "$dockerfile must use rust:${channel}, found: $line" ;; - esac - grep -Fxq 'ENV JMODGUARD_REQUIRE_REMOTE_DB=1' "$root/$dockerfile" \ - || fail "$dockerfile must set JMODGUARD_REQUIRE_REMOTE_DB=1" + final_stage_sets_remote_db "$root/$dockerfile" \ + || fail "$dockerfile runtime stage must set JMODGUARD_REQUIRE_REMOTE_DB=1" done - body="$(impl_body "$root/src/config.rs" BotProcessConfig)" - [[ "$body" == *'open_options(&self.bot, true)'* ]] \ + method_contains "$root/src/config.rs" BotProcessConfig db_open_options 'open_options(&self.bot, true)' \ || fail "BotProcessConfig::db_open_options must migrate (open_options true)" - [[ "$body" != *'open_options(&self.bot, false)'* ]] \ - || fail "BotProcessConfig::db_open_options must not pass migrate false" - body="$(impl_body "$root/src/config.rs" ApiProcessConfig)" - [[ "$body" == *'open_options(&self.bot, false)'* ]] \ + if method_contains "$root/src/config.rs" BotProcessConfig db_open_options 'open_options(&self.bot, false)'; then + fail "BotProcessConfig::db_open_options must not pass migrate false" + fi + method_contains "$root/src/config.rs" ApiProcessConfig db_open_options 'open_options(&self.bot, false)' \ || fail "ApiProcessConfig::db_open_options must not migrate (open_options false)" - [[ "$body" != *'open_options(&self.bot, true)'* ]] \ - || fail "ApiProcessConfig::db_open_options must not pass migrate true" + if method_contains "$root/src/config.rs" ApiProcessConfig db_open_options 'open_options(&self.bot, true)'; then + fail "ApiProcessConfig::db_open_options must not pass migrate true" + fi forbid_section "$root/Cargo.toml" "[dependencies]" '^serenity[[:space:]]*=' \ "root production dependencies must not include serenity" @@ -160,21 +246,9 @@ check_tree() { forbid_section "$root/crates/runtime/Cargo.toml" "[dependencies]" '^serenity[[:space:]]*=' \ "runtime must not depend on serenity" - [[ -n "$(awk -F'"' '/^tag = / { print $2; exit }' "$root/dylint.toml")" ]] \ - || fail "dylint.toml must pin a library tag" - - # Log-channel ids are guild-scoped. This stays in CI because agents asked to - # copy them delete the Rust test that already locks the skip. - grep -Fq 'fn copy_logchannels_skips_cross_guild' "$root/src/db/tests.rs" \ - || fail "tests must keep copy_logchannels_skips_cross_guild" - grep -Fq 'must not copy foreign channel ids' "$root/src/db/tests.rs" \ - || fail "log-channel copy test must still forbid foreign channel ids" - grep -Fq 'log channel IDs are server-specific and cannot be copied' "$root/src/db/configuration.rs" \ - || fail "a logchannels-only copy across guilds must still be refused" - grep -Fq 'channel IDs are not portable across Discord servers' "$root/src/db/configuration.rs" \ - || fail "cross-guild logchannels copy must still skip" - grep -Fq 'result.skipped_logchannels = true' "$root/src/db/configuration.rs" \ - || fail "skipped log-channel copies must still be reported" + tag="$(awk -F'"' '/^tag = / { print $2; exit }' "$root/dylint.toml")" + [[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] \ + || fail "dylint.toml must pin a vX.Y.Z library tag, found: ${tag:-empty}" } self_test diff --git a/scripts/ci-preflight-test.sh b/scripts/ci-preflight-test.sh index 052ed57b2..f64f3468a 100755 --- a/scripts/ci-preflight-test.sh +++ b/scripts/ci-preflight-test.sh @@ -233,7 +233,7 @@ git -C "$frontend_root" -c user.name=Fixture -c user.email=fixture@example.inval fixture_base="$(git -C "$frontend_root" rev-parse HEAD)" cp "$root/scripts/check-test-flakes.mjs" "$frontend_root/scripts/" : >"$frontend_root/tools/test-flake-allowlist.tsv" -for gate in select-checks-test.sh public-install-acceptance-test.sh dependabot-config-test.sh; do +for gate in select-checks-test.sh check-pinned-facts.sh public-install-acceptance-test.sh dependabot-config-test.sh; do printf 'exit 0\n' >"$frontend_root/scripts/$gate" done printf '{"type":"module"}\n' >"$frontend_root/tools/eslint/package.json" diff --git a/scripts/ci-workflow-test.mjs b/scripts/ci-workflow-test.mjs index bbd0d06f9..29095980b 100644 --- a/scripts/ci-workflow-test.mjs +++ b/scripts/ci-workflow-test.mjs @@ -1592,7 +1592,7 @@ try { fs.copyFileSync(path.join(root, "scripts", file), path.join(repo, "scripts", file)); } const record = name => `printf '%s\\n' ${name} >>"$AFFECTED_CALLS"\n`; - const contractGates = ["select-checks-test.sh", "public-install-acceptance-test.sh", "dependabot-config-test.sh"]; + const contractGates = ["select-checks-test.sh", "check-pinned-facts.sh", "public-install-acceptance-test.sh", "dependabot-config-test.sh"]; for (const gate of contractGates) fs.writeFileSync(path.join(repo, "scripts", gate), record(gate)); const nodeContractGates = ["ci-workflow-test.mjs", "check-test-flakes.test.mjs", "check-test-flakes.mjs"]; for (const gate of nodeContractGates) { From d0c4cbe2d37491556d43dfe70e3dd3a2352e91cf Mon Sep 17 00:00:00 2001 From: jatmn Date: Sun, 6 Dec 2026 13:50:35 -0800 Subject: [PATCH 5/6] Count braces when reading db_open_options. The migrate check stopped at the first closing brace, so a nested block before the real call made contracts reject an unchanged migration role. Co-authored-by: Cursor --- scripts/check-pinned-facts.sh | 39 +++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/scripts/check-pinned-facts.sh b/scripts/check-pinned-facts.sh index 055ccbce0..e90cedbbe 100755 --- a/scripts/check-pinned-facts.sh +++ b/scripts/check-pinned-facts.sh @@ -71,9 +71,32 @@ method_contains() { impl_text="$(impl_body "$file" "$impl")" [[ -n "$impl_text" ]] || return 1 method_text="$(printf '%s\n' "$impl_text" | awk -v method="$method" ' + function stripped(line, text) { + text = line + gsub(/"[^"\\]*(\\.[^"\\]*)*"/, "", text) + return text + } + function delta(line, text, i, c, n) { + text = stripped(line) + n = 0 + for (i = 1; i <= length(text); i++) { + c = substr(text, i, 1) + if (c == "{") n++ + else if (c == "}") n-- + } + return n + } + function opens(line, text) { + text = stripped(line) + return gsub(/\{/, "{", text) + } $0 ~ "^[[:space:]]*(pub(\\([^)]*\\))?[[:space:]]+)?fn " method "\\(" { grab = 1 } - grab { print } - grab && /^[[:space:]]*}[[:space:]]*$/ { exit } + grab { + print + depth += delta($0) + if (opens($0) > 0) opened = 1 + if (opened && depth <= 0) exit + } ')" [[ "$method_text" == *"$needle"* ]] } @@ -157,6 +180,18 @@ EOF fi method_contains "$impl_file" ApiProcessConfig db_open_options 'open_options(&self.bot, true)' \ || fail "self-test: missed the API db_open_options flag" + cat >"$impl_file" <<'EOF' +impl BotProcessConfig { + pub fn db_open_options(&self) -> DbOpenOptions { + if tracing::enabled!(tracing::Level::DEBUG) { + tracing::debug!("opening {db}"); + } + self.db.open_options(&self.bot, true) + } +} +EOF + method_contains "$impl_file" BotProcessConfig db_open_options 'open_options(&self.bot, true)' \ + || fail "self-test: a nested block hid the migrate call" cat >"$impl_file" <<'EOF' FROM rust:1.100.0-trixie@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa AS builder From 8b8bb5cad8497baafd25d17e6dfb63b45060e576 Mon Sep 17 00:00:00 2001 From: jatmn Date: Sun, 6 Dec 2026 13:56:39 -0800 Subject: [PATCH 6/6] Stop scanning Rust to decide which process migrates. A comment or character literal containing a brace made the shell matcher reject an unchanged db_open_options. process_options_fix_migration_role_and_keep_shared_settings already calls both process configs and asserts the flags, and core CI runs that test when src/config.rs changes. Co-authored-by: Cursor --- scripts/check-pinned-facts.sh | 106 +--------------------------------- 1 file changed, 2 insertions(+), 104 deletions(-) diff --git a/scripts/check-pinned-facts.sh b/scripts/check-pinned-facts.sh index e90cedbbe..a3c9ac1b7 100755 --- a/scripts/check-pinned-facts.sh +++ b/scripts/check-pinned-facts.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash # Executable stand-in for agent-doc claims that are facts about this tree: -# the Rust pin, which process migrates, and production dependency edges. +# the Rust pin, the runtime image, and production dependency edges. +# Which process migrates is asserted by process_options_fix_migration_role_and_keep_shared_settings. # Operator manuals are not the source of these facts. set -euo pipefail @@ -50,57 +51,6 @@ forbid_section() { fi } -impl_body() { - local file="$1" - local name="$2" - awk -v name="$name" ' - $0 ~ "^impl " name " " { grab = 1 } - grab && seen && /^impl / { exit } - grab { print; seen = 1 } - ' "$file" -} - -# Only the named method counts. A sibling in the same impl that still has the -# old call must not make a rewritten db_open_options look correct. -method_contains() { - local file="$1" - local impl="$2" - local method="$3" - local needle="$4" - local impl_text method_text - impl_text="$(impl_body "$file" "$impl")" - [[ -n "$impl_text" ]] || return 1 - method_text="$(printf '%s\n' "$impl_text" | awk -v method="$method" ' - function stripped(line, text) { - text = line - gsub(/"[^"\\]*(\\.[^"\\]*)*"/, "", text) - return text - } - function delta(line, text, i, c, n) { - text = stripped(line) - n = 0 - for (i = 1; i <= length(text); i++) { - c = substr(text, i, 1) - if (c == "{") n++ - else if (c == "}") n-- - } - return n - } - function opens(line, text) { - text = stripped(line) - return gsub(/\{/, "{", text) - } - $0 ~ "^[[:space:]]*(pub(\\([^)]*\\))?[[:space:]]+)?fn " method "\\(" { grab = 1 } - grab { - print - depth += delta($0) - if (opens($0) > 0) opened = 1 - if (opened && depth <= 0) exit - } - ')" - [[ "$method_text" == *"$needle"* ]] -} - final_stage() { awk ' /^FROM / { stage = ""; has = 1 } @@ -153,47 +103,6 @@ EOF impl_file="$(mktemp)" cat >"$impl_file" <<'EOF' -impl BotProcessConfig { - pub fn note(&self) { - self.db.open_options(&self.bot, true) - } - pub fn db_open_options(&self) -> DbOpenOptions { - self.db.open_options(&self.bot, false) - } -} -impl ApiProcessConfig { - pub fn note(&self) { - self.db.open_options(&self.bot, false) - } - pub fn db_open_options(&self) -> DbOpenOptions { - self.db.open_options(&self.bot, true) - } -} -EOF - if method_contains "$impl_file" BotProcessConfig db_open_options 'open_options(&self.bot, true)'; then - fail "self-test: a sibling method satisfied the bot migrate check" - fi - method_contains "$impl_file" BotProcessConfig db_open_options 'open_options(&self.bot, false)' \ - || fail "self-test: missed the bot db_open_options flag" - if method_contains "$impl_file" ApiProcessConfig db_open_options 'open_options(&self.bot, false)'; then - fail "self-test: a sibling method satisfied the API migrate check" - fi - method_contains "$impl_file" ApiProcessConfig db_open_options 'open_options(&self.bot, true)' \ - || fail "self-test: missed the API db_open_options flag" - cat >"$impl_file" <<'EOF' -impl BotProcessConfig { - pub fn db_open_options(&self) -> DbOpenOptions { - if tracing::enabled!(tracing::Level::DEBUG) { - tracing::debug!("opening {db}"); - } - self.db.open_options(&self.bot, true) - } -} -EOF - method_contains "$impl_file" BotProcessConfig db_open_options 'open_options(&self.bot, true)' \ - || fail "self-test: a nested block hid the migrate call" - - cat >"$impl_file" <<'EOF' FROM rust:1.100.0-trixie@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa AS builder ENV JMODGUARD_REQUIRE_REMOTE_DB=1 FROM debian:trixie-slim @@ -242,17 +151,6 @@ check_tree() { || fail "$dockerfile runtime stage must set JMODGUARD_REQUIRE_REMOTE_DB=1" done - method_contains "$root/src/config.rs" BotProcessConfig db_open_options 'open_options(&self.bot, true)' \ - || fail "BotProcessConfig::db_open_options must migrate (open_options true)" - if method_contains "$root/src/config.rs" BotProcessConfig db_open_options 'open_options(&self.bot, false)'; then - fail "BotProcessConfig::db_open_options must not pass migrate false" - fi - method_contains "$root/src/config.rs" ApiProcessConfig db_open_options 'open_options(&self.bot, false)' \ - || fail "ApiProcessConfig::db_open_options must not migrate (open_options false)" - if method_contains "$root/src/config.rs" ApiProcessConfig db_open_options 'open_options(&self.bot, true)'; then - fail "ApiProcessConfig::db_open_options must not pass migrate true" - fi - forbid_section "$root/Cargo.toml" "[dependencies]" '^serenity[[:space:]]*=' \ "root production dependencies must not include serenity" forbid_section "$root/Cargo.toml" "[dependencies]" '^jmodguard-bot[[:space:]]*=' \