Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions CAPABILITIES.md

Large diffs are not rendered by default.

6 changes: 4 additions & 2 deletions llms-full.txt

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions openadapt/cli_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@
"variants": "compile --variants",
"verify-run": "verify effect",
"visualize": "inspect visualize",
"wrap-dispatch": "run --dispatch",
}


Expand Down
39 changes: 39 additions & 0 deletions packages/flow/benchmark/wrap_fallback/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Opt-in fallback on drift (MockMed)

What happens when a wrapped task's compiled program meets a changed app and
the task has opted in to `FallbackPolicy` ([WRAP_FALLBACK.md](../../docs/WRAP_FALLBACK.md)).

```bash
cd packages/flow
python benchmark/wrap_fallback/measure.py --out benchmark/wrap_fallback/results.json
```

For each MockMed drift mode, a scripted agent's run 1 is compiled and
admitted on the unchanged app (a registered key admits it after two
canaries). Then the app drifts, and the task runs once through the policy.
The fallback agent is scripted: it knows the drifted labels, and it makes no
model calls. A scripted gate stands in for the person and approves every
save that reaches it; a second trial per mode has it refuse. After each
trial the script reads MockMed's own store: `correct` is exactly one record
for the task's patient with the typed note, `none` is nothing saved, and
`wrong` is anything else.

| Mode | What changed | Program | Gate approves | Gate refuses |
| --- | --- | --- | --- | --- |
| redesign | The save is renamed, given a new id and moved; a decoy "Submit feedback" is added | HALTED | agent_fallback: VERIFIED, saved correct, 1 approval | agent_fallback: GATE_REFUSED, saved none, 1 approval |
| relink | The control that opens the form is renamed and moved | HALTED | agent_fallback: VERIFIED, saved correct, 1 approval | agent_fallback: GATE_REFUSED, saved none, 1 approval |
| rename | Labels renamed (`Submit Encounter`, `View`) | VERIFIED | not reached (program verified) | not reached (program verified) |

Summary: 3 drift modes, 6 trials. The program halted before the save on 2 modes and verified on 1 (the compiled program found the renamed labels). Fallbacks: 4, of which 2 verified (every approved one). Wrong saves: 0. Saves after a refusal: 0. Approvals asked for: 4. Model calls: 0.

## Limits

- Synthetic app, scripted agent, scripted gate, three drift modes. It shows
the policy's routing and safety on real browser runs; it does not measure
how often a model-driven agent finishes a drifted task.
- The compiled program runs in process on a thread, not over MCP, until the
MCP worker-thread fix in #2406 lands.
- `repair_opened` is false when the halted step is not a one-step target
replacement, so `SkillCache.open_repair` offers no candidate.

Results: [results.json](results.json).
167 changes: 167 additions & 0 deletions packages/flow/benchmark/wrap_fallback/measure.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
"""Measure the opt-in fallback on MockMed drifts, headless, synthetic data.

python benchmark/wrap_fallback/measure.py --out benchmark/wrap_fallback/results.json

For each drift mode: a scripted agent's run 1 is compiled and admitted on the
undrifted app, MockMed drifts, and the task runs once through
``FallbackPolicy`` with a scripted fallback agent that knows the drifted
labels and a gate that approves every save that reaches it (it stands in for
the person). One more trial per mode has the gate refuse. After every trial
the script reads MockMed's own store and classifies the outcome: ``correct``
(exactly one record, for the task's patient, with the typed note), ``none``
(nothing saved) or ``wrong`` (anything else).

The compiled program runs in process on a thread (the MCP worker-thread fix
is #2406). No model is called.
"""

from __future__ import annotations

import argparse
import json
import platform
import sys
import tempfile
import time
from pathlib import Path
from typing import Any

HERE = Path(__file__).resolve().parent
FLOW = HERE.parents[1]
sys.path.insert(0, str(FLOW))

from tests.e2e.test_wrap_fallback_e2e import ( # noqa: E402
NOTE,
PROMPT,
DriftableMockMed,
Gate,
admitted,
saved,
steps,
)

#: Drift modes, and the steps the scripted fallback agent takes on each.
MODES: dict[str, list] = {
"rename": steps(save="Submit Encounter", new="New Encounter"),
"redesign": steps(save="Submit to chart"),
"relink": steps(new="Start visit"),
}


