SNAPKITTYWEST commited on
Commit
3ce1a40
·
verified ·
1 Parent(s): 22c5f69

October 2026 main drop: mirror from GitHub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +11 -0
  2. .github/workflows/ci.yml +93 -0
  3. .gitignore +21 -0
  4. HANDOFF.md +212 -0
  5. README.md +17 -0
  6. Repoverse.sln +50 -0
  7. assets/snapkitty/LICENSE +661 -0
  8. assets/snapkitty/SOURCE_README.md +55 -0
  9. assets/snapkitty/art/civilization.jpg +3 -0
  10. assets/snapkitty/art/kitten.jpg +3 -0
  11. assets/snapkitty/art/kitten.png +3 -0
  12. assets/snapkitty/art/snap-os.jpg +3 -0
  13. assets/snapkitty/art/suited-man.jpg +3 -0
  14. assets/snapkitty/art/suited-man.png +3 -0
  15. assets/snapkitty/runtime-manifest.json +34 -0
  16. assets/snapkitty/source-manifest.json +118 -0
  17. assets/snapkitty/web/preview_composite.png +3 -0
  18. docs/REPOVERSE-3D.md +93 -0
  19. docs/SNAPKITTY-GAME.md +86 -0
  20. preview/index.html +166 -0
  21. src/Repoverse.Cli/Program.cs +208 -0
  22. src/Repoverse.Cli/Repoverse.Cli.csproj +14 -0
  23. src/Repoverse.Core/Bridge/BuilderPlan.cs +69 -0
  24. src/Repoverse.Core/Bridge/LocalSourceReader.cs +32 -0
  25. src/Repoverse.Core/Bridge/WorldSession.cs +146 -0
  26. src/Repoverse.Core/Generation/Classifier.cs +124 -0
  27. src/Repoverse.Core/Generation/ManifestBuilder.cs +179 -0
  28. src/Repoverse.Core/Generation/Overrides.cs +62 -0
  29. src/Repoverse.Core/Generation/RoomGraph.cs +197 -0
  30. src/Repoverse.Core/Generation/Seed.cs +54 -0
  31. src/Repoverse.Core/Generation/WorldManifest.cs +57 -0
  32. src/Repoverse.Core/Ingestion/GitHubIngest.cs +212 -0
  33. src/Repoverse.Core/Ingestion/LocalGitIngest.cs +113 -0
  34. src/Repoverse.Core/Ingestion/SnapshotStore.cs +63 -0
  35. src/Repoverse.Core/Model/CanonicalRepository.cs +53 -0
  36. src/Repoverse.Core/Model/Derived.cs +66 -0
  37. src/Repoverse.Core/Persistence/SaveGame.cs +96 -0
  38. src/Repoverse.Core/Repoverse.Core.csproj +9 -0
  39. src/Repoverse.Core/RepoverseUri.cs +78 -0
  40. src/Repoverse.Core/Simulation/SimulationClock.cs +58 -0
  41. src/Repoverse.Core/Simulation/WorldEvents.cs +52 -0
  42. src/Repoverse.Core/Voxels/BuildingRasterizer.cs +167 -0
  43. src/Repoverse.Core/Voxels/ChunkStreamer.cs +96 -0
  44. src/Repoverse.Core/Voxels/GreedyMesher.cs +116 -0
  45. src/Repoverse.Core/Voxels/Voxel.cs +94 -0
  46. src/Repoverse.Core/Voxels/WorldGenerator.cs +151 -0
  47. src/Repoverse.Core/WorldConstants.cs +42 -0
  48. src/Repoverse.Sidecar/Program.cs +67 -0
  49. src/Repoverse.Sidecar/Repoverse.Sidecar.csproj +4 -0
  50. tests/Repoverse.Core.Tests/BridgeTests.cs +90 -0
