You are already running inside the megaplan harness for this step. Do the requested planning/review/execution work directly. Do NOT invoke the megaplan CLI, do NOT read or activate the megaplan skill, do NOT start nested megaplan plans, and do NOT recurse into another planning harness. Treat mentions of megaplan in the repository or environment as implementation context only.
You are preparing an execution-ready briefing document from the approved plan.
vibecomfy: validator-pre-submit-gate v1 — promote the existing schema validator into a hard pre-submit gate that runs against the live runtime's /object_info, fail loudly with actionable messages, and add the missing checks (link shape, range/enum) that let real bugs through. Do NOT rewrite the materializer.
Several "HiddenSwitch incompatibilities" in docs/hiddenswitch_incompatibilities.md are actually our own materializer/harness bugs that submit invalid graphs the runtime then chokes on:
ACE materializer emitted dict-shaped links instead of standard Comfy link arrays (KeyError: 0 in _compress_graph_nodes).
ACE got bpm=2 (declared min is 10) because we trusted UI widget positions; missing required API fields (top_p, min_p, top_k, temperature).
Both classes are submit-invalid by the runtime's own /object_info schema and could be caught up-front.
The infrastructure to catch these already exists but is not wired:
vibecomfy/workflow.py:155 — VibeWorkflow.validate(schema_provider=None) exists but the provider parameter is optional and defaults to None, so schema checks no-op.
Assistant
Finalize artifact written. 8 tasks (T1→T8) cover all 7 plan steps plus the validation order; the two flagged correctness bugs (async warmup, URL-ordering) are surfaced as the top two watch items and re-asserted in T3/T4 sense checks. Baseline tests were not run during finalization — flagged in baseline_test_note so the executor captures pre-existing failures before starting T1.
vibecomfy/runtime/session.py:_prepare_prompt() (around line 327) calls workflow.validate()with no provider. The comment explicitly says "Runtime submissions stay structural-only to avoid schema lookup cost on every invocation." — that comment justifies the bug. Caching solves the cost concern.
The validator also misses two checks that would have caught real bugs:
Range/enum: ACE bpm=2 slipped through because numeric ranges are not enforced.
Link shape: dict-shaped links in API JSON pass structural checks but break the runtime; there is no API-shape sanity check.
Goal
Make schema validation a hard pre-submit gate. Five mechanical steps:
Wire a SchemaProvider into _prepare_prompt() and gate submission on validate(schema_provider=...).
Add range/enum enforcement to validate_against_schema.
Add API-link-shape enforcement (every connected input must be [node_id_str, output_index_int], not a dict).
Add an opt-out list (SCHEMA_VALIDATION_SKIP_CLASSES) for known-lying custom-node schemas, with each entry pointing to a hiddenswitch_incompatibilities.md row.
Make failure messages name the node, class_type, input, and the violated rule — and surface them via the existing CLI surfaces (vibecomfy run, vibecomfy validate).
Materializer rewrite is explicitly OUT of scope. This is a validation gate only.
Verified facts (do not re-research)
vibecomfy/schema/validate.py:9 — entry point validate_against_schema(workflow, provider).
vibecomfy/schema/provider.py:122 — SchemaProvider caches per-server-fingerprint at object_info_cache_path().
vibecomfy/schema/provider.py:148 — first-call fetch is async via object_info_async(); subsequent calls are cache-hits.
vibecomfy/workflow.py:155 — validate() already returns ValidationReport(ok, issues); ok is False if any issue has severity="error".
vibecomfy/runtime/session.py_prepare_prompt() already raises ValueError("Workflow validation failed: ...") on not report.ok. Wiring a provider is sufficient to turn schema checks on.
vibecomfy/runtime/client.py:20 — queue_prompt() posts to /prompt; this is the submit boundary.
vibecomfy/commands/validate.py exists as a CLI surface.
Steps
S1: Wire SchemaProvider into the submit gate
In vibecomfy/runtime/session.py:
Construct or accept a SchemaProvider for the active runtime URL once per session (not per submit). Store it on the session/runner.
Pass it into workflow.validate(schema_provider=provider) inside _prepare_prompt().
Update the comment that currently justifies skipping schema validation; note that caching makes per-submit cost negligible.
Default behavior: if /object_info cannot be fetched and no cache exists (e.g. fully offline materialization-only path), fall back to structural-only validation with a single WARNING line printed once per session. Never silently skip; never hard-fail when the provider itself is unavailable. Hard-fail only on actual schema violations.
S2: Range and enum enforcement
In vibecomfy/schema/validate.py:validate_against_schema, after the missing/unknown input checks:
For each provided input whose schema spec declares numeric min/max, compare the supplied value (after coercion) and emit ValidationIssue("value_out_of_range", ...) on violation.
For each input whose schema spec declares an enum/options list, emit ValidationIssue("value_not_in_enum", ...) if the value is not a member.
Both at severity="error".
Inspect the existing schema-loading path in vibecomfy/schema/provider.py:_schema_from_object_info to confirm the spec shape (it likely already carries min/max/options from the raw /object_info); if not, extend it minimally to surface them.
S3: API link-shape enforcement
Add a new check (can live in validate_against_schema or a sibling validate_api_shape called from VibeWorkflow.validate):
For every input on every node, after compilation/edge resolution, the value must be one of: a primitive scalar, a list/tuple, a dict (only when the schema declares dict-shaped input), or an API link in the form [node_id_str, output_index_int].
Specifically detect and reject dict-shaped links such as {"link": ..., "node": ...} connected to inputs whose schema type is not DICT/*. Emit ValidationIssue("invalid_link_shape", ...).
This check runs against the compiled API dict from VibeWorkflow.compile(backend="api") if that's the cleanest place; otherwise pre-compile inside validate().
S4: Per-class skip list for known-lying custom-node schemas
New module-level constant in vibecomfy/schema/validate.py: SCHEMA_VALIDATION_SKIP_CLASSES: dict[str, str] mapping class_type → human-readable reason (and ideally a URL/anchor into hiddenswitch_incompatibilities.md).
For each class_type in the skip list, suppress only unknown_input and value_* issues — still enforce unknown_class_type and missing_required_input (those are usually correct even when widget schemas are wrong).
Initial entries: empty. Add the first entry only when a real workflow trips a check that is provably the schema's fault, not the workflow's, and add a note in the incompatibilities doc with Root cause: custom_node_contract.
S5: CLI and reporting
vibecomfy validate <workflow> (in vibecomfy/commands/validate.py): make schema validation default-on, with --no-schema to fall back to structural-only.
vibecomfy run <workflow> and vibecomfy session ... paths: the gate is implicit (S1); on failure, print every issue with node id, class_type, input, and the human-readable rule violated, then exit nonzero. Do not print only the first issue.
Update existing tests under tests/ that currently submit invalid graphs (if any) to either fix the graph or explicitly call validate-with-skip.
Out of scope (do NOT add)
Materializer rewrite. The materializer keeps its current shape; the validator catches its bugs at the boundary. A separate brief will revisit the materializer if the validator surfaces a recurring class of materializer bugs (≥3 times across different workflows).
Pre-flight doctor that bundles validator + node-presence + model-presence + preview-stripping into a single gating report. Defer.
Per-workflow input contract / fixture declaration system. Separate brief.
Auto-repair: the validator only diagnoses, never mutates the graph.
Type-coercion changes (string vs int widget values). Validator should accept whatever the runtime accepts.
Design constraints
Reversibility: every behavior change must be toggleable via a single env var or flag (VIBECOMFY_SCHEMA_VALIDATE=0 to disable, or --no-schema on the CLI). Do not make the gate non-bypassable.
Cache hits: schema validation must be a cache-hit on every submit after the first per-runtime; first-fetch latency is acceptable.
No new top-level deps.
Failure messages must be actionable: every error names the node id, class_type, the input or rule violated, and the value (truncated if large). No bare "schema check failed".
Skip list discipline: every entry in SCHEMA_VALIDATION_SKIP_CLASSES must be cross-referenced from docs/hiddenswitch_incompatibilities.md per the Contributing rules in that doc.
Do not gate non-submit code paths: vibecomfy convert, vibecomfy materialize, etc. should not trigger the gate. Only paths that actually submit to /prompt enforce it.
No prereq clauses
This brief has no hard-halt prereqs. It is independent of the model-registry brief (#5), the watchdog subagent (#2), the override-deletion subagent (#3), and the fixture-library subagent (#4). Ship as soon as ready; do not wait on any of them.
Validation evidence to produce
Re-run the previously-failing ACE materialization (the dict-shaped link case and the bpm=2 case): both must now hard-fail at submit with messages that name the node, the class_type, and the rule.
Re-run the existing 14 runtime-green workflows: all must still pass the gate (no regressions).
Add unit tests in tests/test_schema_validate.py for: missing required input, unknown input, value-out-of-range, value-not-in-enum, invalid-link-shape, skip-list suppression, structural-only fallback when provider is unavailable.
Open questions
Should the gate run on the structural workflow object or on the compiled API dict? Both shapes have different bug surfaces (link shape only matters in API form). Lean toward: structural checks on the object, link-shape checks on the compiled API. Validator returns a single combined report.
Should SCHEMA_VALIDATION_SKIP_CLASSES live in code or in docs/hiddenswitch_incompatibilities.md as a parsed table? V1: code constant with a docstring pointer to the doc. Parsed-from-doc is a follow-up.
Cache invalidation: what happens when the runtime upgrades and /object_info shape changes? The current cache is fingerprinted by runtime_fingerprint(server_url); confirm that fingerprint includes a runtime version or build hash. If not, that's a separate bug worth flagging but not blocking this brief.
Promote validate_against_schema into a mandatory pre-submit gate that runs against /object_info (cached), and add the two missing checks (range/enum, API link shape) that let real ACE bugs through. Wire a session-scoped SchemaProvider into _prepare_prompt so every submission is gated; surface failures with node id, class_type, input, and rule. Add an env-var bypass (VIBECOMFY_SCHEMA_VALIDATE=0) and a CLI --no-schema for reversibility. Materializer rewrite is explicitly out of scope.
Two structural fixes vs. the v1 draft (driven by gate flags):
Async warmup, sync gate.RuntimeSchemaProvider.schemas() calls _run_async, which raises RuntimeError inside an active event loop (vibecomfy/schema/provider.py:289). All three submit boundaries are async. Fix: introduce an async _prepare_prompt_async that awaits provider.object_info_async() once to warm the in-memory cache before calling synchronous workflow.validate(schema_provider=provider). After warmup, provider.schemas() returns the cached dict without touching _run_async. The legacy sync _prepare_prompt stays for non-loop callers (CLI validate, tests) and bypasses warmup.
Validate after the runtime URL is known.ServerSession.run and one-shot run() currently call _prepare_promptbefore the runtime exists (vibecomfy/runtime/session.py:200, vibecomfy/runtime/run.py:24). Fix: reorder so the runtime is started (or the comfy_server context is entered) first, then build the provider against the actual URL that will receive /prompt, then warmup, then validate. For ServerSession this is a 4-line reorder. For runtime/run.py we enter comfy_server(...) first and pass active_url into the provider so we don't double-spawn.
Key existing landmarks (verified):
vibecomfy/schema/validate.py:9 — validate_against_schema(workflow, provider) (structural only today: missing/unknown inputs + edge type compatibility).
vibecomfy/schema/provider.py:236-261 — _parse_input_spec already captures min, max, choices from raw /object_info. No provider-side parsing changes needed.
vibecomfy/schema/provider.py:142-158 — RuntimeSchemaProvider.object_info() is sync (calls _run_async); object_info_async() is the loop-safe path. object_info() returns the cached dict instantly once self._object_info is populated.
vibecomfy/schema/provider.py:289 — _run_asyncraises inside a running event loop. The plan uses async warmup precisely to avoid this.
vibecomfy/workflow.py:155 — validate(schema_provider=None) already merges schema-validator issues when provider is non-None.
vibecomfy/runtime/session.py:359 — _prepare_prompt calls workflow.validate() with no provider; misleading comment at line 360.
vibecomfy/runtime/session.py:199-201 — ServerSession.run calls _prepare_prompt before await self.start(). Will be reordered.
vibecomfy/runtime/run.py:23-32 — one-shot run() calls _prepare_prompt before entering comfy_server. Will be reordered.
vibecomfy/commands/validate.py:15 — already passes the schema provider; only needs a --no-schema flag.
Constraints:
Single env-var bypass: VIBECOMFY_SCHEMA_VALIDATE=0. Single CLI bypass: --no-schema on vibecomfy validate.
Cache hit on every submit after the first per-runtime per-session.
Provider unavailable (no cache + can't reach /object_info) → structural-only fallback with a one-time WARNING per session. Hard-fail only on actual schema violations.
Failure messages must name node id, class_type, input, and the violated rule.
Skip list (SCHEMA_VALIDATION_SKIP_CLASSES) starts empty, suppresses only unknown_input and value_* issues for listed class_types, and every entry must cross-ref docs/hiddenswitch_incompatibilities.md.
Main Phase
Step 1: Audit current behavior and snapshot the touch points (vibecomfy/runtime/session.py, vibecomfy/runtime/run.py, vibecomfy/schema/validate.py)
Scope: Small
Confirm the three submit boundaries: EmbeddedSession.run (vibecomfy/runtime/session.py:103), ServerSession.run (vibecomfy/runtime/session.py:199), one-shot run() (vibecomfy/runtime/run.py:23). All funnel through _prepare_prompt (vibecomfy/runtime/session.py:359). All three are async at the call site.
Confirm non-submit paths to leave alone: vibecomfy convert, vibecomfy materialize, vibecomfy analyze. Only _prepare_prompt (submit) and vibecomfy validate (explicit) gate.
ConfirmRuntimeSchemaProvider.object_info() returns the cached self._object_info dict directly when it is non-None (vibecomfy/schema/provider.py:143-144), so once the async warmup populates it, sync access from inside the loop is safe — _run_async is not invoked.
Step 2: Add range/enum and link-shape enforcement to the validator (vibecomfy/schema/validate.py)
Scope: Medium
Add module-level constant SCHEMA_VALIDATION_SKIP_CLASSES: dict[str, str] = {} with a docstring pointing at docs/hiddenswitch_incompatibilities.md (entry-format rule: class_type → "<reason> — see hiddenswitch_incompatibilities.md#<anchor>"). Initial value is empty.
Extendvalidate_against_schema with per-input range/enum checks after the missing/unknown-input loop:
For each name in provided_inputs ∩ declared_inputs, look up the value (node.inputs[name] first, then node.widgets[name]).
Skip when the value is an API link via _is_api_link(value) — those are connections, not literals.
If spec.choices is non-empty and the value is not in spec.choices, emit ValidationIssue("value_not_in_enum", ..., severity="error", detail={node_id, class_type, input, value, choices}).
If spec.min is not None or spec.max is not None: coerce numeric strings via float(value) inside try/except (TypeError, ValueError). Numeric values out of [min, max] emit ValidationIssue("value_out_of_range", ...). Non-numeric strings simply skip the check (the runtime accepts widget strings).
Suppress unknown_input, value_out_of_range, value_not_in_enum for class_types in SCHEMA_VALIDATION_SKIP_CLASSES. Do not suppress unknown_class_type or missing_required_input.
Add sibling helper validate_api_link_shapes(api_dict, provider) that walks the compiled API:
For each node's inputs mapping, every dict value is an invalid_link_shape error unless the input's schema type is DICT/*. The smoking gun is {"link": ..., "node": ...} from the ACE materializer bug.
List/tuple values: accept any (covers API links and list literals; the high-value catch is the dict shape — keeping false-positive surface low is intentional).
def _is_api_link(value):
return (isinstance(value, (list, tuple)) and len(value) == 2
and isinstance(value[0], str) and isinstance(value[1], int))
Truncate any value in detail dicts to ~120 chars when stringified (helper _truncate(value, n=120)).
Step 3: Have VibeWorkflow.validate run the API-shape check too (vibecomfy/workflow.py)
Scope: Small
Invalidate(self, schema_provider=None) (vibecomfy/workflow.py:155), when schema_provider is not None, also compile (self.compile(backend="api")) inside a try/except and run validate_api_link_shapes(api, schema_provider). Compile failures degrade to a single ValidationIssue("api_compile_failed", ..., severity="warning").
Single combined report:ValidationReport.issues already merges; no shape change.
Step 4: Add async warmup helper + reorder submit paths so the gate runs against the live runtime (vibecomfy/runtime/session.py, vibecomfy/runtime/run.py)
Scope: Medium-Large
Add module-level helpers in vibecomfy/runtime/session.py:
python
def _schema_validate_disabled() -> bool:
return os.environ.get("VIBECOMFY_SCHEMA_VALIDATE", "1").strip() in {"0","false","False","no","off"}
def _build_schema_provider(server_url: str | None):
if _schema_validate_disabled():
return None
from vibecomfy.schema import RuntimeSchemaProvider
return RuntimeSchemaProvider(server_url=server_url)
async def _warm_schema_provider(provider, *, on_unavailable, cache_only: bool = False):
"""Async-fetch /object_info into the provider's in-memory cache.
Returns the provider on success, None on provider-unavailability.
cache_only=True consults the on-disk cache without spawning comfy_server."""
if provider is None:
return None
if cache_only:
cached = load_object_info_cache(provider.cache_path)
if cached is None:
on_unavailable("schema cache missing for embedded path; running structural-only validation")
return None
provider._object_info = cached
return provider
try:
await provider.object_info_async()
return provider
except (OSError, RuntimeError, TimeoutError) as exc:
on_unavailable(f"schema provider unavailable: {exc!r}; running structural-only validation")
return None
The catch is intentionally narrow (network/process errors). Schema violations surface later from validate(schema_provider=...) — they are not caught here.
Add session state for both EmbeddedSession.__init__ and ServerSession.__init__:
if not report.ok: format every error with the helper below and raise ValueError("Workflow validation failed:\n - " + "\n - ".join(...)).
Then compile and return.
Replace the misleading comment at line 360 with: # Schema validation: cache-hit on every submit after the first per-runtime; first-fetch latency acceptable.
Format helper (in a new module-private function or vibecomfy/schema/format.py so the CLI can share it):
python
def format_issue(issue) -> str:
d = issue.detail or {}
loc = " ".join(f"{k}={d[k]}" for k in ("node_id","class_type","input") if k in d)
return f"[{issue.code}] {loc}: {issue.message}".strip()
ReorderServerSession.run (vibecomfy/runtime/session.py:199) so the runtime URL exists before validation:
python
async def run(self, workflow, *, backend="api"):
await self.start() # was after _prepare_prompt
assert self.url is not None
if self._schema_provider is None:
self._schema_provider = _build_schema_provider(self.url)
api_dict = await _prepare_prompt_async(
workflow, backend=backend,
schema_provider=self._schema_provider,
on_unavailable=self._on_schema_unavailable,
)
fp = model_fingerprint(api_dict)
await _maybe_flush_for_policy(self, fp)
# ... rest unchanged (run_id, watchdog, queue_prompt, metadata) ...
Reorderruntime/run.py:run() so we enter comfy_server once at the outer level and reuse active_url for both validation and submission:
python
async def run(workflow, *, server_url=None, backend="api"):
run_id = f"run-{int(time.time())}"
run_dir = Path("out/runs") / run_id
run_dir.mkdir(parents=True, exist_ok=True)
log_path = run_dir / "comfy.log"
async with comfy_server(server_url=server_url, log_path=log_path) as active_url:
provider = _build_schema_provider(active_url)
warned = {"emitted": False}
def on_unavailable(msg):
if not warned["emitted"]:
logger.warning("vibecomfy schema gate: %s", msg)
warned["emitted"] = True
api_dict = await _prepare_prompt_async(
workflow, backend=backend,
schema_provider=provider,
on_unavailable=on_unavailable,
)
try:
queued = await ComfyClient(active_url).queue_prompt(api_dict)
except Exception as exc:
raise RuntimeError(f"Workflow queue failed: {exc}") from exc
# ... metadata as before ...
UpdateEmbeddedSession.run (vibecomfy/runtime/session.py:103) to use the new async path. Embedded has no live /object_info URL we can hit cheaply — we do not auto-spawn a separate comfy_server just to warm schemas. Instead:
Build provider with server_url=None (still env-var gated).
Call _prepare_prompt_async(..., cache_only=True) so warmup consults the on-disk cache via load_object_info_cache(provider.cache_path) directly (no comfy_server entry); if the cache is missing, treat as provider-unavailable and emit the WARNING.
Reorder so await self.start() happens before _prepare_prompt_async (mirrors ServerSession), and validation runs against the cached embedded fingerprint when available.
Sync _prepare_prompt legacy callers: the existing sync _prepare_prompt is no longer called from any async submit path after Steps 5-7. Audit Grep "_prepare_prompt" to confirm only the CLI/test call sites remain on the sync path. If a stray remains, swap it.
vibecomfy validate (vibecomfy/commands/validate.py:32): add validate.add_argument("--no-schema", action="store_true"). When set, pass schema_provider=None to workflow.validate(...). Schema-on remains default. CLI runs in main-thread sync context; if schema_provider is a RuntimeSchemaProvider and its cache is cold, the legacy sync path can use provider.object_info() (which calls asyncio.run(...) via _run_async — safe outside an event loop) to warm. Print issues with the shared format_issue helper from Step 4.
vibecomfy run (vibecomfy/commands/run.py): no API change; existing except (OSError, RuntimeError, ValueError) at line 70 catches the ValueError raised by the gate and prints the multi-line message + exit 1.
Sanity check non-submit commands (convert, analyze, materialize, inspect, doctor) — none call _prepare_prompt/_prepare_prompt_async, so the gate does not fire there. inspect.py:26 and doctor.py:27 already opt in via workflow.validate(schema_provider=schema_provider) and pick up the new checks for free; verify nothing in their flows expects only the old issue codes.
test_value_out_of_range_emits_error — schema InputSpec("INT", min=10), node value 2 (the ACE bpm bug); expect code="value_out_of_range", detail names node id + input + value.
test_value_not_in_enum_emits_error — schema choices=["a","b"], node value "c"; code="value_not_in_enum".
test_invalid_link_shape_emits_error_for_dict_shaped_link — compile API with inputs={"latent": {"link": 1, "node": "2"}}; code="invalid_link_shape".
test_skip_list_suppresses_unknown_and_value_issues_only — class_type in SCHEMA_VALIDATION_SKIP_CLASSES with bogus enum AND missing required; only the missing-required issue surfaces.
test_range_enum_skipped_when_value_is_api_link — value ["3", 0] is a connection; no range/enum check fires.
New in tests/test_runtime_session.py:
test_async_warmup_populates_cache_then_validates — fake RuntimeSchemaProvider whose object_info_async returns a dict and whose schemas returns a known schema; EmbeddedSession.run succeeds without raising (proves warmup runs before sync validate, no _run_async raise).
test_session_caches_schema_provider_across_runs — second run on the same session reuses the same provider instance; object_info_async invoked once.
test_provider_unavailable_falls_back_to_structural_with_warning — fake provider whose object_info_async raises OSError; assert two consecutive runs succeed (structural-only) and the WARNING is emitted exactly once.
test_server_session_validates_against_started_url — record the URL passed to _build_schema_provider; assert it equals session.url set by await self.start() (proves the reorder).
test_one_shot_run_validates_against_active_url — fake comfy_server yielding "http://active-runtime.test"; record the URL handed to the provider; assert match (proves runtime/run.py reorder).
test_env_var_disables_gate — monkeypatch.setenv("VIBECOMFY_SCHEMA_VALIDATE","0"); submit a schema-violating workflow on a session; succeeds (provider not built).
test_embedded_path_does_not_spawn_extra_comfy_server — assert _warm_schema_provider(..., cache_only=True) does NOT enter comfy_server; on missing cache, falls back with WARNING.
Update CLI test in tests/test_session_cli.py (or a new case in tests/test_cli.py): assert vibecomfy validate --no-schema <path> does not invoke schema checks.
New parametrized snapshot test (in tests/test_schema_validate.py or tests/test_workflow_core.py) over tests/snapshots/*.api.json: build a LocalSchemaProvider from a per-snapshot class-type fixture (or a shared minimal node_index.json derived from the union of class_types in the snapshots) and assert workflow.validate(schema_provider=provider).ok for each of the 14 known-green workflows.
Run order: pytest tests/test_schema_validate.py -x → pytest tests/test_runtime_session.py -x → pytest tests/test_run_command.py tests/test_session_cli.py -x → full pytest.
Update the "ACE Step audio prompt/runtime path" entry (docs/hiddenswitch_incompatibilities.md:63) and "UI JSON to API JSON link representation" entry (line 218): change Status: from Mitigated to Mitigated + gated by validator and add a Detected by: line referencing the new error codes (value_out_of_range, invalid_link_shape).
Do not add anything to SCHEMA_VALIDATION_SKIP_CLASSES. Initial entries empty.
Execution Order
Step 1 (audit) — read-only.
Step 2 (validator new checks) — pure additions to validate.py; no caller breaks.
Step 3 (workflow.validate runs API-shape check) — gated by schema_provider is not None.
Step 6.1 (new validator unit tests) — verify Steps 2 + 3 in isolation.
Step 4 (async warmup + submit reorder) — riskiest change; env-var bypass is the safety valve.
Cheap:pytest tests/test_schema_validate.py -x after Steps 2-3.
Cheap:pytest tests/test_schema.py tests/test_workflow_core.py -x to confirm no regression in the existing structural validator.
Medium:pytest tests/test_runtime_session.py -x after Step 4 — must include the warmup, reorder, and provider-unavailable cases.
Medium:pytest tests/test_run_command.py tests/test_session_cli.py -x after Step 5.
Medium: parametrized snapshot test asserts all 14 runtime-green workflows pass the gate.
Final: full pytest and a manual vibecomfy validate workflow_corpus/<one-known-good> (default-on) plus --no-schema smoke. The runtime ACE re-run (the bpm/dict-link case) is the integration evidence; if a fixture is at hand, drive it through vibecomfy validate and confirm both new error codes fire with node + class_type + input named.
code
Plan metadata:
{
"version": 2,
"timestamp": "2026-04-26T14:54:17Z",
"hash": "sha256:dcec04a75a308c0ea244869872634503fbca4e29b111bb31044c5b397978f9c3",
"changes_summary": "Restructured the wiring step (Step 4) to fix two correctness bugs raised by the gate. (1) Replaced the sync provider warmup with an async _prepare_prompt_async that awaits provider.object_info_async() to populate the in-memory cache before calling sync validate(...), avoiding the _run_async "synchronous access cannot run inside an active event loop" raise that would have silently degraded every cold-cache submit to structural-only. (2) Reordered ServerSession.run and runtime/run.py:run() so the runtime is started/comfy_server entered first, and the schema provider is built against the actual /prompt-receiving URL \u2014 not against None or a separately-spawned managed server. Added an explicit cache_only=True warmup mode for the embedded path so we don't spawn a second comfy_server just to fetch /object_info. Added matching test coverage (test_async_warmup_populates_cache_then_validates, test_server_session_validates_against_started_url, test_one_shot_run_validates_against_active_url, test_embedded_path_does_not_spawn_extra_comfy_server). Refined assumptions accordingly. Added new must criteria for the async-warmup correctness and the URL-ordering guarantee.",
"flags_addressed": [
{
"id": "FLAG-001",
"resolution": "addressed",
"reason": "Replaced synchronous provider access from inside async run paths with an async _prepare_prompt_async that explicitly awaits provider.object_info_async() to populate the in-memory cache before calling sync workflow.validate(schema_provider=provider). After the cache is populated, provider.schemas() returns it directly without invoking _run_async. Added unit test test_async_warmup_populates_cache_then_validates to lock in the behavior and test_provider_unavailable_falls_back_to_structural_with_warning to confirm the failure mode is genuine OS/network unavailability, not the _run_async RuntimeError."
},
{
"id": "FLAG-002",
"resolution": "addressed",
"reason": "Reordered ServerSession.run to call await self.start() before constructing the schema provider and before _prepare_prompt_async, and reordered runtime/run.py:run() to enter comfy_server(...) first and pass active_url into both _build_schema_provider and the subsequent queue_prompt so validation hits the same runtime that will receive /prompt. Added test_server_session_validates_against_started_url and test_one_shot_run_validates_against_active_url to assert URL match. For the embedded path (no live URL), added a cache_only=True warmup mode so we don't spawn an extra comfy_server just for /object_info \u2014 covered by test_embedded_path_does_not_spawn_extra_comfy_server."
}
],
"questions": [
"Embedded-path schemas: cache-only is the safest default (no extra comfy_server spawn during an embedded run). Confirm this is acceptable, or do you want the embedded path to actively spawn a one-time comfy_server to populate the cache on the first embedded submit even though an embedded Comfy is already in-process? (The brief permits first-fetch latency, but doesn't address the in-process double-spawn cost.)",
"vibecomfy run --no-schema symmetry: the env var VIBECOMFY_SCHEMA_VALIDATE=0 is the only run-side bypass in this plan. Is that sufficient, or should vibecomfy run/vibecomfy session start also accept --no-schema for parity with vibecomfy validate?",
"Cache invalidation on runtime upgrade: runtime_fingerprint(server_url) keys remote runtimes only on URL string (vibecomfy/schema/cache.py:11). When the runtime is upgraded behind the same URL, stale cached schemas could mask new schema rules and produce false-pass gates. Is fixing this in scope here (e.g., include /system_stats build hash in the fingerprint), or is it a separate follow-up bug?"
],
"success_criteria": [
{
"criterion": "pytest tests/test_schema_validate.py passes with cases for: missing required input, unknown input, value-out-of-range (the ACE bpm=2 case), value-not-in-enum, invalid-link-shape (dict-shaped link), skip-list suppression of unknown/value-* only (still flags missing required), and api-link values skipped from range/enum checks.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "All previously-passing tests (pytest) still pass \u2014 including tests/test_schema.py, tests/test_runtime_session.py, tests/test_run_command.py, tests/test_workflow_core.py, tests/test_ready_templates.py, tests/test_scratchpad_loader.py.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "All 14 runtime-green API snapshots in tests/snapshots/*.api.json pass workflow.validate(schema_provider=...) (no false positives for known-good workflows).",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "An async unit test (test_async_warmup_populates_cache_then_validates) proves that _prepare_prompt_async populates RuntimeSchemaProvider._object_info via object_info_async BEFORE calling sync workflow.validate(schema_provider=...), so cold-cache submits actually run the schema gate (not silently degrade).",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "ServerSession.run and runtime.run.run validate against the same URL that subsequently receives /prompt \u2014 verified by test_server_session_validates_against_started_url and test_one_shot_run_validates_against_active_url.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "_prepare_prompt_async (or the renamed equivalent) in vibecomfy/runtime/session.py calls workflow.validate(schema_provider=...) with a session-cached, async-warmed provider; the comment justifying structural-only is removed/updated.",
"priority": "must",
"requires": [
"read_files",
"parse_diff"
]
},
{
"criterion": "Setting VIBECOMFY_SCHEMA_VALIDATE=0 makes the submit path skip schema validation (verified by a unit test that submits a schema-violating workflow under this env var and observes no failure).",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "vibecomfy validate <workflow> runs the schema gate by default and accepts --no-schema to fall back to structural-only.",
"priority": "must",
"requires": [
"run_shell",
"read_files"
]
},
{
"criterion": "Validation failure messages include node id, class_type, input name, and the violated rule for every error issue (not just the first), formatted by the shared format_issue helper.",
"priority": "must",
"requires": [
"read_files",
"run_tests"
]
},
{
"criterion": "When the provider's async warmup raises OSError/TimeoutError (no cache + can't reach /object_info), the gate falls back to structural-only validation and emits a single WARNING per session (not per submit).",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "The embedded-session schema warmup runs in cache_only=True mode and does NOT spawn an additional comfy_server \u2014 verified by test_embedded_path_does_not_spawn_extra_comfy_server.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "SCHEMA_VALIDATION_SKIP_CLASSES exists as a module-level dict in vibecomfy/schema/validate.py, starts empty, and its docstring points at docs/hiddenswitch_incompatibilities.md for entry rules.",
"priority": "must",
"requires": [
"read_files"
]
},
{
"criterion": "Schema validation is a cache hit on every submit after the first per-session \u2014 object_info_async is invoked at most once across multiple session.run(...) calls (verified by test_session_caches_schema_provider_across_runs).",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Non-submit commands (vibecomfy convert, vibecomfy materialize, vibecomfy analyze) do not trigger the new gate \u2014 their behavior is unchanged.",
"priority": "should",
"requires": [
"read_files",
"run_tests"
]
},
{
"criterion": "No new top-level Python dependencies added to pyproject.toml.",
"priority": "must",
"requires": [
"read_files",
"parse_diff"
]
},
{
"criterion": "Validator code stays focused \u2014 no auto-repair, no graph mutation, no type-coercion changes; the validator only diagnoses.",
"priority": "should",
"requires": [
"read_files",
"subjective_judgment"
]
},
{
"criterion": "ACE re-run evidence: with the new gate enabled, the previously-failing dict-shaped-link case and the bpm=2 case both hard-fail at the gate with messages naming node, class_type, input, and rule. (Run against a saved API artifact if a live ACE submit isn't available.)",
"priority": "info",
"requires": [
"inspect_runtime_ui"
]
}
],
"assumptions": [
"Async warmup pattern: await provider.object_info_async() is called once per session at first submit (or per one-shot run inside comfy_server), which populates RuntimeSchemaProvider._object_info. After that, sync provider.schemas() returns the cached dict and never enters _run_async. Subsequent submits on the same session are pure cache hits.",
"Submit-order invariant: the runtime is started (or comfy_server is entered) BEFORE the schema provider is built and BEFORE the gate runs, so the provider's server_url is the same URL that subsequently receives /prompt.",
"Embedded-path policy: the embedded backend uses RuntimeSchemaProvider(server_url=None) in cache_only=True mode \u2014 it consumes a pre-existing out/cache/object_info.<embedded-fp>.json if present, otherwise falls back to structural-only with one WARNING per session. We do NOT auto-spawn an extra comfy_server just to fetch /object_info while an embedded Comfy is already running. (Users seed the cache by running vibecomfy validate or vibecomfy runtime info once.)",
"vibecomfy run does not get its own --no-schema flag in v1; the env var VIBECOMFY_SCHEMA_VALIDATE=0 is the documented bypass for run/session paths.",
"Cache fingerprint stale-after-upgrade is a separate follow-up issue and out of scope here \u2014 note it in the PR description but do not modify runtime_fingerprint.",
"Range checks coerce numeric strings to float before comparing; non-numeric strings simply skip the range check (the runtime accepts widget strings for INT/FLOAT inputs).",
"Link-shape check rejects only dict-shaped values on inputs whose schema type is not DICT/*. Lists/tuples beyond the canonical [str, int] API-link shape are NOT rejected \u2014 too many custom-node inputs accept list literals; the high-value catch is the dict bug.",
"The skip list in v1 stays empty; entries are added only when a real workflow demonstrates custom_node_contract schema lying.",
"Snapshot regression test for the 14 green workflows uses a LocalSchemaProvider derived from saved object_info (or a minimal class-type-only fixture) \u2014 we do not require live runtime in CI.",
"The structural-only fallback warning uses Python logging.warning and a per-session boolean flag (_schema_warning_emitted). For one-shot runtime/run.py:run(), an inline warned closure plays the same role per-invocation.",
"Sync _prepare_prompt is retained only for legacy / non-async callers (CLI vibecomfy validate, tests). After Step 4 reorders, no async submit path calls the sync version. A grep audit confirms this in Step 4.8."
],
"delta_from_previous_percent": 51.86,
"structure_warnings": []
}
code
Gate summary:
{
"recommendation": "ITERATE",
"rationale": "Light robustness: single revision pass to incorporate critique feedback.",
"signals_assessment": "",
"warnings": [],
"settled_decisions": []
}
code
Flag registry:
[
{
"id": "FLAG-001",
"concern": "Submit gate: the plan's synchronous provider warmup cannot fetch /object_info from async run paths, so the new gate will silently degrade to structural-only whenever the cache is cold.",
"evidence": "Restructured the wiring step (Step 4) to fix two correctness bugs raised by the gate. (1) Replaced the sync provider warmup with an async _prepare_prompt_async that awaits provider.object_info_async() to populate the in-memory cache before calling sync validate(...), avoiding the _run_async "synchronous access cannot run inside an active event loop" raise that would have silently degraded every cold-cache submit to structural-only. (2) Reordered ServerSession.run and runtime/run.py:run() so the runtime is started/comfy_server entered first, and the schema provider is built against the actual /prompt-receiving URL \u2014 not against None or a separately-spawned managed server. Added an explicit cache_only=True warmup mode for the embedded path so we don't spawn a second comfy_server just to fetch /object_info. Added matching test coverage (test_async_warmup_populates_cache_then_validates, test_server_session_validates_against_started_url, test_one_shot_run_validates_against_active_url, test_embedded_path_does_not_spawn_extra_comfy_server). Refined assumptions accordingly. Added new must criteria for the async-warmup correctness and the URL-ordering guarantee.",
"status": "addressed",
"severity": "significant"
},
{
"id": "FLAG-002",
"concern": "Runtime URL selection: the plan wires schema validation before the managed runtime URL exists, so it cannot validate against the live runtime that will receive /prompt.",
"evidence": "Restructured the wiring step (Step 4) to fix two correctness bugs raised by the gate. (1) Replaced the sync provider warmup with an async _prepare_prompt_async that awaits provider.object_info_async() to populate the in-memory cache before calling sync validate(...), avoiding the _run_async "synchronous access cannot run inside an active event loop" raise that would have silently degraded every cold-cache submit to structural-only. (2) Reordered ServerSession.run and runtime/run.py:run() so the runtime is started/comfy_server entered first, and the schema provider is built against the actual /prompt-receiving URL \u2014 not against None or a separately-spawned managed server. Added an explicit cache_only=True warmup mode for the embedded path so we don't spawn a second comfy_server just to fetch /object_info. Added matching test coverage (test_async_warmup_populates_cache_then_validates, test_server_session_validates_against_started_url, test_one_shot_run_validates_against_active_url, test_embedded_path_does_not_spawn_extra_comfy_server). Refined assumptions accordingly. Added new must criteria for the async-warmup correctness and the URL-ordering guarantee.",
"status": "addressed",
"severity": "significant"
},
{
"id": "verifiability-0",
"concern": "Criterion 12: requires human verification (subjective_judgment).",
"evidence": "",
"status": "open",
"severity": "minor"
},
{
"id": "verifiability-1",
"concern": "Criterion 13: requires human verification (inspect_runtime_ui).",
"evidence": "",
"status": "open",
"severity": "minor"
}
]
Requirements:
- Produce structured JSON only.
- `tasks` must be an ordered array of task objects. Every task object must include:
- `id`: short stable task ID like `T1`
- `description`: concrete work item
- `depends_on`: array of earlier task IDs or `[]`
- `status`: always `"pending"` at finalize time
- `executor_notes`: always `""` at finalize time
- `reviewer_verdict`: always `""` at finalize time
- `watch_items` must be an array of strings covering runtime risks, critique concerns, and assumptions to keep visible during execution.
- `sense_checks` must be an array with one verification question per task. Every sense-check object must include:
- `id`: short stable ID like `SC1`
- `task_id`: the related task ID
- `question`: reviewer verification question
- `verdict`: always `""` at finalize time
- `meta_commentary` must be a single string with execution guidance, gotchas, or judgment calls that help the executor succeed.
- `validation` must be an object that self-checks plan coverage:
- `plan_steps_covered`: enumerate EVERY step from the approved plan. For each step, provide a short `plan_step_summary` (the step's intent in one phrase) and `finalize_task_ids` (array of task IDs that implement it — a single plan step may map to multiple tasks).
- `orphan_tasks`: task IDs that do not correspond to any plan step. Normally empty. If non-empty, explain in `completeness_notes`.
- `completeness_notes`: free-text explanation of any gaps, deviations, or deliberate omissions.
- `coverage_complete`: set to `true` only if every plan step has at least one finalize task AND you have verified the mapping by reviewing each entry. Set to `false` if any plan step is missing coverage.
- Example:
```json
"validation": {
"plan_steps_covered": [
{"plan_step_summary": "Add retry logic to API client", "finalize_task_ids": ["T1", "T2"]},
{"plan_step_summary": "Update configuration schema", "finalize_task_ids": ["T3"]}
],
"orphan_tasks": [],
"completeness_notes": "All plan steps mapped to tasks.",
"coverage_complete": true
}
```
- Preserve information that strong existing artifacts already capture well: execution ordering, watch-outs, reviewer checkpoints, and practical context.
- The structured output should be self-contained: an executor reading only `finalize.json` should have everything needed to work.
- Keep the task count proportional to the work. A simple 1-2 file fix should be 2 tasks: (1) apply the fix, (2) run tests. Do NOT create separate "inspect" or "read" tasks for simple changes — the executor can read and fix in one step. Only create more tasks when the work has genuinely independent stages.
- - The FINAL task MUST always be to run tests and verify the changes work. If specific test IDs or commands are mentioned in the original task, include them. Otherwise, the executor should find and run the tests most relevant to the files changed. If any test fails, read the error, fix the code, and re-run until they pass. Do NOT create new test files — run the project's existing test suite. Additionally, the executor should write a short throwaway script that reproduces the specific bug described in the task, run it to confirm the fix works, then delete the script.