paracosm 0.1.0a1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- paracosm-0.1.0a1/IMPLEMENTATION_PLAN.md +60 -0
- paracosm-0.1.0a1/LICENSE.md +21 -0
- paracosm-0.1.0a1/PKG-INFO +54 -0
- paracosm-0.1.0a1/README.md +40 -0
- paracosm-0.1.0a1/pyproject.toml +31 -0
- paracosm-0.1.0a1/pyproject.toml.orig +26 -0
- paracosm-0.1.0a1/scripts/check_release.py +61 -0
- paracosm-0.1.0a1/scripts/qualify.py +31 -0
- paracosm-0.1.0a1/src/paracosm/__init__.py +13 -0
- paracosm-0.1.0a1/src/paracosm/__main__.py +4 -0
- paracosm-0.1.0a1/src/paracosm/world.py +130 -0
- paracosm-0.1.0a1/tests/test_world.py +67 -0
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# Paracosm implementation plan
|
|
2
|
+
|
|
3
|
+
Paracosm owns authoritative worlds, habitats, spatial membership, deterministic
|
|
4
|
+
time/steps, accepted events and rule validation. Thoughtform owns neutral beings
|
|
5
|
+
and proposed actions; Hypnosis owns execution/job policy; Thoughtformula owns
|
|
6
|
+
model mathematics. The
|
|
7
|
+
[complete Cohesion Block B plan](https://github.com/wispsy/wispsy/blob/main/docs/cohesion-block-b/IMPLEMENTATION_PLAN.md)
|
|
8
|
+
records all shared contracts, library reuse, milestones and task acceptance.
|
|
9
|
+
[Project 28](https://github.com/orgs/wispsy/projects/28) and owning issues are the
|
|
10
|
+
execution queue.
|
|
11
|
+
|
|
12
|
+
## Deterministic stepping — PARA-01
|
|
13
|
+
|
|
14
|
+
Create immutable bounded habitat/resident/world snapshots. Compute actions in
|
|
15
|
+
stable actor-ID order from one pre-step observation snapshot. Validate every
|
|
16
|
+
proposal before applying any state change. Rejected actions, unknown actors,
|
|
17
|
+
identity spoofing and reentrancy preserve the authoritative snapshot. The first
|
|
18
|
+
reference has one habitat and two beings; a second habitat exercises movement.
|
|
19
|
+
|
|
20
|
+
The initial finite action set is wait, move, say and habitat condition. Missing
|
|
21
|
+
policies wait. An optional habitat mind is an explicit Thoughtform being and
|
|
22
|
+
uses the same policy contract; only its own habitat is within its condition
|
|
23
|
+
scope. A role name or model response is never sufficient authority.
|
|
24
|
+
|
|
25
|
+
Verify deterministic repeat episodes, stable call/observation order, rejected
|
|
26
|
+
whole-step atomicity, optional/no-mind operation and actual installed examples.
|
|
27
|
+
No model provider or orchestration framework is required.
|
|
28
|
+
|
|
29
|
+
## Persistence and replay — PARA-SAVE-01
|
|
30
|
+
|
|
31
|
+
Use Backpack typed snapshots and accepted events. Record schema/rules/source
|
|
32
|
+
identity, seeds and clocks. Reopen/replay in separate processes with identical
|
|
33
|
+
accepted state, and refuse incompatible versions before applying data. Replay
|
|
34
|
+
recorded decisions rather than rerunning stochastic inference. Do not create a
|
|
35
|
+
new store or serialize executable callables.
|
|
36
|
+
|
|
37
|
+
## Habitat minds — PARA-MIND-01
|
|
38
|
+
|
|
39
|
+
After explicit model artifact resolution, add an optional configured policy
|
|
40
|
+
adapter for the habitat mind. One habitat and two beings remain the minimum
|
|
41
|
+
scenario. Share base models only through serialized/isolated access; identities,
|
|
42
|
+
context, memory and authority remain separate. Validate environmental proposals
|
|
43
|
+
through world rules exactly like inhabitant proposals.
|
|
44
|
+
|
|
45
|
+
## Experiences — PARA-EXPERIENCE-01
|
|
46
|
+
|
|
47
|
+
Export bounded versioned observations, proposals, accepted actions and outcomes
|
|
48
|
+
with source/data lineage for selected Hypnosis evaluations or training jobs.
|
|
49
|
+
Separate simulated narration from verified outcomes. Select retention, rights
|
|
50
|
+
and development/held-out splits explicitly. Experience export does not trigger
|
|
51
|
+
model training or promotion.
|
|
52
|
+
|
|
53
|
+
## Later composition and releases
|
|
54
|
+
|
|
55
|
+
Collective/whole-world policies may compose through Thoughtform and Hypnosis
|
|
56
|
+
without changing the world authority boundary. UI and hub integrations are
|
|
57
|
+
optional composition profiles. Keep core headless, Python 3.14+, and independent
|
|
58
|
+
of Carets/model packages. Build/install wheel and source on declared platforms.
|
|
59
|
+
Public source is authorized; dataset/weight publication, package releases and
|
|
60
|
+
service deployment require separately selected concrete operations.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 wispsy
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: paracosm
|
|
3
|
+
Version: 0.1.0a1
|
|
4
|
+
Summary: Deterministic worlds and optional environment minds.
|
|
5
|
+
Author: ellainng
|
|
6
|
+
Author-email: ellainng <299958882+ellainng@users.noreply.github.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE.md
|
|
9
|
+
Requires-Dist: thoughtform==0.1.0a1
|
|
10
|
+
Requires-Python: >=3.14
|
|
11
|
+
Project-URL: Source, https://github.com/wispsy/paracosm
|
|
12
|
+
Project-URL: Project, https://github.com/orgs/wispsy/projects/28
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+
# Paracosm
|
|
16
|
+
|
|
17
|
+
Deterministic simulated worlds with optional model-neutral habitat minds.
|
|
18
|
+
Python 3.14+. Uses Thoughtform contracts without a mandatory model or harness.
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
from thoughtform import Being
|
|
22
|
+
from paracosm import Habitat, Resident, Snapshot, World
|
|
23
|
+
|
|
24
|
+
world = World(Snapshot('pluralopia', (Habitat('woods', 'The Woods'),),
|
|
25
|
+
(Resident(Being('alice', 'Alice'), 'woods'),
|
|
26
|
+
Resident(Being('bob', 'Bob'), 'woods'))))
|
|
27
|
+
result = world.step({}) # Missing policies propose wait; one deterministic tick.
|
|
28
|
+
assert result.snapshot.tick == 1
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
A policy implements `decide(Observation) -> Action`. Actor IDs determine call
|
|
32
|
+
order, and every observation comes from the same immutable pre-step snapshot.
|
|
33
|
+
Validate all proposals before committing any state. Unknown actors, identity
|
|
34
|
+
spoofing, unsupported actions and invalid targets preserve the entire step.
|
|
35
|
+
Trusted policy code is ordinary Python, not a sandbox. Reentrant steps fail.
|
|
36
|
+
|
|
37
|
+
Initial actions are `wait`, resident `move`, text `say`, and habitat-mind
|
|
38
|
+
`condition`. A mind is an explicit `Habitat(..., mind=Being(...))`; its policy
|
|
39
|
+
can propose condition changes only for that habitat. Role labels alone do not
|
|
40
|
+
grant authority. A model's text cannot rewrite the authoritative world.
|
|
41
|
+
|
|
42
|
+
`Step` returns the next immutable snapshot and accepted actions. This initial
|
|
43
|
+
in-memory foundation does not persist history or claim model inference replay.
|
|
44
|
+
Backpack snapshot/event storage, rule/version compatibility, learned minds and
|
|
45
|
+
experience exports have separate owning tasks. There are at most 32 habitats
|
|
46
|
+
and 128 total actors; observation/action text is explicitly bounded.
|
|
47
|
+
|
|
48
|
+
Run `uv sync`, `uv run paracosm` for the offline two-being example, and
|
|
49
|
+
`PYTHONPATH=src python -m unittest discover -s tests` for deterministic/atomicity
|
|
50
|
+
checks. CI qualifies wheel/source installations on Linux, macOS and Windows.
|
|
51
|
+
|
|
52
|
+
[Repository plan](IMPLEMENTATION_PLAN.md),
|
|
53
|
+
[complete family plan](https://github.com/wispsy/wispsy/blob/main/docs/cohesion-block-b/IMPLEMENTATION_PLAN.md),
|
|
54
|
+
and [Project](https://github.com/orgs/wispsy/projects/28).
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Paracosm
|
|
2
|
+
|
|
3
|
+
Deterministic simulated worlds with optional model-neutral habitat minds.
|
|
4
|
+
Python 3.14+. Uses Thoughtform contracts without a mandatory model or harness.
|
|
5
|
+
|
|
6
|
+
```python
|
|
7
|
+
from thoughtform import Being
|
|
8
|
+
from paracosm import Habitat, Resident, Snapshot, World
|
|
9
|
+
|
|
10
|
+
world = World(Snapshot('pluralopia', (Habitat('woods', 'The Woods'),),
|
|
11
|
+
(Resident(Being('alice', 'Alice'), 'woods'),
|
|
12
|
+
Resident(Being('bob', 'Bob'), 'woods'))))
|
|
13
|
+
result = world.step({}) # Missing policies propose wait; one deterministic tick.
|
|
14
|
+
assert result.snapshot.tick == 1
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
A policy implements `decide(Observation) -> Action`. Actor IDs determine call
|
|
18
|
+
order, and every observation comes from the same immutable pre-step snapshot.
|
|
19
|
+
Validate all proposals before committing any state. Unknown actors, identity
|
|
20
|
+
spoofing, unsupported actions and invalid targets preserve the entire step.
|
|
21
|
+
Trusted policy code is ordinary Python, not a sandbox. Reentrant steps fail.
|
|
22
|
+
|
|
23
|
+
Initial actions are `wait`, resident `move`, text `say`, and habitat-mind
|
|
24
|
+
`condition`. A mind is an explicit `Habitat(..., mind=Being(...))`; its policy
|
|
25
|
+
can propose condition changes only for that habitat. Role labels alone do not
|
|
26
|
+
grant authority. A model's text cannot rewrite the authoritative world.
|
|
27
|
+
|
|
28
|
+
`Step` returns the next immutable snapshot and accepted actions. This initial
|
|
29
|
+
in-memory foundation does not persist history or claim model inference replay.
|
|
30
|
+
Backpack snapshot/event storage, rule/version compatibility, learned minds and
|
|
31
|
+
experience exports have separate owning tasks. There are at most 32 habitats
|
|
32
|
+
and 128 total actors; observation/action text is explicitly bounded.
|
|
33
|
+
|
|
34
|
+
Run `uv sync`, `uv run paracosm` for the offline two-being example, and
|
|
35
|
+
`PYTHONPATH=src python -m unittest discover -s tests` for deterministic/atomicity
|
|
36
|
+
checks. CI qualifies wheel/source installations on Linux, macOS and Windows.
|
|
37
|
+
|
|
38
|
+
[Repository plan](IMPLEMENTATION_PLAN.md),
|
|
39
|
+
[complete family plan](https://github.com/wispsy/wispsy/blob/main/docs/cohesion-block-b/IMPLEMENTATION_PLAN.md),
|
|
40
|
+
and [Project](https://github.com/orgs/wispsy/projects/28).
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "paracosm"
|
|
3
|
+
version = "0.1.0a1"
|
|
4
|
+
description = "Deterministic worlds and optional environment minds."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE.md"]
|
|
8
|
+
requires-python = ">=3.14"
|
|
9
|
+
dependencies = ["thoughtform==0.1.0a1"]
|
|
10
|
+
|
|
11
|
+
[[project.authors]]
|
|
12
|
+
name = "ellainng"
|
|
13
|
+
email = "299958882+ellainng@users.noreply.github.com"
|
|
14
|
+
|
|
15
|
+
[project.scripts]
|
|
16
|
+
paracosm = "paracosm:main"
|
|
17
|
+
|
|
18
|
+
[project.urls]
|
|
19
|
+
Source = "https://github.com/wispsy/paracosm"
|
|
20
|
+
Project = "https://github.com/orgs/wispsy/projects/28"
|
|
21
|
+
|
|
22
|
+
[build-system]
|
|
23
|
+
requires = ["uv_build>=0.13.6,<0.14.0"]
|
|
24
|
+
build-backend = "uv_build"
|
|
25
|
+
|
|
26
|
+
[tool.uv.build-backend]
|
|
27
|
+
source-include = [
|
|
28
|
+
"tests/**",
|
|
29
|
+
"scripts/**",
|
|
30
|
+
"IMPLEMENTATION_PLAN.md",
|
|
31
|
+
]
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "paracosm"
|
|
3
|
+
version = "0.1.0a1"
|
|
4
|
+
description = "Deterministic worlds and optional environment minds."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE.md"]
|
|
8
|
+
authors = [
|
|
9
|
+
{ name = "ellainng", email = "299958882+ellainng@users.noreply.github.com" }
|
|
10
|
+
]
|
|
11
|
+
requires-python = ">=3.14"
|
|
12
|
+
dependencies = ["thoughtform==0.1.0a1"]
|
|
13
|
+
|
|
14
|
+
[project.scripts]
|
|
15
|
+
paracosm = "paracosm:main"
|
|
16
|
+
|
|
17
|
+
[build-system]
|
|
18
|
+
requires = ["uv_build>=0.13.6,<0.14.0"]
|
|
19
|
+
build-backend = "uv_build"
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
Source = "https://github.com/wispsy/paracosm"
|
|
23
|
+
Project = "https://github.com/orgs/wispsy/projects/28"
|
|
24
|
+
|
|
25
|
+
[tool.uv.build-backend]
|
|
26
|
+
source-include = ["tests/**", "scripts/**", "IMPLEMENTATION_PLAN.md"]
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Validate the exact wheel/source files selected for publication."""
|
|
2
|
+
import argparse
|
|
3
|
+
from email.parser import BytesParser
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import re
|
|
8
|
+
import tarfile
|
|
9
|
+
import tomllib
|
|
10
|
+
import zipfile
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def canonical(name):return re.sub('[-_.]+','-',name).lower()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def main():
|
|
17
|
+
parser=argparse.ArgumentParser(description=__doc__)
|
|
18
|
+
parser.add_argument('directory');parser.add_argument('--tag',required=True)
|
|
19
|
+
parser.add_argument('--output',default='release-artifacts.json')
|
|
20
|
+
args=parser.parse_args()
|
|
21
|
+
root=Path(__file__).resolve().parents[1]
|
|
22
|
+
project=tomllib.loads((root/'pyproject.toml').read_text())['project']
|
|
23
|
+
if args.tag!='v'+project['version']:raise ValueError('Release tag does not match package metadata')
|
|
24
|
+
folder=Path(args.directory);wheels=sorted(folder.glob('*.whl'));sources=sorted(folder.glob('*.tar.gz'))
|
|
25
|
+
if len(wheels)!=1 or len(sources)!=1 or len([p for p in folder.iterdir() if p.name!='.gitignore'])!=2:
|
|
26
|
+
raise ValueError('Publish exactly one wheel and one source distribution')
|
|
27
|
+
records=[]
|
|
28
|
+
for artifact in wheels+sources:
|
|
29
|
+
if artifact.suffix=='.whl':
|
|
30
|
+
with zipfile.ZipFile(artifact) as archive:
|
|
31
|
+
names=archive.namelist();paths=[n for n in names if n.endswith('.dist-info/METADATA')]
|
|
32
|
+
if len(paths)!=1:raise ValueError('Wheel metadata is ambiguous')
|
|
33
|
+
raw=archive.read(paths[0])
|
|
34
|
+
else:
|
|
35
|
+
with tarfile.open(artifact,'r:gz') as archive:
|
|
36
|
+
names=archive.getnames();paths=[n for n in names if n.endswith('/PKG-INFO') and n.count('/')==1]
|
|
37
|
+
if len(paths)!=1:raise ValueError('Source metadata is ambiguous')
|
|
38
|
+
stream=archive.extractfile(paths[0])
|
|
39
|
+
if stream is None:raise ValueError('Source metadata is absent')
|
|
40
|
+
with stream:raw=stream.read()
|
|
41
|
+
metadata=BytesParser().parsebytes(raw)
|
|
42
|
+
if canonical(metadata['Name'])!=canonical(project['name']) or metadata['Version']!=project['version']:
|
|
43
|
+
raise ValueError('Artifact identity does not match the selected release')
|
|
44
|
+
if metadata['Requires-Python']!=project['requires-python']:raise ValueError('Python support metadata differs')
|
|
45
|
+
if not metadata.get_payload().strip():raise ValueError('The published long description is empty')
|
|
46
|
+
if any('@' in requirement for requirement in metadata.get_all('Requires-Dist',[])):
|
|
47
|
+
raise ValueError('Published dependency metadata must use package-index requirements, including extras')
|
|
48
|
+
if not metadata.get('License-Expression') and not metadata.get('License'):raise ValueError('Declare the existing license in metadata')
|
|
49
|
+
if not any(Path(n).name.lower().startswith(('license','copying')) for n in names):raise ValueError('Artifact license text is absent')
|
|
50
|
+
for name in names:
|
|
51
|
+
path=Path(name)
|
|
52
|
+
if path.name=='.env' or '.venv' in path.parts or path.suffix in ('.tft','.safetensors','.pt','.sqlite3'):
|
|
53
|
+
raise ValueError('Private execution artifacts are outside the package release')
|
|
54
|
+
records.append({'filename':artifact.name,'bytes':artifact.stat().st_size,
|
|
55
|
+
'sha256':hashlib.sha256(artifact.read_bytes()).hexdigest()})
|
|
56
|
+
receipt={'distribution':project['name'],'version':project['version'],'tag':args.tag,'artifacts':records}
|
|
57
|
+
Path(args.output).write_text(json.dumps(receipt,indent=2)+'\n')
|
|
58
|
+
print(json.dumps(receipt,indent=2))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
if __name__=='__main__':main()
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Build receipts and installed behavior checks for wheel and source artifacts."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
from tempfile import TemporaryDirectory
|
|
8
|
+
|
|
9
|
+
ROOT = Path(__file__).resolve().parents[1]
|
|
10
|
+
|
|
11
|
+
def main():
|
|
12
|
+
directory = Path(sys.argv[1]).resolve()
|
|
13
|
+
profile = sys.argv[2] if len(sys.argv) > 2 else ''
|
|
14
|
+
artifacts = sorted([*directory.glob('*.whl'), *directory.glob('*.tar.gz')])
|
|
15
|
+
if len(artifacts) != 2:
|
|
16
|
+
raise ValueError('Select exactly one wheel and one source distribution')
|
|
17
|
+
for artifact in artifacts:
|
|
18
|
+
with TemporaryDirectory() as temporary:
|
|
19
|
+
outside = Path(temporary)
|
|
20
|
+
environment = outside / 'env'
|
|
21
|
+
subprocess.run(['uv', 'venv', str(environment), '--python', sys.executable], check=True)
|
|
22
|
+
python = environment / ('Scripts/python.exe' if sys.platform == 'win32' else 'bin/python')
|
|
23
|
+
target = str(artifact) + (f'[{profile}]' if profile else '')
|
|
24
|
+
subprocess.run(['uv', 'pip', 'install', '--python', str(python), target], check=True, cwd=outside)
|
|
25
|
+
subprocess.run([str(python), '-I', '-m', 'unittest', 'discover', '-s', str(ROOT / 'tests'), '-v'], check=True, cwd=outside)
|
|
26
|
+
subprocess.run(['uv', 'pip', 'check', '--python', str(python)], check=True, cwd=outside)
|
|
27
|
+
print(json.dumps({'artifact': artifact.name, 'sha256': hashlib.sha256(artifact.read_bytes()).hexdigest(),
|
|
28
|
+
'profile': profile or 'base', 'python': sys.version.split()[0], 'platform': sys.platform}), flush=True)
|
|
29
|
+
|
|
30
|
+
if __name__ == '__main__':
|
|
31
|
+
main()
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Deterministic worlds with optional model-neutral habitat minds."""
|
|
2
|
+
from .world import Habitat, Resident, Snapshot, Step, World
|
|
3
|
+
|
|
4
|
+
__all__ = ['Habitat', 'Resident', 'Snapshot', 'Step', 'World']
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def main():
|
|
8
|
+
from dataclasses import asdict
|
|
9
|
+
import json
|
|
10
|
+
from thoughtform import Being
|
|
11
|
+
world = World(Snapshot('pluralopia', (Habitat('woods', 'The Woods'),),
|
|
12
|
+
(Resident(Being('alice', 'Alice'), 'woods'), Resident(Being('bob', 'Bob'), 'woods'))))
|
|
13
|
+
print(json.dumps(asdict(world.step({})), ensure_ascii=True, allow_nan=False))
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Authoritative deterministic world steps; policies only propose actions."""
|
|
2
|
+
from dataclasses import dataclass, replace
|
|
3
|
+
|
|
4
|
+
from thoughtform import Action, Being, Observation
|
|
5
|
+
from thoughtform.contracts import identifier, text
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class Habitat:
|
|
10
|
+
habitat_id: str
|
|
11
|
+
name: str
|
|
12
|
+
condition: str = 'calm'
|
|
13
|
+
mind: Being | None = None
|
|
14
|
+
|
|
15
|
+
def __post_init__(self):
|
|
16
|
+
identifier(self.habitat_id, 'Habitat ID')
|
|
17
|
+
text(self.name, 'Habitat name', 256)
|
|
18
|
+
text(self.condition, 'Condition')
|
|
19
|
+
if self.mind is not None and type(self.mind) is not Being:
|
|
20
|
+
raise TypeError('Habitat mind requires a Being')
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class Resident:
|
|
25
|
+
being: Being
|
|
26
|
+
habitat_id: str
|
|
27
|
+
|
|
28
|
+
def __post_init__(self):
|
|
29
|
+
if type(self.being) is not Being:
|
|
30
|
+
raise TypeError('Resident requires a Being')
|
|
31
|
+
identifier(self.habitat_id, 'Habitat ID')
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True)
|
|
35
|
+
class Snapshot:
|
|
36
|
+
world_id: str
|
|
37
|
+
habitats: tuple[Habitat, ...]
|
|
38
|
+
residents: tuple[Resident, ...]
|
|
39
|
+
tick: int = 0
|
|
40
|
+
|
|
41
|
+
def __post_init__(self):
|
|
42
|
+
identifier(self.world_id, 'World ID')
|
|
43
|
+
if type(self.tick) is not int or not 0 <= self.tick < 2**53 - 1:
|
|
44
|
+
raise ValueError('Tick is outside its portable range')
|
|
45
|
+
if type(self.habitats) is not tuple or not 1 <= len(self.habitats) <= 32 or any(type(h) is not Habitat for h in self.habitats):
|
|
46
|
+
raise ValueError('World requires 1–32 immutable habitats')
|
|
47
|
+
if type(self.residents) is not tuple or len(self.residents) > 128 or any(type(r) is not Resident for r in self.residents):
|
|
48
|
+
raise ValueError('World requires at most 128 immutable residents')
|
|
49
|
+
habitat_ids = {h.habitat_id for h in self.habitats}
|
|
50
|
+
if len(habitat_ids) != len(self.habitats):
|
|
51
|
+
raise ValueError('Habitat IDs must be unique')
|
|
52
|
+
actors = [r.being.being_id for r in self.residents] + [h.mind.being_id for h in self.habitats if h.mind is not None]
|
|
53
|
+
if len(actors) != len(set(actors)) or len(actors) > 128:
|
|
54
|
+
raise ValueError('Actor IDs must be unique and bounded')
|
|
55
|
+
if any(r.habitat_id not in habitat_ids for r in self.residents):
|
|
56
|
+
raise ValueError('Residents require known habitats')
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(frozen=True)
|
|
60
|
+
class Step:
|
|
61
|
+
snapshot: Snapshot
|
|
62
|
+
actions: tuple[Action, ...]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class World:
|
|
66
|
+
"""A single owner; policy code is trusted but proposals have no authority."""
|
|
67
|
+
def __init__(self, snapshot):
|
|
68
|
+
if type(snapshot) is not Snapshot:
|
|
69
|
+
raise TypeError('World requires Snapshot')
|
|
70
|
+
self._snapshot = snapshot
|
|
71
|
+
self._stepping = False
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def snapshot(self):
|
|
75
|
+
return self._snapshot
|
|
76
|
+
|
|
77
|
+
def step(self, policies):
|
|
78
|
+
if self._stepping:
|
|
79
|
+
raise RuntimeError('World steps cannot be reentered')
|
|
80
|
+
self._stepping = True
|
|
81
|
+
try:
|
|
82
|
+
result = self._step(dict(policies))
|
|
83
|
+
self._snapshot = result.snapshot
|
|
84
|
+
return result
|
|
85
|
+
finally:
|
|
86
|
+
self._stepping = False
|
|
87
|
+
|
|
88
|
+
def _step(self, policies):
|
|
89
|
+
before = self.snapshot
|
|
90
|
+
locations = {r.being.being_id: r.habitat_id for r in before.residents}
|
|
91
|
+
minds = {h.mind.being_id: h.habitat_id for h in before.habitats if h.mind is not None}
|
|
92
|
+
locations.update(minds)
|
|
93
|
+
if set(policies) - set(locations):
|
|
94
|
+
raise ValueError('Policies contain unknown actors')
|
|
95
|
+
habitats = {h.habitat_id: h for h in before.habitats}
|
|
96
|
+
actions = []
|
|
97
|
+
for actor_id in sorted(locations):
|
|
98
|
+
habitat_id = locations[actor_id]
|
|
99
|
+
visible = (f'condition:{habitats[habitat_id].condition}',) + tuple(sorted(
|
|
100
|
+
r.being.being_id for r in before.residents if r.habitat_id == habitat_id))
|
|
101
|
+
observation = Observation(actor_id, before.tick, habitat_id, visible)
|
|
102
|
+
action = policies[actor_id].decide(observation) if actor_id in policies else Action(actor_id, 'wait')
|
|
103
|
+
if type(action) is not Action or action.actor_id != actor_id:
|
|
104
|
+
raise ValueError('Policy must propose an action for its own actor')
|
|
105
|
+
if action.kind == 'wait':
|
|
106
|
+
if action.target is not None or action.value is not None:
|
|
107
|
+
raise ValueError('Wait takes no target or value')
|
|
108
|
+
elif action.kind == 'move':
|
|
109
|
+
if actor_id in minds or action.target not in habitats or action.value is not None:
|
|
110
|
+
raise ValueError('Move requires a resident and known destination')
|
|
111
|
+
elif action.kind == 'say':
|
|
112
|
+
if action.target is not None or action.value is None:
|
|
113
|
+
raise ValueError('Say requires text and no target')
|
|
114
|
+
elif action.kind == 'condition':
|
|
115
|
+
if minds.get(actor_id) != action.target or action.value is None:
|
|
116
|
+
raise ValueError('Only a habitat mind can propose its own condition')
|
|
117
|
+
else:
|
|
118
|
+
raise ValueError('Unsupported world action')
|
|
119
|
+
actions.append(action)
|
|
120
|
+
# Validate every proposal against the same snapshot before committing.
|
|
121
|
+
residents = {r.being.being_id: r for r in before.residents}
|
|
122
|
+
for action in actions:
|
|
123
|
+
if action.kind == 'move':
|
|
124
|
+
residents[action.actor_id] = replace(residents[action.actor_id], habitat_id=action.target)
|
|
125
|
+
elif action.kind == 'condition':
|
|
126
|
+
habitats[action.target] = replace(habitats[action.target], condition=action.value)
|
|
127
|
+
after = replace(before, tick=before.tick + 1,
|
|
128
|
+
habitats=tuple(habitats[h.habitat_id] for h in before.habitats),
|
|
129
|
+
residents=tuple(residents[r.being.being_id] for r in before.residents))
|
|
130
|
+
return Step(after, tuple(actions))
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import unittest
|
|
2
|
+
|
|
3
|
+
from thoughtform import Action, Being
|
|
4
|
+
from paracosm import Habitat, Resident, Snapshot, World
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Policy:
|
|
8
|
+
def __init__(self, decide):
|
|
9
|
+
self.decide = decide
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def world(mind=False):
|
|
13
|
+
return World(Snapshot('test', (Habitat('woods', 'The Woods', mind=Being('forest', 'Forest', role='environment') if mind else None),
|
|
14
|
+
Habitat('village', 'Village')),
|
|
15
|
+
(Resident(Being('bob', 'Bob'), 'woods'), Resident(Being('alice', 'Alice'), 'woods'))))
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class WorldTests(unittest.TestCase):
|
|
19
|
+
def test_deterministic_order_snapshot_observations_and_step(self):
|
|
20
|
+
def episode():
|
|
21
|
+
value = world()
|
|
22
|
+
observed = []
|
|
23
|
+
def alice(observation):
|
|
24
|
+
observed.append(observation)
|
|
25
|
+
return Action('alice', 'move', 'village')
|
|
26
|
+
def bob(observation):
|
|
27
|
+
observed.append(observation)
|
|
28
|
+
return Action('bob', 'say', value='hello')
|
|
29
|
+
result = value.step({'bob': Policy(bob), 'alice': Policy(alice)})
|
|
30
|
+
self.assertEqual([o.actor_id for o in observed], ['alice', 'bob'])
|
|
31
|
+
self.assertTrue(all(o.habitat == 'woods' and 'alice' in o.visible for o in observed))
|
|
32
|
+
self.assertEqual(value.snapshot.tick, 1)
|
|
33
|
+
return result
|
|
34
|
+
self.assertEqual(episode(), episode())
|
|
35
|
+
|
|
36
|
+
def test_invalid_later_action_preserves_entire_step(self):
|
|
37
|
+
for action in (Action('bob', 'move', 'unknown'), Action('alice', 'wait'),
|
|
38
|
+
Action('bob', 'condition', 'woods', 'storm'), Action('bob', 'invent')):
|
|
39
|
+
value = world()
|
|
40
|
+
before = value.snapshot
|
|
41
|
+
with self.assertRaises(ValueError):
|
|
42
|
+
value.step({'alice': Policy(lambda o: Action('alice', 'move', 'village')),
|
|
43
|
+
'bob': Policy(lambda o: action)})
|
|
44
|
+
self.assertIs(value.snapshot, before)
|
|
45
|
+
with self.assertRaises(ValueError):
|
|
46
|
+
world().step({'unknown': Policy(lambda o: Action('unknown', 'wait'))})
|
|
47
|
+
|
|
48
|
+
def test_optional_environment_policy_is_bounded_by_world_rules(self):
|
|
49
|
+
value = world(mind=True)
|
|
50
|
+
result = value.step({'forest': Policy(lambda o: Action('forest', 'condition', o.habitat, 'rain'))})
|
|
51
|
+
self.assertEqual(result.snapshot.habitats[0].condition, 'rain')
|
|
52
|
+
before = value.snapshot
|
|
53
|
+
with self.assertRaises(ValueError):
|
|
54
|
+
value.step({'forest': Policy(lambda o: Action('forest', 'condition', 'village', 'rain'))})
|
|
55
|
+
self.assertIs(value.snapshot, before)
|
|
56
|
+
self.assertEqual(world().step({}).snapshot.tick, 1)
|
|
57
|
+
|
|
58
|
+
def test_duplicate_actor_unknown_habitat_and_reentrant_policy_are_refused(self):
|
|
59
|
+
with self.assertRaises(ValueError):
|
|
60
|
+
Snapshot('x', (Habitat('woods', 'W'),), (Resident(Being('a', 'A'), 'missing'),))
|
|
61
|
+
with self.assertRaises(ValueError):
|
|
62
|
+
Snapshot('x', (Habitat('woods', 'W', mind=Being('a', 'Mind')),), (Resident(Being('a', 'A'), 'woods'),))
|
|
63
|
+
value = world()
|
|
64
|
+
before = value.snapshot
|
|
65
|
+
with self.assertRaises(RuntimeError):
|
|
66
|
+
value.step({'alice': Policy(lambda o: value.step({}))})
|
|
67
|
+
self.assertIs(value.snapshot, before)
|