diff --git a/packages/desktop/CHANGELOG.md b/packages/desktop/CHANGELOG.md index 9e46aff839..0625af3355 100644 --- a/packages/desktop/CHANGELOG.md +++ b/packages/desktop/CHANGELOG.md @@ -1,6 +1,17 @@ # CHANGELOG +## v0.31.2 (2026-11-22) + +### Bug Fixes + +- **desktop**: omit initial UI policy argument and forward inspected policy on certification +- **desktop**: distinguish omitted policy from explicit selection in dispatcher and qualification +- **types,desktop**: align certification policy readback, strict bool catalog slots, and canonical v1 outcome bytes +- **types,desktop**: preserve v1 wire compat, tighten managed catalog schema, and support bundled Flow policy fallback + + + ## v0.31.1 (2026-11-22) ### Bug Fixes diff --git a/packages/desktop/openadapt_desktop/__init__.py b/packages/desktop/openadapt_desktop/__init__.py index b084dd55e8..384f2ec168 100644 --- a/packages/desktop/openadapt_desktop/__init__.py +++ b/packages/desktop/openadapt_desktop/__init__.py @@ -21,4 +21,4 @@ +-- backends/ Storage backend plugins """ -__version__ = "0.31.1" +__version__ = "0.31.2" diff --git a/packages/desktop/openadapt_desktop/approval_mode.py b/packages/desktop/openadapt_desktop/approval_mode.py index 007d17bc93..e0e4debe34 100644 --- a/packages/desktop/openadapt_desktop/approval_mode.py +++ b/packages/desktop/openadapt_desktop/approval_mode.py @@ -1,27 +1,28 @@ """Only ask a person about problems: the Desktop side of the switch. -The switch lets a clinic stop approving routine items one by one. With it on, -an item saves without a person only when every check before and after the -save passes, and the record read back from the records system shows exactly -the values it was given. Everything else goes to a person in Needs you. +The switch lets an organization stop approving routine items one by one. With +it on, an item saves without a person only when every check before and after +the save passes, and the record read back from the records system shows +exactly the values it was given. Everything else goes to a person in Needs +you. Who decides what: -* A clinic owner or admin turns the switch on in OpenAdapt Cloud, and the - clinic's privacy contact confirms. Desktop never turns it on. No IPC command - writes a switch record; :func:`accept_switch` exists for the Cloud status - client and for tests. +* An organization owner or admin turns the switch on in OpenAdapt Cloud, and + the organization's privacy contact confirms. Desktop never turns it on. No + IPC command writes a switch record; :func:`accept_switch` exists for the + Cloud status client and for tests. * Anyone at this computer can turn it off, offline too. The switch-off goes into Flow's hash-chained switch log, which Flow's pre-save gate reads before every save, so it applies before the next save and Cloud can't undo it. * Flow decides each item: the pre-save checks (P1 to P5), the post-run checks - (R1 and R2) and the switch-off rules. Desktop reads Flow's PHI-free - ``approval`` block from the run report and never upgrades it. An item counts - as saved without a person only when that block says so, both post-run checks - passed, and the item's transaction outcome is a consistent ``VERIFIED``. - Desktop also checks the block against its own records before it lets the - item close without a person (:func:`confirm_no_person`); a block it can't - confirm needs a person. + (R1 and R2) and the switch-off rules. Desktop reads Flow's + sensitive-data-free ``approval`` block from the run report and never + upgrades it. An item counts as saved without a person only when that block + says so, both post-run checks passed, and the item's transaction outcome is + a consistent ``VERIFIED``. Desktop also checks the block against its own + records before it lets the item close without a person + (:func:`confirm_no_person`); a block it can't confirm needs a person. What is local, per task version (local bundle id):: @@ -30,8 +31,8 @@ /approval_mode//turned_off.json a switch-off made here Nothing here holds an input value, screen content or free text. The names of -the clinic staff who turned the switch on and confirmed it are kept on this -computer only, to show who is accountable. +the staff who turned the switch on and confirmed it are kept on this computer +only, to show who is accountable. The switch can't take effect on this computer yet. :func:`blockers` names every missing piece, and while any is missing Desktop shows the switch as not @@ -117,7 +118,7 @@ class SwitchEnvelope(BaseModel): ``record`` is Flow's switch record, validated with Flow's own model. The two people are the accountable admin and the privacy contact. Their names - are display names from the clinic's own Cloud organization. + are display names from the organization's own Cloud account. """ model_config = ConfigDict(extra="forbid", frozen=True) diff --git a/packages/desktop/openadapt_desktop/check_setup.py b/packages/desktop/openadapt_desktop/check_setup.py index 0244031ec6..3bc90b8090 100644 --- a/packages/desktop/openadapt_desktop/check_setup.py +++ b/packages/desktop/openadapt_desktop/check_setup.py @@ -158,7 +158,7 @@ def learn_record_check( } constants = dict(sorted(surface.constants.items())) # A fixed key the app sends with the save to stop a double save. Flow's - # clinical-write policy wants it on the record check; it is the app's + # record-write policy wants it on the record check; it is the app's # own value, so it is checked as sent, never invented. key_field = next((field for field in constants if _is_idempotency_field(field)), None) idempotency_literal = constants.pop(key_field) if key_field else None @@ -403,7 +403,7 @@ def answer_entry(answered_by: str, **extra: Any) -> dict[str, Any]: # --------------------------------------------------------------------------- _WRITE_CLASSES = frozenset({"state_changing", "consequential", "irreversible"}) -POLICY = "clinical-write" +POLICY = "record-write" def _plan(qualification: Mapping[str, Any]) -> dict[str, list[dict[str, Any]]]: @@ -471,7 +471,7 @@ def get_check_setup(dispatcher: Any, workflow_id: str) -> dict[str, Any]: inputs = dispatcher._task_inputs(workflow_id) secrets = frozenset(str(item["name"]) for item in inputs if item.get("secret")) recording = _recording_dir(dispatcher, workflow_id) - qualification = dispatcher.get_qualification(workflow_id=workflow_id, policy=POLICY) + qualification = dispatcher.get_qualification(workflow_id=workflow_id) plan = _plan(qualification) if qualification.get("ok") else {"writes": [], "unproven": []} if recording is None: @@ -611,10 +611,10 @@ def accept_record_check(dispatcher: Any, workflow_id: str, *, answered_by: str) "OpenAdapt has no record check to propose for this workflow. " "Answer the questions in Check it." ) - current = dispatcher.get_qualification(workflow_id=workflow_id, policy=POLICY) + current = dispatcher.get_qualification(workflow_id=workflow_id) if not current.get("project") or current.get("draft_environment"): _start_project(dispatcher, workflow_id) - current = dispatcher.get_qualification(workflow_id=workflow_id, policy=POLICY) + current = dispatcher.get_qualification(workflow_id=workflow_id) plan = _plan(current) quiet = setup.get("quiet_steps") if quiet: diff --git a/packages/desktop/openadapt_desktop/config.py b/packages/desktop/openadapt_desktop/config.py index b59ca7c768..7510219aa3 100644 --- a/packages/desktop/openadapt_desktop/config.py +++ b/packages/desktop/openadapt_desktop/config.py @@ -223,7 +223,7 @@ def settings_customise_sources( default="", description=( "The exact https origin your reverse proxy or VPN publishes for this " - "runner, e.g. https://openadapt.clinic.example. Required for " + "runner, e.g. https://openadapt.runner.example. Required for " "'customer_ingress'; must not be set for 'loopback'." ), ) diff --git a/packages/desktop/openadapt_desktop/dispatch.py b/packages/desktop/openadapt_desktop/dispatch.py index 50262cba8f..851e3adebf 100644 --- a/packages/desktop/openadapt_desktop/dispatch.py +++ b/packages/desktop/openadapt_desktop/dispatch.py @@ -2749,13 +2749,13 @@ def get_qualification(self, **params: Any) -> dict: """Inspect Flow's canonical graph, coverage, and certification contract.""" from openadapt_desktop.qualification import ( - DEFAULT_QUALIFICATION_POLICY, first_replay_review_is_draft, inspect_bundle, ) workflow_id = str(params.get("workflow_id") or "") - policy = str(params.get("policy") or DEFAULT_QUALIFICATION_POLICY) + raw_policy = params.get("policy") + policy = str(raw_policy).strip() or None if raw_policy is not None else None try: bundle = self._qualification_bundle_dir(workflow_id) result = inspect_bundle( @@ -3694,13 +3694,13 @@ def certify_qualification(self, **params: Any) -> dict: """Persist a pass/fail policy attempt into the resealed local bundle.""" from openadapt_desktop.qualification import ( - DEFAULT_QUALIFICATION_POLICY, certify_bundle, first_replay_review_is_draft, ) workflow_id = str(params.get("workflow_id") or "") - policy = str(params.get("policy") or DEFAULT_QUALIFICATION_POLICY) + raw_policy = params.get("policy") + policy = str(raw_policy).strip() or None if raw_policy is not None else None try: bundle = self._qualification_bundle_dir(workflow_id) bundle_key = self._qualification_bundle_key(workflow_id) diff --git a/packages/desktop/openadapt_desktop/portal/ingress.py b/packages/desktop/openadapt_desktop/portal/ingress.py index c3787042a0..2f0ed652b0 100644 --- a/packages/desktop/openadapt_desktop/portal/ingress.py +++ b/packages/desktop/openadapt_desktop/portal/ingress.py @@ -113,7 +113,7 @@ def _validated_public_origin(raw: str) -> str: ): raise IngressError( "The portal ingress origin must be a bare https origin such as " - "https://openadapt.clinic.example, with no path, query, or credentials." + "https://openadapt.runner.example, with no path, query, or credentials." ) if parsed.hostname.endswith("."): raise IngressError("The portal ingress origin has an invalid hostname") diff --git a/packages/desktop/openadapt_desktop/qualification.py b/packages/desktop/openadapt_desktop/qualification.py index feaaa4116a..ff7f6d8d23 100644 --- a/packages/desktop/openadapt_desktop/qualification.py +++ b/packages/desktop/openadapt_desktop/qualification.py @@ -29,7 +29,8 @@ QualificationEffectKind = Literal["record_written", "field_equals"] QualificationIdentityEnforcement = Literal["canonical_ladder", "signal_quorum"] QualificationTargetKind = Literal["web", "windows", "macos", "linux", "rdp", "citrix"] -DEFAULT_QUALIFICATION_POLICY = "clinical-write" +DEFAULT_QUALIFICATION_POLICY = "record-write" +LEGACY_FALLBACK_QUALIFICATION_POLICY = "clinical-write" ENVIRONMENT_IDENTIFIER_DERIVATION = "sha256(trimmed UTF-8 operator identifier)" FIRST_REPLAY_DRAFT_APPLICATION_VERSION = ( "openadapt-desktop-first-replay-draft/v1" @@ -157,10 +158,60 @@ def _load(bundle_dir: Path, *, key: str | None = None): raise QualificationError(f"Cannot open the sealed workflow bundle: {exc}") from exc -def _policy(source: str): +def _recorded_policy_name(workflow: Any) -> str | None: + """Return the policy name recorded on an already-certified bundle, if any.""" + + project = getattr(workflow, "qualification", None) + last_cert = getattr(project, "last_certification", None) if project is not None else None + recorded = getattr(last_cert, "policy_name", None) if last_cert is not None else None + if isinstance(recorded, str) and recorded.strip(): + return recorded.strip() + manifest = getattr(workflow, "manifest", None) + provenance = getattr(manifest, "provenance", None) if manifest is not None else None + prov_policy = getattr(provenance, "policy_name", None) if provenance is not None else None + if isinstance(prov_policy, str) and prov_policy.strip(): + return prov_policy.strip() + return None + + +def _policy(source: str | None, *, workflow: Any = None): + """Load an explicit policy or resolve the default for a bundle. + + When ``source`` is ``None`` (omitted), reuse the bundle's recorded policy + if present; otherwise load ``DEFAULT_QUALIFICATION_POLICY`` (falling back + to ``LEGACY_FALLBACK_QUALIFICATION_POLICY`` only on older bundled Flow + versions that do not ship ``record-write``). + + When ``source`` is explicitly provided, evaluate that exact selection + rather than overriding it with a previously recorded policy. + """ + + load_policy = _flow_api()["load_policy"] + if source is None: + if workflow is not None: + recorded = _recorded_policy_name(workflow) + if recorded: + try: + return load_policy(recorded) + except (FileNotFoundError, ValueError): + pass + try: + return load_policy(DEFAULT_QUALIFICATION_POLICY) + except (FileNotFoundError, ValueError) as exc: + try: + return load_policy(LEGACY_FALLBACK_QUALIFICATION_POLICY) + except (FileNotFoundError, ValueError): + raise QualificationError(str(exc)) from exc try: - return _flow_api()["load_policy"](source) + return load_policy(source) except (FileNotFoundError, ValueError) as exc: + # Older bundled Flow versions (e.g. 2.4.x) ship clinical-write and permissive + # without the domain-neutral record-write alias. Fall back only for that alias. + if source == DEFAULT_QUALIFICATION_POLICY: + try: + return load_policy(LEGACY_FALLBACK_QUALIFICATION_POLICY) + except (FileNotFoundError, ValueError): + pass raise QualificationError(str(exc)) from exc @@ -835,14 +886,14 @@ def inspect_bundle( bundle_dir: Path, *, workflow_id: str, - policy_source: str = DEFAULT_QUALIFICATION_POLICY, + policy_source: str | None = None, bundle_key: str | None = None, ) -> dict: """Return graph, canonical project/report, controls, and exact refusals.""" api = _flow_api() workflow = _load(bundle_dir, key=bundle_key) - policy = _policy(policy_source) + policy = _policy(policy_source, workflow=workflow) graph_payload = program_graph(bundle_dir, workflow) lint = api["lint_workflow"](workflow) runtime_policy = api["evaluate_policy"](workflow, policy) @@ -2235,7 +2286,7 @@ def certify_bundle( bundle_dir: Path, *, workflow_id: str, - policy_source: str = DEFAULT_QUALIFICATION_POLICY, + policy_source: str | None = None, bundle_key: str | None = None, ) -> dict: """Run Flow's canonical certification and persist the versioned report.""" @@ -2246,7 +2297,7 @@ def certify_bundle( raise QualificationError( "Initialize the qualification boundary before running certification." ) - policy = _policy(policy_source) + policy = _policy(policy_source, workflow=workflow) workflow_contract = api["workflow_contract_sha256"](workflow) capability_coverage = _capability_coverage( bundle_dir, diff --git a/packages/desktop/package-lock.json b/packages/desktop/package-lock.json index 5ade03b0a4..5757b07d00 100644 --- a/packages/desktop/package-lock.json +++ b/packages/desktop/package-lock.json @@ -1,12 +1,12 @@ { "name": "openadapt-desktop", - "version": "0.31.1", + "version": "0.31.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "openadapt-desktop", - "version": "0.31.1", + "version": "0.31.2", "dependencies": { "@tauri-apps/api": "^2", "@tauri-apps/plugin-notification": "^2", diff --git a/packages/desktop/package.json b/packages/desktop/package.json index 832475d09c..8a27ab3588 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -1,6 +1,6 @@ { "name": "openadapt-desktop", - "version": "0.31.1", + "version": "0.31.2", "description": "Installed companion for OpenAdapt authoring, teaching, and local pairing", "private": true, "type": "module", diff --git a/packages/desktop/pyproject.toml b/packages/desktop/pyproject.toml index d25e1f1b33..11112a3ecc 100644 --- a/packages/desktop/pyproject.toml +++ b/packages/desktop/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "openadapt-desktop" -version = "0.31.1" +version = "0.31.2" description = "The OpenAdapt desktop app and local engine: record a data-entry task, run it on a list, and check each saved record" readme = "README.md" requires-python = ">=3.11" diff --git a/packages/desktop/src-tauri/Cargo.lock b/packages/desktop/src-tauri/Cargo.lock index 1696ab47ab..10c73d20b7 100644 --- a/packages/desktop/src-tauri/Cargo.lock +++ b/packages/desktop/src-tauri/Cargo.lock @@ -2513,7 +2513,7 @@ dependencies = [ [[package]] name = "openadapt-desktop" -version = "0.31.1" +version = "0.31.2" dependencies = [ "hex", "reqwest", diff --git a/packages/desktop/src-tauri/Cargo.toml b/packages/desktop/src-tauri/Cargo.toml index 8e9fc5320f..1b438a4a2d 100644 --- a/packages/desktop/src-tauri/Cargo.toml +++ b/packages/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "openadapt-desktop" -version = "0.31.1" +version = "0.31.2" description = "Installed companion for OpenAdapt authoring, teaching, and local pairing" authors = ["OpenAdapt AI"] license = "MIT" diff --git a/packages/desktop/src-tauri/tauri.conf.json b/packages/desktop/src-tauri/tauri.conf.json index 9d3b1204a8..4b9a2f6837 100644 --- a/packages/desktop/src-tauri/tauri.conf.json +++ b/packages/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://raw.githubusercontent.com/nicoverbruggen/tauri-v2-schema/main/schema.json", "productName": "OpenAdapt Desktop", - "version": "0.31.1", + "version": "0.31.2", "identifier": "ai.openadapt.desktop", "build": { "frontendDist": "../dist", diff --git a/packages/desktop/src/lib/checkPlan.test.ts b/packages/desktop/src/lib/checkPlan.test.ts index 34981ed240..0a06939269 100644 --- a/packages/desktop/src/lib/checkPlan.test.ts +++ b/packages/desktop/src/lib/checkPlan.test.ts @@ -15,7 +15,7 @@ function subTaskSave({ withCallNode = true, withReportCount = true } = {}) { return { ok: true, workflow_id: "wf-1", - policy: "clinical-write", + policy: "record-write", qualification_schema: "openadapt.qualification-project/v1", migration_required: false, draft_environment: false, diff --git a/packages/desktop/src/lib/outcomes.ts b/packages/desktop/src/lib/outcomes.ts index b94eefbd4e..556e7cd011 100644 --- a/packages/desktop/src/lib/outcomes.ts +++ b/packages/desktop/src/lib/outcomes.ts @@ -239,13 +239,13 @@ export function plainResultForReport(report: { const INPUT_WORDS: Record = { id: "ID", - mrn: "MRN", dob: "date of birth", - npi: "NPI", url: "URL", + api: "API", + sku: "SKU", }; -// Whole names that EMR patient tables abbreviate or write in database word +// Whole names that database tables abbreviate or write in database word // order, so "fname" reads "first name" and "phone_home" reads "home phone". const INPUT_PHRASES: Record = { fname: "first name", @@ -256,7 +256,7 @@ const INPUT_PHRASES: Record = { "phone biz": "work phone", }; -/** "member_id" -> "member ID", "patientName" -> "patient name". */ +/** "member_id" -> "member ID", "accountName" -> "account name". */ export function humanizeInput(name: string): string { const words = name .replace(/([a-z0-9])([A-Z])/g, "$1 $2") diff --git a/packages/desktop/src/screens/CheckIt.test.tsx b/packages/desktop/src/screens/CheckIt.test.tsx index 795aef4f9e..703396b76a 100644 --- a/packages/desktop/src/screens/CheckIt.test.tsx +++ b/packages/desktop/src/screens/CheckIt.test.tsx @@ -28,7 +28,7 @@ function project({ return { ok: true, workflow_id: "wf-1", - policy: "clinical-write", + policy: "record-write", qualification_schema: "openadapt.qualification-project/v1", migration_required: false, draft_environment: draft, @@ -715,3 +715,41 @@ it("does not show an earlier no-input result for another workflow", async () => expect(screen.queryByText("Right-record identity passed.")).toBeNull(); expect(screen.queryByText(/Stopped at the declared save boundary before any input/)).toBeNull(); }); + +it("omits policy on initial load and carries the inspected policy on approval", async () => { + const legacyReady = { + ...project({ + cases: [ + { id: "practice-1", kind: "representative", status: "passed" }, + { id: "fault-identity-swap", kind: "wrong_identity", status: "passed" }, + ], + }), + policy: "clinical-write", + }; + engine(legacyReady); + vi.mocked(engineInvoke).mockImplementation(async (command) => { + if (command === CMD.GET_QUALIFICATION) return legacyReady; + if (command === CMD.CERTIFY_QUALIFICATION) { + return { ...legacyReady, certification_current: true }; + } + if (command === CMD.SEAL_QUALIFICATION_WORKFLOW) { + return { ok: true, workflow_id: "wf-1-v2" }; + } + throw new Error(`unexpected ${command}`); + }); + render( {}} onRun={() => {}} />); + + fireEvent.click(await screen.findByRole("button", { name: "Approve this workflow" })); + expect(await screen.findByText("Approved and locked")).toBeTruthy(); + + const inspectCall = vi + .mocked(engineInvoke) + .mock.calls.find(([command]) => command === CMD.GET_QUALIFICATION); + expect(inspectCall?.[1]).toEqual({ workflow_id: "wf-1" }); + expect(inspectCall?.[1]).not.toHaveProperty("policy"); + + const certifyCall = vi + .mocked(engineInvoke) + .mock.calls.find(([command]) => command === CMD.CERTIFY_QUALIFICATION); + expect(certifyCall?.[1]).toEqual({ workflow_id: "wf-1", policy: "clinical-write" }); +}); diff --git a/packages/desktop/src/screens/CheckIt.tsx b/packages/desktop/src/screens/CheckIt.tsx index 1f32be7a20..1b5f8f2784 100644 --- a/packages/desktop/src/screens/CheckIt.tsx +++ b/packages/desktop/src/screens/CheckIt.tsx @@ -44,7 +44,6 @@ import { ExecutionTargetForm, TARGETS } from "../ui/ExecutionTargetForm"; import { Button, Callout, Field } from "../ui/primitives"; import { Icon, PageHead, Status, TechnicalDetails } from "../ui/simple"; -const POLICY = "clinical-write"; const PRACTICE_CASE = "practice-1"; type Busy = @@ -341,7 +340,7 @@ function armedIdentityGroups ({ text, count })); } -/** "the note you give it", "patient ID p1", joined in plain words. */ +/** "the note you give it", "record ID p1", joined in plain words. */ function checkedThings(learned: LearnedRecordCheck): string[] { const things = (learned.values_checked ?? []).map( (name) => `the ${humanizeInput(name)} you give it`, @@ -498,7 +497,6 @@ export function CheckIt({ }), engineInvoke(CMD.GET_QUALIFICATION, { workflow_id: activeId.current, - policy: POLICY, }), engineTry(CMD.GET_CHECK_SETUP, { workflow_id: activeId.current }, null), ]); @@ -563,7 +561,7 @@ export function CheckIt({ async function call(cmd: string, params: Record): Promise> { return engineInvoke>(cmd, { workflow_id: activeId.current, - policy: POLICY, + ...(project?.policy ? { policy: project.policy } : {}), ...params, }); } diff --git a/packages/desktop/src/screens/NeedsYou.test.tsx b/packages/desktop/src/screens/NeedsYou.test.tsx index a64f31add0..0f65443ff6 100644 --- a/packages/desktop/src/screens/NeedsYou.test.tsx +++ b/packages/desktop/src/screens/NeedsYou.test.tsx @@ -304,5 +304,6 @@ it("shows no field diff when the record check recorded none", async () => { it("labels fields in plain words", () => { expect(fieldLabel("dob")).toBe("DOB"); expect(fieldLabel("first_name")).toBe("First name"); - expect(fieldLabel("patient_mrn")).toBe("Patient MRN"); + expect(fieldLabel("account_id")).toBe("Account ID"); + expect(fieldLabel("item_sku")).toBe("Item SKU"); }); diff --git a/packages/desktop/src/screens/NeedsYou.tsx b/packages/desktop/src/screens/NeedsYou.tsx index 39334b92e0..afc56530f8 100644 --- a/packages/desktop/src/screens/NeedsYou.tsx +++ b/packages/desktop/src/screens/NeedsYou.tsx @@ -41,7 +41,7 @@ interface Notice { text: string; } -const FIELD_ACRONYMS = new Set(["dob", "dos", "mrn", "ssn", "npi", "id", "icd", "cpt", "zip"]); +const FIELD_ACRONYMS = new Set(["id", "url", "api", "sku", "po", "dob", "ssn", "ein", "zip"]); // Short field names apps often use, in the words a person reads. const FIELD_NAMES: Record = { diff --git a/packages/desktop/src/screens/Qualification.tsx b/packages/desktop/src/screens/Qualification.tsx index d77dd6d43b..0fe17556a3 100644 --- a/packages/desktop/src/screens/Qualification.tsx +++ b/packages/desktop/src/screens/Qualification.tsx @@ -21,8 +21,6 @@ import { ProgramWorkbench, type SectionEdit } from "@openadapt/program-graph"; import { PROGRAM_WORKBENCH_NOTES, PROGRAM_WORKBENCH_SURFACE } from "../lib/programWorkbench"; import { QualificationLifecycle } from "./QualificationLifecycle"; -const POLICY = "clinical-write"; - type EditProgramSectionsResponse = | { ok: true; graph: QualificationProject["graph"] } | { ok: false; error: string }; @@ -264,7 +262,7 @@ export function Qualification({ try { const response = await engineInvoke( CMD.GET_QUALIFICATION, - { workflow_id: workflowId, policy: POLICY }, + { workflow_id: workflowId }, ); if (!response.ok) { setError(response.error); @@ -408,7 +406,7 @@ export function Qualification({ .map((value) => value.trim()) .filter(Boolean), minimum_effect_tier: minimumTier, - policy: POLICY, + ...(project?.policy ? { policy: project.policy } : {}), }, ); if (!response.ok) { @@ -461,7 +459,7 @@ export function Qualification({ step_id: stepId, risk, explanation: `Operator reviewed this action as ${risk.replaceAll("_", " ")}`, - policy: POLICY, + ...(project?.policy ? { policy: project.policy } : {}), }, ); if (!response.ok) { @@ -554,7 +552,7 @@ export function Qualification({ })) : [], quorum: identityEnforcement === "signal_quorum" ? identityQuorum : 0, - policy: POLICY, + ...(project?.policy ? { policy: project.policy } : {}), }, ); if (!response.ok) { @@ -581,7 +579,7 @@ export function Qualification({ step_id: selectedActionId, effect_index: selectedEffect.index, verification_tier: verificationTier, - policy: POLICY, + ...(project?.policy ? { policy: project.policy } : {}), }, ); if (!response.ok) { @@ -605,7 +603,7 @@ export function Qualification({ { workflow_id: workflowId, minimum_effect_tier: projectMinimumTier, - policy: POLICY, + ...(project?.policy ? { policy: project.policy } : {}), }, ); if (!response.ok) { @@ -646,7 +644,7 @@ export function Qualification({ effectKind === "record_written" ? countNewOnly : false, effect_index: placeholder?.index, verification_tier: bindingVerificationTier, - policy: POLICY, + ...(project?.policy ? { policy: project.policy } : {}), }, ); if (!response.ok) { @@ -679,7 +677,10 @@ export function Qualification({ try { const response = await engineInvoke( CMD.CERTIFY_QUALIFICATION, - { workflow_id: workflowId, policy: POLICY }, + { + workflow_id: workflowId, + ...(project?.policy ? { policy: project.policy } : {}), + }, ); if (!response.ok) { setError(response.error); diff --git a/packages/desktop/src/screens/QualificationLifecycle.tsx b/packages/desktop/src/screens/QualificationLifecycle.tsx index 87f9db8df4..54a120ee09 100644 --- a/packages/desktop/src/screens/QualificationLifecycle.tsx +++ b/packages/desktop/src/screens/QualificationLifecycle.tsx @@ -13,8 +13,6 @@ import type { import { ExecutionTargetForm } from "../ui/ExecutionTargetForm"; import { Button, Callout, Card, CardHead, Field, Pill } from "../ui/primitives"; -const POLICY = "clinical-write"; - const GUIDED_FAULT_CASES: { id: string; kind: QualificationCaseKind; @@ -216,7 +214,7 @@ export function QualificationLifecycle({ try { const response = await engineInvoke(command, { workflow_id: workflowId, - policy: POLICY, + ...(project.policy ? { policy: project.policy } : {}), ...params, }); if (!response.ok) { @@ -301,7 +299,7 @@ export function QualificationLifecycle({ CMD.IMPORT_QUALIFICATION_RESULTS, { workflow_id: workflowId, - policy: POLICY, + ...(project.policy ? { policy: project.policy } : {}), signed_results_json: await file.text(), }, ); diff --git a/packages/desktop/src/screens/Sample.tsx b/packages/desktop/src/screens/Sample.tsx index 8a7ecf85a1..45fedae58f 100644 --- a/packages/desktop/src/screens/Sample.tsx +++ b/packages/desktop/src/screens/Sample.tsx @@ -1,7 +1,7 @@ // See it work on a sample app, before granting any permission. // -// The engine runs Flow's built-in tutorial: a synthetic clinic app with -// made-up patients, served and driven in a hidden browser on this computer. +// The engine runs Flow's built-in tutorial: a synthetic sample app with +// made-up records, served and driven in a hidden browser on this computer. // It runs the sample task twice. The first time, the app saves normally. The // second time, the app shows "saved" but drops the entry, so the reader sees // what OpenAdapt does when the screen and the record disagree. @@ -20,7 +20,7 @@ import { } from "../ui/simple"; const PROVENANCE = - "Run on this computer with OpenAdapt's built-in sample app. All patients and data are made up."; + "Run on this computer with OpenAdapt's built-in sample app. All records and data are made up."; function SampleRunCard({ run }: { run: SampleRun }) { const copy = resultCopy({ key: run.result, nothingWritten: run.nothing_written }); @@ -40,7 +40,7 @@ function SampleRunCard({ run }: { run: SampleRun }) {

