uro-cli 0.17.0__tar.gz → 0.19.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: uro-cli
3
- Version: 0.17.0
3
+ Version: 0.19.0
4
4
  Summary: Uro Engine reference client — play, dry-run, and dev tools against the engine
5
5
  Project-URL: Homepage, https://github.com/cupskeee/uro
6
6
  Project-URL: Repository, https://github.com/cupskeee/uro
@@ -12,8 +12,8 @@ Requires-Python: >=3.12
12
12
  Requires-Dist: python-dotenv>=1.0
13
13
  Requires-Dist: rich>=13.9
14
14
  Requires-Dist: typer>=0.27.2
15
- Requires-Dist: uro-core[llm,postgres]==0.17.0
16
- Requires-Dist: uro-server==0.17.0
15
+ Requires-Dist: uro-core[llm,postgres]==0.19.0
16
+ Requires-Dist: uro-server==0.19.0
17
17
  Requires-Dist: websockets>=16.1
18
18
  Description-Content-Type: text/markdown
19
19
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "uro-cli"
3
- version = "0.17.0"
3
+ version = "0.19.0"
4
4
  description = "Uro Engine reference client — play, dry-run, and dev tools against the engine"
5
5
  license = "MIT"
6
6
  license-files = ["LICENSE"]
@@ -13,8 +13,8 @@ requires-python = ">=3.12"
13
13
  # pair a new uro-cli with an old uro-core; `just release` bumps all three together, and the
14
14
  # `{workspace = true}` sources make a drifted pin fail `uv sync` locally.
15
15
  dependencies = [
16
- "uro-core[postgres,llm]==0.17.0",
17
- "uro-server==0.17.0",
16
+ "uro-core[postgres,llm]==0.19.0",
17
+ "uro-server==0.19.0",
18
18
  "typer>=0.27.2",
19
19
  "rich>=13.9",
20
20
  "websockets>=16.1",
@@ -180,3 +180,18 @@ def test_token_revoke_by_participant_and_list(monkeypatch) -> None: # type: ign
180
180
  app, ["token", "revoke", "c1", "--participant", "bob", "--target", "t", "--token", "op"]
181
181
  )
182
182
  assert both.exit_code == 1
183
+
184
+
185
+ def test_help_keeps_bracketed_names() -> None:
186
+ # Typer renders help with Rich, which takes `[pacing]` for a markup tag and drops it: the help
187
+ # read "off unless the world's `` turns it on". Escaped, the names survive.
188
+ from typer.testing import CliRunner
189
+ from uro_cli.main import app
190
+
191
+ for args, name in (
192
+ (["campaign", "pacing", "--help"], "[pacing]"),
193
+ (["world", "seed", "--help"], "[history.vocabulary]"),
194
+ (["ruleset", "list", "--help"], "[ruleset.config]"),
195
+ ):
196
+ out = CliRunner().invoke(app, args, env={"COLUMNS": "200"}).output
197
+ assert name in out, (args, out)
@@ -18,7 +18,7 @@ from typing import Any
18
18
  import typer
19
19
  from dotenv import find_dotenv, load_dotenv
20
20
  from uro_core.adapters.postgres.store import PostgresEventStore
21
- from uro_core.pipeline.engine import BeatResult, Engine
21
+ from uro_core.pipeline.engine import BeatMechanics, BeatResult, Engine
22
22
  from uro_core.ports.model_registry import ROLES
23
23
  from uro_core.providers.router import ProviderRouter
24
24
  from uro_core.rulesets import registry
@@ -67,6 +67,9 @@ outbox_app = typer.Typer(
67
67
  help="The transactional outbox — publish committed beats to other processes (D-57).",
68
68
  )
69
69
  ruleset_app = typer.Typer(no_args_is_help=True, help="The built-in ruleset registry (docs/06).")
