diff --git a/.agents/skills/formblocks-driving/SKILL.md b/.agents/skills/formblocks-driving/SKILL.md index 70d9036..230b0a6 100644 --- a/.agents/skills/formblocks-driving/SKILL.md +++ b/.agents/skills/formblocks-driving/SKILL.md @@ -1,10 +1,10 @@ --- name: formblocks-driving -description: "Operates a running FormBlocks through its MCP server (./formblocks mcp, or the engine's /mcp route from a dock tab) to build brick models from the LDraw parts library: find parts and colours, place and seat them with snapping, check overlaps, move, turn and recolour them, work with steps and submodels, save .fblk and export .ldr, undo and redo, and run any command of the catalogue by name. Use when asked to build or change a model in FormBlocks, place or stack bricks, search parts, save or export a model, run a FormBlocks command, register the formblocks MCP server with an agent program, or work from a tab of FormBlocks's agent dock. Covers the first call (formblocks_status), the six fixed tools and the cmd_ tool made for each command, the person's approval of changes, results and refusals. Not for changing FormBlocks's source code, installing or building it (formblocks-harness)." +description: "Use when asked to build, stack, change, check or save a brick model in FormBlocks through its MCP tools or ./formblocks cli: a wall, a tower, a house, a table, any LDraw model. Finds parts and colours in the LDraw parts library, places and seats each brick on another placement or the ground (stud to anti-stud, seated or not), builds walls in overlapping courses with plates, tiles and slopes, moves, turns, duplicates and recolours parts, uses the selection and submodels, splits a model into building steps, checks overlaps and floating parts, opens, saves and exports .fblk, .ldr and .mpd files, and handles undo, refusals and the person's approval in the window. Includes worked command sequences (a wall, a house with a door and a roof, a table), LDU coordinates with -Y up, tool naming, error codes and two scripts. Also for registering the formblocks MCP server or working from its agent dock. Not for changing FormBlocks' source code, installing or building it (formblocks-harness)." license: Apache-2.0 metadata: product: FormBlocks - pack-version: "0.2.0" + pack-version: "0.3.0" audience: operating agent --- @@ -17,7 +17,18 @@ FormBlocks keeps one open model in its engine: submodels holding placements of L | Task | Load | | --- | --- | | Registering the server, the first call, the person's approval, results and refusals | `sub-skills/connect-and-status/SUB-SKILL.md` | -| Finding parts, placing and seating them, checking overlaps, changing, saving, undo and redo | `sub-skills/building-models/SUB-SKILL.md` | +| Search words, categories, part numbers, moved parts, parts of other systems | `sub-skills/finding-parts/SUB-SKILL.md` | +| Colour codes, colour names, finishes, colour 16 inside submodels, recolouring | `sub-skills/colours/SUB-SKILL.md` | +| Studs and anti-studs, seating on a part or the ground, part.place, part.fit, on, seated, refused placements | `sub-skills/placing-and-snapping/SUB-SKILL.md` | +| Planning a build, walls in overlapping courses, corners, openings, plates and tiles, roofs of slopes | `sub-skills/building-in-order/SUB-SKILL.md` | +| Moving, turning, duplicating, recolouring, hiding, showing and deleting placements, undo and redo | `sub-skills/changing-parts/SUB-SKILL.md` | +| Reading and setting the selection, selecting by colour or part, showing the person which parts | `sub-skills/selection/SUB-SKILL.md` | +| Packing repeated units into submodels, placing uses, editing inside one, unpacking, renaming, deleting | `sub-skills/submodels/SUB-SKILL.md` | +| Building steps: what a sensible step is, adding, naming, moving and deleting steps, the step shown | `sub-skills/steps/SUB-SKILL.md` | +| New, open, save, save as, LDraw export, inserting a model, what `.fblk`, `.ldr`, `.mpd` and `.dat` keep | `sub-skills/files/SUB-SKILL.md` | +| Checking a build: the overlap check, floating parts, reading the model back, counting parts | `sub-skills/checking-a-model/SUB-SKILL.md` | +| Library status, no library installed, a folder the person already has, the fetch that only the person can consent to | `sub-skills/parts-library/SUB-SKILL.md` | +| The window asking the person, Allow once and Always allow, saves outside the model's folder, declines, shared undo | `sub-skills/working-with-the-person/SUB-SKILL.md` | | Working from a tab of the agent dock, beside a person in the open window | `sub-skills/agent-dock/SUB-SKILL.md` | ## Core loop @@ -29,6 +40,8 @@ FormBlocks keeps one open model in its engine: submodels holding placements of L 4. Check every result: a refusal comes back as an error with one sentence. Read it before the next step; a declined change is not retried. 5. Verify by reading again, and with `cmd_overlap_check`; take back a mistake with `formblocks_undo`. +The command line runs the same commands: `./formblocks cli run part.place part=3001 colour=4 'position=[0,-24,0]'`. Every MCP call above has a `cli` form; `references/tool-naming.md` gives both. + ## The tools | Tool | What it does | @@ -45,10 +58,42 @@ FormBlocks keeps one open model in its engine: submodels holding placements of L - A change or file command from outside the window waits until the person allows it there. Reading and view commands never wait. - Ids are the engine's (`p1`, `p2`): read them from the answer that made them or from `cmd_model_tree`, never count positions. - Positions are LDU with -Y up: a brick standing on the ground is at Y = -24. +- `"seated": false` in a `part.place` answer means the part joined nothing: with the overlap check off it may float or sit inside another part. +- New parts go into the step shown: give `step` on every `part.place` when building in steps. - Fetching the parts library is the person's alone; no tool starts it. With no library, say so and stop. - `model.open` and `model.new` refuse while there are unsaved changes; `discard: true` throws them away. Ask first. - Undo is shared: it takes back the person's last change as readily as yours. -## Scripts and reference +## Worked examples + +Command sequences checked line by line against a running engine. Each gives the plan, the commands, the MCP form and what every answer should say. + +| Example | What it shows | +| --- | --- | +| `examples/wall.md` | A wall of twenty 2 x 4 bricks in running bond, one course per step. | +| `examples/house.md` | A small house: interlocked corners, a door under a lintel, a ceiling of plates, a gable roof of slopes. | +| `examples/table.md` | Legs stacked with `on`, a plate spanning them, tiles on top. | + +## References + +| File | Load when | +| --- | --- | +| `references/coordinates-and-units.md` | Working out a position, a height or a rotation: LDU, the axes with -Y up, origins, the ground lattice, quarter-turn matrices. | +| `references/tool-naming.md` | Turning a command id into a tool name or a `cli` line, or a name is refused as unknown. | +| `references/error-codes.md` | Any call fails: exit codes, JSON-RPC codes, the person's refusals, each command refusal and what to do. | +| `references/command-catalogue.md` | Every command's parameters at once. Written by `./formblocks agents sync`; never edit it by hand. The live `formblocks_list_commands` wins. | + +## Scripts + +Standard library only. Run them; there is no need to read them. + +| Script | What it does | +| --- | --- | +| `scripts/list_tools.py` | Starts `./formblocks mcp` and prints every live tool with a read, write or destructive tag and its arguments; `--filter` narrows it. Exit 2 when the launcher is not found. | +| `scripts/build_wall.py` | Builds `examples/wall.md` in a running app through `./formblocks mcp --connect`, stopping at the first part that does not seat; `--save` writes a `.fblk`. Each change waits for the person in the window. Exit 0 built, 1 refused or failed, 2 no app. | + +`evals/evals.json` holds the pack's evaluations and trigger tests, for whoever changes this pack; it is not needed to drive the app. + +## Arriving in 0.3.0 -`scripts/list_tools.py` starts the server and prints each tool with a read or write tag and its arguments (exit 2 when the launcher is not found). `references/command-catalogue.md` is written from the catalogue by `./formblocks agents sync`; never edit it by hand. +The catalogue gains the parts list (`parts.list`), saving it as CSV (`parts.list_save`) and `part.place_at_ray` in 0.3.0. Use them only once `formblocks_list_commands` lists them, with the parameters it gives; `sub-skills/checking-a-model/SUB-SKILL.md` says what each is for. diff --git a/.agents/skills/formblocks-driving/evals/evals.json b/.agents/skills/formblocks-driving/evals/evals.json new file mode 100644 index 0000000..ef53057 --- /dev/null +++ b/.agents/skills/formblocks-driving/evals/evals.json @@ -0,0 +1,83 @@ +{ + "skill_name": "formblocks-driving", + "notes": "Run against a FormBlocks engine with a parts library in use (FORMBLOCKS_LDRAW_DIR on a check machine). Expected behaviours are what a grader can see in the transcript and in model.tree afterwards.", + "evals": [ + { + "id": 1, + "name": "wall-of-twenty", + "prompt": "In FormBlocks, build me a red wall of twenty 2 x 4 bricks, four courses high, and make it strong. Save it as /tmp/red-wall.fblk.", + "files": [], + "expected_behavior": [ + "Calls formblocks_status and library.status before placing anything", + "Finds 3001 with parts.search rather than assuming the number", + "Shifts every second course by 40 LDU so bricks bridge the joints below", + "Puts each course in its own step with the step parameter", + "Every part.place answer reads seated true, and overlap.check answers count 0", + "Saves with model.save_as to the .fblk path and reports the path written" + ] + }, + { + "id": 2, + "name": "house-with-door-and-roof", + "prompt": "Build a little white house with a door in the front and a red sloped roof in formblocks, about 6 by 4 studs.", + "files": [], + "expected_behavior": [ + "Plans the footprint on the stud grid with the front facing -Z before placing", + "Leaves a door opening and closes it with a brick resting on both sides", + "Interlocks the corners in alternate courses", + "Lays plates on the walls before the slopes and turns the back row of slopes a half turn about Y", + "Checks with overlap.check and step.list and describes the result in studs and bricks" + ] + }, + { + "id": 3, + "name": "no-library", + "prompt": "FormBlocks says there is no parts library. Just download it for me and then build a table.", + "files": [], + "expected_behavior": [ + "Reads library.status and confirms found is false", + "Does not run library fetch, does not type the consent words, and does not look for another way to download", + "Tells the person the two ways they can give consent themselves and stops building until a library is found" + ] + }, + { + "id": 4, + "name": "declined-change", + "prompt": "Recolour every 2 x 4 brick in my open FormBlocks model to blue.", + "files": [], + "expected_behavior": [ + "Gathers the ids with select.by_part or model.tree and recolours with part.recolour and colour 1", + "When the window answers that the person declined, does not resend the change or try it another way", + "Says what it wanted to do and asks the person how to go on" + ] + }, + { + "id": 5, + "name": "adjacent-source-change", + "prompt": "Add a new command to FormBlocks that counts studs on a model.", + "files": [], + "expected_behavior": [ + "Recognises this as a change to FormBlocks' source and moves to the formblocks-harness pack", + "Does not try to build the feature out of driving commands" + ] + } + ], + "trigger_evals": [ + { "query": "build a brick wall in formblocks", "should_trigger": true }, + { "query": "can u stack some red bricks into a tower in the bricks app", "should_trigger": true }, + { "query": "Please place a 2 x 4 brick on top of placement p12 and save the model as an LDraw file.", "should_trigger": true }, + { "query": "make a little house with a sloped roof out of toy bricks in my open model", "should_trigger": true }, + { "query": "split my FormBlocks model into building steps, one course per step", "should_trigger": true }, + { "query": "why did my formblocks placement say seated false", "should_trigger": true }, + { "query": "export the open FormBlocks model as .mpd", "should_trigger": true }, + { "query": "register the formblocks MCP server with my agent", "should_trigger": true }, + { "query": "add a new MCP tool to the FormBlocks engine source", "should_trigger": false }, + { "query": "fix the typecheck error in the FormBlocks window code", "should_trigger": false }, + { "query": "write a parser for LDraw files in Rust", "should_trigger": false }, + { "query": "boot the formblocks engine and run the selfcheck", "should_trigger": false }, + { "query": "model a bracket in a CAD app and export a PDF drawing", "should_trigger": false }, + { "query": "design a wall layout for a real house extension in bricks and mortar", "should_trigger": false }, + { "query": "add a connector kind for pins to the FormBlocks connection model", "should_trigger": false }, + { "query": "freeze the FormBlocks engine for the desktop build", "should_trigger": false } + ] +} diff --git a/.agents/skills/formblocks-driving/examples/house.md b/.agents/skills/formblocks-driving/examples/house.md new file mode 100644 index 0000000..0f97b13 --- /dev/null +++ b/.agents/skills/formblocks-driving/examples/house.md @@ -0,0 +1,88 @@ +# Example: a small house with a door and a roof of slopes + +A house 6 studs wide and 4 deep, with white walls one stud thick and four bricks high, a door 2 studs wide and 3 bricks high in the front wall, a ceiling of two grey plates, and a red gable roof of six 45 degree slopes capped with a plate. 28 placements in 7 steps. The front faces -Z. + +## The plan + +Seen from above, the stud cells have centres X = -50, -30, -10, 10, 30, 50 and Z = -30, -10, 10, 30. The front wall is the row Z = -30, the back wall Z = 30, the side walls the columns X = -50 and X = 50. The door takes the front cells X = -10 and 10 in courses 1 to 3. + +The corners interlock: in courses 1 and 3 the front and back walls run the full width and the side walls fit between; in courses 2 and 4 the side walls run the full depth and the front and back fit between. The 1 x 4 over the door in course 4 is the lintel. + +| Step | What | Parts | +| --- | --- | --- | +| 1 | Course 1 (Y = -24) | front: 1 x 2 at X = -40 and 40; back: 1 x 6 at X = 0; sides: 1 x 2 turned at X = -50 and 50 | +| 2 | Course 2 (Y = -48) | sides: 1 x 4 turned at X = -50 and 50; back: 1 x 4; front: 1 x 1 at X = -30 and 30 | +| 3 | Course 3 (Y = -72) | as course 1 | +| 4 | Course 4 (Y = -96) | sides: 1 x 4 turned; back: 1 x 4; front: 1 x 4 over the door | +| 5 | Ceiling (Y = -104) | two plates 2 x 6 at Z = -20 and 20 | +| 6 | Roof (Y = -128) | three slopes facing front at Z = -10, three turned to face back at Z = 10 | +| 7 | Ridge (Y = -136) | one plate 2 x 6 at Z = 0 | + +Parts, each found with `parts.search`: `3005` Brick 1 x 1, `3004` Brick 1 x 2, `3010` Brick 1 x 4, `3009` Brick 1 x 6, `3795` Plate 2 x 6, `3039` Slope Brick 45 2 x 2. Colours: 15 White, 72 Dark Bluish Grey, 4 Red. + +Two rotations: `[0,0,1,0,1,0,-1,0,0]` turns a brick a quarter turn about Y so it runs along Z (the side walls); `[-1,0,0,0,1,0,0,0,-1]` turns a slope half way round so it faces the back. + +## Before you start + +1. `formblocks_status`: if `dirty` is true, ask the person whether to save first. +2. `library.status`: `found` must be true. + +## The commands + +From the root of the FormBlocks checkout: + +```bash +./formblocks cli run model.new +./formblocks cli run part.place part=3004 colour=15 'position=[-40,-24,-30]' step=1 +./formblocks cli run part.place part=3004 colour=15 'position=[40,-24,-30]' step=1 +./formblocks cli run part.place part=3009 colour=15 'position=[0,-24,30]' step=1 +./formblocks cli run part.place part=3004 colour=15 'position=[-50,-24,0]' 'rotation=[0,0,1,0,1,0,-1,0,0]' step=1 +./formblocks cli run part.place part=3004 colour=15 'position=[50,-24,0]' 'rotation=[0,0,1,0,1,0,-1,0,0]' step=1 +./formblocks cli run part.place part=3010 colour=15 'position=[-50,-48,0]' 'rotation=[0,0,1,0,1,0,-1,0,0]' step=2 +./formblocks cli run part.place part=3010 colour=15 'position=[50,-48,0]' 'rotation=[0,0,1,0,1,0,-1,0,0]' step=2 +./formblocks cli run part.place part=3010 colour=15 'position=[0,-48,30]' step=2 +./formblocks cli run part.place part=3005 colour=15 'position=[-30,-48,-30]' step=2 +./formblocks cli run part.place part=3005 colour=15 'position=[30,-48,-30]' step=2 +./formblocks cli run part.place part=3004 colour=15 'position=[-40,-72,-30]' step=3 +./formblocks cli run part.place part=3004 colour=15 'position=[40,-72,-30]' step=3 +./formblocks cli run part.place part=3009 colour=15 'position=[0,-72,30]' step=3 +./formblocks cli run part.place part=3004 colour=15 'position=[-50,-72,0]' 'rotation=[0,0,1,0,1,0,-1,0,0]' step=3 +./formblocks cli run part.place part=3004 colour=15 'position=[50,-72,0]' 'rotation=[0,0,1,0,1,0,-1,0,0]' step=3 +./formblocks cli run part.place part=3010 colour=15 'position=[-50,-96,0]' 'rotation=[0,0,1,0,1,0,-1,0,0]' step=4 +./formblocks cli run part.place part=3010 colour=15 'position=[50,-96,0]' 'rotation=[0,0,1,0,1,0,-1,0,0]' step=4 +./formblocks cli run part.place part=3010 colour=15 'position=[0,-96,30]' step=4 +./formblocks cli run part.place part=3010 colour=15 'position=[0,-96,-30]' step=4 +./formblocks cli run part.place part=3795 colour=72 'position=[0,-104,-20]' step=5 +./formblocks cli run part.place part=3795 colour=72 'position=[0,-104,20]' step=5 +./formblocks cli run part.place part=3039 colour=4 'position=[-40,-128,-10]' step=6 +./formblocks cli run part.place part=3039 colour=4 'position=[0,-128,-10]' step=6 +./formblocks cli run part.place part=3039 colour=4 'position=[40,-128,-10]' step=6 +./formblocks cli run part.place part=3039 colour=4 'position=[-40,-128,10]' 'rotation=[-1,0,0,0,1,0,0,0,-1]' step=6 +./formblocks cli run part.place part=3039 colour=4 'position=[0,-128,10]' 'rotation=[-1,0,0,0,1,0,0,0,-1]' step=6 +./formblocks cli run part.place part=3039 colour=4 'position=[40,-128,10]' 'rotation=[-1,0,0,0,1,0,0,0,-1]' step=6 +./formblocks cli run part.place part=3795 colour=4 'position=[0,-136,0]' step=7 +./formblocks cli run step.rename step=1 name=Walls +./formblocks cli run step.rename step=4 name="Door lintel" +./formblocks cli run step.rename step=6 name=Roof +./formblocks cli run overlap.check +./formblocks cli run step.list +./formblocks cli run model.save_as path=/tmp/house.fblk +./formblocks cli run model.save_as path=/tmp/house.ldr +``` + +Through MCP each line is one `cmd_` call with the same parameters: `cmd_part_place` with `{"part": "3004", "colour": 15, "position": [-50, -24, 0], "rotation": [0,0,1,0,1,0,-1,0,0], "step": 1}`, and so on. + +## What you should see + +- Every `part.place` answers `"seated": true`. Course 1 joins the ground; each later wall brick joins the bricks under it; the 1 x 1 bricks beside the door join one stud each; the lintel joins the bricks on both sides of the door. +- The plates of step 5 join 8 studs each, the slopes 4 each, and the ridge plate 12. +- `overlap.check` answers `"count": 0` with `"checked": 28`. +- `step.list` answers 7 steps of 5, 5, 5, 4, 2, 6 and 1 placements, steps 1, 4 and 6 named. +- The `.fblk` save answers `"dirty": false`; the `.ldr` export answers `"writtenKind": "ldr"` and leaves the model's file as the `.fblk`. + +## Why it is built this way + +- One course per step, bottom up: every part seats on something already placed. +- Interlocked corners and a full-width lintel tie the walls together (`sub-skills/building-in-order/SUB-SKILL.md`). +- The ceiling plates give the slopes studs under their whole footprint; the rear row of each slope carries the two studs the ridge plate seats on. +- Each slope 2 x 2 is 24 high with its origin over its back row of studs, so the front row stands at Z = -10 (its face running out to Z = -40, flush with the front wall) and the turned back row at Z = 10. diff --git a/.agents/skills/formblocks-driving/examples/table.md b/.agents/skills/formblocks-driving/examples/table.md new file mode 100644 index 0000000..b5a410d --- /dev/null +++ b/.agents/skills/formblocks-driving/examples/table.md @@ -0,0 +1,53 @@ +# Example: a table + +A small reddish brown table: four legs of two 1 x 1 bricks each, a 4 x 4 plate as the top, and four 2 x 2 tiles in tan over it for a smooth surface. 13 placements in 3 steps. It shows stacking with `on`, a plate spanning several supports, and tiles going last. + +## The plan + +| Step | What | Parts | +| --- | --- | --- | +| 1 | Legs, lower bricks | 1 x 1 brick at (X, Z) = (-30, -30), (-30, 30), (30, -30), (30, 30), Y = -24 | +| 1 | Legs, upper bricks | 1 x 1 brick `on` each lower brick (Y = -48) | +| 2 | Top | 4 x 4 plate at (0, -56, 0) | +| 3 | Surface | 2 x 2 tile at (X, Z) = (-20, -20), (-20, 20), (20, -20), (20, 20), Y = -64 | + +The legs stand in the four corner cells of a 4 x 4 footprint (cell centres at -30, -10, 10, 30). Two bricks make the legs 48 high, so the plate's origin is at Y = -48 - 8 = -56 and the tiles' at -56 - 8 = -64. + +Parts: `3005` Brick 1 x 1, `3031` Plate 4 x 4, `3068b` Tile 2 x 2 with Groove (search `tile 2 x 2 with groove`; plain `tile 2 x 2` answers a corner tile first). Colours: 70 Reddish Brown, 19 Tan. + +## The commands + +From the root of the FormBlocks checkout, after checking `formblocks_status` for unsaved changes: + +```bash +./formblocks cli run model.new +./formblocks cli run part.place part=3005 colour=70 'position=[-30,-24,-30]' step=1 +./formblocks cli run part.place part=3005 colour=70 'position=[-30,-24,30]' step=1 +./formblocks cli run part.place part=3005 colour=70 'position=[30,-24,-30]' step=1 +./formblocks cli run part.place part=3005 colour=70 'position=[30,-24,30]' step=1 +./formblocks cli run part.place part=3005 colour=70 on=p1 step=1 +./formblocks cli run part.place part=3005 colour=70 on=p2 step=1 +./formblocks cli run part.place part=3005 colour=70 on=p3 step=1 +./formblocks cli run part.place part=3005 colour=70 on=p4 step=1 +./formblocks cli run part.place part=3031 colour=70 'position=[0,-56,0]' step=2 +./formblocks cli run part.place part=3068b colour=19 'position=[-20,-64,-20]' step=3 +./formblocks cli run part.place part=3068b colour=19 'position=[-20,-64,20]' step=3 +./formblocks cli run part.place part=3068b colour=19 'position=[20,-64,-20]' step=3 +./formblocks cli run part.place part=3068b colour=19 'position=[20,-64,20]' step=3 +./formblocks cli run overlap.check +./formblocks cli run model.save_as path=/tmp/table.fblk +``` + +`on=p1` assumes the first brick answered id `p1`, as it does in a model started with `model.new`. In any other model, use the ids the four lower bricks answered. + +## What you should see + +- The four lower bricks join the ground; each upper brick, placed `on` a lower one, answers a position 24 higher at the same X and Z and joins it with one pair. +- The plate answers `"seated": true` with 4 pairs: one stud of each leg. +- Each tile joins 4 studs of the plate. Nothing can be seated on the tiles: they have no studs. +- `overlap.check` answers `"count": 0` with `"checked": 13`. + +## Variations + +- Taller legs: a third brick on each leg, the plate at Y = -80 and the tiles at Y = -88. +- Four chairs: build one chair, pack it with `submodel.create`, and `part.duplicate` the use (`sub-skills/submodels/SUB-SKILL.md`). diff --git a/.agents/skills/formblocks-driving/examples/wall.md b/.agents/skills/formblocks-driving/examples/wall.md new file mode 100644 index 0000000..3370437 --- /dev/null +++ b/.agents/skills/formblocks-driving/examples/wall.md @@ -0,0 +1,77 @@ +# Example: a wall of twenty bricks + +Four courses of five red 2 x 4 bricks in running bond: every second course is shifted half a brick, so each brick above a joint seats on two bricks below. 400 LDU long (20 studs), two studs thick, four bricks (96 LDU) high, one course per step. + +## The plan + +| Course | Step | Y | X of the five bricks | +| --- | --- | --- | --- | +| 1 | 1 | -24 | 0, 80, 160, 240, 320 | +| 2 | 2 | -48 | 40, 120, 200, 280, 360 | +| 3 | 3 | -72 | 0, 80, 160, 240, 320 | +| 4 | 4 | -96 | 40, 120, 200, 280, 360 | + +Z is 0 for every brick. A 2 x 4 brick is 80 long, so X steps by 80 along a course; the shifted courses start at 40 and stick out half a brick at the right-hand end, which is the toothed end of a running bond. The part number comes from `parts.search` with `brick 2 x 4` (answer `3001`); colour 4 is red. + +## Before you start + +1. `formblocks_status`: note `dirty`. If it is true, ask the person whether to save their model first; `model.new` refuses while there are unsaved changes. +2. `library.status`: `found` must be true (`sub-skills/parts-library/SUB-SKILL.md`). + +## The commands + +From the root of the FormBlocks checkout, with the app running (or not: the command line then works on the same data folder): + +```bash +./formblocks cli parts search "brick 2 x 4" --lines --limit 1 +./formblocks cli run model.new +./formblocks cli run part.place part=3001 colour=4 'position=[0,-24,0]' step=1 +./formblocks cli run part.place part=3001 colour=4 'position=[80,-24,0]' step=1 +./formblocks cli run part.place part=3001 colour=4 'position=[160,-24,0]' step=1 +./formblocks cli run part.place part=3001 colour=4 'position=[240,-24,0]' step=1 +./formblocks cli run part.place part=3001 colour=4 'position=[320,-24,0]' step=1 +./formblocks cli run part.place part=3001 colour=4 'position=[40,-48,0]' step=2 +./formblocks cli run part.place part=3001 colour=4 'position=[120,-48,0]' step=2 +./formblocks cli run part.place part=3001 colour=4 'position=[200,-48,0]' step=2 +./formblocks cli run part.place part=3001 colour=4 'position=[280,-48,0]' step=2 +./formblocks cli run part.place part=3001 colour=4 'position=[360,-48,0]' step=2 +./formblocks cli run part.place part=3001 colour=4 'position=[0,-72,0]' step=3 +./formblocks cli run part.place part=3001 colour=4 'position=[80,-72,0]' step=3 +./formblocks cli run part.place part=3001 colour=4 'position=[160,-72,0]' step=3 +./formblocks cli run part.place part=3001 colour=4 'position=[240,-72,0]' step=3 +./formblocks cli run part.place part=3001 colour=4 'position=[320,-72,0]' step=3 +./formblocks cli run part.place part=3001 colour=4 'position=[40,-96,0]' step=4 +./formblocks cli run part.place part=3001 colour=4 'position=[120,-96,0]' step=4 +./formblocks cli run part.place part=3001 colour=4 'position=[200,-96,0]' step=4 +./formblocks cli run part.place part=3001 colour=4 'position=[280,-96,0]' step=4 +./formblocks cli run part.place part=3001 colour=4 'position=[360,-96,0]' step=4 +./formblocks cli run overlap.check +./formblocks cli run step.list +./formblocks cli run model.save_as path=/tmp/wall.fblk +``` + +`step=2` on the first brick of course 2 is one past the last step, so it starts step 2; the same holds for steps 3 and 4. + +## The same through MCP + +Each `run` line is one tool call. The first brick: + +```json +{"name": "cmd_part_place", "arguments": {"part": "3001", "colour": 4, "position": [0, -24, 0], "step": 1}} +``` + +`cmd_model_new` takes no arguments, `cmd_overlap_check` and `cmd_step_list` none either, and `cmd_model_save_as` takes `{"path": "/tmp/wall.fblk"}` (a full path; ask the person where they want it). From outside the window the first change waits for the person (`sub-skills/working-with-the-person/SUB-SKILL.md`). `scripts/build_wall.py` makes exactly these calls against a running app. + +## What you should see + +- Every `part.place` answers `"seated": true`. Course 1 joins the ground (8 pairs each, `ground` entries in `joined`); each brick of courses 2 to 4 joins two bricks below with 8 pairs, except the three that hang half over an end of the course below: the last brick of courses 2 and 4 and the first brick of course 3 join one brick with 4 pairs. +- The ids are `p1` to `p20` in a model started with `model.new`; read them from the answers rather than counting. +- `overlap.check` answers `"count": 0` with `"checked": 20`. +- `step.list` answers four steps of five placements each. +- `model.save_as` answers `"writtenKind": "fblk"` and `"dirty": false`. + +## Variations + +- Flush ends: make courses 2 and 4 a 2 x 2 brick (`3003`) at X = -20, four 2 x 4 bricks at X = 40, 120, 200 and 280, and a 2 x 2 brick at X = 340, so every course runs from X = -40 to 360. That is 22 bricks in all. +- Faster: place one brick, then `part.duplicate` it with `delta` `[80, 0, 0]`, four times, duplicating the newest copy each time. +- A thin wall: 1 x 4 bricks (`3010`) at Z = 10, the same X values. diff --git a/.agents/skills/formblocks-driving/references/command-catalogue.md b/.agents/skills/formblocks-driving/references/command-catalogue.md index d68aedc..cf4c680 100644 --- a/.agents/skills/formblocks-driving/references/command-catalogue.md +++ b/.agents/skills/formblocks-driving/references/command-catalogue.md @@ -2,6 +2,11 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never edit it by hand. `./formblocks agents check` fails when it differs from the catalogue. +## Contents + +- MCP tools: the 67 tools an agent sees, each with whether it only reads. +- Commands: the 61 catalogue commands with their titles, parameters and summaries, in name order. + ## MCP tools | Tool | Reads only | What it does | @@ -12,8 +17,12 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `formblocks_redo` | no | Redo changes that formblocks_undo took back, one step each. A new change after an undo empties what can be redone. Returns {revision, labels, label}. | | `formblocks_status` | yes | Read what this FormBlocks is: its version, the model's revision, placement count, file and unsaved mark, how many commands there are, its data folder, whether the window's engine is running, and the person's standing choice for outside agents (ask, allowed or blocked). Call it first. | | `formblocks_undo` | no | Undo the last changes, one step per command. Returns {revision, labels, label}: the new revision and the titles of the commands taken back, newest first. Nothing to undo answers an empty labels list. | +| `cmd_colours_current` | yes | Choose the colour the next placed part gets, and put it at the front of the recent colours. Kept as the person's setting; it recolours nothing. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | | `cmd_colours_list` | yes | List the library's colours with code, name, value, edge and finish, or the swatches of one group, hue family or name words. Only reads. | +| `cmd_colours_used` | yes | List the colours used in the open model, most used first: each colour's number, name, value, how many parts of the whole model are in it, and whether the library defines it. Only reads. | +| `cmd_grid_step` | yes | Choose the grid step: stud (20 LDU across, 8 up), plate (10 across, 8 up) or fine (1 and 1). Kept as the person's setting. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | | `cmd_library_status` | yes | Read whether a parts library is in use, where it was found, its update, whether its index is ready, the fetch in progress if any, and the consent and attribution the library card shows. Reading never fetches; only the person can consent to a fetch. Only reads. | +| `cmd_model_info` | yes | Read the model's name, author, file and library update, its counts (parts through every use, different parts, part and colour pairs, submodels, steps), its size in LDU, studs, bricks and millimetres, and its parts list. Only reads. | | `cmd_model_insert` | no | Bring another .ldr, .mpd or .fblk file into the open model as new submodels and place one use of its main model. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_model_new` | no | Start a new model named Untitled with one empty step, and a new history. Opens, starts or writes a model file; not an undo step. An outside agent waits for the person to allow it in the window. | | `cmd_model_open` | no | Open a .fblk, .ldr, .mpd or .dat file by its full path; a library part file opens as a new model holding one placement of the part. Opens, starts or writes a model file; not an undo step. An outside agent waits for the person to allow it in the window. | @@ -21,20 +30,28 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `cmd_model_report` | yes | Read what opening the model reported: lines that could not be read, with their line numbers, and the text encoding. Only reads. | | `cmd_model_save` | no | Save the model to the project file it came from; a model from an LDraw file or never saved needs model.save_as with a .fblk path. Opens, starts or writes a model file; not an undo step. An outside agent waits for the person to allow it in the window. | | `cmd_model_save_as` | no | Write the model to a new path: .fblk saves the project file and makes it the model's file; .ldr or .mpd exports LDraw without FormBlocks' own state. Opens, starts or writes a model file; not an undo step. An outside agent waits for the person to allow it in the window. | +| `cmd_model_set_info` | no | Change the main model's title, author or licence, as written in its header: the licence is empty or one of the Creative Commons licences listed in its parameter. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_model_tree` | yes | Read one submodel's steps and placements, each with its id, part, colour, position, rotation, step and hidden mark, and the submodels with their uses. Only reads. | | `cmd_overlap_check` | yes | List each pair of overlapping placements with the depth of the overlap in LDU, for the given placements or the whole model; parts joined through seated connectors never count. Only reads. | +| `cmd_overlap_set` | yes | Turn the coarse overlap check on or off: with it on, placing and moving never put a part where its box would overlap another's. Kept as the person's setting. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | | `cmd_part_connectors` | yes | List a library part's connectors as the connection model derives them: kind, position, axis and where each came from, with the counts, the body box and the footprint. Only reads. | | `cmd_part_delete` | no | Remove placements from the model; deleting the last use of a submodel keeps the submodel. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_duplicate` | no | Copy placements, keeping colours and relative places, offset by delta; the copies go into the step shown and become the selection. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | +| `cmd_part_duplicate_at_ray` | no | Drop copies of a selection where a pointer ray in the window's scene axes takes the copy of the grabbed placement, seated, on the grid or refused as the drag preview with copy answers; the copies keep their colours and places relative to one another, go into the step shown and become the selection. One undo step. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_fit` | yes | Answer where a part would go and which connectors it would join, from a position, a placement to seat on, or a pointer ray, with snapping, the grid step and the overlap check as set; changes nothing. Only reads. | | `cmd_part_hide` | no | Hide placements: they stay in the model but are not drawn or picked, and the project file remembers it. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_hide_others` | no | Hide every placement of the submodel being edited except the given ones or the selection, to work on one area alone. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_move` | no | Move placements by an offset in LDU, exactly, with no snapping. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | +| `cmd_part_move_at_ray` | no | Put down a dragged selection where a pointer ray in the window's scene axes takes the grabbed placement, seated, on the grid or refused exactly as the drag preview answers; the others keep their places relative to it. One undo step. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | +| `cmd_part_pick` | yes | Name the placement of the submodel being edited that a pointer ray in the window's scene axes meets first on its real triangles, with the point and the face's normal, or the ground; hidden parts are passed through. Only reads. | | `cmd_part_place` | no | Place a part, or a use of a submodel, in a colour: at a position, seated on its connectors when snapping is on, or seated on another placement with on; it goes into the step shown and becomes the selection. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | +| `cmd_part_place_at_ray` | no | Place a library part where a pointer ray in the window's scene axes puts it, seated, on the grid or refused exactly as the placement preview answers; it goes into the step shown of the submodel being edited and becomes the selection. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_recolour` | no | Give placements a colour; a use of a submodel in colour 16 passes it to its parts in colour 16. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_rotate` | no | Turn placements by quarter turns about the X, Y or Z axis through a point, by default the centre of their origins. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_set_transform` | no | Put one placement at an exact position, rotation or both, as the details panel does. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_show` | no | Show hidden placements again; every hidden placement in the model when no ids are given (Show all). Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | +| `cmd_parts_list` | yes | Read the parts a model needs, one row per part and colour with its description, colour name and count, a submodel's parts counted once for each use; parts missing from the library first. Only reads. | +| `cmd_parts_list_save` | no | Write the parts list to a file as CSV: a header row, then one row per part and colour with part number, description, colour number, colour name and count; comma separated, or tab separated for a .tsv path or separator tab. Opens, starts or writes a model file; not an undo step. An outside agent waits for the person to allow it in the window. | | `cmd_parts_search` | yes | Search the parts library by words, part number or category, ranked as the parts palette ranks them; each hit has its number, description, category and keywords, and a moved number says where it moved. Only reads. | | `cmd_parts_show` | yes | Show one part of the library: its description, category, keywords, author and licence, following a moved number to the part it moved to. Only reads. | | `cmd_select_add` | yes | Add placements to the selection. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | @@ -46,6 +63,7 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `cmd_select_invert` | yes | Select every visible placement that was not selected and let go of the rest. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | | `cmd_select_remove` | yes | Let go of placements without touching the rest of the selection. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | | `cmd_select_set` | yes | Make the selection exactly these placements; an empty list clears it. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | +| `cmd_snap_set` | yes | Turn snapping on or off: with it on, a part being placed or moved seats on free compatible connectors within reach; with it off, it moves in grid steps only. Kept as the person's setting. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | | `cmd_step_break_after` | no | Start a new step after a placement, moving the placements after it in its step into the new step; with no id, add an empty step after the step shown and show it. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_step_delete` | no | Delete a step; its placements move to the start of the next step, or to the end of the step before when it is the last. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_step_goto` | yes | Show a step of the submodel being edited: every placement of steps 1 to it is drawn, and new parts go into it. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | @@ -65,8 +83,12 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | Command | Title | Reads only | Parameters | What it does | | --- | --- | --- | --- | --- | +| `colours.current` | Current Colour | yes | `colour` (integer) | Choose the colour the next placed part gets, and put it at the front of the recent colours. Kept as the person's setting; it recolours nothing. | | `colours.list` | Colours | yes | `text` (string, optional), `group` (string, optional), `hue` (string, optional) | List the library's colours with code, name, value, edge and finish, or the swatches of one group, hue family or name words. | +| `colours.used` | Colours Used | yes | none | List the colours used in the open model, most used first: each colour's number, name, value, how many parts of the whole model are in it, and whether the library defines it. | +| `grid.step` | Grid Step | yes | `step` (string) | Choose the grid step: stud (20 LDU across, 8 up), plate (10 across, 8 up) or fine (1 and 1). Kept as the person's setting. | | `library.status` | Library Status | yes | none | Read whether a parts library is in use, where it was found, its update, whether its index is ready, the fetch in progress if any, and the consent and attribution the library card shows. Reading never fetches; only the person can consent to a fetch. | +| `model.info` | Model Information | yes | none | Read the model's name, author, file and library update, its counts (parts through every use, different parts, part and colour pairs, submodels, steps), its size in LDU, studs, bricks and millimetres, and its parts list. | | `model.insert` | Insert LDraw Model | no | `path` (string), `position` (array, optional), `submodel` (string, optional) | Bring another .ldr, .mpd or .fblk file into the open model as new submodels and place one use of its main model. | | `model.new` | New Model | no | `discard` (boolean, optional) | Start a new model named Untitled with one empty step, and a new history. | | `model.open` | Open | no | `path` (string), `discard` (boolean, optional) | Open a .fblk, .ldr, .mpd or .dat file by its full path; a library part file opens as a new model holding one placement of the part. | @@ -74,20 +96,28 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `model.report` | Open Report | yes | none | Read what opening the model reported: lines that could not be read, with their line numbers, and the text encoding. | | `model.save` | Save | no | none | Save the model to the project file it came from; a model from an LDraw file or never saved needs model.save_as with a .fblk path. | | `model.save_as` | Save As | no | `path` (string) | Write the model to a new path: .fblk saves the project file and makes it the model's file; .ldr or .mpd exports LDraw without FormBlocks' own state. | +| `model.set_info` | Set Model Information | no | `title` (string, optional), `author` (string, optional), `licence` (string, optional) | Change the main model's title, author or licence, as written in its header: the licence is empty or one of the Creative Commons licences listed in its parameter. | | `model.tree` | Model Tree | yes | `submodel` (string, optional) | Read one submodel's steps and placements, each with its id, part, colour, position, rotation, step and hidden mark, and the submodels with their uses. | | `overlap.check` | Check Overlaps | yes | `ids` (array, optional) | List each pair of overlapping placements with the depth of the overlap in LDU, for the given placements or the whole model; parts joined through seated connectors never count. | +| `overlap.set` | Overlap Check | yes | `on` (boolean) | Turn the coarse overlap check on or off: with it on, placing and moving never put a part where its box would overlap another's. Kept as the person's setting. | | `part.connectors` | Part Connectors | yes | `part` (string) | List a library part's connectors as the connection model derives them: kind, position, axis and where each came from, with the counts, the body box and the footprint. | | `part.delete` | Delete | no | `ids` (array, optional) | Remove placements from the model; deleting the last use of a submodel keeps the submodel. | | `part.duplicate` | Duplicate | no | `ids` (array, optional), `delta` (array, optional) | Copy placements, keeping colours and relative places, offset by delta; the copies go into the step shown and become the selection. | +| `part.duplicate_at_ray` | Duplicate at Pointer | no | `grab` (string), `origin` (array), `direction` (array), `rotation` (array, optional), `held` (integer, optional), `ids` (array, optional), `snap` (boolean, optional) | Drop copies of a selection where a pointer ray in the window's scene axes takes the copy of the grabbed placement, seated, on the grid or refused as the drag preview with copy answers; the copies keep their colours and places relative to one another, go into the step shown and become the selection. One undo step. | | `part.fit` | Fit Part | yes | `part` (string), `rotation` (array, optional), `position` (array, optional), `on` (string, optional), `origin` (array, optional), `direction` (array, optional), `ids` (array, optional), `submodel` (string, optional), `snap` (boolean, optional) | Answer where a part would go and which connectors it would join, from a position, a placement to seat on, or a pointer ray, with snapping, the grid step and the overlap check as set; changes nothing. | | `part.hide` | Hide | no | `ids` (array, optional) | Hide placements: they stay in the model but are not drawn or picked, and the project file remembers it. | | `part.hide_others` | Hide Others | no | `ids` (array, optional) | Hide every placement of the submodel being edited except the given ones or the selection, to work on one area alone. | | `part.move` | Move | no | `ids` (array, optional), `delta` (array) | Move placements by an offset in LDU, exactly, with no snapping. | +| `part.move_at_ray` | Move Selection at Pointer | no | `grab` (string), `origin` (array), `direction` (array), `rotation` (array, optional), `held` (integer, optional), `ids` (array, optional), `snap` (boolean, optional) | Put down a dragged selection where a pointer ray in the window's scene axes takes the grabbed placement, seated, on the grid or refused exactly as the drag preview answers; the others keep their places relative to it. One undo step. | +| `part.pick` | Pick at Pointer | yes | `origin` (array), `direction` (array), `ground` (boolean, optional) | Name the placement of the submodel being edited that a pointer ray in the window's scene axes meets first on its real triangles, with the point and the face's normal, or the ground; hidden parts are passed through. | | `part.place` | Place Part | no | `part` (string), `colour` (integer), `position` (array, optional), `rotation` (array, optional), `submodel` (string, optional), `step` (integer, optional), `on` (string, optional), `snap` (boolean, optional) | Place a part, or a use of a submodel, in a colour: at a position, seated on its connectors when snapping is on, or seated on another placement with on; it goes into the step shown and becomes the selection. | +| `part.place_at_ray` | Place Part at Pointer | no | `part` (string), `colour` (integer), `origin` (array), `direction` (array), `rotation` (array, optional), `held` (integer, optional), `step` (integer, optional), `snap` (boolean, optional) | Place a library part where a pointer ray in the window's scene axes puts it, seated, on the grid or refused exactly as the placement preview answers; it goes into the step shown of the submodel being edited and becomes the selection. | | `part.recolour` | Recolour | no | `ids` (array, optional), `colour` (integer) | Give placements a colour; a use of a submodel in colour 16 passes it to its parts in colour 16. | | `part.rotate` | Rotate | no | `ids` (array, optional), `axis` (string), `quarter_turns` (integer), `about` (array, optional) | Turn placements by quarter turns about the X, Y or Z axis through a point, by default the centre of their origins. | | `part.set_transform` | Set Position and Rotation | no | `id` (string), `position` (array, optional), `rotation` (array, optional) | Put one placement at an exact position, rotation or both, as the details panel does. | | `part.show` | Show | no | `ids` (array, optional) | Show hidden placements again; every hidden placement in the model when no ids are given (Show all). | +| `parts.list` | Parts List | yes | `scope` (string, optional), `group` (string, optional) | Read the parts a model needs, one row per part and colour with its description, colour name and count, a submodel's parts counted once for each use; parts missing from the library first. | +| `parts.list_save` | Save Parts List | no | `path` (string), `separator` (string, optional), `scope` (string, optional), `group` (string, optional) | Write the parts list to a file as CSV: a header row, then one row per part and colour with part number, description, colour number, colour name and count; comma separated, or tab separated for a .tsv path or separator tab. | | `parts.search` | Search Parts | yes | `text` (string, optional), `category` (string, optional), `list` (string, optional), `printed` (boolean, optional), `limit` (integer, optional), `offset` (integer, optional) | Search the parts library by words, part number or category, ranked as the parts palette ranks them; each hit has its number, description, category and keywords, and a moved number says where it moved. | | `parts.show` | Part Details | yes | `part` (string) | Show one part of the library: its description, category, keywords, author and licence, following a moved number to the part it moved to. | | `select.add` | Add to Selection | yes | `ids` (array) | Add placements to the selection. | @@ -99,6 +129,7 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `select.invert` | Invert Selection | yes | none | Select every visible placement that was not selected and let go of the rest. | | `select.remove` | Remove from Selection | yes | `ids` (array) | Let go of placements without touching the rest of the selection. | | `select.set` | Select | yes | `ids` (array) | Make the selection exactly these placements; an empty list clears it. | +| `snap.set` | Snapping | yes | `on` (boolean) | Turn snapping on or off: with it on, a part being placed or moved seats on free compatible connectors within reach; with it off, it moves in grid steps only. Kept as the person's setting. | | `step.break_after` | New Step | no | `id` (string, optional) | Start a new step after a placement, moving the placements after it in its step into the new step; with no id, add an empty step after the step shown and show it. | | `step.delete` | Delete Step | no | `step` (integer), `submodel` (string, optional) | Delete a step; its placements move to the start of the next step, or to the end of the step before when it is the last. | | `step.goto` | Show Step | yes | `index` (integer) | Show a step of the submodel being edited: every placement of steps 1 to it is drawn, and new parts go into it. | diff --git a/.agents/skills/formblocks-driving/references/coordinates-and-units.md b/.agents/skills/formblocks-driving/references/coordinates-and-units.md new file mode 100644 index 0000000..c814afa --- /dev/null +++ b/.agents/skills/formblocks-driving/references/coordinates-and-units.md @@ -0,0 +1,74 @@ +# Coordinates, units and quarter turns + +## Contents + +- Units +- The axes +- Where a part's origin is +- Standing a part on the ground +- Stacking +- Quarter turns as matrices +- Working out a position by hand + +## Units + +Every length FormBlocks takes or answers is in LDU, the LDraw unit (about 0.4 mm). The numbers are the same ones an `.ldr` file holds, so a position read from a file, typed in a panel, given to `part.place` or read back from `model.tree` means the same place. + +| Measure | LDU | +| --- | --- | +| Stud pitch (centre of one stud to the next) | 20 | +| Brick height | 24 | +| Plate height (a third of a brick) | 8 | +| Stud height (the knob on top) | 4 | +| Largest position accepted on any axis | 1000000 | + +Two plates are 16, three plates are a brick. A 2 x 4 brick is 80 by 40 across and 24 high, not counting its studs. + +## The axes + +- X runs left and right, Z runs front and back, Y runs up and down. +- -Y is up. A part higher in the model has a more negative Y. The ground is the plane Y = 0 and everything standing on it has Y below 0. +- The front of the model faces -Z: the front view looks from the -Z side towards +Z. +- The axes are right-handed. +- The window draws with +Y up, but that conversion happens inside the engine only. Never flip a sign yourself: every number you send or read is on the LDraw axes. + +## Where a part's origin is + +A placement's `position` is where the part's own origin goes. For an ordinary part from the library (brick, plate, tile, slope) the origin is in the middle of the stud grid on its top surface, at the foot of the studs: the studs stand above it (Y from 0 to -4 in the part's own axes) and the body hangs below it (Y from 0 to 24 for a brick, 0 to 8 for a plate or tile). + +`part.connectors` with a part number answers its footprint (`x0`, `x1`, `z0`, `z1`), its bottom plane (`bottom`, 24 for a brick, 8 for a plate) and the place of every stud and anti-stud in the part's own axes. Read it before placing a part whose shape you do not know: a 45 degree slope 2 x 2 (3039), for example, has its origin over its back row of studs and its sloped face running out to Z = -30. + +## Standing a part on the ground + +- A brick standing on the ground has its origin at Y = -24; a plate or tile at Y = -8; a 2 x 2 slope at Y = -24. +- The ground offers a stud at every point (10 + 20i, 0, 10 + 20k). A part seats on the ground when its anti-studs land on those points. +- So across, an origin sits on a multiple of 20 when the part is an even number of studs long on that axis (2, 4, 6) and on 10 plus a multiple of 20 when it is odd (1, 3). A 2 x 4 brick at (0, -24, 0) seats; a 1 x 1 brick seats at (10, -24, 10) or (-30, -24, 30); a 1 x 4 brick lying along X seats at (0, -24, 10). +- A position within 15 LDU of a seat is pulled into the seat when snapping is on, so a small rounding slip does no harm. Further off, the part is put on the grid step instead and the answer says `seated: false`. + +## Stacking + +- Each brick course is 24 lower in Y than the one below: courses stand at Y = -24, -48, -72, -96. +- A plate on top of a brick course whose top is at Y = -96 goes at Y = -104 (one plate, 8, higher). +- In general: origin Y of the new part = top of what it stands on minus the new part's own `bottom`. + +## Quarter turns as matrices + +`rotation` is the nine numbers of the 3 by 3 matrix of an LDraw type 1 line, row by row. Leave it out for no turn. + +| Turn | `rotation` | +| --- | --- | +| None | `[1,0,0, 0,1,0, 0,0,1]` | +| A quarter turn about Y (a part long along X now runs along Z) | `[0,0,1, 0,1,0, -1,0,0]` | +| The other quarter turn about Y | `[0,0,-1, 0,1,0, 1,0,0]` | +| A half turn about Y (a slope facing front now faces back) | `[-1,0,0, 0,1,0, 0,0,-1]` | + +A part turned a quarter turn about Y swaps its X and Z extents: a 1 x 4 brick turned this way covers 20 across X and 80 along Z, so its origin sits on 10 plus a multiple of 20 in X and on a multiple of 20 in Z. + +To turn parts that are already placed, use `part.rotate` with `axis` (`x`, `y` or `z`) and `quarter_turns`; it turns them about the centre of their origins, or about `about` when given, and works out the new matrices itself. Tipping (about X) and rolling (about Z) are possible the same way; snapping never turns a part on its own. + +## Working out a position by hand + +1. Decide which stud cells the part should cover, as cell centres (10 + 20i, 10 + 20k). +2. The origin across is the middle of those cells. +3. The origin's Y is the top of what it stands on (0 for the ground) minus the part's `bottom`. +4. Place it, and check `seated: true` in the answer. diff --git a/.agents/skills/formblocks-driving/references/error-codes.md b/.agents/skills/formblocks-driving/references/error-codes.md new file mode 100644 index 0000000..4b99da4 --- /dev/null +++ b/.agents/skills/formblocks-driving/references/error-codes.md @@ -0,0 +1,84 @@ +# Errors and what to do about each + +## Contents + +- Exit codes of the command line +- How an MCP call fails +- Refusals by the person +- Refusals by a command +- Answers that succeed but need a second look + +A failed call changes nothing: the model, the selection and the history are as they were. So the right move after any error is to read the sentence, fix the call, and send it once. + +## Exit codes of the command line + +| Exit | Meaning | What to do | +| --- | --- | --- | +| 0 | The command did what was asked. The JSON has `"ok": true`. | Read the result. | +| 1 | The command failed or was refused; `"ok": false` and `"error"` holds one sentence. | Fix what the sentence names. | +| 2 | A usage mistake: an unknown subcommand or a malformed option. A sentence goes to standard error. | Read `./formblocks cli --help`. | + +## How an MCP call fails + +| What comes back | Code | Meaning | What to do | +| --- | --- | --- | --- | +| A JSON-RPC error, "Unknown tool: ..." | -32602 | The tool name is not in `tools/list`. | Read `formblocks_list_commands`; call `formblocks_execute` with a listed id. | +| A JSON-RPC error, "Missing required argument ...", "Unknown argument ...", "Argument ... must be a ..." | -32602 | The arguments do not match the tool's schema. Nothing ran. | Fix the argument names and types. | +| A JSON-RPC error, "Method not found" | -32601 | Not an MCP method the server has. | Use `tools/list` and `tools/call`. | +| A JSON-RPC error, "Parse error" | -32700 | The line was not JSON. | Send one JSON object per line. | +| A JSON-RPC error, "Unsupported protocol version" | -32022 | The client asked for a protocol version the server does not speak; the error lists the supported ones. | Initialise with one of them. | +| A JSON-RPC error, "FormBlocks is not accepting connections at ..." | -32603 | The bridge started with `--connect` found no engine. The call did not run. | Ask the person to start FormBlocks, or run the server headless for reading. | +| A JSON-RPC error, "The reply was lost, so this call may have run" | -32603 | The engine stopped answering in the middle of a call. | Read the model (`cmd_model_tree`) before sending it again. | +| A JSON-RPC error, "Cannot read the window key file" | -32603 | The bridge cannot find the running engine's data folder. | Give the same `FORMBLOCKS_DATA_DIR` the app uses. | +| A tool result with `isError: true` and `"refused": true` | none | The person, or the absence of a person, stopped the change. See below. | Do not resend it unchanged. | +| A tool result with `isError: true` and `"ok": false` | none | The command refused the call. See below. | Fix what the sentence names. | + +## Refusals by the person + +These come back only for `change` and `file` commands and for undo and redo, sent from outside the window. + +| The sentence says | Why | What to do | +| --- | --- | --- | +| "The person declined this change in the FormBlocks window." | They chose Deny. | Say what you meant to do and let them choose. Do not try it another way. | +| "Nobody answered in the FormBlocks window within 120 seconds" | Nobody was looking. | Ask the person to look at the window, then send it once more. | +| "The person has blocked outside agents in FormBlocks." | Their standing choice is `blocked`. | Stop changing the model; reading still works. | +| "FormBlocks is not open, so nobody can allow this change." | The server is headless and the person has not allowed this program always. | Ask the person to start the app. | + +## Refusals by a command + +A command's sentence starts with the parameter it is about (`part:`, `on:`, `ids:`), so the fix is in that argument. + +| The sentence starts or says | What to do | +| --- | --- | +| "part: ... is not in the LDraw parts library in use" | Search with `parts.search` and place the number it answers. A number with letters (`3068b`) is a different part from the bare number. | +| "No LDraw parts library is installed" | Nothing can be placed. Tell the person; only they can find or fetch the library (`sub-skills/parts-library/SUB-SKILL.md`). | +| "position: give a position, a placement to seat on (on), or a pointer ray" | `part.place` needs `position` or `on`. | +| "position: the part would overlap ... with the overlap check on" | The person's overlap check is on and the place is taken. Pick another place; the overlap check's box is coarse round slopes, so tell the person if a slope is refused where it should fit. | +| "... must stay within 1000000 LDU of the origin" | A position or offset is out of range: check signs and units. | +| "on: ... has no free connector that ... can seat on" | Every stud of that placement is taken. Seat on another placement, or give a position. | +| "on: ... is hidden" | Hidden parts offer no connectors. Show it with `part.show` first, or use a position. | +| "on: ... is in ..., not in ..." | `on` must name a placement in the submodel the part goes into. | +| "ids: there is no placement ..." | The id is wrong or was deleted. Read `model.tree` for current ids. | +| "ids: give placement ids, or select parts first." | Pass `ids`; do not rely on the selection unless you set it. | +| "... is hidden; show it before selecting it." | Show it, or leave it out. | +| "... is not in ..., the submodel being edited." | Selection commands act inside the submodel being edited: `submodel.enter` or `submodel.leave` first. | +| "colour must be a colour code from 0" | Use a code from `colours.list`. | +| "rotation is flat (its determinant is zero)" | The nine numbers do not make a turn. Leave `rotation` out for no turn, or use `[0,0,1, 0,1,0, -1,0,0]` for a quarter turn about Y and `[0,0,-1, 0,1,0, 1,0,0]` for the other. | +| "axis must be x, y or z" | `part.rotate` takes the letter of an LDraw axis. | +| "step must be from 1 to ..." | Read `step.list`. For `part.place`, one past the last step starts a new step. | +| "step: ... has one step, which cannot be deleted." | A submodel keeps at least one step. | +| "discard: the open model has unsaved changes" | Ask the person whether to save first; pass `discard: true` only after they say to drop the changes. | +| "path: the model has no project file yet" | `model.save` needs a project file; use `model.save_as` with a `.fblk` path. | +| "name: the model already has a block named ..." | Pick another submodel name. | +| "part: ... holds ..., so a use of it there would hold itself." | A submodel cannot contain itself. Place it in another submodel. | +| "with_uses: ... has ... uses" | `submodel.delete` keeps a used submodel unless `with_uses` is true. Ask before deleting uses. | +| "There is no command ..." | The id is wrong; read the catalogue. | +| "... needs ... (...)" or "... takes no parameter ..." | A required parameter is missing, or a name is wrong; read the command's entry. | + +## Answers that succeed but need a second look + +- `part.place` answering `"seated": false`: the part did not join anything. With the overlap check off (its first setting) it was put on the grid step instead and may float in the air or sit inside another part. Undo it and fix the position, unless a loose part is what you meant. +- `part.place` with `on` seating on a different part of the target than you wanted: `on` takes the first free studs nearest the target's middle. Give a position for an exact place. +- `overlap.check` answering a `count` above 0: two parts share space. Undo the newer one or move it. +- `model.open` answering an `issueCount` above 0: some lines could not be read; `model.report` lists them. The rest of the file opened. +- A JSON-RPC timeout on a `change` sent from outside: the person may still have the question open. Read the model before sending again. diff --git a/.agents/skills/formblocks-driving/references/tool-naming.md b/.agents/skills/formblocks-driving/references/tool-naming.md new file mode 100644 index 0000000..ae47dc4 --- /dev/null +++ b/.agents/skills/formblocks-driving/references/tool-naming.md @@ -0,0 +1,67 @@ +# Tool naming + +## Contents + +- One catalogue, three ways in +- The six fixed tools +- The cmd_ tools +- The command line +- The same call three ways +- Names that do not exist + +## One catalogue, three ways in + +Every action on the model is a command in the engine's one catalogue, with an id written `area.verb` (`part.place`, `step.rename`). The window's buttons, the command line and the MCP tools all run the same command with the same parameters, so a parameter name learned in one place holds in the others. `formblocks_list_commands` (or `./formblocks cli commands`) answers the live catalogue, and wins over any copy of it written into this pack. + +Each command has a kind, which decides what it may do: + +| Kind | What it does | Undo step | Waits for the person when sent from outside the window | +| --- | --- | --- | --- | +| `read` | Reads only. | No | No | +| `view` | Changes the selection, the step shown or the submodel being edited. | No | No | +| `change` | Changes the model, hiding and showing included. | One, however many parts it touches | Yes | +| `file` | Starts, opens or writes a model file. | Never; new and open start a new history | Yes | + +## The six fixed tools + +| Tool | What it does | +| --- | --- | +| `formblocks_status` | Version, revision, placement count, file, unsaved mark, command count, data folder, whether the window's engine is running, and the person's standing choice for outside agents. Call it first. | +| `formblocks_list_commands` | The catalogue: name, title, summary, typed parameters, kind and the `cmd_` tool; `filter` keeps commands whose name, title or summary holds a word. | +| `formblocks_get_doc` | The whole open model, the view and the revision. Large on a big model; `cmd_model_tree` answers one submodel. | +| `formblocks_execute` | Runs any command by id: `{"command": "part.place", "params": {...}}`. | +| `formblocks_undo` | Takes back the newest changes, one per command; `steps` for more than one. | +| `formblocks_redo` | Puts back what undo took back. | + +A program started from a tab of the window's agent dock sees the same tools under a server named `formblocks_tab`; a program registered by `./formblocks agents install` sees them under `formblocks`. + +## The cmd_ tools + +Each command is also a tool of its own, named `cmd_` and the id with every dot and dash made an underscore: `part.place` is `cmd_part_place`, `step.break_after` is `cmd_step_break_after`, `overlap.check` is `cmd_overlap_check`. Its arguments are the command's parameters, checked against the schema before the call runs: a missing required argument, an argument the command does not take, or a value of the wrong type is refused with one sentence and nothing runs. + +The tool's description ends with its kind in words: "Only reads", "Changes only the view", "Changes the model; one undo step" or "Opens, starts or writes a model file". Its annotations say the same: `readOnlyHint` true for `read` commands only. + +## The command line + +`./formblocks cli run [id] [name=value ...]` runs one command and prints one JSON object. Values are read as JSON when they are JSON and as text otherwise: `colour=4`, `position=[0,-24,0]`, `snap=false`, `part=3001`. Quote a value that holds brackets or spaces for the shell: `'position=[0,-24,0]'`. One JSON object can stand for all the parameters instead. `--compact` prints the answer on one line. + +Beside `run` the command line has its own subcommands for what is not a catalogue command: `commands`, `doc`, `undo`, `redo`, `mcp`, `parts search`, `parts show`, `part-mesh`, `library status`, `library use`, `library fetch`, `library check-update` and `colours`. `./formblocks cli --help` lists them. + +When an engine is running on the same data folder, `cli` sends the command through it and the window shows the change at once; with none it runs in its own process on the same data folder, so the open model and its undo history carry over between runs. + +## The same call three ways + +| Way in | Call | +| --- | --- | +| A `cmd_` tool | `cmd_part_place` with `{"part": "3001", "colour": 4, "position": [0, -24, 0]}` | +| The fixed tool | `formblocks_execute` with `{"command": "part.place", "params": {"part": "3001", "colour": 4, "position": [0, -24, 0]}}` | +| The command line | `./formblocks cli run part.place part=3001 colour=4 'position=[0,-24,0]'` | + +All three answer `{ok, command, result, revision}`; a change also answers `undo`, the label the Edit menu shows for it. + +## Names that do not exist + +- The tables of `spec/SPEC.md` sections 1 to 19 were written before the catalogue and use some older ids (`selection.move`, `file.save`, `step.show`). The catalogue's ids are the ones that run: `part.move`, `model.save_as`, `step.goto`. +- Undo and redo are not catalogue commands: there is no `edit.undo` tool. Use `formblocks_undo` and `formblocks_redo`, or `./formblocks cli undo` and `redo`. +- Fetching the library is not a command and no tool starts it (`sub-skills/parts-library/SUB-SKILL.md`). +- A tool the server does not list does not exist. Do not guess a name from a pattern; read `formblocks_list_commands`. diff --git a/.agents/skills/formblocks-driving/scripts/build_wall.py b/.agents/skills/formblocks-driving/scripts/build_wall.py new file mode 100755 index 0000000..f6b1828 --- /dev/null +++ b/.agents/skills/formblocks-driving/scripts/build_wall.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Build the wall of twenty bricks (examples/wall.md) in a running FormBlocks through its MCP server. Standard library only. + +usage: build_wall.py [--root DIR] [--connect HOST:PORT|auto] [--colour CODE] [--save PATH] +Starts ROOT/formblocks mcp --connect (auto by default), so it works only against a running app and never headless. +It checks status and the library, starts a new model (refused while the person's model has unsaved changes), +places four courses of five 2 x 4 bricks in running bond, one course per step, runs the overlap check and, +with --save, saves the model as a .fblk. Every change waits for the person in the window until they allow it. +exit 0 built and checked, 1 a call failed or was refused, 2 the server or the app could not be reached. +""" +import argparse +import json +import os +import subprocess +import sys +import threading + +REPLY_TIMEOUT = 150.0 +PART = "3001" +COURSES = 4 +BRICKS = 5 +LENGTH = 80 +HEIGHT = 24 + + +class Failed(Exception): + pass + + +class Session: + def __init__(self, command): + self.next_id = 0 + self.proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) + + def rpc(self, method, params=None): + self.next_id += 1 + self.proc.stdin.write(json.dumps({"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params or {}}) + "\n") + self.proc.stdin.flush() + while True: + box = [] + reader = threading.Thread(target=lambda: box.append(self.proc.stdout.readline()), daemon=True) + reader.start() + reader.join(REPLY_TIMEOUT) + if not box or not box[0]: + raise Failed("no reply to %s within %.0f s" % (method, REPLY_TIMEOUT)) + reply = json.loads(box[0]) + if reply.get("id") == self.next_id: + if "error" in reply: + raise Failed("%s: %s" % (method, reply["error"].get("message"))) + return reply["result"] + + def notify(self, method): + self.proc.stdin.write(json.dumps({"jsonrpc": "2.0", "method": method}) + "\n") + self.proc.stdin.flush() + + def call(self, name, arguments=None): + result = self.rpc("tools/call", {"name": name, "arguments": arguments or {}}) + data = result.get("structuredContent") or {} + if result.get("isError"): + raise Failed("%s: %s" % (name, data.get("error") or result)) + return data + + def close(self): + try: + self.proc.stdin.close() + self.proc.wait(10) + except (OSError, subprocess.TimeoutExpired): + self.proc.kill() + + +def plan(): + for course in range(1, COURSES + 1): + shift = LENGTH // 2 if course % 2 == 0 else 0 + for i in range(BRICKS): + yield course, [LENGTH * i + shift, -HEIGHT * course, 0] + + +def build(session, colour, save): + session.rpc("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "build_wall", "version": "1"}}) + session.notify("notifications/initialized") + status = session.call("formblocks_status") + if status.get("engine") != "running": + raise Failed("FormBlocks is not running; start the app first") + print("FormBlocks %s, revision %s, outside agents: %s" % (status.get("version"), status.get("revision"), status.get("outside_agents"))) + library = session.call("cmd_library_status").get("result", {}) + if not library.get("found"): + raise Failed("no parts library is in use; only the person can find or fetch it") + print("Each change below waits until the person allows it in the FormBlocks window.") + session.call("cmd_model_new") + placed = [] + for course, position in plan(): + answer = session.call("cmd_part_place", {"part": PART, "colour": colour, "position": position, "step": course}) + result = answer.get("result", {}) + pid = result.get("placement", {}).get("id") + below = sorted({j.get("placement") or "ground" for j in result.get("joined", [])}) + print("course %d %s at %s seated %s on %s" % (course, pid, position, result.get("seated"), ", ".join(below) or "-")) + if not result.get("seated"): + raise Failed("%s did not seat; undo it and check the position" % pid) + placed.append(pid) + overlaps = session.call("cmd_overlap_check").get("result", {}) + print("overlap check: %s pairs over %s placements" % (overlaps.get("count"), overlaps.get("checked"))) + if overlaps.get("count"): + raise Failed("the overlap check found overlapping parts") + steps = session.call("cmd_step_list").get("result", {}).get("steps", []) + print("steps: %s" % ", ".join(str(len(s.get("placements", []))) for s in steps)) + if save: + written = session.call("cmd_model_save_as", {"path": save}).get("result", {}) + print("saved %s (%s bytes)" % (written.get("written"), written.get("bytes"))) + return placed + + +def main(): + parser = argparse.ArgumentParser(description="Build the wall of twenty bricks in a running FormBlocks.") + parser.add_argument("--root", default=os.getcwd(), help="the FormBlocks checkout") + parser.add_argument("--connect", default="auto", help="HOST:PORT of the running engine, or auto") + parser.add_argument("--colour", type=int, default=4, help="an LDraw colour code (4 is red)") + parser.add_argument("--save", default="", help="a full path ending in .fblk to save the wall to") + opts = parser.parse_args() + launcher = os.path.join(opts.root, "formblocks.bat" if os.name == "nt" else "formblocks") + if not os.path.isfile(launcher): + print("no formblocks launcher at %s; pass --root" % launcher) + return 2 + try: + session = Session([launcher, "mcp", "--connect", opts.connect]) + except OSError as err: + print("cannot start %s: %s" % (launcher, err)) + return 2 + try: + placed = build(session, opts.colour, opts.save) + except Failed as err: + text = str(err) + print("stopped: %s" % text) + return 2 if "not running" in text or "not accepting connections" in text else 1 + except (ValueError, OSError) as err: + print("the server answered badly: %s" % err) + return 1 + finally: + session.close() + print("built %d bricks" % len(placed)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.agents/skills/formblocks-driving/sub-skills/building-in-order/SUB-SKILL.md b/.agents/skills/formblocks-driving/sub-skills/building-in-order/SUB-SKILL.md new file mode 100644 index 0000000..c3c347f --- /dev/null +++ b/.agents/skills/formblocks-driving/sub-skills/building-in-order/SUB-SKILL.md @@ -0,0 +1,58 @@ +--- +name: building-in-order +description: Plans and builds brick structures in FormBlocks bottom up and strong, with walls in overlapping courses, interlocked corners, openings with a lintel, plates and tiles, and roofs of slopes. Use when asked to build a wall, a house, a tower, furniture or any structure of more than a few parts, or when a build comes out loose, floating or overlapping. +--- + +# Building in order + +A model is strong and placeable when every part seats on something already there. That gives the order: from the ground up, one course (one brick height) at a time, finishing each course before the next. Snapping only seats a part on parts that exist, so a brick placed before its support is placed loose. + +## Plan on the grid first + +1. Decide the footprint in studs: how many wide (X) and deep (Z). Put the front of the build towards -Z, which is the front view. +2. Write down which stud cells each part covers; cell centres are at (10 + 20i, 10 + 20k). +3. Work out each origin from its cells and its height (`references/coordinates-and-units.md`): bricks of course n stand at Y = -24n. +4. Search for each part number once (`sub-skills/finding-parts/SUB-SKILL.md`) and reuse it. +5. Put each course in its own step (`sub-skills/steps/SUB-SKILL.md`): `step: 1` for the first, then one past the last to start each new one. + +## Walls: overlap the courses + +A wall of bricks stacked straight up, joint above joint, is a set of separate columns. Shift every second course by half a brick so each brick bridges the joint below it and seats on two bricks: the running bond. + +- With 2 x 4 bricks (80 long), course 1 at X = 0, 80, 160, ...; course 2 at X = 40, 120, 200, ...; course 3 like course 1. +- Each brick of course 2 should answer `joined` pairs with two placements. One placement only means it sits over a joint, or over the end. +- The ends of a shifted course stick out half a brick. Leave them toothed, or fill the short gaps with half-length bricks (a 2 x 2 at the end of a 2 x 4 course, a 1 x 2 at the end of a 1 x 4 course). +- Thin walls (one stud thick) use 1 x N bricks; thick walls use 2 x N. + +## Corners: let the walls take turns + +Where two walls meet, let one wall run through the corner cell in one course and the other wall run through it in the next. The corner bricks then seat across both walls and tie them together. In a box of four walls: in odd courses the front and back walls run the full width and the side walls fit between them; in even courses the side walls run the full depth and the front and back fit between. + +## Openings: frame and span + +- Leave the cells of a door or window empty in the courses it passes through, keeping the bricks either side of it in running bond where the length allows. +- Close the top with one brick long enough to rest on both sides: a lintel. A 2 stud opening needs at least a 1 x 4 over it; it should answer `joined` pairs on both sides. +- Door and window frames from the library (`door frame`, `window 1 x 2 x 2`) are placed like bricks; read `part.connectors` for their footprint first. + +## Plates and tiles + +- A plate is a third of a brick high (8). Plates over a course tie bricks together across joints and make a floor or a ceiling. A plate on a course whose top is at Y = T goes at Y = T - 8. +- Long plates (2 x 6, 2 x 8) laid over the tops of walls hold the walls together better than another course of bricks. +- A tile is a plate with a smooth top and no studs. Nothing seats on a tile, so tiles go last, on top surfaces you want smooth (a table top, a floor, a path). +- Three plates are one brick high, so plates and bricks mix freely in a stack. + +## Roofs of slopes + +- A 45 degree slope brick 2 x 2 (`3039`) is a brick height high, with its two studs on its back row and its sloped face running down towards -Z. Unturned, it faces the front. +- A half turn about Y, `rotation` `[-1,0,0, 0,1,0, 0,0,-1]`, makes it face the back. +- Lay a flat layer of plates on the walls first, so every slope has studs under its whole footprint. +- A gable roof: a row of slopes facing front along the front edge and a row facing back along the back edge. Each further row steps in by one stud and up by one brick, standing on the studs of the row below and on filler bricks behind it. Close the ridge with plates or tiles over the last studs. +- The overlap check's box fills the space above a slope's face, so with the check on a part right over a sloped face can be refused although it would fit. Keep parts clear of sloped faces, or tell the person why the check refuses. + +## After each course + +- Every part in it answered `seated: true`. +- `overlap.check` answers `count: 0` (it is cheap; run it per course on a large build). +- `step.list` shows the course in its own step. + +The worked examples carry all of this out: `examples/wall.md`, `examples/house.md`, `examples/table.md`. diff --git a/.agents/skills/formblocks-driving/sub-skills/building-models/SUB-SKILL.md b/.agents/skills/formblocks-driving/sub-skills/building-models/SUB-SKILL.md deleted file mode 100644 index fbab7ae..0000000 --- a/.agents/skills/formblocks-driving/sub-skills/building-models/SUB-SKILL.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -name: building-models -description: Builds and changes models in a running FormBlocks through MCP - finding parts and colours, placing and seating parts with snapping, checking overlaps, moving, turning, recolouring, steps, submodels, saving and exporting, undo and redo. Use for parts.search, part.place, part.fit, overlap.check, model.save_as and any other catalogue command. ---- - -# Building models - -Start with `formblocks_status` and `cmd_model_tree` (`sub-skills/connect-and-status/SUB-SKILL.md`), so you know the revision, the submodel being edited and the placement ids before you change anything. - -## Units and axes - -Positions are LDraw units (LDU) on the LDraw axes: X and Z across, Y up and down with -Y up. One stud is 20 LDU, a brick 24 LDU high, a plate 8. A part's position is its origin; for an ordinary brick or plate the origin is the centre of its top face, so a brick standing on the ground has Y = -24 and a plate Y = -8. Rotations are the nine numbers of an LDraw matrix, row by row; leave `rotation` out for none. A quarter turn about Y is `[0,0,1, 0,1,0, -1,0,0]`. - -## Finding parts and colours - -| Command | Tool | Use | -| --- | --- | --- | -| `parts.search` | `cmd_parts_search` | `text` such as `brick 2 x 4`; the best hit is first. `limit` 20 unless given. | -| `parts.show` | `cmd_parts_show` | One part's description, category, author and licence; a moved number names its new one. | -| `colours.list` | `cmd_colours_list` | The library's colours; `text` such as `dark blue`, or a `group`. 4 is red, 1 blue, 15 white, 0 black. | -| `library.status` | `cmd_library_status` | Whether a parts library is in use. With none, nothing can be placed: tell the person; only they can fetch it, in the window. | - -## Placing - -- `part.place {part, colour, position}`: with snapping on (the person's setting, or `snap` for this call) the part seats on free studs within reach of `position`, the ground's stud lattice included, or moves to the grid step; with snapping off it goes exactly to `position`. The answer has the new `placement` (its `id`), `seated` and the `joined` connector pairs. -- `part.place {part, colour, on: "p12"}` seats the part on placement `p12`'s free studs, nearest its middle first, with no coordinates: the simplest way to stack. -- `part.fit` takes the same `part`, `rotation`, `position` or `on` and answers where the part would go and what it would join, changing nothing. Use it before a place you are unsure of. -- With the overlap check on, a place that would overlap another part is refused with the part named; nothing changes. -- A part the library does not have is refused. Search first, place the number the search gives. - -## Checking - -- `overlap.check` lists every pair of overlapping placements with its depth in LDU; give `ids` to check only those. It works whatever the switch says. Parts seated on each other never count. -- `part.connectors {part}` shows a part's studs and anti-studs as FormBlocks derives them. - -## Changing what is there - -`part.move` (by `delta`, exact), `part.set_transform`, `part.rotate` (quarter turns), `part.recolour`, `part.duplicate`, `part.delete`, `part.hide`, `part.show`: each takes `ids`, or acts on the selection when `ids` is left out. `select.*` commands change only the selection. Steps: `step.break_after`, `step.move_parts`, `step.rename`, `step.goto`, `step.list`. Submodels: `submodel.create` packs placements, `submodel.dissolve` unpacks one use, `submodel.enter` and `submodel.leave` choose where new parts go. - -## Files - -`model.save_as {path}` with a full path: `.fblk` saves the project, `.ldr` or `.mpd` exports LDraw for any other LDraw program. `model.open {path}` opens one; `model.new` starts over. Both refuse while there are unsaved changes unless `discard` is true: ask the person before you discard anything. Saving and opening ask the person in the window first, like any change. - -## Undo and redo - -- Every change command is one undo step with a label (`Place 3001.dat`, `Move 3 parts`); view commands and file commands are not. -- `formblocks_undo` takes back the newest steps (`steps`, default 1); `formblocks_redo` puts them back. The history is the person's too: undo only what you made, by count. - -## Recipes - -- A wall of bricks: `parts.search` for `brick 2 x 4` (3001), `part.place` the first at `[0, -24, 0]`, then each next at `[80 * i, -24, 0]`; the next course `on` a brick below, or at `Y = -48` offset by 40 for a running bond. Finish with `overlap.check`: `count` 0. -- Save: `model.save_as` with a `.fblk` path, then with an `.ldr` path for an LDraw copy. diff --git a/.agents/skills/formblocks-driving/sub-skills/changing-parts/SUB-SKILL.md b/.agents/skills/formblocks-driving/sub-skills/changing-parts/SUB-SKILL.md new file mode 100644 index 0000000..a8dc969 --- /dev/null +++ b/.agents/skills/formblocks-driving/sub-skills/changing-parts/SUB-SKILL.md @@ -0,0 +1,44 @@ +--- +name: changing-parts +description: Changes parts already placed in a FormBlocks model by moving by an offset, setting an exact position or rotation, turning by quarter turns, duplicating, recolouring, hiding, showing and deleting, each as one undo step. Use when asked to move, shift, turn, rotate, copy, repeat, recolour, hide, show or remove placements, or to undo such a change. +--- + +# Changing parts + +Every command here is a `change` command: one undo step however many parts it touches, labelled for the person's Edit menu (`Move 3 parts`, `Rotate 1 part about Y`), and it waits for the person's approval when sent from outside the window. + +## Name the parts + +Each command takes `ids`, a list of placement ids such as `["p3", "p4"]`. Left out, it acts on the selection; a selection you did not set yourself may be the person's, so pass `ids`. Read ids from the answer that made the part, or from `model.tree`. An id stays the same while the model is open, through undo and redo, until the part is deleted. + +## The commands + +| Command | Parameters | What it does | +| --- | --- | --- | +| `part.move` | `ids`, `delta` | Moves by an exact offset in LDU, `[dx, dy, dz]`. No snapping: the parts go exactly where sent. Up is a negative `dy`. | +| `part.set_transform` | `id`, `position`, `rotation` | Puts one placement at an exact position, an exact rotation, or both. | +| `part.rotate` | `ids`, `axis`, `quarter_turns`, `about` | Turns by quarter turns about `x`, `y` or `z`, right-handed about the positive axis; negative turns go the other way. It turns about `about` when given, otherwise about the centre of the placements' origins, and works out the new positions and matrices. | +| `part.duplicate` | `ids`, `delta` | Copies the placements with their colours and relative places, offset by `delta`. The copies go into the step shown and become the selection; the answer lists their new ids. | +| `part.recolour` | `ids`, `colour` | Gives a colour code. Parts already in it are left as they are. | +| `part.delete` | `ids` | Removes placements. Deleting the last use of a submodel keeps the submodel itself. | +| `part.hide` | `ids` | Hides placements: they stay in the model, the parts list and the overlap check, but are not drawn and offer no studs. | +| `part.hide_others` | `ids` | Hides every placement of the submodel being edited except these. | +| `part.show` | `ids` | Shows them again; with no `ids`, shows every hidden placement in the model. | + +## Moving keeps nothing seated by itself + +`part.move` and `part.set_transform` ignore studs. To keep a moved part seated, move it by whole studs across (multiples of 20) and whole plates up or down (multiples of 8), and check with `overlap.check` afterwards. To move a part onto another part's studs, it is often simpler to delete it and `part.place` it again with `on` or a position, and read `seated` in the answer. + +## Turning in place + +- A quarter turn about Y of one 2 x 4 brick about its own origin turns it crosswise on the same spot; it may then overlap its neighbours. +- To turn a whole group as one, give all their ids: they turn about the centre of their origins and keep their places relative to one another. +- To turn about a stud, give `about` as that stud's position. + +## Repeating a row + +`part.duplicate` with a `delta` is the quickest way to repeat: duplicate one brick with `delta` `[80, 0, 0]`, then duplicate the new one, and so on. A course of five bricks becomes one brick and four duplicates. Duplicates do not snap, so pick a delta on the grid. + +## Undo + +`formblocks_undo` (or `./formblocks cli undo`) takes back the newest change, `steps` for more; `formblocks_redo` puts it back. The history is shared with the person: undo counts every change, theirs too, so undo only right after your own change, and read `labels` in the answer to see what was taken back. Parts made by an undone change lose their ids until it is redone. diff --git a/.agents/skills/formblocks-driving/sub-skills/checking-a-model/SUB-SKILL.md b/.agents/skills/formblocks-driving/sub-skills/checking-a-model/SUB-SKILL.md new file mode 100644 index 0000000..1a0edf8 --- /dev/null +++ b/.agents/skills/formblocks-driving/sub-skills/checking-a-model/SUB-SKILL.md @@ -0,0 +1,57 @@ +--- +name: checking-a-model +description: Checks a FormBlocks model after building or changing it (the overlap check, seated answers, the model tree, step and submodel lists, the open report) and counts its parts. Use before telling the person a build is done, when asked whether parts overlap or float, for a parts count or parts list, or to confirm what a model holds after opening it. +--- + +# Checking a model + +Never report a build as done from memory of the commands you sent. Read the model back and check it. + +## The overlap check + +`overlap.check` (`cmd_overlap_check`) lists every pair of placements whose bodies overlap, with the depth of the overlap in LDU. Give `ids` to check only those placements against the rest; leave it out for the whole model. It works whatever the person's overlap switch says. + +```json +{"checked": 28, "overlaps": [], "count": 0} +{"checked": 5, "overlaps": [{"submodel": "untitled.ldr", "a": "p1", "b": "p5", "depth": 23.0}], "count": 1} +``` + +- `count` 0 is the goal. +- Parts seated on each other never count, and parts that only touch face to face never count. +- The check is coarse: each part is stood in for by a box round its body, without its studs, shrunk by half an LDU. The empty space over a slope's face, inside an arch or under an overhang counts as solid, so a part tucked there is reported although it fits. Say so to the person rather than moving a part that is right. +- A depth near a whole brick (24) or plate (8) usually means a part was placed on top of another at the same height: undo it or move it. + +## Seated, or floating + +The overlap check does not find a part floating in the air. That is what `seated` in each `part.place` answer is for: keep a note of any placement that answered `seated: false` and fix or explain each one. To recheck a part later, `part.fit` with its part, rotation and position answers whether that spot seats. + +## Reading the model back + +| Read | Answers | +| --- | --- | +| `model.tree` | One submodel's steps and placements, each with id, part, colour, position, rotation, step and hidden mark, and every submodel with its uses. Pass `submodel` to read one other than the one being edited. | +| `step.list` | The steps of a submodel and their placement ids, and the step shown. | +| `submodel.list` | Every submodel with its step count, placement count and uses; unused ones are marked. | +| `formblocks_get_doc` | Everything at once, with the revision. Large on a big model. | +| `formblocks_status` | The placement count of the whole model, `dirty`, the file and the revision. | +| `model.report` | After opening a file: the lines that could not be read, and the encoding. | + +Check the counts against the plan: the number of placements, the number in each step, the parts in each colour. + +## Counting parts today + +Until the parts list commands arrive (below), count from `model.tree`: group its placements by `part` and `colour`. A use of a submodel is one placement there; count the submodel's own placements once per use to get what the build needs. + +## Looking at the result + +The person sees every change in the window as it lands. Ask them to look when a shape matters (a roof line, a face), and describe what you built in words: footprint in studs, height in bricks, colours, steps. + +## Arriving in 0.3.0 + +These commands are being added to the catalogue in 0.3.0. Check `formblocks_list_commands` before using them: until the catalogue lists them, they do not exist. The parts list commands take the ids `spec/SPEC.md` reserved for them: + +- `parts.list` (read): the parts a model needs, one row per part and colour with description, colour name and count, a submodel's parts counted once per use, parts missing from the library first. `scope` is `model`, `submodel` or `step` (up to the step shown); `group` sorts by `part` or `colour`. +- `parts.list_save` (file): the same rows written to a full path ending in `.csv`, `.tsv` or `.txt`. Like any file command from outside it waits for the person, and a path outside the model's folder asks every time. +- `part.place_at_ray` (change): places a part where a ray meets the model or the ground, as the window's pointer drops it. Its `origin`, `direction` and `rotation` are in the window's scene axes, +Y up, not the LDraw axes every other command uses; prefer `part.place` with a position or `on`. + +Read each one's parameters from the catalogue when it appears; do not guess them from these lines. diff --git a/.agents/skills/formblocks-driving/sub-skills/colours/SUB-SKILL.md b/.agents/skills/formblocks-driving/sub-skills/colours/SUB-SKILL.md new file mode 100644 index 0000000..56146a4 --- /dev/null +++ b/.agents/skills/formblocks-driving/sub-skills/colours/SUB-SKILL.md @@ -0,0 +1,57 @@ +--- +name: colours +description: Chooses and changes colours in FormBlocks by LDraw colour code, from the library's own colour table. Use when the person names a colour, when placing or recolouring parts, when a colour code is refused, or when deciding what colour 16 does inside a submodel. +--- + +# Colours + +FormBlocks offers exactly the colours of the library's colour definitions file and adds none of its own. Every command takes a colour as its LDraw code, a whole number: `colour: 4` is red. Names are for finding a code, not for passing to a command. + +## Finding a code + +`colours.list` (`cmd_colours_list`, or `./formblocks cli colours WORDS`): + +| Parameter | Use | +| --- | --- | +| `text` | Name words in any order: `dark blue`, `bluish grey`, `trans clear`. | +| `group` | One finish: `solid`, `transparent`, `chrome`, `pearl`, `metallic`, `rubber` or `material`. | +| `hue` | One hue family, written as the answer writes it: `reds`, `oranges`, `yellows`, `greens`, `blues`, `purples`, `pinks`, `browns`, `greys`. | + +Each answer row has `code`, `label` (the name with spaces), `value` (the hex colour), `edge`, `alpha` (below 255 for transparent colours), `group` and `hue`. Pick by `label`, pass the `code`. + +Codes that come up most, checked against the library's table: + +| Code | Name | Code | Name | +| --- | --- | --- | --- | +| 0 | Black | 19 | Tan | +| 1 | Blue | 25 | Orange | +| 2 | Green | 28 | Dark Tan | +| 4 | Red | 70 | Reddish Brown | +| 14 | Yellow | 71 | Light Bluish Grey | +| 15 | White | 72 | Dark Bluish Grey | +| 320 | Dark Red | 47 | Trans Clear | + +Read the table again when in doubt; a library update can add colours, and the person's library may be a different update from the one these were read from. + +## The two special codes + +- 16 is "the colour of whatever uses it". A part inside a submodel drawn in 16 takes the colour of each use of that submodel. Do not give 16 to a part of the main model: it has nothing to inherit from. +- 24 is the edge colour of the part's own colour. It is never offered as a swatch and has no use for a placement. + +## Colouring parts + +- `part.place` takes `colour` and it is required: the part is placed in it. +- `part.recolour` with `ids` and `colour` recolours placements as one undo step. Parts already in that colour are left alone; if every part already has it, nothing changes. +- Recolouring a use of a submodel in colour 16 passes the new colour to the parts inside that are in 16; parts with their own colour keep it. +- `select.by_colour` selects every visible placement in a colour, then `part.recolour` without `ids` acts on that selection. + +## Choosing colours for a build + +- One colour per role reads well: walls in one colour, roof in another, plates and trims in a grey. +- Transparent colours (`group` `transparent`) suit windows and lights; chrome, pearl and metallic suit trims. +- Ask the person when they name a colour that matches several codes (there are many greys and blues). Show the labels, not just the codes. + +## Edge cases + +- A model opened from a file may use a code the library does not define. It keeps that number and saves it unchanged; it is drawn in a neutral grey. +- A negative code is refused ("colour must be a colour code from 0"). diff --git a/.agents/skills/formblocks-driving/sub-skills/connect-and-status/SUB-SKILL.md b/.agents/skills/formblocks-driving/sub-skills/connect-and-status/SUB-SKILL.md index 1b85788..9a6e2dd 100644 --- a/.agents/skills/formblocks-driving/sub-skills/connect-and-status/SUB-SKILL.md +++ b/.agents/skills/formblocks-driving/sub-skills/connect-and-status/SUB-SKILL.md @@ -7,7 +7,7 @@ description: Connects an agent program to FormBlocks's MCP server, makes the fir ## Registering the server -The server is the launcher's `mcp` command: `/formblocks mcp` on stdio (`formblocks.bat mcp` on Windows). The checkout already carries the registration for agent programs started inside it: `.mcp.json`, `.codex/config.toml` and `.cursor/mcp.json` name the server `formblocks`. To register it for an agent program everywhere, the person runs `./formblocks agents install` (with `--dry-run` first to see what would change); it writes the same entry into each program's own settings. +The server is the launcher's `mcp` command: `[checkout]/formblocks mcp` on stdio, where `[checkout]` is the folder FormBlocks was cloned or installed into (`formblocks.bat mcp` on Windows). The checkout already carries the registration for agent programs started inside it: `.mcp.json`, `.codex/config.toml` and `.cursor/mcp.json` name the server `formblocks`. To register it for an agent program everywhere, the person runs `./formblocks agents install` (with `--dry-run` first to see what would change); it writes the same entry into each program's own settings. `./formblocks mcp` is a bridge to the running engine when one answers on this computer, so the window shows every change; when none answers it works alone on the same data folder (headless). `--connect HOST:PORT` (or `auto`) insists on a running engine and never falls back; `--headless` never looks for one; `--settings-dir ''` gives a throwaway data folder for a trial. A program started from a tab of the window's agent dock is already connected over HTTP; see `sub-skills/agent-dock/SUB-SKILL.md`. @@ -20,16 +20,7 @@ The server is the launcher's `mcp` command: `/formblocks mcp` on stdio ## When a change waits -Reading and view commands never wait. A change or file command (and undo and redo) from an outside agent is gated by the person: - -| `outside_agents` | `engine` | What happens to a change | -| --- | --- | --- | -| `ask` | `running` | The window asks the person; the call waits up to two minutes for the answer. | -| `allowed`, or this program allowed before | either | It runs at once. | -| `blocked` | either | Refused: nothing was changed. | -| `ask` | `headless` | Refused: the app is not open, so nobody can allow it. Ask the person to start FormBlocks, then try again. | - -A refusal says which of these it was. When the person declines, do not send the same change again another way; say what you wanted to do and let them choose. +Reading and view commands never wait. A change or file command (and undo and redo) from an outside agent waits for the person in the window, or is refused when nobody can be asked. `sub-skills/working-with-the-person/SUB-SKILL.md` says when the window asks, what each answer does, and what to do after a decline. ## Results and errors diff --git a/.agents/skills/formblocks-driving/sub-skills/files/SUB-SKILL.md b/.agents/skills/formblocks-driving/sub-skills/files/SUB-SKILL.md new file mode 100644 index 0000000..f5f2488 --- /dev/null +++ b/.agents/skills/formblocks-driving/sub-skills/files/SUB-SKILL.md @@ -0,0 +1,53 @@ +--- +name: files +description: Opens, starts, saves and exports FormBlocks models, and says what .fblk, .ldr, .mpd and .dat files each keep. Use when asked to save, save as, export to LDraw, open or import a model file, start a new model, insert one model into another, or when a save or open is refused or asks the person. +--- + +# Files + +## The kinds of file + +| File | What it is | What it keeps | +| --- | --- | --- | +| `.fblk` | FormBlocks' project file. | The whole model as an LDraw multi-part document (every submodel, placement, colour, position, rotation, step and step name) plus FormBlocks' own state in `0 !FORMBLOCKS` lines: the step shown, hidden parts, open tree rows, snap and grid, current colour, camera and the library update. Renamed to `.mpd` it opens in any LDraw program that reads multi-part files. | +| `.ldr` | An LDraw model. | Parts, colours, positions, rotations, steps and step names. No hidden marks, no view state. It may hold submodels too. | +| `.mpd` | An LDraw multi-part document. | The same as `.ldr`, with each submodel in its own `0 FILE` block; the usual name for a model with submodels. | +| `.dat` | An LDraw part file from the library. | Opened, it becomes a new model holding one placement of that part. Never written. | + +A saved file holds references to parts (`3001.dat`), never a part's own lines. Files are written UTF-8 with CR LF line ends, and a save writes a new file beside the old one before putting it in place, so a failed save never leaves half a file. + +## The commands + +| Command | Kind | Parameters | What it does | +| --- | --- | --- | --- | +| `model.new` | file | `discard` | Starts a new model named Untitled with one empty step and a new history. | +| `model.open` | file | `path`, `discard` | Opens a `.fblk`, `.ldr`, `.mpd` or `.dat` file. | +| `model.save` | file | none | Saves to the `.fblk` the model came from. A model never saved, or opened from an LDraw file, has none: use `model.save_as`. | +| `model.save_as` | file | `path` | `.fblk` saves the project and makes it the model's file; `.ldr` or `.mpd` exports LDraw and leaves the model's file as it was. Any other ending is refused. | +| `model.insert` | change | `path`, `position`, `submodel` | Brings another `.ldr`, `.mpd` or `.fblk` in as new submodels and places one use of its main model (at `position`, or the origin). | +| `model.recent` | read | none | The last ten files opened or saved, newest first, each with whether it still exists. | +| `model.report` | read | none | What opening reported: lines that could not be read, with their numbers, and the text encoding. | + +## Paths + +- Through MCP, give a full path. Ask the person where they want the file when they have not said. +- On the command line a relative `path` is read from the folder the command was run in. +- A `.fblk` and an LDraw copy are separate writes: `model.save_as` with `/home/me/models/house.fblk`, then with `/home/me/models/house.ldr`. + +## Unsaved changes + +`model.new` and `model.open` refuse while the open model has unsaved changes ("discard: the open model has unsaved changes"). `formblocks_status` answers `dirty`. Ask the person: save first with `model.save` or `model.save_as`, or pass `discard: true` only once they have said to drop the changes. Never discard to get past the refusal on your own. + +## The person's approval + +File commands sent from outside the window wait for the person, like changes (`sub-skills/working-with-the-person/SUB-SKILL.md`). `model.save_as` to a path outside the folder of the model's own file asks every time, even when the person has allowed your program always; a model with no file yet has no folder, so its first `model.save_as` always asks. Say where you are about to write before you send it. + +## Opening files from elsewhere + +- An `.ldr` or `.mpd` from another LDraw program opens with every part reference, submodel and step. Lines FormBlocks does not use (comments, unknown commands) are kept in place and written back. +- `model.open` answers `issueCount` and the first issues; `model.report` lists them all. A file that is not UTF-8 is read as code page 1252. +- A part the library does not have is kept, drawn as a warning box and saved unchanged. + +## After saving + +Read the answer: `written` (the path), `writtenKind`, `bytes`, and `dirty` false after a `.fblk` save. Exporting `.ldr` or `.mpd` does not clear `dirty`, because the project itself was not saved. diff --git a/.agents/skills/formblocks-driving/sub-skills/finding-parts/SUB-SKILL.md b/.agents/skills/formblocks-driving/sub-skills/finding-parts/SUB-SKILL.md new file mode 100644 index 0000000..01af586 --- /dev/null +++ b/.agents/skills/formblocks-driving/sub-skills/finding-parts/SUB-SKILL.md @@ -0,0 +1,57 @@ +--- +name: finding-parts +description: Finds the right LDraw part in FormBlocks before placing it, with search words, categories, part numbers, moved parts and the other brick systems to avoid. Use when looking up a brick, plate, tile or slope by size or name, when a part number is refused, or when a search answers the wrong scale. +--- + +# Finding parts + +Every part is a file of the LDraw parts library on the person's computer, named by its number: `3001.dat` is the 2 x 4 brick. The model refers to the number only and never holds the part's shape. A part is placed by the number a search answers, never by a number remembered from elsewhere, because a library update can move or rename a part. + +## What a part number is + +- The file name without `.dat`: `3001`, `3023b`, `3068b`. Commands take either form, `3001` or `3001.dat`. +- Letters after the digits are part of the number. `3068b` (tile 2 x 2 with groove) and `3068` are different files; a letter often marks a later mould of the same shape. +- Some numbers carry a pattern suffix (`3001p01` and the like): a printed version of the plain part. Printed parts are left out of a search unless `printed` is true. +- A number with no file in the library is refused by `part.place` ("is not in the LDraw parts library in use"). + +## Searching + +`parts.search` (`cmd_parts_search`, or `./formblocks cli parts search WORDS --lines`): + +| Parameter | Use | +| --- | --- | +| `text` | Words of the description, a part number, keywords or a category. Word order does not matter; `2x4`, `2 x 4` and `2 by 4` are the same. | +| `category` | Limit to one category, such as `Brick`, `Plate`, `Tile`, `Slope`. | +| `printed` | `true` to include printed and stickered parts. | +| `limit`, `offset` | Paging: `limit` from 1 to 500 (20 when left out). | +| `list` | `favourites`, `recent` or `hidden`: the person's own lists in the parts palette. | + +Ranking: an exact part number first, then numbers that start with the text, then parts whose description holds every word, then parts that match only by keyword or category; shorter descriptions first within a rank. So `brick 2 x 4` answers `3001` first and `plate 2 x 4` answers `3020` first. + +Good search words name the shape and the size: `brick 1 x 2`, `plate 2 x 6`, `slope 45 2 x 2`, `slope 45 2 x 1`, `door frame`, `window 1 x 2 x 2`. Read the descriptions of the first hits rather than taking the first blindly: shorter descriptions rank first, so `tile 2 x 2` answers `Tile 2 x 2 Corner` before the plain tile, which `tile 2 x 2 with groove` finds (`3068b`). When nothing fits, use fewer words, or the library's own word for the shape: a roof is built from `slope` parts, and `roof` answers other things. + +`parts.show` (`cmd_parts_show`) answers one part's description, category, keywords, author, licence and library update. + +## Moved parts + +A part the library has renumbered is kept as a stub whose description starts with `~Moved to`. Search answers it with `moved_to` and the new part's description, and `parts.show` answers `follows`: + +``` +./formblocks cli run parts.search text=3023 limit=2 +-> 3023 "~Moved to 3023b" moved_to 3023b (Plate 1 x 2) +-> 3023b "Plate 1 x 2" +``` + +Place the number the move points to (`3023b`). A model that already names the old number keeps it and still draws and seats through the move. + +## Other systems and scales + +The library also holds parts of other brick systems at other scales, and a search for `brick 2 x 4` lists some of them among its first hits. Their descriptions start with a system word such as `Duplo`, `Quatro`, `Modulex`, `Primo` or `Scala`. Their studs do not mate with ordinary studs, so they never seat on ordinary bricks. Skip them unless the person asked for that system. + +## Before placing an unfamiliar part + +Run `part.connectors` with the number. It answers the studs and anti-studs FormBlocks finds, the body box, the footprint (`x0`, `x1`, `z0`, `z1`) and the bottom plane, in the part's own axes. That tells you where the origin is and how far the part reaches, which `references/coordinates-and-units.md` turns into a position. A part with no connectors at all (a sticker, a minifigure piece) never seats; it can only be put at an exact position. + +## No library + +`parts.search` and `part.place` both fail when no library is in use. Read `library.status` and follow `sub-skills/parts-library/SUB-SKILL.md`: the fetch is the person's to start, never yours. diff --git a/.agents/skills/formblocks-driving/sub-skills/parts-library/SUB-SKILL.md b/.agents/skills/formblocks-driving/sub-skills/parts-library/SUB-SKILL.md new file mode 100644 index 0000000..bfb1c8e --- /dev/null +++ b/.agents/skills/formblocks-driving/sub-skills/parts-library/SUB-SKILL.md @@ -0,0 +1,43 @@ +--- +name: parts-library +description: Reads whether FormBlocks has an LDraw parts library in use, and what to do when it has none. Use when a placement or search answers that no library is installed, when asked about the library's update, folder or licence, or when someone asks the agent to download or fetch the library, which only the person can consent to. +--- + +# The parts library + +FormBlocks draws and seats parts from the LDraw parts library, a set of files on the person's computer that FormBlocks never ships. Without it nothing can be searched or placed. The library is the work of its many authors, under CC BY 2.0 and CC BY 4.0; every part file names its own author and licence. + +## Reading the status + +`library.status` (`cmd_library_status`, or `./formblocks cli library status`) only reads. It answers: + +| Field | Meaning | +| --- | --- | +| `found` | Whether a library is in use. | +| `folder`, `source` | Where it is, and how it was found (the person's setting, the fetched copy, or the `FORMBLOCKS_LDRAW_DIR` environment variable). | +| `update` | The library release, such as `2026-10`. | +| `index_ready`, `indexing`, `parts` | Whether the search index is built and how many parts it lists. Search waits for the index. | +| `fetch` | A fetch in progress, if any, with its stage and progress. | +| `card` | The address, licence, consent sentence and attribution the window's library card shows. | + +Reading never fetches and never touches the network. + +## The fetch is the person's to give + +The library comes from one address, `https://library.ldraw.org/library/updates/complete.zip`, and only after the person consents: on the library card in the window, or by typing `./formblocks cli library fetch --i-consent "ADDRESS LICENCE"` themselves. The consent is theirs because the download is theirs: it uses their network and disk, and they accept the licence. + +- No MCP tool starts a fetch, and the engine refuses a fetch an agent asks for. +- Never run `library fetch` yourself, even from a shell where you could, and never type the consent words for the person. Do not look for another way to download the library. +- When there is no library: say so in one sentence, name the two ways the person can give it (the library card in the window, or the command above, run by them), and stop building until `library.status` answers `found: true`. + +## A library the person already has + +If the person says they have the library unpacked already, it is a folder holding `parts`, `p` and `LDConfig.ldr`. The person can point FormBlocks at it on the library card ("Find a folder") or with `./formblocks cli library use FOLDER`; FormBlocks reads it in place and never writes into it. Suggest this; let the person do it, or run it only when they have asked you to and named the folder. + +## Updates + +`./formblocks cli library check-update` asks the library's server whether a newer archive is offered; it is a network call, so it is the person's to run too. Saved models keep part references, so a newer library opens them unchanged; parts the library has reshaped are drawn in their new shape. + +## The attribution + +When you tell the person about the library or credit it in something you write, use the `card.attribution` sentence `library.status` answers, word for word. diff --git a/.agents/skills/formblocks-driving/sub-skills/placing-and-snapping/SUB-SKILL.md b/.agents/skills/formblocks-driving/sub-skills/placing-and-snapping/SUB-SKILL.md new file mode 100644 index 0000000..2aacd2c --- /dev/null +++ b/.agents/skills/formblocks-driving/sub-skills/placing-and-snapping/SUB-SKILL.md @@ -0,0 +1,84 @@ +--- +name: placing-and-snapping +description: Places parts in FormBlocks and seats them stud to anti-stud, on another part or on the ground, with part.place, part.fit and the on parameter. Use when putting a brick down, stacking one part on another, working out a position, reading seated and joined in an answer, or when a placement is refused or lands somewhere unexpected. +--- + +# Placing and snapping + +Read `references/coordinates-and-units.md` first if positions in LDU with -Y up are new to you. + +## Studs and anti-studs + +- A stud is the round knob on top of a part, 4 LDU high, on a 20 LDU grid. +- An anti-stud is a place on a part's underside that takes one stud: the gaps between the walls and tubes of a brick, or the inside of a tube. +- A part is seated when its anti-studs sit on another part's studs (or its studs in another part's anti-studs). Seating is how real bricks hold together, so a model built of seated parts is one that could be built. +- FormBlocks finds these connectors from each part's own geometry; `part.connectors` lists them for any part. Only ordinary studs and anti-studs exist in this version: pins, axles, clips and hinges do not seat. + +## The ground + +The ground is the plane Y = 0 and acts as an endless plate: it offers a stud at every point (10 + 20i, 0, 10 + 20k). A part with anti-studs underneath, set down on the ground with snapping on, seats on that lattice, so parts placed side by side line up stud for stud. + +## Three ways to say where + +| How | Call | When | +| --- | --- | --- | +| A position | `part.place {part, colour, position}` | You know the place: walls, rows, anything planned on the stud grid. | +| On a placement | `part.place {part, colour, on: "p12"}` | Stack on one part without working out numbers; it takes the free studs nearest that part's middle first. | +| A trial | `part.fit` with the same `part`, `rotation`, and `position` or `on` | See where it would go and what it would join, changing nothing. | + +`part.place` also takes `rotation` (the nine numbers; none when left out), `step` (the step to put it in; one past the last starts a new step), `submodel` (where it goes; the one being edited when left out) and `snap` (for this call only). + +## What snapping does with a position + +With snapping on (the person's setting, on at the first start; `snap: true` forces it for one call): + +1. FormBlocks looks for free studs and anti-studs of other parts, and of the ground, within 15 LDU of where your part's connectors would be. +2. Among the possible seats it takes the one that joins the most connector pairs, then the one nearest your position, then a fixed order, so the same call always gives the same seat. +3. A seat that would leave a stud standing under a wall of your part (half a stud off the grid, say) is refused, as real bricks would not go there. +4. With no seat in reach, the part goes to the nearest grid step instead (20 LDU across and 8 up at the Stud step, the first setting) and is not seated. + +With snapping off (`snap: false`), the part goes exactly to the position, seated or not. + +Snapping never turns a part. To seat crosswise, give the turned `rotation`. + +## Reading the answer + +The result of a `part.place`, trimmed: + +```json +{"placement": {"id": "p3", "part": "3001.dat", "colour": 4, "position": [40.0, -48.0, 0.0], "step": 1}, + "seated": true, + "joined": [{"held": 0, "placement": "p1", "connector": 13}, {"held": 2, "placement": "p2", "connector": 11}], + "marks": [[10.0, -24.0, -10.0], [50.0, -24.0, -10.0]]} +``` + +- `placement.id` is the id to use from now on. Keep it. +- `placement.position` is where it really went, which may differ from what you sent. +- `seated` true means it joined at least one pair. `joined` lists the pairs: which of your part's connectors (`held`) met which placement's connector, or a `ground` lattice point. +- A brick bridging two bricks below shows pairs with both, which is what you want in a wall. + +Check `seated` on every place. `seated: false` with the overlap check off means the part may be floating or inside another part: undo it (`formblocks_undo`) and fix the position, unless a loose part is what you meant. + +## When a placement is refused + +| Refusal | Cause | +| --- | --- | +| "is not in the LDraw parts library in use" | Wrong number. Search first (`sub-skills/finding-parts/SUB-SKILL.md`). | +| "give a position, a placement to seat on (on), or a pointer ray" | Neither `position` nor `on` was given. | +| "would overlap ... with the overlap check on" | The person turned the overlap check on and the place is taken. | +| "has no free connector that ... can seat on" | Every stud of the `on` target is taken. | +| "is hidden, and hidden parts offer no connectors" | Show the target first, or give a position. | +| "must stay within 1000000 LDU of the origin" | A sign or unit slip. | + +The full list is `references/error-codes.md`. + +## The overlap check + +The overlap check is the person's switch, off at the first start. With it on, `part.place` refuses a place where the part's body box would overlap another part's; with it off, parts may share space without a word. Either way `overlap.check` reports overlaps on demand (`sub-skills/checking-a-model/SUB-SKILL.md`). The switch, like snapping and the grid step, is the person's setting: ask before you change it, and prefer `overlap.check` after placing, which changes nothing. + +## Habits that save undo steps + +- Plan positions on the stud grid before placing: odd-length parts centre on 10 plus a multiple of 20, even-length parts on a multiple of 20. +- Try a doubtful place with `part.fit` first. +- Place lower parts before upper ones: a part seats only on what is already there. +- Use `on` for quick stacking, a position for anything that must line up. diff --git a/.agents/skills/formblocks-driving/sub-skills/selection/SUB-SKILL.md b/.agents/skills/formblocks-driving/sub-skills/selection/SUB-SKILL.md new file mode 100644 index 0000000..cbc7aa2 --- /dev/null +++ b/.agents/skills/formblocks-driving/sub-skills/selection/SUB-SKILL.md @@ -0,0 +1,38 @@ +--- +name: selection +description: Reads and sets the selection in a FormBlocks model, the set of placements the window highlights and that commands act on when no ids are given. Use when asked to select parts by id, colour or part number, to select all or invert, to show the person which parts you mean, or when a command answers that nothing is selected. +--- + +# Selection + +The selection is a list of placement ids in the submodel being edited. The window outlines it, the details panel describes it, and every `part.*` command that takes `ids` acts on it when `ids` is left out. + +Selection commands are `view` commands: they change what is shown, never the model, so they are not undo steps and never wait for the person's approval. + +## The commands + +| Command | Parameters | What it does | +| --- | --- | --- | +| `select.get` | none | Reads the selection: ids, count, how many colours, and the centre of their origins. | +| `select.set` | `ids` | Makes the selection exactly these; an empty list clears it. | +| `select.add` | `ids` | Adds to it. | +| `select.remove` | `ids` | Takes these out of it, leaving the rest. | +| `select.all` | none | Every visible placement of the submodel being edited. | +| `select.clear` | none | Nothing. | +| `select.invert` | none | Every visible placement that was not selected, letting go of the rest. | +| `select.by_colour` | `colour` | Every visible placement in that colour, or in the colours of the selection when left out. | +| `select.by_part` | `part` | Every visible placement of that part, or of the parts of the selection when left out. A printed part counts as a different part. | + +## Rules + +- Only placements of the submodel being edited can be selected. Selecting one in another submodel is refused; `submodel.enter` or `submodel.leave` first (`sub-skills/submodels/SUB-SKILL.md`). +- Hidden placements cannot be selected, and `select.all`, `select.by_colour` and `select.by_part` pass over them. +- A placed or duplicated part becomes the selection, so after `part.place` the new part is selected. +- Undo brings back the selection that went with the change it takes back. +- The selection is never written into a file. + +## When to use it + +- Prefer explicit `ids` on every change. The person can change the selection in the window at any moment, so a change that relies on it can land on parts you did not mean. +- Use the selection to show the person something: `select.set` with the ids of the parts you are about to change, then say so, and the window outlines them. +- Use the kind commands to gather ids: `select.by_part` with `3001`, then `select.get`, answers every 2 x 4 brick in the submodel being edited, ready for `part.recolour` or `part.move`. diff --git a/.agents/skills/formblocks-driving/sub-skills/steps/SUB-SKILL.md b/.agents/skills/formblocks-driving/sub-skills/steps/SUB-SKILL.md new file mode 100644 index 0000000..a3046ac --- /dev/null +++ b/.agents/skills/formblocks-driving/sub-skills/steps/SUB-SKILL.md @@ -0,0 +1,46 @@ +--- +name: steps +description: Breaks a FormBlocks model into building steps that a person can follow, and adds, names, moves, deletes and shows steps. Use when asked to make building instructions or steps, to put parts in a step, to split, rename or reorder steps, to walk through a model step by step, or when new parts land in the wrong step. +--- + +# Steps + +Each submodel has its own building steps, numbered from 1. Every placement is in exactly one step. Showing step k draws steps 1 to k and hides the later ones, which is how a person walks through the build. In a saved file, steps are separated by `0 STEP` lines and a step's name is a line of FormBlocks' own at its start, so names survive an LDraw export. + +## The commands + +| Command | Kind | Parameters | What it does | +| --- | --- | --- | --- | +| `step.list` | read | `submodel` | Each step's number, name and placement ids, and which step is shown. | +| `step.goto` | view | `index` | Shows step `index` of the submodel being edited. New parts go into the step shown. | +| `step.break_after` | change | `id` | Starts a new step after placement `id`, moving the placements after it in its step into the new step. With no `id`, adds an empty step after the step shown and shows it. | +| `step.move_parts` | change | `ids`, `step` | Moves placements into another step of their submodel; one past the last starts a new step at the end. | +| `step.rename` | change | `step`, `name`, `submodel` | Names a step; an empty name clears it. | +| `step.delete` | change | `step`, `submodel` | Deletes a step; its placements move to the start of the next step, or to the end of the step before when it was the last. A submodel keeps at least one step. | + +`part.place` takes `step` too: the step to put the part in, or one past the last to start a new step with it. Without `step` the part goes into the step shown. + +## The trap: the step shown + +`step.goto` changes where new parts go. After `step.goto` with `index` 1, every later `part.place` without `step` lands in step 1, however many steps there are. When building, give `step` on every `part.place`, or `step.goto` the last step before you continue. `step.list` answers `shown`. + +## What makes a sensible step + +A person follows instructions one step at a time, so a step should be one small, clear action: + +- One course of bricks per step for walls; one layer of plates per step. +- Parts that support others come in an earlier step than what they support. A part must never be shown floating because its support is in a later step. +- Few parts per step: about 3 to 12 for a small model. Split a long course into two steps rather than make one of 30 parts. +- Repeated units built as submodels have their own steps; the use goes into one step of the parent (`sub-skills/submodels/SUB-SKILL.md`). +- Name steps that start something new: `Walls`, `Door lintel`, `Roof`. A name is optional; do not name every step. +- Keep the last step the whole model, so `step.goto` with the last index shows everything. + +## Building straight into steps + +Start with `model.new` (one empty step). Place course 1 with `step: 1`; place the first part of course 2 with `step: 2` (one past the last, so a new step starts); the rest of course 2 with `step: 2`; and so on. The examples in `examples/` do exactly this. + +## Fixing steps afterwards + +- A model built all in one step: `step.break_after` with the id of the last part of each course, in order from the bottom, splits it. +- A part in the wrong step: `step.move_parts`. +- Check with `step.list` that each step's parts stand on parts of the same or earlier steps. diff --git a/.agents/skills/formblocks-driving/sub-skills/submodels/SUB-SKILL.md b/.agents/skills/formblocks-driving/sub-skills/submodels/SUB-SKILL.md new file mode 100644 index 0000000..a21ac07 --- /dev/null +++ b/.agents/skills/formblocks-driving/sub-skills/submodels/SUB-SKILL.md @@ -0,0 +1,44 @@ +--- +name: submodels +description: Groups placements of a FormBlocks model into named submodels that can be used many times, and edits, renames, unpacks or deletes them. Use when a build repeats a unit (a leg, a window, a wall section), when asked to group, pack, unpack or rename parts of a model, to work inside a submodel, or when placing a use of one. +--- + +# Submodels + +A model is a tree: the main model at the top, holding placements of parts and uses of submodels, each submodel holding its own placements and steps. All uses of a submodel are linked: a change inside it shows in every use. In a saved file each submodel is a `0 FILE` block named after it, with `.ldr` added. + +## The commands + +| Command | Kind | Parameters | What it does | +| --- | --- | --- | --- | +| `submodel.list` | read | none | Every submodel with title, step count, placement count and uses; one with no uses is unused. | +| `submodel.create` | change | `ids`, `name` | Packs placements of one submodel into a new submodel named `name` and puts one use in their place. | +| `submodel.dissolve` | change | `id` | Unpacks a use: its parts come back into the parent at the same places, in the use's step. The submodel goes when its last use is unpacked. | +| `submodel.independent` | change | `id`, `new_name` | Copies the submodel of one use under a new name for that use alone, so it can change without touching the others. | +| `submodel.rename` | change | `name`, `new_name` | Renames a submodel and every use of it. | +| `submodel.delete` | change | `name`, `with_uses` | Deletes a submodel that is not the main model; one still in use is kept unless `with_uses` is true, which deletes its uses too. | +| `submodel.enter` | view | `id` or `name` | Edits a submodel in place: new parts, steps and the selection then act inside it. | +| `submodel.leave` | view | none | Goes back to the submodel above. | + +## Building a repeated unit + +1. Build one unit in the main model, seated as usual. +2. `submodel.create` with its ids and a name such as `Leg`. Names must be unique and may not hold `& # | ?`; `.ldr` is added for you, so the submodel is `Leg.ldr`. +3. The answer gives the use's id and `position`. The submodel's origin is the middle of the unit's footprint at its lowest placement's origin, moved to the grid, so the use's position is not at the ground: read it, do not assume it. +4. Make more uses with `part.duplicate` of the use and a `delta` on the grid. That keeps every copy at the same height as the first. +5. Or place a use by name: `part.place` with `part` set to the submodel's name (`Leg`) and a `position`. A use is placed exactly where sent: `on` and snapping seat library parts only, so take the height from the first use's position. +6. Give the use colour `16` to let parts inside drawn in 16 take each use's colour; parts with their own colour keep it. + +## Working inside one + +- `submodel.enter` with `name` (or with `id` of a use in the submodel being edited). `model.tree` with no `submodel` then answers the submodel's own placements, in its own coordinates. +- Placements inside a submodel are in its own coordinates, relative to its origin, not to the main model. +- `submodel.leave` when done. Read `editing` in the answer: the path from the main model to where you are. +- Commands that take `submodel` (`part.place`, `model.tree`, `step.list`, `step.rename`, `step.delete`) act in that submodel without entering it, which is safer for an agent because it does not depend on what the window has entered. + +## Rules + +- A submodel can never contain a use of itself, however deep; such a place is refused. +- Packing needs placements of one submodel; ids from two are refused. +- A submodel whose last use was deleted stays in the model, unused, until deleted. +- The main model cannot be deleted. diff --git a/.agents/skills/formblocks-driving/sub-skills/working-with-the-person/SUB-SKILL.md b/.agents/skills/formblocks-driving/sub-skills/working-with-the-person/SUB-SKILL.md new file mode 100644 index 0000000..116fb29 --- /dev/null +++ b/.agents/skills/formblocks-driving/sub-skills/working-with-the-person/SUB-SKILL.md @@ -0,0 +1,57 @@ +--- +name: working-with-the-person +description: Works with the person who has FormBlocks open, whose window asks them before an outside agent changes their model. Use when a change waits or is refused, when deciding what to say before changing or saving, when the person declines, when they edit at the same time, or when undoing could take back their work. +--- + +# Working with the person in the window + +The person and the agent work on the same open model. Everything the agent changes shows in the window as it lands, goes into the same undo history, and can be undone by the person. The person decides what an outside agent may change. + +## When the window asks + +Read and view commands never ask. A `change` or `file` command, and undo and redo, sent by an outside agent through `./formblocks mcp`, waits while the window asks the person, for up to two minutes. The question names your program and the tool. + +| The person answers | What happens | +| --- | --- | +| Deny | The call is refused and nothing changes. | +| Allow once | This call runs. The next change asks again. | +| Always allow | This call runs, and later changes from a program of the same name run without asking. | + +So the first change asks, and once the person has chosen Always allow, it does not ask again, with one exception: `model.save_as` to a path outside the folder of the model's own file asks every time, whatever the person chose before. A model with no file yet has no folder, so its first save as always asks. + +`formblocks_status` answers the person's standing choice in `outside_agents`: + +| `outside_agents` | `engine` | A change | +| --- | --- | --- | +| `ask` | `running` | Waits for the person's answer. | +| `allowed`, or your program allowed always | either | Runs at once (a save outside the folder still asks). | +| `blocked` | either | Refused. | +| `ask` | `headless` | Refused: no window is open, so nobody can allow it. Ask the person to start FormBlocks. | + +A program in a tab of the window's agent dock is the person's own and is not asked (`sub-skills/agent-dock/SUB-SKILL.md`), unless agents are blocked. + +## Before the first change + +Say in one or two sentences what you are going to build or change, so the question in the window makes sense when it appears. Group the work: a person asked twenty times in a row will choose Always allow or Deny out of tiredness, and either is worse than a clear first question. + +## When the person declines + +The answer is final for that change. Do not resend it, do not do the same thing by other commands, do not try another tool. Say what you wanted to do and why, and ask what they want instead. A timeout ("Nobody answered") is not a decline: ask them to look at the window, then send it once more. + +## Saving + +Say where a file will go before `model.save_as`, and use the folder the person named. Saving next to the model's own file asks only by the person's standing choice; anywhere else asks every time, which is the person's protection against files written where they did not expect. + +## Sharing the undo history + +- `formblocks_undo` takes back the newest change in the model, whoever made it. Undo only right after your own change, and read `labels` in the answer to confirm it took back yours. +- If the person may have changed something since, read `model.tree` first and fix your mistake with a change command instead of undo. +- Every change answers `undo`, its label in the Edit menu, so you can tell the person exactly what to undo. + +## Editing at the same time + +The person can select, move and delete parts while you work. Before acting on an id you read a while ago, read it again: `formblocks_status` answers the revision, which rises with every change by either of you. Pass `ids` instead of relying on the selection. + +## Discarding + +Never pass `discard: true` to `model.new` or `model.open` unless the person has said, in this conversation, to drop their unsaved changes. diff --git a/.agents/skills/formblocks-harness/SKILL.md b/.agents/skills/formblocks-harness/SKILL.md index 7a1acf0..4b35a4d 100644 --- a/.agents/skills/formblocks-harness/SKILL.md +++ b/.agents/skills/formblocks-harness/SKILL.md @@ -1,10 +1,10 @@ --- name: formblocks-harness -description: "Use when asked to install, boot, verify, debug or extend the FormBlocks repository (the formblocks launcher, formblocks_engine.py, the engine's LDraw reader, parts library, part meshes, connection model and model commands). Works on the checkout itself as a developer agent: the ./formblocks dispatcher and setup scripts, ports 5330, 5331 and 8330, the engine selfcheck, the health probe and MCP smoke scripts, the CLAUDE.md laws (hand-made single-region edits, zero DOM flash, tokens only, no emoji, HASHOUT logs, one commit identity, the clean room and spec/ as the authority), and the three places a feature is added: a command, a router and a pane. Not for building models in a running FormBlocks through MCP; that is the formblocks-driving skill." +description: "Use when asked to install, boot, verify, debug, extend or release the FormBlocks repository itself: its engine code (the LDraw reader, parts library, part meshes, connection model, the model and its command catalogue), its window, its setup scripts or its skill packs. Works on the checkout as a developer agent: the ./formblocks launcher, ports 5330, 5331 and 8330, doctor, selfcheck, the contract checker, agents check, looking at the window headless, the health probe and MCP smoke scripts, the CLAUDE.md laws (hand-made single-region edits, zero DOM flash, tokens, no emoji, HASHOUT logs, one commit identity), the clean room with spec/ as the authority, the packages and their dependency order, and adding a command, a connector kind, a router or a pane. Also the parts library and its scratch copy for checks, freezing the engine and the release. Not for building models in a running FormBlocks through its MCP tools or command line; that is formblocks-driving." license: Apache-2.0 metadata: product: FormBlocks - pack-version: "0.2.0" + pack-version: "0.3.0" audience: developer agent --- @@ -21,9 +21,14 @@ The pack never repeats what the code can tell you. Command names come from the c | A fresh clone, installing, booting, ports, environment variables, the data folder, the window key | `sub-skills/install-and-boot/SUB-SKILL.md` | | Proving a change: doctor, selfcheck, typecheck, health probe, MCP smoke, agents sync check, the contract check | `sub-skills/verify/SUB-SKILL.md` | | Before editing anything: the laws, hand-made edits, HASHOUT logs, version sites, commits, licences, clean room | `sub-skills/laws-and-logs/SUB-SKILL.md` | +| What may be read and copied, spec/ as the authority, a change of behaviour starting in spec/ | `sub-skills/clean-room-and-spec/SUB-SKILL.md` | +| The engine's packages (ldraw, library, mesh, connect, doc, cmd and above), their dependency order, where new code goes | `sub-skills/packages/SUB-SKILL.md` | | Adding or changing a command of the catalogue, and the MCP tool and references made from it | `sub-skills/add-command/SUB-SKILL.md` | +| Adding a connector kind (pins, axles, clips, hinges) as a registered module, or fixing a kind's data | `sub-skills/add-connector-kind/SUB-SKILL.md` | +| The parts library: where the engine finds it, the consent-gated fetch, the scratch copy for checks, its caches | `sub-skills/parts-library-and-scratch/SUB-SKILL.md` | | Adding an engine route under `/api`, its guard and where it is mounted | `sub-skills/add-router/SUB-SKILL.md` | | Adding a pane or another part of the window without a flash | `sub-skills/add-pane/SUB-SKILL.md` | +| Freezing the engine, desktop builds, data files the freeze carries, dependencies, versions and the release | `sub-skills/freeze-and-ship/SUB-SKILL.md` | For any task that edits files, load `laws-and-logs` as well as the specialist. It is short and its rules are not negotiable. @@ -44,11 +49,14 @@ These come from `CLAUDE.md` and the owner checks them on every change. `sub-skil - SEDO: edit tracked files only with hand-made single-region edits made with the editing tool. Never `sed -i`, `awk`, `patch`, `git apply`, codemods or edit scripts on tracked files. New files are written whole. - Zero DOM flash: every container exists in its final layout before the first paint; script patches nodes in place. - Colours, spacing and every `z-index` come from the tokens in `frontend/src/styles/tokens.css`; icons are inline `currentColor` SVG from `frontend/src/ui/icons.ts`. -- No emoji anywhere and no em dash (U+2014) in markdown. Near-zero comments; reasons go into the `HASHOUT_LOG.md` beside the code. +- No emoji anywhere and no em dash (U+2014) or en dash (U+2013) anywhere. Near-zero comments; reasons go into the `HASHOUT_LOG.md` beside the code. - The engine owns all state; the window renders and dispatches. Every write route needs the window key. +- Clean room: write from `spec/` and the public LDraw documentation only, and change `spec/` before changing behaviour (`sub-skills/clean-room-and-spec/SUB-SKILL.md`). +- The parts library is never committed, bundled or fetched without the person's consent (`sub-skills/parts-library-and-scratch/SUB-SKILL.md`). - No new dependency without a `NOTICE.md` row first. GPL and AGPL never enter a distributed build. - Commits carry the one identity `CLAUDE.md` names and no `Co-Authored-By` or other attribution line. - Write no tests unless the owner asks; verification is the checks in `sub-skills/verify/SUB-SKILL.md`. +- Several agents may run the app from one tree: boot on ports and a data folder of your own (`FORMBLOCKS_PORT`, `FORMBLOCKS_DATA_DIR`), and stop only the processes you started, by their process id. ## Scripts in this pack @@ -62,3 +70,5 @@ Run them, do not read them into context. Both use the Python standard library on ## Reference `references/ports-and-env.md` holds the port table, every `FORMBLOCKS_*` variable with who reads it, and what the engine keeps in its data folder. Load it when you need an exact variable or path. + +`evals/evals.json` holds the pack's evaluations and trigger tests, for whoever changes this pack. diff --git a/.agents/skills/formblocks-harness/evals/evals.json b/.agents/skills/formblocks-harness/evals/evals.json new file mode 100644 index 0000000..786052f --- /dev/null +++ b/.agents/skills/formblocks-harness/evals/evals.json @@ -0,0 +1,77 @@ +{ + "skill_name": "formblocks-harness", + "notes": "Run in a FormBlocks checkout with the engine venv installed. Expected behaviours are visible in the transcript, the diff and the commit.", + "evals": [ + { + "id": 1, + "name": "add-a-read-command", + "prompt": "Add a read-only command to FormBlocks that counts the studs left free on top of the model, so agents can call it.", + "files": [], + "expected_behavior": [ + "Writes the rule into spec/SPEC.md and section 21.2 before the code, in its own commit", + "Adds the command with @command, a title, one sentence, kind read, in backend/app/cmd/commands/", + "Runs the selfcheck, ./formblocks cli commands with the id, a run on a throwaway folder, ./formblocks agents sync and agents check", + "Logs the reason in backend/HASHOUT_LOG.md in the same commit and edits files only by hand-made single-region edits" + ] + }, + { + "id": 2, + "name": "pin-connector-kind", + "prompt": "We need pins and pin holes to connect in FormBlocks. Add them.", + "files": [], + "expected_behavior": [ + "Starts in spec/CONNECTIONS.md and reads the library's own primitive files, never another program's connection data", + "Adds a module in backend/app/connect/kinds/ that registers itself, with its data in JSON beside it and a version for the cache", + "Checks part.connectors on real parts against hand-worked numbers, with a throwaway data folder and FORMBLOCKS_LDRAW_DIR, and confirms 3001 still answers 8 studs and 11 anti-studs" + ] + }, + { + "id": 3, + "name": "window-change-looked-at", + "prompt": "Add a small panel under the colour palette that shows how many parts the model has. Make sure it does not flicker.", + "files": [], + "expected_behavior": [ + "Writes the panel's whole structure once in onShellMounted and patches it from the doc store with the ui/dom.ts helpers", + "Uses tokens from styles/tokens.css and no raw colour or numeric z-index", + "Builds and opens the window headless on ports of its own, screenshots it, and reports the layout shift score under 4x CPU and network throttling" + ] + }, + { + "id": 4, + "name": "library-in-a-fixture", + "prompt": "Copy a few LDraw part files into the repo so the checks can run without the library.", + "files": [], + "expected_behavior": [ + "Refuses to commit any part of the LDraw library and explains why", + "Offers FORMBLOCKS_LDRAW_DIR pointing at a copy outside the tree, and checks that need no parts" + ] + }, + { + "id": 5, + "name": "adjacent-driving-task", + "prompt": "Use FormBlocks to build me a red wall of bricks.", + "files": [], + "expected_behavior": [ + "Recognises a model-building task and moves to formblocks-driving instead of editing source" + ] + } + ], + "trigger_evals": [ + { "query": "add a new command to the FormBlocks engine", "should_trigger": true }, + { "query": "formblocks wont boot, port 8330 busy, help", "should_trigger": true }, + { "query": "Please run the selfcheck, the contract checker and agents check on the FormBlocks checkout.", "should_trigger": true }, + { "query": "add a connector kind for axles to formblocks", "should_trigger": true }, + { "query": "freeze the formblocks engine and build the desktop app", "should_trigger": true }, + { "query": "fix the flicker in the formblocks parts palette", "should_trigger": true }, + { "query": "where does the LDraw reader live in the formblocks code and what may it import", "should_trigger": true }, + { "query": "update the formblocks skill packs and sync the mirrors", "should_trigger": true }, + { "query": "build a house with a roof in FormBlocks", "should_trigger": false }, + { "query": "place a 2 x 4 brick on p12 and save the model", "should_trigger": false }, + { "query": "what colour code is dark bluish grey in FormBlocks", "should_trigger": false }, + { "query": "add a command to the FormAnything app studio", "should_trigger": false }, + { "query": "write a Tauri app from scratch", "should_trigger": false }, + { "query": "export my open FormBlocks model to .ldr", "should_trigger": false }, + { "query": "explain the LDraw file format to me", "should_trigger": false }, + { "query": "register the formblocks MCP server with my agent program", "should_trigger": false } + ] +} diff --git a/.agents/skills/formblocks-harness/references/ports-and-env.md b/.agents/skills/formblocks-harness/references/ports-and-env.md index 09cf1bd..e9d6975 100644 --- a/.agents/skills/formblocks-harness/references/ports-and-env.md +++ b/.agents/skills/formblocks-harness/references/ports-and-env.md @@ -25,6 +25,12 @@ Set them in the shell. A `backend/.env` file is read with `setdefault`, so a rea | `FORMBLOCKS_PORT` | setup scripts, engine | The engine's port (default 8330). | | `FORMBLOCKS_BACKEND_PORT` | `frontend/vite.config.ts` | Development only: the engine port the window proxies to. | | `FORMBLOCKS_DATA_DIR` | engine | The data folder. Default: the platform's app data folder under `FormBlocks`. | +| `FORMBLOCKS_LDRAW_DIR` | engine (`library/locate.py`) | A parts library folder to use when the settings name none; how a check runs against a library unpacked by hand. Nothing from it is ever committed. | +| `FORMBLOCKS_HOST` | `formblocks_engine.py`, `boot_backend.bat` | The address the engine binds; 127.0.0.1 unless changed, with a warning when it is not loopback. | +| `FORMBLOCKS_URL`, `FORMBLOCKS_TOKEN` | `./formblocks mcp` bridge, `cli` | The running engine's address and window key, instead of reading `engine.port` and `session.token` from the data folder. | +| `FORMBLOCKS_CALLER_DIR` | `setup/cli` | The folder `cli` was run from, so a relative `path` is read from there. Set by the launcher. | +| `FORMBLOCKS_SHELL_PID` | engine | The desktop shell's pid, so the engine ends with the shell. Set by the shell. | +| `FORMBLOCKS_WINDOW_PORT`, `FORMBLOCKS_PREVIEW_PORT`, `FORMBLOCKS_ROOT` | `setup/lib.sh` | Set by the setup scripts themselves (5330, 5331, the checkout); not read from the environment. | | `FORMBLOCKS_PORTABLE` | engine | `1` keeps the data beside the app, in `FormBlocksData`. | | `FORMBLOCKS_DIST` | engine, `setup/serve` | A built window folder to serve instead of `frontend/dist`. | | `FORMBLOCKS_DESKTOP` | engine | `1` when the desktop shell started the engine. | diff --git a/.agents/skills/formblocks-harness/sub-skills/add-command/SUB-SKILL.md b/.agents/skills/formblocks-harness/sub-skills/add-command/SUB-SKILL.md index cd7bf01..1b45a0c 100644 --- a/.agents/skills/formblocks-harness/sub-skills/add-command/SUB-SKILL.md +++ b/.agents/skills/formblocks-harness/sub-skills/add-command/SUB-SKILL.md @@ -33,7 +33,8 @@ Load `sub-skills/laws-and-logs/SUB-SKILL.md` first. A command is the only way an The function takes the document and the parameters by name and returns a small dict. It refuses bad input with `CommandError("A plain sentence.")`, which every surface shows as it is; name the parameter in it. Parameter types are `string`, `integer`, `number`, `boolean` and `array` (with `items` and lengths); give strings a maximum length. Pass `kind="read"` for a command that only reads and `kind="view"` for one that changes only the view. 3. Change only the model through `doc.model` (`edit_placement`, `edit_submodel`, `insert`, `take_out`: values are copied on write, so never change one in place) or the view in `doc.view`; never write files, start processes or keep state of your own there. Set `doc.label` for an undo label such as "Move 3 parts". Anything the window must show comes from the document, never from the command's return value alone. 4. Run `./formblocks agents sync`. It rewrites `agents/manifest.json` and the generated tool reference in the formblocks-driving pack, and mirrors the skills. The MCP server gains one tool for the command; read its name from `tools/list`, never guess it. -5. Verify: the selfcheck (its `commands` count goes up by one), `./formblocks cli commands ` to see the entry, `./formblocks cli run key=value --settings-dir ''` once on a throwaway folder, `./formblocks agents sync --check`, then `scripts/mcp_smoke.py`. Log the decision in `backend/HASHOUT_LOG.md` in the same commit. +5. Verify: the selfcheck (its `commands` count goes up by one), `./formblocks cli commands [id]` to see the entry, `./formblocks cli run [id] key=value --settings-dir ''` once on a throwaway folder, `./formblocks agents sync --check`, then `scripts/mcp_smoke.py`. Log the decision in `backend/HASHOUT_LOG.md` in the same commit. +6. Keep the documents in step: `spec/SPEC.md` section 21.2 lists every catalogue command with its kind, and a command added is added there in the same change (`sub-skills/clean-room-and-spec/SUB-SKILL.md`). Tell whoever owns the formblocks-driving pack, so the sub-skill for that area names the new command. ## Changing a command diff --git a/.agents/skills/formblocks-harness/sub-skills/add-connector-kind/SUB-SKILL.md b/.agents/skills/formblocks-harness/sub-skills/add-connector-kind/SUB-SKILL.md new file mode 100644 index 0000000..a2075b1 --- /dev/null +++ b/.agents/skills/formblocks-harness/sub-skills/add-connector-kind/SUB-SKILL.md @@ -0,0 +1,52 @@ +--- +name: add-connector-kind +description: Adds a connector kind to FormBlocks' connection model as a module that registers itself in backend/app/connect/kinds/, with its data beside it as JSON. Use when adding pins, axles, clips, bars, hinges or any joint beyond studs and anti-studs, when correcting the primitive list of an existing kind, or when a part's connectors come out wrong. +--- + +# Add a connector kind + +Load `sub-skills/laws-and-logs/SUB-SKILL.md` and `sub-skills/clean-room-and-spec/SUB-SKILL.md` first. The mechanics are `spec/CONNECTIONS.md`, "Adding a kind"; this page is the working order. The connection service never names a kind: adding one adds a module, and changes nothing in the service, the connector shape, the overrides format or the cache. + +## Before any code + +1. Write the kind into `spec/CONNECTIONS.md` first, in its own commit: what it is, what it mates with, the freedom a mate leaves, how it is found in a part's geometry. +2. Read the official primitive files the kind will claim, from the library (`FORMBLOCKS_LDRAW_DIR` on a check machine, `sub-skills/parts-library-and-scratch/SUB-SKILL.md`), and record their geometry in your own words, as `spec/CONNECTIONS.md` does for studs. +3. Work at least three real parts through the rule by hand before writing the module, and keep the numbers for the check below. +4. Never copy a primitive list, a tolerance or a connection table from another program's data; the list comes from reading the library's own primitives. + +## Where the module lives + +- `backend/app/connect/kinds/[kind].py`, one module per kind or per family of kinds. `kinds.load()` imports every module in the package whose name does not start with `_`, in name order, so no list is edited anywhere. +- The module's data (primitive file names, tolerances) sits beside it as `[kind].json` and is read when the module loads, so a list can be corrected without touching code. A data file that cannot be read stops the engine with a sentence naming the file. +- At the end of the module, one call per kind: `PIN = register(PinKind())`. + +## What the module provides + +A subclass of `Kind` from `backend/app/connect/kinds/__init__.py`: + +| Member | Purpose | +| --- | --- | +| `name` | The kind's name: lower case letters, digits and `_`. `register` refuses anything else, and refuses a second module registering the same name. | +| `mates_with` | The kinds it pairs with; the registry makes pairing symmetric. | +| `version` | Part of the connector cache key. Raise it whenever the kind's rule or data changes, so cached parts are derived again. | +| `body` | Whether the triangles of files it claims count in the overlap check's body box. | +| `claims(file_name)` | True for the primitive files that are this kind's connectors; the walk does not descend into a claimed file. | +| `from_reference(file_name, transform)` | The connectors one claimed reference makes, in part coordinates. | +| `settle(mesh, own)` | Optional: correct this kind's connectors once the walk is over and the bottom plane is known. | +| `from_mesh(mesh, connectors)` | Optional: connectors found from the whole flattened part. | +| `mate(a, b)` | `None`, or a `Mate`: the correction that brings `a` onto `b`, the residual, and the `Freedom` left (`Freedom.spin`, `slide`, `hinge` or `fixed`). `axial_mate` covers round connectors on a shared axis. | +| `blocks(connector, other)` | Optional: a blocked test of the kind's own, as the stud's blocked-stud test is. | + +Connectors already carry `ref` (for kinds whose turn about the axis matters) and `length` (for kinds that slide), so the connector shape does not change. + +## Overrides + +`backend/app/connect/overrides.json` corrects the derivation for single parts. Entries may name the new kind as soon as the module exists. Each entry changes the cache key of the parts it touches. + +## Check + +1. Selfcheck: `backend/venv/bin/python backend/formblocks_engine.py --selfcheck` imports the kinds. +2. With a library in reach, `./formblocks cli run part.connectors part=[number]` for each part you worked by hand: the counts, positions, axes and `source` must match your numbers. Run it with a throwaway data folder (`--settings-dir ''`) so no old cache answers. +3. Place two parts that should mate with `part.fit` and `part.place` and read `seated` and `joined`; run `overlap.check`. +4. Check the stud kind still answers as before: `part.connectors` for `3001` gives 8 studs and 11 anti-studs, as `spec/CONNECTIONS.md` Example 1 works out. +5. Log the kind, its sources and the parts you checked in `backend/app/connect/HASHOUT_LOG.md`, in the same commit as the module. diff --git a/.agents/skills/formblocks-harness/sub-skills/add-pane/SUB-SKILL.md b/.agents/skills/formblocks-harness/sub-skills/add-pane/SUB-SKILL.md index fd6e6e4..8524f05 100644 --- a/.agents/skills/formblocks-harness/sub-skills/add-pane/SUB-SKILL.md +++ b/.agents/skills/formblocks-harness/sub-skills/add-pane/SUB-SKILL.md @@ -10,18 +10,19 @@ Load `sub-skills/laws-and-logs/SUB-SKILL.md` first. The window renders what the ## How the window is put together - `frontend/index.html` boots the theme in an inline script before anything paints and keeps `#app` hidden until the shell is mounted and the fonts are ready. -- `frontend/src/app.ts` is the composition root. `startApp()` writes the shell once (top bar, side panel, main area, status bar) and calls every hook registered with `onShellMounted(fn)`, handing each the hosts: `hosts.topbar`, `hosts.tools`, `hosts.menu`, `hosts.panel`, `hosts.main`, `hosts.status`. -- Each part is a module under `frontend/src/ui/` that registers itself: `notes-view.ts` fills `hosts.main` (the template's starter view, which the viewport will replace), `side-panel.ts` fills `hosts.panel`, `status.ts` fills `hosts.status`. `frontend/src/main.ts` imports each once for its side effect. -- Engine state reaches the window through stores: `ui/doc-store.ts` (the document, with the ids that changed), `io/catalogue.ts` (the command catalogue). Subscribe with `onChange`; never fetch on a timer. +- `frontend/src/app.ts` is the composition root. `startApp()` mounts the shell once and runs every hook registered with `onShellMounted(fn)`, handing each the hosts. +- `frontend/src/ui/shell.ts` holds `SHELL`, the whole window's markup, and `ShellHosts`, the named hosts a module fills: `topbar`, `menu`, `fileTools`, `tools`, `panel` (the parts palette), `main`, `viewport`, `hud`, `right`, `colours`, `tabs`, `details`, `strip` (the step controls) and `status`. Read the file for the current list; the window lane changes it. +- Each part is a module under `frontend/src/ui/` (or `frontend/src/view/` for the 3D viewport) that registers itself. `frontend/src/main.ts` imports the shell's own modules once each for their side effect; feature modules are imported once each from `frontend/src/ui/features.ts`. +- Engine state reaches the window through stores: `ui/doc-store.ts` (the document, with the ids that changed), `io/catalogue.ts` (the command catalogue), `io/settings.ts`, `io/library.ts`, and `io/live.ts` (the engine's live channel). Subscribe; never fetch on a timer. - Commands go out through `ui/run.ts` (`runCommand(name, params)`), which sends the window key; the pane shows a result only when the revision comes back. ## Steps -1. Write `frontend/src/ui/.ts`. In `onShellMounted(({ hosts }) => { ... })`, write the pane's whole structure into its host once, with `innerHTML` or `el()`, including every empty line, count and button it will ever show, so nothing appears or moves later. -2. Fill it from a store: subscribe with `docStore.onChange` or `catalogue.onChange`, and patch with the helpers in `ui/dom.ts`: `patchList` keeps rows by key and touches only changed ones, `setText`, `setHidden`, `setDisabled`, `setAttr` write only when the value differs. Never rebuild a live container to change one node. -3. Add one line to `frontend/src/main.ts`: `import './ui/';`. -4. Style it in `frontend/src/styles/.css`, linked once in `frontend/index.html` beside the others. Every colour, space, size and layer is a `var(--...)` from `styles/tokens.css`; add a token there when none fits. No raw colour, no numeric `z-index`. -5. Icons: add a hand-written inline `currentColor` SVG to `ui/icons.ts` and use `icon('')`. No icon library, no copied icon art. -6. A window command (a button, a menu item, a key) is added with `commands.add({ id, title, summary, icon, group, keys, run })` from `ui/commands.ts`, so the palette, the menu and the keys all find it. A command that changes the document calls `runCommand` with an engine command; it never changes the view directly. -7. A new region of the shell (a second panel, a tab strip) is a change to `SHELL` in `app.ts` and to the grid in `styles/shell.css`. Make it only when no existing host fits, and log why in `frontend/HASHOUT_LOG.md`. -8. Verify: `npm run typecheck` and `npm run build` in `frontend/`, then a hard reload under 4x CPU and network throttling: the first frame shows the pane in its final place and nothing shifts. Say what you saw, or that it was not run. Log the decision in `frontend/HASHOUT_LOG.md` in the same commit. +1. Write `frontend/src/ui/[name].ts`. In `onShellMounted(({ hosts }) => { ... })`, write the pane's whole structure into its host once, with `innerHTML` or `el()` from `ui/dom.ts`, including every empty line, count and button it will ever show, so nothing appears or moves later. +2. Fill it from a store and patch with the helpers in `ui/dom.ts`: `patchList` keeps rows by key and touches only changed ones; `setText`, `setHidden`, `setDisabled`, `setAttr`, `setClass`, `setTitle` and `setHtml` write only when the value differs. Never rebuild a live container to change one node. +3. Add one line to `frontend/src/ui/features.ts`: `import './[name]';`. +4. Style it in `frontend/src/styles/[name].css`, linked once in `frontend/index.html` beside the others. Every colour, space, size and layer is a `var(--...)` from `styles/tokens.css`; add a token there when none fits. No raw colour, no numeric `z-index`. Interface text goes in `ui/strings.ts`. +5. Icons: add a hand-written inline `currentColor` SVG to `ui/icons.ts` and use `icon('[name]')`. No icon library, no copied icon art, never a three-star sparkle. +6. A window command (a button, a menu item, a key) is added through `commands` in `ui/commands.ts`, so the palette, the menu and the keys all find it. A command that changes the document calls `runCommand` with an engine command; it never changes the view directly. +7. A new region of the shell is a change to `SHELL` and `ShellHosts` in `ui/shell.ts` and to the grid in `styles/shell.css`. Make it only when no existing host fits, and log why in `frontend/HASHOUT_LOG.md`. +8. Verify: `npm run typecheck` and `npm run build` in `frontend/`, then look at the window headless (`sub-skills/verify/SUB-SKILL.md`, "Looking at the window"): a screenshot of the pane, and a hard reload under 4x CPU and network throttling with a layout shift score of 0. Say what you looked at, or that it was not run. Log the decision in `frontend/HASHOUT_LOG.md` in the same commit. diff --git a/.agents/skills/formblocks-harness/sub-skills/add-router/SUB-SKILL.md b/.agents/skills/formblocks-harness/sub-skills/add-router/SUB-SKILL.md index 0f36fec..4dd6824 100644 --- a/.agents/skills/formblocks-harness/sub-skills/add-router/SUB-SKILL.md +++ b/.agents/skills/formblocks-harness/sub-skills/add-router/SUB-SKILL.md @@ -13,12 +13,12 @@ Anything that changes the document is a command (`sub-skills/add-command/SUB-SKI ## Steps -1. Write `backend/app/routers/.py` with `router = APIRouter(tags=[""])` and its handlers. Keep the work in a service or the document, not in the handler: the handler reads the request, calls one function and returns a small JSON object. Run blocking work with `run_in_threadpool`, as `routers/commands.py` does. -2. Mount it with one line in the `ROUTERS` list of `backend/app/main.py`: `("app.routers.", "/api")`, or a longer prefix. Add the line only after the module imports cleanly, then run the selfcheck at once: it imports every router and prints the count. +1. Write `backend/app/routers/[name].py` with `router = APIRouter(tags=["[name]"])` and its handlers. Keep the work in a service or the document, not in the handler: the handler reads the request, calls one function and returns a small JSON object. Run blocking work with `run_in_threadpool`, as `routers/commands.py` does. +2. Mount it with one line in the `ROUTERS` list of `backend/app/main.py`: `("app.routers.[name]", "/api")`, or a longer prefix. Add the line only after the module imports cleanly, then run the selfcheck at once: it imports every router and prints the count. 3. Leave the guard alone. `backend/app/core/guard.py` refuses a request from another computer or a foreign origin, and asks every `/api` and `/mcp` path for the window key in the `x-formblocks-token` header, except the short open list (`/api/health`). A new route is guarded the moment it is mounted. Adding a path to the open list is a security decision: log the reason in `backend/HASHOUT_LOG.md` and say so in your report. 4. Outside agents never call `/api` routes; they come in through MCP. If an agent needs what the route gives, expose it as a read-only command or an MCP tool instead of opening the route. 5. If the window calls the route, call it through the engine client in `frontend/src/io/api.ts`, which sends the key; never with a bare `fetch`. -6. Verify: compile, selfcheck, boot, then `curl -s 127.0.0.1:8330/api/` answers 401 or 403 without the key (the guard working) and the window gets its answer with it. Log the route in `backend/HASHOUT_LOG.md` in the same commit. +6. Verify: compile, selfcheck, boot (on a port of your own, `FORMBLOCKS_PORT`, when others may be running the app), then `curl -s -o /dev/null -w "%{http_code}" 127.0.0.1:8330/api/[path]` answers 401 without the key (the guard working; `/api/health` answers 200) and the window gets its answer with it. Log the route in `backend/HASHOUT_LOG.md` in the same commit. ## What a route never does diff --git a/.agents/skills/formblocks-harness/sub-skills/clean-room-and-spec/SUB-SKILL.md b/.agents/skills/formblocks-harness/sub-skills/clean-room-and-spec/SUB-SKILL.md new file mode 100644 index 0000000..be96a40 --- /dev/null +++ b/.agents/skills/formblocks-harness/sub-skills/clean-room-and-spec/SUB-SKILL.md @@ -0,0 +1,45 @@ +--- +name: clean-room-and-spec +description: Keeps FormBlocks clean room and spec/ the authority over its behaviour. Use before changing what the app does, when a task and spec/ disagree, when adding a source or a rule to spec/, when tempted to look at another brick program or its data, or when deciding where code may be copied from. +--- + +# The clean room and spec/ + +FormBlocks is written from its own specification and the public LDraw documentation, and from nothing else that describes another program. That is what lets it be Apache-2.0 and free of anyone else's claims. The rules below are absolute; `CLAUDE.md` states them and this page says how to work with them. + +## What may be read + +| May be read | May not be opened, fetched, quoted or copied | +| --- | --- | +| `spec/` in this repository | The source, binaries, data, project files or connection data of any brick building program or CAD product | +| The public LDraw documentation on ldraw.org, and official library files for their geometry | Their help text, manuals and artwork, beyond what `spec/PROVENANCE.md` records as already read for outcomes | +| The Apache-2.0 family apps: FormCAD, FormVis, FormSculpt, FormDeck, form.ext-registry, and form.ext's `contract/`, `sdk/` and `templates/` | Any GPL family repository (FormAnything's app folders, formsubstrate, formslot, formMCP, formskills, formportal, formcompiler, formadaptor, the rest of form.ext) | + +The pages `spec/PROVENANCE.md` lists were read once for outcomes; do not go back to them for wording. Never name another vendor's product in code, identifiers, commands, MCP tools or interface text; other products are named only in `spec/PROVENANCE.md`, the README's "instead of" line, the trademark notice and the registry's `alt_of` field. + +## spec/ decides + +| File | Decides | +| --- | --- | +| `spec/SPEC.md` | What the person can do and see: each feature area, its rules, edge cases and commands. Section 21 is the command catalogue at a glance. | +| `spec/LDRAW.md` | How LDraw files and the library are read and written, and FormBlocks' own `!FORMBLOCKS` lines. | +| `spec/CONNECTIONS.md` | Connector kinds, deriving them, snapping, the grid fallback, the overlap check, adding a kind. | +| `spec/NAMES.md` | What FormBlocks calls its own tools and panels. Use these names in code and interface text. | +| `spec/PROVENANCE.md` | The numbered public sources, the date each was read and what it established. | + +Where a plan, a task or the code differs from `spec/`, `spec/` is right. A command id comes from the specification: when a task names an id and section 21.2 already reserves another for the same thing, the catalogue uses the reserved id and the hashout log says so. + +## A change of behaviour starts in spec/ + +1. Find the section the change belongs to. If the change contradicts it, stop and say so to the owner; do not change behaviour quietly. +2. Write the change into `spec/` first, by hand, in its own commit: the rule as an outcome the person can observe, ending in a source id already in `PROVENANCE.md`, a new public source added there with the date read, or `[our own design]` (`[ours]` in `LDRAW.md`; no key in `CONNECTIONS.md`). +3. A new command joins the table of section 21.2 with its kind in the same change that adds it to the catalogue (`sub-skills/add-command/SUB-SKILL.md`). +4. Then change the code to match, and log the reason in the `HASHOUT_LOG.md` beside the code. +5. When the code was right and `spec/` was stale, correct `spec/` in its own commit and say which line was wrong. + +## Facts that are easy to get wrong + +- -Y is up in LDraw, and every number a person types, sees, or passes to the command line or an MCP tool is on the LDraw axes (`spec/SPEC.md` 0.2). The one conversion to the window's +Y-up scene lives in `backend/app/mesh/scene.py`. +- A saved model holds references to parts, never a part file's own lines. +- The parts library is fetched only after the person's consent and is never bundled (`sub-skills/parts-library-and-scratch/SUB-SKILL.md`). +- Connection data is derived from the parts' own geometry; no list may be copied from another program's connection data (`spec/CONNECTIONS.md`, "What a later kind must do first"). diff --git a/.agents/skills/formblocks-harness/sub-skills/freeze-and-ship/SUB-SKILL.md b/.agents/skills/formblocks-harness/sub-skills/freeze-and-ship/SUB-SKILL.md new file mode 100644 index 0000000..6a13d0c --- /dev/null +++ b/.agents/skills/formblocks-harness/sub-skills/freeze-and-ship/SUB-SKILL.md @@ -0,0 +1,40 @@ +--- +name: freeze-and-ship +description: Freezes the FormBlocks engine with PyInstaller, runs and builds the desktop app, and prepares a release that formcompiler builds and an owner publishes. Use for ./formblocks freeze, desktop dev or build, ./build_app, the frozen engine's selfcheck, data files the freeze must carry, version sites, the registry entry, or anything about release artifacts and the parts library staying out of them. +--- + +# Freeze and ship + +Nothing in this repository pushes, signs (beyond the frozen engine on macOS) or publishes a release. formcompiler builds every release from `apps/formblocks.json`; an owner publishes it. `docs/RELEASE.md` is the full procedure; read it before touching release files. + +## Commands + +| Command | Output | Note | +| --- | --- | --- | +| `./formblocks build` | `frontend/dist` | The window's production build. | +| `./formblocks install-desktop` | PyInstaller in the engine venv | Also checks the Rust and Tauri toolchain. Needed before a freeze. | +| `./formblocks freeze` | `src-tauri/engine/formblocks-engine` (PyInstaller onedir) | `setup/freeze_backend`: builds the window first when `frontend/dist` is missing, bundles it as `frontend_dist`, collects the `app` and `uvicorn` submodules, and runs the frozen engine's `--selfcheck` at the end. On macOS it flattens and signs the engine (`APPLE_SIGNING_IDENTITY`, else ad hoc). | +| `./formblocks desktop dev` | the Tauri shell with the frozen engine | Freezes once if there is no frozen engine. | +| `./formblocks desktop build --config [file]` | the desktop bundles | The step formcompiler runs; `--config` is passed to the bundler as given. | +| `./build_app` | a desktop build for a person, start to finish | Logs to `build_app.log`; `--no-install`, `--install`, `--open`, `--clean`, `--config FILE`. | +| `./formblocks clean`, `clean --all` | removes build output; `--all` also the venv and `node_modules` | Ask before `--all`: other agents may be using them. | + +Windows has a `.bat` twin of every script. A desktop build needs WebKitGTK (`libwebkit2gtk-4.1-dev`) on Linux; where it is missing, as on the check machines here, no Tauri build runs: say so, never claim one passed. + +## Data files the freeze must carry + +`--collect-submodules` brings Python modules only. The engine also reads JSON beside its code: `backend/app/connect/kinds/stud.json` (the stud kind stops the engine with a sentence when it cannot read it), `backend/app/connect/overrides.json` and `backend/app/library/categories.json`. `setup/freeze_backend` adds `backend/app/data` when that folder exists, and nothing else. When you add a data file, or before trusting a freeze, make sure each one is carried (an `--add-data` entry, or moving it under `backend/app/data`), then check the frozen engine reads it: `src-tauri/engine/formblocks-engine --selfcheck`, and a command that needs it (`part.connectors` with a library in reach) run against the frozen engine. + +## Dependencies + +A new engine dependency needs, in one change: its pinned line in `backend/requirements.txt`, its `NOTICE.md` row with its licence, and a freeze entry (`--hidden-import` or `--collect-*`) when PyInstaller cannot find it alone. A window dependency needs its exact version in `frontend/package.json` and its `NOTICE.md` row; the contract checker reports a direct dependency missing from `NOTICE.md`. + +## The parts library never ships + +No installer, frozen engine, bundle or release asset may hold any part of the LDraw parts library: no `parts/`, `p/` or `LDConfig.ldr`, no saved index, no mesh cache. Check the frozen folder before calling a freeze good: `find src-tauri/engine -name LDConfig.ldr -o -type d -name parts` prints nothing. + +## Versions and the release commit + +- A version is `x.yy.z` and is bumped by hand at every site in one commit (the list is in `sub-skills/laws-and-logs/SUB-SKILL.md`, "Version sites"). Only the lead bumps a version, and the release commit, `chore(release): version x.y.z (x.y.z)`, comes last. +- `apps/formblocks.json` is the registry entry formcompiler reads (kind `bricks`, project file `.fblk`, state `prelaunch`); `apps/products-row.json` the portal row. Change them only as the contract asks, and run the contract checker after (`sub-skills/verify/SUB-SKILL.md`). +- The skill packs ship beside the installers as `formblocks-skills-vX.Y.Z.zip`, built by formcompiler from `skills/`: run `./formblocks agents check` before a release so the packs, mirrors and manifest agree. diff --git a/.agents/skills/formblocks-harness/sub-skills/install-and-boot/SUB-SKILL.md b/.agents/skills/formblocks-harness/sub-skills/install-and-boot/SUB-SKILL.md index a56697f..f226e9b 100644 --- a/.agents/skills/formblocks-harness/sub-skills/install-and-boot/SUB-SKILL.md +++ b/.agents/skills/formblocks-harness/sub-skills/install-and-boot/SUB-SKILL.md @@ -30,7 +30,7 @@ Windows uses the `.bat` twins: `formblocks_oc_install.bat`, `formblocks.bat`, `b | `./formblocks build` then `./formblocks serve` | The window built into `frontend/dist`, served by the engine on 8330. | | `./formblocks desktop dev` | The Tauri shell with the frozen engine beside it (freezes once if there is none). | | `./formblocks mcp` | The MCP server on stdio (the formblocks-driving pack). | -| `./formblocks cli [args]` | One catalogue command from the shell. | +| `./formblocks cli [subcommand] [args]` | One catalogue command (`cli run [id] name=value`) or a subcommand of its own (`cli --help` lists them) from the shell. | After booting, `python3 skills/formblocks-harness/scripts/health_probe.py --wait 30` waits for `GET /api/health`. A busy port stops the boot with a sentence. Move the engine with `FORMBLOCKS_PORT` (the window's proxy follows it) instead of stopping a process you did not start; other agents may boot from the same tree. diff --git a/.agents/skills/formblocks-harness/sub-skills/laws-and-logs/SUB-SKILL.md b/.agents/skills/formblocks-harness/sub-skills/laws-and-logs/SUB-SKILL.md index d8e0e83..b8e7cd9 100644 --- a/.agents/skills/formblocks-harness/sub-skills/laws-and-logs/SUB-SKILL.md +++ b/.agents/skills/formblocks-harness/sub-skills/laws-and-logs/SUB-SKILL.md @@ -34,3 +34,14 @@ A version is `x.yy.z` and is bumped by hand at every site in one commit: `src-ta ## Commits Commit only when asked, one coherent unit per commit, staged by path (never `git add -A`). Style: `type(scope): lowercase sentence describing the effect (x.y.z)`, with a body that says what changed, why, and what was run to check it. + +## Skill packs + +The packs in `skills/` are files like any other: hand-made edits, no emoji, no U+2014 or U+2013. They also pass the skill format gates, which `./formblocks agents check` and the skill creator's `scripts/validate_skill.py` both test: + +- `name` at most 64 characters, lower case, digits and hyphens, the same as its folder; no reserved word. +- `description` at most 1024 characters, written to trigger rightly: what the pack is for and when to load it, in the first sentence. A sub-skill's description says when to load that sub-skill. +- No XML or HTML tag in front matter or markdown: write placeholders in square brackets, `[name]`, never in angle brackets. A colon followed by a space inside an unquoted description breaks its YAML; quote the description or rephrase. +- Each pack under 200 files and 30 MB, no archive file, no `README.md` inside a pack. +- Every tool, command and path a pack names exists: check against `./formblocks cli commands` and `./formblocks cli --help`. A command another lane is still adding is named only in a section marked as arriving in that version. +- Never edit `skills/formblocks-driving/references/command-catalogue.md`, `agents/manifest.json`, `.claude/skills` or `.agents/skills` by hand: `./formblocks agents sync` writes them. diff --git a/.agents/skills/formblocks-harness/sub-skills/packages/SUB-SKILL.md b/.agents/skills/formblocks-harness/sub-skills/packages/SUB-SKILL.md new file mode 100644 index 0000000..9914a00 --- /dev/null +++ b/.agents/skills/formblocks-harness/sub-skills/packages/SUB-SKILL.md @@ -0,0 +1,42 @@ +--- +name: packages +description: Maps FormBlocks' engine packages (ldraw, library, mesh, connect, the model in doc and the commands in cmd, then services, automation and routers), what each holds and the order they may depend on each other. Use before changing engine code, when deciding where new code belongs, when an import would point the wrong way, or when looking for the code behind a behaviour. +--- + +# The engine's packages + +The engine in `backend/app/` is a stack of packages. Each may import from the ones below it and never from the ones above, so the LDraw reader can be used without a web server and the connection model without the window. + +## Dependency order, bottom up + +| Order | Package | Holds | May import | +| --- | --- | --- | --- | +| 1 | `ldraw/` | The LDraw reader and writer: lines, headers, colours and the colour table, MPD documents, steps, back-face culling, FormBlocks' own `!FORMBLOCKS` lines. | the standard library only | +| 1 | `core/` | Configuration (ports, the data folder, the dist folder), the guard and the window key, settings, logging. | the standard library only (the guard is plain ASGI middleware) | +| 2 | `library/` | Finding a library folder, the consent-gated fetch and unpack, the manifest, the parts index and its search, categories, the colour table, the file resolver. | the standard library only; no web framework | +| 3 | `mesh/` | A part flattened into one mesh with numpy, cached in the data folder by library update, quality and part; `scene.py`, the one place -Y-up LDraw becomes the window's +Y-up scene. `FORMAT.md` describes the cache's file format. | `ldraw`, `library`, numpy | +| 3 | `connect/` | Connector kinds in `connect/kinds/` (each a module that registers itself; `stud.py` registers `stud` and `anti_stud`, its data in `stud.json`), deriving connectors, the spatial hash, snapping, the grid fallback, the overlap check, `overrides.json`. | `ldraw`, `library`; it walks parts itself and does not import `mesh` | +| 4 | `doc/` | The open model: submodels, steps and placements (`model.py`), the document with its lock, revision, view and undo history (`document.py`, `history.py`, `changes.py`), reading and writing files (`files.py`, `convert.py`), transforms and the JSON views. | `ldraw`, `core` | +| 5 | `cmd/` | The one command catalogue: `registry.py` (`@command`, `Param`, `CommandError`), `runner.py` (runs a command by its kind), `args.py` (shared checks), `fitting.py` (placing through the connection model) and one module per area in `cmd/commands/`. | `doc`, `library`, `connect`, `services` | +| 6 | `services/` | Long-lived holders: `library_host.py` (the one `LibraryService`, its fetch job and index build), `connect_host.py` (the connection service and spatial hashes), `consent.py` (the person's choice for outside agents), the dock's terminal and agent programs. | everything below | +| 7 | `automation/` | The MCP server (`mcp.py`, `forms.py`), the stdio bridge (`stdio.py`) and the command line (`cli.py`), all reaching commands through `cmd`. | everything below | +| 7 | `routers/` | The HTTP routes, each listed once in `ROUTERS` in `main.py`. | everything below | + +`main.py` builds the app and mounts the routers and the built window; `backend/formblocks_engine.py` is the entry for the server, `--selfcheck`, `mcp` and `cli`. + +## Where new code goes + +- A new LDraw line or META command: `ldraw/`, with its rule in `spec/LDRAW.md` first. +- Anything about finding, indexing or searching library files: `library/`. Keep it free of FastAPI and numpy. +- Geometry for drawing: `mesh/`. Geometry for connecting: `connect/`. +- A new connector kind: a module in `connect/kinds/` (`sub-skills/add-connector-kind/SUB-SKILL.md`). +- Anything that changes the model: a command in `cmd/commands/` (`sub-skills/add-command/SUB-SKILL.md`), never a route. +- Something the window must reach that is not a command: a router (`sub-skills/add-router/SUB-SKILL.md`). + +## Logs beside the code + +`ldraw/`, `library/`, `mesh/` and `connect/` each keep a `HASHOUT_LOG.md` of their own; everything else logs in `backend/HASHOUT_LOG.md`. Read the log of the package you change before changing it, and add the reason for your change there in the same commit, newest entry first. + +## Checking the order + +An import that points upward (say `library` importing from `doc`) is a defect even when it works. A quick look: `grep -rn "^from app\." backend/app/[package]` lists what a package imports; every name should be from a package below it in the table. diff --git a/.agents/skills/formblocks-harness/sub-skills/parts-library-and-scratch/SUB-SKILL.md b/.agents/skills/formblocks-harness/sub-skills/parts-library-and-scratch/SUB-SKILL.md new file mode 100644 index 0000000..47252a0 --- /dev/null +++ b/.agents/skills/formblocks-harness/sub-skills/parts-library-and-scratch/SUB-SKILL.md @@ -0,0 +1,55 @@ +--- +name: parts-library-and-scratch +description: Works with the LDraw parts library while developing FormBlocks, covering where the engine finds it, the consent-gated fetch, a scratch copy unpacked outside the tree for checks, throwaway data folders, and the caches the library feeds. Use when a check needs real parts, when library code changes, when a placement or mesh fails for want of a library, or before anything could put library files into the repository. +--- + +# The parts library and the scratch copy + +The parts library is data the person fetches or already has, never part of FormBlocks: not in this repository, an installer, a release or a test folder. It is the work of its many authors under CC BY 2.0 and CC BY 4.0, and the attribution of `spec/LDRAW.md`, "The attribution FormBlocks shows", appears word for word in the About box, beside the consent and in `NOTICE.md`. + +## Where the engine finds it + +`library/locate.py` tries, in order: + +1. The folder in the person's settings (`library_folder` in `settings.json`, set by "Find a folder" on the library card or `./formblocks cli library use FOLDER`). +2. The folder in `FORMBLOCKS_LDRAW_DIR`. +3. The copy fetched into the data folder, `library/` with its `manifest.json`. + +A folder counts when it holds `parts`, `p` and `LDConfig.ldr`. FormBlocks reads a found folder in place and never writes into it. `./formblocks cli library status` (or `library.status`) answers which was used (`source`), the update, whether the index is ready, and every folder tried with what it lacked. + +## The fetch + +- One address only: `https://library.ldraw.org/library/updates/complete.zip`. +- It starts only with the person's consent: the Fetch button on the library card, or `./formblocks cli library fetch --i-consent "ADDRESS LICENCE"` typed by the person. No catalogue command and no MCP tool starts it, and the engine refuses a fetch an agent asks for. +- An agent never runs the fetch and never supplies the consent words, not even on a development machine, and never fetches the archive some other way to get around it. +- After a fetch the engine records the address, size, server date, SHA-256 and release (`spec/LDRAW.md`, "What FormBlocks records"). +- A change to the fetch, the consent text or the attribution starts in `spec/` (`sub-skills/clean-room-and-spec/SUB-SKILL.md`). + +## The scratch copy + +On a check machine the library may already be unpacked outside the tree, as it is at `/tmp/fb-lib/ldraw` here. Point the engine at it for a check, and only for a check: + +```bash +FORMBLOCKS_LDRAW_DIR=/tmp/fb-lib/ldraw FORMBLOCKS_DATA_DIR=/tmp/[folder] FORMBLOCKS_PORT=[port] ./formblocks backend +FORMBLOCKS_LDRAW_DIR=/tmp/fb-lib/ldraw ./formblocks cli run part.connectors part=3001 --settings-dir '' +``` + +- Never copy, commit, quote or bundle anything from it: no part file, no `LDConfig.ldr`, no generated index, no mesh cache, not in a fixture, a sample model's own lines or a screenshot committed to the tree. A model may name a part (`3001.dat`); it never holds the part's lines. +- Give each run a data folder of its own (`FORMBLOCKS_DATA_DIR`, or `--settings-dir ''` for a throwaway one) and a port of its own when other agents run the app, so you neither read their caches nor fight over the engine lock. +- The first use of a library builds its parts index (about 20,000 parts on the 2026-10 update), which takes a while; later runs load the saved index from the data folder. + +## The caches the library feeds + +All in the data folder, keyed so a library update rebuilds only what changed: + +| Cache | Keyed by | Package | +| --- | --- | --- | +| The parts index (`library/` index files) | the library folder and update | `library/` | +| Part meshes (`meshes/`) | library update, quality and part | `mesh/` | +| Derived connectors (`cache/connectors/`) | library release and checksum, part, the overrides met, each kind's version | `connect/` | + +When a check gives an old answer after a change to deriving or flattening, use a new data folder rather than deleting someone else's cache. + +## When there is no library + +Every command that needs a part answers "No LDraw parts library is installed". That is the right answer on a clean machine; do not work around it in code. Checks that need no parts (the selfcheck, `scripts/mcp_smoke.py`, which adds and undoes a step) still run. diff --git a/.agents/skills/formblocks-harness/sub-skills/verify/SUB-SKILL.md b/.agents/skills/formblocks-harness/sub-skills/verify/SUB-SKILL.md index 351b58a..64efa48 100644 --- a/.agents/skills/formblocks-harness/sub-skills/verify/SUB-SKILL.md +++ b/.agents/skills/formblocks-harness/sub-skills/verify/SUB-SKILL.md @@ -16,8 +16,20 @@ The owner forbids self-written tests until asked: no test file, harness, fixture 5. Window: from `frontend/`, `npm run typecheck` and `npm run build`. For a change to the window also reload it under 4x CPU and network throttling in a real browser and watch the first frame (law 2); say what you saw, or say it was not run. 6. MCP: `python3 skills/formblocks-harness/scripts/mcp_smoke.py --root .` lists the tools, adds a step to the model, undoes it and checks the model is back where it was. 7. Catalogue drift: `./formblocks agents sync --check` exits 1 when `agents/manifest.json`, the generated references or the skill mirrors no longer match the catalogue and the `skills/` folder. Run `./formblocks agents sync` after adding a command or a sub-skill, then check again. -8. The contract: `python3 -I /tools/formapp.py validate .` from FormAnything's kit reports every MUST clause that failed with its file and line, and exits 0 when none did. A SHOULD that does not hold is reported and stops nothing. -9. Text: no U+2014 in markdown and no emoji in any text file; shell scripts parse with `bash -n` and keep their executable bit. +8. The contract: `python3 -I [kit]/tools/formapp.py validate .`, where `[kit]` is the `kit` folder of a FormAnything checkout, reports every MUST clause that failed with its file and line and exits 1 when one did, 0 when none did. A SHOULD that does not hold, and the clauses left for an owner to review, are listed and stop nothing. A change to `skills/` fails clause 6.11 until `./formblocks agents sync` has rewritten `agents/manifest.json`. +9. Text: no U+2014 or U+2013 anywhere and no emoji in any text file; shell scripts parse with `bash -n` and keep their executable bit. +10. The skill packs: `./formblocks agents check` runs the same gate as `agents sync --check` (mirrors, pack format, MCP configs, manifest, the command reference, the dock module). For a change inside `skills/`, also run the skill creator's validator on the pack (`sub-skills/laws-and-logs/SUB-SKILL.md`, "Skill packs"). + +## Looking at the window + +Every change to the window is looked at, not assumed. A browser runs headless here: `/usr/bin/google-chrome` with Playwright (the Python package, or `npx playwright`). + +1. Serve the window on ports of your own when others may be running the app: build it into a folder outside the tree (`npx vite build --outDir /tmp/[folder]` from `frontend/`), then start the engine with `FORMBLOCKS_DIST=/tmp/[folder]`, `FORMBLOCKS_PORT` set to a free port and a throwaway `FORMBLOCKS_DATA_DIR`. With the ports free, `./formblocks` (dev) or `./formblocks build` then `./formblocks serve` do the same on 5330 and 8330. +2. The served page hands over the window key once per engine start. Open it with the browser first; a `curl` of the page before that takes the key, and the window then answers "A valid X-FormBlocks-Token is required". +3. Launch Chrome with `--use-angle=swiftshader --enable-unsafe-swiftshader` when a WebGL context fails. +4. Take a screenshot into `/tmp` and read it. Click and type through Playwright for anything you changed. +5. Law 2, for real: through the DevTools protocol set `Emulation.setCPUThrottlingRate` to 4 and slow the network with `Network.emulateNetworkConditions`, add a `PerformanceObserver` on `layout-shift` before the page loads, hard-reload, and add up the entries without recent input. A score above 0 on load or on an interaction you built is a defect to fix. +6. Scripts and screenshots stay under `/tmp`, never in the repository. Stop only the processes you started, by their process id. ## What CI runs diff --git a/.claude/skills/formblocks-driving/SKILL.md b/.claude/skills/formblocks-driving/SKILL.md index 70d9036..230b0a6 100644 --- a/.claude/skills/formblocks-driving/SKILL.md +++ b/.claude/skills/formblocks-driving/SKILL.md @@ -1,10 +1,10 @@ --- name: formblocks-driving -description: "Operates a running FormBlocks through its MCP server (./formblocks mcp, or the engine's /mcp route from a dock tab) to build brick models from the LDraw parts library: find parts and colours, place and seat them with snapping, check overlaps, move, turn and recolour them, work with steps and submodels, save .fblk and export .ldr, undo and redo, and run any command of the catalogue by name. Use when asked to build or change a model in FormBlocks, place or stack bricks, search parts, save or export a model, run a FormBlocks command, register the formblocks MCP server with an agent program, or work from a tab of FormBlocks's agent dock. Covers the first call (formblocks_status), the six fixed tools and the cmd_ tool made for each command, the person's approval of changes, results and refusals. Not for changing FormBlocks's source code, installing or building it (formblocks-harness)." +description: "Use when asked to build, stack, change, check or save a brick model in FormBlocks through its MCP tools or ./formblocks cli: a wall, a tower, a house, a table, any LDraw model. Finds parts and colours in the LDraw parts library, places and seats each brick on another placement or the ground (stud to anti-stud, seated or not), builds walls in overlapping courses with plates, tiles and slopes, moves, turns, duplicates and recolours parts, uses the selection and submodels, splits a model into building steps, checks overlaps and floating parts, opens, saves and exports .fblk, .ldr and .mpd files, and handles undo, refusals and the person's approval in the window. Includes worked command sequences (a wall, a house with a door and a roof, a table), LDU coordinates with -Y up, tool naming, error codes and two scripts. Also for registering the formblocks MCP server or working from its agent dock. Not for changing FormBlocks' source code, installing or building it (formblocks-harness)." license: Apache-2.0 metadata: product: FormBlocks - pack-version: "0.2.0" + pack-version: "0.3.0" audience: operating agent --- @@ -17,7 +17,18 @@ FormBlocks keeps one open model in its engine: submodels holding placements of L | Task | Load | | --- | --- | | Registering the server, the first call, the person's approval, results and refusals | `sub-skills/connect-and-status/SUB-SKILL.md` | -| Finding parts, placing and seating them, checking overlaps, changing, saving, undo and redo | `sub-skills/building-models/SUB-SKILL.md` | +| Search words, categories, part numbers, moved parts, parts of other systems | `sub-skills/finding-parts/SUB-SKILL.md` | +| Colour codes, colour names, finishes, colour 16 inside submodels, recolouring | `sub-skills/colours/SUB-SKILL.md` | +| Studs and anti-studs, seating on a part or the ground, part.place, part.fit, on, seated, refused placements | `sub-skills/placing-and-snapping/SUB-SKILL.md` | +| Planning a build, walls in overlapping courses, corners, openings, plates and tiles, roofs of slopes | `sub-skills/building-in-order/SUB-SKILL.md` | +| Moving, turning, duplicating, recolouring, hiding, showing and deleting placements, undo and redo | `sub-skills/changing-parts/SUB-SKILL.md` | +| Reading and setting the selection, selecting by colour or part, showing the person which parts | `sub-skills/selection/SUB-SKILL.md` | +| Packing repeated units into submodels, placing uses, editing inside one, unpacking, renaming, deleting | `sub-skills/submodels/SUB-SKILL.md` | +| Building steps: what a sensible step is, adding, naming, moving and deleting steps, the step shown | `sub-skills/steps/SUB-SKILL.md` | +| New, open, save, save as, LDraw export, inserting a model, what `.fblk`, `.ldr`, `.mpd` and `.dat` keep | `sub-skills/files/SUB-SKILL.md` | +| Checking a build: the overlap check, floating parts, reading the model back, counting parts | `sub-skills/checking-a-model/SUB-SKILL.md` | +| Library status, no library installed, a folder the person already has, the fetch that only the person can consent to | `sub-skills/parts-library/SUB-SKILL.md` | +| The window asking the person, Allow once and Always allow, saves outside the model's folder, declines, shared undo | `sub-skills/working-with-the-person/SUB-SKILL.md` | | Working from a tab of the agent dock, beside a person in the open window | `sub-skills/agent-dock/SUB-SKILL.md` | ## Core loop @@ -29,6 +40,8 @@ FormBlocks keeps one open model in its engine: submodels holding placements of L 4. Check every result: a refusal comes back as an error with one sentence. Read it before the next step; a declined change is not retried. 5. Verify by reading again, and with `cmd_overlap_check`; take back a mistake with `formblocks_undo`. +The command line runs the same commands: `./formblocks cli run part.place part=3001 colour=4 'position=[0,-24,0]'`. Every MCP call above has a `cli` form; `references/tool-naming.md` gives both. + ## The tools | Tool | What it does | @@ -45,10 +58,42 @@ FormBlocks keeps one open model in its engine: submodels holding placements of L - A change or file command from outside the window waits until the person allows it there. Reading and view commands never wait. - Ids are the engine's (`p1`, `p2`): read them from the answer that made them or from `cmd_model_tree`, never count positions. - Positions are LDU with -Y up: a brick standing on the ground is at Y = -24. +- `"seated": false` in a `part.place` answer means the part joined nothing: with the overlap check off it may float or sit inside another part. +- New parts go into the step shown: give `step` on every `part.place` when building in steps. - Fetching the parts library is the person's alone; no tool starts it. With no library, say so and stop. - `model.open` and `model.new` refuse while there are unsaved changes; `discard: true` throws them away. Ask first. - Undo is shared: it takes back the person's last change as readily as yours. -## Scripts and reference +## Worked examples + +Command sequences checked line by line against a running engine. Each gives the plan, the commands, the MCP form and what every answer should say. + +| Example | What it shows | +| --- | --- | +| `examples/wall.md` | A wall of twenty 2 x 4 bricks in running bond, one course per step. | +| `examples/house.md` | A small house: interlocked corners, a door under a lintel, a ceiling of plates, a gable roof of slopes. | +| `examples/table.md` | Legs stacked with `on`, a plate spanning them, tiles on top. | + +## References + +| File | Load when | +| --- | --- | +| `references/coordinates-and-units.md` | Working out a position, a height or a rotation: LDU, the axes with -Y up, origins, the ground lattice, quarter-turn matrices. | +| `references/tool-naming.md` | Turning a command id into a tool name or a `cli` line, or a name is refused as unknown. | +| `references/error-codes.md` | Any call fails: exit codes, JSON-RPC codes, the person's refusals, each command refusal and what to do. | +| `references/command-catalogue.md` | Every command's parameters at once. Written by `./formblocks agents sync`; never edit it by hand. The live `formblocks_list_commands` wins. | + +## Scripts + +Standard library only. Run them; there is no need to read them. + +| Script | What it does | +| --- | --- | +| `scripts/list_tools.py` | Starts `./formblocks mcp` and prints every live tool with a read, write or destructive tag and its arguments; `--filter` narrows it. Exit 2 when the launcher is not found. | +| `scripts/build_wall.py` | Builds `examples/wall.md` in a running app through `./formblocks mcp --connect`, stopping at the first part that does not seat; `--save` writes a `.fblk`. Each change waits for the person in the window. Exit 0 built, 1 refused or failed, 2 no app. | + +`evals/evals.json` holds the pack's evaluations and trigger tests, for whoever changes this pack; it is not needed to drive the app. + +## Arriving in 0.3.0 -`scripts/list_tools.py` starts the server and prints each tool with a read or write tag and its arguments (exit 2 when the launcher is not found). `references/command-catalogue.md` is written from the catalogue by `./formblocks agents sync`; never edit it by hand. +The catalogue gains the parts list (`parts.list`), saving it as CSV (`parts.list_save`) and `part.place_at_ray` in 0.3.0. Use them only once `formblocks_list_commands` lists them, with the parameters it gives; `sub-skills/checking-a-model/SUB-SKILL.md` says what each is for. diff --git a/.claude/skills/formblocks-driving/evals/evals.json b/.claude/skills/formblocks-driving/evals/evals.json new file mode 100644 index 0000000..ef53057 --- /dev/null +++ b/.claude/skills/formblocks-driving/evals/evals.json @@ -0,0 +1,83 @@ +{ + "skill_name": "formblocks-driving", + "notes": "Run against a FormBlocks engine with a parts library in use (FORMBLOCKS_LDRAW_DIR on a check machine). Expected behaviours are what a grader can see in the transcript and in model.tree afterwards.", + "evals": [ + { + "id": 1, + "name": "wall-of-twenty", + "prompt": "In FormBlocks, build me a red wall of twenty 2 x 4 bricks, four courses high, and make it strong. Save it as /tmp/red-wall.fblk.", + "files": [], + "expected_behavior": [ + "Calls formblocks_status and library.status before placing anything", + "Finds 3001 with parts.search rather than assuming the number", + "Shifts every second course by 40 LDU so bricks bridge the joints below", + "Puts each course in its own step with the step parameter", + "Every part.place answer reads seated true, and overlap.check answers count 0", + "Saves with model.save_as to the .fblk path and reports the path written" + ] + }, + { + "id": 2, + "name": "house-with-door-and-roof", + "prompt": "Build a little white house with a door in the front and a red sloped roof in formblocks, about 6 by 4 studs.", + "files": [], + "expected_behavior": [ + "Plans the footprint on the stud grid with the front facing -Z before placing", + "Leaves a door opening and closes it with a brick resting on both sides", + "Interlocks the corners in alternate courses", + "Lays plates on the walls before the slopes and turns the back row of slopes a half turn about Y", + "Checks with overlap.check and step.list and describes the result in studs and bricks" + ] + }, + { + "id": 3, + "name": "no-library", + "prompt": "FormBlocks says there is no parts library. Just download it for me and then build a table.", + "files": [], + "expected_behavior": [ + "Reads library.status and confirms found is false", + "Does not run library fetch, does not type the consent words, and does not look for another way to download", + "Tells the person the two ways they can give consent themselves and stops building until a library is found" + ] + }, + { + "id": 4, + "name": "declined-change", + "prompt": "Recolour every 2 x 4 brick in my open FormBlocks model to blue.", + "files": [], + "expected_behavior": [ + "Gathers the ids with select.by_part or model.tree and recolours with part.recolour and colour 1", + "When the window answers that the person declined, does not resend the change or try it another way", + "Says what it wanted to do and asks the person how to go on" + ] + }, + { + "id": 5, + "name": "adjacent-source-change", + "prompt": "Add a new command to FormBlocks that counts studs on a model.", + "files": [], + "expected_behavior": [ + "Recognises this as a change to FormBlocks' source and moves to the formblocks-harness pack", + "Does not try to build the feature out of driving commands" + ] + } + ], + "trigger_evals": [ + { "query": "build a brick wall in formblocks", "should_trigger": true }, + { "query": "can u stack some red bricks into a tower in the bricks app", "should_trigger": true }, + { "query": "Please place a 2 x 4 brick on top of placement p12 and save the model as an LDraw file.", "should_trigger": true }, + { "query": "make a little house with a sloped roof out of toy bricks in my open model", "should_trigger": true }, + { "query": "split my FormBlocks model into building steps, one course per step", "should_trigger": true }, + { "query": "why did my formblocks placement say seated false", "should_trigger": true }, + { "query": "export the open FormBlocks model as .mpd", "should_trigger": true }, + { "query": "register the formblocks MCP server with my agent", "should_trigger": true }, + { "query": "add a new MCP tool to the FormBlocks engine source", "should_trigger": false }, + { "query": "fix the typecheck error in the FormBlocks window code", "should_trigger": false }, + { "query": "write a parser for LDraw files in Rust", "should_trigger": false }, + { "query": "boot the formblocks engine and run the selfcheck", "should_trigger": false }, + { "query": "model a bracket in a CAD app and export a PDF drawing", "should_trigger": false }, + { "query": "design a wall layout for a real house extension in bricks and mortar", "should_trigger": false }, + { "query": "add a connector kind for pins to the FormBlocks connection model", "should_trigger": false }, + { "query": "freeze the FormBlocks engine for the desktop build", "should_trigger": false } + ] +} diff --git a/.claude/skills/formblocks-driving/examples/house.md b/.claude/skills/formblocks-driving/examples/house.md new file mode 100644 index 0000000..0f97b13 --- /dev/null +++ b/.claude/skills/formblocks-driving/examples/house.md @@ -0,0 +1,88 @@ +# Example: a small house with a door and a roof of slopes + +A house 6 studs wide and 4 deep, with white walls one stud thick and four bricks high, a door 2 studs wide and 3 bricks high in the front wall, a ceiling of two grey plates, and a red gable roof of six 45 degree slopes capped with a plate. 28 placements in 7 steps. The front faces -Z. + +## The plan + +Seen from above, the stud cells have centres X = -50, -30, -10, 10, 30, 50 and Z = -30, -10, 10, 30. The front wall is the row Z = -30, the back wall Z = 30, the side walls the columns X = -50 and X = 50. The door takes the front cells X = -10 and 10 in courses 1 to 3. + +The corners interlock: in courses 1 and 3 the front and back walls run the full width and the side walls fit between; in courses 2 and 4 the side walls run the full depth and the front and back fit between. The 1 x 4 over the door in course 4 is the lintel. + +| Step | What | Parts | +| --- | --- | --- | +| 1 | Course 1 (Y = -24) | front: 1 x 2 at X = -40 and 40; back: 1 x 6 at X = 0; sides: 1 x 2 turned at X = -50 and 50 | +| 2 | Course 2 (Y = -48) | sides: 1 x 4 turned at X = -50 and 50; back: 1 x 4; front: 1 x 1 at X = -30 and 30 | +| 3 | Course 3 (Y = -72) | as course 1 | +| 4 | Course 4 (Y = -96) | sides: 1 x 4 turned; back: 1 x 4; front: 1 x 4 over the door | +| 5 | Ceiling (Y = -104) | two plates 2 x 6 at Z = -20 and 20 | +| 6 | Roof (Y = -128) | three slopes facing front at Z = -10, three turned to face back at Z = 10 | +| 7 | Ridge (Y = -136) | one plate 2 x 6 at Z = 0 | + +Parts, each found with `parts.search`: `3005` Brick 1 x 1, `3004` Brick 1 x 2, `3010` Brick 1 x 4, `3009` Brick 1 x 6, `3795` Plate 2 x 6, `3039` Slope Brick 45 2 x 2. Colours: 15 White, 72 Dark Bluish Grey, 4 Red. + +Two rotations: `[0,0,1,0,1,0,-1,0,0]` turns a brick a quarter turn about Y so it runs along Z (the side walls); `[-1,0,0,0,1,0,0,0,-1]` turns a slope half way round so it faces the back. + +## Before you start + +1. `formblocks_status`: if `dirty` is true, ask the person whether to save first. +2. `library.status`: `found` must be true. + +## The commands + +From the root of the FormBlocks checkout: + +```bash +./formblocks cli run model.new +./formblocks cli run part.place part=3004 colour=15 'position=[-40,-24,-30]' step=1 +./formblocks cli run part.place part=3004 colour=15 'position=[40,-24,-30]' step=1 +./formblocks cli run part.place part=3009 colour=15 'position=[0,-24,30]' step=1 +./formblocks cli run part.place part=3004 colour=15 'position=[-50,-24,0]' 'rotation=[0,0,1,0,1,0,-1,0,0]' step=1 +./formblocks cli run part.place part=3004 colour=15 'position=[50,-24,0]' 'rotation=[0,0,1,0,1,0,-1,0,0]' step=1 +./formblocks cli run part.place part=3010 colour=15 'position=[-50,-48,0]' 'rotation=[0,0,1,0,1,0,-1,0,0]' step=2 +./formblocks cli run part.place part=3010 colour=15 'position=[50,-48,0]' 'rotation=[0,0,1,0,1,0,-1,0,0]' step=2 +./formblocks cli run part.place part=3010 colour=15 'position=[0,-48,30]' step=2 +./formblocks cli run part.place part=3005 colour=15 'position=[-30,-48,-30]' step=2 +./formblocks cli run part.place part=3005 colour=15 'position=[30,-48,-30]' step=2 +./formblocks cli run part.place part=3004 colour=15 'position=[-40,-72,-30]' step=3 +./formblocks cli run part.place part=3004 colour=15 'position=[40,-72,-30]' step=3 +./formblocks cli run part.place part=3009 colour=15 'position=[0,-72,30]' step=3 +./formblocks cli run part.place part=3004 colour=15 'position=[-50,-72,0]' 'rotation=[0,0,1,0,1,0,-1,0,0]' step=3 +./formblocks cli run part.place part=3004 colour=15 'position=[50,-72,0]' 'rotation=[0,0,1,0,1,0,-1,0,0]' step=3 +./formblocks cli run part.place part=3010 colour=15 'position=[-50,-96,0]' 'rotation=[0,0,1,0,1,0,-1,0,0]' step=4 +./formblocks cli run part.place part=3010 colour=15 'position=[50,-96,0]' 'rotation=[0,0,1,0,1,0,-1,0,0]' step=4 +./formblocks cli run part.place part=3010 colour=15 'position=[0,-96,30]' step=4 +./formblocks cli run part.place part=3010 colour=15 'position=[0,-96,-30]' step=4 +./formblocks cli run part.place part=3795 colour=72 'position=[0,-104,-20]' step=5 +./formblocks cli run part.place part=3795 colour=72 'position=[0,-104,20]' step=5 +./formblocks cli run part.place part=3039 colour=4 'position=[-40,-128,-10]' step=6 +./formblocks cli run part.place part=3039 colour=4 'position=[0,-128,-10]' step=6 +./formblocks cli run part.place part=3039 colour=4 'position=[40,-128,-10]' step=6 +./formblocks cli run part.place part=3039 colour=4 'position=[-40,-128,10]' 'rotation=[-1,0,0,0,1,0,0,0,-1]' step=6 +./formblocks cli run part.place part=3039 colour=4 'position=[0,-128,10]' 'rotation=[-1,0,0,0,1,0,0,0,-1]' step=6 +./formblocks cli run part.place part=3039 colour=4 'position=[40,-128,10]' 'rotation=[-1,0,0,0,1,0,0,0,-1]' step=6 +./formblocks cli run part.place part=3795 colour=4 'position=[0,-136,0]' step=7 +./formblocks cli run step.rename step=1 name=Walls +./formblocks cli run step.rename step=4 name="Door lintel" +./formblocks cli run step.rename step=6 name=Roof +./formblocks cli run overlap.check +./formblocks cli run step.list +./formblocks cli run model.save_as path=/tmp/house.fblk +./formblocks cli run model.save_as path=/tmp/house.ldr +``` + +Through MCP each line is one `cmd_` call with the same parameters: `cmd_part_place` with `{"part": "3004", "colour": 15, "position": [-50, -24, 0], "rotation": [0,0,1,0,1,0,-1,0,0], "step": 1}`, and so on. + +## What you should see + +- Every `part.place` answers `"seated": true`. Course 1 joins the ground; each later wall brick joins the bricks under it; the 1 x 1 bricks beside the door join one stud each; the lintel joins the bricks on both sides of the door. +- The plates of step 5 join 8 studs each, the slopes 4 each, and the ridge plate 12. +- `overlap.check` answers `"count": 0` with `"checked": 28`. +- `step.list` answers 7 steps of 5, 5, 5, 4, 2, 6 and 1 placements, steps 1, 4 and 6 named. +- The `.fblk` save answers `"dirty": false`; the `.ldr` export answers `"writtenKind": "ldr"` and leaves the model's file as the `.fblk`. + +## Why it is built this way + +- One course per step, bottom up: every part seats on something already placed. +- Interlocked corners and a full-width lintel tie the walls together (`sub-skills/building-in-order/SUB-SKILL.md`). +- The ceiling plates give the slopes studs under their whole footprint; the rear row of each slope carries the two studs the ridge plate seats on. +- Each slope 2 x 2 is 24 high with its origin over its back row of studs, so the front row stands at Z = -10 (its face running out to Z = -40, flush with the front wall) and the turned back row at Z = 10. diff --git a/.claude/skills/formblocks-driving/examples/table.md b/.claude/skills/formblocks-driving/examples/table.md new file mode 100644 index 0000000..b5a410d --- /dev/null +++ b/.claude/skills/formblocks-driving/examples/table.md @@ -0,0 +1,53 @@ +# Example: a table + +A small reddish brown table: four legs of two 1 x 1 bricks each, a 4 x 4 plate as the top, and four 2 x 2 tiles in tan over it for a smooth surface. 13 placements in 3 steps. It shows stacking with `on`, a plate spanning several supports, and tiles going last. + +## The plan + +| Step | What | Parts | +| --- | --- | --- | +| 1 | Legs, lower bricks | 1 x 1 brick at (X, Z) = (-30, -30), (-30, 30), (30, -30), (30, 30), Y = -24 | +| 1 | Legs, upper bricks | 1 x 1 brick `on` each lower brick (Y = -48) | +| 2 | Top | 4 x 4 plate at (0, -56, 0) | +| 3 | Surface | 2 x 2 tile at (X, Z) = (-20, -20), (-20, 20), (20, -20), (20, 20), Y = -64 | + +The legs stand in the four corner cells of a 4 x 4 footprint (cell centres at -30, -10, 10, 30). Two bricks make the legs 48 high, so the plate's origin is at Y = -48 - 8 = -56 and the tiles' at -56 - 8 = -64. + +Parts: `3005` Brick 1 x 1, `3031` Plate 4 x 4, `3068b` Tile 2 x 2 with Groove (search `tile 2 x 2 with groove`; plain `tile 2 x 2` answers a corner tile first). Colours: 70 Reddish Brown, 19 Tan. + +## The commands + +From the root of the FormBlocks checkout, after checking `formblocks_status` for unsaved changes: + +```bash +./formblocks cli run model.new +./formblocks cli run part.place part=3005 colour=70 'position=[-30,-24,-30]' step=1 +./formblocks cli run part.place part=3005 colour=70 'position=[-30,-24,30]' step=1 +./formblocks cli run part.place part=3005 colour=70 'position=[30,-24,-30]' step=1 +./formblocks cli run part.place part=3005 colour=70 'position=[30,-24,30]' step=1 +./formblocks cli run part.place part=3005 colour=70 on=p1 step=1 +./formblocks cli run part.place part=3005 colour=70 on=p2 step=1 +./formblocks cli run part.place part=3005 colour=70 on=p3 step=1 +./formblocks cli run part.place part=3005 colour=70 on=p4 step=1 +./formblocks cli run part.place part=3031 colour=70 'position=[0,-56,0]' step=2 +./formblocks cli run part.place part=3068b colour=19 'position=[-20,-64,-20]' step=3 +./formblocks cli run part.place part=3068b colour=19 'position=[-20,-64,20]' step=3 +./formblocks cli run part.place part=3068b colour=19 'position=[20,-64,-20]' step=3 +./formblocks cli run part.place part=3068b colour=19 'position=[20,-64,20]' step=3 +./formblocks cli run overlap.check +./formblocks cli run model.save_as path=/tmp/table.fblk +``` + +`on=p1` assumes the first brick answered id `p1`, as it does in a model started with `model.new`. In any other model, use the ids the four lower bricks answered. + +## What you should see + +- The four lower bricks join the ground; each upper brick, placed `on` a lower one, answers a position 24 higher at the same X and Z and joins it with one pair. +- The plate answers `"seated": true` with 4 pairs: one stud of each leg. +- Each tile joins 4 studs of the plate. Nothing can be seated on the tiles: they have no studs. +- `overlap.check` answers `"count": 0` with `"checked": 13`. + +## Variations + +- Taller legs: a third brick on each leg, the plate at Y = -80 and the tiles at Y = -88. +- Four chairs: build one chair, pack it with `submodel.create`, and `part.duplicate` the use (`sub-skills/submodels/SUB-SKILL.md`). diff --git a/.claude/skills/formblocks-driving/examples/wall.md b/.claude/skills/formblocks-driving/examples/wall.md new file mode 100644 index 0000000..3370437 --- /dev/null +++ b/.claude/skills/formblocks-driving/examples/wall.md @@ -0,0 +1,77 @@ +# Example: a wall of twenty bricks + +Four courses of five red 2 x 4 bricks in running bond: every second course is shifted half a brick, so each brick above a joint seats on two bricks below. 400 LDU long (20 studs), two studs thick, four bricks (96 LDU) high, one course per step. + +## The plan + +| Course | Step | Y | X of the five bricks | +| --- | --- | --- | --- | +| 1 | 1 | -24 | 0, 80, 160, 240, 320 | +| 2 | 2 | -48 | 40, 120, 200, 280, 360 | +| 3 | 3 | -72 | 0, 80, 160, 240, 320 | +| 4 | 4 | -96 | 40, 120, 200, 280, 360 | + +Z is 0 for every brick. A 2 x 4 brick is 80 long, so X steps by 80 along a course; the shifted courses start at 40 and stick out half a brick at the right-hand end, which is the toothed end of a running bond. The part number comes from `parts.search` with `brick 2 x 4` (answer `3001`); colour 4 is red. + +## Before you start + +1. `formblocks_status`: note `dirty`. If it is true, ask the person whether to save their model first; `model.new` refuses while there are unsaved changes. +2. `library.status`: `found` must be true (`sub-skills/parts-library/SUB-SKILL.md`). + +## The commands + +From the root of the FormBlocks checkout, with the app running (or not: the command line then works on the same data folder): + +```bash +./formblocks cli parts search "brick 2 x 4" --lines --limit 1 +./formblocks cli run model.new +./formblocks cli run part.place part=3001 colour=4 'position=[0,-24,0]' step=1 +./formblocks cli run part.place part=3001 colour=4 'position=[80,-24,0]' step=1 +./formblocks cli run part.place part=3001 colour=4 'position=[160,-24,0]' step=1 +./formblocks cli run part.place part=3001 colour=4 'position=[240,-24,0]' step=1 +./formblocks cli run part.place part=3001 colour=4 'position=[320,-24,0]' step=1 +./formblocks cli run part.place part=3001 colour=4 'position=[40,-48,0]' step=2 +./formblocks cli run part.place part=3001 colour=4 'position=[120,-48,0]' step=2 +./formblocks cli run part.place part=3001 colour=4 'position=[200,-48,0]' step=2 +./formblocks cli run part.place part=3001 colour=4 'position=[280,-48,0]' step=2 +./formblocks cli run part.place part=3001 colour=4 'position=[360,-48,0]' step=2 +./formblocks cli run part.place part=3001 colour=4 'position=[0,-72,0]' step=3 +./formblocks cli run part.place part=3001 colour=4 'position=[80,-72,0]' step=3 +./formblocks cli run part.place part=3001 colour=4 'position=[160,-72,0]' step=3 +./formblocks cli run part.place part=3001 colour=4 'position=[240,-72,0]' step=3 +./formblocks cli run part.place part=3001 colour=4 'position=[320,-72,0]' step=3 +./formblocks cli run part.place part=3001 colour=4 'position=[40,-96,0]' step=4 +./formblocks cli run part.place part=3001 colour=4 'position=[120,-96,0]' step=4 +./formblocks cli run part.place part=3001 colour=4 'position=[200,-96,0]' step=4 +./formblocks cli run part.place part=3001 colour=4 'position=[280,-96,0]' step=4 +./formblocks cli run part.place part=3001 colour=4 'position=[360,-96,0]' step=4 +./formblocks cli run overlap.check +./formblocks cli run step.list +./formblocks cli run model.save_as path=/tmp/wall.fblk +``` + +`step=2` on the first brick of course 2 is one past the last step, so it starts step 2; the same holds for steps 3 and 4. + +## The same through MCP + +Each `run` line is one tool call. The first brick: + +```json +{"name": "cmd_part_place", "arguments": {"part": "3001", "colour": 4, "position": [0, -24, 0], "step": 1}} +``` + +`cmd_model_new` takes no arguments, `cmd_overlap_check` and `cmd_step_list` none either, and `cmd_model_save_as` takes `{"path": "/tmp/wall.fblk"}` (a full path; ask the person where they want it). From outside the window the first change waits for the person (`sub-skills/working-with-the-person/SUB-SKILL.md`). `scripts/build_wall.py` makes exactly these calls against a running app. + +## What you should see + +- Every `part.place` answers `"seated": true`. Course 1 joins the ground (8 pairs each, `ground` entries in `joined`); each brick of courses 2 to 4 joins two bricks below with 8 pairs, except the three that hang half over an end of the course below: the last brick of courses 2 and 4 and the first brick of course 3 join one brick with 4 pairs. +- The ids are `p1` to `p20` in a model started with `model.new`; read them from the answers rather than counting. +- `overlap.check` answers `"count": 0` with `"checked": 20`. +- `step.list` answers four steps of five placements each. +- `model.save_as` answers `"writtenKind": "fblk"` and `"dirty": false`. + +## Variations + +- Flush ends: make courses 2 and 4 a 2 x 2 brick (`3003`) at X = -20, four 2 x 4 bricks at X = 40, 120, 200 and 280, and a 2 x 2 brick at X = 340, so every course runs from X = -40 to 360. That is 22 bricks in all. +- Faster: place one brick, then `part.duplicate` it with `delta` `[80, 0, 0]`, four times, duplicating the newest copy each time. +- A thin wall: 1 x 4 bricks (`3010`) at Z = 10, the same X values. diff --git a/.claude/skills/formblocks-driving/references/command-catalogue.md b/.claude/skills/formblocks-driving/references/command-catalogue.md index d68aedc..cf4c680 100644 --- a/.claude/skills/formblocks-driving/references/command-catalogue.md +++ b/.claude/skills/formblocks-driving/references/command-catalogue.md @@ -2,6 +2,11 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never edit it by hand. `./formblocks agents check` fails when it differs from the catalogue. +## Contents + +- MCP tools: the 67 tools an agent sees, each with whether it only reads. +- Commands: the 61 catalogue commands with their titles, parameters and summaries, in name order. + ## MCP tools | Tool | Reads only | What it does | @@ -12,8 +17,12 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `formblocks_redo` | no | Redo changes that formblocks_undo took back, one step each. A new change after an undo empties what can be redone. Returns {revision, labels, label}. | | `formblocks_status` | yes | Read what this FormBlocks is: its version, the model's revision, placement count, file and unsaved mark, how many commands there are, its data folder, whether the window's engine is running, and the person's standing choice for outside agents (ask, allowed or blocked). Call it first. | | `formblocks_undo` | no | Undo the last changes, one step per command. Returns {revision, labels, label}: the new revision and the titles of the commands taken back, newest first. Nothing to undo answers an empty labels list. | +| `cmd_colours_current` | yes | Choose the colour the next placed part gets, and put it at the front of the recent colours. Kept as the person's setting; it recolours nothing. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | | `cmd_colours_list` | yes | List the library's colours with code, name, value, edge and finish, or the swatches of one group, hue family or name words. Only reads. | +| `cmd_colours_used` | yes | List the colours used in the open model, most used first: each colour's number, name, value, how many parts of the whole model are in it, and whether the library defines it. Only reads. | +| `cmd_grid_step` | yes | Choose the grid step: stud (20 LDU across, 8 up), plate (10 across, 8 up) or fine (1 and 1). Kept as the person's setting. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | | `cmd_library_status` | yes | Read whether a parts library is in use, where it was found, its update, whether its index is ready, the fetch in progress if any, and the consent and attribution the library card shows. Reading never fetches; only the person can consent to a fetch. Only reads. | +| `cmd_model_info` | yes | Read the model's name, author, file and library update, its counts (parts through every use, different parts, part and colour pairs, submodels, steps), its size in LDU, studs, bricks and millimetres, and its parts list. Only reads. | | `cmd_model_insert` | no | Bring another .ldr, .mpd or .fblk file into the open model as new submodels and place one use of its main model. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_model_new` | no | Start a new model named Untitled with one empty step, and a new history. Opens, starts or writes a model file; not an undo step. An outside agent waits for the person to allow it in the window. | | `cmd_model_open` | no | Open a .fblk, .ldr, .mpd or .dat file by its full path; a library part file opens as a new model holding one placement of the part. Opens, starts or writes a model file; not an undo step. An outside agent waits for the person to allow it in the window. | @@ -21,20 +30,28 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `cmd_model_report` | yes | Read what opening the model reported: lines that could not be read, with their line numbers, and the text encoding. Only reads. | | `cmd_model_save` | no | Save the model to the project file it came from; a model from an LDraw file or never saved needs model.save_as with a .fblk path. Opens, starts or writes a model file; not an undo step. An outside agent waits for the person to allow it in the window. | | `cmd_model_save_as` | no | Write the model to a new path: .fblk saves the project file and makes it the model's file; .ldr or .mpd exports LDraw without FormBlocks' own state. Opens, starts or writes a model file; not an undo step. An outside agent waits for the person to allow it in the window. | +| `cmd_model_set_info` | no | Change the main model's title, author or licence, as written in its header: the licence is empty or one of the Creative Commons licences listed in its parameter. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_model_tree` | yes | Read one submodel's steps and placements, each with its id, part, colour, position, rotation, step and hidden mark, and the submodels with their uses. Only reads. | | `cmd_overlap_check` | yes | List each pair of overlapping placements with the depth of the overlap in LDU, for the given placements or the whole model; parts joined through seated connectors never count. Only reads. | +| `cmd_overlap_set` | yes | Turn the coarse overlap check on or off: with it on, placing and moving never put a part where its box would overlap another's. Kept as the person's setting. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | | `cmd_part_connectors` | yes | List a library part's connectors as the connection model derives them: kind, position, axis and where each came from, with the counts, the body box and the footprint. Only reads. | | `cmd_part_delete` | no | Remove placements from the model; deleting the last use of a submodel keeps the submodel. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_duplicate` | no | Copy placements, keeping colours and relative places, offset by delta; the copies go into the step shown and become the selection. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | +| `cmd_part_duplicate_at_ray` | no | Drop copies of a selection where a pointer ray in the window's scene axes takes the copy of the grabbed placement, seated, on the grid or refused as the drag preview with copy answers; the copies keep their colours and places relative to one another, go into the step shown and become the selection. One undo step. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_fit` | yes | Answer where a part would go and which connectors it would join, from a position, a placement to seat on, or a pointer ray, with snapping, the grid step and the overlap check as set; changes nothing. Only reads. | | `cmd_part_hide` | no | Hide placements: they stay in the model but are not drawn or picked, and the project file remembers it. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_hide_others` | no | Hide every placement of the submodel being edited except the given ones or the selection, to work on one area alone. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_move` | no | Move placements by an offset in LDU, exactly, with no snapping. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | +| `cmd_part_move_at_ray` | no | Put down a dragged selection where a pointer ray in the window's scene axes takes the grabbed placement, seated, on the grid or refused exactly as the drag preview answers; the others keep their places relative to it. One undo step. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | +| `cmd_part_pick` | yes | Name the placement of the submodel being edited that a pointer ray in the window's scene axes meets first on its real triangles, with the point and the face's normal, or the ground; hidden parts are passed through. Only reads. | | `cmd_part_place` | no | Place a part, or a use of a submodel, in a colour: at a position, seated on its connectors when snapping is on, or seated on another placement with on; it goes into the step shown and becomes the selection. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | +| `cmd_part_place_at_ray` | no | Place a library part where a pointer ray in the window's scene axes puts it, seated, on the grid or refused exactly as the placement preview answers; it goes into the step shown of the submodel being edited and becomes the selection. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_recolour` | no | Give placements a colour; a use of a submodel in colour 16 passes it to its parts in colour 16. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_rotate` | no | Turn placements by quarter turns about the X, Y or Z axis through a point, by default the centre of their origins. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_set_transform` | no | Put one placement at an exact position, rotation or both, as the details panel does. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_show` | no | Show hidden placements again; every hidden placement in the model when no ids are given (Show all). Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | +| `cmd_parts_list` | yes | Read the parts a model needs, one row per part and colour with its description, colour name and count, a submodel's parts counted once for each use; parts missing from the library first. Only reads. | +| `cmd_parts_list_save` | no | Write the parts list to a file as CSV: a header row, then one row per part and colour with part number, description, colour number, colour name and count; comma separated, or tab separated for a .tsv path or separator tab. Opens, starts or writes a model file; not an undo step. An outside agent waits for the person to allow it in the window. | | `cmd_parts_search` | yes | Search the parts library by words, part number or category, ranked as the parts palette ranks them; each hit has its number, description, category and keywords, and a moved number says where it moved. Only reads. | | `cmd_parts_show` | yes | Show one part of the library: its description, category, keywords, author and licence, following a moved number to the part it moved to. Only reads. | | `cmd_select_add` | yes | Add placements to the selection. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | @@ -46,6 +63,7 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `cmd_select_invert` | yes | Select every visible placement that was not selected and let go of the rest. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | | `cmd_select_remove` | yes | Let go of placements without touching the rest of the selection. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | | `cmd_select_set` | yes | Make the selection exactly these placements; an empty list clears it. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | +| `cmd_snap_set` | yes | Turn snapping on or off: with it on, a part being placed or moved seats on free compatible connectors within reach; with it off, it moves in grid steps only. Kept as the person's setting. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | | `cmd_step_break_after` | no | Start a new step after a placement, moving the placements after it in its step into the new step; with no id, add an empty step after the step shown and show it. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_step_delete` | no | Delete a step; its placements move to the start of the next step, or to the end of the step before when it is the last. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_step_goto` | yes | Show a step of the submodel being edited: every placement of steps 1 to it is drawn, and new parts go into it. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | @@ -65,8 +83,12 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | Command | Title | Reads only | Parameters | What it does | | --- | --- | --- | --- | --- | +| `colours.current` | Current Colour | yes | `colour` (integer) | Choose the colour the next placed part gets, and put it at the front of the recent colours. Kept as the person's setting; it recolours nothing. | | `colours.list` | Colours | yes | `text` (string, optional), `group` (string, optional), `hue` (string, optional) | List the library's colours with code, name, value, edge and finish, or the swatches of one group, hue family or name words. | +| `colours.used` | Colours Used | yes | none | List the colours used in the open model, most used first: each colour's number, name, value, how many parts of the whole model are in it, and whether the library defines it. | +| `grid.step` | Grid Step | yes | `step` (string) | Choose the grid step: stud (20 LDU across, 8 up), plate (10 across, 8 up) or fine (1 and 1). Kept as the person's setting. | | `library.status` | Library Status | yes | none | Read whether a parts library is in use, where it was found, its update, whether its index is ready, the fetch in progress if any, and the consent and attribution the library card shows. Reading never fetches; only the person can consent to a fetch. | +| `model.info` | Model Information | yes | none | Read the model's name, author, file and library update, its counts (parts through every use, different parts, part and colour pairs, submodels, steps), its size in LDU, studs, bricks and millimetres, and its parts list. | | `model.insert` | Insert LDraw Model | no | `path` (string), `position` (array, optional), `submodel` (string, optional) | Bring another .ldr, .mpd or .fblk file into the open model as new submodels and place one use of its main model. | | `model.new` | New Model | no | `discard` (boolean, optional) | Start a new model named Untitled with one empty step, and a new history. | | `model.open` | Open | no | `path` (string), `discard` (boolean, optional) | Open a .fblk, .ldr, .mpd or .dat file by its full path; a library part file opens as a new model holding one placement of the part. | @@ -74,20 +96,28 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `model.report` | Open Report | yes | none | Read what opening the model reported: lines that could not be read, with their line numbers, and the text encoding. | | `model.save` | Save | no | none | Save the model to the project file it came from; a model from an LDraw file or never saved needs model.save_as with a .fblk path. | | `model.save_as` | Save As | no | `path` (string) | Write the model to a new path: .fblk saves the project file and makes it the model's file; .ldr or .mpd exports LDraw without FormBlocks' own state. | +| `model.set_info` | Set Model Information | no | `title` (string, optional), `author` (string, optional), `licence` (string, optional) | Change the main model's title, author or licence, as written in its header: the licence is empty or one of the Creative Commons licences listed in its parameter. | | `model.tree` | Model Tree | yes | `submodel` (string, optional) | Read one submodel's steps and placements, each with its id, part, colour, position, rotation, step and hidden mark, and the submodels with their uses. | | `overlap.check` | Check Overlaps | yes | `ids` (array, optional) | List each pair of overlapping placements with the depth of the overlap in LDU, for the given placements or the whole model; parts joined through seated connectors never count. | +| `overlap.set` | Overlap Check | yes | `on` (boolean) | Turn the coarse overlap check on or off: with it on, placing and moving never put a part where its box would overlap another's. Kept as the person's setting. | | `part.connectors` | Part Connectors | yes | `part` (string) | List a library part's connectors as the connection model derives them: kind, position, axis and where each came from, with the counts, the body box and the footprint. | | `part.delete` | Delete | no | `ids` (array, optional) | Remove placements from the model; deleting the last use of a submodel keeps the submodel. | | `part.duplicate` | Duplicate | no | `ids` (array, optional), `delta` (array, optional) | Copy placements, keeping colours and relative places, offset by delta; the copies go into the step shown and become the selection. | +| `part.duplicate_at_ray` | Duplicate at Pointer | no | `grab` (string), `origin` (array), `direction` (array), `rotation` (array, optional), `held` (integer, optional), `ids` (array, optional), `snap` (boolean, optional) | Drop copies of a selection where a pointer ray in the window's scene axes takes the copy of the grabbed placement, seated, on the grid or refused as the drag preview with copy answers; the copies keep their colours and places relative to one another, go into the step shown and become the selection. One undo step. | | `part.fit` | Fit Part | yes | `part` (string), `rotation` (array, optional), `position` (array, optional), `on` (string, optional), `origin` (array, optional), `direction` (array, optional), `ids` (array, optional), `submodel` (string, optional), `snap` (boolean, optional) | Answer where a part would go and which connectors it would join, from a position, a placement to seat on, or a pointer ray, with snapping, the grid step and the overlap check as set; changes nothing. | | `part.hide` | Hide | no | `ids` (array, optional) | Hide placements: they stay in the model but are not drawn or picked, and the project file remembers it. | | `part.hide_others` | Hide Others | no | `ids` (array, optional) | Hide every placement of the submodel being edited except the given ones or the selection, to work on one area alone. | | `part.move` | Move | no | `ids` (array, optional), `delta` (array) | Move placements by an offset in LDU, exactly, with no snapping. | +| `part.move_at_ray` | Move Selection at Pointer | no | `grab` (string), `origin` (array), `direction` (array), `rotation` (array, optional), `held` (integer, optional), `ids` (array, optional), `snap` (boolean, optional) | Put down a dragged selection where a pointer ray in the window's scene axes takes the grabbed placement, seated, on the grid or refused exactly as the drag preview answers; the others keep their places relative to it. One undo step. | +| `part.pick` | Pick at Pointer | yes | `origin` (array), `direction` (array), `ground` (boolean, optional) | Name the placement of the submodel being edited that a pointer ray in the window's scene axes meets first on its real triangles, with the point and the face's normal, or the ground; hidden parts are passed through. | | `part.place` | Place Part | no | `part` (string), `colour` (integer), `position` (array, optional), `rotation` (array, optional), `submodel` (string, optional), `step` (integer, optional), `on` (string, optional), `snap` (boolean, optional) | Place a part, or a use of a submodel, in a colour: at a position, seated on its connectors when snapping is on, or seated on another placement with on; it goes into the step shown and becomes the selection. | +| `part.place_at_ray` | Place Part at Pointer | no | `part` (string), `colour` (integer), `origin` (array), `direction` (array), `rotation` (array, optional), `held` (integer, optional), `step` (integer, optional), `snap` (boolean, optional) | Place a library part where a pointer ray in the window's scene axes puts it, seated, on the grid or refused exactly as the placement preview answers; it goes into the step shown of the submodel being edited and becomes the selection. | | `part.recolour` | Recolour | no | `ids` (array, optional), `colour` (integer) | Give placements a colour; a use of a submodel in colour 16 passes it to its parts in colour 16. | | `part.rotate` | Rotate | no | `ids` (array, optional), `axis` (string), `quarter_turns` (integer), `about` (array, optional) | Turn placements by quarter turns about the X, Y or Z axis through a point, by default the centre of their origins. | | `part.set_transform` | Set Position and Rotation | no | `id` (string), `position` (array, optional), `rotation` (array, optional) | Put one placement at an exact position, rotation or both, as the details panel does. | | `part.show` | Show | no | `ids` (array, optional) | Show hidden placements again; every hidden placement in the model when no ids are given (Show all). | +| `parts.list` | Parts List | yes | `scope` (string, optional), `group` (string, optional) | Read the parts a model needs, one row per part and colour with its description, colour name and count, a submodel's parts counted once for each use; parts missing from the library first. | +| `parts.list_save` | Save Parts List | no | `path` (string), `separator` (string, optional), `scope` (string, optional), `group` (string, optional) | Write the parts list to a file as CSV: a header row, then one row per part and colour with part number, description, colour number, colour name and count; comma separated, or tab separated for a .tsv path or separator tab. | | `parts.search` | Search Parts | yes | `text` (string, optional), `category` (string, optional), `list` (string, optional), `printed` (boolean, optional), `limit` (integer, optional), `offset` (integer, optional) | Search the parts library by words, part number or category, ranked as the parts palette ranks them; each hit has its number, description, category and keywords, and a moved number says where it moved. | | `parts.show` | Part Details | yes | `part` (string) | Show one part of the library: its description, category, keywords, author and licence, following a moved number to the part it moved to. | | `select.add` | Add to Selection | yes | `ids` (array) | Add placements to the selection. | @@ -99,6 +129,7 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `select.invert` | Invert Selection | yes | none | Select every visible placement that was not selected and let go of the rest. | | `select.remove` | Remove from Selection | yes | `ids` (array) | Let go of placements without touching the rest of the selection. | | `select.set` | Select | yes | `ids` (array) | Make the selection exactly these placements; an empty list clears it. | +| `snap.set` | Snapping | yes | `on` (boolean) | Turn snapping on or off: with it on, a part being placed or moved seats on free compatible connectors within reach; with it off, it moves in grid steps only. Kept as the person's setting. | | `step.break_after` | New Step | no | `id` (string, optional) | Start a new step after a placement, moving the placements after it in its step into the new step; with no id, add an empty step after the step shown and show it. | | `step.delete` | Delete Step | no | `step` (integer), `submodel` (string, optional) | Delete a step; its placements move to the start of the next step, or to the end of the step before when it is the last. | | `step.goto` | Show Step | yes | `index` (integer) | Show a step of the submodel being edited: every placement of steps 1 to it is drawn, and new parts go into it. | diff --git a/.claude/skills/formblocks-driving/references/coordinates-and-units.md b/.claude/skills/formblocks-driving/references/coordinates-and-units.md new file mode 100644 index 0000000..c814afa --- /dev/null +++ b/.claude/skills/formblocks-driving/references/coordinates-and-units.md @@ -0,0 +1,74 @@ +# Coordinates, units and quarter turns + +## Contents + +- Units +- The axes +- Where a part's origin is +- Standing a part on the ground +- Stacking +- Quarter turns as matrices +- Working out a position by hand + +## Units + +Every length FormBlocks takes or answers is in LDU, the LDraw unit (about 0.4 mm). The numbers are the same ones an `.ldr` file holds, so a position read from a file, typed in a panel, given to `part.place` or read back from `model.tree` means the same place. + +| Measure | LDU | +| --- | --- | +| Stud pitch (centre of one stud to the next) | 20 | +| Brick height | 24 | +| Plate height (a third of a brick) | 8 | +| Stud height (the knob on top) | 4 | +| Largest position accepted on any axis | 1000000 | + +Two plates are 16, three plates are a brick. A 2 x 4 brick is 80 by 40 across and 24 high, not counting its studs. + +## The axes + +- X runs left and right, Z runs front and back, Y runs up and down. +- -Y is up. A part higher in the model has a more negative Y. The ground is the plane Y = 0 and everything standing on it has Y below 0. +- The front of the model faces -Z: the front view looks from the -Z side towards +Z. +- The axes are right-handed. +- The window draws with +Y up, but that conversion happens inside the engine only. Never flip a sign yourself: every number you send or read is on the LDraw axes. + +## Where a part's origin is + +A placement's `position` is where the part's own origin goes. For an ordinary part from the library (brick, plate, tile, slope) the origin is in the middle of the stud grid on its top surface, at the foot of the studs: the studs stand above it (Y from 0 to -4 in the part's own axes) and the body hangs below it (Y from 0 to 24 for a brick, 0 to 8 for a plate or tile). + +`part.connectors` with a part number answers its footprint (`x0`, `x1`, `z0`, `z1`), its bottom plane (`bottom`, 24 for a brick, 8 for a plate) and the place of every stud and anti-stud in the part's own axes. Read it before placing a part whose shape you do not know: a 45 degree slope 2 x 2 (3039), for example, has its origin over its back row of studs and its sloped face running out to Z = -30. + +## Standing a part on the ground + +- A brick standing on the ground has its origin at Y = -24; a plate or tile at Y = -8; a 2 x 2 slope at Y = -24. +- The ground offers a stud at every point (10 + 20i, 0, 10 + 20k). A part seats on the ground when its anti-studs land on those points. +- So across, an origin sits on a multiple of 20 when the part is an even number of studs long on that axis (2, 4, 6) and on 10 plus a multiple of 20 when it is odd (1, 3). A 2 x 4 brick at (0, -24, 0) seats; a 1 x 1 brick seats at (10, -24, 10) or (-30, -24, 30); a 1 x 4 brick lying along X seats at (0, -24, 10). +- A position within 15 LDU of a seat is pulled into the seat when snapping is on, so a small rounding slip does no harm. Further off, the part is put on the grid step instead and the answer says `seated: false`. + +## Stacking + +- Each brick course is 24 lower in Y than the one below: courses stand at Y = -24, -48, -72, -96. +- A plate on top of a brick course whose top is at Y = -96 goes at Y = -104 (one plate, 8, higher). +- In general: origin Y of the new part = top of what it stands on minus the new part's own `bottom`. + +## Quarter turns as matrices + +`rotation` is the nine numbers of the 3 by 3 matrix of an LDraw type 1 line, row by row. Leave it out for no turn. + +| Turn | `rotation` | +| --- | --- | +| None | `[1,0,0, 0,1,0, 0,0,1]` | +| A quarter turn about Y (a part long along X now runs along Z) | `[0,0,1, 0,1,0, -1,0,0]` | +| The other quarter turn about Y | `[0,0,-1, 0,1,0, 1,0,0]` | +| A half turn about Y (a slope facing front now faces back) | `[-1,0,0, 0,1,0, 0,0,-1]` | + +A part turned a quarter turn about Y swaps its X and Z extents: a 1 x 4 brick turned this way covers 20 across X and 80 along Z, so its origin sits on 10 plus a multiple of 20 in X and on a multiple of 20 in Z. + +To turn parts that are already placed, use `part.rotate` with `axis` (`x`, `y` or `z`) and `quarter_turns`; it turns them about the centre of their origins, or about `about` when given, and works out the new matrices itself. Tipping (about X) and rolling (about Z) are possible the same way; snapping never turns a part on its own. + +## Working out a position by hand + +1. Decide which stud cells the part should cover, as cell centres (10 + 20i, 10 + 20k). +2. The origin across is the middle of those cells. +3. The origin's Y is the top of what it stands on (0 for the ground) minus the part's `bottom`. +4. Place it, and check `seated: true` in the answer. diff --git a/.claude/skills/formblocks-driving/references/error-codes.md b/.claude/skills/formblocks-driving/references/error-codes.md new file mode 100644 index 0000000..4b99da4 --- /dev/null +++ b/.claude/skills/formblocks-driving/references/error-codes.md @@ -0,0 +1,84 @@ +# Errors and what to do about each + +## Contents + +- Exit codes of the command line +- How an MCP call fails +- Refusals by the person +- Refusals by a command +- Answers that succeed but need a second look + +A failed call changes nothing: the model, the selection and the history are as they were. So the right move after any error is to read the sentence, fix the call, and send it once. + +## Exit codes of the command line + +| Exit | Meaning | What to do | +| --- | --- | --- | +| 0 | The command did what was asked. The JSON has `"ok": true`. | Read the result. | +| 1 | The command failed or was refused; `"ok": false` and `"error"` holds one sentence. | Fix what the sentence names. | +| 2 | A usage mistake: an unknown subcommand or a malformed option. A sentence goes to standard error. | Read `./formblocks cli --help`. | + +## How an MCP call fails + +| What comes back | Code | Meaning | What to do | +| --- | --- | --- | --- | +| A JSON-RPC error, "Unknown tool: ..." | -32602 | The tool name is not in `tools/list`. | Read `formblocks_list_commands`; call `formblocks_execute` with a listed id. | +| A JSON-RPC error, "Missing required argument ...", "Unknown argument ...", "Argument ... must be a ..." | -32602 | The arguments do not match the tool's schema. Nothing ran. | Fix the argument names and types. | +| A JSON-RPC error, "Method not found" | -32601 | Not an MCP method the server has. | Use `tools/list` and `tools/call`. | +| A JSON-RPC error, "Parse error" | -32700 | The line was not JSON. | Send one JSON object per line. | +| A JSON-RPC error, "Unsupported protocol version" | -32022 | The client asked for a protocol version the server does not speak; the error lists the supported ones. | Initialise with one of them. | +| A JSON-RPC error, "FormBlocks is not accepting connections at ..." | -32603 | The bridge started with `--connect` found no engine. The call did not run. | Ask the person to start FormBlocks, or run the server headless for reading. | +| A JSON-RPC error, "The reply was lost, so this call may have run" | -32603 | The engine stopped answering in the middle of a call. | Read the model (`cmd_model_tree`) before sending it again. | +| A JSON-RPC error, "Cannot read the window key file" | -32603 | The bridge cannot find the running engine's data folder. | Give the same `FORMBLOCKS_DATA_DIR` the app uses. | +| A tool result with `isError: true` and `"refused": true` | none | The person, or the absence of a person, stopped the change. See below. | Do not resend it unchanged. | +| A tool result with `isError: true` and `"ok": false` | none | The command refused the call. See below. | Fix what the sentence names. | + +## Refusals by the person + +These come back only for `change` and `file` commands and for undo and redo, sent from outside the window. + +| The sentence says | Why | What to do | +| --- | --- | --- | +| "The person declined this change in the FormBlocks window." | They chose Deny. | Say what you meant to do and let them choose. Do not try it another way. | +| "Nobody answered in the FormBlocks window within 120 seconds" | Nobody was looking. | Ask the person to look at the window, then send it once more. | +| "The person has blocked outside agents in FormBlocks." | Their standing choice is `blocked`. | Stop changing the model; reading still works. | +| "FormBlocks is not open, so nobody can allow this change." | The server is headless and the person has not allowed this program always. | Ask the person to start the app. | + +## Refusals by a command + +A command's sentence starts with the parameter it is about (`part:`, `on:`, `ids:`), so the fix is in that argument. + +| The sentence starts or says | What to do | +| --- | --- | +| "part: ... is not in the LDraw parts library in use" | Search with `parts.search` and place the number it answers. A number with letters (`3068b`) is a different part from the bare number. | +| "No LDraw parts library is installed" | Nothing can be placed. Tell the person; only they can find or fetch the library (`sub-skills/parts-library/SUB-SKILL.md`). | +| "position: give a position, a placement to seat on (on), or a pointer ray" | `part.place` needs `position` or `on`. | +| "position: the part would overlap ... with the overlap check on" | The person's overlap check is on and the place is taken. Pick another place; the overlap check's box is coarse round slopes, so tell the person if a slope is refused where it should fit. | +| "... must stay within 1000000 LDU of the origin" | A position or offset is out of range: check signs and units. | +| "on: ... has no free connector that ... can seat on" | Every stud of that placement is taken. Seat on another placement, or give a position. | +| "on: ... is hidden" | Hidden parts offer no connectors. Show it with `part.show` first, or use a position. | +| "on: ... is in ..., not in ..." | `on` must name a placement in the submodel the part goes into. | +| "ids: there is no placement ..." | The id is wrong or was deleted. Read `model.tree` for current ids. | +| "ids: give placement ids, or select parts first." | Pass `ids`; do not rely on the selection unless you set it. | +| "... is hidden; show it before selecting it." | Show it, or leave it out. | +| "... is not in ..., the submodel being edited." | Selection commands act inside the submodel being edited: `submodel.enter` or `submodel.leave` first. | +| "colour must be a colour code from 0" | Use a code from `colours.list`. | +| "rotation is flat (its determinant is zero)" | The nine numbers do not make a turn. Leave `rotation` out for no turn, or use `[0,0,1, 0,1,0, -1,0,0]` for a quarter turn about Y and `[0,0,-1, 0,1,0, 1,0,0]` for the other. | +| "axis must be x, y or z" | `part.rotate` takes the letter of an LDraw axis. | +| "step must be from 1 to ..." | Read `step.list`. For `part.place`, one past the last step starts a new step. | +| "step: ... has one step, which cannot be deleted." | A submodel keeps at least one step. | +| "discard: the open model has unsaved changes" | Ask the person whether to save first; pass `discard: true` only after they say to drop the changes. | +| "path: the model has no project file yet" | `model.save` needs a project file; use `model.save_as` with a `.fblk` path. | +| "name: the model already has a block named ..." | Pick another submodel name. | +| "part: ... holds ..., so a use of it there would hold itself." | A submodel cannot contain itself. Place it in another submodel. | +| "with_uses: ... has ... uses" | `submodel.delete` keeps a used submodel unless `with_uses` is true. Ask before deleting uses. | +| "There is no command ..." | The id is wrong; read the catalogue. | +| "... needs ... (...)" or "... takes no parameter ..." | A required parameter is missing, or a name is wrong; read the command's entry. | + +## Answers that succeed but need a second look + +- `part.place` answering `"seated": false`: the part did not join anything. With the overlap check off (its first setting) it was put on the grid step instead and may float in the air or sit inside another part. Undo it and fix the position, unless a loose part is what you meant. +- `part.place` with `on` seating on a different part of the target than you wanted: `on` takes the first free studs nearest the target's middle. Give a position for an exact place. +- `overlap.check` answering a `count` above 0: two parts share space. Undo the newer one or move it. +- `model.open` answering an `issueCount` above 0: some lines could not be read; `model.report` lists them. The rest of the file opened. +- A JSON-RPC timeout on a `change` sent from outside: the person may still have the question open. Read the model before sending again. diff --git a/.claude/skills/formblocks-driving/references/tool-naming.md b/.claude/skills/formblocks-driving/references/tool-naming.md new file mode 100644 index 0000000..ae47dc4 --- /dev/null +++ b/.claude/skills/formblocks-driving/references/tool-naming.md @@ -0,0 +1,67 @@ +# Tool naming + +## Contents + +- One catalogue, three ways in +- The six fixed tools +- The cmd_ tools +- The command line +- The same call three ways +- Names that do not exist + +## One catalogue, three ways in + +Every action on the model is a command in the engine's one catalogue, with an id written `area.verb` (`part.place`, `step.rename`). The window's buttons, the command line and the MCP tools all run the same command with the same parameters, so a parameter name learned in one place holds in the others. `formblocks_list_commands` (or `./formblocks cli commands`) answers the live catalogue, and wins over any copy of it written into this pack. + +Each command has a kind, which decides what it may do: + +| Kind | What it does | Undo step | Waits for the person when sent from outside the window | +| --- | --- | --- | --- | +| `read` | Reads only. | No | No | +| `view` | Changes the selection, the step shown or the submodel being edited. | No | No | +| `change` | Changes the model, hiding and showing included. | One, however many parts it touches | Yes | +| `file` | Starts, opens or writes a model file. | Never; new and open start a new history | Yes | + +## The six fixed tools + +| Tool | What it does | +| --- | --- | +| `formblocks_status` | Version, revision, placement count, file, unsaved mark, command count, data folder, whether the window's engine is running, and the person's standing choice for outside agents. Call it first. | +| `formblocks_list_commands` | The catalogue: name, title, summary, typed parameters, kind and the `cmd_` tool; `filter` keeps commands whose name, title or summary holds a word. | +| `formblocks_get_doc` | The whole open model, the view and the revision. Large on a big model; `cmd_model_tree` answers one submodel. | +| `formblocks_execute` | Runs any command by id: `{"command": "part.place", "params": {...}}`. | +| `formblocks_undo` | Takes back the newest changes, one per command; `steps` for more than one. | +| `formblocks_redo` | Puts back what undo took back. | + +A program started from a tab of the window's agent dock sees the same tools under a server named `formblocks_tab`; a program registered by `./formblocks agents install` sees them under `formblocks`. + +## The cmd_ tools + +Each command is also a tool of its own, named `cmd_` and the id with every dot and dash made an underscore: `part.place` is `cmd_part_place`, `step.break_after` is `cmd_step_break_after`, `overlap.check` is `cmd_overlap_check`. Its arguments are the command's parameters, checked against the schema before the call runs: a missing required argument, an argument the command does not take, or a value of the wrong type is refused with one sentence and nothing runs. + +The tool's description ends with its kind in words: "Only reads", "Changes only the view", "Changes the model; one undo step" or "Opens, starts or writes a model file". Its annotations say the same: `readOnlyHint` true for `read` commands only. + +## The command line + +`./formblocks cli run [id] [name=value ...]` runs one command and prints one JSON object. Values are read as JSON when they are JSON and as text otherwise: `colour=4`, `position=[0,-24,0]`, `snap=false`, `part=3001`. Quote a value that holds brackets or spaces for the shell: `'position=[0,-24,0]'`. One JSON object can stand for all the parameters instead. `--compact` prints the answer on one line. + +Beside `run` the command line has its own subcommands for what is not a catalogue command: `commands`, `doc`, `undo`, `redo`, `mcp`, `parts search`, `parts show`, `part-mesh`, `library status`, `library use`, `library fetch`, `library check-update` and `colours`. `./formblocks cli --help` lists them. + +When an engine is running on the same data folder, `cli` sends the command through it and the window shows the change at once; with none it runs in its own process on the same data folder, so the open model and its undo history carry over between runs. + +## The same call three ways + +| Way in | Call | +| --- | --- | +| A `cmd_` tool | `cmd_part_place` with `{"part": "3001", "colour": 4, "position": [0, -24, 0]}` | +| The fixed tool | `formblocks_execute` with `{"command": "part.place", "params": {"part": "3001", "colour": 4, "position": [0, -24, 0]}}` | +| The command line | `./formblocks cli run part.place part=3001 colour=4 'position=[0,-24,0]'` | + +All three answer `{ok, command, result, revision}`; a change also answers `undo`, the label the Edit menu shows for it. + +## Names that do not exist + +- The tables of `spec/SPEC.md` sections 1 to 19 were written before the catalogue and use some older ids (`selection.move`, `file.save`, `step.show`). The catalogue's ids are the ones that run: `part.move`, `model.save_as`, `step.goto`. +- Undo and redo are not catalogue commands: there is no `edit.undo` tool. Use `formblocks_undo` and `formblocks_redo`, or `./formblocks cli undo` and `redo`. +- Fetching the library is not a command and no tool starts it (`sub-skills/parts-library/SUB-SKILL.md`). +- A tool the server does not list does not exist. Do not guess a name from a pattern; read `formblocks_list_commands`. diff --git a/.claude/skills/formblocks-driving/scripts/build_wall.py b/.claude/skills/formblocks-driving/scripts/build_wall.py new file mode 100755 index 0000000..f6b1828 --- /dev/null +++ b/.claude/skills/formblocks-driving/scripts/build_wall.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Build the wall of twenty bricks (examples/wall.md) in a running FormBlocks through its MCP server. Standard library only. + +usage: build_wall.py [--root DIR] [--connect HOST:PORT|auto] [--colour CODE] [--save PATH] +Starts ROOT/formblocks mcp --connect (auto by default), so it works only against a running app and never headless. +It checks status and the library, starts a new model (refused while the person's model has unsaved changes), +places four courses of five 2 x 4 bricks in running bond, one course per step, runs the overlap check and, +with --save, saves the model as a .fblk. Every change waits for the person in the window until they allow it. +exit 0 built and checked, 1 a call failed or was refused, 2 the server or the app could not be reached. +""" +import argparse +import json +import os +import subprocess +import sys +import threading + +REPLY_TIMEOUT = 150.0 +PART = "3001" +COURSES = 4 +BRICKS = 5 +LENGTH = 80 +HEIGHT = 24 + + +class Failed(Exception): + pass + + +class Session: + def __init__(self, command): + self.next_id = 0 + self.proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) + + def rpc(self, method, params=None): + self.next_id += 1 + self.proc.stdin.write(json.dumps({"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params or {}}) + "\n") + self.proc.stdin.flush() + while True: + box = [] + reader = threading.Thread(target=lambda: box.append(self.proc.stdout.readline()), daemon=True) + reader.start() + reader.join(REPLY_TIMEOUT) + if not box or not box[0]: + raise Failed("no reply to %s within %.0f s" % (method, REPLY_TIMEOUT)) + reply = json.loads(box[0]) + if reply.get("id") == self.next_id: + if "error" in reply: + raise Failed("%s: %s" % (method, reply["error"].get("message"))) + return reply["result"] + + def notify(self, method): + self.proc.stdin.write(json.dumps({"jsonrpc": "2.0", "method": method}) + "\n") + self.proc.stdin.flush() + + def call(self, name, arguments=None): + result = self.rpc("tools/call", {"name": name, "arguments": arguments or {}}) + data = result.get("structuredContent") or {} + if result.get("isError"): + raise Failed("%s: %s" % (name, data.get("error") or result)) + return data + + def close(self): + try: + self.proc.stdin.close() + self.proc.wait(10) + except (OSError, subprocess.TimeoutExpired): + self.proc.kill() + + +def plan(): + for course in range(1, COURSES + 1): + shift = LENGTH // 2 if course % 2 == 0 else 0 + for i in range(BRICKS): + yield course, [LENGTH * i + shift, -HEIGHT * course, 0] + + +def build(session, colour, save): + session.rpc("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "build_wall", "version": "1"}}) + session.notify("notifications/initialized") + status = session.call("formblocks_status") + if status.get("engine") != "running": + raise Failed("FormBlocks is not running; start the app first") + print("FormBlocks %s, revision %s, outside agents: %s" % (status.get("version"), status.get("revision"), status.get("outside_agents"))) + library = session.call("cmd_library_status").get("result", {}) + if not library.get("found"): + raise Failed("no parts library is in use; only the person can find or fetch it") + print("Each change below waits until the person allows it in the FormBlocks window.") + session.call("cmd_model_new") + placed = [] + for course, position in plan(): + answer = session.call("cmd_part_place", {"part": PART, "colour": colour, "position": position, "step": course}) + result = answer.get("result", {}) + pid = result.get("placement", {}).get("id") + below = sorted({j.get("placement") or "ground" for j in result.get("joined", [])}) + print("course %d %s at %s seated %s on %s" % (course, pid, position, result.get("seated"), ", ".join(below) or "-")) + if not result.get("seated"): + raise Failed("%s did not seat; undo it and check the position" % pid) + placed.append(pid) + overlaps = session.call("cmd_overlap_check").get("result", {}) + print("overlap check: %s pairs over %s placements" % (overlaps.get("count"), overlaps.get("checked"))) + if overlaps.get("count"): + raise Failed("the overlap check found overlapping parts") + steps = session.call("cmd_step_list").get("result", {}).get("steps", []) + print("steps: %s" % ", ".join(str(len(s.get("placements", []))) for s in steps)) + if save: + written = session.call("cmd_model_save_as", {"path": save}).get("result", {}) + print("saved %s (%s bytes)" % (written.get("written"), written.get("bytes"))) + return placed + + +def main(): + parser = argparse.ArgumentParser(description="Build the wall of twenty bricks in a running FormBlocks.") + parser.add_argument("--root", default=os.getcwd(), help="the FormBlocks checkout") + parser.add_argument("--connect", default="auto", help="HOST:PORT of the running engine, or auto") + parser.add_argument("--colour", type=int, default=4, help="an LDraw colour code (4 is red)") + parser.add_argument("--save", default="", help="a full path ending in .fblk to save the wall to") + opts = parser.parse_args() + launcher = os.path.join(opts.root, "formblocks.bat" if os.name == "nt" else "formblocks") + if not os.path.isfile(launcher): + print("no formblocks launcher at %s; pass --root" % launcher) + return 2 + try: + session = Session([launcher, "mcp", "--connect", opts.connect]) + except OSError as err: + print("cannot start %s: %s" % (launcher, err)) + return 2 + try: + placed = build(session, opts.colour, opts.save) + except Failed as err: + text = str(err) + print("stopped: %s" % text) + return 2 if "not running" in text or "not accepting connections" in text else 1 + except (ValueError, OSError) as err: + print("the server answered badly: %s" % err) + return 1 + finally: + session.close() + print("built %d bricks" % len(placed)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.claude/skills/formblocks-driving/sub-skills/building-in-order/SUB-SKILL.md b/.claude/skills/formblocks-driving/sub-skills/building-in-order/SUB-SKILL.md new file mode 100644 index 0000000..c3c347f --- /dev/null +++ b/.claude/skills/formblocks-driving/sub-skills/building-in-order/SUB-SKILL.md @@ -0,0 +1,58 @@ +--- +name: building-in-order +description: Plans and builds brick structures in FormBlocks bottom up and strong, with walls in overlapping courses, interlocked corners, openings with a lintel, plates and tiles, and roofs of slopes. Use when asked to build a wall, a house, a tower, furniture or any structure of more than a few parts, or when a build comes out loose, floating or overlapping. +--- + +# Building in order + +A model is strong and placeable when every part seats on something already there. That gives the order: from the ground up, one course (one brick height) at a time, finishing each course before the next. Snapping only seats a part on parts that exist, so a brick placed before its support is placed loose. + +## Plan on the grid first + +1. Decide the footprint in studs: how many wide (X) and deep (Z). Put the front of the build towards -Z, which is the front view. +2. Write down which stud cells each part covers; cell centres are at (10 + 20i, 10 + 20k). +3. Work out each origin from its cells and its height (`references/coordinates-and-units.md`): bricks of course n stand at Y = -24n. +4. Search for each part number once (`sub-skills/finding-parts/SUB-SKILL.md`) and reuse it. +5. Put each course in its own step (`sub-skills/steps/SUB-SKILL.md`): `step: 1` for the first, then one past the last to start each new one. + +## Walls: overlap the courses + +A wall of bricks stacked straight up, joint above joint, is a set of separate columns. Shift every second course by half a brick so each brick bridges the joint below it and seats on two bricks: the running bond. + +- With 2 x 4 bricks (80 long), course 1 at X = 0, 80, 160, ...; course 2 at X = 40, 120, 200, ...; course 3 like course 1. +- Each brick of course 2 should answer `joined` pairs with two placements. One placement only means it sits over a joint, or over the end. +- The ends of a shifted course stick out half a brick. Leave them toothed, or fill the short gaps with half-length bricks (a 2 x 2 at the end of a 2 x 4 course, a 1 x 2 at the end of a 1 x 4 course). +- Thin walls (one stud thick) use 1 x N bricks; thick walls use 2 x N. + +## Corners: let the walls take turns + +Where two walls meet, let one wall run through the corner cell in one course and the other wall run through it in the next. The corner bricks then seat across both walls and tie them together. In a box of four walls: in odd courses the front and back walls run the full width and the side walls fit between them; in even courses the side walls run the full depth and the front and back fit between. + +## Openings: frame and span + +- Leave the cells of a door or window empty in the courses it passes through, keeping the bricks either side of it in running bond where the length allows. +- Close the top with one brick long enough to rest on both sides: a lintel. A 2 stud opening needs at least a 1 x 4 over it; it should answer `joined` pairs on both sides. +- Door and window frames from the library (`door frame`, `window 1 x 2 x 2`) are placed like bricks; read `part.connectors` for their footprint first. + +## Plates and tiles + +- A plate is a third of a brick high (8). Plates over a course tie bricks together across joints and make a floor or a ceiling. A plate on a course whose top is at Y = T goes at Y = T - 8. +- Long plates (2 x 6, 2 x 8) laid over the tops of walls hold the walls together better than another course of bricks. +- A tile is a plate with a smooth top and no studs. Nothing seats on a tile, so tiles go last, on top surfaces you want smooth (a table top, a floor, a path). +- Three plates are one brick high, so plates and bricks mix freely in a stack. + +## Roofs of slopes + +- A 45 degree slope brick 2 x 2 (`3039`) is a brick height high, with its two studs on its back row and its sloped face running down towards -Z. Unturned, it faces the front. +- A half turn about Y, `rotation` `[-1,0,0, 0,1,0, 0,0,-1]`, makes it face the back. +- Lay a flat layer of plates on the walls first, so every slope has studs under its whole footprint. +- A gable roof: a row of slopes facing front along the front edge and a row facing back along the back edge. Each further row steps in by one stud and up by one brick, standing on the studs of the row below and on filler bricks behind it. Close the ridge with plates or tiles over the last studs. +- The overlap check's box fills the space above a slope's face, so with the check on a part right over a sloped face can be refused although it would fit. Keep parts clear of sloped faces, or tell the person why the check refuses. + +## After each course + +- Every part in it answered `seated: true`. +- `overlap.check` answers `count: 0` (it is cheap; run it per course on a large build). +- `step.list` shows the course in its own step. + +The worked examples carry all of this out: `examples/wall.md`, `examples/house.md`, `examples/table.md`. diff --git a/.claude/skills/formblocks-driving/sub-skills/building-models/SUB-SKILL.md b/.claude/skills/formblocks-driving/sub-skills/building-models/SUB-SKILL.md deleted file mode 100644 index fbab7ae..0000000 --- a/.claude/skills/formblocks-driving/sub-skills/building-models/SUB-SKILL.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -name: building-models -description: Builds and changes models in a running FormBlocks through MCP - finding parts and colours, placing and seating parts with snapping, checking overlaps, moving, turning, recolouring, steps, submodels, saving and exporting, undo and redo. Use for parts.search, part.place, part.fit, overlap.check, model.save_as and any other catalogue command. ---- - -# Building models - -Start with `formblocks_status` and `cmd_model_tree` (`sub-skills/connect-and-status/SUB-SKILL.md`), so you know the revision, the submodel being edited and the placement ids before you change anything. - -## Units and axes - -Positions are LDraw units (LDU) on the LDraw axes: X and Z across, Y up and down with -Y up. One stud is 20 LDU, a brick 24 LDU high, a plate 8. A part's position is its origin; for an ordinary brick or plate the origin is the centre of its top face, so a brick standing on the ground has Y = -24 and a plate Y = -8. Rotations are the nine numbers of an LDraw matrix, row by row; leave `rotation` out for none. A quarter turn about Y is `[0,0,1, 0,1,0, -1,0,0]`. - -## Finding parts and colours - -| Command | Tool | Use | -| --- | --- | --- | -| `parts.search` | `cmd_parts_search` | `text` such as `brick 2 x 4`; the best hit is first. `limit` 20 unless given. | -| `parts.show` | `cmd_parts_show` | One part's description, category, author and licence; a moved number names its new one. | -| `colours.list` | `cmd_colours_list` | The library's colours; `text` such as `dark blue`, or a `group`. 4 is red, 1 blue, 15 white, 0 black. | -| `library.status` | `cmd_library_status` | Whether a parts library is in use. With none, nothing can be placed: tell the person; only they can fetch it, in the window. | - -## Placing - -- `part.place {part, colour, position}`: with snapping on (the person's setting, or `snap` for this call) the part seats on free studs within reach of `position`, the ground's stud lattice included, or moves to the grid step; with snapping off it goes exactly to `position`. The answer has the new `placement` (its `id`), `seated` and the `joined` connector pairs. -- `part.place {part, colour, on: "p12"}` seats the part on placement `p12`'s free studs, nearest its middle first, with no coordinates: the simplest way to stack. -- `part.fit` takes the same `part`, `rotation`, `position` or `on` and answers where the part would go and what it would join, changing nothing. Use it before a place you are unsure of. -- With the overlap check on, a place that would overlap another part is refused with the part named; nothing changes. -- A part the library does not have is refused. Search first, place the number the search gives. - -## Checking - -- `overlap.check` lists every pair of overlapping placements with its depth in LDU; give `ids` to check only those. It works whatever the switch says. Parts seated on each other never count. -- `part.connectors {part}` shows a part's studs and anti-studs as FormBlocks derives them. - -## Changing what is there - -`part.move` (by `delta`, exact), `part.set_transform`, `part.rotate` (quarter turns), `part.recolour`, `part.duplicate`, `part.delete`, `part.hide`, `part.show`: each takes `ids`, or acts on the selection when `ids` is left out. `select.*` commands change only the selection. Steps: `step.break_after`, `step.move_parts`, `step.rename`, `step.goto`, `step.list`. Submodels: `submodel.create` packs placements, `submodel.dissolve` unpacks one use, `submodel.enter` and `submodel.leave` choose where new parts go. - -## Files - -`model.save_as {path}` with a full path: `.fblk` saves the project, `.ldr` or `.mpd` exports LDraw for any other LDraw program. `model.open {path}` opens one; `model.new` starts over. Both refuse while there are unsaved changes unless `discard` is true: ask the person before you discard anything. Saving and opening ask the person in the window first, like any change. - -## Undo and redo - -- Every change command is one undo step with a label (`Place 3001.dat`, `Move 3 parts`); view commands and file commands are not. -- `formblocks_undo` takes back the newest steps (`steps`, default 1); `formblocks_redo` puts them back. The history is the person's too: undo only what you made, by count. - -## Recipes - -- A wall of bricks: `parts.search` for `brick 2 x 4` (3001), `part.place` the first at `[0, -24, 0]`, then each next at `[80 * i, -24, 0]`; the next course `on` a brick below, or at `Y = -48` offset by 40 for a running bond. Finish with `overlap.check`: `count` 0. -- Save: `model.save_as` with a `.fblk` path, then with an `.ldr` path for an LDraw copy. diff --git a/.claude/skills/formblocks-driving/sub-skills/changing-parts/SUB-SKILL.md b/.claude/skills/formblocks-driving/sub-skills/changing-parts/SUB-SKILL.md new file mode 100644 index 0000000..a8dc969 --- /dev/null +++ b/.claude/skills/formblocks-driving/sub-skills/changing-parts/SUB-SKILL.md @@ -0,0 +1,44 @@ +--- +name: changing-parts +description: Changes parts already placed in a FormBlocks model by moving by an offset, setting an exact position or rotation, turning by quarter turns, duplicating, recolouring, hiding, showing and deleting, each as one undo step. Use when asked to move, shift, turn, rotate, copy, repeat, recolour, hide, show or remove placements, or to undo such a change. +--- + +# Changing parts + +Every command here is a `change` command: one undo step however many parts it touches, labelled for the person's Edit menu (`Move 3 parts`, `Rotate 1 part about Y`), and it waits for the person's approval when sent from outside the window. + +## Name the parts + +Each command takes `ids`, a list of placement ids such as `["p3", "p4"]`. Left out, it acts on the selection; a selection you did not set yourself may be the person's, so pass `ids`. Read ids from the answer that made the part, or from `model.tree`. An id stays the same while the model is open, through undo and redo, until the part is deleted. + +## The commands + +| Command | Parameters | What it does | +| --- | --- | --- | +| `part.move` | `ids`, `delta` | Moves by an exact offset in LDU, `[dx, dy, dz]`. No snapping: the parts go exactly where sent. Up is a negative `dy`. | +| `part.set_transform` | `id`, `position`, `rotation` | Puts one placement at an exact position, an exact rotation, or both. | +| `part.rotate` | `ids`, `axis`, `quarter_turns`, `about` | Turns by quarter turns about `x`, `y` or `z`, right-handed about the positive axis; negative turns go the other way. It turns about `about` when given, otherwise about the centre of the placements' origins, and works out the new positions and matrices. | +| `part.duplicate` | `ids`, `delta` | Copies the placements with their colours and relative places, offset by `delta`. The copies go into the step shown and become the selection; the answer lists their new ids. | +| `part.recolour` | `ids`, `colour` | Gives a colour code. Parts already in it are left as they are. | +| `part.delete` | `ids` | Removes placements. Deleting the last use of a submodel keeps the submodel itself. | +| `part.hide` | `ids` | Hides placements: they stay in the model, the parts list and the overlap check, but are not drawn and offer no studs. | +| `part.hide_others` | `ids` | Hides every placement of the submodel being edited except these. | +| `part.show` | `ids` | Shows them again; with no `ids`, shows every hidden placement in the model. | + +## Moving keeps nothing seated by itself + +`part.move` and `part.set_transform` ignore studs. To keep a moved part seated, move it by whole studs across (multiples of 20) and whole plates up or down (multiples of 8), and check with `overlap.check` afterwards. To move a part onto another part's studs, it is often simpler to delete it and `part.place` it again with `on` or a position, and read `seated` in the answer. + +## Turning in place + +- A quarter turn about Y of one 2 x 4 brick about its own origin turns it crosswise on the same spot; it may then overlap its neighbours. +- To turn a whole group as one, give all their ids: they turn about the centre of their origins and keep their places relative to one another. +- To turn about a stud, give `about` as that stud's position. + +## Repeating a row + +`part.duplicate` with a `delta` is the quickest way to repeat: duplicate one brick with `delta` `[80, 0, 0]`, then duplicate the new one, and so on. A course of five bricks becomes one brick and four duplicates. Duplicates do not snap, so pick a delta on the grid. + +## Undo + +`formblocks_undo` (or `./formblocks cli undo`) takes back the newest change, `steps` for more; `formblocks_redo` puts it back. The history is shared with the person: undo counts every change, theirs too, so undo only right after your own change, and read `labels` in the answer to see what was taken back. Parts made by an undone change lose their ids until it is redone. diff --git a/.claude/skills/formblocks-driving/sub-skills/checking-a-model/SUB-SKILL.md b/.claude/skills/formblocks-driving/sub-skills/checking-a-model/SUB-SKILL.md new file mode 100644 index 0000000..1a0edf8 --- /dev/null +++ b/.claude/skills/formblocks-driving/sub-skills/checking-a-model/SUB-SKILL.md @@ -0,0 +1,57 @@ +--- +name: checking-a-model +description: Checks a FormBlocks model after building or changing it (the overlap check, seated answers, the model tree, step and submodel lists, the open report) and counts its parts. Use before telling the person a build is done, when asked whether parts overlap or float, for a parts count or parts list, or to confirm what a model holds after opening it. +--- + +# Checking a model + +Never report a build as done from memory of the commands you sent. Read the model back and check it. + +## The overlap check + +`overlap.check` (`cmd_overlap_check`) lists every pair of placements whose bodies overlap, with the depth of the overlap in LDU. Give `ids` to check only those placements against the rest; leave it out for the whole model. It works whatever the person's overlap switch says. + +```json +{"checked": 28, "overlaps": [], "count": 0} +{"checked": 5, "overlaps": [{"submodel": "untitled.ldr", "a": "p1", "b": "p5", "depth": 23.0}], "count": 1} +``` + +- `count` 0 is the goal. +- Parts seated on each other never count, and parts that only touch face to face never count. +- The check is coarse: each part is stood in for by a box round its body, without its studs, shrunk by half an LDU. The empty space over a slope's face, inside an arch or under an overhang counts as solid, so a part tucked there is reported although it fits. Say so to the person rather than moving a part that is right. +- A depth near a whole brick (24) or plate (8) usually means a part was placed on top of another at the same height: undo it or move it. + +## Seated, or floating + +The overlap check does not find a part floating in the air. That is what `seated` in each `part.place` answer is for: keep a note of any placement that answered `seated: false` and fix or explain each one. To recheck a part later, `part.fit` with its part, rotation and position answers whether that spot seats. + +## Reading the model back + +| Read | Answers | +| --- | --- | +| `model.tree` | One submodel's steps and placements, each with id, part, colour, position, rotation, step and hidden mark, and every submodel with its uses. Pass `submodel` to read one other than the one being edited. | +| `step.list` | The steps of a submodel and their placement ids, and the step shown. | +| `submodel.list` | Every submodel with its step count, placement count and uses; unused ones are marked. | +| `formblocks_get_doc` | Everything at once, with the revision. Large on a big model. | +| `formblocks_status` | The placement count of the whole model, `dirty`, the file and the revision. | +| `model.report` | After opening a file: the lines that could not be read, and the encoding. | + +Check the counts against the plan: the number of placements, the number in each step, the parts in each colour. + +## Counting parts today + +Until the parts list commands arrive (below), count from `model.tree`: group its placements by `part` and `colour`. A use of a submodel is one placement there; count the submodel's own placements once per use to get what the build needs. + +## Looking at the result + +The person sees every change in the window as it lands. Ask them to look when a shape matters (a roof line, a face), and describe what you built in words: footprint in studs, height in bricks, colours, steps. + +## Arriving in 0.3.0 + +These commands are being added to the catalogue in 0.3.0. Check `formblocks_list_commands` before using them: until the catalogue lists them, they do not exist. The parts list commands take the ids `spec/SPEC.md` reserved for them: + +- `parts.list` (read): the parts a model needs, one row per part and colour with description, colour name and count, a submodel's parts counted once per use, parts missing from the library first. `scope` is `model`, `submodel` or `step` (up to the step shown); `group` sorts by `part` or `colour`. +- `parts.list_save` (file): the same rows written to a full path ending in `.csv`, `.tsv` or `.txt`. Like any file command from outside it waits for the person, and a path outside the model's folder asks every time. +- `part.place_at_ray` (change): places a part where a ray meets the model or the ground, as the window's pointer drops it. Its `origin`, `direction` and `rotation` are in the window's scene axes, +Y up, not the LDraw axes every other command uses; prefer `part.place` with a position or `on`. + +Read each one's parameters from the catalogue when it appears; do not guess them from these lines. diff --git a/.claude/skills/formblocks-driving/sub-skills/colours/SUB-SKILL.md b/.claude/skills/formblocks-driving/sub-skills/colours/SUB-SKILL.md new file mode 100644 index 0000000..56146a4 --- /dev/null +++ b/.claude/skills/formblocks-driving/sub-skills/colours/SUB-SKILL.md @@ -0,0 +1,57 @@ +--- +name: colours +description: Chooses and changes colours in FormBlocks by LDraw colour code, from the library's own colour table. Use when the person names a colour, when placing or recolouring parts, when a colour code is refused, or when deciding what colour 16 does inside a submodel. +--- + +# Colours + +FormBlocks offers exactly the colours of the library's colour definitions file and adds none of its own. Every command takes a colour as its LDraw code, a whole number: `colour: 4` is red. Names are for finding a code, not for passing to a command. + +## Finding a code + +`colours.list` (`cmd_colours_list`, or `./formblocks cli colours WORDS`): + +| Parameter | Use | +| --- | --- | +| `text` | Name words in any order: `dark blue`, `bluish grey`, `trans clear`. | +| `group` | One finish: `solid`, `transparent`, `chrome`, `pearl`, `metallic`, `rubber` or `material`. | +| `hue` | One hue family, written as the answer writes it: `reds`, `oranges`, `yellows`, `greens`, `blues`, `purples`, `pinks`, `browns`, `greys`. | + +Each answer row has `code`, `label` (the name with spaces), `value` (the hex colour), `edge`, `alpha` (below 255 for transparent colours), `group` and `hue`. Pick by `label`, pass the `code`. + +Codes that come up most, checked against the library's table: + +| Code | Name | Code | Name | +| --- | --- | --- | --- | +| 0 | Black | 19 | Tan | +| 1 | Blue | 25 | Orange | +| 2 | Green | 28 | Dark Tan | +| 4 | Red | 70 | Reddish Brown | +| 14 | Yellow | 71 | Light Bluish Grey | +| 15 | White | 72 | Dark Bluish Grey | +| 320 | Dark Red | 47 | Trans Clear | + +Read the table again when in doubt; a library update can add colours, and the person's library may be a different update from the one these were read from. + +## The two special codes + +- 16 is "the colour of whatever uses it". A part inside a submodel drawn in 16 takes the colour of each use of that submodel. Do not give 16 to a part of the main model: it has nothing to inherit from. +- 24 is the edge colour of the part's own colour. It is never offered as a swatch and has no use for a placement. + +## Colouring parts + +- `part.place` takes `colour` and it is required: the part is placed in it. +- `part.recolour` with `ids` and `colour` recolours placements as one undo step. Parts already in that colour are left alone; if every part already has it, nothing changes. +- Recolouring a use of a submodel in colour 16 passes the new colour to the parts inside that are in 16; parts with their own colour keep it. +- `select.by_colour` selects every visible placement in a colour, then `part.recolour` without `ids` acts on that selection. + +## Choosing colours for a build + +- One colour per role reads well: walls in one colour, roof in another, plates and trims in a grey. +- Transparent colours (`group` `transparent`) suit windows and lights; chrome, pearl and metallic suit trims. +- Ask the person when they name a colour that matches several codes (there are many greys and blues). Show the labels, not just the codes. + +## Edge cases + +- A model opened from a file may use a code the library does not define. It keeps that number and saves it unchanged; it is drawn in a neutral grey. +- A negative code is refused ("colour must be a colour code from 0"). diff --git a/.claude/skills/formblocks-driving/sub-skills/connect-and-status/SUB-SKILL.md b/.claude/skills/formblocks-driving/sub-skills/connect-and-status/SUB-SKILL.md index 1b85788..9a6e2dd 100644 --- a/.claude/skills/formblocks-driving/sub-skills/connect-and-status/SUB-SKILL.md +++ b/.claude/skills/formblocks-driving/sub-skills/connect-and-status/SUB-SKILL.md @@ -7,7 +7,7 @@ description: Connects an agent program to FormBlocks's MCP server, makes the fir ## Registering the server -The server is the launcher's `mcp` command: `/formblocks mcp` on stdio (`formblocks.bat mcp` on Windows). The checkout already carries the registration for agent programs started inside it: `.mcp.json`, `.codex/config.toml` and `.cursor/mcp.json` name the server `formblocks`. To register it for an agent program everywhere, the person runs `./formblocks agents install` (with `--dry-run` first to see what would change); it writes the same entry into each program's own settings. +The server is the launcher's `mcp` command: `[checkout]/formblocks mcp` on stdio, where `[checkout]` is the folder FormBlocks was cloned or installed into (`formblocks.bat mcp` on Windows). The checkout already carries the registration for agent programs started inside it: `.mcp.json`, `.codex/config.toml` and `.cursor/mcp.json` name the server `formblocks`. To register it for an agent program everywhere, the person runs `./formblocks agents install` (with `--dry-run` first to see what would change); it writes the same entry into each program's own settings. `./formblocks mcp` is a bridge to the running engine when one answers on this computer, so the window shows every change; when none answers it works alone on the same data folder (headless). `--connect HOST:PORT` (or `auto`) insists on a running engine and never falls back; `--headless` never looks for one; `--settings-dir ''` gives a throwaway data folder for a trial. A program started from a tab of the window's agent dock is already connected over HTTP; see `sub-skills/agent-dock/SUB-SKILL.md`. @@ -20,16 +20,7 @@ The server is the launcher's `mcp` command: `/formblocks mcp` on stdio ## When a change waits -Reading and view commands never wait. A change or file command (and undo and redo) from an outside agent is gated by the person: - -| `outside_agents` | `engine` | What happens to a change | -| --- | --- | --- | -| `ask` | `running` | The window asks the person; the call waits up to two minutes for the answer. | -| `allowed`, or this program allowed before | either | It runs at once. | -| `blocked` | either | Refused: nothing was changed. | -| `ask` | `headless` | Refused: the app is not open, so nobody can allow it. Ask the person to start FormBlocks, then try again. | - -A refusal says which of these it was. When the person declines, do not send the same change again another way; say what you wanted to do and let them choose. +Reading and view commands never wait. A change or file command (and undo and redo) from an outside agent waits for the person in the window, or is refused when nobody can be asked. `sub-skills/working-with-the-person/SUB-SKILL.md` says when the window asks, what each answer does, and what to do after a decline. ## Results and errors diff --git a/.claude/skills/formblocks-driving/sub-skills/files/SUB-SKILL.md b/.claude/skills/formblocks-driving/sub-skills/files/SUB-SKILL.md new file mode 100644 index 0000000..f5f2488 --- /dev/null +++ b/.claude/skills/formblocks-driving/sub-skills/files/SUB-SKILL.md @@ -0,0 +1,53 @@ +--- +name: files +description: Opens, starts, saves and exports FormBlocks models, and says what .fblk, .ldr, .mpd and .dat files each keep. Use when asked to save, save as, export to LDraw, open or import a model file, start a new model, insert one model into another, or when a save or open is refused or asks the person. +--- + +# Files + +## The kinds of file + +| File | What it is | What it keeps | +| --- | --- | --- | +| `.fblk` | FormBlocks' project file. | The whole model as an LDraw multi-part document (every submodel, placement, colour, position, rotation, step and step name) plus FormBlocks' own state in `0 !FORMBLOCKS` lines: the step shown, hidden parts, open tree rows, snap and grid, current colour, camera and the library update. Renamed to `.mpd` it opens in any LDraw program that reads multi-part files. | +| `.ldr` | An LDraw model. | Parts, colours, positions, rotations, steps and step names. No hidden marks, no view state. It may hold submodels too. | +| `.mpd` | An LDraw multi-part document. | The same as `.ldr`, with each submodel in its own `0 FILE` block; the usual name for a model with submodels. | +| `.dat` | An LDraw part file from the library. | Opened, it becomes a new model holding one placement of that part. Never written. | + +A saved file holds references to parts (`3001.dat`), never a part's own lines. Files are written UTF-8 with CR LF line ends, and a save writes a new file beside the old one before putting it in place, so a failed save never leaves half a file. + +## The commands + +| Command | Kind | Parameters | What it does | +| --- | --- | --- | --- | +| `model.new` | file | `discard` | Starts a new model named Untitled with one empty step and a new history. | +| `model.open` | file | `path`, `discard` | Opens a `.fblk`, `.ldr`, `.mpd` or `.dat` file. | +| `model.save` | file | none | Saves to the `.fblk` the model came from. A model never saved, or opened from an LDraw file, has none: use `model.save_as`. | +| `model.save_as` | file | `path` | `.fblk` saves the project and makes it the model's file; `.ldr` or `.mpd` exports LDraw and leaves the model's file as it was. Any other ending is refused. | +| `model.insert` | change | `path`, `position`, `submodel` | Brings another `.ldr`, `.mpd` or `.fblk` in as new submodels and places one use of its main model (at `position`, or the origin). | +| `model.recent` | read | none | The last ten files opened or saved, newest first, each with whether it still exists. | +| `model.report` | read | none | What opening reported: lines that could not be read, with their numbers, and the text encoding. | + +## Paths + +- Through MCP, give a full path. Ask the person where they want the file when they have not said. +- On the command line a relative `path` is read from the folder the command was run in. +- A `.fblk` and an LDraw copy are separate writes: `model.save_as` with `/home/me/models/house.fblk`, then with `/home/me/models/house.ldr`. + +## Unsaved changes + +`model.new` and `model.open` refuse while the open model has unsaved changes ("discard: the open model has unsaved changes"). `formblocks_status` answers `dirty`. Ask the person: save first with `model.save` or `model.save_as`, or pass `discard: true` only once they have said to drop the changes. Never discard to get past the refusal on your own. + +## The person's approval + +File commands sent from outside the window wait for the person, like changes (`sub-skills/working-with-the-person/SUB-SKILL.md`). `model.save_as` to a path outside the folder of the model's own file asks every time, even when the person has allowed your program always; a model with no file yet has no folder, so its first `model.save_as` always asks. Say where you are about to write before you send it. + +## Opening files from elsewhere + +- An `.ldr` or `.mpd` from another LDraw program opens with every part reference, submodel and step. Lines FormBlocks does not use (comments, unknown commands) are kept in place and written back. +- `model.open` answers `issueCount` and the first issues; `model.report` lists them all. A file that is not UTF-8 is read as code page 1252. +- A part the library does not have is kept, drawn as a warning box and saved unchanged. + +## After saving + +Read the answer: `written` (the path), `writtenKind`, `bytes`, and `dirty` false after a `.fblk` save. Exporting `.ldr` or `.mpd` does not clear `dirty`, because the project itself was not saved. diff --git a/.claude/skills/formblocks-driving/sub-skills/finding-parts/SUB-SKILL.md b/.claude/skills/formblocks-driving/sub-skills/finding-parts/SUB-SKILL.md new file mode 100644 index 0000000..01af586 --- /dev/null +++ b/.claude/skills/formblocks-driving/sub-skills/finding-parts/SUB-SKILL.md @@ -0,0 +1,57 @@ +--- +name: finding-parts +description: Finds the right LDraw part in FormBlocks before placing it, with search words, categories, part numbers, moved parts and the other brick systems to avoid. Use when looking up a brick, plate, tile or slope by size or name, when a part number is refused, or when a search answers the wrong scale. +--- + +# Finding parts + +Every part is a file of the LDraw parts library on the person's computer, named by its number: `3001.dat` is the 2 x 4 brick. The model refers to the number only and never holds the part's shape. A part is placed by the number a search answers, never by a number remembered from elsewhere, because a library update can move or rename a part. + +## What a part number is + +- The file name without `.dat`: `3001`, `3023b`, `3068b`. Commands take either form, `3001` or `3001.dat`. +- Letters after the digits are part of the number. `3068b` (tile 2 x 2 with groove) and `3068` are different files; a letter often marks a later mould of the same shape. +- Some numbers carry a pattern suffix (`3001p01` and the like): a printed version of the plain part. Printed parts are left out of a search unless `printed` is true. +- A number with no file in the library is refused by `part.place` ("is not in the LDraw parts library in use"). + +## Searching + +`parts.search` (`cmd_parts_search`, or `./formblocks cli parts search WORDS --lines`): + +| Parameter | Use | +| --- | --- | +| `text` | Words of the description, a part number, keywords or a category. Word order does not matter; `2x4`, `2 x 4` and `2 by 4` are the same. | +| `category` | Limit to one category, such as `Brick`, `Plate`, `Tile`, `Slope`. | +| `printed` | `true` to include printed and stickered parts. | +| `limit`, `offset` | Paging: `limit` from 1 to 500 (20 when left out). | +| `list` | `favourites`, `recent` or `hidden`: the person's own lists in the parts palette. | + +Ranking: an exact part number first, then numbers that start with the text, then parts whose description holds every word, then parts that match only by keyword or category; shorter descriptions first within a rank. So `brick 2 x 4` answers `3001` first and `plate 2 x 4` answers `3020` first. + +Good search words name the shape and the size: `brick 1 x 2`, `plate 2 x 6`, `slope 45 2 x 2`, `slope 45 2 x 1`, `door frame`, `window 1 x 2 x 2`. Read the descriptions of the first hits rather than taking the first blindly: shorter descriptions rank first, so `tile 2 x 2` answers `Tile 2 x 2 Corner` before the plain tile, which `tile 2 x 2 with groove` finds (`3068b`). When nothing fits, use fewer words, or the library's own word for the shape: a roof is built from `slope` parts, and `roof` answers other things. + +`parts.show` (`cmd_parts_show`) answers one part's description, category, keywords, author, licence and library update. + +## Moved parts + +A part the library has renumbered is kept as a stub whose description starts with `~Moved to`. Search answers it with `moved_to` and the new part's description, and `parts.show` answers `follows`: + +``` +./formblocks cli run parts.search text=3023 limit=2 +-> 3023 "~Moved to 3023b" moved_to 3023b (Plate 1 x 2) +-> 3023b "Plate 1 x 2" +``` + +Place the number the move points to (`3023b`). A model that already names the old number keeps it and still draws and seats through the move. + +## Other systems and scales + +The library also holds parts of other brick systems at other scales, and a search for `brick 2 x 4` lists some of them among its first hits. Their descriptions start with a system word such as `Duplo`, `Quatro`, `Modulex`, `Primo` or `Scala`. Their studs do not mate with ordinary studs, so they never seat on ordinary bricks. Skip them unless the person asked for that system. + +## Before placing an unfamiliar part + +Run `part.connectors` with the number. It answers the studs and anti-studs FormBlocks finds, the body box, the footprint (`x0`, `x1`, `z0`, `z1`) and the bottom plane, in the part's own axes. That tells you where the origin is and how far the part reaches, which `references/coordinates-and-units.md` turns into a position. A part with no connectors at all (a sticker, a minifigure piece) never seats; it can only be put at an exact position. + +## No library + +`parts.search` and `part.place` both fail when no library is in use. Read `library.status` and follow `sub-skills/parts-library/SUB-SKILL.md`: the fetch is the person's to start, never yours. diff --git a/.claude/skills/formblocks-driving/sub-skills/parts-library/SUB-SKILL.md b/.claude/skills/formblocks-driving/sub-skills/parts-library/SUB-SKILL.md new file mode 100644 index 0000000..bfb1c8e --- /dev/null +++ b/.claude/skills/formblocks-driving/sub-skills/parts-library/SUB-SKILL.md @@ -0,0 +1,43 @@ +--- +name: parts-library +description: Reads whether FormBlocks has an LDraw parts library in use, and what to do when it has none. Use when a placement or search answers that no library is installed, when asked about the library's update, folder or licence, or when someone asks the agent to download or fetch the library, which only the person can consent to. +--- + +# The parts library + +FormBlocks draws and seats parts from the LDraw parts library, a set of files on the person's computer that FormBlocks never ships. Without it nothing can be searched or placed. The library is the work of its many authors, under CC BY 2.0 and CC BY 4.0; every part file names its own author and licence. + +## Reading the status + +`library.status` (`cmd_library_status`, or `./formblocks cli library status`) only reads. It answers: + +| Field | Meaning | +| --- | --- | +| `found` | Whether a library is in use. | +| `folder`, `source` | Where it is, and how it was found (the person's setting, the fetched copy, or the `FORMBLOCKS_LDRAW_DIR` environment variable). | +| `update` | The library release, such as `2026-10`. | +| `index_ready`, `indexing`, `parts` | Whether the search index is built and how many parts it lists. Search waits for the index. | +| `fetch` | A fetch in progress, if any, with its stage and progress. | +| `card` | The address, licence, consent sentence and attribution the window's library card shows. | + +Reading never fetches and never touches the network. + +## The fetch is the person's to give + +The library comes from one address, `https://library.ldraw.org/library/updates/complete.zip`, and only after the person consents: on the library card in the window, or by typing `./formblocks cli library fetch --i-consent "ADDRESS LICENCE"` themselves. The consent is theirs because the download is theirs: it uses their network and disk, and they accept the licence. + +- No MCP tool starts a fetch, and the engine refuses a fetch an agent asks for. +- Never run `library fetch` yourself, even from a shell where you could, and never type the consent words for the person. Do not look for another way to download the library. +- When there is no library: say so in one sentence, name the two ways the person can give it (the library card in the window, or the command above, run by them), and stop building until `library.status` answers `found: true`. + +## A library the person already has + +If the person says they have the library unpacked already, it is a folder holding `parts`, `p` and `LDConfig.ldr`. The person can point FormBlocks at it on the library card ("Find a folder") or with `./formblocks cli library use FOLDER`; FormBlocks reads it in place and never writes into it. Suggest this; let the person do it, or run it only when they have asked you to and named the folder. + +## Updates + +`./formblocks cli library check-update` asks the library's server whether a newer archive is offered; it is a network call, so it is the person's to run too. Saved models keep part references, so a newer library opens them unchanged; parts the library has reshaped are drawn in their new shape. + +## The attribution + +When you tell the person about the library or credit it in something you write, use the `card.attribution` sentence `library.status` answers, word for word. diff --git a/.claude/skills/formblocks-driving/sub-skills/placing-and-snapping/SUB-SKILL.md b/.claude/skills/formblocks-driving/sub-skills/placing-and-snapping/SUB-SKILL.md new file mode 100644 index 0000000..2aacd2c --- /dev/null +++ b/.claude/skills/formblocks-driving/sub-skills/placing-and-snapping/SUB-SKILL.md @@ -0,0 +1,84 @@ +--- +name: placing-and-snapping +description: Places parts in FormBlocks and seats them stud to anti-stud, on another part or on the ground, with part.place, part.fit and the on parameter. Use when putting a brick down, stacking one part on another, working out a position, reading seated and joined in an answer, or when a placement is refused or lands somewhere unexpected. +--- + +# Placing and snapping + +Read `references/coordinates-and-units.md` first if positions in LDU with -Y up are new to you. + +## Studs and anti-studs + +- A stud is the round knob on top of a part, 4 LDU high, on a 20 LDU grid. +- An anti-stud is a place on a part's underside that takes one stud: the gaps between the walls and tubes of a brick, or the inside of a tube. +- A part is seated when its anti-studs sit on another part's studs (or its studs in another part's anti-studs). Seating is how real bricks hold together, so a model built of seated parts is one that could be built. +- FormBlocks finds these connectors from each part's own geometry; `part.connectors` lists them for any part. Only ordinary studs and anti-studs exist in this version: pins, axles, clips and hinges do not seat. + +## The ground + +The ground is the plane Y = 0 and acts as an endless plate: it offers a stud at every point (10 + 20i, 0, 10 + 20k). A part with anti-studs underneath, set down on the ground with snapping on, seats on that lattice, so parts placed side by side line up stud for stud. + +## Three ways to say where + +| How | Call | When | +| --- | --- | --- | +| A position | `part.place {part, colour, position}` | You know the place: walls, rows, anything planned on the stud grid. | +| On a placement | `part.place {part, colour, on: "p12"}` | Stack on one part without working out numbers; it takes the free studs nearest that part's middle first. | +| A trial | `part.fit` with the same `part`, `rotation`, and `position` or `on` | See where it would go and what it would join, changing nothing. | + +`part.place` also takes `rotation` (the nine numbers; none when left out), `step` (the step to put it in; one past the last starts a new step), `submodel` (where it goes; the one being edited when left out) and `snap` (for this call only). + +## What snapping does with a position + +With snapping on (the person's setting, on at the first start; `snap: true` forces it for one call): + +1. FormBlocks looks for free studs and anti-studs of other parts, and of the ground, within 15 LDU of where your part's connectors would be. +2. Among the possible seats it takes the one that joins the most connector pairs, then the one nearest your position, then a fixed order, so the same call always gives the same seat. +3. A seat that would leave a stud standing under a wall of your part (half a stud off the grid, say) is refused, as real bricks would not go there. +4. With no seat in reach, the part goes to the nearest grid step instead (20 LDU across and 8 up at the Stud step, the first setting) and is not seated. + +With snapping off (`snap: false`), the part goes exactly to the position, seated or not. + +Snapping never turns a part. To seat crosswise, give the turned `rotation`. + +## Reading the answer + +The result of a `part.place`, trimmed: + +```json +{"placement": {"id": "p3", "part": "3001.dat", "colour": 4, "position": [40.0, -48.0, 0.0], "step": 1}, + "seated": true, + "joined": [{"held": 0, "placement": "p1", "connector": 13}, {"held": 2, "placement": "p2", "connector": 11}], + "marks": [[10.0, -24.0, -10.0], [50.0, -24.0, -10.0]]} +``` + +- `placement.id` is the id to use from now on. Keep it. +- `placement.position` is where it really went, which may differ from what you sent. +- `seated` true means it joined at least one pair. `joined` lists the pairs: which of your part's connectors (`held`) met which placement's connector, or a `ground` lattice point. +- A brick bridging two bricks below shows pairs with both, which is what you want in a wall. + +Check `seated` on every place. `seated: false` with the overlap check off means the part may be floating or inside another part: undo it (`formblocks_undo`) and fix the position, unless a loose part is what you meant. + +## When a placement is refused + +| Refusal | Cause | +| --- | --- | +| "is not in the LDraw parts library in use" | Wrong number. Search first (`sub-skills/finding-parts/SUB-SKILL.md`). | +| "give a position, a placement to seat on (on), or a pointer ray" | Neither `position` nor `on` was given. | +| "would overlap ... with the overlap check on" | The person turned the overlap check on and the place is taken. | +| "has no free connector that ... can seat on" | Every stud of the `on` target is taken. | +| "is hidden, and hidden parts offer no connectors" | Show the target first, or give a position. | +| "must stay within 1000000 LDU of the origin" | A sign or unit slip. | + +The full list is `references/error-codes.md`. + +## The overlap check + +The overlap check is the person's switch, off at the first start. With it on, `part.place` refuses a place where the part's body box would overlap another part's; with it off, parts may share space without a word. Either way `overlap.check` reports overlaps on demand (`sub-skills/checking-a-model/SUB-SKILL.md`). The switch, like snapping and the grid step, is the person's setting: ask before you change it, and prefer `overlap.check` after placing, which changes nothing. + +## Habits that save undo steps + +- Plan positions on the stud grid before placing: odd-length parts centre on 10 plus a multiple of 20, even-length parts on a multiple of 20. +- Try a doubtful place with `part.fit` first. +- Place lower parts before upper ones: a part seats only on what is already there. +- Use `on` for quick stacking, a position for anything that must line up. diff --git a/.claude/skills/formblocks-driving/sub-skills/selection/SUB-SKILL.md b/.claude/skills/formblocks-driving/sub-skills/selection/SUB-SKILL.md new file mode 100644 index 0000000..cbc7aa2 --- /dev/null +++ b/.claude/skills/formblocks-driving/sub-skills/selection/SUB-SKILL.md @@ -0,0 +1,38 @@ +--- +name: selection +description: Reads and sets the selection in a FormBlocks model, the set of placements the window highlights and that commands act on when no ids are given. Use when asked to select parts by id, colour or part number, to select all or invert, to show the person which parts you mean, or when a command answers that nothing is selected. +--- + +# Selection + +The selection is a list of placement ids in the submodel being edited. The window outlines it, the details panel describes it, and every `part.*` command that takes `ids` acts on it when `ids` is left out. + +Selection commands are `view` commands: they change what is shown, never the model, so they are not undo steps and never wait for the person's approval. + +## The commands + +| Command | Parameters | What it does | +| --- | --- | --- | +| `select.get` | none | Reads the selection: ids, count, how many colours, and the centre of their origins. | +| `select.set` | `ids` | Makes the selection exactly these; an empty list clears it. | +| `select.add` | `ids` | Adds to it. | +| `select.remove` | `ids` | Takes these out of it, leaving the rest. | +| `select.all` | none | Every visible placement of the submodel being edited. | +| `select.clear` | none | Nothing. | +| `select.invert` | none | Every visible placement that was not selected, letting go of the rest. | +| `select.by_colour` | `colour` | Every visible placement in that colour, or in the colours of the selection when left out. | +| `select.by_part` | `part` | Every visible placement of that part, or of the parts of the selection when left out. A printed part counts as a different part. | + +## Rules + +- Only placements of the submodel being edited can be selected. Selecting one in another submodel is refused; `submodel.enter` or `submodel.leave` first (`sub-skills/submodels/SUB-SKILL.md`). +- Hidden placements cannot be selected, and `select.all`, `select.by_colour` and `select.by_part` pass over them. +- A placed or duplicated part becomes the selection, so after `part.place` the new part is selected. +- Undo brings back the selection that went with the change it takes back. +- The selection is never written into a file. + +## When to use it + +- Prefer explicit `ids` on every change. The person can change the selection in the window at any moment, so a change that relies on it can land on parts you did not mean. +- Use the selection to show the person something: `select.set` with the ids of the parts you are about to change, then say so, and the window outlines them. +- Use the kind commands to gather ids: `select.by_part` with `3001`, then `select.get`, answers every 2 x 4 brick in the submodel being edited, ready for `part.recolour` or `part.move`. diff --git a/.claude/skills/formblocks-driving/sub-skills/steps/SUB-SKILL.md b/.claude/skills/formblocks-driving/sub-skills/steps/SUB-SKILL.md new file mode 100644 index 0000000..a3046ac --- /dev/null +++ b/.claude/skills/formblocks-driving/sub-skills/steps/SUB-SKILL.md @@ -0,0 +1,46 @@ +--- +name: steps +description: Breaks a FormBlocks model into building steps that a person can follow, and adds, names, moves, deletes and shows steps. Use when asked to make building instructions or steps, to put parts in a step, to split, rename or reorder steps, to walk through a model step by step, or when new parts land in the wrong step. +--- + +# Steps + +Each submodel has its own building steps, numbered from 1. Every placement is in exactly one step. Showing step k draws steps 1 to k and hides the later ones, which is how a person walks through the build. In a saved file, steps are separated by `0 STEP` lines and a step's name is a line of FormBlocks' own at its start, so names survive an LDraw export. + +## The commands + +| Command | Kind | Parameters | What it does | +| --- | --- | --- | --- | +| `step.list` | read | `submodel` | Each step's number, name and placement ids, and which step is shown. | +| `step.goto` | view | `index` | Shows step `index` of the submodel being edited. New parts go into the step shown. | +| `step.break_after` | change | `id` | Starts a new step after placement `id`, moving the placements after it in its step into the new step. With no `id`, adds an empty step after the step shown and shows it. | +| `step.move_parts` | change | `ids`, `step` | Moves placements into another step of their submodel; one past the last starts a new step at the end. | +| `step.rename` | change | `step`, `name`, `submodel` | Names a step; an empty name clears it. | +| `step.delete` | change | `step`, `submodel` | Deletes a step; its placements move to the start of the next step, or to the end of the step before when it was the last. A submodel keeps at least one step. | + +`part.place` takes `step` too: the step to put the part in, or one past the last to start a new step with it. Without `step` the part goes into the step shown. + +## The trap: the step shown + +`step.goto` changes where new parts go. After `step.goto` with `index` 1, every later `part.place` without `step` lands in step 1, however many steps there are. When building, give `step` on every `part.place`, or `step.goto` the last step before you continue. `step.list` answers `shown`. + +## What makes a sensible step + +A person follows instructions one step at a time, so a step should be one small, clear action: + +- One course of bricks per step for walls; one layer of plates per step. +- Parts that support others come in an earlier step than what they support. A part must never be shown floating because its support is in a later step. +- Few parts per step: about 3 to 12 for a small model. Split a long course into two steps rather than make one of 30 parts. +- Repeated units built as submodels have their own steps; the use goes into one step of the parent (`sub-skills/submodels/SUB-SKILL.md`). +- Name steps that start something new: `Walls`, `Door lintel`, `Roof`. A name is optional; do not name every step. +- Keep the last step the whole model, so `step.goto` with the last index shows everything. + +## Building straight into steps + +Start with `model.new` (one empty step). Place course 1 with `step: 1`; place the first part of course 2 with `step: 2` (one past the last, so a new step starts); the rest of course 2 with `step: 2`; and so on. The examples in `examples/` do exactly this. + +## Fixing steps afterwards + +- A model built all in one step: `step.break_after` with the id of the last part of each course, in order from the bottom, splits it. +- A part in the wrong step: `step.move_parts`. +- Check with `step.list` that each step's parts stand on parts of the same or earlier steps. diff --git a/.claude/skills/formblocks-driving/sub-skills/submodels/SUB-SKILL.md b/.claude/skills/formblocks-driving/sub-skills/submodels/SUB-SKILL.md new file mode 100644 index 0000000..a21ac07 --- /dev/null +++ b/.claude/skills/formblocks-driving/sub-skills/submodels/SUB-SKILL.md @@ -0,0 +1,44 @@ +--- +name: submodels +description: Groups placements of a FormBlocks model into named submodels that can be used many times, and edits, renames, unpacks or deletes them. Use when a build repeats a unit (a leg, a window, a wall section), when asked to group, pack, unpack or rename parts of a model, to work inside a submodel, or when placing a use of one. +--- + +# Submodels + +A model is a tree: the main model at the top, holding placements of parts and uses of submodels, each submodel holding its own placements and steps. All uses of a submodel are linked: a change inside it shows in every use. In a saved file each submodel is a `0 FILE` block named after it, with `.ldr` added. + +## The commands + +| Command | Kind | Parameters | What it does | +| --- | --- | --- | --- | +| `submodel.list` | read | none | Every submodel with title, step count, placement count and uses; one with no uses is unused. | +| `submodel.create` | change | `ids`, `name` | Packs placements of one submodel into a new submodel named `name` and puts one use in their place. | +| `submodel.dissolve` | change | `id` | Unpacks a use: its parts come back into the parent at the same places, in the use's step. The submodel goes when its last use is unpacked. | +| `submodel.independent` | change | `id`, `new_name` | Copies the submodel of one use under a new name for that use alone, so it can change without touching the others. | +| `submodel.rename` | change | `name`, `new_name` | Renames a submodel and every use of it. | +| `submodel.delete` | change | `name`, `with_uses` | Deletes a submodel that is not the main model; one still in use is kept unless `with_uses` is true, which deletes its uses too. | +| `submodel.enter` | view | `id` or `name` | Edits a submodel in place: new parts, steps and the selection then act inside it. | +| `submodel.leave` | view | none | Goes back to the submodel above. | + +## Building a repeated unit + +1. Build one unit in the main model, seated as usual. +2. `submodel.create` with its ids and a name such as `Leg`. Names must be unique and may not hold `& # | ?`; `.ldr` is added for you, so the submodel is `Leg.ldr`. +3. The answer gives the use's id and `position`. The submodel's origin is the middle of the unit's footprint at its lowest placement's origin, moved to the grid, so the use's position is not at the ground: read it, do not assume it. +4. Make more uses with `part.duplicate` of the use and a `delta` on the grid. That keeps every copy at the same height as the first. +5. Or place a use by name: `part.place` with `part` set to the submodel's name (`Leg`) and a `position`. A use is placed exactly where sent: `on` and snapping seat library parts only, so take the height from the first use's position. +6. Give the use colour `16` to let parts inside drawn in 16 take each use's colour; parts with their own colour keep it. + +## Working inside one + +- `submodel.enter` with `name` (or with `id` of a use in the submodel being edited). `model.tree` with no `submodel` then answers the submodel's own placements, in its own coordinates. +- Placements inside a submodel are in its own coordinates, relative to its origin, not to the main model. +- `submodel.leave` when done. Read `editing` in the answer: the path from the main model to where you are. +- Commands that take `submodel` (`part.place`, `model.tree`, `step.list`, `step.rename`, `step.delete`) act in that submodel without entering it, which is safer for an agent because it does not depend on what the window has entered. + +## Rules + +- A submodel can never contain a use of itself, however deep; such a place is refused. +- Packing needs placements of one submodel; ids from two are refused. +- A submodel whose last use was deleted stays in the model, unused, until deleted. +- The main model cannot be deleted. diff --git a/.claude/skills/formblocks-driving/sub-skills/working-with-the-person/SUB-SKILL.md b/.claude/skills/formblocks-driving/sub-skills/working-with-the-person/SUB-SKILL.md new file mode 100644 index 0000000..116fb29 --- /dev/null +++ b/.claude/skills/formblocks-driving/sub-skills/working-with-the-person/SUB-SKILL.md @@ -0,0 +1,57 @@ +--- +name: working-with-the-person +description: Works with the person who has FormBlocks open, whose window asks them before an outside agent changes their model. Use when a change waits or is refused, when deciding what to say before changing or saving, when the person declines, when they edit at the same time, or when undoing could take back their work. +--- + +# Working with the person in the window + +The person and the agent work on the same open model. Everything the agent changes shows in the window as it lands, goes into the same undo history, and can be undone by the person. The person decides what an outside agent may change. + +## When the window asks + +Read and view commands never ask. A `change` or `file` command, and undo and redo, sent by an outside agent through `./formblocks mcp`, waits while the window asks the person, for up to two minutes. The question names your program and the tool. + +| The person answers | What happens | +| --- | --- | +| Deny | The call is refused and nothing changes. | +| Allow once | This call runs. The next change asks again. | +| Always allow | This call runs, and later changes from a program of the same name run without asking. | + +So the first change asks, and once the person has chosen Always allow, it does not ask again, with one exception: `model.save_as` to a path outside the folder of the model's own file asks every time, whatever the person chose before. A model with no file yet has no folder, so its first save as always asks. + +`formblocks_status` answers the person's standing choice in `outside_agents`: + +| `outside_agents` | `engine` | A change | +| --- | --- | --- | +| `ask` | `running` | Waits for the person's answer. | +| `allowed`, or your program allowed always | either | Runs at once (a save outside the folder still asks). | +| `blocked` | either | Refused. | +| `ask` | `headless` | Refused: no window is open, so nobody can allow it. Ask the person to start FormBlocks. | + +A program in a tab of the window's agent dock is the person's own and is not asked (`sub-skills/agent-dock/SUB-SKILL.md`), unless agents are blocked. + +## Before the first change + +Say in one or two sentences what you are going to build or change, so the question in the window makes sense when it appears. Group the work: a person asked twenty times in a row will choose Always allow or Deny out of tiredness, and either is worse than a clear first question. + +## When the person declines + +The answer is final for that change. Do not resend it, do not do the same thing by other commands, do not try another tool. Say what you wanted to do and why, and ask what they want instead. A timeout ("Nobody answered") is not a decline: ask them to look at the window, then send it once more. + +## Saving + +Say where a file will go before `model.save_as`, and use the folder the person named. Saving next to the model's own file asks only by the person's standing choice; anywhere else asks every time, which is the person's protection against files written where they did not expect. + +## Sharing the undo history + +- `formblocks_undo` takes back the newest change in the model, whoever made it. Undo only right after your own change, and read `labels` in the answer to confirm it took back yours. +- If the person may have changed something since, read `model.tree` first and fix your mistake with a change command instead of undo. +- Every change answers `undo`, its label in the Edit menu, so you can tell the person exactly what to undo. + +## Editing at the same time + +The person can select, move and delete parts while you work. Before acting on an id you read a while ago, read it again: `formblocks_status` answers the revision, which rises with every change by either of you. Pass `ids` instead of relying on the selection. + +## Discarding + +Never pass `discard: true` to `model.new` or `model.open` unless the person has said, in this conversation, to drop their unsaved changes. diff --git a/.claude/skills/formblocks-harness/SKILL.md b/.claude/skills/formblocks-harness/SKILL.md index 7a1acf0..4b35a4d 100644 --- a/.claude/skills/formblocks-harness/SKILL.md +++ b/.claude/skills/formblocks-harness/SKILL.md @@ -1,10 +1,10 @@ --- name: formblocks-harness -description: "Use when asked to install, boot, verify, debug or extend the FormBlocks repository (the formblocks launcher, formblocks_engine.py, the engine's LDraw reader, parts library, part meshes, connection model and model commands). Works on the checkout itself as a developer agent: the ./formblocks dispatcher and setup scripts, ports 5330, 5331 and 8330, the engine selfcheck, the health probe and MCP smoke scripts, the CLAUDE.md laws (hand-made single-region edits, zero DOM flash, tokens only, no emoji, HASHOUT logs, one commit identity, the clean room and spec/ as the authority), and the three places a feature is added: a command, a router and a pane. Not for building models in a running FormBlocks through MCP; that is the formblocks-driving skill." +description: "Use when asked to install, boot, verify, debug, extend or release the FormBlocks repository itself: its engine code (the LDraw reader, parts library, part meshes, connection model, the model and its command catalogue), its window, its setup scripts or its skill packs. Works on the checkout as a developer agent: the ./formblocks launcher, ports 5330, 5331 and 8330, doctor, selfcheck, the contract checker, agents check, looking at the window headless, the health probe and MCP smoke scripts, the CLAUDE.md laws (hand-made single-region edits, zero DOM flash, tokens, no emoji, HASHOUT logs, one commit identity), the clean room with spec/ as the authority, the packages and their dependency order, and adding a command, a connector kind, a router or a pane. Also the parts library and its scratch copy for checks, freezing the engine and the release. Not for building models in a running FormBlocks through its MCP tools or command line; that is formblocks-driving." license: Apache-2.0 metadata: product: FormBlocks - pack-version: "0.2.0" + pack-version: "0.3.0" audience: developer agent --- @@ -21,9 +21,14 @@ The pack never repeats what the code can tell you. Command names come from the c | A fresh clone, installing, booting, ports, environment variables, the data folder, the window key | `sub-skills/install-and-boot/SUB-SKILL.md` | | Proving a change: doctor, selfcheck, typecheck, health probe, MCP smoke, agents sync check, the contract check | `sub-skills/verify/SUB-SKILL.md` | | Before editing anything: the laws, hand-made edits, HASHOUT logs, version sites, commits, licences, clean room | `sub-skills/laws-and-logs/SUB-SKILL.md` | +| What may be read and copied, spec/ as the authority, a change of behaviour starting in spec/ | `sub-skills/clean-room-and-spec/SUB-SKILL.md` | +| The engine's packages (ldraw, library, mesh, connect, doc, cmd and above), their dependency order, where new code goes | `sub-skills/packages/SUB-SKILL.md` | | Adding or changing a command of the catalogue, and the MCP tool and references made from it | `sub-skills/add-command/SUB-SKILL.md` | +| Adding a connector kind (pins, axles, clips, hinges) as a registered module, or fixing a kind's data | `sub-skills/add-connector-kind/SUB-SKILL.md` | +| The parts library: where the engine finds it, the consent-gated fetch, the scratch copy for checks, its caches | `sub-skills/parts-library-and-scratch/SUB-SKILL.md` | | Adding an engine route under `/api`, its guard and where it is mounted | `sub-skills/add-router/SUB-SKILL.md` | | Adding a pane or another part of the window without a flash | `sub-skills/add-pane/SUB-SKILL.md` | +| Freezing the engine, desktop builds, data files the freeze carries, dependencies, versions and the release | `sub-skills/freeze-and-ship/SUB-SKILL.md` | For any task that edits files, load `laws-and-logs` as well as the specialist. It is short and its rules are not negotiable. @@ -44,11 +49,14 @@ These come from `CLAUDE.md` and the owner checks them on every change. `sub-skil - SEDO: edit tracked files only with hand-made single-region edits made with the editing tool. Never `sed -i`, `awk`, `patch`, `git apply`, codemods or edit scripts on tracked files. New files are written whole. - Zero DOM flash: every container exists in its final layout before the first paint; script patches nodes in place. - Colours, spacing and every `z-index` come from the tokens in `frontend/src/styles/tokens.css`; icons are inline `currentColor` SVG from `frontend/src/ui/icons.ts`. -- No emoji anywhere and no em dash (U+2014) in markdown. Near-zero comments; reasons go into the `HASHOUT_LOG.md` beside the code. +- No emoji anywhere and no em dash (U+2014) or en dash (U+2013) anywhere. Near-zero comments; reasons go into the `HASHOUT_LOG.md` beside the code. - The engine owns all state; the window renders and dispatches. Every write route needs the window key. +- Clean room: write from `spec/` and the public LDraw documentation only, and change `spec/` before changing behaviour (`sub-skills/clean-room-and-spec/SUB-SKILL.md`). +- The parts library is never committed, bundled or fetched without the person's consent (`sub-skills/parts-library-and-scratch/SUB-SKILL.md`). - No new dependency without a `NOTICE.md` row first. GPL and AGPL never enter a distributed build. - Commits carry the one identity `CLAUDE.md` names and no `Co-Authored-By` or other attribution line. - Write no tests unless the owner asks; verification is the checks in `sub-skills/verify/SUB-SKILL.md`. +- Several agents may run the app from one tree: boot on ports and a data folder of your own (`FORMBLOCKS_PORT`, `FORMBLOCKS_DATA_DIR`), and stop only the processes you started, by their process id. ## Scripts in this pack @@ -62,3 +70,5 @@ Run them, do not read them into context. Both use the Python standard library on ## Reference `references/ports-and-env.md` holds the port table, every `FORMBLOCKS_*` variable with who reads it, and what the engine keeps in its data folder. Load it when you need an exact variable or path. + +`evals/evals.json` holds the pack's evaluations and trigger tests, for whoever changes this pack. diff --git a/.claude/skills/formblocks-harness/evals/evals.json b/.claude/skills/formblocks-harness/evals/evals.json new file mode 100644 index 0000000..786052f --- /dev/null +++ b/.claude/skills/formblocks-harness/evals/evals.json @@ -0,0 +1,77 @@ +{ + "skill_name": "formblocks-harness", + "notes": "Run in a FormBlocks checkout with the engine venv installed. Expected behaviours are visible in the transcript, the diff and the commit.", + "evals": [ + { + "id": 1, + "name": "add-a-read-command", + "prompt": "Add a read-only command to FormBlocks that counts the studs left free on top of the model, so agents can call it.", + "files": [], + "expected_behavior": [ + "Writes the rule into spec/SPEC.md and section 21.2 before the code, in its own commit", + "Adds the command with @command, a title, one sentence, kind read, in backend/app/cmd/commands/", + "Runs the selfcheck, ./formblocks cli commands with the id, a run on a throwaway folder, ./formblocks agents sync and agents check", + "Logs the reason in backend/HASHOUT_LOG.md in the same commit and edits files only by hand-made single-region edits" + ] + }, + { + "id": 2, + "name": "pin-connector-kind", + "prompt": "We need pins and pin holes to connect in FormBlocks. Add them.", + "files": [], + "expected_behavior": [ + "Starts in spec/CONNECTIONS.md and reads the library's own primitive files, never another program's connection data", + "Adds a module in backend/app/connect/kinds/ that registers itself, with its data in JSON beside it and a version for the cache", + "Checks part.connectors on real parts against hand-worked numbers, with a throwaway data folder and FORMBLOCKS_LDRAW_DIR, and confirms 3001 still answers 8 studs and 11 anti-studs" + ] + }, + { + "id": 3, + "name": "window-change-looked-at", + "prompt": "Add a small panel under the colour palette that shows how many parts the model has. Make sure it does not flicker.", + "files": [], + "expected_behavior": [ + "Writes the panel's whole structure once in onShellMounted and patches it from the doc store with the ui/dom.ts helpers", + "Uses tokens from styles/tokens.css and no raw colour or numeric z-index", + "Builds and opens the window headless on ports of its own, screenshots it, and reports the layout shift score under 4x CPU and network throttling" + ] + }, + { + "id": 4, + "name": "library-in-a-fixture", + "prompt": "Copy a few LDraw part files into the repo so the checks can run without the library.", + "files": [], + "expected_behavior": [ + "Refuses to commit any part of the LDraw library and explains why", + "Offers FORMBLOCKS_LDRAW_DIR pointing at a copy outside the tree, and checks that need no parts" + ] + }, + { + "id": 5, + "name": "adjacent-driving-task", + "prompt": "Use FormBlocks to build me a red wall of bricks.", + "files": [], + "expected_behavior": [ + "Recognises a model-building task and moves to formblocks-driving instead of editing source" + ] + } + ], + "trigger_evals": [ + { "query": "add a new command to the FormBlocks engine", "should_trigger": true }, + { "query": "formblocks wont boot, port 8330 busy, help", "should_trigger": true }, + { "query": "Please run the selfcheck, the contract checker and agents check on the FormBlocks checkout.", "should_trigger": true }, + { "query": "add a connector kind for axles to formblocks", "should_trigger": true }, + { "query": "freeze the formblocks engine and build the desktop app", "should_trigger": true }, + { "query": "fix the flicker in the formblocks parts palette", "should_trigger": true }, + { "query": "where does the LDraw reader live in the formblocks code and what may it import", "should_trigger": true }, + { "query": "update the formblocks skill packs and sync the mirrors", "should_trigger": true }, + { "query": "build a house with a roof in FormBlocks", "should_trigger": false }, + { "query": "place a 2 x 4 brick on p12 and save the model", "should_trigger": false }, + { "query": "what colour code is dark bluish grey in FormBlocks", "should_trigger": false }, + { "query": "add a command to the FormAnything app studio", "should_trigger": false }, + { "query": "write a Tauri app from scratch", "should_trigger": false }, + { "query": "export my open FormBlocks model to .ldr", "should_trigger": false }, + { "query": "explain the LDraw file format to me", "should_trigger": false }, + { "query": "register the formblocks MCP server with my agent program", "should_trigger": false } + ] +} diff --git a/.claude/skills/formblocks-harness/references/ports-and-env.md b/.claude/skills/formblocks-harness/references/ports-and-env.md index 09cf1bd..e9d6975 100644 --- a/.claude/skills/formblocks-harness/references/ports-and-env.md +++ b/.claude/skills/formblocks-harness/references/ports-and-env.md @@ -25,6 +25,12 @@ Set them in the shell. A `backend/.env` file is read with `setdefault`, so a rea | `FORMBLOCKS_PORT` | setup scripts, engine | The engine's port (default 8330). | | `FORMBLOCKS_BACKEND_PORT` | `frontend/vite.config.ts` | Development only: the engine port the window proxies to. | | `FORMBLOCKS_DATA_DIR` | engine | The data folder. Default: the platform's app data folder under `FormBlocks`. | +| `FORMBLOCKS_LDRAW_DIR` | engine (`library/locate.py`) | A parts library folder to use when the settings name none; how a check runs against a library unpacked by hand. Nothing from it is ever committed. | +| `FORMBLOCKS_HOST` | `formblocks_engine.py`, `boot_backend.bat` | The address the engine binds; 127.0.0.1 unless changed, with a warning when it is not loopback. | +| `FORMBLOCKS_URL`, `FORMBLOCKS_TOKEN` | `./formblocks mcp` bridge, `cli` | The running engine's address and window key, instead of reading `engine.port` and `session.token` from the data folder. | +| `FORMBLOCKS_CALLER_DIR` | `setup/cli` | The folder `cli` was run from, so a relative `path` is read from there. Set by the launcher. | +| `FORMBLOCKS_SHELL_PID` | engine | The desktop shell's pid, so the engine ends with the shell. Set by the shell. | +| `FORMBLOCKS_WINDOW_PORT`, `FORMBLOCKS_PREVIEW_PORT`, `FORMBLOCKS_ROOT` | `setup/lib.sh` | Set by the setup scripts themselves (5330, 5331, the checkout); not read from the environment. | | `FORMBLOCKS_PORTABLE` | engine | `1` keeps the data beside the app, in `FormBlocksData`. | | `FORMBLOCKS_DIST` | engine, `setup/serve` | A built window folder to serve instead of `frontend/dist`. | | `FORMBLOCKS_DESKTOP` | engine | `1` when the desktop shell started the engine. | diff --git a/.claude/skills/formblocks-harness/sub-skills/add-command/SUB-SKILL.md b/.claude/skills/formblocks-harness/sub-skills/add-command/SUB-SKILL.md index cd7bf01..1b45a0c 100644 --- a/.claude/skills/formblocks-harness/sub-skills/add-command/SUB-SKILL.md +++ b/.claude/skills/formblocks-harness/sub-skills/add-command/SUB-SKILL.md @@ -33,7 +33,8 @@ Load `sub-skills/laws-and-logs/SUB-SKILL.md` first. A command is the only way an The function takes the document and the parameters by name and returns a small dict. It refuses bad input with `CommandError("A plain sentence.")`, which every surface shows as it is; name the parameter in it. Parameter types are `string`, `integer`, `number`, `boolean` and `array` (with `items` and lengths); give strings a maximum length. Pass `kind="read"` for a command that only reads and `kind="view"` for one that changes only the view. 3. Change only the model through `doc.model` (`edit_placement`, `edit_submodel`, `insert`, `take_out`: values are copied on write, so never change one in place) or the view in `doc.view`; never write files, start processes or keep state of your own there. Set `doc.label` for an undo label such as "Move 3 parts". Anything the window must show comes from the document, never from the command's return value alone. 4. Run `./formblocks agents sync`. It rewrites `agents/manifest.json` and the generated tool reference in the formblocks-driving pack, and mirrors the skills. The MCP server gains one tool for the command; read its name from `tools/list`, never guess it. -5. Verify: the selfcheck (its `commands` count goes up by one), `./formblocks cli commands ` to see the entry, `./formblocks cli run key=value --settings-dir ''` once on a throwaway folder, `./formblocks agents sync --check`, then `scripts/mcp_smoke.py`. Log the decision in `backend/HASHOUT_LOG.md` in the same commit. +5. Verify: the selfcheck (its `commands` count goes up by one), `./formblocks cli commands [id]` to see the entry, `./formblocks cli run [id] key=value --settings-dir ''` once on a throwaway folder, `./formblocks agents sync --check`, then `scripts/mcp_smoke.py`. Log the decision in `backend/HASHOUT_LOG.md` in the same commit. +6. Keep the documents in step: `spec/SPEC.md` section 21.2 lists every catalogue command with its kind, and a command added is added there in the same change (`sub-skills/clean-room-and-spec/SUB-SKILL.md`). Tell whoever owns the formblocks-driving pack, so the sub-skill for that area names the new command. ## Changing a command diff --git a/.claude/skills/formblocks-harness/sub-skills/add-connector-kind/SUB-SKILL.md b/.claude/skills/formblocks-harness/sub-skills/add-connector-kind/SUB-SKILL.md new file mode 100644 index 0000000..a2075b1 --- /dev/null +++ b/.claude/skills/formblocks-harness/sub-skills/add-connector-kind/SUB-SKILL.md @@ -0,0 +1,52 @@ +--- +name: add-connector-kind +description: Adds a connector kind to FormBlocks' connection model as a module that registers itself in backend/app/connect/kinds/, with its data beside it as JSON. Use when adding pins, axles, clips, bars, hinges or any joint beyond studs and anti-studs, when correcting the primitive list of an existing kind, or when a part's connectors come out wrong. +--- + +# Add a connector kind + +Load `sub-skills/laws-and-logs/SUB-SKILL.md` and `sub-skills/clean-room-and-spec/SUB-SKILL.md` first. The mechanics are `spec/CONNECTIONS.md`, "Adding a kind"; this page is the working order. The connection service never names a kind: adding one adds a module, and changes nothing in the service, the connector shape, the overrides format or the cache. + +## Before any code + +1. Write the kind into `spec/CONNECTIONS.md` first, in its own commit: what it is, what it mates with, the freedom a mate leaves, how it is found in a part's geometry. +2. Read the official primitive files the kind will claim, from the library (`FORMBLOCKS_LDRAW_DIR` on a check machine, `sub-skills/parts-library-and-scratch/SUB-SKILL.md`), and record their geometry in your own words, as `spec/CONNECTIONS.md` does for studs. +3. Work at least three real parts through the rule by hand before writing the module, and keep the numbers for the check below. +4. Never copy a primitive list, a tolerance or a connection table from another program's data; the list comes from reading the library's own primitives. + +## Where the module lives + +- `backend/app/connect/kinds/[kind].py`, one module per kind or per family of kinds. `kinds.load()` imports every module in the package whose name does not start with `_`, in name order, so no list is edited anywhere. +- The module's data (primitive file names, tolerances) sits beside it as `[kind].json` and is read when the module loads, so a list can be corrected without touching code. A data file that cannot be read stops the engine with a sentence naming the file. +- At the end of the module, one call per kind: `PIN = register(PinKind())`. + +## What the module provides + +A subclass of `Kind` from `backend/app/connect/kinds/__init__.py`: + +| Member | Purpose | +| --- | --- | +| `name` | The kind's name: lower case letters, digits and `_`. `register` refuses anything else, and refuses a second module registering the same name. | +| `mates_with` | The kinds it pairs with; the registry makes pairing symmetric. | +| `version` | Part of the connector cache key. Raise it whenever the kind's rule or data changes, so cached parts are derived again. | +| `body` | Whether the triangles of files it claims count in the overlap check's body box. | +| `claims(file_name)` | True for the primitive files that are this kind's connectors; the walk does not descend into a claimed file. | +| `from_reference(file_name, transform)` | The connectors one claimed reference makes, in part coordinates. | +| `settle(mesh, own)` | Optional: correct this kind's connectors once the walk is over and the bottom plane is known. | +| `from_mesh(mesh, connectors)` | Optional: connectors found from the whole flattened part. | +| `mate(a, b)` | `None`, or a `Mate`: the correction that brings `a` onto `b`, the residual, and the `Freedom` left (`Freedom.spin`, `slide`, `hinge` or `fixed`). `axial_mate` covers round connectors on a shared axis. | +| `blocks(connector, other)` | Optional: a blocked test of the kind's own, as the stud's blocked-stud test is. | + +Connectors already carry `ref` (for kinds whose turn about the axis matters) and `length` (for kinds that slide), so the connector shape does not change. + +## Overrides + +`backend/app/connect/overrides.json` corrects the derivation for single parts. Entries may name the new kind as soon as the module exists. Each entry changes the cache key of the parts it touches. + +## Check + +1. Selfcheck: `backend/venv/bin/python backend/formblocks_engine.py --selfcheck` imports the kinds. +2. With a library in reach, `./formblocks cli run part.connectors part=[number]` for each part you worked by hand: the counts, positions, axes and `source` must match your numbers. Run it with a throwaway data folder (`--settings-dir ''`) so no old cache answers. +3. Place two parts that should mate with `part.fit` and `part.place` and read `seated` and `joined`; run `overlap.check`. +4. Check the stud kind still answers as before: `part.connectors` for `3001` gives 8 studs and 11 anti-studs, as `spec/CONNECTIONS.md` Example 1 works out. +5. Log the kind, its sources and the parts you checked in `backend/app/connect/HASHOUT_LOG.md`, in the same commit as the module. diff --git a/.claude/skills/formblocks-harness/sub-skills/add-pane/SUB-SKILL.md b/.claude/skills/formblocks-harness/sub-skills/add-pane/SUB-SKILL.md index fd6e6e4..8524f05 100644 --- a/.claude/skills/formblocks-harness/sub-skills/add-pane/SUB-SKILL.md +++ b/.claude/skills/formblocks-harness/sub-skills/add-pane/SUB-SKILL.md @@ -10,18 +10,19 @@ Load `sub-skills/laws-and-logs/SUB-SKILL.md` first. The window renders what the ## How the window is put together - `frontend/index.html` boots the theme in an inline script before anything paints and keeps `#app` hidden until the shell is mounted and the fonts are ready. -- `frontend/src/app.ts` is the composition root. `startApp()` writes the shell once (top bar, side panel, main area, status bar) and calls every hook registered with `onShellMounted(fn)`, handing each the hosts: `hosts.topbar`, `hosts.tools`, `hosts.menu`, `hosts.panel`, `hosts.main`, `hosts.status`. -- Each part is a module under `frontend/src/ui/` that registers itself: `notes-view.ts` fills `hosts.main` (the template's starter view, which the viewport will replace), `side-panel.ts` fills `hosts.panel`, `status.ts` fills `hosts.status`. `frontend/src/main.ts` imports each once for its side effect. -- Engine state reaches the window through stores: `ui/doc-store.ts` (the document, with the ids that changed), `io/catalogue.ts` (the command catalogue). Subscribe with `onChange`; never fetch on a timer. +- `frontend/src/app.ts` is the composition root. `startApp()` mounts the shell once and runs every hook registered with `onShellMounted(fn)`, handing each the hosts. +- `frontend/src/ui/shell.ts` holds `SHELL`, the whole window's markup, and `ShellHosts`, the named hosts a module fills: `topbar`, `menu`, `fileTools`, `tools`, `panel` (the parts palette), `main`, `viewport`, `hud`, `right`, `colours`, `tabs`, `details`, `strip` (the step controls) and `status`. Read the file for the current list; the window lane changes it. +- Each part is a module under `frontend/src/ui/` (or `frontend/src/view/` for the 3D viewport) that registers itself. `frontend/src/main.ts` imports the shell's own modules once each for their side effect; feature modules are imported once each from `frontend/src/ui/features.ts`. +- Engine state reaches the window through stores: `ui/doc-store.ts` (the document, with the ids that changed), `io/catalogue.ts` (the command catalogue), `io/settings.ts`, `io/library.ts`, and `io/live.ts` (the engine's live channel). Subscribe; never fetch on a timer. - Commands go out through `ui/run.ts` (`runCommand(name, params)`), which sends the window key; the pane shows a result only when the revision comes back. ## Steps -1. Write `frontend/src/ui/.ts`. In `onShellMounted(({ hosts }) => { ... })`, write the pane's whole structure into its host once, with `innerHTML` or `el()`, including every empty line, count and button it will ever show, so nothing appears or moves later. -2. Fill it from a store: subscribe with `docStore.onChange` or `catalogue.onChange`, and patch with the helpers in `ui/dom.ts`: `patchList` keeps rows by key and touches only changed ones, `setText`, `setHidden`, `setDisabled`, `setAttr` write only when the value differs. Never rebuild a live container to change one node. -3. Add one line to `frontend/src/main.ts`: `import './ui/';`. -4. Style it in `frontend/src/styles/.css`, linked once in `frontend/index.html` beside the others. Every colour, space, size and layer is a `var(--...)` from `styles/tokens.css`; add a token there when none fits. No raw colour, no numeric `z-index`. -5. Icons: add a hand-written inline `currentColor` SVG to `ui/icons.ts` and use `icon('')`. No icon library, no copied icon art. -6. A window command (a button, a menu item, a key) is added with `commands.add({ id, title, summary, icon, group, keys, run })` from `ui/commands.ts`, so the palette, the menu and the keys all find it. A command that changes the document calls `runCommand` with an engine command; it never changes the view directly. -7. A new region of the shell (a second panel, a tab strip) is a change to `SHELL` in `app.ts` and to the grid in `styles/shell.css`. Make it only when no existing host fits, and log why in `frontend/HASHOUT_LOG.md`. -8. Verify: `npm run typecheck` and `npm run build` in `frontend/`, then a hard reload under 4x CPU and network throttling: the first frame shows the pane in its final place and nothing shifts. Say what you saw, or that it was not run. Log the decision in `frontend/HASHOUT_LOG.md` in the same commit. +1. Write `frontend/src/ui/[name].ts`. In `onShellMounted(({ hosts }) => { ... })`, write the pane's whole structure into its host once, with `innerHTML` or `el()` from `ui/dom.ts`, including every empty line, count and button it will ever show, so nothing appears or moves later. +2. Fill it from a store and patch with the helpers in `ui/dom.ts`: `patchList` keeps rows by key and touches only changed ones; `setText`, `setHidden`, `setDisabled`, `setAttr`, `setClass`, `setTitle` and `setHtml` write only when the value differs. Never rebuild a live container to change one node. +3. Add one line to `frontend/src/ui/features.ts`: `import './[name]';`. +4. Style it in `frontend/src/styles/[name].css`, linked once in `frontend/index.html` beside the others. Every colour, space, size and layer is a `var(--...)` from `styles/tokens.css`; add a token there when none fits. No raw colour, no numeric `z-index`. Interface text goes in `ui/strings.ts`. +5. Icons: add a hand-written inline `currentColor` SVG to `ui/icons.ts` and use `icon('[name]')`. No icon library, no copied icon art, never a three-star sparkle. +6. A window command (a button, a menu item, a key) is added through `commands` in `ui/commands.ts`, so the palette, the menu and the keys all find it. A command that changes the document calls `runCommand` with an engine command; it never changes the view directly. +7. A new region of the shell is a change to `SHELL` and `ShellHosts` in `ui/shell.ts` and to the grid in `styles/shell.css`. Make it only when no existing host fits, and log why in `frontend/HASHOUT_LOG.md`. +8. Verify: `npm run typecheck` and `npm run build` in `frontend/`, then look at the window headless (`sub-skills/verify/SUB-SKILL.md`, "Looking at the window"): a screenshot of the pane, and a hard reload under 4x CPU and network throttling with a layout shift score of 0. Say what you looked at, or that it was not run. Log the decision in `frontend/HASHOUT_LOG.md` in the same commit. diff --git a/.claude/skills/formblocks-harness/sub-skills/add-router/SUB-SKILL.md b/.claude/skills/formblocks-harness/sub-skills/add-router/SUB-SKILL.md index 0f36fec..4dd6824 100644 --- a/.claude/skills/formblocks-harness/sub-skills/add-router/SUB-SKILL.md +++ b/.claude/skills/formblocks-harness/sub-skills/add-router/SUB-SKILL.md @@ -13,12 +13,12 @@ Anything that changes the document is a command (`sub-skills/add-command/SUB-SKI ## Steps -1. Write `backend/app/routers/.py` with `router = APIRouter(tags=[""])` and its handlers. Keep the work in a service or the document, not in the handler: the handler reads the request, calls one function and returns a small JSON object. Run blocking work with `run_in_threadpool`, as `routers/commands.py` does. -2. Mount it with one line in the `ROUTERS` list of `backend/app/main.py`: `("app.routers.", "/api")`, or a longer prefix. Add the line only after the module imports cleanly, then run the selfcheck at once: it imports every router and prints the count. +1. Write `backend/app/routers/[name].py` with `router = APIRouter(tags=["[name]"])` and its handlers. Keep the work in a service or the document, not in the handler: the handler reads the request, calls one function and returns a small JSON object. Run blocking work with `run_in_threadpool`, as `routers/commands.py` does. +2. Mount it with one line in the `ROUTERS` list of `backend/app/main.py`: `("app.routers.[name]", "/api")`, or a longer prefix. Add the line only after the module imports cleanly, then run the selfcheck at once: it imports every router and prints the count. 3. Leave the guard alone. `backend/app/core/guard.py` refuses a request from another computer or a foreign origin, and asks every `/api` and `/mcp` path for the window key in the `x-formblocks-token` header, except the short open list (`/api/health`). A new route is guarded the moment it is mounted. Adding a path to the open list is a security decision: log the reason in `backend/HASHOUT_LOG.md` and say so in your report. 4. Outside agents never call `/api` routes; they come in through MCP. If an agent needs what the route gives, expose it as a read-only command or an MCP tool instead of opening the route. 5. If the window calls the route, call it through the engine client in `frontend/src/io/api.ts`, which sends the key; never with a bare `fetch`. -6. Verify: compile, selfcheck, boot, then `curl -s 127.0.0.1:8330/api/` answers 401 or 403 without the key (the guard working) and the window gets its answer with it. Log the route in `backend/HASHOUT_LOG.md` in the same commit. +6. Verify: compile, selfcheck, boot (on a port of your own, `FORMBLOCKS_PORT`, when others may be running the app), then `curl -s -o /dev/null -w "%{http_code}" 127.0.0.1:8330/api/[path]` answers 401 without the key (the guard working; `/api/health` answers 200) and the window gets its answer with it. Log the route in `backend/HASHOUT_LOG.md` in the same commit. ## What a route never does diff --git a/.claude/skills/formblocks-harness/sub-skills/clean-room-and-spec/SUB-SKILL.md b/.claude/skills/formblocks-harness/sub-skills/clean-room-and-spec/SUB-SKILL.md new file mode 100644 index 0000000..be96a40 --- /dev/null +++ b/.claude/skills/formblocks-harness/sub-skills/clean-room-and-spec/SUB-SKILL.md @@ -0,0 +1,45 @@ +--- +name: clean-room-and-spec +description: Keeps FormBlocks clean room and spec/ the authority over its behaviour. Use before changing what the app does, when a task and spec/ disagree, when adding a source or a rule to spec/, when tempted to look at another brick program or its data, or when deciding where code may be copied from. +--- + +# The clean room and spec/ + +FormBlocks is written from its own specification and the public LDraw documentation, and from nothing else that describes another program. That is what lets it be Apache-2.0 and free of anyone else's claims. The rules below are absolute; `CLAUDE.md` states them and this page says how to work with them. + +## What may be read + +| May be read | May not be opened, fetched, quoted or copied | +| --- | --- | +| `spec/` in this repository | The source, binaries, data, project files or connection data of any brick building program or CAD product | +| The public LDraw documentation on ldraw.org, and official library files for their geometry | Their help text, manuals and artwork, beyond what `spec/PROVENANCE.md` records as already read for outcomes | +| The Apache-2.0 family apps: FormCAD, FormVis, FormSculpt, FormDeck, form.ext-registry, and form.ext's `contract/`, `sdk/` and `templates/` | Any GPL family repository (FormAnything's app folders, formsubstrate, formslot, formMCP, formskills, formportal, formcompiler, formadaptor, the rest of form.ext) | + +The pages `spec/PROVENANCE.md` lists were read once for outcomes; do not go back to them for wording. Never name another vendor's product in code, identifiers, commands, MCP tools or interface text; other products are named only in `spec/PROVENANCE.md`, the README's "instead of" line, the trademark notice and the registry's `alt_of` field. + +## spec/ decides + +| File | Decides | +| --- | --- | +| `spec/SPEC.md` | What the person can do and see: each feature area, its rules, edge cases and commands. Section 21 is the command catalogue at a glance. | +| `spec/LDRAW.md` | How LDraw files and the library are read and written, and FormBlocks' own `!FORMBLOCKS` lines. | +| `spec/CONNECTIONS.md` | Connector kinds, deriving them, snapping, the grid fallback, the overlap check, adding a kind. | +| `spec/NAMES.md` | What FormBlocks calls its own tools and panels. Use these names in code and interface text. | +| `spec/PROVENANCE.md` | The numbered public sources, the date each was read and what it established. | + +Where a plan, a task or the code differs from `spec/`, `spec/` is right. A command id comes from the specification: when a task names an id and section 21.2 already reserves another for the same thing, the catalogue uses the reserved id and the hashout log says so. + +## A change of behaviour starts in spec/ + +1. Find the section the change belongs to. If the change contradicts it, stop and say so to the owner; do not change behaviour quietly. +2. Write the change into `spec/` first, by hand, in its own commit: the rule as an outcome the person can observe, ending in a source id already in `PROVENANCE.md`, a new public source added there with the date read, or `[our own design]` (`[ours]` in `LDRAW.md`; no key in `CONNECTIONS.md`). +3. A new command joins the table of section 21.2 with its kind in the same change that adds it to the catalogue (`sub-skills/add-command/SUB-SKILL.md`). +4. Then change the code to match, and log the reason in the `HASHOUT_LOG.md` beside the code. +5. When the code was right and `spec/` was stale, correct `spec/` in its own commit and say which line was wrong. + +## Facts that are easy to get wrong + +- -Y is up in LDraw, and every number a person types, sees, or passes to the command line or an MCP tool is on the LDraw axes (`spec/SPEC.md` 0.2). The one conversion to the window's +Y-up scene lives in `backend/app/mesh/scene.py`. +- A saved model holds references to parts, never a part file's own lines. +- The parts library is fetched only after the person's consent and is never bundled (`sub-skills/parts-library-and-scratch/SUB-SKILL.md`). +- Connection data is derived from the parts' own geometry; no list may be copied from another program's connection data (`spec/CONNECTIONS.md`, "What a later kind must do first"). diff --git a/.claude/skills/formblocks-harness/sub-skills/freeze-and-ship/SUB-SKILL.md b/.claude/skills/formblocks-harness/sub-skills/freeze-and-ship/SUB-SKILL.md new file mode 100644 index 0000000..6a13d0c --- /dev/null +++ b/.claude/skills/formblocks-harness/sub-skills/freeze-and-ship/SUB-SKILL.md @@ -0,0 +1,40 @@ +--- +name: freeze-and-ship +description: Freezes the FormBlocks engine with PyInstaller, runs and builds the desktop app, and prepares a release that formcompiler builds and an owner publishes. Use for ./formblocks freeze, desktop dev or build, ./build_app, the frozen engine's selfcheck, data files the freeze must carry, version sites, the registry entry, or anything about release artifacts and the parts library staying out of them. +--- + +# Freeze and ship + +Nothing in this repository pushes, signs (beyond the frozen engine on macOS) or publishes a release. formcompiler builds every release from `apps/formblocks.json`; an owner publishes it. `docs/RELEASE.md` is the full procedure; read it before touching release files. + +## Commands + +| Command | Output | Note | +| --- | --- | --- | +| `./formblocks build` | `frontend/dist` | The window's production build. | +| `./formblocks install-desktop` | PyInstaller in the engine venv | Also checks the Rust and Tauri toolchain. Needed before a freeze. | +| `./formblocks freeze` | `src-tauri/engine/formblocks-engine` (PyInstaller onedir) | `setup/freeze_backend`: builds the window first when `frontend/dist` is missing, bundles it as `frontend_dist`, collects the `app` and `uvicorn` submodules, and runs the frozen engine's `--selfcheck` at the end. On macOS it flattens and signs the engine (`APPLE_SIGNING_IDENTITY`, else ad hoc). | +| `./formblocks desktop dev` | the Tauri shell with the frozen engine | Freezes once if there is no frozen engine. | +| `./formblocks desktop build --config [file]` | the desktop bundles | The step formcompiler runs; `--config` is passed to the bundler as given. | +| `./build_app` | a desktop build for a person, start to finish | Logs to `build_app.log`; `--no-install`, `--install`, `--open`, `--clean`, `--config FILE`. | +| `./formblocks clean`, `clean --all` | removes build output; `--all` also the venv and `node_modules` | Ask before `--all`: other agents may be using them. | + +Windows has a `.bat` twin of every script. A desktop build needs WebKitGTK (`libwebkit2gtk-4.1-dev`) on Linux; where it is missing, as on the check machines here, no Tauri build runs: say so, never claim one passed. + +## Data files the freeze must carry + +`--collect-submodules` brings Python modules only. The engine also reads JSON beside its code: `backend/app/connect/kinds/stud.json` (the stud kind stops the engine with a sentence when it cannot read it), `backend/app/connect/overrides.json` and `backend/app/library/categories.json`. `setup/freeze_backend` adds `backend/app/data` when that folder exists, and nothing else. When you add a data file, or before trusting a freeze, make sure each one is carried (an `--add-data` entry, or moving it under `backend/app/data`), then check the frozen engine reads it: `src-tauri/engine/formblocks-engine --selfcheck`, and a command that needs it (`part.connectors` with a library in reach) run against the frozen engine. + +## Dependencies + +A new engine dependency needs, in one change: its pinned line in `backend/requirements.txt`, its `NOTICE.md` row with its licence, and a freeze entry (`--hidden-import` or `--collect-*`) when PyInstaller cannot find it alone. A window dependency needs its exact version in `frontend/package.json` and its `NOTICE.md` row; the contract checker reports a direct dependency missing from `NOTICE.md`. + +## The parts library never ships + +No installer, frozen engine, bundle or release asset may hold any part of the LDraw parts library: no `parts/`, `p/` or `LDConfig.ldr`, no saved index, no mesh cache. Check the frozen folder before calling a freeze good: `find src-tauri/engine -name LDConfig.ldr -o -type d -name parts` prints nothing. + +## Versions and the release commit + +- A version is `x.yy.z` and is bumped by hand at every site in one commit (the list is in `sub-skills/laws-and-logs/SUB-SKILL.md`, "Version sites"). Only the lead bumps a version, and the release commit, `chore(release): version x.y.z (x.y.z)`, comes last. +- `apps/formblocks.json` is the registry entry formcompiler reads (kind `bricks`, project file `.fblk`, state `prelaunch`); `apps/products-row.json` the portal row. Change them only as the contract asks, and run the contract checker after (`sub-skills/verify/SUB-SKILL.md`). +- The skill packs ship beside the installers as `formblocks-skills-vX.Y.Z.zip`, built by formcompiler from `skills/`: run `./formblocks agents check` before a release so the packs, mirrors and manifest agree. diff --git a/.claude/skills/formblocks-harness/sub-skills/install-and-boot/SUB-SKILL.md b/.claude/skills/formblocks-harness/sub-skills/install-and-boot/SUB-SKILL.md index a56697f..f226e9b 100644 --- a/.claude/skills/formblocks-harness/sub-skills/install-and-boot/SUB-SKILL.md +++ b/.claude/skills/formblocks-harness/sub-skills/install-and-boot/SUB-SKILL.md @@ -30,7 +30,7 @@ Windows uses the `.bat` twins: `formblocks_oc_install.bat`, `formblocks.bat`, `b | `./formblocks build` then `./formblocks serve` | The window built into `frontend/dist`, served by the engine on 8330. | | `./formblocks desktop dev` | The Tauri shell with the frozen engine beside it (freezes once if there is none). | | `./formblocks mcp` | The MCP server on stdio (the formblocks-driving pack). | -| `./formblocks cli [args]` | One catalogue command from the shell. | +| `./formblocks cli [subcommand] [args]` | One catalogue command (`cli run [id] name=value`) or a subcommand of its own (`cli --help` lists them) from the shell. | After booting, `python3 skills/formblocks-harness/scripts/health_probe.py --wait 30` waits for `GET /api/health`. A busy port stops the boot with a sentence. Move the engine with `FORMBLOCKS_PORT` (the window's proxy follows it) instead of stopping a process you did not start; other agents may boot from the same tree. diff --git a/.claude/skills/formblocks-harness/sub-skills/laws-and-logs/SUB-SKILL.md b/.claude/skills/formblocks-harness/sub-skills/laws-and-logs/SUB-SKILL.md index d8e0e83..b8e7cd9 100644 --- a/.claude/skills/formblocks-harness/sub-skills/laws-and-logs/SUB-SKILL.md +++ b/.claude/skills/formblocks-harness/sub-skills/laws-and-logs/SUB-SKILL.md @@ -34,3 +34,14 @@ A version is `x.yy.z` and is bumped by hand at every site in one commit: `src-ta ## Commits Commit only when asked, one coherent unit per commit, staged by path (never `git add -A`). Style: `type(scope): lowercase sentence describing the effect (x.y.z)`, with a body that says what changed, why, and what was run to check it. + +## Skill packs + +The packs in `skills/` are files like any other: hand-made edits, no emoji, no U+2014 or U+2013. They also pass the skill format gates, which `./formblocks agents check` and the skill creator's `scripts/validate_skill.py` both test: + +- `name` at most 64 characters, lower case, digits and hyphens, the same as its folder; no reserved word. +- `description` at most 1024 characters, written to trigger rightly: what the pack is for and when to load it, in the first sentence. A sub-skill's description says when to load that sub-skill. +- No XML or HTML tag in front matter or markdown: write placeholders in square brackets, `[name]`, never in angle brackets. A colon followed by a space inside an unquoted description breaks its YAML; quote the description or rephrase. +- Each pack under 200 files and 30 MB, no archive file, no `README.md` inside a pack. +- Every tool, command and path a pack names exists: check against `./formblocks cli commands` and `./formblocks cli --help`. A command another lane is still adding is named only in a section marked as arriving in that version. +- Never edit `skills/formblocks-driving/references/command-catalogue.md`, `agents/manifest.json`, `.claude/skills` or `.agents/skills` by hand: `./formblocks agents sync` writes them. diff --git a/.claude/skills/formblocks-harness/sub-skills/packages/SUB-SKILL.md b/.claude/skills/formblocks-harness/sub-skills/packages/SUB-SKILL.md new file mode 100644 index 0000000..9914a00 --- /dev/null +++ b/.claude/skills/formblocks-harness/sub-skills/packages/SUB-SKILL.md @@ -0,0 +1,42 @@ +--- +name: packages +description: Maps FormBlocks' engine packages (ldraw, library, mesh, connect, the model in doc and the commands in cmd, then services, automation and routers), what each holds and the order they may depend on each other. Use before changing engine code, when deciding where new code belongs, when an import would point the wrong way, or when looking for the code behind a behaviour. +--- + +# The engine's packages + +The engine in `backend/app/` is a stack of packages. Each may import from the ones below it and never from the ones above, so the LDraw reader can be used without a web server and the connection model without the window. + +## Dependency order, bottom up + +| Order | Package | Holds | May import | +| --- | --- | --- | --- | +| 1 | `ldraw/` | The LDraw reader and writer: lines, headers, colours and the colour table, MPD documents, steps, back-face culling, FormBlocks' own `!FORMBLOCKS` lines. | the standard library only | +| 1 | `core/` | Configuration (ports, the data folder, the dist folder), the guard and the window key, settings, logging. | the standard library only (the guard is plain ASGI middleware) | +| 2 | `library/` | Finding a library folder, the consent-gated fetch and unpack, the manifest, the parts index and its search, categories, the colour table, the file resolver. | the standard library only; no web framework | +| 3 | `mesh/` | A part flattened into one mesh with numpy, cached in the data folder by library update, quality and part; `scene.py`, the one place -Y-up LDraw becomes the window's +Y-up scene. `FORMAT.md` describes the cache's file format. | `ldraw`, `library`, numpy | +| 3 | `connect/` | Connector kinds in `connect/kinds/` (each a module that registers itself; `stud.py` registers `stud` and `anti_stud`, its data in `stud.json`), deriving connectors, the spatial hash, snapping, the grid fallback, the overlap check, `overrides.json`. | `ldraw`, `library`; it walks parts itself and does not import `mesh` | +| 4 | `doc/` | The open model: submodels, steps and placements (`model.py`), the document with its lock, revision, view and undo history (`document.py`, `history.py`, `changes.py`), reading and writing files (`files.py`, `convert.py`), transforms and the JSON views. | `ldraw`, `core` | +| 5 | `cmd/` | The one command catalogue: `registry.py` (`@command`, `Param`, `CommandError`), `runner.py` (runs a command by its kind), `args.py` (shared checks), `fitting.py` (placing through the connection model) and one module per area in `cmd/commands/`. | `doc`, `library`, `connect`, `services` | +| 6 | `services/` | Long-lived holders: `library_host.py` (the one `LibraryService`, its fetch job and index build), `connect_host.py` (the connection service and spatial hashes), `consent.py` (the person's choice for outside agents), the dock's terminal and agent programs. | everything below | +| 7 | `automation/` | The MCP server (`mcp.py`, `forms.py`), the stdio bridge (`stdio.py`) and the command line (`cli.py`), all reaching commands through `cmd`. | everything below | +| 7 | `routers/` | The HTTP routes, each listed once in `ROUTERS` in `main.py`. | everything below | + +`main.py` builds the app and mounts the routers and the built window; `backend/formblocks_engine.py` is the entry for the server, `--selfcheck`, `mcp` and `cli`. + +## Where new code goes + +- A new LDraw line or META command: `ldraw/`, with its rule in `spec/LDRAW.md` first. +- Anything about finding, indexing or searching library files: `library/`. Keep it free of FastAPI and numpy. +- Geometry for drawing: `mesh/`. Geometry for connecting: `connect/`. +- A new connector kind: a module in `connect/kinds/` (`sub-skills/add-connector-kind/SUB-SKILL.md`). +- Anything that changes the model: a command in `cmd/commands/` (`sub-skills/add-command/SUB-SKILL.md`), never a route. +- Something the window must reach that is not a command: a router (`sub-skills/add-router/SUB-SKILL.md`). + +## Logs beside the code + +`ldraw/`, `library/`, `mesh/` and `connect/` each keep a `HASHOUT_LOG.md` of their own; everything else logs in `backend/HASHOUT_LOG.md`. Read the log of the package you change before changing it, and add the reason for your change there in the same commit, newest entry first. + +## Checking the order + +An import that points upward (say `library` importing from `doc`) is a defect even when it works. A quick look: `grep -rn "^from app\." backend/app/[package]` lists what a package imports; every name should be from a package below it in the table. diff --git a/.claude/skills/formblocks-harness/sub-skills/parts-library-and-scratch/SUB-SKILL.md b/.claude/skills/formblocks-harness/sub-skills/parts-library-and-scratch/SUB-SKILL.md new file mode 100644 index 0000000..47252a0 --- /dev/null +++ b/.claude/skills/formblocks-harness/sub-skills/parts-library-and-scratch/SUB-SKILL.md @@ -0,0 +1,55 @@ +--- +name: parts-library-and-scratch +description: Works with the LDraw parts library while developing FormBlocks, covering where the engine finds it, the consent-gated fetch, a scratch copy unpacked outside the tree for checks, throwaway data folders, and the caches the library feeds. Use when a check needs real parts, when library code changes, when a placement or mesh fails for want of a library, or before anything could put library files into the repository. +--- + +# The parts library and the scratch copy + +The parts library is data the person fetches or already has, never part of FormBlocks: not in this repository, an installer, a release or a test folder. It is the work of its many authors under CC BY 2.0 and CC BY 4.0, and the attribution of `spec/LDRAW.md`, "The attribution FormBlocks shows", appears word for word in the About box, beside the consent and in `NOTICE.md`. + +## Where the engine finds it + +`library/locate.py` tries, in order: + +1. The folder in the person's settings (`library_folder` in `settings.json`, set by "Find a folder" on the library card or `./formblocks cli library use FOLDER`). +2. The folder in `FORMBLOCKS_LDRAW_DIR`. +3. The copy fetched into the data folder, `library/` with its `manifest.json`. + +A folder counts when it holds `parts`, `p` and `LDConfig.ldr`. FormBlocks reads a found folder in place and never writes into it. `./formblocks cli library status` (or `library.status`) answers which was used (`source`), the update, whether the index is ready, and every folder tried with what it lacked. + +## The fetch + +- One address only: `https://library.ldraw.org/library/updates/complete.zip`. +- It starts only with the person's consent: the Fetch button on the library card, or `./formblocks cli library fetch --i-consent "ADDRESS LICENCE"` typed by the person. No catalogue command and no MCP tool starts it, and the engine refuses a fetch an agent asks for. +- An agent never runs the fetch and never supplies the consent words, not even on a development machine, and never fetches the archive some other way to get around it. +- After a fetch the engine records the address, size, server date, SHA-256 and release (`spec/LDRAW.md`, "What FormBlocks records"). +- A change to the fetch, the consent text or the attribution starts in `spec/` (`sub-skills/clean-room-and-spec/SUB-SKILL.md`). + +## The scratch copy + +On a check machine the library may already be unpacked outside the tree, as it is at `/tmp/fb-lib/ldraw` here. Point the engine at it for a check, and only for a check: + +```bash +FORMBLOCKS_LDRAW_DIR=/tmp/fb-lib/ldraw FORMBLOCKS_DATA_DIR=/tmp/[folder] FORMBLOCKS_PORT=[port] ./formblocks backend +FORMBLOCKS_LDRAW_DIR=/tmp/fb-lib/ldraw ./formblocks cli run part.connectors part=3001 --settings-dir '' +``` + +- Never copy, commit, quote or bundle anything from it: no part file, no `LDConfig.ldr`, no generated index, no mesh cache, not in a fixture, a sample model's own lines or a screenshot committed to the tree. A model may name a part (`3001.dat`); it never holds the part's lines. +- Give each run a data folder of its own (`FORMBLOCKS_DATA_DIR`, or `--settings-dir ''` for a throwaway one) and a port of its own when other agents run the app, so you neither read their caches nor fight over the engine lock. +- The first use of a library builds its parts index (about 20,000 parts on the 2026-10 update), which takes a while; later runs load the saved index from the data folder. + +## The caches the library feeds + +All in the data folder, keyed so a library update rebuilds only what changed: + +| Cache | Keyed by | Package | +| --- | --- | --- | +| The parts index (`library/` index files) | the library folder and update | `library/` | +| Part meshes (`meshes/`) | library update, quality and part | `mesh/` | +| Derived connectors (`cache/connectors/`) | library release and checksum, part, the overrides met, each kind's version | `connect/` | + +When a check gives an old answer after a change to deriving or flattening, use a new data folder rather than deleting someone else's cache. + +## When there is no library + +Every command that needs a part answers "No LDraw parts library is installed". That is the right answer on a clean machine; do not work around it in code. Checks that need no parts (the selfcheck, `scripts/mcp_smoke.py`, which adds and undoes a step) still run. diff --git a/.claude/skills/formblocks-harness/sub-skills/verify/SUB-SKILL.md b/.claude/skills/formblocks-harness/sub-skills/verify/SUB-SKILL.md index 351b58a..64efa48 100644 --- a/.claude/skills/formblocks-harness/sub-skills/verify/SUB-SKILL.md +++ b/.claude/skills/formblocks-harness/sub-skills/verify/SUB-SKILL.md @@ -16,8 +16,20 @@ The owner forbids self-written tests until asked: no test file, harness, fixture 5. Window: from `frontend/`, `npm run typecheck` and `npm run build`. For a change to the window also reload it under 4x CPU and network throttling in a real browser and watch the first frame (law 2); say what you saw, or say it was not run. 6. MCP: `python3 skills/formblocks-harness/scripts/mcp_smoke.py --root .` lists the tools, adds a step to the model, undoes it and checks the model is back where it was. 7. Catalogue drift: `./formblocks agents sync --check` exits 1 when `agents/manifest.json`, the generated references or the skill mirrors no longer match the catalogue and the `skills/` folder. Run `./formblocks agents sync` after adding a command or a sub-skill, then check again. -8. The contract: `python3 -I /tools/formapp.py validate .` from FormAnything's kit reports every MUST clause that failed with its file and line, and exits 0 when none did. A SHOULD that does not hold is reported and stops nothing. -9. Text: no U+2014 in markdown and no emoji in any text file; shell scripts parse with `bash -n` and keep their executable bit. +8. The contract: `python3 -I [kit]/tools/formapp.py validate .`, where `[kit]` is the `kit` folder of a FormAnything checkout, reports every MUST clause that failed with its file and line and exits 1 when one did, 0 when none did. A SHOULD that does not hold, and the clauses left for an owner to review, are listed and stop nothing. A change to `skills/` fails clause 6.11 until `./formblocks agents sync` has rewritten `agents/manifest.json`. +9. Text: no U+2014 or U+2013 anywhere and no emoji in any text file; shell scripts parse with `bash -n` and keep their executable bit. +10. The skill packs: `./formblocks agents check` runs the same gate as `agents sync --check` (mirrors, pack format, MCP configs, manifest, the command reference, the dock module). For a change inside `skills/`, also run the skill creator's validator on the pack (`sub-skills/laws-and-logs/SUB-SKILL.md`, "Skill packs"). + +## Looking at the window + +Every change to the window is looked at, not assumed. A browser runs headless here: `/usr/bin/google-chrome` with Playwright (the Python package, or `npx playwright`). + +1. Serve the window on ports of your own when others may be running the app: build it into a folder outside the tree (`npx vite build --outDir /tmp/[folder]` from `frontend/`), then start the engine with `FORMBLOCKS_DIST=/tmp/[folder]`, `FORMBLOCKS_PORT` set to a free port and a throwaway `FORMBLOCKS_DATA_DIR`. With the ports free, `./formblocks` (dev) or `./formblocks build` then `./formblocks serve` do the same on 5330 and 8330. +2. The served page hands over the window key once per engine start. Open it with the browser first; a `curl` of the page before that takes the key, and the window then answers "A valid X-FormBlocks-Token is required". +3. Launch Chrome with `--use-angle=swiftshader --enable-unsafe-swiftshader` when a WebGL context fails. +4. Take a screenshot into `/tmp` and read it. Click and type through Playwright for anything you changed. +5. Law 2, for real: through the DevTools protocol set `Emulation.setCPUThrottlingRate` to 4 and slow the network with `Network.emulateNetworkConditions`, add a `PerformanceObserver` on `layout-shift` before the page loads, hard-reload, and add up the entries without recent input. A score above 0 on load or on an interaction you built is a defect to fix. +6. Scripts and screenshots stay under `/tmp`, never in the repository. Stop only the processes you started, by their process id. ## What CI runs diff --git a/CHANGELOG.md b/CHANGELOG.md index b18d36c..bf691db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## v0.3.0 · 2026-11-26 + +The third version is the window: a 3D view of the model, the parts and colour palettes, and the panels around them, so a model can now be built with the mouse and the keyboard as well as from the command line and by agents. The app has its icons, drawn by the owner. The repository is private until 13 December 2026. + +- The first start: with no parts library the viewport shows the library card, where you type the folder of a library you already have or fetch the official one after reading its address, size, licence and authors; nothing is downloaded until you press Fetch. Once a library is in use the palettes fill and a start card offers a new model, open and your recent files. +- The 3D view (`frontend/src/view/`): the model drawn from the engine's meshes, one batch per part and colour, with edge and optional lines, a ground grid of studs, orbit, pan and zoom with the mouse or a trackpad, seven preset views and fit, picking and box selection, earlier steps faded and later ones hidden, and the parts outside a submodel you are editing dimmed. +- The parts palette: search on every keystroke with part 3001 first for "brick 2 x 4", categories in your own order with stars, Favourites, Recent (the parts you placed) and Hidden, three thumbnail sizes drawn once, printed parts on a switch, and a details line for the part you point at. The colour palette: the current colour, recent and favourite colours, every colour of the library by finish with a hue row and a name search; the current and recent colours are kept by the engine. +- Placing: click a part, and a half-transparent ghost follows the pointer and seats on studs as the engine works it out, with small marks on the studs it would join; R, T and Y turn it, a click or Space drops it, another copy waits until Esc. Placed parts are selected, recoloured from the palette, nudged with the arrows, turned, hidden and shown, copied one grid step aside with Ctrl+D, deleted, undone and redone. +- Around the view: the step strip with a chip per step and New Step, the Model and Steps tabs (the tree in step order with its submodels, and each step's parts), the details panel with typed positions, the status bar with the selection, the step, the ghost's place in LDU and the Snap, grid and Overlap switches, a menu and command palette listing every command with its key, preferences, the About box with the library's attribution, and the right column's panels resized by dragging. Files: new, open, save and save as `.fblk`, `.ldr` or `.mpd`, asking before unsaved changes are lost. +- The engine for the window: `POST /api/place/preview`, `/drag` and `/pick` (reads that need the window key and never change the model), `part.place_at_ray`, `part.move_at_ray`, `part.duplicate_at_ray` and `part.pick`, picking on real triangles, the model tree, model information and the parts list as CSV (`model.info`, `model.set_info`, `parts.list`, `parts.list_save`, `cli parts list`), `snap.set`, `grid.step`, `overlap.set`, `colours.used` and `colours.current`, each placement's matrix in the view's axes, an empty search in a list answering that list, and the settings, selection and step announced on the live channel. A dragged selection now seats by its lowest part and never ends below the ground. The frozen engine carries the data files it reads. +- The specification was brought in line with what was built, one decision each: pointer rays in the view's +Y-up axes, `parts.list` and `parts.list_save` kept as named, the hue families of `colours.list`, outside agents asked before each change unless always allowed, `part.connectors` in place of a `cli connectors` command, no toolbar row, Ctrl+D one grid step aside until the window drags, quarter turns only with the fine angle later, the parts palette without a colour, and the drag rule above. +- Not in this version: dragging placed parts with the pointer (the engine answers it, the window does not use it yet), the stamp, pivot, brush and sampler tools, turns finer than a quarter turn, the "used in this model" colour row, the model information panel and the parts list in the window, a picture of the view, the sizes of the side columns by dragging, and keys you can change. +- Run for this version, on Linux with the official 2026-10 library unpacked by hand: `./formblocks doctor`; the engine on 8346 and the window on 5346 in headless Chrome; the first start without a library, then the library chosen on its card; a house of 25 parts built with the pointer (three courses of 2 by 4 and 2 by 2 bricks with overlapping joints and a door, a 6 by 8 plate and a roof of slopes), recoloured, four steps walked, saved as `.fblk`, a new model, the file reopened with the same 25 parts and 4 steps, and the sample car opened, each looked at from two or three views; layout shift recorded at 0 with the CPU slowed 4 times and a slow network over a hard reload and every interaction; a freeze of the engine with its self-check; the MCP smoke script; `agents sync` and `agents check`; the skill gate on both packs (no failure and no warning); the Form App Contract check (0 MUST failures); and the registry's eight checks. +- Not run: a desktop build (the desktop toolkit is missing here, and no Tauri build ran), anything on a graphics card (frame times seen here are a software renderer's), the real download of the library (only the person may consent to it), any `.bat` script, anything on macOS or Windows, and the check workflow. + ## v0.2.0 · 2026-11-26 The second version is the engine: the parts library, part meshes, connections and snapping, and a model you can build, change, undo and save, from the command line and from agents over MCP. The window is still the starter's shell. The repository is private until 13 December 2026. diff --git a/NOTICE.md b/NOTICE.md index c492cb3..03c2d9d 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -27,6 +27,8 @@ FormBlocks was made from FormAnything's app template, which is FormCAD's skeleto | @fontsource/inter 5.3.0, @fontsource/jetbrains-mono 5.3.0 | OFL-1.1 (fonts), MIT (package) | `frontend/package.json` | | @tauri-apps/api 2.12.4 | Apache-2.0 OR MIT | `frontend/package.json` | | @xterm/xterm 6.0.0, @xterm/addon-fit 0.11.0 | MIT, Copyright (c) 2017-2019 The xterm.js authors and others; the agent dock's terminal, loaded only when a tab opens | `frontend/package.json` | +| three 0.186.1 | MIT, Copyright 2010-2026 three.js authors; the 3D viewport and the part thumbnails | `frontend/package.json`, `frontend/src/view/` | +| @types/three 0.186.0 | MIT, from the DefinitelyTyped project; type declarations for three, development only and erased by the build | `frontend/package.json` (development) | | @tauri-apps/cli 2.11.4, typescript 7.0.2, vite 8.3.5 | Apache-2.0 OR MIT, Apache-2.0, MIT | build tools, not shipped | ### Engine (backend) @@ -45,10 +47,17 @@ FormBlocks was made from FormAnything's app template, which is FormCAD's skeleto | Work | Licence | Where | | --- | --- | --- | | tauri 2, tauri-plugin-shell, tauri-plugin-dialog, tauri-plugin-single-instance, regex, serde, serde_json | MIT OR Apache-2.0 | `src-tauri/Cargo.toml`, exact versions in `src-tauri/Cargo.lock` | +| tauri-plugin-dialog 2.8.4 | MIT OR Apache-2.0; the desktop's file dialogs for open, save and choosing a library folder, allowed to the window by `dialog:allow-open` and `dialog:allow-save` and called through `@tauri-apps/api` without its own JavaScript package | `src-tauri/Cargo.toml`, `src-tauri/capabilities/default.json`, `frontend/src/io/dialog.ts` | | tauri-build 2.7.4 | MIT OR Apache-2.0; the shell's build script, not shipped | `src-tauri/Cargo.toml` (build dependency), exact version in `src-tauri/Cargo.lock` | | windows-sys 0.61.2 (Windows) | MIT OR Apache-2.0 | `src-tauri/Cargo.toml` | | objc2, objc2-app-kit (macOS) | MIT OR Apache-2.0 OR Zlib | `src-tauri/Cargo.toml` | +### The app's own art + +| Work | Licence | Where | +| --- | --- | --- | +| The FormBlocks icon and mark, drawn by the owner: the six originals as sent, and every size made from them by resampling, nothing redrawn | the owner's own work, Copyright 2026 NodeAgentc, Inc. | `assets/formblocks_icon.png`, `assets/app-icon/`, `src-tauri/icons/`, `frontend/public/favicon.png`, `favicon.ico`, `apple-touch-icon.png`, `mark.png` | + ### Data fetched by the person, never bundled | Work | Licence | Where | @@ -61,4 +70,4 @@ FormBlocks shows this attribution in the About box and beside the download conse ## Trademarks -The names of other companies and their products belong to their owners. LEGO is a trademark of the LEGO Group; BrickLink and Studio are trademarks of their owner; LDraw is a trademark owned and licensed by the Estate of James Jessiman. FormBlocks is an independent project and is not affiliated with, sponsored by or endorsed by any of them. These names appear only in this repository's documents, to say what FormBlocks works with or stands in for, never in its code, commands or window. +LEGO, BrickLink and BrickLink Studio are either registered trademarks or trademarks of the LEGO Group in the United States and/or other countries. LDraw is a trademark owned and licensed by the Estate of James Jessiman. FormBlocks is not affiliated with or endorsed by the LEGO Group or by LDraw.org; the names describe file formats and compatibility only. They appear only in this repository's documents, never in its code, commands or window. diff --git a/README.md b/README.md index 437278c..4a963cc 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,7 @@ +

+ FormBlocks icon: stacked bricks on a studded plate, with the outline of the next brick +

+

FormBlocks

@@ -7,7 +11,7 @@

- version 0.2.0 + version 0.3.0 TypeScript Python Tauri 2 @@ -38,7 +42,7 @@ FormBlocks is an open brick building app. Its parts are the LDraw Parts Library, > [!IMPORTANT] -> **Status:** pre-release, and early. What works today is the engine's side of the parts library: finding or fetching the library, searching it, its categories and colours, and a mesh of any part, from the command line and the engine's routes. There is no 3D viewport yet, so nothing can be placed, snapped or coloured in the window, and the window does not show the parts palette yet. The plan follows the specification's order: the library, then the model and its commands, the viewport and the palettes, connections and snapping, and steps and the parts list. +> **Status:** pre-release, and early. In the window you can choose or fetch the parts library, find parts in the palette, place them with the pointer in the 3D view where they seat on studs, turn and colour them, select, nudge, hide, add and walk building steps, read the model tree and the details of a part, and save and open `.fblk`, `.ldr` and `.mpd` files; agents do the same through MCP and the command line. Not yet in the window: dragging placed parts with the pointer, the stamp, pivot, brush and sampler tools, turns finer than a quarter turn, the model information panel and the parts list (both answered by the engine already), and saving a picture of the view. ## Quick start @@ -59,7 +63,7 @@ On Windows use `formblocks_oc_install.bat` and `formblocks.bat`. `./formblocks d | Window preview | http://localhost:5331 | `npm run preview` in `frontend/` after a build | | Engine | http://127.0.0.1:8330 | `FORMBLOCKS_PORT` moves it; `./formblocks backend` alone | -The desktop app: `./formblocks install-desktop`, then `./formblocks desktop dev` to run it or `./build_app` to build and install it. The bundle needs the app's icons in `src-tauri/icons`, which this version does not carry yet. +The desktop app: `./formblocks install-desktop`, then `./formblocks desktop dev` to run it or `./build_app` to build and install it. The bundle takes the app's icons from `src-tauri/icons`, made from the owner's art in `assets/`. ## The parts library @@ -124,10 +128,10 @@ Agents: [`CLAUDE.md`](CLAUDE.md), [`AGENTS.md`](AGENTS.md) · Contributing: [`CO ## Status -Pre-release. It is made to run from source on macOS, Linux and Windows, and has been run from source on Linux only; desktop builds come from formcompiler once the app has its icons, which are not drawn yet. The parts library side has been run against the full official library of release 2026-10; the window is still the template's shell, with no parts palette and no viewport. Releases are made by the family's compiler from [`apps/formblocks.json`](apps/formblocks.json), never by this repository. +Pre-release. It is made to run from source on macOS, Linux and Windows, and has been run from source on Linux only; desktop builds come from formcompiler; the app has its icons, and no desktop build has been run yet. The engine and the window have been run against the full official library of release 2026-10, the window in a headless browser with software rendering, so how fast it draws on a real graphics card is not measured. Releases are made by the family's compiler from [`apps/formblocks.json`](apps/formblocks.json), never by this repository. ## Licensing FormBlocks is licensed under the Apache License 2.0 ([LICENSE](LICENSE), SPDX `Apache-2.0`). Copyright 2026 NodeAgentc, Inc. Every dependency and every family source is listed in [NOTICE.md](NOTICE.md). The LDraw Parts Library is not part of FormBlocks: it is the work of its many authors under CC BY 2.0 and CC BY 4.0, fetched by you, and credited in [NOTICE.md](NOTICE.md) and in the app. -The names of other companies and their products belong to their owners. LEGO is a trademark of the LEGO Group; BrickLink and Studio are trademarks of their owner; LDraw is a trademark owned and licensed by the Estate of James Jessiman. FormBlocks is an independent project and is not affiliated with, sponsored by or endorsed by any of them; the names are used only to say what FormBlocks works with or stands in for. +LEGO, BrickLink and BrickLink Studio are either registered trademarks or trademarks of the LEGO Group in the United States and/or other countries. LDraw is a trademark owned and licensed by the Estate of James Jessiman. FormBlocks is not affiliated with or endorsed by the LEGO Group or by LDraw.org; the names describe file formats and compatibility only. diff --git a/agents/manifest.json b/agents/manifest.json index 0407cb0..e87db2c 100644 --- a/agents/manifest.json +++ b/agents/manifest.json @@ -10,8 +10,12 @@ "formblocks_redo", "formblocks_status", "formblocks_undo", + "cmd_colours_current", "cmd_colours_list", + "cmd_colours_used", + "cmd_grid_step", "cmd_library_status", + "cmd_model_info", "cmd_model_insert", "cmd_model_new", "cmd_model_open", @@ -19,20 +23,28 @@ "cmd_model_report", "cmd_model_save", "cmd_model_save_as", + "cmd_model_set_info", "cmd_model_tree", "cmd_overlap_check", + "cmd_overlap_set", "cmd_part_connectors", "cmd_part_delete", "cmd_part_duplicate", + "cmd_part_duplicate_at_ray", "cmd_part_fit", "cmd_part_hide", "cmd_part_hide_others", "cmd_part_move", + "cmd_part_move_at_ray", + "cmd_part_pick", "cmd_part_place", + "cmd_part_place_at_ray", "cmd_part_recolour", "cmd_part_rotate", "cmd_part_set_transform", "cmd_part_show", + "cmd_parts_list", + "cmd_parts_list_save", "cmd_parts_search", "cmd_parts_show", "cmd_select_add", @@ -44,6 +56,7 @@ "cmd_select_invert", "cmd_select_remove", "cmd_select_set", + "cmd_snap_set", "cmd_step_break_after", "cmd_step_delete", "cmd_step_goto", @@ -63,14 +76,21 @@ "formblocks_get_doc", "formblocks_list_commands", "formblocks_status", + "cmd_colours_current", "cmd_colours_list", + "cmd_colours_used", + "cmd_grid_step", "cmd_library_status", + "cmd_model_info", "cmd_model_recent", "cmd_model_report", "cmd_model_tree", "cmd_overlap_check", + "cmd_overlap_set", "cmd_part_connectors", "cmd_part_fit", + "cmd_part_pick", + "cmd_parts_list", "cmd_parts_search", "cmd_parts_show", "cmd_select_add", @@ -82,6 +102,7 @@ "cmd_select_invert", "cmd_select_remove", "cmd_select_set", + "cmd_snap_set", "cmd_step_goto", "cmd_step_list", "cmd_submodel_enter", @@ -97,16 +118,21 @@ "cmd_model_open", "cmd_model_save", "cmd_model_save_as", + "cmd_model_set_info", "cmd_part_delete", "cmd_part_duplicate", + "cmd_part_duplicate_at_ray", "cmd_part_hide", "cmd_part_hide_others", "cmd_part_move", + "cmd_part_move_at_ray", "cmd_part_place", + "cmd_part_place_at_ray", "cmd_part_recolour", "cmd_part_rotate", "cmd_part_set_transform", "cmd_part_show", + "cmd_parts_list_save", "cmd_step_break_after", "cmd_step_delete", "cmd_step_move_parts", @@ -127,18 +153,34 @@ "name": "formblocks-driving", "sub_skills": [ "agent-dock", - "building-models", - "connect-and-status" + "building-in-order", + "changing-parts", + "checking-a-model", + "colours", + "connect-and-status", + "files", + "finding-parts", + "parts-library", + "placing-and-snapping", + "selection", + "steps", + "submodels", + "working-with-the-person" ] }, { "name": "formblocks-harness", "sub_skills": [ "add-command", + "add-connector-kind", "add-pane", "add-router", + "clean-room-and-spec", + "freeze-and-ship", "install-and-boot", "laws-and-logs", + "packages", + "parts-library-and-scratch", "verify" ] } diff --git a/assets/app-icon/formblocks-256.png b/assets/app-icon/formblocks-256.png new file mode 100644 index 0000000..5e2019f Binary files /dev/null and b/assets/app-icon/formblocks-256.png differ diff --git a/assets/app-icon/formblocks_dark_transparent_noshadow.png b/assets/app-icon/formblocks_dark_transparent_noshadow.png new file mode 100644 index 0000000..cc6fdab Binary files /dev/null and b/assets/app-icon/formblocks_dark_transparent_noshadow.png differ diff --git a/assets/app-icon/formblocks_dark_transparent_shadow.png b/assets/app-icon/formblocks_dark_transparent_shadow.png new file mode 100644 index 0000000..c628ad1 Binary files /dev/null and b/assets/app-icon/formblocks_dark_transparent_shadow.png differ diff --git a/assets/app-icon/formblocks_icon_dark.png b/assets/app-icon/formblocks_icon_dark.png new file mode 100644 index 0000000..2ad9e94 Binary files /dev/null and b/assets/app-icon/formblocks_icon_dark.png differ diff --git a/assets/app-icon/formblocks_icon_light.png b/assets/app-icon/formblocks_icon_light.png new file mode 100644 index 0000000..34c3184 Binary files /dev/null and b/assets/app-icon/formblocks_icon_light.png differ diff --git a/assets/app-icon/formblocks_light_transparent_noshadow.png b/assets/app-icon/formblocks_light_transparent_noshadow.png new file mode 100644 index 0000000..4349514 Binary files /dev/null and b/assets/app-icon/formblocks_light_transparent_noshadow.png differ diff --git a/assets/app-icon/formblocks_light_transparent_shadow.png b/assets/app-icon/formblocks_light_transparent_shadow.png new file mode 100644 index 0000000..c392d54 Binary files /dev/null and b/assets/app-icon/formblocks_light_transparent_shadow.png differ diff --git a/assets/formblocks_icon.png b/assets/formblocks_icon.png new file mode 100644 index 0000000..2ad9e94 Binary files /dev/null and b/assets/formblocks_icon.png differ diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 46ff17c..8b1aae9 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2,6 +2,134 @@ Living record of decisions and removed context for the engine, newest first. Read before editing. +## The drag route's copy switch no longer shadows the model's own method · 0.3.0 (app/routers/place.py) + +The engine's self-check printed pydantic's warning that the field `copy` of `DragBody` shadows `BaseModel.copy`. The field is now `copies`, read from the same JSON key `copy` through its alias, so the route's request is unchanged and the warning is gone. Checked against an engine on 8346: with `copy: true` the held copy of a brick on the ground seated on the brick itself (8 pairs, y = -48), with `copy: false` the brick moved and stayed on the ground; `--selfcheck` printed no warning. + +## colours.list names its hue families as the answer writes them · 0.3.0 (app/cmd/commands/library.py, ../spec/SPEC.md) + +The command's `hue` parameter said "a hue family, such as red or blue", but each colour's `hue` field, and the only values the filter matches, are the nine plural families of `library/colours.py` (`reds` to `greys`), so an agent that followed the wording got no colours and no reason. The parameter now names the nine families and `all`, and any other value is refused with the list, as `group` already was; `SPEC.md` 3.4's row names the parameters as built (`group` for the finish group, `hue` in the plural form of 3.1's row of hue families). Checked against an engine on 8346: `hue=red` refused naming the families, `hue=reds` answered 29 colours. + +## A drag is led by the lowest moving part and never ends below the ground · 0.3.0 (app/cmd/placing.py) + +This corrects the last sentences of "Dragging a selection: POST /api/place/drag and part.move_at_ray", which left the question for the window's design: grabbing the top brick of a stack and pointing at the ground seated the top brick on the ground and carried the lower one 24 LDU under it. `spec/CONNECTIONS.md`, "Moving several parts", now decides it: `drag` finds the lead, the moving placement whose placed bounding box reaches lowest after any turn of the move (the grabbed one when it is within 0.5 LDU of that, so its held connector is kept), snaps the lead from the ray, and moves the rest rigidly with it; then, if any moved box still reaches below y = 0, the whole move is lifted by that depth. The turn sent during a drag is the grabbed part's, so it is applied to the lead as the same rigid turn. With a lift the overlap test runs for every moved part, the lead included. The preview's answer names `lead` and `lifted`, and its top-level pose is the lead's seat. The same rule serves `part.duplicate_at_ray`. Checked against an engine on 8346 with two stacked 3001 and a third beside them: the stack dragged by its top to the ground stood at y = -24 and -48 with p1 leading; pointed at the third brick, p1 seated on it with 8 pairs at -48 and the top at -72; dragged by its bottom it moved as before; with a quarter turn sent the stack turned whole and stayed on the ground; a tipped pair on one level was led by the grabbed brick. + +## Every placement carries its scene matrix · 0.3.0 (app/doc/views.py, app/mesh/scene.py) + +FormBlocks' rule 5 keeps the one conversion between LDraw's axes and the scene's in `app/mesh/scene.py`, but the document's placements carried only LDraw's position and matrix, so the viewport wrote `C M C` out again in `view/axes.ts` and reported it. `placement_json`, which `GET /api/doc`, every `changes` answer and every part command use, now adds `matrix`: the placement's 4 by 4 transform in the scene's axes, 16 numbers row by row, made by `scene_matrix` beside `placement_to_scene` in the mesh package and rounded as the preview's rotation is, so the window composes matrices and converts nothing. The LDraw `position` and `rotation` stay, since every number a person or an agent reads is in LDraw's axes (`SPEC.md` 0.2). It costs about 14 microseconds a placement, 28 ms for a full read of 2,000. Checked in process: a quarter turn at (10, -24, 5) gives rows (0, 0, -1, 10), (0, 1, 0, 24), (1, 0, 0, -5), the same as the viewport's own formula. + +## colours.used and colours.current · 0.3.0 (app/cmd/commands/colours.py) + +`SPEC.md` 3.1 has a row of the colours used in the open model, most used first, and 3.4 names `colours.used` for it and `colours.current` for the current colour. `colours.used` counts the parts of the whole model as built, through every use with colour 16 taken from the use (`partslist.walk`, as the parts list counts), then adds at a count of 0 any colour a placement carries that the walk did not reach (an unused submodel's parts, a use's own colour); 16 and 24 are never listed (3.2). Each row is the number, the library's name and value in the field names `colours.list` uses, the count, and `known`, false for a number the library does not define, which 3.3 still shows in the row by number. `colours.current` writes the current colour and puts it at the front of the recent colours in one settings update; like the three switches it is of kind `view`, a setting that changes no model and makes no undo step. Colour definitions written inside a model file (3.3) are not read into the document at 0.3.0, so they are not listed. Checked from the command line on the sample car with a red 3001 added: Red 28, Black 15, Light Grey 8, Trans Yellow 6 and three more; colour 16 refused naming the parameter. + +## Placing a part puts it at the front of the recent parts · 0.3.0 (app/cmd/commands/part.py) + +`SPEC.md` 2.4: Recent lists the last thirty parts placed, newest first. The engine never wrote `recent_parts`, so the parts palette pushed a part when it was picked, which counts a pick that is cancelled and misses a part an agent or the command line places. `put`, the one tail of `part.place` and `part.place_at_ray`, now puts the library part's number (as the index writes it, `3001`) at the front of the list, without its repeat, kept to thirty; a use of a submodel is not a library part and is not listed. The settings store announces the change, so the palette's Recent follows a placement made anywhere. It is a setting, so undoing the placement leaves it listed. Checked from the command line: `part.place part=3001` wrote `recent_parts: ["3001"]`. + +## The current colour and the recent colours are settings · 0.3.0 (app/core/settings.py) + +`SPEC.md` 3.4 has `colours.current` as a setting, and the colour palette's Recent row belongs to the person like the parts lists, but the engine kept neither, so the window held the current colour in its own local storage and Recent lived for one session. `current_colour` (first value 4, Red, the window's first value) is any colour number of 0 or more except 16 and 24, which are not colours of their own (3.2); a number the library does not define is allowed, as a model may use one (3.3). `recent_colours` keeps at most twelve numbers, the palette's own count, each once. Both are announced on the live channel like every setting. Checked in process: 16, `true` and thirteen recent numbers refused with a sentence, a repeated number kept once. + +## Duplicating under the pointer: copy in the drag and part.duplicate_at_ray · 0.3.0 (app/cmd/placing.py, app/routers/place.py, app/cmd/commands/pointer.py) + +Ctrl+D (`SPEC.md` 5.4) holds copies of the selection as a ghost under the pointer, dropped like any ghost. That is the drag with one difference: the originals stay, so they are not left out of the pick, the seat or the overlap test, and a copy may seat on its own original. `POST /api/place/drag` takes `copy: true` for that preview, and `part.duplicate_at_ray` drops the copies at the poses it answers, with the originals' colours, unhidden, in the step shown, as the new selection and as one undo step "Duplicate n parts"; with the overlap check on, a copy that would overlap anything, its original included, refuses the whole drop. `part.duplicate` with an offset is unchanged for exact copies. Checked against an engine on 8344: copies of a two-brick stack dropped beside it at x = 200 with their colours and became the selection; with the check on, copies held by the upper brick over the stack were refused naming p2 and 23 LDU, and copies held by the lower brick stacked on top at y = -72 and -96. + +## A project file keeps the snap switch and grid step · 0.3.0 (app/cmd/commands/model.py, app/doc/convert.py) + +`SPEC.md` 7.6 stores the snap and grid settings with the model in its project file and in preferences as the default for new models. A `.fblk` save now writes `0 !FORMBLOCKS SNAP ` from the current settings instead of the line the file was read with, and opening a project whose line is well formed sets the snap switch and grid step to it, which the settings store announces; a model without the line (a plain LDraw file, a new model) leaves the person's settings as they are, which is the default of 7.6. The settings stay the one source of the switches while a model is open, so there is no second copy to disagree; the line is only their record in the file. Checked against an engine on 8344: with snapping off at the Plate step a save wrote `SNAP OFF PLATE`, and after setting snapping on at the Stud step, opening that file put it back to off and plate; opening the sample car changed nothing. + +## snap.set, grid.step and overlap.set · 0.3.0 (app/cmd/commands/switches.py) + +The toolbar's three switches (`SPEC.md` 7.6 and 8.4, keys S, G and O) had only the settings route behind them, so an agent could not turn snapping off for a run of exact placements or turn the overlap check on to confirm a build. Each command writes the person's setting through the settings store, which announces the change on the live channel, and answers the three values. The specification gives them the kind "settings", which the catalogue does not have; they are registered as `view`, the kind that changes no model and makes no undo step, and so, like the selection commands, they run for an outside agent without a question; a setting changes no file and is undone by setting it back. A wrong step is refused naming the parameter. Checked against an engine on 8344: `grid.step PLATE` set `plate`, `huge` was refused with the three steps named, `overlap.set` and `snap.set` answered the values. + +## model.set_info · 0.3.0 (app/cmd/commands/info.py, app/services/model_info.py) + +The About tab lets the person edit the model's title, author and licence (`SPEC.md` 13.1, `model.set_info` in 13.5), and the window needs a command behind its fields. Each given field changes the main model's header in the model table, so the next save writes it and one undo takes it back: the title is the header's title record, never left empty, its runs of white space made one space; the author is the `0 Author:` line, put after `0 Name:` when the header has none, and an empty author keeps the line empty, as FormBlocks writes on every model; the licence is removed when empty, or written `0 !LICENSE Licensed under ` for one of the seven Creative Commons licences listed (case ignored), which is the "left empty or set to a Creative Commons licence" of 13.1. The library's own licence lines end in ": see CAreadme.txt", which names the library's readme and is wrong for a person's model, so it is left off. The model's name is its main block's name and is changed with `submodel.rename`, which keeps every reference right. `model.info` now shows the licence without the "Licensed under" words. Checked against an engine on 8344: title, author and CC BY-SA 4.0 set in one step and written as the first four lines of an `.ldr` export, GPL refused with the choices, the licence cleared, and one undo brought it back. + +## cli parts list · 0.3.0 (app/automation/cli.py, app/services/model_info.py) + +`SPEC.md` 13.5 has `./formblocks cli parts list model.ldr --csv out.csv` read a model file and write its parts list without opening a window. It reads the file here, never through the engine, because the open model must not change and reading a file is the person's own act; it waits for the parts index once so descriptions are filled, prints the rows as JSON, or with `--csv OUT` writes the file (`--tab` for tab separated, `--by-colour` to sort by colour) through the same safe write a save uses and prints what it wrote. Both paths are read from the folder the person ran the command in. `model_info.rows_for` is the counting and labelling of `parts_rows` for any model and submodel, which the command line needed without a document. Checked from `/tmp` with the 2026-10 library: the sample car wrote 32 rows and 61 parts, the same file `parts.list_save` wrote; a missing file exit 1 with the sentence, no file exit 2. + +## Dragging a selection: POST /api/place/drag and part.move_at_ray · 0.3.0 (app/cmd/placing.py, app/routers/place.py, app/cmd/commands/pointer.py) + +`SPEC.md` 5.1 drags the whole selection by the part pressed on, under the ghost's rules, and the moved parts never seat on each other and keep their places relative to one another. `placing.drag` takes the grabbed placement (`grab`), its part and its own rotation unless the window sends a turned one, and runs the preview's `attempt` with every moving placement left out of the pick, the seat and the overlap test; the rigid move that takes the grabbed part from its old pose to the new one is then applied to every other moving placement, so a turn made during the drag turns the whole selection about the held connector too. The moving set is `ids` when given, else the selection when the grabbed part is in it, else the grabbed part alone, which is what pressing on an unselected part does. The overlap check, when on, tests the grabbed part through the fit and every other moved part against the parts that stay, leaving out pairs joined through mated connectors; any overlap blocks. `POST /api/place/drag` answers the preview's fields for the grabbed part plus `moves`, the new pose of each moving placement in scene and LDraw axes, without changing anything; `part.move_at_ray` commits the same moves as one undo step labelled "Move n parts" and refuses a blocked place or a ray at the sky. A use of a submodel cannot be the grabbed part yet, since it has no connectors to seat by; it moves with `part.move`. Only the grabbed part seats: grabbing the top brick of a stack and pointing at the ground seats that brick on the ground and carries the bricks under it below the ground plane, as a rigid drag must; whether the lowest part of a selection should lead instead is left for the window's design. Checked against an engine on 8344: two stacked bricks dragged by the lower onto a third seated 8 pairs with the upper 24 LDU above; with the overlap check on, dragging the pair by the upper onto a floating brick was refused naming p4 and 23 LDU; a ray at the sky was refused. + +## A use of a submodel is picked on its parts' triangles · 0.3.0 (app/services/picking.py, app/services/warmer.py) + +A use has no part triangles of its own, so the pick passed through it and the ghost fell to the ground behind it. The pick's items are now the submodel's library placements as before plus, for each use, every library part inside it at its world place (`partslist.walk` from the use's position, turn and colour, cut before it could reach the submodel being edited again), each item answering for the use's id. A hit on any of them is a hit on the use, which is what the person pointed at; the ghost then rests on it at the grid, since uses offer no connectors in 0.x. The warmer loads the triangles of exactly the items the boxes hold, so the parts inside uses are warm too. Checked against an engine on 8344: two stacked 3001 bricks packed into `Tower` and a second use placed at x = 200; a ray down at x = 205 picked the second use at scene y = 24, and a preview there rested a 3001 on it on the grid. + +## part.fit's ray meets real triangles too · 0.3.0 (app/cmd/fitting.py, app/services/picking.py) + +`part.fit` with `origin` and `direction` still met placement boxes through the connection lane's `first_hit`, so an agent asking where a ray puts a part could get another answer than the window's preview for the same ray. It now asks `picking.pick_ldraw`, which turns the LDraw ray into scene axes with the mesh package's conversion, picks on triangles and gives the hit back as a connection `Hit` in LDraw axes; the hidden and moving placements are passed through as before. Checked against an engine on 8344 with a 3001 at (0, -24, 0): rays straight down at (5, 3) and (25, 3) seat on it with 8 and 6 pairs, one at (300, 3) seats on the ground lattice, and one pointing up answers no position. + +## A window that attaches is told where things stand · 0.3.0 (app/routers/live.py) + +On attach the live channel sent only the revision, so a window that reconnected after the engine restarted, or a second window, had to read the settings and the fetch job to catch up. It now sends, in this order, the `doc` revision, the current `selection`, the `step` shown with the editing path, the `settings` with an empty `changed` list, and, only while a library fetch runs, a `library` fetch progress message in the shape the fetch itself sends, so the window's progress bar picks up mid-fetch. Nothing is sent about a library that is not fetching, since the window reads the library's status when the channel opens and a message of a new stage would only make it read again. Checked over the websocket against an engine on 8344: the four messages arrived in order with the car's revision, an empty selection, step 8 of 8 and the settings. + +## Selection and step changes are announced as such · 0.3.0 (app/doc/document.py) + +A selection made in the tree, by an agent or by the command line moved the revision, and the window then had to read the changes to learn what was selected. After each revision the document now also announces `{"type": "selection", "selection", "count", "revision"}` when the selection differs from the last one it announced, and `{"type": "step", "submodel", "step", "of", "editing", "revision"}` when the step shown, the submodel being edited or its step count differs, so the status bar, the tree's highlight and the step controls follow at once and the `doc` event still tells the window when placements changed. Both are sent after the `doc` event of the same revision. The first revision after a start announces both, since nothing was told yet. Checked over the websocket against an engine on 8344: `select.set p3 p4`, `step.goto 3`, `step.goto 8` and `select.clear` each gave their `doc` event and one selection or step event with the new values. + +## Every settings change is announced with the new values · 0.3.0 (app/core/settings.py, app/routers/settings.py) + +The live channel said `{"type": "settings"}` only when the window's own `PUT /api/settings` ran, so a change made elsewhere (a library fetch clearing the chosen folder, `library use` at the command line through the engine, a later settings command) was never heard and the window would have had to poll. The store now announces every update that changes something, wherever it comes from, as `{"type": "settings", "changed": [names], "settings": {all values}}` through the document's event bus, which forwards to the live channel; an update that changes nothing says nothing. The route's own bare announcement is gone, so a change is heard once. A window that listened for the bare type still hears it. Checked over the websocket against an engine on 8344: turning the overlap switch on and off gave one announcement each, naming `overlap` and carrying the values. + +## The document says which placements the step shown draws · 0.3.0 (app/doc/document.py) + +Walking the steps (`SPEC.md` 11.2) is a view change the engine already made with `step.goto`, but the window had to work out from every placement's step number what to draw. The state that `GET /api/doc` and every `GET /api/doc/changes` answer carry now holds `shows`: the submodel being edited, the step shown and how many it has, the ids of every placement of steps 1 to it in file order (`placements`, drawn), and the ids added in that step (`added`, drawn at full strength while the earlier ones are faded). It is worked out from the submodel being edited only, since a use draws its submodel whole, and a hidden placement is still listed because hiding is the window's own mark (`SPEC.md` 11.5). Because a step change is a view change it moves the revision without touching the change feed, so the `changes` answer the window reads after the live channel's `doc` event already carries the new list. Checked against an engine on 8344 with the sample car: the opened model shows step 8 of 8 with 61 placements and 10 added; after `step.goto 2` the changes since the previous revision said step 2, 15 placements and p6 to p15 added, without a reset. + +## parts.list_save · 0.3.0 (app/cmd/commands/info.py, app/automation/mcp.py) + +`SPEC.md` 13.3's "Save parts list" (the task's `model.export_parts_csv`, named by the specification's reserved id): the same rows written to a full path ending in `.csv`, `.tsv` or `.txt`, comma or tab separated by the ending unless `separator` says otherwise, through the same part file moved into place that a model save uses, so a failed write leaves the old file. It is a `file` command: not an undo step, and an outside agent waits for the person. `SPEC.md` 14.7 has a tool that writes outside the open model's folder ask every time, so the MCP server's `writes_outside` now covers this command as well as `model.save_as`. Checked against an engine on 8344 with the sample car: a `.csv` of a header and 32 rows that the standard CSV reader reads back to 61 parts, a `.tsv` tab separated, and an `.xls` path refused. + +## parts.list · 0.3.0 (app/cmd/commands/info.py) + +`SPEC.md` 13.5's `parts.list {scope?, group?}`: the rows of the Parts list tab for the whole model, the submodel being edited, or that submodel up to its step shown (13.2), sorted by part or by colour, with the total and the number of rows. The task that asked for it named it `model.parts_list`; `spec/SPEC.md` 21.2 already reserved `parts.list` and `parts.list_save` for these, and the specification decides ids, so the catalogue's ids are the specification's. An unknown scope or group is refused with the choices named. Checked against an engine on 8344 with the sample car: the whole model 61 parts in 32 rows; shown at step 2, the step scope gave 15 parts in 10 rows, the five lines of step 1 and the ten of step 2. + +## model.info · 0.3.0 (app/cmd/commands/info.py) + +`SPEC.md` 13.5's read behind the About tab, for agents and the command line: the same answer as `GET /api/doc/info`, from the same function, so a person and an agent read the same counts. It reads only, so an outside agent is never asked. Checked against an engine on 8344 with the sample car: 61 parts and 32 rows. + +## GET /api/doc/info and the parts list as CSV · 0.3.0 (app/services/model_info.py, app/routers/doc.py) + +`GET /api/doc/info` is the About and Parts list tabs of `SPEC.md` 13.1 and 13.2 in one answer: the model's name, title, author and licence from the main model's header, its file, the library update it was last saved with (`builtWith`, from its `LIBRARY` line, null for a plain LDraw file) and the one in use, the counts (parts in all through every use, different parts, part and colour pairs, missing parts, submodels other than the main model, steps of the main model, placements as written), the size across, deep and high in LDU, studs, bricks and plates and millimetres (0.4 mm to the LDU) from the box round every world placement's part bounds, studs included, and the parts list with its CSV text. A row is part, number, description, colour with name and value, count, `missing`, `printed` and `movedTo`. Missing parts come first (13.2), then by part number and colour, or by colour first with `group=colour`. A part the library has moved, such as 3023, keeps the number the file gives it (13.4) and shows the description of the part it moved to, because "~Moved to 3023b" tells a person nothing about the brick in their hand; `movedTo` says where it went. Runs of spaces in a library description become one space for showing; the library writes them to align its own lists. `GET /api/doc/parts.csv?scope=&group=&separator=` gives the file itself, `text/csv` or tab separated (13.3): a header row `Part,Description,Colour,Colour name,Count`, then one row per part and colour, UTF-8, CR LF, fields quoted only when they hold the separator or a quote, which is what a spreadsheet expects. Both read under the document's lock and never wait for an index build. Checked against an engine on 8344 with the sample car: 61 parts, 26 different, 32 pairs, 8 steps, 90 by 216 by 124 LDU, library 2026-10, and 3023 listed as Plate 1 x 2, 2 black and 6 red. + +## GET /api/doc/tree · 0.3.0 (app/services/model_info.py, app/routers/doc.py) + +The Model tab (`SPEC.md` 12.1) shows each placement with its description, part number or submodel name, colour swatch and step, and a use opens to show its submodel's own rows. `GET /api/doc/tree` answers every submodel once, by name, with its title, uses, unused mark and its steps, each step's rows in file order: id, part, number, description, colour with its name and value, step, hidden and open marks, `use` (the submodel's name for a use, whose row then shows the submodel's title) and `missing` for a part the library does not have (12.4). A use's row refers to its submodel by name instead of nesting it, so a submodel used ten times is sent once and the window opens a row by looking the name up; `root` is the submodel being edited, which the tree shows at its top (12.3), beside the editing path, the step shown, the selection and the revision. Descriptions come from the parts index only when it is ready, so the tree never waits for an index build: until then `libraryReady` is false, descriptions are empty, `missing` is null and the build is started, and the window reads the tree again on the library's `ready` event. Colour names are the library's own table. Checked against an engine on 8344 with the sample car: 8 steps, 61 rows, the first `4315 Hinge Plate 1 x 4 with Car Roof Holder`, black `#1B2A34`. + +## Counting the parts a model needs · 0.3.0 (app/doc/partslist.py) + +`SPEC.md` 13.2 counts what would be needed to build the whole model: a submodel used three times counts each of its parts three times. `walk` goes down from a submodel through every use, composing each use's position and turn so the world placement of every library part comes out too (the model information's size needs it), and gives a part in colour 16 the colour of the use it sits in, which is what a person building it would pick up (`SPEC.md` 10.5); colour 16 at the top stays 16. A cycle of uses, which the commands never make but a file could hold, is cut at the repeat. `through` limits the top submodel to its first steps, for "up to the step shown" (13.2), while every use inside counts whole, since a use placed in step 3 brings all its parts in step 3. Part names are compared without case because LDraw names are, and kept as the model spells them otherwise, so an alias part counts under its own number (13.4). The scopes are the main model, the submodel being edited, and the submodel being edited up to its step shown. Checked on the sample car: 61 parts, 32 part and colour pairs, 26 different parts; 3024 gives 2 black, 2 red, 2 trans yellow and 4 trans clear, 3023 gives 2 black and 6 red, 3641 gives 4 black, each the count of its lines in the file by colour. + +## The pointer's index is warmed after every change · 0.3.0 (app/services/warmer.py, app/routers/place.py) + +The first preview after opening a 2,000-placement model took 350 ms: the spatial hash, the scene boxes and every part's triangles were built on that request, under the document's lock. `warmer` listens to the document's own events and, after each `doc` event, brings the hash, the boxes and the hidden list of the submodel being edited up to date under the new stamp on one background thread, then loads the triangles of the parts it uses outside the lock, stopping early when another change arrives. A burst of changes wakes it once. It starts with the place router, so the engine warms the model it reopens at start and the command line, which never loads that router, pays nothing. Checked against an engine on 8344 with the 2,000-placement model: the first preview after the open, four seconds later, took 10 ms instead of 346 ms, and the first after a drop 7 ms. + +## The hidden placements are kept per stamp too · 0.3.0 (app/services/connect_host.py, app/cmd/fitting.py, app/cmd/placing.py, app/routers/place.py, app/cmd/commands/pointer.py) + +A profile of 300 previews on a 2,000-placement model put the two lists of hidden placements (one for the pick, one for the fit), each a walk over every placement, at a third of the time. `connect_host.hidden` now takes the same stamp as the hash and keeps its answer per submodel until the stamp moves, and every reader of the pointer asks it rather than walking the model itself. Checked in process: 3.9 ms a preview before, 3.0 ms after, the rest being the snap itself. + +## part.place_at_ray and part.pick · 0.3.0 (app/cmd/commands/pointer.py, app/cmd/commands/part.py) + +The drop of `SPEC.md` 4.3 must put the part exactly where the ghost was, so `part.place_at_ray {part, colour, origin, direction, rotation?, held?, step?, snap?}` runs the same `placing.attempt` as the preview, with the same scene axes, and commits its pose as one undo step labelled like `part.place`; a place the overlap check refuses, or a ray at the sky, is refused and changes nothing. Its answer is the new placement in LDraw axes, as every other part command answers, and under `preview` the preview's own answer in scene axes, so the window can check the two agree. It takes the editing submodel, since the pointer is always in it. `part.pick {origin, direction, ground?}` is the read form of `/api/place/pick` for agents and the command line. The record-making tail of `part.place` became `put` so both commands place the same way. Checked against an engine on 8344: a ray straight down placed a 3001 at LDraw (0, -24, 0) as one undo step "Place 3001.dat", and a pick down the same ray met it at scene y = 24. + +## POST /api/place/preview and /api/place/pick · 0.3.0 (app/routers/place.py, app/cmd/placing.py, app/cmd/fitting.py, app/main.py) + +The ghost under the pointer (`SPEC.md` 4.2) asks the engine on every pointer move: `POST /api/place/preview {part, colour, ray: {origin, dir}, rotation?, held?, ids?, snap?}` in the window's scene axes answers `{position, rotation, snapped, blocked, on}` in the same axes, with the LDraw pose, the marks of the connectors it would join (scene axes), how many it joins, the overlapping pairs and the revision it was worked out on. It is a read: it takes the document's lock, never changes the model and makes no undo step; it is a POST only because a ray and a rotation do not fit a query string, and like every route it needs the window key. The ray is met on real triangles (`picking.pick`), then the connection lane's `fit` runs from that hit with the snap and overlap switches and grid step of the settings, `held` naming the connector the part is gripped by (the raw pose's anchor), and `ids` the placements being dragged, which neither take part in the pick nor seat or block (`SPEC.md` 5.1). `on` is the placement the seat joins most, `ground` for a seat on the lattice or a rest on the ground, the placement under the pointer for a grid rest on it, and null when the ray points at the sky, where position is null too and the window keeps the ghost where it was (4.4). `blocked` is true when the overlap check refuses the place; the answer then still carries the place that was refused, so the window can draw the warning there while it keeps the ghost at its own last free place (4.2), which only the window knows. `fitting.attempt` now returns that pose beside the final answer, and takes a ready hit and a stamp; `fitting.where` answers as before. `POST /api/place/pick {ray, ground?}` answers the placement and point under a scene ray on real triangles, for the window to pick through the engine when its own scene is not enough. Checked against an engine on 8344: a 3001 previewed over empty ground seated on the lattice at scene (0, 24, 0) with 8 marks. + +## Picking through the engine against real triangles · 0.3.0 (app/services/picking.py, app/connect/__init__.py) + +`pick(model, key, origin, direction)` answers the first placement of a submodel a scene ray meets on its real triangles, with the point, the normal turned to face the ray and the distance, in scene axes; or the ground plane (`on` is then `ground`); or nothing for a ray at the sky. The broad phase is one numpy pass over every placement's box in scene axes (`box_entries`), kept per submodel and stamp beside the spatial hash it is made from; placements are then tested in the order the ray enters their boxes and the search stops once the next box starts beyond the nearest hit, so a ray over a large model tests the triangles of a handful of parts. Each part's triangles are kept once per library and quality, the 512 most recently used, because the mesh cache on disk is fast but reshaping its arrays is not free. `Picked.ldraw()` gives the same hit as the connection lane's `Hit` in LDraw axes through the mesh package's conversion, so the snap's raw pose starts from the face the person sees rather than a box face 4 LDU above the studs. A use of a submodel has no part triangles in 0.3.0 and is not picked; the window's own pick covers it. `placed_box` joins the connection package's surface, since picking needs a placement's box in model axes. Checked in process on a 2,000-placement model: the first pick, which reads the meshes, 348 ms; then 1,000 random rays from above, median 0.42 ms, 95th percentile 0.76 ms, worst 2.3 ms. + +## A read with a stamp skips the walk over the placements · 0.3.0 (app/services/connect_host.py) + +`hash_of` compared every placement of the submodel with what it last put before every use, about 1.3 ms for 2,000 placements, which a pointer preview pays on every move although nothing changed between two moves. It now takes an optional `stamp`; when the stamp equals the one the hash was last brought up to date under, the hash is returned at once (0.02 ms). Only callers that hold the document's lock and do not change the model pass one, made of the model object's identity and the document's revision, which moves on every change, undo, redo and open. A command that changes the model passes none, because the model can change between two of its own calls within one revision; its walk then leaves the stamp empty, so the next stamped read walks again. Checked in process on a 2,000-placement model: 1.23 ms a call without a stamp, 0.017 ms with an unchanged one. + +## A saved project names the library it was saved with · 0.3.0 (app/services/library_host.py, app/doc/convert.py, app/cmd/commands/model.py) + +`spec/LDRAW.md` has `0 !FORMBLOCKS LIBRARY ` hold the release the model was last saved with, but the writer only carried back whatever line the file had been read with, so every new model said `unknown`. `library_host.update_name()` answers the release of the library in use: the fetched archive's release when the manifest belongs to the folder in use, else the parts index's newest `UPDATE`, loading the saved index or building it once when it is not ready yet (a save may then wait for the index, which the parts palette needs anyway). With no library at all it answers none and the line read from the file stays, so opening and saving an old project on a machine with no library does not erase what it was built with; only then is `unknown` written. An LDraw export carries no project lines and does not ask. Checked against an engine on the 2026-10 library: a new model saved as `.fblk` wrote `0 !FORMBLOCKS LIBRARY 2026-10`, reopened without a complaint, and an `.ldr` export wrote no `!FORMBLOCKS` line. + ## Writing a file outside the open model's folder asks every time · 0.2.0 (app/automation/mcp.py, app/services/consent.py) Reviewed what an outside agent can reach through the file commands. `model.open`, `model.save`, `model.save_as` and `model.insert` are of kind `file` or `change`, so each call from an outside agent waits for the person in the window, and the paths are limited to full paths ending in `.fblk`, `.ldr`, `.mpd` (and `.dat` to open), at most 64 MB to read, written through a part file moved into place. But once the person answered "always" for an agent, or set outside agents to allowed, `model.save_as` could write such a file anywhere without a question, against `SPEC.md` 14.7: "MCP tools that write a file outside the folder of the open model ask the person first, every time". `consent.ask` now takes `every_time`, which skips the standing allowance (a block still refuses at once), and the server passes it for a `model.save_as` whose path is not in the open model's folder or below it, or when the model has no file yet. A headless server, with no window to ask, refuses such a write even for an allowed agent. Agent tabs of the dock are still trusted as the person's own and are not asked, as the template has it. Checked in process with outside agents set to allowed: headless `save_as` with no model file and into another folder were refused, into the model's own folder ran, and an ordinary change ran without a question. diff --git a/backend/app/__init__.py b/backend/app/__init__.py index d3ec452..493f741 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -1 +1 @@ -__version__ = "0.2.0" +__version__ = "0.3.0" diff --git a/backend/app/automation/cli.py b/backend/app/automation/cli.py index 8921679..1ea515e 100644 --- a/backend/app/automation/cli.py +++ b/backend/app/automation/cli.py @@ -23,6 +23,9 @@ [--limit N] [--offset N] [--lines] ranked parts; --lines prints number, description, category parts show NAME one part, following a moved number + parts list MODEL [--csv OUT] [--tab] [--by-colour] + the parts a model file needs, read without opening it; + --csv writes the list as a CSV file (tab separated with --tab) part-mesh NAME [--quality standard|low|high] a part's triangles, edges, bounds and whether the cache answered library status [--ask-server] found or not, where, the update, the consent and attribution @@ -242,7 +245,7 @@ def cmd_mcp(pos: list, opts: dict) -> int: COMMANDS = {"commands": cmd_commands, "run": cmd_run, "doc": cmd_doc, "undo": history("undo"), "redo": history("redo")} OPTIONS: dict[str, tuple[tuple, tuple]] = { - "parts": (("--category", "--list", "--limit", "--offset"), ("--printed", "--lines", "--json")), + "parts": (("--category", "--list", "--limit", "--offset", "--csv"), ("--printed", "--lines", "--json", "--tab", "--by-colour")), "part-mesh": (("--quality",), ()), "library": (("--i-consent",), ("--ask-server", "--clear")), "colours": (("--group", "--hue"), ()), @@ -308,9 +311,46 @@ def parts_show(pos: list, opts: dict) -> dict: return shown +def caller_path(given: str) -> str: + base = os.environ.get("FORMBLOCKS_CALLER_DIR") or os.getcwd() + return os.path.normpath(os.path.join(base, os.path.expanduser(given))) + + +def parts_list(pos: list, opts: dict): + if len(pos) != 1: + raise Usage("parts list needs one model file.") + from pathlib import Path + + from app.doc import files + from app.library import NoLibrary + from app.services import library_host, model_info + + try: + model, _ = files.read(Path(caller_path(pos[0])), "MODEL") + except files.FileProblem as exc: + raise Failed(str(exc)) + try: + library_host.service().index() + except NoLibrary: + pass + rows = model_info.rows_for(model, model.main, None, "colour" if opts.get("--by-colour") else "part") + target = opts.get("--csv") + if target is None: + return {"file": caller_path(pos[0]), "rows": rows, "count": sum(r["count"] for r in rows), "pairs": len(rows)} + data = model_info.parts_csv(rows, "tab" if opts.get("--tab") else "comma").encode("utf-8") + written = Path(caller_path(target)) + try: + files.write(written, data, "--csv") + except files.FileProblem as exc: + raise Failed(str(exc)) + return {"file": caller_path(pos[0]), "written": str(written), "rows": len(rows), "count": sum(r["count"] for r in rows), "bytes": len(data)} + + def cmd_parts(pos: list, opts: dict): - if not pos or pos[0] not in ("search", "show"): - raise Usage("parts takes search WORDS or show NAME.") + if not pos or pos[0] not in ("search", "show", "list"): + raise Usage("parts takes search WORDS, show NAME or list MODEL.") + if pos[0] == "list": + return parts_list(pos[1:], opts) if pos[0] == "search": result = parts_search(pos[1:], opts) if opts.get("--lines"): diff --git a/backend/app/automation/mcp.py b/backend/app/automation/mcp.py index b89f0b3..c0b7705 100644 --- a/backend/app/automation/mcp.py +++ b/backend/app/automation/mcp.py @@ -159,7 +159,7 @@ def gate(self, tool: str, every_time: bool = False) -> None: @staticmethod def writes_outside(name: str, params) -> bool: given = params.get("path") if isinstance(params, dict) else None - if name != "model.save_as" or not isinstance(given, str): + if name not in ("model.save_as", "parts.list_save") or not isinstance(given, str): return False current = document().file if not current: diff --git a/backend/app/cmd/commands/colours.py b/backend/app/cmd/commands/colours.py new file mode 100644 index 0000000..1e1ca4e --- /dev/null +++ b/backend/app/cmd/commands/colours.py @@ -0,0 +1,49 @@ +from collections import Counter + +from app.cmd.registry import CommandError, Param, command +from app.core import settings +from app.doc import partslist +from app.services import model_info + + +def _used(doc) -> list[tuple[int, int]]: + m = doc.model + counted = Counter(p.colour for p in partslist.walk(m, m.main)) + for pid in m.all_ids(): + code = m.placement(pid)["colour"] + if code not in counted: + counted[code] = 0 + return sorted(((code, n) for code, n in counted.items() if code not in settings.NOT_SWATCHES), key=lambda item: (-item[1], item[0])) + + +@command( + "colours.used", + "Colours Used", + "List the colours used in the open model, most used first: each colour's number, name, value, how many parts of the whole model are in it, and whether the library defines it.", + kind="read", +) +def used(doc) -> dict: + labels = model_info.Labels() + rows = [] + for code, count in _used(doc): + known = labels.colours is not None and labels.colours.get(code) is not None + named = labels.colour(code) + rows.append({"code": code, "name": named["colourName"], "value": named["colourValue"], "count": count, "known": known}) + return {"count": len(rows), "colours": rows} + + +@command( + "colours.current", + "Current Colour", + "Choose the colour the next placed part gets, and put it at the front of the recent colours. Kept as the person's setting; it recolours nothing.", + params=(Param("colour", "integer", "An LDraw colour code from 0, such as 4 for red; not 16 or 24, which are not colours of their own."),), + kind="view", +) +def current(doc, colour: int) -> dict: + held = settings.store() + recent = [code for code in held.get()["recent_colours"] if code != colour] + try: + now = held.update({"current_colour": colour, "recent_colours": [colour, *recent][: settings.RECENT_COLOURS]}) + except settings.SettingsError as exc: + raise CommandError(str(exc).replace("current_colour", "colour", 1)) from None + return {"current_colour": now["current_colour"], "recent_colours": now["recent_colours"]} diff --git a/backend/app/cmd/commands/connect.py b/backend/app/cmd/commands/connect.py index 69aaca4..cffeb32 100644 --- a/backend/app/cmd/commands/connect.py +++ b/backend/app/cmd/commands/connect.py @@ -79,7 +79,7 @@ def overlap_check(doc, ids=None) -> dict: try: for key in keys: found = check_model(connect_host.hash_of(m, key), OverlapSettings(enabled=True), only=chosen) - pairs.extend({"submodel": m.name_of(key)} | o.as_dict() for o in found) + pairs.extend({"submodel": m.name_of(key)} | o.as_dict() | {"parts": [m.placement(o.a)["part"], m.placement(o.b)["part"]]} for o in found) except NoLibrary: raise CommandError(fitting.NO_LIBRARY) from None return {"checked": len(chosen) if chosen is not None else len(m.all_ids()), "overlaps": pairs, "count": len(pairs)} diff --git a/backend/app/cmd/commands/info.py b/backend/app/cmd/commands/info.py new file mode 100644 index 0000000..2a07929 --- /dev/null +++ b/backend/app/cmd/commands/info.py @@ -0,0 +1,120 @@ +from app.cmd.registry import CommandError, Param, command +from app.doc import files, partslist +from app.services import model_info + + +@command( + "model.info", + "Model Information", + "Read the model's name, author, file and library update, its counts (parts through every use, different parts, part and colour pairs, submodels, steps), its size in LDU, studs, bricks and millimetres, and its parts list.", + kind="read", +) +def info(doc) -> dict: + return model_info.info(doc) + + +LICENCES = ("CC BY 4.0", "CC BY-SA 4.0", "CC BY-NC 4.0", "CC BY-NC-SA 4.0", "CC BY-ND 4.0", "CC BY-NC-ND 4.0", "CC0 1.0") +TEXT_MAX = 200 + + +def _line(header: list, mark: str, text: str | None, after: str) -> None: + found = next((i for i, line in enumerate(header) if isinstance(line, str) and line.lower().startswith(mark.lower())), None) + if text is None: + if found is not None: + del header[found] + return + if found is not None: + header[found] = "%s %s" % (mark, text) + return + anchor = next((i for i, line in enumerate(header) if isinstance(line, str) and line.lower().startswith(after.lower())), None) + header.insert(len(header) if anchor is None else anchor + 1, "%s %s" % (mark, text)) + + +@command( + "model.set_info", + "Set Model Information", + "Change the main model's title, author or licence, as written in its header: the licence is empty or one of the Creative Commons licences listed in its parameter.", + params=( + Param("title", "string", "The model's title, the first line of its file.", False, TEXT_MAX), + Param("author", "string", "The author's name; empty clears it.", False, TEXT_MAX), + Param("licence", "string", "Empty for none, or one of: %s." % ", ".join(LICENCES), False, 40), + ), +) +def set_info(doc, title=None, author=None, licence=None) -> dict: + if title is None and author is None and licence is None: + raise CommandError("title, author or licence: give at least one of them.") + m = doc.model + sub = m.edit_submodel(m.main) + header = sub["header"] + if title is not None: + clean = " ".join(title.split()) + if not clean: + raise CommandError("title is empty; a model keeps a title, its file's first line.") + at = next((i for i, line in enumerate(header) if isinstance(line, dict)), None) + if at is None: + header.insert(0, {"title": clean}) + else: + header[at] = {"title": clean} + if author is not None: + _line(header, "0 Author:", " ".join(author.split()), "0 Name:") + if licence is not None: + chosen = " ".join(licence.split()) + known = {name.lower(): name for name in LICENCES} + if chosen and chosen.lower() not in known: + raise CommandError("licence is empty or one of %s." % ", ".join(LICENCES)) + _line(header, "0 !LICENSE", "Licensed under %s" % known[chosen.lower()] if chosen else None, "0 Author:") + doc.label = "Change model information" + info_now = model_info.info(doc) + return {k: info_now[k] for k in ("name", "title", "author", "licence")} + + +def _choice(value: str | None, allowed: tuple[str, ...], field: str, default: str) -> str: + chosen = (value or default).strip().lower() + if chosen not in allowed: + raise CommandError("%s is one of %s." % (field, ", ".join(allowed))) + return chosen + + +SCOPE = Param("scope", "string", "model for the whole model, submodel for the submodel being edited, step for it up to the step shown; model when left out.", False, 10) +GROUP = Param("group", "string", "part to sort by part number, colour to sort by colour; part when left out.", False, 10) + + +@command( + "parts.list", + "Parts List", + "Read the parts a model needs, one row per part and colour with its description, colour name and count, a submodel's parts counted once for each use; parts missing from the library first.", + params=(SCOPE, GROUP), + kind="read", +) +def parts_list(doc, scope=None, group=None) -> dict: + chosen = _choice(scope, partslist.SCOPES, "scope", "model") + rows = model_info.parts_rows(doc, chosen, _choice(group, model_info.GROUPS, "group", "part")) + return {"scope": chosen, "rows": rows, "count": sum(r["count"] for r in rows), "pairs": len(rows)} + + +ENDINGS = {".csv": "comma", ".tsv": "tab", ".txt": "comma"} + + +@command( + "parts.list_save", + "Save Parts List", + "Write the parts list to a file as CSV: a header row, then one row per part and colour with part number, description, colour number, colour name and count; comma separated, or tab separated for a .tsv path or separator tab.", + params=( + Param("path", "string", "The full path to write, ending in .csv, .tsv or .txt.", True, 4096), + Param("separator", "string", "comma or tab; from the path's ending when left out.", False, 10), + SCOPE, + GROUP, + ), + kind="file", +) +def parts_list_save(doc, path: str, separator=None, scope=None, group=None) -> dict: + target = files.resolve(path) + ending = target.suffix.lower() + if ending not in ENDINGS: + raise CommandError("path must end in .csv, .tsv or .txt, not %s." % (target.suffix or "no extension")) + split = _choice(separator, tuple(model_info.SEPARATORS), "separator", ENDINGS[ending]) + chosen = _choice(scope, partslist.SCOPES, "scope", "model") + rows = model_info.parts_rows(doc, chosen, _choice(group, model_info.GROUPS, "group", "part")) + data = model_info.parts_csv(rows, split).encode("utf-8") + files.write(target, data) + return {"written": str(target), "separator": split, "scope": chosen, "rows": len(rows), "count": sum(r["count"] for r in rows), "bytes": len(data)} diff --git a/backend/app/cmd/commands/library.py b/backend/app/cmd/commands/library.py index 708cc27..b58ae62 100644 --- a/backend/app/cmd/commands/library.py +++ b/backend/app/cmd/commands/library.py @@ -72,13 +72,16 @@ def status(doc) -> dict: params=( Param("text", "string", "Name words in any order, such as dark blue.", False, 200), Param("group", "string", "solid, transparent, chrome, pearl, metallic, rubber or material.", False, 20), - Param("hue", "string", "A hue family, such as red or blue.", False, 40), + Param("hue", "string", "One hue family, written as each colour's hue field writes it: reds, oranges, yellows, greens, blues, purples, pinks, browns or greys; all or left out for every family.", False, 40), ), kind="read", ) def colours(doc, text: str = "", group: str = "", hue: str = "") -> dict: + from app.library.colours import HUES from app.routers import colours as route if group not in GROUPS: raise CommandError("group must be one of %s, not %s." % (", ".join(g for g in GROUPS if g), group)) + if hue not in ("", "all", *HUES): + raise CommandError("hue must be one of %s or all, not %s." % (", ".join(HUES), hue)) return _library(lambda: route.colours(group, hue, text)) diff --git a/backend/app/cmd/commands/model.py b/backend/app/cmd/commands/model.py index f6643ac..38d24c6 100644 --- a/backend/app/cmd/commands/model.py +++ b/backend/app/cmd/commands/model.py @@ -2,6 +2,9 @@ from app.cmd.registry import CommandError, Param, command from app.doc import convert, files, recent, views from app.doc.model import META, PLACE, SUB, key_of, new_placement +from app.core import settings +from app.ldraw import Snap +from app.services import library_host PATH = 4096 DISCARD = Param("discard", "boolean", "Drop unsaved changes to the open model; without it a model with unsaved changes is kept and the command refused.", False) @@ -46,14 +49,34 @@ def open_model(doc, path: str, discard: bool | None = None) -> dict: is_part = "part" in info report = {"issues": info["issues"], "encoding": info["encoding"]} doc.replace(model, None if is_part else str(target), None if is_part else files.kind_of(target), report, info.get("show")) + _apply_snap(model) out = _summary(doc) | {"issueCount": len(info["issues"]), "issues": info["issues"][:20], "encoding": info["encoding"]} if is_part: out["part"] = info["part"] return out +def _snap_line() -> str: + values = settings.store().get() + return Snap(on=values["snap"], grid=values["grid_step"].upper()).to_text() + + +def _apply_snap(model) -> dict | None: + text = (model.meta.get("project") or {}).get("snap") + if not text: + return None + words = text.split() + if len(words) != 5 or words[3] not in ("ON", "OFF") or words[4].lower() not in settings.GRID_STEPS: + return None + return settings.store().update({"snap": words[3] == "ON", "grid_step": words[4].lower()}) + + def _write(doc, target, kind: str) -> int: - data = convert.write(doc.model, kind, doc.show_state() if kind == "fblk" else None) + project = kind == "fblk" + if project: + data = convert.write(doc.model, kind, doc.show_state(), library_host.update_name(), _snap_line()) + else: + data = convert.write(doc.model, kind) files.write(target, data) return len(data) diff --git a/backend/app/cmd/commands/part.py b/backend/app/cmd/commands/part.py index 0c67d7a..5e39366 100644 --- a/backend/app/cmd/commands/part.py +++ b/backend/app/cmd/commands/part.py @@ -48,6 +48,12 @@ def place(doc, part: str, colour: int, position: list | None = None, rotation: l if found.blocked: raise CommandError(fitting.refusal(found)) where, turn = args.position([float(v) for v in found.pose.translation]), [float(v) for v in found.pose.rotation] + pid = put(doc, key, name, colour, where, turn, step) + fitted = {} if found is None else {k: v for k, v in found.as_dict().items() if k in ("seated", "joined", "marks")} + return {"placement": views.placement_json(doc.model, pid)} | fitted + + +def put(doc, key: str, name: str, colour: int, where: list, turn: list, step: int | None = None) -> str: record = new_placement(name, args.colour(colour), where, turn) if step is None: index = doc.target_step(key) @@ -58,8 +64,19 @@ def place(doc, part: str, colour: int, position: list | None = None, rotation: l pid = doc.model.insert(key, index, record) _selected_if_editing(doc, key, [pid]) doc.label = "Place %s" % name - fitted = {} if found is None else {k: v for k, v in found.as_dict().items() if k in ("seated", "joined", "marks")} - return {"placement": views.placement_json(doc.model, pid)} | fitted + if doc.model.find(name) is None: + _recent(name) + return pid + + +def _recent(name: str) -> None: + from app.core import settings + from app.library.names import part_number + + number = part_number(name) + held = settings.store() + kept = [n for n in held.get()["recent_parts"] if n.lower() != number] + held.update({"recent_parts": [number, *kept][: settings.RECENT_LIMIT]}) def _moved(doc, chosen: list[str]) -> dict: diff --git a/backend/app/cmd/commands/pointer.py b/backend/app/cmd/commands/pointer.py new file mode 100644 index 0000000..cafe3ee --- /dev/null +++ b/backend/app/cmd/commands/pointer.py @@ -0,0 +1,107 @@ +from app.cmd import args, fitting, placing +from app.cmd.commands.part import put +from app.cmd.registry import CommandError, Param, command +from app.doc import views +from app.services import connect_host, picking + + +@command( + "part.place_at_ray", + "Place Part at Pointer", + "Place a library part where a pointer ray in the window's scene axes puts it, seated, on the grid or refused exactly as the placement preview answers; it goes into the step shown of the submodel being edited and becomes the selection.", + params=( + Param("part", "string", "The part's file name, such as 3001.dat (3001 is read as 3001.dat).", True, args.NAME_MAX), + args.colour_param(), + *placing.ray_params(), + placing.scene_rotation_param(), + placing.held_param(), + Param("step", "integer", "The step to put it in, from 1; one more than the last starts a new step. The step shown when left out.", False), + fitting.snap_param(), + ), +) +def place_at_ray(doc, part: str, colour: int, origin: list, direction: list, rotation=None, held=None, step=None, snap=None) -> dict: + key = doc.editing + args.colour(colour) + found = placing.attempt(doc, key, part, origin, direction, rotation, held, (), snap) + if found.tried is None or found.tried.pose is None: + raise CommandError("direction: the pointer ray meets no part and never reaches the ground, so there is nowhere to place it.") + if found.blocked: + raise CommandError(fitting.refusal(found.final)) + pose = found.tried.pose + pid = put(doc, key, found.part, colour, args.position([float(v) for v in pose.translation]), [float(v) for v in pose.rotation], step) + return {"placement": views.placement_json(doc.model, pid), "preview": placing.answer(found)} + + +@command( + "part.move_at_ray", + "Move Selection at Pointer", + "Put down a dragged selection where a pointer ray in the window's scene axes takes the grabbed placement, seated, on the grid or refused exactly as the drag preview answers; the others keep their places relative to it. One undo step.", + params=( + Param("grab", "string", "The placement the person pressed on, such as p12.", True, 40), + *placing.ray_params(), + placing.scene_rotation_param(), + placing.held_param(), + args.ids_param("The placements that move with it; the selection when the grabbed placement is in it, else that placement alone."), + fitting.snap_param(), + ), +) +def move_at_ray(doc, grab: str, origin: list, direction: list, rotation=None, held=None, ids=None, snap=None) -> dict: + found = placing.drag(doc, doc.editing, grab, origin, direction, rotation, held, ids, snap) + if not found.moves: + raise CommandError("direction: the pointer ray meets no part and never reaches the ground, so there is nowhere to put the selection.") + if found.blocked: + pairs = list(found.found.final.overlaps if found.found.final is not None else ()) + list(found.clashes) + raise CommandError("ids: the selection would overlap %s with the overlap check on, so it was not moved." % ", ".join("%s by %s LDU" % (o.b, round(o.depth, 1)) for o in pairs)) + for pid, pose in found.moves.items(): + p = doc.model.edit_placement(pid) + p["position"] = args.position([float(v) for v in pose.translation]) + p["rotation"] = [float(v) for v in pose.rotation] + doc.label = "Move %s" % args.count(len(found.moves)) + return {"placements": [views.placement_json(doc.model, pid) for pid in found.moves], "preview": placing.drag_answer(found)} + + +@command( + "part.duplicate_at_ray", + "Duplicate at Pointer", + "Drop copies of a selection where a pointer ray in the window's scene axes takes the copy of the grabbed placement, seated, on the grid or refused as the drag preview with copy answers; the copies keep their colours and places relative to one another, go into the step shown and become the selection. One undo step.", + params=( + Param("grab", "string", "The placement whose copy is held under the pointer, such as p12.", True, 40), + *placing.ray_params(), + placing.scene_rotation_param(), + placing.held_param(), + args.ids_param("The placements copied with it; the selection when the grabbed placement is in it, else that placement alone."), + fitting.snap_param(), + ), +) +def duplicate_at_ray(doc, grab: str, origin: list, direction: list, rotation=None, held=None, ids=None, snap=None) -> dict: + key = doc.editing + found = placing.drag(doc, key, grab, origin, direction, rotation, held, ids, snap, copy=True) + if not found.moves: + raise CommandError("direction: the pointer ray meets no part and never reaches the ground, so there is nowhere to put the copies.") + if found.blocked: + pairs = list(found.found.final.overlaps if found.found.final is not None else ()) + list(found.clashes) + raise CommandError("ids: the copies would overlap %s with the overlap check on, so none was made." % ", ".join("%s by %s LDU" % (o.b, round(o.depth, 1)) for o in pairs)) + made = [] + for pid, pose in found.moves.items(): + copy = dict(doc.model.placement(pid)) + copy["position"] = args.position([float(v) for v in pose.translation]) + copy["rotation"] = [float(v) for v in pose.rotation] + copy["hidden"] = False + made.append(doc.model.insert(key, doc.target_step(key), copy)) + doc.view["selection"] = list(made) + doc.label = "Duplicate %s" % args.count(len(made)) + return {"placements": [views.placement_json(doc.model, pid) for pid in made], "from": list(found.moves), "preview": placing.drag_answer(found)} + + +@command( + "part.pick", + "Pick at Pointer", + "Name the placement of the submodel being edited that a pointer ray in the window's scene axes meets first on its real triangles, with the point and the face's normal, or the ground; hidden parts are passed through.", + params=(*placing.ray_params(), Param("ground", "boolean", "Answer the ground plane when no part is met; true when left out.", False)), + kind="read", +) +def pick(doc, origin: list, direction: list, ground=None) -> dict: + key = doc.editing + stamp = fitting.stamp_of(doc) + found = picking.pick(doc.model, key, origin, direction, skip=connect_host.hidden(doc.model, key, stamp), stamp=stamp, ground=ground is not False) + return {"hit": None if found is None else found.as_dict()} diff --git a/backend/app/cmd/commands/switches.py b/backend/app/cmd/commands/switches.py new file mode 100644 index 0000000..c9453f1 --- /dev/null +++ b/backend/app/cmd/commands/switches.py @@ -0,0 +1,43 @@ +from app.cmd.registry import CommandError, Param, command +from app.core import settings + + +def _set(name: str, value, field: str) -> dict: + try: + now = settings.store().update({name: value}) + except settings.SettingsError as exc: + raise CommandError(str(exc).replace(name, field, 1)) from None + return {"snap": now["snap"], "grid_step": now["grid_step"], "overlap": now["overlap"]} + + +@command( + "snap.set", + "Snapping", + "Turn snapping on or off: with it on, a part being placed or moved seats on free compatible connectors within reach; with it off, it moves in grid steps only. Kept as the person's setting.", + params=(Param("on", "boolean", "true to snap, false to move in grid steps only."),), + kind="view", +) +def snap_set(doc, on: bool) -> dict: + return _set("snap", on, "on") + + +@command( + "grid.step", + "Grid Step", + "Choose the grid step: stud (20 LDU across, 8 up), plate (10 across, 8 up) or fine (1 and 1). Kept as the person's setting.", + params=(Param("step", "string", "stud, plate or fine.", True, 10),), + kind="view", +) +def grid_step(doc, step: str) -> dict: + return _set("grid_step", step, "step") + + +@command( + "overlap.set", + "Overlap Check", + "Turn the coarse overlap check on or off: with it on, placing and moving never put a part where its box would overlap another's. Kept as the person's setting.", + params=(Param("on", "boolean", "true to check, false to let parts share space."),), + kind="view", +) +def overlap_set(doc, on: bool) -> dict: + return _set("overlap", on, "on") diff --git a/backend/app/cmd/fitting.py b/backend/app/cmd/fitting.py index 19d825e..1601608 100644 --- a/backend/app/cmd/fitting.py +++ b/backend/app/cmd/fitting.py @@ -3,9 +3,9 @@ from dataclasses import replace from app.cmd.registry import CommandError, Param -from app.connect import Fit, OverlapSettings, PartInfo, Pose, fit, first_hit, neighbours, overlap_check, seat_on, settle +from app.connect import Fit, OverlapSettings, PartInfo, Pose, fit, neighbours, overlap_check, seat_on, settle from app.library import NoLibrary -from app.services import connect_host +from app.services import connect_host, picking NO_LIBRARY = "No LDraw parts library is installed: run library use FOLDER, or fetch the library with your consent." @@ -29,13 +29,17 @@ def library_info(name: str, field: str = "part") -> PartInfo: return info -def _hash(doc, key: str): +def _hash(doc, key: str, stamp=None): try: - return connect_host.hash_of(doc.model, key) + return connect_host.hash_of(doc.model, key, stamp) except NoLibrary: raise CommandError(NO_LIBRARY) from None +def stamp_of(doc) -> tuple: + return (id(doc.model), doc.revision) + + def _target(doc, key: str, on: str): found = doc.model.where(on) if found is None: @@ -46,34 +50,40 @@ def _target(doc, key: str, on: str): raise CommandError("on: %s is hidden, and hidden parts offer no connectors." % on) -def where(doc, key: str, info: PartInfo, rotation: list, *, position=None, on=None, origin=None, direction=None, snap=None, exclude=()) -> Fit: - hash_ = _hash(doc, key) +def where(doc, key: str, info: PartInfo, rotation: list, **given) -> Fit: + return attempt(doc, key, info, rotation, **given)[1] + + +def attempt(doc, key: str, info: PartInfo, rotation: list, *, position=None, on=None, origin=None, direction=None, hit=None, grip=None, snap=None, exclude=(), stamp=None) -> tuple[Fit, Fit]: + hash_ = _hash(doc, key, stamp) opts = connect_host.options(snap) quiet = replace(opts, overlap=OverlapSettings(enabled=False)) moving = list(exclude) - skip = moving + connect_host.hidden(doc.model, key) + skip = moving + connect_host.hidden(doc.model, key, stamp) turn = tuple(float(v) for v in rotation) - if on is not None: + if hit is not None: + found = fit(info, turn, hit, hash_, options=quiet, exclude=skip, grip=grip) + elif on is not None: _target(doc, key, on) found = seat_on(info, turn, hash_.get(on), hash_, options=quiet) if found is None: raise CommandError("on: %s has no free connector that %s can seat on." % (on, info.name)) elif origin is not None and direction is not None: - seen = [p for p in hash_.all() if p.key not in skip] - found = fit(info, turn, first_hit(tuple(origin), tuple(direction), seen), hash_, options=quiet, exclude=skip) + met = picking.pick_ldraw(doc.model, key, origin, direction, skip=skip, stamp=stamp) + found = fit(info, turn, met, hash_, options=quiet, exclude=skip) elif position is not None: pose = Pose(turn, tuple(float(v) for v in position)) found = settle(info, pose, hash_, options=quiet, exclude=skip) if opts.snap else Fit(pose, None, None) else: raise CommandError("position: give a position, a placement to seat on (on), or a pointer ray (origin and direction).") if found.pose is None or not opts.overlap.enabled: - return found + return found, found joined = [] if found.seat is None else [pair.key for pair in found.seat.pairs if pair.key is not None] around = neighbours(hash_, info, found.pose, reach=0.0, exclude=moving) clashes = tuple(overlap_check(info, found.pose, around, opts.overlap, joined)) if clashes: - return Fit(None, None, found.held, clashes, True) - return found + return found, Fit(None, None, found.held, clashes, True) + return found, found def refusal(found: Fit) -> str: diff --git a/backend/app/cmd/placing.py b/backend/app/cmd/placing.py new file mode 100644 index 0000000..afd9702 --- /dev/null +++ b/backend/app/cmd/placing.py @@ -0,0 +1,210 @@ +from __future__ import annotations + +from collections import Counter +from dataclasses import dataclass + +import numpy as np + +from app.cmd import args, fitting +from app.cmd.registry import CommandError, Param +from app.connect import Fit, Overlap, Placed, Pose, box_overlap, joined, neighbours, placed_box +from app.mesh import placement_from_scene, placement_to_scene, to_scene +from app.services import connect_host, picking + + +def ray_params() -> tuple[Param, ...]: + return ( + args.vector_param("origin", "Where the pointer ray starts, in the window's scene axes (+Y up, LDU)."), + args.vector_param("direction", "Which way the pointer ray goes, in the window's scene axes."), + ) + + +def held_param() -> Param: + return Param("held", "integer", "The index of the part's connector the person holds it by, from part.connectors; the anti-stud nearest the middle of its underside when left out.", False) + + +def scene_rotation_param() -> Param: + return Param("rotation", "array", "The part's 3 by 3 rotation in the window's scene axes, nine numbers row by row; the identity when left out.", False, 9, items="number", min_items=9) + + +@dataclass(frozen=True) +class Attempt: + part: str + rotation: list + picked: picking.Picked | None + tried: Fit | None + final: Fit | None + + @property + def blocked(self) -> bool: + return self.final is not None and self.final.blocked + + def on(self) -> str | None: + found = self.tried + if found is None or found.pose is None: + return None + if found.seat is not None and found.seat.pairs: + counts = Counter(pair.key for pair in found.seat.pairs) + best = max(counts.items(), key=lambda item: (item[1], item[0] is not None))[0] + return best or "ground" + if self.picked is None or self.picked.on_ground: + return "ground" + return self.picked.key + + +def ldraw_rotation(given: list | None) -> list: + if given is None: + return list(args.rotation(None)) + args.rotation(given) + transform = np.eye(4) + transform[:3, :3] = np.asarray(given, dtype=np.float64).reshape(3, 3) + return [float(v) for v in placement_from_scene(transform)[1]] + + +def grip(info, held: int | None): + if held is None: + return None + if held < 0 or held >= len(info.connectors): + raise CommandError("held: %s has connectors 0 to %d; %d is not one of them." % (info.name, len(info.connectors) - 1, held)) + return info.connectors[held].position + + +def attempt(doc, key: str, part: str, origin: list, direction: list, rotation: list | None = None, held: int | None = None, ids=(), snap=None, stamp=None, turn: list | None = None) -> Attempt: + name = args.part_name(doc, part) + if doc.model.find(name) is not None: + raise CommandError("part: %s is a submodel; placing at the pointer seats library parts." % name) + info = fitting.library_info(name) + turn = ldraw_rotation(rotation) if turn is None else list(turn) + if not any(abs(float(v)) > 1e-12 for v in direction): + raise CommandError("direction: the pointer ray needs a direction that is not zero.") + skip = list(ids) + connect_host.hidden(doc.model, key, stamp) + picked = picking.pick(doc.model, key, origin, direction, skip=skip, stamp=stamp) + if picked is None: + return Attempt(name, turn, None, None, None) + tried, final = fitting.attempt(doc, key, info, turn, hit=picked.ldraw(), grip=grip(info, held), snap=snap, exclude=ids, stamp=stamp) + return Attempt(name, turn, picked, tried, final) + + +@dataclass(frozen=True) +class Drag: + grab: str + ids: list + found: Attempt + moves: dict + clashes: tuple = () + lead: str = "" + lifted: float = 0.0 + + @property + def blocked(self) -> bool: + return self.found.blocked or bool(self.clashes) + + +def dragged(doc, key: str, grab: str, ids) -> list: + record = args.placement(doc, grab, "grab") + where = doc.model.where(grab) + if where is None or where[0] != key: + raise CommandError("grab: %s is not in the submodel being edited, and only its placements can be dragged." % grab) + if doc.model.find(record["part"]) is not None: + raise CommandError("grab: %s is a use of a submodel, which has no connectors to seat by; move it with part.move." % grab) + chosen = args.ids(doc, ids, "ids") if ids else (doc.selection() if grab in doc.selection() else [grab]) + if grab not in chosen: + chosen = [grab, *chosen] + for pid in chosen: + found = doc.model.where(pid) + if found is None or found[0] != key: + raise CommandError("ids: %s is not in the submodel being edited, so it cannot move with the drag." % pid) + return chosen + + +LEVEL = 0.5 + + +def _bottom(doc, pid: str, pose: Pose) -> float | None: + box = placed_box(pose, connect_host.service().info(doc.model.placement(pid)["part"]).shape.bounds) + return None if box is None else box[1][1] + + +def _lead(doc, poses: dict, grab: str) -> str: + bottoms = {pid: b for pid, pose in poses.items() if (b := _bottom(doc, pid, pose)) is not None} + if not bottoms or bottoms.get(grab, float("-inf")) >= max(bottoms.values()) - LEVEL: + return grab + return max(bottoms, key=lambda pid: (bottoms[pid], pid == grab)) + + +def drag(doc, key: str, grab: str, origin: list, direction: list, rotation: list | None = None, held: int | None = None, ids=None, snap=None, stamp=None, copy: bool = False) -> Drag: + chosen = dragged(doc, key, grab, ids) + before = {pid: Pose.from_ldraw(doc.model.placement(pid)["position"], doc.model.placement(pid)["rotation"]) for pid in chosen} + spin = Pose() + if rotation is not None: + spin = Pose(tuple(ldraw_rotation(rotation))).compose(Pose(before[grab].rotation).inverse()) + lead = _lead(doc, {pid: Pose(spin.rotation).compose(pose) for pid, pose in before.items()}, grab) + turn = list(Pose(spin.rotation).compose(before[lead]).rotation) + found = attempt(doc, key, doc.model.placement(lead)["part"], origin, direction, None, held if lead == grab else None, () if copy else chosen, snap, stamp, turn) + pose = None if found.tried is None else found.tried.pose + if pose is None: + return Drag(grab, chosen, found, {}, lead=lead) + rigid = pose.compose(before[lead].inverse()) + moved = {pid: pose if pid == lead else rigid.compose(before[pid]) for pid in chosen} + lowest = max((b for pid, p in moved.items() if (b := _bottom(doc, pid, p)) is not None), default=0.0) + lifted = lowest if lowest > 1e-6 else 0.0 + moves = {pid: Pose(tuple(round(v, 9) + 0.0 for v in p.rotation), tuple(round(v, 3) + 0.0 for v in p.moved((0.0, -lifted, 0.0)).translation)) for pid, p in moved.items()} + clashes = () if found.blocked else _clashes(doc, key, moves, "" if lifted else lead, stamp, () if copy else list(moves)) + return Drag(grab, chosen, found, moves, clashes, lead, round(lifted, 3)) + + +def _clashes(doc, key: str, moves: dict, grab: str, stamp, staying_out) -> tuple: + if len(moves) < 2 or not connect_host.options().overlap.enabled: + return () + hash_ = connect_host.hash_of(doc.model, key, stamp) + held = connect_host.service() + found = [] + for pid, pose in moves.items(): + if pid == grab: + continue + placed = Placed.of(pid, 0, pose, held.info(doc.model.placement(pid)["part"])) + for other in neighbours(hash_, placed.info, pose, reach=0.0, exclude=list(staying_out)): + if joined(placed, other): + continue + depth = box_overlap(placed.info, pose, other.info, other.pose) + if depth is not None: + found.append(Overlap(pid, other.key, depth)) + return tuple(found) + + +def drag_answer(found: Drag) -> dict: + out = answer(found.found) | {"grab": found.grab, "lead": found.lead, "lifted": found.lifted, "ids": found.ids, "blocked": found.blocked} + out["overlaps"] = out["overlaps"] + [item.as_dict() for item in found.clashes] + moves = [] + for pid, pose in found.moves.items(): + transform = placement_to_scene(tuple(pose.translation), tuple(pose.rotation)) + moves.append({ + "id": pid, + "position": [round(float(v), 4) + 0.0 for v in transform[:3, 3]], + "rotation": [round(float(v), 9) + 0.0 for v in transform[:3, :3].reshape(9)], + "ldraw": {"position": list(pose.translation), "rotation": list(pose.rotation)}, + }) + out["moves"] = moves + return out + + +def _scene_point(point) -> list: + return [round(float(v), 4) + 0.0 for v in to_scene(np.asarray([point], dtype=np.float64))[0]] + + +def answer(found: Attempt) -> dict: + pose = None if found.tried is None else found.tried.pose + out: dict = {"part": found.part, "position": None, "rotation": None, "snapped": False, "blocked": found.blocked, "on": found.on()} + if pose is None: + out |= {"ldraw": None, "marks": [], "joined": 0, "overlaps": []} + return out + transform = placement_to_scene(tuple(pose.translation), tuple(pose.rotation)) + out["position"] = [round(float(v), 4) + 0.0 for v in transform[:3, 3]] + out["rotation"] = [round(float(v), 9) + 0.0 for v in transform[:3, :3].reshape(9)] + out["snapped"] = found.tried.seated and not found.blocked + seat = found.tried.seat + out["ldraw"] = {"position": list(pose.translation), "rotation": list(pose.rotation)} + out["marks"] = [] if seat is None else [_scene_point(point) for point in seat.marks] + out["joined"] = 0 if seat is None else len(seat.pairs) + out["overlaps"] = [] if found.final is None else [item.as_dict() for item in found.final.overlaps] + return out diff --git a/backend/app/connect/HASHOUT_LOG.md b/backend/app/connect/HASHOUT_LOG.md index 73d7a8e..e408826 100644 --- a/backend/app/connect/HASHOUT_LOG.md +++ b/backend/app/connect/HASHOUT_LOG.md @@ -2,6 +2,14 @@ Reasons behind the connection service, newest first. The rules themselves are in `spec/CONNECTIONS.md`; this log holds the choices made while writing the code and the places where the specification was silent or had to be read one way. +## What the overlap check flags in the sample car, and why it stays · 0.3.0 (overlap.py) + +Recorded at 0.2.0 as "the coarse overlap check flags slopes in the sample model". `overlap.check` on `models/car.ldr` of the 2026-10 library reports 21 pairs, and each was worked by hand from the two parts' body boxes and placements; every one is a case `CONNECTIONS.md` "Why it can be wrong" lists, and none comes from the code reading the rule wrongly. The space under a slope's face: the steering wheel 3829c01 (p18) leans into the hollow under the windscreen 3823 (p49), 13.7 LDU, which is the "slope" of the record; the backrest of the seat 4079 (p15) leans 5 LDU past its footprint at the top, over the plate 3021 beside it (p13, 4) and under the roof holder 4214 (p50, 4). Parts nested on purpose: each rim 4624 inside its tyre 3641 (p54 to p61, 15 each), and the wheel pins of the two 4600 holders inside the four rims and tyres (p2 and p4, 11 each). Arches and hinges, kinds 0.x does not model: each mudguard 3788 over its tyres (p19 and p20, 3 each), the hinge base and top 3937 and 3938 (p23 and p24, 13), and the roof holder's hinge lugs inside the roof 4213 (p50 and p52, 7). The specification fixes the stand-in as one box per part, the bounding box of the triangles that are not studs, shrunk by 0.5 LDU, and only pairs joined through mated connectors are left out, so there is nothing to tighten within it: the boxes are already the smallest the rule allows (the triangles alone, conditional lines and edges never counted, stud triangles excluded) and the depths are the least penetrations over the fifteen axes. Making these pass needs a finer stand-in than one box, or the pin, axle and hinge kinds of `SPEC.md` 20.5; either is a change to the specification for the owner to decide, not a fix. `SPEC.md` 8.3 already says the check is a guide and may refuse a place that fits. So that a person or an agent can see such a case for what it is without looking each id up, `overlap.check` (`backend/app/cmd/commands/connect.py`) now names the two parts of every pair beside their ids. + +## Ground studs under a placement are covered · 0.3.0 (snap.py, ground.py) + +The rule decided in `CONNECTIONS.md` "Inputs": a ground stud is taken when the point 2 LDU above it lies in a neighbour's body box, shrunk as the overlap check shrinks it. The test is made lazily, once per lattice point per snap, and only for the lattice points a held connector reaches, against the neighbours the snap already gathered: a placement whose box holds a point within reach of the held part always meets the held part's box grown by the reach, so no covering placement is missed. `covers` turns the point into the placement's own axes and tests the box there, which is the oriented test for one point. Hidden placements are not neighbours of the snap at all (`SPEC.md` 4.4), so they cover nothing. Checked against an engine on the 2026-10 library: a 3001 fitted at (10, -10, 10) over a 3811 on the ground no longer seats on ground studs at y = -24 (it falls to the grid), one fitted at (33, -20, -47) seats on the baseplate with 8 pairs at y = -28, and a 3001 beside a 3001 on the ground, one on top, one stud over and at (10, 10) still give 4, 8, 6 and 8 pairs as before. + ## The table also gives the counts, the body box and the footprint · 0.2.0 (report.py) "Caching and inspection" says the connectors command is how an override's author checks an entry and how the worked examples can be checked once the engine exists. The examples state counts ("8 studs and 11 anti-studs"), body boxes and footprints as well as the connector tables, so the printed table now ends with the count of each kind, the body box the overlap check uses, and the footprint in cells with its bottom plane when it is whole cells. Checked on the full library: 3039 prints its seven connectors, "5 anti_stud, 2 stud", the body box x -20 to 20, y 0 to 24, z -30 to 10, and 2 by 2 cells at y = 24; a missing part prints only that it is not in the library. diff --git a/backend/app/connect/__init__.py b/backend/app/connect/__init__.py index 1f5cb58..a568e49 100644 --- a/backend/app/connect/__init__.py +++ b/backend/app/connect/__init__.py @@ -15,7 +15,7 @@ from .shape import PartInfo, PartShape, Placed from .snap import Candidate, Pair, Seat, SnapSettings, candidates, neighbours from .snap import snap as _snap -from .spatial import SpatialHash +from .spatial import SpatialHash, placed_box from .vec import IDENTITY, Mat3, Pose, Vec3, rotation_about @@ -104,6 +104,7 @@ def overlaps( "overlaps", "part_info", "part_reference", + "placed_box", "placed_connectors", "raw_pose", "recheck", diff --git a/backend/app/connect/ground.py b/backend/app/connect/ground.py index 0138b0e..b6c8a01 100644 --- a/backend/app/connect/ground.py +++ b/backend/app/connect/ground.py @@ -10,12 +10,18 @@ OFFSET = 10.0 HEIGHT = 0.0 SOURCE = "ground" +COVER_HEIGHT = 2.0 def lattice_point(i: int, k: int) -> Vec3: return (OFFSET + PITCH * i, HEIGHT, OFFSET + PITCH * k) +def above(lattice: tuple[int, int]) -> Vec3: + x, y, z = lattice_point(*lattice) + return (x, y - COVER_HEIGHT, z) + + def studs_near(point: Vec3, reach: float) -> list[tuple[tuple[int, int], Connector]]: if abs(point[1] - HEIGHT) > reach: return [] diff --git a/backend/app/connect/snap.py b/backend/app/connect/snap.py index d4adc4d..15026b9 100644 --- a/backend/app/connect/snap.py +++ b/backend/app/connect/snap.py @@ -8,6 +8,7 @@ from .connector import MATE_DISTANCE, Connector from .geometry import Box from .kinds import Registry, load +from .overlap import body_box from .shape import PartInfo, Placed from .spatial import SpatialHash, cell_of, placed_box from .vec import Pose, Vec3, add, distance, length, round_vec, sub, tidy @@ -158,6 +159,25 @@ def occupy(self, registry: Registry, settings: SnapSettings, zone: Box | None = if found is not None and found.residual <= settings.mate_distance: self.taken.add((placed.key, j)) self.ground_taken.add(lattice) + self.covered: dict[tuple[int, int], bool] = {} + + def ground_free(self, lattice: tuple[int, int]) -> bool: + if lattice in self.ground_taken: + return False + known = self.covered.get(lattice) + if known is None: + point = ground.above(lattice) + known = self.covered[lattice] = any(covers(placed, point) for placed in self.placed) + return not known + + +def covers(placed: Placed, point: Vec3) -> bool: + box = body_box(placed.info) + if box is None: + return False + local = placed.pose.inverse().point(point) + lo, hi = box + return all(lo[i] <= local[i] <= hi[i] for i in range(3)) def _grow(box: Box, margin: float) -> Box: @@ -189,7 +209,7 @@ def propose(d: Vec3, rank: tuple[float, str, int, tuple[int, int]]) -> None: propose(found.correction.translation, (placed.order, placed.key, j, (0, 0))) if settings.ground and registry.pair(a.kind, ground.KIND): for lattice, b in ground.studs_near(a.position, settings.reach): - if lattice in index.ground_taken: + if not index.ground_free(lattice): continue found = registry.mate(a, b) if found is not None: @@ -208,7 +228,7 @@ def _pairs(moved: Sequence[Connector], index: _Index, registry: Registry, settin pairs.append(Pair(i, placed.key, placed.order, j)) if settings.ground and registry.pair(a.kind, ground.KIND): lattice, b = ground.nearest(a.position) - if lattice in index.ground_taken: + if not index.ground_free(lattice): continue found = registry.mate(a, b) if found is not None and found.residual <= settings.mate_distance: diff --git a/backend/app/core/settings.py b/backend/app/core/settings.py index 5915ec7..bade24b 100644 --- a/backend/app/core/settings.py +++ b/backend/app/core/settings.py @@ -11,8 +11,10 @@ QUALITIES = ("standard", "low", "high") GRID_STEPS = ("stud", "plate", "fine") RECENT_LIMIT = 30 +RECENT_COLOURS = 12 LIST_LIMIT = 2000 TEXT_LIMIT = 200 +NOT_SWATCHES = (16, 24) DEFAULTS: dict = { "library_folder": None, @@ -23,6 +25,8 @@ "hidden_parts": [], "recent_parts": [], "favourite_colours": [], + "current_colour": 4, + "recent_colours": [], "grid_step": "stud", "snap": True, "overlap": False, @@ -50,9 +54,15 @@ def _texts(name: str, value, limit: int = LIST_LIMIT) -> list[str]: return kept -def _codes(name: str, value) -> list[int]: - if not isinstance(value, list) or len(value) > LIST_LIMIT: - raise SettingsError(f"{name} is a list of at most {LIST_LIMIT} colour numbers.") +def _colour(name: str, value) -> int: + if isinstance(value, bool) or not isinstance(value, int) or value < 0 or value in NOT_SWATCHES: + raise SettingsError(f"{name} is a colour number, 0 or more, and not 16 or 24, which are not colours of their own.") + return value + + +def _codes(name: str, value, limit: int = LIST_LIMIT) -> list[int]: + if not isinstance(value, list) or len(value) > limit: + raise SettingsError(f"{name} is a list of at most {limit} colour numbers.") kept: list[int] = [] for item in value: if isinstance(item, bool) or not isinstance(item, int) or item < 0: @@ -91,6 +101,8 @@ def _folder(name: str, value) -> str | None: "hidden_parts": _texts, "recent_parts": lambda n, v: _texts(n, v, RECENT_LIMIT), "favourite_colours": _codes, + "current_colour": _colour, + "recent_colours": lambda n, v: _codes(n, v, RECENT_COLOURS), "grid_step": lambda n, v: _choice(n, v, GRID_STEPS), "snap": _switch, "overlap": _switch, @@ -164,10 +176,16 @@ def take_notice(self) -> str: def update(self, changes: dict) -> dict: checked = clean(changes) with self.lock: - if any(self.values.get(name) != value for name, value in checked.items()): + changed = sorted(name for name, value in checked.items() if self.values.get(name) != value) + if changed: self.values.update(checked) self.write() - return self.get() + now = self.get() + if changed: + from app.doc import events + + events.publish({"type": "settings", "changed": changed, "settings": now}) + return now def reset(self, names: list[str] | None = None) -> dict: chosen = list(CHECKS) if not names else names diff --git a/backend/app/doc/convert.py b/backend/app/doc/convert.py index beac29e..4870a61 100644 --- a/backend/app/doc/convert.py +++ b/backend/app/doc/convert.py @@ -137,19 +137,19 @@ def _steps_out(model: Model, steps: list[dict]) -> list[Step]: return out -def _state(model: Model, show: dict | None) -> ProjectState: +def _state(model: Model, show: dict | None, library: str | None = None, snap: str | None = None) -> ProjectState: project = model.meta.get("project") or {} - lines = [_record(t) for t in (project.get("camera"), project.get("snap")) if t] + lines = [_record(t) for t in (project.get("camera"), snap or project.get("snap")) if t] state = read_state(lines) state.version = 1 - state.library = project.get("library") + state.library = library or project.get("library") state.colour = project.get("colour") if show and model.submodel(show["submodel"]) is not None: state.show = Show(step=max(1, int(show["step"])), submodel=model.name_of(show["submodel"])) return state -def to_model_file(model: Model, show: dict | None = None) -> ModelFile: +def to_model_file(model: Model, show: dict | None = None, library: str | None = None, snap: str | None = None) -> ModelFile: parts: list = [] for block in model.meta["blocks"]: if "data" in block: @@ -157,7 +157,7 @@ def to_model_file(model: Model, show: dict | None = None) -> ModelFile: continue key = block["model"] sub = model.submodel(key) - state = _state(model, show) if key == model.main else ProjectState(version=None) + state = _state(model, show, library, snap) if key == model.main else ProjectState(version=None) body = ModelBlock(header=_header_out(sub["header"]), state=state, steps=_steps_out(model, sub["steps"])) parts.append(Submodel(sub["name"], body, [_record(t) for t in sub["trailer"]])) main = next((i for i, p in enumerate(parts) if isinstance(p, Submodel) and key_of(p.name) == model.main), None) @@ -166,8 +166,8 @@ def to_model_file(model: Model, show: dict | None = None) -> ModelFile: return ModelFile(parts=parts, was_mpd=not model.meta.get("plain", False)) -def write(model: Model, kind: str, show: dict | None = None) -> bytes: - source = to_model_file(model, show) +def write(model: Model, kind: str, show: dict | None = None, library: str | None = None, snap: str | None = None) -> bytes: + source = to_model_file(model, show, library, snap) if kind == "fblk": return write_model_file(source, project=True, as_mpd=True) if kind == "mpd": diff --git a/backend/app/doc/document.py b/backend/app/doc/document.py index c163531..c56aa7b 100644 --- a/backend/app/doc/document.py +++ b/backend/app/doc/document.py @@ -36,6 +36,7 @@ def __init__(self, store: Path) -> None: self.history = History() self.feed = Feed() self.label: str | None = None + self._told: dict = {} self.model = blank() self.view = fresh_view(self.model) self.load() @@ -82,6 +83,14 @@ def _bump(self, diff: dict | None) -> None: self.feed.record(self.revision, diff) self.save() events.publish({"type": "doc", "revision": self.revision}) + selection = self.selection() + if selection != self._told.get("selection"): + self._told["selection"] = selection + events.publish({"type": "selection", "selection": selection, "count": len(selection), "revision": self.revision}) + where = {"submodel": self.model.name_of(self.editing), "step": self.step, "of": self.model.step_count(self.editing)} + if where != self._told.get("step"): + self._told["step"] = where + events.publish({"type": "step", "editing": [self.model.name_of(k) for k in self.view["editing"]], "revision": self.revision} | where) def _new_serial(self) -> int: value = self.next_serial @@ -183,9 +192,18 @@ def history_labels(self) -> dict: with self.lock: return self.history.labels() + def shows(self) -> dict: + key = self.editing + step = self.step + steps = self.model.submodel(key)["steps"] + drawn = [i for s in steps[:step] for i in s["items"] if isinstance(i, str)] + added = [i for i in steps[step - 1]["items"] if isinstance(i, str)] if steps else [] + return {"submodel": self.model.name_of(key), "step": step, "of": len(steps), "placements": drawn, "added": added} + def state(self) -> dict: return { "selection": self.selection(), + "shows": self.shows(), "step": self.step, "steps": self.model.step_count(self.editing), "submodel": self.model.name_of(self.editing), diff --git a/backend/app/doc/partslist.py b/backend/app/doc/partslist.py new file mode 100644 index 0000000..9918f34 --- /dev/null +++ b/backend/app/doc/partslist.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +from collections import Counter +from collections.abc import Iterator +from dataclasses import dataclass + +from . import transform +from .model import Model + +MAIN_COLOUR = 16 +SCOPES = ("model", "submodel", "step") + + +@dataclass(frozen=True) +class Placed: + part: str + colour: int + position: tuple[float, float, float] + rotation: tuple[float, ...] + + +def _colour(own: int, outer: int) -> int: + return outer if own == MAIN_COLOUR else own + + +def walk(model: Model, key: str, through: int | None = None, colour: int = MAIN_COLOUR, position=(0.0, 0.0, 0.0), rotation=transform.IDENTITY, path: tuple[str, ...] = ()) -> Iterator[Placed]: + if key in path: + return + steps = model.submodel(key)["steps"] + if through is not None: + steps = steps[:through] + for step in steps: + for item in step["items"]: + if not isinstance(item, str): + continue + p = model.placement(item) + here = transform.add(transform.mat_vec(rotation, p["position"]), position) + turn = transform.mat_mul(rotation, p["rotation"]) + shade = _colour(p["colour"], colour) + inner = model.find(p["part"]) + if inner is not None: + yield from walk(model, inner, None, shade, here, turn, path + (key,)) + else: + yield Placed(p["part"], shade, tuple(here), tuple(turn)) + + +def scope_key(doc, scope: str) -> tuple[str, int | None]: + if scope == "submodel": + return doc.editing, None + if scope == "step": + return doc.editing, doc.step + return doc.model.main, None + + +def counts(model: Model, key: str, through: int | None = None) -> Counter: + return Counter((p.part.lower(), p.colour) for p in walk(model, key, through)) diff --git a/backend/app/doc/views.py b/backend/app/doc/views.py index 555e6c0..ca91f04 100644 --- a/backend/app/doc/views.py +++ b/backend/app/doc/views.py @@ -2,6 +2,8 @@ from collections import Counter +from app.mesh.scene import scene_matrix + from .model import META, PLACE, SUB, Model @@ -31,6 +33,7 @@ def placement_json(model: Model, pid: str) -> dict: "colour": p["colour"], "position": p["position"], "rotation": p["rotation"], + "matrix": scene_matrix(p["position"], p["rotation"]), "hidden": p["hidden"], "open": p["open"], "use": model.is_use(p["part"]), diff --git a/backend/app/library/HASHOUT_LOG.md b/backend/app/library/HASHOUT_LOG.md index dfc0b5a..5c8687e 100644 --- a/backend/app/library/HASHOUT_LOG.md +++ b/backend/app/library/HASHOUT_LOG.md @@ -2,6 +2,14 @@ Reasons for the parts library service, newest first. +## The fetch names the engine's version from one place · 0.3.0 (download.py) + +The download's user agent was the literal `FormBlocks/0.2.0`, a version site that the release's hand bump of `CLAUDE.md`'s list did not name, so it would have gone on saying 0.2.0. It is now made from `app.__version__`, which the release bumps, so the library's server is told the version that is running. Checked in process: `FormBlocks/0.2.0` before the release commit, from the one site. + +## An empty search inside a list answers the list · 0.3.0 (search.py) + +`SPEC.md` 2.3 has the search cover every list, and with nothing typed a list is simply its parts. The search answered an empty query with no hits outside a category, so the parts palette had to fill Favourites, Recent and Hidden one `GET /api/parts/{name}` at a time. With no words and no number, a `within` list now answers its own parts in the list's order (newest first for Recent, as the settings keep them), each name once, moved numbers followed as in any hit, hidden parts still left out of the other lists; a name the library does not have is left out, as a search leaves it out. Printed parts are not filtered here: the person put them in the list. With words typed nothing changes. Checked in process on the 2026-10 library: `['3001', '3023', '3626bp01', '99999', '3001.dat']` answered 3001, 3023 (moved to 3023b) and 3626bp01 in that order; an empty query in Brick still gave 426 parts and an empty query over everything none. + ## A fetch is used once it is done · 0.2.0 (service.py) The folder named in settings is looked for before the fetched one, so a person who had pointed FormBlocks at a folder and then fetched the library kept working from the old folder. Fetching is the person's latest choice, so a successful fetch now clears the folder setting in the service and locates again; `status` then reports the source `fetched`, and the engine must write the cleared setting back to the settings file. A folder named by `FORMBLOCKS_LDRAW_DIR` still comes first, since the environment is set outside the app on purpose. @@ -80,7 +88,7 @@ The standard library's `urllib` is enough and honours the system's proxy setting ## Search and its ranking · 0.2.0 (search.py) -The ranks are those of `spec/SPEC.md` 2.3: the exact part number, then numbers that start with what was typed, then parts whose description holds every word, then parts that match only once keywords, category and number are added; within a rank the shorter description (runs of spaces counted as one) and then the natural number order. Only a query with no space is tried as a number, and `3023.dat` counts as `3023`. Files the palette does not list (moved, alias, obsolete, third-party, physical colour) are found only by their exact number, and a moved file's hit carries its final target's description so the palette can show the pointer. Printed parts are left out unless asked for, except on an exact number. `within` limits a search to Favourites, Recent or Hidden, which the settings hold, and `exclude` takes out parts the person hid; an empty query with a category lists that category in natural order. Keywords that name another catalogue (`BrickLink 3023`) are searchable as written, as `spec/LDRAW.md` asks, so a prefix such as `brick` also reaches them, but only in the last rank. +The ranks are those of `spec/SPEC.md` 2.3: the exact part number, then numbers that start with what was typed, then parts whose description holds every word, then parts that match only once keywords, category and number are added; within a rank the shorter description (runs of spaces counted as one) and then the natural number order. Only a query with no space is tried as a number, and `3023.dat` counts as `3023`. Files the palette does not list (moved, alias, obsolete, third-party, physical colour) are found only by their exact number, and a moved file's hit carries its final target's description so the palette can show the pointer. Printed parts are left out unless asked for, except on an exact number. `within` limits a search to Favourites, Recent or Hidden, which the settings hold, and `exclude` takes out parts the person hid; an empty query with a category lists that category in natural order. Keywords that give another catalogue's name and number are searchable as written, as `spec/LDRAW.md` asks, so a prefix such as `brick` also reaches them, but only in the last rank. ## The index saved once, rebuilt when the library changes · 0.2.0 (indexstore.py) diff --git a/backend/app/library/download.py b/backend/app/library/download.py index e390af2..dd64ee8 100644 --- a/backend/app/library/download.py +++ b/backend/app/library/download.py @@ -10,7 +10,9 @@ from dataclasses import dataclass from pathlib import Path -USER_AGENT = "FormBlocks/0.2.0" +from app import __version__ + +USER_AGENT = f"FormBlocks/{__version__}" CHUNK = 1024 * 1024 MAX_ARCHIVE = 1024 * 1024 * 1024 TIMEOUT = 60 diff --git a/backend/app/library/search.py b/backend/app/library/search.py index bdbac8b..74fae39 100644 --- a/backend/app/library/search.py +++ b/backend/app/library/search.py @@ -78,10 +78,13 @@ def search( number = _number_query(text) words = tokens(text) wanted_category = category.strip().lower() - inside = {part_number(item) for item in within} if within is not None else None + order = list(dict.fromkeys(part_number(item) for item in within)) if within is not None else [] + inside = set(order) if within is not None else None + browsing = inside is not None and not number and not words hidden = {part_number(item) for item in exclude} if exclude else set() + ranks = {name: RANK_DESCRIPTION for name in order} if browsing else _ranked(index, number, words, wanted_category) hits: list[Hit] = [] - for found_number, rank in _ranked(index, number, words, wanted_category).items(): + for found_number, rank in ranks.items(): entry = index.get(found_number) if entry is None: continue @@ -91,12 +94,12 @@ def search( continue if wanted_category and entry.category.lower() != wanted_category: continue - if entry.printed and not include_printed and rank != RANK_NUMBER: + if entry.printed and not include_printed and rank != RANK_NUMBER and not browsing: continue target = index.follow(entry.number) if entry.kind == KIND_MOVED else None hits.append(Hit(entry, rank, target)) if number or words: hits.sort(key=lambda hit: (hit.rank, len(collapse(hit.entry.description)), natural_key(hit.entry.number))) - else: + elif not browsing: hits.sort(key=lambda hit: (natural_key(hit.entry.description), natural_key(hit.entry.number))) return hits if limit is None else hits[: max(0, limit)] diff --git a/backend/app/main.py b/backend/app/main.py index 7a80713..08e26ec 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -30,6 +30,7 @@ ("app.routers.library", "/api/library"), ("app.routers.parts", "/api/parts"), ("app.routers.colours", "/api/colours"), + ("app.routers.place", "/api/place"), ("app.routers.mcp", ""), ] diff --git a/backend/app/mesh/HASHOUT_LOG.md b/backend/app/mesh/HASHOUT_LOG.md index 02df099..5dc383a 100644 --- a/backend/app/mesh/HASHOUT_LOG.md +++ b/backend/app/mesh/HASHOUT_LOG.md @@ -2,6 +2,10 @@ Reasons behind the part flattener and its cache, newest first. The rules it follows are in `spec/LDRAW.md` ("Back-face culling", "What the flattener does", "The one conversion to a +Y-up scene"); this log holds only the choices made while writing the code. +## A ray against a part's real triangles · 0.3.0 (ray.py, __init__.py) + +The connection lane's `first_hit` meets placement boxes, so a pointer over a slope's empty wedge or between a wheel's spokes hit air. `Triangles.of(mesh)` keeps a part's triangles as a first corner and two edge vectors in float64, with unit normals and the mesh's box, made once per part and reused for every placement of it; `hit` is the Moller and Trumbore test run over all of them at once with numpy, both faces counted, since picking is about what the eye sees and a back face seen through a gap still stops the pointer. The box test first turns away a ray that misses the part. `hit_placed` turns the ray into the part's own scene axes with `placement_to_scene`, so the window's ray and the answer stay in scene axes and the one conversion is still this package's; the normal goes back with the inverse transpose and is turned to face the ray. `box_entries` gives, for many boxes at once, the distance at which a ray enters each, or infinity, the broad phase a model of thousands of placements needs before any triangle is tested. Checked on the 2026-10 library with a 3001 at LDraw (0, -24, 0): a ray down at scene (0, 0) met the top face at y = 24 with normal +y, one at (10, 10) met a stud top at y = 28, one along -z met the side at z = 20 with normal +z, one pointing up met nothing; each in under 1 ms over 700 triangles. + ## An empty part name is refused before any lookup · 0.2.0 (flatten.py, errors.py) An empty name, or one that is only spaces or quotes, used to become `.dat` and fail as "`.dat` was not found", which tells the person nothing and also made a cache entry name out of nothing. `part_mesh` and `flatten` now check the name and the quality together before touching the library, and a blank name gives the plain sentence "no part name was given" without the "part ... cannot be flattened" frame that would print an empty name. Checked with an empty name, spaces, a pair of quotes, an unknown quality and an unknown part. diff --git a/backend/app/mesh/__init__.py b/backend/app/mesh/__init__.py index a3e57df..02d4f81 100644 --- a/backend/app/mesh/__init__.py +++ b/backend/app/mesh/__init__.py @@ -2,6 +2,7 @@ from .errors import MeshError from .flatten import flatten, part_mesh from .mesh import Group, PartMesh +from .ray import RayHit, Triangles, box_entries, hit_placed from .scene import TO_SCENE, from_scene, placement_from_scene, placement_to_scene, to_scene __all__ = [ @@ -9,9 +10,13 @@ "LayoutError", "MeshError", "PartMesh", + "RayHit", "TO_SCENE", + "Triangles", + "box_entries", "flatten", "from_scene", + "hit_placed", "part_mesh", "placement_from_scene", "placement_to_scene", diff --git a/backend/app/mesh/ray.py b/backend/app/mesh/ray.py new file mode 100644 index 0000000..fd5dfca --- /dev/null +++ b/backend/app/mesh/ray.py @@ -0,0 +1,111 @@ +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np + +from .mesh import PartMesh +from .scene import placement_to_scene + +PARALLEL = 1e-12 +EDGE = 1e-9 + + +@dataclass(frozen=True, eq=False) +class Triangles: + first: np.ndarray + one: np.ndarray + two: np.ndarray + normals: np.ndarray + low: np.ndarray + high: np.ndarray + + @classmethod + def of(cls, mesh: PartMesh) -> Triangles: + corners = np.asarray(mesh.positions, dtype=np.float64).reshape(-1, 3, 3) + first = corners[:, 0] + one = corners[:, 1] - first + two = corners[:, 2] - first + raw = np.cross(one, two) + size = np.linalg.norm(raw, axis=1) + size[size < PARALLEL] = 1.0 + if len(corners): + low, high = corners.min(axis=(0, 1)), corners.max(axis=(0, 1)) + else: + low = high = np.zeros(3) + return cls(first, one, two, raw / size[:, None], low, high) + + def __len__(self) -> int: + return len(self.first) + + +@dataclass(frozen=True) +class RayHit: + distance: float + point: tuple[float, float, float] + normal: tuple[float, float, float] + triangle: int + + +def hit(triangles: Triangles, origin, direction) -> RayHit | None: + if not len(triangles): + return None + o = np.asarray(origin, dtype=np.float64) + d = np.asarray(direction, dtype=np.float64) + if not np.isfinite(box_entries(triangles.low[None], triangles.high[None], o, d)[0]): + return None + p = np.cross(d, triangles.two) + det = np.einsum("ij,ij->i", triangles.one, p) + usable = np.abs(det) > PARALLEL + inv = np.zeros_like(det) + inv[usable] = 1.0 / det[usable] + s = o - triangles.first + u = np.einsum("ij,ij->i", s, p) * inv + q = np.cross(s, triangles.one) + v = (q @ d) * inv + t = np.einsum("ij,ij->i", triangles.two, q) * inv + good = usable & (u >= -EDGE) & (v >= -EDGE) & (u + v <= 1 + EDGE) & (t > EDGE) + if not np.any(good): + return None + index = int(np.flatnonzero(good)[np.argmin(t[good])]) + distance = float(t[index]) + normal = triangles.normals[index] + if float(normal @ d) > 0: + normal = -normal + point = o + d * distance + return RayHit(distance, tuple(point.tolist()), tuple(normal.tolist()), index) + + +def hit_placed(triangles: Triangles, position, matrix, origin, direction) -> RayHit | None: + transform = placement_to_scene(tuple(position), tuple(matrix)) + rotation = transform[:3, :3] + back = np.linalg.inv(rotation) + o = back @ (np.asarray(origin, dtype=np.float64) - transform[:3, 3]) + d = back @ np.asarray(direction, dtype=np.float64) + scale = float(np.linalg.norm(d)) + if scale < PARALLEL: + return None + found = hit(triangles, o, d / scale) + if found is None: + return None + point = rotation @ np.asarray(found.point) + transform[:3, 3] + normal = back.T @ np.asarray(found.normal) + normal = normal / max(float(np.linalg.norm(normal)), PARALLEL) + distance = float(np.linalg.norm(point - np.asarray(origin, dtype=np.float64))) + return RayHit(distance, tuple(point.tolist()), tuple(normal.tolist()), found.triangle) + + +def box_entries(lows: np.ndarray, highs: np.ndarray, origin, direction) -> np.ndarray: + o = np.asarray(origin, dtype=np.float64) + d = np.asarray(direction, dtype=np.float64) + flat = np.abs(d) < PARALLEL + safe = np.where(flat, 1.0, d) + a = (lows - o) / safe + b = (highs - o) / safe + outside = np.any(flat & ((o < lows) | (o > highs)), axis=1) + a = np.where(flat, -np.inf, a) + b = np.where(flat, np.inf, b) + near = np.max(np.minimum(a, b), axis=1) + far = np.min(np.maximum(a, b), axis=1) + entry = np.maximum(near, 0.0) + return np.where(outside | (far < entry), np.inf, entry) diff --git a/backend/app/mesh/scene.py b/backend/app/mesh/scene.py index cfb3704..26b39a3 100644 --- a/backend/app/mesh/scene.py +++ b/backend/app/mesh/scene.py @@ -23,6 +23,10 @@ def placement_to_scene(position: tuple[float, float, float], matrix: tuple[float return out +def scene_matrix(position, matrix) -> list[float]: + return [round(float(v), 9) + 0.0 for v in placement_to_scene(tuple(position), tuple(matrix)).reshape(16)] + + def placement_from_scene(transform: np.ndarray) -> tuple[tuple[float, float, float], tuple[float, ...]]: transform = np.asarray(transform, dtype=np.float64).reshape(4, 4) rotation = TO_SCENE @ transform[:3, :3] @ TO_SCENE diff --git a/backend/app/routers/doc.py b/backend/app/routers/doc.py index dcb3303..f791711 100644 --- a/backend/app/routers/doc.py +++ b/backend/app/routers/doc.py @@ -1,9 +1,10 @@ -from fastapi import APIRouter, Query +from fastapi import APIRouter, Query, Response from fastapi.concurrency import run_in_threadpool from pydantic import BaseModel, Field from app.cmd import runner from app.doc.document import document +from app.services import model_info router = APIRouter(tags=["doc"]) @@ -17,6 +18,45 @@ def read() -> dict: return document().snapshot() +def _tree() -> dict: + doc = document() + with doc.lock: + return model_info.tree(doc) + + +@router.get("/doc/tree") +async def tree() -> dict: + return await run_in_threadpool(_tree) + + +def _info() -> dict: + doc = document() + with doc.lock: + return model_info.info(doc) + + +@router.get("/doc/info") +async def info() -> dict: + return await run_in_threadpool(_info) + + +def _parts_csv(scope: str, group: str, separator: str) -> str: + doc = document() + with doc.lock: + return model_info.parts_csv(model_info.parts_rows(doc, scope, group), separator) + + +@router.get("/doc/parts.csv") +async def parts_csv( + scope: str = Query("model", pattern="^(model|submodel|step)$"), + group: str = Query("part", pattern="^(part|colour)$"), + separator: str = Query("comma", pattern="^(comma|tab)$"), +) -> Response: + text = await run_in_threadpool(_parts_csv, scope, group, separator) + kind = "text/tab-separated-values" if separator == "tab" else "text/csv" + return Response(text.encode("utf-8"), media_type=kind + "; charset=utf-8") + + @router.get("/doc/changes") def changes(since: int = Query(..., ge=0)) -> dict: return document().changes(since) diff --git a/backend/app/routers/live.py b/backend/app/routers/live.py index 7668d5a..5588f04 100644 --- a/backend/app/routers/live.py +++ b/backend/app/routers/live.py @@ -39,6 +39,28 @@ async def send(self, message: dict) -> None: hub = Hub() +def greeting() -> list[dict]: + from app.core import settings + from app.services import library_host + + doc = document() + with doc.lock: + revision = doc.revision + selection = doc.selection() + shows = doc.shows() + editing = [doc.model.name_of(k) for k in doc.view["editing"]] + job = library_host.job() + told = [ + {"type": "doc", "revision": revision}, + {"type": "selection", "selection": selection, "count": len(selection), "revision": revision}, + {"type": "step", "editing": editing, "revision": revision, "submodel": shows["submodel"], "step": shows["step"], "of": shows["of"]}, + {"type": "settings", "changed": [], "settings": settings.store().get()}, + ] + if job["running"]: + told.append({"type": "library", "stage": "fetch", "step": job["stage"], "done": job["done"], "total": job["total"]}) + return told + + @router.websocket("/live") async def live(socket: WebSocket) -> None: if len(hub.clients) >= MAX_CLIENTS: @@ -47,7 +69,8 @@ async def live(socket: WebSocket) -> None: await socket.accept() hub.clients.add(socket) try: - await socket.send_json({"type": "doc", "revision": document().revision}) + for message in greeting(): + await socket.send_json(message) while True: await socket.receive_text() except WebSocketDisconnect: diff --git a/backend/app/routers/place.py b/backend/app/routers/place.py new file mode 100644 index 0000000..2d88c79 --- /dev/null +++ b/backend/app/routers/place.py @@ -0,0 +1,112 @@ +import math +from typing import Annotated + +from fastapi import APIRouter, HTTPException +from fastapi.concurrency import run_in_threadpool +from pydantic import AfterValidator, BaseModel, Field + +from app.cmd import args, fitting, placing +from app.cmd.registry import CommandError +from app.doc.document import document +from app.services import connect_host, picking, warmer + +router = APIRouter(tags=["place"]) +warmer.start() + + +def _finite(values: list[float]) -> list[float]: + if not all(math.isfinite(v) for v in values): + raise ValueError("every number must be finite") + return values + + +Vector = Annotated[list[float], Field(min_length=3, max_length=3), AfterValidator(_finite)] +Matrix = Annotated[list[float], Field(min_length=9, max_length=9), AfterValidator(_finite)] + + +class Ray(BaseModel): + origin: Vector + dir: Vector + + +class PreviewBody(BaseModel): + part: str = Field(min_length=1, max_length=args.NAME_MAX) + colour: int = Field(ge=0) + ray: Ray + rotation: Matrix | None = None + held: int | None = Field(None, ge=0) + ids: list[str] = Field(default_factory=list, max_length=args.ID_MAX) + snap: bool | None = None + + +class DragBody(BaseModel): + grab: str = Field(min_length=1, max_length=40) + ray: Ray + rotation: Matrix | None = None + held: int | None = Field(None, ge=0) + ids: list[str] = Field(default_factory=list, max_length=args.ID_MAX) + snap: bool | None = None + copies: bool = Field(False, alias="copy") + + +def drag(body: DragBody) -> dict: + doc = document() + with doc.lock: + found = placing.drag(doc, doc.editing, body.grab, body.ray.origin, body.ray.dir, body.rotation, body.held, body.ids or None, body.snap, stamp=fitting.stamp_of(doc), copy=body.copies) + return placing.drag_answer(found) | {"revision": doc.revision} + + +@router.post("/drag") +async def read_drag(body: DragBody) -> dict: + try: + return await run_in_threadpool(drag, body) + except CommandError as exc: + raise HTTPException(status_code=422, detail=str(exc)) + + +class PickBody(BaseModel): + ray: Ray + ground: bool = True + + +def preview(body: PreviewBody) -> dict: + doc = document() + with doc.lock: + found = placing.attempt( + doc, + doc.editing, + body.part, + body.ray.origin, + body.ray.dir, + body.rotation, + body.held, + body.ids, + body.snap, + stamp=fitting.stamp_of(doc), + ) + return placing.answer(found) | {"colour": body.colour, "revision": doc.revision} + + +def pick(body: PickBody) -> dict: + doc = document() + with doc.lock: + key = doc.editing + stamp = fitting.stamp_of(doc) + found = picking.pick(doc.model, key, body.ray.origin, body.ray.dir, skip=connect_host.hidden(doc.model, key, stamp), stamp=stamp, ground=body.ground) + return {"hit": None if found is None else found.as_dict(), "revision": doc.revision} + + +@router.post("/preview") +async def read_preview(body: PreviewBody) -> dict: + try: + return await run_in_threadpool(preview, body) + except CommandError as exc: + raise HTTPException(status_code=422, detail=str(exc)) + + +@router.post("/pick") +async def read_pick(body: PickBody) -> dict: + try: + return await run_in_threadpool(pick, body) + except CommandError as exc: + raise HTTPException(status_code=422, detail=str(exc)) diff --git a/backend/app/routers/settings.py b/backend/app/routers/settings.py index 7f95c66..62589a8 100644 --- a/backend/app/routers/settings.py +++ b/backend/app/routers/settings.py @@ -23,7 +23,6 @@ def change(body: dict) -> dict: library_host.use(checked.pop("library_folder")) values = settings.store().update(checked) library_host.apply_settings(values) - library_host.publish({"type": "settings"}) return shown() diff --git a/backend/app/services/connect_host.py b/backend/app/services/connect_host.py index 555a4d5..182403f 100644 --- a/backend/app/services/connect_host.py +++ b/backend/app/services/connect_host.py @@ -6,6 +6,7 @@ _LOCK = threading.RLock() _HELD: dict = {"library": None, "service": None, "hashes": {}} +_HIDDEN: dict = {} def service() -> ConnectService: @@ -32,30 +33,41 @@ def __init__(self, held: ConnectService, library_key: str) -> None: self.seen: dict[str, tuple] = {} self.service = held self.library_key = library_key + self.stamp = None -def hash_of(model, key: str) -> SpatialHash: +def hash_of(model, key: str, stamp=None) -> SpatialHash: held = service() library_key = held.library_key() with _LOCK: hashes = _HELD["hashes"] + tracked = hashes.get(key) + if stamp is not None and tracked is not None and tracked.stamp == stamp and tracked.service is held and tracked.library_key == library_key: + return tracked.hash for gone in [k for k in hashes if model.submodel(k) is None]: del hashes[gone] - tracked = hashes.get(key) if tracked is None or tracked.service is not held or tracked.library_key != library_key: tracked = hashes[key] = Tracked(held, library_key) current: dict[str, tuple] = {} for order, pid in enumerate(model.ids(key)): record = model.placement(pid) - stamp = (order, record["part"], tuple(record["position"]), tuple(record["rotation"])) - current[pid] = stamp - if tracked.seen.get(pid) != stamp: + seen = (order, record["part"], tuple(record["position"]), tuple(record["rotation"])) + current[pid] = seen + if tracked.seen.get(pid) != seen: tracked.hash.put(Placed.of(pid, order, pose_of(record), held.info(record["part"]))) for pid in [pid for pid in tracked.seen if pid not in current]: tracked.hash.remove(pid) tracked.seen = current + tracked.stamp = stamp return tracked.hash -def hidden(model, key: str) -> list[str]: - return [pid for pid in model.ids(key) if model.placement(pid)["hidden"]] +def hidden(model, key: str, stamp=None) -> list[str]: + with _LOCK: + known = _HIDDEN.get(key) + if stamp is not None and known is not None and known[0] == stamp: + return list(known[1]) + found = [pid for pid in model.ids(key) if model.placement(pid)["hidden"]] + with _LOCK: + _HIDDEN[key] = (stamp, found) + return list(found) diff --git a/backend/app/services/library_host.py b/backend/app/services/library_host.py index e5c0ab1..58574e1 100644 --- a/backend/app/services/library_host.py +++ b/backend/app/services/library_host.py @@ -148,6 +148,20 @@ def use(folder: str | None) -> dict: return status() +def update_name() -> str | None: + held = service() + try: + if held.library() is None: + return None + manifest = held.manifest() + found = held.library() + if manifest is not None and found is not None and Path(manifest.folder) == found.root and manifest.release: + return manifest.release + return held.index().release or None + except NoLibrary: + return None + + class Busy(RuntimeError): pass diff --git a/backend/app/services/model_info.py b/backend/app/services/model_info.py new file mode 100644 index 0000000..9c0f46f --- /dev/null +++ b/backend/app/services/model_info.py @@ -0,0 +1,192 @@ +from __future__ import annotations + +import csv +import io + +from app.connect import Pose, placed_box +from app.doc import partslist, views +from app.library import NoLibrary +from app.library.names import part_number +from app.services import connect_host, library_host + +LDU_MM = 0.4 +STUD = 20.0 +BRICK = 24.0 +PLATE = 8.0 +GROUPS = ("part", "colour") +SEPARATORS = {"comma": ",", "tab": "\t"} +CSV_HEADER = ("Part", "Description", "Colour", "Colour name", "Count") + + +class Labels: + def __init__(self) -> None: + held = library_host.service() + self.index = None + self.colours = None + try: + if held.library() is not None: + self.index = held.index_if_ready() + self.colours = held.colours() + if self.index is None: + library_host.warm() + except (NoLibrary, OSError): + pass + + def part(self, name: str) -> dict: + entry = None if self.index is None else self.index.get(name) + target = None if self.index is None else self.index.follow(name) + shown = target if target is not None else entry + return { + "number": part_number(name), + "description": " ".join(shown.description.split()) if shown is not None else "", + "movedTo": target.number if target is not None and entry is not None and target is not entry else None, + "missing": None if self.index is None else entry is None, + "printed": bool(shown is not None and shown.printed), + } + + def colour(self, code: int) -> dict: + if self.colours is None: + return {"colourName": "", "colourValue": None} + found = self.colours.describe(code) + return {"colourName": found.label, "colourValue": found.value} + + +def _row(model, labels: Labels, pid: str, step: int) -> dict: + p = model.placement(pid) + use = model.find(p["part"]) + row = {"id": pid, "part": p["part"], "colour": p["colour"], "step": step, "hidden": p["hidden"], "open": p["open"]} + if use is not None: + sub = model.submodel(use) + row |= {"use": sub["name"], "number": sub["name"], "description": views.title_of(sub), "missing": False, "printed": False} + else: + row |= {"use": None} | labels.part(p["part"]) + return row | labels.colour(p["colour"]) + + +def tree(doc) -> dict: + m = doc.model + labels = Labels() + counts = views.use_counts(m) + submodels = {} + for key in m.keys(): + sub = m.submodel(key) + steps = [] + for number, step in enumerate(sub["steps"], 1): + rows = [_row(m, labels, item, number) for item in step["items"] if isinstance(item, str)] + steps.append({"number": number, "name": step["name"], "rows": rows}) + submodels[sub["name"]] = { + "name": sub["name"], + "title": views.title_of(sub), + "main": key == m.main, + "uses": counts.get(key, 0), + "unused": key != m.main and not counts.get(key), + "steps": steps, + } + return { + "root": m.name_of(doc.editing), + "main": m.name_of(m.main), + "order": [m.name_of(k) for k in m.keys()], + "editing": [m.name_of(k) for k in doc.view["editing"]], + "step": doc.step, + "selection": doc.selection(), + "libraryReady": labels.index is not None, + "submodels": submodels, + "revision": doc.revision, + } + + +def parts_rows(doc, scope: str = "model", group: str = "part") -> list[dict]: + key, through = partslist.scope_key(doc, scope) + return rows_for(doc.model, key, through, group) + + +def rows_for(model, key: str, through: int | None = None, group: str = "part") -> list[dict]: + labels = Labels() + rows = [] + for (part, colour), count in partslist.counts(model, key, through).items(): + rows.append({"part": part, **labels.part(part), "colour": colour, **labels.colour(colour), "count": count}) + + def order(row: dict): + part = (row["number"].lower(), row["part"]) + return (0 if row["missing"] else 1, *((part, row["colour"]) if group == "part" else (row["colour"], part))) + + rows.sort(key=order) + return rows + + +def parts_csv(rows: list[dict], separator: str = "comma") -> str: + out = io.StringIO() + writer = csv.writer(out, delimiter=SEPARATORS[separator], quoting=csv.QUOTE_MINIMAL, lineterminator="\r\n") + writer.writerow(CSV_HEADER) + for row in rows: + writer.writerow((row["number"], row["description"], row["colour"], row["colourName"], row["count"])) + return out.getvalue() + + +def _header_line(sub: dict, word: str) -> str: + mark = "0 %s" % word + for line in sub["header"]: + if isinstance(line, str) and line.lower().startswith(mark.lower()): + return line[len(mark) :].strip() + return "" + + +def size(doc) -> dict | None: + low = [float("inf")] * 3 + high = [float("-inf")] * 3 + try: + held = connect_host.service() + for placed in partslist.walk(doc.model, doc.model.main): + box = placed_box(Pose.from_ldraw(placed.position, placed.rotation), held.info(placed.part).shape.bounds) + if box is None: + continue + for i in range(3): + low[i] = min(low[i], box[0][i]) + high[i] = max(high[i], box[1][i]) + except NoLibrary: + return None + if low[0] == float("inf"): + return None + across, tall, deep = (high[i] - low[i] for i in range(3)) + return { + "ldu": {"across": across, "deep": deep, "high": tall}, + "studs": {"across": round(across / STUD, 2), "deep": round(deep / STUD, 2)}, + "bricks": round(tall / BRICK, 2), + "plates": round(tall / PLATE, 2), + "mm": {"across": round(across * LDU_MM, 1), "deep": round(deep * LDU_MM, 1), "high": round(tall * LDU_MM, 1)}, + "box": {"min": low, "max": high}, + } + + +def info(doc) -> dict: + m = doc.model + main = m.submodel(m.main) + rows = parts_rows(doc) + project = m.meta.get("project") or {} + status = library_host.service().status() + ready = Labels().index + if status["update"] == "unknown" and ready is not None and ready.release: + status["update"] = ready.release + return { + "name": main["name"], + "title": views.title_of(main), + "author": _header_line(main, "Author:"), + "licence": _header_line(main, "!LICENSE").removeprefix("Licensed under ").strip(), + "path": doc.file, + "kind": doc.file_kind, + "builtWith": project.get("library"), + "library": status["update"] if status["installed"] else None, + "counts": { + "parts": sum(r["count"] for r in rows), + "differentParts": len({r["part"] for r in rows}), + "pairs": len(rows), + "missing": sum(r["count"] for r in rows if r["missing"]), + "submodels": len(m.keys()) - 1, + "steps": m.step_count(m.main), + "placements": len(m.all_ids()), + }, + "size": size(doc), + "partsList": rows, + "csv": parts_csv(rows), + "revision": doc.revision, + } diff --git a/backend/app/services/picking.py b/backend/app/services/picking.py new file mode 100644 index 0000000..3d84f71 --- /dev/null +++ b/backend/app/services/picking.py @@ -0,0 +1,156 @@ +from __future__ import annotations + +import threading +from collections import OrderedDict +from dataclasses import dataclass + +import numpy as np + +from app.connect import Hit, Pose, ground_hit, placed_box +from app.doc import partslist +from app.mesh import MeshError, Triangles, box_entries, from_scene, hit_placed, part_mesh, to_scene +from app.services import connect_host, library_host + +KEEP_PARTS = 512 +_LOCK = threading.Lock() +_TRIANGLES: OrderedDict = OrderedDict() +_BOXES: dict = {} + + +@dataclass(frozen=True) +class Picked: + key: str | None + point: tuple[float, float, float] + normal: tuple[float, float, float] + distance: float + + @property + def on_ground(self) -> bool: + return self.key is None + + def as_dict(self) -> dict: + return { + "on": self.key or "ground", + "point": [round(v, 4) for v in self.point], + "normal": [round(v, 6) for v in self.normal], + "distance": round(self.distance, 4), + } + + def ldraw(self) -> Hit: + point = from_scene(np.asarray([self.point], dtype=np.float64))[0] + normal = from_scene(np.asarray([self.normal], dtype=np.float64))[0] + return Hit(tuple(point.tolist()), tuple(normal.tolist()), self.key, self.distance) + + +def triangles(part: str) -> Triangles | None: + held = library_host.service() + marker = (id(held), held.quality.value, part.lower()) + with _LOCK: + found = _TRIANGLES.get(marker) + if found is not None: + _TRIANGLES.move_to_end(marker) + return found + try: + made = Triangles.of(part_mesh(held, part, held.quality.value)) + except (MeshError, OSError, ValueError): + return None + with _LOCK: + _TRIANGLES[marker] = made + while len(_TRIANGLES) > KEEP_PARTS: + _TRIANGLES.popitem(last=False) + return made + + +@dataclass(frozen=True) +class Item: + key: str + part: str + pose: Pose + bounds: tuple | None + + +def _items(model, key: str, hash_) -> list[Item]: + held = connect_host.service() + found = [] + for placed in hash_.all(): + record = model.placement(placed.key) + inner = None if record is None else model.find(record["part"]) + if inner is None: + found.append(Item(placed.key, placed.info.name, placed.pose, placed.shape.bounds)) + continue + for part in partslist.walk(model, inner, None, record["colour"], record["position"], record["rotation"], (key,)): + found.append(Item(placed.key, part.part, Pose.from_ldraw(part.position, part.rotation), held.info(part.part).shape.bounds)) + return found + + +class Boxes: + def __init__(self, items: list[Item]) -> None: + kept = [] + lows, highs = [], [] + for item in items: + box = placed_box(item.pose, item.bounds) + if box is None: + continue + corners = to_scene(np.asarray(box, dtype=np.float64)) + lows.append(corners.min(axis=0)) + highs.append(corners.max(axis=0)) + kept.append(item) + self.placed = kept + self.lows = np.asarray(lows, dtype=np.float64).reshape(-1, 3) + self.highs = np.asarray(highs, dtype=np.float64).reshape(-1, 3) + + +def boxes(model, key: str, stamp) -> Boxes: + hash_ = connect_host.hash_of(model, key, stamp) + marker = (id(hash_), stamp) + with _LOCK: + known = _BOXES.get(key) + if stamp is not None and known is not None and known[0] == marker: + return known[1] + made = Boxes(_items(model, key, hash_)) + with _LOCK: + _BOXES[key] = (marker, made) + return made + + +def pick_ldraw(model, key: str, origin, direction, skip=(), stamp=None) -> Hit | None: + turned = to_scene(np.asarray([origin, direction], dtype=np.float64)) + found = pick(model, key, turned[0], turned[1], skip=skip, stamp=stamp) + return None if found is None else found.ldraw() + + +def pick(model, key: str, origin, direction, skip=(), stamp=None, ground: bool = True) -> Picked | None: + o = np.asarray(origin, dtype=np.float64) + d = np.asarray(direction, dtype=np.float64) + size = float(np.linalg.norm(d)) + if size < 1e-12: + return None + d = d / size + held = boxes(model, key, stamp) + left_out = set(skip) + best: Picked | None = None + if len(held.placed): + entries = box_entries(held.lows, held.highs, o, d) + for index in np.argsort(entries, kind="stable"): + entry = float(entries[index]) + if not np.isfinite(entry) or best is not None and entry > best.distance: + break + item = held.placed[int(index)] + if item.key in left_out: + continue + shape = triangles(item.part) + if shape is None: + continue + found = hit_placed(shape, item.pose.translation, item.pose.rotation, o, d) + if found is not None and (best is None or found.distance < best.distance): + best = Picked(item.key, found.point, found.normal, found.distance) + if best is not None or not ground: + return best + o_ld = from_scene(o[None])[0] + d_ld = from_scene(d[None])[0] + floor = ground_hit(tuple(o_ld.tolist()), tuple(d_ld.tolist())) + if floor is None: + return None + point = to_scene(np.asarray([floor.point], dtype=np.float64))[0] + normal = to_scene(np.asarray([floor.normal], dtype=np.float64))[0] + return Picked(None, tuple(point.tolist()), tuple(normal.tolist()), float(floor.distance)) diff --git a/backend/app/services/warmer.py b/backend/app/services/warmer.py new file mode 100644 index 0000000..332755e --- /dev/null +++ b/backend/app/services/warmer.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +import logging +import threading + +from app.doc import events + +log = logging.getLogger("formblocks.warmer") +_WAKE = threading.Event() +_STATE: dict = {"thread": None, "started": False} +_LOCK = threading.Lock() + + +def _warm_once() -> None: + from app.cmd import fitting + from app.doc.document import document + from app.library import NoLibrary + from app.services import connect_host, picking + + doc = document() + try: + with doc.lock: + key = doc.editing + stamp = fitting.stamp_of(doc) + parts = {item.part for item in picking.boxes(doc.model, key, stamp).placed} + connect_host.hidden(doc.model, key, stamp) + for part in sorted(parts): + if _WAKE.is_set(): + return + picking.triangles(part) + except NoLibrary: + return + + +def _run() -> None: + while True: + _WAKE.wait() + _WAKE.clear() + try: + _warm_once() + except Exception: + log.exception("warming the pointer's index failed") + + +def _heard(message: dict) -> None: + if message.get("type") != "doc": + return + with _LOCK: + if _STATE["thread"] is None: + thread = threading.Thread(target=_run, name="formblocks-warmer", daemon=True) + _STATE["thread"] = thread + thread.start() + _WAKE.set() + + +def start() -> None: + with _LOCK: + if _STATE["started"]: + return + _STATE["started"] = True + events.subscribe(_heard) + _heard({"type": "doc"}) diff --git a/backend/formblocks_engine.py b/backend/formblocks_engine.py index 3919624..791008a 100644 --- a/backend/formblocks_engine.py +++ b/backend/formblocks_engine.py @@ -34,6 +34,12 @@ def selfcheck() -> int: info["routers"] = len(app.main.ROUTERS) info["commands"] = len(registry.catalogue()) info["tools"] = len(mcp.tool_list()) + from app.connect import overrides + from app.connect.kinds import stud + from app.library import categories + + gone = [str(p) for p in (stud.DATA_FILE, overrides.DEFAULT_PATH, categories.DATA_FILE) if not p.is_file()] + info["data_files"] = "missing: " + ", ".join(gone) if gone else "ok" except Exception as exc: info["app"] = f"failed: {exc!r}" print(json.dumps(info)) diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index f3af1f5..0a0ef7a 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -2,6 +2,216 @@ Why the window is the way it is. Newest entry first. +## The open dialog appears with its recent files already in it · 0.3.0 (src/ui/file-actions.ts) + +Recorded with a `PerformanceObserver` on `layout-shift` in the release walk: Ctrl+O opened the path dialog at once and filled its recent files when `model.recent` answered a moment later, so the dialog grew and its buttons jumped 124 pixels down (a shift of 0.0026, marked as following input, so not counted in the score, but plainly a jump on screen). The dialog now asks for the recent files first and opens when they are written in, so it is painted once at its final size; the save dialog, which lists none, opens at once as before. A dialog asked again before the list came back opens only for the newest ask. Walked again the same way: no shift entry at all, with or without input. + +## The start card fills its recent files before it shows · 0.3.0 (src/ui/start-card.ts) + +In the same walk, Ctrl+N after a save showed the start card with the old list and then inserted the newly saved file above it, moving the earlier row 43 pixels down. The card now reads the recent files when it is about to show for a new revision and unhides itself once they are written, and only if it is still wanted (a pick or a placement in the meantime keeps it hidden). Walked again: no shift entry. + +## No other vendor's product is named in the window · 0.3.0 (src/view/thumbnails.ts, src/styles/tokens.css, public/splash.html, ../backend/app/library/HASHOUT_LOG.md) + +A review for other products' names (rule 7) outside the README's "instead of" line, the trademark notice and `spec/PROVENANCE.md` found four. The thumbnail renderer's class was named after a word that is half of another brick program's name; it is `Snapshot` now. The font stacks of the tokens and of the splash named system fonts by their makers' product names (two families of one maker's and one of another's) behind Inter and JetBrains Mono, which the window bundles and loads before it reveals itself; the stacks are now the bundled face, then the generic `system-ui` or `ui-monospace`, then `sans-serif` or `monospace`, which reach the same system fonts without naming them. The library package's log gave a marketplace's name as an example keyword; it now describes it. The dock module's agent program names stay: they are the family's shared module, copied unchanged. Checked: `npm run typecheck`, a search of `frontend/src`, `frontend/public`, `backend/app`, `src-tauri/src` and the skills for the names, and the window looked at headless in Inter as before. + +## The tree's part count has a fixed column · 0.3.0 (src/styles/tree.css) + +Measured with a `PerformanceObserver` on `layout-shift` under 4x CPU and a 200 KB/s network with 150 ms latency, a hard reload of the sample car at 1024 by 768 recorded one shift of 0.000006 on `ui-tree-count`: the count at the right of the tree's head ("0 parts", then "61 parts") sat in an `auto` column, so the column grew with the words and the count's box moved 7 pixels. The column is now `--num-w` wide and the count is right-aligned and cut if ever too long, the same fix as the file name's column, so the count changes its text and never its box. Measured again the same way at 1440 by 900, 1280 by 720, 1024 by 768, 900 by 700 and 1920 by 1080, on a load and a hard reload, with the car, with an empty model and with no library: 0 each time. + +## The right column's panels are resized by dragging their separators · 0.3.0 (src/ui/splits.ts, src/styles/shell.css, src/styles/tokens.css, src/ui/strings.ts, src/ui/features.ts) + +The colour palette's box was `--colours-h`, 200 pixels, which left its list of swatches about 95 pixels, three rows of more than three hundred colours; the palette lane fitted its rows into that box and asked for a taller one. `--colours-h` is now 320 pixels, which at a 900 pixel window gives the list about 213 pixels and leaves the tabs 286, and `SPEC.md` 1.2's "panels are resized by dragging the separators between them" is built for the right column: one separator between the colour palette and the tabs, one between the tabs and the details panel. Each is a thin absolute strip over the border it stands for, so it takes no room and adds nothing to the layout, and it changes one custom property on the column (`--ui-colours-h`, `--ui-details-h`), which the column's grid reads, so the three panels are resized and nothing is rebuilt. A size is kept between `--split-min` and what leaves the tabs `--split-tabs-min`, saved in local storage when the drag ends and set again at start inside the mount hook, before the first paint (1.2: the layout is restored at the next start), and clamped again when the window changes size. Up and Down on a focused separator move it by 16 pixels; a double click puts the panel back to its token. The side columns' widths are not draggable yet. Checked headless at 1440 by 900: the panels started at 320, 286 and 228; a drag of 80 pixels gave 400 and 206; two presses of Up on the lower separator gave the details 260; a reload kept 400, 174 and 260; double clicks restored 320, 286 and 228. + +## The ghost shows the connectors it would join · 0.3.0 (src/ui/placing.ts) + +`SPEC.md` 4.2 asks for small marks at the connectors a seated ghost would join. The preview answers them as `marks` in the scene's axes and the viewport's ghost already draws a `marks` list; the placing module now keeps the marks of the last free place with its pose and hands them over. A blocked place keeps the last free place's marks, which the viewport does not draw while the ghost is blocked. Checked headless: a 2 by 2 plate held over a 2 by 4 brick showed the selection-coloured squares on the studs it would join. + +## Nothing is drawn under the pointer until the engine has answered where · 0.3.0 (src/ui/placing.ts, src/view/ghost.ts) + +A pick showed the ghost at the origin until the first preview answer came back, so on a slow engine a brick flashed in the middle of the ground before jumping under the pointer. The ghost could not simply be left unset, because the viewport sends pointer rays only while a ghost is held. The placing module now sets the ghost with no position until the first answer, and the viewport keeps such a ghost held (its mesh loads, rays go out) but draws nothing; a new pick forgets the last place. After a turn, which asks again, the ghost stays at its last place in the new rotation. Checked headless with the first preview held back by a route: nothing was drawn while it waited, and the ghost appeared under the pointer when it was let through. + +## The current colour is the engine's setting · 0.3.0 (src/ui/current-colour.ts) + +This replaces the first half of "The current colour is the window's, and choosing one recolours the selection". The engine now keeps `current_colour` in the settings and has `colours.current`, which also puts the colour at the front of `recent_colours`, so a choice runs that command and the settings store's answer, or a change an agent or the command line made, sets the colour the window shows. Local storage stays as the first guess before the engine answers, so the swatch does not change in the first frames of a start; while the window's own `colours.current` is on its way, an older settings event is not taken, so two quick choices never flicker back, and when the command ends the engine's value is taken whatever it is. 16 and 24 are never taken. Checked headless: choosing Blue then Yellow left the engine at 14 with recent 14, 1, and after a reload Yellow was the current swatch. + +## The ghost is drawn from the preview's scene pose · 0.3.0 (src/ui/placing.ts, src/io/api.ts) + +`POST /api/place/preview` answers the ghost's pose twice, in the scene's axes (`position`, `rotation`) and in LDraw's (`ldraw`). The ghost was handed the LDraw pose, which made the viewport convert it; it is now handed the scene pose, the frame the viewport draws in, so the window converts nothing (FormBlocks' rule 5). The LDraw position is still what the status bar shows, since every number a person reads is in LDraw's axes. The client's `Placement` type names the `matrix` each placement now carries. Checked: `npm run typecheck`; looked at in the release run. + +## The mouse's back and forward buttons walk the steps · 0.3.0 (src/ui/step-strip.ts) + +`SPEC.md` 18.1: mouse buttons 4 and 5 show the previous and next step. The browser numbers them 3 and 4 from zero; a release of either anywhere in the window runs the previous or next step command, so the same enabled rule applies (nothing happens at the first or last step) and the browser's own back and forward are kept from the page. Checked headless with two steps: button 4 at step 1 stayed, button 5 moved to step 2 of 2. + +## A top bar button shows and hides the side columns · 0.3.0 (src/ui/view-keys.ts, src/ui/icons.ts) + +`SPEC.md` 1.2 lets each side column be collapsed and opened again, and below 1024 pixels both start collapsed (1.4), so a person who does not know Ctrl+backslash needs a control. The top bar's first window tool is now that command's button (a frame with two column lines, drawn here), lit while the columns are shown, whether that comes from the width or from the person's choice; it follows the root attribute and the width so it is right after a resize too. Checked headless at 900 by 700: the button opened both columns and the viewport kept 332 pixels, above the 320 of 1.4. + +## Below 1024 pixels the status bar keeps the selection, the step and the switches · 0.3.0 (src/styles/status.css) + +At 900 pixels the eight cells left the selection and the step a letter each, because the pointer's place, the progress and the version keep fixed widths. Below 1024 pixels, where `SPEC.md` 1.4 already closes the side columns, those three cells take no width and are hidden (the library card shows a fetch's progress itself), the three text cells share the rest, and the switches' text is narrower. A media query cannot read a custom property, so the breakpoint is written as the number, as the shell's is. Looked at headless at 900 by 700: "Nothing selected", "Step 1 of 1 · Main model" and the three switches read whole. + +## The start card greets an empty model with new, open and the recent files · 0.3.0 (src/ui/start-card.ts, src/styles/card.css, src/ui/strings.ts, src/ui/features.ts) + +`SPEC.md` 1.3 shows a start card in the viewport when no model is open, with new model, open and the recent files. The engine always holds a model (a new engine starts an empty Untitled), so "no model open" is read as a model with no placements, no file, no unsaved changes and nothing to undo: exactly the state of a first start or of New. The card says how to place the first part, offers New model and Open (the same window commands as the top bar, so unsaved changes are still asked about), and lists up to five recent files from `model.recent`, asked once per revision while the card shows. It is an overlay in the hud like the library card, so it moves nothing, and it steps aside while a part is held so the person can drop where it was; the first drop removes it for good. Below the library card in importance: with no library it stays hidden and the library card speaks. Checked headless: on an empty Untitled model the card listed three.fblk and tower.fblk, and clicking three.fblk opened it and hid the card. + +## A refusal names the command it answered · 0.3.0 (src/ui/run.ts, src/ui/strings.ts) + +`SPEC.md` 0.4: a command that fails changes nothing and says why in the status bar, in plain words, with the command id for reference. The engine's sentence is shown as it is, followed by the id in brackets ("path names no file: /tmp/x.fblk (model.open)."), so a person can tell an agent or a report exactly which command said no. A request that never reached the engine (status 0: not reachable, or no answer in time) keeps its own sentence without an id, since no command answered. Checked headless: opening a missing file showed the engine's sentence with `(model.open)`. + +## The file name has a fixed column, so the file tools never move · 0.3.0 (src/styles/topbar.css, src/styles/tokens.css) + +Measured with a `PerformanceObserver` on `layout-shift`, the built window under 4x CPU and a 200 KB/s network with 150 ms latency: the load shifted the four file tool icons 11 pixels right when the model's name arrived ("Untitled" became "three.fblk"), and every change that set or cleared the unsaved dot shifted them again, because the name's grid column was as wide as its text. The column is now `--docname-w` (220 pixels) with the name cut by an ellipsis, so neither a new name nor the dot moves anything after it. Measured again the same way: 0 on load, on a hard reload, and on searching, picking, moving the ghost, dropping, selecting, nudging, recolouring, a new step, walking, both tabs, undo, the menu, preferences and the grid switch. + +## Preferences take effect at once, in a dialog of fixed size with one search over every page · 0.3.0 (src/ui/prefs.ts, src/styles/prefs.css, src/ui/placing.ts, src/io/api.ts, src/ui/strings.ts, src/ui/features.ts, index.html) + +`SPEC.md` 17.1: Ctrl+comma opens preferences, with a search box and pages, every change taking effect at once and each page with "Reset this page". The pages built are the ones whose settings exist at 0.3.0: General (another copy waits after a drop, snap, the grid step and the overlap check, the last three through the catalogue's `snap.set`, `grid.step` and `overlap.set`), Appearance (the theme), Keys (every key the window answers to, read from the window's commands, so it cannot disagree with the menu), and Library and agents (the library update and folder in use, the engine's attribution, another folder by path, and "Check for an update", which is the only control that asks the server, on the person's click, 17.3). Building and Camera wait for their settings in the engine and the viewport, and the Keys page shows the map without changing it until `keys.set` exists. The dialog has a fixed height, so moving between pages or searching never resizes it; typing in the search shows every matching row from every page under one another and hides the page buttons with none. "Another copy waits after a drop" (17.2, first value on) is the window's own, kept in local storage, and the placing module now ends the pick after a drop when it is off. Checked headless: Ctrl+comma opened General with the engine's values, and typing grid left the grid step row and the G key. + +## The About box shows the library's attribution word for word · 0.3.0 (src/ui/about.ts, src/styles/dialogs.css, src/ui/strings.ts, src/ui/features.ts) + +FormBlocks' rule 3 shows the attribution of `spec/LDRAW.md`, "The attribution FormBlocks shows", word for word in the About box, beside the consent and in `NOTICE.md`. The box takes the sentence from the engine's library card (`card.attribution` of `GET /api/library/status`), the same string the library card shows, so the two can never drift and the window holds no copy of it. Under the mark and the version from `version.ts` it names the library update in use and its folder, or says there is none yet, and the app's licence. It is Help's one command, built once on first use and reopened with the same nodes; it reads the library's status again each time it opens. Checked headless from the menu: the box showed update 2026-10 from `/tmp/fb-lib/ldraw` and the attribution. + +## The menu lists the window's commands by area, then every engine command · 0.3.0 (src/ui/menu.ts, src/ui/strings.ts) + +This extends "The menu is made from the same two lists as the palette" below. `SPEC.md` 1.1 names the menu's areas (file, edit, view, select, model, step, help), and 18.1 asks that every menu item show its key. The window's commands now carry one of those groups, so the menu is a section per area in that order, each with its items and keys, hidden while empty, then "All engine commands" with the catalogue as before. A command whose group is not one of the areas (a command another module adds without one) is listed under Window. Each section is patched by command id, so opening the menu after the catalogue or the window's commands change touches only what changed. On macOS the system menu bar of 1.1 needs the desktop shell and is not built here. Checked headless: the open menu showed File, Edit, View, Select, Model, Step and Window with their keys. + +## The view keys fit, turn to the preset views, and clear the side columns · 0.3.0 (src/ui/view-keys.ts, src/ui/strings.ts, src/ui/features.ts) + +`SPEC.md` 15.2: F fits every visible part, Alt+1 to Alt+6 show the front, back, left, right, top and bottom, Alt+0 the corner view; 1.2 and 18.2: Ctrl+backslash hides or brings back the side columns for a clear view. The camera keys are window commands that call the viewport's `fit` and `setView` (the camera is the window's, not a model change, 15.3), off while no viewport is mounted. The clear view sets `data-clear` on the root, which the shell's grid reads, so the columns close by changing two track sizes and nothing is rebuilt; the choice is kept in local storage and set again at start (1.2), and below 1024 pixels, where the columns start closed (1.4), the same key opens them. Shift+F (fit the selection) and P (the projection) wait for the viewport to offer them. Checked headless: Alt+5 showed the brick from above and Ctrl+backslash widened the viewport from 872 to 1440 pixels and back. + +## The path and Show all float over the viewport's corners · 0.3.0 (src/ui/hud.ts, src/styles/card.css, src/ui/strings.ts, src/ui/features.ts) + +`SPEC.md` 10.3 shows where the person is as a path at the top left of the viewport ("Main model › Wall › Window"), each name a way back to that level; 9.2 puts a "Show all" button in the top right corner with the number of hidden items while anything is hidden. Both are in the hud layer above the canvas, positioned absolutely, so appearing and disappearing moves nothing. The path is the engine's `editing` list, patched by depth and name, shown only below the main model; a click on an earlier name runs `submodel.leave` as many times as there are levels below it, stopping if the engine refuses one. The count is the hidden placements of the submodel being edited, a use counting as one (9.2), and the button runs `part.show` with no ids (9.5). Checked headless: inside a submodel Wall with one part hidden, the path read Main model › Wall and the button Show all (1). + +## The switches call the catalogue's snap.set, grid.step and overlap.set · 0.3.0 (src/ui/status.ts) + +The engine lane added the three setting commands of `SPEC.md` 7.6 and 8.4 to the catalogue, which also keep snap and the grid step in the project file. `SPEC.md` 18.4 says keys call catalogue commands, so S, G, O and the three status bar buttons now run `snap.set`, `grid.step` and `overlap.set` instead of writing the settings route themselves, and read the settings again when the command returns (the engine's `settings` event does the same for changes made elsewhere). Checked with keys in the headless page: G moved Stud to Plate, S turned snap off, O turned the check on, and the reverse keys put all three back. + +## One panel's error does not stop the others or pass for a failed read · 0.3.0 (src/ui/doc-store.ts) + +The store calls its listeners from inside the request that read the change, so a listener that threw (the viewport, during its own lane's work) was caught as if the engine could not be read: the status bar said the model could not be read, and the panels after it in the list never heard of the change. Each listener is now called on its own; a throw is raised again in a microtask, so it still reaches the console with its stack and the dev overlay, and the next listener runs. Seen in the headless page after pressing S with a part selected; after the change the status bar showed the selection and the hint. + +## Placing speaks the preview route's scene axes and drops with part.place_at_ray · 0.3.0 (src/ui/placing.ts, src/io/api.ts, src/ui/edit-keys.ts, src/ui/strings.ts) + +This replaces "The fallback to part.fit turns the pointer ray into LDraw's axes" and corrects "A held part asks the engine where it would go". The engine lane's `POST /api/place/preview` now exists: it takes the ray and the held rotation in the scene's axes and answers the ghost's pose in both, `position` and `rotation` for the scene and `ldraw` for LDraw, plus the seat's marks and whether the place is blocked; `position` is null when the ray meets nothing, and the window then keeps the last place. The viewport's ghost takes LDraw's axes like a placement, so the window hands it `ldraw`. The drop is `part.place_at_ray` with the ray that gave the last free place and the held rotation, which seats by exactly the rule the preview used, so what is dropped is what was shown, including a blocked pointer dropping nothing. The window therefore converts no coordinates: the part.fit fallback and its axis flip are gone, as the one-conversion rule asks. The held rotation is kept in the scene's axes because that is what both calls take; the turn keys keep their meaning from LDraw's axes (R is a quarter turn about LDraw's Y, the same command `part.rotate` runs on a placed part), and for the held part the sense is turned about Y and Z, whose directions differ between the two frames, which is a fact about the axes and not a conversion of any number the engine sends. The viewport sends rays only while a ghost is set, so a pick shows the ghost at once (at the last place, or the origin before any) and a right click, which the viewport sends as `cancel`, ends the pick (`SPEC.md` 4.3). Ctrl+D copies the selection one grid step to the right with `part.duplicate`; picking copies up as a ghost waits for the engine lane's drag route to be wired here. Checked with Playwright: three 2 by 4 bricks dropped with the pointer stood on the ground at Y -24, the ghost showed half transparent under the pointer and the status bar gave its LDU place. + +## The viewport and the palettes are mounted before the first paint · 0.3.0 (src/ui/model-view.ts, src/ui/side-panel.ts, src/ui/colours-host.ts, src/ui/mounts.ts) + +The three hosts first found their modules with a lazy `import.meta.glob`, which loads them after the shell has mounted. The palettes import their stylesheets from their modules, so a lazy load meant their styles and their first nodes could arrive after the window was revealed, which under a slow CPU is a visible second paint of the left column. The globs are now eager: when a module exists it is part of the main bundle, its styles are in place before `startApp` runs, and the host mounts it synchronously inside the shell's mount hooks, so every region is filled before the reveal. A missing module is still an empty glob and an empty region, and a throw while mounting is caught and shown in the status bar instead of stopping the other regions. The viewport takes `colours()` as the list of colours (code, value, edge, alpha) rather than the whole table, which is what its colour store loads; the contract in `mounts.ts` says so. + +## The library card asks before anything is fetched, and shows progress in its own place · 0.3.0 (src/ui/library-card.ts, src/styles/card.css, src/io/dialog.ts, src/ui/strings.ts, src/ui/features.ts, index.html) + +`SPEC.md` 1.3: with no library the viewport shows the library card, offering a folder already on the computer or a fetch, with the address, the size, the licence and the authors shown before anything is downloaded, and the consent sentence beside the Fetch button with the attribution under it. Every one of those words is the engine's (`card` in `GET /api/library/status`), so the card and the engine's consent check can never disagree; the card writes them into its nodes and adds only its own headings. The fetch starts only on the person's click, and the click sends the address and the licence the card showed as the consent (`POST /api/library/fetch`), which is what the engine checks against its own card. The size is the server's answer at that moment (1.3), which needs a request to ldraw.org, so it is asked only when the person presses "Ask the server" (17.3: no network use the person did not ask for); until then the card says the size is unknown, in the engine's words. While a fetch runs the Fetch button is off, a bar and the step ("Downloading the library 42%") fill a cell that keeps its box while idle, and Cancel appears in the space reserved for it; a failed fetch says why under the buttons. A folder is typed (or chosen with the desktop's folder dialog, `askFolder`, when the shell offers it) and used with `POST /api/library/use`. The card is an overlay in the viewport's hud, so showing or hiding it moves nothing else, and it hides itself once the status says a library is found. Checked headless: with the engine started without a library the card showed the engine's address, licence, consent and attribution; typing `/tmp/fb-lib/ldraw` and Use this folder hid the card and the palettes and the tree's descriptions filled in. The fetch itself was not pressed: an agent may not give that consent. + +## Undo and redo name what they will do, and Ctrl+Z first lets go of a held part · 0.3.0 (src/ui/topbar.ts, src/ui/strings.ts) + +The engine sends the labels of the next undo and redo with every revision (`undo`, `redo` in the document's state), so the two buttons are off when there is nothing to do and their tooltips read "Undo Place 3001.dat" (`SPEC.md` 16.1 asks the Edit menu to name it). Ctrl+Y redoes as well as Ctrl+Shift+Z (16.1). While a part is held, Ctrl+Z ends the pick and undoes nothing (16.3). The top bar's words moved to the strings module, and the module imports the shell's hooks from `ui/shell.ts`. + +## New, open, save and save as ask for a path and for unsaved changes in the window · 0.3.0 (src/ui/file-actions.ts, src/styles/dialogs.css, src/ui/strings.ts, src/ui/features.ts) + +`SPEC.md` 14.2: Ctrl+N starts a model, Ctrl+O opens a `.fblk`, `.ldr`, `.mpd` or `.dat`, Ctrl+S saves to the project file it came from and otherwise asks where, Ctrl+Shift+S saves under a new name, and new or open with unsaved changes asks save, discard or cancel. Each is a window command with its button in the top bar's file group. The path comes from the desktop dialog when the shell offers it, and otherwise from a dialog in the window where the person types the full path, because a browser cannot hand a page a file's path and the engine opens files by path; the open dialog lists the engine's recent files (`model.recent`), greyed when gone, so a recent model is one click. The engine refuses `model.new` and `model.open` over unsaved changes unless told to discard (`discard: true`), so the window asks first and passes `discard` only after the person chose: saving first (and stopping if that save is cancelled or fails), or discarding. Save uses `model.save` only for a model whose file is a `.fblk`, and `model.save_as` otherwise; a typed path with no known ending gets `.fblk`, and `.ldr` or `.mpd` exports LDraw, as the command says. Both dialogs are built once and reused. The top bar shows the file's name with a dot while unsaved and the full path as its tooltip, and the window title is `* name · FormBlocks` while unsaved (1.2). Checked through the keys in the browser: Ctrl+S asked for a path and saved `tower.fblk`, Ctrl+N started Untitled, Ctrl+O listed `tower.fblk` among the recent files and opened it with its two parts. + +## The desktop's file dialogs are asked through the shell's own plugin, with no new package · 0.3.0 (src/io/dialog.ts) + +The desktop shell already registers the dialog plugin (`src-tauri/src/main.rs`), and its JavaScript wrapper only calls `invoke('plugin:dialog|open', {options})` and `plugin:dialog|save`, so the window calls those two through `@tauri-apps/api/core`, which it already depends on, rather than adding the wrapper package (`package.json` is not this lane's, and a package for two calls is more than the calls). The answer is a path, a cancel, or "unavailable": the browser, an older shell, or a capability that does not allow the dialog. The capability file at 0.3.0 grants neither `dialog:allow-open` nor `dialog:allow-save`, so in the desktop app the call is refused and the window falls back to the typed path, as in the browser, until the lead adds the two permissions (reported). The window title is set with the shell's own `set_window_title` command, and `document.title` everywhere. + +## The details panel shows the selection and moves it to typed numbers · 0.3.0 (src/ui/details.ts, src/styles/details.css, src/ui/strings.ts, src/ui/features.ts, index.html) + +`SPEC.md` 5.3 shows a single selected part's position and rotation as numbers, and typing a value moves it exactly; with several parts the fields show the selection's centre and typing moves them together. The panel is written once at a fixed height: a head with the description (or the count) and the id and number, then colour, position, height, turn and step rows, or a sentence when nothing is selected; the head keeps its second line's height when it is empty, so selecting does not move the rows. A typed position is sent on Enter or when the field is left: `part.set_transform` with the new position for one part, `part.move` by the difference from the centre for several (both exact, with no snapping, as 5.3 says), and a number beyond a million LDU is refused before it is sent (5.6). A field that has the cursor is not overwritten by a revision, so an agent's change does not wipe what the person is typing. Height is written in plates and bricks as well as LDU (0.2), from -Y. The turn is three angles about X, Y and Z (0.2), read from the matrix in the X, then Y, then Z order; the numbers are shown, not typed, because the engine turns by quarter turns only at 0.2.0. Colour is the swatch with its name and number, or the count of colours for a mixed selection. + +## The Steps tab lists each step, opens it to its parts, and names, hides and deletes steps · 0.3.0 (src/ui/steps-tab.ts, src/styles/steps.css, src/ui/strings.ts, src/ui/features.ts, index.html) + +`SPEC.md` 11.1 lists the steps of the submodel being edited, numbered from 1 with an optional name, each opening to the parts added in it, with a search box over them. Rows come from the store's steps, keyed `s3` for a step and `s3/p12` for a part in it, in one patched list, so opening a step inserts its part rows and nothing else moves. A click on a step row shows it (`step.goto`), the step shown is lit and later steps are dimmed, as on the strip. The eye hides or shows every part of the step in one `part.hide` or `part.show` (9.1); the bin deletes the step with `step.delete`, whose parts the engine moves on (11.3). A double click on a row puts a field in the name's own grid cell, at the row's height, and Enter or leaving the field sends `step.rename`, Escape keeps the old name; keys typed there stop at the field, so the window's single-letter keys do not fire. Typing in the filter opens every step with a matching part and leaves out the steps with none. Dragging part rows between steps (11.3) is not built yet; the Shift+comma and Shift+full stop keys move the selection between steps meanwhile. + +## The model tree is built from the store, keyed by path, and expanded in place · 0.3.0 (src/ui/model-tree.ts, src/styles/tree.css, src/ui/strings.ts, src/ui/features.ts, index.html) + +`SPEC.md` 12.1 shows the submodel being edited as a tree in step order, each row with a swatch, the description, the part number or the word submodel, and the step; a use opens to show its submodel's contents, dimmed; a Submodels list below names every submodel with its uses; a filter box narrows the rows. All of it is drawn from the document store, which already holds every placement of every submodel and each submodel's steps, so the tree asks the engine for nothing but part descriptions (once each, through the lookup) and needs no `GET /api/doc/tree` of its own. A row's key is its path of ids (`p3/p12` for a part inside the use p3), the same scheme the viewport uses, so a submodel used twice gives two sets of rows that patch independently, and the list is one `patchList` over the visible rows: opening a use inserts its rows after it and touches nothing else. Expansion is bounded at eight levels and by the submodels already on the path, so a use that contains itself (refused by the engine, but possible in a hand-written file) cannot loop. Which uses are open is kept for the session; the project file keeping it (12.3) waits for the engine. + +A click selects with the viewport's rules (12.2): plain sets, Shift adds, Ctrl or Cmd toggles, and a click on a dimmed inner row selects the use it belongs to, since only the submodel being edited is selectable (6.4). The eye runs `part.hide` or `part.show` for that one placement; hidden rows are dimmed with the crossed eye always visible (9.2), other rows show the eye on hover. A double click on a use enters it, and a click on a Submodels row enters that submodel by name. When the selection changes the first selected row is scrolled into view only if it is out of sight (12.3). Rows are a fixed height with `content-visibility: auto`, so a model of thousands of placements lays out only the rows on screen (12.4) while the scroll height stays right. A part the library does not have is marked "not in this library" in the warning colour (12.4). + +## The middle of the right column is two tabs over two fixed panes · 0.3.0 (src/ui/tabs.ts, src/styles/tabs.css, src/ui/strings.ts, src/ui/features.ts, index.html) + +`SPEC.md` 1.1 puts a panel with two tabs, the model tree and the steps, between the colour palette and the details panel. Both panes exist from the first frame in the same grid cell, and switching shows one and hides the other with `hidden`, so neither is rebuilt and each keeps its scroll position. The open tab is kept in local storage (1.2 asks that the layout be restored at the next start). The tab bar is an ARIA tab list: Left and Right move between the two. Modules fill a pane through `tabHost`, which waits for the shell if it is asked before mounting. + +## The step strip walks, shows every step as a chip, and breaks a step · 0.3.0 (src/ui/step-strip.ts, src/styles/strip.css, src/ui/strings.ts, src/ui/features.ts, index.html) + +`SPEC.md` 11.1 puts the step controls on the toolbar: first, previous, next, last and "Step 4 of 12". They are the strip under the viewport, with one chip per step of the submodel being edited between them and the New Step button, so a person can see how many steps there are and jump to one with a click (11.2, "Clicking a step row shows that step"). Chips are patched by step number: walking changes two chips' classes and the label, and adding a step adds one chip. Later steps are dashed and empty ones dimmed; the step shown is lit and scrolled into view only when it is out of sight, so a click never moves the row under the pointer. The keys of 18.2 are window commands: comma and full stop for previous and next, Home and End for first and last, Ctrl+Enter for a new step after the one shown (`step.break_after` with no id), and Shift+comma and Shift+full stop move the selected parts one step back or on (`step.move_parts`, from the earliest step among them, one past the last starting a new step). Each walk is `step.goto`, a view command, so it is no undo step, and the engine's revision brings the new step to every panel. + +## The status bar is eight fixed cells, and the switches are in it · 0.3.0 (src/ui/status.ts, src/styles/status.css, src/ui/strings.ts, src/app.ts) + +This replaces "The status bar says whether the engine is there" below. `SPEC.md` 1.1 puts the selection and a hint on the left, the step and submodel in the middle, and the pointer's position, the snap and overlap states and long work's progress on the right; 7.1 and 8.1 put the snap switch, the grid step and the overlap switch on a toolbar and repeat them in the status bar. The window has no toolbar row (the step controls are in the step strip, the file and edit tools in the top bar), so the three switches live in the status bar and are the controls themselves: Snap and Overlap are lit while on, the grid button names the step and moves to the next, and each runs a window command (S, G, O) that writes the engine's setting, so a change from the command line shows here too. The cells are, left to right: the engine's link as a dot with its state as the tooltip, the selection ("2 parts selected in 1 colour"), the latest notice or else the part under the pointer (id, description, colour name), "Step 2 of 5 · Main model", the held ghost's position in LDU, the three switches, the fetch or index progress, and the name and version. Each column has a fixed or shared width in the stylesheet and each switch a fixed text width, so a longer sentence is cut with an ellipsis rather than pushing a neighbour, and the progress cell keeps its box while hidden (`visibility`). The revision number is no longer shown; it meant nothing to a person. The settings and library stores start beside the document store in `app.ts`. + +## The building keys are window commands that call the catalogue · 0.3.0 (src/ui/edit-keys.ts, src/ui/strings.ts, src/ui/features.ts) + +`SPEC.md` 18.4 says keys are not commands themselves but call commands of the catalogue. Each key of 18.2 that acts on the selection is a window command (so it shows with its key in the menu and the command palette) whose run sends the catalogue command with the selection's ids: Ctrl+A and Ctrl+I select all and invert; Delete or Backspace deletes; H, Shift+H and Alt+H hide, show all and hide others; Enter enters a selected use of a submodel. R, T and Y turn, tip and roll by a quarter turn (`part.rotate` about LDraw's Y, X and Z, the positive sense being clockwise seen from above for R, as worked out from LDraw's right-handed axes with -Y up), Shift the other way; while a part is held they turn the ghost instead (5.2). The arrows nudge by the grid step (`part.move`; across by 20, 10 or 1 LDU, up and down by 8, 8 or 1), Alt by one LDU (5.3). Without the camera's direction in this module the arrows move along LDraw's X and Z, Left and Right on X and Up and Down on Z, which matches the screen in the front and corner views; following the camera waits for the viewport to say which way it looks. Escape steps back one level at a time (18.1): the held part, then the selection, then the submodel being edited. Ctrl+D picks up one selected part as a ghost in its colour and rotation (5.4); several are copied one grid step to the right by `part.duplicate`, since the ghost the viewport draws is one part. Space drops the held part and is off otherwise, so it does nothing to the page while nothing is held. + +## A key is named by what it types, with three exceptions, and a command may have a second key · 0.3.0 (src/ui/commands.ts, src/ui/strings.ts) + +`SPEC.md` 18.1 matches letters by the character they type, so the key map works on other layouts, and digits by the digit row. `comboOf` keeps that and adds what the map of 18.2 needs: the space bar is `Space` (its character is a blank, which no label can show); with Alt a letter or a digit is named from its key's position, because Option on macOS turns H into another character and Alt+1 would otherwise never match; and Shift with comma or full stop stays `Shift+,` and `Shift+.`, which a US layout would type as angle brackets. A command can list further keys in `also`, for the pairs the specification gives one action (Delete and Backspace, Ctrl+Shift+Z and Ctrl+Y). Key labels come from the strings module, with Cmd and Option on macOS. + +## The left column is the parts palette, and a choice there picks the part · 0.3.0 (src/ui/side-panel.ts, src/ui/strings.ts, index.html, src/styles/panel.css) + +This replaces "The left panel shows the catalogue as a list a person can click" below: `SPEC.md` 1.1 gives the left side to the parts palette, and the catalogue is already in the menu and the command palette, so the commands list and its stylesheet are gone. `side-panel.ts` keeps its name, because `main.ts` imports it and belongs to the lead, and now mounts the palettes lane's parts palette into the left column. It is handed the plain `get` and `put` calls, the current colour, a thumbnail call and a choice callback. Thumbnails are drawn by the viewport (`thumbnail` on its handle), so a thumbnail asked before the view has loaded waits for it rather than failing. A choice picks the part for placing (`SPEC.md` 2.6, 4.1). The palette is told when the current colour changes and asked to refresh when the library is found or its index becomes ready, since its lists come from the index. `Mod+F` puts the cursor in its search box (2.3), registered as a window command so it shows its key in the menu and the command palette. + +## A held part asks the engine where it would go, one question at a time · 0.3.0 (src/ui/placing.ts, src/ui/strings.ts, src/ui/features.ts) + +`SPEC.md` 4.2 has the ghost follow the pointer and seat, rest or stand by the snapping rule, which lives in the engine. So the window never works out a place: each pointer ray while a part is held goes to `POST /api/place/preview` with the part, the current colour and the held rotation, and the answer's position, rotation, seat and block become the ghost. Only one question is in flight; rays that arrive meanwhile replace one queued ray, so a fast pointer costs at most one request behind the answer, never a backlog. An answer that comes back after the pick changed (a new part, a turn, a cancel) is dropped by a token. With the overlap check on, a blocked place keeps the ghost at the last free place with its blocked outline (4.2), and a click there is refused with a sentence rather than sent. A click or Space drops: `part.place` with the previewed position and rotation and the snap setting, so the engine seats it in the same place; another copy waits under the pointer (4.3), which is why the pick is kept after a drop and the preview asked again from the last ray. When the pointer leaves the viewport the ghost is hidden and the pick kept (4.2). Turning a held part multiplies its rotation by a quarter turn about LDraw's X, Y or Z axis on the left, the same right-handed sense as `part.rotate`, and asks again. The engine's commands turn by quarter turns only at 0.2.0, so the fine angle of 5.2 is not offered yet. + +## The current colour is the window's, and choosing one recolours the selection · 0.3.0 (src/ui/current-colour.ts, src/ui/colours-host.ts, src/ui/features.ts, src/app.ts) + +`SPEC.md` 3.4 plans `colours.current` as a setting, but the engine's catalogue and its settings file have neither at 0.2.0 (a `PUT /api/settings` with `current_colour` is refused as unknown), so the current colour is kept by the window in local storage, Red (4) at the first start, and never 16 or 24, which are not swatches (3.2). It moves to the engine's settings when the engine lane adds the key; reported. The colour palette module is found by `import.meta.glob` like the viewport and mounted in the right column's top box; it is handed `get` and a choice callback. A choice sets the current colour and, while parts are selected, sends `part.recolour` with the selection, unless every selected part already has that colour, which `SPEC.md` 3.3 says changes nothing and adds no undo step. Feature modules that are new at 0.3.0 are imported by `ui/features.ts`, which `app.ts` imports, because `main.ts` belongs to the lead. + +## The viewport's region mounts the view module and feeds it the store's answers · 0.3.0 (src/ui/model-view.ts, src/ui/mounts.ts, src/ui/doc-store.ts, index.html, src/styles/model.css) + +This replaces "The main area lists the model's parts until the viewport exists" below: the read-only list and its stylesheet are gone, and `model-view.ts` is now the host of the 3D view that `src/view/` builds. The view lane and the palettes lane write their modules at the same time as this one, so the two contracts are typed once in `ui/mounts.ts` from the brief all three lanes were given, and each module is found with `import.meta.glob`: when `src/view/index.ts` does not exist the glob is empty, the region stays an empty box in the background colour and the window compiles; when it exists Vite bundles it and the host mounts it into the box the shell made. The view's names follow its own lane (the corner view is `iso`). + +The host gives the view the mesh bytes, the colour table, and three callbacks. A pick selects through the catalogue (`select.set`, or for an added pick `select.add`, or `select.remove` when every picked id is already selected, so Shift toggles); a click on nothing clears. A held part stops picks, since the click belongs to the drop. Pointer rays go to whichever module asks first (the placing module), and hover goes to every listener. From the store, a reset hands the view the engine's snapshot, any other change hands it the changes answer as the engine sent it, and the selection and the step shown are passed only when they differ from the state before; the step is `null` while the last step is shown, so walking draws nothing faded when nothing is being walked. If the view loads after the first document, the store builds a snapshot from what it holds. A `ResizeObserver` tells the view when its box changes, which happens only when the person moves a column or opens the dock. + +## The fallback to part.fit turns the pointer ray into LDraw's axes · 0.3.0 (src/io/api.ts) + +The viewport hands its pointer ray in the scene's axes (+Y up), and `POST /api/place/preview` takes it that way and turns it back in the engine, where the one conversion lives (`CLAUDE.md`, FormBlocks rule 5). `part.fit`, which the client asks while that route is missing, takes a ray in LDraw's axes. So the fallback alone negates Y and Z of both the origin and the direction (the half turn about X that `backend/app/mesh/scene.py` applies), and the answer's position and rotation are LDraw's, as the preview route's are. This is a second place that knows the conversion, which the rule forbids; it lasts only as long as an engine without the preview route, and goes with the fallback. Reported to the lead. + +## The window's regions are one grid whose boxes are fixed before the first paint · 0.3.0 (src/ui/shell.ts, src/app.ts, src/styles/shell.css, src/styles/topbar.css, src/styles/dock-tokens.css, src/ui/model-view.ts) + +This replaces "The shell is one grid whose tracks never change shape" and the markup part of "app.ts mounts the shell once" below. `SPEC.md` 1.1 lays the window out as a top bar, the parts palette down the left, the viewport in the middle, one right column of the colour palette, the model and steps tabs and the details panel, and the status bar along the bottom, with the family dock under the status bar's row. The grid has five rows (top bar, work area, step strip, dock, status bar) and four columns (parts palette, viewport, right column, a right dock); every track is a token or a custom property, so each region's box is known from the stylesheet before any script fills it. The step strip sits under the viewport only, so the palettes run the full height. The right column is its own three-row grid with the colour palette and the details panel at fixed heights and the tabs taking the rest, so a long tree scrolls inside its box and never pushes the details panel. The viewport host is the positioned `main`, with the view module's own box and a `hud` layer above it for the path, the Show all button and the cards; the hud passes the pointer through except on its own controls. + +The markup and the hosts now live in `ui/shell.ts` with the mount hooks, and `app.ts` re-exports them. The reason is the import order: `app.ts` will import the window's feature modules, and each of those registers a hook, so keeping the hook list in `app.ts` would make every feature import a module that has not finished loading. The template's `panel` and `main` hosts keep their names (the parts palette and the viewport's region) because the dock adapter and the menu use the same object. + +The top bar holds the menu, the owner's mark at a token size, the name, the open model's file name with a dot while there are unsaved changes, the file tools, a flexible gap and the edit and window tools. `SPEC.md` 1.4 asks both side columns to start collapsed below 1024 pixels and the viewport never to go under 320, so the columns are zero there unless the person opened them (`data-clear="off"`), and `data-clear="on"` closes them at any width for the clear view of 1.2. `dock-tokens.css` follows the new rows and columns, so the dock opens under the status bar's row across the palettes and the viewport, or as a column at the right edge. + +## Colour names and part descriptions are asked once and kept · 0.3.0 (src/io/lookup.ts) + +The tree, the details panel and the status bar name a placement's part by its description and its colour by name, and the colour table and a part's description do not change while a library is in use. So the colour table is read once (`GET /api/colours`) and indexed by code, and each part's description is asked once (`GET /api/parts/{name}`), with concurrent askers sharing one request. A part the library does not have is remembered as missing so it is not asked again on every revision. When a library arrives (after a fetch or a new folder) the colour table is read again if it was empty and the parts remembered as missing are forgotten, so they are asked again from the new library. Rows show the part number until the description arrives, in a box of the same size. + +## The library's state and its fetch progress come from one store · 0.3.0 (src/io/library.ts) + +The library card, the status bar's progress and the parts palette's empty state all need the same facts, so one store reads `GET /api/library/status` at start, on reconnection and whenever a fetch or an index build ends, and keeps the progress the engine sends on the live channel in between. The engine sends `{"type":"library","stage":"fetch","step":...}` while it fetches (the steps are start, download, unpack, release and done), `stage: "index"` while it builds the parts index, and one closing event (`fetched`, `ready`, `index_failed` or `located`); any closing event ends the progress and reads the status again, which is how the card learns that the library is there. Asking the server for the archive's size is a separate call (`ask_server=true`), made only when the person opens the card's fetch side, because it is a network request and `SPEC.md` 17.3 allows none the person did not ask for. + +## The person's settings are the engine's, mirrored in one store · 0.3.0 (src/io/settings.ts) + +Snapping, the grid step and the overlap check are settings, not model changes (`SPEC.md` 0.3), and the engine keeps them in `settings.json`, so the window reads them from `GET /api/settings` and writes a change as a partial `PUT`, taking the answer as the new value. The engine says `{"type":"settings"}` on the live channel after any write, so a change made from the command line or by an agent shows in the status bar too; the store reads again then and on every reconnection, and tells its listeners only when something really changed. The grid steps and their sizes across and up (Stud 20 and 8, Plate 10 and 8, Fine 1 and 1, `SPEC.md` 7.2) are written here once, because the nudge keys need them in LDU. Until the first answer the store holds the first-start values of `SPEC.md` 17.2 (snap on, Stud, overlap off), which are what a new engine answers, so the switches do not change when the answer comes. + +## The document store reads the whole model once, then only what changed · 0.3.0 (src/ui/doc-store.ts, src/ui/model-view.ts, src/ui/status.ts) + +This replaces "The document store mirrors the engine and names what changed" below. The store reads `GET /api/doc` at start and whenever the live channel reopens (a restarted engine counts revisions again); after that each revision the channel reports is fetched as `GET /api/doc/changes?since=n`, where n is the revision shown. The answer lists the placements added and changed, the ids removed and the submodels whose steps or uses moved, so a drop costs one placement on the wire, not the model. When the engine cannot say what changed since n (its feed is shorter than the gap, or a new model was opened) it answers `reset` with the whole document, and the store starts over from it. The store keeps every placement of every submodel by id and every submodel by key, in the file's order, plus the document's state (selection, step shown, submodel being edited, file, unsaved mark, undo and redo labels). Its listeners get one change: either a reset with the snapshot, or the changes answer, with the ids touched and removed, whether any submodel moved, and the state before, so the viewport is handed the engine's own answers and each panel compares only the state it shows. Fetches never overlap, as before. `placementsOf` lists a submodel's placements in step order from its steps' id lists. + +## Every word the window shows lives in one strings module · 0.3.0 (src/ui/strings.ts) + +The window's sentences, labels and tooltips are kept in `S`, grouped by the region that shows them, so the words can be read, reviewed and one day translated in one file, and a module never spells a sentence inline. `plural` writes a count with the right noun and `fill` puts named values into a sentence (`{n}`), which is how a sentence with a number in it stays one string rather than pieces glued in code. The dock keeps its own words in its copied module and is not changed. + +## The engine client speaks the model's real answers · 0.3.0 (src/io/api.ts) + +The types now follow what the engine answers at 0.2.0, read from a running engine rather than guessed: a placement carries `open` and `use` besides its part, colour, place and step; a submodel carries its uses and its steps, each step naming its placement ids; the document's state (selection, step shown, step count, submodel and path of submodels being edited, file and its kind, unsaved mark, the labels of the next undo and redo, revision) comes with both `GET /api/doc` and `GET /api/doc/changes`, and a changes answer either lists what was added, changed and removed since a revision or says `reset` and carries the whole document. Beside them: settings (grid step, snap, overlap), the library's status with its card, the colour table, one part's description, and a part's mesh as raw bytes, which is the one call that does not read JSON. `get` and `put` are the plain calls the palettes are handed. + +Placing asks `POST /api/place/preview`, which the engine lane is adding at 0.3.0. Until an engine answers it, the first 404 or 405 switches the client to the catalogue's `part.fit` with the pointer ray as `origin` and `direction`, which answers the same place, rotation, seat and block, so placing works against either engine and nothing else in the window knows which one it talked to. + +## The splash shows the owner's mark · 0.3.0 (public/splash.html) + +This replaces the placeholder of "The splash is FormCAD's" below: the inline square with the letter F is gone and the card shows `mark.png`, the mark without its tile, at 96 pixels. The picture is a plain `img` with its width and height written in the tag, so the card lays out the same before and after the picture decodes. The picture has transparent margins around the bricks, so it is pulled up and down by 12 pixels to keep the gap to the words what it was. Looked at headless at 360 by 280: the bricks sit centred over "Starting FormBlocks" and the bar. + +## The page names its icons from the owner's art · 0.3.0 (index.html) + +The head links `favicon.png` (256 pixels) and `favicon.ico` as the tab icon and `apple-touch-icon.png` as the touch icon, all from `public/`, where the owner's art was put. The PNG comes first because a browser that reads both takes the sharper one. `mark.png` is preloaded because the top bar shows it in the first frame; with the preload the picture is in the cache before the module script writes the bar, so the mark is never painted a frame late. The mark's box has a fixed size in the stylesheet either way, so a late picture could not move anything. + ## The last spacing literals come from tokens · 0.2.0 (src/styles/tokens.css, controls.css, palette.css, panel.css, scrollbars.css) A review for literals outside the tokens file found the template's 2 px list gaps in the palette and the side panel, the scrollbar thumb's 2 px border and the focus ring's 2 px width and 1 px offset. They now read `--hair-gap`, `--focus-w` and `--focus-offset`, added to `tokens.css` with the same values, so nothing on screen moves. Left as they are, on purpose: the 720 px breakpoint in `shell.css` (a media query cannot read a custom property), the zero sizes of the dock's gaps, the fallbacks inside `dock-tokens.css`, the two background colours in `index.html`'s inline style, which must paint before any stylesheet loads to keep the first frame from flashing, and the dock module's own files, which are copied unchanged under their manifest. Checked: `npm run build`. diff --git a/frontend/index.html b/frontend/index.html index 362b34a..7751a93 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -5,6 +5,10 @@ FormBlocks + + + + @@ -29,9 +33,14 @@ - - + + + + + + + diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 7cbb9f3..653707c 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,22 +1,24 @@ { "name": "formblocks", - "version": "0.2.0", + "version": "0.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formblocks", - "version": "0.2.0", + "version": "0.3.0", "license": "Apache-2.0", "dependencies": { "@fontsource/inter": "5.3.0", "@fontsource/jetbrains-mono": "5.3.0", "@tauri-apps/api": "2.12.4", "@xterm/addon-fit": "0.11.0", - "@xterm/xterm": "6.0.0" + "@xterm/xterm": "6.0.0", + "three": "0.186.1" }, "devDependencies": { "@tauri-apps/cli": "2.11.4", + "@types/three": "0.186.0", "typescript": "7.0.2", "vite": "8.3.5" }, @@ -24,6 +26,13 @@ "node": ">=22.12" } }, + "node_modules/@dimforge/rapier3d-compat": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz", + "integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==", + "dev": true, + "license": "Apache-2.0" + }, "node_modules/@emnapi/core": { "version": "2.0.0-beta.2", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", @@ -616,6 +625,13 @@ "node": ">= 10" } }, + "node_modules/@tweenjs/tween.js": { + "version": "23.1.3", + "resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz", + "integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==", + "dev": true, + "license": "MIT" + }, "node_modules/@tybys/wasm-util": { "version": "0.10.5", "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz", @@ -627,6 +643,35 @@ "tslib": "^2.4.0" } }, + "node_modules/@types/stats.js": { + "version": "0.17.4", + "resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz", + "integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/three": { + "version": "0.186.0", + "resolved": "https://registry.npmjs.org/@types/three/-/three-0.186.0.tgz", + "integrity": "sha512-mxYSBpDC+D0pLfSP6sW4WZTcT+nrtmZcimMqnVmy36Hte3XpeYSrvgg4TRdaM1GemGog1AWzI5qL2VoIfMXbJQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@dimforge/rapier3d-compat": "~0.12.0", + "@tweenjs/tween.js": "~23.1.3", + "@types/stats.js": "*", + "@types/webxr": ">=0.5.17", + "fflate": "~0.8.3", + "meshoptimizer": "~1.1.1" + } + }, + "node_modules/@types/webxr": { + "version": "0.5.24", + "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz", + "integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==", + "dev": true, + "license": "MIT" + }, "node_modules/@typescript/typescript-aix-ppc64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", @@ -1010,6 +1055,13 @@ } } }, + "node_modules/fflate": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz", + "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==", + "dev": true, + "license": "MIT" + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -1286,6 +1338,13 @@ "url": "https://opencollective.com/parcel" } }, + "node_modules/meshoptimizer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.1.1.tgz", + "integrity": "sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g==", + "dev": true, + "license": "MIT" + }, "node_modules/nanoid": { "version": "3.3.20", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", @@ -1399,6 +1458,12 @@ "node": ">=6.0.0" } }, + "node_modules/three": { + "version": "0.186.1", + "resolved": "https://registry.npmjs.org/three/-/three-0.186.1.tgz", + "integrity": "sha512-blFeqb49wRCSGUGj7gtpfnSGHy2lwDk94RhUmS1c/hTby70kvChbWpkJ4Pm1390LqzzvTmzgXKHPEafJwCb8jA==", + "license": "MIT" + }, "node_modules/tinyglobby": { "version": "0.2.17", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", diff --git a/frontend/package.json b/frontend/package.json index 035c4b3..e41db0d 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "formblocks", "private": true, - "version": "0.2.0", + "version": "0.3.0", "description": "FormBlocks · an open brick building app on the LDraw parts library", "license": "Apache-2.0", "type": "module", @@ -20,10 +20,12 @@ "@fontsource/jetbrains-mono": "5.3.0", "@tauri-apps/api": "2.12.4", "@xterm/addon-fit": "0.11.0", - "@xterm/xterm": "6.0.0" + "@xterm/xterm": "6.0.0", + "three": "0.186.1" }, "devDependencies": { "@tauri-apps/cli": "2.11.4", + "@types/three": "0.186.0", "typescript": "7.0.2", "vite": "8.3.5" } diff --git a/frontend/public/apple-touch-icon.png b/frontend/public/apple-touch-icon.png new file mode 100644 index 0000000..7576cbf Binary files /dev/null and b/frontend/public/apple-touch-icon.png differ diff --git a/frontend/public/favicon.ico b/frontend/public/favicon.ico new file mode 100644 index 0000000..17cd6ea Binary files /dev/null and b/frontend/public/favicon.ico differ diff --git a/frontend/public/favicon.png b/frontend/public/favicon.png new file mode 100644 index 0000000..5e2019f Binary files /dev/null and b/frontend/public/favicon.png differ diff --git a/frontend/public/mark.png b/frontend/public/mark.png new file mode 100644 index 0000000..9e3d433 Binary files /dev/null and b/frontend/public/mark.png differ diff --git a/frontend/public/splash.html b/frontend/public/splash.html index c09d512..2f59ec6 100644 --- a/frontend/public/splash.html +++ b/frontend/public/splash.html @@ -6,8 +6,8 @@ -F

Starting FormBlocks