-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrapp_sdk.py
More file actions
1971 lines (1682 loc) · 79.7 KB
/
rapp_sdk.py
File metadata and controls
1971 lines (1682 loc) · 79.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""RAPP Foundation SDK — Build agents, mint cards, track Binders. The open developer toolkit for the RAPP agent ecosystem."""
from __future__ import annotations
__version__ = "1.0.0"
# =============================================================================
# SECTION 1: CONSTANTS + CONFIG
# =============================================================================
import ast
import argparse
import hashlib
import importlib.util
import json
import os
import subprocess
import sys
import urllib.request
from pathlib import Path
REQUIRED_MANIFEST_FIELDS = [
"schema", "name", "version", "display_name",
"description", "author", "tags", "category",
]
VALID_CATEGORIES = [
"core", "pipeline", "integrations", "productivity", "devtools", "general",
"b2b_sales", "b2c_sales", "healthcare", "financial_services", "manufacturing",
"energy", "federal_government", "slg_government", "human_resources",
"it_management", "professional_services", "retail_cpg", "software_digital_products",
]
VALID_TIERS = ["experimental", "community", "verified", "official"]
SUBMITTABLE_TIERS = ["experimental", "community"]
REPO = "kody-w/RAR"
RAW_BASE = f"https://raw.githubusercontent.com/{REPO}/main"
API_BASE = f"https://api.github.com/repos/{REPO}"
TIER_TO_RARITY = {
"official": "mythic",
"verified": "rare",
"community": "core",
"experimental": "starter",
}
RARITY_LABELS = {
"mythic": "Legendary",
"rare": "Elite",
"core": "Core",
"starter": "Starter",
}
RARITY_FLOOR = {
"mythic": 200,
"rare": 100,
"core": 40,
"starter": 10,
}
# Agent scaffold template — uses __TOKEN__ placeholders to avoid brace conflicts
AGENT_TEMPLATE = '''\
"""__DESCRIPTION__"""
__manifest__ = {
"schema": "rapp-agent/1.0",
"name": "__NAME__",
"version": "1.0.0",
"display_name": "__DISPLAY_NAME__",
"description": "__DESCRIPTION__",
"author": "__AUTHOR__",
"tags": [],
"category": "general",
"quality_tier": "community",
"requires_env": [],
"dependencies": ["@rapp/basic-agent"],
}
from agents.basic_agent import BasicAgent
class __CLASS_NAME__(BasicAgent):
def __init__(self):
self.name = "__DISPLAY_NAME__"
self.metadata = {
"description": "__DESCRIPTION__",
}
super().__init__(name=self.name, metadata=self.metadata)
def perform(self, **kwargs) -> str:
task = kwargs.get("task", "default")
return f"__DISPLAY_NAME__ performed: {task}"
if __name__ == "__main__":
agent = __CLASS_NAME__()
print(agent.perform())
'''
# =============================================================================
# SECTION 2: MANIFEST OPERATIONS
# =============================================================================
def extract_manifest(path: str) -> dict | None:
"""Extract __manifest__ dict from a Python file using AST parsing (no code execution)."""
try:
source = Path(path).read_text()
tree = ast.parse(source)
except (SyntaxError, OSError) as e:
return None
for node in ast.walk(tree):
if isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name) and target.id == "__manifest__":
try:
return ast.literal_eval(node.value)
except (ValueError, TypeError):
return None
return None
def validate_manifest(path: str, manifest: dict = None) -> list[str]:
"""Validate a manifest and return a list of error strings. Extracts manifest if not provided."""
errors = []
if manifest is None:
manifest = extract_manifest(path)
if manifest is None:
return ["No __manifest__ dict found in file"]
# Required fields
for field in REQUIRED_MANIFEST_FIELDS:
if field not in manifest:
errors.append(f"Missing required field: {field}")
# Name format: @publisher/slug
name = manifest.get("name", "")
if not name.startswith("@") or "/" not in name:
errors.append(f"Invalid name format '{name}' — must be @publisher/slug")
# Semver
version = manifest.get("version", "")
parts = version.split(".")
if len(parts) != 3 or not all(p.isdigit() for p in parts):
errors.append(f"Invalid version '{version}' — must be semver (e.g., 1.0.0)")
# Tags must be a list
if not isinstance(manifest.get("tags", []), list):
errors.append("tags must be a list")
# Category
category = manifest.get("category", "")
if category and category not in VALID_CATEGORIES:
errors.append(f"Invalid category '{category}' — must be one of: {', '.join(VALID_CATEGORIES)}")
# Tier
tier = manifest.get("quality_tier", "community")
if tier not in VALID_TIERS:
errors.append(f"Invalid quality_tier '{tier}' — must be one of: {', '.join(VALID_TIERS)}")
return errors
def extract_card(path: str) -> dict | None:
"""Extract __card__ dict from a Python file using AST parsing."""
try:
source = Path(path).read_text()
tree = ast.parse(source)
except (SyntaxError, OSError):
return None
for node in ast.walk(tree):
if isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name) and target.id == "__card__":
try:
return ast.literal_eval(node.value)
except (ValueError, TypeError):
return None
return None
# =============================================================================
# SECTION 3: CONTRACT TESTING (no pytest dependency)
# =============================================================================
def run_contract_tests(path: str) -> list[tuple[str, bool, str]]:
"""
Run the RAPP agent contract test suite against a single agent file.
Returns a list of (test_name, passed, message) tuples.
"""
results = []
agent_path = Path(path)
def record(name, passed, msg):
results.append((name, passed, msg))
# 1. has_manifest
try:
manifest = extract_manifest(path)
if manifest is not None:
record("has_manifest", True, "__manifest__ dict found")
else:
record("has_manifest", False, "No __manifest__ dict in file")
manifest = {}
except Exception as e:
record("has_manifest", False, f"Error reading manifest: {e}")
manifest = {}
# 2. manifest_fields
try:
missing = [f for f in REQUIRED_MANIFEST_FIELDS if f not in manifest]
if not missing:
record("manifest_fields", True, "All required fields present")
else:
record("manifest_fields", False, f"Missing fields: {', '.join(missing)}")
except Exception as e:
record("manifest_fields", False, f"Error: {e}")
# 3. name_format
try:
name = manifest.get("name", "")
if name.startswith("@") and "/" in name:
record("name_format", True, f"Name '{name}' is valid @publisher/slug format")
else:
record("name_format", False, f"Name '{name}' must be @publisher/slug format")
except Exception as e:
record("name_format", False, f"Error: {e}")
# 4. has_basic_agent (uses importlib to check class inheritance)
agent_module = None
agent_class = None
try:
# Add known BasicAgent locations to sys.path
rapp_dir = str(agent_path.parent.parent / "@rapp")
templates_dir = str(
agent_path.parent.parent.parent
/ "agents"
/ "@aibast-agents-library"
/ "templates"
)
for extra in [rapp_dir, templates_dir, str(agent_path.parent.parent)]:
if extra not in sys.path and Path(extra).exists():
sys.path.insert(0, extra)
# Also try adding the project root so `from agents.basic_agent import BasicAgent` works
project_root = str(agent_path.parent.parent.parent)
if project_root not in sys.path:
sys.path.insert(0, project_root)
spec = importlib.util.spec_from_file_location("_rapp_test_agent_", str(agent_path))
agent_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(agent_module)
# Find class that inherits BasicAgent
import inspect
found = False
for obj_name, obj in inspect.getmembers(agent_module, inspect.isclass):
bases = [b.__name__ for b in obj.__mro__]
if "BasicAgent" in bases and obj.__name__ != "BasicAgent":
agent_class = obj
found = True
break
if found:
record("has_basic_agent", True, f"Class '{agent_class.__name__}' inherits BasicAgent")
else:
record("has_basic_agent", False, "No class inheriting BasicAgent found")
except Exception as e:
record("has_basic_agent", False, f"Import error: {e}")
# 5. instantiation
agent_instance = None
try:
if agent_class is not None:
agent_instance = agent_class()
record("instantiation", True, f"{agent_class.__name__}() succeeded")
else:
record("instantiation", False, "Skipped — no agent class found")
except Exception as e:
record("instantiation", False, f"Instantiation failed: {e}")
# 6. perform_returns_str
try:
if agent_instance is not None:
result = agent_instance.perform()
if isinstance(result, str):
record("perform_returns_str", True, f"perform() returned str ({len(result)} chars)")
else:
record("perform_returns_str", False, f"perform() returned {type(result).__name__}, expected str")
else:
record("perform_returns_str", False, "Skipped — no agent instance")
except Exception as e:
record("perform_returns_str", False, f"perform() raised: {e}")
# 7. standalone_execution
try:
proc = subprocess.run(
[sys.executable, str(agent_path)],
capture_output=True,
text=True,
timeout=15,
)
if proc.returncode == 0:
record("standalone_execution", True, "python agent.py exited 0")
else:
record("standalone_execution", False, f"Exited {proc.returncode}: {proc.stderr.strip()[:120]}")
except subprocess.TimeoutExpired:
record("standalone_execution", False, "Timed out after 15 seconds")
except Exception as e:
record("standalone_execution", False, f"Error: {e}")
# 8. has_docstring
try:
if agent_module is not None:
doc = getattr(agent_module, "__doc__", None)
if doc and doc.strip():
record("has_docstring", True, f"Module docstring present ({len(doc.strip())} chars)")
else:
record("has_docstring", False, "Module docstring missing or empty")
else:
source = agent_path.read_text()
tree = ast.parse(source)
doc = ast.get_docstring(tree)
if doc:
record("has_docstring", True, "Module docstring present (parsed via AST)")
else:
record("has_docstring", False, "Module docstring missing")
except Exception as e:
record("has_docstring", False, f"Error: {e}")
# 9. no_hardcoded_secrets
try:
source = agent_path.read_text()
suspicious_patterns = [
'API_KEY = "sk-',
"API_KEY = 'sk-",
'password = "',
"password = '",
'token = "',
"token = '",
'secret = "',
"secret = '",
'api_key = "',
"api_key = '",
]
found_patterns = [p for p in suspicious_patterns if p in source]
if not found_patterns:
record("no_hardcoded_secrets", True, "No hardcoded secret patterns detected")
else:
record("no_hardcoded_secrets", False, f"Suspicious patterns found: {found_patterns}")
except Exception as e:
record("no_hardcoded_secrets", False, f"Error scanning source: {e}")
return results
# =============================================================================
# SECTION 4: REGISTRY CLIENT
# =============================================================================
def _get_token() -> str | None:
"""Get GitHub token from GITHUB_TOKEN env or gh CLI."""
token = os.environ.get("GITHUB_TOKEN")
if token:
return token
try:
result = subprocess.run(
["gh", "auth", "token"],
capture_output=True,
text=True,
timeout=5,
)
if result.returncode == 0:
return result.stdout.strip()
except (FileNotFoundError, subprocess.TimeoutExpired):
pass
return None
def _fetch_json(url: str, token: str = None) -> dict | None:
"""Fetch JSON from a URL with optional GitHub auth header."""
try:
req = urllib.request.Request(url)
req.add_header("Accept", "application/json")
if token:
req.add_header("Authorization", f"Bearer {token}")
with urllib.request.urlopen(req, timeout=10) as resp:
return json.loads(resp.read().decode())
except Exception:
return None
def fetch_registry() -> dict:
"""Fetch registry — prefers local file (local-first), falls back to GitHub."""
# Local-first: use local registry.json if it exists
local = Path(__file__).parent / "registry.json"
if local.exists():
try:
return json.loads(local.read_text())
except json.JSONDecodeError:
pass
# Fall back to remote
url = f"{RAW_BASE}/registry.json"
token = _get_token()
data = _fetch_json(url, token)
if data:
return data
return {"agents": [], "stats": {}}
def search_agents(query: str) -> list[dict]:
"""Text search across name, display_name, description, tags, author, category."""
registry = fetch_registry()
agents = registry.get("agents", [])
q = query.lower()
results = []
for agent in agents:
searchable = " ".join([
agent.get("name", ""),
agent.get("display_name", ""),
agent.get("description", ""),
agent.get("author", ""),
agent.get("category", ""),
" ".join(agent.get("tags", [])),
]).lower()
if q in searchable:
results.append(agent)
return results
def get_agent_info(name: str) -> dict | None:
"""Find an agent by exact name in the registry."""
registry = fetch_registry()
for agent in registry.get("agents", []):
if agent.get("name") == name:
return agent
return None
def install_agent(name: str, output_dir: str = "agents") -> str:
"""Download an agent .py file from GitHub and write it to disk. Returns the output path."""
agent = get_agent_info(name)
if agent is None:
raise ValueError(f"Agent '{name}' not found in registry")
file_path = agent.get("_file")
if not file_path:
raise ValueError(f"No _file path recorded for '{name}'")
url = f"{RAW_BASE}/{file_path}"
token = _get_token()
req = urllib.request.Request(url)
if token:
req.add_header("Authorization", f"Bearer {token}")
try:
with urllib.request.urlopen(req, timeout=15) as resp:
content = resp.read().decode()
except Exception as e:
raise RuntimeError(f"Failed to download agent: {e}")
# Reconstruct output path relative to output_dir
parts = Path(file_path).parts # e.g. agents/@kody/my_agent.py
if parts[0] == "agents":
parts = parts[1:] # strip leading "agents/"
dest = Path(output_dir) / Path(*parts)
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_text(content)
return str(dest)
# =============================================================================
# SECTION 5: CARD + BINDER OPERATIONS
# =============================================================================
def seed_hash(s: str) -> int:
"""Deterministic, reproducible hash for card generation."""
h = 0
for c in s:
h = ((h << 5) - h + ord(c)) & 0xFFFFFFFF
return h
def mulberry32(seed: int):
"""Return a callable PRNG producing 0.0–1.0 floats from a seed."""
state = [seed & 0xFFFFFFFF]
def _rand():
state[0] = (state[0] + 0x6D2B79F5) & 0xFFFFFFFF
z = state[0]
z = ((z ^ (z >> 15)) * ((z | 1) & 0xFFFFFFFF)) & 0xFFFFFFFF
z = ((z ^ (z >> 7)) * ((z | 61) & 0xFFFFFFFF)) & 0xFFFFFFFF
z = (z ^ (z >> 14)) & 0xFFFFFFFF
return z / 0xFFFFFFFF
return _rand
# ─── SEED MNEMONIC (7 words = 64-bit seed, full fidelity, memorizable) ───
# 1024 words → 10 bits per word → 7 words = 70 bits (covers 64-bit seed)
# Say 7 words. The card appears. An incantation that summons an agent.
# DRAFT: word list will be curated for incantation feel before first public mnemonic.
# Once locked, the list is PERMANENT — changing it breaks all existing mnemonics.
MNEMONIC_WORDS = """FORGE ANVIL BLADE RUNE SHARD SMELT TEMPER WELD CHISEL BRAND MOLD CAST STAMP ETCH CARVE BIND FUSE ALLOY INGOT RIVET CLASP THORN BARB SPIKE PRONG EDGE HONE GRIND QUENCH SEAR HAMMER STOKE FIRE FROST STORM TIDE QUAKE GUST BOLT SURGE BLAZE EMBER PYRE ASH SMOKE SPARK FLARE FLASH FLOOD GALE DRIFT MIST HAZE VOID FLUX PULSE WAVE SHOCK BURST CRACK ROAR HOWL ECHO BOOM THUNDER VENOM BLIGHT SCORCH SINGE CHAR WITHER ERODE CORRODE DISSOLVE OAK PINE MOSS FERN ROOT VINE BLOOM SEED GROVE GLEN VALE CRAG PEAK RIDGE GORGE CLIFF SHORE REEF DUNE MARSH CAVE LAIR DEN NEST HIVE BURROW STONE IRON STEEL GOLD JADE ONYX RUBY OPAL AMBER PEARL CORAL QUARTZ OBSIDIAN FLINT GRANITE BASALT COBALT CHROME BRONZE COPPER NICKEL RELIC TOTEM SIGIL GLYPH WARD CHARM BANE DOOM FATE OMEN ORACLE SAGE SEER MAGE DRUID SHAMAN WRAITH SHADE PHANTOM SPECTER GOLEM TITAN DRAKE WYRM GRYPHON SPHINX HYDRA CHIMERA SCROLL TOME CODEX LORE MYTH FABLE SAGA EPIC VERSE CHANT HYMN DIRGE OATH CREED VOW AURA MANA ETHER PRISM NEXUS VORTEX RIFT WARP BREACH PORTAL GATE VAULT SHRINE ALTAR CRYPT SPIRE STRIKE SLASH THRUST PARRY GUARD SHIELD HELM LANCE MACE PIKE STAFF WAND DAGGER BOW ARROW QUIVER ARMOR PLATE GAUNTLET VISOR CLOAK CAPE MANTLE AEGIS BULWARK RAMPART BASTION CITADEL KEEP TOWER FORT RALLY CHARGE SIEGE FLANK AMBUSH ROUT VALOR MIGHT FURY WRATH RAGE SPITE MALICE GRUDGE HAVOC CHAOS DASH LEAP SPRINT LUNGE DIVE SOAR GLIDE PROWL STALK CREEP SWIFT FLEET BRISK RAPID SPIN WHIRL TWIST COIL SPIRAL ORBIT ARC CURVE BEND LOOP DAWN DUSK NOON NIGHT SHADOW GLEAM GLOW SHINE BEAM RAY HALO LUSTER MURK GLOOM DREAD FELL GRIM STARK BLEAK PALE ASHEN DIRE GRAVE SOMBER EBON ABYSS SHRIEK WAIL RUMBLE HISS GROWL SNARL BARK BELLOW DRONE CHIME TOLL KNELL CLANG CLASH SNAP THUD RING PEAL GONG HORN DRUM FLUTE LYRE PIPE BOLD KEEN FIERCE STERN VAST DEEP GRAND PRIME NOBLE ROYAL SACRED ANCIENT PRIMAL ELDER PURE VIVID SHARP BRIGHT DARK WILD CALM STILL SILENT STRONG PROUD BRAVE WISE JUST RAW DENSE SOLID WHOLE CORE APEX ZENITH NADIR CUSP BRINK VERGE CREST STAR MOON SUN COMET NOVA SOLAR LUNAR ASTRAL COSMIC NEBULA QUASAR PULSAR ECLIPSE AURORA CORONA PHASE WANE WAX WOLF HAWK EAGLE RAVEN SERPENT VIPER COBRA FALCON STAG BEAR LION TIGER LYNX PANTHER CONDOR OSPREY CRANE HERON OWL CROW BULL BOAR RAM HORSE MARE STALLION AX ORB AWE OAT EEL URN ELK ELM ION IRE ORE AIM ZAP JAB JAW JET JOT JAG HEX HEW HUE HUM DIN DUB DYE FIN FIG FOG FUR GAP GEM GNU SOUL MIND WILL FORCE POWER CRAFT SKILL GRACE POISE NERVE GRIT METTLE VIGOR ZEAL VERVE PLUCK GUILE CUNNING WILE LURE TRAP SNARE BAIT DECOY RUSE FEINT GAMBIT PLOY MESA TARN FORD PASS BLUFF KNOLL MOOR HEATH STEPPE TUNDRA DELTA BASIN PLATEAU FJORD ISLE ATOLL STRAIT CHANNEL HARBOR COVE BAY GULF SOUND CREEK BROOK RAPIDS FALLS CASCADE ARCH DOME PILLAR COLUMN BRIDGE WALL MOAT RAMP LEDGE STEP STAIR HALL NAVE ALCOVE NICHE SILL TRUSS BRACE STRUT JOIST FRAME PLINTH DAIS THRONE QUEST HUNT TRIAL ORDEAL RITE RITUAL PACT BOND PLEDGE DECREE EDICT MANDATE LAW RULE REIGN CROWN SCEPTER BANNER EMBLEM BADGE MARK SEAL TOKEN GUILD CLAN TRIBE ORDER SECT COVEN LEGION HORDE SWARM PACK FLOCK BROOD CLUTCH CRUX JINX GLINT DINT STINT KNIT SLIT SPLIT WHIT CLEFT DEFT HEFT LEFT THEFT WEFT BEREFT SHAFT GRAFT RAFT DRAFT TUFT LOFT CROFT DROIT BRUNT BLUNT STUNT RUNT GRUNT FRONT FONT HAUNT GAUNT FLAUNT JAUNT TAUNT SALT MALT HALT JOLT COLT MOLT SMOLT QUALM BALM PSALM FARM HARM ALARM DISARM FOREARM PLUME FUME LOOM ZOOM GROOM BROOM VROOM SCARCE TERSE MORSE COURSE SOURCE NORSE REMORSE WRENCH CLENCH STENCH TRENCH DRENCH FRENCH BENCH TORCH PORCH MARCH LARCH STARCH SEARCH PERCH BIRCH CHURCH THATCH CATCH MATCH BATCH HATCH LATCH PATCH WATCH SCRATCH SNATCH HEDGE WEDGE DREDGE SLEDGE FRIDGE DANCE TRANCE GLANCE STANCE PRANCE CHANCE ADVANCE ENHANCE BLISS MISS KISS DISMISS AMISS REMISS WHISK DISK RISK FRISK TUSK MUSK RUSK HUSK CROAK SOAK STROKE SPOKE BROKE WOKE INVOKE EVOKE PROVOKE VEIN CHAIN PLAIN STRAIN GRAIN TRAIN BRAIN DOMAIN TERRAIN REMAIN TREAD SPREAD THREAD SHRED BRED SLED STEAD INSTEAD COST LOST HOST GHOST MOST POST ROAST TOAST COAST BOAST STREAM DREAM TEAM CREAM SCHEME THEME SUPREME EXTREME SWAY FRAY PRAY STRAY ARRAY DECAY RELAY CONVEY OBEY SURVEY BETRAY THROW FLOW SNOW GROW KNOW BELOW HOLLOW CLIMB RHYME SLIME THYME SUBLIME PARADIGM PROWESS DURESS FORTRESS MISTRESS COMPASS BYPASS SURPASS AMASS CRIMSON LINDEN MAIDEN WARDEN GOLDEN MOLTEN FROZEN CHOSEN WOVEN SCYTHE CRUCIBLE TORRENT TEMPEST MAELSTROM CINDER INFERNO TYPHOON CYCLONE GLACIER ICECAP PERMAFROST MONSOON SOLSTICE EQUINOX MERIDIAN TWILIGHT MIDNIGHT DAYBREAK SENTINEL WATCHER HUNTER RANGER SCOUT TRACKER SEEKER FINDER KEEPER BINDER ARBITER HERALD ENVOY REGENT PREFECT CONSUL MARSHAL VASSAL SQUIRE KNIGHT PALADIN CHAMPION PARAGON MONARCH SOVEREIGN OVERLORD WARLORD CHIEFTAIN PATRIARCH MATRIARCH PROPHET MYSTIC HERMIT ASCETIC NOMAD PILGRIM WANDERER EXILE OUTCAST ROGUE REBEL VAGRANT DRIFTER MARAUDER BRIGAND CORSAIR BUCCANEER RAIDER REAVER SLAYER BERSERKER GLADIATOR CENTURION LEGIONNAIRE TEMPLAR CRUSADER INQUISITOR ZEALOT HARBINGER AUGUR PORTENT PRESAGE AUGURY PROPHECY DIVINATION REVELATION EPIPHANY REMNANT VESTIGE ARTIFACT FRAGMENT SPLINTER SLIVER MORSEL CRUMB PARTICLE MOTE FILAMENT STRAND FIBER SINEW TENDON LIGAMENT MARROW ICHOR ELIXIR POTION TONIC SALVE REMEDY ANTIDOTE CURE PANACEA CATALYST REAGENT COMPOUND TINCTURE DISTILL INFUSE IMBUE ENCHANT CONJURE SUMMON BANISH DISPEL REVOKE ANNUL NEGATE NULLIFY SUNDER CLEAVE REND SHATTER FRACTURE RUPTURE PIERCE IMPALE SKEWER GORE MAIM RAVAGE DEVASTATE OBLITERATE ANNIHILATE ERADICATE PURGE EXPUNGE EFFACE EXTINGUISH QUELL SUBDUE VANQUISH CONQUER PREVAIL TRIUMPH ASCEND TRANSCEND EVOLVE AWAKEN ARISE EMERGE MANIFEST EMBODY HARNESS WIELD MASTER COMMAND PROCLAIM SANCTIFY CONSECRATE ANOINT BESTOW ENDOW BEQUEST LEGACY HEIRLOOM COVENANT COMPACT TREATY ACCORD ALLIANCE FEDERATION DOMINION REALM KINGDOM EMPIRE DYNASTY EPOCH AEON CYCLE HELIX MATRIX LATTICE TAPESTRY MOSAIC CIPHER ENIGMA RIDDLE PUZZLE LABYRINTH MAZE CAULDRON CHALICE GOBLET GRAIL TRIDENT MAUL FLAIL HALBERD GLAIVE RAPIER SABRE KATANA MACHETE SCIMITAR CUTLASS BROADSWORD GREATSWORD LONGBOW CROSSBOW BALLISTA CATAPULT TREBUCHET MIRAGE ILLUSION REVENANT LICH BANSHEE GHOUL VAMPIRE WEREWOLF GARGOYLE BASILISK KRAKEN LEVIATHAN BEHEMOTH COLOSSUS JUGGERNAUT MONOLITH OBELISK ZIGGURAT MINARET PAGODA DOLMEN BARROW CATACOMB DUNGEON PARAPET TURRET BATTLEMENT DRAWBRIDGE PORTCULLIS BARBICAN PALISADE CONDUIT PYLON TORQUE RATCHET LODESTONE KEYSTONE CAPSTONE BEDROCK SEQUOIA REDWOOD CYPRESS HEMLOCK WILLOW ASPEN HICKORY JUNIPER MAGNOLIA HAWTHORN SAFFRON MYRRH MANGROVE ORCHID THISTLE POPPY HEATHER JASMINE VECTOR SCALAR TENSOR FULCRUM PIVOT CRESCENT PINNACLE VERTEX""".split()
# 10 bits per word, 7 words = 70 bits (covers 64-bit seed)
# The word list is the protocol. Once locked, it's PERMANENT.
# Future: locale-specific word lists map same indices to different languages.
_MNEM_BITS = 10
_MNEM_COUNT = 1 << _MNEM_BITS
assert len(MNEMONIC_WORDS) == _MNEM_COUNT, f"Need exactly {_MNEM_COUNT} words, have {len(MNEMONIC_WORDS)}"
_WORD_TO_IDX = {w: i for i, w in enumerate(MNEMONIC_WORDS)}
def seed_to_words(seed: int) -> str:
"""Encode a 64-bit seed as 7 memorable words. Full fidelity. Offline forever.
This is the hero use case: memorize 7 words, reconstruct the exact card anywhere."""
words = []
remaining = seed
for _ in range(7):
idx = remaining & (_MNEM_COUNT - 1)
words.append(MNEMONIC_WORDS[idx])
remaining >>= _MNEM_BITS
return " ".join(words)
def words_to_seed(mnemonic: str) -> int:
"""Decode 7 words back to a 64-bit seed. Lossless round-trip."""
words = [w.strip().upper() for w in mnemonic.replace("-", " ").split()]
if len(words) != 7:
raise ValueError(f"Mnemonic must be 7 words, got {len(words)}")
seed = 0
for i, word in enumerate(words):
if word not in _WORD_TO_IDX:
raise ValueError(f"Unknown word: {word}")
seed |= _WORD_TO_IDX[word] << (_MNEM_BITS * i)
return seed
# ─── AGENT TYPES (the color identity — like Pokemon types or MTG colors) ───
# Every agent has a primary type derived from its category.
# Tags can add a secondary type. Dual-type agents are rarer and more valuable.
AGENT_TYPES = {
"LOGIC": {"color": "#58a6ff", "icon": "brain", "label": "Logic"},
"DATA": {"color": "#3fb950", "icon": "stream", "label": "Data"},
"SOCIAL": {"color": "#d29922", "icon": "people", "label": "Social"},
"SHIELD": {"color": "#f0f0f0", "icon": "shield", "label": "Shield"},
"CRAFT": {"color": "#f85149", "icon": "gear", "label": "Craft"},
"HEAL": {"color": "#ff7eb3", "icon": "heart", "label": "Heal"},
"WEALTH": {"color": "#bc8cff", "icon": "coin", "label": "Wealth"},
}
# Category → primary type mapping
CATEGORY_TYPE = {
"core": "LOGIC",
"devtools": "LOGIC",
"pipeline": "DATA",
"integrations": "DATA",
"productivity": "SOCIAL",
"general": "SOCIAL",
"federal_government": "SHIELD",
"slg_government": "SHIELD",
"it_management": "SHIELD",
"manufacturing": "CRAFT",
"energy": "CRAFT",
"retail_cpg": "CRAFT",
"healthcare": "HEAL",
"human_resources": "HEAL",
"financial_services": "WEALTH",
"b2b_sales": "WEALTH",
"b2c_sales": "WEALTH",
"professional_services": "WEALTH",
"software_digital_products": "DATA",
}
# Tag keywords → secondary type (first match wins)
TAG_TYPE_HINTS = {
"LOGIC": ["ai", "ml", "algorithm", "compute", "analysis", "ast", "parse", "model", "intelligence"],
"DATA": ["data", "pipeline", "etl", "sync", "migration", "import", "export", "extract", "transform"],
"SOCIAL": ["email", "chat", "meeting", "communication", "demo", "presentation", "coach", "assistant"],
"SHIELD": ["compliance", "security", "audit", "governance", "risk", "regulatory", "permit", "license"],
"CRAFT": ["inventory", "supply", "maintenance", "production", "manufacturing", "field", "dispatch"],
"HEAL": ["patient", "clinical", "care", "health", "wellness", "staff", "credentialing", "intake"],
"WEALTH": ["sales", "revenue", "pricing", "deal", "proposal", "billing", "financial", "portfolio"],
}
# Type effectiveness chart — weakness and resistance
# LOGIC > DATA > SOCIAL > SHIELD > CRAFT > HEAL > WEALTH > LOGIC
TYPE_WEAKNESS = {
"LOGIC": "WEALTH", # gold corrupts pure logic
"DATA": "LOGIC", # logic deconstructs raw data
"SOCIAL": "DATA", # data exposes social spin
"SHIELD": "SOCIAL", # social pressure overwhelms bureaucracy
"CRAFT": "SHIELD", # regulation constrains craft
"HEAL": "CRAFT", # industrial demands strain care
"WEALTH": "HEAL", # care costs erode wealth
}
TYPE_RESISTANCE = {
"LOGIC": "DATA",
"DATA": "SOCIAL",
"SOCIAL": "SHIELD",
"SHIELD": "CRAFT",
"CRAFT": "HEAL",
"HEAL": "WEALTH",
"WEALTH": "LOGIC",
}
# Evolution stages — tied to quality tier
EVOLUTION_STAGES = {
"experimental": {"stage": 0, "label": "Seed", "icon": "seed"},
"community": {"stage": 1, "label": "Base", "icon": "sprout"},
"verified": {"stage": 2, "label": "Evolved", "icon": "flame"},
"official": {"stage": 3, "label": "Legendary", "icon": "crown"},
}
# ─── STAT DERIVATION (deterministic from manifest, never random) ───
def _derive_types(category: str, tags: list) -> list:
"""Derive primary + optional secondary type from category and tags."""
primary = CATEGORY_TYPE.get(category, "SOCIAL")
types = [primary]
# Check tags for secondary type
tag_str = " ".join(t.lower() for t in tags)
for type_name, keywords in TAG_TYPE_HINTS.items():
if type_name == primary:
continue
if any(kw in tag_str for kw in keywords):
types.append(type_name)
break # max 2 types
return types
def _derive_stats(name: str, tier: str, tags: list, deps: list,
env_vars: list, version_str: str, description: str) -> dict:
"""Derive 5 stats (HP, ATK, DEF, SPD, INT) deterministically from manifest data.
Each stat is 10-100. The seed ensures unique distributions per agent."""
rng = mulberry32(seed_hash(name + ":stats"))
# Base stats from tier
tier_base = {"experimental": 15, "community": 30, "verified": 50, "official": 70}
base = tier_base.get(tier, 30)
# Version multiplier (higher version = more refined)
try:
v_parts = [int(x) for x in version_str.split(".")]
v_bonus = min(15, v_parts[0] * 3 + v_parts[1])
except (ValueError, IndexError):
v_bonus = 0
# Tag/dep/env contribution
tag_bonus = min(20, len(tags) * 3)
dep_penalty = min(20, len(deps) * 5)
env_bonus = min(15, len(env_vars) * 5)
desc_bonus = min(10, len(description.split()) // 5)
def clamp(v):
return max(10, min(100, int(v)))
# Each stat has a base + deterministic seed offset + manifest bonuses
hp = clamp(base + v_bonus + tag_bonus + rng() * 25)
atk = clamp(base + tag_bonus + desc_bonus + rng() * 30)
dfs = clamp(base + env_bonus + v_bonus + rng() * 20) # "def" is reserved
spd = clamp(base + 20 - dep_penalty + rng() * 25)
itl = clamp(base + desc_bonus + tag_bonus + rng() * 20)
return {"hp": hp, "atk": atk, "def": dfs, "spd": spd, "int": itl}
def _derive_abilities(name: str, tags: list, category: str, tier: str) -> list:
"""Generate 1-3 abilities deterministically from agent identity."""
rng = mulberry32(seed_hash(name + ":abilities"))
# Ability templates by type
ABILITY_POOL = {
"LOGIC": [
("Analyze", "Inspect target data source. Draw insight."),
("Compute", "Process input through algorithm. Return structured result."),
("Parse", "Decompose complex input into structured components."),
("Reason", "Apply chain-of-thought to derive conclusion."),
],
"DATA": [
("Extract", "Pull data from connected source into working memory."),
("Transform", "Reshape data to match target schema."),
("Sync", "Synchronize state between two systems."),
("Pipeline", "Execute multi-step data flow. Each stage feeds the next."),
],
"SOCIAL": [
("Assist", "Guide user through task with context-aware suggestions."),
("Draft", "Compose human-quality text for target audience."),
("Coach", "Observe performance and provide actionable feedback."),
("Present", "Format findings into presentation-ready output."),
],
"SHIELD": [
("Audit", "Scan target for compliance violations. Report findings."),
("Enforce", "Apply policy rules. Block non-compliant actions."),
("Monitor", "Continuously watch for anomalies. Alert on deviation."),
("Certify", "Validate against standards. Issue compliance attestation."),
],
"CRAFT": [
("Build", "Assemble components into deployable artifact."),
("Optimize", "Tune process parameters for maximum throughput."),
("Schedule", "Allocate resources across timeline. Minimize conflicts."),
("Dispatch", "Route work to available capacity. Track completion."),
],
"HEAL": [
("Triage", "Assess priority and route to appropriate handler."),
("Screen", "Evaluate against criteria. Flag items needing attention."),
("Support", "Provide contextual guidance through complex process."),
("Track", "Monitor progress against care plan. Alert on gaps."),
],
"WEALTH": [
("Prospect", "Identify and qualify potential opportunities."),
("Forecast", "Project future values from historical patterns."),
("Negotiate", "Propose terms optimized for mutual value."),
("Close", "Execute final steps of value exchange. Confirm settlement."),
],
}
primary_type = CATEGORY_TYPE.get(category, "SOCIAL")
pool = ABILITY_POOL.get(primary_type, ABILITY_POOL["SOCIAL"])
# Number of abilities: 1 for experimental, 2 for community, 3 for verified/official
tier_count = {"experimental": 1, "community": 2, "verified": 3, "official": 3}
count = tier_count.get(tier, 2)
abilities = []
used = set()
for _ in range(count):
idx = int(rng() * len(pool))
# Avoid duplicates
attempts = 0
while idx in used and attempts < len(pool):
idx = (idx + 1) % len(pool)
attempts += 1
used.add(idx)
ab_name, ab_text = pool[idx]
# Damage/cost derived from seed
cost = int(rng() * 3) + 1 # 1-3 energy
damage = int(rng() * 40) + 10 # 10-50
abilities.append({
"name": ab_name,
"text": ab_text,
"cost": cost,
"damage": damage,
})
return abilities
# ─── FLAVOR TEXT + TYPE LINE ───
_FLAVOR_FRAGMENTS = [
"Built for the ecosystem. Ready for the edge.",
"One file. Infinite possibilities.",
"Runs anywhere the RAPP runtime breathes.",
"Forged in the registry. Trusted in production.",
"A single-file agent. A single promise: perform.",
"When the network calls, this agent answers.",
"Data in. Insight out. No drama.",
"The pipeline starts here.",
"Born from a manifest. Raised in the registry.",
"Your code, your agent, your card. Permanent.",
"Not just code. Identity.",
"The forge remembers every agent it ever touched.",
]
_TYPE_PREFIXES = {
"core": "Foundation",
"pipeline": "Pipeline",
"integrations": "Integration",
"productivity": "Utility",
"devtools": "DevTool",
"general": "General",
"b2b_sales": "B2B Sales",
"b2c_sales": "B2C Sales",
"healthcare": "Healthcare",
"financial_services": "Financial",
"manufacturing": "Industrial",
"energy": "Energy",
"federal_government": "Federal",
"slg_government": "Government",
"human_resources": "HR",
"it_management": "IT Ops",
"professional_services": "Professional",
"retail_cpg": "Retail",
"software_digital_products": "Software",
}
def mint_card(path: str) -> dict:
"""
Mint a card from an agent file. The canonical path:
manifest → forge_seed() → resolve_card_from_seed() = the card
The seed IS the card. mint_card just reads the manifest, forges the
seed, and resolves from it. Both mint_card and resolve_card_from_seed
produce identical output for the same agent. This is the protocol.
"""
manifest = extract_manifest(path)
if manifest is None:
raise ValueError(f"No __manifest__ found in {path}")
name = manifest.get("name", path)
category = manifest.get("category", "general")
tier = manifest.get("quality_tier", "community")
tags = manifest.get("tags", [])
deps = manifest.get("dependencies", [])
# Forge the seed FROM the manifest data
seed = forge_seed(name, category, tier, tags, deps)
# Resolve the card FROM the seed — one canonical path
card = resolve_card_from_seed(seed)
# Enrich with manifest metadata that doesn't affect the card identity
card["name"] = name
card["display_name"] = manifest.get("display_name", name)
card["version"] = manifest.get("version", "1.0.0")
card["description"] = manifest.get("description", "")
card["author"] = manifest.get("author", "")
card["tags"] = tags
card["power"] = card["stats"]["atk"]
card["toughness"] = card["stats"]["def"]
card["name_seed"] = seed_hash(name) & 0xFFFFFFFF
card["_resolved_from"] = "manifest"
return card
def card_value(name: str) -> dict:
"""Fetch registry, find agent, compute floor value based on tier."""
registry = fetch_registry()
agent = None
for a in registry.get("agents", []):
if a.get("name") == name:
agent = a
break
if agent is None:
return {"error": f"Agent '{name}' not found in registry"}
tier = agent.get("quality_tier", "community")
rarity = TIER_TO_RARITY.get(tier, "core")
floor_pts = RARITY_FLOOR.get(rarity, 10)
# Floor BTC: 1 BTC = ~10,000,000 pts (illustrative peg)
floor_btc = round(floor_pts / 10_000_000, 8)
return {
"name": name,
"display_name": agent.get("display_name", name),
"tier": tier,
"rarity": rarity,
"rarity_label": RARITY_LABELS.get(rarity, rarity),
"floor_pts": floor_pts,
"floor_btc": floor_btc,
}
def forge_seed(name: str, category: str, tier: str, tags: list, deps: list) -> int:
"""
Forge a seed FROM agent data. The seed IS the card's DNA.
Packs the agent's identity, types, tier, and hints into a 64-bit
integer. Anyone with this number reconstructs the exact card —
no registry, no network, no lookup. The protocol is permanent.
Bit layout (64 bits):
[63-32] name_hash (32 bits — identity, drives stat variation)
[31-27] category_idx (5 bits — 0-18, maps to primary type)
[26-24] secondary_type (3 bits — 0-7, 7=none)
[23-22] tier_idx (2 bits — 0-3)
[21-17] tag_count (5 bits — 0-31, influences ability count)
[16-13] dep_count (4 bits — 0-15, influences retreat cost)
[12-0] tag_hash (13 bits — drives ability selection)
"""
name_hash = seed_hash(name) & 0xFFFFFFFF
cat_list = list(CATEGORY_TYPE.keys())
cat_idx = cat_list.index(category) if category in cat_list else 0
# Derive types the same way as _derive_types, then encode
types = _derive_types(category, tags)
type_names = list(AGENT_TYPES.keys())
secondary_idx = 7 # 7 = no secondary type
if len(types) > 1:
secondary_idx = type_names.index(types[1]) if types[1] in type_names else 7
tier_map = {"experimental": 0, "community": 1, "verified": 2, "official": 3}
tier_idx = tier_map.get(tier, 1)
tag_count = min(31, len(tags))
dep_count = min(15, len(deps))
tag_hash = seed_hash(" ".join(tags)) & 0x1FFF if tags else 0
seed = (
(name_hash << 32) |
(cat_idx << 27) |
(secondary_idx << 24) |
(tier_idx << 22) |
(tag_count << 17) |
(dep_count << 13) |
tag_hash
)
return seed
def resolve_card_from_seed(seed: int) -> dict:
"""
Reconstruct a card from a seed number.
Two modes:
- 32-bit name seed (< 2^32): the card's PERMANENT identity.
Resolves to the CURRENT version via registry lookup.
This is the number you memorize and share.
- 64-bit full seed (>= 2^32): a SPECIFIC version's DNA.
Resolves to the exact card from that version, offline.
This is the versioned snapshot.
Share the short seed. It always points to the latest card.
"""
# 32-bit name seed → lookup current version in registry
if seed < (1 << 32):
try:
registry = fetch_registry()
for agent in registry.get("agents", []):
name_hash = seed_hash(agent["name"]) & 0xFFFFFFFF
if name_hash == seed:
return resolve_card(agent["name"])
except Exception:
pass
# Not found in registry — fall through to generate a preview
# Pack as if it were the top 32 bits with default lower bits
seed = seed << 32 # name_hash only, defaults for everything else
# 64-bit full seed → unpack exact version
# Unpack the seed DNA
name_hash = (seed >> 32) & 0xFFFFFFFF
cat_idx = (seed >> 27) & 0x1F
secondary_idx = (seed >> 24) & 0x7
tier_idx = (seed >> 22) & 0x3
tag_count = (seed >> 17) & 0x1F
dep_count = (seed >> 13) & 0xF
tag_hash = seed & 0x1FFF
# Reconstruct category → primary type
cat_list = list(CATEGORY_TYPE.keys())
category = cat_list[cat_idx] if cat_idx < len(cat_list) else "general"
primary_type = CATEGORY_TYPE.get(category, "SOCIAL")
# Reconstruct tier
tier_list = ["experimental", "community", "verified", "official"]
tier = tier_list[tier_idx] if tier_idx < len(tier_list) else "community"
rarity = TIER_TO_RARITY.get(tier, "core")
evo = EVOLUTION_STAGES.get(tier, EVOLUTION_STAGES["community"])
# Reconstruct types (secondary encoded directly)
types = [primary_type]
type_names = list(AGENT_TYPES.keys())
if secondary_idx < len(type_names) and type_names[secondary_idx] != primary_type:
types.append(type_names[secondary_idx])
# Stats — same derivation as _derive_stats using only seed-encoded fields
# We pass empty strings for version/description since those aren't in the seed
# but the core stat inputs (name, tier, tags, deps, env_vars) ARE encoded
fake_tags = ["x"] * tag_count # count is what matters, not the strings
fake_deps = ["x"] * dep_count
stats = _derive_stats(
chr(name_hash & 0xFF) * 4, # reconstruct a name-like string from hash
tier, fake_tags, fake_deps, [], "1.0.0", ""
)
# Override with name_hash-seeded stats for full fidelity
rng = mulberry32(name_hash ^ 0x57415453) # XOR with "STAT" for unique stream
tier_base = {"experimental": 15, "community": 30, "verified": 50, "official": 70}
base = tier_base.get(tier, 30)
tag_bonus = min(20, tag_count * 3)
dep_penalty = min(20, dep_count * 5)
clamp = lambda v: max(10, min(100, int(v)))
hp = clamp(base + tag_bonus + rng() * 25)
atk = clamp(base + tag_bonus + rng() * 30)
dfs = clamp(base + rng() * 20)
spd = clamp(base + 20 - dep_penalty + rng() * 25)
itl = clamp(base + tag_bonus + rng() * 20)
stats = {"hp": hp, "atk": atk, "def": dfs, "spd": spd, "int": itl}