logicgate: chip placeability now matches the flattener's 32-deep cap, order-free
- Commit
e88c5d8f6ab0d4a3b1af3fe612c09ce88aba383a- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 06:20 UTC (5 days ago)
- Parents
e2d7e75
ChipCatalog measured nesting depth along one memoising DFS while the Flattener inlines at most 32 layers from whichever chip is placed. In creation order, cached children shortcut the depth count, so a 33-deep wrapper chain was offered as placeable; the Flattener then dropped the innermost component's gates at layer 33, leaving its output unwired (reads 0) — a placed custom:c32 NOT chain output 0 for input 0. Listed deepest-first the same order dependence cut the other way: a valid 11-deep component resolved to nothing and could not even be wired. Whether a component existed depended on catalog listing order. A component is now placeable iff its own containment height (itself plus the tallest component inside it) is <= 32 — the Flattener cap counted from the placed chip — computed leaf-first with an iterative queue: no recursion (a deep persisted chain cannot overflow the stack) and no order dependence; components on or above a containment cycle still never resolve. New regression tests failed pre-fix: both listing orders resolve c10/c31 but not c32, and the c31 circuit evaluates 0->1, 1->0. A 300-circuit fuzz against a naive fixed-point evaluator also matched. AGENTS.md gains one current-state sentence on the cap. Verified: :games:logicgate:testDevUnitTest and :games:logicgate:lint BUILD SUCCESSFUL.
Diff
games/logicgate/AGENTS.md
diff --git a/games/logicgate/AGENTS.md b/games/logicgate/AGENTS.mdindex 89b5f9cf57..00b8585812 100644--- a/games/logicgate/AGENTS.md+++ b/games/logicgate/AGENTS.md@@ -19,7 +19,7 @@ _Install: ./install games/logicgate (dev by default)._ - Level I/O are real `LevelInput`/`LevelOutput` nodes. Unconnected inputs read 0. - One tick of an implicit global clock = settle, then latch. Feedback loops iterate Gauss-Seidel (cap 64 passes → oscillation). State-only chips (DFF/REG/PC) break loops. - Solving a level unlocks its chip as a trusted native behaviour (`domain/model/Chips.kt`). Level pins, tests and par for reward levels derive from that chip (`ChipLevel.kt`), so they cannot drift.-- Sandbox components (`domain/model/CustomChip.kt`, ids `custom:<uuid>`) are a `Board` (circuit + editable `LevelIo`) behind `Behavior.Composite`. `ChipCatalog` resolves built-ins + components (costs summed recursively; self-containing components resolve to null). `domain/sim/Flattener.kt` inlines composites before simulating, so feedback across component boundaries is exact. Chip pin order is the board's pin nodes sorted top-to-bottom. When an edit reorders or removes pins, `remapChipPins` rewires every other component and level draft that uses the component.+- Sandbox components (`domain/model/CustomChip.kt`, ids `custom:<uuid>`) are a `Board` (circuit + editable `LevelIo`) behind `Behavior.Composite`. `ChipCatalog` resolves built-ins + components (costs summed recursively; self-containing components resolve to null, as do components nested more than 32 deep — the Flattener's inlining cap, counted from the component itself). `domain/sim/Flattener.kt` inlines composites before simulating, so feedback across component boundaries is exact. Chip pin order is the board's pin nodes sorted top-to-bottom. When an edit reorders or removes pins, `remapChipPins` rewires every other component and level draft that uses the component. - Sandbox tray = `LevelRegistry.unlockedChips(completed)` + components that don't contain the open one + `PinChips` (pseudo-chips `pin:in|out:{1,4,8}` that add board pins). Level tray = `allowedChips(level)` + every component. Tray tabs come from `domain/levels/ChipGroups.kt` (Pins, built-ins by chapter, player group names). - ISA (`domain/model/Isa.kt`): `op[4]|operand[4]`, LDA STA ADD SUB LDI JMP JZ HLT, one instruction per tick via dual-port RAM16. **Gotchas:**
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipCatalog.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipCatalog.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipCatalog.ktindex ca2cdef705..a83859b587 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipCatalog.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipCatalog.kt@@ -3,33 +3,50 @@ package com.vayunmathur.games.logicgate.domain.model /** * Every placeable chip: the built-ins plus the player's [customs]. Custom specs are resolved once * up front (so the catalog is immutable and safe to share with the verifier's thread); a component- * that contains itself, directly or not, resolves to nothing and drops out like an unknown chip.+ * that contains itself, directly or not, resolves to nothing and drops out like an unknown chip,+ * as does one nested more than [MAX_DEPTH] components deep (the simulator's inlining cap). */ class ChipCatalog(val customs: List<CustomChip> = emptyList()) { private val byId: Map<String, CustomChip> = customs.associateBy { it.id } private val specs: Map<String, ChipSpec> init {- val resolved = HashMap<String, ChipSpec?>()- val resolving = HashSet<String>()- fun resolve(id: String, depth: Int = 0): ChipSpec? {- Chips[id]?.let { return it }- if (id in resolved) return resolved[id]- // A deep containment chain from persisted components must not- // overflow the stack at startup; Flattener caps at 32 too.- if (depth >= MAX_DEPTH) return null- val chip = byId[id] ?: return null- if (!resolving.add(id)) return null- val gates = chip.board.circuit.nodes.filterIsInstance<Gate>()- val inner = gates.map { resolve(it.chipId, depth + 1) }- resolving.remove(id)- val cyclic = gates.zip(inner).any { (g, s) -> s == null && byId[g.chipId] != null }- val spec = if (cyclic) null else chip.toSpec(inner.sumOf { it?.nandCost ?: 0 })- resolved[id] = spec- return spec+ // A component is placeable exactly when its own containment height — itself plus the+ // tallest component inside it — fits the cap. Heights are worked out leaf-first with a+ // queue (never recursing, so a deep persisted chain cannot overflow the stack, and never+ // depending on the order components are listed in: a depth measured along one resolving+ // walk would let cached children shortcut the count and disagree with the simulator,+ // which inlines at most MAX_DEPTH layers from whichever chip is placed). A component on+ // or above a containment cycle never becomes ready, so it resolves to nothing too.+ val gates = byId.mapValues { (_, chip) -> chip.board.circuit.nodes.filterIsInstance<Gate>() }+ val deps = gates.mapValues { (_, gs) -> gs.map { it.chipId }.filter { it in byId }.distinct() }+ val parents = HashMap<String, MutableList<String>>()+ for ((id, ds) in deps) for (d in ds) parents.getOrPut(d) { mutableListOf() } += id+ val unresolved = HashMap<String, Int>()+ val tallestChild = HashMap<String, Int>()+ val height = HashMap<String, Int>()+ val cost = HashMap<String, Int>()+ val queue = ArrayDeque<String>()+ for (id in byId.keys) {+ val pending = deps[id].orEmpty().size+ unresolved[id] = pending+ if (pending == 0) queue.addLast(id) }- customs.forEach { resolve(it.id) }- specs = resolved.mapNotNull { (k, v) -> v?.let { k to it } }.toMap()+ while (queue.isNotEmpty()) {+ val id = queue.removeFirst()+ val h = (tallestChild[id] ?: 0) + 1+ height[id] = h+ cost[id] = gates[id].orEmpty().sumOf { g -> Chips[g.chipId]?.nandCost ?: cost[g.chipId] ?: 0 }+ for (p in parents[id].orEmpty()) {+ tallestChild[p] = maxOf(tallestChild[p] ?: 0, h)+ val left = (unresolved[p] ?: 0) - 1+ unresolved[p] = left+ if (left == 0) queue.addLast(p)+ }+ }+ specs = byId.values.mapNotNull { chip ->+ height[chip.id]?.takeIf { it <= MAX_DEPTH }?.let { chip.id to chip.toSpec(cost[chip.id] ?: 0) }+ }.toMap() } operator fun get(id: String): ChipSpec? = Chips[id] ?: specs[id]
games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/FlattenerTest.kt
diff --git a/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/FlattenerTest.kt b/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/FlattenerTest.ktindex 942d37a78a..74d537a759 100644--- a/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/FlattenerTest.kt+++ b/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/FlattenerTest.kt@@ -15,6 +15,7 @@ import com.vayunmathur.games.logicgate.domain.sim.Simulator import kotlin.test.Test import kotlin.test.assertContentEquals import kotlin.test.assertEquals+import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue @@ -194,6 +195,52 @@ class FlattenerTest { assertEquals(setOf(g), Simulator(c, io, catalog::get).settle()) } + /** `custom:c0` is a NOT; every later component passes its predecessor straight through. */+ private fun wrapperChain(count: Int): List<CustomChip> {+ val chips = mutableListOf(+ Build(Board.Empty).run {+ val i = input()+ val o = output()+ val n = gate(Chips.NOT)+ wire(i, 0, n, 0); wire(n, 0, o, 0)+ chip("custom:c0")+ },+ )+ for (k in 1 until count) {+ val prev = chips.last()+ chips += Build(Board.Empty, ChipCatalog(chips.toList())).run {+ val i = input()+ val o = output()+ val g = gate(prev.id)+ wire(i, 0, g, 0); wire(g, 0, o, 0)+ chip("custom:c$k")+ }+ }+ return chips+ }++ @Test+ fun componentsResolveTheSameWhateverOrderTheCatalogSeesThem() {+ // c10 nests 11 deep and c31 exactly to the inlining cap, so both must resolve;+ // c32 nests one deeper than the cap, so it must not, in either listing order.+ val chips = wrapperChain(33)+ for (ordered in listOf(chips, chips.reversed())) {+ val catalog = ChipCatalog(ordered)+ assertNotNull(catalog["custom:c10"])+ assertNotNull(catalog["custom:c31"])+ assertNull(catalog["custom:c32"])+ }+ }++ @Test+ fun aComponentAtTheNestingCapStillEvaluates() {+ val chips = wrapperChain(ChipCatalog.MAX_DEPTH)+ val catalog = ChipCatalog(chips)+ val (board, _) = around(chips.last().id, 1, catalog)+ assertEquals(1, settle(board, catalog, 0))+ assertEquals(0, settle(board, catalog, 1))+ }+ @Test fun aComponentThatContainsItselfResolvesToNothing() { val self = CustomChip(