70
+ rules_app = typer.Typer(
71
+ no_args_is_help=True, help="World rules (rules.yaml / agendas.yaml): their grammar (docs/17)."
72
+ )
70
73
  policy_app = typer.Typer(
71
74
  no_args_is_help=True,
72
75
  help="Which emergent world state play may create — the instance's extraction policy (D-49).",
@@ -84,6 +87,7 @@ app.add_typer(provider_app, name="provider")
84
87
  provider_app.add_typer(credential_app, name="credential")
85
88
  app.add_typer(outbox_app, name="outbox")
86
89
  app.add_typer(ruleset_app, name="ruleset")
90
+ app.add_typer(rules_app, name="rules")
87
91
  app.add_typer(policy_app, name="extraction-policy")
88
92
  app.add_typer(memory_app, name="memory")
89
93
 
@@ -114,6 +118,41 @@ async def _metered(router: ProviderRouter) -> AsyncIterator[ProviderRouter]:
114
118
  await store.close()
115
119
 
116
120
 
121
+ async def _play_creates_actors() -> bool:
122
+ """Whether this instance lets play create actors (its extraction policy, D-49), read best
123
+ effort like `_metered`: with no database, the default (on), as a pure parse assumes."""
124
+ try:
125
+ store = build_store()
126
+ await asyncio.wait_for(connect_store(store), timeout=5)
127
+ except Exception:
128
+ return True
129
+ try:
130
+ return (await store.get_extraction_policy()).extract_actors
131
+ finally:
132
+ await store.close()
133
+
134
+
135
+ def _require_migrated(store: PostgresEventStore) -> None:
136
+ """Refuse to serve a database this code's migrations haven't all reached: it would fail at
137
+ the first write that needs a new column, mid-play. Names what's pending and the fix."""
138
+
139
+ async def _pending() -> list[str]:
140
+ await connect_store(store)
141
+ try:
142
+ return await store.pending_migrations()
143
+ finally:
144
+ await store.close()
145
+
146
+ pending = asyncio.run(_pending())
147
+ if pending:
148
+ typer.echo(
149
+ f"error: the database is missing {len(pending)} migration(s) this code needs: "
150
+ f"{', '.join(pending)}. Run `uro db migrate` first.",
151
+ err=True,
152
+ )
153
+ raise typer.Exit(1)
154
+
155
+
117
156
  def _run_async(coro_factory) -> None: # type: ignore[no-untyped-def]
118
157
  """Run an async command, turning config/credential/lookup errors into a clean message."""
119
158
  try:
@@ -212,6 +251,31 @@ def db_migrate() -> None:
212
251
  _run_async(_run)
213
252
 
214
253
 
254
+ @db_app.command("rebuild-projections")
255
+ def db_rebuild_projections(
256
+ world: str = typer.Option(None, "--world", help="one world (name or id); default: every world"),
257
+ ) -> None:
258
+ """Rebuild projections from history (D-102): after `uro db migrate` adds a projection column
259
+ (027: each thread's development and beat counts), so campaigns played before it count their
260
+ whole past. Drops the world's snapshots (a cache) and replays each branch. Run it while the
261
+ world isn't being played."""
262
+
263
+ async def _run() -> None:
264
+ store = build_store()
265
+ await connect_store(store)
266
+ try:
267
+ world_id = (await _world_or_exit(store, world)).world_id if world else None
268
+ done = await store.rebuild_projections(world_id)
269
+ finally:
270
+ await store.close()
271
+ typer.echo(
272
+ f"rebuilt {done['branches']} branches in {done['worlds']} worlds "
273
+ f"({done['snapshots_dropped']} snapshots dropped; new ones form as play goes on)"
274
+ )
275
+
276
+ _run_async(_run)
277
+
278
+
215
279
  @world_app.command("new")
216
280
  def world_new(
217
281
  name: str,
@@ -219,17 +283,34 @@ def world_new(
219
283
  "", "--ruleset", help="a built-in ruleset id (`uro ruleset list`); default uro-basic"
220
284
  ),
221
285
  pc: str = typer.Option("Player", "--pc", help="the player character's name"),
286
+ description: str = typer.Option(
287
+ "", "--description", help="a short pitch for whoever lists the world (D-104)"
288
+ ),
289
+ content_rating: str = typer.Option(
290
+ None,
291
+ "--content-rating",
292
+ help="declare the world's content ceiling: none | mild | mature | explicit (D-104)",
293
+ ),
222
294
  ) -> None:
223
295
  """Create a world (+ its main branch) and a ready-to-play campaign with a default,
224
296
  sheeted PC. Prints the campaign id."""
225
297
 
226
298
  async def _run() -> None:
299
+ from uro_core.worldpack.models import ContentDecl
300
+
227
301
  rs = build_ruleset(ruleset) # an unknown id fails here, before any write
302
+ content = (
303
+ ContentDecl.model_validate({"rating": content_rating}).model_dump()
304
+ if content_rating
305
+ else None
306
+ )
228
307
  sheet, ruleset_id = _build_pc_sheet(rs), rs.id
229
308
  store = build_store()
230
309
  await connect_store(store)
231
310
  try:
232
- world = await store.create_world(name, ruleset_id=ruleset)
311
+ world = await store.create_world(
312
+ name, ruleset_id=ruleset, description=description, content=content
313
+ )
233
314
  campaign = await store.start_campaign(
234
315
  world.world_id,
235
316
  world.main_branch_id,
@@ -248,6 +329,21 @@ def world_new(
248
329
  _run_async(_run)
249
330
 
250
331
 
332
+ @world_app.command("parse")
333
+ def world_parse(path: str) -> None:
334
+ """Print the pack at <path> as Uro reads it, as JSON (D-105): the manifest with every default
335
+ filled in, the seeds, lore, prompt files and rule pack. Nothing is imported."""
336
+ from uro_core.errors import PackError
337
+ from uro_core.worldpack.parse import parse_pack
338
+
339
+ try:
340
+ pack = parse_pack(path)
341
+ except PackError as exc:
342
+ typer.echo(f"error: {exc}", err=True)
343
+ raise typer.Exit(1) from exc
344
+ typer.echo(json.dumps(pack.model_dump(mode="json"), indent=2))
345
+
346
+
251
347
  @world_app.command("validate")
252
348
  def world_validate(path: str) -> None:
253
349
  """Parse a world pack and report its sufficiency (docs/09) — the creator loop, no import."""
@@ -301,10 +397,15 @@ def world_create(
301
397
  store = build_store()
302
398
  try:
303
399
  pack = parse_pack(path)
304
- # build the provider only when a gap needs it: a runnable pack needs no key
305
- needs_fill = backfill and check_sufficiency(pack).grade != "runnable"
306
- router = build_router(provider, model) if needs_fill else None
307
400
  await connect_store(store)
401
+ # build the provider only when a gap needs it (a runnable pack needs no key), graded
402
+ # as the import grades it: with this instance's extraction policy (D-108 review)
403
+ makes_people = (await store.get_extraction_policy()).extract_actors
404
+ needs_fill = (
405
+ backfill
406
+ and check_sufficiency(pack, play_creates_actors=makes_people).grade != "runnable"
407
+ )
408
+ router = build_router(provider, model) if needs_fill else None
308
409
  if router is not None: # the backfill's calls are metered like any other (D-66)
309
410
  router.recorder = store.record_llm_call
310
411
  result = await import_pack(store, pack, backfill_router=router)
@@ -318,34 +419,44 @@ def world_create(
318
419
  for a in result.backfilled:
319
420
  typer.echo(f" backfilled + committed: {a}")
320
421
  if pack.manifest.history.vocabulary is not None: # D-97: seeding speaks the pack's words
321
- typer.echo(f"seed history: uro world seed {path} --seed 42")
422
+ typer.echo(f"seed history: uro world seed {world.world_id} --seed 42")
322
423
 
323
424
  _run_async(_run)
324
425
 
325
426
 
326
427
  @world_app.command("seed")
327
428
  def world_seed(
328
- path: str,
429
+ target_ref: str = typer.Argument(
430
+ ...,
431
+ metavar="WORLD_OR_PACK",
432
+ help="a world (id or name), or the pack directory it was made from",
433
+ ),
329
434
  seed: int = typer.Option(42, "--seed", help="RNG seed for History"),
330
435
  world: str = typer.Option(
331
- None, "--world", help="the world to seed (id or name; default: the pack's name)"
436
+ None,
437
+ "--world",
438
+ help="with a pack: the world to seed (id or name; default: the pack's name)",
332
439
  ),
333
440
  ) -> None:
334
- """Run History seeding on the world imported from <path>: layer a seed-dependent past (power
335
- groups, their leaders and conflicts, in the pack's [history.vocabulary]) on top of the authored
336
- geography (docs/09). Same pack + a different seed → a different history on identical
337
- geography."""
441
+ """Run History seeding on a world: layer a seed-dependent past (power groups, their leaders
442
+ and conflicts, in the manifest's \\[history.vocabulary]) on top of the authored geography
443
+ (docs/09). A world keeps the manifest it was made from (D-104), so naming the world is enough;
444
+ a world made before that takes its pack directory. Same manifest + a different seed → a
445
+ different history on identical geography."""
338
446
 
339
447
  async def _run() -> None:
448
+ from pathlib import Path
449
+
340
450
  from uro_core.errors import PackError
341
451
  from uro_core.worldpack.create import seed_world
342
452
  from uro_core.worldpack.parse import parse_pack
343
453
 
344
454
  store = build_store()
345
455
  try:
346
- pack = parse_pack(path)
456
+ pack = parse_pack(target_ref) if (Path(target_ref) / "world.toml").is_file() else None
347
457
  await connect_store(store)
348
- target = await _world_or_exit(store, world or pack.manifest.name)
458
+ name = world or (pack.manifest.name if pack is not None else target_ref)
459
+ target = await _world_or_exit(store, name)
349
460
  result = await seed_world(store, target, pack, seed)
350
461
  except PackError as exc:
351
462
  typer.echo(f"error: {exc}", err=True)
@@ -381,13 +492,18 @@ def world_backfill(
381
492
  except PackError as exc:
382
493
  typer.echo(f"error: {exc}", err=True)
383
494
  raise typer.Exit(1) from exc
384
- before = check_sufficiency(pack)
495
+ # graded as the import (and POST /worlds/backfill) grade it: this instance's extraction
496
+ # policy, when the database answers (D-108 review)
497
+ makes_people = await _play_creates_actors()
498
+ before = check_sufficiency(pack, play_creates_actors=makes_people)
385
499
  if before.grade == "runnable":
386
500
  typer.echo("pack is already runnable — nothing to backfill")
387
501
  return
388
502
  async with _metered(build_router(provider, model)) as router:
389
- augmented, added = await backfill_gaps(pack, router, report=before)
390
- after = check_sufficiency(augmented)
503
+ augmented, added = await backfill_gaps(
504
+ pack, router, report=before, play_creates_actors=makes_people
505
+ )
506
+ after = check_sufficiency(augmented, play_creates_actors=makes_people)
391
507
  typer.echo(f"backfill: {before.grade} → {after.grade}")
392
508
  for a in added:
393
509
  typer.echo(f" + {a}")
@@ -545,13 +661,25 @@ def play(
545
661
  continue
546
662
  try:
547
663
  results: list[BeatResult] = []
664
+ mechanics: list[BeatMechanics] = []
548
665
  async for chunk in engine.run_beat_stream(
549
- campaign, PARTICIPANT, intent, on_result=results.append
666
+ campaign,
667
+ PARTICIPANT,
668
+ intent,
669
+ on_result=results.append,
670
+ on_mechanics=mechanics.append,
550
671
  ):
672
+ if mechanics: # the rules' answer, before the story (D-100)
673
+ m = mechanics.pop()
674
+ checks = [c.model_dump() for c in m.outcomes]
675
+ for line in mechanics_lines({"checks": checks, "mode": m.mode}):
676
+ typer.echo(line)
551
677
  sys.stdout.write(chunk)
552
678
  sys.stdout.flush()
553
679
  sys.stdout.write("\n")
554
- for line in beat_detail_lines(_details(results[0]) if results else {}, day):
680
+ for line in beat_detail_lines(
681
+ _details(results[0]) if results else {}, day, mechanics_shown=True
682
+ ):
555
683
  typer.echo(line)
556
684
  if results:
557
685
  day = results[0].world_day
@@ -572,21 +700,36 @@ def _details(result: BeatResult) -> dict[str, Any]:
572
700
  "mode": result.mode,
573
701
  "world_day": result.world_day,
574
702
  "created": [c.model_dump() for c in result.created],
703
+ "threads_changed": [t.model_dump() for t in result.threads_changed],
575
704
  }
576
705
 
577
706
 
707
+ def mechanics_lines(details: dict[str, Any]) -> list[str]:
708
+ """Each check's outcome and a fight — what the rules decided (shown before the narration
709
+ when the server sends `beat_checks`, D-100)."""
710
+ lines = [f" · {c['affordance']}: {c['outcome']}" for c in details.get("checks") or []]
711
+ if details.get("mode") == "encounter":
712
+ lines.append(" · a fight was resolved")
713
+ return lines
714
+
715
+
578
716
  def beat_detail_lines(
579
- details: dict[str, Any], previous_day: int | None, *, mine: bool = True
717
+ details: dict[str, Any],
718
+ previous_day: int | None,
719
+ *,
720
+ mine: bool = True,
721
+ mechanics_shown: bool = False,
580
722
  ) -> list[str]:
581
723
  """What `uro play` and `uro connect` show under a beat (D-98): each check's outcome, a
582
724
  fight, the day (when it moved, or first seen), what the beat made, and — under the player's
583
725
  OWN beat only — the planner's suggestions (in a party they belong to whoever acted)."""
584
- lines = [f" · {c['affordance']}: {c['outcome']}" for c in details.get("checks") or []]
585
- if details.get("mode") == "encounter":
586
- lines.append(" · a fight was resolved")
726
+ lines = [] if mechanics_shown else mechanics_lines(details)
587
727
  day = details.get("world_day")
588
728
  if day is not None and day != previous_day:
589
729
  lines.append(f" · day {day}")
730
+ for t in details.get("threads_changed") or []: # D-103: any plot whose state moved
731
+ moved = f"{t['from_state']} → {t['to_state']}" if t["from_state"] else t["to_state"]
732
+ lines.append(f" ~ plot {moved}: {t['stakes']}")
590
733
  created = details.get("created") or []
591
734
  if created:
592
735
  lines.append(" + new: " + ", ".join(f"{c['name']} ({c['kind']})" for c in created))
@@ -690,6 +833,7 @@ def serve(
690
833
  except (RuntimeError, ValueError) as exc: # incl. DatabaseUnavailable (a RuntimeError subclass)
691
834
  typer.echo(f"error: {exc}", err=True)
692
835
  raise typer.Exit(1) from exc
836
+ _require_migrated(store)
693
837
  engine = Engine(store, router, ruleset=build_ruleset(ruleset))
694
838
  # Pick the turn shape (OQ-7, D-31/D-38/D-39). UNSET (--arbiter not given) is AUTO: solo for one
695
839
  # token (the dev loop → SoloArbiter), party for >1. Set EXPLICITLY, the shape binds regardless
@@ -773,6 +917,13 @@ def connect(
773
917
  async def _client() -> None:
774
918
  try:
775
919
  async with websockets.connect(uri) as ws:
920
+ # A refusal is a close code right after the socket opens (D-107); a seat is
921
+ # announced (participant_joined). Wait a moment for either before saying so.
922
+ first: str | bytes | None = None
923
+ with contextlib.suppress(TimeoutError, websockets.ConnectionClosed):
924
+ first = await asyncio.wait_for(ws.recv(), timeout=1.5)
925
+ if ws.close_code is not None:
926
+ _refused(ws.close_code, campaign_id)
776
927
  typer.echo(f"connected to {campaign_id} as {token!r}. Type an action; /quit.\n")
777
928
  # An intent is SETTLED by one of these, each echoing the intent's text. The prompt
778
929
  # waits for it: shown at once, it sat above the streaming narration and was gone by
@@ -795,6 +946,7 @@ def connect(
795
946
  pending: dict[str, tuple[str, asyncio.Event]] = {}
796
947
  echoes = False
797
948
  seen_day: int | None = None # the day the last beat_committed showed
949
+ checked: set[str] = set() # intents whose beat_checks were already printed
798
950
 
799
951
  def settle(msg: dict[str, Any]) -> None:
800
952
  if "intent_id" in msg:
@@ -808,9 +960,17 @@ def connect(
808
960
  if hit is not None:
809
961
  hit[1].set()
810
962
 
963
+ async def frames() -> AsyncIterator[str | bytes]:
964
+ if first is not None: # the frame that told us we were seated
965
+ yield first
966
+ # a server that goes away ends the session: the prompt loop sees it
967
+ with contextlib.suppress(websockets.ConnectionClosed):
968
+ async for raw in ws:
969
+ yield raw
970
+
811
971
  async def receive() -> None:
812
972
  nonlocal echoes, seen_day
813
- async for raw in ws:
973
+ async for raw in frames():
814
974
  msg = json.loads(raw)
815
975
  kind = msg.get("type")
816
976
  echoes = echoes or "intent_id" in msg
@@ -824,9 +984,18 @@ def connect(
824
984
  settle(msg)
825
985
  if kind == "narration_chunk":
826
986
  typer.echo(msg["text"], nl=False)
987
+ elif kind == "beat_checks": # what the rules decided, first (D-100)
988
+ checked.add(str(msg.get("intent_id", msg.get("intent"))))
989
+ for line in mechanics_lines(msg):
990
+ typer.echo(line)
827
991
  elif kind == "beat_committed":
828
992
  typer.echo(f"\n ✓ [{msg['participant_id']}] {msg['intent']!r}")
829
- for line in beat_detail_lines(msg, seen_day, mine=ours):
993
+ key = str(msg.get("intent_id", msg.get("intent")))
994
+ shown = key in checked
995
+ checked.discard(key)
996
+ for line in beat_detail_lines(
997
+ msg, seen_day, mine=ours, mechanics_shown=shown
998
+ ):
830
999
  typer.echo(line)
831
1000
  seen_day = msg.get("world_day", seen_day)
832
1001
  typer.echo("")
@@ -872,30 +1041,44 @@ def connect(
872
1041
 
873
1042
  receiver = asyncio.create_task(receive())
874
1043
  loop = asyncio.get_event_loop()
875
- while True:
876
- intent = (await loop.run_in_executor(None, input, "> ")).strip()
877
- if intent in ("/quit", "/exit"):
878
- break
879
- if intent.startswith("/say "): # non-canon table-talk (D-38)
880
- await ws.send(json.dumps({"type": "table_talk", "text": intent[5:]}))
881
- elif intent.startswith("/vote "): # non-canon consensus vote (D-38)
882
- await ws.send(json.dumps({"type": "vote", "choice": intent[6:]}))
883
- elif intent:
884
- rid = uuid.uuid4().hex
885
- settled = asyncio.Event()
886
- pending[rid] = (intent, settled)
887
- await ws.send(json.dumps({"type": "intent", "text": intent, "id": rid}))
888
- waiting = asyncio.ensure_future(settled.wait())
889
- # a slow beat (a reasoning model's extraction) still settles well inside
890
- # this; past it — or if the server goes away — the prompt comes back anyway
891
- await asyncio.wait(
892
- {waiting, receiver}, timeout=600, return_when=asyncio.FIRST_COMPLETED
893
- )
894
- waiting.cancel()
895
- pending.pop(rid, None)
896
- if receiver.done(): # the server closed the connection
1044
+ # A server that closes the socket while the player is at the prompt (a revoked
1045
+ # token, a removed campaign) ends the session here, then says why (D-107 review).
1046
+ try:
1047
+ while True:
1048
+ intent = (await loop.run_in_executor(None, input, "> ")).strip()
1049
+ if receiver.done(): # closed while the player typed
897
1050
  break
1051
+ if intent in ("/quit", "/exit"):
1052
+ break
1053
+ if intent.startswith("/say "): # non-canon table-talk (D-38)
1054
+ await ws.send(json.dumps({"type": "table_talk", "text": intent[5:]}))
1055
+ elif intent.startswith("/vote "): # non-canon consensus vote (D-38)
1056
+ await ws.send(json.dumps({"type": "vote", "choice": intent[6:]}))
1057
+ elif intent:
1058
+ rid = uuid.uuid4().hex
1059
+ settled = asyncio.Event()
1060
+ pending[rid] = (intent, settled)
1061
+ await ws.send(json.dumps({"type": "intent", "text": intent, "id": rid}))
1062
+ waiting = asyncio.ensure_future(settled.wait())
1063
+ # a slow beat (a reasoning model's extraction) still settles well
1064
+ # inside this; past it, or if the server goes away, the prompt returns
1065
+ await asyncio.wait(
1066
+ {waiting, receiver},
1067
+ timeout=600,
1068
+ return_when=asyncio.FIRST_COMPLETED,
1069
+ )
1070
+ waiting.cancel()
1071
+ pending.pop(rid, None)
1072
+ if receiver.done(): # the server closed the connection
1073
+ break
1074
+ except websockets.ConnectionClosed:
1075
+ pass
898
1076
  receiver.cancel()
1077
+ if ws.close_code in _REFUSALS: # refused after a while (a token revoked mid-session)
1078
+ _refused(ws.close_code, campaign_id)
1079
+ except websockets.InvalidStatus as exc: # a server older than D-107 refuses the handshake
1080
+ typer.echo(f"refused by {server}: {exc}", err=True)
1081
+ raise typer.Exit(1) from exc
899
1082
  except OSError as exc:
900
1083
  typer.echo(f"could not connect to {server}: {exc} (is `uro serve` running?)", err=True)
901
1084
  raise typer.Exit(1) from exc
@@ -903,6 +1086,20 @@ def connect(
903
1086
  asyncio.run(_client())
904
1087
 
905
1088
 
1089
+ _REFUSALS = {
1090
+ 4401: "the server doesn't know this token",
1091
+ 4403: "this token is for another campaign",
1092
+ 4404: "no such campaign on this server",
1093
+ }
1094
+
1095
+
1096
+ def _refused(code: int, campaign_id: str) -> None:
1097
+ """Say why the server closed the play socket (D-107), and exit 1."""
1098
+ why = _REFUSALS.get(code, "the server closed the connection")
1099
+ typer.echo(f"refused ({campaign_id}): {why} [{code}]", err=True)
1100
+ raise typer.Exit(1)
1101
+
1102
+
906
1103
  def _server_post(server: str, path: str, token: str, body: dict[str, Any] | None) -> dict[str, Any]:
907
1104
  """POST JSON (or GET, when `body` is None) to a running `uro serve` — stdlib urllib, no extra
908
1105
  dep — authed by ?token."""
@@ -1238,6 +1435,14 @@ def world_list() -> None:
1238
1435
  typer.echo("(no worlds — create one with `uro world new` or `uro world create`)")
1239
1436
  for w in worlds:
1240
1437
  typer.echo(f"{w.world_id} {w.name}")
1438
+ # what the world says about itself (D-104), when it says anything
1439
+ about = [
1440
+ *([w.description] if w.description else []),
1441
+ *([f"tone: {', '.join(w.tone)}"] if w.tone else []),
1442
+ *([f"content: {w.content.get('rating')}"] if w.content else []),
1443
+ ]
1444
+ if about:
1445
+ typer.echo(f" {' · '.join(about)}")
1241
1446
 
1242
1447
  _run_async(_run)
1243
1448
 
@@ -1460,11 +1665,59 @@ def calls(
1460
1665
  _run_async(_run)
1461
1666
 
1462
1667
 
1668
+ @rules_app.command("schema")
1669
+ def rules_schema() -> None:
1670
+ """Print the world-rules grammar as JSON Schema (D-105), with the version this engine writes
1671
+ and the versions it reads."""
1672
+ from uro_core.worldpack import rules as R
1673
+
1674
+ typer.echo(
1675
+ json.dumps(
1676
+ {
1677
+ "rules_api_version": R.RULES_API_VERSION,
1678
+ "supported_versions": sorted(R._SUPPORTED_VERSIONS),
1679
+ "rule_pack_schema": R.rule_pack_schema(),
1680
+ },
1681
+ indent=2,
1682
+ )
1683
+ )
1684
+
1685
+
1686
+ @rules_app.command("validate")
1687
+ def rules_validate(path: str) -> None:
1688
+ """Check world rules on their own, as creating a world would (D-105): <path> is a pack
1689
+ directory (its rules.yaml / agendas.yaml), or a JSON file holding one rule pack
1690
+ ({rules_api_version, rules, agendas})."""
1691
+ from pathlib import Path
1692
+
1693
+ from uro_core.errors import PackError
1694
+ from uro_core.worldpack.parse import _rule_pack
1695
+ from uro_core.worldpack.rules import check_rule_pack
1696
+
1697
+ target = Path(path)
1698
+ try:
1699
+ if target.is_dir():
1700
+ pack = _rule_pack(target)
1701
+ if pack is None:
1702
+ typer.echo(f"error: {path} has no rules.yaml or agendas.yaml", err=True)
1703
+ raise typer.Exit(1)
1704
+ else:
1705
+ pack = check_rule_pack(json.loads(target.read_text()))
1706
+ except (PackError, ValueError, OSError) as exc: # json.JSONDecodeError is a ValueError
1707
+ typer.echo(f"error: {exc}", err=True)
1708
+ raise typer.Exit(1) from exc
1709
+ typer.echo(
1710
+ f"ok: {len(pack.rules)} rules, {len(pack.agendas)} agendas "
1711
+ f"(rules_api_version {pack.rules_api_version})"
1712
+ )
1713
+
1714
+
1463
1715
  @ruleset_app.command("list")
1464
1716
  def ruleset_list() -> None:
1465
- """The rulesets a world can declare (`[ruleset] id` in world.toml): the built-ins and installed
1466
- plugins (D-65), each with the settings a game may give it under `[ruleset.config]` and their
1467
- defaults (D-62). A plugin that can't be used is listed with the reason."""
1717
+ """The rulesets a world can declare (`\\[ruleset] id` in world.toml): the built-ins and
1718
+ installed plugins (D-65), each with the settings a game may give it under
1719
+ `\\[ruleset.config]` and their defaults (D-62). A plugin that can't be used is listed with
1720
+ the reason."""
1468
1721
  for rid in registry.available():
1469
1722
  try: # one plugin's fault (e.g. a setting with no default) must not hide the rest
1470
1723
  rs = registry.resolve(rid)
@@ -1633,10 +1886,43 @@ def campaign_delete(
1633
1886
  _run_async(_run)
1634
1887
 
1635
1888
 
1889
+ @campaign_app.command("thread-state")
1890
+ def campaign_thread_state(
1891
+ campaign_id: str,
1892
+ thread_id: str,
1893
+ state: str = typer.Argument(..., help="dormant | offered | active | resolved | dead"),
1894
+ ) -> None:
1895
+ """Move a plot through its lifecycle (D-102): one commit, then the world's rules react. Any
1896
+ thread, authored or made in play: when a plot opens, sleeps or ends is the game's call."""
1897
+
1898
+ async def _run() -> None:
1899
+ store = build_store()
1900
+ await connect_store(store)
1901
+ try:
1902
+ c = await _campaign_or_exit(store, campaign_id)
1903
+ # the world's rules need no LLM, so a stub router suffices (like `campaign time-skip`);
1904
+ # and no ruleset either: one that can't be built doesn't block moving a plot (review)
1905
+ ruleset = await _time_skip_ruleset(registry.resolve_for_campaign(store, c))
1906
+ engine = Engine(store, build_router("stub", None), ruleset=ruleset)
1907
+ try:
1908
+ commit = await engine.set_thread_state(c, thread_id, state)
1909
+ except KeyError as exc:
1910
+ typer.echo(f"no such thread on this campaign: {thread_id}", err=True)
1911
+ raise typer.Exit(1) from exc
1912
+ except ValueError as exc:
1913
+ typer.echo(f"error: {exc}", err=True)
1914
+ raise typer.Exit(1) from exc
1915
+ finally:
1916
+ await store.close()
1917
+ typer.echo(f"thread {thread_id} → {state} (commit {commit.commit_id})")
1918
+
1919
+ _run_async(_run)
1920
+
1921
+
1636
1922
  @campaign_app.command("pacing")
1637
1923
  def campaign_pacing(campaign_id: str) -> None:
1638
1924
  """Which live plots have gone quiet, and the one the next beat would name to the narrator
1639
- (the pacing director, D-95: off unless the world's `[pacing]` turns it on, D-96)."""
1925
+ (the pacing director, D-95: off unless the world's `\\[pacing]` turns it on, D-96)."""
1640
1926
 
1641
1927
  async def _run() -> None:
1642
1928
  from uro_core.pipeline.pacing import pacing_report
@@ -1660,7 +1946,8 @@ def campaign_pacing(campaign_id: str) -> None:
1660
1946
  for t in sorted(report.threads, key=lambda t: (-t.quiet_beats, t.thread_id)):
1661
1947
  quiet = f"{t.quiet_beats}{'+' if t.at_least else ''}"
1662
1948
  mark = " ← next" if t.thread_id == report.next_paced else ""
1663
- typer.echo(f" {quiet:>4} beats quiet [{t.thread_id}] {t.stakes}{mark}")
1949
+ life = f"developed {t.developments}, live {t.beats_live}" # D-102
1950
+ typer.echo(f" {quiet:>4} beats quiet [{t.thread_id}] {t.stakes} ({life}){mark}")
1664
1951
 
1665
1952
  _run_async(_run)
1666
1953
 
@@ -1711,8 +1998,18 @@ def campaign_new(
1711
1998
  seed: int = typer.Option(
1712
1999
  0, "--seed", help="mechanics RNG seed (docs/18 G-3) — pin it for reproducible combat"
1713
2000
  ),
2001
+ own_branch: bool = typer.Option(
2002
+ False, "--own-branch", help="a playthrough of its own: fork --branch and play there (D-100)"
2003
+ ),
2004
+ from_ref: str = typer.Option(
2005
+ None, "--from", help="with --own-branch: fork at this marker or commit, not the head"
2006
+ ),
2007
+ branch_name: str = typer.Option(
2008
+ None, "--branch-name", help="with --own-branch: the new branch's name (default play-…)"
2009
+ ),
1714
2010
  ) -> None:
1715
- """Start a campaign on a branch, binding a PC (adopt an existing actor, or create one)."""
2011
+ """Start a campaign on a branch, binding a PC (adopt an existing actor, or create one).
2012
+ With --own-branch it gets a branch of its own, so it can later be removed alone (D-99)."""
1716
2013
 
1717
2014
  async def _run() -> None:
1718
2015
  if (adopt is None) == (pc is None):
@@ -1726,34 +2023,55 @@ def campaign_new(
1726
2023
  if b is None:
1727
2024
  typer.echo(f"no such branch: {branch}", err=True)
1728
2025
  raise typer.Exit(1)
1729
- # Bind the WORLD's declared ruleset (docs/06, D-30): a PbtA world's campaign is
1730
- # played under uro_pbta, not the hard-coded default. ('' → registry default.)
1731
- pin = await store.world_ruleset(b.branch_id)
1732
- rs = await registry.resolve_for_branch(store, b.branch_id) # with the world's settings
1733
- # Every PC needs a sheet so the mechanics gate can check it. A fresh PC gets one; an
1734
- # adopted actor is sheeted only if it lacks one (a re-adopted PC keeps its sheet).
1735
- pc_sheet = None
1736
- if pc is not None or (
1737
- adopt is not None and await store.get_sheet(b.branch_id, adopt) is None
1738
- ):
1739
- pc_sheet = _build_pc_sheet(rs)
1740
- ruleset_id = rs.id
1741
- campaign = await store.start_campaign(
1742
- w.world_id,
1743
- b.branch_id,
1744
- participant_id=participant,
1745
- adopt_actor_id=adopt,
1746
- new_pc_name=pc,
1747
- pc_sheet=pc_sheet,
1748
- starting_items=await starting_gear(store, b.branch_id) if pc is not None else None,
1749
- ruleset_id=ruleset_id,
1750
- ruleset_version=pin.version,
1751
- seed=seed,
1752
- )
2026
+ if (from_ref is not None or branch_name is not None) and not own_branch:
2027
+ typer.echo("--from and --branch-name go with --own-branch", err=True)
2028
+ raise typer.Exit(1)
2029
+ if own_branch:
2030
+ from uro_core.timeline.playthrough import playthrough_branch
2031
+
2032
+ try:
2033
+ b = await playthrough_branch(
2034
+ store, w.world_id, b, from_ref=from_ref, name=branch_name
2035
+ )
2036
+ except (ValueError, KeyError) as exc:
2037
+ typer.echo(f"error: {exc}", err=True)
2038
+ raise typer.Exit(1) from exc
2039
+ try: # from here on, a failure removes the playthrough's fork (D-100 review)
2040
+ # Bind the WORLD's declared ruleset (docs/06, D-30): a PbtA world's campaign is
2041
+ # played under uro_pbta, not the hard-coded default. ('' → registry default.)
2042
+ pin = await store.world_ruleset(b.branch_id)
2043
+ # with the world's settings
2044
+ rs = await registry.resolve_for_branch(store, b.branch_id)
2045
+ # Every PC needs a sheet so the mechanics gate can check it. A fresh PC gets one; an
2046
+ # adopted actor is sheeted only if it lacks one (a re-adopted PC keeps its sheet).
2047
+ pc_sheet = None
2048
+ if pc is not None or (
2049
+ adopt is not None and await store.get_sheet(b.branch_id, adopt) is None
2050
+ ):
2051
+ pc_sheet = _build_pc_sheet(rs)
2052
+ ruleset_id = rs.id
2053
+ campaign = await store.start_campaign(
2054
+ w.world_id,
2055
+ b.branch_id,
2056
+ participant_id=participant,
2057
+ adopt_actor_id=adopt,
2058
+ new_pc_name=pc,
2059
+ pc_sheet=pc_sheet,
2060
+ starting_items=(
2061
+ await starting_gear(store, b.branch_id) if pc is not None else None
2062
+ ),
2063
+ ruleset_id=ruleset_id,
2064
+ ruleset_version=pin.version,
2065
+ seed=seed,
2066
+ )
2067
+ except BaseException:
2068
+ if own_branch: # nothing half-made: the playthrough's fork goes too
2069
+ await store.delete_branch(b.branch_id)
2070
+ raise
1753
2071
  finally:
1754
2072
  await store.close()
1755
2073
  who = f"adopted {adopt}" if adopt else f"new PC {pc!r}"
1756
- typer.echo(f"campaign: {campaign.campaign_id} (branch {branch!r}, {who})")
2074
+ typer.echo(f"campaign: {campaign.campaign_id} (branch {b.name!r}, {who})")
1757
2075
  typer.echo(f"play it: uro play {campaign.campaign_id}")
1758
2076
 
1759
2077
  _run_async(_run)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes