"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/
Python
feat(preview): add preview trajectories and demos
yuhaoaec2c1322694
diff --git a/.gitignore b/.gitignoreindex a28dbe4b0..30cdd4800 100644--- a/.gitignore+++ b/.gitignore@@ -26,25 +26,6 @@!/.github/PULL_REQUEST_TEMPLATE.md!/.github/ISSUE_TEMPLATE/-# Allow examples directory-!/examples/-# Ignore everything inside examples first-/examples/*-# Then allow only the subdirs and files we need-!/examples/README.md-!/examples/drawio/-!/examples/slay_the_spire_ii/-!/examples/videocaptioner/-# Inside each subdir, ignore everything then allow specific files-/examples/drawio/*-!/examples/drawio/drawio_demo.gif-!/examples/drawio/https_handshake.png-/examples/slay_the_spire_ii/*-!/examples/slay_the_spire_ii/example_preview.gif-/examples/videocaptioner/*-!/examples/videocaptioner/videocaptioner_before.png-!/examples/videocaptioner/videocaptioner_after.png-# Step 3: Allow cli-anything-plugin, codex-skill, and skill_generation tests!/cli-anything-plugin/!/codex-skill/diff --git a/README.md b/README.mdindex 0bd2fed71..c33fc3925 100644--- a/README.md+++ b/README.md@@ -7,7 +7,7 @@ CLI-Anything: Bridging the Gap Between AI Agents and the World's Software</stron**π [CLI-Hub](https://hkuds.github.io/CLI-Anything/)**: `pip install cli-anything-hub` then `cli-hub install <name>` β browse, install, and manage all community-built CLIs. Want to add your own? [Open a PR](https://github.com/HKUDS/CLI-Anything/blob/main/CONTRIBUTING.md) β the hub updates instantly.-**π¬ [See Demos](#-real-world-demos)**: Watch AI agents use generated CLIs to produce real artifacts β diagrams, gameplay, subtitles, and more.+**π¬ [See Demos](#-real-world-demos)**: Watch AI agents use generated CLIs plus preview, live preview, and trajectory loops to produce real artifacts β CAD builds, 3D scenes, diagrams, gameplay, subtitles, and more.**π [Become a Contributor, or Request a CLI]**: [Join us](https://github.com/HKUDS/CLI-Anything/issues/new?template=contributor-signup.yml)! Sign up to build a new CLI harness β once reviewed and merged, you'll gain access as one of our community contributors! Wish CLI-Anything supported a specific software or service? Submit a [wishlist request](https://github.com/HKUDS/CLI-Anything/issues/new?template=cli-wishlist.yml)!@@ -695,6 +695,34 @@ SKILL.md files are auto-generated during Phase 6.5 of the pipeline using `skill_AI agents using generated CLIs to produce complete, useful artifacts β no GUI needed.+### FreeCAD — Curiosity Rover via Preview, Live Preview, and Trajectory++> **Harness:** `cli-anything-freecad` | **Preview Stack:** `preview` + `preview live` + `trajectory.json` | **Artifact:** Agent-built Curiosity-style rover++An agent incrementally assembles a Curiosity-inspired rover while publishing real FreeCAD preview bundles, refreshing a live preview session, and recording command-to-preview history for later replay. The resulting demo shows the artifact evolving step by step before the final showcase.++<p align="center">+ <img src="assets/demos/freecad-curiosity-preview-trajectory.gif" alt="FreeCAD Curiosity rover demo driven by preview, live preview, and trajectory history" width="860" />+</p>++<p align="center">+ <sub>README GIF generated from the full local demo video with a speed-adjusted, high-quality ffmpeg palette workflow.</sub>+</p>++### Blender — Orbital Relay Drone via Preview, Live Preview, and Trajectory++> **Harness:** `cli-anything-blender` | **Preview Stack:** `preview` + `preview live` + `trajectory.json` | **Artifact:** Agent-built orbital relay drone++An agent uses the Blender harness to grow a hard-surface orbital relay drone under a real preview loop: each stage pushes new render-backed bundles, the live session tracks the current head, and the trajectory ties every command to the matching visual state. The demo finishes with the completed scene ready for a polished turntable.++<p align="center">+ <img src="assets/demos/blender-orbital-relay-drone-preview-trajectory.gif" alt="Blender orbital relay drone demo driven by preview, live preview, and trajectory history" width="860" />+</p>++<p align="center">+ <sub>README GIF generated from the full local demo video with a speed-adjusted, high-quality ffmpeg palette workflow.</sub>+</p>+### Draw.io — HTTPS Handshake Diagram> **Harness:** `cli-anything-drawio` | **Time:** ~4 min | **Artifact:** `.drawio` + `.png`@@ -702,13 +730,13 @@ AI agents using generated CLIs to produce complete, useful artifacts β no GUIAn agent creates a full HTTPS connection lifecycle diagram from scratch β TCP three-way handshake, TLS negotiation, encrypted data exchange, and TCP four-way termination β entirely through CLI commands.<p align="center">- <img src="examples/drawio/drawio_demo.gif" alt="Draw.io CLI demo: building an HTTPS handshake diagram" width="720" />+ <img src="assets/demos/drawio-demo.gif" alt="Draw.io CLI demo: building an HTTPS handshake diagram" width="720" /></p><details><summary>Final artifact</summary><p align="center">- <img src="examples/drawio/https_handshake.png" alt="HTTPS handshake sequence diagram" width="600" />+ <img src="assets/demos/drawio-https-handshake.png" alt="HTTPS handshake sequence diagram" width="600" /></p></details>@@ -721,7 +749,7 @@ An agent creates a full HTTPS connection lifecycle diagram from scratch β TCPAn agent plays through a Slay the Spire II run using the CLI harness β reading game state, selecting cards, choosing paths, and making strategic decisions in real-time.<p align="center">- <img src="examples/slay_the_spire_ii/example_preview.gif" alt="Slay the Spire II CLI gameplay demo" width="720" />+ <img src="assets/demos/slay-the-spire-ii-gameplay.gif" alt="Slay the Spire II CLI gameplay demo" width="720" /></p>*Contributed by [@TianyuFan0504](https://github.com/TianyuFan0504)*@@ -738,8 +766,8 @@ An agent uses the VideoCaptioner CLI to automatically generate and overlay style<td align="center"><strong>Sub B</strong></td></tr><tr>-<td><img src="examples/videocaptioner/videocaptioner_before.png" alt="Video frame before captioning" width="380" /></td>-<td><img src="examples/videocaptioner/videocaptioner_after.png" alt="Video frame after captioning" width="380" /></td>+<td><img src="assets/demos/videocaptioner-before.png" alt="Video frame before captioning" width="380" /></td>+<td><img src="assets/demos/videocaptioner-after.png" alt="Video frame after captioning" width="380" /></td></tr></table>diff --git a/assets/demos/README.md b/assets/demos/README.mdnew file mode 100644index 000000000..98959889d--- /dev/null+++ b/assets/demos/README.md@@ -0,0 +1,101 @@+# CLI-Anything Demo Assets++This directory centralizes the GIFs and images used by the repository demo pages.+The top-level [README.md](../README.md) is the primary showcase; this file is the+asset-side landing page so the directory still makes sense on its own.++---++## FreeCAD β Curiosity Rover via Preview, Live Preview, and Trajectory++> **Harness:** `cli-anything-freecad` | **Preview Stack:** `preview` + `preview live` + `trajectory.json` | **Artifact:** Agent-built Curiosity-style rover++An agent incrementally assembles a Curiosity-inspired rover while publishing real+FreeCAD preview bundles, refreshing a live preview session, and recording+command-to-preview history for later replay.++<p align="center">+ <img src="freecad-curiosity-preview-trajectory.gif" alt="FreeCAD Curiosity rover demo driven by preview, live preview, and trajectory history" width="860" />+</p>++<p align="center">+ <sub>README GIF generated from the full local demo video with a speed-adjusted, high-quality ffmpeg palette workflow.</sub>+</p>++---++## Blender β Orbital Relay Drone via Preview, Live Preview, and Trajectory++> **Harness:** `cli-anything-blender` | **Preview Stack:** `preview` + `preview live` + `trajectory.json` | **Artifact:** Agent-built orbital relay drone++An agent uses the Blender harness to grow a hard-surface orbital relay drone under+a real preview loop: each stage pushes new render-backed bundles, the live+session tracks the current head, and the trajectory ties every command to the+matching visual state.++<p align="center">+ <img src="blender-orbital-relay-drone-preview-trajectory.gif" alt="Blender orbital relay drone demo driven by preview, live preview, and trajectory history" width="860" />+</p>++<p align="center">+ <sub>README GIF generated from the full local demo video with a speed-adjusted, high-quality ffmpeg palette workflow.</sub>+</p>++---++## Draw.io β HTTPS Handshake Diagram++> **Harness:** `cli-anything-drawio` | **Time:** ~4 min | **Artifact:** `.drawio` + `.png`++An agent creates a full HTTPS connection lifecycle diagram from scratch through+CLI commands only.++<p align="center">+ <img src="drawio-demo.gif" alt="Draw.io CLI demo: building an HTTPS handshake diagram" width="720" />+</p>++<details>+<summary>Final artifact</summary>+<p align="center">+ <img src="drawio-https-handshake.png" alt="HTTPS handshake sequence diagram" width="600" />+</p>+</details>++*Contributed by [@zhangxilong-43](https://github.com/zhangxilong-43)*++---++## Slay the Spire II β Game Automation++> **Harness:** `cli-anything-slay-the-spire-ii` | **Artifact:** Automated gameplay session++An agent plays through a Slay the Spire II run using the CLI harness, making+real-time strategic decisions from game state.++<p align="center">+ <img src="slay-the-spire-ii-gameplay.gif" alt="Slay the Spire II CLI gameplay demo" width="720" />+</p>++*Contributed by [@TianyuFan0504](https://github.com/TianyuFan0504)*++---++## VideoCaptioner β Auto-Generated Subtitles++> **Harness:** `cli-anything-videocaptioner` | **Artifact:** Captioned video frames++An agent uses the VideoCaptioner CLI to automatically generate and overlay styled+subtitles onto video content.++<table align="center">+<tr>+<td align="center"><strong>Sub A</strong></td>+<td align="center"><strong>Sub B</strong></td>+</tr>+<tr>+<td><img src="videocaptioner-before.png" alt="Video frame before captioning" width="380" /></td>+<td><img src="videocaptioner-after.png" alt="Video frame after captioning" width="380" /></td>+</tr>+</table>++*Contributed by [@WEIFENG2333](https://github.com/WEIFENG2333)*diff --git a/assets/demos/blender-orbital-relay-drone-preview-trajectory.gif b/assets/demos/blender-orbital-relay-drone-preview-trajectory.gifnew file mode 100644index 000000000..501b2eb2fBinary files /dev/null and b/assets/demos/blender-orbital-relay-drone-preview-trajectory.gif differdiff --git a/examples/drawio/drawio_demo.gif b/assets/demos/drawio-demo.gifsimilarity index 100%rename from examples/drawio/drawio_demo.gifrename to assets/demos/drawio-demo.gifdiff --git a/examples/drawio/https_handshake.png b/assets/demos/drawio-https-handshake.pngsimilarity index 100%rename from examples/drawio/https_handshake.pngrename to assets/demos/drawio-https-handshake.pngdiff --git a/assets/demos/freecad-curiosity-preview-trajectory.gif b/assets/demos/freecad-curiosity-preview-trajectory.gifnew file mode 100644index 000000000..65bb8eeb6Binary files /dev/null and b/assets/demos/freecad-curiosity-preview-trajectory.gif differdiff --git a/examples/slay_the_spire_ii/example_preview.gif b/assets/demos/slay-the-spire-ii-gameplay.gifsimilarity index 100%rename from examples/slay_the_spire_ii/example_preview.gifrename to assets/demos/slay-the-spire-ii-gameplay.gifdiff --git a/examples/videocaptioner/videocaptioner_after.png b/assets/demos/videocaptioner-after.pngsimilarity index 100%rename from examples/videocaptioner/videocaptioner_after.pngrename to assets/demos/videocaptioner-after.pngdiff --git a/examples/videocaptioner/videocaptioner_before.png b/assets/demos/videocaptioner-before.pngsimilarity index 100%rename from examples/videocaptioner/videocaptioner_before.pngrename to assets/demos/videocaptioner-before.pngdiff --git a/blender/agent-harness/cli_anything/blender/README.md b/blender/agent-harness/cli_anything/blender/README.mdindex acec7b53f..c3d107e1c 100644--- a/blender/agent-harness/cli_anything/blender/README.md+++ b/blender/agent-harness/cli_anything/blender/README.md@@ -54,6 +54,40 @@ python3 -m cli.blender_cli --json scene new -o scene.jsonpython3 -m cli.blender_cli --json --project scene.json object list```+## Preview and Live Preview++Blender exposes real preview bundles through the `preview` command group.++```bash+# Capture a real preview bundle+cli-anything-blender --json --project scene.blend-cli.json preview capture --recipe quick++# Query the latest bundle+cli-anything-blender --json --project scene.blend-cli.json preview latest --recipe quick++# Start a poll-mode live preview session+cli-anything-blender --json --project scene.blend-cli.json preview live start --recipe quick --mode poll --source-poll-ms 500++# Query current live-session state+cli-anything-blender --json --project scene.blend-cli.json preview live status --recipe quick+```++The default `quick` recipe produces real Blender-rendered `hero.png` and+`workbench.png` artifacts. Live sessions persist:++- `session.json`+- immutable bundle directories+- `trajectory.json`++Inspect or open published preview state with:++```bash+cli-hub previews inspect /path/to/bundle-or-session+cli-hub previews html /path/to/bundle-or-session -o page.html+cli-hub previews watch /path/to/session --open+cli-hub previews open /path/to/bundle-or-session+```+## Interactive REPL```bashdiff --git a/blender/agent-harness/cli_anything/blender/blender_cli.py b/blender/agent-harness/cli_anything/blender/blender_cli.pyindex f468b6b03..ea91203de 100644--- a/blender/agent-harness/cli_anything/blender/blender_cli.py+++ b/blender/agent-harness/cli_anything/blender/blender_cli.py@@ -68,7 +68,7 @@ def _spawn_live_viewer(session_dir: str, poll_ms: int) -> dict:hub = shutil.which("cli-hub")command = [hub or "cli-hub",- "preview",+ "previews","watch",session_dir,"--open",diff --git a/blender/agent-harness/cli_anything/blender/core/preview.py b/blender/agent-harness/cli_anything/blender/core/preview.pyindex a9ae855e0..5d8edfd3f 100644--- a/blender/agent-harness/cli_anything/blender/core/preview.py+++ b/blender/agent-harness/cli_anything/blender/core/preview.py@@ -14,12 +14,17 @@ from typing import Any, Dict, List, Optional, Tuplefrom ..utils import blender_backendfrom ..utils.preview_bundle import (+ append_live_trajectory,artifact_record,+ build_live_history_item,finalize_bundle,find_latest_manifest,fingerprint_data,fingerprint_file,+ live_trajectory_path,+ load_live_trajectory,prepare_bundle,+ summarize_trajectory,)from . import render as render_modfrom . import scene as scene_mod@@ -183,6 +188,9 @@ def _terminate_pid(pid: Any) -> bool:def _with_live_refs(session_dir: Path, payload: Dict[str, Any]) -> Dict[str, Any]:payload["_session_dir"] = str(session_dir.resolve())payload["_session_path"] = str((session_dir / "session.json").resolve())+ trajectory_path = live_trajectory_path(session_dir)+ if trajectory_path.is_file():+ payload["_trajectory_path"] = str(trajectory_path.resolve())return payload@@ -215,15 +223,7 @@ def _update_current_symlink(session_dir: Path, bundle_dir: str) -> Path:def _history_item(bundle_manifest: Dict[str, Any]) -> Dict[str, Any]:- return {- "bundle_id": bundle_manifest.get("bundle_id"),- "bundle_dir": bundle_manifest.get("_bundle_dir"),- "manifest_path": bundle_manifest.get("_manifest_path"),- "summary_path": bundle_manifest.get("_summary_path"),- "created_at": bundle_manifest.get("created_at"),- "status": bundle_manifest.get("status"),- "cached": bool(bundle_manifest.get("cached")),- }+ return build_live_history_item(bundle_manifest)def _ensure_preview_rig(project: Dict[str, Any]) -> List[str]:@@ -465,6 +465,7 @@ def _publish_live_session(live_mode: Optional[str] = None,source_poll_ms: int = DEFAULT_SOURCE_POLL_MS,publish_reason: str = "manual",+ command: Optional[str] = None,) -> Dict[str, Any]:session_dir = _live_session_dir(session, recipe, root_dir=root_dir)session_dir.mkdir(parents=True, exist_ok=True)@@ -472,7 +473,21 @@ def _publish_live_session(existing = _load_existing_live_session(session_dir)now = _now_iso()- current_item = _history_item(bundle_manifest)+ project = session.get_project()+ trajectory = append_live_trajectory(+ session_dir,+ software="blender",+ recipe=recipe,+ bundle_manifest=bundle_manifest,+ publish_reason=publish_reason,+ project_path=session.project_path,+ project_name=Path(session.project_path).name if session.project_path else project.get("name", "Untitled"),+ session_name=session_dir.name,+ command=command,+ command_started_at=now,+ command_finished_at=now,+ )+ current_item = dict(trajectory.get("latest_step") or _history_item(bundle_manifest))history = [current_item]for item in existing.get("history", []):if item.get("bundle_id") == current_item["bundle_id"]:@@ -501,6 +516,7 @@ def _publish_live_session(source_state["last_rendered_fingerprint"] = project_file_fingerprintsource_state["last_rendered_at"] = nowsource_state["last_publish_reason"] = publish_reason+ trajectory_rel = os.path.relpath(Path(trajectory["_trajectory_path"]).resolve(), session_dir)payload = {"protocol_version": LIVE_PROTOCOL_VERSION,@@ -524,16 +540,22 @@ def _publish_live_session("current_cached": bool(bundle_manifest.get("cached")),"bundle_count": len(history),"history": history,+ "trajectory_path": trajectory_rel,+ "trajectory_protocol_version": trajectory.get("protocol_version"),+ "trajectory_step_count": trajectory.get("step_count", 0),+ "current_step_id": trajectory.get("current_step_id"),+ "latest_command": current_item.get("command"),+ "latest_publish_reason": current_item.get("publish_reason", publish_reason),"source_state": source_state,"poller": poller,"publish_command": (f"cli-anything-blender{project_flag} preview live push --recipe {recipe}{root_flag}").strip(),"watch_command": (- f"cli-hub preview watch {session_dir} --open --poll-ms {current_refresh_hint_ms}"+ f"cli-hub previews watch {session_dir} --open --poll-ms {current_refresh_hint_ms}"),- "inspect_command": f"cli-hub preview inspect {session_dir}",- "html_command": f"cli-hub preview html {session_dir}",+ "inspect_command": f"cli-hub previews inspect {session_dir}",+ "html_command": f"cli-hub previews html {session_dir}","start_command": (f"cli-anything-blender{project_flag} preview live start --recipe {recipe} "f"--mode {current_live_mode} --source-poll-ms {current_source_poll_ms}{root_flag}"@@ -580,6 +602,7 @@ def live_start(live_mode=live_mode,source_poll_ms=source_poll_ms,publish_reason=publish_reason,+ command=command,)live_payload["bundle"] = {"bundle_id": bundle_manifest.get("bundle_id"),@@ -639,6 +662,9 @@ def live_status(if poller:poller["running"] = _pid_is_running(poller.get("pid"))payload["poller"] = poller+ trajectory = load_live_trajectory(session_dir)+ if trajectory:+ payload["trajectory_summary"] = summarize_trajectory(trajectory)return _with_live_refs(session_dir, payload)diff --git a/blender/agent-harness/cli_anything/blender/skills/SKILL.md b/blender/agent-harness/cli_anything/blender/skills/SKILL.mdindex 6fdf0bf45..7676fb46f 100644--- a/blender/agent-harness/cli_anything/blender/skills/SKILL.md+++ b/blender/agent-harness/cli_anything/blender/skills/SKILL.md@@ -33,11 +33,11 @@ cli-anything-blender --help# Start interactive REPL modecli-anything-blender-# Create a new project-cli-anything-blender project new -o project.json+# Create a new scene project+cli-anything-blender scene new -o scene.blend-cli.json# Run with JSON output (for agent consumption)-cli-anything-blender --json project info -p project.json+cli-anything-blender --json --project scene.blend-cli.json scene info```### REPL Mode@@ -157,6 +157,38 @@ Render settings and output commands.| `execute` | Render the scene (generates bpy script) || `script` | Generate bpy script without rendering |+### Preview++Real preview bundle capture and live preview session commands.++| Command | Description |+|---------|-------------|+| `preview recipes` | List available preview recipes |+| `preview capture` | Render a real preview bundle for the active scene |+| `preview latest` | Return the latest existing preview bundle |+| `preview live start` | Start a live preview session and publish the first bundle |+| `preview live push` | Publish a refreshed bundle into the live session |+| `preview live status` | Read current live-session state without rendering |+| `preview live stop` | Stop the live session without deleting artifacts |++Typical bundle artifacts for recipe `quick`:++- `hero.png` from real Eevee preview rendering+- `workbench.png` from real Blender Workbench rendering++Live sessions persist:++- `session.json` as the mutable head+- immutable bundle directories+- `trajectory.json` as append-only command-to-preview history++Viewer side:++- `cli-hub previews inspect <bundle-or-session>`+- `cli-hub previews html <bundle-or-session> -o page.html`+- `cli-hub previews watch <session-dir> --open`+- `cli-hub previews open <bundle-or-session>`+### Session@@ -177,12 +209,12 @@ Session management commands.### Create a New Project-Create a new blender project file.+Create a new Blender scene project file.```bash-cli-anything-blender project new -o myproject.json+cli-anything-blender scene new -o myscene.blend-cli.json# Or with JSON output for programmatic use-cli-anything-blender --json project new -o myproject.json+cli-anything-blender --json scene new -o myscene.blend-cli.json```@@ -215,12 +247,34 @@ All commands support dual output modes:```bash# Human output-cli-anything-blender project info -p project.json+cli-anything-blender --project scene.blend-cli.json scene info# JSON output for agents-cli-anything-blender --json project info -p project.json+cli-anything-blender --json --project scene.blend-cli.json scene info+```++## Preview Workflow++Use Blender previews when the agent needs truthful visual checkpoints:++```bash+# List preview recipes+cli-anything-blender --project scene.blend-cli.json preview recipes++# Capture a real preview bundle+cli-anything-blender --json --project scene.blend-cli.json preview capture --recipe quick++# Start a live preview loop+cli-anything-blender --json --project scene.blend-cli.json preview live start --recipe quick --mode poll --source-poll-ms 500++# Query current live head without rendering+cli-anything-blender --json --project scene.blend-cli.json preview live status --recipe quick```+For agents, `preview capture --json` returns bundle metadata plus artifact file+paths. `preview live status --json` returns session metadata plus a compact+`trajectory_summary`.+## For AI AgentsWhen using this CLI programmatically:@@ -229,7 +283,10 @@ When using this CLI programmatically:2. **Check return codes** - 0 for success, non-zero for errors3. **Parse stderr** for error messages on failure4. **MANDATORY: Use absolute paths** for all file operations (rendering, project files). Relative paths are prone to failure in background execution.-5. **Verify outputs exist** after export operations+5. **Use `preview capture` or `preview live ...` for visual verification** instead of inferring scene quality from JSON alone+6. **Read returned artifact paths** such as `hero.png` and `workbench.png`; the JSON payload references files, it does not inline image bytes+7. **Treat `_bundle_dir` as one snapshot only**; for stable live history, use `_session_dir` plus `_trajectory_path`+8. **Use `cli-hub previews ...` only to inspect/open existing previews**; preview generation itself always happens through `cli-anything-blender preview ...`## More Information@@ -239,4 +296,4 @@ When using this CLI programmatically:## Version-1.0.0\ No newline at end of file+1.0.0diff --git a/blender/agent-harness/cli_anything/blender/tests/test_core.py b/blender/agent-harness/cli_anything/blender/tests/test_core.pyindex 0ed2c2d51..e227f6ad0 100644--- a/blender/agent-harness/cli_anything/blender/tests/test_core.py+++ b/blender/agent-harness/cli_anything/blender/tests/test_core.py@@ -1160,7 +1160,12 @@ class TestPreview:assert live["source_state"]["project_path"] == str(project_path)assert live["source_state"]["last_rendered_fingerprint"].startswith("sha256:")assert Path(live["_session_path"]).is_file()+ assert Path(live["_trajectory_path"]).is_file()assert (Path(live["_session_dir"]) / "current" / "manifest.json").is_file()+ trajectory = json.loads(Path(live["_trajectory_path"]).read_text(encoding="utf-8"))+ assert trajectory["step_count"] == 1+ assert trajectory["steps"][0]["bundle_id"] == "bundle-a"+ assert live["trajectory_step_count"] == 1def test_live_push_updates_history(self, tmp_path, monkeypatch):sess = Session()@@ -1183,6 +1188,60 @@ class TestPreview:assert pushed["current_bundle_id"] == "bundle-b"assert pushed["history"][0]["bundle_id"] == "bundle-b"assert pushed["history"][1]["bundle_id"] == "bundle-a"+ trajectory = json.loads(Path(pushed["_trajectory_path"]).read_text(encoding="utf-8"))+ assert trajectory["step_count"] == 2+ assert [step["bundle_id"] for step in trajectory["steps"]] == ["bundle-a", "bundle-b"]+ assert pushed["current_step_id"] == "step-0002"++ def test_live_status_includes_trajectory_summary(self, tmp_path, monkeypatch):+ sess = Session()+ proj = create_scene(name="LivePreviewScene")+ project_path = tmp_path / "live-demo.json"+ save_scene(proj, str(project_path))+ sess.set_project(proj, str(project_path))+ bundle_manifest = self._fake_bundle(tmp_path / "bundles", "bundle-a")++ monkeypatch.setattr(preview_mod, "capture", lambda *args, **kwargs: dict(bundle_manifest))++ preview_mod.live_start(sess, root_dir=str(tmp_path), live_mode="manual")+ status = preview_mod.live_status(sess, root_dir=str(tmp_path))+ summary = status["trajectory_summary"]+ assert summary["step_count"] == 1+ assert summary["latest_bundle_id"] == "bundle-a"+ assert summary["latest_publish_reason"] == "live-start"+ assert summary["recent_steps"][0]["step_id"] == "step-0001"++ def test_live_push_appends_trajectory_even_when_bundle_is_reused(self, tmp_path, monkeypatch):+ sess = Session()+ proj = create_scene(name="LivePreviewScene")+ project_path = tmp_path / "live-demo.json"+ save_scene(proj, str(project_path))+ sess.set_project(proj, str(project_path))+ bundle_manifest = self._fake_bundle(tmp_path / "bundles", "bundle-a")+ bundle_manifest["created_at"] = "2025-01-01T00:00:00Z"+ publish_times = [+ "2026-04-23T10:00:00Z",+ "2026-04-23T10:05:00Z",+ ]++ def fake_capture(*args, **kwargs):+ return dict(bundle_manifest)++ monkeypatch.setattr(preview_mod, "capture", fake_capture)+ monkeypatch.setattr(preview_mod, "_now_iso", lambda: publish_times.pop(0))++ preview_mod.live_start(sess, root_dir=str(tmp_path), live_mode="manual")+ pushed = preview_mod.live_push(sess, root_dir=str(tmp_path))+ trajectory = json.loads(Path(pushed["_trajectory_path"]).read_text(encoding="utf-8"))+ assert len(pushed["history"]) == 1+ assert trajectory["step_count"] == 2+ assert [step["step_id"] for step in trajectory["steps"]] == ["step-0001", "step-0002"]+ assert all(step["bundle_id"] == "bundle-a" for step in trajectory["steps"])+ assert [step["command_finished_at"] for step in trajectory["steps"]] == [+ "2026-04-23T10:00:00Z",+ "2026-04-23T10:05:00Z",+ ]+ assert all(step["created_at"] == "2025-01-01T00:00:00Z" for step in trajectory["steps"])def test_live_stop_marks_session_stopped(self, tmp_path, monkeypatch):sess = Session()@@ -1259,10 +1318,13 @@ class TestPreview:result = preview_mod.poll_live_session_once(str(started_session_dir))payload = json.loads((started_session_dir / "session.json").read_text(encoding="utf-8"))+ trajectory = json.loads((started_session_dir / "trajectory.json").read_text(encoding="utf-8"))assert result["action"] == "captured"assert result["bundle_id"] == "bundle-b"assert payload["bundle_count"] >= 2assert payload["source_state"]["last_publish_reason"] == "auto-poll"+ assert trajectory["step_count"] == 2+ assert trajectory["steps"][-1]["publish_reason"] == "auto-poll"def test_poll_live_session_once_exits_for_manual_mode(self, tmp_path, monkeypatch):sess = Session()diff --git a/blender/agent-harness/cli_anything/blender/utils/preview_bundle.py b/blender/agent-harness/cli_anything/blender/utils/preview_bundle.pyindex 3cba5dbf0..0028cc295 100644--- a/blender/agent-harness/cli_anything/blender/utils/preview_bundle.py+++ b/blender/agent-harness/cli_anything/blender/utils/preview_bundle.py@@ -12,6 +12,7 @@ from pathlib import Pathfrom typing import Any, Dict, Iterable, OptionalPROTOCOL_VERSION = "preview-bundle/v1"+TRAJECTORY_PROTOCOL_VERSION = "preview-trajectory/v1"def _slug(value: str) -> str:@@ -123,6 +124,9 @@ def find_cached_manifest():manifest["_manifest_path"] = str(manifest_path.resolve())manifest["_bundle_dir"] = str(manifest_path.parent.resolve())+ manifest["_summary_path"] = str(+ (manifest_path.parent / manifest.get("summary_path", "summary.json")).resolve()+ )return manifestreturn None@@ -157,6 +161,9 @@ def find_latest_manifest(continuemanifest["_manifest_path"] = str(manifest_path.resolve())manifest["_bundle_dir"] = str(manifest_path.parent.resolve())+ manifest["_summary_path"] = str(+ (manifest_path.parent / manifest.get("summary_path", "summary.json")).resolve()+ )return manifestreturn None@@ -302,3 +309,160 @@ def finalize_bundle(manifest["_bundle_dir"] = str(bundle_path)manifest["_summary_path"] = summary_pathreturn manifest+++def _clean_none_fields(data: Dict[str, Any]) -> Dict[str, Any]:+ return {key: value for key, value in data.items() if value is not None}+++def live_trajectory_path(session_dir: str | Path) -> Path:+ return Path(session_dir).expanduser().resolve() / "trajectory.json"+++def load_live_trajectory(session_dir: str | Path) -> Dict[str, Any]:+ trajectory_path = live_trajectory_path(session_dir)+ if not trajectory_path.is_file():+ return {}+ return _load_json(trajectory_path)+++def summarize_trajectory(trajectory: Dict[str, Any], *, recent_steps: int = 3) -> Dict[str, Any]:+ steps = list(trajectory.get("steps") or [])+ latest = steps[-1] if steps else {}+ recent = steps[-max(1, int(recent_steps)):] if steps else []+ return _clean_none_fields(+ {+ "protocol_version": trajectory.get("protocol_version"),+ "software": trajectory.get("software"),+ "recipe": trajectory.get("recipe"),+ "step_count": trajectory.get("step_count", len(steps)),+ "current_step_id": trajectory.get("current_step_id"),+ "latest_command": latest.get("command"),+ "latest_publish_reason": latest.get("publish_reason"),+ "latest_bundle_id": latest.get("bundle_id"),+ "recent_steps": [+ _clean_none_fields(+ {+ "step_id": item.get("step_id"),+ "step_index": item.get("step_index"),+ "bundle_id": item.get("bundle_id"),+ "publish_reason": item.get("publish_reason"),+ "command": item.get("command"),+ "command_finished_at": item.get("command_finished_at"),+ "status": item.get("status"),+ "cached": item.get("cached"),+ }+ )+ for item in recent+ ],+ }+ )+++def build_live_history_item(+ bundle_manifest: Dict[str, Any],+ *,+ step_id: Optional[str] = None,+ step_index: Optional[int] = None,+ publish_reason: Optional[str] = None,+ command: Optional[str] = None,+ command_started_at: Optional[str] = None,+ command_finished_at: Optional[str] = None,+ source_fingerprint: Optional[str] = None,+ stage_label: Optional[str] = None,+ note: Optional[str] = None,+) -> Dict[str, Any]:+ source = bundle_manifest.get("source") or {}+ resolved_command = command or (bundle_manifest.get("generator") or {}).get("command")+ resolved_fingerprint = (+ source_fingerprint+ or source.get("project_fingerprint")+ or source.get("capture_fingerprint")+ )+ created_at = bundle_manifest.get("created_at")+ return _clean_none_fields(+ {+ "step_id": step_id,+ "step_index": step_index,+ "bundle_id": bundle_manifest.get("bundle_id"),+ "bundle_dir": bundle_manifest.get("_bundle_dir"),+ "manifest_path": bundle_manifest.get("_manifest_path"),+ "summary_path": bundle_manifest.get("_summary_path"),+ "created_at": created_at,+ "status": bundle_manifest.get("status"),+ "cached": bool(bundle_manifest.get("cached")),+ "publish_reason": publish_reason,+ "command": resolved_command,+ "command_started_at": command_started_at or created_at,+ "command_finished_at": command_finished_at or created_at,+ "source_fingerprint": resolved_fingerprint,+ "stage_label": stage_label,+ "note": note,+ }+ )+++def append_live_trajectory(+ session_dir: str | Path,+ *,+ software: str,+ recipe: str,+ bundle_manifest: Dict[str, Any],+ publish_reason: str,+ project_path: Optional[str] = None,+ project_name: Optional[str] = None,+ session_name: Optional[str] = None,+ command: Optional[str] = None,+ command_started_at: Optional[str] = None,+ command_finished_at: Optional[str] = None,+ source_fingerprint: Optional[str] = None,+ stage_label: Optional[str] = None,+ note: Optional[str] = None,+) -> Dict[str, Any]:+ session_path = Path(session_dir).expanduser().resolve()+ existing = load_live_trajectory(session_path)+ steps = list(existing.get("steps") or [])+ finished_at = (+ command_finished_at+ or bundle_manifest.get("created_at")+ or datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")+ )+ started_at = command_started_at or finished_at+ step_index = len(steps) + 1+ step_id = f"step-{step_index:04d}"+ step = build_live_history_item(+ bundle_manifest,+ step_id=step_id,+ step_index=step_index,+ publish_reason=publish_reason,+ command=command,+ command_started_at=started_at,+ command_finished_at=finished_at,+ source_fingerprint=source_fingerprint,+ stage_label=stage_label,+ note=note,+ )+ steps.append(step)++ trajectory: Dict[str, Any] = dict(existing)+ trajectory.update(+ _clean_none_fields(+ {+ "protocol_version": TRAJECTORY_PROTOCOL_VERSION,+ "software": software,+ "recipe": recipe,+ "session_name": session_name or session_path.name,+ "project_path": project_path,+ "project_name": project_name,+ "created_at": existing.get("created_at", finished_at),+ "updated_at": finished_at,+ "step_count": len(steps),+ "current_step_id": step_id,+ }+ )+ )+ trajectory["steps"] = steps+ trajectory_path = write_json(str(live_trajectory_path(session_path)), trajectory)+ trajectory["_trajectory_path"] = trajectory_path+ trajectory["latest_step"] = step+ return trajectorydiff --git a/cli-anything-plugin/HARNESS.md b/cli-anything-plugin/HARNESS.mdindex 0a4f64da4..4fd881137 100644--- a/cli-anything-plugin/HARNESS.md+++ b/cli-anything-plugin/HARNESS.md@@ -271,6 +271,11 @@ local skill file.- Document `--json` flag usage for machine-readable output- List all command groups with brief descriptions- Provide realistic examples that demonstrate common workflows+- If the harness supports previews, document the producer surface+ (`cli-anything-<software> preview ...`) and the consumer surface+ (`cli-hub previews ...`) separately in both `README.md` and `SKILL.md`+- If the harness supports live preview, explain what `preview live status --json`+ returns and how agents should use it as a cheap introspection call**Skill Path in CLI Banner:**@@ -499,9 +504,25 @@ These are non-negotiable. Every harness MUST follow all of them.visual checkpoints SHOULD implement a `preview` command group with at least`preview recipes`, `preview capture`, and `preview latest`. Diff-orientedtools SHOULD also expose `preview diff`.+- **Keep producer and viewer roles separate** β Harnesses publish preview state+ through `cli-anything-<software> preview ...`. `cli-hub previews ...` is the+ read-only consumer for inspect/html/watch/open and should not be treated as a+ render path.- **Use the shared preview bundle protocol** β Preview-capable harnesses SHOULDemit `preview-bundle/v1` bundles as described in `docs/PREVIEW_PROTOCOL.md`.The bundle is the contract; the renderer remains the real software.+- **Live preview should separate head vs history** β When a harness supports+ `preview live ...`, it SHOULD persist:+ - `session.json` as the mutable current head+ - immutable bundle directories for each capture+ - `trajectory.json` as the append-only command-to-preview history+- **Do not treat `_bundle_dir` as the permanent build identity** β It is only a+ single snapshot path. Stable live replay should anchor on `session_dir` plus+ `trajectory.json`.+- **Make `preview live status --json` agent-cheap** β Live-preview harnesses+ SHOULD include a compact `trajectory_summary` in `preview live status --json`+ so agents do not need to read `trajectory.json` just to understand the latest+ command-to-bundle mapping.- **Do not screen-scrape GUI windows for previews** β Preview artifacts must beproduced by the real backend or by native inspection/export paths operatingon real project/capture state.@@ -529,6 +550,125 @@ These are non-negotiable. Every harness MUST follow all of them.- **Every `cli_anything/<software>/tests/` directory MUST contain a `TEST.md`**documenting test coverage, realistic workflows tested, and full test results output.+### Preview & Live Preview Norms++Preview support is optional at the harness level, but once a harness exposes+meaningful intermediate visual or inspection state it MUST follow a consistent+contract so agents and humans can reason about it across software.++See [`guides/preview-methodology.md`](guides/preview-methodology.md) for the+detailed design guide and documentation checklist.++#### Producer vs consumer roles++Keep these roles separate:++- **Producer** β `cli-anything-<software> preview ...`+ - talks to the real backend+ - owns preview recipes, source fingerprinting, and live-session publishing+ - creates bundles, sessions, and trajectories+- **Consumer** β `cli-hub previews ...`+ - reads already-published preview state+ - provides `inspect`, `html`, `watch`, and `open`+ - never renders, replays, or synthesizes preview artifacts++Harness help text, README examples, and SKILL examples MUST not present+`cli-hub previews ...` as a render path. Agents should think in two steps:+publish with the software CLI, inspect with `cli-hub`.++#### Three-layer persistence model++Preview-capable harnesses SHOULD treat preview state as three separate objects:++- **`bundle_dir`** β an immutable preview snapshot implementing+ `preview-bundle/v1`+- **`session.json`** β the mutable current head for a live preview stream+- **`trajectory.json`** β the append-only permanent command-to-preview history++Do not use `_bundle_dir` as the long-lived identity of a project. It is a+single snapshot path and may change whenever the source fingerprint changes or a+new bundle is forced. Stable live replay should anchor on `session_dir` plus+`trajectory.json`.++#### Recommended CLI surface++If a harness has meaningful previewable state, it SHOULD expose at least:++- `preview recipes`+- `preview capture`+- `preview latest`++Add the following when the software semantics justify them:++- `preview diff`+- `preview live start`+- `preview live push`+- `preview live status`+- `preview live stop`+- an internal or hidden poll monitor when poll-first refresh is supported++Recommended semantics:++- `preview capture` renders or exports a fresh bundle unless cache reuse is valid+- `preview latest` returns the newest existing bundle and does not render a new one+- `preview diff` publishes an immutable comparison bundle+- `preview live start` creates a live session and publishes an initial bundle+- `preview live push` adds a new bundle to an existing live session+- `preview live status` is a read-only status probe+- `preview live stop` stops further publishing without deleting prior history++#### Agent-facing JSON contract++All preview commands MUST support `--json`.++At minimum, machine-readable preview results SHOULD expose:++- stable paths such as `_bundle_dir`, `_manifest_path`, and `summary_path`+- artifact metadata and relative artifact paths+- session metadata when live mode is involved+- trajectory references when history exists++`preview live status --json` is especially important because agents call it as a+cheap introspection step between mutations. It SHOULD return:++- whether a live session exists and whether it is active+- `session_dir`, `session_path`, and current bundle identifiers or paths+- current publish reason and latest command metadata when available+- a compact `trajectory_summary` with the latest command-to-bundle mapping+- viewer hints such as inspect/html/watch/open commands when the harness emits them++The goal is to let an agent understand current live state without rereading the+entire `trajectory.json` file.++#### Documentation requirements for preview-capable harnesses++Preview-capable harnesses SHOULD document preview usage in both `README.md` and+`SKILL.md`. Cover:++- whether preview support exists at all+- which modes exist: static, diff, live, poll+- the producer commands agents should call+- the consumer commands humans should call with `cli-hub previews ...`+- whether the output is images, video, audio-derived stills, inspection JSON, or mixed artifacts+- what makes the preview truthful for this software++Use concrete examples that show both the publish step and the inspect/watch+step.++#### Truthfulness principle++Preview artifacts MUST be honest views of the real project or capture state.++- Prefer real backend render/export/inspection paths.+- Use native offscreen export or replay when the software provides it.+- Do not fake renders in Python.+- Do not screen-scrape GUI windows just to create something image-like.+- If a temporary camera, light, or helper rig must be injected, mark the bundle+ status accordingly and explain the limitation in summary/context output.++Truthful previews matter more than pretty previews. Agents need intermediate+state they can trust when deciding what to do next.+## Directory Structure```@@ -599,6 +739,7 @@ based on the software you're building a harness for.| Guide | Read when... | Phase ||-------|-------------|-------|| [`session-locking.md`](guides/session-locking.md) | Implementing session save (all harnesses) | Phase 3 |+| [`preview-methodology.md`](guides/preview-methodology.md) | Designing preview, live preview, and agent-facing preview flows | Phase 3, 6.5 || [`skill-generation.md`](guides/skill-generation.md) | Generating the SKILL.md file | Phase 6.5 || [`pypi-publishing.md`](guides/pypi-publishing.md) | Packaging and installing the CLI | Phase 7 || [`mcp-backend.md`](guides/mcp-backend.md) | Software has an MCP server, no native CLI | Phase 3 |diff --git a/cli-anything-plugin/guides/preview-methodology.md b/cli-anything-plugin/guides/preview-methodology.mdnew file mode 100644index 000000000..ccb5b8813--- /dev/null+++ b/cli-anything-plugin/guides/preview-methodology.md@@ -0,0 +1,284 @@+# Preview Methodology for Harnesses++Use this guide when a harness can expose meaningful intermediate state through+images, video snippets, inspection bundles, or other honest artifacts derived+from the real software.++This guide complements `docs/PREVIEW_PROTOCOL.md`. The protocol defines the+bundle/session/trajectory format. This document defines the harness-side+methodology and the agent-facing command contract.++## Producer vs consumer++Keep preview production and preview consumption as separate roles:++- **Producer:** `cli-anything-<software> preview ...`+ - talks to the real backend+ - computes source fingerprints+ - chooses recipes+ - publishes bundles, sessions, and trajectories+- **Consumer:** `cli-hub previews ...`+ - reads existing preview state+ - provides `inspect`, `html`, `watch`, and `open`+ - never renders or synthesizes preview artifacts++This distinction should be visible in:++- command help+- README examples+- `SKILL.md`+- live-session viewer hints++The short rule is:++- publish with `cli-anything-<software>`+- inspect with `cli-hub`++## Three-layer model: bundle, session, trajectory++Preview-capable harnesses should model history explicitly instead of treating+the latest bundle directory as the permanent object.++### `bundle_dir`: immutable snapshot++A bundle directory is one concrete preview result:++- one static capture+- one diff capture+- one live-session publish step++It should implement `preview-bundle/v1` and contain:++- `manifest.json`+- `summary.json`+- `artifacts/`++Treat bundle directories as immutable once published.++### `session.json`: mutable live head++`session.json` represents the current live view for a project and recipe. It is+the stable entry point for βwhat is current right nowβ.++Typical fields include:++- current bundle id and paths+- session root and recipe+- viewer commands+- current step id+- trajectory location++### `trajectory.json`: append-only permanent history++`trajectory.json` is the durable replay object. It should survive beyond the+current head and allow later tooling to reconstruct how the artifact evolved.++At minimum, each trajectory step should capture:++- `step_id`+- `step_index`+- `command`+- `command_started_at`+- `command_finished_at`+- `publish_reason`+- `source_fingerprint`+- `bundle_id`+- `bundle_dir`+- `manifest_path`+- `summary_path`+- optional `stage_label`+- optional `note`++This is the right place to bind agent actions to preview state. Do not expect+`_bundle_dir` alone to serve that role.++## Recommended CLI surface++### Baseline surface++If the software has meaningful previewable state, expose:++- `preview recipes`+- `preview capture`+- `preview latest`++Recommended behavior:++- `preview recipes`+ - list the supported preview recipes and what they produce+- `preview capture`+ - produce a fresh or cache-reused bundle from the current source state+- `preview latest`+ - return the newest existing bundle for the project and recipe without re-rendering++### Optional diff surface++Expose `preview diff` when the software benefits from direct A/B comparison.++Good fits:++- GPU capture tools+- tools with before/after inspection states+- workflows where the delta is more important than the current hero frame++### Optional live surface++Expose these when iterative live inspection is useful:++- `preview live start`+- `preview live push`+- `preview live status`+- `preview live stop`++Recommended semantics:++- `start`+ - initialize the session root and publish the first bundle+- `push`+ - append a new bundle into the existing live session+- `status`+ - report current state only; do not render+- `stop`+ - mark the session inactive but preserve all published history++### Optional poll-first refresh++Use poll-first refresh when the source of truth is file-backed and agents may+save through separate commands between preview calls.++Good fits:++- JSON project files+- XML timelines+- capture files or scene files whose fingerprints are cheap to recompute++Poll support usually looks like:++- `preview live start --mode poll`+- an internal background monitor loop+- source fingerprint checks before rendering++Only add poll mode when it reduces agent friction. Do not add background loops+that publish meaningless duplicate bundles.++## Agent-facing design for `preview live status --json`++This command exists to make the live loop cheap for agents.++It should answer:++- does a live session exist?+- is it active?+- what is the current bundle?+- what was the latest publish reason?+- what is the latest command-to-preview mapping?++Recommended fields:++- `status`+- `active`+- `_session_dir`+- `_session_path`+- `current_bundle_id`+- `current_bundle_dir`+- `current_manifest_path`+- `current_summary_path`+- `_trajectory_path`+- `current_step_id`+- `latest_command`+- `latest_publish_reason`+- `trajectory_summary`++`trajectory_summary` should be compact and cheap to parse. Include:++- `step_count`+- `current_step_id`+- `latest_command`+- `latest_publish_reason`+- `latest_bundle_id`+- `recent_steps`++This lets an agent decide whether the session is progressing without opening the+full trajectory file on every loop.++## README and SKILL guidance++Preview-capable harnesses should explain preview in both `README.md` and+`SKILL.md`.++### README.md should cover++- what preview modes exist+- what each recipe emits+- how to publish a bundle+- how to inspect/watch/open it with `cli-hub previews ...`+- how live sessions behave+- any truthfulness caveats, such as injected cameras or helper rigs++### SKILL.md should cover++- the producer command surface under `preview`+- whether `diff`, `live`, and poll mode are available+- the fact that `cli-hub previews ...` is the read-only consumer+- agent guidance for `--json`+- what artifact roles to expect, such as `hero`, `gallery`, `clip`, or diff outputs++Every preview example should show both sides:++```bash+cli-anything-<software> --project demo.ext preview capture --recipe quick --json+cli-hub previews inspect /path/to/bundle+```++## When to add diff, live, or poll++Use this decision table:++| Capability | Add it when... | Avoid it when... |+|------------|----------------|------------------|+| `preview diff` | the comparison itself is the product | the current-state bundle already answers the question |+| `preview live` | iterative agent work benefits from a stable current head | the tool only produces occasional one-shot exports |+| poll-first refresh | project fingerprints change outside preview commands | the source is expensive to fingerprint or updates are rare |++Do not add complexity just to match another harness. Add the capability only+when it matches the softwareβs actual iteration loop.++## Truthfulness rules++Previews must be honest enough for agent decisions.++Preferred sources, in order:++1. native render/export from the real backend+2. native inspection or replay outputs from the real tool+3. real-project offscreen capture helpers++Avoid:++- fake renders synthesized outside the tool+- screen recordings of the GUI as the primary preview artifact+- approximations that silently diverge from what the software would really produce++If the harness needs temporary helper state, surface that honestly:++- mark the bundle `partial` or equivalent+- note injected preview cameras, lights, or helpers in summary/context output+- keep the project fingerprint separate from the injected preview rig when possible++## Implementation checklist++- Decide whether preview is meaningful for this software.+- Define one or more recipes with clear outputs.+- Publish `preview-bundle/v1` bundles.+- Keep bundle, session, and trajectory distinct.+- Ensure all preview commands support `--json`.+- Make `preview latest` read-only.+- Make `preview live status --json` cheap for agents.+- Document producer vs consumer commands in README and SKILL.+- Verify outputs come from the real backend.++## Related references++- [`../HARNESS.md`](../HARNESS.md)+- [`skill-generation.md`](skill-generation.md)+- [`../../docs/PREVIEW_PROTOCOL.md`](../../docs/PREVIEW_PROTOCOL.md)diff --git a/cli-anything-plugin/guides/skill-generation.md b/cli-anything-plugin/guides/skill-generation.mdindex cf5fd0702..e9916834b 100644--- a/cli-anything-plugin/guides/skill-generation.md+++ b/cli-anything-plugin/guides/skill-generation.md@@ -96,6 +96,20 @@ skill definition.- List all command groups with brief descriptions- Provide realistic examples that demonstrate common workflows+## Preview-Capable Harnesses++If the harness supports previews, the generated or edited `SKILL.md` should+include a dedicated preview section that covers:++- the producer command surface: `cli-anything-<software> preview ...`+- the consumer command surface: `cli-hub previews ...`+- whether `preview diff`, `preview live ...`, or poll mode exist+- how agents should use `--json` results and artifact paths+- at least one publish example and one inspect/watch example++For the full preview methodology, see+[`preview-methodology.md`](preview-methodology.md).+## Skill Path in CLI BannerReplSkin prefers the repo-root canonical skill file and falls back to thediff --git a/cli-anything-plugin/preview_bundle.py b/cli-anything-plugin/preview_bundle.pyindex 3cba5dbf0..0028cc295 100644--- a/cli-anything-plugin/preview_bundle.py+++ b/cli-anything-plugin/preview_bundle.py@@ -12,6 +12,7 @@ from pathlib import Pathfrom typing import Any, Dict, Iterable, OptionalPROTOCOL_VERSION = "preview-bundle/v1"+TRAJECTORY_PROTOCOL_VERSION = "preview-trajectory/v1"def _slug(value: str) -> str:@@ -123,6 +124,9 @@ def find_cached_manifest():manifest["_manifest_path"] = str(manifest_path.resolve())manifest["_bundle_dir"] = str(manifest_path.parent.resolve())+ manifest["_summary_path"] = str(+ (manifest_path.parent / manifest.get("summary_path", "summary.json")).resolve()+ )return manifestreturn None@@ -157,6 +161,9 @@ def find_latest_manifest(continuemanifest["_manifest_path"] = str(manifest_path.resolve())manifest["_bundle_dir"] = str(manifest_path.parent.resolve())+ manifest["_summary_path"] = str(+ (manifest_path.parent / manifest.get("summary_path", "summary.json")).resolve()+ )return manifestreturn None@@ -302,3 +309,160 @@ def finalize_bundle(manifest["_bundle_dir"] = str(bundle_path)manifest["_summary_path"] = summary_pathreturn manifest+++def _clean_none_fields(data: Dict[str, Any]) -> Dict[str, Any]:+ return {key: value for key, value in data.items() if value is not None}+++def live_trajectory_path(session_dir: str | Path) -> Path:+ return Path(session_dir).expanduser().resolve() / "trajectory.json"+++def load_live_trajectory(session_dir: str | Path) -> Dict[str, Any]:+ trajectory_path = live_trajectory_path(session_dir)+ if not trajectory_path.is_file():+ return {}+ return _load_json(trajectory_path)+++def summarize_trajectory(trajectory: Dict[str, Any], *, recent_steps: int = 3) -> Dict[str, Any]:+ steps = list(trajectory.get("steps") or [])+ latest = steps[-1] if steps else {}+ recent = steps[-max(1, int(recent_steps)):] if steps else []+ return _clean_none_fields(+ {+ "protocol_version": trajectory.get("protocol_version"),+ "software": trajectory.get("software"),+ "recipe": trajectory.get("recipe"),+ "step_count": trajectory.get("step_count", len(steps)),+ "current_step_id": trajectory.get("current_step_id"),+ "latest_command": latest.get("command"),+ "latest_publish_reason": latest.get("publish_reason"),+ "latest_bundle_id": latest.get("bundle_id"),+ "recent_steps": [+ _clean_none_fields(+ {+ "step_id": item.get("step_id"),+ "step_index": item.get("step_index"),+ "bundle_id": item.get("bundle_id"),+ "publish_reason": item.get("publish_reason"),+ "command": item.get("command"),+ "command_finished_at": item.get("command_finished_at"),+ "status": item.get("status"),+ "cached": item.get("cached"),+ }+ )+ for item in recent+ ],+ }+ )+++def build_live_history_item(+ bundle_manifest: Dict[str, Any],+ *,+ step_id: Optional[str] = None,+ step_index: Optional[int] = None,+ publish_reason: Optional[str] = None,+ command: Optional[str] = None,+ command_started_at: Optional[str] = None,+ command_finished_at: Optional[str] = None,+ source_fingerprint: Optional[str] = None,+ stage_label: Optional[str] = None,+ note: Optional[str] = None,+) -> Dict[str, Any]:+ source = bundle_manifest.get("source") or {}+ resolved_command = command or (bundle_manifest.get("generator") or {}).get("command")+ resolved_fingerprint = (+ source_fingerprint+ or source.get("project_fingerprint")+ or source.get("capture_fingerprint")+ )+ created_at = bundle_manifest.get("created_at")+ return _clean_none_fields(+ {+ "step_id": step_id,+ "step_index": step_index,+ "bundle_id": bundle_manifest.get("bundle_id"),+ "bundle_dir": bundle_manifest.get("_bundle_dir"),+ "manifest_path": bundle_manifest.get("_manifest_path"),+ "summary_path": bundle_manifest.get("_summary_path"),+ "created_at": created_at,+ "status": bundle_manifest.get("status"),+ "cached": bool(bundle_manifest.get("cached")),+ "publish_reason": publish_reason,+ "command": resolved_command,+ "command_started_at": command_started_at or created_at,+ "command_finished_at": command_finished_at or created_at,+ "source_fingerprint": resolved_fingerprint,+ "stage_label": stage_label,+ "note": note,+ }+ )+++def append_live_trajectory(+ session_dir: str | Path,+ *,+ software: str,+ recipe: str,+ bundle_manifest: Dict[str, Any],+ publish_reason: str,+ project_path: Optional[str] = None,+ project_name: Optional[str] = None,+ session_name: Optional[str] = None,+ command: Optional[str] = None,+ command_started_at: Optional[str] = None,+ command_finished_at: Optional[str] = None,+ source_fingerprint: Optional[str] = None,+ stage_label: Optional[str] = None,+ note: Optional[str] = None,+) -> Dict[str, Any]:+ session_path = Path(session_dir).expanduser().resolve()+ existing = load_live_trajectory(session_path)+ steps = list(existing.get("steps") or [])+ finished_at = (+ command_finished_at+ or bundle_manifest.get("created_at")+ or datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")+ )+ started_at = command_started_at or finished_at+ step_index = len(steps) + 1+ step_id = f"step-{step_index:04d}"+ step = build_live_history_item(+ bundle_manifest,+ step_id=step_id,+ step_index=step_index,+ publish_reason=publish_reason,+ command=command,+ command_started_at=started_at,+ command_finished_at=finished_at,+ source_fingerprint=source_fingerprint,+ stage_label=stage_label,+ note=note,+ )+ steps.append(step)++ trajectory: Dict[str, Any] = dict(existing)+ trajectory.update(+ _clean_none_fields(+ {+ "protocol_version": TRAJECTORY_PROTOCOL_VERSION,+ "software": software,+ "recipe": recipe,+ "session_name": session_name or session_path.name,+ "project_path": project_path,+ "project_name": project_name,+ "created_at": existing.get("created_at", finished_at),+ "updated_at": finished_at,+ "step_count": len(steps),+ "current_step_id": step_id,+ }+ )+ )+ trajectory["steps"] = steps+ trajectory_path = write_json(str(live_trajectory_path(session_path)), trajectory)+ trajectory["_trajectory_path"] = trajectory_path+ trajectory["latest_step"] = step+ return trajectorydiff --git a/cli-hub/README.md b/cli-hub/README.mdindex a43acceee..933edcc9c 100644--- a/cli-hub/README.md+++ b/cli-hub/README.md@@ -37,6 +37,40 @@ cli-hub update gimpcli-hub uninstall gimp```+## Preview Viewer++`cli-hub` also includes the generic preview consumer for preview-capable+harnesses.++Use this split:++- `cli-anything-<software> preview ...` creates or updates preview state+- `cli-hub previews ...` inspects or opens that existing preview state++Canonical viewer commands:++```bash+# Inspect an existing preview bundle or live session+cli-hub previews inspect /path/to/bundle-or-session++# Render HTML for a bundle or live session+cli-hub previews html /path/to/bundle-or-session -o page.html++# Watch a live session over localhost+cli-hub previews watch /path/to/session --open --poll-ms 1500++# Open a bundle or live session directly in a browser+cli-hub previews open /path/to/bundle-or-session+```++For live sessions, `cli-hub previews` reads:++- `session.json` for the current head+- `trajectory.json` for the command-to-preview history+- the current bundle manifest and artifacts++This command group never renders or publishes previews by itself.+## What gets installedEach CLI harness is a standalone Python package that wraps a real application (GIMP, Blender, etc.) with a stateful command-line interface. Every harness supports:@@ -54,6 +88,8 @@ cli-hub is designed to be agent-friendly. AI coding agents can:2. `cli-hub search <keyword>` or `cli-hub list --json` to discover tools3. `cli-hub install <name>` to install what they need4. Use `--json` output for structured data parsing+5. For preview-capable harnesses, call `cli-anything-<software> preview ... --json`+ first, then inspect returned bundle/session paths with `cli-hub previews ...`## Available categoriesdiff --git a/cli-hub/cli_hub/__init__.py b/cli-hub/cli_hub/__init__.pyindex 00aa4cb6a..a0fca10c3 100644--- a/cli-hub/cli_hub/__init__.py+++ b/cli-hub/cli_hub/__init__.py@@ -1,3 +1,3 @@"""cli-hub β Download, manage, and browse CLI-Anything harnesses."""-__version__ = "0.2.3"+__version__ = "0.3.0"diff --git a/cli-hub/cli_hub/cli.py b/cli-hub/cli_hub/cli.pyindex 78e4b9ef2..651dbbb1b 100644--- a/cli-hub/cli_hub/cli.py+++ b/cli-hub/cli_hub/cli.py@@ -264,15 +264,15 @@ def launch(name, args):os.execvp(entry, [entry] + list(args))[email protected](name="preview", invoke_without_command=True)[email protected](name="previews", invoke_without_command=True)@click.pass_context-def preview(ctx):- """Inspect preview bundles emitted by CLI-Anything harnesses."""+def previews(ctx):+ """Inspect existing preview bundles or live sessions; this command does not publish previews."""if ctx.invoked_subcommand is None:click.echo(ctx.get_help())[email protected]("inspect")[email protected]("inspect")@click.argument("preview_ref")@click.option("--json", "as_json", is_flag=True, help="Output preview metadata as JSON.")def preview_inspect(preview_ref, as_json):@@ -290,7 +290,7 @@ def preview_inspect(preview_ref, as_json):click.echo(render_inspect_text(preview_ref), nl=False)[email protected]("html")[email protected]("html")@click.argument("preview_ref")@click.option("--output", "-o", "output_path", default=None, help="Output HTML path.")@click.option("--poll-ms", default=1500, show_default=True, help="Polling interval for live session pages.")@@ -325,7 +325,7 @@ def _serve_live_session(session_ref, poll_ms, auto_open, port):click.echo("Browser launch unavailable. Open this manually:\n"f" {live_url}\n"- f" Suggested command: {session.get('watch_command') or f'cli-hub preview watch {session_dir} --open'}"+ f" Suggested command: {session.get('watch_command') or f'cli-hub previews watch {session_dir} --open'}")click.echo("Press Ctrl-C to stop the live preview server.")try:@@ -336,7 +336,7 @@ def _serve_live_session(session_ref, poll_ms, auto_open, port):server.server_close()[email protected]("watch")[email protected]("watch")@click.argument("session_ref")@click.option("--poll-ms", default=1500, show_default=True, help="Polling interval for the live page.")@click.option("--port", default=0, show_default=True, help="Preferred localhost port. Use 0 for auto.")@@ -346,7 +346,7 @@ def preview_watch(session_ref, poll_ms, port, auto_open):_serve_live_session(session_ref, poll_ms=poll_ms, auto_open=auto_open, port=port)[email protected]("open")[email protected]("open")@click.argument("preview_ref")@click.option("--output", "-o", "output_path", default=None, help="Override the generated HTML path.")@click.option("--poll-ms", default=1500, show_default=True, help="Polling interval when opening a live session.")diff --git a/cli-hub/cli_hub/preview.py b/cli-hub/cli_hub/preview.pyindex 100fad3a6..74174eb47 100644--- a/cli-hub/cli_hub/preview.py+++ b/cli-hub/cli_hub/preview.py@@ -10,7 +10,7 @@ import shutilimport subprocessfrom http.server import SimpleHTTPRequestHandler, ThreadingHTTPServerfrom pathlib import Path-from typing import Any, Dict, Tuple+from typing import Any, Dict, Iterable, List, Optional, Tupledef _read_json(path: Path) -> Dict[str, Any]:@@ -77,6 +77,439 @@ def format_bytes(size: int) -> str:return f"{size / (1024 * 1024 * 1024):.1f} GB"+_TRAJECTORY_FILENAMES = ("trajectory.json", "timeline.json")+_TRAJECTORY_CONTAINER_KEYS = {"trajectory", "timeline"}+_TRAJECTORY_PATH_KEYS = {+ "trajectory_path",+ "timeline_path",+ "trajectory_file",+ "timeline_file",+ "trajectory_ref",+ "timeline_ref",+}+++def _coalesce(*values: Any) -> Any:+ for value in values:+ if value is None:+ continue+ if isinstance(value, str) and not value.strip():+ continue+ return value+ return None+++def _stringify_command(value: Any) -> Optional[str]:+ if value is None:+ return None+ if isinstance(value, str):+ value = value.strip()+ return value or None+ if isinstance(value, (list, tuple)):+ text = " ".join(str(part) for part in value if part is not None)+ return text.strip() or None+ if isinstance(value, dict):+ for key in ("display", "display_cmd", "command", "raw", "argv"):+ if key in value:+ return _stringify_command(value[key])+ return json.dumps(value, ensure_ascii=False, sort_keys=True)+ return str(value)+++def _normalize_index(value: Any, fallback: int) -> int:+ if isinstance(value, bool):+ return fallback+ if isinstance(value, int):+ return value+ if isinstance(value, float):+ return int(value)+ if isinstance(value, str):+ stripped = value.strip()+ if stripped.isdigit():+ return int(stripped)+ return fallback+++def _resolve_ref_path(base_dir: Path, path_ref: str) -> Path:+ ref = Path(path_ref).expanduser()+ if not ref.is_absolute():+ ref = (base_dir / ref).resolve()+ else:+ ref = ref.resolve()+ return ref+++def _iter_trajectory_hints(node: Any, *, _seen: Optional[set[int]] = None) -> Iterable[Tuple[str, Any, str]]:+ if _seen is None:+ _seen = set()+ if not isinstance(node, (dict, list)):+ return+ node_id = id(node)+ if node_id in _seen:+ return+ _seen.add(node_id)+ if isinstance(node, list):+ for item in node:+ yield from _iter_trajectory_hints(item, _seen=_seen)+ return+ for key, value in node.items():+ lower = str(key).lower()+ if lower in _TRAJECTORY_CONTAINER_KEYS:+ if isinstance(value, dict):+ yield ("object", value, lower)+ elif isinstance(value, str):+ yield ("path", value, lower)+ elif lower in _TRAJECTORY_PATH_KEYS and isinstance(value, str):+ yield ("path", value, lower)+ if isinstance(value, (dict, list)):+ yield from _iter_trajectory_hints(value, _seen=_seen)+++def _trajectory_candidate_refs(base_dir: Path, *payloads: Dict[str, Any]) -> List[str]:+ refs: List[str] = []+ seen = set()+ for payload in payloads:+ if not isinstance(payload, dict):+ continue+ for kind, value, _label in _iter_trajectory_hints(payload):+ if kind != "path" or not isinstance(value, str):+ continue+ resolved = _resolve_ref_path(base_dir, value)+ if not resolved.is_file():+ continue+ rel = os.path.relpath(resolved, base_dir)+ if rel not in seen:+ refs.append(rel)+ seen.add(rel)+ for filename in _TRAJECTORY_FILENAMES:+ if filename not in seen:+ refs.append(filename)+ seen.add(filename)+ return refs+++def _extract_bundle_payload(item: Dict[str, Any]) -> Dict[str, Any]:+ for key in ("copied_bundle", "bundle", "preview_bundle", "current_bundle", "published_bundle"):+ value = item.get(key)+ if isinstance(value, dict):+ return value+ return item+++def _normalize_timeline_row(item: Any, index: int) -> Dict[str, Any]:+ if not isinstance(item, dict):+ return {+ "order_index": index,+ "step_index": index,+ "step_id": f"step-{index:03d}",+ "step_label": str(item),+ "command": None,+ "command_started_at": None,+ "command_finished_at": None,+ "timeline_ready_at": None,+ "publish_reason": None,+ "bundle_id": None,+ "bundle_dir": None,+ "manifest_path": None,+ "summary_path": None,+ "status": None,+ "stage_label": None,+ "note": None,+ }++ bundle = _extract_bundle_payload(item)+ command = _stringify_command(+ _coalesce(+ item.get("command"),+ item.get("display_cmd"),+ item.get("display_command"),+ item.get("argv"),+ item.get("raw_command"),+ )+ )+ step_index = _normalize_index(+ _coalesce(item.get("step_index"), item.get("index"), item.get("sequence_index")),+ index,+ )+ status = item.get("status")+ if status is None and "returncode" in item:+ status = "ok" if int(item.get("returncode", 1)) == 0 else "error"++ return {+ "order_index": index,+ "step_index": step_index,+ "step_id": str(+ _coalesce(item.get("step_id"), item.get("id"), item.get("command_id"), f"step-{step_index:03d}")+ ),+ "step_label": _coalesce(+ item.get("step_label"),+ item.get("label"),+ item.get("title"),+ item.get("name"),+ item.get("stage_title"),+ item.get("stage_label"),+ ),+ "command": command,+ "command_started_at": _coalesce(+ item.get("command_started_at"),+ item.get("started_at"),+ item.get("timeline_start_s"),+ item.get("start_s"),+ ),+ "command_finished_at": _coalesce(+ item.get("command_finished_at"),+ item.get("finished_at"),+ item.get("timeline_end_s"),+ item.get("end_s"),+ item.get("completed_at"),+ ),+ "timeline_ready_at": _coalesce(+ item.get("timeline_ready_s"),+ item.get("ready_at"),+ item.get("published_at"),+ item.get("created_at"),+ ),+ "publish_reason": _coalesce(item.get("publish_reason"), item.get("reason")),+ "bundle_id": _coalesce(item.get("bundle_id"), bundle.get("bundle_id")),+ "bundle_dir": _coalesce(item.get("bundle_dir"), bundle.get("bundle_dir")),+ "manifest_path": _coalesce(item.get("manifest_path"), bundle.get("manifest_path")),+ "summary_path": _coalesce(item.get("summary_path"), bundle.get("summary_path")),+ "status": status,+ "stage_label": _coalesce(+ item.get("stage_title"),+ item.get("stage_label"),+ item.get("stage_id"),+ item.get("stage"),+ ),+ "note": _coalesce(+ item.get("note"),+ item.get("stage_story"),+ item.get("story"),+ item.get("description"),+ ),+ }+++def _merge_timeline_rows(target: Dict[str, Any], source: Dict[str, Any]) -> None:+ for key in (+ "step_label",+ "command",+ "command_started_at",+ "command_finished_at",+ "timeline_ready_at",+ "publish_reason",+ "bundle_id",+ "bundle_dir",+ "manifest_path",+ "summary_path",+ "status",+ "stage_label",+ "note",+ ):+ target[key] = _coalesce(target.get(key), source.get(key))+++def _pick_trajectory_events(raw: Dict[str, Any]) -> List[Dict[str, Any]]:+ for key in ("preview_events", "events", "publishes", "entries", "history", "steps", "timeline"):+ value = raw.get(key)+ if isinstance(value, list) and value:+ return value+ return []+++def _sort_timeline_rows(rows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:+ def sort_key(row: Dict[str, Any]) -> Tuple[int, int, str]:+ step_index = _normalize_index(row.get("step_index"), row.get("order_index", 0))+ order_index = _normalize_index(row.get("order_index"), step_index)+ finish = _coalesce(row.get("command_finished_at"), row.get("timeline_ready_at"), "")+ return step_index, order_index, str(finish)++ return sorted(rows, key=sort_key)+++def _normalize_trajectory(raw: Optional[Dict[str, Any]], *, fallback_history: Optional[List[Dict[str, Any]]] = None) -> Optional[Dict[str, Any]]:+ if not raw and not fallback_history:+ return None++ rows: List[Dict[str, Any]] = []+ rows_by_id: Dict[str, Dict[str, Any]] = {}+ rows_by_index: Dict[int, Dict[str, Any]] = {}+ commands = raw.get("commands", []) if isinstance(raw, dict) else []++ if isinstance(commands, list):+ for index, item in enumerate(commands):+ row = _normalize_timeline_row(item, index)+ rows.append(row)+ rows_by_id[row["step_id"]] = row+ rows_by_index[row["step_index"]] = row++ events = _pick_trajectory_events(raw) if isinstance(raw, dict) else []+ if events:+ for index, item in enumerate(events):+ event_row = _normalize_timeline_row(item, index)+ existing = rows_by_id.get(event_row["step_id"]) or rows_by_index.get(event_row["step_index"])+ if existing is None:+ rows.append(event_row)+ rows_by_id[event_row["step_id"]] = event_row+ rows_by_index[event_row["step_index"]] = event_row+ continue+ _merge_timeline_rows(existing, event_row)++ if not rows and fallback_history:+ for index, item in enumerate(fallback_history):+ rows.append(_normalize_timeline_row(item, index))++ rows = _sort_timeline_rows(rows)+ if not rows:+ return None++ recent_command_row = next((row for row in reversed(rows) if row.get("command")), None)+ recent_publish_row = next(+ (row for row in reversed(rows) if row.get("publish_reason") or row.get("bundle_id")),+ None,+ )++ step_count = _coalesce(+ raw.get("step_count") if isinstance(raw, dict) else None,+ len(commands) if isinstance(commands, list) and commands else None,+ len(rows),+ )+ published_bundles = sum(1 for row in rows if row.get("bundle_id"))+ return {+ "protocol": raw.get("protocol") or raw.get("protocol_version") if isinstance(raw, dict) else None,+ "step_count": step_count,+ "current_step_id": _coalesce(+ raw.get("current_step_id") if isinstance(raw, dict) else None,+ recent_publish_row.get("step_id") if recent_publish_row else None,+ recent_command_row.get("step_id") if recent_command_row else None,+ ),+ "published_bundle_count": published_bundles,+ "recent_command": _coalesce(+ raw.get("latest_command") if isinstance(raw, dict) else None,+ recent_command_row.get("command") if recent_command_row else None,+ ),+ "recent_publish_reason": _coalesce(+ raw.get("latest_publish_reason") if isinstance(raw, dict) else None,+ recent_publish_row.get("publish_reason") if recent_publish_row else None,+ ),+ "recent_bundle_id": recent_publish_row.get("bundle_id") if recent_publish_row else None,+ "entries": rows,+ }+++def _load_trajectory(base_dir: Path, *payloads: Dict[str, Any]) -> Optional[Dict[str, Any]]:+ for ref in _trajectory_candidate_refs(base_dir, *payloads):+ candidate = _resolve_ref_path(base_dir, ref)+ if candidate.is_file():+ raw = _read_json(candidate)+ normalized = _normalize_trajectory(raw)+ if normalized is not None:+ normalized["mode"] = "trajectory"+ normalized["source_path"] = str(candidate)+ normalized["source_label"] = os.path.relpath(candidate, base_dir)+ return normalized++ for payload in payloads:+ if not isinstance(payload, dict):+ continue+ for kind, value, label in _iter_trajectory_hints(payload):+ if kind != "object" or not isinstance(value, dict):+ continue+ normalized = _normalize_trajectory(value)+ if normalized is not None:+ normalized["mode"] = "trajectory"+ normalized["source_path"] = None+ normalized["source_label"] = label+ return normalized+ return None+++def _history_from_session(session: Dict[str, Any]) -> Optional[Dict[str, Any]]:+ history = session.get("history", [])+ if not isinstance(history, list) or not history:+ return None+ normalized = _normalize_trajectory({}, fallback_history=history)+ if normalized is None:+ return None+ source_state = session.get("source_state", {}) if isinstance(session.get("source_state"), dict) else {}+ normalized["mode"] = "legacy-history"+ normalized["source_path"] = None+ normalized["source_label"] = "session.history"+ normalized["current_step_id"] = _coalesce(+ session.get("current_step_id"),+ normalized.get("current_step_id"),+ )+ normalized["recent_command"] = _coalesce(+ session.get("latest_command"),+ normalized.get("recent_command"),+ )+ normalized["recent_publish_reason"] = _coalesce(+ session.get("latest_publish_reason"),+ normalized.get("recent_publish_reason"),+ source_state.get("last_publish_reason"),+ )+ return normalized+++def _apply_session_trajectory_metadata(trajectory: Optional[Dict[str, Any]], session: Dict[str, Any]) -> Optional[Dict[str, Any]]:+ if trajectory is None:+ return None+ trajectory["protocol"] = _coalesce(+ trajectory.get("protocol"),+ session.get("trajectory_protocol_version"),+ )+ trajectory["step_count"] = _coalesce(+ session.get("trajectory_step_count"),+ trajectory.get("step_count"),+ )+ trajectory["current_step_id"] = _coalesce(+ session.get("current_step_id"),+ trajectory.get("current_step_id"),+ )+ trajectory["recent_command"] = _coalesce(+ session.get("latest_command"),+ trajectory.get("recent_command"),+ )+ trajectory["recent_publish_reason"] = _coalesce(+ session.get("latest_publish_reason"),+ trajectory.get("recent_publish_reason"),+ )+ return trajectory+++def _render_trajectory_text_lines(title: str, trajectory: Optional[Dict[str, Any]], *, limit: int = 5) -> List[str]:+ if not trajectory:+ return []+ lines = [+ "",+ title,+ f" Source: {trajectory.get('source_label') or trajectory.get('mode') or 'unknown'}",+ f" Steps: {trajectory.get('step_count', 0)}",+ f" Published bundles: {trajectory.get('published_bundle_count', 0)}",+ ]+ if trajectory.get("current_step_id"):+ lines.append(f" Current step: {trajectory['current_step_id']}")+ if trajectory.get("recent_command"):+ lines.append(f" Recent command: {trajectory['recent_command']}")+ if trajectory.get("recent_publish_reason"):+ lines.append(f" Recent publish: {trajectory['recent_publish_reason']}")+ if trajectory.get("recent_bundle_id"):+ lines.append(f" Recent bundle: {trajectory['recent_bundle_id']}")+ entries = trajectory.get("entries", [])+ if entries:+ lines.append(" Timeline")+ for entry in entries[-limit:]:+ label = entry.get("step_label") or entry.get("stage_label") or entry.get("step_id") or "step"+ lines.append(f" - {label}")+ if entry.get("command"):+ lines.append(f" Command: {entry['command']}")+ if entry.get("publish_reason"):+ lines.append(f" Publish: {entry['publish_reason']}")+ if entry.get("bundle_id"):+ lines.append(f" Bundle: {entry['bundle_id']}")+ return lines++def inspect_bundle(bundle_ref: str) -> Dict[str, Any]:bundle_dir, manifest, summary = load_bundle(bundle_ref)return {@@ -84,6 +517,7 @@ def inspect_bundle(bundle_ref: str) -> Dict[str, Any]:"manifest": manifest,"summary": summary,"artifact_count": len(manifest.get("artifacts", [])),+ "trajectory": _load_trajectory(bundle_dir, manifest, summary),}@@ -94,15 +528,23 @@ def inspect_session(session_ref: str) -> Dict[str, Any]:current_bundle = inspect_bundle(str(session_dir / session.get("current_link", "current")))except (FileNotFoundError, ValueError):current_bundle = None+ trajectory = _load_trajectory(session_dir, session)+ if trajectory is None:+ trajectory = _history_from_session(session)+ trajectory = _apply_session_trajectory_metadata(trajectory, session)return {"session_dir": str(session_dir),"session": session,"current_bundle": current_bundle,+ "trajectory": trajectory,}def render_inspect_text(bundle_ref: str) -> str:- bundle_dir, manifest, summary = load_bundle(bundle_ref)+ payload = inspect_bundle(bundle_ref)+ bundle_dir = Path(payload["bundle_dir"])+ manifest = payload["manifest"]+ summary = payload["summary"]lines = [f"Bundle: {bundle_dir}",f"Protocol: {manifest.get('protocol_version', 'unknown')}",@@ -147,11 +589,15 @@ def render_inspect_text(bundle_ref: str) -> str:if artifact.get("bytes") is not None:desc += f" ({format_bytes(int(artifact['bytes']))})"lines.append(desc)+ lines.extend(_render_trajectory_text_lines("Trajectory", payload.get("trajectory")))return "\n".join(lines) + "\n"def render_session_text(session_ref: str) -> str:- session_dir, session = load_session(session_ref)+ payload = inspect_session(session_ref)+ session_dir = Path(payload["session_dir"])+ session = payload["session"]+ trajectory = payload.get("trajectory")lines = [f"Live Session: {session_dir}",f"Protocol: {session.get('protocol_version', 'unknown')}",@@ -164,15 +610,18 @@ def render_session_text(session_ref: str) -> str:]if session.get("watch_command"):lines.append(f"Watch: {session['watch_command']}")- history = session.get("history", [])- if history:- lines.append("")- lines.append("History")- for item in history:- lines.append(- f" - {item.get('bundle_id', '?')} "- f"[{item.get('status', 'unknown')}] {item.get('created_at', 'unknown')}"- )+ history_title = "History" if trajectory and trajectory.get("mode") == "legacy-history" else "Trajectory"+ lines.extend(_render_trajectory_text_lines(history_title, trajectory))+ if trajectory is None:+ history = session.get("history", [])+ if history:+ lines.append("")+ lines.append("History")+ for item in history:+ lines.append(+ f" - {item.get('bundle_id', '?')} "+ f"[{item.get('status', 'unknown')}] {item.get('created_at', 'unknown')}"+ )return "\n".join(lines) + "\n"@@ -223,8 +672,65 @@ def _render_artifact_card(output_dir: Path, bundle_dir: Path, artifact: Dict[str)+def _render_trajectory_html_section(trajectory: Optional[Dict[str, Any]]) -> str:+ if not trajectory:+ return ""++ summary_cards = [+ ("Source", trajectory.get("source_label") or trajectory.get("mode") or "unknown"),+ ("Steps", trajectory.get("step_count", 0)),+ ("Published", trajectory.get("published_bundle_count", 0)),+ ]+ if trajectory.get("recent_publish_reason"):+ summary_cards.append(("Recent publish", trajectory["recent_publish_reason"]))+ elif trajectory.get("recent_bundle_id"):+ summary_cards.append(("Recent bundle", trajectory["recent_bundle_id"]))++ cards_html = "".join(+ f'<div class="fact-card"><span>{html.escape(str(label))}</span><strong>{html.escape(str(value))}</strong></div>'+ for label, value in summary_cards+ )++ items = trajectory.get("entries", [])[-6:]+ items_html = "".join(+ (+ '<article class="trajectory-item">'+ f'<strong>{html.escape(str(item.get("step_label") or item.get("stage_label") or item.get("step_id") or "step"))}</strong>'+ + (+ f'<div class="trajectory-command"><code>{html.escape(str(item["command"]))}</code></div>'+ if item.get("command")+ else ""+ )+ + (+ f'<div class="trajectory-meta">Publish reason: {html.escape(str(item["publish_reason"]))}</div>'+ if item.get("publish_reason")+ else ""+ )+ + (+ f'<div class="trajectory-meta">Bundle: {html.escape(str(item["bundle_id"]))}</div>'+ if item.get("bundle_id")+ else ""+ )+ + "</article>"+ )+ for item in items+ )++ return (+ '<section class="section">'+ "<h2>Trajectory</h2>"+ f'<div class="facts">{cards_html}</div>'+ f'<div class="trajectory-list">{items_html or "<div class=\"artifact-file\">No step timeline entries yet.</div>"}</div>'+ "</section>"+ )++def render_html(bundle_ref: str, output_path: str) -> str:- bundle_dir, manifest, summary = load_bundle(bundle_ref)+ payload = inspect_bundle(bundle_ref)+ bundle_dir = Path(payload["bundle_dir"])+ manifest = payload["manifest"]+ summary = payload["summary"]+ trajectory = payload.get("trajectory")output_file = Path(output_path).expanduser().resolve()output_file.parent.mkdir(parents=True, exist_ok=True)@@ -242,6 +748,7 @@ def render_html(bundle_ref: str, output_path: str) -> str:_render_artifact_card(output_file.parent, bundle_dir, artifact)for artifact in manifest.get("artifacts", []))+ trajectory_html = _render_trajectory_html_section(trajectory)html_text = f"""<!doctype html><html lang="en">@@ -424,6 +931,39 @@ def render_html(bundle_ref: str, output_path: str) -> str:color: var(--accent);text-decoration: none;}}+ .trajectory-list {{+ display: grid;+ gap: 12px;+ margin-top: 16px;+ }}+ .trajectory-item {{+ border: 1px solid var(--edge);+ border-radius: 18px;+ padding: 14px 16px;+ background: rgba(255,255,255,0.72);+ }}+ .trajectory-item strong {{+ display: block;+ font-size: 0.98rem;+ }}+ .trajectory-command {{+ margin-top: 10px;+ padding: 10px 12px;+ border-radius: 14px;+ background: rgba(23,23,23,0.05);+ overflow-x: auto;+ }}+ .trajectory-command code {{+ font-family: "SFMono-Regular", "Menlo", "Consolas", monospace;+ font-size: 12px;+ color: var(--ink);+ }}+ .trajectory-meta {{+ margin-top: 8px;+ color: var(--muted);+ font-size: 0.88rem;+ word-break: break-word;+ }}@media (max-width: 720px) {{.shell {{ padding: 18px 12px 36px; }}.hero-top, .meta-grid {{ padding: 20px 18px; }}@@ -447,6 +987,7 @@ def render_html(bundle_ref: str, output_path: str) -> str:<div class="meta-item">Source<strong>{html.escape(str(manifest.get("source", {}).get("project_path") or manifest.get("source", {}).get("capture_path") or "n/a"))}</strong></div></div></section>+ {trajectory_html}<section class="section"><h2>Artifacts</h2><div class="artifact-grid">{artifact_cards}</div>@@ -461,7 +1002,10 @@ def render_html(bundle_ref: str, output_path: str) -> str:def render_live_html(session_ref: str, output_path: str, poll_ms: int = 1500) -> str:- session_dir, session = load_session(session_ref)+ payload = inspect_session(session_ref)+ session_dir = Path(payload["session_dir"])+ session = payload["session"]+ trajectory = payload.get("trajectory")output_file = Path(output_path).expanduser().resolve()output_file.parent.mkdir(parents=True, exist_ok=True)headline = html.escape(@@ -470,6 +1014,7 @@ def render_live_html(session_ref: str, output_path: str, poll_ms: int = 1500) ->or f"{session.get('software', 'Preview')} live preview")poll_ms = max(250, int(poll_ms))+ trajectory_candidate_refs = _trajectory_candidate_refs(session_dir, session)html_text = f"""<!doctype html><html lang="en"><head>@@ -710,6 +1255,30 @@ def render_live_html(session_ref: str, output_path: str, poll_ms: int = 1500) ->color: var(--muted);word-break: break-word;}}+ .history-chip {{+ display: inline-flex;+ align-items: center;+ gap: 6px;+ border-radius: 999px;+ background: rgba(17,18,21,0.06);+ color: var(--muted);+ padding: 4px 9px;+ font-size: 11px;+ letter-spacing: 0.08em;+ text-transform: uppercase;+ margin-top: 8px;+ width: fit-content;+ }}+ .history-command {{+ margin-top: 8px;+ padding: 10px 12px;+ border-radius: 12px;+ background: rgba(17,18,21,0.05);+ font-family: var(--mono);+ font-size: 12px;+ white-space: pre-wrap;+ word-break: break-word;+ }}.empty {{padding: 28px;border: 1px dashed var(--edge);@@ -782,8 +1351,8 @@ def render_live_html(session_ref: str, output_path: str, poll_ms: int = 1500) -></article><article class="panel"><div class="panel-header">- <h2>Recent Bundles</h2>- <span id="history-meta" class="subtitle">Latest publishes first</span>+ <h2 id="history-title">History / Timeline</h2>+ <span id="history-meta" class="subtitle">Trajectory-aware command to bundle view</span></div><div class="panel-body"><div id="history" class="history"></div>@@ -795,6 +1364,7 @@ def render_live_html(session_ref: str, output_path: str, poll_ms: int = 1500) -><script>const POLL_MS = {poll_ms};const CURRENT_LINK = {json.dumps(session.get("current_link", "current"))};+ const TRAJECTORY_CANDIDATES = {json.dumps(trajectory_candidate_refs)};function escapeHtml(value) {{return String(value ?? "")@@ -804,6 +1374,25 @@ def render_live_html(session_ref: str, output_path: str, poll_ms: int = 1500) ->.replaceAll('"', """);}}+ function firstDefined(...values) {{+ for (const value of values) {{+ if (value === null || value === undefined) continue;+ if (typeof value === "string" && value.trim() === "") continue;+ return value;+ }}+ return null;+ }}++ function commandText(value) {{+ if (value === null || value === undefined) return null;+ if (typeof value === "string") return value.trim() || null;+ if (Array.isArray(value)) return value.map((part) => String(part)).join(" ").trim() || null;+ if (typeof value === "object") {{+ return commandText(value.display_cmd || value.command || value.argv || value.raw) || JSON.stringify(value);+ }}+ return String(value);+ }}+async function fetchJson(path) {{const sep = path.includes("?") ? "&" : "?";const response = await fetch(`${{path}}${{sep}}ts=${{Date.now()}}`, {{ cache: "no-store" }});@@ -819,19 +1408,191 @@ def render_live_html(session_ref: str, output_path: str, poll_ms: int = 1500) ->chip.dataset.state = isError ? "error" : "ok";}}- function renderFacts(session, manifest, summary) {{+ function collectTrajectoryHints(node, state) {{+ if (!node || typeof node !== "object") return;+ if (state.seen.has(node)) return;+ state.seen.add(node);+ if (Array.isArray(node)) {{+ for (const item of node) collectTrajectoryHints(item, state);+ return;+ }}+ for (const [key, value] of Object.entries(node)) {{+ const lower = String(key).toLowerCase();+ if ((lower === "trajectory" || lower === "timeline") && value && typeof value === "object" && !Array.isArray(value)) {{+ state.embedded ||= value;+ }}+ if ((lower === "trajectory" || lower === "timeline" || lower.endsWith("_trajectory") || lower.endsWith("_timeline")) && typeof value === "string") {{+ state.refs.add(value);+ }}+ if ((lower === "trajectory_path" || lower === "timeline_path" || lower === "trajectory_ref" || lower === "timeline_ref") && typeof value === "string") {{+ state.refs.add(value);+ }}+ if (value && typeof value === "object") {{+ collectTrajectoryHints(value, state);+ }}+ }}+ }}++ function collectTrajectoryCandidates(session) {{+ const state = {{ refs: new Set(TRAJECTORY_CANDIDATES), embedded: null, seen: new Set() }};+ collectTrajectoryHints(session, state);+ return {{ refs: Array.from(state.refs), embedded: state.embedded }};+ }}++ async function fetchTrajectory(session) {{+ const hints = collectTrajectoryCandidates(session);+ if (hints.embedded) {{+ return {{ raw: hints.embedded, ref: "embedded:session" }};+ }}+ for (const ref of hints.refs) {{+ try {{+ const raw = await fetchJson(ref);+ return {{ raw, ref }};+ }} catch (_error) {{+ }}+ }}+ return null;+ }}++ function normalizeTimelineItem(item, fallbackIndex) {{+ const bundle = (item && typeof item === "object" && !Array.isArray(item))+ ? (item.copied_bundle || item.bundle || item.preview_bundle || item.current_bundle || item.published_bundle || item)+ : {{}};+ const stepIndex = Number.parseInt(firstDefined(item?.step_index, item?.index, item?.sequence_index, fallbackIndex), 10);+ const returnCode = item?.returncode;+ return {{+ orderIndex: fallbackIndex,+ stepIndex: Number.isFinite(stepIndex) ? stepIndex : fallbackIndex,+ stepId: String(firstDefined(item?.step_id, item?.id, item?.command_id, `step-${{fallbackIndex}}`)),+ stepLabel: firstDefined(item?.step_label, item?.label, item?.title, item?.name, item?.stage_title, item?.stage_label),+ command: commandText(firstDefined(item?.command, item?.display_cmd, item?.display_command, item?.argv, item?.raw_command)),+ commandStartedAt: firstDefined(item?.command_started_at, item?.started_at, item?.timeline_start_s, item?.start_s),+ commandFinishedAt: firstDefined(item?.command_finished_at, item?.finished_at, item?.timeline_end_s, item?.end_s, item?.completed_at),+ createdAt: firstDefined(item?.created_at, item?.timeline_ready_s, item?.ready_at, item?.published_at),+ publishReason: firstDefined(item?.publish_reason, item?.reason),+ bundleId: firstDefined(item?.bundle_id, bundle?.bundle_id),+ bundleDir: firstDefined(item?.bundle_dir, bundle?.bundle_dir),+ manifestPath: firstDefined(item?.manifest_path, bundle?.manifest_path),+ summaryPath: firstDefined(item?.summary_path, bundle?.summary_path),+ status: firstDefined(item?.status, returnCode === 0 ? "ok" : null),+ cached: item?.cached,+ sourceFingerprint: item?.source_fingerprint,+ note: firstDefined(item?.note, item?.stage_story, item?.story, item?.description),+ }};+ }}++ function normalizeLegacyHistory(session) {{+ const history = Array.isArray(session.history) ? session.history : [];+ const entries = history.map((item, index) => normalizeTimelineItem(item, index));+ return {{+ mode: "legacy-history",+ sourceLabel: "session.history",+ stepCount: firstDefined(session.trajectory_step_count, entries.length, 0),+ currentStepId: session.current_step_id || null,+ recentCommand: session.latest_command || null,+ recentPublishReason: firstDefined(session.latest_publish_reason, session.source_state?.last_publish_reason),+ publishedBundleCount: entries.filter((entry) => entry.bundleId).length,+ entries,+ }};+ }}++ function normalizeTrajectory(session, payload) {{+ if (!payload || !payload.raw || typeof payload.raw !== "object") {{+ return normalizeLegacyHistory(session);+ }}++ const raw = payload.raw;+ const commands = Array.isArray(raw.commands) ? raw.commands : [];+ const entries = [];+ const byId = new Map();+ const byIndex = new Map();++ for (let index = 0; index < commands.length; index += 1) {{+ const row = normalizeTimelineItem(commands[index], index);+ entries.push(row);+ byId.set(row.stepId, row);+ byIndex.set(row.stepIndex, row);+ }}++ let events = [];+ for (const key of ["steps", "preview_events", "entries", "events", "history", "timeline", "publishes"]) {{+ if (Array.isArray(raw[key]) && raw[key].length) {{+ events = raw[key];+ break;+ }}+ }}++ for (let index = 0; index < events.length; index += 1) {{+ const row = normalizeTimelineItem(events[index], index);+ const existing = byId.get(row.stepId) || byIndex.get(row.stepIndex);+ if (!existing) {{+ entries.push(row);+ byId.set(row.stepId, row);+ byIndex.set(row.stepIndex, row);+ continue;+ }}+ for (const key of [+ "stepLabel",+ "command",+ "commandStartedAt",+ "commandFinishedAt",+ "createdAt",+ "publishReason",+ "bundleId",+ "bundleDir",+ "manifestPath",+ "summaryPath",+ "status",+ "cached",+ "sourceFingerprint",+ "note",+ ]) {{+ existing[key] = firstDefined(existing[key], row[key]);+ }}+ }}++ if (!entries.length) {{+ return normalizeLegacyHistory(session);+ }}++ entries.sort((left, right) =>+ (left.stepIndex - right.stepIndex)+ || (left.orderIndex - right.orderIndex)+ || String(left.commandFinishedAt || left.createdAt || "").localeCompare(String(right.commandFinishedAt || right.createdAt || ""))+ );++ const recentCommandEntry = [...entries].reverse().find((entry) => entry.command);+ const recentPublishEntry = [...entries].reverse().find((entry) => entry.publishReason || entry.bundleId);++ return {{+ mode: "trajectory",+ protocol: raw.protocol_version || raw.protocol || session.trajectory_protocol_version || null,+ sourceLabel: payload.ref || session.trajectory_path || "trajectory.json",+ stepCount: firstDefined(raw.step_count, session.trajectory_step_count, commands.length || entries.length, 0),+ currentStepId: firstDefined(raw.current_step_id, session.current_step_id, recentPublishEntry?.stepId, recentCommandEntry?.stepId),+ recentCommand: firstDefined(session.latest_command, raw.latest_command, recentCommandEntry?.command),+ recentPublishReason: firstDefined(session.latest_publish_reason, raw.latest_publish_reason, recentPublishEntry?.publishReason),+ publishedBundleCount: entries.filter((entry) => entry.bundleId).length,+ entries,+ }};+ }}++ function renderFacts(session, manifest, summary, trajectory) {{const facts = Object.assign({{software: manifest.software || session.software || "unknown",recipe: manifest.recipe || session.recipe || "unknown",bundle: manifest.bundle_id || session.current_bundle_id || "n/a",+ step_count: trajectory.stepCount || session.trajectory_step_count || "n/a",+ current_step: trajectory.currentStepId || session.current_step_id || "n/a",+ publish_reason: trajectory.recentPublishReason || session.latest_publish_reason || "n/a",updated: session.updated_at || "unknown",}},summary.facts || {{}});const row = document.getElementById("fact-row");row.innerHTML = Object.entries(facts)- .slice(0, 8)+ .slice(0, 9).map(([key, value]) => `<div class="fact-card"><span>${{escapeHtml(key)}}</span>@@ -915,15 +1676,22 @@ def render_live_html(session_ref: str, output_path: str, poll_ms: int = 1500) ->`).join("");}}- function renderNotes(session, manifest, summary) {{+ function renderNotes(session, manifest, summary, trajectory) {{const warnings = summary.warnings || manifest.warnings || [];const actions = summary.next_actions || [];const notes = document.getElementById("notes");const lines = [`<div><strong>Current bundle</strong><br>${{escapeHtml(session.current_bundle_id || manifest.bundle_id || "n/a")}}</div>`,+ `<div><strong>Current step</strong><br>${{escapeHtml(trajectory.currentStepId || session.current_step_id || "n/a")}}</div>`,`<div><strong>Session path</strong><br>${{escapeHtml(session.project_path || session.project_name || "n/a")}}</div>`,`<div><strong>Last update</strong><br>${{escapeHtml(session.updated_at || "unknown")}}</div>`,];+ if (trajectory.recentCommand) {{+ lines.push(`<div><strong>Latest command</strong><br>${{escapeHtml(trajectory.recentCommand)}}</div>`);+ }}+ if (trajectory.recentPublishReason) {{+ lines.push(`<div><strong>Latest publish reason</strong><br>${{escapeHtml(trajectory.recentPublishReason)}}</div>`);+ }}if (warnings.length) {{lines.push(`<div><strong>Warnings</strong><ul>${{warnings.map((item) => `<li>${{escapeHtml(item)}}</li>`).join("")}}</ul></div>`);}}@@ -933,26 +1701,50 @@ def render_live_html(session_ref: str, output_path: str, poll_ms: int = 1500) ->notes.innerHTML = lines.join("");}}- function renderHistory(session) {{- const history = session.history || [];+ function renderHistory(session, trajectory) {{const root = document.getElementById("history");- if (!history.length) {{+ const title = document.getElementById("history-title");+ const meta = document.getElementById("history-meta");+ const entries = Array.isArray(trajectory.entries) ? [...trajectory.entries].reverse() : [];+ if (!entries.length) {{+ title.textContent = "History / Timeline";+ meta.textContent = "No trajectory or publish history yet";root.innerHTML = '<div class="empty">No live preview publishes yet.</div>';return;}}- root.innerHTML = history.map((item) => `- <article class="history-item">- <strong>${{escapeHtml(item.bundle_id || "unknown")}}</strong>- <span>${{escapeHtml(item.created_at || "unknown")}}</span>- <span>${{escapeHtml(item.bundle_dir || "")}}</span>- </article>- `).join("");+ title.textContent = trajectory.mode === "trajectory" ? "Trajectory Timeline" : "Recent Bundles";+ meta.textContent = `${{trajectory.stepCount || entries.length}} steps Β· ${{trajectory.publishedBundleCount || 0}} published bundles Β· ${{trajectory.sourceLabel || trajectory.mode}}`;+ root.innerHTML = entries.slice(0, 10).map((entry) => {{+ const titleText = entry.stepLabel || entry.stepId || entry.bundleId || "step";+ const chips = [];+ if (entry.stepId && entry.stepId === trajectory.currentStepId) chips.push("current-step");+ if (entry.bundleId && entry.bundleId === session.current_bundle_id) chips.push("current-bundle");+ if (entry.status) chips.push(entry.status);+ if (entry.cached === true) chips.push("cached");+ const detailLines = [+ entry.commandFinishedAt || entry.createdAt,+ entry.publishReason ? `publish=${{entry.publishReason}}` : null,+ entry.bundleId ? `bundle=${{entry.bundleId}}` : null,+ entry.sourceFingerprint ? `fp=${{entry.sourceFingerprint}}` : null,+ entry.bundleDir || entry.manifestPath || null,+ ].filter(Boolean);+ return `+ <article class="history-item">+ <strong>${{escapeHtml(titleText)}}</strong>+ ${{chips.map((chip) => `<div class="history-chip">${{escapeHtml(chip)}}</div>`).join("")}}+ ${{entry.command ? `<div class="history-command">${{escapeHtml(entry.command)}}</div>` : ""}}+ ${{detailLines.map((line) => `<span>${{escapeHtml(line)}}</span>`).join("")}}+ </article>+ `;+ }}).join("");}}async function refresh() {{try {{const session = await fetchJson("session.json");const manifest = await fetchJson(`${{CURRENT_LINK}}/manifest.json`);+ const trajectoryPayload = await fetchTrajectory(session);+ const trajectory = normalizeTrajectory(session, trajectoryPayload);let summary = {{}};const summaryPath = manifest.summary_path ? `${{CURRENT_LINK}}/${{manifest.summary_path}}` : `${{CURRENT_LINK}}/summary.json`;try {{@@ -963,15 +1755,16 @@ def render_live_html(session_ref: str, output_path: str, poll_ms: int = 1500) ->document.getElementById("subtitle").textContent =(summary.headline || "Latest bundle loaded") ++ ` Β· ${{trajectory.stepCount || session.trajectory_step_count || 0}} tracked steps` +` Β· polling every ${{POLL_MS}} ms`;- renderFacts(session, manifest, summary);+ renderFacts(session, manifest, summary, trajectory);renderCommands(session);renderHero(session, manifest);renderClip(session, manifest);renderGallery(session, manifest);- renderNotes(session, manifest, summary);- renderHistory(session);+ renderNotes(session, manifest, summary, trajectory);+ renderHistory(session, trajectory);setStatus("Watching", false);}} catch (error) {{setStatus("Waiting", true);diff --git a/cli-hub/setup.py b/cli-hub/setup.pyindex af145e033..936899224 100644--- a/cli-hub/setup.py+++ b/cli-hub/setup.py@@ -4,7 +4,7 @@ from setuptools import setup, find_packagessetup(name="cli-anything-hub",- version="0.2.3",+ version="0.3.0",description="Package manager for CLI-Anything β browse, install, and manage 40+ agent-native CLI interfaces for GUI applications",long_description=open("README.md").read(),long_description_content_type="text/markdown",diff --git a/cli-hub/tests/test_cli_hub.py b/cli-hub/tests/test_cli_hub.pyindex 2085a09bd..883c7db1b 100644--- a/cli-hub/tests/test_cli_hub.py+++ b/cli-hub/tests/test_cli_hub.py@@ -86,7 +86,7 @@ SAMPLE_REGISTRY = {}-def _make_preview_bundle(tmp_path: Path) -> Path:+def _make_preview_bundle(tmp_path: Path, *, with_trajectory: bool = False) -> Path:bundle_dir = tmp_path / "preview-bundle"artifacts_dir = bundle_dir / "artifacts"artifacts_dir.mkdir(parents=True)@@ -137,12 +137,35 @@ def _make_preview_bundle(tmp_path: Path) -> Path:},],}+ if with_trajectory:+ trajectory = {+ "protocol_version": "preview-trajectory/v1",+ "step_count": 1,+ "current_step_id": "step-001",+ "steps": [+ {+ "step_id": "step-001",+ "step_index": 1,+ "bundle_id": "20260419T104530Z_deadbeef_quick",+ "bundle_dir": str(bundle_dir),+ "manifest_path": str(bundle_dir / "manifest.json"),+ "summary_path": str(bundle_dir / "summary.json"),+ "created_at": "2026-04-19T10:45:30Z",+ "status": "ok",+ "cached": False,+ "publish_reason": "capture",+ "command": "cli-anything-shotcut preview capture --recipe quick",+ }+ ],+ }+ (tmp_path / "trajectory.json").write_text(json.dumps(trajectory, indent=2))+ manifest["context"] = {"trajectory_path": "../trajectory.json"}(bundle_dir / "summary.json").write_text(json.dumps(summary, indent=2))(bundle_dir / "manifest.json").write_text(json.dumps(manifest, indent=2))return bundle_dir-def _make_preview_session(tmp_path: Path) -> Path:+def _make_preview_session(tmp_path: Path, *, with_trajectory: bool = False) -> Path:bundle_dir = _make_preview_bundle(tmp_path)session_dir = tmp_path / "live-session"session_dir.mkdir()@@ -158,9 +181,9 @@ def _make_preview_session(tmp_path: Path) -> Path:"updated_at": "2026-04-20T09:00:00Z","current_link": "current","current_bundle_id": "20260419T104530Z_deadbeef_quick",- "watch_command": "cli-hub preview watch /tmp/live-session --open",+ "watch_command": "cli-hub previews watch /tmp/live-session --open","publish_command": "cli-anything-shotcut preview live push --recipe quick",- "inspect_command": "cli-hub preview inspect /tmp/live-session",+ "inspect_command": "cli-hub previews inspect /tmp/live-session","history": [{"bundle_id": "20260419T104530Z_deadbeef_quick",@@ -170,6 +193,57 @@ def _make_preview_session(tmp_path: Path) -> Path:}],}+ if with_trajectory:+ trajectory = {+ "protocol_version": "preview-trajectory/v1",+ "step_count": 2,+ "current_step_id": "step-002",+ "steps": [+ {+ "step_id": "step-001",+ "step_index": 0,+ "bundle_id": "20260419T104530Z_deadbeef_quick",+ "bundle_dir": str(bundle_dir),+ "manifest_path": str(bundle_dir / "manifest.json"),+ "summary_path": str(bundle_dir / "summary.json"),+ "created_at": "2026-04-19T10:45:30Z",+ "status": "ok",+ "cached": False,+ "publish_reason": "live-start",+ "command": "cli-anything-shotcut preview live start --recipe quick",+ "command_started_at": "2026-04-19T10:45:28Z",+ "command_finished_at": "2026-04-19T10:45:30Z",+ "source_fingerprint": "sha256:test-a",+ },+ {+ "step_id": "step-002",+ "step_index": 1,+ "bundle_id": "20260419T104530Z_deadbeef_quick",+ "bundle_dir": str(bundle_dir),+ "manifest_path": str(bundle_dir / "manifest.json"),+ "summary_path": str(bundle_dir / "summary.json"),+ "created_at": "2026-04-19T10:47:10Z",+ "status": "ok",+ "cached": True,+ "publish_reason": "manual-push",+ "command": "cli-anything-shotcut preview live push --recipe quick",+ "command_started_at": "2026-04-19T10:47:07Z",+ "command_finished_at": "2026-04-19T10:47:10Z",+ "source_fingerprint": "sha256:test-b",+ },+ ],+ }+ (session_dir / "trajectory.json").write_text(json.dumps(trajectory, indent=2))+ session.update(+ {+ "trajectory_path": "trajectory.json",+ "trajectory_protocol_version": "preview-trajectory/v1",+ "trajectory_step_count": 2,+ "current_step_id": "step-002",+ "latest_command": "cli-anything-shotcut preview live push --recipe quick",+ "latest_publish_reason": "manual-push",+ }+ )(session_dir / "session.json").write_text(json.dumps(session, indent=2))return session_dir@@ -260,6 +334,13 @@ class TestPreviewBundle:assert payload["manifest"]["software"] == "shotcut"assert payload["summary"]["headline"] == "Quick preview rendered"+ def test_inspect_bundle_loads_trajectory_from_context_path(self, tmp_path):+ bundle_dir = _make_preview_bundle(tmp_path, with_trajectory=True)+ payload = inspect_bundle(str(bundle_dir))+ assert payload["trajectory"]["protocol"] == "preview-trajectory/v1"+ assert payload["trajectory"]["step_count"] == 1+ assert payload["trajectory"]["recent_publish_reason"] == "capture"+def test_render_inspect_text(self, tmp_path):bundle_dir = _make_preview_bundle(tmp_path)text = render_inspect_text(str(bundle_dir))@@ -278,18 +359,18 @@ class TestPreviewBundle:assert "artifacts/hero.png" in contentassert "artifacts/preview.mp4" in content- def test_preview_inspect_cli_command(self, tmp_path):+ def test_previews_inspect_cli_command(self, tmp_path):bundle_dir = _make_preview_bundle(tmp_path)runner = click.testing.CliRunner()- result = runner.invoke(main, ["preview", "inspect", str(bundle_dir)])+ result = runner.invoke(main, ["previews", "inspect", str(bundle_dir)])assert result.exit_code == 0assert "Quick preview rendered" in result.output- def test_preview_html_cli_command(self, tmp_path):+ def test_previews_html_cli_command(self, tmp_path):bundle_dir = _make_preview_bundle(tmp_path)output_path = tmp_path / "bundle-preview.html"runner = click.testing.CliRunner()- result = runner.invoke(main, ["preview", "html", str(bundle_dir), "-o", str(output_path)])+ result = runner.invoke(main, ["previews", "html", str(bundle_dir), "-o", str(output_path)])assert result.exit_code == 0assert str(output_path) in result.outputassert output_path.is_file()@@ -300,6 +381,14 @@ class TestPreviewBundle:assert payload["session"]["software"] == "shotcut"assert payload["current_bundle"]["manifest"]["bundle_id"] == "20260419T104530Z_deadbeef_quick"+ def test_inspect_session_loads_trajectory(self, tmp_path):+ session_dir = _make_preview_session(tmp_path, with_trajectory=True)+ payload = inspect_session(str(session_dir))+ assert payload["trajectory"]["protocol"] == "preview-trajectory/v1"+ assert payload["trajectory"]["step_count"] == 2+ assert payload["trajectory"]["current_step_id"] == "step-002"+ assert payload["trajectory"]["recent_publish_reason"] == "manual-push"+def test_render_session_text(self, tmp_path):session_dir = _make_preview_session(tmp_path)text = render_session_text(str(session_dir))@@ -307,6 +396,14 @@ class TestPreviewBundle:assert "Watch:" in textassert "History" in text+ def test_render_session_text_with_trajectory(self, tmp_path):+ session_dir = _make_preview_session(tmp_path, with_trajectory=True)+ text = render_session_text(str(session_dir))+ assert "Trajectory" in text+ assert "Current step: step-002" in text+ assert "Recent publish: manual-push" in text+ assert "cli-anything-shotcut preview live push --recipe quick" in text+def test_render_live_html(self, tmp_path):session_dir = _make_preview_session(tmp_path)output_path = tmp_path / "live.html"@@ -318,6 +415,17 @@ class TestPreviewBundle:assert "manifest = await fetchJson(`${CURRENT_LINK}/manifest.json`);" in contentassert "const POLL_MS = 800;" in content+ def test_render_live_html_with_trajectory(self, tmp_path):+ session_dir = _make_preview_session(tmp_path, with_trajectory=True)+ output_path = tmp_path / "live-trajectory.html"+ render_live_html(str(session_dir), str(output_path), poll_ms=600)+ content = output_path.read_text()+ assert 'const TRAJECTORY_CANDIDATES = ["trajectory.json", "timeline.json"];' in content+ assert "function normalizeTrajectory(session, payload)" in content+ assert "Trajectory Timeline" in content+ assert "trajectory_step_count" in content+ assert "latest_publish_reason" in content+@patch("cli_hub.preview.subprocess.Popen")@patch("cli_hub.preview.shutil.which")def test_open_in_browser_prefers_app_mode(self, mock_which, mock_popen):@@ -328,22 +436,36 @@ class TestPreviewBundle:assert result["browser"] == "chromium"assert "--app=http://127.0.0.1:9933/live.html" in result["command"]- def test_preview_inspect_cli_handles_session(self, tmp_path):+ def test_previews_inspect_cli_handles_session(self, tmp_path):session_dir = _make_preview_session(tmp_path)runner = click.testing.CliRunner()- result = runner.invoke(main, ["preview", "inspect", str(session_dir)])+ result = runner.invoke(main, ["previews", "inspect", str(session_dir)])assert result.exit_code == 0assert "Live Session:" in result.output- def test_preview_html_cli_renders_session(self, tmp_path):+ def test_previews_html_cli_renders_session(self, tmp_path):session_dir = _make_preview_session(tmp_path)output_path = tmp_path / "session-live.html"runner = click.testing.CliRunner()- result = runner.invoke(main, ["preview", "html", str(session_dir), "-o", str(output_path), "--poll-ms", "700"])+ result = runner.invoke(main, ["previews", "html", str(session_dir), "-o", str(output_path), "--poll-ms", "700"])assert result.exit_code == 0assert output_path.is_file()assert "const POLL_MS = 700;" in output_path.read_text()+ def test_previews_help_and_cli(self, tmp_path):+ session_dir = _make_preview_session(tmp_path, with_trajectory=True)+ runner = click.testing.CliRunner()+ help_result = runner.invoke(main, ["--help"])+ assert help_result.exit_code == 0+ assert "previews" in help_result.output+ assert "\n review" not in help_result.output+ assert "\n open-preview" not in help_result.output++ inspect_result = runner.invoke(main, ["previews", "inspect", str(session_dir)])+ assert inspect_result.exit_code == 0+ assert "Trajectory" in inspect_result.output+ assert "Current step: step-002" in inspect_result.output+# βββ Installer tests ββββββββββββββββββββββββββββββββββββββββββββββββββdiff --git a/docs/PREVIEW_MECHANISM_PROGRESS.md b/docs/PREVIEW_MECHANISM_PROGRESS.mdindex 93b409d03..f78c26a4f 100644--- a/docs/PREVIEW_MECHANISM_PROGRESS.md+++ b/docs/PREVIEW_MECHANISM_PROGRESS.md@@ -1,6 +1,6 @@# Preview Mechanism Progress-Last updated: 2026-04-22 UTC+Last updated: 2026-04-23 UTCThis document records the current state of the cross-harness preview mechanismwork on the dedicated preview branch.@@ -36,9 +36,9 @@ The current mechanism is built as five layers:3. `Live Session`- A long-lived directory that tracks:- - current bundle- - history- - session metadata+ - mutable `session.json`+ - append-only `trajectory.json`+ - current bundle head- Supports both:- explicit push- poll-first automatic refresh based on source-state fingerprints@@ -46,10 +46,10 @@ The current mechanism is built as five layers:4. `Generic Viewer`- Implemented in `cli-hub`.- Supports:- - inspect- - html- - watch- - open+ - `cli-hub previews inspect`+ - `cli-hub previews html`+ - `cli-hub previews watch`+ - `cli-hub previews open`- Lets agents and humans consume the same preview state through differentsurfaces.@@ -66,7 +66,7 @@ The current mechanism is built as five layers:- `cli-anything-plugin/preview_bundle.py`- `cli-anything-plugin/HARNESS.md` preview requirements- `cli-hub/cli_hub/preview.py`-- `cli-hub` preview CLI integration+- `cli-hub` previews CLI integration### Harnesses with preview support@@ -79,17 +79,20 @@ The current mechanism is built as five layers:- `openscreen`- quick preview capture- bundle emission+ - append-only `trajectory.json` beside stable preview roots- `blender`- preview capture- live session- poll-mode auto refresh+ - `preview live status --json` returns `trajectory_summary`- real Gyro Observatory demo script with stage-by-stage preview checkpoints- `freecad`- quick preview capture- live session- poll-mode auto refresh+ - `preview live status --json` returns `trajectory_summary`- richer preview/export macro reconstruction- motion CLI for true frame rendering@@ -97,6 +100,18 @@ The current mechanism is built as five layers:- preview capture- preview diff- replay-oriented bundle generation+ - append-only `trajectory.json` for capture/diff history++## Canonical Command Split++Use this wording consistently:++- software harnesses publish previews through `cli-anything-<software> preview ...`+- `cli-hub previews ...` only inspects, renders, opens, or watches existing+ bundles and live sessions++There are no `cli-hub preview`, `cli-hub review`, or `cli-hub open-preview`+aliases in the current command surface.## FreeCAD-Specific Preview Mechanism Progressdiff --git a/docs/PREVIEW_PROGRESS.md b/docs/PREVIEW_PROGRESS.mdindex 765549350..c83ff74c1 100644--- a/docs/PREVIEW_PROGRESS.md+++ b/docs/PREVIEW_PROGRESS.md@@ -1,6 +1,6 @@# Preview Progress-Last updated: 2026-04-22 UTC+Last updated: 2026-04-23 UTCThis file tracks the current state of the preview work on the dedicated previewbranch and records the next design direction for live popup preview windows.@@ -125,10 +125,11 @@ What was added:- real turntable motion video- polished build-story video with turntable ending- `cli-hub` live viewer surface:- - `preview inspect` now understands live sessions- - `preview html` now renders live-session HTML- - `preview watch` now serves a live session over localhost with auto-refresh- - `preview open` now opens bundles or live sessions in a separate window+ - `previews inspect` now understands live sessions+ - `previews html` now renders bundle and live-session HTML+ - `previews watch` now serves a live session over localhost with auto-refresh+ - `previews open` now opens bundles or live sessions in a separate window+ - live pages and inspect output now consume `trajectory.json` when presentThe live split now looks like this:@@ -596,18 +597,20 @@ This adds one key capability:- the live window can watch one stable path while harnesses keep publishing newpreview states-## Proposed Command Surface+## Canonical Command Surface### `cli-hub`-Add these commands:+The current canonical viewer commands are:-- `cli-hub preview open <bundle-or-session>`- - open a preview in a separate window if possible-- `cli-hub preview watch <session-dir>`+- `cli-hub previews inspect <bundle-or-session>`+ - inspect an existing bundle or live session in text or JSON+- `cli-hub previews html <bundle-or-session>`+ - render HTML for a bundle or live session+- `cli-hub previews watch <session-dir>`- run a live preview viewer against a session-- `cli-hub preview serve <bundle-or-session>`- - start a local HTTP server for a preview viewer+- `cli-hub previews open <bundle-or-session>`+ - open a bundle or live session in a browser windowUseful flags:@@ -632,7 +635,8 @@ Behavior:- `start` creates a live session and optionally opens the viewer window- `push` publishes a new preview state into the session- `stop` closes the session cleanly-- `status` reports session path, viewer URL, and last update metadata+- `status` reports session path, current bundle metadata, and compact+ `trajectory_summary` for agent useThe first implementation can make `push` explicit.@@ -747,7 +751,7 @@ Goal:Deliverables:-- `cli-hub preview open`+- `cli-hub previews open`- browser app-mode launch on Linux/Ubuntu- headless fallback to URL output@@ -762,8 +766,9 @@ Goal:Deliverables:- `session.json`-- `current/` + `history/`-- `cli-hub preview watch`+- `trajectory.json`+- `current/`+- `cli-hub previews watch`- polling-based live reload### Phase 3: Harness Integration@@ -794,8 +799,8 @@ This should be opt-in, because automatic preview generation can be expensive.The next concrete move should be:-- implement `cli-hub preview open`-- implement `cli-hub preview watch`+- keep `cli-hub previews open`+- keep `cli-hub previews watch`- use browser-window popup as the default Linux/Ubuntu strategyReason:diff --git a/docs/PREVIEW_PROTOCOL.md b/docs/PREVIEW_PROTOCOL.mdindex f2940792f..0db91b026 100644--- a/docs/PREVIEW_PROTOCOL.md+++ b/docs/PREVIEW_PROTOCOL.md@@ -1,5 +1,7 @@# Preview Protocol+Last updated: 2026-04-23 UTC+This document proposes a minimal, cross-harness protocol for previewingintermediate results in CLI-Anything workflows.@@ -74,13 +76,17 @@ The protocol has three layers:1. Harness layerThe harness generates real preview artifacts and writes a `Preview Bundle`.2. Viewer layer- `cli-hub` reads any compliant bundle and renders a generic inspection view.+ `cli-hub previews ...` reads any compliant bundle or live session and+ renders a generic inspection view.3. Host/runtime layerAn agent host may decide to attach selected bundle artifacts back into modelcontext, but this is outside the harness itself.The central object is the `Preview Bundle`.+For live preview workflows, the stable object is the `Live Session`, with an+append-only `trajectory.json` beside it.+## Preview BundleA preview bundle is a directory with a small, stable layout:@@ -258,6 +264,128 @@ Recommended shape:The viewer should render `headline`, `facts`, and `warnings` first.+## Live Session++Live preview adds two more protocol objects:++1. `session.json`+ Mutable session head. Tracks the current bundle, viewer commands, and live+ poller state.+2. `trajectory.json`+ Append-only history of command-to-preview publishes for the session. This is+ the permanent replay object.++Recommended live session layout:++```text+<session_dir>/+ session.json+ trajectory.json+ current -> ../quick/<bundle_id>/+```++### Why `trajectory.json` exists++`bundle_dir` is a single immutable snapshot, not the stable history object.+For the same working project:++- a bundle directory may be reused if the cache key is unchanged+- a new bundle directory is created whenever the source fingerprint, recipe,+ options, harness version, or protocol version changes++So agents and host UIs should not treat `bundle_dir` as the permanent handle+for the whole build. The stable handle for live preview is:++- `session_dir` for the current channel+- `trajectory.json` for the full publish history++### `session.json` responsibilities++Recommended fields:++| Field | Type | Notes |+|---|---|---|+| `protocol_version` | string | Start with `preview-live/v1` |+| `software` | string | Harness name |+| `recipe` | string | Active live recipe |+| `status` | string | `active` or `stopped` |+| `current_bundle_id` | string | Current head bundle |+| `current_bundle_dir` | string | Absolute current bundle path |+| `current_manifest_path` | string | Absolute manifest path |+| `current_summary_path` | string | Absolute summary path |+| `current_step_id` | string | Current trajectory step id |+| `latest_command` | string | Latest publish command for agent/UI inspection |+| `latest_publish_reason` | string | Latest publish reason |+| `trajectory_path` | string | Relative path, usually `trajectory.json` |+| `trajectory_step_count` | integer | Total trajectory steps |+| `history` | array | Short recent-bundles list for compatibility |++`history` remains useful for quick inspection, but it is not the authoritative+replay log.++### `trajectory.json` schema++Recommended top-level shape:++```json+{+ "protocol_version": "preview-trajectory/v1",+ "software": "blender",+ "recipe": "quick",+ "session_name": "orbital-relay-drone-blend-cli-48261b51-quick",+ "project_path": "/work/scene.blend-cli.json",+ "project_name": "scene.blend-cli.json",+ "created_at": "2026-04-23T10:10:00Z",+ "updated_at": "2026-04-23T10:12:41Z",+ "step_count": 3,+ "current_step_id": "step-0003",+ "steps": [+ {+ "step_id": "step-0001",+ "step_index": 1,+ "command": "cli-anything-blender --project scene.blend-cli.json preview live start --recipe quick",+ "command_started_at": "2026-04-23T10:10:00Z",+ "command_finished_at": "2026-04-23T10:10:07Z",+ "publish_reason": "live-start",+ "source_fingerprint": "sha256:...",+ "bundle_id": "20260423T101007Z_deadbeef_quick",+ "bundle_dir": "/work/.cli-anything/previews/blender/quick/20260423T101007Z_deadbeef_quick",+ "manifest_path": "/work/.cli-anything/previews/blender/quick/20260423T101007Z_deadbeef_quick/manifest.json",+ "summary_path": "/work/.cli-anything/previews/blender/quick/20260423T101007Z_deadbeef_quick/summary.json",+ "status": "ok",+ "cached": false,+ "stage_label": "service-rig"+ }+ ]+}+```++Minimum recommended step fields:++- `step_id`+- `command`+- `command_started_at`+- `command_finished_at`+- `publish_reason`+- `source_fingerprint`+- `bundle_id`+- `bundle_dir`+- `manifest_path`+- `summary_path`++Optional but useful:++- `stage_label`+- `note`+- `status`+- `cached`++This gives viewers enough structure to render:++- command stream on the left+- matching preview state on the right+- arbitrary rewind to previous build checkpoints+## Artifact DescriptorEach artifact entry in `manifest.json` should use relative paths and carry enough@@ -383,6 +511,59 @@ Returns the latest successful bundle for the current project and optional recipeRecommended for domains with meaningful before/after or event/event comparison.Not every harness must implement this in v1, but the protocol supports it.+### `preview live start`++Starts a live preview session and publishes the initial bundle.++Recommended options:++- `--recipe <name>`+- `--root-dir <path>`+- `--poll-ms <int>`+- `--mode manual|poll`+- `--source-poll-ms <int>`+- `--open`++### `preview live push`++Publishes a fresh bundle into an existing live session.++Use this when:++- the harness supports manual live refresh+- the agent wants an explicit command-to-preview checkpoint+- the source did not change enough to justify poll mode++### `preview live status`++Returns the current live session state without rendering a new bundle.++This command exists for agents. It should answer:++- is there a live session for this project and recipe+- where is `session.json`+- what is the current bundle+- what is the latest publish reason+- where is `trajectory.json`++For `--json`, implementations SHOULD include:++- `_session_dir`+- `_session_path`+- `_trajectory_path`+- `current_bundle_id`+- `current_bundle_dir`+- `current_step_id`+- `latest_publish_reason`+- `trajectory_summary`++`trajectory_summary` should be a compact in-band summary so agents do not need a+second file read just to understand the latest few steps.++### `preview live stop`++Stops a live preview session without deleting published artifacts.+## Caching Rules`preview capture` may return a cached bundle if:@@ -426,12 +607,19 @@ logic. It only needs bundle-aware preview logic.## Generic Viewer-The generic viewer should live in `cli-hub`.+The generic viewer lives in `cli-hub`.++The split is intentional:++- `cli-anything-<software> preview ...` publishes preview state+- `cli-hub previews ...` inspects existing preview state-Minimal viewer commands for v1:+Canonical viewer commands:-- `cli-hub preview inspect <bundle-or-manifest>`-- `cli-hub preview html <bundle-or-manifest> [-o output.html]`+- `cli-hub previews inspect <bundle-or-session>`+- `cli-hub previews html <bundle-or-session> [-o output.html]`+- `cli-hub previews watch <session-dir> [--open] [--poll-ms 1500]`+- `cli-hub previews open <bundle-or-session>``inspect` prints:@@ -439,6 +627,7 @@ Minimal viewer commands for v1:- source identity- summary headline/facts/warnings- artifact table+- trajectory summary when available`html` writes a static HTML page that:@@ -446,6 +635,14 @@ Minimal viewer commands for v1:- renders image galleries from `hero` and `gallery` artifacts- embeds playable `<video>` elements for `preview-clip`- links to JSON artifacts for detailed inspection+- renders session history from `trajectory.json` when present++`watch` serves a live session over localhost and auto-refreshes the page.++`open` opens either:++- a generated HTML file for a bundle+- a browser-backed live session watcher for `session_dir`This viewer is intentionally generic. It does not know what Shotcut, FreeCAD,Blender, or RenderDoc "mean". It only knows bundle roles and artifact kinds.@@ -522,9 +719,9 @@ Concrete file plan:Concrete behavior:-- `cli-hub preview inspect <bundle>`+- `cli-hub previews inspect <bundle>`prints manifest metadata, summary, and artifact inventory-- `cli-hub preview html <bundle> -o page.html`+- `cli-hub previews html <bundle> -o page.html`writes a static HTML page with summary + gallery + video embeddingWhy this works:@@ -611,7 +808,7 @@ Why this works:Acceptance criteria:- both harnesses emit valid bundles for a real project-- `cli-hub preview inspect` can read them+- `cli-hub previews inspect` can read them- the HTML viewer shows the gallery and preview clip without app-specific codeOut of scope:diff --git a/docs/scripts/blender_orbital_relay_drone_demo.py b/docs/scripts/blender_orbital_relay_drone_demo.pyindex b85380769..11179aaca 100644--- a/docs/scripts/blender_orbital_relay_drone_demo.py+++ b/docs/scripts/blender_orbital_relay_drone_demo.py@@ -1,5 +1,14 @@#!/usr/bin/env python3-"""Build a clear Blender orbital relay drone demo with live previews and motion."""+"""Build a clear Blender orbital relay drone demo with live previews and motion.++Outputs:++- real staged preview bundles+- a persisted live `session.json`+- append-only `trajectory.json`+- `live.html` rendered through `cli-hub previews html`+- a final still render and turntable video+"""from __future__ import annotations@@ -117,10 +126,10 @@ def _render_live_html(session_dir: Path, output_path: Path) -> str | None:if not hub:return Noneoutput_path.parent.mkdir(parents=True, exist_ok=True)- command = [hub, "preview", "html", str(session_dir), "-o", str(output_path)]+ command = [hub, "previews", "html", str(session_dir), "-o", str(output_path)]result = subprocess.run(command, capture_output=True, text=True, check=False)if result.returncode != 0:- raise RuntimeError(f"cli-hub preview html failed:\n{result.stderr[-1200:]}")+ raise RuntimeError(f"cli-hub previews html failed:\n{result.stderr[-1200:]}")return str(output_path)@@ -153,7 +162,7 @@ def _configure_scene(project: Dict) -> None:add_light(project, light_type="POINT", name="BeaconBounce", location=[0.0, 0.0, 3.35], power=180)-def _build_stage_01_foundation(project: Dict) -> None:+def _build_stage_00_launch_platform(project: Dict) -> None:add_object(project, mesh_type="plane", name="DeckFloor", mesh_params={"size": 22.0}, location=[0, 0, 0])add_object(project,@@ -188,6 +197,8 @@ def _build_stage_01_foundation(project: Dict) -> None:)add_modifier(project, "bevel", _object_index(project, "LiftColumn"), params={"width": 0.02, "segments": 2})++def _build_stage_01_hull_blockout(project: Dict) -> None:add_object(project, mesh_type="empty", name="DroneRoot", location=[0, 0, 0], rotation=[0, 0, 18])add_object(project,@@ -234,7 +245,7 @@ def _build_stage_01_foundation(project: Dict) -> None:add_modifier(project, "bevel", _object_index(project, "ServiceCabin"), params={"width": 0.03, "segments": 2})-def _build_stage_02_power_and_wings(project: Dict) -> None:+def _build_stage_02_wing_structure(project: Dict) -> None:add_object(project,mesh_type="cube",@@ -259,6 +270,9 @@ def _build_stage_02_power_and_wings(project: Dict) -> None:rotation=[0, 0, -18],scale=[0.56, 0.08, 0.06],)+++def _build_stage_03_solar_arrays(project: Dict) -> None:add_object(project,mesh_type="cube",@@ -305,6 +319,9 @@ def _build_stage_02_power_and_wings(project: Dict) -> None:_object_index(project, "SolarRibRight"),params={"count": 7, "relative_offset_x": 1.95, "relative_offset_y": 0.0, "relative_offset_z": 0.0},)+++def _build_stage_04_propulsion(project: Dict) -> None:add_object(project,mesh_type="cube",@@ -346,7 +363,7 @@ def _build_stage_02_power_and_wings(project: Dict) -> None:)-def _build_stage_03_payload_and_rig(project: Dict) -> None:+def _build_stage_05_sensor_payload(project: Dict) -> None:add_object(project, mesh_type="empty", name="DishPivot", location=[0.62, 0, 4.18])add_object(project,@@ -389,6 +406,9 @@ def _build_stage_03_payload_and_rig(project: Dict) -> None:scale=[0.11, 0.11, 0.11],mesh_params={"radius": 1.0, "segments": 18, "rings": 10},)+++def _build_stage_06_service_rig(project: Dict) -> None:add_object(project,mesh_type="cylinder",@@ -540,7 +560,18 @@ def _add_motion(project: Dict) -> None:set_current_frame(project, 1)-def _capture_stage(session: Session, stage_name: str, stage_log: List[Dict], preview_root: Path, started: bool) -> bool:+def _capture_stage(+ session: Session,+ stage_name: str,+ stage_log: List[Dict],+ preview_root: Path,+ started: bool,+ *,+ label: str,+ story: str,+ display_cmd: str,+ duration_s: float,+) -> bool:if not started:live_payload = preview_mod.live_start(session,@@ -570,20 +601,15 @@ def _capture_stage(session: Session, stage_name: str, stage_log: List[Dict], pre"session_path": live_payload.get("_session_path"),"current_manifest_path": live_payload.get("current_manifest_path"),"current_bundle_dir": live_payload.get("current_bundle_dir"),+ "label": label,+ "story": story,+ "display_cmd": display_cmd,+ "duration_s": duration_s,})return True-def _build_demo_scene(project: Dict) -> None:- _build_stage_01_foundation(project)- _build_stage_02_power_and_wings(project)- _build_stage_03_payload_and_rig(project)- _assign_materials(project)- _rig_parents(project)- _add_motion(project)--def build_demo(output_dir: Path, use_live_preview: bool = True) -> Dict:output_dir.mkdir(parents=True, exist_ok=True)preview_root = output_dir / "live-root"@@ -602,37 +628,150 @@ def build_demo(output_dir: Path, use_live_preview: bool = True) -> Dict:stage_log: List[Dict] = []live_started = False- _build_stage_01_foundation(project)+ _build_stage_00_launch_platform(project)_assign_materials(project)- print("[demo] Stage 01: chassis")+ print("[demo] Stage 00: launch platform")save_scene(project, str(project_path))session.set_project(project, str(project_path))if use_live_preview:- live_started = _capture_stage(session, "01_chassis", stage_log, preview_root, live_started)+ live_started = _capture_stage(+ session,+ "00_launch_platform",+ stage_log,+ preview_root,+ live_started,+ label="Build launch platform",+ story="Deck floor, display base, raised launch pad, stripe ring, and center lift column.",+ display_cmd="add DeckFloor / DisplayBase / LaunchPad / PadStripeRing / LiftColumn",+ duration_s=0.9,+ )++ _build_stage_01_hull_blockout(project)+ _assign_materials(project)+ print("[demo] Stage 01: hull blockout")+ save_scene(project, str(project_path))+ if use_live_preview:+ live_started = _capture_stage(+ session,+ "01_hull_blockout",+ stage_log,+ preview_root,+ live_started,+ label="Block out the hull and docking silhouette",+ story="Drone root, main hull cylinder, nose cone, bridge pod, docking ring, and service cabin.",+ display_cmd="add DroneRoot / HullCore / NoseCone / BridgePod / DockRing / ServiceCabin",+ duration_s=1.0,+ )++ _build_stage_02_wing_structure(project)+ _assign_materials(project)+ print("[demo] Stage 02: wing structure")+ save_scene(project, str(project_path))+ if use_live_preview:+ live_started = _capture_stage(+ session,+ "02_wing_structure",+ stage_log,+ preview_root,+ live_started,+ label="Add wing spar and panel arms",+ story="The drone starts reading as a spacecraft once the lateral wing spar and panel hinges appear.",+ display_cmd="add WingSpar / PanelArmLeft / PanelArmRight",+ duration_s=0.8,+ )- _build_stage_02_power_and_wings(project)+ _build_stage_03_solar_arrays(project)_assign_materials(project)- print("[demo] Stage 02: power and wings")+ print("[demo] Stage 03: solar arrays")save_scene(project, str(project_path))if use_live_preview:- live_started = _capture_stage(session, "02_power_and_wings", stage_log, preview_root, live_started)+ live_started = _capture_stage(+ session,+ "03_solar_arrays",+ stage_log,+ preview_root,+ live_started,+ label="Add solar panels and rib arrays",+ story="Blue panel slabs and rib arrays turn the side arms into readable power modules.",+ display_cmd="add SolarPanelLeft/Right / array SolarRibLeft/Right",+ duration_s=0.9,+ )- _build_stage_03_payload_and_rig(project)+ _build_stage_04_propulsion(project)+ _assign_materials(project)+ print("[demo] Stage 04: propulsion")+ save_scene(project, str(project_path))+ if use_live_preview:+ live_started = _capture_stage(+ session,+ "04_propulsion",+ stage_log,+ preview_root,+ live_started,+ label="Add engine block and thruster pack",+ story="The rear engine block and clustered nozzles complete the propulsion silhouette.",+ display_cmd="add EngineBlock / thrusters / nozzle cones",+ duration_s=0.9,+ )++ _build_stage_05_sensor_payload(project)+ _assign_materials(project)+ print("[demo] Stage 05: sensor payload")+ save_scene(project, str(project_path))+ if use_live_preview:+ live_started = _capture_stage(+ session,+ "05_sensor_payload",+ stage_log,+ preview_root,+ live_started,+ label="Add radar dish and navigation payloads",+ story="Dish pivot, radar plate, beacon core, and nav lights add the recognizable inspection payloads.",+ display_cmd="add DishPivot / SensorMast / RadarDish / BeaconCore / NavLightLeft/Right",+ duration_s=0.9,+ )++ _build_stage_06_service_rig(project)_assign_materials(project)_rig_parents(project)- print("[demo] Stage 03: payload and rig")+ print("[demo] Stage 06: service rig")save_scene(project, str(project_path))if use_live_preview:- live_started = _capture_stage(session, "03_payload_and_rig", stage_log, preview_root, live_started)+ live_started = _capture_stage(+ session,+ "06_service_rig",+ stage_log,+ preview_root,+ live_started,+ label="Add service arm and parenting rig",+ story="Service arm, comm fin, and object parenting wire the drone into an assembled, animatable artifact.",+ display_cmd="add ServiceArmBase / ServiceArmReach / ServiceTool / CommFin / set parent hierarchy",+ duration_s=1.0,+ )_add_motion(project)- print("[demo] Stage 04: motion ready")+ print("[demo] Stage 07: motion ready")+ set_current_frame(project, 18)save_scene(project, str(project_path))if use_live_preview:- live_started = _capture_stage(session, "04_motion_ready", stage_log, preview_root, live_started)+ live_started = _capture_stage(+ session,+ "07_motion_ready",+ stage_log,+ preview_root,+ live_started,+ label="Author hover, spin, and beacon motion",+ story="Hover motion, dish spin, ring rotation, and beacon pulses prepare the final presentation state.",+ display_cmd="add_keyframe DroneRoot / DishPivot / DockRing / BeaconCore / NavLights",+ duration_s=1.0,+ )+ set_current_frame(project, 1)+ save_scene(project, str(project_path))live_payload = preview_mod.live_stop(session, recipe="quick", root_dir=str(preview_root))live_html = _render_live_html(Path(live_payload["_session_dir"]), output_dir / "live.html")else:+ set_current_frame(project, 1)+ save_scene(project, str(project_path))live_payload = Nonelive_html = None@@ -683,8 +822,8 @@ def main() -> None:parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("--output-dir",- default="/root/preview-artifacts/20260422/blender-orbital-relay-drone-v2",- help="Directory for the generated scene, preview bundles, final render, and motion video.",+ default="/root/preview-artifacts/20260422/blender-orbital-relay-drone-v6",+ help="Directory for the generated scene, preview bundles, live session, trajectory.json, final render, and motion video.",)parser.add_argument("--no-live-preview",diff --git a/docs/scripts/blender_preview_story_demo.py b/docs/scripts/blender_preview_story_demo.pyindex 4dc14b855..cbb2d0b19 100644--- a/docs/scripts/blender_preview_story_demo.py+++ b/docs/scripts/blender_preview_story_demo.py@@ -1,5 +1,11 @@#!/usr/bin/env python3-"""Render a polished Blender build-story video from a real preview demo run."""+"""Render a polished Blender build-story video from a real preview demo run.++The source build run must already contain real preview bundles, a persisted live+session, and a `trajectory.json`. This script turns that trajectory into a+split-screen story video, then appends the real turntable ending from the+source run.+"""from __future__ import annotations@@ -35,6 +41,10 @@ LEFT_W = STYLE.LEFT_WFPS = STYLE.FPSCOLORS = STYLE.COLORSHOLD_TAIL_S = 1.4+BASELINE_START_S = 0.55+PREVIEW_SWITCH_LATENCY_S = 0.0+FINAL_STILL_STEP_S = 0.85+TURNTABLE_STEP_S = 0.7DISPLAY_FONT_PATH = STYLE.DISPLAY_FONT_PATHSANS_FONT_PATH = STYLE.SANS_FONT_PATH@@ -52,125 +62,21 @@ def write_json(path: Path, payload: Dict[str, Any]) -> Path:return path-def _stage_title(stage: str) -> str:- labels = {- "01_chassis": "Stage 01 Β· Chassis Blockout",- "02_power_and_wings": "Stage 02 Β· Power + Wings",- "03_payload_and_rig": "Stage 03 Β· Payload + Rig",- "04_motion_ready": "Stage 04 Β· Motion Ready",- }- return labels.get(stage, stage.replace("_", " "))+def _stage_title(stage: Dict[str, Any]) -> str:+ stage_id = str(stage.get("stage") or "stage").strip()+ label = str(stage.get("label") or stage_id.replace("_", " ")).strip()+ prefix = stage_id.split("_", 1)[0]+ if prefix.isdigit():+ return f"Stage {prefix} Β· {label}"+ return label-def _stage_story(stage: str) -> str:- stories = {- "01_chassis": "Display plinth, main hull, bridge pod, docking ring, and service cabin.",- "02_power_and_wings": "Wing spar, solar panel arms, panel rib arrays, engine block, and thruster pack.",- "03_payload_and_rig": "Radar dish, nav beacons, service arm, comm fin, and drone-root parenting rig.",- "04_motion_ready": "Hover motion, dish spin, beacon pulse, and the final preview-ready presentation state.",- }- return stories.get(stage, stage.replace("_", " "))+def _stage_story(stage: Dict[str, Any]) -> str:+ return str(stage.get("story") or stage.get("label") or stage.get("stage") or "Build stage").strip()-def _command_specs(project_path: Path, live_root: Path, final_render_path: Path, turntable_path: Path) -> List[Dict[str, Any]]:- return [- {- "id": "scene-bootstrap",- "label": "Create preview scene",- "display_cmd": "create_scene(name='orbital-relay-drone', profile='preview')",- "duration_s": 0.8,- },- {- "id": "scene-setup",- "label": "Configure camera, lights, and materials",- "display_cmd": "_configure_scene(project) + _add_materials(project)",- "duration_s": 1.0,- },- {- "id": "stage01-build",- "label": "Block out the hull and docking silhouette",- "display_cmd": "add DeckFloor / DisplayBase / LaunchPad / HullCore / NoseCone / DockRing / ServiceCabin",- "duration_s": 1.1,- },- {- "id": "stage01-preview",- "label": "Capture stage 01 live preview",- "display_cmd": f"cli-anything-blender --project {project_path} preview live start --recipe quick --mode manual --root-dir {live_root}",- "duration_s": 0.9,- },- {- "id": "stage02-spar",- "label": "Add wing spar and panel arms",- "display_cmd": "add WingSpar + PanelArmLeft + PanelArmRight",- "duration_s": 0.8,- },- {- "id": "stage02-panels",- "label": "Add solar panels and rib arrays",- "display_cmd": "add SolarPanelLeft/Right + array SolarRibLeft/Right",- "duration_s": 0.9,- },- {- "id": "stage02-engine",- "label": "Add engine block and thruster pack",- "display_cmd": "add EngineBlock + thrusters + nozzle cones",- "duration_s": 1.0,- },- {- "id": "stage02-preview",- "label": "Capture stage 02 live preview",- "display_cmd": f"cli-anything-blender --project {project_path} preview live push --recipe quick --root-dir {live_root} --publish-reason stage:02_power_and_wings",- "duration_s": 0.8,- },- {- "id": "stage03-sensors",- "label": "Add radar dish and navigation payloads",- "display_cmd": "add DishPivot + SensorMast + RadarDish + NavLightLeft/Right",- "duration_s": 0.9,- },- {- "id": "stage03-detail",- "label": "Add service arm and comm fin",- "display_cmd": "add ServiceArmBase + ServiceArmReach + ServiceTool + CommFin",- "duration_s": 0.9,- },- {- "id": "stage03-rig",- "label": "Wire DroneRoot parenting hierarchy",- "display_cmd": "set parent -> DroneRoot / DishPivot / rotating payloads",- "duration_s": 0.7,- },- {- "id": "stage03-preview",- "label": "Capture stage 03 live preview",- "display_cmd": f"cli-anything-blender --project {project_path} preview live push --recipe quick --root-dir {live_root} --publish-reason stage:03_payload_and_rig",- "duration_s": 0.8,- },- {- "id": "motion-authoring",- "label": "Author hover, spin, and beacon motion",- "display_cmd": "add_keyframe(DroneRoot, DishPivot, DockRing, BeaconCore, NavLights)",- "duration_s": 1.0,- },- {- "id": "stage04-preview",- "label": "Capture stage 04 live preview",- "display_cmd": f"cli-anything-blender --project {project_path} preview live push --recipe quick --root-dir {live_root} --publish-reason stage:04_motion_ready",- "duration_s": 0.8,- },- {- "id": "final-still",- "label": "Render final hero still",- "display_cmd": f"render_scene(..., output='{final_render_path}')",- "duration_s": 1.1,- },- {- "id": "turntable",- "label": "Encode turntable motion video",- "display_cmd": f"ffmpeg -> {turntable_path}",- "duration_s": 0.9,- },- ]+def _stage_display_cmd(stage: Dict[str, Any]) -> str:+ return str(stage.get("display_cmd") or f"publish {stage.get('stage') or 'stage'}").strip()def build_trajectory(build_manifest_path: Path, output_dir: Path) -> Dict[str, Any]:@@ -179,38 +85,33 @@ def build_trajectory(build_manifest_path: Path, output_dir: Path) -> Dict[str, Alive_root = Path(build_manifest["preview_root"]).expanduser().resolve()final_render_path = Path(build_manifest["final_render"]["output"]).expanduser().resolve()turntable_path = Path(build_manifest["motion"]["video"]["video_path"]).expanduser().resolve()+ live_session = build_manifest.get("live_session") or {}+ stage_log = build_manifest.get("stage_log") or []+ if not stage_log:+ raise RuntimeError(f"No stage_log entries found in {build_manifest_path}")- command_specs = _command_specs(project_path, live_root, final_render_path, turntable_path)commands: List[Dict[str, Any]] = []t = 0.0- command_index_by_id: Dict[str, int] = {}- for index, spec in enumerate(command_specs):- duration_s = float(spec["duration_s"])++ def add_command(cmd_id: str, label: str, display_cmd: str, duration_s: float) -> Dict[str, Any]:+ nonlocal tcommand = {- "index": index,- "id": spec["id"],- "label": spec["label"],- "display_cmd": spec["display_cmd"],- "duration_s": duration_s,+ "index": len(commands),+ "id": cmd_id,+ "label": label,+ "display_cmd": display_cmd,+ "duration_s": float(duration_s),"timeline_start_s": round(t, 3),- "timeline_end_s": round(t + duration_s, 3),+ "timeline_end_s": round(t + float(duration_s), 3),"stdout": "","stderr": "","returncode": 0,}commands.append(command)- command_index_by_id[spec["id"]] = index- t += duration_s-- preview_events: List[Dict[str, Any]] = []- preview_step_map = {- "01_chassis": "stage01-preview",- "02_power_and_wings": "stage02-preview",- "03_payload_and_rig": "stage03-preview",- "04_motion_ready": "stage04-preview",- }+ t += float(duration_s)+ return command- for sequence_index, stage in enumerate(build_manifest["stage_log"], start=1):+ def bundle_payload(stage: Dict[str, Any]) -> Dict[str, Any]:bundle_dir = Path(stage["current_bundle_dir"]).expanduser().resolve()manifest_path = Path(stage["current_manifest_path"]).expanduser().resolve()summary_path = bundle_dir / "summary.json"@@ -220,43 +121,92 @@ def build_trajectory(build_manifest_path: Path, output_dir: Path) -> Dict[str, Aitem["artifact_id"]: str((bundle_dir / item["path"]).resolve())for item in manifest.get("artifacts", [])}- stage_id = stage["stage"]- cmd_id = preview_step_map[stage_id]- step_index = command_index_by_id[cmd_id]- step = commands[step_index]- ready_t = round(float(step["timeline_end_s"]) + 0.2, 3)+ return {+ "bundle_id": manifest["bundle_id"],+ "bundle_dir": str(bundle_dir),+ "manifest_path": str(manifest_path),+ "summary_path": str(summary_path),+ "artifacts": artifacts,+ "summary": summary,+ }++ baseline_command = add_command(+ "live-baseline",+ "Bring live preview online from the launch-platform baseline",+ str(+ live_session.get("start_command")+ or f"cli-anything-blender --project {project_path} preview live start --recipe quick --mode manual --root-dir {live_root}"+ ),+ BASELINE_START_S,+ )++ preview_events: List[Dict[str, Any]] = []+ baseline_stage = stage_log[0]+ preview_events.append(+ {+ "sequence_index": 1,+ "step_index": baseline_command["index"],+ "step_id": baseline_command["id"],+ "step_label": baseline_command["label"],+ "stage_id": baseline_stage["stage"],+ "stage_title": _stage_title(baseline_stage),+ "stage_story": _stage_story(baseline_stage),+ "timeline_ready_s": 0.0,+ "latency_s": 0.0,+ "bundle_count": int(baseline_stage.get("bundle_count") or 1),+ "publish_reason": f"stage:{baseline_stage['stage']}",+ "session_path": baseline_stage["session_path"],+ "session_dir": str(Path(baseline_stage["session_path"]).expanduser().resolve().parent),+ "copied_bundle": bundle_payload(baseline_stage),+ }+ )++ for sequence_index, stage in enumerate(stage_log[1:], start=2):+ command = add_command(+ f"stage-{stage['stage']}",+ str(stage.get("label") or stage["stage"]).strip(),+ _stage_display_cmd(stage),+ float(stage.get("duration_s") or 0.9),+ )+ ready_t = round(float(command["timeline_end_s"]) + PREVIEW_SWITCH_LATENCY_S, 3)preview_events.append({"sequence_index": sequence_index,- "step_index": step_index,- "step_id": cmd_id,- "step_label": step["label"],- "stage_id": stage_id,- "stage_title": _stage_title(stage_id),- "stage_story": _stage_story(stage_id),+ "step_index": command["index"],+ "step_id": command["id"],+ "step_label": command["label"],+ "stage_id": stage["stage"],+ "stage_title": _stage_title(stage),+ "stage_story": _stage_story(stage),"timeline_ready_s": ready_t,- "latency_s": 0.2,+ "latency_s": PREVIEW_SWITCH_LATENCY_S,"bundle_count": int(stage["bundle_count"]),- "publish_reason": f"stage:{stage_id}",+ "publish_reason": f"stage:{stage['stage']}","session_path": stage["session_path"],"session_dir": str(Path(stage["session_path"]).expanduser().resolve().parent),- "copied_bundle": {- "bundle_id": manifest["bundle_id"],- "bundle_dir": str(bundle_dir),- "manifest_path": str(manifest_path),- "summary_path": str(summary_path),- "artifacts": artifacts,- "summary": summary,- },+ "copied_bundle": bundle_payload(stage),})+ add_command(+ "final-still",+ "Render final hero still",+ f"render_scene(..., output='{final_render_path}')",+ FINAL_STILL_STEP_S,+ )+ add_command(+ "turntable",+ "Package the real turntable ending",+ f"ffmpeg -> {turntable_path}",+ TURNTABLE_STEP_S,+ )+trajectory = {"protocol": "blender-preview-trajectory/v1","created_at": datetime.now(timezone.utc).isoformat(),"scenario": "orbital-relay-drone","scenario_title": "Orbital Relay Drone",- "scenario_subtitle": "agent-built Blender drone with live preview and a real turntable ending",+ "scenario_subtitle": "launch-platform baseline, step-aligned real preview checkpoints, then a real turntable ending","build_manifest_path": str(build_manifest_path.resolve()),"project_path": str(project_path),"live_root": str(live_root),@@ -265,8 +215,8 @@ def build_trajectory(build_manifest_path: Path, output_dir: Path) -> Dict[str, A"commands": commands,"preview_events": preview_events,"notes": [- "The left panel is a scripted agent build trace derived from the actual Blender demo run.",- "The preview monitor uses real Blender quick-preview bundles captured during that run.",+ "The first preview shown on the right is the real stage-00 launch-platform bundle, used as a live baseline instead of leaving the monitor empty.",+ "Every later preview switch is keyed from the matching real stage_log entry, so command completion and preview refresh stay aligned.","The ending appends the existing real turntable video from the same run.",],}@@ -465,7 +415,7 @@ def draw_trace_panel(card_y += card_height + card_gap- footer = "Structured build steps derived from the real Blender demo script; preview captures remain real artifacts."+ footer = "Step-aligned build trace driven by the real Blender stage_log; preview captures remain real artifacts."draw.text((x0 + 24, y1 - 28), footer, fill=COLORS["terminal_muted"], font=fonts["small"])@@ -511,6 +461,7 @@ def draw_preview_panel() -> None:x0, y0, x1, y1 = areadraw = ImageDraw.Draw(canvas)+ snapshot = progress_snapshot(trajectory, t_real)STYLE._draw_panel(canvas, area, radius=30, fill=COLORS["panel"], outline=COLORS["panel_line"], accent=COLORS["accent_warm"])draw.text((x0 + 24, y0 + 24), "Preview Monitor", fill=COLORS["white"], font=fonts["title"])STYLE._draw_chip(@@ -532,6 +483,9 @@ def draw_preview_panel(current = event["copied_bundle"]summary = current.get("summary") or {}facts = summary.get("facts") or {}+ previous_event = None+ if event["sequence_index"] > 1:+ previous_event = trajectory["preview_events"][event["sequence_index"] - 2]stage_area = (x0 + 20, y0 + 96, x1 - 260, y1 - 20)info_area = (x1 - 244, y0 + 96, x1 - 20, y1 - 20)@@ -550,11 +504,16 @@ def draw_preview_panel(label="WORKBENCH",fonts=fonts,)+ secondary_label = "FINAL STILL"+ secondary_img = trajectory.get("final_render")+ if previous_event is not None:+ secondary_label = "PREV HERO"+ secondary_img = previous_event["copied_bundle"]["artifacts"].get("hero")_paste_preview_card(canvas,(stage_area[0] + thumb_w + 12, thumb_y, stage_area[2], thumb_y + thumb_h),- img_path=trajectory.get("final_render"),- label="FINAL STILL",+ img_path=secondary_img,+ label=secondary_label,fonts=fonts,)@@ -562,8 +521,8 @@ def draw_preview_panel(meta_lines = [("STAGE", event["stage_title"]),("BUNDLE", STYLE._trim_middle(current["bundle_id"], 18)),- ("OBJECTS", str(facts.get("object_count", "n/a"))),- ("MATERIALS", str(facts.get("material_count", "n/a"))),+ ("CAUSE", STYLE._trim_middle(str(event.get("publish_reason") or "n/a"), 18)),+ ("LATENCY", f"{event.get('latency_s', 0.0):.2f}s"),("FRAME", str(facts.get("frame_current", "n/a"))),("STREAM", f"{event['sequence_index']:02d}/{len(trajectory['preview_events']):02d}"),]@@ -582,7 +541,10 @@ def draw_preview_panel(meta_y += 74story_lines = STYLE._wrap_trimmed(event["stage_story"], width_chars=24, max_lines=5)- draw.text((info_area[0] + 16, info_area[3] - 176), "Stage note", fill=COLORS["white"], font=fonts["body"])+ note_title = "Stage note"+ if snapshot["active_cmd"] and snapshot["active_cmd"]["id"] in {"final-still", "turntable"}:+ note_title = "Handoff note"+ draw.text((info_area[0] + 16, info_area[3] - 176), note_title, fill=COLORS["white"], font=fonts["body"])story_y = info_area[3] - 148for line in story_lines:draw.text((info_area[0] + 16, story_y), line, fill=COLORS["preview_muted"], font=fonts["small"])@@ -634,7 +596,7 @@ def render_process_video(draw_preview_panel(image, (LEFT_W + 10, 116, VIDEO_W - 26, VIDEO_H - 34), trajectory, t_real, fonts, image_cache)draw = ImageDraw.Draw(image)- footer_left = "SCRIPTED agent build trace Β· REAL Blender preview bundles Β· real turntable ending appended"+ footer_left = "STEP-ALIGNED build trace Β· REAL Blender preview bundles Β· real turntable ending appended"footer_right = STYLE._trim_middle(str(output_dir / "trajectory.json"), 64)draw.text((34, VIDEO_H - 26), footer_left, fill="#7891ab", font=fonts["small"])_draw_text_right(draw, VIDEO_W - 34, VIDEO_H - 26, footer_right, font=fonts["mono_small"], fill="#7891ab")@@ -762,13 +724,13 @@ def parse_args() -> argparse.Namespace:parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("--build-manifest",- default=f"/root/preview-artifacts/{today}/blender-orbital-relay-drone-v4/build_manifest.json",+ default=f"/root/preview-artifacts/{today}/blender-orbital-relay-drone-v6/build_manifest.json",help="Existing Blender build_manifest.json path from the orbital relay drone demo.",)parser.add_argument("--output-dir",- default=f"/root/preview-artifacts/{today}/blender-orbital-relay-drone-story",- help="Directory for trajectory.json, process frames, stills, and final polished video.",+ default=f"/root/preview-artifacts/{today}/blender-orbital-relay-drone-story-v5",+ help="Directory for trajectory.json, process frames, stills, and the final polished video assembled from real preview bundles.",)parser.add_argument("--fps", type=int, default=FPS, help="Output video FPS.")parser.add_argument(diff --git a/docs/scripts/freecad_live_preview_demo.py b/docs/scripts/freecad_live_preview_demo.pyindex 188dce7c0..088e26c09 100644--- a/docs/scripts/freecad_live_preview_demo.py+++ b/docs/scripts/freecad_live_preview_demo.py@@ -11,6 +11,16 @@ This script has two phases:The composition is programmatic, but the commands, outputs, timing, and previewartifacts are all captured from real execution.++The collected run persists:++- `session.json`+- `trajectory.json`+- copied preview bundle snapshots+- optional `live.html` rendered from the live session++Use `cli-hub previews inspect|html|watch|open` on the resulting session or+bundle paths when you want a generic viewer outside the final composed video."""from __future__ import annotations@@ -4897,7 +4907,7 @@ def parse_args() -> argparse.Namespace:parser.add_argument("--output-dir",default=str(default_output),- help="Directory for collected artifacts and rendered video.",+ help="Directory for collected artifacts, live preview state, trajectory.json, and rendered video.",)parser.add_argument("--scenario",@@ -4908,7 +4918,7 @@ def parse_args() -> argparse.Namespace:parser.add_argument("--timeline",default=None,- help="Existing trajectory.json path for render mode.",+ help="Existing trajectory.json path for render or motion-showcase mode.",)parser.add_argument("--fps", type=int, default=FPS, help="Output video framerate.")parser.add_argument("--speed", type=float, default=1.0, help="Playback speed multiplier.")diff --git a/examples/README.md b/examples/README.mddeleted file mode 100644index 70972168c..000000000--- a/examples/README.md+++ /dev/null@@ -1,79 +0,0 @@-# CLI-Anything Examples--Real-world demonstrations of CLI-Anything harnesses in action. Each example shows an AI agent (Claude Code) using a generated CLI to produce a complete, useful artifact β no GUI needed.-------## Draw.io — HTTPS Handshake Diagram--> **Harness:** `cli-anything-drawio` | **Time:** ~4 min | **Artifact:** `.drawio` + `.png`--An agent creates a full HTTPS connection lifecycle diagram from scratch β TCP three-way handshake, TLS negotiation, encrypted data exchange, and TCP four-way termination β entirely through CLI commands.--<p align="center">- <img src="drawio/drawio_demo.gif" alt="Draw.io CLI demo: building an HTTPS handshake diagram" width="720" />-</p>--<details>-<summary>Final artifact</summary>-<p align="center">- <img src="drawio/https_handshake.png" alt="HTTPS handshake sequence diagram" width="600" />-</p>-</details>--**What it demonstrates:**-- Creating shapes (rectangles, labels) with precise positioning-- Adding styled connectors (arrows with colors, labels, dashed lines)-- Section-based layout with color-coded phases (orange/purple/teal/red)-- Exporting to PNG via the Draw.io backend--*Contributed by [@zhangxilong-43](https://github.com/zhangxilong-43)*-------## Slay the Spire II — Game Automation--> **Harness:** `cli-anything-slay-the-spire-ii` | **Artifact:** Automated gameplay session--An agent plays through a Slay the Spire II run using the CLI harness β reading game state, selecting cards, choosing paths, and making strategic decisions in real-time.--<p align="center">- <img src="slay_the_spire_ii/example_preview.gif" alt="Slay the Spire II CLI gameplay demo" width="720" />-</p>--**What it demonstrates:**-- Real-time game state reading and decision making-- Complex multi-step strategy execution-- Agent-driven interaction with a live application--*Contributed by [@TianyuFan0504](https://github.com/TianyuFan0504)*-------## VideoCaptioner — Auto-Generated Subtitles--> **Harness:** `cli-anything-videocaptioner` | **Artifact:** Captioned video frames--An agent uses the VideoCaptioner CLI to automatically generate and overlay styled subtitles onto video content, with bilingual text rendering and customizable formatting.--<table align="center">-<tr>-<td align="center"><strong>Sub A</strong></td>-<td align="center"><strong>Sub B</strong></td>-</tr>-<tr>-<td><img src="videocaptioner/videocaptioner_before.png" alt="Video frame before captioning" width="380" /></td>-<td><img src="videocaptioner/videocaptioner_after.png" alt="Video frame after captioning" width="380" /></td>-</tr>-</table>--**What it demonstrates:**-- Automatic speech-to-text subtitle generation-- Bilingual caption overlay (Chinese + English)-- Styled text rendering with custom formatting and positioning--*Contributed by [@WEIFENG2333](https://github.com/WEIFENG2333)*-------## More CLI Demos Coming Soondiff --git a/freecad/agent-harness/cli_anything/freecad/README.md b/freecad/agent-harness/cli_anything/freecad/README.mdindex 86d961a5f..573387827 100644--- a/freecad/agent-harness/cli_anything/freecad/README.md+++ b/freecad/agent-harness/cli_anything/freecad/README.md@@ -63,6 +63,37 @@ cli-anything-freecad --json -p project.json part add boxcli-anything-freecad --json -p project.json export render output.step```+## Preview and Motion++FreeCAD supports both truthful preview bundles and final motion rendering.++```bash+# Capture a real 4-view preview bundle+cli-anything-freecad --json -p project.json preview capture --recipe quick++# Start poll-mode live preview+cli-anything-freecad --json -p project.json preview live start --recipe quick --mode poll --source-poll-ms 500++# Query current live status without rendering+cli-anything-freecad --json -p project.json preview live status --recipe quick++# Render a final motion sequence+cli-anything-freecad --json -p project.json motion render-video spin output.mp4+```++The preview side publishes `session.json`, immutable bundle dirs, and+`trajectory.json`. The default bundle includes `hero.png`, `front.png`,+`top.png`, and `right.png`.++Inspect/open the published previews with:++```bash+cli-hub previews inspect /path/to/bundle-or-session+cli-hub previews html /path/to/bundle-or-session -o page.html+cli-hub previews watch /path/to/session --open+cli-hub previews open /path/to/bundle-or-session+```+## Command Groups| Group | Description |diff --git a/freecad/agent-harness/cli_anything/freecad/core/preview.py b/freecad/agent-harness/cli_anything/freecad/core/preview.pyindex a6eed0872..0076501ba 100644--- a/freecad/agent-harness/cli_anything/freecad/core/preview.py+++ b/freecad/agent-harness/cli_anything/freecad/core/preview.py@@ -14,12 +14,17 @@ from typing import Any, Dict, List, Optionalfrom cli_anything.freecad.utils import freecad_backendfrom cli_anything.freecad.utils import freecad_macro_gen as macro_genfrom cli_anything.freecad.utils.preview_bundle import (+ append_live_trajectory,artifact_record,+ build_live_history_item,finalize_bundle,find_latest_manifest,fingerprint_data,fingerprint_file,+ live_trajectory_path,+ load_live_trajectory,prepare_bundle,+ summarize_trajectory,)from . import document as doc_mod@@ -191,6 +196,9 @@ def _terminate_pid(pid: Any) -> bool:def _with_live_refs(session_dir: Path, payload: Dict[str, Any]) -> Dict[str, Any]:payload["_session_dir"] = str(session_dir.resolve())payload["_session_path"] = str((session_dir / "session.json").resolve())+ trajectory_path = live_trajectory_path(session_dir)+ if trajectory_path.is_file():+ payload["_trajectory_path"] = str(trajectory_path.resolve())return payload@@ -223,15 +231,7 @@ def _update_current_symlink(session_dir: Path, bundle_dir: str) -> Path:def _history_item(bundle_manifest: Dict[str, Any]) -> Dict[str, Any]:- return {- "bundle_id": bundle_manifest.get("bundle_id"),- "bundle_dir": bundle_manifest.get("_bundle_dir"),- "manifest_path": bundle_manifest.get("_manifest_path"),- "summary_path": bundle_manifest.get("_summary_path"),- "created_at": bundle_manifest.get("created_at"),- "status": bundle_manifest.get("status"),- "cached": bool(bundle_manifest.get("cached")),- }+ return build_live_history_item(bundle_manifest)def _generate_preview_macro(@@ -480,6 +480,7 @@ def _publish_live_session(live_mode: Optional[str] = None,source_poll_ms: int = DEFAULT_SOURCE_POLL_MS,publish_reason: str = "manual",+ command: Optional[str] = None,) -> Dict[str, Any]:session_dir = _live_session_dir(session, recipe, root_dir=root_dir)session_dir.mkdir(parents=True, exist_ok=True)@@ -487,7 +488,21 @@ def _publish_live_session(existing = _load_existing_live_session(session_dir)now = _now_iso()- current_item = _history_item(bundle_manifest)+ project = session.get_project()+ trajectory = append_live_trajectory(+ session_dir,+ software="freecad",+ recipe=recipe,+ bundle_manifest=bundle_manifest,+ publish_reason=publish_reason,+ project_path=session.project_path,+ project_name=Path(session.project_path).name if session.project_path else project.get("name", "Untitled"),+ session_name=session_dir.name,+ command=command,+ command_started_at=now,+ command_finished_at=now,+ )+ current_item = dict(trajectory.get("latest_step") or _history_item(bundle_manifest))history = [current_item]for item in existing.get("history", []):if item.get("bundle_id") == current_item["bundle_id"]:@@ -504,7 +519,6 @@ def _publish_live_session(poller = dict(existing.get("poller") or {})poller["running"] = _pid_is_running(poller.get("pid"))project_file_fingerprint = _project_file_fingerprint(session.project_path)- project = session.get_project()source_state = dict(existing.get("source_state") or {})if session.project_path:source_state["source_type"] = "project-file"@@ -515,6 +529,7 @@ def _publish_live_session(source_state["last_rendered_fingerprint"] = project_file_fingerprintsource_state["last_rendered_at"] = nowsource_state["last_publish_reason"] = publish_reason+ trajectory_rel = os.path.relpath(Path(trajectory["_trajectory_path"]).resolve(), session_dir)payload = {"protocol_version": LIVE_PROTOCOL_VERSION,@@ -538,16 +553,22 @@ def _publish_live_session("current_cached": bool(bundle_manifest.get("cached")),"bundle_count": len(history),"history": history,+ "trajectory_path": trajectory_rel,+ "trajectory_protocol_version": trajectory.get("protocol_version"),+ "trajectory_step_count": trajectory.get("step_count", 0),+ "current_step_id": trajectory.get("current_step_id"),+ "latest_command": current_item.get("command"),+ "latest_publish_reason": current_item.get("publish_reason", publish_reason),"source_state": source_state,"poller": poller,"publish_command": (f"cli-anything-freecad{project_flag} preview live push --recipe {recipe}{root_flag}").strip(),"watch_command": (- f"cli-hub preview watch {session_dir} --open --poll-ms {int(refresh_hint_ms)}"+ f"cli-hub previews watch {session_dir} --open --poll-ms {int(refresh_hint_ms)}"),- "inspect_command": f"cli-hub preview inspect {session_dir}",- "html_command": f"cli-hub preview html {session_dir}",+ "inspect_command": f"cli-hub previews inspect {session_dir}",+ "html_command": f"cli-hub previews html {session_dir}","start_command": (f"cli-anything-freecad{project_flag} preview live start --recipe {recipe} "f"--mode {current_live_mode} --source-poll-ms {current_source_poll_ms}{root_flag}"@@ -594,6 +615,7 @@ def live_start(live_mode=live_mode,source_poll_ms=source_poll_ms,publish_reason=publish_reason,+ command=command,)live_payload["bundle"] = {"bundle_id": bundle_manifest.get("bundle_id"),@@ -650,6 +672,9 @@ def live_status(if poller:poller["running"] = _pid_is_running(poller.get("pid"))payload["poller"] = poller+ trajectory = load_live_trajectory(session_dir)+ if trajectory:+ payload["trajectory_summary"] = summarize_trajectory(trajectory)return _with_live_refs(session_dir, payload)diff --git a/freecad/agent-harness/cli_anything/freecad/freecad_cli.py b/freecad/agent-harness/cli_anything/freecad/freecad_cli.pyindex 63b97a38a..36db2f818 100644--- a/freecad/agent-harness/cli_anything/freecad/freecad_cli.py+++ b/freecad/agent-harness/cli_anything/freecad/freecad_cli.py@@ -86,7 +86,7 @@ def _spawn_live_viewer(session_dir: str, poll_ms: int) -> dict:hub = shutil.which("cli-hub")command = [hub or "cli-hub",- "preview",+ "previews","watch",session_dir,"--open",diff --git a/freecad/agent-harness/cli_anything/freecad/skills/SKILL.md b/freecad/agent-harness/cli_anything/freecad/skills/SKILL.mdindex 58d4a3451..10595b0b2 100644--- a/freecad/agent-harness/cli_anything/freecad/skills/SKILL.md+++ b/freecad/agent-harness/cli_anything/freecad/skills/SKILL.md@@ -25,6 +25,64 @@ cli-anything-freecad --json -p proj.json <cmd> # With project filecli-anything-freecad # Interactive REPL```+## Preview, Live Preview, and Motion++FreeCAD is currently the deepest preview integration in this branch.++Preview commands:++```bash+# List preview recipes+cli-anything-freecad --json -p proj.json preview recipes++# Capture a real 4-view bundle+cli-anything-freecad --json -p proj.json preview capture --recipe quick++# Start poll-mode live preview+cli-anything-freecad --json -p proj.json preview live start --recipe quick --mode poll --source-poll-ms 500++# Query current live state without rendering+cli-anything-freecad --json -p proj.json preview live status --recipe quick++# Stop live preview publication+cli-anything-freecad --json -p proj.json preview live stop --recipe quick+```++Typical `quick` bundle artifacts:++- `hero.png`+- `front.png`+- `top.png`+- `right.png`++Live preview persists:++- `session.json`+- immutable bundle directories+- `trajectory.json`++`preview live status --json` is intended for agents and includes a compact+`trajectory_summary` in addition to `_session_dir`, current bundle refs, and+`_trajectory_path`.++Viewer commands:++```bash+cli-hub previews inspect /path/to/bundle-or-session+cli-hub previews html /path/to/bundle-or-session -o page.html+cli-hub previews watch /path/to/session --open+cli-hub previews open /path/to/bundle-or-session+```++Motion commands remain separate from preview and are used for final truthful+frame rendering and showcase videos:++```bash+cli-anything-freecad --json -p proj.json motion new --name spin --duration 6 --fps 24+cli-anything-freecad --json -p proj.json motion keyframe spin --time 0.0 --part 0 --position 0,0,0+cli-anything-freecad --json -p proj.json motion render-video spin output.mp4+```+## Command Groups (258 commands)### document (5) β Document management@@ -253,3 +311,14 @@ All commands support `--json`. Responses include structured data. Errors: `{"err- Invalid types: Lists valid options- Index out of range: Reports valid range- File exists: Use `--overwrite`++## Agent Preview Notes++- Use `preview capture --json` whenever geometric changes need visual verification.+- Use `preview live start` for iterative build loops; prefer poll mode when the+ project file is being saved repeatedly.+- Use `preview live status --json` as the cheap status probe before reading the+ full `trajectory.json`.+- Treat `_bundle_dir` as a single snapshot only; the stable live identity is+ `_session_dir` plus `_trajectory_path`.+- Use `cli-hub previews ...` only to inspect/open already-published previews.diff --git a/freecad/agent-harness/cli_anything/freecad/tests/test_core.py b/freecad/agent-harness/cli_anything/freecad/tests/test_core.pyindex 73859d6bd..3c242f767 100644--- a/freecad/agent-harness/cli_anything/freecad/tests/test_core.py+++ b/freecad/agent-harness/cli_anything/freecad/tests/test_core.py@@ -1139,7 +1139,12 @@ class TestPreview:assert live["source_state"]["project_path"] == str(project_path)assert live["source_state"]["last_rendered_fingerprint"].startswith("sha256:")assert Path(live["_session_path"]).is_file()+ assert Path(live["_trajectory_path"]).is_file()assert (Path(live["_session_dir"]) / "current" / "manifest.json").is_file()+ trajectory = json.loads(Path(live["_trajectory_path"]).read_text(encoding="utf-8"))+ assert trajectory["step_count"] == 1+ assert trajectory["steps"][0]["bundle_id"] == "bundle-a"+ assert live["trajectory_step_count"] == 1def test_live_push_updates_history(self, tmp_path, monkeypatch):sess = Session()@@ -1163,6 +1168,58 @@ class TestPreview:assert pushed["current_bundle_id"] == "bundle-b"assert pushed["history"][0]["bundle_id"] == "bundle-b"assert pushed["history"][1]["bundle_id"] == "bundle-a"+ trajectory = json.loads(Path(pushed["_trajectory_path"]).read_text(encoding="utf-8"))+ assert trajectory["step_count"] == 2+ assert [step["bundle_id"] for step in trajectory["steps"]] == ["bundle-a", "bundle-b"]+ assert pushed["current_step_id"] == "step-0002"++ def test_live_status_includes_trajectory_summary(self, tmp_path, monkeypatch):+ sess = Session()+ proj = create_document(name="LivePreviewDoc")+ add_part(proj, "box", name="HeroBox")+ project_path = tmp_path / "live-demo.json"+ save_document(proj, str(project_path))+ sess.set_project(proj, str(project_path))+ bundle_manifest = self._fake_bundle(tmp_path / "bundles", "bundle-a")++ monkeypatch.setattr(preview_mod, "capture", lambda *args, **kwargs: dict(bundle_manifest))++ preview_mod.live_start(sess, root_dir=str(tmp_path), live_mode="manual")+ status = preview_mod.live_status(sess, root_dir=str(tmp_path))+ summary = status["trajectory_summary"]+ assert summary["step_count"] == 1+ assert summary["latest_bundle_id"] == "bundle-a"+ assert summary["latest_publish_reason"] == "live-start"+ assert summary["recent_steps"][0]["step_id"] == "step-0001"++ def test_live_push_records_publish_time_when_bundle_is_reused(self, tmp_path, monkeypatch):+ sess = Session()+ proj = create_document(name="LivePreviewDoc")+ add_part(proj, "box", name="HeroBox")+ project_path = tmp_path / "live-demo.json"+ save_document(proj, str(project_path))+ sess.set_project(proj, str(project_path))+ bundle_manifest = self._fake_bundle(tmp_path / "bundles", "bundle-a")+ bundle_manifest["created_at"] = "2025-01-01T00:00:00Z"+ publish_times = [+ "2026-04-23T10:00:00Z",+ "2026-04-23T10:05:00Z",+ ]++ monkeypatch.setattr(preview_mod, "capture", lambda *args, **kwargs: dict(bundle_manifest))+ monkeypatch.setattr(preview_mod, "_now_iso", lambda: publish_times.pop(0))++ preview_mod.live_start(sess, root_dir=str(tmp_path), live_mode="manual")+ pushed = preview_mod.live_push(sess, root_dir=str(tmp_path))+ trajectory = json.loads(Path(pushed["_trajectory_path"]).read_text(encoding="utf-8"))++ assert len(pushed["history"]) == 1+ assert [step["bundle_id"] for step in trajectory["steps"]] == ["bundle-a", "bundle-a"]+ assert [step["command_finished_at"] for step in trajectory["steps"]] == [+ "2026-04-23T10:00:00Z",+ "2026-04-23T10:05:00Z",+ ]+ assert all(step["created_at"] == "2025-01-01T00:00:00Z" for step in trajectory["steps"])def test_live_stop_marks_session_stopped(self, tmp_path, monkeypatch):sess = Session()@@ -1241,10 +1298,13 @@ class TestPreview:result = preview_mod.poll_live_session_once(str(started_session_dir))payload = json.loads((started_session_dir / "session.json").read_text(encoding="utf-8"))+ trajectory = json.loads((started_session_dir / "trajectory.json").read_text(encoding="utf-8"))assert result["action"] == "captured"assert result["bundle_id"] == "bundle-b"assert payload["bundle_count"] >= 2assert payload["source_state"]["last_publish_reason"] == "auto-poll"+ assert trajectory["step_count"] == 2+ assert trajectory["steps"][-1]["publish_reason"] == "auto-poll"def test_poll_live_session_once_exits_for_manual_mode(self, tmp_path, monkeypatch):sess = Session()diff --git a/freecad/agent-harness/cli_anything/freecad/utils/preview_bundle.py b/freecad/agent-harness/cli_anything/freecad/utils/preview_bundle.pyindex 3cba5dbf0..0028cc295 100644--- a/freecad/agent-harness/cli_anything/freecad/utils/preview_bundle.py+++ b/freecad/agent-harness/cli_anything/freecad/utils/preview_bundle.py@@ -12,6 +12,7 @@ from pathlib import Pathfrom typing import Any, Dict, Iterable, OptionalPROTOCOL_VERSION = "preview-bundle/v1"+TRAJECTORY_PROTOCOL_VERSION = "preview-trajectory/v1"def _slug(value: str) -> str:@@ -123,6 +124,9 @@ def find_cached_manifest():manifest["_manifest_path"] = str(manifest_path.resolve())manifest["_bundle_dir"] = str(manifest_path.parent.resolve())+ manifest["_summary_path"] = str(+ (manifest_path.parent / manifest.get("summary_path", "summary.json")).resolve()+ )return manifestreturn None@@ -157,6 +161,9 @@ def find_latest_manifest(continuemanifest["_manifest_path"] = str(manifest_path.resolve())manifest["_bundle_dir"] = str(manifest_path.parent.resolve())+ manifest["_summary_path"] = str(+ (manifest_path.parent / manifest.get("summary_path", "summary.json")).resolve()+ )return manifestreturn None@@ -302,3 +309,160 @@ def finalize_bundle(manifest["_bundle_dir"] = str(bundle_path)manifest["_summary_path"] = summary_pathreturn manifest+++def _clean_none_fields(data: Dict[str, Any]) -> Dict[str, Any]:+ return {key: value for key, value in data.items() if value is not None}+++def live_trajectory_path(session_dir: str | Path) -> Path:+ return Path(session_dir).expanduser().resolve() / "trajectory.json"+++def load_live_trajectory(session_dir: str | Path) -> Dict[str, Any]:+ trajectory_path = live_trajectory_path(session_dir)+ if not trajectory_path.is_file():+ return {}+ return _load_json(trajectory_path)+++def summarize_trajectory(trajectory: Dict[str, Any], *, recent_steps: int = 3) -> Dict[str, Any]:+ steps = list(trajectory.get("steps") or [])+ latest = steps[-1] if steps else {}+ recent = steps[-max(1, int(recent_steps)):] if steps else []+ return _clean_none_fields(+ {+ "protocol_version": trajectory.get("protocol_version"),+ "software": trajectory.get("software"),+ "recipe": trajectory.get("recipe"),+ "step_count": trajectory.get("step_count", len(steps)),+ "current_step_id": trajectory.get("current_step_id"),+ "latest_command": latest.get("command"),+ "latest_publish_reason": latest.get("publish_reason"),+ "latest_bundle_id": latest.get("bundle_id"),+ "recent_steps": [+ _clean_none_fields(+ {+ "step_id": item.get("step_id"),+ "step_index": item.get("step_index"),+ "bundle_id": item.get("bundle_id"),+ "publish_reason": item.get("publish_reason"),+ "command": item.get("command"),+ "command_finished_at": item.get("command_finished_at"),+ "status": item.get("status"),+ "cached": item.get("cached"),+ }+ )+ for item in recent+ ],+ }+ )+++def build_live_history_item(+ bundle_manifest: Dict[str, Any],+ *,+ step_id: Optional[str] = None,+ step_index: Optional[int] = None,+ publish_reason: Optional[str] = None,+ command: Optional[str] = None,+ command_started_at: Optional[str] = None,+ command_finished_at: Optional[str] = None,+ source_fingerprint: Optional[str] = None,+ stage_label: Optional[str] = None,+ note: Optional[str] = None,+) -> Dict[str, Any]:+ source = bundle_manifest.get("source") or {}+ resolved_command = command or (bundle_manifest.get("generator") or {}).get("command")+ resolved_fingerprint = (+ source_fingerprint+ or source.get("project_fingerprint")+ or source.get("capture_fingerprint")+ )+ created_at = bundle_manifest.get("created_at")+ return _clean_none_fields(+ {+ "step_id": step_id,+ "step_index": step_index,+ "bundle_id": bundle_manifest.get("bundle_id"),+ "bundle_dir": bundle_manifest.get("_bundle_dir"),+ "manifest_path": bundle_manifest.get("_manifest_path"),+ "summary_path": bundle_manifest.get("_summary_path"),+ "created_at": created_at,+ "status": bundle_manifest.get("status"),+ "cached": bool(bundle_manifest.get("cached")),+ "publish_reason": publish_reason,+ "command": resolved_command,+ "command_started_at": command_started_at or created_at,+ "command_finished_at": command_finished_at or created_at,+ "source_fingerprint": resolved_fingerprint,+ "stage_label": stage_label,+ "note": note,+ }+ )+++def append_live_trajectory(+ session_dir: str | Path,+ *,+ software: str,+ recipe: str,+ bundle_manifest: Dict[str, Any],+ publish_reason: str,+ project_path: Optional[str] = None,+ project_name: Optional[str] = None,+ session_name: Optional[str] = None,+ command: Optional[str] = None,+ command_started_at: Optional[str] = None,+ command_finished_at: Optional[str] = None,+ source_fingerprint: Optional[str] = None,+ stage_label: Optional[str] = None,+ note: Optional[str] = None,+) -> Dict[str, Any]:+ session_path = Path(session_dir).expanduser().resolve()+ existing = load_live_trajectory(session_path)+ steps = list(existing.get("steps") or [])+ finished_at = (+ command_finished_at+ or bundle_manifest.get("created_at")+ or datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")+ )+ started_at = command_started_at or finished_at+ step_index = len(steps) + 1+ step_id = f"step-{step_index:04d}"+ step = build_live_history_item(+ bundle_manifest,+ step_id=step_id,+ step_index=step_index,+ publish_reason=publish_reason,+ command=command,+ command_started_at=started_at,+ command_finished_at=finished_at,+ source_fingerprint=source_fingerprint,+ stage_label=stage_label,+ note=note,+ )+ steps.append(step)++ trajectory: Dict[str, Any] = dict(existing)+ trajectory.update(+ _clean_none_fields(+ {+ "protocol_version": TRAJECTORY_PROTOCOL_VERSION,+ "software": software,+ "recipe": recipe,+ "session_name": session_name or session_path.name,+ "project_path": project_path,+ "project_name": project_name,+ "created_at": existing.get("created_at", finished_at),+ "updated_at": finished_at,+ "step_count": len(steps),+ "current_step_id": step_id,+ }+ )+ )+ trajectory["steps"] = steps+ trajectory_path = write_json(str(live_trajectory_path(session_path)), trajectory)+ trajectory["_trajectory_path"] = trajectory_path+ trajectory["latest_step"] = step+ return trajectorydiff --git a/openscreen/agent-harness/cli_anything/openscreen/README.md b/openscreen/agent-harness/cli_anything/openscreen/README.mdindex db4356a35..3ee34a669 100644--- a/openscreen/agent-harness/cli_anything/openscreen/README.md+++ b/openscreen/agent-harness/cli_anything/openscreen/README.md@@ -36,6 +36,30 @@ cli-anything-openscreen export render demo.mp4cli-anything-openscreen --json project info```+## Preview Bundles++Openscreen supports static preview bundles for review-ready editing checks.++```bash+# Capture a low-res preview bundle+cli-anything-openscreen --json --project project.openscreen preview capture --recipe quick++# Read the latest bundle+cli-anything-openscreen --json --project project.openscreen preview latest --recipe quick+```++The preview bundle contains a low-res review clip, sampled frames, and summary+metadata. Capture also appends to a stable `trajectory.json` beside the preview+recipe root.++Inspect or open the resulting bundle with:++```bash+cli-hub previews inspect /path/to/bundle+cli-hub previews html /path/to/bundle -o page.html+cli-hub previews open /path/to/bundle+```+## Command Groups| Group | Commands |diff --git a/openscreen/agent-harness/cli_anything/openscreen/core/preview.py b/openscreen/agent-harness/cli_anything/openscreen/core/preview.pyindex eeb012651..0244937b8 100644--- a/openscreen/agent-harness/cli_anything/openscreen/core/preview.py+++ b/openscreen/agent-harness/cli_anything/openscreen/core/preview.py@@ -3,10 +3,13 @@from __future__ import annotationsimport os+from pathlib import Pathfrom typing import Any, Dict, List, Optionalfrom ..utils.preview_bundle import (+ append_live_trajectory,artifact_record,+ bundle_root,finalize_bundle,find_latest_manifest,fingerprint_data,@@ -71,6 +74,28 @@ def _metrics(session: Session) -> Dict[str, Any]:}+def _trajectory_dir(session: Session, recipe: str, root_dir: Optional[str] = None) -> str:+ return str(+ bundle_root(+ "openscreen",+ recipe,+ project_path=session.project_path,+ root_dir=root_dir,+ ).resolve()+ )+++def _attach_trajectory_ref(manifest: Dict[str, Any]) -> Dict[str, Any]:+ bundle_dir = manifest.get("_bundle_dir")+ context = manifest.get("context") or {}+ trajectory_ref = context.get("trajectory_path")+ if bundle_dir and trajectory_ref:+ trajectory_path = (Path(str(bundle_dir)) / str(trajectory_ref)).resolve()+ if trajectory_path.is_file():+ manifest["_trajectory_path"] = str(trajectory_path)+ return manifest++def capture(session: Session,recipe: str = "quick",@@ -103,10 +128,12 @@ def capture(if prepared["cached"]:manifest = dict(prepared["manifest"])manifest["cached"] = True- return manifest+ return _attach_trajectory_ref(manifest)bundle_dir = prepared["bundle_dir"]artifacts_dir = prepared["artifacts_dir"]+ trajectory_dir = _trajectory_dir(session, recipe, root_dir=root_dir)+ trajectory_rel = os.path.relpath(Path(trajectory_dir) / "trajectory.json", Path(bundle_dir))preview_clip = os.path.join(artifacts_dir, "preview.mp4")render_result = export_mod.render(session, preview_clip)@@ -168,7 +195,7 @@ def capture("warnings": warnings,"next_actions": ["Inspect the review clip for zoom timing, speed ramps, and padding.",- "Open the bundle in cli-hub preview html for a gallery layout.",+ "Open the bundle in cli-hub previews html for a gallery layout.",],}@@ -196,10 +223,26 @@ def capture(},status="partial" if warnings else "ok",warnings=warnings or None,- context={"editor": {"aspectRatio": metrics["aspect_ratio"], "background": metrics["background"]}},+ context={+ "editor": {"aspectRatio": metrics["aspect_ratio"], "background": metrics["background"]},+ "trajectory_path": trajectory_rel,+ },metrics=metrics,labels=["video", "screen-recording", "preview"],)+ trajectory = append_live_trajectory(+ trajectory_dir,+ software="openscreen",+ recipe=recipe,+ bundle_manifest=manifest,+ publish_reason="capture",+ project_path=session.project_path,+ project_name=os.path.basename(session.project_path) if session.project_path else None,+ session_name=f"{os.path.splitext(os.path.basename(session.project_path or 'untitled'))[0]}-{recipe}",+ command=command,+ stage_label="preview-capture",+ )+ manifest["_trajectory_path"] = trajectory["_trajectory_path"]manifest["cached"] = Falsereturn manifest@@ -220,4 +263,4 @@ def latest()if manifest is None:raise FileNotFoundError("No Openscreen preview bundle found")- return manifest+ return _attach_trajectory_ref(manifest)diff --git a/openscreen/agent-harness/cli_anything/openscreen/skills/SKILL.md b/openscreen/agent-harness/cli_anything/openscreen/skills/SKILL.mdindex 26f5173c1..a152e81d5 100644--- a/openscreen/agent-harness/cli_anything/openscreen/skills/SKILL.md+++ b/openscreen/agent-harness/cli_anything/openscreen/skills/SKILL.md@@ -128,6 +128,35 @@ Render the final polished video.| `export presets` | List available export presets || `export render <output_path>` | Render project to video file |+### preview++Capture truthful review bundles from the current Openscreen project.++| Command | Description |+|---------|-------------|+| `preview recipes` | List available preview recipes |+| `preview capture --recipe quick` | Render a low-res preview bundle |+| `preview latest [--recipe quick]` | Return the latest existing bundle |++Current preview support is static rather than live. A `quick` bundle typically+contains:++- a low-res preview clip+- sampled frames+- a `hero` frame for quick inspection+- `summary.json` with trim/zoom/speed facts++Bundle capture also writes or updates a stable recipe-level `trajectory.json`+beside the preview root so agents can reconstruct preview history over time.++Viewer commands:++```bash+cli-hub previews inspect /path/to/bundle+cli-hub previews html /path/to/bundle -o page.html+cli-hub previews open /path/to/bundle+```+### sessionManage session state with undo/redo.@@ -173,6 +202,9 @@ Manage session state with undo/redo.5. After `export render`, verify the output exists and probe it6. Times are in **milliseconds** for all region commands7. Coordinates (focus, crop, position) are **normalized 0-1**+8. Use `preview capture --json` to validate zoom, trim, annotation, and timing visually+9. Read returned bundle artifact paths from the JSON payload; images and clips live on disk+10. Use `cli-hub previews ...` only to inspect/open existing bundles## Versiondiff --git a/openscreen/agent-harness/cli_anything/openscreen/tests/test_core.py b/openscreen/agent-harness/cli_anything/openscreen/tests/test_core.pyindex d4a69674b..d7862c516 100644--- a/openscreen/agent-harness/cli_anything/openscreen/tests/test_core.py+++ b/openscreen/agent-harness/cli_anything/openscreen/tests/test_core.py@@ -297,6 +297,11 @@ class TestPreview:assert any(item["role"] == "preview-clip" for item in manifest["artifacts"])assert any(item["role"] == "hero" for item in manifest["artifacts"])assert os.path.isfile(manifest["_manifest_path"])+ assert os.path.isfile(manifest["_trajectory_path"])+ trajectory = json.loads(Path(manifest["_trajectory_path"]).read_text(encoding="utf-8"))+ assert trajectory["step_count"] == 1+ assert trajectory["steps"][0]["bundle_id"] == manifest["bundle_id"]+ assert trajectory["steps"][0]["publish_reason"] == "capture"def test_latest_bundle(self, tmp_path, monkeypatch):session = Session("preview_test")@@ -326,6 +331,7 @@ class TestPreview:created = preview_mod.capture(session, root_dir=str(tmp_path))latest = preview_mod.latest(root_dir=str(tmp_path))assert latest["bundle_id"] == created["bundle_id"]+ assert os.path.isfile(latest["_trajectory_path"])# ββ Zoom Tests ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdiff --git a/openscreen/agent-harness/cli_anything/openscreen/utils/preview_bundle.py b/openscreen/agent-harness/cli_anything/openscreen/utils/preview_bundle.pyindex 3cba5dbf0..0028cc295 100644--- a/openscreen/agent-harness/cli_anything/openscreen/utils/preview_bundle.py+++ b/openscreen/agent-harness/cli_anything/openscreen/utils/preview_bundle.py@@ -12,6 +12,7 @@ from pathlib import Pathfrom typing import Any, Dict, Iterable, OptionalPROTOCOL_VERSION = "preview-bundle/v1"+TRAJECTORY_PROTOCOL_VERSION = "preview-trajectory/v1"def _slug(value: str) -> str:@@ -123,6 +124,9 @@ def find_cached_manifest():manifest["_manifest_path"] = str(manifest_path.resolve())manifest["_bundle_dir"] = str(manifest_path.parent.resolve())+ manifest["_summary_path"] = str(+ (manifest_path.parent / manifest.get("summary_path", "summary.json")).resolve()+ )return manifestreturn None@@ -157,6 +161,9 @@ def find_latest_manifest(continuemanifest["_manifest_path"] = str(manifest_path.resolve())manifest["_bundle_dir"] = str(manifest_path.parent.resolve())+ manifest["_summary_path"] = str(+ (manifest_path.parent / manifest.get("summary_path", "summary.json")).resolve()+ )return manifestreturn None@@ -302,3 +309,160 @@ def finalize_bundle(manifest["_bundle_dir"] = str(bundle_path)manifest["_summary_path"] = summary_pathreturn manifest+++def _clean_none_fields(data: Dict[str, Any]) -> Dict[str, Any]:+ return {key: value for key, value in data.items() if value is not None}+++def live_trajectory_path(session_dir: str | Path) -> Path:+ return Path(session_dir).expanduser().resolve() / "trajectory.json"+++def load_live_trajectory(session_dir: str | Path) -> Dict[str, Any]:+ trajectory_path = live_trajectory_path(session_dir)+ if not trajectory_path.is_file():+ return {}+ return _load_json(trajectory_path)+++def summarize_trajectory(trajectory: Dict[str, Any], *, recent_steps: int = 3) -> Dict[str, Any]:+ steps = list(trajectory.get("steps") or [])+ latest = steps[-1] if steps else {}+ recent = steps[-max(1, int(recent_steps)):] if steps else []+ return _clean_none_fields(+ {+ "protocol_version": trajectory.get("protocol_version"),+ "software": trajectory.get("software"),+ "recipe": trajectory.get("recipe"),+ "step_count": trajectory.get("step_count", len(steps)),+ "current_step_id": trajectory.get("current_step_id"),+ "latest_command": latest.get("command"),+ "latest_publish_reason": latest.get("publish_reason"),+ "latest_bundle_id": latest.get("bundle_id"),+ "recent_steps": [+ _clean_none_fields(+ {+ "step_id": item.get("step_id"),+ "step_index": item.get("step_index"),+ "bundle_id": item.get("bundle_id"),+ "publish_reason": item.get("publish_reason"),+ "command": item.get("command"),+ "command_finished_at": item.get("command_finished_at"),+ "status": item.get("status"),+ "cached": item.get("cached"),+ }+ )+ for item in recent+ ],+ }+ )+++def build_live_history_item(+ bundle_manifest: Dict[str, Any],+ *,+ step_id: Optional[str] = None,+ step_index: Optional[int] = None,+ publish_reason: Optional[str] = None,+ command: Optional[str] = None,+ command_started_at: Optional[str] = None,+ command_finished_at: Optional[str] = None,+ source_fingerprint: Optional[str] = None,+ stage_label: Optional[str] = None,+ note: Optional[str] = None,+) -> Dict[str, Any]:+ source = bundle_manifest.get("source") or {}+ resolved_command = command or (bundle_manifest.get("generator") or {}).get("command")+ resolved_fingerprint = (+ source_fingerprint+ or source.get("project_fingerprint")+ or source.get("capture_fingerprint")+ )+ created_at = bundle_manifest.get("created_at")+ return _clean_none_fields(+ {+ "step_id": step_id,+ "step_index": step_index,+ "bundle_id": bundle_manifest.get("bundle_id"),+ "bundle_dir": bundle_manifest.get("_bundle_dir"),+ "manifest_path": bundle_manifest.get("_manifest_path"),+ "summary_path": bundle_manifest.get("_summary_path"),+ "created_at": created_at,+ "status": bundle_manifest.get("status"),+ "cached": bool(bundle_manifest.get("cached")),+ "publish_reason": publish_reason,+ "command": resolved_command,+ "command_started_at": command_started_at or created_at,+ "command_finished_at": command_finished_at or created_at,+ "source_fingerprint": resolved_fingerprint,+ "stage_label": stage_label,+ "note": note,+ }+ )+++def append_live_trajectory(+ session_dir: str | Path,+ *,+ software: str,+ recipe: str,+ bundle_manifest: Dict[str, Any],+ publish_reason: str,+ project_path: Optional[str] = None,+ project_name: Optional[str] = None,+ session_name: Optional[str] = None,+ command: Optional[str] = None,+ command_started_at: Optional[str] = None,+ command_finished_at: Optional[str] = None,+ source_fingerprint: Optional[str] = None,+ stage_label: Optional[str] = None,+ note: Optional[str] = None,+) -> Dict[str, Any]:+ session_path = Path(session_dir).expanduser().resolve()+ existing = load_live_trajectory(session_path)+ steps = list(existing.get("steps") or [])+ finished_at = (+ command_finished_at+ or bundle_manifest.get("created_at")+ or datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")+ )+ started_at = command_started_at or finished_at+ step_index = len(steps) + 1+ step_id = f"step-{step_index:04d}"+ step = build_live_history_item(+ bundle_manifest,+ step_id=step_id,+ step_index=step_index,+ publish_reason=publish_reason,+ command=command,+ command_started_at=started_at,+ command_finished_at=finished_at,+ source_fingerprint=source_fingerprint,+ stage_label=stage_label,+ note=note,+ )+ steps.append(step)++ trajectory: Dict[str, Any] = dict(existing)+ trajectory.update(+ _clean_none_fields(+ {+ "protocol_version": TRAJECTORY_PROTOCOL_VERSION,+ "software": software,+ "recipe": recipe,+ "session_name": session_name or session_path.name,+ "project_path": project_path,+ "project_name": project_name,+ "created_at": existing.get("created_at", finished_at),+ "updated_at": finished_at,+ "step_count": len(steps),+ "current_step_id": step_id,+ }+ )+ )+ trajectory["steps"] = steps+ trajectory_path = write_json(str(live_trajectory_path(session_path)), trajectory)+ trajectory["_trajectory_path"] = trajectory_path+ trajectory["latest_step"] = step+ return trajectorydiff --git a/renderdoc/agent-harness/cli_anything/renderdoc/README.md b/renderdoc/agent-harness/cli_anything/renderdoc/README.mdindex 890f3c438..21f2619d6 100644--- a/renderdoc/agent-harness/cli_anything/renderdoc/README.md+++ b/renderdoc/agent-harness/cli_anything/renderdoc/README.md@@ -56,6 +56,32 @@ cli-anything-renderdoc -c frame.rdc resources read-buffer <resourceId> --formatcli-anything-renderdoc -c frame.rdc --json actions list```+## Preview Bundles++RenderDoc exposes preview bundles for honest capture inspection and diffing.++```bash+# Capture a preview bundle+cli-anything-renderdoc -c frame.rdc --json preview capture --recipe quick --event-id 42++# Capture a diff preview bundle+cli-anything-renderdoc -c frame.rdc --json preview diff 100 200++# Return the latest existing bundle+cli-anything-renderdoc -c frame.rdc --json preview latest --recipe quick+```++Preview bundles typically contain thumbnails, output-target images, and+pipeline/action JSON. Diff bundles also contain `pipeline_diff.json`.++Inspect or open them with:++```bash+cli-hub previews inspect /path/to/bundle+cli-hub previews html /path/to/bundle -o page.html+cli-hub previews open /path/to/bundle+```+## Command Reference### Global Optionsdiff --git a/renderdoc/agent-harness/cli_anything/renderdoc/core/preview.py b/renderdoc/agent-harness/cli_anything/renderdoc/core/preview.pyindex 81263a825..0c3c0812e 100644--- a/renderdoc/agent-harness/cli_anything/renderdoc/core/preview.py+++ b/renderdoc/agent-harness/cli_anything/renderdoc/core/preview.py@@ -3,10 +3,13 @@from __future__ import annotationsimport os+from pathlib import Pathfrom typing import Any, Dict, List, Optionalfrom ..utils.preview_bundle import (+ append_live_trajectory,artifact_record,+ bundle_root,finalize_bundle,find_latest_manifest,fingerprint_data,@@ -83,6 +86,28 @@ def _count_differences(obj: Any) -> int:return 1+def _trajectory_dir(capture_path: str, recipe: str, root_dir: Optional[str] = None) -> str:+ return str(+ bundle_root(+ "renderdoc",+ recipe,+ project_path=capture_path,+ root_dir=root_dir,+ ).resolve()+ )+++def _attach_trajectory_ref(manifest: Dict[str, Any]) -> Dict[str, Any]:+ bundle_dir = manifest.get("_bundle_dir")+ context = manifest.get("context") or {}+ trajectory_ref = context.get("trajectory_path")+ if bundle_dir and trajectory_ref:+ trajectory_path = (Path(str(bundle_dir)) / str(trajectory_ref)).resolve()+ if trajectory_path.is_file():+ manifest["_trajectory_path"] = str(trajectory_path)+ return manifest++def capture(handle,capture_path: str,@@ -115,10 +140,12 @@ def capture(if prepared["cached"]:manifest = dict(prepared["manifest"])manifest["cached"] = True- return manifest+ return _attach_trajectory_ref(manifest)bundle_dir = prepared["bundle_dir"]artifacts_dir = prepared["artifacts_dir"]+ trajectory_dir = _trajectory_dir(capture_path, recipe, root_dir=root_dir)+ trajectory_rel = os.path.relpath(Path(trajectory_dir) / "trajectory.json", Path(bundle_dir))warnings: List[str] = []artifacts: List[Dict[str, Any]] = []metadata = handle.metadata()@@ -230,13 +257,27 @@ def capture(},status="partial" if warnings else "ok",warnings=warnings or None,- context={"event_id": chosen_event},+ context={"event_id": chosen_event, "trajectory_path": trajectory_rel},metrics={"drawcalls": action_summary.get("drawcalls", 0),"output_targets": output_count,},labels=["gpu", "capture", "preview"],)+ trajectory = append_live_trajectory(+ trajectory_dir,+ software="renderdoc",+ recipe=recipe,+ bundle_manifest=manifest,+ publish_reason="capture",+ project_path=os.path.abspath(capture_path),+ project_name=os.path.basename(capture_path),+ session_name=f"{os.path.splitext(os.path.basename(capture_path))[0]}-{recipe}",+ command=command,+ stage_label=f"event-{chosen_event}" if chosen_event is not None else "capture",+ note=f"RenderDoc capture preview for event {chosen_event}" if chosen_event is not None else None,+ )+ manifest["_trajectory_path"] = trajectory["_trajectory_path"]manifest["cached"] = Falsereturn manifest@@ -277,10 +318,12 @@ def diff(if prepared["cached"]:manifest = dict(prepared["manifest"])manifest["cached"] = True- return manifest+ return _attach_trajectory_ref(manifest)bundle_dir = prepared["bundle_dir"]artifacts_dir = prepared["artifacts_dir"]+ trajectory_dir = _trajectory_dir(capture_path_a, "diff", root_dir=root_dir)+ trajectory_rel = os.path.relpath(Path(trajectory_dir) / "trajectory.json", Path(bundle_dir))warnings: List[str] = []artifacts: List[Dict[str, Any]] = []@@ -427,7 +470,7 @@ def diff(},status="partial" if warnings else "ok",warnings=warnings or None,- context={"event_a": event_a, "event_b": event_b},+ context={"event_a": event_a, "event_b": event_b, "trajectory_path": trajectory_rel},metrics={"difference_count": diff_count},labels=["gpu", "capture", "diff", "preview"],source_bundles=[@@ -435,6 +478,20 @@ def diff({"capture_path": os.path.abspath(capture_path_b), "event_id": event_b},],)+ trajectory = append_live_trajectory(+ trajectory_dir,+ software="renderdoc",+ recipe="diff",+ bundle_manifest=manifest,+ publish_reason="diff",+ project_path=os.path.abspath(capture_path_a),+ project_name=os.path.basename(capture_path_a),+ session_name=f"{os.path.splitext(os.path.basename(capture_path_a))[0]}-diff",+ command=command,+ stage_label=f"diff-{event_a}-vs-{event_b}",+ note=f"Pipeline diff for events {event_a} vs {event_b}",+ )+ manifest["_trajectory_path"] = trajectory["_trajectory_path"]manifest["cached"] = Falsereturn manifest@@ -456,4 +513,4 @@ def latest()if manifest is None:raise FileNotFoundError("No RenderDoc preview bundle found")- return manifest+ return _attach_trajectory_ref(manifest)diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/skills/SKILL.md b/renderdoc/agent-harness/cli_anything/renderdoc/skills/SKILL.mdindex 3e6ded739..f6332f4e4 100644--- a/renderdoc/agent-harness/cli_anything/renderdoc/skills/SKILL.md+++ b/renderdoc/agent-harness/cli_anything/renderdoc/skills/SKILL.md@@ -96,6 +96,50 @@ cli-anything-renderdoc -c frame.rdc counters listcli-anything-renderdoc -c frame.rdc counters fetch --ids 1,2,3```+## Preview Bundles++RenderDoc preview support is for truthful capture inspection rather than live+creative preview.++```bash+# List preview recipes+cli-anything-renderdoc -c frame.rdc --json preview recipes++# Capture a preview bundle for the active capture or a specific event+cli-anything-renderdoc -c frame.rdc --json preview capture --recipe quick --event-id 42++# Capture a diff preview bundle for two events or captures+cli-anything-renderdoc -c frame.rdc --json preview diff 100 200+cli-anything-renderdoc -c a.rdc --json preview diff 100 200 --capture-b b.rdc++# Return the latest existing bundle for the capture+cli-anything-renderdoc -c frame.rdc --json preview latest --recipe quick+```++Typical preview bundle contents:++- capture thumbnail+- output-target images+- `pipeline_state.json`+- `action_summary.json`++Diff bundles additionally include:++- A/B thumbnails+- A/B output-target images+- `pipeline_diff.json`++RenderDoc does not currently expose live preview sessions. Instead, each+capture/diff bundle appends to a stable recipe-level `trajectory.json`.++Viewer commands:++```bash+cli-hub previews inspect /path/to/bundle+cli-hub previews html /path/to/bundle -o page.html+cli-hub previews open /path/to/bundle+```+## JSON ModeAll commands support `--json` for machine-readable output:@@ -121,6 +165,10 @@ cli-anything-renderdoc -c frame.rdc --json actions summary- Always specify `--json` for programmatic consumption- Use `actions summary` first to understand capture complexity- Use `actions list --draws-only` to focus on actual rendering+- Use `preview capture` or `preview diff` when the agent needs a portable,+ honest inspection bundle rather than raw replay calls alone+- Read `_trajectory_path` from preview JSON if you need persistent capture/diff history+- Use `cli-hub previews ...` only to inspect/open already-generated bundles- Pipeline state requires an event ID from the action list- Texture save supports: png, jpg, bmp, tga, hdr, exr, dds- Buffer data can be decoded as hex, float32, uint32, or raw bytesdiff --git a/renderdoc/agent-harness/cli_anything/renderdoc/tests/test_core.py b/renderdoc/agent-harness/cli_anything/renderdoc/tests/test_core.pyindex 40e9306b6..afe69fa0b 100644--- a/renderdoc/agent-harness/cli_anything/renderdoc/tests/test_core.py+++ b/renderdoc/agent-harness/cli_anything/renderdoc/tests/test_core.py@@ -730,6 +730,10 @@ class TestPreviewModule:assert manifest["status"] == "ok"assert any(item["role"] == "hero" for item in manifest["artifacts"])assert any(item["artifact_id"] == "pipeline_state" for item in manifest["artifacts"])+ assert os.path.isfile(manifest["_trajectory_path"])+ trajectory = json.loads(Path(manifest["_trajectory_path"]).read_text(encoding="utf-8"))+ assert trajectory["step_count"] == 1+ assert trajectory["steps"][0]["publish_reason"] == "capture"def test_diff_bundle(self, tmp_path, monkeypatch):from cli_anything.renderdoc.core import preview as preview_mod@@ -762,6 +766,10 @@ class TestPreviewModule:assert manifest["software"] == "renderdoc"assert manifest["bundle_kind"] == "diff"assert any(item["artifact_id"] == "pipeline_diff" for item in manifest["artifacts"])+ assert os.path.isfile(manifest["_trajectory_path"])+ trajectory = json.loads(Path(manifest["_trajectory_path"]).read_text(encoding="utf-8"))+ assert trajectory["step_count"] == 1+ assert trajectory["steps"][0]["publish_reason"] == "diff"def test_latest_bundle(self, tmp_path, monkeypatch):from cli_anything.renderdoc.core import preview as preview_mod@@ -786,3 +794,4 @@ class TestPreviewModule:created = preview_mod.capture(handle, str(capture_path), root_dir=str(tmp_path))latest = preview_mod.latest(root_dir=str(tmp_path))assert latest["bundle_id"] == created["bundle_id"]+ assert os.path.isfile(latest["_trajectory_path"])diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/utils/preview_bundle.py b/renderdoc/agent-harness/cli_anything/renderdoc/utils/preview_bundle.pyindex 3cba5dbf0..0028cc295 100644--- a/renderdoc/agent-harness/cli_anything/renderdoc/utils/preview_bundle.py+++ b/renderdoc/agent-harness/cli_anything/renderdoc/utils/preview_bundle.py@@ -12,6 +12,7 @@ from pathlib import Pathfrom typing import Any, Dict, Iterable, OptionalPROTOCOL_VERSION = "preview-bundle/v1"+TRAJECTORY_PROTOCOL_VERSION = "preview-trajectory/v1"def _slug(value: str) -> str:@@ -123,6 +124,9 @@ def find_cached_manifest():manifest["_manifest_path"] = str(manifest_path.resolve())manifest["_bundle_dir"] = str(manifest_path.parent.resolve())+ manifest["_summary_path"] = str(+ (manifest_path.parent / manifest.get("summary_path", "summary.json")).resolve()+ )return manifestreturn None@@ -157,6 +161,9 @@ def find_latest_manifest(continuemanifest["_manifest_path"] = str(manifest_path.resolve())manifest["_bundle_dir"] = str(manifest_path.parent.resolve())+ manifest["_summary_path"] = str(+ (manifest_path.parent / manifest.get("summary_path", "summary.json")).resolve()+ )return manifestreturn None@@ -302,3 +309,160 @@ def finalize_bundle(manifest["_bundle_dir"] = str(bundle_path)manifest["_summary_path"] = summary_pathreturn manifest+++def _clean_none_fields(data: Dict[str, Any]) -> Dict[str, Any]:+ return {key: value for key, value in data.items() if value is not None}+++def live_trajectory_path(session_dir: str | Path) -> Path:+ return Path(session_dir).expanduser().resolve() / "trajectory.json"+++def load_live_trajectory(session_dir: str | Path) -> Dict[str, Any]:+ trajectory_path = live_trajectory_path(session_dir)+ if not trajectory_path.is_file():+ return {}+ return _load_json(trajectory_path)+++def summarize_trajectory(trajectory: Dict[str, Any], *, recent_steps: int = 3) -> Dict[str, Any]:+ steps = list(trajectory.get("steps") or [])+ latest = steps[-1] if steps else {}+ recent = steps[-max(1, int(recent_steps)):] if steps else []+ return _clean_none_fields(+ {+ "protocol_version": trajectory.get("protocol_version"),+ "software": trajectory.get("software"),+ "recipe": trajectory.get("recipe"),+ "step_count": trajectory.get("step_count", len(steps)),+ "current_step_id": trajectory.get("current_step_id"),+ "latest_command": latest.get("command"),+ "latest_publish_reason": latest.get("publish_reason"),+ "latest_bundle_id": latest.get("bundle_id"),+ "recent_steps": [+ _clean_none_fields(+ {+ "step_id": item.get("step_id"),+ "step_index": item.get("step_index"),+ "bundle_id": item.get("bundle_id"),+ "publish_reason": item.get("publish_reason"),+ "command": item.get("command"),+ "command_finished_at": item.get("command_finished_at"),+ "status": item.get("status"),+ "cached": item.get("cached"),+ }+ )+ for item in recent+ ],+ }+ )+++def build_live_history_item(+ bundle_manifest: Dict[str, Any],+ *,+ step_id: Optional[str] = None,+ step_index: Optional[int] = None,+ publish_reason: Optional[str] = None,+ command: Optional[str] = None,+ command_started_at: Optional[str] = None,+ command_finished_at: Optional[str] = None,+ source_fingerprint: Optional[str] = None,+ stage_label: Optional[str] = None,+ note: Optional[str] = None,+) -> Dict[str, Any]:+ source = bundle_manifest.get("source") or {}+ resolved_command = command or (bundle_manifest.get("generator") or {}).get("command")+ resolved_fingerprint = (+ source_fingerprint+ or source.get("project_fingerprint")+ or source.get("capture_fingerprint")+ )+ created_at = bundle_manifest.get("created_at")+ return _clean_none_fields(+ {+ "step_id": step_id,+ "step_index": step_index,+ "bundle_id": bundle_manifest.get("bundle_id"),+ "bundle_dir": bundle_manifest.get("_bundle_dir"),+ "manifest_path": bundle_manifest.get("_manifest_path"),+ "summary_path": bundle_manifest.get("_summary_path"),+ "created_at": created_at,+ "status": bundle_manifest.get("status"),+ "cached": bool(bundle_manifest.get("cached")),+ "publish_reason": publish_reason,+ "command": resolved_command,+ "command_started_at": command_started_at or created_at,+ "command_finished_at": command_finished_at or created_at,+ "source_fingerprint": resolved_fingerprint,+ "stage_label": stage_label,+ "note": note,+ }+ )+++def append_live_trajectory(+ session_dir: str | Path,+ *,+ software: str,+ recipe: str,+ bundle_manifest: Dict[str, Any],+ publish_reason: str,+ project_path: Optional[str] = None,+ project_name: Optional[str] = None,+ session_name: Optional[str] = None,+ command: Optional[str] = None,+ command_started_at: Optional[str] = None,+ command_finished_at: Optional[str] = None,+ source_fingerprint: Optional[str] = None,+ stage_label: Optional[str] = None,+ note: Optional[str] = None,+) -> Dict[str, Any]:+ session_path = Path(session_dir).expanduser().resolve()+ existing = load_live_trajectory(session_path)+ steps = list(existing.get("steps") or [])+ finished_at = (+ command_finished_at+ or bundle_manifest.get("created_at")+ or datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")+ )+ started_at = command_started_at or finished_at+ step_index = len(steps) + 1+ step_id = f"step-{step_index:04d}"+ step = build_live_history_item(+ bundle_manifest,+ step_id=step_id,+ step_index=step_index,+ publish_reason=publish_reason,+ command=command,+ command_started_at=started_at,+ command_finished_at=finished_at,+ source_fingerprint=source_fingerprint,+ stage_label=stage_label,+ note=note,+ )+ steps.append(step)++ trajectory: Dict[str, Any] = dict(existing)+ trajectory.update(+ _clean_none_fields(+ {+ "protocol_version": TRAJECTORY_PROTOCOL_VERSION,+ "software": software,+ "recipe": recipe,+ "session_name": session_name or session_path.name,+ "project_path": project_path,+ "project_name": project_name,+ "created_at": existing.get("created_at", finished_at),+ "updated_at": finished_at,+ "step_count": len(steps),+ "current_step_id": step_id,+ }+ )+ )+ trajectory["steps"] = steps+ trajectory_path = write_json(str(live_trajectory_path(session_path)), trajectory)+ trajectory["_trajectory_path"] = trajectory_path+ trajectory["latest_step"] = step+ return trajectorydiff --git a/shotcut/agent-harness/cli_anything/shotcut/README.md b/shotcut/agent-harness/cli_anything/shotcut/README.mdindex b9d8cb401..4d1960881 100644--- a/shotcut/agent-harness/cli_anything/shotcut/README.md+++ b/shotcut/agent-harness/cli_anything/shotcut/README.md@@ -263,6 +263,40 @@ Add `--json` before the subcommand for machine-readable output:python3 -m cli.shotcut_cli --json --project p.mlt timeline clips 1```+## Preview and Live Preview++Shotcut supports both static preview bundles and live preview sessions.++```bash+# Capture a low-res preview bundle+cli-anything-shotcut --json --project edit.mlt preview capture --recipe quick++# Start poll-mode live preview+cli-anything-shotcut --json --project edit.mlt preview live start --recipe quick --mode poll --source-poll-ms 500++# Query the current live session without rendering+cli-anything-shotcut --json --project edit.mlt preview live status --recipe quick+```++The default `quick` bundle contains:++- `preview.mp4`+- sampled frames+- midpoint `hero.png`+- `summary.json`++Live preview persists `session.json`, immutable bundle dirs, and+`trajectory.json`.++Inspect or open published preview state with:++```bash+cli-hub previews inspect /path/to/bundle-or-session+cli-hub previews html /path/to/bundle-or-session -o page.html+cli-hub previews watch /path/to/session --open+cli-hub previews open /path/to/bundle-or-session+```+## Running Tests```bashdiff --git a/shotcut/agent-harness/cli_anything/shotcut/core/preview.py b/shotcut/agent-harness/cli_anything/shotcut/core/preview.pyindex 1eefc1413..9c67399f8 100644--- a/shotcut/agent-harness/cli_anything/shotcut/core/preview.py+++ b/shotcut/agent-harness/cli_anything/shotcut/core/preview.py@@ -13,12 +13,17 @@ from typing import Any, Dict, List, Optionalfrom ..utils import mlt_xmlfrom ..utils.preview_bundle import (+ append_live_trajectory,artifact_record,+ build_live_history_item,finalize_bundle,find_latest_manifest,fingerprint_data,fingerprint_file,+ live_trajectory_path,+ load_live_trajectory,prepare_bundle,+ summarize_trajectory,)from . import export as export_modfrom . import media as media_mod@@ -70,6 +75,13 @@ def _seconds_to_timecode(seconds: float) -> str:def _project_fingerprint(session: Session) -> str:if not session.is_open:raise RuntimeError("No project is open")+ if session.project_path and not session.is_modified and os.path.isfile(session.project_path):+ return fingerprint_data(+ {+ "project_path": os.path.abspath(session.project_path),+ "project_file": fingerprint_file(session.project_path),+ }+ )payload: Dict[str, Any] = {"project_path": os.path.abspath(session.project_path) if session.project_path else "","xml": mlt_xml.mlt_to_string(session.root),@@ -214,7 +226,7 @@ def capture("warnings": warnings,"next_actions": ["Inspect the preview clip for pacing, timing, and cut order.",- "Use cli-hub preview html on the bundle for a richer inspection page.",+ "Use cli-hub previews html on the bundle for a richer inspection page.",],}@@ -376,6 +388,9 @@ def _terminate_pid(pid: Any) -> bool:def _with_live_refs(session_dir: Path, payload: Dict[str, Any]) -> Dict[str, Any]:payload["_session_dir"] = str(session_dir.resolve())payload["_session_path"] = str((session_dir / "session.json").resolve())+ trajectory_path = live_trajectory_path(session_dir)+ if trajectory_path.is_file():+ payload["_trajectory_path"] = str(trajectory_path.resolve())return payload@@ -408,15 +423,7 @@ def _update_current_symlink(session_dir: Path, bundle_dir: str) -> Path:def _history_item(bundle_manifest: Dict[str, Any]) -> Dict[str, Any]:- return {- "bundle_id": bundle_manifest.get("bundle_id"),- "bundle_dir": bundle_manifest.get("_bundle_dir"),- "manifest_path": bundle_manifest.get("_manifest_path"),- "summary_path": bundle_manifest.get("_summary_path"),- "created_at": bundle_manifest.get("created_at"),- "status": bundle_manifest.get("status"),- "cached": bool(bundle_manifest.get("cached")),- }+ return build_live_history_item(bundle_manifest)def _publish_live_session(@@ -429,6 +436,7 @@ def _publish_live_session(live_mode: Optional[str] = None,source_poll_ms: int = DEFAULT_SOURCE_POLL_MS,publish_reason: str = "manual",+ command: Optional[str] = None,) -> Dict[str, Any]:session_dir = _live_session_dir(session, recipe, root_dir=root_dir)session_dir.mkdir(parents=True, exist_ok=True)@@ -436,7 +444,20 @@ def _publish_live_session(existing = _load_existing_live_session(session_dir)now = _now_iso()- current_item = _history_item(bundle_manifest)+ trajectory = append_live_trajectory(+ session_dir,+ software="shotcut",+ recipe=recipe,+ bundle_manifest=bundle_manifest,+ publish_reason=publish_reason,+ project_path=session.project_path,+ project_name=Path(session.project_path).name if session.project_path else "untitled",+ session_name=session_dir.name,+ command=command,+ command_started_at=now,+ command_finished_at=now,+ )+ current_item = dict(trajectory.get("latest_step") or _history_item(bundle_manifest))history = [current_item]for item in existing.get("history", []):if item.get("bundle_id") == current_item["bundle_id"]:@@ -462,6 +483,7 @@ def _publish_live_session(source_state["last_rendered_fingerprint"] = project_file_fingerprintsource_state["last_rendered_at"] = nowsource_state["last_publish_reason"] = publish_reason+ trajectory_rel = os.path.relpath(Path(trajectory["_trajectory_path"]).resolve(), session_dir)payload = {"protocol_version": LIVE_PROTOCOL_VERSION,@@ -486,16 +508,22 @@ def _publish_live_session("current_cached": bool(bundle_manifest.get("cached")),"bundle_count": len(history),"history": history,+ "trajectory_path": trajectory_rel,+ "trajectory_protocol_version": trajectory.get("protocol_version"),+ "trajectory_step_count": trajectory.get("step_count", 0),+ "current_step_id": trajectory.get("current_step_id"),+ "latest_command": current_item.get("command"),+ "latest_publish_reason": current_item.get("publish_reason", publish_reason),"source_state": source_state,"poller": poller,"publish_command": (f"cli-anything-shotcut{project_flag} preview live push --recipe {recipe}{root_flag}").strip(),"watch_command": (- f"cli-hub preview watch {session_dir} --open --poll-ms {int(refresh_hint_ms)}"+ f"cli-hub previews watch {session_dir} --open --poll-ms {int(refresh_hint_ms)}"),- "inspect_command": f"cli-hub preview inspect {session_dir}",- "html_command": f"cli-hub preview html {session_dir}",+ "inspect_command": f"cli-hub previews inspect {session_dir}",+ "html_command": f"cli-hub previews html {session_dir}","start_command": (f"cli-anything-shotcut{project_flag} preview live start --recipe {recipe} "f"--mode {current_live_mode} --source-poll-ms {current_source_poll_ms}{root_flag}"@@ -504,10 +532,8 @@ def _publish_live_session(f"cli-anything-shotcut preview live monitor --session-dir {session_dir}"),}- session_path = _write_json(session_dir / "session.json", payload)- payload["_session_dir"] = str(session_dir.resolve())- payload["_session_path"] = str(session_path.resolve())- return payload+ _write_json(session_dir / "session.json", payload)+ return _with_live_refs(session_dir, payload)def live_start(@@ -543,6 +569,7 @@ def live_start(live_mode=live_mode,source_poll_ms=source_poll_ms,publish_reason=publish_reason,+ command=command,)live_payload["bundle"] = {"bundle_id": bundle_manifest.get("bundle_id"),@@ -599,6 +626,9 @@ def live_status(if poller:poller["running"] = _pid_is_running(poller.get("pid"))payload["poller"] = poller+ trajectory = load_live_trajectory(session_dir)+ if trajectory:+ payload["trajectory_summary"] = summarize_trajectory(trajectory)return _with_live_refs(session_dir, payload)diff --git a/shotcut/agent-harness/cli_anything/shotcut/shotcut_cli.py b/shotcut/agent-harness/cli_anything/shotcut/shotcut_cli.pyindex fed298ffe..35a364173 100755--- a/shotcut/agent-harness/cli_anything/shotcut/shotcut_cli.py+++ b/shotcut/agent-harness/cli_anything/shotcut/shotcut_cli.py@@ -69,7 +69,7 @@ def _spawn_live_viewer(session_dir: str, poll_ms: int) -> dict:hub = shutil.which("cli-hub")command = [hub or "cli-hub",- "preview",+ "previews","watch",session_dir,"--open",diff --git a/shotcut/agent-harness/cli_anything/shotcut/skills/SKILL.md b/shotcut/agent-harness/cli_anything/shotcut/skills/SKILL.mdindex 74f20ed60..9dba2279f 100644--- a/shotcut/agent-harness/cli_anything/shotcut/skills/SKILL.md+++ b/shotcut/agent-harness/cli_anything/shotcut/skills/SKILL.md@@ -212,6 +212,45 @@ Session management: status, undo, redo.| `save` | Save session state to disk || `list` | List all saved sessions |+### Preview++Preview bundles and live preview sessions for iterative editing review.++| Command | Description |+|---------|-------------|+| `preview recipes` | List preview recipes |+| `preview capture` | Render a low-res preview bundle |+| `preview latest` | Return the latest existing bundle |+| `preview live start` | Start a live preview session and publish the first bundle |+| `preview live push` | Publish a new bundle into the live session |+| `preview live status` | Query current live-session state without rendering |+| `preview live stop` | Stop the live session without deleting artifacts |++Typical `quick` bundle contents:++- `preview.mp4`+- several sampled frames+- midpoint `hero.png`+- `summary.json` with project facts++Poll mode is supported:++```bash+cli-anything-shotcut --json --project edit.mlt preview live start --recipe quick --mode poll --source-poll-ms 500+```++`preview live status --json` includes session refs and a compact+`trajectory_summary` so agents can cheaply understand the latest few publishes.++Viewer commands:++```bash+cli-hub previews inspect /path/to/bundle-or-session+cli-hub previews html /path/to/bundle-or-session -o page.html+cli-hub previews watch /path/to/session --open+cli-hub previews open /path/to/bundle-or-session+```+@@ -316,6 +355,10 @@ When using this CLI programmatically:5. **Verify outputs exist** after export operations6. **Prefer `timeline add-clip --at`** when recreating a known edit7. **Review final renders** after keyframed volume or ducking changes+8. **Use `preview capture` or `preview live ...` to validate pacing, cuts, and filter effects visually**+9. **Read returned artifact paths** such as `hero.png` and `preview.mp4`; JSON payloads reference files on disk+10. **Use `preview live status --json` before reading the full `trajectory.json`**+11. **Use `cli-hub previews ...` only to inspect/open existing bundles or live sessions**## More Information@@ -325,4 +368,4 @@ When using this CLI programmatically:## Version-1.0.0\ No newline at end of file+1.0.0diff --git a/shotcut/agent-harness/cli_anything/shotcut/tests/test_core.py b/shotcut/agent-harness/cli_anything/shotcut/tests/test_core.pyindex 892e77167..44b172682 100644--- a/shotcut/agent-harness/cli_anything/shotcut/tests/test_core.py+++ b/shotcut/agent-harness/cli_anything/shotcut/tests/test_core.py@@ -477,7 +477,12 @@ class TestPreview:assert live["source_state"]["project_path"] == str(project_path)assert live["source_state"]["last_rendered_fingerprint"].startswith("sha256:")assert Path(live["_session_path"]).is_file()+ assert Path(live["_trajectory_path"]).is_file()assert (Path(live["_session_dir"]) / "current" / "manifest.json").is_file()+ trajectory = json.loads(Path(live["_trajectory_path"]).read_text(encoding="utf-8"))+ assert trajectory["step_count"] == 1+ assert trajectory["steps"][0]["bundle_id"] == "bundle-a"+ assert live["trajectory_step_count"] == 1def test_live_push_updates_history(self, tmp_path, monkeypatch):session = Session("preview_live")@@ -499,6 +504,54 @@ class TestPreview:assert pushed["current_bundle_id"] == "bundle-b"assert pushed["history"][0]["bundle_id"] == "bundle-b"assert pushed["history"][1]["bundle_id"] == "bundle-a"+ trajectory = json.loads(Path(pushed["_trajectory_path"]).read_text(encoding="utf-8"))+ assert trajectory["step_count"] == 2+ assert [step["bundle_id"] for step in trajectory["steps"]] == ["bundle-a", "bundle-b"]+ assert pushed["current_step_id"] == "step-0002"++ def test_live_status_includes_trajectory_summary(self, tmp_path, monkeypatch):+ session = Session("preview_live")+ session.new_project()+ project_path = tmp_path / "live-demo.mlt"+ session.save_project(str(project_path))+ bundle_manifest = self._fake_bundle(tmp_path / "bundles", "bundle-a")++ monkeypatch.setattr(preview_mod, "capture", lambda *args, **kwargs: dict(bundle_manifest))++ preview_mod.live_start(session, root_dir=str(tmp_path), live_mode="manual")+ status = preview_mod.live_status(session, root_dir=str(tmp_path))+ summary = status["trajectory_summary"]+ assert summary["step_count"] == 1+ assert summary["latest_bundle_id"] == "bundle-a"+ assert summary["latest_publish_reason"] == "live-start"+ assert summary["recent_steps"][0]["step_id"] == "step-0001"++ def test_live_push_records_publish_time_when_bundle_is_reused(self, tmp_path, monkeypatch):+ session = Session("preview_live")+ session.new_project()+ project_path = tmp_path / "live-demo.mlt"+ session.save_project(str(project_path))+ bundle_manifest = self._fake_bundle(tmp_path / "bundles", "bundle-a")+ bundle_manifest["created_at"] = "2025-01-01T00:00:00Z"+ publish_times = [+ "2026-04-23T10:00:00Z",+ "2026-04-23T10:05:00Z",+ ]++ monkeypatch.setattr(preview_mod, "capture", lambda *args, **kwargs: dict(bundle_manifest))+ monkeypatch.setattr(preview_mod, "_now_iso", lambda: publish_times.pop(0))++ preview_mod.live_start(session, root_dir=str(tmp_path), live_mode="manual")+ pushed = preview_mod.live_push(session, root_dir=str(tmp_path))+ trajectory = json.loads(Path(pushed["_trajectory_path"]).read_text(encoding="utf-8"))++ assert len(pushed["history"]) == 1+ assert [step["bundle_id"] for step in trajectory["steps"]] == ["bundle-a", "bundle-a"]+ assert [step["command_finished_at"] for step in trajectory["steps"]] == [+ "2026-04-23T10:00:00Z",+ "2026-04-23T10:05:00Z",+ ]+ assert all(step["created_at"] == "2025-01-01T00:00:00Z" for step in trajectory["steps"])def test_live_stop_marks_session_stopped(self, tmp_path, monkeypatch):session = Session("preview_live")@@ -572,11 +625,14 @@ class TestPreview:result = preview_mod.poll_live_session_once(str(started_session_dir))refreshed = json.loads(Path(started["_session_path"]).read_text())+ trajectory = json.loads(Path(started["_session_dir"]).joinpath("trajectory.json").read_text())assert result["action"] == "captured"assert refreshed["current_bundle_id"] == "bundle-b"assert refreshed["source_state"]["last_rendered_fingerprint"].startswith("sha256:")assert refreshed["poller"]["last_capture_status"] == "ok"assert calls+ assert trajectory["step_count"] == 2+ assert trajectory["steps"][-1]["publish_reason"] == "auto-poll"def test_poll_live_session_once_exits_for_manual_mode(self, tmp_path, monkeypatch):session = Session("preview_live")diff --git a/shotcut/agent-harness/cli_anything/shotcut/utils/preview_bundle.py b/shotcut/agent-harness/cli_anything/shotcut/utils/preview_bundle.pyindex 3cba5dbf0..0028cc295 100644--- a/shotcut/agent-harness/cli_anything/shotcut/utils/preview_bundle.py+++ b/shotcut/agent-harness/cli_anything/shotcut/utils/preview_bundle.py@@ -12,6 +12,7 @@ from pathlib import Pathfrom typing import Any, Dict, Iterable, OptionalPROTOCOL_VERSION = "preview-bundle/v1"+TRAJECTORY_PROTOCOL_VERSION = "preview-trajectory/v1"def _slug(value: str) -> str:@@ -123,6 +124,9 @@ def find_cached_manifest():manifest["_manifest_path"] = str(manifest_path.resolve())manifest["_bundle_dir"] = str(manifest_path.parent.resolve())+ manifest["_summary_path"] = str(+ (manifest_path.parent / manifest.get("summary_path", "summary.json")).resolve()+ )return manifestreturn None@@ -157,6 +161,9 @@ def find_latest_manifest(continuemanifest["_manifest_path"] = str(manifest_path.resolve())manifest["_bundle_dir"] = str(manifest_path.parent.resolve())+ manifest["_summary_path"] = str(+ (manifest_path.parent / manifest.get("summary_path", "summary.json")).resolve()+ )return manifestreturn None@@ -302,3 +309,160 @@ def finalize_bundle(manifest["_bundle_dir"] = str(bundle_path)manifest["_summary_path"] = summary_pathreturn manifest+++def _clean_none_fields(data: Dict[str, Any]) -> Dict[str, Any]:+ return {key: value for key, value in data.items() if value is not None}+++def live_trajectory_path(session_dir: str | Path) -> Path:+ return Path(session_dir).expanduser().resolve() / "trajectory.json"+++def load_live_trajectory(session_dir: str | Path) -> Dict[str, Any]:+ trajectory_path = live_trajectory_path(session_dir)+ if not trajectory_path.is_file():+ return {}+ return _load_json(trajectory_path)+++def summarize_trajectory(trajectory: Dict[str, Any], *, recent_steps: int = 3) -> Dict[str, Any]:+ steps = list(trajectory.get("steps") or [])+ latest = steps[-1] if steps else {}+ recent = steps[-max(1, int(recent_steps)):] if steps else []+ return _clean_none_fields(+ {+ "protocol_version": trajectory.get("protocol_version"),+ "software": trajectory.get("software"),+ "recipe": trajectory.get("recipe"),+ "step_count": trajectory.get("step_count", len(steps)),+ "current_step_id": trajectory.get("current_step_id"),+ "latest_command": latest.get("command"),+ "latest_publish_reason": latest.get("publish_reason"),+ "latest_bundle_id": latest.get("bundle_id"),+ "recent_steps": [+ _clean_none_fields(+ {+ "step_id": item.get("step_id"),+ "step_index": item.get("step_index"),+ "bundle_id": item.get("bundle_id"),+ "publish_reason": item.get("publish_reason"),+ "command": item.get("command"),+ "command_finished_at": item.get("command_finished_at"),+ "status": item.get("status"),+ "cached": item.get("cached"),+ }+ )+ for item in recent+ ],+ }+ )+++def build_live_history_item(+ bundle_manifest: Dict[str, Any],+ *,+ step_id: Optional[str] = None,+ step_index: Optional[int] = None,+ publish_reason: Optional[str] = None,+ command: Optional[str] = None,+ command_started_at: Optional[str] = None,+ command_finished_at: Optional[str] = None,+ source_fingerprint: Optional[str] = None,+ stage_label: Optional[str] = None,+ note: Optional[str] = None,+) -> Dict[str, Any]:+ source = bundle_manifest.get("source") or {}+ resolved_command = command or (bundle_manifest.get("generator") or {}).get("command")+ resolved_fingerprint = (+ source_fingerprint+ or source.get("project_fingerprint")+ or source.get("capture_fingerprint")+ )+ created_at = bundle_manifest.get("created_at")+ return _clean_none_fields(+ {+ "step_id": step_id,+ "step_index": step_index,+ "bundle_id": bundle_manifest.get("bundle_id"),+ "bundle_dir": bundle_manifest.get("_bundle_dir"),+ "manifest_path": bundle_manifest.get("_manifest_path"),+ "summary_path": bundle_manifest.get("_summary_path"),+ "created_at": created_at,+ "status": bundle_manifest.get("status"),+ "cached": bool(bundle_manifest.get("cached")),+ "publish_reason": publish_reason,+ "command": resolved_command,+ "command_started_at": command_started_at or created_at,+ "command_finished_at": command_finished_at or created_at,+ "source_fingerprint": resolved_fingerprint,+ "stage_label": stage_label,+ "note": note,+ }+ )+++def append_live_trajectory(+ session_dir: str | Path,+ *,+ software: str,+ recipe: str,+ bundle_manifest: Dict[str, Any],+ publish_reason: str,+ project_path: Optional[str] = None,+ project_name: Optional[str] = None,+ session_name: Optional[str] = None,+ command: Optional[str] = None,+ command_started_at: Optional[str] = None,+ command_finished_at: Optional[str] = None,+ source_fingerprint: Optional[str] = None,+ stage_label: Optional[str] = None,+ note: Optional[str] = None,+) -> Dict[str, Any]:+ session_path = Path(session_dir).expanduser().resolve()+ existing = load_live_trajectory(session_path)+ steps = list(existing.get("steps") or [])+ finished_at = (+ command_finished_at+ or bundle_manifest.get("created_at")+ or datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")+ )+ started_at = command_started_at or finished_at+ step_index = len(steps) + 1+ step_id = f"step-{step_index:04d}"+ step = build_live_history_item(+ bundle_manifest,+ step_id=step_id,+ step_index=step_index,+ publish_reason=publish_reason,+ command=command,+ command_started_at=started_at,+ command_finished_at=finished_at,+ source_fingerprint=source_fingerprint,+ stage_label=stage_label,+ note=note,+ )+ steps.append(step)++ trajectory: Dict[str, Any] = dict(existing)+ trajectory.update(+ _clean_none_fields(+ {+ "protocol_version": TRAJECTORY_PROTOCOL_VERSION,+ "software": software,+ "recipe": recipe,+ "session_name": session_name or session_path.name,+ "project_path": project_path,+ "project_name": project_name,+ "created_at": existing.get("created_at", finished_at),+ "updated_at": finished_at,+ "step_count": len(steps),+ "current_step_id": step_id,+ }+ )+ )+ trajectory["steps"] = steps+ trajectory_path = write_json(str(live_trajectory_path(session_path)), trajectory)+ trajectory["_trajectory_path"] = trajectory_path+ trajectory["latest_step"] = step+ return trajectorydiff --git a/skills/cli-anything-blender/SKILL.md b/skills/cli-anything-blender/SKILL.mdindex b4a3c1422..7676fb46f 100644--- a/skills/cli-anything-blender/SKILL.md+++ b/skills/cli-anything-blender/SKILL.md@@ -1,5 +1,6 @@----name: "cli-anything-blender"+name: >-+ cli-anything-blenderdescription: >-Command-line interface for Blender - A stateful command-line interface for 3D scene editing, following the same patterns as the GIMP CLI ...---@@ -32,11 +33,11 @@ cli-anything-blender --help# Start interactive REPL modecli-anything-blender-# Create a new project-cli-anything-blender project new -o project.json+# Create a new scene project+cli-anything-blender scene new -o scene.blend-cli.json# Run with JSON output (for agent consumption)-cli-anything-blender --json project info -p project.json+cli-anything-blender --json --project scene.blend-cli.json scene info```### REPL Mode@@ -156,6 +157,38 @@ Render settings and output commands.| `execute` | Render the scene (generates bpy script) || `script` | Generate bpy script without rendering |+### Preview++Real preview bundle capture and live preview session commands.++| Command | Description |+|---------|-------------|+| `preview recipes` | List available preview recipes |+| `preview capture` | Render a real preview bundle for the active scene |+| `preview latest` | Return the latest existing preview bundle |+| `preview live start` | Start a live preview session and publish the first bundle |+| `preview live push` | Publish a refreshed bundle into the live session |+| `preview live status` | Read current live-session state without rendering |+| `preview live stop` | Stop the live session without deleting artifacts |++Typical bundle artifacts for recipe `quick`:++- `hero.png` from real Eevee preview rendering+- `workbench.png` from real Blender Workbench rendering++Live sessions persist:++- `session.json` as the mutable head+- immutable bundle directories+- `trajectory.json` as append-only command-to-preview history++Viewer side:++- `cli-hub previews inspect <bundle-or-session>`+- `cli-hub previews html <bundle-or-session> -o page.html`+- `cli-hub previews watch <session-dir> --open`+- `cli-hub previews open <bundle-or-session>`+### Session@@ -176,12 +209,12 @@ Session management commands.### Create a New Project-Create a new blender project file.+Create a new Blender scene project file.```bash-cli-anything-blender project new -o myproject.json+cli-anything-blender scene new -o myscene.blend-cli.json# Or with JSON output for programmatic use-cli-anything-blender --json project new -o myproject.json+cli-anything-blender --json scene new -o myscene.blend-cli.json```@@ -214,12 +247,34 @@ All commands support dual output modes:```bash# Human output-cli-anything-blender project info -p project.json+cli-anything-blender --project scene.blend-cli.json scene info# JSON output for agents-cli-anything-blender --json project info -p project.json+cli-anything-blender --json --project scene.blend-cli.json scene info+```++## Preview Workflow++Use Blender previews when the agent needs truthful visual checkpoints:++```bash+# List preview recipes+cli-anything-blender --project scene.blend-cli.json preview recipes++# Capture a real preview bundle+cli-anything-blender --json --project scene.blend-cli.json preview capture --recipe quick++# Start a live preview loop+cli-anything-blender --json --project scene.blend-cli.json preview live start --recipe quick --mode poll --source-poll-ms 500++# Query current live head without rendering+cli-anything-blender --json --project scene.blend-cli.json preview live status --recipe quick```+For agents, `preview capture --json` returns bundle metadata plus artifact file+paths. `preview live status --json` returns session metadata plus a compact+`trajectory_summary`.+## For AI AgentsWhen using this CLI programmatically:@@ -228,7 +283,10 @@ When using this CLI programmatically:2. **Check return codes** - 0 for success, non-zero for errors3. **Parse stderr** for error messages on failure4. **MANDATORY: Use absolute paths** for all file operations (rendering, project files). Relative paths are prone to failure in background execution.-5. **Verify outputs exist** after export operations+5. **Use `preview capture` or `preview live ...` for visual verification** instead of inferring scene quality from JSON alone+6. **Read returned artifact paths** such as `hero.png` and `workbench.png`; the JSON payload references files, it does not inline image bytes+7. **Treat `_bundle_dir` as one snapshot only**; for stable live history, use `_session_dir` plus `_trajectory_path`+8. **Use `cli-hub previews ...` only to inspect/open existing previews**; preview generation itself always happens through `cli-anything-blender preview ...`## More Information@@ -238,4 +296,4 @@ When using this CLI programmatically:## Version-1.0.0\ No newline at end of file+1.0.0diff --git a/skills/cli-anything-freecad/SKILL.md b/skills/cli-anything-freecad/SKILL.mdindex 58d4a3451..10595b0b2 100644--- a/skills/cli-anything-freecad/SKILL.md+++ b/skills/cli-anything-freecad/SKILL.md@@ -25,6 +25,64 @@ cli-anything-freecad --json -p proj.json <cmd> # With project filecli-anything-freecad # Interactive REPL```+## Preview, Live Preview, and Motion++FreeCAD is currently the deepest preview integration in this branch.++Preview commands:++```bash+# List preview recipes+cli-anything-freecad --json -p proj.json preview recipes++# Capture a real 4-view bundle+cli-anything-freecad --json -p proj.json preview capture --recipe quick++# Start poll-mode live preview+cli-anything-freecad --json -p proj.json preview live start --recipe quick --mode poll --source-poll-ms 500++# Query current live state without rendering+cli-anything-freecad --json -p proj.json preview live status --recipe quick++# Stop live preview publication+cli-anything-freecad --json -p proj.json preview live stop --recipe quick+```++Typical `quick` bundle artifacts:++- `hero.png`+- `front.png`+- `top.png`+- `right.png`++Live preview persists:++- `session.json`+- immutable bundle directories+- `trajectory.json`++`preview live status --json` is intended for agents and includes a compact+`trajectory_summary` in addition to `_session_dir`, current bundle refs, and+`_trajectory_path`.++Viewer commands:++```bash+cli-hub previews inspect /path/to/bundle-or-session+cli-hub previews html /path/to/bundle-or-session -o page.html+cli-hub previews watch /path/to/session --open+cli-hub previews open /path/to/bundle-or-session+```++Motion commands remain separate from preview and are used for final truthful+frame rendering and showcase videos:++```bash+cli-anything-freecad --json -p proj.json motion new --name spin --duration 6 --fps 24+cli-anything-freecad --json -p proj.json motion keyframe spin --time 0.0 --part 0 --position 0,0,0+cli-anything-freecad --json -p proj.json motion render-video spin output.mp4+```+## Command Groups (258 commands)### document (5) β Document management@@ -253,3 +311,14 @@ All commands support `--json`. Responses include structured data. Errors: `{"err- Invalid types: Lists valid options- Index out of range: Reports valid range- File exists: Use `--overwrite`++## Agent Preview Notes++- Use `preview capture --json` whenever geometric changes need visual verification.+- Use `preview live start` for iterative build loops; prefer poll mode when the+ project file is being saved repeatedly.+- Use `preview live status --json` as the cheap status probe before reading the+ full `trajectory.json`.+- Treat `_bundle_dir` as a single snapshot only; the stable live identity is+ `_session_dir` plus `_trajectory_path`.+- Use `cli-hub previews ...` only to inspect/open already-published previews.diff --git a/skills/cli-anything-openscreen/SKILL.md b/skills/cli-anything-openscreen/SKILL.mdindex 7797f642c..a152e81d5 100644--- a/skills/cli-anything-openscreen/SKILL.md+++ b/skills/cli-anything-openscreen/SKILL.md@@ -1,5 +1,6 @@----name: "cli-anything-openscreen"+name: >-+ cli-anything-openscreendescription: >-Command-line interface for Openscreen β a screen recording editor.A stateful CLI for editing screen recordings with zoom, speed ramps,@@ -127,6 +128,35 @@ Render the final polished video.| `export presets` | List available export presets || `export render <output_path>` | Render project to video file |+### preview++Capture truthful review bundles from the current Openscreen project.++| Command | Description |+|---------|-------------|+| `preview recipes` | List available preview recipes |+| `preview capture --recipe quick` | Render a low-res preview bundle |+| `preview latest [--recipe quick]` | Return the latest existing bundle |++Current preview support is static rather than live. A `quick` bundle typically+contains:++- a low-res preview clip+- sampled frames+- a `hero` frame for quick inspection+- `summary.json` with trim/zoom/speed facts++Bundle capture also writes or updates a stable recipe-level `trajectory.json`+beside the preview root so agents can reconstruct preview history over time.++Viewer commands:++```bash+cli-hub previews inspect /path/to/bundle+cli-hub previews html /path/to/bundle -o page.html+cli-hub previews open /path/to/bundle+```+### sessionManage session state with undo/redo.@@ -172,6 +202,9 @@ Manage session state with undo/redo.5. After `export render`, verify the output exists and probe it6. Times are in **milliseconds** for all region commands7. Coordinates (focus, crop, position) are **normalized 0-1**+8. Use `preview capture --json` to validate zoom, trim, annotation, and timing visually+9. Read returned bundle artifact paths from the JSON payload; images and clips live on disk+10. Use `cli-hub previews ...` only to inspect/open existing bundles## Versiondiff --git a/skills/cli-anything-renderdoc/SKILL.md b/skills/cli-anything-renderdoc/SKILL.mdindex 958b473b9..f6332f4e4 100644--- a/skills/cli-anything-renderdoc/SKILL.md+++ b/skills/cli-anything-renderdoc/SKILL.md@@ -1,5 +1,5 @@----name: "cli-anything-renderdoc"+name: cli-anything-renderdocdescription: CLI harness for RenderDoc graphics debugger capture analysisversion: 0.1.0command: cli-anything-renderdoc@@ -96,6 +96,50 @@ cli-anything-renderdoc -c frame.rdc counters listcli-anything-renderdoc -c frame.rdc counters fetch --ids 1,2,3```+## Preview Bundles++RenderDoc preview support is for truthful capture inspection rather than live+creative preview.++```bash+# List preview recipes+cli-anything-renderdoc -c frame.rdc --json preview recipes++# Capture a preview bundle for the active capture or a specific event+cli-anything-renderdoc -c frame.rdc --json preview capture --recipe quick --event-id 42++# Capture a diff preview bundle for two events or captures+cli-anything-renderdoc -c frame.rdc --json preview diff 100 200+cli-anything-renderdoc -c a.rdc --json preview diff 100 200 --capture-b b.rdc++# Return the latest existing bundle for the capture+cli-anything-renderdoc -c frame.rdc --json preview latest --recipe quick+```++Typical preview bundle contents:++- capture thumbnail+- output-target images+- `pipeline_state.json`+- `action_summary.json`++Diff bundles additionally include:++- A/B thumbnails+- A/B output-target images+- `pipeline_diff.json`++RenderDoc does not currently expose live preview sessions. Instead, each+capture/diff bundle appends to a stable recipe-level `trajectory.json`.++Viewer commands:++```bash+cli-hub previews inspect /path/to/bundle+cli-hub previews html /path/to/bundle -o page.html+cli-hub previews open /path/to/bundle+```+## JSON ModeAll commands support `--json` for machine-readable output:@@ -121,6 +165,10 @@ cli-anything-renderdoc -c frame.rdc --json actions summary- Always specify `--json` for programmatic consumption- Use `actions summary` first to understand capture complexity- Use `actions list --draws-only` to focus on actual rendering+- Use `preview capture` or `preview diff` when the agent needs a portable,+ honest inspection bundle rather than raw replay calls alone+- Read `_trajectory_path` from preview JSON if you need persistent capture/diff history+- Use `cli-hub previews ...` only to inspect/open already-generated bundles- Pipeline state requires an event ID from the action list- Texture save supports: png, jpg, bmp, tga, hdr, exr, dds- Buffer data can be decoded as hex, float32, uint32, or raw bytesdiff --git a/skills/cli-anything-shotcut/SKILL.md b/skills/cli-anything-shotcut/SKILL.mdindex 74f20ed60..61e81141a 100644--- a/skills/cli-anything-shotcut/SKILL.md+++ b/skills/cli-anything-shotcut/SKILL.md@@ -1,5 +1,6 @@----name: "cli-anything-shotcut"+name: >-+ cli-anything-shotcutdescription: >-Command-line interface for Shotcut - A stateful command-line interface for video editing, built on the MLT XML format. Designed for AI ag...---@@ -212,6 +213,45 @@ Session management: status, undo, redo.| `save` | Save session state to disk || `list` | List all saved sessions |+### Preview++Preview bundles and live preview sessions for iterative editing review.++| Command | Description |+|---------|-------------|+| `preview recipes` | List preview recipes |+| `preview capture` | Render a low-res preview bundle |+| `preview latest` | Return the latest existing bundle |+| `preview live start` | Start a live preview session and publish the first bundle |+| `preview live push` | Publish a new bundle into the live session |+| `preview live status` | Query current live-session state without rendering |+| `preview live stop` | Stop the live session without deleting artifacts |++Typical `quick` bundle contents:++- `preview.mp4`+- several sampled frames+- midpoint `hero.png`+- `summary.json` with project facts++Poll mode is supported:++```bash+cli-anything-shotcut --json --project edit.mlt preview live start --recipe quick --mode poll --source-poll-ms 500+```++`preview live status --json` includes session refs and a compact+`trajectory_summary` so agents can cheaply understand the latest few publishes.++Viewer commands:++```bash+cli-hub previews inspect /path/to/bundle-or-session+cli-hub previews html /path/to/bundle-or-session -o page.html+cli-hub previews watch /path/to/session --open+cli-hub previews open /path/to/bundle-or-session+```+@@ -316,6 +356,10 @@ When using this CLI programmatically:5. **Verify outputs exist** after export operations6. **Prefer `timeline add-clip --at`** when recreating a known edit7. **Review final renders** after keyframed volume or ducking changes+8. **Use `preview capture` or `preview live ...` to validate pacing, cuts, and filter effects visually**+9. **Read returned artifact paths** such as `hero.png` and `preview.mp4`; JSON payloads reference files on disk+10. **Use `preview live status --json` before reading the full `trajectory.json`**+11. **Use `cli-hub previews ...` only to inspect/open existing bundles or live sessions**## More Information@@ -325,4 +369,4 @@ When using this CLI programmatically:## Version-1.0.0\ No newline at end of file+1.0.0diff --git a/skills/cli-hub-meta-skill/SKILL.md b/skills/cli-hub-meta-skill/SKILL.mdindex 6e89c6362..148f9f83e 100644--- a/skills/cli-hub-meta-skill/SKILL.md+++ b/skills/cli-hub-meta-skill/SKILL.md@@ -38,6 +38,7 @@ The catalog is auto-updated and provides:- One-line `cli-hub install` commands for each tool- Complete descriptions and usage patterns+## What Can You Do?CLI-Hub covers a broad range of software and codebases, empowering agents to conduct complex workflows via CLI:@@ -55,6 +56,32 @@ Each CLI provides stateful operations, JSON output for agents, REPL mode, and in`cli-hub` is a lightweight wrapper around `pip`. When you run `cli-hub install gimp`, it installs a separate Python package (`cli-anything-gimp`) with its own CLI entry point (`cli-anything-gimp`). Each CLI is an independent pip package β `cli-hub` simply resolves names from the registry and tracks installs.+## Preview Consumption++Some installed harnesses also support preview workflows. The command split is:++- `cli-anything-<software> preview ...` creates or updates real preview artifacts+- `cli-hub previews ...` inspects, renders, watches, or opens those existing artifacts++Use:++```bash+# From the harness side: publish preview state+cli-anything-blender --json --project scene.blend-cli.json preview capture --recipe quick++# From cli-hub: inspect or open the resulting bundle or live session+cli-hub previews inspect /path/to/bundle-or-session+cli-hub previews html /path/to/bundle-or-session -o page.html+cli-hub previews watch /path/to/session --open+cli-hub previews open /path/to/bundle-or-session+```++For live sessions, `cli-hub previews` reads:++- `session.json` for the current head+- `trajectory.json` for append-only history+- the current bundle manifest and artifacts+## How to Use1. **Install cli-hub**: `pip install cli-anything-hub`@@ -62,6 +89,8 @@ Each CLI provides stateful operations, JSON output for agents, REPL mode, and in3. **Install**: `cli-hub install <name>` (installs the `cli-anything-<name>` pip package)4. **Run**: `cli-anything-<name>` for REPL, or `cli-anything-<name> <command>` for one-shot5. **JSON output**: All CLIs support `--json` flag for machine-readable output+6. **Preview-capable CLIs**: use `cli-anything-<name> preview ... --json` to publish,+ then `cli-hub previews ...` to inspect or open the result## Example Workflow