Compare commits
@@ -0,0 +1,173 @@
|
||||
# Asset Pipeline — Source-Canonical Rule
|
||||
|
||||
`server/data/systems.db` is a **read-only, deterministic snapshot** produced by the
|
||||
generator pipeline. It is checked in to the repo as a build artefact so the Godot
|
||||
client can ship it without a build step, but **it is never the source of truth**.
|
||||
|
||||
---
|
||||
|
||||
## The Golden Rule
|
||||
|
||||
> **Edit sources, not the DB.**
|
||||
|
||||
If you need to change economics data, modify the TOML/JSON source files.
|
||||
If you need to change atlas markers, modify the `markers.json` files.
|
||||
Never run `UPDATE` or `INSERT` directly on `server/data/systems.db` outside of a
|
||||
migration — those changes will be silently overwritten by the next `make regen-db`.
|
||||
|
||||
---
|
||||
|
||||
## What produces systems.db
|
||||
|
||||
Two generators write to `systems.db`:
|
||||
|
||||
| Generator | Command | Source files (all contribute to the meta stamp SHA) |
|
||||
|-----------|---------|--------------|
|
||||
| `import_economics` | `python3 tooling/economy-db/import_economics.py` | `tooling/economy-db/import_economics.py` + the Rust brand binary sources it invokes: `server/src/bin/generate_brands/main.rs`, `server/src/bin/generate_brands/names.rs`, `tooling/generate-brands` |
|
||||
| `generate_atlas` | `python3 tooling/planet-gen/generate_atlas.py --seed 42` | `tooling/planet-gen/generate_atlas.py` |
|
||||
|
||||
`import_economics` shells out to the Rust `generate_brands` binary as its first
|
||||
step to refresh `wiki/economics/corporations/generated_brands.toml`, then reads
|
||||
the TOML and imports brand data into the DB. The Rust binary is a subroutine
|
||||
of the Python importer, not an independent generator — changes to its source
|
||||
invalidate the `import_economics` meta stamp even though the Python file
|
||||
itself didn't change.
|
||||
|
||||
`make regen-db` runs both in the correct order (economics first, atlas second).
|
||||
|
||||
---
|
||||
|
||||
## The meta table stamp (#855, #856)
|
||||
|
||||
After every successful non-dry-run, each generator writes a row to the `meta` table:
|
||||
|
||||
```sql
|
||||
CREATE TABLE meta (
|
||||
generator_name TEXT PRIMARY KEY, -- 'import_economics' | 'generate_atlas'
|
||||
schema_version TEXT NOT NULL, -- SHA-1 of server/data/systems-schema.sql at generation time
|
||||
generator_sha TEXT NOT NULL, -- SHA-1 of the generator source file(s)
|
||||
generated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
```
|
||||
|
||||
The `generator_sha` is the SHA-1 of the concatenated bytes of the generator's
|
||||
source files (sorted by path, so order is deterministic). If any source file
|
||||
changes and `make regen-db` is not re-run, the stamped SHA will differ from the
|
||||
recomputed current SHA — this is what the pre-push hook detects.
|
||||
|
||||
**What's deterministic:** the stored SHA (same sources → same recorded SHA).
|
||||
**What's NOT deterministic:** the DB binary itself. `meta.generated_at` uses
|
||||
`datetime('now')`, SQLite `rowid`/`autoincrement` values drift across runs, and
|
||||
transaction ordering can reshape freelist pages — two consecutive `make regen-db`
|
||||
calls produce byte-different SQLite files even with identical inputs. This is
|
||||
fine: the freshness guarantee comes from the stamp, not from bytewise DB equality.
|
||||
|
||||
---
|
||||
|
||||
## How to make a DB change
|
||||
|
||||
### Normal data changes (economics, atlas markers)
|
||||
|
||||
1. Edit the source files (TOML, JSON, markers.json).
|
||||
2. Run `make regen-db`.
|
||||
3. Run `make check-systems-db` to confirm the stamp is fresh.
|
||||
4. Stage and commit:
|
||||
```bash
|
||||
git add server/data/systems.db
|
||||
git commit -m "chore(db): regen systems.db — <what changed>"
|
||||
```
|
||||
|
||||
### Schema changes (new tables or columns)
|
||||
|
||||
1. Add the DDL to `server/data/systems-schema.sql`.
|
||||
2. Add migration SQL to `MIGRATION_SQL` in `import_economics.py` if the change
|
||||
affects existing DBs (idempotent `CREATE TABLE IF NOT EXISTS` or `ALTER TABLE`).
|
||||
3. Run `make regen-db`.
|
||||
4. Stage `server/data/systems-schema.sql` and `server/data/systems.db` together.
|
||||
|
||||
---
|
||||
|
||||
## Pre-push hook (#857)
|
||||
|
||||
`.config/hooks/pre-push` (installed via `make install-hooks`) checks that whenever
|
||||
`server/data/systems.db` is in the push, its meta stamp matches the current generator
|
||||
source SHAs. If not, the push is rejected with:
|
||||
|
||||
```
|
||||
systems.db is stale — run `make regen-db` before pushing.
|
||||
Stale generators: ['import_economics']
|
||||
```
|
||||
|
||||
Fix: run `make regen-db`, stage `server/data/systems.db`, amend or add a commit.
|
||||
Or use `/pr-push` — it detects stale generator sources and reruns `make regen-db`
|
||||
automatically before pushing.
|
||||
|
||||
The check script is `tooling/check-systems-db-stamp`. Run it interactively with
|
||||
`make check-systems-db` or `python3 tooling/check-systems-db-stamp --verbose`. The
|
||||
`GENERATOR_SOURCES` dict at the top of that script is the single registry — when
|
||||
you add a new generator or source file, update it there and mirror the change in
|
||||
the `/pr-push` skill's source-file watch list.
|
||||
|
||||
---
|
||||
|
||||
## /pr-push integration (#858)
|
||||
|
||||
The `/pr-push` skill checks whether any generator source files are modified on the
|
||||
branch. If they are, it automatically runs `make regen-db` and stages the updated
|
||||
`server/data/systems.db` before pushing — preventing pre-push hook rejections on
|
||||
branches that modify generators without regenerating.
|
||||
|
||||
---
|
||||
|
||||
## Why direct DB edits are forbidden
|
||||
|
||||
Two branches that both commit `server/data/systems.db` changes produce a binary
|
||||
merge conflict. Git cannot diff or merge binary SQLite files. Sprint 36 hit this
|
||||
exact class of problem. The meta stamp + pre-push hook is the systematic fix:
|
||||
|
||||
- The stamp is deterministic (same generator source → same recorded SHA)
|
||||
- Only one branch modifies generator sources at a time (per team scope rules)
|
||||
- The pre-push hook is a hard blocker before the binary conflict can land
|
||||
|
||||
## The migration escape hatch
|
||||
|
||||
The rule above says "never run UPDATE or INSERT directly on systems.db outside
|
||||
of a migration." Here's what a legitimate migration looks like, and what isn't
|
||||
one:
|
||||
|
||||
**Sanctioned path: the `MIGRATION_SQL` block in `import_economics.py`.** That
|
||||
string is executed at the top of every import run (inside the same transaction
|
||||
that clears + reimports data) and contains idempotent `CREATE TABLE IF NOT
|
||||
EXISTS` / `CREATE INDEX IF NOT EXISTS` statements, plus `ALTER TABLE` additions
|
||||
handled via the `COLUMN_MIGRATIONS` list. When you need a new table, column,
|
||||
or index on systems.db, add it there. It'll run on the next `make regen-db`
|
||||
and the meta stamp will flip because `import_economics.py` changed.
|
||||
|
||||
**Also legitimate:** edits to `server/data/systems-schema.sql` (the canonical
|
||||
DDL used by fresh builds) paired with matching entries in `MIGRATION_SQL` for
|
||||
existing DBs. The stamp's `schema_version` field records the schema file's
|
||||
SHA at generation time — change the schema, commit both files together, and
|
||||
the stamp picks it up automatically.
|
||||
|
||||
**NOT legitimate and forbidden:**
|
||||
|
||||
- Running `tooling/db/sqlite-exec` (or any raw SQL) against `systems.db` by
|
||||
hand. Any changes you make are silently reverted by the next `regen-db` run
|
||||
— your edits die, not the pipeline's.
|
||||
- One-off patch scripts that open `systems.db` and modify rows.
|
||||
- Editing the DB file with a SQLite GUI.
|
||||
- Committing `systems.db` alone, without the corresponding source change that
|
||||
would explain the diff on regen.
|
||||
|
||||
If you think you need an exception, the right move is to make the source
|
||||
change explicit instead: either edit the wiki TOMLs / JSONs that feed the
|
||||
generators, or edit `MIGRATION_SQL` / `systems-schema.sql` directly. There is
|
||||
no hand-edit path that survives regen.
|
||||
|
||||
---
|
||||
|
||||
## Future: savegame migration lineage
|
||||
|
||||
The `meta.schema_version` field records the schema SHA at generation time. When the
|
||||
savegame system is built (Phase 5+), a save file can record which systems.db snapshot
|
||||
it derives from, enabling forward migration without branching the DB file itself.
|
||||
@@ -26,6 +26,20 @@ current branch — never touches main.
|
||||
|
||||
## Workflow
|
||||
|
||||
### 0. Dry-run mode check
|
||||
|
||||
If the user invokes `/pr-push --dry-run`:
|
||||
- Print: "Dry-run mode — inspecting state, nothing will be pushed or committed."
|
||||
- Run steps 1 through 4a in **inspect-only** mode:
|
||||
- Step 4: run `make check-systems-db` to check current stamp freshness (no merge)
|
||||
- Step 4a: report which watched files changed vs origin/main; show whether `make regen-db`
|
||||
would be triggered; do NOT run the regen, stage, or commit
|
||||
- Print a summary: watched files changed (list), regen needed (yes/no), DB stamp fresh (yes/no)
|
||||
- Print "Dry run complete — use /pr-push to apply."
|
||||
- Stop. Do not push or create a PR.
|
||||
|
||||
---
|
||||
|
||||
### 1. Validate branch
|
||||
|
||||
```bash
|
||||
@@ -201,6 +215,73 @@ git merge origin/main --no-edit
|
||||
If merge conflicts, **stop and report** — let the user resolve.
|
||||
If clean, continue.
|
||||
|
||||
### 4a. Regen systems.db if generator sources or data changed (#858)
|
||||
|
||||
Check whether any file in the **source-file watch list** was modified on this branch
|
||||
versus `origin/main`. This list covers generator code AND the data files that feed them.
|
||||
|
||||
The generator-source paths below **must stay in sync** with `GENERATOR_SOURCES` in
|
||||
`tooling/check-systems-db-stamp` (PR #136 review T7) — if you add a new source file
|
||||
to the stamp, add it here too, and vice versa. Drift between the two lists reintroduces
|
||||
exactly the silent-stale-DB class of bug this skill exists to prevent.
|
||||
|
||||
```bash
|
||||
git diff --name-only origin/main...HEAD -- \
|
||||
tooling/economy-db/import_economics.py \
|
||||
tooling/planet-gen/generate_atlas.py \
|
||||
server/src/bin/generate_brands/main.rs \
|
||||
server/src/bin/generate_brands/names.rs \
|
||||
tooling/generate-brands \
|
||||
server/data/systems-schema.sql \
|
||||
wiki/star-systems/ \
|
||||
wiki/economics/ \
|
||||
content/economics/
|
||||
```
|
||||
|
||||
**If output is empty:** skip this step entirely.
|
||||
|
||||
**If any files appear in the output:** the DB must be regenerated on top of the
|
||||
current main. Perform the following:
|
||||
|
||||
1. **Integrate main.** Step 4 merged main into the branch. If you find yourself
|
||||
on a branch that was NOT yet merged with main in step 4, do it now:
|
||||
```bash
|
||||
git fetch origin
|
||||
git merge origin/main --no-edit
|
||||
```
|
||||
If there are merge conflicts in source files, **stop and report which files
|
||||
conflict**. Ask the user to resolve manually — do not attempt to auto-resolve
|
||||
generator source conflicts.
|
||||
|
||||
2. **Regenerate the DB:**
|
||||
```bash
|
||||
make regen-db
|
||||
```
|
||||
`make regen-db` runs all three generators and stamps the meta table. It tolerates
|
||||
coverage gate failures (exit 2 = data quality warning, not an error). If it exits
|
||||
with any other non-zero code, stop and report the stderr output — do not push.
|
||||
|
||||
3. **Stage the updated DB:**
|
||||
```bash
|
||||
git add server/data/systems.db
|
||||
```
|
||||
|
||||
4. **Commit only if the DB actually changed:**
|
||||
```bash
|
||||
git diff --cached --stat -- server/data/systems.db
|
||||
```
|
||||
- If the diff shows changes: commit with `/git-commit`, message:
|
||||
`chore(db): regen systems.db against rebased sources`
|
||||
- If no diff (regen produced identical output — sources were self-consistent):
|
||||
unstage the file (`git restore --staged server/data/systems.db`) and skip the
|
||||
commit. The source changes alone are the PR content.
|
||||
|
||||
**In dry-run mode** (from step 0): report which watch-list files changed and
|
||||
whether regen would be triggered. Do NOT run the regen or modify any files.
|
||||
|
||||
This step prevents the pre-push hook from rejecting a push where the branch modifies
|
||||
a generator source or data file but did not regenerate the DB.
|
||||
|
||||
### 5. Push
|
||||
|
||||
```bash
|
||||
|
||||
@@ -138,24 +138,57 @@ Three-dot diff with pathspec exclusions is unreliable. Instead, either:
|
||||
For large diffs (>1000 lines of source), provide **source files** rather than
|
||||
raw diff to reviewers — cleaner context, better reviews.
|
||||
|
||||
**Reviewer agents read source files via `git show`.** Sprint branches
|
||||
use the naming pattern `sprint-{N}/{team}`. To read a file from the
|
||||
branch being reviewed:
|
||||
**Reviewer agents read source files from the team worktree.**
|
||||
|
||||
Sprint branches follow `sprint-{N}/{team}`. Mid-sprint, a worktree
|
||||
of each branch exists at `$(dirname <repo_root>)/.sprint/sprint-{N}/{team}/`
|
||||
— a *sibling* of the repo root, not a child. This worktree IS the
|
||||
branch: Read/Grep on paths rooted there resolve against the branch's
|
||||
checkout, not main's.
|
||||
|
||||
**Why this matters:** Sprint 37 PR #138 review produced 6 false-
|
||||
positive findings because the reviewer defaulted to Read/Grep on the
|
||||
main repo path (`/var/mnt/data/projects/settled-reach/main/`) instead
|
||||
of the branch worktree. Every finding was a verbatim match against
|
||||
main's state but irrelevant to the branch — the branch had already
|
||||
cleaned the residue the reviewer flagged as "still present." Sending
|
||||
those findings to the team would have caused busywork on already-clean
|
||||
code, and more dangerously, the same drift hides *false negatives*
|
||||
(branch-introduced bugs the reviewer never saw because it never read
|
||||
the branch).
|
||||
|
||||
Fix: before spawning reviewers, resolve the worktree path and pass it
|
||||
into every reviewer prompt with prominent language. The reviewer
|
||||
reads from the worktree, not from main.
|
||||
|
||||
```bash
|
||||
git show origin/<branch>:<path>
|
||||
# Determine worktree path
|
||||
SPRINT_NUM=$(echo "<branch>" | sed -E 's|sprint-([0-9]+)/.*|\1|')
|
||||
TEAM=$(echo "<branch>" | sed -E 's|sprint-[0-9]+/||')
|
||||
REPO_ROOT=$(git rev-parse --show-toplevel)
|
||||
WORKTREE="$(dirname "$REPO_ROOT")/.sprint/sprint-${SPRINT_NUM}/${TEAM}"
|
||||
|
||||
# Verify it exists and matches the branch tip
|
||||
git -C "$WORKTREE" rev-parse HEAD # should equal `git rev-parse origin/<branch>`
|
||||
```
|
||||
|
||||
For example:
|
||||
```bash
|
||||
git show origin/sprint-31/server:server/src/bin/atlas.rs
|
||||
```
|
||||
If the worktree exists and its HEAD matches `origin/<branch>`, use it
|
||||
as the reviewer's source of truth. If it doesn't exist (e.g. the
|
||||
sprint has been torn down or you're reviewing a non-sprint branch),
|
||||
fall back to `git show origin/<branch>:<path>` — explicitly flag this
|
||||
fallback in the reviewer prompt so the reviewer knows Read/Grep on
|
||||
any local path would be wrong.
|
||||
|
||||
If the sprint branch has an active worktree (under `.sprint/`), reviewers
|
||||
can also use the Read tool with the worktree path. But `git show` is
|
||||
the reliable default — it works whether or not a worktree exists.
|
||||
In the reviewer prompt, state the rule non-negotiably:
|
||||
|
||||
Also tell agents to read relevant `decisions/*.md` files for context.
|
||||
> **Read source from `<WORKTREE_PATH>` only.** Do NOT Read or Grep
|
||||
> paths under the main repo root (`/var/mnt/data/projects/settled-reach/main/`).
|
||||
> Those resolve to main, not the branch. The worktree at `<WORKTREE_PATH>`
|
||||
> IS the branch — point all file tools there.
|
||||
|
||||
Also tell agents to read relevant `decisions/*.md` files for context
|
||||
(these can be read from either path — they're usually identical —
|
||||
but for consistency, use the worktree path).
|
||||
|
||||
### 4. Spawn reviewers in parallel
|
||||
|
||||
|
||||
@@ -130,17 +130,34 @@ If the user raises items that should be tracked, create Q-NNN entries
|
||||
or backlog tickets on the spot. If process changes are agreed, update
|
||||
the relevant skill files or CLAUDE.md immediately — don't defer them.
|
||||
|
||||
#### A1c. Clean up sprint worktrees
|
||||
#### A1c. Clean up sprint worktrees (MANDATORY — do not skip)
|
||||
|
||||
Remove ephemeral worktrees for the closed sprint. Run the teardown script:
|
||||
Always run the teardown script. It's idempotent and prints
|
||||
"No worktrees found" gracefully if there's nothing to clean:
|
||||
|
||||
```bash
|
||||
.claude/skills/sprint-start/scripts/sprint-teardown.sh {N}
|
||||
```
|
||||
|
||||
This removes all worktrees under `.sprint/sprint-{N}/` and prunes git
|
||||
metadata. Safe to skip if the sprint didn't use ephemeral worktrees
|
||||
(e.g. legacy persistent worktree setup).
|
||||
**Do not try to pre-check whether worktrees exist by running `ls`
|
||||
locally.** Sprint worktrees live at
|
||||
`$(dirname <repo-root>)/.sprint/sprint-{N}/` — a *sibling* of the
|
||||
repo root, not a child. Running `ls .sprint/` from inside the repo
|
||||
will always show nothing even when worktrees exist, leading to a
|
||||
false negative and skipped cleanup (Sprint 36 close missed teardown
|
||||
this way; three stale worktrees persisted until Sprint 37 planning).
|
||||
|
||||
The script knows the correct path via its own `SCRIPT_DIR` — trust it.
|
||||
|
||||
Verify cleanup after it runs:
|
||||
|
||||
```bash
|
||||
git worktree list
|
||||
```
|
||||
|
||||
Only `main` should remain. Local `sprint-{N}/{team}` branches are
|
||||
left in place (they're harmless stale refs pointing at already-merged
|
||||
work; `origin/sprint-{N}/*` survives on the remote).
|
||||
|
||||
#### A2. Bump the version
|
||||
|
||||
@@ -348,11 +365,25 @@ using `TaskUpdate` with `addBlockedBy`.
|
||||
For each agent from the `**Agents:**` line, spawn a teammate in the
|
||||
background. Spawn all agents in parallel (one message, multiple Task calls):
|
||||
|
||||
**Model pin (MANDATORY for team members):** every team-mode spawn —
|
||||
i.e. any `Task` with a `team_name` argument — must pass `model: "sonnet"`.
|
||||
Sprint 37 observed Opus 4.7 teammates ignoring scope rules, leaving
|
||||
tasks half-done, and failing to report back via SendMessage. Sonnet 4.6
|
||||
follows literal rules block discipline better. The **team lead**
|
||||
(this session, running `/sprint-start`) stays on whatever model the
|
||||
user has selected — typically Opus.
|
||||
|
||||
**Inline (non-team) Agent spawns are exempt.** One-shot reviewers
|
||||
(`/pr-review`), research subagents, and other `Task` calls without a
|
||||
`team_name` keep their default model. The pin applies to the
|
||||
long-running team-coordination path specifically, not every Agent call.
|
||||
|
||||
```
|
||||
Task(
|
||||
subagent_type: "{name_lowercase}",
|
||||
team_name: "sprint-{N}-{team}",
|
||||
name: "{name_lowercase}",
|
||||
model: "sonnet",
|
||||
prompt: "You are on the {team} team for Sprint {N}.
|
||||
Branch: `sprint-{N}/{team}`
|
||||
|
||||
@@ -406,6 +437,9 @@ Task(
|
||||
|
||||
1. Read the sprint briefing: docs/sprints/sprint-{N}/{team}.md
|
||||
2. Read the decision files referenced in the briefing.
|
||||
If your work touches systems.db sources (markers.json, TOML files,
|
||||
or generator code), read .claude/rules/asset-pipeline.md before
|
||||
modifying anything.
|
||||
3. Check TaskList for available work.
|
||||
4. Claim an unblocked task (TaskUpdate with owner: your name),
|
||||
mark it in_progress, and implement it.
|
||||
|
||||
@@ -61,6 +61,7 @@ Use the Task tool to spawn each agent as a teammate. Each call should:
|
||||
- Set `team_name` to the workshop team name
|
||||
- Set `name` to the agent name (e.g., "gestalt")
|
||||
- Set `subagent_type` to the matching agent type (same as name — see reference table)
|
||||
- **Set `model: "sonnet"`** — team-mode participants pin to Sonnet 4.6 for literal-rule-following discipline. Opus 4.7 was observed ignoring scope rules and failing to report back in team mode (Sprint 37). The *team lead* (this session) stays on whatever model the user has selected.
|
||||
- Provide a prompt telling the agent to check TaskList for their assigned task
|
||||
|
||||
Spawn all agents in parallel (one Task call per agent in a single message). Agents will appear as teammates in the Claude Code UI and pick up their tasks from the shared task list.
|
||||
|
||||
+56
-4
@@ -9,14 +9,27 @@ ERRORS=0
|
||||
echo "pre-push: running lint checks..."
|
||||
|
||||
# --- Detect which directories have changes vs remote ---
|
||||
# Prefer origin/<branch> as the baseline (what the remote already has),
|
||||
# but fall back to origin/main for first-push of a new branch — otherwise
|
||||
# every check runs against nothing and the hook treats the whole repo as
|
||||
# changed, spending tens of seconds on linters and JSON validation that
|
||||
# have no diff to cover (e.g. pushing a wiki-only branch rebuilds GDScript
|
||||
# and runs clippy + ruff + validates all 2762 JSON files).
|
||||
BRANCH=$(git branch --show-current)
|
||||
REMOTE_REF="origin/$BRANCH"
|
||||
if git rev-parse --verify "$REMOTE_REF" >/dev/null 2>&1; then
|
||||
if git rev-parse --verify "origin/$BRANCH" >/dev/null 2>&1; then
|
||||
REMOTE_REF="origin/$BRANCH"
|
||||
elif git rev-parse --verify "origin/main" >/dev/null 2>&1; then
|
||||
REMOTE_REF="origin/main"
|
||||
else
|
||||
REMOTE_REF=""
|
||||
fi
|
||||
|
||||
if [ -n "$REMOTE_REF" ]; then
|
||||
CLIENT_CHANGED=$(git diff --name-only "$REMOTE_REF"..HEAD -- client/ 2>/dev/null | wc -l)
|
||||
SERVER_CHANGED=$(git diff --name-only "$REMOTE_REF"..HEAD -- server/ 2>/dev/null | wc -l)
|
||||
TOOLING_CHANGED=$(git diff --name-only "$REMOTE_REF"..HEAD -- tooling/ pyproject.toml 2>/dev/null | wc -l)
|
||||
else
|
||||
# New branch or no remote ref — fall through to directory checks
|
||||
# No remote at all (e.g. fresh clone before first fetch) — be safe, run everything
|
||||
CLIENT_CHANGED=1
|
||||
SERVER_CHANGED=1
|
||||
TOOLING_CHANGED=1
|
||||
@@ -114,7 +127,12 @@ else
|
||||
fi
|
||||
|
||||
# --- JSON syntax validation ---
|
||||
if git rev-parse --verify "$REMOTE_REF" >/dev/null 2>&1; then
|
||||
# Use the same REMOTE_REF the directory-change detection above settled on
|
||||
# (origin/<branch> preferred, origin/main fallback). Without this, a first
|
||||
# push of a new branch falls through to "validate every JSON in the repo,"
|
||||
# which on this repo means 2762 Python parses — tens of seconds of churn
|
||||
# for a push that might not have touched any JSON at all.
|
||||
if [ -n "$REMOTE_REF" ]; then
|
||||
JSON_FILES=$(git diff --name-only "$REMOTE_REF"..HEAD -- '*.json' 2>/dev/null || true)
|
||||
else
|
||||
JSON_FILES=$(git ls-files '*.json')
|
||||
@@ -138,6 +156,40 @@ else
|
||||
echo "pre-push: no JSON changes — skipping"
|
||||
fi
|
||||
|
||||
# --- systems.db stamp check (#857) ---
|
||||
# If the branch touches server/data/systems.db and the meta stamp does not
|
||||
# match current generator sources, reject the push. Prevents pushing a
|
||||
# stale DB snapshot where generator source was modified but the DB was not
|
||||
# regenerated.
|
||||
#
|
||||
# Runs whenever systems.db was modified in ANY branch commit vs. main —
|
||||
# including on a branch's very first push (review T5: the previous version
|
||||
# skipped the check for new branches because it compared against origin/$BRANCH,
|
||||
# which didn't exist yet, leaving a gap where a stale DB could ship via the
|
||||
# first push). We compare against origin/main — which always exists — so the
|
||||
# check covers the first-push case.
|
||||
DB_IN_PUSH=$(git diff --name-only origin/main...HEAD -- server/data/systems.db 2>/dev/null | wc -l)
|
||||
if [ "$DB_IN_PUSH" -gt 0 ] && [ -f "$REPO_ROOT/tooling/check-systems-db-stamp" ]; then
|
||||
echo "pre-push: checking systems.db stamp..."
|
||||
rc=0
|
||||
python3 "$REPO_ROOT/tooling/check-systems-db-stamp" || rc=$?
|
||||
if [ "$rc" -eq 1 ]; then
|
||||
# rc=1 means stale / unknown generator / missing source; message on stderr
|
||||
echo " Fix: run 'make regen-db' then stage server/data/systems.db"
|
||||
echo " Or use /pr-push — it handles regen automatically before pushing."
|
||||
ERRORS=$((ERRORS + 1))
|
||||
elif [ "$rc" -eq 2 ]; then
|
||||
# rc=2 means no meta table — treat as unstamped, warn but don't block.
|
||||
# This is legitimate immediately after the meta table is introduced;
|
||||
# the next `make regen-db` will populate it (H4).
|
||||
echo "pre-push: WARNING — systems.db has no meta stamp — run 'make regen-db' now if this DB was generated by you"
|
||||
else
|
||||
echo "pre-push: systems.db stamp — OK"
|
||||
fi
|
||||
else
|
||||
echo "pre-push: systems.db not in push — skipping stamp check"
|
||||
fi
|
||||
|
||||
if [ "$ERRORS" -gt 0 ]; then
|
||||
echo ""
|
||||
echo "pre-push: $ERRORS check(s) failed. Push aborted."
|
||||
|
||||
@@ -6,6 +6,41 @@ Format based on [Keep a Changelog](https://keepachangelog.com/).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [v0.1.37] — 2026-04-22
|
||||
|
||||
### Added
|
||||
- **Asset pipeline discipline** (#854, #855, #856, #857, #858, #859) — `systems.db` is now a source-canonical snapshot with a `meta` table stamped by every generator (SHA of source + schema). Pre-push hook rejects stale DBs; `/pr-push` auto-runs `make regen-db` when generator sources change. Full rules in `.claude/rules/asset-pipeline.md`
|
||||
- **`make regen-db`** — runs the two DB-writing generators (import_economics, generate_atlas) and stamps the meta table. import_economics now invokes the Rust generate_brands binary internally as its first step, so the brand pipeline is owned by a single stamp.
|
||||
- **`make check-systems-db`** — verifies the meta stamp matches current generator sources
|
||||
- **`make install-hooks`** — installs pre-push and pre-commit hooks in one step
|
||||
- **`tooling/db/decision show <D-NNN>`** (#723) — drill-down view of a decision with implementing tickets and cross-refs
|
||||
- **Atlas determinism smoke test** (#847) — `make test-atlas-determinism` runs `generate_atlas.process_body()` twice with a fixed seed and diffs the output to catch determinism regressions in terrain analysis, city placement, A* routing, and naming
|
||||
- **SelectedBookmark save/load** (#863) — bookmark and starting-location choice now persist across save/load; replaces the v0.2-deferred TODO on `SelectedBookmark`
|
||||
- **`BookmarkPlugin::new(registry)` injection** (#862) — test-friendly plugin construction for future TOML bookmark loading; default constructor still wires the canonical tycoon registry
|
||||
- **Six new corporation wiki pages** (#860) — Arbour Aggregates, Earth Standard Group, Rush Mining, Scapa Flow Industries, Sede Chemical Works, Threshold Fuel Syndicate
|
||||
- **Atlas naming corridor-scoped dedup, compass-direction filter, river vocab filter, infra pair-naming** (#853) — city and mountain names deduplicate across bodies within a corridor; compass-direction defaults blocked in the few-shot prompt; navigational vocabulary (`Flow`, `Current`) rejected for rivers; unnamed roads and railroads receive deterministic `{CityA}–{CityB} {corridor_suffix}` names
|
||||
- **Scene-level merge-path UI flow tests** (#873) — `test_merge_path_flows_sprint37.gd` covers main-menu → new-game, load-game, character-creation → submit, bookmark → confirm. Headless scene-flow tier (4th beyond Gauntlet/MessagePack/TestHarness); pattern for future merge-path regression guards
|
||||
- **105 brand corp wiki stubs** (#861) — every corp page from Sprint 36 PR #133 now authored to three-layer narrative depth (public identity / actual operation / one concealed fact) with ≥95-line DoD
|
||||
- **D-193 Lattice Commission** (#876) — resolves Q-095: "the Lattice Commission" is the canonical long-form of the Concord Assembly's regulatory authority; "Concord Commission" and "Assembly Commission" deprecated as drift forms
|
||||
|
||||
### Changed
|
||||
- `decisions-coverage` Makefile target now lists implementing ticket IDs per decision instead of aggregate counts
|
||||
- **Economy coverage gate** (#860) now passes end-to-end — closes the 21 raw-commodity / system gaps that blocked Phase 2 demand simulation
|
||||
- Tag updates on 15 existing corporation wiki pages to match commodity coverage needs
|
||||
|
||||
### Fixed
|
||||
- **New Game flow hangs on 'connecting'** (#872) — `bookmark_catalog` carry-forward race in `SimBridge.receive_bytes` when tick 0 + tick 1 arrived in the same TCP batch; catalog now carries forward with same invariants as monologue/dialogue/settings_response
|
||||
- **`dialogue_box._escape_bbcode` corrupted `[lb]` escapes** (#866) — chained `.replace('[','[lb]').replace(']','[rb]')` turned `[lb]` into `[lb[rb]`; fix escapes only `[`, since unmatched `]` renders as literal in RichTextLabel
|
||||
- **MetaScreen test helper regression in `test_anti_tedium`** (#869) — bug_report_dialog test helpers now instantiate from `.tscn` instead of `Control.new() + set_script()`, preserving the MetaScreen runtime stack
|
||||
- Storyteller `activation_pass` "no Simmering triangles — holding" no longer fires as `warn` during normal early-game state — downgraded to `debug` (#789)
|
||||
|
||||
### Removed
|
||||
- **`PROTOCOL_VERSION` lockstep handshake** (#874, #875, D-192) — both sides of the handshake now omit the version field; `HandshakeMessage` is empty server-side and the client decode path no longer checks versions. Schema drift surfaces as MessagePack missing-field errors downstream, which is the intended signal
|
||||
- **`HeritageRoot` type alias and `ZonePaletteModifier::Heritage` variant** (#877, D-167) — last stubs of the abstract heritage-root system retired in favour of the corridor cultural framework
|
||||
- **`CharacterArchetype` (Smuggler/Detective) trace from server** (#878) — enum, IPC field, verb-differentiation branch in the observer Phase 2 filter (D-057 superseded), monologue pool partitioning, Gauntlet plumbing, drama-module schema, archetype-dependent integration tests. Per the development cascade, character/NPC differentiation is Phase 6 work and the running trace was pre-cascade filler, not production. Client-side cleanup tracked in #882.
|
||||
- **v0.1 Sova/Van Maanen's residue from wiki** (#865) — `wiki/star-systems/GJ-35/sova/` subtree deleted; authoring-guide examples stripped; canonical lore citing dropped v0.1 NPCs rewritten; "Van Maanen's Star" cultural references converted to "Vuurkloof"
|
||||
- **8 parse-error test files** (#870) — `test_debug_overlay_sprint19`, `test_entanglement_sprint22`, `test_fog_sprint22`, `test_journal_sprint18`, `test_minimap_sprint18`, `test_session_manager_sprint19`, `test_sprint30`, `test_sprite_integration` — referenced removed/renamed APIs from prior sprints. Coverage-revival tickets filed: #879 (fog), #880 (journal), #881 (minimap), #889 (EntityRenderer sprite constants); rest tracked under umbrella #871
|
||||
|
||||
## [v0.1.36] — 2026-04-21
|
||||
|
||||
### Added
|
||||
|
||||
@@ -25,6 +25,12 @@ Full annotated tree: `.claude/rules/project-structure.md`
|
||||
|
||||
See [docs/DEVOPS.md](docs/DEVOPS.md) for build, test, lint, and CI procedures. All development operations go through the top-level `Makefile` — run `make` for a summary of targets.
|
||||
|
||||
### Asset pipeline
|
||||
|
||||
`server/data/systems.db` is a read-only canonical snapshot produced by the generator
|
||||
pipeline — never edit it directly. To regenerate: `make regen-db`. Full rules in
|
||||
`.claude/rules/asset-pipeline.md`.
|
||||
|
||||
## Development Cascade — First Things First
|
||||
|
||||
Development follows a strict cascade. Each phase has a concrete deliverable. **Do NOT discuss, design, or implement detail from a later phase while an earlier phase is incomplete.** If you encounter references to later-phase detail (room grammar, NPC bundles, heritage tokens, etc.) in documents or decisions, either ignore them silently and stay at the correct level, or flag that the reference is dragging attention to the wrong scope level and suggest it be rephrased or moved.
|
||||
@@ -89,7 +95,7 @@ The ticketing database (`settledreach.db`) is accessed via `SR_DB_PATH` env var
|
||||
| Sprints | `tooling/db/sprint status`, `start-work`, `prepare` | `/sprint-start` skill |
|
||||
| SQL queries | `tooling/db/sqlite-query "SELECT ..."` | — |
|
||||
| SQL writes | `tooling/db/sqlite-exec "UPDATE ..."` | — |
|
||||
| Decisions | `tooling/db/decision next`, `claim`, `check-dupes` | — |
|
||||
| Decisions | `tooling/db/decision show`, `next`, `claim`, `check-dupes` | — |
|
||||
|
||||
### Testing preferences
|
||||
|
||||
|
||||
@@ -2,8 +2,8 @@ GODOT := $(shell command -v godot4 2>/dev/null || command -v godot 2>/dev/null)
|
||||
|
||||
.PHONY: help setup build check-protocol client server game stop test lint lint-python setup-venv ci ci-client ci-server clean \
|
||||
decisions-sync decisions-coverage decisions-active decisions-orphan \
|
||||
db-backup db-install validate-content check-fact-ids setup-hooks \
|
||||
audit deny atlas-verify economy-db atlas-generate \
|
||||
db-backup db-install validate-content check-fact-ids setup-hooks install-hooks \
|
||||
audit deny atlas-verify economy-db atlas-generate regen-db check-systems-db \
|
||||
pre-pr pre-pr-lint pre-pr-build pre-pr-test pre-pr-validate pre-pr-fixtures \
|
||||
pre-pr-server pre-pr-client pre-pr-content \
|
||||
fixtures-client fixtures-gauntlet golden-diff golden-update \
|
||||
@@ -46,7 +46,7 @@ help:
|
||||
@echo " make db-install Restore shared database from backup"
|
||||
@echo ""
|
||||
@echo " make decisions-sync Sync decisions/*.md into SQLite"
|
||||
@echo " make decisions-coverage Decision-to-ticket coverage by domain"
|
||||
@echo " make decisions-coverage Each decision with its implementing ticket(s)"
|
||||
@echo " make decisions-active List active decisions"
|
||||
@echo " make decisions-orphan Decisions without implementing tickets"
|
||||
@echo " make audit Run cargo audit (security advisory check)"
|
||||
@@ -58,6 +58,10 @@ help:
|
||||
@echo " make check-star-map Assert star_map_data.json is up to date (part of pre-pr-client)"
|
||||
@echo " make economy-db Import economics data into systems.db (TOML/JSON → SQLite)"
|
||||
@echo " make atlas-generate Generate atlas city/road/rail markers for all inhabited bodies"
|
||||
@echo " make regen-db Regenerate systems.db from all sources + stamp meta table (#855)"
|
||||
@echo " make check-systems-db Verify systems.db meta stamp matches current generator sources"
|
||||
@echo " make install-hooks Install pre-push + pre-commit git hooks (once per clone)"
|
||||
@echo " make test-atlas-determinism Determinism smoke test for generate_atlas.py (#847)"
|
||||
@echo " make fixtures-client Generate GDScript->Rust cross-encoder fixtures (#475)"
|
||||
@echo " make golden-diff Show diff if golden file output has changed"
|
||||
@echo " make golden-update Regenerate golden file and stage for commit"
|
||||
@@ -110,6 +114,10 @@ setup-hooks:
|
||||
@git config core.hooksPath .config/hooks
|
||||
@echo "Git hooks path set to .config/hooks"
|
||||
|
||||
install-hooks: setup-hooks
|
||||
@chmod +x .config/hooks/pre-push .config/hooks/pre-commit
|
||||
@echo "Hooks installed — pre-push and pre-commit are active."
|
||||
|
||||
setup-venv:
|
||||
@python3 -m venv .venv
|
||||
@.venv/bin/pip install -e ".[dev]" --quiet
|
||||
@@ -223,6 +231,9 @@ test-ipc-integration:
|
||||
test-ipc-benchmark:
|
||||
tests/run-ipc-benchmark
|
||||
|
||||
test-atlas-determinism: ## Determinism smoke test for generate_atlas.py (#847)
|
||||
tests/run-atlas-determinism
|
||||
|
||||
# --- Clean ---
|
||||
|
||||
clean-imports:
|
||||
@@ -347,6 +358,27 @@ atlas-generate: ## Generate atlas markers (cities, roads, rail) for all inhabit
|
||||
echo " [guard] $$count bodies with terrain_reference — proceeding."
|
||||
@python3 tooling/planet-gen/generate_atlas.py --seed 42
|
||||
|
||||
regen-db: ## Regenerate systems.db from all sources and stamp meta table (#855, #856)
|
||||
@# Run as a single shell so `set -e` covers all steps. Without this
|
||||
@# each recipe line was a fresh shell and a failure in step 1 did not
|
||||
@# halt step 2, which could produce stale data with a fresh stamp
|
||||
@# (PR #136 review T4). import_economics' exit code 2 is a valid
|
||||
@# coverage-gate-warning state (DB and stamp committed), not an error,
|
||||
@# so it's explicitly tolerated. Any other non-zero exit halts the
|
||||
@# pipeline immediately.
|
||||
@set -e; \
|
||||
echo " [regen-db] Importing economics data (runs generate_brands internally)..."; \
|
||||
ec=0; python3 tooling/economy-db/import_economics.py || ec=$$?; \
|
||||
if [ $$ec -ne 0 ] && [ $$ec -ne 2 ]; then exit $$ec; fi; \
|
||||
echo " [regen-db] Running atlas generator..."; \
|
||||
python3 tooling/planet-gen/generate_atlas.py --seed 42; \
|
||||
echo ""; \
|
||||
echo " regen-db complete — systems.db is up to date and stamped."; \
|
||||
echo " Stage it with: git add server/data/systems.db"
|
||||
|
||||
check-systems-db: ## Verify systems.db meta stamp matches current generator sources (#857)
|
||||
@python3 tooling/check-systems-db-stamp --verbose
|
||||
|
||||
econ-sim: ## Build the economics simulation binary (Layer 1+2: Leontief + tâtonnement trade)
|
||||
@cargo build --manifest-path tooling/econ-sim/Cargo.toml --release
|
||||
@echo "Built: tooling/econ-sim/target/release/econ-sim"
|
||||
@@ -364,7 +396,7 @@ decisions-sync:
|
||||
@tooling/db/decisions-sync
|
||||
|
||||
decisions-coverage:
|
||||
@tooling/db/sqlite-query "SELECT d.domain, COUNT(DISTINCT d.id) as decisions, COUNT(DISTINCT t.decision_ref) as with_tickets FROM decisions d LEFT JOIN tickets t ON d.id = t.decision_ref WHERE d.status='active' AND d.type='confirmed' GROUP BY d.domain"
|
||||
@tooling/db/sqlite-query "SELECT d.id, d.domain, d.title, COALESCE(GROUP_CONCAT(t.id, ', '), '') as implementing_tickets FROM decisions d LEFT JOIN tickets t ON d.id = t.decision_ref WHERE d.status='active' AND d.type='confirmed' GROUP BY d.id ORDER BY d.domain, d.id"
|
||||
|
||||
decisions-active:
|
||||
@tooling/db/sqlite-query "SELECT id, domain, title FROM decisions WHERE status='active' AND type='confirmed' ORDER BY domain, id"
|
||||
|
||||
@@ -3,7 +3,7 @@ extends Node
|
||||
# Signals
|
||||
signal connection_state_changed(old_state: ConnectionState, new_state: ConnectionState)
|
||||
signal snapshot_received(snapshot: Dictionary)
|
||||
signal handshake_complete(protocol_version: int)
|
||||
signal handshake_complete
|
||||
signal handshake_failed(reason: String)
|
||||
|
||||
# Connection states
|
||||
@@ -246,13 +246,10 @@ func _process(delta: float) -> void: # gdlint:disable=max-returns
|
||||
if msg.is_empty():
|
||||
return # Not ready yet, continue polling
|
||||
|
||||
# Decode HandshakeMessage: { "protocol_version": N }
|
||||
# Decode HandshakeMessage — D-192 (#875): protocol_version field dropped.
|
||||
# Server sends {} or a minimal dict; only structural validity is required.
|
||||
var decoded: Variant = Messagepack.decode(msg)
|
||||
if (
|
||||
decoded.status != null
|
||||
or not (decoded.value is Dictionary)
|
||||
or not decoded.value.has("protocol_version")
|
||||
):
|
||||
if decoded.status != null or not (decoded.value is Dictionary):
|
||||
var reason := "Handshake decode failed: malformed HandshakeMessage"
|
||||
push_error("SimBridge: %s" % reason)
|
||||
handshake_failed.emit(reason)
|
||||
@@ -260,18 +257,6 @@ func _process(delta: float) -> void: # gdlint:disable=max-returns
|
||||
_set_state(ConnectionState.ERROR)
|
||||
return
|
||||
|
||||
var server_version: int = decoded.value["protocol_version"]
|
||||
if server_version != Protocol.PROTOCOL_VERSION:
|
||||
var reason := (
|
||||
"Protocol version mismatch: server=%d, client=%d"
|
||||
% [server_version, Protocol.PROTOCOL_VERSION]
|
||||
)
|
||||
push_error("SimBridge: %s" % reason)
|
||||
handshake_failed.emit(reason)
|
||||
_bridge.disconnect_from_server()
|
||||
_set_state(ConnectionState.ERROR)
|
||||
return
|
||||
|
||||
# Send startup message with world_seed and character appearance (#175, D-010/D-029, #718).
|
||||
# Server blocks waiting for this before entering the tick loop.
|
||||
var startup_bytes := Protocol.encode_startup_message(
|
||||
@@ -296,7 +281,7 @@ func _process(delta: float) -> void: # gdlint:disable=max-returns
|
||||
_set_state(ConnectionState.ERROR)
|
||||
return
|
||||
|
||||
handshake_complete.emit(server_version)
|
||||
handshake_complete.emit()
|
||||
_set_state(ConnectionState.CONNECTED)
|
||||
# #646: Request full settings dump on connect — hydrates GameState.ai_enhanced_dialogue_enabled
|
||||
# from server SQLite so the client reflects the authoritative persisted state (D-138).
|
||||
@@ -464,6 +449,15 @@ func receive_bytes(bytes: PackedByteArray) -> void:
|
||||
and _last_snapshot.get("settings_response") != null
|
||||
):
|
||||
snapshot["settings_response"] = _last_snapshot["settings_response"]
|
||||
# #872: Carry forward bookmark_catalog (one-shot, consumed by main_menu._on_snapshot_received_for_catalog).
|
||||
# Server sends catalog on tick 0 and after RequestBookmarkCatalog. If tick 0 and tick 1
|
||||
# arrive in the same TCP batch, the inner receive loop overwrites _last_snapshot and the
|
||||
# catalog is silently lost — this carry-forward prevents that race.
|
||||
if (
|
||||
snapshot.get("bookmark_catalog") == null
|
||||
and _last_snapshot.get("bookmark_catalog") != null
|
||||
):
|
||||
snapshot["bookmark_catalog"] = _last_snapshot["bookmark_catalog"]
|
||||
_last_snapshot = snapshot
|
||||
|
||||
|
||||
|
||||
@@ -9,13 +9,6 @@ extends Node
|
||||
## Unit enum variants (no data) → bare strings ("MoveNorth", "Npc")
|
||||
## Data enum variants → single-element maps ({"UsePerceptionMode": "thermal"})
|
||||
|
||||
## Protocol version — must match server PROTOCOL_VERSION in bridge/types.rs.
|
||||
## Reject snapshots where version != this value.
|
||||
## v20: adds settings_response field to ObserverSnapshot (#627, D-138).
|
||||
## v21: adds economy_snapshot field to ObserverSnapshot (#822, D-181).
|
||||
## v23: adds bookmark_catalog field to ObserverSnapshot (#614).
|
||||
const PROTOCOL_VERSION: int = 23
|
||||
|
||||
# -- Decode: bytes from server → GDScript types --------------------------------
|
||||
|
||||
|
||||
@@ -34,17 +27,6 @@ static func decode_snapshot(bytes: PackedByteArray) -> Variant:
|
||||
push_error("Protocol: snapshot missing required fields")
|
||||
return null
|
||||
|
||||
# Version check: reject snapshots from incompatible server
|
||||
var version: Variant = raw.get("version")
|
||||
if version != PROTOCOL_VERSION:
|
||||
push_error(
|
||||
(
|
||||
"Protocol: version mismatch (got %s, expected %s). Server and client are out of sync."
|
||||
% [version, PROTOCOL_VERSION]
|
||||
)
|
||||
)
|
||||
return null
|
||||
|
||||
var entities: Array[Dictionary] = []
|
||||
var raw_entities: Array = raw["entities"]
|
||||
var dropped := 0
|
||||
@@ -67,7 +49,7 @@ static func decode_snapshot(bytes: PackedByteArray) -> Variant:
|
||||
# in any realistic scenario (would require ~29 billion years at 10 ticks/game-minute per D-031).
|
||||
var tick: int = raw["tick"]
|
||||
|
||||
# version already checked above; game_time for HUD display
|
||||
# game_time for HUD display
|
||||
var game_time: Variant = raw.get("game_time")
|
||||
|
||||
# player_facing: FacingDirection is a unit enum → bare string in rmp_serde
|
||||
@@ -223,6 +205,18 @@ static func decode_snapshot(bytes: PackedByteArray) -> Variant:
|
||||
"speaker_entity_id": int(raw_dr.get("speaker_entity_id", -1)),
|
||||
}
|
||||
|
||||
# v8: gauntlet_mode and room_id (#496) — present only in Gauntlet sessions.
|
||||
# gauntlet_mode is a bool flag; room_id is a String room identifier or absent.
|
||||
# Snapshot handler (snapshot_handler.gd) reads these via snapshot.has() guards.
|
||||
var gauntlet_mode: bool = false
|
||||
var raw_gauntlet: Variant = raw.get("gauntlet_mode")
|
||||
if raw_gauntlet == true:
|
||||
gauntlet_mode = true
|
||||
var room_id: Variant = null
|
||||
var raw_room_id: Variant = raw.get("room_id")
|
||||
if raw_room_id is String:
|
||||
room_id = raw_room_id
|
||||
|
||||
# v9: conversation_events (#535, D-078) — overheard NPC-to-NPC dialogue lines.
|
||||
# Each event carries pre-occluded text plus speaker/target attribution.
|
||||
var conversation_events: Array = []
|
||||
@@ -484,7 +478,6 @@ static func decode_snapshot(bytes: PackedByteArray) -> Variant:
|
||||
"tick": tick,
|
||||
"entities": entities,
|
||||
"decode_errors": dropped,
|
||||
"version": version,
|
||||
"game_time": game_time,
|
||||
"player_facing": player_facing,
|
||||
"player_stance": player_stance,
|
||||
@@ -508,6 +501,8 @@ static func decode_snapshot(bytes: PackedByteArray) -> Variant:
|
||||
"current_ticker": current_ticker,
|
||||
"settings_response": settings_response,
|
||||
"bookmark_catalog": bookmark_catalog,
|
||||
"gauntlet_mode": gauntlet_mode,
|
||||
"room_id": room_id,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -272,7 +272,7 @@ func snapshot() -> Dictionary:
|
||||
|
||||
return {
|
||||
"tick": tick,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"game_time":
|
||||
{
|
||||
"day": 0,
|
||||
|
||||
@@ -15,7 +15,7 @@ extends GdUnitTestSuite
|
||||
const MAIN_SCENE = preload("res://scenes/main.tscn")
|
||||
|
||||
var GauntletHUDScript = load("res://ui/gauntlet_hud.gd")
|
||||
var BugReportDialogScript = load("res://ui/bug_report_dialog.gd")
|
||||
const BugReportDialogScene = preload("res://ui/bug_report_dialog.tscn")
|
||||
var _instance: Node = null
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ func before_test() -> void:
|
||||
GameState.pending_recognitions = []
|
||||
GameState.room_id = null
|
||||
GameState.gauntlet_mode = false
|
||||
MetaStack._stack.clear()
|
||||
|
||||
|
||||
func after_test() -> void:
|
||||
@@ -47,7 +48,7 @@ func after_test() -> void:
|
||||
func _make_snapshot_bytes(overrides: Dictionary = {}) -> PackedByteArray:
|
||||
var snapshot := {
|
||||
"tick": overrides.get("tick", 1),
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": overrides.get("entities", [{
|
||||
"entity_id": 1,
|
||||
"x": 10.0,
|
||||
@@ -92,8 +93,10 @@ func _make_gauntlet_hud() -> Control:
|
||||
|
||||
|
||||
func _make_bug_report_dialog() -> Control:
|
||||
var dialog = Control.new()
|
||||
dialog.set_script(BugReportDialogScript)
|
||||
# Instantiate via .tscn — preserves the MetaScreen runtime stack.
|
||||
# (Sprint 36 migrated bug_report_dialog.gd to extends MetaScreen; bare
|
||||
# Control.new() + set_script() no longer satisfies the base contract.)
|
||||
var dialog: Control = BugReportDialogScene.instantiate()
|
||||
auto_free(dialog)
|
||||
add_child(dialog)
|
||||
return dialog
|
||||
@@ -203,13 +206,15 @@ func test_snapshot_without_room_id_shows_no_gauntlet_ui() -> void:
|
||||
var snapshot: Variant = SimBridge._last_snapshot
|
||||
assert_that(snapshot).is_not_null()
|
||||
|
||||
# Snapshot should NOT contain gauntlet fields
|
||||
assert_that(snapshot.has("room_id")).override_failure_message(
|
||||
"Non-gauntlet snapshot must not contain room_id"
|
||||
).is_false()
|
||||
assert_that(snapshot.has("gauntlet_mode")).override_failure_message(
|
||||
"Non-gauntlet snapshot must not contain gauntlet_mode"
|
||||
# Non-gauntlet snapshot: gauntlet fields must be present with default values.
|
||||
# (Protocol.decode_snapshot always decodes gauntlet fields; non-gauntlet
|
||||
# snapshots produce false/null defaults. Check values, not key presence.)
|
||||
assert_that(snapshot.get("gauntlet_mode", false)).override_failure_message(
|
||||
"Non-gauntlet snapshot must decode gauntlet_mode == false"
|
||||
).is_false()
|
||||
assert_that(snapshot.get("room_id")).override_failure_message(
|
||||
"Non-gauntlet snapshot must decode room_id == null"
|
||||
).is_null()
|
||||
|
||||
# Apply to GameState — gauntlet-related state should not exist
|
||||
GameState.apply_snapshot(snapshot)
|
||||
@@ -497,7 +502,7 @@ func test_bug_report_sends_unpause_on_close() -> void:
|
||||
var dialog := _make_bug_report_dialog()
|
||||
dialog.start_capture()
|
||||
SimBridge._test_input_queue.clear()
|
||||
dialog._close()
|
||||
dialog.close()
|
||||
assert_that(dialog.is_active()).is_false()
|
||||
assert_that(SimBridge._test_input_queue.has("Unpause")).override_failure_message(
|
||||
"Closing bug report should send Unpause to server"
|
||||
|
||||
@@ -14,7 +14,7 @@ extends GdUnitTestSuite
|
||||
# Expected ring buffer capacity per spec.
|
||||
const EXPECTED_CAPACITY := 60
|
||||
|
||||
var BugReportDialogScript = load("res://ui/bug_report_dialog.gd")
|
||||
const BugReportDialogScene = preload("res://ui/bug_report_dialog.tscn")
|
||||
|
||||
|
||||
func after_each() -> void:
|
||||
@@ -35,8 +35,10 @@ func after_each() -> void:
|
||||
# -- Helpers -------------------------------------------------------------------
|
||||
|
||||
func _make_dialog() -> Control:
|
||||
var dialog = Control.new()
|
||||
dialog.set_script(BugReportDialogScript)
|
||||
# Instantiate via .tscn — preserves the MetaScreen runtime stack.
|
||||
# (Sprint 36 migrated bug_report_dialog.gd to extends MetaScreen; bare
|
||||
# Control.new() + set_script() no longer satisfies the base contract.)
|
||||
var dialog: Control = BugReportDialogScene.instantiate()
|
||||
auto_free(dialog)
|
||||
add_child(dialog)
|
||||
return dialog
|
||||
@@ -52,7 +54,7 @@ func _make_input(tick: int, action: String = "MoveNorth") -> Dictionary:
|
||||
func _make_snapshot_json(tick: int) -> String:
|
||||
return JSON.stringify({
|
||||
"tick": tick,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
})
|
||||
|
||||
|
||||
@@ -1,317 +0,0 @@
|
||||
## Sprint 19 — Debug visualization overlay (#348)
|
||||
## F3 toggle, world overlays, tick timing graph.
|
||||
## Extends the existing debug_overlay.gd stub.
|
||||
class_name TestDebugOverlaySprint19
|
||||
extends GdUnitTestSuite
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
const DEBUG_SCENE_PATH: String = "res://scenes/main.tscn"
|
||||
const DEBUG_SCRIPT_PATH: String = "res://ui/debug_overlay.gd"
|
||||
|
||||
|
||||
func _make_overlay() -> Control:
|
||||
## Instantiate a standalone DebugOverlay control for unit testing.
|
||||
## Does not require the full main.tscn scene tree.
|
||||
var script := load(DEBUG_SCRIPT_PATH)
|
||||
if script == null:
|
||||
push_warning("TestDebugOverlaySprint19: debug_overlay.gd not found — skip")
|
||||
return null
|
||||
var node := Control.new()
|
||||
node.set_script(script)
|
||||
add_child(node)
|
||||
return node
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Lifecycle
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func before_test() -> void:
|
||||
GameState.visible_entities = []
|
||||
GameState.visible_tiles = []
|
||||
GameState.player_position = Vector2(10.0, 10.0)
|
||||
GameState.player_facing = "North"
|
||||
GameState.player_stance = "Walk"
|
||||
GameState.current_tick = 1
|
||||
GameState.player_knowledge = null
|
||||
|
||||
|
||||
func after_test() -> void:
|
||||
GameState.visible_entities = []
|
||||
GameState.player_knowledge = null
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Script existence
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_debug_overlay_script_exists() -> void:
|
||||
assert_bool(ResourceLoader.exists(DEBUG_SCRIPT_PATH)).override_failure_message(
|
||||
"debug_overlay.gd must exist at res://ui/debug_overlay.gd (#348)"
|
||||
).is_true()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Instantiation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_debug_overlay_instantiates_without_crash() -> void:
|
||||
var ol := _make_overlay()
|
||||
if ol == null: return
|
||||
assert_that(ol).is_not_null()
|
||||
ol.queue_free()
|
||||
|
||||
|
||||
func test_debug_overlay_starts_hidden() -> void:
|
||||
## Overlay starts hidden — only appears when F3 pressed.
|
||||
var ol := _make_overlay()
|
||||
if ol == null: return
|
||||
assert_bool(ol.visible).override_failure_message(
|
||||
"DebugOverlay must start hidden (visible=false)"
|
||||
).is_false()
|
||||
ol.queue_free()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Dev-only guard
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_update_from_state_exists() -> void:
|
||||
var ol := _make_overlay()
|
||||
if ol == null: return
|
||||
assert_bool(ol.has_method("update_from_state")).override_failure_message(
|
||||
"DebugOverlay must have update_from_state() method"
|
||||
).is_true()
|
||||
ol.queue_free()
|
||||
|
||||
|
||||
func test_update_from_state_does_not_crash_when_hidden() -> void:
|
||||
## update_from_state() called while hidden must not crash.
|
||||
var ol := _make_overlay()
|
||||
if ol == null: return
|
||||
ol.visible = false
|
||||
ol.update_from_state() # Should be a no-op, no crash
|
||||
ol.queue_free()
|
||||
|
||||
|
||||
func test_update_from_state_does_not_crash_when_visible() -> void:
|
||||
var ol := _make_overlay()
|
||||
if ol == null: return
|
||||
ol.visible = true
|
||||
# Simulate a minimal snapshot tick
|
||||
GameState.current_tick = 42
|
||||
ol.update_from_state()
|
||||
ol.queue_free()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# NPC path tracking
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_npc_paths_field_exists() -> void:
|
||||
var ol := _make_overlay()
|
||||
if ol == null: return
|
||||
assert_bool(ol.has("_npc_paths")).override_failure_message(
|
||||
"DebugOverlay must have _npc_paths field for NPC movement history"
|
||||
).is_true()
|
||||
ol.queue_free()
|
||||
|
||||
|
||||
func test_npc_paths_updated_on_state_update() -> void:
|
||||
## After update_from_state with an NPC entity, _npc_paths should have an entry.
|
||||
var ol := _make_overlay()
|
||||
if ol == null: return
|
||||
ol.visible = true
|
||||
|
||||
GameState.visible_entities = [{
|
||||
"entity_id": 2,
|
||||
"x": 12.0, "y": 9.0, "z": 0,
|
||||
"kind": {"variant": "Npc", "data": null},
|
||||
"relationship": "Unknown",
|
||||
}]
|
||||
GameState.current_tick = 100
|
||||
ol.update_from_state()
|
||||
assert_int(ol._npc_paths.size()).override_failure_message(
|
||||
"_npc_paths must record NPC positions from visible_entities"
|
||||
).is_greater(0)
|
||||
ol.queue_free()
|
||||
|
||||
|
||||
func test_npc_paths_not_populated_for_player_entity() -> void:
|
||||
## Player entities must not appear in NPC path history.
|
||||
var ol := _make_overlay()
|
||||
if ol == null: return
|
||||
ol.visible = true
|
||||
GameState.visible_entities = [{
|
||||
"entity_id": 1,
|
||||
"x": 10.0, "y": 10.0, "z": 0,
|
||||
"kind": {"variant": "Player", "data": null},
|
||||
}]
|
||||
GameState.current_tick = 101
|
||||
ol.update_from_state()
|
||||
assert_int(ol._npc_paths.size()).override_failure_message(
|
||||
"Player entity must not appear in _npc_paths"
|
||||
).is_equal(0)
|
||||
ol.queue_free()
|
||||
|
||||
|
||||
func test_npc_paths_max_length_respected() -> void:
|
||||
## Path history must not grow beyond NPC_HISTORY_LEN entries.
|
||||
var ol := _make_overlay()
|
||||
if ol == null: return
|
||||
ol.visible = true
|
||||
# Simulate NPC moving each tick — inject 20 ticks of movement
|
||||
for i in range(20):
|
||||
GameState.visible_entities = [{
|
||||
"entity_id": 5,
|
||||
"x": float(12 + i), "y": 9.0, "z": 0,
|
||||
"kind": {"variant": "Npc", "data": null},
|
||||
"relationship": "Unknown",
|
||||
}]
|
||||
GameState.current_tick = 200 + i
|
||||
ol.update_from_state()
|
||||
var path: Array = ol._npc_paths.get(5, [])
|
||||
assert_int(path.size()).override_failure_message(
|
||||
"NPC path must not exceed NPC_HISTORY_LEN entries (cap at %d)" % ol.NPC_HISTORY_LEN
|
||||
).is_less_equal(ol.NPC_HISTORY_LEN)
|
||||
ol.queue_free()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tick timing ring
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_tick_deltas_field_exists() -> void:
|
||||
var ol := _make_overlay()
|
||||
if ol == null: return
|
||||
assert_bool(ol.has("_tick_deltas")).override_failure_message(
|
||||
"DebugOverlay must have _tick_deltas field for timing sparkline"
|
||||
).is_true()
|
||||
ol.queue_free()
|
||||
|
||||
|
||||
func test_tick_deltas_accumulate_over_state_updates() -> void:
|
||||
## Each new tick snapshot should add a delta to _tick_deltas.
|
||||
var ol := _make_overlay()
|
||||
if ol == null: return
|
||||
ol.visible = true
|
||||
for i in range(5):
|
||||
GameState.current_tick = 300 + i
|
||||
ol.update_from_state()
|
||||
assert_int(ol._tick_deltas.size()).override_failure_message(
|
||||
"_tick_deltas must accumulate entries from successive ticks"
|
||||
).is_greater(0)
|
||||
ol.queue_free()
|
||||
|
||||
|
||||
func test_tick_deltas_max_length_respected() -> void:
|
||||
## _tick_deltas must not grow beyond TICK_HISTORY_LEN.
|
||||
var ol := _make_overlay()
|
||||
if ol == null: return
|
||||
ol.visible = true
|
||||
for i in range(50):
|
||||
GameState.current_tick = 400 + i
|
||||
ol.update_from_state()
|
||||
assert_int(ol._tick_deltas.size()).override_failure_message(
|
||||
"_tick_deltas must not exceed TICK_HISTORY_LEN entries"
|
||||
).is_less_equal(ol.TICK_HISTORY_LEN)
|
||||
ol.queue_free()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Constants defined
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_npc_history_len_constant_exists() -> void:
|
||||
var ol := _make_overlay()
|
||||
if ol == null: return
|
||||
assert_bool(ol.has("NPC_HISTORY_LEN")).override_failure_message(
|
||||
"DebugOverlay must have NPC_HISTORY_LEN constant"
|
||||
).is_true()
|
||||
ol.queue_free()
|
||||
|
||||
|
||||
func test_tick_history_len_constant_exists() -> void:
|
||||
var ol := _make_overlay()
|
||||
if ol == null: return
|
||||
assert_bool(ol.has("TICK_HISTORY_LEN")).override_failure_message(
|
||||
"DebugOverlay must have TICK_HISTORY_LEN constant"
|
||||
).is_true()
|
||||
ol.queue_free()
|
||||
|
||||
|
||||
func test_tick_warn_ms_constant_defined() -> void:
|
||||
var ol := _make_overlay()
|
||||
if ol == null: return
|
||||
assert_bool(ol.has("TICK_WARN_MS")).override_failure_message(
|
||||
"DebugOverlay must have TICK_WARN_MS constant for sparkline warning threshold"
|
||||
).is_true()
|
||||
ol.queue_free()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Facing angle helper
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_facing_to_angle_north() -> void:
|
||||
## North = -PI/2 in Godot 2D (up on screen)
|
||||
var angle := _fetch_facing_angle("North")
|
||||
assert_float(angle).override_failure_message(
|
||||
"_facing_to_angle('North') must return -PI/2"
|
||||
).is_equal_approx(-PI / 2.0, 0.001)
|
||||
|
||||
|
||||
func test_facing_to_angle_east() -> void:
|
||||
var angle := _fetch_facing_angle("East")
|
||||
assert_float(angle).is_equal_approx(0.0, 0.001)
|
||||
|
||||
|
||||
func test_facing_to_angle_south() -> void:
|
||||
var angle := _fetch_facing_angle("South")
|
||||
assert_float(angle).is_equal_approx(PI / 2.0, 0.001)
|
||||
|
||||
|
||||
func test_facing_to_angle_west() -> void:
|
||||
var angle := _fetch_facing_angle("West")
|
||||
assert_float(angle).is_equal_approx(PI, 0.001)
|
||||
|
||||
|
||||
func _fetch_facing_angle(facing: String) -> float:
|
||||
## Helper: load script and call static method.
|
||||
var script = load(DEBUG_SCRIPT_PATH)
|
||||
if script == null:
|
||||
return 0.0
|
||||
# In GDScript 4, static methods can be called via an instance
|
||||
var tmp := Control.new()
|
||||
tmp.set_script(script)
|
||||
add_child(tmp)
|
||||
var result := tmp._facing_to_angle(facing)
|
||||
tmp.queue_free()
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# In-scene placement: DebugOverlay on UILayer
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_debug_overlay_in_main_scene_ui_layer() -> void:
|
||||
## DebugOverlay must be in UILayer (CanvasLayer 20), not InsertOverlay.
|
||||
if not ResourceLoader.exists("res://scenes/main.tscn"):
|
||||
push_warning("TestDebugOverlaySprint19: main.tscn not found — skip")
|
||||
return
|
||||
var scene: Node = load("res://scenes/main.tscn").instantiate()
|
||||
auto_free(scene)
|
||||
add_child(scene)
|
||||
var ui_layer := scene.get_node_or_null("UILayer")
|
||||
assert_that(ui_layer != null).override_failure_message(
|
||||
"UILayer must exist in main.tscn"
|
||||
).is_true()
|
||||
if ui_layer == null: return
|
||||
var overlay := ui_layer.get_node_or_null("DebugOverlay")
|
||||
assert_that(overlay != null).override_failure_message(
|
||||
"DebugOverlay must be a child of UILayer in main.tscn (#348)"
|
||||
).is_true()
|
||||
@@ -1 +0,0 @@
|
||||
uid://bdsgybncfyu52
|
||||
@@ -392,18 +392,16 @@ func test_gamestate_examine_result_entity_id_survives_roundtrip() -> void:
|
||||
## Note: dialogue_box.gd has no class_name — call _escape_bbcode via instance.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func skip_test_escape_bbcode_brackets_in_server_text() -> void:
|
||||
func test_escape_bbcode_brackets_in_server_text() -> void:
|
||||
## _escape_bbcode must convert '[' to '[lb]' to prevent BBCode injection.
|
||||
## BROKEN (#866): chained replace('[', '[lb]').replace(']', '[rb]') corrupts the
|
||||
## [lb] escape — result is [lb[rb]...] instead of [lb]...]]. Bug filed.
|
||||
## Regression test: a malicious NPC name like "[wave]Evil[/wave]" must render
|
||||
## as plain text in the dialogue log.
|
||||
## Fix (#866): only escape '[' — unmatched ']' renders as a literal in RichTextLabel.
|
||||
## Exact expected output: "[lb]wave]Evil NPC[lb]/wave]"
|
||||
## RichTextLabel interprets [lb] as literal '[', and bare ']' as literal ']',
|
||||
## so the rendered output is the plain string "[wave]Evil NPC[/wave]" — no BBCode parsed.
|
||||
var box := _make_dialogue_box()
|
||||
if box == null: return
|
||||
var escaped: String = box._escape_bbcode("[wave]Evil NPC[/wave]")
|
||||
assert_that(escaped).is_not_equal("[wave]Evil NPC[/wave]")
|
||||
assert_that(escaped).contains("[lb]")
|
||||
assert_bool(escaped.begins_with("[")).is_false()
|
||||
assert_that(escaped).is_equal("[lb]wave]Evil NPC[lb]/wave]")
|
||||
box.queue_free()
|
||||
|
||||
|
||||
|
||||
@@ -1,238 +0,0 @@
|
||||
## Sprint 22 — Entanglement ratio configuration acceptance tests (#175, #178)
|
||||
##
|
||||
## Test-first stubs for the client-side surface of the world_seed feature.
|
||||
## These tests will warn-and-skip until the implementation lands (Tyre, #175).
|
||||
##
|
||||
## Client-side acceptance criteria (#175):
|
||||
## - GameState carries a world_seed field (stores the seed for this session)
|
||||
## - SessionManager.new_game() generates and stores a world_seed
|
||||
## - The IPC startup payload carries world_seed so the server can seed SimRng
|
||||
##
|
||||
## Server-side acceptance criteria (#178) are in:
|
||||
## - server/src/content/entanglement.rs (Rust unit tests)
|
||||
##
|
||||
## Spec: D-029 (30/50/20 entanglement ratio, variable per seed), D-010 (deterministic sim)
|
||||
## Tickets: #175, #178
|
||||
class_name TestEntanglementSprint22
|
||||
extends GdUnitTestSuite
|
||||
|
||||
|
||||
# -- Client-side: GameState.world_seed field (#175) ---------------------------
|
||||
|
||||
func test_game_state_has_world_seed_field() -> void:
|
||||
# #175 client-side: GameState must store the world_seed for this session.
|
||||
# The seed is set by SessionManager.new_game() and read by SimBridge to
|
||||
# carry it in the session startup IPC message.
|
||||
if not "world_seed" in GameState:
|
||||
push_warning("TestEntanglementSprint22: GameState.world_seed not found — test-first stub (awaiting #175)")
|
||||
return
|
||||
# Field exists — verify it is numeric (int or null are both acceptable initial states)
|
||||
var seed_val = GameState.get("world_seed")
|
||||
assert_bool(seed_val == null or seed_val is int).override_failure_message(
|
||||
"GameState.world_seed must be int or null"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_game_state_world_seed_can_be_set_and_read() -> void:
|
||||
if not "world_seed" in GameState:
|
||||
push_warning("TestEntanglementSprint22: GameState.world_seed missing — skipped (#175 not yet implemented)")
|
||||
return
|
||||
var orig = GameState.get("world_seed")
|
||||
GameState.world_seed = 0xDEADBEEF
|
||||
assert_int(GameState.world_seed).is_equal(0xDEADBEEF)
|
||||
# Restore
|
||||
GameState.world_seed = orig
|
||||
|
||||
|
||||
func test_game_state_world_seed_default_is_null_or_zero() -> void:
|
||||
# Before a session starts, world_seed should be null (no session) or 0 (unset).
|
||||
if not "world_seed" in GameState:
|
||||
push_warning("TestEntanglementSprint22: GameState.world_seed missing — skipped")
|
||||
return
|
||||
var seed_val = GameState.get("world_seed")
|
||||
assert_bool(seed_val == null or seed_val == 0).override_failure_message(
|
||||
"GameState.world_seed should be null or 0 before any session starts"
|
||||
).is_true()
|
||||
|
||||
|
||||
# -- Client-side: SessionManager seed generation (#175) -----------------------
|
||||
|
||||
func test_session_manager_exists() -> void:
|
||||
var sm = get_node_or_null("/root/SessionManager")
|
||||
if sm == null:
|
||||
push_warning("TestEntanglementSprint22: SessionManager autoload not found — skipped")
|
||||
return
|
||||
assert_that(sm).is_not_null()
|
||||
|
||||
|
||||
func test_session_manager_new_game_generates_world_seed() -> void:
|
||||
# #175: new_game() must generate and store world_seed in GameState.
|
||||
# The seed is a non-zero u64 that will be sent to the server on startup.
|
||||
var sm = get_node_or_null("/root/SessionManager")
|
||||
if sm == null:
|
||||
push_warning("TestEntanglementSprint22: SessionManager not found — skipped")
|
||||
return
|
||||
if not "world_seed" in GameState:
|
||||
push_warning("TestEntanglementSprint22: GameState.world_seed missing — test-first stub")
|
||||
return
|
||||
|
||||
# Call new_game() (will create a save dir — acceptable in test environment)
|
||||
var orig_seed = GameState.get("world_seed")
|
||||
var orig_game_id: String = GameState.current_game_id
|
||||
sm.new_game()
|
||||
var generated_seed = GameState.get("world_seed")
|
||||
|
||||
# world_seed must have been set to a non-null, non-zero value
|
||||
assert_bool(generated_seed != null).override_failure_message(
|
||||
"SessionManager.new_game() must set GameState.world_seed (#175)"
|
||||
).is_true()
|
||||
if generated_seed != null:
|
||||
assert_bool(generated_seed != 0).override_failure_message(
|
||||
"Generated world_seed must be non-zero"
|
||||
).is_true()
|
||||
|
||||
# Restore state
|
||||
GameState.current_game_id = orig_game_id
|
||||
GameState.world_seed = orig_seed
|
||||
|
||||
|
||||
func test_session_manager_same_game_id_has_same_seed() -> void:
|
||||
# Resuming a session must restore the original world_seed (not generate a new one).
|
||||
# This ensures deterministic replays work correctly (D-010).
|
||||
var sm = get_node_or_null("/root/SessionManager")
|
||||
if sm == null:
|
||||
push_warning("TestEntanglementSprint22: SessionManager not found — skipped")
|
||||
return
|
||||
if not sm.has_method("resume_game"):
|
||||
push_warning("TestEntanglementSprint22: resume_game() missing — skipped")
|
||||
return
|
||||
if not "world_seed" in GameState:
|
||||
push_warning("TestEntanglementSprint22: GameState.world_seed missing — test-first stub")
|
||||
return
|
||||
|
||||
# Set a known seed and game_id, then resume — seed must not be clobbered
|
||||
GameState.world_seed = 12345678
|
||||
var orig_game_id: String = GameState.current_game_id
|
||||
sm.resume_game("20260228-120000-abc123")
|
||||
# resume_game() must NOT overwrite world_seed
|
||||
assert_int(GameState.world_seed).override_failure_message(
|
||||
"resume_game() must not overwrite world_seed — seed is loaded from the save, not regenerated"
|
||||
).is_equal(12345678)
|
||||
GameState.current_game_id = orig_game_id
|
||||
|
||||
|
||||
# -- IPC startup message: world_seed field (#175) ----------------------------
|
||||
|
||||
func test_protocol_encode_startup_message_has_world_seed_field() -> void:
|
||||
# #175 acceptance: startup IPC message must carry "world_seed" key.
|
||||
# Verifies Protocol.encode_startup_message encodes the seed so the server
|
||||
# can deserialize it as StartupMessage { world_seed: u64 }.
|
||||
var seed: int = 0xDEADBEEF # 3735928559 — fits in u32, safely maps to Rust u64
|
||||
var bytes: PackedByteArray = Protocol.encode_startup_message(seed)
|
||||
assert_bool(bytes.size() > 0).override_failure_message(
|
||||
"Protocol.encode_startup_message must return non-empty bytes"
|
||||
).is_true()
|
||||
var decoded = Messagepack.decode(bytes)
|
||||
assert_that(decoded.status).override_failure_message(
|
||||
"encode_startup_message output must be valid msgpack: %s" % str(decoded.status)
|
||||
).is_null()
|
||||
var msg = decoded.value
|
||||
assert_bool(msg is Dictionary and msg.has("world_seed")).override_failure_message(
|
||||
"StartupMessage wire payload must contain 'world_seed' key, got: %s" % str(msg)
|
||||
).is_true()
|
||||
assert_int(msg["world_seed"]).override_failure_message(
|
||||
"world_seed must round-trip through msgpack unchanged"
|
||||
).is_equal(seed)
|
||||
|
||||
|
||||
func test_protocol_encode_startup_message_zero_seed() -> void:
|
||||
# Edge case: seed=0 must still encode a valid payload (world_seed: 0).
|
||||
var bytes: PackedByteArray = Protocol.encode_startup_message(0)
|
||||
assert_bool(bytes.size() > 0).is_true()
|
||||
var decoded = Messagepack.decode(bytes)
|
||||
assert_that(decoded.status).is_null()
|
||||
assert_int(decoded.value["world_seed"]).is_equal(0)
|
||||
|
||||
|
||||
func test_sim_bridge_can_send_world_seed_in_startup() -> void:
|
||||
# #175 acceptance: "startup IPC message carries a world_seed field"
|
||||
# The client must be able to include world_seed in the session startup payload.
|
||||
# Test-first: verify the API exists (method or field), else warn-and-skip.
|
||||
var sim_bridge = get_node_or_null("/root/SimBridge")
|
||||
if sim_bridge == null:
|
||||
push_warning("TestEntanglementSprint22: SimBridge not found — skipped")
|
||||
return
|
||||
|
||||
# Option A: SimBridge has a world_seed property that is sent during startup
|
||||
if "world_seed" in sim_bridge:
|
||||
sim_bridge.world_seed = 99999
|
||||
assert_int(sim_bridge.world_seed).is_equal(99999)
|
||||
sim_bridge.world_seed = 0
|
||||
return
|
||||
|
||||
# Option B: SimBridge has a set_world_seed() method
|
||||
if sim_bridge.has_method("set_world_seed"):
|
||||
# Method exists — this is the expected API
|
||||
sim_bridge.set_world_seed(99999)
|
||||
return
|
||||
|
||||
# Neither found — test-first stub
|
||||
push_warning(
|
||||
"TestEntanglementSprint22: SimBridge has no world_seed field or set_world_seed() — " +
|
||||
"test-first stub awaiting #175 implementation"
|
||||
)
|
||||
|
||||
|
||||
# -- Protocol: world_seed flows from client to server (#175) ------------------
|
||||
|
||||
func test_apply_snapshot_does_not_clobber_world_seed() -> void:
|
||||
# world_seed is set at session start and must persist across all subsequent snapshots.
|
||||
# Snapshots must not overwrite or clear the world_seed that was set at startup.
|
||||
if not "world_seed" in GameState:
|
||||
push_warning("TestEntanglementSprint22: GameState.world_seed missing — test-first stub")
|
||||
return
|
||||
GameState.world_seed = 42000
|
||||
GameState.apply_snapshot({"tick": 5, "visible_tiles": []})
|
||||
assert_int(GameState.world_seed).override_failure_message(
|
||||
"apply_snapshot() must not clear or overwrite world_seed — seed is set once at session start"
|
||||
).is_equal(42000)
|
||||
GameState.world_seed = null
|
||||
|
||||
|
||||
# -- Seed variation property (#178, informational — full test is Rust-side) ---
|
||||
|
||||
func test_different_seeds_produce_different_configs_informational() -> void:
|
||||
# D-029: "entanglement rate varies per seed to prevent metagaming calibration"
|
||||
# The definitive acceptance test for this is Rust-side (server/src/content/entanglement.rs):
|
||||
# - EntanglementConfig::from_rng(seed_A) == EntanglementConfig::from_rng(seed_A) [deterministic]
|
||||
# - EntanglementConfig::from_rng(seed_A) != EntanglementConfig::from_rng(seed_B) [variable, >=90%]
|
||||
#
|
||||
# This test only verifies the client side: world_seed is a u64 large enough to
|
||||
# have sufficient entropy. A 24-bit game_id hex component alone has 16M combinations;
|
||||
# the full u64 seed provides 2^64 possibilities.
|
||||
#
|
||||
# We verify that two calls to new_game() produce different seeds.
|
||||
var sm = get_node_or_null("/root/SessionManager")
|
||||
if sm == null:
|
||||
push_warning("TestEntanglementSprint22: SessionManager not found — skipped")
|
||||
return
|
||||
if not "world_seed" in GameState:
|
||||
push_warning("TestEntanglementSprint22: GameState.world_seed missing — test-first stub")
|
||||
return
|
||||
|
||||
var orig_game_id: String = GameState.current_game_id
|
||||
sm.new_game()
|
||||
var seed_a = GameState.get("world_seed")
|
||||
sm.new_game()
|
||||
var seed_b = GameState.get("world_seed")
|
||||
|
||||
if seed_a == null or seed_b == null:
|
||||
push_warning("TestEntanglementSprint22: new_game() did not set world_seed — test-first stub")
|
||||
GameState.current_game_id = orig_game_id
|
||||
return
|
||||
|
||||
# Two different sessions should produce different seeds
|
||||
assert_bool(seed_a != seed_b).override_failure_message(
|
||||
"Two calls to new_game() must produce different world_seeds (D-029 anti-metagaming)"
|
||||
).is_true()
|
||||
GameState.current_game_id = orig_game_id
|
||||
@@ -1 +0,0 @@
|
||||
uid://c1dnlbnxtgqqo
|
||||
@@ -1,652 +0,0 @@
|
||||
## Sprint 22 — Fog system acceptance tests (#569)
|
||||
##
|
||||
## Validates FogState data management against the Sprint 22 acceptance criteria:
|
||||
## - Explored tiles never revert to unexplored black (EXP_EXPLORED persistence)
|
||||
## - Bounds grow-only invariant (explored tiles behind player stay in texture)
|
||||
## - All visible tiles written as Forward (server simplified to Forward-only)
|
||||
## - Exploration data survives texture resize (grow-only bounds copy)
|
||||
## - Shader file present with correct fog_alpha constant
|
||||
##
|
||||
## Spec: D-059 (fog shader), D-015 (vision cone), D-066 (dual-scale grid, 6-8 tile gradient)
|
||||
## Ticket: #569
|
||||
class_name TestFogSprint22
|
||||
extends GdUnitTestSuite
|
||||
|
||||
|
||||
func _get_fog_state() -> Node:
|
||||
var node = get_node_or_null("/root/FogState")
|
||||
if node == null:
|
||||
push_warning("TestFogSprint22: FogState autoload not found — test skipped (awaiting #569)")
|
||||
return node
|
||||
|
||||
|
||||
func before_test() -> void:
|
||||
GameState.visible_positions.clear()
|
||||
GameState.visible_tiles.clear()
|
||||
GameState.visibility_sectors.clear()
|
||||
GameState.boundary_positions.clear()
|
||||
|
||||
|
||||
func after_test() -> void:
|
||||
GameState.visible_positions.clear()
|
||||
GameState.visible_tiles.clear()
|
||||
GameState.visibility_sectors.clear()
|
||||
GameState.boundary_positions.clear()
|
||||
|
||||
|
||||
# -- Spec constants (D-059) ---------------------------------------------------
|
||||
|
||||
func test_exp_explored_constant_is_128() -> void:
|
||||
# EXP_EXPLORED = 128 → shader reads this as ~0.502.
|
||||
# smoothstep(0.0, 0.2, 0.502) = 1.0 → exp_fade fully applied.
|
||||
# If EXP_EXPLORED were 0, explored tiles would render as solid unexplored black.
|
||||
var fog_state = _get_fog_state()
|
||||
if fog_state == null:
|
||||
return
|
||||
assert_int(fog_state.EXP_EXPLORED).override_failure_message(
|
||||
"EXP_EXPLORED must be 128 — shader exp_fade requires explored value > 0.2 to avoid unexplored-black rendering"
|
||||
).is_equal(128)
|
||||
|
||||
|
||||
func test_exp_unexplored_constant_is_0() -> void:
|
||||
var fog_state = _get_fog_state()
|
||||
if fog_state == null:
|
||||
return
|
||||
assert_int(fog_state.EXP_UNEXPLORED).is_equal(0)
|
||||
|
||||
|
||||
func test_exp_visible_constant_is_255() -> void:
|
||||
# EXP_VISIBLE = 255 → shader reads 1.0, full art visibility (currently in LOS)
|
||||
var fog_state = _get_fog_state()
|
||||
if fog_state == null:
|
||||
return
|
||||
assert_int(fog_state.EXP_VISIBLE).is_equal(255)
|
||||
|
||||
|
||||
func test_vis_forward_constant_is_255() -> void:
|
||||
# D-059: VIS_FORWARD = 255 → clear vision, nearly transparent fog overlay
|
||||
var fog_state = _get_fog_state()
|
||||
if fog_state == null:
|
||||
return
|
||||
assert_int(fog_state.VIS_FORWARD).is_equal(255)
|
||||
|
||||
|
||||
func test_vis_hidden_constant_is_0() -> void:
|
||||
# D-059: VIS_HIDDEN = 0 → no vision, fog fully opaque
|
||||
var fog_state = _get_fog_state()
|
||||
if fog_state == null:
|
||||
return
|
||||
assert_int(fog_state.VIS_HIDDEN).is_equal(0)
|
||||
|
||||
|
||||
func test_unexplored_color_spec_value() -> void:
|
||||
# D-059: Unexplored = solid near-black #12141a
|
||||
# Verify the hex value decodes to the expected channel values.
|
||||
var c := Color("#12141a")
|
||||
assert_float(c.r).is_equal_approx(18.0 / 255.0, 0.003)
|
||||
assert_float(c.g).is_equal_approx(20.0 / 255.0, 0.003)
|
||||
assert_float(c.b).is_equal_approx(26.0 / 255.0, 0.003)
|
||||
# Sanity: it IS very dark (all channels < 0.12)
|
||||
assert_float(c.r).is_less(0.12)
|
||||
assert_float(c.g).is_less(0.12)
|
||||
assert_float(c.b).is_less(0.12)
|
||||
|
||||
|
||||
# -- Acceptance: explored tiles persist after leaving LOS (criterion 3) ------
|
||||
|
||||
func test_explored_tile_becomes_exp_explored_after_leaving_los() -> void:
|
||||
# ACCEPTANCE CRITERION: "Explored tiles never revert to unexplored black"
|
||||
# When tile (5,5) was in LOS (frame 1) and then leaves LOS (frame 2),
|
||||
# its exploration byte must be EXP_EXPLORED (128), not EXP_UNEXPLORED (0).
|
||||
var fog_state = _get_fog_state()
|
||||
if fog_state == null:
|
||||
return
|
||||
if not fog_state.has_method("update_from_state"):
|
||||
push_warning("TestFogSprint22: update_from_state missing — skipped")
|
||||
return
|
||||
|
||||
# Frame 1: tile (5,5) is visible
|
||||
GameState.visible_positions = {Vector2i(5, 5): true}
|
||||
GameState.visible_tiles = [{"x": 5, "y": 5, "z": 0, "visibility": "Forward"}]
|
||||
fog_state.update_from_state()
|
||||
|
||||
# Frame 2: tile (5,5) leaves LOS
|
||||
GameState.visible_positions.clear()
|
||||
GameState.visible_tiles = []
|
||||
fog_state.update_from_state()
|
||||
|
||||
# Internal state check: _exp_bytes[tile(5,5)] must be EXP_EXPLORED (128)
|
||||
var exp_bytes = fog_state.get("_exp_bytes")
|
||||
if exp_bytes == null:
|
||||
push_warning("TestFogSprint22: _exp_bytes not accessible — data path untestable headlessly")
|
||||
return
|
||||
var ox: int = fog_state.map_bounds.position.x
|
||||
var oy: int = fog_state.map_bounds.position.y
|
||||
var w: int = fog_state.get("_width") if fog_state.get("_width") != null else -1
|
||||
if w <= 0:
|
||||
push_warning("TestFogSprint22: _width inaccessible — data path untestable")
|
||||
return
|
||||
var px := 5 - ox
|
||||
var py := 5 - oy
|
||||
if px < 0 or py < 0 or px >= w:
|
||||
push_warning("TestFogSprint22: tile (5,5) out of bounds after update — check grow_bounds margin")
|
||||
return
|
||||
var idx := py * w + px
|
||||
if idx < 0 or idx >= exp_bytes.size():
|
||||
push_warning("TestFogSprint22: idx %d out of exp_bytes range %d" % [idx, exp_bytes.size()])
|
||||
return
|
||||
assert_int(exp_bytes[idx]).override_failure_message(
|
||||
"Tile (5,5) must be EXP_EXPLORED=128 after leaving LOS — not EXP_UNEXPLORED=0 (#569 regression)"
|
||||
).is_equal(fog_state.EXP_EXPLORED)
|
||||
|
||||
|
||||
func test_explored_tile_is_exp_visible_while_in_los() -> void:
|
||||
# While in LOS, tile exploration byte must be EXP_VISIBLE (255)
|
||||
var fog_state = _get_fog_state()
|
||||
if fog_state == null:
|
||||
return
|
||||
if not fog_state.has_method("update_from_state"):
|
||||
return
|
||||
|
||||
GameState.visible_positions = {Vector2i(3, 3): true}
|
||||
GameState.visible_tiles = [{"x": 3, "y": 3, "z": 0, "visibility": "Forward"}]
|
||||
fog_state.update_from_state()
|
||||
|
||||
var exp_bytes = fog_state.get("_exp_bytes")
|
||||
if exp_bytes == null:
|
||||
return
|
||||
var ox: int = fog_state.map_bounds.position.x
|
||||
var oy: int = fog_state.map_bounds.position.y
|
||||
var w: int = fog_state.get("_width") if fog_state.get("_width") != null else -1
|
||||
if w <= 0:
|
||||
return
|
||||
var px := 3 - ox
|
||||
var py := 3 - oy
|
||||
if px < 0 or py < 0 or px >= w:
|
||||
return
|
||||
var idx := py * w + px
|
||||
if idx >= 0 and idx < exp_bytes.size():
|
||||
assert_int(exp_bytes[idx]).is_equal(fog_state.EXP_VISIBLE)
|
||||
|
||||
|
||||
func test_unexplored_tile_stays_exp_unexplored() -> void:
|
||||
# Tile (7, 8) was never seen — must remain EXP_UNEXPLORED (0)
|
||||
var fog_state = _get_fog_state()
|
||||
if fog_state == null:
|
||||
return
|
||||
if not fog_state.has_method("update_from_state"):
|
||||
return
|
||||
|
||||
# See only (5, 5) — tile (7, 8) is not in LOS
|
||||
GameState.visible_positions = {Vector2i(5, 5): true}
|
||||
GameState.visible_tiles = [{"x": 5, "y": 5, "z": 0, "visibility": "Forward"}]
|
||||
fog_state.update_from_state()
|
||||
|
||||
var exp_bytes = fog_state.get("_exp_bytes")
|
||||
if exp_bytes == null:
|
||||
return
|
||||
var ox: int = fog_state.map_bounds.position.x
|
||||
var oy: int = fog_state.map_bounds.position.y
|
||||
var w: int = fog_state.get("_width") if fog_state.get("_width") != null else -1
|
||||
if w <= 0:
|
||||
return
|
||||
var px := 7 - ox
|
||||
var py := 8 - oy
|
||||
if px < 0 or py < 0 or px >= w:
|
||||
return
|
||||
var idx := py * w + px
|
||||
if idx >= 0 and idx < exp_bytes.size():
|
||||
assert_int(exp_bytes[idx]).is_equal(fog_state.EXP_UNEXPLORED)
|
||||
|
||||
|
||||
# -- Acceptance: bounds grow-only invariant ------------------------------------
|
||||
|
||||
func test_bounds_never_shrink() -> void:
|
||||
# ACCEPTANCE CRITERION: "Explored tiles never revert to unexplored black"
|
||||
# Requires grow-only bounds: once a tile is in the texture, it stays there.
|
||||
var fog_state = _get_fog_state()
|
||||
if fog_state == null:
|
||||
return
|
||||
if not fog_state.has_method("update_from_state"):
|
||||
return
|
||||
|
||||
# Frame 1: see (10, 10) → establishes initial bounds
|
||||
GameState.visible_positions = {Vector2i(10, 10): true}
|
||||
GameState.visible_tiles = [{"x": 10, "y": 10, "z": 0, "visibility": "Forward"}]
|
||||
fog_state.update_from_state()
|
||||
var b1: Rect2i = fog_state.map_bounds
|
||||
|
||||
# Frame 2: see (30, 30) → bounds must expand to include both
|
||||
GameState.visible_positions = {Vector2i(30, 30): true}
|
||||
GameState.visible_tiles = [{"x": 30, "y": 30, "z": 0, "visibility": "Forward"}]
|
||||
fog_state.update_from_state()
|
||||
var b2: Rect2i = fog_state.map_bounds
|
||||
|
||||
# Frame 3: back to (10, 10) → bounds must NOT shrink
|
||||
GameState.visible_positions = {Vector2i(10, 10): true}
|
||||
GameState.visible_tiles = [{"x": 10, "y": 10, "z": 0, "visibility": "Forward"}]
|
||||
fog_state.update_from_state()
|
||||
var b3: Rect2i = fog_state.map_bounds
|
||||
|
||||
assert_bool(b2.size.x >= b1.size.x).override_failure_message(
|
||||
"Bounds must grow when player moves to larger region"
|
||||
).is_true()
|
||||
assert_bool(b2.size.y >= b1.size.y).is_true()
|
||||
assert_bool(b3.size.x >= b2.size.x).override_failure_message(
|
||||
"Bounds must not shrink when player returns to previous position (grow-only invariant)"
|
||||
).is_true()
|
||||
assert_bool(b3.size.y >= b2.size.y).is_true()
|
||||
|
||||
|
||||
func test_bounds_include_margin_for_gradient_bleed() -> void:
|
||||
# D-066: 6-8 tile gradient at cone edge requires texture margin.
|
||||
# _grow_bounds adds 8-tile margin on each side (accommodates 7x7 Gaussian
|
||||
# kernel at 2-texel intervals = ±6 tile reach). After seeing (10,10),
|
||||
# bounds should extend at least 4 tiles beyond the visible tile.
|
||||
var fog_state = _get_fog_state()
|
||||
if fog_state == null:
|
||||
return
|
||||
if not fog_state.has_method("update_from_state"):
|
||||
return
|
||||
|
||||
GameState.visible_positions = {Vector2i(10, 10): true}
|
||||
GameState.visible_tiles = [{"x": 10, "y": 10, "z": 0, "visibility": "Forward"}]
|
||||
fog_state.update_from_state()
|
||||
|
||||
var b: Rect2i = fog_state.map_bounds
|
||||
# With 4-tile margin: bounds.position.x <= 10 - 4 = 6
|
||||
assert_bool(b.position.x <= 6).override_failure_message(
|
||||
"FogState bounds must include 4-tile margin for gradient bleed (D-066 gradient spec)"
|
||||
).is_true()
|
||||
assert_bool(b.position.y <= 6).is_true()
|
||||
|
||||
|
||||
# -- Acceptance: Forward-only visibility (Sprint 22 server simplification) ----
|
||||
|
||||
func test_visible_tiles_written_as_vis_forward() -> void:
|
||||
# Sprint 22: server sends only Forward tiles (Peripheral sector removed).
|
||||
# FogState writes VIS_FORWARD (255) for all tiles in visible_positions.
|
||||
var fog_state = _get_fog_state()
|
||||
if fog_state == null:
|
||||
return
|
||||
if not fog_state.has_method("update_from_state"):
|
||||
return
|
||||
|
||||
GameState.visible_positions = {Vector2i(5, 5): true, Vector2i(6, 5): true}
|
||||
GameState.visible_tiles = [
|
||||
{"x": 5, "y": 5, "z": 0, "visibility": "Forward"},
|
||||
{"x": 6, "y": 5, "z": 0, "visibility": "Forward"},
|
||||
]
|
||||
fog_state.update_from_state()
|
||||
|
||||
var vis_bytes = fog_state.get("_vis_bytes")
|
||||
if vis_bytes == null:
|
||||
return
|
||||
var ox: int = fog_state.map_bounds.position.x
|
||||
var oy: int = fog_state.map_bounds.position.y
|
||||
var w: int = fog_state.get("_width") if fog_state.get("_width") != null else -1
|
||||
if w <= 0:
|
||||
return
|
||||
for pos in [Vector2i(5, 5), Vector2i(6, 5)]:
|
||||
var px := pos.x - ox
|
||||
var py := pos.y - oy
|
||||
if px < 0 or py < 0 or px >= w:
|
||||
continue
|
||||
var idx := py * w + px
|
||||
if idx >= 0 and idx < vis_bytes.size():
|
||||
assert_int(vis_bytes[idx]).override_failure_message(
|
||||
"All visible tiles should be VIS_FORWARD=255 — server is Forward-only in Sprint 22"
|
||||
).is_equal(fog_state.VIS_FORWARD)
|
||||
|
||||
|
||||
func test_tiles_outside_los_written_as_vis_hidden() -> void:
|
||||
# Tiles in bounds but not in visible_positions must be VIS_HIDDEN (0)
|
||||
var fog_state = _get_fog_state()
|
||||
if fog_state == null:
|
||||
return
|
||||
if not fog_state.has_method("update_from_state"):
|
||||
return
|
||||
|
||||
GameState.visible_positions = {Vector2i(5, 5): true}
|
||||
GameState.visible_tiles = [{"x": 5, "y": 5, "z": 0, "visibility": "Forward"}]
|
||||
fog_state.update_from_state()
|
||||
|
||||
# (5, 7) is inside the padded bounds but not visible — must be VIS_HIDDEN
|
||||
var vis_bytes = fog_state.get("_vis_bytes")
|
||||
if vis_bytes == null:
|
||||
return
|
||||
var ox: int = fog_state.map_bounds.position.x
|
||||
var oy: int = fog_state.map_bounds.position.y
|
||||
var w: int = fog_state.get("_width") if fog_state.get("_width") != null else -1
|
||||
if w <= 0:
|
||||
return
|
||||
var px := 5 - ox
|
||||
var py := 7 - oy
|
||||
if px >= 0 and py >= 0 and px < w:
|
||||
var idx := py * w + px
|
||||
if idx >= 0 and idx < vis_bytes.size():
|
||||
assert_int(vis_bytes[idx]).is_equal(fog_state.VIS_HIDDEN)
|
||||
|
||||
|
||||
# -- Acceptance: exploration survives texture resize --------------------------
|
||||
|
||||
func test_exploration_data_preserved_across_bounds_growth() -> void:
|
||||
# D-059: Texture resize must copy old exploration bytes into new texture.
|
||||
# Without this, tiles seen before a resize appear as EXP_UNEXPLORED (black).
|
||||
var fog_state = _get_fog_state()
|
||||
if fog_state == null:
|
||||
return
|
||||
if not fog_state.has_method("update_from_state"):
|
||||
return
|
||||
|
||||
# Frame 1: see (5, 5), then leave
|
||||
GameState.visible_positions = {Vector2i(5, 5): true}
|
||||
GameState.visible_tiles = [{"x": 5, "y": 5, "z": 0, "visibility": "Forward"}]
|
||||
fog_state.update_from_state()
|
||||
GameState.visible_positions.clear()
|
||||
GameState.visible_tiles = []
|
||||
fog_state.update_from_state() # (5,5) → EXP_EXPLORED
|
||||
|
||||
# Frame 2: move far away — forces bounds growth (resize)
|
||||
GameState.visible_positions = {Vector2i(80, 80): true}
|
||||
GameState.visible_tiles = [{"x": 80, "y": 80, "z": 0, "visibility": "Forward"}]
|
||||
fog_state.update_from_state()
|
||||
|
||||
# (5,5) must still be EXP_EXPLORED after the resize
|
||||
var exp_bytes = fog_state.get("_exp_bytes")
|
||||
if exp_bytes == null:
|
||||
return
|
||||
var ox: int = fog_state.map_bounds.position.x
|
||||
var oy: int = fog_state.map_bounds.position.y
|
||||
var w: int = fog_state.get("_width") if fog_state.get("_width") != null else -1
|
||||
if w <= 0:
|
||||
return
|
||||
var px := 5 - ox
|
||||
var py := 5 - oy
|
||||
if px < 0 or py < 0 or px >= w:
|
||||
push_warning("TestFogSprint22: (5,5) not in bounds after resize — is copy-on-resize working?")
|
||||
return
|
||||
var idx := py * w + px
|
||||
if idx >= 0 and idx < exp_bytes.size():
|
||||
assert_int(exp_bytes[idx]).override_failure_message(
|
||||
"Exploration data at (5,5) must survive bounds growth — EXP_EXPLORED (128) expected after resize"
|
||||
).is_greater_equal(fog_state.EXP_EXPLORED)
|
||||
|
||||
|
||||
# -- Shader file checks (D-059) -----------------------------------------------
|
||||
|
||||
func test_fog_gdshader_exists() -> void:
|
||||
assert_bool(ResourceLoader.exists("res://shaders/fog.gdshader")).override_failure_message(
|
||||
"fog.gdshader must exist — fog rendering requires this shader file (#569)"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_fog_shader_defines_fog_alpha() -> void:
|
||||
# D-059: explored fog overlay must be ~25-30% opacity.
|
||||
# fog_alpha constant controls this. Verify the shader defines it.
|
||||
if not ResourceLoader.exists("res://shaders/fog.gdshader"):
|
||||
push_warning("TestFogSprint22: fog.gdshader not found — shader check skipped")
|
||||
return
|
||||
var source := FileAccess.get_file_as_string("res://shaders/fog.gdshader")
|
||||
if source.is_empty():
|
||||
push_warning("TestFogSprint22: fog.gdshader is empty or unreadable")
|
||||
return
|
||||
assert_bool(source.contains("fog_alpha")).override_failure_message(
|
||||
"fog.gdshader must define fog_alpha for the 25-30%% explored-tile overlay (D-059)"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_fog_shader_defines_smoothstep_clarity_ramp() -> void:
|
||||
# D-059/D-066: smooth gradient requires a clarity ramp (smoothstep).
|
||||
# The blurred visibility → clarity ramp must use smoothstep for smooth gradients.
|
||||
if not ResourceLoader.exists("res://shaders/fog.gdshader"):
|
||||
push_warning("TestFogSprint22: fog.gdshader not found — skipped")
|
||||
return
|
||||
var source := FileAccess.get_file_as_string("res://shaders/fog.gdshader")
|
||||
if source.is_empty():
|
||||
return
|
||||
assert_bool(source.contains("smoothstep")).override_failure_message(
|
||||
"fog.gdshader must use smoothstep for the clarity ramp — hard steps violate D-066 gradient spec"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_fog_shader_defines_unexplored_color() -> void:
|
||||
# D-059: unexplored = solid near-black #12141a.
|
||||
if not ResourceLoader.exists("res://shaders/fog.gdshader"):
|
||||
push_warning("TestFogSprint22: fog.gdshader not found — skipped")
|
||||
return
|
||||
var source := FileAccess.get_file_as_string("res://shaders/fog.gdshader")
|
||||
if source.is_empty():
|
||||
return
|
||||
assert_bool(source.contains("UNEXPLORED_COLOR")).override_failure_message(
|
||||
"fog.gdshader must define UNEXPLORED_COLOR constant (D-059 #12141a spec)"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_fog_shader_uses_gaussian_blur_for_gradient() -> void:
|
||||
# D-066: 6-8 tile soft gradient requires Gaussian blur on visibility texture.
|
||||
# Current implementation: 7x7 kernel at 2-texel intervals (±6 tiles), sigma 2.0
|
||||
# in kernel space = 4.0 tiles effective. At 2-sigma (8 tiles), weight drops to 0.14.
|
||||
# This covers the D-066 "6-8 tile" gradient spec.
|
||||
if not ResourceLoader.exists("res://shaders/fog.gdshader"):
|
||||
push_warning("TestFogSprint22: fog.gdshader not found — skipped")
|
||||
return
|
||||
var source := FileAccess.get_file_as_string("res://shaders/fog.gdshader")
|
||||
if source.is_empty():
|
||||
return
|
||||
# 7x7 Gaussian uses dy from -3 to 3
|
||||
assert_bool(source.contains("sample_visibility")).override_failure_message(
|
||||
"fog.gdshader must call sample_visibility() for Gaussian-blurred visibility (D-066 gradient)"
|
||||
).is_true()
|
||||
assert_bool(source.contains("-3.0")).override_failure_message(
|
||||
"fog.gdshader sample_visibility must use 7x7 kernel (±3 tiles) for 6-tile gradient coverage (D-066)"
|
||||
).is_true()
|
||||
|
||||
|
||||
# -- Regression: GameState visible_positions (existing contract) ---------------
|
||||
|
||||
func test_visible_positions_derived_from_visible_tiles_in_server_mode() -> void:
|
||||
# D-020: In real server mode, visible_positions derives from visible_tiles.
|
||||
# Fog rendering depends on this derivation being correct.
|
||||
GameState.apply_snapshot({
|
||||
"tick": 10,
|
||||
"visible_tiles": [
|
||||
{"x": 7, "y": 7, "z": 0, "visibility": "Forward"},
|
||||
{"x": 8, "y": 7, "z": 0, "visibility": "Forward"},
|
||||
],
|
||||
})
|
||||
assert_bool(GameState.visible_positions.has(Vector2i(7, 7))).override_failure_message(
|
||||
"visible_positions must be derived from visible_tiles when no explicit visible_positions key"
|
||||
).is_true()
|
||||
assert_bool(GameState.visible_positions.has(Vector2i(8, 7))).is_true()
|
||||
|
||||
|
||||
func test_visibility_sectors_populated_forward_only() -> void:
|
||||
# D-015: visibility_sectors must be populated from visible_tiles.
|
||||
# In Forward-only mode, all sectors are "Forward".
|
||||
GameState.apply_snapshot({
|
||||
"tick": 11,
|
||||
"visible_tiles": [
|
||||
{"x": 4, "y": 4, "z": 0, "visibility": "Forward"},
|
||||
],
|
||||
})
|
||||
assert_bool(GameState.visibility_sectors.has(Vector2i(4, 4))).is_true()
|
||||
assert_str(GameState.visibility_sectors[Vector2i(4, 4)]).is_equal("Forward")
|
||||
|
||||
|
||||
func test_visible_positions_cleared_on_new_snapshot() -> void:
|
||||
# Old positions from tick N must not persist to tick N+1
|
||||
GameState.apply_snapshot({
|
||||
"tick": 1,
|
||||
"visible_tiles": [{"x": 5, "y": 5, "z": 0, "visibility": "Forward"}],
|
||||
})
|
||||
assert_int(GameState.visible_positions.size()).is_equal(1)
|
||||
GameState.apply_snapshot({
|
||||
"tick": 2,
|
||||
"visible_tiles": [{"x": 10, "y": 10, "z": 0, "visibility": "Forward"}],
|
||||
})
|
||||
assert_bool(GameState.visible_positions.has(Vector2i(5, 5))).override_failure_message(
|
||||
"Old visible positions must be cleared when new visible_tiles arrive"
|
||||
).is_false()
|
||||
assert_bool(GameState.visible_positions.has(Vector2i(10, 10))).is_true()
|
||||
|
||||
|
||||
# -- Sprint 23: BoundaryWall handling (#585) ----------------------------------
|
||||
|
||||
func test_boundary_positions_populated_from_snapshot() -> void:
|
||||
# #585: BoundaryWall tiles go to boundary_positions (not visible_positions).
|
||||
# Fog lifts for boundary wall tiles so wall content composites correctly.
|
||||
GameState.apply_snapshot({
|
||||
"tick": 20,
|
||||
"visible_tiles": [
|
||||
{"x": 10, "y": 10, "z": 0, "visibility": "Forward", "type": "floor"},
|
||||
{"x": 11, "y": 10, "z": 0, "visibility": "BoundaryWall", "type": "wall"},
|
||||
],
|
||||
})
|
||||
assert_bool(GameState.visible_positions.has(Vector2i(10, 10))).override_failure_message(
|
||||
"Forward tile must be in visible_positions"
|
||||
).is_true()
|
||||
assert_bool(GameState.visible_positions.has(Vector2i(11, 10))).override_failure_message(
|
||||
"BoundaryWall tile must NOT be in visible_positions (#585)"
|
||||
).is_false()
|
||||
assert_bool(GameState.boundary_positions.has(Vector2i(11, 10))).override_failure_message(
|
||||
"BoundaryWall tile must be in boundary_positions (#585)"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_boundary_wall_vis_forward_not_exp_visible() -> void:
|
||||
# #585: BoundaryWall tiles get VIS_FORWARD (fog lifted) but NOT EXP_VISIBLE.
|
||||
# They render through fog but are not stored as exploration memory.
|
||||
var fog_state = _get_fog_state()
|
||||
if fog_state == null:
|
||||
return
|
||||
if not fog_state.has_method("update_from_state"):
|
||||
return
|
||||
|
||||
GameState.visible_positions = {Vector2i(5, 5): true}
|
||||
GameState.boundary_positions = {Vector2i(6, 5): true}
|
||||
GameState.visible_tiles = [
|
||||
{"x": 5, "y": 5, "z": 0, "visibility": "Forward", "type": "floor"},
|
||||
{"x": 6, "y": 5, "z": 0, "visibility": "BoundaryWall", "type": "wall"},
|
||||
]
|
||||
fog_state.update_from_state()
|
||||
|
||||
var vis_bytes = fog_state.get("_vis_bytes")
|
||||
var exp_bytes = fog_state.get("_exp_bytes")
|
||||
if vis_bytes == null or exp_bytes == null:
|
||||
push_warning("TestFogSprint22: byte arrays not accessible — skipped")
|
||||
return
|
||||
var ox: int = fog_state.map_bounds.position.x
|
||||
var oy: int = fog_state.map_bounds.position.y
|
||||
var w: int = fog_state.get("_width") if fog_state.get("_width") != null else -1
|
||||
if w <= 0:
|
||||
return
|
||||
var px := 6 - ox
|
||||
var py := 5 - oy
|
||||
if px < 0 or py < 0 or px >= w:
|
||||
push_warning("TestFogSprint22: boundary tile (6,5) out of bounds — skipped")
|
||||
return
|
||||
var idx := py * w + px
|
||||
if idx < 0 or idx >= vis_bytes.size():
|
||||
return
|
||||
assert_int(vis_bytes[idx]).override_failure_message(
|
||||
"BoundaryWall tile must have VIS_FORWARD — fog must lift to composite wall content (#585)"
|
||||
).is_equal(fog_state.VIS_FORWARD)
|
||||
assert_int(exp_bytes[idx]).override_failure_message(
|
||||
"BoundaryWall tile must NOT be EXP_VISIBLE — it is not explored memory (#585)"
|
||||
).is_not_equal(fog_state.EXP_VISIBLE)
|
||||
|
||||
|
||||
func test_boundary_wall_stays_unexplored_after_leaving_los() -> void:
|
||||
# #585: When BoundaryWall tile leaves LOS, it must NOT decay to EXP_EXPLORED.
|
||||
# Normal LOS tiles decay to EXP_EXPLORED when they leave LOS.
|
||||
# Boundary tiles must stay EXP_UNEXPLORED — they were never explored.
|
||||
var fog_state = _get_fog_state()
|
||||
if fog_state == null:
|
||||
return
|
||||
if not fog_state.has_method("update_from_state"):
|
||||
return
|
||||
|
||||
# Frame 1: BoundaryWall at (6,5) is visible
|
||||
GameState.visible_positions = {Vector2i(5, 5): true}
|
||||
GameState.boundary_positions = {Vector2i(6, 5): true}
|
||||
GameState.visible_tiles = [
|
||||
{"x": 5, "y": 5, "z": 0, "visibility": "Forward", "type": "floor"},
|
||||
{"x": 6, "y": 5, "z": 0, "visibility": "BoundaryWall", "type": "wall"},
|
||||
]
|
||||
fog_state.update_from_state()
|
||||
|
||||
# Frame 2: both leave LOS
|
||||
GameState.visible_positions.clear()
|
||||
GameState.boundary_positions.clear()
|
||||
GameState.visible_tiles = []
|
||||
fog_state.update_from_state()
|
||||
|
||||
var exp_bytes = fog_state.get("_exp_bytes")
|
||||
if exp_bytes == null:
|
||||
return
|
||||
var ox: int = fog_state.map_bounds.position.x
|
||||
var oy: int = fog_state.map_bounds.position.y
|
||||
var w: int = fog_state.get("_width") if fog_state.get("_width") != null else -1
|
||||
if w <= 0:
|
||||
return
|
||||
var px := 6 - ox
|
||||
var py := 5 - oy
|
||||
if px >= 0 and py >= 0 and px < w:
|
||||
var idx := py * w + px
|
||||
if idx >= 0 and idx < exp_bytes.size():
|
||||
assert_int(exp_bytes[idx]).override_failure_message(
|
||||
"BoundaryWall tile must stay EXP_UNEXPLORED after leaving LOS (#585 — not explored memory)"
|
||||
).is_equal(fog_state.EXP_UNEXPLORED)
|
||||
|
||||
|
||||
func test_boundary_wall_cleared_on_new_snapshot() -> void:
|
||||
# #585: boundary_positions must be cleared each tick — old walls must not persist.
|
||||
# BoundaryWall positions shift as the player moves; stale positions would lift fog
|
||||
# where no wall exists.
|
||||
GameState.apply_snapshot({
|
||||
"tick": 30,
|
||||
"visible_tiles": [
|
||||
{"x": 5, "y": 5, "z": 0, "visibility": "Forward", "type": "floor"},
|
||||
{"x": 6, "y": 5, "z": 0, "visibility": "BoundaryWall", "type": "wall"},
|
||||
],
|
||||
})
|
||||
assert_bool(GameState.boundary_positions.has(Vector2i(6, 5))).is_true()
|
||||
|
||||
GameState.apply_snapshot({
|
||||
"tick": 31,
|
||||
"visible_tiles": [
|
||||
{"x": 5, "y": 5, "z": 0, "visibility": "Forward", "type": "floor"},
|
||||
],
|
||||
})
|
||||
assert_bool(GameState.boundary_positions.has(Vector2i(6, 5))).override_failure_message(
|
||||
"Stale BoundaryWall position must be cleared on next snapshot (#585)"
|
||||
).is_false()
|
||||
|
||||
|
||||
# -- Performance (D-059) -------------------------------------------------------
|
||||
|
||||
func test_fog_state_update_under_2ms_for_400_tiles() -> void:
|
||||
# D-059: <1ms/frame CPU budget for fog update. Allow 2x margin for test env.
|
||||
var fog_state = _get_fog_state()
|
||||
if fog_state == null:
|
||||
return
|
||||
if not fog_state.has_method("update_from_state"):
|
||||
return
|
||||
|
||||
var positions: Dictionary = {}
|
||||
var tiles: Array = []
|
||||
for x in range(20):
|
||||
for y in range(20):
|
||||
positions[Vector2i(x, y)] = true
|
||||
tiles.append({"x": x, "y": y, "z": 0, "visibility": "Forward"})
|
||||
GameState.visible_positions = positions
|
||||
GameState.visible_tiles = tiles
|
||||
|
||||
var start := Time.get_ticks_usec()
|
||||
fog_state.update_from_state()
|
||||
var elapsed_ms := (Time.get_ticks_usec() - start) / 1000.0
|
||||
|
||||
assert_float(elapsed_ms).override_failure_message(
|
||||
"FogState.update_from_state() must complete in <2ms for 400 tiles (spec: <1ms D-059)"
|
||||
).is_less(2.0)
|
||||
@@ -1 +0,0 @@
|
||||
uid://bxhgo1e4rvfmi
|
||||
@@ -15,7 +15,7 @@ const _THRESHOLD: float = 5.0 # Mirror of main.gd TELEPORT_DISTANCE_THRESHOLD
|
||||
|
||||
var _gauntlet_snapshot := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"game_time": {"day": 0, "time_of_day": 100, "day_phase": "Morning", "tick_rate": "Full"},
|
||||
"player_facing": "North",
|
||||
"player_stance": "Walk",
|
||||
@@ -36,7 +36,7 @@ var _gauntlet_snapshot := {
|
||||
|
||||
var _normal_snapshot := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"game_time": {"day": 0, "time_of_day": 100, "day_phase": "Morning", "tick_rate": "Full"},
|
||||
"player_facing": "North",
|
||||
"player_stance": "Walk",
|
||||
|
||||
@@ -160,8 +160,6 @@ func test_interact_roundtrip() -> void:
|
||||
# Server accepts it (currently a no-op) and responds with a valid snapshot.
|
||||
var snapshot: Dictionary = await _send_and_receive("Interact", 0)
|
||||
|
||||
# Snapshot should be valid with correct protocol version
|
||||
assert_that(snapshot.version).is_equal(Protocol.PROTOCOL_VERSION)
|
||||
assert_that(snapshot.entities.size()).is_greater(0)
|
||||
|
||||
# Player should be at start position (Interact doesn't move)
|
||||
@@ -173,7 +171,6 @@ func test_interact_roundtrip() -> void:
|
||||
# Send Interact again at next tick — server should still accept it
|
||||
var snap2: Dictionary = await _send_and_receive("Interact", 1)
|
||||
assert_that(snap2).is_not_null()
|
||||
assert_that(snap2.version).is_equal(Protocol.PROTOCOL_VERSION)
|
||||
|
||||
|
||||
# -- Mixed sequence: movement then interact in one session ---------------------
|
||||
|
||||
@@ -305,7 +305,7 @@ func test_contradicted_entity_verbs_decode() -> void:
|
||||
# #422: NearbyInteraction.contradicted=true should be decodeable
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"nearby_interactions": [{
|
||||
"entity_id": 2,
|
||||
@@ -329,7 +329,7 @@ func test_object_type_verbs_decode() -> void:
|
||||
# #421: ObjectType appears in NearbyInteraction.object_type
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"nearby_interactions": [{
|
||||
"entity_id": 3,
|
||||
|
||||
@@ -11,7 +11,7 @@ extends GdUnitTestSuite
|
||||
func test_protocol_decode_v4_with_nearby_interactions() -> void:
|
||||
var raw := {
|
||||
"tick": 10,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [
|
||||
{"entity_id": 1, "x": 5.0, "y": 5.0, "z": 0, "kind": "Player",
|
||||
"visibility": "Forward", "relationship": "Unknown", "observation": "Visible"},
|
||||
@@ -46,7 +46,7 @@ func test_protocol_decode_v4_with_nearby_interactions() -> void:
|
||||
func test_protocol_decode_v4_no_nearby_interactions() -> void:
|
||||
var raw := {
|
||||
"tick": 5,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
}
|
||||
var encoded = Messagepack.encode(raw)
|
||||
@@ -57,7 +57,7 @@ func test_protocol_decode_v4_no_nearby_interactions() -> void:
|
||||
func test_protocol_decode_empty_nearby_interactions() -> void:
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"nearby_interactions": [],
|
||||
}
|
||||
@@ -68,7 +68,7 @@ func test_protocol_decode_empty_nearby_interactions() -> void:
|
||||
func test_protocol_decode_interaction_missing_verbs() -> void:
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"nearby_interactions": [{"entity_id": 2}],
|
||||
}
|
||||
@@ -79,7 +79,7 @@ func test_protocol_decode_interaction_missing_verbs() -> void:
|
||||
func test_protocol_decode_interaction_empty_verbs() -> void:
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"nearby_interactions": [{"entity_id": 2, "entity_type": "Npc", "distance": 1, "verbs": []}],
|
||||
}
|
||||
@@ -90,7 +90,7 @@ func test_protocol_decode_interaction_empty_verbs() -> void:
|
||||
func test_protocol_decode_v4_entity_relationship() -> void:
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [
|
||||
{"entity_id": 1, "x": 5.0, "y": 5.0, "z": 0, "kind": "Npc",
|
||||
"visibility": "Forward", "relationship": "Friendly", "observation": "Visible"},
|
||||
@@ -100,17 +100,6 @@ func test_protocol_decode_v4_entity_relationship() -> void:
|
||||
var snapshot = Protocol.decode_snapshot(encoded.value)
|
||||
assert_that(snapshot.entities[0].relationship).is_equal("Friendly")
|
||||
|
||||
func test_protocol_rejects_version_mismatch() -> void:
|
||||
var raw := {
|
||||
"tick": 5,
|
||||
"version": 2,
|
||||
"entities": [],
|
||||
}
|
||||
var encoded = Messagepack.encode(raw)
|
||||
var snapshot = Protocol.decode_snapshot(encoded.value)
|
||||
assert_that(snapshot).is_null()
|
||||
|
||||
|
||||
# -- GameState: nearby_interactions storage --
|
||||
|
||||
func test_game_state_stores_nearby_interactions() -> void:
|
||||
@@ -153,12 +142,6 @@ func test_sim_bridge_test_snapshot_interaction_at_range_2() -> void:
|
||||
var snap = SimBridge._test_snapshot()
|
||||
assert_that(snap.nearby_interactions.size()).is_equal(1)
|
||||
|
||||
func test_sim_bridge_test_snapshot_protocol_version() -> void:
|
||||
SimBridge.reset_test_state()
|
||||
var snap = SimBridge._test_snapshot()
|
||||
assert_that(snap.version).is_equal(Protocol.PROTOCOL_VERSION)
|
||||
|
||||
|
||||
# -- InteractionPrompt UI --
|
||||
|
||||
func test_prompt_get_selected_verb_returns_first_kind() -> void:
|
||||
|
||||
@@ -19,13 +19,6 @@ func _load_fixture(name: String) -> PackedByteArray:
|
||||
|
||||
# -- snapshot_minimal ----------------------------------------------------------
|
||||
|
||||
func test_fixture_snapshot_minimal_version() -> void:
|
||||
var bytes = _load_fixture("snapshot_minimal")
|
||||
var snapshot = Protocol.decode_snapshot(bytes)
|
||||
assert_that(snapshot).is_not_null()
|
||||
assert_that(snapshot.version).is_equal(Protocol.PROTOCOL_VERSION)
|
||||
|
||||
|
||||
func test_fixture_snapshot_minimal_tick() -> void:
|
||||
var bytes = _load_fixture("snapshot_minimal")
|
||||
var snapshot = Protocol.decode_snapshot(bytes)
|
||||
|
||||
@@ -1,601 +0,0 @@
|
||||
## Sprint 18 — Knowledge/journal display (#264)
|
||||
## Spec refs: D-041 (knowledge graph data model), D-027 (vertical slice — KG display),
|
||||
## D-042 (UIStrings for all labels)
|
||||
##
|
||||
## Tests now run against live Stig implementation.
|
||||
## Wire format per game_state.gd v14:
|
||||
## player_knowledge: {entities: [{entity_id, name, confidence, source, state, relationship, last_observed_tick}]}
|
||||
##
|
||||
## NOTE: player_knowledge PERSISTS between snapshots (no-clear behavior, by design).
|
||||
## The server sends KG updates only when the graph changes — absence = no change.
|
||||
## Contrast with current_examine_result which DOES clear each snapshot.
|
||||
class_name TestJournalSprint18
|
||||
extends GdUnitTestSuite
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
const JOURNAL_SCENE_PATH: String = "res://ui/journal_panel.tscn"
|
||||
|
||||
func _make_journal_panel() -> Control:
|
||||
if not ResourceLoader.exists(JOURNAL_SCENE_PATH):
|
||||
push_warning("TestJournalSprint18: journal_panel.tscn not found — scene tests skipped")
|
||||
return null
|
||||
var node: Control = load(JOURNAL_SCENE_PATH).instantiate()
|
||||
add_child(node)
|
||||
return node
|
||||
|
||||
|
||||
func _make_kg_entity(overrides: Dictionary = {}) -> Dictionary:
|
||||
## Wire format per game_state.gd v14 / Stig's Stig confirmation (2026-02-25).
|
||||
## entities: [{entity_id, name, confidence, source, state, relationship, last_observed_tick}]
|
||||
var base: Dictionary = {
|
||||
"entity_id": 42,
|
||||
"name": "Kael Davan",
|
||||
"confidence": "KnowsOf",
|
||||
"source": "DirectObservation",
|
||||
"state": "Active",
|
||||
"relationship": "PersonOfInterest",
|
||||
"last_observed_tick": 1024,
|
||||
}
|
||||
base.merge(overrides, true)
|
||||
return base
|
||||
|
||||
|
||||
func _make_player_knowledge(entities: Array = []) -> Dictionary:
|
||||
if entities.is_empty():
|
||||
entities = [_make_kg_entity()]
|
||||
return {"entities": entities}
|
||||
|
||||
|
||||
func _entries_container(panel: Control) -> Node:
|
||||
return panel.get_node_or_null(
|
||||
"PanelContainer/MarginContainer/VBoxContainer/ScrollContainer/EntriesContainer"
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Lifecycle
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func before_test() -> void:
|
||||
GameState.player_knowledge = null
|
||||
GameState.current_dialogue = null
|
||||
GameState.dialogue_active = false
|
||||
GameState.current_tick = 0
|
||||
|
||||
func after_test() -> void:
|
||||
GameState.player_knowledge = null
|
||||
GameState.current_dialogue = null
|
||||
GameState.dialogue_active = false
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# GameState: player_knowledge snapshot parsing
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_gamestate_player_knowledge_field_exists() -> void:
|
||||
## GameState must have player_knowledge field (v14, #264).
|
||||
assert_bool(GameState.has("player_knowledge")).override_failure_message(
|
||||
"GameState must have 'player_knowledge' field (Sprint 18 #264)"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_gamestate_player_knowledge_null_by_default() -> void:
|
||||
GameState.player_knowledge = null
|
||||
assert_that(GameState.player_knowledge).is_null()
|
||||
|
||||
|
||||
func test_gamestate_player_knowledge_set_from_snapshot() -> void:
|
||||
GameState.apply_snapshot({
|
||||
"tick": 10,
|
||||
"player_knowledge": _make_player_knowledge(),
|
||||
})
|
||||
assert_that(GameState.player_knowledge).is_not_null()
|
||||
assert_bool(GameState.player_knowledge.has("entities")).is_true()
|
||||
|
||||
|
||||
func test_gamestate_player_knowledge_persists_when_absent() -> void:
|
||||
## IMPORTANT: player_knowledge does NOT clear when absent from snapshot.
|
||||
## Server sends KG updates only on change — absence means "no change since last tick".
|
||||
## This is intentional behavior (journal should not flash empty every tick).
|
||||
GameState.player_knowledge = _make_player_knowledge()
|
||||
GameState.apply_snapshot({"tick": 11})
|
||||
assert_that(GameState.player_knowledge).is_not_null()
|
||||
|
||||
|
||||
func test_gamestate_player_knowledge_null_when_non_dict() -> void:
|
||||
## Malformed player_knowledge (non-dict) must be rejected.
|
||||
## First set a valid value, then try to overwrite with invalid
|
||||
GameState.player_knowledge = _make_player_knowledge()
|
||||
GameState.apply_snapshot({"tick": 1, "player_knowledge": "bad-value"})
|
||||
# Non-dict is rejected — previous value preserved (or null if first time)
|
||||
# The implementation only updates on Dictionary type, so value persists
|
||||
assert_that(GameState.player_knowledge).is_not_null()
|
||||
|
||||
|
||||
func test_gamestate_player_knowledge_entities_survive_roundtrip() -> void:
|
||||
var entities := [
|
||||
_make_kg_entity({"name": "Kael Davan", "state": "Active"}),
|
||||
_make_kg_entity({"name": "Lysa Orin", "state": "Contradicted", "entity_id": 55}),
|
||||
]
|
||||
GameState.apply_snapshot({"tick": 5, "player_knowledge": {"entities": entities}})
|
||||
var parsed_entities: Array = GameState.player_knowledge.get("entities", [])
|
||||
assert_int(parsed_entities.size()).is_equal(2)
|
||||
assert_that(parsed_entities[0].get("name")).is_equal("Kael Davan")
|
||||
assert_that(parsed_entities[1].get("state")).is_equal("Contradicted")
|
||||
|
||||
|
||||
func test_gamestate_player_knowledge_updated_when_new_data_arrives() -> void:
|
||||
## When server sends a new player_knowledge, it replaces the previous value.
|
||||
GameState.apply_snapshot({"tick": 1, "player_knowledge": _make_player_knowledge([
|
||||
_make_kg_entity({"name": "Person A"}),
|
||||
])})
|
||||
GameState.apply_snapshot({"tick": 2, "player_knowledge": _make_player_knowledge([
|
||||
_make_kg_entity({"name": "Person A"}),
|
||||
_make_kg_entity({"name": "Person B", "entity_id": 99}),
|
||||
])})
|
||||
var entities: Array = GameState.player_knowledge.get("entities", [])
|
||||
assert_int(entities.size()).is_equal(2)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Journal panel: scene and API
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_journal_panel_scene_exists() -> void:
|
||||
assert_bool(ResourceLoader.exists(JOURNAL_SCENE_PATH)).override_failure_message(
|
||||
"Journal panel scene must exist at res://ui/journal_panel.tscn"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_journal_panel_instantiates_without_crash() -> void:
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
assert_that(panel).is_not_null()
|
||||
panel.queue_free()
|
||||
|
||||
|
||||
func test_journal_panel_has_toggle_method() -> void:
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
assert_bool(panel.has_method("toggle")).override_failure_message(
|
||||
"JournalPanel must have toggle() method"
|
||||
).is_true()
|
||||
panel.queue_free()
|
||||
|
||||
|
||||
func test_journal_panel_has_close_method() -> void:
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
assert_bool(panel.has_method("close")).override_failure_message(
|
||||
"JournalPanel must have close() method"
|
||||
).is_true()
|
||||
panel.queue_free()
|
||||
|
||||
|
||||
func test_journal_panel_has_is_open_method() -> void:
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
assert_bool(panel.has_method("is_open")).override_failure_message(
|
||||
"JournalPanel must have is_open() method"
|
||||
).is_true()
|
||||
panel.queue_free()
|
||||
|
||||
|
||||
func test_journal_panel_has_update_from_state_method() -> void:
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
assert_bool(panel.has_method("update_from_state")).override_failure_message(
|
||||
"JournalPanel must have update_from_state() method (called from main.gd)"
|
||||
).is_true()
|
||||
panel.queue_free()
|
||||
|
||||
|
||||
func test_journal_panel_closed_on_init() -> void:
|
||||
## Panel starts hidden — not open by default.
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
assert_bool(panel.is_open()).override_failure_message(
|
||||
"JournalPanel must be closed on _ready()"
|
||||
).is_false()
|
||||
panel.queue_free()
|
||||
|
||||
|
||||
func test_journal_panel_toggle_opens() -> void:
|
||||
## First toggle() opens the panel.
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
panel.toggle()
|
||||
assert_bool(panel.is_open()).override_failure_message(
|
||||
"toggle() must set is_open() = true"
|
||||
).is_true()
|
||||
panel.queue_free()
|
||||
|
||||
|
||||
func test_journal_panel_toggle_closes() -> void:
|
||||
## Second toggle() closes the panel.
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
panel.toggle() # open
|
||||
panel.toggle() # close
|
||||
assert_bool(panel.is_open()).override_failure_message(
|
||||
"Second toggle() must close the panel"
|
||||
).is_false()
|
||||
panel.queue_free()
|
||||
|
||||
|
||||
func test_journal_panel_close_when_already_closed_is_safe() -> void:
|
||||
## close() on an already-closed panel must not crash.
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
panel.close()
|
||||
assert_bool(panel.is_open()).is_false()
|
||||
panel.queue_free()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Journal panel: entry rendering
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_journal_panel_entries_container_exists() -> void:
|
||||
## EntriesContainer is the VBoxContainer that holds entity entries.
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
var container := _entries_container(panel)
|
||||
assert_that(container != null).override_failure_message(
|
||||
"EntriesContainer must exist at PanelContainer/MarginContainer/VBoxContainer/ScrollContainer/EntriesContainer"
|
||||
).is_true()
|
||||
panel.queue_free()
|
||||
|
||||
|
||||
func test_journal_panel_shows_entries_when_knowledge_populated() -> void:
|
||||
## Opening panel with player_knowledge set creates entry nodes in EntriesContainer.
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
|
||||
GameState.player_knowledge = _make_player_knowledge([
|
||||
_make_kg_entity({"name": "Kael Davan"}),
|
||||
])
|
||||
panel.toggle() # calls _show_panel() -> _rebuild_entries()
|
||||
|
||||
var container := _entries_container(panel)
|
||||
if container == null: panel.queue_free(); return
|
||||
|
||||
assert_int(container.get_child_count()).override_failure_message(
|
||||
"EntriesContainer must have children when player_knowledge is populated"
|
||||
).is_greater(0)
|
||||
panel.queue_free()
|
||||
|
||||
|
||||
func test_journal_panel_shows_empty_state_when_no_knowledge() -> void:
|
||||
## Empty state Label is shown when player_knowledge is null.
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
|
||||
GameState.player_knowledge = null
|
||||
panel.toggle()
|
||||
|
||||
var container := _entries_container(panel)
|
||||
if container == null: panel.queue_free(); return
|
||||
|
||||
## Empty state = exactly 1 child (the "Nothing logged yet." label)
|
||||
assert_int(container.get_child_count()).override_failure_message(
|
||||
"EntriesContainer should have 1 child (empty state label) when knowledge is null"
|
||||
).is_equal(1)
|
||||
panel.queue_free()
|
||||
|
||||
|
||||
func test_journal_panel_two_entities_create_more_entries() -> void:
|
||||
## Two entities create more entries than one (header + detail each, plus spacers).
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
|
||||
GameState.player_knowledge = _make_player_knowledge([
|
||||
_make_kg_entity({"name": "Entity A", "entity_id": 1}),
|
||||
_make_kg_entity({"name": "Entity B", "entity_id": 2}),
|
||||
])
|
||||
panel.toggle()
|
||||
|
||||
var container := _entries_container(panel)
|
||||
if container == null: panel.queue_free(); return
|
||||
|
||||
## Each entity: header_rtl + detail_rtl + spacer = 3 nodes. Two entities = 6 min.
|
||||
assert_int(container.get_child_count()).override_failure_message(
|
||||
"Two entities must create at least 6 child nodes (2 × [header + detail + spacer])"
|
||||
).is_greater_equal(6)
|
||||
panel.queue_free()
|
||||
|
||||
|
||||
func test_journal_panel_contradicted_entity_uses_strikethrough() -> void:
|
||||
## D-041: Contradicted entities must have strikethrough in their header BBCode.
|
||||
## journal_panel.gd renders [s]Name[/s] for Contradicted state.
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
|
||||
GameState.player_knowledge = _make_player_knowledge([
|
||||
_make_kg_entity({"name": "Bad Guy", "state": "Contradicted"}),
|
||||
])
|
||||
panel.toggle()
|
||||
|
||||
var container := _entries_container(panel)
|
||||
if container == null: panel.queue_free(); return
|
||||
|
||||
## First child should be the header RichTextLabel with [s]...[/s]
|
||||
if container.get_child_count() == 0:
|
||||
push_warning("test_journal_panel_contradicted_entity_uses_strikethrough: no entries — skip")
|
||||
panel.queue_free(); return
|
||||
|
||||
var first_child := container.get_child(0)
|
||||
if first_child is RichTextLabel:
|
||||
assert_that(first_child.text).override_failure_message(
|
||||
"Contradicted entity header must contain [s] (strikethrough) BBCode"
|
||||
).contains("[s]")
|
||||
panel.queue_free()
|
||||
|
||||
|
||||
func test_journal_panel_active_entity_no_strikethrough() -> void:
|
||||
## Active entity must NOT have strikethrough in its header.
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
|
||||
GameState.player_knowledge = _make_player_knowledge([
|
||||
_make_kg_entity({"name": "Good Guy", "state": "Active"}),
|
||||
])
|
||||
panel.toggle()
|
||||
|
||||
var container := _entries_container(panel)
|
||||
if container == null: panel.queue_free(); return
|
||||
|
||||
if container.get_child_count() == 0:
|
||||
push_warning("test_journal_panel_active_entity_no_strikethrough: no entries — skip")
|
||||
panel.queue_free(); return
|
||||
|
||||
var first_child := container.get_child(0)
|
||||
if first_child is RichTextLabel:
|
||||
assert_bool(first_child.text.contains("[s]")).override_failure_message(
|
||||
"Active entity header must NOT have strikethrough — only Contradicted gets [s]"
|
||||
).is_false()
|
||||
panel.queue_free()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Journal panel: mutual exclusion with dialogue
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_update_from_state_closes_journal_when_dialogue_active() -> void:
|
||||
## Sprint briefing: journal must close when dialogue opens.
|
||||
## update_from_state() is called from main.gd on each snapshot.
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
|
||||
panel.toggle() # open journal
|
||||
assert_bool(panel.is_open()).is_true()
|
||||
|
||||
GameState.dialogue_active = true
|
||||
panel.update_from_state()
|
||||
|
||||
assert_bool(panel.is_open()).override_failure_message(
|
||||
"Journal must close when GameState.dialogue_active = true (update_from_state() called)"
|
||||
).is_false()
|
||||
panel.queue_free()
|
||||
|
||||
|
||||
func test_update_from_state_does_not_close_when_dialogue_inactive() -> void:
|
||||
## update_from_state() must NOT close journal when dialogue is not active.
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
|
||||
panel.toggle() # open journal
|
||||
GameState.dialogue_active = false
|
||||
panel.update_from_state()
|
||||
|
||||
assert_bool(panel.is_open()).override_failure_message(
|
||||
"Journal must stay open when dialogue is inactive"
|
||||
).is_true()
|
||||
panel.queue_free()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# UIStrings: confidence and source label keys (D-042 — now via UIStrings)
|
||||
## CONFIDENCE_LABELS and SOURCE_LABELS dicts were removed from journal_panel.gd.
|
||||
## Labels now come from UIStrings: knowledge_panel.confidence_* / knowledge_panel.source_*
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_ui_strings_confidence_direct_exists() -> void:
|
||||
## D-042: confidence label for "Direct" tier must be in UIStrings.
|
||||
assert_bool(UIStrings.has_key("knowledge_panel.confidence_direct")).override_failure_message(
|
||||
"UIStrings must have 'knowledge_panel.confidence_direct' (D-042)"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_ui_strings_confidence_knowsdetails_exists() -> void:
|
||||
assert_bool(UIStrings.has_key("knowledge_panel.confidence_knowsdetails")).override_failure_message(
|
||||
"UIStrings must have 'knowledge_panel.confidence_knowsdetails' (D-042)"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_ui_strings_confidence_knowsof_exists() -> void:
|
||||
assert_bool(UIStrings.has_key("knowledge_panel.confidence_knowsof")).override_failure_message(
|
||||
"UIStrings must have 'knowledge_panel.confidence_knowsof' (D-042)"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_ui_strings_confidence_suspects_exists() -> void:
|
||||
assert_bool(UIStrings.has_key("knowledge_panel.confidence_suspects")).override_failure_message(
|
||||
"UIStrings must have 'knowledge_panel.confidence_suspects' (D-042)"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_ui_strings_all_confidence_keys_non_empty() -> void:
|
||||
## All four confidence label values must be non-empty strings.
|
||||
var keys := [
|
||||
"knowledge_panel.confidence_direct",
|
||||
"knowledge_panel.confidence_knowsdetails",
|
||||
"knowledge_panel.confidence_knowsof",
|
||||
"knowledge_panel.confidence_suspects",
|
||||
]
|
||||
for key in keys:
|
||||
if not UIStrings.has_key(key): continue
|
||||
assert_bool(UIStrings.get_text(key).length() > 0).override_failure_message(
|
||||
"UIStrings key '%s' must be non-empty" % key
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_ui_strings_source_directobservation_exists() -> void:
|
||||
assert_bool(UIStrings.has_key("knowledge_panel.source_directobservation")).override_failure_message(
|
||||
"UIStrings must have 'knowledge_panel.source_directobservation' (D-042)"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_ui_strings_source_toldby_exists() -> void:
|
||||
assert_bool(UIStrings.has_key("knowledge_panel.source_toldby")).override_failure_message(
|
||||
"UIStrings must have 'knowledge_panel.source_toldby' (D-042)"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_ui_strings_source_heard_exists() -> void:
|
||||
assert_bool(UIStrings.has_key("knowledge_panel.source_heard")).override_failure_message(
|
||||
"UIStrings must have 'knowledge_panel.source_heard' (D-042)"
|
||||
).is_true()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Journal panel: _state_color() contract
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_state_color_contradicted_is_amber() -> void:
|
||||
## D-041: Contradicted → amber tint (ENTITY_COLOR_POI) — THE FRIEND arc surface.
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
var color: Color = panel._state_color("Contradicted")
|
||||
assert_that(color).override_failure_message(
|
||||
"_state_color('Contradicted') must return ENTITY_COLOR_POI (amber)"
|
||||
).is_equal(Constants.ENTITY_COLOR_POI)
|
||||
panel.queue_free()
|
||||
|
||||
|
||||
func test_state_color_stale_is_dimmed() -> void:
|
||||
## Stale → dimmed text color (IMPLANT_TEXT_DIM).
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
var color: Color = panel._state_color("Stale")
|
||||
assert_that(color).override_failure_message(
|
||||
"_state_color('Stale') must return IMPLANT_TEXT_DIM"
|
||||
).is_equal(Constants.IMPLANT_TEXT_DIM)
|
||||
panel.queue_free()
|
||||
|
||||
|
||||
func test_state_color_active_is_normal() -> void:
|
||||
## Active → normal insert text color (INSERT_COLOR_TEXT).
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
var color: Color = panel._state_color("Active")
|
||||
assert_that(color).override_failure_message(
|
||||
"_state_color('Active') must return INSERT_COLOR_TEXT"
|
||||
).is_equal(Constants.INSERT_COLOR_TEXT)
|
||||
panel.queue_free()
|
||||
|
||||
|
||||
func test_state_color_contradicted_differs_from_active() -> void:
|
||||
## Contradicted and Active must have visually distinct colors.
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
var contradicted := panel._state_color("Contradicted")
|
||||
var active := panel._state_color("Active")
|
||||
assert_that(contradicted).is_not_equal(active)
|
||||
panel.queue_free()
|
||||
|
||||
|
||||
func test_state_color_stale_differs_from_active() -> void:
|
||||
## Stale and Active must have visually distinct colors.
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
var stale := panel._state_color("Stale")
|
||||
var active := panel._state_color("Active")
|
||||
assert_that(stale).is_not_equal(active)
|
||||
panel.queue_free()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# UIStrings: knowledge_panel keys (D-042)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_ui_strings_knowledge_panel_tab_contacts_exists() -> void:
|
||||
## Journal title uses knowledge_panel.tab_contacts.
|
||||
assert_bool(UIStrings.has_key("knowledge_panel.tab_contacts")).override_failure_message(
|
||||
"UIStrings must have 'knowledge_panel.tab_contacts' key (D-042)"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_ui_strings_knowledge_panel_empty_state_exists() -> void:
|
||||
## Empty state message uses knowledge_panel.empty_state.
|
||||
assert_bool(UIStrings.has_key("knowledge_panel.empty_state")).override_failure_message(
|
||||
"UIStrings must have 'knowledge_panel.empty_state' key (D-042)"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_ui_strings_knowledge_panel_empty_state_non_empty() -> void:
|
||||
if not UIStrings.has_key("knowledge_panel.empty_state"): return
|
||||
assert_bool(UIStrings.get_text("knowledge_panel.empty_state").length() > 0).is_true()
|
||||
|
||||
|
||||
func test_ui_strings_knowledge_panel_tab_contacts_non_empty() -> void:
|
||||
if not UIStrings.has_key("knowledge_panel.tab_contacts"): return
|
||||
assert_bool(UIStrings.get_text("knowledge_panel.tab_contacts").length() > 0).is_true()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# D-042: CONFIDENCE_LABELS/SOURCE_LABELS now via UIStrings — FIXED (2026-02-25)
|
||||
## Previously filed as a gap: journal_panel.gd had hardcoded CONFIDENCE_LABELS dict.
|
||||
## Fixed by Stig: dicts removed, all labels now use UIStrings.get_text("knowledge_panel.*").
|
||||
## Regression guard: verify the dicts are gone and UIStrings fallback works.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_d042_fixed_panel_has_no_confidence_labels_dict() -> void:
|
||||
## Regression: CONFIDENCE_LABELS dict must NOT exist on journal_panel — it was removed.
|
||||
## If this test fails, the hardcoded dict was accidentally re-introduced.
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
assert_bool(panel.get("CONFIDENCE_LABELS") == null).override_failure_message(
|
||||
"D-042 regression: CONFIDENCE_LABELS dict must be removed from journal_panel.gd"
|
||||
).is_true()
|
||||
panel.queue_free()
|
||||
|
||||
|
||||
func test_d042_fixed_panel_has_no_source_labels_dict() -> void:
|
||||
## Regression: SOURCE_LABELS dict must NOT exist on journal_panel — it was removed.
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
assert_bool(panel.get("SOURCE_LABELS") == null).override_failure_message(
|
||||
"D-042 regression: SOURCE_LABELS dict must be removed from journal_panel.gd"
|
||||
).is_true()
|
||||
panel.queue_free()
|
||||
|
||||
|
||||
func test_d042_uistrings_fallback_for_unknown_confidence() -> void:
|
||||
## UIStrings falls back to the key string itself for missing keys.
|
||||
## journal_panel.gd relies on this for graceful degradation.
|
||||
var fallback := UIStrings.get_text("knowledge_panel.confidence_nonexistent_level")
|
||||
assert_that(fallback).override_failure_message(
|
||||
"UIStrings fallback must return the key string itself for unknown keys"
|
||||
).is_equal("knowledge_panel.confidence_nonexistent_level")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Constants
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_canvas_insert_constant_is_10() -> void:
|
||||
assert_int(Constants.CANVAS_INSERT).is_equal(10)
|
||||
|
||||
|
||||
func test_journal_fade_constants_reasonable() -> void:
|
||||
## FADE_IN and FADE_OUT must be short (< 0.5s) for responsive UI.
|
||||
var panel := _make_journal_panel()
|
||||
if panel == null: return
|
||||
assert_float(panel.FADE_IN).is_between(0.0, 0.5)
|
||||
assert_float(panel.FADE_OUT).is_between(0.0, 0.5)
|
||||
panel.queue_free()
|
||||
@@ -1 +0,0 @@
|
||||
uid://cao5jf5h36img
|
||||
@@ -95,7 +95,7 @@ func test_frame_encode_large_payload_length() -> void:
|
||||
|
||||
func test_framed_protocol_snapshot_roundtrip() -> void:
|
||||
# Encode a snapshot with Protocol, frame it, decode the frame, decode the snapshot
|
||||
var snapshot_data := {"tick": 42, "version": Protocol.PROTOCOL_VERSION, "entities": []}
|
||||
var snapshot_data := {"tick": 42, "version": 23, "entities": []}
|
||||
var encoded: Variant = Messagepack.encode(snapshot_data)
|
||||
assert_that(encoded.status).is_null()
|
||||
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
## Sprint 37 — Scene-level merge-path UI flow tests (#873)
|
||||
##
|
||||
## Four flows that cover the critical paths through the pre-game UI.
|
||||
## These tests are the merge-gate mechanism added in the Sprint 36 retro:
|
||||
## regressions like #872 (New Game hang) must be caught here, not in post-merge
|
||||
## smoke tests.
|
||||
##
|
||||
## Pattern: load scene → simulate input via button.pressed.emit() or direct
|
||||
## handler call → assert terminal state. No pixel diffing, no xdotool.
|
||||
##
|
||||
## NOTE: Tests that end in a scene transition (change_scene_to_file) assert state
|
||||
## synchronously before the deferred transition fires. The test scene is
|
||||
## queue_freed in after_test() regardless.
|
||||
##
|
||||
## Reference: test_character_creation_sprint28.gd
|
||||
## Ticket: #873 | motivating regression: #872
|
||||
class_name TestMergePathFlowsSprint37
|
||||
extends GdUnitTestSuite
|
||||
|
||||
const MAIN_MENU_SCENE_PATH := "res://scenes/main_menu.tscn"
|
||||
const CHAR_CREATE_SCENE_PATH := "res://scenes/character_creation.tscn"
|
||||
|
||||
var _scene = null # MainMenu or CharacterCreation — untyped, varies per test
|
||||
|
||||
|
||||
func before_test() -> void:
|
||||
# Reset all shared state that these flows touch
|
||||
SimBridge.disconnect_from_sim()
|
||||
SimBridge._last_snapshot = null
|
||||
SimBridge._outbound_buffer.clear()
|
||||
GameState.bookmark_catalog = []
|
||||
GameState.pending_load_path = ""
|
||||
# Clear MetaStack from any leftover overlays to prevent push/pop ordering issues
|
||||
MetaStack._stack.clear()
|
||||
|
||||
|
||||
func after_test() -> void:
|
||||
if is_instance_valid(_scene):
|
||||
_scene.queue_free()
|
||||
_scene = null
|
||||
SimBridge.disconnect_from_sim()
|
||||
SimBridge._outbound_buffer.clear()
|
||||
MetaStack._stack.clear()
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
func _load_main_menu() -> void:
|
||||
var packed := load(MAIN_MENU_SCENE_PATH) as PackedScene
|
||||
# Hard-fail on missing scene (PR #135 review T3): silent skip turns a broken
|
||||
# merge-path test into a uselessly green one.
|
||||
assert_that(packed).override_failure_message(
|
||||
"main_menu.tscn missing — merge-path coverage is broken, not skipped"
|
||||
).is_not_null()
|
||||
_scene = packed.instantiate()
|
||||
add_child(_scene)
|
||||
|
||||
|
||||
func _load_char_create() -> void:
|
||||
var packed := load(CHAR_CREATE_SCENE_PATH) as PackedScene
|
||||
# Hard-fail on missing scene (PR #135 review T3): silent skip turns a broken
|
||||
# merge-path test into a uselessly green one.
|
||||
assert_that(packed).override_failure_message(
|
||||
"character_creation.tscn missing — merge-path coverage is broken, not skipped"
|
||||
).is_not_null()
|
||||
_scene = packed.instantiate()
|
||||
# Seed required state so Start is not disabled (guard added in PR #134 / R2-Hoshe-1).
|
||||
# Individual tests override these as needed. add_child() must run first so
|
||||
# _ready() populates @onready vars (_footer_start, etc.) that
|
||||
# _update_start_btn_state() dereferences.
|
||||
add_child(_scene)
|
||||
_scene._selected_bookmark_id = "test-bookmark"
|
||||
_scene._selected_location_id = "test-location"
|
||||
if _scene.has_method("_update_start_btn_state"):
|
||||
_scene._update_start_btn_state()
|
||||
|
||||
|
||||
func _make_catalog_snapshot() -> Dictionary:
|
||||
## Minimal valid snapshot with a bookmark_catalog for flow-1 testing.
|
||||
## D-192: no version field required; decode accepts snapshots with or without.
|
||||
return {
|
||||
"tick": 0,
|
||||
"entities": [],
|
||||
"game_time": {"day": 0, "time_of_day": 0, "day_phase": "Morning", "tick_rate": "Full"},
|
||||
"player_facing": "North",
|
||||
"player_stance": "Walk",
|
||||
"player_inventory": [],
|
||||
"visible_tiles": [],
|
||||
"nearby_interactions": [],
|
||||
"pending_recognitions": [],
|
||||
"bookmark_catalog": {
|
||||
"bookmarks": [
|
||||
{
|
||||
"id": "bm_tycoon_arion",
|
||||
"title": "Arion Freight Broker",
|
||||
"subtitle": "Start at Arion orbital",
|
||||
"flavor": "Commodities and logistics.",
|
||||
"default_location": "arion",
|
||||
"allowed_locations": ["arion", "arion_low"],
|
||||
"allowed_locations_cultures": ["arion"],
|
||||
"career": "tycoon",
|
||||
"starting_capital_tractus": 50000,
|
||||
}
|
||||
]
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Flow 1: main menu → new game → loading state → catalog received → resolved
|
||||
# =============================================================================
|
||||
# Regression guard for #872: New Game used to hang on "Connecting to simulation..."
|
||||
# because bookmark_catalog was overwritten in receive_bytes before poll_snapshot consumed it.
|
||||
# This test catches that regression by verifying the full state machine:
|
||||
# pressed → loading visible → catalog signal → loading dismissed.
|
||||
|
||||
func test_new_game_shows_loading_screen() -> void:
|
||||
## Pressing New Game must show the loading screen and set _waiting_for_catalog.
|
||||
_load_main_menu()
|
||||
if _scene == null:
|
||||
return
|
||||
|
||||
assert_bool(_scene._waiting_for_catalog).override_failure_message(
|
||||
"_waiting_for_catalog must be false before New Game is pressed"
|
||||
).is_false()
|
||||
|
||||
# Press New Game via the button signal (same as real player input)
|
||||
_scene._new_game_btn.pressed.emit()
|
||||
|
||||
assert_bool(_scene._waiting_for_catalog).override_failure_message(
|
||||
"_waiting_for_catalog must be true after New Game pressed"
|
||||
).is_true()
|
||||
assert_that(_scene._loading_screen).override_failure_message(
|
||||
"Loading screen instance must exist after New Game pressed"
|
||||
).is_not_null()
|
||||
assert_bool(_scene._loading_screen.visible).override_failure_message(
|
||||
"Loading screen must be visible after New Game pressed"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_new_game_catalog_snapshot_resolves_loading_state() -> void:
|
||||
## When snapshot_received fires with a bookmark_catalog, the loading state must clear.
|
||||
## This is the exact regression introduced in #872 — if the catalog is never delivered,
|
||||
## _waiting_for_catalog stays true and the screen hangs forever.
|
||||
_load_main_menu()
|
||||
if _scene == null:
|
||||
return
|
||||
|
||||
# Simulate the New Game press to set up the signal subscription and loading state.
|
||||
# In test mode, connect_to_sim() immediately fires CONNECTED, which triggers
|
||||
# _on_sim_state_changed_for_new_game and connects snapshot_received.
|
||||
_scene._new_game_btn.pressed.emit()
|
||||
|
||||
assert_bool(_scene._waiting_for_catalog).override_failure_message(
|
||||
"Precondition: _waiting_for_catalog must be true before catalog arrives"
|
||||
).is_true()
|
||||
|
||||
# Deliver the catalog via the signal path (same path the server uses in live mode).
|
||||
# snapshot_received is emitted here directly because in test mode poll_snapshot()
|
||||
# uses the harness snapshot (no catalog). The carry-forward fix (#872) ensures
|
||||
# this signal path also works correctly in live mode when ticks batch.
|
||||
var catalog_snapshot := _make_catalog_snapshot()
|
||||
SimBridge.snapshot_received.emit(catalog_snapshot)
|
||||
|
||||
# Terminal state: loading resolved
|
||||
assert_bool(_scene._waiting_for_catalog).override_failure_message(
|
||||
"_waiting_for_catalog must be false after catalog snapshot delivered — #872 regression"
|
||||
).is_false()
|
||||
# PR #135 review H4: assert the SimBridge terminus, not just the loading flag.
|
||||
# In test mode connect_to_sim() jumps state to CONNECTED synchronously; this
|
||||
# guarantees the flow reached its terminal state, not merely that the catalog
|
||||
# flag cleared.
|
||||
assert_int(SimBridge.state).override_failure_message(
|
||||
"SimBridge must be in CONNECTED terminus after catalog resolves — flow completion guard"
|
||||
).is_equal(SimBridge.ConnectionState.CONNECTED)
|
||||
assert_bool(GameState.bookmark_catalog.size() > 0).override_failure_message(
|
||||
"GameState.bookmark_catalog must be populated after catalog snapshot applied"
|
||||
).is_true()
|
||||
assert_str(GameState.bookmark_catalog[0].get("id", "")).override_failure_message(
|
||||
"Catalog entry must have the expected bookmark id"
|
||||
).is_equal("bm_tycoon_arion")
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Flow 2: main menu → load game → save picker → save selected
|
||||
# =============================================================================
|
||||
|
||||
func test_load_game_save_picker_shows_on_browse() -> void:
|
||||
## Calling _on_load_game_browse() must show the save picker panel.
|
||||
_load_main_menu()
|
||||
if _scene == null:
|
||||
return
|
||||
|
||||
assert_bool(_scene._load_panel.visible).override_failure_message(
|
||||
"Load panel must be hidden before Load Game is pressed"
|
||||
).is_false()
|
||||
|
||||
_scene._on_load_game_browse()
|
||||
|
||||
assert_bool(_scene._load_panel.visible).override_failure_message(
|
||||
"Load panel must be visible after _on_load_game_browse()"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_load_game_save_selection_sets_pending_load_path() -> void:
|
||||
## Selecting a save entry must set GameState.pending_load_path for main.gd to consume.
|
||||
_load_main_menu()
|
||||
if _scene == null:
|
||||
return
|
||||
|
||||
var mock_save := {
|
||||
"game_id": "20260421-120000-abc123",
|
||||
"newest_save": "quicksave.sav",
|
||||
}
|
||||
|
||||
# Call _on_save_selected directly — mirrors what the generated save-list button does.
|
||||
_scene._on_save_selected(mock_save)
|
||||
|
||||
assert_str(GameState.pending_load_path).override_failure_message(
|
||||
"pending_load_path must be set to the selected save's full path"
|
||||
).is_equal("user://saves/20260421-120000-abc123/quicksave.sav")
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Flow 3: character creation → submit → sim_bridge receives correct payload
|
||||
# =============================================================================
|
||||
|
||||
func test_character_creation_submit_sends_confirm_bookmark_action() -> void:
|
||||
## _on_start() must queue a ConfirmBookmark action with the selected bookmark
|
||||
## and location IDs. This is the payload the server uses to initialize the run.
|
||||
_load_char_create()
|
||||
if _scene == null:
|
||||
return
|
||||
|
||||
# Ensure SimBridge is connected so send_named_action doesn't silently drop the action
|
||||
SimBridge.connect_to_sim() # test mode: immediately CONNECTED
|
||||
|
||||
_scene._selected_bookmark_id = "bm_tycoon_arion"
|
||||
_scene._selected_location_id = "arion"
|
||||
if _scene.has_method("_update_start_btn_state"):
|
||||
_scene._update_start_btn_state()
|
||||
|
||||
SimBridge._outbound_buffer.clear()
|
||||
_scene._on_start()
|
||||
|
||||
var found := false
|
||||
for entry in SimBridge._outbound_buffer:
|
||||
if entry.get("action_name") == "ConfirmBookmark":
|
||||
var data: Variant = entry.get("action_data")
|
||||
if (
|
||||
data is Dictionary
|
||||
and data.get("bookmark_id") == "bm_tycoon_arion"
|
||||
and data.get("starting_location_id") == "arion"
|
||||
):
|
||||
found = true
|
||||
break
|
||||
assert_bool(found).override_failure_message(
|
||||
"_outbound_buffer must contain ConfirmBookmark{bookmark_id='bm_tycoon_arion', starting_location_id='arion'}"
|
||||
).is_true()
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Flow 4: bookmark tab → select location → confirm → server gets bookmark action
|
||||
# =============================================================================
|
||||
|
||||
func test_bookmark_tab_select_location_then_confirm_queues_action() -> void:
|
||||
## Exercises the full selection path: picking a bookmark, picking a location, then
|
||||
## confirming. Verifies the correct bookmark_id + starting_location_id reach the server.
|
||||
## This is the flow the player actually takes — selection handlers must propagate
|
||||
## to the outbound buffer correctly.
|
||||
|
||||
# Populate catalog before scene instantiation so _build_bookmark_cards() sees it
|
||||
GameState.bookmark_catalog = [
|
||||
{
|
||||
"id": "bm_tycoon_arion",
|
||||
"title": "Arion Freight Broker",
|
||||
"subtitle": "Start at Arion orbital",
|
||||
"flavor": "Commodities and logistics.",
|
||||
"default_location": "arion",
|
||||
"allowed_locations": ["arion", "arion_low"],
|
||||
"allowed_locations_cultures": ["arion"],
|
||||
"career": "tycoon",
|
||||
"starting_capital_tractus": 50000,
|
||||
}
|
||||
]
|
||||
|
||||
_load_char_create()
|
||||
if _scene == null:
|
||||
return
|
||||
|
||||
SimBridge.connect_to_sim() # test mode: immediately CONNECTED
|
||||
SimBridge._outbound_buffer.clear()
|
||||
|
||||
# Simulate the player selecting the bookmark card
|
||||
var bm: Dictionary = GameState.bookmark_catalog[0]
|
||||
_scene._on_bookmark_selected(bm)
|
||||
|
||||
assert_str(_scene._selected_bookmark_id).override_failure_message(
|
||||
"_on_bookmark_selected must update _selected_bookmark_id"
|
||||
).is_equal("bm_tycoon_arion")
|
||||
assert_str(_scene._selected_location_id).override_failure_message(
|
||||
"_on_bookmark_selected must populate _selected_location_id from default_location"
|
||||
).is_not_empty()
|
||||
|
||||
# Simulate the player picking a specific allowed location
|
||||
_scene._on_location_selected("arion_low")
|
||||
|
||||
assert_str(_scene._selected_location_id).override_failure_message(
|
||||
"_on_location_selected must update _selected_location_id"
|
||||
).is_equal("arion_low")
|
||||
|
||||
# Confirm — sends the action to the server
|
||||
_scene._on_start()
|
||||
|
||||
var found := false
|
||||
for entry in SimBridge._outbound_buffer:
|
||||
if entry.get("action_name") == "ConfirmBookmark":
|
||||
var data: Variant = entry.get("action_data")
|
||||
if (
|
||||
data is Dictionary
|
||||
and data.get("bookmark_id") == "bm_tycoon_arion"
|
||||
and data.get("starting_location_id") == "arion_low"
|
||||
):
|
||||
found = true
|
||||
break
|
||||
assert_bool(found).override_failure_message(
|
||||
"_outbound_buffer must contain ConfirmBookmark{bookmark_id='bm_tycoon_arion', starting_location_id='arion_low'}"
|
||||
).is_true()
|
||||
@@ -1,321 +0,0 @@
|
||||
## Sprint 18 — Minimap rendering (#151)
|
||||
## Spec refs: D-013 (diegetic insert/POI system), D-015 (fixed-north, player-centered),
|
||||
## D-049 (z-layer 6 = InsertOverlay)
|
||||
##
|
||||
## MinimapRenderer: circular insert overlay, always renders frame, draws discovered POIs.
|
||||
## Scene: res://ui/minimap.tscn (class_name MinimapRenderer)
|
||||
## Positioned at InsertOverlay/Minimap in main.tscn.
|
||||
##
|
||||
## Tests run against live Stig implementation (minimap.gd).
|
||||
class_name TestMinimapSprint18
|
||||
extends GdUnitTestSuite
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
const MINIMAP_SCENE_PATH: String = "res://ui/minimap.tscn"
|
||||
const MAIN_SCENE = preload("res://scenes/main.tscn")
|
||||
|
||||
func _make_minimap() -> Control:
|
||||
if not ResourceLoader.exists(MINIMAP_SCENE_PATH):
|
||||
push_warning("TestMinimapSprint18: minimap.tscn not found — skip")
|
||||
return null
|
||||
var node: Control = load(MINIMAP_SCENE_PATH).instantiate()
|
||||
add_child(node)
|
||||
return node
|
||||
|
||||
|
||||
func _make_poi(overrides: Dictionary = {}) -> Dictionary:
|
||||
var base: Dictionary = {
|
||||
"id": "poi_test_001",
|
||||
"x": 20,
|
||||
"y": 15,
|
||||
"poi_category": "location",
|
||||
"label": "Exit A",
|
||||
}
|
||||
base.merge(overrides, true)
|
||||
return base
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Lifecycle
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func before_test() -> void:
|
||||
GameState.discovered_pois = []
|
||||
GameState.player_position = Vector2(10.0, 10.0)
|
||||
GameState.insert_active = true
|
||||
|
||||
func after_test() -> void:
|
||||
GameState.discovered_pois = []
|
||||
GameState.player_position = Vector2.ZERO
|
||||
GameState.insert_active = true
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Scene and class
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_minimap_scene_exists() -> void:
|
||||
assert_bool(ResourceLoader.exists(MINIMAP_SCENE_PATH)).override_failure_message(
|
||||
"Minimap scene must exist at res://ui/minimap.tscn (#151)"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_minimap_instantiates_without_crash() -> void:
|
||||
var mm := _make_minimap()
|
||||
if mm == null: return
|
||||
assert_that(mm).is_not_null()
|
||||
mm.queue_free()
|
||||
|
||||
|
||||
func test_minimap_is_minimap_renderer_class() -> void:
|
||||
## class_name MinimapRenderer in minimap.gd.
|
||||
var mm := _make_minimap()
|
||||
if mm == null: return
|
||||
assert_bool(mm is MinimapRenderer).override_failure_message(
|
||||
"Minimap node must be a MinimapRenderer instance (check class_name in minimap.gd)"
|
||||
).is_true()
|
||||
mm.queue_free()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Constants: D-015, visual parameters
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_minimap_radius_constant() -> void:
|
||||
## MINIMAP_RADIUS defines the sim-tile distance of visible POI area.
|
||||
## Value is tuned to 24 tiles — reasonable coverage without map reveal.
|
||||
assert_float(MinimapRenderer.MINIMAP_RADIUS).override_failure_message(
|
||||
"MinimapRenderer.MINIMAP_RADIUS must be 24.0"
|
||||
).is_equal_approx(24.0, 0.01)
|
||||
|
||||
|
||||
func test_player_dot_radius_defined() -> void:
|
||||
## Player dot must be visible (> 0) and distinct from POI dot.
|
||||
assert_float(MinimapRenderer.PLAYER_DOT_RADIUS).is_greater(0.0)
|
||||
|
||||
|
||||
func test_poi_dot_radius_defined() -> void:
|
||||
## POI dot must be visible (> 0).
|
||||
assert_float(MinimapRenderer.POI_DOT_RADIUS).is_greater(0.0)
|
||||
|
||||
|
||||
func test_player_dot_larger_than_poi_dot() -> void:
|
||||
## D-015: Player is always centered and visually distinct.
|
||||
## Player dot should be at least as large as POI dot.
|
||||
assert_float(MinimapRenderer.PLAYER_DOT_RADIUS).is_greater_equal(MinimapRenderer.POI_DOT_RADIUS)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _category_color() — D-013 POI category color mapping
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_category_color_danger_is_hostile_color() -> void:
|
||||
## "danger", "threat", "hostile" → ENTITY_COLOR_HOSTILE (red)
|
||||
for cat in ["danger", "threat", "hostile"]:
|
||||
var color: Color = MinimapRenderer._category_color(cat)
|
||||
assert_that(color).override_failure_message(
|
||||
"Category '%s' must map to ENTITY_COLOR_HOSTILE" % cat
|
||||
).is_equal(Constants.ENTITY_COLOR_HOSTILE)
|
||||
|
||||
|
||||
func test_category_color_evidence_is_poi_color() -> void:
|
||||
## "evidence", "note", "clue" → ENTITY_COLOR_POI (amber)
|
||||
for cat in ["evidence", "note", "clue"]:
|
||||
var color: Color = MinimapRenderer._category_color(cat)
|
||||
assert_that(color).override_failure_message(
|
||||
"Category '%s' must map to ENTITY_COLOR_POI (amber)" % cat
|
||||
).is_equal(Constants.ENTITY_COLOR_POI)
|
||||
|
||||
|
||||
func test_category_color_contact_is_unknown_color() -> void:
|
||||
## "contact", "npc", "person" → ENTITY_COLOR_UNKNOWN (teal)
|
||||
for cat in ["contact", "npc", "person"]:
|
||||
var color: Color = MinimapRenderer._category_color(cat)
|
||||
assert_that(color).override_failure_message(
|
||||
"Category '%s' must map to ENTITY_COLOR_UNKNOWN (teal)" % cat
|
||||
).is_equal(Constants.ENTITY_COLOR_UNKNOWN)
|
||||
|
||||
|
||||
func test_category_color_unknown_category_defaults_to_insert_text() -> void:
|
||||
## Unknown/unspecified categories → INSERT_COLOR_TEXT (white-blue default)
|
||||
var color: Color = MinimapRenderer._category_color("some_unknown_type")
|
||||
assert_that(color).override_failure_message(
|
||||
"Unknown category must default to INSERT_COLOR_TEXT"
|
||||
).is_equal(Constants.INSERT_COLOR_TEXT)
|
||||
|
||||
|
||||
func test_category_color_empty_string_defaults() -> void:
|
||||
## Empty category string → default color, no crash.
|
||||
var color: Color = MinimapRenderer._category_color("")
|
||||
assert_that(color).is_equal(Constants.INSERT_COLOR_TEXT)
|
||||
|
||||
|
||||
func test_category_color_case_insensitive() -> void:
|
||||
## Category matching is case-insensitive (uses to_lower()).
|
||||
var danger_lower := MinimapRenderer._category_color("danger")
|
||||
var danger_upper := MinimapRenderer._category_color("DANGER")
|
||||
var danger_mixed := MinimapRenderer._category_color("Danger")
|
||||
assert_that(danger_lower).is_equal(danger_upper)
|
||||
assert_that(danger_lower).is_equal(danger_mixed)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# set_insert_active() — D-049: insert layer visibility
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_set_insert_active_false_hides_minimap() -> void:
|
||||
## When insert is inactive, minimap must be hidden.
|
||||
var mm := _make_minimap()
|
||||
if mm == null: return
|
||||
mm.set_insert_active(false)
|
||||
assert_bool(mm.visible).override_failure_message(
|
||||
"set_insert_active(false) must hide the minimap"
|
||||
).is_false()
|
||||
mm.queue_free()
|
||||
|
||||
|
||||
func test_set_insert_active_true_shows_minimap() -> void:
|
||||
## When insert is active, minimap must be visible.
|
||||
var mm := _make_minimap()
|
||||
if mm == null: return
|
||||
mm.set_insert_active(false)
|
||||
mm.set_insert_active(true)
|
||||
assert_bool(mm.visible).override_failure_message(
|
||||
"set_insert_active(true) must show the minimap"
|
||||
).is_true()
|
||||
mm.queue_free()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Main scene structural check: InsertOverlay/Minimap
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_minimap_in_main_scene_on_insert_overlay() -> void:
|
||||
## D-049: Minimap must be in InsertOverlay (CanvasLayer 10), not UILayer.
|
||||
## Scene path: Game/InsertOverlay/Minimap or InsertOverlay/Minimap.
|
||||
if not ResourceLoader.exists("res://scenes/main.tscn"):
|
||||
push_warning("TestMinimapSprint18: main.tscn not found — scene tree test skipped")
|
||||
return
|
||||
var scene: Node = MAIN_SCENE.instantiate()
|
||||
auto_free(scene)
|
||||
add_child(scene)
|
||||
|
||||
# Check for Minimap in InsertOverlay
|
||||
var insert_overlay := scene.get_node_or_null("InsertOverlay")
|
||||
assert_that(insert_overlay != null).override_failure_message(
|
||||
"InsertOverlay (CanvasLayer 10) must exist in main.tscn"
|
||||
).is_true()
|
||||
if insert_overlay == null: return
|
||||
|
||||
var minimap := insert_overlay.get_node_or_null("Minimap")
|
||||
assert_that(minimap != null).override_failure_message(
|
||||
"Minimap must be a child of InsertOverlay in main.tscn (D-049: insert layer)"
|
||||
).is_true()
|
||||
if minimap == null: return
|
||||
|
||||
assert_bool(minimap is MinimapRenderer).override_failure_message(
|
||||
"InsertOverlay/Minimap must be a MinimapRenderer instance"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_insert_overlay_is_canvas_layer_10() -> void:
|
||||
## InsertOverlay must be CanvasLayer 10 (CANVAS_INSERT per D-049).
|
||||
if not ResourceLoader.exists("res://scenes/main.tscn"):
|
||||
push_warning("TestMinimapSprint18: main.tscn not found — canvas layer test skipped")
|
||||
return
|
||||
var scene: Node = MAIN_SCENE.instantiate()
|
||||
auto_free(scene)
|
||||
add_child(scene)
|
||||
|
||||
var insert_overlay := scene.get_node_or_null("InsertOverlay") as CanvasLayer
|
||||
if insert_overlay == null: return
|
||||
assert_int(insert_overlay.layer).override_failure_message(
|
||||
"InsertOverlay must be CanvasLayer %d (CANVAS_INSERT)" % Constants.CANVAS_INSERT
|
||||
).is_equal(Constants.CANVAS_INSERT)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# GameState.discovered_pois integration
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_discovered_pois_field_exists_in_gamestate() -> void:
|
||||
assert_bool(GameState.has("discovered_pois")).override_failure_message(
|
||||
"GameState must have 'discovered_pois' field (#151)"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_discovered_pois_set_from_poi_list_snapshot() -> void:
|
||||
## Snapshot with "poi_list" key (Sprint 17 server wire name) populates discovered_pois.
|
||||
GameState.apply_snapshot({
|
||||
"tick": 1,
|
||||
"poi_list": [
|
||||
_make_poi({"id": "p1", "x": 50, "y": 30, "poi_category": "location"}),
|
||||
_make_poi({"id": "p2", "x": 80, "y": 15, "poi_category": "contact"}),
|
||||
],
|
||||
})
|
||||
assert_int(GameState.discovered_pois.size()).override_failure_message(
|
||||
"discovered_pois must be populated from snapshot 'poi_list' field"
|
||||
).is_equal(2)
|
||||
|
||||
|
||||
func test_discovered_pois_set_from_discovered_pois_snapshot() -> void:
|
||||
## Snapshot with "discovered_pois" key also works.
|
||||
GameState.apply_snapshot({
|
||||
"tick": 2,
|
||||
"discovered_pois": [_make_poi()],
|
||||
})
|
||||
assert_int(GameState.discovered_pois.size()).is_equal(1)
|
||||
|
||||
|
||||
func test_discovered_pois_persists_when_absent_from_snapshot() -> void:
|
||||
## Like player_knowledge: POI list persists when server doesn't send an update.
|
||||
GameState.discovered_pois = [_make_poi()]
|
||||
GameState.apply_snapshot({"tick": 3})
|
||||
assert_int(GameState.discovered_pois.size()).override_failure_message(
|
||||
"discovered_pois must persist when absent from snapshot (not cleared each tick)"
|
||||
).is_equal(1)
|
||||
|
||||
|
||||
func test_discovered_pois_poi_category_field_present() -> void:
|
||||
## MinimapRenderer reads poi_category to determine shape/color.
|
||||
## Verify the wire format includes this field.
|
||||
GameState.apply_snapshot({
|
||||
"tick": 1,
|
||||
"poi_list": [_make_poi({"poi_category": "danger"})],
|
||||
})
|
||||
assert_int(GameState.discovered_pois.size()).is_greater(0)
|
||||
var first_poi: Dictionary = GameState.discovered_pois[0]
|
||||
assert_bool(first_poi.has("poi_category")).override_failure_message(
|
||||
"POI entries must have 'poi_category' field for MinimapRenderer shape selection"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_discovered_pois_x_y_fields_present() -> void:
|
||||
## MinimapRenderer reads x, y for position calculation.
|
||||
GameState.apply_snapshot({
|
||||
"tick": 1,
|
||||
"poi_list": [_make_poi({"x": 42, "y": 17})],
|
||||
})
|
||||
assert_int(GameState.discovered_pois.size()).is_greater(0)
|
||||
var first_poi: Dictionary = GameState.discovered_pois[0]
|
||||
assert_bool(first_poi.has("x") and first_poi.has("y")).override_failure_message(
|
||||
"POI entries must have 'x' and 'y' coordinate fields"
|
||||
).is_true()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Color constants: all distinct
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_category_colors_are_distinct() -> void:
|
||||
## All three primary category color groups must be visually distinct.
|
||||
var danger_color := MinimapRenderer._category_color("danger")
|
||||
var evidence_color := MinimapRenderer._category_color("evidence")
|
||||
var contact_color := MinimapRenderer._category_color("contact")
|
||||
assert_that(danger_color).is_not_equal(evidence_color)
|
||||
assert_that(evidence_color).is_not_equal(contact_color)
|
||||
assert_that(danger_color).is_not_equal(contact_color)
|
||||
@@ -1 +0,0 @@
|
||||
uid://dm46ip672i3jc
|
||||
@@ -1,10 +1,14 @@
|
||||
## Client P0 regression tests: guards for Bug #5 (monologue lost) and Bug #2 (camera drift).
|
||||
## Client P0 regression tests: guards for Bug #5 (monologue lost), Bug #2 (camera drift),
|
||||
## and Bug #872 (bookmark_catalog lost on batch receive).
|
||||
## These must pass before any other client testing is meaningful.
|
||||
##
|
||||
## Bug #5: Monologue text lost when server sends snapshots faster than client
|
||||
## consumes them. Fix: carry-forward one-shot events in receive_bytes().
|
||||
## Bug #2: Camera doesn't center at startup / drifts during pause. Fix: anchor
|
||||
## pattern with smoothing disabled until first snapshot applied.
|
||||
## Bug #872: bookmark_catalog silently dropped when tick 0 (with catalog) and tick 1
|
||||
## (without catalog) arrive in the same TCP batch. Fix: carry-forward
|
||||
## bookmark_catalog in receive_bytes() like save_result/settings_response.
|
||||
##
|
||||
## Spec ref: stig-round3.md Section 1 (P0 tests #1, #2).
|
||||
class_name TestP0Regressions
|
||||
@@ -39,12 +43,13 @@ func after_test() -> void:
|
||||
# -- Helpers -------------------------------------------------------------------
|
||||
|
||||
## Encode a minimal valid snapshot as MessagePack bytes.
|
||||
## Protocol.decode_snapshot() requires: tick, version, entities (with kind as
|
||||
## bare string for unit enum variants per rmp_serde wire format).
|
||||
## Protocol.decode_snapshot() requires: tick, entities (with kind as bare string
|
||||
## for unit enum variants per rmp_serde wire format). D-192 dropped the version
|
||||
## field — kept here inertly in existing fixtures so decode still accepts either
|
||||
## shape while older tests migrate.
|
||||
func _make_snapshot_bytes(overrides: Dictionary = {}) -> PackedByteArray:
|
||||
var snapshot := {
|
||||
"tick": overrides.get("tick", 1),
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"entities": overrides.get("entities", [{
|
||||
"entity_id": 1,
|
||||
"x": 10.0,
|
||||
@@ -71,6 +76,8 @@ func _make_snapshot_bytes(overrides: Dictionary = {}) -> PackedByteArray:
|
||||
snapshot["current_monologue"] = overrides["current_monologue"]
|
||||
if overrides.has("current_dialogue"):
|
||||
snapshot["current_dialogue"] = overrides["current_dialogue"]
|
||||
if overrides.has("bookmark_catalog"):
|
||||
snapshot["bookmark_catalog"] = overrides["bookmark_catalog"]
|
||||
var result = Messagepack.encode(snapshot)
|
||||
return result.value
|
||||
|
||||
@@ -229,3 +236,71 @@ func test_camera_anchored_after_pause_unpause() -> void:
|
||||
# Camera still tracking player (position may have changed due to test_snapshot)
|
||||
var player_pos := GameState.player_position * Constants.TILE_SIZE
|
||||
assert_that(camera.global_position).is_equal(player_pos)
|
||||
|
||||
|
||||
# -- Bug #872: bookmark_catalog carry-forward ---------------------------------
|
||||
# Server sends bookmark_catalog on tick 0. If tick 1 arrives before poll_snapshot()
|
||||
# is called (same TCP batch), the inner receive loop overwrites _last_snapshot and
|
||||
# the catalog is silently lost. The carry-forward fix must preserve the catalog.
|
||||
|
||||
func test_bookmark_catalog_not_lost_on_snapshot_overwrite() -> void:
|
||||
var catalog := {
|
||||
"bookmarks": [
|
||||
{
|
||||
"id": "bm_tycoon_arion",
|
||||
"title": "Arion Freight Broker",
|
||||
"subtitle": "Start at Arion orbital",
|
||||
"flavor": "Commodities and logistics.",
|
||||
"default_location": "arion",
|
||||
"allowed_locations": ["arion"],
|
||||
"allowed_locations_cultures": ["arion"],
|
||||
"career": "tycoon",
|
||||
"starting_capital_tractus": 50000,
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
# Tick 0: server sends catalog automatically after handshake
|
||||
var bytes_tick0 := _make_snapshot_bytes({
|
||||
"tick": 0,
|
||||
"bookmark_catalog": catalog,
|
||||
})
|
||||
SimBridge.receive_bytes(bytes_tick0)
|
||||
|
||||
# Tick 1: server sends next tick WITHOUT catalog (fast server, same TCP batch)
|
||||
var bytes_tick1 := _make_snapshot_bytes({"tick": 1})
|
||||
SimBridge.receive_bytes(bytes_tick1)
|
||||
|
||||
# Assert: catalog must survive the overwrite — this is the Bug #872 fix.
|
||||
assert_that(SimBridge._last_snapshot).is_not_null()
|
||||
var bmc: Variant = SimBridge._last_snapshot.get("bookmark_catalog")
|
||||
assert_that(bmc).is_not_null()
|
||||
assert_that(bmc is Dictionary).is_true()
|
||||
var bookmarks: Variant = bmc.get("bookmarks")
|
||||
assert_that(bookmarks is Array).is_true()
|
||||
assert_that((bookmarks as Array).size()).is_equal(1)
|
||||
assert_that((bookmarks as Array)[0].get("id")).is_equal("bm_tycoon_arion")
|
||||
|
||||
|
||||
func test_bookmark_catalog_not_carried_forward_after_consumption() -> void:
|
||||
# After poll_snapshot() consumes the catalog, the next snapshot without catalog
|
||||
# must NOT carry it forward (it was already consumed and the scene transitioned).
|
||||
var catalog := {
|
||||
"bookmarks": [{"id": "bm_test", "title": "Test", "subtitle": "", "flavor": "",
|
||||
"default_location": "arion", "allowed_locations": [], "allowed_locations_cultures": [],
|
||||
"career": "tycoon", "starting_capital_tractus": 0}]
|
||||
}
|
||||
var bytes_tick0 := _make_snapshot_bytes({"tick": 0, "bookmark_catalog": catalog})
|
||||
SimBridge.receive_bytes(bytes_tick0)
|
||||
|
||||
# Simulate poll_snapshot() consumption — sets _last_snapshot to null
|
||||
var snapshot = SimBridge._last_snapshot
|
||||
SimBridge._last_snapshot = null
|
||||
assert_that(snapshot).is_not_null()
|
||||
|
||||
# Next snapshot arrives without catalog — no carry-forward should happen
|
||||
var bytes_tick1 := _make_snapshot_bytes({"tick": 1})
|
||||
SimBridge.receive_bytes(bytes_tick1)
|
||||
|
||||
var bmc: Variant = SimBridge._last_snapshot.get("bookmark_catalog")
|
||||
assert_that(bmc).is_null()
|
||||
|
||||
@@ -188,7 +188,7 @@ func test_decode_snapshot_malformed_entities_counted() -> void:
|
||||
# Snapshot with one valid and one malformed entity — decode_errors should count the bad one
|
||||
var raw := {
|
||||
"tick": 7,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [
|
||||
{"entity_id": 1, "x": 5.0, "y": 10.0, "z": 0, "kind": "Npc"},
|
||||
{"entity_id": 2, "broken": true}, # Missing required fields
|
||||
@@ -282,7 +282,6 @@ func test_decode_snapshot_v2_full() -> void:
|
||||
|
||||
assert_that(snapshot).is_not_null()
|
||||
assert_that(snapshot.tick).is_equal(500)
|
||||
assert_that(snapshot.version).is_equal(Protocol.PROTOCOL_VERSION)
|
||||
|
||||
# game_time
|
||||
assert_that(snapshot.game_time).is_not_null()
|
||||
@@ -309,7 +308,6 @@ func test_existing_fixtures_have_v2_fields() -> void:
|
||||
var bytes = _load_fixture(fixture_name)
|
||||
var snapshot = Protocol.decode_snapshot(bytes)
|
||||
assert_that(snapshot).is_not_null()
|
||||
assert_that(snapshot.version).is_equal(Protocol.PROTOCOL_VERSION)
|
||||
assert_that(snapshot.player_facing).is_equal("North")
|
||||
assert_that(snapshot.game_time).is_not_null()
|
||||
|
||||
@@ -324,30 +322,6 @@ func test_multi_entity_visibility_sectors() -> void:
|
||||
assert_that(snapshot.entities[3].visibility).is_equal("Forward")
|
||||
|
||||
|
||||
# -- Version enforcement (strict PROTOCOL_VERSION check) --------------------
|
||||
|
||||
func test_decode_snapshot_rejects_missing_version() -> void:
|
||||
# Snapshot without version field → rejected by strict version check
|
||||
var v1_raw := {"tick": 10, "entities": [
|
||||
{"entity_id": 1, "x": 5.0, "y": 5.0, "z": 0, "kind": "Player"},
|
||||
]}
|
||||
var encoded: Variant = Messagepack.encode(v1_raw)
|
||||
assert_that(encoded.status).is_null()
|
||||
|
||||
var snapshot: Variant = Protocol.decode_snapshot(encoded.value)
|
||||
assert_that(snapshot).is_null()
|
||||
|
||||
|
||||
func test_decode_snapshot_rejects_old_version() -> void:
|
||||
# Snapshot with version 2 → rejected by strict version check
|
||||
var old_raw := {"tick": 10, "version": 2, "entities": []}
|
||||
var encoded: Variant = Messagepack.encode(old_raw)
|
||||
assert_that(encoded.status).is_null()
|
||||
|
||||
var snapshot: Variant = Protocol.decode_snapshot(encoded.value)
|
||||
assert_that(snapshot).is_null()
|
||||
|
||||
|
||||
# -- Batch input fixture (D-030 Layer 1 bidirectional symmetry) ----------------
|
||||
|
||||
func test_decode_batch_input_fixture() -> void:
|
||||
@@ -391,7 +365,7 @@ func test_decode_snapshot_with_bookmark_catalog() -> void:
|
||||
# Hand-built dict — fixture generation requires server work, skip round-trip (#614).
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"bookmark_catalog": {
|
||||
"bookmarks": [
|
||||
@@ -451,7 +425,7 @@ func test_decode_snapshot_no_bookmark_catalog_is_null() -> void:
|
||||
# Snapshot without bookmark_catalog key → field should be null.
|
||||
var raw := {
|
||||
"tick": 2,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
}
|
||||
var encoded: Variant = Messagepack.encode(raw)
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
## D-030 Layer 1: Protocol bridge tests for ObserverSnapshot features.
|
||||
## Validates player_stance (D-053) and player_inventory (D-065) decode,
|
||||
## GameState storage, SimBridge test mode, input encoding for stance toggles,
|
||||
## protocol version checks, and fixture round-trips.
|
||||
## Spec refs: D-053, D-065, D-020, #449
|
||||
## and fixture round-trips. Protocol version checks removed per D-192.
|
||||
## Spec refs: D-053, D-065, D-020, #449, D-192
|
||||
class_name TestProtocolBridge
|
||||
extends GdUnitTestSuite
|
||||
|
||||
@@ -24,33 +24,12 @@ func _load_fixture(name: String) -> PackedByteArray:
|
||||
return file.get_buffer(file.get_length())
|
||||
|
||||
|
||||
# -- Protocol version upgrade -------------------------------------------------
|
||||
# Tautological "PROTOCOL_VERSION == N" assertions deleted: they assert a constant
|
||||
# equals its own literal, fail mechanically on every protocol bump, and have
|
||||
# never caught a real bug. Mismatch handling is exercised by test_rejects_version_6
|
||||
# below; field-presence is exercised by the per-version decode tests.
|
||||
|
||||
func test_fixtures_at_protocol_version_8() -> void:
|
||||
# NOTE: These binary fixtures embed version 8 and are rejected by the version
|
||||
# mismatch guard in decode_snapshot(). This test is pre-existing broken since v9+.
|
||||
# Fixtures need regeneration via `make fixtures-gauntlet` to match current protocol.
|
||||
# Skipping rather than deleting to preserve the fixture round-trip pattern.
|
||||
pass
|
||||
|
||||
|
||||
func test_rejects_version_6() -> void:
|
||||
var raw := {"tick": 1, "version": 6, "entities": []}
|
||||
var encoded = Messagepack.encode(raw)
|
||||
var snapshot = Protocol.decode_snapshot(encoded.value)
|
||||
assert_that(snapshot).is_null()
|
||||
|
||||
|
||||
# -- player_stance decode (D-053) ---------------------------------------------
|
||||
|
||||
func test_decode_player_stance_walk() -> void:
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"player_stance": "Walk",
|
||||
"player_inventory": [],
|
||||
@@ -64,7 +43,7 @@ func test_decode_player_stance_walk() -> void:
|
||||
func test_decode_player_stance_sprint() -> void:
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"player_stance": "Sprint",
|
||||
"player_inventory": [],
|
||||
@@ -77,7 +56,7 @@ func test_decode_player_stance_sprint() -> void:
|
||||
func test_decode_player_stance_careful() -> void:
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"player_stance": "Careful",
|
||||
"player_inventory": [],
|
||||
@@ -90,7 +69,7 @@ func test_decode_player_stance_careful() -> void:
|
||||
func test_decode_player_stance_crouch() -> void:
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"player_stance": "Crouch",
|
||||
"player_inventory": [],
|
||||
@@ -104,7 +83,7 @@ func test_decode_player_stance_missing_defaults_to_walk() -> void:
|
||||
# v6 snapshot without player_stance → should default to "Walk"
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
}
|
||||
var encoded = Messagepack.encode(raw)
|
||||
@@ -118,7 +97,7 @@ func test_decode_player_stance_missing_defaults_to_walk() -> void:
|
||||
func test_decode_empty_inventory() -> void:
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"player_stance": "Walk",
|
||||
"player_inventory": [],
|
||||
@@ -132,7 +111,7 @@ func test_decode_smuggler_inventory_3_items() -> void:
|
||||
# D-065: smuggler carries 3 specific items
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"player_stance": "Walk",
|
||||
"player_inventory": [
|
||||
@@ -161,7 +140,7 @@ func test_decode_full_9_slot_inventory() -> void:
|
||||
items.append({"item_id": 100 + i, "name": "Item %d" % i, "slot": i})
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"player_inventory": items,
|
||||
}
|
||||
@@ -177,7 +156,7 @@ func test_decode_full_9_slot_inventory() -> void:
|
||||
func test_decode_inventory_missing_defaults_to_empty() -> void:
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
}
|
||||
var encoded = Messagepack.encode(raw)
|
||||
@@ -188,7 +167,7 @@ func test_decode_inventory_missing_defaults_to_empty() -> void:
|
||||
func test_decode_inventory_skips_malformed_items() -> void:
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"player_inventory": [
|
||||
{"item_id": 100, "name": "Valid Item", "slot": 0},
|
||||
@@ -209,7 +188,7 @@ func test_decode_inventory_skips_malformed_items() -> void:
|
||||
func test_decode_inventory_item_slot_defaults_to_zero() -> void:
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"player_inventory": [
|
||||
{"item_id": 100, "name": "No Slot"},
|
||||
@@ -281,12 +260,6 @@ func test_sim_bridge_test_snapshot_has_player_inventory() -> void:
|
||||
assert_that(snap.player_inventory is Array).is_true()
|
||||
|
||||
|
||||
func test_sim_bridge_test_snapshot_uses_current_protocol_version() -> void:
|
||||
SimBridge.reset_test_state()
|
||||
var snap = SimBridge._test_snapshot()
|
||||
assert_that(snap.version).is_equal(Protocol.PROTOCOL_VERSION)
|
||||
|
||||
|
||||
# -- Fixture: v6 snapshots include new fields ----------------------------------
|
||||
|
||||
func test_fixture_snapshots_have_v6_defaults() -> void:
|
||||
@@ -334,7 +307,7 @@ func test_full_v6_snapshot_decode() -> void:
|
||||
# Simulate a realistic v6 snapshot with all fields populated
|
||||
var raw := {
|
||||
"tick": 100,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"game_time": {"day": 1, "time_of_day": 720, "day_phase": "Evening", "tick_rate": "Full"},
|
||||
"player_facing": "Southeast",
|
||||
"player_stance": "Careful",
|
||||
@@ -367,7 +340,6 @@ func test_full_v6_snapshot_decode() -> void:
|
||||
|
||||
assert_that(snapshot).is_not_null()
|
||||
assert_that(snapshot.tick).is_equal(100)
|
||||
assert_that(snapshot.version).is_equal(Protocol.PROTOCOL_VERSION)
|
||||
assert_that(snapshot.player_facing).is_equal("Southeast")
|
||||
assert_that(snapshot.player_stance).is_equal("Careful")
|
||||
assert_that(snapshot.player_inventory.size()).is_equal(3)
|
||||
|
||||
@@ -12,7 +12,7 @@ extends GdUnitTestSuite
|
||||
func test_decode_pending_recognitions_basic() -> void:
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"pending_recognitions": [
|
||||
{"entity_id": 100, "x": 13.5, "y": 12.5, "z": 0, "remaining_ticks": 4, "total_delay_ticks": 6},
|
||||
@@ -33,7 +33,7 @@ func test_decode_pending_recognitions_basic() -> void:
|
||||
func test_decode_pending_recognitions_empty() -> void:
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"pending_recognitions": [],
|
||||
}
|
||||
@@ -45,7 +45,7 @@ func test_decode_pending_recognitions_empty() -> void:
|
||||
func test_decode_pending_recognitions_missing_defaults_empty() -> void:
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
}
|
||||
var encoded = Messagepack.encode(raw)
|
||||
@@ -56,7 +56,7 @@ func test_decode_pending_recognitions_missing_defaults_empty() -> void:
|
||||
func test_decode_pending_recognitions_skips_malformed() -> void:
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"pending_recognitions": [
|
||||
{"entity_id": 100, "x": 13.5, "y": 12.5, "z": 0, "remaining_ticks": 4, "total_delay_ticks": 6},
|
||||
@@ -76,7 +76,7 @@ func test_decode_pending_recognitions_defaults() -> void:
|
||||
# remaining_ticks and total_delay_ticks default to 0 and 1
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"pending_recognitions": [
|
||||
{"entity_id": 100, "x": 5.0, "y": 5.0},
|
||||
@@ -94,7 +94,7 @@ func test_decode_pending_recognitions_defaults() -> void:
|
||||
func test_decode_current_dialogue() -> void:
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"current_dialogue": {
|
||||
"npc_name": "Kael",
|
||||
@@ -123,7 +123,7 @@ func test_decode_current_dialogue() -> void:
|
||||
func test_decode_current_dialogue_missing_is_null() -> void:
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
}
|
||||
var encoded = Messagepack.encode(raw)
|
||||
@@ -136,7 +136,7 @@ func test_decode_current_dialogue_options_default_fields() -> void:
|
||||
# response_id and priority default when absent
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"current_dialogue": {
|
||||
"speech": "Just speech.",
|
||||
@@ -158,7 +158,7 @@ func test_decode_current_dialogue_options_default_fields() -> void:
|
||||
func test_decode_current_dialogue_confrontation_option() -> void:
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"current_dialogue": {
|
||||
"npc_name": "Sera",
|
||||
@@ -179,7 +179,7 @@ func test_decode_current_dialogue_confrontation_option() -> void:
|
||||
func test_decode_current_dialogue_skips_malformed_options() -> void:
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"current_dialogue": {
|
||||
"npc_name": "Sera",
|
||||
@@ -332,7 +332,7 @@ func test_insert_color_constants_exist() -> void:
|
||||
func test_full_v7_snapshot_decode() -> void:
|
||||
var raw := {
|
||||
"tick": 200,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"game_time": {"day": 2, "time_of_day": 1000, "day_phase": "Evening", "tick_rate": "Full"},
|
||||
"player_facing": "West",
|
||||
"player_stance": "Careful",
|
||||
@@ -362,7 +362,6 @@ func test_full_v7_snapshot_decode() -> void:
|
||||
|
||||
assert_that(snapshot).is_not_null()
|
||||
assert_that(snapshot.tick).is_equal(200)
|
||||
assert_that(snapshot.version).is_equal(Protocol.PROTOCOL_VERSION)
|
||||
assert_that(snapshot.player_facing).is_equal("West")
|
||||
assert_that(snapshot.player_stance).is_equal("Careful")
|
||||
assert_that(snapshot.player_inventory.size()).is_equal(1)
|
||||
|
||||
@@ -174,8 +174,6 @@ func test_sim_bridge_test_tiles_contain_all_types() -> void:
|
||||
func test_sim_bridge_test_snapshot_has_v2_fields() -> void:
|
||||
SimBridge.reset_test_state()
|
||||
var snap = SimBridge._test_snapshot()
|
||||
assert_that(snap.has("version")).is_true()
|
||||
assert_that(snap.version).is_equal(Protocol.PROTOCOL_VERSION)
|
||||
assert_that(snap.has("game_time")).is_true()
|
||||
assert_that(snap.has("player_facing")).is_true()
|
||||
assert_that(snap.has("visible_tiles")).is_true()
|
||||
|
||||
@@ -1,210 +0,0 @@
|
||||
## Sprint 19 — Game session management (#258, D-085)
|
||||
## Per-game save directories: created on New Game, resumed via game-id.
|
||||
## SessionManager autoload: new_game(), resume_game(), list_game_dirs().
|
||||
class_name TestSessionManagerSprint19
|
||||
extends GdUnitTestSuite
|
||||
|
||||
const MAIN_MENU_SCENE = preload("res://scenes/main_menu.tscn")
|
||||
|
||||
# Game IDs created during the current test — deleted in after_test().
|
||||
var _created_ids: Array = []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Lifecycle
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func before_test() -> void:
|
||||
GameState.current_game_id = ""
|
||||
_created_ids = []
|
||||
|
||||
|
||||
func after_test() -> void:
|
||||
for game_id in _created_ids:
|
||||
var path := "user://saves/" + game_id
|
||||
DirAccess.remove_absolute(ProjectSettings.globalize_path(path))
|
||||
_created_ids.clear()
|
||||
GameState.current_game_id = ""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helper: call new_game() and track the created directory for cleanup.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func _new_game() -> String:
|
||||
var game_id := SessionManager.new_game()
|
||||
if not game_id.is_empty():
|
||||
_created_ids.append(game_id)
|
||||
return game_id
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# GameState.current_game_id field
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_current_game_id_field_exists() -> void:
|
||||
## D-085: GameState must have current_game_id field.
|
||||
assert_bool(GameState.has("current_game_id")).override_failure_message(
|
||||
"GameState must have 'current_game_id' field (D-085 #258)"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_current_game_id_default_is_empty_string() -> void:
|
||||
## Before any session starts, current_game_id is empty.
|
||||
GameState.current_game_id = ""
|
||||
assert_str(GameState.current_game_id).override_failure_message(
|
||||
"GameState.current_game_id default must be empty string"
|
||||
).is_empty()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# SessionManager autoload exists
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_session_manager_autoload_exists() -> void:
|
||||
## SessionManager must be registered as an autoload.
|
||||
var sm := Engine.get_singleton("SessionManager")
|
||||
assert_that(sm != null).override_failure_message(
|
||||
"SessionManager must be registered as autoload in project.godot (#258)"
|
||||
).is_true()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# new_game() — game-id format and GameState update
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_new_game_returns_non_empty_string() -> void:
|
||||
var game_id := _new_game()
|
||||
assert_str(game_id).override_failure_message(
|
||||
"SessionManager.new_game() must return a non-empty game-id string"
|
||||
).is_not_empty()
|
||||
|
||||
|
||||
func test_new_game_sets_current_game_id_on_gamestate() -> void:
|
||||
var game_id := _new_game()
|
||||
assert_str(GameState.current_game_id).override_failure_message(
|
||||
"new_game() must set GameState.current_game_id"
|
||||
).is_equal(game_id)
|
||||
|
||||
|
||||
func test_new_game_id_format_has_two_dashes() -> void:
|
||||
## Format: <YYYYMMDD>-<HHMMSS>-<hex6> — two separator dashes.
|
||||
var game_id := _new_game()
|
||||
var parts := game_id.split("-")
|
||||
assert_int(parts.size()).override_failure_message(
|
||||
"game-id must have format <YYYYMMDD>-<HHMMSS>-<hex6> (3 parts separated by '-')"
|
||||
).is_equal(3)
|
||||
|
||||
|
||||
func test_new_game_id_first_part_is_8_digits() -> void:
|
||||
## First part is YYYYMMDD — 8 decimal digits.
|
||||
var game_id := _new_game()
|
||||
var parts := game_id.split("-")
|
||||
assert_int(parts[0].length()).override_failure_message(
|
||||
"game-id first part (date) must be 8 characters (YYYYMMDD)"
|
||||
).is_equal(8)
|
||||
|
||||
|
||||
func test_new_game_id_second_part_is_6_digits() -> void:
|
||||
## Second part is HHMMSS — 6 decimal digits.
|
||||
var game_id := _new_game()
|
||||
var parts := game_id.split("-")
|
||||
assert_int(parts[1].length()).override_failure_message(
|
||||
"game-id second part (time) must be 6 characters (HHMMSS)"
|
||||
).is_equal(6)
|
||||
|
||||
|
||||
func test_new_game_id_third_part_is_6_hex_chars() -> void:
|
||||
## Third part is 6 hex characters (RNG seed).
|
||||
var game_id := _new_game()
|
||||
var parts := game_id.split("-")
|
||||
assert_int(parts[2].length()).override_failure_message(
|
||||
"game-id third part (hex seed) must be 6 characters"
|
||||
).is_equal(6)
|
||||
|
||||
|
||||
func test_new_game_ids_are_unique() -> void:
|
||||
## Two rapid new_game() calls should produce different IDs
|
||||
## (different RNG seeds; same-second timestamps are valid but seeds differ).
|
||||
var id1 := _new_game()
|
||||
var id2 := _new_game()
|
||||
# Check that hex seeds differ (they almost certainly will)
|
||||
var seed1 := id1.split("-")[2]
|
||||
var seed2 := id2.split("-")[2]
|
||||
assert_str(seed1).override_failure_message(
|
||||
"Successive new_game() calls should have different RNG seeds"
|
||||
).is_not_equal(seed2)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# resume_game() — sets GameState.current_game_id
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_resume_game_sets_current_game_id() -> void:
|
||||
var test_id := "20260225-143022-a7b3f1"
|
||||
SessionManager.resume_game(test_id)
|
||||
assert_str(GameState.current_game_id).override_failure_message(
|
||||
"resume_game() must set GameState.current_game_id to the given id"
|
||||
).is_equal(test_id)
|
||||
|
||||
|
||||
func test_resume_game_overwrites_previous_game_id() -> void:
|
||||
SessionManager.resume_game("20260225-100000-aabbcc")
|
||||
SessionManager.resume_game("20260225-120000-112233")
|
||||
assert_str(GameState.current_game_id).is_equal("20260225-120000-112233")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Main menu scene
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_main_menu_scene_exists() -> void:
|
||||
assert_bool(ResourceLoader.exists("res://scenes/main_menu.tscn")).override_failure_message(
|
||||
"Main menu scene must exist at res://scenes/main_menu.tscn (#258)"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_main_menu_instantiates_without_crash() -> void:
|
||||
if not ResourceLoader.exists("res://scenes/main_menu.tscn"):
|
||||
push_warning("TestSessionManagerSprint19: main_menu.tscn not found — skip")
|
||||
return
|
||||
var scene: Node = MAIN_MENU_SCENE.instantiate()
|
||||
auto_free(scene)
|
||||
add_child(scene)
|
||||
assert_that(scene).is_not_null()
|
||||
|
||||
|
||||
func test_main_menu_has_new_game_button() -> void:
|
||||
if not ResourceLoader.exists("res://scenes/main_menu.tscn"):
|
||||
return
|
||||
var scene: Node = MAIN_MENU_SCENE.instantiate()
|
||||
auto_free(scene)
|
||||
add_child(scene)
|
||||
var btn := scene.get_node_or_null("VBox/NewGameBtn")
|
||||
assert_that(btn != null).override_failure_message(
|
||||
"Main menu must have VBox/NewGameBtn (#258)"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_main_menu_has_continue_button() -> void:
|
||||
if not ResourceLoader.exists("res://scenes/main_menu.tscn"):
|
||||
return
|
||||
var scene: Node = MAIN_MENU_SCENE.instantiate()
|
||||
auto_free(scene)
|
||||
add_child(scene)
|
||||
var btn := scene.get_node_or_null("VBox/ContinueBtn")
|
||||
assert_that(btn != null).override_failure_message(
|
||||
"Main menu must have VBox/ContinueBtn (#258)"
|
||||
).is_true()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Project main scene changed to main_menu.tscn
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
func test_project_main_scene_is_main_menu() -> void:
|
||||
## D-085: project boots to main menu, not directly to game scene.
|
||||
var scene_path: String = ProjectSettings.get_setting("application/run/main_scene", "")
|
||||
assert_str(scene_path).override_failure_message(
|
||||
"project.godot run/main_scene must be res://scenes/main_menu.tscn (#258)"
|
||||
).is_equal("res://scenes/main_menu.tscn")
|
||||
@@ -1 +0,0 @@
|
||||
uid://c7lnnr2apbyqw
|
||||
@@ -80,7 +80,7 @@ func test_protocol_decode_includes_triangle_crisis_events_field() -> void:
|
||||
# decode_snapshot() must return a "triangle_crisis_events" key (#590).
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"triangle_crisis_events": [{"triangle_id": 42}],
|
||||
}
|
||||
@@ -102,7 +102,7 @@ func test_protocol_decode_triangle_crisis_events_empty_array() -> void:
|
||||
# When no events are present, field is present and empty.
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"triangle_crisis_events": [],
|
||||
}
|
||||
@@ -117,7 +117,7 @@ func test_protocol_decode_triangle_crisis_events_absent_returns_empty() -> void:
|
||||
# When server doesn't send field (pre-#589), field defaults to empty array.
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
}
|
||||
var encoded = Messagepack.encode(raw)
|
||||
@@ -167,7 +167,7 @@ func test_protocol_decode_includes_current_ticker_field() -> void:
|
||||
# decode_snapshot() must return a "current_ticker" key (#592).
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"current_ticker": {"id": "ticker_001", "text": "Station systems nominal.", "category": "System"},
|
||||
}
|
||||
@@ -187,7 +187,7 @@ func test_protocol_decode_current_ticker_null_when_absent() -> void:
|
||||
# When server doesn't send current_ticker (player outside bar zone), field is null.
|
||||
var raw := {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
}
|
||||
var encoded = Messagepack.encode(raw)
|
||||
@@ -210,7 +210,7 @@ func test_news_ticker_hidden_when_snapshot_has_no_ticker() -> void:
|
||||
# Snapshot with no current_ticker (player outside bar zone).
|
||||
GameState.current_snapshot = {
|
||||
"tick": 1,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
}
|
||||
ticker.update_from_state()
|
||||
@@ -229,7 +229,7 @@ func test_news_ticker_visible_when_snapshot_has_ticker() -> void:
|
||||
|
||||
GameState.current_snapshot = {
|
||||
"tick": 2,
|
||||
"version": Protocol.PROTOCOL_VERSION,
|
||||
"version": 23,
|
||||
"entities": [],
|
||||
"current_ticker": {"id": "t1", "text": "Station systems nominal.", "category": "System"},
|
||||
}
|
||||
@@ -249,7 +249,7 @@ func test_news_ticker_hides_when_ticker_becomes_null() -> void:
|
||||
|
||||
# Show it first.
|
||||
GameState.current_snapshot = {
|
||||
"tick": 1, "version": Protocol.PROTOCOL_VERSION, "entities": [],
|
||||
"tick": 1, "version": 23, "entities": [],
|
||||
"current_ticker": {"id": "t1", "text": "Breaking news.", "category": "System"},
|
||||
}
|
||||
ticker.update_from_state()
|
||||
@@ -257,7 +257,7 @@ func test_news_ticker_hides_when_ticker_becomes_null() -> void:
|
||||
|
||||
# Null current_ticker — player left the bar zone.
|
||||
GameState.current_snapshot = {
|
||||
"tick": 2, "version": Protocol.PROTOCOL_VERSION, "entities": [],
|
||||
"tick": 2, "version": 23, "entities": [],
|
||||
}
|
||||
ticker.update_from_state()
|
||||
assert_bool(ticker.visible).override_failure_message(
|
||||
|
||||
@@ -132,7 +132,6 @@ func skip_test_proof_player_moves_and_v2_snapshot() -> void:
|
||||
assert_float(player.y).is_equal_approx(15.5, 0.001)
|
||||
|
||||
# v4 protocol fields present
|
||||
assert_that(snapshot.version).is_equal(Protocol.PROTOCOL_VERSION)
|
||||
assert_that(snapshot.player_facing).is_equal("North")
|
||||
assert_that(snapshot.game_time).is_not_null()
|
||||
|
||||
|
||||
@@ -1,552 +0,0 @@
|
||||
## Sprint 30 — QA acceptance tests
|
||||
##
|
||||
## Covers all 5 Sprint 30 client tickets:
|
||||
## #718 — Persist CharacterVisualDescriptor on new game start
|
||||
## #719 — Hair highlight: make swatch read-only (Option B — no compositor yet)
|
||||
## #720 — Replace DirAccess scanning with manifest JSON for export builds
|
||||
## #712 — BoneAttachment3D marker above Head bone for floating icons
|
||||
## #674 — Star map insert module (test-first: scene must exist when implemented)
|
||||
##
|
||||
## Test convention:
|
||||
## - Tests that should PASS immediately = regression guards on existing code
|
||||
## - Tests prefixed [ACCEPTANCE] = will FAIL until the ticket is implemented
|
||||
##
|
||||
## Ticket refs: #718, #719, #720, #712, #674
|
||||
class_name TestSprint30
|
||||
extends GdUnitTestSuite
|
||||
|
||||
|
||||
func before_each() -> void:
|
||||
# Reset GameState fields touched by #718 tests to avoid cross-test pollution.
|
||||
GameState.character_visual_descriptor = null
|
||||
|
||||
|
||||
func after_each() -> void:
|
||||
GameState.character_visual_descriptor = null
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# #718 — Persist CharacterVisualDescriptor
|
||||
# =============================================================================
|
||||
|
||||
func test_game_state_has_character_visual_descriptor_field() -> void:
|
||||
## GameState.character_visual_descriptor must exist and default to null.
|
||||
## Confirms the field added in game_state.gd line 103 is present.
|
||||
var gs := GameState.new()
|
||||
auto_free(gs)
|
||||
# The field is declared on the class — access it without error
|
||||
var val: Variant = gs.get("character_visual_descriptor")
|
||||
# Field should exist (not return null from missing property vs. null value)
|
||||
assert_bool(gs.has_method("apply_snapshot")).override_failure_message(
|
||||
"GameState must be a valid autoload class with apply_snapshot"
|
||||
).is_true()
|
||||
# The property itself must be gettable and null by default
|
||||
assert_bool(val == null).override_failure_message(
|
||||
"GameState.character_visual_descriptor must default to null"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_descriptor_to_dict_includes_all_required_fields() -> void:
|
||||
## CharacterVisualDescriptor.to_dict() must include all wire-format fields.
|
||||
var desc := CharacterVisualDescriptor.new()
|
||||
auto_free(desc)
|
||||
var d := desc.to_dict()
|
||||
var required_keys := [
|
||||
"body_type", "head_id", "hair_id", "hair_tint",
|
||||
"facial_hair_id", "facial_hair_tint", "eyebrow_id", "eyebrow_tint",
|
||||
"eye_color", "skin_tone", "clothing_slots", "clothing_tints",
|
||||
"accessory_slots", "accessory_tints",
|
||||
]
|
||||
for key in required_keys:
|
||||
assert_bool(d.has(key)).override_failure_message(
|
||||
"to_dict() must include field '%s'" % key
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_descriptor_to_dict_body_type_is_wire_string() -> void:
|
||||
## body_type in to_dict() must be a string (rmp_serde unit enum), not an int.
|
||||
var desc := CharacterVisualDescriptor.new()
|
||||
auto_free(desc)
|
||||
desc.body_type = CharacterVisualDescriptor.BodyType.AVERAGE_M
|
||||
var d := desc.to_dict()
|
||||
assert_str(d["body_type"]).override_failure_message(
|
||||
"to_dict() body_type must be wire string 'AverageM'"
|
||||
).is_equal("AverageM")
|
||||
|
||||
|
||||
func test_descriptor_round_trip_preserves_fields() -> void:
|
||||
## from_dict(to_dict(desc)) must preserve all scalar fields.
|
||||
var original := CharacterVisualDescriptor.new()
|
||||
auto_free(original)
|
||||
original.body_type = CharacterVisualDescriptor.BodyType.THIN_F
|
||||
original.head_id = "head_002"
|
||||
original.hair_id = "bob"
|
||||
original.hair_tint = Color(0.8, 0.4, 0.2)
|
||||
original.skin_tone = 3
|
||||
|
||||
var wire := original.to_dict()
|
||||
var restored := CharacterVisualDescriptor.from_dict(wire)
|
||||
assert_bool(restored != null).override_failure_message(
|
||||
"from_dict() must return a descriptor for valid wire data"
|
||||
).is_true()
|
||||
if restored == null:
|
||||
return
|
||||
|
||||
assert_int(int(restored.body_type)).override_failure_message(
|
||||
"body_type must survive round-trip"
|
||||
).is_equal(int(CharacterVisualDescriptor.BodyType.THIN_F))
|
||||
|
||||
assert_str(restored.head_id).override_failure_message(
|
||||
"head_id must survive round-trip"
|
||||
).is_equal("head_002")
|
||||
|
||||
assert_str(restored.hair_id).override_failure_message(
|
||||
"hair_id must survive round-trip"
|
||||
).is_equal("bob")
|
||||
|
||||
assert_int(restored.skin_tone).override_failure_message(
|
||||
"skin_tone must survive round-trip"
|
||||
).is_equal(3)
|
||||
|
||||
|
||||
func test_descriptor_from_dict_returns_null_when_missing_body_type() -> void:
|
||||
## from_dict() must return null if body_type is absent (required field).
|
||||
var d := {"head_id": "head_001"} # missing body_type
|
||||
var result := CharacterVisualDescriptor.from_dict(d)
|
||||
assert_bool(result == null).override_failure_message(
|
||||
"from_dict() must return null when body_type is missing"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_descriptor_color_encoding_is_float_array() -> void:
|
||||
## Colors must encode as [r, g, b, a] float arrays for rmp_serde compatibility.
|
||||
var desc := CharacterVisualDescriptor.new()
|
||||
auto_free(desc)
|
||||
desc.eye_color = Color(0.1, 0.2, 0.3, 1.0)
|
||||
var d := desc.to_dict()
|
||||
var encoded: Variant = d["eye_color"]
|
||||
assert_bool(encoded is Array).override_failure_message(
|
||||
"eye_color must encode as an Array [r, g, b, a]"
|
||||
).is_true()
|
||||
if not (encoded is Array):
|
||||
return
|
||||
assert_int((encoded as Array).size()).override_failure_message(
|
||||
"eye_color array must have 4 elements"
|
||||
).is_equal(4)
|
||||
assert_float((encoded as Array)[0]).override_failure_message(
|
||||
"eye_color[0] (r) must be approx 0.1"
|
||||
).is_equal_approx(0.1, 0.001)
|
||||
|
||||
|
||||
func test_apply_snapshot_restores_character_visual_descriptor() -> void:
|
||||
## #718: apply_snapshot() must restore character_visual_descriptor from
|
||||
## the "character_visual_descriptor" key in ObserverSnapshot (save/load path).
|
||||
var desc := CharacterVisualDescriptor.new()
|
||||
desc.body_type = CharacterVisualDescriptor.BodyType.MUSCULAR_F
|
||||
desc.head_id = "head_003"
|
||||
desc.hair_id = "dreads"
|
||||
desc.skin_tone = 5
|
||||
var snapshot := {
|
||||
"character_visual_descriptor": desc.to_dict(),
|
||||
}
|
||||
GameState.apply_snapshot(snapshot)
|
||||
var restored: Variant = GameState.character_visual_descriptor
|
||||
assert_bool(restored != null).override_failure_message(
|
||||
"apply_snapshot() must restore character_visual_descriptor from snapshot"
|
||||
).is_true()
|
||||
if restored != null and restored is CharacterVisualDescriptor:
|
||||
var r := restored as CharacterVisualDescriptor
|
||||
assert_int(int(r.body_type)).override_failure_message(
|
||||
"restored body_type must match"
|
||||
).is_equal(int(CharacterVisualDescriptor.BodyType.MUSCULAR_F))
|
||||
assert_str(r.head_id).override_failure_message(
|
||||
"restored head_id must match"
|
||||
).is_equal("head_003")
|
||||
assert_int(r.skin_tone).override_failure_message(
|
||||
"restored skin_tone must match"
|
||||
).is_equal(5)
|
||||
|
||||
|
||||
func test_apply_snapshot_preserves_descriptor_when_field_absent() -> void:
|
||||
## #718: If snapshot lacks "character_visual_descriptor", the existing field
|
||||
## must not be overwritten (server only sends when descriptor changes).
|
||||
var desc := CharacterVisualDescriptor.new()
|
||||
desc.hair_id = "bob"
|
||||
GameState.character_visual_descriptor = desc
|
||||
# Snapshot with no character_visual_descriptor key
|
||||
GameState.apply_snapshot({"tick": 1})
|
||||
var after: Variant = GameState.character_visual_descriptor
|
||||
assert_bool(after != null).override_failure_message(
|
||||
"apply_snapshot() must NOT clear descriptor when field is absent"
|
||||
).is_true()
|
||||
if after is CharacterVisualDescriptor:
|
||||
assert_str((after as CharacterVisualDescriptor).hair_id).override_failure_message(
|
||||
"descriptor must be unchanged after snapshot with no character_visual_descriptor key"
|
||||
).is_equal("bob")
|
||||
|
||||
|
||||
func test_protocol_encode_startup_includes_descriptor() -> void:
|
||||
## #718: Protocol.encode_startup_message() must include "character_visual_descriptor"
|
||||
## in the encoded payload when a descriptor is provided.
|
||||
var desc := CharacterVisualDescriptor.new()
|
||||
desc.body_type = CharacterVisualDescriptor.BodyType.THIN_M
|
||||
desc.hair_id = "buzzed"
|
||||
var bytes := Protocol.encode_startup_message(12345, "detective", desc)
|
||||
assert_bool(bytes.size() > 0).override_failure_message(
|
||||
"encode_startup_message() must produce non-empty bytes"
|
||||
).is_true()
|
||||
# Decode and verify the field is present (Messagepack.decode returns {status, value})
|
||||
var raw = Messagepack.decode(bytes)
|
||||
assert_bool(raw.status == null).override_failure_message(
|
||||
"encode_startup_message() output must be valid msgpack"
|
||||
).is_true()
|
||||
if raw.status != null:
|
||||
return
|
||||
var msg: Dictionary = raw.value as Dictionary
|
||||
assert_bool(msg.has("character_visual_descriptor")).override_failure_message(
|
||||
"StartupMessage must include 'character_visual_descriptor' key when descriptor is provided"
|
||||
).is_true()
|
||||
if msg.has("character_visual_descriptor"):
|
||||
assert_bool(msg["character_visual_descriptor"] is Dictionary).override_failure_message(
|
||||
"character_visual_descriptor in StartupMessage must be a Dictionary"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_protocol_encode_startup_omits_descriptor_when_null() -> void:
|
||||
## #718: encode_startup_message() must still produce valid bytes when descriptor is null.
|
||||
var bytes := Protocol.encode_startup_message(0, "detective", null)
|
||||
assert_bool(bytes.size() > 0).override_failure_message(
|
||||
"encode_startup_message() must produce valid bytes even with null descriptor"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_descriptor_has_no_hair_highlight_tint_field() -> void:
|
||||
## CharacterVisualDescriptor must NOT have a hair_highlight_tint field.
|
||||
## The highlight is always auto-derived from hair_tint (Option B of #719).
|
||||
## to_dict() must not include it in the wire format.
|
||||
var desc := CharacterVisualDescriptor.new()
|
||||
auto_free(desc)
|
||||
var d := desc.to_dict()
|
||||
assert_bool(d.has("hair_highlight_tint")).override_failure_message(
|
||||
"to_dict() must NOT include hair_highlight_tint — highlight is auto-derived"
|
||||
).is_false()
|
||||
assert_bool("hair_highlight_tint" in desc).override_failure_message(
|
||||
"CharacterVisualDescriptor must not define a hair_highlight_tint property"
|
||||
).is_false()
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# #719 — Hair highlight swatch (Option B: read-only, auto-derived)
|
||||
# =============================================================================
|
||||
|
||||
func test_derive_hair_highlight_lightens_primary() -> void:
|
||||
## _derive_hair_highlight() must return primary.lightened(0.3).
|
||||
## Tests the derivation formula in character_creation.gd:1917.
|
||||
var cc_scene_path := "res://scenes/character_creation.tscn"
|
||||
if not ResourceLoader.exists(cc_scene_path):
|
||||
push_warning("test_derive_hair_highlight_lightens_primary: scene not available in headless — skipping")
|
||||
return
|
||||
var packed := load(cc_scene_path) as PackedScene
|
||||
if packed == null:
|
||||
return
|
||||
var cc := packed.instantiate() as CharacterCreation
|
||||
if cc == null:
|
||||
push_warning("test_derive_hair_highlight_lightens_primary: failed to instantiate — skipping")
|
||||
return
|
||||
auto_free(cc)
|
||||
|
||||
# CharacterCreation._derive_hair_highlight is a private method but testable via call()
|
||||
var primary := Color(0.4, 0.3, 0.5)
|
||||
var expected := primary.lightened(0.3)
|
||||
var result: Variant = cc.call("_derive_hair_highlight", primary)
|
||||
assert_bool(result is Color).override_failure_message(
|
||||
"_derive_hair_highlight must return a Color"
|
||||
).is_true()
|
||||
if not (result is Color):
|
||||
return
|
||||
var r := result as Color
|
||||
assert_float(r.r).override_failure_message("derived highlight.r incorrect").is_equal_approx(expected.r, 0.001)
|
||||
assert_float(r.g).override_failure_message("derived highlight.g incorrect").is_equal_approx(expected.g, 0.001)
|
||||
assert_float(r.b).override_failure_message("derived highlight.b incorrect").is_equal_approx(expected.b, 0.001)
|
||||
|
||||
|
||||
func test_hair_highlight_swatch_exists_in_ui() -> void:
|
||||
## [ACCEPTANCE #719] After fix, _hair_highlight_swatch must be non-null
|
||||
## (a display node must be created in _build_hair_color_dock).
|
||||
## WILL FAIL until #719 is implemented.
|
||||
var cc_scene_path := "res://scenes/character_creation.tscn"
|
||||
if not ResourceLoader.exists(cc_scene_path):
|
||||
push_warning("test_hair_highlight_swatch_exists_in_ui: scene not available in headless — skipping")
|
||||
return
|
||||
var packed := load(cc_scene_path) as PackedScene
|
||||
if packed == null:
|
||||
return
|
||||
var cc := packed.instantiate() as CharacterCreation
|
||||
if cc == null:
|
||||
return
|
||||
auto_free(cc)
|
||||
add_child(cc)
|
||||
await get_tree().process_frame
|
||||
|
||||
# _hair_highlight_swatch must be set after _ready() builds the hair color dock
|
||||
var swatch: Variant = cc.get("_hair_highlight_swatch")
|
||||
assert_bool(swatch != null).override_failure_message(
|
||||
"[#719] _hair_highlight_swatch must not be null — a display node must be created"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_hair_highlight_swatch_is_not_interactive() -> void:
|
||||
## [ACCEPTANCE #719] The highlight swatch must be non-interactive.
|
||||
## Either mouse_filter = IGNORE, or the node is a ColorRect (not a Button with a callback).
|
||||
## WILL FAIL until #719 is implemented.
|
||||
var cc_scene_path := "res://scenes/character_creation.tscn"
|
||||
if not ResourceLoader.exists(cc_scene_path):
|
||||
push_warning("test_hair_highlight_swatch_is_not_interactive: scene not available — skipping")
|
||||
return
|
||||
var packed := load(cc_scene_path) as PackedScene
|
||||
if packed == null:
|
||||
return
|
||||
var cc := packed.instantiate() as CharacterCreation
|
||||
if cc == null:
|
||||
return
|
||||
auto_free(cc)
|
||||
add_child(cc)
|
||||
await get_tree().process_frame
|
||||
|
||||
var swatch: Variant = cc.get("_hair_highlight_swatch")
|
||||
if swatch == null:
|
||||
push_warning("test_hair_highlight_swatch_is_not_interactive: swatch not found — #719 not yet implemented")
|
||||
return
|
||||
|
||||
# If swatch is a Control node, mouse_filter must be IGNORE (2)
|
||||
if swatch is Control:
|
||||
var ctrl := swatch as Control
|
||||
assert_int(ctrl.mouse_filter).override_failure_message(
|
||||
"[#719] hair highlight swatch must have mouse_filter=IGNORE (non-interactive)"
|
||||
).is_equal(Control.MOUSE_FILTER_IGNORE)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# #720 — Manifest JSON completeness (replaces DirAccess scanning)
|
||||
# =============================================================================
|
||||
|
||||
func test_manifest_json_is_parseable() -> void:
|
||||
## manifest.json must exist and parse as a Dictionary.
|
||||
var path := "res://assets/characters/manifest.json"
|
||||
assert_bool(ResourceLoader.exists(path) or FileAccess.file_exists(path)).override_failure_message(
|
||||
"manifest.json must exist at res://assets/characters/manifest.json"
|
||||
).is_true()
|
||||
var file := FileAccess.open(path, FileAccess.READ)
|
||||
if file == null:
|
||||
push_warning("test_manifest_json_is_parseable: file not openable — skipping")
|
||||
return
|
||||
var parsed: Variant = JSON.parse_string(file.get_as_text())
|
||||
file.close()
|
||||
assert_bool(parsed is Dictionary).override_failure_message(
|
||||
"manifest.json must parse as a JSON object (Dictionary)"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_manifest_hair_includes_all_asset_dirs() -> void:
|
||||
## [ACCEPTANCE #720] manifest.json "hair" array must include every .glb in
|
||||
## assets/characters/hair/. Currently missing: balding, buzzed_female, dreads,
|
||||
## long_dreads, mohawk, ponytail_f, simple_parted, slick_back.
|
||||
## WILL FAIL until #720 populates the manifest fully.
|
||||
var path := "res://assets/characters/manifest.json"
|
||||
var file := FileAccess.open(path, FileAccess.READ)
|
||||
if file == null:
|
||||
push_warning("test_manifest_hair_includes_all_asset_dirs: manifest not readable — skipping")
|
||||
return
|
||||
var parsed: Variant = JSON.parse_string(file.get_as_text())
|
||||
file.close()
|
||||
if not (parsed is Dictionary):
|
||||
return
|
||||
var manifest := parsed as Dictionary
|
||||
var hair_list: Array = manifest.get("hair", [])
|
||||
|
||||
# All hair IDs confirmed from assets/characters/hair/*.glb scan (2026-04-04)
|
||||
var expected_hair := [
|
||||
"bald", "balding", "bob", "buns", "buzzed", "buzzed_female",
|
||||
"dreads", "long", "long_dreads", "mohawk", "ponytail", "ponytail_f",
|
||||
"simple_parted", "slick_back",
|
||||
]
|
||||
for hair_id in expected_hair:
|
||||
assert_bool(hair_list.has(hair_id)).override_failure_message(
|
||||
"[#720] manifest 'hair' must include '%s'" % hair_id
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_manifest_heads_are_populated() -> void:
|
||||
## [ACCEPTANCE #720] manifest.json "heads" must not be empty.
|
||||
## heads/templates/ contains head_001..head_004 — all must be listed.
|
||||
## WILL FAIL until #720 populates the manifest.
|
||||
var path := "res://assets/characters/manifest.json"
|
||||
var file := FileAccess.open(path, FileAccess.READ)
|
||||
if file == null:
|
||||
push_warning("test_manifest_heads_are_populated: manifest not readable — skipping")
|
||||
return
|
||||
var parsed: Variant = JSON.parse_string(file.get_as_text())
|
||||
file.close()
|
||||
if not (parsed is Dictionary):
|
||||
return
|
||||
var manifest := parsed as Dictionary
|
||||
var heads_list: Array = manifest.get("heads", [])
|
||||
|
||||
var expected_heads := ["head_001", "head_002", "head_003", "head_004"]
|
||||
assert_bool(not heads_list.is_empty()).override_failure_message(
|
||||
"[#720] manifest 'heads' must not be empty — 4 head templates exist"
|
||||
).is_true()
|
||||
for head_id in expected_heads:
|
||||
assert_bool(heads_list.has(head_id)).override_failure_message(
|
||||
"[#720] manifest 'heads' must include '%s'" % head_id
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_manifest_body_types_includes_all_11() -> void:
|
||||
## [ACCEPTANCE #720] manifest.json "body_types" must include all 11 types.
|
||||
## Currently has 6; missing: thin_m, thin_f, heavy_m, heavy_f, child.
|
||||
## WILL FAIL until #720 updates the manifest.
|
||||
var path := "res://assets/characters/manifest.json"
|
||||
var file := FileAccess.open(path, FileAccess.READ)
|
||||
if file == null:
|
||||
push_warning("test_manifest_body_types_includes_all_11: manifest not readable — skipping")
|
||||
return
|
||||
var parsed: Variant = JSON.parse_string(file.get_as_text())
|
||||
file.close()
|
||||
if not (parsed is Dictionary):
|
||||
return
|
||||
var manifest := parsed as Dictionary
|
||||
var bt_list: Array = manifest.get("body_types", [])
|
||||
|
||||
var expected_types := [
|
||||
"thin_m", "thin_f", "average_m", "average_f",
|
||||
"muscular_m", "muscular_f", "teen_m", "teen_f",
|
||||
"heavy_m", "heavy_f", "child",
|
||||
]
|
||||
for bt in expected_types:
|
||||
assert_bool(bt_list.has(bt)).override_failure_message(
|
||||
"[#720] manifest 'body_types' must include '%s'" % bt
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_manifest_clothing_includes_all_items() -> void:
|
||||
## [ACCEPTANCE #720] manifest.json "clothing" must include all items in
|
||||
## assets/characters/clothing/. Currently missing: boots_work, coveralls_basic,
|
||||
## jacket_utility, pants_cargo, shirt_henley.
|
||||
## WILL FAIL until #720 populates the manifest.
|
||||
var path := "res://assets/characters/manifest.json"
|
||||
var file := FileAccess.open(path, FileAccess.READ)
|
||||
if file == null:
|
||||
push_warning("test_manifest_clothing_includes_all_items: manifest not readable — skipping")
|
||||
return
|
||||
var parsed: Variant = JSON.parse_string(file.get_as_text())
|
||||
file.close()
|
||||
if not (parsed is Dictionary):
|
||||
return
|
||||
var manifest := parsed as Dictionary
|
||||
var clothing_data: Variant = manifest.get("clothing", {})
|
||||
var clothing_keys: Array = []
|
||||
if clothing_data is Dictionary:
|
||||
clothing_keys = (clothing_data as Dictionary).keys()
|
||||
|
||||
# All clothing item IDs confirmed from assets/characters/clothing/ scan (2026-04-04)
|
||||
var expected_items := [
|
||||
"boots_work", "coveralls_basic", "jacket_utility", "pants_cargo",
|
||||
"peasant_pants", "peasant_shoes", "peasant_tunic", "shirt_henley",
|
||||
]
|
||||
for item_id in expected_items:
|
||||
assert_bool(clothing_keys.has(item_id)).override_failure_message(
|
||||
"[#720] manifest 'clothing' must include '%s'" % item_id
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_manifest_eyebrows_are_populated() -> void:
|
||||
## [ACCEPTANCE #720] manifest.json "eyebrows" must list all eyebrow styles.
|
||||
## assets/characters/eyebrows/ has: female, regular, teen, thick.
|
||||
## WILL FAIL until #720 populates the manifest.
|
||||
var path := "res://assets/characters/manifest.json"
|
||||
var file := FileAccess.open(path, FileAccess.READ)
|
||||
if file == null:
|
||||
push_warning("test_manifest_eyebrows_are_populated: manifest not readable — skipping")
|
||||
return
|
||||
var parsed: Variant = JSON.parse_string(file.get_as_text())
|
||||
file.close()
|
||||
if not (parsed is Dictionary):
|
||||
return
|
||||
var manifest := parsed as Dictionary
|
||||
var eb_list: Array = manifest.get("eyebrows", [])
|
||||
|
||||
var expected_eyebrows := ["female", "regular", "teen", "thick"]
|
||||
assert_bool(not eb_list.is_empty()).override_failure_message(
|
||||
"[#720] manifest 'eyebrows' must not be empty"
|
||||
).is_true()
|
||||
for eb_id in expected_eyebrows:
|
||||
assert_bool(eb_list.has(eb_id)).override_failure_message(
|
||||
"[#720] manifest 'eyebrows' must include '%s'" % eb_id
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_dir_access_scan_functions_removed() -> void:
|
||||
## [ACCEPTANCE #720] After fix, _scan_subdirs and _scan_asset_ids must be
|
||||
## removed from CharacterCreation. These functions fail in exported PCK builds.
|
||||
## WILL FAIL until #720 removes the DirAccess fallbacks.
|
||||
var cc_scene_path := "res://scenes/character_creation.tscn"
|
||||
if not ResourceLoader.exists(cc_scene_path):
|
||||
push_warning("test_dir_access_scan_functions_removed: scene not available — skipping")
|
||||
return
|
||||
var packed := load(cc_scene_path) as PackedScene
|
||||
if packed == null:
|
||||
return
|
||||
var cc := packed.instantiate() as CharacterCreation
|
||||
if cc == null:
|
||||
return
|
||||
auto_free(cc)
|
||||
|
||||
assert_bool(cc.has_method("_scan_subdirs")).override_failure_message(
|
||||
"[#720] _scan_subdirs must be removed — use manifest JSON instead"
|
||||
).is_false()
|
||||
assert_bool(cc.has_method("_scan_asset_ids")).override_failure_message(
|
||||
"[#720] _scan_asset_ids must be removed — use manifest JSON instead"
|
||||
).is_false()
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# #712 — BoneAttachment3D overhead anchor in CharacterVisual
|
||||
# =============================================================================
|
||||
|
||||
func test_character_visual_has_get_overhead_anchor() -> void:
|
||||
## CharacterVisual must expose get_overhead_anchor() as part of its public API.
|
||||
## This is a static assertion — no 3D assets required.
|
||||
var cv := CharacterVisual.new()
|
||||
auto_free(cv)
|
||||
assert_bool(cv.has_method("get_overhead_anchor")).override_failure_message(
|
||||
"CharacterVisual must have get_overhead_anchor() method (#712)"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_overhead_anchor_is_null_before_load() -> void:
|
||||
## get_overhead_anchor() must return null before load_descriptor() is called.
|
||||
## The anchor is created during skeleton load, not at construction.
|
||||
var cv := CharacterVisual.new()
|
||||
auto_free(cv)
|
||||
var anchor: Variant = cv.get_overhead_anchor()
|
||||
assert_bool(anchor == null).override_failure_message(
|
||||
"get_overhead_anchor() must be null before load_descriptor() is called"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_overhead_anchor_offset_constant() -> void:
|
||||
## [ACCEPTANCE #712] If CharacterVisual exposes the overhead anchor offset
|
||||
## as a constant or via get_overhead_anchor(), the offset must be Vector3(0, 0.3, 0).
|
||||
## Verified via code inspection: _overhead_anchor.position = Vector3(0, 0.3, 0).
|
||||
## This test loads a scene and verifies if assets are present.
|
||||
var cv := CharacterVisual.new()
|
||||
auto_free(cv)
|
||||
add_child(cv)
|
||||
|
||||
# Without GLB assets available in headless, skeleton load is a no-op.
|
||||
# Check that _overhead_attachment is also null before load (belt-and-suspenders).
|
||||
var attachment: Variant = cv.get("_overhead_attachment")
|
||||
assert_bool(attachment == null).override_failure_message(
|
||||
"_overhead_attachment must be null before skeleton is loaded"
|
||||
).is_true()
|
||||
@@ -1,292 +0,0 @@
|
||||
## Sprint 16 #540: Sprite integration tests.
|
||||
## Tests z-sorting with real sprites, 24x32 D-044 footprint within D-066 64x64
|
||||
## bounding box, sprite asset existence from #541, and fog shader independence.
|
||||
## Spec refs: D-019, D-043, D-044, D-049, D-066, #540, #541.
|
||||
class_name TestSpriteIntegration
|
||||
extends GdUnitTestSuite
|
||||
|
||||
var EntityRendererScript = load("res://scripts/rendering/entity_renderer.gd")
|
||||
|
||||
|
||||
func before_test() -> void:
|
||||
GameState.player_entity_id = 1
|
||||
GameState.player_position = Vector2.ZERO
|
||||
GameState.visible_entities = []
|
||||
|
||||
|
||||
# -- Helpers -------------------------------------------------------------------
|
||||
|
||||
func _make_entity_renderer() -> Node2D:
|
||||
var renderer = Node2D.new()
|
||||
renderer.set_script(EntityRendererScript)
|
||||
add_child(renderer)
|
||||
return renderer
|
||||
|
||||
|
||||
# -- Footprint constants: D-044 spec (S16-S01, S16-S02) -----------------------
|
||||
|
||||
func test_entity_footprint_matches_d044_spec() -> void:
|
||||
# S16-S01: D-044 specifies 24x32 entity footprint within 32x32 visual tile.
|
||||
# (64x64 source sprite scaled to 32px runtime at 2x retina per D-066).
|
||||
assert_that(EntityRenderer.ENTITY_WIDTH).override_failure_message(
|
||||
"D-044: ENTITY_WIDTH must be 24px"
|
||||
).is_equal(24)
|
||||
assert_that(EntityRenderer.ENTITY_HEIGHT).override_failure_message(
|
||||
"D-044: ENTITY_HEIGHT must be 32px"
|
||||
).is_equal(32)
|
||||
|
||||
|
||||
func test_entity_footprint_within_d066_2x2_sim_tile_bounding_box() -> void:
|
||||
# S16-S02: D-066 requires entity sprite footprint contained within 2x2 sim tile
|
||||
# bounding box. At 32px/tile → 64x64px max. Entity must fit to keep interaction
|
||||
# range (2 sim tiles) accurate with the tilted perspective.
|
||||
var tile_2x: int = Constants.TILE_SIZE * 2
|
||||
assert_that(EntityRenderer.ENTITY_WIDTH <= tile_2x).override_failure_message(
|
||||
"D-066: ENTITY_WIDTH %d must fit within 2x tile width %dpx" % [
|
||||
EntityRenderer.ENTITY_WIDTH, tile_2x]
|
||||
).is_true()
|
||||
assert_that(EntityRenderer.ENTITY_HEIGHT <= tile_2x).override_failure_message(
|
||||
"D-066: ENTITY_HEIGHT %d must fit within 2x tile height %dpx" % [
|
||||
EntityRenderer.ENTITY_HEIGHT, tile_2x]
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_entity_width_fits_within_single_tile() -> void:
|
||||
# S16-S03: Entity width (24) < TILE_SIZE (32) → centered within tile.
|
||||
# Ensures horizontal centering offset is positive and entity doesn't overflow.
|
||||
assert_that(EntityRenderer.ENTITY_WIDTH < Constants.TILE_SIZE).override_failure_message(
|
||||
"Entity width must be less than TILE_SIZE for centered layout"
|
||||
).is_true()
|
||||
assert_that(EntityRenderer.ENTITY_OFFSET_X >= 0.0).override_failure_message(
|
||||
"ENTITY_OFFSET_X must be non-negative for horizontal centering"
|
||||
).is_true()
|
||||
|
||||
|
||||
# -- Pixel position (S16-S04) -------------------------------------------------
|
||||
|
||||
func test_entity_pixel_position_at_tile_3_7() -> void:
|
||||
# S16-S04: Entity at tile (3.0, 7.0) → pixel position must be
|
||||
# (3 * TILE_SIZE + ENTITY_OFFSET_X, 7 * TILE_SIZE + ENTITY_OFFSET_Y).
|
||||
var renderer := _make_entity_renderer()
|
||||
var entity := [{"entity_id": 10, "x": 3.0, "y": 7.0, "z": 0,
|
||||
"kind": {"variant": "Npc", "data": null}}]
|
||||
renderer.update_entities(entity)
|
||||
var node = renderer.entity_nodes[10]
|
||||
var expected_x := 3.0 * Constants.TILE_SIZE + EntityRenderer.ENTITY_OFFSET_X
|
||||
var expected_y := 7.0 * Constants.TILE_SIZE + EntityRenderer.ENTITY_OFFSET_Y
|
||||
assert_that(node.position.x).override_failure_message(
|
||||
"Entity x must be tile_x * TILE_SIZE + ENTITY_OFFSET_X"
|
||||
).is_equal_approx(expected_x, 0.1)
|
||||
assert_that(node.position.y).override_failure_message(
|
||||
"Entity y must be tile_y * TILE_SIZE + ENTITY_OFFSET_Y"
|
||||
).is_equal_approx(expected_y, 0.1)
|
||||
renderer.queue_free()
|
||||
|
||||
|
||||
# -- Z-sort ordering: D-049 y-based (S16-S05, S16-S06) -----------------------
|
||||
|
||||
func test_z_sort_south_entity_has_higher_pixel_y() -> void:
|
||||
# S16-S05: D-049 y-sort — entity at y=8 (south) must have higher pixel.y
|
||||
# than entity at y=4 (north). Godot y-sort renders higher-y on top.
|
||||
# With tilted sprites, south-facing entity must visually overlap northern.
|
||||
var renderer := _make_entity_renderer()
|
||||
var entities := [
|
||||
{"entity_id": 20, "x": 5.0, "y": 4.0, "z": 0, "kind": {"variant": "Npc", "data": null}},
|
||||
{"entity_id": 21, "x": 5.0, "y": 8.0, "z": 0, "kind": {"variant": "Npc", "data": null}},
|
||||
]
|
||||
renderer.update_entities(entities)
|
||||
var north_node = renderer.entity_nodes[20]
|
||||
var south_node = renderer.entity_nodes[21]
|
||||
assert_that(south_node.position.y > north_node.position.y).override_failure_message(
|
||||
"Entity at y=8 must have higher pixel.y than entity at y=4 for y-sort"
|
||||
).is_true()
|
||||
renderer.queue_free()
|
||||
|
||||
|
||||
func test_z_sort_y_position_difference_equals_tile_size() -> void:
|
||||
# S16-S06: Two entities one tile apart in y → pixel y difference = TILE_SIZE.
|
||||
# Verifies position calculation is consistent for adjacent tiles.
|
||||
var renderer := _make_entity_renderer()
|
||||
var entities := [
|
||||
{"entity_id": 30, "x": 5.0, "y": 3.0, "z": 0, "kind": {"variant": "Npc", "data": null}},
|
||||
{"entity_id": 31, "x": 5.0, "y": 4.0, "z": 0, "kind": {"variant": "Npc", "data": null}},
|
||||
]
|
||||
renderer.update_entities(entities)
|
||||
var node3 = renderer.entity_nodes[30]
|
||||
var node4 = renderer.entity_nodes[31]
|
||||
var delta_y := node4.position.y - node3.position.y
|
||||
assert_that(delta_y).override_failure_message(
|
||||
"Adjacent tiles must differ by exactly TILE_SIZE (%dpx) in y" % Constants.TILE_SIZE
|
||||
).is_equal_approx(float(Constants.TILE_SIZE), 0.1)
|
||||
renderer.queue_free()
|
||||
|
||||
|
||||
func test_z_sort_same_y_different_x_no_y_difference() -> void:
|
||||
# S16-S07: Two entities at same y but different x → same pixel.y.
|
||||
# Horizontal position must not affect y-sort order.
|
||||
var renderer := _make_entity_renderer()
|
||||
var entities := [
|
||||
{"entity_id": 40, "x": 2.0, "y": 5.0, "z": 0, "kind": {"variant": "Npc", "data": null}},
|
||||
{"entity_id": 41, "x": 8.0, "y": 5.0, "z": 0, "kind": {"variant": "Npc", "data": null}},
|
||||
]
|
||||
renderer.update_entities(entities)
|
||||
var left_node = renderer.entity_nodes[40]
|
||||
var right_node = renderer.entity_nodes[41]
|
||||
assert_that(left_node.position.y).override_failure_message(
|
||||
"Entities at same y-tile must have same pixel.y regardless of x"
|
||||
).is_equal_approx(right_node.position.y, 0.1)
|
||||
renderer.queue_free()
|
||||
|
||||
|
||||
# -- Sprite assets from #541 (S16-S08, S16-S09) --------------------------------
|
||||
|
||||
func test_npc_sprite_assets_exist_for_all_cardinal_directions() -> void:
|
||||
# S16-S08: #541 delivers 64px NPC sprites for all four cardinal directions.
|
||||
# entity_renderer.gd must be able to load these paths.
|
||||
for direction in ["north", "east", "south", "west"]:
|
||||
var path := "res://assets/sprites/npc_generic_%s_64.png" % direction
|
||||
assert_that(ResourceLoader.exists(path)).override_failure_message(
|
||||
"NPC sprite missing: %s" % path
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_wall_sprite_assets_exist_for_all_cardinal_directions() -> void:
|
||||
# S16-S09: #541 delivers 64px wall sprites for all four cardinal directions.
|
||||
for direction in ["north", "east", "south", "west"]:
|
||||
var path := "res://assets/sprites/wall_structural_%s_64.png" % direction
|
||||
assert_that(ResourceLoader.exists(path)).override_failure_message(
|
||||
"Wall sprite missing: %s" % path
|
||||
).is_true()
|
||||
|
||||
|
||||
# -- Fog shader independence: D-019 (S16-S10, S16-S11) -----------------------
|
||||
|
||||
func test_fog_shader_script_and_gdshader_load_correctly() -> void:
|
||||
# S16-S10: fog_shader.gd and fog.gdshader must remain intact after sprite
|
||||
# changes. D-019: "fog vision cone math remains pure 2D" — unaffected by
|
||||
# the art-direction tilt baked into sprites.
|
||||
assert_that(ResourceLoader.exists("res://scripts/rendering/fog_shader.gd")).override_failure_message(
|
||||
"fog_shader.gd must load correctly — must not be affected by sprite changes"
|
||||
).is_true()
|
||||
assert_that(ResourceLoader.exists("res://shaders/fog.gdshader")).override_failure_message(
|
||||
"fog.gdshader must exist — fog is screen-space and sprite-independent"
|
||||
).is_true()
|
||||
|
||||
|
||||
func test_fog_update_runs_independently_of_entity_renderer_state() -> void:
|
||||
# S16-S11: FogState.update_from_state() must succeed with no entity renderer
|
||||
# active. D-019: fog driven by LOS mask (visible_positions), not sprites.
|
||||
var fog = get_node_or_null("/root/FogState")
|
||||
if fog == null:
|
||||
push_warning("TestSpriteIntegration: FogState not available — fog independence test skipped")
|
||||
return
|
||||
# Provide visibility data but no entity renderer context
|
||||
GameState.visible_positions = {Vector2i(5, 5): true, Vector2i(6, 5): true}
|
||||
GameState.visibility_sectors = {
|
||||
Vector2i(5, 5): "Forward",
|
||||
Vector2i(6, 5): "Peripheral",
|
||||
}
|
||||
if fog.has_method("update_from_state"):
|
||||
fog.update_from_state()
|
||||
assert_that(fog.visibility_texture).override_failure_message(
|
||||
"FogState visibility_texture must be populated independently of sprite state"
|
||||
).is_not_null()
|
||||
GameState.visible_positions.clear()
|
||||
GameState.visibility_sectors.clear()
|
||||
|
||||
|
||||
# -- Direction mapping: _octant_to_direction (S16-S12 through S16-S21) --------
|
||||
|
||||
func test_octant_north_maps_to_north() -> void:
|
||||
# S16-S12: "North" → "north"
|
||||
assert_that(EntityRenderer._octant_to_direction("North")).is_equal("north")
|
||||
|
||||
func test_octant_northwest_maps_to_north() -> void:
|
||||
# S16-S13: "Northwest" → "north" (grouped with North per mapping spec)
|
||||
assert_that(EntityRenderer._octant_to_direction("Northwest")).is_equal("north")
|
||||
|
||||
func test_octant_northeast_maps_to_east() -> void:
|
||||
# S16-S14: "Northeast" → "east"
|
||||
assert_that(EntityRenderer._octant_to_direction("Northeast")).is_equal("east")
|
||||
|
||||
func test_octant_east_maps_to_east() -> void:
|
||||
# S16-S15: "East" → "east"
|
||||
assert_that(EntityRenderer._octant_to_direction("East")).is_equal("east")
|
||||
|
||||
func test_octant_southeast_maps_to_south() -> void:
|
||||
# S16-S16: "Southeast" → "south"
|
||||
assert_that(EntityRenderer._octant_to_direction("Southeast")).is_equal("south")
|
||||
|
||||
func test_octant_south_maps_to_south() -> void:
|
||||
# S16-S17: "South" → "south"
|
||||
assert_that(EntityRenderer._octant_to_direction("South")).is_equal("south")
|
||||
|
||||
func test_octant_southwest_maps_to_west() -> void:
|
||||
# S16-S18: "Southwest" → "west"
|
||||
assert_that(EntityRenderer._octant_to_direction("Southwest")).is_equal("west")
|
||||
|
||||
func test_octant_west_maps_to_west() -> void:
|
||||
# S16-S19: "West" → "west"
|
||||
assert_that(EntityRenderer._octant_to_direction("West")).is_equal("west")
|
||||
|
||||
func test_octant_unknown_string_falls_back_to_south() -> void:
|
||||
# S16-S20: Unknown string → "south" fallback (safe default — viewer-facing per D-019)
|
||||
assert_that(EntityRenderer._octant_to_direction("Unknown")).is_equal("south")
|
||||
assert_that(EntityRenderer._octant_to_direction("invalid")).is_equal("south")
|
||||
|
||||
func test_octant_empty_string_falls_back_to_south() -> void:
|
||||
# S16-S21: Empty string → "south" fallback
|
||||
assert_that(EntityRenderer._octant_to_direction("")).is_equal("south")
|
||||
|
||||
|
||||
# -- Direction mapping: _entity_direction (S16-S22 through S16-S25) ----------
|
||||
|
||||
func test_entity_direction_npc_always_south() -> void:
|
||||
# S16-S22: NPC entity → always "south" regardless of any data field.
|
||||
# NPCs have no facing in v1 entity format; south is viewer-facing (D-019 angle).
|
||||
var renderer := _make_entity_renderer()
|
||||
GameState.player_entity_id = 1
|
||||
# entity_id 99 is not the player
|
||||
var dir := renderer._entity_direction(99, {"entity_id": 99,
|
||||
"kind": {"variant": "Npc", "data": null}})
|
||||
assert_that(dir).override_failure_message(
|
||||
"NPC entity must always return 'south'"
|
||||
).is_equal("south")
|
||||
renderer.queue_free()
|
||||
|
||||
func test_entity_direction_player_uses_player_facing() -> void:
|
||||
# S16-S23: Player entity → uses GameState.player_facing via _octant_to_direction.
|
||||
var renderer := _make_entity_renderer()
|
||||
GameState.player_entity_id = 1
|
||||
GameState.player_facing = "North"
|
||||
var dir := renderer._entity_direction(1, {"entity_id": 1,
|
||||
"kind": {"variant": "Player", "data": null}})
|
||||
assert_that(dir).override_failure_message(
|
||||
"Player entity with player_facing='North' must return 'north'"
|
||||
).is_equal("north")
|
||||
renderer.queue_free()
|
||||
|
||||
func test_entity_direction_player_facing_east() -> void:
|
||||
# S16-S24: Player facing "East" → "east"
|
||||
var renderer := _make_entity_renderer()
|
||||
GameState.player_entity_id = 1
|
||||
GameState.player_facing = "East"
|
||||
var dir := renderer._entity_direction(1, {"entity_id": 1,
|
||||
"kind": {"variant": "Player", "data": null}})
|
||||
assert_that(dir).override_failure_message(
|
||||
"Player entity with player_facing='East' must return 'east'"
|
||||
).is_equal("east")
|
||||
renderer.queue_free()
|
||||
|
||||
func test_entity_direction_player_facing_diagonal_uses_nearest_cardinal() -> void:
|
||||
# S16-S25: Player facing "Northwest" → "north" (nearest cardinal mapping).
|
||||
# Diagonal octants map to one of the four cardinal sprite sets.
|
||||
var renderer := _make_entity_renderer()
|
||||
GameState.player_entity_id = 1
|
||||
GameState.player_facing = "Northwest"
|
||||
var dir := renderer._entity_direction(1, {"entity_id": 1,
|
||||
"kind": {"variant": "Player", "data": null}})
|
||||
assert_that(dir).override_failure_message(
|
||||
"Player entity with player_facing='Northwest' must return 'north'"
|
||||
).is_equal("north")
|
||||
renderer.queue_free()
|
||||
@@ -1 +0,0 @@
|
||||
uid://b8snipm64g2b2
|
||||
@@ -291,7 +291,7 @@ func test_hud_time_row_updates_after_process() -> void:
|
||||
add_child(instance)
|
||||
|
||||
GameState.apply_snapshot({
|
||||
"tick": 1, "version": Protocol.PROTOCOL_VERSION, "entities": [],
|
||||
"tick": 1, "version": 23, "entities": [],
|
||||
"game_time": {"day": 0, "time_of_day": 720, "day_phase": "Afternoon", "tick_rate": "Full"},
|
||||
})
|
||||
instance._process(0.016)
|
||||
|
||||
@@ -625,8 +625,11 @@ func _format_entry(entry: Dictionary, alpha: float) -> String:
|
||||
|
||||
|
||||
## Escape BBCode bracket characters in server-sourced text (Hoshe #2).
|
||||
## #866 fix: only escape '[' — unmatched ']' renders as a literal in RichTextLabel.
|
||||
## Chaining .replace("]", "[rb]") after .replace("[", "[lb]") corrupted the [lb] escape
|
||||
## itself: "[lb]" → "[lb[rb]", making the BBCode injection guard non-functional.
|
||||
static func _escape_bbcode(text: String) -> String:
|
||||
return text.replace("[", "[lb]").replace("]", "[rb]")
|
||||
return text.replace("[", "[lb]")
|
||||
|
||||
|
||||
## Assign a palette color to an NPC entity ID on first encounter (#573).
|
||||
|
||||
@@ -1611,7 +1611,7 @@ func _take_screenshot(suffix: String = "") -> void:
|
||||
# Take screenshot for current cardinal, then advance. Single array for
|
||||
# both facing and filename label — previously two arrays with different
|
||||
# orderings produced swapped labels at indices 1 and 3.
|
||||
var dir_name := CARDINAL_DIRS[_screenshot_cardinal_idx]
|
||||
var dir_name: String = CARDINAL_DIRS[_screenshot_cardinal_idx]
|
||||
_char_visual.set_facing(dir_name)
|
||||
suffix = dir_name
|
||||
|
||||
|
||||
@@ -39,13 +39,9 @@ func _build_ui() -> void:
|
||||
_label.mouse_filter = Control.MOUSE_FILTER_IGNORE
|
||||
add_child(_label)
|
||||
|
||||
# client_ver and proto_ver are independent — project.yaml version is the client release,
|
||||
# Protocol.PROTOCOL_VERSION is the wire protocol. Mismatches between builds are visible
|
||||
# only to the observer reading the loading-screen label; a future ticket will surface them.
|
||||
var client_ver := _read_client_version()
|
||||
var proto_ver: int = Protocol.PROTOCOL_VERSION
|
||||
_version_label = Label.new()
|
||||
_version_label.text = "v%s · protocol %d" % [client_ver, proto_ver]
|
||||
_version_label.text = "v%s" % [client_ver]
|
||||
_version_label.add_theme_font_size_override("font_size", VERSION_FONT_SIZE)
|
||||
_version_label.add_theme_color_override("font_color", VERSION_COLOR)
|
||||
_version_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
|
||||
|
||||
+15
-4
@@ -44,9 +44,10 @@ How narrative, NPCs, and world content are created: content tiers, NPC generatio
|
||||
- **Dissent:** None
|
||||
- **Amendment (2026-03-05, Where's the Fun? Workshop):** The 30/50/20 population split rationale survives but implementation context changes. [D-122](#d-122-all-npcs-generated--no-named-hand-authored-characters) (all NPCs generated) means no NPC is hand-authored. The "entangled 20%" are generated NPCs whose triangles happen to be flagged for intrigue content. For the tycoon v0.2 bookmark ([D-117](scope.md#d-117-tycoon-is-the-v02-bookmark--zero-investigation-content)), the split applies to economic, social, and mundane triangles rather than investigation-intrigue triangles. The specific ratios will be revisited after the generator spike ([D-119](scope.md#d-119-generator-spike-confirmed-for-sprint-25--critical-path)) proves what population density the generator can sustain.
|
||||
|
||||
### D-032: Separate monologue pools per character [SUPERSEDED]
|
||||
### D-032: Separate monologue pools per character [SUPERSEDED — deferred to Phase 6]
|
||||
- **Date:** 2026-02-11
|
||||
- **Superseded by:** [D-117](scope.md#d-117-tycoon-is-the-v02-bookmark--zero-investigation-content) (single tycoon character in v0.2 eliminates the smuggler/detective hard partition). The principle of character-specific monologue pools survives — the tycoon has their own monologue pool. The hard partition between smuggler and detective does not apply when there is only one playable character. Per [D-127](#d-127-player-choices-are-the-content--rimworld-model-job-as-rails), the player's monologue reflects their character background. The partition design is preserved as a pattern for when multiple playable characters are reintroduced.
|
||||
- **Superseded by:** Development cascade (CLAUDE.md) — character/NPC monologue content is Phase 6 detail-coloring, below the current Phase 1 (wiki content). The smuggler/detective archetype enum and its hard-partitioned monologue pools were pre-cascade scaffolding and have been fully stripped from the server codebase (Sprint 37, #878, PR #137). The original D-117 supersession framing (single tycoon character in v0.2) is itself obsolete now that v0.2 is dropped (CLAUDE.md: "v0.2 target is dropped"). The partition *design pattern* is preserved in this record for when culture-driven / generator-produced monologue is reintroduced in Phase 6, but no corresponding code or content exists today.
|
||||
- **Amendment (2026-04-22, Sprint 37, PR #137):** Monologue pool selection is now unkeyed by archetype until a Phase 6 character system exists. `MonologueState.character` field and `CharacterArchetype` enum deleted from `server/src/bridge/types.rs`, `server/src/simulation/monologue.rs`, observer relabeling logic, and `server/content/modules/tier1/smuggling_ring_v0_1.yaml`. Uniform single-pool behavior is the intended end state pre-Phase-6 — not scaffolding deferred in place with a stub, but retired pending the real character system. Lead override recorded in `docs/architecture/sprint-37-878-audit.md` (2026-04-21 override section). Reintroduction gate: a confirmed Phase 6 character-model design is a prerequisite before this decision is revived.
|
||||
- **Decision:** Internal monologue content is hard-partitioned by playable character. The smuggler and detective have completely separate monologue pools — no shared lines. The `character` tag on monologue lines is a hard partition, not a filter. File structure uses separate files per character per location (e.g., `monologue-smuggler.yaml`, `monologue-detective.yaml`).
|
||||
- **Rationale:** Shared monologue would dilute character voice and undermine the dual-lens experience. Each character's internal voice must be independently coherent. Same trigger, different pool — this is how mirror moments work without either pool knowing about the other.
|
||||
- **Cross-reference:** Dialogue lines remain character-agnostic — the access tier system (D-028 Layer 1) handles per-character filtering without separate pools.
|
||||
@@ -80,7 +81,7 @@ How narrative, NPCs, and world content are created: content tiers, NPC generatio
|
||||
- `mood` (list\<enum\>): 8 moods for v0.1 — D-028 Layer 4 weighted selection
|
||||
- `tags` (list\<string\>): freeform escape hatch for author intent
|
||||
- **Monologue-specific additions:**
|
||||
- `character` (enum): `smuggler`, `detective` — hard partition per D-032 **[Obsolete post-D-117: smuggler/detective eliminated. v0.2 uses culture-driven voice per D-121; this enum is unused.]**
|
||||
- `character` (enum): historically `smuggler`, `detective` — removed. Per [D-032 SUPERSEDED] and the development cascade (CLAUDE.md), character-partitioned monologue is Phase 6 and has been stripped from the codebase (Sprint 37, #878). Field is unused; do not reintroduce without a confirmed Phase 6 design.
|
||||
- `trigger` (enum): 9 trigger types (enter_location, observe_npc, hear_sound, observe_anomaly, post_conversation, discover_evidence, witness_interaction, time_idle, return_visit)
|
||||
- `prerequisite` (map or null): knowledge state gate
|
||||
- **Authoring-only tags (not consumed by engine):** `dual_lens` (map, per-character notes), `notes` (string)
|
||||
@@ -92,6 +93,7 @@ How narrative, NPCs, and world content are created: content tiers, NPC generatio
|
||||
- **Amendment (Sprint 14):** Mood vocabulary renamed to match voice guide (monologue-voice-guide.md). Old → new: `fond`→`warm`, `comfortable`→`content`, `worried`→`anxious`, `concerned`→`frustrated`. Dropped: `analytical` (merged into `focused`), `conflicted` (modeled as `suspicious`+`warm` collision). Added: `hostile`. Final 8 moods: `anxious`, `frustrated`, `content`, `suspicious`, `warm`, `hostile`, `relieved`, `focused`. Neutral = untagged.
|
||||
- **Amendment (Sprint 24):** `triangle_activated` added as 15th situation (fires post-TriangleActivated when player observes anchor NPCs). Two freeform tags registered as conventions: `triangle-signal` (line is part of the triangle activation sequence) and `tell-observation` (line observes a behavioral tell without naming its cause). `npc_in_los` prerequisite added for LOS-gated monologue lines. Schema updated to match.
|
||||
- **Amendment (Sprint 15):** Line ID namespace changed from location-scoped to NPC-scoped. Old scheme: `{location_slug}_{d|m}_{###}` (e.g., `the-terminal_d_039`) — all NPCs at a location share one ID sequence, requiring cross-file coordination and causing collisions at scale. New scheme: `{npc-slug}_{d|m}_{###}` for dialogue, `{npc-slug}_m_{s|d}_{###}` for monologue (e.g., `kael-davan_d_001`, `dock-worker_d_001`). Each NPC's IDs are independent — no cross-file coordination needed. Auto-generated NPCs use their generated slug. Schema regex patterns unchanged (prefix is still `^[a-z][a-z0-9-]*`), only the `description` field and convention documentation update. Migration: mechanical rename of all existing line IDs across ~20 dialogue files and monologue pools.
|
||||
- **Amendment (2026-04-22, Sprint 37, PR #137):** The `character` monologue-specific tag (historically `smuggler | detective`) is retired pending a Phase 6 character-model design — not deferred in place with a stub enum. Per the development cascade (CLAUDE.md), character-partitioned monologue is Phase 6 detail-coloring; the codebase has been stripped of the `CharacterArchetype` enum and the `MonologueState.character` field that keyed pool selection (#878). Pool selection is now archetype-independent. Authoring files that carry historical `character:` tags are content artifacts and will be re-evaluated when the Phase 6 character system is designed; engine consumption of the field is gone. Reintroduction gate: a confirmed Phase 6 character-model design is a prerequisite. See `docs/architecture/sprint-37-878-audit.md` (lead override section) for the cascade rationale.
|
||||
|
||||
### D-036: Sova Transit District / Van Maanen's Star as v0.1 setting
|
||||
- **Date:** 2026-02-11
|
||||
@@ -605,6 +607,15 @@ How narrative, NPCs, and world content are created: content tiers, NPC generatio
|
||||
- **Raised by:** Miri (Sprint 31, ticket #773)
|
||||
- **Dissent:** None.
|
||||
|
||||
### D-193: Lattice Commission — canonical long-form of the Commission
|
||||
- **Date:** 2026-04-21
|
||||
- **Decision:** The Concord Assembly's regulatory authority is formally named **"the Lattice Commission"**. In-prose short form remains "the Commission" (unambiguous in context). Drift forms that appeared in earlier copy reviews — "Concord Commission" and "Assembly Commission" — are **non-canonical** and must be corrected wherever they appear. The long-form is required for institutional POI signage, tractus fee legal text, wiki page headers, and any formal/legal context.
|
||||
- **Rationale:** The Commission's regulated domain — implant hardware, medical-grade replacements, pharmaceutical production, and safety-critical manufactured goods that feed the Lattice — is what authorizes and scopes its jurisdiction. Naming it after the regulated domain (rather than the parent Assembly) mirrors how real-world regulatory bodies are often named by what they regulate (FDA, FAA, NRC) rather than by their chartering body. It also disambiguates from "Concord" which otherwise appears in the Concord Assembly itself, the Concord's member systems, etc. The Commission has no authority in Compact member systems — its identity is Lattice-scoped, not Concord-scoped.
|
||||
- **Affects:** Wiki content (all `wiki/factions/`, `wiki/technology/`, `wiki/corporations/` pages that reference the Commission), marker POI naming (e.g. `"Lattice Commission — Sirius Office"`), formal legal text in tractus fee documentation, institutional signage, institution templates in `wiki/_templates/`, dialogue pools, copy guides.
|
||||
- **Resolves:** [Q-095](questions-content.md#q-095-commission-formal-name--authoritative-designation)
|
||||
- **Raised by:** Copy review (Sprint 35, PR #127); resolved by Jeroen on 2026-04-21
|
||||
- **Dissent:** None.
|
||||
|
||||
---
|
||||
|
||||
*46 decisions. Last updated: 2026-04-05 (D-168 Iserlohn IP evaluation filed)*
|
||||
*47 decisions. Last updated: 2026-04-21 (D-193 Lattice Commission name resolved)*
|
||||
|
||||
@@ -225,10 +225,11 @@ How the player observes and interacts with the world: camera, fog, line-of-sight
|
||||
- `GameState.insert_active` is the source of truth (defaults true in v0.1; wired from snapshot field `insert_active`).
|
||||
- Rationale: diegetically consistent — the body reacts to proximity; the insert reacts to commands.
|
||||
|
||||
### D-057: Entity interaction — vertical list, insert-styled
|
||||
### D-057: Entity interaction — vertical list, insert-styled [PARTIALLY SUPERSEDED — archetype portion deferred to Phase 6]
|
||||
- **Date:** 2026-02-13
|
||||
- **Supersession note (2026-04-21 / amended 2026-04-22, Sprint 37, #878, PR #137):** The character-archetype verb variation portion of this decision is retired pending a Phase 6 character-model design — not deferred in place with a stub. Per the development cascade (CLAUDE.md), archetype-driven verb relabeling is Phase 6 detail-coloring and has been stripped from the server. Vertical-list structure, Phase 1/Phase 2 split, POI priority flips, and contradiction markers remain live. Relabeling (Open→"Move"/"Stash" vs "Scan"/"Flag") is deleted; container verb labels are now identical across all player states, and uniform labeling is the intended pre-Phase-6 end state, not a regression. Reintroduction gate: a confirmed Phase 6 character-model design is a prerequisite. See `docs/architecture/sprint-37-878-audit.md` (lead override section) for the cascade rationale.
|
||||
- **Decision:** Entity interactions use a compact vertical list (not radial). 2-4 options max, anchored to entity position. Insert-styled with Araminta's geometric aesthetic. New options unlocked by knowledge changes are highlighted with a gradient glow background. Radial menu reserved for world menu only ([D-058](#d-058-world-menu--radial-4-spokes)). Max 3 visible response options in dialogue context.
|
||||
- **Server architecture:** Two-phase verb computation. Phase 1 (simulation, no KG): compute maximum possible verb set from ObjectType component (Readable, Container, Terminal, Door, Pickup, Furniture — each with specific verb sets). Phase 2 (observer, reads KG): filter by character's knowledge (Confront requires KnowsDetails+ per [D-041](architecture.md#d-041-knowledge-graph-data-model)), apply POI priority flips, add contradiction markers. Character-archetype verb variation implemented as Phase 2 observer filter rules (same crate: smuggler sees "Move/Stash", detective sees "Scan/Flag").
|
||||
- **Server architecture:** Two-phase verb computation. Phase 1 (simulation, no KG): compute maximum possible verb set from ObjectType component (Readable, Container, Terminal, Door, Pickup, Furniture — each with specific verb sets). Phase 2 (observer, reads KG): filter by character's knowledge (Confront requires KnowsDetails+ per [D-041](architecture.md#d-041-knowledge-graph-data-model)), apply POI priority flips, add contradiction markers. ~~Character-archetype verb variation implemented as Phase 2 observer filter rules (same crate: smuggler sees "Move/Stash", detective sees "Scan/Flag").~~ *[Removed Sprint 37 — archetype verb relabeling deleted; see supersession note above.]*
|
||||
- **Diegetic test:** Labels render on z-layer 6. If insert is off, labels disappear.
|
||||
- **Rationale:** Variable-length text options (e.g., confrontation lines in character voice) break radial spatial memory. List handles 1-4 options cleanly. New-item glow signals "something changed" without UX hazard of geometry transforming under cursor. Two-phase computation enables character differentiation without separate verb systems.
|
||||
- **References:** Disco Elysium (world-embedded indicators), Darkwood (minimal cursor), Rimworld (right-click context list).
|
||||
|
||||
@@ -229,12 +229,13 @@ Narrative, NPCs, dialogue, templates, setting, worldbuilding, and storyteller me
|
||||
---
|
||||
|
||||
### Q-095: Commission formal name — authoritative designation
|
||||
- **Status:** Open
|
||||
- **Status:** Resolved — see [D-193](content.md#d-193-lattice-commission--canonical-long-form-of-the-commission) (2026-04-21)
|
||||
- **Resolution:** Canonical long-form is **"the Lattice Commission"**. Short form "the Commission" remains standard in-prose. "Concord Commission" and "Assembly Commission" drift forms are non-canonical.
|
||||
- **Question:** What is the full formal name of the Concord Assembly's regulatory authority? In-prose use is "the Commission", but several drift forms have appeared in copy reviews ("Concord Commission", "Assembly Commission", "Lattice Commission"). A canonical long-form is needed for formal/legal contexts, institutional signage, and wiki headers.
|
||||
- **Context:** The Commission certifies implant hardware, medical equipment, pharmaceutical production, and safety-critical manufactured goods under tractus-denominated fees. It has no authority in Compact member systems. Current glossary guidance is to use "the Commission" until the full name is resolved, but authors writing institutional POIs and formal documents need a decision.
|
||||
- **Affects:** Wiki content, marker POI naming (e.g. `"Commission — Sirius Office"`), formal legal text in tractus fee documentation, institutional signage.
|
||||
- **Affects:** Wiki content, marker POI naming (e.g. `"Lattice Commission — Sirius Office"`), formal legal text in tractus fee documentation, institutional signage.
|
||||
- **Source:** Sprint 35 copy review (PR #127)
|
||||
|
||||
---
|
||||
|
||||
*25 questions (10 resolved, 2 partially resolved, 13 open). Last updated: 2026-04-14 (Q-095 added — Commission formal name)*
|
||||
*25 questions (11 resolved, 2 partially resolved, 12 open). Last updated: 2026-04-21 (Q-095 resolved — D-193 Lattice Commission)*
|
||||
|
||||
@@ -17,9 +17,9 @@ Tracked questions awaiting discussion or resolution. Split by domain, mirroring
|
||||
|--------|-------|----------|---------|------|
|
||||
| Architecture | 46 | 6 | 1 | 39 |
|
||||
| Perception | 9 | 5 | 0 | 4 |
|
||||
| Content | 25 | 10 | 2 | 13 |
|
||||
| Content | 25 | 11 | 2 | 12 |
|
||||
| Scope | 17 | 6 | 2 | 9 |
|
||||
| **Total** | **97** | **27** | **5** | **65** |
|
||||
| **Total** | **97** | **28** | **5** | **64** |
|
||||
|
||||
*Updated 2026-04-05: Full recount. Q-002, Q-004, Q-005, Q-007 closed as resolved (D-117/D-166). Architecture index corrected (was 13, actually 46 — Q-060 through Q-094 were missing from index).*
|
||||
|
||||
@@ -35,4 +35,4 @@ Tracked questions awaiting discussion or resolution. Split by domain, mirroring
|
||||
|
||||
When in doubt about where a question belongs: if it constrains **how we build**, it's architecture. If it defines **what the player observes or knows**, it's perception. If it defines **narrative, NPCs, dialogue, or setting**, it's content. If it defines **what we ship or how big it is**, it's scope.
|
||||
|
||||
*97 questions. Last updated: 2026-04-14 (Q-095 added — Commission formal name).*
|
||||
*97 questions. Last updated: 2026-04-21 (Q-095 resolved — D-193 Lattice Commission).*
|
||||
|
||||
+52
-5
@@ -207,13 +207,55 @@ Schema: `content/_schema/checklist.schema.json`. The checklist format feeds into
|
||||
- **Advisory** — when knowledge catalogs (`content/global/knowledge/*.yaml`) have no fact definitions yet: lists referenced fact_ids and exits cleanly.
|
||||
- **Enforcing** — when catalogs are populated: fails on any `fact_id` reference that doesn't match a canonical definition.
|
||||
|
||||
## Pre-commit Hooks
|
||||
## Asset Pipeline — Generator-Driven DB (#855, #856, #857)
|
||||
|
||||
`server/data/systems.db` is a **read-only canonical snapshot** produced by three
|
||||
generators. It is committed to the repo so the client can ship it, but it is never
|
||||
the source of truth. Direct edits are forbidden — they are silently overwritten by
|
||||
the next regeneration.
|
||||
|
||||
### Generators
|
||||
|
||||
| Generator | Source | Runs via |
|
||||
|-----------|--------|----------|
|
||||
| `generate_brands` | `server/src/bin/generate_brands/main.rs` | `tooling/generate-brands` |
|
||||
| `import_economics` | `tooling/economy-db/import_economics.py` | `python3 tooling/economy-db/import_economics.py` |
|
||||
| `generate_atlas` | `tooling/planet-gen/generate_atlas.py` | `python3 tooling/planet-gen/generate_atlas.py --seed 42` |
|
||||
|
||||
Run all three at once with:
|
||||
|
||||
```bash
|
||||
make regen-db
|
||||
```
|
||||
|
||||
### Meta table stamp
|
||||
|
||||
After every successful non-dry-run, each generator writes a row to the `meta` table in
|
||||
`systems.db` recording the SHA-1 of its source file(s) and the schema file.
|
||||
|
||||
```bash
|
||||
make check-systems-db # Verify the stamp is fresh (exit 1 = stale)
|
||||
```
|
||||
|
||||
### Making a DB change
|
||||
|
||||
1. Edit source files (TOML, JSON, `markers.json`).
|
||||
2. `make regen-db`
|
||||
3. `git add server/data/systems.db`
|
||||
4. Commit with `chore(db): regen systems.db — <reason>`
|
||||
|
||||
For schema changes, also update `server/data/systems-schema.sql` and add migration DDL
|
||||
to `MIGRATION_SQL` in `import_economics.py`.
|
||||
|
||||
See `.claude/rules/asset-pipeline.md` for the full rule set.
|
||||
|
||||
## Pre-commit and Pre-push Hooks
|
||||
|
||||
Git hooks are stored in `.config/hooks/` (version-controlled). Activate them with:
|
||||
|
||||
```bash
|
||||
make setup # Includes hook installation
|
||||
make setup-hooks # Just hooks
|
||||
make install-hooks # Just hooks (also makes them executable)
|
||||
```
|
||||
|
||||
Or manually:
|
||||
@@ -224,9 +266,14 @@ git config core.hooksPath .config/hooks
|
||||
|
||||
Active checks:
|
||||
|
||||
| Check | Script | Behavior |
|
||||
|-------|--------|----------|
|
||||
| fact_id validation | `tooling/check-fact-ids` | Warns if catalogs are stubs; fails on unknown fact_ids when populated |
|
||||
| Hook | Check | Script | Behavior |
|
||||
|------|-------|--------|----------|
|
||||
| pre-commit | fact_id validation | `tooling/check-fact-ids` | Warns if catalogs are stubs; fails on unknown fact_ids when populated |
|
||||
| pre-push | GDScript parse | internal | Fails on any SCRIPT ERROR |
|
||||
| pre-push | Rust lint | internal | fmt + clippy |
|
||||
| pre-push | Python lint | internal | ruff |
|
||||
| pre-push | JSON syntax | internal | python3 -m json.tool |
|
||||
| pre-push | systems.db stamp | `tooling/check-systems-db-stamp` | Rejects stale DB when pushed (#857) |
|
||||
|
||||
The `core.hooksPath` setting uses a relative path (`.config/hooks`) that resolves per worktree, so it works correctly across all worktrees in the repository.
|
||||
|
||||
|
||||
@@ -213,15 +213,12 @@ Note: `ConfirmBookmark` is the **trigger** for transitioning from the character-
|
||||
|
||||
```rust
|
||||
/// The confirmed bookmark selection for the current session.
|
||||
/// Populated when `ConfirmBookmark` is processed. `None` during the
|
||||
/// character-creation phase (before confirm) and always `None` in a
|
||||
/// fresh session.
|
||||
/// Populated when `ConfirmBookmark` is processed. `None` fields during the
|
||||
/// character-creation phase (before confirm) and in a fresh session.
|
||||
///
|
||||
/// **v0.2 scope: transient only.** Not serialized — save/load of
|
||||
/// `SelectedBookmark` is deferred to Sprint 37 (follow-up ticket
|
||||
/// filed alongside #614). Add `Serialize`/`Deserialize` derives and
|
||||
/// wire into `SaveState` when that ticket is claimed.
|
||||
#[derive(Resource, Debug, Clone, Default)]
|
||||
/// Serialized into `SaveStateV1.selected_bookmark` (#863) so that a loaded
|
||||
/// game remembers which bookmark and starting location were chosen.
|
||||
#[derive(Resource, Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct SelectedBookmark {
|
||||
pub bookmark_id: Option<String>,
|
||||
pub starting_location_id: Option<String>,
|
||||
@@ -231,15 +228,11 @@ pub struct SelectedBookmark {
|
||||
Downstream systems (apartment generator, skill seeder) read from this
|
||||
resource.
|
||||
|
||||
**Save/load scope (v0.2 deferred):** `SelectedBookmark` is transient for
|
||||
v0.2 — it lives in-memory from `ConfirmBookmark` through session end and
|
||||
is not persisted. A reload after quit returns the player to the
|
||||
character-creation screen. Promotion to persistent state (adding
|
||||
`Serialize`/`Deserialize` and threading into `SaveState` / #553) is
|
||||
tracked in a follow-up ticket for Sprint 37. `SelectedBookmark` must
|
||||
carry an inline `// TODO(sprint-37): serialize — see #<follow-up ticket>`
|
||||
comment in `server/src/bookmark/mod.rs` pointing at the follow-up so the
|
||||
omission is greppable.
|
||||
**Save/load scope (Sprint 37, #863):** `SelectedBookmark` is persisted into
|
||||
`SaveStateV1.selected_bookmark`. After `load_from_file` completes, the resource
|
||||
reflects the bookmark confirmed at session-start. Saves created before Sprint 37
|
||||
will deserialize the field as `SelectedBookmark::default()` (both fields `None`)
|
||||
via `#[serde(default)]` on the `SaveStateV1` field.
|
||||
|
||||
## 5. Content source — how bookmarks get into the registry
|
||||
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
# Sprint 37 #878 — CharacterArchetype audit (D-032 obsolete claim)
|
||||
|
||||
**Author:** Tyre (architecture)
|
||||
**Date:** 2026-04-21 (audit); 2026-04-22 (lead override amendment)
|
||||
**Ticket:** #878 — Audit and purge dead smuggler/detective character enum (D-032 obsolete)
|
||||
**Status:** CLOSED — lead override 2026-04-21: strip stays. See override section below.
|
||||
|
||||
---
|
||||
|
||||
## Lead override (2026-04-21)
|
||||
|
||||
**Decision:** STRIP the full `CharacterArchetype` trace from the server. The
|
||||
original audit (below) recommended Option A (no-op, docs-only) on the basis
|
||||
that grep identified five load-bearing consumers. The lead reframed the
|
||||
live-vs-filler determination:
|
||||
|
||||
> "It is live because we have not scrapped the system loading it in the
|
||||
> client. This is not live gameplay. Only the character creation elements
|
||||
> and the insert screens are actual production code. The rest is uncleaned
|
||||
> filler — per the cascade, we don't deal with character and NPC
|
||||
> instructions." — Jeroen, 2026-04-21
|
||||
|
||||
**Rationale — the cascade framing.** Per `CLAUDE.md`, development follows a
|
||||
strict six-phase cascade. Current focus is Phase 1 (wiki content). Character
|
||||
model, NPC differentiation, verb-label relabeling, and character-keyed
|
||||
monologue pools all belong to Phase 6 (detail coloring). Code that executes
|
||||
at runtime is **not** automatically production — if the topic belongs to a
|
||||
later cascade phase, it is pre-cascade filler regardless of how deeply it is
|
||||
wired in.
|
||||
|
||||
The audit's identification of `archetype_verb_label` as "live feature code"
|
||||
was mechanically correct: the code runs, produces output, and is observed on
|
||||
the wire. But the **feature itself is premature**. Container verb
|
||||
differentiation (Smuggler Move/Stash vs Detective Scan/Flag) and
|
||||
archetype-keyed monologue pools are Phase 6 detail, not Phase 1–3
|
||||
scaffolding. Uniform verb labels and a single monologue pool are the
|
||||
intended end state until a Phase 6 character system is designed — not a
|
||||
regression.
|
||||
|
||||
**Audit correction.** The audit's TL;DR conclusion ("v0.2 dropped reverses
|
||||
D-117 which reverses D-032-obsolete, therefore keep the enum") was the
|
||||
wrong frame. The supersession chain collapsed — yes — but the correct
|
||||
reading is that **all three decisions sit below the current cascade
|
||||
floor**, so the enum is cruft on cascade grounds independent of the D-117
|
||||
revocation. The audit should have consulted the cascade phase before
|
||||
grep-counting consumers; that is the non-obvious precedent captured in
|
||||
memory (`feedback_running_code_not_production.md`).
|
||||
|
||||
**Scope of the strip (Sprint 37, #878, merged via PR #137). Commit `cae3d3ab`
|
||||
— "refactor(simulation): strip archetype trace + HeritageRoot per cascade
|
||||
(#877, #878)" — is the authoritative file list; the summary below is the
|
||||
high-signal view:**
|
||||
|
||||
- `server/src/bridge/types.rs` — `CharacterArchetype` enum +
|
||||
`StartupMessage.character_archetype` field removed. Protocol break rides
|
||||
the `PROTOCOL_VERSION` drop in #874 (D-192), co-shipped in the same PR.
|
||||
- `server/src/perception/observer/mod.rs` — `apply_phase2_verb_filter`
|
||||
loses its archetype parameter; `archetype_verb_label` helper + the
|
||||
container-relabeling block deleted.
|
||||
- `server/src/simulation/monologue.rs` — `MonologueState.character`
|
||||
field + `Default` value removed. Pool selection is now uniform.
|
||||
- `server/src/simulation/examine.rs` — `generate_examine_text` collapses
|
||||
two archetype-specific branches into a single detective-style frame.
|
||||
- `server/src/test_world/mod.rs` + `server/src/main.rs` — `setup_gauntlet`
|
||||
and `setup_proof_room` drop the archetype parameter; all internal
|
||||
callsites + the production main loop updated.
|
||||
- `server/tests/archetype_monologue.rs` — deleted (regression guard for
|
||||
#587's archetype→monologue wiring; wiring itself deleted).
|
||||
- `server/tests/v01_integration_playthrough.rs` — deleted (5
|
||||
archetype-using integration tests; superseded by Gauntlet coverage).
|
||||
- `server/content/schemas/drama_module.schema.yaml` — deleted.
|
||||
- `server/content/modules/tier1/smuggling_ring_v0_1.yaml` — deleted.
|
||||
|
||||
**Client follow-up: ticket #882** — *"Strip archetype-driven client code
|
||||
(follow-up to #878 server)"*. The server strip leaves client-side code
|
||||
referencing the removed `character_archetype` wire field and archetype-
|
||||
keyed palette/monologue branches. Client cleanup preserves the character-
|
||||
creation UI and insert screens (production per the lead call) and strips
|
||||
`lattice_profile` branching, `character.txt` session I/O, and protocol
|
||||
decoding of the removed field. Blocked by this PR; cross-referenced in
|
||||
the server task description.
|
||||
|
||||
**Decision record amendments (2026-04-22):**
|
||||
|
||||
- `decisions/content.md` D-032 `[SUPERSEDED]` header rewritten to cite the
|
||||
cascade instead of the dropped D-117.
|
||||
- `decisions/content.md` D-035 monologue `character` enum note updated
|
||||
(was `[Obsolete post-D-117]`, now cites the cascade strip).
|
||||
- `decisions/perception.md` D-057 marked `[PARTIALLY SUPERSEDED]` with
|
||||
the archetype verb relabeling portion crossed out; vertical-list +
|
||||
Phase 1/2 split preserved.
|
||||
|
||||
**Regression guards for the new uniform behavior** are being added under
|
||||
separate tasks (Hoshe, Sprint 37) — positive assertions that container
|
||||
verb labels and monologue pool selection are archetype-independent, to
|
||||
prevent silent reintroduction.
|
||||
|
||||
**DECISION: STRIP.**
|
||||
|
||||
The original audit body below is retained as a historical record of the
|
||||
pre-override analysis. Do not take its recommendation as current.
|
||||
|
||||
---
|
||||
|
||||
## TL;DR (original audit, SUPERSEDED by lead override above)
|
||||
|
||||
The ticket's premise — that `CharacterArchetype` (Smuggler/Detective) is dead
|
||||
code per D-032's "[Obsolete post-D-117]" footnote — is **stale**. The
|
||||
footnote relied on D-117 (tycoon is the v0.2 bookmark), but `CLAUDE.md`
|
||||
now declares **"v0.2 target is dropped. No scoping negotiations."** That
|
||||
revocation is the most recent architectural directive, and it rolls back
|
||||
the premise that justified marking the enum obsolete.
|
||||
|
||||
Recommendation: **do not delete `CharacterArchetype`**. Instead, update
|
||||
the decision record to clear the stale obsolete footnote, close the
|
||||
ticket as "no-op — premise superseded," and (optionally) claim a small
|
||||
D-record documenting the reversal chain.
|
||||
|
||||
## Audit
|
||||
|
||||
Grep was run against `server/`, `tooling/`, and `tests/`. `CharacterArchetype`
|
||||
has **five load-bearing consumers** plus content-schema users:
|
||||
|
||||
### 1. IPC protocol surface
|
||||
- `server/src/bridge/types.rs:51-54` — `StartupMessage.character_archetype: CharacterArchetype`.
|
||||
Field is serialized into the session handshake. Removing it is a protocol break.
|
||||
- `server/src/bridge/types.rs:500-518` — enum + `as_monologue_key()` helper + `Default = Detective`.
|
||||
- Roundtrip tests at lines 1133, 1146, 1157, 1166, 1173, 1184 exercise the field.
|
||||
|
||||
### 2. Observer pipeline (D-057, #422) — real runtime behavior
|
||||
- `server/src/perception/observer/mod.rs:81,117,138,200` — archetype flows through
|
||||
`apply_phase2_verb_filter`.
|
||||
- `server/src/perception/observer/mod.rs:657-760` — `archetype_verb_label()` swaps
|
||||
container verb labels based on archetype (Smuggler sees `Move`/`Stash`, Detective
|
||||
sees `Scan`/`Flag`). This is live feature code, not scaffolding.
|
||||
|
||||
### 3. Monologue pool selection (D-032, #587, #595)
|
||||
- `server/src/simulation/monologue.rs:134-152` — `MonologueState.character: String` is
|
||||
initialized from `CharacterArchetype.as_monologue_key()` at session start.
|
||||
Pool partition is by string key, but the string is *derived* from the enum.
|
||||
|
||||
### 4. Gauntlet test-world plumbing
|
||||
- `server/src/test_world/mod.rs:98` — `pub fn setup_gauntlet(app: &mut App, archetype: CharacterArchetype)`.
|
||||
- 5 internal callsites (lines 702, 725, 742, 761, 778) plus the external
|
||||
`archetype_monologue.rs` integration suite.
|
||||
|
||||
### 5. Regression test suite
|
||||
- `server/tests/archetype_monologue.rs` — entire file is a regression guard
|
||||
against #587 (archetype→monologue character wiring). Seven tests, four
|
||||
explicitly assert Smuggler vs Detective behavior. Deleting the enum requires
|
||||
deleting this guard, which is the thing that catches the bug it was built for.
|
||||
|
||||
### 6. Content schemas (authoring)
|
||||
- `server/content/schemas/drama_module.schema.yaml:231,233,234,280,558` —
|
||||
schema enumerates `smuggler | detective | any` for dialogue/monologue
|
||||
partitioning in drama modules.
|
||||
|
||||
## Decision chain (why the ticket premise is stale)
|
||||
|
||||
```
|
||||
D-027 (v0.1 vertical slice = smuggler + detective)
|
||||
└─ superseded by D-117 (2026-03-05: tycoon is the v0.2 bookmark)
|
||||
└─ superseded by "v0.2 target is dropped" (CLAUDE.md, current)
|
||||
```
|
||||
|
||||
The obsolete footnote in D-035 line 83 and the `[SUPERSEDED]` header on
|
||||
D-032 both point at D-117 as the supersession. With v0.2 dropped, we are
|
||||
back to the v0.1 smuggler/detective frame as the implemented base until
|
||||
the 6-phase cascade reaches Phase 4 (Player control) — and even then,
|
||||
the cascade describes a 2-floor test map + character rendering, not a
|
||||
wholesale character-model replacement.
|
||||
|
||||
## Proposed alternative scope for #878
|
||||
|
||||
Three options, cheapest first:
|
||||
|
||||
### A. Close as no-op + documentation cleanup (recommended)
|
||||
- Strip the `[Obsolete post-D-117]` footnote from `decisions/content.md:83`
|
||||
(D-035 tag taxonomy).
|
||||
- Remove the `[SUPERSEDED]` marker from `decisions/content.md:47` (D-032
|
||||
header) or add a "supersession reversed" note.
|
||||
- Optionally claim a new D-record in `decisions/scope.md` documenting
|
||||
that the v0.2-dropped directive implicitly reverses D-117's character
|
||||
frame revocation.
|
||||
- Zero code changes. Build stays green. 30 minutes.
|
||||
|
||||
### B. Narrow the ticket to the authoring-side leftovers
|
||||
- If there are *authoring* artifacts (half-written tycoon monologue
|
||||
partitioning, stale schema fields) that were added in anticipation of
|
||||
D-117 and never used, those can be purged. But a quick scan of
|
||||
`drama_module.schema.yaml` shows the schema is consistent with v0.1 usage.
|
||||
- Requires a content team review — server-team scope alone cannot
|
||||
confirm what is live in authoring.
|
||||
|
||||
### C. Rename without removing (if lead wants distance from v0.1 framing)
|
||||
- Rename `CharacterArchetype` → `PlayerCharacterRole` (or similar) and
|
||||
its variants to preserve behavior while shedding the "smuggler/detective
|
||||
investigation framing" language. Higher risk, touches ~45 files, and
|
||||
doesn't actually change runtime. **Not recommended** unless the lead
|
||||
specifically wants the naming to match post-cascade vocabulary.
|
||||
|
||||
## Recommendation (SUPERSEDED — see "Lead override" at top)
|
||||
|
||||
~~Go with **Option A**. The enum is architecturally sound, the ticket is
|
||||
a casualty of the v0.2→cascade pivot, and the cleanup is documentation-
|
||||
only.~~
|
||||
|
||||
**Actual decision:** strip (Option D, not enumerated above — full trace
|
||||
purge driven by cascade framing, not by the D-117/v0.2 supersession
|
||||
chain). The audit's grep-count-first methodology was the wrong starting
|
||||
heuristic; cascade phase comes first. See top of document.
|
||||
Binary file not shown.
@@ -0,0 +1,88 @@
|
||||
# Sprint 37: Sweep — CI Tasks
|
||||
|
||||
**Goal:** Spring-clean accumulated debt: asset pipeline discipline, PROTOCOL_VERSION removal, D-167/D-032 dead-code purge, New Game regression fix, copy wiki residue, bookmark save-state, and generator quality patches.
|
||||
|
||||
**Branch:** `sprint-37/ci`
|
||||
**Agents:** Gestalt (systems), Hoshe (QA)
|
||||
|
||||
## New Tickets
|
||||
|
||||
| # | Title | Priority | Blocked by |
|
||||
|---|-------|----------|------------|
|
||||
| #854 | Generator-driven asset pipeline — regeneration discipline and versioning (epic) | high | — |
|
||||
| #855 | systems.db regeneration with versioning awareness | high | #854 |
|
||||
| #856 | Stamp systems.db with generator metadata (meta table) | high | #855 |
|
||||
| #857 | Pre-push git hook for systems.db consistency | high | #856 |
|
||||
| #858 | Extend /pr-push with rebase + regen + stage | high | #856 |
|
||||
| #859 | Document the source-canonical rule (.claude/rules/asset-pipeline.md + DEVOPS) | medium | #856 |
|
||||
| #723 | Add decision-to-ticket coverage report | medium | — |
|
||||
|
||||
Use `tooling/db/ticket show <id>` for full details.
|
||||
|
||||
## Key Decisions
|
||||
|
||||
No domain decisions gate this sprint's work. The asset pipeline epic creates new process conventions documented in `.claude/rules/asset-pipeline.md` (deliverable of #859).
|
||||
|
||||
## Notes
|
||||
|
||||
**#854 — Generator-driven asset pipeline (epic wrapper)**
|
||||
- This epic establishes the mental model: `server/data/systems.db` is a read-only canonical snapshot, deterministically produced from source files (markers.json, *.toml, generator code). Direct DB edits are forbidden except when mirrored back to source.
|
||||
- Children: #855 → #856 → #857 and #858 (parallel after #856) → #859 (docs, after #856).
|
||||
- Driver: Sprint 36 had a binary conflict risk between two branches both committing systems.db changes. This epic prevents the class of problem going forward and establishes the versioning primitives the future savegame system will need.
|
||||
- #854 itself has no code deliverable — it is the parent epic for tracking purposes. Work happens in children.
|
||||
|
||||
**#855 — systems.db regeneration with versioning awareness**
|
||||
- Every generator (`import_economics.py`, `generate_atlas.py`, `generate_brands`) must be updated to accept a `--stamp` flag (or equivalent) that writes metadata to the DB after generation.
|
||||
- The regeneration step should be idempotent: running it twice on the same sources produces identical output.
|
||||
- Unblocks #856, #857, #858, #859.
|
||||
|
||||
**#856 — Stamp systems.db with generator metadata (meta table)**
|
||||
- Add a `meta` table to `db/schema.sql`: columns `schema_version`, `generator_sha`, `generated_at`.
|
||||
- Each generator writes its own row on completion.
|
||||
- The stamp is what lets a future savegame DB record which canonical snapshot it derives from (migration lineage).
|
||||
- Blocked by #855 (generators must be updated before stamping is meaningful).
|
||||
|
||||
**#857 — Pre-push git hook for systems.db consistency**
|
||||
- Hook fires on `git push` and verifies: if `systems.db` is staged, its `meta.generator_sha` matches the current HEAD SHA of the generator source files.
|
||||
- If not, rejects the push with a message: "systems.db is stale — run `make regen-db` before pushing."
|
||||
- Install via `make install-hooks`. Document in #859.
|
||||
|
||||
**#858 — Extend /pr-push with rebase + regen + stage**
|
||||
- The `/pr-push` skill runs before PR creation. Extend it to: (1) rebase on main, (2) run `make regen-db` if any generator source was modified in the branch, (3) stage the updated `systems.db`.
|
||||
- This prevents the class of binary conflict where two branches both modify generator sources and commit separate DB snapshots.
|
||||
- Parallel to #857 after #856 is done.
|
||||
|
||||
**#859 — Document the source-canonical rule**
|
||||
- Deliverables:
|
||||
1. `.claude/rules/asset-pipeline.md` — canonical rules file covering: what systems.db is, how to make a DB change, why direct edits are forbidden, the meta table stamp, the pre-push hook, why /pr-push regenerates.
|
||||
2. `CLAUDE.md` hook — one-line reference under a new `### Asset pipeline` subsection pointing at the rules file.
|
||||
3. `docs/DEVOPS.md` — short section on the pipeline: meta table, `make install-hooks`, regenerate-before-push workflow.
|
||||
- Blocked by #856 (meta table must exist before documenting it).
|
||||
|
||||
**#723 — Decision-to-ticket coverage report**
|
||||
- No schema change needed — `tickets.decision_ref` already exists.
|
||||
- Deliverables:
|
||||
1. `make decisions-coverage` — shows each D-record with its implementing ticket(s).
|
||||
2. `make decisions-orphan` — shows D-records with no implementing tickets (verify existing target works).
|
||||
3. `tooling/db/decision show D-159` — includes linked ticket IDs in output.
|
||||
- The reverse link (decision → tickets) is a `SELECT` query, not a new column. Avoids fragile two-way sync.
|
||||
- Standalone, parallel to the asset pipeline chain.
|
||||
|
||||
## Dependency Chain
|
||||
|
||||
```
|
||||
#854 (epic) → no code
|
||||
#855 (regen awareness) → #856 (meta table) → #857 (pre-push hook)
|
||||
→ #858 (pr-push extension)
|
||||
→ #859 (documentation)
|
||||
#723 → standalone, parallel to all above
|
||||
```
|
||||
|
||||
## PR Workflow
|
||||
|
||||
```bash
|
||||
tea pr create --repo jpmschweitzer/settled-reach --login schweitz \
|
||||
--title "ci: sprint 37 — asset pipeline discipline, decision coverage report" \
|
||||
--description "body" \
|
||||
--base main --head sprint-37/ci
|
||||
```
|
||||
@@ -0,0 +1,93 @@
|
||||
# Sprint 37: Sweep — Client Tasks
|
||||
|
||||
**Goal:** Spring-clean accumulated debt: asset pipeline discipline, PROTOCOL_VERSION removal, D-167/D-032 dead-code purge, New Game regression fix, copy wiki residue, bookmark save-state, and generator quality patches.
|
||||
|
||||
**Branch:** `sprint-37/client`
|
||||
**Agents:** Stig (dev), Hoshe (QA)
|
||||
|
||||
## New Tickets
|
||||
|
||||
| # | Title | Priority | Blocked by |
|
||||
|---|-------|----------|------------|
|
||||
| #872 | New Game flow hangs on 'connecting' after sprint-36 Option A handoff | high | — |
|
||||
| #873 | Scene-level merge-path UI flow tests (gdUnit4) | high | — |
|
||||
| #866 | dialogue_box _escape_bbcode chained replace corrupts [lb] escapes | high | — |
|
||||
| #869 | Fix MetaScreen test helper regression — anti_tedium suite (7 fails) | high | — |
|
||||
| #870 | Delete or revive 8 parse-error test files | medium | — |
|
||||
| #875 | Drop PROTOCOL_VERSION on client (D-192) | medium | #874 (server) |
|
||||
| #882 | Strip archetype-driven client code (follow-up to #878) | medium | #878 (server) |
|
||||
|
||||
Use `tooling/db/ticket show <id>` for full details.
|
||||
|
||||
## Key Decisions
|
||||
|
||||
- `decisions/architecture.md` — D-192 (drop PROTOCOL_VERSION lockstep handshake), D-005 (IPC protocol)
|
||||
|
||||
## Notes
|
||||
|
||||
**#872 — New Game flow hangs on 'connecting' (motivating regression)**
|
||||
- Manual repro during Sprint 36 PR #134 smoke test: main menu → New Game → loading screen shows 'connecting' and never progresses.
|
||||
- Likely suspects:
|
||||
1. `client/ui/meta/screens/main_menu/main_menu.gd` — `_process()` polls `SimBridge.poll_snapshot()` while `_waiting_for_catalog` is true. If `bookmark_catalog` never arrives (or arrives but the flag isn't cleared), the loop runs forever.
|
||||
2. `client/ui/meta/screens/loading/loading_screen.gd` — opaque BG + `MOUSE_FILTER_STOP` means a never-dismissed loading state looks identical to 'hung connecting'.
|
||||
3. `client/scripts/protocol/protocol.gd` — `bookmark_catalog` decode landed in v23 (commit 41e89579). Verify server is actually sending `bookmark_catalog` in the first snapshot after connect.
|
||||
4. Option A scene handoff race — confirm `main_menu → character_creation` triggers on a signal, not a polled flag.
|
||||
- Suggested investigation order: add trace prints in `main_menu._process` to confirm `SimBridge.state` and `GameState.bookmark_catalog` contents during the hang. That will disambiguate suspects 1 vs 3 in minutes.
|
||||
|
||||
**#873 — Scene-level merge-path UI flow tests (gdUnit4)**
|
||||
- Add gdUnit4 scene-level tests for merge-path UI flows so regressions like #872 are caught pre-merge instead of post-merge.
|
||||
- Scope — one test per flow:
|
||||
- main menu → new game → character creation → confirm → connected state
|
||||
- main menu → load game → save picker → selected
|
||||
- character creation → submit → `sim_bridge` receives correct payload
|
||||
- bookmark tab → select location → confirm → server gets bookmark action
|
||||
- Tests must run headless via `tests/run-godot`. Pattern: load scene → simulate input via `_input()` or `button.pressed.emit()` → await signals or poll state with timeout → assert terminal state.
|
||||
- NOT pixel/screenshot diffing. NOT RPA/xdotool. NOT CI integration (existing `make test-client` already covers this).
|
||||
- Reference pattern: `test_character_creation_sprint28.gd`.
|
||||
- These tests are the mechanism the `pr-review` merge-path gate (added Sprint 36 retro) assumes exists.
|
||||
|
||||
**#866 — _escape_bbcode chained replace corruption**
|
||||
- `dialogue_box.gd:628` chains `.replace('[', '[lb]').replace(']', '[rb]')`. The second replace turns `[lb]` into `[lb[rb]`, corrupting the escape. BBCode injection guard is effectively broken for server-sourced text.
|
||||
- Fix: escape only `[` (not `]`), since unmatched `]` in RichTextLabel renders as literal.
|
||||
- Test: `test_escape_bbcode_brackets_in_server_text` in `test_dialogue_sprint18.gd` (currently skipped) — unskip and make it pass.
|
||||
|
||||
**#869 — MetaScreen test helper regression (7 fails)**
|
||||
- Sprint 36 migrated `bug_report_dialog.gd` from `extends Control` to `extends MetaScreen`. `test_anti_tedium.gd:94` builds the dialog via `Control.new() + set_script(BugReportDialogScript)`, which no longer satisfies the MetaScreen base contract.
|
||||
- Every call to `dialog.start_capture()` fails with `Nonexistent function in base Control`. 7 failing tests in the anti_tedium suite.
|
||||
- Fix: instantiate the `.tscn` (preserves the MetaScreen runtime stack) instead of building from script, OR have the test instantiate a MetaScreen-rooted node.
|
||||
|
||||
**#870 — Delete or revive 8 parse-error test files**
|
||||
- These 8 files fail to parse (not just fail tests), contributing to gdUnit error counts: `test_debug_overlay_sprint19.gd`, `test_entanglement_sprint22.gd`, `test_fog_sprint22.gd`, `test_journal_sprint18.gd`, `test_minimap_sprint18.gd`, `test_session_manager_sprint19.gd`, `test_sprint30.gd`, `test_sprite_integration.gd`.
|
||||
- They reference removed/renamed APIs from prior sprints.
|
||||
- Default: delete. File a fresh ticket if/when the underlying coverage is needed again. If any file is worth reviving, rewrite it against the current API.
|
||||
|
||||
**#875 — Drop PROTOCOL_VERSION on client (D-192)**
|
||||
- Blocked by server ticket #874 — merge server PR first.
|
||||
- Remove: `version` field read in `client/scripts/protocol/protocol.gd` (`Protocol.decode_snapshot`), the `PROTOCOL_VERSION` constant, and the version-mismatch guard.
|
||||
- Update any fixture-replay paths that read `version`.
|
||||
- Keep all field-presence and roundtrip behavioral tests.
|
||||
|
||||
**#882 — Strip archetype-driven client code (follow-up to server #878)**
|
||||
- Added 2026-04-21. Blocked by server #878 (removes `character_archetype` from StartupMessage; rides #874's PROTOCOL_VERSION break).
|
||||
- Per lead direction: the CharacterArchetype trace is Phase 6 filler, not production. Keep character-creation UI and insert screens; strip everything else.
|
||||
- Strip: `character_archetype` field in `game_state.gd` (line 100), `lattice_profile` derivation (line 47); `session_manager.gd` `save_character_archetype()`, `_read_archetype_file()`, character.txt save/load (lines 58, 172–192); `protocol.gd` `character_archetype` on StartupMessage; `sim_bridge.gd` archetype wire-up; any monologue color-palette code keyed on `lattice_augmented`/`lattice_baseline`; audit `tests/client/test_signal_sprint24.gd`.
|
||||
- Verify: client launches, character creation UI loads, insert screens render, session starts. Grep `character_archetype`, `lattice_profile`, `smuggler`, `detective` in `client/` — only character-creation UI references remain.
|
||||
- Context: server-side audit at `docs/architecture/sprint-37-878-audit.md` (on server branch until #878 merges).
|
||||
|
||||
## Dependency Chain
|
||||
|
||||
```
|
||||
#874 (server) → #875 (client PROTOCOL_VERSION drop)
|
||||
#878 (server) → #882 (client archetype strip)
|
||||
#872 (New Game regression fix) → #873 (merge-path tests add coverage for this flow)
|
||||
#866, #869, #870 → standalone, parallel
|
||||
```
|
||||
|
||||
## PR Workflow
|
||||
|
||||
```bash
|
||||
tea pr create --repo jpmschweitzer/settled-reach --login schweitz \
|
||||
--title "fix(client): sprint 37 — New Game regression, test cleanup, PROTOCOL_VERSION drop" \
|
||||
--description "body" \
|
||||
--base main --head sprint-37/client
|
||||
```
|
||||
@@ -0,0 +1,65 @@
|
||||
# Sprint 37: Sweep — Copy Tasks
|
||||
|
||||
**Goal:** Spring-clean accumulated debt: asset pipeline discipline, PROTOCOL_VERSION removal, D-167/D-032 dead-code purge, New Game regression fix, copy wiki residue, bookmark save-state, and generator quality patches.
|
||||
|
||||
**Branch:** `sprint-37/copy`
|
||||
**Agents:** Mellanie (author), Paula (narrative), Miri (consistency)
|
||||
|
||||
## New Tickets
|
||||
|
||||
| # | Title | Priority | Blocked by |
|
||||
|---|-------|----------|------------|
|
||||
| #876 | decide(content): Commission formal name — canonical long-form designation (Q-095) | medium | — |
|
||||
| #865 | Purge remaining v0.1 Sova/Van Maanen's residue from wiki | medium | — |
|
||||
| #861 | Author 112 brand corp wiki stubs to three-layer narrative depth | medium | — |
|
||||
|
||||
Use `tooling/db/ticket show <id>` for full details.
|
||||
|
||||
## Key Decisions
|
||||
|
||||
- `decisions/questions.md` — Q-095 (Commission formal name — Concord Commission vs. Lattice Commission)
|
||||
- `decisions/content.md` — D-128 (culture implicit in starting location), D-122 (all NPCs generated)
|
||||
- `decisions/economics.md` — D-189 (brand layer architecture — 8 categories), D-185 (brands are not commodities)
|
||||
|
||||
## Open Questions to Resolve Early
|
||||
|
||||
- **Q-095: Commission formal name** — Drift between "Concord Commission" and "Lattice Commission" blocks institutional POI signage and tractus fee legal text. Jeroen picks the long-form name; Mellanie/Paula codify everywhere. Resolve in the first session of the sprint before #865 touches faction files.
|
||||
|
||||
## Notes
|
||||
|
||||
**#876 — Commission formal name decision (Q-095)**
|
||||
- One-conversation resolution. The two drifted names appear in: faction wiki pages, tractus fee descriptions, legal-text authoring guide examples, and institution templates.
|
||||
- Deliverable: a confirmed D-record (claim an ID with `tooling/db/decision claim D content "Commission formal name"` before writing). Update `decisions/questions.md` to mark Q-095 resolved with the D-record reference.
|
||||
- Do this first — #865 will touch faction files and should use the canonical name.
|
||||
|
||||
**#865 — Purge v0.1 Sova/Van Maanen's residue from wiki**
|
||||
- Start by running `grep -rln 'v0\.1\|Sova Transit\|Van Maanen\|Kael Davan\|Sera Venn\|Nils Davan\|the-ring' wiki/` to scope the full hit list.
|
||||
- Confirm three decision points with Jeroen before bulk editing:
|
||||
1. Sova/Transit tree under `wiki/star-systems/GJ-35/sova/` — delete outright, or reparent/retag as a legitimate Vuurkloof station?
|
||||
2. Example references in authoring guides/templates — keep as illustrative voice examples, or replace with galactic-scope alternatives?
|
||||
3. Decision/lore files citing Kael/Sera/etc. as canonical — rewrite to generic, or delete those sections?
|
||||
- This is judgment-heavy cleanup, not a mechanical find/replace. Confirm the decision points first; do the bulk editing after.
|
||||
- Resolve Q-095 (#876) before touching faction files so the correct Commission name is used throughout.
|
||||
|
||||
**#861 — Author 112 brand corp wiki stubs to three-layer narrative depth**
|
||||
- Sprint 36 PR #133 shipped 112 new corp wiki pages in `wiki/corporations/` as 24-line frontmatter-only placeholders. They need authoring to the canonical three-layer standard.
|
||||
- Reference template: Calloway, Thrds, VGV, Thalassa stubs (95–125 lines each). Three layers: (1) public identity, (2) actual operation, (3) one concealed fact.
|
||||
- DoD per page: ≥95 lines, all three layers present, cross-refs populated, corridor/founding-system specificity (not generic boilerplate).
|
||||
- This is a full sprint's worth of work for the team. Do not attempt to cram into a single session — divide by corridor or category across Mellanie/Paula/Miri and review as you go.
|
||||
- Paula reviews narrative as authoring progresses. Miri checks cross-ref consistency.
|
||||
|
||||
## Dependency Chain
|
||||
|
||||
```
|
||||
#876 (Q-095 Commission name) → #865 (wiki residue purge touches faction files)
|
||||
#861 → standalone, parallel to both above
|
||||
```
|
||||
|
||||
## PR Workflow
|
||||
|
||||
```bash
|
||||
tea pr create --repo jpmschweitzer/settled-reach --login schweitz \
|
||||
--title "content(wiki): sprint 37 — brand corp stubs, wiki residue purge, Commission name" \
|
||||
--description "body" \
|
||||
--base main --head sprint-37/copy
|
||||
```
|
||||
@@ -0,0 +1,71 @@
|
||||
# Sprint 37: Sweep — Joint Overview
|
||||
|
||||
**Sprint goal:** Spring-clean accumulated debt: asset pipeline discipline, PROTOCOL_VERSION removal, D-167/D-032 dead-code purge, New Game regression fix, copy wiki residue, bookmark save-state, and generator quality patches.
|
||||
|
||||
**Sprint 37 is a maintenance and polish sprint.** No new features. Every ticket is either closing a decision-without-follow-through, fixing a regression, establishing infrastructure discipline, or clearing content debt.
|
||||
|
||||
## Pre-Sprint Decisions
|
||||
|
||||
| Decision | Status | Owner | Blocks |
|
||||
|----------|--------|-------|--------|
|
||||
| Q-095: Commission formal name | Open — resolve sprint day 1 | copy (Jeroen picks) | #876, #865 |
|
||||
| D-192: Drop PROTOCOL_VERSION | Confirmed | server then client | #874 → #875 |
|
||||
| D-167: HeritageRoot removal | Confirmed | server | #877 |
|
||||
| D-032: Smuggler/detective enum | Confirmed obsolete | server | #878 |
|
||||
|
||||
## Full Ticket Roster
|
||||
|
||||
| Team | # | Title | Priority |
|
||||
|------|---|-------|----------|
|
||||
| ci | #854 | Generator-driven asset pipeline (epic) | high |
|
||||
| ci | #855 | systems.db regeneration with versioning awareness | high |
|
||||
| ci | #856 | Stamp systems.db with generator metadata (meta table) | high |
|
||||
| ci | #857 | Pre-push git hook for systems.db consistency | high |
|
||||
| ci | #858 | Extend /pr-push with rebase + regen + stage | high |
|
||||
| ci | #859 | Document the source-canonical rule | medium |
|
||||
| ci | #723 | Add decision-to-ticket coverage report | medium |
|
||||
| server | #853 | Generator-patch follow-up: dedup, mountains, suffix, compass | medium |
|
||||
| server | #860 | Resolve 21 raw-commodity / system coverage gate gaps | medium |
|
||||
| server | #863 | Wire SelectedBookmark into SaveState | medium |
|
||||
| server | #874 | Drop PROTOCOL_VERSION on server (D-192) | medium |
|
||||
| server | #877 | Remove HeritageRoot type alias and Heritage variant (D-167) | medium |
|
||||
| server | #878 | Audit and purge dead smuggler/detective enum (D-032) | medium |
|
||||
| server | #789 | Storyteller activation_pass log should be DEBUG not WARN | low |
|
||||
| server | #847 | Determinism smoke test for generate_atlas.py | low |
|
||||
| server | #862 | Refactor BookmarkPlugin to accept injected registry | low |
|
||||
| client | #866 | dialogue_box _escape_bbcode chained replace corrupts [lb] | high |
|
||||
| client | #869 | Fix MetaScreen test helper regression — anti_tedium (7 fails) | high |
|
||||
| client | #872 | New Game flow hangs on 'connecting' | high |
|
||||
| client | #873 | Scene-level merge-path UI flow tests (gdUnit4) | high |
|
||||
| client | #870 | Delete or revive 8 parse-error test files | medium |
|
||||
| client | #875 | Drop PROTOCOL_VERSION on client (D-192) | medium |
|
||||
| copy | #861 | Author 112 brand corp wiki stubs to three-layer depth | medium |
|
||||
| copy | #865 | Purge remaining v0.1 Sova/Van Maanen's residue from wiki | medium |
|
||||
| copy | #876 | decide(content): Commission formal name (Q-095) | medium |
|
||||
|
||||
**Total: 25 tickets across 4 teams.**
|
||||
|
||||
## Cross-Team Dependencies
|
||||
|
||||
```
|
||||
server #874 (PROTOCOL_VERSION drop) → client #875
|
||||
copy #876 (Commission name) → copy #865 (faction files use resolved name)
|
||||
ci #855 → #856 → #857, #858, #859 (asset pipeline chain)
|
||||
```
|
||||
|
||||
## Sprint Completion Criteria
|
||||
|
||||
The sprint is done when all of the following are true:
|
||||
|
||||
1. `make economy-db` passes end-to-end with no coverage gate failures (#860 done).
|
||||
2. `make game` → New Game → character creation completes without hanging (#872 done).
|
||||
3. Scene-level gdUnit4 tests exist for all four merge-path flows and pass headless (#873 done).
|
||||
4. `server/src/bridge/types.rs` contains no `PROTOCOL_VERSION` constant and no `version` field in the snapshot envelope (#874 done).
|
||||
5. `client/scripts/protocol/protocol.gd` contains no version-mismatch guard (#875 done, after #874).
|
||||
6. `server/src/simulation/generator.rs` contains no `HeritageRoot` type alias and no `Heritage` enum variant (#877 done).
|
||||
7. `server/data/systems.db` carries a `meta` table with `schema_version`, `generator_sha`, `generated_at` (#856 done).
|
||||
8. `git push` on a branch with a stale systems.db is rejected by the pre-push hook (#857 done).
|
||||
9. `.claude/rules/asset-pipeline.md` exists and is referenced from `CLAUDE.md` (#859 done).
|
||||
10. All 112 new brand corp wiki pages are ≥95 lines with three-layer content (#861 done).
|
||||
11. Q-095 is resolved: a D-record exists for the Commission formal name (#876 done).
|
||||
12. `tooling/db/ticket list --sprint 37` shows all 25 tickets as `done`.
|
||||
@@ -0,0 +1,102 @@
|
||||
# Sprint 37: Sweep — Server Tasks
|
||||
|
||||
**Goal:** Spring-clean accumulated debt: asset pipeline discipline, PROTOCOL_VERSION removal, D-167/D-032 dead-code purge, New Game regression fix, copy wiki residue, bookmark save-state, and generator quality patches.
|
||||
|
||||
**Branch:** `sprint-37/server`
|
||||
**Agents:** Dudley (dev), Tyre (arch), Hoshe (QA)
|
||||
|
||||
## New Tickets
|
||||
|
||||
| # | Title | Priority | Blocked by |
|
||||
|---|-------|----------|------------|
|
||||
| #863 | Wire SelectedBookmark into SaveState | medium | — |
|
||||
| #874 | Drop PROTOCOL_VERSION on server (D-192) | medium | — |
|
||||
| #853 | Generator-patch follow-up: dedup, mountains, suffix, compass | medium | — |
|
||||
| #860 | Resolve 21 raw-commodity / system coverage gate gaps | medium | — |
|
||||
| #877 | Remove HeritageRoot type alias and Heritage enum variant (D-167) | medium | — |
|
||||
| #878 | Audit and purge dead smuggler/detective character enum (D-032) | medium | — |
|
||||
| #847 | Determinism smoke test for generate_atlas.py | low | — |
|
||||
| #789 | fix(simulation): storyteller activation_pass log DEBUG not WARN | low | — |
|
||||
| #862 | Refactor BookmarkPlugin to accept injected registry | low | — |
|
||||
|
||||
Use `tooling/db/ticket show <id>` for full details.
|
||||
|
||||
## Key Decisions
|
||||
|
||||
- `decisions/architecture.md` — D-192 (drop PROTOCOL_VERSION lockstep handshake), D-005 (IPC protocol)
|
||||
- `decisions/content.md` — D-167 (corridors replace heritage roots, 2026-03-24)
|
||||
- `decisions/perception.md` — D-032 (smuggler/detective enum obsolete post-D-117; D-121 culture-driven voice)
|
||||
|
||||
## Notes
|
||||
|
||||
**#863 — Wire SelectedBookmark into SaveState**
|
||||
- Add `Serialize`, `Deserialize` derives to `SelectedBookmark` in `server/src/bookmark/mod.rs`.
|
||||
- Register `SelectedBookmark` as a serializable resource in `server/src/simulation/save_state.rs`.
|
||||
- Round-trip test: save with bookmark selected → load → `SelectedBookmark` survives.
|
||||
- Update bookmark spec §4.4 (`docs/architecture/sprint-36-bookmark-spec.md`) — remove the v0.2-deferred scope note.
|
||||
- Replaces inline TODO at `server/src/bookmark/mod.rs:95-99`.
|
||||
|
||||
**#874 — Drop PROTOCOL_VERSION on server (D-192)**
|
||||
- Remove: `version` field from snapshot envelope in `server/src/bridge/types.rs`, `PROTOCOL_VERSION` constant, and version stamp in encode path.
|
||||
- Keep all field-presence and roundtrip behavioral tests. Tautological version-literal assertions were already deleted in Sprint 36.
|
||||
- Client ticket #875 is blocked by this — server PR merges first.
|
||||
- After this lands, genuine schema drift surfaces as MessagePack missing-field errors downstream. That is the intended signal.
|
||||
|
||||
**#853 — Generator-patch follow-up**
|
||||
- Patch `tooling/planet-gen/generate_atlas.py` and `tooling/planet-gen/gemma_naming.py` for 7 systematic issues documented in `docs/design/atlas-generator-refinement-notes.md`:
|
||||
1. Cross-body city name dedup (49 collisions — 'Jade Harbor' on 20 bodies, 'Fort Iron' on 10)
|
||||
2. Cross-body mountain name dedup (186 bodies with empty names, 'Riverbend' on 39)
|
||||
3. Suffix monotony (-rant/-berg clustering)
|
||||
4. Compass-direction defaults — forbid 'Eastern X / Western Y' pattern in few-shot
|
||||
5. Cultural crossmix gap — thread corridor + cultural-history context into naming prompt
|
||||
6. River vocabulary bleeding from navigational terms (blocklist circumflex/contraflow)
|
||||
7. Unnamed infrastructure — emit `<City-A>-<City-B>` convention for roads/rail at generation time
|
||||
- Verification: re-run Paula's analysis script after patching; confirm collision counts drop.
|
||||
|
||||
**#860 — Resolve 21 coverage gate gaps**
|
||||
- `make economy-db` Phase 2 coverage gate fails on 21 raw-commodity/system gaps in tier1 corp tags. The brand layer (V-B01..V-B06) passes cleanly — this is upstream.
|
||||
- Identify the 21 specific gaps. Either backfill tier1 corp tags or relax the gate if gaps are intentional (e.g. commodity deliberately imported from outside the Reach).
|
||||
- `make economy-db` must pass end-to-end before Phase 2 demand simulation can run in anger.
|
||||
|
||||
**#877 — Remove HeritageRoot + Heritage variant (D-167)**
|
||||
- D-167 (2026-03-24) retired the 7 abstract heritage roots in favor of corridors. Two dead stubs remain:
|
||||
- `pub type HeritageRoot = String;` at `server/src/simulation/generator.rs:76`
|
||||
- `ZonePaletteModifier::Heritage(HeritageRoot)` variant at `generator.rs:369`
|
||||
- Delete the type alias, drop the enum variant, remove all Heritage modifier construction sites.
|
||||
- Verify no external consumer before deleting. Same pattern as D-192 cleanup.
|
||||
|
||||
**#878 — Audit and purge D-032 dead enum**
|
||||
- D-032 is marked "[Obsolete post-D-117: smuggler/detective eliminated. v0.2 uses culture-driven voice per D-121; this enum is unused.]"
|
||||
- Known reference sites: `server/src/bridge/types.rs`, `server/src/perception/observer/mod.rs`, `server/tests/archetype_monologue.rs`, and content schemas.
|
||||
- Audit first — some usages may be load-bearing (e.g. a wider pattern match). Remove confirmed-dead surface only. Do not mass-delete before reading each callsite.
|
||||
|
||||
**#847 — Determinism smoke test for generate_atlas.py**
|
||||
- ~60 lines of bash or pytest. Place in `tests/` consistent with project test layout.
|
||||
- Run `generate_atlas.py --body <small-body> --force --seed 42` twice; diff `markers.json` byte-for-byte.
|
||||
- Fails if output differs. Guardrail against determinism regressions in terrain analysis, city placement, A*, and naming.
|
||||
|
||||
**#789 — Storyteller log level fix**
|
||||
- `activation_pass: no Simmering triangles — holding` fires as WARN every few seconds during early gameplay when no NPC relationships have escalated. This is normal state, not an error condition.
|
||||
- Change to DEBUG or TRACE. One-line fix.
|
||||
|
||||
**#862 — BookmarkPlugin registry injection**
|
||||
- `BookmarkPlugin::build` calls `register_default_bookmarks(&mut registry)` unconditionally — no hook for a test registry.
|
||||
- Proposed: `BookmarkPlugin::new(registry)` injection. Default constructor still wires the canonical tycoon registry; injection variant is for tests and future TOML loading.
|
||||
- File: `server/src/bookmark/mod.rs:107-118`. Flagged in PR #132 review; accepted as follow-up.
|
||||
|
||||
## Dependency Chain
|
||||
|
||||
```
|
||||
#874 (server PROTOCOL_VERSION drop) → unblocks #875 (client)
|
||||
#877, #878, #789, #847, #862 → standalone, parallel
|
||||
#863, #853, #860 → standalone, parallel
|
||||
```
|
||||
|
||||
## PR Workflow
|
||||
|
||||
```bash
|
||||
tea pr create --repo jpmschweitzer/settled-reach --login schweitz \
|
||||
--title "refactor(server): sprint 37 — dead code purge, protocol cleanup, generator patches" \
|
||||
--description "body" \
|
||||
--base main --head sprint-37/server
|
||||
```
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
name: The Settled Reach
|
||||
version: 0.1.36
|
||||
version: 0.1.37
|
||||
repository: settled-reach
|
||||
|
||||
|
||||
|
||||
Generated
+1
-1
@@ -1294,7 +1294,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "settled-reach-server"
|
||||
version = "0.1.36"
|
||||
version = "0.1.37"
|
||||
dependencies = [
|
||||
"bevy_app",
|
||||
"bevy_ecs",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "settled-reach-server"
|
||||
version = "0.1.36"
|
||||
version = "0.1.37"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
|
||||
@@ -1,692 +0,0 @@
|
||||
# yaml-language-server: $schema=../../schemas/drama_module.schema.yaml
|
||||
#
|
||||
# Tier 1 Drama Module: The Smuggling Ring (v0.1)
|
||||
# The vertical slice Tier 1 module for D-027.
|
||||
#
|
||||
# NARRATIVE CORE:
|
||||
# A logistics worker (the smuggler PC, if played) is embedded in a small ring
|
||||
# smuggling unlicensed lattice components through Sova Transit District (D-037).
|
||||
# The ring is led by Voss from The Terminal. Kael Davan — a ring member and the
|
||||
# smuggler's FRIEND — is quietly trying to exit to protect his partner Naia Tamm.
|
||||
# Sera Venn (the detective's FRIEND) has noticed Kael's manifest discrepancies
|
||||
# but hasn't reported them, protecting Naia by proxy.
|
||||
#
|
||||
# DUAL-LENS EXPERIENCE:
|
||||
# Smuggler plays INSIDE the ring: manage drops, cover tracks, notice Kael going cold.
|
||||
# Detective plays OUTSIDE: cargo anomalies → follow Kael → witness secret meeting →
|
||||
# confront or protect.
|
||||
#
|
||||
# SUCCESS CRITERIA (D-027):
|
||||
# #1: 30 minutes of daily-life play before the ring activates (min_play_ticks: 2100)
|
||||
# #3: Player names Kael as an NPC they felt conflicted about
|
||||
# #4: observe→notice→follow→discover emerges from systems, not scripts
|
||||
|
||||
module_id: smuggling_ring_v0_1
|
||||
display_name: "The Smuggling Ring"
|
||||
version: "0.1"
|
||||
tier: 1
|
||||
description: >
|
||||
A small ring of logistics workers smuggling unlicensed lattice components through
|
||||
Sova Transit District. The ring's weakest link — Kael Davan — is trying to exit
|
||||
to protect his partner. The detective investigates cargo anomalies. The smuggler
|
||||
manages ring operations and navigates Kael's loyalty crisis. Neither character
|
||||
knows the other's full picture until confrontation forces it.
|
||||
|
||||
notes: >
|
||||
This module IS the vertical slice (D-027). It exercises every system at full depth:
|
||||
dual-lens NPC observation, tell progression, trust-gated dialogue, knowledge graph
|
||||
confidence accumulation, confrontation weight (D-063), walk-away consequences (D-064),
|
||||
and THE FRIEND contradiction arc (D-034). All outcome paths must feel earned.
|
||||
No outcome is "the right answer" — Kael's situation has no clean resolution.
|
||||
|
||||
dual_lens:
|
||||
smuggler: >
|
||||
You're inside the ring. Voss manages operations; you handle logistics cover.
|
||||
Kael used to be reliable. Lately he's absent, distracted, making excuses.
|
||||
The drop schedule is at risk. Do you pressure him, cover for him, or cut him?
|
||||
You don't know he's trying to get out. He doesn't know you've noticed.
|
||||
detective: >
|
||||
Cargo manifest discrepancies in The Terminal. Small, systematic, deniable.
|
||||
Your analytical lattice flags them before your conscious mind does.
|
||||
Follow the thread: discrepancy → dock worker with odd schedule → Kael Davan →
|
||||
maintenance corridors → someone he shouldn't be meeting. And then what?
|
||||
Arrest a man trying to leave a ring he never wanted to join?
|
||||
|
||||
pool:
|
||||
weight: 8
|
||||
compatible_districts:
|
||||
- sova-transit
|
||||
max_concurrent: 1
|
||||
|
||||
# ── ENTRY CONDITIONS ─────────────────────────────────────────────────────────
|
||||
# Ring activity begins after player has had time to establish routine (D-027 #1).
|
||||
# The ring is already running at game start — the module activates when the
|
||||
# storyteller decides the tension has built enough to surface.
|
||||
|
||||
entry_conditions:
|
||||
world_state:
|
||||
- type: npc_present
|
||||
role: ring-leader
|
||||
- type: npc_present
|
||||
role: ring-member-exiting
|
||||
- type: location_accessible
|
||||
location: the-terminal
|
||||
- type: location_accessible
|
||||
location: maintenance-corridors
|
||||
|
||||
activation:
|
||||
trigger: storyteller_push
|
||||
min_play_ticks: 2100 # ~35 minutes at 1 tick/second — D-027 criterion #1
|
||||
# The storyteller pushes activation when player has established presence
|
||||
# in The Terminal or The Last Shift through routine interaction.
|
||||
# Proximity trigger (maintenance-corridors) is a secondary activation path
|
||||
# if the player wanders there early.
|
||||
|
||||
# ── NPC REQUIREMENTS ─────────────────────────────────────────────────────────
|
||||
# All core roles are named (hand-authored NPCs from the vertical slice).
|
||||
# No generated NPC slots in v0.1 — the smuggling ring uses the 15 authored NPCs.
|
||||
|
||||
npc_requirements:
|
||||
- role: ring-leader
|
||||
display_hint: >
|
||||
Runs the ring from The Terminal. Logistics authority = cover.
|
||||
Never handles contraband directly. Pressure source for Kael.
|
||||
binding: named
|
||||
named_npc: "npc:voss"
|
||||
must_have_motivation: HANDLER
|
||||
|
||||
- role: ring-member-exiting
|
||||
display_hint: >
|
||||
Kael Davan. Dock worker, ring member, smuggler's FRIEND.
|
||||
Trying to exit quietly to protect Naia. This is THE FRIEND contradiction.
|
||||
Every event sequence runs through this role.
|
||||
binding: named
|
||||
named_npc: "npc:kael-davan"
|
||||
must_have_pattern: FRIEND
|
||||
must_have_motivation: TURNCOAT
|
||||
|
||||
- role: partner-uninvolved
|
||||
display_hint: >
|
||||
Naia Tamm. Kael's partner. Does not know about the ring.
|
||||
Her safety is Kael's motivation for exiting. Her ignorance is the moral weight.
|
||||
Discovery of her connection to Kael is a late-investigation revelation.
|
||||
binding: named
|
||||
named_npc: "npc:naia-tamm"
|
||||
must_have_motivation: CIVILIAN
|
||||
|
||||
- role: evidence-holder
|
||||
display_hint: >
|
||||
Sera Venn. Detective's FRIEND. Commission field tech.
|
||||
She has noticed Kael's manifest discrepancies but hasn't reported them —
|
||||
she knows Naia, and filing means Kael's arrest and Naia's exposure.
|
||||
Her silence IS the detective's investigation blocker in phase 1.
|
||||
binding: named
|
||||
named_npc: "npc:sera-venn"
|
||||
must_have_pattern: FRIEND
|
||||
must_have_motivation: WITNESS
|
||||
|
||||
- role: ring-operative
|
||||
display_hint: >
|
||||
The ring's operational member in maintenance corridors.
|
||||
Handles physical drops. Not a speaking character — observable behavior only.
|
||||
Can be the anonymous contact Kael meets.
|
||||
binding: named
|
||||
named_npc: "npc:nils-davan"
|
||||
is_optional: false
|
||||
|
||||
- role: institutional-watcher
|
||||
display_hint: >
|
||||
Maret Korr. A Commission observer embedded at The Terminal.
|
||||
Her growing attention is the external pressure that accelerates the timeline.
|
||||
She doesn't know about the ring specifically — she's tracking cargo patterns.
|
||||
binding: named
|
||||
named_npc: "npc:maret-korr"
|
||||
must_have_motivation: OPERATOR
|
||||
is_optional: true # Module runs without Maret, but with degraded tension arc
|
||||
|
||||
# ── EVENTS ───────────────────────────────────────────────────────────────────
|
||||
# Two sequences + one pool.
|
||||
# Sequence A: Kael's exit arc (the FRIEND contradiction backbone)
|
||||
# Sequence B: Investigation pressure arc (escalating discovery opportunities)
|
||||
# Pool: ambient ring activity (fires opportunistically throughout the module)
|
||||
|
||||
events:
|
||||
|
||||
sequences:
|
||||
|
||||
# SEQUENCE A: Kael's Exit Arc
|
||||
# The narrative spine. Each step makes Kael's contradiction more visible.
|
||||
# Observable to both characters, interpreted differently.
|
||||
|
||||
- sequence_id: kael_exit_arc
|
||||
label: "Kael's Exit Arc"
|
||||
description: >
|
||||
Kael Davan's progressive attempt to leave the ring.
|
||||
Tells intensify. Routine deviations appear. The secret meeting is the
|
||||
pivot point — after it fires, both characters' understanding shifts.
|
||||
steps:
|
||||
|
||||
- event_id: kael_goes_cold
|
||||
label: "Kael Goes Cold"
|
||||
description: >
|
||||
Kael starts missing social patterns he'd normally keep — fewer bar visits,
|
||||
shorter responses at The Terminal, leaving early. His tell system activates:
|
||||
the shoulder-check behavior appears. Nothing dramatic. Just absence where
|
||||
there was presence. The smuggler notices because they work together.
|
||||
The detective might notice if they've been tracking Kael's baseline.
|
||||
triggers:
|
||||
- type: ticks_since_activation
|
||||
ticks: 300 # ~5 minutes after module activates
|
||||
effects:
|
||||
- type: npc_routine_deviation
|
||||
npc_role: ring-member-exiting
|
||||
description: >
|
||||
Kael skips his usual post-shift drink at The Last Shift.
|
||||
Leaves the terminal 15 minutes early. No explanation.
|
||||
- type: tell_intensify
|
||||
npc_role: ring-member-exiting
|
||||
description: >
|
||||
Kael's shoulder-check behavior activates at The Terminal.
|
||||
Visible to any character with forward vision cone in his direction.
|
||||
sets_flag: kael_behavior_changed
|
||||
|
||||
- event_id: drop_happens_without_kael
|
||||
label: "Scheduled Drop — Kael Absent"
|
||||
description: >
|
||||
A ring drop occurs in maintenance corridor C-7. Kael was supposed
|
||||
to verify the cargo. He wasn't there. Nils covered it.
|
||||
The smuggler notices the irregularity in the paperwork.
|
||||
The detective — if watching cargo patterns — sees a manifest entry
|
||||
with no verifying signature where one is normally present.
|
||||
triggers:
|
||||
- type: ticks_since_event
|
||||
after_event: kael_goes_cold
|
||||
ticks: 450 # ~7.5 minutes after goes-cold
|
||||
effects:
|
||||
- type: fact_becomes_discoverable
|
||||
fact_id: "ring.kael_missed_verification"
|
||||
discoverable_by: any
|
||||
discovery_method: >
|
||||
Smuggler: check the cargo manifest in The Terminal office.
|
||||
Detective: analytical lattice flags unsigned verification entry.
|
||||
- type: location_state
|
||||
location: maintenance-corridors
|
||||
description: "An unsigned cargo verification entry exists in corridor C-7's log."
|
||||
sets_flag: kael_missed_drop
|
||||
|
||||
- event_id: kael_secret_meeting
|
||||
label: "Kael's Secret Meeting"
|
||||
description: >
|
||||
Kael meets an off-district contact in maintenance corridor B-7.
|
||||
This is the observable contradiction (D-034): Kael, in a restricted
|
||||
area he has no logged reason to be in, talking to someone who's
|
||||
not in any district NPC roster. His body language is tense.
|
||||
If the player is in visual range: this is the pivot moment.
|
||||
If not: the meeting happens anyway — the world doesn't wait.
|
||||
triggers:
|
||||
- type: ticks_since_event
|
||||
after_event: drop_happens_without_kael
|
||||
ticks: 600 # ~10 minutes after the dropped verification
|
||||
- type: player_proximity
|
||||
target_type: location
|
||||
target: maintenance-corridors
|
||||
radius_tiles: 12 # Player wandering near triggers the meeting early
|
||||
effects:
|
||||
- type: npc_routine_deviation
|
||||
npc_role: ring-member-exiting
|
||||
description: >
|
||||
Kael enters maintenance corridor B-7. Locked door to restricted
|
||||
supply closet. Emerges with the ring-operative 8 minutes later.
|
||||
Neither acknowledges the encounter publicly.
|
||||
- type: fact_becomes_discoverable
|
||||
fact_id: "ring.kael_unauthorized_corridor_access"
|
||||
discoverable_by: any
|
||||
discovery_method: >
|
||||
Player must be in visual range of corridor B-7.
|
||||
Or examine the corridor door access log (investigative action).
|
||||
- type: tell_intensify
|
||||
npc_role: ring-member-exiting
|
||||
description: >
|
||||
After the meeting, Kael's shoulder-check frequency doubles.
|
||||
Also: he avoids eye contact with the smuggler at The Terminal.
|
||||
sets_flag: secret_meeting_occurred
|
||||
|
||||
- event_id: kael_sends_message
|
||||
label: "Kael Sends the Message"
|
||||
description: >
|
||||
Kael sends an encrypted Meridian message to an off-district contact.
|
||||
The detective's analytical lattice can detect an anomalous outgoing
|
||||
packet from the district node — not the content, just the pattern
|
||||
(frequent, encrypted, sent from cargo bay terminals, not personal devices).
|
||||
The smuggler won't see this unless they're specifically watching Kael.
|
||||
triggers:
|
||||
- type: ticks_since_event
|
||||
after_event: kael_secret_meeting
|
||||
ticks: 200
|
||||
effects:
|
||||
- type: fact_becomes_discoverable
|
||||
fact_id: "ring.kael_unusual_meridian_activity"
|
||||
discoverable_by: detective
|
||||
discovery_method: >
|
||||
Detective's analytical lattice flags the outgoing packet pattern.
|
||||
Requires player to be in or adjacent to The Terminal cargo bay.
|
||||
sets_flag: kael_message_sent
|
||||
|
||||
- event_id: ring_leader_confronts_kael
|
||||
label: "Voss Confronts Kael"
|
||||
description: >
|
||||
Voss calls Kael into The Terminal supervisor's office.
|
||||
Closed door. Raised voices (audible only from adjacent room/position).
|
||||
Kael emerges pale. Voss emerges neutral. The smuggler can witness
|
||||
the approach/departure without hearing content. The detective can
|
||||
observe Kael's state immediately after if in The Terminal.
|
||||
This is Voss applying pressure. Kael is now visibly under strain.
|
||||
triggers:
|
||||
- type: flag_set
|
||||
flag: kael_message_sent
|
||||
- type: ticks_since_event
|
||||
after_event: kael_message_sent
|
||||
ticks: 400
|
||||
effects:
|
||||
- type: npc_routine_deviation
|
||||
npc_role: ring-leader
|
||||
description: "Voss calls Kael into the supervisor's office. Door closed."
|
||||
- type: npc_routine_deviation
|
||||
npc_role: ring-member-exiting
|
||||
description: >
|
||||
Kael emerges from the meeting looking strained. His shoulder-check
|
||||
is now constant. He takes an unscheduled break outside, alone.
|
||||
- type: tell_intensify
|
||||
npc_role: ring-member-exiting
|
||||
description: >
|
||||
Kael's contentment hits lowest observed level. He now actively avoids
|
||||
the ring-operative (Nils) in public. The disconnection is visible.
|
||||
- type: fact_becomes_discoverable
|
||||
fact_id: "ring.voss_kael_private_meeting"
|
||||
discoverable_by: any
|
||||
discovery_method: >
|
||||
Observe the meeting room door (spatial). Or ask Kael directly
|
||||
after (trust-gated dialogue unlocks "Are you alright?" option).
|
||||
sets_flag: voss_pressure_applied
|
||||
|
||||
# SEQUENCE B: Investigation Pressure Arc
|
||||
# External pressure that escalates the timeline.
|
||||
# Fires in parallel with Sequence A.
|
||||
|
||||
- sequence_id: investigation_pressure
|
||||
label: "Investigation Pressure Arc"
|
||||
description: >
|
||||
Maret Korr's institutional attention creates a closing window.
|
||||
Her growing interest is the reason the module can't stay in equilibrium forever.
|
||||
She doesn't know about the ring — she's a pattern-watcher. But patterns
|
||||
are what the detective investigates too. Their paths converge.
|
||||
steps:
|
||||
|
||||
- event_id: maret_flags_anomaly
|
||||
label: "Maret Flags the Cargo Anomaly"
|
||||
description: >
|
||||
Maret Korr files an internal Commission note flagging The Terminal's
|
||||
cargo variance rate as statistically unusual. Not an investigation —
|
||||
just a flag. The detective's institutional access can pull this note.
|
||||
The smuggler has no way to know it exists (unless the detective tells them).
|
||||
triggers:
|
||||
- type: ticks_since_activation
|
||||
ticks: 900 # ~15 minutes after activation
|
||||
effects:
|
||||
- type: fact_becomes_discoverable
|
||||
fact_id: "ring.commission_cargo_flag"
|
||||
discoverable_by: detective
|
||||
discovery_method: >
|
||||
Detective queries Commission data via institutional access
|
||||
(authority access tier, Terminal records).
|
||||
sets_flag: commission_flag_exists
|
||||
|
||||
- event_id: maret_increases_presence
|
||||
label: "Maret Increases Her Presence"
|
||||
description: >
|
||||
Maret starts spending more time in The Terminal. More frequent
|
||||
walkthroughs during shift changes. Her attention to the cargo bay
|
||||
area is noticeable to anyone watching. Ring members are unnerved.
|
||||
Voss starts accelerating the timeline to close operations before
|
||||
institutional attention becomes formal investigation.
|
||||
triggers:
|
||||
- type: ticks_since_event
|
||||
after_event: maret_flags_anomaly
|
||||
ticks: 600
|
||||
- type: player_action
|
||||
action: examine
|
||||
target_role: institutional-watcher
|
||||
effects:
|
||||
- type: npc_routine_deviation
|
||||
npc_role: institutional-watcher
|
||||
description: >
|
||||
Maret adds two extra Terminal walkthroughs per shift cycle.
|
||||
Spends 15 minutes studying the cargo bay manifest terminals.
|
||||
- type: tell_intensify
|
||||
npc_role: ring-leader
|
||||
description: >
|
||||
Voss becomes quieter, more deliberate. Less casual conversation.
|
||||
His tell — the stillness before speaking — becomes more frequent.
|
||||
- type: fact_becomes_discoverable
|
||||
fact_id: "ring.voss_accelerating_timeline"
|
||||
discoverable_by: any
|
||||
discovery_method: >
|
||||
Smuggler: Voss mentions "the schedule moving up" in a guarded
|
||||
conversation (trust-gated, ring-insider access required).
|
||||
Detective: observe Voss and Nils in two exchanges within same shift.
|
||||
sets_flag: timeline_accelerating
|
||||
|
||||
- event_id: final_shipment_scheduled
|
||||
label: "The Final Shipment Is Scheduled"
|
||||
description: >
|
||||
The ring schedules the last major drop — after this, they go dark.
|
||||
This is the closing window. If the detective hasn't uncovered enough
|
||||
by the time this fires, the ring disperses and the operation closes
|
||||
without exposure (escaped outcome). If they have, confrontation
|
||||
becomes unavoidable. The smuggler knows about this drop. Kael doesn't
|
||||
want to participate. Voss insists.
|
||||
triggers:
|
||||
- type: flag_set
|
||||
flag: timeline_accelerating
|
||||
- type: ticks_since_event
|
||||
after_event: maret_increases_presence
|
||||
ticks: 800
|
||||
effects:
|
||||
- type: fact_becomes_discoverable
|
||||
fact_id: "ring.final_shipment_scheduled"
|
||||
discoverable_by: any
|
||||
discovery_method: >
|
||||
Smuggler: direct notification from Voss.
|
||||
Detective: cargo manifest shows an unusual large entry for 3 days out.
|
||||
- type: npc_routine_deviation
|
||||
npc_role: ring-member-exiting
|
||||
description: >
|
||||
Kael's schedule changes: he's assigned to the cargo bay
|
||||
during the drop window. He doesn't want to be there.
|
||||
sets_flag: final_shipment_known
|
||||
|
||||
pools:
|
||||
|
||||
# POOL: Ambient ring activity — opportunistic events that add texture
|
||||
- pool_id: ambient_ring_activity
|
||||
label: "Ambient Ring Activity"
|
||||
description: >
|
||||
Low-level ring business that happens throughout the module regardless of
|
||||
player engagement. Creates the sense that the ring exists independently.
|
||||
Players who look closely will find more; players who don't still feel the world moving.
|
||||
events:
|
||||
- event_id: cargo_discrepancy_appears
|
||||
label: "Small Cargo Discrepancy Appears"
|
||||
description: >
|
||||
A minor manifest irregularity appears in The Terminal records.
|
||||
Small enough to be deniable. Systematic enough to be a pattern.
|
||||
The detective's analytical lattice may flag it. The smuggler can
|
||||
correct it if they notice it — covering tracks is part of their role.
|
||||
triggers:
|
||||
- type: ticks_since_activation
|
||||
ticks: 150 # Fires early and repeats
|
||||
effects:
|
||||
- type: fact_becomes_discoverable
|
||||
fact_id: "ring.cargo_discrepancy_pattern"
|
||||
discoverable_by: any
|
||||
discovery_method: >
|
||||
Detective: analytical lattice flags during Terminal walkthrough.
|
||||
Smuggler: check manifest terminals (or get flagged by the discrepancy
|
||||
in their own work).
|
||||
once: false # Repeats — pattern builds over time
|
||||
|
||||
- event_id: sera_avoids_torek
|
||||
label: "Sera Avoids Torek at The Bar"
|
||||
description: >
|
||||
Sera Venn reroutes her usual path through The Last Shift to avoid
|
||||
standing near Torek Lintar (the Commission enforcement officer).
|
||||
Anyone watching Sera's normal pattern would notice.
|
||||
This is the detective's first clue that Sera's behavior is odd.
|
||||
triggers:
|
||||
- type: ticks_since_activation
|
||||
ticks: 500
|
||||
effects:
|
||||
- type: npc_routine_deviation
|
||||
npc_role: evidence-holder
|
||||
description: >
|
||||
Sera takes a longer route to her usual seat, passing through
|
||||
the back of the bar to avoid Torek's sightline.
|
||||
- type: fact_becomes_discoverable
|
||||
fact_id: "ring.sera_avoidance_behavior"
|
||||
discoverable_by: detective
|
||||
discovery_method: >
|
||||
Observe Sera's path through the bar on two separate occasions.
|
||||
Requires forward vision cone and awareness of her baseline route.
|
||||
once: false
|
||||
|
||||
- event_id: nils_makes_supply_run
|
||||
label: "Nils Makes an Unscheduled Supply Run"
|
||||
description: >
|
||||
The ring-operative (Nils) enters the maintenance corridors with a
|
||||
small container logged as "calibration tools". The container isn't
|
||||
logged for return. Someone paying attention to cargo flow would notice.
|
||||
triggers:
|
||||
- type: ticks_since_activation
|
||||
ticks: 700
|
||||
effects:
|
||||
- type: npc_routine_deviation
|
||||
npc_role: ring-operative
|
||||
description: "Nils takes a container to maintenance corridor C-7."
|
||||
- type: fact_becomes_discoverable
|
||||
fact_id: "ring.nils_unlogged_cargo"
|
||||
discoverable_by: any
|
||||
discovery_method: >
|
||||
Watch Nils's cargo handling pattern over two shifts.
|
||||
Or examine maintenance corridor C-7 access log.
|
||||
once: false
|
||||
|
||||
# ── OUTCOMES ─────────────────────────────────────────────────────────────────
|
||||
# Five resolution states. Checked each tick after the first sequence step fires.
|
||||
# Order matters — the storyteller applies the first matching outcome.
|
||||
# is_terminal: true ends the module.
|
||||
|
||||
outcomes:
|
||||
|
||||
# 1. RING EXPOSED
|
||||
# Detective successfully uncovers the operation.
|
||||
# Commission becomes involved. Arrests/flight follow.
|
||||
- outcome_id: ring_exposed
|
||||
label: "Ring Exposed"
|
||||
is_terminal: true
|
||||
description: >
|
||||
The detective accumulates enough evidence to trigger a formal Commission
|
||||
inquiry. The ring collapses: arrests, flight, or both. Voss is detained.
|
||||
Kael's situation is now public. The smuggler (if played) faces consequences.
|
||||
Naia learns what Kael was doing — and why he was trying to leave.
|
||||
No clean endings. The right outcome for the detective who goes all the way.
|
||||
conditions:
|
||||
facts_known:
|
||||
- "ring.cargo_discrepancy_pattern"
|
||||
- "ring.kael_unauthorized_corridor_access"
|
||||
- "ring.voss_kael_private_meeting"
|
||||
flags_set:
|
||||
- secret_meeting_occurred # set by kael_secret_meeting event
|
||||
- commission_flag_exists # Commission was watching before exposure
|
||||
effects:
|
||||
- type: npc_disposition
|
||||
npc_role: ring-leader
|
||||
shift: hostile
|
||||
description: "Voss is detained or flees. Commission inquiry opens."
|
||||
- type: npc_disposition
|
||||
npc_role: ring-member-exiting
|
||||
shift: hostile
|
||||
description: >
|
||||
Kael is arrested or disappears. His exit attempt is now moot.
|
||||
His relationship with Naia is exposed.
|
||||
- type: faction_reaction
|
||||
faction: lattice-commission
|
||||
reaction: grateful
|
||||
description: "Commission credits the detective's investigation."
|
||||
- type: npc_exit
|
||||
npc_role: ring-leader
|
||||
description: "Voss leaves the district — detained, fled, or both."
|
||||
|
||||
# 2. KAEL ESCAPES THE RING
|
||||
# Unique path. Requires the player to engage with Kael directly
|
||||
# and choose to help him rather than expose the ring wholesale.
|
||||
- outcome_id: kael_escapes
|
||||
label: "Kael Escapes the Ring"
|
||||
is_terminal: true
|
||||
description: >
|
||||
Through the player's choices — helping Kael cover his exit, or warning him,
|
||||
or simply choosing not to act on what they know — Kael successfully leaves
|
||||
the ring before the final shipment. He and Naia leave the district quietly.
|
||||
The ring continues without him, smaller and more cautious.
|
||||
This outcome requires discovering Kael's secret AND choosing restraint.
|
||||
The smuggler can engineer this by covering for Kael with Voss.
|
||||
The detective can achieve this by confronting Kael privately rather than
|
||||
filing a report. The most morally complicated path.
|
||||
conditions:
|
||||
facts_known:
|
||||
- "ring.kael_unauthorized_corridor_access"
|
||||
flags_set:
|
||||
- kael_behavior_changed # set by kael_goes_cold — his exit arc begins here
|
||||
- secret_meeting_occurred # set by kael_secret_meeting — the pivot moment
|
||||
- voss_pressure_applied # set by ring_leader_confronts_kael — pressure applied
|
||||
# ring_exposed is checked first in the outcomes list and is terminal,
|
||||
# so kael_escapes only evaluates if ring_exposed hasn't fired.
|
||||
# No flags_not_set needed here — outcome ordering handles priority.
|
||||
effects:
|
||||
- type: npc_disposition
|
||||
npc_role: ring-member-exiting
|
||||
shift: friendly
|
||||
description: "Kael remembers whoever helped him. He's gone, but grateful."
|
||||
- type: npc_exit
|
||||
npc_role: ring-member-exiting
|
||||
description: "Kael and Naia leave Sova Transit District."
|
||||
- type: faction_reaction
|
||||
faction: the-ring
|
||||
reaction: suspicious
|
||||
description: "The ring is destabilized by Kael's exit. Voss is alert to further leaks."
|
||||
|
||||
# 3. RING COMPLETES OPERATION
|
||||
# The ring finishes the final shipment and goes dark before discovery.
|
||||
# Default path if the detective doesn't move fast enough.
|
||||
- outcome_id: ring_completes
|
||||
label: "Ring Completes the Operation"
|
||||
is_terminal: true
|
||||
description: >
|
||||
The final shipment clears. The ring disperses. Voss transfers. Nils goes quiet.
|
||||
Kael stays — he's now out by default, the ring having dissolved around him.
|
||||
The evidence trail goes cold. The detective closes the case as inconclusive.
|
||||
The smuggler completes their last run and waits to see if there's another.
|
||||
Unsatisfying only if you expected a tidy resolution. The world moved on.
|
||||
conditions:
|
||||
flags_set:
|
||||
- final_shipment_known # set by final_shipment_scheduled event
|
||||
- timeline_accelerating # set by maret_increases_presence — Maret forced their hand
|
||||
facts_not_known:
|
||||
- "ring.cargo_discrepancy_pattern" # detective never found the basic pattern — no investigation
|
||||
ticks_since_activation: 3600 # Module ran for ~60 minutes without full exposure
|
||||
# kael_message_sent was previously gated here but auto-fires at tick ~1550,
|
||||
# making this outcome permanently unreachable. Replaced with player-action fact gate.
|
||||
effects:
|
||||
- type: faction_reaction
|
||||
faction: the-ring
|
||||
reaction: neutral
|
||||
description: "The ring successfully completed this operation. They'll be back."
|
||||
- type: npc_exit
|
||||
npc_role: ring-leader
|
||||
description: "Voss transfers to another station for 'career development'."
|
||||
- type: location_access_change
|
||||
location: maintenance-corridors
|
||||
change: open
|
||||
description: "The restricted supply closet is now empty. Access log shows it cleared."
|
||||
|
||||
# 4. RING SPLINTERS
|
||||
# Partial discovery. The ring fractures but doesn't fully collapse.
|
||||
# An incomplete ending that leaves threads for future investigation.
|
||||
- outcome_id: ring_splinters
|
||||
label: "Ring Splinters"
|
||||
is_terminal: false # Not terminal — splinter state can evolve
|
||||
description: >
|
||||
Enough evidence surfaces that the ring knows it's been partially seen.
|
||||
Voss shuts down active operations. Nils disappears. Kael stays — now the
|
||||
one person in the district who knows what happened and has no one to tell.
|
||||
The formal investigation stalls for lack of a clear chain of evidence.
|
||||
The detective has facts but not the complete picture. The smuggler
|
||||
faces an awkward return to normalcy. Both know the ring isn't gone — just quiet.
|
||||
conditions:
|
||||
facts_known:
|
||||
- "ring.cargo_discrepancy_pattern" # detective found some evidence — ring responds
|
||||
events_fired:
|
||||
- kael_goes_cold # event ID — Kael's behavioral shift fired
|
||||
flags_set:
|
||||
- kael_missed_drop # set by drop_happens_without_kael — ring destabilized
|
||||
ticks_since_activation: 2400
|
||||
# Mutually exclusive with ring_completes via facts_known/facts_not_known on
|
||||
# ring.cargo_discrepancy_pattern. No auto-flag gate needed.
|
||||
effects:
|
||||
- type: npc_disposition
|
||||
npc_role: ring-leader
|
||||
shift: suspicious
|
||||
description: "Voss goes quiet. He's watching to see who knows what."
|
||||
- type: npc_exit
|
||||
npc_role: ring-operative
|
||||
description: "Nils stops appearing at The Terminal. Transferred, officially."
|
||||
- type: faction_reaction
|
||||
faction: the-ring
|
||||
reaction: suspicious
|
||||
description: "The ring is alerted to exposure risk. Future operations will be more careful."
|
||||
|
||||
# 5. INVESTIGATION STALLS (post-splinter exit)
|
||||
# The ring splinters but the detective never breaks through to the pivot evidence.
|
||||
# Explicit terminal exit for the non-terminal ring_splinters state.
|
||||
- outcome_id: ring_stalemate
|
||||
label: "Investigation Stalls"
|
||||
is_terminal: true
|
||||
description: >
|
||||
The ring went dark after the splinter. The detective has the cargo discrepancy
|
||||
on record — enough to flag, not enough to pursue. The case stays open but cold.
|
||||
No arrests. No answers. Kael stays in the district, the only person who knows
|
||||
the full shape of what happened, with no one left to tell it to.
|
||||
The ring will reconstitute elsewhere. It always does.
|
||||
conditions:
|
||||
facts_known:
|
||||
- "ring.cargo_discrepancy_pattern" # ring_splinters already fired (same gate)
|
||||
facts_not_known:
|
||||
- "ring.kael_unauthorized_corridor_access" # detective never reached the pivot evidence
|
||||
flags_set:
|
||||
- kael_missed_drop
|
||||
- final_shipment_known # ring finished while investigation stalled
|
||||
ticks_since_activation: 4500 # 2100 ticks after ring_splinters window — investigation ran cold
|
||||
effects:
|
||||
- type: faction_reaction
|
||||
faction: lattice-commission
|
||||
reaction: neutral
|
||||
description: "The discrepancy flag stays in Maret's file. No follow-up action."
|
||||
- type: npc_exit
|
||||
npc_role: ring-leader
|
||||
description: "Voss quietly transfers. No announcement, no incident report."
|
||||
|
||||
# 6. MODULE EXPIRY (quiet exit)
|
||||
# Player never engaged at all. Module times out without drama.
|
||||
# NOTE (Gestalt, Sprint 18): Condition uses facts_not_known, not flags_not_set.
|
||||
# kael_behavior_changed fires automatically at tick 300 (time-triggered), making
|
||||
# flags_not_set: [kael_behavior_changed] permanently false after tick 300.
|
||||
# Gate expiry on player-action-required facts instead.
|
||||
- outcome_id: module_abandoned
|
||||
label: "Module Abandoned"
|
||||
is_terminal: true
|
||||
is_expiry: true
|
||||
description: >
|
||||
The player never engaged with the ring's signals. The final shipment
|
||||
completed without incident. The ring disperses on its own schedule.
|
||||
Kael stays. The world is unchanged. This is not failure — it's the game
|
||||
acknowledging that not every conspiracy needs a protagonist.
|
||||
The 70% mundane majority (D-029) plays out: life continued.
|
||||
conditions:
|
||||
facts_not_known:
|
||||
- "ring.cargo_discrepancy_pattern" # Only known via player examination of terminal
|
||||
- "ring.kael_unauthorized_corridor_access" # Only known via player observing Kael in B-7
|
||||
ticks_since_activation: 5400 # ~90 minutes with zero player investigation
|
||||
effects:
|
||||
- type: faction_reaction
|
||||
faction: the-ring
|
||||
reaction: neutral
|
||||
description: "The ring closed operations without incident. No record of compromise."
|
||||
@@ -1,718 +0,0 @@
|
||||
# Drama Module Schema — Tier 1 Content (D-023)
|
||||
# YAML expression of JSON Schema 2020-12
|
||||
# Validated against this schema: server/content/modules/tier1/*.yaml
|
||||
#
|
||||
# Ownership:
|
||||
# Dramatic structure (this file): Paula
|
||||
# YAML validation tooling / serde structs: Gestalt / Tyre
|
||||
# Authoring ergonomics review: Mellanie
|
||||
#
|
||||
# See: docs/design/tier1-module-authoring.md for field-by-field guide.
|
||||
|
||||
$schema: "https://json-schema.org/draft/2020-12/schema"
|
||||
$id: "drama_module.schema.yaml"
|
||||
title: "Tier 1 Drama Module"
|
||||
description: >
|
||||
A hand-authored drama module drawn from the pool at game start.
|
||||
The storyteller activates one or more modules per playthrough based on
|
||||
entry conditions, then fires events and detects outcomes. Tier 1 modules
|
||||
are the conspiracy layer of D-023 — authored, optional, relocatable.
|
||||
type: object
|
||||
required:
|
||||
- module_id
|
||||
- display_name
|
||||
- version
|
||||
- tier
|
||||
- pool
|
||||
- entry_conditions
|
||||
- npc_requirements
|
||||
- events
|
||||
- outcomes
|
||||
additionalProperties: false
|
||||
|
||||
properties:
|
||||
|
||||
# ── IDENTITY ────────────────────────────────────────────────────────────────
|
||||
|
||||
module_id:
|
||||
type: string
|
||||
pattern: "^[a-z][a-z0-9-]*_v[0-9]+_[0-9]+$"
|
||||
description: >
|
||||
Stable unique slug. Format: {name}_v{major}_{minor}.
|
||||
Never reuse IDs. Increment version on breaking structural changes.
|
||||
Example: "smuggling_ring_v0_1"
|
||||
|
||||
display_name:
|
||||
type: string
|
||||
minLength: 1
|
||||
description: "Human-readable title shown in dev/debug tooling."
|
||||
|
||||
version:
|
||||
type: string
|
||||
pattern: "^[0-9]+\\.[0-9]+$"
|
||||
description: "Authoring version. Semantic: major.minor."
|
||||
|
||||
tier:
|
||||
type: integer
|
||||
const: 1
|
||||
description: "Always 1 for Tier 1 drama modules."
|
||||
|
||||
description:
|
||||
type: string
|
||||
description: "One-paragraph authoring summary. Not shown in-game."
|
||||
|
||||
# ── POOL METADATA ─────────────────────────────────────────────────────────
|
||||
# Controls how the storyteller includes this module in the per-playthrough pool.
|
||||
|
||||
pool:
|
||||
type: object
|
||||
required:
|
||||
- weight
|
||||
additionalProperties: false
|
||||
description: "How the storyteller samples this module from the pool."
|
||||
properties:
|
||||
weight:
|
||||
type: integer
|
||||
minimum: 1
|
||||
maximum: 10
|
||||
description: >
|
||||
Relative selection probability (1–10). Higher = more likely to be
|
||||
included in a given playthrough's active module set. Default: 5.
|
||||
compatible_districts:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
description: >
|
||||
District slugs where this module can activate, or omit for "any".
|
||||
Example: ["sova-transit"]
|
||||
incompatible_with:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
pattern: "^[a-z][a-z0-9-]*_v[0-9]+_[0-9]+$"
|
||||
description: >
|
||||
Module IDs that cannot run concurrently with this one.
|
||||
The storyteller will not activate both in the same playthrough.
|
||||
max_concurrent:
|
||||
type: integer
|
||||
minimum: 1
|
||||
default: 1
|
||||
description: >
|
||||
Maximum simultaneous active instances. Almost always 1.
|
||||
Set to 2+ only for modules designed to stack (rare).
|
||||
|
||||
# ── ENTRY CONDITIONS ──────────────────────────────────────────────────────
|
||||
# All listed conditions must be true for the module to become activatable.
|
||||
# The storyteller checks these each tick after min_play_ticks.
|
||||
|
||||
entry_conditions:
|
||||
type: object
|
||||
required:
|
||||
- activation
|
||||
additionalProperties: false
|
||||
description: >
|
||||
World-state prerequisites. The storyteller activates the module when
|
||||
ALL conditions are satisfied AND the activation trigger fires.
|
||||
properties:
|
||||
world_state:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/$defs/world_state_condition"
|
||||
description: "World-state conditions checked each tick."
|
||||
player:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/$defs/player_condition"
|
||||
description: >
|
||||
Optional player-state conditions. Module can activate without
|
||||
player engagement — these gate on player-specific world state,
|
||||
not on player noticing the module.
|
||||
activation:
|
||||
type: object
|
||||
required:
|
||||
- trigger
|
||||
additionalProperties: false
|
||||
description: "How and when activation is evaluated."
|
||||
properties:
|
||||
trigger:
|
||||
type: string
|
||||
enum:
|
||||
- proximity # Player comes within range of a key NPC/location
|
||||
- storyteller_push # Storyteller activates on its own schedule
|
||||
- player_action # Player performs a specific action
|
||||
description: "What pushes the module from 'eligible' to 'active'."
|
||||
min_play_ticks:
|
||||
type: integer
|
||||
minimum: 0
|
||||
description: >
|
||||
Minimum ticks of game time before this module can activate.
|
||||
Enforces D-027 success criterion #1: 30 minutes of daily-life
|
||||
breathing room. At 1 tick/second, 30 minutes ≈ 1800 ticks.
|
||||
proximity_location:
|
||||
type: string
|
||||
description: >
|
||||
Required when trigger = proximity. Location slug the player
|
||||
must enter or approach. Example: "maintenance-corridors"
|
||||
proximity_radius_tiles:
|
||||
type: integer
|
||||
minimum: 1
|
||||
description: >
|
||||
Required when trigger = proximity. Tile radius around the
|
||||
location's anchor point.
|
||||
player_action_required:
|
||||
type: string
|
||||
description: >
|
||||
Required when trigger = player_action. The action that fires
|
||||
activation. Example: "examine:cargo-manifest"
|
||||
|
||||
# ── NPC REQUIREMENTS ──────────────────────────────────────────────────────
|
||||
# NPC slots this module requires. Each slot is filled at module load time.
|
||||
# Named bindings resolve to specific authored NPCs; generated bindings
|
||||
# are filled from the district's generated NPC pool.
|
||||
|
||||
npc_requirements:
|
||||
type: array
|
||||
minItems: 1
|
||||
items:
|
||||
$ref: "#/$defs/npc_slot"
|
||||
description: >
|
||||
Module-internal NPC role slots. Roles are referenced by slug throughout
|
||||
the rest of this document. Hand-authored NPCs use named bindings.
|
||||
Generated NPCs use constraint-based bindings.
|
||||
|
||||
# ── EVENTS ────────────────────────────────────────────────────────────────
|
||||
# Ordered sequences and unordered event pools the storyteller can fire.
|
||||
# Sequences are narrative beats in a defined order.
|
||||
# Pools are events the storyteller can fire in any order when conditions are met.
|
||||
|
||||
events:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
description: "Event sequences and pools the storyteller manages."
|
||||
properties:
|
||||
sequences:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/$defs/event_sequence"
|
||||
description: >
|
||||
Ordered event sequences. Steps fire in order; the next step
|
||||
becomes eligible only after the previous one fires.
|
||||
pools:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/$defs/event_pool"
|
||||
description: >
|
||||
Unordered event pools. The storyteller may fire any eligible
|
||||
event in the pool when its trigger conditions are met.
|
||||
|
||||
# ── OUTCOMES ──────────────────────────────────────────────────────────────
|
||||
# Resolution states the module can reach. The storyteller checks outcome
|
||||
# conditions each tick. First matching outcome wins.
|
||||
# Every module MUST include an expiry outcome.
|
||||
|
||||
outcomes:
|
||||
type: array
|
||||
minItems: 1
|
||||
items:
|
||||
$ref: "#/$defs/outcome"
|
||||
description: >
|
||||
Terminal and transitional resolution states. The storyteller checks
|
||||
these each tick and applies the first matching outcome.
|
||||
|
||||
# ── AUTHORING NOTES ───────────────────────────────────────────────────────
|
||||
|
||||
notes:
|
||||
type: string
|
||||
description: "Authoring-only field. Design rationale, cross-references. Ignored at load time."
|
||||
|
||||
dual_lens:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
description: "Authoring-only. How smuggler vs detective experience this module."
|
||||
properties:
|
||||
smuggler: { type: string }
|
||||
detective: { type: string }
|
||||
|
||||
# ── SHARED DEFINITIONS ────────────────────────────────────────────────────────
|
||||
|
||||
$defs:
|
||||
|
||||
# World-state condition types
|
||||
|
||||
world_state_condition:
|
||||
type: object
|
||||
required:
|
||||
- type
|
||||
description: "A single world-state prerequisite for module activation."
|
||||
oneOf:
|
||||
- # NPC with the given module role is present in the district
|
||||
properties:
|
||||
type: { type: string, const: "npc_present" }
|
||||
role: { type: string, description: "Module-internal NPC role slug." }
|
||||
required: [type, role]
|
||||
additionalProperties: false
|
||||
|
||||
- # A specific location is accessible to the player
|
||||
properties:
|
||||
type: { type: string, const: "location_accessible" }
|
||||
location: { type: string, description: "Location slug." }
|
||||
required: [type, location]
|
||||
additionalProperties: false
|
||||
|
||||
- # Player has NOT yet discovered a specific fact
|
||||
properties:
|
||||
type: { type: string, const: "fact_not_known" }
|
||||
fact_id: { type: string, description: "Fact ID from global/knowledge/." }
|
||||
required: [type, fact_id]
|
||||
additionalProperties: false
|
||||
|
||||
- # No other Tier 1 module of the given ID is currently active
|
||||
properties:
|
||||
type: { type: string, const: "no_active_module" }
|
||||
module_id: { type: string }
|
||||
required: [type, module_id]
|
||||
additionalProperties: false
|
||||
|
||||
- # A named fact IS known (module requires precondition awareness)
|
||||
properties:
|
||||
type: { type: string, const: "fact_known" }
|
||||
fact_id: { type: string }
|
||||
known_by: { type: string, enum: [smuggler, detective, any] }
|
||||
required: [type, fact_id]
|
||||
additionalProperties: false
|
||||
|
||||
# Player-state condition types
|
||||
|
||||
player_condition:
|
||||
type: object
|
||||
required:
|
||||
- type
|
||||
description: "A player-state prerequisite."
|
||||
oneOf:
|
||||
- # Player has reached minimum relationship threshold with an NPC
|
||||
properties:
|
||||
type: { type: string, const: "relationship_threshold" }
|
||||
npc_role: { type: string, description: "Module-internal NPC role." }
|
||||
min_state:
|
||||
type: string
|
||||
enum: [stranger, known, friendly]
|
||||
description: "Minimum RelationshipState required."
|
||||
required: [type, npc_role, min_state]
|
||||
additionalProperties: false
|
||||
|
||||
- # Minimum game ticks elapsed
|
||||
properties:
|
||||
type: { type: string, const: "min_ticks" }
|
||||
ticks: { type: integer, minimum: 0 }
|
||||
required: [type, ticks]
|
||||
additionalProperties: false
|
||||
|
||||
# NPC slot definition
|
||||
|
||||
npc_slot:
|
||||
type: object
|
||||
required:
|
||||
- role
|
||||
- binding
|
||||
additionalProperties: false
|
||||
description: >
|
||||
One NPC slot in the module. Named binding = specific authored NPC.
|
||||
Generated binding = constraint-matched NPC from district pool.
|
||||
properties:
|
||||
role:
|
||||
type: string
|
||||
pattern: "^[a-z][a-z0-9-]*$"
|
||||
description: >
|
||||
Module-internal role slug. Referenced in events, outcomes, and
|
||||
triggers. Example: "ring-leader", "ring-member-exiting", "witness"
|
||||
display_hint:
|
||||
type: string
|
||||
description: "Authoring note. What this role is narratively."
|
||||
binding:
|
||||
type: string
|
||||
enum: [named, generated]
|
||||
description: >
|
||||
named = resolves to a specific authored NPC (use named_npc).
|
||||
generated = any district NPC matching the axis constraints.
|
||||
named_npc:
|
||||
type: string
|
||||
pattern: "^npc:[a-z][a-z0-9-]*$"
|
||||
description: >
|
||||
Required when binding = named. Short-form NPC canonical ID.
|
||||
Example: "npc:kael-davan"
|
||||
axes:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/$defs/axis_constraint"
|
||||
description: >
|
||||
Required when binding = generated. The NPC must satisfy all
|
||||
listed axis constraints to fill this slot.
|
||||
must_have_pattern:
|
||||
type: string
|
||||
enum: [FRIEND, MIRROR, ANCHOR, GHOST, CATALYST, THRESHOLD, REMNANT, SYSTEM, NOBODY]
|
||||
description: "Optional: NPC must have this pattern (D-024)."
|
||||
must_have_motivation:
|
||||
type: string
|
||||
enum: [HANDLER, WITNESS, TURNCOAT, CIVILIAN, OPERATOR, SKEPTIC]
|
||||
description: "Optional: NPC must have this motivation (D-024)."
|
||||
is_optional:
|
||||
type: boolean
|
||||
default: false
|
||||
description: >
|
||||
If true, the module can activate without this slot filled.
|
||||
Optional slots produce degraded but valid module runs.
|
||||
|
||||
# NPC axis constraint (used in generated bindings)
|
||||
|
||||
axis_constraint:
|
||||
type: object
|
||||
required:
|
||||
- axis
|
||||
- constraint
|
||||
additionalProperties: false
|
||||
properties:
|
||||
axis:
|
||||
type: string
|
||||
enum: [want, secret, relationships, tolerance, routine, information, contentment, personality, tells, skills]
|
||||
description: "Which NPC axis to constrain (D-024)."
|
||||
constraint:
|
||||
type: string
|
||||
description: >
|
||||
Constraint expression. Freeform string interpreted by the storyteller.
|
||||
Convention: "has_{value}", "min_{N}", "not_{value}".
|
||||
Examples: "has_major_secret", "min_contentment_-3", "not_combat_trained"
|
||||
|
||||
# Event sequence
|
||||
|
||||
event_sequence:
|
||||
type: object
|
||||
required:
|
||||
- sequence_id
|
||||
- steps
|
||||
additionalProperties: false
|
||||
description: "An ordered sequence of narrative events."
|
||||
properties:
|
||||
sequence_id:
|
||||
type: string
|
||||
pattern: "^[a-z][a-z0-9_-]*$"
|
||||
label:
|
||||
type: string
|
||||
description:
|
||||
type: string
|
||||
steps:
|
||||
type: array
|
||||
minItems: 1
|
||||
items:
|
||||
$ref: "#/$defs/event_step"
|
||||
|
||||
# Unordered event pool
|
||||
|
||||
event_pool:
|
||||
type: object
|
||||
required:
|
||||
- pool_id
|
||||
- events
|
||||
additionalProperties: false
|
||||
properties:
|
||||
pool_id:
|
||||
type: string
|
||||
pattern: "^[a-z][a-z0-9_-]*$"
|
||||
label:
|
||||
type: string
|
||||
description:
|
||||
type: string
|
||||
events:
|
||||
type: array
|
||||
minItems: 1
|
||||
items:
|
||||
$ref: "#/$defs/event_step"
|
||||
|
||||
# Individual event step
|
||||
|
||||
event_step:
|
||||
type: object
|
||||
required:
|
||||
- event_id
|
||||
- triggers
|
||||
additionalProperties: false
|
||||
description: "A single storyteller-managed event with triggers and effects."
|
||||
properties:
|
||||
event_id:
|
||||
type: string
|
||||
pattern: "^[a-z][a-z0-9_-]*$"
|
||||
description: "Unique within this module. Used in outcome conditions."
|
||||
label:
|
||||
type: string
|
||||
description:
|
||||
type: string
|
||||
description: "What happens narratively when this event fires."
|
||||
triggers:
|
||||
type: array
|
||||
minItems: 1
|
||||
items:
|
||||
$ref: "#/$defs/event_trigger"
|
||||
description: "ANY trigger being true fires this event."
|
||||
effects:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/$defs/event_effect"
|
||||
description: "What changes in the world when this event fires."
|
||||
once:
|
||||
type: boolean
|
||||
default: true
|
||||
description: "If true, fires only once. If false, may repeat when conditions reset."
|
||||
sets_flag:
|
||||
type: string
|
||||
pattern: "^[a-z][a-z0-9_-]*$"
|
||||
description: "Module-internal flag set when this event fires. Queryable in outcomes."
|
||||
|
||||
# Event trigger conditions
|
||||
|
||||
event_trigger:
|
||||
type: object
|
||||
required:
|
||||
- type
|
||||
description: "A condition that causes an event to fire."
|
||||
oneOf:
|
||||
- # Ticks elapsed since module activation
|
||||
properties:
|
||||
type: { type: string, const: "ticks_since_activation" }
|
||||
ticks: { type: integer, minimum: 1 }
|
||||
required: [type, ticks]
|
||||
additionalProperties: false
|
||||
|
||||
- # Ticks elapsed since a previous event fired
|
||||
properties:
|
||||
type: { type: string, const: "ticks_since_event" }
|
||||
after_event: { type: string }
|
||||
ticks: { type: integer, minimum: 1 }
|
||||
required: [type, after_event, ticks]
|
||||
additionalProperties: false
|
||||
|
||||
- # Player enters a location or comes within range of NPC
|
||||
properties:
|
||||
type: { type: string, const: "player_proximity" }
|
||||
target_type: { type: string, enum: [location, npc_role] }
|
||||
target: { type: string }
|
||||
radius_tiles: { type: integer, minimum: 1 }
|
||||
required: [type, target_type, target]
|
||||
additionalProperties: false
|
||||
|
||||
- # Player performs an interaction
|
||||
properties:
|
||||
type: { type: string, const: "player_action" }
|
||||
action:
|
||||
type: string
|
||||
enum: [talk, examine, confront, follow, observe]
|
||||
target_role: { type: string, description: "Module NPC role or location slug." }
|
||||
required: [type, action, target_role]
|
||||
additionalProperties: false
|
||||
|
||||
- # Player has discovered a specific fact
|
||||
properties:
|
||||
type: { type: string, const: "fact_known_by_player" }
|
||||
fact_id: { type: string }
|
||||
required: [type, fact_id]
|
||||
additionalProperties: false
|
||||
|
||||
- # A module flag has been set
|
||||
properties:
|
||||
type: { type: string, const: "flag_set" }
|
||||
flag: { type: string }
|
||||
required: [type, flag]
|
||||
additionalProperties: false
|
||||
|
||||
- # NPC enters a specific mood state
|
||||
properties:
|
||||
type: { type: string, const: "npc_mood" }
|
||||
npc_role: { type: string }
|
||||
mood:
|
||||
type: string
|
||||
enum: [anxious, frustrated, content, suspicious, warm, hostile, relieved, focused]
|
||||
required: [type, npc_role, mood]
|
||||
additionalProperties: false
|
||||
|
||||
# Event effects
|
||||
|
||||
event_effect:
|
||||
type: object
|
||||
required:
|
||||
- type
|
||||
description: "A world change triggered by an event."
|
||||
oneOf:
|
||||
- # NPC deviates from their normal routine
|
||||
properties:
|
||||
type: { type: string, const: "npc_routine_deviation" }
|
||||
npc_role: { type: string }
|
||||
description: { type: string, description: "What the deviation looks like." }
|
||||
duration_ticks: { type: integer }
|
||||
required: [type, npc_role, description]
|
||||
additionalProperties: false
|
||||
|
||||
- # A fact becomes discoverable (moves to Rumoured confidence)
|
||||
properties:
|
||||
type: { type: string, const: "fact_becomes_discoverable" }
|
||||
fact_id: { type: string }
|
||||
discoverable_by:
|
||||
type: string
|
||||
enum: [smuggler, detective, any]
|
||||
discovery_method:
|
||||
type: string
|
||||
description: "How the player can discover this. Authoring note."
|
||||
required: [type, fact_id, discoverable_by]
|
||||
additionalProperties: false
|
||||
|
||||
- # NPC tell behavior becomes more pronounced
|
||||
properties:
|
||||
type: { type: string, const: "tell_intensify" }
|
||||
npc_role: { type: string }
|
||||
description: { type: string }
|
||||
required: [type, npc_role]
|
||||
additionalProperties: false
|
||||
|
||||
- # A module-internal flag is set
|
||||
properties:
|
||||
type: { type: string, const: "flag_set" }
|
||||
flag: { type: string, pattern: "^[a-z][a-z0-9_-]*$" }
|
||||
required: [type, flag]
|
||||
additionalProperties: false
|
||||
|
||||
- # Something changes about a location
|
||||
properties:
|
||||
type: { type: string, const: "location_state" }
|
||||
location: { type: string }
|
||||
description: { type: string }
|
||||
required: [type, location, description]
|
||||
additionalProperties: false
|
||||
|
||||
- # NPC's access to information changes
|
||||
properties:
|
||||
type: { type: string, const: "npc_knowledge_update" }
|
||||
npc_role: { type: string }
|
||||
fact_id: { type: string }
|
||||
description: { type: string }
|
||||
required: [type, npc_role, fact_id]
|
||||
additionalProperties: false
|
||||
|
||||
# Module outcome definition
|
||||
|
||||
outcome:
|
||||
type: object
|
||||
required:
|
||||
- outcome_id
|
||||
- label
|
||||
- is_terminal
|
||||
additionalProperties: false
|
||||
description: >
|
||||
A resolution state the module can reach. Conditions are checked each tick.
|
||||
The first matching outcome is applied. is_terminal = true ends the module.
|
||||
properties:
|
||||
outcome_id:
|
||||
type: string
|
||||
pattern: "^[a-z][a-z0-9_-]*$"
|
||||
label:
|
||||
type: string
|
||||
description:
|
||||
type: string
|
||||
description: "What this outcome means narratively."
|
||||
is_terminal:
|
||||
type: boolean
|
||||
description: "If true, this outcome ends the module permanently."
|
||||
is_expiry:
|
||||
type: boolean
|
||||
default: false
|
||||
description: >
|
||||
If true, this is the quiet-exit outcome when the player never engages.
|
||||
Every module must include exactly one expiry outcome.
|
||||
conditions:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
description: "ALL conditions must be true to reach this outcome."
|
||||
properties:
|
||||
facts_known:
|
||||
type: array
|
||||
items: { type: string }
|
||||
description: "Player must know all these facts."
|
||||
facts_not_known:
|
||||
type: array
|
||||
items: { type: string }
|
||||
description: "Player must NOT know any of these facts."
|
||||
flags_set:
|
||||
type: array
|
||||
items: { type: string }
|
||||
description: "All these module flags must be set."
|
||||
flags_not_set:
|
||||
type: array
|
||||
items: { type: string }
|
||||
description: "None of these module flags may be set."
|
||||
events_fired:
|
||||
type: array
|
||||
items: { type: string }
|
||||
description: "All these events must have fired."
|
||||
ticks_since_activation:
|
||||
type: integer
|
||||
description: "Module has been active for at least this many ticks."
|
||||
effects:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/$defs/outcome_effect"
|
||||
description: "Effects applied when this outcome is reached."
|
||||
|
||||
# Outcome-level effects (broader scope than event effects)
|
||||
|
||||
outcome_effect:
|
||||
type: object
|
||||
required:
|
||||
- type
|
||||
oneOf:
|
||||
- # NPC disposition toward player changes
|
||||
properties:
|
||||
type: { type: string, const: "npc_disposition" }
|
||||
npc_role: { type: string }
|
||||
shift:
|
||||
type: string
|
||||
enum: [hostile, suspicious, neutral, friendly]
|
||||
description: { type: string }
|
||||
required: [type, npc_role, shift]
|
||||
additionalProperties: false
|
||||
|
||||
- # Faction reaction
|
||||
properties:
|
||||
type: { type: string, const: "faction_reaction" }
|
||||
faction: { type: string }
|
||||
reaction:
|
||||
type: string
|
||||
enum: [hostile, suspicious, neutral, friendly, grateful]
|
||||
description: { type: string }
|
||||
required: [type, faction, reaction]
|
||||
additionalProperties: false
|
||||
|
||||
- # Location becomes restricted or opens up
|
||||
properties:
|
||||
type: { type: string, const: "location_access_change" }
|
||||
location: { type: string }
|
||||
change:
|
||||
type: string
|
||||
enum: [restricted, locked, open]
|
||||
description: { type: string }
|
||||
required: [type, location, change]
|
||||
additionalProperties: false
|
||||
|
||||
- # A fact is now permanently known/unknown
|
||||
properties:
|
||||
type: { type: string, const: "fact_state" }
|
||||
fact_id: { type: string }
|
||||
state:
|
||||
type: string
|
||||
enum: [known, hidden, destroyed]
|
||||
description: { type: string }
|
||||
required: [type, fact_id, state]
|
||||
additionalProperties: false
|
||||
|
||||
- # NPC leaves the district or changes role
|
||||
properties:
|
||||
type: { type: string, const: "npc_exit" }
|
||||
npc_role: { type: string }
|
||||
description: { type: string }
|
||||
required: [type, npc_role]
|
||||
additionalProperties: false
|
||||
@@ -480,6 +480,23 @@ CREATE INDEX IF NOT EXISTS idx_corps_type ON corporations(corp_type);
|
||||
CREATE INDEX IF NOT EXISTS idx_star_systems_currency ON star_systems(currency_zone);
|
||||
CREATE INDEX IF NOT EXISTS idx_gate_links_from ON gate_links(from_system_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_gate_links_to ON gate_links(to_system_id);
|
||||
|
||||
-- Generator metadata stamp (#855, #856)
|
||||
-- One row per generator, updated on each successful non-dry-run.
|
||||
-- schema_version: SHA-1 of server/data/systems-schema.sql content at generation time
|
||||
-- generator_sha: SHA-1 of the generator source file(s) content
|
||||
-- generated_at: ISO-8601 UTC timestamp of the run
|
||||
--
|
||||
-- Used by:
|
||||
-- tooling/check-systems-db-stamp — verifies freshness before push (#857)
|
||||
-- .config/hooks/pre-push — rejects pushes with stale DB (#857)
|
||||
-- /pr-push skill — triggers make regen-db if stale (#858)
|
||||
CREATE TABLE IF NOT EXISTS meta (
|
||||
generator_name TEXT PRIMARY KEY, -- 'import_economics' | 'generate_atlas' | 'generate_brands'
|
||||
schema_version TEXT NOT NULL, -- SHA-1 hex of systems-schema.sql content
|
||||
generator_sha TEXT NOT NULL, -- SHA-1 hex of generator source file(s) content
|
||||
generated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_commodities_tier ON commodities(tier);
|
||||
CREATE INDEX IF NOT EXISTS idx_production_chains_output ON production_chains(output_commodity_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_chain_inputs_commodity ON chain_inputs(input_commodity_id);
|
||||
|
||||
Binary file not shown.
+49
-15
@@ -20,7 +20,11 @@ use crate::knowledge::{resolve_culture, CultureResolver};
|
||||
///
|
||||
/// Built once during `BookmarkPlugin::build`, read-only at runtime.
|
||||
/// `BTreeMap` for deterministic iteration (D-010 principle 4, D-041).
|
||||
#[derive(Resource, Debug, Default)]
|
||||
///
|
||||
/// `Clone` is required by `BookmarkPlugin::build` which moves the registry into
|
||||
/// the Bevy `App` via `insert_resource` while retaining the value from `self`
|
||||
/// (#862 injection pattern).
|
||||
#[derive(Resource, Debug, Default, Clone)]
|
||||
pub struct BookmarkRegistry {
|
||||
entries: BTreeMap<String, BookmarkDefinition>,
|
||||
}
|
||||
@@ -88,18 +92,15 @@ impl BookmarkRegistry {
|
||||
}
|
||||
|
||||
/// The confirmed bookmark selection for the current session.
|
||||
/// Populated when `ConfirmBookmark` is processed. `None` during the
|
||||
/// character-creation phase (before confirm) and always `None` in a
|
||||
/// fresh session.
|
||||
///
|
||||
/// **v0.2 scope: transient only.** Not serialized — save/load of
|
||||
/// `SelectedBookmark` is deferred to Sprint 37 (follow-up ticket
|
||||
/// filed alongside #614). Add `Serialize`/`Deserialize` derives and
|
||||
/// wire into `SaveState` when that ticket is claimed.
|
||||
/// Populated when `ConfirmBookmark` is processed. `None` fields during the
|
||||
/// character-creation phase (before confirm) and in a fresh session.
|
||||
///
|
||||
/// Serialized into `SaveStateV1.selected_bookmark` (#863) so that a loaded
|
||||
/// game remembers which bookmark and starting location were chosen.
|
||||
///
|
||||
/// Downstream systems (apartment generator, skill seeder) read from this resource.
|
||||
// TODO(sprint-37): serialize — see #863
|
||||
#[derive(Resource, Debug, Clone, Default)]
|
||||
#[derive(Resource, Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
|
||||
pub struct SelectedBookmark {
|
||||
pub bookmark_id: Option<String>,
|
||||
pub starting_location_id: Option<String>,
|
||||
@@ -109,14 +110,47 @@ pub struct SelectedBookmark {
|
||||
///
|
||||
/// Registers `BookmarkRegistry`, `SelectedBookmark`, and the startup system that
|
||||
/// stages the initial catalog in `SnapshotBuffer` for tick-0 delivery.
|
||||
pub struct BookmarkPlugin;
|
||||
///
|
||||
/// **Default construction** uses the canonical tycoon registry:
|
||||
/// ```ignore
|
||||
/// app.add_plugins(BookmarkPlugin::default());
|
||||
/// ```
|
||||
///
|
||||
/// **Injection** substitutes a custom registry (for tests and future TOML loading):
|
||||
/// ```ignore
|
||||
/// let mut registry = BookmarkRegistry::default();
|
||||
/// // populate ...
|
||||
/// app.add_plugins(BookmarkPlugin::new(registry));
|
||||
/// ```
|
||||
pub struct BookmarkPlugin {
|
||||
registry: BookmarkRegistry,
|
||||
}
|
||||
|
||||
impl BookmarkPlugin {
|
||||
/// Create a plugin with an injected registry.
|
||||
///
|
||||
/// Useful in tests (inject a minimal registry with fixed entries) and
|
||||
/// for future TOML loading (caller constructs the registry from disk,
|
||||
/// then hands it to the plugin).
|
||||
pub fn new(registry: BookmarkRegistry) -> Self {
|
||||
Self { registry }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for BookmarkPlugin {
|
||||
/// Default plugin pre-populates the canonical tycoon registry via
|
||||
/// `register_default_bookmarks`. Equivalent to the v0.2 behaviour before
|
||||
/// injection was introduced.
|
||||
fn default() -> Self {
|
||||
let mut registry = BookmarkRegistry::default();
|
||||
register_default_bookmarks(&mut registry);
|
||||
Self { registry }
|
||||
}
|
||||
}
|
||||
|
||||
impl Plugin for BookmarkPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
let mut registry = BookmarkRegistry::default();
|
||||
register_default_bookmarks(&mut registry);
|
||||
|
||||
app.insert_resource(registry)
|
||||
app.insert_resource(self.registry.clone())
|
||||
.init_resource::<SelectedBookmark>()
|
||||
.add_systems(Startup, prime_initial_catalog);
|
||||
|
||||
|
||||
@@ -96,17 +96,17 @@ impl SimBridge for LocalBridge {
|
||||
}
|
||||
|
||||
fn send_handshake(&self) -> Result<(), BridgeError> {
|
||||
use super::types::{HandshakeMessage, PROTOCOL_VERSION};
|
||||
let msg = HandshakeMessage {
|
||||
protocol_version: PROTOCOL_VERSION,
|
||||
};
|
||||
// D-192: HandshakeMessage carries no version. Send an empty marker so the
|
||||
// client knows to begin the startup sequence (send StartupMessage next).
|
||||
use super::types::HandshakeMessage;
|
||||
let msg = HandshakeMessage {};
|
||||
let payload = rmp_serde::to_vec_named(&msg)?;
|
||||
let mut writer = self
|
||||
.writer
|
||||
.lock()
|
||||
.map_err(|e| BridgeError::MutexPoisoned(format!("writer: {}", e)))?;
|
||||
write_framed(writer.get_mut(), &payload)?;
|
||||
tracing::info!("sent handshake: protocol_version={}", PROTOCOL_VERSION);
|
||||
tracing::info!("sent handshake");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -158,10 +158,10 @@ impl SimBridge for TcpBridge {
|
||||
}
|
||||
|
||||
fn send_handshake(&self) -> Result<(), BridgeError> {
|
||||
use super::types::{HandshakeMessage, PROTOCOL_VERSION};
|
||||
let msg = HandshakeMessage {
|
||||
protocol_version: PROTOCOL_VERSION,
|
||||
};
|
||||
// D-192: HandshakeMessage carries no version. Send an empty marker so the
|
||||
// client knows to begin the startup sequence (send StartupMessage next).
|
||||
use super::types::HandshakeMessage;
|
||||
let msg = HandshakeMessage {};
|
||||
let payload = rmp_serde::to_vec_named(&msg)?;
|
||||
let mut writer = self
|
||||
.writer
|
||||
@@ -173,7 +173,7 @@ impl SimBridge for TcpBridge {
|
||||
let result = write_framed(stream, &payload);
|
||||
stream.set_nonblocking(true).map_err(BridgeError::Io)?;
|
||||
result?;
|
||||
tracing::info!("sent handshake: protocol_version={}", PROTOCOL_VERSION);
|
||||
tracing::info!("sent handshake");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -220,7 +220,6 @@ mod tests {
|
||||
|
||||
fn make_snapshot() -> ObserverSnapshot {
|
||||
ObserverSnapshot {
|
||||
version: PROTOCOL_VERSION,
|
||||
tick: 42,
|
||||
game_time: GameTime {
|
||||
day: 0,
|
||||
@@ -427,7 +426,6 @@ mod tests {
|
||||
#[test]
|
||||
fn empty_snapshot_no_panic() {
|
||||
let snap = ObserverSnapshot {
|
||||
version: PROTOCOL_VERSION,
|
||||
tick: 0,
|
||||
game_time: GameTime {
|
||||
day: 0,
|
||||
|
||||
+27
-105
@@ -10,34 +10,24 @@ pub use crate::knowledge::types::{
|
||||
};
|
||||
pub use crate::simulation::time::{DayPhase, TickRate};
|
||||
|
||||
/// Wire protocol version for ObserverSnapshot.
|
||||
///
|
||||
/// Versioning strategy: flat struct + serde defaults for field evolution.
|
||||
/// Client and server are co-versioned (subprocess IPC per D-020), so protocol
|
||||
/// negotiation is unnecessary. Client should reject snapshots with version !=
|
||||
/// PROTOCOL_VERSION. New fields use #[serde(default)] only during the migration
|
||||
/// period, then the default is removed once both sides are updated.
|
||||
pub const PROTOCOL_VERSION: u8 = 23;
|
||||
|
||||
/// Handshake message sent as the very first framed message after connection (#555).
|
||||
/// Client reads this before entering the normal tick loop and validates
|
||||
/// `protocol_version` against its own `PROTOCOL_VERSION` constant.
|
||||
/// Client reads this before entering the normal tick loop, then sends StartupMessage.
|
||||
/// Wire format: MessagePack, same 4-byte length-prefixed framing as ObserverSnapshot.
|
||||
///
|
||||
/// No version field — D-192 dropped the lockstep version check. Client and server
|
||||
/// are always co-shipped (D-005); genuine schema drift surfaces as a downstream
|
||||
/// MessagePack missing-field error rather than an eager handshake rejection.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct HandshakeMessage {
|
||||
/// Must match client's PROTOCOL_VERSION or the client should disconnect.
|
||||
pub protocol_version: u8,
|
||||
}
|
||||
pub struct HandshakeMessage {}
|
||||
|
||||
/// Startup message sent by the client after receiving HandshakeMessage (#175).
|
||||
/// Contains the world seed for deterministic simulation (D-010, D-029).
|
||||
///
|
||||
/// Protocol flow:
|
||||
/// Protocol flow (D-192: no version field, no validation step):
|
||||
/// 1. Server sends HandshakeMessage (server → client)
|
||||
/// 2. Client validates protocol_version
|
||||
/// 3. Client sends StartupMessage (client → server)
|
||||
/// 4. Server reads world_seed, initializes SimRng
|
||||
/// 5. Normal tick loop begins
|
||||
/// 2. Client sends StartupMessage (client → server)
|
||||
/// 3. Server reads world_seed, initializes SimRng
|
||||
/// 4. Normal tick loop begins
|
||||
///
|
||||
/// Wire format: MessagePack, same 4-byte length-prefixed framing.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
@@ -46,12 +36,6 @@ pub struct StartupMessage {
|
||||
/// Generated by SessionManager.new_game() on the client.
|
||||
/// Same seed → same EntanglementConfig → same NPC population (D-029).
|
||||
pub world_seed: u64,
|
||||
/// Character archetype selected by the player (#587).
|
||||
/// Gates monologue pool selection, verb labels, and examine text.
|
||||
/// Defaults to Detective for backward compatibility (old clients
|
||||
/// that omit this field).
|
||||
#[serde(default)]
|
||||
pub character_archetype: CharacterArchetype,
|
||||
}
|
||||
|
||||
/// The ONLY data structure crossing the client-server boundary (D-020)
|
||||
@@ -79,18 +63,25 @@ pub struct StartupMessage {
|
||||
/// v17 adds: state_hash (#85, desync detection — fast hash of player pos + NPC count + tick),
|
||||
/// sim_errors (#85, structured error reporting to client).
|
||||
/// v18 adds: debug_response (#580, debug console server — command/response wire).
|
||||
/// v19 adds: character_archetype on StartupMessage (#587), current_ticker (#591).
|
||||
/// v19 adds: current_ticker (#591). (character_archetype on StartupMessage was
|
||||
/// added in #587 and removed in Sprint 37 — see "Sprint 37 wire-format shifts" below.)
|
||||
/// v20 adds: settings_response (#627, SQLite settings IPC).
|
||||
/// v21 adds: economy_snapshot (#822, D-181 7-signal snapshot per queried system),
|
||||
/// EconStateQuery PlayerAction variant (#822).
|
||||
/// v22 adds: bookmark_catalog (#614, D-115/D-117 CK3-style bookmark system),
|
||||
/// RequestBookmarkCatalog + ConfirmBookmark PlayerAction variants (#614).
|
||||
/// v23 removes: conversation_events, conversation_ended (D-078 scrapped per R-012).
|
||||
/// Sprint 37 wire-format shifts (no snapshot-version bump needed — PROTOCOL_VERSION lockstep gone):
|
||||
/// - D-192 (#874): `PROTOCOL_VERSION` field removed from `HandshakeMessage`. The
|
||||
/// handshake is now an empty marker ("server ready"); there is no negotiated
|
||||
/// version field on the wire. Genuine schema drift surfaces as MessagePack
|
||||
/// missing-field errors downstream — that is the intended signal per D-192.
|
||||
/// - #878 (cascade cleanup): `character_archetype` field removed from
|
||||
/// `StartupMessage`. This protocol break rides the D-192 drop.
|
||||
///
|
||||
/// Future fields: ambient sound events, HUD state (D-020 expansion).
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ObserverSnapshot {
|
||||
/// Protocol version for forward compatibility. See [`PROTOCOL_VERSION`].
|
||||
pub version: u8,
|
||||
/// Simulation tick when this snapshot was produced
|
||||
pub tick: u64,
|
||||
/// Game time data for client HUD display (D-031)
|
||||
@@ -495,28 +486,6 @@ pub enum ObjectType {
|
||||
Furniture,
|
||||
}
|
||||
|
||||
/// Character archetype for Phase 2 verb filtering (#422) and monologue pool
|
||||
/// selection. Determines how the character perceives and labels interactions.
|
||||
/// v0.1: Smuggler and Detective (the two playable characters).
|
||||
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
|
||||
pub enum CharacterArchetype {
|
||||
/// Smuggler character — sees Move/Stash on containers, physical manipulation verbs
|
||||
Smuggler,
|
||||
/// Detective character — sees Scan/Flag on containers, investigation verbs
|
||||
#[default]
|
||||
Detective,
|
||||
}
|
||||
|
||||
impl CharacterArchetype {
|
||||
/// String key for monologue pool filtering (#587).
|
||||
pub fn as_monologue_key(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Smuggler => "smuggler",
|
||||
Self::Detective => "detective",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Semantic player actions, not raw key events (D-020)
|
||||
/// Timestamped for deterministic processing
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -1105,73 +1074,28 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn handshake_message_roundtrip() {
|
||||
let msg = HandshakeMessage {
|
||||
protocol_version: PROTOCOL_VERSION,
|
||||
};
|
||||
// D-192: HandshakeMessage carries no version field; roundtrip verifies
|
||||
// the empty struct serialises and deserialises cleanly.
|
||||
let msg = HandshakeMessage {};
|
||||
let bytes = rmp_serde::to_vec_named(&msg).expect("serialize");
|
||||
let decoded: HandshakeMessage = rmp_serde::from_slice(&bytes).expect("deserialize");
|
||||
assert_eq!(decoded, msg);
|
||||
assert_eq!(decoded.protocol_version, PROTOCOL_VERSION);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handshake_message_rejects_wrong_version() {
|
||||
let msg = HandshakeMessage {
|
||||
protocol_version: PROTOCOL_VERSION,
|
||||
};
|
||||
let bytes = rmp_serde::to_vec_named(&msg).expect("serialize");
|
||||
let decoded: HandshakeMessage = rmp_serde::from_slice(&bytes).expect("deserialize");
|
||||
// Simulate client-side validation: version mismatch should be detectable
|
||||
let wrong_version = PROTOCOL_VERSION.wrapping_add(1);
|
||||
assert_ne!(decoded.protocol_version, wrong_version);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_message_roundtrip() {
|
||||
let msg = StartupMessage {
|
||||
world_seed: 0xDEADBEEF,
|
||||
character_archetype: CharacterArchetype::Detective,
|
||||
};
|
||||
let bytes = rmp_serde::to_vec_named(&msg).expect("serialize");
|
||||
let decoded: StartupMessage = rmp_serde::from_slice(&bytes).expect("deserialize");
|
||||
assert_eq!(decoded, msg);
|
||||
assert_eq!(decoded.world_seed, 0xDEADBEEF);
|
||||
assert_eq!(decoded.character_archetype, CharacterArchetype::Detective);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_message_smuggler_roundtrip() {
|
||||
let msg = StartupMessage {
|
||||
world_seed: 42,
|
||||
character_archetype: CharacterArchetype::Smuggler,
|
||||
};
|
||||
let bytes = rmp_serde::to_vec_named(&msg).expect("serialize");
|
||||
let decoded: StartupMessage = rmp_serde::from_slice(&bytes).expect("deserialize");
|
||||
assert_eq!(decoded, msg);
|
||||
assert_eq!(decoded.character_archetype, CharacterArchetype::Smuggler);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_message_missing_archetype_defaults_to_detective() {
|
||||
// Simulate an old client that sends only world_seed (no character_archetype).
|
||||
// serde(default) on StartupMessage.character_archetype should default to Detective.
|
||||
#[derive(Serialize)]
|
||||
struct OldStartupMessage {
|
||||
world_seed: u64,
|
||||
}
|
||||
let old = OldStartupMessage { world_seed: 99 };
|
||||
let bytes = rmp_serde::to_vec_named(&old).expect("serialize");
|
||||
let decoded: StartupMessage = rmp_serde::from_slice(&bytes).expect("deserialize");
|
||||
assert_eq!(decoded.world_seed, 99);
|
||||
assert_eq!(decoded.character_archetype, CharacterArchetype::Detective);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_message_zero_seed() {
|
||||
let msg = StartupMessage {
|
||||
world_seed: 0,
|
||||
character_archetype: CharacterArchetype::default(),
|
||||
};
|
||||
let msg = StartupMessage { world_seed: 0 };
|
||||
let bytes = rmp_serde::to_vec_named(&msg).expect("serialize");
|
||||
let decoded: StartupMessage = rmp_serde::from_slice(&bytes).expect("deserialize");
|
||||
assert_eq!(decoded.world_seed, 0);
|
||||
@@ -1181,7 +1105,6 @@ mod tests {
|
||||
fn startup_message_max_seed() {
|
||||
let msg = StartupMessage {
|
||||
world_seed: u64::MAX,
|
||||
character_archetype: CharacterArchetype::default(),
|
||||
};
|
||||
let bytes = rmp_serde::to_vec_named(&msg).expect("serialize");
|
||||
let decoded: StartupMessage = rmp_serde::from_slice(&bytes).expect("deserialize");
|
||||
@@ -1191,10 +1114,9 @@ mod tests {
|
||||
#[test]
|
||||
fn handshake_is_distinct_from_snapshot() {
|
||||
// HandshakeMessage and ObserverSnapshot are different types on the wire.
|
||||
// A HandshakeMessage should NOT deserialize as an ObserverSnapshot.
|
||||
let msg = HandshakeMessage {
|
||||
protocol_version: PROTOCOL_VERSION,
|
||||
};
|
||||
// A HandshakeMessage (empty map) must NOT deserialize as an ObserverSnapshot
|
||||
// because ObserverSnapshot has required fields (tick, game_time, etc.).
|
||||
let msg = HandshakeMessage {};
|
||||
let bytes = rmp_serde::to_vec_named(&msg).expect("serialize");
|
||||
let result = rmp_serde::from_slice::<ObserverSnapshot>(&bytes);
|
||||
assert!(
|
||||
|
||||
+9
-28
@@ -153,7 +153,7 @@ fn main() {
|
||||
app.add_plugins(settled_reach_server::npc::NpcPlugin);
|
||||
app.add_plugins(settled_reach_server::storyteller::StorytellerPlugin);
|
||||
app.add_plugins(settled_reach_server::settings::SettingsPlugin);
|
||||
app.add_plugins(settled_reach_server::bookmark::BookmarkPlugin);
|
||||
app.add_plugins(settled_reach_server::bookmark::BookmarkPlugin::default());
|
||||
|
||||
// Initialize culture resolver (#679, D-128).
|
||||
// systems.db is shipped read-only alongside the binary.
|
||||
@@ -216,20 +216,17 @@ fn main() {
|
||||
),
|
||||
);
|
||||
|
||||
// Character archetype from client's StartupMessage (#587).
|
||||
let archetype = startup.character_archetype;
|
||||
|
||||
// Gauntlet test world for --test-mode, proof room for normal mode.
|
||||
if test_mode {
|
||||
#[cfg(feature = "gauntlet")]
|
||||
settled_reach_server::test_world::setup_gauntlet(&mut app, archetype);
|
||||
settled_reach_server::test_world::setup_gauntlet(&mut app);
|
||||
#[cfg(not(feature = "gauntlet"))]
|
||||
{
|
||||
eprintln!("--test-mode requires the 'gauntlet' feature");
|
||||
std::process::exit(1);
|
||||
}
|
||||
} else {
|
||||
setup_proof_room(&mut app, archetype, seed);
|
||||
setup_proof_room(&mut app, seed);
|
||||
}
|
||||
|
||||
tracing::info!(
|
||||
@@ -325,7 +322,6 @@ fn send_panic_error(app: &App, panic_msg: &str) {
|
||||
|
||||
// Build a minimal snapshot carrying the panic error
|
||||
let snapshot = ObserverSnapshot {
|
||||
version: PROTOCOL_VERSION,
|
||||
tick,
|
||||
game_time: GameTime {
|
||||
day: 0,
|
||||
@@ -394,7 +390,7 @@ fn dump_schedule_graph() {
|
||||
app.add_plugins(settled_reach_server::npc::NpcPlugin);
|
||||
app.add_plugins(settled_reach_server::storyteller::StorytellerPlugin);
|
||||
app.add_plugins(settled_reach_server::settings::SettingsPlugin);
|
||||
app.add_plugins(settled_reach_server::bookmark::BookmarkPlugin);
|
||||
app.add_plugins(settled_reach_server::bookmark::BookmarkPlugin::default());
|
||||
app.insert_resource(settled_reach_server::simulation::rng::SimRng::new(0));
|
||||
|
||||
// Access Schedules resource directly — schedules are populated by plugins
|
||||
@@ -422,11 +418,7 @@ fn dump_schedule_graph() {
|
||||
|
||||
/// Proof room: 32x32 map, wall at (16,14), player at (16,16), 3 NPCs.
|
||||
/// Extracted from the original inline setup for reuse by both test-mode and normal mode.
|
||||
fn setup_proof_room(
|
||||
app: &mut App,
|
||||
archetype: settled_reach_server::bridge::types::CharacterArchetype,
|
||||
world_seed: u64,
|
||||
) {
|
||||
fn setup_proof_room(app: &mut App, world_seed: u64) {
|
||||
use settled_reach_server::knowledge::registry::EntityRegistry;
|
||||
use settled_reach_server::knowledge::KnowledgeGraph;
|
||||
use settled_reach_server::npc::relationships::{RelationshipEdge, RelationshipGraph};
|
||||
@@ -459,19 +451,9 @@ fn setup_proof_room(
|
||||
|
||||
let mut registry = EntityRegistry::new(0);
|
||||
|
||||
// Player at (16,16) — archetype from StartupMessage (#587, D-053)
|
||||
let profile = match archetype {
|
||||
settled_reach_server::bridge::types::CharacterArchetype::Smuggler => {
|
||||
MovementProfile::smuggler()
|
||||
}
|
||||
settled_reach_server::bridge::types::CharacterArchetype::Detective => {
|
||||
MovementProfile::detective()
|
||||
}
|
||||
};
|
||||
let monologue_state = MonologueState {
|
||||
character: archetype.as_monologue_key().to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
// Player at (16,16). Archetype-specific spawn logic was removed in Sprint 37
|
||||
// (D-032 purge); per-culture/per-role voice is reintroduced in Phase 6.
|
||||
let profile = MovementProfile::default();
|
||||
let player = app
|
||||
.world_mut()
|
||||
.spawn((
|
||||
@@ -480,12 +462,11 @@ fn setup_proof_room(
|
||||
Facing::default(),
|
||||
KnowledgeGraph::new(),
|
||||
NearbyInteractionBuffer::default(),
|
||||
monologue_state,
|
||||
MonologueState::default(),
|
||||
MonologueBuffer::default(),
|
||||
SprintAnomalyQueue::default(),
|
||||
CognitiveDelay::default(),
|
||||
ListeningFocus::new(TilePosition::new(16, 16, 0)),
|
||||
archetype,
|
||||
profile,
|
||||
profile.initial_stance(),
|
||||
PlayerMoveCooldown::default(),
|
||||
|
||||
@@ -78,7 +78,6 @@ pub fn compute_observer_snapshot(
|
||||
&mut NearbyInteractionBuffer,
|
||||
&mut MonologueBuffer,
|
||||
Option<&Stance>,
|
||||
Option<&CharacterArchetype>,
|
||||
Option<&mut SprintAnomalyQueue>,
|
||||
Option<&CognitiveDelay>,
|
||||
Option<&mut DialogueResponseBuffer>,
|
||||
@@ -114,7 +113,6 @@ pub fn compute_observer_snapshot(
|
||||
mut interaction_buffer,
|
||||
mut monologue_buffer,
|
||||
stance_opt,
|
||||
archetype_opt,
|
||||
mut anomaly_queue_opt,
|
||||
cognitive_delay_opt,
|
||||
mut dialogue_response_opt,
|
||||
@@ -135,8 +133,6 @@ pub fn compute_observer_snapshot(
|
||||
.map(|f| f.0)
|
||||
.unwrap_or(FacingDirection::default());
|
||||
|
||||
let archetype = archetype_opt.copied().unwrap_or_default();
|
||||
|
||||
// Collect player inventory (D-065 info boundary: only own items)
|
||||
let player_inventory = registry
|
||||
.to_stable(observer_entity)
|
||||
@@ -197,7 +193,7 @@ pub fn compute_observer_snapshot(
|
||||
|
||||
// Take interactions and apply Phase 2 verb filter (D-057, #422)
|
||||
let mut nearby_interactions = interaction_buffer.take();
|
||||
apply_phase2_verb_filter(&mut nearby_interactions, observer_kg, archetype);
|
||||
apply_phase2_verb_filter(&mut nearby_interactions, observer_kg);
|
||||
|
||||
tracing::trace!(
|
||||
"compute_observer_snapshot: tick={}, visible={}, remembered={}, tiles={}",
|
||||
@@ -453,7 +449,6 @@ pub fn compute_observer_snapshot(
|
||||
};
|
||||
|
||||
buffer.snapshot = Some(ObserverSnapshot {
|
||||
version: crate::bridge::types::PROTOCOL_VERSION,
|
||||
tick: time.tick,
|
||||
game_time,
|
||||
player_facing: facing,
|
||||
@@ -654,17 +649,12 @@ fn collect_remembered_entities(
|
||||
/// 1. POI priority flips (D-060) — ExamineNpc above Talk for POI entities
|
||||
/// 2. Confront injection — adds Confront verb for NPCs when KnowsDetails+
|
||||
/// 3. Contradiction marking — sets contradicted flag when entity knowledge is Contradicted
|
||||
/// 4. Archetype label relabeling — smuggler/detective see different labels for same verb
|
||||
///
|
||||
/// Phase boundary: Phase 1 (interaction.rs) determines verb availability from
|
||||
/// ObjectType + proximity. Phase 2 (here) reads the observer's KnowledgeGraph
|
||||
/// to filter, augment, and relabel. This separation keeps D-010 principle 1
|
||||
/// (info boundary) clean — simulation doesn't know what the observer knows.
|
||||
fn apply_phase2_verb_filter(
|
||||
interactions: &mut [NearbyInteraction],
|
||||
observer_kg: &KnowledgeGraph,
|
||||
archetype: CharacterArchetype,
|
||||
) {
|
||||
fn apply_phase2_verb_filter(interactions: &mut [NearbyInteraction], observer_kg: &KnowledgeGraph) {
|
||||
for interaction in interactions.iter_mut() {
|
||||
let stable_id = StableId(interaction.entity_id);
|
||||
let knowledge = observer_kg.entity_knowledge(&stable_id);
|
||||
@@ -713,18 +703,6 @@ fn apply_phase2_verb_filter(
|
||||
}
|
||||
}
|
||||
|
||||
// --- Archetype label relabeling ---
|
||||
// Phase 2 swaps verb labels based on character archetype.
|
||||
// The VerbKind stays the same (same handler), only the display label changes.
|
||||
// This implements D-057: "Character differentiation via Phase 2 observer
|
||||
// filter, not separate verb systems."
|
||||
for verb in &mut interaction.verbs {
|
||||
if let Some(label) = archetype_verb_label(archetype, interaction.object_type, verb.kind)
|
||||
{
|
||||
verb.label = label.into();
|
||||
}
|
||||
}
|
||||
|
||||
// Re-sort after priority changes and verb additions
|
||||
interaction
|
||||
.verbs
|
||||
@@ -732,37 +710,5 @@ fn apply_phase2_verb_filter(
|
||||
}
|
||||
}
|
||||
|
||||
/// Archetype-specific verb label overrides (#422, D-057).
|
||||
///
|
||||
/// Returns a replacement label for the given (archetype, object_type, verb_kind)
|
||||
/// combination, or None to keep the Phase 1 default label.
|
||||
///
|
||||
/// v0.1: Container verbs differ by archetype. Other object types keep defaults.
|
||||
/// Add match arms here for future archetype-specific labels.
|
||||
fn archetype_verb_label(
|
||||
archetype: CharacterArchetype,
|
||||
object_type: Option<ObjectType>,
|
||||
kind: VerbKind,
|
||||
) -> Option<&'static str> {
|
||||
match (archetype, object_type, kind) {
|
||||
// Smuggler: Container verbs — physical manipulation vocabulary
|
||||
(CharacterArchetype::Smuggler, Some(ObjectType::Container), VerbKind::Open) => Some("Move"),
|
||||
(CharacterArchetype::Smuggler, Some(ObjectType::Container), VerbKind::Search) => {
|
||||
Some("Stash")
|
||||
}
|
||||
|
||||
// Detective: Container verbs — investigation vocabulary
|
||||
(CharacterArchetype::Detective, Some(ObjectType::Container), VerbKind::Open) => {
|
||||
Some("Scan")
|
||||
}
|
||||
(CharacterArchetype::Detective, Some(ObjectType::Container), VerbKind::Search) => {
|
||||
Some("Flag")
|
||||
}
|
||||
|
||||
// All other combinations: keep Phase 1 default label
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -59,7 +59,6 @@ fn player_always_visible_in_snapshot() {
|
||||
|
||||
let buffer = world.resource::<SnapshotBuffer>();
|
||||
let snapshot = buffer.snapshot.as_ref().expect("snapshot should exist");
|
||||
assert_eq!(snapshot.version, PROTOCOL_VERSION);
|
||||
assert_eq!(snapshot.entities.len(), 1);
|
||||
assert!(matches!(snapshot.entities[0].kind, EntityKind::Player));
|
||||
assert_eq!(snapshot.entities[0].observation, EntityVisibility::Visible);
|
||||
@@ -679,10 +678,6 @@ fn snapshot_v6_fields_default_through_pipeline() {
|
||||
let buffer = world.resource::<SnapshotBuffer>();
|
||||
let snapshot = buffer.snapshot.as_ref().expect("snapshot should exist");
|
||||
|
||||
assert_eq!(
|
||||
snapshot.version, PROTOCOL_VERSION,
|
||||
"should be current protocol version"
|
||||
);
|
||||
assert_eq!(
|
||||
snapshot.player_stance,
|
||||
MovementStance::Walk,
|
||||
@@ -694,29 +689,6 @@ fn snapshot_v6_fields_default_through_pipeline() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_v6_version_is_protocol_version() {
|
||||
let mut world = setup_world(32, 32);
|
||||
world.spawn((
|
||||
PlayerCharacter,
|
||||
TilePosition::new(16, 16, 0),
|
||||
Facing::default(),
|
||||
KnowledgeGraph::new(),
|
||||
NearbyInteractionBuffer::default(),
|
||||
MonologueBuffer::default(),
|
||||
));
|
||||
|
||||
run_observer_pipeline(&mut world);
|
||||
|
||||
let buffer = world.resource::<SnapshotBuffer>();
|
||||
let snapshot = buffer.snapshot.as_ref().unwrap();
|
||||
assert_eq!(
|
||||
snapshot.version,
|
||||
crate::bridge::types::PROTOCOL_VERSION,
|
||||
"snapshot version must match PROTOCOL_VERSION constant"
|
||||
);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Phase 2 verb filter tests (#422, D-057)
|
||||
// -----------------------------------------------------------------------
|
||||
@@ -967,148 +939,13 @@ fn phase2_no_contradiction_for_active_knowledge() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn phase2_smuggler_relabels_container_verbs() {
|
||||
let mut world = setup_world(32, 32);
|
||||
let mut registry = EntityRegistry::new(0);
|
||||
|
||||
// Container at close range, north of player
|
||||
let container = world
|
||||
.spawn((
|
||||
TilePosition::new(16, 15, 0),
|
||||
crate::simulation::interaction::Interactable,
|
||||
ObjectType::Container,
|
||||
))
|
||||
.id();
|
||||
registry.register(container);
|
||||
|
||||
// Smuggler player
|
||||
let player = world
|
||||
.spawn((
|
||||
PlayerCharacter,
|
||||
TilePosition::new(16, 16, 0),
|
||||
Facing(FacingDirection::North),
|
||||
KnowledgeGraph::new(),
|
||||
NearbyInteractionBuffer::default(),
|
||||
MonologueBuffer::default(),
|
||||
CharacterArchetype::Smuggler,
|
||||
))
|
||||
.id();
|
||||
registry.register(player);
|
||||
world.insert_resource(registry);
|
||||
|
||||
run_full_pipeline(&mut world);
|
||||
|
||||
let buffer = world.resource::<SnapshotBuffer>();
|
||||
let snapshot = buffer.snapshot.as_ref().unwrap();
|
||||
assert_eq!(snapshot.nearby_interactions.len(), 1);
|
||||
let interaction = &snapshot.nearby_interactions[0];
|
||||
// Container at close range: Open→"Move", Search→"Stash", Observe stays "Observe"
|
||||
let open_verb = interaction.verbs.iter().find(|v| v.kind == VerbKind::Open);
|
||||
let search_verb = interaction
|
||||
.verbs
|
||||
.iter()
|
||||
.find(|v| v.kind == VerbKind::Search);
|
||||
let observe_verb = interaction
|
||||
.verbs
|
||||
.iter()
|
||||
.find(|v| v.kind == VerbKind::Observe);
|
||||
assert_eq!(open_verb.unwrap().label, "Move", "smuggler Open→Move");
|
||||
assert_eq!(search_verb.unwrap().label, "Stash", "smuggler Search→Stash");
|
||||
assert_eq!(observe_verb.unwrap().label, "Observe", "Observe unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn phase2_detective_relabels_container_verbs() {
|
||||
let mut world = setup_world(32, 32);
|
||||
let mut registry = EntityRegistry::new(0);
|
||||
|
||||
let container = world
|
||||
.spawn((
|
||||
TilePosition::new(16, 15, 0),
|
||||
crate::simulation::interaction::Interactable,
|
||||
ObjectType::Container,
|
||||
))
|
||||
.id();
|
||||
registry.register(container);
|
||||
|
||||
// Detective player (explicit)
|
||||
let player = world
|
||||
.spawn((
|
||||
PlayerCharacter,
|
||||
TilePosition::new(16, 16, 0),
|
||||
Facing(FacingDirection::North),
|
||||
KnowledgeGraph::new(),
|
||||
NearbyInteractionBuffer::default(),
|
||||
MonologueBuffer::default(),
|
||||
CharacterArchetype::Detective,
|
||||
))
|
||||
.id();
|
||||
registry.register(player);
|
||||
world.insert_resource(registry);
|
||||
|
||||
run_full_pipeline(&mut world);
|
||||
|
||||
let buffer = world.resource::<SnapshotBuffer>();
|
||||
let snapshot = buffer.snapshot.as_ref().unwrap();
|
||||
assert_eq!(snapshot.nearby_interactions.len(), 1);
|
||||
let interaction = &snapshot.nearby_interactions[0];
|
||||
let open_verb = interaction.verbs.iter().find(|v| v.kind == VerbKind::Open);
|
||||
let search_verb = interaction
|
||||
.verbs
|
||||
.iter()
|
||||
.find(|v| v.kind == VerbKind::Search);
|
||||
assert_eq!(open_verb.unwrap().label, "Scan", "detective Open→Scan");
|
||||
assert_eq!(search_verb.unwrap().label, "Flag", "detective Search→Flag");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn phase2_default_archetype_is_detective() {
|
||||
// When no CharacterArchetype component attached, defaults to Detective
|
||||
let mut world = setup_world(32, 32);
|
||||
let mut registry = EntityRegistry::new(0);
|
||||
|
||||
let container = world
|
||||
.spawn((
|
||||
TilePosition::new(16, 15, 0),
|
||||
crate::simulation::interaction::Interactable,
|
||||
ObjectType::Container,
|
||||
))
|
||||
.id();
|
||||
registry.register(container);
|
||||
|
||||
// Player WITHOUT CharacterArchetype component
|
||||
let player = world
|
||||
.spawn((
|
||||
PlayerCharacter,
|
||||
TilePosition::new(16, 16, 0),
|
||||
Facing(FacingDirection::North),
|
||||
KnowledgeGraph::new(),
|
||||
NearbyInteractionBuffer::default(),
|
||||
MonologueBuffer::default(),
|
||||
))
|
||||
.id();
|
||||
registry.register(player);
|
||||
world.insert_resource(registry);
|
||||
|
||||
run_full_pipeline(&mut world);
|
||||
|
||||
let buffer = world.resource::<SnapshotBuffer>();
|
||||
let snapshot = buffer.snapshot.as_ref().unwrap();
|
||||
assert_eq!(snapshot.nearby_interactions.len(), 1);
|
||||
let interaction = &snapshot.nearby_interactions[0];
|
||||
// Default = Detective labels
|
||||
let open_verb = interaction.verbs.iter().find(|v| v.kind == VerbKind::Open);
|
||||
assert_eq!(
|
||||
open_verb.unwrap().label,
|
||||
"Scan",
|
||||
"default archetype should use Detective labels"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn phase2_non_container_keeps_default_labels() {
|
||||
// Readable objects should keep their default labels regardless of archetype
|
||||
// Readable objects keep their Phase 1 verb labels unchanged through Phase 2.
|
||||
// Regression guard: archetype-verb differentiation is Phase 6 detail — not present
|
||||
// in the current server per the development cascade (CLAUDE.md). D-057 superseded.
|
||||
// If this test fails, a character-class relabelling branch was reintroduced before
|
||||
// Phase 6 scope is confirmed by the team lead.
|
||||
let mut world = setup_world(32, 32);
|
||||
let mut registry = EntityRegistry::new(0);
|
||||
|
||||
@@ -1129,7 +966,6 @@ fn phase2_non_container_keeps_default_labels() {
|
||||
KnowledgeGraph::new(),
|
||||
NearbyInteractionBuffer::default(),
|
||||
MonologueBuffer::default(),
|
||||
CharacterArchetype::Smuggler,
|
||||
))
|
||||
.id();
|
||||
registry.register(player);
|
||||
@@ -1145,7 +981,7 @@ fn phase2_non_container_keeps_default_labels() {
|
||||
assert_eq!(
|
||||
read_verb.unwrap().label,
|
||||
"Read",
|
||||
"Readable labels unchanged for smuggler"
|
||||
"Readable labels unchanged"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2764,3 +2600,124 @@ fn tell_state_none_when_npc_has_no_derived_tell_component() {
|
||||
"NPC without DerivedTellState component should have tell_state = None"
|
||||
);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Regression: Phase 2 container verb labels are uniform (D-057 / #878)
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn phase2_container_verb_labels_uniform_regardless_of_player_state() {
|
||||
// Regression guard (D-057 superseded, #878 cascade purge):
|
||||
// apply_phase2_verb_filter no longer has an archetype branch that relabels
|
||||
// container verbs. Labels must be the Phase-1 defaults — "Open", "Search",
|
||||
// "Observe" — regardless of the observer's KnowledgeGraph contents or
|
||||
// relationship state with other entities.
|
||||
//
|
||||
// This test FAILS if a character-class verb-label branch is reintroduced
|
||||
// without a confirmed Phase 6 scope decision from the team lead.
|
||||
|
||||
// --- Trial A: empty KnowledgeGraph ---
|
||||
{
|
||||
let mut world = setup_world(32, 32);
|
||||
let mut registry = EntityRegistry::new(0);
|
||||
|
||||
let container = world
|
||||
.spawn((
|
||||
TilePosition::new(16, 15, 0),
|
||||
crate::simulation::interaction::Interactable,
|
||||
ObjectType::Container,
|
||||
))
|
||||
.id();
|
||||
registry.register(container);
|
||||
|
||||
world.spawn((
|
||||
PlayerCharacter,
|
||||
TilePosition::new(16, 16, 0),
|
||||
Facing(FacingDirection::North),
|
||||
KnowledgeGraph::new(),
|
||||
NearbyInteractionBuffer::default(),
|
||||
MonologueBuffer::default(),
|
||||
));
|
||||
world.insert_resource(registry);
|
||||
|
||||
run_full_pipeline(&mut world);
|
||||
|
||||
let buffer = world.resource::<SnapshotBuffer>();
|
||||
let snapshot = buffer.snapshot.as_ref().unwrap();
|
||||
assert_eq!(snapshot.nearby_interactions.len(), 1);
|
||||
let labels: Vec<&str> = snapshot.nearby_interactions[0]
|
||||
.verbs
|
||||
.iter()
|
||||
.map(|v| v.label.as_str())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
labels,
|
||||
["Open", "Search", "Observe"],
|
||||
"Trial A (empty KG): container verb labels must equal Phase-1 defaults"
|
||||
);
|
||||
}
|
||||
|
||||
// --- Trial B: KG with PersonOfInterest NPC nearby ---
|
||||
// Player has a non-trivial knowledge state; container labels must still be
|
||||
// the Phase-1 defaults — Phase 2 NPC-specific logic must not bleed into
|
||||
// ObjectType::Container interactions.
|
||||
{
|
||||
let mut world = setup_world(32, 32);
|
||||
let mut registry = EntityRegistry::new(0);
|
||||
|
||||
let container = world
|
||||
.spawn((
|
||||
TilePosition::new(16, 15, 0),
|
||||
crate::simulation::interaction::Interactable,
|
||||
ObjectType::Container,
|
||||
))
|
||||
.id();
|
||||
registry.register(container);
|
||||
|
||||
// NPC out of close-range so Confront is not injected; still in KG as POI.
|
||||
let npc = world
|
||||
.spawn((
|
||||
crate::npc::Npc,
|
||||
TilePosition::new(16, 13, 0),
|
||||
crate::simulation::interaction::Interactable,
|
||||
))
|
||||
.id();
|
||||
let npc_sid = registry.register(npc);
|
||||
|
||||
let mut kg = KnowledgeGraph::new();
|
||||
kg.observe_entity(npc_sid, TilePosition::new(16, 13, 0), 5);
|
||||
kg.set_relationship(&npc_sid, RelationshipState::PersonOfInterest);
|
||||
|
||||
world.spawn((
|
||||
PlayerCharacter,
|
||||
TilePosition::new(16, 16, 0),
|
||||
Facing(FacingDirection::North),
|
||||
kg,
|
||||
NearbyInteractionBuffer::default(),
|
||||
MonologueBuffer::default(),
|
||||
));
|
||||
world.insert_resource(registry);
|
||||
|
||||
run_full_pipeline(&mut world);
|
||||
|
||||
let buffer = world.resource::<SnapshotBuffer>();
|
||||
let snapshot = buffer.snapshot.as_ref().unwrap();
|
||||
|
||||
let container_interaction = snapshot
|
||||
.nearby_interactions
|
||||
.iter()
|
||||
.find(|i| i.object_type == Some(ObjectType::Container))
|
||||
.expect("container interaction must be present");
|
||||
|
||||
let labels: Vec<&str> = container_interaction
|
||||
.verbs
|
||||
.iter()
|
||||
.map(|v| v.label.as_str())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
labels,
|
||||
["Open", "Search", "Observe"],
|
||||
"Trial B (POI NPC in KG): container verb labels must equal Phase-1 defaults"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
use bevy_ecs::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::bridge::types::CharacterArchetype;
|
||||
use crate::knowledge::events::{KnowledgeEvent, KnowledgeEventQueue, KnowledgeEventType};
|
||||
use crate::knowledge::EntityRegistry;
|
||||
use crate::npc::mood::{MoodState, NpcMood};
|
||||
@@ -37,11 +36,12 @@ pub struct ExamineRequest {
|
||||
pub target: Entity,
|
||||
}
|
||||
|
||||
/// Character-filtered examination result for snapshot delivery.
|
||||
/// Examination result for snapshot delivery.
|
||||
///
|
||||
/// Content differs per CharacterArchetype:
|
||||
/// Smuggler — physical threat read, cargo-handling posture, opportunity windows.
|
||||
/// Detective — procedural tells, behavioral inconsistencies, stress indicators.
|
||||
/// Phase 6 note: per-archetype text variants (smuggler/detective flavor) were
|
||||
/// removed during the cascade cleanup. Text is a single unified "subject read"
|
||||
/// until archetype differentiation is reintroduced per the culture-driven
|
||||
/// voice system (D-121) in a later cascade phase.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ExamineResultEvent {
|
||||
/// Character-filtered observation text for client display.
|
||||
@@ -106,12 +106,15 @@ fn has_trait(traits_opt: Option<&PersonalityTraits>, t: PersonalityTrait) -> boo
|
||||
traits_opt.map(|p| p.traits.contains(&t)).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Generate character-filtered examination text from NPC component state.
|
||||
/// Generate examination text from NPC component state.
|
||||
/// All logic is pure, deterministic, and integer-based (D-010).
|
||||
///
|
||||
/// Archetype-specific text variants were removed during the cascade cleanup
|
||||
/// (D-032 / Sprint 37). Reintroduce per-culture voice when the cascade reaches
|
||||
/// the Phase 6 character/NPC layer (see D-121).
|
||||
pub fn generate_examine_text(
|
||||
mood: NpcMood,
|
||||
ratio: u8,
|
||||
archetype: CharacterArchetype,
|
||||
traits_opt: Option<&PersonalityTraits>,
|
||||
) -> String {
|
||||
let stress_label = match ratio {
|
||||
@@ -123,53 +126,29 @@ pub fn generate_examine_text(
|
||||
|
||||
let mood_label = mood_word(mood);
|
||||
|
||||
match archetype {
|
||||
CharacterArchetype::Smuggler => {
|
||||
// Physical threat read + cargo opportunity window
|
||||
let threat = if matches!(mood, NpcMood::Hostile | NpcMood::Suspicious) {
|
||||
"Threat posture. Don't push it."
|
||||
} else if has_trait(traits_opt, PersonalityTrait::Bold) {
|
||||
"Confident bearing. Will push back if cornered."
|
||||
} else if has_trait(traits_opt, PersonalityTrait::Cautious) {
|
||||
"Nervous type. Predictable under pressure."
|
||||
} else {
|
||||
"No obvious threat read."
|
||||
};
|
||||
let tell = if has_trait(traits_opt, PersonalityTrait::Deceptive) {
|
||||
"Controlled affect — practiced concealment."
|
||||
} else if matches!(mood, NpcMood::Anxious | NpcMood::Frustrated) {
|
||||
"Involuntary stress markers present."
|
||||
} else if matches!(mood, NpcMood::Suspicious) {
|
||||
"Scanning. Aware of being observed."
|
||||
} else if matches!(mood, NpcMood::Hostile) {
|
||||
"Threat posture. Aware of being observed."
|
||||
} else {
|
||||
"Baseline presentation."
|
||||
};
|
||||
|
||||
let window = if ratio > 60 {
|
||||
"Too distracted to track cargo movement."
|
||||
} else if matches!(mood, NpcMood::Focused) {
|
||||
"Paying close attention to this section."
|
||||
} else {
|
||||
"Standard patrol pattern. Window is there."
|
||||
};
|
||||
let read = if ratio > 60 {
|
||||
"Under pressure — potential liability or asset."
|
||||
} else if matches!(mood, NpcMood::Content | NpcMood::Warm) {
|
||||
"Comfortable. Less guarded than usual."
|
||||
} else if matches!(mood, NpcMood::Focused) {
|
||||
"Paying close attention."
|
||||
} else {
|
||||
"Routine behavior pattern."
|
||||
};
|
||||
|
||||
format!("Appears {mood_label}, {stress_label}. {threat} {window}")
|
||||
}
|
||||
|
||||
CharacterArchetype::Detective => {
|
||||
// Procedural tells + behavioral read
|
||||
let tell = if has_trait(traits_opt, PersonalityTrait::Deceptive) {
|
||||
"Controlled affect — practiced concealment."
|
||||
} else if matches!(mood, NpcMood::Anxious | NpcMood::Frustrated) {
|
||||
"Involuntary stress markers present."
|
||||
} else if matches!(mood, NpcMood::Suspicious) {
|
||||
"Scanning. Aware of being observed."
|
||||
} else {
|
||||
"Baseline presentation."
|
||||
};
|
||||
|
||||
let read = if ratio > 60 {
|
||||
"Under pressure — potential liability or asset."
|
||||
} else if matches!(mood, NpcMood::Content | NpcMood::Warm) {
|
||||
"Comfortable. Less guarded than usual."
|
||||
} else {
|
||||
"Routine behavior pattern."
|
||||
};
|
||||
|
||||
format!("Subject: {mood_label}, {stress_label}. {tell} {read}")
|
||||
}
|
||||
}
|
||||
format!("Subject: {mood_label}, {stress_label}. {tell} {read}")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -196,7 +175,6 @@ pub fn process_examine_interaction(
|
||||
Entity,
|
||||
&TilePosition,
|
||||
&ExamineRequest,
|
||||
Option<&CharacterArchetype>,
|
||||
&mut ExamineResultBuffer,
|
||||
),
|
||||
With<PlayerCharacter>,
|
||||
@@ -212,14 +190,12 @@ pub fn process_examine_interaction(
|
||||
>,
|
||||
examine_text_query: Query<(&TilePosition, Option<&ExamineText>)>,
|
||||
) {
|
||||
let Ok((player_entity, player_pos, examine_req, archetype_opt, mut result_buffer)) =
|
||||
player_query.single_mut()
|
||||
let Ok((player_entity, player_pos, examine_req, mut result_buffer)) = player_query.single_mut()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
let target = examine_req.target;
|
||||
let archetype = archetype_opt.copied().unwrap_or_default();
|
||||
|
||||
// Try NPC examine path first
|
||||
if let Ok((target_pos, mood_opt, tolerance_opt, traits_opt)) = npc_query.get(target) {
|
||||
@@ -238,7 +214,7 @@ pub fn process_examine_interaction(
|
||||
|
||||
let mood = mood_opt.map(|m| m.mood).unwrap_or(NpcMood::Neutral);
|
||||
let ratio = tolerance_opt.map(stress_ratio).unwrap_or(0);
|
||||
let text = generate_examine_text(mood, ratio, archetype, traits_opt);
|
||||
let text = generate_examine_text(mood, ratio, traits_opt);
|
||||
|
||||
kg_events.push(KnowledgeEvent {
|
||||
observer: player_entity,
|
||||
@@ -323,8 +299,8 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smuggler_hostile_npc_gives_threat_read() {
|
||||
let text = generate_examine_text(NpcMood::Hostile, 20, CharacterArchetype::Smuggler, None);
|
||||
fn hostile_npc_gives_threat_read() {
|
||||
let text = generate_examine_text(NpcMood::Hostile, 20, None);
|
||||
assert!(
|
||||
text.contains("Threat posture"),
|
||||
"expected threat read, got: {text}"
|
||||
@@ -332,32 +308,27 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smuggler_focused_npc_notes_attention() {
|
||||
let text = generate_examine_text(NpcMood::Focused, 30, CharacterArchetype::Smuggler, None);
|
||||
fn focused_npc_notes_attention() {
|
||||
let text = generate_examine_text(NpcMood::Focused, 30, None);
|
||||
assert!(
|
||||
text.contains("close attention"),
|
||||
text.contains("Paying close attention"),
|
||||
"expected attention note, got: {text}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smuggler_high_stress_identifies_distraction() {
|
||||
let text = generate_examine_text(NpcMood::Anxious, 80, CharacterArchetype::Smuggler, None);
|
||||
fn high_stress_identifies_pressure() {
|
||||
let text = generate_examine_text(NpcMood::Anxious, 80, None);
|
||||
assert!(
|
||||
text.contains("Too distracted"),
|
||||
"expected distraction read, got: {text}"
|
||||
text.contains("Under pressure"),
|
||||
"expected pressure read, got: {text}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detective_deceptive_npc_notes_concealment() {
|
||||
fn deceptive_npc_notes_concealment() {
|
||||
let t = traits(&[PersonalityTrait::Deceptive]);
|
||||
let text = generate_examine_text(
|
||||
NpcMood::Neutral,
|
||||
20,
|
||||
CharacterArchetype::Detective,
|
||||
Some(&t),
|
||||
);
|
||||
let text = generate_examine_text(NpcMood::Neutral, 20, Some(&t));
|
||||
assert!(
|
||||
text.contains("Controlled affect"),
|
||||
"expected concealment note, got: {text}"
|
||||
@@ -365,8 +336,8 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detective_anxious_npc_notes_stress_markers() {
|
||||
let text = generate_examine_text(NpcMood::Anxious, 50, CharacterArchetype::Detective, None);
|
||||
fn anxious_npc_notes_stress_markers() {
|
||||
let text = generate_examine_text(NpcMood::Anxious, 50, None);
|
||||
assert!(
|
||||
text.contains("stress markers"),
|
||||
"expected stress markers, got: {text}"
|
||||
@@ -374,8 +345,8 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detective_content_npc_notes_low_guard() {
|
||||
let text = generate_examine_text(NpcMood::Content, 10, CharacterArchetype::Detective, None);
|
||||
fn content_npc_notes_low_guard() {
|
||||
let text = generate_examine_text(NpcMood::Content, 10, None);
|
||||
assert!(
|
||||
text.contains("Less guarded"),
|
||||
"expected low guard note, got: {text}"
|
||||
|
||||
@@ -72,8 +72,6 @@ pub type EconomicModifier = String;
|
||||
pub type FactionModifier = String;
|
||||
/// Condition modifier on a zone palette (worn, pristine, damaged). Stub.
|
||||
pub type ConditionModifier = String;
|
||||
/// Heritage root modifier (Settled Reach cultural grammar layer). Stub.
|
||||
pub type HeritageRoot = String;
|
||||
/// Season modifier (affects palette and ambient conditions). Stub.
|
||||
pub type Season = String;
|
||||
/// Role slot within a social site template. Stub.
|
||||
@@ -366,7 +364,6 @@ pub enum PaletteModifier {
|
||||
Era(Era),
|
||||
FactionPresence(FactionModifier),
|
||||
Condition(ConditionModifier),
|
||||
Heritage(HeritageRoot),
|
||||
Season(Season),
|
||||
}
|
||||
|
||||
|
||||
@@ -119,7 +119,7 @@ impl PostConversationQueue {
|
||||
|
||||
/// Tracks monologue state for cooldown and trigger detection.
|
||||
/// Attached to the PlayerCharacter entity.
|
||||
#[derive(Component, Debug)]
|
||||
#[derive(Component, Debug, Default)]
|
||||
pub struct MonologueState {
|
||||
/// Tick when the last monologue was fired.
|
||||
pub last_fired_tick: u64,
|
||||
@@ -131,29 +131,12 @@ pub struct MonologueState {
|
||||
pub entered: bool,
|
||||
/// IDs of lines already shown (dedup within session).
|
||||
pub shown_ids: BTreeSet<String>,
|
||||
/// Character type for pool filtering. Set from CharacterArchetype (#587).
|
||||
pub character: String,
|
||||
/// Tick of the last observation event we reacted to (#119, observe_npc).
|
||||
/// Observation events arrive one tick after the snapshot that caused them,
|
||||
/// so we track which tick's events we've already processed.
|
||||
pub last_observation_tick: u64,
|
||||
}
|
||||
|
||||
impl Default for MonologueState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
last_fired_tick: 0,
|
||||
last_position: None,
|
||||
idle_ticks: 0,
|
||||
entered: false,
|
||||
shown_ids: BTreeSet::new(),
|
||||
// Default to detective; overridden by CharacterArchetype at spawn (#587)
|
||||
character: "detective".to_string(),
|
||||
last_observation_tick: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Buffer holding the monologue event to include in the next snapshot.
|
||||
/// `take()` drains the buffer (consumed once per snapshot).
|
||||
#[derive(Component, Debug, Default)]
|
||||
@@ -2142,4 +2125,103 @@ mod tests {
|
||||
"queue should be empty after monologue consumed the event"
|
||||
);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Regression: monologue pool selection is uniform (D-032 / #878)
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn monologue_pool_selection_uniform_no_archetype_key() {
|
||||
// Regression guard (D-032 cascade purge, #878):
|
||||
// trigger_event_monologue previously partitioned pool selection by
|
||||
// CharacterArchetype key (MonologueState.character). That field is gone.
|
||||
// Pool selection is now by trigger string only — "observe_npc", "hear_sound",
|
||||
// "post_conversation" — and the line IDs are drawn exclusively from the
|
||||
// corresponding hardcoded constant (OBSERVE_NPC_LINES et al.).
|
||||
//
|
||||
// This test asserts the POSITIVE behaviour: an observe_npc trigger always
|
||||
// produces a line whose ID begins with "observe_npc_", regardless of any
|
||||
// additional observer state. It FAILS if an archetype-keyed dispatch path
|
||||
// is reintroduced (which would produce IDs outside that prefix or panic on
|
||||
// a missing archetype field).
|
||||
|
||||
// Known line IDs from OBSERVE_NPC_LINES (compile-checked below).
|
||||
const VALID_OBSERVE_NPC_IDS: &[&str] =
|
||||
&["observe_npc_01", "observe_npc_02", "observe_npc_03"];
|
||||
|
||||
// --- Observer A: minimal state (no extra components) ---
|
||||
let line_a = {
|
||||
let mut world = setup_event_world();
|
||||
let player = spawn_event_player(&mut world);
|
||||
|
||||
world
|
||||
.resource_mut::<ObservationEventQueue>()
|
||||
.push(ObservationEvent {
|
||||
tick: 1,
|
||||
trigger: ObservationTrigger::NewEntity {
|
||||
entity: StableId(10),
|
||||
location: TilePosition::new(12, 12, 0),
|
||||
},
|
||||
observer: player,
|
||||
});
|
||||
|
||||
run_event_system(&mut world);
|
||||
|
||||
let buf = world.get::<MonologueBuffer>(player).unwrap();
|
||||
buf.event
|
||||
.as_ref()
|
||||
.expect("observe_npc trigger must fire a monologue")
|
||||
.id
|
||||
.clone()
|
||||
};
|
||||
|
||||
// --- Observer B: player has heard a previous sound (last_fired_tick set) ---
|
||||
// Simulates a player with non-default MonologueState — the pool key must
|
||||
// still resolve to OBSERVE_NPC_LINES, not an archetype-partitioned variant.
|
||||
let line_b = {
|
||||
let mut world = setup_event_world();
|
||||
let player = spawn_event_player(&mut world);
|
||||
|
||||
// Pre-populate state to exercise a non-fresh observer
|
||||
world.resource_mut::<SimulationTime>().tick = 10;
|
||||
{
|
||||
let mut state = world.get_mut::<MonologueState>(player).unwrap();
|
||||
state.last_fired_tick = 3;
|
||||
}
|
||||
|
||||
world
|
||||
.resource_mut::<ObservationEventQueue>()
|
||||
.push(ObservationEvent {
|
||||
tick: 5,
|
||||
trigger: ObservationTrigger::NewEntity {
|
||||
entity: StableId(20),
|
||||
location: TilePosition::new(14, 14, 0),
|
||||
},
|
||||
observer: player,
|
||||
});
|
||||
|
||||
run_event_system(&mut world);
|
||||
|
||||
let buf = world.get::<MonologueBuffer>(player).unwrap();
|
||||
buf.event
|
||||
.as_ref()
|
||||
.expect("observe_npc trigger must fire for observer B")
|
||||
.id
|
||||
.clone()
|
||||
};
|
||||
|
||||
// Both observers must produce IDs from the unified observe_npc pool.
|
||||
assert!(
|
||||
VALID_OBSERVE_NPC_IDS.contains(&line_a.as_str()),
|
||||
"Observer A line_id '{}' is not from OBSERVE_NPC_LINES — \
|
||||
archetype-keyed pool dispatch may have been reintroduced",
|
||||
line_a
|
||||
);
|
||||
assert!(
|
||||
VALID_OBSERVE_NPC_IDS.contains(&line_b.as_str()),
|
||||
"Observer B line_id '{}' is not from OBSERVE_NPC_LINES — \
|
||||
archetype-keyed pool dispatch may have been reintroduced",
|
||||
line_b
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ use std::path::{Path, PathBuf};
|
||||
use bevy_ecs::prelude::*;
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::bookmark::SelectedBookmark;
|
||||
use crate::bridge::types::SaveLoadResultWire;
|
||||
use crate::bridge::types::SnapshotBuffer;
|
||||
use crate::knowledge::graph::KnowledgeGraph;
|
||||
@@ -160,6 +161,10 @@ pub fn save_to_file(path: &Path, world: &mut World) -> Result<(), SaveLoadError>
|
||||
last_activation_tick: world
|
||||
.get_resource::<ActivationState>()
|
||||
.and_then(|a| a.last_activation_tick),
|
||||
selected_bookmark: world
|
||||
.get_resource::<SelectedBookmark>()
|
||||
.cloned()
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
|
||||
let bytes = state
|
||||
@@ -285,6 +290,10 @@ pub fn load_from_file(path: &Path, world: &mut World) -> Result<(), SaveLoadErro
|
||||
last_activation_tick: state.last_activation_tick,
|
||||
});
|
||||
|
||||
// Restore bookmark selection (#863) — the player's confirmed bookmark and
|
||||
// starting location survive save/load so downstream systems stay consistent.
|
||||
world.insert_resource(state.selected_bookmark);
|
||||
|
||||
// Reset event queues and transient buffers — prevent stale events/history
|
||||
// from the pre-load world leaking into the post-load simulation.
|
||||
world.insert_resource(ContaminationEventQueue::default());
|
||||
@@ -415,8 +424,11 @@ mod tests {
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
fn temp_path() -> PathBuf {
|
||||
// Include the process ID so nextest processes (each starts COUNTER at 0)
|
||||
// do not collide on the same filename when running concurrently.
|
||||
let pid = std::process::id();
|
||||
let id = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
std::env::temp_dir().join(format!("settled_reach_save_io_test_{}.msgpack", id))
|
||||
std::env::temp_dir().join(format!("settled_reach_save_io_test_{}_{}.msgpack", pid, id))
|
||||
}
|
||||
|
||||
fn minimal_world() -> World {
|
||||
@@ -623,6 +635,7 @@ mod tests {
|
||||
contamination_active: false,
|
||||
activated_count: 0,
|
||||
last_activation_tick: None,
|
||||
selected_bookmark: SelectedBookmark::default(),
|
||||
};
|
||||
let bytes = bad_state.to_bytes().expect("serialize");
|
||||
let path = temp_path();
|
||||
@@ -955,4 +968,69 @@ mod tests {
|
||||
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// SelectedBookmark round-trip (#863)
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn save_load_preserves_selected_bookmark() {
|
||||
let mut world = minimal_world();
|
||||
|
||||
// Set a bookmark selection before saving.
|
||||
world.insert_resource(SelectedBookmark {
|
||||
bookmark_id: Some("tycoon".to_string()),
|
||||
starting_location_id: Some("new-stockholm".to_string()),
|
||||
});
|
||||
|
||||
let path = temp_path();
|
||||
save_to_file(&path, &mut world).expect("save");
|
||||
|
||||
// Clear the resource to prove load restores it, not the pre-existing value.
|
||||
world.insert_resource(SelectedBookmark::default());
|
||||
assert!(
|
||||
world.resource::<SelectedBookmark>().bookmark_id.is_none(),
|
||||
"bookmark must be cleared before load"
|
||||
);
|
||||
|
||||
load_from_file(&path, &mut world).expect("load");
|
||||
|
||||
let restored = world.resource::<SelectedBookmark>();
|
||||
assert_eq!(
|
||||
restored.bookmark_id.as_deref(),
|
||||
Some("tycoon"),
|
||||
"bookmark_id must survive round-trip"
|
||||
);
|
||||
assert_eq!(
|
||||
restored.starting_location_id.as_deref(),
|
||||
Some("new-stockholm"),
|
||||
"starting_location_id must survive round-trip"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_load_selected_bookmark_defaults_when_unset() {
|
||||
// Save without a bookmark selection (default = both None).
|
||||
// Load must produce SelectedBookmark::default(), not error.
|
||||
let mut world = minimal_world();
|
||||
// SelectedBookmark not explicitly inserted — should default to no selection.
|
||||
|
||||
let path = temp_path();
|
||||
save_to_file(&path, &mut world).expect("save");
|
||||
load_from_file(&path, &mut world).expect("load");
|
||||
|
||||
let restored = world.resource::<SelectedBookmark>();
|
||||
assert!(
|
||||
restored.bookmark_id.is_none(),
|
||||
"unset bookmark_id must survive as None"
|
||||
);
|
||||
assert!(
|
||||
restored.starting_location_id.is_none(),
|
||||
"unset starting_location_id must survive as None"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,6 +39,7 @@ use bevy_ecs::entity::Entity;
|
||||
use bevy_ecs::world::World;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::bookmark::SelectedBookmark;
|
||||
use crate::knowledge::graph::KnowledgeGraph;
|
||||
use crate::knowledge::registry::StableEntityId;
|
||||
use crate::knowledge::types::StableId;
|
||||
@@ -122,6 +123,11 @@ pub struct SaveStateV1 {
|
||||
/// `None` if no activation yet. Persisted alongside `activated_count`.
|
||||
#[serde(default)]
|
||||
pub last_activation_tick: Option<u64>,
|
||||
/// Bookmark and starting location confirmed by the player at session start (#863, #614).
|
||||
/// Both fields are `None` in saves created before #863 or before character creation
|
||||
/// completes. Defaults to `SelectedBookmark::default()` for backward compatibility.
|
||||
#[serde(default)]
|
||||
pub selected_bookmark: SelectedBookmark,
|
||||
}
|
||||
|
||||
/// Per-NPC state snapshot for `SaveStateV1`.
|
||||
@@ -435,6 +441,7 @@ mod tests {
|
||||
contamination_active: false,
|
||||
activated_count: 0,
|
||||
last_activation_tick: None,
|
||||
selected_bookmark: crate::bookmark::SelectedBookmark::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -854,6 +861,7 @@ mod tests {
|
||||
contamination_active: false,
|
||||
activated_count: 0,
|
||||
last_activation_tick: None,
|
||||
selected_bookmark: crate::bookmark::SelectedBookmark::default(),
|
||||
};
|
||||
|
||||
let bytes = save.to_bytes().expect("serialize");
|
||||
@@ -878,6 +886,63 @@ mod tests {
|
||||
assert!(result.is_err(), "must panic without StableEntityId");
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// SelectedBookmark round-trip (#863)
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn selected_bookmark_with_values_survives_roundtrip() {
|
||||
// Spec (#863): SelectedBookmark persisted in SaveStateV1 must survive a
|
||||
// full MessagePack serialize → deserialize cycle with field values intact.
|
||||
let mut state = minimal_save_state();
|
||||
state.selected_bookmark = crate::bookmark::SelectedBookmark {
|
||||
bookmark_id: Some("tycoon".to_string()),
|
||||
starting_location_id: Some("GJ 35".to_string()),
|
||||
};
|
||||
|
||||
let bytes = state.to_bytes().expect("serialize");
|
||||
let recovered = SaveStateV1::from_bytes(&bytes).expect("deserialize");
|
||||
|
||||
assert_eq!(
|
||||
recovered.selected_bookmark.bookmark_id,
|
||||
Some("tycoon".to_string()),
|
||||
"bookmark_id must survive roundtrip"
|
||||
);
|
||||
assert_eq!(
|
||||
recovered.selected_bookmark.starting_location_id,
|
||||
Some("GJ 35".to_string()),
|
||||
"starting_location_id must survive roundtrip"
|
||||
);
|
||||
|
||||
// Idempotent re-serialize: bytes must be stable
|
||||
let bytes2 = recovered.to_bytes().expect("re-serialize");
|
||||
assert_eq!(
|
||||
bytes, bytes2,
|
||||
"SelectedBookmark roundtrip must be idempotent"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_bookmark_default_survives_roundtrip() {
|
||||
// Spec (#863): saves from before Sprint 37 (both fields None) must load
|
||||
// cleanly via serde(default) on the SaveStateV1 field.
|
||||
let state = minimal_save_state();
|
||||
assert!(state.selected_bookmark.bookmark_id.is_none());
|
||||
assert!(state.selected_bookmark.starting_location_id.is_none());
|
||||
|
||||
let bytes = state.to_bytes().expect("serialize");
|
||||
let recovered = SaveStateV1::from_bytes(&bytes).expect("deserialize");
|
||||
|
||||
assert!(
|
||||
recovered.selected_bookmark.bookmark_id.is_none(),
|
||||
"default bookmark_id (None) must roundtrip"
|
||||
);
|
||||
assert!(
|
||||
recovered.selected_bookmark.starting_location_id.is_none(),
|
||||
"default starting_location_id (None) must roundtrip"
|
||||
);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Modifications stub round-trip (#567, D-111/D-112)
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@@ -535,7 +535,7 @@ pub fn activation_pass(
|
||||
}
|
||||
|
||||
if candidates.is_empty() {
|
||||
tracing::warn!(
|
||||
tracing::debug!(
|
||||
"activation_pass: no co-present NPC is assigned to a Simmering triangle at tick {} — holding",
|
||||
time.tick
|
||||
);
|
||||
|
||||
@@ -95,7 +95,7 @@ pub const MAP_HEIGHT: i32 = 125;
|
||||
/// is intentional for deterministic test setups but should be revisited
|
||||
/// if Gauntlet is ever served by the production startup pipeline.
|
||||
#[cfg(feature = "gauntlet")]
|
||||
pub fn setup_gauntlet(app: &mut App, archetype: crate::bridge::types::CharacterArchetype) {
|
||||
pub fn setup_gauntlet(app: &mut App) {
|
||||
// Start with a fully blocked map, then carve rooms and corridors.
|
||||
let mut walkability = WalkabilityMap::new_blocked(MAP_WIDTH, MAP_HEIGHT, 1);
|
||||
|
||||
@@ -190,12 +190,8 @@ pub fn setup_gauntlet(app: &mut App, archetype: crate::bridge::types::CharacterA
|
||||
|
||||
// --- Player (StableId 0) ---
|
||||
// Spawn at Hub center: absolute (50, 58)
|
||||
let profile = MovementProfile::smuggler();
|
||||
let profile = MovementProfile::default();
|
||||
let player_pos = TilePosition::new(50, 58, 0);
|
||||
let monologue_state = MonologueState {
|
||||
character: archetype.as_monologue_key().to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
let player = app
|
||||
.world_mut()
|
||||
.spawn((
|
||||
@@ -204,7 +200,7 @@ pub fn setup_gauntlet(app: &mut App, archetype: crate::bridge::types::CharacterA
|
||||
Facing::default(),
|
||||
KnowledgeGraph::new(),
|
||||
NearbyInteractionBuffer::default(),
|
||||
monologue_state,
|
||||
MonologueState::default(),
|
||||
MonologueBuffer::default(),
|
||||
SprintAnomalyQueue::default(),
|
||||
ScanEventBuffer::default(),
|
||||
@@ -216,7 +212,6 @@ pub fn setup_gauntlet(app: &mut App, archetype: crate::bridge::types::CharacterA
|
||||
crate::simulation::pressure::CharacterPressure::default(),
|
||||
))
|
||||
.id();
|
||||
app.world_mut().entity_mut(player).insert(archetype);
|
||||
registry.register(player);
|
||||
|
||||
// --- Hub signs (StableId 1-4) ---
|
||||
@@ -699,10 +694,7 @@ mod tests {
|
||||
app.add_plugins(crate::knowledge::KnowledgePlugin);
|
||||
app.add_plugins(crate::npc::NpcPlugin);
|
||||
|
||||
setup_gauntlet(
|
||||
&mut app,
|
||||
crate::bridge::types::CharacterArchetype::default(),
|
||||
);
|
||||
setup_gauntlet(&mut app);
|
||||
|
||||
// Run all 29 world-query invariants against the fully-initialized gauntlet world.
|
||||
invariants::run_invariants(app.world_mut());
|
||||
@@ -722,10 +714,7 @@ mod tests {
|
||||
app.add_plugins(crate::knowledge::KnowledgePlugin);
|
||||
app.add_plugins(crate::npc::NpcPlugin);
|
||||
|
||||
setup_gauntlet(
|
||||
&mut app,
|
||||
crate::bridge::types::CharacterArchetype::default(),
|
||||
);
|
||||
setup_gauntlet(&mut app);
|
||||
|
||||
let wm = app.world().resource::<WalkabilityMap>();
|
||||
// Hub center at (50, 58) must be walkable
|
||||
@@ -739,10 +728,7 @@ mod tests {
|
||||
app.add_plugins(crate::knowledge::KnowledgePlugin);
|
||||
app.add_plugins(crate::npc::NpcPlugin);
|
||||
|
||||
setup_gauntlet(
|
||||
&mut app,
|
||||
crate::bridge::types::CharacterArchetype::default(),
|
||||
);
|
||||
setup_gauntlet(&mut app);
|
||||
|
||||
let wm = app.world().resource::<WalkabilityMap>();
|
||||
// North wall segment at absolute (90, 54) should be blocked
|
||||
@@ -758,10 +744,7 @@ mod tests {
|
||||
app.add_plugins(crate::knowledge::KnowledgePlugin);
|
||||
app.add_plugins(crate::npc::NpcPlugin);
|
||||
|
||||
setup_gauntlet(
|
||||
&mut app,
|
||||
crate::bridge::types::CharacterArchetype::default(),
|
||||
);
|
||||
setup_gauntlet(&mut app);
|
||||
|
||||
let wm = app.world().resource::<WalkabilityMap>();
|
||||
// corridor-E center should be walkable
|
||||
@@ -775,10 +758,7 @@ mod tests {
|
||||
app.add_plugins(crate::knowledge::KnowledgePlugin);
|
||||
app.add_plugins(crate::npc::NpcPlugin);
|
||||
|
||||
setup_gauntlet(
|
||||
&mut app,
|
||||
crate::bridge::types::CharacterArchetype::default(),
|
||||
);
|
||||
setup_gauntlet(&mut app);
|
||||
|
||||
let registry = app.world().resource::<EntityRegistry>();
|
||||
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
//! Regression tests: character archetype flows end-to-end to MonologueState (#595, D-032).
|
||||
//!
|
||||
//! Verifies that when a session starts with a given CharacterArchetype, the
|
||||
//! player entity's MonologueState.character reflects it correctly. This is the
|
||||
//! guard against the default "detective" string leaking into smuggler sessions.
|
||||
//!
|
||||
//! Two complementary approaches:
|
||||
//! 1. Unit-level: CharacterArchetype::as_monologue_key() mapping is correct.
|
||||
//! 2. Integration (gauntlet): setup_gauntlet() correctly wires archetype → MonologueState.
|
||||
//!
|
||||
//! Spec refs:
|
||||
//! D-032: character tag is a hard pool partition, not a filter — wrong character string
|
||||
//! silently serves wrong content.
|
||||
//! D-010: no player identity baked into game loop — archetype is a configuration.
|
||||
//! #587: character_archetype added to StartupMessage; monologue key derived from it.
|
||||
//! #595: MonologueState.character initialized from CharacterArchetype at session start.
|
||||
|
||||
use settled_reach_server::bridge::types::CharacterArchetype;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Layer 1 — pure unit tests, no ECS
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn smuggler_archetype_maps_to_monologue_key() {
|
||||
assert_eq!(
|
||||
CharacterArchetype::Smuggler.as_monologue_key(),
|
||||
"smuggler",
|
||||
"Smuggler must produce the exact pool key 'smuggler' used in monologue YAML"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detective_archetype_maps_to_monologue_key() {
|
||||
assert_eq!(
|
||||
CharacterArchetype::Detective.as_monologue_key(),
|
||||
"detective",
|
||||
"Detective must produce the exact pool key 'detective' used in monologue YAML"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_archetype_is_detective() {
|
||||
// D-010: the safe fallback is Detective (the original single-character game).
|
||||
// If serde default fires (old client, missing field), Detective must be chosen.
|
||||
assert_eq!(
|
||||
CharacterArchetype::default(),
|
||||
CharacterArchetype::Detective,
|
||||
"Default archetype must be Detective for backward compatibility (#587)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn archetype_keys_are_distinct() {
|
||||
// Sanity guard: the two keys must differ. If they were the same, pool partitioning
|
||||
// (D-032) would be broken and both characters would see identical monologue lines.
|
||||
assert_ne!(
|
||||
CharacterArchetype::Smuggler.as_monologue_key(),
|
||||
CharacterArchetype::Detective.as_monologue_key(),
|
||||
"Smuggler and Detective monologue keys must be distinct (D-032 hard partition)"
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Layer 2 — integration: setup_gauntlet wires archetype → MonologueState
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[cfg(feature = "gauntlet")]
|
||||
mod gauntlet_integration {
|
||||
use bevy_app::prelude::*;
|
||||
use bevy_ecs::prelude::*;
|
||||
use settled_reach_server::{
|
||||
bridge::types::CharacterArchetype,
|
||||
simulation::{monologue::MonologueState, movement::PlayerCharacter, SimulationPlugin},
|
||||
test_world,
|
||||
};
|
||||
|
||||
/// Build a minimal Gauntlet app with the given archetype and run one tick.
|
||||
fn boot_gauntlet(archetype: CharacterArchetype) -> App {
|
||||
let mut app = App::new();
|
||||
app.add_plugins(SimulationPlugin { seed: 0 });
|
||||
test_world::setup_gauntlet(&mut app, archetype);
|
||||
app.update();
|
||||
app
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smuggler_archetype_sets_monologue_character_to_smuggler() {
|
||||
let mut app = boot_gauntlet(CharacterArchetype::Smuggler);
|
||||
|
||||
let mut query = app
|
||||
.world_mut()
|
||||
.query_filtered::<&MonologueState, With<PlayerCharacter>>();
|
||||
let state = query
|
||||
.single(app.world())
|
||||
.expect("player entity with MonologueState must exist after gauntlet setup");
|
||||
|
||||
assert_eq!(
|
||||
state.character, "smuggler",
|
||||
"Smuggler archetype must produce MonologueState.character = 'smuggler' (D-032, #587)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detective_archetype_sets_monologue_character_to_detective() {
|
||||
let mut app = boot_gauntlet(CharacterArchetype::Detective);
|
||||
|
||||
let mut query = app
|
||||
.world_mut()
|
||||
.query_filtered::<&MonologueState, With<PlayerCharacter>>();
|
||||
let state = query
|
||||
.single(app.world())
|
||||
.expect("player entity with MonologueState must exist after gauntlet setup");
|
||||
|
||||
assert_eq!(
|
||||
state.character, "detective",
|
||||
"Detective archetype must produce MonologueState.character = 'detective' (D-032, #587)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smuggler_and_detective_produce_different_monologue_characters() {
|
||||
// Regression guard: if both sessions return the same character string, D-032
|
||||
// partitioning is broken. This test catches copy-paste mistakes in setup paths.
|
||||
let mut smuggler_app = boot_gauntlet(CharacterArchetype::Smuggler);
|
||||
let mut detective_app = boot_gauntlet(CharacterArchetype::Detective);
|
||||
|
||||
let smuggler_char = {
|
||||
let mut q = smuggler_app
|
||||
.world_mut()
|
||||
.query_filtered::<&MonologueState, With<PlayerCharacter>>();
|
||||
q.single(smuggler_app.world())
|
||||
.expect("smuggler player must exist")
|
||||
.character
|
||||
.clone()
|
||||
};
|
||||
|
||||
let detective_char = {
|
||||
let mut q = detective_app
|
||||
.world_mut()
|
||||
.query_filtered::<&MonologueState, With<PlayerCharacter>>();
|
||||
q.single(detective_app.world())
|
||||
.expect("detective player must exist")
|
||||
.character
|
||||
.clone()
|
||||
};
|
||||
|
||||
assert_ne!(
|
||||
smuggler_char, detective_char,
|
||||
"Smuggler and Detective sessions must have different MonologueState.character values \
|
||||
(D-032 hard partition: same key means both characters see each other's monologue pool)"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,6 @@ fn snapshot_roundtrip_over_unix_socket() {
|
||||
let bridge = LocalBridge::accept(&server_path).expect("failed to accept");
|
||||
|
||||
let snapshot = ObserverSnapshot {
|
||||
version: PROTOCOL_VERSION,
|
||||
tick: 42,
|
||||
game_time: GameTime {
|
||||
day: 0,
|
||||
|
||||
@@ -19,7 +19,6 @@ fn snapshot_roundtrip_over_tcp() {
|
||||
let bridge = TcpBridge::accept_on(listener).expect("failed to accept");
|
||||
|
||||
let snapshot = ObserverSnapshot {
|
||||
version: PROTOCOL_VERSION,
|
||||
tick: 42,
|
||||
game_time: GameTime {
|
||||
day: 0,
|
||||
|
||||
@@ -432,6 +432,7 @@ fn minimal_save() -> SaveStateV1 {
|
||||
contamination_active: false,
|
||||
activated_count: 0,
|
||||
last_activation_tick: None,
|
||||
selected_bookmark: settled_reach_server::bookmark::SelectedBookmark::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -268,7 +268,6 @@ fn snapshot_with_sim_errors_roundtrips() {
|
||||
use settled_reach_server::simulation::time::{DayPhase, TickRate};
|
||||
|
||||
let snapshot = ObserverSnapshot {
|
||||
version: PROTOCOL_VERSION,
|
||||
tick: 10,
|
||||
game_time: GameTime {
|
||||
day: 0,
|
||||
|
||||
@@ -68,7 +68,6 @@ fn player_moves_north_through_full_pipeline() {
|
||||
rmp_serde::from_slice(&response).expect("deserialize snapshot");
|
||||
|
||||
// Snapshot captures state at end of tick 0 (before advance_tick increments to 1)
|
||||
assert_eq!(snapshot.version, PROTOCOL_VERSION);
|
||||
assert_eq!(snapshot.tick, 0);
|
||||
assert_eq!(snapshot.entities.len(), 1);
|
||||
|
||||
|
||||
@@ -16,10 +16,9 @@ fn write_fixture(name: &str, bytes: &[u8]) {
|
||||
eprintln!("Wrote {} ({} bytes)", path.display(), bytes.len());
|
||||
}
|
||||
|
||||
/// Helper to create a minimal v2 snapshot for fixtures
|
||||
/// Helper to create a minimal snapshot for fixtures (D-192: no version field)
|
||||
fn fixture_snapshot(tick: u64, entities: Vec<VisibleEntity>) -> ObserverSnapshot {
|
||||
ObserverSnapshot {
|
||||
version: PROTOCOL_VERSION,
|
||||
tick,
|
||||
game_time: GameTime {
|
||||
day: 0,
|
||||
@@ -181,7 +180,6 @@ fn generate_msgpack_fixtures() {
|
||||
|
||||
// v2 snapshot with visible_tiles and game_time populated
|
||||
let snapshot_v2_full = ObserverSnapshot {
|
||||
version: PROTOCOL_VERSION,
|
||||
tick: 500,
|
||||
game_time: GameTime {
|
||||
day: 1,
|
||||
@@ -302,7 +300,7 @@ fn generate_msgpack_fixtures() {
|
||||
|
||||
// === #271 fixtures: named fixtures for cross-language Layer 1 testing ===
|
||||
|
||||
// snapshot_minimal: version=PROTOCOL_VERSION, tick=0, one Player entity, all optionals absent
|
||||
// snapshot_minimal: tick=0, one Player entity, all optionals absent
|
||||
let snapshot_minimal = fixture_snapshot(
|
||||
0,
|
||||
vec![VisibleEntity {
|
||||
@@ -322,9 +320,8 @@ fn generate_msgpack_fixtures() {
|
||||
&rmp_serde::to_vec_named(&snapshot_minimal).unwrap(),
|
||||
);
|
||||
|
||||
// snapshot_full: version=PROTOCOL_VERSION, tick=42, monologue + dialogue + inventory + POIs + KG dump
|
||||
// snapshot_full: tick=42, monologue + dialogue + inventory + POIs + KG dump
|
||||
let snapshot_full = ObserverSnapshot {
|
||||
version: PROTOCOL_VERSION,
|
||||
tick: 42,
|
||||
game_time: GameTime {
|
||||
day: 3,
|
||||
|
||||
@@ -45,10 +45,7 @@ fn build_gauntlet(seed: u64) -> App {
|
||||
app.add_plugins(NpcPlugin);
|
||||
app.insert_resource(SimRng::new(seed));
|
||||
|
||||
test_world::setup_gauntlet(
|
||||
&mut app,
|
||||
settled_reach_server::bridge::types::CharacterArchetype::default(),
|
||||
);
|
||||
test_world::setup_gauntlet(&mut app);
|
||||
|
||||
app
|
||||
}
|
||||
|
||||
@@ -214,6 +214,7 @@ fn save_state_npc_kg_isolation() {
|
||||
contamination_active: false,
|
||||
activated_count: 0,
|
||||
last_activation_tick: None,
|
||||
selected_bookmark: settled_reach_server::bookmark::SelectedBookmark::default(),
|
||||
};
|
||||
|
||||
// Roundtrip: serialize → deserialize.
|
||||
|
||||
@@ -99,13 +99,9 @@ fn ipc_round_trip_latency() {
|
||||
let handshake_bytes = read_framed(&mut reader)
|
||||
.expect("read handshake")
|
||||
.expect("server closed before sending HandshakeMessage");
|
||||
let handshake: HandshakeMessage =
|
||||
// D-192: HandshakeMessage carries no version field. Verify it deserialises cleanly.
|
||||
let _handshake: HandshakeMessage =
|
||||
rmp_serde::from_slice(&handshake_bytes).expect("deserialize HandshakeMessage");
|
||||
assert_eq!(
|
||||
handshake.protocol_version, PROTOCOL_VERSION,
|
||||
"handshake version mismatch: server={}, client={}",
|
||||
handshake.protocol_version, PROTOCOL_VERSION
|
||||
);
|
||||
|
||||
let make_input = |tick: u64| PlayerInput {
|
||||
tick,
|
||||
|
||||
+3
-15
@@ -76,19 +76,12 @@ fn server_subprocess_sends_snapshot_on_connect() {
|
||||
let handshake_frame = read_framed(&mut reader)
|
||||
.expect("read handshake frame")
|
||||
.expect("server closed connection before sending handshake");
|
||||
let handshake: HandshakeMessage =
|
||||
// D-192: HandshakeMessage carries no version field. Verify it deserialises cleanly.
|
||||
let _handshake: HandshakeMessage =
|
||||
rmp_serde::from_slice(&handshake_frame).expect("deserialize HandshakeMessage");
|
||||
assert_eq!(
|
||||
handshake.protocol_version, PROTOCOL_VERSION,
|
||||
"handshake protocol_version mismatch: got {}, expected {}",
|
||||
handshake.protocol_version, PROTOCOL_VERSION
|
||||
);
|
||||
|
||||
// 5. Send StartupMessage with world_seed (#175)
|
||||
let startup = StartupMessage {
|
||||
world_seed: 42,
|
||||
character_archetype: settled_reach_server::bridge::types::CharacterArchetype::default(),
|
||||
};
|
||||
let startup = StartupMessage { world_seed: 42 };
|
||||
let startup_payload = rmp_serde::to_vec_named(&startup).expect("serialize StartupMessage");
|
||||
write_framed(&mut writer, &startup_payload).expect("send StartupMessage to server");
|
||||
|
||||
@@ -108,11 +101,6 @@ fn server_subprocess_sends_snapshot_on_connect() {
|
||||
rmp_serde::from_slice(&response).expect("deserialize ObserverSnapshot");
|
||||
|
||||
// 8. Assert protocol correctness (D-020)
|
||||
assert_eq!(
|
||||
snapshot.version, PROTOCOL_VERSION,
|
||||
"protocol version mismatch: got {}, expected {}",
|
||||
snapshot.version, PROTOCOL_VERSION
|
||||
);
|
||||
assert!(
|
||||
snapshot.entities.len() > 0,
|
||||
"snapshot should contain at least one entity (the player), got 0"
|
||||
|
||||
@@ -4,10 +4,9 @@ use settled_reach_server::bridge::types::*;
|
||||
use settled_reach_server::simulation::time::{DayPhase, TickRate};
|
||||
use std::fs;
|
||||
|
||||
/// Helper to create a minimal v2 snapshot for tests
|
||||
/// Helper to create a minimal snapshot for tests (D-192: no version field)
|
||||
fn test_snapshot(tick: u64, entities: Vec<VisibleEntity>) -> ObserverSnapshot {
|
||||
ObserverSnapshot {
|
||||
version: PROTOCOL_VERSION,
|
||||
tick,
|
||||
game_time: GameTime {
|
||||
day: 0,
|
||||
@@ -65,7 +64,6 @@ fn observer_snapshot_roundtrip() {
|
||||
let bytes = rmp_serde::to_vec_named(&snapshot).expect("serialize");
|
||||
let decoded: ObserverSnapshot = rmp_serde::from_slice(&bytes).expect("deserialize");
|
||||
|
||||
assert_eq!(decoded.version, PROTOCOL_VERSION);
|
||||
assert_eq!(decoded.tick, 42);
|
||||
assert_eq!(decoded.entities.len(), 1);
|
||||
assert_eq!(decoded.entities[0].entity_id, 1);
|
||||
@@ -171,18 +169,13 @@ fn all_fixtures_deserialize() {
|
||||
let bytes = fs::read(&path).unwrap_or_else(|_| panic!("read fixture {}", name));
|
||||
|
||||
if name.starts_with("snapshot_boundary") {
|
||||
// Boundary snapshot fixtures (#472): tick may exceed PROTOCOL_VERSION check
|
||||
// Boundary snapshot fixtures (#472)
|
||||
rmp_serde::from_slice::<ObserverSnapshot>(&bytes).unwrap_or_else(|e| {
|
||||
panic!("deserialize boundary snapshot fixture {}: {}", name, e)
|
||||
});
|
||||
} else if name.starts_with("snapshot") {
|
||||
let snap = rmp_serde::from_slice::<ObserverSnapshot>(&bytes)
|
||||
rmp_serde::from_slice::<ObserverSnapshot>(&bytes)
|
||||
.unwrap_or_else(|e| panic!("deserialize snapshot fixture {}: {}", name, e));
|
||||
assert_eq!(
|
||||
snap.version, PROTOCOL_VERSION,
|
||||
"fixture {} has wrong version",
|
||||
name
|
||||
);
|
||||
} else if name.starts_with("input_batch") {
|
||||
rmp_serde::from_slice::<Vec<PlayerInput>>(&bytes)
|
||||
.unwrap_or_else(|e| panic!("deserialize batch input fixture {}: {}", name, e));
|
||||
@@ -244,7 +237,6 @@ fn all_entity_kind_variants_roundtrip() {
|
||||
#[test]
|
||||
fn snapshot_v2_fields_roundtrip() {
|
||||
let snapshot = ObserverSnapshot {
|
||||
version: PROTOCOL_VERSION,
|
||||
tick: 100,
|
||||
game_time: GameTime {
|
||||
day: 3,
|
||||
@@ -311,7 +303,6 @@ fn snapshot_v2_fields_roundtrip() {
|
||||
let bytes = rmp_serde::to_vec_named(&snapshot).expect("serialize");
|
||||
let decoded: ObserverSnapshot = rmp_serde::from_slice(&bytes).expect("deserialize");
|
||||
|
||||
assert_eq!(decoded.version, PROTOCOL_VERSION);
|
||||
assert_eq!(decoded.game_time.day, 3);
|
||||
assert_eq!(decoded.game_time.time_of_day, 720);
|
||||
assert_eq!(decoded.game_time.day_phase, DayPhase::Evening);
|
||||
@@ -354,17 +345,6 @@ fn entity_to_bits_roundtrip() {
|
||||
}
|
||||
}
|
||||
|
||||
/// PROTOCOL_VERSION constant matches snapshot version field
|
||||
#[test]
|
||||
fn protocol_version_constant_matches_snapshot() {
|
||||
let snapshot = test_snapshot(0, vec![]);
|
||||
assert_eq!(snapshot.version, PROTOCOL_VERSION);
|
||||
assert_eq!(
|
||||
PROTOCOL_VERSION, 21,
|
||||
"bump this assertion when protocol version changes"
|
||||
);
|
||||
}
|
||||
|
||||
/// All FacingDirection variants round-trip
|
||||
#[test]
|
||||
fn all_facing_direction_variants_roundtrip() {
|
||||
@@ -381,7 +361,6 @@ fn all_facing_direction_variants_roundtrip() {
|
||||
|
||||
for dir in directions {
|
||||
let snapshot = ObserverSnapshot {
|
||||
version: PROTOCOL_VERSION,
|
||||
tick: 0,
|
||||
game_time: GameTime {
|
||||
day: 0,
|
||||
@@ -525,7 +504,6 @@ fn v5_payload_deserializes_into_v6_struct() {
|
||||
.expect("v5 payload should deserialize into v6 struct via serde(default)");
|
||||
|
||||
// New fields should get their defaults
|
||||
assert_eq!(decoded.version, 5, "version field preserved from v5");
|
||||
assert_eq!(decoded.tick, 42);
|
||||
assert_eq!(
|
||||
decoded.player_stance,
|
||||
@@ -717,23 +695,6 @@ fn verb_kind_confront_roundtrip() {
|
||||
assert_eq!(decoded.nearby_interactions[0].verbs[0].label, "Confront");
|
||||
}
|
||||
|
||||
/// CharacterArchetype enum round-trips through MessagePack (#422).
|
||||
/// Used in Phase 2 label relabeling — must survive the wire.
|
||||
#[test]
|
||||
fn all_character_archetype_variants_roundtrip() {
|
||||
let archetypes = [CharacterArchetype::Smuggler, CharacterArchetype::Detective];
|
||||
|
||||
for archetype in archetypes {
|
||||
let bytes = rmp_serde::to_vec_named(&archetype).expect("serialize");
|
||||
let decoded: CharacterArchetype = rmp_serde::from_slice(&bytes).expect("deserialize");
|
||||
assert_eq!(
|
||||
decoded, archetype,
|
||||
"CharacterArchetype::{:?} roundtrip failed",
|
||||
archetype
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// NearbyInteraction.contradicted=true round-trips through MessagePack (#422).
|
||||
/// Guards the contradiction flag survives serialization.
|
||||
#[test]
|
||||
@@ -1247,7 +1208,6 @@ fn v8_payload_deserializes_into_v9_struct() {
|
||||
let decoded: ObserverSnapshot = rmp_serde::from_slice(&bytes)
|
||||
.expect("v8 payload should deserialize into v9 struct via serde(default)");
|
||||
|
||||
assert_eq!(decoded.version, 8, "version field preserved from v8");
|
||||
assert_eq!(decoded.tick, 100);
|
||||
assert!(
|
||||
decoded.blocked_entities.is_empty(),
|
||||
@@ -1321,7 +1281,6 @@ fn v9_payload_deserializes_into_v10_struct() {
|
||||
let decoded: ObserverSnapshot = rmp_serde::from_slice(&bytes)
|
||||
.expect("v9 payload should deserialize into v10 struct via serde(default)");
|
||||
|
||||
assert_eq!(decoded.version, 9, "version field preserved from v9");
|
||||
assert_eq!(decoded.tick, 200);
|
||||
assert_eq!(
|
||||
decoded.rng_seed, None,
|
||||
@@ -1397,7 +1356,6 @@ fn v10_payload_deserializes_into_v11_struct() {
|
||||
let decoded: ObserverSnapshot = rmp_serde::from_slice(&bytes)
|
||||
.expect("v10 payload should deserialize into v11 struct via serde(default)");
|
||||
|
||||
assert_eq!(decoded.version, 10, "version field preserved from v10");
|
||||
assert_eq!(decoded.tick, 300);
|
||||
assert_eq!(decoded.visible_tiles.len(), 1);
|
||||
assert_eq!(
|
||||
@@ -1458,8 +1416,6 @@ fn serde_default_fields_fill_in_when_missing_from_wire() {
|
||||
let decoded: ObserverSnapshot =
|
||||
serde_json::from_value(minimal_json).expect("minimal JSON must deserialize");
|
||||
|
||||
// Version matches what was in the wire
|
||||
assert_eq!(decoded.version, 13);
|
||||
assert_eq!(decoded.tick, 42);
|
||||
assert_eq!(decoded.entities.len(), 1);
|
||||
|
||||
@@ -1492,28 +1448,6 @@ fn serde_default_fields_fill_in_when_missing_from_wire() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A snapshot with version != PROTOCOL_VERSION can be detected by checking
|
||||
/// the version field after deserialization (#232 compatibility checking).
|
||||
#[test]
|
||||
fn snapshot_version_mismatch_is_detectable() {
|
||||
let mut snapshot = test_snapshot(0, vec![]);
|
||||
let future_version: u8 = PROTOCOL_VERSION + 1;
|
||||
snapshot.version = future_version;
|
||||
|
||||
let bytes = rmp_serde::to_vec_named(&snapshot).expect("serialize");
|
||||
let decoded: ObserverSnapshot = rmp_serde::from_slice(&bytes).expect("deserialize");
|
||||
|
||||
// The version field faithfully preserves the value — caller detects mismatch
|
||||
assert_eq!(
|
||||
decoded.version, future_version,
|
||||
"version field must survive round-trip unchanged"
|
||||
);
|
||||
assert_ne!(
|
||||
decoded.version, PROTOCOL_VERSION,
|
||||
"client should detect this as a version mismatch"
|
||||
);
|
||||
}
|
||||
|
||||
/// tell_state=None is skipped in msgpack serialization (skip_serializing_if).
|
||||
/// A snapshot with tell_state=None produces fewer bytes than one with
|
||||
/// tell_state=Some(Nervous) — demonstrates the skip_serializing_if contract.
|
||||
@@ -1627,19 +1561,6 @@ fn all_verb_kind_variants_roundtrip_v232() {
|
||||
}
|
||||
}
|
||||
|
||||
/// PROTOCOL_VERSION u8 type fits in one byte — wire overhead is minimal (#232).
|
||||
/// This guards against accidental widening of the version type.
|
||||
#[test]
|
||||
fn protocol_version_fits_in_u8() {
|
||||
// u8 max is 255 — enough for ~242 more protocol iterations.
|
||||
// If PROTOCOL_VERSION ever reaches 200, consider migrating to u16.
|
||||
assert!(
|
||||
PROTOCOL_VERSION <= 200,
|
||||
"PROTOCOL_VERSION={} is approaching u8 saturation; consider widening the type",
|
||||
PROTOCOL_VERSION
|
||||
);
|
||||
}
|
||||
|
||||
/// NearbyInteraction.object_type round-trips through MessagePack (#422).
|
||||
/// Verifies object_type=Some(Container) survives the wire.
|
||||
#[test]
|
||||
@@ -1687,7 +1608,6 @@ fn fixture_snapshot_minimal_fields() {
|
||||
let snap: ObserverSnapshot =
|
||||
rmp_serde::from_slice(&bytes).expect("deserialize snapshot_minimal");
|
||||
|
||||
assert_eq!(snap.version, PROTOCOL_VERSION, "protocol version mismatch");
|
||||
assert_eq!(snap.tick, 0, "tick should be 0");
|
||||
assert_eq!(snap.entities.len(), 1, "should have exactly 1 entity");
|
||||
assert_eq!(snap.entities[0].entity_id, 1);
|
||||
@@ -1707,7 +1627,6 @@ fn fixture_snapshot_full_fields() {
|
||||
let bytes = read_named_fixture("snapshot_full");
|
||||
let snap: ObserverSnapshot = rmp_serde::from_slice(&bytes).expect("deserialize snapshot_full");
|
||||
|
||||
assert_eq!(snap.version, PROTOCOL_VERSION, "protocol version mismatch");
|
||||
assert_eq!(snap.tick, 42, "tick should be 42");
|
||||
|
||||
// Monologue
|
||||
|
||||
@@ -108,12 +108,10 @@ fn no_deviation_component_does_not_produce_deviation_tell() {
|
||||
/// Set up a minimal gauntlet-based app with storyteller plugin running.
|
||||
#[cfg(feature = "gauntlet")]
|
||||
fn build_storyteller_app() -> App {
|
||||
use settled_reach_server::{
|
||||
bridge::types::CharacterArchetype, simulation::SimulationPlugin, test_world,
|
||||
};
|
||||
use settled_reach_server::{simulation::SimulationPlugin, test_world};
|
||||
let mut app = App::new();
|
||||
app.add_plugins(SimulationPlugin { seed: 0 });
|
||||
test_world::setup_gauntlet(&mut app, CharacterArchetype::default());
|
||||
test_world::setup_gauntlet(&mut app);
|
||||
app
|
||||
}
|
||||
|
||||
|
||||
@@ -1,328 +0,0 @@
|
||||
//! v0.1 integration playthrough test (#593, D-027).
|
||||
//!
|
||||
//! Validates the full session lifecycle from StartupMessage to storyteller activation:
|
||||
//! D-027 criterion 1: player sees opening monologue on session start
|
||||
//! D-027 criterion 4: NPC RoutineDeviation tell observable after triangle activation
|
||||
//! D-036: news ticker headline visible in The Last Shift zone
|
||||
//!
|
||||
//! Test structure:
|
||||
//! - `test_smuggler_opening_monologue`: asserts smuggler pool fires on tick 1 (runs now)
|
||||
//! - `test_detective_opening_monologue`: asserts detective pool fires on tick 1 (runs now)
|
||||
//! - `test_v0_1_integration_playthrough`: full E2E proof (#[ignore] until #589, #591 land)
|
||||
//!
|
||||
//! Uses Layer 3 pattern: real server subprocess, TCP IPC, no mocks.
|
||||
//!
|
||||
//! Prerequisites to unblock:
|
||||
//! #589: escalate_tells_on_activation system (for RoutineDeviation assertion)
|
||||
//! #591: TickerPool + current_ticker in snapshot (for ticker assertion)
|
||||
|
||||
use settled_reach_server::bridge::framing::{read_framed, write_framed};
|
||||
use settled_reach_server::bridge::types::*;
|
||||
use settled_reach_server::npc::tell_state::TellCategory;
|
||||
use std::io::{BufRead, BufReader, BufWriter};
|
||||
use std::net::TcpStream;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Timeout for the server to emit LISTENING:{port} on stdout.
|
||||
const LISTEN_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
/// Timeout for any individual snapshot read.
|
||||
const SNAPSHOT_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Server lifecycle helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
struct TestServer {
|
||||
child: std::process::Child,
|
||||
reader: BufReader<TcpStream>,
|
||||
writer: BufWriter<TcpStream>,
|
||||
}
|
||||
|
||||
impl TestServer {
|
||||
/// Boot the server binary in test mode (gauntlet), send StartupMessage,
|
||||
/// return a connected handle ready to receive snapshots.
|
||||
fn boot_gauntlet(world_seed: u64, archetype: CharacterArchetype) -> Self {
|
||||
let server_bin = env!("CARGO_BIN_EXE_settled-reach-server");
|
||||
let mut child = Command::new(server_bin)
|
||||
.args(["--test-mode", "--port", "0"])
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.expect("failed to spawn server binary");
|
||||
|
||||
let stdout = child.stdout.take().expect("stdout not captured");
|
||||
let mut stdout_reader = BufReader::new(stdout);
|
||||
|
||||
// Parse LISTENING:{port}
|
||||
let port = {
|
||||
let deadline = Instant::now() + LISTEN_TIMEOUT;
|
||||
let mut line = String::new();
|
||||
loop {
|
||||
line.clear();
|
||||
match stdout_reader.read_line(&mut line) {
|
||||
Ok(0) => panic!("server stdout closed before LISTENING signal"),
|
||||
Ok(_) => {
|
||||
let trimmed = line.trim();
|
||||
if let Some(port_str) = trimmed.strip_prefix("LISTENING:") {
|
||||
break port_str.parse::<u16>().expect("invalid port");
|
||||
}
|
||||
}
|
||||
Err(e) => panic!("failed to read server stdout: {}", e),
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"timed out waiting for LISTENING signal"
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let addr = format!("127.0.0.1:{}", port);
|
||||
let stream = TcpStream::connect(&addr).expect("client connect");
|
||||
stream
|
||||
.set_read_timeout(Some(SNAPSHOT_TIMEOUT))
|
||||
.expect("set timeout");
|
||||
let mut reader = BufReader::new(stream.try_clone().expect("clone stream"));
|
||||
let mut writer = BufWriter::new(stream);
|
||||
|
||||
// Protocol handshake
|
||||
let hf = read_framed(&mut reader)
|
||||
.expect("read handshake")
|
||||
.expect("connection closed");
|
||||
let _: HandshakeMessage = rmp_serde::from_slice(&hf).expect("deserialize handshake");
|
||||
|
||||
// StartupMessage with chosen archetype
|
||||
let startup = StartupMessage {
|
||||
world_seed,
|
||||
character_archetype: archetype,
|
||||
};
|
||||
let startup_payload = rmp_serde::to_vec_named(&startup).expect("serialize startup");
|
||||
write_framed(&mut writer, &startup_payload).expect("send startup");
|
||||
|
||||
TestServer {
|
||||
child,
|
||||
reader,
|
||||
writer,
|
||||
}
|
||||
}
|
||||
|
||||
/// Send a tick's worth of inputs (empty = idle tick) and read back one snapshot.
|
||||
fn tick(&mut self, inputs: Vec<PlayerInput>) -> ObserverSnapshot {
|
||||
let payload = rmp_serde::to_vec_named(&inputs).expect("serialize inputs");
|
||||
write_framed(&mut self.writer, &payload).expect("send inputs");
|
||||
|
||||
let frame = read_framed(&mut self.reader)
|
||||
.expect("read snapshot frame")
|
||||
.expect("server closed connection");
|
||||
rmp_serde::from_slice(&frame).expect("deserialize snapshot")
|
||||
}
|
||||
|
||||
/// Send a debug command and get the next snapshot.
|
||||
fn send_debug(&mut self, cmd: DebugCommandKind) -> ObserverSnapshot {
|
||||
self.tick(vec![PlayerInput {
|
||||
tick: 0,
|
||||
action: PlayerAction::DebugCommand(cmd),
|
||||
}])
|
||||
}
|
||||
|
||||
fn shutdown(mut self) {
|
||||
drop(self.reader);
|
||||
drop(self.writer);
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
match self.child.try_wait() {
|
||||
Ok(Some(_)) => break,
|
||||
Ok(None) => {
|
||||
if Instant::now() > deadline {
|
||||
self.child.kill().ok();
|
||||
self.child.wait().ok();
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
Err(_) => {
|
||||
self.child.kill().ok();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests: opening monologue archetype partitioning (runs now — no #[ignore])
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn test_smuggler_opening_monologue() {
|
||||
// Boot with Smuggler, advance 1 tick, assert opening monologue fires from smuggler pool.
|
||||
// Monologue IDs from smuggler/opening.yaml start with "pc-smuggler_".
|
||||
// This verifies: archetype → MonologueState.character → pool selection (D-032, #587, #595).
|
||||
let mut server = TestServer::boot_gauntlet(12345, CharacterArchetype::Smuggler);
|
||||
let snapshot = server.tick(vec![PlayerInput {
|
||||
tick: 0,
|
||||
action: PlayerAction::MoveNorth,
|
||||
}]);
|
||||
|
||||
assert_eq!(
|
||||
snapshot.version, PROTOCOL_VERSION,
|
||||
"protocol version mismatch"
|
||||
);
|
||||
|
||||
let monologue = snapshot.current_monologue;
|
||||
assert!(
|
||||
monologue.is_some(),
|
||||
"Smuggler session must fire opening monologue on tick 1 (enter_location trigger, D-027 criterion 1). \
|
||||
Got None — either MonologueState.character is wrong or opening.yaml lines are not loaded."
|
||||
);
|
||||
|
||||
let monologue = monologue.unwrap();
|
||||
assert!(
|
||||
monologue.id.starts_with("pc-smuggler_"),
|
||||
"Smuggler opening monologue ID must start with 'pc-smuggler_' (D-032 hard partition). \
|
||||
Got id='{}'. Likely cause: MonologueState.character defaulted to 'detective' despite Smuggler archetype.",
|
||||
monologue.id
|
||||
);
|
||||
|
||||
server.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_detective_opening_monologue() {
|
||||
// Boot with Detective, advance 1 tick, assert opening monologue fires from detective pool.
|
||||
// Monologue IDs from detective/opening.yaml start with "pc-detective_".
|
||||
let mut server = TestServer::boot_gauntlet(12345, CharacterArchetype::Detective);
|
||||
let snapshot = server.tick(vec![PlayerInput {
|
||||
tick: 0,
|
||||
action: PlayerAction::MoveNorth,
|
||||
}]);
|
||||
|
||||
assert_eq!(
|
||||
snapshot.version, PROTOCOL_VERSION,
|
||||
"protocol version mismatch"
|
||||
);
|
||||
|
||||
let monologue = snapshot.current_monologue;
|
||||
assert!(
|
||||
monologue.is_some(),
|
||||
"Detective session must fire opening monologue on tick 1 (enter_location trigger). \
|
||||
Got None — either MonologueState.character is wrong or opening.yaml lines are not loaded."
|
||||
);
|
||||
|
||||
let monologue = monologue.unwrap();
|
||||
assert!(
|
||||
monologue.id.starts_with("pc-detective_"),
|
||||
"Detective opening monologue ID must start with 'pc-detective_' (D-032 hard partition). \
|
||||
Got id='{}'. Likely cause: archetype defaulted incorrectly.",
|
||||
monologue.id
|
||||
);
|
||||
|
||||
server.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_smuggler_and_detective_get_different_opening_monologue_ids() {
|
||||
// Regression guard: two sessions with different archetypes must never produce
|
||||
// the same monologue ID on tick 1. If they do, D-032 partitioning is broken.
|
||||
let mut smug = TestServer::boot_gauntlet(12345, CharacterArchetype::Smuggler);
|
||||
let smug_snap = smug.tick(vec![]);
|
||||
let smug_id = smug_snap
|
||||
.current_monologue
|
||||
.as_ref()
|
||||
.map(|m| m.id.clone())
|
||||
.unwrap_or_default();
|
||||
smug.shutdown();
|
||||
|
||||
let mut det = TestServer::boot_gauntlet(12345, CharacterArchetype::Detective);
|
||||
let det_snap = det.tick(vec![]);
|
||||
let det_id = det_snap
|
||||
.current_monologue
|
||||
.as_ref()
|
||||
.map(|m| m.id.clone())
|
||||
.unwrap_or_default();
|
||||
det.shutdown();
|
||||
|
||||
assert_ne!(
|
||||
smug_id, det_id,
|
||||
"Smuggler and Detective must fire different opening monologue IDs (D-032). \
|
||||
Both got '{}' — pool partitioning is broken.",
|
||||
smug_id
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Full v0.1 playthrough proof (blocked until #589 + #591 land)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
#[ignore = "blocked: TeleportToLocation debug command not implemented (needs location tile_bounds from ContentStore). Criteria 1+2 covered by non-ignored tests above."]
|
||||
fn test_v0_1_integration_playthrough() {
|
||||
// Full E2E proof per D-027 v0.1 success criteria:
|
||||
// 1. Opening monologue fires in correct character pool
|
||||
// 2. After activation, anchor NPC shows RoutineDeviation tell
|
||||
// 3. News ticker visible when player is in "bar" zone
|
||||
// (Manual criterion: walk to terminal, observe Kael, see fog-and-tension)
|
||||
|
||||
let mut server = TestServer::boot_gauntlet(12345, CharacterArchetype::Smuggler);
|
||||
|
||||
// === Criterion 1: Opening monologue (Smuggler) ===
|
||||
let tick1 = server.tick(vec![]);
|
||||
let monologue = tick1
|
||||
.current_monologue
|
||||
.expect("Opening monologue must fire on tick 1");
|
||||
assert!(
|
||||
monologue.id.starts_with("pc-smuggler_"),
|
||||
"Tick-1 monologue must be from smuggler pool. Got: {}",
|
||||
monologue.id
|
||||
);
|
||||
|
||||
// === Skip to contamination phase (fast-forward via debug) ===
|
||||
let _skip_snap = server.send_debug(DebugCommandKind::SkipToContamination);
|
||||
let _contaminate = server.send_debug(DebugCommandKind::ForceContaminationActivate);
|
||||
|
||||
// === Run ticks and watch for triangle activation ===
|
||||
let mut triangle_crisis_observed = false;
|
||||
for _ in 0..20 {
|
||||
let snap = server.tick(vec![]);
|
||||
if !snap.triangle_crisis_events.is_empty() {
|
||||
triangle_crisis_observed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
triangle_crisis_observed,
|
||||
"Triangle crisis event must appear within 20 ticks after contamination activation (#589)"
|
||||
);
|
||||
|
||||
// === Criterion 2 (D-027 criterion 4): RoutineDeviation tell visible ===
|
||||
// After activation, at least one NPC must show RoutineDeviation tell in the snapshot.
|
||||
let mut deviation_observed = false;
|
||||
for _ in 0..5 {
|
||||
let snap = server.tick(vec![]);
|
||||
if snap
|
||||
.entities
|
||||
.iter()
|
||||
.any(|e| e.tell_state == Some(TellCategory::RoutineDeviation))
|
||||
{
|
||||
deviation_observed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
deviation_observed,
|
||||
"After triangle activation, at least one NPC must show RoutineDeviation tell (D-027 criterion 4, #589)"
|
||||
);
|
||||
|
||||
// === Criterion 3 (D-036): News ticker visible in bar zone ===
|
||||
// Teleport to The Last Shift bar zone and check current_ticker is Some.
|
||||
let _teleport = server.send_debug(DebugCommandKind::TeleportToLocation(
|
||||
"the-last-shift".into(),
|
||||
));
|
||||
let bar_snap = server.tick(vec![]);
|
||||
assert!(
|
||||
bar_snap.current_ticker.is_some(),
|
||||
"current_ticker must be Some when player is in 'the-last-shift' zone (D-036, #591)"
|
||||
);
|
||||
|
||||
server.shutdown();
|
||||
}
|
||||
+3
-1
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
# tests/run-all: Run all test suites in order (D-030)
|
||||
# Invokes run-rust, run-godot, run-ipc-fixtures, run-ipc-protocol, run-ipc-integration.
|
||||
# Invokes run-rust, run-godot, run-ipc-fixtures, run-ipc-protocol,
|
||||
# run-ipc-integration, run-visual, run-atlas-determinism.
|
||||
# Exit: 0 = all suites pass, non-zero = any suite failed
|
||||
# Stdout: {"suite":"all","total":N,"passed":N,"failed":N,"duration_ms":N,"suites":[...]}
|
||||
set -euo pipefail
|
||||
@@ -26,6 +27,7 @@ SUITES=(
|
||||
run-ipc-protocol
|
||||
run-ipc-integration
|
||||
run-visual
|
||||
run-atlas-determinism
|
||||
)
|
||||
|
||||
START_MS=$(date +%s%3N)
|
||||
|
||||
Executable
+139
@@ -0,0 +1,139 @@
|
||||
#!/usr/bin/env bash
|
||||
# tests/run-atlas-determinism: Determinism smoke test for generate_atlas.py (#847)
|
||||
#
|
||||
# Imports generate_atlas as a Python module, calls process_body() twice with
|
||||
# seed=42 and dry_run=True, compares the returned markers dicts as JSON.
|
||||
# No wiki files are written or modified.
|
||||
#
|
||||
# Purpose: cheap guardrail against determinism regressions in terrain analysis,
|
||||
# city placement, A* road routing, infrastructure MST, and gate terminal
|
||||
# placement. GJ892f is a domed body (population=300, 1 city) — the smallest
|
||||
# well-exercised case in the atlas pipeline.
|
||||
#
|
||||
# Spec ref: #847
|
||||
# Exit: 0 = deterministic (pass), non-zero = failure
|
||||
# Stdout: {"suite":"atlas-determinism","total":1,"passed":N,"failed":N,"duration_ms":N}
|
||||
set -euo pipefail
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
START_MS=$(date +%s%3N)
|
||||
|
||||
# Write the comparison script to a real file so that the generate_atlas venv
|
||||
# bootstrap (os.execv) can re-exec it from the venv Python when needed.
|
||||
# A heredoc (python3 - <<'EOF') does not work after os.execv because stdin
|
||||
# has already been consumed.
|
||||
HELPER=$(mktemp /tmp/atlas_det_helper.XXXXXX.py)
|
||||
trap "rm -f '$HELPER'" EXIT
|
||||
|
||||
cat > "$HELPER" << 'PYEOF'
|
||||
"""Atlas determinism helper — called by tests/run-atlas-determinism (#847).
|
||||
|
||||
Imports generate_atlas as a module and calls process_body() twice with
|
||||
dry_run=True. Compares the returned markers dicts as JSON. Exits 0 if
|
||||
identical, 1 if they differ, 2 on setup/import failure.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(os.environ["SR_REPO_ROOT"])
|
||||
sys.path.insert(0, str(REPO_ROOT / "tooling" / "planet-gen"))
|
||||
|
||||
try:
|
||||
import generate_atlas
|
||||
except ImportError as e:
|
||||
print(f"SKIP: generate_atlas import failed (missing deps?): {e}", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
|
||||
DB_PATH = REPO_ROOT / "server" / "data" / "systems.db"
|
||||
BODY_ID = "GJ892f" # domed, pop=300 → exactly 1 city; minimal and fast
|
||||
SEED = 42
|
||||
|
||||
if not DB_PATH.exists():
|
||||
print(f"SKIP: systems.db not found: {DB_PATH}", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
|
||||
conn = sqlite3.connect(str(DB_PATH))
|
||||
conn.execute("PRAGMA foreign_keys=ON")
|
||||
row = conn.execute("""
|
||||
SELECT b.body_id, b.system_id, b.terrain_reference, b.population,
|
||||
b.settlement_pattern, b.planet_class, b.economic_role,
|
||||
COALESCE(b.cultural_corridor, s.cultural_corridor)
|
||||
FROM bodies b JOIN star_systems s ON b.system_id = s.system_id
|
||||
WHERE b.body_id = ?
|
||||
""", (BODY_ID,)).fetchone()
|
||||
conn.close()
|
||||
|
||||
if not row:
|
||||
print(f"SKIP: {BODY_ID} not found in systems.db", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
|
||||
body_info = dict(zip(
|
||||
("body_id", "system_id", "terrain_reference", "population",
|
||||
"settlement_pattern", "planet_class", "economic_role", "cultural_corridor"),
|
||||
row,
|
||||
))
|
||||
body_info["population"] = body_info["population"] or 0
|
||||
|
||||
kwargs = dict(
|
||||
body_info=body_info,
|
||||
seed=SEED,
|
||||
noise_factor=0.25,
|
||||
dry_run=True, # no files written
|
||||
force=True, # skip the already-populated check
|
||||
verbose=False,
|
||||
)
|
||||
|
||||
a = generate_atlas.process_body(**kwargs)
|
||||
b = generate_atlas.process_body(**kwargs)
|
||||
|
||||
if a["status"] != "generated":
|
||||
print(f"FAIL: run 1 status={a['status']} — {a.get('message', '')}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
if b["status"] != "generated":
|
||||
print(f"FAIL: run 2 status={b['status']} — {b.get('message', '')}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
json_a = json.dumps(a["markers"], indent=2)
|
||||
json_b = json.dumps(b["markers"], indent=2)
|
||||
|
||||
if json_a == json_b:
|
||||
print(f"PASS: {BODY_ID} markers identical on two runs (seed={SEED})", file=sys.stderr)
|
||||
sys.exit(0)
|
||||
else:
|
||||
import difflib
|
||||
diff = "\n".join(list(difflib.unified_diff(
|
||||
json_a.splitlines(), json_b.splitlines(), lineterm="",
|
||||
fromfile="run1", tofile="run2",
|
||||
))[:40])
|
||||
print(f"FAIL: {BODY_ID} markers differ between run 1 and run 2 (seed={SEED})", file=sys.stderr)
|
||||
print(diff, file=sys.stderr)
|
||||
sys.exit(1)
|
||||
PYEOF
|
||||
|
||||
set +e
|
||||
SR_REPO_ROOT="$REPO_ROOT" python3 "$HELPER" 2>&1 >&2
|
||||
EXIT_CODE=$?
|
||||
set -e
|
||||
|
||||
END_MS=$(date +%s%3N)
|
||||
DURATION_MS=$((END_MS - START_MS))
|
||||
|
||||
# Exit code 2 = setup failure / missing deps → count as 0 tests (skip, not fail)
|
||||
if [[ $EXIT_CODE -eq 0 ]]; then
|
||||
PASSED=1; FAILED=0; TOTAL=1
|
||||
elif [[ $EXIT_CODE -eq 2 ]]; then
|
||||
PASSED=0; FAILED=0; TOTAL=0
|
||||
echo " [atlas-determinism] SKIPPED (import failure or missing DB)" >&2
|
||||
else
|
||||
PASSED=0; FAILED=1; TOTAL=1
|
||||
fi
|
||||
|
||||
printf '{"suite":"atlas-determinism","total":%d,"passed":%d,"failed":%d,"duration_ms":%d}\n' \
|
||||
"$TOTAL" "$PASSED" "$FAILED" "$DURATION_MS"
|
||||
|
||||
# Exit code 2 = venv/DB missing → treated as skip, not failure (exit 0 for run-all).
|
||||
# Exit code 1 = determinism failure → exit 1 to fail CI.
|
||||
[[ $EXIT_CODE -eq 2 ]] && exit 0 || exit $EXIT_CODE
|
||||
@@ -0,0 +1,154 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
check-systems-db-stamp — verify that server/data/systems.db is up to date.
|
||||
|
||||
Reads the meta table from systems.db and checks that the stored SHA-1 of each
|
||||
generator's source file(s) matches the current file content on disk.
|
||||
|
||||
Exit codes:
|
||||
0 — DB is stamped and all generator SHAs match current sources
|
||||
1 — DB is stale, has an unknown generator, or references a missing source file
|
||||
2 — DB does not have a meta table (treat as unstamped — run make regen-db)
|
||||
|
||||
Usage (called by .config/hooks/pre-push):
|
||||
tooling/check-systems-db-stamp
|
||||
|
||||
Usage (interactive):
|
||||
tooling/check-systems-db-stamp --verbose
|
||||
|
||||
Decision refs: #855 (generator versioning), #857 (pre-push hook)
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import sqlite3
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
DB_PATH = REPO_ROOT / "server" / "data" / "systems.db"
|
||||
|
||||
# Maps generator_name (as stored in meta.generator_name) to the source
|
||||
# file(s) whose SHA is stamped. The SHA is computed as SHA-1 of the
|
||||
# concatenated bytes of all files in sorted order.
|
||||
#
|
||||
# import_economics' source set includes the Rust generate_brands binary it now
|
||||
# invokes as a subroutine (#136 review T2/H3). Keep this list in sync with
|
||||
# IMPORT_ECONOMICS_SOURCES in tooling/economy-db/import_economics.py.
|
||||
GENERATOR_SOURCES: dict[str, list[Path]] = {
|
||||
"import_economics": [
|
||||
REPO_ROOT / "tooling" / "economy-db" / "import_economics.py",
|
||||
REPO_ROOT / "server" / "src" / "bin" / "generate_brands" / "main.rs",
|
||||
REPO_ROOT / "server" / "src" / "bin" / "generate_brands" / "names.rs",
|
||||
REPO_ROOT / "tooling" / "generate-brands",
|
||||
],
|
||||
"generate_atlas": [
|
||||
REPO_ROOT / "tooling" / "planet-gen" / "generate_atlas.py",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def file_sha1(*paths: Path) -> str:
|
||||
"""SHA-1 of concatenated file contents (sorted paths).
|
||||
|
||||
Missing files raise FileNotFoundError rather than silently contributing
|
||||
an empty-string hash (H2): a ghost SHA could mask real breakage when
|
||||
stored and current SHAs converge on the empty-bytes digest.
|
||||
"""
|
||||
h = hashlib.sha1()
|
||||
for p in sorted(paths):
|
||||
if not p.exists():
|
||||
raise FileNotFoundError(f"generator source not found: {p}")
|
||||
h.update(p.read_bytes())
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def check(verbose: bool = False) -> int:
|
||||
"""Return exit code: 0 = fresh, 1 = stale, 2 = no meta table."""
|
||||
if not DB_PATH.exists():
|
||||
if verbose:
|
||||
print(f"check-systems-db-stamp: {DB_PATH} not found — skipping check")
|
||||
return 0
|
||||
|
||||
try:
|
||||
conn = sqlite3.connect(str(DB_PATH))
|
||||
rows = conn.execute(
|
||||
"SELECT generator_name, generator_sha FROM meta"
|
||||
).fetchall()
|
||||
conn.close()
|
||||
except sqlite3.OperationalError:
|
||||
# meta table does not exist
|
||||
if verbose:
|
||||
print("check-systems-db-stamp: no meta table — systems.db has not been stamped")
|
||||
print(" Run: make regen-db")
|
||||
return 2
|
||||
|
||||
if not rows:
|
||||
if verbose:
|
||||
print("check-systems-db-stamp: meta table is empty — systems.db has not been stamped")
|
||||
print(" Run: make regen-db")
|
||||
return 2
|
||||
|
||||
stale: list[str] = []
|
||||
unknown: list[str] = []
|
||||
for generator_name, stored_sha in rows:
|
||||
sources = GENERATOR_SOURCES.get(generator_name)
|
||||
if sources is None:
|
||||
# Unknown generator — fail closed (T6). A future branch adding a
|
||||
# new generator without registering it here must update this map
|
||||
# before the check will pass, preventing the "silent no-op" trap.
|
||||
unknown.append(generator_name)
|
||||
continue
|
||||
try:
|
||||
current_sha = file_sha1(*sources)
|
||||
except FileNotFoundError as exc:
|
||||
# Source file moved/deleted — explicit failure instead of
|
||||
# silent empty-hash (H2).
|
||||
print(
|
||||
f"check-systems-db-stamp: BROKEN — {generator_name}: {exc}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
if current_sha != stored_sha:
|
||||
stale.append(generator_name)
|
||||
if verbose:
|
||||
print(
|
||||
f"check-systems-db-stamp: STALE — {generator_name}"
|
||||
f"\n stored: {stored_sha}"
|
||||
f"\n current: {current_sha}"
|
||||
)
|
||||
|
||||
if unknown:
|
||||
print(
|
||||
"check-systems-db-stamp: UNKNOWN generator(s) in meta table: "
|
||||
f"{unknown}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
print(
|
||||
" Update GENERATOR_SOURCES in tooling/check-systems-db-stamp to "
|
||||
"register them before pushing.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
|
||||
if stale:
|
||||
if not verbose:
|
||||
print(
|
||||
"systems.db is stale — run `make regen-db` before pushing.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
print(f" Stale generators: {stale}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
if verbose:
|
||||
print(f"check-systems-db-stamp: OK — {len(rows)} generator(s) up to date")
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> None:
|
||||
verbose = "--verbose" in sys.argv or "-v" in sys.argv
|
||||
sys.exit(check(verbose=verbose))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user