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 an independent reviewer. Critique the plan against the actual repository.
MP-4: Custom-node lifecycle and lockfile enforcement.
Runs in parallel with MP-2 (typed Handle scaffold). Zero file overlap — MP-2 owns vibecomfy/blocks/ and vibecomfy/workflow.py; MP-4 owns vibecomfy/runtime/session.py, the nodes CLI, and doctor. Both are P1/P2 deliverables for the design in docs/python_composition_dsl_plan.md (recently revised) and address issues §6 and §7 of docs/python_composition_dsl_review.md.
DELIVERABLES — all must land:
EmbeddedSession.reload_for_nodepack_change() — new explicit verb. Today's documented recipe is session.stop(); install; session.start() (see plan §"Custom Nodes — Adding On the Fly"), but no method captures this contract. The new method:
Refuses to run while a run() call is in flight (see deliverable #2).
Closes the existing _comfy context (mirror stop() at session.py:185-195, including the model_mmap_residency AttributeError swallow).
Reopens a fresh _comfy context (mirror start() at session.py:103-109).
Resets any cached state that would carry stale NODE_CLASS_MAPPINGS references.
Implement equivalent for ServerSession: tear down and respawn the comfyui serve subprocess.
In-flight guard on session.stop() and session.reload_for_nodepack_change() — today, EmbeddedSession.stop() (session.py:185-195) doesn't check whether a run() call is awaiting queue_prompt_api. A concurrent stop tears down _comfy mid-prompt. Add a tracking field (e.g. _inflight_run: asyncio.Future | None) and have stop() either:
{"checks":[{"id":"status","question":"Progress update","findings":[{"detail":"I started validating the lockfile and CLI assumptions and found the plan is already stale against the current repository there. I’m going back through the requested template now and will complete all five checks before writing the JSON output.","flagged":false}]}],"flags":[],"verified_flag_ids":[],"disputed_flag_ids":[]}
Assistant
{"checks":[{"id":"status","question":"Progress update","findings":[{"detail":"The template has the expected five checks. I confirmed one earlier concern was based on the plan text, not the repo: custom_nodes.lock really is the three-token format the plan describes, while nodes install-plan also already exists.","flagged":false}]}],"flags":[],"verified_flag_ids":[],"disputed_flag_ids":[]}
Assistant
{"checks":[{"id":"status","question":"Progress update","findings":[{"detail":"I have enough repository context now to fill the critique. The main risks are not structural formatting; they are runtime enforcement being deferred, stale assumptions in direct _cmd_doctor tests, and an in-flight guard design that does not actually cover concurrent runs on the same session.","flagged":false}]}],"flags":[],"verified_flag_ids":[],"disputed_flag_ids":[]}
Assistant
User
Assistant
I’m going to re-open the critique template and verify the revised plan against the repository, with special attention to the previously open flags and any new regressions introduced by the added runtime gate.
Assistant
The revised plan resolves the specific previous doctor-CLI and single-slot tracking objections, but I found two remaining lifecycle issues in the plan details: tracking starts too late in run(), and external-mode reconfigure() is not defined. I’m writing those into the critique output now.
Assistant
Updated the critique output at .megaplan/plans/mp-4-custom-node-lifecycle-20260426-1847/critique_output.json.
Key result: most prior flags are verified addressed, but I re-opened FLAG-002 for in-flight tracking starting too late in run(), and added FLAG-005 for undefined ServerSession.reconfigure() behavior in external-server mode.
Validated the JSON with python -m json.tool.
User
Assistant
I’m checking the iteration 3 template and then the relevant runtime code again. The two previous gaps look explicitly addressed, so I’m focusing now on whether the wider tracking window and narrow queue lock introduce any new race against the repository’s actual pre-queue work.
Assistant
The previous two open issues are addressed in the revised plan, but the repository’s _maybe_flush_for_policy() shows the new narrow queue lock is still too narrow for concurrent run() calls: pre-queue work includes cache/free-memory side effects and shared fingerprint state. I’m adding that as a new correctness flag rather than re-opening the fixed tracking-window flag.
Assistant
Updated .megaplan/plans/mp-4-custom-node-lifecycle-20260426-1847/critique_output.json for iteration 3.
New flag added: FLAG-006 for the queue-only _run_lock: concurrent run() calls can still interleave shared session side effects before/after queueing, especially _maybe_flush_for_policy() / flush(), last_fingerprint, _schema_provider, and run-dir metadata writes.
Validated the JSON with python -m json.tool.
RuntimeError("session has an in-flight run; await it before stop()")
Cancel-and-await the in-flight future.
Pick whichever matches the existing call-site contract (audit how session.stop() is called today). If both reasonable, expose wait_for_inflight: bool = True.
ServerSession external-mode handling — when configured to talk to an external-managed comfyui serve (one VibeComfy didn't spawn), reload_for_nodepack_change() must NOT terminate it. Raise a defined error class (e.g. ExternalServerRestartRequired) with a clear message. Plan §"Custom Nodes — Adding On the Fly" specifies: "External server mode can report that a restart is required, but it should not terminate a server it does not own." Today there's no detection path for external mode at install time and no error class — both must be created.
vibecomfy nodes lock CLI command — write custom_nodes.lock after resolving any semantic_label values. Schema per plan §"Custom Nodes — Pinning, Hashes, and Lockfiles":
semantic_label (optional advisory, e.g. "v1.4.0", "main").
source_sha256 (optional per-node-class content digest, hex).
Today the lockfile records (name, sha, url) only — see custom_nodes.lock entries for ComfyUI-KJNodes, ComfyUI-WanVideoWrapper. Extend the format and migrate existing entries. Preserve git_sha → git_commit_sha rename with backward-compat read.
vibecomfy doctor SHA verification verb — read the lockfile before session.start() (or as a separate doctor invocation) and verify each installed nodepack's git HEAD matches git_commit_sha. If source_sha256 is present, also verify the named class file's content hash. Default behavior on mismatch: FAIL CLOSED (refuse to start). Provide --allow-drift opt-in to downgrade to a warning. Hardening called out in review §7: "the lockfile is decoration without a doctor/runtime check and a defined mismatch policy."
Tests:
In-flight guard: kick off a slow run() (mock or real), call stop() concurrently, assert documented behavior.
Reload verb: install a fake nodepack, call reload_for_nodepack_change(), verify NODE_CLASS_MAPPINGS reflects the new pack.
External-server-mode: configure session pointing at external URL, call reload, assert ExternalServerRestartRequired raised and external process NOT touched.
SHA verification: synthetic mismatch case fails closed without --allow-drift, warns with it.
CRITICAL CONSTRAINTS:
Backward compatibility: existing custom_nodes.lock must still load (handle git_sha → git_commit_sha gracefully). Existing session.stop() callers must keep working — if you choose the "refuse" option for the in-flight guard, audit every call site.
Do not touch vibecomfy/blocks/, vibecomfy/workflow.py, or anything in the typed-Handle path. MP-2 owns those, running in parallel.
Do not implement VibeFlow stage-aware run-dir naming or stage_index/flow_id in RunResult — those are MP-5 deliverables (SD-013 in the revised plan).
Do not implement schema validation — that's MP-6.
Hot-loading a nodepack into a running session WITHOUT reload is explicitly NOT in scope per the plan: "An optional Python import-and-load path may exist later, but only behind a feature flag and only for proven-safe packs."
KEY FILES (read first, before planning):
docs/python_composition_dsl_plan.md — full design, esp. §"Custom Nodes — Adding On the Fly", §"Custom Nodes — Pinning, Hashes, and Lockfiles", §"Enforcement Gates", and SD-006/SD-013.
lines 88-195: EmbeddedSession class (init, start, run, stop)
lines 198-299: ServerSession class
line 144: queue_prompt_api — currently unshielded
lines 185-195: EmbeddedSession.stop() — no in-flight check today
lines 281-290: ServerSession.reconfigure — only reacts to argv changes, won't catch nodepack installs
lines 487-507: _run_metadata — records vibecomfy git_sha, not custom-node SHAs
vibecomfy/cli/ (search for existing vibecomfy nodes and vibecomfy doctor command modules).
custom_nodes.lock — current entries.
docs/custom_nodes.md — existing custom-node docs.
ACCEPTANCE:
All existing tests pass unchanged.
New tests for in-flight guard, reload verb, external-server detection, lockfile round-trip, and SHA verification all pass.
vibecomfy nodes lock produces a lockfile in the new schema; existing entries migrate cleanly.
vibecomfy doctor fails closed on a synthetic SHA drift; succeeds with --allow-drift.
EmbeddedSession.reload_for_nodepack_change() is exposed and documented.
code
Plan:
Implementation Plan: MP-4 — Custom-Node Lifecycle and Lockfile Enforcement
Overview
Land the four lifecycle/integrity gates from docs/python_composition_dsl_review.md §6–§7 and docs/python_composition_dsl_plan.md SD-006 / "Custom Nodes — Adding On the Fly" / "Custom Nodes — Pinning, Hashes, and Lockfiles":
an in-flight guard on EmbeddedSession.stop() and the new reload verb,
an explicit reload_for_nodepack_change() verb on both EmbeddedSession and ServerSession,
external-server-mode detection on ServerSession plus an ExternalServerRestartRequired error class,
a structured custom_nodes.lock schema (git_commit_sha required; semantic_label, source_sha256 optional) with a backward-compat reader for today's three-token lines,
a vibecomfy nodes lock writer and a vibecomfy doctor --check-nodepack-locks (fail-closed, --allow-drift opt-in).
Hard fences (per the brief): no edits to vibecomfy/blocks/ or vibecomfy/workflow.py (MP-2 territory); no flow_id / stage_index (MP-5); no schema validation work (MP-6); no in-process hot-load path. Existing custom_nodes.lock file format (name sha url) loads unchanged. Existing session.stop() callers (vibecomfy/runtime/run.py:80, vibecomfy/commands/session.py:69, internal ServerSession.start/reconfigure at lines 219/286) keep working — they're all sequential after run(), so default wait_for_inflight=True is a safe widening.
vibecomfy/commands/doctor.py — add --check-nodepack-locks / a nodepacks subcommand surface, plus default-on lockfile check.
New module vibecomfy/node_locks.py — pure I/O for custom_nodes.lock (read/write, format detection, drift verification). No new dir; sits next to existing vibecomfy/node_packs.py.
New tests in tests/test_runtime_session.py, tests/test_node_locks.py, tests/test_nodes_cli.py, tests/test_doctor_models.py (or new test_doctor_nodepacks.py).
Main Phase
Step 1: Audit current behavior and confirm fences (vibecomfy/runtime/session.py, vibecomfy/commands/session.py, vibecomfy/runtime/run.py)
Scope: Small
RereadEmbeddedSession.stop() (vibecomfy/runtime/session.py:185-195) and ServerSession.stop() (vibecomfy/runtime/session.py:292-305) — confirmed: both wipe state unconditionally; neither tracks in-flight runs.
List all session.stop() callers and verify they are sequential-after-run, so a default wait_for_inflight=True is non-breaking:
vibecomfy/runtime/run.py:80 — run_embedded() finally clause, after session.run() returns.
vibecomfy/commands/session.py:69 — daemon shutdown, no in-flight runs (daemon owns the server but does not call run()).
vibecomfy/runtime/session.py:219 — ServerSession.start() cleanup of dead process, no concurrent run.
vibecomfy/runtime/session.py:286 — ServerSession.reconfigure(), no concurrent run.
Test sites in tests/test_runtime_session.py (~14 calls) — all sequential.
Note that ServerSession today always spawns; there is no external_url field. External-mode is a new constructor argument, not a refactor of comfy_server (vibecomfy/runtime/server.py).
Step 2: Add the in-flight guard and reload_for_nodepack_change() to EmbeddedSession (vibecomfy/runtime/session.py)
Wrap the queue_prompt_api call in EmbeddedSession.run() (line 144) so the awaiting task is recorded:
Capture current_task = asyncio.current_task() before entering the try.
Set self._inflight_run = current_task immediately before the inner await self._comfy.queue_prompt_api(api_dict) line; clear it in a finally (alongside the existing watchdog finalizer).
Use a small counter / set if we ever support nested runs in the future, but for P1 a single Task slot is enough — the embedded session is documented as serial.
ModifyEmbeddedSession.stop() to take wait_for_inflight: bool = True:
If self._inflight_run is not None and not self._inflight_run.done():
When wait_for_inflight — await asyncio.shield(self._inflight_run) swallowing the run's own exception (the in-flight task should report its own error).
When not — raise RuntimeError("session has an in-flight run; await it before stop()").
Then run today's teardown: await self._context.__aexit__(...), including the existing model_mmap_residencyAttributeError swallow (lines 190–192). Reset _context, _comfy, _schema_provider, _schema_warning_emitted, and _inflight_run.
Always refuse on in-flight: if self._inflight_run and not self._inflight_run.done(): raise RuntimeError(f"reload_for_nodepack_change refused: run in flight (reason={reason!r})").
Call await self.stop(wait_for_inflight=False) (we already proved no run is in flight).
Call await self.start() to reopen the context (mirrors lines 103–109).
Clear _schema_provider and _schema_warning_emitted so NODE_CLASS_MAPPINGS is re-read from the fresh Comfy() context on the next run().
Reason: clearing _schema_provider is the fix for the "stale NODE_CLASS_MAPPINGS" callout — the provider caches _object_info across calls (_warm_schema_provider line 411).
Step 3: Extend ServerSession with external-mode and the reload verb (vibecomfy/runtime/session.py)
Scope: Medium
Add an exception class at module top (above OVERRIDES_INCLUDE):
python
class ExternalServerRestartRequired(RuntimeError):
"""Raised when a nodepack reload is requested on an externally-managed comfyui serve."""
ExtendServerSession.__init__ to accept external_url: str | None = None. Store it; track _external = external_url is not None. Document: when set, start() does not spawn and stop() is a no-op for the external process.
ModifyServerSession.start() (lines 215–221):
If self._external: set self.url = self._external_url and skip subprocess spawn; still call await ComfyClient(self.url).ready() once with a short timeout to fail loudly when the external URL is unreachable. No process / no log handle.
Else: existing behavior.
ModifyServerSession.stop() (lines 292–305):
Add the same _inflight_run tracking + wait_for_inflight: bool = True parameter as EmbeddedSession.stop() (initialize the slot in __init__, wrap ComfyClient.queue_prompt in run() line 248).
If self._external: clear self.url (or leave it — it's a client-side label, not state we own) and return without sending SIGTERM. Do not touch self.process (it stays None).
Refuse on in-flight (same shape as EmbeddedSession).
If self._external: raise ExternalServerRestartRequired(f"external comfyui serve at {self.url}; restart it manually to pick up nodepack changes (reason={reason!r})"). Do not touch the process or call stop().
Else: await self.stop(wait_for_inflight=False); self._argv = _comfy_server_argv(self.config); await self.start(). (Mirrors reconfigure at lines 281–290 for the spawn-managed case.)
UpdateVibeSession Protocol (lines 68–85) to add async def reload_for_nodepack_change(self, *, reason: str | None = None) -> None. Keep stop signature compatible — Protocols allow extra parameters with defaults on implementations.
Format pick: keep custom_nodes.lock as a text file but switch to YAML for new writes — already a project pattern (vibecomfy/registry/models.yaml, see models_loader.py). YAML carries optional fields and per-class hashes cleanly. The reader auto-detects legacy three-token lines vs YAML by sniffing the first non-blank line: if it parses as name sha url, read all lines as legacy; otherwise parse as YAML.
Backward-compat field rename: when reading YAML, accept either git_commit_sha or legacy git_sha for the same field; prefer git_commit_sha. Emit a one-shot deprecation warning when git_sha is used. (This satisfies the brief's "preserve git_sha → git_commit_sha rename with backward-compat read.")
Always emit YAML in canonical key order (name, repo_url, git_commit_sha, then optional semantic_label, then optional source_sha256 with sorted class names). Stable enough for round-trip equality tests.
semantic_label: best-effort — git describe --tags --exact-match else git rev-parse --abbrev-ref HEAD. Skip if both fail.
source_sha256: only when explicitly requested (--hash-classes class1,class2). Compute SHA-256 over the bytes of the file declaring each class (look up via nodepack_dir/__init__.py or scan *.py). Out of scope: auto-discover all classes per pack.
Each lock: check custom_nodes_dir/<name>/.git exists, git rev-parse HEAD == git_commit_sha. Mismatch carries (name, expected_sha, actual_sha, kind) where kind is "missing", "sha_drift", or "source_drift".
For each (class_name, expected_sha256) in source_sha256, locate the class file (heuristic: scan pack tree for class <name>), recompute SHA-256, compare.
(Default ON so the gate is enforced; users opt out per-invocation.)
Insert a check inside _cmd_doctor() before model checks (so a stale nodepack fails fast):
python
if args.check_nodepack_locks:
mismatches = node_locks.verify_locks(node_locks.load_locks())
if mismatches:
for m in mismatches:
print(f"nodepack drift: {m.name} {m.kind} expected={m.expected[:12]} got={m.actual[:12]}")
if not args.allow_drift:
return 1
print("(continuing despite drift due to --allow-drift)")
Surface the same gate to programmatic startup: add a thin helper node_locks.assert_clean(*, allow_drift: bool) that callers (e.g., a future EmbeddedSession.start() extension) can opt into. Do not wire it into session.start() in this MP — start() is autocalled by run() and we don't want a hard fail in tests that don't carry a lockfile. Document as a follow-up.
Subclass FakeComfy.queue_prompt_api to await an asyncio.Event controlled by the test. Start the run as a task, await one event-loop turn, then call session.stop(wait_for_inflight=False) and assert RuntimeError mentioning "in-flight run". Then release the event, call session.stop(wait_for_inflight=True) and assert clean teardown.
Same shape against ServerSession — patch ComfyClient.queue_prompt.
Reload verb (tests/test_runtime_session.py):
Use the existing fake_comfy fixture. Call await session.start(), then await session.reload_for_nodepack_change(reason="install KJNodes"). Assert enter_count == 2, exit_count == 1 (one reopen) and that _schema_provider was reset.
Provide a fake _object_info mapping that flips between calls; assert the post-reload provider re-warms.
Call await session.stop(); assert no SIGTERM was attempted (no process to send to) and the test does not hang.
Lockfile round-trip (tests/test_node_locks.py):
Write a fixture YAML with two packs (one with semantic_label, one with source_sha256); read; mutate; write; reread; assert deep equality.
Read the legacy three-token form (use the current custom_nodes.lock content as a fixture string); assert it parses to two NodepackLocks with empty semantic_label/source_sha256.
Read a YAML lockfile containing legacy git_sha keys; assert it parses identically to one using git_commit_sha and that a deprecation warning is emitted.
Build a tmp_path containing a fake custom_nodes/PackA/.git/HEAD plus git shim (or monkeypatch subprocess.run for git rev-parse). Run _cmd_doctor with a synthetic lockfile that mismatches; assert exit code 1 and the drift message.
Repeat with --allow-drift; assert exit code 0 and the warning text.
Set up tmp_path/custom_nodes/PackA with stub git output; run the command; assert the resulting lockfile YAML round-trips through load_locks.
Step 8: Docs touch-up (docs/custom_nodes.md)
Scope: Small
Add a one-paragraph reference to vibecomfy nodes lock and vibecomfy doctor --check-nodepack-locks (default-on, --allow-drift opt-out) plus the new YAML schema. No prose rewrites elsewhere.
Execution Order
Step 1 audit — confirm fences and call-site safety; produces no code.
Steps 2 + 3 (session.py changes) before any CLI work — the lifecycle verbs are the new contract everything else hangs off.
Step 4 (node_locks.py module) before Steps 5–6 — both CLI commands import it.
Steps 5 and 6 in either order (independent CLI surfaces), but easiest sequentially.
Step 7 tests interleaved with the corresponding implementation step where possible — write the in-flight-guard test alongside Step 2, the lockfile round-trip alongside Step 4, etc. This keeps each step independently green.
Step 8 docs last so the wording matches the actual flags/behavior.
Validation Order
Step 7.1, 7.2, 7.3 session-level pytests first (cheap; no I/O).
Full pytest tests/ to confirm no regression in the existing 14 session.stop() callers and the broader suite.
Manual smoke (info-only): vibecomfy nodes lock --dry-run --root custom_nodes against a real checkout and vibecomfy doctor <ready_template> to confirm the lock check fires.
code
Plan metadata:
{
"version": 1,
"timestamp": "2026-04-26T16:53:02Z",
"hash": "sha256:dde977c8bbbaae4aab618267f14bb979a5715ea8b3ae4614312c9195552b05bd",
"questions": [
"For EmbeddedSession.stop(), default to wait_for_inflight=True (await the in-flight queue_prompt_api) or False (refuse with RuntimeError)? Plan assumes True \u2014 matches every current call site and is non-breaking \u2014 but the brief leaves it open. Confirm or override.",
"External-server mode: should configuration come from a new ServerSession(external_url=...) constructor argument (current plan), or from a new SessionConfig.external_url field? The constructor route keeps SessionConfig clean and avoids touching EmbeddedSession, but the config route lets the daemon CLI pass it through --config JSON without a separate flag.",
"vibecomfy nodes lock output format: switch custom_nodes.lock to YAML (current plan, matches vibecomfy/registry/models.yaml precedent and carries optional/per-class fields cleanly) or stay text-with-extra-tokens? YAML breaks no readers since the only existing reader will be the new one we ship; the legacy three-token reader stays for backward compat.",
"Should EmbeddedSession.start() (or ServerSession.start()) auto-call node_locks.assert_clean() on first start(), or keep enforcement strictly inside vibecomfy doctor? Plan defers auto-enforcement to keep tests/fixtures simple; the brief mentions 'before session.start() (or as a separate doctor invocation)' so either is fair."
],
"success_criteria": [
{
"criterion": "All previously-passing tests in tests/ still pass after MP-4 lands.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "EmbeddedSession.reload_for_nodepack_change() exists, refuses with RuntimeError while a run() is in flight, closes the existing _comfy context (preserving the model_mmap_residencyAttributeError swallow), reopens a fresh one, and clears _schema_provider so NODE_CLASS_MAPPINGS is re-read on the next run. Verified by a unit test using the fake_comfy fixture asserting enter_count == 2, exit_count == 1, and post-reload schema-provider re-warm.",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "ServerSession.reload_for_nodepack_change() tears down and respawns the comfyui serve subprocess for spawn-managed mode, and raises ExternalServerRestartRequired (without touching the process) when external_url was provided. Verified by tests using monkeypatched _spawn_comfy_server and a ComfyClient.ready stub.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "An in-flight guard exists on EmbeddedSession.stop() and ServerSession.stop(): with wait_for_inflight=True (default) the in-flight task is awaited; with wait_for_inflight=False and a pending run, RuntimeError is raised. Verified by the slow-run/concurrent-stop test for both session classes.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "custom_nodes.lock loads in both the legacy three-token form (name sha url) and the new YAML form, and YAML reads accept both git_commit_sha and the legacy git_sha field name. Verified by tests/test_node_locks.py fixtures covering each path.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "vibecomfy nodes lock writes a YAML lockfile containing git_commit_sha (required), semantic_label (optional), and source_sha256 (optional, only when --hash-classes is provided). Existing entries from a legacy lockfile are preserved/migrated. Round-trip equality holds across read-mutate-write-read.",
"priority": "must",
"requires": [
"run_tests",
"run_shell"
]
},
{
"criterion": "vibecomfy doctor exits non-zero on synthetic SHA drift by default and exits zero with --allow-drift, emitting a clear drift line in both cases. Verified via a tests/test_doctor_nodepacks.py test with a monkeypatched git rev-parse.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "No file under vibecomfy/blocks/ and no edits to vibecomfy/workflow.py are touched by this branch (MP-2 ownership preserved).",
"priority": "must",
"requires": [
"parse_diff"
]
},
{
"criterion": "No flow_id, stage_index, or stage-aware run-dir naming changes are introduced in RunResult or run-dir creation (MP-5 ownership preserved).",
"priority": "must",
"requires": [
"parse_diff",
"read_files"
]
},
{
"criterion": "session.py stays under ~900 lines and vibecomfy/node_locks.py stays under ~250 lines \u2014 file-level cohesion target.",
"priority": "should",
"requires": [
"read_files"
]
},
{
"criterion": "reload_for_nodepack_change is named consistently across EmbeddedSession, ServerSession, and the VibeSession Protocol, with the same reason: str | None = None keyword arg.",
"priority": "should",
"requires": [
"read_files"
]
},
{
"criterion": "vibecomfy doctor --check-nodepack-locks is default-ON in the CLI surface so the gate is enforced unless the user opts out (--no-check-nodepack-locks or --allow-drift).",
"priority": "should",
"requires": [
"read_files"
]
},
{
"criterion": "Smoke-tested manually: running vibecomfy nodes lock --dry-run --root custom_nodes against a real working tree produces YAML matching the new schema and vibecomfy doctor against a live ready template enforces the gate as designed.",
"priority": "info",
"requires": [
"subjective_judgment"
]
}
],
"assumptions": [
"No existing call site to EmbeddedSession.stop() or ServerSession.stop() is concurrent with an active run(); verified by grep of vibecomfy/, tests/ (14 sites \u2014 all sequential try/finally after a single run).",
"External-server mode is a new affordance on ServerSession (no existing external_url plumbing), introduced via a constructor argument; daemon _cmd_session_start is not modified in this MP \u2014 external-mode users instantiate ServerSession directly today and the CLI surface can extend later.",
"custom_nodes.lock is rewritten to YAML on first vibecomfy nodes lock invocation; legacy three-token files keep loading via format auto-detection, so users can adopt the new schema lazily.",
"source_sha256 is opt-in per --hash-classes class1,class2 and not auto-discovered for every class \u2014 matches the plan's intent ('Skip it for typical packs whose git_commit_sha already pins all classes').",
"vibecomfy doctor --check-nodepack-locks defaults ON and fails closed; tests that don't carry a lockfile still pass because load_locks(missing_path) returns [] and verify_locks([]) returns [].",
"The Protocol-level VibeSession.stop signature can be widened with a default-valued wait_for_inflight parameter without breaking implementers \u2014 Python Protocols are structural and only require call-site compatibility, which await session.stop() preserves.",
"Per-pack lookup of class source files for source_sha256 is a heuristic (scan *.py for class <Name>() and out-of-band failures (multiple matches, mangled file) emit a CLI warning rather than aborting the lock write."
],
"structure_warnings": []
}
code
Plan structure warnings from validator:
[]
Existing flags:
[]
Known accepted debt grouped by subsystem:
{}
Escalated debt subsystems:
[]
Debt guidance:
These are known accepted limitations. Do not re-flag them unless the current plan makes them worse, broadens them, or fails to contain them.
Prefix every new concern with a subsystem tag followed by a colon, for example Timeout recovery: retry backoff remains brittle.
When a concern is recurring debt that still needs to be flagged, prefix it with Recurring debt: after the subsystem tag, for example Timeout recovery: Recurring debt: retry backoff remains brittle.
code
Your output template is at: /Users/user_c042661f/Documents/reigh-workspace/vibecomfy/.megaplan/plans/mp-4-custom-node-lifecycle-20260426-1847/critique_output.json
Read this file first — it contains 5 checks, each with a question and guidance.
For each check, investigate the codebase, then add your findings to the findings array for that check.
Each finding needs:
"detail": what you specifically checked and what you found (at least a full sentence)
"flagged": true if this describes a difference, risk, or tension — even if you think it's justified. false only if purely informational with no possible downside.
Every check must end with at least one finding. Never leave a findings array empty. If you found no issue, add one detailed flagged: false finding explaining what you checked and why it appears clear.
When in doubt, flag it — the gate can accept tradeoffs, but it can't act on findings it never sees.
Good: {"detail": "Checked callers of nthroot_mod in solveset.py line 1205 — passes prime moduli only, consistent with the fix.", "flagged": false}
Good: {"detail": "The fix handles empty tuples but not single-element tuples which need a trailing comma.", "flagged": true}
Bad: {"detail": "No issue found", "flagged": false} ← too brief, will be rejected
Bad: {"detail": "The hints suggest approach X but the plan uses Y. However Y is consistent with X's intent.", "flagged": false} ← a different approach than the hints IS a flag. You found a divergence — flag it. The gate decides if it's acceptable.
After filling in checks, add any additional concerns to the flags array (e.g., security, performance, dependencies).
Use the standard format (id, concern, category, severity_hint, evidence). This array can be empty.
Workflow: read the file → investigate → read file again → add finding → write file back. Repeat for each check.
code
Additional guidelines:
- Robustness level: standard. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Over-engineering: prefer the simplest approach that fully solves the problem.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids`: list flag IDs from prior iterations that the revised plan actually resolves (e.g., if the plan was revised to fix FLAG-001, and you confirm the fix is correct, include "FLAG-001"). Only include flags you've verified — don't guess.
- Verify that the plan follows the expected structure when validator warnings or the outline suggest drift.
- Additional flags may use these categories: correctness, security, completeness, performance, maintainability, other.
- Focus on concrete issues, not structural formatting.
{"checks":[{"id":"lockfile-integration","question":"Does the plan align with the repository's existing custom-node CLI/data model and current custom_nodes.lock shape, without inventing incompatible surfaces?","findings":[{"detail":"Checked vibecomfy/commands/nodes.py and found the existing nodes command is only list plus spec; there is no install-plan subcommand despite the plan saying to add lock alongside list/spec/install-plan. That part of the plan is stale against the actual CLI, although adding a new lock subcommand remains feasible.","flagged":true},{"detail":"Checked custom_nodes.lock, which is currently YAML with a top-level nodepacks list and entries shaped as name, url, sha, and classes, not legacy three-token text lines. The plan's legacy reader for name sha url and YAML git_sha compatibility does not cover the actual in-repo legacy field names sha and url, so migration would likely fail or drop current data unless expanded.","flagged":true},{"detail":"Checked vibecomfy/commands/nodes.py and vibecomfy/registry/nodes.py; the existing data model is a curated node registry from vibecomfy/registry/nodes.yaml with source, git_ref, git_sha, install, classes, and nodes spec can already emit JSON with these fields. The plan does not reuse this registry when resolving semantic labels or class/source metadata, instead proposing filesystem scanning only, which risks producing a lock that is disconnected from the existing custom-node catalog.","flagged":true},{"detail":"Checked dependency metadata in pyproject.toml; pyyaml is already a runtime dependency, so the plan's YAML writer does not introduce a new dependency burden.","flagged":false}]}],"flags":[{"id":"FLAG-001","concern":"Lockfile integration: The migration plan does not handle the actual committed custom_nodes.lock schema (nodepacks[].sha, nodepacks[].url, classes) and instead targets a nonexistent three-token text format plus git_sha.","category":"correctness","severity_hint":"likely-significant","evidence":"custom_nodes.lock currently contains YAML entries like name: ComfyUI-KJNodes, url: ..., sha: ..., classes: [...]; the plan's reader maps legacy text and YAML git_commit_sha/git_sha only."},{"id":"FLAG-002","concern":"Nodes CLI/data model: The plan bypasses the existing custom-node registry and claims an install-plan command exists, so nodes lock may not preserve registry metadata such as source, git_ref, and declared classes.","category":"maintainability","severity_hint":"likely-minor","evidence":"vibecomfy/commands/nodes.py registers only list and spec; vibecomfy/registry/nodes.py already loads nodes.yaml entries containing source, git_ref, git_sha, install, and classes."}],"verified_flag_ids":[],"disputed_flag_ids":[]}
{"checks":[{"id":"issue_hints","question":"Did the work fully address the issue hints, user notes, and approved plan requirements?","findings":[{"detail":"Checked the brief's SHA verification requirement against the plan's Step 6. The brief says doctor and/or runtime startup should compare installed nodepacks and the default mismatch policy should fail closed, including refusing to start; the plan explicitly says not to wire node_locks.assert_clean() into session.start(). That is a deliberate partial implementation of the accepted requirement and leaves runtime startup unenforced.","flagged":true},{"detail":"Checked the MP-2 and MP-5 ownership fences against the proposed touch points. The plan keeps edits out of vibecomfy/blocks/ and vibecomfy/workflow.py, and it does not propose flow_id, stage_index, or stage-aware run directory changes, so those fences appear respected.","flagged":false},{"detail":"Checked custom_nodes.lock and docs/custom_nodes.md; the repository's current lockfile really is the documented legacy three-token form name sha url, and vibecomfy nodes install-plan already exists. The plan's backward-compatible text reader and CLI placement are aligned with the current repository here.","flagged":false}]},{"id":"correctness","question":"Are the proposed changes technically correct?","findings":[{"detail":"Checked the proposed _inflight_run: asyncio.Task | None design against EmbeddedSession.run() and ServerSession.run(). The current code does not serialize multiple concurrent run() calls on the same session, so a single task slot can be overwritten by a second run; stop(wait_for_inflight=True) would then await only the last recorded task while another queued prompt could still be using _comfy or the server.","flagged":true},{"detail":"Checked the RuntimeSchemaProvider implementation in vibecomfy/schema/provider.py. Resetting only _schema_provider on reload is sufficient to drop cached _object_info and _schemas held by that provider instance, because a fresh provider is constructed by _build_schema_provider() on the next run.","flagged":false},{"detail":"Checked the lockfile format proposal against installed dependencies. The project already depends on pyyaml>=6 in pyproject.toml, so switching new lock writes to YAML is technically viable without adding a new dependency.","flagged":false},{"detail":"Checked the proposed ServerSession.start() external-mode readiness step against ComfyClient.ready(). The plan asks for a short timeout but does not identify an existing timeout parameter or wrapper; ready() is currently just an async client call, so implementers need to add an explicit asyncio.wait_for or similar or this branch may hang longer than intended.","flagged":true}]},{"id":"scope","question":"Search for related code that handles the same concept. Is the reported issue a symptom of something broader?","findings":[{"detail":"Searched for existing external-server handling and found it lives in vibecomfy/runtime/run.py via the server_url argument and vibecomfy/runtime/server.py's comfy_server(server_url=...) context manager, not in ServerSession. Adding ServerSession(external_url=...) covers the requested class but does not unify the existing external-server path or expose reload semantics there, so the lifecycle behavior remains split across two runtime surfaces.","flagged":true},{"detail":"Searched custom-node resolution code and found vibecomfy/node_packs.py is the existing catalog used by both doctor and nodes install-plan. The plan's nodes lock flow scans git checkout directories and only merges existing lock entries, but it does not use the catalog to preserve known classes or pip package metadata; this is acceptable for a lockfile writer if the lockfile is intentionally narrower, but it is a real divergence from the existing custom-node data model.","flagged":true},{"detail":"Checked docs around SD-013 and the brief's explicit exclusions. The plan avoids implementing VibeFlow stage identity and schema validation, which keeps MP-4 scoped to lifecycle and lockfile enforcement rather than broadening into MP-5 or MP-6.","flagged":false}]},{"id":"all_locations","question":"Does the change touch all locations AND supporting infrastructure?","findings":[{"detail":"Checked CLI registration. vibecomfy/commands/nodes.py explicitly registers list, spec, and install-plan, so adding lock there is the right glue location and vibecomfy/commands/__init__.py will pick it up through the existing command module registration.","flagged":false},{"detail":"Checked vibecomfy/commands/doctor.py and existing tests. _cmd_doctor is currently called directly in tests with argparse.Namespace(path=...); if the implementation follows the plan literally and reads args.check_nodepack_locks / args.allow_drift without getattr defaults or test updates, those direct callers will raise AttributeError rather than preserving existing behavior.","flagged":true},{"detail":"Checked the doctor command surface. The current parser requires a positional workflow path, while the plan describes lock verification as default-on flags on the same command and only sketches a possible separate invocation; without a subcommand or optional path, there is still no clean vibecomfy doctor invocation that only verifies custom_nodes.lock.","flagged":true},{"detail":"Checked documentation touch points. Updating docs/custom_nodes.md is the right minimum doc location because it already documents the current pinned packs, lockfile, doctor, and nodes install-plan custom-node workflow.","flagged":false}]},{"id":"callers","question":"Find the callers of the changed function. What arguments do they actually pass? Does the fix handle all of them?","findings":[{"detail":"Grep found production stop() callers in vibecomfy/runtime/run.py, vibecomfy/commands/session.py, and internally in ServerSession.start() / ServerSession.reconfigure(). They all call await session.stop() with no arguments after sequential work or daemon shutdown, so adding a defaulted wait_for_inflight parameter should preserve these call sites.","flagged":false},{"detail":"Checked test call sites in tests/test_runtime_session.py; they also call await session.stop() with no arguments, including direct asyncio.run(session.stop()) in the SIGTERM fallback test. The defaulted signature should keep them syntactically compatible, but the new in-flight guard must not introduce unwanted waits for tests that manually attach fake processes without a running prompt.","flagged":false},{"detail":"Checked ServerSession.reconfigure(), which currently calls await self.stop() when argv changes. If the plan changes stop() to wait for in-flight runs by default, a concurrent reconfigure() will block behind a running prompt rather than immediately restarting; that may be acceptable, but it is a semantic change the plan should call out because reconfigure is not only a final cleanup path.","flagged":true},{"detail":"Checked _cmd_doctor callers and parser-created arguments. CLI-created namespaces will have any new flags, but direct tests and any internal callers that construct argparse.Namespace(path=...) currently pass no allow_drift or check_nodepack_locks attributes, so the implementation should use getattr(args, 'allow_drift', False) and getattr(args, 'check_nodepack_locks', True) or update all direct callers.","flagged":true}]}],"flags":[{"id":"FLAG-001","concern":"Runtime lock enforcement: The plan explicitly defers wiring lockfile drift checks into EmbeddedSession.start() or ServerSession.start(), so SHA drift can still reach runtime startup despite the fail-closed requirement.","category":"completeness","severity_hint":"likely-significant","evidence":"Plan Step 6 says to add node_locks.assert_clean() but 'Do not wire it into session.start() in this MP'; docs/python_composition_dsl_plan.md says doctor and startup compare installed nodepacks against custom_nodes.lock and fail/report by policy."},{"id":"FLAG-002","concern":"In-flight guard: A single _inflight_run task slot is insufficient because the current sessions do not reject or serialize concurrent run() calls, so one run can overwrite another in-flight task.","category":"correctness","severity_hint":"likely-significant","evidence":"EmbeddedSession.run() and ServerSession.run() have no lock or concurrency guard today; the plan stores only self._inflight_run: asyncio.Task | None around the queue call."},{"id":"FLAG-003","concern":"Doctor CLI compatibility: Adding default-on lock flags directly to _cmd_doctor can break existing direct callers unless the implementation supplies defaults for namespaces that only contain path.","category":"correctness","severity_hint":"likely-minor","evidence":"Existing tests call _cmd_doctor(argparse.Namespace(path=str(scratchpad))); the plan's sample code reads args.check_nodepack_locks and args.allow_drift."},{"id":"FLAG-004","concern":"External server lifecycle split: The plan adds external mode only to ServerSession, while existing external-server use is through runtime.run.run(server_url=...) and comfy_server(server_url=...), so reload/restart-required behavior will not be consistent across runtime surfaces.","category":"completeness","severity_hint":"uncertain","evidence":"vibecomfy/runtime/run.py accepts server_url; vibecomfy/runtime/server.py yields external server_url without spawning. The plan introduces ServerSession(external_url=...) and does not discuss these existing paths."}],"verified_flag_ids":[],"disputed_flag_ids":[]}
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 an independent reviewer. Critique the plan against the actual repository.
MP-4: Custom-node lifecycle and lockfile enforcement.
Runs in parallel with MP-2 (typed Handle scaffold). Zero file overlap — MP-2 owns vibecomfy/blocks/ and vibecomfy/workflow.py; MP-4 owns vibecomfy/runtime/session.py, the nodes CLI, and doctor. Both are P1/P2 deliverables for the design in docs/python_composition_dsl_plan.md (recently revised) and address issues §6 and §7 of docs/python_composition_dsl_review.md.
DELIVERABLES — all must land:
EmbeddedSession.reload_for_nodepack_change() — new explicit verb. Today's documented recipe is session.stop(); install; session.start() (see plan §"Custom Nodes — Adding On the Fly"), but no method captures this contract. The new method:
Refuses to run while a run() call is in flight (see deliverable #2).
Closes the existing _comfy context (mirror stop() at session.py:185-195, including the model_mmap_residency AttributeError swallow).
Reopens a fresh _comfy context (mirror start() at session.py:103-109).
Resets any cached state that would carry stale NODE_CLASS_MAPPINGS references.
Implement equivalent for ServerSession: tear down and respawn the comfyui serve subprocess.
In-flight guard on session.stop() and session.reload_for_nodepack_change() — today, EmbeddedSession.stop() (session.py:185-195) doesn't check whether a run() call is awaiting queue_prompt_api. A concurrent stop tears down _comfy mid-prompt. Add a tracking field (e.g. _inflight_run: asyncio.Future | None) and have stop() either:
Refuse with a clear RuntimeError("session has an in-flight run; await it before stop()"), OR
Cancel-and-await the in-flight future.
Pick whichever matches the existing call-site contract (audit how session.stop() is called today). If both reasonable, expose wait_for_inflight: bool = True.
ServerSession external-mode handling — when configured to talk to an external-managed comfyui serve (one VibeComfy didn't spawn), reload_for_nodepack_change() must NOT terminate it. Raise a defined error class (e.g. ExternalServerRestartRequired) with a clear message. Plan §"Custom Nodes — Adding On the Fly" specifies: "External server mode can report that a restart is required, but it should not terminate a server it does not own." Today there's no detection path for external mode at install time and no error class — both must be created.
vibecomfy nodes lock CLI command — write custom_nodes.lock after resolving any semantic_label values. Schema per plan §"Custom Nodes — Pinning, Hashes, and Lockfiles":
semantic_label (optional advisory, e.g. "v1.4.0", "main").
source_sha256 (optional per-node-class content digest, hex).
Today the lockfile records (name, sha, url) only — see custom_nodes.lock entries for ComfyUI-KJNodes, ComfyUI-WanVideoWrapper. Extend the format and migrate existing entries. Preserve git_sha → git_commit_sha rename with backward-compat read.
vibecomfy doctor SHA verification verb — read the lockfile before session.start() (or as a separate doctor invocation) and verify each installed nodepack's git HEAD matches git_commit_sha. If source_sha256 is present, also verify the named class file's content hash. Default behavior on mismatch: FAIL CLOSED (refuse to start). Provide --allow-drift opt-in to downgrade to a warning. Hardening called out in review §7: "the lockfile is decoration without a doctor/runtime check and a defined mismatch policy."
Tests:
In-flight guard: kick off a slow run() (mock or real), call stop() concurrently, assert documented behavior.
Reload verb: install a fake nodepack, call reload_for_nodepack_change(), verify NODE_CLASS_MAPPINGS reflects the new pack.
External-server-mode: configure session pointing at external URL, call reload, assert ExternalServerRestartRequired raised and external process NOT touched.
SHA verification: synthetic mismatch case fails closed without --allow-drift, warns with it.
CRITICAL CONSTRAINTS:
Backward compatibility: existing custom_nodes.lock must still load (handle git_sha → git_commit_sha gracefully). Existing session.stop() callers must keep working — if you choose the "refuse" option for the in-flight guard, audit every call site.
Do not touch vibecomfy/blocks/, vibecomfy/workflow.py, or anything in the typed-Handle path. MP-2 owns those, running in parallel.
Do not implement VibeFlow stage-aware run-dir naming or stage_index/flow_id in RunResult — those are MP-5 deliverables (SD-013 in the revised plan).
Do not implement schema validation — that's MP-6.
Hot-loading a nodepack into a running session WITHOUT reload is explicitly NOT in scope per the plan: "An optional Python import-and-load path may exist later, but only behind a feature flag and only for proven-safe packs."
KEY FILES (read first, before planning):
docs/python_composition_dsl_plan.md — full design, esp. §"Custom Nodes — Adding On the Fly", §"Custom Nodes — Pinning, Hashes, and Lockfiles", §"Enforcement Gates", and SD-006/SD-013.
lines 88-195: EmbeddedSession class (init, start, run, stop)
lines 198-299: ServerSession class
line 144: queue_prompt_api — currently unshielded
lines 185-195: EmbeddedSession.stop() — no in-flight check today
lines 281-290: ServerSession.reconfigure — only reacts to argv changes, won't catch nodepack installs
lines 487-507: _run_metadata — records vibecomfy git_sha, not custom-node SHAs
vibecomfy/cli/ (search for existing vibecomfy nodes and vibecomfy doctor command modules).
custom_nodes.lock — current entries.
docs/custom_nodes.md — existing custom-node docs.
ACCEPTANCE:
All existing tests pass unchanged.
New tests for in-flight guard, reload verb, external-server detection, lockfile round-trip, and SHA verification all pass.
vibecomfy nodes lock produces a lockfile in the new schema; existing entries migrate cleanly.
vibecomfy doctor fails closed on a synthetic SHA drift; succeeds with --allow-drift.
EmbeddedSession.reload_for_nodepack_change() is exposed and documented.
code
Plan:
Implementation Plan: MP-4 — Custom-Node Lifecycle and Lockfile Enforcement
Overview
The 12 critique flags are all refinements to the original approach, not signals to redirect — the file ownership (vibecomfy/runtime/session.py, vibecomfy/commands/nodes.py, vibecomfy/commands/doctor.py, new vibecomfy/node_locks.py), the verb names, and the lockfile schema all stay. What changes is rigor on six points: (a) runtime-startup enforcement, not doctor-only; (b) asyncio.Lock + in-flight task set instead of a single overwrite-prone slot; (c) explicit asyncio.wait_for around the external-mode readiness probe; (d) explicit policy for the reconfigure() → stop() semantic widening; (e) getattr defaults so existing direct _cmd_doctor test callers stay green; (f) doctor's positional path becomes nargs='?' so a bare vibecomfy doctor runs only the lock gate; (g) explicit "out of scope" wording for runtime/run.py and runtime/server.py's one-shot server_url= paths and for the node_packs.py catalog/lockfile split.
Hard fences (unchanged): no edits to vibecomfy/blocks/ or vibecomfy/workflow.py (MP-2); no flow_id / stage_index (MP-5); no schema validation (MP-6); no in-process hot-load.
Touch points (revised):
vibecomfy/runtime/session.py — EmbeddedSession.run/stop, ServerSession.__init__/start/stop/reconfigure, plus a small docstring noting that one-shot comfy_server(server_url=...) and runtime/run.py's server_url= are intentionally out of reload scope.
vibecomfy/commands/nodes.py — lock subcommand.
vibecomfy/commands/doctor.py — path becomes optional; --check-nodepack-locks (default-on) + --allow-drift; getattr defaults for direct callers.
New vibecomfy/node_locks.py — read/write/verify, plus assert_clean(*, allow_drift, lockfile_check) for runtime-startup callers.
Tests: tests/test_runtime_session.py, new tests/test_node_locks.py, new tests/test_nodes_cli.py, new tests/test_doctor_nodepacks.py.
Conftest: tests/conftest.py (or a fixture in the new test files) sets VIBECOMFY_LOCK_CHECK=skip for sessions that don't carry a lockfile, so unrelated session tests don't accidentally trip the gate.
docs/custom_nodes.md — one paragraph describing the new gate, schema, and CLI.
Main Phase
Step 1: Audit current behavior and confirm fences (vibecomfy/runtime/session.py, vibecomfy/runtime/run.py, vibecomfy/runtime/server.py, vibecomfy/commands/doctor.py, vibecomfy/runtime/client.py)
Scope: Small
RereadEmbeddedSession.stop() (vibecomfy/runtime/session.py:185-195) and ServerSession.stop() (vibecomfy/runtime/session.py:292-305) — confirmed: both wipe state unconditionally; neither tracks in-flight runs.
Listsession.stop() callers: vibecomfy/runtime/run.py:80 (run_embedded finally), vibecomfy/commands/session.py:69 (daemon shutdown), vibecomfy/runtime/session.py:219 (ServerSession.start() cleanup of dead process), vibecomfy/runtime/session.py:286 (ServerSession.reconfigure()), and ~14 sequential test sites in tests/test_runtime_session.py. None are concurrent with an active run, so a default wait_for_inflight=True is non-breaking — including the reconfigure() path, where waiting for an in-flight prompt is safer than today's silent mid-prompt teardown (callers-1).
List direct _cmd_doctor callers in tests that pass argparse.Namespace(path=...) only: tests/test_doctor_models.py:54,76 and tests/test_cli.py:285. New flags will be read with getattr(args, …, default) so these stay green (callers-2, all_locations-1).
ConfirmComfyClient.ready() (vibecomfy/runtime/client.py:12-18) wraps each request in httpx.AsyncClient(timeout=5) — returns within ~5 s on TCP-accept-then-hang, but we still wrap the readiness probe in asyncio.wait_for(..., timeout=10) for an explicit upper bound (correctness-2).
Note the external-server surfaces: runtime/run.py:27-32 and runtime/server.py:11-14 accept server_url= and execute one prompt then return — they have no in-process session state to reload, so reload semantics are intentionally a ServerSession concept and the one-shot paths are out of reload scope (FLAG-004 / scope-1). This is documented in the new reload_for_nodepack_change docstring rather than expanded into those files.
Note the catalog/lockfile split (scope-2): vibecomfy/node_packs.py is the discovery catalog (which packs ship which classes, pip deps); custom_nodes.lock is the integrity manifest (git-pin + optional content hashes). They are intentionally distinct — nodes lock writes the integrity manifest only; the discovery catalog is unchanged.
Step 2: Concurrency-correct in-flight tracking on EmbeddedSession (vibecomfy/runtime/session.py)
The set is the source of truth for "is anything in flight"; the lock guarantees the embedded Comfy context only sees one prompt at a time (matches the documented serial contract while making concurrent callers safe). This addresses FLAG-002 / correctness-1: a second run() cannot overwrite the first's tracking slot because we use a set, and it cannot race the existing prompt because the lock serializes them.
Wrap the queue call in EmbeddedSession.run() (line 144):
When wait_for_inflight: await asyncio.gather(*[asyncio.shield(t) for t in tuple(self._inflight)], return_exceptions=True). Drains every in-flight run, swallowing per-task exceptions (each run reports its own failure via its own awaiter).
When not: raise RuntimeError(f"session has {len(self._inflight)} in-flight run(s); await them before stop()").
Then run today's teardown (lines 185-195), preserving the model_mmap_residencyAttributeError swallow. Reset _context, _comfy, _schema_provider, _schema_warning_emitted, and clear self._inflight.
Always refuse on in-flight: if self._inflight: raise RuntimeError(f"reload_for_nodepack_change refused: {len(self._inflight)} run(s) in flight (reason={reason!r})").
EmbeddedSession.__init__ gets the same lockfile_check parameter for symmetry.
ModifyServerSession.start() (lines 215-221):
Call node_locks.assert_clean(policy=self._lockfile_check)first (Step 6 below). For external mode, additionally:
python
if self._external:
self.url = self._external_url
try:
ready = await asyncio.wait_for(ComfyClient(self.url).ready(), timeout=10)
except asyncio.TimeoutError as exc:
raise RuntimeError(f"external comfyui serve at {self.url} not ready within 10s") from exc
if not ready:
raise RuntimeError(f"external comfyui serve at {self.url} not ready (returned non-200)")
return
The explicit asyncio.wait_for(..., 10) (correctness-2) caps the readiness probe even though ComfyClient.ready() already has an internal 5 s httpx timeout — belt-and-braces against socket-accept-then-hang.
Sniff the first non-blank, non-comment line: if it splits into 3 whitespace-separated tokens with len(tokens[1]) == 40 (SHA-1 hex), treat the whole file as legacy name sha url lines.
Otherwise parse as YAML: {nodepacks: [{name, repo_url, git_commit_sha | git_sha, semantic_label?, source_sha256?}, ...]}. When a git_sha key is encountered, accept it, emit a one-shot warnings.warn(...) deprecation about the rename, and treat the value as git_commit_sha (satisfies the brief's backward-compat clause).
Always emit YAML with canonical key order: name, repo_url, git_commit_sha, semantic_label (omitted when None), source_sha256 (omitted when empty; sorted by class name when present). Write with sort_keys=False, default_flow_style=False for stable round-trips.
Walk <root> for child dirs containing .git; skip non-git entries.
Parse --hash-classes as a comma-separated list.
For each pack: node_locks.resolve_pack(<root>/<name>, hash_classes=requested).
Merge with existing entries from args.lockfile so packs not under <root> aren't dropped (e.g., a pack documented in the lockfile but not yet checked out locally).
On --dry-run: write canonical YAML to stdout via node_locks.write_locks(..., path=sys.stdout) adapter (or just use a small helper to serialize without writing). Else: node_locks.write_locks(merged, args.lockfile).
Exit non-zero only when a <root>/<name>/.git exists but git rev-parse HEAD fails.
Step 6: vibecomfy doctor SHA verification with backward-compat (vibecomfy/commands/doctor.py)
Scope: Small
Make path optional in the parser at the bottom of the file (all_locations-2):
python
doctor.add_argument("path", nargs="?", default=None,
help="Workflow or scratchpad to inspect; omit to run lock-only checks.")
doctor.add_argument("--check-nodepack-locks",
action=argparse.BooleanOptionalAction, default=True)
doctor.add_argument("--allow-drift", action="store_true")
Update_cmd_doctor to use getattr defaults for the new flags so direct test callers (tests/test_doctor_models.py:54,76, tests/test_cli.py:285) keep working without modification (callers-2, all_locations-1):
python
def _cmd_doctor(args: argparse.Namespace) -> int:
check_locks = getattr(args, "check_nodepack_locks", True)
allow_drift = getattr(args, "allow_drift", False)
path = getattr(args, "path", None)
if check_locks:
mismatches = node_locks.verify_locks(node_locks.load_locks())
if mismatches:
for m in mismatches:
print(f"nodepack drift: {m.name} {m.kind} expected={m.expected[:12]} got={m.actual[:12]}{(' '+m.detail) if m.detail else ''}")
if not allow_drift:
return 1
print("(continuing despite drift due to --allow-drift)")
if path is None:
# Lock-only invocation (`vibecomfy doctor`).
if not check_locks:
print("nothing to check (path omitted and --no-check-nodepack-locks)")
return 1
print("Lockfile clean.")
return 0
# ... existing workflow-doctor flow (unchanged) ...
Conftest (tests/conftest.py — create or extend): autouse fixture monkeypatch.setenv("VIBECOMFY_LOCK_CHECK", "skip") for any test file that exercises EmbeddedSession/ServerSession lifecycle but doesn't ship a fixture lockfile. Scope to the relevant test modules (or apply globally and explicitly opt back into enforce in the doctor tests).
Single in-flight: FakeComfy.queue_prompt_api awaits an asyncio.Event. Start run() as a task, yield, call session.stop(wait_for_inflight=False) → assert RuntimeError mentioning "in-flight". Set the event, await, call session.stop() (default True) → clean teardown.
Concurrent runs (FLAG-002 covered): kick off two run() tasks against the same session, both gated on the same event. Assert that the _run_lock serializes them (only one queue_prompt_api is active at a time per FakeComfy.queue_calls snapshot taken inside the await). Then session.stop(wait_for_inflight=False) → assert RuntimeError mentions "2 in-flight". Set the event, both finish, then stop() cleans up.
Same shapes for ServerSession with ComfyClient.queue_prompt patched to gate on an event.
ServerSession(SessionConfig(port=8200), external_url="http://example.test"); patch ComfyClient.ready to return True. await session.start() → assert session.process is None (no spawn). await session.reload_for_nodepack_change(...) → assert ExternalServerRestartRequired. await session.stop() → no SIGTERM, returns promptly.
Step 8: Docs touch-up (docs/custom_nodes.md)
Scope: Small
Add one paragraph: lockfile schema (git_commit_sha required; semantic_label, source_sha256 optional), vibecomfy nodes lock writer, vibecomfy doctor (default-on lock check, --allow-drift opt-out), and the runtime gate (lockfile_check constructor arg / VIBECOMFY_LOCK_CHECK env override). One short sentence stating that runtime/run.py's server_url= and runtime/server.py's comfy_server(server_url=...) are stateless one-shot adapters with no reload verb — use ServerSession(external_url=...) for reload-aware external mode (FLAG-004).
Execution Order
Step 1 audit — confirm fences, call-site safety, and the catalog/lockfile split. No code changes.
Step 4 (vibecomfy/node_locks.py) — pure module with no runtime dependencies; both Step 5 (CLI) and Step 6 (doctor) and Step 3 (runtime gate) import it.
Step 2 + Step 3 (session.py changes). Step 3 lands the runtime assert_clean call alongside the in-flight tracking and external-mode plumbing.
Step 5 (nodes lock CLI) and Step 6 (doctor flag/optional path); independent — either order.
Step 7 tests interleaved with each implementation step (write the in-flight test alongside Step 2, the lock round-trip alongside Step 4, etc.) so each step is independently green.
Step 8 docs last so wording matches shipped flags.
Validation Order
Run pytest tests/test_node_locks.py -x first (pure I/O; fastest).
Run pytest tests/test_runtime_session.py -x — exercises the new in-flight, reload, external-mode, and runtime-gate paths.
Run pytest tests/test_doctor_nodepacks.py tests/test_nodes_cli.py -x for CLI coverage.
Run pytest tests/ (full suite) to confirm zero regressions in the existing 14 session.stop() callers and the existing direct _cmd_doctor callers.
Manual smoke (info-only): vibecomfy nodes lock --dry-run --root custom_nodes against the live tree; vibecomfy doctor (no args) → confirms lock-only mode runs the gate and exits cleanly when locked SHAs match HEAD.
code
Plan metadata:
{
"version": 2,
"timestamp": "2026-04-26T17:05:19Z",
"hash": "sha256:7da064dc73c15da3668444b220dfb66cefe267e3824d13906a24b1d082a71f65",
"changes_summary": "Addressed every open critique flag without changing the original approach: (1) Added a runtime-startup lock gate via node_locks.assert_clean() called from Embedded/ServerSession.start(), with lockfile_check: \"enforce\"|\"warn\"|\"skip\" constructor arg and VIBECOMFY_LOCK_CHECK env override (FLAG-001, issue_hints). (2) Replaced the single _inflight_run: Task | None slot with asyncio.Lock + set[Task] so concurrent run() calls are serialized and tracked correctly (FLAG-002, correctness-1). (3) Wrapped the external-mode ComfyClient.ready() probe in asyncio.wait_for(..., timeout=10) with explicit error messages for timeout vs non-200 (correctness-2). (4) Made ServerSession.reconfigure()'s new wait-then-restart semantics explicit and intentional in the docstring + a dedicated test (callers-1). (5) Switched _cmd_doctor to getattr(args, ..., default) for the new flags so direct argparse.Namespace(path=...) test callers keep working unchanged (all_locations-1, callers-2). (6) Made the doctor path argument nargs='?' so a bare vibecomfy doctor invocation runs the lock-only gate (all_locations-2). (7) Documented in the VibeSession Protocol docstring that runtime/run.py:run(server_url=...) and runtime/server.py:comfy_server(server_url=...) are stateless one-shot adapters with no reload verb (FLAG-004, scope-1). (8) Documented the intentional split between node_packs.py (discovery catalog) and custom_nodes.lock (integrity manifest) (scope-2). Added new conftest env-var fixture so unrelated session tests aren't tripped by the gate. Added new success criteria for runtime gate enforcement, concurrency correctness, ready() timeout, and _cmd_doctor backward compat.",
"flags_addressed": [
{
"id": "FLAG-001",
"resolution": "addressed",
"reason": "Step 3 + Step 4 wire node_locks.assert_clean() into both EmbeddedSession.start() and ServerSession.start() via a lockfile_check: \"enforce\"|\"warn\"|\"skip\" constructor parameter (default enforce) plus a VIBECOMFY_LOCK_CHECK env-var override. Step 7.7 adds explicit tests for the enforce/warn/skip paths."
},
{
"id": "FLAG-002",
"resolution": "addressed",
"reason": "Step 2 replaces _inflight_run: Task | None with asyncio.Lock + set[asyncio.Task]. Concurrent calls are now serialized by the lock, every awaiting task is tracked in the set, and raises with the exact in-flight count. Step 7.2 adds a concurrent-runs test that catches the original overwrite race."
},
{
"id": "FLAG-004",
"resolution": "addressed",
"reason": "Step 1.5 + Step 3.8 + Step 8 explicitly document that 's and 's are stateless one-shot adapters with no in-process state to reload, so is a concept by design. The docstring on the Protocol calls this out so the split is intentional and discoverable."
},
{
"id": "issue_hints",
"resolution": "addressed",
"reason": "Same fix as FLAG-001 \u2014 the runtime-startup gate is now wired in Step 3.3 via called at the top of . The brief's 'before session.start() (or as a separate doctor invocation)' is now satisfied on both surfaces."
},
{
"id": "correctness-1",
"resolution": "addressed",
"reason": "Same fix as FLAG-002 \u2014 serializes the queue call and tracks every awaiting run. Step 7.2 adds a two-concurrent-runs test that would fail under the old single-slot design."
},
{
"id": "correctness-2",
"resolution": "addressed",
"reason": "Step 3.3 wraps the external-mode readiness probe in with distinct messages for timeout vs non-200. Step 7.4 includes a hanging-ready test that exercises the wait_for path."
},
{
"id": "scope-1",
"resolution": "addressed",
"reason": "Step 1.5 + Step 3.8 + Step 8 document the deliberate split: and 's are stateless one-shot adapters; reload is a concept. No silent two-class system \u2014 the boundary is named in the Protocol docstring and the docs page."
},
{
"id": "scope-2",
"resolution": "addressed",
"reason": "Step 1.6 + Step 8 explicitly state that is the discovery catalog (which packs ship which classes, pip deps) and is the integrity manifest (git-pin + optional content hashes). The two are intentionally separate data models; writes the integrity manifest only and does not modify or read from the catalog."
},
{
"id": "all_locations-1",
"resolution": "addressed",
"reason": "Step 6.2 reads the new flags via / / , so existing direct callers in and (which pass ) continue to work without changes."
},
{
"id": "all_locations-2",
"resolution": "addressed",
"reason": "Step 6.1 declares as so a bare invocation is valid. Step 6.2 short-circuits to lock-only mode when . No new subcommand is needed."
},
{
"id": "callers-1",
"resolution": "addressed",
"reason": "Step 3.6 keeps calling with the new default , and explicitly documents this as an intentional safety widening (today's reconfigure tears down a running prompt mid-flight; the new behavior waits for it). Step 7.5 adds a test asserting reconfigure waits for in-flight runs."
},
{
"id": "callers-2",
"resolution": "addressed",
"reason": "Same fix as all_locations-1 \u2014 uses defaults for every new flag so existing direct callers stay green."
}
],
"questions": [
"Should the runtime gate's behavior when exists be (current plan) or ? The current plan stays silent so projects without a lockfile aren't pestered, but a single-shot 'no lockfile present \u2014 nodepack drift cannot be enforced' warning would push adoption."
],
"success_criteria": [
{
"criterion": "All previously-passing tests in still pass after MP-4 lands.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": " exists, refuses with while a is in flight, closes the existing context (preserving the swallow), reopens a fresh one, and clears so is re-read on the next run. Verified by using the fixture asserting , , and post-reload schema-provider re-warm.",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": " tears down and respawns the comfyui serve subprocess for spawn-managed mode and raises (without touching the process) when was provided. Verified by tests using monkeypatched and a stub.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "An in-flight guard exists on and using + : with (default) all in-flight tasks are awaited; with and any pending run, is raised with the exact count. Verified by both single-in-flight and concurrent-runs tests for both session classes \u2014 the concurrent test must fail under any single-slot design.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "External-mode readiness probe uses and produces distinct messages for timeout vs non-200. Verified by a hanging-ready test that exercises the path.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Runtime startup gate fails closed: / with (default) raise from when lists a SHA that doesn't match of the corresponding . With start succeeds with a warning; with (or env ) start succeeds silently. Verified by .",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": " with the new default waits for in-flight runs to complete before tearing down, instead of today's silent mid-prompt teardown. Verified by .",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": " loads in both the legacy three-token form () and the new YAML form, and YAML reads accept both and the legacy field name (with a one-shot deprecation warning). Verified by fixtures covering each path.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": " writes a YAML lockfile containing (required), (optional), and (optional, only when is provided). Existing entries from a legacy lockfile are preserved/migrated. Round-trip equality holds across read-mutate-write-read.",
"priority": "must",
"requires": [
"run_tests",
"run_shell"
]
},
{
"criterion": " exits non-zero on synthetic SHA drift by default and exits zero with , emitting a clear drift line in both cases. The bare invocation (no ) runs the lock-only gate. reads the new flags via so existing direct callers in and keep working unchanged.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "No file under and no edits to are touched by this branch (MP-2 ownership preserved).",
"priority": "must",
"requires": [
"parse_diff"
]
},
{
"criterion": "No , , or stage-aware run-dir naming changes are introduced in or run-dir creation (MP-5 ownership preserved).",
"priority": "must",
"requires": [
"parse_diff",
"read_files"
]
},
{
"criterion": " stays under ~950 lines and stays under ~300 lines.",
"priority": "should",
"requires": [
"read_files"
]
},
{
"criterion": " is named consistently across , , and the Protocol, with the same keyword arg.",
"priority": "should",
"requires": [
"read_files"
]
},
{
"criterion": " is default-ON in the CLI surface so the gate is enforced unless the user opts out ( or ).",
"priority": "should",
"requires": [
"read_files"
]
},
{
"criterion": "The Protocol docstring (and ) explicitly note that and are stateless one-shot adapters with no verb \u2014 use for reload-aware external mode.",
"priority": "should",
"requires": [
"read_files"
]
},
{
"criterion": "Smoke-tested manually: against a real working tree produces YAML matching the new schema; (no args) enforces the gate as designed; downgrades to a warning.",
"priority": "info",
"requires": [
"subjective_judgment"
]
}
],
"assumptions": [
"No existing call site to or is concurrent with an active ; verified by audit (Step 1.2). The default is therefore non-breaking and is also intentionally inherited by as a safer-than-today behavior.",
"External-server mode is a affordance on (constructor ); the existing one-shot and paths are intentionally stateless and out of reload scope, documented in the Protocol docstring and in .",
" is rewritten to YAML on first invocation; legacy three-token files keep loading via format auto-detection (sniff first non-blank, non-comment line for 3 tokens with a 40-char SHA-1 in slot 2).",
" is opt-in per ; the resolver scans for and warns + skips when zero-or-multiple matches are found rather than aborting the lock.",
" (discovery catalog) and (integrity manifest) are intentionally distinct data models; does not consult or modify the catalog (scope-2).",
"Runtime startup gate defaults to and is opt-out via the constructor argument or env var. When no is present in the cwd (the test default), returns immediately \u2014 nothing to enforce \u2014 so unrelated session tests are unaffected. A conftest fixture sets for explicit safety.",
" + is the correct shape for the in-flight guard: the lock matches the documented serial contract on /, the set lets see in-flight task without a single-slot overwrite race, and the count appears in the message for diagnostics.",
" already has an internal 5 s timeout (); wrapping it in is belt-and-braces against socket-accept-then-hang, not a fix for an unbounded call.",
"Direct callers in tests (, ) construct only; the implementation reads new flags via defaults so these stay green.",
"Per the Python rules, widening with a default-valued parameter and adding to is structurally compatible \u2014 implementers only need to satisfy the call shape / ."
],
"delta_from_previous_percent": 73.97,
"structure_warnings": []
}
code
Plan structure warnings from validator:
[]
Existing flags:
[
{
"id": "FLAG-001",
"concern": "Runtime lock enforcement: The plan explicitly defers wiring lockfile drift checks into EmbeddedSession.start() or ServerSession.start(), so SHA drift can still reach runtime startup despite the fail-closed requirement.",
"status": "addressed",
"severity": "significant"
},
{
"id": "FLAG-002",
"concern": "In-flight guard: A single _inflight_run task slot is insufficient because the current sessions do not reject or serialize concurrent run() calls, so one run can overwrite another in-flight task.",
"status": "addressed",
"severity": "significant"
},
{
"id": "FLAG-003",
"concern": "Doctor CLI compatibility: Adding default-on lock flags directly to _cmd_doctor can break existing direct callers unless the implementation supplies defaults for namespaces that only contain path.",
"status": "open",
"severity": "minor"
},
{
"id": "FLAG-004",
"concern": "External server lifecycle split: The plan adds external mode only to ServerSession, while existing external-server use is through runtime.run.run(server_url=...) and comfy_server(server_url=...), so reload/restart-required behavior will not be consistent across runtime surfaces.",
"status": "addressed",
"severity": "significant"
},
{
"id": "verifiability-0",
"concern": "Criterion 12: requires human verification (subjective_judgment).",
"status": "open",
"severity": "minor"
},
{
"id": "issue_hints",
"concern": "Did the work fully address the issue hints, user notes, and approved plan requirements?: Checked the brief's SHA verification requirement against the plan's Step 6. The brief says doctor and/or runtime startup should compare installed nodepacks and the default mismatch policy should fail closed, including refusing to start; the plan explicitly says not to wire node_locks.assert_clean() into session.start(). That is a deliberate partial implementation of the accepted requirement and leaves runtime startup unenforced.",
"status": "addressed",
"severity": "significant"
},
{
"id": "correctness-1",
"concern": "Are the proposed changes technically correct?: Checked the proposed _inflight_run: asyncio.Task | None design against EmbeddedSession.run() and ServerSession.run(). The current code does not serialize multiple concurrent run() calls on the same session, so a single task slot can be overwritten by a second run; stop(wait_for_inflight=True) would then await only the last recorded task while another queued prompt could still be using _comfy or the server.",
"status": "addressed",
"severity": "significant"
},
{
"id": "correctness-2",
"concern": "Are the proposed changes technically correct?: Checked the proposed ServerSession.start() external-mode readiness step against ComfyClient.ready(). The plan asks for a short timeout but does not identify an existing timeout parameter or wrapper; is currently just an async client call, so implementers need to add an explicit or similar or this branch may hang longer than intended.",
"status": "addressed",
"severity": "significant"
},
{
"id": "scope-1",
"concern": "Search for related code that handles the same concept. Is the reported issue a symptom of something broader?: Searched for existing external-server handling and found it lives in via the argument and 's context manager, not in . Adding covers the requested class but does not unify the existing external-server path or expose reload semantics there, so the lifecycle behavior remains split across two runtime surfaces.",
"status": "addressed",
"severity": "significant"
},
{
"id": "scope-2",
"concern": "Search for related code that handles the same concept. Is the reported issue a symptom of something broader?: Searched custom-node resolution code and found is the existing catalog used by both and . The plan's flow scans git checkout directories and only merges existing lock entries, but it does not use the catalog to preserve known classes or pip package metadata; this is acceptable for a lockfile writer if the lockfile is intentionally narrower, but it is a real divergence from the existing custom-node data model.",
"status": "addressed",
"severity": "significant"
},
{
"id": "all_locations-1",
"concern": "Does the change touch all locations AND supporting infrastructure?: Checked and existing tests. is currently called directly in tests with ; if the implementation follows the plan literally and reads / without defaults or test updates, those direct callers will raise rather than preserving existing behavior.",
"status": "addressed",
"severity": "significant"
},
{
"id": "all_locations-2",
"concern": "Does the change touch all locations AND supporting infrastructure?: Checked the doctor command surface. The current parser requires a positional workflow path, while the plan describes lock verification as default-on flags on the same command and only sketches a possible separate invocation; without a subcommand or optional path, there is still no clean invocation that only verifies .",
"status": "addressed",
"severity": "significant"
},
{
"id": "callers-1",
"concern": "Find the callers of the changed function. What arguments do they actually pass? Does the fix handle all of them?: Checked , which currently calls when argv changes. If the plan changes to wait for in-flight runs by default, a concurrent will block behind a running prompt rather than immediately restarting; that may be acceptable, but it is a semantic change the plan should call out because reconfigure is not only a final cleanup path.",
"status": "addressed",
"severity": "significant"
},
{
"id": "callers-2",
"concern": "Find the callers of the changed function. What arguments do they actually pass? Does the fix handle all of them?: Checked callers and parser-created arguments. CLI-created namespaces will have any new flags, but direct tests and any internal callers that construct currently pass no or attributes, so the implementation should use and or update all direct callers.",
"status": "addressed",
"severity": "significant"
}
]
code
Known accepted debt grouped by subsystem:
{}
Escalated debt subsystems:
[]
Debt guidance:
These are known accepted limitations. Do not re-flag them unless the current plan makes them worse, broadens them, or fails to contain them.
Prefix every new concern with a subsystem tag followed by a colon, for example Timeout recovery: retry backoff remains brittle.
When a concern is recurring debt that still needs to be flagged, prefix it with Recurring debt: after the subsystem tag, for example Timeout recovery: Recurring debt: retry backoff remains brittle.
code
Your output template is at: /Users/user_c042661f/Documents/reigh-workspace/vibecomfy/.megaplan/plans/mp-4-custom-node-lifecycle-20260426-1847/critique_output.json
Read this file first — it contains 5 checks, each with a question and guidance.
For each check, investigate the codebase, then add your findings to the findings array for that check.
Each finding needs:
"detail": what you specifically checked and what you found (at least a full sentence)
"flagged": true if this describes a difference, risk, or tension — even if you think it's justified. false only if purely informational with no possible downside.
Every check must end with at least one finding. Never leave a findings array empty. If you found no issue, add one detailed flagged: false finding explaining what you checked and why it appears clear.
When in doubt, flag it — the gate can accept tradeoffs, but it can't act on findings it never sees.
Good: {"detail": "Checked callers of nthroot_mod in solveset.py line 1205 — passes prime moduli only, consistent with the fix.", "flagged": false}
Good: {"detail": "The fix handles empty tuples but not single-element tuples which need a trailing comma.", "flagged": true}
Bad: {"detail": "No issue found", "flagged": false} ← too brief, will be rejected
Bad: {"detail": "The hints suggest approach X but the plan uses Y. However Y is consistent with X's intent.", "flagged": false} ← a different approach than the hints IS a flag. You found a divergence — flag it. The gate decides if it's acceptable.
After filling in checks, add any additional concerns to the flags array (e.g., security, performance, dependencies).
Use the standard format (id, concern, category, severity_hint, evidence). This array can be empty.
Workflow: read the file → investigate → read file again → add finding → write file back. Repeat for each check.
This is critique iteration 2. The template file includes prior findings with their status. Verify addressed flags were actually fixed, re-flag if inadequate, and check for new issues introduced by the revision.
code
Additional guidelines:
- Robustness level: standard. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Over-engineering: prefer the simplest approach that fully solves the problem.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids`: list flag IDs from prior iterations that the revised plan actually resolves (e.g., if the plan was revised to fix FLAG-001, and you confirm the fix is correct, include "FLAG-001"). Only include flags you've verified — don't guess.
- Verify that the plan follows the expected structure when validator warnings or the outline suggest drift.
- Additional flags may use these categories: correctness, security, completeness, performance, maintainability, other.
- Focus on concrete issues, not structural formatting.
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 an independent reviewer. Critique the plan against the actual repository.
MP-4: Custom-node lifecycle and lockfile enforcement.
Runs in parallel with MP-2 (typed Handle scaffold). Zero file overlap — MP-2 owns vibecomfy/blocks/ and vibecomfy/workflow.py; MP-4 owns vibecomfy/runtime/session.py, the nodes CLI, and doctor. Both are P1/P2 deliverables for the design in docs/python_composition_dsl_plan.md (recently revised) and address issues §6 and §7 of docs/python_composition_dsl_review.md.
DELIVERABLES — all must land:
EmbeddedSession.reload_for_nodepack_change() — new explicit verb. Today's documented recipe is session.stop(); install; session.start() (see plan §"Custom Nodes — Adding On the Fly"), but no method captures this contract. The new method:
Refuses to run while a run() call is in flight (see deliverable #2).
Closes the existing _comfy context (mirror stop() at session.py:185-195, including the model_mmap_residency AttributeError swallow).
Reopens a fresh _comfy context (mirror start() at session.py:103-109).
Resets any cached state that would carry stale NODE_CLASS_MAPPINGS references.
Implement equivalent for ServerSession: tear down and respawn the comfyui serve subprocess.
In-flight guard on session.stop() and session.reload_for_nodepack_change() — today, EmbeddedSession.stop() (session.py:185-195) doesn't check whether a run() call is awaiting queue_prompt_api. A concurrent stop tears down _comfy mid-prompt. Add a tracking field (e.g. _inflight_run: asyncio.Future | None) and have stop() either:
Refuse with a clear RuntimeError("session has an in-flight run; await it before stop()"), OR
Cancel-and-await the in-flight future.
Pick whichever matches the existing call-site contract (audit how session.stop() is called today). If both reasonable, expose wait_for_inflight: bool = True.
ServerSession external-mode handling — when configured to talk to an external-managed comfyui serve (one VibeComfy didn't spawn), reload_for_nodepack_change() must NOT terminate it. Raise a defined error class (e.g. ExternalServerRestartRequired) with a clear message. Plan §"Custom Nodes — Adding On the Fly" specifies: "External server mode can report that a restart is required, but it should not terminate a server it does not own." Today there's no detection path for external mode at install time and no error class — both must be created.
vibecomfy nodes lock CLI command — write custom_nodes.lock after resolving any semantic_label values. Schema per plan §"Custom Nodes — Pinning, Hashes, and Lockfiles":
semantic_label (optional advisory, e.g. "v1.4.0", "main").
source_sha256 (optional per-node-class content digest, hex).
Today the lockfile records (name, sha, url) only — see custom_nodes.lock entries for ComfyUI-KJNodes, ComfyUI-WanVideoWrapper. Extend the format and migrate existing entries. Preserve git_sha → git_commit_sha rename with backward-compat read.
vibecomfy doctor SHA verification verb — read the lockfile before session.start() (or as a separate doctor invocation) and verify each installed nodepack's git HEAD matches git_commit_sha. If source_sha256 is present, also verify the named class file's content hash. Default behavior on mismatch: FAIL CLOSED (refuse to start). Provide --allow-drift opt-in to downgrade to a warning. Hardening called out in review §7: "the lockfile is decoration without a doctor/runtime check and a defined mismatch policy."
Tests:
In-flight guard: kick off a slow run() (mock or real), call stop() concurrently, assert documented behavior.
Reload verb: install a fake nodepack, call reload_for_nodepack_change(), verify NODE_CLASS_MAPPINGS reflects the new pack.
External-server-mode: configure session pointing at external URL, call reload, assert ExternalServerRestartRequired raised and external process NOT touched.
SHA verification: synthetic mismatch case fails closed without --allow-drift, warns with it.
CRITICAL CONSTRAINTS:
Backward compatibility: existing custom_nodes.lock must still load (handle git_sha → git_commit_sha gracefully). Existing session.stop() callers must keep working — if you choose the "refuse" option for the in-flight guard, audit every call site.
Do not touch vibecomfy/blocks/, vibecomfy/workflow.py, or anything in the typed-Handle path. MP-2 owns those, running in parallel.
Do not implement VibeFlow stage-aware run-dir naming or stage_index/flow_id in RunResult — those are MP-5 deliverables (SD-013 in the revised plan).
Do not implement schema validation — that's MP-6.
Hot-loading a nodepack into a running session WITHOUT reload is explicitly NOT in scope per the plan: "An optional Python import-and-load path may exist later, but only behind a feature flag and only for proven-safe packs."
KEY FILES (read first, before planning):
docs/python_composition_dsl_plan.md — full design, esp. §"Custom Nodes — Adding On the Fly", §"Custom Nodes — Pinning, Hashes, and Lockfiles", §"Enforcement Gates", and SD-006/SD-013.
lines 88-195: EmbeddedSession class (init, start, run, stop)
lines 198-299: ServerSession class
line 144: queue_prompt_api — currently unshielded
lines 185-195: EmbeddedSession.stop() — no in-flight check today
lines 281-290: ServerSession.reconfigure — only reacts to argv changes, won't catch nodepack installs
lines 487-507: _run_metadata — records vibecomfy git_sha, not custom-node SHAs
vibecomfy/cli/ (search for existing vibecomfy nodes and vibecomfy doctor command modules).
custom_nodes.lock — current entries.
docs/custom_nodes.md — existing custom-node docs.
ACCEPTANCE:
All existing tests pass unchanged.
New tests for in-flight guard, reload verb, external-server detection, lockfile round-trip, and SHA verification all pass.
vibecomfy nodes lock produces a lockfile in the new schema; existing entries migrate cleanly.
vibecomfy doctor fails closed on a synthetic SHA drift; succeeds with --allow-drift.
EmbeddedSession.reload_for_nodepack_change() is exposed and documented.
code
Plan:
Implementation Plan: MP-4 — Custom-Node Lifecycle and Lockfile Enforcement
Overview
Iteration 3 closes two concrete correctness gaps from iteration 2 — neither indicates the approach is wrong:
In-flight tracking window (FLAG-002 / correctness): the _inflight set must span the entirerun() lifetime, not just the queue_prompt_api call. Today run() does several awaits before reaching the queue (start(), _warm_schema_provider, _prepare_prompt_async, _maybe_flush_for_policy, _start_watchdog); a concurrent stop(wait_for_inflight=False) or reload during that window would see an empty set and tear down _comfy mid-prep. Fix: register the task at the top of run() (before any await) and discard in an outer finally. The asyncio.Lock stays narrow around queue_prompt_api — it serializes the actual prompt submission, while the set tracks "is anything in flight" for the whole call.
External-mode reconfigure() (scope / callers): with external_url set, today's plan would let reconfigure() silently no-op (stop is a no-op, start re-points at the same URL) and return True. Fix: raise ExternalServerRestartRequired from reconfigure() whenever self._external is True and new_argv != self._argv, mirroring the reload_for_nodepack_change policy. A future ExternalServerReconfigureRequired could be introduced if the use cases diverge, but for now the same exception type carries the same intent: "VibeComfy can't restart a server it doesn't own."
All other settled decisions (SD-A through SD-H) carry forward unchanged. Hard fences unchanged: no edits to vibecomfy/blocks/ or vibecomfy/workflow.py (MP-2); no flow_id / stage_index (MP-5); no schema validation (MP-6); no in-process hot-load.
Touch points (unchanged from v2): vibecomfy/runtime/session.py, vibecomfy/commands/nodes.py, vibecomfy/commands/doctor.py, new vibecomfy/node_locks.py, tests, tests/conftest.py, docs/custom_nodes.md.
Main Phase
Step 1: Audit current behavior and confirm fences (vibecomfy/runtime/session.py, vibecomfy/runtime/run.py, vibecomfy/runtime/server.py, vibecomfy/commands/doctor.py, vibecomfy/runtime/client.py)
Scope: Small
RereadEmbeddedSession.stop() (vibecomfy/runtime/session.py:185-195) and ServerSession.stop() (vibecomfy/runtime/session.py:292-305) — both wipe state unconditionally; neither tracks in-flight runs today.
Map every awaited operation in EmbeddedSession.run() (lines 111-172) and ServerSession.run() (lines 223-274) so the in-flight tracker can be installed before all of them: start() → _warm_schema_provider → _prepare_prompt_async → _maybe_flush_for_policy → run_dir.mkdir (sync) → _start_watchdog → queue_prompt_api. The new tracking window opens immediately on entry to run() and closes in an outer finally.
Listsession.stop() callers (audited in v2 — unchanged): vibecomfy/runtime/run.py:80, vibecomfy/commands/session.py:69, vibecomfy/runtime/session.py:219, 286, ~14 sequential test sites in tests/test_runtime_session.py. None concurrent with an active run.
List direct _cmd_doctor callers in tests: tests/test_doctor_models.py:54,76, tests/test_cli.py:285 — pass argparse.Namespace(path=...) only; covered by getattr defaults.
ConfirmComfyClient.ready() (vibecomfy/runtime/client.py:12-18) wraps each request in httpx.AsyncClient(timeout=5); we still wrap in asyncio.wait_for(..., timeout=10) for an explicit upper bound (correctness-2, settled v2).
Note the catalog/lockfile split: vibecomfy/node_packs.py is the discovery catalog; custom_nodes.lock is the integrity manifest. Intentionally distinct (settled v2).
Step 2: Concurrency-correct in-flight tracking on EmbeddedSession (vibecomfy/runtime/session.py)
Scope: Medium
Add to EmbeddedSession.__init__:
python
self._run_lock = asyncio.Lock() # serializes queue_prompt_api
self._inflight: set[asyncio.Task] = set() # tracks every awaiting task across the WHOLE run() call
Wrap the entireEmbeddedSession.run() body so tracking spans every await, not just the queue call. Concretely (insertion point = top of run() at vibecomfy/runtime/session.py:111):
The outer try/finally is the only place the task is removed from _inflight. The narrow serializes the prompt submission against concurrent callers (matching the documented serial contract on ) without holding the lock during pre-prep or watchdog finalization. Addresses FLAG-002 / correctness: and now see the in-flight task across schema warmup, prompt prep, and watchdog start — not just the queue submission.
EmbeddedSession.__init__ gets the same lockfile_check parameter for symmetry.
ModifyServerSession.start() (lines 215-221):
First call node_locks.assert_clean(policy=self._lockfile_check) (Step 4 below). Then:
python
if self._external:
self.url = self._external_url
try:
ready = await asyncio.wait_for(ComfyClient(self.url).ready(), timeout=10)
except asyncio.TimeoutError as exc:
raise RuntimeError(f"external comfyui serve at {self.url} not ready within 10s") from exc
if not ready:
raise RuntimeError(f"external comfyui serve at {self.url} not ready (returned non-200)")
return
WrapServerSession.run() (lines 223-274) with the same outer try/finally shape as Step 2.2 — self._inflight.add(task) on entry, in outer , narrow around .
(Unchanged from v2 — settled SD-A, SD-C, SD-H. Brief recap for executability.)
Createvibecomfy/node_locks.py with NodepackLock, LockMismatch, and LockfileDriftError dataclasses/exception.
Readerload_locks(path=Path("custom_nodes.lock")) -> list[NodepackLock]: missing/empty → []; sniff first non-blank, non-comment line for 3 tokens with a 40-char SHA-1 in slot 2 → legacy form; otherwise YAML; accept git_sha and git_commit_sha field names with a one-shot deprecation warning.
Writerwrite_locks(...): canonical YAML key order (name, repo_url, git_commit_sha, optional semantic_label, optional source_sha256 sorted by class name).
Resolverresolve_pack(repo_dir, *, hash_classes=()) -> NodepackLock: git rev-parse HEAD, git config --get remote.origin.url, best-effort git describe --tags --exact-match/git rev-parse --abbrev-ref HEAD, optional per-class SHA-256 by scanning repo_dir/**/*.py for class <Name>(.
Register lock subparser with --root, --lockfile, --hash-classes, --dry-run.
Walk <root>/<pack>/.git; resolve via node_locks.resolve_pack; merge with existing lockfile entries; --dry-run writes YAML to stdout, else node_locks.write_locks(...). Exit non-zero only when <root>/<name>/.git exists but git rev-parse HEAD fails.
Step 6: vibecomfy doctor SHA verification with backward-compat (vibecomfy/commands/doctor.py)
Scope: Small
(Unchanged from v2 — settled SD-F.)
Make pathnargs='?', default=None; add --check-nodepack-locks (BooleanOptionalAction, default True) and --allow-drift.
_cmd_doctor reads new flags via getattr(args, ..., default). Lock-only invocation when path is None. Workflow-doctor flow unchanged otherwise.
Conftest (tests/conftest.py): autouse-or-explicit fixture sets VIBECOMFY_LOCK_CHECK=skip for session-lifecycle tests that don't ship a fixture lockfile. Doctor/runtime-gate tests opt back in with monkeypatch.setenv("VIBECOMFY_LOCK_CHECK", "enforce").
In-flight guard — pre-queue window (covers FLAG-002 / correctness for v3): monkeypatch _warm_schema_provider (or _prepare_prompt_async) to await an asyncio.Eventbeforequeue_prompt_api is reached. Start run() as a task, yield once, call session.stop(wait_for_inflight=False) → assert RuntimeError("session has 1 in-flight run(s); ..."). Set the event, await the run, call session.stop() (default True) → clean teardown. This test would fail if _inflight.add lived inside the lock-holding block. Mirror for ServerSession.
In-flight guard — single in-flight at queue: same shape as today's plan, but gated on FakeComfy.queue_prompt_api awaiting an event. Demonstrates the lock-window case still works.
In-flight guard — concurrent runs (settled v2): kick off two run() tasks, both gated on the same event. Assert _run_lock serializes them (FakeComfy.queue_calls snapshot taken inside the await shows exactly one active call). session.stop(wait_for_inflight=False) → assert RuntimeError mentions "2 in-flight". Set event, both finish, clean stop.
Add one paragraph: lockfile schema (git_commit_sha required; semantic_label, source_sha256 optional), vibecomfy nodes lock writer, vibecomfy doctor (default-on lock check, --allow-drift opt-out), runtime gate (lockfile_check constructor arg / VIBECOMFY_LOCK_CHECK env override). One sentence stating that runtime/run.py's server_url= and runtime/server.py's comfy_server(server_url=...) are stateless one-shot adapters with no reload verb — use ServerSession(external_url=...) for reload-aware external mode. One sentence stating that ServerSession.reconfigure() raises ExternalServerRestartRequired when an external_url session is asked to change argv.
Execution Order
Step 1 audit — confirms fences, call-site safety, the catalog/lockfile split, and the full pre-queue await chain in run().
Step 4 (vibecomfy/node_locks.py) — pure module; everyone imports from it.
Step 2 + Step 3 (session.py changes). Step 3 adds the runtime gate call, the external-mode reconfigure refusal, and the in-flight tracking expansion.
Step 5 (nodes lock CLI) and Step 6 (doctor flag/optional path); independent — either order.
Step 7 tests interleaved with each implementation step (write the pre-queue-window test alongside Step 2.2; the external-mode reconfigure test alongside Step 3.6).
Step 8 docs last so wording matches shipped flags.
pytest tests/test_doctor_nodepacks.py tests/test_nodes_cli.py -x for CLI coverage.
pytest tests/ (full suite) to confirm zero regressions in the existing 14 session.stop() callers, _cmd_doctor direct callers, and ServerSession.reconfigure() callers (none today, but the new external-mode raise must not surprise managed-mode tests).
Manual smoke (info-only): vibecomfy nodes lock --dry-run --root custom_nodes; vibecomfy doctor (no args) for lock-only mode; verify ExternalServerRestartRequired text reads cleanly when triggered against a stub external server.
code
Plan metadata:
{
"version": 3,
"timestamp": "2026-04-26T17:13:37Z",
"hash": "sha256:5c53e0191ca3765462b7e5b85f2debf622304189f5d1558bf0a12e09a1a85efd",
"changes_summary": "Two concrete fixes, no architectural change. (1) In-flight tracking window (FLAG-002 / correctness): Step 2.2 now wraps the entirerun() body in try/finally with self._inflight.add(task) at entry (before start(), schema warmup, prompt prep, watchdog start, etc.) and discard only in the outer finally. The asyncio.Lock stays narrow around queue_prompt_api for serialization. A new test (Step 7.2) gates on _warm_schema_provider instead of the queue call, proving stop(wait_for_inflight=False) sees the in-flight task during the pre-queue window \u2014 a test that would fail under the v2 design. Step 3.4 applies the same shape to ServerSession.run(). (2) External-mode reconfigure() (scope / callers): Step 3.6 now explicitly raises ExternalServerRestartRequired from reconfigure() whenever self._external is True and new_argv != self._argv, instead of silently no-op'ing. Same exception type as reload_for_nodepack_change carries the same intent. New test in Step 7.6 covers both the refusal case and the same-argv no-op case. Docs (Step 8) gain one sentence describing the new refusal. Added one new must-priority success criterion for the pre-queue tracking window and one for external-mode reconfigure refusal.",
"flags_addressed": [
{
"id": "FLAG-002",
"resolution": "addressed",
"reason": "Step 2.2 (and Step 3.4 for ServerSession) now wraps the entire run() body in try/finally with self._inflight.add(asyncio.current_task()) at the top of the method \u2014 before start(), _warm_schema_provider, _prepare_prompt_async, _maybe_flush_for_policy, run_dir.mkdir, and _start_watchdog. The discard happens only in the outermost finally. The narrow async with self._run_lock: stays around queue_prompt_api for serialization. Step 7.2 adds a dedicated test that gates on _warm_schema_provider (a pre-queue await) and asserts stop(wait_for_inflight=False) raises with the correct in-flight count \u2014 this test would fail under the v2 design where tracking opened only at the queue call."
},
{
"id": "correctness",
"resolution": "addressed",
"reason": "Same fix as FLAG-002 \u2014 they are the same flag. The in-flight set is now the source of truth for 'is anything in flight' across the run lifetime, not just the queue submission window. The asyncio.Lock continues to serialize the actual prompt submission, but the set's window covers every awaited operation in ."
},
{
"id": "scope",
"resolution": "addressed",
"reason": "Step 3.6 explicitly handles external mode in : when is True and , it raises with a message naming the argv change. The same-argv path still returns without raising (no actual change). This mirrors the policy and avoids the silent-no-op-then-misleading-True-return behavior the flag identified."
},
{
"id": "callers",
"resolution": "addressed",
"reason": "Same fix as . The future caller scenario the flag identified \u2014 invoking on an external-mode session \u2014 now produces a defined, named error class instead of silently re-pointing at the original URL. Step 7.6 adds explicit test coverage."
},
{
"id": "correctness-1",
"resolution": "addressed",
"reason": "Already marked addressed in v2 metadata; the in-flight tracking design (asyncio.Lock + set[Task]) is unchanged in v3, only the is widened. Concurrent calls remain serialized by the lock and tracked in the set."
}
],
"questions": [
"Should be split into (for ) and (for ), or stay as a single class? Current plan reuses one class \u2014 same intent ('VibeComfy can't restart a server it doesn't own'), simpler exception hierarchy. A split would be more precise if downstream code wants to distinguish the trigger; no concrete need today."
],
"success_criteria": [
{
"criterion": "All previously-passing tests in still pass after MP-4 lands.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": " exists, refuses with while a is in flight, closes the existing context (preserving the swallow), reopens a fresh one, and clears so is re-read on the next run. Verified by using the fixture asserting , , and post-reload schema-provider re-warm.",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": " tears down and respawns the comfyui serve subprocess for spawn-managed mode and raises (without touching the process) when was provided. Verified by tests using monkeypatched and a stub.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": " raises when is True and (instead of silently no-op'ing). Same-argv reconfigure on an external session returns without raising. Verified by covering both branches.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "An in-flight guard exists on and using (narrow, around the queue call) + (wide, spanning the entire lifetime). With (default) all in-flight tasks are awaited; with and any pending run, is raised with the exact count. Verified by both single-in-flight and concurrent-runs tests for both session classes.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "In-flight tracking spans the lifetime, not just the queue submission window. Verified by a test that awaits an event inside (a pre-queue await) and asserts raises mentioning the in-flight count \u2014 this test must fail under any design where happens after /schema warmup/prompt prep.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "External-mode readiness probe uses and produces distinct messages for timeout vs non-200. Verified by a hanging-ready test that exercises the path.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Runtime startup gate fails closed: / with (default) raise from when lists a SHA that doesn't match of the corresponding . With start succeeds with a warning; with (or env ) start succeeds silently. Verified by .",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": " in managed mode with the new default waits for in-flight runs to complete before tearing down, instead of today's silent mid-prompt teardown. Verified by .",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": " loads in both the legacy three-token form () and the new YAML form, and YAML reads accept both and the legacy field name (with a one-shot deprecation warning). Verified by fixtures covering each path.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": " writes a YAML lockfile containing (required), (optional), and (optional, only when is provided). Existing entries from a legacy lockfile are preserved/migrated. Round-trip equality holds across read-mutate-write-read.",
"priority": "must",
"requires": [
"run_tests",
"run_shell"
]
},
{
"criterion": " exits non-zero on synthetic SHA drift by default and exits zero with , emitting a clear drift line in both cases. The bare invocation (no ) runs the lock-only gate. reads the new flags via so existing direct callers in and keep working unchanged.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "No file under and no edits to are touched by this branch (MP-2 ownership preserved).",
"priority": "must",
"requires": [
"parse_diff"
]
},
{
"criterion": "No , , or stage-aware run-dir naming changes are introduced in or run-dir creation (MP-5 ownership preserved).",
"priority": "must",
"requires": [
"parse_diff",
"read_files"
]
},
{
"criterion": " stays under ~950 lines and stays under ~300 lines.",
"priority": "should",
"requires": [
"read_files"
]
},
{
"criterion": " is named consistently across , , and the Protocol, with the same keyword arg.",
"priority": "should",
"requires": [
"read_files"
]
},
{
"criterion": " is default-ON in the CLI surface so the gate is enforced unless the user opts out ( or ).",
"priority": "should",
"requires": [
"read_files"
]
},
{
"criterion": "The Protocol docstring and explicitly note that and are stateless one-shot adapters with no verb \u2014 use for reload-aware external mode \u2014 and that raises on argv changes for external sessions.",
"priority": "should",
"requires": [
"read_files"
]
},
{
"criterion": "Smoke-tested manually: against a real working tree produces YAML matching the new schema; (no args) enforces the gate as designed; downgrades to a warning; produces a clean error message.",
"priority": "info",
"requires": [
"subjective_judgment"
]
}
],
"assumptions": [
"The pre-queue awaits in (, , , , ) are non-trivial to instrument individually but cheap to wrap collectively \u2014 a single outer registering on entry and discarding on exit covers all of them without per-await bookkeeping.",
"The narrow around keeps the serialization scope minimal: only the actual prompt submission is mutually exclusive across concurrent callers. Pre-queue work (schema warmup, prompt prep) can run concurrently across tasks because the underlying calls are read-only/idempotent. This matches the documented serial-prompt contract while not over-locking.",
"External-mode raising is consistent with 's policy: VibeComfy can advertise that a restart is required, but never restarts a server it does not own. A future split into is reserved if the use cases diverge, but for now the same exception type carries the same intent.",
"All v2 settled decisions (SD-A through SD-H) are preserved unchanged in v3.",
"No existing call site to invokes it on an external-mode session today (external mode is new in this MP), so the new raise is non-breaking. The daemon CLI does not currently construct external-mode sessions; adding that surface is deferred."
],
"delta_from_previous_percent": 76.7,
"structure_warnings": []
}
code
Plan structure warnings from validator:
[]
Existing flags:
[
{
"id": "FLAG-002",
"concern": "Runtime lifecycle: The revised in-flight guard still starts tracking too late in run(), so stop(wait_for_inflight=False) or reload can miss an active run during schema warmup, prompt preparation, flush policy, or watchdog startup before the queue call is reached.",
"status": "addressed",
"severity": "significant"
},
{
"id": "verifiability-0",
"concern": "Criterion 16: requires human verification (subjective_judgment).",
"status": "open",
"severity": "minor"
},
{
"id": "correctness-1",
"concern": "Are the proposed changes technically correct?: Checked the proposed _inflight_run: asyncio.Task | None design against EmbeddedSession.run() and ServerSession.run(). The current code does not serialize multiple concurrent run() calls on the same session, so a single task slot can be overwritten by a second run; stop(wait_for_inflight=True) would then await only the last recorded task while another queued prompt could still be using _comfy or the server.",
"status": "addressed",
"severity": "significant"
},
{
"id": "FLAG-005",
"concern": "External server lifecycle: ServerSession.reconfigure() behavior is undefined for external_url sessions and would appear to succeed even though VibeComfy cannot apply argv/config changes to a server it did not spawn.",
"status": "open",
"severity": "minor"
},
{
"id": "correctness",
"concern": "Are the proposed changes technically correct?: The revised in-flight plan still adds tasks to _inflight only immediately around queue_prompt_api / ComfyClient.queue_prompt, after start(), schema warmup, prompt preparation, fingerprint flush policy, run-dir creation, and watchdog startup. A concurrent stop(wait_for_inflight=False) or reload during those pre-queue awaits would see an empty _inflight set and could tear down _comfy or the server while run() is already active, contradicting the plan's own claim that the set is the source of truth for 'is anything in flight'.",
"status": "addressed",
"severity": "significant"
},
{
"id": "scope",
"concern": "Search for related code that handles the same concept. Is the reported issue a symptom of something broader?: Checked the new external-mode scope against ServerSession.reconfigure(). The plan keeps the managed-mode reconfigure logic but does not define external-mode behavior; with external_url set, a config change would run through stop() as a no-op, ignore the new config on start(), keep pointing at the original external URL, and still return True, which is misleading for a session that cannot reconfigure or restart the server it does not own.",
"status": "addressed",
"severity": "significant"
},
{
"id": "callers",
"concern": "Find the callers of the changed function. What arguments do they actually pass? Does the fix handle all of them?: Checked external-mode callers introduced by the plan. Because is new, there are no existing callers to break, but any future caller that invokes on such a session would hit the undefined external-mode behavior described in the scope finding.",
"status": "addressed",
"severity": "significant"
}
]
code
Known accepted debt grouped by subsystem:
{}
Escalated debt subsystems:
[]
Debt guidance:
These are known accepted limitations. Do not re-flag them unless the current plan makes them worse, broadens them, or fails to contain them.
Prefix every new concern with a subsystem tag followed by a colon, for example Timeout recovery: retry backoff remains brittle.
When a concern is recurring debt that still needs to be flagged, prefix it with Recurring debt: after the subsystem tag, for example Timeout recovery: Recurring debt: retry backoff remains brittle.
code
Your output template is at: /Users/user_c042661f/Documents/reigh-workspace/vibecomfy/.megaplan/plans/mp-4-custom-node-lifecycle-20260426-1847/critique_output.json
Read this file first — it contains 5 checks, each with a question and guidance.
For each check, investigate the codebase, then add your findings to the findings array for that check.
Each finding needs:
"detail": what you specifically checked and what you found (at least a full sentence)
"flagged": true if this describes a difference, risk, or tension — even if you think it's justified. false only if purely informational with no possible downside.
Every check must end with at least one finding. Never leave a findings array empty. If you found no issue, add one detailed flagged: false finding explaining what you checked and why it appears clear.
When in doubt, flag it — the gate can accept tradeoffs, but it can't act on findings it never sees.
Good: {"detail": "Checked callers of nthroot_mod in solveset.py line 1205 — passes prime moduli only, consistent with the fix.", "flagged": false}
Good: {"detail": "The fix handles empty tuples but not single-element tuples which need a trailing comma.", "flagged": true}
Bad: {"detail": "No issue found", "flagged": false} ← too brief, will be rejected
Bad: {"detail": "The hints suggest approach X but the plan uses Y. However Y is consistent with X's intent.", "flagged": false} ← a different approach than the hints IS a flag. You found a divergence — flag it. The gate decides if it's acceptable.
After filling in checks, add any additional concerns to the flags array (e.g., security, performance, dependencies).
Use the standard format (id, concern, category, severity_hint, evidence). This array can be empty.
Workflow: read the file → investigate → read file again → add finding → write file back. Repeat for each check.
This is critique iteration 3. The template file includes prior findings with their status. Verify addressed flags were actually fixed, re-flag if inadequate, and check for new issues introduced by the revision.
code
Additional guidelines:
- Robustness level: standard. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Over-engineering: prefer the simplest approach that fully solves the problem.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids`: list flag IDs from prior iterations that the revised plan actually resolves (e.g., if the plan was revised to fix FLAG-001, and you confirm the fix is correct, include "FLAG-001"). Only include flags you've verified — don't guess.
- Verify that the plan follows the expected structure when validator warnings or the outline suggest drift.
- Additional flags may use these categories: correctness, security, completeness, performance, maintainability, other.
- Focus on concrete issues, not structural formatting.
“You are already running inside the megaplan harness for this step. Do the requested….” Conversation with gpt-5.5, from the Peter O’Mallet DataClaw Conversations dataset. The Chat Archive, 2026. https://thechatarchive.com/c/01m80eqaajp9azv5zmgqy538q8
Dataset releases
Not yet included in a published release.
await self.stop(wait_for_inflight=False) (we just verified the set is empty).
await self.start() — reopens the Comfy context (mirrors lines 103-109).
Clear self._schema_provider and self._schema_warning_emitted so NODE_CLASS_MAPPINGS is re-read on the next run().
Wrap the queue call in ServerSession.run() (line 248) with the same _inflight set + _run_lock shape as EmbeddedSession.run().
Intentional semantic widening (callers-1): today reconfigure() tears down a running prompt mid-flight; the new default waits for in-flight runs to finish before restarting. That is strictly safer and matches the new contract. Document in the method docstring; no caller needs to opt out today (the only existing caller path is from the daemon CLI which doesn't run prompts via ServerSession.run itself).
Refuse on in-flight (same shape as EmbeddedSession).
If self._external: raise ExternalServerRestartRequired(f"external comfyui serve at {self.url}; restart it manually to pick up nodepack changes (reason={reason!r})"). Do not touch the process, do not call self.stop().
Update the VibeSession Protocol (lines 68-85) to add async def reload_for_nodepack_change(self, *, reason: str | None = None) -> None. Add a one-line docstring on the Protocol noting that the one-shot comfy_server() / runtime.run.run(server_url=...) paths in runtime/run.py and runtime/server.py are stateless and intentionally have no reload verb (FLAG-004 / scope-1).
source_sha256: only for class names in hash_classes. Locate by scanning repo_dir/**/*.py for class <Name>(; if exactly one match, hash that file's bytes with SHA-256; if zero or multiple matches, log a warning and skip that class (do not abort the whole lock).
Per lock: if custom_nodes_dir/<name>/.git is missing → LockMismatch(kind="missing", expected=git_commit_sha, actual="").
Else git -C <dir> rev-parse HEAD; if it differs → LockMismatch(kind="sha_drift", expected=..., actual=...).
For each (class_name, expected_sha256) in source_sha256: locate the class file as in resolve_pack; recompute SHA-256; if it differs → LockMismatch(kind="source_drift", expected=..., actual=..., detail=class_name).
Honor env var override: os.environ.get("VIBECOMFY_LOCK_CHECK", policy). When effective policy is "skip", return immediately.
locks = load_locks(lockfile). When empty, return (no lockfile → nothing to enforce; keeps tests green and matches the brief's "lockfile is decoration without a doctor/runtime check" framing — there has to be a lockfile to enforce).
mismatches = verify_locks(locks, custom_nodes_dir=custom_nodes_dir). When empty, return.
When effective policy is "warn": logger.warning(...) for each mismatch and return.
When effective policy is "enforce": raise LockfileDriftError("nodepack lockfile drift: ..." with a structured per-mismatch summary in the message). New exception class lives in node_locks.py.
This satisfies FLAG-001 / issue_hints — runtime startup does enforce, gated by lockfile_check on the session constructor (default "enforce") and overridable via VIBECOMFY_LOCK_CHECK. Tests that don't ship a custom_nodes.lock are unaffected because load_locks of a missing path returns [].
No wiring of node_locks.assert_clean() into a separate doctor surface — Step 4's assert_clean is the runtime hook (called from session.start()); Step 6's verify_locks + print is the doctor surface. Same data layer, two presentations, no duplication.
Add a ready() returns False test → assert RuntimeError("...not ready (returned non-200)").
Add a ready() hangs test (use asyncio.Event that never gets set inside the patched ready) wrapped via monkeypatch of the timeout to a short value → assert RuntimeError("...not ready within ...s") (correctness-2).
Kick off a slow ServerSession.run(); concurrently call await session.reconfigure(new_config_with_different_argv). Assert reconfigure waits for the in-flight run to finish, then restarts. (Documents callers-1 as intentional behavior.)
Lockfile round-trip (tests/test_node_locks.py):
Round-trip: write a fixture with two packs (one with semantic_label, one with source_sha256: {ClassA: ...}); read; mutate; write; reread; deep-equal.
Legacy three-token form: parse the current custom_nodes.lock content (two entries) → assert two NodepackLocks with empty semantic_label/source_sha256.
YAML with legacy git_sha key → parses identically; deprecation warning emitted exactly once across multiple loads.
Runtime startup gate (tests/test_node_locks.py or tests/test_runtime_session.py):
Construct an EmbeddedSession with lockfile_check="enforce", write a synthetic custom_nodes.lock and a mismatched fake custom_nodes/PackA/.git/HEAD in tmp_path, monkeypatch subprocess.run for git rev-parse. await session.start() → assert LockfileDriftError.
Same scenario with lockfile_check="warn" → assert start succeeds and a warning is logged.
Same scenario with VIBECOMFY_LOCK_CHECK=skip env var → assert start succeeds silently. (Covers FLAG-001 / issue_hints.)
SHA verification via vibecomfy doctor (tests/test_doctor_nodepacks.py):
Build tmp_path/custom_nodes/PackA/.git; monkeypatch subprocess.run for git rev-parse. Synthetic mismatched lockfile → _cmd_doctor(argparse.Namespace()) (no path, no flags) → assert exit 1 and the "nodepack drift" line.
Repeat with argparse.Namespace(allow_drift=True) → exit 0, warning line.
Repeat with argparse.Namespace(path=str(workflow_fixture)) (existing-style call) → confirms backward compat through getattr (callers-2).
Set up tmp_path/custom_nodes/PackA with a stub git tree (or monkeypatch subprocess.run to return canned rev-parse/config/describe output). Run _cmd_nodes_lock(argparse.Namespace(root=..., lockfile=..., hash_classes="", dry_run=False)); assert the resulting YAML round-trips through load_locks to the expected NodepackLock.
Same with --hash-classes "ClassA" plus a stub PackA/nodes.py containing class ClassA(...): → assert source_sha256 is populated.
ModifyEmbeddedSession.stop(wait_for_inflight: bool = True) (unchanged from v2):
If self._inflight:
When wait_for_inflight: await asyncio.gather(*[asyncio.shield(t) for t in tuple(self._inflight)], return_exceptions=True).
When not: raise RuntimeError(f"session has {len(self._inflight)} in-flight run(s); await them before stop()").
Then run today's teardown (lines 185-195) preserving the model_mmap_residencyAttributeError swallow. Reset _context, _comfy, _schema_provider, _schema_warning_emitted, and clear self._inflight.
async def reconfigure(self, config: SessionConfig) -> bool:
new_argv = _comfy_server_argv(config)
if new_argv == self._argv:
self.config = config
return False
if self._external:
# We do not own this comfyui serve; restarting it requires the
# operator. Refuse rather than silently re-pointing at the same URL.
raise ExternalServerRestartRequired(
f"external comfyui serve at {self.url} cannot be reconfigured by VibeComfy "
f"(argv change requested: {self._argv} -> {new_argv}); restart it manually."
)
await self.stop() # default wait_for_inflight=True — intentional safety widening (callers-1, settled v2)
self.config = config
self._argv = new_argv
await self.start()
return True
Two distinct semantic changes are now explicit on this method:
External mode (new in v3):argv change while self._external raises ExternalServerRestartRequired. Resolves the scope / callers flag.
Managed mode (settled v2): the new default wait_for_inflight=True waits for in-flight runs before tearing down — strictly safer than today's silent mid-prompt teardown.
If self._external: raise ExternalServerRestartRequired(f"external comfyui serve at {self.url}; restart it manually to pick up nodepack changes (reason={reason!r})"). Do not touch the process, do not call self.stop().
Update the VibeSession Protocol (lines 68-85) to add async def reload_for_nodepack_change(self, *, reason: str | None = None) -> None. Add a one-line docstring noting that the one-shot comfy_server() / runtime.run.run(server_url=...) paths in runtime/run.py and runtime/server.py are stateless and intentionally have no reload verb (FLAG-004, settled v2).
ExternalServerRestartRequired
await session.stop()
reconfigure() refuses (NEW in v3 — covers scope / callers): construct external session with port 8200; await session.start(); call await session.reconfigure(SessionConfig(port=8201)) → assert ExternalServerRestartRequired with a message naming the argv change. Confirm no client request was made and self.url still equals the original external_url.
reconfigure() with same argv on external session: returns False without raising (no actual change).
ready() hangs → RuntimeError("...not ready within 10s").
reconfigure() semantic widening (managed mode, settled v2): kick off a slow ServerSession.run(); concurrently call await session.reconfigure(new_config_with_different_argv); assert reconfigure waits for the in-flight run to finish, then restarts.
Lockfile round-trip (tests/test_node_locks.py): write/read/mutate/write/reread deep-equal; legacy three-token form parses; YAML with git_sha parses identically with one-shot deprecation warning.
Runtime startup gate (tests/test_node_locks.py):
Construct EmbeddedSession(lockfile_check="enforce"), write a synthetic custom_nodes.lock and a mismatched fake custom_nodes/PackA/.git/HEAD in tmp_path, monkeypatch subprocess.run for git rev-parse. await session.start() → assert LockfileDriftError.
Same with lockfile_check="warn" → assert start succeeds and a warning is logged.
Same with VIBECOMFY_LOCK_CHECK=skip env var → assert start succeeds silently.
SHA verification via vibecomfy doctor (tests/test_doctor_nodepacks.py):
Build tmp_path/custom_nodes/PackA/.git; monkeypatch subprocess.run for git rev-parse. Synthetic mismatched lockfile → _cmd_doctor(argparse.Namespace()) → exit 1 and the "nodepack drift" line.
Repeat with argparse.Namespace(allow_drift=True) → exit 0, warning line.
Repeat with argparse.Namespace(path=str(workflow_fixture)) → confirms backward compat through getattr (callers-2).
vibecomfy nodes lock CLI (tests/test_nodes_cli.py): stub git tree under tmp_path/custom_nodes/PackA; run command; assert YAML round-trips through load_locks. Repeat with --hash-classes "ClassA" and a stub PackA/nodes.py containing class ClassA(...): to populate source_sha256.