{normal && run.result === "done_checked" - ? `OpenAdapt checked it had the right patient, typed the note, and saved it. Then it read the record back: ${run.record_checks_confirmed} of ${run.record_checks_confirmed + run.record_checks_failed} checks matched.` + ? `OpenAdapt checked it had the right record, typed the note, and saved it. Then it read the record back: ${run.record_checks_confirmed} of ${run.record_checks_confirmed + run.record_checks_failed} checks matched.` : !normal && run.result === "check_record" ? "The app showed “Encounter saved”, but when OpenAdapt read the record back, the note wasn't there. OpenAdapt stopped and flagged the record for a person to check. It doesn't try again on its own." : copy.sentence} @@ -137,7 +137,7 @@ export function Sample({

{state !== "done" && ( diff --git a/packages/desktop/src/screens/Welcome.test.tsx b/packages/desktop/src/screens/Welcome.test.tsx index 5768bca85b..f3dc268df3 100644 --- a/packages/desktop/src/screens/Welcome.test.tsx +++ b/packages/desktop/src/screens/Welcome.test.tsx @@ -23,8 +23,8 @@ test("says what OpenAdapt does for any app, for a person or an AI agent", () => ); }); -test("names regulated settings only as examples", () => { +test("stays domain-neutral on the welcome screen", () => { const text = welcomeText(); - expect(text).toContain("such as medical records and insurance"); - expect(text).not.toMatch(/EMR|payer|Citrix|patient|member|clinic/i); + expect(text).toContain("high-stakes and regulated systems of record"); + expect(text).not.toMatch(/EMR|payer|Citrix|patient|member|clinic|medical|insurance/i); }); diff --git a/packages/desktop/src/screens/Welcome.tsx b/packages/desktop/src/screens/Welcome.tsx index 8cc139203d..626ece20dd 100644 --- a/packages/desktop/src/screens/Welcome.tsx +++ b/packages/desktop/src/screens/Welcome.tsx @@ -35,9 +35,8 @@ export function Welcome({ A person or an AI agent does a workflow once, in any app. OpenAdapt turns it into a program that repeats the workflow with new inputs and checks each save by reading it back. When something doesn't - match, it stops and asks instead of guessing. It suits highly - regulated work, such as medical records and insurance, where a wrong - entry matters. + match, it stops and asks instead of guessing. It suits high-stakes + and regulated systems of record where a wrong entry matters.

diff --git a/packages/desktop/src/ui/ApprovalSwitch.tsx b/packages/desktop/src/ui/ApprovalSwitch.tsx index c6faa1730d..5df905dc7b 100644 --- a/packages/desktop/src/ui/ApprovalSwitch.tsx +++ b/packages/desktop/src/ui/ApprovalSwitch.tsx @@ -1,7 +1,7 @@ // The switch "Only ask a person about problems" on a task card. // // Read-only, plus Turn off. Turning it on happens in OpenAdapt Cloud, by an -// owner or admin, and the clinic's privacy contact confirms. The panel shows +// owner or admin, and the organization's privacy contact confirms. The panel shows // the evidence behind the state: who turned it on and confirmed, what the // switch is bound to, the local switch log, and the requirements. import { useId, useState } from "react"; diff --git a/packages/desktop/src/ui/BusinessDecisionAuthoring.test.tsx b/packages/desktop/src/ui/BusinessDecisionAuthoring.test.tsx index 00a1e5afce..7b2b591b26 100644 --- a/packages/desktop/src/ui/BusinessDecisionAuthoring.test.tsx +++ b/packages/desktop/src/ui/BusinessDecisionAuthoring.test.tsx @@ -15,7 +15,7 @@ function project(): QualificationProject { return { ok: true, workflow_id: "wf-1", - policy: "clinical-write", + policy: "record-write", project: { revision: 3 }, controls: { parameters: [], diff --git a/packages/desktop/tests/test_engine/test_qualification.py b/packages/desktop/tests/test_engine/test_qualification.py index b46684fc10..2bb3c75b81 100644 --- a/packages/desktop/tests/test_engine/test_qualification.py +++ b/packages/desktop/tests/test_engine/test_qualification.py @@ -1744,3 +1744,155 @@ def test_review_graph_carries_the_named_sections_and_edits_them(tmp_path: Path) "other": graph["sections"][1]["section"], }, ) + + +def test_default_policy_falls_back_when_bundled_flow_lacks_record_write( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from openadapt_desktop import qualification as desktop_qual + + real_api = desktop_qual._flow_api() + real_load = real_api["load_policy"] + + def _legacy_load_policy(name: str): + if name == "record-write": + raise FileNotFoundError("Policy 'record-write' not found") + return real_load(name) + + monkeypatch.setattr( + desktop_qual, + "_flow_api", + lambda: {**real_api, "load_policy": _legacy_load_policy}, + ) + + fallback = desktop_qual._policy(desktop_qual.DEFAULT_QUALIFICATION_POLICY) + assert fallback.name == "clinical-write" + + # Explicit unknown policies still fail closed instead of falling back. + with pytest.raises(QualificationError): + desktop_qual._policy("nonexistent-policy") + + +def test_inspect_bundle_preserves_recorded_policy_for_existing_certified_bundle( + tmp_path: Path, +) -> None: + bundle = _bundle( + tmp_path / "bundle", + Step(id="settle", intent="Wait", action=ActionKind.WAIT), + ) + workflow = Workflow.load(bundle) + workflow.stamp_certification("clinical-write", True) + workflow.save(bundle) + + # Opening a bundle with recorded clinical-write provenance under the new + # domain-neutral default preserves its recorded policy identity. + reopened_legacy = inspect_bundle(bundle, workflow_id="wf-1") + assert reopened_legacy["policy"] == "clinical-write" + + initialize_qualification( + bundle, + workflow_id="wf-1", + target_kind="web", + application="Sample app", + application_version="1.0", + environment_label="local-test", + ) + certified = certify_bundle( + bundle, + workflow_id="wf-1", + policy_source="clinical-write", + ) + assert certified["policy"] == "clinical-write" + assert certified["project"]["last_certification"]["policy_name"] == "clinical-write" + + # Re-opening under the new domain-neutral default keeps the recorded policy + # identity from last_certification. + reopened = inspect_bundle(bundle, workflow_id="wf-1") + assert reopened["policy"] == "clinical-write" + + # Re-running certification with the UI's default policy ("record-write") also + # keeps the recorded policy identity instead of switching policies mid-flight. + recertified = certify_bundle(bundle, workflow_id="wf-1") + assert recertified["policy"] == "clinical-write" + assert recertified["project"]["last_certification"]["policy_name"] == "clinical-write" + + +def test_certify_bundle_with_custom_policy_yaml_path_succeeds_on_readback( + tmp_path: Path, +) -> None: + custom_policy = tmp_path / "custom-policy.yaml" + custom_policy.write_text( + "name: custom-campaign-policy\n" + "description: Custom YAML policy whose internal name is not a built-in.\n" + "prohibit_unarmed_clicks: false\n" + "prohibit_vacuous_postconditions: false\n" + "max_unverified_steps: 99\n", + encoding="utf-8", + ) + bundle = _bundle( + tmp_path / "bundle", + Step(id="settle", intent="Wait", action=ActionKind.WAIT), + ) + initialize_qualification( + bundle, + workflow_id="wf-1", + target_kind="web", + application="Sample app", + application_version="1.0", + environment_label="local-test", + ) + certified = certify_bundle( + bundle, + workflow_id="wf-1", + policy_source=str(custom_policy), + ) + assert certified["ok"] is True + assert certified["policy"] == "custom-campaign-policy" + assert certified["project"]["last_certification"]["policy_name"] == "custom-campaign-policy" + + +def test_dispatcher_distinguishes_omitted_policy_from_explicit_stricter_policy( + tmp_path: Path, +) -> None: + config = EngineConfig(data_dir=tmp_path / ".openadapt", log_level="WARNING") + bundle = _bundle( + config.data_dir / "bundles" / "wf-1", + Step(id="settle", intent="Wait", action=ActionKind.WAIT), + ) + initialize_qualification( + bundle, + workflow_id="wf-1", + target_kind="web", + application="Sample app", + application_version="1.0", + environment_label="local-test", + ) + # First certify under permissive so the bundle records permissive. + permissive_result = certify_bundle( + bundle, + workflow_id="wf-1", + policy_source="permissive", + ) + assert permissive_result["policy"] == "permissive" + assert permissive_result["project"]["last_certification"]["policy_name"] == "permissive" + + db = IndexDB(tmp_path / "index.db") + db.initialize() + db.insert_bundle("wf-1", str(bundle)) + dispatcher = EngineDispatcher(config, services=EngineServices(config, db=db)) + try: + # Omitted policy reuses the recorded permissive policy. + reused = dispatcher.certify_qualification(workflow_id="wf-1") + assert reused["policy"] == "permissive" + assert reused["project"]["last_certification"]["policy_name"] == "permissive" + + # Explicit record-write overrides permissive instead of reusing it. + upgraded = dispatcher.certify_qualification( + workflow_id="wf-1", + policy="record-write", + ) + assert upgraded["policy"] in {"record-write", "clinical-write"} + assert upgraded["policy"] != "permissive" + assert upgraded["project"]["last_certification"]["policy_name"] == upgraded["policy"] + finally: + db.close() diff --git a/packages/desktop/uv.lock b/packages/desktop/uv.lock index 77904b7a72..f5903fd209 100644 --- a/packages/desktop/uv.lock +++ b/packages/desktop/uv.lock @@ -1172,7 +1172,7 @@ wheels = [ [[package]] name = "openadapt-desktop" -version = "0.31.1" +version = "0.31.2" source = { editable = "." } dependencies = [ { name = "cryptography" }, diff --git a/packages/types/README.md b/packages/types/README.md index e360ce4c45..5ac00363a2 100644 --- a/packages/types/README.md +++ b/packages/types/README.md @@ -141,7 +141,7 @@ print(json.dumps(ComputerState.model_json_schema(), indent=2)) ``` The messages that OpenAdapt components exchange ship under -`openadapt_types/schemas/`: forty-four files, including `execute-v1-openapi.json`, +`openadapt_types/schemas/`: forty-eight files, including `execute-v1-openapi.json`, the OpenAPI document for OpenAdapt Execute, the API that starts runs and reports their results. Two files hold test vectors, and the rest are JSON Schema files. diff --git a/packages/types/docs/CONTRACTS.md b/packages/types/docs/CONTRACTS.md index a140b714c9..bade1674ef 100644 --- a/packages/types/docs/CONTRACTS.md +++ b/packages/types/docs/CONTRACTS.md @@ -20,7 +20,8 @@ A test checks that every file in that directory appears in this index. | `reward-contract-v1.json`, `reward-certificate-v1.json`, `reward-evidence-receipt-v1.json` | `RewardContractV1`, `RewardCertificateV1`, `RewardEvidenceReceiptV1` | Training against one verified terminal effect. The receipt is not an Execute Seal | [Reward contracts](#reward-contracts) | | `authentication-task-v1.json`, `authentication-receipt-v1.json`, `authentication-capture-policy-v1.json` | `AuthenticationTaskContractV1`, `AuthenticationReceiptV1`, `AuthenticationCapturePolicyV1` | A value-free login requirement bound to an existing attended task, its receipt, and the capture-exclusion policy | [Authentication tasks](#authentication-tasks) | | `authoring-observe-v1.json`, `authoring-command-v1.json`, `authoring-bind-v1.json` | `AuthoringObserveV1`, `AuthoringCommandV1`, `AuthoringBindV1` | The hosted authoring MCP wire: a PHI-safe observe tree, the mailbox command envelope, and bind status | [Authoring MCP wire](#authoring-mcp-wire) | -| `clinic-inbox-v1.json`, `clinic-outbox-v1.json`, `clinic-tool-result-v1.json`, `clinic-mcp-tools-v1.json` | `ClinicInboxV1`, `ClinicOutboxV1`, `ClinicToolResultV1`, `ClinicMcpToolCatalogV1` | The clinic job handoff: an inbox job, an actuation intent, an MCP tool result, and the tool catalog | [Clinic job inbox and MCP tools](#clinic-job-inbox-and-mcp-tools) | +| `managed-inbox-v1.json`, `managed-outbox-v1.json`, `managed-tool-result-v1.json`, `managed-mcp-tools-v1.json` | `ManagedInboxV1`, `ManagedOutboxV1`, `ManagedToolResultV1`, `ManagedMcpToolCatalogV1` | The domain-neutral managed job handoff: an inbox job, an actuation intent, an MCP tool result, and the tool catalog | [Managed job inbox and MCP tools](#clinic-job-inbox-and-mcp-tools) | +| `clinic-inbox-v1.json`, `clinic-outbox-v1.json`, `clinic-tool-result-v1.json`, `clinic-mcp-tools-v1.json` | `ClinicInboxV1`, `ClinicOutboxV1`, `ClinicToolResultV1`, `ClinicMcpToolCatalogV1` | Legacy/compat wire schemas for `openadapt.clinic-*/v1` payloads; prefer `managed-*-v1.json` | [Clinic job inbox and MCP tools](#clinic-job-inbox-and-mcp-tools) | | `approver-identity-v1.json`, `approver-policy-v1.json`, `approval-record-v1.json`, `autonomy-eligibility-v1.json` | `ApproverIdentityV1`, `ApproverPolicyV1`, `ApprovalRecordV1`, `AutonomyEligibilityV1` | Who approved a step (a person, a rule, an agent or a system), which approvers each step class allows, one approval decision for the audit trail and receipt, and the evidence a workflow needs before it runs on exceptions only | [Approvals and read-back](#approvals-and-read-back) | | `plain-outcome-v1.json`, `plain-progress-v1.json` | `PlainOutcomeV1`, `PlainProgressV1` | One run's result in plain words, or the state of a run that hasn't ended | [Plain results](#plain-results) | diff --git a/packages/types/docs/VOCABULARY.md b/packages/types/docs/VOCABULARY.md index c2efdda33b..a77a04d883 100644 --- a/packages/types/docs/VOCABULARY.md +++ b/packages/types/docs/VOCABULARY.md @@ -94,7 +94,7 @@ The one exception only adds caution: when `transaction_outcome` and |---|---|---| | 1 | `transaction_outcome`, `execute_terminal_outcome`, `execute_state` | Flow's `report.json` and hosted callbacks; an Execute status, receipt, or webhook | | 2 | `execution_outcome` | Flow's coarse outcome | -| 3 | `agent_status`, `connector_status`, `clinic_tool_status`, `program_terminal_state`, `overlay_phase` | The Agent, a Flow connector, a clinic tool result, where the program graph ended, and the on-screen overlay | +| 3 | `agent_status`, `connector_status`, `clinic_tool_status`, `program_terminal_state`, `overlay_phase` | The Agent, a Flow connector, a managed tool result (v1 wire key `clinic_tool_status`), where the program graph ended, and the on-screen overlay | Tiers 2 and 3 are coarse. A halt from them never says that nothing was written. An Agent timeout or error, or a connector failure, says so only when you pass diff --git a/packages/types/openadapt_types/__init__.py b/packages/types/openadapt_types/__init__.py index c930f36df6..0d4a6dcbec 100644 --- a/packages/types/openadapt_types/__init__.py +++ b/packages/types/openadapt_types/__init__.py @@ -191,6 +191,7 @@ validate_business_decision_answer, validate_business_decision_delivery, ) + # Legacy/compat shim; prefer openadapt_types.managed_job for new code. from openadapt_types.clinic_job import ( ACTION_TO_TOOL, CLINIC_INBOX_SCHEMA, @@ -224,6 +225,39 @@ planner_visible_payload, require_actuation_dispatch, ) + from openadapt_types.managed_job import ( + MANAGED_ACTION_TO_TOOL, + MANAGED_INBOX_SCHEMA, + MANAGED_MCP_TOOL_CATALOG, + MANAGED_MCP_TOOL_DESCRIPTIONS, + MANAGED_MCP_TOOL_NAMES, + MANAGED_MCP_TOOLS_SCHEMA, + MANAGED_OUTBOX_SCHEMA, + MANAGED_TOOL_RESULT_SCHEMA, + MANAGED_TOOL_TO_ACTION, + ManagedActuationDecisionV1, + ManagedActuationHeld, + ManagedBoundToolCallV1, + ManagedInboxV1, + ManagedMcpToolCatalogV1, + ManagedMcpToolNameV1, + ManagedMcpToolSpecV1, + ManagedOutboxActionV1, + ManagedOutboxV1, + ManagedToolResultV1, + ManagedToolStatusV1, + ManagedToolUnknown, + bind_managed_tool_call, + bind_managed_tool_result, + decide_managed_actuation, + is_managed_verified_success, + managed_mcp_tool_spec, + managed_planner_status, + managed_planner_visible_payload, + parse_managed_inbox, + parse_managed_outbox, + require_managed_actuation_dispatch, + ) from openadapt_types.computer_state import ( BoundingBox, ComputerState, @@ -653,6 +687,37 @@ "planner_status": "clinic_job", "planner_visible_payload": "clinic_job", "require_actuation_dispatch": "clinic_job", + "MANAGED_ACTION_TO_TOOL": "managed_job", + "MANAGED_INBOX_SCHEMA": "managed_job", + "MANAGED_MCP_TOOL_CATALOG": "managed_job", + "MANAGED_MCP_TOOL_DESCRIPTIONS": "managed_job", + "MANAGED_MCP_TOOL_NAMES": "managed_job", + "MANAGED_MCP_TOOLS_SCHEMA": "managed_job", + "MANAGED_OUTBOX_SCHEMA": "managed_job", + "MANAGED_TOOL_RESULT_SCHEMA": "managed_job", + "MANAGED_TOOL_TO_ACTION": "managed_job", + "ManagedActuationDecisionV1": "managed_job", + "ManagedActuationHeld": "managed_job", + "ManagedBoundToolCallV1": "managed_job", + "ManagedInboxV1": "managed_job", + "ManagedMcpToolCatalogV1": "managed_job", + "ManagedMcpToolNameV1": "managed_job", + "ManagedMcpToolSpecV1": "managed_job", + "ManagedOutboxActionV1": "managed_job", + "ManagedOutboxV1": "managed_job", + "ManagedToolResultV1": "managed_job", + "ManagedToolStatusV1": "managed_job", + "ManagedToolUnknown": "managed_job", + "bind_managed_tool_call": "managed_job", + "bind_managed_tool_result": "managed_job", + "decide_managed_actuation": "managed_job", + "is_managed_verified_success": "managed_job", + "managed_mcp_tool_spec": "managed_job", + "managed_planner_status": "managed_job", + "managed_planner_visible_payload": "managed_job", + "parse_managed_inbox": "managed_job", + "parse_managed_outbox": "managed_job", + "require_managed_actuation_dispatch": "managed_job", "BoundingBox": "computer_state", "ComputerState": "computer_state", "ElementRole": "computer_state", @@ -977,7 +1042,39 @@ def __dir__() -> list[str]: "parse_authoring_lease_secret", "parse_authoring_runner_uri", "require_authoring_command_active", - # clinic job inbox / outbox / MCP + # managed job inbox / outbox / MCP + "MANAGED_ACTION_TO_TOOL", + "MANAGED_INBOX_SCHEMA", + "MANAGED_MCP_TOOL_CATALOG", + "MANAGED_MCP_TOOL_DESCRIPTIONS", + "MANAGED_MCP_TOOL_NAMES", + "MANAGED_MCP_TOOLS_SCHEMA", + "MANAGED_OUTBOX_SCHEMA", + "MANAGED_TOOL_RESULT_SCHEMA", + "MANAGED_TOOL_TO_ACTION", + "ManagedActuationDecisionV1", + "ManagedActuationHeld", + "ManagedBoundToolCallV1", + "ManagedInboxV1", + "ManagedMcpToolCatalogV1", + "ManagedMcpToolNameV1", + "ManagedMcpToolSpecV1", + "ManagedOutboxActionV1", + "ManagedOutboxV1", + "ManagedToolResultV1", + "ManagedToolStatusV1", + "ManagedToolUnknown", + "bind_managed_tool_call", + "bind_managed_tool_result", + "decide_managed_actuation", + "is_managed_verified_success", + "managed_mcp_tool_spec", + "managed_planner_status", + "managed_planner_visible_payload", + "parse_managed_inbox", + "parse_managed_outbox", + "require_managed_actuation_dispatch", + # legacy/compat clinic job inbox / outbox / MCP (prefer managed_job) "ACTION_TO_TOOL", "CLINIC_INBOX_SCHEMA", "CLINIC_MCP_TOOL_CATALOG", diff --git a/packages/types/openadapt_types/approval.py b/packages/types/openadapt_types/approval.py index 4271552c57..b0e950ec10 100644 --- a/packages/types/openadapt_types/approval.py +++ b/packages/types/openadapt_types/approval.py @@ -10,7 +10,7 @@ * :class:`ApprovalModeV1` says when a step waits for a decision, and :class:`ApproverPolicyV1` says which kinds of approver may decide for each class of step. The default policy lets only a person decide, and a - ``clinical_write`` step accepts a non-person approver only after an explicit + ``high_risk_write`` step accepts a non-person approver only after an explicit opt-in. * :class:`ReadBackTier` and :class:`ReadBackOutcome` are the coarse, customer-facing verification ladder. Only an independent system read-back @@ -126,7 +126,7 @@ class ApproverAuth(str, Enum): class ApproverIdentityV1(_Strict): - """Who or what approved or declined one step. PHI-free by construction. + """Who or what approved or declined one step. Sensitive-data-free by construction. ``id`` is an opaque identifier (a Cloud user id, a rule id, an agent id, a system id), never a name or free text. @@ -281,9 +281,18 @@ class StepClass(str, Enum): REVERSIBLE = "reversible" CONSEQUENTIAL = "consequential" IRREVERSIBLE = "irreversible" - #: An irreversible write to a clinical record. + #: An irreversible, high-risk write to a system of record. + #: Wire value remains ``clinical_write`` in v1 for signed-grant and receipt compatibility. + HIGH_RISK_WRITE = "clinical_write" + #: Legacy alias for ``HIGH_RISK_WRITE``. CLINICAL_WRITE = "clinical_write" + @classmethod + def _missing_(cls, value: object) -> Optional["StepClass"]: + if value == "high_risk_write": + return cls.HIGH_RISK_WRITE + return None + _PERSON_ONLY: tuple[ApproverKind, ...] = (ApproverKind.PERSON,) @@ -296,16 +305,26 @@ class ApproverPolicyRefusal(str, Enum): """Closed reasons a policy refuses an approver.""" KIND_NOT_ALLOWED = "approver_kind_not_allowed" + #: Wire value remains ``clinical_write_needs_opt_in`` in v1 for Flow compatibility. + HIGH_RISK_WRITE_NEEDS_OPT_IN = "clinical_write_needs_opt_in" + #: Legacy alias for ``HIGH_RISK_WRITE_NEEDS_OPT_IN``. CLINICAL_WRITE_NEEDS_OPT_IN = "clinical_write_needs_opt_in" + @classmethod + def _missing_(cls, value: object) -> Optional["ApproverPolicyRefusal"]: + if value == "high_risk_write_needs_opt_in": + return cls.HIGH_RISK_WRITE_NEEDS_OPT_IN + return None + class ApproverPolicyV1(_Strict): """Which kinds of approver may decide each class of step. The default allows only a person for every class. A deployment may - widen a class to rules, agents or systems. ``clinical_write`` accepts a - non-person approver only when ``clinical_write_opt_in_sha256`` pins the - customer's signed opt-in. + widen a class to rules, agents or systems. ``HIGH_RISK_WRITE`` (v1 wire + key ``clinical_write``) accepts a non-person approver only when + ``high_risk_write_opt_in_sha256`` (v1 wire field + ``clinical_write_opt_in_sha256``) pins the customer's signed opt-in. """ schema_version: Literal["openadapt.approver-policy/v1"] = APPROVER_POLICY_SCHEMA @@ -316,6 +335,46 @@ class ApproverPolicyV1(_Strict): default=None, pattern=_SHA256 ) + @model_validator(mode="before") + @classmethod + def _normalize_domain_neutral_fields(cls, data: object) -> object: + # Accept domain-neutral input keys and normalize onto the v1 wire fields so + # signed v1 grants and Flow's v1 reader keep exact canonical bytes. + if not isinstance(data, Mapping): + return data + normalized = dict(data) + if "high_risk_write_opt_in_sha256" in normalized: + new_opt_in = normalized.pop("high_risk_write_opt_in_sha256") + if ( + "clinical_write_opt_in_sha256" in normalized + and normalized["clinical_write_opt_in_sha256"] != new_opt_in + ): + raise ValueError( + "conflicting high_risk_write_opt_in_sha256 and " + "clinical_write_opt_in_sha256 values" + ) + normalized.setdefault("clinical_write_opt_in_sha256", new_opt_in) + allowed = normalized.get("allowed") + if isinstance(allowed, Mapping) and "high_risk_write" in allowed: + allowed_copy = dict(allowed) + high_risk_kinds = allowed_copy.pop("high_risk_write") + if ( + "clinical_write" in allowed_copy + or StepClass.HIGH_RISK_WRITE in allowed_copy + ): + raise ValueError( + "policy cannot specify both high_risk_write and clinical_write" + ) + allowed_copy["clinical_write"] = high_risk_kinds + normalized["allowed"] = allowed_copy + return normalized + + @property + def high_risk_write_opt_in_sha256(self) -> Optional[StrictStr]: + """Domain-neutral alias for the v1 ``clinical_write_opt_in_sha256`` field.""" + + return self.clinical_write_opt_in_sha256 + @model_validator(mode="after") def _complete(self) -> "ApproverPolicyV1": missing = [c.value for c in StepClass if c not in self.allowed] @@ -324,9 +383,9 @@ def _complete(self) -> "ApproverPolicyV1": for step_class, kinds in self.allowed.items(): if not kinds or len(set(kinds)) != len(kinds): raise ValueError(f"{step_class.value} needs distinct approver kinds") - clinical = self.allowed[StepClass.CLINICAL_WRITE] - if clinical != _PERSON_ONLY and self.clinical_write_opt_in_sha256 is None: - raise ValueError("clinical_write allows a non-person only with an opt-in") + high_risk = self.allowed[StepClass.HIGH_RISK_WRITE] + if high_risk != _PERSON_ONLY and self.clinical_write_opt_in_sha256 is None: + raise ValueError("high_risk_write allows a non-person only with an opt-in") return self def refusal( @@ -336,10 +395,10 @@ def refusal( if approver.kind not in self.allowed[step_class]: if ( - step_class is StepClass.CLINICAL_WRITE + step_class is StepClass.HIGH_RISK_WRITE and self.clinical_write_opt_in_sha256 is None ): - return ApproverPolicyRefusal.CLINICAL_WRITE_NEEDS_OPT_IN + return ApproverPolicyRefusal.HIGH_RISK_WRITE_NEEDS_OPT_IN return ApproverPolicyRefusal.KIND_NOT_ALLOWED return None @@ -360,8 +419,8 @@ class ReadBackTier(IntEnum): save has several checks, the weakest wins. * ``INDEPENDENT_READBACK``: a read of the system of record that doesn't - go through the UI: REST, SQL, FHIR, GraphQL or a file export (Flow - tier 1). + go through the UI: REST, SQL, GraphQL, or a structured API/file export + (Flow tier 1). * ``SCREEN_READBACK``: any read through the UI, in a separate session (Flow tier 2), the acting session (tier 3) or the acting screen (tier 4). @@ -588,13 +647,23 @@ def counts_as_clean(tier: ReadBackTier, outcome: ReadBackOutcome) -> bool: class ApprovalRecordV1(_Strict): """One approval decision, as it goes into the audit trail and receipt. - PHI-free: digests, codes and opaque ids only. + Sensitive-data-free: digests, codes and opaque ids only. """ schema_version: Literal["openadapt.approval-record/v1"] = APPROVAL_RECORD_SCHEMA workflow_id: StrictStr = Field(pattern=_OPAQUE_ID) step_id: StrictStr = Field(min_length=1, max_length=256) step_class: StepClass + + @model_validator(mode="before") + @classmethod + def _normalize_domain_neutral_step_class(cls, data: object) -> object: + # Normalize domain-neutral input onto the v1 wire value for receipt compatibility. + if isinstance(data, Mapping) and data.get("step_class") == "high_risk_write": + normalized = dict(data) + normalized["step_class"] = StepClass.HIGH_RISK_WRITE.value + return normalized + return data mode: ApprovalModeV1 decision: Literal["approved", "declined"] decline_reason: Optional[StrictStr] = Field(default=None, pattern=_CODE) diff --git a/packages/types/openadapt_types/clinic_job.py b/packages/types/openadapt_types/clinic_job.py index 8c481a2798..abf63bf7dc 100644 --- a/packages/types/openadapt_types/clinic_job.py +++ b/packages/types/openadapt_types/clinic_job.py @@ -1,22 +1,10 @@ -"""Thin inbox, outbox, and MCP result contracts for clinic jobs. +"""LEGACY / COMPATIBILITY SHIM for ``openadapt.clinic-*/v1`` wire payloads. -The workbench owns schema, extract, review, and NL2SQL. This package does -not reimplement those. OpenAdapt is the hands: a compiled, admitted -program that halts on the wrong patient. Claude Code may call only the -three named tools, and only against admitted programs. +New code should use :mod:`openadapt_types.managed_job` (``openadapt.managed-*/v1``), +which provides the domain-neutral inbox, outbox, and MCP result contracts. -Identity on this wire is ``patient_token`` only. A name, MRN, or other -live identifier has no field to travel in. Wrong-patient halt is the -existing OpenAdapt identity gate. This adapter does not invent a visual -click. - -SaMD: there is no tool that decides urgency or writes follow-up copy -into a chart. ``run_create_triage_task`` creates a task the clinic -already defined, and only after ``needs_human`` is false because a -human accepted. - -Fax-first: ``run_attach_fax`` is attach plus task create. OCR stays -out of this package. +This module is retained only so previously serialized ``openadapt.clinic-*/v1`` +inbox, outbox, tool-result, and catalog payloads continue to validate cleanly. """ from __future__ import annotations @@ -26,7 +14,6 @@ from typing import Any, Literal from pydantic import ( - BaseModel, ConfigDict, Field, StrictBool, @@ -34,6 +21,20 @@ model_validator, ) +from openadapt_types.managed_job import ( + ManagedActuationDecisionV1, + ManagedActuationHeld, + ManagedToolStatusV1, + ManagedToolUnknown, + _ARTIFACT_PATH_PATTERN, + _OPAQUE_TOKEN_PATTERN, + _SOURCE_PATTERN, + _SUCCESS_STATUSES_NOTE, + _TIMESTAMP_PATTERN, + _StrictContract, +) + +# Legacy wire schema identifiers; prefer MANAGED_*_SCHEMA in openadapt_types.managed_job. CLINIC_INBOX_SCHEMA: Literal["openadapt.clinic-inbox/v1"] = "openadapt.clinic-inbox/v1" CLINIC_OUTBOX_SCHEMA: Literal["openadapt.clinic-outbox/v1"] = ( "openadapt.clinic-outbox/v1" @@ -45,32 +46,11 @@ "openadapt.clinic-mcp-tools/v1" ) -_OPAQUE_TOKEN_PATTERN = r"^[A-Za-z0-9][A-Za-z0-9._:-]{7,127}$" -_SOURCE_PATTERN = r"^[a-z][a-z0-9_]{0,63}$" -_TIMESTAMP_PATTERN = r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(Z|[+-]\d{2}:\d{2})$" -# Relative POSIX path of opaque segments. Each segment starts with an -# alphanumeric or underscore. Dots only appear as an extension separator, -# so `..`, a leading slash, and a drive letter have no legal shape. -_ARTIFACT_PATH_PATTERN = ( - r"^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*(?:/[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*)*$" -) - -_SUCCESS_STATUSES_NOTE = ( - "Only status VERIFIED is success. HALTED and RECONCILIATION_REQUIRED " - "are not success and must not be summarized as success." -) - - -class _StrictContract(BaseModel): - model_config = ConfigDict(extra="forbid", frozen=True) - - -class ClinicActuationHeld(ValueError): - """Outbox still needs a human stamp; actuation must not dispatch.""" - - -class ClinicToolUnknown(ValueError): - """Caller named a tool this catalog does not admit.""" +# Legacy/compat aliases to domain-neutral exceptions and enums in managed_job. +ClinicActuationHeld = ManagedActuationHeld +ClinicToolUnknown = ManagedToolUnknown +ClinicToolStatusV1 = ManagedToolStatusV1 +ClinicActuationDecisionV1 = ManagedActuationDecisionV1 class ClinicOutboxActionV1(str, Enum): @@ -85,17 +65,6 @@ class ClinicMcpToolNameV1(str, Enum): RUN_CREATE_TRIAGE_TASK = "run_create_triage_task" -class ClinicToolStatusV1(str, Enum): - VERIFIED = "VERIFIED" - HALTED = "HALTED" - RECONCILIATION_REQUIRED = "RECONCILIATION_REQUIRED" - - -class ClinicActuationDecisionV1(str, Enum): - DISPATCH = "dispatch" - HOLD_FOR_HUMAN = "hold_for_human" - - ACTION_TO_TOOL: dict[ClinicOutboxActionV1, ClinicMcpToolNameV1] = { ClinicOutboxActionV1.HARVEST: ClinicMcpToolNameV1.RUN_HARVEST, ClinicOutboxActionV1.ATTACH_FAX: ClinicMcpToolNameV1.RUN_ATTACH_FAX, diff --git a/packages/types/openadapt_types/managed_job.py b/packages/types/openadapt_types/managed_job.py new file mode 100644 index 0000000000..c5a9b700df --- /dev/null +++ b/packages/types/openadapt_types/managed_job.py @@ -0,0 +1,422 @@ +"""Thin inbox, outbox, and MCP result contracts for managed jobs. + +An upstream workbench owns extraction, review, and planning. This package does +not reimplement those. OpenAdapt is the execution layer: a compiled, admitted +program that halts on target identity mismatch. An agent may call only the +named tools in the catalog, and only against admitted programs. + +Identity on this wire is ``subject_token`` only. A personal name, account +number, or other live identifier has no field to travel in. Wrong-record halt +is the existing OpenAdapt identity gate. This adapter does not invent a visual +click. + +There is no tool that makes domain decisions or writes unreviewed free-text +copy into a system of record. ``run_create_task`` creates a task the +organization already defined, and only after ``needs_human`` is false because +a human approved it. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from enum import Enum +from typing import Any, Literal + +from pydantic import ( + BaseModel, + ConfigDict, + Field, + StrictBool, + StrictStr, + field_validator, + model_validator, +) + +MANAGED_INBOX_SCHEMA: Literal["openadapt.managed-inbox/v1"] = ( + "openadapt.managed-inbox/v1" +) +MANAGED_OUTBOX_SCHEMA: Literal["openadapt.managed-outbox/v1"] = ( + "openadapt.managed-outbox/v1" +) +MANAGED_TOOL_RESULT_SCHEMA: Literal["openadapt.managed-tool-result/v1"] = ( + "openadapt.managed-tool-result/v1" +) +MANAGED_MCP_TOOLS_SCHEMA: Literal["openadapt.managed-mcp-tools/v1"] = ( + "openadapt.managed-mcp-tools/v1" +) + +_OPAQUE_TOKEN_PATTERN = r"^[A-Za-z0-9][A-Za-z0-9._:-]{7,127}$" +_SOURCE_PATTERN = r"^[a-z][a-z0-9_]{0,63}$" +_TIMESTAMP_PATTERN = r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(Z|[+-]\d{2}:\d{2})$" +# Relative POSIX path of opaque segments. Each segment starts with an +# alphanumeric or underscore. Dots only appear as an extension separator, +# so `..`, a leading slash, and a drive letter have no legal shape. +_ARTIFACT_PATH_PATTERN = ( + r"^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*(?:/[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*)*$" +) + +_SUCCESS_STATUSES_NOTE = ( + "Only status VERIFIED is success. HALTED and RECONCILIATION_REQUIRED " + "are not success and must not be summarized as success." +) + + +class _StrictContract(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + +class ManagedActuationHeld(ValueError): + """Outbox still needs a human approval; actuation must not dispatch.""" + + +class ManagedToolUnknown(ValueError): + """Caller named a tool this catalog does not admit.""" + + +class ManagedOutboxActionV1(str, Enum): + COLLECT = "collect" + ATTACH_ARTIFACT = "attach_artifact" + CREATE_TASK = "create_task" + + +class ManagedMcpToolNameV1(str, Enum): + RUN_COLLECT = "run_collect" + RUN_ATTACH_ARTIFACT = "run_attach_artifact" + RUN_CREATE_TASK = "run_create_task" + + +class ManagedToolStatusV1(str, Enum): + VERIFIED = "VERIFIED" + HALTED = "HALTED" + RECONCILIATION_REQUIRED = "RECONCILIATION_REQUIRED" + + +class ManagedActuationDecisionV1(str, Enum): + DISPATCH = "dispatch" + HOLD_FOR_HUMAN = "hold_for_human" + + +MANAGED_ACTION_TO_TOOL: dict[ManagedOutboxActionV1, ManagedMcpToolNameV1] = { + ManagedOutboxActionV1.COLLECT: ManagedMcpToolNameV1.RUN_COLLECT, + ManagedOutboxActionV1.ATTACH_ARTIFACT: ManagedMcpToolNameV1.RUN_ATTACH_ARTIFACT, + ManagedOutboxActionV1.CREATE_TASK: ManagedMcpToolNameV1.RUN_CREATE_TASK, +} + +MANAGED_TOOL_TO_ACTION: dict[ManagedMcpToolNameV1, ManagedOutboxActionV1] = { + tool: action for action, tool in MANAGED_ACTION_TO_TOOL.items() +} + +MANAGED_MCP_TOOL_NAMES: tuple[ManagedMcpToolNameV1, ...] = ( + ManagedMcpToolNameV1.RUN_COLLECT, + ManagedMcpToolNameV1.RUN_ATTACH_ARTIFACT, + ManagedMcpToolNameV1.RUN_CREATE_TASK, +) + +# Closed copy for an MCP host. Not a domain decision, not free-text copy, +# not an extract/review/ask/audit tool. +MANAGED_MCP_TOOL_DESCRIPTIONS: dict[ManagedMcpToolNameV1, str] = { + ManagedMcpToolNameV1.RUN_COLLECT: ( + "Run the admitted collect program for this inbox job. Returns " + "VERIFIED, HALTED, or RECONCILIATION_REQUIRED. Halt is halt." + ), + ManagedMcpToolNameV1.RUN_ATTACH_ARTIFACT: ( + "Attach the artifact and create the organization-defined task. " + "Returns VERIFIED, HALTED, or RECONCILIATION_REQUIRED. Halt is halt." + ), + ManagedMcpToolNameV1.RUN_CREATE_TASK: ( + "Create the organization-defined task after a human approval. " + "Returns VERIFIED, HALTED, or RECONCILIATION_REQUIRED. Halt is halt." + ), +} + +_TOOLS_THAT_REQUIRE_OUTBOX = frozenset( + { + ManagedMcpToolNameV1.RUN_ATTACH_ARTIFACT, + ManagedMcpToolNameV1.RUN_CREATE_TASK, + } +) + + +class ManagedInboxV1(_StrictContract): + """Workbench to OpenAdapt job. Opaque token only; never a live name.""" + + schema_version: Literal["openadapt.managed-inbox/v1"] = MANAGED_INBOX_SCHEMA + subject_token: StrictStr = Field(pattern=_OPAQUE_TOKEN_PATTERN) + artifact_path: StrictStr = Field( + pattern=_ARTIFACT_PATH_PATTERN, + min_length=1, + max_length=512, + ) + source: StrictStr = Field(pattern=_SOURCE_PATTERN) + recorded_at: StrictStr = Field(pattern=_TIMESTAMP_PATTERN) + + @model_validator(mode="after") + def _artifact_path_has_no_relative_segments(self) -> "ManagedInboxV1": + for segment in self.artifact_path.split("/"): + if segment in {".", ".."} or ".." in segment: + raise ValueError("artifact_path must not contain relative segments") + return self + + +class ManagedOutboxV1(_StrictContract): + """Actuation intent. OpenAdapt applies the template only after a human approval.""" + + schema_version: Literal["openadapt.managed-outbox/v1"] = MANAGED_OUTBOX_SCHEMA + action: ManagedOutboxActionV1 + template: StrictStr = Field(pattern=_OPAQUE_TOKEN_PATTERN) + needs_human: StrictBool + + +class ManagedToolResultV1(_StrictContract): + """Typed MCP result. Status is the outcome; there is no success flag to set.""" + + model_config = ConfigDict( + extra="forbid", + frozen=True, + json_schema_extra={ + "x-openadapt-success-rule": _SUCCESS_STATUSES_NOTE, + }, + ) + + schema_version: Literal["openadapt.managed-tool-result/v1"] = ( + MANAGED_TOOL_RESULT_SCHEMA + ) + tool: ManagedMcpToolNameV1 + status: ManagedToolStatusV1 + subject_token: StrictStr = Field(pattern=_OPAQUE_TOKEN_PATTERN) + + @property + def ok(self) -> bool: + return self.status is ManagedToolStatusV1.VERIFIED + + +class ManagedMcpToolSpecV1(_StrictContract): + name: ManagedMcpToolNameV1 + action: ManagedOutboxActionV1 + requires_outbox: StrictBool + destructive: Literal[True] = True + read_only: Literal[False] = False + + @field_validator("requires_outbox", "destructive", "read_only", mode="before") + @classmethod + def _must_be_strict_bool(cls, value: object) -> object: + if type(value) is not bool: + raise ValueError("Input should be a valid boolean") + return value + + @model_validator(mode="after") + def _action_matches_name(self) -> "ManagedMcpToolSpecV1": + expected = MANAGED_TOOL_TO_ACTION[self.name] + if self.action is not expected: + raise ValueError("tool name and action must match") + required = self.name in _TOOLS_THAT_REQUIRE_OUTBOX + if self.requires_outbox is not required: + raise ValueError("requires_outbox must match the tool") + return self + + +class ManagedCollectToolSpecV1(ManagedMcpToolSpecV1): + name: Literal[ManagedMcpToolNameV1.RUN_COLLECT] + action: Literal[ManagedOutboxActionV1.COLLECT] + requires_outbox: Literal[False] + + +class ManagedAttachArtifactToolSpecV1(ManagedMcpToolSpecV1): + name: Literal[ManagedMcpToolNameV1.RUN_ATTACH_ARTIFACT] + action: Literal[ManagedOutboxActionV1.ATTACH_ARTIFACT] + requires_outbox: Literal[True] + + +class ManagedCreateTaskToolSpecV1(ManagedMcpToolSpecV1): + name: Literal[ManagedMcpToolNameV1.RUN_CREATE_TASK] + action: Literal[ManagedOutboxActionV1.CREATE_TASK] + requires_outbox: Literal[True] + + +class ManagedMcpToolCatalogV1(_StrictContract): + schema_version: Literal["openadapt.managed-mcp-tools/v1"] = MANAGED_MCP_TOOLS_SCHEMA + tools: tuple[ + ManagedCollectToolSpecV1, + ManagedAttachArtifactToolSpecV1, + ManagedCreateTaskToolSpecV1, + ] + + @model_validator(mode="after") + def _exactly_the_three_admitted_tools(self) -> "ManagedMcpToolCatalogV1": + names = tuple(spec.name for spec in self.tools) + if names != MANAGED_MCP_TOOL_NAMES: + raise ValueError("catalog must be exactly the three admitted tools") + return self + + +class ManagedBoundToolCallV1(_StrictContract): + tool: ManagedMcpToolNameV1 + inbox: ManagedInboxV1 + outbox: ManagedOutboxV1 | None = None + + @model_validator(mode="after") + def _outbox_matches_tool(self) -> "ManagedBoundToolCallV1": + if self.tool in _TOOLS_THAT_REQUIRE_OUTBOX and self.outbox is None: + raise ValueError(f"{self.tool.value} requires an outbox") + if self.outbox is not None: + expected = MANAGED_TOOL_TO_ACTION[self.tool] + if self.outbox.action is not expected: + raise ValueError("outbox action must match the tool") + return self + + +MANAGED_MCP_TOOL_CATALOG = ManagedMcpToolCatalogV1( + tools=( + ManagedCollectToolSpecV1( + name=ManagedMcpToolNameV1.RUN_COLLECT, + action=ManagedOutboxActionV1.COLLECT, + requires_outbox=False, + ), + ManagedAttachArtifactToolSpecV1( + name=ManagedMcpToolNameV1.RUN_ATTACH_ARTIFACT, + action=ManagedOutboxActionV1.ATTACH_ARTIFACT, + requires_outbox=True, + ), + ManagedCreateTaskToolSpecV1( + name=ManagedMcpToolNameV1.RUN_CREATE_TASK, + action=ManagedOutboxActionV1.CREATE_TASK, + requires_outbox=True, + ), + ) +) + + +def parse_managed_inbox(payload: Mapping[str, Any]) -> ManagedInboxV1: + """Parse a workbench inbox. Missing ``subject_token`` is a validation error.""" + + return ManagedInboxV1.model_validate(payload) + + +def parse_managed_outbox(payload: Mapping[str, Any]) -> ManagedOutboxV1: + return ManagedOutboxV1.model_validate(payload) + + +def decide_managed_actuation(outbox: ManagedOutboxV1) -> ManagedActuationDecisionV1: + if outbox.needs_human: + return ManagedActuationDecisionV1.HOLD_FOR_HUMAN + return ManagedActuationDecisionV1.DISPATCH + + +def require_managed_actuation_dispatch(outbox: ManagedOutboxV1) -> None: + """Refuse to dispatch when human approval is still required.""" + + if outbox.needs_human: + raise ManagedActuationHeld( + "outbox.needs_human is true; do not dispatch actuation" + ) + + +def is_managed_verified_success(result: ManagedToolResultV1) -> bool: + """True only for ``VERIFIED``. Halt and reconciliation are not success.""" + + return result.status is ManagedToolStatusV1.VERIFIED + + +def managed_planner_status(result: ManagedToolResultV1) -> ManagedToolStatusV1: + """Return the typed status unchanged. Halt is halt.""" + + return result.status + + +def managed_planner_visible_payload( + result: ManagedToolResultV1, +) -> dict[str, object]: + """Planner-facing dict. ``ok`` is derived from status and cannot be set.""" + + return { + "tool": result.tool.value, + "status": result.status.value, + "subject_token": result.subject_token, + "ok": is_managed_verified_success(result), + } + + +def managed_mcp_tool_spec( + name: ManagedMcpToolNameV1 | str, +) -> ManagedMcpToolSpecV1: + label = name.value if isinstance(name, ManagedMcpToolNameV1) else name + if not isinstance(label, str): + raise ManagedToolUnknown("tool name is not an admitted managed tool") + try: + tool = ManagedMcpToolNameV1(label) + except ValueError as exc: + raise ManagedToolUnknown(f"{label!r} is not an admitted managed tool") from exc + for spec in MANAGED_MCP_TOOL_CATALOG.tools: + if spec.name is tool: + return spec + raise ManagedToolUnknown(f"{label!r} is not an admitted managed tool") + + +def bind_managed_tool_call( + tool: ManagedMcpToolNameV1 | str, + inbox: Mapping[str, Any], + outbox: Mapping[str, Any] | None = None, +) -> ManagedBoundToolCallV1: + """Validate inbox/outbox and refuse actuation that still needs a human.""" + + spec = managed_mcp_tool_spec(tool) + parsed_inbox = parse_managed_inbox(inbox) + parsed_outbox: ManagedOutboxV1 | None + if outbox is None: + parsed_outbox = None + else: + parsed_outbox = parse_managed_outbox(outbox) + require_managed_actuation_dispatch(parsed_outbox) + return ManagedBoundToolCallV1( + tool=spec.name, + inbox=parsed_inbox, + outbox=parsed_outbox, + ) + + +def bind_managed_tool_result( + call: ManagedBoundToolCallV1, + status: ManagedToolStatusV1, +) -> ManagedToolResultV1: + """Stamp the inbox token onto the result. Identity does not get rewritten.""" + + return ManagedToolResultV1( + tool=call.tool, + status=status, + subject_token=call.inbox.subject_token, + ) + + +__all__ = [ + "MANAGED_ACTION_TO_TOOL", + "MANAGED_INBOX_SCHEMA", + "MANAGED_MCP_TOOL_CATALOG", + "MANAGED_MCP_TOOL_DESCRIPTIONS", + "MANAGED_MCP_TOOL_NAMES", + "MANAGED_MCP_TOOLS_SCHEMA", + "MANAGED_OUTBOX_SCHEMA", + "MANAGED_TOOL_RESULT_SCHEMA", + "MANAGED_TOOL_TO_ACTION", + "ManagedActuationDecisionV1", + "ManagedActuationHeld", + "ManagedBoundToolCallV1", + "ManagedInboxV1", + "ManagedMcpToolCatalogV1", + "ManagedMcpToolNameV1", + "ManagedMcpToolSpecV1", + "ManagedOutboxActionV1", + "ManagedOutboxV1", + "ManagedToolResultV1", + "ManagedToolStatusV1", + "ManagedToolUnknown", + "bind_managed_tool_call", + "bind_managed_tool_result", + "decide_managed_actuation", + "is_managed_verified_success", + "managed_mcp_tool_spec", + "managed_planner_status", + "managed_planner_visible_payload", + "parse_managed_inbox", + "parse_managed_outbox", + "require_managed_actuation_dispatch", +] diff --git a/packages/types/openadapt_types/plain_results.py b/packages/types/openadapt_types/plain_results.py index 591fff870e..a2ed1031fd 100644 --- a/packages/types/openadapt_types/plain_results.py +++ b/packages/types/openadapt_types/plain_results.py @@ -61,7 +61,7 @@ PLAIN_PROGRESS_SCHEMA = "openadapt.plain-progress/v1" # An outcome code: an enum value, never free text. Anything else is treated as -# unrecognized and kept out of ``exact`` so a stray string can't carry PHI. +# unrecognized and kept out of ``exact`` so a stray string can't carry sensitive data. _CODE = re.compile(r"^[A-Za-z][A-Za-z0-9_]{0,63}$") _CODE_PATTERN = _CODE.pattern _TECHNICAL_CODE_PATTERN = ( @@ -105,6 +105,9 @@ class OutcomeSourceV1(str, Enum): EXECUTION_OUTCOME = "execution_outcome" AGENT_STATUS = "agent_status" CONNECTOR_STATUS = "connector_status" + #: Domain-neutral alias; v1 wire key remains ``clinic_tool_status`` for + #: compatibility with deployed v1 readers and schemas. + MANAGED_TOOL_STATUS = "clinic_tool_status" CLINIC_TOOL_STATUS = "clinic_tool_status" PROGRAM_TERMINAL_STATE = "program_terminal_state" OVERLAY_PHASE = "overlay_phase" @@ -137,6 +140,31 @@ class PlainOutcomeInputsV1(_StrictContract): dispatched: StrictBool | None = None delivery_uncertain: StrictBool | None = None + @model_validator(mode="before") + @classmethod + def _normalize_managed_tool_status(cls, data: object) -> object: + # Accept domain-neutral managed_tool_status input and normalize onto the + # v1 wire field so deployed v1 readers and schemas see exact v1 bytes. + if isinstance(data, Mapping) and "managed_tool_status" in data: + normalized = dict(data) + managed_val = normalized.pop("managed_tool_status") + if ( + "clinic_tool_status" in normalized + and normalized["clinic_tool_status"] != managed_val + ): + raise ValueError( + "conflicting managed_tool_status and legacy clinic_tool_status values" + ) + normalized.setdefault("clinic_tool_status", managed_val) + return normalized + return data + + @property + def managed_tool_status(self) -> StrictStr | None: + """Domain-neutral alias for the v1 ``clinic_tool_status`` field.""" + + return self.clinic_tool_status + class PlainOutcomeV1(_StrictContract): """One run's result in plain words, with the exact values behind it. @@ -470,6 +498,7 @@ def plain_outcome( execution_outcome: str | Enum | None = None, agent_status: str | Enum | None = None, connector_status: str | Enum | None = None, + managed_tool_status: str | Enum | None = None, clinic_tool_status: str | Enum | None = None, program_terminal_state: str | Enum | None = None, overlay_phase: str | Enum | None = None, @@ -496,6 +525,26 @@ def plain_outcome( for a person, or an overlay phase such as executing or paused. """ + # Legacy/compat: accept clinic_tool_status when managed_tool_status is omitted, + # and refuse conflicting values when both are supplied. + if managed_tool_status is not None and clinic_tool_status is not None: + m_val = ( + managed_tool_status.value + if isinstance(managed_tool_status, Enum) + else managed_tool_status + ) + c_val = ( + clinic_tool_status.value + if isinstance(clinic_tool_status, Enum) + else clinic_tool_status + ) + if m_val != c_val: + raise ValueError( + "conflicting managed_tool_status and legacy clinic_tool_status values" + ) + effective_managed_tool_status = ( + managed_tool_status if managed_tool_status is not None else clinic_tool_status + ) resolved = _resolve( { "transaction_outcome": transaction_outcome, @@ -504,7 +553,7 @@ def plain_outcome( "execution_outcome": execution_outcome, "agent_status": agent_status, "connector_status": connector_status, - "clinic_tool_status": clinic_tool_status, + "clinic_tool_status": effective_managed_tool_status, "program_terminal_state": program_terminal_state, "overlay_phase": overlay_phase, }, diff --git a/packages/types/openadapt_types/schemas/approval-record-v1.json b/packages/types/openadapt_types/schemas/approval-record-v1.json index 31b444abd9..4d01d1d632 100644 --- a/packages/types/openadapt_types/schemas/approval-record-v1.json +++ b/packages/types/openadapt_types/schemas/approval-record-v1.json @@ -27,7 +27,7 @@ }, "ApproverIdentityV1": { "additionalProperties": false, - "description": "Who or what approved or declined one step. PHI-free by construction.\n\n``id`` is an opaque identifier (a Cloud user id, a rule id, an agent id,\na system id), never a name or free text.", + "description": "Who or what approved or declined one step. Sensitive-data-free by construction.\n\n``id`` is an opaque identifier (a Cloud user id, a rule id, an agent id,\na system id), never a name or free text.", "properties": { "auth": { "$ref": "#/$defs/ApproverAuth" @@ -116,6 +116,7 @@ "reversible", "consequential", "irreversible", + "clinical_write", "clinical_write" ], "title": "StepClass", @@ -123,7 +124,7 @@ } }, "additionalProperties": false, - "description": "One approval decision, as it goes into the audit trail and receipt.\n\nPHI-free: digests, codes and opaque ids only.", + "description": "One approval decision, as it goes into the audit trail and receipt.\n\nSensitive-data-free: digests, codes and opaque ids only.", "properties": { "approver": { "$ref": "#/$defs/ApproverIdentityV1" diff --git a/packages/types/openadapt_types/schemas/approver-identity-v1.json b/packages/types/openadapt_types/schemas/approver-identity-v1.json index 27a82049da..68907f4fe3 100644 --- a/packages/types/openadapt_types/schemas/approver-identity-v1.json +++ b/packages/types/openadapt_types/schemas/approver-identity-v1.json @@ -26,7 +26,7 @@ } }, "additionalProperties": false, - "description": "Who or what approved or declined one step. PHI-free by construction.\n\n``id`` is an opaque identifier (a Cloud user id, a rule id, an agent id,\na system id), never a name or free text.", + "description": "Who or what approved or declined one step. Sensitive-data-free by construction.\n\n``id`` is an opaque identifier (a Cloud user id, a rule id, an agent id,\na system id), never a name or free text.", "properties": { "auth": { "$ref": "#/$defs/ApproverAuth" diff --git a/packages/types/openadapt_types/schemas/approver-policy-v1.json b/packages/types/openadapt_types/schemas/approver-policy-v1.json index 939d61d990..383f4da299 100644 --- a/packages/types/openadapt_types/schemas/approver-policy-v1.json +++ b/packages/types/openadapt_types/schemas/approver-policy-v1.json @@ -18,6 +18,7 @@ "reversible", "consequential", "irreversible", + "clinical_write", "clinical_write" ], "title": "StepClass", @@ -25,7 +26,7 @@ } }, "additionalProperties": false, - "description": "Which kinds of approver may decide each class of step.\n\nThe default allows only a person for every class. A deployment may\nwiden a class to rules, agents or systems. ``clinical_write`` accepts a\nnon-person approver only when ``clinical_write_opt_in_sha256`` pins the\ncustomer's signed opt-in.", + "description": "Which kinds of approver may decide each class of step.\n\nThe default allows only a person for every class. A deployment may\nwiden a class to rules, agents or systems. ``HIGH_RISK_WRITE`` (v1 wire\nkey ``clinical_write``) accepts a non-person approver only when\n``high_risk_write_opt_in_sha256`` (v1 wire field\n``clinical_write_opt_in_sha256``) pins the customer's signed opt-in.", "properties": { "allowed": { "additionalProperties": { diff --git a/packages/types/openadapt_types/schemas/clinic-tool-result-v1.json b/packages/types/openadapt_types/schemas/clinic-tool-result-v1.json index 6d34544c40..53067af9c5 100644 --- a/packages/types/openadapt_types/schemas/clinic-tool-result-v1.json +++ b/packages/types/openadapt_types/schemas/clinic-tool-result-v1.json @@ -9,13 +9,13 @@ "title": "ClinicMcpToolNameV1", "type": "string" }, - "ClinicToolStatusV1": { + "ManagedToolStatusV1": { "enum": [ "VERIFIED", "HALTED", "RECONCILIATION_REQUIRED" ], - "title": "ClinicToolStatusV1", + "title": "ManagedToolStatusV1", "type": "string" } }, @@ -34,7 +34,7 @@ "type": "string" }, "status": { - "$ref": "#/$defs/ClinicToolStatusV1" + "$ref": "#/$defs/ManagedToolStatusV1" }, "tool": { "$ref": "#/$defs/ClinicMcpToolNameV1" diff --git a/packages/types/openadapt_types/schemas/managed-inbox-v1.json b/packages/types/openadapt_types/schemas/managed-inbox-v1.json new file mode 100644 index 0000000000..dff3f1de93 --- /dev/null +++ b/packages/types/openadapt_types/schemas/managed-inbox-v1.json @@ -0,0 +1,42 @@ +{ + "additionalProperties": false, + "description": "Workbench to OpenAdapt job. Opaque token only; never a live name.", + "properties": { + "artifact_path": { + "maxLength": 512, + "minLength": 1, + "pattern": "^[A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)*(?:/[A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)*)*$", + "title": "Artifact Path", + "type": "string" + }, + "recorded_at": { + "pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(Z|[+-]\\d{2}:\\d{2})$", + "title": "Recorded At", + "type": "string" + }, + "schema_version": { + "const": "openadapt.managed-inbox/v1", + "default": "openadapt.managed-inbox/v1", + "title": "Schema Version", + "type": "string" + }, + "source": { + "pattern": "^[a-z][a-z0-9_]{0,63}$", + "title": "Source", + "type": "string" + }, + "subject_token": { + "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{7,127}$", + "title": "Subject Token", + "type": "string" + } + }, + "required": [ + "subject_token", + "artifact_path", + "source", + "recorded_at" + ], + "title": "ManagedInboxV1", + "type": "object" +} diff --git a/packages/types/openadapt_types/schemas/managed-mcp-tools-v1.json b/packages/types/openadapt_types/schemas/managed-mcp-tools-v1.json new file mode 100644 index 0000000000..19e3369a12 --- /dev/null +++ b/packages/types/openadapt_types/schemas/managed-mcp-tools-v1.json @@ -0,0 +1,152 @@ +{ + "$defs": { + "ManagedAttachArtifactToolSpecV1": { + "additionalProperties": false, + "properties": { + "action": { + "const": "attach_artifact", + "title": "Action", + "type": "string" + }, + "destructive": { + "const": true, + "default": true, + "title": "Destructive", + "type": "boolean" + }, + "name": { + "const": "run_attach_artifact", + "title": "Name", + "type": "string" + }, + "read_only": { + "const": false, + "default": false, + "title": "Read Only", + "type": "boolean" + }, + "requires_outbox": { + "const": true, + "title": "Requires Outbox", + "type": "boolean" + } + }, + "required": [ + "name", + "action", + "requires_outbox" + ], + "title": "ManagedAttachArtifactToolSpecV1", + "type": "object" + }, + "ManagedCollectToolSpecV1": { + "additionalProperties": false, + "properties": { + "action": { + "const": "collect", + "title": "Action", + "type": "string" + }, + "destructive": { + "const": true, + "default": true, + "title": "Destructive", + "type": "boolean" + }, + "name": { + "const": "run_collect", + "title": "Name", + "type": "string" + }, + "read_only": { + "const": false, + "default": false, + "title": "Read Only", + "type": "boolean" + }, + "requires_outbox": { + "const": false, + "title": "Requires Outbox", + "type": "boolean" + } + }, + "required": [ + "name", + "action", + "requires_outbox" + ], + "title": "ManagedCollectToolSpecV1", + "type": "object" + }, + "ManagedCreateTaskToolSpecV1": { + "additionalProperties": false, + "properties": { + "action": { + "const": "create_task", + "title": "Action", + "type": "string" + }, + "destructive": { + "const": true, + "default": true, + "title": "Destructive", + "type": "boolean" + }, + "name": { + "const": "run_create_task", + "title": "Name", + "type": "string" + }, + "read_only": { + "const": false, + "default": false, + "title": "Read Only", + "type": "boolean" + }, + "requires_outbox": { + "const": true, + "title": "Requires Outbox", + "type": "boolean" + } + }, + "required": [ + "name", + "action", + "requires_outbox" + ], + "title": "ManagedCreateTaskToolSpecV1", + "type": "object" + } + }, + "additionalProperties": false, + "properties": { + "schema_version": { + "const": "openadapt.managed-mcp-tools/v1", + "default": "openadapt.managed-mcp-tools/v1", + "title": "Schema Version", + "type": "string" + }, + "tools": { + "maxItems": 3, + "minItems": 3, + "prefixItems": [ + { + "$ref": "#/$defs/ManagedCollectToolSpecV1" + }, + { + "$ref": "#/$defs/ManagedAttachArtifactToolSpecV1" + }, + { + "$ref": "#/$defs/ManagedCreateTaskToolSpecV1" + } + ], + "title": "Tools", + "type": "array" + } + }, + "required": [ + "tools" + ], + "title": "ManagedMcpToolCatalogV1", + "type": "object" +} diff --git a/packages/types/openadapt_types/schemas/managed-outbox-v1.json b/packages/types/openadapt_types/schemas/managed-outbox-v1.json new file mode 100644 index 0000000000..a71100d455 --- /dev/null +++ b/packages/types/openadapt_types/schemas/managed-outbox-v1.json @@ -0,0 +1,42 @@ +{ + "$defs": { + "ManagedOutboxActionV1": { + "enum": [ + "collect", + "attach_artifact", + "create_task" + ], + "title": "ManagedOutboxActionV1", + "type": "string" + } + }, + "additionalProperties": false, + "description": "Actuation intent. OpenAdapt applies the template only after a human approval.", + "properties": { + "action": { + "$ref": "#/$defs/ManagedOutboxActionV1" + }, + "needs_human": { + "title": "Needs Human", + "type": "boolean" + }, + "schema_version": { + "const": "openadapt.managed-outbox/v1", + "default": "openadapt.managed-outbox/v1", + "title": "Schema Version", + "type": "string" + }, + "template": { + "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{7,127}$", + "title": "Template", + "type": "string" + } + }, + "required": [ + "action", + "template", + "needs_human" + ], + "title": "ManagedOutboxV1", + "type": "object" +} diff --git a/packages/types/openadapt_types/schemas/managed-tool-result-v1.json b/packages/types/openadapt_types/schemas/managed-tool-result-v1.json new file mode 100644 index 0000000000..4062e17d02 --- /dev/null +++ b/packages/types/openadapt_types/schemas/managed-tool-result-v1.json @@ -0,0 +1,51 @@ +{ + "$defs": { + "ManagedMcpToolNameV1": { + "enum": [ + "run_collect", + "run_attach_artifact", + "run_create_task" + ], + "title": "ManagedMcpToolNameV1", + "type": "string" + }, + "ManagedToolStatusV1": { + "enum": [ + "VERIFIED", + "HALTED", + "RECONCILIATION_REQUIRED" + ], + "title": "ManagedToolStatusV1", + "type": "string" + } + }, + "additionalProperties": false, + "description": "Typed MCP result. Status is the outcome; there is no success flag to set.", + "properties": { + "schema_version": { + "const": "openadapt.managed-tool-result/v1", + "default": "openadapt.managed-tool-result/v1", + "title": "Schema Version", + "type": "string" + }, + "status": { + "$ref": "#/$defs/ManagedToolStatusV1" + }, + "subject_token": { + "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{7,127}$", + "title": "Subject Token", + "type": "string" + }, + "tool": { + "$ref": "#/$defs/ManagedMcpToolNameV1" + } + }, + "required": [ + "tool", + "status", + "subject_token" + ], + "title": "ManagedToolResultV1", + "type": "object", + "x-openadapt-success-rule": "Only status VERIFIED is success. HALTED and RECONCILIATION_REQUIRED are not success and must not be summarized as success." +} diff --git a/packages/types/openadapt_types/vocabulary/outcomes.json b/packages/types/openadapt_types/vocabulary/outcomes.json index e68c4be2b5..88fee216c9 100644 --- a/packages/types/openadapt_types/vocabulary/outcomes.json +++ b/packages/types/openadapt_types/vocabulary/outcomes.json @@ -81,7 +81,7 @@ { "source": "clinic_tool_status", "repository": "OpenAdaptAI/openadapt-types", - "symbol": "openadapt_types/clinic_job.py ClinicToolStatusV1", + "symbol": "openadapt_types/managed_job.py ManagedToolStatusV1", "read_at": "origin/main 07b8b0c, read 2026-10-09", "values": ["VERIFIED", "HALTED", "RECONCILIATION_REQUIRED"] }, @@ -459,7 +459,7 @@ } }, "clinic_tool_status": { - "meaning": "The status on a clinic tool result. HALTED here is coarse.", + "meaning": "The status on a managed tool result. HALTED here is coarse.", "values": { "VERIFIED": { "result": "done", diff --git a/packages/types/scripts/export_managed_job_schemas.py b/packages/types/scripts/export_managed_job_schemas.py new file mode 100644 index 0000000000..6a988e1249 --- /dev/null +++ b/packages/types/scripts/export_managed_job_schemas.py @@ -0,0 +1,36 @@ +"""Export the managed inbox, outbox, and MCP JSON Schemas into the package.""" + +from __future__ import annotations + +import json +from pathlib import Path + +from openadapt_types.managed_job import ( + ManagedInboxV1, + ManagedMcpToolCatalogV1, + ManagedOutboxV1, + ManagedToolResultV1, +) + +ROOT = Path(__file__).resolve().parents[1] +SCHEMA_DIR = ROOT / "openadapt_types" / "schemas" +SCHEMAS = { + "managed-inbox-v1.json": ManagedInboxV1, + "managed-outbox-v1.json": ManagedOutboxV1, + "managed-tool-result-v1.json": ManagedToolResultV1, + "managed-mcp-tools-v1.json": ManagedMcpToolCatalogV1, +} + + +def main() -> int: + SCHEMA_DIR.mkdir(parents=True, exist_ok=True) + for filename, model in SCHEMAS.items(): + (SCHEMA_DIR / filename).write_text( + json.dumps(model.model_json_schema(), indent=2, sort_keys=True) + "\n", + encoding="utf-8", + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packages/types/tests/test_approval.py b/packages/types/tests/test_approval.py index 599bbc12f0..2438f4c33c 100644 --- a/packages/types/tests/test_approval.py +++ b/packages/types/tests/test_approval.py @@ -158,7 +158,7 @@ def test_default_policy_is_person_only() -> None: assert not policy.permits(step_class, other) -def test_policy_can_allow_an_agent_and_still_forbid_it_for_clinical_writes() -> None: +def test_policy_can_allow_an_agent_and_still_forbid_it_for_high_risk_writes() -> None: allowed = {c: (ApproverKind.PERSON,) for c in StepClass} allowed[StepClass.CONSEQUENTIAL] = (ApproverKind.PERSON, ApproverKind.AGENT) policy = ApproverPolicyV1(allowed=allowed) @@ -166,18 +166,91 @@ def test_policy_can_allow_an_agent_and_still_forbid_it_for_clinical_writes() -> assert policy.refusal(StepClass.IRREVERSIBLE, AGENT) is ( ApproverPolicyRefusal.KIND_NOT_ALLOWED ) - assert policy.refusal(StepClass.CLINICAL_WRITE, AGENT) is ( - ApproverPolicyRefusal.CLINICAL_WRITE_NEEDS_OPT_IN + assert policy.refusal(StepClass.HIGH_RISK_WRITE, AGENT) is ( + ApproverPolicyRefusal.HIGH_RISK_WRITE_NEEDS_OPT_IN ) -def test_clinical_write_non_person_needs_an_opt_in() -> None: +def test_high_risk_write_non_person_needs_an_opt_in() -> None: allowed = {c: (ApproverKind.PERSON,) for c in StepClass} - allowed[StepClass.CLINICAL_WRITE] = (ApproverKind.PERSON, ApproverKind.AGENT) + allowed[StepClass.HIGH_RISK_WRITE] = (ApproverKind.PERSON, ApproverKind.AGENT) with pytest.raises(ValidationError): ApproverPolicyV1(allowed=allowed) - policy = ApproverPolicyV1(allowed=allowed, clinical_write_opt_in_sha256=DIGEST) - assert policy.permits(StepClass.CLINICAL_WRITE, AGENT) + policy = ApproverPolicyV1(allowed=allowed, high_risk_write_opt_in_sha256=DIGEST) + assert policy.permits(StepClass.HIGH_RISK_WRITE, AGENT) + + +def test_legacy_clinical_write_wire_aliases_remain_compatible() -> None: + # Legacy serialized v1 policy using clinical_write / clinical_write_opt_in_sha256 + legacy_payload = { + "schema_version": "openadapt.approver-policy/v1", + "allowed": { + "read_only": ["person"], + "reversible": ["person"], + "consequential": ["person"], + "irreversible": ["person"], + "clinical_write": ["person", "agent"], + }, + "clinical_write_opt_in_sha256": DIGEST, + } + policy = ApproverPolicyV1.model_validate(legacy_payload) + assert policy.high_risk_write_opt_in_sha256 == DIGEST + assert policy.clinical_write_opt_in_sha256 == DIGEST + assert policy.model_dump(mode="json") == legacy_payload + assert StepClass.CLINICAL_WRITE is StepClass.HIGH_RISK_WRITE + assert StepClass("clinical_write") is StepClass.HIGH_RISK_WRITE + assert StepClass("high_risk_write") is StepClass.HIGH_RISK_WRITE + assert ( + ApproverPolicyRefusal("clinical_write_needs_opt_in") + is ApproverPolicyRefusal.HIGH_RISK_WRITE_NEEDS_OPT_IN + ) + assert ( + ApproverPolicyRefusal("high_risk_write_needs_opt_in") + is ApproverPolicyRefusal.HIGH_RISK_WRITE_NEEDS_OPT_IN + ) + assert policy.permits(StepClass.HIGH_RISK_WRITE, AGENT) + + # Domain-neutral input normalizes to identical canonical v1 wire bytes + neutral_payload = { + "schema_version": "openadapt.approver-policy/v1", + "allowed": { + "read_only": ["person"], + "reversible": ["person"], + "consequential": ["person"], + "irreversible": ["person"], + "high_risk_write": ["person", "agent"], + }, + "high_risk_write_opt_in_sha256": DIGEST, + } + neutral_policy = ApproverPolicyV1.model_validate(neutral_payload) + assert neutral_policy.model_dump(mode="json") == legacy_payload + + # Both v1 and domain-neutral approval records round-trip to canonical v1 wire bytes + for step_class_value in ("clinical_write", "high_risk_write"): + record = ApprovalRecordV1.model_validate( + { + "workflow_id": "wf-1", + "step_id": "step_1", + "step_class": step_class_value, + "mode": "each_item", + "decision": "approved", + "approver": PERSON.model_dump(mode="json"), + "route": "desktop_run_it", + "request_sha256": DIGEST, + "decided_at": "2026-10-01T12:00:00Z", + } + ) + assert record.step_class is StepClass.HIGH_RISK_WRITE + assert record.model_dump(mode="json")["step_class"] == "clinical_write" + + # Conflicting canonical and legacy fields are refused + with pytest.raises(ValidationError): + ApproverPolicyV1.model_validate( + { + **legacy_payload, + "high_risk_write_opt_in_sha256": "sha256:" + "1" * 64, + } + ) def test_policy_must_name_every_step_class() -> None: diff --git a/packages/types/tests/test_managed_job.py b/packages/types/tests/test_managed_job.py new file mode 100644 index 0000000000..290d5aefe5 --- /dev/null +++ b/packages/types/tests/test_managed_job.py @@ -0,0 +1,306 @@ +"""Invariants for the domain-neutral managed inbox, outbox, and MCP contracts.""" + +from __future__ import annotations + +import json +from importlib.resources import files + +import pytest +from pydantic import ValidationError + +from openadapt_types.managed_job import ( + MANAGED_INBOX_SCHEMA, + MANAGED_MCP_TOOL_CATALOG, + MANAGED_MCP_TOOL_NAMES, + MANAGED_OUTBOX_SCHEMA, + MANAGED_TOOL_RESULT_SCHEMA, + ManagedActuationDecisionV1, + ManagedActuationHeld, + ManagedBoundToolCallV1, + ManagedInboxV1, + ManagedMcpToolCatalogV1, + ManagedMcpToolNameV1, + ManagedOutboxActionV1, + ManagedOutboxV1, + ManagedToolResultV1, + ManagedToolStatusV1, + ManagedToolUnknown, + bind_managed_tool_call, + bind_managed_tool_result, + decide_managed_actuation, + is_managed_verified_success, + managed_mcp_tool_spec, + managed_planner_status, + managed_planner_visible_payload, + parse_managed_inbox, + require_managed_actuation_dispatch, +) + + +def _inbox_fields(**updates: object) -> dict[str, object]: + fields: dict[str, object] = { + "subject_token": "tok_aaaaaaaa", + "artifact_path": "intake/job_001.pdf", + "source": "intake", + "recorded_at": "2026-09-01T12:00:00Z", + } + fields.update(updates) + return fields + + +def _outbox_fields(**updates: object) -> dict[str, object]: + fields: dict[str, object] = { + "action": "attach_artifact", + "template": "tmpl_attach01", + "needs_human": False, + } + fields.update(updates) + return fields + + +def _unconstrained_string_paths(schema: dict[str, object]) -> list[str]: + unconstrained: list[str] = [] + + def visit(node: object, path: str) -> None: + if isinstance(node, dict): + if node.get("type") == "string" and not ( + {"pattern", "const", "enum"} & set(node) + ): + unconstrained.append(path) + for key, value in node.items(): + visit(value, f"{path}/{key}") + elif isinstance(node, list): + for index, value in enumerate(node): + visit(value, f"{path}/{index}") + + visit(schema, "") + return unconstrained + + +def test_inbox_rejects_missing_subject_token() -> None: + payload = _inbox_fields() + del payload["subject_token"] + with pytest.raises(ValidationError, match="subject_token"): + parse_managed_inbox(payload) + + +def test_inbox_rejects_name_or_other_extra_fields() -> None: + inbox = ManagedInboxV1.model_validate(_inbox_fields()) + assert inbox.schema_version == MANAGED_INBOX_SCHEMA + payload = inbox.model_dump(mode="json") + for field, value in { + "name": "Jane Doe", + "account_number": "0093211", + "screenshot": "data:image/png;base64,secret", + "ocr": "raw document text", + }.items(): + with pytest.raises(ValidationError, match="Extra inputs are not permitted"): + ManagedInboxV1.model_validate({**payload, field: value}) + + +@pytest.mark.parametrize( + "token", + ["Jane Doe", "record jd", "jd", "tok", ""], +) +def test_inbox_rejects_name_shaped_subject_token(token: str) -> None: + with pytest.raises(ValidationError): + parse_managed_inbox(_inbox_fields(subject_token=token)) + + +@pytest.mark.parametrize( + "path", + [ + "/Users/jane/doc.pdf", + "../secret.pdf", + "C:\\Users\\Jane\\doc.pdf", + "Jane Doe doc.pdf", + "", + ], +) +def test_inbox_rejects_unsafe_artifact_path(path: str) -> None: + with pytest.raises(ValidationError): + parse_managed_inbox(_inbox_fields(artifact_path=path)) + + +def test_outbox_with_needs_human_refuses_dispatch() -> None: + outbox = ManagedOutboxV1.model_validate( + _outbox_fields(needs_human=True, schema_version=MANAGED_OUTBOX_SCHEMA) + ) + assert decide_managed_actuation(outbox) is ManagedActuationDecisionV1.HOLD_FOR_HUMAN + with pytest.raises(ManagedActuationHeld): + require_managed_actuation_dispatch(outbox) + with pytest.raises(ManagedActuationHeld): + bind_managed_tool_call( + ManagedMcpToolNameV1.RUN_ATTACH_ARTIFACT, + _inbox_fields(), + _outbox_fields(needs_human=True), + ) + + +def test_catalog_exposes_exactly_three_domain_neutral_tools() -> None: + assert tuple(spec.name for spec in MANAGED_MCP_TOOL_CATALOG.tools) == ( + ManagedMcpToolNameV1.RUN_COLLECT, + ManagedMcpToolNameV1.RUN_ATTACH_ARTIFACT, + ManagedMcpToolNameV1.RUN_CREATE_TASK, + ) + assert tuple(MANAGED_MCP_TOOL_NAMES) == ( + ManagedMcpToolNameV1.RUN_COLLECT, + ManagedMcpToolNameV1.RUN_ATTACH_ARTIFACT, + ManagedMcpToolNameV1.RUN_CREATE_TASK, + ) + with pytest.raises(ManagedToolUnknown): + managed_mcp_tool_spec("run_arbitrary") + + +def test_bind_call_and_result_preserve_subject_token_and_status_semantics() -> None: + call = bind_managed_tool_call( + ManagedMcpToolNameV1.RUN_CREATE_TASK, + _inbox_fields(), + _outbox_fields(action=ManagedOutboxActionV1.CREATE_TASK.value), + ) + assert isinstance(call, ManagedBoundToolCallV1) + + verified = bind_managed_tool_result(call, ManagedToolStatusV1.VERIFIED) + assert verified.schema_version == MANAGED_TOOL_RESULT_SCHEMA + assert verified.subject_token == "tok_aaaaaaaa" + assert verified.ok is True + assert is_managed_verified_success(verified) is True + assert managed_planner_status(verified) is ManagedToolStatusV1.VERIFIED + assert managed_planner_visible_payload(verified) == { + "tool": "run_create_task", + "status": "VERIFIED", + "subject_token": "tok_aaaaaaaa", + "ok": True, + } + + for non_success in ( + ManagedToolStatusV1.HALTED, + ManagedToolStatusV1.RECONCILIATION_REQUIRED, + ): + result = bind_managed_tool_result(call, non_success) + assert result.ok is False + assert is_managed_verified_success(result) is False + assert managed_planner_status(result) is non_success + assert managed_planner_visible_payload(result)["ok"] is False + + +@pytest.mark.parametrize( + ("model", "filename", "schema_version"), + [ + (ManagedInboxV1, "managed-inbox-v1.json", MANAGED_INBOX_SCHEMA), + (ManagedOutboxV1, "managed-outbox-v1.json", MANAGED_OUTBOX_SCHEMA), + ( + ManagedToolResultV1, + "managed-tool-result-v1.json", + MANAGED_TOOL_RESULT_SCHEMA, + ), + ( + ManagedMcpToolCatalogV1, + "managed-mcp-tools-v1.json", + "openadapt.managed-mcp-tools/v1", + ), + ], +) +def test_exported_schemas_match_models_and_forbid_unconstrained_strings( + model: type, + filename: str, + schema_version: str, +) -> None: + shipped = json.loads( + files("openadapt_types.schemas").joinpath(filename).read_text(encoding="utf-8") + ) + assert shipped == model.model_json_schema() + assert shipped["properties"]["schema_version"]["const"] == schema_version + assert _unconstrained_string_paths(shipped) == [] + + +def test_catalog_schema_and_model_reject_invalid_tool_combinations() -> None: + shipped = json.loads( + files("openadapt_types.schemas") + .joinpath("managed-mcp-tools-v1.json") + .read_text(encoding="utf-8") + ) + prefix_items = shipped["properties"]["tools"]["prefixItems"] + assert len(prefix_items) == 3 + defs = shipped["$defs"] + expected = [ + ("run_collect", "collect", False), + ("run_attach_artifact", "attach_artifact", True), + ("run_create_task", "create_task", True), + ] + for item, (name, action, requires_outbox) in zip( + prefix_items, expected, strict=True + ): + ref_name = item["$ref"].rsplit("/", 1)[-1] + spec_schema = defs[ref_name] + assert spec_schema["properties"]["name"]["const"] == name + assert spec_schema["properties"]["action"]["const"] == action + assert spec_schema["properties"]["requires_outbox"]["const"] is requires_outbox + assert {"name", "action", "requires_outbox"} <= set(spec_schema["required"]) + + valid_tools = MANAGED_MCP_TOOL_CATALOG.model_dump(mode="json")["tools"] + invalid_catalogs = [ + # Repeated tool name in slot 1 + { + "schema_version": "openadapt.managed-mcp-tools/v1", + "tools": [valid_tools[0], valid_tools[0], valid_tools[2]], + }, + # Wrong requires_outbox on run_collect + { + "schema_version": "openadapt.managed-mcp-tools/v1", + "tools": [ + {**valid_tools[0], "requires_outbox": True}, + valid_tools[1], + valid_tools[2], + ], + }, + # Mismatched action for run_attach_artifact + { + "schema_version": "openadapt.managed-mcp-tools/v1", + "tools": [ + valid_tools[0], + {**valid_tools[1], "action": "create_task"}, + valid_tools[2], + ], + }, + # Missing required fields in slot 0 + { + "schema_version": "openadapt.managed-mcp-tools/v1", + "tools": [{}, valid_tools[1], valid_tools[2]], + }, + # Non-boolean numeric 0 for run_collect.requires_outbox (rejected by StrictBool and JSON Schema) + { + "schema_version": "openadapt.managed-mcp-tools/v1", + "tools": [ + {**valid_tools[0], "requires_outbox": 0}, + valid_tools[1], + valid_tools[2], + ], + }, + # Non-boolean numeric 1 for run_attach_artifact.requires_outbox (rejected by StrictBool and JSON Schema) + { + "schema_version": "openadapt.managed-mcp-tools/v1", + "tools": [ + valid_tools[0], + {**valid_tools[1], "requires_outbox": 1}, + valid_tools[2], + ], + }, + ] + for bad in invalid_catalogs: + with pytest.raises(ValidationError): + ManagedMcpToolCatalogV1.model_validate(bad) + # Verify the same fixture violates the published JSON Schema constraints + slot_mismatches = 0 + for tool_obj, (name, action, requires_outbox) in zip( + bad["tools"], expected, strict=True + ): + raw_outbox = tool_obj.get("requires_outbox") + if ( + tool_obj.get("name") != name + or tool_obj.get("action") != action + or type(raw_outbox) is not bool + or raw_outbox is not requires_outbox + ): + slot_mismatches += 1 + assert slot_mismatches > 0 diff --git a/packages/types/tests/test_plain_outcome.py b/packages/types/tests/test_plain_outcome.py index 84081fbdaf..f156869084 100644 --- a/packages/types/tests/test_plain_outcome.py +++ b/packages/types/tests/test_plain_outcome.py @@ -28,7 +28,6 @@ import openadapt_types from openadapt_types import ( CONTROL_OVERLAY_TERMINAL_PHASES, - ClinicToolStatusV1, ControlOverlayPhase, EffectStrengthV1, ExecuteEvidenceContractV1, @@ -37,8 +36,10 @@ ExecuteStatusV1, ExecuteTerminalOutcomeV1, ExecuteWebhookEventTypeV1, + ManagedToolStatusV1, OutcomeSourceV1, PlainOutcomeInProgress, + PlainOutcomeInputsV1, PlainOutcomeV1, PlainProgressV1, PlainProofV1, @@ -77,7 +78,7 @@ def test_sources_match_the_table_in_precedence_order() -> None: [ (ExecuteTerminalOutcomeV1, "execute_terminal_outcome"), (ExecuteLifecycleStateV1, "execute_state"), - (ClinicToolStatusV1, "clinic_tool_status"), + (ManagedToolStatusV1, "clinic_tool_status"), (ControlOverlayPhase, "overlay_phase"), ], ) @@ -92,9 +93,9 @@ def test_every_value_of_this_packages_enums_is_mapped(enum_cls: type, source: st [ "openadapt_types.execute:ExecuteTerminalOutcomeV1=execute_terminal_outcome", "openadapt_types.execute:ExecuteLifecycleStateV1=execute_state", - "openadapt_types.clinic_job:ClinicToolStatusV1=clinic_tool_status", + "openadapt_types.managed_job:ManagedToolStatusV1=clinic_tool_status", "openadapt_types.execute:ExecuteStatusV1.terminal_outcome=execute_terminal_outcome", - "openadapt_types.clinic_job:ClinicToolResultV1.status=clinic_tool_status", + "openadapt_types.managed_job:ManagedToolResultV1.status=clinic_tool_status", "openadapt_types.control_overlay:ControlOverlayPhase=overlay_phase", "openadapt_types.control_overlay:ControlOverlayFrameV1.phase=overlay_phase", "openadapt_types.control_overlay_tracking:ControlOverlayFrameV2.phase=overlay_phase", @@ -324,7 +325,7 @@ def test_precise_and_coarse_combinations_keep_the_safety_rule() -> None: def test_coarse_status_combinations_keep_the_safety_rule() -> None: - for agent, connector, clinic, program in itertools.product( + for agent, connector, managed, program in itertools.product( _value_choices("agent_status"), _value_choices("connector_status"), _value_choices("clinic_tool_status"), @@ -334,7 +335,7 @@ def test_coarse_status_combinations_keep_the_safety_rule() -> None: inputs = { "agent_status": agent, "connector_status": connector, - "clinic_tool_status": clinic, + "managed_tool_status": managed, "program_terminal_state": program, "dispatched": dispatched, "delivery_uncertain": uncertain, @@ -346,6 +347,7 @@ def test_a_coarse_halt_never_reads_as_stopped_before_saving() -> None: for status in ("HALTED",): for result in ( plain_outcome(execution_outcome=status), + plain_outcome(managed_tool_status=status), plain_outcome(clinic_tool_status=status), plain_outcome(agent_status="halt"), plain_outcome(connector_status="halt"), @@ -356,6 +358,44 @@ def test_a_coarse_halt_never_reads_as_stopped_before_saving() -> None: assert "nothing was written" not in result.next_action.lower() +def test_legacy_clinic_tool_status_compat_alias() -> None: + outcome_from_managed = plain_outcome(managed_tool_status="HALTED") + outcome_from_legacy = plain_outcome(clinic_tool_status="HALTED") + assert outcome_from_managed == outcome_from_legacy + assert outcome_from_managed.result is PlainResultV1.CHECK_THE_RECORD + assert outcome_from_managed.technical_code == "clinic_tool_status=HALTED" + assert outcome_from_managed.exact.managed_tool_status == "HALTED" + assert outcome_from_managed.exact.clinic_tool_status == "HALTED" + + # Saved v1 outcome round-trips without adding unknown fields to v1 exact + dumped = outcome_from_legacy.model_dump(mode="json") + assert "managed_tool_status" not in dumped["exact"] + assert dumped["exact"]["clinic_tool_status"] == "HALTED" + assert PlainOutcomeV1.model_validate(dumped).model_dump(mode="json") == dumped + + # Domain-neutral PlainOutcomeInputsV1 input normalizes onto canonical v1 field + parsed_inputs = PlainOutcomeInputsV1.model_validate( + {"managed_tool_status": "VERIFIED"} + ) + assert parsed_inputs.managed_tool_status == "VERIFIED" + assert parsed_inputs.clinic_tool_status == "VERIFIED" + assert "managed_tool_status" not in parsed_inputs.model_dump(mode="json") + + # Conflicting managed_tool_status and clinic_tool_status must fail closed + with pytest.raises(ValueError, match="conflicting"): + plain_outcome( + managed_tool_status="VERIFIED", + clinic_tool_status="RECONCILIATION_REQUIRED", + ) + with pytest.raises(ValidationError, match="conflicting"): + PlainOutcomeInputsV1.model_validate( + { + "managed_tool_status": "VERIFIED", + "clinic_tool_status": "RECONCILIATION_REQUIRED", + } + ) + + def test_coarse_and_overlay_combinations_keep_the_safety_rule() -> None: for coarse, overlay, agent in itertools.product( _value_choices("execution_outcome"), diff --git a/packages/types/tests/test_readme_claims.py b/packages/types/tests/test_readme_claims.py index 2445de9545..d52360f9e1 100644 --- a/packages/types/tests/test_readme_claims.py +++ b/packages/types/tests/test_readme_claims.py @@ -80,6 +80,11 @@ "forty-three", "forty-four", "forty-five", + "forty-six", + "forty-seven", + "forty-eight", + "forty-nine", + "fifty", ) # Tied to the sentence itself, so an unrelated "N files" elsewhere in the