class Env:
"""The two monkeypatch calls the shared helpers make, outside pytest."""

def __init__(self) -> None:
self.undo: list = []

def setenv(self, name: str, value: str) -> None:
import os

self.undo.append(("env", name, os.environ.get(name)))
os.environ[name] = value

def setattr(self, target: Any, name: str, value: Any) -> None:
self.undo.append(("attr", target, name, getattr(target, name)))
setattr(target, name, value)

def close(self) -> None:
import os

for item in reversed(self.undo):
if item[0] == "env":
if item[2] is None:
os.environ.pop(item[1], None)
else:
os.environ[item[1]] = item[2]
else:
setattr(item[1], item[2], item[3])


def classify(rows: list) -> str:
if not rows:
return "none"
return "correct" if rows == [("p1", "Triage", NOTE)] else "wrong"


def trial(mode: str, approve: bool) -> dict[str, Any]:
from openadapt_flow.agent.repair import RepairAccessPolicy, RepairDesk
from openadapt_flow.compile_agent import ScriptedAgent
from openadapt_flow.wrap.fallback import FallbackPolicy

env = Env()
with tempfile.TemporaryDirectory(prefix="wrap-fallback-") as raw:
tmp = Path(raw)
app = DriftableMockMed(tmp / "app")
try:
cache = admitted(tmp, app, env)
app.drift(mode)
gate = Gate(approve=approve)
policy = FallbackPolicy(
cache,
max_cost_usd=0.5,
gate=gate,
repair_desk=RepairDesk(tmp / "repairs", RepairAccessPolicy(None)),
)
started = time.monotonic()
run = policy.run(PROMPT, {"note": NOTE}, ScriptedAgent(steps=MODES[mode]))
seconds = round(time.monotonic() - started, 2)
rows = saved(app)
finally:
app.stop()
env.close()
last = policy.last or {}
program = run.replay if run.path == "skill" else run.replay.get("program")
return {
"mode": mode,
"gate": "approve" if approve else "refuse",
"program_status": program.get("status") if isinstance(program, dict) else None,
"path": run.path,
"status": run.status,
"verified": run.verified,
"fallback_reason": last.get("reason"),
"approvals_needed": len(gate.requests),
"model_calls": run.model_calls,
"seconds": seconds,
"saved": classify(rows),
"repair_opened": bool((last.get("repair") or {}).get("opened")),
}


def main() -> int:
parser = argparse.ArgumentParser(allow_abbrev=False)
parser.add_argument("--out", required=True)
parser.add_argument("--modes", nargs="*", default=sorted(MODES))
args = parser.parse_args()
trials = [trial(m, approve) for m in args.modes for approve in (True, False)]
fell_back = [t for t in trials if t["path"] == "agent_fallback"]
summary = {
"drifts": len(args.modes),
"trials": len(trials),
"program_verified": sum(t["path"] == "skill" and t["verified"] for t in trials),
"fallbacks": len(fell_back),
"fallback_verified": sum(t["verified"] for t in fell_back),
"wrong_saves": sum(t["saved"] == "wrong" for t in trials),
"saves_after_refusal": sum(
t["gate"] == "refuse" and t["saved"] != "none" and t["path"] != "skill"
for t in trials
),
"approvals_needed": sum(t["approvals_needed"] for t in trials),
"model_calls": sum(t["model_calls"] or 0 for t in trials),
}
result = {
"schema": "openadapt.wrap-fallback-benchmark/v1",
"app": "MockMed (synthetic), headless Chromium",
"agent": "scripted (no model)",
"gate": "scripted: approves or refuses every save that reaches it",
"measured_at": time.strftime("%Y-%m-%d"),
"python": platform.python_version(),
"summary": summary,
"trials": trials,
}
Path(args.out).write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
print(json.dumps(summary, indent=2))
return 0 if summary["wrong_saves"] == 0 else 1


