diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4a53bff6..d21cfd3a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -77,11 +77,42 @@ jobs: - name: Run tests run: xvfb-run --auto-servernum uv run pytest test tests -q + # `sca edit` serves a web UI that is built from editor-web/ and git-ignored: + # without this step the wheel would ship an editor with no front end. + - name: Set up Node.js + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: "22" + cache: npm + cache-dependency-path: editor-web/package-lock.json + - name: Build the editor web UI + working-directory: editor-web + run: | + npm ci + npm run build + - name: Build wheel and source distribution run: uv build - name: Verify distributions run: uv run twine check dist/* + + - name: Verify the wheel carries the editor, the skill and the example + run: | + set -euo pipefail + wheel="$(ls dist/*.whl)" + listing="$(unzip -Z1 "$wheel")" + for required in \ + simplecadapi/editor/webui/index.html \ + simplecadapi/skill/resources/skillproj.toml \ + simplecadapi/skill/resources/docs/skill/SKILL.md \ + simplecadapi/example/resources/u_link_motor_mount/u_link.py \ + simplecadapi/example/resources/u_link_motor_mount/dimensions.py; do + if ! grep -qx "$required" <<<"$listing"; then + echo "wheel is missing $required" >&2 + exit 1 + fi + done - name: Build and verify Agent Skill archive run: | uv run python tools/auto_docs_gen.py --quiet diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.md index 12a9e423..8d52b23c 100644 --- a/docs/skill/SKILL.md +++ b/docs/skill/SKILL.md @@ -4,9 +4,9 @@ description: Build, assemble, inspect, reconstruct, and export parametric CAD mo license: Apache-2.0 metadata: project: simplecadapi - version: 2.1.3 + version: 2.2.0b1 package-name: simplecadapi - package-version: 2.1.3 + package-version: 2.2.0b1 --- # SimpleCAD SDK Skill @@ -44,6 +44,13 @@ Paths are relative to this file's directory. - Questions about an existing STEP file that change nothing enter no workflow; you MUST use `references/domains/step-inspection.md` for them directly. +- A person who has the code-first editor open (`sca edit`) and talks + about what they selected, a cell they copied, or a value they + tuned enters no new workflow: the modeling follows the workflow you + selected, and you MUST read + `references/domains/editor-collaboration.md` first to see what they + see (selection cell, `sca snapshot`, cell references) and how to + hand the work back. - Creating, installing, updating, or removing a SimpleCADAPI addon (a third-party skill+tooling package around `.scadpkg`) enters no workflow; you MUST use `references/domains/addon-development.md` @@ -134,7 +141,8 @@ it and stop that route; never invent an alternative route. `scad.std.bearing`. 11. Read `references/docs/guides/notebook-runtime.md` in full before writing a notebook, composing notebooks, or reasoning - about the cell cache. Run models with `sca run`; never enable + about the cell cache. Run models with `sca run` (`sca edit` opens + them in the editor for a person); never enable marimo's `[tool.marimo.runtime] cache_cells` in the editor, and never commit the generated `__marimo__/` directory. @@ -193,6 +201,8 @@ print(len(rebuilt)) - `references/SDK_OVERVIEW.md` — package-level map - `references/inspect/brep-reverse-engineering.md` - `references/domains/addon-development.md` — `sca` addon CLI and authoring guide +- `references/domains/editor-collaboration.md` — working with a person in `sca edit`: + selection cell, snapshot, cell references, parameters - `references/docs/guides/reconstruction-agent-test-prompt.md` - `references/docs/guides/reconstruction-agent-strategy.md` - `references/docs/guides/notebook-runtime.md` diff --git a/docs/skill/references/domains/editor-collaboration.md b/docs/skill/references/domains/editor-collaboration.md new file mode 100644 index 00000000..30e16d63 --- /dev/null +++ b/docs/skill/references/domains/editor-collaboration.md @@ -0,0 +1,151 @@ +# Editor collaboration: working with a person in `sca edit` + +Use this domain when a person has the code-first editor open (`sca edit`) and +you work on the same notebooks: they click, drag and tune; you read files and +edit code. It is not a workflow. The modeling you do still follows the workflow +you selected; this page says how to see what the person sees and how to hand +work back. + +The notebook file is the only shared state. The editor autosaves every edit to +it, and every message the person gives you (a selection, a cell reference, a +tuned value) is also something you can read from disk. Never rely on what the +person says they selected when the file or the snapshot can tell you. + +## Start the editor for a person + +```bash +sca edit # a directory of notebooks, or one notebook +sca edit --no-browser --port 7180 +``` + +- Needs the `editor` extra (`pip install "simplecadapi[editor]"`); without it + the command says so and stops. +- The workspace is any directory tree. Models are the notebooks whose header has + `[tool.simplecadapi]`; assemblies list the parts they `use(...)`. Open the + assembly to see the product, a part to edit that part. +- The URL is printed (default `http://127.0.0.1:7180`). Give it to the person. +- To try it: `sca example u_link` copies a motor-mount workspace (two parts and + the assembly that fixes them together) to `./u_link_motor_mount`, then + `sca edit ./u_link_motor_mount`. + +## Read what the person is doing + +| Need | Where | +| --- | --- | +| What is selected | the cell headed `# ---- selection ----` in the notebook file | +| Everything at once (selection, cell states, errors, parameter values) | `sca snapshot [WORKSPACE]`, or `/.sca-editor/snapshot.json` | +| What the viewport looks like | `/.sca-editor/viewport.png` (a PNG; look at it) | +| Which notebook is open | `notebook` in the snapshot | + +`sca snapshot` only has an answer while the editor runs; it reports the last +state the editor wrote. If the snapshot is old (`updated`), ask the person to +move the viewport or re-select, or read the notebook file instead. + +## The selection cell + +Every pick in the viewport (Ctrl/Cmd+click adds) rewrites one cell: + +```python +# ---- selection ---- +# edge (of u-link-motor-mount, node node/u_link) +selected_edge_1 = scad.ql.edges().where(scad.ql.and_( + scad.ql.prop("geom.type", "==", "CIRCLE"), + ... +)).exactly(1) +selected_edge_2 = scad.ql.edges().where(...).exactly(1) +selected_item = [selected_edge_1, selected_edge_2] +``` + +- One variable per picked entity: `selected_`, or `selected__` + when several of a kind are picked; `kind` is solid, face, edge or vertex. + `selected_item` lists all of them in pick order. An empty selection is + `selected_item = []`. +- Each selector is built from the entity's geometry (type, centre, size), not + from an id. It keeps selecting the same place while the model is edited, as + long as that geometry stays put. `.exactly(1)` fails loudly if the geometry + moved away, which is the right signal. +- The cell is rewritten at every pick, so **do not put your code in it**. + Build on it from a cell below it or from the cell that makes the feature: + + ```python + # ---- feature: edge-chamfer (modifier) ---- + body = scad.chamfer_rsolid(solid=body, edges=selected_edge_1, distance=1.0) + ``` + +- A selector says where, not what: confirm before changing geometry. Resolve it + and print small QL facts (count, a measurement) per the global rules. If it + matches nothing the person's model changed since the pick: ask them to pick + again rather than guessing. +- Do not rename `selected_*` variables or delete the cell; the editor finds it + again by its first line. When the person is done with the selection, they + clear it themselves. + +### Turning "do X to the selection" into an edit + +1. Read the selection cell and the snapshot (`kind`, how many). +2. Find the cell that owns the geometry (the feature cell that made the body the + selection lies on, by its `# ---- feature: ----` header). +3. Add a feature cell after it, or edit the owning cell, using the selectors by + name. Keep one feature per cell; give it a feature header. +4. Save the file. The editor shows the change (cells you edited show `stale` + until run). Ask the person to run it, or run `sca run ` yourself + to check the model builds, and read the errors. + +## Cell references + +The copy button on a cell's header puts a reference on the person's clipboard, +for pasting to you: + +``` +/path/to/u_link.py:L47-L48 (cell 02 `guard: parameter feasibility (REQUIREMEN`) +``` + +(Alt/Shift+click adds the cell's code in a fenced block.) + +- `path:Lstart-Lend` is the cell's lines in the file; `cell NN` is its position + in the notebook, and the backticked title is the feature slug, params header + or first variable. Trust the path and lines; re-read them in the file, since + they move when cells above are edited. +- "Change this cell" means edit those lines in place. Do not add a duplicate + cell and leave the old one running. +- `@app.function` cells are shown as `function` and are read-only in the + editor (marimo would turn them into plain cells if edited there). Edit them on + disk; the editor reloads. + +## Parameters + +- A `# ---- params ----` cell lists parameters, each optionally with a trailing + `# ui:` comment that sets the control: `slider(min, max, step=)`, + `number(...)`, `toggle()`. Declare the controls you want the person to tune; + without a comment a number gets a number box and a bool a toggle. +- Shared dimensions in a local module (`from dimensions import DIMS`) show in + the workspace tab under *modules*. A module opens in a module view with its + dataclass fields (and constants with a `# ui:` comment) as controls; a change + reloads the module and reruns what imports it. Editing the module file from + disk does the same. +- A slider **does not edit the file**: the value is saved in the notebook's state + directory and the cells that read it rerun. The person's tuned values apply + in the editor only; `sca run` ignores them unless given `--set NAME=VALUE`. + When the person likes a value, they use **Write to source**, or you change + the source. Do not treat the number in the file as what they see on screen: + check `params` in the snapshot. + +## The log dock + +The bottom dock lists what ran and what failed (with times), and during a +re-evaluation shows how many cells are done and which one is running. +Errors there are the same errors `sca snapshot` reports per cell. A module that +does not compile is reported as `setup failed` with the file and line; fix that +file first, since every cell is blocked until it compiles. + +## Rules of thumb + +- Re-read the file before editing: the person edits and autosaves too, and the + editor rewrites the selection cell. +- Edit by cell. A change that touches many cells at once makes the person's + screen reflow and loses their place. +- After an edit, say which cells you changed (by reference) and what to look + at, so the person can run them and judge the result. +- Never edit `__marimo__/` or `.sca-editor/`; both are generated. +- The editor only models. Exports and packages come from `sca run` / + `sca export`, not from the editor. diff --git a/pyproject.toml b/pyproject.toml index b81650a1..65bea2df 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -92,9 +92,17 @@ artifacts = ["src/simplecadapi/editor/webui/**"] [tool.hatch.build.targets.wheel.force-include] "docs/skill" = "simplecadapi/skill/resources/docs/skill" "skillproj.toml" = "simplecadapi/skill/resources/skillproj.toml" +# The notebooks `sca example u_link` copies out. +"examples/u_link_motor_mount/u_link.py" = "simplecadapi/example/resources/u_link_motor_mount/u_link.py" +"examples/u_link_motor_mount/shell.py" = "simplecadapi/example/resources/u_link_motor_mount/shell.py" +"examples/u_link_motor_mount/u_link_motor_mount.py" = "simplecadapi/example/resources/u_link_motor_mount/u_link_motor_mount.py" +"examples/u_link_motor_mount/dimensions.py" = "simplecadapi/example/resources/u_link_motor_mount/dimensions.py" +"examples/u_link_motor_mount/common.py" = "simplecadapi/example/resources/u_link_motor_mount/common.py" [tool.hatch.build.targets.sdist] core-metadata-version = "2.4" +# The release builds its wheel from this sdist, so the built webui has to be in it. +artifacts = ["src/simplecadapi/editor/webui/**"] include = [ "/README.md", "/LICENSE", @@ -113,6 +121,15 @@ exclude = [ "/examples", ] +# The sdist leaves out /examples, but `sca example u_link` builds its wheel +# from these five notebooks (the wheel is built from the sdist on release). +[tool.hatch.build.targets.sdist.force-include] +"examples/u_link_motor_mount/u_link.py" = "examples/u_link_motor_mount/u_link.py" +"examples/u_link_motor_mount/shell.py" = "examples/u_link_motor_mount/shell.py" +"examples/u_link_motor_mount/u_link_motor_mount.py" = "examples/u_link_motor_mount/u_link_motor_mount.py" +"examples/u_link_motor_mount/dimensions.py" = "examples/u_link_motor_mount/dimensions.py" +"examples/u_link_motor_mount/common.py" = "examples/u_link_motor_mount/common.py" + [dependency-groups] dev = [ "twine>=6.1.0", diff --git a/src/simplecadapi/cli.py b/src/simplecadapi/cli.py index 09400087..900b6d8a 100644 --- a/src/simplecadapi/cli.py +++ b/src/simplecadapi/cli.py @@ -5,11 +5,12 @@ Groups, each owned by its module and registered here at parser level so sca init # machine setup: addon home + shell wiring sca addon add|update|remove|list|use - sca skill targets|install + sca skill targets|where|install sca export [--format ...] sca run [--set NAME=VALUE] [--out ...] sca ls [DIR] | sca params sca edit [WORKSPACE] # the web editor (needs the 'editor' extra) + sca example [NAME] [DIR] # copy a bundled example workspace out sca snapshot [WORKSPACE] # what the editor user has selected / sees Shared contract: group handlers return ``(report, exit_code)`` and are @@ -33,6 +34,7 @@ from .skill.compiler import SkillBuildError def build_parser() -> argparse.ArgumentParser: from .addon import cli as addon_cli from .editor import cli as editor_cli + from .example import cli as example_cli from .exporter import cli as exporter_cli from .runtime import cli as runtime_cli from .skill import cli as skill_cli @@ -48,6 +50,7 @@ def build_parser() -> argparse.ArgumentParser: subparsers = parser.add_subparsers(dest="group", required=True) addon_cli.configure(subparsers) editor_cli.configure(subparsers) + example_cli.configure(subparsers) exporter_cli.configure(subparsers) runtime_cli.configure(subparsers) skill_cli.configure(subparsers) diff --git a/src/simplecadapi/example/__init__.py b/src/simplecadapi/example/__init__.py new file mode 100644 index 00000000..7fee03af --- /dev/null +++ b/src/simplecadapi/example/__init__.py @@ -0,0 +1,6 @@ +"""Bundled example workspaces, copied out for a person to open in ``sca edit``.""" + +from .cli import configure +from .runtime import EXAMPLES, copy_example, example_names + +__all__ = ["EXAMPLES", "configure", "copy_example", "example_names"] diff --git a/src/simplecadapi/example/cli.py b/src/simplecadapi/example/cli.py new file mode 100644 index 00000000..d164f250 --- /dev/null +++ b/src/simplecadapi/example/cli.py @@ -0,0 +1,52 @@ +"""The ``sca example`` command (see :mod:`simplecadapi.cli`). + +:: + + sca example # list the examples + sca example u_link [DIR] # copy one out, ready for ``sca edit`` +""" + +from __future__ import annotations + +import argparse +import shlex +from pathlib import Path +from typing import Any + +from .runtime import EXAMPLES, copy_example, example_names + + +def configure(subparsers: argparse._SubParsersAction) -> None: + parser = subparsers.add_parser( + "example", + help="copy a bundled example workspace out to open in the editor", + description="Copy a bundled example (a directory of SimpleCAD notebooks) into DIR " + "(default: ./), then open it with `sca edit`. Without a name, " + "list the examples. An existing directory is never overwritten.", + ) + parser.add_argument("name", nargs="?", choices=example_names(), help="the example to copy") + parser.add_argument("directory", nargs="?", type=Path, help="where to copy it to") + parser.set_defaults(handler=_run, printer=_print) + + +def _run(args: argparse.Namespace) -> tuple[dict[str, Any], int]: + if args.name is None: + return {"examples": {name: EXAMPLES[name].summary for name in example_names()}}, 0 + target = copy_example(args.name, args.directory) + example = EXAMPLES[args.name] + opened = (target / example.open_with).resolve() + return { + "name": args.name, + "path": str(target), + "files": sorted(path.name for path in target.iterdir()), + "edit": f"sca edit {shlex.quote(str(opened))}", + }, 0 + + +def _print(report: dict[str, Any]) -> None: + if "examples" in report: + for name, summary in report["examples"].items(): + print(f"{name}\t{summary}") + return + print(f"copied {report['name']} to {report['path']} ({len(report['files'])} files)") + print(f"open it: {report['edit']}") diff --git a/src/simplecadapi/example/runtime.py b/src/simplecadapi/example/runtime.py new file mode 100644 index 00000000..990c6015 --- /dev/null +++ b/src/simplecadapi/example/runtime.py @@ -0,0 +1,83 @@ +"""Find and copy the bundled example workspaces. + +An example is a directory of notebooks. The wheel carries the sources under +``resources/`` (see ``pyproject.toml``); a checkout (editable install) reads +them from ``examples/`` at the repository root. +""" + +from __future__ import annotations + +import shutil +from dataclasses import dataclass +from pathlib import Path + + +@dataclass(frozen=True) +class Example: + name: str + directory: str + """Name of the directory it is copied to by default.""" + open_with: str + """What to hand ``sca edit``, relative to the copy.""" + summary: str + + +EXAMPLES: dict[str, Example] = { + "u_link": Example( + name="u_link", + directory="u_link_motor_mount", + open_with=".", + summary="a motor mount: two parts and the assembly that fixes them together, " + "driven by the shared dimensions in dimensions.py", + ), +} + +_SOURCES = { + "u_link": ( + "u_link.py", + "shell.py", + "u_link_motor_mount.py", + "dimensions.py", + "common.py", + ), +} + + +def example_names() -> list[str]: + return sorted(EXAMPLES) + + +def _source_root(example: Example) -> Path: + bundled = Path(__file__).parent / "resources" / example.directory + if bundled.is_dir(): + return bundled + # An editable install keeps the examples where the repository has them. + return Path(__file__).resolve().parents[3] / "examples" / example.directory + + +def copy_example(name: str, destination: Path | None = None) -> Path: + """Copy example *name* to *destination* (default: its own name in the current directory). + + Refuses to write into an existing directory, so nothing of the person's is + overwritten. Returns the directory made. + """ + if name not in EXAMPLES: + raise ValueError(f"unknown example {name!r}; choose from: {', '.join(example_names())}") + example = EXAMPLES[name] + target = (destination if destination is not None else Path.cwd() / example.directory).expanduser() + target = target.absolute() + if target.exists(): + raise ValueError(f"{target} already exists; pick another directory (nothing was changed)") + source = _source_root(example) + files = [source / relative for relative in _SOURCES[name]] + missing = [file.name for file in files if not file.is_file()] + if missing: + raise ValueError(f"the bundled example is incomplete (missing {', '.join(missing)}); reinstall simplecadapi") + target.mkdir(parents=True) + try: + for file in files: + shutil.copy2(file, target / file.name) + except OSError: + shutil.rmtree(target, ignore_errors=True) + raise + return target diff --git a/src/simplecadapi/runtime/_marimo.py b/src/simplecadapi/runtime/_marimo.py index 971161f8..2760aea5 100644 --- a/src/simplecadapi/runtime/_marimo.py +++ b/src/simplecadapi/runtime/_marimo.py @@ -78,7 +78,7 @@ def load_notebook(path: Path, *, cell_prefix: str) -> App | None: marimo compiles each cell under a file name made of its cell id, and registers the cell's source in :mod:`linecache` under that name. Cell ids come from a fixed seed, so every notebook has the same ones: two - notebooks loaded into one process (a ``use``\ d child, or a headless + notebooks loaded into one process (a child run by ``use``, or a headless run inside the editor kernel) would show each other's source in tracebacks, source positions and restored functions. A prefix per notebook keeps them apart, as marimo's own prefix for nested apps does. diff --git a/src/simplecadapi/skill/cli.py b/src/simplecadapi/skill/cli.py index c10c4fc2..8073c898 100644 --- a/src/simplecadapi/skill/cli.py +++ b/src/simplecadapi/skill/cli.py @@ -15,6 +15,13 @@ def configure(subparsers: argparse._SubParsersAction) -> None: ) commands = skill.add_subparsers(dest="command", required=True) commands.add_parser("targets", help="list supported harness targets") + where = commands.add_parser( + "where", help="print where `install` would put the skill (nothing is written)" + ) + where.add_argument( + "--skills-dir", type=Path, + help="skills parent directory (default: config/env or ~/.agents/skills)", + ) install = commands.add_parser( "install", help="compile the bundled skill into /" ) @@ -37,6 +44,9 @@ def _run(args: argparse.Namespace) -> tuple[dict[str, Any], int]: if args.command == "targets": return {"targets": list(project.targets)}, 0 skills_dir = resolve_paths(skills_dir=args.skills_dir).skills_dir + if args.command == "where": + destination = skills_dir.expanduser().absolute() / project.name + return {"where": str(destination), "exists": destination.exists()}, 0 report = build_skill( project=project, target=args.target, @@ -50,6 +60,8 @@ def _run(args: argparse.Namespace) -> tuple[dict[str, Any], int]: def _print(report: dict[str, Any]) -> None: if "targets" in report: print("\n".join(report["targets"])) + elif "where" in report: + print(report["where"]) else: print( f"installed {report['name']} for {report['target']}: " diff --git a/test/test_example_cli.py b/test/test_example_cli.py new file mode 100644 index 00000000..1e5dd923 --- /dev/null +++ b/test/test_example_cli.py @@ -0,0 +1,46 @@ +"""``sca example``: a bundled example workspace copied out for the editor.""" +from pathlib import Path + +import pytest + +from simplecadapi.cli import main, run +from simplecadapi.runtime.workspace import scan_workspace + + +def test_without_a_name_the_examples_are_listed(): + report, code, printer = run(["example"]) + assert code == 0 and "u_link" in report["examples"] + printer(report) + + +def test_copy_makes_a_workspace_the_editor_can_open(tmp_path, capsys): + target = tmp_path / "demo" + report, code, printer = run(["example", "u_link", str(target)]) + assert code == 0 and Path(report["path"]) == target + assert report["edit"].startswith("sca edit ") and str(target) in report["edit"] + entries = {entry.path: entry for entry in scan_workspace(target)} + assert set(entries) == {"shell.py", "u_link.py", "u_link_motor_mount.py"} + assert entries["u_link_motor_mount.py"].kind == "assembly" + assert set(entries["u_link_motor_mount.py"].uses) == {"u_link.py", "shell.py"} + printer(report) + assert "open it:" in capsys.readouterr().out + + +def test_an_existing_directory_is_never_overwritten(tmp_path, capsys): + target = tmp_path / "mine" + target.mkdir() + (target / "notes.txt").write_text("keep me") + assert main(["example", "u_link", str(target)]) == 2 + assert "already exists" in capsys.readouterr().err + assert [path.name for path in target.iterdir()] == ["notes.txt"] + + +def test_the_default_directory_is_the_examples_own_name(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + report, _, _ = run(["example", "u_link"]) + assert Path(report["path"]) == tmp_path / "u_link_motor_mount" + + +def test_an_unknown_example_is_refused(): + with pytest.raises(SystemExit): + run(["example", "nope"]) diff --git a/test/test_skill_cli.py b/test/test_skill_cli.py index 36abf4ad..0e0f9574 100644 --- a/test/test_skill_cli.py +++ b/test/test_skill_cli.py @@ -124,3 +124,27 @@ def test_main_reports_unknown_target_without_traceback(project, tmp_path, capsys error = capsys.readouterr().err assert "unknown target" in error and "Traceback" not in error assert not (tmp_path / "s").exists() + + +def test_where_reports_the_destination_without_writing(project, tmp_path): + report, code, printer = run(["skill", "where"]) + expected = tmp_path / "home" / ".agents" / "skills" / "demo" + assert code == 0 and Path(report["where"]) == expected and report["exists"] is False + assert not expected.parent.exists() # nothing was created + printer(report) + run(install_args()) + assert run(["skill", "where"])[0]["exists"] is True + elsewhere, _, _ = run(["skill", "where", "--skills-dir", str(tmp_path / "other")]) + assert Path(elsewhere["where"]) == tmp_path / "other" / "demo" + + +def test_where_reports_the_destination_without_writing(project, tmp_path): + report, code, printer = run(["skill", "where"]) + expected = tmp_path / "home" / ".agents" / "skills" / "demo" + assert code == 0 and Path(report["where"]) == expected and report["exists"] is False + assert not expected.parent.exists() # nothing was created + printer(report) + run(install_args()) + assert run(["skill", "where"])[0]["exists"] is True + elsewhere, _, _ = run(["skill", "where", "--skills-dir", str(tmp_path / "other")]) + assert Path(elsewhere["where"]) == tmp_path / "other" / "demo"