arkai2025 Claude Opus 4.8 (1M context) commited on
Commit
f2b4b4e
·
1 Parent(s): 18c42c1

feat(edit): replace small-model selector with keyword + parametric assembler

Browse files

Edit path is now pure Python: an English keyword parser maps the instruction to
a catalog part plus count/scale/anchor/rotation/color, and the assembler snaps it
on deterministically (symmetric pairs first, overflow to rear; float scale rounded
to the grid; exact 90deg integer-grid rotation). Instant, no GPU. Gemma 12B stays
only for full generation, hatch fusion, and the freeform-edit safety valve.

Removes select_part, the MiniCPM selector constants/preflight/warmup bench, and
SELECT_SCHEMA/build_select_messages.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

docs/superpowers/plans/2026-06-15-keyword-parametric-edit.md ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Keyword + Parametric Edit Path (drop the small model) Implementation Plan
2
+
3
+ > REQUIRED SUB-SKILL: superpowers:executing-plans. Steps use `- [ ]`.
4
+
5
+ **Goal:** Replace the MiniCPM5-1B selector on the edit path with a pure-Python,
6
+ English keyword parser feeding a parametric assembler (scale / count / rotation /
7
+ symmetric distribution). The edit path becomes instant and model-free; Gemma 12B
8
+ stays only for full generation + hatch fusion.
9
+
10
+ **Architecture:** New `edit_parser.py` turns an instruction into a `PlacementSpec`
11
+ {part, anchor, scale, count, rotation, color}. `assembler.assemble_part` gains
12
+ float scale (round to grid), 90° integer-grid rotation (per-voxel, exact), and
13
+ count>1 distribution (symmetric pairs first, overflow to rear). Both runtimes
14
+ (fake + llama) route edits through this one path. The selector, its schema,
15
+ preflight, and warmup bench are deleted.
16
+
17
+ **Tech Stack:** Python, pytest. No model on the edit path.
18
+
19
+ ---
20
+
21
+ ## File Structure
22
+
23
+ - Create `src/buddy_fusion/edit_parser.py` — `PlacementSpec` + `parse_edit()` + `match_part()`.
24
+ - Modify `src/buddy_fusion/assembler.py` — float `_scaled`, `_rotate`, count distribution in `assemble_part`.
25
+ - Modify `src/buddy_fusion/runtime.py` — both runtimes call `parse_edit` → `assemble_part`; delete `select_part`, selector constants, `_active_selector`, `_selector_preflight`, warmup selector bench.
26
+ - Modify `src/buddy_fusion/prompts.py` — delete `SELECT_SCHEMA`, `build_select_messages`.
27
+ - Create `tests/test_edit_parser.py`; extend `tests/test_assembler.py`; trim `tests/test_select_routing.py` (selector gone).
28
+
29
+ Box convention unchanged: x,z center; y bottom; symmetric authors left half.
30
+
31
+ ---
32
+
33
+ ### Task 1: Parametric assembler
34
+
35
+ - [ ] `_scaled` accepts float, rounds coords + sizes to grid (sizes >= 1).
36
+ - [ ] `_rotate(boxes, axis, quarters)`: explode to unit cells, rotate on grid about the part center, return 1x1x1 boxes.
37
+ - [ ] `assemble_part(boxes, part_id, anchor, scale=1, color=None, count=1, rotation=None)`: build local (mirror symmetric → scale → rotate → recolor), then distribute `count` instances (symmetric-pairs-first along the side tangent z; overflow to rear along x; tails/front spread along x), face-aligned per slot. Repair once.
38
+ - [ ] Tests: float scale grows cell count; rotation preserves cell count; count=3 adds ~3x cells; placement stays within repair clamps. `pytest -q`.
39
+
40
+ ### Task 2: Keyword parser
41
+
42
+ - [ ] `match_part(text)`: score parts by normalized (singular) token overlap — id tokens primary, generic-id tie-break, desc secondary. "bat wing"→wing_bat, "wing"→wings, "fox tail"→tail_fox, "house"→house.
43
+ - [ ] `parse_edit(instruction)`: part (None if no match) + count (digits/one..ten, clamp 1..8) + scale (size adjectives, default 1.0) + anchor (behind/back→rear, top/above/head→top, under/below→bottom, front, left, right; else part default) + rotation (upside-down→x180, sideways→z90, rotated→y90) + color (reuse `_COLOR_WORDS`/`_COLOR_HEX`, English keys).
44
+ - [ ] Tests: each axis parsed; "add five big bat wings behind it" → wing_bat, count 5, scale 1.5, anchor rear. `pytest -q`.
45
+
46
+ ### Task 3: Wire runtimes, delete selector
47
+
48
+ - [ ] `FakeBuddyRuntime.edit_creature` and `LlamaCppBuddyRuntime.edit_creature`: `spec = parse_edit(instruction)`; if spec → `assemble_part(boxes, spec.part, spec.anchor, spec.scale, spec.color, spec.count, spec.rotation)` + `suggest_tweaks_fallback`; else (no part matched) Gemma `_freeform_edit_creature` stays as the only safety valve in llama, fake returns unchanged/horns.
49
+ - [ ] Delete `select_part`, `SELECTOR_MODEL_*`, `_active_selector`, `_selector_preflight`, the warmup selector bench/preflight calls, `SELECT_SCHEMA`, `build_select_messages`. Remove `BUDDY_SELECTOR_*` envs.
50
+ - [ ] Update/trim `tests/test_select_routing.py` → assert parse_edit routing instead. `pytest -q`. Commit.
51
+
52
+ ### Task 4: Verify
53
+
54
+ - [ ] `pytest -q` green. Local fake launch + chrome-devtools: type "add five big bat wings behind it", confirm fast template placement. Screenshot to `.playwright-mcp/`.
55
+
56
+ ---
57
+
58
+ ## Decisions locked (user)
59
+
60
+ - No small model anywhere on the edit path. English-only keywords.
61
+ - Distribution: symmetric pairs first, overflow to rear.
62
+ - Rotation: 90° integer-grid only, keyword-triggered.
63
+ - Scale: float multiplier, rounded to the integer voxel grid (cube size constant).
src/buddy_fusion/assembler.py CHANGED
@@ -26,18 +26,75 @@ def _mirror_x(boxes: list[dict]) -> list[dict]:
26
  return [{**b, "x": -b["x"]} for b in boxes]