.gitattributes CHANGED
@@ -33,3 +33,14 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/snapkitty/art/civilization.jpg filter=lfs diff=lfs merge=lfs -text
37
+ assets/snapkitty/art/kitten.jpg filter=lfs diff=lfs merge=lfs -text
38
+ assets/snapkitty/art/kitten.png filter=lfs diff=lfs merge=lfs -text
39
+ assets/snapkitty/art/snap-os.jpg filter=lfs diff=lfs merge=lfs -text
40
+ assets/snapkitty/art/suited-man.jpg filter=lfs diff=lfs merge=lfs -text
41
+ assets/snapkitty/art/suited-man.png filter=lfs diff=lfs merge=lfs -text
42
+ assets/snapkitty/web/preview_composite.png filter=lfs diff=lfs merge=lfs -text
43
+ unify/game/assets/textures/snapkitty/civilization.qoi filter=lfs diff=lfs merge=lfs -text
44
+ unify/game/assets/textures/snapkitty/kitten.qoi filter=lfs diff=lfs merge=lfs -text
45
+ unify/game/assets/textures/snapkitty/snap-os.qoi filter=lfs diff=lfs merge=lfs -text
46
+ unify/game/assets/textures/snapkitty/suited-man.qoi filter=lfs diff=lfs merge=lfs -text
.github/workflows/ci.yml ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Repoverse core
2
+
3
+ on:
4
+ push:
5
+ pull_request:
6
+
7
+ jobs:
8
+ test:
9
+ runs-on: ubuntu-latest
10
+ steps:
11
+ - uses: actions/checkout@v4
12
+ - uses: actions/setup-dotnet@v4
13
+ with:
14
+ dotnet-version: '8.0.x'
15
+ - run: dotnet build -warnaserror
16
+ - run: dotnet test --no-build
17
+ - name: Exercise the authenticated world sidecar
18
+ run: python3 tools/test-sidecar.py
19
+ - uses: actions/checkout@v4
20
+ with:
21
+ repository: SNAPKITTYWEST/BOBS-Many-Voxel-Worlds
22
+ path: sample
23
+ fetch-depth: 0 # local ingest reads commit history
24
+ - name: Generate a world from the sample monorepo
25
+ run: |
26
+ dotnet run --project src/Repoverse.Cli --no-build -- ingest-local sample --owner SNAPKITTYWEST --subprojects --out out/snapshot.json
27
+ dotnet run --project src/Repoverse.Cli --no-build -- generate --snapshot out/snapshot.json --out out/manifest.json
28
+ dotnet run --project src/Repoverse.Cli --no-build -- stats --manifest out/manifest.json
29
+
30
+ unified-engine:
31
+ runs-on: ubuntu-latest
32
+ defaults:
33
+ run:
34
+ working-directory: unified-engine
35
+ steps:
36
+ - uses: actions/checkout@v4
37
+ - uses: actions/setup-node@v4
38
+ with:
39
+ node-version: '22'
40
+ - run: npm ci
41
+ - run: npm test
42
+
43
+ unify:
44
+ runs-on: ubuntu-24.04
45
+ defaults:
46
+ run:
47
+ working-directory: unify
48
+ steps:
49
+ - uses: actions/checkout@v4
50
+ - run: sudo apt-get update && sudo apt-get install -y ninja-build libsdl2-dev
51
+ - run: cmake -S . -B build -G Ninja
52
+ - run: cmake --build build
53
+ - run: ctest --test-dir build --output-on-failure
54
+ - name: SDL backend smoke run
55
+ run: SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy ./build/unify_game --frames 240 --screenshot title.png
56
+ - uses: actions/upload-artifact@v4
57
+ with:
58
+ name: unify-playtest-screenshots
59
+ path: |
60
+ unify/build/*.png
61
+ unify/build/snapkitty-evidence/*.png
62
+
63
+ unify-sanitizers:
64
+ runs-on: ubuntu-24.04
65
+ defaults:
66
+ run:
67
+ working-directory: unify
68
+ steps:
69
+ - uses: actions/checkout@v4
70
+ - run: sudo apt-get update && sudo apt-get install -y ninja-build
71
+ - run: >
72
+ cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug
73
+ -DCMAKE_CXX_FLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer"
74
+ -DCMAKE_C_FLAGS="-fsanitize=address,undefined"
75
+ -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=address,undefined"
76
+ - run: cmake --build build
77
+ - run: ctest --test-dir build --output-on-failure
78
+ env:
79
+ UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1
80
+
81
+ unify-windows-mingw:
82
+ runs-on: windows-latest
83
+ steps:
84
+ - uses: actions/checkout@v4
85
+ - name: Build and test SDL game
86
+ shell: pwsh
87
+ run: ./tools/Build-Snapkitty.ps1
88
+ - name: Package playable game
89
+ run: python tools/package-snapkitty.py
90
+ - uses: actions/upload-artifact@v4
91
+ with:
92
+ name: Snapkitty-Windows
93
+ path: out/Snapkitty-Windows.zip
.gitignore ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ bin/
2
+ obj/
3
+ *.user
4
+ .vs/
5
+ TestResults/
6
+
7
+ # Generated by the CLI (§66): regenerate, never hand-edit.
8
+ out/
9
+ preview/world-mesh.json
10
+
11
+ # unified-engine (Node)
12
+ node_modules/
13
+
14
+ # Unreal generated host artifacts
15
+ unreal/Repoverse/Plugins/
16
+ unreal/Repoverse/Unify/
17
+ unreal/Repoverse/Binaries/
18
+ unreal/Repoverse/Intermediate/
19
+ unreal/Repoverse/Saved/
20
+ unreal/Repoverse/DerivedDataCache/
21
+ unreal/Repoverse/Content/
HANDOFF.md ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Repoverse handoff
2
+
3
+ **From:** the cloud session that built the C# core (Master Directive, Part I)
4
+ **To:** whoever builds the engine side and the back end locally (Rider, Unreal, Swift, CAD)
5
+ **State at handoff:** `dotnet build -warnaserror` is clean and all 72 tests pass. The pipeline has run end to end on real
6
+ data (the 15 sub-projects of `SNAPKITTYWEST/BOBS-Many-Voxel-Worlds`). Nothing has run inside Unreal, Swift or CAD
7
+ tooling yet. The Parts II and III directive text has not been received.
8
+
9
+ ---
10
+
11
+ ## 1. What exists
12
+
13
+ Read `README.md` for the full table. In one line: **GitHub or local git → `CanonicalRepository` → classifier →
14
+ deterministic `WorldManifest` → procedural chunks (32³, 16-bit voxels) → greedy-meshed quads**, plus snapshot
15
+ diff events, a fixed-step clock, versioned saves and `repoverse://` URIs.
16
+
17
+ | Path | Responsibility |
18
+ |---|---|
19
+ | `src/Repoverse.Core/Model/` | Canonical GitHub facts; `Derived<T>` + `Provenance` for everything inferred |
20
+ | `src/Repoverse.Core/Ingestion/` | `GitHubIngest` (REST, ETag cache, rate limits), `LocalGitIngest`, `SnapshotStore` (offline merge) |
21
+ | `src/Repoverse.Core/Generation/` | `Seed`, `Classifier`, `Overrides`, `RoomGraph`, `ManifestBuilder`, `WorldManifest` |
22
+ | `src/Repoverse.Core/Voxels/` | `Voxel`/`Chunk`, `BuildingRasterizer`, `WorldGenerator`, `WorldEdits`, `ChunkStreamer`, `GreedyMesher` |
23
+ | `src/Repoverse.Core/Simulation/` | `WorldEvents` + `SnapshotDiff`, `SimulationClock` |
24
+ | `src/Repoverse.Core/Persistence/` | `SaveGame` (schema 2, v1 migration) |
25
+ | `src/Repoverse.Core/WorldConstants.cs` | Every tunable dimension; change numbers here only |
26
+ | `src/Repoverse.Cli/` | `ingest-local`, `ingest-github`, `generate`, `stats`, `export-mesh`, `diff` |
27
+ | `preview/index.html` | Three.js viewer for `export-mesh` output. A debugging aid, not the game |
28
+ | `tests/` | 72 behaviour tests; run `dotnet test` before and after every change to the core |
29
+
30
+ ---
31
+
32
+ ## 2. Contracts the back end must honour
33
+
34
+ The **C# types are the source of truth**. The JSON below is what they serialise to (`Json.Options`: camelCase,
35
+ enums as camelCase strings, nulls omitted). If you need a field, add it in C# and bump the schema version.
36
+ Don't patch the JSON.
37
+
38
+ ### 2.1 World manifest (`generate` → `manifest.json`, schema 1)
39
+
40
+ ```jsonc
41
+ {
42
+ "schemaVersion": 1, "generator": "repoverse-gen/1", "worldSeed": "000000005aa4c177",
43
+ "snapshots": { "snapkittywest/guppy": "git:<sha>" }, // repo key → snapshot id it was built from
44
+ "buildings": [{
45
+ "repo": "SNAPKITTYWEST/guppy", // display form; identity is the lower-cased key
46
+ "category": { "value": "compiler", "why": { "rule": "classifier:rules", "evidence": "mentions-compiler (score 5)" } },
47
+ "district": { "value": "kernel", "why": { ... } },
48
+ "archetype": { "value": "foundry", "why": { ... } },
49
+ "material": "metal",
50
+ "plot": { "district": "kernel", "slot": 0 }, // sticky across regenerations (pass --previous)
51
+ "footprint": { "x": 257, "z": 254, "width": 14, "depth": 19 }, // voxel units, ground plane
52
+ "floors": 1, "roomsPerSide": 2, "roomDepth": 6, "height": 7,
53
+ "activity": { "value": "low", "why": { ... } }, // dormant | low | moderate | high
54
+ "construction": { "value": "unreleased", "why": { ... } }, // unreleased | prerelease | released | archived
55
+ "landmark": false, "population": 1, "seed": "d17a3db530f2e546",
56
+ "interior": {
57
+ "rooms": [{ "id": 3, "name": "examples", "purpose": "workshop", "floor": 0, "directories": ["examples"],
58
+ "fileCount": 3, "artifacts": [{ "path": "examples/grover_2qubit.py", "kind": "sourceTerminal",
59
+ "sizeBytes": 4083, "language": "Python" }] }],
60
+ "doors": [{ "a": 0, "b": 1 }]
61
+ }
62
+ }],
63
+ "dependencies": [{ "from": "owner/a", "to": "owner/b" }]
64
+ }
65
+ ```
66
+
67
+ **Rule:** Unreal actors are built *from* this and never written back into it (§5). The same snapshot, seed and
68
+ previous manifest must always produce byte-identical JSON; `GenerationTests` enforces this.
69
+
70
+ ### 2.2 Voxels and chunks
71
+
72
+ - `Voxel` is a `ushort`: bits 0–7 `BlockType`, bits 8–11 `MaterialFamily`, bits 12–15 state (activity level for
73
+ walls, floors and roofs). `MeshKey = packed & 0x0FFF`, and one material/draw group per key.
74
+ - A chunk is 32×32×32, indexed as `(y * 32 + z) * 32 + x`. Chunk Y layers run from 0 to `WorldGenerator.MaxChunkY`
75
+ (currently 2).
76
+ - World units are **1 voxel = 1 unit**. Pick one Unreal scale and put it in one place. Suggested: 1 voxel = 50 cm,
77
+ a 6-voxel storey = 3 m.
78
+ - Axes: **Y is up** in the core. Unreal is Z-up, so map core (x, y, z) → UE (x, z, y) and flip winding, or
79
+ mirror one axis. Do it in exactly one conversion function.
80
+ - `GreedyMesher.Build(chunk, neighbourSampler)` → `Quad(axis, positive, layer, u, v, width, height, meshKey)`.
81
+ `GreedyMesher.Corners()` returns counter-clockwise world-space corners (core handedness). Pass a
82
+ neighbour sampler, or chunk-border faces will not be culled.
83
+ - Interactive things are **not voxels**. `BuildingRasterizer.Objects(building)` yields `WorldObject`
84
+ (id, repo, x, y, z, kind, sourcePath, roomId, actions). Spawn these as actors or instances.
85
+ - `BuildingRasterizer.Plan(building)` gives each room's voxel rectangle and floor Y. Use it for cutaway,
86
+ floor isolation and room highlighting.
87
+
88
+ ### 2.3 Other formats
89
+
90
+ | Format | Where | Notes |
91
+ |---|---|---|
92
+ | Snapshot | `Ingestion/SnapshotStore.cs` | schema 1; last-known-good; written atomically |
93
+ | Save | `Persistence/SaveGame.cs` | schema 2; player + edits + tick only; add migrations to `Migrations` |
94
+ | Events | `Simulation/WorldEvents.cs` | typed records; `SnapshotDiff.Diff(before, after)` produces them |
95
+ | URI | `RepoverseUri.cs` | `repoverse://owner/repo/path#L12`, `?room=N`, `@x,y,z` |
96
+ | Mesh export | `Cli/Program.cs` `export-mesh` | **debug format only**: enum names here are PascalCase, unlike the manifest. Don't build the engine on it; use §3.1 |
97
+
98
+ ---
99
+
100
+ ## 3. What to build next, in order
101
+
102
+ Order follows the directive's vertical-slice rule (§55–57): get one district walkable end to end before scaling.
103
+
104
+ ### P0: finish the Part I vertical slice
105
+
106
+ **3.1 C# ↔ Unreal bridge (decide first; everything else depends on it)**
107
+ The core is .NET 8 and Unreal is C++. The options, in my recommended order:
108
+
109
+ 1. **Sidecar process (recommended to start).** Run the core as a local server. An Unreal C++ plugin talks to it
110
+ over a named pipe or localhost TCP with length-prefixed binary messages. It's the easiest to debug
111
+ (both sides test alone), the core stays engine-free, and the repo already uses this pattern
112
+ (`voxel/server/QuantumVoxelServer.cs` in BOBS-Many-Voxel-Worlds). Minimum messages: `LoadManifest`,
113
+ `SetFocus(x,z)` → stream `ChunkMesh`/`ChunkUnloaded`, `GetObjects(buildingKey)`, `ApplyEdit`, `Save`/`Load`,
114
+ `Events` (push).
115
+ 2. **Embed .NET in Unreal via `hostfxr`.** In-process with no IPC cost, but you own the hosting and threading.
116
+ 3. **UnrealSharp or a similar plugin.** Quickest to write gameplay in C#, but it's a third-party dependency on
117
+ your engine version.
118
+
119
+ *Done when:* Unreal shows the chunks around a focus point, updates as the focus moves, and memory stays flat
120
+ while travelling (mirror `VoxelTests.Streaming_memory_is_bounded_by_radius_while_travelling`).
121
+
122
+ **3.2 Unreal chunk rendering (C++)**
123
+ - Build one mesh section per `MeshKey` from `Quad`s. Use `RealtimeMeshComponent` or
124
+ `UProceduralMeshComponent`, and do not spawn one actor per voxel (§14).
125
+ - Collision comes from the same quads (complex-as-simple is fine to start).
126
+ - Map `MaterialFamily` × `BlockType` to material instances. Windows are translucent.
127
+ - *Done when:* the 15-building district renders at target frame rate, and `stat unit` and draw calls are logged
128
+ (§44).
129
+
130
+ **3.3 Player, interaction, camera modes**
131
+ - First/third-person walk with collision. Enter through the east-wall door (`Plan().Entrance`) and climb the
132
+ ladder shaft between floors.
133
+ - Interaction comes from `WorldObject.Actions` (the object advertises its verbs; the player code doesn't
134
+ hard-code them, §52).
135
+ - Camera modes World, Architectural Orbit (roof hide via `BlockType.Roof`, floor isolation via
136
+ `Plan().Rooms[].FloorY`), Code and City Overview. Selection is one `repoverse://` URI shared by all modes (§73).
137
+ - *Done when:* you can walk the whole §57 success path: enter building → pick room → pick file → Code
138
+ Mode → back outside → travel → quit → reload → same state.
139
+
140
+ **3.4 Source inspection**
141
+ - Fetch file contents on demand: from the GitHub contents API, via `GitHubIngest`'s cache pattern, or from a
142
+ local clone. Page large files (§38). Nothing is fetched at manifest time.
143
+
144
+ **3.5 Save/load wiring**
145
+ - On quit, `SaveGame.Capture(manifest, player, edits, clock.Tick)`; on boot, `Read` then `RestoreEdits`. Player
146
+ position and mode must come back exactly.
147
+
148
+ **3.6 Dependency extraction** (core, C#)
149
+ - Fill `CanonicalRepository.DependsOn` by parsing `Cargo.toml`, `package.json`, `*.csproj`, `go.mod`,
150
+ `pyproject.toml`/`requirements.txt` and `.gitmodules`, matched against repos in the world. Edges then flow
151
+ into the manifest automatically, with a test for each format.
152
+
153
+ ### P1: control plane and navigation
154
+
155
+ - **Swift control plane (§33–34).** An `AppState` holding selection, camera, overlays, simulation state and
156
+ graph filters, bridged to the engine. It controls intent only and must never copy world data. Every toggle
157
+ in §34 must change real filter state (add a test per toggle).
158
+ - **CSS design tokens (§35).** Spacing, radii, blur, type scale, status colours, focus, hover, selected,
159
+ disabled and stale states. Pair each colour with a shape or icon (§70). Use it for any HTML/UMG-web overlays.
160
+ - **Graph Mode (§21).** Draw `dependencies` edges between buildings, filterable by category and depth.
161
+ - **Search, command palette, world map, bookmarks, fast travel (§48–50, §74–75).** The data is already there:
162
+ manifest buildings plus artifacts plus `RepoverseUri`.
163
+ - **Live sync loop.** Periodic `ingest-github`, then `SnapshotDiff`, then events drive visuals (§26, §92):
164
+ release → illumination, archived → archive state, new files → rebuild that building's chunks only.
165
+
166
+ ### P2: later
167
+
168
+ - CAD import pipeline, offline only (§24): DWG/DXF/IFC → cleaned mesh + metadata → packaged asset,
169
+ referenced from `Overrides` (`landmark`, custom archetype).
170
+ - Audio, accessibility pass, and diagnostics overlay (§61, §69–70).
171
+ - Parts II and III (agents, simulation, 388-repo scale, packaging), once the directive text is available.
172
+
173
+ ---
174
+
175
+ ## 4. Known gaps in the core (fix before scaling to 388 repos)
176
+
177
+ | Gap | Where | Impact |
178
+ |---|---|---|
179
+ | **District overflow throws.** Each district holds 144 plots, and a 145th repo in one district fails the whole build | `ManifestBuilder.Build` | Likely to hit at 388 repos if the classifier skews. Needs §85 expansion (a new ring or an overflow district) |
180
+ | `DependsOn` never populated | ingesters | Graph Mode has no data (see 3.6) |
181
+ | Contributors capped at 100 (1 page); recent commits capped at 300 (3 pages) | `GitHubIngest` | Fine for activity levels; wrong as absolute counts |
182
+ | `.v` counts as both Coq and Verilog | `Classifier` | Ties break by enum order; provenance shows it. Use overrides |
183
+ | One floor plan (a corridor spine) for every archetype | `BuildingRasterizer` | Buildings read alike; archetype shells are future work |
184
+ | Headers are added on every `GitHubIngest` construction | `GitHubIngest` ctor | Duplicate headers if one `HttpClient` is reused. Give each ingest its own client, or move the headers onto the request |
185
+ | Local ingest treats git tags as releases, whole-repo only | `LocalGitIngest` | Sub-project buildings always show `unreleased` (scaffolding) |
186
+ | Classifier is keyword rules | `Classifier` | Fine for a slice. An AI classifier must follow §82 (cached, versioned, overridable, never blocking) |
187
+
188
+ ---
189
+
190
+ ## 5. Setup
191
+
192
+ ```bash
193
+ # .NET 8 SDK + git
194
+ dotnet build -warnaserror && dotnet test
195
+ dotnet run --project src/Repoverse.Cli -- ingest-local <any-git-checkout> --owner SNAPKITTYWEST --subprojects --out out/snapshot.json
196
+ dotnet run --project src/Repoverse.Cli -- generate --snapshot out/snapshot.json --out out/manifest.json
197
+ dotnet run --project src/Repoverse.Cli -- stats --manifest out/manifest.json
198
+ GITHUB_TOKEN=<fine-grained, read-only> dotnet run --project src/Repoverse.Cli -- ingest-github SNAPKITTYWEST --out out/snapshot.json
199
+ ```
200
+
201
+ Keep the token in the environment or the OS keychain, never in files (§41). `GitHubIngest.Redact` scrubs
202
+ tokens from error text.
203
+
204
+ ## 6. Decisions you need to make
205
+
206
+ 1. **Bridge:** sidecar, hostfxr or UnrealSharp (3.1). I recommend the sidecar.
207
+ 2. **Unreal version and mesh component:** RealtimeMesh plugin or built-in ProceduralMesh.
208
+ 3. **Voxel scale in Unreal:** 50 cm is suggested.
209
+ 4. **Swift's target platform:** macOS only, or an iPad companion over the network. This decides whether Swift
210
+ talks to the engine in-process or over the same sidecar protocol.
211
+ 5. **Scope of the first live ingest:** all 349 public repos plus private ones, or a curated list via
212
+ `ingest-github --limit` / overrides.
README.md ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - snapkitty
4
+ - october-2026-drop
5
+ - csharp
6
+ - c++
7
+ - c
8
+ - lua
9
+ - javascript
10
+ - voxel
11
+ - game
12
+ - visualization
13
+ - community
14
+ ---
15
+
16
+ > Mirrored from [https://github.com/SNAPKITTYWEST/repoverse](https://github.com/SNAPKITTYWEST/repoverse) at commit `90d5c60`. Part of the **SnapKitty October 2026 main drop**.
17
+
Repoverse.sln ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 
2
+ Microsoft Visual Studio Solution File, Format Version 12.00
3
+ # Visual Studio Version 17
4
+ VisualStudioVersion = 17.0.31903.59
5
+ MinimumVisualStudioVersion = 10.0.40219.1
6
+ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{196A873E-0AA4-4B28-B58D-D2936643B90D}"
7
+ EndProject
8
+ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Repoverse.Core", "src\Repoverse.Core\Repoverse.Core.csproj", "{FB897333-4192-456C-A1EA-B3B741592B1F}"
9
+ EndProject
10
+ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Repoverse.Cli", "src\Repoverse.Cli\Repoverse.Cli.csproj", "{A7AECCC2-1FB7-4326-8410-A4673DAAC665}"
11
+ EndProject
12
+ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{5F82D87A-4CE3-468B-9DFD-AC07CB8E0F7F}"
13
+ EndProject
14
+ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Repoverse.Core.Tests", "tests\Repoverse.Core.Tests\Repoverse.Core.Tests.csproj", "{72CB5AFA-688D-4237-A5D7-40BC49B555B0}"
15
+ EndProject
16
+ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Repoverse.Sidecar", "src\Repoverse.Sidecar\Repoverse.Sidecar.csproj", "{0AB89BF5-CB58-4F06-9753-77D84414244B}"
17
+ EndProject
18
+ Global
19
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
20
+ Debug|Any CPU = Debug|Any CPU
21
+ Release|Any CPU = Release|Any CPU
22
+ EndGlobalSection
23
+ GlobalSection(SolutionProperties) = preSolution
24
+ HideSolutionNode = FALSE
25
+ EndGlobalSection
26
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
27
+ {FB897333-4192-456C-A1EA-B3B741592B1F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
28
+ {FB897333-4192-456C-A1EA-B3B741592B1F}.Debug|Any CPU.Build.0 = Debug|Any CPU
29
+ {FB897333-4192-456C-A1EA-B3B741592B1F}.Release|Any CPU.ActiveCfg = Release|Any CPU
30
+ {FB897333-4192-456C-A1EA-B3B741592B1F}.Release|Any CPU.Build.0 = Release|Any CPU
31
+ {A7AECCC2-1FB7-4326-8410-A4673DAAC665}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
32
+ {A7AECCC2-1FB7-4326-8410-A4673DAAC665}.Debug|Any CPU.Build.0 = Debug|Any CPU
33
+ {A7AECCC2-1FB7-4326-8410-A4673DAAC665}.Release|Any CPU.ActiveCfg = Release|Any CPU
34
+ {A7AECCC2-1FB7-4326-8410-A4673DAAC665}.Release|Any CPU.Build.0 = Release|Any CPU
35
+ {72CB5AFA-688D-4237-A5D7-40BC49B555B0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
36
+ {72CB5AFA-688D-4237-A5D7-40BC49B555B0}.Debug|Any CPU.Build.0 = Debug|Any CPU
37
+ {72CB5AFA-688D-4237-A5D7-40BC49B555B0}.Release|Any CPU.ActiveCfg = Release|Any CPU
38
+ {72CB5AFA-688D-4237-A5D7-40BC49B555B0}.Release|Any CPU.Build.0 = Release|Any CPU
39
+ {0AB89BF5-CB58-4F06-9753-77D84414244B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
40
+ {0AB89BF5-CB58-4F06-9753-77D84414244B}.Debug|Any CPU.Build.0 = Debug|Any CPU
41
+ {0AB89BF5-CB58-4F06-9753-77D84414244B}.Release|Any CPU.ActiveCfg = Release|Any CPU
42
+ {0AB89BF5-CB58-4F06-9753-77D84414244B}.Release|Any CPU.Build.0 = Release|Any CPU
43
+ EndGlobalSection
44
+ GlobalSection(NestedProjects) = preSolution
45
+ {FB897333-4192-456C-A1EA-B3B741592B1F} = {196A873E-0AA4-4B28-B58D-D2936643B90D}
46
+ {A7AECCC2-1FB7-4326-8410-A4673DAAC665} = {196A873E-0AA4-4B28-B58D-D2936643B90D}
47
+ {72CB5AFA-688D-4237-A5D7-40BC49B555B0} = {5F82D87A-4CE3-468B-9DFD-AC07CB8E0F7F}
48
+ {0AB89BF5-CB58-4F06-9753-77D84414244B} = {196A873E-0AA4-4B28-B58D-D2936643B90D}
49
+ EndGlobalSection
50
+ EndGlobal
assets/snapkitty/LICENSE ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU AFFERO GENERAL PUBLIC LICENSE
2
+ Version 3, 19 November 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU Affero General Public License is a free, copyleft license for
11
+ software and other kinds of works, specifically designed to ensure
12
+ cooperation with the community in the case of network server software.
13
+
14
+ The licenses for most software and other practical works are designed
15
+ to take away your freedom to share and change the works. By contrast,
16
+ our General Public Licenses are intended to guarantee your freedom to
17
+ share and change all versions of a program--to make sure it remains free
18
+ software for all its users.
19
+
20
+ When we speak of free software, we are referring to freedom, not
21
+ price. Our General Public Licenses are designed to make sure that you
22
+ have the freedom to distribute copies of free software (and charge for
23
+ them if you wish), that you receive source code or can get it if you
24
+ want it, that you can change the software or use pieces of it in new
25
+ free programs, and that you know you can do these things.
26
+
27
+ Developers that use our General Public Licenses protect your rights
28
+ with two steps: (1) assert copyright on the software, and (2) offer
29
+ you this License which gives you legal permission to copy, distribute
30
+ and/or modify the software.
31
+
32
+ A secondary benefit of defending all users' freedom is that
33
+ improvements made in alternate versions of the program, if they
34
+ receive widespread use, become available for other developers to
35
+ incorporate. Many developers of free software are heartened and
36
+ encouraged by the resulting cooperation. However, in the case of
37
+ software used on network servers, this result may fail to come about.
38
+ The GNU General Public License permits making a modified version and
39
+ letting the public access it on a server without ever releasing its
40
+ source code to the public.
41
+
42
+ The GNU Affero General Public License is designed specifically to
43
+ ensure that, in such cases, the modified source code becomes available
44
+ to the community. It requires the operator of a network server to
45
+ provide the source code of the modified version running there to the
46
+ users of that server. Therefore, public use of a modified version, on
47
+ a publicly accessible server, gives the public access to the source
48
+ code of the modified version.
49
+
50
+ An older license, called the Affero General Public License and
51
+ published by Affero, was designed to accomplish similar goals. This is
52
+ a different license, not a version of the Affero GPL, but Affero has
53
+ released a new version of the Affero GPL which permits relicensing under
54
+ this license.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ TERMS AND CONDITIONS
60
+
61
+ 0. Definitions.
62
+
63
+ "This License" refers to version 3 of the GNU Affero General Public License.
64
+
65
+ "Copyright" also means copyright-like laws that apply to other kinds of
66
+ works, such as semiconductor masks.
67
+
68
+ "The Program" refers to any copyrightable work licensed under this
69
+ License. Each licensee is addressed as "you". "Licensees" and
70
+ "recipients" may be individuals or organizations.
71
+
72
+ To "modify" a work means to copy from or adapt all or part of the work
73
+ in a fashion requiring copyright permission, other than the making of an
74
+ exact copy. The resulting work is called a "modified version" of the
75
+ earlier work or a work "based on" the earlier work.
76
+
77
+ A "covered work" means either the unmodified Program or a work based
78
+ on the Program.
79
+
80
+ To "propagate" a work means to do anything with it that, without
81
+ permission, would make you directly or secondarily liable for
82
+ infringement under applicable copyright law, except executing it on a
83
+ computer or modifying a private copy. Propagation includes copying,
84
+ distribution (with or without modification), making available to the
85
+ public, and in some countries other activities as well.
86
+
87
+ To "convey" a work means any kind of propagation that enables other
88
+ parties to make or receive copies. Mere interaction with a user through
89
+ a computer network, with no transfer of a copy, is not conveying.
90
+
91
+ An interactive user interface displays "Appropriate Legal Notices"
92
+ to the extent that it includes a convenient and prominently visible
93
+ feature that (1) displays an appropriate copyright notice, and (2)
94
+ tells the user that there is no warranty for the work (except to the
95
+ extent that warranties are provided), that licensees may convey the
96
+ work under this License, and how to view a copy of this License. If
97
+ the interface presents a list of user commands or options, such as a
98
+ menu, a prominent item in the list meets this criterion.
99
+
100
+ 1. Source Code.
101
+
102
+ The "source code" for a work means the preferred form of the work
103
+ for making modifications to it. "Object code" means any non-source
104
+ form of a work.
105
+
106
+ A "Standard Interface" means an interface that either is an official
107
+ standard defined by a recognized standards body, or, in the case of
108
+ interfaces specified for a particular programming language, one that
109
+ is widely used among developers working in that language.
110
+
111
+ The "System Libraries" of an executable work include anything, other
112
+ than the work as a whole, that (a) is included in the normal form of
113
+ packaging a Major Component, but which is not part of that Major
114
+ Component, and (b) serves only to enable use of the work with that
115
+ Major Component, or to implement a Standard Interface for which an
116
+ implementation is available to the public in source code form. A
117
+ "Major Component", in this context, means a major essential component
118
+ (kernel, window system, and so on) of the specific operating system
119
+ (if any) on which the executable work runs, or a compiler used to
120
+ produce the work, or an object code interpreter used to run it.
121
+
122
+ The "Corresponding Source" for a work in object code form means all
123
+ the source code needed to generate, install, and (for an executable
124
+ work) run the object code and to modify the work, including scripts to
125
+ control those activities. However, it does not include the work's
126
+ System Libraries, or general-purpose tools or generally available free
127
+ programs which are used unmodified in performing those activities but
128
+ which are not part of the work. For example, Corresponding Source
129
+ includes interface definition files associated with source files for
130
+ the work, and the source code for shared libraries and dynamically
131
+ linked subprograms that the work is specifically designed to require,
132
+ such as by intimate data communication or control flow between those
133
+ subprograms and other parts of the work.
134
+
135
+ The Corresponding Source need not include anything that users
136
+ can regenerate automatically from other parts of the Corresponding
137
+ Source.
138
+
139
+ The Corresponding Source for a work in source code form is that
140
+ same work.
141
+
142
+ 2. Basic Permissions.
143
+
144
+ All rights granted under this License are granted for the term of
145
+ copyright on the Program, and are irrevocable provided the stated
146
+ conditions are met. This License explicitly affirms your unlimited
147
+ permission to run the unmodified Program. The output from running a
148
+ covered work is covered by this License only if the output, given its
149
+ content, constitutes a covered work. This License acknowledges your
150
+ rights of fair use or other equivalent, as provided by copyright law.
151
+
152
+ You may make, run and propagate covered works that you do not
153
+ convey, without conditions so long as your license otherwise remains
154
+ in force. You may convey covered works to others for the sole purpose
155
+ of having them make modifications exclusively for you, or provide you
156
+ with facilities for running those works, provided that you comply with
157
+ the terms of this License in conveying all material for which you do
158
+ not control copyright. Those thus making or running the covered works
159
+ for you must do so exclusively on your behalf, under your direction
160
+ and control, on terms that prohibit them from making any copies of
161
+ your copyrighted material outside their relationship with you.
162
+
163
+ Conveying under any other circumstances is permitted solely under
164
+ the conditions stated below. Sublicensing is not allowed; section 10
165
+ makes it unnecessary.
166
+
167
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168
+
169
+ No covered work shall be deemed part of an effective technological
170
+ measure under any applicable law fulfilling obligations under article
171
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172
+ similar laws prohibiting or restricting circumvention of such
173
+ measures.
174
+
175
+ When you convey a covered work, you waive any legal power to forbid
176
+ circumvention of technological measures to the extent such circumvention
177
+ is effected by exercising rights under this License with respect to
178
+ the covered work, and you disclaim any intention to limit operation or
179
+ modification of the work as a means of enforcing, against the work's
180
+ users, your or third parties' legal rights to forbid circumvention of
181
+ technological measures.
182
+
183
+ 4. Conveying Verbatim Copies.
184
+
185
+ You may convey verbatim copies of the Program's source code as you
186
+ receive it, in any medium, provided that you conspicuously and
187
+ appropriately publish on each copy an appropriate copyright notice;
188
+ keep intact all notices stating that this License and any
189
+ non-permissive terms added in accord with section 7 apply to the code;
190
+ keep intact all notices of the absence of any warranty; and give all
191
+ recipients a copy of this License along with the Program.
192
+
193
+ You may charge any price or no price for each copy that you convey,
194
+ and you may offer support or warranty protection for a fee.
195
+
196
+ 5. Conveying Modified Source Versions.
197
+
198
+ You may convey a work based on the Program, or the modifications to
199
+ produce it from the Program, in the form of source code under the
200
+ terms of section 4, provided that you also meet all of these conditions:
201
+
202
+ a) The work must carry prominent notices stating that you modified
203
+ it, and giving a relevant date.
204
+
205
+ b) The work must carry prominent notices stating that it is
206
+ released under this License and any conditions added under section
207
+ 7. This requirement modifies the requirement in section 4 to
208
+ "keep intact all notices".
209
+
210
+ c) You must license the entire work, as a whole, under this
211
+ License to anyone who comes into possession of a copy. This
212
+ License will therefore apply, along with any applicable section 7
213
+ additional terms, to the whole of the work, and all its parts,
214
+ regardless of how they are packaged. This License gives no
215
+ permission to license the work in any other way, but it does not
216
+ invalidate such permission if you have separately received it.
217
+
218
+ d) If the work has interactive user interfaces, each must display
219
+ Appropriate Legal Notices; however, if the Program has interactive
220
+ interfaces that do not display Appropriate Legal Notices, your
221
+ work need not make them do so.
222
+
223
+ A compilation of a covered work with other separate and independent
224
+ works, which are not by their nature extensions of the covered work,
225
+ and which are not combined with it such as to form a larger program,
226
+ in or on a volume of a storage or distribution medium, is called an
227
+ "aggregate" if the compilation and its resulting copyright are not
228
+ used to limit the access or legal rights of the compilation's users
229
+ beyond what the individual works permit. Inclusion of a covered work
230
+ in an aggregate does not cause this License to apply to the other
231
+ parts of the aggregate.
232
+
233
+ 6. Conveying Non-Source Forms.
234
+
235
+ You may convey a covered work in object code form under the terms
236
+ of sections 4 and 5, provided that you also convey the
237
+ machine-readable Corresponding Source under the terms of this License,
238
+ in one of these ways:
239
+
240
+ a) Convey the object code in, or embodied in, a physical product
241
+ (including a physical distribution medium), accompanied by the
242
+ Corresponding Source fixed on a durable physical medium
243
+ customarily used for software interchange.
244
+
245
+ b) Convey the object code in, or embodied in, a physical product
246
+ (including a physical distribution medium), accompanied by a
247
+ written offer, valid for at least three years and valid for as
248
+ long as you offer spare parts or customer support for that product
249
+ model, to give anyone who possesses the object code either (1) a
250
+ copy of the Corresponding Source for all the software in the
251
+ product that is covered by this License, on a durable physical
252
+ medium customarily used for software interchange, for a price no
253
+ more than your reasonable cost of physically performing this
254
+ conveying of source, or (2) access to copy the
255
+ Corresponding Source from a network server at no charge.
256
+
257
+ c) Convey individual copies of the object code with a copy of the
258
+ written offer to provide the Corresponding Source. This
259
+ alternative is allowed only occasionally and noncommercially, and
260
+ only if you received the object code with such an offer, in accord
261
+ with subsection 6b.
262
+
263
+ d) Convey the object code by offering access from a designated
264
+ place (gratis or for a charge), and offer equivalent access to the
265
+ Corresponding Source in the same way through the same place at no
266
+ further charge. You need not require recipients to copy the
267
+ Corresponding Source along with the object code. If the place to
268
+ copy the object code is a network server, the Corresponding Source
269
+ may be on a different server (operated by you or a third party)
270
+ that supports equivalent copying facilities, provided you maintain
271
+ clear directions next to the object code saying where to find the
272
+ Corresponding Source. Regardless of what server hosts the
273
+ Corresponding Source, you remain obligated to ensure that it is
274
+ available for as long as needed to satisfy these requirements.
275
+
276
+ e) Convey the object code using peer-to-peer transmission, provided
277
+ you inform other peers where the object code and Corresponding
278
+ Source of the work are being offered to the general public at no
279
+ charge under subsection 6d.
280
+
281
+ A separable portion of the object code, whose source code is excluded
282
+ from the Corresponding Source as a System Library, need not be
283
+ included in conveying the object code work.
284
+
285
+ A "User Product" is either (1) a "consumer product", which means any
286
+ tangible personal property which is normally used for personal, family,
287
+ or household purposes, or (2) anything designed or sold for incorporation
288
+ into a dwelling. In determining whether a product is a consumer product,
289
+ doubtful cases shall be resolved in favor of coverage. For a particular
290
+ product received by a particular user, "normally used" refers to a
291
+ typical or common use of that class of product, regardless of the status
292
+ of the particular user or of the way in which the particular user
293
+ actually uses, or expects or is expected to use, the product. A product
294
+ is a consumer product regardless of whether the product has substantial
295
+ commercial, industrial or non-consumer uses, unless such uses represent
296
+ the only significant mode of use of the product.
297
+
298
+ "Installation Information" for a User Product means any methods,
299
+ procedures, authorization keys, or other information required to install
300
+ and execute modified versions of a covered work in that User Product from
301
+ a modified version of its Corresponding Source. The information must
302
+ suffice to ensure that the continued functioning of the modified object
303
+ code is in no case prevented or interfered with solely because
304
+ modification has been made.
305
+
306
+ If you convey an object code work under this section in, or with, or
307
+ specifically for use in, a User Product, and the conveying occurs as
308
+ part of a transaction in which the right of possession and use of the
309
+ User Product is transferred to the recipient in perpetuity or for a
310
+ fixed term (regardless of how the transaction is characterized), the
311
+ Corresponding Source conveyed under this section must be accompanied
312
+ by the Installation Information. But this requirement does not apply
313
+ if neither you nor any third party retains the ability to install
314
+ modified object code on the User Product (for example, the work has
315
+ been installed in ROM).
316
+
317
+ The requirement to provide Installation Information does not include a
318
+ requirement to continue to provide support service, warranty, or updates
319
+ for a work that has been modified or installed by the recipient, or for
320
+ the User Product in which it has been modified or installed. Access to a
321
+ network may be denied when the modification itself materially and
322
+ adversely affects the operation of the network or violates the rules and
323
+ protocols for communication across the network.
324
+
325
+ Corresponding Source conveyed, and Installation Information provided,
326
+ in accord with this section must be in a format that is publicly
327
+ documented (and with an implementation available to the public in
328
+ source code form), and must require no special password or key for
329
+ unpacking, reading or copying.
330
+
331
+ 7. Additional Terms.
332
+
333
+ "Additional permissions" are terms that supplement the terms of this
334
+ License by making exceptions from one or more of its conditions.
335
+ Additional permissions that are applicable to the entire Program shall
336
+ be treated as though they were included in this License, to the extent
337
+ that they are valid under applicable law. If additional permissions
338
+ apply only to part of the Program, that part may be used separately
339
+ under those permissions, but the entire Program remains governed by
340
+ this License without regard to the additional permissions.
341
+
342
+ When you convey a copy of a covered work, you may at your option
343
+ remove any additional permissions from that copy, or from any part of
344
+ it. (Additional permissions may be written to require their own
345
+ removal in certain cases when you modify the work.) You may place
346
+ additional permissions on material, added by you to a covered work,
347
+ for which you have or can give appropriate copyright permission.
348
+
349
+ Notwithstanding any other provision of this License, for material you
350
+ add to a covered work, you may (if authorized by the copyright holders of
351
+ that material) supplement the terms of this License with terms:
352
+
353
+ a) Disclaiming warranty or limiting liability differently from the
354
+ terms of sections 15 and 16 of this License; or
355
+
356
+ b) Requiring preservation of specified reasonable legal notices or
357
+ author attributions in that material or in the Appropriate Legal
358
+ Notices displayed by works containing it; or
359
+
360
+ c) Prohibiting misrepresentation of the origin of that material, or
361
+ requiring that modified versions of such material be marked in
362
+ reasonable ways as different from the original version; or
363
+
364
+ d) Limiting the use for publicity purposes of names of licensors or
365
+ authors of the material; or
366
+
367
+ e) Declining to grant rights under trademark law for use of some
368
+ trade names, trademarks, or service marks; or
369
+
370
+ f) Requiring indemnification of licensors and authors of that
371
+ material by anyone who conveys the material (or modified versions of
372
+ it) with contractual assumptions of liability to the recipient, for
373
+ any liability that these contractual assumptions directly impose on
374
+ those licensors and authors.
375
+
376
+ All other non-permissive additional terms are considered "further
377
+ restrictions" within the meaning of section 10. If the Program as you
378
+ received it, or any part of it, contains a notice stating that it is
379
+ governed by this License along with a term that is a further
380
+ restriction, you may remove that term. If a license document contains
381
+ a further restriction but permits relicensing or conveying under this
382
+ License, you may add to a covered work material governed by the terms
383
+ of that license document, provided that the further restriction does
384
+ not survive such relicensing or conveying.
385
+
386
+ If you add terms to a covered work in accord with this section, you
387
+ must place, in the relevant source files, a statement of the
388
+ additional terms that apply to those files, or a notice indicating
389
+ where to find the applicable terms.
390
+
391
+ Additional terms, permissive or non-permissive, may be stated in the
392
+ form of a separately written license, or stated as exceptions;
393
+ the above requirements apply either way.
394
+
395
+ 8. Termination.
396
+
397
+ You may not propagate or modify a covered work except as expressly
398
+ provided under this License. Any attempt otherwise to propagate or
399
+ modify it is void, and will automatically terminate your rights under
400
+ this License (including any patent licenses granted under the third
401
+ paragraph of section 11).
402
+
403
+ However, if you cease all violation of this License, then your
404
+ license from a particular copyright holder is reinstated (a)
405
+ provisionally, unless and until the copyright holder explicitly and
406
+ finally terminates your license, and (b) permanently, if the copyright
407
+ holder fails to notify you of the violation by some reasonable means
408
+ prior to 60 days after the cessation.
409
+
410
+ Moreover, your license from a particular copyright holder is
411
+ reinstated permanently if the copyright holder notifies you of the
412
+ violation by some reasonable means, this is the first time you have
413
+ received notice of violation of this License (for any work) from that
414
+ copyright holder, and you cure the violation prior to 30 days after
415
+ your receipt of the notice.
416
+
417
+ Termination of your rights under this section does not terminate the
418
+ licenses of parties who have received copies or rights from you under
419
+ this License. If your rights have been terminated and not permanently
420
+ reinstated, you do not qualify to receive new licenses for the same
421
+ material under section 10.
422
+
423
+ 9. Acceptance Not Required for Having Copies.
424
+
425
+ You are not required to accept this License in order to receive or
426
+ run a copy of the Program. Ancillary propagation of a covered work
427
+ occurring solely as a consequence of using peer-to-peer transmission
428
+ to receive a copy likewise does not require acceptance. However,
429
+ nothing other than this License grants you permission to propagate or
430
+ modify any covered work. These actions infringe copyright if you do
431
+ not accept this License. Therefore, by modifying or propagating a
432
+ covered work, you indicate your acceptance of this License to do so.
433
+
434
+ 10. Automatic Licensing of Downstream Recipients.
435
+
436
+ Each time you convey a covered work, the recipient automatically
437
+ receives a license from the original licensors, to run, modify and
438
+ propagate that work, subject to this License. You are not responsible
439
+ for enforcing compliance by third parties with this License.
440
+
441
+ An "entity transaction" is a transaction transferring control of an
442
+ organization, or substantially all assets of one, or subdividing an
443
+ organization, or merging organizations. If propagation of a covered
444
+ work results from an entity transaction, each party to that
445
+ transaction who receives a copy of the work also receives whatever
446
+ licenses to the work the party's predecessor in interest had or could
447
+ give under the previous paragraph, plus a right to possession of the
448
+ Corresponding Source of the work from the predecessor in interest, if
449
+ the predecessor has it or can get it with reasonable efforts.
450
+
451
+ You may not impose any further restrictions on the exercise of the
452
+ rights granted or affirmed under this License. For example, you may
453
+ not impose a license fee, royalty, or other charge for exercise of
454
+ rights granted under this License, and you may not initiate litigation
455
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
456
+ any patent claim is infringed by making, using, selling, offering for
457
+ sale, or importing the Program or any portion of it.
458
+
459
+ 11. Patents.
460
+
461
+ A "contributor" is a copyright holder who authorizes use under this
462
+ License of the Program or a work on which the Program is based. The
463
+ work thus licensed is called the contributor's "contributor version".
464
+
465
+ A contributor's "essential patent claims" are all patent claims
466
+ owned or controlled by the contributor, whether already acquired or
467
+ hereafter acquired, that would be infringed by some manner, permitted
468
+ by this License, of making, using, or selling its contributor version,
469
+ but do not include claims that would be infringed only as a
470
+ consequence of further modification of the contributor version. For
471
+ purposes of this definition, "control" includes the right to grant
472
+ patent sublicenses in a manner consistent with the requirements of
473
+ this License.
474
+
475
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
476
+ patent license under the contributor's essential patent claims, to
477
+ make, use, sell, offer for sale, import and otherwise run, modify and
478
+ propagate the contents of its contributor version.
479
+
480
+ In the following three paragraphs, a "patent license" is any express
481
+ agreement or commitment, however denominated, not to enforce a patent
482
+ (such as an express permission to practice a patent or covenant not to
483
+ sue for patent infringement). To "grant" such a patent license to a
484
+ party means to make such an agreement or commitment not to enforce a
485
+ patent against the party.
486
+
487
+ If you convey a covered work, knowingly relying on a patent license,
488
+ and the Corresponding Source of the work is not available for anyone
489
+ to copy, free of charge and under the terms of this License, through a
490
+ publicly available network server or other readily accessible means,
491
+ then you must either (1) cause the Corresponding Source to be so
492
+ available, or (2) arrange to deprive yourself of the benefit of the
493
+ patent license for this particular work, or (3) arrange, in a manner
494
+ consistent with the requirements of this License, to extend the patent
495
+ license to downstream recipients. "Knowingly relying" means you have
496
+ actual knowledge that, but for the patent license, your conveying the
497
+ covered work in a country, or your recipient's use of the covered work
498
+ in a country, would infringe one or more identifiable patents in that
499
+ country that you have reason to believe are valid.
500
+
501
+ If, pursuant to or in connection with a single transaction or
502
+ arrangement, you convey, or propagate by procuring conveyance of, a
503
+ covered work, and grant a patent license to some of the parties
504
+ receiving the covered work authorizing them to use, propagate, modify
505
+ or convey a specific copy of the covered work, then the patent license
506
+ you grant is automatically extended to all recipients of the covered
507
+ work and works based on it.
508
+
509
+ A patent license is "discriminatory" if it does not include within
510
+ the scope of its coverage, prohibits the exercise of, or is
511
+ conditioned on the non-exercise of one or more of the rights that are
512
+ specifically granted under this License. You may not convey a covered
513
+ work if you are a party to an arrangement with a third party that is
514
+ in the business of distributing software, under which you make payment
515
+ to the third party based on the extent of your activity of conveying
516
+ the work, and under which the third party grants, to any of the
517
+ parties who would receive the covered work from you, a discriminatory
518
+ patent license (a) in connection with copies of the covered work
519
+ conveyed by you (or copies made from those copies), or (b) primarily
520
+ for and in connection with specific products or compilations that
521
+ contain the covered work, unless you entered into that arrangement,
522
+ or that patent license was granted, prior to 28 March 2007.
523
+
524
+ Nothing in this License shall be construed as excluding or limiting
525
+ any implied license or other defenses to infringement that may
526
+ otherwise be available to you under applicable patent law.
527
+
528
+ 12. No Surrender of Others' Freedom.
529
+
530
+ If conditions are imposed on you (whether by court order, agreement or
531
+ otherwise) that contradict the conditions of this License, they do not
532
+ excuse you from the conditions of this License. If you cannot convey a
533
+ covered work so as to satisfy simultaneously your obligations under this
534
+ License and any other pertinent obligations, then as a consequence you may
535
+ not convey it at all. For example, if you agree to terms that obligate you
536
+ to collect a royalty for further conveying from those to whom you convey
537
+ the Program, the only way you could satisfy both those terms and this
538
+ License would be to refrain entirely from conveying the Program.
539
+
540
+ 13. Remote Network Interaction; Use with the GNU General Public License.
541
+
542
+ Notwithstanding any other provision of this License, if you modify the
543
+ Program, your modified version must prominently offer all users
544
+ interacting with it remotely through a computer network (if your version
545
+ supports such interaction) an opportunity to receive the Corresponding
546
+ Source of your version by providing access to the Corresponding Source
547
+ from a network server at no charge, through some standard or customary
548
+ means of facilitating copying of software. This Corresponding Source
549
+ shall include the Corresponding Source for any work covered by version 3
550
+ of the GNU General Public License that is incorporated pursuant to the
551
+ following paragraph.
552
+
553
+ Notwithstanding any other provision of this License, you have
554
+ permission to link or combine any covered work with a work licensed
555
+ under version 3 of the GNU General Public License into a single
556
+ combined work, and to convey the resulting work. The terms of this
557
+ License will continue to apply to the part which is the covered work,
558
+ but the work with which it is combined will remain governed by version
559
+ 3 of the GNU General Public License.
560
+
561
+ 14. Revised Versions of this License.
562
+
563
+ The Free Software Foundation may publish revised and/or new versions of
564
+ the GNU Affero General Public License from time to time. Such new versions
565
+ will be similar in spirit to the present version, but may differ in detail to
566
+ address new problems or concerns.
567
+
568
+ Each version is given a distinguishing version number. If the
569
+ Program specifies that a certain numbered version of the GNU Affero General
570
+ Public License "or any later version" applies to it, you have the
571
+ option of following the terms and conditions either of that numbered
572
+ version or of any later version published by the Free Software
573
+ Foundation. If the Program does not specify a version number of the
574
+ GNU Affero General Public License, you may choose any version ever published
575
+ by the Free Software Foundation.
576
+
577
+ If the Program specifies that a proxy can decide which future
578
+ versions of the GNU Affero General Public License can be used, that proxy's
579
+ public statement of acceptance of a version permanently authorizes you
580
+ to choose that version for the Program.
581
+
582
+ Later license versions may give you additional or different
583
+ permissions. However, no additional obligations are imposed on any
584
+ author or copyright holder as a result of your choosing to follow a
585
+ later version.
586
+
587
+ 15. Disclaimer of Warranty.
588
+
589
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597
+
598
+ 16. Limitation of Liability.
599
+
600
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608
+ SUCH DAMAGES.
609
+
610
+ 17. Interpretation of Sections 15 and 16.
611
+
612
+ If the disclaimer of warranty and limitation of liability provided
613
+ above cannot be given local legal effect according to their terms,
614
+ reviewing courts shall apply local law that most closely approximates
615
+ an absolute waiver of all civil liability in connection with the
616
+ Program, unless a warranty or assumption of liability accompanies a
617
+ copy of the Program in return for a fee.
618
+
619
+ END OF TERMS AND CONDITIONS
620
+
621
+ How to Apply These Terms to Your New Programs
622
+
623
+ If you develop a new program, and you want it to be of the greatest
624
+ possible use to the public, the best way to achieve this is to make it
625
+ free software which everyone can redistribute and change under these terms.
626
+
627
+ To do so, attach the following notices to the program. It is safest
628
+ to attach them to the start of each source file to most effectively
629
+ state the exclusion of warranty; and each file should have at least
630
+ the "copyright" line and a pointer to where the full notice is found.
631
+
632
+ <one line to give the program's name and a brief idea of what it does.>
633
+ Copyright (C) <year> <name of author>
634
+
635
+ This program is free software: you can redistribute it and/or modify
636
+ it under the terms of the GNU Affero General Public License as published by
637
+ the Free Software Foundation, either version 3 of the License, or
638
+ (at your option) any later version.
639
+
640
+ This program is distributed in the hope that it will be useful,
641
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
642
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643
+ GNU Affero General Public License for more details.
644
+
645
+ You should have received a copy of the GNU Affero General Public License
646
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
647
+
648
+ Also add information on how to contact you by electronic and paper mail.
649
+
650
+ If your software can interact with users remotely through a computer
651
+ network, you should also make sure that it provides a way for users to
652
+ get its source. For example, if your program is a web application, its
653
+ interface could display a "Source" link that leads users to an archive
654
+ of the code. There are many ways you could offer source, and different
655
+ solutions will be better for different programs; see section 13 for the
656
+ specific requirements.
657
+
658
+ You should also get your employer (if you work as a programmer) or school,
659
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
660
+ For more information on this, and how to apply and follow the GNU AGPL, see
661
+ <https://www.gnu.org/licenses/>.
assets/snapkitty/SOURCE_README.md ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SNAPKITTY: Bifrost Runner — 2D game
2
+
3
+ **Play it live:** https://ahmadaliparr.github.io/snapkitty-2d/
4
+
5
+ Built from your four art pieces: the hoodie kitten (player), the suited
6
+ Architect (NPC), the SNAP-OS dashboard (HUD language), and the
7
+ Snapkitty civilization poster (world backdrop).
8
+
9
+ ## Play it now — `index.html`
10
+
11
+ A playable 2D platformer prototype of the full game design. Open in any
12
+ browser, no build step.
13
+
14
+ - **Move:** A/D or arrows · **Jump:** Space/W (coyote time included)
15
+ - **E:** talk to the Architect at checkpoints · **R:** restart after winning
16
+ - Seal all **8 Bifrost event cubes**, then reach the **Bifrost terminal**
17
+ - Gaps respawn you; HUD tracks sealed events + ledger integrity
18
+
19
+ Verified: `node --check` clean, headless DOM-stubbed run of the full
20
+ game loop (boot, run, jump, all 8 pickups, NPC dialogue open/close,
21
+ win banner, reset) — all OK. Layout composited against the real art
22
+ and visually inspected.
23
+
24
+ ## Build it for real — `UnrealProject/` (C# / UnrealSharp)
25
+
26
+ Unreal Engine 5.5+ project using **C# via UnrealSharp** + Paper2D:
27
+
28
+ - `Snapkitty2D.uproject` — module `Snapkitty2D`, depends on
29
+ `Paper2D`, `EnhancedInput`, `UnrealSharpCore`
30
+ - `Source/Snapkitty2D/`:
31
+ - `SnapkittyPlayer.cs` — plane-locked 2D character controller,
32
+ run/jump, flipbook animation states (idle/run/jump)
33
+ - `ArchitectNPC.cs` — dialogue NPC, talk radius, briefing lines
34
+ - `BifrostPickup.cs` — bobbing/spinning collectible event cube
35
+ - `SnapkittyGameMode.cs` — sealed-event counter, win condition,
36
+ Blueprint events for UI/fanfare
37
+ - `SnapkittyHUD.cs` — SNAP-OS styled HUD bindings (event counter,
38
+ integrity bar, timed dialogue box)
39
+ - `Config/DefaultEngine.ini` — 2D-oriented defaults
40
+
41
+ Open the `.uproject` in UE5, import `art/` as Paper2D sprites, subclass
42
+ the C# classes in Blueprints, build `L_BifrostRunner`.
43
+
44
+ ## Art — `art/`
45
+
46
+ | file | role |
47
+ |---|---|
48
+ | `kitten.png` | player sprite (background-removed cutout) |
49
+ | `suited-man.png` | Architect NPC sprite (background-removed cutout) |
50
+ | `civilization.jpg` | parallax world backdrop |
51
+ | `snap-os.jpg` | HUD/title-screen reference |
52
+ | `*.jpg` originals | kept as fallback sources |
53
+
54
+ (Cutouts produced with `rembg`; the web prototype auto-falls back to
55
+ the `.jpg` originals if a `.png` is missing.)
assets/snapkitty/art/civilization.jpg ADDED

Git LFS Details

  • SHA256: 560114843cdde8834771b08aaf5130190c215bcf56771420fda33b3a69055d0d
  • Pointer size: 131 Bytes
  • Size of remote file: 606 kB
assets/snapkitty/art/kitten.jpg ADDED

Git LFS Details

  • SHA256: 49ca2191fda8c44aab8dc852a63bebe3af805deefdbba0f2cd45be7edc0907c5
  • Pointer size: 131 Bytes
  • Size of remote file: 317 kB
assets/snapkitty/art/kitten.png ADDED

Git LFS Details

  • SHA256: f52ec70ff5fbfd6c9fd09c9cdb39d3c263c5d4301b91a4ced483011ca1df45f3
  • Pointer size: 132 Bytes
  • Size of remote file: 1.02 MB
assets/snapkitty/art/snap-os.jpg ADDED

Git LFS Details

  • SHA256: a37710ee48448b03a978f084996549c27eafdf820d46703621e7d84a4d57e4b2
  • Pointer size: 131 Bytes
  • Size of remote file: 308 kB
assets/snapkitty/art/suited-man.jpg ADDED

Git LFS Details

  • SHA256: b72a3df0b2aae60010d3f30ef8722d659c0282f3ffd1e6a4fddc0241889c5404
  • Pointer size: 131 Bytes
  • Size of remote file: 347 kB
assets/snapkitty/art/suited-man.png ADDED

Git LFS Details

  • SHA256: dcadcf72892ec067a74e1655b009b70e5c8b5f3d9192f7aef5c7eccc038342b2
  • Pointer size: 131 Bytes
  • Size of remote file: 979 kB
assets/snapkitty/runtime-manifest.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "source": "assets/snapkitty/art/kitten.png",
4
+ "runtime": "unify/game/assets/textures/snapkitty/kitten.qoi",
5
+ "sha256": "f52ec70ff5fbfd6c9fd09c9cdb39d3c263c5d4301b91a4ced483011ca1df45f3",
6
+ "qoiSha256": "994a3f728f87a01958a7cc9e777e3a9fe397f43dfc389ad9dcae256c6aa8ec51",
7
+ "width": 1320,
8
+ "height": 1320
9
+ },
10
+ {
11
+ "source": "assets/snapkitty/art/suited-man.png",
12
+ "runtime": "unify/game/assets/textures/snapkitty/suited-man.qoi",
13
+ "sha256": "dcadcf72892ec067a74e1655b009b70e5c8b5f3d9192f7aef5c7eccc038342b2",
14
+ "qoiSha256": "2052e2b6e328ad1507a6a90fd2137856a34f0fd5a755a0b479535bb7e653b0ff",
15
+ "width": 1320,
16
+ "height": 1320
17
+ },
18
+ {
19
+ "source": "assets/snapkitty/art/civilization.jpg",
20
+ "runtime": "unify/game/assets/textures/snapkitty/civilization.qoi",
21
+ "sha256": "560114843cdde8834771b08aaf5130190c215bcf56771420fda33b3a69055d0d",
22
+ "qoiSha256": "1b4464a6040bb3795084ae76d1819b118ea767649f32eb4116081fcc95650eb5",
23
+ "width": 1320,
24
+ "height": 880
25
+ },
26
+ {
27
+ "source": "assets/snapkitty/art/snap-os.jpg",
28
+ "runtime": "unify/game/assets/textures/snapkitty/snap-os.qoi",
29
+ "sha256": "a37710ee48448b03a978f084996549c27eafdf820d46703621e7d84a4d57e4b2",
30
+ "qoiSha256": "3c3b05598b2dbbd1ba0d8f2cd63fad22f1cd24ad3aeb83e53635bea68877c787",
31
+ "width": 1320,
32
+ "height": 880
33
+ }
34
+ ]
assets/snapkitty/source-manifest.json ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "repository": "https://github.com/SNAPKITTYWEST/snapkitty-2d",
3
+ "commit": "2a9314984723affc01aafcd31c4d2a6858dd16ca",
4
+ "files": [
5
+ {
6
+ "source": "art/civilization.jpg",
7
+ "path": "art/civilization.jpg",
8
+ "bytes": 605588,
9
+ "sha256": "560114843cdde8834771b08aaf5130190c215bcf56771420fda33b3a69055d0d",
10
+ "git_blob": "6e0069394259333ede3d0a7cb64ec04d8dc51d15",
11
+ "width": 1320,
12
+ "height": 880,
13
+ "mode": "RGB",
14
+ "transparent": false
15
+ },
16
+ {
17
+ "source": "art/kitten.jpg",
18
+ "path": "art/kitten.jpg",
19
+ "bytes": 316701,
20
+ "sha256": "49ca2191fda8c44aab8dc852a63bebe3af805deefdbba0f2cd45be7edc0907c5",
21
+ "git_blob": "332282b974640cf96f599267adc4fbfc6521c9a8",
22
+ "width": 1320,
23
+ "height": 1320,
24
+ "mode": "RGB",
25
+ "transparent": false
26
+ },
27
+ {
28
+ "source": "art/kitten.png",
29
+ "path": "art/kitten.png",
30
+ "bytes": 1016545,
31
+ "sha256": "f52ec70ff5fbfd6c9fd09c9cdb39d3c263c5d4301b91a4ced483011ca1df45f3",
32
+ "git_blob": "e8e764c4e059c8fa81ed78335396b8361d922e5a",
33
+ "width": 1320,
34
+ "height": 1320,
35
+ "mode": "RGBA",
36
+ "transparent": true
37
+ },
38
+ {
39
+ "source": "art/snap-os.jpg",
40
+ "path": "art/snap-os.jpg",
41
+ "bytes": 307687,
42
+ "sha256": "a37710ee48448b03a978f084996549c27eafdf820d46703621e7d84a4d57e4b2",
43
+ "git_blob": "d0bc5717d7b9babcf65bffff2ad8813b191c6923",
44
+ "width": 1320,
45
+ "height": 880,
46
+ "mode": "RGB",
47
+ "transparent": false
48
+ },
49
+ {
50
+ "source": "art/suited-man.jpg",
51
+ "path": "art/suited-man.jpg",
52
+ "bytes": 347109,
53
+ "sha256": "b72a3df0b2aae60010d3f30ef8722d659c0282f3ffd1e6a4fddc0241889c5404",
54
+ "git_blob": "6d31688381dc93bb533f35e0e60f9db7ba564d36",
55
+ "width": 1320,
56
+ "height": 1320,
57
+ "mode": "RGB",
58
+ "transparent": false
59
+ },
60
+ {
61
+ "source": "art/suited-man.png",
62
+ "path": "art/suited-man.png",
63
+ "bytes": 979481,
64
+ "sha256": "dcadcf72892ec067a74e1655b009b70e5c8b5f3d9192f7aef5c7eccc038342b2",
65
+ "git_blob": "731074d01595784c6568c3418131eda3f0287380",
66
+ "width": 1320,
67
+ "height": 1320,
68
+ "mode": "RGBA",
69
+ "transparent": true
70
+ },
71
+ {
72
+ "source": "web/preview_composite.png",
73
+ "path": "web/preview_composite.png",
74
+ "bytes": 708880,
75
+ "sha256": "f661f75012d47bc0a551f01a90cfd38d777bb605175ef531dfff013c7b459a67",
76
+ "git_blob": "202494492ad9bb81b311bdaf3e3489583493a157",
77
+ "width": 960,
78
+ "height": 540,
79
+ "mode": "RGB",
80
+ "transparent": false
81
+ },
82
+ {
83
+ "source": "LICENSE",
84
+ "path": "reference/LICENSE",
85
+ "bytes": 34523,
86
+ "sha256": "0d96a4ff68ad6d4b6f1f30f713b18d5184912ba8dd389f86aa7710db079abcb0",
87
+ "git_blob": "be3f7b28e564e7dd05eaf59d64adba1a4065ac0e"
88
+ },
89
+ {
90
+ "source": "README.md",
91
+ "path": "reference/README.md",
92
+ "bytes": 2296,
93
+ "sha256": "3ac8607a0398e15c310b17b57f0b13c548190e5d69af1992075ac9b20554ed30",
94
+ "git_blob": "82da211c53edfee056550ee2ec0b816f40a6a851"
95
+ },
96
+ {
97
+ "source": "UnrealProject/README.md",
98
+ "path": "reference/UnrealProject/README.md",
99
+ "bytes": 1538,
100
+ "sha256": "ef8cfab3d0793bd2439deb5b96b208c5528043cdebfcf28cf9372897a846d52b",
101
+ "git_blob": "4aae26523f1b196e2e07cf93e331643ae2f53e81"
102
+ },
103
+ {
104
+ "source": "UnrealProject/Source/Snapkitty2D/SnapkittyHUD.cs",
105
+ "path": "reference/UnrealProject/Source/Snapkitty2D/SnapkittyHUD.cs",
106
+ "bytes": 2487,
107
+ "sha256": "3c975334862a6b09a119e11a3a445d51acbb0fcb5c28a0b57ea222899261ed26",
108
+ "git_blob": "ba93d33510521fd217be03576f9fe2d33a455dd2"
109
+ },
110
+ {
111
+ "source": "index.html",
112
+ "path": "reference/index.html",
113
+ "bytes": 13777,
114
+ "sha256": "373db3983f31f9379ae8224da526eab3f16fddf89168ba5229277c6a90a60bc4",
115
+ "git_blob": "efd4e254fdd11d06c0c63d8054e9dccda812af9c"
116
+ }
117
+ ]
118
+ }
assets/snapkitty/web/preview_composite.png ADDED

Git LFS Details

  • SHA256: f661f75012d47bc0a551f01a90cfd38d777bb605175ef531dfff013c7b459a67
  • Pointer size: 131 Bytes
  • Size of remote file: 709 kB
docs/REPOVERSE-3D.md ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Repoverse 3D district
2
+
3
+ The C# world generator now has an authenticated, loopback-only HTTP sidecar and
4
+ an Unreal client in the existing Repoverse module. The original 2D GameMode
5
+ remains the default; the 3D launcher selects RepoverseWorldMode explicitly.
6
+
7
+ ## Build and run
8
+
9
+ Requires .NET 8 SDK, Unreal Engine 5.4 or newer, and the matching Visual Studio
10
+ C++ toolchain. From the repository root in PowerShell:
11
+
12
+ ./tools/Start-Repoverse3D.ps1 -EngineRoot 'D:/Epic/UE_5.6'
13
+
14
+ Use your actual installation path. This example is not an installed-engine claim.
15
+ The script ingests this Git checkout, creates the authoritative manifest, builds
16
+ Unify and the Unreal host, starts a local sidecar with a fresh session token,
17
+ waits for its health endpoint, and launches the 3D GameMode. On editor exit it
18
+ stops only the sidecar process it started. Logs and the save are in out/world3d.
19
+ Use -SourceRoot to explore another local Git checkout, or -SkipBuild after a
20
+ successful build. The default launcher creates a world for one repository;
21
+ multiple buildings can be served from an existing multi-repository manifest.
22
+
23
+ ## Controls implemented in the Unreal client
24
+
25
+ - WASD/arrows move, mouse looks, Space jumps, Shift runs.
26
+ - Near a ladder, hold Space to climb or Ctrl to descend.
27
+ - E inspects a nearby source terminal. PgUp/PgDn page source; Esc closes it.
28
+ - Tab/Shift+Tab travel between manifest repositories.
29
+ - 1 returns to walking, 2 orbits the selected destination, 3 opens its overview.
30
+ - F5 saves, F9 restores. Esc outside source view saves successfully before quitting.
31
+
32
+ Movement waits for nearby terrain to load. Meshes and collision use the same
33
+ C# greedy quads. The coordinate conversion is centralized: one voxel is 50 cm,
34
+ core (x,y,z) becomes Unreal (x,z,y), and triangle winding reverses once.
35
+ Ladder mesh sections do not collide. Materials are generated by create-map.py;
36
+ no new artwork is required. Windows currently use an opaque blue material.
37
+
38
+ ## Service contract, version 1
39
+
40
+ All requests require X-Repoverse-Token. The service binds 127.0.0.1 only and
41
+ rejects Origin-bearing requests. A single renderer owns a service session;
42
+ requests execute serially. This is not a multiplayer server.
43
+
44
+ | Route | Behavior |
45
+ | --- | --- |
46
+ | POST /v1/session | Reset renderer residency; return player, destinations and artifact objects |
47
+ | POST /v1/focus | Accept x/z in core units; return at most four chunk meshes plus unload IDs |
48
+ | POST /v1/save | Accept PlayerState; atomically save player and voxel edits |
49
+ | POST /v1/load | Restore matching world snapshot; invalidate resident meshes |
50
+ | POST /v1/edit | Apply a packed voxel edit and invalidate neighboring faces |
51
+ | GET /v1/source | Read 32 lines of a manifest artifact from the explicitly mapped local checkout |
52
+ | GET /v1/health | Report protocol version and resident chunk count |
53
+
54
+ The stream radius is one chunk with one chunk of unload hysteresis. Source reads
55
+ are capped at 2 MiB, reject links/path traversal, and never execute repository
56
+ code. Local source contents reflect the current working copy, not a historical
57
+ Git blob. Other repositories require their own source mapping; remote source
58
+ fetching is not implemented. Save restoration rejects a different world seed,
59
+ generator, or snapshot. API edits are available; an in-game build tool is not.
60
+
61
+ ## Verification and remaining work
62
+
63
+ The C# solution builds with warnings as errors. Unit tests cover bounded
64
+ residency, unload/reload, edit persistence, boundary remeshing, outward triangle
65
+ winding, passable ladders, source paging and source restrictions. Run:
66
+
67
+ dotnet test Repoverse.sln
68
+ python tools/test-sidecar.py
69
+
70
+ The second command runs a real sidecar process against a manifest generated
71
+ from this checkout, including auth, HTTP streaming, save/load and source reads.
72
+
73
+ **The new Unreal client has not been compiled or played in Unreal.** An Unreal
74
+ installation was not found in this session. This is an integration awaiting
75
+ engine validation, not a finished or packaged 3D game. Required editor checks:
76
+ compile with UBT; walk into the building; collide with walls; climb all floors;
77
+ inspect a file; orbit; travel; save; quit; restart and restore; disconnect the
78
+ service; exit PIE. Measure frame time and mesh/collision upload costs.
79
+
80
+ Remaining beyond this vertical slice: rendered dependency graph, architectural
81
+ roof/floor cutaways, remote source retrieval, multi-repository source mappings,
82
+ search/bookmarks, live synchronization, complete camera persistence, transparent
83
+ windows, CAD, Swift control plane, and the absent Parts II/III directive.
84
+
85
+ ## Twin-O-Matic builder
86
+
87
+ Export a build from the matching Twin-O-Matic browser app, then pass its JSON path to the launcher with `-BuildPlan`. The launcher sends the plan to authenticated `POST /v1/build` before opening Unreal. This leaves browser-origin requests blocked. No generated script is executed.
88
+
89
+ Version 1 plans carry `id`, `actor`, `units: "voxel"`, integer `origin` (Y-up), and `operations` with shape names and arguments. Boxes, spheres, cylinders, cones and XY-plane tori are supported. The entire plan is validated/rasterized before edits apply. Limits: 128 operations, 262144 candidate samples, 32768 resulting voxels, 16 builder identities per world. Smaller-than-voxel features may vanish; colors quantize to existing material families. Lights/particles are preview-only. Imported blocks can replace existing terrain, so select an empty construction area using the plan origin.
90
+
91
+ The builder body follows its latest completed build position; this is a representation of accepted build commands, not an autonomous Unreal-hosted language model. F5 stores builder identity and edits; F9 and reconnect restore them. Existing schema-2 saves default to no builders.
92
+
93
+ Verification: 88 C# tests, real local HTTP build/save/load/reconnect, and a build downloaded by the Twin browser test and submitted to this service. Unreal client changes still require compilation and a real playtest with an installed engine and the user's supplied assets.
docs/SNAPKITTY-GAME.md ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Repoverse / SNAPKITTY game
2
+
3
+ ## Play the Windows build
4
+
5
+ The native game opens the SNAPKITTY menu. Enter or Space starts Bifrost Runner.
6
+ A/D or arrows move, Space/W jumps, E talks near the Architect, F5 saves, F9
7
+ restores the disk save (including after restarting), and Escape returns to the menu.
8
+ F9 on the title screen continues the saved game. I opens the about panel. R opens the
9
+ repository browser; Left/Right selects a repository and Escape returns.
10
+
11
+ Build from the repository root with PowerShell:
12
+
13
+ ./tools/Build-Snapkitty.ps1 -Play
14
+
15
+ After building, run python tools/package-snapkitty.py to create
16
+ out/Snapkitty-Windows.zip. Extract it and double-click Play.cmd.
17
+ The package includes runtime assets, original artwork, notices and checksums.
18
+
19
+ Requires CMake, MinGW GCC/G++, and network access for the first SDL2 download.
20
+ The script pins SDL 2.32.10 and verifies its SHA-256. The runtime has no network
21
+ dependency. Generated sprites and audio remain part of the existing Unify build.
22
+
23
+ ## What is shared
24
+
25
+ The title, repository browser, gameplay, physics, WASM compute, saves and artwork
26
+ are shared Unify Lua/assets. The SDL backend provides a desktop window. Unreal
27
+ provides a Canvas renderer, input and audio through the existing Unify backend.
28
+ This is a native 2D game hosted inside Unreal, not a new browser simulation.
29
+
30
+ The existing demo remains available with --scene title. The new default is
31
+ snapkitty, which opens snapkitty_level. The player uses the original kitten
32
+ cutout; motion uses the existing run/jump state machine and procedural squash,
33
+ not invented sprite-sheet frames. The Architect is an interactive NPC near the
34
+ start. Event pickups, obstacles, moving platforms, the finish trigger and
35
+ save/restore use the existing platformer systems.
36
+
37
+ ## Repoverse data bridge
38
+
39
+ The C# core remains the authority for world generation. Export a snapshot and
40
+ manifest using the existing CLI, then generate the read-only repository scene:
41
+
42
+ dotnet run --project src/Repoverse.Cli -- ingest-local . --owner SNAPKITTYWEST --out out/snapshot.json
43
+ dotnet run --project src/Repoverse.Cli -- generate --snapshot out/snapshot.json --out out/manifest.json
44
+ python tools/export-unify-world.py out/manifest.json
45
+
46
+ The exporter accepts schema 1 and encodes text as Lua string bytes, never as
47
+ executable source. It does not modify the manifest or run repository code.
48
+ The checked-in menu data is a snapshot of this repository, not live GitHub data.
49
+ The browser shows category, district, activity, construction, rooms and seed.
50
+ It is not yet the streamed 3D voxel district described in HANDOFF.md.
51
+
52
+ ## Unreal project
53
+
54
+ See unreal/README.md. The project enables the UnifyUnreal plugin, assigns the
55
+ Unify GameMode, creates a host automatically, and stages ordinary files as
56
+ NonUFS assets because the engine opens them through its file loader.
57
+
58
+ ## Artwork and provenance
59
+
60
+ Originals and the upstream AGPL license are under assets/snapkitty. Four QOI
61
+ runtime copies were converted losslessly, with pixel equality checked.
62
+ The source and runtime SHA-256 hashes are in runtime-manifest.json.
63
+ No original was recolored, resized or overwritten; scene tint is applied at
64
+ runtime for readability. Both original JPGs and transparent PNGs are retained.
65
+ The upstream source commit is recorded in source-manifest.json. This does not
66
+ replace the licensing terms of unrelated Repoverse code.
67
+
68
+ Regenerate texture files with python tools/import-snapkitty.py (Pillow required).
69
+ The checked-in QOI files make Pillow unnecessary for ordinary game builds.
70
+
71
+ ## Validation
72
+
73
+ CTest runs the engine suite, the original demo playthrough and the SNAPKITTY
74
+ playthrough. The latter exercises the actual game rather than a mock scene.
75
+ An additional engine test covers the about panel, repository scene, play
76
+ transition, original textures and Architect interaction. Screenshots are
77
+ written under unify/build-game/snapkitty-evidence.
78
+
79
+ The Unreal Editor is not installed in the inspected locations on this machine.
80
+ Its C++ integration therefore still needs compilation and a PIE check with the
81
+ user's engine version. SDL/headless results do not establish Unreal compilation.
82
+
83
+ ## 3D district integration
84
+
85
+ See [REPOVERSE-3D.md](REPOVERSE-3D.md) for the new C# sidecar, Unreal client,
86
+ launcher and the remaining Unreal compilation/playtest boundary.
preview/index.html ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Repoverse Preview</title>
7
+ <!-- Developer preview of generator output (world-mesh.json from `repoverse export-mesh`).
8
+ This checks geometry and manifest data by eye; the shipped renderer is Unreal. -->
9
+ <style>
10
+ :root { --bg:#0e1116; --panel:rgba(20,24,31,.86); --line:rgba(255,255,255,.12); --text:#e6e9ef; --muted:#9aa3b2; --accent:#7cc4ff; }
11
+ * { box-sizing: border-box; }
12
+ html, body { margin: 0; height: 100%; background: var(--bg); color: var(--text); font: 13px/1.45 ui-sans-serif, system-ui, sans-serif; overflow: hidden; }
13
+ canvas { display: block; }
14
+ .panel { position: fixed; background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 12px 14px; backdrop-filter: blur(8px); }
15
+ #hud { top: 16px; left: 16px; max-width: min(360px, calc(100vw - 32px)); }
16
+ #inspector { top: 16px; right: 16px; width: min(340px, calc(100vw - 32px)); display: none; max-height: calc(100vh - 32px); overflow: auto; }
17
+ h1 { font-size: 14px; margin: 0 0 4px; } h2 { font-size: 14px; margin: 0 0 2px; word-break: break-all; }
18
+ .muted { color: var(--muted); } .why { color: var(--muted); font-size: 11px; }
19
+ label { display: inline-flex; gap: 6px; align-items: center; margin-right: 12px; cursor: pointer; }
20
+ dl { display: grid; grid-template-columns: auto 1fr; gap: 2px 10px; margin: 8px 0; } dt { color: var(--muted); } dd { margin: 0; }
21
+ ul { margin: 6px 0 0; padding-left: 16px; } li { margin: 1px 0; }
22
+ @media (max-width: 640px) { #inspector { top: auto; bottom: 16px; max-height: 45vh; } }
23
+ </style>
24
+ <script type="importmap">{ "imports": {
25
+ "three": "https://cdn.jsdelivr.net/npm/three@0.169.0/build/three.module.js",
26
+ "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.169.0/examples/jsm/" } }</script>
27
+ </head>
28
+ <body>
29
+ <div id="hud" class="panel">
30
+ <h1>Repoverse · generator preview</h1>
31
+ <div id="stats" class="muted">loading world-mesh.json…</div>
32
+ <div style="margin-top:8px">
33
+ <label><input type="checkbox" id="roofs" checked> roofs</label>
34
+ <label><input type="checkbox" id="objects" checked> source objects</label>
35
+ </div>
36
+ <div class="muted" style="margin-top:6px">drag to orbit · scroll to zoom · click a building</div>
37
+ </div>
38
+ <div id="inspector" class="panel"></div>
39
+ <script type="module">
40
+ import * as THREE from 'three';
41
+ import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
42
+
43
+ // Material-family base colours, lightened per block role so walls, floors and windows read apart.
44
+ const FAMILY = { stone:0x9a948a, concrete:0xb8bcc2, glass:0x8fc7e8, metal:0x8c96a3, wood:0xb88a5a, ceramic:0xe2d6c4,
45
+ electronics:0x5e7b8f, laboratory:0xdfe7ec, archive:0xc9a86b, security:0x5b6275 };
46
+ const BLOCK = { grass:0x5f8f4e, road:0x3b3f46, sidewalk:0x9fa3a8, soil:0x6b5237, bedrock:0x333333, foundation:0x7f7a72,
47
+ ladder:0xd9a441, scaffold:0xe0b030 };
48
+ const OBJECT = { SourceTerminal:0x7cc4ff, TestBench:0x7de3a1, ProofVault:0xc39bff, ArchiveShelf:0xe8c47c, BuildStation:0xff9d6b,
49
+ DataRack:0x5fd4d0, ConfigPanel:0xb0b8c4, AssetCrate:0xd28ac7, NotebookDesk:0xf2e28a, HardwareBench:0xff6b6b };
50
+
51
+ const colorFor = (block, family) => {
52
+ const b = block.toLowerCase(), f = family.toLowerCase();
53
+ if (BLOCK[b] !== undefined) return new THREE.Color(BLOCK[b]);
54
+ const c = new THREE.Color(FAMILY[f] ?? 0xaaaaaa);
55
+ if (b === 'window') return c.lerp(new THREE.Color(0x9fd8ff), .6);
56
+ if (b === 'roof') return c.multiplyScalar(.72);
57
+ if (b === 'floor') return c.multiplyScalar(.85);
58
+ if (b === 'partition') return c.lerp(new THREE.Color(0xffffff), .3);
59
+ return c;
60
+ };
61
+
62
+ const renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true });
63
+ renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
64
+ renderer.setSize(innerWidth, innerHeight);
65
+ document.body.prepend(renderer.domElement);
66
+ const scene = new THREE.Scene();
67
+ scene.background = new THREE.Color(0xbfd6e6);
68
+ scene.fog = new THREE.Fog(0xbfd6e6, 900, 3200);
69
+ const camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 1, 8000);
70
+ const controls = new OrbitControls(camera, renderer.domElement);
71
+ controls.enableDamping = true;
72
+ scene.add(new THREE.HemisphereLight(0xffffff, 0x6b5a45, 1.1));
73
+ const sun = new THREE.DirectionalLight(0xffffff, 1.6); sun.position.set(.6, 1, .35); scene.add(sun);
74
+
75
+ // Terrain outside exported chunks: a plane just below the ground surface (y = GroundLevel = 8).
76
+ const ground = new THREE.Mesh(new THREE.PlaneGeometry(20000, 20000), new THREE.MeshLambertMaterial({ color: 0x5f8f4e }));
77
+ ground.rotation.x = -Math.PI / 2; ground.position.y = 7.9; scene.add(ground);
78
+
79
+ const world = await (await fetch(new URLSearchParams(location.search).get('data') ?? 'world-mesh.json')).json();
80
+ const roofMeshes = [];
81
+ let quads = 0;
82
+ const NORMALS = [null, [1,0,0], [0,1,0], [0,0,1]];
83
+ for (const g of world.groups) {
84
+ const n = g.normals.length; quads += n;
85
+ const pos = new Float32Array(g.positions), nor = new Float32Array(n * 12), idx = new Uint32Array(n * 6);
86
+ for (let q = 0; q < n; q++) {
87
+ const s = Math.sign(g.normals[q]), v = NORMALS[Math.abs(g.normals[q])];
88
+ for (let k = 0; k < 4; k++) nor.set([v[0]*s, v[1]*s, v[2]*s], (q*4+k)*3);
89
+ idx.set([q*4, q*4+1, q*4+2, q*4, q*4+2, q*4+3], q*6);
90
+ }
91
+ const geo = new THREE.BufferGeometry();
92
+ geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
93
+ geo.setAttribute('normal', new THREE.BufferAttribute(nor, 3));
94
+ geo.setIndex(new THREE.BufferAttribute(idx, 1));
95
+ const glass = g.block === 'Window';
96
+ const mesh = new THREE.Mesh(geo, new THREE.MeshLambertMaterial({ color: colorFor(g.block, g.material), transparent: glass, opacity: glass ? .55 : 1 }));
97
+ scene.add(mesh);
98
+ if (g.block === 'Roof') roofMeshes.push(mesh);
99
+ }
100
+
101
+ const box = new THREE.BoxGeometry(.8, .8, .8);
102
+ const objects = new THREE.InstancedMesh(box, new THREE.MeshLambertMaterial(), world.objects.length);
103
+ world.objects.forEach((o, i) => {
104
+ objects.setMatrixAt(i, new THREE.Matrix4().makeTranslation(o.x + .5, o.y + .4, o.z + .5));
105
+ objects.setColorAt(i, new THREE.Color(OBJECT[o.kind] ?? 0xffffff));
106
+ });
107
+ scene.add(objects);
108
+
109
+ // Invisible pick volumes, one per building.
110
+ const pickables = world.buildings.map(b => {
111
+ const m = new THREE.Mesh(new THREE.BoxGeometry(b.width, b.height, b.depth), new THREE.MeshBasicMaterial({ visible: false }));
112
+ m.position.set(b.x + b.width / 2, 8 + b.height / 2, b.z + b.depth / 2);
113
+ m.userData = b; scene.add(m); return m;
114
+ });
115
+
116
+ const bounds = new THREE.Box3();
117
+ pickables.forEach(p => bounds.expandByObject(p));
118
+ const center = bounds.getCenter(new THREE.Vector3()), size = bounds.getSize(new THREE.Vector3()).length();
119
+ controls.target.copy(center);
120
+ camera.position.copy(center).add(new THREE.Vector3(size * .35, size * .45, size * .55));
121
+
122
+ document.getElementById('stats').textContent =
123
+ `${world.buildings.length} buildings · ${quads.toLocaleString()} quads · ${world.groups.length} material groups · ${world.objects.length} source objects · seed ${world.worldSeed}`;
124
+ document.getElementById('roofs').onchange = e => roofMeshes.forEach(m => m.visible = e.target.checked);
125
+ document.getElementById('objects').onchange = e => objects.visible = e.target.checked;
126
+
127
+ function inspect(b, target) {
128
+ const el = document.getElementById('inspector');
129
+ el.style.display = 'block';
130
+ el.innerHTML = `<h2>${esc(b.repo)}</h2><div class="muted">${esc(b.description)}</div>
131
+ <dl><dt>category</dt><dd>${esc(b.category)}<div class="why">${esc(b.categoryWhy)}</div></dd>
132
+ <dt>district</dt><dd>${esc(b.district)}</dd><dt>archetype</dt><dd>${esc(b.archetype)}</dd>
133
+ <dt>floors</dt><dd>${b.floors}</dd><dt>activity</dt><dd>${esc(b.activity)}</dd><dt>state</dt><dd>${esc(b.construction)}</dd></dl>
134
+ <div class="muted">rooms</div><ul>${b.rooms.map(r => `<li>${esc(r.name)} <span class="muted">· ${esc(r.purpose)} · floor ${r.floor} · ${r.fileCount} files</span></li>`).join('')}</ul>`;
135
+ controls.target.copy(target);
136
+ }
137
+
138
+ const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;' }[c]));
139
+ const ray = new THREE.Raycaster(), ptr = new THREE.Vector2();
140
+ let down = null;
141
+ renderer.domElement.addEventListener('pointerdown', e => down = [e.clientX, e.clientY]);
142
+ renderer.domElement.addEventListener('pointerup', e => {
143
+ if (!down || Math.hypot(e.clientX - down[0], e.clientY - down[1]) > 4) return;
144
+ ptr.set(e.clientX / innerWidth * 2 - 1, -e.clientY / innerHeight * 2 + 1);
145
+ ray.setFromCamera(ptr, camera);
146
+ const hit = ray.intersectObjects(pickables)[0];
147
+ const el = document.getElementById('inspector');
148
+ if (!hit) { el.style.display = 'none'; return; }
149
+ inspect(hit.object.userData, hit.object.position);
150
+ });
151
+
152
+ // ?focus=owner/repo frames one building and opens its inspector (deep link, §76).
153
+ const focus = new URLSearchParams(location.search).get('focus');
154
+ const focused = pickables.find(p => p.userData.repo === focus?.toLowerCase());
155
+ if (focused) {
156
+ const b = focused.userData;
157
+ inspect(b, focused.position);
158
+ camera.position.copy(focused.position).add(new THREE.Vector3(b.width * 1.1, b.height + 34, b.depth * 1.6));
159
+ }
160
+
161
+ addEventListener('resize', () => { camera.aspect = innerWidth / innerHeight; camera.updateProjectionMatrix(); renderer.setSize(innerWidth, innerHeight); });
162
+ renderer.setAnimationLoop(() => { controls.update(); renderer.render(scene, camera); });
163
+ window.__ready = true;
164
+ </script>
165
+ </body>
166
+ </html>
src/Repoverse.Cli/Program.cs ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using System.Diagnostics;
2
+ using System.Text.Json;
3
+ using Repoverse.Core;
4
+ using Repoverse.Core.Generation;
5
+ using Repoverse.Core.Ingestion;
6
+ using Repoverse.Core.Simulation;
7
+ using Repoverse.Core.Voxels;
8
+
9
+ // repoverse <command> [options]. Each command reads/writes plain JSON so stages can be run,
10
+ // inspected and diffed independently: snapshot → manifest → chunks/meshes.
11
+
12
+ var cmd = args.FirstOrDefault();
13
+ var opts = ParseOptions(args.Skip(1).ToArray());
14
+ try
15
+ {
16
+ return cmd switch
17
+ {
18
+ "ingest-local" => IngestLocal(opts),
19
+ "ingest-github" => await IngestGitHub(opts),
20
+ "generate" => Generate(opts),
21
+ "stats" => await Stats(opts),
22
+ "export-mesh" => ExportMesh(opts),
23
+ "diff" => Diff(opts),
24
+ _ => Usage(),
25
+ };
26
+ }
27
+ catch (Exception e) when (e is IOException or InvalidDataException or FormatException or ArgumentException or InvalidOperationException or JsonException)
28
+ {
29
+ Console.Error.WriteLine($"error: {GitHubIngest.Redact(e.Message)}");
30
+ return 1;
31
+ }
32
+
33
+ static int Usage()
34
+ {
35
+ Console.Error.WriteLine("""
36
+ usage:
37
+ repoverse ingest-local <git-dir> [--owner NAME] [--subprojects] --out snapshot.json
38
+ repoverse ingest-github <owner> [--limit N] [--forks] [--cache DIR] --out snapshot.json (token: $GITHUB_TOKEN)
39
+ repoverse generate --snapshot snapshot.json --out manifest.json [--seed N] [--overrides FILE] [--previous manifest.json]
40
+ repoverse stats --manifest manifest.json
41
+ repoverse export-mesh --manifest manifest.json --out world-mesh.json
42
+ repoverse diff --before snapshot.json --after snapshot.json
43
+ """);
44
+ return 2;
45
+ }
46
+
47
+ static int IngestLocal(Dictionary<string, string> o)
48
+ {
49
+ var dir = Required(o, "_0");
50
+ var owner = o.GetValueOrDefault("owner", "local");
51
+ var repos = LocalGitIngest.Ingest(dir, owner, o.ContainsKey("subprojects"));
52
+ var snap = new Snapshot { TakenAt = DateTimeOffset.UtcNow, Source = $"git:{Path.GetFullPath(dir)}", Repositories = repos };
53
+ SnapshotStore.Save(Required(o, "out"), snap);
54
+ Console.WriteLine($"[GITHUB] ingested {repos.Count} repositories from {dir}");
55
+ return 0;
56
+ }
57
+
58
+ static async Task<int> IngestGitHub(Dictionary<string, string> o)
59
+ {
60
+ var owner = Required(o, "_0");
61
+ var outPath = Required(o, "out");
62
+ var cache = o.GetValueOrDefault("cache", Path.Combine(Path.GetTempPath(), "repoverse-cache"));
63
+ var token = Environment.GetEnvironmentVariable("GITHUB_TOKEN");
64
+ var ingest = new GitHubIngest(new HttpClient(), cache, token);
65
+ var result = await ingest.IngestOwnerAsync(owner, o.ContainsKey("forks"), o.TryGetValue("limit", out var l) ? int.Parse(l) : null);
66
+
67
+ var merged = SnapshotStore.Merge(SnapshotStore.Load(outPath), result, $"github:{owner}", DateTimeOffset.UtcNow);
68
+ if (merged.Snapshot.Repositories.Count > 0) SnapshotStore.Save(outPath, merged.Snapshot);
69
+ foreach (var f in result.Failures) Console.Error.WriteLine($"[GITHUB] failed {f.Repo}: {f.Reason}");
70
+ Console.WriteLine($"[GITHUB] {result.Repositories.Count} fresh, {merged.Stale.Count} stale, {result.Failures.Count} failed; " +
71
+ $"{ingest.RequestsSent} requests ({ingest.NotModified} not modified){(result.RateLimited ? "; RATE LIMITED" : "")}");
72
+ return merged.Snapshot.Repositories.Count > 0 ? 0 : 1;
73
+ }
74
+
75
+ static int Generate(Dictionary<string, string> o)
76
+ {
77
+ var snap = SnapshotStore.Load(Required(o, "snapshot")) ?? throw new IOException("snapshot not found");
78
+ var seed = new Seed(o.TryGetValue("seed", out var s) ? ulong.Parse(s) : 0x5AA4C177UL);
79
+ var overrides = o.TryGetValue("overrides", out var ov) ? Overrides.Load(ov) : null;
80
+ var previous = o.TryGetValue("previous", out var pv) && File.Exists(pv) ? ReadManifest(pv) : null;
81
+
82
+ var sw = Stopwatch.StartNew();
83
+ var manifest = ManifestBuilder.Build(snap.Repositories, seed, overrides, previous);
84
+ File.WriteAllText(Required(o, "out"), JsonSerializer.Serialize(manifest, Json.Options));
85
+ Console.WriteLine($"[MANIFEST] {manifest.Buildings.Count} buildings, {manifest.Dependencies.Count} dependency edges in {sw.ElapsedMilliseconds} ms (seed {manifest.WorldSeed})");
86
+ Console.WriteLine($"{"repository",-44} {"category",-22} {"district",-18} {"archetype",-13} {"floors",6} {"rooms",6}");
87
+ foreach (var b in manifest.Buildings)
88
+ Console.WriteLine($"{b.Repo.Key,-44} {b.Category.Value,-22} {b.District.Value,-18} {b.Archetype.Value,-13} {b.Floors,6} {b.Interior.Rooms.Count(BuildingRasterizer.IsWorkRoom),6} ← {b.Category.Why}");
89
+ return 0;
90
+ }
91
+
92
+ static async Task<int> Stats(Dictionary<string, string> o)
93
+ {
94
+ var manifest = ReadManifest(Required(o, "manifest"));
95
+ var gen = new WorldGenerator(manifest);
96
+ var chunks = ChunksForBuildings(manifest).ToList();
97
+
98
+ var sw = Stopwatch.StartNew();
99
+ var generated = chunks.AsParallel().Select(c => gen.Generate(c)).ToList();
100
+ var genTime = sw.Elapsed;
101
+ var byCoord = generated.ToDictionary(c => c.Coord);
102
+ Voxel? Sample(int x, int y, int z) => byCoord.TryGetValue(ChunkCoord.FromVoxel(x, y, z), out var ch)
103
+ ? ch[x - ch.Coord.OriginX, y - ch.Coord.OriginY, z - ch.Coord.OriginZ] : null;
104
+
105
+ sw.Restart();
106
+ var meshes = generated.AsParallel().Select(c => GreedyMesher.Build(c, Sample)).ToList();
107
+ var meshTime = sw.Elapsed;
108
+ int faces = meshes.Sum(m => m.VisibleFaces), quads = meshes.Sum(m => m.Quads.Count);
109
+ int objects = manifest.Buildings.Sum(b => BuildingRasterizer.Objects(b).Count());
110
+
111
+ Console.WriteLine($"[VOXEL] {generated.Count} chunks, {generated.Sum(c => (long)c.NonAirCount):N0} solid voxels, {generated.Count * 64} KiB voxel memory");
112
+ Console.WriteLine($"[VOXEL] generate {genTime.TotalMilliseconds:F0} ms total, {genTime.TotalMilliseconds / generated.Count:F2} ms/chunk (parallel)");
113
+ Console.WriteLine($"[VOXEL] mesh {meshTime.TotalMilliseconds:F0} ms; {faces:N0} visible faces → {quads:N0} quads ({quads * 2:N0} tris), {100.0 * quads / Math.Max(1, faces):F1}% of naive");
114
+ Console.WriteLine($"[VOXEL] draw groups: max {meshes.Max(m => m.MaterialGroups)} per chunk, {meshes.Sum(m => m.MaterialGroups)} total");
115
+ Console.WriteLine($"[WORLDGEN] {objects} interactive objects (entities, not voxels)");
116
+
117
+ var streamer = new ChunkStreamer(gen, new WorldEdits(), radius: 4);
118
+ var b0 = manifest.Buildings[0];
119
+ sw.Restart();
120
+ await streamer.SettleAsync(b0.Footprint.X, b0.Footprint.Z);
121
+ Console.WriteLine($"[STREAMING] radius 4 around {b0.Repo}: {streamer.Loaded.Count} chunks resident in {sw.ElapsedMilliseconds} ms");
122
+ return 0;
123
+ }
124
+
125
+ static int ExportMesh(Dictionary<string, string> o)
126
+ {
127
+ var manifest = ReadManifest(Required(o, "manifest"));
128
+ var gen = new WorldGenerator(manifest);
129
+ var chunks = ChunksForBuildings(manifest).AsParallel().Select(c => gen.Generate(c)).ToDictionary(c => c.Coord);
130
+ Voxel? Sample(int x, int y, int z) => chunks.TryGetValue(ChunkCoord.FromVoxel(x, y, z), out var ch)
131
+ ? ch[x - ch.Coord.OriginX, y - ch.Coord.OriginY, z - ch.Coord.OriginZ] : null;
132
+
133
+ // Flat arrays per mesh key keep the file small and map 1:1 onto GPU buffers.
134
+ var groups = new Dictionary<ushort, (List<float> Pos, List<int> Normal)>();
135
+ foreach (var mesh in chunks.Values.AsParallel().Select(c => GreedyMesher.Build(c, Sample)).ToList())
136
+ foreach (var q in mesh.Quads)
137
+ {
138
+ if (!groups.TryGetValue(q.MeshKey, out var g)) groups[q.MeshKey] = g = ([], []);
139
+ foreach (var (x, y, z) in GreedyMesher.Corners(mesh.Coord, q)) { g.Pos.Add(x); g.Pos.Add(y); g.Pos.Add(z); }
140
+ g.Normal.Add((q.Axis + 1) * (q.Positive ? 1 : -1));
141
+ }
142
+
143
+ var export = new
144
+ {
145
+ manifest.WorldSeed,
146
+ Groups = groups.OrderBy(kv => kv.Key).Select(kv => new
147
+ {
148
+ Block = ((BlockType)(kv.Key & 0xFF)).ToString(),
149
+ Material = ((Repoverse.Core.Model.MaterialFamily)(kv.Key >> 8 & 0xF)).ToString(),
150
+ Positions = kv.Value.Pos,
151
+ Normals = kv.Value.Normal,
152
+ }),
153
+ Buildings = manifest.Buildings.Select(b => new
154
+ {
155
+ Repo = b.Repo.Key, b.Description, Category = b.Category.Value.ToString(), CategoryWhy = b.Category.Why.ToString(),
156
+ District = b.District.Value.ToString(), Archetype = b.Archetype.Value.ToString(), b.Floors,
157
+ Activity = b.Activity.Value.ToString(), Construction = b.Construction.Value.ToString(),
158
+ b.Footprint.X, b.Footprint.Z, b.Footprint.Width, b.Footprint.Depth, b.Height,
159
+ Rooms = b.Interior.Rooms.Where(BuildingRasterizer.IsWorkRoom).Select(r => new { r.Name, Purpose = r.Purpose.ToString(), r.Floor, r.FileCount }),
160
+ }),
161
+ Objects = manifest.Buildings.SelectMany(BuildingRasterizer.Objects)
162
+ .Select(w => new { w.X, w.Y, w.Z, Kind = w.Kind.ToString(), Uri = new RepoverseUri { Repo = w.Repo, Path = w.SourcePath }.ToString() }),
163
+ Dependencies = manifest.Dependencies.Select(d => new[] { d.From.Key, d.To.Key }),
164
+ };
165
+ File.WriteAllText(Required(o, "out"), JsonSerializer.Serialize(export, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }));
166
+ Console.WriteLine($"[VOXEL] exported {groups.Values.Sum(g => g.Normal.Count):N0} quads in {groups.Count} material groups");
167
+ return 0;
168
+ }
169
+
170
+ static int Diff(Dictionary<string, string> o)
171
+ {
172
+ var before = SnapshotStore.Load(Required(o, "before")) ?? throw new IOException("before snapshot not found");
173
+ var after = SnapshotStore.Load(Required(o, "after")) ?? throw new IOException("after snapshot not found");
174
+ foreach (var e in SnapshotDiff.Diff(before.Repositories, after.Repositories)) Console.WriteLine(e);
175
+ return 0;
176
+ }
177
+
178
+ static IEnumerable<ChunkCoord> ChunksForBuildings(WorldManifest m)
179
+ {
180
+ var set = new HashSet<ChunkCoord>();
181
+ foreach (var b in m.Buildings)
182
+ {
183
+ var lo = ChunkCoord.FromVoxel(b.Footprint.X - WorldConstants.RoadWidth, 0, b.Footprint.Z - WorldConstants.RoadWidth);
184
+ var hi = ChunkCoord.FromVoxel(b.Footprint.MaxX + WorldConstants.RoadWidth, WorldConstants.GroundLevel + b.Height, b.Footprint.MaxZ + WorldConstants.RoadWidth);
185
+ for (int x = lo.X; x <= hi.X; x++) for (int y = 0; y <= hi.Y; y++) for (int z = lo.Z; z <= hi.Z; z++)
186
+ set.Add(new ChunkCoord(x, y, z));
187
+ }
188
+ return set.OrderBy(c => c.X).ThenBy(c => c.Z).ThenBy(c => c.Y);
189
+ }
190
+
191
+ static WorldManifest ReadManifest(string path) =>
192
+ JsonSerializer.Deserialize<WorldManifest>(File.ReadAllText(path), Json.Options) ?? throw new InvalidDataException($"{path} is empty");
193
+
194
+ static string Required(Dictionary<string, string> o, string key) =>
195
+ o.TryGetValue(key, out var v) ? v : throw new ArgumentException(key.StartsWith('_') ? "missing positional argument" : $"missing --{key}");
196
+
197
+ static Dictionary<string, string> ParseOptions(string[] a)
198
+ {
199
+ var o = new Dictionary<string, string>();
200
+ int pos = 0;
201
+ for (int i = 0; i < a.Length; i++)
202
+ {
203
+ if (!a[i].StartsWith("--")) { o[$"_{pos++}"] = a[i]; continue; }
204
+ var key = a[i][2..];
205
+ o[key] = i + 1 < a.Length && !a[i + 1].StartsWith("--") ? a[++i] : "true";
206
+ }
207
+ return o;
208
+ }
src/Repoverse.Cli/Repoverse.Cli.csproj ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <Project Sdk="Microsoft.NET.Sdk">
2
+
3
+ <ItemGroup>
4
+ <ProjectReference Include="..\Repoverse.Core\Repoverse.Core.csproj" />
5
+ </ItemGroup>
6
+
7
+ <PropertyGroup>
8
+ <OutputType>Exe</OutputType>
9
+ <TargetFramework>net8.0</TargetFramework>
10
+ <ImplicitUsings>enable</ImplicitUsings>
11
+ <Nullable>enable</Nullable>
12
+ </PropertyGroup>
13
+
14
+ </Project>
src/Repoverse.Core/Bridge/BuilderPlan.cs ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using System.Text.Json;
2
+ using System.Text.RegularExpressions;
3
+ using Repoverse.Core.Model;
4
+ using Repoverse.Core.Voxels;
5
+ namespace Repoverse.Core.Bridge;
6
+
7
+ public sealed record BuildOrigin(int X,int Y,int Z);
8
+ public sealed record BuildOperation(string Name,JsonElement Args);
9
+ public sealed record BuilderPlan(int SchemaVersion,string Id,string Actor,string Units,BuildOrigin Origin,BuildOperation[] Operations);
10
+ public sealed record BuilderState(string Actor,string PlanId,double X,double Y,double Z,int Voxels);
11
+ public readonly record struct BuildVoxel(int X,int Y,int Z,ushort Packed);
12
+
13
+ /// <summary>Data-only Twin builder contract. Validate and rasterize completely before editing the world.</summary>
14
+ public static class BuilderRasterizer
15
+ {
16
+ public const int MaxVoxels=32768;
17
+ public static IReadOnlyList<BuildVoxel> Rasterize(BuilderPlan plan)
18
+ {
19
+ if(plan.SchemaVersion!=1 || plan.Units!="voxel" || string.IsNullOrWhiteSpace(plan.Id) || plan.Id.Length>128 || string.IsNullOrWhiteSpace(plan.Actor) || plan.Actor.Length>64
20
+ || plan.Origin is null || plan.Operations is null || plan.Operations.Length is <1 or >128)throw new ArgumentException("Invalid builder plan.");
21
+ if(Math.Abs((long)plan.Origin.X)>1_000_000 || Math.Abs((long)plan.Origin.Z)>1_000_000)throw new ArgumentException("Invalid build origin.");
22
+ var result=new Dictionary<(int,int,int),BuildVoxel>();long candidates=0;
23
+ foreach(var operation in plan.Operations)
24
+ {
25
+ if(operation is null || operation.Args.ValueKind!=JsonValueKind.Object)throw new ArgumentException("Invalid build operation.");
26
+ var a=operation.Args;
27
+ double N(string key,double fallback,double min,double max) {
28
+ double v=fallback;
29
+ if(a.TryGetProperty(key,out var p) && (p.ValueKind!=JsonValueKind.Number || !p.TryGetDouble(out v)))throw new ArgumentException("Invalid "+key);
30
+ if(!double.IsFinite(v)||v<min||v>max)throw new ArgumentException("Invalid "+key);return v;
31
+ }
32
+ double cx=plan.Origin.X+N("x",0,-256,256), cy=plan.Origin.Y+N("y",1,-256,256), cz=plan.Origin.Z+N("z",0,-256,256);
33
+ double rx,ry,rz,r=0,tube=0,h=0;
34
+ switch(operation.Name) {
35
+ case "add_box":rx=N("width",1,.02,64)/2;ry=N("height",1,.02,64)/2;rz=N("depth",1,.02,64)/2;break;
36
+ case "add_sphere":rx=ry=rz=r=N("radius",.7,.02,64);break;
37
+ case "add_cylinder":rx=rz=r=N("radius",.5,.02,64);ry=(h=N("height",2,.02,64))/2;break;
38
+ case "add_cone":rx=rz=r=N("radius",.6,.02,64);ry=(h=N("height",1.5,.02,64))/2;break;
39
+ case "add_torus":r=N("radius",1,.02,64);tube=N("tube",.3,.02,64);if(tube>r)throw new ArgumentException("Invalid torus tube");rx=ry=r+tube;rz=tube;break;
40
+ default:throw new ArgumentException("Unsupported build shape: "+operation.Name);
41
+ }
42
+ // Sample voxel centers in the same Y-up coordinates as the preview. Torus lies in XY.
43
+ int xmin=(int)Math.Ceiling(cx-rx-.5),xmax=(int)Math.Floor(cx+rx-.5),ymin=(int)Math.Ceiling(cy-ry-.5),ymax=(int)Math.Floor(cy+ry-.5),zmin=(int)Math.Ceiling(cz-rz-.5),zmax=(int)Math.Floor(cz+rz-.5);
44
+ if(cx-rx < -1_000_000 || cx+rx>1_000_000 || cz-rz < -1_000_000 || cz+rz>1_000_000 || cy-ry<1 || cy+ry>(WorldGenerator.MaxChunkY+1)*WorldConstants.ChunkSize)throw new ArgumentException("Build exceeds world bounds.");
45
+ candidates+=(long)Math.Max(0,xmax-xmin+1)*Math.Max(0,ymax-ymin+1)*Math.Max(0,zmax-zmin+1);
46
+ if(candidates>262144)throw new ArgumentException("Build sampling budget exceeded.");
47
+ var color=a.TryGetProperty("color",out var c)?(c.ValueKind==JsonValueKind.String?c.GetString():null):"#5ad1c4";
48
+ if(color is null || !Regex.IsMatch(color,"^#[0-9a-fA-F]{6}$"))throw new ArgumentException("Invalid build color.");
49
+ // Quantize to the existing ten material families; save schema retains packed voxel materials.
50
+ int red=Convert.ToInt32(color.Substring(1,2),16),green=Convert.ToInt32(color.Substring(3,2),16),blue=Convert.ToInt32(color.Substring(5,2),16);
51
+ var material=red>green&&red>blue?MaterialFamily.Ceramic:green>red&&green>blue?MaterialFamily.Wood:blue>red?MaterialFamily.Glass:MaterialFamily.Concrete;
52
+ ushort packed=new Voxel(BlockType.Wall,material).Packed;
53
+ for(int x=xmin;x<=xmax;x++)for(int y=ymin;y<=ymax;y++)for(int z=zmin;z<=zmax;z++) {
54
+ double dx=x+.5-cx,dy=y+.5-cy,dz=z+.5-cz;
55
+ bool inside=operation.Name switch {
56
+ "add_sphere"=>dx*dx+dy*dy+dz*dz<=r*r,
57
+ "add_cylinder"=>dx*dx+dz*dz<=r*r,
58
+ "add_cone"=>dx*dx+dz*dz<=Math.Pow(r*(.5-dy/h),2),
59
+ "add_torus"=>Math.Pow(Math.Sqrt(dx*dx+dy*dy)-r,2)+dz*dz<=tube*tube,
60
+ _=>true
61
+ };
62
+ if(!inside)continue;result[(x,y,z)]=new(x,y,z,packed);
63
+ if(result.Count>MaxVoxels)throw new ArgumentException("Build voxel budget exceeded.");
64
+ }
65
+ }
66
+ if(result.Count==0)throw new ArgumentException("Shapes are too small for this voxel grid. Increase their size.");
67
+ return result.Values.ToArray();
68
+ }
69
+ }
src/Repoverse.Core/Bridge/LocalSourceReader.cs ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using Repoverse.Core.Generation;
2
+
3
+ namespace Repoverse.Core.Bridge;
4
+
5
+ public sealed record SourcePage(string Path, int Offset, string[] Lines, bool HasMore);
6
+ /// <summary>Read-only, bounded source pages for artifacts in one explicitly mapped local repository.</summary>
7
+ public sealed class LocalSourceReader(WorldManifest manifest, string repo, string sourceRoot)
8
+ {
9
+ private readonly string _root = Path.GetFullPath(sourceRoot);
10
+ private readonly HashSet<string> _allowed = manifest.Buildings.Where(b => b.Repo.Key == repo.ToLowerInvariant())
11
+ .SelectMany(b => b.Interior.Rooms).SelectMany(r => r.Artifacts).Select(a => a.Path).ToHashSet(StringComparer.Ordinal);
12
+ public SourcePage Read(string requestedRepo, string relative, int offset)
13
+ {
14
+ if (!requestedRepo.Equals(repo,StringComparison.OrdinalIgnoreCase) || !_allowed.Contains(relative))
15
+ throw new ArgumentException("Source is not an artifact in the mapped repository.");
16
+ if (offset is < 0 or > 100_000 || Path.IsPathRooted(relative)) throw new ArgumentException("Invalid source page.");
17
+ var parts = relative.Replace('\\','/').Split('/');
18
+ if (parts.Any(p => p is "" or "." or ".." || p.Contains(':'))) throw new ArgumentException("Invalid source path.");
19
+ // Reject links/junctions at every component, including the configured root.
20
+ var target = _root;
21
+ if ((File.GetAttributes(target) & FileAttributes.ReparsePoint) != 0) throw new ArgumentException("Linked source roots are unsupported.");
22
+ foreach (var part in parts) {
23
+ target = Path.Combine(target,part);
24
+ if ((File.GetAttributes(target) & FileAttributes.ReparsePoint) != 0) throw new ArgumentException("Linked source paths are unsupported.");
25
+ }
26
+ if (new FileInfo(target).Length > 2*1024*1024) throw new ArgumentException("Source exceeds the 2 MiB inspection limit.");
27
+ var text = File.ReadAllText(target);
28
+ if (text.Contains('\0')) throw new ArgumentException("Binary artifact; open it in its native application.");
29
+ var lines = text.Replace("\r\n","\n").Split('\n');
30
+ return new(relative,offset,lines.Skip(offset).Take(32).Select(s => s.Length>240 ? s[..240]+"..." : s).ToArray(),offset+32<lines.Length);
31
+ }
32
+ }
src/Repoverse.Core/Bridge/WorldSession.cs ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using Repoverse.Core.Generation;
2
+ using Repoverse.Core.Model;
3
+ using Repoverse.Core.Persistence;
4
+ using Repoverse.Core.Voxels;
5
+
6
+ namespace Repoverse.Core.Bridge;
7
+
8
+ public sealed record MeshSection(ushort Key, bool Collision, float[][] Vertices, int[] Indices);
9
+ public sealed record MeshPacket(string Id, IReadOnlyList<MeshSection> Sections);
10
+ public sealed record StreamPacket(IReadOnlyList<string> Unloaded, IReadOnlyList<MeshPacket> Chunks, int Remaining, int Resident);
11
+ public sealed record Destination(string Repo, string Description, double X, double Y, double Z,
12
+ int Floors, int LadderX, int LadderZ, IReadOnlyList<RoomPlacement> Rooms);
13
+
14
+ /// <summary>Single-client, serialized bridge session. Core Y-up units remain authoritative.</summary>
15
+ public sealed class WorldSession
16
+ {
17
+ private readonly WorldGenerator _generator;
18
+ private readonly Dictionary<ChunkCoord, Chunk> _chunks = new();
19
+ private readonly HashSet<ChunkCoord> _dirty = new();
20
+ private readonly int _radius;
21
+ public WorldManifest Manifest { get; }
22
+ public WorldEdits Edits { get; } = new();
23
+ public PlayerState Player { get; private set; }
24
+ public long Tick { get; private set; }
25
+ public IReadOnlyList<BuilderState> Builders => _builders.Values.ToArray();
26
+ private readonly Dictionary<string,BuilderState> _builders = new(StringComparer.Ordinal);
27
+ public IReadOnlyList<Destination> Destinations { get; }
28
+ public int Resident => _chunks.Count;
29
+
30
+ public WorldSession(WorldManifest manifest, int radius = 1)
31
+ {
32
+ if (manifest.SchemaVersion != WorldManifest.CurrentSchema) throw new InvalidDataException("Unsupported manifest schema.");
33
+ if (radius is < 0 or > 3) throw new ArgumentOutOfRangeException(nameof(radius));
34
+ Manifest = manifest; _radius = radius; _generator = new(manifest);
35
+ Destinations = manifest.Buildings.Select(b => {
36
+ var p = BuildingRasterizer.Plan(b);
37
+ return new Destination(b.Repo.Key, b.Description, p.Entrance.X + 3.5,
38
+ p.Entrance.Y + 1.5, p.Entrance.Z + .5, b.Floors, p.LadderX, p.CorridorZ + 1, p.Rooms);
39
+ }).ToArray();
40
+ var start = Destinations.FirstOrDefault();
41
+ Player = new PlayerState { X = start?.X ?? 10, Y = start?.Y ?? 11, Z = start?.Z ?? 10, Yaw = 180 };
42
+ }
43
+
44
+ public static void Validate(PlayerState p)
45
+ {
46
+ if (!double.IsFinite(p.X) || !double.IsFinite(p.Y) || !double.IsFinite(p.Z) || !double.IsFinite(p.Yaw)
47
+ || Math.Abs(p.X) > 1_000_000 || Math.Abs(p.Z) > 1_000_000 || p.Y < -100 || p.Y > 10_000
48
+ || !Enum.IsDefined(p.Mode)) throw new ArgumentException("Invalid player state.");
49
+ }
50
+
51
+ public void SetPlayer(PlayerState player) { Validate(player); Player = player; }
52
+
53
+ private static IEnumerable<ChunkCoord> Neighbours(ChunkCoord c)
54
+ {
55
+ yield return c;
56
+ yield return c with { X = c.X - 1 }; yield return c with { X = c.X + 1 };
57
+ yield return c with { Y = c.Y - 1 }; yield return c with { Y = c.Y + 1 };
58
+ yield return c with { Z = c.Z - 1 }; yield return c with { Z = c.Z + 1 };
59
+ }
60
+ private static int Distance(ChunkCoord a, ChunkCoord b) => Math.Max(Math.Abs(a.X-b.X), Math.Abs(a.Z-b.Z));
61
+
62
+ /// <summary>Bounded generation and upload, nearest first. Unloads are sent before replacement meshes.</summary>
63
+ public StreamPacket Focus(double x, double z, int budget = 4)
64
+ {
65
+ Validate(Player with { X = x, Z = z });
66
+ if (budget is < 1 or > 16) throw new ArgumentOutOfRangeException(nameof(budget));
67
+ var center = ChunkCoord.FromVoxel((int)Math.Floor(x), WorldConstants.GroundLevel, (int)Math.Floor(z));
68
+ var unloaded = new List<string>();
69
+ foreach (var c in _chunks.Keys.Where(c => Distance(c, center) > _radius + 1).ToArray())
70
+ {
71
+ _chunks.Remove(c); _dirty.Remove(c); unloaded.Add(c.ToString());
72
+ foreach (var n in Neighbours(c)) if (_chunks.ContainsKey(n)) _dirty.Add(n);
73
+ }
74
+ var wanted = new List<ChunkCoord>();
75
+ for (int dx = -_radius; dx <= _radius; dx++)
76
+ for (int dz = -_radius; dz <= _radius; dz++)
77
+ for (int y = 0; y <= WorldGenerator.MaxChunkY; y++)
78
+ wanted.Add(new(center.X + dx, y, center.Z + dz));
79
+ wanted = wanted.OrderBy(c => Distance(c, center)).ThenBy(c => c.Y).ThenBy(c => c.X).ThenBy(c => c.Z).ToList();
80
+ foreach (var c in wanted.Where(c => !_chunks.ContainsKey(c)).Take(budget))
81
+ {
82
+ _chunks[c] = _generator.Generate(c, Edits);
83
+ foreach (var n in Neighbours(c)) if (_chunks.ContainsKey(n)) _dirty.Add(n);
84
+ }
85
+ var result = new List<MeshPacket>();
86
+ foreach (var c in _dirty.OrderBy(c => Distance(c, center)).ThenBy(c => c.Y).ThenBy(c => c.X).ThenBy(c => c.Z).Take(budget).ToArray())
87
+ {
88
+ result.Add(Encode(GreedyMesher.Build(_chunks[c], Sample)));
89
+ _dirty.Remove(c);
90
+ }
91
+ Tick++;
92
+ return new(unloaded, result, wanted.Count(c => !_chunks.ContainsKey(c)) + _dirty.Count, _chunks.Count);
93
+ }
94
+ public Voxel? Sample(int x, int y, int z) => _chunks.TryGetValue(ChunkCoord.FromVoxel(x,y,z), out var c)
95
+ ? c[x-c.Coord.OriginX, y-c.Coord.OriginY, z-c.Coord.OriginZ] : null;
96
+
97
+ public static MeshPacket Encode(ChunkMesh mesh)
98
+ {
99
+ var sections = new List<MeshSection>();
100
+ foreach (var group in mesh.Quads.GroupBy(q => q.MeshKey).OrderBy(g => g.Key))
101
+ {
102
+ var vertices = new List<float[]>(); var indices = new List<int>();
103
+ foreach (var q in group)
104
+ {
105
+ int i = vertices.Count;
106
+ vertices.AddRange(GreedyMesher.Corners(mesh.Coord, q).Select(v => new[] {v.X,v.Y,v.Z}));
107
+ indices.AddRange([i,i+1,i+2,i,i+2,i+3]);
108
+ }
109
+ sections.Add(new(group.Key, !new Voxel(group.Key).IsPassable, vertices.ToArray(), indices.ToArray()));
110
+ }
111
+ return new(mesh.Coord.ToString(), sections);
112
+ }
113
+ public IReadOnlyList<WorldObject> Objects() => Manifest.Buildings.SelectMany(BuildingRasterizer.Objects).ToArray();
114
+ public void Edit(int x, int y, int z, ushort packed)
115
+ {
116
+ if (y < 1 || y > WorldGenerator.MaxChunkY * WorldConstants.ChunkSize + 31 || Math.Abs((long)x)>1_000_000 || Math.Abs((long)z)>1_000_000
117
+ || !Enum.IsDefined(new Voxel(packed).Type)) throw new ArgumentException("Invalid voxel edit.");
118
+ Edits.Set(x,y,z,new Voxel(packed));
119
+ var c = ChunkCoord.FromVoxel(x,y,z);
120
+ if (_chunks.ContainsKey(c)) _chunks[c] = _generator.Generate(c,Edits);
121
+ foreach (var n in Neighbours(c)) if (_chunks.ContainsKey(n)) _dirty.Add(n);
122
+ }
123
+ public BuilderState Build(BuilderPlan plan)
124
+ {
125
+ var voxels=BuilderRasterizer.Rasterize(plan);
126
+ if(!_builders.ContainsKey(plan.Actor) && _builders.Count>=16)throw new ArgumentException("Builder actor limit reached.");
127
+ var changed=new HashSet<ChunkCoord>();
128
+ foreach(var v in voxels){Edits.Set(v.X,v.Y,v.Z,new Voxel(v.Packed));changed.Add(ChunkCoord.FromVoxel(v.X,v.Y,v.Z));}
129
+ foreach(var c in changed){if(_chunks.ContainsKey(c))_chunks[c]=_generator.Generate(c,Edits);foreach(var n in Neighbours(c))if(_chunks.ContainsKey(n))_dirty.Add(n);}
130
+ var last=voxels[^1];var state=new BuilderState(plan.Actor,plan.Id,last.X+.5,last.Y+1,last.Z+.5,voxels.Count);_builders[plan.Actor]=state;return state;
131
+ }
132
+ public SaveGame Capture() => SaveGame.Capture(Manifest, Player, Edits, Tick) with {Builders=Builders};
133
+ public void Restore(SaveGame save)
134
+ {
135
+ if (save.WorldSeed != Manifest.WorldSeed || save.Generator != Manifest.Generator
136
+ || save.Snapshots.Count != Manifest.Snapshots.Count || save.Snapshots.Any(s => !Manifest.Snapshots.TryGetValue(s.Key,out var v) || v != s.Value))
137
+ throw new InvalidDataException("Save belongs to a different world snapshot.");
138
+ Validate(save.Player);
139
+ // Validate in a temporary store before changing the live session.
140
+ var restored = new WorldEdits(); save.RestoreEdits(restored);
141
+ if(save.Builders.Count>16 || save.Builders.Any(b=>string.IsNullOrWhiteSpace(b.Actor)||b.Actor.Length>64||!double.IsFinite(b.X)||!double.IsFinite(b.Y)||!double.IsFinite(b.Z)) || save.Builders.Select(b=>b.Actor).Distinct().Count()!=save.Builders.Count)throw new InvalidDataException("Invalid saved builders.");
142
+ Edits.Load(restored.Snapshot()); Player = save.Player; Tick = save.SimulationTick;
143
+ _builders.Clear();foreach(var b in save.Builders)_builders.Add(b.Actor,b);
144
+ foreach (var c in _chunks.Keys.ToArray()) { _chunks[c] = _generator.Generate(c,Edits); _dirty.Add(c); }
145
+ }
146
+ }
src/Repoverse.Core/Generation/Classifier.cs ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using Repoverse.Core.Model;
2
+
3
+ namespace Repoverse.Core.Generation;
4
+
5
+ /// <summary>
6
+ /// Deterministic, rule-based semantic classification. Each rule contributes weighted
7
+ /// evidence; the highest total wins and the winning evidence becomes the provenance.
8
+ /// Purpose signals (topics, description, file layout) outweigh language (§80).
9
+ /// </summary>
10
+ public static class Classifier
11
+ {
12
+ /// <summary>A rule returns how many independent signals matched; weight applies per signal, capped at 3.</summary>
13
+ private sealed record Rule(SemanticCategory Category, int Weight, string Name, Func<CanonicalRepository, int> Match);
14
+
15
+ /// <summary>
16
+ /// Counts keywords present as whole words in name, description and topics. Text and keywords are
17
+ /// both reduced to space-separated alphanumeric tokens, so "Guppy-to-IR" matches "ir" and
18
+ /// "multi-agent" matches "multi agent". A trailing '*' makes a keyword a word prefix.
19
+ /// </summary>
20
+ private static int Mentions(CanonicalRepository r, params string[] words)
21
+ {
22
+ var text = Tokens($"{r.Id.Name} {r.Description} {string.Join(' ', r.Topics)}");
23
+ return words.Count(w => w.EndsWith('*')
24
+ ? text.Contains(Tokens(w[..^1]).TrimEnd(), StringComparison.Ordinal)
25
+ : text.Contains(Tokens(w), StringComparison.Ordinal));
26
+ }
27
+
28
+ private static string Tokens(string s) => " " + TokenSplit.Replace(s.ToLowerInvariant(), " ").Trim() + " ";
29
+ private static readonly System.Text.RegularExpressions.Regex TokenSplit = new("[^a-z0-9]+");
30
+
31
+ private static int One(bool b) => b ? 1 : 0;
32
+
33
+ private static bool HasFile(CanonicalRepository r, Func<string, bool> pred) =>
34
+ r.Tree.Any(e => e.Kind == TreeEntryKind.File && pred(e.Path.ToLowerInvariant()));
35
+
36
+ private static bool HasExt(CanonicalRepository r, params string[] exts) =>
37
+ HasFile(r, p => exts.Any(x => p.EndsWith(x, StringComparison.Ordinal)));
38
+
39
+ private static bool Lang(CanonicalRepository r, params string[] langs) =>
40
+ r.PrimaryLanguage is { } l && langs.Contains(l, StringComparer.OrdinalIgnoreCase);
41
+
42
+ private static readonly Rule[] Rules =
43
+ [
44
+ new(SemanticCategory.FormalVerification, 6, "proof-sources", r => One(HasExt(r, ".lean", ".v", ".agda", ".idr", ".thy", ".tla"))),
45
+ new(SemanticCategory.FormalVerification, 4, "mentions-proof", r => Mentions(r, "proof*", "verified", "formal", "theorem*", "lean4", "coq")),
46
+ new(SemanticCategory.Compiler, 5, "mentions-compiler", r => Mentions(r, "compiler", "codegen", "llvm", "parser", "interpreter", "wasm", "ir", "lowering")),
47
+ new(SemanticCategory.Compiler, 3, "grammar-files", r => One(HasExt(r, ".g4", ".y", ".lalrpop", ".ll"))),
48
+ new(SemanticCategory.OperatingSystem, 6, "mentions-os", r => Mentions(r, "kernel", "microkernel", "operating system", "bootloader", "hypervisor")),
49
+ new(SemanticCategory.OperatingSystem, 3, "linker-script", r => One(HasExt(r, ".ld", ".lds"))),
50
+ new(SemanticCategory.CryptographicCore, 6, "mentions-crypto", r => Mentions(r, "crypto", "cipher", "signature", "ed25519", "zk", "zero-knowledge", "encryption")),
51
+ new(SemanticCategory.Financial, 6, "mentions-finance", r => Mentions(r, "finance", "trading", "ledger", "payment", "bank", "exchange", "portfolio")),
52
+ new(SemanticCategory.Quantum, 6, "mentions-quantum", r => Mentions(r, "quantum", "qubit", "qiskit", "qir", "circuit")),
53
+ new(SemanticCategory.Hardware, 6, "hdl-sources", r => One(HasExt(r, ".v", ".sv", ".vhd", ".vhdl", ".kicad_pcb", ".sch"))),
54
+ new(SemanticCategory.Hardware, 4, "mentions-hardware", r => Mentions(r, "fpga", "firmware", "embedded", "pcb", "risc-v", "microcontroller")),
55
+ new(SemanticCategory.Training, 6, "mentions-training", r => Mentions(r, "dataset", "corpus", "training", "fine-tune", "finetune")),
56
+ new(SemanticCategory.AgentSystem, 5, "mentions-agent", r => Mentions(r, "agent*", "multi-agent", "autonomous", "llm", "mcp")),
57
+ new(SemanticCategory.Simulation, 5, "mentions-simulation", r => Mentions(r, "simulat*", "voxel", "physics", "game")),
58
+ new(SemanticCategory.Database, 6, "mentions-database", r => Mentions(r, "database", "storage engine", "sql", "kv store")),
59
+ new(SemanticCategory.Networking, 5, "mentions-network", r => Mentions(r, "network", "protocol", "http", "rpc", "proxy", "p2p")),
60
+ new(SemanticCategory.WebInterface, 4, "mentions-web", r => Mentions(r, "frontend", "website", "dashboard", "ui", "react", "web app")),
61
+ new(SemanticCategory.WebInterface, 3, "web-language", r => One(Lang(r, "TypeScript", "JavaScript", "HTML", "CSS", "Vue", "Svelte"))),
62
+ new(SemanticCategory.Documentation, 4, "docs-only", r => One(r.Tree.Count > 0 && r.Tree.Where(e => e.Kind == TreeEntryKind.File)
63
+ .All(e => e.Path.EndsWith(".md", StringComparison.OrdinalIgnoreCase) || e.Path.EndsWith(".txt", StringComparison.OrdinalIgnoreCase) || e.Path.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase)))),
64
+ new(SemanticCategory.SystemsInfrastructure, 3, "systems-language", r => One(Lang(r, "Rust", "C", "C++", "Zig", "Go", "Assembly"))),
65
+ new(SemanticCategory.SystemsInfrastructure, 4, "mentions-infra", r => Mentions(r, "infrastructure", "deploy", "orchestrat*", "ci/cd", "terraform", "runtime")),
66
+ ];
67
+
68
+ public static Derived<SemanticCategory> Classify(CanonicalRepository repo, Overrides? overrides = null)
69
+ {
70
+ if (overrides?.Category(repo.Id) is { } forced)
71
+ return new(forced, Provenance.Override(overrides.Source));
72
+
73
+ var scores = new Dictionary<SemanticCategory, (int Score, List<string> Evidence)>();
74
+ foreach (var rule in Rules)
75
+ {
76
+ var hits = Math.Min(3, rule.Match(repo));
77
+ if (hits == 0) continue;
78
+ if (!scores.TryGetValue(rule.Category, out var s)) s = (0, []);
79
+ s.Evidence.Add(hits > 1 ? $"{rule.Name}x{hits}" : rule.Name);
80
+ scores[rule.Category] = (s.Score + rule.Weight * hits, s.Evidence);
81
+ }
82
+
83
+ if (scores.Count == 0)
84
+ return new(SemanticCategory.Experimental, new("classifier:fallback", "no rule matched"));
85
+
86
+ // Ties break on enum order so the result never depends on dictionary iteration.
87
+ var best = scores.OrderByDescending(kv => kv.Value.Score).ThenBy(kv => (int)kv.Key).First();
88
+ return new(best.Key, new("classifier:rules", $"{string.Join('+', best.Value.Evidence)} (score {best.Value.Score})"));
89
+ }
90
+
91
+ public static District DistrictFor(SemanticCategory c, bool archived) => archived ? District.Archive : c switch
92
+ {
93
+ SemanticCategory.OperatingSystem or SemanticCategory.Compiler => District.Kernel,
94
+ SemanticCategory.SystemsInfrastructure or SemanticCategory.Networking => District.Infrastructure,
95
+ SemanticCategory.CryptographicCore => District.Security,
96
+ SemanticCategory.FormalVerification => District.FormalMethods,
97
+ SemanticCategory.Financial => District.Financial,
98
+ SemanticCategory.Quantum => District.QuantumResearch,
99
+ SemanticCategory.Hardware => District.HardwareIndustrial,
100
+ SemanticCategory.Training => District.Training,
101
+ SemanticCategory.AgentSystem => District.Agent,
102
+ SemanticCategory.Simulation => District.Ai,
103
+ SemanticCategory.Database => District.Data,
104
+ SemanticCategory.WebInterface => District.WebInterface,
105
+ SemanticCategory.Documentation => District.Archive,
106
+ _ => District.Experimental,
107
+ };
108
+
109
+ public static BuildingArchetype ArchetypeFor(SemanticCategory c) => c switch
110
+ {
111
+ SemanticCategory.Compiler => BuildingArchetype.Foundry,
112
+ SemanticCategory.OperatingSystem or SemanticCategory.SystemsInfrastructure => BuildingArchetype.ControlTower,
113
+ SemanticCategory.CryptographicCore => BuildingArchetype.Vault,
114
+ SemanticCategory.FormalVerification => BuildingArchetype.ProofChamber,
115
+ SemanticCategory.Financial => BuildingArchetype.Exchange,
116
+ SemanticCategory.Quantum or SemanticCategory.Hardware or SemanticCategory.Simulation => BuildingArchetype.Laboratory,
117
+ SemanticCategory.Training or SemanticCategory.Documentation => BuildingArchetype.Library,
118
+ SemanticCategory.WebInterface => BuildingArchetype.Studio,
119
+ SemanticCategory.Database => BuildingArchetype.Warehouse,
120
+ SemanticCategory.Networking => BuildingArchetype.Relay,
121
+ SemanticCategory.AgentSystem => BuildingArchetype.Commons,
122
+ _ => BuildingArchetype.Workshop,
123
+ };
124
+ }
src/Repoverse.Core/Generation/ManifestBuilder.cs ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using Repoverse.Core.Model;
2
+ using static Repoverse.Core.WorldConstants;
3
+
4
+ namespace Repoverse.Core.Generation;
5
+
6
+ /// <summary>
7
+ /// Canonical repositories → world manifest. Pure and deterministic: same snapshot,
8
+ /// seed, overrides and previous manifest give an equal manifest (§59).
9
+ /// </summary>
10
+ public static class ManifestBuilder
11
+ {
12
+ private const int RoomWidth = 6;
13
+
14
+ /// <summary>Plot slots of a district ordered outward from its centre, so districts grow as compact blobs.</summary>
15
+ private static readonly (int Col, int Row)[] SpiralSlots = Enumerable.Range(0, DistrictSide * DistrictSide)
16
+ .Select(i => (Col: i % DistrictSide, Row: i / DistrictSide))
17
+ .OrderBy(s => Math.Max(Math.Abs(s.Col * 2 + 1 - DistrictSide), Math.Abs(s.Row * 2 + 1 - DistrictSide)))
18
+ .ThenBy(s => Math.Atan2(s.Row * 2 + 1 - DistrictSide, s.Col * 2 + 1 - DistrictSide))
19
+ .ToArray();
20
+
21
+ public static (int X, int Z) DistrictOrigin(District d)
22
+ {
23
+ var i = (int)d;
24
+ const int stride = DistrictSpan + 2 * PlotSize; // avenue between districts
25
+ return (i % DistrictGridColumns * stride, i / DistrictGridColumns * stride);
26
+ }
27
+
28
+ public static (int X, int Z) PlotOrigin(PlotAddress plot)
29
+ {
30
+ var (ox, oz) = DistrictOrigin(plot.District);
31
+ var (col, row) = SpiralSlots[plot.Slot];
32
+ return (ox + col * PlotSize, oz + row * PlotSize);
33
+ }
34
+
35
+ public static WorldManifest Build(
36
+ IReadOnlyList<CanonicalRepository> repos,
37
+ Seed worldSeed,
38
+ Overrides? overrides = null,
39
+ WorldManifest? previous = null)
40
+ {
41
+ overrides ??= Overrides.Empty;
42
+ var ordered = repos.OrderBy(r => r.Id.Key, StringComparer.Ordinal).ToList();
43
+ var dup = ordered.GroupBy(r => r.Id.Key).FirstOrDefault(g => g.Count() > 1);
44
+ if (dup != null) throw new ArgumentException($"Repository '{dup.Key}' appears twice in the snapshot.");
45
+
46
+ var classified = ordered.Select(r =>
47
+ {
48
+ var category = Classifier.Classify(r, overrides);
49
+ var district = overrides.District(r.Id) is { } d
50
+ ? new Derived<District>(d, Provenance.Override(overrides.Source))
51
+ : new Derived<District>(Classifier.DistrictFor(category.Value, r.Archived),
52
+ new("district-from-category", r.Archived ? "archived" : category.Value.ToString()));
53
+ return (Repo: r, Category: category, District: district);
54
+ }).ToList();
55
+
56
+ // Sticky placement (§7, §85): a repo keeps its plot while it stays in the same district;
57
+ // newcomers take the innermost free slot in id order.
58
+ var taken = new Dictionary<District, HashSet<int>>();
59
+ var slotOf = new Dictionary<string, PlotAddress>();
60
+ foreach (var c in classified)
61
+ {
62
+ var old = previous?.Find(c.Repo.Id);
63
+ if (old == null || old.Plot.District != c.District.Value) continue;
64
+ if (!taken.TryGetValue(old.Plot.District, out var set)) taken[old.Plot.District] = set = [];
65
+ if (set.Add(old.Plot.Slot)) slotOf[c.Repo.Id.Key] = old.Plot;
66
+ }
67
+ foreach (var c in classified)
68
+ {
69
+ if (slotOf.ContainsKey(c.Repo.Id.Key)) continue;
70
+ if (!taken.TryGetValue(c.District.Value, out var set)) taken[c.District.Value] = set = [];
71
+ var slot = Enumerable.Range(0, SpiralSlots.Length).FirstOrDefault(s => !set.Contains(s), -1);
72
+ if (slot < 0) throw new InvalidOperationException($"District {c.District.Value} is full ({SpiralSlots.Length} plots).");
73
+ set.Add(slot);
74
+ slotOf[c.Repo.Id.Key] = new PlotAddress(c.District.Value, slot);
75
+ }
76
+
77
+ var inWorld = ordered.Select(r => r.Id.Key).ToHashSet();
78
+ var buildings = classified.Select(c => Transform(c.Repo, c.Category, c.District, slotOf[c.Repo.Id.Key], worldSeed, overrides)).ToList();
79
+ var edges = ordered
80
+ .SelectMany(r => r.DependsOn.Where(d => inWorld.Contains(d.Key) && d.Key != r.Id.Key).Select(d => new DependencyEdge(r.Id, d)))
81
+ .DistinctBy(e => (e.From.Key, e.To.Key))
82
+ .OrderBy(e => e.From.Key, StringComparer.Ordinal).ThenBy(e => e.To.Key, StringComparer.Ordinal)
83
+ .ToList();
84
+
85
+ return new WorldManifest
86
+ {
87
+ WorldSeed = worldSeed.ToString(),
88
+ Snapshots = ordered.ToDictionary(r => r.Id.Key, r => r.SnapshotId),
89
+ Buildings = buildings,
90
+ Dependencies = edges,
91
+ };
92
+ }
93
+
94
+ /// <summary>
95
+ /// Repository → building (§9). Floors follow module structure (room count), depth follows
96
+ /// code volume, activity follows recent commits, construction follows releases — not size → height.
97
+ /// </summary>
98
+ public static BuildingDefinition Transform(
99
+ CanonicalRepository repo,
100
+ Derived<SemanticCategory> category,
101
+ Derived<District> district,
102
+ PlotAddress plot,
103
+ Seed worldSeed,
104
+ Overrides overrides)
105
+ {
106
+ var seed = worldSeed.Derive("repo:" + repo.Id.Key);
107
+ var archetype = overrides.Archetype(repo.Id) is { } a
108
+ ? new Derived<BuildingArchetype>(a, Provenance.Override(overrides.Source))
109
+ : new Derived<BuildingArchetype>(Classifier.ArchetypeFor(category.Value), new("archetype-from-category", category.Value.ToString()));
110
+ bool landmark = overrides.Landmark(repo.Id);
111
+
112
+ // Count prospective rooms first to size the floor plate, then build the real graph with that width.
113
+ var probe = RoomGraphBuilder.Build(repo, int.MaxValue);
114
+ int workRooms = probe.Rooms.Count(r => r.Purpose is not (RoomPurpose.Lobby or RoomPurpose.Corridor or RoomPurpose.Stairwell));
115
+ int maxPerSide = (MaxFootprint - 2) / RoomWidth;
116
+ int perSide = Math.Clamp((int)Math.Ceiling(Math.Sqrt(Math.Max(1, workRooms))), 1, maxPerSide);
117
+ if (landmark) perSide = maxPerSide;
118
+ var interior = RoomGraphBuilder.Build(repo, perSide * 2);
119
+ int floors = Math.Min(MaxFloors, interior.Rooms.Count(r => r.Purpose == RoomPurpose.Corridor));
120
+
121
+ long codeBytes = repo.Languages.Values.Sum();
122
+ if (codeBytes == 0) codeBytes = repo.Tree.Where(e => e.Kind == TreeEntryKind.File).Sum(e => e.SizeBytes);
123
+ int roomDepth = Math.Clamp(3 + (int)Math.Log2(Math.Max(1, codeBytes / 4096.0) + 1), 4, 10);
124
+
125
+ int width = Math.Clamp(2 + perSide * RoomWidth, MinFootprint, MaxFootprint);
126
+ int depth = Math.Clamp(2 * roomDepth + 7, MinFootprint, MaxFootprint);
127
+ var (px, pz) = PlotOrigin(plot);
128
+ var footprint = new Footprint(px + (PlotSize - width) / 2, pz + (PlotSize - depth) / 2, width, depth);
129
+
130
+ var activity = repo.CommitsLast90Days switch
131
+ {
132
+ 0 => ActivityLevel.Dormant,
133
+ < 10 => ActivityLevel.Low,
134
+ < 50 => ActivityLevel.Moderate,
135
+ _ => ActivityLevel.High,
136
+ };
137
+ var construction = repo.Archived ? ConstructionState.Archived
138
+ : repo.Releases.Any(r => !r.Prerelease) ? ConstructionState.Released
139
+ : repo.Releases.Count > 0 ? ConstructionState.Prerelease
140
+ : ConstructionState.Unreleased;
141
+
142
+ return new BuildingDefinition
143
+ {
144
+ Repo = repo.Id,
145
+ Description = repo.Description ?? "",
146
+ Category = category,
147
+ District = district,
148
+ Archetype = archetype,
149
+ Material = MaterialFor(archetype.Value),
150
+ Plot = plot,
151
+ Footprint = footprint,
152
+ Floors = floors,
153
+ RoomsPerSide = perSide,
154
+ RoomDepth = roomDepth,
155
+ Activity = new(activity, new("commits-in-window", $"{repo.CommitsLast90Days} commits / {ActivityWindowDays}d")),
156
+ Construction = new(construction, new("release-state", repo.Archived ? "archived" : $"{repo.Releases.Count} releases")),
157
+ Landmark = landmark,
158
+ Population = Math.Clamp(repo.Contributors, 1, perSide * 2 * floors),
159
+ Seed = seed.ToString(),
160
+ Interior = interior,
161
+ };
162
+ }
163
+
164
+ public static MaterialFamily MaterialFor(BuildingArchetype a) => a switch
165
+ {
166
+ BuildingArchetype.Foundry => MaterialFamily.Metal,
167
+ BuildingArchetype.ControlTower => MaterialFamily.Concrete,
168
+ BuildingArchetype.Vault => MaterialFamily.Security,
169
+ BuildingArchetype.ProofChamber => MaterialFamily.Stone,
170
+ BuildingArchetype.Exchange => MaterialFamily.Glass,
171
+ BuildingArchetype.Laboratory => MaterialFamily.Laboratory,
172
+ BuildingArchetype.Library => MaterialFamily.Archive,
173
+ BuildingArchetype.Studio => MaterialFamily.Glass,
174
+ BuildingArchetype.Warehouse => MaterialFamily.Concrete,
175
+ BuildingArchetype.Relay => MaterialFamily.Electronics,
176
+ BuildingArchetype.Commons => MaterialFamily.Wood,
177
+ _ => MaterialFamily.Wood,
178
+ };
179
+ }
src/Repoverse.Core/Generation/Overrides.cs ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using System.Text.Json;
2
+ using System.Text.Json.Serialization;
3
+ using Repoverse.Core.Model;
4
+
5
+ namespace Repoverse.Core.Generation;
6
+
7
+ /// <summary>
8
+ /// Hand-authored world design (§83). Overrides augment procedural output; any repo
9
+ /// not listed is generated normally.
10
+ /// </summary>
11
+ public sealed class Overrides
12
+ {
13
+ public sealed record Entry
14
+ {
15
+ public SemanticCategory? Category { get; init; }
16
+ public District? District { get; init; }
17
+ public BuildingArchetype? Archetype { get; init; }
18
+ public bool Landmark { get; init; }
19
+ }
20
+
21
+ private readonly Dictionary<string, Entry> _entries;
22
+ public string Source { get; }
23
+
24
+ public Overrides(IReadOnlyDictionary<string, Entry> entries, string source)
25
+ {
26
+ _entries = entries.ToDictionary(kv => kv.Key.ToLowerInvariant(), kv => kv.Value);
27
+ Source = source;
28
+ }
29
+
30
+ public static Overrides Empty { get; } = new(new Dictionary<string, Entry>(), "(none)");
31
+
32
+ public static Overrides Load(string path)
33
+ {
34
+ var entries = JsonSerializer.Deserialize<Dictionary<string, Entry>>(File.ReadAllText(path), Json.Options)
35
+ ?? throw new InvalidDataException($"Override file '{path}' is empty.");
36
+ return new Overrides(entries, Path.GetFileName(path));
37
+ }
38
+
39
+ private Entry? Get(RepoId id) => _entries.GetValueOrDefault(id.Key);
40
+ public SemanticCategory? Category(RepoId id) => Get(id)?.Category;
41
+ public District? District(RepoId id) => Get(id)?.District;
42
+ public BuildingArchetype? Archetype(RepoId id) => Get(id)?.Archetype;
43
+ public bool Landmark(RepoId id) => Get(id)?.Landmark ?? false;
44
+ }
45
+
46
+ /// <summary>Shared serializer settings: enums as strings so manifests stay human-readable and diffable.</summary>
47
+ public static class Json
48
+ {
49
+ public static JsonSerializerOptions Options { get; } = new()
50
+ {
51
+ WriteIndented = true,
52
+ PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
53
+ DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
54
+ Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase), new RepoIdConverter() },
55
+ };
56
+
57
+ private sealed class RepoIdConverter : JsonConverter<RepoId>
58
+ {
59
+ public override RepoId Read(ref Utf8JsonReader reader, Type t, JsonSerializerOptions o) => RepoId.Parse(reader.GetString()!);
60
+ public override void Write(Utf8JsonWriter writer, RepoId value, JsonSerializerOptions o) => writer.WriteStringValue($"{value.Owner}/{value.Name}");
61
+ }
62
+ }
src/Repoverse.Core/Generation/RoomGraph.cs ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using Repoverse.Core.Model;
2
+
3
+ namespace Repoverse.Core.Generation;
4
+
5
+ public enum RoomPurpose { Lobby, Corridor, Stairwell, Workshop, InspectionLab, Archive, ProofVault, Assembly, Storage, Toolroom, Commons }
6
+
7
+ /// <summary>Software concept a world object stands for (§53).</summary>
8
+ public enum ArtifactKind { SourceTerminal, TestBench, ProofVault, ArchiveShelf, BuildStation, DataRack, ConfigPanel, AssetCrate, NotebookDesk, HardwareBench }
9
+
10
+ public sealed record Artifact(string Path, ArtifactKind Kind, long SizeBytes, string Language);
11
+
12
+ public sealed record Room
13
+ {
14
+ public required int Id { get; init; }
15
+ public required string Name { get; init; }
16
+ public required RoomPurpose Purpose { get; init; }
17
+ public required int Floor { get; init; }
18
+ /// <summary>Repository directories this room represents; several when small dirs were merged.</summary>
19
+ public IReadOnlyList<string> Directories { get; init; } = [];
20
+ public int FileCount { get; init; }
21
+ public IReadOnlyList<Artifact> Artifacts { get; init; } = [];
22
+ }
23
+
24
+ public sealed record Door(int A, int B);
25
+
26
+ /// <summary>Logical interior (§88): rooms and their connections, before any geometry exists.</summary>
27
+ public sealed record RoomGraph(IReadOnlyList<Room> Rooms, IReadOnlyList<Door> Doors)
28
+ {
29
+ public int EntranceId => Rooms.First(r => r.Purpose == RoomPurpose.Lobby).Id;
30
+
31
+ /// <summary>Rooms not reachable from the entrance. Empty for a valid graph (§89).</summary>
32
+ public IReadOnlyList<Room> Unreachable()
33
+ {
34
+ var adj = Rooms.ToDictionary(r => r.Id, _ => new List<int>());
35
+ foreach (var d in Doors) { adj[d.A].Add(d.B); adj[d.B].Add(d.A); }
36
+ var seen = new HashSet<int> { EntranceId };
37
+ var queue = new Queue<int>(seen);
38
+ while (queue.Count > 0)
39
+ foreach (var n in adj[queue.Dequeue()])
40
+ if (seen.Add(n)) queue.Enqueue(n);
41
+ return Rooms.Where(r => !seen.Contains(r.Id)).ToList();
42
+ }
43
+ }
44
+
45
+ public static class RoomGraphBuilder
46
+ {
47
+ public static bool IsIgnored(string path)
48
+ {
49
+ foreach (var segment in path.Split('/'))
50
+ if (WorldConstants.IgnoredDirectories.Contains(segment, StringComparer.OrdinalIgnoreCase))
51
+ return true;
52
+ return false;
53
+ }
54
+
55
+ public static RoomPurpose PurposeFor(string directory)
56
+ {
57
+ var d = directory.ToLowerInvariant();
58
+ var leaf = d[(d.LastIndexOf('/') + 1)..];
59
+ return leaf switch
60
+ {
61
+ "test" or "tests" or "spec" or "specs" or "__tests__" or "testing" => RoomPurpose.InspectionLab,
62
+ "doc" or "docs" or "documentation" or "papers" or "notes" => RoomPurpose.Archive,
63
+ "proof" or "proofs" or "formal" or "theories" or "verification" => RoomPurpose.ProofVault,
64
+ ".github" or "ci" or ".circleci" or "workflows" or "deploy" => RoomPurpose.Assembly,
65
+ "assets" or "data" or "fixtures" or "demo" or "screenshots" or "resources" => RoomPurpose.Storage,
66
+ "scripts" or "tools" or "bin" or "cmd" => RoomPurpose.Toolroom,
67
+ _ => RoomPurpose.Workshop,
68
+ };
69
+ }
70
+
71
+ public static ArtifactKind KindFor(string path)
72
+ {
73
+ var p = path.ToLowerInvariant();
74
+ var name = p[(p.LastIndexOf('/') + 1)..];
75
+ if (name.Contains("test") || name.Contains("spec") || p.Split('/')[..^1].Any(d => d is "test" or "tests" or "spec" or "specs" or "__tests__"))
76
+ return ArtifactKind.TestBench;
77
+ if (name is "makefile" or "cargo.toml" or "package.json" or "cmakelists.txt" or "dockerfile" or "project.toml"
78
+ || name.EndsWith(".csproj") || name.EndsWith(".cabal") || name.EndsWith(".sln") || p.Contains(".github/workflows/"))
79
+ return ArtifactKind.BuildStation;
80
+ var ext = Path.GetExtension(name);
81
+ return ext switch
82
+ {
83
+ ".lean" or ".v" or ".agda" or ".idr" or ".thy" or ".tla" => ArtifactKind.ProofVault,
84
+ ".md" or ".rst" or ".txt" or ".pdf" or ".tex" => ArtifactKind.ArchiveShelf,
85
+ ".json" or ".csv" or ".parquet" or ".sqlite" or ".db" or ".vox" => ArtifactKind.DataRack,
86
+ ".toml" or ".yaml" or ".yml" or ".ini" or ".cfg" or ".lock" => ArtifactKind.ConfigPanel,
87
+ ".png" or ".jpg" or ".svg" or ".zip" or ".wav" or ".glb" => ArtifactKind.AssetCrate,
88
+ ".ipynb" => ArtifactKind.NotebookDesk,
89
+ ".sv" or ".vhd" or ".vhdl" or ".metal" or ".asm" or ".s" => ArtifactKind.HardwareBench,
90
+ _ => ArtifactKind.SourceTerminal,
91
+ };
92
+ }
93
+
94
+ public static string LanguageFor(string path) => Path.GetExtension(path).ToLowerInvariant() switch
95
+ {
96
+ ".cs" => "C#", ".rs" => "Rust", ".py" => "Python", ".hs" => "Haskell", ".jl" => "Julia",
97
+ ".js" or ".mjs" or ".cjs" => "JavaScript", ".ts" or ".tsx" => "TypeScript", ".swift" => "Swift",
98
+ ".c" or ".h" => "C", ".cpp" or ".cc" or ".hpp" => "C++", ".go" => "Go", ".lean" => "Lean",
99
+ ".asm" or ".s" => "Assembly", ".metal" => "Metal", ".m" => "Objective-C", ".pl" => "Prolog",
100
+ ".html" => "HTML", ".css" => "CSS", ".md" => "Markdown", ".json" => "JSON", ".toml" => "TOML",
101
+ ".yml" or ".yaml" => "YAML", ".idr" => "Idris", ".zig" => "Zig", ".java" => "Java", ".kt" => "Kotlin",
102
+ _ => "Other",
103
+ };
104
+
105
+ /// <summary>
106
+ /// Groups the tree into rooms by top-level directory (then second level for large ones),
107
+ /// merges tiny directories into a Commons room, and lays rooms out over floors joined
108
+ /// by a stairwell. Every room hangs off its floor's corridor, so the graph is connected
109
+ /// by construction; <see cref="RoomGraph.Unreachable"/> verifies it.
110
+ /// </summary>
111
+ public static RoomGraph Build(CanonicalRepository repo, int roomsPerFloor)
112
+ {
113
+ var files = repo.Tree
114
+ .Where(e => e.Kind == TreeEntryKind.File && !IsIgnored(e.Path))
115
+ .OrderBy(e => e.Path, StringComparer.Ordinal)
116
+ .ToList();
117
+
118
+ // Bucket by top-level directory; split big buckets one level deeper.
119
+ var buckets = new SortedDictionary<string, List<TreeEntry>>(StringComparer.Ordinal);
120
+ void Add(string key, TreeEntry e)
121
+ {
122
+ if (!buckets.TryGetValue(key, out var list)) buckets[key] = list = [];
123
+ list.Add(e);
124
+ }
125
+ var byTop = files.GroupBy(f => f.Path.Contains('/') ? f.Path[..f.Path.IndexOf('/')] : "");
126
+ foreach (var group in byTop)
127
+ {
128
+ var items = group.ToList();
129
+ bool split = group.Key != "" && items.Count > WorldConstants.MaxArtifactsPerRoom;
130
+ foreach (var e in items)
131
+ {
132
+ if (!split) { Add(group.Key, e); continue; }
133
+ var rest = e.Path[(group.Key.Length + 1)..];
134
+ Add(rest.Contains('/') ? $"{group.Key}/{rest[..rest.IndexOf('/')]}" : group.Key, e);
135
+ }
136
+ }
137
+
138
+ var roomDirs = new List<(string Name, List<string> Dirs, List<TreeEntry> Files)>();
139
+ var commons = (Name: "Commons", Dirs: new List<string>(), Files: new List<TreeEntry>());
140
+ foreach (var (dir, list) in buckets)
141
+ {
142
+ if (dir == "" || list.Count < WorldConstants.MinFilesForOwnRoom) { commons.Dirs.Add(dir == "" ? "/" : dir); commons.Files.AddRange(list); }
143
+ else roomDirs.Add((dir, [dir], list));
144
+ }
145
+ // Semantic compression: keep the biggest rooms, fold the tail into Commons.
146
+ var budget = WorldConstants.MaxRoomsPerBuilding - 1;
147
+ foreach (var extra in roomDirs.OrderByDescending(r => r.Files.Count).ThenBy(r => r.Name, StringComparer.Ordinal).Skip(budget).ToList())
148
+ {
149
+ roomDirs.Remove(extra);
150
+ commons.Dirs.AddRange(extra.Dirs);
151
+ commons.Files.AddRange(extra.Files);
152
+ }
153
+ if (commons.Files.Count > 0) roomDirs.Add(commons);
154
+
155
+ var rooms = new List<Room>();
156
+ var doors = new List<Door>();
157
+ int nextId = 0;
158
+ var lobby = new Room { Id = nextId++, Name = "Lobby", Purpose = RoomPurpose.Lobby, Floor = 0 };
159
+ rooms.Add(lobby);
160
+
161
+ int floors = Math.Max(1, (int)Math.Ceiling(roomDirs.Count / (double)roomsPerFloor));
162
+ int prevStair = -1;
163
+ for (int f = 0; f < floors; f++)
164
+ {
165
+ var corridor = new Room { Id = nextId++, Name = $"Corridor {f}", Purpose = RoomPurpose.Corridor, Floor = f };
166
+ var stair = new Room { Id = nextId++, Name = $"Stairwell {f}", Purpose = RoomPurpose.Stairwell, Floor = f };
167
+ rooms.Add(corridor); rooms.Add(stair);
168
+ doors.Add(new Door(corridor.Id, stair.Id));
169
+ if (f == 0) doors.Add(new Door(lobby.Id, corridor.Id));
170
+ if (prevStair >= 0) doors.Add(new Door(prevStair, stair.Id));
171
+ prevStair = stair.Id;
172
+
173
+ foreach (var (name, dirs, list) in roomDirs.Skip(f * roomsPerFloor).Take(roomsPerFloor))
174
+ {
175
+ var room = new Room
176
+ {
177
+ Id = nextId++,
178
+ Name = name,
179
+ Purpose = name == "Commons" ? RoomPurpose.Commons : PurposeFor(name),
180
+ Floor = f,
181
+ Directories = dirs,
182
+ FileCount = list.Count,
183
+ Artifacts = list
184
+ .OrderByDescending(e => KindFor(e.Path) == ArtifactKind.BuildStation)
185
+ .ThenByDescending(e => e.SizeBytes)
186
+ .ThenBy(e => e.Path, StringComparer.Ordinal)
187
+ .Take(WorldConstants.MaxArtifactsPerRoom)
188
+ .Select(e => new Artifact(e.Path, KindFor(e.Path), e.SizeBytes, LanguageFor(e.Path)))
189
+ .ToList(),
190
+ };
191
+ rooms.Add(room);
192
+ doors.Add(new Door(corridor.Id, room.Id));
193
+ }
194
+ }
195
+ return new RoomGraph(rooms, doors);
196
+ }
197
+ }
src/Repoverse.Core/Generation/Seed.cs ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using System.Text;
2
+
3
+ namespace Repoverse.Core.Generation;
4
+
5
+ /// <summary>
6
+ /// Deterministic seed derivation (§8). string.GetHashCode is randomized per process,
7
+ /// so seeds use FNV-1a over UTF-8 followed by a SplitMix64 finalizer.
8
+ /// </summary>
9
+ public readonly record struct Seed(ulong Value)
10
+ {
11
+ public Seed Derive(string scope)
12
+ {
13
+ var h = 14695981039346656037UL ^ Value;
14
+ foreach (var b in Encoding.UTF8.GetBytes(scope))
15
+ {
16
+ h ^= b;
17
+ h *= 1099511628211UL;
18
+ }
19
+ return new Seed(Mix(h));
20
+ }
21
+
22
+ public SeededRandom Random() => new(Value);
23
+
24
+ internal static ulong Mix(ulong z)
25
+ {
26
+ z += 0x9E3779B97F4A7C15UL;
27
+ z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL;
28
+ z = (z ^ (z >> 27)) * 0x94D049BB133111EBUL;
29
+ return z ^ (z >> 31);
30
+ }
31
+
32
+ public override string ToString() => Value.ToString("x16");
33
+ }
34
+
35
+ /// <summary>SplitMix64 stream. Same seed → same sequence on every platform and runtime.</summary>
36
+ public sealed class SeededRandom(ulong state)
37
+ {
38
+ private ulong _state = state;
39
+
40
+ public ulong NextULong()
41
+ {
42
+ _state += 0x9E3779B97F4A7C15UL;
43
+ return Seed.Mix(_state - 0x9E3779B97F4A7C15UL);
44
+ }
45
+
46
+ /// <summary>Uniform integer in [min, maxExclusive).</summary>
47
+ public int Next(int min, int maxExclusive)
48
+ {
49
+ if (maxExclusive <= min) return min;
50
+ return min + (int)(NextULong() % (ulong)(maxExclusive - min));
51
+ }
52
+
53
+ public T Pick<T>(IReadOnlyList<T> items) => items[Next(0, items.Count)];
54
+ }
src/Repoverse.Core/Generation/WorldManifest.cs ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using Repoverse.Core.Model;
2
+
3
+ namespace Repoverse.Core.Generation;
4
+
5
+ public enum ActivityLevel { Dormant, Low, Moderate, High }
6
+ public enum ConstructionState { Unreleased, Prerelease, Released, Archived }
7
+
8
+ public readonly record struct PlotAddress(District District, int Slot);
9
+
10
+ /// <summary>Voxel-space rectangle on the ground plane; Y is implied by <see cref="WorldConstants.GroundLevel"/>.</summary>
11
+ public readonly record struct Footprint(int X, int Z, int Width, int Depth)
12
+ {
13
+ public int MaxX => X + Width - 1;
14
+ public int MaxZ => Z + Depth - 1;
15
+ }
16
+
17
+ /// <summary>What the world generator needs to build one repository's structure (§7, §9).</summary>
18
+ public sealed record BuildingDefinition
19
+ {
20
+ public required RepoId Repo { get; init; }
21
+ public required string Description { get; init; }
22
+ public required Derived<SemanticCategory> Category { get; init; }
23
+ public required Derived<District> District { get; init; }
24
+ public required Derived<BuildingArchetype> Archetype { get; init; }
25
+ public required MaterialFamily Material { get; init; }
26
+ public required PlotAddress Plot { get; init; }
27
+ public required Footprint Footprint { get; init; }
28
+ public required int Floors { get; init; }
29
+ public required int RoomsPerSide { get; init; }
30
+ public required int RoomDepth { get; init; }
31
+ public required Derived<ActivityLevel> Activity { get; init; }
32
+ public required Derived<ConstructionState> Construction { get; init; }
33
+ public required bool Landmark { get; init; }
34
+ /// <summary>Agent seats reserved for Part II's simulation, from contributor count.</summary>
35
+ public required int Population { get; init; }
36
+ public required string Seed { get; init; }
37
+ public required RoomGraph Interior { get; init; }
38
+ public int Height => Floors * WorldConstants.FloorHeight + 1;
39
+ }
40
+
41
+ public sealed record DependencyEdge(RepoId From, RepoId To);
42
+
43
+ public sealed record WorldManifest
44
+ {
45
+ public const int CurrentSchema = 1;
46
+ public const string GeneratorVersion = "repoverse-gen/1";
47
+
48
+ public int SchemaVersion { get; init; } = CurrentSchema;
49
+ public string Generator { get; init; } = GeneratorVersion;
50
+ public required string WorldSeed { get; init; }
51
+ /// <summary>repo key → snapshot id each building was generated from.</summary>
52
+ public required IReadOnlyDictionary<string, string> Snapshots { get; init; }
53
+ public required IReadOnlyList<BuildingDefinition> Buildings { get; init; }
54
+ public required IReadOnlyList<DependencyEdge> Dependencies { get; init; }
55
+
56
+ public BuildingDefinition? Find(RepoId id) => Buildings.FirstOrDefault(b => b.Repo.Key == id.Key);
57
+ }
src/Repoverse.Core/Ingestion/GitHubIngest.cs ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using System.Net;
2
+ using System.Net.Http.Headers;
3
+ using System.Security.Cryptography;
4
+ using System.Text;
5
+ using System.Text.Json;
6
+ using Repoverse.Core.Model;
7
+
8
+ namespace Repoverse.Core.Ingestion;
9
+
10
+ public sealed class RateLimitedException(DateTimeOffset resetsAt) : Exception($"GitHub rate limit reached; resets at {resetsAt:u}.")
11
+ {
12
+ public DateTimeOffset ResetsAt { get; } = resetsAt;
13
+ }
14
+
15
+ public sealed record IngestFailure(string Repo, string Reason);
16
+
17
+ public sealed record IngestResult(IReadOnlyList<CanonicalRepository> Repositories, IReadOnlyList<IngestFailure> Failures, bool RateLimited);
18
+
19
+ /// <summary>
20
+ /// The only place Repoverse talks to GitHub (§25). Responses are cached on disk with their
21
+ /// ETag and re-requested conditionally, so unchanged data costs no rate-limit budget.
22
+ /// A repo that fails to ingest is reported and skipped; it never aborts the whole run.
23
+ /// </summary>
24
+ public sealed class GitHubIngest
25
+ {
26
+ private readonly HttpClient _http;
27
+ private readonly string _cacheDir;
28
+ private readonly TimeProvider _clock;
29
+
30
+ /// <param name="token">Read from the environment or a secret store by the caller; never persisted (§41).</param>
31
+ public GitHubIngest(HttpClient http, string cacheDir, string? token, TimeProvider? clock = null)
32
+ {
33
+ _http = http;
34
+ _cacheDir = cacheDir;
35
+ _clock = clock ?? TimeProvider.System;
36
+ Directory.CreateDirectory(cacheDir);
37
+ _http.BaseAddress ??= new Uri("https://api.github.com/");
38
+ _http.DefaultRequestHeaders.UserAgent.TryParseAdd("repoverse/1");
39
+ _http.DefaultRequestHeaders.Accept.ParseAdd("application/vnd.github+json");
40
+ if (!string.IsNullOrEmpty(token))
41
+ _http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
42
+ }
43
+
44
+ public int RequestsSent { get; private set; }
45
+ public int NotModified { get; private set; }
46
+
47
+ public async Task<IngestResult> IngestOwnerAsync(string owner, bool includeForks = false, int? limit = null, CancellationToken ct = default)
48
+ {
49
+ List<JsonElement> listing;
50
+ try
51
+ {
52
+ // /users/{owner}/repos works for both users and organisations.
53
+ listing = await GetPagedAsync($"users/{Uri.EscapeDataString(owner)}/repos?per_page=100&type=owner&sort=full_name", ct);
54
+ }
55
+ catch (RateLimitedException)
56
+ {
57
+ return new IngestResult([], [new IngestFailure(owner, "rate limited while listing repositories")], true);
58
+ }
59
+
60
+ var repos = new List<CanonicalRepository>();
61
+ var failures = new List<IngestFailure>();
62
+ foreach (var r in listing.Where(r => includeForks || !r.GetProperty("fork").GetBoolean()).Take(limit ?? int.MaxValue))
63
+ {
64
+ var fullName = r.GetProperty("full_name").GetString()!;
65
+ try
66
+ {
67
+ repos.Add(await IngestRepoAsync(r, ct));
68
+ }
69
+ catch (RateLimitedException e)
70
+ {
71
+ failures.Add(new IngestFailure(fullName, e.Message));
72
+ return new IngestResult(repos, failures, true);
73
+ }
74
+ catch (Exception e) when (e is HttpRequestException or JsonException or KeyNotFoundException or InvalidOperationException)
75
+ {
76
+ failures.Add(new IngestFailure(fullName, Redact(e.Message)));
77
+ }
78
+ }
79
+ return new IngestResult(repos, failures, false);
80
+ }
81
+
82
+ private async Task<CanonicalRepository> IngestRepoAsync(JsonElement r, CancellationToken ct)
83
+ {
84
+ var id = RepoId.Parse(r.GetProperty("full_name").GetString()!);
85
+ var path = $"repos/{Uri.EscapeDataString(id.Owner)}/{Uri.EscapeDataString(id.Name)}";
86
+ var branch = r.TryGetProperty("default_branch", out var db) && db.ValueKind == JsonValueKind.String ? db.GetString()! : "main";
87
+ var since = _clock.GetUtcNow().AddDays(-WorldConstants.ActivityWindowDays).ToString("yyyy-MM-ddTHH:mm:ssZ");
88
+
89
+ var languages = (await GetAsync($"{path}/languages", ct)) is { ValueKind: JsonValueKind.Object } langs
90
+ ? langs.EnumerateObject().ToDictionary(p => p.Name, p => p.Value.GetInt64())
91
+ : new Dictionary<string, long>();
92
+
93
+ var tree = new List<TreeEntry>();
94
+ // Empty repositories answer 409 here; treat as an empty tree.
95
+ if (await GetAsync($"{path}/git/trees/{Uri.EscapeDataString(branch)}?recursive=1", ct, allowStatus: HttpStatusCode.Conflict) is { ValueKind: JsonValueKind.Object } t
96
+ && t.TryGetProperty("tree", out var entries))
97
+ {
98
+ foreach (var e in entries.EnumerateArray())
99
+ {
100
+ var type = e.GetProperty("type").GetString();
101
+ if (type is not ("blob" or "tree")) continue; // submodules ("commit") are dependencies, not rooms
102
+ tree.Add(new TreeEntry(e.GetProperty("path").GetString()!,
103
+ type == "tree" ? TreeEntryKind.Directory : TreeEntryKind.File,
104
+ e.TryGetProperty("size", out var s) ? s.GetInt64() : 0));
105
+ }
106
+ }
107
+
108
+ var releases = (await GetPagedAsync($"{path}/releases?per_page=100", ct, maxPages: 1))
109
+ .Where(x => x.TryGetProperty("published_at", out var p) && p.ValueKind == JsonValueKind.String)
110
+ .Select(x => new Release(x.GetProperty("tag_name").GetString()!, x.GetProperty("published_at").GetDateTimeOffset(), x.GetProperty("prerelease").GetBoolean()))
111
+ .ToList();
112
+ var commits = await GetPagedAsync($"{path}/commits?since={since}&per_page=100", ct, maxPages: 3, allowStatus: HttpStatusCode.Conflict);
113
+ var pulls = await GetPagedAsync($"{path}/pulls?state=open&per_page=100", ct, maxPages: 3);
114
+ var contributors = await GetPagedAsync($"{path}/contributors?per_page=100", ct, maxPages: 1, allowStatus: HttpStatusCode.NoContent);
115
+
116
+ var pushed = r.TryGetProperty("pushed_at", out var pa) && pa.ValueKind == JsonValueKind.String ? pa.GetDateTimeOffset() : default;
117
+ return new CanonicalRepository
118
+ {
119
+ Id = id,
120
+ Description = r.TryGetProperty("description", out var d) && d.ValueKind == JsonValueKind.String ? d.GetString() : null,
121
+ PrimaryLanguage = r.TryGetProperty("language", out var l) && l.ValueKind == JsonValueKind.String ? l.GetString() : null,
122
+ Languages = languages,
123
+ Topics = r.TryGetProperty("topics", out var tp) ? tp.EnumerateArray().Select(x => x.GetString()!).ToList() : [],
124
+ SizeKb = r.GetProperty("size").GetInt64(),
125
+ Archived = r.GetProperty("archived").GetBoolean(),
126
+ Fork = r.GetProperty("fork").GetBoolean(),
127
+ DefaultBranch = branch,
128
+ CreatedAt = r.GetProperty("created_at").GetDateTimeOffset(),
129
+ PushedAt = pushed,
130
+ License = r.TryGetProperty("license", out var li) && li.ValueKind == JsonValueKind.Object ? li.GetProperty("spdx_id").GetString() : null,
131
+ // GitHub's open_issues_count includes PRs.
132
+ OpenIssues = Math.Max(0, r.GetProperty("open_issues_count").GetInt32() - pulls.Count),
133
+ OpenPullRequests = pulls.Count,
134
+ Contributors = contributors.Count,
135
+ CommitsLast90Days = commits.Count,
136
+ Releases = releases,
137
+ Tree = tree,
138
+ SnapshotId = $"{pushed:O}",
139
+ };
140
+ }
141
+
142
+ /// <summary>Follows rel="next" Link headers up to <paramref name="maxPages"/>.</summary>
143
+ private async Task<List<JsonElement>> GetPagedAsync(string url, CancellationToken ct, int maxPages = 50, HttpStatusCode? allowStatus = null)
144
+ {
145
+ var items = new List<JsonElement>();
146
+ string? next = url;
147
+ for (int page = 0; next != null && page < maxPages; page++)
148
+ {
149
+ var (json, link) = await SendAsync(next, ct, allowStatus);
150
+ if (json is { ValueKind: JsonValueKind.Array } arr) items.AddRange(arr.EnumerateArray());
151
+ next = NextLink(link);
152
+ }
153
+ return items;
154
+ }
155
+
156
+ private async Task<JsonElement?> GetAsync(string url, CancellationToken ct, HttpStatusCode? allowStatus = null) =>
157
+ (await SendAsync(url, ct, allowStatus)).Json;
158
+
159
+ private async Task<(JsonElement? Json, string? Link)> SendAsync(string url, CancellationToken ct, HttpStatusCode? allowStatus)
160
+ {
161
+ var key = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(url)))[..32];
162
+ var bodyPath = Path.Combine(_cacheDir, key + ".json");
163
+ var metaPath = Path.Combine(_cacheDir, key + ".meta");
164
+ string[] meta = File.Exists(metaPath) ? await File.ReadAllLinesAsync(metaPath, ct) : [];
165
+
166
+ using var req = new HttpRequestMessage(HttpMethod.Get, url);
167
+ if (meta.Length > 0 && meta[0].Length > 0 && File.Exists(bodyPath))
168
+ req.Headers.TryAddWithoutValidation("If-None-Match", meta[0]);
169
+
170
+ RequestsSent++;
171
+ using var res = await _http.SendAsync(req, ct);
172
+ if (res.StatusCode == HttpStatusCode.NotModified)
173
+ {
174
+ NotModified++;
175
+ return (Parse(await File.ReadAllTextAsync(bodyPath, ct)), meta.Length > 1 ? meta[1] : null);
176
+ }
177
+ if (res.StatusCode is HttpStatusCode.Forbidden or HttpStatusCode.TooManyRequests
178
+ && res.Headers.TryGetValues("x-ratelimit-remaining", out var rem) && rem.FirstOrDefault() == "0")
179
+ {
180
+ var reset = res.Headers.TryGetValues("x-ratelimit-reset", out var rs) && long.TryParse(rs.FirstOrDefault(), out var epoch)
181
+ ? DateTimeOffset.FromUnixTimeSeconds(epoch) : _clock.GetUtcNow().AddHours(1);
182
+ throw new RateLimitedException(reset);
183
+ }
184
+ if (allowStatus == res.StatusCode) return (null, null);
185
+ if (!res.IsSuccessStatusCode)
186
+ throw new HttpRequestException($"GET {url} → {(int)res.StatusCode} {res.ReasonPhrase}", null, res.StatusCode);
187
+
188
+ var body = await res.Content.ReadAsStringAsync(ct);
189
+ var link = res.Headers.TryGetValues("Link", out var lv) ? string.Join(",", lv) : null;
190
+ await File.WriteAllTextAsync(bodyPath, body, ct);
191
+ await File.WriteAllLinesAsync(metaPath, [res.Headers.ETag?.ToString() ?? "", link ?? ""], ct);
192
+ return (Parse(body), link);
193
+ }
194
+
195
+ private static JsonElement? Parse(string body) => string.IsNullOrWhiteSpace(body) ? null : JsonDocument.Parse(body).RootElement.Clone();
196
+
197
+ public static string? NextLink(string? link)
198
+ {
199
+ if (link == null) return null;
200
+ foreach (var part in link.Split(','))
201
+ {
202
+ var bits = part.Split(';');
203
+ if (bits.Length > 1 && bits[1..].Any(b => b.Trim() == "rel=\"next\""))
204
+ return bits[0].Trim().TrimStart('<').TrimEnd('>');
205
+ }
206
+ return null;
207
+ }
208
+
209
+ /// <summary>Strips anything token-shaped from text that may end up in logs (§41).</summary>
210
+ public static string Redact(string text) =>
211
+ System.Text.RegularExpressions.Regex.Replace(text, @"(gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|Bearer\s+\S+)", "[REDACTED]");
212
+ }
src/Repoverse.Core/Ingestion/LocalGitIngest.cs ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using System.Diagnostics;
2
+ using Repoverse.Core.Generation;
3
+ using Repoverse.Core.Model;
4
+
5
+ namespace Repoverse.Core.Ingestion;
6
+
7
+ /// <summary>
8
+ /// Builds canonical repositories from a local git checkout, with no network. With
9
+ /// <c>subprojects</c> each top-level directory becomes its own repository, which turns
10
+ /// a monorepo into a multi-building district.
11
+ /// </summary>
12
+ public static class LocalGitIngest
13
+ {
14
+ public static IReadOnlyList<CanonicalRepository> Ingest(string repoPath, string owner, bool subprojects)
15
+ {
16
+ var files = Git(repoPath, "ls-files", "-z").Split('\0', StringSplitOptions.RemoveEmptyEntries);
17
+ var head = Git(repoPath, "rev-parse", "HEAD").Trim();
18
+ var since = $"--since={WorldConstants.ActivityWindowDays}.days";
19
+ var tags = Git(repoPath, "for-each-ref", "--format=%(refname:short)|%(creatordate:iso-strict)", "refs/tags")
20
+ .Split('\n', StringSplitOptions.RemoveEmptyEntries)
21
+ .Select(l => l.Split('|'))
22
+ .Select(p => new Release(p[0], DateTimeOffset.Parse(p[1]), p[0].Contains('-')))
23
+ .ToList();
24
+
25
+ CanonicalRepository Make(string name, string prefix, IEnumerable<string> paths)
26
+ {
27
+ var list = paths.ToList();
28
+ var tree = new List<TreeEntry>();
29
+ var dirs = new SortedSet<string>(StringComparer.Ordinal);
30
+ foreach (var p in list)
31
+ {
32
+ var rel = p[prefix.Length..];
33
+ var full = Path.Combine(repoPath, p);
34
+ tree.Add(new TreeEntry(rel, TreeEntryKind.File, File.Exists(full) ? new FileInfo(full).Length : 0));
35
+ for (int i = rel.IndexOf('/'); i > 0; i = rel.IndexOf('/', i + 1)) dirs.Add(rel[..i]);
36
+ }
37
+ tree.AddRange(dirs.Select(d => new TreeEntry(d, TreeEntryKind.Directory, 0)));
38
+
39
+ var languages = tree.Where(e => e.Kind == TreeEntryKind.File && !RoomGraphBuilder.IsIgnored(e.Path))
40
+ .GroupBy(e => RoomGraphBuilder.LanguageFor(e.Path))
41
+ .Where(g => g.Key is not ("Other" or "Markdown" or "JSON" or "TOML" or "YAML"))
42
+ .ToDictionary(g => g.Key, g => g.Sum(e => e.SizeBytes));
43
+ var scope = prefix.Length == 0 ? "." : prefix.TrimEnd('/');
44
+ var authors = Git(repoPath, "log", "--format=%ae", "--", scope).Split('\n', StringSplitOptions.RemoveEmptyEntries).Distinct().Count();
45
+ var recent = Git(repoPath, "rev-list", "--count", since, "HEAD", "--", scope).Trim();
46
+ var dates = Git(repoPath, "log", "--format=%cI", "--", scope).Split('\n', StringSplitOptions.RemoveEmptyEntries);
47
+
48
+ return new CanonicalRepository
49
+ {
50
+ Id = new RepoId(owner, name),
51
+ Description = ReadmeSummary(repoPath, prefix, list),
52
+ PrimaryLanguage = languages.OrderByDescending(kv => kv.Value).ThenBy(kv => kv.Key).Select(kv => kv.Key).FirstOrDefault(),
53
+ Languages = languages,
54
+ SizeKb = tree.Sum(e => e.SizeBytes) / 1024,
55
+ CreatedAt = dates.Length > 0 ? DateTimeOffset.Parse(dates[^1]) : default,
56
+ PushedAt = dates.Length > 0 ? DateTimeOffset.Parse(dates[0]) : default,
57
+ Contributors = authors,
58
+ CommitsLast90Days = int.TryParse(recent, out var n) ? n : 0,
59
+ Releases = prefix.Length == 0 ? tags : [],
60
+ Tree = tree,
61
+ SnapshotId = $"git:{head}",
62
+ };
63
+ }
64
+
65
+ if (!subprojects)
66
+ return [Make(new DirectoryInfo(repoPath).Name, "", files)];
67
+
68
+ return files.Where(f => f.Contains('/'))
69
+ .GroupBy(f => f[..f.IndexOf('/')])
70
+ .Where(g => !g.Key.StartsWith('.'))
71
+ .OrderBy(g => g.Key, StringComparer.Ordinal)
72
+ .Select(g => Make(g.Key, g.Key + "/", g))
73
+ .ToList();
74
+ }
75
+
76
+ private static string? ReadmeSummary(string root, string prefix, List<string> files)
77
+ {
78
+ var readme = files.FirstOrDefault(f => string.Equals(f[prefix.Length..], "README.md", StringComparison.OrdinalIgnoreCase))
79
+ ?? files.FirstOrDefault(f => f.EndsWith(".md", StringComparison.OrdinalIgnoreCase) && !f[prefix.Length..].Contains('/'));
80
+ if (readme == null) return null;
81
+ string? prose = null;
82
+ foreach (var line in File.ReadLines(Path.Combine(root, readme)).Take(60))
83
+ {
84
+ var t = line.Trim().TrimStart('#', ' ', '*', '>').Trim();
85
+ // Agent reports open with "KEY: value" headers; TASK/MISSION/DESCRIPTION carry the purpose.
86
+ var meta = MetadataLine.Match(t);
87
+ if (meta.Success)
88
+ {
89
+ if (meta.Groups[1].Value is "TASK" or "MISSION" or "DESCRIPTION" or "SUMMARY") return Clip(meta.Groups[2].Value);
90
+ continue;
91
+ }
92
+ if (prose == null && t.Length > 3 && !t.StartsWith("![") && !t.StartsWith('<') && !t.StartsWith("---") && !t.StartsWith("```"))
93
+ prose = t;
94
+ }
95
+ return prose == null ? null : Clip(prose);
96
+ }
97
+
98
+ private static readonly System.Text.RegularExpressions.Regex MetadataLine = new(@"^([A-Z][A-Z_]+):\s*(.*)$");
99
+
100
+ private static string Clip(string s) => s.Length > 160 ? s[..160] : s;
101
+
102
+ private static string Git(string dir, params string[] args)
103
+ {
104
+ var psi = new ProcessStartInfo("git") { WorkingDirectory = dir, RedirectStandardOutput = true, RedirectStandardError = true };
105
+ foreach (var a in args) psi.ArgumentList.Add(a);
106
+ using var p = Process.Start(psi) ?? throw new InvalidOperationException("git is not available.");
107
+ var output = p.StandardOutput.ReadToEnd();
108
+ var err = p.StandardError.ReadToEnd();
109
+ p.WaitForExit();
110
+ if (p.ExitCode != 0) throw new InvalidOperationException($"git {string.Join(' ', args)} failed: {err.Trim()}");
111
+ return output;
112
+ }
113
+ }
src/Repoverse.Core/Ingestion/SnapshotStore.cs ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using System.Text.Json;
2
+ using Repoverse.Core.Generation;
3
+ using Repoverse.Core.Model;
4
+
5
+ namespace Repoverse.Core.Ingestion;
6
+
7
+ public sealed record Snapshot
8
+ {
9
+ public const int CurrentSchema = 1;
10
+ public int SchemaVersion { get; init; } = CurrentSchema;
11
+ public required DateTimeOffset TakenAt { get; init; }
12
+ public required string Source { get; init; }
13
+ public required IReadOnlyList<CanonicalRepository> Repositories { get; init; }
14
+ public IReadOnlyList<IngestFailure> Failures { get; init; } = [];
15
+ }
16
+
17
+ /// <summary>
18
+ /// Last-known-good canonical state (§27). A refresh is merged per repository: repos that
19
+ /// failed this time keep their previous record and are reported stale, and an empty or
20
+ /// wholly failed refresh never replaces a populated snapshot.
21
+ /// </summary>
22
+ public static class SnapshotStore
23
+ {
24
+ public static Snapshot? Load(string path) =>
25
+ File.Exists(path) ? JsonSerializer.Deserialize<Snapshot>(File.ReadAllText(path), Json.Options) : null;
26
+
27
+ public static void Save(string path, Snapshot snapshot)
28
+ {
29
+ Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);
30
+ var tmp = path + ".tmp";
31
+ File.WriteAllText(tmp, JsonSerializer.Serialize(snapshot, Json.Options));
32
+ File.Move(tmp, path, overwrite: true); // atomic replace: a crash never leaves half a snapshot
33
+ }
34
+
35
+ public sealed record MergeResult(Snapshot Snapshot, IReadOnlyList<string> Stale, bool KeptPrevious);
36
+
37
+ public static MergeResult Merge(Snapshot? previous, IngestResult fresh, string source, DateTimeOffset now)
38
+ {
39
+ if (previous != null && fresh.Repositories.Count == 0)
40
+ return new MergeResult(previous with { Failures = fresh.Failures }, previous.Repositories.Select(r => r.Id.Key).ToList(), true);
41
+
42
+ var failed = fresh.Failures.Select(f => f.Repo.ToLowerInvariant()).ToHashSet();
43
+ var byKey = fresh.Repositories.ToDictionary(r => r.Id.Key);
44
+ var stale = new List<string>();
45
+ if (previous != null)
46
+ foreach (var old in previous.Repositories)
47
+ // Keep old records for repos that failed or were not reached (e.g. rate limit mid-run).
48
+ if (!byKey.ContainsKey(old.Id.Key) && (failed.Contains(old.Id.Key) || fresh.RateLimited))
49
+ {
50
+ byKey[old.Id.Key] = old;
51
+ stale.Add(old.Id.Key);
52
+ }
53
+
54
+ var merged = new Snapshot
55
+ {
56
+ TakenAt = now,
57
+ Source = source,
58
+ Repositories = byKey.Values.OrderBy(r => r.Id.Key, StringComparer.Ordinal).ToList(),
59
+ Failures = fresh.Failures,
60
+ };
61
+ return new MergeResult(merged, stale, false);
62
+ }
63
+ }
src/Repoverse.Core/Model/CanonicalRepository.cs ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ namespace Repoverse.Core.Model;
2
+
3
+ /// <summary>Stable internal identity for a repository: lower-cased "owner/name".</summary>
4
+ public readonly record struct RepoId(string Owner, string Name)
5
+ {
6
+ public string Key => $"{Owner.ToLowerInvariant()}/{Name.ToLowerInvariant()}";
7
+ public override string ToString() => Key;
8
+
9
+ public static RepoId Parse(string fullName)
10
+ {
11
+ var slash = fullName.IndexOf('/');
12
+ if (slash <= 0 || slash == fullName.Length - 1)
13
+ throw new FormatException($"Expected 'owner/name', got '{fullName}'.");
14
+ return new RepoId(fullName[..slash], fullName[(slash + 1)..]);
15
+ }
16
+ }
17
+
18
+ public enum TreeEntryKind { File, Directory }
19
+
20
+ public sealed record TreeEntry(string Path, TreeEntryKind Kind, long SizeBytes);
21
+
22
+ public sealed record Release(string Tag, DateTimeOffset PublishedAt, bool Prerelease);
23
+
24
+ /// <summary>
25
+ /// GitHub-sourced facts about a repository. Nothing in here is inferred by Repoverse;
26
+ /// derived values live in <see cref="DerivedRepository"/> with provenance.
27
+ /// </summary>
28
+ public sealed record CanonicalRepository
29
+ {
30
+ public required RepoId Id { get; init; }
31
+ public string? Description { get; init; }
32
+ public string? PrimaryLanguage { get; init; }
33
+ /// <summary>Bytes of code per language, as reported by GitHub's languages endpoint.</summary>
34
+ public IReadOnlyDictionary<string, long> Languages { get; init; } = new Dictionary<string, long>();
35
+ public IReadOnlyList<string> Topics { get; init; } = [];
36
+ public long SizeKb { get; init; }
37
+ public bool Archived { get; init; }
38
+ public bool Fork { get; init; }
39
+ public string DefaultBranch { get; init; } = "main";
40
+ public DateTimeOffset CreatedAt { get; init; }
41
+ public DateTimeOffset PushedAt { get; init; }
42
+ public string? License { get; init; }
43
+ public int OpenIssues { get; init; }
44
+ public int OpenPullRequests { get; init; }
45
+ public int Contributors { get; init; }
46
+ public int CommitsLast90Days { get; init; }
47
+ public IReadOnlyList<Release> Releases { get; init; } = [];
48
+ public IReadOnlyList<TreeEntry> Tree { get; init; } = [];
49
+ /// <summary>Other repos in the world this one depends on (from manifests / submodules).</summary>
50
+ public IReadOnlyList<RepoId> DependsOn { get; init; } = [];
51
+ /// <summary>Opaque version marker of the snapshot this record came from (e.g. pushed_at + ETag).</summary>
52
+ public string SnapshotId { get; init; } = "";
53
+ }
src/Repoverse.Core/Model/Derived.cs ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ namespace Repoverse.Core.Model;
2
+
3
+ /// <summary>Why a derived value has the value it has (§28).</summary>
4
+ public sealed record Provenance(string Rule, string Evidence)
5
+ {
6
+ public static Provenance Override(string file) => new("manual-override", file);
7
+ public override string ToString() => $"{Rule}: {Evidence}";
8
+ }
9
+
10
+ public sealed record Derived<T>(T Value, Provenance Why);
11
+
12
+ public enum SemanticCategory
13
+ {
14
+ SystemsInfrastructure,
15
+ OperatingSystem,
16
+ Compiler,
17
+ CryptographicCore,
18
+ FormalVerification,
19
+ Financial,
20
+ Simulation,
21
+ Hardware,
22
+ Quantum,
23
+ Training,
24
+ AgentSystem,
25
+ Database,
26
+ Networking,
27
+ WebInterface,
28
+ Documentation,
29
+ Experimental,
30
+ }
31
+
32
+ public enum District
33
+ {
34
+ Kernel,
35
+ Ai,
36
+ Financial,
37
+ FormalMethods,
38
+ HardwareIndustrial,
39
+ QuantumResearch,
40
+ Agent,
41
+ WebInterface,
42
+ Data,
43
+ Security,
44
+ Archive,
45
+ Experimental,
46
+ Infrastructure,
47
+ Training,
48
+ }
49
+
50
+ public enum BuildingArchetype
51
+ {
52
+ Foundry, // compilers, runtimes: transformation machinery
53
+ ControlTower, // OS / kernel / infrastructure
54
+ Vault, // crypto, security
55
+ ProofChamber, // formal methods
56
+ Exchange, // finance
57
+ Laboratory, // quantum, hardware, simulation
58
+ Library, // docs, training corpora
59
+ Studio, // web / interface
60
+ Warehouse, // databases
61
+ Relay, // networking
62
+ Commons, // agent systems
63
+ Workshop, // small / experimental
64
+ }
65
+
66
+ public enum MaterialFamily { Stone, Concrete, Glass, Metal, Wood, Ceramic, Electronics, Laboratory, Archive, Security }
src/Repoverse.Core/Persistence/SaveGame.cs ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using Repoverse.Core.Bridge;
2
+ using System.Text.Json;
3
+ using System.Text.Json.Nodes;
4
+ using Repoverse.Core.Generation;
5
+ using Repoverse.Core.Voxels;
6
+
7
+ namespace Repoverse.Core.Persistence;
8
+
9
+ public enum ViewMode { World, Code, Graph, Build, Cad, Audit, Agent }
10
+
11
+ public sealed record Bookmark(string Label, string Uri);
12
+
13
+ public sealed record PlayerState
14
+ {
15
+ public double X { get; init; }
16
+ public double Y { get; init; }
17
+ public double Z { get; init; }
18
+ public double Yaw { get; init; }
19
+ public ViewMode Mode { get; init; } = ViewMode.World;
20
+ /// <summary>repoverse:// URI of the current selection, if any.</summary>
21
+ public string? Selection { get; init; }
22
+ public IReadOnlyList<Bookmark> Bookmarks { get; init; } = [];
23
+ }
24
+
25
+ public sealed record ChunkEdits(string Chunk, IReadOnlyDictionary<int, ushort> Voxels);
26
+
27
+ /// <summary>
28
+ /// Versioned save (§42, §43). Holds player state and user modifications only;
29
+ /// canonical and generated state are rebuilt from the snapshot and manifest.
30
+ /// </summary>
31
+ public sealed record SaveGame
32
+ {
33
+ public const int CurrentSchema = 2;
34
+
35
+ public int SchemaVersion { get; init; } = CurrentSchema;
36
+ public required string WorldSeed { get; init; }
37
+ public required string Generator { get; init; }
38
+ public required IReadOnlyDictionary<string, string> Snapshots { get; init; }
39
+ public required PlayerState Player { get; init; }
40
+ public IReadOnlyList<ChunkEdits> Edits { get; init; } = [];
41
+ public long SimulationTick { get; init; }
42
+ public IReadOnlyList<BuilderState> Builders { get; init; } = [];
43
+
44
+ public static SaveGame Capture(WorldManifest manifest, PlayerState player, WorldEdits edits, long tick) => new()
45
+ {
46
+ WorldSeed = manifest.WorldSeed,
47
+ Generator = manifest.Generator,
48
+ Snapshots = manifest.Snapshots,
49
+ Player = player,
50
+ Edits = edits.Snapshot().OrderBy(kv => kv.Key.ToString(), StringComparer.Ordinal)
51
+ .Select(kv => new ChunkEdits(kv.Key.ToString(), kv.Value)).ToList(),
52
+ SimulationTick = tick,
53
+ };
54
+
55
+ public void RestoreEdits(WorldEdits edits) => edits.Load(Edits.ToDictionary(
56
+ e => { var p = e.Chunk.Split(','); return new ChunkCoord(int.Parse(p[0]), int.Parse(p[1]), int.Parse(p[2])); },
57
+ e => e.Voxels));
58
+
59
+ public static void Write(string path, SaveGame save)
60
+ {
61
+ var tmp = path + ".tmp";
62
+ File.WriteAllText(tmp, JsonSerializer.Serialize(save, Json.Options));
63
+ File.Move(tmp, path, overwrite: true);
64
+ }
65
+
66
+ public static SaveGame Read(string path) => Parse(File.ReadAllText(path));
67
+
68
+ public static SaveGame Parse(string json)
69
+ {
70
+ var node = JsonNode.Parse(json)?.AsObject() ?? throw new InvalidDataException("Save file is empty.");
71
+ var version = node["schemaVersion"]?.GetValue<int>() ?? 1;
72
+ if (version > CurrentSchema)
73
+ throw new InvalidDataException($"Save schema {version} is newer than this build supports ({CurrentSchema}).");
74
+ for (; version < CurrentSchema; version++) Migrations[version](node);
75
+ node["schemaVersion"] = CurrentSchema;
76
+ return node.Deserialize<SaveGame>(Json.Options) ?? throw new InvalidDataException("Save file could not be read.");
77
+ }
78
+
79
+ /// <summary>Migration from schema N to N+1, applied in order.</summary>
80
+ private static readonly Dictionary<int, Action<JsonObject>> Migrations = new()
81
+ {
82
+ // v1 kept "seed" and "cameraMode" and had no bookmarks or edits.
83
+ [1] = n =>
84
+ {
85
+ if (n["seed"] is { } seed) { n.Remove("seed"); n["worldSeed"] = seed.GetValue<string>(); }
86
+ n["generator"] ??= "repoverse-gen/0";
87
+ n["snapshots"] ??= new JsonObject();
88
+ if (n["player"] is JsonObject p)
89
+ {
90
+ if (p["cameraMode"] is { } mode) { p.Remove("cameraMode"); p["mode"] = mode.GetValue<string>(); }
91
+ p["bookmarks"] ??= new JsonArray();
92
+ }
93
+ n["edits"] ??= new JsonArray();
94
+ },
95
+ };
96
+ }
src/Repoverse.Core/Repoverse.Core.csproj ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ <Project Sdk="Microsoft.NET.Sdk">
2
+
3
+ <PropertyGroup>
4
+ <TargetFramework>net8.0</TargetFramework>
5
+ <ImplicitUsings>enable</ImplicitUsings>
6
+ <Nullable>enable</Nullable>
7
+ </PropertyGroup>
8
+
9
+ </Project>
src/Repoverse.Core/RepoverseUri.cs ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using Repoverse.Core.Model;
2
+
3
+ namespace Repoverse.Core;
4
+
5
+ /// <summary>
6
+ /// Deep link into the world (§76). Grammar, version 1:
7
+ /// <code>
8
+ /// repoverse://{owner}/{repo}[/{path}][#L{line}]
9
+ /// repoverse://{owner}/{repo}?room={id}
10
+ /// repoverse://@{x},{y},{z}
11
+ /// </code>
12
+ /// Path segments are percent-encoded; the repo part matches GitHub's owner/name.
13
+ /// </summary>
14
+ public sealed record RepoverseUri
15
+ {
16
+ public const string Scheme = "repoverse";
17
+
18
+ public RepoId? Repo { get; init; }
19
+ public string? Path { get; init; }
20
+ public int? Line { get; init; }
21
+ public int? Room { get; init; }
22
+ public (int X, int Y, int Z)? Location { get; init; }
23
+
24
+ public static RepoverseUri Parse(string text)
25
+ {
26
+ const string prefix = Scheme + "://";
27
+ if (!text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
28
+ throw new FormatException($"Not a {Scheme} URI: '{text}'.");
29
+ var rest = text[prefix.Length..];
30
+
31
+ if (rest.StartsWith('@'))
32
+ {
33
+ var p = rest[1..].Split(',');
34
+ if (p.Length != 3) throw new FormatException("Location must be @x,y,z.");
35
+ return new RepoverseUri { Location = (int.Parse(p[0]), int.Parse(p[1]), int.Parse(p[2])) };
36
+ }
37
+
38
+ int? line = null, room = null;
39
+ var hash = rest.IndexOf('#');
40
+ if (hash >= 0)
41
+ {
42
+ var frag = rest[(hash + 1)..];
43
+ if (!frag.StartsWith('L') || !int.TryParse(frag[1..], out var l)) throw new FormatException($"Bad fragment '#{frag}'.");
44
+ line = l;
45
+ rest = rest[..hash];
46
+ }
47
+ var q = rest.IndexOf('?');
48
+ if (q >= 0)
49
+ {
50
+ foreach (var kv in rest[(q + 1)..].Split('&'))
51
+ if (kv.StartsWith("room=") && int.TryParse(kv[5..], out var r)) room = r;
52
+ else throw new FormatException($"Unknown query '{kv}'.");
53
+ rest = rest[..q];
54
+ }
55
+
56
+ var parts = rest.Split('/', 3);
57
+ if (parts.Length < 2 || parts[0].Length == 0 || parts[1].Length == 0) throw new FormatException("Expected owner/repo.");
58
+ var path = parts.Length == 3 && parts[2].Length > 0
59
+ ? string.Join('/', parts[2].Split('/').Select(Uri.UnescapeDataString))
60
+ : null;
61
+ return new RepoverseUri { Repo = new RepoId(Uri.UnescapeDataString(parts[0]), Uri.UnescapeDataString(parts[1])), Path = path, Line = line, Room = room };
62
+ }
63
+
64
+ public override string ToString()
65
+ {
66
+ if (Location is var (x, y, z)) return $"{Scheme}://@{x},{y},{z}";
67
+ var s = $"{Scheme}://{Uri.EscapeDataString(Repo!.Value.Owner)}/{Uri.EscapeDataString(Repo.Value.Name)}";
68
+ if (Path != null) s += "/" + string.Join('/', Path.Split('/').Select(Uri.EscapeDataString));
69
+ if (Room != null) s += $"?room={Room}";
70
+ if (Line != null) s += $"#L{Line}";
71
+ return s;
72
+ }
73
+
74
+ /// <summary>External reference back to GitHub (§77); internal identity stays the RepoId.</summary>
75
+ public string? GitHubUrl(string branch = "HEAD") => Repo is not { } r ? null
76
+ : Path == null ? $"https://github.com/{r.Owner}/{r.Name}"
77
+ : $"https://github.com/{r.Owner}/{r.Name}/blob/{branch}/{Path}{(Line is { } l ? $"#L{l}" : "")}";
78
+ }
src/Repoverse.Core/Simulation/SimulationClock.cs ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ namespace Repoverse.Core.Simulation;
2
+
3
+ /// <summary>
4
+ /// Fixed-step simulation time, decoupled from render frames (§31). The host calls
5
+ /// <see cref="Advance"/> with real frame time; the clock runs zero or more fixed ticks
6
+ /// scaled by <see cref="Speed"/>, and fires scheduled actions in tick order.
7
+ /// </summary>
8
+ public sealed class SimulationClock(double ticksPerSecond = WorldConstants.SimulationTicksPerSecond, int maxTicksPerAdvance = 16)
9
+ {
10
+ private readonly PriorityQueue<(long Tick, long Seq, Action Action), (long, long)> _scheduled = new();
11
+ private double _accumulator;
12
+ private long _seq;
13
+
14
+ public long Tick { get; private set; }
15
+ public double Speed { get; set; } = 1.0;
16
+ public bool Paused { get; set; }
17
+ public TimeSpan TickLength => TimeSpan.FromSeconds(1 / ticksPerSecond);
18
+ public TimeSpan SimulatedTime => TickLength * Tick;
19
+
20
+ /// <summary>Raised once per fixed tick, after that tick's scheduled actions.</summary>
21
+ public event Action<long>? Ticked;
22
+
23
+ public void Schedule(long ticksFromNow, Action action)
24
+ {
25
+ ArgumentOutOfRangeException.ThrowIfNegative(ticksFromNow);
26
+ var at = Tick + ticksFromNow;
27
+ _scheduled.Enqueue((at, _seq, action), (at, _seq++));
28
+ }
29
+
30
+ /// <returns>Number of ticks run.</returns>
31
+ public int Advance(TimeSpan realElapsed)
32
+ {
33
+ if (Paused || Speed <= 0) return 0;
34
+ _accumulator += realElapsed.TotalSeconds * Speed * ticksPerSecond;
35
+ int ran = 0;
36
+ while (_accumulator >= 1 && ran < maxTicksPerAdvance)
37
+ {
38
+ _accumulator -= 1;
39
+ Step();
40
+ ran++;
41
+ }
42
+ // Spiral-of-death guard: drop backlog rather than stall the frame.
43
+ if (ran == maxTicksPerAdvance) _accumulator = Math.Min(_accumulator, 1);
44
+ return ran;
45
+ }
46
+
47
+ /// <summary>Runs exactly one tick regardless of pause; used for deterministic stepping.</summary>
48
+ public void Step()
49
+ {
50
+ Tick++;
51
+ while (_scheduled.TryPeek(out var item, out _) && item.Tick <= Tick)
52
+ {
53
+ _scheduled.Dequeue();
54
+ item.Action();
55
+ }
56
+ Ticked?.Invoke(Tick);
57
+ }
58
+ }
src/Repoverse.Core/Simulation/WorldEvents.cs ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using Repoverse.Core.Model;
2
+
3
+ namespace Repoverse.Core.Simulation;
4
+
5
+ /// <summary>Typed world events (§32). Each carries the data needed to visualise it.</summary>
6
+ public abstract record WorldEvent(RepoId Repo);
7
+
8
+ public sealed record RepositoryAdded(RepoId Repo) : WorldEvent(Repo);
9
+ public sealed record RepositoryRemoved(RepoId Repo) : WorldEvent(Repo);
10
+ public sealed record RepositoryArchived(RepoId Repo) : WorldEvent(Repo);
11
+ public sealed record RepositoryUnarchived(RepoId Repo) : WorldEvent(Repo);
12
+ public sealed record ReleasePublished(RepoId Repo, string Tag, bool Prerelease) : WorldEvent(Repo);
13
+ public sealed record IssuesChanged(RepoId Repo, int Before, int After) : WorldEvent(Repo);
14
+ public sealed record PullRequestsChanged(RepoId Repo, int Before, int After) : WorldEvent(Repo);
15
+ public sealed record ActivityChanged(RepoId Repo, int CommitsBefore, int CommitsAfter) : WorldEvent(Repo);
16
+ public sealed record StructureChanged(RepoId Repo, int FilesAdded, int FilesRemoved) : WorldEvent(Repo);
17
+
18
+ /// <summary>Turns two canonical snapshots into the events that justify world changes (§26).</summary>
19
+ public static class SnapshotDiff
20
+ {
21
+ public static IReadOnlyList<WorldEvent> Diff(IReadOnlyList<CanonicalRepository> before, IReadOnlyList<CanonicalRepository> after)
22
+ {
23
+ var old = before.ToDictionary(r => r.Id.Key);
24
+ var now = after.ToDictionary(r => r.Id.Key);
25
+ var events = new List<WorldEvent>();
26
+
27
+ foreach (var key in old.Keys.Union(now.Keys).OrderBy(k => k, StringComparer.Ordinal))
28
+ {
29
+ old.TryGetValue(key, out var a);
30
+ now.TryGetValue(key, out var b);
31
+ if (a == null) { events.Add(new RepositoryAdded(b!.Id)); continue; }
32
+ if (b == null) { events.Add(new RepositoryRemoved(a.Id)); continue; }
33
+
34
+ if (!a.Archived && b.Archived) events.Add(new RepositoryArchived(b.Id));
35
+ if (a.Archived && !b.Archived) events.Add(new RepositoryUnarchived(b.Id));
36
+
37
+ var oldTags = a.Releases.Select(r => r.Tag).ToHashSet();
38
+ foreach (var r in b.Releases.Where(r => !oldTags.Contains(r.Tag)).OrderBy(r => r.PublishedAt))
39
+ events.Add(new ReleasePublished(b.Id, r.Tag, r.Prerelease));
40
+
41
+ if (a.OpenIssues != b.OpenIssues) events.Add(new IssuesChanged(b.Id, a.OpenIssues, b.OpenIssues));
42
+ if (a.OpenPullRequests != b.OpenPullRequests) events.Add(new PullRequestsChanged(b.Id, a.OpenPullRequests, b.OpenPullRequests));
43
+ if (a.CommitsLast90Days != b.CommitsLast90Days) events.Add(new ActivityChanged(b.Id, a.CommitsLast90Days, b.CommitsLast90Days));
44
+
45
+ var aFiles = a.Tree.Where(e => e.Kind == TreeEntryKind.File).Select(e => e.Path).ToHashSet();
46
+ var bFiles = b.Tree.Where(e => e.Kind == TreeEntryKind.File).Select(e => e.Path).ToHashSet();
47
+ int added = bFiles.Count(f => !aFiles.Contains(f)), removed = aFiles.Count(f => !bFiles.Contains(f));
48
+ if (added + removed > 0) events.Add(new StructureChanged(b.Id, added, removed));
49
+ }
50
+ return events;
51
+ }
52
+ }
src/Repoverse.Core/Voxels/BuildingRasterizer.cs ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using Repoverse.Core.Generation;
2
+ using Repoverse.Core.Model;
3
+ using static Repoverse.Core.WorldConstants;
4
+
5
+ namespace Repoverse.Core.Voxels;
6
+
7
+ /// <summary>An interactive object placed in the world, kept out of bulk voxel data (§12, §91).</summary>
8
+ public sealed record WorldObject(
9
+ string Id,
10
+ RepoId Repo,
11
+ int X, int Y, int Z,
12
+ ArtifactKind Kind,
13
+ string SourcePath,
14
+ int RoomId,
15
+ IReadOnlyList<string> Actions);
16
+
17
+ /// <summary>Where each room of a building ended up in voxel space, for navigation checks and cutaway.</summary>
18
+ public sealed record RoomPlacement(int RoomId, int Floor, int MinX, int MinZ, int MaxX, int MaxZ, int FloorY);
19
+
20
+ /// <summary>
21
+ /// Turns a <see cref="BuildingDefinition"/> into voxels. Floor plan per storey:
22
+ /// a 3-wide corridor along X through the middle, rooms on both sides separated by
23
+ /// partitions, a door from every room to the corridor, a ladder shaft at the west end
24
+ /// of the corridor and the entrance on the east wall.
25
+ ///
26
+ /// z=D-1 ┌──────────┬──────────┐
27
+ /// │ room │ room │
28
+ /// ├───door───┴───door───┤
29
+ /// │L corridor ⌂ entrance (floor 0)
30
+ /// ├───door───┬───door───┤
31
+ /// │ room │ room │
32
+ /// z=0 └──────────┴──────────┘
33
+ /// </summary>
34
+ public static class BuildingRasterizer
35
+ {
36
+ public delegate void Setter(int x, int y, int z, Voxel v);
37
+
38
+ public sealed record Layout(IReadOnlyList<RoomPlacement> Rooms, int CorridorZ, int LadderX, (int X, int Y, int Z) Entrance);
39
+
40
+ public static Layout Plan(BuildingDefinition b)
41
+ {
42
+ var f = b.Footprint;
43
+ int cz = f.Z + b.RoomDepth + 2; // first corridor row
44
+ int slot = (f.Width - 2) / b.RoomsPerSide;
45
+ var rooms = new List<RoomPlacement>();
46
+ var byFloor = b.Interior.Rooms.Where(IsWorkRoom).GroupBy(r => r.Floor);
47
+ foreach (var floor in byFloor)
48
+ {
49
+ if (floor.Key >= b.Floors) continue;
50
+ int y = GroundLevel + floor.Key * FloorHeight;
51
+ int i = 0;
52
+ foreach (var room in floor)
53
+ {
54
+ int side = i % 2, col = i / 2;
55
+ int x0 = f.X + 1 + col * slot;
56
+ int x1 = col == b.RoomsPerSide - 1 ? f.MaxX - 1 : x0 + slot - 2;
57
+ var (z0, z1) = side == 0 ? (f.Z + 1, cz - 2) : (cz + 4, f.MaxZ - 1);
58
+ rooms.Add(new RoomPlacement(room.Id, floor.Key, x0, z0, x1, z1, y));
59
+ i++;
60
+ }
61
+ }
62
+ return new Layout(rooms, cz, f.X + 1, (f.MaxX, GroundLevel + 1, cz + 1));
63
+ }
64
+
65
+ public static bool IsWorkRoom(Room r) => r.Purpose is not (RoomPurpose.Lobby or RoomPurpose.Corridor or RoomPurpose.Stairwell);
66
+
67
+ public static void Rasterize(BuildingDefinition b, Setter set)
68
+ {
69
+ var f = b.Footprint;
70
+ var layout = Plan(b);
71
+ var m = b.Material;
72
+ int cz = layout.CorridorZ;
73
+ int top = GroundLevel + b.Floors * FloorHeight;
74
+ bool scaffold = b.Construction.Value == ConstructionState.Unreleased;
75
+ byte state = (byte)b.Activity.Value;
76
+
77
+ // Foundation one voxel wider than the footprint.
78
+ for (int x = f.X - 1; x <= f.MaxX + 1; x++)
79
+ for (int z = f.Z - 1; z <= f.MaxZ + 1; z++)
80
+ set(x, GroundLevel - 1, z, new Voxel(BlockType.Foundation, MaterialFamily.Stone));
81
+
82
+ for (int floor = 0; floor < b.Floors; floor++)
83
+ {
84
+ int y0 = GroundLevel + floor * FloorHeight;
85
+ for (int x = f.X; x <= f.MaxX; x++)
86
+ for (int z = f.Z; z <= f.MaxZ; z++)
87
+ {
88
+ bool shaft = x == layout.LadderX && z == cz + 1;
89
+ set(x, y0, z, shaft && floor > 0 ? Voxel.Air : new Voxel(BlockType.Floor, m, state));
90
+ bool edge = x == f.X || x == f.MaxX || z == f.Z || z == f.MaxZ;
91
+ for (int y = y0 + 1; y < y0 + FloorHeight; y++)
92
+ {
93
+ if (edge)
94
+ {
95
+ bool window = (y - y0) is 2 or 3 && (x + z) % 3 != 0 && !IsCorner(f, x, z);
96
+ set(x, y, z, new Voxel(window ? BlockType.Window : BlockType.Wall, m, state));
97
+ }
98
+ else if (z == cz - 1 || z == cz + 3)
99
+ set(x, y, z, new Voxel(BlockType.Partition, m)); // corridor walls; doors carved below
100
+ else if (shaft)
101
+ set(x, y, z, new Voxel(BlockType.Ladder, MaterialFamily.Metal));
102
+ }
103
+ }
104
+
105
+ foreach (var room in layout.Rooms.Where(r => r.Floor == floor))
106
+ {
107
+ // East partition between neighbouring rooms.
108
+ if (room.MaxX + 1 < f.MaxX)
109
+ for (int z = room.MinZ; z <= room.MaxZ; z++)
110
+ for (int y = y0 + 1; y < y0 + FloorHeight; y++)
111
+ set(room.MaxX + 1, y, z, new Voxel(BlockType.Partition, m));
112
+ // Door into the corridor, centred on the room.
113
+ int dx = (room.MinX + room.MaxX) / 2;
114
+ int dz = room.MinZ < cz ? cz - 1 : cz + 3;
115
+ for (int y = y0 + 1; y <= y0 + DoorHeight; y++)
116
+ set(dx, y, dz, Voxel.Air);
117
+ }
118
+ // Ladder shaft continues through the ceiling of every storey but the top one.
119
+ if (floor < b.Floors - 1)
120
+ set(layout.LadderX, y0 + FloorHeight, cz + 1, Voxel.Air);
121
+ }
122
+
123
+ // Entrance on the east wall at the corridor.
124
+ for (int y = GroundLevel + 1; y <= GroundLevel + DoorHeight; y++)
125
+ for (int z = cz; z <= cz + 2; z++)
126
+ set(f.MaxX, y, z, Voxel.Air);
127
+
128
+ for (int x = f.X; x <= f.MaxX; x++)
129
+ for (int z = f.Z; z <= f.MaxZ; z++)
130
+ set(x, top, z, new Voxel(BlockType.Roof, m, state));
131
+
132
+ if (scaffold) // unreleased work reads as a construction site (§26)
133
+ for (int y = GroundLevel; y <= top; y += 2)
134
+ for (int x = f.X - 1; x <= f.MaxX + 1; x += 4)
135
+ set(x, y, f.Z - 1, new Voxel(BlockType.Scaffold, MaterialFamily.Metal));
136
+ }
137
+
138
+ private static bool IsCorner(Footprint f, int x, int z) => (x == f.X || x == f.MaxX) && (z == f.Z || z == f.MaxZ);
139
+
140
+ /// <summary>Places each room's leading artifacts along its back wall as interactive objects.</summary>
141
+ public static IEnumerable<WorldObject> Objects(BuildingDefinition b)
142
+ {
143
+ var layout = Plan(b);
144
+ var rooms = b.Interior.Rooms.ToDictionary(r => r.Id);
145
+ foreach (var p in layout.Rooms)
146
+ {
147
+ var room = rooms[p.RoomId];
148
+ bool south = p.MinZ < layout.CorridorZ;
149
+ int z = south ? p.MinZ : p.MaxZ;
150
+ int x = p.MinX;
151
+ foreach (var a in room.Artifacts)
152
+ {
153
+ if (x > p.MaxX) break;
154
+ yield return new WorldObject($"{b.Repo.Key}:{a.Path}", b.Repo, x, p.FloorY + 1, z, a.Kind, a.Path, room.Id, ActionsFor(a.Kind));
155
+ x++;
156
+ }
157
+ }
158
+ }
159
+
160
+ public static IReadOnlyList<string> ActionsFor(ArtifactKind k) => k switch
161
+ {
162
+ ArtifactKind.TestBench => ["inspect", "view-history", "test"],
163
+ ArtifactKind.BuildStation => ["inspect", "view-history", "build"],
164
+ ArtifactKind.ProofVault => ["inspect", "view-history", "verify"],
165
+ _ => ["inspect", "view-history", "open"],
166
+ };
167
+ }
src/Repoverse.Core/Voxels/ChunkStreamer.cs ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using static Repoverse.Core.WorldConstants;
2
+
3
+ namespace Repoverse.Core.Voxels;
4
+
5
+ /// <summary>
6
+ /// Keeps the chunks around a focus point resident (§11, §13). Each <see cref="Update"/>
7
+ /// starts generation for the nearest missing chunks on the thread pool (bounded by
8
+ /// <c>maxInFlight</c>), collects finished ones, and unloads chunks beyond radius + hysteresis,
9
+ /// cancelling their pending work. Memory is bounded by the radius, not by world size.
10
+ /// </summary>
11
+ public sealed class ChunkStreamer(WorldGenerator generator, WorldEdits edits, int radius = StreamRadiusChunks, int maxInFlight = 8)
12
+ {
13
+ private readonly Dictionary<ChunkCoord, Chunk> _loaded = new();
14
+ private readonly Dictionary<ChunkCoord, (Task<Chunk> Task, CancellationTokenSource Cts)> _pending = new();
15
+ private readonly object _statsGate = new();
16
+
17
+ public IReadOnlyDictionary<ChunkCoord, Chunk> Loaded => _loaded;
18
+ public int InFlight => _pending.Count;
19
+ public long ChunksGenerated { get; private set; }
20
+ public TimeSpan TotalGenerationTime { get; private set; }
21
+
22
+ public sealed record Tick(int Started, int Completed, int Unloaded, int Cancelled);
23
+
24
+ public Tick Update(int focusX, int focusZ)
25
+ {
26
+ var center = ChunkCoord.FromVoxel(focusX, GroundLevel, focusZ);
27
+ int completed = 0, unloaded = 0, cancelled = 0, started = 0;
28
+
29
+ foreach (var (c, p) in _pending.Where(kv => kv.Value.Task.IsCompleted).ToList())
30
+ {
31
+ _pending.Remove(c);
32
+ p.Cts.Dispose();
33
+ if (p.Task.IsCompletedSuccessfully) { _loaded[c] = p.Task.Result; completed++; }
34
+ }
35
+
36
+ int keep = radius + StreamHysteresisChunks;
37
+ foreach (var c in _loaded.Keys.Where(c => HorizontalDistance(c, center) > keep).ToList())
38
+ {
39
+ _loaded.Remove(c);
40
+ unloaded++;
41
+ }
42
+ foreach (var (c, p) in _pending.Where(kv => HorizontalDistance(kv.Key, center) > keep).ToList())
43
+ {
44
+ p.Cts.Cancel();
45
+ _pending.Remove(c);
46
+ cancelled++;
47
+ }
48
+
49
+ foreach (var c in Wanted(center))
50
+ {
51
+ if (_pending.Count >= maxInFlight) break;
52
+ if (_loaded.ContainsKey(c) || _pending.ContainsKey(c)) continue;
53
+ var cts = new CancellationTokenSource();
54
+ var token = cts.Token;
55
+ _pending[c] = (Task.Run(() =>
56
+ {
57
+ var start = System.Diagnostics.Stopwatch.GetTimestamp();
58
+ var chunk = generator.Generate(c, edits, token);
59
+ lock (_statsGate) { ChunksGenerated++; TotalGenerationTime += System.Diagnostics.Stopwatch.GetElapsedTime(start); }
60
+ return chunk;
61
+ }, token), cts);
62
+ started++;
63
+ }
64
+ return new Tick(started, completed, unloaded, cancelled);
65
+ }
66
+
67
+ /// <summary>Runs updates until everything wanted around the focus is resident.</summary>
68
+ public async Task SettleAsync(int focusX, int focusZ, CancellationToken ct = default)
69
+ {
70
+ while (true)
71
+ {
72
+ Update(focusX, focusZ);
73
+ if (_pending.Count == 0) return;
74
+ await Task.WhenAny(_pending.Values.Select(p => p.Task)).WaitAsync(ct);
75
+ }
76
+ }
77
+
78
+ /// <summary>Chunks within the radius, nearest first (§13 prioritisation).</summary>
79
+ public IEnumerable<ChunkCoord> Wanted(ChunkCoord center)
80
+ {
81
+ var list = new List<ChunkCoord>();
82
+ for (int dx = -radius; dx <= radius; dx++)
83
+ for (int dz = -radius; dz <= radius; dz++)
84
+ for (int y = 0; y <= WorldGenerator.MaxChunkY; y++)
85
+ list.Add(new ChunkCoord(center.X + dx, y, center.Z + dz));
86
+ return list.OrderBy(c => HorizontalDistance(c, center)).ThenBy(c => Math.Abs(c.Y - center.Y)).ThenBy(c => c.X).ThenBy(c => c.Z);
87
+ }
88
+
89
+ private static int HorizontalDistance(ChunkCoord a, ChunkCoord b) => Math.Max(Math.Abs(a.X - b.X), Math.Abs(a.Z - b.Z));
90
+
91
+ /// <summary>World-space voxel lookup across loaded chunks; null when the chunk is not resident.</summary>
92
+ public Voxel? Sample(int x, int y, int z) =>
93
+ _loaded.TryGetValue(ChunkCoord.FromVoxel(x, y, z), out var chunk)
94
+ ? chunk[x - chunk.Coord.OriginX, y - chunk.Coord.OriginY, z - chunk.Coord.OriginZ]
95
+ : null;
96
+ }
src/Repoverse.Core/Voxels/GreedyMesher.cs ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using System.Diagnostics;
2
+ using static Repoverse.Core.WorldConstants;
3
+
4
+ namespace Repoverse.Core.Voxels;
5
+
6
+ /// <summary>
7
+ /// An axis-aligned face rectangle. <see cref="Axis"/> is the normal axis (0=X,1=Y,2=Z),
8
+ /// <see cref="Positive"/> its direction; (U,V) span the other two axes in cyclic order.
9
+ /// Coordinates are chunk-local voxel corners.
10
+ /// </summary>
11
+ public readonly record struct Quad(int Axis, bool Positive, int Layer, int U, int V, int Width, int Height, ushort MeshKey);
12
+
13
+ public sealed record ChunkMesh(ChunkCoord Coord, IReadOnlyList<Quad> Quads, int VisibleFaces, TimeSpan BuildTime)
14
+ {
15
+ public int Triangles => Quads.Count * 2;
16
+ /// <summary>One draw call per distinct material key (§14).</summary>
17
+ public int MaterialGroups => Quads.Select(q => q.MeshKey).Distinct().Count();
18
+ }
19
+
20
+ /// <summary>
21
+ /// Greedy meshing (§14): emits only faces between a visible voxel and a non-opaque
22
+ /// neighbour, then merges coplanar faces with the same material key into maximal rectangles.
23
+ /// Faces between identical see-through blocks (window next to window) are culled.
24
+ /// </summary>
25
+ public static class GreedyMesher
26
+ {
27
+ private const int S = ChunkSize;
28
+
29
+ /// <param name="neighbour">World-space sampler for voxels outside the chunk; null result = not loaded, treated as air.</param>
30
+ public static ChunkMesh Build(Chunk chunk, Func<int, int, int, Voxel?>? neighbour = null)
31
+ {
32
+ var sw = Stopwatch.StartNew();
33
+ var quads = new List<Quad>();
34
+ int faces = 0;
35
+ if (chunk.IsEmpty) return new ChunkMesh(chunk.Coord, quads, 0, sw.Elapsed);
36
+
37
+ var mask = new ushort[S * S];
38
+ Span<int> pos = stackalloc int[3];
39
+ Span<int> npos = stackalloc int[3];
40
+
41
+ for (int axis = 0; axis < 3; axis++)
42
+ {
43
+ int u = (axis + 1) % 3, v = (axis + 2) % 3;
44
+ foreach (var positive in new[] { false, true })
45
+ {
46
+ for (int layer = 0; layer < S; layer++)
47
+ {
48
+ // Build the face mask for this slice. 0 = no face; otherwise MeshKey + 1.
49
+ for (int j = 0; j < S; j++)
50
+ for (int i = 0; i < S; i++)
51
+ {
52
+ pos[axis] = layer; pos[u] = i; pos[v] = j;
53
+ var here = chunk[pos[0], pos[1], pos[2]];
54
+ ushort m = 0;
55
+ if (!here.IsAir)
56
+ {
57
+ npos[0] = pos[0]; npos[1] = pos[1]; npos[2] = pos[2];
58
+ npos[axis] += positive ? 1 : -1;
59
+ var there = Sample(chunk, npos, neighbour);
60
+ if (!there.IsOpaque && there.Type != here.Type) { m = (ushort)(here.MeshKey + 1); faces++; }
61
+ }
62
+ mask[j * S + i] = m;
63
+ }
64
+
65
+ // Merge the mask into maximal rectangles.
66
+ for (int j = 0; j < S; j++)
67
+ for (int i = 0; i < S;)
68
+ {
69
+ var m = mask[j * S + i];
70
+ if (m == 0) { i++; continue; }
71
+ int w = 1;
72
+ while (i + w < S && mask[j * S + i + w] == m) w++;
73
+ int h = 1;
74
+ for (; j + h < S; h++)
75
+ {
76
+ bool rowOk = true;
77
+ for (int k = 0; k < w && rowOk; k++) rowOk = mask[(j + h) * S + i + k] == m;
78
+ if (!rowOk) break;
79
+ }
80
+ for (int dy = 0; dy < h; dy++)
81
+ for (int dx = 0; dx < w; dx++)
82
+ mask[(j + dy) * S + i + dx] = 0;
83
+ quads.Add(new Quad(axis, positive, layer + (positive ? 1 : 0), i, j, w, h, (ushort)(m - 1)));
84
+ i += w;
85
+ }
86
+ }
87
+ }
88
+ }
89
+ return new ChunkMesh(chunk.Coord, quads, faces, sw.Elapsed);
90
+ }
91
+
92
+ private static Voxel Sample(Chunk chunk, ReadOnlySpan<int> p, Func<int, int, int, Voxel?>? neighbour)
93
+ {
94
+ if ((uint)p[0] < S && (uint)p[1] < S && (uint)p[2] < S) return chunk[p[0], p[1], p[2]];
95
+ if (neighbour == null) return Voxel.Air;
96
+ return neighbour(chunk.Coord.OriginX + p[0], chunk.Coord.OriginY + p[1], chunk.Coord.OriginZ + p[2]) ?? Voxel.Air;
97
+ }
98
+
99
+ /// <summary>Quad corners in world space, counter-clockwise when viewed from the face normal.</summary>
100
+ public static (float X, float Y, float Z)[] Corners(ChunkCoord c, Quad q)
101
+ {
102
+ int u = (q.Axis + 1) % 3, v = (q.Axis + 2) % 3;
103
+ var o = new[] { c.OriginX, c.OriginY, c.OriginZ };
104
+ (float, float, float) At(int du, int dv)
105
+ {
106
+ var p = new float[3];
107
+ p[q.Axis] = o[q.Axis] + q.Layer;
108
+ p[u] = o[u] + q.U + du;
109
+ p[v] = o[v] + q.V + dv;
110
+ return (p[0], p[1], p[2]);
111
+ }
112
+ var quad = new[] { At(0, 0), At(q.Width, 0), At(q.Width, q.Height), At(0, q.Height) };
113
+ if (!q.Positive) Array.Reverse(quad);
114
+ return quad;
115
+ }
116
+ }
src/Repoverse.Core/Voxels/Voxel.cs ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using Repoverse.Core.Model;
2
+
3
+ namespace Repoverse.Core.Voxels;
4
+
5
+ /// <summary>Structural role of a voxel. Interactive things are entities, not blocks (§12).</summary>
6
+ public enum BlockType : byte
7
+ {
8
+ Air = 0,
9
+ Bedrock,
10
+ Soil,
11
+ Grass,
12
+ Road,
13
+ Sidewalk,
14
+ Foundation,
15
+ Wall,
16
+ Floor,
17
+ Roof,
18
+ Window,
19
+ Partition,
20
+ Ladder,
21
+ Scaffold,
22
+ }
23
+
24
+ /// <summary>
25
+ /// 16-bit packed voxel: 8 bits block type, 4 bits material family, 4 bits state.
26
+ /// A 32³ chunk is 64 KiB.
27
+ /// </summary>
28
+ public readonly record struct Voxel(ushort Packed)
29
+ {
30
+ public static readonly Voxel Air = default;
31
+
32
+ public Voxel(BlockType type, MaterialFamily material = MaterialFamily.Concrete, byte state = 0)
33
+ : this((ushort)((byte)type | ((int)material & 0xF) << 8 | (state & 0xF) << 12)) { }
34
+
35
+ public BlockType Type => (BlockType)(Packed & 0xFF);
36
+ public MaterialFamily Material => (MaterialFamily)((Packed >> 8) & 0xF);
37
+ public byte State => (byte)(Packed >> 12);
38
+
39
+ public bool IsAir => Type == BlockType.Air;
40
+ /// <summary>Blocks the player/agents can move through.</summary>
41
+ public bool IsPassable => Type is BlockType.Air or BlockType.Ladder;
42
+ /// <summary>Hides faces of neighbours. Windows and ladders are see-through.</summary>
43
+ public bool IsOpaque => Type is not (BlockType.Air or BlockType.Window or BlockType.Ladder or BlockType.Scaffold);
44
+
45
+ /// <summary>Key used to batch faces into one draw call (§14 material groups).</summary>
46
+ public ushort MeshKey => (ushort)(Packed & 0x0FFF);
47
+ }
48
+
49
+ public readonly record struct ChunkCoord(int X, int Y, int Z)
50
+ {
51
+ public static ChunkCoord FromVoxel(int x, int y, int z) =>
52
+ new(FloorDiv(x), FloorDiv(y), FloorDiv(z));
53
+
54
+ public static int FloorDiv(int v) => v >= 0 ? v / WorldConstants.ChunkSize : (v + 1) / WorldConstants.ChunkSize - 1;
55
+
56
+ public int OriginX => X * WorldConstants.ChunkSize;
57
+ public int OriginY => Y * WorldConstants.ChunkSize;
58
+ public int OriginZ => Z * WorldConstants.ChunkSize;
59
+
60
+ public int ChebyshevDistance(ChunkCoord o) => Math.Max(Math.Abs(X - o.X), Math.Max(Math.Abs(Y - o.Y), Math.Abs(Z - o.Z)));
61
+
62
+ public override string ToString() => $"{X},{Y},{Z}";
63
+ }
64
+
65
+ public sealed class Chunk
66
+ {
67
+ private const int S = WorldConstants.ChunkSize;
68
+ private readonly ushort[] _voxels = new ushort[WorldConstants.ChunkVolume];
69
+
70
+ public Chunk(ChunkCoord coord) => Coord = coord;
71
+
72
+ public ChunkCoord Coord { get; }
73
+ public int NonAirCount { get; private set; }
74
+ public bool IsEmpty => NonAirCount == 0;
75
+
76
+ public static int Index(int x, int y, int z) => (y * S + z) * S + x;
77
+
78
+ public Voxel this[int x, int y, int z]
79
+ {
80
+ get => new(_voxels[Index(x, y, z)]);
81
+ set
82
+ {
83
+ var i = Index(x, y, z);
84
+ var was = _voxels[i] & 0xFF;
85
+ var now = value.Packed & 0xFF;
86
+ if (was == 0 && now != 0) NonAirCount++;
87
+ else if (was != 0 && now == 0) NonAirCount--;
88
+ _voxels[i] = value.Packed;
89
+ }
90
+ }
91
+
92
+ public Voxel GetIndex(int i) => new(_voxels[i]);
93
+ public ReadOnlySpan<ushort> Raw => _voxels;
94
+ }
src/Repoverse.Core/Voxels/WorldGenerator.cs ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using Repoverse.Core.Generation;
2
+ using Repoverse.Core.Model;
3
+ using static Repoverse.Core.WorldConstants;
4
+
5
+ namespace Repoverse.Core.Voxels;
6
+
7
+ /// <summary>
8
+ /// Procedural base state for any chunk, derived only from the manifest (§11): terrain,
9
+ /// district road grid and buildings. Player edits are layered on top by <see cref="WorldEdits"/>.
10
+ /// </summary>
11
+ public sealed class WorldGenerator
12
+ {
13
+ private readonly Dictionary<(int, int), BuildingDefinition> _byPlotCell = new();
14
+
15
+ public WorldGenerator(WorldManifest manifest)
16
+ {
17
+ Manifest = manifest;
18
+ foreach (var b in manifest.Buildings)
19
+ _byPlotCell[(Math.DivRem(b.Footprint.X, PlotSize).Quotient, Math.DivRem(b.Footprint.Z, PlotSize).Quotient)] = b;
20
+ }
21
+
22
+ public WorldManifest Manifest { get; }
23
+
24
+ /// <summary>Top chunk layer that can contain anything.</summary>
25
+ public static int MaxChunkY => ChunkCoord.FloorDiv(GroundLevel + MaxFloors * FloorHeight + 1);
26
+
27
+ public Chunk Generate(ChunkCoord c, WorldEdits? edits = null, CancellationToken ct = default)
28
+ {
29
+ var chunk = new Chunk(c);
30
+ if (c.Y < 0 || c.Y > MaxChunkY) return chunk;
31
+
32
+ for (int z = 0; z < ChunkSize; z++)
33
+ for (int x = 0; x < ChunkSize; x++)
34
+ {
35
+ int wx = c.OriginX + x, wz = c.OriginZ + z;
36
+ var surface = Surface(wx, wz);
37
+ for (int y = 0; y < ChunkSize; y++)
38
+ {
39
+ int wy = c.OriginY + y;
40
+ if (wy >= GroundLevel) break;
41
+ chunk[x, y, z] = wy == 0 ? new Voxel(BlockType.Bedrock, MaterialFamily.Stone)
42
+ : wy < GroundLevel - 1 ? new Voxel(BlockType.Soil, MaterialFamily.Stone)
43
+ : surface;
44
+ }
45
+ }
46
+ ct.ThrowIfCancellationRequested();
47
+
48
+ foreach (var b in BuildingsTouching(c))
49
+ {
50
+ BuildingRasterizer.Rasterize(b, (x, y, z, v) =>
51
+ {
52
+ int lx = x - c.OriginX, ly = y - c.OriginY, lz = z - c.OriginZ;
53
+ if ((uint)lx < ChunkSize && (uint)ly < ChunkSize && (uint)lz < ChunkSize)
54
+ chunk[lx, ly, lz] = v;
55
+ });
56
+ ct.ThrowIfCancellationRequested();
57
+ }
58
+
59
+ edits?.ApplyTo(chunk);
60
+ return chunk;
61
+ }
62
+
63
+ public IEnumerable<BuildingDefinition> BuildingsTouching(ChunkCoord c)
64
+ {
65
+ int x0 = Math.DivRem(c.OriginX - PlotSize, PlotSize).Quotient, x1 = Math.DivRem(c.OriginX + ChunkSize + PlotSize, PlotSize).Quotient;
66
+ int z0 = Math.DivRem(c.OriginZ - PlotSize, PlotSize).Quotient, z1 = Math.DivRem(c.OriginZ + ChunkSize + PlotSize, PlotSize).Quotient;
67
+ for (int px = x0; px <= x1; px++)
68
+ for (int pz = z0; pz <= z1; pz++)
69
+ if (_byPlotCell.TryGetValue((px, pz), out var b) && Overlaps(b, c))
70
+ yield return b;
71
+ }
72
+
73
+ private static bool Overlaps(BuildingDefinition b, ChunkCoord c)
74
+ {
75
+ // Rasterized extent: footprint plus one voxel of foundation/scaffold, ground-1 to roof.
76
+ int minY = GroundLevel - 1, maxY = GroundLevel + b.Floors * FloorHeight;
77
+ return b.Footprint.X - 1 < c.OriginX + ChunkSize && b.Footprint.MaxX + 1 >= c.OriginX
78
+ && b.Footprint.Z - 1 < c.OriginZ + ChunkSize && b.Footprint.MaxZ + 1 >= c.OriginZ
79
+ && minY < c.OriginY + ChunkSize && maxY >= c.OriginY;
80
+ }
81
+
82
+ /// <summary>Ground block: roads ring every plot inside a district, grass elsewhere.</summary>
83
+ public static Voxel Surface(int wx, int wz)
84
+ {
85
+ const int stride = DistrictSpan + 2 * PlotSize;
86
+ int dx = Mod(wx, stride), dz = Mod(wz, stride);
87
+ if (dx >= DistrictSpan || dz >= DistrictSpan)
88
+ {
89
+ // Avenue between districts with a central road.
90
+ int ax = dx - DistrictSpan, az = dz - DistrictSpan;
91
+ bool onRoad = (dx >= DistrictSpan && Math.Abs(ax - PlotSize) < RoadWidth) || (dz >= DistrictSpan && Math.Abs(az - PlotSize) < RoadWidth);
92
+ return onRoad ? new Voxel(BlockType.Road, MaterialFamily.Concrete) : new Voxel(BlockType.Grass, MaterialFamily.Wood);
93
+ }
94
+ int px = dx % PlotSize, pz = dz % PlotSize;
95
+ int half = RoadWidth / 2;
96
+ bool road = px < half || px >= PlotSize - half || pz < half || pz >= PlotSize - half;
97
+ bool walk = !road && (px < RoadWidth || px >= PlotSize - RoadWidth || pz < RoadWidth || pz >= PlotSize - RoadWidth);
98
+ return road ? new Voxel(BlockType.Road, MaterialFamily.Concrete)
99
+ : walk ? new Voxel(BlockType.Sidewalk, MaterialFamily.Stone)
100
+ : new Voxel(BlockType.Grass, MaterialFamily.Wood);
101
+ }
102
+
103
+ private static int Mod(int a, int m) => ((a % m) + m) % m;
104
+ }
105
+
106
+ /// <summary>Persistent user modifications, stored separately from procedural state (§11, §22).</summary>
107
+ public sealed class WorldEdits
108
+ {
109
+ private readonly Dictionary<ChunkCoord, Dictionary<int, ushort>> _edits = new();
110
+ private readonly object _gate = new();
111
+
112
+ public void Set(int x, int y, int z, Voxel v)
113
+ {
114
+ var c = ChunkCoord.FromVoxel(x, y, z);
115
+ lock (_gate)
116
+ {
117
+ if (!_edits.TryGetValue(c, out var map)) _edits[c] = map = new();
118
+ map[Chunk.Index(x - c.OriginX, y - c.OriginY, z - c.OriginZ)] = v.Packed;
119
+ }
120
+ }
121
+
122
+ public void ApplyTo(Chunk chunk)
123
+ {
124
+ lock (_gate)
125
+ {
126
+ if (!_edits.TryGetValue(chunk.Coord, out var map)) return;
127
+ foreach (var (i, packed) in map)
128
+ {
129
+ int x = i % ChunkSize, z = i / ChunkSize % ChunkSize, y = i / (ChunkSize * ChunkSize);
130
+ chunk[x, y, z] = new Voxel(packed);
131
+ }
132
+ }
133
+ }
134
+
135
+ public int Count { get { lock (_gate) return _edits.Values.Sum(m => m.Count); } }
136
+
137
+ public IReadOnlyDictionary<ChunkCoord, IReadOnlyDictionary<int, ushort>> Snapshot()
138
+ {
139
+ lock (_gate)
140
+ return _edits.ToDictionary(kv => kv.Key, kv => (IReadOnlyDictionary<int, ushort>)new Dictionary<int, ushort>(kv.Value));
141
+ }
142
+
143
+ public void Load(IReadOnlyDictionary<ChunkCoord, IReadOnlyDictionary<int, ushort>> data)
144
+ {
145
+ lock (_gate)
146
+ {
147
+ _edits.Clear();
148
+ foreach (var (c, map) in data) _edits[c] = new Dictionary<int, ushort>(map);
149
+ }
150
+ }
151
+ }
src/Repoverse.Core/WorldConstants.cs ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ namespace Repoverse.Core;
2
+
3
+ /// <summary>All tunable world dimensions in one place (§64). Units are voxels unless stated.</summary>
4
+ public static class WorldConstants
5
+ {
6
+ public const int ChunkSize = 32;
7
+ public const int ChunkVolume = ChunkSize * ChunkSize * ChunkSize;
8
+
9
+ /// <summary>One building plot plus its surrounding road.</summary>
10
+ public const int PlotSize = 48;
11
+ public const int RoadWidth = 6;
12
+ public const int MaxFootprint = PlotSize - 2 * RoadWidth; // 36
13
+ public const int MinFootprint = 10;
14
+
15
+ /// <summary>Plots per district side; a district holds DistrictSide² buildings before overflow.</summary>
16
+ public const int DistrictSide = 12;
17
+ public const int DistrictSpan = DistrictSide * PlotSize;
18
+ public const int DistrictGridColumns = 4;
19
+
20
+ public const int GroundLevel = 8;
21
+ public const int FloorHeight = 6; // 1 slab + 5 air
22
+ public const int MaxFloors = 12;
23
+ public const int CorridorWidth = 3;
24
+ public const int DoorHeight = 3;
25
+
26
+ /// <summary>Directories with fewer files merge into a shared room (§78 semantic compression).</summary>
27
+ public const int MinFilesForOwnRoom = 2;
28
+ public const int MaxRoomsPerBuilding = 48;
29
+ public const int MaxArtifactsPerRoom = 24;
30
+
31
+ public const int ActivityWindowDays = 90;
32
+ public const int StreamRadiusChunks = 6;
33
+ public const int StreamHysteresisChunks = 2;
34
+
35
+ public const double SimulationTicksPerSecond = 10;
36
+
37
+ public static readonly string[] IgnoredDirectories =
38
+ [
39
+ "node_modules", "target", "bin", "obj", "build", "dist", "out", ".git", ".idea", ".vs",
40
+ "__pycache__", ".venv", "venv", "vendor", ".gradle", ".next", ".cache", "coverage",
41
+ ];
42
+ }
src/Repoverse.Sidecar/Program.cs ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using System.Security.Cryptography;
2
+ using System.Text;
3
+ using System.Text.Json;
4
+ using Repoverse.Core.Bridge;
5
+ using Repoverse.Core.Generation;
6
+ using Repoverse.Core.Persistence;
7
+
8
+ // Local-only service. One Unreal client owns a session; reconnect starts a new stream.
9
+ var builder = WebApplication.CreateBuilder(args);
10
+ string Required(string name) => builder.Configuration[name] ?? throw new ArgumentException($"--{name} is required");
11
+ var manifest = JsonSerializer.Deserialize<WorldManifest>(File.ReadAllText(Required("manifest")), Repoverse.Core.Generation.Json.Options)
12
+ ?? throw new InvalidDataException("Empty manifest");
13
+ var token = Required("token");
14
+ if (token.Length < 32) throw new ArgumentException("Use a random token of at least 32 characters.");
15
+ var tokenHash = SHA256.HashData(Encoding.UTF8.GetBytes(token));
16
+ int port = int.Parse(builder.Configuration["port"] ?? "38473");
17
+ if (port is < 1024 or > 65535) throw new ArgumentException("Invalid port");
18
+ builder.WebHost.UseUrls($"http://127.0.0.1:{port}");
19
+ builder.WebHost.ConfigureKestrel(k => k.Limits.MaxRequestBodySize = 64 * 1024);
20
+ builder.Services.ConfigureHttpJsonOptions(o => {
21
+ o.SerializerOptions.PropertyNamingPolicy = Repoverse.Core.Generation.Json.Options.PropertyNamingPolicy;
22
+ foreach (var c in Repoverse.Core.Generation.Json.Options.Converters) o.SerializerOptions.Converters.Add(c);
23
+ });
24
+ var app = builder.Build();
25
+ var gate = new SemaphoreSlim(1,1);
26
+ var session = new WorldSession(manifest);
27
+ var savePath = Path.GetFullPath(builder.Configuration["save"] ?? "repoverse-save.json");
28
+ var sourceRoot = builder.Configuration["source-root"];
29
+ var sourceRepo = builder.Configuration["source-repo"];
30
+ var sources = sourceRoot == null || sourceRepo == null ? null : new LocalSourceReader(manifest, sourceRepo, sourceRoot);
31
+ app.Use(async (context,next) => {
32
+ // No CORS: web pages cannot use this service. Authenticate even read-only requests.
33
+ var supplied = SHA256.HashData(Encoding.UTF8.GetBytes(context.Request.Headers["X-Repoverse-Token"].ToString()));
34
+ if (context.Request.Headers.ContainsKey("Origin") || !CryptographicOperations.FixedTimeEquals(tokenHash,supplied)) {
35
+ context.Response.StatusCode=403; return;
36
+ }
37
+ await gate.WaitAsync(context.RequestAborted);
38
+ try { await next(context); }
39
+ catch (Exception e) when (e is ArgumentException or InvalidDataException or JsonException or FormatException or IOException) {
40
+ context.Response.StatusCode=400;
41
+ await context.Response.WriteAsJsonAsync(new { error=e.Message });
42
+ }
43
+ finally { gate.Release(); }
44
+ });
45
+ app.MapPost("/v1/session", () => {
46
+ var player = session.Player;
47
+ var saved = session.Capture();
48
+ session = new WorldSession(manifest); session.Restore(saved);
49
+ return new { schemaVersion=1, worldSeed=manifest.WorldSeed, player, destinations=session.Destinations, objects=session.Objects(), builders=session.Builders };
50
+ });
51
+ app.MapPost("/v1/focus", (FocusRequest r) => {var p=session.Focus(r.X,r.Z);return new {p.Unloaded,p.Chunks,p.Remaining,p.Resident,builders=session.Builders};});
52
+ app.MapPost("/v1/build", (BuilderPlan plan) => session.Build(plan));
53
+ app.MapPost("/v1/save", (PlayerState player) => {
54
+ session.SetPlayer(player);
55
+ Directory.CreateDirectory(Path.GetDirectoryName(savePath)!);
56
+ SaveGame.Write(savePath,session.Capture());
57
+ return new { saved=true };
58
+ });
59
+ app.MapPost("/v1/load", () => { session.Restore(SaveGame.Read(savePath)); return session.Player; });
60
+ app.MapPost("/v1/edit", (EditRequest r) => {session.Edit(r.X,r.Y,r.Z,r.Packed);return new { edited=true };});
61
+ app.MapGet("/v1/source", (string repo, string path, int offset = 0) => sources is null
62
+ ? Results.BadRequest(new { error="Local source inspection is not configured. Use --source-root and --source-repo." })
63
+ : Results.Ok(sources.Read(repo,path,offset)));
64
+ app.MapGet("/v1/health", () => new { schemaVersion=1, resident=session.Resident });
65
+ await app.RunAsync();
66
+ record FocusRequest(double X,double Z);
67
+ record EditRequest(int X,int Y,int Z,ushort Packed);
src/Repoverse.Sidecar/Repoverse.Sidecar.csproj ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ <Project Sdk="Microsoft.NET.Sdk.Web">
2
+ <PropertyGroup><TargetFramework>net8.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
3
+ <ItemGroup><ProjectReference Include="../Repoverse.Core/Repoverse.Core.csproj" /></ItemGroup>
4
+ </Project>
tests/Repoverse.Core.Tests/BridgeTests.cs ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using Repoverse.Core.Bridge;
2
+ using Repoverse.Core.Generation;
3
+ using Repoverse.Core.Persistence;
4
+ using Repoverse.Core.Voxels;
5
+
6
+ namespace Repoverse.Core.Tests;
7
+
8
+ public class BridgeTests
9
+ {
10
+ private static WorldSession Session(int radius = 0) => new(ManifestBuilder.Build(TestRepos.Slice(),new Seed(42)),radius);
11
+ private static List<MeshPacket> Settle(WorldSession s,double x,double z)
12
+ {
13
+ var meshes=new List<MeshPacket>();
14
+ for(int i=0;i<100;i++) {
15
+ var p=s.Focus(x,z); meshes.AddRange(p.Chunks);
16
+ if(p.Remaining==0)return meshes;
17
+ }
18
+ throw new Exception("Stream did not settle");
19
+ }
20
+ [Fact] public void Streaming_is_bounded_and_unloads_old_meshes()
21
+ {
22
+ var s=Session(); var first=Settle(s,0,0);
23
+ Assert.NotEmpty(first);
24
+ Assert.Equal(WorldGenerator.MaxChunkY+1,s.Resident);
25
+ var moved=s.Focus(1000,1000);
26
+ Assert.Equal(first.Select(m=>m.Id).Distinct().Order(),moved.Unloaded.Order());
27
+ for(int i=0;i<20;i++) {
28
+ Settle(s,i*500,i*500);
29
+ Assert.InRange(s.Resident,1,WorldGenerator.MaxChunkY+1);
30
+ }
31
+ }
32
+ [Fact] public void Edits_remesh_and_survive_unload_and_save_restore()
33
+ {
34
+ var s=Session();Settle(s,0,0);
35
+ s.Edit(2,15,2,new Voxel(BlockType.Wall).Packed);
36
+ Assert.NotEmpty(s.Focus(0,0).Chunks);
37
+ s.SetPlayer(new PlayerState {X=2,Y=16,Z=2,Selection="repoverse://snapkitty/site"});
38
+ var saved=s.Capture();
39
+ Settle(s,2000,2000);Settle(s,0,0);
40
+ Assert.Equal(BlockType.Wall,s.Sample(2,15,2)!.Value.Type);
41
+ var restored=Session();restored.Restore(saved);Settle(restored,0,0);
42
+ Assert.Equal(saved.Player,restored.Player);
43
+ Assert.Equal(BlockType.Wall,restored.Sample(2,15,2)!.Value.Type);
44
+ Assert.Throws<InvalidDataException>(()=>restored.Restore(saved with {WorldSeed="other"}));
45
+ }
46
+ [Fact] public void Mesh_packets_have_outward_core_winding_and_passable_ladders()
47
+ {
48
+ var c=new Chunk(new(0,0,0));c[1,1,1]=new Voxel(BlockType.Wall);c[4,1,1]=new Voxel(BlockType.Ladder);
49
+ var packet=WorldSession.Encode(GreedyMesher.Build(c));
50
+ Assert.Contains(packet.Sections,s=>!s.Collision && (s.Key&255)==(int)BlockType.Ladder);
51
+ var wall=packet.Sections.Single(s=>(s.Key&255)==(int)BlockType.Wall);
52
+ Assert.Equal(24,wall.Vertices.Length);Assert.Equal(36,wall.Indices.Length);
53
+ for(int i=0;i<wall.Indices.Length;i+=3) {
54
+ System.Numerics.Vector3 V(int n) {var v=wall.Vertices[n];return new(v[0],v[1],v[2]);}
55
+ var a=V(wall.Indices[i]);var b=V(wall.Indices[i+1]);var d=V(wall.Indices[i+2]);
56
+ Assert.True(System.Numerics.Vector3.Dot(System.Numerics.Vector3.Cross(b-a,d-a),(a+b+d)/3-new System.Numerics.Vector3(1.5f))>0);
57
+ }
58
+ }
59
+ [Fact] public void Adjacent_arrivals_remesh_boundaries()
60
+ {
61
+ var s=Session(1); var seen=new Dictionary<string,int>();
62
+ for(int i=0;i<100;i++) {
63
+ var p=s.Focus(0,0,1);
64
+ foreach(var c in p.Chunks)seen[c.Id]=seen.GetValueOrDefault(c.Id)+1;
65
+ if(p.Remaining==0)break;
66
+ }
67
+ Assert.Contains(seen.Values,n=>n>1);
68
+ Assert.Equal(9*(WorldGenerator.MaxChunkY+1),s.Resident);
69
+ }
70
+ [Fact] public void Invalid_coordinates_are_rejected()
71
+ {
72
+ var s=Session();Assert.Throws<ArgumentException>(()=>s.Focus(double.NaN,0));
73
+ Assert.Throws<ArgumentException>(()=>s.SetPlayer(new PlayerState{Y=double.PositiveInfinity}));
74
+ Assert.Throws<ArgumentException>(()=>s.Edit(0,0,0,0));
75
+ }
76
+ [Fact] public void Source_is_paged_and_restricted_to_manifest_artifacts()
77
+ {
78
+ var dir=Path.Combine(Path.GetTempPath(),Guid.NewGuid().ToString());Directory.CreateDirectory(dir);
79
+ try {
80
+ var manifest=ManifestBuilder.Build([TestRepos.Make("source",files:["README.md","../escape.txt"])],new Seed(1));
81
+ File.WriteAllLines(Path.Combine(dir,"README.md"),Enumerable.Range(0,80).Select(i=>$"line {i}"));
82
+ var source=new LocalSourceReader(manifest,"snapkitty/source",dir);
83
+ var page=source.Read("snapkitty/source","README.md",32);
84
+ Assert.Equal("line 32",page.Lines[0]);Assert.Equal(32,page.Lines.Length);Assert.True(page.HasMore);
85
+ Assert.Throws<ArgumentException>(()=>source.Read("someone/else","README.md",0));
86
+ Assert.Throws<ArgumentException>(()=>source.Read("snapkitty/source",".git/config",0));
87
+ Assert.Throws<ArgumentException>(()=>source.Read("snapkitty/source","../escape.txt",0));
88
+ } finally {Directory.Delete(dir,true);}
89
+ }
90
+ }