diff --git a/INTERFACE.md b/INTERFACE.md index 994f559e..8b1c3ffa 100644 --- a/INTERFACE.md +++ b/INTERFACE.md @@ -352,7 +352,7 @@ cheapest way to keep it from calcifying into one. | `GET /project` | `{root, name, units, parts[], serve_mode, capabilities}` — the `open_project` projection, same serializer as `mcp/app.py` | | `GET /parts` | `[{name, path, content_hash, snapshot_ref}]` — `list_parts` projection. **Same serializer** as `heph part list --json` (`hephaestus.core.project_store.listing`). | | `GET /parts/{part}/script?offset_line&limit_lines` | `read_part` result verbatim, `_PAGING_FIELDS` intact. CLI counterpart: `heph script show --json`. | -| `GET /parts/{part}/build` | `BuildResult` projection: `{status, current, artifact_ref, project_snapshot_ref, effective_params, geometry_count, geometries[], metrics, checks, source_map_ref, warnings, error?, critique?}`. CLI counterpart: `heph part show --json` emits the engine `BuildResult` (same document `heph build --json` writes) or `{status:"not_built"}`. | +| `GET /parts/{part}/build` | `BuildResult` projection: `{status, current, artifact_ref, project_snapshot_ref, effective_params, geometry_count, geometries[], metrics, checks, source_map_ref, warnings, checkpoints[], error?, critique?}`. CLI counterpart: `heph part show --json` emits the engine `BuildResult` (same document `heph build --json` writes) or `{status:"not_built"}`. | | `GET /parts/{part}/properties` | the enumerated `part.*` metadata projection (§6.2) | | `GET /parts/{part}/checks` | the shared `heph check --json` serializer (§6.3) | | `GET /parts/{part}/params` | `PARAMS` declarations `{name, value, default, min, max, step, scope}` + `state_hash`. CLI counterpart: `heph params [PART] --json` (script literals + last-build effective values; no sandbox, no `state_hash` — it does not write `set_params`). | diff --git a/architecture.md b/architecture.md index acd2d768..4fa4b4bc 100644 --- a/architecture.md +++ b/architecture.md @@ -71,9 +71,14 @@ Runs a part script in a sandboxed subprocess with the injected namespace from - **Statement-level execution.** The script is split into top-level statements via `ast`. Statements execute sequentially; after each one the executor - records a checkpoint: statement index, source span, names bound, and — for - names bound to build123d shapes — a metrics snapshot (solid count, bbox, - volume, face count, `sealed` = is-manifold, `genus`). + records a checkpoint: statement index, source span, names bound, the + verbatim statement text, and — for names bound to build123d shapes — a + metrics snapshot (solid count, bbox, volume, face count, `sealed` = + is-manifold, `genus`). Those checkpoints persist on the §8 `BuildResult` + and are projected by `GET /parts/{part}/build` as `checkpoints[]`. Metrics + and per-statement BRep writes stay lazy (mission rule 4): a checkpoint + carries an `artifact_ref` only when publication minted a last-good blob + for that stop. - **Failure semantics.** On exception, the build result MUST include: the failing line and column, exception type, a source frame (±2 lines), the last successfully executed statement, the last-good metrics snapshot, and a diff --git a/core/schemas/build_result.schema.json b/core/schemas/build_result.schema.json index cd1f19df..52269cf6 100644 --- a/core/schemas/build_result.schema.json +++ b/core/schemas/build_result.schema.json @@ -201,6 +201,13 @@ "type": "string" }, "description": "\u00a75.2 manufacturing metadata as the worker evaluated it (runtime truth; empty for pre-2026-08-03 records)." + }, + "checkpoints": { + "type": "array", + "description": "Incremental-executor per-statement checkpoints (architecture \u00a73.1). Absent from records written before the HTTP Timeline projection.", + "items": { + "$ref": "#/$defs/statementCheckpoint" + } } }, "$defs": { @@ -361,6 +368,63 @@ } } }, + "statementCheckpoint": { + "type": "object", + "required": [ + "index", + "line", + "statement", + "span", + "bound", + "shapes", + "artifact_ref" + ], + "additionalProperties": false, + "properties": { + "index": { + "type": "integer", + "minimum": 0 + }, + "line": { + "type": "integer", + "minimum": 1 + }, + "statement": { + "type": "string" + }, + "span": { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + }, + "minItems": 4, + "maxItems": 4 + }, + "bound": { + "type": "array", + "items": { + "type": "string" + } + }, + "shapes": { + "type": "array", + "items": { + "type": "string" + } + }, + "artifact_ref": { + "oneOf": [ + { + "$ref": "#/$defs/artifactRef" + }, + { + "type": "null" + } + ] + } + } + }, "lastGood": { "type": "object", "required": [ diff --git a/core/src/hephaestus/core/executor/runner.py b/core/src/hephaestus/core/executor/runner.py index 25e3219f..3b893480 100644 --- a/core/src/hephaestus/core/executor/runner.py +++ b/core/src/hephaestus/core/executor/runner.py @@ -15,7 +15,7 @@ import json import sys from collections.abc import Mapping -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from pathlib import Path from typing import Literal, cast @@ -51,6 +51,7 @@ GeometryEntry, InputHashes, Metrics, + StatementCheckpoint, Warning, ) from opstore.types import JSONValue @@ -183,6 +184,53 @@ def _require_dict(value: JSONValue, what: str) -> dict[str, JSONValue]: return value +def _checkpoints_from_worker( + raw: JSONValue | None, + last_good_ref: str | None, + error: ErrorRecord | None, +) -> tuple[StatementCheckpoint, ...]: + """Lift the worker's per-statement checkpoints onto the §8 record. + + The worker records index/span/bound/shapes (and, from this change, line + + verbatim statement text). Publication mints at most one checkpoint blob — + the last-good BRep of a failed build — and that ref is attached to the + checkpoint whose line is ``error.built_through.line``. Intermediate stops + carry ``artifact_ref=null``: mission rule 4 keeps per-statement BRep writes + lazy, and inventing a ref the store does not hold would be a lie. + """ + if raw is None: + return () + if not isinstance(raw, list): + raise ValidationError("worker result: checkpoints must be a list", kind="evaluation") + parsed: list[StatementCheckpoint] = [] + for item in raw: + if not isinstance(item, dict): + raise ValidationError("worker result: checkpoints must be objects", kind="evaluation") + record = dict(cast("dict[str, JSONValue]", item)) + span = record.get("span") + if "line" not in record and isinstance(span, list) and span: + first = span[0] + if isinstance(first, int) and not isinstance(first, bool): + record["line"] = first + record.setdefault("statement", "") + record.setdefault("artifact_ref", None) + parsed.append(StatementCheckpoint.from_json(record)) + if last_good_ref is None or error is None or error.built_through is None: + return tuple(parsed) + line = error.built_through.line + attached = False + out: list[StatementCheckpoint] = [] + for checkpoint in parsed: + if not attached and checkpoint.line == line: + out.append(replace(checkpoint, artifact_ref=last_good_ref)) + attached = True + else: + out.append(checkpoint) + if not attached and out: + out[-1] = replace(out[-1], artifact_ref=last_good_ref) + return tuple(out) + + def import_hashes(request: BuildRequest) -> dict[str, str]: """§8 ``input_hashes.imports``: ``{declared path: sha256}`` of the frozen bytes. @@ -469,6 +517,9 @@ def assemble_build( ).items() if isinstance(v, str) }, + checkpoints=_checkpoints_from_worker( + worker_result.get("checkpoints"), last_good_ref, error + ), ) geometry_index_raw = worker_result.get("geometry_index") geometry_index_json = geometry_index_raw if isinstance(geometry_index_raw, dict) else None diff --git a/core/src/hephaestus/core/executor/worker.py b/core/src/hephaestus/core/executor/worker.py index d1aeb0ee..46f47659 100644 --- a/core/src/hephaestus/core/executor/worker.py +++ b/core/src/hephaestus/core/executor/worker.py @@ -1,10 +1,11 @@ """The sandboxed build worker: one JSON job on stdin -> one JSON result on stdout. Executes a part script statement by statement under the §2 injected -namespace, checkpointing after every statement (index, span, bound names; -shape refs are held eagerly, metrics are computed lazily — for the last-good -snapshot on failure and for the final compound on success, per mission -rule 4). On failure it emits the complete §8 error record (line/col, type, +namespace, checkpointing after every statement (index, line, verbatim +statement text, span, bound names; shape refs are held eagerly, metrics +are computed lazily — for the last-good snapshot on failure and for the +final compound on success, per mission rule 4). On failure it emits the +complete §8 error record (line/col, type, message, ±2-line frame with a ``"> "`` marker, ``built_through``, ``last_good`` metrics) and writes the last-good BRep under the out dir; on success it writes the final compound BRep plus geometry index, source map, @@ -489,6 +490,8 @@ def execute_job(job: Mapping[str, JSONValue]) -> dict[str, JSONValue]: last_good.update(statement, bound_shapes) checkpoint: dict[str, JSONValue] = { "index": statement.index, + "line": statement.lineno, + "statement": statement.text, "span": list(statement.span), "bound": list(bound), "shapes": list(shape_names), diff --git a/core/src/hephaestus/core/project_store/publication.py b/core/src/hephaestus/core/project_store/publication.py index f2af57d9..3a1f034c 100644 --- a/core/src/hephaestus/core/project_store/publication.py +++ b/core/src/hephaestus/core/project_store/publication.py @@ -339,6 +339,20 @@ def current_result(self, part: str) -> BuildResult | None: raise ValidationError("current bundle has no result record", kind="contract") return BuildResult.from_json(result_raw) + def last_failure_result(self, part: str) -> BuildResult | None: + """The most-recent failed BuildResult of ``part`` (lock-free read). + + Failed publishes store the §8 record (not a current bundle) at the + last-failure pointer. ``None`` when no failed build has been published. + """ + pointer = self._store.blobs.read_pointer(last_failure_pointer(part)) + if pointer is None: + return None + raw = json.loads(self._store.blobs.get(pointer).decode("utf-8")) + if not isinstance(raw, dict): + raise ValidationError("last-failure record is not an object", kind="contract") + return BuildResult.from_json(cast("Mapping[str, JSONValue]", raw)) + def baseline_for(self, part: str) -> FingerprintBaseline | None: """§5.3 fingerprint baseline: the current bundle's descriptors + ref. diff --git a/core/src/hephaestus/core/types.py b/core/src/hephaestus/core/types.py index eb3b09ba..de995055 100644 --- a/core/src/hephaestus/core/types.py +++ b/core/src/hephaestus/core/types.py @@ -2,10 +2,11 @@ Mirrors ``script_contract.md`` §8 exactly — every field of the build-result record, including the full ``error`` object with ``built_through``, -``last_good``, ``last_good_artifact_ref`` and ``hint`` — plus the CheckReport -shape from ``architecture.md`` §3.4 (check-set generation, immutable bundle -ref, per-file hashes, geometry ``project_snapshot_ref``, per-check -pass + measured). +``last_good``, ``last_good_artifact_ref`` and ``hint``, plus the incremental +executor's per-statement ``checkpoints`` (architecture §3.1) — and the +CheckReport shape from ``architecture.md`` §3.4 (check-set generation, +immutable bundle ref, per-file hashes, geometry ``project_snapshot_ref``, +per-check pass + measured). Every record serializes with ``to_json()`` (a JSON-ready dict) and rebuilds with ``from_json()``. The committed JSON Schema at @@ -74,6 +75,16 @@ def _str_map(data: Mapping[str, JSONValue], key: str) -> dict[str, str]: return out +def _str_tuple(data: Mapping[str, JSONValue], key: str) -> tuple[str, ...]: + raw = cast("list[JSONValue]", _req(data, key, list)) + out: list[str] = [] + for item in raw: + if not isinstance(item, str): + raise ValidationError(f"field {key!r}: expected list of str", kind="contract") + out.append(item) + return tuple(out) + + @dataclass(frozen=True) class InputHashes: """§8 ``input_hashes``: the immutable snapshot identity of a build.""" @@ -277,6 +288,56 @@ def from_json(cls, data: Mapping[str, JSONValue]) -> BuiltThrough: return cls(line=_req(data, "line", int), statement=_req(data, "statement", str)) +@dataclass(frozen=True) +class StatementCheckpoint: + """One incremental-executor per-statement checkpoint (architecture §3.1). + + The worker records these after every top-level statement that completed: + index, source span, names bound, and shape-binding names. ``statement`` is + the verbatim source slice so a Timeline (or a repair loop) can name the + stop without slicing the script itself. ``artifact_ref`` is set only when + publication minted a blob for that stop — today that is the last-good + checkpoint of a failed build, never an invented per-statement BRep. + """ + + index: int + line: int + statement: str + span: tuple[int, int, int, int] + bound: tuple[str, ...] + shapes: tuple[str, ...] + artifact_ref: str | None = None + + def to_json(self) -> dict[str, JSONValue]: + return { + "index": self.index, + "line": self.line, + "statement": self.statement, + "span": list(self.span), + "bound": list(self.bound), + "shapes": list(self.shapes), + "artifact_ref": self.artifact_ref, + } + + @classmethod + def from_json(cls, data: Mapping[str, JSONValue]) -> StatementCheckpoint: + span_raw = cast("list[JSONValue]", _req(data, "span", list)) + if len(span_raw) != 4 or not all( + isinstance(item, int) and not isinstance(item, bool) for item in span_raw + ): + raise ValidationError("field 'span': expected four integers", kind="contract") + span = cast("tuple[int, int, int, int]", tuple(span_raw)) + return cls( + index=_req(data, "index", int), + line=_req(data, "line", int), + statement=_req(data, "statement", str), + span=span, + bound=_str_tuple(data, "bound"), + shapes=_str_tuple(data, "shapes"), + artifact_ref=_opt_str(data, "artifact_ref"), + ) + + @dataclass(frozen=True) class LastGood: """§8 ``error.last_good``: metrics of the last-good checkpoint geometry.""" @@ -395,6 +456,11 @@ class BuildResult: #: downstream reader into literal-only static script parsing — the #: nest-gusset "missing" blank_size the model had in fact written). metadata: Mapping[str, str] = field(default_factory=dict[str, str]) + #: Incremental-executor per-statement checkpoints. Empty on records written + #: before this field existed — the worker always recorded them; the §8 + #: record used to drop them, which left ``GET /parts/{part}/build`` unable + #: to name the stops the Timeline is a projection of. + checkpoints: tuple[StatementCheckpoint, ...] = () def __post_init__(self) -> None: if self.status not in ("ok", "failed"): @@ -423,6 +489,7 @@ def to_json(self) -> dict[str, JSONValue]: "warnings": [warning.to_json() for warning in self.warnings], "error": None if self.error is None else self.error.to_json(), "metadata": dict(self.metadata), + "checkpoints": [checkpoint.to_json() for checkpoint in self.checkpoints], } @classmethod @@ -487,6 +554,9 @@ def from_json(cls, data: Mapping[str, JSONValue]) -> BuildResult: error=error, # Absent from pre-2026-08-03 records; {} is the honest reading. metadata=_str_map(data, "metadata") if "metadata" in data else {}, + # Absent from records written before the HTTP Timeline projection; + # () is the honest reading of "this build named no statement stops". + checkpoints=_checkpoints(data) if "checkpoints" in data else (), ) def __eq__(self, other: object) -> bool: @@ -571,6 +641,16 @@ def __hash__(self) -> int: return hash((self.part, self.check_set_generation, self.check_bundle_ref)) +def _checkpoints(data: Mapping[str, JSONValue]) -> tuple[StatementCheckpoint, ...]: + raw = cast("list[JSONValue]", _req(data, "checkpoints", list)) + out: list[StatementCheckpoint] = [] + for item in raw: + if not isinstance(item, dict): + raise ValidationError("checkpoints: expected list of objects", kind="contract") + out.append(StatementCheckpoint.from_json(cast("dict[str, JSONValue]", item))) + return tuple(out) + + __all__: Sequence[str] = ( "AuditHashes", "BuildResult", @@ -583,5 +663,6 @@ def __hash__(self) -> int: "InputHashes", "LastGood", "Metrics", + "StatementCheckpoint", "Warning", ) diff --git a/core/tests/test_executor_build.py b/core/tests/test_executor_build.py index 42b519ea..7677d3ac 100644 --- a/core/tests/test_executor_build.py +++ b/core/tests/test_executor_build.py @@ -119,6 +119,11 @@ def test_checkpoints_cover_every_statement(self, golden: UnpublishedBuild) -> No for name in bound: by_bound.setdefault(str(name), []).append(str(index)) assert "base" in by_bound and "slotted" in by_bound and "posts" in by_bound + # The §8 record carries the same stops the worker recorded — this is + # the projection GET /parts/{part}/build reads, not a second list. + assert [c.index for c in golden.result.checkpoints] == list(range(STATEMENT_COUNT)) + assert all(c.artifact_ref is None for c in golden.result.checkpoints) + assert golden.result.checkpoints[0].statement.startswith("PARAMS") def test_checkpoint_spans_are_exact(self, golden: UnpublishedBuild) -> None: checkpoints_raw = golden.worker_result["checkpoints"] diff --git a/core/tests/test_executor_failure.py b/core/tests/test_executor_failure.py index 5a36be50..3c1868e8 100644 --- a/core/tests/test_executor_failure.py +++ b/core/tests/test_executor_failure.py @@ -112,6 +112,17 @@ def test_checkpoints_stop_at_failure(self, failed: UnpublishedBuild) -> None: checkpoints = failed.worker_result["checkpoints"] assert isinstance(checkpoints, list) assert len(checkpoints) == 4 # statements before the failing fillet + persisted = failed.result.checkpoints + assert len(persisted) == 4 + last_good = error_of(failed).last_good_artifact_ref + assert last_good is not None + # The last completed statement is the rewindable last-good stop. + assert persisted[-1].artifact_ref == last_good + assert all(stop.artifact_ref is None for stop in persisted[:-1]) + built_through = error_of(failed).built_through + assert built_through is not None + assert persisted[-1].line == built_through.line + assert persisted[-1].statement class TestNamespaceDenialBuildError: diff --git a/core/tests/test_project_store_publication.py b/core/tests/test_project_store_publication.py index dc6c894d..be92e386 100644 --- a/core/tests/test_project_store_publication.py +++ b/core/tests/test_project_store_publication.py @@ -158,6 +158,10 @@ def test_failed_build_publishes_evidence_only( outcome = publisher.publish_build(failed, op_id="pub-failed") assert outcome.kind == "failed" assert outcome.result.current is False + recorded = publisher.last_failure_result("widget") + assert recorded is not None + assert recorded.status == "failed" + assert recorded.artifact_ref is None # Checkpoint evidence blobs are published... assert len(outcome.evidence_refs) == 1 checkpoint_ref = outcome.evidence_refs[0] diff --git a/core/tests/test_types.py b/core/tests/test_types.py index fc6dce52..57438622 100644 --- a/core/tests/test_types.py +++ b/core/tests/test_types.py @@ -20,6 +20,7 @@ InputHashes, LastGood, Metrics, + StatementCheckpoint, Warning, ) from jsonschema import Draft202012Validator @@ -141,6 +142,17 @@ def failed_result() -> BuildResult: last_good_artifact_ref=_REF_CHECKPOINT, hint="inspect_part(name, artifact_ref=last_good_artifact_ref) renders this snapshot", ), + checkpoints=( + StatementCheckpoint( + index=0, + line=44, + statement="tread_shelf = slotted_shelf - groove_cutter", + span=(44, 0, 44, 48), + bound=("tread_shelf",), + shapes=("tread_shelf",), + artifact_ref=_REF_CHECKPOINT, + ), + ), ) @@ -228,6 +240,9 @@ def test_failed_round_trip_full_error_object(self) -> None: assert error.last_good.volume_mm3 == pytest.approx(868892.28, abs=1e-6) assert error.last_good_artifact_ref == _REF_CHECKPOINT assert error.hint.startswith("inspect_part") + assert len(rebuilt.checkpoints) == 1 + assert rebuilt.checkpoints[0].artifact_ref == _REF_CHECKPOINT + assert rebuilt.checkpoints[0].statement.startswith("tread_shelf") def test_round_trip_through_json_text(self) -> None: original = failed_result() @@ -275,6 +290,38 @@ def test_from_json_rejects_bad_status(self) -> None: with pytest.raises(ValidationError): BuildResult.from_json(data) + def test_absent_checkpoints_read_as_empty(self) -> None: + data = ok_result().to_json() + del data["checkpoints"] + rebuilt = BuildResult.from_json(data) + assert rebuilt.checkpoints == () + + +class TestStatementCheckpoint: + def test_round_trip(self) -> None: + checkpoint = StatementCheckpoint( + index=3, + line=44, + statement="tread_shelf = slotted_shelf - groove_cutter", + span=(44, 0, 44, 48), + bound=("tread_shelf",), + shapes=("tread_shelf",), + artifact_ref=_REF_CHECKPOINT, + ) + assert StatementCheckpoint.from_json(checkpoint.to_json()) == checkpoint + + def test_null_artifact_ref_round_trips(self) -> None: + checkpoint = StatementCheckpoint( + index=0, + line=1, + statement="x = 1", + span=(1, 0, 1, 5), + bound=("x",), + shapes=(), + ) + rebuilt = StatementCheckpoint.from_json(checkpoint.to_json()) + assert rebuilt.artifact_ref is None + class TestInvariants: def test_failed_requires_error(self) -> None: diff --git a/script_contract.md b/script_contract.md index ef90a21f..60a497b1 100644 --- a/script_contract.md +++ b/script_contract.md @@ -453,6 +453,14 @@ record: "source_map_ref": "artifact:source-map:sha256:…", "metadata": { "description": "…", "blank_size": "210.0 x 125.0 x 6 mm", … }, "warnings": [ {"kind": "tag_descriptor_changed", "tag": "tread_top", "detail": "…"} ], + "checkpoints": [ + {"index": 0, "line": 1, "statement": "PARAMS = {…}", + "span": [1, 0, 4, 1], "bound": ["PARAMS"], "shapes": [], + "artifact_ref": null}, + {"index": 3, "line": 44, "statement": "tread_shelf = slotted_shelf - groove_cutter", + "span": [44, 0, 44, 48], "bound": ["tread_shelf"], "shapes": ["tread_shelf"], + "artifact_ref": "artifact:build-checkpoint:sha256:…"} + ], "error": null | { "line": 46, "col": 14, "type": "ValueError", "message": "Failed creating a fillet with radius of 6, try a smaller value or use max_fillet() to find the largest valid fillet radius", @@ -481,7 +489,12 @@ available as evidence but MUST NOT clear stale markers or replace the prior successful current artifact. A trusted invocation id freezes these inputs so a lost-response retry returns the original result rather than rebuilding newer state. `artifact_ref`, `source_map_ref`, and `last_good_artifact_ref` are opaque -project-scoped capabilities, never mutable filesystem paths. +project-scoped capabilities, never mutable filesystem paths. `checkpoints` is +the incremental executor's per-statement list (architecture §3.1): every +top-level statement that completed, in order, with its source span and the +names it bound. A checkpoint's `artifact_ref` is set only when publication +minted a last-good blob for that stop; intermediate stops carry `null`. +Records written before this field existed read back as an empty list. The failed-build text rendering MUST carry the same fields as the captured Smith error (line/col, type, source frame, built-through statement, last-good diff --git a/server/src/hephaestus/agent_bridge/cad_ops/_build.py b/server/src/hephaestus/agent_bridge/cad_ops/_build.py index e46c591f..c47fd928 100644 --- a/server/src/hephaestus/agent_bridge/cad_ops/_build.py +++ b/server/src/hephaestus/agent_bridge/cad_ops/_build.py @@ -306,6 +306,16 @@ def current_build(self, name: str) -> BuildResult | None: """ return self._publisher().current_result(name) + def last_failure_build(self, name: str) -> BuildResult | None: + """The most-recent published *failed* build of ``name`` (lock-free). + + ``GET /parts/{part}/build`` reads this when there is no current + successful build, so a first-fail part projects its checkpoints and + last-good instead of a ``not_built`` silence. A later success still + wins: this is never preferred over :meth:`current_build`. + """ + return self._publisher().last_failure_result(name) + def current_bundle(self, name: str) -> Mapping[str, JSONValue] | None: """The published *bundle* behind ``name``'s current pointer (lock-free). diff --git a/server/src/hephaestus/http/app.py b/server/src/hephaestus/http/app.py index 06b07e1b..1351f67c 100644 --- a/server/src/hephaestus/http/app.py +++ b/server/src/hephaestus/http/app.py @@ -54,6 +54,7 @@ from hephaestus.contract import toolgen from hephaestus.contract.tools_decl import READ_ARTIFACT_PAGE_MAX, TOOLS_BY_NAME from hephaestus.core.checks.report import project_check_report +from hephaestus.core.types import BuildResult from hephaestus.mcp.validate import SchemaError, normalize_arguments from starlette.applications import Starlette from starlette.requests import Request @@ -598,7 +599,14 @@ async def get_script(request: Request) -> Response: async def get_build(request: Request) -> Response: part = _part(request) - result = await asyncio.to_thread(runtime.cad.current_build, part) + + def _read() -> BuildResult | None: + current = runtime.cad.current_build(part) + if current is not None: + return current + return runtime.cad.last_failure_build(part) + + result = await asyncio.to_thread(_read) return JSONResponse(build_projection(result)) async def get_properties(request: Request) -> Response: diff --git a/server/src/hephaestus/http/projections.py b/server/src/hephaestus/http/projections.py index 7a775761..ba84c22a 100644 --- a/server/src/hephaestus/http/projections.py +++ b/server/src/hephaestus/http/projections.py @@ -72,12 +72,26 @@ def build_projection(result: BuildResult | None) -> dict[str, Any]: part of the persisted ``BuildResult``, so a read of the current build has none to report and says so by omission rather than by inventing an empty one. - A part with no current build is ``status="not_built"`` — a named absence, not - a 404 and not an empty success. Silence never reads as a pass (§6.3's rule, - applied to the build axis). + ``checkpoints`` is the incremental executor's per-statement list, persisted + on the §8 record. The Timeline reads this field and does not invent stops + from the script text. A record written before the field existed projects + ``[]`` — a named empty list, not an omitted key, so the client can tell + "this build named no stops" from "the projection forgot to say". + + A part with no current build *and* no last-failure record is + ``status="not_built"`` — a named absence, not a 404 and not an empty + success. Silence never reads as a pass (§6.3's rule, applied to the build + axis). The route prefers the current successful record when both exist + (G4.2's ``geometry_count`` is a fact about the current build). """ if result is None: - return {"status": "not_built", "current": False, "geometry_count": 0, "geometries": []} + return { + "status": "not_built", + "current": False, + "geometry_count": 0, + "geometries": [], + "checkpoints": [], + } payload: dict[str, Any] = { "status": "ok" if result.status == "ok" else "error", "current": result.current, @@ -90,6 +104,7 @@ def build_projection(result: BuildResult | None) -> dict[str, Any]: "checks": {name: check.to_json() for name, check in result.checks.items()}, "source_map_ref": result.source_map_ref, "warnings": [warning.to_json() for warning in result.warnings], + "checkpoints": [checkpoint.to_json() for checkpoint in result.checkpoints], } if result.error is not None: payload["error"] = result.error.to_json() diff --git a/server/tests/test_http_reads.py b/server/tests/test_http_reads.py index 421bf9e2..544b0c54 100644 --- a/server/tests/test_http_reads.py +++ b/server/tests/test_http_reads.py @@ -14,6 +14,7 @@ import subprocess import sys from pathlib import Path +from typing import Any, cast import pytest from hephaestus.core.checks.report import project_check_report, report_json @@ -108,6 +109,67 @@ def test_build_route_names_the_absence_rather_than_returning_an_empty_success( body = web.get("/parts/bracket/build").json() assert body["status"] == "not_built" assert body["geometry_count"] == 0 + assert body["checkpoints"] == [] + + +def test_build_route_projects_executor_checkpoints(tmp_path: Path) -> None: + """``checkpoints[]`` is the worker list, persisted on the §8 record.""" + with workspace(tmp_path / "proj") as web: + assert web.post("/parts/widget/build", json={}, key=uuid7()).status_code == 200 + body = web.get("/parts/widget/build").json() + assert body["status"] == "ok" + checkpoints = cast("list[dict[str, Any]]", body["checkpoints"]) + assert isinstance(checkpoints, list) and len(checkpoints) >= 1 + first = checkpoints[0] + assert first["index"] == 0 + assert isinstance(first["line"], int) and first["line"] >= 1 + assert isinstance(first["statement"], str) and first["statement"] + assert first["span"] == [first["line"], *first["span"][1:]] + assert first["artifact_ref"] is None + assert "bound" in first and "shapes" in first + + +def test_build_route_serves_last_failure_when_there_is_no_current(tmp_path: Path) -> None: + """A first-fail part projects its failed record, not a ``not_built`` silence.""" + root = tmp_path / "proj" + with workspace(root) as web: + (root / "parts" / "bracket.py").write_text( + "plate = Box(30, 20, 6)\n" + "bad = fillet(plate.edges(), radius=99.0)\n" + "part.geometry = plate\n", + encoding="utf-8", + ) + posted = web.post("/parts/bracket/build", json={}, key=uuid7()).json() + assert posted["status"] == "error" + body = web.get("/parts/bracket/build").json() + assert body["status"] == "error" + assert body["current"] is False + checkpoints = cast("list[dict[str, Any]]", body["checkpoints"]) + assert len(checkpoints) >= 1 + error = cast("dict[str, Any]", body["error"]) + assert error["last_good_artifact_ref"] + last = checkpoints[-1] + assert last["artifact_ref"] == error["last_good_artifact_ref"] + + +def test_build_route_prefers_current_over_a_later_failure(tmp_path: Path) -> None: + """G4.2's geometry_count is a fact about the current build, not last-fail.""" + root = tmp_path / "proj" + with workspace(root) as web: + assert web.post("/parts/widget/build", json={}, key=uuid7()).status_code == 200 + current = web.get("/parts/widget/build").json() + (root / "parts" / "widget.py").write_text( + "body = Box(10, 10, 2)\n" + "bad = fillet(body.edges(), radius=99.0)\n" + "part.geometry = body\n", + encoding="utf-8", + ) + assert web.post("/parts/widget/build", json={}, key=uuid7()).json()["status"] == "error" + body = web.get("/parts/widget/build").json() + assert body["status"] == "ok" + assert body["current"] is True + assert body["artifact_ref"] == current["artifact_ref"] + assert body["geometry_count"] == current["geometry_count"] def test_properties_projection_keys_are_exactly_the_declared_part_metadata( diff --git a/web/src/api/queries.ts b/web/src/api/queries.ts index 995e3324..ec9dfe21 100644 --- a/web/src/api/queries.ts +++ b/web/src/api/queries.ts @@ -102,9 +102,12 @@ export function useParts(): UseQueryResult { /** * `GET /parts/{part}/build` — the projection G4.2's row count is read from. * - * A part with no current build answers `status: "not_built"` with - * `geometry_count: 0`: a **named absence**, not a 404 and not an empty success - * (`http/projections.py`). The tree renders that state as words, because §6.3's + * A part with no current build and no last-failure record answers + * `status: "not_built"` with `geometry_count: 0`: a **named absence**, not a + * 404 and not an empty success (`http/projections.py`). A first-fail part + * projects the failed record (checkpoints + last-good) instead of silence. + * A later success still wins: G4.2's `geometry_count` is a fact about the + * current build. The tree renders the named absence as words, because §6.3's * rule — silence never reads as a pass — is a UI obligation on every axis. */ export function useBuild( diff --git a/web/src/api/types.ts b/web/src/api/types.ts index a67f16b4..300af3ed 100644 --- a/web/src/api/types.ts +++ b/web/src/api/types.ts @@ -49,6 +49,24 @@ export interface BuildWarning { readonly detail: string; } +/** + * One incremental-executor checkpoint (`core/types.py::StatementCheckpoint`). + * + * `GET /parts/{part}/build` projects the worker's per-statement list. A + * Timeline mark invented from the script text would be a client-side event + * the engine did not name. `artifact_ref` is set only when publication + * minted a last-good blob for that stop. + */ +export interface StatementCheckpoint { + readonly index: number; + readonly line: number; + readonly statement: string; + readonly span: readonly number[]; + readonly bound: readonly string[]; + readonly shapes: readonly string[]; + readonly artifact_ref: string | null; +} + /** * `GET /api/v1/parts/{part}/build` — the §2.3 BuildResult projection. * @@ -74,6 +92,7 @@ export interface BuildDocument { readonly checks?: Readonly>; readonly source_map_ref?: string | null; readonly warnings?: readonly BuildWarning[]; + readonly checkpoints?: readonly StatementCheckpoint[]; readonly error?: BuildError | undefined; readonly critique?: Readonly>; } diff --git a/web/src/components/stage/Timeline.module.css b/web/src/components/stage/Timeline.module.css index a1ee03ba..056281a3 100644 --- a/web/src/components/stage/Timeline.module.css +++ b/web/src/components/stage/Timeline.module.css @@ -17,8 +17,8 @@ padding: 0; list-style: none; display: flex; - justify-content: space-between; - gap: var(--gap-inline); + flex-direction: column; + gap: var(--gap-stack); } .mark { diff --git a/web/src/components/stage/Timeline.tsx b/web/src/components/stage/Timeline.tsx index 323f7e0b..8a55c62b 100644 --- a/web/src/components/stage/Timeline.tsx +++ b/web/src/components/stage/Timeline.tsx @@ -4,11 +4,11 @@ // Statement Timeline — a scrubber over the positions `GET /parts/{part}/build` // actually names (INTERFACE.md §0.1, architecture.md §3.1). // -// "Drag to rewind" is `hold(error.last_good_artifact_ref)`. The viewport is -// bound to the pin, so holding the last-good checkpoint is last-good inspect -// (`artifact_ref` and `last_good` are mutually exclusive; the pin path sends -// the ref). Dragging back follows current. Nothing here invents a per-statement -// event list: the worker's `checkpoints` array is not on the HTTP projection. +// Stops come from the projected `checkpoints[]` plus last-good / failed / +// current. "Drag to rewind" is `hold` of a checkpoint the engine minted a +// ref for (today: `error.last_good_artifact_ref`). The viewport is bound +// to the pin. Nothing here invents a per-statement event list from the +// script text. import { copy } from "../../copy"; import { useBuild } from "../../api/queries"; @@ -17,7 +17,14 @@ import { workspaceStore, useWorkspace } from "../../state/react"; import { Chip, EmptyState, formatRef, Panel, PanelBody, PanelHeader, Slider } from "../../system"; import roles from "../../system/type.module.css"; import { Fact } from "../Fact"; -import { actionForIndex, indexForPin, marksFromBuild, type TimelineKind } from "./timelineMarks"; +import { + actionForIndex, + indexForPin, + kindForPin, + marksFromBuild, + rewindMarks, + type TimelineKind, +} from "./timelineMarks"; import styles from "./Timeline.module.css"; export interface TimelineViewProps { @@ -28,20 +35,26 @@ export interface TimelineViewProps { } const KIND_COPY: Readonly> = { + statement: copy.timeline.statement, last_good: copy.timeline.lastGood, failed: copy.timeline.failed, current: copy.timeline.current, }; +function markKey(mark: { kind: string; index?: number }): string { + return mark.index === undefined ? mark.kind : `${mark.kind}:${String(mark.index)}`; +} + /** The panel's rendering half: a pure function of one build document and the pin. */ export function TimelineView(props: TimelineViewProps): React.JSX.Element { const { build, pin, onRewind, onFollowCurrent } = props; const marks = marksFromBuild(build); + const rewindable = rewindMarks(marks); const index = indexForPin(marks, pin); - const selected = marks[index] ?? null; + const selectedKind = kindForPin(marks, pin); const error = build.error; const lastGoodRef = error?.last_good_artifact_ref ?? null; - const canScrub = marks.length > 1 && lastGoodRef !== null; + const canScrub = rewindable.length > 1 && lastGoodRef !== null; return ( @@ -49,57 +62,74 @@ export function TimelineView(props: TimelineViewProps): React.JSX.Element { title={copy.timeline.heading} level={3} actions={ - selected === null ? undefined : ( - {KIND_COPY[selected.kind]} + selectedKind === null ? undefined : ( + {KIND_COPY[selectedKind]} ) } /> {build.status === "not_built" ? ( - ) : build.status === "ok" ? ( - - ) : lastGoodRef === null ? ( - + ) : marks.length === 0 ? ( + build.status === "ok" ? ( + + ) : ( + + ) ) : (
- { - const nextAction = actionForIndex(marks, next, build.artifact_ref ?? null); - if (nextAction === null) return; - if (nextAction.action === "hold") onRewind(nextAction.ref); - else onFollowCurrent(nextAction.currentRef); - }} - /> + {canScrub ? ( + { + const nextAction = actionForIndex(marks, next, build.artifact_ref ?? null); + if (nextAction === null) return; + if (nextAction.action === "hold") onRewind(nextAction.ref); + else onFollowCurrent(nextAction.currentRef); + }} + /> + ) : null}
    {marks.map((mark) => (
  1. {KIND_COPY[mark.kind]} + {mark.line !== undefined ? ( + + ) : null} + {mark.statement !== undefined && mark.statement !== "" ? ( + + {mark.statement} + + ) : null} {mark.kind === "last_good" && mark.artifact_ref !== null ? ( {formatRef(mark.artifact_ref)} - ) : mark.artifact_ref !== null ? ( + ) : mark.kind !== "statement" && mark.artifact_ref !== null ? ( {formatRef(mark.artifact_ref)} + ) : mark.kind === "statement" && mark.artifact_ref !== null ? ( + + {formatRef(mark.artifact_ref)} + ) : null}
  2. ))} diff --git a/web/src/components/stage/timelineMarks.ts b/web/src/components/stage/timelineMarks.ts index 9acb5c8e..b3c7df70 100644 --- a/web/src/components/stage/timelineMarks.ts +++ b/web/src/components/stage/timelineMarks.ts @@ -3,30 +3,60 @@ // // Timeline marks from `GET /parts/{part}/build` (INTERFACE.md §0.1). // -// The incremental executor records per-statement checkpoints **inside the -// worker**. Those checkpoints are not a field on the HTTP BuildResult -// projection. What the projection *does* carry, when a build failed, is -// `error.built_through`, `error.last_good`, and `error.last_good_artifact_ref`. -// This module emits only those positions. A mark invented from the script's -// statements, or from a recount of `geometries`, would be a client-side -// timeline the engine did not project. +// After the engine persisted worker per-statement `checkpoints` on the §8 +// record, this helper projects those stops and the positions the error +// object already named (last-good / failed / current). A mark invented +// from the script's statements, or from a recount of `geometries`, would +// be a client-side timeline the engine did not project. -import type { BuildDocument } from "../../api/types"; +import type { BuildDocument, StatementCheckpoint } from "../../api/types"; -/** The three positions the build projection can name. Closed. */ -export const TIMELINE_KINDS = ["last_good", "failed", "current"] as const; +/** Closed. `statement` is a projected executor checkpoint. */ +export const TIMELINE_KINDS = ["statement", "last_good", "failed", "current"] as const; export type TimelineKind = (typeof TIMELINE_KINDS)[number]; export interface TimelineMark { readonly kind: TimelineKind; /** The artifact this mark rewinds to, or `null` when the engine named none. */ readonly artifact_ref: string | null; + readonly index?: number; + readonly line?: number; + readonly statement?: string; + readonly bound?: readonly string[]; + readonly shapes?: readonly string[]; +} + +function rewindable(mark: TimelineMark): boolean { + return mark.kind === "last_good" || mark.kind === "failed" || mark.kind === "current"; +} + +/** The stops the scrubber may pin: last-good / failed / current only. */ +export function rewindMarks(marks: readonly TimelineMark[]): readonly TimelineMark[] { + return marks.filter(rewindable); +} + +function markFromCheckpoint( + checkpoint: StatementCheckpoint, + lastGood: string | null, +): TimelineMark { + const ref = checkpoint.artifact_ref; + const kind = lastGood !== null && ref === lastGood ? "last_good" : "statement"; + return { + kind, + artifact_ref: ref, + index: checkpoint.index, + line: checkpoint.line, + statement: checkpoint.statement, + bound: checkpoint.bound, + shapes: checkpoint.shapes, + }; } /** - * The scrubber's stops, in order: last-good (if the error named a checkpoint), - * then the failed statement, or — on a successful build — the current artifact - * alone. + * The Timeline's stops, in order: every projected checkpoint, then the + * failed statement or the current artifact. A checkpoint whose + * `artifact_ref` is the error's last-good ref is the last-good stop — + * the engine named that join, not the client. * * `not_built` has no marks: silence is a named absence in the panel, not an * empty scrubber that looks like "rewound to the start". @@ -35,7 +65,10 @@ export function marksFromBuild(build: BuildDocument): readonly TimelineMark[] { if (build.status === "not_built") return []; const marks: TimelineMark[] = []; const lastGood = build.error?.last_good_artifact_ref ?? null; - if (lastGood !== null) { + for (const checkpoint of build.checkpoints ?? []) { + marks.push(markFromCheckpoint(checkpoint, lastGood)); + } + if (lastGood !== null && !marks.some((mark) => mark.kind === "last_good")) { marks.push({ kind: "last_good", artifact_ref: lastGood }); } if (build.status === "error") { @@ -47,7 +80,7 @@ export function marksFromBuild(build: BuildDocument): readonly TimelineMark[] { } /** - * Which mark the pin is on. + * Which rewindable mark the pin is on. * * Holding the last-good ref selects that mark. Any other pin — including * `null` after a failed build with no current artifact — selects the @@ -58,20 +91,22 @@ export function kindForPin( marks: readonly TimelineMark[], pin: string | null, ): TimelineKind | null { - if (marks.length === 0) return null; - const lastGood = marks.find((mark) => mark.kind === "last_good"); + const rewindableMarks = rewindMarks(marks); + if (rewindableMarks.length === 0) return null; + const lastGood = rewindableMarks.find((mark) => mark.kind === "last_good"); if (lastGood !== undefined && pin !== null && pin === lastGood.artifact_ref) { return "last_good"; } - const rest = marks.find((mark) => mark.kind !== "last_good"); + const rest = rewindableMarks.find((mark) => mark.kind !== "last_good"); return rest?.kind ?? lastGood?.kind ?? null; } /** The index the scrubber sits on for a pin. `0` when there is nothing to match. */ export function indexForPin(marks: readonly TimelineMark[], pin: string | null): number { + const rewindableMarks = rewindMarks(marks); const kind = kindForPin(marks, pin); if (kind === null) return 0; - const index = marks.findIndex((mark) => mark.kind === kind); + const index = rewindableMarks.findIndex((mark) => mark.kind === kind); return index === -1 ? 0 : index; } @@ -82,15 +117,16 @@ export type TimelineAction = /** * What a scrubber index does to the pin. * - * Last-good with a ref is `hold` — rewind. Every other mark follows current, - * including a failed build whose `artifact_ref` is null. + * Last-good with a ref is `hold` — rewind. Every other rewindable mark + * follows current, including a failed build whose `artifact_ref` is null. + * The index is over `rewindMarks`, not the full projected list. */ export function actionForIndex( marks: readonly TimelineMark[], index: number, currentRef: string | null, ): TimelineAction | null { - const mark = marks[index]; + const mark = rewindMarks(marks)[index]; if (mark === undefined) return null; if (mark.kind === "last_good" && mark.artifact_ref !== null) { return { action: "hold", ref: mark.artifact_ref }; diff --git a/web/src/copy.ts b/web/src/copy.ts index 9f0658d2..45bbfe21 100644 --- a/web/src/copy.ts +++ b/web/src/copy.ts @@ -149,11 +149,12 @@ export const copy = { /** * Statement Timeline. Marks come from `GET /parts/{part}/build` only — - * last-good checkpoint, failed statement, or the current successful artifact. + * projected `checkpoints[]`, last-good, failed, or the current artifact. */ timeline: { heading: "Timeline", tabsLabel: "Build timeline", + statement: "Statement", lastGood: "Last good", failed: "Failed", current: "Current", diff --git a/web/test/fixtures/README.md b/web/test/fixtures/README.md index 0ce669ac..7354ca30 100644 --- a/web/test/fixtures/README.md +++ b/web/test/fixtures/README.md @@ -48,6 +48,12 @@ assert that the client is self-consistent, which is not the property under test. | `dfm.json` | `GET /api/v1/parts/panel/dfm`, after a run against the current artifact | | `dfm_preview.json` | the same, after a run resolved through an explicit `artifact_ref` | +**`build_failed.json`** is the Timeline's failed-build document. It is assembled +around the §8 error shape (line/col/type/frame/built_through/last_good) plus +the worker `checkpoints[]` `GET /parts/{part}/build` now projects. The +checkpoint refs are illustrative (a last-good `build-checkpoint` hash); the +fields and the last-good join are what the marks helper asserts. + ## The three fixtures that are not pure route output Each says so here rather than passing quietly as a recording. diff --git a/web/test/fixtures/build_failed.json b/web/test/fixtures/build_failed.json index 4ab1c0de..0fc0f9c4 100644 --- a/web/test/fixtures/build_failed.json +++ b/web/test/fixtures/build_failed.json @@ -12,6 +12,26 @@ "checks": {}, "source_map_ref": null, "warnings": [], + "checkpoints": [ + { + "index": 0, + "line": 1, + "statement": "PARAMS = {\n \"groove_count\": Param(5, min=2, max=10),\n}", + "span": [1, 0, 3, 1], + "bound": ["PARAMS"], + "shapes": [], + "artifact_ref": null + }, + { + "index": 1, + "line": 44, + "statement": "tread_shelf = slotted_shelf - groove_cutter", + "span": [44, 0, 44, 48], + "bound": ["tread_shelf"], + "shapes": ["tread_shelf"], + "artifact_ref": "artifact:build-checkpoint:sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + } + ], "error": { "line": 46, "col": 14, diff --git a/web/test/timeline.test.tsx b/web/test/timeline.test.tsx index 7bcab08e..b98d72b0 100644 --- a/web/test/timeline.test.tsx +++ b/web/test/timeline.test.tsx @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 // // Statement Timeline: marks from `GET /parts/{part}/build` only, rewind is -// `hold(error.last_good_artifact_ref)`. No invented statement events. +// `hold` of a projected checkpoint ref. No invented statement events. import { describe, expect, it } from "vitest"; import { renderToStaticMarkup } from "react-dom/server"; @@ -17,10 +17,35 @@ import { indexForPin, kindForPin, marksFromBuild, + rewindMarks, } from "../src/components/stage/timelineMarks"; const failed = failedJson as BuildDocument; -const ok = okJson as BuildDocument; +const okRecorded = okJson as BuildDocument; +/** Recorded `build.json` predates `checkpoints[]`; compose the projection here. */ +const ok: BuildDocument = { + ...okRecorded, + checkpoints: [ + { + index: 0, + line: 1, + statement: 'PARAMS = {\n "thickness": Param(5.5, min=3.0, max=12.0),\n}', + span: [1, 0, 4, 1], + bound: ["PARAMS"], + shapes: [], + artifact_ref: null, + }, + { + index: 1, + line: 7, + statement: "panel = Box(p.width, 40.0, p.thickness)", + span: [7, 0, 7, 39], + bound: ["panel"], + shapes: ["panel"], + artifact_ref: null, + }, + ], +}; const LAST_GOOD = failed.error?.last_good_artifact_ref ?? ""; function render(element: ReactElement): HTMLElement { @@ -30,18 +55,30 @@ function render(element: ReactElement): HTMLElement { } describe("marksFromBuild", () => { - it("emits last-good then failed from the error projection, and nothing else", () => { + it("projects executor checkpoints and names last-good from the minted ref", () => { const marks = marksFromBuild(failed); - expect(marks.map((mark) => mark.kind)).toEqual(["last_good", "failed"]); - expect(marks[0]?.artifact_ref).toBe(LAST_GOOD); - // No statement index, no script-derived events, no geometry recount. - expect(marks).toHaveLength(2); + expect(marks.map((mark) => mark.kind)).toEqual(["statement", "last_good", "failed"]); + expect(marks[0]?.statement).toBe(failed.checkpoints?.[0]?.statement); + expect(marks[1]?.artifact_ref).toBe(LAST_GOOD); + expect(marks[1]?.statement).toBe(failed.checkpoints?.[1]?.statement); + // No script-derived extra events, no geometry recount. + expect(marks).toHaveLength(3); }); - it("emits only current on a successful build — there is no last-good to invent", () => { + it("projects successful-build checkpoints then the current artifact", () => { const marks = marksFromBuild(ok); - expect(marks.map((mark) => mark.kind)).toEqual(["current"]); - expect(marks[0]?.artifact_ref).toBe(ok.artifact_ref); + expect(marks.map((mark) => mark.kind)).toEqual(["statement", "statement", "current"]); + expect(marks[0]?.statement).toBe(ok.checkpoints?.[0]?.statement); + expect(marks[2]?.artifact_ref).toBe(ok.artifact_ref); + }); + + it("falls back to last-good vs failed when the record named no checkpoints", () => { + const marks = marksFromBuild({ + ...failed, + checkpoints: [], + }); + expect(marks.map((mark) => mark.kind)).toEqual(["last_good", "failed"]); + expect(marks[0]?.artifact_ref).toBe(LAST_GOOD); }); it("emits nothing for a named absence", () => { @@ -51,6 +88,7 @@ describe("marksFromBuild", () => { current: false, geometry_count: 0, geometries: [], + checkpoints: [], }), ).toEqual([]); }); @@ -63,6 +101,7 @@ describe("the pin match", () => { expect(kindForPin(marks, null)).toBe("failed"); expect(indexForPin(marks, LAST_GOOD)).toBe(0); expect(indexForPin(marks, null)).toBe(1); + expect(rewindMarks(marks).map((mark) => mark.kind)).toEqual(["last_good", "failed"]); }); it("rewinds by holding the last-good ref and follows current otherwise", () => { @@ -73,29 +112,34 @@ describe("the pin match", () => { }); describe("TimelineView", () => { - it("renders the last-good ref as a fact and the two projected marks", () => { + it("renders projected statement stops as facts and the rewindable marks", () => { const host = render( undefined} onFollowCurrent={() => undefined} />, ); const marks = [...host.querySelectorAll("[data-timeline-mark]")].map((node) => node.getAttribute("data-timeline-mark"), ); - expect(marks).toEqual(["last_good", "failed"]); + expect(marks).toEqual(["statement", "last_good", "failed"]); + const statement = host.querySelector('[data-source="build.checkpoints[].statement"]'); + expect(statement?.getAttribute("data-value")).toBe(failed.checkpoints?.[0]?.statement ?? ""); const fact = host.querySelector('[data-source="build.error.last_good_artifact_ref"]'); expect(fact?.getAttribute("data-value")).toBe(LAST_GOOD); - const statement = host.querySelector('[data-source="build.error.built_through.statement"]'); - expect(statement?.getAttribute("data-value")).toBe( + const builtThrough = host.querySelector('[data-source="build.error.built_through.statement"]'); + expect(builtThrough?.getAttribute("data-value")).toBe( failed.error?.built_through?.statement ?? "", ); expect(host.querySelector("[data-timeline-scrub]")).not.toBeNull(); }); - it("does not invent a scrubber on a successful build", () => { + it("does not invent a rewind scrubber on a successful build", () => { const host = render( undefined} onFollowCurrent={() => undefined} />, ); expect(host.querySelector("[data-timeline-scrub]")).toBeNull(); - expect(host.querySelectorAll("[data-timeline-mark]")).toHaveLength(0); + const marks = [...host.querySelectorAll("[data-timeline-mark]")].map((node) => + node.getAttribute("data-timeline-mark"), + ); + expect(marks).toEqual(["statement", "statement", "current"]); }); it("marks the last-good stop selected when that ref is pinned", () => {