if __name__ == "__main__":
raise SystemExit(main())
105 changes: 105 additions & 0 deletions packages/flow/benchmark/wrap_fallback/results.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
{
"schema": "openadapt.wrap-fallback-benchmark/v1",
"app": "MockMed (synthetic), headless Chromium",
"agent": "scripted (no model)",
"gate": "scripted: approves or refuses every save that reaches it",
"measured_at": "2026-11-21",
"python": "3.12.13",
"summary": {
"drifts": 3,
"trials": 6,
"program_verified": 2,
"fallbacks": 4,
"fallback_verified": 2,
"wrong_saves": 0,
"saves_after_refusal": 0,
"approvals_needed": 4,
"model_calls": 0
},
"trials": [
{
"mode": "redesign",
"gate": "approve",
"program_status": "HALTED",
"path": "agent_fallback",
"status": "VERIFIED",
"verified": true,
"fallback_reason": null,
"approvals_needed": 1,
"model_calls": 0,
"seconds": 24.2,
"saved": "correct",
"repair_opened": true
},
{
"mode": "redesign",
"gate": "refuse",
"program_status": "HALTED",
"path": "agent_fallback",
"status": "GATE_REFUSED",
"verified": false,
"fallback_reason": null,
"approvals_needed": 1,
"model_calls": 0,
"seconds": 17.08,
"saved": "none",
"repair_opened": false
},
{
"mode": "relink",
"gate": "approve",
"program_status": "HALTED",
"path": "agent_fallback",
"status": "VERIFIED",
"verified": true,
"fallback_reason": null,
"approvals_needed": 1,
"model_calls": 0,
"seconds": 17.3,
"saved": "correct",
"repair_opened": true
},
{
"mode": "relink",
"gate": "refuse",
"program_status": "HALTED",
"path": "agent_fallback",
"status": "GATE_REFUSED",
"verified": false,
"fallback_reason": null,
"approvals_needed": 1,
"model_calls": 0,
"seconds": 19.21,
"saved": "none",
"repair_opened": false
},
{
"mode": "rename",
"gate": "approve",
"program_status": "VERIFIED",
"path": "skill",
"status": "VERIFIED",
"verified": true,
"fallback_reason": null,
"approvals_needed": 0,
"model_calls": 0,
"seconds": 6.08,
"saved": "correct",
"repair_opened": false
},
{
"mode": "rename",
"gate": "refuse",
"program_status": "VERIFIED",
"path": "skill",
"status": "VERIFIED",
"verified": true,
"fallback_reason": null,
"approvals_needed": 0,
"model_calls": 0,
"seconds": 6.1,
"saved": "correct",
"repair_opened": false
}
]
}
12 changes: 9 additions & 3 deletions packages/flow/docs/AGENT_FRAMEWORKS.md
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,13 @@ What each skill run has:
record check fails, the result is `RECORD_CHECK_FAILED` with the check's
reasons, for a person to look at the record.

A skill that fails a run is evicted: it moves to `<cache_dir>/evicted/`, and
the next run of the task goes to the agent and compiles afresh.
`cache.evict(prompt, params)` does the same by hand. Skills live in
A skill that fails a run is held, not rerun by the agent: the next run of the
task returns `CACHE_HALTED` with the stop's reason, makes no model calls, and
keeps the halt as evidence until a person reconciles, repairs or releases it.
`cache.evict(prompt, params)` sets the skill aside by hand (it moves to
`<cache_dir>/evicted/`), and the next run goes to the agent and compiles
afresh. To send a proved pre-effect drift to the agent behind a pre-commit
gate instead, opt in per task with `FallbackPolicy` or
`openadapt-flow wrap-dispatch --fallback agent`
([WRAP_FALLBACK.md](WRAP_FALLBACK.md)). Skills live in
`~/.openadapt/skills` unless you pass `cache_dir=`.
1 change: 1 addition & 0 deletions packages/flow/docs/BACKEND_PARITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,7 @@ and `--log-url`, the transparency log) are not app URLs.
| `openadapt-flow validate-hosted` | `--target-url` | The surface comes from the signed run report. A non-web report refuses a target URL ("Target URL is web-only and must be omitted"). |
| `openadapt-agent authoring connect` | `--url` | `--url` opens a fresh browser. Without it the command pins the local app window (one macOS or Linux window). Windows, RDP and Citrix are coach-only on the mailbox: the person drives and Capture records (`COACH_ONLY_BACKENDS` in `agent/mailbox.py`). |
| `openadapt-agent seal keys pin` | `--url` | The seal key server's address, not an app. |
| `openadapt-flow wrap-dispatch` | `--pricing-source-url` | The primary source cited for the model prices the fallback's cost is computed with, not an app. The task's app comes from `--task`. |



Expand Down
Loading
Loading