27
 
28
 
29
- def _scaled(boxes: list[dict], scale: int) -> list[dict]:
30
- if scale <= 1:
 
 
 
31
  return deepcopy(boxes)
 
32
  out = []
33
  for b in boxes:
34
  nb = dict(b)
35
- for k in ("x", "y", "z", "w", "h", "d"):
36
- nb[k] = b[k] * scale
 
 
37
  out.append(nb)
38
  return out
39
 
40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  def _translate(boxes: list[dict], dx: int, dy: int, dz: int) -> list[dict]:
42
  return [{**b, "x": b["x"] + dx, "y": b["y"] + dy, "z": b["z"] + dz} for b in boxes]
43
 
@@ -61,19 +118,55 @@ def _offset_for_anchor(anchor: str, tgt, part) -> tuple[int, int, int]:
61
  return (tcx, tmaxy - pminy, tcz) # "top" (and default)
62
 
63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  def assemble_part(boxes: list[dict], part_id: str, anchor: str,
65
- scale: int = 1, color: str | None = None) -> list[dict]:
66
- """Return boxes + the placed part. Unknown part_id (or empty boxes) → unchanged."""
 
 
 
 
 
67
  part = PARTS.get(part_id)
68
  if part is None or not boxes:
69
  return boxes
70
  if anchor not in ANCHORS:
71
  anchor = part["default_anchor"]
72
- local = _scaled(part["boxes"], int(scale or part.get("default_scale", 1)))
73
  if part.get("symmetric"):
74
  local = local + _mirror_x(local)
75
- dx, dy, dz = _offset_for_anchor(anchor, bbox(boxes), bbox(local))
76
- placed = _translate(local, dx, dy, dz)
77
  if color:
78
- placed = [{**b, "color": color} for b in placed]
 
 
 
 
 
79
  return list(boxes) + repair_boxes(placed)
 
26
  return [{**b, "x": -b["x"]} for b in boxes]
27
 
28
 
29
+ def _scaled(boxes: list[dict], scale: float) -> list[dict]:
30
+ """Scale by a float multiplier, rounding to the integer voxel grid. The cube
31
+ size stays 1 — a bigger part is simply more voxels (wider/taller block), per
32
+ the design: "voxel stays the same size, the whole block just gets bigger"."""
33
+ if abs(float(scale) - 1.0) < 1e-9:
34
  return deepcopy(boxes)
35
+ s = float(scale)
36
  out = []
37
  for b in boxes:
38
  nb = dict(b)
39
+ for k in ("x", "y", "z"):
40
+ nb[k] = round(b[k] * s)
41
+ for k in ("w", "h", "d"):
42
+ nb[k] = max(1, round(b[k] * s))
43
  out.append(nb)
44
  return out
45
 
46
 
47
+ def _cells(boxes: list[dict]) -> list[tuple]:
48
+ """Explode boxes into (x, y, z, color) unit cells, matching voxelsFromBoxes
49
+ (x,z = center, y = bottom)."""
50
+ out = []
51
+ for b in boxes:
52
+ cx, cy, cz = b["x"], b["y"], b["z"]
53
+ w, h, d = b["w"], b["h"], b["d"]
54
+ color = b.get("color", "#caa06f")
55
+ for ix in range(w):
56
+ for iy in range(h):
57
+ for iz in range(d):
58
+ out.append((round(cx + ix - (w - 1) / 2), cy + iy,
59
+ round(cz + iz - (d - 1) / 2), color))
60
+ return out
61
+
62
+
63
+ def _rotate(boxes: list[dict], axis: str, quarters: int) -> list[dict]:
64
+ """Rotate the part by 90° increments about its own center, on the integer
65
+ grid (exact, per-voxel). Returns 1x1x1 boxes — small parts, renders identically
66
+ through voxelsFromBoxes."""
67
+ q = quarters % 4
68
+ if q == 0:
69
+ return deepcopy(boxes)
70
+ cells = _cells(boxes)
71
+ if not cells:
72
+ return deepcopy(boxes)
73
+ cx = sum(c[0] for c in cells) / len(cells)
74
+ cy = sum(c[1] for c in cells) / len(cells)
75
+ cz = sum(c[2] for c in cells) / len(cells)
76
+ out = []
77
+ for x, y, z, color in cells:
78
+ dx, dy, dz = x - cx, y - cy, z - cz
79
+ for _ in range(q):
80
+ if axis == "x":
81
+ dy, dz = -dz, dy
82
+ elif axis == "z":
83
+ dx, dy = -dy, dx
84
+ else: # "y"
85
+ dx, dz = -dz, dx
86
+ out.append({"x": round(cx + dx), "y": round(cy + dy),
87
+ "z": round(cz + dz), "w": 1, "h": 1, "d": 1, "color": color})
88
+ return out
89
+
90
+
91
+ def _spread(n: int, spacing: int) -> list[int]:
92
+ """n integer offsets centered on 0, `spacing` apart."""
93
+ if n <= 1:
94
+ return [0]
95
+ return [round((i - (n - 1) / 2) * spacing) for i in range(n)]
96
+
97
+
98
  def _translate(boxes: list[dict], dx: int, dy: int, dz: int) -> list[dict]:
