mycelium-network 0.3.1__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.
Files changed (89) hide show
  1. mycelium_network-0.3.1/LICENSE +21 -0
  2. mycelium_network-0.3.1/PKG-INFO +111 -0
  3. mycelium_network-0.3.1/README.md +80 -0
  4. mycelium_network-0.3.1/lichen/__init__.py +4 -0
  5. mycelium_network-0.3.1/lichen/api.py +303 -0
  6. mycelium_network-0.3.1/lichen/cartographer.py +337 -0
  7. mycelium_network-0.3.1/lichen/checkpoint.py +291 -0
  8. mycelium_network-0.3.1/lichen/commands.py +723 -0
  9. mycelium_network-0.3.1/lichen/engine.py +926 -0
  10. mycelium_network-0.3.1/lichen/inventory.py +79 -0
  11. mycelium_network-0.3.1/lichen/lore/lexicon.json +22 -0
  12. mycelium_network-0.3.1/lichen/lore/self_claims.yaml +8 -0
  13. mycelium_network-0.3.1/lichen/lore/structured_turn.txt +54 -0
  14. mycelium_network-0.3.1/lichen/lore/style_crimes.json +12 -0
  15. mycelium_network-0.3.1/lichen/lore/system_prompts.json +3 -0
  16. mycelium_network-0.3.1/lichen/opening.py +41 -0
  17. mycelium_network-0.3.1/lichen/premise.py +277 -0
  18. mycelium_network-0.3.1/lichen/static/index.html +1066 -0
  19. mycelium_network-0.3.1/lichen/story.py +705 -0
  20. mycelium_network-0.3.1/lichen/story_context.py +201 -0
  21. mycelium_network-0.3.1/lichen/story_journal.py +181 -0
  22. mycelium_network-0.3.1/lichen/story_migration.py +190 -0
  23. mycelium_network-0.3.1/lichen/story_objects.py +226 -0
  24. mycelium_network-0.3.1/lichen/story_observations.py +238 -0
  25. mycelium_network-0.3.1/lichen/story_presence.py +266 -0
  26. mycelium_network-0.3.1/lichen/story_scenes.py +376 -0
  27. mycelium_network-0.3.1/lichen/story_tags.py +381 -0
  28. mycelium_network-0.3.1/lichen/turn.py +139 -0
  29. mycelium_network-0.3.1/muscaria/__init__.py +1 -0
  30. mycelium_network-0.3.1/muscaria/api.py +117 -0
  31. mycelium_network-0.3.1/muscaria/engine.py +320 -0
  32. mycelium_network-0.3.1/muscaria/lore/lexicon.json +22 -0
  33. mycelium_network-0.3.1/muscaria/lore/self_claims.yaml +10 -0
  34. mycelium_network-0.3.1/muscaria/lore/style_crimes.json +12 -0
  35. mycelium_network-0.3.1/muscaria/lore/system_prompts.json +3 -0
  36. mycelium_network-0.3.1/muscaria/static/index.html +288 -0
  37. mycelium_network-0.3.1/mycelium/__init__.py +67 -0
  38. mycelium_network-0.3.1/mycelium/adventure_snapshot.py +69 -0
  39. mycelium_network-0.3.1/mycelium/api.py +305 -0
  40. mycelium_network-0.3.1/mycelium/chat_intake.py +175 -0
  41. mycelium_network-0.3.1/mycelium/chat_store.py +103 -0
  42. mycelium_network-0.3.1/mycelium/checkin.py +150 -0
  43. mycelium_network-0.3.1/mycelium/cli.py +105 -0
  44. mycelium_network-0.3.1/mycelium/composer.py +337 -0
  45. mycelium_network-0.3.1/mycelium/config.py +162 -0
  46. mycelium_network-0.3.1/mycelium/core_engine.py +362 -0
  47. mycelium_network-0.3.1/mycelium/distress.py +148 -0
  48. mycelium_network-0.3.1/mycelium/doctor.py +297 -0
  49. mycelium_network-0.3.1/mycelium/gate.py +118 -0
  50. mycelium_network-0.3.1/mycelium/lexicon.py +92 -0
  51. mycelium_network-0.3.1/mycelium/llm.py +107 -0
  52. mycelium_network-0.3.1/mycelium/lore/lexicon.json +20 -0
  53. mycelium_network-0.3.1/mycelium/lore/self_claims.yaml +8 -0
  54. mycelium_network-0.3.1/mycelium/lore/style_crimes.json +5 -0
  55. mycelium_network-0.3.1/mycelium/lore/system_prompts.json +3 -0
  56. mycelium_network-0.3.1/mycelium/memory_zones.py +530 -0
  57. mycelium_network-0.3.1/mycelium/model_routes.py +78 -0
  58. mycelium_network-0.3.1/mycelium/physics.py +68 -0
  59. mycelium_network-0.3.1/mycelium/recall.py +215 -0
  60. mycelium_network-0.3.1/mycelium/receipts.py +120 -0
  61. mycelium_network-0.3.1/mycelium/somatic_budget.py +320 -0
  62. mycelium_network-0.3.1/mycelium/static/index.html +509 -0
  63. mycelium_network-0.3.1/mycelium/static/safe_markdown.js +175 -0
  64. mycelium_network-0.3.1/mycelium/store.py +244 -0
  65. mycelium_network-0.3.1/mycelium/turn_guard.py +72 -0
  66. mycelium_network-0.3.1/mycelium/vector_index.py +294 -0
  67. mycelium_network-0.3.1/mycelium_hub/__init__.py +12 -0
  68. mycelium_network-0.3.1/mycelium_hub/app.py +160 -0
  69. mycelium_network-0.3.1/mycelium_hub/static/index.html +483 -0
  70. mycelium_network-0.3.1/mycelium_network.egg-info/PKG-INFO +111 -0
  71. mycelium_network-0.3.1/mycelium_network.egg-info/SOURCES.txt +87 -0
  72. mycelium_network-0.3.1/mycelium_network.egg-info/dependency_links.txt +1 -0
  73. mycelium_network-0.3.1/mycelium_network.egg-info/entry_points.txt +2 -0
  74. mycelium_network-0.3.1/mycelium_network.egg-info/requires.txt +9 -0
  75. mycelium_network-0.3.1/mycelium_network.egg-info/top_level.txt +5 -0
  76. mycelium_network-0.3.1/pyproject.toml +58 -0
  77. mycelium_network-0.3.1/setup.cfg +4 -0
  78. mycelium_network-0.3.1/spore/__init__.py +1 -0
  79. mycelium_network-0.3.1/spore/api.py +85 -0
  80. mycelium_network-0.3.1/spore/engine.py +480 -0
  81. mycelium_network-0.3.1/spore/lore/lexicon.json +22 -0
  82. mycelium_network-0.3.1/spore/lore/self_claims.yaml +7 -0
  83. mycelium_network-0.3.1/spore/lore/style_crimes.json +17 -0
  84. mycelium_network-0.3.1/spore/lore/system_prompts.json +3 -0
  85. mycelium_network-0.3.1/spore/patches.py +231 -0
  86. mycelium_network-0.3.1/spore/sandbox.py +346 -0
  87. mycelium_network-0.3.1/spore/static/index.html +203 -0
  88. mycelium_network-0.3.1/tests/test_hub.py +99 -0
  89. mycelium_network-0.3.1/tests/test_phase5_fruiting.py +177 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Gordon Knot
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,111 @@
1
+ Metadata-Version: 2.4
2
+ Name: mycelium-network
3
+ Version: 0.3.1
4
+ Summary: Biological AI core (semantic drag, ATP, neurochemistry, SomaticBudget, Halcyon memory) and specialized fruiting bodies (Lichen, Muscaria, Spore).
5
+ Author-email: Gordon Knot <a.edmark@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/aedmark/Mycelium
8
+ Project-URL: Repository, https://github.com/aedmark/Mycelium
9
+ Project-URL: Issues, https://github.com/aedmark/Mycelium/issues
10
+ Keywords: ai,ollama,llm,fastapi,sqlite,agent,interactive-fiction
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Web Environment
13
+ Classifier: Framework :: FastAPI
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: fastapi
23
+ Requires-Dist: uvicorn
24
+ Requires-Dist: pydantic
25
+ Requires-Dist: pyyaml
26
+ Requires-Dist: numpy
27
+ Requires-Dist: ordvec>=0.5.0
28
+ Provides-Extra: dev
29
+ Requires-Dist: pytest; extra == "dev"
30
+ Dynamic: license-file
31
+
32
+ # 🍄 Mycelium Network
33
+
34
+ The extracted biological core and its specialized fruiting bodies, grown from the BoneAmanita monolith.
35
+
36
+ - **New here?** Follow the step-by-step [Live Trial Guide](docs/LIVE_TRIAL_GUIDE.md) to try every mode in ~15 minutes.
37
+ - **Want the architecture & rationale?** Open the [3x project manual](docs/manual.html) or the [documentation map](docs/README.md).
38
+
39
+ ## Architecture
40
+ - **Mycelium (Core Chat · `/chat/`):** The shared biological core library—semantic physics with homeostasis, `SomaticBudget` & `PartnerState`, Lexical Firewall with 0 ms inline repairs and soft-crime salvage, `StageArbiter`, private bounded `/checkin`, 3-tier Memory Zones (`/remember`, `/consolidate`), `ordvec` semantic recall, credential intake screening, `ReceiptLedger` (`/api/diag`), Substrate Doctor, and Halcyon SQLite persistence.
41
+ - **Lichen (Adventure · `/lichen/`):** Text Adventure & Free Adventure with Cartographer mapping, single-custody containers, deterministic verbatim **Journal**, hidden Core-6 inline narrator tags, story-safe puzzle passwords (`in_story=True`), two-pass continuity + `/review`, and shared Stamina/Cortisol/Dopamine pacing.
42
+ - **Muscaria (Creative · `/muscaria/`):** Exploratory vs. directive creative posture, inline steering micro-tags (`[!r]`, `[!k]`, `[!l]`, `[!s]`), multi-modal image prompts (upload or `Ctrl+V` paste up to 4 images), soft-crime salvage, and Halcyon persistence.
43
+ - **Spore (Technical Kernel · `/spore/`):** Strict technical & code generation with prose-only code firewall, code-fence-safe low-ATP trimming, `POINT_OF_NO_RETURN` `/confirm` gate for irreversible commands, and opt-in jailed local workspace tooling (`SPORE_WORKSPACE`: `/ls`, `/read`, `/grep`, `/git status`, `/git diff`, `/patch` → `/confirm` with auto-rollback).
44
+
45
+ ## Quick Start
46
+
47
+ Requires **Python 3.10+** and a local **[Ollama](https://ollama.com/)** instance listening on port `11434`.
48
+
49
+ ### Install globally without cloning (recommended on Linux/Arch/macOS)
50
+
51
+ ```sh
52
+ # Pull local models (+ optional embeddings for ordvec semantic recall)
53
+ ollama pull gemma4:12b
54
+ ollama pull nomic-embed-text
55
+
56
+ # Install isolated with uv (or pipx) — avoids PEP 668 system-Python conflicts
57
+ uv tool install mycelium-network
58
+ mycelium doctor
59
+ mycelium
60
+ ```
61
+
62
+ *(Or install directly from `main`: `uv tool install "git+https://github.com/aedmark/Mycelium.git"`.)*
63
+
64
+ ### Or run from a local git clone (development)
65
+
66
+ ```sh
67
+ # 1. Create and activate a virtual environment, then install editable package + CLI
68
+ python3 -m venv .venv
69
+ source .venv/bin/activate
70
+ pip install -e .
71
+
72
+ # 2. Verify your local setup (Python, packages, SQLite, Ollama, models, embeddings)
73
+ mycelium doctor
74
+
75
+ # 3. Boot the Unified Hub (all 4 apps under one local server; add --workspace . for Spore sandbox)
76
+ mycelium --workspace .
77
+ ```
78
+
79
+ *(You can also install with `pip install -r requirements.txt` and run `uvicorn hub:app --host 127.0.0.1 --port 8000` directly, or launch any single mode via `mycelium core`, `mycelium lichen`, `mycelium muscaria`, or `mycelium spore`.)*
80
+
81
+ Open [http://127.0.0.1:8000](http://127.0.0.1:8000). On first launch, the Hub checks Ollama, lets you assign installed models per app (check **Disable reasoning (`think: false`)** for Gemma 4), and saves your choices to `~/.config/mycelium/config.json`. You can switch models live from any app's sidebar dropdown, override via env vars (`MYCELIUM_MODEL`, `LICHEN_MODEL`, `MUSCARIA_MODEL`, `SPORE_MODEL`), or inspect health anytime via **Diagnostics** in the Hub topbar.
82
+
83
+ You can also run any single app standalone:
84
+ - Core Chat: `uvicorn mycelium.api:app --host 127.0.0.1 --port 8000`
85
+ - Lichen: `uvicorn lichen.api:app --host 127.0.0.1 --port 8000`
86
+ - Muscaria: `uvicorn muscaria.api:app --host 127.0.0.1 --port 8000`
87
+ - Spore: `uvicorn spore.api:app --host 127.0.0.1 --port 8000`
88
+
89
+ ## Mode Highlights
90
+
91
+ - **Core Chat (`/chat/`):** Conversations save locally in `mycelium-chat.db` and resume across refresh or restart; **New chat** keeps older threads in **Saved chats**. Click **Check-in** (or `/checkin [2-12]`) for an ephemeral, low-pressure check-in that stays out of SQLite unless you explicitly click **Keep check-in** (`/checkin keep`). Click **Memories** (or use `/remember`, `/remember --global`, `/consolidate`, `/forget`) to inspect, pin, or delete distilled one-sentence sūtras.
92
+ - **Lichen (`/lichen/`):** Choose **Text Adventure** or **Free Adventure** in the browser. Both share Stamina, Cortisol, and Dopamine pacing and save locally in `lichen.db` (set `LICHEN_DB=other.db` for a separate campaign). Free Adventure keeps a verbatim **Journal** (`DOCS` / `QUOTES` / `CLUES` / `PACTS`) plus an optional **Show tagged spans** audit toggle. Use **Download chat snapshot** in any mapped room and **Attach Lichen snapshot** inside Core Chat (`/chat/`) to discuss your adventure with Core Chat.
93
+ - **Muscaria (`/muscaria/`):** Persists exchanges and vitals in `muscaria.db` (**New Session** resets cleanly). Prefix prompts with `[!r]` (riff), `[!k]` (tighten), `[!l]` (darker/stranger), or `[!s]` (sensory) to steer prose, and click **+ Image** or press `Ctrl+V` to attach up to four PNG, JPEG, WebP, or GIF images on vision-capable models like `gemma4:12b`.
94
+ - **Spore (`/spore/`):** Persists history and vitals in `spore.db`. Guards destructive operations (`git push --force`, `DROP TABLE`, `rm -rf`, `terraform destroy`, `deploy to prod`) behind `/confirm`. With `SPORE_WORKSPACE` set, inspects code strictly inside the jail (blocking traversal, symlink escapes, `.env*`, keys, `.db`, and credential dot-dirs) and stages surgical diffs in memory with `/patch` before applying on `/confirm` (with automatic rollback on failed `SPORE_VERIFY_CMD`).
95
+
96
+ ## Quick Command Reference
97
+
98
+ | App | Commands |
99
+ | --- | --- |
100
+ | **Core Chat** | `/checkin [2-12]`, `/checkin end`, `/checkin keep`, `/remember [--global] <fact>`, `/memories`, `/forget <id\|all>`, `/consolidate` |
101
+ | **Lichen** | `look`, `inventory`, `take <item>`, `put <item> in <container>`, `set <item> down`, `/review`, `/pause` |
102
+ | **Muscaria** | `[!r]` (riff), `[!k]` (tighten), `[!l]` (darker), `[!s]` (sensory), `/remember`, `/memories`, `/forget`, `/consolidate`, `/rest` |
103
+ | **Spore** | `/ls [path]`, `/read <path> [start-end]`, `/grep <pat> [path]`, `/git status`, `/git diff [path]`, `/context clear`, `/patch <desc>`, `/confirm`, `/discard`, `/remember`, `/memories`, `/rest` |
104
+
105
+ ## Testing & Diagnostics
106
+
107
+ ```sh
108
+ pytest # 292 offline deterministic tests (no Ollama required)
109
+ python -m mycelium.doctor # Live substrate check against local Ollama
110
+ python3 tools/check_docs.py # Repository documentation & link verification
111
+ ```
@@ -0,0 +1,80 @@
1
+ # 🍄 Mycelium Network
2
+
3
+ The extracted biological core and its specialized fruiting bodies, grown from the BoneAmanita monolith.
4
+
5
+ - **New here?** Follow the step-by-step [Live Trial Guide](docs/LIVE_TRIAL_GUIDE.md) to try every mode in ~15 minutes.
6
+ - **Want the architecture & rationale?** Open the [3x project manual](docs/manual.html) or the [documentation map](docs/README.md).
7
+
8
+ ## Architecture
9
+ - **Mycelium (Core Chat · `/chat/`):** The shared biological core library—semantic physics with homeostasis, `SomaticBudget` & `PartnerState`, Lexical Firewall with 0 ms inline repairs and soft-crime salvage, `StageArbiter`, private bounded `/checkin`, 3-tier Memory Zones (`/remember`, `/consolidate`), `ordvec` semantic recall, credential intake screening, `ReceiptLedger` (`/api/diag`), Substrate Doctor, and Halcyon SQLite persistence.
10
+ - **Lichen (Adventure · `/lichen/`):** Text Adventure & Free Adventure with Cartographer mapping, single-custody containers, deterministic verbatim **Journal**, hidden Core-6 inline narrator tags, story-safe puzzle passwords (`in_story=True`), two-pass continuity + `/review`, and shared Stamina/Cortisol/Dopamine pacing.
11
+ - **Muscaria (Creative · `/muscaria/`):** Exploratory vs. directive creative posture, inline steering micro-tags (`[!r]`, `[!k]`, `[!l]`, `[!s]`), multi-modal image prompts (upload or `Ctrl+V` paste up to 4 images), soft-crime salvage, and Halcyon persistence.
12
+ - **Spore (Technical Kernel · `/spore/`):** Strict technical & code generation with prose-only code firewall, code-fence-safe low-ATP trimming, `POINT_OF_NO_RETURN` `/confirm` gate for irreversible commands, and opt-in jailed local workspace tooling (`SPORE_WORKSPACE`: `/ls`, `/read`, `/grep`, `/git status`, `/git diff`, `/patch` → `/confirm` with auto-rollback).
13
+
14
+ ## Quick Start
15
+
16
+ Requires **Python 3.10+** and a local **[Ollama](https://ollama.com/)** instance listening on port `11434`.
17
+
18
+ ### Install globally without cloning (recommended on Linux/Arch/macOS)
19
+
20
+ ```sh
21
+ # Pull local models (+ optional embeddings for ordvec semantic recall)
22
+ ollama pull gemma4:12b
23
+ ollama pull nomic-embed-text
24
+
25
+ # Install isolated with uv (or pipx) — avoids PEP 668 system-Python conflicts
26
+ uv tool install mycelium-network
27
+ mycelium doctor
28
+ mycelium
29
+ ```
30
+
31
+ *(Or install directly from `main`: `uv tool install "git+https://github.com/aedmark/Mycelium.git"`.)*
32
+
33
+ ### Or run from a local git clone (development)
34
+
35
+ ```sh
36
+ # 1. Create and activate a virtual environment, then install editable package + CLI
37
+ python3 -m venv .venv
38
+ source .venv/bin/activate
39
+ pip install -e .
40
+
41
+ # 2. Verify your local setup (Python, packages, SQLite, Ollama, models, embeddings)
42
+ mycelium doctor
43
+
44
+ # 3. Boot the Unified Hub (all 4 apps under one local server; add --workspace . for Spore sandbox)
45
+ mycelium --workspace .
46
+ ```
47
+
48
+ *(You can also install with `pip install -r requirements.txt` and run `uvicorn hub:app --host 127.0.0.1 --port 8000` directly, or launch any single mode via `mycelium core`, `mycelium lichen`, `mycelium muscaria`, or `mycelium spore`.)*
49
+
50
+ Open [http://127.0.0.1:8000](http://127.0.0.1:8000). On first launch, the Hub checks Ollama, lets you assign installed models per app (check **Disable reasoning (`think: false`)** for Gemma 4), and saves your choices to `~/.config/mycelium/config.json`. You can switch models live from any app's sidebar dropdown, override via env vars (`MYCELIUM_MODEL`, `LICHEN_MODEL`, `MUSCARIA_MODEL`, `SPORE_MODEL`), or inspect health anytime via **Diagnostics** in the Hub topbar.
51
+
52
+ You can also run any single app standalone:
53
+ - Core Chat: `uvicorn mycelium.api:app --host 127.0.0.1 --port 8000`
54
+ - Lichen: `uvicorn lichen.api:app --host 127.0.0.1 --port 8000`
55
+ - Muscaria: `uvicorn muscaria.api:app --host 127.0.0.1 --port 8000`
56
+ - Spore: `uvicorn spore.api:app --host 127.0.0.1 --port 8000`
57
+
58
+ ## Mode Highlights
59
+
60
+ - **Core Chat (`/chat/`):** Conversations save locally in `mycelium-chat.db` and resume across refresh or restart; **New chat** keeps older threads in **Saved chats**. Click **Check-in** (or `/checkin [2-12]`) for an ephemeral, low-pressure check-in that stays out of SQLite unless you explicitly click **Keep check-in** (`/checkin keep`). Click **Memories** (or use `/remember`, `/remember --global`, `/consolidate`, `/forget`) to inspect, pin, or delete distilled one-sentence sūtras.
61
+ - **Lichen (`/lichen/`):** Choose **Text Adventure** or **Free Adventure** in the browser. Both share Stamina, Cortisol, and Dopamine pacing and save locally in `lichen.db` (set `LICHEN_DB=other.db` for a separate campaign). Free Adventure keeps a verbatim **Journal** (`DOCS` / `QUOTES` / `CLUES` / `PACTS`) plus an optional **Show tagged spans** audit toggle. Use **Download chat snapshot** in any mapped room and **Attach Lichen snapshot** inside Core Chat (`/chat/`) to discuss your adventure with Core Chat.
62
+ - **Muscaria (`/muscaria/`):** Persists exchanges and vitals in `muscaria.db` (**New Session** resets cleanly). Prefix prompts with `[!r]` (riff), `[!k]` (tighten), `[!l]` (darker/stranger), or `[!s]` (sensory) to steer prose, and click **+ Image** or press `Ctrl+V` to attach up to four PNG, JPEG, WebP, or GIF images on vision-capable models like `gemma4:12b`.
63
+ - **Spore (`/spore/`):** Persists history and vitals in `spore.db`. Guards destructive operations (`git push --force`, `DROP TABLE`, `rm -rf`, `terraform destroy`, `deploy to prod`) behind `/confirm`. With `SPORE_WORKSPACE` set, inspects code strictly inside the jail (blocking traversal, symlink escapes, `.env*`, keys, `.db`, and credential dot-dirs) and stages surgical diffs in memory with `/patch` before applying on `/confirm` (with automatic rollback on failed `SPORE_VERIFY_CMD`).
64
+
65
+ ## Quick Command Reference
66
+
67
+ | App | Commands |
68
+ | --- | --- |
69
+ | **Core Chat** | `/checkin [2-12]`, `/checkin end`, `/checkin keep`, `/remember [--global] <fact>`, `/memories`, `/forget <id\|all>`, `/consolidate` |
70
+ | **Lichen** | `look`, `inventory`, `take <item>`, `put <item> in <container>`, `set <item> down`, `/review`, `/pause` |
71
+ | **Muscaria** | `[!r]` (riff), `[!k]` (tighten), `[!l]` (darker), `[!s]` (sensory), `/remember`, `/memories`, `/forget`, `/consolidate`, `/rest` |
72
+ | **Spore** | `/ls [path]`, `/read <path> [start-end]`, `/grep <pat> [path]`, `/git status`, `/git diff [path]`, `/context clear`, `/patch <desc>`, `/confirm`, `/discard`, `/remember`, `/memories`, `/rest` |
73
+
74
+ ## Testing & Diagnostics
75
+
76
+ ```sh
77
+ pytest # 292 offline deterministic tests (no Ollama required)
78
+ python -m mycelium.doctor # Live substrate check against local Ollama
79
+ python3 tools/check_docs.py # Repository documentation & link verification
80
+ ```
@@ -0,0 +1,4 @@
1
+ """
2
+ Lichen: The Gamified Spatial Presentation Layer (Clone).
3
+ An independent container rebuilding BoneAmanita's MUD mechanics.
4
+ """
@@ -0,0 +1,303 @@
1
+ from fastapi import FastAPI
2
+ from fastapi.responses import HTMLResponse, JSONResponse
3
+ from fastapi.staticfiles import StaticFiles
4
+ from pydantic import BaseModel, ValidationError, model_validator
5
+ import os
6
+ import json
7
+ import sqlite3
8
+ from datetime import datetime, timezone
9
+ from lichen import checkpoint
10
+ from lichen.cartographer import Room
11
+ from lichen.inventory import Item
12
+ from lichen.opening import PlayMode, STARTER_ACTIONS
13
+ from lichen.story import Story
14
+ from lichen.turn import PendingTransfer
15
+ from mycelium.physics import PhysicsPacket
16
+ from mycelium.adventure_snapshot import SnapshotPickup
17
+ from typing import Literal
18
+ from uuid import UUID
19
+ from pydantic import Field, ConfigDict
20
+
21
+ from lichen.engine import PAUSE_PLAY, LichenEngine, UnresolvedTurn
22
+ from mycelium.chat_intake import has_credential
23
+ from mycelium.model_routes import attach_model_routes
24
+ from mycelium.receipts import attach_diag_route
25
+ from mycelium.turn_guard import TurnBusy, TurnGuard, TurnTimeout
26
+
27
+ app = FastAPI(title="Lichen Adventure API")
28
+
29
+ # Initialize Engine globally for the session
30
+ engine = LichenEngine()
31
+ # Chat runs off the event loop and one turn owns the world at a time.
32
+ turns = TurnGuard()
33
+
34
+ # Setup static directory
35
+ static_dir = os.path.join(os.path.dirname(__file__), "static")
36
+ os.makedirs(static_dir, exist_ok=True)
37
+ app.mount("/static", StaticFiles(directory=static_dir), name="static")
38
+ attach_model_routes(
39
+ app,
40
+ app_name="lichen",
41
+ get_llm=lambda: engine.llm,
42
+ is_busy=lambda: turns.is_busy,
43
+ )
44
+ attach_diag_route(app, engine.ledger)
45
+
46
+ class ChatRequest(BaseModel):
47
+ message: str
48
+ request_id: UUID | None = None
49
+
50
+ def state_payload():
51
+ room = None
52
+ if engine.cartographer.current_room:
53
+ r = engine.cartographer.get_room(engine.cartographer.current_room)
54
+ if r:
55
+ room = {
56
+ "name": r.name,
57
+ "description": r.visible_description(),
58
+ "pois": r.visible_points(),
59
+ "items": [item.name for item in r.available_items()],
60
+ "exits": [*r.exits, *sorted(r.uncharted_exits)],
61
+ "characters": [
62
+ {"id": str(character.character_id), "name": character.name, "description": character.description}
63
+ for character in r.characters
64
+ ],
65
+ }
66
+
67
+ vitals = {
68
+ "stamina": engine.physics.energy.stamina,
69
+ "dopamine": engine.physics.energy.dopamine,
70
+ "cortisol": engine.physics.energy.cortisol,
71
+ "drag": engine.physics.space.narrative_drag
72
+ }
73
+
74
+ inventory = engine.inventory.list_items()
75
+ inventory_items = [
76
+ {"name": item.name, "contents": [held.name for held in item.contents]}
77
+ for item in engine.inventory.inventory
78
+ ]
79
+ if engine.story is not None:
80
+ room = engine.story.scene_payload()
81
+ inventory = [entry.name for entry in engine.story.possessions]
82
+ inventory_items = [
83
+ {"name": entry.name, "contents": [held.name for held in engine.story.contents(entry)]}
84
+ for entry in engine.story.possessions
85
+ ]
86
+ starter_actions = list(STARTER_ACTIONS[engine.mode]) if (
87
+ engine.mode and engine.seeded_opening and len(engine.transcript) == 1 and not engine.visible_from
88
+ ) else []
89
+ if (engine.story and engine.story.last_beat_turn == len(engine.transcript)
90
+ and engine.story.reviewed_turn != engine.story.last_beat_turn):
91
+ starter_actions.append("/review")
92
+ if engine.can_pause_play:
93
+ starter_actions.append(PAUSE_PLAY)
94
+
95
+ return {
96
+ "mode": engine.mode,
97
+ "shared_biology": True,
98
+ "starter_actions": starter_actions,
99
+ "room": room,
100
+ "vitals": vitals,
101
+ "inventory": inventory,
102
+ # The sidebar shows what each container holds; inventory stays a name list for older callers.
103
+ "inventory_items": inventory_items,
104
+ "journal": engine.story.journal_payload() if engine.story is not None else [],
105
+ "inline_tags": engine.story.inline_tags_payload() if engine.story is not None else [],
106
+ "max_slots": engine.inventory.max_slots
107
+ }
108
+
109
+ @app.get("/api/state")
110
+ async def saved_adventure():
111
+ return JSONResponse(
112
+ {**state_payload(), "history": engine.transcript[engine.visible_from:], "cleared": bool(engine.visible_from)},
113
+ headers={"Cache-Control": "no-store"},
114
+ )
115
+
116
+ class AdventureFile(BaseModel):
117
+ model_config = ConfigDict(allow_inf_nan=False)
118
+ version: Literal[1]
119
+ mode: PlayMode | None = None
120
+ seeded_opening: bool = False
121
+ legacy_prose: bool = False
122
+ story: Story | None = None
123
+ # The typed Story fills a default version on a versionless file. Remember the
124
+ # version the file declared so checkpoint migration still recognizes an old save.
125
+ story_version: int | None = Field(default=None, exclude=True)
126
+ rooms: list[Room]
127
+ current_room: str | None
128
+ offer: tuple[str, str] | None = None
129
+ pending_transfer: PendingTransfer | None = None
130
+ pending_exit: tuple[str, str] | None
131
+ inventory: list[Item]
132
+ capacity: int = Field(ge=0)
133
+ pickups: list[SnapshotPickup]
134
+ history: list[tuple[str, str]]
135
+ transcript: list[tuple[str, str]] | None = None
136
+ visible_from: int = Field(default=0, ge=0)
137
+ turn_receipts: dict[UUID, int] = Field(default_factory=dict)
138
+ physics: PhysicsPacket
139
+
140
+ @model_validator(mode="before")
141
+ @classmethod
142
+ def note_story_version(cls, values):
143
+ story = values.get("story") if isinstance(values, dict) else None
144
+ if isinstance(story, dict):
145
+ values["story_version"] = story.get("version")
146
+ return values
147
+
148
+
149
+ @app.get("/api/adventure/save")
150
+ async def download_adventure():
151
+ return JSONResponse(checkpoint.capture(engine), headers={
152
+ "Cache-Control": "no-store",
153
+ "Content-Disposition": 'attachment; filename="lichen-adventure.json"',
154
+ })
155
+
156
+
157
+ @app.get("/api/adventure/history")
158
+ async def adventure_history():
159
+ return JSONResponse(
160
+ {"transcript": engine.transcript, "archives": checkpoint.archived_adventures(engine)},
161
+ headers={"Cache-Control": "no-store"},
162
+ )
163
+
164
+
165
+ @app.get("/api/adventure/history/{archive_id}")
166
+ async def archived_adventure(archive_id: UUID):
167
+ data = engine.store.get_record(checkpoint.ARCHIVE_PREFIX + str(archive_id))
168
+ if data is None:
169
+ return JSONResponse({"error": "Adventure history not found."}, status_code=404)
170
+ return JSONResponse(data, headers={"Cache-Control": "no-store"})
171
+
172
+
173
+ @app.post("/api/adventure/open")
174
+ async def open_adventure(save: AdventureFile, legacy_mode: PlayMode | None = None):
175
+ data = save.model_dump(mode="json")
176
+ if save.story is not None and save.story_version is None:
177
+ data["story"].pop("version", None)
178
+ transcript = save.history if save.transcript is None else save.transcript
179
+ rooms = {room.slug: room for room in save.rooms}
180
+ pending = save.pending_exit
181
+ valid_route = not pending or pending[0] in rooms and (
182
+ rooms[pending[0]].exits.get(pending[1]) == save.current_room and pending[1] in rooms[pending[0]].exits
183
+ or pending[0] == save.current_room and pending[1] in rooms[pending[0]].uncharted_exits
184
+ )
185
+ if (has_credential(json.dumps(data)) or len(rooms) != len(save.rooms)
186
+ or save.visible_from > len(transcript)
187
+ or (save.story is not None and (save.mode != "free" or save.legacy_prose))
188
+ or (save.story is not None and any(event.turn > len(transcript) for event in save.story.object_events))
189
+ or (save.story is not None and any(event.turn > len(transcript) for event in save.story.scene_events))
190
+ or (save.story is not None and any(record.turn > len(transcript) for record in save.story.observations))
191
+ or (save.story is not None and (save.story.reviewed_turn or 0) > len(transcript))
192
+ or (save.story is not None and (save.story.last_beat_turn or 0) > len(transcript))
193
+ or any(not 0 <= index < len(transcript) for index in save.turn_receipts.values())
194
+ or (save.pending_transfer and save.pending_transfer.room_id != save.current_room)
195
+ or not valid_route
196
+ or (save.current_room is not None and save.current_room not in rooms and not pending)):
197
+ return JSONResponse({"error": "Invalid adventure snapshot."}, status_code=422)
198
+ if save.mode is None and legacy_mode is None:
199
+ return JSONResponse({"error": "Choose a play mode for this older save."}, status_code=409)
200
+ data["mode"] = save.mode or legacy_mode
201
+ data["transcript"] = transcript
202
+ before = checkpoint.capture(engine)
203
+ try:
204
+ checkpoint.restore(engine, data)
205
+ checkpoint.switch_adventure(engine, before, checkpoint.capture(engine))
206
+ except (ValueError, sqlite3.Error):
207
+ checkpoint.restore(engine, before)
208
+ return JSONResponse({"error": "Could not open the adventure snapshot."}, status_code=422)
209
+ return await saved_adventure()
210
+
211
+
212
+ class AdventureAction(BaseModel):
213
+ confirmed: Literal[True]
214
+
215
+
216
+ class AdventureStart(BaseModel):
217
+ mode: PlayMode
218
+ opening: Literal["preset", "custom", "surprise"]
219
+ premise: str = Field(default="", max_length=2_000)
220
+
221
+
222
+ @app.post("/api/adventure/start")
223
+ async def start_adventure(request: AdventureStart):
224
+ if engine.mode is not None:
225
+ return JSONResponse({"error": "There is already an active adventure."}, status_code=409)
226
+ premise = request.premise.strip()
227
+ if request.opening == "custom":
228
+ if not premise:
229
+ return JSONResponse({"error": "Enter a premise before starting."}, status_code=422)
230
+ if has_credential(premise):
231
+ return JSONResponse({"error": "This premise appears to contain a credential."}, status_code=422)
232
+ elif request.opening == "surprise":
233
+ premise = "Surprise me with an opening scene."
234
+ else:
235
+ premise = None
236
+ try:
237
+ engine.start_adventure(request.mode, premise)
238
+ except (UnresolvedTurn, sqlite3.Error):
239
+ return JSONResponse(
240
+ {"error": "Could not start this adventure. Try again or choose a ready-made opening."},
241
+ status_code=503,
242
+ )
243
+ return await saved_adventure()
244
+
245
+
246
+ @app.post("/api/adventure/new")
247
+ async def new_adventure(request: AdventureAction):
248
+ try:
249
+ checkpoint.switch_adventure(engine, checkpoint.capture(engine), None)
250
+ except sqlite3.Error:
251
+ return JSONResponse({"error": "Could not save the outgoing adventure."}, status_code=503)
252
+ engine.reset_world()
253
+ return await saved_adventure()
254
+
255
+
256
+ @app.post("/api/adventure/clear")
257
+ async def clear_conversation(request: AdventureAction):
258
+ data = checkpoint.capture(engine)
259
+ data["visible_from"] = len(engine.transcript)
260
+ engine.store.put_record(checkpoint.CHECKPOINT_KEY, data)
261
+ engine.visible_from = len(engine.transcript)
262
+ return await saved_adventure()
263
+
264
+
265
+ @app.post("/api/chat")
266
+ def chat(request: ChatRequest):
267
+ try:
268
+ response_text = turns.run(
269
+ lambda abandoned: engine.process_input(
270
+ request.message, str(request.request_id) if request.request_id else None,
271
+ aborted=abandoned,
272
+ )
273
+ )
274
+ except TurnBusy:
275
+ return JSONResponse({"error": "The previous turn is still in progress."}, status_code=409)
276
+ except TurnTimeout:
277
+ return JSONResponse({"error": "This turn took too long. The world was not changed."}, status_code=504)
278
+ return {"response": response_text, **state_payload()}
279
+
280
+ @app.get("/api/context-snapshot")
281
+ async def export_snapshot():
282
+ try:
283
+ snapshot = (engine.cmd_processor.snapshot() if engine.story is None
284
+ else engine.story.snapshot(datetime.now(timezone.utc)))
285
+ except ValidationError:
286
+ return JSONResponse({"error": "The current room contains labels that cannot be shared."}, status_code=422)
287
+ if snapshot is None:
288
+ return JSONResponse({"error": "There is no mapped room to share."}, status_code=409)
289
+ if has_credential(snapshot.model_dump_json()):
290
+ return JSONResponse({"error": "The snapshot appears to contain a credential."}, status_code=422)
291
+ return JSONResponse(
292
+ snapshot.model_dump(mode="json"),
293
+ headers={
294
+ "Cache-Control": "no-store",
295
+ "Content-Disposition": 'attachment; filename="lichen-snapshot.json"',
296
+ },
297
+ )
298
+
299
+ @app.get("/", response_class=HTMLResponse)
300
+ async def serve_ui():
301
+ with open(os.path.join(static_dir, "index.html"), "r") as f:
302
+ return HTMLResponse(f.read(), headers={"Cache-Control": "no-store"})
303
+