Compare commits

..
67 Commits
Author SHA1 Message Date
dingoandClaude Opus 5.5 0d9cc122aa deploy(dev): promote 9de55e3's server image on region 16 (one action per account a tick)
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m48s
Foundation / postgres-tools (push) Successful in 5s
Foundation / server-image (push) Successful in 5s
Foundation / image (push) Successful in 5s
Gitea run 576: server 9ba0d78a; postgres-tools unchanged (c200bd43). The
previous build 1d0585ef stays retained.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 08:40:17 -04:00
dingoandClaude Opus 5.5 9de55e352d fix(cellular): one action per account a tick, never a refused tick
Foundation / checks (client) (push) Successful in 4s
Foundation / checks (checks) (push) Successful in 4s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 5s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / postgres-tools (push) Successful in 1m39s
Foundation / server-image (push) Successful in 5m19s
Foundation / image (push) Successful in 6m54s
Region 16 playtest: a bud showed and was then undone, and several buds were
refused. The client scheduled a discrete action at server tick + lead, but
movement runs ahead of that once the lead shrinks (each movement takes the
tick after the last one sent), so a bud could name a tick a movement already
had. A tick takes one action per account: the region refused the whole tick
and dropped every player's actions on it ("tick stalled ... error=4").

- Server: keep_one_action_per_account keeps each account's discrete action
  (engulf, bud, become, emerge), else its newest, and refuses only the rest.
- Client: a discrete action is scheduled after every tick already sent, and
  movement is held off the tick a queued discrete action owns.
- Failed background commits now log their category, publication error,
  store error and SQLSTATE (never server text), to diagnose ok=0 commits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 08:31:16 -04:00
dingoandClaude Opus 5.5 2ce8c3afb1 deploy(dev): promote 6de2b7b's images on region 16 (end a stranded life)
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m40s
Foundation / postgres-tools (push) Successful in 5s
Foundation / server-image (push) Successful in 5s
Foundation / image (push) Successful in 5s
Gitea run 574: server 1d0585ef, postgres-tools c200bd43 (schema 69). The
previous build 441c25a5 stays retained.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 07:44:02 -04:00
dingoandClaude Opus 5.5 6de2b7b1ca feat(admin): end a stranded life from the portal (schema 69)
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (checks) (push) Successful in 6s
Foundation / checks (deploy) (push) Successful in 6s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / postgres-tools (push) Successful in 5m17s
Foundation / image (push) Successful in 6m23s
Foundation / server-image (push) Successful in 8m26s
ADR-0182 section 18. Region 16 refused every birth for an account with
"Existing cell is already bound to this account" although no cell in it
held the account: a published reservation was never ended, and the only
remedy was tools/ops/end-account-life.sql as the database owner.

- Account action POST /api/accounts/<uuid>/end-life?request=N. The admin
  API reads the life's region from the account's lives and refuses while
  that region's live view lists a cell holding the account (also a bud,
  split offspring or organism control moved to), a region it cannot view,
  an incomplete view, an unpublished request or a life no longer open.
- Schema 69: admin_end_account_life_v1 (admin role only) ends it at the
  region's latest commit and appends who and why to admin_life_endings.
- The account page shows End life for each published life not ended.
- A region refusing a birth because the account holds a cell (life_exists)
  could never record it: reject_primitive_life accepted reasons 1..3 only.
  The reservation stayed open and unpublished and refused every later
  birth. Schema 69 and the C++ wrapper accept existing_life (4).
- A region with no ticking cells ignored queued admin commands (such as a
  spawn) until something else woke it; a queued command now keeps it
  ticking until applied.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 07:32:08 -04:00
dingoandClaude Opus 5.5 8085392122 deploy(dev): promote 3c75397's images on region 16 (4,096-life ticks)
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m33s
Foundation / postgres-tools (push) Successful in 5s
Foundation / image (push) Successful in 5s
Foundation / server-image (push) Successful in 5s
Gitea run 571: server 441c25a5 and postgres-tools 03a24875 (schema 68).
The previous server build a7ab3f34 stays retained.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 17:37:37 -04:00
dingoandClaude Opus 5.5 3c753970c8 feat(cellular): region ticks of up to 4,096 lives for testing (schema 68)
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / postgres-tools (push) Successful in 31s
Foundation / server-image (push) Successful in 4m29s
Foundation / image (push) Successful in 5m43s
ADR-0182 section 17. The plan's 2,000-organism cap became the rules-12
key region.organism_cap, which was parsed but never enforced; the real
bound was max_cellular_tick_lives = 256 (ADR-0106), which rules 13's
organism cap could not exceed. The bound is now 4,096, for testing limits
only; the DEV tuning file keeps 256.

- max_cellular_tick_lives (4,096) bounds the raw region path: step, owner
  state, batch trace (cellular_batch_bytes_for) and current checkpoint
  traces. max_cellular_frozen_lives (256) keeps cohort populations,
  population batches, migration traces and pre-v3 cellular traces, whose
  database checks are fixed.
- Tuning: reproduction.organism_cap and wildlife_cap accept up to 4,096.
- Schema 68: the trace checker under the current publishers
  (cellular_births_v45) accepts 4,096 intents, births and mutations per
  tick; spawn_wildlife takes up to 256 cells a command.
- Region view and portal: the lineage archive's fill (births of 65,536,
  genomes of 4,096), at which a region stops ticking.
- PostgreSQL suite: 256 wildlife spawned in one command, then a 289-life
  tick published and recovered exactly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 17:30:22 -04:00
dingoandClaude Opus 5.5 8005e7c4ae deploy(dev): promote 7573044's images on region 16 (take, cull, wildlife cap)
Foundation / checks (checks) (push) Successful in 6s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m43s
Foundation / postgres-tools (push) Successful in 5s
Foundation / server-image (push) Successful in 5s
Foundation / image (push) Successful in 5s
Gitea run 569: server a7ab3f34 and postgres-tools f2ce1192 (schema 67).
The previous server build 87d607f5 stays retained.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 16:20:28 -04:00
dingoandClaude Opus 5.5 757304437e feat(admin): take reserve, cull wildlife, wildlife cap, fresh bud costs (schema 67)
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m34s
Foundation / postgres-tools (push) Successful in 26s
Foundation / server-image (push) Successful in 4m30s
Foundation / image (push) Successful in 5m46s
ADR-0182 section 16, from playtesting region 16 at its 256-life cap.

- Bud costs: the region host's cache of each genome's bud cost was keyed
  by genome only, so after a tuning adoption the client kept the old cost
  (or "cannot bud"). It now clears when the rules' encoding changes.
- Wildlife cap: reproduction.wildlife_cap (optional, 0..organism cap,
  0 = the organism cap) refuses buds of parents without an account at that
  many lives, keeping the slots above it for players. Bits 17-31 of the
  energy-cycle word, so older rules keep their bytes. DEV file: 200.
- Schema 67: admin command kinds take_reserve (8: up to the amounts from a
  life's reserve to the spent pool) and remove_wildlife (9: every life
  without an account, as remove_cell).
- Region view: caps; the portal shows lives against the cap.
- Portal: Take reserve in the inspector, Remove all wildlife, and marking
  cells on the map (shift+click, shift+drag) for bulk removal; the guided
  editor lists optional keys the base revision lacks.
- Client: a refused bud says the region may be full.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 16:06:56 -04:00
dingoandClaude Opus 5.5 51aa08446d deploy(dev): promote 9b854e6's server image on region 16 (open regions from the portal)
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 4s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m39s
Foundation / postgres-tools (push) Successful in 5s
Foundation / server-image (push) Successful in 5s
Foundation / image (push) Successful in 5s
Gitea run 567: server sha256:87d607f5bc1cb6b8673767ad44d62d773fac4116b1f952cdb80fac61625b1d02
on the region, its hooks and the admin portal; 2f2d5c2b stays retained. The
postgres-tools image stays at run 556's (no schema change). This sync also
applies the portal's new egress and mounts Secret aevolution-admin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 14:04:35 -04:00
dingoandClaude Opus 5.5 9b854e6960 feat(admin): open a fresh region from the portal (ADR-0182 section 15)
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 4s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m31s
Foundation / postgres-tools (push) Successful in 27s
Foundation / server-image (push) Successful in 4m33s
Foundation / image (push) Successful in 5m39s
The Regions page opens the next region in place of the one DEV serves: the
admin API reads the region overlay, its kustomization, the grant broker and the
portal deployment from main at one commit, rewrites only the region id, routes,
genesis commit and seeded wildlife range (refusing files whose layout differs),
commits them in one Gitea multi-file commit as aevolution-bot, then starts a full
Argo sync of exactly that commit. The page follows the sync until the region is
live, across the portal's own restart.

Credentials come from Secret aevolution-admin mounted read-only as files
(--deploy-config); without it the feature stays off. A small OpenSSL HTTPS
client talks to Gitea (verified) and argocd-server (verification per
ARGOCD_TLS_VERIFY). The portal's NetworkPolicy gains egress to the node's
ingress for Gitea and to the argocd-server pods, as approved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 13:51:36 -04:00
dingoandClaude Opus 5.5 e0f9512567 deploy(dev): promote 23ea240's server image on region 16 (guided tuning editor)
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m44s
Foundation / postgres-tools (push) Successful in 5s
Foundation / server-image (push) Successful in 5s
Foundation / image (push) Successful in 6s
Gitea run 565: server sha256:2f2d5c2bd6baa68163d81cbdd75496e200e8446cf806f443834cd03bdb6eb828
on the region, its hooks and the admin portal; a8edb67c stays retained. The
postgres-tools image stays at run 556's (no schema change).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:16:59 -04:00
dingoandClaude Opus 5.5 23ea24080e feat(admin): guided tuning editor that sends only the changes
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 6s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / postgres-tools (push) Successful in 28s
Foundation / server-image (push) Successful in 4m48s
Foundation / image (push) Successful in 5m37s
DEV's ingress refuses request bodies over about 1 KB, so adopting a whole
revamp file (5 KB) failed with a 413 the portal misreported as the API's 64 KiB
limit. POST /api/tuning?base=baseline|REV now takes only changed `key = value`
lines, applies them to the baseline file or the newest revision (409 stale_base
for an older one), keeping its comments, then checks and stores as before.

The Tuning page becomes a guided editor: sections, a field per setting with its
unit, plain reading and comment, a changes list with Check and Apply (or Adopt
as is), and loading a past revision or the baseline as changes. The full-text
editor stays as Text mode and names a proxy refusal plainly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:09:54 -04:00
dingoandClaude Opus 5.5 8dedde454d deploy(dev): promote cc2eaf2's server image on region 16 (energy cycle)
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / postgres-tools (push) Successful in 5s
Foundation / image (push) Successful in 5s
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m43s
Foundation / server-image (push) Successful in 5s
Gitea run 563: server sha256:a8edb67c9b69edb5c2c750a068c6d89553691fccc47a4241c67c12f3f9e2a0b2
on the region, its hooks and the admin portal; 12e62108 stays retained. The
postgres-tools image stays at run 556's (no schema change). Region 16 keeps its
recorded rules until the energy cycle is adopted as a tuning revision.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:31:25 -04:00
dingoandClaude Opus 5.5 cc2eaf2e05 feat(cellular): energy cycles back through the spent pool (ADR-0182 section 14)
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m42s
Foundation / checks (checks) (push) Successful in 6s
Foundation / checks (client) (push) Successful in 5s
Foundation / postgres-tools (push) Successful in 31s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / server-image (push) Successful in 4m45s
Foundation / checks (network) (push) Successful in 4s
Foundation / image (push) Successful in 5m31s
Energy cells used went to the region's heat store and never returned, so a
region without photosynthesizers drained: region 16's wildlife ate its energy
and starved, and its matter-only drip filled the deposit limit.

Two optional rules-13 tuning keys, adoptable live: spent.heat_recycle_per_mille
moves that share of the heat store to the spent pool at the end of every tick,
before the drip (1,000 closes the loop and returns heat built up before), and
spent.drip_absorb lets a drip at the deposit limit join the first existing bubble
at or after its spot. Both use the reserved word after the offer interval, so
rules without them keep their bytes, digests, checkpoints and replays. The DEV
revamp file turns both on. The region view reports heat and the cycle; the
portal counts heat in the region's energy and ledger.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:18:24 -04:00
dingoandClaude Opus 5.5 944f6719cf deploy(dev): promote c481a7f's server image on region 16 (map canvas fix)
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / image (push) Successful in 6s
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m41s
Foundation / checks (client) (push) Successful in 5s
Foundation / postgres-tools (push) Successful in 6s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / server-image (push) Successful in 5s
Gitea run 561: server sha256:12e62108f7b920bea0b91f50b21fcabd2463af6f1e94242140bbde786e42eee5
on the region, its hooks and the admin portal; 9f76430c stays retained. The
postgres-tools image stays at run 556's (no schema change).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 08:42:05 -04:00
dingoandClaude Opus 5.5 c481a7fe5e fix(admin): keep the region map canvas out of the layout
Foundation / checks (postgres) (push) Successful in 2m22s
Foundation / checks (ecs) (push) Successful in 2m23s
Foundation / checks (client) (push) Successful in 2m26s
Foundation / postgres-tools (push) Successful in 1m38s
Foundation / checks (network) (push) Successful in 2m22s
Foundation / server-image (push) Successful in 5m14s
Foundation / image (push) Successful in 6m17s
Foundation / checks (checks) (push) Successful in 2m27s
Foundation / checks (deploy) (push) Successful in 2m27s
Foundation / checks (tsan) (push) Successful in 5s
The map canvas is absolutely placed in its stage, so its backing size can never
feed back into the page layout, and the backing store is capped at 2x and 4,096
pixels a side; a refused 2D context skips the paint instead of throwing. The tab
bar no longer shows a vertical scrollbar, the overlays drop backdrop blur, and
the theme icons are HTML entities.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 08:30:41 -04:00
dingoandClaude Opus 5.5 2fc50df26c deploy(dev): promote 6338cc9's server image on region 16 (admin region page)
Foundation / checks (checks) (push) Successful in 6s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m40s
Foundation / postgres-tools (push) Successful in 6s
Foundation / server-image (push) Successful in 5s
Foundation / image (push) Successful in 5s
Gitea run 559: server sha256:9f76430c33a33d246384dc198b4df3d7e4abf28277a2f435cce25696d01a4863
on the region, its hooks and the admin portal; ec473b40 stays retained. The
postgres-tools image is unchanged (no schema change).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 08:07:47 -04:00
dingoandClaude Opus 5.5 6338cc9142 feat(admin): region page redesign, resource ledger, drip and dark mode
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m40s
Foundation / postgres-tools (push) Successful in 30s
Foundation / server-image (push) Successful in 4m46s
Foundation / image (push) Successful in 5m34s
The region view adds the rules-13 drip and complete counts and totals over every
life and deposit. The region page is rebuilt around the map: a KPI strip (tick
pace, population, deposit capacity, region energy and matter, spent pool, next
drip), layer toggles that double as the legend, zoom and a scale, and tabs for
inspecting cells and deposits, resources (where each channel sits, the spent pool
and each channel's next drip), actions, the running tuning and session access.
The admin API serves the region tuning file read only (--region-tuning). Light
and dark themes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 07:54:28 -04:00
dingoandClaude Opus 5.5 68f2567253 deploy(dev): promote 7273b15's images on region 16 (live tuning)
Foundation / checks (checks) (push) Successful in 6s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m44s
Foundation / postgres-tools (push) Successful in 5s
Foundation / server-image (push) Successful in 5s
Foundation / image (push) Successful in 4s
Server ec473b40 and postgres-tools 946de1a1 from Gitea run 556 (schema 66).
de1b4b32 stays retained.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 21:47:38 -04:00
dingoandClaude Opus 5.5 7273b157d6 feat(admin): live tuning revisions adopted at recorded ticks (schema 66)
Foundation / checks (client) (push) Successful in 4s
Foundation / checks (checks) (push) Successful in 4s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m47s
Foundation / postgres-tools (push) Successful in 29s
Foundation / server-image (push) Successful in 4m42s
Foundation / image (push) Successful in 5m55s
ADR-0182 section 13. The admin portal's Tuning page edits the world's
rules-13 tuning (the Git revamp file format); the admin API checks it,
stores an append-only revision and queues an adopt_tuning admin command
(kind 7: revision and rules digest) for every region of the world.

- Lifecycle: adopt_tuning replaces the region's rules after births when
  a resolver names the rules for that revision and digest; the safety
  revision cannot change live. At most one adoption per batch.
- Host: fetches the revision text, rebuilds and digests the rules before
  appending the command; publication and recovery name the rules from
  the successor state, checked against the recorded digest.
- Schema 66: tuning_revisions, admin_set_tuning_v1, load_tuning_revision_v1
  (runtime), admin_tuning_revisions_v1, admin_tuning_text_v1.
- OpsServer: optional bounded request bodies (Content-Length, 413).
- Region view: rules_sha256, so the portal shows each region's revision.
- Portal: Tuning page; baseline from the mounted cellular-revamp.tuning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 19:35:09 -04:00
dingoandClaude Opus 5.5 7041c947a9 deploy(dev): promote 018b4b1's images on region 16 (resource schedules)
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m43s
Foundation / postgres-tools (push) Successful in 5s
Foundation / server-image (push) Successful in 5s
Foundation / image (push) Successful in 5s
Server de1b4b32 and postgres-tools ae4449c2 from Gitea run 554 (schema 65).
db678279 stays retained.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 18:43:52 -04:00
dingoandClaude Opus 5.5 018b4b1817 feat(admin): resource schedules for bubbles, pool releases and wildlife (schema 65)
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 6s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / postgres-tools (push) Successful in 23s
Foundation / server-image (push) Successful in 4m38s
Foundation / image (push) Successful in 5m35s
ADR-0182 section 12: the game source as recurring admin commands. A schedule
repeats add_bubbles, release_pool or spawn_wildlife every 1 s to 24 h while
enabled; the region's pending-command read queues each due run as an ordinary
command (recorded in the trace, bound once), never two waiting per schedule,
so an idle region builds no backlog. Append-only schedule versions; admin API
GET/POST /api/regions/<n>/schedules and a portal card to add, stop and start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 18:30:37 -04:00
dingoandClaude Opus 5.5 2485a028bb deploy(dev): promote 070c458's images on region 16 (bans, logout, time played)
Foundation / checks (checks) (push) Successful in 6s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m42s
Foundation / image (push) Successful in 4s
Foundation / postgres-tools (push) Successful in 6s
Foundation / server-image (push) Successful in 5s
Server db678279 and postgres-tools 5c10dfe9 from Gitea run 552 (schema 64).
03ce069d stays retained.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 18:04:22 -04:00
dingoandClaude Opus 5.5 070c458dc5 feat(admin): bans, admin logout and time played (schema 64)
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 4s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 5s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / postgres-tools (push) Successful in 2m9s
Foundation / server-image (push) Successful in 5m23s
Foundation / image (push) Successful in 6m10s
ADR-0182 section 11.
- Append-only account bans; a ban also revokes the account's grants (its live
  session closes at the next control renewal) and issue_account_grant refuses a
  banned account (EVL20 -> broker 403 account_banned). Lifting is another row.
- admin_logout_account_v1 revokes by account id.
- Session intervals recorded by claim/renew/release (signatures unchanged):
  time played, sessions and last seen per account.
- The region view carries each cell's lineage root; the portal counts living
  wildlife descended from an account's lives.
- Portal: Ban/Unban and Log out with reason and history; time played column.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:50:34 -04:00
dingoandClaude Opus 5.5 b3eca78549 deploy(dev): promote b1cc3b1's images on region 16 (admin commands, schema 63)
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m42s
Foundation / postgres-tools (push) Successful in 5s
Foundation / server-image (push) Successful in 5s
Foundation / image (push) Successful in 5s
Server 03ce069d and postgres-tools e9f04a09 from Gitea run 550: queued admin
commands in trace 5 (spawn wildlife, bubbles, spent pool, remove, grant).
82e24842 stays retained.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:26:54 -04:00
dingoandClaude Opus 5.5 b1cc3b121b feat(admin): live admin commands in trace 5 (schema 63)
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / postgres-tools (push) Successful in 30s
Foundation / server-image (push) Successful in 4m44s
Foundation / image (push) Successful in 5m33s
The admin portal can now spawn wildlife, add bubbles, add to or release the
spent pool, remove a cell and grant a cell's reserve on a running rules-13
region (ADR-0182 section 10). No new owner format or region opening.

- Trace 5: trace 4 plus 64-byte command records counted in the tick header's
  last word; a batch without commands stays trace 4 (older builds replay it).
  Bundle 15 admits trace 5.
- CellularLives::admin_candidate applies a tick's commands after its births,
  each on a copy kept only when it applies and closes: imports through the
  boundary ledger, removals into the spent pool with a new `removed` corpse
  cause, spawned roots via the ADR-0180 seed (now a shared helper) funded by
  an exact import. Refused commands change nothing.
- Schema 63: the immutable admin_commands queue (spawn identities from the
  life allocator), pending/history reads, and binding of every recorded
  command exactly once inside both cellular publishers; the SQL trace parsers
  read trace 5 through its trace-4 normal form.
- The region polls pending commands every 2 s and appends up to 16 per tick;
  the admin API and portal gain region actions, per-cell Remove/Grant and the
  command history.
- Fixes an existing test that did not advance its head after a tick commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:14:04 -04:00
dingoandClaude Opus 5.5 b075198040 deploy(dev): promote 46c1064's images on region 16 (session windows in SQL)
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m36s
Foundation / postgres-tools (push) Successful in 5s
Foundation / server-image (push) Successful in 6s
Foundation / image (push) Successful in 5s
Server 82e24842 and postgres-tools 4ab36349 from Gitea run 548: schema 62
session windows and the admin group role. d4b62521 stays retained. Sync only
after the aevolution_admin role exists and aevolution-admin-pg uses its login;
sessions stay closed until a window is opened in the admin portal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 15:33:11 -04:00
dingoandClaude Opus 5.5 46c106409e feat(admin): session windows in SQL, opened from the admin portal (schema 62)
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m33s
Foundation / postgres-tools (push) Successful in 2m14s
Foundation / server-image (push) Successful in 5m21s
Foundation / image (push) Successful in 6m18s
The dev session window moves from Git to SQL (ADR-0087 amendment): the admin
portal opens, extends (30 min to 4 h from now) and closes it, and the cellular
region re-reads it every 5 s with --session-window-source db. No push, sync or
restart per window; a closed window keeps the region running instead of
crash-looping.

- Schema 62: append-only session_windows (4 h cap, no rewrites),
  load_session_window_v1 for the runtime group, admin_set_session_window_v1
  and admin_session_windows_v1 for a dedicated admin group role, granted and
  audited each migration run when EVO_PG_ADMIN_ROLE is set (aevolution_admin in
  DEV). Schema 61's views are revoked from the runtime group.
- RegionSessions admission switch: while closed every Hello is refused before
  signature work and closing closes open sessions (new sessions were still
  admitted after expiry before).
- Admin API: GET/POST /api/regions/<n>/session-window, window state in the
  regions list; the portal's session-window card with history.
- Git: REGION_SESSION_WINDOW and the pre-push refresh rule are removed; the
  policy check requires the database source and refuses a committed window.

Needs the new image and the aevolution_admin role (with the portal's login in
aevolution-admin-pg) before a sync.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 15:13:02 -04:00
dingoandClaude Opus 5.5 510ecaee80 deploy(dev): promote 4adcc7b's server image on region 16; retain 1dd1ea05
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m41s
Foundation / postgres-tools (push) Successful in 6s
Foundation / server-image (push) Successful in 5s
Foundation / image (push) Successful in 6s
Server image d4b62521 from Gitea run 546 (4adcc7b: admin OAuth callbacks with
longer query strings); postgres-tools stays at run 544's schema-61 image.

Region 16 was quarantined (exit 4, crash loop) under c7347c2d: its head was
committed by 1dd1ea05, which the previous manifests dropped from
REGION_RETAINED. Both 1dd1ea05 and c7347c2d are retained now. Refreshes the
session window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 13:59:39 -04:00
aevolution-gitops-bot 4adcc7b638 fix(admin): accept OAuth callback query strings
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m42s
Foundation / postgres-tools (push) Successful in 1m43s
Foundation / server-image (push) Successful in 5m17s
Foundation / image (push) Successful in 6m2s
2026-10-27 13:37:30 -04:00
dingoandClaude Opus 5.5 d851717b7b deploy(dev): promote bc1eeb9's images on region 16 (admin portal, schema 61)
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m37s
Foundation / postgres-tools (push) Successful in 5s
Foundation / server-image (push) Successful in 5s
Foundation / image (push) Successful in 5s
Server and postgres-tools images from Gitea run 544 (bc1eeb9): the read-only
admin API and portal, the region's /admin/view route and schema 61's read
functions, on top of d46de25's reproduction-safety build. Region 16 keeps its
recorded rules; f235d14 (provisioned under, never served) and 222fa3de stay
retained. The admin portal Deployment needs the out-of-band aevolution-admin-pg
Secret and Ingress before it is reachable. Refreshes the session window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 12:58:22 -04:00
dingoandClaude Opus 5.5 bc1eeb970b deploy(dev): refresh the session window for the admin portal push
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m34s
Foundation / postgres-tools (push) Successful in 2m1s
Foundation / server-image (push) Successful in 4m59s
Foundation / image (push) Successful in 6m17s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 12:39:28 -04:00
dingoandClaude Opus 5.5 54beceb823 feat(admin): read-only admin portal and API (ADR-0182 step 1, schema 61)
evo-admin-api serves the portal at srs.aeternalisgames.com and read-only JSON
for world 100 behind Keycloak (realm role aevolution-admin, audience
aevolution-admin, client aevolution-admin-portal): accounts with session,
status, lives, deaths, resets and mutation choices; one account's lives; the
world's regions; and a live 2D region view of cells, wildlife, pools and
bubbles. The portal is plain HTML/CSS/JS with PKCE sign-in, a strict CSP and
no third-party code.

- Schema 61: three bounded SECURITY DEFINER read functions, fenced in the
  privilege audit; no table or existing function changes.
- Cellular regions answer GET /admin/view on the ops port (NetworkPolicy:
  Prometheus and the admin portal only); CellularLives::extent_of reads the
  existing phenotype budget. No simulation, checkpoint or wire change.
- TokenVerifier takes an optional realm role and returns the email; the ops
  server's response bound is configurable (16 KiB default unchanged).
- DEV component admin-portal-dev (Deployment, Service, NetworkPolicies); the
  Ingress and the aevolution-admin-pg Secret are created out of band.
- CI scripts pinned to schema 60 now expect 61.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 12:39:28 -04:00
dingoandClaude Opus 5.5 46e5ea6c5d test(postgres): provision the Git revamp rules without the DEV wildlife fixture
Since 054e485 the DEV revamp tuning file seeds 100 wildlife (ADR-0180), which
evo-world-clone provision refuses without an audited --playtest-wildlife-first-id
range, so the cellular-v10 provisioning test failed at region_store_tests line
826 (also Gitea run 542). The test now provisions the Git file's rules with its
DEV opening fixture set to zero; seeded wildlife keeps its own suite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 12:39:28 -04:00
aevolution-gitops-bot f047cd8833 deploy(dev): restore evo-sim Harbor digest
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m40s
Foundation / postgres-tools (push) Successful in 5s
Foundation / image (push) Successful in 5s
Foundation / server-image (push) Successful in 6s
2026-10-27 11:45:26 -04:00
dingoandClaude Opus 5.5 477ea8980b deploy(dev): promote d46de25's images on region 16; ADR-0182 admin portal
Foundation / checks (checks) (push) Successful in 4s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m38s
Foundation / postgres-tools (push) Successful in 6s
Foundation / server-image (push) Successful in 5s
Foundation / image (push) Successful in 5s
Server and postgres-tools images from Gitea run 540 (d46de25, all checks green):
reproduction safety revision 1 and resizable cellular panels. Region 16 keeps
running on its recorded rules; the staged safety tuning profile stays unmounted,
so the safety trial still needs a fresh opening. 51f979a's build (222fa3de) is
retained. Refreshes the session window.

ADR-0182 records the admin portal direction: world tuning revisions in SQL,
adopted per tick and recorded in region history; admin commands with a named
game source; drip/source settings; data-defined mutations; bans and session
intervals; a Keycloak-gated admin API and portal at srs.aeternalisgames.com.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 10:10:05 -04:00
dingo d46de25bef Refresh session window for authenticated publication
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m38s
Foundation / server-image (push) Successful in 6m15s
Foundation / postgres-tools (push) Successful in 6m21s
Foundation / image (push) Successful in 7m42s
2026-10-27 09:38:54 -04:00
dingo d0e0e2cf87 Record reproduction trial publication authentication limit 2026-10-27 09:15:57 -04:00
dingo 5416590f9e Add reproduction safety trial and resizable cellular panels 2026-10-27 09:13:28 -04:00
dingo 7ca5f74f03 fix(client): keep nutrient readouts on stable single-line rows 2026-10-26 17:30:47 -04:00
dingoandClaude Opus 5.5 82d21e65b2 deploy(dev): open region 16 on 51f979a's image - even split, 130% collection
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m32s
Foundation / server-image (push) Successful in 5s
Foundation / postgres-tools (push) Successful in 21s
Foundation / image (push) Successful in 4m41s
Region 16 keeps region 15's tuning (100 seeded wildlife, triple food, half
the bud fee) and adds feeding.split_evenly = 1 and feeding.collection_percent
= 130: food sources share the matter limit equally between the nutrients they
hold. Its 100 wildlife take IDs 900000003716-900000003815. The grant broker
routes accounts to region 16; region 15 stays stored and 736bf98's build stays
retained. Refreshes the session window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 16:44:16 -04:00
dingoandClaude Opus 5.5 51f979a664 feat(cellular): split collection evenly across a source's nutrients
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m31s
Foundation / postgres-tools (push) Successful in 21s
Foundation / server-image (push) Successful in 4m21s
Foundation / image (push) Successful in 5m3s
Playtest: phosphorus held growth back everywhere. Per-nutrient collection
limits followed the body recipe (5% phosphorus), but the membrane is 10%
phosphorus, so no cell could collect phosphorus as fast as it builds with it.

Two optional revamp tuning keys, stored in a formerly reserved rules word so
regions opened without them keep their exact meaning:
- feeding.split_evenly: matter from one food source is split equally between
  the nutrients it holds (a carbon-only bubble gives the whole matter limit to
  carbon, carbon and phosphorus half each, all four a quarter each), each share
  scaled by the cell's collection trait;
- feeding.collection_percent: every collection limit per cent (100 default).

The DEV tuning file takes these keys with the image that reads them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 15:56:00 -04:00
dingoandClaude Opus 5.5 054e48579c deploy(dev): open region 15 - 100 seeded wildlife, triple food, half bud fee
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m29s
Foundation / server-image (push) Successful in 5s
Foundation / postgres-tools (push) Successful in 19s
Foundation / image (push) Successful in 4m50s
Maintainer tuning for the next playtest, on the current server image:
- 100 starting wildlife (was 32) on their own ADR-0180 identity range,
  900000003616-900000003715;
- every pool and bubble holds three times region 14's food;
- the nursery funds 256 founders' worth (was 64), so the wildlife leave room
  for player births;
- the bud fee scale drops to 50%.
The grant broker routes accounts to region 15; region 14 stays stored.
Refreshes the session window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 15:19:29 -04:00
dingo d057374148 fix(client): stabilize HUD and anchor draggable panels
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m29s
Foundation / postgres-tools (push) Successful in 20s
Foundation / server-image (push) Canceled after 1m43s
Foundation / image (push) Canceled after 1m43s
2026-10-26 15:13:15 -04:00
dingoandClaude Opus 5.5 840816c541 deploy(dev): promote 736bf98's server image on region 14 (life endings)
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m27s
Foundation / postgres-tools (push) Successful in 5s
Foundation / server-image (push) Successful in 5s
Foundation / image (push) Successful in 5s
A player's death is now recorded under the reservation's lineage root, so an
account that became an offspring, a bud or an organism can be born again.
Region 14 keeps running; 8a48e40's build stays retained. Refreshes the session
window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 14:17:41 -04:00
dingoandClaude Opus 5.5 736bf98aaa fix(server): end a player's life under the reservation's root identity
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m27s
Foundation / postgres-tools (push) Successful in 26s
Foundation / server-image (push) Successful in 4m18s
Foundation / image (push) Successful in 5m4s
Playtest: after becoming a split's offspring and being engulfed, every new
birth was refused ("Existing cell is already bound to this account"). The
region recorded the ending under the dead cell's own identity, which was never
reserved, so the database ignored it and the founder's reservation stayed
open. After Adhesion the opposite happened: the merged founder's ending closed
the reservation while the player lived on as the organism.

An account's life now ends only when no life holds the account, and the ending
names the lineage root (cellular_lineage_root): the life born from the
reservation, reached through parent links in lives and corpses.

tools/ops/end-account-life.sql lets the operator end one stranded account's
reservation (dry run unless confirm=yes; exactly one match required).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 13:24:06 -04:00
dingoandClaude Opus 5.5 5dab8e4018 deploy(dev): promote 8a48e40's server image on region 14 (bud fee fix)
Foundation / checks (client) (push) Successful in 4s
Foundation / checks (checks) (push) Successful in 4s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m29s
Foundation / postgres-tools (push) Successful in 5s
Foundation / server-image (push) Successful in 5s
Foundation / image (push) Successful in 4s
Region 14 stalled at tick 6068 on the short bud fee; this image refuses such a
bud instead. Committed history is unchanged, so region 14 resumes. Run 529's
build stays retained. Refreshes the session window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 12:55:43 -04:00
dingoandClaude Opus 5.5 8a48e405fd fix(lifecycle): a bud's fee comes on top of its cost, or the bud is refused
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m28s
Foundation / postgres-tools (push) Successful in 22s
Foundation / server-image (push) Successful in 4m21s
Foundation / image (push) Successful in 5m1s
DEV region 14 stalled at tick 6068 with a conservation error. The bud fee was
checked against the reserve before funding the bud, then deducted with a clamp
after: a parent whose reserve covered the bud but not the fee as well paid less
than the fee while the region reclaimed all of it, creating matter. The fee
was zero until the budding playtest tuning, so it never showed.

Funding now requires the reserve left after the bud to cover the fee; a parent
that cannot is refused for insufficient funding, and the fee is subtracted
exactly. No committed tick changes: a short-fee bud never committed. The
regression runs seeded wildlife under the DEV fee until a bud (it failed with
the conservation error before this fix).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 12:46:00 -04:00
dingoandClaude Opus 5.5 467402e404 deploy(dev): open region 14 on run 529's image (seeded wildlife, bud fee)
Foundation / checks (checks) (push) Successful in 4s
Foundation / checks (client) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m33s
Foundation / postgres-tools (push) Successful in 5s
Foundation / server-image (push) Successful in 5s
Foundation / image (push) Successful in 5s
Run 529 (ff121c3) adds the opt-in starting wildlife (ADR-0180) and the
budding playtest tuning. The server image moves to run 529's in the region and
store Jobs; run 18a64a2's build stays retained so region 13 stays recoverable.
The grant broker routes accounts to region 14. Refreshes the session window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 12:20:17 -04:00
dingo ff121c3ed1 feat(cellular): seed dev wildlife and tune budding playtests
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m27s
Foundation / postgres-tools (push) Successful in 30s
Foundation / server-image (push) Successful in 4m16s
Foundation / image (push) Successful in 4m54s
2026-10-26 12:01:57 -04:00
dingoandClaude Opus 5.5 18a64a29cd deploy(dev): promote run 15b4342's server image on region 13
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m39s
Foundation / postgres-tools (push) Successful in 5s
Foundation / server-image (push) Successful in 5s
Foundation / image (push) Successful in 5s
Shows what holds growth back and each nutrient's flows (session v14 body
block). Region 13 keeps running; run 525's build stays retained. Refreshes the
session window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 09:59:32 -04:00
dingoandClaude Opus 5.5 15b4342934 feat(cellular): show what holds growth back and each nutrient's flows
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 4s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m23s
Foundation / postgres-tools (push) Successful in 21s
Foundation / server-image (push) Successful in 4m18s
Foundation / image (push) Successful in 4m56s
Playtest: phosphorus jumped between ~100 fg and a few pg because growth spends
it as it arrives and only pauses when another nutrient runs short. The owner
now records, per owned life and tick, which channel narrowed the growth step
(or no room) and what the tick collected, built into the body and burned;
session v14 carries them (flag bits 2-4 and a 120-byte flows block).

The client shows "Growing 62% - waiting for phosphorus" or "Fully grown",
outlines the limiting nutrient's bar in amber, and gives each bar (and the
energy figure) a tooltip with the last second's flows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 09:48:37 -04:00
dingoandClaude Opus 5.5 6988cf39b2 deploy(dev): open region 13 on run 525's image (playtest fixes)
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m32s
Foundation / postgres-tools (push) Successful in 5s
Foundation / server-image (push) Successful in 5s
Foundation / image (push) Successful in 5s
Run 525 (131ed5f) gates offers on a split, draws the region's walls and cell
count, adds mixed bubbles and keeps pools out of the currents. Region 13 is a
fresh cellular-v10 opening with 1,200 single-nutrient and 2,400 mixed bubbles
(about the earlier food in total), pools in still water, and splits at half
growth from the revamp tuning. The grant broker routes accounts to region 13.
Region 12 stays stored; run 521's build stays retained. Refreshes the session
window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 09:23:25 -04:00
dingoandClaude Opus 5.5 131ed5f254 feat(cellular): playtest fixes - edge, cell count, mixed bubbles, still pools
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m29s
Foundation / postgres-tools (push) Successful in 29s
Foundation / server-image (push) Successful in 4m24s
Foundation / image (push) Successful in 4m58s
From the first rules-13 playtest:
- An earned offer waits until a single cell can split (keeping its count),
  so choices are no longer refused one after another.
- The client draws the region's walls (dimming outside), names the edge
  when the cell is against it, shows the region's cell count, and says when
  upkeep is burning kept matter because no energy is left.
- Mixed bubbles hold every nutrient at once (--mixed-motes; none leaves the
  scatter stream unchanged) and are drawn as small pools of their nutrients.
  With intake split by the body's recipe, single-nutrient phosphorus
  bubbles fed slowly; mixed ones carry it with everything else.
- Liquid openings move each pool out of the currents to the nearest still
  water (cellular_still_centre).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 09:02:43 -04:00
dingoandClaude Opus 5.5 e2da92768c feat(cellular): show growth and gate splits; DEV splits at half growth
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m32s
Foundation / postgres-tools (push) Successful in 28s
Foundation / server-image (push) Successful in 4m21s
Foundation / image (push) Successful in 5m1s
Playtest: after one mutation every later choice came back "split refused"
because a split needs a grown cell, and the client gave no reason. The v14
body block now carries the body's growth per thousand (the reserved bytes)
and a split-ready flag; the client disables Stay / Become until the cell can
split ("Grow to split (now 62%)") and shows growth in the Body panel.
Adhesion and organism choices do not split and stay open.

The DEV revamp tuning splits once half grown (split_min_growth 500, was full
growth); it takes effect in the next region opened.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 08:28:57 -04:00
dingoandClaude Opus 5.5 542cefafce deploy(dev): grant broker routes accounts to region 12
Foundation / checks (client) (push) Successful in 4s
Foundation / checks (checks) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m28s
Foundation / postgres-tools (push) Successful in 5s
Foundation / server-image (push) Successful in 5s
Foundation / image (push) Successful in 5s
The region 12 promotion left the broker issuing grants for region 11, which
no server serves now. New accounts start in region 12 and grants may name only
region 12.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 08:10:54 -04:00
dingoandClaude Opus 5.5 5b69c3d4ec deploy(dev): open region 12 on cellular-v10 (rules 13) with run 521's images
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m29s
Foundation / postgres-tools (push) Successful in 5s
Foundation / server-image (push) Successful in 5s
Foundation / image (push) Successful in 5s
Run 521 (4bc5d5e) carries session v14, bundle 15 and schema 60. DEV now
serves region 12: the cellular-v9 genesis and upgrades followed by the
durable revamp upgrade from tuning/cellular-revamp.tuning, mounted beside
cellular.tuning. Region 11 stays stored; run 494's build stays retained.
The postgres-tools image applies schema 60. Refreshes the session window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 08:04:38 -04:00
dingoandClaude Opus 5.5 4bc5d5eee7 feat(cellular): session v14, bundle 15 and rules-13 wildlife
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m29s
Foundation / postgres-tools (push) Successful in 24s
Foundation / server-image (push) Successful in 4m33s
Foundation / image (push) Successful in 4m59s
Session v14 carries the rules-13 revamp: a body block in the owner's view
(members, emergence threshold, exclusions, Emerge open, payable energy,
mass and the 20 traits), become, emerge and channel exclusions on actions,
become on mutation choices, catalog offers (id, chance, cost) and the
emerged ending. Older sessions never see a v14 field. The client shows
Stay / Become offspring offers named from the shared catalog, continuing
as a bud, the organism and its Emerge button, kept channels, the body and
the emerged end screen.

Bundle 15 (rules 13 on owner format 11) is durable: schema 60 admits it
raw-only, stores become as bit 15 of the choice's operator, widens the
action input and mutation results, and publishes the 14 -> 15 revamp
profile migration. evo-world-clone opens cellular-v10 (cellular-v9 plus the
revamp upgrade from --revamp-tuning), resumable and recoverable.

Wildlife counts reserve matter as energy, waits for the bud fee, grows
organisms one short of emerging, and hunts by the region step's rules-13
engulf test. The play summary adds organisms, offers and the spent pool.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 07:31:32 -04:00
dingoandClaude Opus 5.5 f454e038a1 feat(lifecycle): rules 13 multicellular organisms and Emerge
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m32s
Foundation / postgres-tools (push) Successful in 21s
Foundation / server-image (push) Successful in 4m12s
Foundation / image (push) Successful in 4m52s
Adhesion turns a cell into a two-member organism: one life with a member
count, one genome and one reserve, developed as its genome with the target
size times its members. The single cell ends as an empty merged corpse.
An organism expresses accepted mutations as a whole, paid from its reserve;
its buds add internal members (wildlife stops one short of the threshold);
the extra members' mass loads its thrust. At the emergence threshold the
Emerge intent exports the body and reserve through the boundary ledger and
ends the life as emerged.

Records the maintainer's 2026-10-23 decisions in ADR-0179 and the project
vision (whole-organism mutations; the playtest form of Emerge).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 06:50:19 -04:00
dingoandClaude Opus 5.5 9f117c9545 feat(lifecycle): rules 13 mutation splits, stay-or-become and litter
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m22s
Foundation / postgres-tools (push) Successful in 22s
Foundation / server-image (push) Successful in 4m21s
Foundation / image (push) Successful in 5m6s
Phase 4 of the cellular revamp build plan (ADR-0179), server half.

- A chosen mutation now splits the cell (Cellular_reproduction_plan.md section
  4): split_cell divides body and reserve per channel by the tuned share, each
  cell develops the largest body its own genome builds from its part, and the
  rest joins its reserve, conserving every channel. Both plans carry the
  mutation; only the offspring expresses it. A split is refused, spending
  nothing and keeping the offer, below the tuned growth, without room beside
  the cell or at the region's organism cap.
- Stay or become: a choice (trace mutation byte 34) or a bud (step intent bit 2
  of byte 13) can hand control to the offspring; the parent becomes wildlife.
  Ownership now follows the account under rules 13, so validation and plan
  history accept a founder that became wildlife (ADR-0163 succession).
- Buds under rules 13: litter replaces the 25% twin (whole hundreds plus a
  chance, up to the tuned maximum, sharing one investment), the tuned bud fee is
  charged once and reclaimed, and births stop at the organism cap.
- New results split_applied and split_refused; owners below rules 13 refuse a
  become.

The revamp tuning file gains the reproduction keys. Tests cover the split's
conservation and refusals, stay and become splits with exact restore, a refused
second split, the cap, become validation and the litter count. Refreshes the DEV
session window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 22:19:48 -04:00
dingoandClaude Opus 5.5 7e5775b6f7 feat(lifecycle): rules 13 behaviour-weighted mutation offers in the owner
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 4s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m34s
Foundation / postgres-tools (push) Successful in 22s
Foundation / server-image (push) Successful in 4m16s
Foundation / image (push) Successful in 4m47s
Phase 3 of the cellular revamp build plan (ADR-0179), server half.

- Every owned, active rules-13 life gathers its activity each tick from every
  phase (thrust and drift, brake presses, feeding and the collection limits,
  matter burned by channel, energy by use, contact with larger cells, engulf
  outcomes, growth blocked by a channel, buds made, refused or lost young, the
  reserve against the body) and advances its 98 triggers and 49 affinity scores.
- Active play earns an offer every interval: eligible catalog mutations of the
  life's plan, weighted by affinity, drawn with the floored and capped chances
  and a seeded systematic draw (a retry draws the same offer). Wildlife,
  newborns and frozen cells earn nothing; a plan without schema-7 traits has no
  catalog.
- A choice must name the life's own pending offer. It edits the offspring plan
  (phase 4 turns this into the split), pays the mutation's tuned cost from the
  reserve (matter may stand in for its energy, excluded channels excepted) and
  reclaims it as seeded random bubbles, merging into the farthest deposit at the
  deposit limit. Unaffordable choices keep the offer; declines clear it.
- Offspring inherit affinity scores and lineage progress. Growth speed scales
  the growth step with a carried fraction.
- Format 11 persists the offer tunables and each life's mutation state; the
  revamp tuning file gains the offer keys and optional per-mutation overrides
  (mutation.<key>.<field>), defaulting to the catalog with zero costs.

Tests cover per-mutation overrides and refusals, the collection-limit flags,
offers from active play, founder-5 plans never offered, exact restore of a
pending offer, a choice editing only the plan and reclaiming its cost with
closure, unaffordable choices, declines, foreign choices, and thrust moving
affinity. Refreshes the DEV session window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:58:32 -04:00
dingoandClaude Opus 5.5 732d008aa1 feat(biology): rules 13 mutation catalog, behaviour triggers and offer draw
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m30s
Foundation / postgres-tools (push) Successful in 22s
Foundation / server-image (push) Successful in 4m10s
Foundation / image (push) Successful in 4m46s
Phase 3 of the cellular revamp build plan (ADR-0179), first part: the headless
pieces the owner will use.

- The named catalog: all 49 mutations of Cellular_mutation_plan.md as data
  (stable ids and tuning keys, name, pro, con, effect, availability, increase
  and decrease triggers, base weight). Applying one edits a schema-7 plan by
  fixed reference points (a point is a hundredth of the founder's value), with
  paired edits, spreads across a channel group, recipe shifts, photosynthesis
  acquire and shed, and Adhesion; bounds, gates (carbon burned, buds made) and
  the enabled switch close it. 43 mutations are open at birth, as planned.
- Triggers: per-tick activity signals and eight trigger kinds (accumulate,
  absence, count in a window, event, share over a window, regular recurrence,
  straight heading, sharp turns) move each mutation's affinity score within
  bounds; integer state only, so replay reproduces scores.
- Offers: weight = base x a score multiplier; chances clamp(k x weight, floor,
  cap) summing to the options, in parts per million (floor 0.001%, cap 70%),
  found exactly by water-filling over sorted weights; a systematic draw picks
  distinct mutations whose inclusion frequencies equal their chances exactly.

Tests cover the catalog's identities, the pool at birth, every kind of edit,
bounds and gates; every trigger kind; score bounds; weights; a 300-seed chance
ensemble; and an exhaustive draw over all million draws. Refreshes the DEV
session window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:46:21 -04:00
dingoandClaude Opus 5.5 76d21b4815 feat(cellular): rules 13 feeding, matter as energy, spent pool and predation
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 4s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m29s
Foundation / postgres-tools (push) Successful in 31s
Foundation / server-image (push) Successful in 4m24s
Foundation / image (push) Successful in 5m3s
Phase 2 of the cellular revamp build plan (ADR-0179), server half.

- Matter as energy: when an energy cost exceeds the reserve's energy, reserve
  matter stands in for the rest at each channel's burn rate (pJ per 1,000 fg,
  scaled by the genome's burn efficiency), largest channel first. Upkeep may
  burn any channel; thrust only channels the player has not excluded. Burned
  matter adds no heat; it goes to the region's spent pool. A cell dies only when
  nothing can pay its upkeep.
- Collection: per-channel limits scaled by the genome's collection indices, a
  shared limit on all matter, a tunable cost per membrane point, and only the
  genome's kept share (energy conversion) of bubble energy reaching the reserve.
- Predation: engulf mass carries a tunable share of reserve matter, the
  predator's engulf capacity scales its side and the prey's membrane (now in
  nanometres) its own; kill absorption scales the predator's intake; the kill's
  remainder is split between bubbles at the prey and the spent pool, and a full
  habitat sends overflow to the pool.
- The spent pool is owner format 11 state, counted in conservation, and drips
  back as seeded random bubbles every interval tick.
- Reserve matter is carried as load: slower thrust and turning, costlier thrust.
- Channel exclusions are a 4-bit step intent field, trace byte 14; only owned
  lives under rules 13 may send them.

All values come from the revamp tuning file. Rules up to 12 are unchanged. Tests
cover payments and their conservation over 400 seeds, the rules-13 region step
(collection, membrane, kept energy, burning, engulfment and kill splits with
closure), the drip, load, exclusions, a 700-tick run with closure and exact
restore, and trace replay with exclusions. Session v14 and the client follow
the server phases (build plan). Refreshes the DEV session window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:35:31 -04:00
dingoandClaude Opus 5.5 c7b4846901 feat(lifecycle): rules 13 owner on format 11 with the revamp tuning file
Foundation / checks (client) (push) Successful in 4s
Foundation / checks (checks) (push) Successful in 4s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 3s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m30s
Foundation / postgres-tools (push) Successful in 22s
Foundation / server-image (push) Successful in 4m12s
Foundation / image (push) Successful in 4m40s
Phase 1 of the cellular revamp build plan (ADR-0179). The cellular owner gains
rules 13 on owner format 11: an explicit no-tick format-10/rules-12 upgrade
declares the region's revamp rules (so far the body's essential upkeep share),
existing lives keep their genomes, and founders born afterwards are founder 6
(genome schema 7, development 7). Format 11 is format 10 plus the revamp rules
block; it stays undeployed while later phases extend it. The tick, perception
and wildlife controller derive budgets with the declared body tuning, which
earlier development versions ignore.

Revamp tunables live in their own Git file,
deploy/kubernetes/region/dev/tuning/cellular-revamp.tuning, parsed by
parse_cellular_revamp_tuning with the same format and refusals as the rules-12
file, so images from before rules 13 never meet keys they do not know. Both
parsers now share read_tuning_lines; the rules-12 file's behaviour is unchanged.
The revamp file is not yet mounted into the region (build plan, phase 6).

Tests cover the upgrade and its refusals, mixed founder 5 and founder 6 lives
ticking with closure, exact restore and continuation, trace replay, and the new
tuning file including the checked-in DEV copy. Refreshes the DEV session window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:19:18 -04:00
dingoandClaude Opus 5.5 c183021fd5 feat(biology): genome schema 7 traits, founder 6 and development 7
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (client) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m27s
Foundation / postgres-tools (push) Successful in 33s
Foundation / server-image (push) Successful in 4m14s
Foundation / image (push) Successful in 4m41s
Phase 1 of the cellular revamp build plan (ADR-0179). Genome schema 7 carries
twenty 16-bit cellular traits after the movement arrangement: density, upkeep
efficiency, growth speed, collection per channel (E/C/N/P/O), burn efficiency
per matter channel, engulf capacity, kill absorption, litter, the body recipe
(C/N/P/O per thousand, summing to 1000) and adhesion. Its membrane is held in
nanometres so it can change in 5% steps of the founder's 1 um. The largest
record still fits the 256-byte bound.

Development 7 and founder 6 serve rules 13: density sets how large a body is
for its mass, the recipe sets the body's composition (intake keeps the founder
shares), upkeep is an essential share no trait reduces plus the rest over upkeep
efficiency (region-declared BodyTuning, trial 25%), the producer speed penalty
is dropped, and the reproduction value is the bud's share of the body with the
construction discount fixed at the founder's level. Founder 6 builds exactly
founder 5's cell. Earlier schemas and development versions are unchanged.

The development and metabolism test mains now print the failing line. Refreshes
the DEV session window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:09:06 -04:00
dingoandClaude Opus 5.5 0a5cf3e6bd docs: cellular revamp build plan and ADR-0179
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m34s
Foundation / postgres-tools (push) Successful in 5s
Foundation / server-image (push) Successful in 5s
Foundation / image (push) Successful in 5s
ADR-0179 records the maintainer's cellular gameplay revamp (rules 13) and the
two locked-requirement questions it raises: whole-organism mutations versus
"structural changes are expressed in offspring", and what Emerge does before
the 3D world exists. The build plan stages the work in six phases (genome and
body, feeding and predation, mutation offers, reproduction, multicellular and
emergence, wildlife and the playtest), each pushed with CI green and deployed
once at the end. Refreshes the DEV session window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 17:59:35 -04:00
dingoandClaude Opus 5.5 628721dff4 docs: cellular gameplay revamp plans
Plans for the cellular revamp, from the maintainer's decisions of 2026-10-22:
an overview of every gameplay system, the mutation offer system with a
49-mutation catalog, reproduction (on-demand buds, mutation splits,
multicellular organisms, emergence), feeding and energy (per-channel
collection, matter as energy, the spent pool), predation and defense, and
body and maintenance. Nothing is implemented by this commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 17:49:38 -04:00
185 changed files with 22421 additions and 626 deletions
+3 -4
View File
@@ -25,7 +25,6 @@ limits in docs/engineering/VALIDATION.md. Preserve uncommitted work by others.
After each completed and validated gate segment, commit its scoped changes and push After each completed and validated gate segment, commit its scoped changes and push
to the configured Git remote. Preserve unrelated untracked work; never stage secrets. to the configured Git remote. Preserve unrelated untracked work; never stage secrets.
Immediately before each push, refresh REGION_SESSION_WINDOW in The dev session window lives in SQL and is opened from the admin portal (ADR-0087
deploy/kubernetes/region/dev-session-route/listener.yaml with a unique activation amendment of 2026-10-27); Git carries no window. Do not deploy or claim live
and absolute UTC expiry four hours ahead (ADR-0087). Include it in that push; reachability from a Git update alone.
do not deploy or claim live reachability from a Git update alone.
+56 -3
View File
@@ -76,7 +76,10 @@ add_library(evo_biology STATIC
src/biology/genome.cpp src/biology/development.cpp src/biology/metabolism.cpp src/biology/genome.cpp src/biology/development.cpp src/biology/metabolism.cpp
src/biology/mutation.cpp src/biology/lineage.cpp src/biology/founder.cpp src/biology/mutation.cpp src/biology/lineage.cpp src/biology/founder.cpp
src/biology/cellular_motion.cpp src/biology/cellular_kinematics.cpp src/biology/cellular_motion.cpp src/biology/cellular_kinematics.cpp
src/biology/cellular_tuning.cpp src/biology/cellular_currents.cpp src/biology/cellular_tuning.cpp src/biology/cellular_revamp_tuning.cpp
src/biology/cellular_burn.cpp src/biology/cellular_catalog.cpp
src/biology/cellular_triggers.cpp src/biology/cellular_offers.cpp
src/biology/cellular_currents.cpp
src/biology/cellular_deposit_motion.cpp src/biology/cellular_deposit_motion.cpp
src/biology/cellular_uptake.cpp src/biology/cellular_uptake.cpp
src/biology/cellular_habitat.cpp src/biology/cellular_step.cpp src/biology/cellular_habitat.cpp src/biology/cellular_step.cpp
@@ -99,7 +102,8 @@ add_library(evo_lifecycle STATIC src/server/lifecycle/primitive_lives.cpp
src/server/lifecycle/cellular_population_codec.cpp src/server/lifecycle/cellular_population_policy.cpp src/server/lifecycle/cellular_population_codec.cpp src/server/lifecycle/cellular_population_policy.cpp
src/server/lifecycle/cellular_schedule.cpp src/server/lifecycle/cellular_population_batch.cpp src/server/lifecycle/cellular_schedule.cpp src/server/lifecycle/cellular_population_batch.cpp
src/server/lifecycle/cellular_environment.cpp src/server/lifecycle/cellular_environment_batch.cpp src/server/lifecycle/cellular_environment.cpp src/server/lifecycle/cellular_environment_batch.cpp
src/server/lifecycle/cellular_light.cpp src/server/lifecycle/cellular_liquid.cpp) src/server/lifecycle/cellular_light.cpp src/server/lifecycle/cellular_liquid.cpp
src/server/lifecycle/cellular_revamp.cpp src/server/lifecycle/cellular_admin_view.cpp)
add_library(evo::lifecycle ALIAS evo_lifecycle) add_library(evo::lifecycle ALIAS evo_lifecycle)
target_link_libraries(evo_lifecycle PUBLIC evo::biology evo::world) target_link_libraries(evo_lifecycle PUBLIC evo::biology evo::world)
evo_owned_target(evo_lifecycle) evo_owned_target(evo_lifecycle)
@@ -307,6 +311,16 @@ if(EVO_BUILD_POSTGRES)
add_executable(evo-grant-broker apps/evo-grant-broker/main.cpp) add_executable(evo-grant-broker apps/evo-grant-broker/main.cpp)
target_link_libraries(evo-grant-broker PRIVATE evo_grant_broker) target_link_libraries(evo-grant-broker PRIVATE evo_grant_broker)
evo_owned_target(evo-grant-broker) evo_owned_target(evo-grant-broker)
# ADR-0182 read-only admin API and portal host (schema v61).
# Section 15: its HTTPS client to Gitea and Argo CD (OpenSSL libssl) and the region switch.
find_package(OpenSSL 3 REQUIRED COMPONENTS Crypto SSL)
add_library(evo_admin_api STATIC src/server/admin/admin_api.cpp
src/server/admin/https_client.cpp src/server/admin/region_switch.cpp)
target_link_libraries(evo_admin_api PUBLIC evo_grant_broker PRIVATE OpenSSL::SSL OpenSSL::Crypto)
evo_owned_target(evo_admin_api)
add_executable(evo-admin-api apps/evo-admin-api/main.cpp)
target_link_libraries(evo-admin-api PRIVATE evo_admin_api)
evo_owned_target(evo-admin-api)
endif() endif()
# M7.9 clone and history audit tool (ADR-0067). # M7.9 clone and history audit tool (ADR-0067).
add_executable(evo-world-clone apps/evo-world-clone/main.cpp) add_executable(evo-world-clone apps/evo-world-clone/main.cpp)
@@ -333,7 +347,7 @@ if(EVO_BUILD_POSTGRES)
target_sources(evo-postgres-tests PRIVATE tests/region_session_tests.cpp target_sources(evo-postgres-tests PRIVATE tests/region_session_tests.cpp
tests/grant_broker_tests.cpp) tests/grant_broker_tests.cpp)
target_link_libraries(evo-postgres-tests PRIVATE evo_network_session evo_control_ledger_postgres target_link_libraries(evo-postgres-tests PRIVATE evo_network_session evo_control_ledger_postgres
evo_grant_broker OpenSSL::Crypto) evo_grant_broker evo_admin_api OpenSSL::Crypto)
target_compile_definitions(evo-postgres-tests PRIVATE EVO_POSTGRES_SESSIONS=1) target_compile_definitions(evo-postgres-tests PRIVATE EVO_POSTGRES_SESSIONS=1)
endif() endif()
if(EVO_BUILD_QUIC) if(EVO_BUILD_QUIC)
@@ -498,6 +512,34 @@ if(BUILD_TESTING)
else() else()
add_test(NAME cellular-tuning-contracts COMMAND evo-cellular-tuning-tests) add_test(NAME cellular-tuning-contracts COMMAND evo-cellular-tuning-tests)
endif() endif()
add_executable(evo-cellular-revamp-step-tests tests/cellular_revamp_step_tests.cpp)
target_link_libraries(evo-cellular-revamp-step-tests PRIVATE evo::biology)
evo_owned_target(evo-cellular-revamp-step-tests)
add_test(NAME cellular-revamp-step-contracts COMMAND evo-cellular-revamp-step-tests)
add_executable(evo-cellular-offers-tests tests/cellular_offers_tests.cpp)
target_link_libraries(evo-cellular-offers-tests PRIVATE evo::biology)
evo_owned_target(evo-cellular-offers-tests)
add_test(NAME cellular-offers-contracts COMMAND evo-cellular-offers-tests)
add_executable(evo-cellular-catalog-tests tests/cellular_catalog_tests.cpp)
target_link_libraries(evo-cellular-catalog-tests PRIVATE evo::biology)
evo_owned_target(evo-cellular-catalog-tests)
add_test(NAME cellular-catalog-contracts COMMAND evo-cellular-catalog-tests)
add_executable(evo-cellular-burn-tests tests/cellular_burn_tests.cpp)
target_link_libraries(evo-cellular-burn-tests PRIVATE evo::biology)
evo_owned_target(evo-cellular-burn-tests)
add_test(NAME cellular-burn-contracts COMMAND evo-cellular-burn-tests)
add_executable(evo-cellular-revamp-tuning-tests tests/cellular_revamp_tuning_tests.cpp)
target_link_libraries(evo-cellular-revamp-tuning-tests PRIVATE evo::biology)
evo_owned_target(evo-cellular-revamp-tuning-tests)
set(evo_dev_revamp_tuning
"${CMAKE_CURRENT_SOURCE_DIR}/deploy/kubernetes/region/dev/tuning/cellular-revamp.tuning")
if(EXISTS "${evo_dev_revamp_tuning}")
add_test(NAME cellular-revamp-tuning-contracts
COMMAND evo-cellular-revamp-tuning-tests "${evo_dev_revamp_tuning}"
"${CMAKE_CURRENT_SOURCE_DIR}/deploy/kubernetes/region/dev/tuning/cellular-reproduction-safety.tuning")
else()
add_test(NAME cellular-revamp-tuning-contracts COMMAND evo-cellular-revamp-tuning-tests)
endif()
set_tests_properties(cellular-tuning-contracts PROPERTIES TIMEOUT 60) set_tests_properties(cellular-tuning-contracts PROPERTIES TIMEOUT 60)
add_executable(evo-cellular-currents-tests tests/cellular_currents_tests.cpp) add_executable(evo-cellular-currents-tests tests/cellular_currents_tests.cpp)
target_link_libraries(evo-cellular-currents-tests PRIVATE evo::biology) target_link_libraries(evo-cellular-currents-tests PRIVATE evo::biology)
@@ -749,6 +791,17 @@ if(BUILD_TESTING)
evo_owned_target(evo-cellular-liquid-owner-tests) evo_owned_target(evo-cellular-liquid-owner-tests)
add_test(NAME cellular-liquid-owner-contracts COMMAND evo-cellular-liquid-owner-tests) add_test(NAME cellular-liquid-owner-contracts COMMAND evo-cellular-liquid-owner-tests)
set_tests_properties(cellular-liquid-owner-contracts PROPERTIES TIMEOUT 300) set_tests_properties(cellular-liquid-owner-contracts PROPERTIES TIMEOUT 300)
add_executable(evo-cellular-revamp-owner-tests tests/cellular_revamp_owner_tests.cpp)
target_include_directories(evo-cellular-revamp-owner-tests PRIVATE tests)
target_link_libraries(evo-cellular-revamp-owner-tests PRIVATE evo::lifecycle)
evo_owned_target(evo-cellular-revamp-owner-tests)
add_test(NAME cellular-revamp-owner-contracts COMMAND evo-cellular-revamp-owner-tests)
set_tests_properties(cellular-revamp-owner-contracts PROPERTIES TIMEOUT 300)
add_executable(evo-cellular-admin-view-tests tests/cellular_admin_view_tests.cpp)
target_include_directories(evo-cellular-admin-view-tests PRIVATE tests)
target_link_libraries(evo-cellular-admin-view-tests PRIVATE evo::lifecycle)
evo_owned_target(evo-cellular-admin-view-tests)
add_test(NAME cellular-admin-view-contracts COMMAND evo-cellular-admin-view-tests)
add_executable(evo-photosynthesis-tests tests/photosynthesis_tests.cpp) add_executable(evo-photosynthesis-tests tests/photosynthesis_tests.cpp)
target_link_libraries(evo-photosynthesis-tests PRIVATE evo::lifecycle) target_link_libraries(evo-photosynthesis-tests PRIVATE evo::lifecycle)
evo_owned_target(evo-photosynthesis-tests) evo_owned_target(evo-photosynthesis-tests)
+214
View File
@@ -0,0 +1,214 @@
# Cellular revamp build plan
Status: approved for implementation, 2026-10-22. Builds the
[cellular gameplay plan](Cellular_gameplay_plan.md) and its system plans:
[mutation](Cellular_mutation_plan.md), [reproduction](Cellular_reproduction_plan.md),
[feeding and energy](Cellular_feeding_energy_plan.md),
[predation and defense](Cellular_predation_defense_plan.md) and
[body and maintenance](Cellular_body_maintenance_plan.md). Decision record:
[ADR-0179](docs/adr/0179-cellular-gameplay-revamp.md). Continues from phases 1-2 of
the [region and movement plan](Cellular_Region_Movement_Plan.md), which shipped as
rules 12.
## Approach
- **Build every phase, then playtest once.** Each phase is committed and pushed with
CI green (AGENTS.md), but nothing is deployed until the last phase. The playtest
runs on a fresh DEV region opened with the new rules.
- **New versions, disposable DEV worlds.** Rules 13, genome schema 7, development 7,
founder 6, a new owner format, bundle and schema, and a fresh `cellular-v10`
opening. No upgrade from existing rules-12 regions (ADR-0177).
- **One revamp tuning file.** Every new tunable goes in
`deploy/kubernetes/region/dev/tuning/cellular-revamp.tuning`, beside the rules-12
`cellular.tuning`, with the same format and validation.
- **Server phases first, then one session version.** Phases 1-5 build and test the
server halves. The wire changes in every one of them (body values, offers, bud
choices, organisms), so session v14 and the client screens for all of them are one
step after phase 5, rather than a protocol revision per phase. Nothing deploys before
that step anyway.
- **Shared biology.** Derivations stay in the headless library, so the client
predictor and the server agree.
## Phases
### Phase 1: genome and body (rules 13 foundation) - done
Server:
- Genome schema 7: every heritable value the plans name, in points (founder 100)
unless stated:
- size, density, membrane, body recipe (per thousand, C/N/P/O), upkeep
efficiency, growth speed;
- collection per channel (E/C/N/P/O), shared intake, burn efficiency per matter
channel, energy kept per bubble (`energy_conversion`), light capture;
- engulf capacity, kill absorption;
- bud share, litter (founder 0), Adhesion flag;
- the existing movement arrangement.
- Development 7 and founder 6: size, density and recipe set mass, footprint and
surface; upkeep = essential floor + adjustable part / efficiency; membrane mass
from points; no legacy photosynthesis speed penalty.
- Rules 13 owner skeleton (new owner format) and tuning keys for every body value.
Client: in the session v14 step.
Verify: founder 6 derives the same body as founder 5 where the plans say "today's
value"; the essential floor holds; encode/decode and bound checks for schema 7.
### Phase 2: feeding, energy and predation - server done
Server:
- Collection per channel with the shared intake limit; the membrane collection penalty.
- Energy kept per bubble; the rest to heat.
- Matter as energy: burn the largest non-excluded channel, upkeep overrides
exclusions, death only when nothing can pay.
- Region spent pool with a seeded drip back as bubbles; waits at the deposit limit.
- Reserve matter in mass for handling and movement energy, not upkeep.
- Engulf check with engulf capacity and `engulf_reserve_mass_percent`; kill
absorption; the kill remainder split between bubbles and the spent pool.
- Channel exclusions are a 4-bit step intent field, carried in the trace's byte 14.
Client (session v14 step): energy display including what matter can stand in for;
channel exclusion toggles; spent-pool drips drawn like infall; hover and HUD show the
phase 1 body values.
Verify: conservation per channel and energy across burning, the pool, kills and
drips; no burn of excluded matter except for upkeep; replay determinism.
### Phase 3: mutation offers - server done
Server:
- Catalog of the 49 mutations as data: effect, eligibility, triggers, base weight,
steps, cost and `enabled`, all from the tuning file.
- Per-cell affinity scores, inherited at birth; activity counters for every trigger.
- Chance allocation (`clamp(k x weight, floor, cap)`, summing to the option count)
and a seeded systematic draw; the draw and chances are recorded so a retry never
rerolls.
- Offer cadence from the tuning file; one pending offer.
- Cost paid from the reserve (matter may stand in for energy) and reclaimed as seeded
random bubbles, merging into the farthest bubble at the deposit limit.
Until phase 4, a chosen mutation edits the offspring plan (as rules 10-12 do); phase 4
turns the choice into the split.
Client (session v14 step): offer screen with name, pro, con, chance, cost and shortfall.
Verify: chances sum to the option count and respect floor and cap; the draw's
marginal frequencies match the chances over a seed ensemble; triggers fire as
specified; costs conserve.
### Phase 4: reproduction - server done
Server:
- On-demand bud with the control choice (stay or become the bud), the tunable fee and
bud share; one-way control transfer (ADR-0163).
- Mutation split: write the mutation into both plans, split body and reserve by
`split_share`, the offspring expresses it, the player chooses the cell; refusals
leave the offer pending.
- Litter: guaranteed and chance extra offspring sharing one investment, limited by
free spots and the region cap.
- Wildlife buds from its own plan with litter; wildlife never mutates.
Client: Bud with Stay / Become; offer options with Stay as founder / Become offspring;
refusal reasons.
Verify: control transfer is one way and exactly once across retries and restarts;
splits and litters conserve; a refused split spends nothing.
### Phase 5: multicellular organisms and emergence - server done
Unblocked 2026-10-23: the maintainer accepted whole-organism mutations and the
playtest form of Emerge (ADR-0179).
Server:
- Adhesion forms the organism at once. The organism is one life with a member count,
one genome, one reserve and a body that is the sum of its members.
- Internal buds add members; mutations are expressed by the whole organism; whole-
organism engulfment by total mass; mass-scaled handling.
- Emergence threshold (members, mass, reserve energy) and the Emerge action; the
wildlife member limit as a safeguard.
As built:
- An organism develops as its genome with the target size times its members, so mass,
footprint, upkeep, intake and engulf mass all follow from it. Its corpse records the
single-cell extent.
- Adhesion ends the single cell's life as `merged` (an empty corpse) and starts the
organism as a new life (bud identity, two members) holding the whole body and reserve,
at the cell's spot and with its account, affinity and progress.
- An organism's mutation is recorded as a direct expression (no split); its changed
tissue is paid from the reserve with construction energy. Unaffordable keeps the offer.
- An organism's bud pays the bud fee and adds litter members at the current growth.
Wildlife organisms stop one member short of the threshold. An organism cannot become
its bud.
- Handling adds `organism.load_per_mille` of the extra members' mass as load.
- Emerge (intent bit, exclusive with bud, engulf, intake and frozen) at the threshold
exports the body and reserve through the boundary ledger and ends the life as
`emerged`. Below the threshold the request is ignored.
Client: organism drawn as its member cells; Emerge button at the threshold.
Verify: one reserve and one genome across members; whole engulfment conserves; the
Emerge action only at the threshold.
### Session v14 and the client - done
- Session v14: the phase 1 body values in perception; payable energy; the exclusion
control; named offers with pro, con, chance, cost and Stay / Become; the bud choice;
organisms and the Emerge action.
- Client screens for all of the above.
As built ([schema](schemas/network/session-v14-cellular-revamp.md)): a 64-byte body block
(members, threshold, exclusions, Emerge open, payable energy, mass, the 20 traits); become,
emerge and exclusions on actions; become on choices; catalog offers (id, chance, cost) named
by the client from the shared catalog; the emerged ending. The client shows Stay / Become
offspring on each offer (one Choose for an organism or Adhesion), "Continue as the bud",
the organism's size and the Emerge button, the channels kept from burning, the body, and the
emerged end screen.
### Durable plumbing - done
Bundle 15, schema 60 and the `cellular-v10` opening (ADR-0179 "Durable form"): the
14 -> 15 revamp profile migration with recovery, become stored as bit 15 of the durable
choice's operator, the action input's new bits, and mutation results 0-6.
### Phase 6: wildlife, instrumentation and the playtest
- Wildlife controller: matter-as-energy aware, budding with litter, engulfing with the
new eligibility. Done: hunger counts payable energy, buds wait for the bud fee (litter is
the owner's), an organism adds members until one short of the threshold, and hunting uses
the region step's rules-13 engulf test (reserve share, capacity, membrane in nanometres).
- Play summary: first-birth time, time to Adhesion, deaths by cause, energy share paid
by matter, offers seen and chosen, mutations held per lineage.
- Mount `tuning/cellular-revamp.tuning` into the provision Job beside `cellular.tuning`
(kustomize `configMapGenerator`) in the push that promotes the new images. Revamp keys
live in that separate file so images from before rules 13 never read them.
- Opening `cellular-v10` in a new DEV region; promote the images; full Argo sync.
- Playtest.
## Playtest feedback (2026-10-26)
- Choices stalled after one split: a split needs a grown cell. The view now carries growth and
a split-ready flag; the client gates Stay / Become; an offer waits until a single cell can
split; DEV splits once half grown (region 13).
- The region edge is drawn and named when the cell is against it; the region's cell count is
shown; the client says when upkeep is burning kept matter.
- Mixed bubbles (every nutrient, recipe proportions) via `--mixed-motes`, drawn as small pools;
liquid openings move pools out of the currents into still water.
- Phosphorus: intake per channel follows the body's recipe, so single-nutrient phosphorus
bubbles fed slowly while growth used it at once; mixed bubbles carry it with everything else.
## Open items
| Item | Phase |
| --- | --- |
| Retuning bubble energy or founder `energy_conversion` (keep 40% vs today's 100%) | 2 |
| Organism pace: in tests a two-member organism at half growth swims about 7.5 µm per tick and needed about 5,000 ticks on a rich mote to fund one internal member | 6 |
| Region migration does not carry rules-13 per-life state (affinity, members); an organism's move would be refused | 6 |
## Risks
| Risk | Mitigation |
| --- | --- |
| Many new genome fields exceed the 256-byte genome bound | Measure in phase 1; widen the bound in schema 7 if needed. |
| Matter-as-energy makes cells nearly unkillable by starvation | Burn rates and drip rate are tunable; instrument the matter share of energy paid. |
| 49 triggers add per-tick work | Counters are integer and per cell; measure tick time in phase 6. |
| Control transfer across retries duplicates or loses control | Durable action receipts, as for existing births. |
| One deploy at the end hides integration problems | Every phase ships its client half and runs end to end in local tests. |
+135
View File
@@ -0,0 +1,135 @@
# Cellular body and maintenance plan
Amendment, 2026-10-26: [ADR-0181](docs/adr/0181-cellular-reproduction-safety.md)
adds an opt-in growth fuel buffer. Automatic construction spends only what leaves
the resulting body its declared survival reserve; tissue prices remain unchanged.
Status: planning draft, 2026-10-22. Records the maintainer's decisions on body size,
body recipe, upkeep, density, growth and bud size. Part of the
[Cellular gameplay plan](Cellular_gameplay_plan.md). Replaces the 031-050 notes in
[Cellular_energy_photosynthesis_draft.md](Cellular_energy_photosynthesis_draft.md).
No code, runtime rule or live region is changed by it.
All indices below are stored in points with the founder at 100, and change in the
mutation plan's 5-point steps unless stated otherwise.
## 1. Size
The genome's `target_size` (the full-grown body mass) moves to points; 100 is today's
founder (8,000,000 fg).
| Larger | Smaller |
| --- | --- |
| Harder to engulf; can engulf bigger prey | Easier to engulf; limited to smaller prey |
| More upkeep (upkeep follows body mass) | Less upkeep |
| Costlier buds and regrowth | Cheaper buds and regrowth |
| Heavier, so slower to move | Lighter, so quicker |
| Bigger footprint, so it touches more food | Smaller footprint |
None of these are separate penalties; they follow from mass and size.
## 2. Body recipe
The body's share of each matter channel (C, N, P, O, in per thousand, summing to
1000) becomes a heritable trait. The founder's recipe is today's fixed composition.
- A recipe mutation moves a tunable step (trial 20 per thousand) from one channel to
another.
- Each channel has a tunable minimum share, so no body drops a channel entirely.
- The recipe changes what the body needs to build, regrow and bud. It has no
performance effect: its value is fitting the body to what the region supplies.
- Together with separate collection rates, this lets a lineage specialize, for example
a nitrogen-poor body that thrives where nitrogen is scarce.
## 3. Upkeep efficiency
Upkeep can be made cheaper but never zero:
```text
upkeep = essential part + adjustable part x 100 / upkeep efficiency
```
- The essential part is a tunable share of the founder's upkeep (trial 25%), which no
mutation reduces.
- Upkeep efficiency is an index, founder 100.
- Upkeep stays on the body only (feeding and energy plan).
Flexible upkeep (switching unused machinery off, draft 030) is postponed.
## 4. Density
Tissue density is an index, founder 100. Body mass is set by size, so density changes
how large the body is for that mass:
| Denser | Lighter |
| --- | --- |
| Smaller footprint for the same mass | Larger footprint for the same mass |
| Less surface, so slower collection and less membrane mass | More surface, so faster collection but more membrane mass and upkeep |
| Touches less food and fewer cells | Touches more food and more cells |
Body mass is unchanged by density; only membrane mass changes, because it follows the
surface.
Shape traits (elongated, flattened, rounded, flexible, rigid) and flexible adult size
are dropped: the body is a square and there is no shape or deformation model.
## 5. Growth
- Growth speed is an index, founder 100, scaling a tunable base rate (trial 5 per
thousand of full size per tick, today's value).
- Faster growth spends the same matter and energy in less time; it does not make
growth cheaper.
- After a mutation split, each half starts at the size its half of the body covers and
regrows at its growth speed.
## 6. Bud size
The reproduction capability sets the size of an on-demand bud, as a share of the
parent's body, in points (founder 100, which is 500 per thousand: half the body),
built from the parent's reserve. Extra offspring per bud come from litter (mutation
plan, section 9). Bigger buds cost more but start larger and are harder to engulf; smaller
buds are cheap but vulnerable.
## 7. Dropped
| Draft | Why |
| --- | --- |
| 031-034 storage | No storage caps. |
| 039-040 recycling and leakage | No tissue turnover or leakage model. |
| Dropping food to provision offspring | Splits already share resources. |
| 043-047 shape, 050 flexible size | No shape model. |
## 8. Genome indices and mutations
| Index | Founder | Mutations |
| --- | --- | --- |
| Size | 100 | Larger Body, Smaller Body (mutation plan, section 8) |
| Body recipe | Today's composition | Carbon-, Nitrogen-, Phosphorus- and Other-Thrifty Body (section 8) |
| Upkeep efficiency | 100 | Efficient Upkeep, Rapid Growth (section 8) |
| Density | 100 | Dense Tissue, Light Tissue (section 8) |
| Growth speed | 100 | Rapid Growth, Efficient Upkeep (section 8) |
| Bud share | 100 | Bigger Buds, Smaller Buds (section 9) |
## 9. Tunables
| Setting | Trial |
| --- | --- |
| Recipe step | 20 per thousand |
| Minimum share per channel | To be selected in playtesting |
| Essential upkeep share | 25% of the founder's upkeep |
| Base growth rate | 5 per thousand per tick |
| Size, density, efficiency and growth index bounds | To be selected in playtesting |
## 10. Implementation map
| Piece | State today |
| --- | --- |
| Size from `target_size` | Exists, in femtograms; points are new. |
| Body recipe | Fixed per development version; heritable shares are new. |
| Upkeep with an essential floor and efficiency | New. |
| Density | Fixed per development version; heritable index is new. |
| Funded regrowth | Exists (funded maturation, rules 9); the growth index is new. |
| Bud size from the reproduction capability | Exists; the new bud flow is in the reproduction plan. |
Every new behaviour goes in a new rules version; regions on earlier rules keep their
meaning.
+165
View File
@@ -0,0 +1,165 @@
# Cellular feeding and energy plan
Status: planning draft, 2026-10-22. Records the maintainer's decisions on how cells
collect resources and pay for energy. Part of the
[Cellular gameplay plan](Cellular_gameplay_plan.md). Replaces the collection and fuel
sections of [Cellular_feeding_draft.md](Cellular_feeding_draft.md) and the energy
sections of [Cellular_energy_photosynthesis_draft.md](Cellular_energy_photosynthesis_draft.md).
No code, runtime rule or live region is changed by it.
## 1. Resources
| Channel | Unit | Used for |
| --- | --- | --- |
| E (energy) | picojoules | Upkeep, thrust, construction, mutation costs |
| C (carbon) | femtograms | Body tissue; energy stand-in |
| N (nitrogen) | femtograms | Body tissue; energy stand-in |
| P (phosphorus) | femtograms | Body tissue; energy stand-in |
| O (other matter) | femtograms | Body tissue; energy stand-in |
Resources enter a region through its infall sources (as today), and come from light
for producers. They return to the region through deaths, kills (predation and defense
plan), mutation costs and the spent pool (section 3).
There are no storage caps. Reserve matter counts toward the cell's mass (section 4).
## 2. Collection
### Separate rates per channel
Each cell has a **collection index per channel** in its genome, with the founder at
100 on every channel:
```text
collection: energy 100, carbon 100, nitrogen 100, phosphorus 100, other 100
```
- A channel's collection rate is the founder's rate for that channel scaled by its
index (105 collects that channel 5% faster).
- The existing ingestion capability stays as the **shared limit**: total matter taken
per tick cannot exceed it, so raising every channel does not bypass the cell's
overall intake.
- Collection is still by contact, as today: the cell drains what it touches.
This gives lives real variation: a nitrogen gatherer and a carbon gatherer feed
differently in the same region. The founder rates, the shared limit and how they
interact need serious tuning.
## 3. Matter as energy
### The rule
When an energy cost is larger than the reserve's energy, the cell pays the remainder
with **reserve matter** instead. The matter is not converted into energy; it stands in
for it. It covers every energy cost: upkeep, thrust, growth and bud construction, and
the energy part of mutation costs.
- **Burn rate:** each channel has a tunable rate, the picojoules 1,000 fg of it stands in
for, scaled by the cell's burn efficiency for that channel (founder 100). Matter pays
at a worse rate than the energy bubbles carry, so burning matter is always the
expensive way to stay alive (trial: 2,000 pJ per 1,000 fg).
- **Only reserve matter burns.** The body is never burned.
- **Death:** a cell dies when its upkeep cannot be paid by energy or any reserve
matter.
### Which matter burns
- The cell burns the channel it has the **most** of (in femtograms). If that channel
runs out mid-payment, it moves to the next largest. Ties go in the order C, N, P, O.
- The player can **exclude** channels (for example, keep phosphorus for budding).
Excluded channels are not burned for thrust, construction or mutation costs. The
controlled cell keeps its exclusions through splits and buds; wildlife excludes
nothing.
- **Upkeep overrides exclusions.** If upkeep cannot be paid any other way, it burns
excluded matter rather than let the cell die with matter on board.
### Where the burned matter goes
Burned matter goes into the region's **spent pool**, one amount per channel. The pool
drips back into the region as new bubbles at random points, at a tunable rate. If the
region is at its deposit limit, the drip waits.
- The region keeps all its matter; nothing is destroyed.
- Burned matter cannot be collected straight back, so matter is not an endless energy
supply. The drip rate decides how scarce energy is.
- Energy paid with real energy still goes to heat, as today.
### Presentation
The energy display shows the reserve's energy plus what the usable (non-excluded)
matter can stand in for, and roughly how long the cell can live on it.
## 4. Mass
Carried reserve matter counts toward the cell's total mass, alongside its body. Mass
slows acceleration and turning and raises movement energy (see the reproduction plan's
mass rule). Hoarding mass for emergence makes an organism slower and costlier to move.
Upkeep is charged on the **body only**. Reserve matter adds to movement costs, not to
upkeep, so hoarding is paid for once.
## 4a. Energy-bubble efficiency
The founder's `energy_conversion` capability (400 per thousand, unused in cellular play
today) becomes the share of collected energy-bubble E the cell keeps as reserve
energy. The rest goes to heat. Matter is collected whole; this applies to E only.
This gives extraction mutations a real axis: a higher share means more energy per
bubble, paid for by the mutation's paired change.
Today a cell keeps 100% of bubble energy. At the founder's 400 per thousand it would
keep 40%, cutting its energy income by more than half. Either the founder's value or
the energy in bubbles must be retuned when this is turned on.
## 5. Photosynthesis
- **Unlock:** Acquire Photosynthesis becomes available after the cell has burned a
tunable amount of carbon as energy. The count carries to offspring, like affinity
scores.
- **Weights:** burning carbon raises its chance; burning other channels lowers it.
Cells that live on carbon drift toward becoming producers.
- **Mass:** producer tissue slows the cell through the mass model only. The legacy
speed penalty is dropped in the new rules.
- **Light:** constant; there is no day/night cycle and no spatial light. The light
specialists (024/025) are dropped.
## 6. Genome indices and mutations
| Index | Founder | Mutations (mutation plan, section 6) |
| --- | --- | --- |
| Collection per channel (E, C, N, P, O) | 100 each | Carbon, Nitrogen, Phosphorus and Other Matter Gatherer |
| Shared intake limit | 100 | Big Appetite, Small Appetite |
| Burn efficiency per matter channel | 100 each | Carbon, Nitrogen, Phosphorus and Other Matter Metabolism |
| Energy kept per bubble (`energy_conversion`) | 100 | Thorough Extraction, Rapid Extraction |
| Light capture | Absent; 100 when acquired | Acquire, Expand, Reduce and Shed Photosynthesis |
## 7. Tunables
| Setting | Trial |
| --- | --- |
| Founder collection rate per channel | From today's derived limits |
| Shared ingestion limit | Founder ingestion capability |
| Burn rate per channel (pJ per 1,000 fg) | 2,000 |
| Spent-pool drip rate | To be selected in playtesting |
| Carbon burned before photosynthesis is offered | To be selected in playtesting |
## 8. Open questions
None.
## 9. Implementation map
| Piece | State today |
| --- | --- |
| Contact feeding with per-channel limits | Exists; limits derive from one ingestion rate. |
| Collection index per channel | New genome field (new genome schema). |
| Matter paying energy costs | New, in every place an energy cost is charged. |
| Burn order and player exclusions | New per-cell state and a new client control. |
| Region spent pool and drip | New region state; releases bubbles like infall. |
| Reserve matter in mass | New in handling and movement energy; upkeep unchanged. |
| Energy-bubble efficiency from `energy_conversion` | Capability exists; applying it to cellular E intake is new. |
| Carbon-burned count, inherited | New per-cell state. |
| Photosynthesis without the legacy speed penalty | New rules; light capture exists (rules 11+). |
Every new behaviour goes in a new rules version; regions on earlier rules keep their
meaning.
+106
View File
@@ -0,0 +1,106 @@
# Cellular gameplay plan
Status: planning index, 2026-10-22. Tracks every cellular gameplay system, its state,
and the maintainer's decisions. Each system gets its own plan; once all are settled,
the mutation catalog is reworked across them. After the cellular game is finished,
every mutation is reviewed for its effect on the 3D organism.
Plans so far:
- [Cellular_mutation_plan.md](Cellular_mutation_plan.md): what a mutation is, offers,
weights, costs, and the full catalog (49 mutations).
- [Cellular_reproduction_plan.md](Cellular_reproduction_plan.md): budding, mutation
splits, multicellular organisms, emergence.
- [Cellular_feeding_energy_plan.md](Cellular_feeding_energy_plan.md): collection,
matter as energy, the spent pool, photosynthesis.
- [Cellular_predation_defense_plan.md](Cellular_predation_defense_plan.md): engulfment,
what a predator gets, membrane defense.
- [Cellular_body_maintenance_plan.md](Cellular_body_maintenance_plan.md): size, body
recipe, upkeep, density, growth, bud size.
The earlier drafts (feeding, energy/photosynthesis, defense, movement, mutation) are
source material. They were written against superseded policies and are rewritten
into plans rather than merged.
## Systems
| System | Today | Status | Plan |
| --- | --- | --- | --- |
| Movement | Liquid motion with the movement arrangement | Planned | Mutation plan |
| Reproduction and multicellular | Budding into wildlife | Planned | Reproduction plan |
| Collection | One ingestion rate split into per-channel limits; contact feeding | Planned | Feeding and energy plan |
| Energy sources | Energy bubbles; light (rules 11+) | Planned | Feeding and energy plan |
| Engulfment | Instant; attacker mass vs prey mass x membrane | Planned | Predation and defense plan |
| Defense | Membrane thickness | Planned | Predation and defense plan |
| Body and maintenance | Upkeep from mass and membrane | Planned | Body and maintenance plan |
| Temperature | Tuning keys read, unused | **Postponed** | - |
| Sensing and communication | None | **Postponed** | - |
| Multicellular mutations | None | **Postponed** | - |
| Damage and repair | Damage field exists, unused | **Out for now** | - |
## Decisions, 2026-10-22
### Feeding and energy
- **Matter as energy.** When the reserve's energy cannot cover an energy cost, the
cell pays it with reserve matter instead, at a higher rate than pure energy. The
matter is not converted into energy; it stands in for it. A cell dies only when
neither energy nor usable matter can pay. The cell burns the channel it has most of;
the player can exclude channels. Burned matter goes to a region spent pool that drips
back as random bubbles.
- **Separate collection rates per channel** (E, C, N, P, O). More variation between
lives; needs serious tuning.
- **Carried reserve matter counts toward mass** for movement and movement energy, not
upkeep. Hoarding for emergence slows an organism down.
- **No storage caps.**
### Predation and defense
- **Engulfment stays instant** for this pass.
- **Prey recovery:** the predator absorbs up to its per-tick collection limit; half the
remainder becomes bubbles at the prey's spot, half goes to the spent pool.
- **Everyone engulfs**, wildlife included.
- **Membrane** is stored in points (founder 100); thicker membrane also slows
collection.
- **Reserve matter in engulf mass** is a tunable percentage (0% turns it off).
- **Armor is postponed.** Membrane thickness is the defense for now.
- Postponed with live capture: prey retention, slippery coating, adhesive grip,
defensive expulsion, siphoning.
### Photosynthesis
- **Legacy speed penalty dropped** in the new rules. Producer tissue slows a cell
through the mass model only.
- **Light specialists dropped** (024/025): there is no day/night cycle and no spatial
light.
- **Unlock:** offered after burning a tunable amount of carbon as energy; burning
carbon raises its chance, burning other channels lowers it.
### Body and maintenance
- **Size** moves to points; Larger and Smaller follow from mass.
- **Body recipe** (C/N/P/O shares) becomes heritable.
- **Upkeep efficiency** is in, with an essential floor; flexible upkeep is postponed.
- **Density** is kept as an index; all shape traits are dropped.
- **Growth speed** is a trait with a tunable base rate.
- **Bud size** comes from the reproduction capability.
- **Dropped:** storage (031-034), recycling and leakage (039-040), food provisioning.
### Catalog scope
- Mutation deep dive covers the planned systems: movement, feeding and energy,
predation and defense, body and maintenance, reproduction.
- **Draft groups 071-150 are on hold**: colonies and colony architecture, producers and
exchange, environmental adaptation, sensing, metabolic regulation, loss and
simplification, habitat specializations. Sensing and multicellular mutations are
postponed as systems.
## Order
1. Done: system plans for movement, reproduction, feeding and energy, predation and
defense, body and maintenance; the mutation catalog for this pass.
2. Build the plans in phases ([build plan](Cellular_Revamp_Build_Plan.md),
[ADR-0179](docs/adr/0179-cellular-gameplay-revamp.md)), then playtest at the end.
3. Later: temperature, damage and repair, armor, live capture, sensing, multicellular
mutations, draft groups 071-150.
4. After the cellular game: each mutation's effect on the 3D organism.
+400
View File
@@ -0,0 +1,400 @@
# Cellular mutation plan
Status: planning draft, 2026-10-22. Records the maintainer's decisions on what a
mutation is, how offers work, and the full catalog for this pass (49 mutations). Where this document
conflicts with [Cellular_mutation_draft.md](Cellular_mutation_draft.md) or
[Cellular_movement_draft.md](Cellular_movement_draft.md), this document wins. No code,
runtime rule or live region is changed by it.
For a single cell, accepting a mutation divides it: the offspring expresses the
mutation and both cells carry it in their heritable plan. A multicellular organism
expresses an accepted mutation directly, without dividing. See
[Cellular_reproduction_plan.md](Cellular_reproduction_plan.md), sections 4 and 6.
## 1. What a mutation is
A mutation is an opportunity to steer the evolution of your organism. Each one is a
catalog entry describing one change to the genome. Very few mutations are pure
upgrades: most carry a pro and a con, and both are shown to the player when choosing.
| Field | Meaning |
| --- | --- |
| Name / description | What the player sees. |
| Effect | The exact genome change, e.g. `output +5, efficiency -2`. |
| Pro / Con | Shown in the offer. Derived from the effect where possible, not a flat penalty. |
| Available | Prerequisites (anatomy, region features) and limits (never past an axis bound). |
| Increase trigger | Behaviour that raises the mutation's affinity score. |
| Decrease trigger | Behaviour that lowers it. |
| Cost | Tunable price in energy and matter, per channel (section 4). |
## 2. Offer cadence
Offers arrive periodically while the player is actively playing. One offer is pending
at a time; it stays available while the player moves and is not dismissed by a timer.
Tunable: `mutation.offer_interval_ms` (trial 25,000) and the definition of active play.
Both need playtesting.
## 3. Weights and the draw
### Affinity scores
- Every cell holds an integer **affinity score per mutation**, starting at 0.
- When a mutation's increase trigger completes, its score rises by that mutation's
`increase_points`; a decrease trigger lowers it by `decrease_points`. The trigger's
timer then restarts, so a held behaviour fires repeatedly.
- Scores are bounded to `[score_min, score_max]`.
- **No drift:** scores change only through triggers, never with time.
- **Inheritance:** offspring start with their parent's scores.
### From score to chance
1. **Eligible pool:** every mutation whose prerequisites are met and whose effect stays
within its limits. Ineligible mutations have no chance at all.
2. **Weight:** `weight = base_weight x multiplier(score)`. The multiplier is 1 at score 0
and rises or falls linearly to `max_multiplier` at `score_max` and `min_multiplier`
at `score_min`.
3. **Chance of appearing in the offer:** `p = clamp(k x weight, floor, cap)`, with `k`
solved so that the chances of the eligible pool sum to the number of options
(300% for three). `floor` = **0.001%** (anomalies always happen); `cap` = **70%**.
4. **Draw:** systematic sampling over the pool. One random number picks the options,
they are always distinct, and each mutation's real chance of appearing equals its
`p`. The draw is seeded per cell and offer, so a retry or reconnect never rerolls.
The pool always holds well over five eligible mutations, so the 70% cap is always
satisfiable.
### Tunable draw settings
| Setting | Scope | Trial |
| --- | --- | --- |
| `offer_options` | global | 3 |
| `cap`, `floor` | global | 70%, 0.001% |
| `score_min`, `score_max` | global | -1000, +1000 |
| `max_multiplier`, `min_multiplier` | global | 10x, 0x (the floor still applies) |
| `base_weight` | per mutation | 100 |
| `increase_points`, `decrease_points` | per mutation | 100 |
| Trigger thresholds (seconds, counts, angles) | per mutation | listed with each mutation |
| Step sizes: primary, paired, spread | per mutation | 5, 2, 1 points |
## 4. Choosing and cost
The player picks one of the options or declines. Declining is free; the next offer
draws again.
Each mutation has its own tunable **cost**: an amount per channel (energy E in
picojoules; carbon C, nitrogen N, phosphorus P and other matter O in femtograms), plus
one **scale** from 0% to 100% for fine tuning. The charged amount per channel is
`amount x scale`.
```text
mutation.strong_propulsion.cost_e_pj = 0
mutation.strong_propulsion.cost_c_fg = 0
mutation.strong_propulsion.cost_n_fg = 0
mutation.strong_propulsion.cost_p_fg = 0
mutation.strong_propulsion.cost_o_fg = 0
mutation.strong_propulsion.cost_scale_percent = 0
```
Every mutation starts with all amounts and the scale at 0. Playtesting decides whether
a mutation needs a cost at all, and further playtesting tunes it, one mutation at a
time.
The cost is paid from the reserve when the mutation is applied; reserve matter can
stand in for its energy part (feeding and energy plan, section 3). An unaffordable
option is still offered; it shows the shortfall and cannot be selected until the
reserve covers it.
**Where the cost goes:** the environment reclaims it. Each non-empty channel of the
paid cost becomes a new resource bubble of that amount at a random point in the
region, chosen by the region's seeded draw so a replay places it identically. Nothing
is destroyed; the region's totals are unchanged.
If the region is already at its deposit limit, the reclaimed amount merges into the
existing bubble **farthest** from the paying cell, so the cost cannot easily be
collected straight back.
This replaces the earlier draft policy of no separate fee for selecting a mutation.
### Testing the pool
For testing, every mutation can be switched on or off in the tuning file
(`mutation.<name>.enabled = 1`). A disabled mutation is not in the pool at all, even
at the floor. Together with `base_weight`, this lets a playtest narrow the pool to
the mutations under test or bias the draw toward them.
## 5. Movement mutations
Movement edits the genome's movement arrangement, in reference points where the founder
is 100. Steps add or remove fixed points; they never compound (100 -> 105 -> 110).
Global defaults: primary step `mutation.step_points` = 5, paired step
`mutation.paired_points` = 2; each mutation can override them (section 3).
Percentages below are at matched conditions against the arrangement before the edit,
from the current handling model (top speed ~ thrust / drag; thrust energy ~ output /
efficiency).
### Core mutations (available from birth)
#### Strong Propulsion
- **Effect:** output +5, efficiency -2.
- **Pro:** top speed and acceleration +5%.
- **Con:** energy per second at full thrust +7%; energy per distance +2%.
- **Increase:** thrust for 10 s in total.
- **Decrease:** no thrust for 30 min.
#### Economical Propulsion
- **Effect:** coasting +5 (lower drag, forward and sideways).
- **Pro:** drifts about 5% further after letting go; top speed +5%; cheaper travel when
thrust is pulsed.
- **Con:** stops more slowly, so precise stops need braking, which costs energy; slides
more in turns.
- **Increase:** thrust at least every 15 s for a minute, or move steadily for a minute.
- **Decrease:** no movement for 2 min.
#### Efficient Propulsion
- **Effect:** efficiency +5, output -2.
- **Pro:** energy per distance -5%; energy per second at full thrust -7%.
- **Con:** top speed and acceleration -2%.
- **Increase:** movement is over half the energy spent in a minute.
- **Decrease:** no thrust for 5 min.
#### Agile Steering
- **Effect:** steering +5, output -2.
- **Pro:** turns 5% faster.
- **Con:** top speed and acceleration -2%.
- **Increase:** 5 sharp turns (over 90 degrees) within 20 s.
- **Decrease:** hold one heading (within 20 degrees) for 60 s of thrust.
#### Streamlined Body
- **Effect:** streamlining +5, steering -2 (lower forward drag only).
- **Pro:** top speed +5% and longer forward glide.
- **Con:** turns 2% slower.
- **Increase:** thrust in a straight line (within 20 degrees) for 20 s.
- **Decrease:** 5 sharp turns within 20 s.
Distinct from Economical Propulsion: Streamlined lowers forward drag only and pays in
turning; Economical lowers drag in every direction and pays in stopping and sliding.
#### Strong Brakes
- **Effect:** braking +5, output -2.
- **Pro:** stops and reverses 5% faster.
- **Con:** top speed -2%; each brake draws 5% more energy.
- **Increase:** brake 5 times within a minute.
- **Decrease:** no braking for 10 min.
### Mirror mutations (kept for now)
Each core mutation has a mirror that moves the same axes the other way, so lowering a
trait is a real choice with its own benefit. A mirror's triggers are its core
mutation's triggers swapped.
| Mirror | Effect | Pro | Con | Increase | Decrease |
| --- | --- | --- | --- | --- | --- |
| Light Propulsion | output -5, efficiency +2 | Energy per second -7%, per distance -2% | Top speed -5% | No thrust for 30 min | Thrust for 10 s |
| Damped Body | coasting -5 | Stops sooner, slides less | Top speed -5%; energy per distance +5% | No movement for 2 min | Pulsed or steady movement for a minute |
| Overdriven Propulsion | efficiency -5, output +2 | Top speed +2% | Energy per second +7%, per distance +5% | No thrust for 5 min | Movement over half of energy spent |
| Forward Drive | steering -5, output +2 | Top speed +2% | Turns 5% slower | One heading for 60 s of thrust | 5 sharp turns in 20 s |
| Rounded Body | streamlining -5, steering +2 | Turns 2% faster | Top speed -5% | 5 sharp turns in 20 s | Straight thrust for 20 s |
| Light Brakes | braking -5, output +2 | Top speed +2% | Stops 5% slower | No braking for 10 min | Brake 5 times in a minute |
### Limits
Each axis has tunable bounds (trial: 25 to 1,000 points; the genome already caps at
1,000). A mutation that would cross a bound is not eligible. Efficiency divides thrust
cost, so it can never reach 0.
### Postponed
Burst, Anchor, Shed propulsion and Colony propulsion are postponed. They are not in the
pool, not even at the 0.001% floor, until their mechanics exist.
## 6. Feeding and energy mutations
Systems and terms are defined in the
[feeding and energy plan](Cellular_feeding_energy_plan.md). All indices are points with
the founder at 100. All available from birth unless stated.
**Spread pattern:** a channel mutation raises one matter channel by the primary step
(5) and lowers each of the other three matter channels by the spread step (1). The
steps are tunable per mutation.
### Feeding
| Name | Effect | Pro | Con | Increase | Decrease |
| --- | --- | --- | --- | --- | --- |
| Carbon Gatherer | C collection +5, N/P/O collection -1 each | Collects carbon 5% faster | Collects N, P, O 1% slower each | Carbon is at least half the matter collected in the last minute | No carbon collected for 5 min |
| Nitrogen Gatherer | N collection +5, C/P/O -1 each | Collects nitrogen 5% faster | Collects C, P, O 1% slower each | Same, for nitrogen | Same, for nitrogen |
| Phosphorus Gatherer | P collection +5, C/N/O -1 each | Collects phosphorus 5% faster | Collects C, N, O 1% slower each | Same, for phosphorus | Same, for phosphorus |
| Other Matter Gatherer | O collection +5, C/N/P -1 each | Collects other matter 5% faster | Collects C, N, P 1% slower each | Same, for other matter | Same, for other matter |
| Big Appetite | Shared intake limit +5, upkeep efficiency -2 | Takes in 5% more per second at rich food | More upkeep | Feeding at the intake limit for 10 s total | No feeding for 5 min |
| Small Appetite (mirror) | Shared intake limit -5, upkeep efficiency +2 | Less upkeep | Takes in 5% less at rich food | No feeding for 5 min | Feeding at the intake limit for 10 s total |
### Energy
| Name | Effect | Pro | Con | Increase | Decrease |
| --- | --- | --- | --- | --- | --- |
| Thorough Extraction | Energy kept per bubble +5, energy collection -2 | More energy from each energy bubble | Drains energy bubbles 2% slower | Burning matter for energy for 30 s total | No matter burned for 10 min |
| Rapid Extraction | Energy collection +5, energy kept per bubble -2 | Drains energy bubbles 5% faster | Keeps slightly less of each | Energy collection at its limit for 10 s total | No energy collected for 5 min |
| Carbon Metabolism | C burn efficiency +5, N/P/O -1 each | Carbon covers 5% more energy when burned | N, P, O cover 1% less each | Burning carbon for 30 s total | No carbon burned for 10 min |
| Nitrogen Metabolism | N burn efficiency +5, C/P/O -1 each | Nitrogen covers 5% more energy | C, P, O cover 1% less each | Burning nitrogen for 30 s total | No nitrogen burned for 10 min |
| Phosphorus Metabolism | P burn efficiency +5, C/N/O -1 each | Phosphorus covers 5% more energy | C, N, O cover 1% less each | Burning phosphorus for 30 s total | No phosphorus burned for 10 min |
| Other Matter Metabolism | O burn efficiency +5, C/N/P -1 each | Other matter covers 5% more energy | C, N, P cover 1% less each | Burning other matter for 30 s total | No other matter burned for 10 min |
Thorough and Rapid Extraction mirror each other. Energy kept per bubble can never
exceed 100% of the bubble's energy.
### Photosynthesis
Light capture is in points, with acquisition at 100.
| Name | Effect | Pro | Con | Available | Increase | Decrease |
| --- | --- | --- | --- | --- | --- | --- |
| Acquire Photosynthesis | Gain producer tissue at 100, energy collection -2 | Steady energy from light | Tissue adds mass (slower, more upkeep); drains energy bubbles slower | After burning a tunable amount of carbon; not a producer | Burning carbon for 30 s total | Burning other channels for 30 s total |
| Expand Photosynthesis | Light capture +5, energy collection -2 | 5% more energy from light | More tissue mass and upkeep; drains energy bubbles slower | Is a producer | Drifting without thrust for 60 s total | Thrust for 2 min total |
| Reduce Photosynthesis (mirror) | Light capture -5, energy collection +2 | Less tissue, lighter; drains energy bubbles faster | Less energy from light | Is a producer, above the minimum | Thrust for 2 min total | Drifting without thrust for 60 s total |
| Shed Photosynthesis | Remove producer tissue | No producer mass or upkeep | No light energy | Is a producer | Thrust for 5 min total | Drifting without thrust for 60 s total |
Shed Photosynthesis has `base_weight` 25 (others 100), so shedding is rarer than
trimming. A cell that sheds it can be offered Acquire again; the carbon it has already
burned still counts.
## 7. Predation and defense mutations
Systems and terms are defined in the
[predation and defense plan](Cellular_predation_defense_plan.md). All indices are points
with the founder at 100. All available from birth.
| Name | Effect | Pro | Con | Increase | Decrease |
| --- | --- | --- | --- | --- | --- |
| Reinforced Membrane | Membrane +5 | Predators need 5% more mass to engulf you | More membrane mass and upkeep, slower collection, heavier | In contact with a cell over 1.5x your mass for 5 s total | No contact with a larger cell for 10 min |
| Thin Membrane (mirror) | Membrane -5 | Faster collection, less mass and upkeep | Easier to engulf | No contact with a larger cell for 10 min | In contact with a cell over 1.5x your mass for 5 s total |
| Expanding Chamber | Engulf capacity +5, membrane -2 | Can engulf prey 5% bigger | Stretched wall: slightly easier to engulf yourself | 3 failed engulfs because the prey was too large or its membrane too thick | No engulf attempts for 10 min |
| Small Mouth (mirror) | Engulf capacity -5, membrane +2 | Tougher wall | Only smaller prey | No engulf attempts for 10 min | 3 failed engulfs because the prey was too large |
| Rapid Digestion | Kill absorption +5, shared intake -2 | Takes 5% more from a kill straight away, so less is left behind | Slower everyday feeding | A successful engulf | No successful engulf for 15 min |
| Grazer's Gut (mirror) | Kill absorption -5, shared intake +2 | Faster everyday feeding | Takes less from kills | No successful engulf for 15 min | A successful engulf |
Expanding Chamber links offense and defense: a better hunter is slightly easier prey.
Failed-engulf reasons (prey too large, membrane too thick) are already reported by the
server; contact with a larger cell is a new counter.
## 8. Body and maintenance mutations
Systems and terms are defined in the
[body and maintenance plan](Cellular_body_maintenance_plan.md). Indices are points with
the founder at 100; the body recipe is in per thousand. All available from birth.
**Recipe spread:** a thrifty body lowers one channel's share by the recipe step (20 per
thousand) and spreads the same amount evenly across the other three. Tunable per
mutation.
| Name | Effect | Pro | Con | Increase | Decrease |
| --- | --- | --- | --- | --- | --- |
| Larger Body | Size +5 | Harder to engulf, can engulf bigger prey, larger footprint touches more food | More upkeep, costlier buds and regrowth, heavier and slower | Reserve holds more matter than the body for 60 s total | Burning matter for energy for 30 s total |
| Smaller Body (mirror) | Size -5 | Less upkeep, cheaper buds and regrowth, quicker | Easier to engulf, smaller prey only | Burning matter for energy for 30 s total | Reserve holds more matter than the body for 60 s total |
| Carbon-Thrifty Body | Carbon share -20, N/P/O share +20 in total | Building, regrowth and buds need less carbon | Need more N, P and O | Growth or a bud blocked by lack of carbon for 10 s total | Carbon is at least half the matter collected in the last minute |
| Nitrogen-Thrifty Body | Nitrogen share -20, C/P/O share +20 in total | Need less nitrogen | Need more C, P and O | Same, for nitrogen | Same, for nitrogen |
| Phosphorus-Thrifty Body | Phosphorus share -20, C/N/O share +20 in total | Need less phosphorus | Need more C, N and O | Same, for phosphorus | Same, for phosphorus |
| Other-Thrifty Body | Other-matter share -20, C/N/P share +20 in total | Need less other matter | Need more C, N and P | Same, for other matter | Same, for other matter |
| Efficient Upkeep | Upkeep efficiency +5, growth speed -2 | Lower upkeep, never below the essential floor | Regrows 2% slower | Upkeep is over half the energy spent in the last 5 min | Regrowing for 60 s total |
| Rapid Growth | Growth speed +5, upkeep efficiency -2 | Regrows 5% faster after splits | More upkeep | Regrowing for 60 s total | Fully grown for 10 min |
| Dense Tissue | Density +5 | Smaller footprint for the same mass, lighter membrane, less upkeep | Less surface: slower collection, touches less food | In contact with a cell over 1.5x your mass for 5 s total | Feeding by contact for 60 s total |
| Light Tissue (mirror) | Density -5 | Larger surface: faster collection, touches more food | More membrane mass and upkeep, bigger target | Feeding by contact for 60 s total | In contact with a cell over 1.5x your mass for 5 s total |
Thrifty bodies have no performance effect; their value is fitting the region's supply,
and they pair with the Gatherer mutations. Efficient Upkeep and Rapid Growth mirror
each other. Dense Tissue and Reinforced Membrane share an increase trigger: both answer
the same threat.
## 9. Reproduction mutations
Systems and terms are defined in the
[reproduction plan](Cellular_reproduction_plan.md). Bud share is in points with the
founder at 100 (half the parent's body). Only on-demand buds count as reproductions;
mutation splits do not.
### Bud size
| Name | Effect | Pro | Con | Increase | Decrease |
| --- | --- | --- | --- | --- | --- |
| Bigger Buds | Bud share +5 | Buds start 5% larger: harder to engulf, more likely to survive | Each bud costs 5% more from the reserve | One of your buds is engulfed within 2 min of birth | A bud refused for lack of resources |
| Smaller Buds (mirror) | Bud share -5 | Each bud is cheaper | Buds start smaller and more vulnerable | A bud refused for lack of resources | One of your buds is engulfed within 2 min of birth |
### Multiple offspring
**Litter** is a heritable value, founder 0, giving extra offspring per bud:
- Each full 100 litter points is one guaranteed extra offspring; the remainder is the
percentage chance of one more. Litter 150 means one extra, plus a 50% chance of a
second.
- Every offspring of one bud shares the same investment, so more offspring means each
is smaller. The bud costs the same.
- The maximum offspring per bud is tunable (trial 10, so litter up to 900).
- Each extra offspring needs a free spot touching the parent and room under the region
cap. If fewer can be placed, fewer are born; the parent keeps the share of any that
were not.
- This replaces the current 25% twin chance: new founders start at litter 0.
| Name | Effect | Pro | Con | Increase | Decrease |
| --- | --- | --- | --- | --- | --- |
| Twinning | Litter +25 | More offspring per bud | Each offspring starts smaller and more vulnerable | Bud while the reserve covers at least twice the bud's cost | One of your buds is engulfed within 2 min of birth |
| Single Bud (mirror) | Litter -25 | Each offspring starts larger | Fewer offspring per bud | One of your buds is engulfed within 2 min of birth | Bud while the reserve covers at least twice the bud's cost |
Single Bud is not eligible at litter 0. Twinning is not eligible at the maximum.
### Becoming multicellular
| Name | Effect | Pro | Con | Available | Increase | Decrease |
| --- | --- | --- | --- | --- | --- | --- |
| Adhesion | Gain Adhesion | Become a multicellular organism: the path to emerging into the world | Permanent: no more splits, one shared reserve, the whole organism can be engulfed at once, heavier | After a tunable number of on-demand buds (trial 5) | Each on-demand bud | No bud for 15 min |
Adhesion has `base_weight` 50. Accepting it is a split whose offspring expresses
Adhesion and attaches, so the organism forms at once whichever cell the player keeps;
its offer shows Accept and Decline only.
Emerging into the world is a **button**, not a mutation: it appears once the organism
reaches the emergence threshold (reproduction plan, section 7).
## 10. Balance notes
- Economical Propulsion and Streamlined Body raise top speed without raising energy per
second. Their cost and weights must keep them from dominating.
- Big Appetite only matters where a channel's own limit is above the share of the
shared limit it gets; the shared limit and channel limits must be tuned together.
- Thresholds above are first guesses. "Thrust for 10 s" is cumulative and fires each
time 10 s of thrust accrues; "no thrust for 30 min" is continuous.
## 11. Implementation map
| Piece | State today |
| --- | --- |
| Movement arrangement in the genome | Exists (schema 6); not edited by any mutation yet. |
| Handling from the arrangement | Exists: output, efficiency, steering, streamlining, braking, coasting. |
| Step/paired points, interval, option count | Keys exist in `cellular.tuning`; unused by code. |
| Named catalog with pro/con, triggers and cost | New: replaces the 32 generic adjust/acquire/shed operators for new rules. |
| Per-cell affinity scores | New persisted state, inherited at birth (lives format bump). |
| Trigger tracking | New server-side activity counters from per-tick thrust, brake, heading and velocity. |
| Chance allocation and systematic draw | New: replaces the current uniform draw of 3. |
| Per-mutation cost and scale | New tuning keys and funding path; defaults all 0. |
| Reclaimed cost | New: paid channels become seeded random bubbles in the region. |
| Per-mutation `enabled` switch | New tuning key, for narrowing the pool in tests. |
| Per-mutation step sizes | New tuning keys (primary, paired, spread). |
| Feeding and energy genome fields | New: collection index per channel, shared intake, burn efficiency per channel; energy kept per bubble reuses `energy_conversion`. |
| Feeding and energy triggers | New counters: diet share per channel, time at intake limit, matter burned per channel, drifting time. |
| Predation genome fields | New: membrane in points, engulf capacity, kill absorption. |
| Predation triggers | Failed-engulf reasons exist; contact time with larger cells and kill timers are new. |
| Body genome fields | New: size in points, body recipe, upkeep efficiency, density, growth speed. |
| Body triggers | New: growth or bud blocked by a named channel, regrowth time, time fully grown, reserve-to-body ratio. |
| Reproduction genome fields | Bud share exists (reproduction capability, in points is new); litter and Adhesion are new. |
| Multiple offspring per bud | Twin budding exists (shared investment, room check); litter in place of the fixed 25% chance is new. |
| Reproduction triggers | New: on-demand bud count, bud refusals, early deaths of own buds, reserve-to-bud-cost ratio. |
| Offer UI | Shows name, pro, con, cost, shortfall and chance. |
Every new behaviour goes in a new rules version; regions on earlier rules keep their
meaning.
+108
View File
@@ -0,0 +1,108 @@
# Cellular predation and defense plan
Status: planning draft, 2026-10-22. Records the maintainer's decisions on engulfment
and membrane defense. Part of the [Cellular gameplay plan](Cellular_gameplay_plan.md).
Replaces the engulfment sections of [Cellular_feeding_draft.md](Cellular_feeding_draft.md)
and the active parts of [Cellular_defense_draft.md](Cellular_defense_draft.md). No code,
runtime rule or live region is changed by it.
## 1. Who can engulf
Every cell can try to engulf, wildlife included. The player engulfs by targeting a cell
it touches (the existing engulf action); wildlife uses the same action through its
controller. Engulfing is not a capability gained by mutation.
## 2. Eligibility
Engulfment is **instant**: if the attempt is eligible, the prey dies that tick.
```text
predator engulf mass x (predator engulf capacity / 100)
>= prey engulf mass x engulf ratio x (prey membrane points / 100)
```
Engulf capacity is a genome index, founder 100 (section 6).
- **Engulf mass** = body mass + reserve matter x `engulf_reserve_mass_percent`. At 100%
a hoarding cell is both harder to engulf and able to take larger prey; at 0% only
the body counts. Movement always counts all reserve matter; this setting affects
predation only.
- **Engulf ratio:** tunable; trial 1.5 (today's value), so at the founder's membrane a
predator needs 1.5 times the prey's mass.
- **Multicellular organisms** are engulfed whole or not at all, judged on the
organism's total engulf mass.
- Same-tick contests resolve in stable life order, as today.
## 3. What the predator gets
1. The predator absorbs up to its **per-tick collection limit** on each channel,
scaled by its kill absorption index (founder 100), from the prey's body and
reserve. Energy absorbed this way follows the energy-bubble efficiency rule
(feeding and energy plan, section 4a); the rest of it is heat.
2. The **remainder** is split:
- **Half becomes bubbles** at the prey's spot (one per non-empty channel), for the
predator to eat over the next ticks. Other cells and the currents compete for
them.
- **Half goes to the region's spent pool** and seeps back into the region as
random bubbles.
3. The prey's accumulated heat goes to the region's heat owner, as today.
If the region is at its deposit limit, the bubble half goes to the spent pool as well.
Staying to eat the bubbles is a risk: a predator that sits still long enough can
become prey itself.
## 4. Membrane defense
Membrane thickness is stored in **points**, with the founder at 100 (today's 1 µm), so
it can change in 5-point steps like movement.
| Thicker membrane | Thinner membrane |
| --- | --- |
| Harder to engulf (the ratio scales with points) | Easier to engulf |
| More membrane mass, which is upkept twice (exists) | Less mass and upkeep |
| Slower collection on every channel (new) | Faster collection |
| Heavier, so slower to move | Lighter |
The collection penalty is a tunable coefficient. Membrane points have a tunable
minimum (a viable cell wall) and maximum.
## 5. Postponed
Armor, live capture and escape, prey retention, slippery coating, adhesive grip,
defensive expulsion and siphoning wait for a live-capture system. They are not in the
mutation pool.
## 6. Genome indices and mutations
| Index | Founder | Mutations (mutation plan, section 7) |
| --- | --- | --- |
| Membrane points | 100 | Reinforced Membrane, Thin Membrane |
| Engulf capacity: scales the predator's side of the eligibility check | 100 | Expanding Chamber, Small Mouth |
| Kill absorption: scales the per-tick limit during a kill | 100 | Rapid Digestion, Grazer's Gut |
## 7. Tunables
| Setting | Trial |
| --- | --- |
| Engulf ratio | 1.5 |
| `engulf_reserve_mass_percent` | 100% |
| Kill remainder bubble share | 50% (the rest to the spent pool) |
| Membrane collection penalty | To be selected in playtesting |
| Membrane points minimum and maximum | To be selected in playtesting |
## 8. Implementation map
| Piece | State today |
| --- | --- |
| Instant engulfment by contact, in stable order | Exists (rules 3+). |
| Wildlife engulfing | Exists (rules 7+). |
| Engulf mass with tunable reserve share | New; today only body plus reserve as total mass. |
| Membrane in points | New genome representation (whole micrometres today). |
| Kill remainder split between bubbles and spent pool | New; today all of it becomes bubbles. |
| Membrane slowing collection | New. |
| Engulf capacity and kill absorption indices | New genome fields. |
| Whole-organism engulfment | New, with the multicellular organism. |
Every new behaviour goes in a new rules version; regions on earlier rules keep their
meaning.
+211
View File
@@ -0,0 +1,211 @@
# Cellular reproduction plan
Amendment, 2026-10-26: [ADR-0181](docs/adr/0181-cellular-reproduction-safety.md)
adds an opt-in DEV safety revision: controlled-cell split allocation, retained bud
provision and physical offspring separation. Historical declarations retain the
baseline below. All allocation/launch values remain trial tuning.
Status: planning draft, 2026-10-22. Records the maintainer's decisions on the
reproduction revamp. Companion to [Cellular_mutation_plan.md](Cellular_mutation_plan.md).
Where this document conflicts with the earlier drafts or with the unimplemented
proposals in ADR-0135, this document wins. No code, runtime rule or live region is
changed by it.
## 1. Purpose
Today reproduction has no purpose for the player: it costs resources, and the player
watches the offspring swim off, eat and reproduce until it dies.
The goal is one loop:
**gather energy and matter -> evolve and reproduce -> become a multicellular
organism -> break out of the region into the world.**
Reproduction becomes the way a lineage evolves, and the way a multicellular organism
grows.
## 2. Two genomes per cell
Every cell carries two genome references (they already exist from rules 10):
| Genome | Meaning |
| --- | --- |
| **Expressed** | What its own body is built from: its traits, handling, costs. |
| **Heritable plan** | What its offspring are born expressing. |
A newborn starts with both references naming the same genome: it expresses its plan.
## 3. Bud (on demand)
- **Trigger:** the player presses Bud.
- **Requires:** fully grown (`bud_min_growth`), a free spot touching the parent, and
the region below its organism cap.
- **Cost:** the parent's reserve pays the bud's body, the energy to build it and its
starting energy supply, as today. A tunable fee per channel (default 0, with the same
amount-and-scale model as mutation costs) is added on top and reclaimed by the
environment as random bubbles.
- **Offspring:** expresses the parent's heritable plan, so it carries every mutation
held in that plan.
- **Size:** the reproduction capability's share of the parent's body (founder: half),
built from the parent's reserve (body and maintenance plan, section 6).
- **Litter:** a heritable value (founder 0) can give extra offspring per bud, up to a
tunable maximum (trial 10). They share one investment, so each is smaller. See the
mutation plan, section 9.
- **Control:** the player chooses to stay as the parent or become the bud. The cell the
player leaves becomes wildlife. The choice is one way.
This section describes a single cell. A multicellular organism's bud becomes an
internal cell instead (section 6).
## 4. Mutation split
Accepting a mutation divides a single cell. (A multicellular organism expresses an
accepted mutation directly; section 6.)
1. The mutation's cost is paid and reclaimed by the environment (mutation plan,
section 4).
2. The mutation is written into the heritable plan of **both** cells.
3. The cell divides. Body and reserve are split per channel by `split_share` (trial
50%); a rounding remainder stays with the founder. Each half starts at the size its
half of the body covers and regrows by feeding (body and maintenance plan,
section 5).
4. The **offspring expresses the mutation**. The **founder does not**: its body is
unchanged, but its plan now carries the mutation.
5. The player chooses which cell to continue as. The other becomes wildlife. (When the
mutation is Adhesion, the two stay attached instead; section 6.)
The control choice is made in the offer itself: each option has **Stay as founder**
and **Become offspring**. Nothing waits on a decision window after the birth.
| Choice | The player controls | The other cell |
| --- | --- | --- |
| Stay as founder | The unchanged body, with half the resources. Every later bud expresses the mutation. | The mutated offspring becomes wildlife: the player watches how the mutation does. |
| Become offspring | The mutated body, with half the resources, not starting from nothing. | The founder becomes wildlife with an unchanged body; its own buds are mutated. |
Consequences:
- A player who always stays as the founder accumulates mutations in their plan, but
their own body never changes. To live in a mutated body, the player must at some
point become an offspring.
- If a mutation changes how much matter the body needs, the offspring funds the
difference from its half. If it cannot, the split is refused and nothing is spent.
- Both cells inherit the founder's affinity scores.
### When a split is not possible
A split needs a minimum growth (`split_min_growth`, trial: fully grown), a free spot
touching the founder, and the region below its organism cap. If any is missing, the
option shows why and cannot be chosen; the offer stays pending until the split is
possible or the player declines.
## 5. The cell the player leaves
It becomes autonomous wildlife, as today: it feeds, buds from its own heritable plan
and dies. Wildlife earns no mutation offers.
## 6. Becoming multicellular
### The transition
- **Adhesion** is a mutation, offered after a tunable number of on-demand buds (trial
5; mutation splits do not count). A newborn that expresses Adhesion stays attached to
its parent.
- The moment a newborn attaches, the parent and newborn become **one multicellular
organism**. There is no separate colony stage.
- Accepting Adhesion is a mutation split (section 4) whose offspring expresses
Adhesion, so it attaches at once: the organism forms immediately, whichever cell the
player would have kept. The offer shows Accept and Decline only.
- The organism expresses **one genome**: the founder's heritable plan at the moment of
attachment, which now includes Adhesion. Mutations the founder held in its plan
become expressed for the whole organism. Any tissue that change requires is funded
from the combined reserve; if it cannot be funded, the split is refused and nothing
is spent.
- A member can never be detached.
### Life as a multicellular organism
- **One reserve:** every member's reserve combines into the organism's reserve.
- **Mutations affect the whole organism.** Accepting one does not split anything; it is
expressed by the organism directly, paid from the organism's reserve, and changed
tissue is funded from it. The offer shows only Accept or Decline; there is no
Stay / Become choice.
- **Budding adds an internal cell.** The bud's body is built from the organism's
reserve and becomes part of the organism. It counts toward the emergence threshold.
- **The goal changes:** the organism gathers mass and energy to emerge into the world.
- **Region cap:** a multicellular organism counts once toward the region's organism
cap, however many members it has.
- **Mass drives movement and energy.** Every member adds to the organism's mass.
Heavier organisms accelerate and turn more slowly for the same thrust, and movement
energy rises with total mass, reserve matter included. Upkeep rises with body mass
only (feeding and energy plan, section 4). The coefficients are tuned in
playtesting.
### Wildlife organisms
Because Adhesion always forms the organism at once with the player's cell, and an
organism never releases a cell, wildlife cannot currently become multicellular. As a
safeguard, a wildlife organism **cannot emerge**: it stops budding one member short of
the emergence member threshold. Wildlife earns no mutation offers.
### Death
The organism lives and dies as one body.
- **Starvation:** with one reserve, members cannot starve individually. The organism
starves when its reserve cannot pay its maintenance, and the whole organism dies.
- **Engulfment:** a predator engulfs the whole organism or none of it, judged on the
organism's total mass.
- **On death:** every member becomes a corpse and its matter returns to the region as
food, as deaths do today.
This replaces the earlier rule that a dead member is recycled to the colony: with a
combined reserve, a member cannot die on its own.
## 7. Emergence
When the organism reaches the emergence threshold, an **Emerge** button appears. It is
not a mutation and is not drawn in offers. Pressing it leaves the region and enters the
world as ADR-0177 describes: the matter is a recorded export, and the organism arrives
at a world-scaled value at a location chosen near its preferred temperature and
nutrients. Individual or bulk emergence
follows ADR-0177.
The threshold is tunable: member count, total mass and reserve energy.
## 8. Tunables
| Setting | Trial |
| --- | --- |
| `bud_min_growth` | 1000 per thousand (fully grown) |
| `bud_fee` per channel, `bud_fee_scale_percent` | 0, 0 |
| `split_min_growth` | 1000 per thousand |
| `split_share` | 50% |
| Emergence threshold: members, total mass, reserve energy | To be selected in playtesting |
| Wildlife member limit | Emergence member threshold minus 1 |
| Mass coefficients for acceleration, turning, movement and maintenance energy | To be selected in playtesting |
## 9. Open questions
None. Organism size, drag and feeding contact by member count are tuned with the mass
coefficients above.
## 10. Implementation map
| Piece | State today |
| --- | --- |
| Expressed genome and heritable plan per cell | Exists (lives format 8, rules 10-12). |
| Bud funding with a different offspring genome | Exists (`fund_offspring`, ADR-0164). |
| Funding a mutation at the current growth | Exists (`fund_mutation_at_growth`, ADR-0157). |
| Funded regrowth after a split | Exists (funded maturation, rules 9). |
| Choosing parent or child at birth | Accepted direction (ADR-0163); not built. |
| On-demand bud with a control choice and a fee | New. |
| Mutation split: even division of body and reserve | New transition; not the bud bill. |
| Offer options with Stay / Become | New wire and UI. |
| Adhesion and the multicellular transition | New. |
| Multicellular organism: one genome, one reserve, internal buds | New. |
| Mass-scaled handling and energy for the organism | Partial: movement and maintenance energy already scale with a cell's body mass; reserve mass in movement and organism-level handling are new. |
| Wildlife member limit below the emergence threshold | New safeguard. |
| Emergence | Accepted direction (ADR-0177); not built. |
Every new behaviour goes in a new rules version; regions on earlier rules keep their
meaning.
+261
View File
@@ -0,0 +1,261 @@
// ADR-0182 read-only admin API and portal host for one world (DEV).
//
// evo-admin-api --listen ADDRESS:PORT --world N --jwks JSON --oidc-issuer URL
// --audience NAME --client NAME --role NAME --assets DIR
// --pg-passfile F --pg-service F [--region REGION=HOST:PORT ...] [--baseline-tuning F]
// [--region-tuning F] [--deploy-config DIR]
//
// --assets holds the portal's index.html, app.js and style.css. Each --region names a
// region's operations address, whose /admin/view the portal may show; those regions adopt
// tuning revisions. --baseline-tuning is the revamp tuning file they opened with, shown
// until the first revision; --region-tuning the region tuning file they start with, shown
// read only. --deploy-config is the mounted Secret holding the Gitea and Argo CD settings and
// tokens (one file per key) that let the portal open a region (ADR-0182 section 15); without
// it, or with a key missing, that feature stays off. No token is printed.
#include "evo/persistence/postgres.hpp"
#include "evo/server/admin/admin_api.hpp"
#include <algorithm>
#include <charconv>
#include <chrono>
#include <csignal>
#include <cstdio>
#include <fstream>
#include <iterator>
#include <map>
#include <optional>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
namespace {
using namespace evo;
using namespace std::chrono_literals;
volatile std::sig_atomic_t stop_requested = 0;
void on_stop(int) {
stop_requested = 1;
}
struct Options {
std::string listen, jwks, oidc_issuer, audience, client, role, assets, baseline_tuning,
region_tuning, deploy_config;
std::uint64_t world{};
std::map<std::uint64_t, std::string> regions; // Region to its operations address.
persistence::PgOptions pg;
};
std::optional<std::uint64_t> number(std::string_view text) {
std::uint64_t value{};
const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), value);
if (error != std::errc{} || end != text.data() + text.size())
return std::nullopt;
return value;
}
std::optional<Options> parse(int argc, char** argv) {
Options o;
std::string pg_service, pg_passfile;
for (int i = 1; i + 1 < argc; i += 2) {
const std::string_view flag = argv[i];
const std::string_view value = argv[i + 1];
const auto n = number(value);
if (flag == "--listen")
o.listen = value;
else if (flag == "--world" && n && *n > 0)
o.world = *n;
else if (flag == "--jwks")
o.jwks = value;
else if (flag == "--oidc-issuer")
o.oidc_issuer = value;
else if (flag == "--audience")
o.audience = value;
else if (flag == "--client")
o.client = value;
else if (flag == "--role")
o.role = value;
else if (flag == "--assets")
o.assets = value;
else if (flag == "--baseline-tuning")
o.baseline_tuning = value;
else if (flag == "--region-tuning")
o.region_tuning = value;
else if (flag == "--deploy-config")
o.deploy_config = value;
else if (flag == "--pg-service")
pg_service = value;
else if (flag == "--pg-passfile")
pg_passfile = value;
else if (flag == "--region") {
const auto equals = value.find('=');
const auto region =
equals == std::string_view::npos ? std::nullopt : number(value.substr(0, equals));
const auto address =
equals == std::string_view::npos ? std::string_view{} : value.substr(equals + 1);
if (!region || *region == 0 || address.empty() || address.size() > 128 ||
!o.regions.emplace(*region, std::string(address)).second)
return std::nullopt;
} else
return std::nullopt;
}
// Names are embedded in the portal's JSON settings: printable ASCII without quotes.
const auto plain = [](std::string_view text) {
return !text.empty() && text.size() <= 256 && std::ranges::all_of(text, [](char ch) {
return ch > ' ' && ch <= '~' && ch != '"' && ch != '\\';
});
};
if (argc % 2 != 1 || o.listen.empty() || o.world == 0 || o.jwks.empty() ||
!plain(o.oidc_issuer) || !o.oidc_issuer.starts_with("https://") || !plain(o.audience) ||
!plain(o.client) || !plain(o.role) || o.assets.empty() || pg_service.empty() ||
pg_passfile.empty())
return std::nullopt;
auto service = persistence::read_pg_service(pg_service, "evolution");
if (!service)
return std::nullopt;
o.pg = *service;
o.pg.password_file = pg_passfile;
return o;
}
std::optional<std::string> read_file(const std::string& path) {
std::ifstream file{path, std::ios::binary};
if (!file)
return std::nullopt;
std::string body{std::istreambuf_iterator<char>{file}, std::istreambuf_iterator<char>{}};
if (body.empty() || body.size() > (std::size_t{1} << 20U))
return std::nullopt;
return body;
}
std::uint64_t wall_seconds() {
return static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch())
.count());
}
} // namespace
int main(int argc, char** argv) {
const auto options = parse(argc, argv);
if (!options) {
std::fputs("usage: evo-admin-api (see apps/evo-admin-api/main.cpp)\n", stderr);
return 2;
}
std::signal(SIGTERM, on_stop);
std::signal(SIGINT, on_stop);
std::signal(SIGPIPE, SIG_IGN);
auto verifier = server::broker::TokenVerifier::from_jwks(
options->jwks,
{options->oidc_issuer, options->audience, options->client, 30, options->role});
if (!verifier) {
std::puts("error jwks");
return 2;
}
std::vector<server::admin::AdminAsset> assets;
for (const auto& [name, type] : {std::pair{"index.html", "text/html; charset=utf-8"},
std::pair{"app.js", "text/javascript; charset=utf-8"},
std::pair{"style.css", "text/css; charset=utf-8"}}) {
auto body = read_file(options->assets + "/" + name);
if (!body) {
std::printf("error assets %s\n", name);
return 2;
}
assets.push_back({std::string("/") + name, type, std::move(*body)});
}
// The realm's origin: sign-in redirects there and the portal exchanges tokens with it.
const auto origin_end = options->oidc_issuer.find('/', std::string_view{"https://"}.size());
const auto origin = options->oidc_issuer.substr(0, origin_end);
server::admin::AdminConfig config;
config.world = options->world;
for (const auto& [region, address] : options->regions)
config.view_regions.push_back(region);
if (!options->baseline_tuning.empty()) {
auto baseline = read_file(options->baseline_tuning);
if (!baseline) {
std::puts("error baseline-tuning");
return 2;
}
config.baseline_tuning = std::move(*baseline);
}
if (!options->region_tuning.empty()) {
auto region = read_file(options->region_tuning);
if (!region) {
std::puts("error region-tuning");
return 2;
}
config.region_tuning = std::move(*region);
}
config.portal_config_json = "{\"issuer\":\"" + options->oidc_issuer + "\",\"client_id\":\"" +
options->client + "\",\"world\":" + std::to_string(options->world) +
"}\n";
config.content_security_policy =
"default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; "
"connect-src 'self' " +
origin + "; form-action 'self' " + origin + "; frame-ancestors 'none'; base-uri 'none'";
auto listening = server::OpsServer::listen(options->listen,
server::OpsServer::max_configurable_response_bytes);
if (!listening) {
std::puts("error listen");
return 2;
}
const auto pg = options->pg;
const auto regions = options->regions;
server::admin::AdminApi api{std::move(config), std::move(*verifier),
[pg]() -> std::unique_ptr<persistence::Postgres> {
auto db = persistence::Postgres::connect(pg, 3s);
return db ? std::move(*db) : nullptr;
},
[regions](std::uint64_t region) -> std::optional<std::string> {
const auto found = regions.find(region);
if (found == regions.end())
return std::nullopt;
return server::admin::http_get(
found->second, "/admin/view", 1500ms,
server::OpsServer::max_configurable_response_bytes);
},
std::move(assets)};
// ADR-0182 section 15: the portal opens regions only when every deploy key is present.
if (!options->deploy_config.empty()) {
const auto key = [&](const char* name) {
auto text = read_file(options->deploy_config + "/" + name).value_or("");
while (!text.empty() &&
(text.back() == '\n' || text.back() == '\r' || text.back() == ' '))
text.pop_back();
return text;
};
server::admin::AdminDeployConfig deploy{.gitea_base = key("GITEA_BASE_URL"),
.gitea_repository = key("GITEA_REPOSITORY"),
.gitea_token = key("GITEA_TOKEN"),
.branch = "main",
.argo_server = key("ARGOCD_SERVER"),
.argo_application = key("ARGOCD_APPLICATION"),
.argo_token = key("ARGOCD_TOKEN"),
.argo_verify = key("ARGOCD_TLS_VERIFY") != "false"};
if (deploy.gitea_base.empty() || deploy.gitea_repository.empty() ||
deploy.gitea_token.empty() || deploy.argo_server.empty() ||
deploy.argo_application.empty() || deploy.argo_token.empty()) {
std::puts("deploy disabled (incomplete configuration)");
} else {
std::printf("deploy enabled repository %s application %s argo-verify %s\n",
deploy.gitea_repository.c_str(), deploy.argo_application.c_str(),
deploy.argo_verify ? "yes" : "no");
api.enable_deploy(std::move(deploy), server::admin::https_request);
}
}
std::printf("admin api listening %u world %llu\n", static_cast<unsigned>((*listening)->port()),
static_cast<unsigned long long>(options->world));
std::fflush(stdout);
while (stop_requested == 0) {
(*listening)
->serve_api(
[&](const server::ApiRequest& request) {
return api.handle(request, wall_seconds(), std::chrono::steady_clock::now());
},
server::OpsServer::max_api_body_bytes); // Tuning texts (ADR-0182 section 13).
std::this_thread::sleep_for(5ms);
}
std::puts("admin api stopped");
return 0;
}
File diff suppressed because it is too large Load Diff
+37
View File
@@ -0,0 +1,37 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>AEvolution Admin</title>
<link rel="stylesheet" href="/style.css">
<script type="module" src="/app.js"></script>
</head>
<body>
<header class="bar">
<a class="brand" href="#/accounts">AEvolution <span>admin</span></a>
<nav class="sections" aria-label="Sections">
<div class="section">
<span class="section-name">Cellular</span>
<a href="#/accounts" data-route="accounts">Accounts</a>
<a href="#/regions" data-route="regions">Regions</a>
<a href="#/tuning" data-route="tuning">Tuning</a>
</div>
</nav>
<div class="who">
<span id="env" class="env" hidden></span>
<div class="theme-switch" role="group" aria-label="Theme">
<button type="button" data-theme-choice="system" title="Follow the system">Auto</button>
<button type="button" data-theme-choice="light" title="Light">&#9728;</button>
<button type="button" data-theme-choice="dark" title="Dark">&#9790;</button>
</div>
<span id="who" class="muted small"></span>
<button id="sign-out" class="ghost" hidden>Sign out</button>
</div>
</header>
<main id="main" tabindex="-1">
<p class="muted">Loading…</p>
</main>
</body>
</html>
+625
View File
@@ -0,0 +1,625 @@
/* ADR-0182 admin portal. Tokens first: light by default, dark from the system or the header's
theme switch (html[data-theme]). The region map reads the map tokens when it paints. */
:root {
--bg: #f3f5f8;
--panel: #ffffff;
--panel-2: #f6f8fa;
--panel-3: #eef1f5;
--line: #e1e6ec;
--line-strong: #cfd6de;
--text: #17202a;
--muted: #5f6c79;
--faint: #8b96a2;
--accent: #2563eb;
--accent-soft: rgba(37, 99, 235, 0.1);
--on-accent: #ffffff;
--good: #15925f;
--good-soft: rgba(21, 146, 95, 0.1);
--warn: #b7791f;
--warn-soft: rgba(183, 121, 31, 0.12);
--bad: #d64545;
--bad-soft: rgba(214, 69, 69, 0.1);
--shadow: 0 1px 2px rgba(16, 24, 40, 0.05), 0 1px 3px rgba(16, 24, 40, 0.06);
--shadow-pop: 0 8px 24px rgba(16, 24, 40, 0.14);
/* Region map. */
--map-bg: #fbfcfd;
--map-grid: rgba(23, 32, 42, 0.05);
--map-edge: #cfd6de;
--map-glass: rgba(255, 255, 255, 0.86);
--player: #2f6fed;
--online: #06b6d4;
--wildlife: #16a34a;
--pool: rgba(37, 99, 235, 0.1);
--pool-edge: rgba(37, 99, 235, 0.45);
--patch: rgba(120, 90, 40, 0.14);
--select: #f59e0b;
--energy: #eab308;
--carbon: #4b5563;
--nitrogen: #8b5cf6;
--phosphorus: #f97316;
--other: #ec4899;
--radius: 10px;
--radius-sm: 7px;
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
color-scheme: light;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--bg: #0b0f14;
--panel: #121820;
--panel-2: #161e27;
--panel-3: #1c2531;
--line: #232d3a;
--line-strong: #2f3b4b;
--text: #e4eaf0;
--muted: #8d9aa8;
--faint: #64717f;
--accent: #5b9dff;
--accent-soft: rgba(91, 157, 255, 0.14);
--on-accent: #06101f;
--good: #3ecf8e;
--good-soft: rgba(62, 207, 142, 0.12);
--warn: #f2b84b;
--warn-soft: rgba(242, 184, 75, 0.13);
--bad: #ff6b6b;
--bad-soft: rgba(255, 107, 107, 0.12);
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4);
--shadow-pop: 0 10px 30px rgba(0, 0, 0, 0.55);
--map-bg: #070b10;
--map-grid: rgba(140, 170, 200, 0.06);
--map-edge: #2a3646;
--map-glass: rgba(18, 24, 32, 0.86);
--player: #5b9dff;
--online: #5ff2ff;
--wildlife: #3ecf8e;
--pool: rgba(91, 157, 255, 0.12);
--pool-edge: rgba(91, 157, 255, 0.5);
--patch: rgba(200, 160, 90, 0.14);
--select: #ffd166;
--energy: #ffd84d;
--carbon: #a3adb8;
--nitrogen: #a78bfa;
--phosphorus: #ff9a3c;
--other: #ff6fb5;
color-scheme: dark;
}
}
:root[data-theme="dark"] {
--bg: #0b0f14;
--panel: #121820;
--panel-2: #161e27;
--panel-3: #1c2531;
--line: #232d3a;
--line-strong: #2f3b4b;
--text: #e4eaf0;
--muted: #8d9aa8;
--faint: #64717f;
--accent: #5b9dff;
--accent-soft: rgba(91, 157, 255, 0.14);
--on-accent: #06101f;
--good: #3ecf8e;
--good-soft: rgba(62, 207, 142, 0.12);
--warn: #f2b84b;
--warn-soft: rgba(242, 184, 75, 0.13);
--bad: #ff6b6b;
--bad-soft: rgba(255, 107, 107, 0.12);
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4);
--shadow-pop: 0 10px 30px rgba(0, 0, 0, 0.55);
--map-bg: #070b10;
--map-grid: rgba(140, 170, 200, 0.06);
--map-edge: #2a3646;
--map-glass: rgba(18, 24, 32, 0.86);
--player: #5b9dff;
--online: #5ff2ff;
--wildlife: #3ecf8e;
--pool: rgba(91, 157, 255, 0.12);
--pool-edge: rgba(91, 157, 255, 0.5);
--patch: rgba(200, 160, 90, 0.14);
--select: #ffd166;
--energy: #ffd84d;
--carbon: #a3adb8;
--nitrogen: #a78bfa;
--phosphorus: #ff9a3c;
--other: #ff6fb5;
color-scheme: dark;
}
/* ---------- Base ---------- */
* { box-sizing: border-box; }
[hidden] { display: none !important; }
html, body { margin: 0; }
body {
background: var(--bg);
color: var(--text);
font: 14px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
-webkit-font-smoothing: antialiased;
}
a { color: var(--accent); text-decoration: none; }
a:hover { text-decoration: underline; }
h1 { font-size: 22px; font-weight: 650; letter-spacing: -0.01em; margin: 0; }
h2 { font-size: 15px; font-weight: 600; margin: 0 0 10px; }
h3 { font-size: 13px; font-weight: 600; margin: 0; }
.muted { color: var(--muted); }
.faint { color: var(--faint); }
.mono { font-family: var(--mono); font-size: 12.5px; }
.num { font-variant-numeric: tabular-nums; }
.error { color: var(--bad); }
.good { color: var(--good); }
.small { font-size: 12px; }
.center { display: grid; place-items: center; min-height: 55vh; text-align: center; }
.center h1 { margin-bottom: 6px; }
.center .muted { margin-bottom: 18px; }
button {
font: inherit;
font-weight: 500;
color: var(--text);
background: var(--panel);
border: 1px solid var(--line-strong);
border-radius: var(--radius-sm);
padding: 6px 13px;
cursor: pointer;
transition: background 0.12s, border-color 0.12s, color 0.12s;
white-space: nowrap;
}
button:hover { border-color: var(--accent); color: var(--accent); }
button:disabled { opacity: 0.5; cursor: default; }
button:disabled:hover { border-color: var(--line-strong); color: var(--text); }
button.primary { background: var(--accent); border-color: var(--accent); color: var(--on-accent); }
button.primary:hover { filter: brightness(1.08); color: var(--on-accent); }
button.ghost { background: transparent; border-color: transparent; color: var(--muted); }
button.ghost:hover { background: var(--panel-3); color: var(--text); }
button.danger { color: var(--bad); border-color: color-mix(in srgb, var(--bad) 45%, transparent); }
button.danger:hover { background: var(--bad-soft); border-color: var(--bad); }
button.icon { padding: 5px 9px; line-height: 1; }
:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
input[type="search"], input[type="text"], input[type="number"], select {
font: inherit;
color: var(--text);
background: var(--panel);
border: 1px solid var(--line-strong);
border-radius: var(--radius-sm);
padding: 6px 10px;
min-width: 0;
}
input:focus, select:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); }
input[type="search"] { width: 280px; }
input[type="checkbox"] { accent-color: var(--accent); }
/* ---------- Top bar ---------- */
.bar {
display: flex;
align-items: center;
gap: 28px;
height: 56px;
padding: 0 22px;
background: color-mix(in srgb, var(--panel) 88%, transparent);
backdrop-filter: saturate(1.4) blur(10px);
border-bottom: 1px solid var(--line);
position: sticky;
top: 0;
z-index: 10;
}
.brand { display: flex; align-items: center; gap: 9px; font-weight: 700; color: var(--text); letter-spacing: 0.01em; }
.brand:hover { text-decoration: none; }
.brand::before {
content: "";
width: 18px;
height: 18px;
border-radius: 50%;
background: radial-gradient(circle at 35% 35%, var(--online), var(--player) 55%, var(--wildlife));
box-shadow: 0 0 12px color-mix(in srgb, var(--online) 45%, transparent);
}
.brand span { color: var(--muted); font-weight: 500; }
.sections { display: flex; gap: 20px; flex: 1; }
.section { display: flex; align-items: center; gap: 2px; }
.section-name {
text-transform: uppercase;
font-size: 10.5px;
font-weight: 600;
letter-spacing: 0.1em;
color: var(--faint);
margin-right: 10px;
}
.section a { padding: 6px 12px; border-radius: var(--radius-sm); color: var(--muted); font-weight: 500; }
.section a:hover { color: var(--text); background: var(--panel-3); text-decoration: none; }
.section a.active { background: var(--accent-soft); color: var(--accent); }
.who { display: flex; align-items: center; gap: 12px; }
.env {
font-size: 11px;
font-weight: 600;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--warn);
background: var(--warn-soft);
border-radius: 999px;
padding: 2px 9px;
}
.theme-switch { display: flex; background: var(--panel-3); border-radius: 999px; padding: 2px; }
.theme-switch button {
border: 0;
background: transparent;
color: var(--muted);
border-radius: 999px;
padding: 3px 9px;
font-size: 13px;
line-height: 1.3;
}
.theme-switch button:hover { color: var(--text); }
.theme-switch button.on { background: var(--panel); color: var(--text); box-shadow: var(--shadow); }
/* ---------- Page ---------- */
main { padding: 22px 24px 40px; max-width: 1760px; margin: 0 auto; }
main:focus { outline: none; }
.head { display: flex; align-items: flex-end; justify-content: space-between; gap: 14px; flex-wrap: wrap; margin-bottom: 18px; }
.head .crumb { display: inline-block; font-size: 12.5px; margin-bottom: 4px; color: var(--muted); }
.head .crumb:hover { color: var(--accent); }
.title-row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.tools { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
.subtitle { color: var(--muted); margin-top: 3px; }
.card {
background: var(--panel);
border: 1px solid var(--line);
border-radius: var(--radius);
padding: 16px 18px;
box-shadow: var(--shadow);
}
.card + .card { margin-top: 14px; }
.card-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 12px; }
.card-head h2 { margin: 0; }
.stats, .kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 12px; margin-bottom: 18px; }
.stat, .kpi {
background: var(--panel);
border: 1px solid var(--line);
border-radius: var(--radius);
padding: 12px 14px;
box-shadow: var(--shadow);
min-width: 0;
}
.stat .label, .kpi .label {
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.07em;
color: var(--muted);
display: flex;
align-items: center;
gap: 6px;
}
.stat .value, .kpi .value { font-size: 21px; font-weight: 650; margin-top: 4px; font-variant-numeric: tabular-nums; letter-spacing: -0.01em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.stat .value small { font-size: 12px; font-weight: 400; color: var(--muted); }
.kpi .sub { font-size: 12px; color: var(--muted); margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.kpi.warn { border-color: color-mix(in srgb, var(--warn) 55%, var(--line)); }
.kpi.warn .value { color: var(--warn); }
.kpi.bad { border-color: color-mix(in srgb, var(--bad) 55%, var(--line)); }
.kpi.bad .value { color: var(--bad); }
.kpi .meter { margin-top: 8px; }
.meter { height: 5px; border-radius: 999px; background: var(--panel-3); overflow: hidden; }
.meter > span { display: block; height: 100%; background: var(--accent); border-radius: 999px; }
.meter.warn > span { background: var(--warn); }
.meter.bad > span { background: var(--bad); }
.meter.smooth > span { transition: width 0.25s linear; }
/* ---------- Tables ---------- */
.table-wrap { overflow-x: auto; border: 1px solid var(--line); border-radius: var(--radius); box-shadow: var(--shadow); background: var(--panel); }
table { border-collapse: collapse; width: 100%; background: var(--panel); }
th, td { text-align: left; padding: 9px 12px; border-bottom: 1px solid var(--line); white-space: nowrap; }
tbody tr:last-child td { border-bottom: 0; }
th { font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); background: var(--panel-2); cursor: pointer; user-select: none; }
th.sorted { color: var(--text); }
th.sorted::after { content: " ▾"; }
th.sorted.up::after { content: " ▴"; }
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
tbody tr:hover { background: var(--panel-2); }
tbody tr.clickable { cursor: pointer; }
table.compact { font-size: 12.5px; background: transparent; }
table.compact td { padding: 6px 4px; white-space: normal; vertical-align: top; }
table.compact tr:hover { background: transparent; }
.badge {
display: inline-flex;
align-items: center;
gap: 5px;
font-size: 11.5px;
font-weight: 500;
padding: 1px 9px;
border-radius: 999px;
background: var(--panel-3);
color: var(--muted);
white-space: nowrap;
}
.badge.alive { color: var(--good); background: var(--good-soft); }
.badge.dead { color: var(--bad); background: var(--bad-soft); }
.badge.online { color: var(--accent); background: var(--accent-soft); }
.badge.warn { color: var(--warn); background: var(--warn-soft); }
.badge .dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; }
.badge .dot.pulse { animation: pulse 1.6s ease-in-out infinite; }
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.3; } }
dl.facts { display: grid; grid-template-columns: max-content 1fr; gap: 7px 18px; margin: 0; }
dl.facts dt { color: var(--muted); }
dl.facts dd { margin: 0; min-width: 0; overflow-wrap: anywhere; }
.window-controls { display: flex; gap: 8px; margin: 12px 0 8px; flex-wrap: wrap; }
/* ---------- Region page ---------- */
.region-grid { display: grid; grid-template-columns: minmax(0, 1fr) clamp(420px, 30vw, 560px); gap: 16px; align-items: start; }
@media (max-width: 1150px) { .region-grid { grid-template-columns: minmax(0, 1fr); } }
.map-card {
display: flex;
flex-direction: column;
height: max(560px, calc(100vh - 250px));
border: 1px solid var(--line);
border-radius: var(--radius);
background: var(--panel);
overflow: hidden;
box-shadow: var(--shadow);
}
.map-toolbar { display: flex; align-items: flex-start; gap: 12px; padding: 10px 12px; border-bottom: 1px solid var(--line); }
.map-stage { position: relative; flex: 1; min-height: 0; background: var(--map-bg); overflow: hidden; }
.map-stage canvas { position: absolute; inset: 0; display: block; width: 100%; height: 100%; cursor: crosshair; }
.map-stage canvas.dragging { cursor: grabbing; }
.glass {
background: var(--map-glass);
border: 1px solid var(--line);
border-radius: var(--radius-sm);
box-shadow: var(--shadow);
}
.map-layers { flex: 1; display: flex; flex-wrap: wrap; gap: 6px; }
.chip {
display: inline-flex;
background: var(--panel-2);
border: 1px solid var(--line);
align-items: center;
gap: 7px;
font-size: 12.5px;
font-weight: 500;
padding: 4px 10px 4px 8px;
border-radius: 999px;
color: var(--text);
cursor: pointer;
user-select: none;
}
.chip .count { color: var(--muted); font-variant-numeric: tabular-nums; }
.chip.off { opacity: 0.45; }
.chip.off .swatch { background: transparent !important; }
.chip:hover { border-color: var(--accent); }
.map-zoom { display: flex; overflow: hidden; flex: none; border: 1px solid var(--line-strong); border-radius: var(--radius-sm); }
.map-zoom button { border: 0; border-radius: 0; background: transparent; padding: 5px 11px; font-size: 15px; line-height: 1.2; }
.map-zoom button + button { border-left: 1px solid var(--line); }
.map-zoom button:hover { background: var(--panel-3); }
.map-foot { position: absolute; left: 12px; right: 12px; bottom: 10px; display: flex; justify-content: space-between; align-items: flex-end; gap: 10px; pointer-events: none; }
.map-hint { font-size: 12px; color: var(--muted); padding: 3px 9px; }
.mark-bar { position: absolute; left: 12px; top: 12px; display: flex; align-items: center; gap: 8px; padding: 6px 8px 6px 12px; font-size: 13px; font-weight: 500; }
.mark-bar button { padding: 3px 10px; }
.scale { font-size: 11.5px; color: var(--muted); padding: 4px 9px 3px; text-align: center; }
.scale .rule { height: 6px; border: 1.5px solid var(--muted); border-top: 0; margin-top: 2px; }
.map-banner {
position: absolute;
left: 50%;
top: 12px;
transform: translateX(-50%);
padding: 6px 14px;
font-size: 12.5px;
color: var(--warn);
border-color: color-mix(in srgb, var(--warn) 50%, var(--line));
}
.tooltip {
position: absolute;
pointer-events: none;
padding: 8px 10px;
font-size: 12px;
min-width: 170px;
max-width: 290px;
z-index: 3;
box-shadow: var(--shadow-pop);
}
.tooltip .tip-title { font-weight: 600; margin-bottom: 4px; display: flex; align-items: center; gap: 6px; }
.tooltip .tip-row { display: flex; justify-content: space-between; gap: 14px; }
.tooltip .tip-row span:first-child { color: var(--muted); }
.swatch { width: 10px; height: 10px; border-radius: 50%; flex: none; display: inline-block; }
.swatch.player { background: var(--player); }
.swatch.online { background: var(--online); }
.swatch.wildlife { background: var(--wildlife); }
.swatch.pool { background: var(--pool); border: 1.5px solid var(--pool-edge); }
.swatch.patch { background: var(--patch); border: 1.5px solid var(--faint); border-radius: 2px; }
.swatch.energy { background: var(--energy); }
.swatch.carbon { background: var(--carbon); }
.swatch.nitrogen { background: var(--nitrogen); }
.swatch.phosphorus { background: var(--phosphorus); }
.swatch.other { background: var(--other); }
/* Side panel with tabs. */
.panel {
position: sticky;
top: 72px;
max-height: calc(100vh - 88px);
display: flex;
flex-direction: column;
background: var(--panel);
border: 1px solid var(--line);
border-radius: var(--radius);
box-shadow: var(--shadow);
overflow: hidden;
}
@media (max-width: 1150px) { .panel { position: static; max-height: none; } }
.tabs { flex: none; display: flex; gap: 2px; padding: 8px 8px 0; border-bottom: 1px solid var(--line); background: var(--panel-2); overflow-x: auto; overflow-y: hidden; }
.tabs button {
border: 0;
border-radius: var(--radius-sm) var(--radius-sm) 0 0;
background: transparent;
color: var(--muted);
padding: 8px 12px 9px;
font-size: 13px;
border-bottom: 2px solid transparent;
margin-bottom: -1px;
}
.tabs button:hover { color: var(--text); background: transparent; }
.tabs button.on { color: var(--accent); border-bottom-color: var(--accent); background: var(--panel); }
.tabs .tab-badge { margin-left: 6px; font-size: 10.5px; padding: 0 6px; border-radius: 999px; background: var(--warn-soft); color: var(--warn); }
.panel-body { overflow-y: auto; padding: 4px 18px 18px; flex: 1; }
.block { padding: 16px 0; border-bottom: 1px solid var(--line); }
.block:last-child { border-bottom: 0; }
.block-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 10px; }
.block-head .muted { font-size: 12px; }
.hint { font-size: 12.5px; color: var(--muted); margin: 0 0 10px; }
.empty { text-align: center; color: var(--muted); padding: 26px 10px; }
.empty .big { font-size: 26px; margin-bottom: 6px; opacity: 0.6; }
/* Forms. */
.field-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; }
.field { display: flex; flex-direction: column; gap: 3px; min-width: 0; }
.field label { font-size: 11.5px; color: var(--muted); display: flex; align-items: center; gap: 5px; }
.field input, .field select { width: 100%; }
.form-row { display: flex; gap: 8px; align-items: flex-end; flex-wrap: wrap; margin-top: 10px; }
.form-row .grow { flex: 1; min-width: 120px; }
.form-row input.count { width: 84px; }
input.wide, .wide { width: 100%; }
.note { font-size: 12.5px; margin-top: 8px; min-height: 0; }
.note:empty { display: none; }
.segmented { display: inline-flex; background: var(--panel-3); border-radius: var(--radius-sm); padding: 2px; gap: 2px; flex-wrap: wrap; }
.segmented button { border: 0; background: transparent; color: var(--muted); padding: 4px 10px; font-size: 12.5px; border-radius: 5px; }
.segmented button.on { background: var(--panel); color: var(--text); box-shadow: var(--shadow); }
/* Resource ledger. */
table.ledger { font-size: 12.5px; background: transparent; }
table.ledger th { background: transparent; cursor: default; padding: 6px 6px; font-size: 10.5px; }
table.ledger td { padding: 6px 6px; }
table.ledger td:first-child, table.ledger th:first-child { padding-left: 0; }
table.ledger td:last-child, table.ledger th:last-child { padding-right: 0; }
table.ledger tr.total td { font-weight: 650; border-top: 1px solid var(--line-strong); }
table.ledger tr:hover { background: transparent; }
table.ledger th .swatch { margin-right: 4px; vertical-align: -1px; width: 8px; height: 8px; }
.split { display: flex; height: 8px; border-radius: 999px; overflow: hidden; background: var(--panel-3); }
.split > span { display: block; height: 100%; }
.split-legend { display: flex; flex-wrap: wrap; gap: 4px 12px; font-size: 11.5px; color: var(--muted); margin-top: 6px; }
.split-legend span { display: inline-flex; align-items: center; gap: 5px; }
.split-row { display: grid; grid-template-columns: 80px 1fr; gap: 10px; align-items: center; margin-top: 8px; font-size: 12px; }
/* Spent pool and drip. */
.drip-card { background: var(--panel-2); border: 1px solid var(--line); border-radius: var(--radius-sm); padding: 12px 14px; }
.drip-top { display: flex; justify-content: space-between; align-items: baseline; gap: 10px; }
.drip-count { font-size: 20px; font-weight: 650; font-variant-numeric: tabular-nums; }
.channels { display: grid; grid-template-columns: repeat(auto-fill, minmax(112px, 1fr)); gap: 6px; margin-top: 10px; }
.channel { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius-sm); padding: 6px 8px; min-width: 0; }
.channel .name { font-size: 11px; color: var(--muted); display: flex; align-items: center; gap: 5px; }
.channel .amt { font-weight: 600; font-variant-numeric: tabular-nums; font-size: 12.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.channel .sub { font-size: 11px; color: var(--faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.channel.empty-ch { opacity: 0.55; }
.callout {
display: flex;
gap: 10px;
padding: 10px 12px;
border-radius: var(--radius-sm);
font-size: 12.5px;
background: var(--warn-soft);
color: var(--text);
border: 1px solid color-mix(in srgb, var(--warn) 35%, transparent);
margin-bottom: 12px;
}
.callout::before { content: "!"; flex: none; width: 18px; height: 18px; border-radius: 50%; background: var(--warn); color: var(--panel); font-weight: 700; display: grid; place-items: center; font-size: 12px; }
.callout.info { background: var(--accent-soft); border-color: color-mix(in srgb, var(--accent) 30%, transparent); }
.callout.info::before { content: "i"; background: var(--accent); }
/* Lists in the panel. */
.list { display: flex; flex-direction: column; }
.list-item { display: flex; align-items: center; gap: 10px; padding: 8px 0; border-bottom: 1px solid var(--line); font-size: 12.5px; }
.list-item:last-child { border-bottom: 0; }
.list-item .grow { flex: 1; min-width: 0; }
.list-item.clickable { cursor: pointer; }
.list-item.clickable:hover .grow { color: var(--accent); }
.list-item .sub { color: var(--muted); font-size: 11.5px; }
/* Inspector. */
.inspect-head { display: flex; align-items: center; gap: 10px; margin-bottom: 12px; }
.inspect-head .swatch { width: 14px; height: 14px; }
.inspect-head h2 { margin: 0; }
.inspect-head .grow { flex: 1; }
/* Tuning settings. */
.settings-group { margin-top: 6px; }
.settings-group summary {
cursor: pointer;
list-style: none;
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px 0;
font-weight: 600;
font-size: 12.5px;
text-transform: capitalize;
border-bottom: 1px solid var(--line);
}
.settings-group summary::-webkit-details-marker { display: none; }
.settings-group summary::before { content: "▸"; color: var(--faint); margin-right: 8px; transition: transform 0.15s; display: inline-block; }
.settings-group[open] summary::before { transform: rotate(90deg); }
.settings-group summary .label { flex: 1; }
.setting { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 2px 12px; padding: 6px 0 6px 16px; border-bottom: 1px dashed var(--line); font-size: 12.5px; }
.setting:last-child { border-bottom: 0; }
.setting .key { font-family: var(--mono); font-size: 12px; overflow-wrap: anywhere; }
.setting .val { font-family: var(--mono); font-size: 12px; font-weight: 600; text-align: right; }
.setting .why { grid-column: 1 / -1; color: var(--muted); font-size: 11.5px; }
.setting.changed .val { color: var(--accent); }
mark { background: var(--warn-soft); color: inherit; border-radius: 2px; }
/* ---------- Tuning editor ---------- */
.tuning-layout { display: grid; grid-template-columns: minmax(0, 1fr) 400px; gap: 16px; align-items: start; }
@media (max-width: 1100px) { .tuning-layout { grid-template-columns: 1fr; } }
.tuning-layout .side { display: flex; flex-direction: column; gap: 14px; }
.tuning-layout .side .card + .card { margin-top: 0; }
textarea.tuning {
display: block;
width: 100%;
min-height: 62vh;
font-family: var(--mono);
font-size: 12.5px;
line-height: 1.55;
color: var(--text);
background: var(--panel-2);
border: 1px solid var(--line);
border-radius: var(--radius-sm);
padding: 12px 14px;
resize: vertical;
tab-size: 4;
}
textarea.tuning:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); }
.action { border-top: 1px solid var(--line); padding-top: 12px; margin-top: 12px; }
.action .row { display: flex; gap: 8px; align-items: center; margin-top: 8px; flex-wrap: wrap; }
/* Guided tuning editor: sections, fields, changes. */
.tuning-guided { display: grid; grid-template-columns: 230px minmax(0, 1fr) 380px; gap: 16px; align-items: start; }
@media (max-width: 1250px) { .tuning-guided { grid-template-columns: 210px minmax(0, 1fr); } .tuning-guided > .side { grid-column: 1 / -1; } }
@media (max-width: 800px) { .tuning-guided { grid-template-columns: minmax(0, 1fr); } }
.tuning-guided .side { display: flex; flex-direction: column; gap: 14px; }
.tuning-guided .side .card + .card { margin-top: 0; }
.nav-card { position: sticky; top: 72px; padding: 12px; }
.section-nav { display: flex; flex-direction: column; gap: 2px; margin-top: 10px; }
.section-link { display: flex; align-items: center; gap: 8px; text-align: left; border: 0; background: transparent; color: var(--text); padding: 7px 10px; border-radius: var(--radius-sm); font-weight: 500; }
.section-link .grow { flex: 1; }
.section-link:hover { background: var(--panel-3); color: var(--text); }
.section-link.on { background: var(--accent-soft); color: var(--accent); }
.tuning-section + .tuning-section { margin-top: 14px; }
.field-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(220px, 300px); gap: 8px 20px; padding: 12px 0; border-top: 1px solid var(--line); align-items: start; }
.field-row.changed .field-label { color: var(--accent); }
.field-row.changed .input-unit input, .field-row.changed .input-unit select { border-color: var(--accent); }
.field-row.bad .input-unit input { border-color: var(--bad); }
.field-label { font-weight: 600; }
.field-key { color: var(--faint); font-size: 11.5px; margin-top: 1px; overflow-wrap: anywhere; }
.field-note { color: var(--muted); font-size: 12.5px; margin-top: 4px; }
.field-input { display: flex; flex-direction: column; gap: 3px; }
.input-unit { display: flex; align-items: center; gap: 6px; }
.input-unit input, .input-unit select { flex: 1; min-width: 0; font-family: var(--mono); font-size: 13px; text-align: right; }
.input-unit select { text-align: left; font-family: inherit; }
.input-unit .unit { color: var(--muted); font-size: 12px; white-space: nowrap; min-width: 48px; }
.gloss { color: var(--muted); font-size: 12px; text-align: right; padding-right: 86px; min-height: 0; }
.gloss:empty, .field-problem:empty { display: none; }
.field-problem { font-size: 12px; text-align: right; padding-right: 86px; color: var(--accent); }
.field-row.bad .field-problem { color: var(--bad); }
.changes-card { position: sticky; top: 72px; }
.changes-card .wide { margin-top: 10px; }
@media (max-width: 1250px) { .changes-card, .nav-card { position: static; } }
+10
View File
@@ -12,6 +12,9 @@ namespace evo::client_app {
struct CellularControls { struct CellularControls {
bool auto_feed{true}, slow_near_food{true}, precision{}; bool auto_feed{true}, slow_near_food{true}, precision{};
int speed_percent{100}; int speed_percent{100};
// Rules 13 (v14): matter channels kept from burning as energy (bit 0 carbon .. bit 3
// other). Upkeep still burns them when nothing else can pay.
std::uint8_t exclude{};
}; };
struct CellularSteering { struct CellularSteering {
client::Intention intention; client::Intention intention;
@@ -96,6 +99,13 @@ steer_cellular(const CellularControls& controls, client::Intention intention,
short_on[i + 1] = d.bud_cost_matter_fg[i] > d.reserve_matter_fg[i]; short_on[i + 1] = d.bud_cost_matter_fg[i] > d.reserve_matter_fg[i];
return short_on; return short_on;
} }
[[nodiscard]] inline bool bud_affordable(const network::CellularLifeDiagnostics& d) {
const bool known =
d.bud_cost_energy_pj != 0 ||
std::ranges::any_of(d.bud_cost_matter_fg, [](auto amount) { return amount != 0; });
const auto short_on = bud_shortfall(d);
return known && std::ranges::none_of(short_on, [](bool missing) { return missing; });
}
[[nodiscard]] inline bool can_fund(const network::CellularOfferedCandidate& candidate, [[nodiscard]] inline bool can_fund(const network::CellularOfferedCandidate& candidate,
const network::CellularLifeDiagnostics& reserve) { const network::CellularLifeDiagnostics& reserve) {
if (candidate.cost_energy_pj > reserve.reserve_energy_pj) if (candidate.cost_energy_pj > reserve.reserve_energy_pj)
+50 -5
View File
@@ -2,6 +2,7 @@
#include "evo/network/session_protocol.hpp" #include "evo/network/session_protocol.hpp"
#include <algorithm> #include <algorithm>
#include <array>
#include <cstddef> #include <cstddef>
#include <cstdint> #include <cstdint>
#include <deque> #include <deque>
@@ -14,9 +15,10 @@ namespace evo::client_app {
struct MutationChoice { struct MutationChoice {
std::uint64_t life{}, event{}, offer_tick{}; std::uint64_t life{}, event{}, offer_tick{};
std::uint16_t operator_id{}; std::uint16_t operator_id{};
bool become{}; // Rules 13 (v14): continue as the offspring the choice splits off.
friend bool operator==(const MutationChoice&, const MutationChoice&) = default; friend bool operator==(const MutationChoice&, const MutationChoice&) = default;
}; };
enum class CellAction : std::uint8_t { engulf, bud, mutation }; enum class CellAction : std::uint8_t { engulf, bud, mutation, emerge };
enum class CellActionState : std::uint8_t { enum class CellActionState : std::uint8_t {
queued, queued,
sent, sent,
@@ -35,11 +37,16 @@ struct CellActionRecord {
// The region's reported effect of this engulf or bud, once a view carries it. // The region's reported effect of this engulf or bud, once a view carries it.
std::optional<network::CellularEngulfResult> engulf; std::optional<network::CellularEngulfResult> engulf;
std::optional<network::CellularBudOutcome> bud; std::optional<network::CellularBudOutcome> bud;
bool become{}; // A bud the player continues as (v14).
}; };
struct CellEnergyChange { struct CellEnergyChange {
std::uint64_t from_tick{}, to_tick{}, amount{}; std::uint64_t from_tick{}, to_tick{}, amount{};
bool falling{}; bool falling{};
}; };
// Rules 13 (v14): each channel's flows over the last second of views (energy, C, N, P, other).
struct CellFlows {
std::array<std::uint64_t, 5> collected{}, into_growth{}, burned{};
};
class CellularPlay { class CellularPlay {
public: public:
@@ -93,6 +100,16 @@ class CellularPlay {
energy_change_.reset(); energy_change_.reset();
} }
energy_sample_ = EnergySample{view.life_identity, view.tick, energy}; energy_sample_ = EnergySample{view.life_identity, view.tick, energy};
// One sample per tick of this life, the last second (20 ticks) kept.
if (!flow_samples_.empty() && flow_samples_.back().life != view.life_identity)
flow_samples_.clear();
const auto& d = *view.diagnostics;
if (d.has_tick_effects &&
(flow_samples_.empty() || flow_samples_.back().tick < view.tick))
flow_samples_.push_back(
{view.life_identity, view.tick, {d.collected, d.into_growth, d.burned}});
while (!flow_samples_.empty() && flow_samples_.front().tick + 20 <= view.tick)
flow_samples_.pop_front();
} }
// Never replay an intention onto a later life. Keep its uncertain result visible. // Never replay an intention onto a later life. Keep its uncertain result visible.
if (life_ != view.life_identity) { if (life_ != view.life_identity) {
@@ -149,7 +166,8 @@ class CellularPlay {
[[nodiscard]] bool can_act() const { [[nodiscard]] bool can_act() const {
return connected_ && fresh_ && life_ != 0 && !ended_ && !pending_ && !birth_pending_; return connected_ && fresh_ && life_ != 0 && !ended_ && !pending_ && !birth_pending_;
} }
[[nodiscard]] bool queue(CellAction kind, std::uint64_t tick, MutationChoice choice = {}) { [[nodiscard]] bool queue(CellAction kind, std::uint64_t tick, MutationChoice choice = {},
bool become = false) {
if (!can_act() || tick == 0) if (!can_act() || tick == 0)
return false; return false;
if (kind == CellAction::mutation && if (kind == CellAction::mutation &&
@@ -163,9 +181,16 @@ class CellularPlay {
const auto id = allocate_id(); const auto id = allocate_id();
if (id == 0) if (id == 0)
return false; return false;
pending_ = CellActionRecord{ pending_ = CellActionRecord{kind,
kind, CellActionState::queued, id, life_, tick, CellActionState::queued,
choice, network::AdmitStatus::admitted, std::nullopt, std::nullopt}; id,
life_,
tick,
choice,
network::AdmitStatus::admitted,
std::nullopt,
std::nullopt,
kind == CellAction::bud && become};
return true; return true;
} }
void sent() { void sent() {
@@ -299,6 +324,21 @@ class CellularPlay {
[[nodiscard]] const auto& energy_change() const { [[nodiscard]] const auto& energy_change() const {
return energy_change_; return energy_change_;
} }
// Flows per second, scaled up when views were missed.
[[nodiscard]] CellFlows flows_per_second() const {
CellFlows total;
for (const auto& sample : flow_samples_)
for (std::size_t c = 0; c < 5; ++c) {
total.collected.at(c) += sample.flows.collected.at(c);
total.into_growth.at(c) += sample.flows.into_growth.at(c);
total.burned.at(c) += sample.flows.burned.at(c);
}
if (!flow_samples_.empty() && flow_samples_.size() < 20)
for (auto* channel : {&total.collected, &total.into_growth, &total.burned})
for (auto& value : *channel)
value = value * 20 / flow_samples_.size();
return total;
}
private: private:
void finish() { void finish() {
@@ -336,6 +376,11 @@ class CellularPlay {
std::uint64_t life{}, tick{}, energy{}; std::uint64_t life{}, tick{}, energy{};
}; };
std::optional<EnergySample> energy_sample_; std::optional<EnergySample> energy_sample_;
struct FlowSample {
std::uint64_t life{}, tick{};
CellFlows flows;
};
std::deque<FlowSample> flow_samples_;
std::optional<CellEnergyChange> energy_change_; std::optional<CellEnergyChange> energy_change_;
}; };
} // namespace evo::client_app } // namespace evo::client_app
+41 -1
View File
@@ -573,7 +573,8 @@ int main(int argc, char** argv) try {
buffers.cellular_controls.auto_feed = false; buffers.cellular_controls.auto_feed = false;
} }
if (auto* remote = host.session(); remote && mode() == Mode::remote) { if (auto* remote = host.session(); remote && mode() == Mode::remote) {
if (actions.cell_action && remote->request_cellular(*actions.cell_action)) if (actions.cell_action &&
remote->request_cellular(*actions.cell_action, {}, actions.cell_become))
cellular_feed_target.reset(); cellular_feed_target.reset();
if (actions.mutation) if (actions.mutation)
static_cast<void>(remote->request_cellular(evo::client_app::CellAction::mutation, static_cast<void>(remote->request_cellular(evo::client_app::CellAction::mutation,
@@ -753,6 +754,8 @@ int main(int argc, char** argv) try {
scene.deposits.clear(); scene.deposits.clear();
scene.pops.clear(); scene.pops.clear();
scene.cells.clear(); scene.cells.clear();
scene.region = scene.at_edge = false;
scene.region_cells = 0;
scene_active = false; scene_active = false;
const auto* cellular_remote = host.session(); const auto* cellular_remote = host.session();
const bool microscope = cellular_remote && mode() == Mode::remote && cellular_trial; const bool microscope = cellular_remote && mode() == Mode::remote && cellular_trial;
@@ -913,6 +916,43 @@ int main(int argc, char** argv) try {
} }
} }
const auto own = cellular_remote->cellular_play().life(); const auto own = cellular_remote->cellular_play().life();
// The region's walls, from the perceived current configuration (mm).
double region_w_mm = 0, region_h_mm = 0;
if (const auto* perception = cellular_remote->cellular_perception();
perception && perception->currents) {
region_w_mm = static_cast<double>(perception->currents->width_um) / 1000;
region_h_mm = static_cast<double>(perception->currents->height_um) / 1000;
const auto low = camera->world_to_screen({0, 0});
const auto high = camera->world_to_screen({region_w_mm, region_h_mm});
if (low && high) {
scene.region = true;
scene.region_left = static_cast<float>(std::min(low->x, high->x));
scene.region_right = static_cast<float>(std::max(low->x, high->x));
scene.region_top = static_cast<float>(std::min(low->y, high->y));
scene.region_bottom = static_cast<float>(std::max(low->y, high->y));
}
}
if (orgs) {
scene.region_cells = static_cast<std::size_t>(
std::ranges::count_if(orgs->cells(), [](const auto& cell) {
return cell.state != evo::client::OrganismState::dead;
}));
// Against a wall: within 50 um of it (positions are the lower-left corner).
for (const auto& cell : orgs->cells()) {
if (own == 0 || cell.id != own || region_w_mm == 0)
continue;
constexpr auto pitch = static_cast<double>(evo::world::cell_pitch_mm);
const double x = static_cast<double>(cell.voxel.x) * pitch +
static_cast<double>(cell.x.value) / 1000;
const double y = static_cast<double>(cell.voxel.y) * pitch +
static_cast<double>(cell.y.value) / 1000;
const double extent = static_cast<double>(cell.phenotype.extent) / 1000;
constexpr double near = 0.05;
scene.at_edge = x <= near || y <= near ||
x + extent >= region_w_mm - near ||
y + extent >= region_h_mm - near;
}
}
// ADR-0176: the owner's view lists the producers it can see, by organism. // ADR-0176: the owner's view lists the producers it can see, by organism.
const auto* seen = cellular_remote->cellular_perception(); const auto* seen = cellular_remote->cellular_perception();
const auto photosynthesis = [&](std::uint64_t organism) -> std::uint32_t { const auto photosynthesis = [&](std::uint64_t organism) -> std::uint32_t {
+401 -37
View File
@@ -1,4 +1,5 @@
#include "panels.hpp" #include "panels.hpp"
#include "evo/biology/cellular_catalog.hpp"
#include "evo/client/labels.hpp" #include "evo/client/labels.hpp"
#include <algorithm> #include <algorithm>
#include <array> #include <array>
@@ -6,6 +7,7 @@
#include <cstdio> #include <cstdio>
#include <cstring> #include <cstring>
#include <imgui.h> #include <imgui.h>
#include <limits>
#include <string> #include <string>
#include <string_view> #include <string_view>
@@ -565,6 +567,8 @@ const char* cell_action_name(CellAction kind) {
return "Bud"; return "Bud";
case CellAction::mutation: case CellAction::mutation:
return "Mutation"; return "Mutation";
case CellAction::emerge:
return "Emerge";
} }
return "Action"; return "Action";
} }
@@ -606,7 +610,7 @@ const char* bud_text(network::CellularBudOutcome outcome) {
"Bud created: a descendant split off", "Bud created: a descendant split off",
"Bud failed: not fully grown", "Bud failed: not fully grown",
"Bud failed: not enough resources", "Bud failed: not enough resources",
"Bud failed: no space beside you"}; "Bud failed: no space beside you, or the region is full"};
const auto index = static_cast<std::size_t>(outcome); const auto index = static_cast<std::size_t>(outcome);
return index < text.size() ? text.at(index) : ""; return index < text.size() ? text.at(index) : "";
} }
@@ -653,10 +657,22 @@ void dot(ImU32 color, bool hollow = false) {
ImGui::Dummy({size, size}); ImGui::Dummy({size, size});
} }
// One table row: a nutrient's dot and name, a bar filled to `share`, and a value. // One table row: a nutrient's dot and name, a bar filled to `share`, and a value.
void nutrient_row(std::size_t channel, const char* name, float share, const std::string& value) { void nutrient_row(std::size_t channel, const char* name, float share, const std::string& value,
bool highlight = false, const std::string& tip = {}) {
// Quantities are readouts, not prose: wrapping one changes every later row's baseline.
ImGui::PushTextWrapPos(-1);
ImGui::TableNextRow(); ImGui::TableNextRow();
ImGui::TableNextColumn(); ImGui::TableNextColumn();
if (highlight) {
const auto at = ImGui::GetCursorScreenPos();
const float line = ImGui::GetTextLineHeight();
const float marker_width = ImGui::CalcTextSize("*").x;
ImGui::GetWindowDrawList()->AddText({at.x + (line - marker_width) / 2, at.y},
ImGui::ColorConvertFloat4ToU32(amber), "*");
ImGui::Dummy({line, line});
} else {
dot(nutrient_colors.at(channel)); dot(nutrient_colors.at(channel));
}
ImGui::SameLine(0, ImGui::GetStyle().ItemInnerSpacing.x); ImGui::SameLine(0, ImGui::GetStyle().ItemInnerSpacing.x);
ImGui::TextUnformatted(name); ImGui::TextUnformatted(name);
ImGui::TableNextColumn(); ImGui::TableNextColumn();
@@ -670,17 +686,16 @@ void nutrient_row(std::size_t channel, const char* name, float share, const std:
height / 2); height / 2);
list.AddRectFilled({at.x, top}, {at.x + width * std::clamp(share, 0.0F, 1.0F), top + height}, list.AddRectFilled({at.x, top}, {at.x + width * std::clamp(share, 0.0F, 1.0F), top + height},
nutrient_colors.at(channel), height / 2); nutrient_colors.at(channel), height / 2);
// The nutrient holding growth back: an amber outline around its bar.
if (highlight)
list.AddRect({at.x - 2, top - 2}, {at.x + width + 2, top + height + 2},
IM_COL32(243, 176, 77, 255), height / 2 + 2, 0, 1.5F);
ImGui::Dummy({width, line}); ImGui::Dummy({width, line});
if (!tip.empty() && ImGui::IsItemHovered())
ImGui::SetTooltip("%s", tip.c_str());
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::TextUnformatted(value.c_str()); ImGui::TextUnformatted(value.c_str());
} ImGui::PopTextWrapPos();
bool begin_nutrient_table(const char* id) {
if (!ImGui::BeginTable(id, 3, ImGuiTableFlags_SizingFixedFit))
return false;
ImGui::TableSetupColumn("name", ImGuiTableColumnFlags_WidthFixed, px(104));
ImGui::TableSetupColumn("bar", ImGuiTableColumnFlags_WidthStretch);
ImGui::TableSetupColumn("value", ImGuiTableColumnFlags_WidthFixed, px(64));
return true;
} }
// Three significant digits in the largest unit that keeps the value at least 1. // Three significant digits in the largest unit that keeps the value at least 1.
std::string scaled(std::uint64_t value, const std::array<const char*, 4>& units) { std::string scaled(std::uint64_t value, const std::array<const char*, 4>& units) {
@@ -701,6 +716,20 @@ std::string energy_text(std::uint64_t picojoules) {
std::string mass_text(std::uint64_t femtograms) { std::string mass_text(std::uint64_t femtograms) {
return scaled(femtograms, {"fg", "pg", "ng", "\xC2\xB5g"}); return scaled(femtograms, {"fg", "pg", "ng", "\xC2\xB5g"});
} }
bool begin_nutrient_table(const char* id) {
if (!ImGui::BeginTable(id, 3, ImGuiTableFlags_SizingFixedFit))
return false;
// Reserve the widest supported stock for this font/scale, never from the live
// amount. Even the full uint64 range stays legible without growing the column.
constexpr auto maximum = std::numeric_limits<std::uint64_t>::max();
const float value_width =
std::ceil(std::max({px(64), ImGui::CalcTextSize(energy_text(maximum).c_str()).x,
ImGui::CalcTextSize(mass_text(maximum).c_str()).x}));
ImGui::TableSetupColumn("name", ImGuiTableColumnFlags_WidthFixed, px(104));
ImGui::TableSetupColumn("bar", ImGuiTableColumnFlags_WidthStretch);
ImGui::TableSetupColumn("value", ImGuiTableColumnFlags_WidthFixed, value_width);
return true;
}
std::uint64_t mix(std::uint64_t x) noexcept { std::uint64_t mix(std::uint64_t x) noexcept {
x += 0x9E3779B97F4A7C15ULL; x += 0x9E3779B97F4A7C15ULL;
x = (x ^ (x >> 30U)) * 0xBF58476D1CE4E5B9ULL; x = (x ^ (x >> 30U)) * 0xBF58476D1CE4E5B9ULL;
@@ -882,7 +911,24 @@ std::size_t dominant_channel(const std::array<std::uint64_t, 5>& stock) {
// ADR-0136: a bubble is a translucent circle in its nutrient's colour, sized by what it // ADR-0136: a bubble is a translucent circle in its nutrient's colour, sized by what it
// holds (never below its contact disc). While something eats it, a soft glow of its own // holds (never below its contact disc). While something eats it, a soft glow of its own
// colour fades in and out around it; the bubble itself keeps its size. // colour fades in and out around it; the bubble itself keeps its size.
void draw_pool(ImDrawList& list, const SceneDeposit& d, float time);
void draw_bubble(ImDrawList& list, const SceneDeposit& d, float time) { void draw_bubble(ImDrawList& list, const SceneDeposit& d, float time) {
// A bubble holding more than one nutrient looks like a little pool of all of them.
if (std::ranges::count_if(d.stock, [](std::uint64_t amount) { return amount != 0; }) > 1) {
std::uint64_t total{};
for (const auto amount : d.stock)
total += amount;
auto small = d;
small.radius = std::max(
d.radius *
std::clamp(0.7F + 0.12F * static_cast<float>(std::log10(static_cast<double>(
std::max<std::uint64_t>(1, total)))),
0.8F, 2.2F) *
0.6F,
6.0F);
draw_pool(list, small, time);
return;
}
const auto channel = dominant_channel(d.stock); const auto channel = dominant_channel(d.stock);
const auto total = static_cast<double>(std::max<std::uint64_t>(1, d.stock.at(channel))); const auto total = static_cast<double>(std::max<std::uint64_t>(1, d.stock.at(channel)));
const float scale = const float scale =
@@ -1035,6 +1081,17 @@ void draw_scene(const PanelView& v) {
const auto time = v.cellular_scene->stale ? 0.0F : static_cast<float>(ImGui::GetTime()); const auto time = v.cellular_scene->stale ? 0.0F : static_cast<float>(ImGui::GetTime());
draw_liquid(list, ImGui::GetIO().DisplaySize, time); draw_liquid(list, ImGui::GetIO().DisplaySize, time);
draw_flows(list, v.cellular_scene->flows, time); draw_flows(list, v.cellular_scene->flows, time);
if (const auto& s = *v.cellular_scene; s.region) {
const auto size = ImGui::GetIO().DisplaySize;
const auto outside = IM_COL32(4, 3, 6, 200);
list.AddRectFilled({0, 0}, {size.x, s.region_top}, outside);
list.AddRectFilled({0, s.region_bottom}, {size.x, size.y}, outside);
list.AddRectFilled({0, s.region_top}, {s.region_left, s.region_bottom}, outside);
list.AddRectFilled({s.region_right, s.region_top}, {size.x, s.region_bottom}, outside);
list.AddRect({s.region_left, s.region_top}, {s.region_right, s.region_bottom},
s.at_edge ? IM_COL32(243, 176, 77, 230) : IM_COL32(166, 220, 199, 140), 0, 0,
s.at_edge ? 3.0F : 1.5F);
}
for (const auto& patch : v.cellular_scene->patches) for (const auto& patch : v.cellular_scene->patches)
draw_patch(list, patch); draw_patch(list, patch);
const auto visible = [&](const SceneDeposit& d) { const auto visible = [&](const SceneDeposit& d) {
@@ -1107,12 +1164,93 @@ bool action_button(const char* label, ImVec2 size, ImVec4 accent) {
ImGui::PopStyleColor(4); ImGui::PopStyleColor(4);
return pressed; return pressed;
} }
void panel_heading(const char* title, bool& minimized) { ImVec2 hud_position(ImVec2 position, ImVec2 size) {
const auto display = ImGui::GetIO().DisplaySize;
const float margin = px(8);
return {std::clamp(position.x, margin, std::max(margin, display.x - size.x - margin)),
std::clamp(position.y, margin, std::max(margin, display.y - size.y - margin))};
}
void place_hud_panel(HudPanelPlacement& placement, ImVec2 fallback, ImVec2 size, bool minimized) {
const auto display = ImGui::GetIO().DisplaySize;
ImGui::GetIO().ConfigWindowsResizeFromEdges = true;
const ImVec2 minimum{std::min(size.x, px(260)), minimized ? size.y : px(120)};
if (placement.size) {
size.x = px(placement.size->first);
if (!minimized)
size.y = px(placement.size->second);
}
size.x = std::min(size.x, std::max(1.0F, display.x - 2 * px(8)));
size.y = std::min(size.y, std::max(1.0F, display.y - 2 * px(8)));
const ImVec2 maximum{std::max(1.0F, display.x - 2 * px(8)),
minimized ? size.y : std::max(1.0F, display.y - 2 * px(8))};
ImGui::SetNextWindowSizeConstraints(
{std::min(minimum.x, maximum.x), std::min(minimum.y, maximum.y)}, maximum);
auto position = fallback;
if (placement.anchor)
position = {placement.anchor->first * display.x, placement.anchor->second * display.y};
position = hud_position(position, size);
if (placement.anchor)
placement.anchor = {position.x / display.x, position.y / display.y};
ImGui::SetNextWindowPos(position, ImGuiCond_Always);
ImGui::SetNextWindowSize(size, ImGuiCond_Always);
placement.requested_size = {size.x, size.y};
}
float collapsed_height(bool energy = false) {
return 2 * ImGui::GetStyle().WindowPadding.y + ImGui::GetFrameHeight() +
(energy ? ImGui::GetTextLineHeightWithSpacing() : 0);
}
void begin_hud_body(const char* id) {
ImGui::BeginChild(id, {0, 0}, ImGuiChildFlags_None, ImGuiWindowFlags_AlwaysVerticalScrollbar);
ImGui::PushTextWrapPos(0);
}
void end_hud_body() {
ImGui::PopTextWrapPos();
ImGui::EndChild();
}
// The heading stays outside the scrollable body. Only this handle moves a panel.
void panel_heading(const char* title, bool& minimized, HudPanelPlacement& placement) {
// Begin applies native edge/corner resizing after the requested layout. Retain only
// deliberate edits, so untouched cards still follow the viewport's default layout.
const auto size = ImGui::GetWindowSize();
const auto resized_position = ImGui::GetWindowPos();
if (!minimized && (std::abs(size.x - placement.requested_size.first) > 0.5F ||
std::abs(size.y - placement.requested_size.second) > 0.5F)) {
placement.size = {size.x / px(1), size.y / px(1)};
const auto display = ImGui::GetIO().DisplaySize;
placement.anchor = {resized_position.x / display.x, resized_position.y / display.y};
}
ImGui::PushID(title); ImGui::PushID(title);
const float right = ImGui::GetCursorPosX() + ImGui::GetContentRegionAvail().x; const float right = ImGui::GetCursorPosX() + ImGui::GetContentRegionAvail().x;
ImGui::AlignTextToFramePadding(); ImGui::AlignTextToFramePadding();
ImGui::TextUnformatted(title); ImGui::TextUnformatted(title);
ImGui::SameLine(); ImGui::SameLine();
const float small_width = ImGui::CalcTextSize(" + ").x + 2 * ImGui::GetStyle().FramePadding.x;
ImGui::SetCursorPosX(right - 2 * small_width - ImGui::GetStyle().ItemSpacing.x);
ImGui::SmallButton("::");
if (ImGui::IsItemActivated()) {
const auto position = ImGui::GetWindowPos();
placement.drag_origin = {position.x, position.y};
}
if (ImGui::IsItemActive() && ImGui::IsMouseDragging(ImGuiMouseButton_Left)) {
ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeAll);
const auto delta = ImGui::GetMouseDragDelta(ImGuiMouseButton_Left);
const auto position = hud_position(
{placement.drag_origin.first + delta.x, placement.drag_origin.second + delta.y},
ImGui::GetWindowSize());
const auto display = ImGui::GetIO().DisplaySize;
placement.anchor = {position.x / display.x, position.y / display.y};
ImGui::SetWindowPos(position);
}
if (ImGui::IsItemHovered()) {
ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeAll);
ImGui::SetTooltip("Drag to place %s; drag an edge to resize. Double-click to reset.",
title);
if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) {
placement.anchor.reset();
placement.size.reset();
}
}
ImGui::SameLine();
ImGui::SetCursorPosX(right - ImGui::CalcTextSize(" + ").x - ImGui::SetCursorPosX(right - ImGui::CalcTextSize(" + ").x -
2 * ImGui::GetStyle().FramePadding.x); 2 * ImGui::GetStyle().FramePadding.x);
if (ImGui::SmallButton(minimized ? " + " : " - ")) if (ImGui::SmallButton(minimized ? " + " : " - "))
@@ -1163,30 +1301,33 @@ void hud_vitals(const PanelView& v, FormBuffers& form, bool compact) {
const auto& io = ImGui::GetIO(); const auto& io = ImGui::GetIO();
const float clearance = eyepiece_clearance(); const float clearance = eyepiece_clearance();
const float width = std::min(px(300), io.DisplaySize.x - 2 * px(12)); const float width = std::min(px(300), io.DisplaySize.x - 2 * px(12));
if (compact)
ImGui::SetNextWindowPos({px(12), px(64)}, ImGuiCond_Always);
else
ImGui::SetNextWindowPos({clearance, io.DisplaySize.y - px(16)}, ImGuiCond_Always, {0, 1});
const auto* play = v.cellular_play; const auto* play = v.cellular_play;
const auto* d = diagnostics(v); const auto* d = diagnostics(v);
if (!play || play->life() == 0) if (!play || play->life() == 0)
return; // The life window speaks for a cell that is not alive. return; // The life window speaks for a cell that is not alive.
const float max_height = const float max_height =
compact ? std::max(px(120), io.DisplaySize.y - px(220)) : io.DisplaySize.y * 0.43F; compact ? std::max(px(120), io.DisplaySize.y - px(220)) : io.DisplaySize.y * 0.43F;
ImGui::SetNextWindowSizeConstraints({width, 0}, {width, max_height}); const float height = form.vitals_minimized ? collapsed_height(true) : max_height;
place_hud_panel(form.vitals_placement,
compact ? ImVec2{px(12), px(64)}
: ImVec2{clearance, io.DisplaySize.y - px(16) - height},
{width, height}, form.vitals_minimized);
ImGui::Begin("Vitals", nullptr, ImGui::Begin("Vitals", nullptr,
hud_flags | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_AlwaysAutoResize); (hud_flags & ~ImGuiWindowFlags_NoResize) | ImGuiWindowFlags_NoTitleBar |
panel_heading("Your cell", form.vitals_minimized); ImGuiWindowFlags_NoScrollbar);
panel_heading("Your cell", form.vitals_minimized, form.vitals_placement);
if (form.vitals_minimized) { if (form.vitals_minimized) {
if (d) if (d)
ImGui::Text("Energy %s", energy_text(d->reserve_energy_pj).c_str()); ImGui::Text("Energy %s", energy_text(d->reserve_energy_pj).c_str());
ImGui::End(); ImGui::End();
return; return;
} }
begin_hud_body("##body");
if (!play->fresh()) if (!play->fresh())
ImGui::TextColored(amber, "Waiting for a fresh server view"); ImGui::TextColored(amber, "Waiting for a fresh server view");
if (!d) { if (!d) {
disabled_wrapped("Your cell's reserves appear with the next server view."); disabled_wrapped("Your cell's reserves appear with the next server view.");
end_hud_body();
ImGui::End(); ImGui::End();
return; return;
} }
@@ -1203,6 +1344,15 @@ void hud_vitals(const PanelView& v, FormBuffers& form, bool compact) {
ImGui::PushFont(nullptr, px(26)); ImGui::PushFont(nullptr, px(26));
ImGui::TextUnformatted(energy_text(d->reserve_energy_pj).c_str()); ImGui::TextUnformatted(energy_text(d->reserve_energy_pj).c_str());
ImGui::PopFont(); ImGui::PopFont();
if (d->members != 0 && ImGui::IsItemHovered()) {
const auto flows = play->flows_per_second();
ImGui::SetTooltip("Last second: +%s collected, -%s into growth.%s",
energy_text(flows.collected[0]).c_str(),
energy_text(flows.into_growth[0]).c_str(),
d->growth_limit == 1
? "\nEnergy availability or the survival buffer is limiting growth."
: "");
}
if (const auto& change = play->energy_change(); change && change->falling) if (const auto& change = play->energy_change(); change && change->falling)
disabled_wrapped("Energy is falling: feeding may not cover upkeep and movement."); disabled_wrapped("Energy is falling: feeding may not cover upkeep and movement.");
if (v.cellular_feed_target && v.cellular_perception) { if (v.cellular_feed_target && v.cellular_perception) {
@@ -1213,8 +1363,23 @@ void hud_vitals(const PanelView& v, FormBuffers& form, bool compact) {
if (patch != patches.end() && patch->energy_pj == 0) if (patch != patches.end() && patch->energy_pj == 0)
ImGui::TextColored(amber, "Feed target has no energy left"); ImGui::TextColored(amber, "Feed target has no energy left");
} }
// Rules 13 (v14): how far the body has grown, and what is holding it back.
const bool revamp = d->members != 0;
if (revamp) {
constexpr std::array held{"", "energy", "carbon", "nitrogen",
"phosphorus", "other matter", "room to grow here"};
const auto grown = static_cast<unsigned>(d->growth_per_thousand / 10);
if (d->growth_per_thousand >= 1000)
ImGui::TextColored(lavender, "Fully grown");
else if (d->growth_limit != 0 && d->growth_limit < held.size())
ImGui::TextColored(amber, "Growing %u%% - waiting for %s", grown,
held.at(d->growth_limit));
else
ImGui::TextColored(lavender, "Growing %u%%", grown);
}
ImGui::Separator(); ImGui::Separator();
const bool toward_bud = bud_known(*d); const bool toward_bud = bud_known(*d);
const auto flows = revamp ? play->flows_per_second() : CellFlows{};
if (begin_nutrient_table("matter")) { if (begin_nutrient_table("matter")) {
for (std::size_t i = 0; i < d->reserve_matter_fg.size(); ++i) { for (std::size_t i = 0; i < d->reserve_matter_fg.size(); ++i) {
const auto have = d->reserve_matter_fg.at(i); const auto have = d->reserve_matter_fg.at(i);
@@ -1223,10 +1388,24 @@ void hud_vitals(const PanelView& v, FormBuffers& form, bool compact) {
toward_bud && need != 0 toward_bud && need != 0
? static_cast<float>(static_cast<double>(have) / static_cast<double>(need)) ? static_cast<float>(static_cast<double>(have) / static_cast<double>(need))
: 1.0F; : 1.0F;
nutrient_row(i + 1, nutrient_names.at(i + 1), share, mass_text(have)); const bool limiting = revamp && d->growth_limit == i + 2;
std::string tip;
if (revamp) {
const std::string name = nutrient_names.at(i + 1);
tip = "Last second: +" + mass_text(flows.collected.at(i + 1)) + " collected, -" +
mass_text(flows.into_growth.at(i + 1)) + " into growth, -" +
mass_text(flows.burned.at(i + 1)) + " burned for energy.\n" + name +
" goes into your body as soon as it arrives while you grow; the bar\n"
"shows only what is left over.";
if (limiting)
tip += "\nThis is what is holding your growth back right now.";
}
nutrient_row(i + 1, nutrient_names.at(i + 1), share, mass_text(have), limiting, tip);
} }
ImGui::EndTable(); ImGui::EndTable();
} }
if (revamp && d->growth_limit >= 2 && d->growth_limit <= 5)
disabled_wrapped("* holds your growth back. Hover a bar for its flows.");
if (toward_bud) if (toward_bud)
disabled_wrapped("Bars: progress toward your next bud."); disabled_wrapped("Bars: progress toward your next bud.");
if (d->has_tick_effects) { if (d->has_tick_effects) {
@@ -1241,6 +1420,7 @@ void hud_vitals(const PanelView& v, FormBuffers& form, bool compact) {
if (d->light_pj != 0) if (d->light_pj != 0)
ImGui::TextDisabled("Sunlight +%s", energy_text(d->light_pj).c_str()); ImGui::TextDisabled("Sunlight +%s", energy_text(d->light_pj).c_str());
} }
end_hud_body();
ImGui::End(); ImGui::End();
} }
// Bottom centre: the three things a cell does, with what a bud still needs and the last // Bottom centre: the three things a cell does, with what a bud still needs and the last
@@ -1259,9 +1439,11 @@ void hud_dock(const PanelView& v, FormBuffers& form, PanelActions& a, bool compa
left = std::max(left, eyepiece_clearance() + std::min(px(300), io.DisplaySize.x) + px(12)); left = std::max(left, eyepiece_clearance() + std::min(px(300), io.DisplaySize.x) + px(12));
left = std::max(px(12), std::min(left, io.DisplaySize.x - width - px(12))); left = std::max(px(12), std::min(left, io.DisplaySize.x - width - px(12)));
ImGui::SetNextWindowPos({left, io.DisplaySize.y - px(16)}, ImGuiCond_Always, {0, 1}); ImGui::SetNextWindowPos({left, io.DisplaySize.y - px(16)}, ImGuiCond_Always, {0, 1});
ImGui::SetNextWindowSizeConstraints({width, 0}, {width, io.DisplaySize.y}); ImGui::SetNextWindowSize(
{width, std::min(px(compact ? 140.0F : 180.0F), io.DisplaySize.y - px(32))},
ImGuiCond_Always);
ImGui::Begin("Actions", nullptr, ImGui::Begin("Actions", nullptr,
hud_flags | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_AlwaysAutoResize); hud_flags | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoScrollbar);
const float each = const float each =
(ImGui::GetContentRegionAvail().x - 2 * ImGui::GetStyle().ItemSpacing.x) / 3.0F; (ImGui::GetContentRegionAvail().x - 2 * ImGui::GetStyle().ItemSpacing.x) / 3.0F;
const bool active = play && play->fresh() && play->life() != 0; const bool active = play && play->fresh() && play->life() != 0;
@@ -1274,10 +1456,53 @@ void hud_dock(const PanelView& v, FormBuffers& form, PanelActions& a, bool compa
ImGui::BeginDisabled(!play || !play->can_act()); ImGui::BeginDisabled(!play || !play->can_act());
if (action_button("Engulf", {each, px(44)}, {0.38F, 0.68F, 1.0F, 1})) if (action_button("Engulf", {each, px(44)}, {0.38F, 0.68F, 1.0F, 1}))
a.cell_action = CellAction::engulf; a.cell_action = CellAction::engulf;
ImGui::SameLine();
if (action_button("Bud", {each, px(44)}, {0.82F, 0.53F, 0.96F, 1}))
a.cell_action = CellAction::bud;
ImGui::EndDisabled(); ImGui::EndDisabled();
ImGui::SameLine();
const bool bud_ready = play && play->can_act() && d && bud_affordable(*d);
ImGui::BeginDisabled(!bud_ready);
if (action_button("Bud", {each, px(44)},
bud_ready ? ImVec4{0.82F, 0.53F, 0.96F, 1} : ImVec4{0.5F, 0.5F, 0.5F, 1})) {
a.cell_action = CellAction::bud;
a.cell_become = form.bud_become && d && d->members == 1;
}
ImGui::EndDisabled();
if (!bud_ready && ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) {
ImGui::BeginTooltip();
if (d && bud_known(*d)) {
ImGui::TextUnformatted("Resources needed to bud (required / available):");
ImGui::Text("Energy: %s / %s", energy_text(d->bud_cost_energy_pj).c_str(),
energy_text(d->reserve_energy_pj).c_str());
for (std::size_t i = 0; i < d->bud_cost_matter_fg.size(); ++i)
ImGui::Text("%s: %s / %s", nutrient_names.at(i + 1),
mass_text(d->bud_cost_matter_fg[i]).c_str(),
mass_text(d->reserve_matter_fg[i]).c_str());
if (!play || !play->can_act())
ImGui::TextUnformatted("Waiting for a connection, fresh state or pending action.");
if (d->members > 1)
ImGui::TextUnformatted("Includes the largest possible litter of internal cells.");
} else {
ImGui::TextUnformatted("Budding requirements are unavailable for this cell.");
}
ImGui::EndTooltip();
}
begin_hud_body("##details");
// Rules 13 (v14): continue as the bud, or grow the organism toward Emerge.
if (d && d->members != 0 && play && play->life() != 0) {
if (d->members == 1) {
ImGui::Checkbox("Continue as the bud", &form.bud_become);
} else {
ImGui::TextColored(lavender, "Organism of %u cells (Emerge at %u)",
static_cast<unsigned>(d->members),
static_cast<unsigned>(d->emerge_members));
ImGui::BeginDisabled(!play->can_act() || !d->can_emerge);
if (action_button("Emerge", {-1, px(40)}, {0.98F, 0.82F, 0.35F, 1}))
a.cell_action = CellAction::emerge;
ImGui::EndDisabled();
if (!d->can_emerge)
disabled_wrapped("Emerge opens at the threshold of cells, mass and reserve. Buds "
"add cells to the organism.");
}
}
// What a bud needs, by nutrient (ADR-0129 amendment). // What a bud needs, by nutrient (ADR-0129 amendment).
if (d && play && play->life() != 0) { if (d && play && play->life() != 0) {
if (!bud_known(*d)) { if (!bud_known(*d)) {
@@ -1296,6 +1521,9 @@ void hud_dock(const PanelView& v, FormBuffers& form, PanelActions& a, bool compa
ImGui::TextColored(amber, "Bud: short on %s", missing.c_str()); ImGui::TextColored(amber, "Bud: short on %s", missing.c_str());
} }
} }
if (const auto* s = v.cellular_scene; s && s->at_edge && play && play->life() != 0)
ImGui::TextColored(amber, "At the region edge: nothing lies beyond. Swim back in; "
"pushing on the wall still costs energy.");
if (play) { if (play) {
if (const auto& f = play->engulf_feedback(); f && *engulf_text(f->second) != '\0') if (const auto& f = play->engulf_feedback(); f && *engulf_text(f->second) != '\0')
ImGui::TextWrapped("%s", engulf_text(f->second)); ImGui::TextWrapped("%s", engulf_text(f->second));
@@ -1311,6 +1539,7 @@ void hud_dock(const PanelView& v, FormBuffers& form, PanelActions& a, bool compa
} }
} }
} }
end_hud_body();
ImGui::End(); ImGui::End();
} }
// Upper left: what the colours mean, steering, food in range, recent actions. // Upper left: what the colours mean, steering, food in range, recent actions.
@@ -1319,16 +1548,21 @@ void hud_notes(const PanelView& v, FormBuffers& form, PanelActions& a, bool comp
return; return;
const auto& io = ImGui::GetIO(); const auto& io = ImGui::GetIO();
const float clearance = eyepiece_clearance(); const float clearance = eyepiece_clearance();
ImGui::SetNextWindowPos({clearance, px(64)}, ImGuiCond_Always); place_hud_panel(form.notes_placement, {clearance, px(64)},
ImGui::SetNextWindowSizeConstraints({px(260), 0}, {px(260), form.notes_minimized
{px(260), std::max(px(120), io.DisplaySize.y * 0.41F)}); ? collapsed_height()
: std::min(px(260), std::max(px(120), io.DisplaySize.y * 0.41F))},
form.notes_minimized);
ImGui::Begin("Field notes", nullptr, ImGui::Begin("Field notes", nullptr,
hud_flags | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_AlwaysAutoResize); (hud_flags & ~ImGuiWindowFlags_NoResize) | ImGuiWindowFlags_NoTitleBar |
panel_heading("Field notes", form.notes_minimized); ImGuiWindowFlags_NoScrollbar);
panel_heading("Field notes", form.notes_minimized, form.notes_placement);
if (form.notes_minimized) { if (form.notes_minimized) {
ImGui::End(); ImGui::End();
return; return;
} }
begin_hud_body("##body");
ImGui::PushTextWrapPos(-1);
for (std::size_t i = 0; i < nutrient_names.size(); ++i) { for (std::size_t i = 0; i < nutrient_names.size(); ++i) {
const float glyph_size = ImGui::GetTextLineHeight(); const float glyph_size = ImGui::GetTextLineHeight();
const auto at = ImGui::GetCursorScreenPos(); const auto at = ImGui::GetCursorScreenPos();
@@ -1338,8 +1572,9 @@ void hud_notes(const PanelView& v, FormBuffers& form, PanelActions& a, bool comp
ImGui::SameLine(0, ImGui::GetStyle().ItemInnerSpacing.x); ImGui::SameLine(0, ImGui::GetStyle().ItemInnerSpacing.x);
ImGui::TextUnformatted(nutrient_names.at(i)); ImGui::TextUnformatted(nutrient_names.at(i));
if (i % 2 == 0 && i + 1 < nutrient_names.size()) if (i % 2 == 0 && i + 1 < nutrient_names.size())
ImGui::SameLine(px(130)); ImGui::SameLine(px(112));
} }
ImGui::PopTextWrapPos();
if (ImGui::CollapsingHeader("Food in range")) { if (ImGui::CollapsingHeader("Food in range")) {
const bool active = const bool active =
v.cellular_play && v.cellular_play->fresh() && v.cellular_play->life() != 0; v.cellular_play && v.cellular_play->fresh() && v.cellular_play->life() != 0;
@@ -1386,6 +1621,39 @@ void hud_notes(const PanelView& v, FormBuffers& form, PanelActions& a, bool comp
} }
ImGui::EndDisabled(); ImGui::EndDisabled();
} }
// Rules 13 (v14): which reserve matter may stand in for energy, and the heritable body.
if (const auto* d = diagnostics(v); d && d->members != 0) {
if (ImGui::CollapsingHeader("Burning reserve matter")) {
for (std::size_t c = 0; c < 4; ++c) {
const auto bit = static_cast<std::uint8_t>(1U << c);
bool keep = (form.cellular_controls.exclude & bit) != 0;
const std::string label = std::string{"Keep "} + nutrient_names.at(c + 1);
if (ImGui::Checkbox(label.c_str(), &keep))
form.cellular_controls.exclude =
static_cast<std::uint8_t>(keep ? form.cellular_controls.exclude | bit
: form.cellular_controls.exclude & ~bit);
}
ImGui::TextDisabled("Can pay %s now", energy_text(d->payable_energy_pj).c_str());
if (form.cellular_controls.exclude != 0 && d->has_tick_effects &&
d->reserve_energy_pj < d->maintenance_cost_pj)
ImGui::TextColored(amber, "No energy left: upkeep is burning kept matter.");
disabled_wrapped("Matter you keep is never burned for movement or mutations; upkeep "
"still burns it when nothing else can pay.");
}
if (ImGui::CollapsingHeader("Body")) {
const auto& t = d->traits;
ImGui::Text("Mass %s Grown %u%%", mass_text(d->total_mass_fg).c_str(),
static_cast<unsigned>(d->growth_per_thousand / 10));
ImGui::TextDisabled("Density %u Upkeep efficiency %u Growth %u", unsigned{t[0]},
unsigned{t[1]}, unsigned{t[2]});
ImGui::TextDisabled("Engulf capacity %u Kill absorption %u", unsigned{t[12]},
unsigned{t[13]});
ImGui::TextDisabled("Litter %u Recipe C%u N%u P%u O%u", unsigned{t[14]},
unsigned{t[15]}, unsigned{t[16]}, unsigned{t[17]}, unsigned{t[18]});
if (t[19] != 0)
ImGui::TextColored(lavender, "Adhesive: a multicellular organism");
}
}
if (ImGui::CollapsingHeader("Steering")) { if (ImGui::CollapsingHeader("Steering")) {
ImGui::Checkbox("Slow near food", &form.cellular_controls.slow_near_food); ImGui::Checkbox("Slow near food", &form.cellular_controls.slow_near_food);
ImGui::Checkbox("Precision steering (20%)", &form.cellular_controls.precision); ImGui::Checkbox("Precision steering (20%)", &form.cellular_controls.precision);
@@ -1406,6 +1674,7 @@ void hud_notes(const PanelView& v, FormBuffers& form, PanelActions& a, bool comp
"vulnerable for 10 seconds before it is suspended."); "vulnerable for 10 seconds before it is suspended.");
ImGui::Checkbox("Engineering panels", &form.engineering); ImGui::Checkbox("Engineering panels", &form.engineering);
} }
end_hud_body();
ImGui::End(); ImGui::End();
} }
// Upper right: a quiet callout while an offer waits; click it or press E. // Upper right: a quiet callout while an offer waits; click it or press E.
@@ -1494,10 +1763,89 @@ void candidate_glyph(const network::CellularOfferedCandidate& c, float width) {
IM_COL32(173, 164, 184, 255), "->"); IM_COL32(173, 164, 184, 255), "->");
ImGui::Dummy({width, height}); ImGui::Dummy({width, height});
} }
// Rules 13 (v14): a named catalog mutation, with its pro, con, chance and tuned cost. The
// choice splits a single cell (stay as the founder or become the offspring that expresses it);
// an organism expresses it as a whole.
const biology::CellularMutationSpec* named_mutation(const network::CellularLifeDiagnostics* d,
const network::CellularOfferedCandidate& c) {
if (!d || d->members == 0 || c.capability != 0 || c.effect != 0)
return nullptr;
return biology::cellular_mutation(c.operator_id);
}
void named_offer_card(const PanelView& v, const network::CellularMutationOffer& offer,
const network::CellularOfferedCandidate& c,
const biology::CellularMutationSpec& spec, PanelActions& a) {
const auto* play = v.cellular_play;
const auto* d = diagnostics(v);
ImGui::TextDisabled("%.1f%% chance", static_cast<double>(c.parameter) / 10'000.0);
ImGui::PushFont(nullptr, px(18));
ImGui::TextWrapped("%.*s", static_cast<int>(spec.name.size()), spec.name.data());
ImGui::PopFont();
ImGui::TextColored({0.32F, 0.90F, 0.73F, 1}, "+ %.*s", static_cast<int>(spec.pro.size()),
spec.pro.data());
ImGui::TextColored(amber, "- %.*s", static_cast<int>(spec.con.size()), spec.con.data());
bool affordable = d != nullptr;
const bool table = begin_nutrient_table("cost");
for (std::size_t channel = 0; channel < 5; ++channel) {
const auto need = channel == 0 ? c.cost_energy_pj : c.cost_matter_fg.at(channel - 1);
if (need == 0)
continue;
// Energy may be paid with burnable matter standing in.
const auto have =
d ? (channel == 0 ? d->payable_energy_pj : d->reserve_matter_fg.at(channel - 1)) : 0;
affordable = affordable && have >= need;
if (table)
nutrient_row(channel, nutrient_names.at(channel),
static_cast<float>(static_cast<double>(have) / static_cast<double>(need)),
channel == 0 ? energy_text(need) : mass_text(need));
}
if (table)
ImGui::EndTable();
const bool organism = d && d->members > 1;
const bool adhesion = spec.effect == biology::CellularEffect::acquire_adhesion;
// A choice that splits the cell waits until it has grown enough (the offer waits too).
const bool splits = !organism && !adhesion;
const bool grown = !splits || (d && d->split_ready);
if (adhesion)
disabled_wrapped("Your cell and its split-off offspring stay joined: one organism with "
"one genome and one reserve, growing toward Emerge.");
else if (organism)
disabled_wrapped("Your whole organism changes, paid from its reserve.");
else
disabled_wrapped("Your cell splits: both keep the change in their plan; only the "
"offspring expresses it.");
if (!grown)
ImGui::TextColored(amber, "Grow to split (now %u%%). Feed; the offer waits.",
d ? static_cast<unsigned>(d->growth_per_thousand / 10) : 0U);
const bool ready =
play && play->can_act() && v.remote && v.remote->server_tick > offer.offer_tick;
ImGui::BeginDisabled(!affordable || !ready || !grown);
const MutationChoice stay{offer.life_identity, offer.event_index, offer.offer_tick,
c.operator_id, false};
if (organism || adhesion) {
if (ImGui::Button(affordable ? "Choose" : "Feed first", {-1, px(40)}))
a.mutation = stay;
} else {
const float half = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) / 2;
if (ImGui::Button(affordable ? "Stay" : "Feed first", {half, px(40)}))
a.mutation = stay;
ImGui::SameLine();
if (ImGui::Button("Become offspring", {half, px(40)})) {
auto become = stay;
become.become = true;
a.mutation = become;
}
}
ImGui::EndDisabled();
}
void offer_card(const PanelView& v, const network::CellularMutationOffer& offer, void offer_card(const PanelView& v, const network::CellularMutationOffer& offer,
const network::CellularOfferedCandidate& c, PanelActions& a) { const network::CellularOfferedCandidate& c, PanelActions& a) {
const auto* play = v.cellular_play; const auto* play = v.cellular_play;
const auto* d = diagnostics(v); const auto* d = diagnostics(v);
if (const auto* spec = named_mutation(d, c)) {
named_offer_card(v, offer, c, *spec, a);
return;
}
ImGui::TextDisabled("%s", capability_kinds.at(c.capability)); ImGui::TextDisabled("%s", capability_kinds.at(c.capability));
const float width = ImGui::GetContentRegionAvail().x; const float width = ImGui::GetContentRegionAvail().x;
candidate_glyph(c, width); candidate_glyph(c, width);
@@ -1573,10 +1921,14 @@ void evolution_window(const PanelView& v, FormBuffers& form, PanelActions& a, bo
ImGui::TextWrapped( ImGui::TextWrapped(
"%s", cause == network::CellularDeathReason::starved ? "Your cell starved" "%s", cause == network::CellularDeathReason::starved ? "Your cell starved"
: cause == network::CellularDeathReason::engulfed ? "Your cell was engulfed" : cause == network::CellularDeathReason::engulfed ? "Your cell was engulfed"
: cause == network::CellularDeathReason::emerged ? "Your organism emerged"
: "Your cell died"); : "Your cell died");
ImGui::PopFont(); ImGui::PopFont();
disabled_wrapped(cause == network::CellularDeathReason::starved disabled_wrapped(cause == network::CellularDeathReason::starved
? "Its reserve could not pay upkeep. Its body became food." ? "Its reserve could not pay upkeep. Its body became food."
: cause == network::CellularDeathReason::emerged
? "It left the cellular region for the world, taking all its "
"matter with it. This cellular life is complete."
: "Its body became food for another cell."); : "Its body became food for another cell.");
ImGui::TextWrapped("Your descendants live on as wildlife. You return as a new " ImGui::TextWrapped("Your descendants live on as wildlife. You return as a new "
"primitive cell."); "primitive cell.");
@@ -1602,8 +1954,12 @@ void evolution_window(const PanelView& v, FormBuffers& form, PanelActions& a, bo
ImGui::PushFont(nullptr, px(24)); ImGui::PushFont(nullptr, px(24));
ImGui::TextUnformatted("Shape this life"); ImGui::TextUnformatted("Shape this life");
ImGui::PopFont(); ImGui::PopFont();
disabled_wrapped("Your feeding earned one change. Each trades a capability against upkeep " const bool named = !offer->candidates.empty() &&
"and body mass. Buds inherit what you choose."); named_mutation(diagnostics(v), offer->candidates.front()) != nullptr;
disabled_wrapped(named ? "Your play earned one change. Each has a benefit and a cost; what "
"you do makes some more likely to appear."
: "Your feeding earned one change. Each trades a capability against "
"upkeep and body mass. Buds inherit what you choose.");
const auto count = static_cast<int>(offer->candidates.size()); const auto count = static_cast<int>(offer->candidates.size());
const int columns = compact ? 1 : std::max(1, count); const int columns = compact ? 1 : std::max(1, count);
if (ImGui::BeginTable("offers", columns, ImGuiTableFlags_SizingStretchSame)) { if (ImGui::BeginTable("offers", columns, ImGuiTableFlags_SizingStretchSame)) {
@@ -1643,16 +1999,23 @@ void hud_map(const PanelView& v, FormBuffers& form, bool compact) {
const auto& scene = *v.cellular_scene; const auto& scene = *v.cellular_scene;
const auto& io = ImGui::GetIO(); const auto& io = ImGui::GetIO();
const float width = px(compact ? 184.0F : 210.0F); const float width = px(compact ? 184.0F : 210.0F);
ImGui::SetNextWindowPos({io.DisplaySize.x - (compact ? px(12) : eyepiece_clearance()), px(126)}, place_hud_panel(form.map_placement,
ImGuiCond_Always, {1, 0}); {io.DisplaySize.x - (compact ? px(12) : eyepiece_clearance()) - width, px(126)},
ImGui::SetNextWindowSizeConstraints({width, 0}, {width, io.DisplaySize.y - px(200)}); {width, form.map_minimized ? collapsed_height()
: std::min(px(compact ? 192.0F : 300.0F),
io.DisplaySize.y - px(200))},
form.map_minimized);
ImGui::Begin("Nearby", nullptr, ImGui::Begin("Nearby", nullptr,
hud_flags | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_AlwaysAutoResize); (hud_flags & ~ImGuiWindowFlags_NoResize) | ImGuiWindowFlags_NoTitleBar |
panel_heading("Nearby", form.map_minimized); ImGuiWindowFlags_NoScrollbar);
panel_heading("Nearby", form.map_minimized, form.map_placement);
if (form.map_minimized) { if (form.map_minimized) {
ImGui::End(); ImGui::End();
return; return;
} }
begin_hud_body("##body");
if (const auto* s = v.cellular_scene; s && s->region_cells != 0)
ImGui::TextDisabled("%zu cells in this region", s->region_cells);
auto at = ImGui::GetCursorScreenPos(); auto at = ImGui::GetCursorScreenPos();
const float available = ImGui::GetContentRegionAvail().x; const float available = ImGui::GetContentRegionAvail().x;
const float side = std::min(available, px(compact ? 96.0F : 178.0F)); const float side = std::min(available, px(compact ? 96.0F : 178.0F));
@@ -1725,6 +2088,7 @@ void hud_map(const PanelView& v, FormBuffers& form, bool compact) {
ImGui::SetTooltip( ImGui::SetTooltip(
"Camera-centred local map. Unseen space is unknown.\nRings: pools. Dots: nutrients. " "Camera-centred local map. Unseen space is unknown.\nRings: pools. Dots: nutrients. "
"Triangles: cells.\nLocal +Y is up; planetary north is not defined."); "Triangles: cells.\nLocal +Y is up; planetary north is not defined.");
end_hud_body();
ImGui::End(); ImGui::End();
} }
void cellular(const PanelView& v, FormBuffers& form, PanelActions& a) { void cellular(const PanelView& v, FormBuffers& form, PanelActions& a) {
+18 -1
View File
@@ -71,15 +71,31 @@ struct CellularScene {
// Camera mapping for the local observation map; no undiscovered world state. // Camera mapping for the local observation map; no undiscovered world state.
client::WorldPoint camera_centre{}; client::WorldPoint camera_centre{};
bool stale{}; bool stale{};
// The region's walls on screen (liquid regions, from the perceived current configuration),
// whether the owner's cell is against one, and how many cells the region holds.
bool region{};
float region_left{}, region_top{}, region_right{}, region_bottom{};
bool at_edge{};
std::size_t region_cells{};
}; };
// Notice layout (logical pixels); the window name is the prefix plus the notice id. // Notice layout (logical pixels); the window name is the prefix plus the notice id.
inline constexpr float notice_width = 320, notice_close_width = 22; inline constexpr float notice_width = 320, notice_close_width = 22;
inline constexpr const char* notice_window_prefix = "##notice"; inline constexpr const char* notice_window_prefix = "##notice";
// Text-field storage for the connect form (bounded; never persisted). // HUD positions are client-session preferences in normalized viewport coordinates.
struct HudPanelPlacement {
std::optional<std::pair<float, float>> anchor;
// Expanded size in unscaled UI units; collapse never overwrites it.
std::optional<std::pair<float, float>> size;
std::pair<float, float> drag_origin{};
std::pair<float, float> requested_size{};
};
// Connect form fields and presentation preferences; never persisted.
struct FormBuffers { struct FormBuffers {
bool engineering{}; bool engineering{};
bool evolution_open{}; // The mutation window (E or the callout opens it). bool evolution_open{}; // The mutation window (E or the callout opens it).
bool notes_minimized{}, vitals_minimized{}, map_minimized{}; bool notes_minimized{}, vitals_minimized{}, map_minimized{};
HudPanelPlacement notes_placement, vitals_placement, map_placement;
bool bud_become{}; // Rules 13: the next bud is the player's cell.
CellularControls cellular_controls; CellularControls cellular_controls;
std::array<char, client::max_field_bytes> endpoint{}, server_name{}, authority{}, grants{}; std::array<char, client::max_field_bytes> endpoint{}, server_name{}, authority{}, grants{};
void load(const client::ConnectForm& form); void load(const client::ConnectForm& form);
@@ -126,6 +142,7 @@ struct PanelActions {
std::optional<std::pair<std::uint32_t, std::uint32_t>> feed_patch; std::optional<std::pair<std::uint32_t, std::uint32_t>> feed_patch;
bool stop_feeding{}; bool stop_feeding{};
std::optional<CellAction> cell_action; std::optional<CellAction> cell_action;
bool cell_become{}; // With a bud: continue as it (v14).
std::optional<MutationChoice> mutation; std::optional<MutationChoice> mutation;
bool restart_life{}, keep_unknown{}; bool restart_life{}, keep_unknown{};
}; };
+24 -11
View File
@@ -262,13 +262,17 @@ class RemoteSession {
[[nodiscard]] const CellularPlay& cellular_play() const noexcept { [[nodiscard]] const CellularPlay& cellular_play() const noexcept {
return cellular_play_; return cellular_play_;
} }
[[nodiscard]] bool request_cellular(CellAction kind, MutationChoice choice = {}) { [[nodiscard]] bool request_cellular(CellAction kind, MutationChoice choice = {},
bool become = false) {
const auto lead = cellular_lead_.lead(); const auto lead = cellular_lead_.lead();
const auto tick = // A tick takes one action per account: never one a movement already named (movement
kind == CellAction::mutation // runs ahead of the lead after the lead shrinks).
const auto tick = kind == CellAction::mutation
? server_tick_ ? server_tick_
: server_tick_ + lead + (sent_tick_ && *sent_tick_ == server_tick_ ? 1 : 0); : std::max(server_tick_ + lead +
if (!cellular_trial_ || !cellular_play_.queue(kind, tick, choice)) (sent_tick_ && *sent_tick_ == server_tick_ ? 1 : 0),
cellular_sent_tick_ + 1);
if (!cellular_trial_ || !cellular_play_.queue(kind, tick, choice, become))
return false; return false;
action_check_at_ = {}; action_check_at_ = {};
if (kind != CellAction::mutation) if (kind != CellAction::mutation)
@@ -501,8 +505,9 @@ class RemoteSession {
return false; return false;
client::RegionSessionClientConfig config; client::RegionSessionClientConfig config;
if (cellular_trial_) if (cellular_trial_)
// Rules 12: v13 is v12 (deposits, light, producers) plus liquid motion and brake. // Rules 13: v14 is v13 (deposits, light, producers, liquid motion and brake) plus the
config.protocol_version = network::session_protocol_v13; // revamp: become, emerge, exclusions, catalog offers and the body block.
config.protocol_version = network::session_protocol_v14;
const auto route = routes_.find(target_region_); const auto route = routes_.find(target_region_);
config.transport = route != routes_.end() ? route->second : transport_; config.transport = route != routes_.end() ? route->second : transport_;
if (ticket_) { // A handoff: the ticket replaces a grant, once. if (ticket_) { // A handoff: the ticket replaces a grant, once.
@@ -628,13 +633,19 @@ class RemoteSession {
// trails it by the replication delay, so schedule by the adaptive lead. // trails it by the replication delay, so schedule by the adaptive lead.
// Strictly increasing even when the lead shrinks: one movement per tick. // Strictly increasing even when the lead shrinks: one movement per tick.
const auto tick = std::max(server_tick_ + cellular_lead_.lead(), cellular_sent_tick_ + 1); const auto tick = std::max(server_tick_ + cellular_lead_.lead(), cellular_sent_tick_ + 1);
// A queued discrete action owns its tick; movement resumes after it is sent.
if (const auto& p = cellular_play_.pending(); p && p->state == CellActionState::queued &&
p->kind != CellAction::mutation &&
p->tick <= tick)
return;
const auto steering = steer_cellular(cellular_controls_, intention, cellular_perception(), const auto steering = steer_cellular(cellular_controls_, intention, cellular_perception(),
organisms_.current(), cellular_feed_target_); organisms_.current(), cellular_feed_target_);
cellular_feed_target_ = steering.patch; cellular_feed_target_ = steering.patch;
const auto id = cellular_play_.allocate_id(); const auto id = cellular_play_.allocate_id();
if (id == 0 || !client_->send_cellular_action( if (id == 0 || !client_->send_cellular_action(
id, tick, steering.intention.move_x, steering.intention.move_y, id, tick, steering.intention.move_x, steering.intention.move_y,
cellular_feed_target_, false, false, steering.intention.brake)) cellular_feed_target_, false, false, steering.intention.brake, false,
false, cellular_controls_.exclude))
return; return;
sent_tick_ = server_tick_; sent_tick_ = server_tick_;
cellular_sent_tick_ = tick; cellular_sent_tick_ = tick;
@@ -652,12 +663,14 @@ class RemoteSession {
bool sent = false; bool sent = false;
if (p.kind == CellAction::mutation) { if (p.kind == CellAction::mutation) {
sent = client_->send_cellular_mutation(p.id, p.tick, p.choice.life, p.choice.event, sent = client_->send_cellular_mutation(p.id, p.tick, p.choice.life, p.choice.event,
p.choice.offer_tick, p.choice.operator_id); p.choice.offer_tick, p.choice.operator_id,
p.choice.become);
} else if (p.state == CellActionState::queued) { } else if (p.state == CellActionState::queued) {
if (p.tick > server_tick_ + cellular_lead_.lead()) if (p.tick > server_tick_ + cellular_lead_.lead())
return; // Do not replace a movement/feeding intention already sent this tick. return; // Do not replace a movement/feeding intention already sent this tick.
sent = client_->send_cellular_action( sent = client_->send_cellular_action(
p.id, p.tick, 0, 0, {}, p.kind == CellAction::engulf, p.kind == CellAction::bud); p.id, p.tick, 0, 0, {}, p.kind == CellAction::engulf, p.kind == CellAction::bud,
false, p.become, p.kind == CellAction::emerge, cellular_controls_.exclude);
if (sent) { if (sent) {
sent_tick_ = server_tick_; // The discrete intention owns this tick's target. sent_tick_ = server_tick_; // The discrete intention owns this tick's target.
cellular_sent_tick_ = std::max(cellular_sent_tick_, p.tick); cellular_sent_tick_ = std::max(cellular_sent_tick_, p.tick);
@@ -1010,7 +1023,7 @@ class RemoteSession {
[[nodiscard]] const CellularPlay& cellular_play() const noexcept { [[nodiscard]] const CellularPlay& cellular_play() const noexcept {
return cellular_play_; return cellular_play_;
} }
[[nodiscard]] bool request_cellular(CellAction, MutationChoice = {}) { [[nodiscard]] bool request_cellular(CellAction, MutationChoice = {}, bool = false) {
return false; return false;
} }
[[nodiscard]] bool restart_cellular() { [[nodiscard]] bool restart_cellular() {
+167 -31
View File
@@ -42,9 +42,16 @@ class CellularBridge {
if (!options.complete()) if (!options.complete())
return fail("error cellular-session-config"); return fail("error cellular-session-config");
CellularBridge bridge; CellularBridge bridge;
// A fixed --session-window must be open now; a database window (ADR-0087 amendment)
// may open, close and reopen while the region runs.
if (!options.window_from_database) {
const auto window = server::SessionWindow::open(options.session_window, wall_seconds()); const auto window = server::SessionWindow::open(options.session_window, wall_seconds());
if (!window) if (!window)
return fail("error cellular-session-window"); return fail("error cellular-session-window");
bridge.window_ = *window;
}
bridge.window_from_database_ = options.window_from_database;
bridge.key_ = key;
const auto colon = options.listen.rfind(':'); const auto colon = options.listen.rfind(':');
std::uint16_t port{}; std::uint16_t port{};
if (colon == std::string::npos || if (colon == std::string::npos ||
@@ -85,7 +92,6 @@ class CellularBridge {
std::copy(issuer.begin(), issuer.end(), public_key.begin()); std::copy(issuer.begin(), issuer.end(), public_key.begin());
config.issuer_keys.push_back({1, public_key}); config.issuer_keys.push_back({1, public_key});
bridge.window_ = *window;
bridge.slot_ = std::make_unique<server::PgSlot>(pg, std::chrono::seconds{2}); bridge.slot_ = std::make_unique<server::PgSlot>(pg, std::chrono::seconds{2});
const auto lease = [&host] { return host.authority(); }; const auto lease = [&host] { return host.authority(); };
bridge.control_ = bridge.control_ =
@@ -110,9 +116,9 @@ class CellularBridge {
config.select_cellular_mutation = [&host](const network::AccountId& account, config.select_cellular_mutation = [&host](const network::AccountId& account,
std::uint64_t generation, std::uint64_t generation,
const network::CellularMutationAction& m) { const network::CellularMutationAction& m) {
const auto reply = const auto reply = host.select_mutation(
host.select_mutation(account.bytes, generation, m.action_id, account.bytes, generation, m.action_id,
{m.life_identity, m.event_index, m.offer_tick, m.operator_id}); {m.life_identity, m.event_index, m.offer_tick, m.operator_id, m.become});
server::CellularMutationAnswer answer{ server::CellularMutationAnswer answer{
server::admit_status(reply.status), reply.tick, {}}; server::admit_status(reply.status), reply.tick, {}};
if (reply.outcome) if (reply.outcome)
@@ -126,15 +132,25 @@ class CellularBridge {
: "error cellular-session-config"); : "error cellular-session-config");
bridge.sessions_ = std::move(*sessions); bridge.sessions_ = std::move(*sessions);
bridge.sessions_->set_default_interest({0, 0, 0, 7}); bridge.sessions_->set_default_interest({0, 0, 0, 7});
// A database window admits nobody until it has been read.
if (bridge.window_from_database_)
bridge.sessions_->set_admission(false);
std::printf("cellular listening %u\n", static_cast<unsigned>(bridge.sessions_->port())); std::printf("cellular listening %u\n", static_cast<unsigned>(bridge.sessions_->port()));
return std::optional<CellularBridge>{std::move(bridge)}; return std::optional<CellularBridge>{std::move(bridge)};
} }
// Applies the session window: while it is closed every Hello is refused, and closing
// closes the open sessions.
[[nodiscard]] bool accepting(std::uint64_t now_seconds) { [[nodiscard]] bool accepting(std::uint64_t now_seconds) {
const bool open = window_ && window_->accepting(now_seconds); if (window_from_database_)
if (!open && !shutdown_) { read_window(now_seconds);
const bool open = window_from_database_ ? feed_.accepting(now_seconds)
: window_ && window_->accepting(now_seconds);
if (open != sessions_->admitting()) {
sessions_->set_admission(open);
if (!open)
sessions_->shutdown(std::chrono::steady_clock::now()); sessions_->shutdown(std::chrono::steady_clock::now());
shutdown_ = true; std::printf("cellular sessions %s\n", open ? "admitted" : "closed");
} }
return open; return open;
} }
@@ -206,6 +222,12 @@ class CellularBridge {
return result; return result;
}; };
sessions_->replicate(tick, source); sessions_->replicate(tick, source);
// A tuning adoption changes what a bud costs, so cached costs hold for one rules set.
if (auto rules = server::encode_cellular_revamp_rules(state.revamp_rules());
rules != bud_rules_) {
bud_rules_ = std::move(rules);
bud_costs_.clear();
}
for (const auto& life : state.lives()) { for (const auto& life : state.lives()) {
if (life.presence == server::CellularPresence::suspended) if (life.presence == server::CellularPresence::suspended)
continue; continue;
@@ -219,7 +241,7 @@ class CellularBridge {
diagnostics.reserve_energy_pj = life.reserve.energy.value; diagnostics.reserve_energy_pj = life.reserve.energy.value;
for (std::size_t i = 0; i < diagnostics.reserve_matter_fg.size(); ++i) for (std::size_t i = 0; i < diagnostics.reserve_matter_fg.size(); ++i)
diagnostics.reserve_matter_fg[i] = life.reserve.matter[i].value; diagnostics.reserve_matter_fg[i] = life.reserve.matter[i].value;
if (const auto cost = bud_cost_for(state, life.identity.genome)) { if (const auto cost = bud_cost_for(state, life)) {
diagnostics.bud_cost_energy_pj = cost->energy.value; diagnostics.bud_cost_energy_pj = cost->energy.value;
for (std::size_t i = 0; i < diagnostics.bud_cost_matter_fg.size(); ++i) for (std::size_t i = 0; i < diagnostics.bud_cost_matter_fg.size(); ++i)
diagnostics.bud_cost_matter_fg[i] = cost->matter[i].value; diagnostics.bud_cost_matter_fg[i] = cost->matter[i].value;
@@ -262,8 +284,20 @@ class CellularBridge {
} }
// ADR-0129 (v10): what an engulf or bud intention did this tick. // ADR-0129 (v10): what an engulf or bud intention did this tick.
diagnostics.engulf = engulf_result(feedback->engulf); diagnostics.engulf = engulf_result(feedback->engulf);
diagnostics.bud = feedback->bud ? bud_outcome(*feedback->bud) const auto bud = feedback->bud;
: network::CellularBudOutcome::not_requested; diagnostics.bud =
bud ? bud_outcome(*bud) : network::CellularBudOutcome::not_requested;
// Rules 13 (v14): what held growth back and the tick's flows by channel.
diagnostics.growth_limit = feedback->growth_limit;
const auto channels = [](const accounting::Inventory& value) {
return std::array<std::uint64_t, 5>{
value.energy.value, value.matter[0].value, value.matter[1].value,
value.matter[2].value, value.matter[3].value};
};
diagnostics.collected = channels(feedback->collected);
diagnostics.into_growth = channels(feedback->into_growth);
diagnostics.burned = channels(feedback->burned);
diagnostics.burned[0] = 0; // Energy is spent, never burned.
} }
// Rules 12 (v13): the authoritative motion state and the region's currents, from // Rules 12 (v13): the authoritative motion state and the region's currents, from
// which the client regenerates the identical flow field. // which the client regenerates the identical flow field.
@@ -284,6 +318,45 @@ class CellularBridge {
c.min_speed_um_per_s, c.min_speed_um_per_s,
c.max_speed_um_per_s}; c.max_speed_um_per_s};
} }
// Rules 13 (v14): the body block. Older sessions never see it.
diagnostics.members = life.revamp.members;
diagnostics.growth_per_thousand = static_cast<std::uint16_t>(
std::min<std::uint32_t>(life.growth.realized_per_thousand, 1000));
if (const auto genome = state.archive().find(life.identity.genome)) {
const auto& traits = genome->cellular_traits();
const auto t = traits.value_or(biology::CellularTraits{});
const std::array<std::uint16_t, 20> fields{
t.density, t.upkeep_efficiency, t.growth_speed, t.collection[0],
t.collection[1], t.collection[2], t.collection[3], t.collection[4],
t.burn[0], t.burn[1], t.burn[2], t.burn[3],
t.engulf_capacity, t.kill_absorption, t.litter, t.recipe[0],
t.recipe[1], t.recipe[2], t.recipe[3], t.adhesion};
if (traits)
diagnostics.traits = fields;
if (state.rules_version() >= server::cellular_lives_revamp_rules) {
const auto& rules = state.revamp_rules();
diagnostics.emerge_members = static_cast<std::uint16_t>(
std::min<std::uint32_t>(rules.emerge_members, 0xFFFF));
diagnostics.can_emerge = server::cellular_can_emerge(life, rules);
diagnostics.split_ready =
life.revamp.members == 1 &&
life.growth.realized_per_thousand >= rules.split_min_growth;
if (feedback != state.last_tick_feedback().end() &&
feedback->life_id == life.identity.life && feedback->tick == tick)
diagnostics.exclude = feedback->exclude;
const auto burn = biology::cellular_burn(
rules.burn_pj_per_kfg,
traits ? t.burn : std::array<std::uint16_t, 4>{100, 100, 100, 100},
diagnostics.exclude);
diagnostics.payable_energy_pj =
biology::cellular_payable_energy(life.reserve, burn, false);
} else {
diagnostics.payable_energy_pj = life.reserve.energy.value;
}
}
for (std::size_t c = 0; c < life.body.matter.size(); ++c)
diagnostics.total_mass_fg +=
life.body.matter[c].value + life.reserve.matter[c].value;
view.diagnostics = diagnostics; view.diagnostics = diagnostics;
view.patches.reserve(perceived->size()); view.patches.reserve(perceived->size());
// ADR-0136 (rules 8): pools and bubbles go out as v11 deposits, the nearest 512 to // ADR-0136 (rules 8): pools and bubbles go out as v11 deposits, the nearest 512 to
@@ -311,9 +384,7 @@ class CellularBridge {
const auto before = deposit_stock_.find(patch.id); const auto before = deposit_stock_.find(patch.id);
deposit.drained = before != deposit_stock_.end() && deposit.drained = before != deposit_stock_.end() &&
(patch.available.energy.value < before->second.energy.value || (patch.available.energy.value < before->second.energy.value ||
std::ranges::any_of( std::ranges::any_of(std::array{0, 1, 2, 3}, [&](int c) {
std::array{0, 1, 2, 3},
[&](int c) {
const auto i = static_cast<std::size_t>(c); const auto i = static_cast<std::size_t>(c);
return patch.available.matter.at(i).value < return patch.available.matter.at(i).value <
before->second.matter.at(i).value; before->second.matter.at(i).value;
@@ -450,6 +521,10 @@ class CellularBridge {
return l.identity.life; return l.identity.life;
}) != state.lives().end()) }) != state.lives().end())
continue; continue;
// Rules 13: control moved to another life (succession, or a merge into an organism).
if (std::ranges::find(state.lives(), account, &server::CellularOwnedLife::account) !=
state.lives().end())
continue;
const auto corpse = const auto corpse =
std::ranges::find(state.corpses(), life_id, &server::CellularOwnedCorpse::life_id); std::ranges::find(state.corpses(), life_id, &server::CellularOwnedCorpse::life_id);
if (corpse == state.corpses().end()) if (corpse == state.corpses().end())
@@ -458,6 +533,8 @@ class CellularBridge {
? network::CellularDeathReason::starved ? network::CellularDeathReason::starved
: corpse->cause == biology::CellularDeathCause::engulfed : corpse->cause == biology::CellularDeathCause::engulfed
? network::CellularDeathReason::engulfed ? network::CellularDeathReason::engulfed
: corpse->cause == biology::CellularDeathCause::emerged
? network::CellularDeathReason::emerged
: network::CellularDeathReason::unrecorded; : network::CellularDeathReason::unrecorded;
static_cast<void>(sessions_->send_life_ended(network::AccountId{account}, static_cast<void>(sessions_->send_life_ended(network::AccountId{account},
{corpse->died_tick, life_id, cause})); {corpse->died_tick, life_id, cause}));
@@ -506,17 +583,23 @@ class CellularBridge {
std::uint64_t tick) { std::uint64_t tick) {
const network::AccountId account{life.account}; const network::AccountId account{life.account};
const auto session = sessions_->holder(account); const auto session = sessions_->holder(account);
const auto& progress = life.mutation; // Rules 13 offers are catalog offers (v14 only); earlier rules use the operator offer.
const bool named = state.rules_version() >= server::cellular_lives_revamp_rules;
const bool pending = named ? life.revamp.offer.count != 0 : life.mutation.offer.has_value();
const SentOffer current{life.account, session.value_or(0), life.identity.life, const SentOffer current{life.account, session.value_or(0), life.identity.life,
progress.offer ? progress.event_index : 0, !pending ? 0
progress.offer ? progress.offer_tick : 0}; : named ? life.revamp.offer.event_index
: life.mutation.event_index,
!pending ? 0
: named ? life.revamp.offer.offer_tick
: life.mutation.offer_tick};
auto sent = std::ranges::find(offers_, life.account, &SentOffer::account); auto sent = std::ranges::find(offers_, life.account, &SentOffer::account);
if (sent != offers_.end() && *sent == current) if (sent != offers_.end() && *sent == current)
return; return;
if (!session || (!progress.offer && sent == offers_.end())) if (!session || (!pending && sent == offers_.end()))
return; // Nothing to show, or no one to show it to. return; // Nothing to show, or no one to show it to.
if (!sessions_->send_mutation_offer(account, server::offer_view(state, life, tick))) if (!sessions_->send_mutation_offer(account, server::offer_view(state, life, tick), named))
return; // Not a v10 owner (or the stream refused): retried on a later tick. return; // Not a v10 (v14) owner (or the stream refused): retried on a later tick.
if (sent != offers_.end()) if (sent != offers_.end())
*sent = current; *sent = current;
else else
@@ -527,19 +610,18 @@ class CellularBridge {
} }
private: private:
// ADR-0129 amendment: a genome's bud cost is pure for this region's temperature, and // The parent/plan charge is pure at this region's temperature and fixed rules.
// deriving it scans up to a thousand bodies, so it is computed once per genome. // Internal-cell costs depend on the current body and are recomputed.
std::optional<accounting::Inventory> bud_cost_for(const server::CellularLives& state, std::optional<accounting::Inventory> bud_cost_for(const server::CellularLives& state,
std::uint64_t genome_id) { const server::CellularOwnedLife& life) {
if (const auto known = bud_costs_.find(genome_id); known != bud_costs_.end()) if (life.revamp.members > 1)
return state.budding_cost(life.identity.life);
const auto key = std::pair{life.identity.genome, server::cellular_offspring_genome(life)};
if (const auto known = bud_costs_.find(key); known != bud_costs_.end())
return known->second; return known->second;
const auto genome = state.archive().find(genome_id);
if (!genome)
return std::nullopt;
if (bud_costs_.size() >= 4096) if (bud_costs_.size() >= 4096)
bud_costs_.clear(); // Bounded: recomputing is only slower. bud_costs_.clear(); // Bounded: recomputing is only slower.
return bud_costs_[genome_id] = return bud_costs_[key] = state.budding_cost(life.identity.life);
biology::bud_cost(*genome, state.ambient_temperature_millikelvin());
} }
static std::uint64_t wall_seconds() { static std::uint64_t wall_seconds() {
return static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::seconds>( return static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::seconds>(
@@ -554,12 +636,65 @@ class CellularBridge {
std::puts(message); std::puts(message);
return std::nullopt; return std::nullopt;
} }
// The region's newest window record, every 5 s. A failed read keeps the current window,
// which still closes at its own deadline.
void read_window(std::uint64_t now_seconds) {
constexpr std::chrono::seconds interval{5};
const auto now = std::chrono::steady_clock::now();
if (now < next_window_read_)
return;
next_window_read_ = now + interval;
auto* db = slot_->get();
if (db == nullptr)
return;
const std::array<std::string, 2> parameters{std::to_string(key_.world),
std::to_string(key_.region)};
const auto rows =
db->query("SELECT activation_id, floor(extract(epoch FROM expires_at))::bigint FROM "
"evolution.load_session_window_v1($1::evolution.u64, $2::evolution.u64)",
parameters, std::chrono::milliseconds{1000});
if (!rows) {
slot_->broken();
return;
}
std::optional<server::SessionWindowFeed::Record> record;
if (!rows->empty() && rows->front().size() == 2 && rows->front()[0]) {
record = server::SessionWindowFeed::Record{*rows->front()[0], std::nullopt};
if (const auto& expiry = rows->front()[1]) {
std::uint64_t value{};
const auto [end, ec] =
std::from_chars(expiry->data(), expiry->data() + expiry->size(), value);
if (ec == std::errc{} && end == expiry->data() + expiry->size())
record->expires_at = value;
}
}
switch (feed_.observe(record, now_seconds)) {
case server::SessionWindowFeed::Change::opened:
std::printf("cellular window opened activation=%s expires=%llu\n",
feed_.window()->activation_id().c_str(),
static_cast<unsigned long long>(feed_.window()->deadline_seconds()));
break;
case server::SessionWindowFeed::Change::closed:
std::puts("cellular window closed");
break;
case server::SessionWindowFeed::Change::refused:
std::printf("cellular window refused activation=%s\n",
record ? record->activation_id.c_str() : "");
break;
case server::SessionWindowFeed::Change::none:
break;
}
}
std::unique_ptr<server::PgSlot> slot_; std::unique_ptr<server::PgSlot> slot_;
std::unique_ptr<server::PostgresControlLedger> control_; std::unique_ptr<server::PostgresControlLedger> control_;
std::unique_ptr<server::PostgresActionLedger> actions_; std::unique_ptr<server::PostgresActionLedger> actions_;
std::unique_ptr<server::RegionSessions> sessions_; std::unique_ptr<server::RegionSessions> sessions_;
std::optional<server::SessionWindow> window_; std::optional<server::SessionWindow> window_; // A fixed --session-window.
bool window_from_database_{};
persistence::RegionKey key_{};
server::SessionWindowFeed feed_;
std::chrono::steady_clock::time_point next_window_read_{};
std::optional<std::uint64_t> replicated_tick_; std::optional<std::uint64_t> replicated_tick_;
struct SentOffer { struct SentOffer {
server::LifeAccount account{}; server::LifeAccount account{};
@@ -567,10 +702,11 @@ class CellularBridge {
friend bool operator==(const SentOffer&, const SentOffer&) = default; friend bool operator==(const SentOffer&, const SentOffer&) = default;
}; };
std::vector<SentOffer> offers_; // Last offer view sent to each owner. std::vector<SentOffer> offers_; // Last offer view sent to each owner.
std::map<std::uint64_t, std::optional<accounting::Inventory>> bud_costs_; // By genome. std::map<std::pair<std::uint64_t, std::uint64_t>, std::optional<accounting::Inventory>>
bud_costs_;
std::vector<std::uint8_t> bud_rules_; // The rules bud_costs_ were computed under.
// ADR-0136: deposit stocks seen at the last replicated tick, and this tick's. // ADR-0136: deposit stocks seen at the last replicated tick, and this tick's.
std::map<std::uint32_t, accounting::Inventory> deposit_stock_, seen_stock_; std::map<std::uint32_t, accounting::Inventory> deposit_stock_, seen_stock_;
std::vector<std::pair<server::LifeAccount, std::uint64_t>> owned_; // At last replication. std::vector<std::pair<server::LifeAccount, std::uint64_t>> owned_; // At last replication.
bool shutdown_{};
}; };
} // namespace evo::server_app } // namespace evo::server_app
+10 -3
View File
@@ -53,6 +53,10 @@
namespace evo::server_app { namespace evo::server_app {
struct M10Options { struct M10Options {
std::string listen, certificate, key, issuer, environment, session_window; std::string listen, certificate, key, issuer, environment, session_window;
// ADR-0087 amendment: `--session-window-source db` reads the window from
// evolution.load_session_window_v1 every few seconds instead of --session-window
// (cellular profile only). Exactly one of the two is given.
bool window_from_database{};
// M10.5c: dev only, 60..14400 s; 0 keeps the default (300 s, ADR-0091). // M10.5c: dev only, 60..14400 s; 0 keeps the default (300 s, ADR-0091).
std::uint64_t max_grant_lifetime{}; std::uint64_t max_grant_lifetime{};
// M10.9 (ADR-0097, dev only): `--m10-load-governor off` keeps measuring and exposing the // M10.9 (ADR-0097, dev only): `--m10-load-governor off` keeps measuring and exposing the
@@ -68,15 +72,16 @@ struct M10Options {
std::vector<std::string> life_routes; std::vector<std::string> life_routes;
[[nodiscard]] bool session_any() const noexcept { [[nodiscard]] bool session_any() const noexcept {
return !listen.empty() || !certificate.empty() || !key.empty() || !issuer.empty() || return !listen.empty() || !certificate.empty() || !key.empty() || !issuer.empty() ||
!environment.empty() || !session_window.empty() || max_grant_lifetime != 0 || !environment.empty() || !session_window.empty() || window_from_database ||
!area.empty() || !handoff_key.empty() || !neighbours.empty() || !load_governor; max_grant_lifetime != 0 || !area.empty() || !handoff_key.empty() ||
!neighbours.empty() || !load_governor;
} }
[[nodiscard]] bool any() const noexcept { [[nodiscard]] bool any() const noexcept {
return session_any() || !life_routes.empty(); return session_any() || !life_routes.empty();
} }
[[nodiscard]] bool complete() const noexcept { [[nodiscard]] bool complete() const noexcept {
return !listen.empty() && !certificate.empty() && !key.empty() && !issuer.empty() && return !listen.empty() && !certificate.empty() && !key.empty() && !issuer.empty() &&
!environment.empty() && !session_window.empty(); !environment.empty() && (session_window.empty() == window_from_database);
} }
}; };
// Actions are handed to the host as soon as they are scheduled (at most 8 ticks ahead). // Actions are handed to the host as soon as they are scheduled (at most 8 ticks ahead).
@@ -117,6 +122,8 @@ template <typename Host> class M10Bridge {
M10Bridge bridge; M10Bridge bridge;
if (!o.any()) if (!o.any())
return bridge; return bridge;
if (o.window_from_database)
return fail("error m10-window-source"); // The cellular profile only.
const auto window = server::SessionWindow::open(o.session_window, wall_seconds()); const auto window = server::SessionWindow::open(o.session_window, wall_seconds());
if (!window) if (!window)
return fail(window.error() == server::SessionWindow::Error::expired return fail(window.error() == server::SessionWindow::Error::expired
+97 -11
View File
@@ -53,8 +53,10 @@
// --primitive-* flags enable the v5 new-life listener; biology ticks and genesis // --primitive-* flags enable the v5 new-life listener; biology ticks and genesis
// provisioning remain disabled. // provisioning remain disabled.
#include "evo/biology/founder.hpp" #include "evo/biology/founder.hpp"
#include "evo/persistence/sha256.hpp"
#include "evo/processes/development_opening.hpp" #include "evo/processes/development_opening.hpp"
#include "evo/server/cellular_session_batch.hpp" #include "evo/server/cellular_session_batch.hpp"
#include "evo/server/lifecycle/cellular_admin_view.hpp"
#include "evo/server/lifecycle/cellular_schedule.hpp" #include "evo/server/lifecycle/cellular_schedule.hpp"
#include "evo/server/lifecycle/primitive_lives.hpp" #include "evo/server/lifecycle/primitive_lives.hpp"
#include "evo/server/lifecycle/wildlife_controller.hpp" #include "evo/server/lifecycle/wildlife_controller.hpp"
@@ -262,6 +264,8 @@ std::optional<Options> parse(int argc, char** argv) {
o.m10.environment = value; o.m10.environment = value;
else if (flag == "--session-window") else if (flag == "--session-window")
o.m10.session_window = value; o.m10.session_window = value;
else if (flag == "--session-window-source" && value == "db")
o.m10.window_from_database = true;
else if (flag == "--m10-max-grant-lifetime" && n && *n >= 60 && *n <= 14400) else if (flag == "--m10-max-grant-lifetime" && n && *n >= 60 && *n <= 14400)
o.m10.max_grant_lifetime = *n; o.m10.max_grant_lifetime = *n;
else if (flag == "--m10-area") else if (flag == "--m10-area")
@@ -925,7 +929,9 @@ int serve_cellular(Options& o) {
return 2; return 2;
std::unique_ptr<server::OpsServer> ops; std::unique_ptr<server::OpsServer> ops;
if (!o.ops_listen.empty()) { if (!o.ops_listen.empty()) {
auto listening = server::OpsServer::listen(o.ops_listen); // Room for /admin/view (ADR-0182); probes and metrics stay small.
auto listening = server::OpsServer::listen(
o.ops_listen, server::OpsServer::max_configurable_response_bytes);
if (!listening) { if (!listening) {
std::puts("error ops-listen"); std::puts("error ops-listen");
return 2; return 2;
@@ -1032,6 +1038,18 @@ int serve_cellular(Options& o) {
std::printf("cellular commit ticks=%zu ms=%lld handoff_ms=%lld ok=%d\n", std::printf("cellular commit ticks=%zu ms=%lld handoff_ms=%lld ok=%d\n",
flight_ticks, static_cast<long long>(commit_ms), flight_handoff_ms, flight_ticks, static_cast<long long>(commit_ms), flight_handoff_ms,
*landed ? 1 : 0); *landed ? 1 : 0);
if (!*landed) {
// Categories and SQLSTATE only (never server text); -1 when not reported.
const auto& failure = landed->error();
const auto store = failure.store.value_or(persistence::LeaseStoreFailure{});
std::printf("cellular commit failed host=%u publication=%d store=%d "
"sqlstate=%.5s object=%d\n",
static_cast<unsigned>(failure.kind),
failure.publication ? static_cast<int>(*failure.publication) : -1,
failure.store ? static_cast<int>(store.kind) : -1,
failure.store ? store.cause.sqlstate.data() : "-",
failure.object ? static_cast<int>(*failure.object) : -1);
}
if (*landed) { if (*landed) {
host.refuse_births(flight_refusals); host.refuse_births(flight_refusals);
flight_actions.clear(); flight_actions.clear();
@@ -1092,6 +1110,31 @@ int serve_cellular(Options& o) {
counters.checkpoint_age_ms = schedule.status().head_age_us / 1000; counters.checkpoint_age_ms = schedule.status().head_age_us / 1000;
return {200, server::render_metrics(paced, counters)}; return {200, server::render_metrics(paced, counters)};
} }
// ADR-0182: the admin portal's read-only region view. The port admits only
// Prometheus and the admin API (NetworkPolicy).
if (path == "/admin/view") {
const auto* state = host.state();
if (!current.ready || state == nullptr)
return {503, "not ready\n"};
const auto online = [&](const server::LifeAccount& account) {
network::AccountId id;
id.bytes = account;
return bridge->sessions().holder(id).has_value();
};
// The digest tuning revisions are adopted by (ADR-0182 section 13).
std::string rules_sha256;
if (state->rules_version() >= server::cellular_lives_revamp_rules)
if (const auto digest = persistence::sha256(
server::encode_cellular_revamp_rules(state->revamp_rules())))
for (const auto byte : *digest) {
constexpr std::string_view digits = "0123456789abcdef";
rules_sha256.push_back(digits[byte >> 4U]);
rules_sha256.push_back(digits[byte & 0x0FU]);
}
return {200,
server::render_cellular_admin_view(*state, online, {}, rules_sha256),
"application/json"};
}
return {404, "not found\n"}; return {404, "not found\n"};
}; };
ops->serve(handler); ops->serve(handler);
@@ -1131,9 +1174,11 @@ int serve_cellular(Options& o) {
[[maybe_unused]] const auto changed = host.set_population_mode(want_population); [[maybe_unused]] const auto changed = host.set_population_mode(want_population);
state = host.state(); state = host.state();
} }
const bool needed = state && (player_present || birth_waiting || // A queued admin command needs a tick too: an empty region must still take a spawn.
server::cellular_unattended_tick_needed(*state) || const bool needed =
status.ecological_pending_ticks != 0); state &&
(player_present || birth_waiting || server::cellular_unattended_tick_needed(*state) ||
status.ecological_pending_ticks != 0 || !host.unbound_admin_commands().empty());
const auto monotonic_us = [] { const auto monotonic_us = [] {
return static_cast<std::uint64_t>( return static_cast<std::uint64_t>(
std::chrono::duration_cast<std::chrono::microseconds>( std::chrono::duration_cast<std::chrono::microseconds>(
@@ -1184,8 +1229,10 @@ int serve_cellular(Options& o) {
provisional.digest.fill(0xFF); provisional.digest.fill(0xFF);
if (auto created = if (auto created =
server::CellularSessionBatchBuilder::create(candidate, provisional); server::CellularSessionBatchBuilder::create(candidate, provisional);
created) created) {
next.emplace(std::move(*created)); next.emplace(std::move(*created));
next->set_tuning_resolver(host.tuning_resolver());
}
} }
flight_ticks = batch_builder->batch().ticks.size(); flight_ticks = batch_builder->batch().ticks.size();
const auto refusals = batch_builder->refused_births(); const auto refusals = batch_builder->refused_births();
@@ -1290,12 +1337,17 @@ int serve_cellular(Options& o) {
}); });
bridge->dropped(departed, true); bridge->dropped(departed, true);
} }
// One action per account a tick; a second would refuse the whole tick.
if (const auto superseded = server::keep_one_action_per_account(actions);
!superseded.empty())
bridge->dropped(superseded, true);
if (!batch_builder) { if (!batch_builder) {
auto created = server::CellularSessionBatchBuilder::create( auto created = server::CellularSessionBatchBuilder::create(
*state, host.committed()->head); *state, host.committed()->head);
if (created) if (created) {
batch_builder.emplace(std::move(*created)); batch_builder.emplace(std::move(*created));
else batch_builder->set_tuning_resolver(host.tuning_resolver());
} else
report_stall("create", created.error(), tick); report_stall("create", created.error(), tick);
} }
if (!batch_builder) { if (!batch_builder) {
@@ -1319,8 +1371,34 @@ int serve_cellular(Options& o) {
}); });
const std::span<const persistence::CellularMutationReservation> mutations = const std::span<const persistence::CellularMutationReservation> mutations =
unbound; unbound;
// ADR-0182: queued admin commands not already in this batch, and at
// most one tuning adoption per batch (its successor names its rules).
auto admin = host.unbound_admin_commands();
std::erase_if(admin, [&](const auto& queued) {
return std::ranges::any_of(
batch_builder->batch().ticks, [&](const auto& previous) {
return std::ranges::find(previous.admin, queued.id,
&server::CellularAdminCommand::id) !=
previous.admin.end();
});
});
bool adopting = std::ranges::any_of(
batch_builder->batch().ticks, [](const auto& previous) {
return std::ranges::any_of(previous.admin, [](const auto& c) {
return c.kind == server::CellularAdminKind::adopt_tuning;
});
});
std::erase_if(admin, [&](const auto& queued) {
if (queued.kind != server::CellularAdminKind::adopt_tuning)
return false;
if (adopting)
return true;
adopting = true;
return false;
});
const auto admin_before = batch_builder->admin_results().size();
auto appended = batch_builder->append_with_birth_refusals( auto appended = batch_builder->append_with_birth_refusals(
tick, baseline, actions, births, mutations); tick, baseline, actions, births, mutations, admin);
if (!appended && !actions.empty()) { if (!appended && !actions.empty()) {
// ADR-0127: one account's unusable action (its life died, or it // ADR-0127: one account's unusable action (its life died, or it
// names an unperceived patch) refuses only that action, never the // names an unperceived patch) refuses only that action, never the
@@ -1335,7 +1413,7 @@ int serve_cellular(Options& o) {
bridge->dropped(refused, true); bridge->dropped(refused, true);
actions = std::move(usable); actions = std::move(usable);
appended = batch_builder->append_with_birth_refusals( appended = batch_builder->append_with_birth_refusals(
tick, baseline, actions, births, mutations); tick, baseline, actions, births, mutations, admin);
} }
if (!appended) { if (!appended) {
const auto lives = batch_builder->last_lives_error(); const auto lives = batch_builder->last_lives_error();
@@ -1351,7 +1429,14 @@ int serve_cellular(Options& o) {
actions.end()); actions.end());
batch_actions.insert(batch_actions.end(), actions.begin(), batch_actions.insert(batch_actions.end(), actions.begin(),
actions.end()); actions.end());
const bool prompt = !births.empty() || !mutations.empty(); const auto results = batch_builder->admin_results();
for (std::size_t i = admin_before; i < results.size(); ++i)
std::printf("cellular admin command=%llu tick=%llu %s\n",
static_cast<unsigned long long>(results[i].id),
static_cast<unsigned long long>(tick),
results[i].applied ? "applied" : "refused");
const bool prompt =
!births.empty() || !mutations.empty() || !admin.empty();
if (prompt || batch_builder->batch().ticks.size() >= flush_ticks) if (prompt || batch_builder->batch().ticks.size() >= flush_ticks)
flush(); flush();
} }
@@ -1389,7 +1474,8 @@ int main(int argc, char** argv) {
"--session-cert F --session-key F --session-grant-key F " "--session-cert F --session-key F --session-grant-key F "
"--session-grant-ledger F --session-environment dev]] [--m10-listen " "--session-grant-ledger F --session-environment dev]] [--m10-listen "
"ADDRESS:PORT --m10-cert F --m10-key F --m10-issuer F " "ADDRESS:PORT --m10-cert F --m10-key F --m10-issuer F "
"--m10-environment dev|stage|world0 --session-window ACTIVATION:UTC_EXPIRY " "--m10-environment dev|stage|world0 (--session-window ACTIVATION:UTC_EXPIRY | "
"--session-window-source db) "
"[--m10-max-grant-lifetime 60..14400] [--m10-area X0,Y0,X1,Y1] " "[--m10-max-grant-lifetime 60..14400] [--m10-area X0,Y0,X1,Y1] "
"[--m10-handoff-key F [--m10-neighbour " "[--m10-handoff-key F [--m10-neighbour "
"REGION=X0,Y0,X1,Y1=HOST:PORT=NAME=PUBFILE]...] " "REGION=X0,Y0,X1,Y1=HOST:PORT=NAME=PUBFILE]...] "
+127 -23
View File
@@ -10,7 +10,7 @@
// evo-world-clone check-store --world W --region R --pg-* ... --objects DIR // evo-world-clone check-store --world W --region R --pg-* ... --objects DIR
// [--reserve-mib N] // [--reserve-mib N]
// evo-world-clone provision --world W --region R --opening // evo-world-clone provision --world W --region R --opening
// development-v1|primitive-v1|cellular-v1 to cellular-v9 // development-v1|primitive-v1|cellular-v1 to cellular-v10
// --pg-* ... --objects DIR --build HEX [--commit HEX32] [--retain-build] // --pg-* ... --objects DIR --build HEX [--commit HEX32] [--retain-build]
// primitive-v1 also requires --frame N --source-id N, every --funding-*-* channel, // primitive-v1 also requires --frame N --source-id N, every --funding-*-* channel,
// and one or more ordered --site X,Y values. // and one or more ordered --site X,Y values.
@@ -28,7 +28,11 @@
// cellular-v8 (ADR-0176) also requires --light-pj N. cellular-v9 (rules 12, ADR-0177) // cellular-v8 (ADR-0176) also requires --light-pj N. cellular-v9 (rules 12, ADR-0177)
// is cellular-v8 followed by the liquid upgrade: it also requires --tuning FILE (the Git // is cellular-v8 followed by the liquid upgrade: it also requires --tuning FILE (the Git
// tuning file, whose region size must match --width-um/--height-um) and accepts // tuning file, whose region size must match --width-um/--height-um) and accepts
// --current-seed N (default: derived from the --commit bytes). // --current-seed N (default: derived from the --commit bytes). cellular-v10 (rules 13,
// ADR-0179) is cellular-v9 followed by the revamp upgrade: it also requires
// --revamp-tuning FILE (the Git revamp tuning file).
// A nonzero playtest.starting_wildlife_cells (ADR-0180) additionally requires
// --playtest-wildlife-first-id N: an audited unused range below --life-allocator-start.
// primitive-v1 and cellular-v1/v2/v3 accept --life-allocator-start N // primitive-v1 and cellular-v1/v2/v3 accept --life-allocator-start N
// (ADR-0123): the world's life-identity allocator is created once at the operator-audited // (ADR-0123): the world's life-identity allocator is created once at the operator-audited
// start N; a later run leaves it untouched and refuses one that is below N. // start N; a later run leaves it untouched and refuses one that is below N.
@@ -74,6 +78,7 @@
// Exit: 0 done, 2 usage, 3 source/history/database failure, 4 target/objects refused, // Exit: 0 done, 2 usage, 3 source/history/database failure, 4 target/objects refused,
// 5 target unknown, 6 compared histories differ. // 5 target unknown, 6 compared histories differ.
#include "evo/biology/cellular_habitat.hpp" #include "evo/biology/cellular_habitat.hpp"
#include "evo/biology/cellular_revamp_tuning.hpp"
#include "evo/persistence/checkpoint_store.hpp" #include "evo/persistence/checkpoint_store.hpp"
#include "evo/persistence/region_clone.hpp" #include "evo/persistence/region_clone.hpp"
#include "evo/persistence/sha256.hpp" #include "evo/persistence/sha256.hpp"
@@ -124,19 +129,27 @@ struct Options {
std::vector<biology::CellularPatch> cellular_patches; std::vector<biology::CellularPatch> cellular_patches;
std::vector<biology::CellularPatch> cellular_pools; // cellular-v7 std::vector<biology::CellularPatch> cellular_pools; // cellular-v7
std::optional<biology::CellularMoteField> cellular_motes; // cellular-v7 and v8 std::optional<biology::CellularMoteField> cellular_motes; // cellular-v7 and v8
std::optional<biology::CellularMoteField> cellular_mixed; // Mixed bubbles (v7 and later)
std::optional<std::uint64_t> light_pj; // cellular-v8/v9: pJ per square um per tick std::optional<std::uint64_t> light_pj; // cellular-v8/v9: pJ per square um per tick
std::optional<std::string> tuning_path; // cellular-v9: the Git tuning file std::optional<std::string> tuning_path; // cellular-v9: the Git tuning file
std::optional<std::uint64_t> current_seed; std::optional<std::uint64_t> current_seed;
std::optional<biology::CellularTuning> tuning; // Parsed from tuning_path. std::optional<biology::CellularTuning> tuning; // Parsed from tuning_path.
std::optional<std::string> revamp_tuning_path; // cellular-v10
std::optional<biology::CellularRevampTuning> revamp_tuning; // Parsed from it.
std::optional<std::uint64_t> playtest_wildlife_first_id; // Audited DEV-only reserved range.
std::optional<std::uint64_t> life_allocator_start; std::optional<std::uint64_t> life_allocator_start;
std::optional<persistence::Sha256Digest> build; std::optional<persistence::Sha256Digest> build;
bool retain_build{}; bool retain_build{};
bool crash{}; bool crash{};
}; };
// The openings that declare light: cellular-v8, and cellular-v9 which adds the liquid upgrade. // The openings that declare light: cellular-v8, cellular-v9 which adds the liquid upgrade, and
// cellular-v10 which adds the revamp upgrade after it.
bool lit_opening(std::string_view opening) { bool lit_opening(std::string_view opening) {
return opening == "cellular-v8" || opening == "cellular-v9"; return opening == "cellular-v8" || opening == "cellular-v9" || opening == "cellular-v10";
}
bool liquid_opening(std::string_view opening) {
return opening == "cellular-v9" || opening == "cellular-v10";
} }
std::optional<std::uint64_t> number(std::string_view text) { std::optional<std::uint64_t> number(std::string_view text) {
std::uint64_t value{}; std::uint64_t value{};
@@ -349,9 +362,17 @@ std::optional<Options> parse(int argc, char** argv) {
(value == "development-v1" || value == "primitive-v1" || value == "cellular-v1" || (value == "development-v1" || value == "primitive-v1" || value == "cellular-v1" ||
value == "cellular-v2" || value == "cellular-v3" || value == "cellular-v4" || value == "cellular-v2" || value == "cellular-v3" || value == "cellular-v4" ||
value == "cellular-v5" || value == "cellular-v6" || value == "cellular-v7" || value == "cellular-v5" || value == "cellular-v6" || value == "cellular-v7" ||
value == "cellular-v8" || value == "cellular-v9")) value == "cellular-v8" || value == "cellular-v9" || value == "cellular-v10"))
o.opening = value; o.opening = value;
else if (o.command == "provision" && flag == "--light-pj" && n && *n > 0) else if (o.command == "provision" && flag == "--mixed-motes" && cellular_motes(value))
o.cellular_mixed = cellular_motes(value);
else if (o.command == "provision" && flag == "--revamp-tuning" && !value.empty())
o.revamp_tuning_path = std::string{value};
else if (o.command == "provision" && flag == "--playtest-wildlife-first-id") {
o.playtest_wildlife_first_id = number(value);
if (!o.playtest_wildlife_first_id || *o.playtest_wildlife_first_id == 0)
return std::nullopt;
} else if (o.command == "provision" && flag == "--light-pj" && n && *n > 0)
o.light_pj = n; o.light_pj = n;
else if (o.command == "provision" && flag == "--tuning" && !value.empty()) else if (o.command == "provision" && flag == "--tuning" && !value.empty())
o.tuning_path = std::string{value}; o.tuning_path = std::string{value};
@@ -442,11 +463,38 @@ std::optional<Options> parse(int argc, char** argv) {
return std::nullopt; return std::nullopt;
} else if (o.opening == "cellular-v7" || lit_opening(o.opening)) { } else if (o.opening == "cellular-v7" || lit_opening(o.opening)) {
// Pools and bubbles only: square patches belong to the earlier openings. Only // Pools and bubbles only: square patches belong to the earlier openings. Only
// cellular-v8 and v9 (ADR-0176) declare light; only v9 takes a tuning file. // cellular-v8 to v10 (ADR-0176) declare light; v9 and v10 take a tuning file, and
// v10 the revamp tuning file.
if (lit_opening(o.opening) != o.light_pj.has_value() || if (lit_opening(o.opening) != o.light_pj.has_value() ||
(o.opening == "cellular-v9") != o.tuning_path.has_value() || liquid_opening(o.opening) != o.tuning_path.has_value() ||
(o.current_seed && o.opening != "cellular-v9")) (o.opening == "cellular-v10") != o.revamp_tuning_path.has_value() ||
(o.current_seed && !liquid_opening(o.opening)))
return std::nullopt; return std::nullopt;
if (o.revamp_tuning_path) {
std::ifstream file(*o.revamp_tuning_path, std::ios::binary);
const std::string text{std::istreambuf_iterator<char>(file),
std::istreambuf_iterator<char>()};
if (!file.good() && !file.eof()) {
std::printf("revamp tuning file unreadable: %s\n",
o.revamp_tuning_path->c_str());
return std::nullopt;
}
auto parsed = biology::parse_cellular_revamp_tuning(text);
if (!parsed) {
std::printf("revamp tuning file refused at line %zu (%s): %s\n",
parsed.error().line, parsed.error().key.c_str(),
std::string{biology::describe(parsed.error().kind)}.c_str());
return std::nullopt;
}
o.revamp_tuning = *parsed;
const auto count = parsed->playtest_starting_wildlife_cells;
if (count != 0 && (!o.playtest_wildlife_first_id || !o.life_allocator_start ||
*o.playtest_wildlife_first_id == 0 ||
*o.playtest_wildlife_first_id >= *o.life_allocator_start ||
static_cast<std::uint64_t>(count) >
*o.life_allocator_start - *o.playtest_wildlife_first_id))
return std::nullopt;
}
if (o.tuning_path) { if (o.tuning_path) {
std::ifstream file(*o.tuning_path, std::ios::binary); std::ifstream file(*o.tuning_path, std::ios::binary);
const std::string text{std::istreambuf_iterator<char>(file), const std::string text{std::istreambuf_iterator<char>(file),
@@ -500,6 +548,8 @@ std::optional<Options> parse(int argc, char** argv) {
return std::nullopt; // The development opening has no lives to allocate. return std::nullopt; // The development opening has no lives to allocate.
} }
} }
if (o.playtest_wildlife_first_id && o.opening != "cellular-v10")
return std::nullopt;
if (!complete(o.source) || (needs_builds && o.retained.empty()) || if (!complete(o.source) || (needs_builds && o.retained.empty()) ||
(clone && !complete(o.target))) (clone && !complete(o.target)))
return std::nullopt; return std::nullopt;
@@ -593,7 +643,7 @@ std::vector<std::uint8_t> probe_bytes() {
// cellular-v9 (rules 12): the liquid rules from the tuning file, for the opening's area and // cellular-v9 (rules 12): the liquid rules from the tuning file, for the opening's area and
// a current seed (given, or derived from the genesis commit's bytes 8-15). // a current seed (given, or derived from the genesis commit's bytes 8-15).
std::optional<server::CellularLiquidRules> liquid_rules(const Options& o) { std::optional<server::CellularLiquidRules> liquid_rules(const Options& o) {
if (o.opening != "cellular-v9" || !o.tuning || !o.cellular_width_um || !o.cellular_height_um) if (!liquid_opening(o.opening) || !o.tuning || !o.cellular_width_um || !o.cellular_height_um)
return std::nullopt; return std::nullopt;
std::uint64_t seed = o.current_seed.value_or(0); std::uint64_t seed = o.current_seed.value_or(0);
if (!o.current_seed) { if (!o.current_seed) {
@@ -605,18 +655,31 @@ std::optional<server::CellularLiquidRules> liquid_rules(const Options& o) {
seed); seed);
} }
// cellular-v10 (rules 13): the revamp rules from the revamp tuning file.
std::optional<server::CellularRevampRules> revamp_rules(const Options& o) {
if (o.opening != "cellular-v10" || !o.revamp_tuning)
return std::nullopt;
return server::cellular_revamp_rules(*o.revamp_tuning);
}
// ADR-0176 cellular-v8: a cellular-v7 genesis taken through one empty tick and the durable // ADR-0176 cellular-v8: a cellular-v7 genesis taken through one empty tick and the durable
// bundle 9 -> 10 -> 11 -> 12 -> 13 upgrades, declaring the region's light. cellular-v9 adds the // bundle 9 -> 10 -> 11 -> 12 -> 13 upgrades, declaring the region's light. cellular-v9 adds the
// 13 -> 14 liquid upgrade. Resumable: it continues from whichever bundle the head has reached, // 13 -> 14 liquid upgrade and cellular-v10 the 14 -> 15 revamp upgrade. Resumable: it continues
// and does nothing at its target bundle. // from whichever bundle the head has reached, and does nothing at its target bundle.
int finish_photosynthesis_opening(const Options& o, persistence::Postgres& db, int finish_photosynthesis_opening(const Options& o, persistence::Postgres& db,
const persistence::FilesystemObjectStore& store, const persistence::FilesystemObjectStore& store,
std::uint64_t frame, const persistence::Sha256Digest& build, std::uint64_t frame, const persistence::Sha256Digest& build,
std::uint64_t light_pj, std::uint64_t light_pj,
const std::optional<server::CellularLiquidRules>& liquid) { const std::optional<server::CellularLiquidRules>& liquid,
const std::optional<server::CellularRevampRules>& revamp) {
const auto& key = o.source.key; const auto& key = o.source.key;
const auto target = std::uint32_t wildlife_count{};
liquid ? persistence::cellular_v14_versions : persistence::cellular_v13_versions; if (o.revamp_tuning)
wildlife_count =
static_cast<std::uint32_t>(o.revamp_tuning->playtest_starting_wildlife_cells);
const auto target = revamp ? persistence::cellular_v15_versions
: liquid ? persistence::cellular_v14_versions
: persistence::cellular_v13_versions;
// A finished opening needs no lease: a rerun (every Argo sync's provision hook) runs // A finished opening needs no lease: a rerun (every Argo sync's provision hook) runs
// while the region server holds it, and must report the region rather than fail. // while the region server holds it, and must report the region rather than fail.
if (const auto current = persistence::load_region_checkpoint(db, key, timeout); current) { if (const auto current = persistence::load_region_checkpoint(db, key, timeout); current) {
@@ -640,7 +703,7 @@ int finish_photosynthesis_opening(const Options& o, persistence::Postgres& db,
auto head = persistence::load_region_checkpoint(db, key, timeout); auto head = persistence::load_region_checkpoint(db, key, timeout);
if (!head) if (!head)
return finish(3); return finish(3);
for (unsigned step = 0; step < 7; ++step) { for (unsigned step = 0; step < 8; ++step) {
const auto manifest = persistence::decode_manifest(head->manifest); const auto manifest = persistence::decode_manifest(head->manifest);
if (!manifest || manifest->profile != persistence::CheckpointProfile::cellular_lives_v1 || if (!manifest || manifest->profile != persistence::CheckpointProfile::cellular_lives_v1 ||
manifest->frame != frame) manifest->frame != frame)
@@ -700,6 +763,10 @@ int finish_photosynthesis_opening(const Options& o, persistence::Postgres& db,
else if (versions == persistence::cellular_v13_versions && liquid) else if (versions == persistence::cellular_v13_versions && liquid)
upgraded = persistence::migrate_cellular_liquid_profile(db, store, *lease, *head, id, upgraded = persistence::migrate_cellular_liquid_profile(db, store, *lease, *head, id,
build, *liquid, timeout); build, *liquid, timeout);
else if (versions == persistence::cellular_v14_versions && liquid && revamp)
upgraded = persistence::migrate_cellular_revamp_profile(
db, store, *lease, *head, id, build, *revamp, timeout, {}, wildlife_count,
wildlife_count == 0 ? 0 : o.playtest_wildlife_first_id.value_or(0));
else else
return finish(4); return finish(4);
if (!upgraded) { if (!upgraded) {
@@ -815,10 +882,38 @@ int provision(const Options& o) {
if (o.opening == "cellular-v7" || lit_opening(o.opening)) { if (o.opening == "cellular-v7" || lit_opening(o.opening)) {
// ADR-0136 step A: pools and bubbles scattered from the genesis commit's bytes. // ADR-0136 step A: pools and bubbles scattered from the genesis commit's bytes.
auto field = o.cellular_motes.value_or(biology::CellularMoteField{0, 1, {}, 0}); auto field = o.cellular_motes.value_or(biology::CellularMoteField{0, 1, {}, 0});
if (const auto& mixed = o.cellular_mixed) {
// Mixed bubbles hold every nutrient of the --mixed-motes amounts at once.
if (!o.cellular_motes)
field.source = mixed->source;
field.mixed_count = mixed->count;
field.mixed = mixed->amount;
}
// Liquid openings: a pool rests in still water, never in a current.
auto pools = o.cellular_pools;
if (const auto liquid = liquid_rules(o)) {
const auto& c = liquid->currents;
const auto flow = biology::CellularFlowField::generate(
{c.seed, c.width_um, c.height_um, c.pitch_um, c.min_count, c.max_count,
c.min_route_width_um, c.max_route_width_um, c.min_speed_um_per_s,
c.max_speed_um_per_s});
if (!flow) {
std::puts("cellular currents refused");
return 4;
}
for (auto& pool : pools) {
const auto moved =
biology::cellular_still_centre(*flow, pool.address, pool.radius_um);
if (moved != pool.address)
std::printf("pool %u,%u moved out of a current to %u,%u\n",
pool.address.x_um, pool.address.y_um, moved.x_um, moved.y_um);
pool.address = moved;
}
}
const auto commit = o.commit.value_or(persistence::Uuid{}); const auto commit = o.commit.value_or(persistence::Uuid{});
for (std::size_t i = 0; i < 8; ++i) for (std::size_t i = 0; i < 8; ++i)
field.seed = (field.seed << 8U) | commit.at(i); field.seed = (field.seed << 8U) | commit.at(i);
auto scattered = biology::scatter_deposits(habitat_config, o.cellular_pools, field); auto scattered = biology::scatter_deposits(habitat_config, pools, field);
if (!scattered) { if (!scattered) {
std::printf("cellular habitat refused %u\n", std::printf("cellular habitat refused %u\n",
static_cast<unsigned>(scattered.error())); static_cast<unsigned>(scattered.error()));
@@ -887,9 +982,9 @@ int provision(const Options& o) {
"--commit to resolve genesis"); "--commit to resolve genesis");
return 4; return 4;
} }
if (const auto finished = if (const auto finished = finish_photosynthesis_opening(
finish_photosynthesis_opening(o, *db, *store, primitive_frame, build, o, *db, *store, primitive_frame, build, o.light_pj.value_or(0),
o.light_pj.value_or(0), liquid_rules(o)); liquid_rules(o), revamp_rules(o));
finished != 0) finished != 0)
return finished; return finished;
auto head = persistence::load_region_checkpoint(*db, o.source.key, timeout); auto head = persistence::load_region_checkpoint(*db, o.source.key, timeout);
@@ -942,9 +1037,9 @@ int provision(const Options& o) {
return 4; return 4;
} }
if (lit_opening(o.opening)) { if (lit_opening(o.opening)) {
if (const auto finished = if (const auto finished = finish_photosynthesis_opening(
finish_photosynthesis_opening(o, *db, *store, primitive_frame, build, o, *db, *store, primitive_frame, build, o.light_pj.value_or(0), liquid_rules(o),
o.light_pj.value_or(0), liquid_rules(o)); revamp_rules(o));
finished != 0) finished != 0)
return finished; return finished;
auto head = persistence::load_region_checkpoint(*db, o.source.key, timeout); auto head = persistence::load_region_checkpoint(*db, o.source.key, timeout);
@@ -1091,6 +1186,15 @@ int summary(const Options& o) {
static_cast<unsigned long long>(play->unrecorded), static_cast<unsigned long long>(play->unrecorded),
static_cast<unsigned long long>(play->owned_deaths), static_cast<unsigned long long>(play->owned_deaths),
static_cast<unsigned long long>(play->wildlife_deaths)); static_cast<unsigned long long>(play->wildlife_deaths));
std::printf("revamp merged=%llu emerged=%llu organisms=%llu largest=%llu offers_pending=%llu "
"offers_earned=%llu spent_fg=%llu\n",
static_cast<unsigned long long>(play->merged),
static_cast<unsigned long long>(play->emerged),
static_cast<unsigned long long>(play->organisms),
static_cast<unsigned long long>(play->largest_organism),
static_cast<unsigned long long>(play->offers_pending),
static_cast<unsigned long long>(play->offers_earned),
static_cast<unsigned long long>(play->spent_matter_fg));
std::printf("lifespan_ticks min=%llu median=%llu max=%llu\n", std::printf("lifespan_ticks min=%llu median=%llu max=%llu\n",
static_cast<unsigned long long>(play->lifespan_min), static_cast<unsigned long long>(play->lifespan_min),
static_cast<unsigned long long>(play->lifespan_median), static_cast<unsigned long long>(play->lifespan_median),
+5 -1
View File
@@ -145,7 +145,8 @@ RUN cmake --preset release -B build/postgres -DCMAKE_CXX_COMPILER=g++-14 \
-DCMAKE_C_COMPILER=gcc-14 -DEVO_BUILD_NETWORK=ON \ -DCMAKE_C_COMPILER=gcc-14 -DEVO_BUILD_NETWORK=ON \
-DEVO_BUILD_QUIC=ON -DEVO_BUILD_POSTGRES=ON \ -DEVO_BUILD_QUIC=ON -DEVO_BUILD_POSTGRES=ON \
-DPostgreSQL_ROOT=/source/.cache/postgres/install \ -DPostgreSQL_ROOT=/source/.cache/postgres/install \
&& cmake --build build/postgres --target evo-server evo-session-probe evo-world-clone evo-grant-broker --parallel "${PG_BUILD_JOBS}" && cmake --build build/postgres --target evo-server evo-session-probe evo-world-clone evo-grant-broker \
evo-admin-api --parallel "${PG_BUILD_JOBS}"
FROM postgres-build AS postgres-test-build FROM postgres-build AS postgres-test-build
ARG PG_BUILD_JOBS=6 ARG PG_BUILD_JOBS=6
@@ -202,6 +203,9 @@ COPY --from=postgres-build /source/build/postgres/evo-server /usr/local/bin/evo-
COPY --from=postgres-build /source/build/postgres/evo-world-clone /usr/local/bin/evo-world-clone COPY --from=postgres-build /source/build/postgres/evo-world-clone /usr/local/bin/evo-world-clone
# ADR-0131 grant broker (Keycloak tokens to session grants); its own Deployment. # ADR-0131 grant broker (Keycloak tokens to session grants); its own Deployment.
COPY --from=postgres-build /source/build/postgres/evo-grant-broker /usr/local/bin/evo-grant-broker COPY --from=postgres-build /source/build/postgres/evo-grant-broker /usr/local/bin/evo-grant-broker
# ADR-0182 read-only admin API and the portal's static files; its own Deployment.
COPY --from=postgres-build /source/build/postgres/evo-admin-api /usr/local/bin/evo-admin-api
COPY apps/evo-admin-api/portal/ /usr/local/share/evo-admin-portal/
COPY --from=postgres-build /source/.cache/postgres/install/lib/libpq.so* /opt/postgres/lib/ COPY --from=postgres-build /source/.cache/postgres/install/lib/libpq.so* /opt/postgres/lib/
COPY --from=postgres-build /source/build/postgres/msquic/bin/Release/libmsquic.so* /opt/msquic/lib/ COPY --from=postgres-build /source/build/postgres/msquic/bin/Release/libmsquic.so* /opt/msquic/lib/
COPY --from=postgres-build /source/.cache/postgres/postgresql-18.6/COPYRIGHT /usr/share/doc/evo-postgres/COPYRIGHT COPY --from=postgres-build /source/.cache/postgres/postgresql-18.6/COPYRIGHT /usr/share/doc/evo-postgres/COPYRIGHT
@@ -0,0 +1,116 @@
# ADR-0182 admin API and portal. One replica; it holds no state but a short view
# cache. The realm's public signing key is pinned below (ADMIN_JWKS, the same key as the grant
# broker's); a Keycloak key rotation needs a Git update in both.
apiVersion: apps/v1
kind: Deployment
metadata:
name: evo-admin-portal
annotations:
argocd.argoproj.io/sync-wave: "2" # After migration (schema v61).
labels:
app.kubernetes.io/name: evo-admin-portal
app.kubernetes.io/component: admin-portal
spec:
replicas: 1
revisionHistoryLimit: 3
progressDeadlineSeconds: 180
selector:
matchLabels:
app.kubernetes.io/name: evo-admin-portal
template:
metadata:
labels:
app.kubernetes.io/name: evo-admin-portal
app.kubernetes.io/component: admin-portal
app.kubernetes.io/part-of: aevolution
spec:
serviceAccountName: aevolution-admin-portal
automountServiceAccountToken: false
terminationGracePeriodSeconds: 10
securityContext:
runAsNonRoot: true
runAsUser: 10001
runAsGroup: 10001
fsGroup: 10001
seccompProfile: {type: RuntimeDefault}
containers:
- name: evo-admin-api
image: aevolution-server
command: ["/bin/bash", "-c"]
args:
- |
set -eu
regions=()
for region in $ADMIN_REGIONS; do regions+=(--region "$region"); done
exec /usr/local/bin/evo-admin-api --listen 0.0.0.0:8080 --world "$ADMIN_WORLD" \
--jwks "$ADMIN_JWKS" --oidc-issuer "$ADMIN_OIDC_ISSUER" \
--audience aevolution-admin --client aevolution-admin-portal \
--role aevolution-admin --assets /usr/local/share/evo-admin-portal \
--pg-service /run/postgres/pg_service.conf --pg-passfile /run/postgres/pgpass \
--baseline-tuning /etc/evo/tuning/cellular-revamp.tuning \
--region-tuning /etc/evo/tuning/cellular.tuning \
--deploy-config /run/deploy "${regions[@]}"
env:
- {name: ADMIN_WORLD, value: "100"}
# Space-separated REGION=HOST:PORT: each region's operations address for /admin/view.
- {name: ADMIN_REGIONS, value: "16=evo-region-ops:9100"}
- {name: ADMIN_OIDC_ISSUER, value: "https://auth.aeternalisgames.com/realms/aeternalis"}
# Public RS256 signing key(s) of realm aeternalis, from its JWKS endpoint.
- name: ADMIN_JWKS
value: '{"keys":[{"alg":"RS256","e":"AQAB","kid":"NGQG4QzQuBCIHVEomUPy-OoWOTVQIuyf3RXqeNbP8JI","kty":"RSA","n":"vvOpu1xxdyH_mB8LkJG6cwc6UVmmAj6mwQi1oEwrpJDLerBI2OZr2kpgMAUJ3-hMIkz5tRtSjHieMFteVrpDDQaCViIPCIvJTL3T7ujTGFNReSE6ho7h0DB_kybFeEWVpLqm6SSXWFYls5TKo6_t8Hw4G3njiRW9pX_NxyaBHqLkrCi63EyIGHOkdgUczg2d4pM4JTt-q25bcFSlYz8bhD3WEORQmbp-bU7aPPluCqCEAZRrbzf8Iy7svNemP5daDdlWQ3LaNy-ixC2HRjiPZdqK5BgAE800BigI-l1dkyJ4X172TLIPVPLW1WKlvdm3kHOpBXwACYiy8boSNDW7gQ","use":"sig"}]}'
ports:
- {name: http, containerPort: 8080, protocol: TCP}
readinessProbe:
httpGet: {path: /healthz, port: http}
periodSeconds: 5
timeoutSeconds: 1
livenessProbe:
httpGet: {path: /healthz, port: http}
initialDelaySeconds: 5
periodSeconds: 10
timeoutSeconds: 2
failureThreshold: 3
resources:
requests: {cpu: 10m, memory: 16Mi}
limits: {memory: 128Mi}
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities: {drop: [ALL]}
volumeMounts:
- {name: connection, mountPath: /run/postgres, readOnly: true}
# The revamp tuning file the regions opened with: the portal's baseline until the
# first tuning revision (ADR-0182 section 13); the region tuning file, shown read only.
- {name: tuning, mountPath: /etc/evo/tuning, readOnly: true}
# ADR-0182 section 15: the Gitea and Argo CD settings and tokens that let the portal
# open a region, one file per key; without the Secret that feature stays off.
- {name: deploy, mountPath: /run/deploy, readOnly: true}
volumes:
- name: deploy
secret:
secretName: aevolution-admin
optional: true
defaultMode: 0440
items:
- {key: GITEA_BASE_URL, path: GITEA_BASE_URL}
- {key: GITEA_REPOSITORY, path: GITEA_REPOSITORY}
- {key: GITEA_TOKEN, path: GITEA_TOKEN}
- {key: ARGOCD_SERVER, path: ARGOCD_SERVER}
- {key: ARGOCD_APPLICATION, path: ARGOCD_APPLICATION}
- {key: ARGOCD_TOKEN, path: ARGOCD_TOKEN}
- {key: ARGOCD_TLS_VERIFY, path: ARGOCD_TLS_VERIFY}
- name: tuning
configMap:
name: cellular-tuning
defaultMode: 0444
items:
- {key: cellular-revamp.tuning, path: cellular-revamp.tuning}
- {key: cellular.tuning, path: cellular.tuning}
- name: connection
secret:
secretName: aevolution-admin-pg
defaultMode: 0440
items:
- {key: pg_service.conf, path: pg_service.conf}
- {key: pgpass, path: pgpass}
- {key: ca.crt, path: ca.crt}
@@ -0,0 +1,15 @@
# ADR-0182 read-only admin API and portal for evolution-dev ONLY: verifies Keycloak access
# tokens (realm aeternalis, realm role aevolution-admin, audience aevolution-admin) and reads
# world 100 through the schema v61 views and region 16's /admin/view.
# Public route, 443 only: https://srs.aeternalisgames.com -> ingress-nginx (TLS; Ingress
# created out of band, since the aevolution-dev Argo project admits none) -> ClusterIP
# Service evo-admin-portal:8080, in-cluster only.
# Out-of-band Secret in evolution-dev: aevolution-admin-pg (pg_service.conf, pgpass, ca.crt
# for a login in the runtime group, as aevolution-grant-broker-pg).
apiVersion: kustomize.config.k8s.io/v1alpha1
kind: Component
resources:
- serviceaccount.yaml
- deployment.yaml
- service.yaml
- networkpolicy.yaml
@@ -0,0 +1,74 @@
# Admin portal traffic on top of the namespace default-deny. Admins reach it only at
# https://srs.aeternalisgames.com on 443, where ingress-nginx terminates TLS; port 8080 is
# admitted from the ingress-nginx pods and nothing else. Egress: PostgreSQL on pg-forge-01,
# the region's operations port (9100) for /admin/view, and for opening a region (ADR-0182
# section 15, approved 2026-10-28) Gitea through the node's ingress (git.aeternalisgames.com,
# 172.10.1.160:443) and the argocd-server pods (8080, behind the Service's 443).
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: evo-admin-portal
annotations:
argocd.argoproj.io/sync-wave: "-1"
spec:
podSelector:
matchLabels:
app.kubernetes.io/name: evo-admin-portal
policyTypes: [Ingress, Egress]
ingress:
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: kube-system
podSelector:
matchLabels:
app.kubernetes.io/name: rke2-ingress-nginx
ports:
- {protocol: TCP, port: 8080}
egress:
- to:
- ipBlock:
cidr: 172.10.1.127/32
ports:
- {protocol: TCP, port: 5432}
- to:
- podSelector:
matchLabels:
app.kubernetes.io/name: evo-region
ports:
- {protocol: TCP, port: 9100}
- to:
- ipBlock:
cidr: 172.10.1.160/32
ports:
- {protocol: TCP, port: 443}
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: argocd
podSelector:
matchLabels:
app.kubernetes.io/name: argocd-server
ports:
- {protocol: TCP, port: 8080}
---
# The region's operations port also admits the admin portal (alongside Prometheus,
# evo-region-scrape). Only 9100: never the session port.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: evo-region-admin-view
annotations:
argocd.argoproj.io/sync-wave: "-1"
spec:
podSelector:
matchLabels:
app.kubernetes.io/name: evo-region
policyTypes: [Ingress]
ingress:
- from:
- podSelector:
matchLabels:
app.kubernetes.io/name: evo-admin-portal
ports:
- {protocol: TCP, port: 9100}
@@ -0,0 +1,15 @@
# Cluster-internal; the Ingress for srs.aeternalisgames.com terminates TLS and forwards here.
apiVersion: v1
kind: Service
metadata:
name: evo-admin-portal
annotations:
argocd.argoproj.io/sync-wave: "2"
labels:
app.kubernetes.io/name: evo-admin-portal
spec:
type: ClusterIP
selector:
app.kubernetes.io/name: evo-admin-portal
ports:
- {name: http, port: 8080, targetPort: http, protocol: TCP}
@@ -0,0 +1,10 @@
apiVersion: v1
kind: ServiceAccount
metadata:
name: aevolution-admin-portal
annotations:
argocd.argoproj.io/sync-wave: "-1"
automountServiceAccountToken: false
# Create this pull-only Secret separately in evolution-dev; never commit credentials.
imagePullSecrets:
- name: harbor-pull
+2 -2
View File
@@ -12,5 +12,5 @@ resources:
images: images:
- name: evo-sim - name: evo-sim
newName: registry.aeternalisgames.com/aeternalis/aevolution newName: registry.aeternalisgames.com/aeternalis/aevolution
# Verified Gitea run 1399; source commit 8ab48d3a5639121693f5881b600482e870b49f05. # Verified Harbor publish from source commit 477ea8980bb0b7ecd5de16cedf149060f4f92bac.
digest: sha256:0c6c6e1ac28de2ce0648fd0992ca694963e303ef5c9414fe5ac668937136800d digest: sha256:72a779906e06d5080dcfc03de7692bd1f8c7c8ff6b31893925533b13c2c9a103
@@ -47,9 +47,9 @@ spec:
- {name: BROKER_WORLD, value: "100"} - {name: BROKER_WORLD, value: "100"}
- {name: BROKER_FRAME, value: "9"} - {name: BROKER_FRAME, value: "9"}
# New accounts start here; an account with a live life goes to its region. # New accounts start here; an account with a live life goes to its region.
- {name: BROKER_DEFAULT_REGION, value: "11"} - {name: BROKER_DEFAULT_REGION, value: "16"}
# Space-separated REGION=HOST:PORT=TLS_NAME, every region a grant may name. # Space-separated REGION=HOST:PORT=TLS_NAME, every region a grant may name.
- {name: BROKER_ROUTES, value: "11=void.aeternalisgames.com:7400=void.aeternalisgames.com"} - {name: BROKER_ROUTES, value: "16=void.aeternalisgames.com:7400=void.aeternalisgames.com"}
# Must not exceed the region's REGION_M10_MAX_GRANT_LIFETIME. # Must not exceed the region's REGION_M10_MAX_GRANT_LIFETIME.
- {name: BROKER_GRANT_LIFETIME, value: "600"} - {name: BROKER_GRANT_LIFETIME, value: "600"}
- {name: BROKER_OIDC_ISSUER, value: "https://auth.aeternalisgames.com/realms/aeternalis"} - {name: BROKER_OIDC_ISSUER, value: "https://auth.aeternalisgames.com/realms/aeternalis"}
@@ -63,7 +63,7 @@ spec:
if [ -n "$REGION_SESSION" ]; then if [ -n "$REGION_SESSION" ]; then
m10=(--m10-listen "$REGION_SESSION_LISTEN" --m10-cert /run/session/server.pem m10=(--m10-listen "$REGION_SESSION_LISTEN" --m10-cert /run/session/server.pem
--m10-key /run/session/server.key --m10-issuer /run/session/issuer.pub --m10-key /run/session/server.key --m10-issuer /run/session/issuer.pub
--m10-environment "$REGION_SESSION" --session-window "$REGION_SESSION_WINDOW") --m10-environment "$REGION_SESSION" --session-window-source db)
grant=(--m10-max-grant-lifetime "$REGION_M10_MAX_GRANT_LIFETIME") grant=(--m10-max-grant-lifetime "$REGION_M10_MAX_GRANT_LIFETIME")
fi fi
# Lineage keeps its 20 s drain. Both profiles take the overlay grant ceiling; # Lineage keeps its 20 s drain. Both profiles take the overlay grant ceiling;
@@ -100,8 +100,6 @@ spec:
# Session listener address; the policy check allows only this loopback value # Session listener address; the policy check allows only this loopback value
# outside region/dev-session-route. # outside region/dev-session-route.
- {name: REGION_SESSION_LISTEN, value: "127.0.0.1:7400"} - {name: REGION_SESSION_LISTEN, value: "127.0.0.1:7400"}
# Absolute UTC expiry; route overlays must provide activation-id:unix-seconds.
- {name: REGION_SESSION_WINDOW, value: ""}
# DEV-only grant ceiling; overlays must keep this within the server contract. # DEV-only grant ceiling; overlays must keep this within the server contract.
- {name: REGION_M10_MAX_GRANT_LIFETIME, value: "300"} - {name: REGION_M10_MAX_GRANT_LIFETIME, value: "300"}
ports: ports:
@@ -1,5 +1,5 @@
# With the route, the opt-in M10 QUIC listener binds the pod interface. The absolute # With the route, the opt-in M10 QUIC listener binds the pod interface. Its session window
# expiry is committed so a delayed Argo sync fails closed (ADR-0087). # is not in Git: the region reads it from SQL, set in the admin portal (ADR-0087 amendment).
apiVersion: apps/v1 apiVersion: apps/v1
kind: Deployment kind: Deployment
metadata: metadata:
@@ -12,7 +12,6 @@ spec:
env: env:
- {name: REGION_SESSION, value: "dev"} - {name: REGION_SESSION, value: "dev"}
- {name: REGION_SESSION_LISTEN, value: "0.0.0.0:7400"} - {name: REGION_SESSION_LISTEN, value: "0.0.0.0:7400"}
- {name: REGION_SESSION_WINDOW, value: "dev-20261022T143710-858ce998:1792694230"}
- {name: REGION_M10_MAX_GRANT_LIFETIME, value: "14400"} - {name: REGION_M10_MAX_GRANT_LIFETIME, value: "14400"}
ports: ports:
# QUIC (ADR-0090): UDP only; nothing listens on TCP 7400. # QUIC (ADR-0090): UDP only; nothing listens on TCP 7400.
@@ -1,4 +1,4 @@
# Region host for evolution-dev: world 100, region 11, frame 9 (cellular-v9 opening, rules 12). # Region host for evolution-dev: world 100, region 16, frame 9 (cellular-v10 opening, rules 13).
# The server image digest appears twice on purpose: as the image and as the build # The server image digest appears twice on purpose: as the image and as the build
# identity the region records in every commit. The policy check requires they match. # identity the region records in every commit. The policy check requires they match.
apiVersion: kustomize.config.k8s.io/v1beta1 apiVersion: kustomize.config.k8s.io/v1beta1
@@ -9,19 +9,22 @@ resources:
components: components:
- ../dev-session-route - ../dev-session-route
- ../../grant-broker-dev - ../../grant-broker-dev
- ../../admin-portal-dev
- ../../worker-only-dev - ../../worker-only-dev
images: images:
- name: aevolution-server - name: aevolution-server
newName: registry.aeternalisgames.com/aeternalis/aevolution-server newName: registry.aeternalisgames.com/aeternalis/aevolution-server
digest: sha256:f0869be511179866f9a71a63a6a5f65e577e851fd7851184734bb5c56940b1a6 # Gitea run 576 (9de55e3): one action per account a tick.
digest: sha256:9ba0d78a0db2cd4016711b1c4a621f3945b4b4895d3c4a420389f281bbb781a5
patches: patches:
- path: region-values.yaml - path: region-values.yaml
# The Git tuning file (rules 12) for the provision Job's liquid upgrade. A fixed name: a change # The Git tuning files for the provision Job's liquid (rules 12) and revamp (rules 13)
# updates the ConfigMap in place (the Job is a sync hook and reads it afresh every sync), so # upgrades. A fixed name: a change updates the ConfigMap in place (the Job is a sync hook and
# no superseded copies are left for Argo to report. # reads it afresh every sync), so no superseded copies are left for Argo to report.
configMapGenerator: configMapGenerator:
- name: cellular-tuning - name: cellular-tuning
files: files:
- tuning/cellular.tuning - tuning/cellular.tuning
- tuning/cellular-revamp.tuning
options: options:
disableNameSuffixHash: true disableNameSuffixHash: true
+47 -35
View File
@@ -1,9 +1,10 @@
# Region identity and build (the server image digest without "sha256:"). # Region identity and build (the server image digest without "sha256:").
# Liquid playtests (rules 12, ADR-0177): region 11 holds a cellular-v9 opening, a 60 x 60 mm # Revamp playtests (rules 13, ADR-0179): region 16 holds a cellular-v10 opening, a 60 x 60 mm
# cellular-v7 genesis taken durably to rules 11 with light (trial 40 pJ per square um per # cellular-v7 genesis taken durably to rules 11 with light (trial 40 pJ per square um per
# tick) and then to rules 12 with the currents, handling and moving food of the Git tuning # tick), to rules 12 with the currents, handling and moving food of the Git tuning file
# file (tuning/cellular.tuning). Regions 1-10 stay in the stores untouched; they are simply # (tuning/cellular.tuning), and to rules 13 with the revamp rules of
# not served while dev runs region 11. A region keeps the tuning it opened with, so a new # tuning/cellular-revamp.tuning. Regions 1-15 stay in the stores untouched; they are simply
# not served while dev runs region 16. A region keeps the tuning it opened with, so a new
# region opens when the tuning changes (until live retuning exists). # region opens when the tuning changes (until live retuning exists).
apiVersion: apps/v1 apiVersion: apps/v1
kind: Deployment kind: Deployment
@@ -16,13 +17,13 @@ spec:
- name: evo-server - name: evo-server
env: env:
- {name: REGION_WORLD, value: "100"} - {name: REGION_WORLD, value: "100"}
- {name: REGION_ID, value: "11"} - {name: REGION_ID, value: "16"}
- {name: REGION_BUILD, value: f0869be511179866f9a71a63a6a5f65e577e851fd7851184734bb5c56940b1a6} - {name: REGION_BUILD, value: 9ba0d78a0db2cd4016711b1c4a621f3945b4b4895d3c4a420389f281bbb781a5}
- {name: REGION_PROFILE, value: cellular} - {name: REGION_PROFILE, value: cellular}
# The whole world's catalog: dev world 100 has only this region. # The whole world's catalog: dev world 100 has only this region.
- {name: REGION_LIFE_ROUTES, value: "11=void.aeternalisgames.com:7400=void.aeternalisgames.com"} - {name: REGION_LIFE_ROUTES, value: "16=void.aeternalisgames.com:7400=void.aeternalisgames.com"}
# Keep the currently promoted build plus prior committed builds recoverable. # Keep the currently promoted build plus prior committed builds recoverable.
- {name: REGION_RETAINED, value: "f1183f4476bac87c09504a574112df4663931f67e88cc38dc08f867ce98ff726 815153514ca4a53967932bb46456ff4cb4e1784f9db247bc3b613b7e8365c59f 21507d4369cebef83ee05152daea5ac2f581ea86a9dc85276ef54e3f9f6388c5 5a77cf9e96e7a0e40ea07e9394a3fa458184ce54f8f774a8fb59cbec1db75c54 e17c62bc8dbad089da57e8b30adc391ff8b947cc7182b3160f5e2709103ded78 6c96629eb3c26513d55207b109fe2a9873a58f43510bd067b7d5422572e3fb42 7952185d5ef96504b5793b76fe72e42cbe9c9ac19149bf912adb2c3a735f8dbf f378a43d6146eeed864110b90848df0bec9672fa4c9941a2d04de249068a4a09 ecac8f9f2489c547ce58f12ed01baaa3939c8adbf8aed05c313abbf422cdc855 4af7209941643e0c6a100e2b4e2fef8a959b87fdbfac2173b7867cfc1808bd66 edb39f956df1f481d7ba724cac4ceb3a4fe494efc02f994d31d6c96dfae04a78 0ded41070dd3e0c0daa43e13dadc58c449865eec00530cfceff3c1579c66e916 754446fe4e5f33e9c0d5a1a74a02444a01de1700673442c90827c708aba62cee c597c0bac8b4a796e1e8b70344f9866cb047cc90cfb15af774d38860594ea27a e83c333a87056c678b5e835947647ef42370b43dbfc31997744f28d993f9c4aa db2b0e6a6071502381a768d70fd9bab8c08c64e4717fc23da45dbe8adc5fa3d6 cdc10712ff8bf956f8f5900709500046493523b51dc670d5b2d01eaf604bcd38 028571f257b485acafbe79b704a80f273d899485c4bb264d9c8137bf51e33217 566c29329433934f1436faf94652a7b925df8b4587ab04470322172f47c31c02 1dd640eba3e9dbdd10106698215a0a06df89c5cdf801c53c4c26fb923116552a faeb26fc5db5c4aae9ae9eb4388e807ab4d59499d7639fcab3d878843a740037 5e13e0096eb4010253c270ab98f0e9bbc11571c221eb779d428333e8cd63c955 e891f9427d5ec81b32595d70be9d00bb66c6d8223b4747d12be8c388c2fc0c8e 58aab8aaa538c0c6e5ad7281fd27e50374b489942aa317296dbf9c2ec5ca3434 4a8b0a9dc9f6be491e9eacb464aa7ef7c0d449de3018c4172c01448ce39a5108 3e5b8cef06838821113c8bba064e9415e8c627bca552fb978f830d40027b80f2 67e6bb3d138e7d489850ac99b5915ef8659178a68140b963e282b24020a288e2 f178f7f44251fdc9ae9ccaaecc5ea6f10aa534caa25d506abc3fbde21c69db17 6532f97e9b7d1492f1a17d1228ce7e563016c2187735f44e58ff1e9f786019aa 7c5462391a9bff4f7c25f2761098e7189b7ae204af0a7be61a652e4482f63e6a 9ba005f9216a2211491afd0e335ac5c6f20af1166fbb7518bcc8cec2e536f5ce 7eb84318234e23c223d4279ac01e925ba0b08d6d6950f7ba328f0ce909af8307 0fcdbf1518b677829322dc18e1feebd354a6e39700bd9cdb60ab47dc0465c3a6 801a9ae4fe1049dd27cfd9c356f21f29c6e07238448c201c08d288b5cc8e7e9a"} - {name: REGION_RETAINED, value: "f1183f4476bac87c09504a574112df4663931f67e88cc38dc08f867ce98ff726 815153514ca4a53967932bb46456ff4cb4e1784f9db247bc3b613b7e8365c59f 21507d4369cebef83ee05152daea5ac2f581ea86a9dc85276ef54e3f9f6388c5 5a77cf9e96e7a0e40ea07e9394a3fa458184ce54f8f774a8fb59cbec1db75c54 e17c62bc8dbad089da57e8b30adc391ff8b947cc7182b3160f5e2709103ded78 6c96629eb3c26513d55207b109fe2a9873a58f43510bd067b7d5422572e3fb42 7952185d5ef96504b5793b76fe72e42cbe9c9ac19149bf912adb2c3a735f8dbf f378a43d6146eeed864110b90848df0bec9672fa4c9941a2d04de249068a4a09 ecac8f9f2489c547ce58f12ed01baaa3939c8adbf8aed05c313abbf422cdc855 4af7209941643e0c6a100e2b4e2fef8a959b87fdbfac2173b7867cfc1808bd66 edb39f956df1f481d7ba724cac4ceb3a4fe494efc02f994d31d6c96dfae04a78 0ded41070dd3e0c0daa43e13dadc58c449865eec00530cfceff3c1579c66e916 754446fe4e5f33e9c0d5a1a74a02444a01de1700673442c90827c708aba62cee c597c0bac8b4a796e1e8b70344f9866cb047cc90cfb15af774d38860594ea27a e83c333a87056c678b5e835947647ef42370b43dbfc31997744f28d993f9c4aa db2b0e6a6071502381a768d70fd9bab8c08c64e4717fc23da45dbe8adc5fa3d6 cdc10712ff8bf956f8f5900709500046493523b51dc670d5b2d01eaf604bcd38 028571f257b485acafbe79b704a80f273d899485c4bb264d9c8137bf51e33217 566c29329433934f1436faf94652a7b925df8b4587ab04470322172f47c31c02 1dd640eba3e9dbdd10106698215a0a06df89c5cdf801c53c4c26fb923116552a faeb26fc5db5c4aae9ae9eb4388e807ab4d59499d7639fcab3d878843a740037 5e13e0096eb4010253c270ab98f0e9bbc11571c221eb779d428333e8cd63c955 e891f9427d5ec81b32595d70be9d00bb66c6d8223b4747d12be8c388c2fc0c8e 58aab8aaa538c0c6e5ad7281fd27e50374b489942aa317296dbf9c2ec5ca3434 4a8b0a9dc9f6be491e9eacb464aa7ef7c0d449de3018c4172c01448ce39a5108 3e5b8cef06838821113c8bba064e9415e8c627bca552fb978f830d40027b80f2 67e6bb3d138e7d489850ac99b5915ef8659178a68140b963e282b24020a288e2 f178f7f44251fdc9ae9ccaaecc5ea6f10aa534caa25d506abc3fbde21c69db17 6532f97e9b7d1492f1a17d1228ce7e563016c2187735f44e58ff1e9f786019aa 7c5462391a9bff4f7c25f2761098e7189b7ae204af0a7be61a652e4482f63e6a 9ba005f9216a2211491afd0e335ac5c6f20af1166fbb7518bcc8cec2e536f5ce 7eb84318234e23c223d4279ac01e925ba0b08d6d6950f7ba328f0ce909af8307 0fcdbf1518b677829322dc18e1feebd354a6e39700bd9cdb60ab47dc0465c3a6 801a9ae4fe1049dd27cfd9c356f21f29c6e07238448c201c08d288b5cc8e7e9a f0869be511179866f9a71a63a6a5f65e577e851fd7851184734bb5c56940b1a6 178cd8ffcdfe9fe14f39084d78341a8705ca72e78947bada31ab0356508fc232 0fd4807f67ab317561f115f12c0d8540e04596fdea389d7c2104e97dda5a0351 effea9180d802e50abed76a5da665374f3591eda8aeb99c0fff085ed6df618ae 7a35cc170b935508b9b88379f4fb581acb852ebe769ac269f1596861aca2ffa7 2d1307493202464773734b0a2d33f4a737b0a897cb179de05bdf433cbdb1aec1 a5b70d945b63618a2897a848320e9af6b73a1a4f3bf8fb052d8286a93f6f8ada 222fa3dea0cb25335234678fa0d628222fc92c9ff38a1869330d973b8c4b4e53 f235d14aa06924010ac9e1a4cfad6148ed24447eafb33ef2df968a285f467457 1dd1ea052376c2c5daf2b0a910b1a5972474c836672f9cb61b32ecae58dabfd1 c7347c2d7aa2ea0e5d00665da81cd7d710b109e4e306dd7e09562463d33a5d8f d4b62521c57323025ed611b6873cffa5da49b84acda38081758e8a23b7b8d981 82e248426f5cb31cfe8ddc3aea84982d2fcfd34d12fbf78204de2ccffdbf2a2a 03ce069df16244e47d4c7b7ceac699949c099168f9c531f1ece08d2111d286e5 db67827962bd96ec8c19f4dbb039d29e897592db9d8e9da9ddf00bc0770a0b5f de1b4b32ef7d38785efc562a3288ed066b0be9398e4a64551d12adf423aac31f ec473b40c5958e1cd38765dcf3f52027f39ef29e5b776ba9ad03a6a25af31819 9f76430c33a33d246384dc198b4df3d7e4abf28277a2f435cce25696d01a4863 12e62108f7b920bea0b91f50b21fcabd2463af6f1e94242140bbde786e42eee5 a8edb67c9b69edb5c2c750a068c6d89553691fccc47a4241c67c12f3f9e2a0b2 2f2d5c2bd6baa68163d81cbdd75496e200e8446cf806f443834cd03bdb6eb828 87d607f5bc1cb6b8673767ad44d62d773fac4116b1f952cdb80fac61625b1d02 a7ab3f34b18c06ce17f374d662f57a19d2754f079d899fe29d4262c5b26f7855 441c25a5d728f37d257c4b7bde6d15736aa66d16b07ea088d2d1838eb01a5c55 1d0585ef57e70ab0ab8ea67a780f2a4680101a854bfab46dbb2a5092e7f2251b"}
--- ---
apiVersion: batch/v1 apiVersion: batch/v1
kind: Job kind: Job
@@ -35,39 +36,50 @@ spec:
- name: provision - name: provision
env: env:
- {name: REGION_WORLD, value: "100"} - {name: REGION_WORLD, value: "100"}
- {name: REGION_ID, value: "11"} - {name: REGION_ID, value: "16"}
- {name: REGION_BUILD, value: f0869be511179866f9a71a63a6a5f65e577e851fd7851184734bb5c56940b1a6} - {name: REGION_BUILD, value: 9ba0d78a0db2cd4016711b1c4a621f3945b4b4895d3c4a420389f281bbb781a5}
# Region 11 (rules 12): cellular-v9, 60 x 60 mm at 20 C, taken through one empty tick, # Region 16 (rules 13): cellular-v10, 60 x 60 mm at 20 C, taken through one empty tick,
# the durable upgrades to rules 11 with light and the liquid upgrade from the mounted # the durable upgrades to rules 11 with light, the liquid upgrade from the mounted
# tuning file (whose region size must match). 9 pools (500 um radius; a pool feeds at # tuning file (whose region size must match) and the revamp upgrade from the mounted
# a quarter rate) and 3,600 single-nutrient bubbles scattered from the genesis commit # revamp tuning file. 9 pools (500 um radius; a pool feeds at a quarter rate; any in a
# (720 per channel: 7e7 pJ energy, 4.2e6 fg C, 9.4e5 N, 4.9e5 P, 2e6 other each); the # current moves to the nearest still water), 1,200 single-nutrient bubbles (240 per
# format-2 genesis holds at most 4,096 deposits. The current seed comes from the # channel: 2.1e8 pJ energy, 1.26e7 fg C, 2.82e6 N, 1.47e6 P, 6e6 other each) and 2,400
# commit. The nursery funds 64 primitive founders; rules-12 founders start at random spots # mixed bubbles holding every nutrient in the founder recipe's proportions (4.2e7 pJ,
# (the 9 sites, 3 mm from pools, are the fallback). # 2.52e6 fg C, 7.56e5 N, 2.52e5 P, 1.512e6 other), scattered from the genesis commit:
# Genesis is written once: keep --commit stable so every sync resolves it. The world 100 # three times region 14's food in every pool and bubble. The format-2 genesis holds
# at most 4,096 deposits. The current seed comes from the commit. The nursery funds
# 256 primitive founders' worth (100 go to the seeded wildlife, the rest to player
# births, each new life included); rules-12 founders start at random spots (the 9
# sites, 3 mm from pools, are the fallback).
# Genesis is written once: keep --commit stable so every sync resolves it.
# ADR-0180: region 14 used IDs 900000003584-900000003615 for its 32 seeded wildlife;
# region 15 used 900000003616-900000003715; region 16 reserves
# 900000003716-900000003815 for its 100. Their
# resources come from the nursery, leaving its remainder for players. The
# life allocator starts far above the unserved lineage region 1 identities (ADR-0123). # life allocator starts far above the unserved lineage region 1 identities (ADR-0123).
- {name: REGION_OPENING, value: cellular-v9} - {name: REGION_OPENING, value: cellular-v10}
- name: REGION_OPENING_ARGS - name: REGION_OPENING_ARGS
value: >- value: >-
--frame 9 --source-id 1 --commit 3e8b5f1a7c2d4e6f8091a2b3c4d5e6f7 --light-pj 40 --frame 9 --source-id 1 --commit c3a29d5e1f2b3a4c6d8e0f1a2b3c4d5f --light-pj 40
--tuning /etc/evo/tuning/cellular.tuning --tuning /etc/evo/tuning/cellular.tuning
--life-allocator-start 1000000000000 --revamp-tuning /etc/evo/tuning/cellular-revamp.tuning
--life-allocator-start 1000000000000 --playtest-wildlife-first-id 900000003716
--width-um 60000 --height-um 60000 --ambient-temperature-mk 293150 --width-um 60000 --height-um 60000 --ambient-temperature-mk 293150
--funding-energy-pj 528588800 --funding-carbon-fg 385024000 --funding-energy-pj 2114355200 --funding-carbon-fg 1540096000
--funding-nitrogen-fg 86016000 --funding-phosphorus-fg 44032000 --funding-nitrogen-fg 344064000 --funding-phosphorus-fg 176128000
--funding-other-fg 181248000 --funding-other-fg 724992000
--site 12000,12000 --site 12000,27000 --site 12000,42000 --site 27000,12000 --site 27000,27000 --site 27000,42000 --site 42000,12000 --site 42000,27000 --site 42000,42000 --site 12000,12000 --site 12000,27000 --site 12000,42000 --site 27000,12000 --site 27000,27000 --site 27000,42000 --site 42000,12000 --site 42000,27000 --site 42000,42000
--pool 15000,15000,500,2,2800000000,167000000,38000000,19600000,80000000 --pool 15000,15000,500,2,8400000000,501000000,114000000,58800000,240000000
--pool 15000,30000,500,2,2800000000,167000000,38000000,19600000,80000000 --pool 15000,30000,500,2,8400000000,501000000,114000000,58800000,240000000
--pool 15000,45000,500,2,2800000000,167000000,38000000,19600000,80000000 --pool 15000,45000,500,2,8400000000,501000000,114000000,58800000,240000000
--pool 30000,15000,500,2,2800000000,167000000,38000000,19600000,80000000 --pool 30000,15000,500,2,8400000000,501000000,114000000,58800000,240000000
--pool 30000,30000,500,2,2800000000,167000000,38000000,19600000,80000000 --pool 30000,30000,500,2,8400000000,501000000,114000000,58800000,240000000
--pool 30000,45000,500,2,2800000000,167000000,38000000,19600000,80000000 --pool 30000,45000,500,2,8400000000,501000000,114000000,58800000,240000000
--pool 45000,15000,500,2,2800000000,167000000,38000000,19600000,80000000 --pool 45000,15000,500,2,8400000000,501000000,114000000,58800000,240000000
--pool 45000,30000,500,2,2800000000,167000000,38000000,19600000,80000000 --pool 45000,30000,500,2,8400000000,501000000,114000000,58800000,240000000
--pool 45000,45000,500,2,2800000000,167000000,38000000,19600000,80000000 --pool 45000,45000,500,2,8400000000,501000000,114000000,58800000,240000000
--motes 3600,2,70000000,4200000,940000,490000,2000000 --motes 1200,2,210000000,12600000,2820000,1470000,6000000
--mixed-motes 2400,2,42000000,2520000,756000,252000,1512000
volumeMounts: volumeMounts:
- {name: tuning, mountPath: /etc/evo/tuning, readOnly: true} - {name: tuning, mountPath: /etc/evo/tuning, readOnly: true}
volumes: volumes:
@@ -0,0 +1,88 @@
# Reproduction safety trial (ADR-0181): NOT mounted by the active DEV overlay.
# For a fresh opening with a build supporting safety revision 1, pass this file
# as --revamp-tuning. Promote the server image before adopting it as mounted tuning.
# Cellular revamp trial values (rules 13, ADR-0179; Cellular_Revamp_Build_Plan.md).
# Same format as cellular.tuning: `key = value`, integers only, `_` may separate digits,
# core keys required exactly once; playtest.* and mutation overrides are optional.
# Use for new-region provisioning with the new image; existing regions retain recorded rules.
tuning.version = 1
# DEV opening fixture only (ADR-0180). Zero disables seeding; never replenished on restart.
# Requires an audited --playtest-wildlife-first-id range below --life-allocator-start.
playtest.starting_wildlife_cells = 100
# Body (body and maintenance plan).
body.essential_upkeep_per_mille = 250 # share of upkeep no upkeep-efficiency trait reduces
body.reserve_load_per_mille = 1_000 # reserve matter carried as load (slower, costlier thrust)
body.growth_per_tick_centi_mille = 625 # 6.25 per mille per tick; 25% faster for playtesting
# Energy (feeding and energy plan): what 1,000 fg of reserve matter stands in for when the
# reserve's energy runs out. Bubbles carry ~17 pJ of energy per fg of matter, so 2 pJ per fg
# makes burning matter the expensive way to stay alive (a founder burns a carbon bubble in
# about 80 s of upkeep).
energy.burn_carbon_pj_per_kfg = 2_000
energy.burn_nitrogen_pj_per_kfg = 2_000
energy.burn_phosphorus_pj_per_kfg = 2_000
energy.burn_other_pj_per_kfg = 2_000
# Feeding: collection lost per membrane point above the founder's 100 (5 points: -1%).
feeding.membrane_collection_per_mille_per_point = 2
# Every collection limit, per cent of the body's own (optional; 100 when absent).
feeding.collection_percent = 130
# Matter from one source split evenly between the nutrients it holds (optional; 0 when
# absent): a carbon-only bubble gives the whole matter limit to carbon, carbon and
# phosphorus half each, all four a quarter each.
feeding.split_evenly = 1
# Predation (predation and defense plan).
predation.engulf_ratio_milli = 1_500 # a predator needs 1.5x the prey's engulf mass
predation.engulf_reserve_percent = 100 # share of reserve matter in engulf mass
predation.kill_bubble_per_mille = 500 # a kill's remainder left as bubbles; the rest is spent
# The spent pool drips back as bubbles at random spots.
spent.drip_interval_ticks = 20 # once a second
spent.drip_bubble_pj = 20_000_000 # largest energy bubble per drip
spent.drip_bubble_fg = 1_000_000 # largest matter bubble per drip and channel
# Mutation offers (mutation plan section 3). Chances in parts per million.
mutation.options = 3
mutation.floor_ppm = 10 # 0.001%: anomalies always happen
mutation.cap_ppm = 700_000 # 70%
mutation.score_min = -1_000
mutation.score_max = 1_000
mutation.max_multiplier_per_mille = 10_000 # weight x10 at the top score
mutation.min_multiplier_per_mille = 0 # weight x0 at the bottom (the floor still applies)
mutation.offer_interval_ticks = 500 # an offer every 25 s of active play
mutation.min_points = 25 # trait bounds in reference points (founder 100)
mutation.max_points = 1_000
mutation.recipe_min_share = 20 # per thousand of the body per channel
mutation.max_offspring = 10 # per bud, so litter at most 900
mutation.carbon_for_light_fg = 20_000_000 # carbon burned before photosynthesis is offered
mutation.buds_for_adhesion = 5 # on-demand buds before Adhesion is offered
# Reproduction (reproduction plan).
reproduction.split_share_per_mille = 800 # safety revision 1: controlled cell's share
reproduction.split_min_growth_per_mille = 500 # a cell splits once half grown
reproduction.safety_version = 1 # opt-in; historical snapshots retain revision 0
reproduction.split_launch_um_per_s = 800 # outward launch, ordinary drag/braking afterward
body.growth_reserve_seconds = 60 # growth preserves fuel for the resulting body
reproduction.bud_fee_e_pj = 250_000 # extra fee above the offspring's tissue and provision
reproduction.bud_fee_c_fg = 100_000
reproduction.bud_fee_n_fg = 30_000
reproduction.bud_fee_p_fg = 10_000
reproduction.bud_fee_o_fg = 60_000
reproduction.bud_fee_scale_percent = 50 # 0 disables the fee; 100 charges the listed amounts
reproduction.organism_cap = 256 # births refused at this many lives (an organism counts once)
# Multicellular organisms (reproduction plan section 6).
organism.load_per_mille = 500 # share of the extra members' mass loading one cell's thrust
organism.emerge_members = 8 # Emerge needs at least this many cells,
organism.emerge_mass_fg = 100_000_000 # this much body and reserve mass,
organism.emerge_reserve_pj = 0 # and this much reserve energy
# Per-mutation overrides are optional: `mutation.<key>.<field> = value`, with fields enabled,
# base_weight, increase_points, decrease_points, primary_step, paired_step, spread_step,
# increase_ticks, decrease_ticks, cost_e_pj, cost_c_fg, cost_n_fg, cost_p_fg, cost_o_fg and
# cost_scale_percent. Unset fields keep the catalog's defaults (costs 0). For example:
# mutation.strong_propulsion.cost_e_pj = 1_000_000
# mutation.strong_propulsion.cost_scale_percent = 50
@@ -0,0 +1,88 @@
# Cellular revamp trial values (rules 13, ADR-0179; Cellular_Revamp_Build_Plan.md).
# Same format as cellular.tuning: `key = value`, integers only, `_` may separate digits,
# core keys required exactly once; playtest.* and mutation overrides are optional.
# Mounted for new-region provisioning; an existing region retains its recorded rules.
tuning.version = 1
# DEV opening fixture only (ADR-0180). Zero disables seeding; never replenished on restart.
# Requires an audited --playtest-wildlife-first-id range below --life-allocator-start.
playtest.starting_wildlife_cells = 100
# Body (body and maintenance plan).
body.essential_upkeep_per_mille = 250 # share of upkeep no upkeep-efficiency trait reduces
body.reserve_load_per_mille = 1_000 # reserve matter carried as load (slower, costlier thrust)
body.growth_per_tick_centi_mille = 625 # 6.25 per mille per tick; 25% faster for playtesting
# Energy (feeding and energy plan): what 1,000 fg of reserve matter stands in for when the
# reserve's energy runs out. Bubbles carry ~17 pJ of energy per fg of matter, so 2 pJ per fg
# makes burning matter the expensive way to stay alive (a founder burns a carbon bubble in
# about 80 s of upkeep).
energy.burn_carbon_pj_per_kfg = 2_000
energy.burn_nitrogen_pj_per_kfg = 2_000
energy.burn_phosphorus_pj_per_kfg = 2_000
energy.burn_other_pj_per_kfg = 2_000
# Feeding: collection lost per membrane point above the founder's 100 (5 points: -1%).
feeding.membrane_collection_per_mille_per_point = 2
# Every collection limit, per cent of the body's own (optional; 100 when absent).
feeding.collection_percent = 130
# Matter from one source split evenly between the nutrients it holds (optional; 0 when
# absent): a carbon-only bubble gives the whole matter limit to carbon, carbon and
# phosphorus half each, all four a quarter each.
feeding.split_evenly = 1
# Predation (predation and defense plan).
predation.engulf_ratio_milli = 1_500 # a predator needs 1.5x the prey's engulf mass
predation.engulf_reserve_percent = 100 # share of reserve matter in engulf mass
predation.kill_bubble_per_mille = 500 # a kill's remainder left as bubbles; the rest is spent
# The spent pool drips back as bubbles at random spots.
spent.drip_interval_ticks = 20 # once a second
spent.drip_bubble_pj = 20_000_000 # largest energy bubble per drip
spent.drip_bubble_fg = 1_000_000 # largest matter bubble per drip and channel
# Energy cycle (ADR-0182 section 14; optional, 0 when absent): the share of the region's heat
# (energy its cells used) returned to the spent pool every tick before the drip, and whether a
# drip at the deposit limit (8,192) joins an existing bubble instead of waiting.
spent.heat_recycle_per_mille = 1_000 # all of it: energy cycles back like matter
spent.drip_absorb = 1
# Mutation offers (mutation plan section 3). Chances in parts per million.
mutation.options = 3
mutation.floor_ppm = 10 # 0.001%: anomalies always happen
mutation.cap_ppm = 700_000 # 70%
mutation.score_min = -1_000
mutation.score_max = 1_000
mutation.max_multiplier_per_mille = 10_000 # weight x10 at the top score
mutation.min_multiplier_per_mille = 0 # weight x0 at the bottom (the floor still applies)
mutation.offer_interval_ticks = 500 # an offer every 25 s of active play
mutation.min_points = 25 # trait bounds in reference points (founder 100)
mutation.max_points = 1_000
mutation.recipe_min_share = 20 # per thousand of the body per channel
mutation.max_offspring = 10 # per bud, so litter at most 900
mutation.carbon_for_light_fg = 20_000_000 # carbon burned before photosynthesis is offered
mutation.buds_for_adhesion = 5 # on-demand buds before Adhesion is offered
# Reproduction (reproduction plan).
reproduction.split_share_per_mille = 500 # the offspring's share of a mutation split
reproduction.split_min_growth_per_mille = 500 # a cell splits once half grown
reproduction.bud_fee_e_pj = 250_000 # extra fee above the offspring's tissue and provision
reproduction.bud_fee_c_fg = 100_000
reproduction.bud_fee_n_fg = 30_000
reproduction.bud_fee_p_fg = 10_000
reproduction.bud_fee_o_fg = 60_000
reproduction.bud_fee_scale_percent = 50 # 0 disables the fee; 100 charges the listed amounts
reproduction.organism_cap = 256 # births refused at this many lives (an organism counts once)
reproduction.wildlife_cap = 200 # wildlife buds refused at this many lives: the rest are for players
# Multicellular organisms (reproduction plan section 6).
organism.load_per_mille = 500 # share of the extra members' mass loading one cell's thrust
organism.emerge_members = 8 # Emerge needs at least this many cells,
organism.emerge_mass_fg = 100_000_000 # this much body and reserve mass,
organism.emerge_reserve_pj = 0 # and this much reserve energy
# Per-mutation overrides are optional: `mutation.<key>.<field> = value`, with fields enabled,
# base_weight, increase_points, decrease_points, primary_step, paired_step, spread_step,
# increase_ticks, decrease_ticks, cost_e_pj, cost_c_fg, cost_n_fg, cost_p_fg, cost_o_fg and
# cost_scale_percent. Unset fields keep the catalog's defaults (costs 0). For example:
# mutation.strong_propulsion.cost_e_pj = 1_000_000
# mutation.strong_propulsion.cost_scale_percent = 50
@@ -38,6 +38,8 @@ spec:
- {name: PGSERVICEFILE, value: /run/postgres/pg_service.conf} - {name: PGSERVICEFILE, value: /run/postgres/pg_service.conf}
- {name: EVO_PGPASS_SOURCE, value: /run/postgres/pgpass} - {name: EVO_PGPASS_SOURCE, value: /run/postgres/pgpass}
- {name: EVO_PG_RUNTIME_ROLE, value: set-by-overlay} - {name: EVO_PG_RUNTIME_ROLE, value: set-by-overlay}
# ADR-0182: the admin API's group role; empty grants no admin functions.
- {name: EVO_PG_ADMIN_ROLE, value: ""}
resources: resources:
requests: {cpu: 100m, memory: 64Mi} requests: {cpu: 100m, memory: 64Mi}
limits: {memory: 128Mi} limits: {memory: 128Mi}
@@ -10,12 +10,11 @@ resources:
images: images:
- name: aevolution-postgres-tools - name: aevolution-postgres-tools
newName: registry.aeternalisgames.com/aeternalis/aevolution-postgres-tools newName: registry.aeternalisgames.com/aeternalis/aevolution-postgres-tools
# Gitea CI run 507 for 71d195d (schema v59, durable mutation queue); the server image # Gitea CI run 576 for 9de55e3 (schema v69: one action per account a tick; bundle 15).
# is from the same run. digest: sha256:c200bd438376abf49292c63691bca8cd8adc097a9e1f94cf926250f50be1fba8
digest: sha256:0f41a3588863833dc76d4b244c9ae7d7dc3372714cf54f3b7408170ddfcac8a9
- name: aevolution-server - name: aevolution-server
newName: registry.aeternalisgames.com/aeternalis/aevolution-server newName: registry.aeternalisgames.com/aeternalis/aevolution-server
digest: sha256:f0869be511179866f9a71a63a6a5f65e577e851fd7851184734bb5c56940b1a6 digest: sha256:9ba0d78a0db2cd4016711b1c4a621f3945b4b4895d3c4a420389f281bbb781a5
patches: patches:
- target: - target:
kind: Job kind: Job
@@ -24,3 +23,7 @@ patches:
- op: replace - op: replace
path: /spec/template/spec/containers/0/env/3/value path: /spec/template/spec/containers/0/env/3/value
value: aevolution_runtime value: aevolution_runtime
# Operator-created NOLOGIN group of the admin portal's login (ADR-0182).
- op: replace
path: /spec/template/spec/containers/0/env/4/value
value: aevolution_admin
+5 -1
View File
@@ -21,7 +21,7 @@ requirements. See [the architecture](architecture/SYSTEM_OVERVIEW.md),
|---|---| |---|---|
| Absolute permadeath | Dead organisms never resume. A fresh life after death starts as a primitive cell with no account-age advantage. Voluntary one-way succession into living newborn offspring at birth is distinct from a fresh life; no return to the NPC parent or fallback after the child's death. | | Absolute permadeath | Dead organisms never resume. A fresh life after death starts as a primitive cell with no account-age advantage. Voluntary one-way succession into living newborn offspring at birth is distinct from a fresh life; no return to the NPC parent or fallback after the child's death. |
| Persistent ancestry | At birth the player stays as the parent or continues as the child; the other organism is independent wildlife. A relinquished parent retains its established behavior and reproductive plan. Independent relatives survive player logout/death and face ordinary ecology. Extinct genomes remain in history. | | Persistent ancestry | At birth the player stays as the parent or continues as the child; the other organism is independent wildlife. A relinquished parent retains its established behavior and reproductive plan. Independent relatives survive player logout/death and face ordinary ecology. Extinct genomes remain in history. |
| Structural inheritance | Body-plan changes are expressed in offspring; retain the parent's existing anatomy separately from its heritable offspring plan. Capability and construction costs remain real. | | Structural inheritance | Body-plan changes of a single cell are expressed in offspring; retain the parent's existing anatomy separately from its heritable offspring plan. A multicellular organism, one body of many cells, expresses an accepted change as a whole, funded from its reserve (maintainer, 2026-10-23; ADR-0179). Capability and construction costs remain real. |
| Player-origin biology | A world can start with geology and chemistry but no life. Every lineage must ultimately reference a player-influenced founder. Do not silently seed prebuilt wildlife. | | Player-origin biology | A world can start with geology and chemistry but no life. Every lineage must ultimately reference a player-influenced founder. Do not silently seed prebuilt wildlife. |
| Ecological progression | No classes, mandatory intelligence endgame, linear mutation tree, or cell-to-human ladder. Mixed and unfamiliar strategies are valid. | | Ecological progression | No classes, mandatory intelligence endgame, linear mutation tree, or cell-to-human ladder. Mixed and unfamiliar strategies are valid. |
| Biological costs | Traits change physical/developmental parameters. Energy, matter, nutrients and environmental constraints determine consequences. | | Biological costs | Traits change physical/developmental parameters. Energy, matter, nutrients and environmental constraints determine consequences. |
@@ -35,6 +35,10 @@ requirements. See [the architecture](architecture/SYSTEM_OVERVIEW.md),
## Recommendations versus experiments ## Recommendations versus experiments
The maintainer's 2026-10-26 test request permits opt-in randomized wildlife roots
only in disposable DEV openings ([ADR-0180](adr/0180-dev-starting-wildlife.md)).
This fixture exception does not change the player-origin requirement for product worlds.
The maintainer clarified structural inheritance, birth-time control choice and The maintainer clarified structural inheritance, birth-time control choice and
NPC-parent continuity on 2026-10-19 in NPC-parent continuity on 2026-10-19 in
[ADR-0163](adr/0163-structural-inheritance-and-offspring-succession.md). These are [ADR-0163](adr/0163-structural-inheritance-and-offspring-succession.md). These are
+150
View File
@@ -1,5 +1,155 @@
# Project status and next steps # Project status and next steps
## One action per account a tick - 2026-10-29
Region 16 playtest: a bud was shown, then undone, and several were "refused". The client
scheduled a bud at the server tick plus its lead, while movement had run ahead of that after the
lead shrank, so both named one tick. A tick takes one action per account, so the region refused
the whole tick and dropped every player's actions on it (`tick stalled ... error=4`). The region
now keeps each account's discrete action (else its newest) and refuses only the others; the client
schedules a discrete action after every tick it already sent and holds movement off that tick.
Failed commits now log their category and SQLSTATE.
## Ending a stranded life - 2026-10-29
The portal's account page can end a published life whose reservation was never ended, which
refused every new birth ("Existing cell is already bound to this account"). The admin API first
checks the region's live view for any cell holding the account; schema 69 records who ended it
and why. A region with no ticking cells now still applies queued admin commands, such as a
spawn. See [ADR-0182](adr/0182-admin-portal-and-world-tuning.md) section 18.
## Larger region ticks for testing - 2026-10-28
A region tick may hold up to 4,096 lives (was 256), for testing limits only, and
`reproduction.organism_cap` accepts up to 4,096; the DEV file keeps 256. Schema 68 raises the
database's per-tick trace counts and lets one spawn command place 256 wildlife. The region page
shows the lineage archive's fill, which stops a region at 65,536 births. See
[ADR-0182](adr/0182-admin-portal-and-world-tuning.md) section 17.
## Testing a full region - 2026-10-28
The Bud button follows a tuning adoption at once (the region's bud-cost cache was keyed by
genome only). `reproduction.wildlife_cap` keeps lives above it for players' buds. Two admin
commands (schema 67): take reserve from a cell, and remove all wildlife; the region map marks
cells (shift+click, shift+drag) for bulk removal. See
[ADR-0182](adr/0182-admin-portal-and-world-tuning.md) section 16.
## Opening regions from the portal - 2026-10-28
The Regions page can open a fresh region in place of the one DEV serves: the admin API
commits the region switch to `main` as aevolution-bot (through Secret `aevolution-admin`) and
runs a full Argo sync, and the page follows the sync until the new region is live. See
[ADR-0182](adr/0182-admin-portal-and-world-tuning.md) section 15.
## Guided tuning editor - 2026-10-28
The Tuning page is a guided editor: pick a section, edit a setting's value (units and plain
readings shown), review the changes and apply. Only the changed values are sent and applied to
the newest revision on the server, which keeps the file's comments and refuses a stale base;
the whole-file text editor remains as Text mode.
## Energy cycle - 2026-10-28
Energy now cycles like matter: the heat cells produce (upkeep, motion, growth, feeding and
predation losses) returns to the spent pool every tick and drips back as bubbles, and a drip at
the deposit limit joins an existing bubble. Both are optional rules-13 tuning keys
(`spent.heat_recycle_per_mille`, `spent.drip_absorb`), adoptable live; the DEV revamp file
turns them on. See [ADR-0182](adr/0182-admin-portal-and-world-tuning.md) section 14.
## Admin region page - 2026-10-28
The admin portal's region page is reorganized around the map: a KPI strip (tick pace,
population, deposit capacity, region energy and matter, spent pool, next drip), a map with
layer toggles, zoom and a scale, and tabs for inspecting cells and deposits, the region's
resources (where every channel sits, the spent pool and its drip), actions, the running
tuning and session access. The region view adds complete counts and totals and the drip
rules; the portal has light and dark themes. See
[ADR-0182](adr/0182-admin-portal-and-world-tuning.md) section 13.
## Live tuning - 2026-10-27
The admin portal's Tuning page edits the world's rules-13 tuning (the Git revamp file
format) and adopts it in every region at a recorded tick, without a new image or region:
upkeep, burn, feeding, predation, the spent-pool drip, mutation offers and costs,
reproduction and organisms. Revisions are append-only with author and reason (schema 66);
the reproduction safety revision stays fixed. See
[ADR-0182](adr/0182-admin-portal-and-world-tuning.md) section 13.
## Resource schedules - 2026-10-27
The admin portal can schedule recurring bubbles (the game source), spent-pool releases and
wildlife spawns per region, every 1 s to 24 h, and stop or restart them. Each run is an
ordinary recorded admin command (schema 65). See
[ADR-0182](adr/0182-admin-portal-and-world-tuning.md) section 12.
## Account administration: bans, logout, time played - 2026-10-27
The admin portal can ban (and unban) an account, which also logs it out and stops new
grants; log an account out; and shows time played, sessions, last seen and living
offspring (wildlife descended from its lives). Schema 64; see
[ADR-0182](adr/0182-admin-portal-and-world-tuning.md) section 11.
## Admin commands: spawn wildlife, resources, remove and grant - 2026-10-27
The admin portal can now spawn wildlife, add bubbles, add to or release the spent pool,
remove a cell and grant a cell's reserve, live. Commands are queued in SQL (schema 63) and
the region applies each once, recording it in its history (trace 5) so replay and recovery
reproduce it. Imports are counted in the region's boundary ledger. No new region is needed.
See [ADR-0182](adr/0182-admin-portal-and-world-tuning.md) section 10 and
[validation](engineering/VALIDATION.md).
## Session windows from the admin portal - 2026-10-27
The dev session window now lives in SQL (schema 62) instead of Git: the admin portal opens,
extends (up to four hours from now) and closes it, and the region applies the change within
about five seconds without a push, sync or restart. A closed window refuses every new
session and the region keeps running. The admin API moves to its own database role. See the
[ADR-0087 amendment](adr/0087-dev-session-route.md) and [validation](engineering/VALIDATION.md).
## Read-only admin portal - 2026-10-27
[ADR-0182](adr/0182-admin-portal-and-world-tuning.md) records the admin portal direction
(world tuning in SQL adopted per tick, admin commands, data-defined mutations) and delivers
its read-only first step: `evo-admin-api` and the portal at `https://srs.aeternalisgames.com`
behind the Keycloak realm role `aevolution-admin`. It lists accounts (session, status,
lives, deaths, resets, mutation choices), one account's lives, the world's regions, and a
live 2D view of a region's cells, wildlife, pools and bubbles from the region's new
`/admin/view` ops route. Schema 61 adds only read functions. Nothing in the simulation,
wire protocol or checkpoints changed. Not yet deployed: it needs a new server image, the
Keycloak client, an Ingress and a database Secret. See [validation](engineering/VALIDATION.md).
## Reproduction safety trial and resizable cards - 2026-10-27
[ADR-0181](adr/0181-cellular-reproduction-safety.md) declares opt-in safety
revision 1 for future rules-13 openings: 80% of mutation body/resources follow
control, the ordinary bud fee returns to the selected cell, mutation offspring
separate with an outward launch, and automatic growth protects 60 seconds of fuel.
Recorded revision 0 keeps historical simulation semantics and bytes. This is
prepared trial tuning, not live retuning, image promotion or a deployed new region.
Field notes, Vitals and Nearby resize by native edge/corner dragging, retain their
expanded sizes across collapse and clamp to the viewport. The heading reset gesture
resets size and placement. See [validation](engineering/VALIDATION.md).
## Stable and movable cellular panels - 2026-10-26
The client HUD now uses stable card dimensions and scrolling content, keeping
headings and action buttons fixed as live messages change. Field notes, Vitals
and Nearby have a dedicated drag handle, session anchoring, viewport clamping
and double-click position reset. See [controls](engineering/CLIENT_VISUAL_REFRESH.md)
and [executed validation](engineering/VALIDATION.md). No biological or wire rule changed.
## DEV startup wildlife and Bud controls - 2026-10-26
[ADR-0180](adr/0180-dev-starting-wildlife.md) implements opt-in, nursery-funded
random-genome roots at a fresh rules-13 opening, with deterministic durable
recovery and no replenishment on restart. The DEV trial prepares region 14 with
32 cells, 25% faster funded growth and the existing per-channel budding fee knobs.
Bud disables on resource shortfall and explains all five channels on hover; the
server projection includes the inherited plan and fee. See [tuning and promotion
limits](engineering/CELLULAR_PLAYTEST_TUNING.md) and [validation](engineering/VALIDATION.md).
Source/configuration preparation is distinct from image promotion and deployment.
## Photosynthesis producers (ADR-0136 step C) - 2026-10-19 ## Photosynthesis producers (ADR-0136 step C) - 2026-10-19
[ADR-0175](adr/0175-photosynthesis-producers.md) adds genome schema 5's photosynthesis [ADR-0175](adr/0175-photosynthesis-producers.md) adds genome schema 5's photosynthesis
+25
View File
@@ -131,3 +131,28 @@ at 13 px.
- **Applying it.** The scale goes to ImGui's `FontScaleMain` and to `ScaleAllSizes`, - **Applying it.** The scale goes to ImGui's `FontScaleMain` and to `ScaleAllSizes`,
taken from the unscaled style. Panel sizes are given in logical units at that scale. taken from the unscaled style. Panel sizes are given in logical units at that scale.
Movable panels return to their default place and size once, at each new scale. Movable panels return to their default place and size once, at each new scale.
## Amendment (2026-10-26): stable, anchored cellular HUD cards
At the maintainer's request, Field notes, Vitals and Nearby use a distinct drag
handle beside minimize. Client-session normalized positions remain anchored on
release, including through viewport/UI-scale changes, and clamp inside the new
viewport. Double-clicking the handle resets its position. This supersedes the
scale-reset behavior above for these three cards; no layout is saved to disk.
Their expanded outer sizes and the action dock size depend only on viewport and
UI scale. Scrollable bodies reserve scrollbar gutters and wrap live text; the
headings and action buttons stay outside those bodies. Thus temporary text and
scrollbar thresholds cannot resize/reposition the outer panels. This reuses the
pinned toolkit and existing pointer-capture boundary; biological authority,
protocols, dependencies and headless APIs are unchanged.
## Amendment (2026-10-26): cellular card edge resizing
The maintainer requested draggable panel edges. Field notes, Vitals and Nearby
now use native toolkit edge/corner resizing within bounded minimum/viewport sizes.
Client-owned expanded dimensions are stored in unscaled UI units for the session;
collapse retains them, viewport changes clamp them and the heading's double-click
resets both placement and size. Live text cannot change the chosen dimensions.
The adapter owns the toolkit's border hit margin from the first pointer event,
including presses just outside a panel. No simulation, wire or dependency changes.
+31
View File
@@ -197,3 +197,34 @@ the pod-side checks (ready, listener bound) could not show this. Decision:
Service UDP 7400 -> NetworkPolicy UDP 7400 -> evo-region M10 listener`, with the dev CA Service UDP 7400 -> NetworkPolicy UDP 7400 -> evo-region M10 listener`, with the dev CA
and issuer key read from the authorized cluster Secret without printing or persisting and issuer key read from the authorized cluster Secret without printing or persisting
them. Until that is recorded in VALIDATION.md the route is not declared working. them. Until that is recorded in VALIDATION.md the route is not declared working.
## Amendment 2026-10-27: Session windows in SQL, opened from the admin portal
Maintainer decision (ADR-0182 discussion). Committing the window to Git meant a push and a
full Argo sync for every opening or extension, and an expired window made the region exit
and crash-loop until the next sync. The window moves to the database:
- **Record.** Schema 62 adds the append-only `evolution.session_windows` (world, region,
activation id, absolute UTC expiry or none, author, reason, time written). A row with an
expiry opens or replaces the window until then; a row without one closes it. The table
refuses updates, deletes and truncation, and a window may end at most **four hours** after
it is written (the maximum is unchanged).
- **Writing.** Only the admin group role, through `admin_set_session_window_v1`, from the
admin portal (Open or Extend for 30 min to 4 h, Close). The author is the signed-in
admin's email and Keycloak subject. The runtime group may only read the newest row
(`load_session_window_v1`).
- **Reading.** The cellular region runs with `--session-window-source db` and reads the newest
row every 5 s on its session-ledger connection. A newer activation replaces the window
without disturbing open sessions; a closing, expired, over-long or missing row closes it.
Each admitted window keeps its own absolute deadline, a window once closed never reopens
(only a newer activation opens sessions again), and an unreadable database leaves the
current window to close at its deadline.
- **Closed means closed.** While no window is open, every Hello is refused with `shutdown`
before signature work, and closing closes the open sessions. Previously the cellular
bridge closed the sessions once at expiry but still admitted new ones. The region keeps
running while closed instead of exiting.
- **Git.** `REGION_SESSION_WINDOW` and the pre-push refresh are removed; the policy check
requires `--session-window-source db` and refuses a committed window. A fixed
`--session-window` remains for the lineage/primitive bridge and process tests.
The elapsed-time guard of the 2026-10-08 clock amendment is still pending.
+90
View File
@@ -0,0 +1,90 @@
# ADR-0179: Cellular gameplay revamp
## Status and scope
Accepted product direction, 2026-10-22, from the maintainer's decisions in chat.
Implementation pending; see the [build plan](../../Cellular_Revamp_Build_Plan.md).
New rules (13) only: historical rules, checkpoints, tests and running worlds keep their
meanings. Every number is a trial value in the Git tuning file. DEV-only; no World0
operation.
## Context
Playtests of rules 11-12 showed that reproduction had no purpose for the player and
that mutations were uniform draws over 32 generic operators unrelated to play. The
maintainer reviewed the cellular drafts (movement, feeding, energy and photosynthesis,
defense, the 150-entry mutation catalog) and settled each gameplay system in turn.
## Decision
The system plans are the decision. In summary:
- **Mutations** ([plan](../../Cellular_mutation_plan.md)): a named catalog of 49 with a
pro and a con each. Per-cell affinity scores, raised and lowered by behaviour
triggers, inherited and never drifting, set each mutation's chance of appearing in
an offer between a 0.001% floor and a 70% cap. Three distinct options per offer by a
seeded draw that honors those chances. Per-mutation tunable cost, reclaimed by the
region as random bubbles.
- **Reproduction** ([plan](../../Cellular_reproduction_plan.md)): on-demand buds with a
stay-or-become choice; accepting a mutation splits the cell, both halves carry the
mutation in their heritable plan, only the offspring expresses it, and the player
chooses which cell to continue as. Litter gives up to 10 offspring per bud. Adhesion
forms a multicellular organism (one genome, one reserve) whose goal is emergence.
- **Feeding and energy** ([plan](../../Cellular_feeding_energy_plan.md)): per-channel
collection rates; reserve matter stands in for energy at a worse rate; burned matter
goes to a region spent pool that drips back as bubbles; reserve matter counts toward
mass for movement.
- **Predation and defense** ([plan](../../Cellular_predation_defense_plan.md)): instant
engulfment for everyone, with engulf capacity and membrane points; a kill's remainder
is split between bubbles and the spent pool. Armor and live capture are postponed.
- **Body and maintenance** ([plan](../../Cellular_body_maintenance_plan.md)): size,
density, a heritable body recipe, upkeep efficiency above an essential floor, growth
speed and bud share.
- **Postponed:** temperature, sensing, multicellular mutations, damage, draft groups
071-150.
## Conflicts with locked requirements (resolved 2026-10-23)
The project vision is the product authority. The maintainer settled both conflicts:
1. **Whole-organism mutations: accepted.** The vision's structural-inheritance rule now
applies to single cells. A multicellular organism, one body grown from many cells,
expresses an accepted mutation as a whole, funded from its shared reserve
([PROJECT_VISION.md](../PROJECT_VISION.md) amended).
2. **Emergence before the 3D world: accepted.** Emerge records the organism's matter as
an export from the region and ends the cellular life with an "emerged" outcome; the
player then starts a fresh life. This lets the full cellular loop be played several
times before work on the 3D space.
## Durable form (2026-10-26)
- **Bundle 15** `{13, 11, 2, 1, 1, 7, 6, 2, 1}`: rules 13 on owner format 11, development 7,
founder 6, raw trace 4. Schema 60 admits it raw-only, as bundle 14 is: the manifest, births
and profile-migration parsers normalize it to bundle 14; a bundle-15 trace selection's byte
34 is its become flag; mutation results 0-6 (an organism's applied, life died, insufficient
funding, declined, split applied, split refused); the action input's become, emerge and
exclusion bits.
- **Opening `cellular-v10`.** `cellular-v9` followed by the durable 14 -> 15 revamp upgrade,
with `--revamp-tuning FILE` (the Git revamp tuning file); resumable and idempotent at bundle
15. Recovery re-derives the target from the source and the rules it declares.
- **Session v14.** See
[schemas/network/session-v14-cellular-revamp.md](../../schemas/network/session-v14-cellular-revamp.md).
## Alternatives
- Keep the generic operator catalog and add weights (ADR-0135's rules-7 proposal):
rejected; operators carried no pro or con and no behaviour link.
- Burning matter into energy through bound chemical potential (feeding draft):
rejected as a new hidden resource; matter instead stands in for energy, so no energy
is created.
- Colonies of separate cells (ADR-0135 rules 8-9): replaced by one organism with one
genome and one reserve.
## Consequences
- Benefits: reproduction drives evolution; mutations follow play; more variation
between lives; a defined path toward emergence.
- Costs: genome schema 7 with many new fields, a new owner format, session protocol
and client screens; 49 triggers' counters per cell.
- Risks: matter-as-energy may make starvation rare; the energy-kept rule cuts founder
income to 40% unless bubble energy is retuned; one deploy at the end of the build.
+41
View File
@@ -0,0 +1,41 @@
# ADR-0180: Opt-in starting wildlife for disposable playtests
Accepted scoped experiment, 2026-10-26, requested by the maintainer in chat.
The vision requires player-origin lineages. Random founding wildlife conflicts with
that rule. Resolve this only for explicitly opted-in disposable DEV openings; this
does not change the product rule or authorize a World0 operation.
The optional revamp tuning key `playtest.starting_wildlife_cells` defaults to zero
and accepts 0–255, below the region's organism cap. Provisioning a nonzero count
also requires `--playtest-wildlife-first-id`, an operator-audited unused identity
range below `--life-allocator-start`. As with ADR-0123, the operator owns the
world-wide identity audit. Never use this range in another region or restored branch
of the same world. The DEV example reserves 900000003584–900000003615 for region 14.
Seeding is an explicit input to the bundle 14 -> 15 opening upgrade. It requires an
empty region at tick 1, spends nursery resources including construction heat, and
fails atomically on inadequate funding or placement. Roots are unowned test
organisms, with no fabricated player ancestry. Each begins fully grown, undamaged,
with zero spare matter and 30 seconds of full demand as energy, using the same
founder provisioning formula as players. Genome variation uses seeded, bounded
reference indices around the founder, with no acquired modules or free mutations.
The existing format-11 archive and organism records store the entire result.
Recovery first tries the historical upgrade, then, only for an empty tick-1 source,
reconstructs the fixture from the target's count and first identity and requires
byte equality. No per-tick rule, checkpoint encoding, wire version or golden
changes. Older readers can decode these checkpoints but cannot qualify this new
opening operation; retain the writing build. Existing non-fixture upgrades retain
their exact meaning. Restart and repeated provision never replenish wildlife.
Alternatives: silently seed product worlds (violates the vision); inject on every
worker start (duplicates stock and breaks history); add a general administrator
spawn protocol (unnecessary scope). Costs: an explicit exception to the no-biology
upgrade convention, extra replay qualification, and finite nursery consumption.
This is fixture coverage, not ecological balance or production qualification.
The Bud HUD consumes the server's current offspring-plan cost plus the configured
fee. Internal-cell litter displays a conservative maximum because its random draw
occurs at action time. No new simulation or wire version is needed for correcting
this derived presentation. Growth and fee changes remain new-region trial inputs.
@@ -0,0 +1,75 @@
# ADR-0181: Opt-in cellular reproduction safety revision 1
Accepted scoped DEV experiment, 2026-10-26, from the maintainer's playtest review.
Repeated starvation and predation prevented meaningful reproduction. The maintainer
approved a controlled-cell 80/20 mutation split, retaining the bud fee in the selected
cell, outward separation at mutation birth, and a growth survival buffer. These are
trial rules, not locked balance or permission to modify World0.
## Decision
New rules-13 openings may declare `reproduction.safety_version = 1`. Missing/zero
preserves the historical law, including existing snapshots and golden outputs.
Revision 1 uses `reproduction.split_share_per_mille` as the controlled cell's share
(trial 800), whether the player stays as the parent or becomes the offspring.
Body matter and reserves divide channel by channel after mutation charges; the
offspring alone expresses the mutation. The 50%-growth eligibility gate remains.
Adhesion and whole-organism mutation retain their distinct behavior.
A mutation offspring is placed with a clear outward gap equal to one tick of its
declared launch speed, then receives outward liquid-relative velocity in addition
to inherited parent velocity, bounded by the existing velocity limit. Trial speed:
800 micrometres/second. Placement checks the launch corridor, other cells and region
boundaries, trying the existing eight deterministic directions. Failure leaves the
offer and reproduction resources unchanged; ordinary tick actions still execute.
There is no invulnerability or kinship exception: later predation, drag, currents
and braking apply. Initial separation is an escape opportunity, not a guarantee
against every surrounding predator.
The single-cell bud fee must still be affordable on top of tissue, construction
and the newborn's existing 30-second full-demand provision. On successful budding
the fee returns exactly once to the selected cell's reserve, instead of becoming
environmental bubbles. Staying refunds the surcharge; becoming transfers it to the
newborn. Wildlife has no selected player cell and retains environmental fee
reclamation. Internal-cell organism budding retains its existing fee rule.
Ordinary budding consumes no parent tissue and grants no extra resources.
For every active organism, wildlife included, automatic growth chooses the largest
ordinary funded step leaving at least `body.growth_reserve_seconds` (trial 60) of
the resulting body's full metabolic demand. Energy plus non-excluded burnable
reserve matter count after construction intake and rounding releases. Tissue
cannot count as fuel. This conservative buffer is checked, not paid: below it,
growth waits without debt or free tissue. Existing energy-limited feedback also
covers reserve protection, with no unnegotiated wire field.
## Recorded declaration and compatibility
Owner format 11 retains its byte length and bundle 15/raw trace 4. Three formerly
zero u32 words now hold safety version (after growth rate), growth reserve seconds
(after offer multipliers), and launch speed (after catalog bounds). Version 0
requires both amounts zero. Version 1 requires positive, bounded amounts; unknown
revisions are refused. Zero declarations encode exactly as before. Older readers
reject nonzero reserved words rather than replay incorrect physics. Retain the
writing build for new openings. This follows format 11's recorded collection-rate
and even-splitting extensions: it is an explicit simulation-law revision although
the outer bundle is unchanged. Recovery derives from the recorded declaration.
Git tuning affects future openings only. No live retune, reset, new DEV region,
deployment or image promotion is part of this change.
The prepared `cellular-reproduction-safety.tuning` profile lives beside the active
`cellular-revamp.tuning`, but is deliberately absent from the active ConfigMap.
The current provision image cannot parse these new keys. Test both profiles;
adopt the safety profile only with a qualified new image and a fresh region.
## Alternatives and consequences
Free reserve grants break accounting. Globally cheaper growth changes more of the
economy than protecting a buffer. Sibling immunity invents a hidden predation
exemption; physical separation keeps ordinary rules. Environmental fees leave the
selected newborn without additional provision.
The smaller sibling remains vulnerable later; the larger chosen body still costs
more upkeep. Buffering may delay growth, buds and wildlife turnover. This trial
needs aged-region playtests, not just a living population. Qualification covers
both control choices, channel closure, refusal, launch and immediate engulf attempts,
historical behavior, checkpoint restore and trace replay.
@@ -0,0 +1,473 @@
# ADR-0182: Admin portal, world tuning in SQL and per-tick amendments
## Status and scope
Accepted direction, 2026-10-27, from the maintainer's decisions in chat; delivered in parts
(sections 8-13). DEV (world 100) only; stage and World0 need their own review. Supersedes, for
rules-13 regions, ADR-0181's "Git tuning affects future openings only. No live retune": since
schema 66 (section 13) a running rules-13 region adopts tuning revisions at recorded ticks.
Regions on older rules keep their recorded rules.
## Context
Every balance change so far has meant a Git tuning edit, a new image or ConfigMap and a new
DEV region (regions 14, 15 and 16 in a week). The maintainer wants an admin portal to review
accounts, act on regions and tune the cellular game while it runs. This is a game, not a
pure simulation: designer-controlled resource sources are acceptable when they are named and
counted.
The constraint is determinism. A region's history must replay to the same state, so nothing
may change a running region except an event recorded at a tick.
## Decision
### 1. World tuning lives in SQL
- Schema 63 adds append-only `world_tuning_revisions(world, revision, parent_revision,
format, canonical_text, digest, author_subject, reason, created_at)`. A revision is the
complete canonical tuning text (`encode_cellular_revamp_tuning`), never a diff, so the
existing parser and validator are the only interpretation.
- All regions of a world share its tuning and mutation definitions (maintainer decision).
Per-region values are not offered.
- Revisions are immutable. Undo is a new revision whose text equals an earlier one.
- Git keeps the seed file for creating a world and the test fixtures. It is not consulted
by a running region, and Argo no longer carries tuning for regions on the new format.
### 2. Amendments are recorded per tick
- A region polls for a newer world revision on its existing database connection, bounded
and off the tick path (at most once a second).
- It validates the revision with its own parser. If it can parse it, it adopts it at its next
tick boundary and records `tuning_adopted(revision, digest)` at that tick in its own
history, published with that tick. If it cannot, for example because the revision uses
keys its image does not know, it keeps its current revision and reports `tuning_refused`
with the revision number. The portal shows each region's adopted revision.
- Replay and recovery read the recorded revision by number and digest, never "the latest".
- Amendments change future calculations only. Heritable values already in a genome are not
rewritten (for example, a new `mutation.min_points` does not change existing traits).
- Every tuning key is classified **live** or **opening-only**. Opening-only keys (geometry
and size, tick rate, world/frame, liquid profile structure) can be revised, but a running
region ignores them and the portal labels them "next opening".
### 3. Admin commands
- Schema 63 adds `admin_commands(world, region, command_id, kind, payload, author_subject,
reason, created_at, applied_tick, outcome)`. The admin API inserts and the region host
drains them at tick boundaries in id order, publishing each with that tick. This is the
same pattern as the durable mutation queue (schema 59).
- Kinds:
- `kill_cell(life)`: the cell dies with an "admin" outcome. Its body and reserve go to
the spent pool and drip back.
- `grant_reserve(life, inventory)`: a **game-source import** into that cell's reserve.
- `add_region_bubbles(inventory, count)`: a game-source import as bubbles at random
spots, at most the region's bubble limit per tick; the rest follows on later ticks.
- `add_pool(inventory)`: a game-source import into the spent pool.
- `release_pool(inventory)`: moves pool matter into the region through the drip settings
below, so a large release is spread over drips, never one tick.
- **Game source** is a named import in the region's accounting, like emergence is a named
export. Conservation still holds: every unit is either from the starting stock, imported
by a recorded source or exported by a recorded sink.
### 4. Drip and source settings
The spent-pool drip (today: interval, largest energy bubble, largest matter bubble per
channel) becomes one settings group used by both the pool drip and the game-source spawn:
| Setting | Meaning |
|---|---|
| `drip.interval_ticks` | how often a drip happens (0: never) |
| `drip.bubbles_per_drip` | the most bubbles one drip creates |
| `drip.bubble_max.<channel>` | the most of that channel one bubble may carry (energy pj; carbon, nitrogen, phosphorus, other fg) |
| `drip.scale_percent.<channel>` | per channel, how much faster or slower that channel is released |
| `source.per_drip.<channel>` | game-source import per drip and channel (0: none) |
For the pool, scale changes how quickly the pool drains; it never releases more than the
pool holds. For the source, scale multiplies the import.
### 5. Data-defined mutations
- Mutation definitions move from the compiled catalog into the world revision:
`mutation.<key>.*` gains the definition itself (name, description, effect, primary and
paired traits, steps, costs, triggers and requirements), not only overrides.
- A definition may use only effects, traits, triggers and requirement predicates the image
implements. Requirements come from a fixed predicate set (carbon burned, buds made, a
trait at or above a value, a mutation held). New behaviour needs code and a new image;
the region then refuses revisions using it until promoted.
- The per-cell affinity scores become a vector keyed by mutation id. New entries start at
zero. This is part of the new owner format.
- Mutations are never deleted from a running world. `enabled = 0` stops new offers;
applied mutations stay applied because their effect already changed the genome.
Replacement is disable plus a new definition.
- Session protocol: the client receives definitions (name, description, costs) instead of
using compiled names.
### 6. Accounts
- **Status**: logged in (an open session interval), banned, alive or dead, the region of
the active life, and current mutations (applied mutation results along the life's line).
- **Ban**: `account_bans(account, author_subject, reason, created_at, lifted_at)`. The grant
broker refuses a banned account (`403 account_banned`) and the ban runs the existing
logout (`revoke_account_grants`), so a live session closes within 5 s.
- **Log out**: the existing `revoke_account_grants`.
- **Grant resource**: `grant_reserve` against the account's active life.
- **Death count**: the account's lives with a death outcome.
- **Reset count**: the account's founder births after its first (a new life after death).
- **Living offspring**: living wildlife descended from any of the account's lives, using
the parent links kept since format 5.
- **Time played**: `session_intervals(account, region, started_at, ended_at)` written by the
region host on session open and close. Intervals still open at a region start are closed
at that start. History begins with this schema; earlier play is not recoverable.
### 7. Admin API and portal
- `evo-admin-api`: a C++ service built like the grant broker. It verifies Keycloak access
tokens against the realm keys pinned in Git, requires audience `aevolution-admin`,
authorized party `aevolution-admin-portal` and realm role `aevolution-admin`, and serves
one configured world. Its component exists only in the evolution-dev overlay; World0 and
stage have no admin portal (World0 has no fixed world id to refuse in code).
- Every write records the token subject and a reason.
- The region view: the region host's internal ops port gains a bounded snapshot route (cell
id, position, extent, wildlife/player and account, bubbles), reachable only from the admin
API by NetworkPolicy. The admin API serves it to the portal at up to 1 Hz.
- The portal is a static browser application at `https://srs.aeternalisgames.com`
(section **Cellular** now, **3D** later) using authorization code with PKCE. It is plain
HTML, CSS and JavaScript with no third-party code, so no dependency evaluation is needed.
- Keycloak (maintainer setup): realm role `aevolution-admin`; public client
`aevolution-admin-portal` with standard flow and PKCE S256, redirect URI
`https://srs.aeternalisgames.com/*`, web origin `https://srs.aeternalisgames.com` and
post-logout redirect `https://srs.aeternalisgames.com/`; an audience mapper adding
`aevolution-admin`; MFA required for the role.
### 8. Read-only portal (delivered first, schema 61)
- **Schema 61** adds three bounded, read-only SECURITY DEFINER functions, executable by the
runtime group and listed in the privilege audit: `admin_accounts_v1(world)` (every account
with its identity, session control, lives, deaths, active life and mutation-choice count),
`admin_account_lives_v1(world, account)` (its life requests and endings) and
`admin_regions_v1(world)` (leases and heads). No table or existing function changes. The
runtime group still has no table privilege. DEV's admin API logs in with its own login in
that group, as the grant broker does; a dedicated read role is a later least-privilege step.
- **Derived values.** A life is a published, unrefused reservation; a death is an ended one;
resets are lives after the first; logged in means the session control has not expired.
- **Region view.** `GET /admin/view` on the cellular region's ops port renders the committed
in-memory owner (`render_cellular_admin_view`): every cell (life and organism ids as
strings, account, footprint, extent, wildlife/connected/lingering/suspended flags,
members, reserve, body mass) and every pool and bubble, bounded to 4,096 cells and 16,384
deposits with totals. It reads without changing anything; the ops server's response
bound becomes configurable (4 MiB for this port), default 16 KiB elsewhere.
- **Portal files and headers.** The image ships the portal under
`/usr/local/share/evo-admin-portal`. Files go out with a strict Content-Security-Policy
(`'self'` scripts and styles, connections only to this origin and the realm), `nosniff`,
`no-referrer` and `DENY` framing; every answer is `no-store`. The access token stays in
page memory and the rotating refresh token in the tab's sessionStorage.
- **Not yet available** (they need the schema-63 records): time played, bans, current
mutations and living offspring.
### 9. Session windows and the admin role (schema 62)
The dev session window moves from Git to SQL and is opened, extended and closed from the
portal; see the [ADR-0087 amendment](0087-dev-session-route.md). Schema 62 also moves the
admin functions to a dedicated, operator-created NOLOGIN group role (`aevolution_admin` in
DEV, `EVO_PG_ADMIN_ROLE` for the migration): every migration run grants it exactly the admin
functions and audits it like the runtime group (no table privilege, no privileged
attribute, no membership outside it, not the runtime role). Schema 61's read views are
revoked from the runtime group. The admin API logs in with its own login in that group.
Writes go through POST without a body (`?minutes=M&reason=R`); the bearer token in the
`Authorization` header, never a cookie, is the only credential.
### 10. Admin commands (delivered, schema 63, trace 5)
The commands of section 3 are delivered without a new owner format or region opening:
- **Trace 5.** A rules-13 batch may record operator commands: trace 4 plus 64-byte records
(id, kind, count, target, energy and four matter amounts) counted in the tick header's last
word, which trace 4 keeps zero. A batch without commands stays trace 4, so builds before
this one still replay it; only commits that carry commands need this build or later.
Bundle 15 admits trace 5 (`cellular_checkpoint_trace_admits`); the manifest is unchanged.
- **Application.** `CellularLives::admin_candidate` applies a tick's commands after its
births, by ascending id, each on a copy kept only if it applies and still closes:
`remove_cell` (body and reserve to the spent pool, a corpse with the new `removed` cause;
a player's life then ends as any death does), `grant_reserve`, `add_bubbles` and
`add_pool` (imports in the boundary ledger), `release_pool` (moves at most what the pool
holds into bubbles) and `spawn_wildlife` (1-64 randomized founder roots, the ADR-0180 seed
with an exact import for their reserve, body and construction). A command whose target is
gone, or that does not fit (region cap, deposit limit, a taken identity), is refused and
changes nothing.
- **Queue and binding.** `admin_enqueue_command_v1` (admin role) stores the exact command;
spawning reserves its identities from the world's life allocator. The region reads
`load_pending_admin_commands_v1` every 2 s and appends up to 16 per tick. Both cellular
publishers bind every recorded command to its queue row exactly once, in the publishing
transaction; a differing or already-applied command refuses the publication. The SQL trace
parsers read a trace 5 through its trace-4 normal form, after binding the real trace to
the manifest.
- **Portal.** Region actions (spawn wildlife, add bubbles, add to or release the spent pool),
per-cell Remove and Grant reserve, and the command history with the tick each applied at.
Amounts are entered in µJ and ng.
### 11. Account administration (delivered, schema 64)
- **Bans.** Append-only `account_bans` rows; the newest per account decides. A banned
account's grant request fails with SQLSTATE EVL20 (the broker answers 403
`account_banned`), and banning also revokes its grants, so a live session closes at its
next control renewal. Lifting a ban is another row.
- **Logout.** `admin_logout_account_v1` revokes by account id, as the player's own logout
does by Keycloak identity.
- **Time played.** The session-control functions keep their signatures and also record
`session_intervals`: a claim opens one, a renewal moves its last-seen time, a release ends
it; an unreleased session ends at its last renewal. History starts with schema 64.
- **Living offspring.** The region view adds each cell's lineage root; the portal counts
living wildlife whose root is one of the account's lives.
### 12. Resource schedules (delivered, schema 65)
The game source of section 4 without a new owner format: a schedule repeats an
`add_bubbles`, `release_pool` or `spawn_wildlife` command (count, amounts per resource)
every 1 s to 24 h while enabled. When the region reads its pending commands, each due
schedule queues its next command as an operator would, so it is recorded in the trace and
bound once; a schedule never has two commands waiting, so an idle region (no living cells,
no ticks) accumulates nothing. Versions are append-only; the newest decides.
The spent pool's own drip (interval, bubble caps, bubbles per drip, per-channel scale) is a
rules setting and stays with the tuning amendments.
### 13. Tuning amendments (delivered, schema 66)
Sections 1-2 are delivered without a new owner format or opening, so running rules-13 regions
(region 16 included) can be retuned:
- **Revisions.** Append-only `tuning_revisions(revision, world, text, rules_sha256, author,
reason, created_at)`. The text is the Git revamp tuning file format, kept as the admin wrote
it (comments included); `rules_sha256` is the SHA-256 of `encode_cellular_revamp_rules` for
the rules it produces, the same canonical bytes the owner snapshot stores. The admin API
parses and validates the text (`parse_cellular_revamp_tuning`, `cellular_revamp_rules`,
`cellular_revamp_valid`) before storing it, and `admin_set_tuning_v1` queues the adoption
in every region of the world in the same transaction.
- **Adoption is an admin command.** Kind 7 `adopt_tuning` carries the revision as its target
and the rules digest in its four amount words (little-endian; `other` zero). It is queued
only through a revision, never by kind. The region fetches the revision's text
(`load_tuning_revision_v1`), rebuilds the rules with its own parser and appends the command
only when the digest matches; a text it cannot parse or a mismatch is logged and the command
stays pending (section 2's `tuning_refused`). Applied at a tick after births, the command
replaces the region's rules; it is recorded in trace 5 and bound once like any command.
- **Replay and recovery.** Applying or replaying an adoption needs whoever does it to name
the rules for that revision and digest (`CellularTuningResolver`): the host from its
verified revisions, the publisher and recovery from the successor state, checked against
the recorded digest. A batch carries at most one adoption, so its successor names exactly
one set of rules. Nothing reads "the latest" revision.
- **What cannot change live.** `reproduction.safety_version` is a law of the opening
(ADR-0181): the admin API refuses a text that changes it, and a region would refuse the
command. `playtest.*` only matters when a region opens. Heritable values already in genomes
are not rewritten.
- **Portal.** A Tuning page: the editor starts from the newest revision or the baseline file
the regions opened with (`--baseline-tuning`, the mounted Git revamp file), Check reports
the line, key and kind of a problem, Adopt stores the revision with a reason, the revision
list shows how many regions adopted each, and each region shows which revision its live
rules match (`rules_sha256` in the region view).
- **Guided editor (2026-10-28).** The Tuning page edits by section: each setting as a field
with its unit, a reading in plain units and its comment, changed values listed against the
base. `POST /api/tuning?base=baseline|REV` takes only the changed `key = value` lines and
applies them to the baseline file or to revision REV, which must be the newest (409
`stale_base` otherwise), keeping the base's comments; the result is checked and stored as
any full text. DEV's ingress admits request bodies of about 1 KB, below a whole revamp
file, so the full-text editor (kept as Text mode) reports that proxy refusal plainly.
- **Region page (2026-10-28).** The region view also carries the rules-13 drip
(`drip`: interval, energy and matter bubble caps) and, over every life and deposit whatever
the listing limits, `counts` (players, wildlife, patches, pools, bubbles) and `totals`
(reserve, body, patch, pool and bubble stock). The region page shows where the region's
stock sits, the spent pool with each channel's next drip and time to empty, a countdown to
the next drip at the measured tick pace, the deposit capacity (8,192) and whether the tick
is advancing. Its Tuning tab lists the settings the region runs (the matching revision or
baseline text) and the region tuning file (`--region-tuning`, the mounted `cellular.tuning`,
read only). The portal has light and dark themes.
Live today: everything the revamp file holds, including the drip (`spent.drip_interval_ticks`,
`spent.drip_bubble_pj`, `spent.drip_bubble_fg`). Section 4's new drip settings (bubbles per
drip, per-channel scale) are new rules fields, so they need a rules format change; the
resource schedules of section 12 cover the game source meanwhile.
Still pending from this ADR: section 4's new drip settings,
data-defined mutations (section 5) and the account's current mutations; opening new regions
or worlds from the portal (a later gate: Git-generated manifests through the Gitea API and an
Argo sync for one more region in the world; several concurrent regions or worlds need
per-region Deployments, volumes and routes).
### 14. Energy cycle (delivered 2026-10-28, live-tunable)
Matter a cell burns returns to the spent pool and drips back; energy it uses (upkeep, motion,
growth, mutation rebuilds, the share of a bubble lost in feeding, predation losses) went to the
region's heat store and never came back. Light is the only new energy, so a region without
photosynthesizers drained into heat: region 16's wildlife ate the region's energy and starved,
its spent pool held only matter, and the matter-only bubbles it dripped filled the 8,192
deposits.
- **Heat recycling.** `spent.heat_recycle_per_mille` (rules field `heat_recycle_per_thousand`,
0..1,000): at the end of every tick, before the drip, that share of the region's whole heat
store moves to the spent pool. 1,000 closes the loop, and adopting it also returns the heat
a region built up before. Energy is conserved as before (heat and spent are both region
stock). Below 1,000 the heat returns more slowly; nothing is lost.
- **Absorbing drip.** `spent.drip_absorb` (0/1): a drip at the deposit limit adds its amount
to an existing bubble, the first at or after its seeded spot in address order (wrapping),
instead of waiting. A habitat with no bubble at all still waits.
- **Encoding.** Both fields use the reserved word after the offer interval (the recycle share
in the low 16 bits, the absorbing drip in bit 16), so rules without them keep their exact
bytes, digests, checkpoints and replays. Both keys are optional in the tuning file and can be
adopted live as a tuning revision; the DEV file sets 1,000 and 1.
- **View and portal.** The region view reports `heat` and the drip's recycle share and absorb
flag; the region page counts heat in the region's energy and its ledger, and says when energy
is being lost as heat.
Not changed: a region with no living cell does not tick, so it neither recycles nor drips; an
empty region needs a spawn or a player before the cycle restarts.
### 15. Opening a region from the portal (delivered 2026-10-28, DEV)
The portal opens a fresh region in place of the one DEV serves, as was done by hand for
regions 14, 15 and 16. Concurrent regions and new worlds remain later work (per-region
Deployments, routes and ports; a multi-world admin API and broker).
- **Decisions (2026-10-28).** Replace the served region; commit straight to `main` and run a
full Argo sync at once (CI runs on the commit afterwards); the admin portal pod may reach
Gitea and argocd-server; the in-cluster Argo hop may skip TLS verification
(`ARGOCD_TLS_VERIFY=false`).
- **Credentials.** Secret `aevolution-admin` (created by the operator: Gitea base URL,
repository and repository-scoped token for `aevolution-bot`; Argo CD server, Application and
token) is mounted read-only as files at `/run/deploy` (`--deploy-config`), never as
environment; optional, so the portal runs without it and the feature stays off. Tokens travel
only in request headers and are never logged.
- **The change.** Four files, read at one commit of `main` with their blob shas
(`region_switch_paths`): the region overlay's `region-values.yaml` (REGION_ID for the
Deployment and the provision Job, REGION_LIFE_ROUTES, the opening's `--commit` and
`--playtest-wildlife-first-id`, and a one-line note above the opening), its kustomization
header, and the region named in the grant broker's routes and the portal's `ADMIN_REGIONS`.
Nothing else changes; a file whose expected lines are missing, repeated or inconsistent is
refused. The next region is one above every region with a lease in the world; its seeded
wildlife range follows the previous one by `playtest.starting_wildlife_cells`; its genesis
commit is 16 random bytes. One Gitea multi-file commit (the shas guard concurrent edits),
then `POST /api/v1/applications/<app>/sync` for exactly that commit with prune: the
provision hook opens the region before the region host restarts on it.
- **Guards.** The request names the region the portal showed (409 if another is next now);
a running Argo operation refuses (409); the portal asks the admin to type the number. The
earlier region stays in the stores, unserved; a new region's session window starts closed.
- **Network.** The portal's NetworkPolicy adds egress to 172.10.1.160:443 (Gitea through the
node's ingress) and to the argocd-server pods on 8080.
### 16. Testing a full region (delivered 2026-10-28, schema 67)
Playtesting region 16 (230 spawned wildlife under the 256-life cap) found three gaps.
- **Stale bud costs.** The region host caches each genome's bud cost for the client's Bud
button. The cache was keyed by genome only, so after a tuning adoption players saw the old
cost (or "cannot bud") until the region restarted. The cache now clears when the rules'
encoding changes.
- **Wildlife cap.** Wildlife bud whenever they can pay, so at the organism cap every slot a
death freed went to a wildlife bud before a player's bud arrived; the player saw "no space".
`reproduction.wildlife_cap` (rules field `wildlife_cap`, 0..organism cap, 0 = the organism
cap) refuses buds of a parent without an account at that many lives, keeping the slots above
it for players. Spawning still answers to the organism cap. It takes bits 17-31 of the
word holding the energy cycle (section 14), so rules without it keep their bytes and digests;
the key is optional, adoptable live, and the DEV file sets 200. The region view reports
both caps (`caps`), and the region page's Population shows lives against the cap.
- **Take and cull.** Two admin command kinds: `take_reserve` (8) moves up to the given amounts
from one life's reserve to the spent pool, per channel never more than it holds (the inverse
of `grant_reserve`); `remove_wildlife` (9) removes every life without an account in one
command, each as `remove_cell` does (body and reserve to the spent pool, a removed corpse).
Schema 67 widens the kind check and `admin_enqueue_command_v1`. The portal adds Take reserve
to the cell inspector, Remove all wildlife to Actions, and marking on the map (shift+click,
shift+drag a box) to remove the marked cells, one `remove_cell` each.
The organism cap itself is section 17.
### 17. Larger region ticks for testing (delivered 2026-10-28, schema 68)
The region/movement plan set a 2,000-organism region cap, but the rules-12 key it became
(`region.organism_cap`) was parsed and never enforced. The real bound was the engine's
`max_cellular_tick_lives = 256`, a per-tick safety bound from ADR-0106 that the batch trace,
checkpoints and database trace checks were sized from; rules 13's `reproduction.organism_cap`
was capped at it.
- **Decision (2026-10-28).** The tick bound is 4,096 lives, for testing limits only; regions
are not meant to run that many. The DEV tuning file keeps 256.
- **Split bound.** `max_cellular_tick_lives` (4,096) bounds the raw region path: the step, the
owner state, the batch trace (`cellular_batch_bytes_for`) and current checkpoint traces.
`max_cellular_frozen_lives` (256) keeps the formats whose database checks are fixed: cohort
populations, population batches, migration traces and pre-v3 cellular traces. Rules 12 and
13 never use those paths.
- **Tuning.** `reproduction.organism_cap` and `reproduction.wildlife_cap` accept up to 4,096.
- **Schema 68.** The trace checker under the current publishers (schema 43's, renamed
`cellular_births_v45` by schema 46) accepts up to 4,096 intents, births and mutation choices
per tick; `spawn_wildlife` takes up to 256 cells a command (sixteen commands fill a tick).
- **Archive.** The lineage archive never forgets: a region stops ticking at 65,536 recorded
births or 4,096 genomes. The region view reports both (`archive`) and the portal's
Population shows the fuller one, warning at 80%. A crowded region reaches them sooner.
- **Not changed.** Performance: region 16 ran at about 5 of 20 ticks per second with about
250 lives, so a region near the bound will run far below real time. The client snapshot is
budgeted (nearest changes first), so it degrades rather than fails.
### 18. Ending a stranded life (delivered 2026-10-29, schema 69)
Region 16 playtest: the region refused every birth for an account with "Existing cell is
already bound to this account", although no cell in it held the account. The database refuses
a birth while the account has an open life reservation anywhere in the world; this one was
published and never ended. How it was left open is not yet known. Until 2026-10-29 the only
remedy was `tools/ops/end-account-life.sql` as the database owner.
- **Account action.** `POST /api/accounts/<uuid>/end-life?request=N[&reason=R]`. The admin API
reads the life's region from the account's lives, fetches that region's live view and refuses
(409 `life_in_region`) while any listed cell holds the account, including a bud, a split's
offspring or an organism that control moved to. It also refuses a region it cannot view, a
view that does not list every cell, a request never published (404) and a life no longer open
(409 `not_open`).
- **Schema 69.** `admin_end_account_life_v1` (admin role only) ends the reservation at the
region's latest commit, as `end_cellular_lives` does, and appends who and why to
`admin_life_endings` (immutable). Unpublished reservations stay with the region, which still
holds them as queued births. Checkpoints and history are unchanged.
- **Safety.** If the check were wrong, the region still refuses a birth for an account that holds
a cell in its state (`life_exists`), which records an existing-life refusal.
- **Existing-life refusals are recorded.** That refusal could never be recorded:
`reject_primitive_life` (schema 15) accepted only reasons 1 to 3, and existing_life is 4.
The region dropped the birth from its queue but left the reservation open and unpublished,
which then refused every later birth for the account. Schema 69 accepts 4, both in the
function and in its C++ wrapper.
- **Portal.** The account page shows an End life button for each published life that has not
ended.
- **Idle regions take commands.** A region ticks only while something needs it: a player, a
waiting birth, a cell not suspended, or ecological work. A command queued in an empty region,
such as a spawn of wildlife, waited until something else woke it. A queued admin command now
keeps the region ticking until it is applied.
## Delivery order
1. Read-only portal: login, accounts (from existing data), regions, region view (schema 61,
section 8).
2. Schema 63 and the new owner format: world revisions, adoption records, admin commands,
game source, drip settings, the score vector, session intervals and bans. One new
opening on that format.
3. Admin commands and account actions in the portal.
4. Live tuning in the portal.
5. Data-defined mutations in the portal.
## Deferred
- **Cell migration between regions.** With world-shared tuning and mutations it no longer
meets per-region mismatches, but still needs the paired transfer extended to the new
format and to player lives, and a client handoff.
- **New matter types.** `accounting::Element` has four channels throughout accounting,
traits, bubbles, the protocol and the client. A later decision; a fixed number of matter
slots is the expected approach.
## Alternatives
- **Export portal changes to Git and reopen regions.** Rejected: more steps for the same
result, and not live.
- **Change values in a running region's memory.** Rejected: replay and recovery would diverge.
- **Per-region tuning.** Rejected: all regions of a world share rules.
- **Database push instead of polling.** Not needed at one adoption check per second.
## Consequences
- Balance changes become data: no image, ConfigMap or region per change.
- Balance history moves from Git review to the revision table (author, reason, full text).
It is covered by database backups and history domains (ADR-0155).
- Argo no longer shows tuning drift for new-format regions; the portal shows each region's
adopted revision instead.
- One more opening is required, for the new owner format.
+8
View File
@@ -1,5 +1,13 @@
# Architecture decision records # Architecture decision records
- [ADR-0182: Admin portal, world tuning in SQL and per-tick amendments](0182-admin-portal-and-world-tuning.md) - accepted direction: world tuning revisions in SQL adopted per tick and recorded in region history, admin commands with a named game source, drip/source settings, data-defined mutations, bans and session intervals, and a Keycloak-gated admin API and portal; the read-only portal (schema 61 read views and the region view) comes first; migration and new matter types deferred.
- [ADR-0181: Reproduction safety revision 1](0181-cellular-reproduction-safety.md) - opt-in controlled-cell mutation share, retained budding provision, outward mutation launch and a protected growth fuel buffer; historical declarations unchanged.
- [ADR-0180: DEV starting wildlife](0180-dev-starting-wildlife.md) - opt-in, nursery-funded random-genome roots for disposable playtest openings, exact recovery and no restart replenishment; a scoped exception to player-origin biology.
- [ADR-0179: Cellular gameplay revamp](0179-cellular-gameplay-revamp.md) - maintainer-accepted direction for rules 13: a 49-mutation catalog with behaviour-weighted offers, mutation splits and stay-or-become reproduction, multicellular organisms and emergence, matter as energy with a region spent pool, per-channel collection, membrane points and heritable body traits; two locked-requirement questions open; implementation pending.
- [ADR-0178: Durable liquid regions and session v13](0178-durable-liquid-region.md) - rules 12 on owner format 10 (currents, moving food, liquid motion), raw bundle 14 and schema 58 with a 13 -> 14 upgrade from the Git tuning file, the `cellular-v9` opening and session v13 (motion, currents, brake). - [ADR-0178: Durable liquid regions and session v13](0178-durable-liquid-region.md) - rules 12 on owner format 10 (currents, moving food, liquid motion), raw bundle 14 and schema 58 with a 13 -> 14 upgrade from the Git tuning file, the `cellular-v9` opening and session v13 (motion, currents, brake).
- [ADR-0177: Cellular regions, world linkage and emergence](0177-cellular-regions-world-linkage.md) - maintainer-accepted direction: regions map to a world area rather than a voxel, currents and the thermal map are conditions not stock, capped regions refuse births, scaled emergence export, protected anchored logout; implementation pending. - [ADR-0177: Cellular regions, world linkage and emergence](0177-cellular-regions-world-linkage.md) - maintainer-accepted direction: regions map to a world area rather than a voxel, currents and the thermal map are conditions not stock, capped regions refuse births, scaled emergence export, protected anchored logout; implementation pending.
+20
View File
@@ -111,3 +111,23 @@ observations only; optical liquid shading is not a thermal field. Body temperatu
ambient temperature and directional heat guidance remain pending authoritative ambient temperature and directional heat guidance remain pending authoritative
phase-3 state and a negotiated perception contract. Existing public library and phase-3 state and a negotiated perception contract. Existing public library and
wire interfaces are unchanged. wire interfaces are unchanged.
The [DEV playtest tuning](../engineering/CELLULAR_PLAYTEST_TUNING.md) Bud control
uses the current server-projected charge, including the inherited plan and fee.
Insufficient funding disables it, with a hover tooltip listing required and held
energy, carbon, nitrogen, phosphorus and other matter. Internal-cell litter shows
the maximum possible charge. The server remains authoritative at execution time.
The cellular HUD cards use client-owned session placement in `FormBuffers`.
Only each heading's drag handle moves its card; normalized anchors are retained
through redraws, collapse/restore and viewport/scale changes, with on-screen
clamping and a double-click reset. Fixed outer dimensions and scrollable bodies
with reserved gutters prevent live text from feeding back into panel geometry.
The action dock's button row stays outside its scrolling details. This state is
presentation-only and is neither persisted nor sent to the server; see the
[visual refresh controls](../engineering/CLIENT_VISUAL_REFRESH.md).
These three cards also resize by dragging any edge or corner. Expanded dimensions
are client-session values in unscaled UI units; minimize/restore preserves them,
viewport changes clamp them and the handle's double-click resets position and size.
The pointer-capture boundary includes native resize border hit margins.
@@ -0,0 +1,70 @@
# Cellular playtest opening controls
The reproduction safety trial is recorded as `reproduction.safety_version = 1`
([ADR-0181](../adr/0181-cellular-reproduction-safety.md)). Its split share is the
controlled cell's share (800/1000); mutation offspring launch at 800 um/s; growth
preserves 60 seconds of the resulting body's full-demand fuel. Ordinary bud fees
return to the selected player cell. Missing safety keys preserve historical rules.
These declarations apply to future openings only, not an existing running region.
The complete prepared profile is
`deploy/kubernetes/region/dev/tuning/cellular-reproduction-safety.tuning`; it is not
mounted by the active overlay. Use it as `--revamp-tuning` only with a build that
supports safety revision 1 and a fresh opening. The currently mounted profile
remains compatible with the currently promoted image. Image/region promotion is
a separate operation; a Git push does not activate the gameplay trial.
These trial settings live in
`deploy/kubernetes/region/dev/tuning/cellular-revamp.tuning`. They are read by
`evo-world-clone provision --opening cellular-v10 --revamp-tuning FILE`; the owner
then retains its recorded rules. Editing the file does not retune an existing
region. Open a fresh disposable region for a changed trial. See [ADR-0180](../adr/0180-dev-starting-wildlife.md).
| Key | Current DEV value | Meaning |
| --- | --- | --- |
| `playtest.starting_wildlife_cells` | 32 | Initial random-genome cells; 0 disables; max 255 and below the organism cap. Omission defaults to 0 for older files. |
| `body.growth_per_tick_centi_mille` | 625 | 6.25 per thousand per tick at growth speed 100, up from 5: 25% faster when funded. |
| `reproduction.bud_fee_e_pj` | 250000 | Additional energy fee per bud action. |
| `reproduction.bud_fee_c_fg` | 100000 | Additional carbon fee. |
| `reproduction.bud_fee_n_fg` | 30000 | Additional nitrogen fee. |
| `reproduction.bud_fee_p_fg` | 10000 | Additional phosphorus fee. |
| `reproduction.bud_fee_o_fg` | 60000 | Additional other-matter fee. |
| `reproduction.bud_fee_scale_percent` | 100 | Percentage of the listed fee charged; 0 disables it. |
The fee controls already existed; this change activates and documents them and
corrects the displayed cost to include them. Offspring tissue and starting reserve
remain funded biological costs. Faster growth spends the same resources in less
time; insufficient nutrients can still hold it back.
The DEV manifest prepares world 100, region 14, with a new stable genesis commit
and `--playtest-wildlife-first-id 900000003584` below
`--life-allocator-start 1000000000000`. This declares a reserved fixture range;
operators must audit its uniqueness across the world's other retained regions.
Regions 1–13 remain stored. Counts other than 32 need a correspondingly audited
range and enough nursery stock. The fixture spends the nursery rather than
minting resources; player founders draw its remainder.
Each cell uses founder-6 capabilities and full growth, no damage or spare matter,
30 seconds of its own full demand as reserve energy, and a seeded genome with
75–125-point body, collection, burn, engulfment and movement indices. It has no
acquired modules, player account or fabricated ancestry. Randomness is stable
for world, region and identity. Normal autonomous wildlife control takes over.
Recovery and repeated provisioning retain the saved population, including deaths;
they do not top it up.
Bud uses the current expressed parent and inherited offspring plan, plus the fee;
internal-cell litter conservatively shows its largest possible charge. Hover a
grey Bud button to inspect every required/available channel. A resource-ready
button still submits an intention: growth, placement, regional capacity and
changes before execution can affect the authoritative outcome.
The region-14 configuration requires an image built from this change before
manual Argo sync. The currently pinned image is not claimed to support the new
opening flag. Build promotion, deployment, live playtesting and identity auditing
against production stores were not performed by these local checks. No World0
operation is involved.
Focused durable verification in a new private local PostgreSQL cluster:
```sh
bash tools/ci/postgres-check.sh --starting-wildlife-only "$PWD/build/playtest-postgres/evo-postgres-tests"
```
+27 -3
View File
@@ -37,9 +37,27 @@ violet for budding. Labels and authoritative enable/disable logic remain intact;
color alone does not communicate affordability or success. Existing bindings color alone does not communicate affordability or success. Existing bindings
remain authoritative; decorative shortcut numbers are not invented. remain authoritative; decorative shortcut numbers are not invented.
Field notes, Vitals and Nearby have explicit minus/plus buttons. Collapsing Field notes, Vitals and Nearby have explicit minus/plus buttons and a separate
Vitals retains energy. State lasts for the client session; it is not saved. `::` drag handle. Drag the handle to place a card; releasing anchors its position.
The responsive compact layout keeps the dock and map within the viewport. Double-click the handle to restore the responsive default. Collapsing Vitals
retains energy. Placement and collapse state last for the client session and are
not saved to disk. Anchors use normalized viewport coordinates and are clamped
inside the window when it is resized or the UI scale changes.
Expanded card sizes depend on viewport/scale, not the current text. Overflow
scrolls inside a body with a reserved vertical scrollbar gutter; headings stay
fixed and long text wraps at the body width. Minimize/restore intentionally
changes a card's height. The action dock likewise keeps its buttons fixed above
a scrollable details area. Changing nutrient values, growth warnings, pending
results, region-edge notices and stale observations cannot resize or re-anchor
these panels. The responsive compact layout keeps the dock and map within the viewport.
Resource-table rows also have stable single-line geometry: names and formatted
quantities never inherit prose wrapping. The amount column reserves the widest
supported energy/mass readout at the current font/scale, including the full u64
range, independently of live values. A growth-limiting nutrient shows `*` in its
existing dot slot, with the same bar outline; the marker never lengthens an amount.
This prevents transitions such as `714 fg` to `1.54 pg` from shifting later rows.
Nearby is a camera-centred observation map with a fixed six-millimetre radius. Nearby is a camera-centred observation map with a fixed six-millimetre radius.
It reads the received food and organism views only, including observations It reads the received food and organism views only, including observations
@@ -77,6 +95,12 @@ Proposed resolution, not an accepted protocol or biological rule:
## Validation ## Validation
Field notes, Vitals and Nearby can be resized by dragging any edge or corner.
Minimum dimensions keep controls readable, while larger content scrolls inside
the chosen bounds. Sizes last for the client session, survive minimize/restore,
and adapt to UI scale and viewport limits. Double-click the heading's drag handle
to reset both size and position. Resizing captures input before world controls.
The native panel suite exercises multiple sizes, collapse/restore and input The native panel suite exercises multiple sizes, collapse/restore and input
capture alongside existing mutation, affordability and action tests. See capture alongside existing mutation, affordability and action tests. See
[VALIDATION](VALIDATION.md) for executed builds, screenshots and environmental [VALIDATION](VALIDATION.md) for executed builds, screenshots and environmental
+396
View File
@@ -10178,3 +10178,399 @@ Environmental limits and initial failures:
The AGENTS.md-required pre-push session-window refresh is desired Git configuration The AGENTS.md-required pre-push session-window refresh is desired Git configuration
only. No deployment, live reachability, World0 mutation or world reset is claimed. only. No deployment, live reachability, World0 mutation or world reset is claimed.
## 2026-10-26 - DEV starting wildlife and resource-aware Bud
Scope: ADR-0180's explicit disposable DEV fixture, cellular opening/recovery,
server-projected budding requirements, native Bud control, and new-region tuning.
Existing unrelated drafts and untracked files were preserved. No golden, per-tick
simulation version, checkpoint encoding or wire layout changed.
Executed:
- GCC 14.2 Release with NDEBUG, configured from the release preset with client and
network enabled in build/playtest-release: complete CTest suite 122/122 passed.
Final focused UI-model/owner checks passed 2/2 after a test-only optional-access
cleanup and formatting-only correction in the affected revamp module.
- MSVC 19.44 client preset build succeeded; client CTest 10/10 passed. The final
UI-model cleanup was rebuilt and its test passed again. TMP/TEMP were directed
to ignored build/playtest-windows-tmp for local bindings-file checks.
- Clang 19 ASan+UBSan, existing asan-preset build/client-asan: focused tuning,
owner, UI-model and native panel checks 4/4 passed; final UI-model cleanup 1/1.
- PostgreSQL 18.6, GCC 14 Release with the existing prepared dependency:
tools/ci/postgres-check.sh --starting-wildlife-only against
build/playtest-postgres/evo-postgres-tests passed in a fresh private local
cluster. It published an empty genesis and all prerequisite upgrades, seeded
32 funded roots, replaced the lease, recovered byte-identical state, published
a real wildlife tick and replayed it identically without adding more cells.
- Parser/owner coverage includes optional count default zero, count bounds,
deterministic genome/placement, ordinary founder endowment rules, exact
conservation, refusal on inadequate nursery stock, invalid identities and
repeated seeding, and restored continuation. Cost checks include the fee;
UI checks cover all five shortfall channels and exact affordability equality.
- Native panels exercise 640x480, 960x640 and 1280x800, including the production
disabled Bud hover tooltip, refusal to click while short, and funded clicking.
A cost-aware fixture exposed Vitals gaining horizontal overflow after restore;
fixed content width and a reserved vertical scrollbar resolved it.
- Repository format-check passed with clang-format 19. A pre-existing formatting
violation in the affected cellular_revamp.cpp was corrected. git diff --check
passed. Rendered deployment policy passed (75 source objects, 140 rendered
objects, 17 overlays); its 50-case fail-closed self-test passed.
Limits and initial failures:
- The Windows debug build stopped with MSVC C1902 (program-database manager
mismatch) before compiling the changed code; the Windows Release client build
and Linux Release/sanitizer builds succeeded. No debug pass is claimed.
- Initial compiler and static-analysis failures (a missing draft initializer and
optional-access checks), plus the native layout/hover fixture failures, were
corrected before the successful checks above. An initial sanitizer compile
overlapped a header formatting write; the stable-source rerun passed.
- These are local fixtures, not live gameplay, ecological balance, hardware
performance, or production-store identity-audit evidence. DEV region 14 needs
a compatible image promotion before manual Argo sync. No deployment, live
reachability, World0 change, reset or pruning was performed. The AGENTS.md
pre-push session-window refresh is desired Git configuration only.
Final static analysis: the analysis preset in build/playtest-analysis built the
changed lifecycle, tuning, persistence, bootstrap and client targets, plus their
regressions, with clang-tidy 19 and warnings as errors. Its focused CTests passed
5/5 and the isolated PostgreSQL opening/recovery check passed again. A pre-existing
unchecked optional access in the touched UI-model test was rewritten through its
existing checked helper. Changed C++ files also passed clang-format 19 dry-run.
The actual QUIC-enabled evo-server also built successfully in build/tidy-postgres.
A separate clang-tidy-19 run on its main translation unit, with an explicit
cellular_bridge.hpp header filter and warnings as errors, passed. It required a
pre-existing optional-feedback access to be made local before checking/reading.
The bridge header passed the Linux clang-format 19 dry-run (minor formatter
versions differ on an existing multiline lambda's wrapping).
Publication limit: the scoped commit was created locally, but the configured HTTPS
remote rejected git push with an authentication failure. Git Credential Manager
is configured; no stored credential was deleted or changed. A user-authorized retry uses credentials supplied outside the repository. Unrelated drafts and untracked files
remain outside the commit.
## 2026-10-26 - Stable HUD geometry and anchored panel dragging
Scope: apps/evo-client panel drawing/state and native panel regression, with the
ADR-0084 presentation amendment. No simulation, server, wire, dependency or
persistent-settings format changed. Unrelated drafts and untracked work remain
untouched.
Executed:
- GCC 14.2 Release/NDEBUG in the existing release-preset build/playtest-release:
rebuilt evo-client, panel and UI-model targets; client CTests excluding the
panel test passed 9/9. The final production panel executable passed separately
with SDL_VIDEO_DRIVER=dummy, SDL_RENDER_DRIVER=software and review output in
ignored build/hud-review. Earlier panel CTest runs also passed during iteration.
- MSVC 19.44: tools/windows-check.ps1 -Preset client -Action check passed; all
10/10 client CTests passed with TMP/TEMP in ignored build/playtest-windows-tmp.
- Clang 19 analysis-preset build/playtest-analysis: rebuilt evo-client and its
panel regression with clang-tidy and warnings as errors; build passed.
- Clang 19 ASan+UBSan, existing asan-preset build/client-asan: rebuilt the final
native panel test and its production panels; focused CTest passed 1/1.
- Repository format-check passed with clang-format 19, including a dry run of
the changed app header through the same formatter; git diff --check passed.
- Native coverage at 640x480, 960x640 and 1280x800 changes diagnostics/membership,
growth warnings, sunlight, edge/stale/census text and expanded notes on each
of 16 consecutive frames. Outer position/size and child content width must
remain identical, with zero horizontal overflow. Action details exercise both
fitting and vertically overflowing content without changing the button row.
- Real SDL pointer events drag all three card handles, release and retain their
anchors, minimize/restore a moved card, resize the viewport, drag far outside
bounds and double-click the reset handle. Bounds and pointer capture prevent
world clicks. Existing Bud/tooltip, evolution, death/restart and panel capture
checks remain in the same native regression.
- Generated native BMPs for normal, overflowing and moved panels in
build/hud-review. Reviewed PNG conversions at 640x480, 960x640 and 1280x800.
The first review showed the nutrient legend breaking a word in its narrower
scrolling body; a tighter two-column legend with unwrapped names fixed it,
followed by the final Release, Windows, analysis and sanitizer checks above.
Limits: positions/collapse state are client-session preferences, not saved across
application restarts. Hardware DPI, accessibility, touch interaction and motion
comfort still need interactive review. No deployment, live session, World0 change,
reset or prune occurred. The required pre-push session-window refresh is desired
Git configuration only.
## 2026-10-26 - String-length stability inside nutrient tables
Reviewed the supplied Recording 2026-10-26 171124.mp4 locally (420x428, 5.83 s).
The outer Vitals card was already fixed; its carbon amount changed from
714 fg * to 1.54 pg *, wrapping the marker and shifting later nutrient rows.
The prior outer-geometry regression did not check those inner row baselines.
Changes: quantity/name cells explicitly disable prose wrapping; a font/scale-based
fixed amount-column width covers the largest supported energy and mass readouts.
The growth-limiting * occupies the existing nutrient-dot slot, with unchanged
bar outline and explanatory legend. No number formatting, simulation rule,
checkpoint, protocol, dependency or public API changed. The shared table also
serves mutation cost readouts.
Executed:
- First added the native table-geometry regression without the fix. It failed
at the baseline/height assertion on the old renderer, reproducing the recording.
- GCC 14.2 Release/NDEBUG, build/playtest-release: rebuilt evo-client and native
panel tests. Focused panel CTest passed; the final executable also passed with
review screenshots under SDL_VIDEO_DRIVER=dummy and SDL_RENDER_DRIVER=software.
- Regression spans 714, 999, 1000, 1540, 9999, 10000 and higher unit boundaries,
zero and UINT64_MAX. It checks unchanged last-row baseline, total table height,
amount-column width and zero horizontal overflow. Viewports are 640x480,
960x640, 1280x800 and 1600x1008; the latter exercises the recording's 1.4 scale.
Existing dragging, anchoring, Bud, mutation and death/restart paths still run.
- MSVC 19.44 client preset check: build succeeded and client CTests passed 10/10.
TMP/TEMP used ignored build/playtest-windows-tmp.
- Clang 19 analysis-preset build/playtest-analysis: production client and panel
regression built with clang-tidy and warnings as errors.
- Clang 19 ASan+UBSan build/client-asan: focused native panel CTest passed 1/1.
- Changed C++ files passed clang-format 19 dry-run. The full format-check initially
found an existing wrapping violation in cellular_revamp.cpp; normalized those
lines only, verified identical non-whitespace text, and the full gate passed.
git diff --check passed. No server behavior changed by that formatting correction.
- Visually reviewed generated Vitals crops for 714 fg, 1.54 pg and UINT64_MAX at
1.4 scale in ignored build/string-bounce-review/fixed/stock-comparison.png.
All four rows stay aligned and the full formatted maximum remains visible.
Video decoding used the existing ignored review-tool FFmpeg, not a new runtime
or repository dependency.
Limits: local software-renderer fixtures do not replace interactive hardware DPI
and accessibility review. No deployment, World0 change, reset or pruning was
performed. Existing unrelated drafts and untracked files were preserved; the
required pre-push session-window update is desired Git configuration only.
Publication limit: the scoped commit was created locally, but the configured
Gitea remote returned HTTP 500 during push. Two bounded read-only remote checks,
including a delayed HTTP/1.1 check, returned the same server error. Publication
remains pending remote recovery. No force push, credential-store change, server
operation or deployment was attempted.
## 2026-10-27 - Reproduction safety revision 1 and resizable cellular cards
Scope: ADR-0181's explicitly recorded rules-13 safety revision, portable lifecycle
funding/placement/growth, optional tuning and native card geometry/input capture.
The active DEV tuning retains its previous contents; the complete safety profile
is staged separately and is not mounted by the current overlay. No default world,
manifest bundle, genome, wire version or golden was replaced. Older readers refuse
the new nonzero reserved declarations instead of replaying the wrong law.
Executed:
- GCC 14.2.0 Release/NDEBUG, existing release-preset build/playtest-release:
complete build and CTest passed 122/122. After separating the staged profile,
rebuilt and reran the tuning and region-step contracts: 2/2 passed, including
both the active historical file and new trial file in the tuning test.
- MSVC 19.44.35217.0: tools/windows-check.ps1 -Preset client -Action check
passed 10/10, including the final panel code. Headless Release built and passed
107/108 initially; cli-file-integration could not create its build-local hard
link under the restricted sandbox. The isolated test passed 1/1 when rerun with
that filesystem permission. Thus all 108 headless tests passed across the full
run and permission-corrected rerun. TMP/TEMP used build/playtest-windows-tmp.
A pre-existing MSVC narrowing warning in the related revamp-step fixture was
corrected with explicit casts of its fixed 3000x2000 coordinates; no test value
or production rule changed.
- Clang 19.1.1 analysis-preset build/playtest-analysis: rebuilt the production
client/panels, lifecycle, owner/tuning regressions with clang-tidy and warnings
as errors. The final separate-profile/portable-step test build passed as well.
- Clang 19 ASan+UBSan, asan-preset build/client-asan: selected native panels,
revamp region-step, tuning and owner CTests passed 4/4. Owner checks took
221.59 s, within their existing 300 s timeout. The final separate-profile
tuning/portable-step rebuild and focused sanitizer CTest passed 2/2 as well.
- Repository format-check with clang-format 19 passed; git diff --check passed.
- Both mutation control choices check exact body/reserve allocation against
constant 800/200 shares, conserved resources, inherited plans and control,
outward velocity, separated footprints, a next-tick engulf attempt, exact
checkpoint restore and raw trace-4 replay. Unknown/inconsistent safety
declarations are refused; missing optional keys preserve revision 0.
- Both ordinary bud choices check the fee retained/transferred exactly once,
unchanged parent tissue, unchanged environmental deposit count and full
closure/restore. A finite, deliberately rich, high-collection fixture isolates
allocation from navigation. Subsequent actual juvenile growth checks that
every observed construction step leaves the new body's 60-second fuel buffer;
the low-fuel mutation fixture checks deferred growth. This is not balance
qualification or evidence that a live aged region has sufficient food.
- Native SDL pointer events resize all three cards across horizontal and vertical
edges, including top/left placement changes and the outer border hit margin.
Tests verify no world clicks, retained sizes after minimize/restore, viewport
clamping, reset and zero horizontal overflow, alongside stable live text and
existing mutation/bud/restart controls at four viewport sizes.
- Generated native BMPs with the software renderer in
build/reproduction-safety-review and visually inspected resized.png (960x640).
PNG conversion used Windows System.Drawing; no runtime dependency was added.
Limits: live SQL crash/recovery drills, hardware DPI/accessibility and aged-region
ecological playtests were not run. This change does not promote an image, open or
reset a region, deploy, prune or operate on World0. Unrelated drafts and untracked
files remain untouched. The mandatory pre-push session-window refresh is desired
Git configuration only, not a claim of live reachability.
Publication history: the initial push followed the required session-window
refresh but the remote rejected authentication ("Failed to authenticate user").
The maintainer subsequently supplied an external local credential file and
authorized a retry. An authenticated read-only remote check passed. The retry
uses per-command askpass credentials with the stored helper disabled for that
command, and another unique session activation expiring four hours ahead. No
credential values, credential file, remote URL change or credential-store change
are included in the repository; temporary helpers stay in ignored build output.
No deployment or live-reachability claim follows from publication.
## 2026-10-27 - Read-only admin portal (ADR-0182 step 1, schema 61)
Scope: ADR-0182's read-only first step. `evo-admin-api` (Keycloak realm role
`aevolution-admin`, audience `aevolution-admin`, client `aevolution-admin-portal`) serves
the static portal and read-only JSON for world 100; schema 61 adds three bounded
SECURITY DEFINER read functions; the cellular region's ops port gains `/admin/view`.
The token verifier gains an optional realm-role rule and returns the email; the ops
server's response bound becomes configurable (default unchanged). No simulation rule,
checkpoint, manifest, wire protocol, genome or golden changed; `extent_of` reads the
existing phenotype budget.
Also fixed a pre-existing PostgreSQL failure (`region store test line 826`, also seen in
Gitea run 542): since 054e485 the DEV revamp tuning file seeds 100 wildlife, which
`evo-world-clone provision` refuses without an audited `--playtest-wildlife-first-id`
range. The cellular-v10 provisioning test now provisions the Git file's rules with its
DEV opening fixture set to zero; seeded wildlife keeps its own suite. Earlier push builds
skipped the PostgreSQL gate, and the 09:00 nightly (run 539) stopped at the format check,
so the failure had not surfaced.
Executed (WSL Ubuntu, GCC 14.2 Release/NDEBUG, existing build/m97-postgres with network,
QUIC and PostgreSQL):
- Built evo-server, evo-world-clone, evo-grant-broker, evo-admin-api, evo-postgres-tests
and evo-cellular-admin-view-tests with -Werror (two missing-field-initializer errors
from the new aggregate members were fixed with default initializers).
- `cellular-admin-view-contracts` passed: header, totals, every cell row (id strings,
account text, position, extent, connected flag, members), the cell and deposit limits
keeping the lowest ids, empty lists, and an unchanged owner snapshot after rendering.
- `tools/ci/postgres-check.sh --suite-only` passed after the fixes above: token role
checks (required role present, absent, wrong shape; email), the admin API over world
9831 (public files with CSP/nosniff headers, `/config.json`, 405 for POST, 401 without or
with a foreign token, 403 without the role, no database contact before verification,
accounts with session/status/lives/resets, one account, 404s, regions, the view cache,
unviewable and unreachable regions, an offline database as 503, and the runtime role
still refused direct table reads), the migration path to schema 61 with the privilege
audit's new fenced functions, and the updated migration history expectation.
- `tools/ci/postgres-check.sh --full` passed (634 s: suite, migration partitions, life
reservations, backup, DR, upgrade, migration history, permission audit, checksum drift).
Two CI scripts that pin the newest schema were updated: history-domain-check's schema-50
rewind now drops the three schema-61 functions first, and the unknown-future-version
probe moves from 61 to 62.
- clang-tidy 19 with warnings as errors on every new or changed source passed after one
unchecked-optional fix in the view test; clang-format 19.1.5 applied to changed C++.
- Deploy suite (deploy-policy-check 80 objects / 150 rendered in 17 overlays, selftest,
ops-lib-check) passed with the new admin-portal-dev component.
- Local process smoke of the built evo-admin-api with the realm's pinned JWKS and a
placeholder (unreachable) database: `/`, `/app.js`, `/style.css`, `/config.json`,
`/healthz` answered 200 with the expected types and security headers, `/api/accounts`
401 for a malformed token, `/missing` 404; no arguments exit 2 with usage.
- `node --check` on the portal script.
Limits: no Keycloak sign-in, browser session or live region view was exercised (the
Keycloak client, Ingress, Secret and a new server image are not in place yet); account
lives and deaths were checked only on accounts without lives. The MSVC and sanitizer
presets and the image build/smoke were not run locally. Nothing was deployed, pushed or
synced; no World0, stage or live database operation occurred.
## 2026-10-27 - Session windows in SQL and the admin role (schema 62)
Scope: the ADR-0087 amendment and ADR-0182 section 9. Schema 62 adds the append-only
`session_windows` table, `load_session_window_v1` (runtime), `admin_set_session_window_v1`
and `admin_session_windows_v1` (admin), and moves schema 61's views to the optional
operator-created admin group role, granted and audited on every migration run. The cellular
region reads the window every 5 s with `--session-window-source db`; `RegionSessions` gains
an admission switch so a closed window refuses Hellos before signature work (previously new
sessions were still admitted after expiry). The portal opens, extends and closes windows.
Git no longer carries `REGION_SESSION_WINDOW`. No simulation, checkpoint or wire change.
Executed (WSL Ubuntu, GCC 14.2 Release/NDEBUG, build/m97-postgres):
- Full build of the tree with -Werror (one -Wshadow fix in the new test).
- CTest `session`: 5/5 passed, including the new SessionWindowFeed cases (no record, open,
same-record no-op, extension by a newer activation, own deadline, no reopening, closing
row, expired and over-long refusals, a vanished record).
- `tools/ci/postgres-check.sh --full` passed (637 s, every phase). The admin API tests now
log in as the new admin login: open with reason, history and author, extend, close,
regions list state, 400s for bad minutes and reasons, 403 without the role, 405 on other
POST paths, 503 for an unknown region; the runtime role reads only the current window and
can no longer call the admin views or the writer; the table refuses UPDATE, DELETE and a
window over four hours. The test cluster gained an admin group role and login; the
private verify-backup cluster ignores the admin role; the schema-50 rewind and the
future-version probe move up to 62/63.
- clang-tidy 19 (warnings as errors) on the changed sources; one unchecked-optional fix in
the window test. A pre-existing finding in region_sessions.cpp:291 under the standalone
invocation is outside this change. clang-format 19.1.5 applied; `node --check` on the
portal script.
- Deploy suite passed: the policy check now requires `--session-window-source db` and
refuses a committed `REGION_SESSION_WINDOW` (self-test cases added for both).
Limits: no live region has read a SQL window yet, and no process test drives the database
window through a real session; the elapsed-time guard of the 2026-10-08 clock amendment is
still pending. Applying it needs the DEV `aevolution_admin` role and the admin portal's own
login first.
## 2026-10-27 - Admin commands in trace 5 (schema 63)
Scope: ADR-0182 section 10. Operators queue commands in the admin portal (remove a cell,
grant a reserve, add bubbles, add to or release the spent pool, spawn wildlife); the
cellular region applies each once after a tick's births and records it in trace 5, which
bundle 15 admits beside trace 4. Publication binds each recorded command to its queue row
in the same transaction. No owner format, rules, manifest bundle, genome, wire version or
golden changed; a corpse may carry the new `removed` cause (refused by older readers).
The ADR-0180 seeding loop moved into a shared helper with identical draws.
Executed (WSL Ubuntu, GCC 14.2 Release/NDEBUG, build/m97-postgres):
- `cellular-revamp-owner-contracts`: new case applying all six kinds plus a refused one
(missing target): results, closure through the boundary ledger, the exact spent pool,
bubble counts, the removed corpse, spawned wildlife, restore, determinism, trace-5
round trip and replay equality, trace 4 refusing commands; the existing starting-wildlife
and trace cases still pass after the seeding refactor.
- `tools/ci/postgres-check.sh --full` passed (637 s, every phase). New PostgreSQL cases: on
the starting-wildlife region, commands queued through `admin_enqueue_command_v1` (spawn
identities from the life allocator), a tampered trace-5 batch refused by the binding, the
exact batch published with three bindings at its tick and no pending commands left,
recovery equal to the applied state, and a second publication of the same commands
refused; admin API command endpoints (shape refusals, unknown region, author/reason,
history order, runtime role limited to the pending read, rows immutable).
- An existing test bug surfaced: the starting-wildlife publication test did not advance its
head after its tick commit; it now does before the command batch.
- clang-tidy 19 (warnings as errors) on the changed sources after narrowing the command kind
to a byte (the trace keeps a u16 and refuses values over 255); clang-format 19.1.5;
`node --check` on the portal script.
Limits: no live region has applied a command yet; the portal's command forms were not
driven in a browser.
## 2026-10-27 - Account administration (schema 64)
Scope: ADR-0182 section 11. Bans (append-only, a ban also revokes grants), an admin logout,
time played from session intervals recorded by the unchanged-signature control functions,
the broker's 403 `account_banned`, and each cell's lineage root in the region view for the
portal's living-offspring count. No simulation, trace, checkpoint or wire change.
Executed (WSL Ubuntu, GCC 14.2 Release/NDEBUG, build/m97-postgres): full build; CTest
119/119; `tools/ci/postgres-check.sh --full` passed (637 s, every phase, including the
schema-50 rewind restoring the four wrapped control and grant functions, the permission
audit and checksum drift with the probe at 65). New PostgreSQL cases: sessions recorded from
the broker test's control claims, ban with reason (listed in the account and its history),
`issue_account_grant` refused with the banned error while banned and allowed after lifting,
admin logout, refused shapes (bad flag, unknown action, POST on the account itself).
Limits: no live ban or logout was exercised against a connected client; time played starts
at this schema.
## 2026-10-27 - Resource schedules (schema 65)
Scope: ADR-0182 section 12. Recurring add_bubbles, release_pool and spawn_wildlife commands
queued by the pending-command read when due (one outstanding per schedule); append-only
schedule versions; admin API and portal card. No C++ simulation, trace or wire change.
Executed (WSL Ubuntu, GCC 14.2 Release/NDEBUG): full build; CTest 119/119;
`tools/ci/postgres-check.sh --full` passed (639 s, every phase; the schema-50 rewind restores
the pending-command read, and the probe moves to 66). New PostgreSQL cases: refused shapes
(disallowed kind, zero and over-long intervals, missing amounts, unknown schedule), a due
schedule queuing exactly one command across repeated reads, its run count and author in the
listings, and stopping it by a new version.
Limits: no live schedule has run on a region yet.
+1 -1
View File
@@ -120,7 +120,7 @@ void capacity(std::uint32_t count) {
std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now() - start).count())); std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now() - start).count()));
require(population->state().lives().size() == count, "capacity silently culled a life"); require(population->state().lives().size() == count, "capacity silently culled a life");
} }
if (count == biology::max_cellular_tick_lives) { if (count == biology::max_cellular_frozen_lives) {
const auto before = population->state().snapshot(); const auto before = population->state().snapshot();
LifeRequest request{}; LifeRequest request{};
request.account.front() = 1; request.account.front() = 1;
+24
View File
@@ -5,6 +5,7 @@
#include <cstdint> #include <cstdint>
#include <expected> #include <expected>
#include <optional> #include <optional>
#include <utility>
// M11.5 budding (ADR-0098 decision 1, ADR-0125): a funded proposal, detached from any // M11.5 budding (ADR-0098 decision 1, ADR-0125): a funded proposal, detached from any
// owner. The parent pays its ADR-0032 reproduction investment and a starting provision // owner. The parent pays its ADR-0032 reproduction investment and a starting provision
@@ -50,6 +51,29 @@ fund_offspring(const Genome& parent, const Genome& offspring, GrowthState parent
[[nodiscard]] std::optional<accounting::Inventory> [[nodiscard]] std::optional<accounting::Inventory>
offspring_cost(const Genome& parent, const Genome& offspring, std::uint32_t temperature_millikelvin, offspring_cost(const Genome& parent, const Genome& offspring, std::uint32_t temperature_millikelvin,
std::uint32_t share = 1); std::uint32_t share = 1);
// Rules 13 (ADR-0179; Cellular_reproduction_plan.md section 4): a mutation split. The parent's
// body and reserve divide per channel, the offspring taking `share_per_thousand` (rounded
// down); each cell then develops the largest growth its own genome builds from its part of the
// body, and matter beyond that joins its reserve. Nothing is built, burned or lost: on every
// channel the two bodies and reserves sum to the parent's. Refused, changing nothing, when
// the parent is below `min_growth` or damaged, or either part builds no cell at all.
struct SplitTransition {
GrowthState parent_growth{}, child_growth{};
accounting::Inventory parent_body{}, parent_reserve{}, child_body{}, child_reserve{};
auto operator<=>(const SplitTransition&) const = default;
};
[[nodiscard]] std::expected<SplitTransition, BuddingError>
split_cell(const Genome& parent, const Genome& child, GrowthState growth,
const accounting::Inventory& body, const accounting::Inventory& reserve,
std::uint32_t temperature_millikelvin, std::uint32_t share_per_thousand,
std::uint32_t min_growth, const BodyTuning& tuning = default_body_tuning);
// Rules 13: the largest growth whose body `genome` builds within `matter` on every channel and
// that body; nothing when even the smallest does not fit.
[[nodiscard]] std::expected<std::optional<std::pair<GrowthState, accounting::Inventory>>,
BuddingError>
largest_growth_within(const Genome& genome, const accounting::Inventory& matter,
std::uint32_t temperature_millikelvin,
const BodyTuning& tuning = default_body_tuning);
// What one bud takes from a fully grown, undamaged parent of this genome at this temperature // What one bud takes from a fully grown, undamaged parent of this genome at this temperature
// (ADR-0129 amendment): investment matter per channel, and construction energy plus the // (ADR-0129 amendment): investment matter per channel, and construction energy plus the
// bud's provision; exactly what `fund_bud` charges such a parent. Nullopt when the genome // bud's provision; exactly what `fund_bud` charges such a parent. Nullopt when the genome
+52
View File
@@ -0,0 +1,52 @@
#pragma once
#include "evo/accounting/ledger.hpp"
#include <array>
#include <compare>
#include <cstdint>
#include <optional>
// Matter as energy (rules 13, ADR-0179; Cellular_feeding_energy_plan.md section 3). When an
// energy cost is larger than the reserve's energy, reserve matter stands in for the rest at
// each channel's burn rate. The matter is not converted: it leaves the cell as spent matter,
// which the region owner keeps in its spent pool. No energy is created, so a cost paid with
// matter adds no heat.
namespace evo::biology {
inline constexpr std::size_t cellular_matter_channels = 4; // C, N, P, other.
struct CellularBurn {
// Picojoules 1,000 fg of each matter channel stands in for, after the cell's burn
// efficiency. Zero means the channel cannot be burned.
std::array<std::uint64_t, cellular_matter_channels> pj_per_kfg{};
// Bit c set: the player keeps channel c (C = bit 0). Upkeep may override it.
std::uint8_t excluded{};
auto operator<=>(const CellularBurn&) const = default;
};
// The burn rates of a cell: each base rate times its burn efficiency index over 100.
[[nodiscard]] CellularBurn
cellular_burn(const std::array<std::uint64_t, cellular_matter_channels>& base_pj_per_kfg,
const std::array<std::uint16_t, cellular_matter_channels>& efficiency,
std::uint8_t excluded) noexcept;
// Energy the reserve could pay: its energy plus what its burnable matter stands in for.
// `override_exclusions` also counts excluded channels (upkeep).
[[nodiscard]] std::uint64_t cellular_payable_energy(const accounting::Inventory& reserve,
const CellularBurn& burn,
bool override_exclusions) noexcept;
// Pays `cost` from `reserve`: its energy first, then matter from the largest burnable channel
// (ties C, N, P, O), the next largest when that runs out. Returns the energy paid and the
// matter spent, and leaves `reserve` debited; nothing changes when the whole cost cannot be
// paid. A channel pays whole femtograms, so matter may cover slightly more than the cost.
struct CellularPayment {
std::uint64_t energy{};
accounting::Inventory spent{}; // Matter only.
auto operator<=>(const CellularPayment&) const = default;
};
[[nodiscard]] std::optional<CellularPayment> cellular_pay(accounting::Inventory& reserve,
std::uint64_t cost,
const CellularBurn& burn,
bool override_exclusions) noexcept;
} // namespace evo::biology
+190
View File
@@ -0,0 +1,190 @@
#pragma once
#include "evo/accounting/ledger.hpp"
#include "evo/biology/genome.hpp"
#include <array>
#include <compare>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <span>
#include <string_view>
// The named mutation catalog of rules 13 (ADR-0179; Cellular_mutation_plan.md sections 5-9).
// Each entry edits a genome's plan within bounds; what triggers raise or lower its chance and
// how offers are drawn live in cellular_triggers.hpp and cellular_offers.hpp. IDs are stable.
namespace evo::biology {
// What a mutation edits. Point-based traits move in fixed reference points: one point is a
// hundredth of the founder's value, whatever the trait's unit.
enum class CellularTrait : std::uint8_t {
none,
move_output,
move_efficiency,
move_steering,
move_streamlining,
move_braking,
move_coasting,
collect_energy,
collect_carbon,
collect_nitrogen,
collect_phosphorus,
collect_other,
intake, // Ingestion capability, femtograms per second.
energy_kept, // Energy conversion capability, per thousand.
burn_carbon,
burn_nitrogen,
burn_phosphorus,
burn_other,
light, // Photosynthesis capability, per thousand.
membrane, // Nanometres.
engulf_capacity,
kill_absorption,
size, // Target size, femtograms.
recipe_carbon,
recipe_nitrogen,
recipe_phosphorus,
recipe_other,
upkeep_efficiency,
growth_speed,
density,
bud_share, // Reproduction capability, per thousand.
litter, // Hundredths of an extra offspring; moves in its own units, not points.
};
enum class CellularEffect : std::uint8_t {
adjust, // Primary by the primary step, paired by the paired step, spread.
recipe, // Recipe: primary loses the recipe step, the other three share it.
acquire_light, // Photosynthesis at the founder reference, with the paired edit.
shed_light, // Photosynthesis removed.
acquire_adhesion, // Adhesion set.
};
// A spread lowers each other channel of the primary's group by the spread step.
enum class CellularSpread : std::uint8_t { none, collect_matter, burn };
// Extra eligibility beyond staying within bounds.
enum class CellularAvailability : std::uint8_t {
always,
light_absent_after_carbon, // No photosynthesis, and enough carbon burned.
light_present,
adhesion_absent_after_buds, // No adhesion, and enough on-demand buds.
};
// What a cell does that a trigger counts. Flags are 0 or 1 per tick; amounts are pJ or fg.
enum class CellularSignal : std::uint8_t {
thrust, // Thrust applied this tick.
drifting, // No thrust this tick.
brake_press, // Brake pressed this tick and not the last.
fed, // Anything collected.
intake_limited, // Matter collection held by a limit.
energy_limited, // Energy collection held by its limit.
energy_collected, // Amount of energy collected.
collected_carbon, // Amounts of matter collected, by channel, and in total.
collected_nitrogen,
collected_phosphorus,
collected_other,
collected_matter,
burned_carbon, // Amounts of matter burned for energy, by channel, and in total.
burned_nitrogen,
burned_phosphorus,
burned_other,
burned_matter,
burned_not_carbon,
energy_upkeep, // Energy spent on upkeep, on movement, and in total.
energy_movement,
energy_spent,
larger_contact, // Touching a cell over 1.5 times this cell's mass.
engulf_attempt, // An engulf was asked for.
engulf_success,
engulf_too_large, // Failed: prey too large.
engulf_too_large_or_membrane, // Failed: prey too large or membrane too thick.
reserve_over_body, // More matter in the reserve than in the body.
regrowing, // Growing toward full size.
fully_grown,
blocked_carbon, // Growth or a bud held back by this channel.
blocked_nitrogen,
blocked_phosphorus,
blocked_other,
bud_done, // An on-demand bud was made.
bud_refused, // An on-demand bud was refused for lack of resources.
bud_lost_early, // One of this cell's buds was engulfed within 2 minutes of birth.
bud_with_surplus, // A bud made with the reserve covering twice its cost.
};
inline constexpr std::size_t cellular_signal_count = 37;
enum class CellularTriggerKind : std::uint8_t {
accumulate, // Fires each time the signal has been present for `ticks` ticks in total.
absence, // Fires when the signal has been absent for `ticks` ticks running.
count, // Fires when the signal happened `count` times within `ticks` (0: any time).
event, // Fires each time the signal happens.
share, // Every `ticks` ticks: fires if signal / denominator >= per_thousand.
regular, // Fires when the signal recurred with gaps of at most `gap` for `ticks`.
straight, // Fires after `ticks` thrust ticks within `angle` of one heading.
turns, // Fires after `count` turns of more than `angle` within `ticks`.
};
struct CellularTriggerSpec {
CellularTriggerKind kind{};
CellularSignal signal{};
std::uint32_t ticks{};
std::uint32_t count{};
CellularSignal denominator{}; // share only.
std::uint32_t per_thousand{}; // share only.
std::uint32_t gap{}; // regular only.
std::uint16_t angle{}; // straight and turns: heading units (65,536 per turn).
auto operator<=>(const CellularTriggerSpec&) const = default;
};
struct CellularMutationSpec {
std::uint16_t id{};
std::string_view key, name, pro, con;
CellularEffect effect{};
CellularTrait primary{}, paired{};
std::int8_t primary_sign{}, paired_sign{};
CellularSpread spread{};
CellularAvailability available{};
CellularTriggerSpec increase{}, decrease{};
std::uint32_t base_weight{100};
std::uint32_t primary_step{5}; // Default primary step in its units (points; recipe 20).
};
inline constexpr std::size_t cellular_catalog_size = 49;
[[nodiscard]] std::span<const CellularMutationSpec> cellular_catalog() noexcept;
[[nodiscard]] const CellularMutationSpec* cellular_mutation(std::uint16_t id) noexcept;
// One mutation's tunables (Cellular_mutation_plan.md sections 3-4); defaults from its spec.
struct CellularMutationTuning {
bool enabled{true};
std::uint32_t base_weight{100};
std::int32_t increase_points{100}, decrease_points{100};
std::uint32_t primary_step{5}, paired_step{2}, spread_step{1};
accounting::Inventory cost{};
std::uint32_t cost_scale_percent{};
std::uint32_t increase_ticks{}, decrease_ticks{}; // 0: the spec's threshold.
auto operator<=>(const CellularMutationTuning&) const = default;
};
// Bounds and gates shared by every mutation.
struct CellularCatalogBounds {
std::uint32_t min_points{25}, max_points{1'000};
std::uint32_t recipe_min_share{20}; // Per thousand; the founder's phosphorus is 50.
std::uint32_t max_litter{900}; // 10 offspring per bud.
std::uint64_t carbon_for_light{}; // Femtograms of carbon burned before photosynthesis.
std::uint32_t buds_for_adhesion{5};
auto operator<=>(const CellularCatalogBounds&) const = default;
};
// Lineage progress the gates read.
struct CellularLineageProgress {
std::uint64_t carbon_burned{};
std::uint32_t buds{};
auto operator<=>(const CellularLineageProgress&) const = default;
};
[[nodiscard]] CellularMutationTuning
cellular_default_tuning(const CellularMutationSpec& spec) noexcept;
// The successor plan the mutation makes from `plan` (a schema-7 genome), or nothing when it is
// not available: a gate is closed, the trait is absent, or an edit would leave its bounds. The
// successor has one parent, `plan`, and identity `successor_id` from `origin_event`.
[[nodiscard]] std::optional<GenomeDraft>
apply_cellular_mutation(const Genome& plan, const CellularMutationSpec& spec,
const CellularMutationTuning& tuning, const CellularCatalogBounds& bounds,
const CellularLineageProgress& progress, std::uint64_t successor_id,
std::uint64_t origin_event);
} // namespace evo::biology
@@ -1,5 +1,6 @@
#pragma once #pragma once
#include "evo/biology/cellular_habitat.hpp"
#include "evo/biology/cellular_kinematics.hpp" #include "evo/biology/cellular_kinematics.hpp"
#include <compare> #include <compare>
@@ -80,4 +81,10 @@ class CellularFlowField {
std::vector<CellularFlowSample> nodes_; std::vector<CellularFlowSample> nodes_;
std::size_t columns_{}, rows_{}; std::size_t columns_{}, rows_{};
}; };
// A pool (a fixed deposit) cannot sit in a current. The nearest centre to the pool's within the
// region whose whole disc is in still water (no current at its centre, rim or half-rim), or
// the pool's own centre when it already is or none is found within 30 mm.
[[nodiscard]] CellularPatchAddress cellular_still_centre(const CellularFlowField& field,
CellularPatchAddress centre,
std::uint32_t radius_um) noexcept;
} // namespace evo::biology } // namespace evo::biology
+4
View File
@@ -113,6 +113,10 @@ struct CellularMoteField {
std::uint64_t source{}; std::uint64_t source{};
accounting::Inventory amount{}; // Per bubble, per channel. accounting::Inventory amount{}; // Per bubble, per channel.
std::uint64_t seed{}; std::uint64_t seed{};
// Mixed bubbles, each holding all of `mixed` (every nutrient at once), scattered after the
// single-nutrient ones from the same stream. None leaves the stream unchanged.
std::uint32_t mixed_count{};
accounting::Inventory mixed{};
}; };
// A format-2 habitat of the given pools (centre, radius, source and stock; their ids and kind // A format-2 habitat of the given pools (centre, radius, source and stock; their ids and kind
// are assigned) and the scattered bubbles, sorted by address with ids 1..n. // are assigned) and the scattered bubbles, sorted by address with ids 1..n.
+44
View File
@@ -0,0 +1,44 @@
#pragma once
#include <compare>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <span>
#include <vector>
// Mutation offers (rules 13, ADR-0179; Cellular_mutation_plan.md section 3): a mutation's
// weight from its affinity score, every eligible mutation's chance of appearing in an offer
// (floored and capped, summing to the number of options), and a systematic draw whose
// inclusion frequencies equal those chances. Chances are parts per million (1,000,000 = 100%).
namespace evo::biology {
inline constexpr std::uint32_t cellular_chance_whole = 1'000'000;
struct CellularOfferRules {
std::uint32_t options{3};
std::uint32_t floor_ppm{10}; // 0.001%.
std::uint32_t cap_ppm{700'000}; // 70%.
std::int32_t score_min{-1'000}, score_max{1'000};
std::uint32_t max_multiplier_per_mille{10'000}; // At score_max: 10x.
std::uint32_t min_multiplier_per_mille{0}; // At score_min: 0x.
auto operator<=>(const CellularOfferRules&) const = default;
};
// base_weight times the score's multiplier: 1 at score 0, rising linearly to the maximum at
// score_max and falling to the minimum at score_min.
[[nodiscard]] std::uint64_t cellular_offer_weight(std::uint32_t base_weight, std::int32_t score,
const CellularOfferRules& rules) noexcept;
// Each weight's chance: clamp(k x weight, floor, cap) with k chosen so the chances sum to
// `options` x 100%, in the weights' order. Nothing when no such allocation exists (too few
// mutations for the cap, too many for the floor, or weights too large).
[[nodiscard]] std::optional<std::vector<std::uint32_t>>
cellular_offer_chances(std::span<const std::uint64_t> weights, const CellularOfferRules& rules);
// Systematic draw over chances summing to `options` x 100%: the indices at
// u, u + 100%, u + 200%, ... along the cumulative chances, `u` in [0, 100%). Distinct by
// construction; each index appears with exactly its chance over uniform `u`.
[[nodiscard]] std::vector<std::size_t>
cellular_systematic_draw(std::span<const std::uint32_t> chances, std::uint32_t options,
std::uint32_t u) noexcept;
} // namespace evo::biology
+64 -2
View File
@@ -2,20 +2,66 @@
#include "evo/biology/cellular_step.hpp" #include "evo/biology/cellular_step.hpp"
#include <array>
#include <compare> #include <compare>
#include <cstddef> #include <cstddef>
#include <cstdint> #include <cstdint>
#include <expected> #include <expected>
#include <optional>
#include <span> #include <span>
#include <vector> #include <vector>
namespace evo::biology { namespace evo::biology {
inline constexpr std::size_t max_cellular_tick_lives = 256; // Lives one region tick may hold (ADR-0182 section 17: 4,096 for testing; regions run far
// fewer). Formats frozen at the original 256 (cohort populations, migration traces and the
// pre-v3 cellular traces) keep max_cellular_frozen_lives.
inline constexpr std::size_t max_cellular_tick_lives = 4'096;
inline constexpr std::size_t max_cellular_frozen_lives = 256;
// ADR-0124 (rules 3): a predator needs total mass >= ratio x prey total mass, with the // ADR-0124 (rules 3): a predator needs total mass >= ratio x prey total mass, with the
// ratio in thousandths per micrometre of prey membrane (tunable; 1.5 for 1 um). // ratio in thousandths per micrometre of prey membrane (tunable; 1.5 for 1 um).
inline constexpr std::uint64_t cellular_engulf_ratio_milli_per_membrane_um = 1'500; inline constexpr std::uint64_t cellular_engulf_ratio_milli_per_membrane_um = 1'500;
// Rules 13 (ADR-0179; feeding and energy, predation and defense plans): region-declared
// feeding, energy and predation values. All trial values from the revamp tuning file.
struct CellularRevampStepRules {
// Collection changes by this many per mille per membrane point away from the founder's 100
// (thicker collects slower), bounded to 10%-200%.
std::uint32_t membrane_collection_per_mille_per_point{};
// A predator needs engulf mass x capacity / 100 >= prey engulf mass x ratio / 1000 x prey
// membrane points / 100.
std::uint32_t engulf_ratio_milli{1'500};
// Share of reserve matter that counts toward engulf mass, per cent.
std::uint32_t engulf_reserve_percent{100};
// Share of a kill's remainder left as bubbles at the prey; the rest goes to the spent pool.
std::uint32_t kill_bubble_per_thousand{500};
// Every collection limit, per cent of the body's own (100: unchanged).
std::uint32_t collection_percent{100};
// Matter from one food source is split evenly between the nutrients it holds: all of the
// shared matter limit to a carbon-only bubble, half each to carbon and phosphorus, and so
// on (each share then scaled by the cell's collection trait). Off: per-nutrient limits in
// the body's proportions.
bool split_evenly{};
auto operator<=>(const CellularRevampStepRules&) const = default;
};
// Rules 13: engulf mass is the body plus the declared share of reserve matter.
[[nodiscard]] std::uint64_t cellular_engulf_mass(std::uint64_t body_mass,
const accounting::Inventory& reserve,
const CellularRevampStepRules& rules) noexcept;
// Rules 13: whether a hunter of this engulf mass and capacity may take prey of this engulf mass
// and membrane (nanometres), exactly as the region step decides.
[[nodiscard]] bool cellular_engulfable(std::uint64_t hunter_mass, std::uint16_t engulf_capacity,
std::uint64_t prey_mass, std::uint32_t prey_membrane_nm,
const CellularRevampStepRules& rules) noexcept;
// Rules 13: one life's heritable feeding, energy and predation values, from its genome.
struct CellularRevampLifeInput {
CellularBurn burn{};
std::array<std::uint16_t, 5> collection{100, 100, 100, 100, 100}; // E, C, N, P, O.
std::uint32_t energy_kept_per_thousand{1'000}; // Of each energy bubble; the rest is heat.
std::uint32_t membrane_nm{1'000};
std::uint16_t engulf_capacity{100}, kill_absorption{100};
auto operator<=>(const CellularRevampLifeInput&) const = default;
};
struct CellularRegionRules { struct CellularRegionRules {
// Rules 3: engulfment, and every corpse's inventory deposited as patch detritus. // Rules 3: engulfment, and every corpse's inventory deposited as patch detritus.
// Rules 2 (false) is the original trial: engulf intents are ignored and starvation // Rules 2 (false) is the original trial: engulf intents are ignored and starvation
@@ -25,6 +71,8 @@ struct CellularRegionRules {
// its intake rate, with no intake target; pools yield at most a quarter of that rate. // its intake rate, with no intake target; pools yield at most a quarter of that rate.
// A dead life's detritus becomes one bubble per non-empty channel. // A dead life's detritus becomes one bubble per non-empty channel.
bool contact_feeding{}; bool contact_feeding{};
// Rules 13: present exactly when every life carries its revamp input.
std::optional<CellularRevampStepRules> revamp{};
auto operator<=>(const CellularRegionRules&) const = default; auto operator<=>(const CellularRegionRules&) const = default;
}; };
@@ -42,6 +90,8 @@ struct CellularLifeStepInput {
// Rules 12: liquid motion, required exactly when the habitat is format 3. The movement // Rules 12: liquid motion, required exactly when the habitat is format 3. The movement
// intent becomes the propulsion command. // intent becomes the propulsion command.
std::optional<CellularLiquidInput> liquid{}; std::optional<CellularLiquidInput> liquid{};
// Rules 13 (ADR-0179), required exactly when the region rules declare revamp.
std::optional<CellularRevampLifeInput> revamp{};
auto operator<=>(const CellularLifeStepInput&) const = default; auto operator<=>(const CellularLifeStepInput&) const = default;
}; };
enum class CellularEngulfStatus : std::uint8_t { enum class CellularEngulfStatus : std::uint8_t {
@@ -67,7 +117,16 @@ struct CellularPatchStockUpdate {
auto operator<=>(const CellularPatchStockUpdate&) const = default; auto operator<=>(const CellularPatchStockUpdate&) const = default;
}; };
// Unrecorded: a corpse from a checkpoint format that kept no cause (before format 4). // Unrecorded: a corpse from a checkpoint format that kept no cause (before format 4).
enum class CellularDeathCause : std::uint8_t { unrecorded = 0, starved = 1, engulfed = 2 }; // Rules 13 (ADR-0179): merged, a single cell that became a multicellular organism (its body and
// reserve moved into the organism); emerged, an organism that left the region for the world.
enum class CellularDeathCause : std::uint8_t {
unrecorded = 0,
starved = 1,
engulfed = 2,
merged = 3,
emerged = 4,
removed = 5 // ADR-0182: an operator removed the cell (rules 13).
};
struct CellularCorpseCandidate { struct CellularCorpseCandidate {
std::uint64_t life_id{}; std::uint64_t life_id{};
CellularPosition position; CellularPosition position;
@@ -88,6 +147,9 @@ struct CellularRegionStepCandidate {
// Rules 3 detritus patches created at empty cells, sorted by address. // Rules 3 detritus patches created at empty cells, sorted by address.
std::vector<CellularPatch> new_patches; std::vector<CellularPatch> new_patches;
accounting::Picojoules heat_released{}; accounting::Picojoules heat_released{};
// Rules 13: everything for the region's spent pool this tick: matter every life burned in
// place of energy (also in its own step candidate) and the spent share of kill remainders.
accounting::Inventory spent{};
auto operator<=>(const CellularRegionStepCandidate&) const = default; auto operator<=>(const CellularRegionStepCandidate&) const = default;
}; };
enum class CellularRegionStepError : std::uint8_t { enum class CellularRegionStepError : std::uint8_t {
@@ -0,0 +1,82 @@
#pragma once
#include "evo/biology/cellular_catalog.hpp"
#include "evo/biology/cellular_tuning.hpp"
#include <array>
#include <compare>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <string>
#include <string_view>
// Git-managed trial values for the cellular revamp (rules 13, ADR-0179), in their own file
// beside the rules-12 tuning file so older images never meet keys they do not know. Same
// format: plain `key = value` integer lines, range-checked; core keys required once,
// per-mutation overrides and the zero-default DEV opening count optional.
namespace evo::biology {
inline constexpr std::int64_t cellular_revamp_tuning_version = 1;
inline constexpr std::size_t max_cellular_revamp_tuning_bytes = std::size_t{256} * 1'024;
struct CellularRevampTuning {
std::int64_t version{};
// Optional DEV opening fixture; zero preserves unseeded, player-origin worlds.
std::int64_t playtest_starting_wildlife_cells{};
// Optional feeding keys: every collection limit per cent, and the even split.
std::int64_t feeding_collection_percent{100}, feeding_split_evenly{};
// Body: the share of upkeep no upkeep-efficiency trait reduces.
std::int64_t body_essential_upkeep_per_mille{};
// Body: share of reserve matter carried as load on handling and thrust costs.
std::int64_t body_reserve_load_per_mille{};
// Body: growth per tick at growth speed 100, in hundredths of a per mille.
std::int64_t body_growth_per_tick_centi_mille{};
// Energy: picojoules 1,000 fg of each matter channel stand in for (burn efficiency 100).
std::int64_t energy_burn_carbon_pj_per_kfg{}, energy_burn_nitrogen_pj_per_kfg{},
energy_burn_phosphorus_pj_per_kfg{}, energy_burn_other_pj_per_kfg{};
// Feeding: per mille of collection lost per membrane point above the founder's 100.
std::int64_t feeding_membrane_collection_per_mille_per_point{};
// Predation.
std::int64_t predation_engulf_ratio_milli{}, predation_engulf_reserve_percent{},
predation_kill_bubble_per_mille{};
// The spent pool's drip back into the region.
std::int64_t spent_drip_interval_ticks{}, spent_drip_bubble_pj{}, spent_drip_bubble_fg{};
// Optional energy cycle (ADR-0182 section 14): the share of the region's heat returned to
// the spent pool each tick, and whether a drip at the deposit limit joins an existing bubble.
std::int64_t spent_heat_recycle_per_mille{}, spent_drip_absorb{};
// Mutation offers (Cellular_mutation_plan.md section 3).
std::int64_t mutation_options{}, mutation_floor_ppm{}, mutation_cap_ppm{};
std::int64_t mutation_score_min{}, mutation_score_max{};
std::int64_t mutation_max_multiplier_per_mille{}, mutation_min_multiplier_per_mille{};
std::int64_t mutation_offer_interval_ticks{};
std::int64_t mutation_min_points{}, mutation_max_points{}, mutation_recipe_min_share{};
std::int64_t mutation_max_offspring{}, mutation_carbon_for_light_fg{},
mutation_buds_for_adhesion{};
// Reproduction (Cellular_reproduction_plan.md).
std::int64_t reproduction_split_share_per_mille{}, reproduction_split_min_growth_per_mille{};
std::int64_t reproduction_bud_fee_e_pj{}, reproduction_bud_fee_c_fg{},
reproduction_bud_fee_n_fg{}, reproduction_bud_fee_p_fg{}, reproduction_bud_fee_o_fg{};
std::int64_t reproduction_bud_fee_scale_percent{}, reproduction_organism_cap{};
std::int64_t reproduction_wildlife_cap{}; // Optional; 0 is the organism cap.
// Multicellular organisms.
std::int64_t organism_load_per_mille{}, organism_emerge_members{}, organism_emerge_mass_fg{},
organism_emerge_reserve_pj{};
// Optional, explicitly versioned reproduction-safety trial (ADR-0181).
std::int64_t reproduction_safety_version{}, body_growth_reserve_seconds{},
reproduction_split_launch_um_per_s{};
// Each catalog mutation's tunables, in catalog order. Optional keys
// `mutation.<key>.<field>` override the defaults from its spec.
std::array<CellularMutationTuning, cellular_catalog_size> mutations{};
auto operator<=>(const CellularRevampTuning&) const = default;
};
// A mutation's tunables as the file names them.
inline constexpr std::array<std::string_view, 15> cellular_mutation_tuning_fields{
"enabled", "base_weight", "increase_points", "decrease_points", "primary_step",
"paired_step", "spread_step", "increase_ticks", "decrease_ticks", "cost_e_pj",
"cost_c_fg", "cost_n_fg", "cost_p_fg", "cost_o_fg", "cost_scale_percent"};
[[nodiscard]] std::expected<CellularRevampTuning, CellularTuningError>
parse_cellular_revamp_tuning(std::string_view text);
// Canonical text: every key once, in schema order.
[[nodiscard]] std::string encode_cellular_revamp_tuning(const CellularRevampTuning& tuning);
} // namespace evo::biology
+17 -2
View File
@@ -1,5 +1,6 @@
#pragma once #pragma once
#include "evo/biology/cellular_burn.hpp"
#include "evo/biology/cellular_habitat.hpp" #include "evo/biology/cellular_habitat.hpp"
#include "evo/biology/cellular_kinematics.hpp" #include "evo/biology/cellular_kinematics.hpp"
@@ -21,6 +22,13 @@ struct CellularStepIntent {
bool frozen{}; bool frozen{};
// Rules 12: oppose relative velocity instead of following `movement`. // Rules 12: oppose relative velocity instead of following `movement`.
bool brake{}; bool brake{};
// Rules 13 (ADR-0179): matter channels the player keeps from being burned for anything but
// upkeep, bit 0 carbon to bit 3 other matter. Wildlife keeps nothing.
std::uint8_t exclude{};
// Rules 13: with `bud`, the player continues as the (first) bud; the parent becomes wildlife.
bool become{};
// Rules 13: an organism at the emergence threshold leaves the region for the world.
bool emerge{};
auto operator<=>(const CellularStepIntent&) const = default; auto operator<=>(const CellularStepIntent&) const = default;
}; };
@@ -54,6 +62,11 @@ struct CellularStepCandidate {
// Rules 12 (liquid motion): the motion state after the tick and the path travelled. // Rules 12 (liquid motion): the motion state after the tick and the path travelled.
CellularMotionState motion{}; CellularMotionState motion{};
std::uint64_t path_um{}; std::uint64_t path_um{};
// Rules 13 (ADR-0179): reserve matter burned in place of energy, for the region's spent
// pool. Costs paid this way add no heat.
accounting::Inventory spent{};
// Rules 13: a collection limit held matter (or energy) back while food was left.
bool matter_limited{}, energy_limited{};
auto operator<=>(const CellularStepCandidate&) const = default; auto operator<=>(const CellularStepCandidate&) const = default;
}; };
// Rules 12: liquid-relative motion inputs for one life (Cellular_Region_Movement_Plan.md). // Rules 12: liquid-relative motion inputs for one life (Cellular_Region_Movement_Plan.md).
@@ -72,10 +85,12 @@ propose_cellular_step(std::uint64_t begin_tick, CellularArea area, CellularPosit
const MetabolicBudget& budget, const CellularHabitat& habitat) noexcept; const MetabolicBudget& budget, const CellularHabitat& habitat) noexcept;
// Rules 12: maintenance first, then one kinematic tick funded from what is left; thrust it // Rules 12: maintenance first, then one kinematic tick funded from what is left; thrust it
// cannot fund is not applied and the cell coasts with the flow. No targeted intake: liquid // cannot fund is not applied and the cell coasts with the flow. No targeted intake: liquid
// regions feed by contact in the region step. // regions feed by contact in the region step. Rules 13 pass `burn`: reserve matter stands in
// for missing energy, any channel for maintenance and only unexcluded ones for thrust.
[[nodiscard]] std::expected<CellularStepCandidate, CellularStepError> [[nodiscard]] std::expected<CellularStepCandidate, CellularStepError>
propose_liquid_cellular_step(std::uint64_t begin_tick, CellularArea area, CellularPosition position, propose_liquid_cellular_step(std::uint64_t begin_tick, CellularArea area, CellularPosition position,
std::uint32_t extent_um, CellularIntent movement, std::uint32_t extent_um, CellularIntent movement,
const CellularLiquidInput& liquid, accounting::Inventory reserve, const CellularLiquidInput& liquid, accounting::Inventory reserve,
accounting::Inventory heat, const MetabolicBudget& budget) noexcept; accounting::Inventory heat, const MetabolicBudget& budget,
const CellularBurn* burn = nullptr) noexcept;
} // namespace evo::biology } // namespace evo::biology
+56
View File
@@ -0,0 +1,56 @@
#pragma once
#include "evo/biology/cellular_catalog.hpp"
#include <array>
#include <compare>
#include <cstdint>
// Behaviour triggers (rules 13, ADR-0179; Cellular_mutation_plan.md section 3): what a cell did
// each tick raises or lowers its affinity score for each mutation. Integer state only, advanced
// once per tick by the owner, so replay reproduces every score exactly.
namespace evo::biology {
// One tick of a cell's activity: flags are 0 or 1, amounts are pJ or fg (CellularSignal).
struct CellularActivity {
std::array<std::uint64_t, cellular_signal_count> signal{};
std::uint16_t heading{}; // The cell's heading after the tick (65,536 per turn).
[[nodiscard]] std::uint64_t operator[](CellularSignal s) const noexcept {
return signal[static_cast<std::size_t>(s)];
}
std::uint64_t& operator[](CellularSignal s) noexcept {
return signal[static_cast<std::size_t>(s)];
}
};
// One trigger's progress. Its meaning depends on the trigger kind; all fields start at zero.
struct CellularTriggerState {
std::uint64_t first{}, second{};
std::uint32_t ticks{};
std::uint16_t heading{};
std::uint8_t running{};
auto operator<=>(const CellularTriggerState&) const = default;
};
// Advances one trigger by one tick; true when it fires. `threshold` replaces the spec's tick
// threshold (or window) when non-zero.
[[nodiscard]] bool cellular_trigger_tick(const CellularTriggerSpec& spec, std::uint32_t threshold,
CellularTriggerState& state,
const CellularActivity& activity) noexcept;
// Affinity: every mutation's score, and its increase and decrease triggers' progress.
struct CellularAffinity {
std::array<std::int16_t, cellular_catalog_size> score{};
std::array<CellularTriggerState, cellular_catalog_size> increase{}, decrease{};
auto operator<=>(const CellularAffinity&) const = default;
};
// Bounds of every score.
struct CellularScoreBounds {
std::int32_t min{-1'000}, max{1'000};
auto operator<=>(const CellularScoreBounds&) const = default;
};
// Advances every mutation's triggers by one tick and applies their points to its score
// (`tuning` is indexed like the catalog). Disabled mutations do not move.
void cellular_affinity_tick(CellularAffinity& affinity, const CellularActivity& activity,
std::span<const CellularMutationTuning> tuning,
CellularScoreBounds bounds) noexcept;
} // namespace evo::biology
+12
View File
@@ -7,8 +7,10 @@
#include <cstddef> #include <cstddef>
#include <cstdint> #include <cstdint>
#include <expected> #include <expected>
#include <optional>
#include <string> #include <string>
#include <string_view> #include <string_view>
#include <vector>
// Git-managed trial values (Cellular_Region_Movement_Plan.md, tuning file). The file is // Git-managed trial values (Cellular_Region_Movement_Plan.md, tuning file). The file is
// plain `key = value` lines with `#` comments and integer values; `_` may separate digits. // plain `key = value` lines with `#` comments and integer values; `_` may separate digits.
@@ -73,6 +75,16 @@ struct CellularTuningError {
[[nodiscard]] std::expected<CellularTuning, CellularTuningError> [[nodiscard]] std::expected<CellularTuning, CellularTuningError>
parse_cellular_tuning(std::string_view text); parse_cellular_tuning(std::string_view text);
// The shared line reader for Git tuning files: comments and blank lines dropped, each other
// line split into a valid key and its unparsed value text. Views point into `text`.
struct TuningLine {
std::size_t line{}; // 1-based.
std::string_view key, value;
};
[[nodiscard]] std::expected<std::vector<TuningLine>, CellularTuningError>
read_tuning_lines(std::string_view text, std::size_t max_bytes);
// Optional '-', then digits with single '_' separators between digits; at most 18 digits.
[[nodiscard]] std::optional<std::int64_t> parse_tuning_integer(std::string_view text) noexcept;
// Canonical text: every key once, in schema order, so equal tunings encode identically. // Canonical text: every key once, in schema order, so equal tunings encode identically.
[[nodiscard]] std::string encode_cellular_tuning(const CellularTuning& tuning); [[nodiscard]] std::string encode_cellular_tuning(const CellularTuning& tuning);
[[nodiscard]] std::string_view describe(CellularTuningErrorKind kind) noexcept; [[nodiscard]] std::string_view describe(CellularTuningErrorKind kind) noexcept;
+15 -4
View File
@@ -32,10 +32,18 @@ inline constexpr std::uint64_t development_v2_rate_microseconds = 1'000'000;
[[nodiscard]] constexpr std::uint64_t [[nodiscard]] constexpr std::uint64_t
development_rate_microseconds(std::uint32_t development_version) noexcept { development_rate_microseconds(std::uint32_t development_version) noexcept {
return development_version == 1 ? development_v1_tick_microseconds return development_version == 1 ? development_v1_tick_microseconds
: development_version >= 2 && development_version <= 6 : development_version >= 2 && development_version <= 7
? development_v2_rate_microseconds // Versions 3-6 keep version 2's rates. ? development_v2_rate_microseconds // Versions 3-7 keep version 2's rates.
: 0; : 0;
} }
// Development version 7 (ADR-0179): region-declared body tuning. Upkeep is an essential
// share of the mass-based upkeep that no trait reduces, plus the rest divided by the
// genome's upkeep efficiency. Earlier versions ignore it.
struct BodyTuning {
std::uint32_t essential_upkeep_per_thousand{250}; // Trial (ADR-0179).
auto operator<=>(const BodyTuning&) const = default;
};
inline constexpr BodyTuning default_body_tuning{};
// Chosen constants, reviewable as a unit and selected by the genome's // Chosen constants, reviewable as a unit and selected by the genome's
// development version. Declared model parameters, not balance. // development version. Declared model parameters, not balance.
struct DevelopmentRules { struct DevelopmentRules {
@@ -68,6 +76,7 @@ struct Phenotype {
// built inside the cell. At efficiency p per thousand they add p/4 of the structural mass // built inside the cell. At efficiency p per thousand they add p/4 of the structural mass
// as membrane mass (so they are upkept twice, like membrane) and slow movement by p/2 per // as membrane mass (so they are upkept twice, like membrane) and slow movement by p/2 per
// thousand. Light itself is captured by the region's environment owner, never here. // thousand. Light itself is captured by the region's environment owner, never here.
// Version 7 keeps the organelle mass but drops the speed penalty: mass slows the cell.
inline constexpr std::uint32_t photosynthesis_organelle_quarter = 4; inline constexpr std::uint32_t photosynthesis_organelle_quarter = 4;
inline constexpr std::uint32_t photosynthesis_speed_halving = 2; inline constexpr std::uint32_t photosynthesis_speed_halving = 2;
// A proposal. It reserves nothing, pays for nothing and commits nothing; the // A proposal. It reserves nothing, pays for nothing and commits nothing; the
@@ -85,12 +94,14 @@ rules_for(std::uint32_t development_version);
// Pure: a phenotype is recomputed from retained inputs rather than cached, so a // Pure: a phenotype is recomputed from retained inputs rather than cached, so a
// cached copy can always be checked against a recomputation. // cached copy can always be checked against a recomputation.
[[nodiscard]] std::expected<Phenotype, DevelopmentError> [[nodiscard]] std::expected<Phenotype, DevelopmentError>
derive_phenotype(const Genome& genome, GrowthState growth, EnvironmentState environment); derive_phenotype(const Genome& genome, GrowthState growth, EnvironmentState environment,
const BodyTuning& tuning = default_body_tuning);
// Advances realized growth toward the target by at most the rule step, reduced to // Advances realized growth toward the target by at most the rule step, reduced to
// the largest step the available mass and energy admit. This bounds by total mass // the largest step the available mass and energy admit. This bounds by total mass
// only: it cannot see which elements a step consumes, so it is a proposal and not // only: it cannot see which elements a step consumes, so it is a proposal and not
// an affordability authority. `metabolic_budget` decides that, per channel, and // an affordability authority. `metabolic_budget` decides that, per channel, and
// can only narrow this further. Never repairs damage. // can only narrow this further. Never repairs damage.
[[nodiscard]] std::expected<DevelopmentPlan, DevelopmentError> [[nodiscard]] std::expected<DevelopmentPlan, DevelopmentError>
plan_development(const Genome& genome, GrowthState growth, EnvironmentState environment); plan_development(const Genome& genome, GrowthState growth, EnvironmentState environment,
const BodyTuning& tuning = default_body_tuning);
} // namespace evo::biology } // namespace evo::biology
+4
View File
@@ -40,6 +40,10 @@ inline constexpr FounderVersion primitive_founder_v4{genome_schema_v5, 5};
// Founder 5 serves rules 12 (Cellular_Region_Movement_Plan.md): founder 4 with the founder // Founder 5 serves rules 12 (Cellular_Region_Movement_Plan.md): founder 4 with the founder
// movement arrangement (every index at the 100-point reference). // movement arrangement (every index at the 100-point reference).
inline constexpr FounderVersion primitive_founder_v5{genome_schema_v6, 6}; inline constexpr FounderVersion primitive_founder_v5{genome_schema_v6, 6};
// Founder 6 serves rules 13 (ADR-0179): founder 5 on genome schema 7 and development 7, with
// the membrane in nanometres (1,000 nm, the same 1 um) and the founder's cellular traits.
inline constexpr FounderVersion primitive_founder_v6{genome_schema_v7, 7};
inline constexpr std::uint32_t founder_membrane_nanometres = 1'000;
inline constexpr std::uint32_t primitive_founder_development_version = inline constexpr std::uint32_t primitive_founder_development_version =
primitive_founder_v1.development_version; primitive_founder_v1.development_version;
// The founder genome under a world-scoped identity and its origin event. Fails only on // The founder genome under a world-scoped identity and its origin event. Fails only on
+48 -3
View File
@@ -32,7 +32,8 @@ enum class Unit : std::uint8_t {
femtograms_per_tick, // Schema 1: per 50 ms tick. femtograms_per_tick, // Schema 1: per 50 ms tick.
millikelvin, millikelvin,
micrometres_per_second, // Schema 2 (ADR-0099). micrometres_per_second, // Schema 2 (ADR-0099).
femtograms_per_second // Schema 2 (ADR-0099). femtograms_per_second, // Schema 2 (ADR-0099).
nanometres // Schema 7 membrane (ADR-0179).
}; };
struct CapabilitySpec { struct CapabilitySpec {
Unit unit; Unit unit;
@@ -88,6 +89,21 @@ inline constexpr std::array<CapabilitySpec, capability_count> capability_schema_
CapabilitySpec{Unit::femtograms, 1, 1'000'000'000, true, 0}, CapabilitySpec{Unit::femtograms, 1, 1'000'000'000, true, 0},
CapabilitySpec{Unit::millikelvin, 1, 100'000, false, 0}, CapabilitySpec{Unit::millikelvin, 1, 100'000, false, 0},
CapabilitySpec{Unit::per_thousand, 1, 1000, false, capability_bit(Capability::membrane)}}; CapabilitySpec{Unit::per_thousand, 1, 1000, false, capability_bit(Capability::membrane)}};
// Schema 7 (ADR-0179): schema 5 with the membrane in nanometres, so it can change in 5%
// steps of the founder's 1 um (1,000 nm). Other units are unchanged; energy conversion is
// read as the share of bubble energy kept, reproduction as the bud's share of the body.
inline constexpr std::array<CapabilitySpec, capability_count> capability_schema_v7{
CapabilitySpec{Unit::per_thousand, 1, 1000, true, 0},
CapabilitySpec{Unit::nanometres, 1, 10'000'000, true, 0},
CapabilitySpec{Unit::micrometres_per_second, 0, 2'000'000, false,
capability_bit(Capability::membrane)},
CapabilitySpec{Unit::femtograms_per_second, 0, 20'000'000, false,
capability_bit(Capability::membrane)},
CapabilitySpec{Unit::per_thousand, 1, 1000, false,
capability_bit(Capability::energy_conversion)},
CapabilitySpec{Unit::femtograms, 1, 1'000'000'000, true, 0},
CapabilitySpec{Unit::millikelvin, 1, 100'000, false, 0},
CapabilitySpec{Unit::per_thousand, 1, 1000, false, capability_bit(Capability::membrane)}};
// The current schema's table. // The current schema's table.
inline constexpr const auto& capability_schema = capability_schema_v2; inline constexpr const auto& capability_schema = capability_schema_v2;
// Schema 1 rates are per tick of this quantum. // Schema 1 rates are per tick of this quantum.
@@ -113,6 +129,24 @@ inline constexpr std::uint16_t movement_reference_points = 100;
inline constexpr std::uint16_t max_movement_points = 1'000; inline constexpr std::uint16_t max_movement_points = 1'000;
inline constexpr MovementArrangement founder_movement_arrangement{100, 100, 0, 100, 100, inline constexpr MovementArrangement founder_movement_arrangement{100, 100, 0, 100, 100,
100, 0, 100, 0}; 100, 0, 100, 0};
// Schema 7 (ADR-0179): heritable cellular traits beyond the capability records. Indices are
// reference points where 100 is the founder; the recipe is per thousand of the body's
// structure in C, N, P and other matter (summing to 1000); litter is extra offspring per
// bud in hundredths (150 = one extra plus a 50% chance of a second); adhesion is 0 or 1.
struct CellularTraits {
std::uint16_t density{}, upkeep_efficiency{}, growth_speed{};
std::array<std::uint16_t, 5> collection{}; // E, C, N, P, O.
std::array<std::uint16_t, 4> burn{}; // C, N, P, O.
std::uint16_t engulf_capacity{}, kill_absorption{}, litter{};
std::array<std::uint16_t, 4> recipe{}; // C, N, P, O per thousand.
std::uint16_t adhesion{};
auto operator<=>(const CellularTraits&) const = default;
};
inline constexpr std::uint16_t max_trait_points = 1'000;
inline constexpr std::uint16_t max_litter = 9'900; // At most 100 offspring per bud.
inline constexpr CellularTraits founder_cellular_traits{
100, 100, 100, {100, 100, 100, 100, 100}, {100, 100, 100, 100},
100, 100, 0, {500, 150, 50, 300}, 0};
// Unvalidated input. Only Genome::create turns one into a record. // Unvalidated input. Only Genome::create turns one into a record.
struct GenomeDraft { struct GenomeDraft {
std::uint64_t id{}; std::uint64_t id{};
@@ -126,6 +160,8 @@ struct GenomeDraft {
std::uint32_t schema_version{1}; std::uint32_t schema_version{1};
// Required from schema 6 and refused before it. // Required from schema 6 and refused before it.
std::optional<MovementArrangement> movement_arrangement{}; std::optional<MovementArrangement> movement_arrangement{};
// Required from schema 7 and refused before it.
std::optional<CellularTraits> cellular_traits{};
}; };
enum class GenomeError : std::uint8_t { enum class GenomeError : std::uint8_t {
unsupported_version, unsupported_version,
@@ -153,15 +189,19 @@ inline constexpr std::uint32_t genome_schema_v5 = 5;
// Schema 6 (rules 12, Cellular_Region_Movement_Plan.md): schema 5's capabilities and steps // Schema 6 (rules 12, Cellular_Region_Movement_Plan.md): schema 5's capabilities and steps
// plus the movement arrangement. // plus the movement arrangement.
inline constexpr std::uint32_t genome_schema_v6 = 6; inline constexpr std::uint32_t genome_schema_v6 = 6;
// Schema 7 (rules 13, ADR-0179): schema 6 with the membrane in nanometres and the cellular
// traits. Its mutations are the named catalog, not the generic operators.
inline constexpr std::uint32_t genome_schema_v7 = 7;
// The newest schema. Older records stay valid and are never rewritten (ADR-0099). // The newest schema. Older records stay valid and are never rewritten (ADR-0099).
inline constexpr std::uint32_t genome_schema_version = genome_schema_v6; inline constexpr std::uint32_t genome_schema_version = genome_schema_v7;
// The capability table of a supported schema (1 to 6); nullptr otherwise. // The capability table of a supported schema (1 to 7); nullptr otherwise.
[[nodiscard]] constexpr const std::array<CapabilitySpec, capability_count>* [[nodiscard]] constexpr const std::array<CapabilitySpec, capability_count>*
capability_schema_for(std::uint32_t schema) noexcept { capability_schema_for(std::uint32_t schema) noexcept {
return schema == genome_schema_v1 ? &capability_schema_v1 return schema == genome_schema_v1 ? &capability_schema_v1
: schema == genome_schema_v2 || schema == genome_schema_v3 || schema == genome_schema_v4 : schema == genome_schema_v2 || schema == genome_schema_v3 || schema == genome_schema_v4
? &capability_schema_v2 ? &capability_schema_v2
: schema == genome_schema_v5 || schema == genome_schema_v6 ? &capability_schema_v5 : schema == genome_schema_v5 || schema == genome_schema_v6 ? &capability_schema_v5
: schema == genome_schema_v7 ? &capability_schema_v7
: nullptr; : nullptr;
} }
inline constexpr std::size_t max_parents = 2; inline constexpr std::size_t max_parents = 2;
@@ -205,6 +245,10 @@ class Genome {
[[nodiscard]] const std::optional<MovementArrangement>& movement_arrangement() const noexcept { [[nodiscard]] const std::optional<MovementArrangement>& movement_arrangement() const noexcept {
return movement_arrangement_; return movement_arrangement_;
} }
// Present exactly from schema 7.
[[nodiscard]] const std::optional<CellularTraits>& cellular_traits() const noexcept {
return cellular_traits_;
}
[[nodiscard]] bool carries(Capability kind) const noexcept; [[nodiscard]] bool carries(Capability kind) const noexcept;
[[nodiscard]] std::expected<std::uint32_t, GenomeError> [[nodiscard]] std::expected<std::uint32_t, GenomeError>
parameter(Capability kind) const noexcept; parameter(Capability kind) const noexcept;
@@ -230,6 +274,7 @@ class Genome {
std::vector<std::uint64_t> parents_; std::vector<std::uint64_t> parents_;
std::vector<CapabilityRecord> capabilities_; std::vector<CapabilityRecord> capabilities_;
std::optional<MovementArrangement> movement_arrangement_; std::optional<MovementArrangement> movement_arrangement_;
std::optional<CellularTraits> cellular_traits_;
std::uint64_t digest_{}; std::uint64_t digest_{};
}; };
} // namespace evo::biology } // namespace evo::biology
+5 -1
View File
@@ -8,6 +8,9 @@
namespace evo::biology { namespace evo::biology {
// Development version 4 (rules 7, ADR-0137): a bud is always this share of the parent's body. // Development version 4 (rules 7, ADR-0137): a bud is always this share of the parent's body.
inline constexpr std::uint32_t bud_body_per_thousand_v4 = 500; inline constexpr std::uint32_t bud_body_per_thousand_v4 = 500;
// Development version 7 (ADR-0179): the reproduction value is the bud's share of the body again,
// and the construction discount stays at the founder's level (500 per thousand: a quarter off).
inline constexpr std::uint32_t primitive_bud_skill_v7 = 500;
// Shares in thousandths over the ledger's C/N/P/other channels, summing to 1000. // Shares in thousandths over the ledger's C/N/P/other channels, summing to 1000.
// The last channel absorbs the rounding remainder, so a split conserves mass. // The last channel absorbs the rounding remainder, so a split conserves mass.
using Composition = std::array<std::uint16_t, 4>; using Composition = std::array<std::uint16_t, 4>;
@@ -59,7 +62,8 @@ metabolic_rules_for(std::uint32_t development_version);
// its versioned cadence. The default preserves earlier budget results exactly. // its versioned cadence. The default preserves earlier budget results exactly.
[[nodiscard]] std::expected<MetabolicBudget, DevelopmentError> [[nodiscard]] std::expected<MetabolicBudget, DevelopmentError>
metabolic_budget(const Genome& genome, GrowthState growth, EnvironmentState environment, metabolic_budget(const Genome& genome, GrowthState growth, EnvironmentState environment,
std::uint32_t max_growth_per_thousand = 1000); std::uint32_t max_growth_per_thousand = 1000,
const BodyTuning& tuning = default_body_tuning);
// An analysis, not a rule (ADR-0098 decision 7): whole seconds until feeding funds the // An analysis, not a rule (ADR-0098 decision 7): whole seconds until feeding funds the
// budget's reproduction investment, channel by channel and in energy, when the organism // budget's reproduction investment, channel by channel and in energy, when the organism
// takes in its full intake limit for `feeding_per_thousand` of the time and pays its // takes in its full intake limit for `feeding_per_thousand` of the time and pays its
+6 -3
View File
@@ -59,20 +59,23 @@ class RegionSessionClient {
// retries and reconnects). False unless established and sent. // retries and reconnects). False unless established and sent.
[[nodiscard]] bool send_action(std::uint64_t action_id, network::ActionKind kind, [[nodiscard]] bool send_action(std::uint64_t action_id, network::ActionKind kind,
std::uint64_t tick); std::uint64_t tick);
// Protocol v7-v10. Reuse the exact same fields and action id after reconnect. `engulf` // Protocol v7-v14. Reuse the exact same fields and action id after reconnect. `engulf`
// and `bud` (ADR-0124/0125) are exclusive and need a v10 session and no intake target. // and `bud` (ADR-0124/0125) are exclusive and need a v10 session and no intake target.
// `brake` needs v13 or v14; `become` (with `bud`), `emerge` (alone) and `exclude` (matter
// channels kept from burning) need v14. Older sessions never send them.
[[nodiscard]] bool [[nodiscard]] bool
send_cellular_action(std::uint64_t action_id, std::uint64_t tick, std::int16_t move_x, send_cellular_action(std::uint64_t action_id, std::uint64_t tick, std::int16_t move_x,
std::int16_t move_y, std::int16_t move_y,
std::optional<std::pair<std::uint32_t, std::uint32_t>> intake_target = {}, std::optional<std::pair<std::uint32_t, std::uint32_t>> intake_target = {},
bool engulf = false, bool bud = false, bool brake = false); bool engulf = false, bool bud = false, bool brake = false,
bool become = false, bool emerge = false, std::uint8_t exclude = 0);
// Protocol v10 (ADR-0121): choose one candidate of the life's outstanding offer. The // Protocol v10 (ADR-0121): choose one candidate of the life's outstanding offer. The
// receipt names the tick it publishes with; the outcome follows that commit. `tick` is // receipt names the tick it publishes with; the outcome follows that commit. `tick` is
// the client's latest simulated tick (after the offer); the server schedules the next. // the client's latest simulated tick (after the offer); the server schedules the next.
[[nodiscard]] bool send_cellular_mutation(std::uint64_t action_id, std::uint64_t tick, [[nodiscard]] bool send_cellular_mutation(std::uint64_t action_id, std::uint64_t tick,
std::uint64_t life_identity, std::uint64_t life_identity,
std::uint64_t event_index, std::uint64_t offer_tick, std::uint64_t event_index, std::uint64_t offer_tick,
std::uint16_t operator_id); std::uint16_t operator_id, bool become = false);
[[nodiscard]] bool query_action(std::uint64_t action_id); [[nodiscard]] bool query_action(std::uint64_t action_id);
// Primitive profile v5 only. The account and generation are always supplied by the // Primitive profile v5 only. The account and generation are always supplied by the
// authenticated session; callers choose only a stable request id. // authenticated session; callers choose only a stable request id.
+46 -6
View File
@@ -45,19 +45,30 @@ inline constexpr std::uint16_t session_protocol_v12 = 12;
// region's current configuration in its perception, each deposit's world velocity, and a brake // region's current configuration in its perception, each deposit's world velocity, and a brake
// flag on cellular actions. // flag on cellular actions.
inline constexpr std::uint16_t session_protocol_v13 = 13; inline constexpr std::uint16_t session_protocol_v13 = 13;
// v10 to v13 share every cellular message but the perception's contents and v13's brake. // v14 (rules 13, ADR-0179) is v13 plus the cellular revamp: the body block in the perception,
// become, emerge and channel exclusions on actions, become on mutation choices, catalog offers
// and the emerged ending.
inline constexpr std::uint16_t session_protocol_v14 = 14;
// v10 to v14 share every cellular message but the perception's contents, v13's brake and v14's
// revamp fields.
[[nodiscard]] constexpr bool cellular_v10_family(std::uint16_t version) noexcept { [[nodiscard]] constexpr bool cellular_v10_family(std::uint16_t version) noexcept {
return version == session_protocol_v10 || version == session_protocol_v11 || return version == session_protocol_v10 || version == session_protocol_v11 ||
version == session_protocol_v12 || version == session_protocol_v13; version == session_protocol_v12 || version == session_protocol_v13 ||
version == session_protocol_v14;
} }
// Versions whose perception lists pools and bubbles (ADR-0136) instead of square patches. // Versions whose perception lists pools and bubbles (ADR-0136) instead of square patches.
[[nodiscard]] constexpr bool cellular_deposit_version(std::uint16_t version) noexcept { [[nodiscard]] constexpr bool cellular_deposit_version(std::uint16_t version) noexcept {
return version == session_protocol_v11 || version == session_protocol_v12 || return version == session_protocol_v11 || version == session_protocol_v12 ||
version == session_protocol_v13; version == session_protocol_v13 || version == session_protocol_v14;
} }
// Versions that carry captured light and producers (ADR-0176). // Versions that carry captured light and producers (ADR-0176).
[[nodiscard]] constexpr bool cellular_light_version(std::uint16_t version) noexcept { [[nodiscard]] constexpr bool cellular_light_version(std::uint16_t version) noexcept {
return version == session_protocol_v12 || version == session_protocol_v13; return version == session_protocol_v12 || version == session_protocol_v13 ||
version == session_protocol_v14;
}
// Versions that carry liquid motion (rules 12).
[[nodiscard]] constexpr bool cellular_liquid_version(std::uint16_t version) noexcept {
return version == session_protocol_v13 || version == session_protocol_v14;
} }
// The highest capability a version's mutation offers may name. // The highest capability a version's mutation offers may name.
[[nodiscard]] constexpr std::uint8_t [[nodiscard]] constexpr std::uint8_t
@@ -208,6 +219,10 @@ struct CellularActionInput {
bool engulf{}; bool engulf{};
bool bud{}; // Kind 3 (ADR-0125): fund one wildlife bud, zero coordinates, v10 only. bool bud{}; // Kind 3 (ADR-0125): fund one wildlife bud, zero coordinates, v10 only.
bool brake{}; // Byte 13 bit 0 (schema 58, rules 12): oppose relative velocity. bool brake{}; // Byte 13 bit 0 (schema 58, rules 12): oppose relative velocity.
// Schema 60 (rules 13): byte 13 bit 1 become the bud, bit 2 emerge; byte 14 the channels
// excluded from burning (bits 0-3: C, N, P, other).
bool become{}, emerge{};
std::uint8_t exclude{};
friend bool operator==(const CellularActionInput&, const CellularActionInput&) = default; friend bool operator==(const CellularActionInput&, const CellularActionInput&) = default;
}; };
inline constexpr std::size_t cellular_action_input_bytes = 24; inline constexpr std::size_t cellular_action_input_bytes = 24;
@@ -224,6 +239,10 @@ struct CellularAction {
bool bud{}; bool bud{};
// v13 (rules 12): brake against relative velocity instead of following the movement. // v13 (rules 12): brake against relative velocity instead of following the movement.
bool brake{}; bool brake{};
// v14 (rules 13): with `bud`, continue as the bud; leave the region as an organism at the
// threshold (no target); matter channels excluded from burning (bits 0-3).
bool become{}, emerge{};
std::uint8_t exclude{};
friend bool operator==(const CellularAction&, const CellularAction&) = default; friend bool operator==(const CellularAction&, const CellularAction&) = default;
}; };
// v10 reliable choice. The server binds these values to the authenticated account and // v10 reliable choice. The server binds these values to the authenticated account and
@@ -232,12 +251,16 @@ struct CellularMutationAction {
std::uint64_t session{}, epoch{}, action_id{}, tick{}; std::uint64_t session{}, epoch{}, action_id{}, tick{};
std::uint64_t life_identity{}, event_index{}, offer_tick{}; std::uint64_t life_identity{}, event_index{}, offer_tick{};
std::uint16_t operator_id{}; std::uint16_t operator_id{};
bool become{}; // v14: continue as the offspring the choice splits off.
friend bool operator==(const CellularMutationAction&, const CellularMutationAction&) = default; friend bool operator==(const CellularMutationAction&, const CellularMutationAction&) = default;
}; };
// v10 server-to-owner offer (ADR-0121, 11.4d): the life's outstanding earned offer, its // v10 server-to-owner offer (ADR-0121, 11.4d): the life's outstanding earned offer, its
// candidates in stable operator order (never ranked). Each candidate states the successor's // candidates in stable operator order (never ranked). Each candidate states the successor's
// actual tradeoffs: its capability value and its maintenance and total mass. No candidates // actual tradeoffs: its capability value and its maintenance and total mass. No candidates
// (and zero event/offer) clears a consumed or absent offer. // (and zero event/offer) clears a consumed or absent offer.
// v14 (rules 13) keeps the layout for a named catalog mutation: `operator_id` is its catalog
// id, `parameter` its chance of appearing in parts per million, capability, effect,
// maintenance and mass zero, and the cost its tuned cost. The client names it from the catalog.
struct CellularOfferedCandidate { struct CellularOfferedCandidate {
std::uint16_t operator_id{}; std::uint16_t operator_id{};
std::uint8_t capability{}, effect{}; // biology::Capability, biology::MutationEffect. std::uint8_t capability{}, effect{}; // biology::Capability, biology::MutationEffect.
@@ -257,8 +280,9 @@ struct CellularMutationOffer {
friend bool operator==(const CellularMutationOffer&, const CellularMutationOffer&) = default; friend bool operator==(const CellularMutationOffer&, const CellularMutationOffer&) = default;
}; };
// v10 (ADR-0129): the owner's life ended in `tick`. Cause 1 starved, 2 engulfed, 0 not // v10 (ADR-0129): the owner's life ended in `tick`. Cause 1 starved, 2 engulfed, 0 not
// recorded (rules below 3). Death is final; a new life is a new request. // recorded (rules below 3); v14 adds 3, the organism emerged. Death is final; a new life is a
enum class CellularDeathReason : std::uint8_t { unrecorded, starved, engulfed }; // new request.
enum class CellularDeathReason : std::uint8_t { unrecorded, starved, engulfed, emerged };
struct CellularLifeEnded { struct CellularLifeEnded {
std::uint64_t tick{}, life_identity{}; std::uint64_t tick{}, life_identity{};
CellularDeathReason cause{}; CellularDeathReason cause{};
@@ -357,6 +381,22 @@ struct CellularLifeDiagnostics {
// turn), the authoritative motion state the client predictor reconciles against. // turn), the authoritative motion state the client predictor reconciles against.
std::int32_t velocity_x_q10{}, velocity_y_q10{}; std::int32_t velocity_x_q10{}, velocity_y_q10{};
std::uint16_t heading{}; std::uint16_t heading{};
// v14 only (rules 13): cells in the organism and the emergence threshold, the exclusions
// in effect, whether Emerge is open, what the reserve can pay as energy with matter standing
// in, total mass, and the heritable body traits (biology::CellularTraits field order).
std::uint16_t members{}, emerge_members{};
std::uint8_t exclude{};
bool can_emerge{};
// How grown the body is (per thousand), and whether a mutation choice can split it now.
std::uint16_t growth_per_thousand{};
bool split_ready{};
// What held this tick's growth step back (0 nothing; 1 energy; 2-5 C, N, P, other; 6 no
// room), and the tick's flows by channel (energy, C, N, P, other): collected from food,
// built into the body, and burned in place of energy (matter only).
std::uint8_t growth_limit{};
std::array<std::uint64_t, 5> collected{}, into_growth{}, burned{};
std::uint64_t payable_energy_pj{}, total_mass_fg{};
std::array<std::uint16_t, 20> traits{};
friend bool operator==(const CellularLifeDiagnostics&, friend bool operator==(const CellularLifeDiagnostics&,
const CellularLifeDiagnostics&) = default; const CellularLifeDiagnostics&) = default;
}; };
@@ -12,6 +12,7 @@
namespace evo::persistence { namespace evo::persistence {
enum class AccountIdentityError : std::uint8_t { enum class AccountIdentityError : std::uint8_t {
invalid, // Arguments refused. invalid, // Arguments refused.
banned, // ADR-0182: the account is banned (schema 64); nothing changed.
store, // Other failure; nothing changed. store, // Other failure; nothing changed.
unknown // May have executed: reconnect before relying on the serial. unknown // May have executed: reconnect before relying on the serial.
}; };
@@ -292,6 +292,14 @@ migrate_cellular_liquid_profile(Postgres&, const FilesystemObjectStore&, const L
const CommittedCheckpoint&, Uuid commit, const Sha256Digest& build, const CommittedCheckpoint&, Uuid commit, const Sha256Digest& build,
const server::CellularLiquidRules& rules, const server::CellularLiquidRules& rules,
std::chrono::milliseconds timeout, const PublishHooks& hooks = {}); std::chrono::milliseconds timeout, const PublishHooks& hooks = {});
// Rules 13: explicit raw-only bundle 14 -> 15, declaring the region's revamp rules.
[[nodiscard]] std::expected<CommittedCheckpoint, CellularProfileMigrationFailure>
migrate_cellular_revamp_profile(Postgres&, const FilesystemObjectStore&, const LeaseGrant&,
const CommittedCheckpoint&, Uuid commit, const Sha256Digest& build,
const server::CellularRevampRules& rules,
std::chrono::milliseconds timeout, const PublishHooks& hooks = {},
std::uint32_t playtest_wildlife_count = 0,
std::uint64_t playtest_first_identity = 0);
// Verify the recorded no-tick operation under current authority, replaying its // Verify the recorded no-tick operation under current authority, replaying its
// entire source/target payload. Version upgrades and profile transitions retain // entire source/target payload. Version upgrades and profile transitions retain
// separate evidence; neither is inferred solely from the target tuple. // separate evidence; neither is inferred solely from the target tuple.
+26 -1
View File
@@ -89,9 +89,12 @@ inline constexpr CellularVersionBundle cellular_v12_versions{10, 8, 2, 1, 1, 4,
inline constexpr CellularVersionBundle cellular_v13_versions{11, 9, 2, 1, 1, 5, 4, 2, 1}; inline constexpr CellularVersionBundle cellular_v13_versions{11, 9, 2, 1, 1, 5, 4, 2, 1};
// Rules 12 on owner format 10 (liquid region), development 6, founder 5 (ADR-0177). // Rules 12 on owner format 10 (liquid region), development 6, founder 5 (ADR-0177).
inline constexpr CellularVersionBundle cellular_v14_versions{12, 10, 2, 1, 1, 6, 5, 2, 1}; inline constexpr CellularVersionBundle cellular_v14_versions{12, 10, 2, 1, 1, 6, 5, 2, 1};
// Rules 13 on owner format 11 (the cellular revamp), development 7, founder 6 (ADR-0179).
inline constexpr CellularVersionBundle cellular_v15_versions{13, 11, 2, 1, 1, 7, 6, 2, 1};
// Raw-only retained-plan bundles, which use trace 4 and their own SQL admission. // Raw-only retained-plan bundles, which use trace 4 and their own SQL admission.
[[nodiscard]] constexpr bool cellular_plan_bundle(const CellularVersionBundle& b) noexcept { [[nodiscard]] constexpr bool cellular_plan_bundle(const CellularVersionBundle& b) noexcept {
return b == cellular_v12_versions || b == cellular_v13_versions || b == cellular_v14_versions; return b == cellular_v12_versions || b == cellular_v13_versions || b == cellular_v14_versions ||
b == cellular_v15_versions;
} }
// Zero means this bundle has no population representation. // Zero means this bundle has no population representation.
[[nodiscard]] constexpr std::uint32_t [[nodiscard]] constexpr std::uint32_t
@@ -115,6 +118,14 @@ cellular_checkpoint_trace_format(const CellularVersionBundle& b) noexcept {
: server::cellular_batch_v2_format; : server::cellular_batch_v2_format;
} }
// ADR-0182: a bundle-15 commit may carry admin commands in trace 5; every other format is
// exactly the bundle's.
[[nodiscard]] constexpr bool cellular_checkpoint_trace_admits(const CellularVersionBundle& b,
std::uint32_t format) noexcept {
return format == cellular_checkpoint_trace_format(b) ||
(format == server::cellular_batch_admin_format && b == cellular_v15_versions);
}
// Batch evidence bound by manifest v2 (ADR-0063); all zero at genesis. // Batch evidence bound by manifest v2 (ADR-0063); all zero at genesis.
struct BatchDigests { struct BatchDigests {
std::uint64_t trace_bytes{}; std::uint64_t trace_bytes{};
@@ -306,6 +317,20 @@ cellular_liquid_upgrade_manifest(const CheckpointManifest& predecessor,
cellular_liquid_upgrade_payload(std::span<const std::uint8_t> payload, cellular_liquid_upgrade_payload(std::span<const std::uint8_t> payload,
const CheckpointManifest& predecessor, const CheckpointManifest& predecessor,
const server::CellularLiquidRules& rules); const server::CellularLiquidRules& rules);
// Rules 13 (ADR-0179): explicit raw-only bundle 14 -> 15 upgrade declaring the revamp rules
// from the Git tuning file. ADR-0180 also admits an explicit empty-opening fixture;
// recovery reads its count/first identity from the target and re-derives every byte.
[[nodiscard]] std::expected<CheckpointManifest, CheckpointError>
cellular_revamp_upgrade_manifest(const CheckpointManifest& predecessor,
const Sha256Digest& predecessor_digest, Uuid commit,
const LeaseGrant& lease, const Sha256Digest& build,
std::uint64_t payload_bytes, const Sha256Digest& payload_sha256);
[[nodiscard]] std::expected<std::vector<std::uint8_t>, CheckpointError>
cellular_revamp_upgrade_payload(std::span<const std::uint8_t> payload,
const CheckpointManifest& predecessor,
const server::CellularRevampRules& rules,
std::uint32_t playtest_wildlife_count = 0,
std::uint64_t playtest_first_identity = 0);
// ADR-0174: explicit one-way, no-tick profile 5 -> 6 transition. The payload wraps the // ADR-0174: explicit one-way, no-tick profile 5 -> 6 transition. The payload wraps the
// identical population with its declared environment; bundle and policy are unchanged. // identical population with its declared environment; bundle and policy are unchanged.
[[nodiscard]] std::expected<CheckpointManifest, CheckpointError> [[nodiscard]] std::expected<CheckpointManifest, CheckpointError>
+4 -2
View File
@@ -30,8 +30,10 @@ class JsonValue {
[[nodiscard]] const JsonValue* member(std::string_view name) const; [[nodiscard]] const JsonValue* member(std::string_view name) const;
[[nodiscard]] const std::vector<JsonValue>* array() const; [[nodiscard]] const std::vector<JsonValue>* array() const;
// Whole-document parse; nullopt for anything malformed or out of bounds. // Whole-document parse; nullopt for anything malformed or out of bounds. `limit` bounds
[[nodiscard]] static std::optional<JsonValue> parse(std::string_view text); // the text: access tokens and keys keep the default; a service's answer may allow more.
[[nodiscard]] static std::optional<JsonValue> parse(std::string_view text,
std::size_t limit = max_json_bytes);
private: private:
friend class JsonParser; friend class JsonParser;
+173
View File
@@ -0,0 +1,173 @@
#pragma once
#include "evo/persistence/postgres.hpp"
#include "evo/server/admin/https_client.hpp"
#include "evo/server/broker/access_token.hpp"
#include "evo/server/ops_http.hpp"
#include <chrono>
#include <cstdint>
#include <functional>
#include <map>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
// ADR-0182 read-only admin API and portal host. One world; every /api route needs a Keycloak
// access token carrying the admin realm role. The portal's static files and its OIDC settings
// are public; they carry no secret.
//
// GET /healthz ok
// GET / and the portal's files the portal (index.html, app.js, style.css)
// GET /config.json issuer, client id and world for the portal's sign-in
// GET /api/me the signed-in admin's subject and email
// GET /api/accounts every account with session, lives, deaths and resets
// GET /api/accounts/<uuid> one account, its life requests and ban history
// POST /api/accounts/<uuid>/ban?banned=1|0[&reason=R] bans (and logs out) or lifts a ban
// POST /api/accounts/<uuid>/logout ends the account's sessions now
// POST /api/accounts/<uuid>/end-life?request=N[&reason=R]
// ends a stranded published life (its reservation was
// never ended), refused while a cell in its region still
// holds the account (ADR-0182 section 18)
// GET /api/regions the world's regions, leases and heads
// GET /api/regions/<n>/view the region's live view (render_cellular_admin_view)
// GET /api/regions/<n>/session-window the current session window and its last changes
// POST /api/regions/<n>/session-window?minutes=M[&reason=R]
// opens or extends the window for M (1..240) minutes
// from now, or closes it (M = 0), as the signed-in admin
// (ADR-0087 amendment). No request body.
// GET /api/regions/<n>/commands the region's last admin commands and where they applied
// POST /api/regions/<n>/commands?kind=K[&count=N][&target=ID][&energy=PJ][&carbon=FG]
// [&nitrogen=FG][&phosphorus=FG][&other=FG][&reason=R]
// queues a command (remove_cell, grant_reserve,
// add_bubbles, add_pool, release_pool, spawn_wildlife)
// GET /api/regions/<n>/schedules the region's resource schedules (schema 65)
// POST /api/regions/<n>/schedules?kind=K&count=N&interval=S[&id=ID][&enabled=0|1]
// [&energy=PJ][&carbon=FG]...[&reason=R]
// creates (no id) or replaces a schedule repeating
// add_bubbles, release_pool or spawn_wildlife
// GET /api/tuning the world's rules-13 tuning revisions, the newest text,
// the baseline file regions opened with (schema 66) and
// the region tuning file they restart with (read only)
// GET /api/tuning/<revision> one revision's text
// POST /api/tuning[?check=1][&reason=R] the request body is a tuning text (the Git
// revamp file format): checked, then stored as a new
// revision that every region of the world adopts at its
// next tick (check=1: checked only, nothing stored)
// POST /api/tuning?base=baseline|REV[&check=1][&reason=R] the body holds only changed
// `key = value` lines, applied to the baseline file or to
// revision REV (which must be the newest: 409 stale_base),
// keeping its comments; then as above
// GET /api/deploy[?argo=1] ADR-0182 section 15: whether opening a region is
// configured, the region Git main serves, the next region
// and its seeded wildlife range, and the Argo Application's
// sync (argo=1: the Argo status only)
// POST /api/deploy/region?region=N[&reason=R] opens region N (the next one) in place of
// the served region: one Gitea commit to the region,
// broker and portal files, then a full Argo sync
namespace evo::server::admin {
struct AdminAsset {
std::string path; // "/index.html", ...; "/" serves "/index.html".
std::string content_type, body;
};
struct AdminConfig {
std::uint64_t world{};
// The world's regions: their live view can be fetched and they adopt tuning revisions.
std::vector<std::uint64_t> view_regions;
// The revamp tuning file the world's regions opened with (empty: unknown).
std::string baseline_tuning;
// The region tuning file (shape, movement, currents) they read at startup (empty: unknown).
std::string region_tuning;
std::string portal_config_json; // Served at /config.json.
std::string content_security_policy; // Sent with every portal file.
std::chrono::milliseconds db_timeout{3000};
std::chrono::milliseconds view_cache{750}; // A fetched view answers repeats this long.
};
// ADR-0182 section 15: where the admin API commits a region switch and what it syncs. The
// tokens come from mounted Secret files and are only ever sent in request headers.
struct AdminDeployConfig {
std::string gitea_base; // https://git.example[:port][/prefix]
std::string gitea_repository; // owner/name
std::string gitea_token;
std::string branch{"main"};
std::string argo_server; // host:port, https assumed
std::string argo_application;
std::string argo_token;
bool argo_verify{true};
};
using AdminConnect = std::function<std::unique_ptr<persistence::Postgres>()>;
// The region's /admin/view body, or nullopt when it cannot be reached or is not ready.
using AdminRegionView = std::function<std::optional<std::string>(std::uint64_t region)>;
class AdminApi {
public:
AdminApi(AdminConfig config, broker::TokenVerifier verifier, AdminConnect connect,
AdminRegionView view, std::vector<AdminAsset> assets);
// `now_seconds` is wall time (token expiry); `now` paces the view cache.
[[nodiscard]] OpsResponse handle(const ApiRequest& request, std::uint64_t now_seconds,
std::chrono::steady_clock::time_point now);
// Turns on /api/deploy with the given services and transport (tests pass a fake).
void enable_deploy(AdminDeployConfig config, HttpsTransport transport);
private:
[[nodiscard]] OpsResponse api(std::string_view method, std::string_view path,
std::string_view query, std::string_view body,
const broker::AccessTokenClaims& admin,
std::chrono::steady_clock::time_point now);
[[nodiscard]] OpsResponse accounts(std::optional<std::string_view> account);
[[nodiscard]] OpsResponse account_action(std::string_view account, std::string_view action,
std::string_view query,
const broker::AccessTokenClaims& admin);
[[nodiscard]] OpsResponse end_life(std::string_view account, std::string_view query,
const broker::AccessTokenClaims& admin);
[[nodiscard]] OpsResponse regions();
[[nodiscard]] OpsResponse view(std::uint64_t region, std::chrono::steady_clock::time_point now);
[[nodiscard]] OpsResponse window(std::uint64_t region);
[[nodiscard]] OpsResponse commands(std::uint64_t region);
[[nodiscard]] OpsResponse schedules(std::uint64_t region);
[[nodiscard]] OpsResponse set_schedule(std::uint64_t region, std::string_view query,
const broker::AccessTokenClaims& admin);
[[nodiscard]] OpsResponse enqueue(std::uint64_t region, std::string_view query,
const broker::AccessTokenClaims& admin);
[[nodiscard]] OpsResponse set_window(std::uint64_t region, std::string_view query,
const broker::AccessTokenClaims& admin);
[[nodiscard]] OpsResponse tuning();
[[nodiscard]] OpsResponse tuning_text(std::uint64_t revision);
[[nodiscard]] OpsResponse set_tuning(std::string_view query, std::string_view text,
const broker::AccessTokenClaims& admin);
[[nodiscard]] OpsResponse deploy_status(std::string_view query);
[[nodiscard]] OpsResponse open_region(std::string_view query,
const broker::AccessTokenClaims& admin);
[[nodiscard]] std::optional<std::uint64_t> next_region(std::uint64_t served);
[[nodiscard]] std::optional<persistence::PgRows> query(const std::string& sql,
std::vector<std::string> parameters);
AdminConfig config_;
broker::TokenVerifier verifier_;
AdminConnect connect_;
AdminRegionView view_;
std::vector<AdminAsset> assets_;
std::optional<AdminDeployConfig> deploy_;
HttpsTransport https_;
std::unique_ptr<persistence::Postgres> db_;
struct CachedView {
std::chrono::steady_clock::time_point at;
std::string body;
};
std::map<std::uint64_t, CachedView> views_;
};
// Bounded blocking HTTP/1.1 GET of `path` from "host:port" (a name is resolved): the body of
// a 200 answer of at most `limit` bytes, or nullopt on any error, other status or timeout.
[[nodiscard]] std::optional<std::string> http_get(std::string_view address, std::string_view path,
std::chrono::milliseconds timeout,
std::size_t limit);
// JSON string literal (quotes included) with control characters escaped.
[[nodiscard]] std::string json_string(std::string_view text);
// The decoded value of `name` in a URL query ("a=1&b=x%20y"), or nullopt when absent or
// malformed (bad escape, a decoded control character, over `limit` bytes).
[[nodiscard]] std::optional<std::string> query_value(std::string_view query, std::string_view name,
std::size_t limit = 200);
} // namespace evo::server::admin
+50
View File
@@ -0,0 +1,50 @@
#pragma once
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
// ADR-0182 section 15: a bounded, blocking HTTPS/1.1 client for the admin API's two outbound
// services (Gitea and Argo CD). One request per connection (Connection: close); the system
// trust store and host name check unless `verify` is false. Credentials travel only in the
// request headers and are never logged.
namespace evo::server::admin {
struct HttpsRequest {
std::string host;
std::uint16_t port{443};
std::string method{"GET"};
std::string target{"/"}; // Path and query, already percent-encoded.
std::vector<std::pair<std::string, std::string>> headers;
std::string body;
bool verify{true};
std::chrono::milliseconds timeout{10'000};
std::size_t limit{std::size_t{4} << 20U}; // Largest body accepted.
};
struct HttpsResponse {
int status{};
std::string body;
};
// The transport the admin API uses; tests substitute a fake.
using HttpsTransport = std::function<std::optional<HttpsResponse>(const HttpsRequest&)>;
// Sends `request` over TLS: the answer, or nullopt on any connection, TLS, timeout, size or
// framing failure.
[[nodiscard]] std::optional<HttpsResponse> https_request(const HttpsRequest& request);
// An HTTP/1.1 response read to the end of the connection: the status and the body (by
// Content-Length, chunked, or to the end), or nullopt when malformed or over `limit`.
[[nodiscard]] std::optional<HttpsResponse> parse_http_response(std::string_view raw,
std::size_t limit);
// "https://host[:port][/...]" split into host, port and the path prefix (no trailing slash).
struct HttpsBase {
std::string host;
std::uint16_t port{443};
std::string prefix;
};
[[nodiscard]] std::optional<HttpsBase> parse_https_base(std::string_view url);
} // namespace evo::server::admin
@@ -0,0 +1,39 @@
#pragma once
#include <array>
#include <cstdint>
#include <expected>
#include <string>
#include <string_view>
// ADR-0182 section 15: the admin portal opens a fresh region in place of the one DEV serves.
// The change is four Git files edited in place: the region overlay's values (world, region,
// life routes, the opening's genesis commit and seeded wildlife range, both for the region
// Deployment and its provision Job), its kustomization header, and the region named by the
// grant broker's routes and the admin portal. Anything else is left exactly as it is; a file
// whose layout differs from the expected lines is refused rather than guessed at.
namespace evo::server::admin {
inline constexpr std::array<std::string_view, 4> region_switch_paths{
"deploy/kubernetes/region/dev/region-values.yaml",
"deploy/kubernetes/region/dev/kustomization.yaml",
"deploy/kubernetes/grant-broker-dev/deployment.yaml",
"deploy/kubernetes/admin-portal-dev/deployment.yaml",
};
// The four files' text, in region_switch_paths order.
using RegionSwitchFiles = std::array<std::string, 4>;
// What the files say DEV serves: the world and region, the opening's genesis commit (32
// lowercase hex digits) and the first seeded wildlife identity.
struct RegionLayout {
std::uint64_t world{}, region{};
std::string commit;
std::uint64_t wildlife_first{};
auto operator<=>(const RegionLayout&) const = default;
};
// The served layout, or the name of the line that is missing, repeated or inconsistent.
[[nodiscard]] std::expected<RegionLayout, std::string>
read_region_layout(const RegionSwitchFiles& files);
// The files serving `to` (same world) instead, with `note` (one line, no line breaks) recorded
// as a comment above the opening; or why the files or `to` cannot be switched.
[[nodiscard]] std::expected<RegionSwitchFiles, std::string>
switch_region(const RegionSwitchFiles& files, const RegionLayout& to, std::string_view note);
} // namespace evo::server::admin
+5 -1
View File
@@ -17,10 +17,13 @@ struct AccessTokenRules {
std::string audience; // Must appear in `aud` (string or array). std::string audience; // Must appear in `aud` (string or array).
std::string authorized_party; // `azp`: the game's public client. std::string authorized_party; // `azp`: the game's public client.
std::uint64_t leeway_seconds{30}; std::uint64_t leeway_seconds{30};
// ADR-0182: when set, the role must appear in `realm_access.roles` (the admin portal).
std::string realm_role{};
}; };
struct AccessTokenClaims { struct AccessTokenClaims {
std::string issuer, subject; std::string issuer, subject;
std::uint64_t expires_at{}; std::uint64_t expires_at{};
std::string email{}; // Empty when absent; shown to the admin, never used as identity.
}; };
enum class TokenError : std::uint8_t { enum class TokenError : std::uint8_t {
malformed, malformed,
@@ -34,7 +37,8 @@ enum class TokenError : std::uint8_t {
expired, expired,
not_yet_valid, not_yet_valid,
unverified_email, unverified_email,
missing_subject missing_subject,
missing_role
}; };
inline constexpr std::size_t max_access_token_bytes = 6144; inline constexpr std::size_t max_access_token_bytes = 6144;
@@ -13,6 +13,7 @@
#include <cstdint> #include <cstdint>
#include <expected> #include <expected>
#include <functional> #include <functional>
#include <map>
#include <memory> #include <memory>
#include <optional> #include <optional>
#include <span> #include <span>
@@ -152,6 +153,11 @@ class CellularRegionHost {
} }
// Queued choices not carried by the commit in flight: the open batch binds these. // Queued choices not carried by the commit in flight: the open batch binds these.
[[nodiscard]] std::vector<persistence::CellularMutationReservation> unbound_mutations() const; [[nodiscard]] std::vector<persistence::CellularMutationReservation> unbound_mutations() const;
// ADR-0182: queued admin commands (rules 13) not carried by the commit in flight, oldest
// first, at most one tick's worth. Publication binds each to its queue row once.
[[nodiscard]] std::vector<CellularAdminCommand> unbound_admin_commands() const;
// ADR-0182: the tuning revisions this host fetched and verified, for adopt_tuning commands.
[[nodiscard]] CellularTuningResolver tuning_resolver() const;
[[nodiscard]] std::vector<FinalCellularMutation> take_finalized_mutations(); [[nodiscard]] std::vector<FinalCellularMutation> take_finalized_mutations();
// v5 requests allocate durably, then wait for the scheduler to include the exact // v5 requests allocate durably, then wait for the scheduler to include the exact
// reservation in a profile-4 batch. Repeating the request is idempotent. // reservation in a profile-4 batch. Repeating the request is idempotent.
@@ -207,6 +213,7 @@ class CellularRegionHost {
void finalize_births(std::span<const CellularTickIntents::Birth> births); void finalize_births(std::span<const CellularTickIntents::Birth> births);
void queue_birth(const CellularTickIntents::Birth& birth); void queue_birth(const CellularTickIntents::Birth& birth);
void reload_mutations(); void reload_mutations();
void reload_admin_commands();
// ADR-0127: owned lives that died record their ending so the account may start again. // ADR-0127: owned lives that died record their ending so the account may start again.
void note_endings(const CellularLives& before, const CellularLives& after, void note_endings(const CellularLives& before, const CellularLives& after,
const persistence::Uuid& commit); const persistence::Uuid& commit);
@@ -285,6 +292,9 @@ class CellularRegionHost {
std::vector<CellularTickIntents::Birth> queued_births_; std::vector<CellularTickIntents::Birth> queued_births_;
std::vector<CellularBirthRefusal> pending_birth_refusals_; std::vector<CellularBirthRefusal> pending_birth_refusals_;
std::vector<persistence::CellularMutationReservation> queued_mutations_; std::vector<persistence::CellularMutationReservation> queued_mutations_;
std::vector<CellularAdminCommand> queued_admin_;
std::map<std::uint64_t, CellularRevampRules> verified_tuning_; // By revision.
std::chrono::steady_clock::time_point next_admin_reload_{};
// A reservation may exist that the queue does not show; reload before publishing. // A reservation may exist that the queue does not show; reload before publishing.
bool mutations_uncertain_{}; bool mutations_uncertain_{};
std::vector<FinalCellularMutation> finalized_mutations_; std::vector<FinalCellularMutation> finalized_mutations_;
+22 -3
View File
@@ -47,6 +47,13 @@ prepare_cellular_session_tick(
std::span<const network::CarriedAction> actions, std::span<const network::CarriedAction> actions,
std::span<const persistence::CellularMutationReservation> mutations = {}); std::span<const persistence::CellularMutationReservation> mutations = {});
// A tick takes one action per account. Keeps each account's discrete action (engulf, bud,
// become, emerge), else its newest (highest id), in `actions`, and returns the others, which
// the caller refuses. A client naming a tick it already sent a movement for then loses only
// that movement, not every player's actions on the tick.
[[nodiscard]] std::vector<network::CarriedAction>
keep_one_action_per_account(std::vector<network::CarriedAction>& actions);
// Builds one bounded publication from the last durable head. Its working copy is private; // Builds one bounded publication from the last durable head. Its working copy is private;
// only the host may publish, and callers must discard it after uncertainty until the host // only the host may publish, and callers must discard it after uncertainty until the host
// resolves that exact prepared batch. // resolves that exact prepared batch.
@@ -58,7 +65,8 @@ class CellularSessionBatchBuilder {
append(std::uint64_t tick, std::span<const CellularLifeIntent> baseline, append(std::uint64_t tick, std::span<const CellularLifeIntent> baseline,
std::span<const network::CarriedAction> actions, std::span<const network::CarriedAction> actions,
std::span<const CellularTickIntents::Birth> births = {}, std::span<const CellularTickIntents::Birth> births = {},
std::span<const persistence::CellularMutationReservation> mutations = {}); std::span<const persistence::CellularMutationReservation> mutations = {},
std::span<const CellularAdminCommand> admin = {});
// Scheduler path: expected placement/funding/existing-life refusals are reported // Scheduler path: expected placement/funding/existing-life refusals are reported
// separately, so they cannot prevent other births or the ordinary tick. Unexpected // separately, so they cannot prevent other births or the ordinary tick. Unexpected
// failures retain append's all-or-nothing behavior. Persist reports only after publish. // failures retain append's all-or-nothing behavior. Persist reports only after publish.
@@ -66,13 +74,22 @@ class CellularSessionBatchBuilder {
std::uint64_t tick, std::span<const CellularLifeIntent> baseline, std::uint64_t tick, std::span<const CellularLifeIntent> baseline,
std::span<const network::CarriedAction> actions, std::span<const network::CarriedAction> actions,
std::span<const CellularTickIntents::Birth> births = {}, std::span<const CellularTickIntents::Birth> births = {},
std::span<const persistence::CellularMutationReservation> mutations = {}); std::span<const persistence::CellularMutationReservation> mutations = {},
std::span<const CellularAdminCommand> admin = {});
[[nodiscard]] std::span<const CellularBirthRefusal> refused_births() const noexcept { [[nodiscard]] std::span<const CellularBirthRefusal> refused_births() const noexcept {
return refused_births_; return refused_births_;
} }
[[nodiscard]] const CellularBatch& batch() const noexcept { [[nodiscard]] const CellularBatch& batch() const noexcept {
return batch_; return batch_;
} }
// ADR-0182: names the rules of adopt_tuning commands (the host's verified revisions).
void set_tuning_resolver(CellularTuningResolver tuning) {
tuning_ = std::move(tuning);
}
// ADR-0182: each admin command appended so far and whether it applied, in trace order.
[[nodiscard]] std::span<const CellularAdminResult> admin_results() const noexcept {
return admin_results_;
}
[[nodiscard]] std::span<const CellularActionRecord> actions() const noexcept { [[nodiscard]] std::span<const CellularActionRecord> actions() const noexcept {
return actions_; return actions_;
} }
@@ -106,7 +123,7 @@ class CellularSessionBatchBuilder {
std::span<const network::CarriedAction> actions, std::span<const network::CarriedAction> actions,
std::span<const CellularTickIntents::Birth> births, std::span<const CellularTickIntents::Birth> births,
std::span<const persistence::CellularMutationReservation> mutations, std::span<const persistence::CellularMutationReservation> mutations,
bool allow_refusals); std::span<const CellularAdminCommand> admin, bool allow_refusals);
explicit CellularSessionBatchBuilder(std::unique_ptr<CellularLives> working) explicit CellularSessionBatchBuilder(std::unique_ptr<CellularLives> working)
: working_{std::move(working)} {} : working_{std::move(working)} {}
std::unique_ptr<CellularLives> working_; std::unique_ptr<CellularLives> working_;
@@ -114,6 +131,8 @@ class CellularSessionBatchBuilder {
std::vector<CellularActionRecord> actions_; std::vector<CellularActionRecord> actions_;
std::vector<CellularMutationActionRecord> mutation_actions_; std::vector<CellularMutationActionRecord> mutation_actions_;
std::vector<CellularBirthRefusal> refused_births_; std::vector<CellularBirthRefusal> refused_births_;
std::vector<CellularAdminResult> admin_results_;
CellularTuningResolver tuning_;
std::optional<CellularLivesError> last_lives_error_; std::optional<CellularLivesError> last_lives_error_;
}; };
} // namespace evo::server } // namespace evo::server
@@ -0,0 +1,49 @@
#pragma once
#include "evo/server/lifecycle/cellular_lives.hpp"
#include <cstddef>
#include <functional>
#include <string>
#include <string_view>
// ADR-0182 read-only region view for the admin portal: every cell, pool and bubble of a
// cellular owner as compact JSON. It reads the committed in-memory state and changes nothing;
// it is not a simulation output, a checkpoint or a client protocol.
//
// {"world":W,"region":R,"tick":T,"rules":N,["rules_sha256":"hex",]"area":[w,h],
// "spent":[e,c,n,p,o],"heat":pj,
// ["drip":[interval_ticks,bubble_pj,bubble_fg,heat_recycle_per_mille,absorb],]
// "cells_total":N,"deposits_total":N,
// "counts":[players,wildlife,patches,pools,bubbles],
// "totals":{"reserve":[e,c,n,p,o],"body":[...],"patches":[...],"pools":[...],"bubbles":[...]},
// "cells":[["life","organism","account",x,y,extent,flags,members,
// reserve_e,reserve_c,reserve_n,reserve_p,reserve_o,body_mass,"root"],...],
// "deposits":[[id,kind,x,y,radius,e,c,n,p,o],...]}
//
// Cell positions are the lower-left corner of the square footprint and deposits their centre,
// in micrometres. Life and organism ids are decimal strings (bud ids exceed 2^53); `account`
// is the lowercase UUID, empty for wildlife; `root` the lineage root (the founder whose life
// request a lineage descends from, cellular_lineage_root). Flags: 1 wildlife, 2 the account's
// session is connected, 4 lingering, 8 suspended. Deposit kind: 0 patch, 1 pool, 2 bubble. Energy
// in pJ, matter in fg. Cells and deposits beyond the limits are left out (by ascending life id and
// deposit id); the totals still count them. `rules_sha256` is given by the caller (the SHA-256
// of encode_cellular_revamp_rules, which tuning revisions are adopted by) and left out when empty.
// `heat` is the energy the region's cells have used and not yet recycled (CellularLives::heat).
// `drip` is the rules-13 spent-pool drip (cellular_drip_spent) and its energy cycle (ADR-0182
// section 14), left out before rules 13.
// `counts` and `totals` cover every life and deposit, whatever the limits: the region's stock
// is the totals plus `spent`.
namespace evo::server {
struct CellularAdminViewLimits {
std::size_t cells{4096}, deposits{16384};
};
// True when the account's session is connected to this region.
using CellularAdminOnline = std::function<bool(const LifeAccount&)>;
[[nodiscard]] std::string render_cellular_admin_view(const CellularLives& state,
const CellularAdminOnline& online,
CellularAdminViewLimits limits = {},
std::string_view rules_sha256 = {});
// Lowercase 8-4-4-4-12 text of a 16-byte account.
[[nodiscard]] std::string cellular_account_text(const LifeAccount& account);
} // namespace evo::server
@@ -22,6 +22,8 @@ struct CellularBatchHeader {
inline constexpr std::uint32_t cellular_batch_format = 3; inline constexpr std::uint32_t cellular_batch_format = 3;
// ADR-0166: explicit opt-in for owner format 8/rules 10; the default remains 3. // ADR-0166: explicit opt-in for owner format 8/rules 10; the default remains 3.
inline constexpr std::uint32_t cellular_batch_inheritance_format = 4; inline constexpr std::uint32_t cellular_batch_inheritance_format = 4;
// ADR-0182: trace 4 plus admin commands, for rules 13 only. A batch without commands stays 4.
inline constexpr std::uint32_t cellular_batch_admin_format = 5;
inline constexpr std::uint32_t cellular_batch_v2_format = 2; inline constexpr std::uint32_t cellular_batch_v2_format = 2;
inline constexpr std::uint32_t cellular_batch_legacy_format = 1; inline constexpr std::uint32_t cellular_batch_legacy_format = 1;
struct CellularTickIntents { struct CellularTickIntents {
@@ -38,6 +40,8 @@ struct CellularTickIntents {
// Choices accepted against the preceding checkpoint and scheduled for this tick. // Choices accepted against the preceding checkpoint and scheduled for this tick.
// The successor identity is durably reserved before the batch is replayed. // The successor identity is durably reserved before the batch is replayed.
std::vector<CellularMutationSelection> mutations; std::vector<CellularMutationSelection> mutations;
// Format 5 (ADR-0182): operator commands applied after the births, by ascending id.
std::vector<CellularAdminCommand> admin{};
friend bool operator==(const CellularTickIntents&, const CellularTickIntents&) = default; friend bool operator==(const CellularTickIntents&, const CellularTickIntents&) = default;
}; };
// Transient scheduler report, not part of the replay trace. A refused birth changes // Transient scheduler report, not part of the replay trace. A refused birth changes
@@ -61,6 +65,8 @@ struct CellularActionRecord {
struct CellularMutationActionInput { struct CellularMutationActionInput {
std::uint64_t life_id{}, event_index{}, offer_tick{}; std::uint64_t life_id{}, event_index{}, offer_tick{};
std::uint16_t operator_id{}; std::uint16_t operator_id{};
// Rules 13: continue as the split's offspring. Stored as bit 15 of the operator (schema 60).
bool become{};
friend bool operator==(const CellularMutationActionInput&, friend bool operator==(const CellularMutationActionInput&,
const CellularMutationActionInput&) = default; const CellularMutationActionInput&) = default;
}; };
@@ -79,13 +85,21 @@ inline constexpr std::size_t cellular_batch_tick_header_bytes = 16;
inline constexpr std::size_t cellular_batch_intent_bytes = 24; inline constexpr std::size_t cellular_batch_intent_bytes = 24;
inline constexpr std::size_t cellular_batch_birth_bytes = 40; inline constexpr std::size_t cellular_batch_birth_bytes = 40;
inline constexpr std::size_t cellular_batch_mutation_bytes = 40; inline constexpr std::size_t cellular_batch_mutation_bytes = 40;
// Format 5: id u64, kind u16, count u16, zero u32, target u64, energy and four matter u64.
inline constexpr std::size_t cellular_batch_admin_bytes = 64;
inline constexpr std::size_t max_cellular_tick_admin_commands = 16;
inline constexpr std::size_t max_cellular_batch_ticks = 64; inline constexpr std::size_t max_cellular_batch_ticks = 64;
// The largest trace of a batch whose ticks hold at most `lives` lives.
[[nodiscard]] constexpr std::size_t cellular_batch_bytes_for(std::size_t lives) noexcept {
return cellular_batch_header_bytes +
max_cellular_batch_ticks *
(cellular_batch_tick_header_bytes +
lives * (cellular_batch_intent_bytes + cellular_batch_birth_bytes +
cellular_batch_mutation_bytes) +
max_cellular_tick_admin_commands * cellular_batch_admin_bytes);
}
inline constexpr std::size_t max_cellular_batch_bytes = inline constexpr std::size_t max_cellular_batch_bytes =
cellular_batch_header_bytes + cellular_batch_bytes_for(biology::max_cellular_tick_lives);
max_cellular_batch_ticks * (cellular_batch_tick_header_bytes +
biology::max_cellular_tick_lives *
(cellular_batch_intent_bytes + cellular_batch_birth_bytes +
cellular_batch_mutation_bytes));
enum class CellularBatchError : std::uint8_t { format, version, scope, state }; enum class CellularBatchError : std::uint8_t { format, version, scope, state };
inline constexpr std::size_t cellular_action_record_bytes = 48; inline constexpr std::size_t cellular_action_record_bytes = 48;
inline constexpr std::size_t max_cellular_action_records = 1'024; inline constexpr std::size_t max_cellular_action_records = 1'024;
@@ -116,6 +130,19 @@ struct CellularMutationOutcome {
[[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularBatchError> [[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularBatchError>
replay_cellular_batch(const CellularLives& base, const CellularBatch& batch, replay_cellular_batch(const CellularLives& base, const CellularBatch& batch,
std::vector<CellularMutationOutcome>& mutation_outcomes); std::vector<CellularMutationOutcome>& mutation_outcomes);
// ADR-0182: also reports every admin command's result in trace order; `tuning` names the
// rules an adopt_tuning command adopts (a batch holds at most one).
[[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularBatchError>
replay_cellular_batch(const CellularLives& base, const CellularBatch& batch,
std::vector<CellularMutationOutcome>& mutation_outcomes,
std::vector<CellularAdminResult>& admin_results,
const CellularTuningResolver& tuning = {});
// ADR-0182: the rules a batch's single adopt_tuning names are its successor's (nothing else
// changes them), so publication and recovery resolve from the successor once they have
// checked the digest: this returns the successor's rules for `check(encoding, digest)`.
[[nodiscard]] CellularTuningResolver cellular_successor_tuning(
const CellularLives& successor,
std::function<bool(std::span<const std::uint8_t>, const std::array<std::uint8_t, 32>&)> check);
// The canonical 34-byte reserved choice (schema v29): tick, life, event and offer tick as // The canonical 34-byte reserved choice (schema v29): tick, life, event and offer tick as
// u64 and the operator as u16, little-endian. // u64 and the operator as u16, little-endian.
inline constexpr std::size_t cellular_mutation_input_bytes = 34; inline constexpr std::size_t cellular_mutation_input_bytes = 34;
+117 -4
View File
@@ -4,12 +4,15 @@
#include "evo/biology/mutation.hpp" #include "evo/biology/mutation.hpp"
#include "evo/server/lifecycle/cellular_light.hpp" #include "evo/server/lifecycle/cellular_light.hpp"
#include "evo/server/lifecycle/cellular_liquid.hpp" #include "evo/server/lifecycle/cellular_liquid.hpp"
#include "evo/server/lifecycle/cellular_revamp.hpp"
#include "evo/server/lifecycle/primitive_lives.hpp" #include "evo/server/lifecycle/primitive_lives.hpp"
#include <array>
#include <compare> #include <compare>
#include <cstddef> #include <cstddef>
#include <cstdint> #include <cstdint>
#include <expected> #include <expected>
#include <functional>
#include <memory> #include <memory>
#include <optional> #include <optional>
#include <span> #include <span>
@@ -61,16 +64,25 @@ inline constexpr std::uint32_t cellular_lives_photosynthesis_rules = 11;
// liquid rules and each life's motion state, on a format-3 habitat whose food moves. // liquid rules and each life's motion state, on a format-3 habitat whose food moves.
inline constexpr std::uint32_t cellular_lives_liquid_format = 10; inline constexpr std::uint32_t cellular_lives_liquid_format = 10;
inline constexpr std::uint32_t cellular_lives_liquid_rules = 12; inline constexpr std::uint32_t cellular_lives_liquid_rules = 12;
// Rules that retain offspring plans (formats 8 to 10): 10 to 12. // Rules 13 (ADR-0179, Cellular_Revamp_Build_Plan.md): rules 12 with founder 6 (genome schema 7,
// development 7) and the region's declared revamp rules. Format 11 is format 10 with those
// rules; later build phases extend it before it is first deployed.
inline constexpr std::uint32_t cellular_lives_revamp_format = 11;
inline constexpr std::uint32_t cellular_lives_revamp_rules = 13;
// Rules that retain offspring plans (formats 8 to 11): 10 to 13.
[[nodiscard]] constexpr bool cellular_retained_plans(std::uint32_t rules) noexcept { [[nodiscard]] constexpr bool cellular_retained_plans(std::uint32_t rules) noexcept {
return rules == cellular_lives_inheritance_rules || return rules == cellular_lives_inheritance_rules ||
rules == cellular_lives_photosynthesis_rules || rules == cellular_lives_liquid_rules; rules == cellular_lives_photosynthesis_rules || rules == cellular_lives_liquid_rules ||
rules == cellular_lives_revamp_rules;
} }
inline constexpr std::uint32_t cellular_growth_per_tick = 5; // Per 50 ms; trial rate. inline constexpr std::uint32_t cellular_growth_per_tick = 5; // Per 50 ms; trial rate.
// Rules 13: a bud engulfed within this many ticks of birth reports to its parent (2 minutes).
inline constexpr std::uint64_t cellular_bud_early_ticks = 2'400;
// The founder a region of these rules creates. // The founder a region of these rules creates.
[[nodiscard]] constexpr biology::FounderVersion [[nodiscard]] constexpr biology::FounderVersion
cellular_founder_version(std::uint32_t rules) noexcept { cellular_founder_version(std::uint32_t rules) noexcept {
return rules >= cellular_lives_liquid_rules ? biology::primitive_founder_v5 return rules >= cellular_lives_revamp_rules ? biology::primitive_founder_v6
: rules >= cellular_lives_liquid_rules ? biology::primitive_founder_v5
: rules >= cellular_lives_photosynthesis_rules ? biology::primitive_founder_v4 : rules >= cellular_lives_photosynthesis_rules ? biology::primitive_founder_v4
: rules >= cellular_lives_reproduction_rules ? biology::primitive_founder_v3 : rules >= cellular_lives_reproduction_rules ? biology::primitive_founder_v3
: rules >= cellular_lives_balance_rules ? biology::primitive_founder_v2 : rules >= cellular_lives_balance_rules ? biology::primitive_founder_v2
@@ -128,6 +140,7 @@ struct CellularOwnedLife {
std::uint64_t frozen_since{}; std::uint64_t frozen_since{};
std::uint64_t offspring_genome{}; // Format 8; older formats retain zero. std::uint64_t offspring_genome{}; // Format 8; older formats retain zero.
biology::CellularMotionState motion{}; // Format 10; older formats retain zero. biology::CellularMotionState motion{}; // Format 10; older formats retain zero.
CellularRevampLife revamp{}; // Format 11 (rules 13): mutation state.
auto operator<=>(const CellularOwnedLife&) const = default; auto operator<=>(const CellularOwnedLife&) const = default;
}; };
struct CellularOwnedCorpse { struct CellularOwnedCorpse {
@@ -157,6 +170,10 @@ struct CellularOffspringRevision {
[[nodiscard]] constexpr std::uint64_t cellular_offspring_genome(const CellularOwnedLife& life) { [[nodiscard]] constexpr std::uint64_t cellular_offspring_genome(const CellularOwnedLife& life) {
return life.offspring_genome == 0 ? life.identity.genome : life.offspring_genome; return life.offspring_genome == 0 ? life.identity.genome : life.offspring_genome;
} }
// Rules 13 (reproduction plan section 7): an owned organism with enough members, body and reserve
// mass, and reserve energy may emerge.
[[nodiscard]] bool cellular_can_emerge(const CellularOwnedLife& life,
const CellularRevampRules& rules) noexcept;
class CellularMigration; class CellularMigration;
class CellularEnvironment; class CellularEnvironment;
struct CellularLifeIntent { struct CellularLifeIntent {
@@ -164,9 +181,58 @@ struct CellularLifeIntent {
biology::CellularStepIntent intent{}; biology::CellularStepIntent intent{};
auto operator<=>(const CellularLifeIntent&) const = default; auto operator<=>(const CellularLifeIntent&) const = default;
}; };
// ADR-0182 admin commands: operator inputs recorded in the trace (batch format 5) and applied
// after a tick's births, in ascending id. Imports enter the boundary ledger as a named game
// source; removed matter goes to the spent pool. A command whose target is gone or that does
// not fit is refused and changes nothing; the others still apply.
enum class CellularAdminKind : std::uint8_t { // A u16 in the trace.
remove_cell = 1, // `target` life: body and reserve go to the spent pool.
grant_reserve = 2, // `amount` imported into the `target` life's reserve.
add_bubbles = 3, // `amount` imported as `count` (1..256) bubbles sharing it.
add_pool = 4, // `amount` imported into the spent pool.
release_pool = 5, // Up to `amount` moved from the spent pool into `count` bubbles.
spawn_wildlife = 6, // `count` (1..256) random-genome roots, identities `target`.., imported.
// ADR-0182 tuning amendment: the region's rules-13 rules become tuning revision `target`,
// whose canonical rules encoding (encode_cellular_revamp_rules) has the SHA-256 held in the
// energy, carbon, nitrogen and phosphorus amounts (little-endian words; `other` zero).
adopt_tuning = 7,
// Schema 67: up to `amount` (per channel, never more than it holds) moved from the
// `target` life's reserve to the spent pool; and every wildlife life removed as by 1.
take_reserve = 8,
remove_wildlife = 9,
};
struct CellularAdminCommand {
std::uint64_t id{}; // The durable queue id.
CellularAdminKind kind{};
std::uint16_t count{};
std::uint64_t target{};
accounting::Inventory amount{};
friend bool operator==(const CellularAdminCommand&, const CellularAdminCommand&) = default;
};
// Shape only (kind, counts, amounts, identity range); whether it applies is decided at its tick.
[[nodiscard]] bool cellular_admin_command_valid(const CellularAdminCommand& command) noexcept;
// The 32-byte digest an adopt_tuning command carries, and a command carrying one.
[[nodiscard]] std::array<std::uint8_t, 32>
cellular_admin_digest(const CellularAdminCommand& command) noexcept;
[[nodiscard]] CellularAdminCommand
cellular_adopt_tuning_command(std::uint64_t id, std::uint64_t revision,
const std::array<std::uint8_t, 32>& digest) noexcept;
// The rules an adopt_tuning command names, from whoever can check its digest (the region host
// from the revision text, publication and recovery from the successor state). Nullopt: unknown.
using CellularTuningResolver = std::function<std::optional<CellularRevampRules>(
std::uint64_t revision, const std::array<std::uint8_t, 32>& digest)>;
// Canonical bytes of the rules-13 rules (as the owner snapshot stores them, without the pool).
[[nodiscard]] std::vector<std::uint8_t> encode_cellular_revamp_rules(const CellularRevampRules& r);
struct CellularAdminResult {
std::uint64_t id{};
bool applied{};
friend bool operator==(const CellularAdminResult&, const CellularAdminResult&) = default;
};
struct CellularMutationSelection { struct CellularMutationSelection {
std::uint64_t life_id{}, event_index{}, offer_tick{}, successor_id{}; std::uint64_t life_id{}, event_index{}, offer_tick{}, successor_id{};
std::uint16_t operator_id{}; std::uint16_t operator_id{};
// Rules 13: the split's offspring becomes the player's cell; the founder becomes wildlife.
bool become{};
auto operator<=>(const CellularMutationSelection&) const = default; auto operator<=>(const CellularMutationSelection&) const = default;
}; };
// declined (ADR-0120 amendment): operator 0 consumed the offer without changing the genome. // declined (ADR-0120 amendment): operator 0 consumed the offer without changing the genome.
@@ -175,7 +241,9 @@ enum class CellularMutationResult : std::uint8_t {
life_died, life_died,
insufficient_funding, insufficient_funding,
declined, declined,
offspring_plan_applied // Rules 10: inherited plan changed, expressed body did not. offspring_plan_applied, // Rules 10: inherited plan changed, expressed body did not.
split_applied, // Rules 13: the cell split; the offspring expresses the mutation.
split_refused // Rules 13: no split now (size, room or region cap); offer kept.
}; };
struct CellularMutationExecution { struct CellularMutationExecution {
std::uint64_t life_id{}, successor_id{}; std::uint64_t life_id{}, successor_id{};
@@ -220,6 +288,12 @@ struct CellularLifeTickFeedback {
CellularPresence presence{CellularPresence::active}; CellularPresence presence{CellularPresence::active};
bool resume_blocked{}; bool resume_blocked{};
accounting::Picojoules light{}; // Rules 11 (ADR-0175): light captured this tick. accounting::Picojoules light{}; // Rules 11 (ADR-0175): light captured this tick.
std::uint8_t exclude{}; // Rules 13: the matter channels kept from burning this tick.
// Rules 13, owned lives: what held this tick's growth step back (0 nothing: a full step or
// fully grown; 1 energy; 2-5 carbon, nitrogen, phosphorus, other; 6 no room), and what the
// tick moved: collected from food, built into the body, and burned in place of energy.
std::uint8_t growth_limit{};
accounting::Inventory collected{}, into_growth{}, burned{};
auto operator<=>(const CellularLifeTickFeedback&) const = default; auto operator<=>(const CellularLifeTickFeedback&) const = default;
}; };
// Which owner version a new region starts on. Offers: format 2, rules 2 (the M11.3/11.4 // Which owner version a new region starts on. Offers: format 2, rules 2 (the M11.3/11.4
@@ -261,6 +335,16 @@ enum class CellularLivesError : std::uint8_t {
checksum, checksum,
noncanonical noncanonical
}; };
// Rules 13 (reproduction plan section 6): the genome an organism of `members` cells develops
// as (the target size times its members); the genome itself for a single cell.
[[nodiscard]] std::expected<biology::Genome, CellularLivesError>
cellular_organism_genome(const biology::Genome& genome, std::uint32_t members);
class CellularLives;
// The root of a life's lineage: its parent's parent and so on, through living cells and
// corpses, up to the life without a parent (a player's birth). A player's life reservation
// names that root, even after control moved to an offspring, a bud or an organism.
[[nodiscard]] std::uint64_t cellular_lineage_root(const CellularLives& state,
std::uint64_t life_id);
// In-memory authoritative cellular owner. It consumes funded profile-3 opening // In-memory authoritative cellular owner. It consumes funded profile-3 opening
// state but never mutates or reinterprets that checkpoint. Each tick is applied // state but never mutates or reinterprets that checkpoint. Each tick is applied
@@ -291,6 +375,11 @@ class CellularLives {
[[nodiscard]] const biology::LineageArchive& archive() const noexcept; [[nodiscard]] const biology::LineageArchive& archive() const noexcept;
[[nodiscard]] accounting::Inventory nursery() const noexcept; [[nodiscard]] accounting::Inventory nursery() const noexcept;
[[nodiscard]] accounting::Inventory heat() const noexcept; [[nodiscard]] accounting::Inventory heat() const noexcept;
// Rules 13: burned matter and kill remainders waiting to drip back as bubbles.
[[nodiscard]] accounting::Inventory spent() const noexcept;
// ADR-0182 observers: a life's square footprint side in micrometres, as the step uses it;
// nullopt when its genome cannot be costed. Reads the state; changes nothing.
[[nodiscard]] std::optional<std::uint32_t> extent_of(const CellularOwnedLife& life) const;
[[nodiscard]] accounting::Inventory opening_total() const noexcept; [[nodiscard]] accounting::Inventory opening_total() const noexcept;
[[nodiscard]] accounting::Inventory current_total() const noexcept; [[nodiscard]] accounting::Inventory current_total() const noexcept;
[[nodiscard]] const CellularBoundaryLedger& boundary_ledger() const noexcept; [[nodiscard]] const CellularBoundaryLedger& boundary_ledger() const noexcept;
@@ -313,6 +402,19 @@ class CellularLives {
// bubble) and lives start at rest. Founders born afterwards are founder 5. // bubble) and lives start at rest. Founders born afterwards are founder 5.
[[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularLivesError> [[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
liquid_upgrade_candidate(const CellularLiquidRules& rules) const; liquid_upgrade_candidate(const CellularLiquidRules& rules) const;
// Rules 13: explicit no-tick format-10/rules-12 -> format-11/rules-13 upgrade declaring the
// region's revamp rules. Existing lives keep their genomes; founders born afterwards are
// founder 6. ADR-0180 optionally seeds nursery-funded DEV roots in an empty tick-1
// opening. Count zero with first identity zero retains the historical upgrade.
[[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
revamp_upgrade_candidate(const CellularRevampRules& rules,
std::uint32_t playtest_wildlife_count = 0,
std::uint64_t playtest_first_identity = 0) const;
// Exact displayed charge, including inherited plan, rules-13 fee and internal tissue.
// Internal litter reports the maximum possible charge (the draw occurs at action time).
[[nodiscard]] std::optional<accounting::Inventory> budding_cost(std::uint64_t life_id) const;
// Format 11: the declared revamp rules (defaults before).
[[nodiscard]] const CellularRevampRules& revamp_rules() const noexcept;
// Format 10: the declared liquid rules and the current field they generate (null before). // Format 10: the declared liquid rules and the current field they generate (null before).
[[nodiscard]] const CellularLiquidRules& liquid_rules() const noexcept; [[nodiscard]] const CellularLiquidRules& liquid_rules() const noexcept;
[[nodiscard]] const biology::CellularFlowField* flow_field() const noexcept; [[nodiscard]] const biology::CellularFlowField* flow_field() const noexcept;
@@ -359,6 +461,12 @@ class CellularLives {
[[nodiscard]] std::expected<CellularTickExecution, CellularLivesError> [[nodiscard]] std::expected<CellularTickExecution, CellularLivesError>
advance_tick_with_mutations(std::span<const CellularLifeIntent> intents, advance_tick_with_mutations(std::span<const CellularLifeIntent> intents,
std::span<const CellularMutationSelection> selections); std::span<const CellularMutationSelection> selections);
// ADR-0182: a detached candidate after `commands` (valid, strictly ascending ids) at the
// current tick, after its births. Rules 13 only. `results` reports each command, in order.
[[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
admin_candidate(std::span<const CellularAdminCommand> commands,
std::vector<CellularAdminResult>* results = nullptr,
const CellularTuningResolver& tuning = {}) const;
private: private:
friend class CellularMigration; friend class CellularMigration;
@@ -379,6 +487,11 @@ class CellularLives {
migration_replacement(std::vector<CellularOwnedLife>, const biology::LineageArchive&, migration_replacement(std::vector<CellularOwnedLife>, const biology::LineageArchive&,
CellularBoundaryLedger) const; CellularBoundaryLedger) const;
struct State; struct State;
// ADR-0180/0182: one randomized founder root `id` placed at a seeded free spot, funded
// from the nursery, or (with `imported`) by a game-source import added to it.
[[nodiscard]] static std::optional<CellularLivesError>
seed_wildlife_root(State& next, std::uint64_t world, std::uint64_t region, std::uint64_t tick,
std::uint64_t id, accounting::Inventory* imported);
explicit CellularLives(std::unique_ptr<State> state); explicit CellularLives(std::unique_ptr<State> state);
std::unique_ptr<State> state_; std::unique_ptr<State> state_;
std::vector<CellularLifeTickFeedback> last_tick_feedback_; std::vector<CellularLifeTickFeedback> last_tick_feedback_;
@@ -30,7 +30,7 @@ struct CellularMigrationTrace {
}; };
inline constexpr std::size_t migration_trace_header_bytes = 256; inline constexpr std::size_t migration_trace_header_bytes = 256;
inline constexpr std::size_t max_migration_trace_bytes = inline constexpr std::size_t max_migration_trace_bytes =
migration_trace_header_bytes + 8 * biology::max_cellular_tick_lives + 8; migration_trace_header_bytes + 8 * biology::max_cellular_frozen_lives + 8;
struct RecordedCellularMigration { struct RecordedCellularMigration {
CellularMigrationTrace trace; CellularMigrationTrace trace;
CellularMigrationExecution execution; CellularMigrationExecution execution;
@@ -15,11 +15,17 @@ struct CellularPlaySummary {
std::uint64_t owned{}, wildlife{}, lingering{}, suspended{}; std::uint64_t owned{}, wildlife{}, lingering{}, suspended{};
// Every death so far, by recorded cause (unrecorded below rules 3) and by kind. // Every death so far, by recorded cause (unrecorded below rules 3) and by kind.
std::uint64_t deaths{}, starved{}, engulfed{}, unrecorded{}; std::uint64_t deaths{}, starved{}, engulfed{}, unrecorded{};
// Rules 13: single cells that became organisms, and organisms that emerged.
std::uint64_t merged{}, emerged{};
std::uint64_t owned_deaths{}, wildlife_deaths{}; std::uint64_t owned_deaths{}, wildlife_deaths{};
// Lifespans in ticks of the dead (born to death), from the archive. // Lifespans in ticks of the dead (born to death), from the archive.
std::uint64_t lifespan_min{}, lifespan_median{}, lifespan_max{}; std::uint64_t lifespan_min{}, lifespan_median{}, lifespan_max{};
// Reproduction and evolution: buds so far, mutations applied, living variety. // Reproduction and evolution: buds so far, mutations applied, living variety.
std::uint64_t buds{}, mutations{}, living_genomes{}, deepest_lineage{}; std::uint64_t buds{}, mutations{}, living_genomes{}, deepest_lineage{};
// Rules 13: living organisms and the largest one's cells; offers waiting for a choice and
// offers earned by the living; matter in the spent pool.
std::uint64_t organisms{}, largest_organism{}, offers_pending{}, offers_earned{};
std::uint64_t spent_matter_fg{};
friend bool operator==(const CellularPlaySummary&, const CellularPlaySummary&) = default; friend bool operator==(const CellularPlaySummary&, const CellularPlaySummary&) = default;
}; };
@@ -33,8 +33,8 @@ struct CellularTierPolicy {
}; };
inline constexpr std::size_t cellular_population_header_bytes = 80; inline constexpr std::size_t cellular_population_header_bytes = 80;
inline constexpr std::uint32_t cellular_population_inheritance_format = 3; inline constexpr std::uint32_t cellular_population_inheritance_format = 3;
inline constexpr std::size_t max_cellular_population_bytes = cellular_population_header_bytes + inline constexpr std::size_t max_cellular_population_bytes =
16 * biology::max_cellular_tick_lives + cellular_population_header_bytes + 16 * biology::max_cellular_frozen_lives +
max_cellular_lives_bytes + 8; max_cellular_lives_bytes + 8;
class CellularPopulation { class CellularPopulation {
@@ -26,8 +26,8 @@ struct CellularPopulationBatch {
}; };
inline constexpr std::size_t population_batch_header_bytes = 136; inline constexpr std::size_t population_batch_header_bytes = 136;
inline constexpr std::size_t max_population_batch_bytes = inline constexpr std::size_t max_population_batch_bytes =
population_batch_header_bytes + max_cellular_batch_bytes + population_batch_header_bytes + cellular_batch_bytes_for(biology::max_cellular_frozen_lives) +
max_cellular_batch_ticks * (16 + 16 * biology::max_cellular_tick_lives); max_cellular_batch_ticks * (16 + 16 * biology::max_cellular_frozen_lives);
struct CellularPopulationExecution { struct CellularPopulationExecution {
CellularPopulationBatch batch; CellularPopulationBatch batch;
std::unique_ptr<CellularPopulation> state; std::unique_ptr<CellularPopulation> state;
@@ -0,0 +1,151 @@
#pragma once
#include "evo/biology/cellular_catalog.hpp"
#include "evo/biology/cellular_habitat.hpp"
#include "evo/biology/cellular_motion.hpp"
#include "evo/biology/cellular_offers.hpp"
#include "evo/biology/cellular_region_step.hpp"
#include "evo/biology/cellular_revamp_tuning.hpp"
#include "evo/biology/cellular_triggers.hpp"
#include "evo/biology/development.hpp"
#include <array>
#include <compare>
#include <cstdint>
#include <optional>
// Rules 13 (ADR-0179, Cellular_Revamp_Build_Plan.md): what a cellular owner declares when it
// upgrades to owner format 11. Taken from the Git tuning file when the region opens and
// persisted with the owner, so replay and restore never read the file. Later build phases add
// the feeding, mutation and reproduction tunables here.
namespace evo::server {
struct CellularRevampRules {
biology::BodyTuning body{};
// Picojoules 1,000 fg of C, N, P and other matter stand in for at burn efficiency 100.
std::array<std::uint64_t, 4> burn_pj_per_kfg{};
biology::CellularRevampStepRules step{};
// The spent pool drips back as bubbles every `drip_interval_ticks` ticks (0: never), one
// bubble per non-empty channel of at most these amounts, at seeded random spots.
std::uint32_t drip_interval_ticks{};
std::uint64_t drip_bubble_pj{}, drip_bubble_fg{};
// ADR-0182 section 14 (0 and false keep the historical law): the share of the region's
// heat, per mille, moved to the spent pool at the end of every tick before the drip, so
// energy cycles back like matter; and a drip at the deposit limit joins an existing bubble
// (the first at or after its spot) instead of waiting.
std::uint32_t heat_recycle_per_thousand{};
bool drip_absorb{};
// Share of reserve matter carried as load, per mille: it slows thrust and turning and makes
// thrust costlier, in proportion to the body's mass. Upkeep stays on the body.
std::uint32_t reserve_load_per_thousand{};
// Growth per tick in hundredths of a per mille at growth speed 100 (trial 500: 5 per mille).
std::uint32_t growth_per_tick_centi_mille{500};
// Mutation offers: the draw, the catalog's bounds and gates, the cadence in active ticks,
// and every catalog mutation's tunables in catalog order.
biology::CellularOfferRules offers{};
biology::CellularCatalogBounds bounds{};
std::uint32_t offer_interval_ticks{500};
std::array<biology::CellularMutationTuning, biology::cellular_catalog_size> mutations{};
// Reproduction: the offspring's share of a split and the growth a cell needs to split; the
// on-demand bud's fee (amounts times scale, reclaimed); the region's organism cap.
std::uint32_t split_share_per_thousand{500}, split_min_growth{1'000};
accounting::Inventory bud_fee{};
std::uint32_t bud_fee_scale_percent{};
std::uint32_t organism_cap{256};
// Wildlife buds are refused at this many lives (0: the organism cap), leaving the slots
// above it to players; spawning still answers to the organism cap. Below 32,768.
std::uint32_t wildlife_cap{};
// Multicellular organisms (reproduction plan section 6): the share of the extra members'
// mass carried as load on one cell's thrust, and the emergence threshold.
std::uint32_t organism_load_per_thousand{500};
std::uint32_t emerge_members{8};
std::uint64_t emerge_mass_fg{}, emerge_reserve_pj{};
// ADR-0181: 0 preserves historical behavior. Revision 1 makes split_share
// the controlled cell's share, returns bud fees to that cell, launches mutation
// offspring, and protects a growth fuel buffer for every organism.
std::uint32_t safety_version{}, growth_reserve_seconds{}, split_launch_um_per_s{};
auto operator<=>(const CellularRevampRules&) const = default;
};
// A rules-13 offer: the drawn mutations (catalog ids) and their chances, in catalog order.
inline constexpr std::size_t max_cellular_offer_options = 10;
struct CellularRevampOffer {
std::uint64_t event_index{}, offer_tick{};
std::uint8_t count{};
std::array<std::uint16_t, max_cellular_offer_options> ids{};
std::array<std::uint32_t, max_cellular_offer_options> chances{};
auto operator<=>(const CellularRevampOffer&) const = default;
};
// A rules-13 life's mutation state: affinity, lineage progress, the cadence counter, the pending
// offer (count 0: none), the previous tick's brake (for presses) and the growth carry.
struct CellularRevampLife {
biology::CellularAffinity affinity{};
biology::CellularLineageProgress progress{};
std::uint32_t active_ticks{};
std::uint8_t last_brake{};
std::uint16_t members{1}; // Cells in the organism: 1 for a single cell.
std::uint32_t growth_carry{};
std::uint64_t events{}; // Offers made so far; the next offer's event index is events + 1.
CellularRevampOffer offer{};
auto operator<=>(const CellularRevampLife&) const = default;
};
// The rules' offer settings as the catalog and offer code take them.
[[nodiscard]] bool cellular_revamp_offer_rules_valid(const CellularRevampRules& rules) noexcept;
// Draws an offer from `plan`'s eligible mutations at its affinity, or nothing when fewer
// mutations are eligible than the cap can fill. Seeded by world, region, life and event, so a
// retry draws the same offer.
[[nodiscard]] std::optional<CellularRevampOffer>
cellular_draw_offer(const biology::Genome& plan, const CellularRevampLife& life,
const CellularRevampRules& rules, std::uint64_t world, std::uint64_t region,
std::uint64_t life_id, std::uint64_t tick);
// How many offspring one bud makes from `litter` (hundredths of an extra offspring) and a roll:
// one, plus every whole hundred, plus one more when roll % 100 falls below the remainder; at most
// max_litter / 100 + 1.
[[nodiscard]] constexpr std::uint32_t
cellular_litter_count(std::uint32_t litter, std::uint64_t roll, std::uint32_t max_litter) noexcept {
const auto count = 1 + litter / 100 + (roll % 100 < litter % 100 ? 1U : 0U);
return count < max_litter / 100 + 1 ? count : max_litter / 100 + 1;
}
// What choosing a mutation costs: its amounts times its scale.
[[nodiscard]] accounting::Inventory
cellular_mutation_cost(const biology::CellularMutationTuning& tuning) noexcept;
// Returns `amount` to the region as bubbles at seeded random spots, one per non-empty channel;
// a habitat at its deposit limit merges each into the existing deposit farthest from `from`.
// False only on identity overflow.
[[nodiscard]] bool cellular_reclaim(biology::CellularHabitatConfig& config,
const accounting::Inventory& amount, std::uint64_t seed,
biology::CellularPosition from, std::uint64_t source);
[[nodiscard]] bool cellular_revamp_valid(const CellularRevampRules& rules) noexcept;
// The spent pool's drip for the tick ending at `tick`: on every `drip_interval_ticks`-th tick,
// one bubble per non-empty channel of at most the declared size, taken from `spent`, at a
// seeded random spot (nudged east past taken addresses) with the next deposit id and `source`.
// A habitat at its deposit limit keeps the rest waiting, or with `drip_absorb` adds it to the
// first bubble at or after that spot in address order (wrapping). False only on identity
// overflow, with `config` and `spent` then unusable.
[[nodiscard]] bool cellular_drip_spent(biology::CellularHabitatConfig& config,
accounting::Inventory& spent,
const CellularRevampRules& rules, std::uint64_t world,
std::uint64_t region, std::uint64_t tick,
std::uint64_t source);
// ADR-0182 admin bubbles: `amount` as `count` bubbles, each channel split evenly (the remainder
// in the last), at seeded random spots nudged east past taken addresses, with the next deposit
// ids and `source`. False, with `config` unchanged, when the habitat cannot take them all.
[[nodiscard]] bool cellular_scatter_bubbles(biology::CellularHabitatConfig& config,
const accounting::Inventory& amount,
std::uint16_t count, std::uint64_t seed,
std::uint64_t source);
// A body's handling carrying reserve matter: thrust, reverse thrust and turning scale by
// body / (body + load), full-output costs by (body + load) / body, where load is the declared
// share of `carried` matter. Drag is unchanged. No load leaves the handling as it is.
[[nodiscard]] biology::CellularHandling
cellular_loaded_handling(const biology::CellularHandling& handling, std::uint64_t body_mass,
std::uint64_t carried, const CellularRevampRules& rules,
std::uint64_t extra_load = 0) noexcept;
// Rules from the revamp tuning file.
[[nodiscard]] CellularRevampRules
cellular_revamp_rules(const biology::CellularRevampTuning& tuning);
} // namespace evo::server
+21 -9
View File
@@ -19,13 +19,17 @@ struct OpsResponse {
int status{200}; int status{200};
std::string body; std::string body;
std::string content_type{"text/plain; charset=utf-8"}; std::string content_type{"text/plain; charset=utf-8"};
std::string headers{}; // Extra header lines, each ending in CRLF (ADR-0182 portal).
}; };
// Receives the request path (no query handling: probes use exact paths). // Receives the request path (no query handling: probes use exact paths).
using OpsHandler = std::function<OpsResponse(std::string_view path)>; using OpsHandler = std::function<OpsResponse(std::string_view path)>;
// ADR-0131 API mode (the grant broker): GET or POST without a body, the path and the // ADR-0131 API mode (the grant broker): GET or POST, the path and the Authorization header
// Authorization header value (empty when absent). Views are valid during the call only. // value (empty when absent). A body (Content-Length, no chunked encoding) is accepted only
// when the server is asked for one (ADR-0182 admin tuning); otherwise it is a 400. Views are
// valid during the call only.
struct ApiRequest { struct ApiRequest {
std::string_view method, path, authorization; std::string_view method, path, authorization;
std::string_view body{};
}; };
using ApiHandler = std::function<OpsResponse(const ApiRequest&)>; using ApiHandler = std::function<OpsResponse(const ApiRequest&)>;
enum class OpsError : std::uint8_t { address, socket }; enum class OpsError : std::uint8_t { address, socket };
@@ -38,12 +42,17 @@ class OpsServer {
static constexpr std::size_t max_accepts_per_serve = 4; static constexpr std::size_t max_accepts_per_serve = 4;
static constexpr std::size_t max_request_bytes = 4096; static constexpr std::size_t max_request_bytes = 4096;
static constexpr std::size_t max_api_request_bytes = 8192; // Room for an access token. static constexpr std::size_t max_api_request_bytes = 8192; // Room for an access token.
static constexpr std::size_t max_response_bytes = 16384; static constexpr std::size_t max_api_body_bytes = std::size_t{64} << 10U; // Beyond those.
static constexpr std::size_t max_response_bytes = 16384; // The default bound.
// ADR-0182: the admin view and portal answer up to this many bytes when asked to.
static constexpr std::size_t max_configurable_response_bytes = std::size_t{4} << 20U;
static constexpr std::chrono::milliseconds connection_deadline{1000}; static constexpr std::chrono::milliseconds connection_deadline{1000};
// Numeric address only ("127.0.0.1:9100" or "[::1]:9100"); port 0 picks one. // Numeric address only ("127.0.0.1:9100" or "[::1]:9100"); port 0 picks one. A
// response over `response_limit` bytes (at most max_configurable_response_bytes) is
// replaced by a 500.
[[nodiscard]] static std::expected<std::unique_ptr<OpsServer>, OpsError> [[nodiscard]] static std::expected<std::unique_ptr<OpsServer>, OpsError>
listen(std::string_view address); listen(std::string_view address, std::size_t response_limit = max_response_bytes);
OpsServer(const OpsServer&) = delete; OpsServer(const OpsServer&) = delete;
OpsServer& operator=(const OpsServer&) = delete; OpsServer& operator=(const OpsServer&) = delete;
OpsServer(OpsServer&&) = delete; OpsServer(OpsServer&&) = delete;
@@ -56,8 +65,9 @@ class OpsServer {
// expires connections without waiting. Connections beyond the bound are closed // expires connections without waiting. Connections beyond the bound are closed
// at once; slow or oversized ones are answered or dropped without delaying others. // at once; slow or oversized ones are answered or dropped without delaying others.
void serve(const OpsHandler& handler); void serve(const OpsHandler& handler);
// The same bounded loop for API requests (max_api_request_bytes). // The same bounded loop for API requests (max_api_request_bytes), with request bodies of
void serve_api(const ApiHandler& handler); // at most `body_limit` (at most max_api_body_bytes) bytes; larger ones answer 413.
void serve_api(const ApiHandler& handler, std::size_t body_limit = 0);
[[nodiscard]] std::uint64_t refused() const noexcept { [[nodiscard]] std::uint64_t refused() const noexcept {
return refused_; return refused_;
} }
@@ -72,12 +82,14 @@ class OpsServer {
std::size_t sent{}; std::size_t sent{};
std::chrono::steady_clock::time_point deadline{}; std::chrono::steady_clock::time_point deadline{};
}; };
OpsServer(int fd, std::uint16_t port) : fd_(fd), port_(port) {} OpsServer(int fd, std::uint16_t port, std::size_t response_limit)
: fd_(fd), port_(port), response_limit_(response_limit) {}
void respond(Connection& c, const OpsHandler& handler); void respond(Connection& c, const OpsHandler& handler);
void respond_api(Connection& c, const ApiHandler& handler); void respond_api(Connection& c, const ApiHandler& handler, std::size_t body_limit);
template <typename Answer> void serve_with(std::size_t request_limit, const Answer& answer); template <typename Answer> void serve_with(std::size_t request_limit, const Answer& answer);
int fd_; int fd_;
std::uint16_t port_; std::uint16_t port_;
std::size_t response_limit_;
std::vector<Connection> connections_; std::vector<Connection> connections_;
std::uint64_t refused_{}; std::uint64_t refused_{};
}; };
+10 -2
View File
@@ -183,9 +183,12 @@ class RegionSessions {
// A published v10 choice's outcome, to the account's current v10 session if any. // A published v10 choice's outcome, to the account's current v10 session if any.
[[nodiscard]] bool send_mutation_outcome(const network::AccountId& account, [[nodiscard]] bool send_mutation_outcome(const network::AccountId& account,
const network::ActionOutcome& outcome); const network::ActionOutcome& outcome);
// The owner's outstanding offer (11.4d), to the account's current v10 session if any. // The owner's outstanding offer (11.4d), to the account's current v10 session if any. A
// rules-13 catalog offer (`named`) goes only to a v14 session, an operator offer only to
// v10-v13.
[[nodiscard]] bool send_mutation_offer(const network::AccountId& account, [[nodiscard]] bool send_mutation_offer(const network::AccountId& account,
const network::CellularMutationOffer& offer); const network::CellularMutationOffer& offer,
bool named = false);
// 11.8 (ADR-0129): the owner's life ended, with its cause, to its v10 session if any. // 11.8 (ADR-0129): the owner's life ended, with its cause, to its v10 session if any.
[[nodiscard]] bool send_life_ended(const network::AccountId& account, [[nodiscard]] bool send_life_ended(const network::AccountId& account,
const network::CellularLifeEnded& ended); const network::CellularLifeEnded& ended);
@@ -204,6 +207,11 @@ class RegionSessions {
[[nodiscard]] const network::motion::ProbeMarkers& markers() const noexcept; [[nodiscard]] const network::motion::ProbeMarkers& markers() const noexcept;
// Closes every connection with `shutdown` (flushed by later polls). // Closes every connection with `shutdown` (flushed by later polls).
void shutdown(std::chrono::steady_clock::time_point now); void shutdown(std::chrono::steady_clock::time_point now);
// ADR-0087 session window: while closed, every Hello (grant or handoff ticket) is closed
// with `shutdown` before signature work. Open by default; closing does not close the
// connections already open (call shutdown for that).
void set_admission(bool open) noexcept;
[[nodiscard]] bool admitting() const noexcept;
[[nodiscard]] std::vector<RegionSessionEvent> take_events(); [[nodiscard]] std::vector<RegionSessionEvent> take_events();
[[nodiscard]] std::optional<std::uint64_t> holder(const network::AccountId& account) const; [[nodiscard]] std::optional<std::uint64_t> holder(const network::AccountId& account) const;
[[nodiscard]] std::size_t sessions() const noexcept; [[nodiscard]] std::size_t sessions() const noexcept;
+49
View File
@@ -3,6 +3,7 @@
#include <charconv> #include <charconv>
#include <cstdint> #include <cstdint>
#include <expected> #include <expected>
#include <optional>
#include <string> #include <string>
#include <string_view> #include <string_view>
#include <utility> #include <utility>
@@ -67,4 +68,52 @@ class SessionWindow {
bool closed_{}; bool closed_{};
}; };
// ADR-0087 amendment (2026-10-27): the window as the database records it, re-read every few
// seconds. A newer activation replaces the current window (sessions continue); a closed,
// expired, over-long or absent record closes it. Each admitted window keeps its own absolute
// deadline, and a window once closed never reopens: only a newer activation opens sessions
// again. While the database cannot be read the caller does not observe, so the current
// window keeps running to its deadline.
class SessionWindowFeed {
public:
struct Record {
std::string activation_id;
std::optional<std::uint64_t> expires_at; // nullopt: the record closes the window.
};
enum class Change : std::uint8_t { none, opened, closed, refused };
// `record` is the region's newest row, or nullopt when it has none.
Change observe(const std::optional<Record>& record, std::uint64_t now_seconds) {
if (!record) {
const bool had = window_.has_value();
window_.reset();
seen_.clear();
return had ? Change::closed : Change::none;
}
if (record->activation_id == seen_)
return Change::none;
seen_ = record->activation_id;
const bool had = window_.has_value();
window_.reset();
if (!record->expires_at)
return had ? Change::closed : Change::none;
auto opened = SessionWindow::open(
record->activation_id + ":" + std::to_string(*record->expires_at), now_seconds);
if (!opened)
return Change::refused;
window_ = std::move(*opened);
return Change::opened;
}
[[nodiscard]] bool accepting(std::uint64_t now_seconds) noexcept {
return window_ && window_->accepting(now_seconds);
}
[[nodiscard]] const std::optional<SessionWindow>& window() const noexcept {
return window_;
}
private:
std::optional<SessionWindow> window_;
std::string seen_; // The newest activation observed, admitted or not.
};
} // namespace evo::server } // namespace evo::server
+323
View File
@@ -0,0 +1,323 @@
-- Rules 13 (ADR-0179, Cellular_Revamp_Build_Plan.md): raw-only bundle 15 (rules 13 on owner
-- format 11: the cellular revamp) and exact bundle 14 -> 15 upgrades declaring the region's
-- revamp rules. Normalization is parser-local; stored evidence and retries retain real bytes.
-- Raw trace 4 is unchanged except that a bundle-15 mutation selection may set byte 34 (become).
-- The canonical cellular action input: byte 13 bit 1 become (with a bud) and bit 2 emerge (no
-- target); byte 14 the matter channels excluded from burning. Widening cannot invalidate an
-- existing row; earlier inputs keep both zero.
CREATE OR REPLACE FUNCTION evolution.valid_cellular_action_input(p_input bytea, p_tick evolution.u64)
RETURNS boolean LANGUAGE plpgsql IMMUTABLE STRICT
SET search_path = pg_catalog, pg_temp AS $$
BEGIN
IF octet_length(p_input) <> 24 THEN
RETURN false;
END IF;
IF evolution.manifest_uint(p_input, 0, 8) = 0
OR evolution.manifest_uint(p_input, 0, 8) <> p_tick OR get_byte(p_input, 12) > 3
OR get_byte(p_input, 13) > 7 OR get_byte(p_input, 14) > 15 OR get_byte(p_input, 15) <> 0
OR (get_byte(p_input, 13) & 2 <> 0 AND get_byte(p_input, 12) <> 3)
OR (get_byte(p_input, 13) & 4 <> 0 AND get_byte(p_input, 12) <> 0) THEN
RETURN false;
END IF;
IF get_byte(p_input, 12) <> 1 AND substring(p_input FROM 17 FOR 8) <> '\x0000000000000000' THEN
RETURN false;
END IF;
RETURN true;
END $$;
ALTER FUNCTION evolution.parse_checkpoint_manifest(bytea) RENAME TO parse_checkpoint_manifest_v59;
REVOKE ALL ON FUNCTION evolution.parse_checkpoint_manifest_v59(bytea) FROM PUBLIC, :"runtime_role";
CREATE FUNCTION evolution.parse_checkpoint_manifest(m bytea)
RETURNS evolution.checkpoint_manifest LANGUAGE plpgsql IMMUTABLE
SET search_path=pg_catalog,pg_temp AS $$
DECLARE c evolution.checkpoint_manifest;
b14 constant bytea := '\x0c0000000a00000002000000010000000100000006000000050000000200000001000000';
b15 constant bytea := '\x0d0000000b00000002000000010000000100000007000000060000000200000001000000';
BEGIN
IF m IS NOT NULL AND octet_length(m)=360 AND evolution.manifest_uint(m,12,4)=4
AND substring(m FROM 161 FOR 36)=b15 THEN
c := evolution.parse_checkpoint_manifest_v59(overlay(m PLACING b14 FROM 161 FOR 36));
c.versions := b15;
RETURN c;
END IF;
RETURN evolution.parse_checkpoint_manifest_v59(m);
END $$;
REVOKE ALL ON FUNCTION evolution.parse_checkpoint_manifest(bytea) FROM PUBLIC;
ALTER FUNCTION evolution.cellular_births(bytea,bytea) RENAME TO cellular_births_v59;
REVOKE ALL ON FUNCTION evolution.cellular_births_v59(bytea,bytea) FROM PUBLIC, :"runtime_role";
CREATE FUNCTION evolution.cellular_births(t bytea,m bytea)
RETURNS TABLE(account_id uuid,request_id evolution.u64,generation evolution.u64,identity evolution.u64,born evolution.u64)
LANGUAGE plpgsql IMMUTABLE SET search_path=pg_catalog,pg_temp AS $$
DECLARE c evolution.checkpoint_manifest := evolution.parse_checkpoint_manifest(m);
BEGIN
IF c.versions='\x0d0000000b00000002000000010000000100000007000000060000000200000001000000'::bytea THEN
m := overlay(m PLACING '\x0c0000000a00000002000000010000000100000006000000050000000200000001000000'::bytea FROM 161 FOR 36);
END IF;
RETURN QUERY SELECT * FROM evolution.cellular_births_v59(t,m);
END $$;
REVOKE ALL ON FUNCTION evolution.cellular_births(bytea,bytea) FROM PUBLIC;
-- Results 5 split applied and 6 split refused (rules 13).
ALTER TABLE evolution.cellular_mutation_action_publications
DROP CONSTRAINT cellular_mutation_action_publications_result_check;
ALTER TABLE evolution.cellular_mutation_action_publications
ADD CONSTRAINT cellular_mutation_action_publications_result_check CHECK(result BETWEEN 0 AND 6);
-- A bundle-15 selection's byte 34 is its become flag (0 or 1). The returned operator carries
-- it as bit 15, exactly as the reservation input stores it, so the block check compares them.
CREATE OR REPLACE FUNCTION evolution.cellular_mutation_selections(p_trace bytea, p_manifest bytea)
RETURNS TABLE(tick evolution.u64, life_id evolution.u64, event_index evolution.u64,
offer_tick evolution.u64, successor_identity evolution.u64, operator_id integer)
LANGUAGE plpgsql IMMUTABLE SECURITY INVOKER SET search_path = pg_catalog, pg_temp AS $$
DECLARE
c evolution.checkpoint_manifest := evolution.parse_checkpoint_manifest(p_manifest);
revamp boolean := c.versions =
'\x0d0000000b00000002000000010000000100000007000000060000000200000001000000'::bytea;
ticks integer;
off integer := 112;
intent_count integer;
birth_count integer;
mutation_count integer;
previous_life numeric;
become integer;
BEGIN
PERFORM * FROM evolution.cellular_births(p_trace, p_manifest); -- Binding and structure.
IF evolution.manifest_uint(p_trace, 8, 4) NOT IN (3,4) THEN
RETURN; -- Format 2 carries no selections.
END IF;
ticks := (c.end_tick - c.begin_tick)::integer;
FOR tick_index IN 0 .. ticks - 1 LOOP
intent_count := evolution.manifest_uint(p_trace, off, 4)::integer;
birth_count := evolution.manifest_uint(p_trace, off + 4, 4)::integer;
mutation_count := evolution.manifest_uint(p_trace, off + 8, 4)::integer;
off := off + 16 + intent_count * 24 + birth_count * 40;
previous_life := 0;
FOR mutation_index IN 0 .. mutation_count - 1 LOOP
tick := c.begin_tick + tick_index + 1;
life_id := evolution.manifest_uint(p_trace, off, 8);
event_index := evolution.manifest_uint(p_trace, off + 8, 8);
offer_tick := evolution.manifest_uint(p_trace, off + 16, 8);
successor_identity := evolution.manifest_uint(p_trace, off + 24, 8);
operator_id := evolution.manifest_uint(p_trace, off + 32, 2)::integer;
become := get_byte(p_trace, off + 34);
IF life_id = 0 OR life_id <= previous_life OR event_index = 0 OR offer_tick = 0
OR offer_tick >= tick OR successor_identity = 0 OR operator_id >= 32768
OR become > (CASE WHEN revamp THEN 1 ELSE 0 END) OR (become = 1 AND operator_id = 0)
OR substring(p_trace FROM off + 36 FOR 5) <> '\x0000000000' THEN
RAISE EXCEPTION 'invalid cellular mutation selection' USING ERRCODE = '22023';
END IF;
operator_id := operator_id + 32768 * become;
previous_life := life_id;
off := off + 40;
RETURN NEXT;
END LOOP;
END LOOP;
END $$;
-- Schema 59's block check, with bundle 15's results: a decline is life died or declined; a
-- choice is applied (an organism), life died, insufficient funding, split applied or split
-- refused. Only bundle 15 stores become (operator bit 15), and only with a choice.
CREATE OR REPLACE FUNCTION evolution.check_cellular_mutation_block(p_manifest bytea, p_trace bytea,
p_mutations bytea, p_results bytea)
RETURNS integer LANGUAGE plpgsql STABLE SECURITY INVOKER
SET search_path = pg_catalog, pg_temp AS $$
DECLARE
c evolution.checkpoint_manifest := evolution.parse_checkpoint_manifest(p_manifest);
b15 constant bytea := '\x0d0000000b00000002000000010000000100000007000000060000000200000001000000';
n integer;
account uuid;
account_bytes bytea;
action numeric;
tick numeric;
input bytea;
stored integer;
previous_tick numeric := -1;
previous_account bytea := ''::bytea;
previous_action numeric := -1;
applied numeric;
r evolution.cellular_mutation_reservations%ROWTYPE;
BEGIN
IF p_mutations IS NULL OR p_results IS NULL OR octet_length(p_mutations) = 0
OR octet_length(p_mutations) % 64 <> 0 OR octet_length(p_mutations) / 64 > 1024
OR octet_length(p_results) <> octet_length(p_mutations) / 64 THEN
RAISE EXCEPTION 'invalid cellular mutation block' USING ERRCODE = '22023';
END IF;
n := octet_length(p_mutations) / 64;
IF (SELECT count(*) FROM evolution.cellular_mutation_selections(p_trace, p_manifest)) <> n THEN
RAISE EXCEPTION 'cellular mutation block does not cover the trace' USING ERRCODE = '22023';
END IF;
FOR i IN 0 .. n - 1 LOOP
account_bytes := substring(p_mutations FROM 64 * i + 1 FOR 16);
account := encode(account_bytes, 'hex')::uuid;
action := evolution.manifest_uint(p_mutations, 64 * i + 16, 8);
input := substring(p_mutations FROM 64 * i + 25 FOR 34);
tick := evolution.manifest_uint(input, 0, 8);
stored := evolution.manifest_uint(input, 32, 2)::integer;
IF account = '00000000-0000-0000-0000-000000000000' OR action = 0
OR NOT evolution.valid_cellular_mutation_input(input)
OR substring(p_mutations FROM 64 * i + 59 FOR 6) <> '\x000000000000'
OR (c.versions = b15
AND ((stored % 32768 = 0 AND (stored >= 32768 OR get_byte(p_results,i) NOT IN (1,3)))
OR (stored % 32768 <> 0 AND get_byte(p_results,i) NOT IN (0,1,2,5,6))))
OR (c.versions <> b15 AND stored >= 32768)
OR (c.versions IN ('\x0a0000000800000002000000010000000100000004000000030000000200000001000000'::bytea,
'\x0b0000000900000002000000010000000100000005000000040000000200000001000000'::bytea,
'\x0c0000000a00000002000000010000000100000006000000050000000200000001000000'::bytea)
AND (get_byte(p_results,i) NOT IN (1,3,4)
OR (stored=0 AND get_byte(p_results,i) NOT IN (1,3))
OR (stored<>0 AND get_byte(p_results,i) NOT IN (1,4))))
OR (c.versions NOT IN ('\x0a0000000800000002000000010000000100000004000000030000000200000001000000'::bytea,
'\x0b0000000900000002000000010000000100000005000000040000000200000001000000'::bytea,
'\x0c0000000a00000002000000010000000100000006000000050000000200000001000000'::bytea,
b15)
AND get_byte(p_results,i)>3)
OR tick <= c.begin_tick OR tick > c.end_tick
OR (tick, account_bytes, action) <= (previous_tick, previous_account, previous_action) THEN
RAISE EXCEPTION 'invalid cellular mutation record' USING ERRCODE = '22023';
END IF;
previous_tick := tick;
previous_account := account_bytes;
previous_action := action;
SELECT * INTO r FROM evolution.cellular_mutation_reservations x
WHERE x.world_id = c.world_id AND x.account_id = account AND x.action_id = action;
-- The reservation's tick is the earliest the choice may apply at; the record carries
-- the tick it applied at, and the rest of the input must match exactly.
applied := tick;
IF NOT FOUND OR r.region_id <> c.region_id
OR substring(r.input_bytes FROM 9) <> substring(input FROM 9)
OR r.target_tick <> evolution.manifest_uint(r.input_bytes, 0, 8)
OR applied < r.target_tick THEN
RAISE EXCEPTION 'cellular mutation reservation conflicts' USING ERRCODE = 'EVL16';
END IF;
IF NOT EXISTS (SELECT 1 FROM evolution.cellular_mutation_selections(p_trace, p_manifest) s
WHERE s.tick = applied AND s.successor_identity = r.successor_identity
AND s.life_id = evolution.manifest_uint(input, 8, 8)
AND s.event_index = evolution.manifest_uint(input, 16, 8)
AND s.offer_tick = evolution.manifest_uint(input, 24, 8)
AND s.operator_id = stored) THEN
RAISE EXCEPTION 'cellular mutation differs from its trace' USING ERRCODE = '22023';
END IF;
END LOOP;
RETURN n;
END $$;
ALTER FUNCTION evolution.publish_cellular_profile_migration(bytea) RENAME TO publish_cellular_profile_migration_v59;
REVOKE ALL ON FUNCTION evolution.publish_cellular_profile_migration_v59(bytea) FROM PUBLIC, :"runtime_role";
CREATE OR REPLACE FUNCTION evolution.publish_cellular_profile_migration(p_manifest bytea)
RETURNS TABLE(region_frame evolution.u64, head_sequence evolution.u64, head_commit uuid,
head_digest text, head_tick evolution.u64)
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
DECLARE
c evolution.checkpoint_manifest := evolution.parse_checkpoint_manifest(p_manifest);
s evolution.checkpoint_manifest;
h evolution.region_heads%ROWTYPE;
p evolution.region_commits%ROWTYPE;
old evolution.region_commits%ROWTYPE;
frame evolution.u64;
d bytea := sha256(p_manifest);
source_bundle constant bytea := '\x0c0000000a00000002000000010000000100000006000000050000000200000001000000';
target_bundle constant bytea := '\x0d0000000b00000002000000010000000100000007000000060000000200000001000000';
zero32 constant bytea := decode(repeat('00', 32), 'hex');
BEGIN
IF c.versions <> target_bundle THEN
RETURN QUERY SELECT * FROM evolution.publish_cellular_profile_migration_v59(p_manifest);
RETURN;
END IF;
IF c.profile <> 4 OR c.commit_sequence = 0 OR c.begin_tick <> c.end_tick
OR c.end_tick = 0 OR c.versions <> target_bundle
OR evolution.manifest_uint(p_manifest, 228, 4) <> 0
OR evolution.manifest_uint(p_manifest, 232, 4) <> (CASE c.profile WHEN 4 THEN 4 ELSE 5 END)
OR evolution.manifest_uint(p_manifest, 236, 4) <> 1
OR c.trace_bytes <> 0 OR c.trace_sha256 <> zero32
OR c.decision_count <> 0 OR c.decisions_sha256 <> zero32 THEN
RAISE EXCEPTION 'invalid revamp profile migration' USING ERRCODE = '22023';
END IF;
PERFORM evolution.check_region_lease(c.world_id, c.region_id, c.holder, c.epoch);
SELECT * INTO old FROM evolution.region_commits r WHERE r.commit_id = c.commit_id;
IF FOUND THEN
IF old.manifest <> p_manifest THEN
RAISE EXCEPTION 'cellular profile migration identity reused' USING ERRCODE = 'EVL07';
END IF;
SELECT * INTO p FROM evolution.region_commits r
WHERE r.world_id = old.world_id AND r.region_id = old.region_id
AND r.commit_sequence = old.commit_sequence - 1;
IF NOT FOUND OR NOT EXISTS (
SELECT 1 FROM evolution.cellular_profile_migrations m
WHERE m.target_commit = c.commit_id AND m.world_id = c.world_id
AND m.region_id = c.region_id AND m.source_sequence = p.commit_sequence
AND m.source_commit = p.commit_id AND m.source_manifest_sha256 = p.commit_digest
AND m.source_payload_sha256 = p.payload_sha256 AND m.source_versions = p.versions
AND m.target_sequence = old.commit_sequence AND m.target_manifest_sha256 = d
AND m.target_payload_sha256 = old.payload_sha256 AND m.target_versions = old.versions
AND m.source_commit = c.predecessor_commit
AND m.source_manifest_sha256 = c.predecessor_digest) THEN
RAISE EXCEPTION 'cellular profile migration identity reused' USING ERRCODE = 'EVL07';
END IF;
SELECT l.frame_id INTO frame FROM evolution.region_leases l
WHERE l.world_id = c.world_id AND l.region_id = c.region_id;
RETURN QUERY SELECT frame, old.commit_sequence, old.commit_id,
encode(old.commit_digest, 'hex'), old.end_tick;
RETURN;
END IF;
IF EXISTS (SELECT 1 FROM evolution.population_interval_pending x
WHERE x.world_id = c.world_id AND x.region_id = c.region_id) THEN
RAISE EXCEPTION 'revamp upgrade waits for interval' USING ERRCODE = 'EVL18';
END IF;
IF EXISTS (SELECT 1 FROM evolution.cellular_mutation_reservations x
WHERE x.world_id=c.world_id AND x.region_id=c.region_id AND NOT EXISTS
(SELECT 1 FROM evolution.cellular_mutation_action_publications a
WHERE a.world_id=x.world_id AND a.account_id=x.account_id AND a.action_id=x.action_id)) THEN
RAISE EXCEPTION 'revamp upgrade waits for mutation choice' USING ERRCODE='EVL18';
END IF;
SELECT * INTO h FROM evolution.region_heads r
WHERE r.world_id = c.world_id AND r.region_id = c.region_id FOR UPDATE;
IF NOT FOUND OR h.commit_sequence = 18446744073709551615
OR c.commit_sequence <> h.commit_sequence + 1 OR c.predecessor_commit <> h.commit_id
OR c.predecessor_digest <> h.digest OR c.begin_tick <> h.end_tick THEN
RAISE EXCEPTION 'region head moved' USING ERRCODE = 'EVL03';
END IF;
SELECT * INTO p FROM evolution.region_commits r
WHERE r.world_id = c.world_id AND r.region_id = c.region_id
AND r.commit_sequence = h.commit_sequence;
IF NOT FOUND THEN
RAISE EXCEPTION 'missing migration predecessor' USING ERRCODE = 'XX000';
END IF;
s := evolution.parse_checkpoint_manifest(p.manifest);
IF s.profile <> c.profile OR s.versions <> source_bundle OR p.versions <> source_bundle
OR c.frame_id <> s.frame_id OR c.tick_microseconds <> s.tick_microseconds
OR s.commit_id <> c.predecessor_commit OR s.end_tick <> c.end_tick
OR evolution.manifest_uint(p.manifest, 232, 4) <> (CASE c.profile WHEN 4 THEN 4 ELSE 5 END)
OR NOT EXISTS (SELECT 1 FROM evolution.retained_builds b
WHERE b.build_identity = c.build_identity) THEN
RAISE EXCEPTION 'unsupported revamp profile migration' USING ERRCODE = 'EVL06';
END IF;
SELECT l.frame_id INTO frame FROM evolution.region_leases l
WHERE l.world_id = c.world_id AND l.region_id = c.region_id;
IF c.frame_id <> frame THEN
RAISE EXCEPTION 'foreign frame' USING ERRCODE = '22023';
END IF;
INSERT INTO evolution.cellular_profile_migrations(target_commit, world_id, region_id,
source_sequence, source_commit, source_manifest_sha256, source_payload_sha256,
source_versions, target_sequence, target_manifest_sha256, target_payload_sha256,
target_versions)
VALUES (c.commit_id, c.world_id, c.region_id, p.commit_sequence, p.commit_id,
p.commit_digest, p.payload_sha256, p.versions, c.commit_sequence, d,
c.payload_sha256, c.versions);
INSERT INTO evolution.region_commits(world_id, region_id, commit_sequence, commit_id,
commit_digest, manifest, begin_tick, end_tick, published_epoch, tick_microseconds,
versions, build_identity, payload_bytes, payload_sha256)
VALUES (c.world_id, c.region_id, c.commit_sequence, c.commit_id, d, p_manifest,
c.begin_tick, c.end_tick, c.epoch, c.tick_microseconds, c.versions,
c.build_identity, c.payload_bytes, c.payload_sha256);
UPDATE evolution.region_heads r
SET commit_sequence = c.commit_sequence, commit_id = c.commit_id, digest = d,
end_tick = c.end_tick, published_epoch = c.epoch
WHERE r.world_id = c.world_id AND r.region_id = c.region_id;
RETURN QUERY SELECT frame, c.commit_sequence, c.commit_id, encode(d, 'hex'), c.end_tick;
END $$;
REVOKE ALL ON FUNCTION evolution.publish_cellular_profile_migration(bytea) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION evolution.publish_cellular_profile_migration(bytea) TO :"runtime_role";
INSERT INTO evolution.schema_migrations(version,sha256) VALUES(60,:'migration_sha_60');
+82
View File
@@ -0,0 +1,82 @@
-- Admin portal read views (ADR-0182, 2026-10-27). Three read-only, bounded SECURITY DEFINER
-- functions for the DEV admin API: a world's accounts with their lives and session control,
-- one account's lives, and a world's regions with their heads. Nothing is written; no table,
-- row, constraint or existing function changes. The runtime group may execute them; DEV's
-- admin API logs in within that group, as the grant broker does (ADR-0131).
-- Every account known to the world: Keycloak identities and accounts that reserved a life.
-- A life is a published, unrefused reservation; a death is an ended one. The control row is
-- the account's session claim (region and expiry), as the region last renewed it.
CREATE FUNCTION evolution.admin_accounts_v1(p_world evolution.u64)
RETURNS TABLE (account_id uuid, created_at timestamptz, issuer text, subject text,
control_region evolution.u64, control_expires timestamptz, lives bigint, deaths bigint,
active_life evolution.u64, active_region evolution.u64, mutation_choices bigint)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
WITH accounts AS (
SELECT i.account_id FROM evolution.account_identities i
UNION
SELECT r.account_id FROM evolution.life_reservations r WHERE r.world_id = p_world
), lives AS (
SELECT r.account_id, r.identity, r.region_id, r.request_id, r.ended_commit
FROM evolution.life_reservations r
JOIN evolution.primitive_life_bindings b ON b.world_id = r.world_id
AND b.account_id = r.account_id AND b.request_id = r.request_id
WHERE r.world_id = p_world AND r.rejection = 0
)
SELECT a.account_id, i.created_at, i.issuer, i.subject, c.region_id, c.expires_at,
(SELECT count(*) FROM lives l WHERE l.account_id = a.account_id),
(SELECT count(*) FROM lives l WHERE l.account_id = a.account_id
AND l.ended_commit IS NOT NULL),
active.identity, active.region_id,
(SELECT count(*) FROM evolution.cellular_mutation_reservations m
WHERE m.world_id = p_world AND m.account_id = a.account_id)
FROM accounts a
LEFT JOIN evolution.account_identities i ON i.account_id = a.account_id
LEFT JOIN evolution.account_controls c ON c.world_id = p_world AND c.account_id = a.account_id
LEFT JOIN LATERAL (SELECT l.identity, l.region_id FROM lives l
WHERE l.account_id = a.account_id AND l.ended_commit IS NULL
ORDER BY l.request_id DESC LIMIT 1) active ON true
ORDER BY i.created_at NULLS LAST, a.account_id
LIMIT 10000
$$;
REVOKE ALL ON FUNCTION evolution.admin_accounts_v1(evolution.u64) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION evolution.admin_accounts_v1(evolution.u64) TO :"runtime_role";
-- One account's life requests in order: published or not, refused or not, and when an
-- ended life's commit was published (its last tick and time).
CREATE FUNCTION evolution.admin_account_lives_v1(p_world evolution.u64, p_account uuid)
RETURNS TABLE (request_id evolution.u64, identity evolution.u64, region_id evolution.u64,
rejection smallint, born evolution.u64, ended_tick evolution.u64, ended_at timestamptz)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT r.request_id, r.identity, r.region_id, r.rejection, b.born, e.end_tick, e.committed_at
FROM evolution.life_reservations r
LEFT JOIN evolution.primitive_life_bindings b ON b.world_id = r.world_id
AND b.account_id = r.account_id AND b.request_id = r.request_id
LEFT JOIN evolution.region_commits e ON e.commit_id = r.ended_commit
WHERE r.world_id = p_world AND r.account_id = p_account
ORDER BY r.request_id
LIMIT 1000
$$;
REVOKE ALL ON FUNCTION evolution.admin_account_lives_v1(evolution.u64, uuid) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION evolution.admin_account_lives_v1(evolution.u64, uuid)
TO :"runtime_role";
-- A world's regions: lease (epoch, whether held and until when) and the head commit.
CREATE FUNCTION evolution.admin_regions_v1(p_world evolution.u64)
RETURNS TABLE (region_id evolution.u64, frame_id evolution.u64, lease_epoch evolution.u64,
lease_held boolean, lease_expires timestamptz, commit_sequence evolution.u64,
end_tick evolution.u64, committed_at timestamptz, build_identity text)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT l.region_id, l.frame_id, l.epoch, l.holder IS NOT NULL, l.expires_at,
h.commit_sequence, h.end_tick, c.committed_at, encode(c.build_identity, 'hex')
FROM evolution.region_leases l
LEFT JOIN evolution.region_heads h ON h.world_id = l.world_id AND h.region_id = l.region_id
LEFT JOIN evolution.region_commits c ON c.commit_id = h.commit_id
WHERE l.world_id = p_world
ORDER BY l.region_id
LIMIT 1000
$$;
REVOKE ALL ON FUNCTION evolution.admin_regions_v1(evolution.u64) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION evolution.admin_regions_v1(evolution.u64) TO :"runtime_role";
INSERT INTO evolution.schema_migrations(version,sha256) VALUES(61,:'migration_sha_61');
+97
View File
@@ -0,0 +1,97 @@
-- Session windows in SQL (ADR-0087 amendment and ADR-0182, 2026-10-27). A region's dev
-- session window is the newest row of an append-only table instead of a Git-committed
-- environment value: the admin portal opens, extends and closes it, and the region reads it
-- every few seconds. A row with an expiry opens (or replaces) the window until then, at most
-- four hours after it was written; a row without one closes it. Rows are never changed.
--
-- The admin functions move to a dedicated group role: schema 61's read views are revoked
-- from the runtime group, and apply.sql grants every admin function to :admin_role on each
-- run when that role is configured. The runtime group may only read the current window.
CREATE TABLE evolution.session_windows (
world_id evolution.u64 NOT NULL,
region_id evolution.u64 NOT NULL,
sequence bigint GENERATED ALWAYS AS IDENTITY,
activation_id text NOT NULL UNIQUE CHECK (activation_id ~ '^[A-Za-z0-9._-]{1,64}$'),
expires_at timestamptz,
author_subject text NOT NULL CHECK (octet_length(author_subject) BETWEEN 1 AND 255),
reason text NOT NULL DEFAULT '' CHECK (octet_length(reason) <= 500),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
PRIMARY KEY (world_id, region_id, sequence),
FOREIGN KEY (world_id, region_id) REFERENCES evolution.region_leases,
CHECK (expires_at IS NULL OR
(expires_at > created_at AND expires_at <= created_at + interval '4 hours'))
);
CREATE TRIGGER session_windows_immutable BEFORE UPDATE OR DELETE ON evolution.session_windows
FOR EACH ROW EXECUTE FUNCTION evolution.refuse_history_rewrite();
CREATE TRIGGER session_windows_no_truncate BEFORE TRUNCATE ON evolution.session_windows
FOR EACH STATEMENT EXECUTE FUNCTION evolution.refuse_history_rewrite();
-- The region's current window: its newest row, or nothing when none was ever written.
CREATE FUNCTION evolution.load_session_window_v1(p_world evolution.u64, p_region evolution.u64)
RETURNS TABLE (activation_id text, expires_at timestamptz, author_subject text,
created_at timestamptz)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT w.activation_id, w.expires_at, w.author_subject, w.created_at
FROM evolution.session_windows w
WHERE w.world_id = p_world AND w.region_id = p_region
ORDER BY w.sequence DESC
LIMIT 1
$$;
REVOKE ALL ON FUNCTION evolution.load_session_window_v1(evolution.u64, evolution.u64) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION evolution.load_session_window_v1(evolution.u64, evolution.u64)
TO :"runtime_role";
-- Opens or extends (1..14400 seconds from now, a new activation) or closes (0 seconds) the
-- region's window, recording who and why. Returns the row written.
CREATE FUNCTION evolution.admin_set_session_window_v1(p_world evolution.u64,
p_region evolution.u64, p_seconds integer, p_subject text, p_reason text)
RETURNS TABLE (activation_id text, expires_at timestamptz)
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
#variable_conflict use_column
DECLARE
now_at timestamptz := clock_timestamp();
id text := 'adm-' || to_char(now_at AT TIME ZONE 'UTC', 'YYYYMMDD"T"HH24MISS') || '-'
|| substr(replace(gen_random_uuid()::text, '-', ''), 1, 8);
BEGIN
IF p_seconds IS NULL OR p_seconds < 0 OR p_seconds > 14400 THEN
RAISE EXCEPTION 'session window duration out of range' USING ERRCODE = '22023';
END IF;
IF NOT EXISTS (SELECT 1 FROM evolution.region_leases l
WHERE l.world_id = p_world AND l.region_id = p_region) THEN
RAISE EXCEPTION 'unknown region' USING ERRCODE = '22023';
END IF;
RETURN QUERY
WITH written AS (
INSERT INTO evolution.session_windows AS w(world_id, region_id, activation_id, expires_at,
author_subject, reason, created_at)
VALUES (p_world, p_region, id,
CASE WHEN p_seconds = 0 THEN NULL ELSE now_at + make_interval(secs => p_seconds) END,
p_subject, coalesce(p_reason, ''), now_at)
RETURNING w.activation_id, w.expires_at)
SELECT written.activation_id, written.expires_at FROM written;
END $$;
REVOKE ALL ON FUNCTION evolution.admin_set_session_window_v1(evolution.u64, evolution.u64,
integer, text, text) FROM PUBLIC;
-- The region's last 50 window changes, newest first.
CREATE FUNCTION evolution.admin_session_windows_v1(p_world evolution.u64, p_region evolution.u64)
RETURNS TABLE (sequence bigint, activation_id text, expires_at timestamptz,
author_subject text, reason text, created_at timestamptz)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT w.sequence, w.activation_id, w.expires_at, w.author_subject, w.reason, w.created_at
FROM evolution.session_windows w
WHERE w.world_id = p_world AND w.region_id = p_region
ORDER BY w.sequence DESC
LIMIT 50
$$;
REVOKE ALL ON FUNCTION evolution.admin_session_windows_v1(evolution.u64, evolution.u64)
FROM PUBLIC;
-- Schema 61's read views belong to the admin role from now on.
REVOKE EXECUTE ON FUNCTION evolution.admin_accounts_v1(evolution.u64) FROM :"runtime_role";
REVOKE EXECUTE ON FUNCTION evolution.admin_account_lives_v1(evolution.u64, uuid)
FROM :"runtime_role";
REVOKE EXECUTE ON FUNCTION evolution.admin_regions_v1(evolution.u64) FROM :"runtime_role";
INSERT INTO evolution.schema_migrations(version,sha256) VALUES(62,:'migration_sha_62');
+341
View File
@@ -0,0 +1,341 @@
-- Admin commands (ADR-0182, 2026-10-27). The admin portal queues operator commands for a
-- region: remove a cell, grant a reserve, add bubbles, add to or release the spent pool, and
-- spawn wildlife. The region applies each once, after a tick's births, and records it in the
-- trace (format 5: trace 4 plus 64-byte command records counted in the tick header's last
-- word), so replay and recovery reproduce it. Publication binds every recorded command to
-- its queue row exactly once. A bundle-15 trace without commands stays trace 4; the existing
-- parsers read a trace 5 through its trace-4 normal form, so nothing else changes.
-- u64 values as little-endian bytes.
CREATE FUNCTION evolution.le_bytes(v numeric, n integer)
RETURNS bytea LANGUAGE plpgsql IMMUTABLE SET search_path = pg_catalog, pg_temp AS $$
DECLARE out bytea := ''::bytea; x numeric := v;
BEGIN
FOR i IN 1 .. n LOOP
out := out || set_byte('\x00'::bytea, 0, (x % 256)::integer);
x := floor(x / 256);
END LOOP;
RETURN out;
END $$;
REVOKE ALL ON FUNCTION evolution.le_bytes(numeric, integer) FROM PUBLIC;
-- The trace-4 normal form of a trace 5: version 4, command counts zero, records dropped.
CREATE FUNCTION evolution.cellular_trace_without_admin(t bytea)
RETURNS bytea LANGUAGE plpgsql IMMUTABLE SET search_path = pg_catalog, pg_temp AS $$
DECLARE
ticks integer;
off integer := 112;
out bytea;
records integer;
admin integer;
BEGIN
IF t IS NULL OR octet_length(t) < 112 OR evolution.manifest_uint(t, 8, 4) <> 5 THEN
RETURN t;
END IF;
ticks := evolution.manifest_uint(t, 104, 4)::integer;
out := overlay(substring(t FROM 1 FOR 112) PLACING '\x04000000'::bytea FROM 9 FOR 4);
FOR i IN 1 .. ticks LOOP
IF octet_length(t) < off + 16 THEN
RAISE EXCEPTION 'invalid admin trace' USING ERRCODE = '22023';
END IF;
records := evolution.manifest_uint(t, off, 4)::integer * 24
+ evolution.manifest_uint(t, off + 4, 4)::integer * 40
+ evolution.manifest_uint(t, off + 8, 4)::integer * 40;
admin := evolution.manifest_uint(t, off + 12, 4)::integer;
IF admin > 16 OR octet_length(t) < off + 16 + records + admin * 64 THEN
RAISE EXCEPTION 'invalid admin trace' USING ERRCODE = '22023';
END IF;
out := out || substring(t FROM off + 1 FOR 12) || '\x00000000'::bytea
|| substring(t FROM off + 17 FOR records);
off := off + 16 + records + admin * 64;
END LOOP;
IF off <> octet_length(t) THEN
RAISE EXCEPTION 'invalid admin trace' USING ERRCODE = '22023';
END IF;
RETURN out;
END $$;
REVOKE ALL ON FUNCTION evolution.cellular_trace_without_admin(bytea) FROM PUBLIC;
-- A trace 5's command records with the tick each applies at, in trace order.
CREATE FUNCTION evolution.cellular_trace_admin(t bytea, m bytea)
RETURNS TABLE (tick evolution.u64, command_id bigint, kind integer, cell_count integer,
target evolution.u64, energy evolution.u64, carbon evolution.u64, nitrogen evolution.u64,
phosphorus evolution.u64, other evolution.u64)
LANGUAGE plpgsql IMMUTABLE SET search_path = pg_catalog, pg_temp AS $$
DECLARE
c evolution.checkpoint_manifest := evolution.parse_checkpoint_manifest(m);
ticks integer;
off integer := 112;
records integer;
admin integer;
previous numeric;
BEGIN
IF t IS NULL OR octet_length(t) < 112 OR evolution.manifest_uint(t, 8, 4) <> 5 THEN
RETURN;
END IF;
ticks := evolution.manifest_uint(t, 104, 4)::integer;
FOR tick_index IN 0 .. ticks - 1 LOOP
records := evolution.manifest_uint(t, off, 4)::integer * 24
+ evolution.manifest_uint(t, off + 4, 4)::integer * 40
+ evolution.manifest_uint(t, off + 8, 4)::integer * 40;
admin := evolution.manifest_uint(t, off + 12, 4)::integer;
off := off + 16 + records;
previous := 0;
FOR i IN 1 .. admin LOOP
tick := c.begin_tick + tick_index + 1;
command_id := evolution.manifest_uint(t, off, 8)::bigint;
kind := evolution.manifest_uint(t, off + 8, 2)::integer;
cell_count := evolution.manifest_uint(t, off + 10, 2)::integer;
target := evolution.manifest_uint(t, off + 16, 8);
energy := evolution.manifest_uint(t, off + 24, 8);
carbon := evolution.manifest_uint(t, off + 32, 8);
nitrogen := evolution.manifest_uint(t, off + 40, 8);
phosphorus := evolution.manifest_uint(t, off + 48, 8);
other := evolution.manifest_uint(t, off + 56, 8);
IF command_id <= previous OR substring(t FROM off + 13 FOR 4) <> '\x00000000'::bytea THEN
RAISE EXCEPTION 'invalid admin trace' USING ERRCODE = '22023';
END IF;
previous := command_id;
off := off + 64;
RETURN NEXT;
END LOOP;
END LOOP;
END $$;
REVOKE ALL ON FUNCTION evolution.cellular_trace_admin(bytea, bytea) FROM PUBLIC;
-- The trace parsers read a bundle-15 trace 5 through its normal form, after binding the real
-- trace to the manifest (as schema 55 did for retained plans).
CREATE FUNCTION evolution.cellular_trace_normal(INOUT t bytea, INOUT m bytea)
LANGUAGE plpgsql IMMUTABLE SET search_path = pg_catalog, pg_temp AS $$
DECLARE
c evolution.checkpoint_manifest := evolution.parse_checkpoint_manifest(m);
b15 constant bytea := '\x0d0000000b00000002000000010000000100000007000000060000000200000001000000';
BEGIN
IF t IS NULL OR octet_length(t) < 12 OR evolution.manifest_uint(t, 8, 4) <> 5 THEN
RETURN;
END IF;
IF c.versions <> b15 OR octet_length(t) <> c.trace_bytes OR sha256(t) <> c.trace_sha256 THEN
RAISE EXCEPTION 'invalid admin trace binding' USING ERRCODE = '22023';
END IF;
t := evolution.cellular_trace_without_admin(t);
m := overlay(m PLACING evolution.le_bytes(octet_length(t), 8) FROM 281 FOR 8);
m := overlay(m PLACING sha256(t) FROM 289 FOR 32);
END $$;
REVOKE ALL ON FUNCTION evolution.cellular_trace_normal(bytea, bytea) FROM PUBLIC;
ALTER FUNCTION evolution.cellular_births(bytea,bytea) RENAME TO cellular_births_v62;
REVOKE ALL ON FUNCTION evolution.cellular_births_v62(bytea,bytea) FROM PUBLIC, :"runtime_role";
CREATE FUNCTION evolution.cellular_births(t bytea, m bytea)
RETURNS TABLE(account_id uuid, request_id evolution.u64, generation evolution.u64,
identity evolution.u64, born evolution.u64)
LANGUAGE plpgsql IMMUTABLE SET search_path = pg_catalog, pg_temp AS $$
DECLARE n record := evolution.cellular_trace_normal(t, m);
BEGIN
RETURN QUERY SELECT * FROM evolution.cellular_births_v62(n.t, n.m);
END $$;
REVOKE ALL ON FUNCTION evolution.cellular_births(bytea,bytea) FROM PUBLIC;
ALTER FUNCTION evolution.cellular_mutation_selections(bytea,bytea)
RENAME TO cellular_mutation_selections_v62;
REVOKE ALL ON FUNCTION evolution.cellular_mutation_selections_v62(bytea,bytea)
FROM PUBLIC, :"runtime_role";
CREATE FUNCTION evolution.cellular_mutation_selections(p_trace bytea, p_manifest bytea)
RETURNS TABLE (tick evolution.u64, life_id evolution.u64, event_index evolution.u64,
offer_tick evolution.u64, successor_identity evolution.u64, operator_id integer)
LANGUAGE plpgsql IMMUTABLE SECURITY INVOKER SET search_path = pg_catalog, pg_temp AS $$
DECLARE n record := evolution.cellular_trace_normal(p_trace, p_manifest);
BEGIN
RETURN QUERY SELECT * FROM evolution.cellular_mutation_selections_v62(n.t, n.m);
END $$;
REVOKE ALL ON FUNCTION evolution.cellular_mutation_selections(bytea,bytea) FROM PUBLIC;
-- The queue. A row is the operator's exact command; its application is recorded separately.
CREATE TABLE evolution.admin_commands (
command_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
world_id evolution.u64 NOT NULL,
region_id evolution.u64 NOT NULL,
kind smallint NOT NULL CHECK (kind BETWEEN 1 AND 6),
cell_count integer NOT NULL CHECK (cell_count BETWEEN 0 AND 256),
target evolution.u64 NOT NULL,
energy evolution.u64 NOT NULL,
carbon evolution.u64 NOT NULL,
nitrogen evolution.u64 NOT NULL,
phosphorus evolution.u64 NOT NULL,
other evolution.u64 NOT NULL,
author_subject text NOT NULL CHECK (octet_length(author_subject) BETWEEN 1 AND 255),
reason text NOT NULL DEFAULT '' CHECK (octet_length(reason) <= 500),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
FOREIGN KEY (world_id, region_id) REFERENCES evolution.region_leases
);
CREATE TRIGGER admin_commands_immutable BEFORE UPDATE OR DELETE ON evolution.admin_commands
FOR EACH ROW EXECUTE FUNCTION evolution.refuse_history_rewrite();
CREATE TRIGGER admin_commands_no_truncate BEFORE TRUNCATE ON evolution.admin_commands
FOR EACH STATEMENT EXECUTE FUNCTION evolution.refuse_history_rewrite();
CREATE TABLE evolution.admin_command_applications (
command_id bigint PRIMARY KEY REFERENCES evolution.admin_commands,
commit_id uuid NOT NULL,
commit_sequence evolution.u64 NOT NULL,
tick evolution.u64 NOT NULL
);
CREATE TRIGGER admin_command_applications_immutable BEFORE UPDATE OR DELETE
ON evolution.admin_command_applications
FOR EACH ROW EXECUTE FUNCTION evolution.refuse_history_rewrite();
-- Queues a command (the same shapes the owner accepts). Spawning takes its identities from the
-- world's life allocator, so they never meet a player's.
CREATE FUNCTION evolution.admin_enqueue_command_v1(p_world evolution.u64, p_region evolution.u64,
p_kind integer, p_count integer, p_target evolution.u64, p_energy evolution.u64,
p_carbon evolution.u64, p_nitrogen evolution.u64, p_phosphorus evolution.u64,
p_other evolution.u64, p_subject text, p_reason text)
RETURNS TABLE (command_id bigint, target evolution.u64)
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
#variable_conflict use_column
DECLARE
has_amount boolean := p_energy + p_carbon + p_nitrogen + p_phosphorus + p_other > 0;
first numeric := p_target;
BEGIN
IF NOT ((p_kind IN (1, 2) AND p_target > 0 AND p_count = 0 AND has_amount = (p_kind = 2))
OR (p_kind IN (3, 5) AND p_target = 0 AND p_count BETWEEN 1 AND 256 AND has_amount)
OR (p_kind = 4 AND p_target = 0 AND p_count = 0 AND has_amount)
OR (p_kind = 6 AND p_count BETWEEN 1 AND 64 AND NOT has_amount)) THEN
RAISE EXCEPTION 'invalid admin command' USING ERRCODE = '22023';
END IF;
IF NOT EXISTS (SELECT 1 FROM evolution.region_leases l
WHERE l.world_id = p_world AND l.region_id = p_region) THEN
RAISE EXCEPTION 'unknown region' USING ERRCODE = '22023';
END IF;
IF p_kind = 6 THEN
SELECT a.next_identity INTO first FROM evolution.life_allocators a
WHERE a.world_id = p_world FOR UPDATE;
IF first IS NULL OR first + p_count > 9223372036854775808 THEN
RAISE EXCEPTION 'no identities for wildlife' USING ERRCODE = '22023';
END IF;
UPDATE evolution.life_allocators SET next_identity = first + p_count
WHERE world_id = p_world;
END IF;
RETURN QUERY
WITH queued AS (
INSERT INTO evolution.admin_commands AS q(world_id, region_id, kind, cell_count, target,
energy, carbon, nitrogen, phosphorus, other, author_subject, reason)
VALUES (p_world, p_region, p_kind, p_count, first, p_energy, p_carbon, p_nitrogen,
p_phosphorus, p_other, p_subject, coalesce(p_reason, ''))
RETURNING q.command_id, q.target)
SELECT queued.command_id, queued.target FROM queued;
END $$;
REVOKE ALL ON FUNCTION evolution.admin_enqueue_command_v1(evolution.u64, evolution.u64, integer,
integer, evolution.u64, evolution.u64, evolution.u64, evolution.u64, evolution.u64,
evolution.u64, text, text) FROM PUBLIC;
-- The region's commands not yet published, oldest first.
CREATE FUNCTION evolution.load_pending_admin_commands_v1(p_world evolution.u64,
p_region evolution.u64)
RETURNS TABLE (command_id bigint, kind integer, cell_count integer, target evolution.u64,
energy evolution.u64, carbon evolution.u64, nitrogen evolution.u64, phosphorus evolution.u64,
other evolution.u64)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT q.command_id, q.kind, q.cell_count, q.target, q.energy, q.carbon, q.nitrogen,
q.phosphorus, q.other
FROM evolution.admin_commands q
WHERE q.world_id = p_world AND q.region_id = p_region
AND NOT EXISTS (SELECT 1 FROM evolution.admin_command_applications a
WHERE a.command_id = q.command_id)
ORDER BY q.command_id
LIMIT 64
$$;
REVOKE ALL ON FUNCTION evolution.load_pending_admin_commands_v1(evolution.u64, evolution.u64)
FROM PUBLIC;
GRANT EXECUTE ON FUNCTION evolution.load_pending_admin_commands_v1(evolution.u64, evolution.u64)
TO :"runtime_role";
-- The region's last 100 commands, newest first, with the tick each applied at.
CREATE FUNCTION evolution.admin_commands_v1(p_world evolution.u64, p_region evolution.u64)
RETURNS TABLE (command_id bigint, kind integer, cell_count integer, target evolution.u64,
energy evolution.u64, carbon evolution.u64, nitrogen evolution.u64, phosphorus evolution.u64,
other evolution.u64, author_subject text, reason text, created_at timestamptz,
applied_tick evolution.u64)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT q.command_id, q.kind, q.cell_count, q.target, q.energy, q.carbon, q.nitrogen,
q.phosphorus, q.other, q.author_subject, q.reason, q.created_at, a.tick
FROM evolution.admin_commands q
LEFT JOIN evolution.admin_command_applications a ON a.command_id = q.command_id
WHERE q.world_id = p_world AND q.region_id = p_region
ORDER BY q.command_id DESC
LIMIT 100
$$;
REVOKE ALL ON FUNCTION evolution.admin_commands_v1(evolution.u64, evolution.u64) FROM PUBLIC;
-- Every command recorded in a published trace is exactly its queue row and applies once.
CREATE FUNCTION evolution.bind_cellular_admin_commands(p_manifest bytea, p_trace bytea)
RETURNS void LANGUAGE plpgsql SECURITY INVOKER SET search_path = pg_catalog, pg_temp AS $$
DECLARE
c evolution.checkpoint_manifest := evolution.parse_checkpoint_manifest(p_manifest);
r record;
BEGIN
FOR r IN SELECT * FROM evolution.cellular_trace_admin(p_trace, p_manifest) LOOP
IF NOT EXISTS (SELECT 1 FROM evolution.admin_commands q
WHERE q.command_id = r.command_id AND q.world_id = c.world_id
AND q.region_id = c.region_id AND q.kind = r.kind AND q.cell_count = r.cell_count
AND q.target = r.target AND q.energy = r.energy AND q.carbon = r.carbon
AND q.nitrogen = r.nitrogen AND q.phosphorus = r.phosphorus AND q.other = r.other) THEN
RAISE EXCEPTION 'admin command differs from its queue' USING ERRCODE = '22023';
END IF;
IF EXISTS (SELECT 1 FROM evolution.admin_command_applications a
WHERE a.command_id = r.command_id AND (a.commit_id <> c.commit_id OR a.tick <> r.tick)) THEN
RAISE EXCEPTION 'admin command already applied' USING ERRCODE = 'EVL07';
END IF;
INSERT INTO evolution.admin_command_applications(command_id, commit_id, commit_sequence, tick)
VALUES (r.command_id, c.commit_id, c.commit_sequence, r.tick)
ON CONFLICT (command_id) DO NOTHING;
END LOOP;
END $$;
REVOKE ALL ON FUNCTION evolution.bind_cellular_admin_commands(bytea, bytea) FROM PUBLIC;
-- Schema 59's publishers, binding admin commands in the same transaction.
ALTER FUNCTION evolution.publish_cellular_checkpoint(bytea,bytea,bytea,bytea)
RENAME TO publish_cellular_checkpoint_v62;
REVOKE ALL ON FUNCTION evolution.publish_cellular_checkpoint_v62(bytea,bytea,bytea,bytea)
FROM PUBLIC, :"runtime_role";
CREATE FUNCTION evolution.publish_cellular_checkpoint(p_manifest bytea, p_decisions bytea,
p_actions bytea, p_trace bytea)
RETURNS TABLE(region_frame evolution.u64, head_sequence evolution.u64, head_commit uuid,
head_digest text, head_tick evolution.u64)
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
DECLARE h record;
BEGIN
SELECT * INTO h FROM evolution.publish_cellular_checkpoint_v62(p_manifest, p_decisions,
p_actions, p_trace);
IF NOT FOUND THEN
RAISE EXCEPTION 'publication returned no head' USING ERRCODE = 'XX000';
END IF;
PERFORM evolution.bind_cellular_admin_commands(p_manifest, p_trace);
RETURN QUERY SELECT h.region_frame, h.head_sequence, h.head_commit, h.head_digest, h.head_tick;
END $$;
REVOKE ALL ON FUNCTION evolution.publish_cellular_checkpoint(bytea,bytea,bytea,bytea) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION evolution.publish_cellular_checkpoint(bytea,bytea,bytea,bytea)
TO :"runtime_role";
ALTER FUNCTION evolution.publish_cellular_mutation_checkpoint(bytea,bytea,bytea,bytea,bytea,bytea)
RENAME TO publish_cellular_mutation_checkpoint_v62;
REVOKE ALL ON FUNCTION evolution.publish_cellular_mutation_checkpoint_v62(bytea,bytea,bytea,bytea,
bytea,bytea) FROM PUBLIC, :"runtime_role";
CREATE FUNCTION evolution.publish_cellular_mutation_checkpoint(p_manifest bytea,
p_decisions bytea, p_actions bytea, p_trace bytea, p_mutations bytea, p_results bytea)
RETURNS TABLE(region_frame evolution.u64, head_sequence evolution.u64, head_commit uuid,
head_digest text, head_tick evolution.u64)
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
DECLARE h record;
BEGIN
SELECT * INTO h FROM evolution.publish_cellular_mutation_checkpoint_v62(p_manifest,
p_decisions, p_actions, p_trace, p_mutations, p_results);
IF NOT FOUND THEN
RAISE EXCEPTION 'publication returned no head' USING ERRCODE = 'XX000';
END IF;
PERFORM evolution.bind_cellular_admin_commands(p_manifest, p_trace);
RETURN QUERY SELECT h.region_frame, h.head_sequence, h.head_commit, h.head_digest, h.head_tick;
END $$;
REVOKE ALL ON FUNCTION evolution.publish_cellular_mutation_checkpoint(bytea,bytea,bytea,bytea,
bytea,bytea) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION evolution.publish_cellular_mutation_checkpoint(bytea,bytea,bytea,bytea,
bytea,bytea) TO :"runtime_role";
INSERT INTO evolution.schema_migrations(version,sha256) VALUES(63,:'migration_sha_63');
+223
View File
@@ -0,0 +1,223 @@
-- Account administration (ADR-0182 section 6, 2026-10-27): bans, an admin logout and time
-- played. A ban is an append-only row; the newest row per account decides. A banned account
-- gets no grant (SQLSTATE EVL20, which the broker reports as account_banned), and banning
-- also revokes its grants, so a live session closes at its next control renewal. Session
-- intervals are recorded by the session-control functions the regions already call: a claim
-- opens one, a renewal moves its last-seen time, a release closes it. A session that is
-- never released ends at its last renewal.
CREATE TABLE evolution.account_bans (
sequence bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
account_id uuid NOT NULL,
banned boolean NOT NULL,
author_subject text NOT NULL CHECK (octet_length(author_subject) BETWEEN 1 AND 255),
reason text NOT NULL DEFAULT '' CHECK (octet_length(reason) <= 500),
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE INDEX account_bans_by_account ON evolution.account_bans(account_id, sequence);
CREATE TRIGGER account_bans_immutable BEFORE UPDATE OR DELETE ON evolution.account_bans
FOR EACH ROW EXECUTE FUNCTION evolution.refuse_history_rewrite();
CREATE TABLE evolution.session_intervals (
world_id evolution.u64 NOT NULL,
account_id uuid NOT NULL,
generation evolution.u64 NOT NULL,
region_id evolution.u64 NOT NULL,
started_at timestamptz NOT NULL,
last_seen timestamptz NOT NULL,
ended_at timestamptz,
PRIMARY KEY (world_id, account_id, generation)
);
CREATE FUNCTION evolution.account_banned(p_account uuid)
RETURNS boolean LANGUAGE sql STABLE SET search_path = pg_catalog, pg_temp AS $$
SELECT coalesce((SELECT b.banned FROM evolution.account_bans b
WHERE b.account_id = p_account ORDER BY b.sequence DESC LIMIT 1), false)
$$;
REVOKE ALL ON FUNCTION evolution.account_banned(uuid) FROM PUBLIC;
-- Raises the account's accepted serial past every grant issued and expires its control, as
-- revoke_account_grants does for a Keycloak identity.
CREATE FUNCTION evolution.revoke_account_by_id(p_world evolution.u64, p_account uuid)
RETURNS boolean LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp AS $$
DECLARE r evolution.account_identities%ROWTYPE;
BEGIN
SELECT * INTO r FROM evolution.account_identities x WHERE x.account_id = p_account FOR UPDATE;
IF NOT FOUND THEN
UPDATE evolution.account_controls a
SET expires_at = CASE WHEN a.region_id IS NULL THEN NULL
ELSE least(a.expires_at, clock_timestamp()) END
WHERE a.world_id = p_world AND a.account_id = p_account;
RETURN FOUND;
END IF;
INSERT INTO evolution.account_controls AS a (world_id, account_id, serial, generation)
VALUES (p_world, r.account_id, greatest(r.last_serial, 1), 1)
ON CONFLICT (world_id, account_id) DO UPDATE
SET serial = greatest(a.serial, EXCLUDED.serial),
expires_at = CASE WHEN a.region_id IS NULL THEN NULL
ELSE least(a.expires_at, clock_timestamp()) END;
RETURN true;
END $$;
REVOKE ALL ON FUNCTION evolution.revoke_account_by_id(evolution.u64, uuid) FROM PUBLIC;
-- Admin: ban or lift a ban (recorded with who and why); a ban also logs the account out.
CREATE FUNCTION evolution.admin_set_account_ban_v1(p_world evolution.u64, p_account uuid,
p_banned boolean, p_subject text, p_reason text)
RETURNS boolean LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
BEGIN
IF p_world IS NULL OR p_world = 0 OR p_account IS NULL OR p_banned IS NULL THEN
RAISE EXCEPTION 'invalid ban' USING ERRCODE = '22023';
END IF;
INSERT INTO evolution.account_bans(account_id, banned, author_subject, reason)
VALUES (p_account, p_banned, p_subject, coalesce(p_reason, ''));
IF p_banned THEN
PERFORM evolution.revoke_account_by_id(p_world, p_account);
END IF;
RETURN p_banned;
END $$;
REVOKE ALL ON FUNCTION evolution.admin_set_account_ban_v1(evolution.u64, uuid, boolean, text, text)
FROM PUBLIC;
-- Admin: end the account's sessions now (its next login needs a new grant).
CREATE FUNCTION evolution.admin_logout_account_v1(p_world evolution.u64, p_account uuid)
RETURNS boolean LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
BEGIN
IF p_world IS NULL OR p_world = 0 OR p_account IS NULL THEN
RAISE EXCEPTION 'invalid account' USING ERRCODE = '22023';
END IF;
RETURN evolution.revoke_account_by_id(p_world, p_account);
END $$;
REVOKE ALL ON FUNCTION evolution.admin_logout_account_v1(evolution.u64, uuid) FROM PUBLIC;
-- Admin: each account's ban state, time played and last session activity in the world.
CREATE FUNCTION evolution.admin_account_status_v1(p_world evolution.u64)
RETURNS TABLE (account_id uuid, banned boolean, played_seconds bigint, last_seen timestamptz,
sessions bigint)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
WITH accounts AS (
SELECT i.account_id FROM evolution.account_identities i
UNION SELECT s.account_id FROM evolution.session_intervals s WHERE s.world_id = p_world
UNION SELECT b.account_id FROM evolution.account_bans b
)
SELECT a.account_id, evolution.account_banned(a.account_id),
coalesce((SELECT floor(sum(extract(epoch FROM coalesce(s.ended_at, s.last_seen)
- s.started_at)))::bigint
FROM evolution.session_intervals s
WHERE s.world_id = p_world AND s.account_id = a.account_id), 0),
(SELECT max(coalesce(s.ended_at, s.last_seen)) FROM evolution.session_intervals s
WHERE s.world_id = p_world AND s.account_id = a.account_id),
(SELECT count(*) FROM evolution.session_intervals s
WHERE s.world_id = p_world AND s.account_id = a.account_id)
FROM accounts a
LIMIT 10000
$$;
REVOKE ALL ON FUNCTION evolution.admin_account_status_v1(evolution.u64) FROM PUBLIC;
-- Admin: one account's ban history, newest first.
CREATE FUNCTION evolution.admin_account_bans_v1(p_account uuid)
RETURNS TABLE (banned boolean, author_subject text, reason text, created_at timestamptz)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT b.banned, b.author_subject, b.reason, b.created_at FROM evolution.account_bans b
WHERE b.account_id = p_account ORDER BY b.sequence DESC LIMIT 50
$$;
REVOKE ALL ON FUNCTION evolution.admin_account_bans_v1(uuid) FROM PUBLIC;
-- A banned account gets no grant.
ALTER FUNCTION evolution.issue_account_grant(evolution.u64, text, text)
RENAME TO issue_account_grant_v63;
REVOKE ALL ON FUNCTION evolution.issue_account_grant_v63(evolution.u64, text, text)
FROM PUBLIC, :"runtime_role";
CREATE FUNCTION evolution.issue_account_grant(p_world evolution.u64, p_issuer text,
p_subject text)
RETURNS TABLE(grant_account uuid, grant_serial evolution.u64, home_region evolution.u64)
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
DECLARE known uuid;
BEGIN
SELECT x.account_id INTO known FROM evolution.account_identities x
WHERE x.issuer = p_issuer AND x.subject = p_subject;
IF known IS NOT NULL AND evolution.account_banned(known) THEN
RAISE EXCEPTION 'account banned' USING ERRCODE = 'EVL20';
END IF;
RETURN QUERY SELECT * FROM evolution.issue_account_grant_v63(p_world, p_issuer, p_subject);
END $$;
REVOKE ALL ON FUNCTION evolution.issue_account_grant(evolution.u64, text, text) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION evolution.issue_account_grant(evolution.u64, text, text)
TO :"runtime_role";
-- Session intervals from the control functions (signatures unchanged).
ALTER FUNCTION evolution.claim_account_control(evolution.u64, evolution.u64, uuid, evolution.u64,
uuid, evolution.u64, evolution.u64, integer) RENAME TO claim_account_control_v63;
REVOKE ALL ON FUNCTION evolution.claim_account_control_v63(evolution.u64, evolution.u64, uuid,
evolution.u64, uuid, evolution.u64, evolution.u64, integer) FROM PUBLIC, :"runtime_role";
CREATE FUNCTION evolution.claim_account_control(p_world evolution.u64, p_region evolution.u64,
p_holder uuid, p_epoch evolution.u64, p_account uuid, p_serial evolution.u64,
p_session evolution.u64, p_duration_ms integer)
RETURNS TABLE (control_generation evolution.u64, wait_ms integer, granted_ms integer)
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
DECLARE r record;
BEGIN
FOR r IN SELECT * FROM evolution.claim_account_control_v63(p_world, p_region, p_holder,
p_epoch, p_account, p_serial, p_session, p_duration_ms) LOOP
IF r.granted_ms > 0 THEN
INSERT INTO evolution.session_intervals(world_id, account_id, generation, region_id,
started_at, last_seen)
VALUES (p_world, p_account, r.control_generation, p_region, clock_timestamp(),
clock_timestamp())
ON CONFLICT (world_id, account_id, generation) DO NOTHING;
END IF;
control_generation := r.control_generation;
wait_ms := r.wait_ms;
granted_ms := r.granted_ms;
RETURN NEXT;
END LOOP;
END $$;
REVOKE ALL ON FUNCTION evolution.claim_account_control(evolution.u64, evolution.u64, uuid,
evolution.u64, uuid, evolution.u64, evolution.u64, integer) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION evolution.claim_account_control(evolution.u64, evolution.u64, uuid,
evolution.u64, uuid, evolution.u64, evolution.u64, integer) TO :"runtime_role";
ALTER FUNCTION evolution.renew_account_control(evolution.u64, evolution.u64, uuid, evolution.u64,
uuid, evolution.u64, integer) RENAME TO renew_account_control_v63;
REVOKE ALL ON FUNCTION evolution.renew_account_control_v63(evolution.u64, evolution.u64, uuid,
evolution.u64, uuid, evolution.u64, integer) FROM PUBLIC, :"runtime_role";
CREATE FUNCTION evolution.renew_account_control(p_world evolution.u64, p_region evolution.u64,
p_holder uuid, p_epoch evolution.u64, p_account uuid, p_generation evolution.u64,
p_duration_ms integer)
RETURNS integer LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
DECLARE granted integer;
BEGIN
granted := evolution.renew_account_control_v63(p_world, p_region, p_holder, p_epoch, p_account,
p_generation, p_duration_ms);
UPDATE evolution.session_intervals s SET last_seen = clock_timestamp()
WHERE s.world_id = p_world AND s.account_id = p_account AND s.generation = p_generation
AND s.ended_at IS NULL;
RETURN granted;
END $$;
REVOKE ALL ON FUNCTION evolution.renew_account_control(evolution.u64, evolution.u64, uuid,
evolution.u64, uuid, evolution.u64, integer) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION evolution.renew_account_control(evolution.u64, evolution.u64, uuid,
evolution.u64, uuid, evolution.u64, integer) TO :"runtime_role";
ALTER FUNCTION evolution.release_account_control(evolution.u64, evolution.u64, uuid,
evolution.u64, uuid, evolution.u64) RENAME TO release_account_control_v63;
REVOKE ALL ON FUNCTION evolution.release_account_control_v63(evolution.u64, evolution.u64, uuid,
evolution.u64, uuid, evolution.u64) FROM PUBLIC, :"runtime_role";
CREATE FUNCTION evolution.release_account_control(p_world evolution.u64, p_region evolution.u64,
p_holder uuid, p_epoch evolution.u64, p_account uuid, p_generation evolution.u64)
RETURNS boolean LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
DECLARE released boolean;
BEGIN
released := evolution.release_account_control_v63(p_world, p_region, p_holder, p_epoch,
p_account, p_generation);
UPDATE evolution.session_intervals s SET last_seen = clock_timestamp(),
ended_at = clock_timestamp()
WHERE s.world_id = p_world AND s.account_id = p_account AND s.generation = p_generation
AND s.ended_at IS NULL;
RETURN released;
END $$;
REVOKE ALL ON FUNCTION evolution.release_account_control(evolution.u64, evolution.u64, uuid,
evolution.u64, uuid, evolution.u64) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION evolution.release_account_control(evolution.u64, evolution.u64, uuid,
evolution.u64, uuid, evolution.u64) TO :"runtime_role";
INSERT INTO evolution.schema_migrations(version,sha256) VALUES(64,:'migration_sha_64');
+143
View File
@@ -0,0 +1,143 @@
-- Resource schedules (ADR-0182 section 4, 2026-10-27): the game source as recurring admin
-- commands. A schedule repeats an add_bubbles, release_pool or spawn_wildlife command every
-- `interval_seconds` while it is enabled. When the region reads its pending commands, each
-- enabled schedule whose last command was applied (or that never ran) and whose interval has
-- passed queues its next command, exactly as an operator would; it is then recorded in the
-- trace and bound once like any command. At most one command per schedule waits, so an idle
-- region (no living cells, no ticks) builds no backlog. Schedule versions are append-only;
-- the newest row of a schedule decides.
ALTER TABLE evolution.admin_commands ADD COLUMN schedule_id bigint;
CREATE TABLE evolution.admin_schedules (
sequence bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
schedule_id bigint NOT NULL,
world_id evolution.u64 NOT NULL,
region_id evolution.u64 NOT NULL,
kind smallint NOT NULL CHECK (kind IN (3, 5, 6)),
cell_count integer NOT NULL CHECK (cell_count BETWEEN 1 AND 256),
energy evolution.u64 NOT NULL,
carbon evolution.u64 NOT NULL,
nitrogen evolution.u64 NOT NULL,
phosphorus evolution.u64 NOT NULL,
other evolution.u64 NOT NULL,
interval_seconds integer NOT NULL CHECK (interval_seconds BETWEEN 1 AND 86400),
enabled boolean NOT NULL,
author_subject text NOT NULL CHECK (octet_length(author_subject) BETWEEN 1 AND 255),
reason text NOT NULL DEFAULT '' CHECK (octet_length(reason) <= 500),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
FOREIGN KEY (world_id, region_id) REFERENCES evolution.region_leases,
CHECK ((kind = 6 AND cell_count <= 64 AND energy + carbon + nitrogen + phosphorus + other = 0)
OR (kind IN (3, 5) AND energy + carbon + nitrogen + phosphorus + other > 0))
);
CREATE INDEX admin_schedules_by_schedule ON evolution.admin_schedules(schedule_id, sequence);
CREATE SEQUENCE evolution.admin_schedule_ids;
CREATE TRIGGER admin_schedules_immutable BEFORE UPDATE OR DELETE ON evolution.admin_schedules
FOR EACH ROW EXECUTE FUNCTION evolution.refuse_history_rewrite();
-- Admin: creates (p_schedule 0) or replaces a schedule's settings; disabling stops it.
CREATE FUNCTION evolution.admin_set_schedule_v1(p_world evolution.u64, p_region evolution.u64,
p_schedule bigint, p_kind integer, p_count integer, p_energy evolution.u64,
p_carbon evolution.u64, p_nitrogen evolution.u64, p_phosphorus evolution.u64,
p_other evolution.u64, p_interval integer, p_enabled boolean, p_subject text, p_reason text)
RETURNS bigint LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
DECLARE id bigint := p_schedule;
BEGIN
IF id IS NULL OR id = 0 THEN
id := nextval('evolution.admin_schedule_ids');
ELSIF NOT EXISTS (SELECT 1 FROM evolution.admin_schedules s WHERE s.schedule_id = id
AND s.world_id = p_world AND s.region_id = p_region) THEN
RAISE EXCEPTION 'unknown schedule' USING ERRCODE = '22023';
END IF;
BEGIN
INSERT INTO evolution.admin_schedules(schedule_id, world_id, region_id, kind, cell_count,
energy, carbon, nitrogen, phosphorus, other, interval_seconds, enabled, author_subject,
reason)
VALUES (id, p_world, p_region, p_kind, p_count, p_energy, p_carbon, p_nitrogen,
p_phosphorus, p_other, p_interval, p_enabled, p_subject, coalesce(p_reason, ''));
EXCEPTION WHEN check_violation OR foreign_key_violation OR not_null_violation THEN
RAISE EXCEPTION 'invalid schedule' USING ERRCODE = '22023';
END;
RETURN id;
END $$;
REVOKE ALL ON FUNCTION evolution.admin_set_schedule_v1(evolution.u64, evolution.u64, bigint,
integer, integer, evolution.u64, evolution.u64, evolution.u64, evolution.u64, evolution.u64,
integer, boolean, text, text) FROM PUBLIC;
-- Admin: a region's schedules as they now stand, with their last queued command.
CREATE FUNCTION evolution.admin_schedules_v1(p_world evolution.u64, p_region evolution.u64)
RETURNS TABLE (schedule_id bigint, kind integer, cell_count integer, energy evolution.u64,
carbon evolution.u64, nitrogen evolution.u64, phosphorus evolution.u64, other evolution.u64,
interval_seconds integer, enabled boolean, author_subject text, reason text,
changed_at timestamptz, last_queued timestamptz, runs bigint)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT s.schedule_id, s.kind, s.cell_count, s.energy, s.carbon, s.nitrogen, s.phosphorus,
s.other, s.interval_seconds, s.enabled, s.author_subject, s.reason, s.created_at,
(SELECT max(q.created_at) FROM evolution.admin_commands q
WHERE q.schedule_id = s.schedule_id),
(SELECT count(*) FROM evolution.admin_commands q WHERE q.schedule_id = s.schedule_id)
FROM evolution.admin_schedules s
WHERE s.world_id = p_world AND s.region_id = p_region
AND s.sequence = (SELECT max(x.sequence) FROM evolution.admin_schedules x
WHERE x.schedule_id = s.schedule_id)
ORDER BY s.schedule_id
$$;
REVOKE ALL ON FUNCTION evolution.admin_schedules_v1(evolution.u64, evolution.u64) FROM PUBLIC;
-- Queues every due schedule's next command (spawning takes identities from the allocator).
CREATE FUNCTION evolution.queue_due_schedules(p_world evolution.u64, p_region evolution.u64)
RETURNS void LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp AS $$
DECLARE
s record;
first numeric;
BEGIN
FOR s IN SELECT * FROM evolution.admin_schedules x
WHERE x.world_id = p_world AND x.region_id = p_region
AND x.sequence = (SELECT max(y.sequence) FROM evolution.admin_schedules y
WHERE y.schedule_id = x.schedule_id)
AND x.enabled
ORDER BY x.schedule_id LOOP
CONTINUE WHEN EXISTS (SELECT 1 FROM evolution.admin_commands q
WHERE q.schedule_id = s.schedule_id
AND NOT EXISTS (SELECT 1 FROM evolution.admin_command_applications a
WHERE a.command_id = q.command_id));
CONTINUE WHEN coalesce((SELECT max(q.created_at) FROM evolution.admin_commands q
WHERE q.schedule_id = s.schedule_id), '-infinity'::timestamptz)
+ make_interval(secs => s.interval_seconds) > clock_timestamp();
first := 0;
IF s.kind = 6 THEN
SELECT a.next_identity INTO first FROM evolution.life_allocators a
WHERE a.world_id = p_world FOR UPDATE;
CONTINUE WHEN first IS NULL OR first + s.cell_count > 9223372036854775808;
UPDATE evolution.life_allocators SET next_identity = first + s.cell_count
WHERE world_id = p_world;
END IF;
INSERT INTO evolution.admin_commands(world_id, region_id, kind, cell_count, target, energy,
carbon, nitrogen, phosphorus, other, author_subject, reason, schedule_id)
VALUES (p_world, p_region, s.kind, s.cell_count, first, s.energy, s.carbon, s.nitrogen,
s.phosphorus, s.other, 'schedule ' || s.schedule_id, s.reason, s.schedule_id);
END LOOP;
END $$;
REVOKE ALL ON FUNCTION evolution.queue_due_schedules(evolution.u64, evolution.u64) FROM PUBLIC;
-- The region's pending commands, after queuing what its schedules owe (same signature).
ALTER FUNCTION evolution.load_pending_admin_commands_v1(evolution.u64, evolution.u64)
RENAME TO load_pending_admin_commands_v64;
REVOKE ALL ON FUNCTION evolution.load_pending_admin_commands_v64(evolution.u64, evolution.u64)
FROM PUBLIC, :"runtime_role";
CREATE FUNCTION evolution.load_pending_admin_commands_v1(p_world evolution.u64,
p_region evolution.u64)
RETURNS TABLE (command_id bigint, kind integer, cell_count integer, target evolution.u64,
energy evolution.u64, carbon evolution.u64, nitrogen evolution.u64, phosphorus evolution.u64,
other evolution.u64)
LANGUAGE plpgsql VOLATILE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
BEGIN
PERFORM evolution.queue_due_schedules(p_world, p_region);
RETURN QUERY SELECT * FROM evolution.load_pending_admin_commands_v64(p_world, p_region);
END $$;
REVOKE ALL ON FUNCTION evolution.load_pending_admin_commands_v1(evolution.u64, evolution.u64)
FROM PUBLIC;
GRANT EXECUTE ON FUNCTION evolution.load_pending_admin_commands_v1(evolution.u64, evolution.u64)
TO :"runtime_role";
INSERT INTO evolution.schema_migrations(version,sha256) VALUES(65,:'migration_sha_65');
+106
View File
@@ -0,0 +1,106 @@
-- Tuning revisions (ADR-0182 sections 1-2, 2026-10-27). The rules-13 tuning of a world is a
-- sequence of append-only revisions: the canonical tuning text and the SHA-256 of the rules it
-- produces (encode_cellular_revamp_rules). Storing a revision queues an adopt_tuning admin
-- command (kind 7) for each named region; the region fetches the text, rebuilds the rules,
-- checks the digest and adopts them at a tick recorded in its trace, so replay and recovery
-- reproduce the change exactly. Commands of kind 7 come only from this function.
ALTER TABLE evolution.admin_commands DROP CONSTRAINT admin_commands_kind_check;
ALTER TABLE evolution.admin_commands ADD CONSTRAINT admin_commands_kind_check
CHECK (kind BETWEEN 1 AND 7);
CREATE TABLE evolution.tuning_revisions (
revision bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
world_id evolution.u64 NOT NULL,
text text NOT NULL CHECK (octet_length(text) BETWEEN 1 AND 262144),
rules_sha256 bytea NOT NULL CHECK (octet_length(rules_sha256) = 32),
author_subject text NOT NULL CHECK (octet_length(author_subject) BETWEEN 1 AND 255),
reason text NOT NULL DEFAULT '' CHECK (octet_length(reason) <= 500),
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE TRIGGER tuning_revisions_immutable BEFORE UPDATE OR DELETE ON evolution.tuning_revisions
FOR EACH ROW EXECUTE FUNCTION evolution.refuse_history_rewrite();
-- Admin: stores a revision (validated by the admin API, which also computed the rules digest;
-- the text is kept as written, comments included) and queues its adoption in each of
-- `p_regions`.
CREATE FUNCTION evolution.admin_set_tuning_v1(p_world evolution.u64, p_text text,
p_rules_sha256 bytea, p_regions bigint[], p_subject text, p_reason text)
RETURNS bigint LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
DECLARE
made bigint;
region bigint;
BEGIN
IF p_world IS NULL OR p_world = 0 OR p_regions IS NULL OR cardinality(p_regions) = 0
OR cardinality(p_regions) > 64 OR p_rules_sha256 IS NULL
OR octet_length(p_rules_sha256) <> 32 THEN
RAISE EXCEPTION 'invalid tuning revision' USING ERRCODE = '22023';
END IF;
BEGIN
INSERT INTO evolution.tuning_revisions(world_id, text, rules_sha256, author_subject, reason)
VALUES (p_world, p_text, p_rules_sha256, p_subject, coalesce(p_reason, ''))
RETURNING revision INTO made;
EXCEPTION WHEN check_violation OR not_null_violation THEN
RAISE EXCEPTION 'invalid tuning revision' USING ERRCODE = '22023';
END;
FOREACH region IN ARRAY p_regions LOOP
IF NOT EXISTS (SELECT 1 FROM evolution.region_leases l
WHERE l.world_id = p_world AND l.region_id = region) THEN
RAISE EXCEPTION 'unknown region' USING ERRCODE = '22023';
END IF;
INSERT INTO evolution.admin_commands(world_id, region_id, kind, cell_count, target, energy,
carbon, nitrogen, phosphorus, other, author_subject, reason)
VALUES (p_world, region, 7, 0, made, evolution.manifest_uint(p_rules_sha256, 0, 8),
evolution.manifest_uint(p_rules_sha256, 8, 8),
evolution.manifest_uint(p_rules_sha256, 16, 8),
evolution.manifest_uint(p_rules_sha256, 24, 8), 0, p_subject, coalesce(p_reason, ''));
END LOOP;
RETURN made;
END $$;
REVOKE ALL ON FUNCTION evolution.admin_set_tuning_v1(evolution.u64, text, bytea, bigint[], text,
text) FROM PUBLIC;
-- The region: a revision's text and rules digest.
CREATE FUNCTION evolution.load_tuning_revision_v1(p_world evolution.u64, p_revision bigint)
RETURNS TABLE (text text, rules_sha256 bytea)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT t.text, t.rules_sha256 FROM evolution.tuning_revisions t
WHERE t.world_id = p_world AND t.revision = p_revision
$$;
REVOKE ALL ON FUNCTION evolution.load_tuning_revision_v1(evolution.u64, bigint) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION evolution.load_tuning_revision_v1(evolution.u64, bigint)
TO :"runtime_role";
-- Admin: the world's revisions, newest first, with how many regions have adopted each.
CREATE FUNCTION evolution.admin_tuning_revisions_v1(p_world evolution.u64)
RETURNS TABLE (revision bigint, rules_sha256 text, author_subject text, reason text,
created_at timestamptz, regions bigint, adopted bigint, last_tick evolution.u64)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT t.revision, encode(t.rules_sha256, 'hex'), t.author_subject, t.reason, t.created_at,
(SELECT count(*) FROM evolution.admin_commands q
WHERE q.kind = 7 AND q.world_id = p_world AND q.target = t.revision),
(SELECT count(*) FROM evolution.admin_commands q
JOIN evolution.admin_command_applications a ON a.command_id = q.command_id
WHERE q.kind = 7 AND q.world_id = p_world AND q.target = t.revision),
(SELECT max(a.tick) FROM evolution.admin_commands q
JOIN evolution.admin_command_applications a ON a.command_id = q.command_id
WHERE q.kind = 7 AND q.world_id = p_world AND q.target = t.revision)
FROM evolution.tuning_revisions t
WHERE t.world_id = p_world
ORDER BY t.revision DESC
LIMIT 100
$$;
REVOKE ALL ON FUNCTION evolution.admin_tuning_revisions_v1(evolution.u64) FROM PUBLIC;
-- Admin: a revision's text (0: the newest).
CREATE FUNCTION evolution.admin_tuning_text_v1(p_world evolution.u64, p_revision bigint)
RETURNS TABLE (revision bigint, text text)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
SELECT t.revision, t.text FROM evolution.tuning_revisions t
WHERE t.world_id = p_world AND (p_revision = 0 OR t.revision = p_revision)
ORDER BY t.revision DESC
LIMIT 1
$$;
REVOKE ALL ON FUNCTION evolution.admin_tuning_text_v1(evolution.u64, bigint) FROM PUBLIC;
INSERT INTO evolution.schema_migrations(version,sha256) VALUES(66,:'migration_sha_66');
+54
View File
@@ -0,0 +1,54 @@
-- Admin take and cull (ADR-0182 section 16, 2026-10-28). Two more admin command kinds for
-- testing a live region: take_reserve (8) moves up to the given amounts from one life's
-- reserve to the spent pool, the inverse of grant_reserve; remove_wildlife (9) removes every
-- life without an account at once, as remove_cell does one.
ALTER TABLE evolution.admin_commands DROP CONSTRAINT admin_commands_kind_check;
ALTER TABLE evolution.admin_commands ADD CONSTRAINT admin_commands_kind_check
CHECK (kind BETWEEN 1 AND 9);
-- Queues a command (the same shapes the owner accepts). Spawning takes its identities from the
-- world's life allocator, so they never meet a player's.
CREATE OR REPLACE FUNCTION evolution.admin_enqueue_command_v1(p_world evolution.u64,
p_region evolution.u64, p_kind integer, p_count integer, p_target evolution.u64,
p_energy evolution.u64, p_carbon evolution.u64, p_nitrogen evolution.u64,
p_phosphorus evolution.u64, p_other evolution.u64, p_subject text, p_reason text)
RETURNS TABLE (command_id bigint, target evolution.u64)
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
#variable_conflict use_column
DECLARE
has_amount boolean := p_energy + p_carbon + p_nitrogen + p_phosphorus + p_other > 0;
first numeric := p_target;
BEGIN
IF NOT ((p_kind IN (1, 2, 8) AND p_target > 0 AND p_count = 0
AND has_amount = (p_kind IN (2, 8)))
OR (p_kind IN (3, 5) AND p_target = 0 AND p_count BETWEEN 1 AND 256 AND has_amount)
OR (p_kind = 4 AND p_target = 0 AND p_count = 0 AND has_amount)
OR (p_kind = 6 AND p_count BETWEEN 1 AND 64 AND NOT has_amount)
OR (p_kind = 9 AND p_target = 0 AND p_count = 0 AND NOT has_amount)) THEN
RAISE EXCEPTION 'invalid admin command' USING ERRCODE = '22023';
END IF;
IF NOT EXISTS (SELECT 1 FROM evolution.region_leases l
WHERE l.world_id = p_world AND l.region_id = p_region) THEN
RAISE EXCEPTION 'unknown region' USING ERRCODE = '22023';
END IF;
IF p_kind = 6 THEN
SELECT a.next_identity INTO first FROM evolution.life_allocators a
WHERE a.world_id = p_world FOR UPDATE;
IF first IS NULL OR first + p_count > 9223372036854775808 THEN
RAISE EXCEPTION 'no identities for wildlife' USING ERRCODE = '22023';
END IF;
UPDATE evolution.life_allocators SET next_identity = first + p_count
WHERE world_id = p_world;
END IF;
RETURN QUERY
WITH queued AS (
INSERT INTO evolution.admin_commands AS q(world_id, region_id, kind, cell_count, target,
energy, carbon, nitrogen, phosphorus, other, author_subject, reason)
VALUES (p_world, p_region, p_kind, p_count, first, p_energy, p_carbon, p_nitrogen,
p_phosphorus, p_other, p_subject, coalesce(p_reason, ''))
RETURNING q.command_id, q.target)
SELECT queued.command_id, queued.target FROM queued;
END $$;
INSERT INTO evolution.schema_migrations(version,sha256) VALUES(67,:'migration_sha_67');
+145
View File
@@ -0,0 +1,145 @@
-- Larger region ticks (ADR-0182 section 17, 2026-10-28). A region tick may hold up to 4,096
-- lives, a bound for testing (regions run far fewer). The cellular trace checker under the
-- current publishers (schema 43's, renamed cellular_births_v45 by schema 46) accepts up to
-- 4,096 intents, births and mutation choices per tick; nothing else in it changes. Cohort
-- populations and migration traces keep their 256 bounds. Spawning takes up to 256 wildlife
-- per command.
CREATE OR REPLACE FUNCTION evolution.cellular_births_v45(p_trace bytea, p_manifest bytea)
RETURNS TABLE(account_id uuid, request_id evolution.u64, generation evolution.u64,
identity evolution.u64, born evolution.u64)
LANGUAGE plpgsql IMMUTABLE SECURITY INVOKER SET search_path = pg_catalog, pg_temp AS $$
DECLARE
c evolution.checkpoint_manifest := evolution.parse_checkpoint_manifest(p_manifest);
revision boolean;
ticks numeric;
tick_index integer;
trace_format numeric;
tick_header_size integer;
intent_count numeric;
birth_count numeric;
mutation_count numeric;
off integer := 112;
account bytea;
previous_account bytea;
previous_request numeric;
BEGIN
revision := c.versions IN (
'\x020000000300000001000000010000000100000002000000010000000200000001000000'::bytea,
'\x030000000400000001000000010000000100000002000000010000000200000001000000'::bytea,
'\x040000000500000001000000010000000100000002000000010000000200000001000000'::bytea,
'\x050000000600000001000000010000000100000002000000010000000200000001000000'::bytea,
'\x060000000600000001000000010000000100000003000000020000000200000001000000'::bytea,
'\x070000000600000001000000010000000100000004000000030000000200000001000000'::bytea,
'\x080000000600000002000000010000000100000004000000030000000200000001000000'::bytea);
trace_format := evolution.manifest_uint(p_trace, 8, 4);
tick_header_size := CASE trace_format WHEN 2 THEN 8 WHEN 3 THEN 16 ELSE 0 END;
IF c.profile <> 4 OR c.commit_sequence = 0 OR p_trace IS NULL
OR octet_length(p_trace) <> c.trace_bytes OR sha256(p_trace) <> c.trace_sha256
OR substring(p_trace FROM 1 FOR 8) <> '\x45564c4342543031'
OR tick_header_size = 0
OR (revision AND trace_format <> 3)
OR (NOT revision AND trace_format <> 2)
OR evolution.manifest_uint(p_trace, 12, 4) <> 4
OR evolution.manifest_uint(p_trace, 16, 8) <> c.world_id
OR evolution.manifest_uint(p_trace, 24, 8) <> c.region_id
OR evolution.manifest_uint(p_trace, 32, 8) <> c.frame_id
OR encode(substring(p_trace FROM 41 FOR 16), 'hex')::uuid <> c.predecessor_commit
OR substring(p_trace FROM 57 FOR 32) <> c.predecessor_digest
OR evolution.manifest_uint(p_trace, 88, 8) <> c.begin_tick
OR evolution.manifest_uint(p_trace, 96, 8) <> c.end_tick THEN
RAISE EXCEPTION 'invalid cellular birth trace binding' USING ERRCODE = '22023';
END IF;
ticks := c.end_tick - c.begin_tick;
IF ticks < 1 OR ticks > 64 OR evolution.manifest_uint(p_trace, 104, 4) <> ticks
OR evolution.manifest_uint(p_trace, 108, 4) <> 0 THEN
RAISE EXCEPTION 'invalid cellular birth trace range' USING ERRCODE = '22023';
END IF;
FOR tick_index IN 0 .. ticks::integer - 1 LOOP
IF off + tick_header_size > octet_length(p_trace) THEN
RAISE EXCEPTION 'truncated cellular tick header' USING ERRCODE = '22023';
END IF;
intent_count := evolution.manifest_uint(p_trace, off, 4);
birth_count := evolution.manifest_uint(p_trace, off + 4, 4);
mutation_count := 0;
IF trace_format = 3 THEN
mutation_count := evolution.manifest_uint(p_trace, off + 8, 4);
IF evolution.manifest_uint(p_trace, off + 12, 4) <> 0 THEN
RAISE EXCEPTION 'invalid cellular tick reserved word' USING ERRCODE = '22023';
END IF;
END IF;
IF intent_count > 4096 OR birth_count > 4096 OR mutation_count > 4096
OR off + tick_header_size + intent_count * 24 + birth_count * 40
+ mutation_count * 40 > octet_length(p_trace) THEN
RAISE EXCEPTION 'invalid cellular tick counts' USING ERRCODE = '22023';
END IF;
off := off + tick_header_size + intent_count::integer * 24;
previous_account := ''::bytea;
previous_request := -1;
FOR birth_index IN 0 .. birth_count::integer - 1 LOOP
account := substring(p_trace FROM off + 1 FOR 16);
account_id := encode(account, 'hex')::uuid;
request_id := evolution.manifest_uint(p_trace, off + 16, 8);
generation := evolution.manifest_uint(p_trace, off + 24, 8);
identity := evolution.manifest_uint(p_trace, off + 32, 8);
born := c.begin_tick + tick_index + 1;
IF account_id = '00000000-0000-0000-0000-000000000000' OR request_id = 0
OR generation = 0 OR identity = 0
OR (account, request_id) <= (previous_account, previous_request) THEN
RAISE EXCEPTION 'invalid cellular birth record' USING ERRCODE = '22023';
END IF;
previous_account := account;
previous_request := request_id;
off := off + 40;
RETURN NEXT;
END LOOP;
off := off + mutation_count::integer * 40;
END LOOP;
IF off <> octet_length(p_trace) THEN
RAISE EXCEPTION 'trailing cellular trace bytes' USING ERRCODE = '22023';
END IF;
END $$;
CREATE OR REPLACE FUNCTION evolution.admin_enqueue_command_v1(p_world evolution.u64,
p_region evolution.u64, p_kind integer, p_count integer, p_target evolution.u64,
p_energy evolution.u64, p_carbon evolution.u64, p_nitrogen evolution.u64,
p_phosphorus evolution.u64, p_other evolution.u64, p_subject text, p_reason text)
RETURNS TABLE (command_id bigint, target evolution.u64)
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
#variable_conflict use_column
DECLARE
has_amount boolean := p_energy + p_carbon + p_nitrogen + p_phosphorus + p_other > 0;
first numeric := p_target;
BEGIN
IF NOT ((p_kind IN (1, 2, 8) AND p_target > 0 AND p_count = 0
AND has_amount = (p_kind IN (2, 8)))
OR (p_kind IN (3, 5) AND p_target = 0 AND p_count BETWEEN 1 AND 256 AND has_amount)
OR (p_kind = 4 AND p_target = 0 AND p_count = 0 AND has_amount)
OR (p_kind = 6 AND p_count BETWEEN 1 AND 256 AND NOT has_amount)
OR (p_kind = 9 AND p_target = 0 AND p_count = 0 AND NOT has_amount)) THEN
RAISE EXCEPTION 'invalid admin command' USING ERRCODE = '22023';
END IF;
IF NOT EXISTS (SELECT 1 FROM evolution.region_leases l
WHERE l.world_id = p_world AND l.region_id = p_region) THEN
RAISE EXCEPTION 'unknown region' USING ERRCODE = '22023';
END IF;
IF p_kind = 6 THEN
SELECT a.next_identity INTO first FROM evolution.life_allocators a
WHERE a.world_id = p_world FOR UPDATE;
IF first IS NULL OR first + p_count > 9223372036854775808 THEN
RAISE EXCEPTION 'no identities for wildlife' USING ERRCODE = '22023';
END IF;
UPDATE evolution.life_allocators SET next_identity = first + p_count
WHERE world_id = p_world;
END IF;
RETURN QUERY
WITH queued AS (
INSERT INTO evolution.admin_commands AS q(world_id, region_id, kind, cell_count, target,
energy, carbon, nitrogen, phosphorus, other, author_subject, reason)
VALUES (p_world, p_region, p_kind, p_count, first, p_energy, p_carbon, p_nitrogen,
p_phosphorus, p_other, p_subject, coalesce(p_reason, ''))
RETURNING q.command_id, q.target)
SELECT queued.command_id, queued.target FROM queued;
END $$;
INSERT INTO evolution.schema_migrations(version,sha256) VALUES(68,:'migration_sha_68');

Some files were not shown because too many files have changed in this diff Show More