small-text-mmo-engine 0.41.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- config_schema.py +443 -0
- config_write.py +247 -0
- dashboard.html +3679 -0
- harness/__init__.py +3 -0
- harness/__main__.py +98 -0
- harness/bridge.py +241 -0
- harness/mcp_stdio.py +485 -0
- ml/__init__.py +0 -0
- ml/arena_probe.py +457 -0
- ml/balance.py +2650 -0
- ml/conductor/__init__.py +36 -0
- ml/conductor/churn.py +206 -0
- ml/conductor/conductor.py +457 -0
- ml/conductor/metrics.py +124 -0
- ml/conductor/mixer.py +113 -0
- ml/conductor/pbt.py +157 -0
- ml/conductor/registry.py +384 -0
- ml/conductor/reload.py +75 -0
- ml/conductor/runners.py +70 -0
- ml/conductor/soak.py +542 -0
- ml/conductor/soak_server_config.json +15 -0
- ml/conductor/supervisor.py +873 -0
- ml/diversity.py +214 -0
- ml/dungeon_generator.py +272 -0
- ml/generalist.py +274 -0
- ml/guild_probe.py +342 -0
- ml/launcher.py +314 -0
- ml/league.py +283 -0
- ml/market_equilibrium.py +283 -0
- ml/ml_best.json +11514 -0
- ml/ml_botfarm.py +564 -0
- ml/ml_client.py +350 -0
- ml/ml_config.json +15 -0
- ml/ml_env.py +3234 -0
- ml/modes/__init__.py +242 -0
- ml/modes/arena.py +64 -0
- ml/open_mode.py +231 -0
- ml/plugin_inventory.py +175 -0
- ml/plugins/__init__.py +518 -0
- ml/plugins/linear.py +52 -0
- ml/plugins/scripted.py +1060 -0
- ml/plugins/torch_plugin.py +76 -0
- ml/repro.py +170 -0
- ml/reward_dsl.py +373 -0
- ml/runlog.py +516 -0
- ml/structured_log.py +52 -0
- ml/telemetry.py +177 -0
- ml/transcript.py +69 -0
- ml/versioning.py +64 -0
- plugins/README.md +52 -0
- plugins/redteam.py +213 -0
- server.py +15477 -0
- server_config.json +107 -0
- small_text_mmo_engine-0.41.1.dist-info/METADATA +273 -0
- small_text_mmo_engine-0.41.1.dist-info/RECORD +73 -0
- small_text_mmo_engine-0.41.1.dist-info/WHEEL +5 -0
- small_text_mmo_engine-0.41.1.dist-info/entry_points.txt +2 -0
- small_text_mmo_engine-0.41.1.dist-info/licenses/LICENSE +201 -0
- small_text_mmo_engine-0.41.1.dist-info/licenses/THIRD_PARTY_NOTICES.md +26 -0
- small_text_mmo_engine-0.41.1.dist-info/top_level.txt +8 -0
- start.py +447 -0
- torch_agents/__init__.py +0 -0
- torch_agents/dqn_agent.py +1079 -0
- torch_agents/eval.py +431 -0
- torch_agents/torch_farm.py +597 -0
- tui/__init__.py +30 -0
- tui/__main__.py +13 -0
- tui/app.py +357 -0
- tui/panels.py +1635 -0
- tui/snapshot.py +181 -0
- tui/tabs.py +73 -0
- uplot.min.js +2 -0
- world.json +966 -0
config_schema.py
ADDED
|
@@ -0,0 +1,443 @@
|
|
|
1
|
+
"""Declarative schema for the two operator-editable config files (#63).
|
|
2
|
+
|
|
3
|
+
Neither loader declares a schema: `server.py::_apply_config` and
|
|
4
|
+
`ml/ml_env.py::_apply_ml_config` both coerce with `type(default)(value)`
|
|
5
|
+
and validate nothing else, so a negative tax rate or a 99999 dungeon floor
|
|
6
|
+
loads silently. The dashboard editor needs bounds and help text to render
|
|
7
|
+
and validate a form, and this is the only place those can live without
|
|
8
|
+
teaching the loaders something they do not already do.
|
|
9
|
+
|
|
10
|
+
Bounds are a floor for catching typos, not a balance opinion. Values here
|
|
11
|
+
are rejected only where they are structurally impossible (a negative count,
|
|
12
|
+
a percentage over 100, a growth rate below 1). Widening them is a tuning
|
|
13
|
+
decision and belongs to the operator.
|
|
14
|
+
|
|
15
|
+
Defaults are deliberately absent for server_config.json. The default for a
|
|
16
|
+
key is the module global it overrides, and duplicating those numbers here is
|
|
17
|
+
how a schema rots: `server.py` resolves them from `globals()`, so a default
|
|
18
|
+
can never drift from the code it came from.
|
|
19
|
+
|
|
20
|
+
The ML keys are the exception, and only because the server cannot resolve
|
|
21
|
+
them: reading ml_env's globals would import the whole env (and its torch
|
|
22
|
+
side) into the game server for six numbers. ML_DEFAULTS below is pinned
|
|
23
|
+
against ml_env by tests/test_config_editor.py, which fails if the module
|
|
24
|
+
moves.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
# ---------------------------------------------------------------------------
|
|
28
|
+
# Bounds + help. type is "int" or "float"; "list" keys take a bracketed
|
|
29
|
+
# list of numbers and are validated elementwise.
|
|
30
|
+
# ---------------------------------------------------------------------------
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _i(minimum, maximum, help_text, step=1):
|
|
34
|
+
return {
|
|
35
|
+
"type": "int",
|
|
36
|
+
"min": minimum,
|
|
37
|
+
"max": maximum,
|
|
38
|
+
"step": step,
|
|
39
|
+
"help": help_text,
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _f(minimum, maximum, help_text, step=0.01):
|
|
44
|
+
return {
|
|
45
|
+
"type": "float",
|
|
46
|
+
"min": minimum,
|
|
47
|
+
"max": maximum,
|
|
48
|
+
"step": step,
|
|
49
|
+
"help": help_text,
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _pct(help_text):
|
|
54
|
+
"""0-100 percentage; stored as a number, not a 0-1 fraction."""
|
|
55
|
+
return {"type": "float", "min": 0.0, "max": 100.0, "step": 0.5, "help": help_text}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _ratio(help_text):
|
|
59
|
+
"""0-1 fraction (tax rate, share of a pool)."""
|
|
60
|
+
return {"type": "float", "min": 0.0, "max": 1.0, "step": 0.01, "help": help_text}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _list(count, minimum, maximum, help_text):
|
|
64
|
+
return {
|
|
65
|
+
"type": "list",
|
|
66
|
+
"count": count,
|
|
67
|
+
"min": minimum,
|
|
68
|
+
"max": maximum,
|
|
69
|
+
"step": 1,
|
|
70
|
+
"help": help_text,
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# ---------------------------------------------------------------------------
|
|
75
|
+
# ---------------------------------------------------------------------------
|
|
76
|
+
|
|
77
|
+
SERVER_SCHEMA = {
|
|
78
|
+
"scoring": {
|
|
79
|
+
"ACTION_WINDOW": _i(
|
|
80
|
+
1, 500, "Actions scored per decision window; the agent's move horizon."
|
|
81
|
+
),
|
|
82
|
+
"MIN_HISTORY_FOR_VARIETY": _i(
|
|
83
|
+
0, 100, "Actions required before variety bonus counts."
|
|
84
|
+
),
|
|
85
|
+
"MIN_VARIETY": _ratio("Minimum action diversity for the variety bonus."),
|
|
86
|
+
"DIFFICULTY_K": _f(
|
|
87
|
+
0.0001, 1000.0, "Difficulty scaling constant for spawned mobs."
|
|
88
|
+
),
|
|
89
|
+
"DISCOVERY_POINTS": _i(0, 1000, "Score points for finding a new area."),
|
|
90
|
+
"DISCOVERY_XP": _i(0, 1000, "XP for finding a new area."),
|
|
91
|
+
"DEATH_PENALTY": _f(0.0, 1000.0, "Flat score penalty floor on death."),
|
|
92
|
+
"DEATH_GOLD_DROP_PCT": _pct(
|
|
93
|
+
"Share of carried gold dropped as a floor pile on death."
|
|
94
|
+
),
|
|
95
|
+
"DEATH_GOLD_LOST_PCT": _pct(
|
|
96
|
+
"Share of carried gold destroyed permanently on death."
|
|
97
|
+
),
|
|
98
|
+
"DEATH_SCORE_PER_GOLD_LOST": _f(
|
|
99
|
+
0.0, 100.0, "Extra score penalty per gold permanently lost."
|
|
100
|
+
),
|
|
101
|
+
"DEATH_ITEM_DROP_PCT": _pct("Share of carried items dropped on death."),
|
|
102
|
+
"SCORE_ENTRY_MAX": _i(1, 1000000, "Leaderboard entries retained."),
|
|
103
|
+
"SCORE_ENTRY_TTL_SECONDS": _i(
|
|
104
|
+
60, 31536000, "Seconds before a leaderboard entry expires."
|
|
105
|
+
),
|
|
106
|
+
},
|
|
107
|
+
"economy": {
|
|
108
|
+
"TAX_RATE": _ratio("Market tax share of each sale."),
|
|
109
|
+
"TAX_MINIMUM": _i(0, 10000, "Flat minimum tax per sale, in gold."),
|
|
110
|
+
"TREASURY_RESERVE": _f(
|
|
111
|
+
0, 1000000, "Gold the treasury banks before sinking the rest."
|
|
112
|
+
),
|
|
113
|
+
"TRAINING_DAMAGE_FRACTION": _f(
|
|
114
|
+
0,
|
|
115
|
+
1000000,
|
|
116
|
+
"Share of NPC damage trainees take; 1.0 or more disables dampening.",
|
|
117
|
+
),
|
|
118
|
+
"MARKET_ORDER_SLOTS_BASE": _i(
|
|
119
|
+
1, 200, "Base sell order slots available to every character."
|
|
120
|
+
),
|
|
121
|
+
"MARKET_SLOT_PRICE_BASE": _i(
|
|
122
|
+
1, 100000, "Gold cost of one extra market slot at base."
|
|
123
|
+
),
|
|
124
|
+
"MARKET_ORDER_TTL_SECONDS": _i(
|
|
125
|
+
60, 31536000, "Seconds a sell order stays listed."
|
|
126
|
+
),
|
|
127
|
+
"BROKER_FEE_PCT": _pct("Agent-to-agent listing fee, percent."),
|
|
128
|
+
"RELIST_FEE_PCT": _pct("Fee to relist an expired order, percent."),
|
|
129
|
+
"INVENTORY_CAP": _i(1, 500, "Item slots carried before the bag is full."),
|
|
130
|
+
"AMMO_EXEMPT_COUNT": _i(
|
|
131
|
+
0, 500, "Ammo stacks that never count against the inventory cap."
|
|
132
|
+
),
|
|
133
|
+
"STARTING_GOLD": _i(0, 1000000, "Gold every new character begins with."),
|
|
134
|
+
"MOB_EXTRA_SPAWNS": _i(
|
|
135
|
+
0, 20, "Extra hostile instances of each mob template (startup-only)."
|
|
136
|
+
),
|
|
137
|
+
},
|
|
138
|
+
"commissions": {
|
|
139
|
+
"COMMISSION_MAX_XP": _i(
|
|
140
|
+
0, 100000, "Largest XP reward a single commission may offer."
|
|
141
|
+
),
|
|
142
|
+
"COMMISSION_MAX_KILLS": _i(
|
|
143
|
+
0, 10000, "Largest kill count a single commission may require."
|
|
144
|
+
),
|
|
145
|
+
"COMMISSION_MAX_OPEN_PER_POSTER": _i(
|
|
146
|
+
1, 100, "Open commissions per poster, per quest type."
|
|
147
|
+
),
|
|
148
|
+
"COMMISSION_COLLAB_CAP": _i(
|
|
149
|
+
0, 10000, "Contributors allowed on one shared commission."
|
|
150
|
+
),
|
|
151
|
+
"COMMISSION_TTL_SECONDS": _i(
|
|
152
|
+
60, 31536000, "Seconds before an unfinished commission expires."
|
|
153
|
+
),
|
|
154
|
+
},
|
|
155
|
+
"guilds": {
|
|
156
|
+
"GUILD_MAX_MEMBERS": _i(1, 1000, "Characters allowed in one guild."),
|
|
157
|
+
"GUILD_MAX_GUILDS": _i(1, 100000, "Guilds the world may keep at once."),
|
|
158
|
+
"GUILD_AUDIT_CAP": _i(1, 100000, "Audit entries kept per guild."),
|
|
159
|
+
"GUILD_INVITE_TTL_SECONDS": _i(
|
|
160
|
+
60, 86400, "Seconds a guild invite stays valid."
|
|
161
|
+
),
|
|
162
|
+
"GUILD_VAULT_ITEM_CAP": _i(1, 100000, "Items one guild vault may hold."),
|
|
163
|
+
"GUILD_NAME_MIN": _i(1, 64, "Shortest guild name, in characters."),
|
|
164
|
+
"GUILD_NAME_MAX": _i(1, 64, "Longest guild name, in characters."),
|
|
165
|
+
},
|
|
166
|
+
"intel": {
|
|
167
|
+
"INTEL_TTL_SECONDS": _i(
|
|
168
|
+
60, 604800, "Seconds a logged sighting stays queryable."
|
|
169
|
+
),
|
|
170
|
+
"INTEL_MAX_ENTRIES": _i(1, 100000, "Sightings the pool keeps world-wide."),
|
|
171
|
+
"INTEL_MAX_PER_GUILD": _i(1, 100000, "Sightings one guild may hold."),
|
|
172
|
+
"INTEL_MAX_PER_OBSERVER": _i(1, 100000, "Sightings one character may hold."),
|
|
173
|
+
"INTEL_COALESCE_SECONDS": _i(
|
|
174
|
+
0, 86400, "Identical sightings inside this window replace a row."
|
|
175
|
+
),
|
|
176
|
+
"INTEL_LIVE_SECONDS": _i(
|
|
177
|
+
1, 3600, "Age ceiling, in seconds, for the live label."
|
|
178
|
+
),
|
|
179
|
+
},
|
|
180
|
+
"leveling": {
|
|
181
|
+
"XP_BASE": _i(1, 1000000, "XP required for level 2."),
|
|
182
|
+
"XP_GROWTH": _f(1.0, 10.0, "XP curve multiplier per level."),
|
|
183
|
+
"LEVEL_HP_PER_LEVEL": _i(0, 1000, "Max HP gained per level."),
|
|
184
|
+
"LEVEL_ATK_PER_LEVEL": _i(0, 1000, "Attack gained per level."),
|
|
185
|
+
"XP_LOSS_PCT": _pct("Share of level progress lost on death."),
|
|
186
|
+
},
|
|
187
|
+
"dungeon": {
|
|
188
|
+
"DUNGEON_BASE_HP": _i(1, 100000, "Floor-1 monster HP."),
|
|
189
|
+
"DUNGEON_BASE_ATK": _i(0, 10000, "Floor-1 monster attack."),
|
|
190
|
+
"DUNGEON_HP_GROWTH": _f(0.0, 10.0, "HP multiplier per dungeon floor."),
|
|
191
|
+
"DUNGEON_ATK_GROWTH": _f(0.0, 10.0, "Attack multiplier per dungeon floor."),
|
|
192
|
+
"DUNGEON_MAX_FLOOR": _i(1, 1000, "Deepest floor a character may enter."),
|
|
193
|
+
"WARDEN_HP": _i(1, 1000000, "Floor-boss HP."),
|
|
194
|
+
"WARDEN_ATK": _i(0, 100000, "Floor-boss attack."),
|
|
195
|
+
"WARDEN_GOLD": _i(0, 1000000, "Gold the floor boss drops."),
|
|
196
|
+
"WARDEN_RESPAWN_SECONDS": _i(
|
|
197
|
+
1, 86400, "Seconds before a slain floor boss returns."
|
|
198
|
+
),
|
|
199
|
+
"PARTY_MAX_MEMBERS": _i(1, 100, "Characters allowed in one party."),
|
|
200
|
+
"PARTY_INVITE_TTL_SECONDS": _i(
|
|
201
|
+
10, 86400, "Seconds a party invite stays valid."
|
|
202
|
+
),
|
|
203
|
+
"DUNGEON_REENTER_DELAY_SECONDS": _i(
|
|
204
|
+
0, 86400, "Cooldown before re-entering the dungeon after a clear."
|
|
205
|
+
),
|
|
206
|
+
"DUNGEON_REENTER_DELAY_GROWTH_SECONDS": _i(
|
|
207
|
+
0, 86400, "Added re-entry cooldown per floor cleared."
|
|
208
|
+
),
|
|
209
|
+
"DUNGEON_REENTER_DELAY_MAX_SECONDS": _i(
|
|
210
|
+
0, 604800, "Ceiling on the re-entry cooldown."
|
|
211
|
+
),
|
|
212
|
+
"DUNGEON_CLEAR_BASE_PTS": _i(0, 100000, "Score for clearing any floor."),
|
|
213
|
+
"DUNGEON_CLEAR_PTS_PER_FLOOR": _i(0, 10000, "Extra score per floor cleared."),
|
|
214
|
+
"DUNGEON_CLEAR_BASE_XP": _i(0, 100000, "XP for clearing any floor."),
|
|
215
|
+
"DUNGEON_CLEAR_XP_PER_FLOOR": _i(0, 10000, "Extra XP per floor cleared."),
|
|
216
|
+
},
|
|
217
|
+
"quests": {
|
|
218
|
+
"QUEST_GUARD_XP": _i(0, 100000, "Guard quest XP reward."),
|
|
219
|
+
"QUEST_GUARD_GOLD": _i(0, 1000000, "Guard quest gold reward."),
|
|
220
|
+
"QUEST_GUARD_POINTS": _i(0, 10000, "Guard quest score reward."),
|
|
221
|
+
"QUEST_DELVER_XP": _i(0, 100000, "Delver quest XP reward."),
|
|
222
|
+
"QUEST_DELVER_GOLD": _i(0, 1000000, "Delver quest gold reward."),
|
|
223
|
+
"QUEST_DELVER_POINTS": _i(0, 10000, "Delver quest score reward."),
|
|
224
|
+
"QUEST_DELVER_FLOORS": _i(1, 1000, "Dungeon floors a delver must clear."),
|
|
225
|
+
"QUEST_REMEDY_XP": _i(0, 100000, "Remedy quest XP reward."),
|
|
226
|
+
"QUEST_REMEDY_GOLD": _i(0, 1000000, "Remedy quest gold reward."),
|
|
227
|
+
"QUEST_REMEDY_POINTS": _i(0, 10000, "Remedy quest score reward."),
|
|
228
|
+
"QUEST_TONIC_XP": _i(0, 100000, "Tonic quest XP reward."),
|
|
229
|
+
"QUEST_TONIC_GOLD": _i(0, 1000000, "Tonic quest gold reward."),
|
|
230
|
+
"QUEST_TONIC_POINTS": _i(0, 10000, "Tonic quest score reward."),
|
|
231
|
+
},
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
# ---------------------------------------------------------------------------
|
|
235
|
+
# ---------------------------------------------------------------------------
|
|
236
|
+
|
|
237
|
+
ML_SCHEMA = {
|
|
238
|
+
"reward_shaping": {
|
|
239
|
+
"SOCIAL_PER_ALLY": _f(
|
|
240
|
+
0.0,
|
|
241
|
+
100.0,
|
|
242
|
+
"Per-step reward per ally beyond self; reward for staying in a party.",
|
|
243
|
+
),
|
|
244
|
+
"FORMATION_BONUS": _f(
|
|
245
|
+
0.0, 100.0, "One-time bonus for joining or forming a party."
|
|
246
|
+
),
|
|
247
|
+
"FORMATION_COOLDOWN_STEPS": _i(
|
|
248
|
+
1,
|
|
249
|
+
1000000,
|
|
250
|
+
"Env steps between formation bonuses, so cycling cannot farm it.",
|
|
251
|
+
),
|
|
252
|
+
"XP_LEVEL_BONUS": _f(
|
|
253
|
+
0.0, 100.0, "Extra reward per level-up in xp reward mode."
|
|
254
|
+
),
|
|
255
|
+
"ECON_INV_LAMBDA": _f(
|
|
256
|
+
0.0, 100.0, "Weight of inventory-value delta in econ reward mode."
|
|
257
|
+
),
|
|
258
|
+
},
|
|
259
|
+
"curriculum": {
|
|
260
|
+
"CURRICULUM_THRESHOLDS": _list(
|
|
261
|
+
4, 0, 100000, "Min score to enter rats, dungeons, crafting, full."
|
|
262
|
+
),
|
|
263
|
+
},
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
# File id -> (schema, label, relative path for the operator's benefit).
|
|
267
|
+
FILES = {
|
|
268
|
+
"server": {
|
|
269
|
+
"schema": SERVER_SCHEMA,
|
|
270
|
+
"label": "server_config.json",
|
|
271
|
+
"path": "server_config.json",
|
|
272
|
+
"restart": "Restart the server to apply these values.",
|
|
273
|
+
},
|
|
274
|
+
"ml": {
|
|
275
|
+
"schema": ML_SCHEMA,
|
|
276
|
+
"label": "ml/ml_config.json",
|
|
277
|
+
"path": "ml/ml_config.json",
|
|
278
|
+
"restart": "Restart training to apply these values.",
|
|
279
|
+
},
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
# ---------------------------------------------------------------------------
|
|
283
|
+
# Presets. Each is a value set, not a rule change: applying one stages values
|
|
284
|
+
# into the form for review. Nothing is written until the operator saves.
|
|
285
|
+
# ---------------------------------------------------------------------------
|
|
286
|
+
|
|
287
|
+
PRESETS = [
|
|
288
|
+
{
|
|
289
|
+
"name": "Balanced",
|
|
290
|
+
"help": "Shipped defaults for the training-facing keys. Restores them to code defaults.",
|
|
291
|
+
"values": {
|
|
292
|
+
"server": {
|
|
293
|
+
"scoring.DISCOVERY_POINTS": None,
|
|
294
|
+
"scoring.DISCOVERY_XP": None,
|
|
295
|
+
"scoring.DEATH_PENALTY": None,
|
|
296
|
+
},
|
|
297
|
+
"ml": {
|
|
298
|
+
"reward_shaping.SOCIAL_PER_ALLY": None,
|
|
299
|
+
"reward_shaping.FORMATION_BONUS": None,
|
|
300
|
+
"reward_shaping.XP_LEVEL_BONUS": None,
|
|
301
|
+
"curriculum.CURRICULUM_THRESHOLDS": None,
|
|
302
|
+
},
|
|
303
|
+
},
|
|
304
|
+
},
|
|
305
|
+
{
|
|
306
|
+
"name": "Fast Training",
|
|
307
|
+
"help": "Reward staying alive and grouped, and open the curriculum earlier, "
|
|
308
|
+
"so an agent reaches the full world in fewer steps.",
|
|
309
|
+
"values": {
|
|
310
|
+
"server": {
|
|
311
|
+
"scoring.DEATH_PENALTY": 2.0,
|
|
312
|
+
"scoring.DEATH_GOLD_LOST_PCT": 0.0,
|
|
313
|
+
"leveling.XP_LOSS_PCT": 2.0,
|
|
314
|
+
},
|
|
315
|
+
"ml": {
|
|
316
|
+
"reward_shaping.SOCIAL_PER_ALLY": 0.15,
|
|
317
|
+
"reward_shaping.FORMATION_BONUS": 1.0,
|
|
318
|
+
"reward_shaping.FORMATION_COOLDOWN_STEPS": 200,
|
|
319
|
+
"curriculum.CURRICULUM_THRESHOLDS": [0, 5, 15, 30],
|
|
320
|
+
},
|
|
321
|
+
},
|
|
322
|
+
},
|
|
323
|
+
{
|
|
324
|
+
"name": "Economy Focus",
|
|
325
|
+
"help": "Weight inventory value over raw score, and widen the market so "
|
|
326
|
+
"agents can actually trade the goods they farm.",
|
|
327
|
+
"values": {
|
|
328
|
+
"server": {
|
|
329
|
+
"economy.MARKET_ORDER_SLOTS_BASE": 6,
|
|
330
|
+
"economy.MARKET_SLOT_PRICE_BASE": 25,
|
|
331
|
+
"economy.BROKER_FEE_PCT": 2.0,
|
|
332
|
+
"economy.RELIST_FEE_PCT": 2.0,
|
|
333
|
+
"economy.INVENTORY_CAP": 40,
|
|
334
|
+
},
|
|
335
|
+
"ml": {
|
|
336
|
+
"reward_shaping.ECON_INV_LAMBDA": 3.0,
|
|
337
|
+
},
|
|
338
|
+
},
|
|
339
|
+
},
|
|
340
|
+
]
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
# Code defaults for ml_config.json keys, copied from ml/ml_env.py. Pinned by
|
|
344
|
+
# test, not by import: the game server must not import the ML env.
|
|
345
|
+
ML_DEFAULTS = {
|
|
346
|
+
"SOCIAL_PER_ALLY": 0.05,
|
|
347
|
+
"FORMATION_BONUS": 0.5,
|
|
348
|
+
"FORMATION_COOLDOWN_STEPS": 500,
|
|
349
|
+
"XP_LEVEL_BONUS": 5.0,
|
|
350
|
+
"ECON_INV_LAMBDA": 1.0,
|
|
351
|
+
"CURRICULUM_THRESHOLDS": [0, 10, 30, 60],
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def field_spec(file_id, section, key):
|
|
356
|
+
"""Spec for one key, or None when the key is not in the schema."""
|
|
357
|
+
entry = FILES.get(file_id, {}).get("schema", {}).get(section, {})
|
|
358
|
+
return entry.get(key)
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def sections(file_id):
|
|
362
|
+
"""Ordered [(section, [key, ...])] for a file."""
|
|
363
|
+
return [
|
|
364
|
+
(section, list(keys))
|
|
365
|
+
for section, keys in FILES.get(file_id, {}).get("schema", {}).items()
|
|
366
|
+
]
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def validate(file_id, section, key, raw):
|
|
370
|
+
"""Coerce and bounds-check one submitted value.
|
|
371
|
+
|
|
372
|
+
Returns (value, None) or (None, error). Deliberately mirrors what the
|
|
373
|
+
loaders can actually accept: an int-typed global rejects 2.5 rather than
|
|
374
|
+
silently truncating it through `type(default)(value)`, because a form that
|
|
375
|
+
shows 2.5 in the box and saves 2 in the file is worse than a refusal.
|
|
376
|
+
"""
|
|
377
|
+
spec = field_spec(file_id, section, key)
|
|
378
|
+
if spec is None:
|
|
379
|
+
return None, f"unknown key {section}.{key}"
|
|
380
|
+
kind = spec["type"]
|
|
381
|
+
|
|
382
|
+
if kind == "list":
|
|
383
|
+
text = str(raw).strip()
|
|
384
|
+
if text.startswith("[") and text.endswith("]"):
|
|
385
|
+
text = text[1:-1]
|
|
386
|
+
parts = [p.strip() for p in text.split(",") if p.strip()]
|
|
387
|
+
if len(parts) != spec["count"]:
|
|
388
|
+
return None, f"{key} needs exactly {spec['count']} numbers"
|
|
389
|
+
out = []
|
|
390
|
+
for part in parts:
|
|
391
|
+
# float() first, then narrow: int("1e2") is a ValueError, so
|
|
392
|
+
# testing for a decimal point and otherwise calling int() would
|
|
393
|
+
# reject a number JSON itself accepts.
|
|
394
|
+
try:
|
|
395
|
+
number = float(part)
|
|
396
|
+
except ValueError:
|
|
397
|
+
return None, f"{key}: {part!r} is not a number"
|
|
398
|
+
out.append(int(number) if number.is_integer() else number)
|
|
399
|
+
for item in out:
|
|
400
|
+
if not spec["min"] <= item <= spec["max"]:
|
|
401
|
+
return None, f"{key}: {item} outside {spec['min']}-{spec['max']}"
|
|
402
|
+
return out, None
|
|
403
|
+
|
|
404
|
+
text = str(raw).strip()
|
|
405
|
+
if not text:
|
|
406
|
+
return None, f"{key} is empty"
|
|
407
|
+
if kind == "int":
|
|
408
|
+
try:
|
|
409
|
+
value = int(text, 10)
|
|
410
|
+
except ValueError:
|
|
411
|
+
return None, f"{key} must be a whole number"
|
|
412
|
+
else:
|
|
413
|
+
try:
|
|
414
|
+
value = float(text)
|
|
415
|
+
except ValueError:
|
|
416
|
+
return None, f"{key} must be a number"
|
|
417
|
+
if not spec["min"] <= value <= spec["max"]:
|
|
418
|
+
return None, f"{key}: {value} outside {spec['min']}-{spec['max']}"
|
|
419
|
+
return value, None
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def format_value(spec, value):
|
|
423
|
+
"""Render a value the way the file should spell it.
|
|
424
|
+
|
|
425
|
+
Floats keep a decimal point (2.0, not 2) because the loader coerces with
|
|
426
|
+
`type(default)(value)` and an int-typed default given 2.0 stays 2.0, but a
|
|
427
|
+
float-typed default given a bare 2 would round-trip through JSON as an int
|
|
428
|
+
and make the file disagree with its own type.
|
|
429
|
+
"""
|
|
430
|
+
if spec["type"] == "list":
|
|
431
|
+
return (
|
|
432
|
+
"["
|
|
433
|
+
+ ", ".join((f"{v:g}" if isinstance(v, float) else str(v)) for v in value)
|
|
434
|
+
+ "]"
|
|
435
|
+
)
|
|
436
|
+
if spec["type"] == "float":
|
|
437
|
+
# %g rather than repr: repr(2.0) is "2.0" but repr(1e-07) is
|
|
438
|
+
# "1e-07", which json.load reads back fine and json.dump would not
|
|
439
|
+
# have written. %g keeps small values in the 0.0000001 spelling a
|
|
440
|
+
# human editing the file would use, and json.load accepts either.
|
|
441
|
+
text = f"{float(value):g}"
|
|
442
|
+
return text if ("." in text or "e" in text) else text + ".0"
|
|
443
|
+
return str(int(value))
|
config_write.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""Surgical config-file writer for the dashboard editor (#63).
|
|
2
|
+
|
|
3
|
+
json.dump round-trips are unusable here. `ml/versioning.py` hashes the raw
|
|
4
|
+
bytes of server_config.json and ml/ml_config.json into every checkpoint's
|
|
5
|
+
config_hash, and `version_notes` reports "config differs" when it moves. A
|
|
6
|
+
rewrite that reorders keys, drops the blank lines between sections, or spells
|
|
7
|
+
0.10 as 0.1 would flip every checkpoint in the repo to "config differs" the
|
|
8
|
+
first time an operator saved a config from the browser.
|
|
9
|
+
|
|
10
|
+
So this rewrites only the lines it must. Each scalar sits alone on its own
|
|
11
|
+
line in both files, which makes the edit a match over that one line: the
|
|
12
|
+
file's indentation, key order, spacing, trailing commas and `_comment` all
|
|
13
|
+
survive untouched, and a save that changes nothing writes no bytes at all
|
|
14
|
+
(so the hash does not move). Adding a key inserts a line in its section;
|
|
15
|
+
removing one drops the line and fixes up the neighbor's comma.
|
|
16
|
+
|
|
17
|
+
Validated by json.loads before and after: a config file that does not parse is
|
|
18
|
+
never written, and a parse failure after the rewrite leaves the file on disk
|
|
19
|
+
untouched (the write is a single os.replace of a temp file).
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import re
|
|
25
|
+
import tempfile
|
|
26
|
+
|
|
27
|
+
from config_schema import field_spec, format_value
|
|
28
|
+
|
|
29
|
+
# One scalar per line: "KEY": value, with the value running to the line end.
|
|
30
|
+
# Anchored on the full line so a key whose name is a prefix of another
|
|
31
|
+
# (XP_BASE vs XP_BASE2) cannot match across keys.
|
|
32
|
+
_ENTRY_RE = re.compile(r'^(\s*)"([A-Za-z0-9_]+)"(\s*:\s*)(.+?)(,?)\s*$')
|
|
33
|
+
_SECTION_RE = re.compile(r'^\s*"([A-Za-z0-9_]+)"(\s*:\s*\{)\s*$')
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class _Absent:
|
|
37
|
+
"""Sentinel: the key is not in the file at all, so it is at its default."""
|
|
38
|
+
|
|
39
|
+
def __repr__(self):
|
|
40
|
+
return "<absent>"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
_ABSENT = _Absent()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _json_equal(a, b):
|
|
47
|
+
"""Compare as the loader would see them, so 2 and 2.0 are one value."""
|
|
48
|
+
if isinstance(a, bool) != isinstance(b, bool):
|
|
49
|
+
return False
|
|
50
|
+
if isinstance(a, (int, float)) and isinstance(b, (int, float)):
|
|
51
|
+
return float(a) == float(b)
|
|
52
|
+
return a == b
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _read(path):
|
|
56
|
+
try:
|
|
57
|
+
# newline="" keeps the file's own line endings: without it, Windows
|
|
58
|
+
# text mode rewrites every LF to CRLF on write and the whole file's
|
|
59
|
+
# bytes change, which is the exact provenance break this module exists
|
|
60
|
+
# to avoid.
|
|
61
|
+
with open(path, encoding="utf-8", newline="") as handle:
|
|
62
|
+
return handle.read()
|
|
63
|
+
except OSError:
|
|
64
|
+
return ""
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _indent_of(line):
|
|
68
|
+
return line[: len(line) - len(line.lstrip())]
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _section_bounds(lines, section):
|
|
72
|
+
"""(header_index, first_body, closing_brace) line indices for a section."""
|
|
73
|
+
for index, line in enumerate(lines):
|
|
74
|
+
match = _SECTION_RE.match(line)
|
|
75
|
+
if not match or match.group(1) != section:
|
|
76
|
+
continue
|
|
77
|
+
for close in range(index + 1, len(lines)):
|
|
78
|
+
if lines[close].strip().startswith("}"):
|
|
79
|
+
return index, index + 1, close
|
|
80
|
+
return None
|
|
81
|
+
return None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _rendered(key, spec, value, comma):
|
|
85
|
+
return f'"{key}": {format_value(spec, value)}{"," if comma else ""}'
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _apply_section(lines, file_id, section, edits):
|
|
89
|
+
"""Apply {key: value_or_None} inside one section. Returns (ok, note).
|
|
90
|
+
|
|
91
|
+
Resets (None) are applied first: removing a line shifts every index after
|
|
92
|
+
it, and doing the removals in one pass keeps the remaining lookups valid.
|
|
93
|
+
"""
|
|
94
|
+
bounds = _section_bounds(lines, section)
|
|
95
|
+
if bounds is None:
|
|
96
|
+
return False, f"section {section} not found in file"
|
|
97
|
+
header, body_start, close = bounds
|
|
98
|
+
indent = _indent_of(lines[header]) + " "
|
|
99
|
+
|
|
100
|
+
pending = dict(edits)
|
|
101
|
+
for key, value in list(pending.items()):
|
|
102
|
+
if value is not None:
|
|
103
|
+
continue
|
|
104
|
+
for index in range(body_start, close):
|
|
105
|
+
match = _ENTRY_RE.match(lines[index])
|
|
106
|
+
if not match or match.group(2) != key:
|
|
107
|
+
continue
|
|
108
|
+
del lines[index]
|
|
109
|
+
# Deleting a middle or first entry leaves the surrounding commas
|
|
110
|
+
# correct. Deleting the LAST entry does not: the entry that now
|
|
111
|
+
# ends the section still carries the comma that separated it from
|
|
112
|
+
# the removed one. After the delete that entry sits at close - 2
|
|
113
|
+
# (the closing brace has shifted into close - 1).
|
|
114
|
+
if index == close - 1 and close - 2 >= body_start:
|
|
115
|
+
lines[close - 2] = _strip_comma(lines[close - 2])
|
|
116
|
+
close -= 1
|
|
117
|
+
break
|
|
118
|
+
del pending[key]
|
|
119
|
+
|
|
120
|
+
if pending:
|
|
121
|
+
updates = {}
|
|
122
|
+
for index in range(body_start, close):
|
|
123
|
+
match = _ENTRY_RE.match(lines[index])
|
|
124
|
+
if match and match.group(2) in pending:
|
|
125
|
+
updates[match.group(2)] = index
|
|
126
|
+
for key, index in updates.items():
|
|
127
|
+
# A submitted value that already parses to what the line says must
|
|
128
|
+
# not be respelled. 0.10 and 0.1 are the same value to the loader
|
|
129
|
+
# but different bytes, and a save that only retypes a value the
|
|
130
|
+
# operator did not change would move the config hash and make every
|
|
131
|
+
# existing checkpoint report "config differs".
|
|
132
|
+
try:
|
|
133
|
+
have = json.loads(_ENTRY_RE.match(lines[index]).group(4))
|
|
134
|
+
except (ValueError, AttributeError):
|
|
135
|
+
have = _ABSENT
|
|
136
|
+
if _json_equal(have, pending[key]):
|
|
137
|
+
continue
|
|
138
|
+
spec = field_spec(file_id, section, key)
|
|
139
|
+
comma = lines[index].rstrip().endswith(",")
|
|
140
|
+
lines[index] = _indent_of(lines[index]) + _rendered(
|
|
141
|
+
key, spec, pending[key], comma
|
|
142
|
+
)
|
|
143
|
+
added = [k for k in pending if k not in updates]
|
|
144
|
+
if added:
|
|
145
|
+
# New entries go last in the section. The entry that currently ends
|
|
146
|
+
# the section carries no trailing comma (a valid file has none
|
|
147
|
+
# before a closing brace), so it needs one ADDED, not stripped:
|
|
148
|
+
# stripping it left the old last entry and the new first entry
|
|
149
|
+
# unseparated, which made every reset-then-set round trip die on a
|
|
150
|
+
# re-parse instead of writing.
|
|
151
|
+
if close - 1 >= body_start:
|
|
152
|
+
lines[close - 1] = _ensure_comma(lines[close - 1])
|
|
153
|
+
for offset, key in enumerate(added):
|
|
154
|
+
last = offset == len(added) - 1
|
|
155
|
+
lines.insert(
|
|
156
|
+
close + offset,
|
|
157
|
+
indent
|
|
158
|
+
+ _rendered(
|
|
159
|
+
key, field_spec(file_id, section, key), pending[key], not last
|
|
160
|
+
),
|
|
161
|
+
)
|
|
162
|
+
return True, ""
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _strip_comma(line):
|
|
166
|
+
return line.rstrip().rstrip(",")
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _ensure_comma(line):
|
|
170
|
+
stripped = line.rstrip()
|
|
171
|
+
return stripped if stripped.endswith(",") else stripped + ","
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def write_edits(path, file_id, edits):
|
|
175
|
+
"""Write {section: {key: value_or_None}} into the config file at path.
|
|
176
|
+
|
|
177
|
+
None means "delete the override" (reset to the code default). Returns
|
|
178
|
+
(ok, message, changed_keys). Writes no bytes when every submitted value
|
|
179
|
+
already matches what the file says.
|
|
180
|
+
"""
|
|
181
|
+
wanted = {}
|
|
182
|
+
for section, keys in edits.items():
|
|
183
|
+
for key, value in keys.items():
|
|
184
|
+
if field_spec(file_id, section, key) is None:
|
|
185
|
+
return False, f"unknown key {section}.{key}", []
|
|
186
|
+
wanted[(section, key)] = value
|
|
187
|
+
|
|
188
|
+
original = _read(path)
|
|
189
|
+
try:
|
|
190
|
+
before = json.loads(original) if original.strip() else {}
|
|
191
|
+
except ValueError as exc:
|
|
192
|
+
return False, f"{os.path.basename(path)} is not valid JSON ({exc})", []
|
|
193
|
+
|
|
194
|
+
lines = original.splitlines()
|
|
195
|
+
changed = []
|
|
196
|
+
for section, keys in edits.items():
|
|
197
|
+
current = before.get(section) if isinstance(before.get(section), dict) else {}
|
|
198
|
+
for key, value in keys.items():
|
|
199
|
+
have = current.get(key, _ABSENT)
|
|
200
|
+
if _json_equal(have, value) or (value is None and have is _ABSENT):
|
|
201
|
+
continue
|
|
202
|
+
changed.append(f"{section}.{key}")
|
|
203
|
+
ok, note = _apply_section(lines, file_id, section, keys)
|
|
204
|
+
if not ok:
|
|
205
|
+
return False, note, []
|
|
206
|
+
|
|
207
|
+
# The file's own line ending, not "\n". A checkout on Windows can hand us a
|
|
208
|
+
# CRLF config, and these bytes are hashed into every checkpoint's
|
|
209
|
+
# config_hash: rejoining with "\n" would rewrite every line of the file.
|
|
210
|
+
newline = "\r\n" if "\r\n" in original else "\n"
|
|
211
|
+
|
|
212
|
+
updated = newline.join(lines)
|
|
213
|
+
if original.endswith(("\n", "\r")):
|
|
214
|
+
updated += newline
|
|
215
|
+
if updated == original:
|
|
216
|
+
return True, "no changes", []
|
|
217
|
+
|
|
218
|
+
try:
|
|
219
|
+
parsed = json.loads(updated)
|
|
220
|
+
except ValueError as exc:
|
|
221
|
+
return False, f"refusing to write invalid JSON ({exc})", []
|
|
222
|
+
# The rewritten text must mean what was asked for, not merely parse.
|
|
223
|
+
for (section, key), value in wanted.items():
|
|
224
|
+
got = (
|
|
225
|
+
parsed.get(section, {}).get(key)
|
|
226
|
+
if isinstance(parsed.get(section), dict)
|
|
227
|
+
else None
|
|
228
|
+
)
|
|
229
|
+
if value is None:
|
|
230
|
+
if got is not None:
|
|
231
|
+
return False, f"{section}.{key} survived removal", []
|
|
232
|
+
elif not _json_equal(got, value):
|
|
233
|
+
return False, f"{section}.{key} did not round-trip", []
|
|
234
|
+
|
|
235
|
+
directory = os.path.dirname(os.path.abspath(path)) or "."
|
|
236
|
+
handle, tmp = tempfile.mkstemp(dir=directory, prefix=".config-", suffix=".tmp")
|
|
237
|
+
try:
|
|
238
|
+
with os.fdopen(handle, "w", encoding="utf-8", newline="") as out:
|
|
239
|
+
out.write(updated)
|
|
240
|
+
os.replace(tmp, path)
|
|
241
|
+
except OSError as exc:
|
|
242
|
+
try:
|
|
243
|
+
os.remove(tmp)
|
|
244
|
+
except OSError:
|
|
245
|
+
pass
|
|
246
|
+
return False, f"could not write {os.path.basename(path)} ({exc})", []
|
|
247
|
+
return True, f"{len(changed)} value(s) written", changed
|