Skip to content

feat(verify): add local JIT compiler (openadapt_verify.jit) and mcpify --from-compiled - #2633

Open
abrichr wants to merge 3 commits into
mainfrom
gemini/jit-compiler-v1
Open

abrichr wants to merge 3 commits into
mainfrom
gemini/jit-compiler-v1

Conversation

@abrichr

@abrichr abrichr commented Nov 24, 2026

Copy link
Copy Markdown
Member

Summary

Adds the local JIT workflow compiler (openadapt_verify.jit) and exposes compiled plans as verified MCP tools via mcpify --from-compiled. All changes are scoped to packages/verify/ and .github/workflows/packages.yml.

What changed

  • packages/verify/src/openadapt_verify/jit.py:
    • ParameterBinder: templates concrete action values into {{param_name}} (longest-match first, refuses empty values, flags secret-named parameters like password/api_key/token, and audits serialized plans so raw secret values never persist on disk).
    • CompiledStep, CompiledPlanStats, CompiledPlan: JSON-serializable plan (openadapt.jit.plan/v1) saved atomically to .openadapt/compiled/<name>.json with fallback selector chains (role/label/css/text), templated read-back expectations, cumulative latency/cost savings, and to_workflow_tool_spec() conversion.
    • jit_wrap: sync and async decorator that records actions on Cold Run (pip install -r requirements (There is no requirements file in the repo) #1) through RecordingPageProxy, writes the cache only when independent read-back passes VERIFIED, replays deterministically with substituted parameters on Warm Runs (alembic upgrade head #2+) with 0 agent calls, and runs bounded step-level self-healing (max_heal_steps) that updates the cache only after final read-back passes VERIFIED.
    • JitResult & format_scorecard: structured result with optional Ed25519 SignedReceipt and terminal scorecard.
  • packages/verify/src/openadapt_verify/mcpify.py:
    • Added load_compiled_tools(cache_dir) and --from-compiled <dir> on serve and config so every CompiledPlan JSON in .openadapt/compiled/ is exposed as a verified MCP tool with its parameterized JSON Schema.
  • packages/verify/src/openadapt_verify/__init__.py: exported jit, jit_wrap, CompiledPlan, CompiledStep, JitResult, ParameterBinder, format_scorecard, and load_compiled_tools.
  • packages/verify/tests/test_jit.py: 8 tests covering longest-match parameter binding, Cold -> Warm 0-agent replay with different parameters + Ed25519 receipt verification, unconfirmed-write cache refusal, bounded self-heal -> warm Run pip install -r requirements.txt #3, failed self-heal cache preservation, secret redaction, async jit_wrap, and mcpify --from-compiled.
  • .github/workflows/packages.yml: updated verify-facade collected test count from 168 to 176.

Verification

  • PYTHONPATH=src:../flow:../types pytest tests/test_jit.py -v: 8 passed in 0.61s (176 tests collected across packages/verify/tests)
  • ruff check src tests & ruff format --check src tests: passed
  • mypy src/openadapt_verify: Success: no issues found in 21 source files
  • gitleaks detect --no-git: no leaks found

@abrichr

abrichr commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Gemini
Review-Mode: independent-subagent
Reviewed-Head: 9b5d946

Full read-only audit of all 5 files in #2633 (packages/verify/src/openadapt_verify/jit.py, mcpify.py, __init__.py, tests/test_jit.py, .github/workflows/packages.yml). Found 4 concrete P1 bugs that should be fixed before approval:

Blocking Findings (P1)

  1. ParameterBinder.bind_value double-substitutes already-inserted {{name}} placeholders (jit.py:194-206)
    Iteratively calling templated = templated.replace(pval, f"{{{{{pname}}}}}") corrupts templates whenever a later parameter value matches an earlier parameter name. Example: params={"user": "alice", "field": "user"} turns "hello alice" into "hello {{user}}" on pass 1 and then "hello {{{{field}}}}" on pass 2.

    • Fix: Use a single-pass regex alternation (re.compile("|".join(re.escape(v) for _, v in ordered))) with a lookup dict so inserted {{...}} placeholders are never re-matched.
  2. Empty recording (proxy.recorded == []) on Cold Run caches a 0-step plan and mints a VERIFIED SignedReceipt (jit.py:1166-1215, 1384-1435)
    If fn performs zero recorded actions (e.g., uses page.evaluate(), page.mouse, or does nothing on a page where the expected text already exists), Cold Run still writes CompiledPlan(steps=()) to disk and signs a VERIFIED receipt. Every subsequent Warm Run then executes 0 steps and immediately runs read-back.

    • Fix: Refuse to compile, cache, or sign a VERIFIED receipt when not proxy.recorded (return status="UNCONFIRMED_WRITE" or "STOPPED", plan_path=None, receipt=None) and reject empty steps in CompiledPlan.from_dict.
  3. Full-agent fallback healer (healer_fn=None) duplicates prefix steps 0..idx-1 in the saved plan (jit.py:1298-1305, 1515-1520)
    When healer_fn is None, active_healer is fn (the full workflow starting from step 0). Doing candidate_steps[idx:] = healed_with_counts keeps the already-replayed prefix 0..idx-1 and appends the full workflow recording after it, saving duplicated prefix steps to disk.

    • Fix: When healer_fn is None, replace the full plan (candidate_steps = healed_with_counts) rather than slicing at idx:.
  4. Secret parameter values can leak into JitResult.reason and plan.readback_expectations when readback_expectations is supplied (jit.py:935-950, 971-986, 1064-1069)
    _default_fresh_reload_readback_sync/_async filter out is_secret_param(k) only in the default else branch; when explicit readback_expectations is passed, secret-named keys are retained and on failure missing = [f"{k}={v!r}" ...] embeds the plaintext secret value into JitResult.reason (which format_scorecard prints).

    • Fix: Strip/reject secret-named keys in readback_expectations (and never include secret values in JitResult.reason).

Non-Blocking Notes (P2)

  • SignedReceipt records llm_calls=0 on Cold Run and Healed Run (jit.py:1198, 1358, 1418, 1574): Pass llm_calls=1 (or len(healed_indices)) on cold/healed runs so only genuine warm runs attest llm_calls=0.
  • Symlink containment in load_compiled_tools (mcpify.py:1634): Verify path.resolve().is_relative_to(root.resolve()) before reading *.json files.
  • Read-back exceptions (jit.py:1170, 1308, 1388, 1523): Catching transport/reload errors from readback_fn / reload() and returning UNCONFIRMED_WRITE (with receipt=None and no cache write) would avoid unhandled crashes on transient reload failures.

@abrichr

abrichr commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Gemini
Review-Mode: independent-subagent
Reviewed-Head: 0a67b0c

Delta review of 9b5d94663f7107595b2f11438b2af25272d0ad0e..0a67b0c8db85c256b6c1abe9a8b4cb7c9fc24715 confirms all 4 P1 findings and all 3 P2 notes are cleanly resolved with regression tests:

  • P1 pip install -r requirements (There is no requirements file in the repo) #1 (ParameterBinder.bind_value): Single-pass regex alternation ordered by descending length prevents double-substitution of already-inserted {{name}} placeholders.
  • P1 alembic upgrade head #2 (empty recording): Both sync and async cold runs stop without caching or signing when not proxy.recorded, and CompiledPlan.from_dict rejects empty steps.
  • P1 pip install -r requirements.txt #3 (full-agent fallback healer): When healer_fn is None, both sync and async paths replace candidate_steps = healed_with_counts instead of duplicating prefix steps 0..idx-1.
  • P1 Modify record.py to accept a command line description of the task that is being performed #4 (secret redaction & expectations): _reject_secret_expectations blocks secret keys, references, and values in readback_expectations; ParameterBinder.redact_secrets scrubs secret values from read-back and healer failure reasons.
  • P2s: SignedReceipt records llm_calls=1 on cold runs and len(healed_indices) on warm/healed runs; load_compiled_tools enforces symlink containment via is_relative_to(resolved_root); _run_readback_sync/_async convert read-back exceptions into UNCONFIRMED_WRITE with redacted reasons; .github/workflows/packages.yml count updated 176 -> 181 (+5 regression tests).

No blocking issues remain at 0a67b0c8db85c256b6c1abe9a8b4cb7c9fc24715.

@abrichr

abrichr commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Grok
Reviewed-Head: 0a67b0c

This is a cross-vendor review. Both earlier reviews on this PR are from the author's own vendor. The binder, empty-recording, healer and secret-redaction fixes from the previous round hold. Two problems remain, and I reproduced both at this head.

P1: the default fresh_reload read-back signs VERIFIED for a write that never persisted

_default_fresh_reload_readback_sync and _default_fresh_reload_readback_async reload the page and pass if each expected value is a substring of page.content() anywhere in the HTML. That check does not show the write landed:

  • A <select> value is always in the HTML as an <option>, so every select step "verifies".
  • A short value like 1 or Yes appears on almost any page.
  • Nothing compares the page with a snapshot taken before the write.

Probe (mock page; the save click is a no-op, so nothing persists; the reloaded form renders <option>Approved</option> and "Showing 1 of 12"):

P1 cold: cold VERIFIED cached: True receipt_valid: True | reason: Fresh reload confirmed expected values.
P1 warm: warm VERIFIED

So the cold run caches the plan and issues a valid Ed25519 receipt. After that, every warm run reports VERIFIED with zero agent calls. This is a false VERIFIED with a signature, which is the outcome the package exists to prevent.

Simplest fix: don't sign VERIFIED from the substring default. Two options:

  • (a) Require readback_fn to issue VERIFIED. Without it, return UNCONFIRMED_WRITE and don't cache.
  • (b) Keep the default, but make it field-scoped: read each expected selector's value after reload. Also require each expected value to be absent before the write. Fail closed when a value was already present.

Add a regression test for a dropped write on a page that already shows the value (a select option, or a short number).

P2: mcpify serve --from-compiled advertises tools that can never succeed

to_workflow_tool_spec() emits jit.goto / jit.click / jit.fill / jit.select / jit.press ops. The CLI serve path uses default_deterministic_runner, which runs only json_write / sqlite_insert. The default oracle also has no jit_fresh_reload contract. As a result, every tools/call halts:

P2 serve default: isError=True HALT | Runner left unexecuted ops ['jit.goto', 'jit.select', 'jit.fill', 'jit.click']; refusing to verify a partially executed workflow

It fails closed, so this is safe, but the feature doesn't work. The template syntaxes also differ. Compiled plans use {{name}}, while mcpify._render_value substitutes {name}, so {{status}} renders as {Approved}. test_mcpify_from_compiled_exposes_compiled_plan_as_callable_mcp_tool passes only because it injects a stub runner and an oracle that always returns VERIFIED. The CLI never gets those.

Simplest fix: either ship a page-backed runner and a real jit_* read-back oracle for serve --from-compiled, or drop --from-compiled from serve/config in this PR and keep load_compiled_tools as a library helper. In both cases, the test should cover the real CLI path, not stubs.

Evidence at this head (Linux, Python 3.12, fresh venv with editable types, flow and verify)

  • packages/verify/tests/test_jit.py: 13 passed.
  • packages/verify/tests (full suite): 170 passed, 9 skipped. The skips are the database-service quickstart controls.
  • The probe script is a standalone mock-page reproduction of the two results above, using only the public jit_wrap, load_compiled_tools and McpifyServer API.
  • Generality: the JIT core is app-agnostic (selector chains plus parameter templating), so it passes the gate. P1 is general too, since any form with a select or a short value hits it.

CI and limits

  • Failing on this head: seal-view (receiptRecord.test.mjs, evidence_scope vectors) and desktop test / Real Chrome profile (macos-latest). Neither touches packages/verify. seal-view also failed on main's push run for 559e1d3. The Real Chrome failure is what fix(desktop): open() lands on the requested URL; skip real-Chrome test without Chrome (fix-forward #2358) #2636 addresses. packages-gate, ci and run-ci are red only because of those two. The branch will need main merged in or a rerun after those fixes land. Its author should do that; this review does not.
  • Not run: macOS, Windows, and real Playwright or Chrome. Every probe used mock pages.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant