Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
e0ff0e5
feat(core): local-path guard shared by the Studio+ tracks
DVOpenLabs Nov 1, 2026
ecd0404
feat(creative): creative-tool container inspection (P2)
DVOpenLabs Nov 1, 2026
80a96e8
feat(calibration): calibration library and comparison (P4)
DVOpenLabs Nov 1, 2026
87fcc26
feat(assemblies): assembly library (P5)
DVOpenLabs Nov 1, 2026
4342251
feat(variants): output variant comparison (P6)
DVOpenLabs Nov 1, 2026
ac89ce9
feat(passport): job passport and u1convert passport commands (P7)
DVOpenLabs Nov 1, 2026
9f18b2c
feat(recovery): workspace recovery and monitoring context (P8)
DVOpenLabs Nov 1, 2026
d8b44e4
test: cross-track review-fix regression tests
DVOpenLabs Nov 1, 2026
78cd887
test(passport): keep the foreign-locator fixture path out of /home
DVOpenLabs Nov 1, 2026
0c1a8c6
docs: correct network and evidence wording in the passport, creative …
DVOpenLabs Nov 1, 2026
082af75
fix(passport): pin the export output directory so a swap cannot redir…
DVOpenLabs Nov 13, 2026
c824bf0
fix(passport): close Windows in-place junction and Linux /proc gaps i…
DVOpenLabs Nov 13, 2026
3e89141
fix(passport): exact file-path check, platform-aware name test, repor…
DVOpenLabs Nov 13, 2026
f84829a
test(passport): drive the post-recheck window and the failed-cleanup …
DVOpenLabs Nov 13, 2026
4be90cb
docs(passport): state the interrupted-write, filesystem and macOS lim…
DVOpenLabs Nov 14, 2026
b23dbc2
Merge pull request #147 from DVOpenLabs/fix/passport-export-publication
DVOpenLabs Nov 14, 2026
8f70ce1
Merge integ/phase2 (with main) into feat/portfolio-integration
DVOpenLabs Nov 14, 2026
ba878b4
Merge main (with #138) into feat/portfolio-integration
DVOpenLabs Nov 14, 2026
6304dac
fix(calibration): real palette inputs, empty initial readings, refuse…
DVOpenLabs Nov 14, 2026
dcfc697
docs(calibration): README for real palette formats and basis identity
DVOpenLabs Nov 14, 2026
f40a18d
fix(creative): refuse entity/DTD 3MF model XML in every encoding
DVOpenLabs Nov 14, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 129 additions & 0 deletions backend/snapstudio_api/routes_assemblies.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
"""Routes of the Assemblies track: plan a multi-tile project against shared spools.

POST /assemblies/evaluate {assembly, supply?, now?} -> {report}
POST /assemblies/save {assembly, id?, expected_revision?} -> {id, revision, assembly}
POST /assemblies/list {} -> {assemblies}
POST /assemblies/get {id} -> {id, revision, assembly}
POST /assemblies/delete {id} -> {deleted}

Everything here is local arithmetic and local files: no network request of its own, no printer, no
model file is written (file-path checks are best-effort, see snapstudio_core/localpath.py). The library is only read (to say whether a tile's project is still there and unchanged).
The verdicts are advisory.
"""
from __future__ import annotations

import hashlib
import os
from snapstudio_core import localpath
import sqlite3

from snapstudio_core import paths
from snapstudio_core.assemblies import evaluate as ev
from snapstudio_core.assemblies import store
from snapstudio_core.assemblies.model import AssemblyInputError, read_assembly
from snapstudio_core.foundation.decode import is_finite_number

from . import ext_routes
from . import request_validation as rv

#: A library file larger than this is not re-hashed inside a request; its tile says "unverified".
MAX_HASH_BYTES = 256 * 1024 * 1024


def _refused(exc: AssemblyInputError) -> rv.ValidationError:
return rv.ValidationError(str(exc))


def _id(data: dict) -> int:
value = data.get("id")
if isinstance(value, bool) or not isinstance(value, int) or value < 1:
raise rv.ValidationError("Missing or invalid 'id'")
return value


def _now(data: dict):
value = data.get("now")
if value is None:
return None
if not is_finite_number(value) or value < 0:
raise rv.ValidationError("Invalid 'now'")
return value


def _sha256_of(path: str) -> str | None:
if not localpath.is_local_regular_file(path, max_bytes=MAX_HASH_BYTES):
return None
try:
if os.path.getsize(path) > MAX_HASH_BYTES:
return None
digest = hashlib.sha256()
with open(path, "rb") as fh:
for chunk in iter(lambda: fh.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
except OSError:
return None


def library_lookup(project_id: int) -> dict | None:
"""The library row for `project_id`, read-only: {sha256} of its source file, or None when it is gone.

Opens `library.db` read-only and never creates it; a missing library means no project is in it.
"""
db = os.path.join(paths.data_dir(create=False), "library.db")
if not os.path.isfile(db):
return None
uri = "file:" + db.replace("\\", "/").replace("?", "%3f").replace("#", "%23") + "?mode=ro"
try:
conn = sqlite3.connect(uri, uri=True, timeout=2)
try:
row = conn.execute("SELECT source_path FROM projects WHERE id=?", (project_id,)).fetchone()
finally:
conn.close()
except sqlite3.Error:
return {"sha256": None} # a locked or unfamiliar library leaves the tile unverified
if row is None:
return None
return {"sha256": _sha256_of(row[0]) if isinstance(row[0], str) else None}


@ext_routes.route("/assemblies/evaluate")
def evaluate(data: dict) -> tuple[int, dict]:
try:
assembly = read_assembly(data.get("assembly"))
now = _now(data)
supply = ev.read_supply(data.get("supply"), now)
except AssemblyInputError as exc:
raise _refused(exc) from None
lookup = library_lookup if any(t.library is not None for t in assembly.tiles) else None
return 200, {"report": ev.evaluate(assembly, supply, now=now, lookup=lookup)}


@ext_routes.route("/assemblies/save")
def save(data: dict) -> tuple[int, dict]:
expected = data.get("expected_revision")
if expected is not None and (isinstance(expected, bool) or not isinstance(expected, int) or expected < 0):
raise rv.ValidationError("Invalid 'expected_revision'")
assembly_id = _id(data) if data.get("id") is not None else None
try:
return 200, store.save(data.get("assembly"), assembly_id, expected)
except AssemblyInputError as exc:
raise _refused(exc) from None


@ext_routes.route("/assemblies/list")
def list_saved(data: dict) -> tuple[int, dict]:
return 200, {"assemblies": store.list_saved()}


@ext_routes.route("/assemblies/get")
def get(data: dict) -> tuple[int, dict]:
try:
return 200, store.get(_id(data))
except AssemblyInputError as exc:
raise _refused(exc) from None


@ext_routes.route("/assemblies/delete")
def delete(data: dict) -> tuple[int, dict]:
return 200, {"deleted": store.delete(_id(data))}
80 changes: 80 additions & 0 deletions backend/snapstudio_api/routes_calibration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
"""Palette calibration routes. All work is local parsing, comparison and persistence."""
from __future__ import annotations

import re

from snapstudio_core import paths
from snapstudio_core.calibration import palette as palette_reader
from snapstudio_core.calibration import service
from snapstudio_core.foundation.decode import Decoded

from . import ext_routes
from . import request_validation as rv

_COLOR = re.compile(r"^#[0-9A-Fa-f]{6}$")


def _decoded_dict(decoded: Decoded) -> dict:
return decoded.to_dict()


def _colors(data: dict) -> dict[str, str]:
raw = data.get("physical_colors", {})
if not isinstance(raw, dict) or len(raw) > 256:
raise rv.ValidationError("Invalid 'physical_colors'")
result = {}
for key, value in raw.items():
if not str(key).isdigit() or not isinstance(value, str) or not _COLOR.fullmatch(value):
raise rv.ValidationError("Invalid 'physical_colors'")
result[str(key)] = value.upper()
return result


def _owned(data: dict) -> list[dict]:
rows = data.get("owned_filaments", [])
if not isinstance(rows, list) or len(rows) > 100:
raise rv.ValidationError("Invalid 'owned_filaments'")
result = []
for row in rows:
if not isinstance(row, dict):
raise rv.ValidationError("Invalid 'owned_filaments'")
color = row.get("color")
label = row.get("label", "Owned filament")
if not isinstance(color, str) or not _COLOR.fullmatch(color) or not isinstance(label, str) or len(label) > 80:
raise rv.ValidationError("Invalid 'owned_filaments'")
result.append({"color": color.upper(), "label": label})
return result


@ext_routes.route("/calibration/evaluate")
def evaluate(data: dict) -> tuple[int, dict]:
source = data.get("source")
if source not in ("ditherforge_txt", "kromacut_json"):
raise rv.ValidationError("Invalid 'source'")
content = data.get("content")
if not isinstance(content, str) or len(content.encode("utf-8")) > 512_000:
raise rv.ValidationError("Invalid 'content'")
decoded = palette_reader.parse_palette(source, content)
if decoded.value is None:
return 200, {"status": "unknown", "decoded": _decoded_dict(decoded), "result": None}
family = data.get("family")
if family not in ("frontlit", "backlit"):
raise rv.ValidationError("Invalid 'family'")
material = rv.require_bounded_str(data, "material", 32) if "material" in data else "PLA"
if not material.strip():
raise rv.ValidationError("Material must not be empty")
basis = service.basis_document(family, rv.require_positive_float(data, "layer_height_mm"),
rv.optional_positive_float(data, "nozzle_mm", 0.4),
material,
source=source, model=rv.optional_bounded_str(data, "model", 128),
first_layer_height_mm=rv.require_positive_float(data, "first_layer_height_mm")
if "first_layer_height_mm" in data else None)
palette = decoded.value.to_dict()
result = service.evaluate(palette, basis, _colors(data), _owned(data))
saved = service.save_run(basis, palette, result, data_dir=paths.data_dir())
return 200, {"status": "evaluated", "decoded": _decoded_dict(decoded), "result": saved}


@ext_routes.route("/calibration/history")
def get_history(data: dict) -> tuple[int, dict]:
return 200, {"runs": service.history(data_dir=paths.data_dir())}
180 changes: 180 additions & 0 deletions backend/snapstudio_api/routes_creative.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
"""Routes of the Creative track: inspect one local creative project (3MF) and say what Studio read.

POST /creative/inspect {path, format?} -> {origin, understood, passed_through, could_not_interpret,
missing, diagnostics, recipes, source, evidence, advisory}

The handler opens the file for reading only. It never writes, renames or deletes anything, never
slices, never contacts a printer and makes no network request of its own (the local-path check is
best-effort, see snapstudio_core/localpath.py). `source` carries the SHA-256 of the
file before the readers ran and again afterwards, so the response itself shows the original is
unchanged. Recipes are simulated: `execution_supported` is False and nothing here runs them. An
unrecognised generator is reported as origin "unknown", never guessed.
"""
from __future__ import annotations

import hashlib
import os

from snapstudio_core import localpath
from snapstudio_core.creative import container, readers

from . import ext_routes
from . import request_validation as rv

#: Same ceiling the 3MF reader enforces; a larger file is refused before it is read.
MAX_FILE_BYTES = container.MAX_ARCHIVE_BYTES
MAX_PATH_CHARS = 1024

EVIDENCE = "fixture-tested; fixtures are hand-written to published shapes, not captures"
ADVISORY = ("Advisory read of one project file. Studio does not slice, does not run recipes and "
"does not change the file. What it could not interpret is listed, not guessed.")

#: format hint -> reader. "auto" picks by the keys the project settings contain.
_READERS = {
"forcaslicer": readers.read_forca,
"lixnix": readers.read_lixnix,
"fullspectrum": readers.read_fullspectrum,
"imagemap": readers.read_imagemap,
"lumina": readers.read_lumina,
}
_FORMATS = ("auto",) + tuple(_READERS)

_ERROR_TEXT = {
"bad_zip": "That file is not a readable 3MF archive.",
"archive_too_large": "That file is larger than the inspector reads.",
"too_many_members": "That archive holds more parts than the inspector reads.",
"unsafe_member_name": "That archive has a part name that is not safe to read.",
"duplicate_member": "That archive lists the same part name twice.",
"member_too_large": "A part inside that archive is larger than the inspector reads.",
"archive_expanded_too_large": "That archive expands to more data than the inspector reads.",
"compression_ratio_exceeded": "A part inside that archive expands far more than a normal 3MF.",
"bad_zip_member": "A part inside that archive could not be read.",
"truncated_member": "A part inside that archive is truncated.",
"missing_model": "That archive has no 3D model part, so it is not a 3MF project.",
"unsafe_xml": "The model part uses XML features the inspector does not read.",
"bad_xml": "The model part is not valid XML.",
"unsupported_3mf_version": "That 3MF uses a core namespace the inspector does not read.",
"bad_project_settings": "The project settings part is not a JSON object.",
}


def _path(data: dict) -> str:
raw = rv.require_path_string(data, "path")
if len(raw) > MAX_PATH_CHARS or "\x00" in raw:
raise rv.ValidationError("Invalid 'path'")
return raw


def _format(data: dict) -> str:
value = data.get("format", "auto")
if not isinstance(value, str) or value not in _FORMATS:
raise rv.ValidationError("Invalid 'format'")
return value


def _read_source(path: str) -> bytes:
"""The file bytes, after checking it is a regular file under the size cap. Read-only open."""
try:
if localpath.is_network_or_device_path(path) or not localpath.is_local_regular_file(path):
raise rv.ValidationError("That path is not a local file Studio can read.")
if os.path.getsize(path) > MAX_FILE_BYTES:
raise rv.ValidationError("That file is larger than the inspector reads.")
with open(path, "rb") as fh:
blob = fh.read(MAX_FILE_BYTES + 1)
except rv.ValidationError:
raise
except OSError:
raise rv.ValidationError("That file could not be opened.") from None
if len(blob) > MAX_FILE_BYTES:
raise rv.ValidationError("That file is larger than the inspector reads.")
return blob


def _detect(settings: dict) -> list[str]:
"""Formats whose published keys are present. Several can match; none means unknown."""
keys = set(settings)
found = []
if keys & readers._FORCA_KEYS:
found.append("forcaslicer")
if keys & readers._LIX_KEYS:
found.append("lixnix")
if keys & readers._FULLSPECTRUM_KEYS:
found.append("fullspectrum")
return found


def _wrap(exc: container.ContainerError) -> rv.ValidationError:
code = str(exc)
return rv.ValidationError(_ERROR_TEXT.get(code, "That file could not be read as a 3MF project."))


@ext_routes.route("/creative/inspect")
def inspect(data: dict) -> tuple[int, dict]:
path = _path(data)
hint = _format(data)
blob = _read_source(path)
before = hashlib.sha256(blob).hexdigest()
try:
manifest = container.read_3mf(blob)
except container.ContainerError as exc:
raise _wrap(exc) from None

settings = manifest.project_settings or {}
names = [hint] if hint != "auto" else _detect(settings)
projects = []
try:
for name in names:
projects.append(_READERS[name](blob))
except container.ContainerError as exc:
raise _wrap(exc) from None

if not projects:
# Unknown generator: container identity only. Every part is preserved, nothing is interpreted.
passed = [{"name": m.name, "sha256": m.sha256} for m in manifest.passed_through]
passed += [{"name": k, "sha256": readers._digest_obj({k: v})["sha256"]} for k, v in sorted(settings.items())]
origin = {"generator": "unknown", "status": "unknown", "candidates": []}
understood = [p for p in manifest.understood_parts]
unknown: list = []
missing: list = []
diagnostics = ["generator_not_recognized"]
recipes: list = []
slots = None
else:
status = "detected" if len(projects) == 1 else "ambiguous"
origin = {"generator": projects[0].source_format if len(projects) == 1 else "unknown",
"status": status if hint == "auto" else "chosen",
"candidates": [p.source_format for p in projects]}
understood = sorted({k for p in projects for k in p.understood})
seen = set()
passed = []
for p in projects:
for item in p.passed_through:
key = (item["name"], item["sha256"])
if key not in seen:
seen.add(key)
passed.append(item)
# A key one reader understood is not passed through by another reading of the same file.
passed = [i for i in passed if i["name"] not in understood]
unknown = sorted({u for p in projects for u in p.unknown})
missing = sorted({m for p in projects for m in p.missing})
diagnostics = [d for p in projects for d in p.diagnostics]
recipes = [r.to_dict() for p in projects for r in p.recipes]
slots = next((p.physical_slots_needed for p in projects if p.recipes), None)

after = _read_source(path)
after_hash = hashlib.sha256(after).hexdigest()
return 200, {
"origin": origin,
"understood": list(understood),
"passed_through": passed,
"could_not_interpret": list(unknown),
"missing": list(missing),
"diagnostics": list(diagnostics),
"recipes": recipes,
"physical_slots_needed": slots,
"source": {"name": os.path.basename(path), "size_bytes": len(blob),
"sha256_before": before, "sha256_after": after_hash,
"unchanged": before == after_hash},
"evidence": EVIDENCE,
"advisory": ADVISORY,
}
Loading
Loading