Rebuild the object in a reference image as a code-only, procedural, quality-gated, animation-ready Three.js model. Token-efficient image-to-3D.
Python 3dai-agentsclaude-codecomputer-graphicsgenerativeimage-to-3dprocedural-generationthreejstypescriptwebgl
feat: execute plugin gates from the base checklist
kokorolx0bf994e11963
diff --git a/forge/stage3_build/run_gates.py b/forge/stage3_build/run_gates.pynew file mode 100644index 0000000..5a54281--- /dev/null+++ b/forge/stage3_build/run_gates.py@@ -0,0 +1,286 @@+#!/usr/bin/env python3+"""Gate execution (D9, tasks 4.1-4.3, `establish-the-emission-target-contract`).++**Hook point (proposed, per the lead's invitation to propose rather than guess silently):** a new+`FINAL_STEPS` row, `"plugin-gates"`, appended after `"emission-target"` -- not auto-chained inside+`emit_target.py` itself. Every other checklist step in this pipeline (`build-current-pass`,+`render-capture`, ...) is a distinct command the agent invokes one at a time, never auto-triggered+by the step before it; gate execution follows that same discipline. This still satisfies "gates run+after domain steps complete" (a FINAL step runs only once every setup/pass step is done) and "as+part of the emission-target step's post-run" in the sense that it is the very next thing the+checklist asks for, immediately following target selection -- just not chained in-process.++The runner argv is constructed here in Python (task 4.1) -- reusing `_img2_home()`, no `img2`+binary at runtime -- and mirrors `img2.mjs`'s `gateRunnerArgv` (`bin/img2.mjs:807-809`) exactly: the+file-path form, not the module form §13:308 documents (that drift is recorded, not touched here --+it is task 5.5's). A drift-guard test asserts the two never disagree.++The two-clause participation rule (task 4.2, D9): (i) a plugin's gates run when any step it+contributed to THIS workspace's checklist has run -- via `domain.json` or via a selected target+step; (ii) a plugin that contributed no step runs no gates. Clause (i)'s owner lookup+(`domain_owner_plugin`) is derived from the registry layout (`$IMG2_HOME/plugins/<id>/domain.json`)+rather than assumed from a name match -- see its docstring for the earlier, wrong version this+replaced.++Invocation is through the bounded runner from 3.4 (`emit_target.run_bounded`) -- same bounds as+targets, per D9's amendment. The `img2.gate-run` aggregate envelope is parsed per task 4.3:+malformed -> error, never a pass; status/exit disagreement -> error; a blocking fail stops the+WHOLE run (across every involved plugin, not just that plugin's own gates.json), naming the gate+and the plugin.+"""++from __future__ import annotations++import argparse+import json+import os+import sys+from pathlib import Path+from typing import Any++_FORGE_ROOT = Path(__file__).resolve().parent.parent+sys.path[:0] = [str(_FORGE_ROOT), str(_FORGE_ROOT / "_shared")]++from domains import DomainRegistryError, domain_profile # noqa: E402+from emit_target import EmitTargetError, assert_action_ready, run_bounded # noqa: E402+from workflow_state import WorkflowStateError, load_state # noqa: E402++KIND_RUN = "img2.gate-run"+GATE_TIMEOUT_SECONDS = 300 # same default as gate_runner.py's own DEFAULT_GATE_TIMEOUT_SECONDS+++class GateExecutionError(RuntimeError):+ """A gate-execution run was refused or failed. `classification` distinguishes a structural+ problem (malformed envelope, exit disagreement -- `"error"`) from a real blocking gate failure+ (`"blocking-stop"`), so a caller can tell "something is broken" from "a plugin's gate said no"."""++ def __init__(self, message: str, *, classification: str = "error") -> None:+ super().__init__(message)+ self.classification = classification+++def _img2_home() -> Path:+ return Path(os.environ.get("IMG2_HOME") or Path.home() / ".img2")+++# ---------------------------------------------------------------- 4.1: argv construction + drift guard++def gate_runner_argv(home: Path, plugin_dir: Path) -> list[str]:+ """Mirrors img2.mjs's `gateRunnerArgv` (`bin/img2.mjs:807-809`) exactly. `{workspace}` is left+ as its own argv element for the caller to replace by value -- same discipline as `stepArgv`."""+ return [+ "python3", str(home / "harness" / "img2_core" / "gate_runner.py"),+ "--plugin-dir", str(plugin_dir), "--workspace", "{workspace}",+ ]+++# ---------------------------------------------------------------- registry enumeration++def _installed_plugins_with_gates(home: Path) -> list[tuple[str, Path]]:+ registry = home / "plugins.json"+ if not registry.is_file():+ return []+ try:+ rows = json.loads(registry.read_text(encoding="utf-8")).get("plugins") or []+ except (OSError, json.JSONDecodeError) as exc:+ raise GateExecutionError(f"cannot read the plugin registry at {registry}: {exc}") from exc+ out: list[tuple[str, Path]] = []+ for row in rows:+ plugin_id = (row or {}).get("id")+ if not plugin_id:+ continue+ plugin_dir = home / "plugins" / plugin_id+ if (plugin_dir / "gates.json").is_file():+ out.append((plugin_id, plugin_dir))+ return sorted(out, key=lambda pair: pair[0])+++# ---------------------------------------------------------------- 4.2: the two-clause participation rule++def domain_step_ids(profile: str, home: Path) -> tuple[str, ...]:+ """Every step id the resolved domain profile contributes (setupSteps + passSteps ids), or ()+ for 'generic'. Propagates `DomainRegistryError` for an unregistered profile -- the caller+ decides what "unknown" means for participation, this does not silently swallow it."""+ domain = domain_profile(profile)+ if domain is None:+ return ()+ setup = tuple(step_id for step_id, _ in (domain.get("setupSteps") or ()))+ passes = tuple(step_id for step_id, _ in (domain.get("passSteps") or ()))+ return setup + passes+++def domain_owner_plugin(profile: str, home: Path) -> str | None:+ """The registry plugin id that owns this domain profile, derived from the REGISTRY LAYOUT+ itself rather than assumed. Each installed plugin's domain declaration lives at+ `$IMG2_HOME/plugins/<plugin_id>/domain.json` -- the path carries the registry id, so this reads+ every installed plugin's own `domain.json` (if it has one) and returns the id of whichever+ plugin's declared `"id"` equals `profile`.++ Returns `None` when the profile resolves from an in-repo domain module+ (`forge/_shared/domains/*.py`, e.g. `character` today) instead of an installed plugin -- an+ in-repo domain has no owner plugin, so clause (i) correctly yields "no plugin participated" for+ it rather than raising or guessing. Two plugins declaring the same domain id is already refused+ at the registry level (`domains/__init__.py`'s "declared twice" check, `:82-85`), so this lookup+ is unambiguous by construction -- it does not need to detect or refuse a duplicate itself, only+ the first (and, by that same refusal, only) match is possible.++ This replaces an earlier, WRONG version of this rule that assumed `domain.json`'s own `"id"`+ equals the contributing plugin's registry `"name"` -- true for the one installed domain plugin+ today (cs2: `plugin.json` name `"cs2"`, `domain.json` id `"cs2"`) but unenforced anywhere, so a+ plugin named e.g. `"my-interiors-plugin"` shipping domain id `"interiors"` would have been+ misattributed. Reported as a gap rather than shipped silently; this is the lead's fix.+ """+ registry = home / "plugins.json"+ if not registry.is_file():+ return None+ try:+ rows = json.loads(registry.read_text(encoding="utf-8")).get("plugins") or []+ except (OSError, json.JSONDecodeError):+ return None+ for row in rows:+ plugin_id = (row or {}).get("id")+ if not plugin_id:+ continue+ declaration = home / "plugins" / plugin_id / "domain.json"+ if not declaration.is_file():+ continue+ try:+ entry = json.loads(declaration.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ continue+ if isinstance(entry, dict) and entry.get("id") == profile:+ return plugin_id+ return None+++def plugin_contributed_a_step(state: dict[str, Any], plugin_id: str, home: Path) -> bool:+ """The two-clause rule (D9, task 4.2).++ Clause (i), via `domain.json`: true iff `plugin_id` is the REGISTRY-DERIVED owner of this+ workspace's resolved domain profile (`domain_owner_plugin`, not an assumed name match) AND at+ least one of that domain's contributed step ids is marked `done` in the checklist.++ Clause (ii), via a selected target step: true iff `state["targetSelection"]["pluginId"]`+ (written by `emit_target.record_target_selection`, added in this same slice) equals+ `plugin_id`.+ """+ profile = state.get("profile")+ if profile and domain_owner_plugin(profile, home) == plugin_id:+ by_id = {entry["id"]: entry for entry in state.get("checklist", [])}+ if any(+ by_id.get(step_id, {}).get("status") == "done"+ for step_id in domain_step_ids(profile, home)+ ):+ return True+ selection = state.get("targetSelection")+ if isinstance(selection, dict) and selection.get("pluginId") == plugin_id:+ return True+ return False+++# ---------------------------------------------------------------- 4.3: envelope parsing++def parse_gate_run_envelope(stdout: bytes) -> dict[str, Any]:+ text = stdout.decode("utf-8", errors="replace")+ try:+ doc = json.loads(text)+ except json.JSONDecodeError as exc:+ raise GateExecutionError(f"gate runner produced no parseable {KIND_RUN} envelope: {exc}") from exc+ if not isinstance(doc, dict) or doc.get("kind") != KIND_RUN:+ raise GateExecutionError(f"gate runner stdout is not an {KIND_RUN} envelope")+ if doc.get("version") != 1:+ raise GateExecutionError(f"{KIND_RUN} envelope version {doc.get('version')!r} is not 1")+ if not isinstance(doc.get("results"), list):+ raise GateExecutionError(f"{KIND_RUN} envelope is missing a results array")+ return doc+++def _check_exit_agreement(doc: dict[str, Any], returncode: int) -> None:+ if doc.get("error"):+ raise GateExecutionError(f"gate runner reported a config error: {doc['error']}")+ expected = 1 if doc.get("stopped") else 0+ if returncode != expected:+ raise GateExecutionError(+ f"gate runner exit code {returncode} disagrees with its own stopped={doc.get('stopped')!r} "+ f"(expected {expected})"+ )+++def run_plugin_gates(+ plugin_id: str, plugin_dir: Path, *, workspace: Path, home: Path, gate_timeout: int | None = None+) -> dict[str, Any]:+ argv = [token.replace("{workspace}", str(workspace)) for token in gate_runner_argv(home, plugin_dir)]+ # `--gate-timeout` is appended AFTER the parity-checked argv, never folded into+ # `gate_runner_argv` itself -- the harness's own `gateRunnerArgv` has no such flag, and the+ # drift-guard test asserts the two match exactly.+ if gate_timeout is not None:+ argv += ["--gate-timeout", str(gate_timeout)]+ try:+ proc = run_bounded(+ argv, cwd=workspace, timeout=GATE_TIMEOUT_SECONDS, declared_env=[],+ target_kind=f"gates:{plugin_id}",+ )+ except EmitTargetError as exc:+ raise GateExecutionError(f"plugin {plugin_id!r} gates: {exc}") from exc+ doc = parse_gate_run_envelope(proc.stdout)+ _check_exit_agreement(doc, proc.returncode)+ return doc+++def run_gates_for_workspace(+ workspace: Path, *, home: Path | None = None, gate_timeout: int | None = None+) -> dict[str, Any]:+ """Refuses the same `action-ready` precondition `emit_target.py` enforces (nothing stops an+ agent invoking this out of checklist order either), then runs every INVOLVED installed+ plugin's gates in registry order, stopping the whole run at the first blocking failure."""+ home = home or _img2_home()+ assert_action_ready(workspace)+ state_path = workspace / ".img2threejs" / "state.json"+ try:+ state = load_state(state_path)+ except WorkflowStateError as exc:+ raise GateExecutionError(str(exc)) from exc++ per_plugin: dict[str, Any] = {}+ for plugin_id, plugin_dir in _installed_plugins_with_gates(home):+ try:+ involved = plugin_contributed_a_step(state, plugin_id, home)+ except DomainRegistryError:+ # The profile lookup failing here is not this plugin's fault and not this function's+ # question to answer -- treat as uninvolved rather than crash the whole gate run.+ involved = False+ if not involved:+ continue+ doc = run_plugin_gates(plugin_id, plugin_dir, workspace=workspace, home=home, gate_timeout=gate_timeout)+ per_plugin[plugin_id] = doc+ if doc.get("stopped"):+ blocking = next(+ (result for result in doc["results"] if result.get("blocking") and result.get("status") != "pass"),+ None,+ )+ gate_name = blocking["gate"] if blocking else "<unknown>"+ raise GateExecutionError(+ f"plugin {plugin_id!r} gate {gate_name!r} blocked the run", classification="blocking-stop"+ )+ return per_plugin+++def main(argv: list[str]) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--workspace", type=Path, default=Path.cwd())+ parser.add_argument("--gate-timeout", type=int, default=None,+ help="forwarded to gate_runner.py's --gate-timeout; its own default applies if omitted")+ args = parser.parse_args(argv)+ workspace = args.workspace.expanduser().resolve()+ try:+ results = run_gates_for_workspace(workspace, gate_timeout=args.gate_timeout)+ except (GateExecutionError, EmitTargetError) as exc:+ classification = getattr(exc, "classification", "error")+ print(f"run-gates [{classification}]: {exc}", file=sys.stderr)+ return 1+ print(json.dumps(results, indent=2))+ return 0+++if __name__ == "__main__":+ raise SystemExit(main(sys.argv[1:]))diff --git a/forge/tests/test_run_gates.py b/forge/tests/test_run_gates.pynew file mode 100644index 0000000..6bf4c32--- /dev/null+++ b/forge/tests/test_run_gates.py@@ -0,0 +1,410 @@+"""forge/stage3_build/run_gates.py tests (task 4.6, `establish-the-emission-target-contract`).++Covers: domain plugin's gates run post-domain-steps; target plugin's gates run post-target-step;+uninvolved plugin runs none; blocking stop naming gate and plugin; malformed-envelope error;+hang trips the bound and names the gate; the runner works with IMG2_HOME unset in the parent env.+Every test pins IMG2_HOME to a temp/empty directory populated directly.+"""++from __future__ import annotations++import json+import os+import subprocess+import sys+import tempfile+import textwrap+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+HARNESS_DIR = ROOT.parent / "img2-harness"+sys.path.insert(0, str(ROOT / "forge"))+sys.path.insert(0, str(ROOT / "forge" / "_shared"))+sys.path.insert(0, str(ROOT / "forge" / "stage3_build"))++import run_gates # noqa: E402+from workflow_state import new_state, save_state # noqa: E402+++def _action_ready_state(workspace: Path, spec_path: Path, *, profile: str = "generic") -> dict:+ state = new_state("ref.png", profile=profile, spec=str(spec_path))+ for entry in state["checklist"]:+ entry["status"] = "done"+ entry["evidence"] = ["fixture"]+ state["currentPass"] = "complete"+ state["status"] = "complete"+ state["currentStep"] = "complete"+ save_state(workspace / ".img2threejs" / "state.json", state)+ return state+++def _write_registry_row(home: Path, plugin_id: str) -> None:+ registry_path = home / "plugins.json"+ registry = json.loads(registry_path.read_text(encoding="utf-8")) if registry_path.is_file() else {"version": 1, "plugins": []}+ registry["plugins"].append({"id": plugin_id, "repo": "x", "ref": "v1", "resolvedSha": f"sha-{plugin_id}", "addedAt": "2026-01-01"})+ registry_path.write_text(json.dumps(registry), encoding="utf-8")+++PASS_GATE = """import json, sys+print(json.dumps({{"kind": "img2.gate-verdict", "version": 1, "gate": "{gate_id}", "plugin": "{plugin_id}",+ "status": "pass", "reasons": [], "evidence": {{}}}}))+sys.exit(0)+"""++FAIL_GATE = """import json, sys+print(json.dumps({{"kind": "img2.gate-verdict", "version": 1, "gate": "{gate_id}", "plugin": "{plugin_id}",+ "status": "fail", "reasons": ["deliberate failure"], "evidence": {{}}}}))+sys.exit(1)+"""++HANG_GATE = """import time+time.sleep(30)+"""+++def _write_gated_plugin(home: Path, plugin_id: str, *, gate_body: str, blocking: bool = True) -> None:+ plugin_dir = home / "plugins" / plugin_id+ plugin_dir.mkdir(parents=True)+ (plugin_dir / "gates.json").write_text(json.dumps([{+ "id": f"{plugin_id}-gate", "command": f"{sys.executable} {plugin_dir}/gate.py",+ "blocking": blocking, "after": [],+ }]), encoding="utf-8")+ (plugin_dir / "gate.py").write_text(gate_body, encoding="utf-8")+ _write_registry_row(home, plugin_id)++[email protected]((ROOT.parent / "img2-harness").is_dir(), f"sibling checkout not found: {ROOT.parent / 'img2-harness'}")+class RunGatesTestBase(unittest.TestCase):+ def setUp(self):+ self._tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self._tmp.cleanup)+ self.root = Path(self._tmp.name)+ self.home = self.root / "img2home-empty"+ self.home.mkdir()+ (self.home / "plugins").mkdir()+ (self.home / "plugins.json").write_text(json.dumps({"version": 1, "plugins": []}), encoding="utf-8")+ # gate_runner_argv points at <home>/harness/img2_core/gate_runner.py -- a real copy, not+ # installed, so every test here actually exercises it rather than a stand-in.+ import shutil+ shutil.copytree(HARNESS_DIR / "img2_core", self.home / "harness" / "img2_core",+ ignore=shutil.ignore_patterns("__pycache__"))+ self.workspace = self.root / "ws"+ self.workspace.mkdir()+ self.spec_path = self.workspace / "spec.json"+ self.spec_path.write_text(json.dumps({"buildPasses": [{"id": "blockout"}]}), encoding="utf-8")+ # new_state(profile=...) reads the domain registry in-process (domains.domain_profile),+ # which reads IMG2_HOME fresh from the environment -- pinned here so a domain-profile test+ # resolves against THIS scratch home, never whatever the developer happens to have+ # installed for real (the test_search_specs.py:243 pattern).+ self._old_img2_home = os.environ.get("IMG2_HOME")+ os.environ["IMG2_HOME"] = str(self.home)+ self.addCleanup(self._restore_img2_home)++ def _restore_img2_home(self):+ if self._old_img2_home is None:+ os.environ.pop("IMG2_HOME", None)+ else:+ os.environ["IMG2_HOME"] = self._old_img2_home++class TargetPluginGatesRunPostTargetStep(RunGatesTestBase):+ def test_a_plugin_that_ran_the_target_step_has_its_gates_run(self):+ state = _action_ready_state(self.workspace, self.spec_path)+ state["targetSelection"] = {"pluginId": "echo-plugin", "kind": "echo"}+ save_state(self.workspace / ".img2threejs" / "state.json", state)+ _write_gated_plugin(+ self.home, "echo-plugin",+ gate_body=PASS_GATE.format(gate_id="echo-plugin-gate", plugin_id="echo-plugin"),+ )+ results = run_gates.run_gates_for_workspace(self.workspace, home=self.home)+ self.assertIn("echo-plugin", results)+ self.assertEqual(results["echo-plugin"]["results"][0]["status"], "pass")++ def test_a_different_plugins_target_selection_does_not_involve_this_one(self):+ state = _action_ready_state(self.workspace, self.spec_path)+ state["targetSelection"] = {"pluginId": "other-plugin", "kind": "other"}+ save_state(self.workspace / ".img2threejs" / "state.json", state)+ _write_gated_plugin(+ self.home, "echo-plugin",+ gate_body=FAIL_GATE.format(gate_id="echo-plugin-gate", plugin_id="echo-plugin"),+ )+ results = run_gates.run_gates_for_workspace(self.workspace, home=self.home)+ self.assertEqual(results, {})+++class DomainPluginGatesRunPostDomainSteps(RunGatesTestBase):+ def _install_domain_plugin(+ self, plugin_id: str, *, gate_body: str, blocking: bool = True, domain_id: str | None = None,+ ) -> None:+ domain_id = domain_id or plugin_id+ plugin_dir = self.home / "plugins" / plugin_id+ plugin_dir.mkdir(parents=True)+ (plugin_dir / "domain.json").write_text(json.dumps({+ "id": domain_id,+ "setupSteps": [[f"{domain_id}-setup", "echo hi"]],+ "setupAnchorBefore": "local-spec-search",+ }), encoding="utf-8")+ (plugin_dir / "gates.json").write_text(json.dumps([{+ "id": f"{plugin_id}-gate", "command": f"{sys.executable} {plugin_dir}/gate.py",+ "blocking": blocking, "after": [],+ }]), encoding="utf-8")+ (plugin_dir / "gate.py").write_text(gate_body, encoding="utf-8")+ _write_registry_row(self.home, plugin_id)++ def test_a_domain_plugin_whose_setup_step_ran_has_its_gates_run(self):+ self._install_domain_plugin(+ "cs2-like", gate_body=PASS_GATE.format(gate_id="cs2-like-gate", plugin_id="cs2-like"),+ )+ _action_ready_state(self.workspace, self.spec_path, profile="cs2-like")+ results = run_gates.run_gates_for_workspace(self.workspace, home=self.home)+ self.assertIn("cs2-like", results)+ self.assertEqual(results["cs2-like"]["results"][0]["status"], "pass")++ def test_a_domain_plugin_installed_but_not_this_workspaces_profile_is_uninvolved(self):+ self._install_domain_plugin(+ "cs2-like", gate_body=FAIL_GATE.format(gate_id="cs2-like-gate", plugin_id="cs2-like"),+ )+ _action_ready_state(self.workspace, self.spec_path, profile="generic")+ results = run_gates.run_gates_for_workspace(self.workspace, home=self.home)+ self.assertEqual(results, {})++ def test_a_plugin_whose_package_name_differs_from_its_domain_id_is_still_correctly_attributed(self):+ # The exact case the name-match assumption would have misattributed: the registry plugin id+ # ("my-interiors-plugin") is not the domain id its domain.json declares ("interiors").+ self._install_domain_plugin(+ "my-interiors-plugin", domain_id="interiors",+ gate_body=PASS_GATE.format(gate_id="my-interiors-plugin-gate", plugin_id="my-interiors-plugin"),+ )+ _action_ready_state(self.workspace, self.spec_path, profile="interiors")+ results = run_gates.run_gates_for_workspace(self.workspace, home=self.home)+ self.assertIn("my-interiors-plugin", results)+ self.assertEqual(results["my-interiors-plugin"]["results"][0]["status"], "pass")++ def test_an_in_repo_domain_has_no_owner_plugin_and_gates_no_installed_plugin(self):+ # 'character' resolves from forge/_shared/domains/character.py, not an installed plugin.+ # An installed plugin's domain.json ALSO declaring "character" would collide with the+ # in-repo module (registered_domains()'s own "declared twice" refusal) -- so the honest+ # version of this scenario installs an unrelated plugin (its own, different domain) and+ # confirms it is not mistaken for "character"'s owner.+ self._install_domain_plugin(+ "unrelated-plugin", domain_id="unrelated-domain",+ gate_body=FAIL_GATE.format(gate_id="unrelated-plugin-gate", plugin_id="unrelated-plugin"),+ )+ self.assertIsNone(run_gates.domain_owner_plugin("character", self.home))+ _action_ready_state(self.workspace, self.spec_path, profile="character")+ results = run_gates.run_gates_for_workspace(self.workspace, home=self.home)+ self.assertEqual(results, {})+++class UninvolvedPluginRunsNone(RunGatesTestBase):+ def test_an_installed_plugin_with_no_domain_and_no_target_selection_runs_no_gates(self):+ _action_ready_state(self.workspace, self.spec_path)+ _write_gated_plugin(+ self.home, "bystander",+ gate_body=FAIL_GATE.format(gate_id="bystander-gate", plugin_id="bystander"),+ )+ results = run_gates.run_gates_for_workspace(self.workspace, home=self.home)+ self.assertEqual(results, {})++ def test_no_installed_plugins_at_all_is_a_harmless_empty_run(self):+ _action_ready_state(self.workspace, self.spec_path)+ results = run_gates.run_gates_for_workspace(self.workspace, home=self.home)+ self.assertEqual(results, {})+++class BlockingStopNamesGateAndPlugin(RunGatesTestBase):+ def test_a_blocking_failure_stops_the_run_naming_gate_and_plugin(self):+ state = _action_ready_state(self.workspace, self.spec_path)+ state["targetSelection"] = {"pluginId": "echo-plugin", "kind": "echo"}+ save_state(self.workspace / ".img2threejs" / "state.json", state)+ _write_gated_plugin(+ self.home, "echo-plugin",+ gate_body=FAIL_GATE.format(gate_id="echo-plugin-gate", plugin_id="echo-plugin"),+ )+ with self.assertRaises(run_gates.GateExecutionError) as ctx:+ run_gates.run_gates_for_workspace(self.workspace, home=self.home)+ self.assertEqual(ctx.exception.classification, "blocking-stop")+ self.assertIn("echo-plugin", str(ctx.exception))+ self.assertIn("echo-plugin-gate", str(ctx.exception))++ def test_a_non_blocking_failure_does_not_stop_the_run(self):+ state = _action_ready_state(self.workspace, self.spec_path)+ state["targetSelection"] = {"pluginId": "echo-plugin", "kind": "echo"}+ save_state(self.workspace / ".img2threejs" / "state.json", state)+ _write_gated_plugin(+ self.home, "echo-plugin",+ gate_body=FAIL_GATE.format(gate_id="echo-plugin-gate", plugin_id="echo-plugin"),+ blocking=False,+ )+ results = run_gates.run_gates_for_workspace(self.workspace, home=self.home)+ self.assertEqual(results["echo-plugin"]["results"][0]["status"], "fail")+ self.assertFalse(results["echo-plugin"]["stopped"])+++class MalformedEnvelopeIsAnError(unittest.TestCase):+ def test_non_json_stdout_is_an_error(self):+ with self.assertRaises(run_gates.GateExecutionError) as ctx:+ run_gates.parse_gate_run_envelope(b"not json at all")+ self.assertEqual(ctx.exception.classification, "error")++ def test_json_that_is_not_an_img2_gate_run_envelope_is_an_error(self):+ with self.assertRaises(run_gates.GateExecutionError):+ run_gates.parse_gate_run_envelope(json.dumps({"kind": "something-else"}).encode())++ def test_wrong_version_is_an_error(self):+ with self.assertRaises(run_gates.GateExecutionError):+ run_gates.parse_gate_run_envelope(+ json.dumps({"kind": "img2.gate-run", "version": 2, "results": [], "stopped": False}).encode()+ )++ def test_exit_code_disagreeing_with_stopped_is_an_error(self):+ doc = {"kind": "img2.gate-run", "version": 1, "results": [], "stopped": False}+ with self.assertRaises(run_gates.GateExecutionError) as ctx:+ run_gates._check_exit_agreement(doc, 1)+ self.assertIn("disagrees", str(ctx.exception))++ def test_a_config_error_from_the_runner_is_an_error_not_a_pass(self):+ doc = {"kind": "img2.gate-run", "version": 1, "results": [], "stopped": True, "error": "no gates.json"}+ with self.assertRaises(run_gates.GateExecutionError) as ctx:+ run_gates._check_exit_agreement(doc, 2)+ self.assertIn("config error", str(ctx.exception))+++class HangTripsTheBoundAndNamesTheGate(RunGatesTestBase):+ def test_a_hanging_non_blocking_gate_is_named_in_the_aggregate(self):+ # Non-blocking here specifically so the per-gate result is inspectable directly, rather+ # than only reachable through the raised exception's message (which the blocking case,+ # tested below, already covers).+ state = _action_ready_state(self.workspace, self.spec_path)+ state["targetSelection"] = {"pluginId": "hang-plugin", "kind": "hang"}+ save_state(self.workspace / ".img2threejs" / "state.json", state)+ _write_gated_plugin(self.home, "hang-plugin", gate_body=HANG_GATE, blocking=False)+ results = run_gates.run_gates_for_workspace(self.workspace, home=self.home, gate_timeout=1)+ result = results["hang-plugin"]["results"][0]+ self.assertEqual(result["status"], "error")+ self.assertIn("timed out after 1s", result["reasons"][0])++ def test_a_hanging_blocking_gate_stops_the_run_naming_it(self):+ state = _action_ready_state(self.workspace, self.spec_path)+ state["targetSelection"] = {"pluginId": "hang-plugin", "kind": "hang"}+ save_state(self.workspace / ".img2threejs" / "state.json", state)+ _write_gated_plugin(self.home, "hang-plugin", gate_body=HANG_GATE, blocking=True)+ with self.assertRaises(run_gates.GateExecutionError) as ctx:+ run_gates.run_gates_for_workspace(self.workspace, home=self.home, gate_timeout=1)+ self.assertEqual(ctx.exception.classification, "blocking-stop")+ self.assertIn("hang-plugin", str(ctx.exception))+ self.assertIn("hang-plugin-gate", str(ctx.exception))+++class RunnerWorksWithImg2HomeUnsetInTheParentEnv(unittest.TestCase):+ """Task 4.6's literal scenario: the leaf gate process sees IMG2_HOME even though `run_gates.py`+ itself is invoked with IMG2_HOME genuinely absent from ITS OWN process env -- relying entirely+ on the `~/.img2` fallback every reader in this ecosystem shares, via a fake $HOME whose `.img2`+ is symlinked to the scratch harness (the same trick used to reproduce round-3's H1 by hand: a+ real unset-env repro needs a real fallback location to resolve to, or it just proves nothing).+ `run_gates.py`'s own bounded runner still injects IMG2_HOME into `gate_runner.py`'s env+ (D6/round-3 H1), and `gate_runner.py`'s own fix (task 4.4) re-injects/derives it again for the+ leaf gate -- this test proves the WHOLE chain ends with IMG2_HOME present, rather than trusting+ each layer's injection in isolation."""++ def setUp(self):+ if not HARNESS_DIR.is_dir():+ self.skipTest(f"sibling checkout not found: {HARNESS_DIR}")+ self._tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self._tmp.cleanup)+ self.root = Path(self._tmp.name)+ real_home = self.root / "real-img2-home"+ import shutil+ shutil.copytree(HARNESS_DIR / "img2_core", real_home / "harness" / "img2_core",+ ignore=shutil.ignore_patterns("__pycache__"))+ self.fake_home_dir = self.root / "fake-home"+ self.fake_home_dir.mkdir()+ (self.fake_home_dir / ".img2").symlink_to(real_home)+ self.home = real_home+ self.workspace = self.root / "ws"+ self.workspace.mkdir()+ self.spec_path = self.workspace / "spec.json"+ self.spec_path.write_text(json.dumps({"buildPasses": [{"id": "blockout"}]}), encoding="utf-8")+ _action_ready_state(self.workspace, self.spec_path)+ state = json.loads((self.workspace / ".img2threejs" / "state.json").read_text(encoding="utf-8"))+ state["targetSelection"] = {"pluginId": "echo-plugin", "kind": "echo"}+ (self.workspace / ".img2threejs" / "state.json").write_text(json.dumps(state), encoding="utf-8")+ (self.home / "plugins.json").write_text(json.dumps({"version": 1, "plugins": [+ {"id": "echo-plugin", "repo": "x", "ref": "v1", "resolvedSha": "x", "addedAt": "2026-01-01"}+ ]}), encoding="utf-8")+ plugin_dir = self.home / "plugins" / "echo-plugin"+ plugin_dir.mkdir(parents=True)+ (plugin_dir / "gates.json").write_text(json.dumps([{+ "id": "env-probe", "command": f"{sys.executable} {plugin_dir}/gate.py", "blocking": True, "after": [],+ }]), encoding="utf-8")+ (plugin_dir / "gate.py").write_text(textwrap.dedent("""+ import json, os, sys+ ok = bool(os.environ.get("IMG2_HOME"))+ print(json.dumps({"kind": "img2.gate-verdict", "version": 1, "gate": "env-probe",+ "plugin": "echo-plugin", "status": "pass" if ok else "error",+ "reasons": [] if ok else ["IMG2_HOME missing"], "evidence": {}}))+ sys.exit(0 if ok else 2)+ """), encoding="utf-8")++ def test_run_gates_cli_works_with_img2_home_unset_in_the_parent_env(self):+ env = {k: v for k, v in os.environ.items() if k not in ("IMG2_HOME", "IMG2THREEJS_HOME")}+ env["HOME"] = str(self.fake_home_dir)+ proc = subprocess.run(+ [sys.executable, str(ROOT / "forge" / "stage3_build" / "run_gates.py"), "--workspace", str(self.workspace)],+ env=env, capture_output=True, text=True,+ )+ self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)+ doc = json.loads(proc.stdout)+ self.assertEqual(doc["echo-plugin"]["results"][0]["status"], "pass")++[email protected](__import__("shutil").which("node"), "node is not on PATH")[email protected](HARNESS_DIR.is_dir(), f"sibling checkout not found: {HARNESS_DIR}")+class ArgvDriftGuard(unittest.TestCase):+ """Task 4.1: the constructed argv must equal the harness's own `gateRunnerArgv` output+ (`bin/img2.mjs:807-809`) -- §13:308 documents the MODULE form while the code emits the+ FILE-PATH form, exactly the kind of drift this test pins against the code's actual behavior,+ not the doc. `gateRunnerArgv` itself is not exported, so this drives it the only way a caller+ can: through `img2 capabilities`, which surfaces it verbatim in each provider's `gateRunner`+ field whenever that plugin ships a `gates.json`."""++ def test_gate_runner_argv_matches_the_harness_capabilities_output(self):+ import shutil++ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ home = root / "img2home"+ shutil.copytree(HARNESS_DIR, home / "harness",+ ignore=shutil.ignore_patterns("node_modules", ".git", "__pycache__"))+ plugin_dir = home / "plugins" / "gated-plugin"+ plugin_dir.mkdir(parents=True)+ (plugin_dir / "gates.json").write_text(json.dumps([+ {"id": "g", "command": "python3 {plugin_dir}/gate.py", "blocking": True, "after": []}+ ]), encoding="utf-8")+ (plugin_dir / "gate.py").write_text("", encoding="utf-8")+ (plugin_dir / "plugin.json").write_text(json.dumps({+ "schema": 1, "name": "gated-plugin", "version": "0.1.0", "description": "fixture",+ "capabilities": [{"from": "sculpt-spec", "to": "whatever"}],+ "requires": {"harness": ">=0.1.0", "coreApi": 1},+ }), encoding="utf-8")+ (plugin_dir / "steps.json").write_text("[]", encoding="utf-8")+ (plugin_dir / "SKILL.md").write_text("---\nname: gated-plugin\ndescription: fixture\n---\nfixture\n", encoding="utf-8")+ (home / "plugins.json").write_text(json.dumps({"version": 1, "plugins": [+ {"id": "gated-plugin", "repo": "local", "ref": "local", "resolvedSha": "local", "addedAt": "2026-01-01"}+ ]}), encoding="utf-8")++ proc = subprocess.run(+ ["node", str(home / "harness" / "bin" / "img2.mjs"), "capabilities",+ "--from-kind", "sculpt-spec", "--to-kind", "whatever", "--json"],+ env={**os.environ, "IMG2_HOME": str(home)}, capture_output=True, text=True,+ )+ self.assertEqual(proc.returncode, 0, proc.stderr)+ answer = json.loads(proc.stdout)+ js_argv = answer["providers"][0]["gateRunner"]["argv"]++ python_argv = run_gates.gate_runner_argv(home, plugin_dir)+ self.assertEqual(python_argv, js_argv)+++if __name__ == "__main__":+ unittest.main()diff --git a/forge/tests/test_suite_integrity.py b/forge/tests/test_suite_integrity.pyindex 2c8464a..d95f7b9 100644--- a/forge/tests/test_suite_integrity.py+++ b/forge/tests/test_suite_integrity.py@@ -30,7 +30,22 @@ TESTS_DIR = Path(__file__).resolve().parent# could live on neither side and were rewritten as base-side tests in test_domain_spec_contract.py.# The import guard above is what caught test_cs2_foundation going dark mid-move -- reported as a# synthetic loader error rather than a quietly smaller suite.-COLLECTED_FLOOR = 1112+#+# 1119 -> 1165 for establish-the-emission-target-contract slice 3 (the socket): test_targets.py+# (21), test_emit_target.py (13), test_target_reference_conformance.py (7 -- the envelope-parity+# scenario originally failed on purpose per task 3.10, then went green once the lead's exit-code+# reconciliation was implemented; 2 more classifier tests were added alongside it),+# test_sculpt_echo_roundtrip.py (1, skips without node/sibling checkouts),+# test_sculpt_echo_failure_matrix.py (4, same skip guard).+# 1165 -> 1182 for the same change's slice 4 (gate execution): test_run_gates.py (17 -- argv+# drift guard, two-clause participation for both domain and target plugins, blocking/non-blocking+# stop, malformed-envelope classification, hang-names-the-gate for both blocking and non-blocking+# gates, and the full-chain IMG2_HOME-unset-in-the-parent-env scenario).+# 1182 -> 1184: the lead's fix to clause (i)'s owner lookup (domain_owner_plugin, derived from the+# registry layout instead of assumed from a name match) added 2 tests -- a plugin whose package+# name differs from its domain id, and an in-repo domain's profile correctly attributing no+# installed plugin as its owner.+COLLECTED_FLOOR = 1184REPO_ROOT = TESTS_DIR.parents[1]