99
  return [{**b, "x": b["x"] + dx, "y": b["y"] + dy, "z": b["z"] + dz} for b in boxes]
100
 
 
118
  return (tcx, tmaxy - pminy, tcz) # "top" (and default)
119
 
120
 
121
+ def _slots(anchor: str, count: int, tgt, part) -> list[tuple]:
122
+ """Placement slots for `count` instances: (slot_anchor, dx, dy, dz tangent shift).
123
+
124
+ Rule (user-chosen): symmetric pairs first, overflow to the rear. Side anchors
125
+ (left/right/top/bottom) fan along z (front-back) up to what the target depth
126
+ holds, then spill onto the rear fanned along x. Front/rear anchors fan along x.
127
+ """
128
+ if count <= 1:
129
+ return [(anchor, 0, 0, 0)]
130
+ tminx, tmaxx, tminy, tmaxy, tminz, tmaxz = tgt
131
+ pminx, pmaxx, pminy, pmaxy, pminz, pmaxz = part
132
+ pw = max(1, pmaxx - pminx)
133
+ pd = max(1, pmaxz - pminz)
134
+ if anchor in ("front", "rear"):
135
+ return [(anchor, dx, 0, 0) for dx in _spread(count, pw + 1)]
136
+ # side anchors: fan along z, cap by target depth, overflow to rear along x
137
+ depth = max(1, tmaxz - tminz)
138
+ cap = max(1, depth // (pd + 1) + 1)
139
+ n_primary = min(count, cap)
140
+ slots = [(anchor, 0, 0, dz) for dz in _spread(n_primary, pd + 1)]
141
+ rem = count - n_primary
142
+ if rem > 0:
143
+ slots += [("rear", dx, 0, 0) for dx in _spread(rem, pw + 1)]
144
+ return slots
145
+
146
+
147
  def assemble_part(boxes: list[dict], part_id: str, anchor: str,
148
+ scale: float = 1, color: str | None = None,
149
+ count: int = 1, rotation: tuple | None = None) -> list[dict]:
150
+ """Return boxes + the placed part(s). Unknown part_id (or empty boxes) → unchanged.
151
+
152
+ scale: float multiplier (rounded to grid). count>1 distributes instances
153
+ (symmetric pairs first, overflow rear). rotation: (axis, quarter_turns) for an
154
+ exact 90° integer-grid rotation. See the keyword-parametric-edit plan."""
155
  part = PARTS.get(part_id)
156
  if part is None or not boxes:
157
  return boxes
158
  if anchor not in ANCHORS:
159
  anchor = part["default_anchor"]
160
+ local = _scaled(part["boxes"], scale or part.get("default_scale", 1))
161
  if part.get("symmetric"):
162
  local = local + _mirror_x(local)
163
+ if rotation:
164
+ local = _rotate(local, rotation[0], int(rotation[1]))
165
  if color:
166
+ local = [{**b, "color": color} for b in local]
167
+ local_bb = bbox(local)
168
+ placed: list[dict] = []
169
+ for slot_anchor, sx, sy, sz in _slots(anchor, max(1, int(count)), bbox(boxes), local_bb):
170
+ dx, dy, dz = _offset_for_anchor(slot_anchor, bbox(boxes), local_bb)
171
+ placed += _translate(local, dx + sx, dy + sy, dz + sz)
172
  return list(boxes) + repair_boxes(placed)
src/buddy_fusion/edit_parser.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """English keyword -> parametric placement spec for the edit path. No model.
2
+
3
+ Replaces the small-model selector: the edit path is pure Python, instant, and
4
+ deterministic. An instruction is parsed into which catalog part to add, how many,
5
+ how big, where, whether to rotate, and what color; assembler.assemble_part turns
6
+ that into geometry. English-only by design (see CLAUDE.md / wiki).
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from dataclasses import dataclass
12
+
13
+ from .parts import PARTS, ANCHORS
14
+ from .fallback import _COLOR_WORDS, _COLOR_HEX
15
+
16
+ # Count words. Digits are matched separately. Articles count as 1.
17
+ _NUM = {"a": 1, "an": 1, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5,
18
+ "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10}
19
+
20
+ # Size adjective -> float scale (cube size constant; the block grows).
21
+ _SIZE = {"tiny": 0.5, "teeny": 0.5, "mini": 0.6, "small": 0.6, "little": 0.6,
22
+ "big": 1.5, "large": 1.5, "bigger": 1.5,
23
+ "huge": 2.0, "giant": 2.0, "massive": 2.0, "enormous": 2.0}
24
+
25
+ # Position word -> anchor override. Single tokens, matched on word boundaries
26
+ # (so "back" never fires inside "backpack").
27
+ _ANCHOR = {"behind": "rear", "back": "rear", "rear": "rear",
28
+ "front": "front", "forward": "front", "ahead": "front",
29
+ "top": "top", "above": "top", "head": "top", "atop": "top",
30
+ "under": "bottom", "below": "bottom", "beneath": "bottom", "bottom": "bottom",
31
+ "left": "left", "right": "right"}
32
+
33
+ # Rotation phrases -> (axis, quarter_turns). Checked as substrings, longest first.
34
+ _ROT = [(("upside down", "upside-down", "inverted"), ("x", 2)),
35
+ (("sideways", "on its side", "tilted"), ("z", 1)),
36
+ (("rotated", "turned", "spun"), ("y", 1))]
37
+
38
+ # Tokens that carry no part identity (articles, sizes, verbs, generic nouns).
39
+ _STOP = {"a", "an", "the", "of", "with", "and", "to", "its", "it", "on", "in",
40
+ "add", "give", "put", "make", "please", "some", "pair", "set",
41
+ "big", "small", "tiny", "huge", "giant", "little", "large"}
42
+
43
+
44
+ def _norm(tok: str) -> str:
45
+ """Crude singular: strip a trailing plural 's' so wings/wing, ears/ear match."""
46
+ return tok[:-1] if len(tok) > 3 and tok.endswith("s") else tok
47
+
48
+
49
+ def _toks(s: str) -> list[str]:
50
+ return [_norm(w) for w in re.findall(r"[a-z]+", s.lower())]
51
+
52
+
53
+ _PART_IDTOKS = {pid: set(_toks(pid.replace("_", " "))) for pid in PARTS}
54
+ _PART_DESCTOKS = {pid: (set(_toks(p["desc"])) - _STOP) for pid, p in PARTS.items()}
55
+
56
+
57
+ def match_part(text: str) -> str | None:
58
+ """Best catalog part for an instruction, or None. Ranks by id-token overlap
59
+ (primary), then generic-id tie-break (fewer id tokens wins, so "wing" -> the
60
+ generic `wings` not `wing_bat`), then desc-token overlap."""
61
+ tt = set(_toks(text)) - _STOP
62
+ if not tt:
63
+ return None
64
+ best = None
65
+ best_key = None
66
+ for pid in PARTS:
67
+ ih = len(_PART_IDTOKS[pid] & tt)
68
+ dh = len(_PART_DESCTOKS[pid] & tt)
69
+ if ih == 0 and dh == 0:
70
+ continue
71
+ key = (ih, -len(_PART_IDTOKS[pid]), dh)
72
+ if best_key is None or key > best_key:
73
+ best_key = key
74
+ best = pid
75
+ return best
76
+
77
+
78
+ @dataclass(frozen=True)
79
+ class PlacementSpec:
80
+ part: str
81
+ anchor: str
82
+ scale: float
83
+ count: int
84
+ rotation: tuple | None
85
+ color: str | None
86
+
87
+
88
+ def parse_edit(instruction: str) -> PlacementSpec | None:
89
+ """Parse an English instruction into a PlacementSpec, or None if no catalog
90
+ part is recognised (the caller then falls back to the generative model)."""
91
+ t = (instruction or "").lower()
92
+ part = match_part(t)
93
+ if part is None:
94
+ return None
95
+
96
+ # count: explicit digit wins, else a number word, else 1. Clamp 1..8.
97
+ count = 1
98
+ m = re.search(r"\b(\d+)\b", t)
99
+ if m:
100
+ count = int(m.group(1))
101
+ else:
102
+ for w, n in _NUM.items():
103
+ if w in ("a", "an", "one"):
104
+ continue # articles don't signal a real multi-count
105
+ if re.search(rf"\b{w}\b", t):
106
+ count = n
107
+ break
108
+ count = max(1, min(8, count))
109
+
110
+ scale = 1.0
111
+ for w, s in _SIZE.items():
112
+ if re.search(rf"\b{w}\b", t):
113
+ scale = s
114
+ break
115
+
116
+ anchor = PARTS[part]["default_anchor"]
117
+ for w, a in _ANCHOR.items():
118
+ if re.search(rf"\b{w}\b", t):
119
+ anchor = a
120
+ break
121
+
122
+ rotation = None
123
+ for phrases, rot in _ROT:
124
+ if any(p in t for p in phrases):
125
+ rotation = rot
126
+ break
127
+
128
+ color = None
129
+ for col, words in _COLOR_WORDS.items():
130
+ if any(w in t for w in words):
131
+ color = _COLOR_HEX[col]
132
+ break
133
+
134
+ if anchor not in ANCHORS:
135
+ anchor = PARTS[part]["default_anchor"]
136
+ return PlacementSpec(part=part, anchor=anchor, scale=scale,
137
+ count=count, rotation=rotation, color=color)
src/buddy_fusion/prompts.py CHANGED
@@ -201,36 +201,3 @@ def build_genome_command_messages(genome: dict, transcript: str) -> list[dict]:
201
  payload = {"genome": genome, "instruction": transcript}
202
  return [{"role": "system", "content": sys_p},
203
  {"role": "user", "content": json.dumps(payload, ensure_ascii=False)}]
204
-
205
-
206
- # --- Template-assembly edit: pick a catalog part + anchor (NOT freeform geometry).
207
- from .parts import ANCHORS as _ANCHORS, part_ids as _part_ids, catalog_text as _catalog_text
208
-
209
- SELECT_SCHEMA = {
210
- "type": "object",
211
- "properties": {
212
- "part": {"type": "string", "enum": _part_ids()},
213
- "anchor": {"type": "string", "enum": list(_ANCHORS)},
214
- "scale": {"type": "integer"},
215
- "color": {"type": "string"},
216
- },
217
- "required": ["part", "anchor"],
218
- }
219
-
220
-
221
- def build_select_messages(instruction: str, boxes: list[dict]) -> list[dict]:
222
- """Ask a small model to map a free-text edit to ONE catalog part + anchor.
223
- English only. Grammar enforcement (SELECT_SCHEMA) constrains output to the JSON
224
- object from the first token, which also suppresses any reasoning/think tokens."""
225
- sys_p = (
226
- "Pick the single best part to ADD to a blocky voxel creature for the user's "
227
- "request, and where to attach it. Choose `part` from this catalog only:\n"
228
- + _catalog_text()
229
- + "\nChoose `anchor` from: " + ", ".join(_ANCHORS)
230
- + " (top/bottom/front/rear=behind/left/right). Optionally set integer `scale` "
231
- "1-3 and a #RRGGBB `color`. Output JSON only: "
232
- "{\"part\": str, \"anchor\": str, \"scale\": int, \"color\": str}."
233
- )
234
- payload = "REQUEST:\n" + (instruction or "")
235
- return [{"role": "system", "content": sys_p},
236
- {"role": "user", "content": payload}]
 
201
  payload = {"genome": genome, "instruction": transcript}
202
  return [{"role": "system", "content": sys_p},
203
  {"role": "user", "content": json.dumps(payload, ensure_ascii=False)}]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/buddy_fusion/runtime.py CHANGED
@@ -43,21 +43,11 @@ DEFAULT_FALLBACK_MODEL_FILE = "SmolLM2-1.7B-Instruct-Q4_K_M.gguf"
43
  FREEFORM_MODEL_REPO = os.getenv("BUDDY_FREEFORM_MODEL_REPO", "unsloth/gemma-4-12b-it-GGUF")
44
  FREEFORM_MODEL_FILE = os.getenv("BUDDY_FREEFORM_MODEL_FILE", "gemma-4-12b-it-Q4_K_M.gguf")
45
 
46
- # Selector for the template-assembly edit path: it only PICKS a catalog part +
47
- # anchor (tiny structured output), never draws geometry. Default to the in-stack
48
- # Qwen2.5-3B (verified on the Space's llama-cpp-python 0.3.19). To try a different
49
- # small model (e.g. MiniCPM5-1B) set BUDDY_SELECTOR_MODEL_REPO / _FILE on the Space
50
- # — _selector_preflight() logs whether it loads. See
51
- # docs/superpowers/specs/2026-06-15-template-part-assembly-edit-design.md.
52
- SELECTOR_MODEL_REPO = os.getenv("BUDDY_SELECTOR_MODEL_REPO", "openbmb/MiniCPM5-1B-GGUF")
53
- SELECTOR_MODEL_FILE = os.getenv("BUDDY_SELECTOR_MODEL_FILE", "MiniCPM5-1B-Q4_K_M.gguf")
54
-
55
- # The selector model actually in use this container. Starts as the configured
56
- # model; if it fails to load (e.g. MiniCPM5-1B's chat template throws on the
57
- # Space-pinned llama-cpp-python 0.3.19), select_part switches this to the known-good
58
- # Qwen2.5-3B for the rest of the container so edits stay fast instead of retrying
59
- # the broken model every call.
60
- _active_selector: tuple[str, str] | None = None
61
 
62
 
63
  def _blocking_completion(
@@ -199,19 +189,20 @@ class FakeBuddyRuntime:
199
  return {"name": name, "archetype": "chick", "parts": []}, boxes, self._STATUS
200
 
201
  def edit_creature(self, genome: dict, boxes: list[dict], instruction: str) -> tuple[dict, list[dict], list[str], RuntimeStatus]:
202
- # Fake runtime has no model: keyword-match the instruction to a catalog
203
- # part so local UI testing exercises the whole catalog (not just horns).
 
 
204
  from .assembler import assemble_part
205
  from .parts import PARTS
 
206
  from .fallback import suggest_tweaks_fallback
207
- t = (instruction or "").lower()
208
- words = {"horn": "horns", "wing": "wings", "tail": "tail", "ear": "ears",
209
- "house": "house", "hut": "house", "hat": "hat", "cap": "hat",
210
- "crown": "crown"}
211
- pick = next((p for p in PARTS if p in t), None)
212
- if pick is None:
213
- pick = next((pid for w, pid in words.items() if w in t), "horns")
214
- nb = assemble_part(boxes, pick, PARTS[pick]["default_anchor"], 1, None)
215
  return genome, nb, suggest_tweaks_fallback(nb), self._STATUS
216
 
217
  def suggest_tweaks(self, boxes: list[dict]) -> list[str]:
@@ -348,55 +339,24 @@ class LlamaCppBuddyRuntime:
348
  pass
349
  return {"name": name, "archetype": "chick", "parts": []}, fb_boxes, RuntimeStatus("Used a reference template", used_fallback=True)
350
 
351
- def select_part(self, instruction: str, boxes: list[dict]) -> dict | None:
352
- """Map a free-text edit to {part, anchor, scale, color} via the small selector
353
- model. Grammar-enforced (which also suppresses thinking). Returns None on
354
- failure — the caller falls back. The configured model is tried first; on a
355
- load/run failure it logs and switches the container to Qwen2.5-3B (retried
356
- immediately so this edit still lands fast), never crashing the edit."""
357
- global _active_selector
358
- from .prompts import build_select_messages, SELECT_SCHEMA
359
- if _active_selector is None:
360
- _active_selector = (SELECTOR_MODEL_REPO, SELECTOR_MODEL_FILE)
361
-
362
- def _run(repo: str, file: str) -> dict | None:
363
- return self._chat_json(
364
- build_select_messages(instruction, boxes), SELECT_SCHEMA,
365
- max_tokens=int(os.environ.get("BUDDY_SELECT_MAX_TOKENS", "64")),
366
- temperature=0.0, model_repo=repo, model_file=file,
367
- )
368
-
369
- repo, file = _active_selector
370
- try:
371
- return _run(repo, file)
372
- except Exception as exc: # noqa: BLE001 - log, never crash the edit
373
- print(f"[selector] failed ({repo}): {exc}", flush=True)
374
- if (repo, file) != (DEFAULT_MODEL_REPO, DEFAULT_MODEL_FILE):
375
- print(f"[selector] switching to {DEFAULT_MODEL_REPO} for the rest of "
376
- "this container", flush=True)
377
- _active_selector = (DEFAULT_MODEL_REPO, DEFAULT_MODEL_FILE)
378
- try:
379
- return _run(DEFAULT_MODEL_REPO, DEFAULT_MODEL_FILE)
380
- except Exception as exc2: # noqa: BLE001
381
- print(f"[selector] Qwen fallback also failed: {exc2}", flush=True)
382
- return None
383
-
384
  def edit_creature(self, genome: dict, boxes: list[dict], instruction: str) -> tuple[dict, list[dict], list[str], RuntimeStatus]:
385
- # Fast path: pick a catalog part with the small selector + snap it on
386
- # deterministically. Off-catalog / transform / selector miss falls through
387
- # to the freeform Gemma edit below (the slow, flexible safety valve).
 
 
388
  from .assembler import assemble_part
389
- from .parts import PARTS
390
  from .fallback import suggest_tweaks_fallback
391
- sel = self.select_part(instruction, boxes)
392
- if isinstance(sel, dict) and sel.get("part") in PARTS:
393
- print(f"[selector] picked part={sel['part']} anchor={sel.get('anchor')} "
394
- f"scale={sel.get('scale')}", flush=True)
395
- new_boxes = assemble_part(boxes, sel["part"], sel.get("anchor", ""),
396
- int(sel.get("scale") or 1), sel.get("color"))
397
  if new_boxes and new_boxes != boxes:
398
  return (genome, new_boxes, suggest_tweaks_fallback(new_boxes),
399
- RuntimeStatus("Generated by the local model"))
400
  return self._freeform_edit_creature(genome, boxes, instruction)
401
 
402
  def _freeform_edit_creature(self, genome: dict, boxes: list[dict], instruction: str) -> tuple[dict, list[dict], list[str], RuntimeStatus]:
@@ -556,30 +516,11 @@ def warmup() -> None:
556
  )
557
  if os.getenv("BUDDY_GRAMMAR_BENCH") == "1":
558
  _grammar_bench(cfg, model_path)
559
- if os.getenv("BUDDY_SELECTOR_PREFLIGHT") == "1":
560
- _selector_preflight()
561
  except Exception as exc: # noqa: BLE001 - warmup is best-effort
562
  _warmed = False # allow a retry on the next page load
563
  print(f"[zerogpu-warmup] failed: {exc}", flush=True)
564
 
565
 
566
- def _selector_preflight() -> None:
567
- """Gated by BUDDY_SELECTOR_PREFLIGHT=1. Loads the configured selector model and
568
- runs one sample selection, printing exactly one result line so a 0.3.19
569
- chat-template load failure is visible (vs silently swallowed into fallback)."""
570
- sample = [{"x": 0, "y": 0, "z": 0, "w": 4, "h": 3, "d": 4, "color": "#caa06f"}]
571
- try:
572
- sel = LlamaCppBuddyRuntime().select_part("add a small house behind it", sample)
573
- if isinstance(sel, dict) and sel.get("part"):
574
- print(f"[selector-preflight] ok model={SELECTOR_MODEL_REPO} "
575
- f"part={sel.get('part')} anchor={sel.get('anchor')}", flush=True)
576
- else:
577
- print(f"[selector-preflight] FAILED: model={SELECTOR_MODEL_REPO} "
578
- f"returned {sel!r}", flush=True)
579
- except Exception as exc: # noqa: BLE001 - diagnostic only
580
- print(f"[selector-preflight] FAILED: {type(exc).__name__}: {exc}", flush=True)
581
-
582
-
583
  def _grammar_bench(cfg: "LlamaRuntimeConfig", model_path: str) -> None:
584
  """One-off diagnostic: run the freeform prompt UNCONSTRAINED (no GBNF grammar)
585
  to isolate how much grammar-constrained sampling costs vs raw 12B decode.
 
43
  FREEFORM_MODEL_REPO = os.getenv("BUDDY_FREEFORM_MODEL_REPO", "unsloth/gemma-4-12b-it-GGUF")
44
  FREEFORM_MODEL_FILE = os.getenv("BUDDY_FREEFORM_MODEL_FILE", "gemma-4-12b-it-Q4_K_M.gguf")
45
 
46
+ # The edit path no longer uses a model: an English keyword parser
47
+ # (edit_parser.parse_edit) maps the instruction to a catalog part + parameters
48
+ # and the assembler snaps it on deterministically — instant, no GPU. The
49
+ # generative model below is reserved for full generation + hatch fusion, and for
50
+ # the freeform-edit safety valve when no catalog part matches.
 
 
 
 
 
 
 
 
 
 
51
 
52
 
53
  def _blocking_completion(
 
189
  return {"name": name, "archetype": "chick", "parts": []}, boxes, self._STATUS
190
 
191
  def edit_creature(self, genome: dict, boxes: list[dict], instruction: str) -> tuple[dict, list[dict], list[str], RuntimeStatus]:
192
+ # Same model-free edit path as the real runtime: the keyword parser maps
193
+ # the instruction to a catalog part + parameters, the assembler snaps it
194
+ # on. An unmatched instruction defaults to horns so local UI testing
195
+ # always produces a visible change.
196
  from .assembler import assemble_part
197
  from .parts import PARTS
198
+ from .edit_parser import parse_edit
199
  from .fallback import suggest_tweaks_fallback
200
+ spec = parse_edit(instruction)
201
+ if spec is not None:
202
+ nb = assemble_part(boxes, spec.part, spec.anchor, spec.scale,
203
+ spec.color, spec.count, spec.rotation)
204
+ else:
205
+ nb = assemble_part(boxes, "horns", PARTS["horns"]["default_anchor"])
 
 
206
  return genome, nb, suggest_tweaks_fallback(nb), self._STATUS
207
 
208
  def suggest_tweaks(self, boxes: list[dict]) -> list[str]:
 
339
  pass
340
  return {"name": name, "archetype": "chick", "parts": []}, fb_boxes, RuntimeStatus("Used a reference template", used_fallback=True)
341
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
342
  def edit_creature(self, genome: dict, boxes: list[dict], instruction: str) -> tuple[dict, list[dict], list[str], RuntimeStatus]:
343
+ # Fast path: an English keyword parser maps the instruction to a catalog
344
+ # part + parameters (count / scale / anchor / rotation / color) and the
345
+ # assembler snaps it on deterministically. No model — instant. Only an
346
+ # instruction that matches no catalog part falls through to the freeform
347
+ # Gemma edit below (the slow, flexible safety valve).
348
  from .assembler import assemble_part
349
+ from .edit_parser import parse_edit
350
  from .fallback import suggest_tweaks_fallback
351
+ spec = parse_edit(instruction)
352
+ if spec is not None:
353
+ print(f"[edit] part={spec.part} anchor={spec.anchor} count={spec.count} "
354
+ f"scale={spec.scale} rot={spec.rotation}", flush=True)
355
+ new_boxes = assemble_part(boxes, spec.part, spec.anchor, spec.scale,
356
+ spec.color, spec.count, spec.rotation)
357
  if new_boxes and new_boxes != boxes:
358
  return (genome, new_boxes, suggest_tweaks_fallback(new_boxes),
359
+ RuntimeStatus("Built from the part catalog"))
360
  return self._freeform_edit_creature(genome, boxes, instruction)
361
 
362
  def _freeform_edit_creature(self, genome: dict, boxes: list[dict], instruction: str) -> tuple[dict, list[dict], list[str], RuntimeStatus]:
 
516
  )
517
  if os.getenv("BUDDY_GRAMMAR_BENCH") == "1":
518
  _grammar_bench(cfg, model_path)
 
 
519
  except Exception as exc: # noqa: BLE001 - warmup is best-effort
520
  _warmed = False # allow a retry on the next page load
521
  print(f"[zerogpu-warmup] failed: {exc}", flush=True)
522
 
523
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
524
  def _grammar_bench(cfg: "LlamaRuntimeConfig", model_path: str) -> None:
525
  """One-off diagnostic: run the freeform prompt UNCONSTRAINED (no GBNF grammar)
526
  to isolate how much grammar-constrained sampling costs vs raw 12B decode.
tests/test_assembler.py CHANGED
@@ -44,3 +44,25 @@ def test_color_override_recolors_added_boxes():
44
 
45
  def test_unknown_part_returns_original_unchanged():
46
  assert assemble_part(CUBE, "nope", "top", 1, None) == CUBE
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
  def test_unknown_part_returns_original_unchanged():
46
  assert assemble_part(CUBE, "nope", "top", 1, None) == CUBE
47
+
48
+
49
+ def _cell_count(boxes):
50
+ return sum(b["w"] * b["h"] * b["d"] for b in boxes)
51
+
52
+
53
+ def test_float_scale_grows_cell_count():
54
+ one = assemble_part(CUBE, "house", "rear", 1.0, None)[len(CUBE):]
55
+ big = assemble_part(CUBE, "house", "rear", 1.5, None)[len(CUBE):]
56
+ assert _cell_count(big) > _cell_count(one)
57
+
58
+
59
+ def test_count_distributes_more_instances():
60
+ one = assemble_part(CUBE, "tail", "rear", 1, None, count=1)[len(CUBE):]
61
+ three = assemble_part(CUBE, "tail", "rear", 1, None, count=3)[len(CUBE):]
62
+ assert _cell_count(three) > _cell_count(one) * 2 # roughly 3x the geometry
63
+
64
+
65
+ def test_rotation_preserves_cell_count():
66
+ base = assemble_part(CUBE, "horns", "top", 1, None)[len(CUBE):]
67
+ rot = assemble_part(CUBE, "horns", "top", 1, None, rotation=("y", 1))[len(CUBE):]
68
+ assert _cell_count(rot) == _cell_count(base) # rotation moves cells, never drops them
tests/test_edit_parser.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from buddy_fusion.edit_parser import parse_edit, match_part
2
+
3
+
4
+ def test_generic_noun_picks_generic_part():
5
+ assert match_part("give it wings") == "wings"
6
+ assert match_part("add a tail") == "tail"
7
+ assert match_part("add horns") == "horns"
8
+
9
+
10
+ def test_specific_phrase_beats_generic():
11
+ assert match_part("add bat wings") == "wing_bat"
12
+ assert match_part("a bushy fox tail") == "tail_fox"
13
+ assert match_part("put a wizard hat on it") == "wizard_hat"
14
+
15
+
16
+ def test_no_match_returns_none():
17
+ assert match_part("asdfghjkl zzz") is None
18
+ assert parse_edit("asdfghjkl zzz") is None
19
+
20
+
21
+ def test_count_from_number_word_and_digit():
22
+ assert parse_edit("add five arms").count == 5
23
+ assert parse_edit("give it 3 horns").count == 3
24
+ assert parse_edit("add a tail").count == 1 # article is not a multi-count
25
+
26
+
27
+ def test_scale_from_size_adjective():
28
+ assert parse_edit("add big wings").scale == 1.5
29
+ assert parse_edit("a huge tail").scale == 2.0
30
+ assert parse_edit("tiny ears").scale == 0.5
31
+ assert parse_edit("add wings").scale == 1.0
32
+
33
+
34
+ def test_anchor_override():
35
+ assert parse_edit("add a house behind it").anchor == "rear"
36
+ assert parse_edit("put a hat on top").anchor == "top"
37
+ assert parse_edit("wings under it").anchor == "bottom"
38
+
39
+
40
+ def test_anchor_word_does_not_fire_inside_part_name():
41
+ # "backpack" contains "back" but must not be parsed as a rear anchor cue
42
+ spec = parse_edit("add a backpack")
43
+ assert spec.part == "backpack"
44
+
45
+
46
+ def test_rotation_keyword():
47
+ assert parse_edit("add horns upside down").rotation == ("x", 2)
48
+ assert parse_edit("a tail sideways").rotation == ("z", 1)
49
+ assert parse_edit("add wings").rotation is None
50
+
51
+
52
+ def test_color_override():
53
+ assert parse_edit("add red horns").color == "#ef4444"
54
+ assert parse_edit("add horns").color is None
55
+
56
+
57
+ def test_combined_instruction():
58
+ spec = parse_edit("add five big bat wings behind it")
59
+ assert spec.part == "wing_bat"
60
+ assert spec.count == 5
61
+ assert spec.scale == 1.5
62
+ assert spec.anchor == "rear"
tests/test_select_routing.py CHANGED
@@ -1,24 +1,7 @@
1
- from buddy_fusion.prompts import SELECT_SCHEMA, build_select_messages
2
- from buddy_fusion.parts import part_ids
3
  from buddy_fusion.runtime import FakeBuddyRuntime
4
 
5
 
6
- def test_select_schema_shape():
7
- props = SELECT_SCHEMA["properties"]
8
- assert props["part"]["enum"] == part_ids()
9
- assert set(SELECT_SCHEMA["required"]) >= {"part", "anchor"}
10
-
11
-
12
- def test_build_select_messages_includes_catalog_and_instruction():
13
- msgs = build_select_messages(
14
- "add a house behind it",
15
- [{"x": 0, "y": 0, "z": 0, "w": 2, "h": 2, "d": 2, "color": "#888"}],
16
- )
17
- blob = " ".join(m["content"] for m in msgs)
18
- assert "house" in blob and "add a house behind it" in blob
19
-
20
-
21
- def test_fake_runtime_select_part_returns_catalog_pick():
22
  g, boxes, tweaks, status = FakeBuddyRuntime().edit_creature(
23
  {"name": "x"},
24
  [{"x": 0, "y": 0, "z": 0, "w": 2, "h": 2, "d": 2, "color": "#888"}],
@@ -26,3 +9,11 @@ def test_fake_runtime_select_part_returns_catalog_pick():
26
  )
27
  assert len(boxes) >= 1
28
  assert len(tweaks) == 4
 
 
 
 
 
 
 
 
 
 
 
1
  from buddy_fusion.runtime import FakeBuddyRuntime
2
 
3
 
4
+ def test_fake_runtime_edit_returns_catalog_pick():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  g, boxes, tweaks, status = FakeBuddyRuntime().edit_creature(
6
  {"name": "x"},
7
  [{"x": 0, "y": 0, "z": 0, "w": 2, "h": 2, "d": 2, "color": "#888"}],
 
9
  )
10
  assert len(boxes) >= 1
11
  assert len(tweaks) == 4
12
+
13
+
14
+ def test_fake_runtime_unmatched_still_changes():
15
+ base = [{"x": 0, "y": 0, "z": 0, "w": 2, "h": 2, "d": 2, "color": "#888"}]
16
+ g, boxes, tweaks, status = FakeBuddyRuntime().edit_creature(
17
+ {"name": "x"}, base, "asdfghjkl",
18
+ )
19
+ assert len(boxes) > len(base) # defaults to horns, never a no-op