diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 462d157c9d..86358dbced 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -198,6 +198,11 @@ improvising or retrying when something is off. | Learn the record check from the recording, when the person looks the record up after saving | Released ([#1290](https://github.com/OpenAdaptAI/OpenAdapt/pull/1290)) | Synthetic | `record --verify` | | A record check's duplicate key can be several fields together, such as last name, first name and birth date: the check fails when more than one record carries all of them, counting records that were already there | Released ([#1393](https://github.com/OpenAdaptAI/OpenAdapt/issues/1393)) | Synthetic (OpenEMR-shaped patient rows) | verify.yaml `record.duplicate_key: [lname, fname, DOB]`, `confirm_params(idempotency_key=[...])`, `Effect.composite_key` | | Checked later: a save confirmed by a later report or acknowledgment, never counted as done until then | Released ([#1297](https://github.com/OpenAdaptAI/OpenAdapt/pull/1297)) | Synthetic | `SAVED_AWAITING_CHECK` | +| Counterparty confirmations for payer claims: each claim with a deferred check is a handoff, and the payer's 999 or 277CA moves it to `acknowledged` (received or accepted, status only) or back to `sent` with a reason (rejected, no answer by the deadline, two claims on one key). The deferred check settles exactly as before | In a pull request | Synthetic (X12 999 and 277CA fixtures, unit tests) | `deferred settle`, `openadapt_flow/handoffs/payer.py`, [COUNTERPARTY_CONFIRMATIONS.md](packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md) | +| Counterparty confirmations by read-back: the sender records what it sent (as digests), then reads the other party's system by a profile (data) and reports `recorded_as_intended`, `recorded_differently` with the differing field ids, or `sent` with a reason (not found, matched twice, unreachable). One comparator for every producer | In a pull request | Real app: a second, synthetic OpenEMR 7.0.3 as the receiving clinic, written through its REST API and read back through FHIR with a read-only token; 180 of 180 runs as expected over 9 cases, 0 false alarms in 40 correctly recorded referrals, [results](packages/flow/benchmark/handoff_receiver/results/2026-11-21.json) | `openadapt_flow/handoffs/`, [COUNTERPARTY_CONFIRMATIONS.md](packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md) | +| Open handoffs by state, with who still needs to follow up | In a pull request | Unit tests | `openadapt handoff list` | +| Receipts carry the run's handoffs as counterparty confirmation lines (`predicate.confirmations[]` in `record/run/v1`), written by the after-run receipt hook | In a pull request | Unit tests, and a real replayer run whose receipt carries its claim's `sent` line and verifies | `openadapt_flow/handoffs/line.py`, `receipt_record.py` | +| Follow-up receipts: each later change in a handoff's state is a separately signed `record/run/v1` record naming the original receipt (`follows`), and the chain verifies in order (`verify_chain`) | In a pull request | Unit tests: a three-record chain verifies; wrong original, out of sequence, changed fields and empty updates are refused | `openadapt handoff list --run RUN --sign-updates`, `openadapt_flow/handoffs/followup.py` | | Keep the server's own answer to a save as lower-level evidence on the receipt | Released ([#1298](https://github.com/OpenAdaptAI/OpenAdapt/pull/1298)) | Synthetic | receipts | | A ledger of what changed before a stop, a write-ordering lint, and undo steps a person approves | Released ([#1263](https://github.com/OpenAdaptAI/OpenAdapt/pull/1263)) | Synthetic (MockMed) | change ledger | | Propose an undo for each saving step (another recording, captured traffic, or the old value), keep it only if a test copy shows every record restored, and offer it after a stop once a person approves it | Released ([#1346](https://github.com/OpenAdaptAI/OpenAdapt/pull/1346)) | Synthetic (MockMed, MockLoan, live browser) | `openadapt-flow undo propose`, `undo accept`; [AFTER_A_STOP.md](packages/flow/docs/AFTER_A_STOP.md) | diff --git a/llms-full.txt b/llms-full.txt index 5d3446e884..754d0beb3b 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -658,6 +658,11 @@ improvising or retrying when something is off. | Learn the record check from the recording, when the person looks the record up after saving | Released ([#1290](https://github.com/OpenAdaptAI/OpenAdapt/pull/1290)) | Synthetic | `record --verify` | | A record check's duplicate key can be several fields together, such as last name, first name and birth date: the check fails when more than one record carries all of them, counting records that were already there | Released ([#1393](https://github.com/OpenAdaptAI/OpenAdapt/issues/1393)) | Synthetic (OpenEMR-shaped patient rows) | verify.yaml `record.duplicate_key: [lname, fname, DOB]`, `confirm_params(idempotency_key=[...])`, `Effect.composite_key` | | Checked later: a save confirmed by a later report or acknowledgment, never counted as done until then | Released ([#1297](https://github.com/OpenAdaptAI/OpenAdapt/pull/1297)) | Synthetic | `SAVED_AWAITING_CHECK` | +| Counterparty confirmations for payer claims: each claim with a deferred check is a handoff, and the payer's 999 or 277CA moves it to `acknowledged` (received or accepted, status only) or back to `sent` with a reason (rejected, no answer by the deadline, two claims on one key). The deferred check settles exactly as before | In a pull request | Synthetic (X12 999 and 277CA fixtures, unit tests) | `deferred settle`, `openadapt_flow/handoffs/payer.py`, [COUNTERPARTY_CONFIRMATIONS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md) | +| Counterparty confirmations by read-back: the sender records what it sent (as digests), then reads the other party's system by a profile (data) and reports `recorded_as_intended`, `recorded_differently` with the differing field ids, or `sent` with a reason (not found, matched twice, unreachable). One comparator for every producer | In a pull request | Real app: a second, synthetic OpenEMR 7.0.3 as the receiving clinic, written through its REST API and read back through FHIR with a read-only token; 180 of 180 runs as expected over 9 cases, 0 false alarms in 40 correctly recorded referrals, [results](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/handoff_receiver/results/2026-11-21.json) | `openadapt_flow/handoffs/`, [COUNTERPARTY_CONFIRMATIONS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md) | +| Open handoffs by state, with who still needs to follow up | In a pull request | Unit tests | `openadapt handoff list` | +| Receipts carry the run's handoffs as counterparty confirmation lines (`predicate.confirmations[]` in `record/run/v1`), written by the after-run receipt hook | In a pull request | Unit tests, and a real replayer run whose receipt carries its claim's `sent` line and verifies | `openadapt_flow/handoffs/line.py`, `receipt_record.py` | +| Follow-up receipts: each later change in a handoff's state is a separately signed `record/run/v1` record naming the original receipt (`follows`), and the chain verifies in order (`verify_chain`) | In a pull request | Unit tests: a three-record chain verifies; wrong original, out of sequence, changed fields and empty updates are refused | `openadapt handoff list --run RUN --sign-updates`, `openadapt_flow/handoffs/followup.py` | | Keep the server's own answer to a save as lower-level evidence on the receipt | Released ([#1298](https://github.com/OpenAdaptAI/OpenAdapt/pull/1298)) | Synthetic | receipts | | A ledger of what changed before a stop, a write-ordering lint, and undo steps a person approves | Released ([#1263](https://github.com/OpenAdaptAI/OpenAdapt/pull/1263)) | Synthetic (MockMed) | change ledger | | Propose an undo for each saving step (another recording, captured traffic, or the old value), keep it only if a test copy shows every record restored, and offer it after a stop once a person approves it | Released ([#1346](https://github.com/OpenAdaptAI/OpenAdapt/pull/1346)) | Synthetic (MockMed, MockLoan, live browser) | `openadapt-flow undo propose`, `undo accept`; [AFTER_A_STOP.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/AFTER_A_STOP.md) | diff --git a/openadapt/cli.py b/openadapt/cli.py index 43ebabfe24..ecfc787933 100644 --- a/openadapt/cli.py +++ b/openadapt/cli.py @@ -1630,6 +1630,10 @@ def flow(command_ctx: click.Context) -> None: ("record", "Record a workflow. Uses the same options as flow record."), ("compile", "Compile a recording. Uses the same options as flow compile."), ("run", "Run a bundle with its checks. Uses the same options as flow run."), + ( + "handoff", + "Handoffs to other parties: what they recorded, and who follows up.", + ), ): main.add_command( _FlowAliasCommand( diff --git a/openadapt/receipt_verify.py b/openadapt/receipt_verify.py index 1c2c52d725..ba2d145dde 100644 --- a/openadapt/receipt_verify.py +++ b/openadapt/receipt_verify.py @@ -56,6 +56,8 @@ def _describe(result: Any, say: Say, indent: str = " ") -> None: statement = result.statement or {} predicate = statement.get("predicate", {}) reason = predicate.get("reason_code") + if reason == "awaiting_counterparty": + say(f"{indent}Awaiting counterparty confirmation: sent, not yet confirmed.") say( f"{indent}Outcome: {result.outcome}" + (f" ({reason})" if reason else "") diff --git a/openadapt/seal_view/viewer.html b/openadapt/seal_view/viewer.html index 1685a14681..2a5dbd0ce5 100644 --- a/openadapt/seal_view/viewer.html +++ b/openadapt/seal_view/viewer.html @@ -36,7 +36,7 @@ B4nOvzAKBggqhkjOPQQDAwNpADBmAjEAwGEGrfGZR1cen1R8/DTVMI943LssZmJR tDp/i7SfGHmGRP6gRbuj9vOK3b67Z0QQAjEAuT2H673LQEaHTcyQSZrkp4mX7Wwk mF+sVbkYY5mXN+RMH13KUEHHOqASaemYWK/E ------END CERTIFICATE-----`,Md="openadapt.record-timestamp/v1",Ne={signedData:"1.2.840.113549.1.7.2",tstInfo:"1.2.840.113549.1.9.16.1.4",contentType:"1.2.840.113549.1.9.3",messageDigest:"1.2.840.113549.1.9.4",sha256:"2.16.840.1.101.3.4.2.1",sha384:"2.16.840.1.101.3.4.2.2",sha512:"2.16.840.1.101.3.4.2.3",ecdsaSha256:"1.2.840.10045.4.3.2",ecdsaSha384:"1.2.840.10045.4.3.3",ecdsaSha512:"1.2.840.10045.4.3.4",ecPublicKey:"1.2.840.10045.2.1",p256:"1.2.840.10045.3.1.7",p384:"1.3.132.0.34",extKeyUsage:"2.5.29.37",timeStamping:"1.3.6.1.5.5.7.3.8"},Ls={[Ne.sha256]:"SHA-256",[Ne.sha384]:"SHA-384",[Ne.sha512]:"SHA-512"},Rd={[Ne.ecdsaSha256]:"SHA-256",[Ne.ecdsaSha384]:"SHA-384",[Ne.ecdsaSha512]:"SHA-512"},Id={[Ne.p256]:["P-256",32],[Ne.p384]:["P-384",48]},eo=class extends Error{},qe=e=>{throw new eo(e)};function Gt(e,t){t+2>e.length&&qe("truncated");let n=e[t];(n&31)===31&&qe("long tag");let o=e[t+1],r=t+2;if(o&128){let i=o&127;(i===0||i>4)&&qe("length"),o=0;for(let l=0;le.length&&qe("truncated"),{tag:n,start:r,end:a,bytes:e,raw:e.subarray(t,a),content:e.subarray(r,a)}}function se(e){let t=[],n=e.start;for(;ne&&e.tag===t?e:qe(`tag ${t}`);function Be(e){ve(e,6);let t=e.content,n=[Math.floor(t[0]/40),t[0]%40],o=0;for(let r=1;rnew TextDecoder().decode(e.content);function ir(e){let t=Cd(e),n=e.tag===24?/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\.\d+)?Z$/.exec(t):e.tag===23?/^(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)()Z$/.exec(t):null;n||qe("time");let o=e.tag===23?(Number(n[1])<50?2e3:1900)+Number(n[1]):Number(n[1]);return`${String(o).padStart(4,"0")}-${n[2]}-${n[3]}T${n[4]}:${n[5]}:${n[6]}${n[7]||""}Z`}var Pd=e=>Array.from(e,t=>t.toString(16).padStart(2,"0")).join(""),sr=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]);function Od(e){let t=String(e).replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=atob(t);return Uint8Array.from(n,o=>o.charCodeAt(0))}function Hs(e){let[t,n,o]=se(ve(e,48)),r=se(ve(t,48)),a=r[0].tag===160?1:0,i=r[a+2],l=se(r[a+3]),d=r[a+4],c=ve(r[a+5],48),[g]=se(c),[h,p]=se(g),u=!1;for(let f of r.slice(a+6))if(f.tag===163)for(let v of se(se(f)[0])){let m=se(v);if(Be(m[0])!==Ne.extKeyUsage)continue;u=se(Gt(m.at(-1).content,0)).some(y=>Be(y)===Ne.timeStamping)}return{tbs:t.raw,sigAlg:Be(se(n)[0]),signature:ve(o,3).content.subarray(1),issuer:i.raw,subject:d.raw,notBefore:ir(l[0]),notAfter:ir(l[1]),spki:c.raw,keyAlg:Be(h),curve:p&&p.tag===6?Be(p):null,timestamping:u,serial:r[a].content}}function zd(e,t){let[n,o]=se(ve(Gt(e,0),48)),r=i=>{let l=i.content;for(;l.length>t&&l[0]===0;)l=l.subarray(1);l.length>t&&qe("signature");let d=new Uint8Array(t);return d.set(l,t-l.length),d},a=new Uint8Array(t*2);return a.set(r(n),0),a.set(r(o),t),a}async function Ds(e,t,n,o){let r=Rd[t],a=Id[e.curve];(!r||!a||e.keyAlg!==Ne.ecPublicKey)&&qe("algorithm");let i=globalThis.crypto.subtle,l=await i.importKey("spki",e.spki,{name:"ECDSA",namedCurve:a[0]},!1,["verify"]);return i.verify({name:"ECDSA",hash:r},l,zd(n,a[1]),o)}function Ld(e){let t=se(ve(Gt(e,0),48));Be(t[0])!==Ne.signedData&&qe("not signed data");let n=se(ve(se(ve(t[1],160))[0],48)),o=se(ve(n[2],48));Be(o[0])!==Ne.tstInfo&&qe("not a timestamp");let r=ve(se(ve(o[1],160))[0],4).content,a=3,i=[];if(n[a]&&n[a].tag===160){for(let w of se(n[a]))i.push(Hs(w));a+=1}n[a]&&n[a].tag===161&&(a+=1);let l=se(ve(n[a],49));l.length!==1&&qe("signers");let d=se(ve(l[0],48)),c=d[1],g=Be(se(d[2])[0]),h=ve(d[3],160),p=Be(se(d[4])[0]),u=ve(d[5],4).content,f={};for(let w of se(h)){let[N,M]=se(w);f[Be(N)]=se(M)[0]}let v=se(ve(Gt(r,0),48)),[m,b]=se(ve(v[2],48)),y=c.tag===48?se(c)[1].content:null,_=Uint8Array.from(h.raw);return _[0]=49,{eContent:r,certs:i,signerSerial:y,digestAlg:g,sigAlg:p,signature:u,signedBytes:_,contentType:f[Ne.contentType]?Be(f[Ne.contentType]):null,messageDigest:f[Ne.messageDigest]?ve(f[Ne.messageDigest],4).content:null,policy:Be(v[1]),imprintAlg:Be(se(m)[0]),imprint:Pd(ve(b,4).content),genTime:ir(v[4])}}async function Dd(e,t=Ad){let n;try{n=Ld(e)}catch{return{ok:!1,reason:"tsa_malformed"}}let o={genTime:n.genTime,imprint:n.imprint,imprintAlg:Ls[n.imprintAlg]||n.imprintAlg},r=(a,i)=>({ok:a,reason:i,...o});try{let a=Ls[n.digestAlg];if(!a||n.contentType!==Ne.tstInfo||!n.messageDigest)return r(!1,"tsa_content_mismatch");let i=new Uint8Array(await globalThis.crypto.subtle.digest(a,n.eContent));if(!sr(i,n.messageDigest))return r(!1,"tsa_content_mismatch");let l=Hs(Gt(Od(t),0)),d=n.certs.find(g=>n.signerSerial&&sr(g.serial,n.signerSerial))||(n.certs.length===1?n.certs[0]:null);if(!d)return r(!1,"tsa_untrusted");if(!await Ds(d,n.sigAlg,n.signature,n.signedBytes))return r(!1,"tsa_bad_signature");if(!sr(d.issuer,l.subject)||!await Ds(l,d.sigAlg,d.signature,d.tbs))return r(!1,"tsa_untrusted");if(!d.timestamping)return r(!1,"tsa_not_timestamping");let c=Date.parse(n.genTime);for(let g of[d,l])if(!(Date.parse(g.notBefore)<=c&&c<=Date.parse(g.notAfter)))return r(!1,"tsa_expired");return r(!0,null)}catch(a){return r(!1,a instanceof eo?"tsa_malformed":"tsa_bad_signature")}}var Fd=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}\.tsr$/,Fs=/^[a-f0-9]{64}$/;async function Hd(e){return[...new Uint8Array(await crypto.subtle.digest("SHA-256",e))].map(n=>n.toString(16).padStart(2,"0")).join("")}function js(e){if(typeof e!="string"||Xe(e)!==null)return null;let t;try{t=JSON.parse(e)}catch{return null}return!t||typeof t!="object"||Array.isArray(t)||t.schema!==Md||typeof t.tsr_file!="string"||!Fd.test(t.tsr_file)||!Fs.test(t.tsr_sha256)||!Fs.test(t.imprint_sha256)||"token"in t?null:t}async function jd(e,t,n){let o=js(e);if(!o)return{ok:!1,reason:"tsa_malformed"};if(!t||!t.length)return{ok:!1,reason:"tsa_token_missing"};if(await Hd(t)!==o.tsr_sha256)return{ok:!1,reason:"tsa_token_mismatch"};if(o.imprint_sha256!==n)return{ok:!1,reason:"tsa_imprint_mismatch",matches:!1};let r=await Dd(t),a=r.imprintAlg==="SHA-256"&&r.imprint===n;return r.ok&&!a?{...r,ok:!1,reason:"tsa_imprint_mismatch",matches:a}:{...r,matches:a}}async function Gs(e,t,n){let o=js(e);return o?o.seal_sha256!==t?{ok:!1,reason:"tsa_imprint_mismatch",matches:!1}:jd(e,n,t):{ok:!1,reason:"tsa_malformed"}}function Us(e){if(e==null||Xe(e)!==null)return null;try{return JSON.parse(e)}catch{return null}}async function Bs(e,t,{logKeys:n=null}={}){let o=Us(e.sealText),r=null,a=null;if(e.anchorText!=null){let i=Us(e.anchorText),l=o?fn(t).filter(d=>d.key_id===o.key_id&&d.status==="active"):[];if(!o||!i)r={ok:!1,reason:"anchor_malformed"};else if(l.length!==1)r={ok:!1,reason:"anchor_key_mismatch"};else{let d=n||[await Jn(Vn)],c=await Xn(o,i,Ge(l[0].public_key),d);r={...c,entry:c.ok?i.entry:null}}}return e.tsaText!=null&&(a=o?await Gs(e.tsaText,await gn(o),e.tsrBytes??null):{ok:!1,reason:"tsa_malformed"}),{rekor:r,tsa:a}}var Gd="https://rekor.sigstore.dev/api/v1/log/entries",Ks=e=>`https://search.sigstore.dev/?logIndex=${Number(e)}`;async function Ws(e,{fetchImpl:t=globalThis.fetch,timeoutMs:n=6e3}={}){if(!e||!Number.isInteger(e.logIndex)||e.logIndex<0)return"unavailable";let o=typeof AbortController=="function"?new AbortController:null,r=o?setTimeout(()=>o.abort(),n):null;try{let a=await t(`${Gd}?logIndex=${e.logIndex}`,{signal:o?.signal,headers:{accept:"application/json"},credentials:"omit",referrerPolicy:"no-referrer"});if(!a.ok)return"unavailable";let i=await a.json(),l=i&&typeof i=="object"?Object.keys(i):[];if(l.length!==1)return"unavailable";let d=i[l[0]];return String(l[0]).slice(-64)===String(e.uuid).slice(-64)&&d?.body===e.body&&d?.integratedTime===e.integratedTime&&d?.logID===e.logID&&d?.logIndex===e.logIndex?"match":"differs"}catch{return"unavailable"}finally{r&&clearTimeout(r)}}var Vs=[700,1500],Ut={identity:2600,checks:2200,save:1800,readback:650,stop:4200,done:1600};function qs(e){let t=[],n=i=>t.push({i:t.length,readbacks:0,spotlight:null,highlight:!1,...i}),o=!0,r=!0;for(let i of e.steps){if(i.status==="not_reached")break;let l=Math.min(Vs[1],Math.max(Vs[0],((i.t1??0)-(i.t0??0))*.5)),d=e.readbacks.filter(g=>g.step===i.i&&g.result!=="not_reached"),c=d.length>0;if(n({step:i.i,stage:"step",dwell:c?Ut.save:l,spotlight:c?"save":null,highlight:c}),i.identity==="passed"||i.identity==="failed"){let g=o;o=!1,n({step:i.i,stage:"identity",dwell:g?Ut.identity:Math.max(350,Math.round(l*.45)),spotlight:g?"identity":null,highlight:g})}if(i.checks.passed+i.checks.failed>0&&i.status!=="stopped"){let g=r;r=!1,n({step:i.i,stage:"checks",dwell:g?Ut.checks:Math.max(350,Math.round(l*.45)),spotlight:g?"checks":null,highlight:g})}d.forEach((g,h)=>n({step:i.i,stage:"readback",readbacks:h+1,dwell:Ut.readback,spotlight:"save"})),i.status==="stopped"&&n({step:i.i,stage:"stop",dwell:Ut.stop,spotlight:"stop",highlight:!0})}let a=t.at(-1);return a&&a.stage!=="stop"&&n({step:a.step,stage:"done",readbacks:a.readbacks,dwell:Ut.done}),t}var Ud={step:0,identity:1,checks:2,readback:3,stop:3,done:4};function Zs(e,t){if(!e)return null;let n=Ud[e.stage],o=r=>rr<=e.step,identity:r=>o(r)||r===e.step&&n>=1,checks:r=>o(r)||r===e.step&&(n>=2||e.stage==="stop"),readback:r=>{let a=t.readbacks[r];return!a||a.step==null?!1:a.stepe.step?!1:t.readbacks.filter(l=>l.step===a.step).indexOf(a){let n=e.find(o=>o.step===t);return n?n.i:e.length-1};function Ys(e,t){let n=e.filter(r=>r.highlight);return(n.find(r=>r.i>t)||n[0]||e[0]).i}var Bd=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Js(e){let t=new Date(e);if(!e||Number.isNaN(t.getTime()))return null;let n=o=>String(o).padStart(2,"0");return`${t.getUTCDate()} ${Bd[t.getUTCMonth()]} ${t.getUTCFullYear()}, ${n(t.getUTCHours())}:${n(t.getUTCMinutes())} UTC`}function no(e){return typeof e!="string"||!e||/[\\\s]/.test(e)||e.startsWith("//")?null:e.startsWith("https://")?/^https:\/\/[A-Za-z0-9.-]+(?::\d{1,5})?(?:[/?#]|$)/.test(e)?e:null:/^[A-Za-z][A-Za-z0-9+.-]*:/.test(e)?null:/^(?:\/|\.{1,2}\/|[\w.-]+(?:\/|$))/.test(e)?e:null}function Xs(e,t){let n=e.rings.counts;return`${e.rings.anchor?.kind==="stop"?`Stopped: ${e.stopReason||String(e.headline||"").replace(/^[^:]*:\s*/,"")||"before saving"}`:`${e.label} · ${n.readbacksPassed} of ${n.readbacks} read back`}${t?" · signature valid":""}`}dt();var re={section:272,step:238,stepWidth:15,tickIn:205,tickOut:217,tickFailIn:199,tickFailOut:223,dot:176,dotSize:4.6,petal:128,petalWidth:6,core:94},ge=e=>Math.round(e*100)/100;function Ae(e,t){let n=t*Math.PI/180;return[ge(300+e*Math.sin(n)),ge(300-e*Math.cos(n))]}function bn(e,t,n){let[o,r]=Ae(e,t),[a,i]=Ae(e,n),l=n-t>180?1:0;return`M${o} ${r}A${e} ${e} 0 ${l} 1 ${a} ${i}`}function vn(e,t){let n=Math.sin(e*12.9898+t*78.233)*43758.5453;return n-Math.floor(n)}function oo(e,t,n,o){let r=e*Math.PI/180,a=o*(.5+vn(t,n)),i=(vn(t,n+1)-.5)*o*.8;return{bx:ge(Math.sin(r)*a+Math.cos(r)*i),by:ge(-Math.cos(r)*a+Math.sin(r)*i),br:ge((vn(t,n+2)-.5)*16)}}function Qs(e){let n=360/e.steps.length,o=Math.min(1.4,n*.12),r=m=>[m*n+o/2,(m+1)*n-o/2],a=e.steps.map((m,b)=>{let[y,_]=r(b);return{i:b,d:bn(re.step,y,_),hit:bn(re.step,b*n,(b+1)*n),status:m.status,at:ge((y+_)/2/360),t:m.t0,...oo((y+_)/2,b,1,26)}}),i=[];e.steps.forEach((m,b)=>{let y=i.at(-1);y&&y.title===m.section?y.to=b:i.push({title:m.section,from:b,to:b})});let l=i.filter(m=>m.title).map((m,b)=>{let y=m.from*n+o,_=(m.to+1)*n-o,w=(y+_)/2,N=w>90&&w<270,M=Math.max((_-y)/2,40);return{k:b,title:m.title,from:m.from,to:m.to,d:bn(re.section,y,_),text:N?Kd(re.section+9,w-M,w+M):bn(re.section-4,w-M,w+M),mark:[Ae(re.step+12,m.from*n),Ae(re.step+20,m.from*n)],at:ge(y/360)}}),d=[];e.steps.forEach((m,b)=>{let y=e.checks.filter(N=>N.step===b),[_,w]=r(b);y.forEach((N,M)=>{let S=_+(M+1)/(y.length+1)*(w-_),A=N.result!=="passed",[O,I]=Ae(A?re.tickFailIn:re.tickIn,S),[$,C]=Ae(A?re.tickFailOut:re.tickOut,S);d.push({i:d.length,step:b,x1:O,y1:I,x2:$,y2:C,result:N.result,at:ge(S/360),t:N.t,...oo(S,d.length,2,18)})})});let c=e.readbacks.length,g=e.readbacks.map((m,b)=>{let y=b/c*360,[_,w]=Ae(re.dot,y);return{i:b,cx:_,cy:w,result:m.result,label:m.label,at:ge(y/360),t:m.t,...oo(y,b,3,16)}}),h=e.identity.length,p=360/Math.max(1,h),u=Math.min(4,p*.28),f=e.identity.map((m,b)=>{let y=b*p+u/2,_=(b+1)*p-u/2;return{i:b,step:m.step,d:bn(re.petal,y,_),result:m.result,at:ge((y+_)/2/360),t:m.t,...oo((y+_)/2,b,4,12)}}),v=e.stoppedAt==null?null:(()=>{let m=(e.stoppedAt+1)*n,[b,y]=Ae(re.step-24,m),[_,w]=Ae(re.step+18,m);return{x1:b,y1:y,x2:_,y2:w,deg:ge(m),at:ge(m/360)}})();return{steps:a,bands:l,ticks:d,dots:g,petals:f,stop:v,per:n}}function Kd(e,t,n){let[o,r]=Ae(e,n),[a,i]=Ae(e,t),l=n-t>180?1:0;return`M${o} ${r}A${e} ${e} 0 ${l} 0 ${a} ${i}`}function lr(e,{radius:t=100,disorder:n=0}={}){let o=2166136261;for(let l=0;l+1<(e||"").length;l+=2)o^=parseInt(e.slice(l,l+2),16)||0,o=Math.imul(o,16777619)>>>0;let a=Array.from({length:32},()=>{o=o+1831565813>>>0;let l=o;return l=Math.imul(l^l>>>15,l|1),l^=l+Math.imul(l^l>>>7,l|61),((l^l>>>14)>>>0)%256}),i=[];for(let l=0;l<3;l+=1){let d=1+l*8,c=5+a[d]%9,g=a[d+1]/255*Math.PI*2,h=t*(.5+.2*l+a[d+2]/255*.08),p=.16+a[d+3]/255*.24,u=(a[d+4]/255-.5)*.7,f=1.2+a[d+6]/255*.8,v=f*(2.4+a[d+5]/255*1.6),m=_=>{let w=h*(1-p+p*Math.cos(c*_+g)),N=_+u*Math.sin(c*_);return[t+w*Math.cos(N),t+w*Math.sin(N)]},b=[],y=0;for(let _=0;_=N;){let C=1-($-N)/Math.max(1e-9,Math.hypot(I[0]-M[0],I[1]-M[1])),R=M[0]+(I[0]-M[0])*C,k=M[1]+(I[1]-M[1])*C;n&&(R+=(vn(_*97+S,l+11)-.5)*5*n,k+=(vn(_*89+S,l+23)-.5)*5*n),R=ge(R),k=ge(k),w+=`M${ge(R-f)} ${k}a${ge(f)} ${ge(f)} 0 1 0 ${ge(f*2)} 0a${ge(f)} ${ge(f)} 0 1 0 ${ge(-f*2)} 0`,S+=1,$-=N,N=v}N-=$,M=I}y=Math.max(y,S),b.push({d:w,at:ge(_/c)})}i.push({petals:b,count:c,dots:y,dir:(l%2?-1:1)*(a[0]%2?1:-1)})}return i}var F={wrap:"a",svg:"ba",halo:"Z",breathe:"ua",g0:"lo",g1:"go",c0:"co",c1:"fo",layer:"ha",hair:"ka",seal:"y",bandArc:"wa",bandMark:"xo",bandText:"vo",step:"r",bloom:"n",petal:"e",tick:"i",dot:"t",stop:"b",core:"mo",rosette:"u",check:"h",cross:"U",square:"z",hit:"ya",witnessLink:"za",witnessDot:"k",witnessGlyph:"_",witnessPing:"aa",witnessText:"j",witness:"f",witnessWait:"_a",witnessLit:"ja",draw:"oa",bloomIn:"Sa",ghostIn:"ra",tickIn:"Ca",pop:"q",stopIn:"Ma",band:"bo",coreIn:"Ya",sweep:"S",flare:"Fa",tickFlare:"Ra",dotFlare:"Ea",jolt:"Ia",iris:"C",irisIn:"Aa",irisBreathe:"Ha",irisLayer:"ta",irisSpin:"Ua",irisGlow:"qa",irisPulse:"Ba",anchorMark:"x",anchorDot:"Da",playhead:"B",mini:"M"};Lt();Lt();var Vd=0;function s(e,t,n,o,r,a){t||(t={});var i,l,d=t;if("ref"in d)for(l in d={},t)l=="ref"?i=t[l]:d[l]=t[l];var c={type:e,props:d,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Vd,__i:-1,__u:0,__source:r,__self:a};if(typeof e=="function"&&(i=e.defaultProps))for(l in i)d[l]===void 0&&(d[l]=i[l]);return j.vnode&&j.vnode(c),c}var qd=.94;function Zd(e,t){let n={passed:"passed",stopped:"the run stopped here",not_reached:"not reached"}[e.status];return`Step ${e.i+1} of ${t}: ${e.name}, ${n}`}function ro({rings:e,tone:t,digest:n,phase:o="rest",still:r=!1,variant:a="full",buildMs:i=3200,active:l=null,focusIndex:d=0,onActive:c,onPick:g,onKey:h,ringFocus:p=null,witnesses:u=null,lit:f=null,spot:v=null,label:m}){let b=ne(()=>Qs(e),[e]),y=a==="full",_=o==="broken",w=ne(()=>y?lr(n,{radius:100,disorder:_?1:0}):null,[n,_,y]),N=e.anchor,M=!!(f&&N&&f.step===N.step&&["done","stop","readback"].includes(f.stage)),A=`s${st().replace(/[^a-zA-Z0-9]/g,"")}`,O=Math.max(1,e.runMs),I=k=>k==null?0:Math.round(Math.min(k/O,1)*qd*i),$=k=>l!=null&&k===l?"1":void 0,C=k=>f?k?"1":"0":void 0,R=(k,B={})=>({"--d":`${I(k.t)}ms`,"--a":k.at,"--bx":`${k.bx}px`,"--by":`${k.by}px`,"--br":`${k.br}deg`,...B});return s("div",{className:F.wrap,"data-phase":o,"data-tone":t,"data-variant":a,"data-still":r?"1":void 0,"data-focus":l!=null?"1":void 0,"data-ring":p||void 0,"data-spot":v||void 0,"data-anchored":M?"1":void 0,style:{"--build":`${i}ms`},children:[s("div",{className:F.halo,"aria-hidden":"true"}),w?s(ei,{layers:w,phase:o,broken:_,tone:t},n):null,s("svg",{className:F.svg,viewBox:"0 0 600 600",role:y?"group":"img","aria-label":m,children:[s("defs",{children:[s("linearGradient",{id:`${A}g`,x1:"80",y1:"40",x2:"520",y2:"560",gradientUnits:"userSpaceOnUse",children:[s("stop",{offset:"0",className:F.g0}),s("stop",{offset:"1",className:F.g1})]}),s("radialGradient",{id:`${A}c`,cx:"300",cy:"280",r:"110",gradientUnits:"userSpaceOnUse",children:[s("stop",{offset:"0",className:F.c0}),s("stop",{offset:"1",className:F.c1})]})]}),s("g",{className:F.layer,style:{"--z":1},children:[s("circle",{className:F.seal,cx:300,cy:300,r:re.section+16,pathLength:"1"}),s("circle",{className:F.hair,cx:300,cy:300,r:re.step+32}),b.bands.map(k=>s("g",{className:F.band,style:{"--d":`${Math.round(k.at*i*.4)}ms`},children:[s("path",{className:F.bandArc,d:k.d,pathLength:"1"}),s("line",{className:F.bandMark,x1:k.mark[0][0],y1:k.mark[0][1],x2:k.mark[1][0],y2:k.mark[1][1]}),y?s(ae,{children:[s("path",{id:`${A}b${k.k}`,d:k.text,fill:"none"}),s("text",{className:F.bandText,children:s("textPath",{href:`#${A}b${k.k}`,startOffset:"50%",textAnchor:"middle",children:k.title.toUpperCase()})})]}):null]},k.k))]}),u?s(Jd,{witnesses:u}):null,N?s(Xd,{deg:(N.step+.5)*b.per,kind:N.kind}):null,s("g",{className:F.layer,style:{"--z":.8},children:[b.steps.map(k=>s("path",{className:F.bloom,"data-status":k.status,"data-on":$(k.i),"data-lit":C(f?.steps(k.i)),d:k.d,pathLength:"1",style:R(k)},`b${k.i}`)),b.steps.map(k=>s("path",{className:F.step,"data-status":k.status,"data-on":$(k.i),"data-lit":C(f?.steps(k.i)),"data-current":f&&f.step===k.i?"1":void 0,"data-anchor":N&&N.step===k.i?N.kind:void 0,"data-i":k.i,d:k.d,pathLength:"1",stroke:k.status==="passed"?`url(#${A}g)`:void 0,style:R(k)},k.i)),b.stop?s("g",{"data-lit":C(f&&f.stage==="stop"),className:F.stop,style:{"--d":`${I(e.steps[e.stoppedAt].t1)}ms`},children:s("line",{x1:b.stop.x1,y1:b.stop.y1,x2:b.stop.x2,y2:b.stop.y2})}):null]}),s("g",{className:F.layer,style:{"--z":.6},children:[s("circle",{className:F.hair,cx:300,cy:300,r:re.dot+16}),b.ticks.map(k=>s("line",{className:F.tick,"data-result":k.result,"data-on":$(k.step),"data-lit":C(f?.checks(k.step)),x1:k.x1,y1:k.y1,x2:k.x2,y2:k.y2,style:R(k)},k.i))]}),s("g",{className:F.layer,style:{"--z":.45},children:[b.dots.map(k=>s("circle",{className:F.dot,"data-result":k.result,"data-lit":C(f?.readback(k.i)),"data-on":l!=null&&e.readbacks[k.i].step===l?"1":void 0,cx:k.cx,cy:k.cy,r:re.dotSize,style:R(k),onMouseEnter:y&&c?()=>c(e.readbacks[k.i].step,{readback:k.i}):void 0},k.i)),s("circle",{className:F.hair,cx:300,cy:300,r:re.petal+18})]}),s("g",{className:F.layer,style:{"--z":.3},children:b.petals.map(k=>s("path",{className:F.petal,"data-result":k.result,"data-on":$(k.step),"data-lit":C(f?.identity(k.step)),d:k.d,pathLength:"1",style:R(k),onMouseEnter:y&&c?()=>c(k.step,{identity:k.i}):void 0},k.i))}),s("g",{className:F.layer,style:{"--z":.15},children:[s("circle",{className:F.core,cx:300,cy:300,r:re.core,fill:`url(#${A}c)`}),s("g",{className:F.glyph,children:[s("path",{className:F.check,d:`M${278} ${301}l15 15 31-33`,pathLength:"1"}),s("rect",{className:F.square,x:285,y:285,width:"30",height:"30",rx:"4"}),s("path",{className:F.cross,d:`M${283} ${283}l34 34M${317} ${283}l-34 34`,pathLength:"1"})]})]}),f?s("g",{className:F.playhead,style:{"--deg":`${((f.step+.5)*b.per).toFixed(2)}deg`},"aria-hidden":"true",children:[s("line",{x1:300,y1:300-re.core-6,x2:300,y2:300-re.step-22}),s("circle",{cx:300,cy:300-re.step-22,r:"4.5"})]}):null,y?s("g",{className:F.hits,role:"list","aria-label":`${e.steps.length} program steps`,children:b.steps.map(k=>s("path",{role:"listitem",className:F.hit,d:k.hit,tabIndex:k.i===d?0:-1,"aria-label":Zd(e.steps[k.i],e.steps.length),"data-step":k.i,onMouseEnter:c?()=>c(k.i):void 0,onFocus:c?()=>c(k.i,{focus:!0}):void 0,onClick:g?()=>g(k.i):void 0,onKeyDown:h},k.i))}):null]}),s("div",{className:F.sweep,"aria-hidden":"true"})]})}var Yd={rekor:{deg:226,short:"PUBLIC LOG",name:"Sigstore Rekor: the receipt is in the public transparency log"},tsa:{deg:134,short:"TIMESTAMP",name:"Sigstore Timestamp Authority: a trusted time for the receipt"}};function Jd({witnesses:e}){return s("g",{className:F.layer,style:{"--z":1.15},children:Object.entries(Yd).map(([t,n])=>{let o=e[t];if(!o)return null;let[r,a]=Ae(re.section+32,n.deg),[i,l]=Ae(re.section+6,n.deg),[d,c]=Ae(re.section+17,n.deg);return s("g",{className:F.witness,"data-state":o,"data-witness":t,children:[s("title",{children:`${n.name}${o==="pass"?", checked":o==="fail"?", doesn't check":""}`}),s("line",{className:F.witnessLink,x1:i,y1:l,x2:d,y2:c}),s("circle",{className:F.witnessPing,cx:r,cy:a,r:"15"}),s("circle",{className:F.witnessDot,cx:r,cy:a,r:"15"}),t==="rekor"?s("path",{className:F.witnessGlyph,d:`M${r-6.5} ${a-5}h13M${r-6.5} ${a}h13M${r-6.5} ${a+5}h13`}):s("path",{className:F.witnessGlyph,d:`M${r} ${a-6.5}v6.5l4 3M${r-7.5} ${a}a7.5 7.5 0 1 0 15 0a7.5 7.5 0 1 0 -15 0`}),s("text",{className:F.witnessText,x:r,y:a+30,textAnchor:"middle",children:n.short})]},t)})})}function Xd({deg:e,kind:t}){let[n,o]=Ae(re.section+2,e),[r,a]=Ae(re.step+10,e);return s("g",{className:F.layer,style:{"--z":1},children:s("g",{className:F.anchorMark,"data-kind":t,children:[s("title",{children:t==="stop"?"Signed here: the run stopped at this step":"Signed here: the save OpenAdapt confirmed by reading the record back"}),s("line",{x1:r,y1:a,x2:n,y2:o}),s("circle",{cx:n,cy:o,r:"8"}),s("circle",{cx:n,cy:o,r:"3",className:F.anchorDot})]})})}var Qd=1700;function ei({layers:e,phase:t,broken:n,tone:o}){let r=X(null),a=X([]);return U(()=>{let i=r.current;if(!i)return;let l=[],d="#ffffff",c=()=>{let m=getComputedStyle(i),b=(y,_)=>m.getPropertyValue(y).trim()||_;l=n?[b("--fail","#ff4d6a"),b("--fail","#ff4d6a"),b("--fail","#ff4d6a")]:[b("--t0","#4cf0b8"),b("--soft","#b9fbe5"),b("--t0","#4cf0b8")],d=b("--seal-ink","#ffffff")};c();let g=n?[.3,.26,.22]:[.62,.45,.35],h=e.map(m=>m.petals.map(b=>({path:new Path2D(b.d),at:b.at}))),p=m=>{a.current.forEach((b,y)=>{if(!b)return;let _=b.clientWidth,w=Math.min(2,window.devicePixelRatio||1);b.width!==Math.round(_*w)&&(b.width=Math.round(_*w),b.height=Math.round(_*w));let N=b.getContext("2d");N.setTransform(_*w/200,0,0,_*w/200,0,0),N.clearRect(0,0,200,200);for(let M of h[y]){let S=m==null?0:Math.max(0,1-Math.abs(m-M.at)*6);N.globalAlpha=Math.min(1,g[y]+S*.6),N.fillStyle=S>.3?d:l[y],N.fill(M.path)}})};p(null);let u=new MutationObserver(()=>requestAnimationFrame(()=>{c(),p(null)}));if(u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),t!=="verify"||window.matchMedia("(prefers-reduced-motion: reduce)").matches)return()=>u.disconnect();let f=performance.now(),v=requestAnimationFrame(function m(b){let y=(b-f)/Qd;p(y>1.1?null:y),y<=1.1&&(v=requestAnimationFrame(m))});return()=>{cancelAnimationFrame(v),u.disconnect()}},[e,t,n,o]),s("div",{className:F.iris,ref:r,"aria-hidden":"true",children:[e.map((i,l)=>s("canvas",{ref:d=>{a.current[l]=d},className:F.irisLayer,style:{"--spin":`${i.dir*(140+l*50)}s`}},l)),s("div",{className:F.irisGlow})]})}function ti({seed:e,tone:t,size:n=64}){let o=ne(()=>lr(e,{radius:100}),[e]);return s("span",{className:F.mini,"data-tone":t,style:{width:n,height:n},"aria-hidden":"true",children:s(ei,{layers:o,phase:"rest",broken:!1,tone:t})})}dt();var E={page:"o",srOnly:"uo",skip:"La",top:"ea",home:"Na",mark:"ho",crumb:"D",runs:"ia",run:"L",runSeal:"ko",runText:"Pa",topEnd:"wo",chip:"Y",chipDot:"Ta",blink:"na",iconBtn:"N",app:"pa",hero:"F",tabs:"d",panels:"P",resizer:"v",mapPane:"R",paneHead:"Xa",map:"p",stage:"sa",tilt:"Ga",heading:"yo",outcome:"zo",reason:"_o",meta:"Ja",verdict:"w",code:"jo",pending:"Ka",dots:"Oa",signer:"T",shotsNote:"So",older:"Co",changed:"Qa",actions:"Va",another:"Wa",anotherHead:"Mo",changeHead:"Yo",change:"X",primary:"E",ghost:"I",dock:"Fo",player:"Za",pBtn:"da",scrub:"Ro",pTime:"ao",speeds:"la",stepLine:"Eo",count:"oo",panel:"ga",panelIn:"ro",sub:"Io",line:"Ao",by:"to",stats:"s",swatch:"G",calls:"Ho",proof:"Uo",hashRow:"J",signed:"eo",proofLabel:"ca",hex:"A",chips:"qo",tchip:"H",foot:"io",steps:"m",sNum:"Bo",sMark:"fa",sName:"xa",sTags:"K",evHead:"Do",evTitle:"no",evNum:"Lo",evNav:"No",empty:"po",inspector:"Po",inMain:"To",kv:"l",recordTable:"g",spotNote:"Xo",shots:"O",readTable:"c",flash:"so",record:"Go",recordH:"Jo",wMark:"Q",fileLinks:"va",cmds:"Ko",wideOnly:"Oo"};var tp="0123456789abcdef",Bt=64,np=1100;function cr({label:e,from:t,to:n,against:o,running:r,still:a}){let[i,l]=D(()=>(t||"").slice(0,Bt)),[d,c]=D(!1),g=X(n);g.current=n,U(()=>{if(!r){n&&(l(n),c(!0));return}if(c(!1),a){n&&(l(n),c(!0));return}let f=(t||"").slice(0,Bt).padEnd(Bt,"0"),v=0,m=0,b=null,y=_=>{let w=g.current;w&&b==null&&(b=_);let N=b==null?0:Math.min(1,(_-b)/np);if(_-m>45||N===1){m=_;let M=Math.floor(N*Bt),S="";for(let A=0;AcancelAnimationFrame(v)},[r,a]),U(()=>{!r&&n&&(l(n),c(!0))},[n,r]);let h=d&&n,p=h&&n===o,u=!r&&!n;return s("div",{className:E.hashRow,"data-state":u?"idle":h?p?"match":"differs":"running",children:[s("span",{className:E.proofLabel,children:[e,h?s("b",{children:p?" · matches":" · differs"}):null]}),s("code",{className:E.hex,"aria-label":h?`SHA-256 ${n}`:u?"Not computed":"Computing the SHA-256",children:u?"not computed":h?[...n].map((f,v)=>s("span",{"data-diff":f!==o[v]?"1":void 0,children:f},v)):i})]})}function ao({className:e}){return s("svg",{className:e,viewBox:"0 0 700 700","aria-hidden":"true",focusable:"false",children:s("g",{transform:"translate(0 700) scale(0.1 -0.1)",fill:"currentColor",children:s("path",{d:"M3390 6546 c-220 -60 -361 -281 -316 -496 25 -117 87 -214 176 -271 l50 -32 0 -249 0 -248 -877 0 -878 -1 -117 -80 -118 -80 0 -475 0 -474 -108 0 -107 0 -108 -108 -107 -107 0 -215 0 -215 108 -108 107 -107 108 0 107 0 0 -623 0 -622 111 -143 111 -142 549 0 549 0 2 -527 3 -526 175 -73 c96 -40 180 -73 186 -74 6 0 256 270 555 600 l543 600 681 0 680 0 113 113 112 112 0 653 0 652 113 0 112 0 108 108 107 107 0 215 0 215 -108 108 -107 107 -113 0 -112 0 0 443 0 442 -113 113 -112 112 -873 0 -872 0 0 258 1 257 41 25 c83 51 160 176 179 289 32 203 -122 422 -332 470 -59 14 -154 13 -209 -3z m1860 -3046 l0 -1310 -619 0 -619 0 -73 -31 c-41 -17 -84 -41 -97 -52 -13 -12 -193 -214 -400 -449 l-377 -428 -3 480 -2 480 -133 0 c-125 0 -1012 44 -1124 56 l-53 5 0 1280 0 1279 1750 0 1750 0 0 -1310z M2400 3935 l0 -215 220 0 220 0 0 215 0 215 -220 0 -220 0 0 -215z M4150 3935 l0 -215 220 0 220 0 0 215 0 215 -220 0 -220 0 0 -215z M2511 3126 l-152 -152 53 -50 c119 -113 304 -230 469 -298 573 -235 1197 -133 1673 274 l76 65 -154 154 -154 154 -53 -47 c-115 -103 -267 -189 -427 -242 -102 -33 -155 -39 -357 -39 -142 1 -185 4 -260 23 -180 45 -349 131 -488 247 l-74 63 -152 -152z"})})})}dt();dt();var le=e=>e.kind??"action",At=e=>e.kind??"sequence",Fe=e=>e.halts??[],it=e=>e.effects??[],yn=e=>e.postconditions??[],ye=e=>e.nodes??[],Ke=e=>e.edges??[];var Ze="__opg_stop__",xn=e=>String(e).padStart(2,"0");var op=e=>e.index+1;function rp(e,t,n){let o=i=>n(i)??i.index+1,r=t.map(i=>i.identity).filter(i=>i?.applicable),a=i=>[...new Set(i)];return{id:e.id,index:Math.min(...t.map(i=>i.index)),kind:t.every(i=>le(i)==="action")?"action":le(t[0]),title:e.title??`Steps ${xn(o(t[0]))}–${xn(o(t[t.length-1]))}`,action:null,risk:t.some(i=>i.risk==="irreversible")?"irreversible":t.some(i=>i.risk)?"reversible":null,resolution:null,identity:r.length?{applicable:!0,armed:r.every(i=>i?.armed===!0)}:null,effects:t.flatMap(it),postconditions:t.flatMap(yn),halts:t.flatMap(i=>Fe(i).map(l=>`step ${xn(o(i))}: ${l}`)),badges:a(t.flatMap(i=>i.badges??[]))}}function ni(e,t={}){let n=t.numberOf??op,o=ye(e),r=new Map(o.map(p=>[p.id,p])),a=new Map(o.map(p=>[p.id,p.id])),i=new Map,l=new Map;for(let p of t.folds?.groups??[]){if(t.expanded?.has(p.id)||r.has(p.id))continue;let u=p.nodes.map(v=>r.get(v)).filter(v=>v!==void 0&&a.get(v.id)===v.id).sort((v,m)=>v.index-m.index);if(u.length===0)continue;let f=rp(p,u,n);for(let v of u)a.set(v.id,p.id);l.set(u[0].id,f),i.set(p.id,{id:p.id,title:f.title,subtitle:p.subtitle,members:u,first:n(u[0])??u[0].index+1,last:n(u[u.length-1])??u[u.length-1].index+1})}let d=[];for(let p of o)a.get(p.id)===p.id?d.push(p):l.get(p.id)&&d.push(l.get(p.id));let c=[],g=new Set;for(let p of Ke(e)){let u=a.get(p.source),f=a.get(p.target);if(!u||!f||u===f&&i.has(u))continue;let v=At(p),m=`${u}>${f}>${v}>${p.label??""}`;g.has(m)||(g.add(m),c.push({...p,source:u,target:f,kind:v}))}let h=(t.stopExits??[]).filter(p=>a.has(p.node));if(h.length){let p=Math.max(-1,...d.map(u=>u.index))+1;d.push({id:Ze,index:p,kind:"terminal",title:t.stopLabel??"Stop the run",outcome:"halt",halts:[],effects:[],postconditions:[]});for(let u of h){let f=a.get(u.node),v=`${f}>${Ze}`;g.has(v)||(g.add(v),c.push({source:f,target:Ze,kind:"exception",label:u.label??"stops"}))}}return{spec:{...e,nodes:d,edges:c},folds:i,ownerOf:a}}function oi(e){let t=e.sections??[];return t.length?{groups:t.map(n=>({id:n.id,title:n.title,subtitle:n.subtitle,nodes:[...n.nodes]}))}:null}function dr(e,t,n){let o=e.sections??[],r=o.findIndex(g=>g.id===t);if(r<0)return null;let a=o[r],i=o[r+1],l=ye(e),d=i!==void 0&&i.kind==="save"==(a.kind==="save")&&Ke(e).some(g=>g.source===a.nodes[a.nodes.length-1]&&g.target===i.nodes[0])&&l.some(g=>g.id===i.nodes[0]),c=n?a.nodes.indexOf(n):-1;return{section:a,mergeWith:d?i:void 0,splitAt:a.kind!=="save"&&c>0?a.steps[c]:void 0}}function ri(e,t={}){let n=t.minLength??6,o=t.maxLength??10,r=[...ye(e)].sort((h,p)=>h.index-p.index),a=new Map,i=new Map;for(let h of Ke(e))a.set(h.target,[...a.get(h.target)??[],h]),i.set(h.source,[...i.get(h.source)??[],h]);let l=(h,p)=>{let u=i.get(h.id)??[],f=a.get(p.id)??[];return u.length===1&&f.length===1&&u[0].target===p.id&&At(u[0])==="sequence"&&le(h)==="action"&&le(p)==="action"},d=[],c=[];for(let h of r)c.length&&l(c[c.length-1],h)?c.push(h):(c.length&&d.push(c),c=le(h)==="action"?[h]:[]);c.length&&d.push(c);let g=[];for(let h of d){if(h.lengthm.id)})}}return{groups:g}}var ap={nodeWidth:194,nodeHeight:70,xGap:42,yGap:48,margin:34,minWidth:0,laneGap:14,laneInset:22},xt=6;function ai(e){return new Map(e.map((t,n)=>[t.id,Number.isFinite(t.index)?t.index:n]))}function si(e,t){let n=t.get(e.source),o=t.get(e.target);return n===void 0||o===void 0?!1:o<=n}function sp(e){let t=[...ye(e)],n=ai(t);t.sort((h,p)=>n.get(h.id)-n.get(p.id));let o=new Set(t.map(h=>h.id)),r=Ke(e).filter(h=>o.has(h.source)&&o.has(h.target)),a=r.filter(h=>!si(h,n)),i=new Map(t.map(h=>[h.id,[]])),l=new Map(t.map(h=>[h.id,[]]));for(let h of a)i.get(h.target).push(h),l.get(h.source).push(h);let d=h=>{let p=new Set([h]),u=[h];for(;u.length;){let f=u.shift();for(let v of r)v.target===f&&!p.has(v.source)&&(p.add(v.source),u.push(v.source))}return p},c=[];for(let h of t){let p=l.get(h.id).filter(y=>At(y)==="loop_body");if(le(h)!=="loop"&&p.length===0)continue;let u=l.get(h.id).filter(y=>At(y)!=="loop_body").map(y=>y.target);if(p.length===0||u.length===0)continue;let f=new Set([h.id,...u]),v=d(h.id),m=new Set,b=p.map(y=>y.target).filter(y=>!f.has(y));for(;b.length;){let y=b.shift();if(!m.has(y)){m.add(y);for(let _ of l.get(y))f.has(_.target)||b.push(_.target)}}for(let y of m)v.has(y)||m.delete(y);c.push({exits:u,body:m})}let g=new Map(t.map(h=>[h.id,0]));for(let h=0;h<=t.length;h+=1){let p=!1,u=(f,v)=>{v>g.get(f)&&(g.set(f,v),p=!0)};for(let f of t)for(let v of i.get(f.id))u(f.id,g.get(v.source)+1);for(let f of c){if(f.body.size===0)continue;let v=Math.max(...[...f.body].map(m=>g.get(m)));for(let m of f.exits)u(m,v+1)}if(!p)break}return g}function ip(e,t,n){let o=Math.min(t,n),r=Math.max(t,n);for(let a=0;;a+=1)if(e[a]??=[],e[a].every(i=>ri.to))return e[a].push({from:o,to:r}),a}function ii(e,t={}){let n={...ap,...t},o=ye(e),r=ai(o),a=sp(e),i=new Set(o.map(S=>S.id)),l=Ke(e).filter(S=>i.has(S.source)&&i.has(S.target)),d=new Map;for(let S of o){let A=a.get(S.id)??0,O=d.get(A)??[];O.push(S),d.set(A,O)}for(let S of d.values())S.sort((A,O)=>r.get(A.id)-r.get(O.id));let c=Math.max(0,...a.values()),g=Math.max(1,...[...d.values()].map(S=>S.length)),h=S=>n.margin+S*(n.nodeHeight+n.yGap),p=l.map((S,A)=>{let O=si(S,r),I=(a.get(S.target)??0)-(a.get(S.source)??0);return{edge:S,index:A,back:O,lane:O?"right":I===1?null:"left",slot:0}}),u=[],f=[];for(let S of p){if(S.lane===null)continue;let A=a.get(S.edge.source)??0,O=a.get(S.edge.target)??0;S.slot=ip(S.lane==="left"?u:f,A,O)}let v=S=>S?n.laneInset+(S-1)*n.laneGap+12:0,m=g*n.nodeWidth+(g-1)*n.xGap,b=Math.max(n.minWidth,n.margin*2+m+2*Math.max(v(u.length),v(f.length))),y=n.margin*2+(c+1)*n.nodeHeight+c*n.yGap,_=[];for(let[S,A]of[...d.entries()].sort((O,I)=>O[0]-I[0])){let O=A.length*n.nodeWidth+(A.length-1)*n.xGap,I=(b-O)/2;A.forEach(($,C)=>{_.push({id:$.id,x:I+C*(n.nodeWidth+n.xGap),y:h(S),width:n.nodeWidth,height:n.nodeHeight,rank:S})})}let w=new Map(_.map(S=>[S.id,S])),N=(S,A)=>{let O=Math.min(S,A),I=Math.max(S,A),$=_.filter(C=>C.rank>=O&&C.rank<=I);return{left:Math.min(...$.map(C=>C.x)),right:Math.max(...$.map(C=>C.x+C.width))}},M=p.map(({edge:S,index:A,back:O,lane:I,slot:$})=>{let C=w.get(S.source),R=w.get(S.target),k=At(S),B=S.label??"",H=`${S.source}:${S.target}:${k}:${A}`,G=C.y+C.height/2,V=R.y+R.height/2;if(I===null){let te=C.x+C.width/2,Y=R.x+R.width/2,K=C.y+C.height,xe=R.y,we=(K+xe)/2;return{id:H,source:S.source,target:S.target,kind:k,label:B,path:`M ${te} ${K} C ${te} ${we}, ${Y} ${we}, ${Y} ${xe}`,labelX:(te+Y)/2+6,labelY:we+3,labelRotate:!1,backEdge:O,lane:I}}let me=N(C.rank,R.rank);if(I==="right"){let te=me.right+n.laneInset+$*n.laneGap,Y=C.x+C.width,K=R.x+R.width,xe=VG;return{id:H,source:S.source,target:S.target,kind:k,label:B,path:`M ${Me} ${G} H ${Q+ce} Q ${Q} ${G} ${Q} ${G+(Ee?ce:-ce)} V ${V+(Ee?-ce:ce)} Q ${Q} ${V} ${Q+ce} ${V} H ${ee}`,labelX:Q-8,labelY:(G+V)/2,labelRotate:!0,backEdge:O,lane:I}});return{width:b,height:y,nodes:_,edges:M}}function pr(e){return/^(click|double click) at \(\d+,\s*\d+\)$/i.test(e.title.trim())?e.action==="double_click"?"Double-click recorded target":"Click recorded target":e.title}function ur(e){let t=le(e);if(t==="terminal"){let n=e.outcome?.toLowerCase();return n==="halt"||n==="halted"||n==="escalate"?"stop":"terminal"}return e.risk==="irreversible"?"halt":t==="branch"||t==="loop"?"branch":e.identity?.armed||it(e).length>0?"governed":"default"}var lp=e=>String(e).padStart(2,"0"),_n=e=>e.index+1;function li(e,t="index"){if(t==="index")return _n;let n=new Map;return[...ye(e)].sort((o,r)=>o.index-r.index).filter(o=>le(o)==="action").forEach((o,r)=>n.set(o.id,r+1)),o=>n.get(o.id)??null}var cp={loop:"LOOP",branch:"IF",business_decision:"ASK",subflow_call:"CALL",child_bundle:"SUB",action:"STEP"};function so(e,t=_n){if(le(e)==="terminal")return ur(e)==="stop"?"STOP":"END";let n=t(e);return n===null?cp[le(e)]??"STEP":lp(n)}function Kt(e){return le(e).replaceAll("_"," ")}function io(e){let t=e.resolution?.rungs?.filter(o=>o.present)??[],n=e.identity;return{resolve:{state:t.length?"present":"none",count:t.length,labels:t.map(o=>o.label)},identity:{state:n?.armed?"present":n?.applicable?"warn":"none",text:n?.armed?"Checked":n?.applicable?"Not checked":"Not needed"},screen:{state:yn(e).length?"present":"none",count:yn(e).length},readback:{state:it(e).length?"present":"none",count:it(e).length}}}function ci(e,t=pr(e),n=_n){let o=so(e,n),a=[`${/^\d+$/.test(o)?`step ${o}, ${Kt(e)}`:o==="END"||o==="STOP"?`${o.toLowerCase()}, ${Kt(e)}`:Kt(e)}: ${t}.`];e.identity?.armed&&a.push("Checks the right record."),it(e).length&&a.push("Reads the saved record back.");let i=Fe(e).length;return i&&a.push(`${i} stop ${i===1?"rule":"rules"}.`),a.join(" ")}var Ye=[[/^halts until an operator binds the placeholder effect$/,{kind:"run",text:"Waits until a person names the check for this save."}],[/^halts if the system-of-record effect is not confirmed$/,{kind:"run",text:"Stops if reading the saved record back doesn’t confirm it."}],[/^halts if precondition unmet/,{kind:"run",text:"Stops if the screen isn’t in the expected state before this step."}],[/^halts if not ready in time/,{kind:"run",text:"Stops if the screen isn’t ready in time."}],[/^irreversible write WITHOUT an armed identity gate$/,{kind:"review",text:"Flagged for review: this action can’t be undone, and this step has no right-record check of its own."}],[/^certification halts until action risk is explicitly reviewed$/,{kind:"review",text:"A person reviews this action before the program is approved to run on its own."}],[/^halts until an authenticated answer is signed$/,{kind:"decision",text:"Waits for a signed answer from a person."}],[/^terminal: (halt|escalate)$/,{kind:"end",text:"The program ends here and hands the item to a person."}]];function Wt(e){let t=Fe(e);if(t.length===0)return[];if(!t.every(c=>/^declared stop rule \d+$/.test(c)))return t.map(c=>Ye.find(([g])=>g.test(c))?.[1]??{kind:"run",text:c});let n=c=>Ye.find(([g])=>g.source===c.source)[1],o=le(e);if(o==="terminal")return t.map(()=>Ye[Ye.length-1][1]);if(o==="business_decision")return t.map(()=>Ye[6][1]);let r=[],a=[],i=it(e);i.length&&r.push(n(i.some(c=>c.needs_operator_confirmation)?Ye[0][0]:Ye[1][0])),e.guard_on_unmet==="halt"&&r.push(n(Ye[2][0])),e.risk==="irreversible"&&e.identity?.applicable&&e.identity.armed===!1&&a.push(n(Ye[4][0])),e.risk_review_required&&a.push(n(Ye[5][0]));let l=e.wait_until!=null?[n(Ye[3][0])]:[],d=[...r,...l,...a];return d.length===t.length-1&&!e.wait_until&&(d=[...r,n(Ye[3][0]),...a]),d.length!==t.length?t.map(()=>({kind:"run",text:"Stops if a declared check fails."})):d}function lo(e){return e?.events.find(t=>t.status==="halted")??null}function di(e,t,n){let o=Math.max(0,Math.min(t,e.events.length)),r=u=>n?.get(u)??u,a=new Map,i=new Map,l=new Set,d=null,c=null,g=null,h=null;for(let u=0;u${v}`,l.add(d)):d=null,c=v,g===f&&(d=`${v}>${Ze}`,l.add(d),a.set(Ze,{status:"halted",visits:1,iterations:0,last:f,events:[f]}))}let p=o>0?e.events[o-1]:null;if(p){let u=a.get(r(p.node));u.status!=="halted"&&(u.status="active")}return{cursor:o,nodes:a,taken:l,latestEdge:d,current:p,iteration:h,halted:g,finished:o===e.events.length}}function pi(e,t,n){let r=e.events[t]?.duration_ms;return r==null||!Number.isFinite(r)?140:Math.max(45,Math.min(700,r/Math.max(n,.1)))}function ui(e,t,n){let o=p=>n?.get(p)??p,r=ye(e),a=o(t.node),i=r.find(p=>p.id===a),l=t.iteration??null,d={node:t.node,status:t.status==="stopped"?"halted":"ok",iteration:l,reason:t.reason??null},c=new Map,g=new Set,h=null;if(i){for(let p of r){if(p.index>=i.index||p.id===Ze||le(p)==="terminal")continue;let u=le(p)==="loop";c.set(p.id,{status:"done",visits:1,iterations:u&&l?l:0,events:[]})}c.set(a,{status:t.status==="stopped"?"halted":"active",visits:1,iterations:le(i)==="loop"&&l?l:0,last:d,events:[d]});for(let p of Ke(e)){let u=r.find(v=>v.id===p.source),f=r.find(v=>v.id===p.target);u&&f&&u.indexu.index&&g.add(`${u.id}>${f.id}`)}if(le(i)==="loop"&&(l??1)>1){let p=Ke(e).find(u=>{let f=r.find(v=>v.id===u.source);return u.target===a&&f!==void 0&&f.index>i.index});p&&(h=`${p.source}>${a}`)}else{let p=Ke(e).find(u=>{let f=r.find(v=>v.id===u.source);return u.target===a&&f!==void 0&&f.index${a}`)}h&&g.add(h),t.status==="stopped"&&(h=`${a}>${Ze}`,g.add(h),c.set(Ze,{status:"halted",visits:1,iterations:0,last:d,events:[d]}))}return{cursor:0,nodes:c,taken:g,latestEdge:h,current:d,iteration:l,halted:t.status==="stopped"?d:null,finished:t.status==="stopped"}}var fi=(e,t)=>{for(let n=0;nu.title),r=[...ye(e)].sort((u,f)=>u.index-f.index),a=r.filter(u=>le(u)==="action"),i=[],l=u=>n?fi(n,f=>n.events[f].node===u):-1,d=u=>{let f=l(u);return f>=0?f+1:null};a.length&&i.push({id:"recording",title:"Recorded once",body:`OpenAdapt compiled these ${a.length} steps from one recorded run of the task. Each card is a step, or a section of steps you can open.`,select:a[0].id,cursor:n?0:null,view:"program"});let c=a.find(u=>(u.resolution?.rungs??[]).filter(f=>f.present).length>=2);if(c){let u=(c.resolution?.rungs??[]).filter(f=>f.present).map(f=>f.label.toLowerCase());i.push({id:"step",title:"One step",body:`“${o(c)}” recorded ${u.length} ways to find its target: ${u.join(", ")}. A run tries the strongest first.`,select:c.id,cursor:d(c.id),view:"program"})}let g=r.find(u=>le(u)==="loop");if(g){let u=n?new Set(n.events.map(v=>v.iteration).filter(v=>v!=null)).size:0,f=n?fi(n,v=>n.events[v].node===g.id&&n.events[v].iteration===2):-1;i.push({id:"loop",title:"The loop",body:u>1?`The steps run once for each item in the list. This run reached ${u} items; the dashed line is the return for the next one.`:"The steps run once for each item in the list; the dashed line is the return for the next one.",select:g.id,cursor:f>=0?f+1:d(g.id),view:"program"})}let h=a.find(u=>u.identity?.armed&&u.id!==c?.id)??a.find(u=>u.identity?.armed);h&&i.push({id:"right-record",title:"The right-record check",body:"Before this step acts, it checks that the screen shows the right record. If it doesn’t, the run stops instead of acting.",select:h.id,cursor:d(h.id),view:"program"});let p=lo(n);if(n&&p)i.push({id:"stop",title:"A stop",body:p.reason??"The run stopped here, where a check failed.",select:p.node,cursor:n.events.indexOf(p)+1,view:"program"});else{let u=a.find(f=>Fe(f).length>0);u&&i.push({id:"stop",title:"A stop rule",body:Wt(u).map(f=>f.text).join(" "),select:u.id,cursor:d(u.id),view:"program"})}return n?.receipt&&i.push({id:"receipt",title:n.receipt.kind==="seal"?"The Seal":"The run record",body:n.receipt.summary,select:p?.node??null,cursor:n.events.length,view:"program"}),i}dt();var dp={program:"Program map",evidence:"Evidence lanes",stops:"Stop rules"},pp="The map follows the emitted edge targets. It keeps each loop and exception route visible.",up="These rows show the declared contract. They do not report a live verdict.",fr=e=>String(e).padStart(2,"0"),po=zt(_n);function fp(){let[e,t]=D(!1);return U(()=>{if(typeof window>"u"||!window.matchMedia)return;let n=window.matchMedia("(prefers-reduced-motion: reduce)");t(n.matches);let o=()=>t(n.matches);return n.addEventListener?.("change",o),()=>n.removeEventListener?.("change",o)},[]),e}function ht({label:e,state:t,value:n}){return s("div",{className:"opg-evidence-state","data-state":t,children:[s("span",{children:e}),s("strong",{children:n})]})}function hr(e,t,n){return t?t.first===t.last?fr(t.first):`${fr(t.first)}–${fr(t.last)}`:so(e,n)}function hp({state:e}){let t=e.last;if(!t)return null;let n=[];return n.push(["Reached",e.iterations>1?`${e.iterations} iterations`:e.visits>1?`${e.visits} times`:"Once","none"]),t.rung&&n.push(["Found by",t.rung,"present"]),t.identity&&n.push(["Right record",t.identity==="verified"?"Verified":"Not verified",t.identity==="verified"?"present":"warn"]),t.screen_check&&n.push(["Screen check",t.screen_check==="passed"?"Passed":"Failed",t.screen_check==="passed"?"present":"warn"]),t.effect_checks?n.push(["Read-back",`${t.effect_checks.confirmed} of ${t.effect_checks.total} confirmed`,t.effect_checks.confirmed===t.effect_checks.total?"present":"warn"]):t.effect&&n.push(["Read-back",t.effect,t.effect==="confirmed"?"present":"warn"]),t.duration_ms!=null&&n.push(["Took",`${(t.duration_ms/1e3).toFixed(1)} s`,"none"]),s("div",{className:"opg-run-facts","aria-label":"This run at this step",children:[s("span",{children:"This run"}),n.map(([o,r,a])=>s(ht,{label:o,state:a,value:r},o)),e.status==="halted"&&t.reason&&s("div",{className:"opg-stop-rule","data-run":"halted",children:[s("span",{children:"Stopped here"}),s("strong",{children:t.reason})]})]})}function gp({node:e,fold:t,run:n,resolveMedia:o,title:r}){if(!o)return null;let a=t?t.members.find(h=>h.media?.recorded):e,i=a?.media?.recorded,l=i?.crop??i?.frame??null,d=a&&l?o(l,{node:a.id,kind:i?.crop?"recorded-crop":"recorded-frame"}):null,c=n?[...n.events].reverse().find(h=>h.frame):void 0,g=c?.frame?o(c.frame,{node:c.node,kind:"live",iteration:c.iteration}):null;return!d&&!g?null:s("div",{className:"opg-media",children:[s("span",{children:"Pictures"}),s("div",{className:"opg-media-pair",children:[d&&s("figure",{children:[s("a",{href:d,target:"_blank",rel:"noopener noreferrer",children:s("img",{src:d,alt:a?.media?.alt||`The recorded target of ${r}`,loading:"lazy",decoding:"async"})}),s("figcaption",{children:"Recorded"})]}),g&&s("figure",{children:[s("a",{href:g,target:"_blank",rel:"noopener noreferrer",children:s("img",{src:g,alt:`The screen in this run at ${r}`,loading:"lazy",decoding:"async"})}),s("figcaption",{children:["This run",c?.iteration!=null?`, iteration ${c.iteration}`:""]})]})]})]})}function mp({review:e,folded:t,onEditSection:n}){let{section:o,mergeWith:r,splitAt:a}=e,[i,l]=D(!1),[d,c]=D(o.title);return U(()=>{l(!1),c(o.title)},[o.id,o.title]),s("div",{className:"opg-section-review","aria-label":"Review this section",children:[s("span",{children:"Section"}),t&&i?s("form",{onSubmit:h=>{h.preventDefault();let p=d.replace(/\s+/g," ").trim();p&&p!==o.title&&n({op:"rename",section:o.section,title:p}),l(!1)},children:[s("input",{"aria-label":"Section title",value:d,maxLength:80,autoFocus:!0,onChange:h=>c(h.target.value)}),s("button",{type:"submit",children:"Save"}),s("button",{type:"button",onClick:()=>l(!1),children:"Cancel"})]}):t&&s("button",{type:"button",className:"opg-fold-toggle",onClick:()=>l(!0),children:"Rename this section"}),t&&r&&s("button",{type:"button",className:"opg-fold-toggle",onClick:()=>n({op:"merge",section:o.section,other:r.section}),children:"Merge with the next section"}),!t&&a&&s("button",{type:"button",className:"opg-fold-toggle",onClick:()=>n({op:"split",section:o.section,at:a}),children:"Start a new section at this step"})]})}function bp({node:e,fold:t,partOf:n,run:o,titleFor:r,onUnfold:a,onRefold:i,onPickMember:l,plainStopRules:d,resolveMedia:c,onClose:g,review:h,onEditSection:p}){let u=yt(po),f=io(e),v=t?.members.map(io)??[],m=e.id===Ze;return s("aside",{className:"opg-inspector","aria-label":"Selected program step","aria-live":"polite",children:[s("div",{className:"opg-inspector-head",children:[s("span",{children:t?"Selected steps":"Selected step"}),s("code",{children:hr(e,t,u)}),g&&s("button",{type:"button",className:"opg-icon-button",onClick:g,"aria-label":"Close the step details",children:s(kn,{d:"M3 3l8 8M11 3l-8 8"})})]}),s("h3",{children:r(e)}),s("p",{className:"opg-mono",children:t?t.subtitle??`${t.members.length} steps`:m?"Where a stop rule ends the run":e.id}),!m&&s("div",{className:"opg-inspector-lanes",children:t?s(ae,{children:[s(ht,{label:"Finds the field",state:v.some(b=>b.resolve.count)?"present":"none",value:`${v.filter(b=>b.resolve.count).length} of ${t.members.length} steps`}),s(ht,{label:"Right record",state:f.identity.state,value:`${v.filter(b=>b.identity.text==="Checked").length} checked`}),s(ht,{label:"Screen check",state:f.screen.state,value:f.screen.count?`${f.screen.count} checks`:"Not declared"}),s(ht,{label:"Read-back",state:f.readback.state,value:f.readback.count?`${f.readback.count} independent checks`:"Not declared"})]}):s(ae,{children:[s(ht,{label:"Finds the field",state:f.resolve.state,value:f.resolve.count?`${f.resolve.count} evidence types`:"Not applicable"}),s(ht,{label:"Right record",state:f.identity.state,value:f.identity.text}),s(ht,{label:"Screen check",state:f.screen.state,value:f.screen.count?`${f.screen.count} checks`:"Not declared"}),s(ht,{label:"Read-back",state:f.readback.state,value:f.readback.count?`${f.readback.count} independent checks`:"Not declared"})]})}),!t&&e.resolution&&(e.resolution.rungs?.length??0)>0&&s("div",{className:"opg-ladder",children:[s("span",{children:"Recorded resolution evidence"}),s("ol",{children:e.resolution.rungs.map(b=>s("li",{"data-present":b.present||void 0,"data-top":b.name===e.resolution?.top_rung||void 0,children:[s("i",{"aria-hidden":"true"}),b.label,s("span",{className:"opg-sr-only",children:b.present?" (recorded)":" (not recorded)"})]},b.name))})]}),t&&s("div",{className:"opg-fold-members",children:[s("span",{children:"Steps in this card"}),s("ol",{children:t.members.map(b=>s("li",{children:s("button",{type:"button",onClick:()=>l(t.id,b.id),children:[s("code",{children:so(b,u)}),r(b)]})},b.id))}),s("button",{type:"button",className:"opg-fold-toggle",onClick:()=>a(t.id),children:["Show the ",t.members.length," steps"]})]}),n&&s("button",{type:"button",className:"opg-fold-toggle",onClick:()=>i(n.id),children:["Fold into “",n.title,"”"]}),h&&p&&s(mp,{review:h,folded:!!t,onEditSection:p}),Fe(e).length>0&&(d?s("div",{className:"opg-stop-rule",children:[s("span",{children:"Stop rules"}),(t?t.members.flatMap(Wt):Wt(e)).filter((b,y,_)=>_.findIndex(w=>w.text===b.text)===y).map((b,y)=>s("strong",{"data-kind":b.kind,children:b.text},y))]}):s("div",{className:"opg-stop-rule",children:[s("span",{children:"Stops before acting if"}),s("strong",{children:Fe(e).join("; ")})]})),s(gp,{node:e,fold:t,run:o,resolveMedia:c,title:r(e)}),o&&o.status!=="pending"&&s(hp,{state:o})]})}function vp(e,t){if(!t)return;let n=`${e.source}>${e.target}`;if(t.latestEdge===n)return"latest";if(t.taken.has(n))return"taken"}function yp({display:e,fullSpec:t,folds:n,expanded:o,setExpanded:r,traceState:a,selectedId:i,setSelectedId:l,titleFor:d,canvasNote:c,layoutOptions:g,showInspector:h=!0,plainStopRules:p,compact:u=!1,resolveMedia:f,inspectorOpen:v,setInspectorOpen:m,onEditSection:b}){let y=yt(po),_=ne(()=>ii(e.spec,g),[e.spec,g]),w=ye(e.spec),N=ne(()=>new Map(w.map(T=>[T.id,T])),[w]),M=`opg-arrow-${st().replace(/[^a-zA-Z0-9_-]/g,"")}`,S=X(new Map),A=X(null),O=e.ownerOf.get(i)??(N.has(i)?i:w[0]?.id),I=N.get(O??"")??w[0],[$,C]=D(1),R=Se(T=>C(Math.round(Math.max(.4,Math.min(1.6,T))*100)/100),[]),[k,B]=D(!1),H=u&&!k,G=X(null),V=X(new Map),[me,Q]=D(0);U(()=>{let T=new Set,L=q=>{let Z=V.current.get(q.pointerId);if(!Z)return;let Te=requestAnimationFrame(()=>{T.delete(Te),V.current.get(q.pointerId)===Z&&(V.current.delete(q.pointerId),V.current.size||Q(Ie=>Ie+1))});T.add(Te)},de=()=>{V.current.clear(),Q(q=>q+1)};return window.addEventListener("pointerup",L),window.addEventListener("pointercancel",L),window.addEventListener("blur",de),()=>{window.removeEventListener("pointerup",L),window.removeEventListener("pointercancel",L),window.removeEventListener("blur",de);for(let q of T)cancelAnimationFrame(q);V.current.clear()}},[]);let Me=a?.current?e.ownerOf.get(a.current.node):void 0;U(()=>{let T=G.current,L=_.nodes.find(Zt=>Zt.id===Me);if(!T||!L||V.current.size)return;let q=T.firstElementChild?.offsetLeft??0,Z=L.x*$+q,Te=L.y*$,Ie=L.width*$,Ce=L.height*$,J=Te>=T.scrollTop&&Te+Ce<=T.scrollTop+T.clientHeight,ue=Z>=T.scrollLeft&&Z+Ie<=T.scrollLeft+T.clientWidth;if(J&&ue)return;let et=J?T.scrollTop:Math.max(0,Te-(T.clientHeight-Ce)/2),_t=ue?T.scrollLeft:Math.max(0,Z-(T.clientWidth-Ie)/2);typeof T.scrollTo=="function"?T.scrollTo({top:et,left:_t}):(T.scrollTop=et,T.scrollLeft=_t)},[Me,a?.cursor,_,$,me]),U(()=>{let T=G.current;if(!T||!u)return;let L=de=>{!de.ctrlKey&&!de.metaKey||(de.preventDefault(),C(q=>Math.round(Math.max(.4,Math.min(1.6,q*(de.deltaY>0?.9:1.1)))*100)/100))};return T.addEventListener("wheel",L,{passive:!1}),()=>T.removeEventListener("wheel",L)},[u]);let ee=X(null),ce=u?{onPointerDown:T=>{if(T.target.closest("button")||T.button!==0)return;let L=G.current;ee.current={x:T.clientX,y:T.clientY,left:L.scrollLeft,top:L.scrollTop},L.setPointerCapture?.(T.pointerId)},onPointerMove:T=>{let L=ee.current,de=G.current;!L||!de||(de.scrollLeft=L.left-(T.clientX-L.x),de.scrollTop=L.top-(T.clientY-L.y))},onPointerUp:()=>{ee.current=null},onPointerCancel:()=>{ee.current=null}}:{},Ee=()=>{let T=G.current;T&&R(Math.min(1,(T.clientWidth-16)/_.width,(T.clientHeight-16)/_.height))};if(U(()=>{let T=A.current;T&&(A.current=null,S.current.get(T)?.focus())}),!I)return s("p",{className:"opg-empty",children:"The compiled graph is empty."});let te=n?.groups.find(T=>o.has(T.id)&&T.nodes.includes(I.id)),Y=b?e.folds.has(I.id)?dr(t,I.id):te?dr(t,te.id,I.id):null:null,K=s(bp,{node:I,fold:e.folds.get(I.id),partOf:te?{id:te.id,title:te.title??te.id}:void 0,review:Y,onEditSection:b,run:a?.nodes.get(I.id),titleFor:d,plainStopRules:p,resolveMedia:f,onClose:u?()=>m(!1):void 0,onUnfold:T=>{let L=e.folds.get(T);r(new Set([...o,T])),L&&(l(L.members[0].id,"user"),A.current=L.members[0].id)},onRefold:T=>{let L=new Set(o);L.delete(T),r(L),l(T,"user"),A.current=T},onPickMember:(T,L)=>{r(new Set([...o,T])),l(L,"user"),A.current=L}}),xe=T=>a?.nodes.get(T),we=Ke(t).length,Qe=ye(t).length,uo=w.filter(T=>T.id!==Ze).length,qt=(T,L)=>{let de=_.nodes.find(J=>J.id===L);if(!de)return;let q,Z=J=>_.nodes.filter(ue=>ue.rank===J).sort((ue,et)=>ue.x-et.x),Te=J=>Z(J).sort((ue,et)=>Math.abs(ue.x-de.x)-Math.abs(et.x-de.x))[0]?.id,Ie=[...new Set(_.nodes.map(J=>J.rank))].sort((J,ue)=>J-ue),Ce=Ie.indexOf(de.rank);switch(T.key){case"ArrowDown":q=_.edges.find(J=>J.source===L&&!J.backEdge)?.target??(CeJ.target===L&&!J.backEdge)?.source??(Ce>0?Te(Ie[Ce-1]):void 0);break;case"ArrowRight":case"ArrowLeft":{let J=Z(de.rank),ue=J.findIndex(et=>et.id===L)+(T.key==="ArrowRight"?1:-1);q=J[ue]?.id;break}case"Home":q=_.nodes.slice().sort((J,ue)=>J.rank-ue.rank||J.x-ue.x)[0]?.id;break;case"End":q=_.nodes.slice().sort((J,ue)=>ue.rank-J.rank||ue.x-J.x)[0]?.id;break;default:return}T.preventDefault(),q&&(l(q,"user"),S.current.get(q)?.focus())};return s("div",{className:"opg-grid","data-inspector":h&&v||void 0,"data-staged":H||void 0,children:[s("div",{className:"opg-canvas-shell",children:[s("div",{className:"opg-canvas-head",children:[s("span",{children:"Compiled topology"}),s("span",{children:[Qe," nodes · ",we," exact edges",e.folds.size>0&&` · ${uo} cards`]})]}),u&&s("div",{className:"opg-stage-tools",role:"toolbar","aria-label":"Map view",children:[s("button",{type:"button",onClick:()=>R($-.1),"aria-label":"Zoom out",disabled:$<=.4,children:s(kn,{d:"M3 7h8"})}),s("span",{"aria-live":"polite",children:[Math.round($*100),"%"]}),s("button",{type:"button",onClick:()=>R($+.1),"aria-label":"Zoom in",disabled:$>=1.6,children:s(kn,{d:"M3 7h8M7 3v8"})}),s("button",{type:"button",onClick:Ee,children:"Fit"}),s("button",{type:"button",onClick:()=>B(!k),"aria-pressed":k,children:k?"Collapse":"Expand"}),h&&!v&&s("button",{type:"button",onClick:()=>m(!0),children:"Show step details"})]}),s("div",{className:"opg-canvas-viewport",ref:G,onPointerDownCapture:T=>{T.button===0&&T.isPrimary!==!1&&V.current.set(T.pointerId,{})},"data-stage":H||void 0,"data-pan":u||void 0,...ce,children:s("div",{className:"opg-canvas-sizer",style:{width:_.width*$,height:_.height*$},children:s("div",{className:"opg-canvas",style:{width:_.width,height:_.height,transform:$===1?void 0:`scale(${$})`},children:[s("svg",{className:"opg-edges",viewBox:`0 0 ${_.width} ${_.height}`,width:_.width,height:_.height,role:"img","aria-label":`${_.edges.length} compiled program edges`,children:[s("defs",{children:s("marker",{id:M,markerWidth:"8",markerHeight:"8",refX:"7",refY:"4",orient:"auto",markerUnits:"strokeWidth",children:s("path",{d:"M 0 0 L 8 4 L 0 8 z"})})}),_.edges.map(T=>s("g",{"data-kind":T.kind,"data-back-edge":T.backEdge||void 0,"data-lane":T.lane??void 0,"data-run":vp(T,a),children:[s("path",{d:T.path,markerEnd:`url(#${M})`}),T.label&&s("text",{x:T.labelX,y:T.labelY,textAnchor:T.labelRotate?"middle":void 0,dominantBaseline:T.labelRotate?"middle":void 0,transform:T.labelRotate?`rotate(-90 ${T.labelX} ${T.labelY})`:void 0,children:T.label})]},T.id))]}),_.nodes.map(T=>{let L=N.get(T.id),de=L.id===I.id,q=e.folds.get(L.id),Z=xe(L.id),Te=d(L),Ie=Z&&Z.status!=="pending"?` This run: ${Z.status==="halted"?"stopped here":Z.status==="active"?"here now":"reached"}${Z.iterations>1?`, ${Z.iterations} iterations`:""}.`:"";return s("button",{ref:Ce=>{Ce?S.current.set(L.id,Ce):S.current.delete(L.id)},type:"button",className:"opg-node","data-tone":ur(L),"data-fold":q?"folded":void 0,"data-selected":de||void 0,"data-run":Z?.status,style:{left:T.x,top:T.y,width:T.width,height:T.height},"aria-pressed":de,"aria-label":q?`Steps ${hr(L,q,y)}, ${q.members.length} steps: ${Te}.${Ie}`:`${ci(L,Te,y)}${Ie}`,tabIndex:de?0:-1,onClick:()=>{l(L.id,"user"),v||m(!0)},onDoubleClick:()=>{q&&(r(new Set([...o,q.id])),l(q.members[0].id,"user"),A.current=q.members[0].id)},onKeyDown:Ce=>qt(Ce,L.id),children:[s("span",{className:"opg-node-index",children:hr(L,q,y)}),s("span",{className:"opg-node-copy",children:[s("small",{children:q?q.subtitle??`${q.members.length} steps`:Kt(L)}),s("strong",{title:q?Te:void 0,children:Te})]}),s("span",{className:"opg-node-signals","aria-hidden":"true",children:[le(L)==="loop"&&Z&&Z.iterations>0&&s("b",{children:["×",Z.iterations]}),L.identity?.armed&&s("i",{title:"Checks the right record",children:"R"}),it(L).length>0&&s("i",{title:"Reads the saved record back",children:"C"}),Fe(L).length>0&&s("i",{title:"Stop rules",children:"H"})]})]},L.id)})]})})}),s("ul",{className:"opg-sr-only","aria-label":"Program edges",children:_.edges.map(T=>s("li",{children:[d(N.get(T.source))," to ",d(N.get(T.target)),T.backEdge?", returns to an earlier step":""," (",T.kind.replaceAll("_"," "),T.label?`: ${T.label}`:"",")"]},T.id))}),c&&s("p",{className:"opg-canvas-note",children:c})]}),h&&v&&K]})}function xp({spec:e,titleFor:t,note:n}){return s("div",{className:"opg-matrix-scroll",children:[s("table",{className:"opg-matrix",children:[s("thead",{children:s("tr",{children:[s("th",{scope:"col",children:"Step"}),s("th",{scope:"col",children:"Finds the field"}),s("th",{scope:"col",children:"Right record"}),s("th",{scope:"col",children:"Screen check"}),s("th",{scope:"col",children:"Read-back"})]})}),s("tbody",{children:ye(e).map(o=>{let r=io(o);return s("tr",{children:[s("td",{children:[s("strong",{children:t(o)}),s("small",{className:"opg-mono",children:o.id})]}),s("td",{"data-state":r.resolve.state,children:r.resolve.count?r.resolve.labels.join(", "):"Not applicable"}),s("td",{"data-state":r.identity.state,children:r.identity.text}),s("td",{"data-state":r.screen.state,children:r.screen.count?`${r.screen.count} declared`:"Not declared"}),s("td",{"data-state":r.readback.state,children:r.readback.count?`${r.readback.count} independent`:"Not declared"})]},`evidence-${o.id}`)})})]}),n&&s("p",{className:"opg-boundary-note",children:n})]})}function _p({spec:e,titleFor:t,halt:n,plain:o}){let r=yt(po),a=ye(e).filter(l=>Fe(l).length>0||le(l)==="terminal"),i=n?ye(e).find(l=>l.id===n.node):void 0;return s("div",{className:"opg-stop-list",children:[n&&i&&s("article",{"data-run":"halted",children:[s("span",{className:"opg-mono",children:["this run stopped at step ",r(i)??i.index+1]}),s("strong",{children:t(i)}),s("p",{children:n.reason??"The run stopped at this step."})]}),a.length===0?s("p",{className:"opg-empty",children:"This graph does not declare a stop rule or terminal outcome."}):a.map(l=>s("article",{children:[s("span",{className:"opg-mono",children:le(l)==="terminal"?"terminal":r(l)===null?Kt(l):`step ${r(l)}`}),s("strong",{children:t(l)}),s("p",{children:Fe(l).length?o?Wt(l).map(d=>d.text).join(" "):Fe(l).join("; "):"Declared terminal program state."})]},`stop-${l.id}`))]})}function kn({d:e}){return s("svg",{viewBox:"0 0 14 14",width:"12",height:"12","aria-hidden":"true",focusable:"false",children:s("path",{d:e})})}function kp({trace:e,state:t,playing:n,setPlaying:o,setCursor:r,iterationNoun:a,liveFrame:i}){let l=e.events.length,d=new Set(e.events.map(h=>h.iteration).filter(h=>h!=null)).size,c=t.cursor===0?"Ready":t.iteration!=null?`${a[0].toUpperCase()}${a.slice(1)} ${t.iteration} of ${d}`:`Step ${t.cursor} of ${l}`,g=t.halted&&t.finished?`Stopped. ${t.halted.reason??""}`:t.finished?"The run finished.":t.iteration!=null?`${a} ${t.iteration}`:"";return s("div",{className:"opg-player",role:"group","aria-label":"Run trace player",children:[s("button",{type:"button",onClick:()=>r(0),"aria-label":"Back to the start",disabled:t.cursor===0,children:"⏮"}),s("button",{type:"button",onClick:()=>r(t.cursor-1),"aria-label":"Step back",disabled:t.cursor===0,children:s(kn,{d:"M11 2 4 7l7 5z"})}),s("button",{type:"button",className:"opg-play",onClick:()=>{t.finished&&r(0),o(!n)},"aria-label":n?"Pause":t.finished?"Replay":"Play",children:n?"Pause":t.finished?"Replay":"Play"}),s("button",{type:"button",onClick:()=>r(t.cursor+1),"aria-label":"Step forward",disabled:t.finished,children:s(kn,{d:"M3 2l7 5-7 5z"})}),s("input",{type:"range",min:0,max:l,value:t.cursor,onChange:h=>{o(!1),r(Number(h.target.value))},"aria-label":"Run position","aria-valuetext":`${c}, event ${t.cursor} of ${l}`}),s("span",{className:"opg-player-where",children:c}),i&&s("img",{className:"opg-player-frame",src:i,alt:"The screen in this run now",decoding:"async"}),s("span",{className:"opg-sr-only","aria-live":"polite",children:g})]})}function wp({trace:e,state:t,playing:n}){if(!e||!t)return s("span",{className:"opg-trace-state",children:[s("i",{})," No live trace bound"]});let o=t.halted&&t.finished?"halted":t.finished?"done":n?"playing":"ready",r=o==="halted"?"Run stopped":o==="done"?"Run finished":o==="playing"?"Playing run trace":"Run trace bound";return s("span",{className:"opg-trace-state","data-run":o,children:[s("i",{})," ",e.label?`${r} · ${e.label}`:r]})}function Sp({receipt:e}){let t=e.label??(e.kind==="seal"?"Seal":"Run record");return s("section",{className:"opg-receipt","data-kind":e.kind,"data-status":e.status.toLowerCase(),"aria-label":t,children:[s("div",{children:[s("span",{className:"opg-kicker",children:t}),s("strong",{children:e.status})]}),s("p",{children:e.summary}),e.href&&s("a",{href:e.href,target:"_blank",rel:"noopener noreferrer",children:e.kind==="seal"?"Open the Seal":"Open the run record"})]})}function Np({stop:e,at:t,count:n,focus:o,onBack:r,onNext:a,onSkip:i}){let l=`opg-tour-${st().replace(/[^a-zA-Z0-9_-]/g,"")}`,d=X(null);return U(()=>{o.current&&d.current?.focus()},[t,o]),s("section",{className:"opg-tour",role:"region","aria-labelledby":l,onKeyDown:c=>{if(c.key==="Escape")i();else if(c.key==="ArrowRight"&&!(c.target instanceof HTMLInputElement))a();else if(c.key==="ArrowLeft"&&t>0)r();else return;c.preventDefault()},children:[s("span",{className:"opg-kicker",children:["Tour · ",t+1," of ",n]}),s("h3",{id:l,ref:d,tabIndex:-1,"aria-live":"polite",children:e.title}),s("p",{children:e.body}),s("div",{className:"opg-tour-actions",children:[s("button",{type:"button",onClick:r,disabled:t===0,children:"Back"}),s("button",{type:"button",className:"opg-tour-next",onClick:a,children:t+1===n?"Done":"Next"}),s("button",{type:"button",className:"opg-tour-skip",onClick:i,children:"Skip the tour"})]})]})}function Ep(e){let{spec:t,folds:n,stopExits:o,trace:r,playhead:a,autoPlay:i=!1,initialCursor:l=0,speed:d=14,numbering:c}=e,g=ne(()=>li(t,c),[t,c]),[h,p]=D(e.initialSelectedId??ye(t)[0]?.id??""),u=e.selectedId??h,[f,v]=D(()=>new Set),m=ne(()=>e.expanded?new Set(e.expanded):f,[e.expanded,f]),b=fp(),[y,_]=D(l),w=e.cursor??y,[N,M]=D(!1),S=r?.events.length??0,{onSelect:A,onCursorChange:O,onExpandedChange:I}=e,$=Se((ee,ce)=>{p(ee),A?.(ee,ce)},[A]),C=Se(ee=>{v(ee),I?.([...ee])},[I]),R=X(w);R.current=w;let k=Se(ee=>{let ce=Math.max(0,Math.min(S,ee));_(ce),O?.(ce)},[S,O]);U(()=>{e.cursor===void 0&&_(Math.max(0,Math.min(r?.events.length??0,l))),M(!!r&&i&&!b)},[r,i,b,l]),U(()=>{if(!N||!r)return;if(w>=S){M(!1);return}let ee=setTimeout(()=>k(R.current+1),pi(r,w,d));return()=>clearTimeout(ee)},[N,w,S,r,d,k]);let B=r?lo(r):a?.status==="stopped"?{node:a.node,status:"halted"}:null,H=ne(()=>{let ee=[...o??[]];return B&&!ee.some(ce=>ce.node===B.node)&&ee.push({node:B.node,label:"stopped"}),ee},[o,B?.node]),G=ne(()=>ni(t,{folds:n,expanded:m,stopExits:H,numberOf:g}),[t,n,m,H,g]),V=ne(()=>r?di(r,w,G.ownerOf):a?ui(G.spec,a,G.ownerOf):null,[r,w,a,G]),me=X(null),Q=Se(ee=>{me.current=`c${ee}`},[]),Me=r?`c${w}`:a?`p${a.node}:${a.iteration??""}:${a.status}`:null;return U(()=>{if(!V?.current||Me===null||me.current===Me)return;let ee=me.current===null&&w===0&&!!r;me.current=Me,ee||$(V.current.node,"follow")},[V,Me,w,r,$]),{selectedId:u,setSelectedId:$,expanded:m,setExpanded:C,cursor:w,setCursor:k,playing:N,setPlaying:M,display:G,traceState:V,numberOf:g,suppressFollow:Q}}function gr(e){let{spec:t,title:n,kicker:o="The steps",trace:r,iterationNoun:a="iteration",views:i=["program","evidence","stops"],initialView:l,titleFor:d=pr,notes:c,layout:g,theme:h="dark",className:p,style:u,showHeader:f=!0,showPlayer:v=!0,showInspector:m=!0,plainStopRules:b=!1,compact:y=!1,resolveMedia:_,tour:w,tourSeen:N=!1,onTourEnd:M}=e,S=ne(()=>e.folds!==void 0?e.folds:oi(t)??(y?ri(t):null),[e.folds,y,t]),A=Ep({...e,folds:S}),[O,I]=D(l??i[0]??"program"),{traceState:$}=A,[C,R]=D(!0),k=ne(()=>w===!0?co(t,{trace:r,title:d}):Array.isArray(w)?w:[],[w,t,r,d]),[B,H]=D(()=>k.length&&!N?0:null),G=X(!1);U(()=>{if(B===null)return;let K=k[B];K&&(A.setPlaying(!1),K.view&&I(K.view),K.cursor!=null&&r&&(A.suppressFollow(K.cursor),A.setCursor(K.cursor)),K.select&&A.setSelectedId(K.select,"tour"),R(!0))},[B,k]);let V=K=>{H(null),M?.(K)},me=k.length>0&&B===null?s("button",{type:"button",className:"opg-tour-launch",onClick:()=>{G.current=!0,H(0)},children:"Take the tour"}):null,Q=r?.receipt&&$?.finished?r.receipt:null,Me=_&&$?.current?.frame?_($.current.frame,{node:$.current.node,kind:"live",iteration:$.current.iteration}):null,ee=st().replace(/[^a-zA-Z0-9_-]/g,""),ce=X(new Map),Ee=i.length>1,te=(K,xe)=>{let we=i.indexOf(xe),Qe=K.key==="ArrowRight"?i[(we+1)%i.length]:K.key==="ArrowLeft"?i[(we-1+i.length)%i.length]:K.key==="Home"?i[0]:K.key==="End"?i[i.length-1]:void 0;Qe&&(K.preventDefault(),I(Qe),ce.current.get(Qe)?.focus())},Y=(K,xe)=>Ee?s("div",{role:"tabpanel",id:`${ee}-panel-${K}`,"aria-labelledby":`${ee}-tab-${K}`,hidden:O!==K,tabIndex:-1,children:O===K&&xe}):O===K&&s("div",{children:xe});return s(po.Provider,{value:A.numberOf,children:s("div",{className:`opg-root${p?` ${p}`:""}`,"data-theme":h,"data-compact":y||void 0,style:u,children:[f&&s("div",{className:"opg-topbar",children:[s("div",{children:[s("span",{className:"opg-kicker",children:o}),s("strong",{children:n??t.bundle.name})]}),s("div",{className:"opg-topbar-end",children:[me,s(wp,{trace:r,state:r?$:null,playing:A.playing})]})]}),!f&&me&&s("div",{className:"opg-tour-bar",children:me}),v&&r&&$&&s(kp,{trace:r,state:$,playing:A.playing,setPlaying:A.setPlaying,setCursor:A.setCursor,iterationNoun:a,liveFrame:Me}),B!==null&&k[B]&&s(Np,{stop:k[B],at:B,count:k.length,focus:G,onBack:()=>H(Math.max(0,B-1)),onNext:()=>B+1V("skipped")}),Q&&s(Sp,{receipt:Q}),Ee&&s("div",{className:"opg-tabs",role:"tablist","aria-label":"Program workbench views",children:i.map(K=>s("button",{ref:xe=>{xe&&ce.current.set(K,xe)},id:`${ee}-tab-${K}`,type:"button",role:"tab","aria-selected":O===K,"aria-controls":`${ee}-panel-${K}`,tabIndex:O===K?0:-1,onClick:()=>I(K),onKeyDown:xe=>te(xe,K),children:dp[K]},K))}),i.includes("program")&&Y("program",s(yp,{display:A.display,fullSpec:t,folds:S,expanded:A.expanded,setExpanded:A.setExpanded,traceState:$,selectedId:A.selectedId,setSelectedId:A.setSelectedId,titleFor:d,canvasNote:c?.canvas===void 0?pp:c.canvas,layoutOptions:g,showInspector:m,plainStopRules:b,compact:y,resolveMedia:_,inspectorOpen:C,setInspectorOpen:R,onEditSection:e.onEditSection})),i.includes("evidence")&&Y("evidence",s(xp,{spec:t,titleFor:d,note:c?.evidence===void 0?up:c.evidence})),i.includes("stops")&&Y("stops",s(_p,{spec:t,titleFor:d,halt:$?.finished?$.halted:null,plain:b}))]})})}dt();var gt={host:"Qo",card:"V",cardIn:"do",body:"Vo",kicker:"Wo",line:"Zo",sub:"ar",action:"W",others:"ma"};function $p(e){let t=e.querySelector(".opg-inspector-head span")?.textContent||"";if(t==="Selected step"){let n=e.querySelector(":scope > p.opg-mono")?.textContent||null;return n?{step:n}:null}if(t==="Selected steps"){let n=e.querySelector(":scope > h3")?.textContent||null;return n?{fold:n}:null}return null}function Ap(e,t,n){if(!e)return[];if(e.step)return t.includes(e.step)?[e.step]:[];let o=n.find(r=>(r.title??r.id)===e.fold);return o?t.filter(r=>o.nodes.includes(r)):[]}function hi(e,t,n){let[o,r]=D({host:null,ids:[]}),a=t.join(" ");return U(()=>{let i=e.current;if(!i||!a)return;let l=a.split(" "),d=null,c="",g=()=>{let p=i.querySelector(".opg-inspector"),u=p?Ap($p(p),l,n):[];if(!u.length){d&&(d.remove(),d=null,c="",r({host:null,ids:[]}));return}d||(d=document.createElement("div"),d.className=gt.host,d.dataset.sealCardHost=""),p.firstChild!==d&&p.prepend(d);let f=u.join(" ");f!==c&&(c=f,r({host:d,ids:u}))},h=new MutationObserver(g);return h.observe(i,{childList:!0,subtree:!0,characterData:!0}),g(),()=>{h.disconnect(),d?.remove(),r({host:null,ids:[]})}},[e,a,n]),o}function gi({seals:e,here:t=!1,Link:n="a"}){let[o,...r]=e,a=o.anchor?.kind==="stop",i=!t;return s("section",{className:gt.card,"data-tone":o.tone,"data-seal-card":i?"open":"here","aria-label":"This step's receipt",children:[s(ti,{seed:o.irisSeed,tone:o.tone,size:58}),s("div",{className:gt.body,children:[s("p",{className:gt.kicker,children:i?`Signed here${o.n?` · referral ${o.n}`:""}`:"This is the step the receipt covers"}),s("p",{className:gt.line,children:o.line}),s("p",{className:gt.sub,children:a?"The run stopped here, before saving, and was signed.":"The save its read-backs prove, signed on the machine that ran it."}),i?s(n,{className:gt.action,"data-seal-open":"",href:o.href,children:"Open the receipt →"}):null,r.length?s("p",{className:gt.others,children:[s("span",{children:"Also signed here:"}),r.map(l=>s(n,{href:l.href,children:["Referral ",l.n]},l.n))]}):null]})]})}var Mp=[];function mr({program:e,map:t={},step:n,status:o,onPick:r,anchor:a=null,sealRun:i=null,sealLine:l="",theme:d="dark",fill:c=!1}){let{spec:g,folds:h=null,titles:p={}}=e,u=h?.groups||Mp,f=ne(()=>g.nodes.filter(R=>R.kind==="action").map(R=>R.id),[g]),v=ne(()=>Object.fromEntries(u.flatMap(R=>R.nodes.map(k=>[k,R.id]))),[u]),m=ne(()=>R=>p[R.id]||R.title,[p]),b=ne(()=>co(g,{title:m}),[g,m]),y=X(null);U(()=>{let R=y.current;if(!R)return;for(let Q of R.querySelectorAll("[data-seal-anchor]"))delete Q.dataset.sealAnchor;if(!a)return;let k=f[a.step],B=p[k],H=u.find(Q=>Q.nodes.includes(k)),G=[...R.querySelectorAll(".opg-node")],V=Q=>Q.getAttribute("aria-label")||"",me=(B?G.find(Q=>!Q.dataset.fold&&V(Q).includes(B)):null)||(H?G.find(Q=>Q.dataset.fold&&V(Q).includes(`: ${H.title}.`)):null);me&&(me.dataset.sealAnchor=a.kind)}),U(()=>{let R=y.current;if(!R||!c||typeof ResizeObserver>"u")return;let k=0,B=()=>{k=0;let G=R.querySelector(".opg-root"),V=R.querySelector(".opg-canvas-viewport");if(!G||!V)return;let me=G.offsetHeight-V.offsetHeight,Q=Math.max(240,Math.floor(R.clientHeight-me-2));R.style.getPropertyValue("--seal-stage-h")!==`${Q}px`&&R.style.setProperty("--seal-stage-h",`${Q}px`)},H=new ResizeObserver(()=>{k||(k=requestAnimationFrame(B))});return H.observe(R),B(),()=>{H.disconnect(),cancelAnimationFrame(k),R.style.removeProperty("--seal-stage-h")}},[c]);let _=n!=null?f[n]:null,[w,N]=D(null);U(()=>N(null),[_]);let[M,S]=D([]),A=ne(()=>[...new Set([...M,..._&&v[_]?[v[_]]:[]])],[M,_,v]),O=ne(()=>_?{node:_,iteration:1,status:o||"running"}:null,[_,o]),I=a?f[a.step]:null,$=ne(()=>I?[I]:[],[I]),C=hi(y,$,u).host;return s("div",{className:E.map,"data-step":n??"","data-fill":c?"1":void 0,ref:y,children:[s(gr,{spec:g,folds:h,stopExits:h?.stops,compact:!0,numbering:"actions",kicker:t.kicker||"Compiled program",title:t.title,titleFor:m,resolveMedia:t.resolveMedia,tour:b,tourSeen:!0,plainStopRules:!0,theme:d,playhead:O,selectedId:w||_||f[0],onSelect:(R,k)=>{if(k==="follow")return;if(I&&v[I]===R&&u.some(H=>H.id===R)){N(null),r(a.step);return}let B=f.indexOf(R);B>=0?(N(null),r(B)):N(R)},expanded:A,onExpandedChange:S}),C&&i?Fn(s(gi,{seals:[{...i,line:l,anchor:a}],here:!0}),C):null]})}var mi=3400,Rp=1700,Ip=[1,2,4],Cp={subject_mismatch:"The report doesn't match the SHA-256 the receipt signed.",bad_signature:"The Ed25519 signature doesn't match the signed fields.",malformed:"The receipt file isn't well formed.",unknown_key:"The receipt names a key this site doesn't pin.",revoked_key:"The receipt names a revoked key.",key_mismatch:"The key in the receipt isn't the key this site pins.",ambiguous_key:"The pinned key list names this key twice."},Pp=new Set(["unknown_key","key_mismatch","ambiguous_key"]),bi=e=>Cp[e]||(String(e).startsWith("anchor_")?"The public log's record doesn't back this signature.":String(e).startsWith("auth")?"The authorization doesn't cover this run.":"The check failed."),Vt=e=>`${(e/1e3).toFixed(1)} s`,Op=(e,t)=>`${e} of ${t} record checks confirmed`,zp=e=>e&&e.charAt(0).toUpperCase()+e.slice(1);function Lp(){let[e,t]=D(!1);return U(()=>{let n=window.matchMedia("(prefers-reduced-motion: reduce)"),o=()=>t(n.matches);return o(),n.addEventListener("change",o),()=>n.removeEventListener("change",o)},[]),e}function Dp(e){let[t,n]=D(!1);return U(()=>{let o=window.matchMedia(e),r=()=>n(o.matches);return r(),o.addEventListener("change",r),()=>o.removeEventListener("change",r)},[e]),t}var Si="oa-theme",vi=()=>{try{let e=window.localStorage.getItem(Si);return e==="light"||e==="dark"?e:null}catch{return null}},yi=()=>window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark",xi=()=>{let e=document.documentElement.getAttribute("data-theme");return e==="light"||e==="dark"?e:null};function Fp(e){let[t,n]=D("dark");U(()=>{let r=()=>xi()||vi()||yi(),a=()=>{let c=r();e&&!xi()&&document.documentElement.setAttribute("data-theme",c),n(c)};a();let i=window.matchMedia("(prefers-color-scheme: light)"),l=()=>{vi()||(e&&document.documentElement.setAttribute("data-theme",yi()),a())};i.addEventListener("change",l);let d=new MutationObserver(()=>n(r()));return d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>{i.removeEventListener("change",l),d.disconnect()}},[e]);let o=Se(()=>{let r=t==="dark"?"light":"dark";document.documentElement.setAttribute("data-theme",r);let a=document.querySelector('meta[name="theme-color"]');a&&a.setAttribute("content",r==="light"?"#ffffff":"#05080d");try{window.localStorage.setItem(Si,r)}catch{}n(r)},[t]);return[t,o]}var Ni=["summary","steps","evidence","raw"],Hp={summary:"Summary",program:"Program",steps:"Steps",evidence:"Evidence",raw:"Raw"};function jp(e){let t=new URLSearchParams(window.location.hash.replace(/^#/,"")),n=t.get("tab"),o=Number.parseInt(t.get("step")||"",10);return{tab:Ni.includes(n)||n==="program"?n:null,step:Number.isInteger(o)&&o>=1&&o<=e?o-1:null}}function _i(e,t){let n=[];return e&&e!=="summary"&&n.push(`tab=${e}`),t!=null&&n.push(`step=${t+1}`),n.length?`#${n.join("&")}`:""}function Gp(e,t){U(()=>{let n=e.current;if(!n||!t||!window.matchMedia("(hover: hover) and (pointer: fine)").matches)return;let o=0,r=0,a=0,i=0,l=0,d=()=>{a+=(o-a)*.08,i+=(r-i)*.08,n.style.setProperty("--px",a.toFixed(4)),n.style.setProperty("--py",i.toFixed(4)),l=Math.abs(o-a)+Math.abs(r-i)>8e-4?requestAnimationFrame(d):0},c=h=>{let p=n.getBoundingClientRect();o=Math.max(-1,Math.min(1,(h.clientX-p.left)/p.width*2-1)),r=Math.max(-1,Math.min(1,(h.clientY-p.top)/p.height*2-1)),l||(l=requestAnimationFrame(d))},g=()=>{o=0,r=0,l||(l=requestAnimationFrame(d))};return window.addEventListener("pointermove",c,{passive:!0}),document.documentElement.addEventListener("pointerleave",g),()=>{window.removeEventListener("pointermove",c),document.documentElement.removeEventListener("pointerleave",g),cancelAnimationFrame(l),n.style.removeProperty("--px"),n.style.removeProperty("--py")}},[e,t])}function Ei(e){let t=e.rings.counts;return{title:`${e.label} · ${e.job} · OpenAdapt Receipt`,description:`${e.app}, ${e.job}: ${e.label}. ${t.stepsPassed} of ${t.steps} steps, ${t.checksPassed} of ${t.checks} screen checks${t.readbacksPassed?`, ${t.readbacksPassed} of ${t.readbacks} record checks confirmed`:""}. A signed run report you can check in your browser.`}}function vr({seal:e,host:t={}}){let{loadFiles:n=null,Link:o="a",links:r={},copyHref:a=null,live:i=!0,kicker:l=null,footer:d=null,trustWords:c="signed by the pinned key",unchanged:g="The published files are unchanged; this was a copy in your browser.",canonicalOrigin:h=null,chrome:p=!0,map:u={},signer:f=null,mediaNote:v="From this computer's run folder: not part of the receipt, never uploaded"}=t,{rings:m,seal:b,tone:y,label:_,line:w,job:N,app:M,startedAt:S,stopReason:A,media:O,tamper:I,runs:$,referral:C,referrals:R,files:k,keys:B,authorization:H,authorizedLine:G,authTiming:V,stopNote:me,program:Q,commands:Me=null,irisSeed:ee}=e,ce=Lp(),[Ee,te]=D("build"),[Y,K]=D(null),[xe,we]=D(null),[Qe,uo]=D(ee),qt=!!(k.anchor||k.tsa),[T,L]=D(null),[de,q]=D(null),[Z,Te]=D(null),[Ie,Ce]=D(!1),[J,ue]=D(null),[et,_t]=D(null),[Zt,wn]=D(0),[Li,xr]=D(null),[_r,fo]=D(!1),[Sn,Di]=D(Me),[Yt,Fi]=Fp(p),mt=Dp("(min-width: 900px)"),[Nn,Rt]=D("summary"),[Hi,ji]=D(!1),[ho,kr]=D(!1),[go,wr]=D(50),[Sr,Gi]=D(!1),En=X(null),mo=X(null),Jt=X(0);Gp(mo,!ce);let Ui=X(null),$e=ne(()=>qs(m),[m]),[Je,Xt]=D(null),[tt,bt]=D(!1),[bo,Bi]=D(1),Oe=Je!==null,nt=Oe?$e[Je]:null,Ki=ne(()=>nt?Zs(nt,m):null,[nt,m]);U(()=>{if(!p)return;let{body:x,documentElement:P}=document,W=[x.style.background,P.style.background];return x.style.background="var(--oa-canvas)",P.style.background="var(--oa-canvas)",()=>{x.style.background=W[0],P.style.background=W[1]}},[p]),U(()=>{try{let x=Number(window.localStorage.getItem("oa-seal-split"));x>=30&&x<=70&&wr(x)}catch{}},[]);let Qt=Se(x=>{let P=Math.max(30,Math.min(70,Math.round(x)));wr(P);try{window.localStorage.setItem("oa-seal-split",String(P))}catch{}},[]);U(()=>{let x=()=>{let P=jp(m.steps.length);P.tab&&Rt(P.tab),P.step!=null&&(ue(P.step),wn(P.step),P.tab||Rt("evidence"))};return x(),Gi(!0),window.addEventListener("hashchange",x),()=>window.removeEventListener("hashchange",x)},[m.steps.length]),U(()=>{Nn==="program"&&ji(!0)},[Nn]),U(()=>{let x=window.location.origin;Me&&h&&/^https?:/.test(x)&&x!==h&&Di(Me.split(h).join(x))},[Me,h]);let Wi=async(x,P,W)=>{if(x.sealOk&&!x.ok)return{...x,record:null};if(!x.sealOk&&(W.anchor||W.authorization))return{...x,ok:!1,reason:W.authorization?"auth_missing":"anchor_missing",record:null};if(!P.receiptKeys)return{...x,ok:!1,reason:"unknown_key",record:null};let oe;try{oe=JSON.parse(P.receiptText)}catch{return{...x,ok:!1,reason:"malformed",record:null}}let Le=await Is(oe,P.receiptKeys);if(!Le.ok)return{...x,ok:!1,reason:Le.reason,record:Le};let be=Le.statement.subject.find(ot=>ot.name==="report.json");return!be||be.digest.sha256!==await Re(P.report)?{...x,ok:!1,reason:"subject_mismatch",record:Le}:{...x,ok:!0,reason:null,record:Le}},en=Se(async x=>{let P=++Jt.current;Te(x||null),K(null),we(null),L(null),Xt(null),bt(!1),te("verify");let W=new Promise(be=>setTimeout(be,ce?0:Rp)),oe,Le=null;try{En.current=En.current||await(n?n():Cs(k,H));let be=x?zs(En.current,x):En.current,ot={anchor:!!k.anchor,authorization:!!H};oe=await ks(be,B,{requireAnchor:ot.anchor,requireAuthorization:ot.authorization}),be.receiptText&&(oe=await Wi(oe,be,ot)),Le=qt?await Bs(be,B):null;try{let wo=await gn(JSON.parse(be.sealText)),il=await Re(new TextEncoder().encode(`${await Re(be.report)}${wo}`));P===Jt.current&&uo(il)}catch{}}catch{oe={ok:!1,reason:"not_loaded",steps:[]}}P===Jt.current&&we(oe.subject?.sha256??null),await W,P===Jt.current&&(L(Le),K(oe),te(oe.ok?"valid":oe.reason==="unsupported"||oe.reason==="not_loaded"?"rest":"broken"))},[k,B,H,ce,qt,n]),[Vi,qi]=D("unverified");U(()=>{if(!i||!H||!Y?.ok||!Y.authorizedBy?.publicKey)return;let x=!1;return ps(H.login,Y.authorizedBy.publicKey).then(P=>{x||qi(P)}),()=>{x=!0}},[H,Y,i]);let vo=V??Y?.timing??null,yo=H&&(G||(vo==="before_run"||vo==="after_run")&&Y?.ok)?hs(H.login,vo,H.anchorTime??Y?.authAnchorTime,Vi):null,Nr=X(!1);U(()=>{!i||!T?.rekor?.ok||Z||Nr.current||(Nr.current=!0,q("checking"),Ws(T.rekor.entry).then(q))},[T,Z,i]),U(()=>{ce&&te("rest");let x=setTimeout(()=>en(null),ce?0:mi+450);return()=>clearTimeout(x)},[ce]),U(()=>{if(!Oe||!tt)return;if(Je>=$e.length-1){bt(!1);return}let x=setTimeout(()=>Xt(P=>Math.min($e.length-1,P+1)),$e[Je].dwell/bo);return()=>clearTimeout(x)},[Oe,tt,Je,$e,bo]);let xo=Se(()=>{Jt.current+=1,Te(null),te("replay"),ue(null),_t(null),Rt(x=>x==="program"?x:"evidence"),Xt(x=>x===null||x>=$e.length-1?0:x),bt(!0)},[$e.length]),kt=Se((x,P=!1)=>{te("replay"),Xt(Math.max(0,Math.min($e.length-1,x))),P||bt(!1)},[$e.length]),Er=()=>{Xt(null),bt(!1),te(Y?.ok?"valid":Y?"broken":"rest")},Tr=()=>kt(Ys($e,Je??-1),tt),tn=x=>{let P=nt?nt.step:-1,W=Math.max(0,Math.min($e.at(-1).step,P+x));kt(to($e,W))};U(()=>{let x=P=>{let W=P.target;if(W&&(W.closest?.("input, textarea, select, [contenteditable]")||P.metaKey||P.ctrlKey||P.altKey))return;let oe=!!W?.closest?.('[role="tablist"], [role="separator"], [data-steplist], .opg-root'),Le=W?.closest?.("button, a, summary");if(!(oe&&P.key!=="j"&&P.key!=="k")){if(P.key===" "&&!Le&&!W?.closest?.("[data-step]"))P.preventDefault(),tt?bt(!1):xo();else if(Oe&&P.key==="ArrowRight"&&!W?.closest?.("[data-step]"))P.preventDefault(),P.shiftKey?Tr():tn(1);else if(Oe&&P.key==="ArrowLeft"&&!W?.closest?.("[data-step]"))P.preventDefault(),tn(-1);else if(Oe&&P.key==="Escape")Er();else if((P.key==="j"||P.key==="k")&&!P.shiftKey){P.preventDefault();let be=P.key==="j"?1:-1;if(Oe)tn(be);else{let ot=m.steps.length,wo=J??(be>0?-1:ot);lt(Math.max(0,Math.min(ot-1,wo+be)))}}}};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)});let Tn=Oe?nt.step:J??et,nn=Tn!=null?m.steps[Tn]:null,$r=Se((x,P={})=>{P.focus&&wn(x),Je!==null?kt(to($e,x)):_t(x)},[Je,$e,kt]),lt=Se((x,{keepTab:P=!1}={})=>{Je!==null?kt(to($e,x)):ue(x),wn(x),P||Rt(W=>W==="program"?W:"evidence")},[Je,$e,kt]),Zi=x=>{let P=m.steps.length,W={ArrowRight:1,ArrowDown:1,ArrowLeft:-1,ArrowUp:-1},oe=null;if(x.key in W)oe=(Zt+W[x.key]+P)%P;else if(x.key==="Home")oe=0;else if(x.key==="End")oe=P-1;else if(x.key==="Escape"){ue(null),_t(null),x.currentTarget.blur();return}else if(x.key==="Enter"||x.key===" "){x.preventDefault(),lt(Zt);return}else return;x.preventDefault(),wn(oe),$r(oe),mo.current?.querySelector(`[data-step="${oe}"]`)?.focus()},We=Nn==="program"&&mt?"summary":Nn,_o=Oe?null:J;U(()=>{if(!Sr||tt)return;let x=_i(We,_o);if(!(x===window.location.hash||!x&&!window.location.hash))try{window.history.replaceState(window.history.state,"",`${window.location.pathname}${window.location.search}${x}`)}catch{}},[We,_o,Sr,tt]);let Yi=async()=>{try{await navigator.clipboard.writeText(`${a}${_i(We,_o)}`),fo(!0),setTimeout(()=>fo(!1),2200)}catch{fo(!1)}},Pe=m.counts,Ar=[{ring:"steps",big:`${Pe.stepsPassed}/${Pe.steps}`,small:m.stoppedAt==null?"steps passed":`steps, stopped at ${m.stoppedAt+1}`},{ring:"checks",big:`${Pe.checksPassed}/${Pe.checks}`,small:Pe.checksFailed?`screen checks, ${Pe.checksFailed} failed`:"screen checks"},{ring:"readbacks",big:`${Pe.readbacksPassed}/${Pe.readbacks}`,small:Pe.readbacksFailed?`record checks, ${Pe.readbacksFailed} failed`:Pe.readbacksPassed?"record checks confirmed":"record checks, not reached"},{ring:"identity",big:`${Pe.identityPassed}/${Pe.identity}`,small:"right-record checks"}],Mr=S?Js(S):null,Rr=l??(C?`Referral ${C} of ${R}`:null),on=!!Z,_e=Ee==="verify"||Ee==="build"?null:Y?.ok?"valid":Y?.reason==="unsupported"?"unsupported":Y?.reason==="not_loaded"?"not_loaded":Y?"fails":null,Ir=(x,P)=>x?P?P.ok?"pass":"fail":"pending":null,Cr=qt?{rekor:Ir(k.anchor,T?.rekor),tsa:Ir(k.tsa,T?.tsa)}:null,Ji=`The receipt of this run: ${Ar.map(x=>`${x.big} ${x.small}`).join("; ")}.`,It=Ee==="verify"||Ee==="build",Ct=nn,Xi=Ct?`Step ${Ct.i+1} of ${m.steps.length}${Ct.section?` · ${Ct.section}`:""}${Ct.t0!=null?` · at ${Vt(Ct.t0)}`:""}`:null,ko=Oe?nt.step:J,ze=ko!=null?m.steps[ko]:null,Qi=m.steps.filter(x=>x.status!=="not_reached").length,Pr=_e===null?{state:"pending",text:Ee==="build"?"Assembling":"Checking signature"}:_e==="valid"?{state:"valid",text:on?"Restored · signature valid":"Signature valid"}:_e==="fails"?{state:"fails",text:on?"Changed copy fails":"Signature check fails"}:_e==="unsupported"?{state:"unchecked",text:"Report matches · signature not checked here"}:{state:"unchecked",text:"Not checked here"},Or=["summary","program","steps","evidence","raw"],wt=mt?Ni:Or,el=x=>{let P=wt.indexOf(We),W={ArrowRight:1,ArrowLeft:-1},oe=null;if(x.key in W)oe=wt[(P+W[x.key]+wt.length)%wt.length];else if(x.key==="Home")oe=wt[0];else if(x.key==="End")oe=wt[wt.length-1];else return;x.preventDefault(),Rt(oe),x.currentTarget.querySelector(`[data-tab="${oe}"]`)?.focus()},zr=X(null),Lr=X(null),Dr=X(null);U(()=>{let x=Lr.current,P=Dr.current;if(!x||!P||typeof ResizeObserver>"u")return;let W=new ResizeObserver(()=>P.style.setProperty("--top-h",`${x.offsetHeight}px`));return W.observe(x),()=>W.disconnect()},[]);let tl=x=>{let P={ArrowLeft:-2,ArrowRight:2};if(x.key in P)Qt(go+P[x.key]);else if(x.key==="Home")Qt(30);else if(x.key==="End")Qt(70);else if(x.key==="Enter")kr(W=>!W);else return;x.preventDefault()},nl=x=>{let P=zr.current;if(!P||x.button!==0)return;x.preventDefault();let W=x.currentTarget;W.setPointerCapture?.(x.pointerId);let oe=P.getBoundingClientRect(),Le=ot=>Qt((ot.clientX-oe.left)/oe.width*100),be=()=>{W.removeEventListener("pointermove",Le),W.removeEventListener("pointerup",be),W.removeEventListener("pointercancel",be)};W.addEventListener("pointermove",Le),W.addEventListener("pointerup",be),W.addEventListener("pointercancel",be)},ol=mt||We==="program"||Hi,rl=f==="demo"||b?.issuer==="demo",Pt=Y?.record??null,Fr=Pt?_e===null?{state:"pending",text:"Checking who signed it"}:Pt.ok&&_e==="valid"?{state:Pt.demo?"demo":"signed",text:Pt.signerLines.join(" · ")}:Pt.reason==="unknown_signer"?{state:"unknown",text:"Not verified: unknown signer"}:{state:"fails",text:Pt.signerLines?.[0]||"Not verified"}:_e===null?{state:"pending",text:"Checking who signed it"}:_e==="valid"?rl?{state:"demo",text:"Demo key: checks only in this demo"}:f==="this_computer"?{state:"signed",text:"Signed by this computer"}:{state:"signed",text:"Signed by a pinned key"}:Pp.has(Y?.reason)?{state:"unknown",text:"Not verified: unknown signer"}:_e==="fails"?{state:"fails",text:"Not verified: the signature check failed"}:{state:"unchecked",text:"Not verified here"},Hr=!!(k?.receiptText||Y?.record),al=!Hr&&typeof b?.schema=="string"&&/^openadapt\.(local-seal|public-seal)\//.test(b.schema),sl=_e===null?s("span",{className:E.pending,children:Ee==="build"?"Assembling the receipt from the report":"Checking the Ed25519 signature in your browser"}):_e==="valid"?s(ae,{children:[s("b",{children:"Valid."})," This is the report exactly as the run wrote it, ",c,"."]}):_e==="unsupported"?s(ae,{children:[s("b",{children:"The report matches."})," This browser can't check Ed25519 signatures; ",Sn?"use the commands under Raw.":"check it from a terminal: openadapt verify RUN_FOLDER."]}):_e==="not_loaded"?s(ae,{children:[s("b",{children:"The files didn't load,"})," so nothing was checked here. ",Sn?"Use the commands under Raw.":"Check it from a terminal: openadapt verify RUN_FOLDER."]}):s(ae,{children:[s("b",{children:"Fails."})," ",bi(Y.reason)," ",s("code",{className:E.code,children:Y.reason})]});return s(ae,{children:[s("a",{className:E.skip,href:"#main",onClick:x=>{x.preventDefault(),document.getElementById("main")?.focus()},children:"Skip to content"}),s("div",{ref:Dr,className:E.page,"data-tone":y,"data-phase":Ee,"data-theme":p?void 0:Yt,"data-layout":mt?"split":"stack","data-expanded":mt&&ho?"1":void 0,"data-view":We,style:{"--split":`${go}%`},children:[s("header",{className:E.top,ref:Lr,children:[r.home?s(o,{href:r.home.href,className:E.home,"aria-label":r.home.label,children:[s(ao,{className:E.mark}),s("span",{children:r.home.label})]}):s("span",{className:E.home,children:[s(ao,{className:E.mark}),s("span",{children:"OpenAdapt"})]}),s("span",{className:E.crumb,children:[s("span",{children:"Signed run report"}),Rr?s("span",{children:Rr}):null]}),$?.length?s("nav",{className:E.runs,"aria-label":"The other runs",children:$.map(x=>s(o,{href:x.href,className:E.run,"data-tone":x.tone,"aria-current":x.sealId===e.sealId?"page":void 0,title:`Referral ${x.referral}: ${x.label}`,children:[s("span",{className:E.runSeal,"aria-hidden":"true",children:s(ro,{rings:x.rings,tone:x.tone,digest:x.digest,variant:"emblem",phase:"rest",still:!0,label:""})}),s("span",{className:E.runText,children:[s("b",{children:x.referral}),s("span",{children:x.label})]})]},x.sealId))}):null,s("span",{className:E.topEnd,children:[s("span",{className:E.chip,"data-chip":Pr.state,role:"status",children:[s("span",{className:E.chipDot,"aria-hidden":"true"}),Pr.text]}),a?s("button",{type:"button",className:E.iconBtn,onClick:Yi,title:"Copy a link to this view","aria-label":_r?"Link copied":"Copy link",children:[s(Up,{}),s("span",{className:E.wideOnly,children:_r?"Copied":"Copy link"})]}):null,s("button",{type:"button",className:E.iconBtn,onClick:Fi,"aria-label":`Switch to the ${Yt==="dark"?"light":"dark"} theme`,title:`Switch to the ${Yt==="dark"?"light":"dark"} theme`,children:s(Bp,{theme:Yt})})]})]}),s("div",{className:E.app,ref:zr,children:[s("main",{id:"main",tabIndex:-1,className:E.hero,"aria-labelledby":"seal-h1",children:[s("section",{className:E.stage,ref:mo,"aria-label":"The receipt",tabIndex:-1,onMouseLeave:()=>_t(null),children:s("div",{className:E.tilt,ref:Ui,children:s(ro,{rings:m,tone:y,digest:Qe,phase:Ee,buildMs:mi,active:Oe?null:Tn,focusIndex:Zt,onActive:$r,onPick:lt,onKey:Zi,ringFocus:Li,witnesses:Cr,lit:Ki,spot:nt?.spotlight||null,label:Ji})})}),s("div",{className:E.heading,children:[s("h1",{id:"seal-h1",className:E.outcome,children:_}),A?s("p",{className:E.reason,children:zp(A)}):null,s("p",{className:E.meta,children:[s("span",{children:N}),s("span",{children:M}),Mr?s("span",{children:Mr}):null]}),s("p",{className:E.verdict,"data-verdict":_e||"pending","aria-live":"polite",children:sl}),s("p",{className:E.signer,"data-signer":Fr.state,children:s("span",{children:Fr.text})}),on&&_e==="fails"?s("div",{className:E.changed,"data-changed":"",children:[s("p",{className:E.changeHead,children:[s("b",{children:"This changed copy fails:"})," ",Z.field==="model_calls"?"model calls":"outcome"," ",Z.from," → ",Z.to,". The receipt no longer matches."]}),s("p",{className:E.change,children:["Changed in a copy of the ",Z.target==="seal"?"receipt":"report",": ",s("code",{children:Z.field})," ",s("del",{children:Z.from})," → ",s("ins",{children:Z.to}),"."]}),s("p",{className:E.change,children:g}),s("div",{className:E.actions,children:[s("button",{type:"button",className:E.primary,onClick:()=>en(null),disabled:It,children:"Restore"}),s("button",{type:"button",className:E.ghost,"aria-expanded":Ie,"aria-controls":"receipt-changes",onClick:()=>Ce(x=>!x),children:"Try another change"})]}),s("div",{id:"receipt-changes",className:E.another,role:"group","aria-label":"Other changes",hidden:!Ie,children:I.filter(x=>x.id!==Z.id).map(x=>s("button",{type:"button",className:E.tchip,disabled:It,onClick:()=>en(x),children:[s("span",{children:x.label}),s("code",{children:[x.from," → ",x.to]})]},x.id))})]}):null,s("div",{className:E.actions,children:[s("button",{type:"button",className:E.primary,onClick:tt?()=>bt(!1):xo,disabled:It,children:[s("span",{"aria-hidden":"true",children:tt?"❚❚":"▶"}),tt?"Pause the run":Oe?"Resume the run":"Play the run"]}),s("button",{type:"button",className:E.ghost,onClick:()=>en(null),disabled:It,children:"Verify"}),on&&_e==="fails"?null:s("button",{type:"button",className:E.ghost,onClick:()=>{Ce(!1),en(I[0])},disabled:It||!I.length,children:"Try changing it"})]})]}),s("div",{className:E.dock,children:[s(Wp,{frames:$e,frame:Je,playing:tt,speed:bo,busy:It,rings:m,onPlay:xo,onPause:()=>bt(!1),onSeek:kt,onNext:Tr,onSpeed:Bi,onClose:Er}),s("p",{className:E.stepLine,"data-step":nn?nn.i:"","aria-live":"polite",children:Xi||(_e==="valid"?`✓ Signature valid over this exact report · ${Qi} steps`:_e==="fails"?`✗ ${bi(Y?.reason)}`:" ")})]})]}),s("section",{className:E.mapPane,"aria-labelledby":"map-h",id:"seal-panel-program",role:mt?void 0:"tabpanel",children:[s("div",{className:E.paneHead,children:[s("h2",{id:"map-h",children:"Program steps for this run"}),mt?s("button",{type:"button",className:E.iconBtn,"aria-pressed":ho,onClick:()=>kr(x=>!x),children:ho?"Show details":"Expand map"}):null]}),ol?s(mr,{program:Q,map:{title:`${N} · ${M}`,...u},step:Tn,status:nn?nn.status==="stopped"?"stopped":nt?.stage==="done"?"saved":"running":null,onPick:x=>lt(x),anchor:m.anchor,sealRun:{rings:m,tone:y,irisSeed:Qe,referral:C},sealLine:Xs({rings:m,label:_,stopReason:A},_e==="valid"),theme:Yt,fill:mt}):null]}),s("div",{className:E.resizer,role:"separator","aria-orientation":"vertical","aria-label":"Resize the program map","aria-valuenow":go,"aria-valuemin":30,"aria-valuemax":70,tabIndex:0,onKeyDown:tl,onPointerDown:nl,onDoubleClick:()=>Qt(50),title:"Drag, or use the arrow keys. Enter expands the map."}),s("div",{className:E.tabs,role:"tablist","aria-label":"Details",onKeyDown:el,children:Or.map(x=>s("button",{type:"button",role:"tab",id:`seal-tab-${x}`,"data-tab":x,"aria-selected":We===x,"aria-controls":`seal-panel-${x}`,tabIndex:We===x?0:-1,onClick:()=>Rt(x),children:[Hp[x],x==="steps"?s("span",{className:E.count,children:m.steps.length}):null,x==="evidence"&&ze?s("span",{className:E.count,children:ze.i+1}):null]},x))}),s("div",{className:E.panels,children:[s("section",{id:"seal-panel-summary",role:"tabpanel","aria-labelledby":"seal-tab-summary",hidden:We!=="summary",className:E.panel,children:[s("p",{className:E.line,children:w}),H&&yo?s("p",{className:E.by,children:s("a",{href:`https://github.com/${H.login}`,rel:"noopener noreferrer",children:yo})}):null,s("dl",{className:E.stats,"aria-label":"What the receipt shows",children:Ar.map(x=>s("div",{"data-ring":x.ring,onMouseEnter:()=>xr(x.ring),onMouseLeave:()=>xr(null),children:[s("dt",{children:[s("span",{className:E.swatch,"aria-hidden":"true"}),x.small]}),s("dd",{children:x.big})]},x.ring))}),s("p",{className:E.calls,children:Pe.modelCalls==null?`The program ran for ${Vt(m.runMs)}.`:`The program ran for ${Vt(m.runMs)} and made ${Pe.modelCalls} AI model calls.`}),s("h2",{className:E.sub,children:"The signature check"}),s("div",{className:E.proof,children:[s(cr,{label:on&&Z.target==="report"?"This copy of report.json":"report.json, in this browser",from:b.signature,to:xe,against:b.subject_sha256,running:Ee==="verify",still:ce}),s("div",{className:E.signed,children:[s("span",{className:E.proofLabel,children:"Signed in the receipt"}),s("code",{className:E.hex,children:b.subject_sha256})]})]}),s("p",{className:E.foot,children:[d||"The signature comes from the machine that ran it: it shows the report hasn't changed since the run."," ",r.programMap?s(o,{href:r.programMap.href,children:r.programMap.label}):null," ",s("a",{href:r.docs||"https://docs.openadapt.ai/reference/receipts-and-seals/",children:"How receipts work"})]})]}),s("section",{id:"seal-panel-steps",role:"tabpanel","aria-labelledby":"seal-tab-steps",hidden:We!=="steps",className:E.panel,children:s(Kp,{rings:m,active:ko,onPick:x=>lt(x),onFocusStep:x=>lt(x,{keepTab:!0})})}),s("section",{id:"seal-panel-evidence",role:"tabpanel","aria-labelledby":"seal-tab-evidence",hidden:We!=="evidence",className:E.panel,children:ze?s(ae,{children:[s("div",{className:E.evHead,children:[s("p",{className:E.evTitle,children:[s("span",{className:E.evNum,children:["Step ",ze.i+1," of ",m.steps.length]}),ze.section?s("span",{children:ze.section}):null,ze.t0!=null?s("span",{children:["at ",Vt(ze.t0)]}):null]}),s("span",{className:E.evNav,children:[s("button",{type:"button",className:E.iconBtn,onClick:()=>Oe?tn(-1):lt(Math.max(0,ze.i-1)),disabled:ze.i===0,"aria-label":"Previous step",title:"Previous step (k)",children:"‹"}),s("button",{type:"button",className:E.iconBtn,onClick:()=>Oe?tn(1):lt(Math.min(m.steps.length-1,ze.i+1)),disabled:ze.i===m.steps.length-1,"aria-label":"Next step",title:"Next step (j)",children:"›"})]})]}),s(Vp,{step:ze,rings:m,media:O[ze.i],frame:nt,stopReason:A,stopNote:me,mediaNote:v})]}):s("div",{className:E.empty,children:[s("p",{children:["Pick a step on the map, on the receipt or in Steps to see its checks",O.some(x=>x&&(x.crop||x.frame))?", its pictures":""," and its record checks."]}),m.anchor?s("button",{type:"button",className:E.ghost,onClick:()=>lt(m.anchor.step),children:["Show the step the receipt covers (step ",m.anchor.step+1,")"]}):null]})}),s("section",{id:"seal-panel-raw",role:"tabpanel","aria-labelledby":"seal-tab-raw",hidden:We!=="raw",className:E.panel,children:[al?s("p",{className:E.older,"data-format":"",children:["Format: ",b.schema.replace(/^openadapt\./,""),", still verifies"]}):Hr?s("p",{className:E.older,"data-format":"",children:"Format: record/run/v1"}):null,s(Zp,{seal:b,files:k,links:r,witnesses:Cr,witness:T,live:Z?null:de,authorization:H,authorizedLine:yo}),Sn?s(ae,{children:[s("h2",{className:E.sub,children:e.commandsLabel||"Check the same files on your computer"}),s("pre",{className:E.cmds,tabIndex:0,children:s("code",{children:Sn})})]}):null]})]})]})]})]})}function Up(){return s("svg",{viewBox:"0 0 24 24",width:"15",height:"15","aria-hidden":"true",children:s("path",{d:"M10 14a4.5 4.5 0 0 0 6.4 0l3-3a4.5 4.5 0 0 0-6.4-6.4l-1 1M14 10a4.5 4.5 0 0 0-6.4 0l-3 3a4.5 4.5 0 0 0 6.4 6.4l1-1",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round"})})}function Bp({theme:e}){return e==="dark"?s("svg",{viewBox:"0 0 24 24",width:"16",height:"16","aria-hidden":"true",children:[s("circle",{cx:"12",cy:"12",r:"4.2",fill:"none",stroke:"currentColor",strokeWidth:"1.8"}),s("path",{d:"M12 2.5v2.2M12 19.3v2.2M2.5 12h2.2M19.3 12h2.2M5.3 5.3l1.6 1.6M17.1 17.1l1.6 1.6M5.3 18.7l1.6-1.6M17.1 6.9l1.6-1.6",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round"})]}):s("svg",{viewBox:"0 0 24 24",width:"16",height:"16","aria-hidden":"true",children:s("path",{d:"M20 14.5A8.5 8.5 0 0 1 9.5 4a8.5 8.5 0 1 0 10.5 10.5Z",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinejoin:"round"})})}function Kp({rings:e,active:t,onPick:n,onFocusStep:o}){let r=X(null),[a,i]=D(t??0);U(()=>{t!=null&&i(t)},[t]);let l=e.steps.length,d=c=>{let g={ArrowDown:1,ArrowUp:-1},h=null;if(c.key in g)h=Math.max(0,Math.min(l-1,a+g[c.key]));else if(c.key==="Home")h=0;else if(c.key==="End")h=l-1;else return;c.preventDefault(),i(h),o(h),r.current?.querySelector(`[data-row="${h}"]`)?.focus()};return s("ol",{className:E.steps,ref:r,"data-steplist":"",onKeyDown:d,"aria-label":"The run's steps",children:e.steps.map(c=>{let g=e.identity.find(u=>u.step===c.i),h=e.readbacks.filter(u=>u.step===c.i),p=c.checks.passed+c.checks.failed;return s("li",{children:s("button",{type:"button","data-row":c.i,"data-status":c.status,"aria-current":t===c.i?"step":void 0,tabIndex:a===c.i?0:-1,onClick:()=>n(c.i),children:[s("span",{className:E.sNum,children:String(c.i+1).padStart(2,"0")}),s("span",{className:E.sMark,"aria-hidden":"true",children:c.status==="passed"?"✓":c.status==="stopped"?"■":"·"}),s("span",{className:E.sName,children:[c.name,c.section?s("small",{children:c.section}):null]}),s("span",{className:E.sTags,children:[g?s("span",{"data-ok":g.result==="passed"?"1":"0",children:"record"}):null,p?s("span",{"data-ok":c.checks.failed?"0":"1",children:[p," ",p===1?"check":"checks"]}):null,h.length?s("span",{"data-ok":h.some(u=>u.result==="failed")?"0":"1",children:[h.length," record ",h.length===1?"check":"checks"]}):null]}),s("span",{className:E.srOnly,children:[c.status==="passed"?", passed":c.status==="stopped"?", stopped here":", not reached",g?", checks the right record":""]})]})},c.i)})})}function Wp({frames:e,frame:t,playing:n,speed:o,busy:r,rings:a,onPlay:i,onPause:l,onSeek:d,onNext:c,onSpeed:g,onClose:h}){let p=t??0,u=e[p],f=u?a.steps[u.step]?.t0??0:0;return s("div",{className:E.player,"data-active":t!==null?"1":void 0,children:[s("button",{type:"button",className:E.pBtn,onClick:n?l:i,disabled:r,"aria-label":n?"Pause":"Play the run",children:n?"❚❚":"▶"}),s("button",{type:"button",className:E.pBtn,onClick:c,disabled:r,"aria-label":"Next highlight",title:"Next highlight (Shift + →)",children:"⏭"}),s("input",{className:E.scrub,type:"range",min:"0",max:e.length-1,value:p,disabled:r,"aria-label":"Position in the run","aria-valuetext":u?`Step ${u.step+1} of ${a.steps.length}`:void 0,onChange:v=>d(Number(v.target.value))}),s("span",{className:E.pTime,children:[Vt(f)," / ",Vt(a.runMs)]}),s("span",{className:E.speeds,role:"group","aria-label":"Speed",children:Ip.map(v=>s("button",{type:"button","aria-pressed":o===v,onClick:()=>g(v),children:[v,"×"]},v))}),t!==null?s("button",{type:"button",className:E.pBtn,onClick:h,"aria-label":"Leave the replay",children:"×"}):null]})}function Vp({step:e,rings:t,media:n,frame:o,stopReason:r,stopNote:a,mediaNote:i}){let l=t.readbacks.filter(f=>f.step===e.i),d=t.identity.find(f=>f.step===e.i),c=e.checks.passed+e.checks.failed,g=!!o,h=g?o.step===e.i?o.readbacks:0:l.length,p=g?o.spotlight:null,u=[["Action",e.name],["Result",e.status==="passed"?"✓ Passed":e.status==="stopped"?`■ Stopped here${r?`: ${r}`:""}`:"Not reached",e.status==="passed"?"ok":e.status==="stopped"?"halt":"ghost","stop"],d?["Right record",d.result==="passed"?"✓ Confirmed before acting":d.result==="not_reached"?"Not reached":"✗ Not confirmed",d.result==="passed"?"ok":"ghost","identity"]:null,c?["Screen checks",e.checks.failed?`■ ${e.checks.failed} of ${c} failed`:`✓ ${e.checks.passed} of ${c} passed`,e.checks.failed?"halt":"ok","checks"]:null,l.length?["Read-back",Op(l.filter(f=>f.result==="passed").length,l.length),l.some(f=>f.result==="failed")?"halt":l.every(f=>f.result==="passed")?"ok":"ghost","save"]:null].filter(Boolean);return s("aside",{className:E.inspector,"data-status":e.status,"data-step":e.i,"data-spot":p||void 0,"aria-live":"polite",children:[s("div",{className:E.inMain,children:[s("table",{className:E.kv,children:s("tbody",{children:u.map(([f,v,m,b])=>s("tr",{"data-tone":m,"data-spot":p&&p===b?"1":void 0,children:[s("th",{scope:"row",children:f}),s("td",{children:v})]},f))})}),p==="stop"&&a?s("p",{className:E.spotNote,children:a}):null,n&&(n.crop||n.frame)?s("div",{className:E.shots,children:[n.crop?s("figure",{children:[s("img",{src:n.crop,alt:"The step's target as recorded, synthetic data",width:"160",height:"64",loading:"lazy"}),s("figcaption",{children:"Recorded"})]}):null,n.frame?s("figure",{children:[s("img",{src:n.frame,alt:"The screen after this step in this run, synthetic data",width:"640",height:"400",loading:"lazy"}),s("figcaption",{children:"This run"})]}):null,i?s("p",{className:E.shotsNote,"data-media-note":"",children:i}):null]}):null]}),l.length?s("table",{className:E.readTable,"data-count":h,children:[s("caption",{children:"Each saved field was read back from the record after the save. The values aren't published."}),s("thead",{children:s("tr",{children:[s("th",{scope:"col",children:"Field"}),s("th",{scope:"col",children:"Expected"}),s("th",{scope:"col",children:"Read back"}),s("th",{scope:"col","aria-label":"Result"})]})}),s("tbody",{children:l.map((f,v)=>{let m=vnew Date(e*1e3).toISOString().replace("T"," ").replace(/\.\d+Z$/," UTC"),ki=e=>String(e).replace("T"," ").replace(/(\.\d+)?Z$/," UTC"),br=(e,t=16)=>`${String(e).slice(0,t)}…`,wi={anchor_mismatch:"The log entry isn't for this receipt.",anchor_key_mismatch:"The log entry isn't signed by the receipt's key.",anchor_bad_signature:"The log entry's signature doesn't match.",anchor_unknown_log:"The entry names a log this site doesn't pin.",anchor_bad_timestamp:"The log's signed timestamp doesn't verify.",anchor_bad_inclusion:"The inclusion proof doesn't reach the log's tree.",anchor_bad_checkpoint:"The log's signed checkpoint doesn't verify.",anchor_malformed:"The log entry isn't well formed.",tsa_imprint_mismatch:"The timestamp stamps a different digest from this receipt's.",tsa_bad_signature:"The timestamp's signature doesn't verify.",tsa_untrusted:"The timestamp doesn't chain to the pinned Sigstore root.",tsa_expired:"The timestamp's certificate wasn't valid at that time.",tsa_not_timestamping:"The signing certificate isn't for time stamping.",tsa_content_mismatch:"The timestamp's signed content doesn't match.",tsa_malformed:"The timestamp isn't well formed.",tsa_token_missing:"The timestamp's token file is missing.",tsa_token_mismatch:"The timestamp's token file isn't the one its record names."};function Zp({seal:e,files:t,links:n,witnesses:o,witness:r,live:a,authorization:i,authorizedLine:l}){let d=r?.rekor,c=r?.tsa,g=[["Outcome",s("code",{children:e.outcome},"o"),null],["Report SHA-256",s("code",{title:e.subject_sha256,children:br(e.subject_sha256,24)},"d"),null],["Signed by",s("code",{children:e.key_id},"k"),null],["Signature",s("code",{title:e.signature,children:br(e.signature,24)},"s"),"Ed25519"],["Issued",ki(e.issued_at),null],...e.scope_item?[["Scope",s("code",{children:e.scope_item},"sc"),null]]:[]];return o?.rekor&&g.push(["Public log",o.rekor==="pending"?"Checking…":d?.ok?s("span",{children:["Sigstore Rekor entry"," ",s("a",{href:Ks(d.logIndex),rel:"noopener noreferrer",children:d.logIndex}),", logged ",qp(d.integratedTime),", log ",s("code",{children:br(d.logId,8)}),". The inclusion proof, signed timestamp and checkpoint verify against the pinned Rekor key.",a==="match"?" This entry matches the public log.":a==="differs"?" The public log serves a different entry.":""]},"r"):s("span",{children:[wi[d?.reason]||"The log entry doesn't verify."," ",s("code",{children:d?.reason})]},"rf"),o.rekor]),o?.tsa&&g.push(["Timestamp",o.tsa==="pending"?"Checking…":c?.ok?s("span",{children:["Sigstore Timestamp Authority (RFC 3161): ",ki(c.genTime),", over this receipt's SHA-256, chained to the pinned"," ",s("a",{href:"https://timestamp.sigstore.dev/api/v1/timestamp/certchain",rel:"noopener noreferrer",children:"Sigstore TSA root"}),"."]},"t"):s("span",{children:[wi[c?.reason]||"The timestamp doesn't verify."," ",s("code",{children:c?.reason})]},"tf"),o.tsa]),i&&l&&g.push(["Authorized",s("span",{children:[l,", with an SSH key"," ",s("a",{href:`https://github.com/${i.login}.keys`,rel:"noopener noreferrer",children:["GitHub lists for @",i.login]}),"."]},"a"),"pass"]),s("section",{className:E.record,"aria-labelledby":"record-h",children:[s("h2",{id:"record-h",className:E.recordH,children:"The signed record"}),s("table",{className:E.recordTable,children:s("tbody",{children:g.map(([h,p,u])=>s("tr",{"data-state":u||void 0,children:[s("th",{scope:"row",children:[u==="pass"||u==="fail"||u==="pending"?s("span",{className:E.wMark,"aria-hidden":"true"}):null,h]}),s("td",{children:p})]},h))})}),n.file?s("p",{className:E.fileLinks,children:[["report.json","seal.json",t.anchor?"seal.anchor.json":null,t.tsa?"seal.tsa.json":null,t.tsr?"seal.tsr":null].filter(Boolean).map(h=>[h,no(n.file(h))]).filter(([,h])=>h).map(([h,p])=>s("a",{href:p,children:h},h)),n.keys&&no(n.keys.href)?s("a",{href:no(n.keys.href),children:n.keys.label}):null]}):null]})}var Ti={title:"Title",fname:"First name",lname:"Last name",DOB:"Date of birth",sex:"Sex",street:"Street",city:"City",state_label:"State",postal_code:"Postal code",phone_home:"Home phone",email:"Email",country_code:"Country"};function yr(e){if(Ti[e])return Ti[e];let t=String(e).replace(/[_-]+/g," ").trim();return t.charAt(0).toUpperCase()+t.slice(1)}function $i(e){let t=e.match(/^type <(\w+)>$/);if(t)return`Type ${yr(t[1])}`;if(e==="press Control+a")return"Select the field’s text";if(e==="press Enter")return"Press Enter";if(e.startsWith("scroll"))return"Scroll down";if(e==="click recorded visual target")return"Click the next field";let n=e.match(/^click '(.+)'$/);return n?/nassigned/.test(n[1])?"Open the list":`Click ${n[1].replace("FirstName","First name")}`:e.charAt(0).toUpperCase()+e.slice(1)}var Yp={title:"Title",fname:"First name",lname:"Last name",DOB:"Date of birth",sex:"Sex",street:"Street",city:"City",state:"State",state_label:"State",postal_code:"Postal code",phone_home:"Home phone",email:"Email",country_code:"Country"},Mt=e=>String(e).replace(/^.*::/,"");function Jp(e){let t=/field '(\w+)' equals/.exec(e||"");return t?`${Yp[t[1]]||yr(t[1])} matches`:/record_written/.test(e||"")?"The new record exists":null}function Ai(e,t){if(!e||typeof e!="object")throw new Error("no report");if(e.bundle_content_digest!==t.digest)throw new Error("the report is from a different program");let n=Array.isArray(e.results)?e.results:[];if(n.length>t.steps.length)throw new Error("the report has more steps than the program");n.forEach((w,N)=>{if(Mt(w.step_id)!==Mt(t.steps[N].id))throw new Error(`step ${N+1}: the report and the program differ`)});let o=0,r=n.map(w=>{let N=Math.max(0,Number(w.elapsed_ms)||0),M={t0:o,t1:o+N};return o+=N,M}),a=o,i=e.outcome_envelope?.postcondition_evidence||[],l=new Map;for(let w of i){let N=l.get(w.result_index)||[];N.push(w),l.set(w.result_index,N)}let d=t.steps.map((w,N)=>{let M=n[N],S=M?M.ok?"passed":"stopped":"not_reached",A=l.get(N)||[];return{i:N,id:Mt(w.id),name:w.name,section:w.section,status:S,t0:M?r[N].t0:null,t1:M?r[N].t1:null,checks:{passed:A.filter(O=>O.verdict==="passed").length,failed:A.filter(O=>O.verdict!=="passed").length},identity:M?M.identity?.status==="verified"?"passed":M.identity?"failed":null:null}}),c=i.map(w=>{let N=d[w.result_index];if(!N||N.status==="not_reached")throw new Error("a screen check on a step the run never reached");return{step:w.result_index,result:w.verdict==="passed"?"passed":"failed",t:N.t1}}),g=Array.isArray(e.governed_qualified_effect_requirements)?e.governed_qualified_effect_requirements:[],h=g.length?g.map(w=>({step:d.findIndex(N=>N.id===Mt(w.step_id??"")),at:Number.isInteger(w.effect_index)?w.effect_index:-1})):n.flatMap((w,N)=>(Array.isArray(w.effect_evidence)?w.effect_evidence:[]).map((M,S)=>({step:N,at:S}))),p=h.map((w,N)=>{let M=n[w.step],S=Array.isArray(M?.effect_evidence)?M.effect_evidence:[],A=Array.isArray(M?.effect_results)?M.effect_results:[],O=S[w.at],I=M?r[w.step]:null,$=h.filter(R=>R.step===w.step),C=$.indexOf(w);return{i:N,step:w.step,result:O?O.final_verdict==="confirmed"?"passed":"failed":"not_reached",label:w.at>=0&&Jp(A[w.at])||null,t:O&&I?I.t0+(I.t1-I.t0)*(.55+.45*C/$.length):null}}),f=(Array.isArray(e.required_identity_step_ids)?e.required_identity_step_ids.map(Mt):[]).map(w=>{let N=d.find(M=>M.id===w);if(!N)throw new Error(`a right-record check on an unknown step ${w}`);return{step:N.i,result:N.identity??"not_reached",t:N.t0==null?null:N.t0+(N.t1-N.t0)*.3}}),v=d.find(w=>w.status==="stopped")||null,m=(w,N)=>w.filter(M=>M.result===N).length,b=p.find(w=>w.result==="passed"),y=[...d].reverse().find(w=>w.status!=="not_reached"),_=v?{step:v.i,kind:"stop"}:b?{step:b.step,kind:"save"}:y?{step:y.i,kind:"end"}:null;return{outcome:e.execution_outcome,transaction:e.transaction_outcome??null,runMs:a,totalMs:typeof e.total_ms=="number"?e.total_ms:a,startedAt:e.started_at??null,stoppedAt:v?v.i:null,anchor:_,steps:d,checks:c,readbacks:p,identity:f,counts:{steps:d.length,stepsPassed:d.filter(w=>w.status==="passed").length,checks:c.length,checksPassed:m(c,"passed"),checksFailed:m(c,"failed"),readbacks:p.length,readbacksPassed:m(p,"passed"),readbacksFailed:m(p,"failed"),identity:f.length,identityPassed:m(f,"passed"),modelCalls:e.model_calls??null}}}function Mi(e,{folds:t=null,report:n=null,titles:o=null,digest:r=null}={}){let a=(e?.nodes||[]).filter(d=>d.kind==="action"),i=new Map((Array.isArray(n?.results)?n.results:[]).map(d=>[Mt(d.step_id),d.intent])),l=new Map;for(let d of t?.groups||[])for(let c of d.nodes)l.set(c,d.title);return{digest:r||e?.bundle?.provenance?.content_digest||t?.source?.body_content_digest||null,steps:a.map(d=>{let c=i.get(Mt(d.id));return{id:d.id,name:o?.[d.id]||(c?$i(c):d.title),section:l.get(d.id)||null}})}}function Xp(e,t,{readBack:n=!1}={}){return e==="VERIFIED"&&n?{tone:"ok",label:"Saved and checked",line:"The entry reached the record, and reading the record back found it there."}:e==="VERIFIED"?{tone:"ok",label:"Completed",line:"Every step's checks passed. This run didn't read the saved record back."}:t==="HALTED_BEFORE_EFFECT"?{tone:"halt",label:"Stopped before saving",line:"The run stopped before it changed anything, so a person decides what happens next."}:t==="RECONCILIATION_REQUIRED"?{tone:"halt",label:"Stopped for a person to check",line:"The run stopped after a save it couldn't confirm, so a person checks the record before anything else runs."}:{tone:"halt",label:"Stopped",line:"The run stopped, so a person decides what happens next."}}var Qp=[[/duplicate|already exists|1 of 1|existing (?:chart|record|patient)|No matches were found/i,"possible duplicate patient"],[/0 records match|never reached the record|missing \/ phantom/i,"the save never reached the record"],[/identity|wrong (?:record|patient)/i,"couldn't confirm the right record"]],eu={"possible duplicate patient":"The screen check before saving expected the app to find no matching patient. It found one, so the run stopped before it changed anything.","the save never reached the record":"The app showed its saved message, but reading the record back found nothing there, so the run stopped instead of reporting success.","couldn't confirm the right record":"The run couldn't confirm it was on the right record, so it stopped before acting."};function tu(e){let t=[e?.halt?.reason,e?.halt?.intent].filter(Boolean).join(" "),n=Qp.find(([o])=>o.test(t));return n?n[1]:null}function Ri(e,t,n){let o=Xp(t?.outcome,e?.transaction_outcome,{readBack:!!n?.counts?.readbacksPassed}),r=t?.outcome==="VERIFIED"?null:tu(e);return{...o,headline:r?`${o.label}: ${r}`:o.label,reason:r,note:r&&eu[r]||null}}var nu=e=>new TextDecoder().decode(e),Ii=async e=>Re(new TextEncoder().encode(e)),ou=async e=>Ii(e.subject_sha256+await Ii(je(e)));async function Ci({files:e,keys:t,program:n,about:o={},authorization:r=null}){let a=JSON.parse(e.sealText),i=JSON.parse(nu(e.report)),l=Mi(n.spec,{folds:n.folds||null,titles:n.titles||null,digest:n.digest||null,report:i}),d=Ai(i,l),c=Ri(i,a,d);return{files:e,page:{id:o.id||a.run_id,tone:c.tone,label:c.label,headline:c.headline,line:c.line,job:o.job||i.workflow_name||"Run",app:o.app||"Test copy",startedAt:i.started_at??null,stopReason:c.reason,stopNote:c.note,rings:d,irisSeed:await ou(a),media:d.steps.map(()=>({crop:null,frame:null})),seal:a,keys:t,files:{report:"report.json",seal:"seal.json",anchor:e.anchorText!=null?"seal.anchor.json":null,tsa:e.tsaText!=null?"seal.tsa.json":null,tsr:e.tsrBytes!=null?"seal.tsr":null},anchor:null,authorization:r,authTiming:null,authorizedLine:null,tamper:Os(a.outcome,i.execution_outcome),program:{spec:n.spec,folds:n.folds||null,titles:Object.fromEntries(l.steps.map(g=>[g.id,g.name]))},runs:[]}}}var Pi=e=>Uint8Array.from(atob(e),t=>t.charCodeAt(0));function Oi({text:e}){return s("main",{style:{font:"16px/1.5 var(--oa-font-body)",color:"var(--oa-text)",padding:"48px 24px",maxWidth:640,margin:"0 auto"},children:[s("h1",{style:{fontSize:22},children:"This receipt can't be shown"}),s("p",{children:e}),s("p",{children:["Check it from a terminal instead: ",s("code",{children:"openadapt verify RUN_FOLDER"})]})]})}async function ru(){let e=(0,zi.createRoot)(document.getElementById("root")),t=document.getElementById("seal-data"),n;try{n=JSON.parse(t?.textContent||"null")}catch{n=null}if(!n||!n.report_b64||!n.seal_text){e.render(s(Oi,{text:"The page has no run in it. Write one with: openadapt receipt view RUN_FOLDER"}));return}let o={report:Pi(n.report_b64),sealText:n.seal_text,anchorText:n.anchor_text??null,tsaText:n.tsa_text??null,tsrBytes:n.tsr_b64?Pi(n.tsr_b64):null,auth:n.auth??null,receiptText:n.receipt_text??null,receiptKeys:n.receipt_keys??null},r;try{r=await Ci({files:o,keys:n.keys,program:n.program,about:n.about||{},authorization:n.authorization??null})}catch(l){e.render(s(Oi,{text:`The run's files don't fit together: ${l.message}.`}));return}let a={...r.page,commands:n.commands??null,commandsLabel:n.commands_label??null};document.title=Ei(a).title;let i=n.host||{};e.render(s(vr,{seal:a,host:{loadFiles:async()=>({...o,report:o.report.slice()}),live:!1,kicker:n.about?.kicker??null,trustWords:i.trustWords,unchanged:i.unchanged,footer:i.footer,links:{home:null,map:null,file:l=>i.files?.includes(l)?l:null,keys:null,docs:"https://docs.openadapt.ai/reference/receipts-and-seals/"}}}))}ru();})(); +-----END CERTIFICATE-----`,Md="openadapt.record-timestamp/v1",Ne={signedData:"1.2.840.113549.1.7.2",tstInfo:"1.2.840.113549.1.9.16.1.4",contentType:"1.2.840.113549.1.9.3",messageDigest:"1.2.840.113549.1.9.4",sha256:"2.16.840.1.101.3.4.2.1",sha384:"2.16.840.1.101.3.4.2.2",sha512:"2.16.840.1.101.3.4.2.3",ecdsaSha256:"1.2.840.10045.4.3.2",ecdsaSha384:"1.2.840.10045.4.3.3",ecdsaSha512:"1.2.840.10045.4.3.4",ecPublicKey:"1.2.840.10045.2.1",p256:"1.2.840.10045.3.1.7",p384:"1.3.132.0.34",extKeyUsage:"2.5.29.37",timeStamping:"1.3.6.1.5.5.7.3.8"},Ls={[Ne.sha256]:"SHA-256",[Ne.sha384]:"SHA-384",[Ne.sha512]:"SHA-512"},Rd={[Ne.ecdsaSha256]:"SHA-256",[Ne.ecdsaSha384]:"SHA-384",[Ne.ecdsaSha512]:"SHA-512"},Id={[Ne.p256]:["P-256",32],[Ne.p384]:["P-384",48]},eo=class extends Error{},qe=e=>{throw new eo(e)};function Gt(e,t){t+2>e.length&&qe("truncated");let n=e[t];(n&31)===31&&qe("long tag");let o=e[t+1],r=t+2;if(o&128){let i=o&127;(i===0||i>4)&&qe("length"),o=0;for(let l=0;le.length&&qe("truncated"),{tag:n,start:r,end:a,bytes:e,raw:e.subarray(t,a),content:e.subarray(r,a)}}function se(e){let t=[],n=e.start;for(;ne&&e.tag===t?e:qe(`tag ${t}`);function Be(e){ve(e,6);let t=e.content,n=[Math.floor(t[0]/40),t[0]%40],o=0;for(let r=1;rnew TextDecoder().decode(e.content);function ir(e){let t=Cd(e),n=e.tag===24?/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\.\d+)?Z$/.exec(t):e.tag===23?/^(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)()Z$/.exec(t):null;n||qe("time");let o=e.tag===23?(Number(n[1])<50?2e3:1900)+Number(n[1]):Number(n[1]);return`${String(o).padStart(4,"0")}-${n[2]}-${n[3]}T${n[4]}:${n[5]}:${n[6]}${n[7]||""}Z`}var Pd=e=>Array.from(e,t=>t.toString(16).padStart(2,"0")).join(""),sr=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]);function Od(e){let t=String(e).replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=atob(t);return Uint8Array.from(n,o=>o.charCodeAt(0))}function Hs(e){let[t,n,o]=se(ve(e,48)),r=se(ve(t,48)),a=r[0].tag===160?1:0,i=r[a+2],l=se(r[a+3]),d=r[a+4],c=ve(r[a+5],48),[g]=se(c),[h,p]=se(g),u=!1;for(let f of r.slice(a+6))if(f.tag===163)for(let v of se(se(f)[0])){let m=se(v);if(Be(m[0])!==Ne.extKeyUsage)continue;u=se(Gt(m.at(-1).content,0)).some(y=>Be(y)===Ne.timeStamping)}return{tbs:t.raw,sigAlg:Be(se(n)[0]),signature:ve(o,3).content.subarray(1),issuer:i.raw,subject:d.raw,notBefore:ir(l[0]),notAfter:ir(l[1]),spki:c.raw,keyAlg:Be(h),curve:p&&p.tag===6?Be(p):null,timestamping:u,serial:r[a].content}}function zd(e,t){let[n,o]=se(ve(Gt(e,0),48)),r=i=>{let l=i.content;for(;l.length>t&&l[0]===0;)l=l.subarray(1);l.length>t&&qe("signature");let d=new Uint8Array(t);return d.set(l,t-l.length),d},a=new Uint8Array(t*2);return a.set(r(n),0),a.set(r(o),t),a}async function Ds(e,t,n,o){let r=Rd[t],a=Id[e.curve];(!r||!a||e.keyAlg!==Ne.ecPublicKey)&&qe("algorithm");let i=globalThis.crypto.subtle,l=await i.importKey("spki",e.spki,{name:"ECDSA",namedCurve:a[0]},!1,["verify"]);return i.verify({name:"ECDSA",hash:r},l,zd(n,a[1]),o)}function Ld(e){let t=se(ve(Gt(e,0),48));Be(t[0])!==Ne.signedData&&qe("not signed data");let n=se(ve(se(ve(t[1],160))[0],48)),o=se(ve(n[2],48));Be(o[0])!==Ne.tstInfo&&qe("not a timestamp");let r=ve(se(ve(o[1],160))[0],4).content,a=3,i=[];if(n[a]&&n[a].tag===160){for(let w of se(n[a]))i.push(Hs(w));a+=1}n[a]&&n[a].tag===161&&(a+=1);let l=se(ve(n[a],49));l.length!==1&&qe("signers");let d=se(ve(l[0],48)),c=d[1],g=Be(se(d[2])[0]),h=ve(d[3],160),p=Be(se(d[4])[0]),u=ve(d[5],4).content,f={};for(let w of se(h)){let[N,M]=se(w);f[Be(N)]=se(M)[0]}let v=se(ve(Gt(r,0),48)),[m,b]=se(ve(v[2],48)),y=c.tag===48?se(c)[1].content:null,_=Uint8Array.from(h.raw);return _[0]=49,{eContent:r,certs:i,signerSerial:y,digestAlg:g,sigAlg:p,signature:u,signedBytes:_,contentType:f[Ne.contentType]?Be(f[Ne.contentType]):null,messageDigest:f[Ne.messageDigest]?ve(f[Ne.messageDigest],4).content:null,policy:Be(v[1]),imprintAlg:Be(se(m)[0]),imprint:Pd(ve(b,4).content),genTime:ir(v[4])}}async function Dd(e,t=Ad){let n;try{n=Ld(e)}catch{return{ok:!1,reason:"tsa_malformed"}}let o={genTime:n.genTime,imprint:n.imprint,imprintAlg:Ls[n.imprintAlg]||n.imprintAlg},r=(a,i)=>({ok:a,reason:i,...o});try{let a=Ls[n.digestAlg];if(!a||n.contentType!==Ne.tstInfo||!n.messageDigest)return r(!1,"tsa_content_mismatch");let i=new Uint8Array(await globalThis.crypto.subtle.digest(a,n.eContent));if(!sr(i,n.messageDigest))return r(!1,"tsa_content_mismatch");let l=Hs(Gt(Od(t),0)),d=n.certs.find(g=>n.signerSerial&&sr(g.serial,n.signerSerial))||(n.certs.length===1?n.certs[0]:null);if(!d)return r(!1,"tsa_untrusted");if(!await Ds(d,n.sigAlg,n.signature,n.signedBytes))return r(!1,"tsa_bad_signature");if(!sr(d.issuer,l.subject)||!await Ds(l,d.sigAlg,d.signature,d.tbs))return r(!1,"tsa_untrusted");if(!d.timestamping)return r(!1,"tsa_not_timestamping");let c=Date.parse(n.genTime);for(let g of[d,l])if(!(Date.parse(g.notBefore)<=c&&c<=Date.parse(g.notAfter)))return r(!1,"tsa_expired");return r(!0,null)}catch(a){return r(!1,a instanceof eo?"tsa_malformed":"tsa_bad_signature")}}var Fd=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}\.tsr$/,Fs=/^[a-f0-9]{64}$/;async function Hd(e){return[...new Uint8Array(await crypto.subtle.digest("SHA-256",e))].map(n=>n.toString(16).padStart(2,"0")).join("")}function js(e){if(typeof e!="string"||Xe(e)!==null)return null;let t;try{t=JSON.parse(e)}catch{return null}return!t||typeof t!="object"||Array.isArray(t)||t.schema!==Md||typeof t.tsr_file!="string"||!Fd.test(t.tsr_file)||!Fs.test(t.tsr_sha256)||!Fs.test(t.imprint_sha256)||"token"in t?null:t}async function jd(e,t,n){let o=js(e);if(!o)return{ok:!1,reason:"tsa_malformed"};if(!t||!t.length)return{ok:!1,reason:"tsa_token_missing"};if(await Hd(t)!==o.tsr_sha256)return{ok:!1,reason:"tsa_token_mismatch"};if(o.imprint_sha256!==n)return{ok:!1,reason:"tsa_imprint_mismatch",matches:!1};let r=await Dd(t),a=r.imprintAlg==="SHA-256"&&r.imprint===n;return r.ok&&!a?{...r,ok:!1,reason:"tsa_imprint_mismatch",matches:a}:{...r,matches:a}}async function Gs(e,t,n){let o=js(e);return o?o.seal_sha256!==t?{ok:!1,reason:"tsa_imprint_mismatch",matches:!1}:jd(e,n,t):{ok:!1,reason:"tsa_malformed"}}function Us(e){if(e==null||Xe(e)!==null)return null;try{return JSON.parse(e)}catch{return null}}async function Bs(e,t,{logKeys:n=null}={}){let o=Us(e.sealText),r=null,a=null;if(e.anchorText!=null){let i=Us(e.anchorText),l=o?fn(t).filter(d=>d.key_id===o.key_id&&d.status==="active"):[];if(!o||!i)r={ok:!1,reason:"anchor_malformed"};else if(l.length!==1)r={ok:!1,reason:"anchor_key_mismatch"};else{let d=n||[await Jn(Vn)],c=await Xn(o,i,Ge(l[0].public_key),d);r={...c,entry:c.ok?i.entry:null}}}return e.tsaText!=null&&(a=o?await Gs(e.tsaText,await gn(o),e.tsrBytes??null):{ok:!1,reason:"tsa_malformed"}),{rekor:r,tsa:a}}var Gd="https://rekor.sigstore.dev/api/v1/log/entries",Ks=e=>`https://search.sigstore.dev/?logIndex=${Number(e)}`;async function Ws(e,{fetchImpl:t=globalThis.fetch,timeoutMs:n=6e3}={}){if(!e||!Number.isInteger(e.logIndex)||e.logIndex<0)return"unavailable";let o=typeof AbortController=="function"?new AbortController:null,r=o?setTimeout(()=>o.abort(),n):null;try{let a=await t(`${Gd}?logIndex=${e.logIndex}`,{signal:o?.signal,headers:{accept:"application/json"},credentials:"omit",referrerPolicy:"no-referrer"});if(!a.ok)return"unavailable";let i=await a.json(),l=i&&typeof i=="object"?Object.keys(i):[];if(l.length!==1)return"unavailable";let d=i[l[0]];return String(l[0]).slice(-64)===String(e.uuid).slice(-64)&&d?.body===e.body&&d?.integratedTime===e.integratedTime&&d?.logID===e.logID&&d?.logIndex===e.logIndex?"match":"differs"}catch{return"unavailable"}finally{r&&clearTimeout(r)}}var Vs=[700,1500],Ut={identity:2600,checks:2200,save:1800,readback:650,stop:4200,done:1600};function qs(e){let t=[],n=i=>t.push({i:t.length,readbacks:0,spotlight:null,highlight:!1,...i}),o=!0,r=!0;for(let i of e.steps){if(i.status==="not_reached")break;let l=Math.min(Vs[1],Math.max(Vs[0],((i.t1??0)-(i.t0??0))*.5)),d=e.readbacks.filter(g=>g.step===i.i&&g.result!=="not_reached"),c=d.length>0;if(n({step:i.i,stage:"step",dwell:c?Ut.save:l,spotlight:c?"save":null,highlight:c}),i.identity==="passed"||i.identity==="failed"){let g=o;o=!1,n({step:i.i,stage:"identity",dwell:g?Ut.identity:Math.max(350,Math.round(l*.45)),spotlight:g?"identity":null,highlight:g})}if(i.checks.passed+i.checks.failed>0&&i.status!=="stopped"){let g=r;r=!1,n({step:i.i,stage:"checks",dwell:g?Ut.checks:Math.max(350,Math.round(l*.45)),spotlight:g?"checks":null,highlight:g})}d.forEach((g,h)=>n({step:i.i,stage:"readback",readbacks:h+1,dwell:Ut.readback,spotlight:"save"})),i.status==="stopped"&&n({step:i.i,stage:"stop",dwell:Ut.stop,spotlight:"stop",highlight:!0})}let a=t.at(-1);return a&&a.stage!=="stop"&&n({step:a.step,stage:"done",readbacks:a.readbacks,dwell:Ut.done}),t}var Ud={step:0,identity:1,checks:2,readback:3,stop:3,done:4};function Zs(e,t){if(!e)return null;let n=Ud[e.stage],o=r=>rr<=e.step,identity:r=>o(r)||r===e.step&&n>=1,checks:r=>o(r)||r===e.step&&(n>=2||e.stage==="stop"),readback:r=>{let a=t.readbacks[r];return!a||a.step==null?!1:a.stepe.step?!1:t.readbacks.filter(l=>l.step===a.step).indexOf(a){let n=e.find(o=>o.step===t);return n?n.i:e.length-1};function Ys(e,t){let n=e.filter(r=>r.highlight);return(n.find(r=>r.i>t)||n[0]||e[0]).i}var Bd=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Js(e){let t=new Date(e);if(!e||Number.isNaN(t.getTime()))return null;let n=o=>String(o).padStart(2,"0");return`${t.getUTCDate()} ${Bd[t.getUTCMonth()]} ${t.getUTCFullYear()}, ${n(t.getUTCHours())}:${n(t.getUTCMinutes())} UTC`}function no(e){return typeof e!="string"||!e||/[\\\s]/.test(e)||e.startsWith("//")?null:e.startsWith("https://")?/^https:\/\/[A-Za-z0-9.-]+(?::\d{1,5})?(?:[/?#]|$)/.test(e)?e:null:/^[A-Za-z][A-Za-z0-9+.-]*:/.test(e)?null:/^(?:\/|\.{1,2}\/|[\w.-]+(?:\/|$))/.test(e)?e:null}function Xs(e,t){let n=e.rings.counts;return`${e.rings.anchor?.kind==="stop"?`Stopped: ${e.stopReason||String(e.headline||"").replace(/^[^:]*:\s*/,"")||"before saving"}`:`${e.label} · ${n.readbacksPassed} of ${n.readbacks} read back`}${t?" · signature valid":""}`}dt();var re={section:272,step:238,stepWidth:15,tickIn:205,tickOut:217,tickFailIn:199,tickFailOut:223,dot:176,dotSize:4.6,petal:128,petalWidth:6,core:94},ge=e=>Math.round(e*100)/100;function Ae(e,t){let n=t*Math.PI/180;return[ge(300+e*Math.sin(n)),ge(300-e*Math.cos(n))]}function bn(e,t,n){let[o,r]=Ae(e,t),[a,i]=Ae(e,n),l=n-t>180?1:0;return`M${o} ${r}A${e} ${e} 0 ${l} 1 ${a} ${i}`}function vn(e,t){let n=Math.sin(e*12.9898+t*78.233)*43758.5453;return n-Math.floor(n)}function oo(e,t,n,o){let r=e*Math.PI/180,a=o*(.5+vn(t,n)),i=(vn(t,n+1)-.5)*o*.8;return{bx:ge(Math.sin(r)*a+Math.cos(r)*i),by:ge(-Math.cos(r)*a+Math.sin(r)*i),br:ge((vn(t,n+2)-.5)*16)}}function Qs(e){let n=360/e.steps.length,o=Math.min(1.4,n*.12),r=m=>[m*n+o/2,(m+1)*n-o/2],a=e.steps.map((m,b)=>{let[y,_]=r(b);return{i:b,d:bn(re.step,y,_),hit:bn(re.step,b*n,(b+1)*n),status:m.status,at:ge((y+_)/2/360),t:m.t0,...oo((y+_)/2,b,1,26)}}),i=[];e.steps.forEach((m,b)=>{let y=i.at(-1);y&&y.title===m.section?y.to=b:i.push({title:m.section,from:b,to:b})});let l=i.filter(m=>m.title).map((m,b)=>{let y=m.from*n+o,_=(m.to+1)*n-o,w=(y+_)/2,N=w>90&&w<270,M=Math.max((_-y)/2,40);return{k:b,title:m.title,from:m.from,to:m.to,d:bn(re.section,y,_),text:N?Kd(re.section+9,w-M,w+M):bn(re.section-4,w-M,w+M),mark:[Ae(re.step+12,m.from*n),Ae(re.step+20,m.from*n)],at:ge(y/360)}}),d=[];e.steps.forEach((m,b)=>{let y=e.checks.filter(N=>N.step===b),[_,w]=r(b);y.forEach((N,M)=>{let S=_+(M+1)/(y.length+1)*(w-_),A=N.result!=="passed",[O,I]=Ae(A?re.tickFailIn:re.tickIn,S),[$,C]=Ae(A?re.tickFailOut:re.tickOut,S);d.push({i:d.length,step:b,x1:O,y1:I,x2:$,y2:C,result:N.result,at:ge(S/360),t:N.t,...oo(S,d.length,2,18)})})});let c=e.readbacks.length,g=e.readbacks.map((m,b)=>{let y=b/c*360,[_,w]=Ae(re.dot,y);return{i:b,cx:_,cy:w,result:m.result,label:m.label,at:ge(y/360),t:m.t,...oo(y,b,3,16)}}),h=e.identity.length,p=360/Math.max(1,h),u=Math.min(4,p*.28),f=e.identity.map((m,b)=>{let y=b*p+u/2,_=(b+1)*p-u/2;return{i:b,step:m.step,d:bn(re.petal,y,_),result:m.result,at:ge((y+_)/2/360),t:m.t,...oo((y+_)/2,b,4,12)}}),v=e.stoppedAt==null?null:(()=>{let m=(e.stoppedAt+1)*n,[b,y]=Ae(re.step-24,m),[_,w]=Ae(re.step+18,m);return{x1:b,y1:y,x2:_,y2:w,deg:ge(m),at:ge(m/360)}})();return{steps:a,bands:l,ticks:d,dots:g,petals:f,stop:v,per:n}}function Kd(e,t,n){let[o,r]=Ae(e,n),[a,i]=Ae(e,t),l=n-t>180?1:0;return`M${o} ${r}A${e} ${e} 0 ${l} 0 ${a} ${i}`}function lr(e,{radius:t=100,disorder:n=0}={}){let o=2166136261;for(let l=0;l+1<(e||"").length;l+=2)o^=parseInt(e.slice(l,l+2),16)||0,o=Math.imul(o,16777619)>>>0;let a=Array.from({length:32},()=>{o=o+1831565813>>>0;let l=o;return l=Math.imul(l^l>>>15,l|1),l^=l+Math.imul(l^l>>>7,l|61),((l^l>>>14)>>>0)%256}),i=[];for(let l=0;l<3;l+=1){let d=1+l*8,c=5+a[d]%9,g=a[d+1]/255*Math.PI*2,h=t*(.5+.2*l+a[d+2]/255*.08),p=.16+a[d+3]/255*.24,u=(a[d+4]/255-.5)*.7,f=1.2+a[d+6]/255*.8,v=f*(2.4+a[d+5]/255*1.6),m=_=>{let w=h*(1-p+p*Math.cos(c*_+g)),N=_+u*Math.sin(c*_);return[t+w*Math.cos(N),t+w*Math.sin(N)]},b=[],y=0;for(let _=0;_=N;){let C=1-($-N)/Math.max(1e-9,Math.hypot(I[0]-M[0],I[1]-M[1])),R=M[0]+(I[0]-M[0])*C,k=M[1]+(I[1]-M[1])*C;n&&(R+=(vn(_*97+S,l+11)-.5)*5*n,k+=(vn(_*89+S,l+23)-.5)*5*n),R=ge(R),k=ge(k),w+=`M${ge(R-f)} ${k}a${ge(f)} ${ge(f)} 0 1 0 ${ge(f*2)} 0a${ge(f)} ${ge(f)} 0 1 0 ${ge(-f*2)} 0`,S+=1,$-=N,N=v}N-=$,M=I}y=Math.max(y,S),b.push({d:w,at:ge(_/c)})}i.push({petals:b,count:c,dots:y,dir:(l%2?-1:1)*(a[0]%2?1:-1)})}return i}var F={wrap:"a",svg:"ba",halo:"Z",breathe:"ua",g0:"lo",g1:"go",c0:"co",c1:"fo",layer:"ha",hair:"ka",seal:"y",bandArc:"wa",bandMark:"xo",bandText:"vo",step:"r",bloom:"n",petal:"e",tick:"i",dot:"t",stop:"b",core:"mo",rosette:"u",check:"h",cross:"U",square:"z",hit:"ya",witnessLink:"za",witnessDot:"k",witnessGlyph:"_",witnessPing:"aa",witnessText:"j",witness:"f",witnessWait:"_a",witnessLit:"ja",draw:"oa",bloomIn:"Sa",ghostIn:"ra",tickIn:"Ca",pop:"q",stopIn:"Ma",band:"bo",coreIn:"Ya",sweep:"S",flare:"Fa",tickFlare:"Ra",dotFlare:"Ea",jolt:"Ia",iris:"C",irisIn:"Aa",irisBreathe:"Ha",irisLayer:"ta",irisSpin:"Ua",irisGlow:"qa",irisPulse:"Ba",anchorMark:"x",anchorDot:"Da",playhead:"B",mini:"M"};Lt();Lt();var Vd=0;function s(e,t,n,o,r,a){t||(t={});var i,l,d=t;if("ref"in d)for(l in d={},t)l=="ref"?i=t[l]:d[l]=t[l];var c={type:e,props:d,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Vd,__i:-1,__u:0,__source:r,__self:a};if(typeof e=="function"&&(i=e.defaultProps))for(l in i)d[l]===void 0&&(d[l]=i[l]);return j.vnode&&j.vnode(c),c}var qd=.94;function Zd(e,t){let n={passed:"passed",stopped:"the run stopped here",not_reached:"not reached"}[e.status];return`Step ${e.i+1} of ${t}: ${e.name}, ${n}`}function ro({rings:e,tone:t,digest:n,phase:o="rest",still:r=!1,variant:a="full",buildMs:i=3200,active:l=null,focusIndex:d=0,onActive:c,onPick:g,onKey:h,ringFocus:p=null,witnesses:u=null,lit:f=null,spot:v=null,label:m}){let b=ne(()=>Qs(e),[e]),y=a==="full",_=o==="broken",w=ne(()=>y?lr(n,{radius:100,disorder:_?1:0}):null,[n,_,y]),N=e.anchor,M=!!(f&&N&&f.step===N.step&&["done","stop","readback"].includes(f.stage)),A=`s${st().replace(/[^a-zA-Z0-9]/g,"")}`,O=Math.max(1,e.runMs),I=k=>k==null?0:Math.round(Math.min(k/O,1)*qd*i),$=k=>l!=null&&k===l?"1":void 0,C=k=>f?k?"1":"0":void 0,R=(k,B={})=>({"--d":`${I(k.t)}ms`,"--a":k.at,"--bx":`${k.bx}px`,"--by":`${k.by}px`,"--br":`${k.br}deg`,...B});return s("div",{className:F.wrap,"data-phase":o,"data-tone":t,"data-variant":a,"data-still":r?"1":void 0,"data-focus":l!=null?"1":void 0,"data-ring":p||void 0,"data-spot":v||void 0,"data-anchored":M?"1":void 0,style:{"--build":`${i}ms`},children:[s("div",{className:F.halo,"aria-hidden":"true"}),w?s(ei,{layers:w,phase:o,broken:_,tone:t},n):null,s("svg",{className:F.svg,viewBox:"0 0 600 600",role:y?"group":"img","aria-label":m,children:[s("defs",{children:[s("linearGradient",{id:`${A}g`,x1:"80",y1:"40",x2:"520",y2:"560",gradientUnits:"userSpaceOnUse",children:[s("stop",{offset:"0",className:F.g0}),s("stop",{offset:"1",className:F.g1})]}),s("radialGradient",{id:`${A}c`,cx:"300",cy:"280",r:"110",gradientUnits:"userSpaceOnUse",children:[s("stop",{offset:"0",className:F.c0}),s("stop",{offset:"1",className:F.c1})]})]}),s("g",{className:F.layer,style:{"--z":1},children:[s("circle",{className:F.seal,cx:300,cy:300,r:re.section+16,pathLength:"1"}),s("circle",{className:F.hair,cx:300,cy:300,r:re.step+32}),b.bands.map(k=>s("g",{className:F.band,style:{"--d":`${Math.round(k.at*i*.4)}ms`},children:[s("path",{className:F.bandArc,d:k.d,pathLength:"1"}),s("line",{className:F.bandMark,x1:k.mark[0][0],y1:k.mark[0][1],x2:k.mark[1][0],y2:k.mark[1][1]}),y?s(ae,{children:[s("path",{id:`${A}b${k.k}`,d:k.text,fill:"none"}),s("text",{className:F.bandText,children:s("textPath",{href:`#${A}b${k.k}`,startOffset:"50%",textAnchor:"middle",children:k.title.toUpperCase()})})]}):null]},k.k))]}),u?s(Jd,{witnesses:u}):null,N?s(Xd,{deg:(N.step+.5)*b.per,kind:N.kind}):null,s("g",{className:F.layer,style:{"--z":.8},children:[b.steps.map(k=>s("path",{className:F.bloom,"data-status":k.status,"data-on":$(k.i),"data-lit":C(f?.steps(k.i)),d:k.d,pathLength:"1",style:R(k)},`b${k.i}`)),b.steps.map(k=>s("path",{className:F.step,"data-status":k.status,"data-on":$(k.i),"data-lit":C(f?.steps(k.i)),"data-current":f&&f.step===k.i?"1":void 0,"data-anchor":N&&N.step===k.i?N.kind:void 0,"data-i":k.i,d:k.d,pathLength:"1",stroke:k.status==="passed"?`url(#${A}g)`:void 0,style:R(k)},k.i)),b.stop?s("g",{"data-lit":C(f&&f.stage==="stop"),className:F.stop,style:{"--d":`${I(e.steps[e.stoppedAt].t1)}ms`},children:s("line",{x1:b.stop.x1,y1:b.stop.y1,x2:b.stop.x2,y2:b.stop.y2})}):null]}),s("g",{className:F.layer,style:{"--z":.6},children:[s("circle",{className:F.hair,cx:300,cy:300,r:re.dot+16}),b.ticks.map(k=>s("line",{className:F.tick,"data-result":k.result,"data-on":$(k.step),"data-lit":C(f?.checks(k.step)),x1:k.x1,y1:k.y1,x2:k.x2,y2:k.y2,style:R(k)},k.i))]}),s("g",{className:F.layer,style:{"--z":.45},children:[b.dots.map(k=>s("circle",{className:F.dot,"data-result":k.result,"data-lit":C(f?.readback(k.i)),"data-on":l!=null&&e.readbacks[k.i].step===l?"1":void 0,cx:k.cx,cy:k.cy,r:re.dotSize,style:R(k),onMouseEnter:y&&c?()=>c(e.readbacks[k.i].step,{readback:k.i}):void 0},k.i)),s("circle",{className:F.hair,cx:300,cy:300,r:re.petal+18})]}),s("g",{className:F.layer,style:{"--z":.3},children:b.petals.map(k=>s("path",{className:F.petal,"data-result":k.result,"data-on":$(k.step),"data-lit":C(f?.identity(k.step)),d:k.d,pathLength:"1",style:R(k),onMouseEnter:y&&c?()=>c(k.step,{identity:k.i}):void 0},k.i))}),s("g",{className:F.layer,style:{"--z":.15},children:[s("circle",{className:F.core,cx:300,cy:300,r:re.core,fill:`url(#${A}c)`}),s("g",{className:F.glyph,children:[s("path",{className:F.check,d:`M${278} ${301}l15 15 31-33`,pathLength:"1"}),s("rect",{className:F.square,x:285,y:285,width:"30",height:"30",rx:"4"}),s("path",{className:F.cross,d:`M${283} ${283}l34 34M${317} ${283}l-34 34`,pathLength:"1"})]})]}),f?s("g",{className:F.playhead,style:{"--deg":`${((f.step+.5)*b.per).toFixed(2)}deg`},"aria-hidden":"true",children:[s("line",{x1:300,y1:300-re.core-6,x2:300,y2:300-re.step-22}),s("circle",{cx:300,cy:300-re.step-22,r:"4.5"})]}):null,y?s("g",{className:F.hits,role:"list","aria-label":`${e.steps.length} program steps`,children:b.steps.map(k=>s("path",{role:"listitem",className:F.hit,d:k.hit,tabIndex:k.i===d?0:-1,"aria-label":Zd(e.steps[k.i],e.steps.length),"data-step":k.i,onMouseEnter:c?()=>c(k.i):void 0,onFocus:c?()=>c(k.i,{focus:!0}):void 0,onClick:g?()=>g(k.i):void 0,onKeyDown:h},k.i))}):null]}),s("div",{className:F.sweep,"aria-hidden":"true"})]})}var Yd={rekor:{deg:226,short:"PUBLIC LOG",name:"Sigstore Rekor: the receipt is in the public transparency log"},tsa:{deg:134,short:"TIMESTAMP",name:"Sigstore Timestamp Authority: a trusted time for the receipt"}};function Jd({witnesses:e}){return s("g",{className:F.layer,style:{"--z":1.15},children:Object.entries(Yd).map(([t,n])=>{let o=e[t];if(!o)return null;let[r,a]=Ae(re.section+32,n.deg),[i,l]=Ae(re.section+6,n.deg),[d,c]=Ae(re.section+17,n.deg);return s("g",{className:F.witness,"data-state":o,"data-witness":t,children:[s("title",{children:`${n.name}${o==="pass"?", checked":o==="fail"?", doesn't check":""}`}),s("line",{className:F.witnessLink,x1:i,y1:l,x2:d,y2:c}),s("circle",{className:F.witnessPing,cx:r,cy:a,r:"15"}),s("circle",{className:F.witnessDot,cx:r,cy:a,r:"15"}),t==="rekor"?s("path",{className:F.witnessGlyph,d:`M${r-6.5} ${a-5}h13M${r-6.5} ${a}h13M${r-6.5} ${a+5}h13`}):s("path",{className:F.witnessGlyph,d:`M${r} ${a-6.5}v6.5l4 3M${r-7.5} ${a}a7.5 7.5 0 1 0 15 0a7.5 7.5 0 1 0 -15 0`}),s("text",{className:F.witnessText,x:r,y:a+30,textAnchor:"middle",children:n.short})]},t)})})}function Xd({deg:e,kind:t}){let[n,o]=Ae(re.section+2,e),[r,a]=Ae(re.step+10,e);return s("g",{className:F.layer,style:{"--z":1},children:s("g",{className:F.anchorMark,"data-kind":t,children:[s("title",{children:t==="stop"?"Signed here: the run stopped at this step":"Signed here: the save OpenAdapt confirmed by reading the record back"}),s("line",{x1:r,y1:a,x2:n,y2:o}),s("circle",{cx:n,cy:o,r:"8"}),s("circle",{cx:n,cy:o,r:"3",className:F.anchorDot})]})})}var Qd=1700;function ei({layers:e,phase:t,broken:n,tone:o}){let r=X(null),a=X([]);return U(()=>{let i=r.current;if(!i)return;let l=[],d="#ffffff",c=()=>{let m=getComputedStyle(i),b=(y,_)=>m.getPropertyValue(y).trim()||_;l=n?[b("--fail","#ff4d6a"),b("--fail","#ff4d6a"),b("--fail","#ff4d6a")]:[b("--t0","#4cf0b8"),b("--soft","#b9fbe5"),b("--t0","#4cf0b8")],d=b("--seal-ink","#ffffff")};c();let g=n?[.3,.26,.22]:[.62,.45,.35],h=e.map(m=>m.petals.map(b=>({path:new Path2D(b.d),at:b.at}))),p=m=>{a.current.forEach((b,y)=>{if(!b)return;let _=b.clientWidth,w=Math.min(2,window.devicePixelRatio||1);b.width!==Math.round(_*w)&&(b.width=Math.round(_*w),b.height=Math.round(_*w));let N=b.getContext("2d");N.setTransform(_*w/200,0,0,_*w/200,0,0),N.clearRect(0,0,200,200);for(let M of h[y]){let S=m==null?0:Math.max(0,1-Math.abs(m-M.at)*6);N.globalAlpha=Math.min(1,g[y]+S*.6),N.fillStyle=S>.3?d:l[y],N.fill(M.path)}})};p(null);let u=new MutationObserver(()=>requestAnimationFrame(()=>{c(),p(null)}));if(u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),t!=="verify"||window.matchMedia("(prefers-reduced-motion: reduce)").matches)return()=>u.disconnect();let f=performance.now(),v=requestAnimationFrame(function m(b){let y=(b-f)/Qd;p(y>1.1?null:y),y<=1.1&&(v=requestAnimationFrame(m))});return()=>{cancelAnimationFrame(v),u.disconnect()}},[e,t,n,o]),s("div",{className:F.iris,ref:r,"aria-hidden":"true",children:[e.map((i,l)=>s("canvas",{ref:d=>{a.current[l]=d},className:F.irisLayer,style:{"--spin":`${i.dir*(140+l*50)}s`}},l)),s("div",{className:F.irisGlow})]})}function ti({seed:e,tone:t,size:n=64}){let o=ne(()=>lr(e,{radius:100}),[e]);return s("span",{className:F.mini,"data-tone":t,style:{width:n,height:n},"aria-hidden":"true",children:s(ei,{layers:o,phase:"rest",broken:!1,tone:t})})}dt();var E={page:"o",srOnly:"uo",skip:"La",top:"ea",home:"Na",mark:"ho",crumb:"D",runs:"ia",run:"L",runSeal:"ko",runText:"Pa",topEnd:"wo",chip:"Y",chipDot:"Ta",blink:"na",iconBtn:"N",app:"pa",hero:"F",tabs:"d",panels:"P",resizer:"v",mapPane:"R",paneHead:"Xa",map:"p",stage:"sa",tilt:"Ga",heading:"yo",outcome:"zo",reason:"_o",meta:"Ja",verdict:"w",code:"jo",pending:"Ka",dots:"Oa",signer:"T",shotsNote:"So",older:"Co",changed:"Qa",actions:"Va",another:"Wa",anotherHead:"Mo",changeHead:"Yo",change:"X",primary:"E",ghost:"I",dock:"Fo",player:"Za",pBtn:"da",scrub:"Ro",pTime:"ao",speeds:"la",stepLine:"Eo",count:"oo",panel:"ga",panelIn:"ro",sub:"Io",line:"Ao",by:"to",stats:"s",swatch:"G",calls:"Ho",proof:"Uo",hashRow:"J",signed:"eo",proofLabel:"ca",hex:"A",chips:"qo",tchip:"H",foot:"io",steps:"m",sNum:"Bo",sMark:"fa",sName:"xa",sTags:"K",evHead:"Do",evTitle:"no",evNum:"Lo",evNav:"No",empty:"po",inspector:"Po",inMain:"To",kv:"l",recordTable:"g",spotNote:"Xo",shots:"O",readTable:"c",flash:"so",record:"Go",recordH:"Jo",wMark:"Q",fileLinks:"va",cmds:"Ko",wideOnly:"Oo"};var tp="0123456789abcdef",Bt=64,np=1100;function cr({label:e,from:t,to:n,against:o,running:r,still:a}){let[i,l]=D(()=>(t||"").slice(0,Bt)),[d,c]=D(!1),g=X(n);g.current=n,U(()=>{if(!r){n&&(l(n),c(!0));return}if(c(!1),a){n&&(l(n),c(!0));return}let f=(t||"").slice(0,Bt).padEnd(Bt,"0"),v=0,m=0,b=null,y=_=>{let w=g.current;w&&b==null&&(b=_);let N=b==null?0:Math.min(1,(_-b)/np);if(_-m>45||N===1){m=_;let M=Math.floor(N*Bt),S="";for(let A=0;AcancelAnimationFrame(v)},[r,a]),U(()=>{!r&&n&&(l(n),c(!0))},[n,r]);let h=d&&n,p=h&&n===o,u=!r&&!n;return s("div",{className:E.hashRow,"data-state":u?"idle":h?p?"match":"differs":"running",children:[s("span",{className:E.proofLabel,children:[e,h?s("b",{children:p?" · matches":" · differs"}):null]}),s("code",{className:E.hex,"aria-label":h?`SHA-256 ${n}`:u?"Not computed":"Computing the SHA-256",children:u?"not computed":h?[...n].map((f,v)=>s("span",{"data-diff":f!==o[v]?"1":void 0,children:f},v)):i})]})}function ao({className:e}){return s("svg",{className:e,viewBox:"0 0 700 700","aria-hidden":"true",focusable:"false",children:s("g",{transform:"translate(0 700) scale(0.1 -0.1)",fill:"currentColor",children:s("path",{d:"M3390 6546 c-220 -60 -361 -281 -316 -496 25 -117 87 -214 176 -271 l50 -32 0 -249 0 -248 -877 0 -878 -1 -117 -80 -118 -80 0 -475 0 -474 -108 0 -107 0 -108 -108 -107 -107 0 -215 0 -215 108 -108 107 -107 108 0 107 0 0 -623 0 -622 111 -143 111 -142 549 0 549 0 2 -527 3 -526 175 -73 c96 -40 180 -73 186 -74 6 0 256 270 555 600 l543 600 681 0 680 0 113 113 112 112 0 653 0 652 113 0 112 0 108 108 107 107 0 215 0 215 -108 108 -107 107 -113 0 -112 0 0 443 0 442 -113 113 -112 112 -873 0 -872 0 0 258 1 257 41 25 c83 51 160 176 179 289 32 203 -122 422 -332 470 -59 14 -154 13 -209 -3z m1860 -3046 l0 -1310 -619 0 -619 0 -73 -31 c-41 -17 -84 -41 -97 -52 -13 -12 -193 -214 -400 -449 l-377 -428 -3 480 -2 480 -133 0 c-125 0 -1012 44 -1124 56 l-53 5 0 1280 0 1279 1750 0 1750 0 0 -1310z M2400 3935 l0 -215 220 0 220 0 0 215 0 215 -220 0 -220 0 0 -215z M4150 3935 l0 -215 220 0 220 0 0 215 0 215 -220 0 -220 0 0 -215z M2511 3126 l-152 -152 53 -50 c119 -113 304 -230 469 -298 573 -235 1197 -133 1673 274 l76 65 -154 154 -154 154 -53 -47 c-115 -103 -267 -189 -427 -242 -102 -33 -155 -39 -357 -39 -142 1 -185 4 -260 23 -180 45 -349 131 -488 247 l-74 63 -152 -152z"})})})}dt();dt();var le=e=>e.kind??"action",At=e=>e.kind??"sequence",Fe=e=>e.halts??[],it=e=>e.effects??[],yn=e=>e.postconditions??[],ye=e=>e.nodes??[],Ke=e=>e.edges??[];var Ze="__opg_stop__",xn=e=>String(e).padStart(2,"0");var op=e=>e.index+1;function rp(e,t,n){let o=i=>n(i)??i.index+1,r=t.map(i=>i.identity).filter(i=>i?.applicable),a=i=>[...new Set(i)];return{id:e.id,index:Math.min(...t.map(i=>i.index)),kind:t.every(i=>le(i)==="action")?"action":le(t[0]),title:e.title??`Steps ${xn(o(t[0]))}–${xn(o(t[t.length-1]))}`,action:null,risk:t.some(i=>i.risk==="irreversible")?"irreversible":t.some(i=>i.risk)?"reversible":null,resolution:null,identity:r.length?{applicable:!0,armed:r.every(i=>i?.armed===!0)}:null,effects:t.flatMap(it),postconditions:t.flatMap(yn),halts:t.flatMap(i=>Fe(i).map(l=>`step ${xn(o(i))}: ${l}`)),badges:a(t.flatMap(i=>i.badges??[]))}}function ni(e,t={}){let n=t.numberOf??op,o=ye(e),r=new Map(o.map(p=>[p.id,p])),a=new Map(o.map(p=>[p.id,p.id])),i=new Map,l=new Map;for(let p of t.folds?.groups??[]){if(t.expanded?.has(p.id)||r.has(p.id))continue;let u=p.nodes.map(v=>r.get(v)).filter(v=>v!==void 0&&a.get(v.id)===v.id).sort((v,m)=>v.index-m.index);if(u.length===0)continue;let f=rp(p,u,n);for(let v of u)a.set(v.id,p.id);l.set(u[0].id,f),i.set(p.id,{id:p.id,title:f.title,subtitle:p.subtitle,members:u,first:n(u[0])??u[0].index+1,last:n(u[u.length-1])??u[u.length-1].index+1})}let d=[];for(let p of o)a.get(p.id)===p.id?d.push(p):l.get(p.id)&&d.push(l.get(p.id));let c=[],g=new Set;for(let p of Ke(e)){let u=a.get(p.source),f=a.get(p.target);if(!u||!f||u===f&&i.has(u))continue;let v=At(p),m=`${u}>${f}>${v}>${p.label??""}`;g.has(m)||(g.add(m),c.push({...p,source:u,target:f,kind:v}))}let h=(t.stopExits??[]).filter(p=>a.has(p.node));if(h.length){let p=Math.max(-1,...d.map(u=>u.index))+1;d.push({id:Ze,index:p,kind:"terminal",title:t.stopLabel??"Stop the run",outcome:"halt",halts:[],effects:[],postconditions:[]});for(let u of h){let f=a.get(u.node),v=`${f}>${Ze}`;g.has(v)||(g.add(v),c.push({source:f,target:Ze,kind:"exception",label:u.label??"stops"}))}}return{spec:{...e,nodes:d,edges:c},folds:i,ownerOf:a}}function oi(e){let t=e.sections??[];return t.length?{groups:t.map(n=>({id:n.id,title:n.title,subtitle:n.subtitle,nodes:[...n.nodes]}))}:null}function dr(e,t,n){let o=e.sections??[],r=o.findIndex(g=>g.id===t);if(r<0)return null;let a=o[r],i=o[r+1],l=ye(e),d=i!==void 0&&i.kind==="save"==(a.kind==="save")&&Ke(e).some(g=>g.source===a.nodes[a.nodes.length-1]&&g.target===i.nodes[0])&&l.some(g=>g.id===i.nodes[0]),c=n?a.nodes.indexOf(n):-1;return{section:a,mergeWith:d?i:void 0,splitAt:a.kind!=="save"&&c>0?a.steps[c]:void 0}}function ri(e,t={}){let n=t.minLength??6,o=t.maxLength??10,r=[...ye(e)].sort((h,p)=>h.index-p.index),a=new Map,i=new Map;for(let h of Ke(e))a.set(h.target,[...a.get(h.target)??[],h]),i.set(h.source,[...i.get(h.source)??[],h]);let l=(h,p)=>{let u=i.get(h.id)??[],f=a.get(p.id)??[];return u.length===1&&f.length===1&&u[0].target===p.id&&At(u[0])==="sequence"&&le(h)==="action"&&le(p)==="action"},d=[],c=[];for(let h of r)c.length&&l(c[c.length-1],h)?c.push(h):(c.length&&d.push(c),c=le(h)==="action"?[h]:[]);c.length&&d.push(c);let g=[];for(let h of d){if(h.lengthm.id)})}}return{groups:g}}var ap={nodeWidth:194,nodeHeight:70,xGap:42,yGap:48,margin:34,minWidth:0,laneGap:14,laneInset:22},xt=6;function ai(e){return new Map(e.map((t,n)=>[t.id,Number.isFinite(t.index)?t.index:n]))}function si(e,t){let n=t.get(e.source),o=t.get(e.target);return n===void 0||o===void 0?!1:o<=n}function sp(e){let t=[...ye(e)],n=ai(t);t.sort((h,p)=>n.get(h.id)-n.get(p.id));let o=new Set(t.map(h=>h.id)),r=Ke(e).filter(h=>o.has(h.source)&&o.has(h.target)),a=r.filter(h=>!si(h,n)),i=new Map(t.map(h=>[h.id,[]])),l=new Map(t.map(h=>[h.id,[]]));for(let h of a)i.get(h.target).push(h),l.get(h.source).push(h);let d=h=>{let p=new Set([h]),u=[h];for(;u.length;){let f=u.shift();for(let v of r)v.target===f&&!p.has(v.source)&&(p.add(v.source),u.push(v.source))}return p},c=[];for(let h of t){let p=l.get(h.id).filter(y=>At(y)==="loop_body");if(le(h)!=="loop"&&p.length===0)continue;let u=l.get(h.id).filter(y=>At(y)!=="loop_body").map(y=>y.target);if(p.length===0||u.length===0)continue;let f=new Set([h.id,...u]),v=d(h.id),m=new Set,b=p.map(y=>y.target).filter(y=>!f.has(y));for(;b.length;){let y=b.shift();if(!m.has(y)){m.add(y);for(let _ of l.get(y))f.has(_.target)||b.push(_.target)}}for(let y of m)v.has(y)||m.delete(y);c.push({exits:u,body:m})}let g=new Map(t.map(h=>[h.id,0]));for(let h=0;h<=t.length;h+=1){let p=!1,u=(f,v)=>{v>g.get(f)&&(g.set(f,v),p=!0)};for(let f of t)for(let v of i.get(f.id))u(f.id,g.get(v.source)+1);for(let f of c){if(f.body.size===0)continue;let v=Math.max(...[...f.body].map(m=>g.get(m)));for(let m of f.exits)u(m,v+1)}if(!p)break}return g}function ip(e,t,n){let o=Math.min(t,n),r=Math.max(t,n);for(let a=0;;a+=1)if(e[a]??=[],e[a].every(i=>ri.to))return e[a].push({from:o,to:r}),a}function ii(e,t={}){let n={...ap,...t},o=ye(e),r=ai(o),a=sp(e),i=new Set(o.map(S=>S.id)),l=Ke(e).filter(S=>i.has(S.source)&&i.has(S.target)),d=new Map;for(let S of o){let A=a.get(S.id)??0,O=d.get(A)??[];O.push(S),d.set(A,O)}for(let S of d.values())S.sort((A,O)=>r.get(A.id)-r.get(O.id));let c=Math.max(0,...a.values()),g=Math.max(1,...[...d.values()].map(S=>S.length)),h=S=>n.margin+S*(n.nodeHeight+n.yGap),p=l.map((S,A)=>{let O=si(S,r),I=(a.get(S.target)??0)-(a.get(S.source)??0);return{edge:S,index:A,back:O,lane:O?"right":I===1?null:"left",slot:0}}),u=[],f=[];for(let S of p){if(S.lane===null)continue;let A=a.get(S.edge.source)??0,O=a.get(S.edge.target)??0;S.slot=ip(S.lane==="left"?u:f,A,O)}let v=S=>S?n.laneInset+(S-1)*n.laneGap+12:0,m=g*n.nodeWidth+(g-1)*n.xGap,b=Math.max(n.minWidth,n.margin*2+m+2*Math.max(v(u.length),v(f.length))),y=n.margin*2+(c+1)*n.nodeHeight+c*n.yGap,_=[];for(let[S,A]of[...d.entries()].sort((O,I)=>O[0]-I[0])){let O=A.length*n.nodeWidth+(A.length-1)*n.xGap,I=(b-O)/2;A.forEach(($,C)=>{_.push({id:$.id,x:I+C*(n.nodeWidth+n.xGap),y:h(S),width:n.nodeWidth,height:n.nodeHeight,rank:S})})}let w=new Map(_.map(S=>[S.id,S])),N=(S,A)=>{let O=Math.min(S,A),I=Math.max(S,A),$=_.filter(C=>C.rank>=O&&C.rank<=I);return{left:Math.min(...$.map(C=>C.x)),right:Math.max(...$.map(C=>C.x+C.width))}},M=p.map(({edge:S,index:A,back:O,lane:I,slot:$})=>{let C=w.get(S.source),R=w.get(S.target),k=At(S),B=S.label??"",H=`${S.source}:${S.target}:${k}:${A}`,G=C.y+C.height/2,V=R.y+R.height/2;if(I===null){let te=C.x+C.width/2,Y=R.x+R.width/2,K=C.y+C.height,xe=R.y,we=(K+xe)/2;return{id:H,source:S.source,target:S.target,kind:k,label:B,path:`M ${te} ${K} C ${te} ${we}, ${Y} ${we}, ${Y} ${xe}`,labelX:(te+Y)/2+6,labelY:we+3,labelRotate:!1,backEdge:O,lane:I}}let me=N(C.rank,R.rank);if(I==="right"){let te=me.right+n.laneInset+$*n.laneGap,Y=C.x+C.width,K=R.x+R.width,xe=VG;return{id:H,source:S.source,target:S.target,kind:k,label:B,path:`M ${Me} ${G} H ${Q+ce} Q ${Q} ${G} ${Q} ${G+(Ee?ce:-ce)} V ${V+(Ee?-ce:ce)} Q ${Q} ${V} ${Q+ce} ${V} H ${ee}`,labelX:Q-8,labelY:(G+V)/2,labelRotate:!0,backEdge:O,lane:I}});return{width:b,height:y,nodes:_,edges:M}}function pr(e){return/^(click|double click) at \(\d+,\s*\d+\)$/i.test(e.title.trim())?e.action==="double_click"?"Double-click recorded target":"Click recorded target":e.title}function ur(e){let t=le(e);if(t==="terminal"){let n=e.outcome?.toLowerCase();return n==="halt"||n==="halted"||n==="escalate"?"stop":"terminal"}return e.risk==="irreversible"?"halt":t==="branch"||t==="loop"?"branch":e.identity?.armed||it(e).length>0?"governed":"default"}var lp=e=>String(e).padStart(2,"0"),_n=e=>e.index+1;function li(e,t="index"){if(t==="index")return _n;let n=new Map;return[...ye(e)].sort((o,r)=>o.index-r.index).filter(o=>le(o)==="action").forEach((o,r)=>n.set(o.id,r+1)),o=>n.get(o.id)??null}var cp={loop:"LOOP",branch:"IF",business_decision:"ASK",subflow_call:"CALL",child_bundle:"SUB",action:"STEP"};function so(e,t=_n){if(le(e)==="terminal")return ur(e)==="stop"?"STOP":"END";let n=t(e);return n===null?cp[le(e)]??"STEP":lp(n)}function Kt(e){return le(e).replaceAll("_"," ")}function io(e){let t=e.resolution?.rungs?.filter(o=>o.present)??[],n=e.identity;return{resolve:{state:t.length?"present":"none",count:t.length,labels:t.map(o=>o.label)},identity:{state:n?.armed?"present":n?.applicable?"warn":"none",text:n?.armed?"Checked":n?.applicable?"Not checked":"Not needed"},screen:{state:yn(e).length?"present":"none",count:yn(e).length},readback:{state:it(e).length?"present":"none",count:it(e).length}}}function ci(e,t=pr(e),n=_n){let o=so(e,n),a=[`${/^\d+$/.test(o)?`step ${o}, ${Kt(e)}`:o==="END"||o==="STOP"?`${o.toLowerCase()}, ${Kt(e)}`:Kt(e)}: ${t}.`];e.identity?.armed&&a.push("Checks the right record."),it(e).length&&a.push("Reads the saved record back.");let i=Fe(e).length;return i&&a.push(`${i} stop ${i===1?"rule":"rules"}.`),a.join(" ")}var Ye=[[/^halts until an operator binds the placeholder effect$/,{kind:"run",text:"Waits until a person names the check for this save."}],[/^halts if the system-of-record effect is not confirmed$/,{kind:"run",text:"Stops if reading the saved record back doesn’t confirm it."}],[/^halts if precondition unmet/,{kind:"run",text:"Stops if the screen isn’t in the expected state before this step."}],[/^halts if not ready in time/,{kind:"run",text:"Stops if the screen isn’t ready in time."}],[/^irreversible write WITHOUT an armed identity gate$/,{kind:"review",text:"Flagged for review: this action can’t be undone, and this step has no right-record check of its own."}],[/^certification halts until action risk is explicitly reviewed$/,{kind:"review",text:"A person reviews this action before the program is approved to run on its own."}],[/^halts until an authenticated answer is signed$/,{kind:"decision",text:"Waits for a signed answer from a person."}],[/^terminal: (halt|escalate)$/,{kind:"end",text:"The program ends here and hands the item to a person."}]];function Wt(e){let t=Fe(e);if(t.length===0)return[];if(!t.every(c=>/^declared stop rule \d+$/.test(c)))return t.map(c=>Ye.find(([g])=>g.test(c))?.[1]??{kind:"run",text:c});let n=c=>Ye.find(([g])=>g.source===c.source)[1],o=le(e);if(o==="terminal")return t.map(()=>Ye[Ye.length-1][1]);if(o==="business_decision")return t.map(()=>Ye[6][1]);let r=[],a=[],i=it(e);i.length&&r.push(n(i.some(c=>c.needs_operator_confirmation)?Ye[0][0]:Ye[1][0])),e.guard_on_unmet==="halt"&&r.push(n(Ye[2][0])),e.risk==="irreversible"&&e.identity?.applicable&&e.identity.armed===!1&&a.push(n(Ye[4][0])),e.risk_review_required&&a.push(n(Ye[5][0]));let l=e.wait_until!=null?[n(Ye[3][0])]:[],d=[...r,...l,...a];return d.length===t.length-1&&!e.wait_until&&(d=[...r,n(Ye[3][0]),...a]),d.length!==t.length?t.map(()=>({kind:"run",text:"Stops if a declared check fails."})):d}function lo(e){return e?.events.find(t=>t.status==="halted")??null}function di(e,t,n){let o=Math.max(0,Math.min(t,e.events.length)),r=u=>n?.get(u)??u,a=new Map,i=new Map,l=new Set,d=null,c=null,g=null,h=null;for(let u=0;u${v}`,l.add(d)):d=null,c=v,g===f&&(d=`${v}>${Ze}`,l.add(d),a.set(Ze,{status:"halted",visits:1,iterations:0,last:f,events:[f]}))}let p=o>0?e.events[o-1]:null;if(p){let u=a.get(r(p.node));u.status!=="halted"&&(u.status="active")}return{cursor:o,nodes:a,taken:l,latestEdge:d,current:p,iteration:h,halted:g,finished:o===e.events.length}}function pi(e,t,n){let r=e.events[t]?.duration_ms;return r==null||!Number.isFinite(r)?140:Math.max(45,Math.min(700,r/Math.max(n,.1)))}function ui(e,t,n){let o=p=>n?.get(p)??p,r=ye(e),a=o(t.node),i=r.find(p=>p.id===a),l=t.iteration??null,d={node:t.node,status:t.status==="stopped"?"halted":"ok",iteration:l,reason:t.reason??null},c=new Map,g=new Set,h=null;if(i){for(let p of r){if(p.index>=i.index||p.id===Ze||le(p)==="terminal")continue;let u=le(p)==="loop";c.set(p.id,{status:"done",visits:1,iterations:u&&l?l:0,events:[]})}c.set(a,{status:t.status==="stopped"?"halted":"active",visits:1,iterations:le(i)==="loop"&&l?l:0,last:d,events:[d]});for(let p of Ke(e)){let u=r.find(v=>v.id===p.source),f=r.find(v=>v.id===p.target);u&&f&&u.indexu.index&&g.add(`${u.id}>${f.id}`)}if(le(i)==="loop"&&(l??1)>1){let p=Ke(e).find(u=>{let f=r.find(v=>v.id===u.source);return u.target===a&&f!==void 0&&f.index>i.index});p&&(h=`${p.source}>${a}`)}else{let p=Ke(e).find(u=>{let f=r.find(v=>v.id===u.source);return u.target===a&&f!==void 0&&f.index${a}`)}h&&g.add(h),t.status==="stopped"&&(h=`${a}>${Ze}`,g.add(h),c.set(Ze,{status:"halted",visits:1,iterations:0,last:d,events:[d]}))}return{cursor:0,nodes:c,taken:g,latestEdge:h,current:d,iteration:l,halted:t.status==="stopped"?d:null,finished:t.status==="stopped"}}var fi=(e,t)=>{for(let n=0;nu.title),r=[...ye(e)].sort((u,f)=>u.index-f.index),a=r.filter(u=>le(u)==="action"),i=[],l=u=>n?fi(n,f=>n.events[f].node===u):-1,d=u=>{let f=l(u);return f>=0?f+1:null};a.length&&i.push({id:"recording",title:"Recorded once",body:`OpenAdapt compiled these ${a.length} steps from one recorded run of the task. Each card is a step, or a section of steps you can open.`,select:a[0].id,cursor:n?0:null,view:"program"});let c=a.find(u=>(u.resolution?.rungs??[]).filter(f=>f.present).length>=2);if(c){let u=(c.resolution?.rungs??[]).filter(f=>f.present).map(f=>f.label.toLowerCase());i.push({id:"step",title:"One step",body:`“${o(c)}” recorded ${u.length} ways to find its target: ${u.join(", ")}. A run tries the strongest first.`,select:c.id,cursor:d(c.id),view:"program"})}let g=r.find(u=>le(u)==="loop");if(g){let u=n?new Set(n.events.map(v=>v.iteration).filter(v=>v!=null)).size:0,f=n?fi(n,v=>n.events[v].node===g.id&&n.events[v].iteration===2):-1;i.push({id:"loop",title:"The loop",body:u>1?`The steps run once for each item in the list. This run reached ${u} items; the dashed line is the return for the next one.`:"The steps run once for each item in the list; the dashed line is the return for the next one.",select:g.id,cursor:f>=0?f+1:d(g.id),view:"program"})}let h=a.find(u=>u.identity?.armed&&u.id!==c?.id)??a.find(u=>u.identity?.armed);h&&i.push({id:"right-record",title:"The right-record check",body:"Before this step acts, it checks that the screen shows the right record. If it doesn’t, the run stops instead of acting.",select:h.id,cursor:d(h.id),view:"program"});let p=lo(n);if(n&&p)i.push({id:"stop",title:"A stop",body:p.reason??"The run stopped here, where a check failed.",select:p.node,cursor:n.events.indexOf(p)+1,view:"program"});else{let u=a.find(f=>Fe(f).length>0);u&&i.push({id:"stop",title:"A stop rule",body:Wt(u).map(f=>f.text).join(" "),select:u.id,cursor:d(u.id),view:"program"})}return n?.receipt&&i.push({id:"receipt",title:n.receipt.kind==="seal"?"The Seal":"The run record",body:n.receipt.summary,select:p?.node??null,cursor:n.events.length,view:"program"}),i}dt();var dp={program:"Program map",evidence:"Evidence lanes",stops:"Stop rules"},pp="The map follows the emitted edge targets. It keeps each loop and exception route visible.",up="These rows show the declared contract. They do not report a live verdict.",fr=e=>String(e).padStart(2,"0"),po=zt(_n);function fp(){let[e,t]=D(!1);return U(()=>{if(typeof window>"u"||!window.matchMedia)return;let n=window.matchMedia("(prefers-reduced-motion: reduce)");t(n.matches);let o=()=>t(n.matches);return n.addEventListener?.("change",o),()=>n.removeEventListener?.("change",o)},[]),e}function ht({label:e,state:t,value:n}){return s("div",{className:"opg-evidence-state","data-state":t,children:[s("span",{children:e}),s("strong",{children:n})]})}function hr(e,t,n){return t?t.first===t.last?fr(t.first):`${fr(t.first)}–${fr(t.last)}`:so(e,n)}function hp({state:e}){let t=e.last;if(!t)return null;let n=[];return n.push(["Reached",e.iterations>1?`${e.iterations} iterations`:e.visits>1?`${e.visits} times`:"Once","none"]),t.rung&&n.push(["Found by",t.rung,"present"]),t.identity&&n.push(["Right record",t.identity==="verified"?"Verified":"Not verified",t.identity==="verified"?"present":"warn"]),t.screen_check&&n.push(["Screen check",t.screen_check==="passed"?"Passed":"Failed",t.screen_check==="passed"?"present":"warn"]),t.effect_checks?n.push(["Read-back",`${t.effect_checks.confirmed} of ${t.effect_checks.total} confirmed`,t.effect_checks.confirmed===t.effect_checks.total?"present":"warn"]):t.effect&&n.push(["Read-back",t.effect,t.effect==="confirmed"?"present":"warn"]),t.duration_ms!=null&&n.push(["Took",`${(t.duration_ms/1e3).toFixed(1)} s`,"none"]),s("div",{className:"opg-run-facts","aria-label":"This run at this step",children:[s("span",{children:"This run"}),n.map(([o,r,a])=>s(ht,{label:o,state:a,value:r},o)),e.status==="halted"&&t.reason&&s("div",{className:"opg-stop-rule","data-run":"halted",children:[s("span",{children:"Stopped here"}),s("strong",{children:t.reason})]})]})}function gp({node:e,fold:t,run:n,resolveMedia:o,title:r}){if(!o)return null;let a=t?t.members.find(h=>h.media?.recorded):e,i=a?.media?.recorded,l=i?.crop??i?.frame??null,d=a&&l?o(l,{node:a.id,kind:i?.crop?"recorded-crop":"recorded-frame"}):null,c=n?[...n.events].reverse().find(h=>h.frame):void 0,g=c?.frame?o(c.frame,{node:c.node,kind:"live",iteration:c.iteration}):null;return!d&&!g?null:s("div",{className:"opg-media",children:[s("span",{children:"Pictures"}),s("div",{className:"opg-media-pair",children:[d&&s("figure",{children:[s("a",{href:d,target:"_blank",rel:"noopener noreferrer",children:s("img",{src:d,alt:a?.media?.alt||`The recorded target of ${r}`,loading:"lazy",decoding:"async"})}),s("figcaption",{children:"Recorded"})]}),g&&s("figure",{children:[s("a",{href:g,target:"_blank",rel:"noopener noreferrer",children:s("img",{src:g,alt:`The screen in this run at ${r}`,loading:"lazy",decoding:"async"})}),s("figcaption",{children:["This run",c?.iteration!=null?`, iteration ${c.iteration}`:""]})]})]})]})}function mp({review:e,folded:t,onEditSection:n}){let{section:o,mergeWith:r,splitAt:a}=e,[i,l]=D(!1),[d,c]=D(o.title);return U(()=>{l(!1),c(o.title)},[o.id,o.title]),s("div",{className:"opg-section-review","aria-label":"Review this section",children:[s("span",{children:"Section"}),t&&i?s("form",{onSubmit:h=>{h.preventDefault();let p=d.replace(/\s+/g," ").trim();p&&p!==o.title&&n({op:"rename",section:o.section,title:p}),l(!1)},children:[s("input",{"aria-label":"Section title",value:d,maxLength:80,autoFocus:!0,onChange:h=>c(h.target.value)}),s("button",{type:"submit",children:"Save"}),s("button",{type:"button",onClick:()=>l(!1),children:"Cancel"})]}):t&&s("button",{type:"button",className:"opg-fold-toggle",onClick:()=>l(!0),children:"Rename this section"}),t&&r&&s("button",{type:"button",className:"opg-fold-toggle",onClick:()=>n({op:"merge",section:o.section,other:r.section}),children:"Merge with the next section"}),!t&&a&&s("button",{type:"button",className:"opg-fold-toggle",onClick:()=>n({op:"split",section:o.section,at:a}),children:"Start a new section at this step"})]})}function bp({node:e,fold:t,partOf:n,run:o,titleFor:r,onUnfold:a,onRefold:i,onPickMember:l,plainStopRules:d,resolveMedia:c,onClose:g,review:h,onEditSection:p}){let u=yt(po),f=io(e),v=t?.members.map(io)??[],m=e.id===Ze;return s("aside",{className:"opg-inspector","aria-label":"Selected program step","aria-live":"polite",children:[s("div",{className:"opg-inspector-head",children:[s("span",{children:t?"Selected steps":"Selected step"}),s("code",{children:hr(e,t,u)}),g&&s("button",{type:"button",className:"opg-icon-button",onClick:g,"aria-label":"Close the step details",children:s(kn,{d:"M3 3l8 8M11 3l-8 8"})})]}),s("h3",{children:r(e)}),s("p",{className:"opg-mono",children:t?t.subtitle??`${t.members.length} steps`:m?"Where a stop rule ends the run":e.id}),!m&&s("div",{className:"opg-inspector-lanes",children:t?s(ae,{children:[s(ht,{label:"Finds the field",state:v.some(b=>b.resolve.count)?"present":"none",value:`${v.filter(b=>b.resolve.count).length} of ${t.members.length} steps`}),s(ht,{label:"Right record",state:f.identity.state,value:`${v.filter(b=>b.identity.text==="Checked").length} checked`}),s(ht,{label:"Screen check",state:f.screen.state,value:f.screen.count?`${f.screen.count} checks`:"Not declared"}),s(ht,{label:"Read-back",state:f.readback.state,value:f.readback.count?`${f.readback.count} independent checks`:"Not declared"})]}):s(ae,{children:[s(ht,{label:"Finds the field",state:f.resolve.state,value:f.resolve.count?`${f.resolve.count} evidence types`:"Not applicable"}),s(ht,{label:"Right record",state:f.identity.state,value:f.identity.text}),s(ht,{label:"Screen check",state:f.screen.state,value:f.screen.count?`${f.screen.count} checks`:"Not declared"}),s(ht,{label:"Read-back",state:f.readback.state,value:f.readback.count?`${f.readback.count} independent checks`:"Not declared"})]})}),!t&&e.resolution&&(e.resolution.rungs?.length??0)>0&&s("div",{className:"opg-ladder",children:[s("span",{children:"Recorded resolution evidence"}),s("ol",{children:e.resolution.rungs.map(b=>s("li",{"data-present":b.present||void 0,"data-top":b.name===e.resolution?.top_rung||void 0,children:[s("i",{"aria-hidden":"true"}),b.label,s("span",{className:"opg-sr-only",children:b.present?" (recorded)":" (not recorded)"})]},b.name))})]}),t&&s("div",{className:"opg-fold-members",children:[s("span",{children:"Steps in this card"}),s("ol",{children:t.members.map(b=>s("li",{children:s("button",{type:"button",onClick:()=>l(t.id,b.id),children:[s("code",{children:so(b,u)}),r(b)]})},b.id))}),s("button",{type:"button",className:"opg-fold-toggle",onClick:()=>a(t.id),children:["Show the ",t.members.length," steps"]})]}),n&&s("button",{type:"button",className:"opg-fold-toggle",onClick:()=>i(n.id),children:["Fold into “",n.title,"”"]}),h&&p&&s(mp,{review:h,folded:!!t,onEditSection:p}),Fe(e).length>0&&(d?s("div",{className:"opg-stop-rule",children:[s("span",{children:"Stop rules"}),(t?t.members.flatMap(Wt):Wt(e)).filter((b,y,_)=>_.findIndex(w=>w.text===b.text)===y).map((b,y)=>s("strong",{"data-kind":b.kind,children:b.text},y))]}):s("div",{className:"opg-stop-rule",children:[s("span",{children:"Stops before acting if"}),s("strong",{children:Fe(e).join("; ")})]})),s(gp,{node:e,fold:t,run:o,resolveMedia:c,title:r(e)}),o&&o.status!=="pending"&&s(hp,{state:o})]})}function vp(e,t){if(!t)return;let n=`${e.source}>${e.target}`;if(t.latestEdge===n)return"latest";if(t.taken.has(n))return"taken"}function yp({display:e,fullSpec:t,folds:n,expanded:o,setExpanded:r,traceState:a,selectedId:i,setSelectedId:l,titleFor:d,canvasNote:c,layoutOptions:g,showInspector:h=!0,plainStopRules:p,compact:u=!1,resolveMedia:f,inspectorOpen:v,setInspectorOpen:m,onEditSection:b}){let y=yt(po),_=ne(()=>ii(e.spec,g),[e.spec,g]),w=ye(e.spec),N=ne(()=>new Map(w.map(T=>[T.id,T])),[w]),M=`opg-arrow-${st().replace(/[^a-zA-Z0-9_-]/g,"")}`,S=X(new Map),A=X(null),O=e.ownerOf.get(i)??(N.has(i)?i:w[0]?.id),I=N.get(O??"")??w[0],[$,C]=D(1),R=Se(T=>C(Math.round(Math.max(.4,Math.min(1.6,T))*100)/100),[]),[k,B]=D(!1),H=u&&!k,G=X(null),V=X(new Map),[me,Q]=D(0);U(()=>{let T=new Set,L=q=>{let Z=V.current.get(q.pointerId);if(!Z)return;let Te=requestAnimationFrame(()=>{T.delete(Te),V.current.get(q.pointerId)===Z&&(V.current.delete(q.pointerId),V.current.size||Q(Ie=>Ie+1))});T.add(Te)},de=()=>{V.current.clear(),Q(q=>q+1)};return window.addEventListener("pointerup",L),window.addEventListener("pointercancel",L),window.addEventListener("blur",de),()=>{window.removeEventListener("pointerup",L),window.removeEventListener("pointercancel",L),window.removeEventListener("blur",de);for(let q of T)cancelAnimationFrame(q);V.current.clear()}},[]);let Me=a?.current?e.ownerOf.get(a.current.node):void 0;U(()=>{let T=G.current,L=_.nodes.find(Zt=>Zt.id===Me);if(!T||!L||V.current.size)return;let q=T.firstElementChild?.offsetLeft??0,Z=L.x*$+q,Te=L.y*$,Ie=L.width*$,Ce=L.height*$,J=Te>=T.scrollTop&&Te+Ce<=T.scrollTop+T.clientHeight,ue=Z>=T.scrollLeft&&Z+Ie<=T.scrollLeft+T.clientWidth;if(J&&ue)return;let et=J?T.scrollTop:Math.max(0,Te-(T.clientHeight-Ce)/2),_t=ue?T.scrollLeft:Math.max(0,Z-(T.clientWidth-Ie)/2);typeof T.scrollTo=="function"?T.scrollTo({top:et,left:_t}):(T.scrollTop=et,T.scrollLeft=_t)},[Me,a?.cursor,_,$,me]),U(()=>{let T=G.current;if(!T||!u)return;let L=de=>{!de.ctrlKey&&!de.metaKey||(de.preventDefault(),C(q=>Math.round(Math.max(.4,Math.min(1.6,q*(de.deltaY>0?.9:1.1)))*100)/100))};return T.addEventListener("wheel",L,{passive:!1}),()=>T.removeEventListener("wheel",L)},[u]);let ee=X(null),ce=u?{onPointerDown:T=>{if(T.target.closest("button")||T.button!==0)return;let L=G.current;ee.current={x:T.clientX,y:T.clientY,left:L.scrollLeft,top:L.scrollTop},L.setPointerCapture?.(T.pointerId)},onPointerMove:T=>{let L=ee.current,de=G.current;!L||!de||(de.scrollLeft=L.left-(T.clientX-L.x),de.scrollTop=L.top-(T.clientY-L.y))},onPointerUp:()=>{ee.current=null},onPointerCancel:()=>{ee.current=null}}:{},Ee=()=>{let T=G.current;T&&R(Math.min(1,(T.clientWidth-16)/_.width,(T.clientHeight-16)/_.height))};if(U(()=>{let T=A.current;T&&(A.current=null,S.current.get(T)?.focus())}),!I)return s("p",{className:"opg-empty",children:"The compiled graph is empty."});let te=n?.groups.find(T=>o.has(T.id)&&T.nodes.includes(I.id)),Y=b?e.folds.has(I.id)?dr(t,I.id):te?dr(t,te.id,I.id):null:null,K=s(bp,{node:I,fold:e.folds.get(I.id),partOf:te?{id:te.id,title:te.title??te.id}:void 0,review:Y,onEditSection:b,run:a?.nodes.get(I.id),titleFor:d,plainStopRules:p,resolveMedia:f,onClose:u?()=>m(!1):void 0,onUnfold:T=>{let L=e.folds.get(T);r(new Set([...o,T])),L&&(l(L.members[0].id,"user"),A.current=L.members[0].id)},onRefold:T=>{let L=new Set(o);L.delete(T),r(L),l(T,"user"),A.current=T},onPickMember:(T,L)=>{r(new Set([...o,T])),l(L,"user"),A.current=L}}),xe=T=>a?.nodes.get(T),we=Ke(t).length,Qe=ye(t).length,uo=w.filter(T=>T.id!==Ze).length,qt=(T,L)=>{let de=_.nodes.find(J=>J.id===L);if(!de)return;let q,Z=J=>_.nodes.filter(ue=>ue.rank===J).sort((ue,et)=>ue.x-et.x),Te=J=>Z(J).sort((ue,et)=>Math.abs(ue.x-de.x)-Math.abs(et.x-de.x))[0]?.id,Ie=[...new Set(_.nodes.map(J=>J.rank))].sort((J,ue)=>J-ue),Ce=Ie.indexOf(de.rank);switch(T.key){case"ArrowDown":q=_.edges.find(J=>J.source===L&&!J.backEdge)?.target??(CeJ.target===L&&!J.backEdge)?.source??(Ce>0?Te(Ie[Ce-1]):void 0);break;case"ArrowRight":case"ArrowLeft":{let J=Z(de.rank),ue=J.findIndex(et=>et.id===L)+(T.key==="ArrowRight"?1:-1);q=J[ue]?.id;break}case"Home":q=_.nodes.slice().sort((J,ue)=>J.rank-ue.rank||J.x-ue.x)[0]?.id;break;case"End":q=_.nodes.slice().sort((J,ue)=>ue.rank-J.rank||ue.x-J.x)[0]?.id;break;default:return}T.preventDefault(),q&&(l(q,"user"),S.current.get(q)?.focus())};return s("div",{className:"opg-grid","data-inspector":h&&v||void 0,"data-staged":H||void 0,children:[s("div",{className:"opg-canvas-shell",children:[s("div",{className:"opg-canvas-head",children:[s("span",{children:"Compiled topology"}),s("span",{children:[Qe," nodes · ",we," exact edges",e.folds.size>0&&` · ${uo} cards`]})]}),u&&s("div",{className:"opg-stage-tools",role:"toolbar","aria-label":"Map view",children:[s("button",{type:"button",onClick:()=>R($-.1),"aria-label":"Zoom out",disabled:$<=.4,children:s(kn,{d:"M3 7h8"})}),s("span",{"aria-live":"polite",children:[Math.round($*100),"%"]}),s("button",{type:"button",onClick:()=>R($+.1),"aria-label":"Zoom in",disabled:$>=1.6,children:s(kn,{d:"M3 7h8M7 3v8"})}),s("button",{type:"button",onClick:Ee,children:"Fit"}),s("button",{type:"button",onClick:()=>B(!k),"aria-pressed":k,children:k?"Collapse":"Expand"}),h&&!v&&s("button",{type:"button",onClick:()=>m(!0),children:"Show step details"})]}),s("div",{className:"opg-canvas-viewport",ref:G,onPointerDownCapture:T=>{T.button===0&&T.isPrimary!==!1&&V.current.set(T.pointerId,{})},"data-stage":H||void 0,"data-pan":u||void 0,...ce,children:s("div",{className:"opg-canvas-sizer",style:{width:_.width*$,height:_.height*$},children:s("div",{className:"opg-canvas",style:{width:_.width,height:_.height,transform:$===1?void 0:`scale(${$})`},children:[s("svg",{className:"opg-edges",viewBox:`0 0 ${_.width} ${_.height}`,width:_.width,height:_.height,role:"img","aria-label":`${_.edges.length} compiled program edges`,children:[s("defs",{children:s("marker",{id:M,markerWidth:"8",markerHeight:"8",refX:"7",refY:"4",orient:"auto",markerUnits:"strokeWidth",children:s("path",{d:"M 0 0 L 8 4 L 0 8 z"})})}),_.edges.map(T=>s("g",{"data-kind":T.kind,"data-back-edge":T.backEdge||void 0,"data-lane":T.lane??void 0,"data-run":vp(T,a),children:[s("path",{d:T.path,markerEnd:`url(#${M})`}),T.label&&s("text",{x:T.labelX,y:T.labelY,textAnchor:T.labelRotate?"middle":void 0,dominantBaseline:T.labelRotate?"middle":void 0,transform:T.labelRotate?`rotate(-90 ${T.labelX} ${T.labelY})`:void 0,children:T.label})]},T.id))]}),_.nodes.map(T=>{let L=N.get(T.id),de=L.id===I.id,q=e.folds.get(L.id),Z=xe(L.id),Te=d(L),Ie=Z&&Z.status!=="pending"?` This run: ${Z.status==="halted"?"stopped here":Z.status==="active"?"here now":"reached"}${Z.iterations>1?`, ${Z.iterations} iterations`:""}.`:"";return s("button",{ref:Ce=>{Ce?S.current.set(L.id,Ce):S.current.delete(L.id)},type:"button",className:"opg-node","data-tone":ur(L),"data-fold":q?"folded":void 0,"data-selected":de||void 0,"data-run":Z?.status,style:{left:T.x,top:T.y,width:T.width,height:T.height},"aria-pressed":de,"aria-label":q?`Steps ${hr(L,q,y)}, ${q.members.length} steps: ${Te}.${Ie}`:`${ci(L,Te,y)}${Ie}`,tabIndex:de?0:-1,onClick:()=>{l(L.id,"user"),v||m(!0)},onDoubleClick:()=>{q&&(r(new Set([...o,q.id])),l(q.members[0].id,"user"),A.current=q.members[0].id)},onKeyDown:Ce=>qt(Ce,L.id),children:[s("span",{className:"opg-node-index",children:hr(L,q,y)}),s("span",{className:"opg-node-copy",children:[s("small",{children:q?q.subtitle??`${q.members.length} steps`:Kt(L)}),s("strong",{title:q?Te:void 0,children:Te})]}),s("span",{className:"opg-node-signals","aria-hidden":"true",children:[le(L)==="loop"&&Z&&Z.iterations>0&&s("b",{children:["×",Z.iterations]}),L.identity?.armed&&s("i",{title:"Checks the right record",children:"R"}),it(L).length>0&&s("i",{title:"Reads the saved record back",children:"C"}),Fe(L).length>0&&s("i",{title:"Stop rules",children:"H"})]})]},L.id)})]})})}),s("ul",{className:"opg-sr-only","aria-label":"Program edges",children:_.edges.map(T=>s("li",{children:[d(N.get(T.source))," to ",d(N.get(T.target)),T.backEdge?", returns to an earlier step":""," (",T.kind.replaceAll("_"," "),T.label?`: ${T.label}`:"",")"]},T.id))}),c&&s("p",{className:"opg-canvas-note",children:c})]}),h&&v&&K]})}function xp({spec:e,titleFor:t,note:n}){return s("div",{className:"opg-matrix-scroll",children:[s("table",{className:"opg-matrix",children:[s("thead",{children:s("tr",{children:[s("th",{scope:"col",children:"Step"}),s("th",{scope:"col",children:"Finds the field"}),s("th",{scope:"col",children:"Right record"}),s("th",{scope:"col",children:"Screen check"}),s("th",{scope:"col",children:"Read-back"})]})}),s("tbody",{children:ye(e).map(o=>{let r=io(o);return s("tr",{children:[s("td",{children:[s("strong",{children:t(o)}),s("small",{className:"opg-mono",children:o.id})]}),s("td",{"data-state":r.resolve.state,children:r.resolve.count?r.resolve.labels.join(", "):"Not applicable"}),s("td",{"data-state":r.identity.state,children:r.identity.text}),s("td",{"data-state":r.screen.state,children:r.screen.count?`${r.screen.count} declared`:"Not declared"}),s("td",{"data-state":r.readback.state,children:r.readback.count?`${r.readback.count} independent`:"Not declared"})]},`evidence-${o.id}`)})})]}),n&&s("p",{className:"opg-boundary-note",children:n})]})}function _p({spec:e,titleFor:t,halt:n,plain:o}){let r=yt(po),a=ye(e).filter(l=>Fe(l).length>0||le(l)==="terminal"),i=n?ye(e).find(l=>l.id===n.node):void 0;return s("div",{className:"opg-stop-list",children:[n&&i&&s("article",{"data-run":"halted",children:[s("span",{className:"opg-mono",children:["this run stopped at step ",r(i)??i.index+1]}),s("strong",{children:t(i)}),s("p",{children:n.reason??"The run stopped at this step."})]}),a.length===0?s("p",{className:"opg-empty",children:"This graph does not declare a stop rule or terminal outcome."}):a.map(l=>s("article",{children:[s("span",{className:"opg-mono",children:le(l)==="terminal"?"terminal":r(l)===null?Kt(l):`step ${r(l)}`}),s("strong",{children:t(l)}),s("p",{children:Fe(l).length?o?Wt(l).map(d=>d.text).join(" "):Fe(l).join("; "):"Declared terminal program state."})]},`stop-${l.id}`))]})}function kn({d:e}){return s("svg",{viewBox:"0 0 14 14",width:"12",height:"12","aria-hidden":"true",focusable:"false",children:s("path",{d:e})})}function kp({trace:e,state:t,playing:n,setPlaying:o,setCursor:r,iterationNoun:a,liveFrame:i}){let l=e.events.length,d=new Set(e.events.map(h=>h.iteration).filter(h=>h!=null)).size,c=t.cursor===0?"Ready":t.iteration!=null?`${a[0].toUpperCase()}${a.slice(1)} ${t.iteration} of ${d}`:`Step ${t.cursor} of ${l}`,g=t.halted&&t.finished?`Stopped. ${t.halted.reason??""}`:t.finished?"The run finished.":t.iteration!=null?`${a} ${t.iteration}`:"";return s("div",{className:"opg-player",role:"group","aria-label":"Run trace player",children:[s("button",{type:"button",onClick:()=>r(0),"aria-label":"Back to the start",disabled:t.cursor===0,children:"⏮"}),s("button",{type:"button",onClick:()=>r(t.cursor-1),"aria-label":"Step back",disabled:t.cursor===0,children:s(kn,{d:"M11 2 4 7l7 5z"})}),s("button",{type:"button",className:"opg-play",onClick:()=>{t.finished&&r(0),o(!n)},"aria-label":n?"Pause":t.finished?"Replay":"Play",children:n?"Pause":t.finished?"Replay":"Play"}),s("button",{type:"button",onClick:()=>r(t.cursor+1),"aria-label":"Step forward",disabled:t.finished,children:s(kn,{d:"M3 2l7 5-7 5z"})}),s("input",{type:"range",min:0,max:l,value:t.cursor,onChange:h=>{o(!1),r(Number(h.target.value))},"aria-label":"Run position","aria-valuetext":`${c}, event ${t.cursor} of ${l}`}),s("span",{className:"opg-player-where",children:c}),i&&s("img",{className:"opg-player-frame",src:i,alt:"The screen in this run now",decoding:"async"}),s("span",{className:"opg-sr-only","aria-live":"polite",children:g})]})}function wp({trace:e,state:t,playing:n}){if(!e||!t)return s("span",{className:"opg-trace-state",children:[s("i",{})," No live trace bound"]});let o=t.halted&&t.finished?"halted":t.finished?"done":n?"playing":"ready",r=o==="halted"?"Run stopped":o==="done"?"Run finished":o==="playing"?"Playing run trace":"Run trace bound";return s("span",{className:"opg-trace-state","data-run":o,children:[s("i",{})," ",e.label?`${r} · ${e.label}`:r]})}function Sp({receipt:e}){let t=e.label??(e.kind==="seal"?"Seal":"Run record");return s("section",{className:"opg-receipt","data-kind":e.kind,"data-status":e.status.toLowerCase(),"aria-label":t,children:[s("div",{children:[s("span",{className:"opg-kicker",children:t}),s("strong",{children:e.status})]}),s("p",{children:e.summary}),e.href&&s("a",{href:e.href,target:"_blank",rel:"noopener noreferrer",children:e.kind==="seal"?"Open the Seal":"Open the run record"})]})}function Np({stop:e,at:t,count:n,focus:o,onBack:r,onNext:a,onSkip:i}){let l=`opg-tour-${st().replace(/[^a-zA-Z0-9_-]/g,"")}`,d=X(null);return U(()=>{o.current&&d.current?.focus()},[t,o]),s("section",{className:"opg-tour",role:"region","aria-labelledby":l,onKeyDown:c=>{if(c.key==="Escape")i();else if(c.key==="ArrowRight"&&!(c.target instanceof HTMLInputElement))a();else if(c.key==="ArrowLeft"&&t>0)r();else return;c.preventDefault()},children:[s("span",{className:"opg-kicker",children:["Tour · ",t+1," of ",n]}),s("h3",{id:l,ref:d,tabIndex:-1,"aria-live":"polite",children:e.title}),s("p",{children:e.body}),s("div",{className:"opg-tour-actions",children:[s("button",{type:"button",onClick:r,disabled:t===0,children:"Back"}),s("button",{type:"button",className:"opg-tour-next",onClick:a,children:t+1===n?"Done":"Next"}),s("button",{type:"button",className:"opg-tour-skip",onClick:i,children:"Skip the tour"})]})]})}function Ep(e){let{spec:t,folds:n,stopExits:o,trace:r,playhead:a,autoPlay:i=!1,initialCursor:l=0,speed:d=14,numbering:c}=e,g=ne(()=>li(t,c),[t,c]),[h,p]=D(e.initialSelectedId??ye(t)[0]?.id??""),u=e.selectedId??h,[f,v]=D(()=>new Set),m=ne(()=>e.expanded?new Set(e.expanded):f,[e.expanded,f]),b=fp(),[y,_]=D(l),w=e.cursor??y,[N,M]=D(!1),S=r?.events.length??0,{onSelect:A,onCursorChange:O,onExpandedChange:I}=e,$=Se((ee,ce)=>{p(ee),A?.(ee,ce)},[A]),C=Se(ee=>{v(ee),I?.([...ee])},[I]),R=X(w);R.current=w;let k=Se(ee=>{let ce=Math.max(0,Math.min(S,ee));_(ce),O?.(ce)},[S,O]);U(()=>{e.cursor===void 0&&_(Math.max(0,Math.min(r?.events.length??0,l))),M(!!r&&i&&!b)},[r,i,b,l]),U(()=>{if(!N||!r)return;if(w>=S){M(!1);return}let ee=setTimeout(()=>k(R.current+1),pi(r,w,d));return()=>clearTimeout(ee)},[N,w,S,r,d,k]);let B=r?lo(r):a?.status==="stopped"?{node:a.node,status:"halted"}:null,H=ne(()=>{let ee=[...o??[]];return B&&!ee.some(ce=>ce.node===B.node)&&ee.push({node:B.node,label:"stopped"}),ee},[o,B?.node]),G=ne(()=>ni(t,{folds:n,expanded:m,stopExits:H,numberOf:g}),[t,n,m,H,g]),V=ne(()=>r?di(r,w,G.ownerOf):a?ui(G.spec,a,G.ownerOf):null,[r,w,a,G]),me=X(null),Q=Se(ee=>{me.current=`c${ee}`},[]),Me=r?`c${w}`:a?`p${a.node}:${a.iteration??""}:${a.status}`:null;return U(()=>{if(!V?.current||Me===null||me.current===Me)return;let ee=me.current===null&&w===0&&!!r;me.current=Me,ee||$(V.current.node,"follow")},[V,Me,w,r,$]),{selectedId:u,setSelectedId:$,expanded:m,setExpanded:C,cursor:w,setCursor:k,playing:N,setPlaying:M,display:G,traceState:V,numberOf:g,suppressFollow:Q}}function gr(e){let{spec:t,title:n,kicker:o="The steps",trace:r,iterationNoun:a="iteration",views:i=["program","evidence","stops"],initialView:l,titleFor:d=pr,notes:c,layout:g,theme:h="dark",className:p,style:u,showHeader:f=!0,showPlayer:v=!0,showInspector:m=!0,plainStopRules:b=!1,compact:y=!1,resolveMedia:_,tour:w,tourSeen:N=!1,onTourEnd:M}=e,S=ne(()=>e.folds!==void 0?e.folds:oi(t)??(y?ri(t):null),[e.folds,y,t]),A=Ep({...e,folds:S}),[O,I]=D(l??i[0]??"program"),{traceState:$}=A,[C,R]=D(!0),k=ne(()=>w===!0?co(t,{trace:r,title:d}):Array.isArray(w)?w:[],[w,t,r,d]),[B,H]=D(()=>k.length&&!N?0:null),G=X(!1);U(()=>{if(B===null)return;let K=k[B];K&&(A.setPlaying(!1),K.view&&I(K.view),K.cursor!=null&&r&&(A.suppressFollow(K.cursor),A.setCursor(K.cursor)),K.select&&A.setSelectedId(K.select,"tour"),R(!0))},[B,k]);let V=K=>{H(null),M?.(K)},me=k.length>0&&B===null?s("button",{type:"button",className:"opg-tour-launch",onClick:()=>{G.current=!0,H(0)},children:"Take the tour"}):null,Q=r?.receipt&&$?.finished?r.receipt:null,Me=_&&$?.current?.frame?_($.current.frame,{node:$.current.node,kind:"live",iteration:$.current.iteration}):null,ee=st().replace(/[^a-zA-Z0-9_-]/g,""),ce=X(new Map),Ee=i.length>1,te=(K,xe)=>{let we=i.indexOf(xe),Qe=K.key==="ArrowRight"?i[(we+1)%i.length]:K.key==="ArrowLeft"?i[(we-1+i.length)%i.length]:K.key==="Home"?i[0]:K.key==="End"?i[i.length-1]:void 0;Qe&&(K.preventDefault(),I(Qe),ce.current.get(Qe)?.focus())},Y=(K,xe)=>Ee?s("div",{role:"tabpanel",id:`${ee}-panel-${K}`,"aria-labelledby":`${ee}-tab-${K}`,hidden:O!==K,tabIndex:-1,children:O===K&&xe}):O===K&&s("div",{children:xe});return s(po.Provider,{value:A.numberOf,children:s("div",{className:`opg-root${p?` ${p}`:""}`,"data-theme":h,"data-compact":y||void 0,style:u,children:[f&&s("div",{className:"opg-topbar",children:[s("div",{children:[s("span",{className:"opg-kicker",children:o}),s("strong",{children:n??t.bundle.name})]}),s("div",{className:"opg-topbar-end",children:[me,s(wp,{trace:r,state:r?$:null,playing:A.playing})]})]}),!f&&me&&s("div",{className:"opg-tour-bar",children:me}),v&&r&&$&&s(kp,{trace:r,state:$,playing:A.playing,setPlaying:A.setPlaying,setCursor:A.setCursor,iterationNoun:a,liveFrame:Me}),B!==null&&k[B]&&s(Np,{stop:k[B],at:B,count:k.length,focus:G,onBack:()=>H(Math.max(0,B-1)),onNext:()=>B+1V("skipped")}),Q&&s(Sp,{receipt:Q}),Ee&&s("div",{className:"opg-tabs",role:"tablist","aria-label":"Program workbench views",children:i.map(K=>s("button",{ref:xe=>{xe&&ce.current.set(K,xe)},id:`${ee}-tab-${K}`,type:"button",role:"tab","aria-selected":O===K,"aria-controls":`${ee}-panel-${K}`,tabIndex:O===K?0:-1,onClick:()=>I(K),onKeyDown:xe=>te(xe,K),children:dp[K]},K))}),i.includes("program")&&Y("program",s(yp,{display:A.display,fullSpec:t,folds:S,expanded:A.expanded,setExpanded:A.setExpanded,traceState:$,selectedId:A.selectedId,setSelectedId:A.setSelectedId,titleFor:d,canvasNote:c?.canvas===void 0?pp:c.canvas,layoutOptions:g,showInspector:m,plainStopRules:b,compact:y,resolveMedia:_,inspectorOpen:C,setInspectorOpen:R,onEditSection:e.onEditSection})),i.includes("evidence")&&Y("evidence",s(xp,{spec:t,titleFor:d,note:c?.evidence===void 0?up:c.evidence})),i.includes("stops")&&Y("stops",s(_p,{spec:t,titleFor:d,halt:$?.finished?$.halted:null,plain:b}))]})})}dt();var gt={host:"Qo",card:"V",cardIn:"do",body:"Vo",kicker:"Wo",line:"Zo",sub:"ar",action:"W",others:"ma"};function $p(e){let t=e.querySelector(".opg-inspector-head span")?.textContent||"";if(t==="Selected step"){let n=e.querySelector(":scope > p.opg-mono")?.textContent||null;return n?{step:n}:null}if(t==="Selected steps"){let n=e.querySelector(":scope > h3")?.textContent||null;return n?{fold:n}:null}return null}function Ap(e,t,n){if(!e)return[];if(e.step)return t.includes(e.step)?[e.step]:[];let o=n.find(r=>(r.title??r.id)===e.fold);return o?t.filter(r=>o.nodes.includes(r)):[]}function hi(e,t,n){let[o,r]=D({host:null,ids:[]}),a=t.join(" ");return U(()=>{let i=e.current;if(!i||!a)return;let l=a.split(" "),d=null,c="",g=()=>{let p=i.querySelector(".opg-inspector"),u=p?Ap($p(p),l,n):[];if(!u.length){d&&(d.remove(),d=null,c="",r({host:null,ids:[]}));return}d||(d=document.createElement("div"),d.className=gt.host,d.dataset.sealCardHost=""),p.firstChild!==d&&p.prepend(d);let f=u.join(" ");f!==c&&(c=f,r({host:d,ids:u}))},h=new MutationObserver(g);return h.observe(i,{childList:!0,subtree:!0,characterData:!0}),g(),()=>{h.disconnect(),d?.remove(),r({host:null,ids:[]})}},[e,a,n]),o}function gi({seals:e,here:t=!1,Link:n="a"}){let[o,...r]=e,a=o.anchor?.kind==="stop",i=!t;return s("section",{className:gt.card,"data-tone":o.tone,"data-seal-card":i?"open":"here","aria-label":"This step's receipt",children:[s(ti,{seed:o.irisSeed,tone:o.tone,size:58}),s("div",{className:gt.body,children:[s("p",{className:gt.kicker,children:i?`Signed here${o.n?` · referral ${o.n}`:""}`:"This is the step the receipt covers"}),s("p",{className:gt.line,children:o.line}),s("p",{className:gt.sub,children:a?"The run stopped here, before saving, and was signed.":"The save its read-backs prove, signed on the machine that ran it."}),i?s(n,{className:gt.action,"data-seal-open":"",href:o.href,children:"Open the receipt →"}):null,r.length?s("p",{className:gt.others,children:[s("span",{children:"Also signed here:"}),r.map(l=>s(n,{href:l.href,children:["Referral ",l.n]},l.n))]}):null]})]})}var Mp=[];function mr({program:e,map:t={},step:n,status:o,onPick:r,anchor:a=null,sealRun:i=null,sealLine:l="",theme:d="dark",fill:c=!1}){let{spec:g,folds:h=null,titles:p={}}=e,u=h?.groups||Mp,f=ne(()=>g.nodes.filter(R=>R.kind==="action").map(R=>R.id),[g]),v=ne(()=>Object.fromEntries(u.flatMap(R=>R.nodes.map(k=>[k,R.id]))),[u]),m=ne(()=>R=>p[R.id]||R.title,[p]),b=ne(()=>co(g,{title:m}),[g,m]),y=X(null);U(()=>{let R=y.current;if(!R)return;for(let Q of R.querySelectorAll("[data-seal-anchor]"))delete Q.dataset.sealAnchor;if(!a)return;let k=f[a.step],B=p[k],H=u.find(Q=>Q.nodes.includes(k)),G=[...R.querySelectorAll(".opg-node")],V=Q=>Q.getAttribute("aria-label")||"",me=(B?G.find(Q=>!Q.dataset.fold&&V(Q).includes(B)):null)||(H?G.find(Q=>Q.dataset.fold&&V(Q).includes(`: ${H.title}.`)):null);me&&(me.dataset.sealAnchor=a.kind)}),U(()=>{let R=y.current;if(!R||!c||typeof ResizeObserver>"u")return;let k=0,B=()=>{k=0;let G=R.querySelector(".opg-root"),V=R.querySelector(".opg-canvas-viewport");if(!G||!V)return;let me=G.offsetHeight-V.offsetHeight,Q=Math.max(240,Math.floor(R.clientHeight-me-2));R.style.getPropertyValue("--seal-stage-h")!==`${Q}px`&&R.style.setProperty("--seal-stage-h",`${Q}px`)},H=new ResizeObserver(()=>{k||(k=requestAnimationFrame(B))});return H.observe(R),B(),()=>{H.disconnect(),cancelAnimationFrame(k),R.style.removeProperty("--seal-stage-h")}},[c]);let _=n!=null?f[n]:null,[w,N]=D(null);U(()=>N(null),[_]);let[M,S]=D([]),A=ne(()=>[...new Set([...M,..._&&v[_]?[v[_]]:[]])],[M,_,v]),O=ne(()=>_?{node:_,iteration:1,status:o||"running"}:null,[_,o]),I=a?f[a.step]:null,$=ne(()=>I?[I]:[],[I]),C=hi(y,$,u).host;return s("div",{className:E.map,"data-step":n??"","data-fill":c?"1":void 0,ref:y,children:[s(gr,{spec:g,folds:h,stopExits:h?.stops,compact:!0,numbering:"actions",kicker:t.kicker||"Compiled program",title:t.title,titleFor:m,resolveMedia:t.resolveMedia,tour:b,tourSeen:!0,plainStopRules:!0,theme:d,playhead:O,selectedId:w||_||f[0],onSelect:(R,k)=>{if(k==="follow")return;if(I&&v[I]===R&&u.some(H=>H.id===R)){N(null),r(a.step);return}let B=f.indexOf(R);B>=0?(N(null),r(B)):N(R)},expanded:A,onExpandedChange:S}),C&&i?Fn(s(gi,{seals:[{...i,line:l,anchor:a}],here:!0}),C):null]})}var mi=3400,Rp=1700,Ip=[1,2,4],Cp={subject_mismatch:"The report doesn't match the SHA-256 the receipt signed.",bad_signature:"The Ed25519 signature doesn't match the signed fields.",malformed:"The receipt file isn't well formed.",unknown_key:"The receipt names a key this site doesn't pin.",revoked_key:"The receipt names a revoked key.",key_mismatch:"The key in the receipt isn't the key this site pins.",ambiguous_key:"The pinned key list names this key twice."},Pp=new Set(["unknown_key","key_mismatch","ambiguous_key"]),bi=e=>Cp[e]||(String(e).startsWith("anchor_")?"The public log's record doesn't back this signature.":String(e).startsWith("auth")?"The authorization doesn't cover this run.":"The check failed."),Vt=e=>`${(e/1e3).toFixed(1)} s`,Op=(e,t)=>`${e} of ${t} record checks confirmed`,zp=e=>e&&e.charAt(0).toUpperCase()+e.slice(1);function Lp(){let[e,t]=D(!1);return U(()=>{let n=window.matchMedia("(prefers-reduced-motion: reduce)"),o=()=>t(n.matches);return o(),n.addEventListener("change",o),()=>n.removeEventListener("change",o)},[]),e}function Dp(e){let[t,n]=D(!1);return U(()=>{let o=window.matchMedia(e),r=()=>n(o.matches);return r(),o.addEventListener("change",r),()=>o.removeEventListener("change",r)},[e]),t}var Si="oa-theme",vi=()=>{try{let e=window.localStorage.getItem(Si);return e==="light"||e==="dark"?e:null}catch{return null}},yi=()=>window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark",xi=()=>{let e=document.documentElement.getAttribute("data-theme");return e==="light"||e==="dark"?e:null};function Fp(e){let[t,n]=D("dark");U(()=>{let r=()=>xi()||vi()||yi(),a=()=>{let c=r();e&&!xi()&&document.documentElement.setAttribute("data-theme",c),n(c)};a();let i=window.matchMedia("(prefers-color-scheme: light)"),l=()=>{vi()||(e&&document.documentElement.setAttribute("data-theme",yi()),a())};i.addEventListener("change",l);let d=new MutationObserver(()=>n(r()));return d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>{i.removeEventListener("change",l),d.disconnect()}},[e]);let o=Se(()=>{let r=t==="dark"?"light":"dark";document.documentElement.setAttribute("data-theme",r);let a=document.querySelector('meta[name="theme-color"]');a&&a.setAttribute("content",r==="light"?"#ffffff":"#05080d");try{window.localStorage.setItem(Si,r)}catch{}n(r)},[t]);return[t,o]}var Ni=["summary","steps","evidence","raw"],Hp={summary:"Summary",program:"Program",steps:"Steps",evidence:"Evidence",raw:"Raw"};function jp(e){let t=new URLSearchParams(window.location.hash.replace(/^#/,"")),n=t.get("tab"),o=Number.parseInt(t.get("step")||"",10);return{tab:Ni.includes(n)||n==="program"?n:null,step:Number.isInteger(o)&&o>=1&&o<=e?o-1:null}}function _i(e,t){let n=[];return e&&e!=="summary"&&n.push(`tab=${e}`),t!=null&&n.push(`step=${t+1}`),n.length?`#${n.join("&")}`:""}function Gp(e,t){U(()=>{let n=e.current;if(!n||!t||!window.matchMedia("(hover: hover) and (pointer: fine)").matches)return;let o=0,r=0,a=0,i=0,l=0,d=()=>{a+=(o-a)*.08,i+=(r-i)*.08,n.style.setProperty("--px",a.toFixed(4)),n.style.setProperty("--py",i.toFixed(4)),l=Math.abs(o-a)+Math.abs(r-i)>8e-4?requestAnimationFrame(d):0},c=h=>{let p=n.getBoundingClientRect();o=Math.max(-1,Math.min(1,(h.clientX-p.left)/p.width*2-1)),r=Math.max(-1,Math.min(1,(h.clientY-p.top)/p.height*2-1)),l||(l=requestAnimationFrame(d))},g=()=>{o=0,r=0,l||(l=requestAnimationFrame(d))};return window.addEventListener("pointermove",c,{passive:!0}),document.documentElement.addEventListener("pointerleave",g),()=>{window.removeEventListener("pointermove",c),document.documentElement.removeEventListener("pointerleave",g),cancelAnimationFrame(l),n.style.removeProperty("--px"),n.style.removeProperty("--py")}},[e,t])}function Ei(e){let t=e.rings.counts;return{title:`${e.label} · ${e.job} · OpenAdapt Receipt`,description:`${e.app}, ${e.job}: ${e.label}. ${t.stepsPassed} of ${t.steps} steps, ${t.checksPassed} of ${t.checks} screen checks${t.readbacksPassed?`, ${t.readbacksPassed} of ${t.readbacks} record checks confirmed`:""}. A signed run report you can check in your browser.`}}function vr({seal:e,host:t={}}){let{loadFiles:n=null,Link:o="a",links:r={},copyHref:a=null,live:i=!0,kicker:l=null,footer:d=null,trustWords:c="signed by the pinned key",unchanged:g="The published files are unchanged; this was a copy in your browser.",canonicalOrigin:h=null,chrome:p=!0,map:u={},signer:f=null,mediaNote:v="From this computer's run folder: not part of the receipt, never uploaded"}=t,{rings:m,seal:b,tone:y,label:_,line:w,job:N,app:M,startedAt:S,stopReason:A,media:O,tamper:I,runs:$,referral:C,referrals:R,files:k,keys:B,authorization:H,authorizedLine:G,authTiming:V,stopNote:me,program:Q,commands:Me=null,irisSeed:ee}=e,ce=Lp(),[Ee,te]=D("build"),[Y,K]=D(null),[xe,we]=D(null),[Qe,uo]=D(ee),qt=!!(k.anchor||k.tsa),[T,L]=D(null),[de,q]=D(null),[Z,Te]=D(null),[Ie,Ce]=D(!1),[J,ue]=D(null),[et,_t]=D(null),[Zt,wn]=D(0),[Li,xr]=D(null),[_r,fo]=D(!1),[Sn,Di]=D(Me),[Yt,Fi]=Fp(p),mt=Dp("(min-width: 900px)"),[Nn,Rt]=D("summary"),[Hi,ji]=D(!1),[ho,kr]=D(!1),[go,wr]=D(50),[Sr,Gi]=D(!1),En=X(null),mo=X(null),Jt=X(0);Gp(mo,!ce);let Ui=X(null),$e=ne(()=>qs(m),[m]),[Je,Xt]=D(null),[tt,bt]=D(!1),[bo,Bi]=D(1),Oe=Je!==null,nt=Oe?$e[Je]:null,Ki=ne(()=>nt?Zs(nt,m):null,[nt,m]);U(()=>{if(!p)return;let{body:x,documentElement:P}=document,W=[x.style.background,P.style.background];return x.style.background="var(--oa-canvas)",P.style.background="var(--oa-canvas)",()=>{x.style.background=W[0],P.style.background=W[1]}},[p]),U(()=>{try{let x=Number(window.localStorage.getItem("oa-seal-split"));x>=30&&x<=70&&wr(x)}catch{}},[]);let Qt=Se(x=>{let P=Math.max(30,Math.min(70,Math.round(x)));wr(P);try{window.localStorage.setItem("oa-seal-split",String(P))}catch{}},[]);U(()=>{let x=()=>{let P=jp(m.steps.length);P.tab&&Rt(P.tab),P.step!=null&&(ue(P.step),wn(P.step),P.tab||Rt("evidence"))};return x(),Gi(!0),window.addEventListener("hashchange",x),()=>window.removeEventListener("hashchange",x)},[m.steps.length]),U(()=>{Nn==="program"&&ji(!0)},[Nn]),U(()=>{let x=window.location.origin;Me&&h&&/^https?:/.test(x)&&x!==h&&Di(Me.split(h).join(x))},[Me,h]);let Wi=async(x,P,W)=>{if(x.sealOk&&!x.ok)return{...x,record:null};if(!x.sealOk&&(W.anchor||W.authorization))return{...x,ok:!1,reason:W.authorization?"auth_missing":"anchor_missing",record:null};if(!P.receiptKeys)return{...x,ok:!1,reason:"unknown_key",record:null};let oe;try{oe=JSON.parse(P.receiptText)}catch{return{...x,ok:!1,reason:"malformed",record:null}}let Le=await Is(oe,P.receiptKeys);if(!Le.ok)return{...x,ok:!1,reason:Le.reason,record:Le};let be=Le.statement.subject.find(ot=>ot.name==="report.json");return!be||be.digest.sha256!==await Re(P.report)?{...x,ok:!1,reason:"subject_mismatch",record:Le}:{...x,ok:!0,reason:null,record:Le}},en=Se(async x=>{let P=++Jt.current;Te(x||null),K(null),we(null),L(null),Xt(null),bt(!1),te("verify");let W=new Promise(be=>setTimeout(be,ce?0:Rp)),oe,Le=null;try{En.current=En.current||await(n?n():Cs(k,H));let be=x?zs(En.current,x):En.current,ot={anchor:!!k.anchor,authorization:!!H};oe=await ks(be,B,{requireAnchor:ot.anchor,requireAuthorization:ot.authorization}),be.receiptText&&(oe=await Wi(oe,be,ot)),Le=qt?await Bs(be,B):null;try{let wo=await gn(JSON.parse(be.sealText)),il=await Re(new TextEncoder().encode(`${await Re(be.report)}${wo}`));P===Jt.current&&uo(il)}catch{}}catch{oe={ok:!1,reason:"not_loaded",steps:[]}}P===Jt.current&&we(oe.subject?.sha256??null),await W,P===Jt.current&&(L(Le),K(oe),te(oe.ok?"valid":oe.reason==="unsupported"||oe.reason==="not_loaded"?"rest":"broken"))},[k,B,H,ce,qt,n]),[Vi,qi]=D("unverified");U(()=>{if(!i||!H||!Y?.ok||!Y.authorizedBy?.publicKey)return;let x=!1;return ps(H.login,Y.authorizedBy.publicKey).then(P=>{x||qi(P)}),()=>{x=!0}},[H,Y,i]);let vo=V??Y?.timing??null,yo=H&&(G||(vo==="before_run"||vo==="after_run")&&Y?.ok)?hs(H.login,vo,H.anchorTime??Y?.authAnchorTime,Vi):null,Nr=X(!1);U(()=>{!i||!T?.rekor?.ok||Z||Nr.current||(Nr.current=!0,q("checking"),Ws(T.rekor.entry).then(q))},[T,Z,i]),U(()=>{ce&&te("rest");let x=setTimeout(()=>en(null),ce?0:mi+450);return()=>clearTimeout(x)},[ce]),U(()=>{if(!Oe||!tt)return;if(Je>=$e.length-1){bt(!1);return}let x=setTimeout(()=>Xt(P=>Math.min($e.length-1,P+1)),$e[Je].dwell/bo);return()=>clearTimeout(x)},[Oe,tt,Je,$e,bo]);let xo=Se(()=>{Jt.current+=1,Te(null),te("replay"),ue(null),_t(null),Rt(x=>x==="program"?x:"evidence"),Xt(x=>x===null||x>=$e.length-1?0:x),bt(!0)},[$e.length]),kt=Se((x,P=!1)=>{te("replay"),Xt(Math.max(0,Math.min($e.length-1,x))),P||bt(!1)},[$e.length]),Er=()=>{Xt(null),bt(!1),te(Y?.ok?"valid":Y?"broken":"rest")},Tr=()=>kt(Ys($e,Je??-1),tt),tn=x=>{let P=nt?nt.step:-1,W=Math.max(0,Math.min($e.at(-1).step,P+x));kt(to($e,W))};U(()=>{let x=P=>{let W=P.target;if(W&&(W.closest?.("input, textarea, select, [contenteditable]")||P.metaKey||P.ctrlKey||P.altKey))return;let oe=!!W?.closest?.('[role="tablist"], [role="separator"], [data-steplist], .opg-root'),Le=W?.closest?.("button, a, summary");if(!(oe&&P.key!=="j"&&P.key!=="k")){if(P.key===" "&&!Le&&!W?.closest?.("[data-step]"))P.preventDefault(),tt?bt(!1):xo();else if(Oe&&P.key==="ArrowRight"&&!W?.closest?.("[data-step]"))P.preventDefault(),P.shiftKey?Tr():tn(1);else if(Oe&&P.key==="ArrowLeft"&&!W?.closest?.("[data-step]"))P.preventDefault(),tn(-1);else if(Oe&&P.key==="Escape")Er();else if((P.key==="j"||P.key==="k")&&!P.shiftKey){P.preventDefault();let be=P.key==="j"?1:-1;if(Oe)tn(be);else{let ot=m.steps.length,wo=J??(be>0?-1:ot);lt(Math.max(0,Math.min(ot-1,wo+be)))}}}};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)});let Tn=Oe?nt.step:J??et,nn=Tn!=null?m.steps[Tn]:null,$r=Se((x,P={})=>{P.focus&&wn(x),Je!==null?kt(to($e,x)):_t(x)},[Je,$e,kt]),lt=Se((x,{keepTab:P=!1}={})=>{Je!==null?kt(to($e,x)):ue(x),wn(x),P||Rt(W=>W==="program"?W:"evidence")},[Je,$e,kt]),Zi=x=>{let P=m.steps.length,W={ArrowRight:1,ArrowDown:1,ArrowLeft:-1,ArrowUp:-1},oe=null;if(x.key in W)oe=(Zt+W[x.key]+P)%P;else if(x.key==="Home")oe=0;else if(x.key==="End")oe=P-1;else if(x.key==="Escape"){ue(null),_t(null),x.currentTarget.blur();return}else if(x.key==="Enter"||x.key===" "){x.preventDefault(),lt(Zt);return}else return;x.preventDefault(),wn(oe),$r(oe),mo.current?.querySelector(`[data-step="${oe}"]`)?.focus()},We=Nn==="program"&&mt?"summary":Nn,_o=Oe?null:J;U(()=>{if(!Sr||tt)return;let x=_i(We,_o);if(!(x===window.location.hash||!x&&!window.location.hash))try{window.history.replaceState(window.history.state,"",`${window.location.pathname}${window.location.search}${x}`)}catch{}},[We,_o,Sr,tt]);let Yi=async()=>{try{await navigator.clipboard.writeText(`${a}${_i(We,_o)}`),fo(!0),setTimeout(()=>fo(!1),2200)}catch{fo(!1)}},Pe=m.counts,Ar=[{ring:"steps",big:`${Pe.stepsPassed}/${Pe.steps}`,small:m.stoppedAt==null?"steps passed":`steps, stopped at ${m.stoppedAt+1}`},{ring:"checks",big:`${Pe.checksPassed}/${Pe.checks}`,small:Pe.checksFailed?`screen checks, ${Pe.checksFailed} failed`:"screen checks"},{ring:"readbacks",big:`${Pe.readbacksPassed}/${Pe.readbacks}`,small:Pe.readbacksFailed?`record checks, ${Pe.readbacksFailed} failed`:Pe.readbacksPassed?"record checks confirmed":"record checks, not reached"},{ring:"identity",big:`${Pe.identityPassed}/${Pe.identity}`,small:"right-record checks"}],Mr=S?Js(S):null,Rr=l??(C?`Referral ${C} of ${R}`:null),on=!!Z,_e=Ee==="verify"||Ee==="build"?null:Y?.ok?"valid":Y?.reason==="unsupported"?"unsupported":Y?.reason==="not_loaded"?"not_loaded":Y?"fails":null,Ir=(x,P)=>x?P?P.ok?"pass":"fail":"pending":null,Cr=qt?{rekor:Ir(k.anchor,T?.rekor),tsa:Ir(k.tsa,T?.tsa)}:null,Ji=`The receipt of this run: ${Ar.map(x=>`${x.big} ${x.small}`).join("; ")}.`,It=Ee==="verify"||Ee==="build",Ct=nn,Xi=Ct?`Step ${Ct.i+1} of ${m.steps.length}${Ct.section?` · ${Ct.section}`:""}${Ct.t0!=null?` · at ${Vt(Ct.t0)}`:""}`:null,ko=Oe?nt.step:J,ze=ko!=null?m.steps[ko]:null,Qi=m.steps.filter(x=>x.status!=="not_reached").length,Pr=_e===null?{state:"pending",text:Ee==="build"?"Assembling":"Checking signature"}:_e==="valid"?{state:"valid",text:on?"Restored · signature valid":"Signature valid"}:_e==="fails"?{state:"fails",text:on?"Changed copy fails":"Signature check fails"}:_e==="unsupported"?{state:"unchecked",text:"Report matches · signature not checked here"}:{state:"unchecked",text:"Not checked here"},Or=["summary","program","steps","evidence","raw"],wt=mt?Ni:Or,el=x=>{let P=wt.indexOf(We),W={ArrowRight:1,ArrowLeft:-1},oe=null;if(x.key in W)oe=wt[(P+W[x.key]+wt.length)%wt.length];else if(x.key==="Home")oe=wt[0];else if(x.key==="End")oe=wt[wt.length-1];else return;x.preventDefault(),Rt(oe),x.currentTarget.querySelector(`[data-tab="${oe}"]`)?.focus()},zr=X(null),Lr=X(null),Dr=X(null);U(()=>{let x=Lr.current,P=Dr.current;if(!x||!P||typeof ResizeObserver>"u")return;let W=new ResizeObserver(()=>P.style.setProperty("--top-h",`${x.offsetHeight}px`));return W.observe(x),()=>W.disconnect()},[]);let tl=x=>{let P={ArrowLeft:-2,ArrowRight:2};if(x.key in P)Qt(go+P[x.key]);else if(x.key==="Home")Qt(30);else if(x.key==="End")Qt(70);else if(x.key==="Enter")kr(W=>!W);else return;x.preventDefault()},nl=x=>{let P=zr.current;if(!P||x.button!==0)return;x.preventDefault();let W=x.currentTarget;W.setPointerCapture?.(x.pointerId);let oe=P.getBoundingClientRect(),Le=ot=>Qt((ot.clientX-oe.left)/oe.width*100),be=()=>{W.removeEventListener("pointermove",Le),W.removeEventListener("pointerup",be),W.removeEventListener("pointercancel",be)};W.addEventListener("pointermove",Le),W.addEventListener("pointerup",be),W.addEventListener("pointercancel",be)},ol=mt||We==="program"||Hi,rl=f==="demo"||b?.issuer==="demo",Pt=Y?.record??null,Fr=Pt?_e===null?{state:"pending",text:"Checking who signed it"}:Pt.ok&&_e==="valid"?{state:Pt.demo?"demo":"signed",text:Pt.signerLines.join(" · ")}:Pt.reason==="unknown_signer"?{state:"unknown",text:"Not verified: unknown signer"}:{state:"fails",text:Pt.signerLines?.[0]||"Not verified"}:_e===null?{state:"pending",text:"Checking who signed it"}:_e==="valid"?rl?{state:"demo",text:"Demo key: checks only in this demo"}:f==="this_computer"?{state:"signed",text:"Signed by this computer"}:{state:"signed",text:"Signed by a pinned key"}:Pp.has(Y?.reason)?{state:"unknown",text:"Not verified: unknown signer"}:_e==="fails"?{state:"fails",text:"Not verified: the signature check failed"}:{state:"unchecked",text:"Not verified here"},Hr=!!(k?.receiptText||Y?.record),al=!Hr&&typeof b?.schema=="string"&&/^openadapt\.(local-seal|public-seal)\//.test(b.schema),sl=_e===null?s("span",{className:E.pending,children:Ee==="build"?"Assembling the receipt from the report":"Checking the Ed25519 signature in your browser"}):_e==="valid"?s(ae,{children:[s("b",{children:"Valid."})," This is the report exactly as the run wrote it, ",c,"."]}):_e==="unsupported"?s(ae,{children:[s("b",{children:"The report matches."})," This browser can't check Ed25519 signatures; ",Sn?"use the commands under Raw.":"check it from a terminal: openadapt verify RUN_FOLDER."]}):_e==="not_loaded"?s(ae,{children:[s("b",{children:"The files didn't load,"})," so nothing was checked here. ",Sn?"Use the commands under Raw.":"Check it from a terminal: openadapt verify RUN_FOLDER."]}):s(ae,{children:[s("b",{children:"Fails."})," ",bi(Y.reason)," ",s("code",{className:E.code,children:Y.reason})]});return s(ae,{children:[s("a",{className:E.skip,href:"#main",onClick:x=>{x.preventDefault(),document.getElementById("main")?.focus()},children:"Skip to content"}),s("div",{ref:Dr,className:E.page,"data-tone":y,"data-phase":Ee,"data-theme":p?void 0:Yt,"data-layout":mt?"split":"stack","data-expanded":mt&&ho?"1":void 0,"data-view":We,style:{"--split":`${go}%`},children:[s("header",{className:E.top,ref:Lr,children:[r.home?s(o,{href:r.home.href,className:E.home,"aria-label":r.home.label,children:[s(ao,{className:E.mark}),s("span",{children:r.home.label})]}):s("span",{className:E.home,children:[s(ao,{className:E.mark}),s("span",{children:"OpenAdapt"})]}),s("span",{className:E.crumb,children:[s("span",{children:"Signed run report"}),Rr?s("span",{children:Rr}):null]}),$?.length?s("nav",{className:E.runs,"aria-label":"The other runs",children:$.map(x=>s(o,{href:x.href,className:E.run,"data-tone":x.tone,"aria-current":x.sealId===e.sealId?"page":void 0,title:`Referral ${x.referral}: ${x.label}`,children:[s("span",{className:E.runSeal,"aria-hidden":"true",children:s(ro,{rings:x.rings,tone:x.tone,digest:x.digest,variant:"emblem",phase:"rest",still:!0,label:""})}),s("span",{className:E.runText,children:[s("b",{children:x.referral}),s("span",{children:x.label})]})]},x.sealId))}):null,s("span",{className:E.topEnd,children:[s("span",{className:E.chip,"data-chip":Pr.state,role:"status",children:[s("span",{className:E.chipDot,"aria-hidden":"true"}),Pr.text]}),a?s("button",{type:"button",className:E.iconBtn,onClick:Yi,title:"Copy a link to this view","aria-label":_r?"Link copied":"Copy link",children:[s(Up,{}),s("span",{className:E.wideOnly,children:_r?"Copied":"Copy link"})]}):null,s("button",{type:"button",className:E.iconBtn,onClick:Fi,"aria-label":`Switch to the ${Yt==="dark"?"light":"dark"} theme`,title:`Switch to the ${Yt==="dark"?"light":"dark"} theme`,children:s(Bp,{theme:Yt})})]})]}),s("div",{className:E.app,ref:zr,children:[s("main",{id:"main",tabIndex:-1,className:E.hero,"aria-labelledby":"seal-h1",children:[s("section",{className:E.stage,ref:mo,"aria-label":"The receipt",tabIndex:-1,onMouseLeave:()=>_t(null),children:s("div",{className:E.tilt,ref:Ui,children:s(ro,{rings:m,tone:y,digest:Qe,phase:Ee,buildMs:mi,active:Oe?null:Tn,focusIndex:Zt,onActive:$r,onPick:lt,onKey:Zi,ringFocus:Li,witnesses:Cr,lit:Ki,spot:nt?.spotlight||null,label:Ji})})}),s("div",{className:E.heading,children:[s("h1",{id:"seal-h1",className:E.outcome,children:_}),A?s("p",{className:E.reason,children:zp(A)}):null,s("p",{className:E.meta,children:[s("span",{children:N}),s("span",{children:M}),Mr?s("span",{children:Mr}):null]}),s("p",{className:E.verdict,"data-verdict":_e||"pending","aria-live":"polite",children:sl}),s("p",{className:E.signer,"data-signer":Fr.state,children:s("span",{children:Fr.text})}),on&&_e==="fails"?s("div",{className:E.changed,"data-changed":"",children:[s("p",{className:E.changeHead,children:[s("b",{children:"This changed copy fails:"})," ",Z.field==="model_calls"?"model calls":"outcome"," ",Z.from," → ",Z.to,". The receipt no longer matches."]}),s("p",{className:E.change,children:["Changed in a copy of the ",Z.target==="seal"?"receipt":"report",": ",s("code",{children:Z.field})," ",s("del",{children:Z.from})," → ",s("ins",{children:Z.to}),"."]}),s("p",{className:E.change,children:g}),s("div",{className:E.actions,children:[s("button",{type:"button",className:E.primary,onClick:()=>en(null),disabled:It,children:"Restore"}),s("button",{type:"button",className:E.ghost,"aria-expanded":Ie,"aria-controls":"receipt-changes",onClick:()=>Ce(x=>!x),children:"Try another change"})]}),s("div",{id:"receipt-changes",className:E.another,role:"group","aria-label":"Other changes",hidden:!Ie,children:I.filter(x=>x.id!==Z.id).map(x=>s("button",{type:"button",className:E.tchip,disabled:It,onClick:()=>en(x),children:[s("span",{children:x.label}),s("code",{children:[x.from," → ",x.to]})]},x.id))})]}):null,s("div",{className:E.actions,children:[s("button",{type:"button",className:E.primary,onClick:tt?()=>bt(!1):xo,disabled:It,children:[s("span",{"aria-hidden":"true",children:tt?"❚❚":"▶"}),tt?"Pause the run":Oe?"Resume the run":"Play the run"]}),s("button",{type:"button",className:E.ghost,onClick:()=>en(null),disabled:It,children:"Verify"}),on&&_e==="fails"?null:s("button",{type:"button",className:E.ghost,onClick:()=>{Ce(!1),en(I[0])},disabled:It||!I.length,children:"Try changing it"})]})]}),s("div",{className:E.dock,children:[s(Wp,{frames:$e,frame:Je,playing:tt,speed:bo,busy:It,rings:m,onPlay:xo,onPause:()=>bt(!1),onSeek:kt,onNext:Tr,onSpeed:Bi,onClose:Er}),s("p",{className:E.stepLine,"data-step":nn?nn.i:"","aria-live":"polite",children:Xi||(_e==="valid"?`✓ Signature valid over this exact report · ${Qi} steps`:_e==="fails"?`✗ ${bi(Y?.reason)}`:" ")})]})]}),s("section",{className:E.mapPane,"aria-labelledby":"map-h",id:"seal-panel-program",role:mt?void 0:"tabpanel",children:[s("div",{className:E.paneHead,children:[s("h2",{id:"map-h",children:"Program steps for this run"}),mt?s("button",{type:"button",className:E.iconBtn,"aria-pressed":ho,onClick:()=>kr(x=>!x),children:ho?"Show details":"Expand map"}):null]}),ol?s(mr,{program:Q,map:{title:`${N} · ${M}`,...u},step:Tn,status:nn?nn.status==="stopped"?"stopped":nt?.stage==="done"?"saved":"running":null,onPick:x=>lt(x),anchor:m.anchor,sealRun:{rings:m,tone:y,irisSeed:Qe,referral:C},sealLine:Xs({rings:m,label:_,stopReason:A},_e==="valid"),theme:Yt,fill:mt}):null]}),s("div",{className:E.resizer,role:"separator","aria-orientation":"vertical","aria-label":"Resize the program map","aria-valuenow":go,"aria-valuemin":30,"aria-valuemax":70,tabIndex:0,onKeyDown:tl,onPointerDown:nl,onDoubleClick:()=>Qt(50),title:"Drag, or use the arrow keys. Enter expands the map."}),s("div",{className:E.tabs,role:"tablist","aria-label":"Details",onKeyDown:el,children:Or.map(x=>s("button",{type:"button",role:"tab",id:`seal-tab-${x}`,"data-tab":x,"aria-selected":We===x,"aria-controls":`seal-panel-${x}`,tabIndex:We===x?0:-1,onClick:()=>Rt(x),children:[Hp[x],x==="steps"?s("span",{className:E.count,children:m.steps.length}):null,x==="evidence"&&ze?s("span",{className:E.count,children:ze.i+1}):null]},x))}),s("div",{className:E.panels,children:[s("section",{id:"seal-panel-summary",role:"tabpanel","aria-labelledby":"seal-tab-summary",hidden:We!=="summary",className:E.panel,children:[s("p",{className:E.line,children:w}),H&&yo?s("p",{className:E.by,children:s("a",{href:`https://github.com/${H.login}`,rel:"noopener noreferrer",children:yo})}):null,s("dl",{className:E.stats,"aria-label":"What the receipt shows",children:Ar.map(x=>s("div",{"data-ring":x.ring,onMouseEnter:()=>xr(x.ring),onMouseLeave:()=>xr(null),children:[s("dt",{children:[s("span",{className:E.swatch,"aria-hidden":"true"}),x.small]}),s("dd",{children:x.big})]},x.ring))}),s("p",{className:E.calls,children:Pe.modelCalls==null?`The program ran for ${Vt(m.runMs)}.`:`The program ran for ${Vt(m.runMs)} and made ${Pe.modelCalls} AI model calls.`}),s("h2",{className:E.sub,children:"The signature check"}),s("div",{className:E.proof,children:[s(cr,{label:on&&Z.target==="report"?"This copy of report.json":"report.json, in this browser",from:b.signature,to:xe,against:b.subject_sha256,running:Ee==="verify",still:ce}),s("div",{className:E.signed,children:[s("span",{className:E.proofLabel,children:"Signed in the receipt"}),s("code",{className:E.hex,children:b.subject_sha256})]})]}),s("p",{className:E.foot,children:[d||"The signature comes from the machine that ran it: it shows the report hasn't changed since the run."," ",r.programMap?s(o,{href:r.programMap.href,children:r.programMap.label}):null," ",s("a",{href:r.docs||"https://docs.openadapt.ai/reference/receipts-and-seals/",children:"How receipts work"})]})]}),s("section",{id:"seal-panel-steps",role:"tabpanel","aria-labelledby":"seal-tab-steps",hidden:We!=="steps",className:E.panel,children:s(Kp,{rings:m,active:ko,onPick:x=>lt(x),onFocusStep:x=>lt(x,{keepTab:!0})})}),s("section",{id:"seal-panel-evidence",role:"tabpanel","aria-labelledby":"seal-tab-evidence",hidden:We!=="evidence",className:E.panel,children:ze?s(ae,{children:[s("div",{className:E.evHead,children:[s("p",{className:E.evTitle,children:[s("span",{className:E.evNum,children:["Step ",ze.i+1," of ",m.steps.length]}),ze.section?s("span",{children:ze.section}):null,ze.t0!=null?s("span",{children:["at ",Vt(ze.t0)]}):null]}),s("span",{className:E.evNav,children:[s("button",{type:"button",className:E.iconBtn,onClick:()=>Oe?tn(-1):lt(Math.max(0,ze.i-1)),disabled:ze.i===0,"aria-label":"Previous step",title:"Previous step (k)",children:"‹"}),s("button",{type:"button",className:E.iconBtn,onClick:()=>Oe?tn(1):lt(Math.min(m.steps.length-1,ze.i+1)),disabled:ze.i===m.steps.length-1,"aria-label":"Next step",title:"Next step (j)",children:"›"})]})]}),s(Vp,{step:ze,rings:m,media:O[ze.i],frame:nt,stopReason:A,stopNote:me,mediaNote:v})]}):s("div",{className:E.empty,children:[s("p",{children:["Pick a step on the map, on the receipt or in Steps to see its checks",O.some(x=>x&&(x.crop||x.frame))?", its pictures":""," and its record checks."]}),m.anchor?s("button",{type:"button",className:E.ghost,onClick:()=>lt(m.anchor.step),children:["Show the step the receipt covers (step ",m.anchor.step+1,")"]}):null]})}),s("section",{id:"seal-panel-raw",role:"tabpanel","aria-labelledby":"seal-tab-raw",hidden:We!=="raw",className:E.panel,children:[al?s("p",{className:E.older,"data-format":"",children:["Format: ",b.schema.replace(/^openadapt\./,""),", still verifies"]}):Hr?s("p",{className:E.older,"data-format":"",children:"Format: record/run/v1"}):null,s(Zp,{seal:b,files:k,links:r,witnesses:Cr,witness:T,live:Z?null:de,authorization:H,authorizedLine:yo}),Sn?s(ae,{children:[s("h2",{className:E.sub,children:e.commandsLabel||"Check the same files on your computer"}),s("pre",{className:E.cmds,tabIndex:0,children:s("code",{children:Sn})})]}):null]})]})]})]})]})}function Up(){return s("svg",{viewBox:"0 0 24 24",width:"15",height:"15","aria-hidden":"true",children:s("path",{d:"M10 14a4.5 4.5 0 0 0 6.4 0l3-3a4.5 4.5 0 0 0-6.4-6.4l-1 1M14 10a4.5 4.5 0 0 0-6.4 0l-3 3a4.5 4.5 0 0 0 6.4 6.4l1-1",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round"})})}function Bp({theme:e}){return e==="dark"?s("svg",{viewBox:"0 0 24 24",width:"16",height:"16","aria-hidden":"true",children:[s("circle",{cx:"12",cy:"12",r:"4.2",fill:"none",stroke:"currentColor",strokeWidth:"1.8"}),s("path",{d:"M12 2.5v2.2M12 19.3v2.2M2.5 12h2.2M19.3 12h2.2M5.3 5.3l1.6 1.6M17.1 17.1l1.6 1.6M5.3 18.7l1.6-1.6M17.1 6.9l1.6-1.6",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round"})]}):s("svg",{viewBox:"0 0 24 24",width:"16",height:"16","aria-hidden":"true",children:s("path",{d:"M20 14.5A8.5 8.5 0 0 1 9.5 4a8.5 8.5 0 1 0 10.5 10.5Z",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinejoin:"round"})})}function Kp({rings:e,active:t,onPick:n,onFocusStep:o}){let r=X(null),[a,i]=D(t??0);U(()=>{t!=null&&i(t)},[t]);let l=e.steps.length,d=c=>{let g={ArrowDown:1,ArrowUp:-1},h=null;if(c.key in g)h=Math.max(0,Math.min(l-1,a+g[c.key]));else if(c.key==="Home")h=0;else if(c.key==="End")h=l-1;else return;c.preventDefault(),i(h),o(h),r.current?.querySelector(`[data-row="${h}"]`)?.focus()};return s("ol",{className:E.steps,ref:r,"data-steplist":"",onKeyDown:d,"aria-label":"The run's steps",children:e.steps.map(c=>{let g=e.identity.find(u=>u.step===c.i),h=e.readbacks.filter(u=>u.step===c.i),p=c.checks.passed+c.checks.failed;return s("li",{children:s("button",{type:"button","data-row":c.i,"data-status":c.status,"aria-current":t===c.i?"step":void 0,tabIndex:a===c.i?0:-1,onClick:()=>n(c.i),children:[s("span",{className:E.sNum,children:String(c.i+1).padStart(2,"0")}),s("span",{className:E.sMark,"aria-hidden":"true",children:c.status==="passed"?"✓":c.status==="stopped"?"■":"·"}),s("span",{className:E.sName,children:[c.name,c.section?s("small",{children:c.section}):null]}),s("span",{className:E.sTags,children:[g?s("span",{"data-ok":g.result==="passed"?"1":"0",children:"record"}):null,p?s("span",{"data-ok":c.checks.failed?"0":"1",children:[p," ",p===1?"check":"checks"]}):null,h.length?s("span",{"data-ok":h.some(u=>u.result==="failed")?"0":"1",children:[h.length," record ",h.length===1?"check":"checks"]}):null]}),s("span",{className:E.srOnly,children:[c.status==="passed"?", passed":c.status==="stopped"?", stopped here":", not reached",g?", checks the right record":""]})]})},c.i)})})}function Wp({frames:e,frame:t,playing:n,speed:o,busy:r,rings:a,onPlay:i,onPause:l,onSeek:d,onNext:c,onSpeed:g,onClose:h}){let p=t??0,u=e[p],f=u?a.steps[u.step]?.t0??0:0;return s("div",{className:E.player,"data-active":t!==null?"1":void 0,children:[s("button",{type:"button",className:E.pBtn,onClick:n?l:i,disabled:r,"aria-label":n?"Pause":"Play the run",children:n?"❚❚":"▶"}),s("button",{type:"button",className:E.pBtn,onClick:c,disabled:r,"aria-label":"Next highlight",title:"Next highlight (Shift + →)",children:"⏭"}),s("input",{className:E.scrub,type:"range",min:"0",max:e.length-1,value:p,disabled:r,"aria-label":"Position in the run","aria-valuetext":u?`Step ${u.step+1} of ${a.steps.length}`:void 0,onChange:v=>d(Number(v.target.value))}),s("span",{className:E.pTime,children:[Vt(f)," / ",Vt(a.runMs)]}),s("span",{className:E.speeds,role:"group","aria-label":"Speed",children:Ip.map(v=>s("button",{type:"button","aria-pressed":o===v,onClick:()=>g(v),children:[v,"×"]},v))}),t!==null?s("button",{type:"button",className:E.pBtn,onClick:h,"aria-label":"Leave the replay",children:"×"}):null]})}function Vp({step:e,rings:t,media:n,frame:o,stopReason:r,stopNote:a,mediaNote:i}){let l=t.readbacks.filter(f=>f.step===e.i),d=t.identity.find(f=>f.step===e.i),c=e.checks.passed+e.checks.failed,g=!!o,h=g?o.step===e.i?o.readbacks:0:l.length,p=g?o.spotlight:null,u=[["Action",e.name],["Result",e.status==="passed"?"✓ Passed":e.status==="stopped"?`■ Stopped here${r?`: ${r}`:""}`:"Not reached",e.status==="passed"?"ok":e.status==="stopped"?"halt":"ghost","stop"],d?["Right record",d.result==="passed"?"✓ Confirmed before acting":d.result==="not_reached"?"Not reached":"✗ Not confirmed",d.result==="passed"?"ok":"ghost","identity"]:null,c?["Screen checks",e.checks.failed?`■ ${e.checks.failed} of ${c} failed`:`✓ ${e.checks.passed} of ${c} passed`,e.checks.failed?"halt":"ok","checks"]:null,l.length?["Read-back",Op(l.filter(f=>f.result==="passed").length,l.length),l.some(f=>f.result==="failed")?"halt":l.every(f=>f.result==="passed")?"ok":"ghost","save"]:null].filter(Boolean);return s("aside",{className:E.inspector,"data-status":e.status,"data-step":e.i,"data-spot":p||void 0,"aria-live":"polite",children:[s("div",{className:E.inMain,children:[s("table",{className:E.kv,children:s("tbody",{children:u.map(([f,v,m,b])=>s("tr",{"data-tone":m,"data-spot":p&&p===b?"1":void 0,children:[s("th",{scope:"row",children:f}),s("td",{children:v})]},f))})}),p==="stop"&&a?s("p",{className:E.spotNote,children:a}):null,n&&(n.crop||n.frame)?s("div",{className:E.shots,children:[n.crop?s("figure",{children:[s("img",{src:n.crop,alt:"The step's target as recorded, synthetic data",width:"160",height:"64",loading:"lazy"}),s("figcaption",{children:"Recorded"})]}):null,n.frame?s("figure",{children:[s("img",{src:n.frame,alt:"The screen after this step in this run, synthetic data",width:"640",height:"400",loading:"lazy"}),s("figcaption",{children:"This run"})]}):null,i?s("p",{className:E.shotsNote,"data-media-note":"",children:i}):null]}):null]}),l.length?s("table",{className:E.readTable,"data-count":h,children:[s("caption",{children:"Each saved field was read back from the record after the save. The values aren't published."}),s("thead",{children:s("tr",{children:[s("th",{scope:"col",children:"Field"}),s("th",{scope:"col",children:"Expected"}),s("th",{scope:"col",children:"Read back"}),s("th",{scope:"col","aria-label":"Result"})]})}),s("tbody",{children:l.map((f,v)=>{let m=vnew Date(e*1e3).toISOString().replace("T"," ").replace(/\.\d+Z$/," UTC"),ki=e=>String(e).replace("T"," ").replace(/(\.\d+)?Z$/," UTC"),br=(e,t=16)=>`${String(e).slice(0,t)}…`,wi={anchor_mismatch:"The log entry isn't for this receipt.",anchor_key_mismatch:"The log entry isn't signed by the receipt's key.",anchor_bad_signature:"The log entry's signature doesn't match.",anchor_unknown_log:"The entry names a log this site doesn't pin.",anchor_bad_timestamp:"The log's signed timestamp doesn't verify.",anchor_bad_inclusion:"The inclusion proof doesn't reach the log's tree.",anchor_bad_checkpoint:"The log's signed checkpoint doesn't verify.",anchor_malformed:"The log entry isn't well formed.",tsa_imprint_mismatch:"The timestamp stamps a different digest from this receipt's.",tsa_bad_signature:"The timestamp's signature doesn't verify.",tsa_untrusted:"The timestamp doesn't chain to the pinned Sigstore root.",tsa_expired:"The timestamp's certificate wasn't valid at that time.",tsa_not_timestamping:"The signing certificate isn't for time stamping.",tsa_content_mismatch:"The timestamp's signed content doesn't match.",tsa_malformed:"The timestamp isn't well formed.",tsa_token_missing:"The timestamp's token file is missing.",tsa_token_mismatch:"The timestamp's token file isn't the one its record names."};function Zp({seal:e,files:t,links:n,witnesses:o,witness:r,live:a,authorization:i,authorizedLine:l}){let d=r?.rekor,c=r?.tsa,g=[["Outcome",s("code",{children:e.outcome},"o"),null],["Report SHA-256",s("code",{title:e.subject_sha256,children:br(e.subject_sha256,24)},"d"),null],["Signed by",s("code",{children:e.key_id},"k"),null],["Signature",s("code",{title:e.signature,children:br(e.signature,24)},"s"),"Ed25519"],["Issued",ki(e.issued_at),null],...e.scope_item?[["Scope",s("code",{children:e.scope_item},"sc"),null]]:[]];return o?.rekor&&g.push(["Public log",o.rekor==="pending"?"Checking…":d?.ok?s("span",{children:["Sigstore Rekor entry"," ",s("a",{href:Ks(d.logIndex),rel:"noopener noreferrer",children:d.logIndex}),", logged ",qp(d.integratedTime),", log ",s("code",{children:br(d.logId,8)}),". The inclusion proof, signed timestamp and checkpoint verify against the pinned Rekor key.",a==="match"?" This entry matches the public log.":a==="differs"?" The public log serves a different entry.":""]},"r"):s("span",{children:[wi[d?.reason]||"The log entry doesn't verify."," ",s("code",{children:d?.reason})]},"rf"),o.rekor]),o?.tsa&&g.push(["Timestamp",o.tsa==="pending"?"Checking…":c?.ok?s("span",{children:["Sigstore Timestamp Authority (RFC 3161): ",ki(c.genTime),", over this receipt's SHA-256, chained to the pinned"," ",s("a",{href:"https://timestamp.sigstore.dev/api/v1/timestamp/certchain",rel:"noopener noreferrer",children:"Sigstore TSA root"}),"."]},"t"):s("span",{children:[wi[c?.reason]||"The timestamp doesn't verify."," ",s("code",{children:c?.reason})]},"tf"),o.tsa]),i&&l&&g.push(["Authorized",s("span",{children:[l,", with an SSH key"," ",s("a",{href:`https://github.com/${i.login}.keys`,rel:"noopener noreferrer",children:["GitHub lists for @",i.login]}),"."]},"a"),"pass"]),s("section",{className:E.record,"aria-labelledby":"record-h",children:[s("h2",{id:"record-h",className:E.recordH,children:"The signed record"}),s("table",{className:E.recordTable,children:s("tbody",{children:g.map(([h,p,u])=>s("tr",{"data-state":u||void 0,children:[s("th",{scope:"row",children:[u==="pass"||u==="fail"||u==="pending"?s("span",{className:E.wMark,"aria-hidden":"true"}):null,h]}),s("td",{children:p})]},h))})}),n.file?s("p",{className:E.fileLinks,children:[["report.json","seal.json",t.anchor?"seal.anchor.json":null,t.tsa?"seal.tsa.json":null,t.tsr?"seal.tsr":null].filter(Boolean).map(h=>[h,no(n.file(h))]).filter(([,h])=>h).map(([h,p])=>s("a",{href:p,children:h},h)),n.keys&&no(n.keys.href)?s("a",{href:no(n.keys.href),children:n.keys.label}):null]}):null]})}var Ti={title:"Title",fname:"First name",lname:"Last name",DOB:"Date of birth",sex:"Sex",street:"Street",city:"City",state_label:"State",postal_code:"Postal code",phone_home:"Home phone",email:"Email",country_code:"Country"};function yr(e){if(Ti[e])return Ti[e];let t=String(e).replace(/[_-]+/g," ").trim();return t.charAt(0).toUpperCase()+t.slice(1)}function $i(e){let t=e.match(/^type <(\w+)>$/);if(t)return`Type ${yr(t[1])}`;if(e==="press Control+a")return"Select the field’s text";if(e==="press Enter")return"Press Enter";if(e.startsWith("scroll"))return"Scroll down";if(e==="click recorded visual target")return"Click the next field";let n=e.match(/^click '(.+)'$/);return n?/nassigned/.test(n[1])?"Open the list":`Click ${n[1].replace("FirstName","First name")}`:e.charAt(0).toUpperCase()+e.slice(1)}var Yp={title:"Title",fname:"First name",lname:"Last name",DOB:"Date of birth",sex:"Sex",street:"Street",city:"City",state:"State",state_label:"State",postal_code:"Postal code",phone_home:"Home phone",email:"Email",country_code:"Country"},Mt=e=>String(e).replace(/^.*::/,"");function Jp(e){let t=/field '(\w+)' equals/.exec(e||"");return t?`${Yp[t[1]]||yr(t[1])} matches`:/record_written/.test(e||"")?"The new record exists":null}function Ai(e,t){if(!e||typeof e!="object")throw new Error("no report");if(e.bundle_content_digest!==t.digest)throw new Error("the report is from a different program");let n=Array.isArray(e.results)?e.results:[];if(n.length>t.steps.length)throw new Error("the report has more steps than the program");n.forEach((w,N)=>{if(Mt(w.step_id)!==Mt(t.steps[N].id))throw new Error(`step ${N+1}: the report and the program differ`)});let o=0,r=n.map(w=>{let N=Math.max(0,Number(w.elapsed_ms)||0),M={t0:o,t1:o+N};return o+=N,M}),a=o,i=e.outcome_envelope?.postcondition_evidence||[],l=new Map;for(let w of i){let N=l.get(w.result_index)||[];N.push(w),l.set(w.result_index,N)}let d=t.steps.map((w,N)=>{let M=n[N],S=M?M.ok?"passed":"stopped":"not_reached",A=l.get(N)||[];return{i:N,id:Mt(w.id),name:w.name,section:w.section,status:S,t0:M?r[N].t0:null,t1:M?r[N].t1:null,checks:{passed:A.filter(O=>O.verdict==="passed").length,failed:A.filter(O=>O.verdict!=="passed").length},identity:M?M.identity?.status==="verified"?"passed":M.identity?"failed":null:null}}),c=i.map(w=>{let N=d[w.result_index];if(!N||N.status==="not_reached")throw new Error("a screen check on a step the run never reached");return{step:w.result_index,result:w.verdict==="passed"?"passed":"failed",t:N.t1}}),g=Array.isArray(e.governed_qualified_effect_requirements)?e.governed_qualified_effect_requirements:[],h=g.length?g.map(w=>({step:d.findIndex(N=>N.id===Mt(w.step_id??"")),at:Number.isInteger(w.effect_index)?w.effect_index:-1})):n.flatMap((w,N)=>(Array.isArray(w.effect_evidence)?w.effect_evidence:[]).map((M,S)=>({step:N,at:S}))),p=h.map((w,N)=>{let M=n[w.step],S=Array.isArray(M?.effect_evidence)?M.effect_evidence:[],A=Array.isArray(M?.effect_results)?M.effect_results:[],O=S[w.at],I=M?r[w.step]:null,$=h.filter(R=>R.step===w.step),C=$.indexOf(w);return{i:N,step:w.step,result:O?O.final_verdict==="confirmed"?"passed":"failed":"not_reached",label:w.at>=0&&Jp(A[w.at])||null,t:O&&I?I.t0+(I.t1-I.t0)*(.55+.45*C/$.length):null}}),f=(Array.isArray(e.required_identity_step_ids)?e.required_identity_step_ids.map(Mt):[]).map(w=>{let N=d.find(M=>M.id===w);if(!N)throw new Error(`a right-record check on an unknown step ${w}`);return{step:N.i,result:N.identity??"not_reached",t:N.t0==null?null:N.t0+(N.t1-N.t0)*.3}}),v=d.find(w=>w.status==="stopped")||null,m=(w,N)=>w.filter(M=>M.result===N).length,b=p.find(w=>w.result==="passed"),y=[...d].reverse().find(w=>w.status!=="not_reached"),_=v?{step:v.i,kind:"stop"}:b?{step:b.step,kind:"save"}:y?{step:y.i,kind:"end"}:null;return{outcome:e.execution_outcome,transaction:e.transaction_outcome??null,runMs:a,totalMs:typeof e.total_ms=="number"?e.total_ms:a,startedAt:e.started_at??null,stoppedAt:v?v.i:null,anchor:_,steps:d,checks:c,readbacks:p,identity:f,counts:{steps:d.length,stepsPassed:d.filter(w=>w.status==="passed").length,checks:c.length,checksPassed:m(c,"passed"),checksFailed:m(c,"failed"),readbacks:p.length,readbacksPassed:m(p,"passed"),readbacksFailed:m(p,"failed"),identity:f.length,identityPassed:m(f,"passed"),modelCalls:e.model_calls??null}}}function Mi(e,{folds:t=null,report:n=null,titles:o=null,digest:r=null}={}){let a=(e?.nodes||[]).filter(d=>d.kind==="action"),i=new Map((Array.isArray(n?.results)?n.results:[]).map(d=>[Mt(d.step_id),d.intent])),l=new Map;for(let d of t?.groups||[])for(let c of d.nodes)l.set(c,d.title);return{digest:r||e?.bundle?.provenance?.content_digest||t?.source?.body_content_digest||null,steps:a.map(d=>{let c=i.get(Mt(d.id));return{id:d.id,name:o?.[d.id]||(c?$i(c):d.title),section:l.get(d.id)||null}})}}function Xp(e,t,{readBack:n=!1}={}){return e==="VERIFIED"&&n?{tone:"ok",label:"Saved and checked",line:"The entry reached the record, and reading the record back found it there."}:e==="VERIFIED"?{tone:"ok",label:"Completed",line:"Every step's checks passed. This run didn't read the saved record back."}:t==="SAVED_AWAITING_CHECK"?{tone:"halt",label:"Awaiting counterparty confirmation",line:"The entry was sent. The other party has not confirmed it yet; a signed update records the answer."}:t==="HALTED_BEFORE_EFFECT"?{tone:"halt",label:"Stopped before saving",line:"The run stopped before it changed anything, so a person decides what happens next."}:t==="RECONCILIATION_REQUIRED"?{tone:"halt",label:"Stopped for a person to check",line:"The run stopped after a save it couldn't confirm, so a person checks the record before anything else runs."}:{tone:"halt",label:"Stopped",line:"The run stopped, so a person decides what happens next."}}var Qp=[[/duplicate|already exists|1 of 1|existing (?:chart|record|patient)|No matches were found/i,"possible duplicate patient"],[/0 records match|never reached the record|missing \/ phantom/i,"the save never reached the record"],[/identity|wrong (?:record|patient)/i,"couldn't confirm the right record"]],eu={"possible duplicate patient":"The screen check before saving expected the app to find no matching patient. It found one, so the run stopped before it changed anything.","the save never reached the record":"The app showed its saved message, but reading the record back found nothing there, so the run stopped instead of reporting success.","couldn't confirm the right record":"The run couldn't confirm it was on the right record, so it stopped before acting."};function tu(e){let t=[e?.halt?.reason,e?.halt?.intent].filter(Boolean).join(" "),n=Qp.find(([o])=>o.test(t));return n?n[1]:null}function Ri(e,t,n){let o=Xp(t?.outcome,e?.transaction_outcome,{readBack:!!n?.counts?.readbacksPassed}),r=t?.outcome==="VERIFIED"?null:tu(e);return{...o,headline:r?`${o.label}: ${r}`:o.label,reason:r,note:r&&eu[r]||null}}var nu=e=>new TextDecoder().decode(e),Ii=async e=>Re(new TextEncoder().encode(e)),ou=async e=>Ii(e.subject_sha256+await Ii(je(e)));async function Ci({files:e,keys:t,program:n,about:o={},authorization:r=null}){let a=JSON.parse(e.sealText),i=JSON.parse(nu(e.report)),l=Mi(n.spec,{folds:n.folds||null,titles:n.titles||null,digest:n.digest||null,report:i}),d=Ai(i,l),c=Ri(i,a,d);return{files:e,page:{id:o.id||a.run_id,tone:c.tone,label:c.label,headline:c.headline,line:c.line,job:o.job||i.workflow_name||"Run",app:o.app||"Test copy",startedAt:i.started_at??null,stopReason:c.reason,stopNote:c.note,rings:d,irisSeed:await ou(a),media:d.steps.map(()=>({crop:null,frame:null})),seal:a,keys:t,files:{report:"report.json",seal:"seal.json",anchor:e.anchorText!=null?"seal.anchor.json":null,tsa:e.tsaText!=null?"seal.tsa.json":null,tsr:e.tsrBytes!=null?"seal.tsr":null},anchor:null,authorization:r,authTiming:null,authorizedLine:null,tamper:Os(a.outcome,i.execution_outcome),program:{spec:n.spec,folds:n.folds||null,titles:Object.fromEntries(l.steps.map(g=>[g.id,g.name]))},runs:[]}}}var Pi=e=>Uint8Array.from(atob(e),t=>t.charCodeAt(0));function Oi({text:e}){return s("main",{style:{font:"16px/1.5 var(--oa-font-body)",color:"var(--oa-text)",padding:"48px 24px",maxWidth:640,margin:"0 auto"},children:[s("h1",{style:{fontSize:22},children:"This receipt can't be shown"}),s("p",{children:e}),s("p",{children:["Check it from a terminal instead: ",s("code",{children:"openadapt verify RUN_FOLDER"})]})]})}async function ru(){let e=(0,zi.createRoot)(document.getElementById("root")),t=document.getElementById("seal-data"),n;try{n=JSON.parse(t?.textContent||"null")}catch{n=null}if(!n||!n.report_b64||!n.seal_text){e.render(s(Oi,{text:"The page has no run in it. Write one with: openadapt receipt view RUN_FOLDER"}));return}let o={report:Pi(n.report_b64),sealText:n.seal_text,anchorText:n.anchor_text??null,tsaText:n.tsa_text??null,tsrBytes:n.tsr_b64?Pi(n.tsr_b64):null,auth:n.auth??null,receiptText:n.receipt_text??null,receiptKeys:n.receipt_keys??null},r;try{r=await Ci({files:o,keys:n.keys,program:n.program,about:n.about||{},authorization:n.authorization??null})}catch(l){e.render(s(Oi,{text:`The run's files don't fit together: ${l.message}.`}));return}let a={...r.page,commands:n.commands??null,commandsLabel:n.commands_label??null};document.title=Ei(a).title;let i=n.host||{};e.render(s(vr,{seal:a,host:{loadFiles:async()=>({...o,report:o.report.slice()}),live:!1,kicker:n.about?.kicker??null,trustWords:i.trustWords,unchanged:i.unchanged,footer:i.footer,links:{home:null,map:null,file:l=>i.files?.includes(l)?l:null,keys:null,docs:"https://docs.openadapt.ai/reference/receipts-and-seals/"}}}))}ru();})(); diff --git a/packages/flow/benchmark/handoff_receiver/README.md b/packages/flow/benchmark/handoff_receiver/README.md new file mode 100644 index 0000000000..e89c71bd89 --- /dev/null +++ b/packages/flow/benchmark/handoff_receiver/README.md @@ -0,0 +1,66 @@ +# Referral intake: a real, synthetic OpenEMR as the receiving clinic + +These are the real-app cases for counterparty confirmations by read-back +(see [COUNTERPARTY_CONFIRMATIONS.md](../../docs/COUNTERPARTY_CONFIRMATIONS.md)). A synthetic referring clinic +sends referrals to a **second, separate OpenEMR 7.0.3** that plays the +receiving clinic. OpenAdapt reads the receiver back and says whether each +referral was recorded as intended, recorded differently, or never arrived. + +- **Sender:** `referral_cases.Sender`, a SQLite outbox of generated synthetic + patients. +- **Delivery:** the receiving clinic's intake, written through OpenEMR's + standard REST API (`/apis/default/api/patient`), with the sender's + referral id as the patient's external id. It makes mistakes on purpose. +- **Read-back:** OpenEMR's FHIR R4 `Patient` search, with a separate + read-only token, by the profile in + [`tests/fixtures/handoffs/fhir-patient-intake.yaml`](../../tests/fixtures/handoffs/fhir-patient-intake.yaml). + It never reads the delivery call's answer. + +## Bring-up (lab, WSL Docker) + +```bash +docker compose -f docker-compose.yml up -d # project ho-openemr, loopback 9780/9781 +# wait for "Starting apache!" in the logs (about 8 minutes on first boot), then: +OPENEMR_COMPOSE_FILE=$PWD/docker-compose.yml OPENEMR_BASE_HTTPS=https://127.0.0.1:9781 \ +OPENEMR_SCOPES="openid api:oemr api:fhir user/patient.read user/patient.write user/Patient.read user/Patient.write" \ + ../openemr_live/setup.sh > write.env +OPENEMR_COMPOSE_FILE=$PWD/docker-compose.yml OPENEMR_BASE_HTTPS=https://127.0.0.1:9781 \ +OPENEMR_SCOPES="openid api:fhir user/Patient.read" \ + ../openemr_live/setup.sh > read.env +``` + +Export these from the two tokens: + +- `HANDOFF_RECEIVER_API_BASE=https://127.0.0.1:9781/apis/default/api` +- `HANDOFF_RECEIVER_WRITE_TOKEN` (from `write.env`) +- `HANDOFF_RECEIVER_FHIR_BASE=https://127.0.0.1:9781/apis/default/fhir` +- `HANDOFF_RECEIVER_READ_TOKEN` (from `read.env`; a POST with it gets 401) +- `HANDOFF_RECEIVER_VERIFY_TLS=0` (self-signed certificate) + +Then run: + +```bash +pytest tests/test_handoffs_live_openemr.py # or: +python -m benchmark.handoff_receiver.referral_cases --repeat 5 --out results.json +``` + +Tear down with `docker compose -f docker-compose.yml down -v`. + +## Cases + +Each case is repeated with a fresh synthetic patient. The table is in +`referral_cases.py`, and results are in [`results/`](results/). + +| Case | What the intake does | Expected | +|---|---|---| +| intended | records it as sent | `recorded_as_intended` | +| benign_format | names in capitals with extra spaces | `recorded_as_intended` (no false alarm) | +| wrong_date | birth date one day later | `recorded_differently` [birth_date] | +| swapped_date | day and month swapped | `recorded_differently` [birth_date] | +| wrong_patient_field | another family name | `recorded_differently` [family_name] | +| wrong_sex | the other sex | `recorded_differently` [sex] | +| never_arrived | drops it | `sent`, `not_found` (follow-up due) | +| duplicate | records it twice | `sent`, `ambiguous_key` | +| unreachable | records it; the read goes to a closed port | `sent`, `receiver_unreachable` | + +Synthetic data only. diff --git a/packages/flow/benchmark/handoff_receiver/docker-compose.yml b/packages/flow/benchmark/handoff_receiver/docker-compose.yml new file mode 100644 index 0000000000..1666d69d82 --- /dev/null +++ b/packages/flow/benchmark/handoff_receiver/docker-compose.yml @@ -0,0 +1,60 @@ +# The receiving clinic for the referral-intake handoff tests: a second, +# separate, synthetic OpenEMR 7.0.3 with its own database. Nothing here is +# shared with any other OpenEMR stack. Ports are loopback only. +# +# docker compose -f docker-compose.yml up -d --wait +# OPENEMR_COMPOSE_FILE=$PWD/docker-compose.yml \ +# OPENEMR_BASE_HTTPS=https://127.0.0.1:9781 \ +# eval "$(../openemr_live/setup.sh)" +# +# See README.md. + +name: ho-openemr + +services: + mysql: + image: mariadb:11.4 + command: + - mariadbd + - --character-set-server=utf8mb4 + - --collation-server=utf8mb4_general_ci + - --innodb-buffer-pool-size=96M + - --performance-schema=OFF + environment: + MYSQL_ROOT_PASSWORD: root + healthcheck: + test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"] + interval: 10s + timeout: 5s + retries: 30 + volumes: + - receiver_db:/var/lib/mysql + + openemr: + image: openemr/openemr:7.0.3 + ports: + - "127.0.0.1:9780:80" + - "127.0.0.1:9781:443" + environment: + MYSQL_HOST: mysql + MYSQL_ROOT_PASS: root + MYSQL_USER: openemr + MYSQL_PASS: openemr + OE_USER: admin + OE_PASS: pass + depends_on: + mysql: + condition: service_healthy + healthcheck: + test: ["CMD", "test", "-f", "/var/www/localhost/htdocs/openemr/sites/default/sqlconf.php"] + interval: 15s + timeout: 5s + retries: 80 + volumes: + - receiver_sites:/var/www/localhost/htdocs/openemr/sites + - receiver_logs:/var/log + +volumes: + receiver_db: + receiver_sites: + receiver_logs: diff --git a/packages/flow/benchmark/handoff_receiver/referral_cases.py b/packages/flow/benchmark/handoff_receiver/referral_cases.py new file mode 100644 index 0000000000..1e4863caf0 --- /dev/null +++ b/packages/flow/benchmark/handoff_receiver/referral_cases.py @@ -0,0 +1,278 @@ +"""Referral intake cases against a real, synthetic OpenEMR receiver. + +The sender is a synthetic referring clinic: a SQLite outbox that creates +referrals with generated, synthetic patients. Each referral goes to the +receiver (a second, separate OpenEMR in Docker, see README.md) through a +delivery channel that plays the receiving clinic's intake. The channel +writes through OpenEMR's standard REST API (``/apis/default/api/patient``) +and can, on purpose, get something wrong. + +OpenAdapt reads the receiver back through its FHIR API, with a separate +read-only token, by the profile in +``tests/fixtures/handoffs/fhir-patient-intake.yaml``. It never reads the +delivery call's own answer. + +Cases (each repeated ``repeat`` times with a fresh patient): + +| Case | Delivery | Expected | +|---|---|---| +| ``intended`` | as sent | ``recorded_as_intended`` | +| ``benign_format`` | names in capitals with extra spaces | ``recorded_as_intended`` (no false alarm) | +| ``wrong_date`` | birth date one day later | ``recorded_differently`` [birth_date] | +| ``swapped_date`` | day and month swapped | ``recorded_differently`` [birth_date] | +| ``wrong_patient_field`` | another family name | ``recorded_differently`` [family_name] | +| ``wrong_sex`` | the other sex | ``recorded_differently`` [sex] | +| ``never_arrived`` | dropped | ``sent``, reason ``not_found``, follow-up due | +| ``duplicate`` | delivered twice | ``sent``, reason ``ambiguous_key`` | +| ``unreachable`` | as sent; read at a closed port | ``sent``, reason ``receiver_unreachable`` | + +Synthetic data only. Run inside the lab (``remote-run.sh``), with the +``HANDOFF_RECEIVER_*`` variables from the receiver's setup. +""" + +from __future__ import annotations + +import json +import os +import random +import secrets +import sqlite3 +import time +from dataclasses import dataclass +from datetime import date, timedelta +from pathlib import Path +from typing import Any, Optional + +from openadapt_flow.handoffs import intake +from openadapt_flow.handoffs.ledger import Handoff, HandoffLedger +from openadapt_flow.handoffs.line import to_line +from openadapt_flow.handoffs.readers import FhirSearchProfile, FhirSearchReader + +PROFILE = ( + Path(__file__).resolve().parents[2] + / "tests" + / "fixtures" + / "handoffs" + / "fhir-patient-intake.yaml" +) +GIVEN = ["Avery", "Rowan", "Sage", "Quinn", "Emery", "Harper", "Reese", "Tatum"] +FAMILY = ["Quill", "Marlow", "Thorne", "Vance", "Ashby", "Corwin", "Hollis", "Pryor"] + +EXPECTED: dict[str, tuple[str, Optional[str], list[str]]] = { + "intended": ("recorded_as_intended", None, []), + "benign_format": ("recorded_as_intended", None, []), + "wrong_date": ("recorded_differently", None, ["birth_date"]), + "swapped_date": ("recorded_differently", None, ["birth_date"]), + "wrong_patient_field": ("recorded_differently", None, ["family_name"]), + "wrong_sex": ("recorded_differently", None, ["sex"]), + "never_arrived": ("sent", "not_found", []), + "duplicate": ("sent", "ambiguous_key", []), + "unreachable": ("sent", "receiver_unreachable", []), +} + + +class Sender: + """The synthetic referring clinic: an outbox of referrals.""" + + def __init__(self, path: Path, seed: int) -> None: + self.db = sqlite3.connect(path) + self.db.execute( + "create table if not exists referral (id text primary key, given text," + " family text, birth_date text, sex text, reason text)" + ) + self.rng = random.Random(seed) + + def create(self, *, unswappable: bool = False) -> dict[str, str]: + day = self.rng.randint(13, 28) if unswappable else self.rng.randint(1, 12) + month = self.rng.randint(1, 12) + if not unswappable: + while month == day: + month = self.rng.randint(1, 12) + row = { + "id": f"REF-{secrets.token_hex(6).upper()}", + "given": self.rng.choice(GIVEN), + "family": self.rng.choice(FAMILY) + secrets.token_hex(2), + "birth_date": date(self.rng.randint(1940, 2015), month, day).isoformat(), + "sex": self.rng.choice(["female", "male"]), + "reason": "synthetic referral", + } + self.db.execute( + "insert into referral values (:id, :given, :family, :birth_date, :sex," + " :reason)", + row, + ) + self.db.commit() + return row + + +def _post_patient(base: str, token: str, row: dict[str, str]) -> None: + import httpx + + body = { + "fname": row["given"], + "lname": row["family"], + "DOB": row["birth_date"], + "sex": row["sex"].capitalize() + if row["sex"] in ("female", "male") + else row["sex"], + "pubpid": row["id"], + "street": "", + "postal_code": "", + "city": "", + "state": "", + "country_code": "", + "phone_contact": "", + "race": "", + "ethnicity": "", + } + with httpx.Client(verify=_verify(), timeout=30) as client: + response = client.post( + f"{base}/patient", json=body, headers={"Authorization": f"Bearer {token}"} + ) + if response.status_code >= 300 or response.json().get("validationErrors"): + raise RuntimeError(f"delivery failed: HTTP {response.status_code}") + + +def _verify() -> bool: + return os.environ.get("HANDOFF_RECEIVER_VERIFY_TLS", "1") != "0" + + +def deliver(case: str, row: dict[str, str], base: str, token: str) -> None: + """The receiving clinic's intake, getting it wrong on purpose.""" + + sent = dict(row) + born = date.fromisoformat(row["birth_date"]) + if case == "never_arrived": + return + if case == "benign_format": + sent["given"] = f" {row['given'].upper()} " + sent["family"] = row["family"].upper() + elif case == "wrong_date": + sent["birth_date"] = (born + timedelta(days=1)).isoformat() + elif case == "swapped_date": + sent["birth_date"] = date(born.year, born.day, born.month).isoformat() + elif case == "wrong_patient_field": + sent["family"] = row["family"] + "s" + elif case == "wrong_sex": + sent["sex"] = "male" if row["sex"] == "female" else "female" + _post_patient(base, token, sent) + if case == "duplicate": + _post_patient(base, token, sent) + + +@dataclass +class CaseResult: + case: str + referral: str + state: str + reason: Optional[str] + differing: list[str] + line: dict[str, Any] + ok: bool + seconds: float + + +def run_cases( + work: Path, + *, + repeat: int = 5, + seed: int = 20261121, + cases: Optional[list[str]] = None, +) -> list[CaseResult]: + api = os.environ["HANDOFF_RECEIVER_API_BASE"] + write_token = os.environ["HANDOFF_RECEIVER_WRITE_TOKEN"] + fhir = os.environ["HANDOFF_RECEIVER_FHIR_BASE"] + read_token = os.environ["HANDOFF_RECEIVER_READ_TOKEN"] + profile = FhirSearchProfile.load(PROFILE) + reader = FhirSearchReader(profile, fhir, token=read_token, verify_tls=_verify()) + closed = FhirSearchReader( + profile, + "https://127.0.0.1:9789/apis/default/fhir", + token=read_token, + verify_tls=False, + timeout=5, + ) + sender = Sender(work / "sender.sqlite", seed) + ledger = HandoffLedger(work / "handoffs") + results: list[CaseResult] = [] + for name in cases or list(EXPECTED): + for _ in range(repeat): + row = sender.create(unswappable=False) + started = time.monotonic() + handoff: Handoff = ledger.send( + row["id"], + { + "given_name": (row["given"], "text"), + "family_name": (row["family"], "text"), + "birth_date": (row["birth_date"], "date"), + "sex": (row["sex"], "code"), + }, + counterparty=profile.counterparty, + system_kind=profile.system_kind, + follow_up="referrals desk", + follow_up_hours=24, + step=0, + ) + deliver(name, row, api, write_token) + used = closed if name == "unreachable" else reader + after = intake.check(ledger, handoff.id, row["id"], used) + last = after.last + assert last is not None + want_state, want_reason, want_fields = EXPECTED[name] + got = (after.state, last.reason, list(last.differing_fields)) + results.append( + CaseResult( + case=name, + referral=row["id"], + state=after.state, + reason=last.reason, + differing=list(last.differing_fields), + line=to_line(after).line, + ok=got == (want_state, want_reason, want_fields), + seconds=round(time.monotonic() - started, 3), + ) + ) + return results + + +def summarize(results: list[CaseResult]) -> dict[str, Any]: + by_case: dict[str, dict[str, Any]] = {} + for item in results: + entry = by_case.setdefault( + item.case, + { + "expected": list(EXPECTED[item.case]), + "runs": 0, + "as_expected": 0, + "got": {}, + }, + ) + entry["runs"] += 1 + entry["as_expected"] += item.ok + label = f"{item.state}|{item.reason}|{','.join(item.differing)}" + entry["got"][label] = entry["got"].get(label, 0) + 1 + return { + "receiver": "OpenEMR 7.0.3 (docker, synthetic, second instance)", + "read": "FHIR R4 Patient search, read-only token", + "delivery": "OpenEMR standard REST API (write token)", + "cases": by_case, + "total_runs": len(results), + "as_expected": sum(r.ok for r in results), + } + + +if __name__ == "__main__": # pragma: no cover - lab entry point + import argparse + import tempfile + + parser = argparse.ArgumentParser(allow_abbrev=False) + parser.add_argument("--repeat", type=int, default=5) + parser.add_argument("--out", default=None) + args = parser.parse_args() + with tempfile.TemporaryDirectory() as tmp: + found = run_cases(Path(tmp), repeat=args.repeat) + summary = summarize(found) + text = json.dumps(summary, indent=2) + if args.out: + Path(args.out).write_text(text + "\n") + print(text) diff --git a/packages/flow/benchmark/handoff_receiver/results/2026-11-21.json b/packages/flow/benchmark/handoff_receiver/results/2026-11-21.json new file mode 100644 index 0000000000..02be3ba4e1 --- /dev/null +++ b/packages/flow/benchmark/handoff_receiver/results/2026-11-21.json @@ -0,0 +1,134 @@ +{ + "receiver": "OpenEMR 7.0.3 (docker, synthetic, second instance)", + "read": "FHIR R4 Patient search, read-only token", + "delivery": "OpenEMR standard REST API (write token)", + "cases": { + "intended": { + "expected": [ + "recorded_as_intended", + null, + [] + ], + "runs": 20, + "as_expected": 20, + "got": { + "recorded_as_intended|None|": 20 + } + }, + "benign_format": { + "expected": [ + "recorded_as_intended", + null, + [] + ], + "runs": 20, + "as_expected": 20, + "got": { + "recorded_as_intended|None|": 20 + } + }, + "wrong_date": { + "expected": [ + "recorded_differently", + null, + [ + "birth_date" + ] + ], + "runs": 20, + "as_expected": 20, + "got": { + "recorded_differently|None|birth_date": 20 + } + }, + "swapped_date": { + "expected": [ + "recorded_differently", + null, + [ + "birth_date" + ] + ], + "runs": 20, + "as_expected": 20, + "got": { + "recorded_differently|None|birth_date": 20 + } + }, + "wrong_patient_field": { + "expected": [ + "recorded_differently", + null, + [ + "family_name" + ] + ], + "runs": 20, + "as_expected": 20, + "got": { + "recorded_differently|None|family_name": 20 + } + }, + "wrong_sex": { + "expected": [ + "recorded_differently", + null, + [ + "sex" + ] + ], + "runs": 20, + "as_expected": 20, + "got": { + "recorded_differently|None|sex": 20 + } + }, + "never_arrived": { + "expected": [ + "sent", + "not_found", + [] + ], + "runs": 20, + "as_expected": 20, + "got": { + "sent|not_found|": 20 + } + }, + "duplicate": { + "expected": [ + "sent", + "ambiguous_key", + [] + ], + "runs": 20, + "as_expected": 20, + "got": { + "sent|ambiguous_key|": 20 + } + }, + "unreachable": { + "expected": [ + "sent", + "receiver_unreachable", + [] + ], + "runs": 20, + "as_expected": 20, + "got": { + "sent|receiver_unreachable|": 20 + } + } + }, + "total_runs": 180, + "as_expected": 180, + "date": "2026-11-21", + "repeat_per_case": 20, + "host": "zenbook lab, WSL Docker, project ho-openemr", + "pytest": "53 passed (test_handoffs.py, test_handoffs_live_openemr.py, test_deferred_report.py) via remote-run.sh slot gate", + "code_head": "80fae9911fbd439733a5ecbbf81fcfb4b8f2326f", + "earlier_runs": [ + "13c6e3f68: 180 of 180 at 20 per case", + "13c6e3f68: 45 of 45 at 5 per case" + ] +} diff --git a/packages/flow/benchmark/openemr_live/setup.sh b/packages/flow/benchmark/openemr_live/setup.sh index cc787fcb72..99b5452874 100755 --- a/packages/flow/benchmark/openemr_live/setup.sh +++ b/packages/flow/benchmark/openemr_live/setup.sh @@ -24,9 +24,11 @@ set -euo pipefail # --- config ----------------------------------------------------------------- -COMPOSE_FILE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/docker-compose.yml" +# OPENEMR_COMPOSE_FILE and OPENEMR_BASE_HTTPS point this script at another +# stack (benchmark/handoff_receiver uses them). +COMPOSE_FILE="${OPENEMR_COMPOSE_FILE:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/docker-compose.yml}" DC=(docker compose -f "$COMPOSE_FILE") -BASE_HTTPS="https://localhost:9390" +BASE_HTTPS="${OPENEMR_BASE_HTTPS:-https://localhost:9390}" FHIR_BASE="${BASE_HTTPS}/apis/default/fhir" OE_USER="admin" OE_PASS="pass" @@ -36,7 +38,7 @@ OE_PASS="pass" # - OpenEMR's FHIR API exposes Observation/Encounter READ only (there is no # `user/Observation.write`), so the live write path is a FHIR Patient # POST, independently read back through FHIR. -SCOPES="openid offline_access api:fhir user/Patient.read user/Patient.write user/Observation.read user/Encounter.read" +SCOPES="${OPENEMR_SCOPES:-openid offline_access api:fhir user/Patient.read user/Patient.write user/Observation.read user/Encounter.read}" log() { echo "[setup] $*" >&2; } # MariaDB 11.x ships the `mariadb` client (not `mysql`). diff --git a/packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md b/packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md new file mode 100644 index 0000000000..4436be0fa9 --- /dev/null +++ b/packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md @@ -0,0 +1,205 @@ +# Handoffs: did the other party record what we sent? + +A handoff is one item a run sends to another party's system, such as a claim +to a payer or a referral to a receiving clinic. A read-back of your own +system can't tell you whether the other side recorded it. A **counterparty +confirmation** can: it is evidence read from the other party's system about +what that system recorded. + +Each handoff is in one of four states: + +| State | Meaning | +|---|---| +| `sent` | We sent it. The other side hasn't confirmed anything yet, or it refused the item. | +| `acknowledged` | The other side says it has the item, but not what it recorded (an X12 999, a 277CA `A1` or `A2`). | +| `recorded_as_intended` | A read-back of the other system found the item, and every compared field matches what we sent. | +| `recorded_differently` | A read-back found the item, but some fields differ. The ledger names the field ids, never the values. | + +Only a read-back that compares fields can say `recorded_*`. An +acknowledgment message says what the other side received or accepted, never +what it stored in each field. + +## See who still needs to follow up + +```bash +openadapt handoff list --ledger /var/lib/openadapt/deferred +openadapt handoff list --config deployment.yaml --all +openadapt handoff list --ledger DIR --run runs/claim-0412 --json +``` + +```text +Needs follow-up (2) + receiving clinic: recorded differently: birth_date + sent 2026-11-21 06:00, follow up by 2026-11-22 06:00; who: referrals desk + payer x12-277ca: sent, no answer yet; they refused it + sent 2026-10-18 06:00, follow up by 2026-10-20 06:00; who: billing +Waiting (1) + payer x12-277ca: acknowledged + sent 2026-10-18 06:00, follow up by 2026-10-20 06:00 + +Done: 1 (--all lists them) +``` + +A handoff needs follow-up when it was recorded differently, refused, matched +more than one record, or is past its follow-up time and still isn't +confirmed. It is done when it was recorded as intended, or a status-only +report accepted it. `openadapt-flow handoff list` is the same command. It +reads ledgers only, and never contacts the other party. + +## Producer 1: payer acknowledgments + +A claim saved with a deferred check (`effects.kind: deferred_report`, see +[EFFECT_KIT.md](EFFECT_KIT.md#checked-later-deferred_report)) is a handoff to +the payer. Its handoff record lives in `/handoffs`. `deferred settle` +records what each report says, including rows that settle nothing yet: + +| The report says | Handoff | +|---|---| +| nothing yet | `sent`, follow-up due at the check's deadline | +| received (999 `A` or `E`, 277CA `A1`, any other pending status) | `acknowledged` | +| accepted (277CA `A2`) | `acknowledged`, accepted: done | +| rejected (999 `R`, `M`, `W`, `X`; 277CA `A3`, `A4`, `A6`, `A7`, `A8`) | `sent`, reason `rejected_by_counterparty` | +| two rows that disagree | `acknowledged`, reason `conflicting_report` | +| two waiting claims on one key | unchanged, reason `ambiguous_key` | +| nothing by the deadline | unchanged, reason `no_answer_by_deadline` | + +The deferred check settles the run exactly as before; the handoff only +listens. Only X12 reports count as the payer's own answer. A CSV export or a +saved status page may be your own system's report, so those checks are not +handoffs. + +## Producer 2: a read-back of the other system + +The sender records the handoff when it sends the item, together with the +field values it sent: + +```python +from openadapt_flow.handoffs import HandoffLedger, intake +from openadapt_flow.handoffs.readers import FhirSearchProfile, FhirSearchReader + +ledger = HandoffLedger("/var/lib/openadapt/handoffs") +h = ledger.send( + referral_id, + {"family_name": (family, "text"), "birth_date": (dob, "date"), "sex": (sex, "code")}, + counterparty="receiving clinic", system_kind="ehr", + follow_up="referrals desk", follow_up_hours=24, +) +# later +profile = FhirSearchProfile.load("fhir-patient-intake.yaml") +reader = FhirSearchReader(profile, fhir_base, token_env="RECEIVER_FHIR_TOKEN") +intake.check(ledger, h.id, referral_id, reader) +``` + +The reader finds the item by its key, which is the sender's reference that +the receiver keeps. Then it reports one of these: + +| Read | Handoff | +|---|---| +| one record, every field matches | `recorded_as_intended` | +| one record, some fields differ | `recorded_differently`, with those field ids | +| no record | unchanged (`sent`), reason `not_found`; it follows up when due | +| more than one record | unchanged, reason `ambiguous_key` | +| the read failed (network, 4xx, 5xx, bad body) | unchanged, reason `receiver_unreachable`; it never undoes an earlier confirmation | + +Fields compare by kind after normalizing, the same way as on-screen +read-backs (`readback_values`). `text` ignores case and runs of whitespace. +`code` ignores separators. `date` compares the calendar date. A field the +other side doesn't hold, or holds in a form that doesn't parse, differs. + +What to read is a **profile**, which is data. `FhirSearchProfile` names the +resource, the search parameter, where each record holds the key, and a path +and kind for each field. Every record the server returns is checked for the +exact key, so a server that ignores the search parameter can't make the +wrong record "found". A UI read-back plugs in the same way: any reader that +returns a `ReadResult`. + +## On the receipt + +`openadapt_flow.handoffs.line` turns a handoff into the receipt's +`counterparty_confirmation` line (`predicate.confirmations[]` in +`record/run/v1`, [RECEIPTS.md](RECEIPTS.md)): + +| Ledger | Line | +|---|---| +| `x12_999`, `x12_277ca`, `report_csv`, `report_text` | `read_method: acknowledgment_message`, `strength: acknowledgment` | +| `api_readback` | `api`, `read_back` | +| `ui_readback` | `portal_read_back`, `read_back` | +| `sent` | `strength: none` | +| differing field ids | `differing_count`; each compared field opens as `:`, with `:differs` when it differs | + +The other party, the time and the fields are salted commitments. They open +only in `receipt.private.json`, never on a public card. A reason the schema +doesn't allow for a state stays in the local ledger and is left off the +line. + +**The run's receipt carries its handoffs.** When the run ends, the receipt +hook adds a line for each of the run's handoffs, usually `sent`: + +- a deferred claim check is found from its step's evidence; +- any other handoff is found by its `run_id`, which can be the report's + `run_id` or the run directory. + +The hook looks in the ledgers the run used in this process (a deferred check +and `HandoffLedger.send` note theirs). It also looks in any ledgers listed in +`OPENADAPT_HANDOFF_LEDGERS`, separated by the OS path separator. + +## Follow-up receipts + +A receipt is signed once, but a handoff keeps changing after that: it is +sent, then acknowledged, then recorded. Each change gets its own small +signed record: + +```bash +openadapt handoff list --ledger DIR --run runs/claim-0412 --sign-updates +``` + +This signs `receipt.update-N.json`, a `record/run/v1` statement that: + +- copies the original receipt's predicate unchanged; +- names the original's payload digest in `follows`, with `sequence` N; +- carries only the confirmation lines that changed since they were last + signed. A new read of the same state is not a change. + +The openings go in `receipt.update-N.private.json` (0600). Which handoff +each signed line belongs to is kept in `receipt.handoffs.json` (0600). That +file is local only and holds handoff ids, never values. + +`handoff list --run` verifies the chain with +`openadapt_types.receipt.verify_chain` and prints it: + +```text +Signed history (receipt and 2 update(s), verified) + Sent to the other party at 2026-11-21T06:00:00Z, not confirmed + Update 1: Confirmed in the other party's system at 2026-11-21T07:10:02Z + Update 2: Recorded differently in the other party's system at 2026-11-21T09:30:41Z: 1 field differs +``` + +The chain is refused in any of these cases: + +- any record fails to verify; +- a follow-up names another receipt; +- a follow-up skips or repeats a sequence number; +- a follow-up changes anything it copies from the original; +- a follow-up carries no confirmation. Such a follow-up can't be signed. + +## Privacy + +The ledger is a private directory (0700, files 0600). It holds no record +values. Keys and sent field values are HMAC-SHA256 digests of the normalized +value, under a salt kept in the ledger directory. A read-back compares +digests. No model calls. + +## Limits + +- **Follow-ups aren't signed automatically.** `--sign-updates` signs them + when someone runs it; no scheduler does. The TypeScript verifiers don't + check follow-up chains yet, and no shared test vectors exist for them. +- **Payer reports are status only.** They never compare fields, so a payer + handoff is never `recorded_*`. +- **The FHIR profile needs the receiver to keep the sender's key.** It must + be in a searchable identifier, so the read can find the record. +- **`handoff send` and `handoff verify`** are being built separately. Until + they land, the referral producer is the Python API above. +- **Real-app evidence covers one receiver.** That receiver is a synthetic + OpenEMR 7.0.3 read through FHIR. See + [`benchmark/handoff_receiver`](../benchmark/handoff_receiver/README.md). diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index 7e74f59283..386c63fad5 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -13207,6 +13207,11 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None: _add_proxy_parser(sub) register_fleet_parser(sub) + # After any other ``handoff`` verbs: it adds ``list`` to the same group. + from openadapt_flow.cli_handoff_list import register_handoff_list + + register_handoff_list(sub) + parser.add_task_help() return parser diff --git a/packages/flow/openadapt_flow/cli_deferred.py b/packages/flow/openadapt_flow/cli_deferred.py index 8daa007a53..d7c4e8f45a 100644 --- a/packages/flow/openadapt_flow/cli_deferred.py +++ b/packages/flow/openadapt_flow/cli_deferred.py @@ -17,6 +17,7 @@ from openadapt_flow.reports.parse import ReportError, ReportFormat if TYPE_CHECKING: # pragma: no cover + from openadapt_flow.handoffs.payer import SettleRecorder from openadapt_flow.runtime.effects.deferred_report import ( DeferredReportSpec, PendingLedger, @@ -130,6 +131,19 @@ def _ui_final_from_config(path: Optional[str]) -> list[Any]: ] +def _recorder( + ledger: "PendingLedger", report_format: Optional[str], report: Optional[Path] +) -> "SettleRecorder": + """Record what the report says into the claim's handoff (``handoff list``).""" + + import hashlib + + from openadapt_flow.handoffs.payer import SettleRecorder + + sha = hashlib.sha256(report.read_bytes()).hexdigest() if report else None + return SettleRecorder(ledger, report_format or "", sha) + + def cmd_deferred_settle(args: argparse.Namespace) -> int: from openadapt_flow.runtime.effects.deferred_report import settle_report_file @@ -188,11 +202,13 @@ def cmd_deferred_settle(args: argparse.Namespace) -> int: issued_at = datetime.fromisoformat(args.report_time) if issued_at.tzinfo is None: raise ValueError("--report-time needs a time zone") + recorder = _recorder(ledger, fmt.format, Path(args.report)) settled = settle_report_file( - ledger, Path(args.report), fmt, issued_at=issued_at + ledger, Path(args.report), fmt, issued_at=issued_at, observer=recorder ) else: - settled = ledger.settle(None, None) + recorder = _recorder(ledger, None, None) + settled = ledger.settle(None, None, observer=recorder) except (OSError, ValueError, ReportError) as exc: print(f"deferred settle: {exc}", file=sys.stderr) return 2 @@ -201,6 +217,9 @@ def cmd_deferred_settle(args: argparse.Namespace) -> int: word = "VERIFIED" if item.state == "verified" else "RECONCILIATION_REQUIRED" print(f"{item.id}: {word} ({item.reason}; code {item.code})") print(f"Settled {len(settled)}; {len(waiting)} still waiting.") + print( + "Open handoffs: openadapt-flow handoff list --ledger " + str(ledger.directory) + ) return 0 diff --git a/packages/flow/openadapt_flow/cli_handoff.py b/packages/flow/openadapt_flow/cli_handoff.py index 44465f4cd8..862f84db48 100644 --- a/packages/flow/openadapt_flow/cli_handoff.py +++ b/packages/flow/openadapt_flow/cli_handoff.py @@ -16,7 +16,7 @@ import urllib.parse import urllib.request from pathlib import Path -from typing import Any, Optional +from typing import Any, Literal, Optional def handoff_group(sub: argparse._SubParsersAction) -> argparse._SubParsersAction: @@ -235,7 +235,7 @@ def record_in_ledger( value = json.loads(data.decode("utf-8")) except (UnicodeDecodeError, ValueError): value = None - fields: dict[str, tuple[str, str]] = {} + fields: dict[str, tuple[str, Literal["text"]]] = {} key = None if isinstance(value, dict): if key_field is not None: diff --git a/packages/flow/openadapt_flow/cli_handoff_list.py b/packages/flow/openadapt_flow/cli_handoff_list.py new file mode 100644 index 0000000000..3ba7d8d59a --- /dev/null +++ b/packages/flow/openadapt_flow/cli_handoff_list.py @@ -0,0 +1,306 @@ +"""``openadapt-flow handoff list``: open handoffs by state, and who follows up. + +A handoff is one thing a run sent to another party's system (a claim to a +payer, a referral to a receiving clinic). ``handoff list`` reads handoff +ledgers and shows which ones still need someone to follow up: + + openadapt-flow handoff list --ledger /var/lib/openadapt/deferred + openadapt-flow handoff list --config deployment.yaml --all + openadapt-flow handoff list --ledger DIR --run runs/claim-0412 --json + +A deferred-check ledger (``effects.deferred_report.ledger``) is read as the +payer handoffs beside it (``/handoffs``), created on first read. Any +other directory is read as a handoff ledger. See ``docs/COUNTERPARTY_CONFIRMATIONS.md``. + +The ``send`` and ``verify`` subcommands belong to the same group and are +registered elsewhere; this module adds only ``list``. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from datetime import datetime +from pathlib import Path +from typing import TYPE_CHECKING, Optional + +if TYPE_CHECKING: # pragma: no cover + from openadapt_flow.handoffs.ledger import Handoff, HandoffLedger + +_STATE_WORDS = { + "sent": "sent, no answer yet", + "acknowledged": "acknowledged", + "recorded_as_intended": "recorded as intended", + "recorded_differently": "recorded differently", +} +_REASON_WORDS = { + "rejected_by_counterparty": "they refused it", + "conflicting_report": "their reports disagree", + "ambiguous_key": "the key matches more than one item", + "receiver_unreachable": "their system could not be read", + "not_found": "not in their system", + "no_answer_by_deadline": "no answer by the follow-up time", +} +_GROUPS = ( + ("needs_follow_up", "Needs follow-up"), + ("waiting", "Waiting"), + ("done", "Done"), +) + + +def _handoff_verbs(sub: argparse._SubParsersAction) -> argparse._SubParsersAction: + """The ``handoff`` group's subcommands, made if no one registered it yet. + + ``handoff send`` and ``handoff verify`` live in another module; whichever + registers first makes the group, and the other adds its verbs to it. + """ + + parser = sub.choices.get("handoff") + if parser is None: + parser = sub.add_parser( + "handoff", + help="Handoffs to other parties: what they recorded, and who follows up", + allow_abbrev=False, + ) + return parser.add_subparsers(dest="handoff_command", required=True) + for action in parser._actions: + if isinstance(action, argparse._SubParsersAction): + return action + return parser.add_subparsers(dest="handoff_command", required=True) + + +def _group(sub: argparse._SubParsersAction) -> argparse._SubParsersAction: + """The shared group: ``cli_handoff.handoff_group`` where it exists (the + module with ``send`` and ``verify``), else the same rule here.""" + + try: + from openadapt_flow.cli_handoff import handoff_group + except ImportError: + return _handoff_verbs(sub) + return handoff_group(sub) + + +def register_handoff_list(sub: argparse._SubParsersAction) -> None: + verbs = _group(sub) + listing = verbs.add_parser( + "list", + help="Open handoffs by state, with who still needs to follow up", + allow_abbrev=False, + ) + listing.add_argument( + "--ledger", + action="append", + default=[], + help="A handoff ledger, or a deferred-check ledger (repeatable)", + ) + listing.add_argument( + "--config", + default=None, + help="deployment.yaml whose effects.deferred_report names the ledger", + ) + listing.add_argument( + "--all", action="store_true", help="Also list the handoffs that are done" + ) + listing.add_argument( + "--run", + default=None, + help="Only this run's handoffs (its directory, holding report.json)", + ) + listing.add_argument( + "--json", + action="store_true", + help="Print JSON: each handoff's status and its receipt line", + ) + listing.add_argument( + "--sign-updates", + action="store_true", + help="With --run: sign a follow-up receipt for the handoffs whose state " + "changed since the run's receipt (receipt.update-N.json)", + ) + listing.set_defaults(func=cmd_handoff_list) + + +def _ledgers(args: argparse.Namespace) -> list["HandoffLedger"]: + from openadapt_flow.handoffs.ledger import HandoffLedger + from openadapt_flow.handoffs.payer import sync + from openadapt_flow.runtime.effects.deferred_report import PendingLedger + + dirs = [Path(d) for d in args.ledger] + if args.config: + from openadapt_flow.cli_deferred import _from_config + + spec = _from_config(args.config) + if spec is not None: + dirs.append(Path(spec.ledger)) + if not dirs: + raise ValueError("name a ledger with --ledger or --config") + found: list[HandoffLedger] = [] + for directory in dirs: + if not directory.is_dir(): + raise ValueError(f"no ledger at {directory}") + pending = PendingLedger(directory) + if any(e for e in _quiet_entries(pending)): + found.append(sync(pending)) + else: + found.append(HandoffLedger(directory)) + return found + + +def _quiet_entries(pending: object) -> list[object]: + try: + return list(pending.entries()) # type: ignore[attr-defined] + except Exception: # noqa: BLE001 - not a deferred ledger + return [] + + +def _describe(handoff: "Handoff") -> str: + last = handoff.evidence + words = _STATE_WORDS[handoff.state] + if last is not None and last.counterparty_accepted and last.reason is None: + words = "accepted (status only, fields not compared)" + if handoff.state == "recorded_differently" and last is not None: + words += ": " + ", ".join(last.differing_fields) + latest = handoff.last + if latest is not None and latest.reason is not None: + if handoff.state == "sent": + words = "sent" + words += f"; {_REASON_WORDS[latest.reason]}" + return words + + +def _when(text: str) -> str: + return text.replace("T", " ").removesuffix(":00Z").removesuffix("Z") + + +def cmd_handoff_list(args: argparse.Namespace) -> int: + from openadapt_flow.handoffs.ledger import now_utc + from openadapt_flow.handoffs.line import handoffs_for_run, to_line + + try: + ledgers = _ledgers(args) + if args.run: + report = json.loads((Path(args.run) / "report.json").read_text("utf-8")) + handoffs = handoffs_for_run(report, ledgers, Path(args.run)) + else: + handoffs = [h for ledger in ledgers for h in ledger.entries()] + except (OSError, ValueError) as exc: + print(f"handoff list: {exc}", file=sys.stderr) + return 2 + if args.sign_updates and not args.run: + print("handoff list: --sign-updates needs --run", file=sys.stderr) + return 2 + history = _history(Path(args.run), ledgers, args.sign_updates) if args.run else None + if history is not None and history.get("error"): + print(f"handoff list: {history['error']}", file=sys.stderr) + return 2 + # A signed history that doesn't verify fails the command, after listing. + status_code = 1 if history is not None and not history.get("verified") else 0 + now: datetime = now_utc() + if args.json: + out = [] + for handoff in handoffs: + status = handoff.status(now) + if status == "done" and not args.all and not args.run: + continue + item = to_line(handoff) + out.append( + { + "id": handoff.id, + "status": status, + "state": handoff.state, + "counterparty": handoff.counterparty, + "follow_up": handoff.follow_up, + "follow_up_due": handoff.follow_up_due, + "sent_at": handoff.sent_at, + "differing_fields": list( + handoff.evidence.differing_fields if handoff.evidence else [] + ), + "reason": handoff.last.reason if handoff.last else None, + "receipt_line": item.line, + } + ) + if history is not None: + print(json.dumps({"handoffs": out, "signed_history": history}, indent=2)) + else: + print(json.dumps(out, indent=2)) + return status_code + if not handoffs: + print("No handoffs.") + if history is not None: + _print_history(history) + return status_code + grouped: dict[str, list["Handoff"]] = {key: [] for key, _ in _GROUPS} + for handoff in handoffs: + grouped[handoff.status(now)].append(handoff) + for key, title in _GROUPS: + items = grouped[key] + if key == "done" and not args.all: + if items: + print(f"{title}: {len(items)} (--all lists them)") + continue + print(f"{title} ({len(items)})") + for handoff in items: + overdue = " OVERDUE" if handoff.overdue(now) and key != "done" else "" + print(f" {handoff.counterparty}: {_describe(handoff)}") + print( + f" sent {_when(handoff.sent_at)}, follow up by " + f"{_when(handoff.follow_up_due)}{overdue}" + + (f"; who: {handoff.follow_up}" if key == "needs_follow_up" else "") + ) + print() + if history is not None: + _print_history(history) + return status_code + + +def _history( + run_dir: Path, ledgers: list["HandoffLedger"], sign: bool +) -> Optional[dict[str, object]]: + """The run's signed handoff history: its receipt and follow-ups, verified + against this computer's key and pinned keys. With ``sign``, first sign a + follow-up for what changed.""" + + from openadapt_types import receipt as r + + from openadapt_flow.handoffs.followup import SIDECAR + + orphans = ( + any(run_dir.glob("receipt.update-*.json")) or (run_dir / SIDECAR).is_file() + ) + if not (run_dir / r.RECEIPT_FILE).is_file() and not orphans: + return {"error": "no receipt.json in the run"} if sign else None + try: + from openadapt_flow.handoffs.followup import sign_updates, verify_history + from openadapt_flow.offline_seal import seal_home, signer_for + from openadapt_flow.receipt_record import local_registry + + signed = None + if sign: + signed = sign_updates(run_dir, ledgers, signer=signer_for(seal_home())) + chain = verify_history(run_dir, local_registry()) + except ImportError: + return {"error": "openadapt-types has no follow-up receipts"} + except (OSError, ValueError) as exc: + return {"error": str(exc)} + return { + "signed_now": signed.name if signed is not None else None, + "verified": bool(chain.ok), + "reason": chain.reason, + "updates": len(chain.updates), + "lines": list(chain.lines), + } + + +def _print_history(history: dict[str, object]) -> None: + if history.get("signed_now"): + print(f"Signed {history['signed_now']}") + if not history["verified"]: + print(f"Signed history: not verified ({history['reason']})") + return + print(f"Signed history (receipt and {history['updates']} update(s), verified)") + for line in history["lines"]: # type: ignore[attr-defined] + print(f" {line}") + + +__all__ = ["register_handoff_list"] diff --git a/packages/flow/openadapt_flow/handoffs/__init__.py b/packages/flow/openadapt_flow/handoffs/__init__.py new file mode 100644 index 0000000000..0edf4c638b --- /dev/null +++ b/packages/flow/openadapt_flow/handoffs/__init__.py @@ -0,0 +1,49 @@ +"""Handoffs: did the other party record what we sent? + +A handoff is one thing a run sends to another party's system: a claim to a +payer, a referral to a receiving clinic. A counterparty confirmation is +evidence, read from that other system, of what it recorded. Each handoff +moves through four states: + +- ``sent``: we sent it, and nothing from the other side has said so yet; +- ``acknowledged``: the other side says it has it, without saying what it + recorded (an X12 999 or a 277CA ``A1``), or says it won't take it; +- ``recorded_as_intended``: the other side recorded it, and every field we + compared matches what we sent (or, for a status-only report, it accepted + it: see ``strength``); +- ``recorded_differently``: the other side recorded it, and these fields + differ from what we sent (field ids only, never the values). + +One mechanism serves every producer: a local ledger of handoffs +(:mod:`.ledger`), readers that look at the other system (:mod:`.readers`), +one comparator (:mod:`.intake`), and the mapping of the existing deferred +claim check onto handoffs (:mod:`.payer`). :mod:`.line` turns a handoff into +the receipt's ``counterparty_confirmation`` line. No engine code names an +app, a payer or a clinic: what to read, and how each field compares, is a +profile (data). + +No model calls. The ledger holds no record values: keys and field values are +HMAC-SHA256 digests under a salt kept in the ledger directory (0600). +""" + +from openadapt_flow.handoffs.ledger import ( + FieldSpec, + Handoff, + HandoffLedger, + HandoffState, + Observation, + ReadMethod, + Reason, + Strength, +) + +__all__ = [ + "FieldSpec", + "Handoff", + "HandoffLedger", + "HandoffState", + "Observation", + "ReadMethod", + "Reason", + "Strength", +] diff --git a/packages/flow/openadapt_flow/handoffs/followup.py b/packages/flow/openadapt_flow/handoffs/followup.py new file mode 100644 index 0000000000..5ac9aaa519 --- /dev/null +++ b/packages/flow/openadapt_flow/handoffs/followup.py @@ -0,0 +1,325 @@ +"""Follow-up receipts: a signed record of each change after the run's receipt. + +A run's receipt is signed once, when the run ends, so its handoff lines are +usually ``sent``. When a handoff later changes (acknowledged, recorded as +intended, recorded differently), :func:`sign_updates` signs a small +follow-up record: a ``record/run/v1`` statement that repeats the original's +predicate, names the original's payload digest in ``follows``, counts its +place in the chain (``sequence``), and carries only the confirmation lines +that changed. ``openadapt_types.receipt.verify_chain`` checks the chain, and +``handoff list --run`` shows it. + +Files in the run folder: + +- ``receipt.update-N.json``: the N-th follow-up (a DSSE envelope); +- ``receipt.update-N.private.json``: its openings (0600); +- ``receipt.handoffs.json``: which handoff each signed line belongs to, and + the line as signed, so a later update signs only what changed (0600, + local only: it names handoff ids, never values). +""" + +from __future__ import annotations + +import base64 +import hashlib +import json +import os +import re +from pathlib import Path +from typing import Any, Mapping, Optional, Sequence + +from openadapt_flow.handoffs.ledger import Handoff, HandoffLedger +from openadapt_flow.handoffs.line import ( + build_confirmations, + handoffs_for_run, + place, + to_line, +) + +SIDECAR = "receipt.handoffs.json" +SCHEMA = "openadapt.receipt-handoffs/v1" + + +def update_file(sequence: int) -> str: + return f"receipt.update-{sequence}.json" + + +def update_private_file(sequence: int) -> str: + return f"receipt.update-{sequence}.private.json" + + +def _signature(handoff: Handoff) -> dict[str, Any]: + """What a signed line says, minus when it was observed: a new read of + the same state is not a change.""" + + item = to_line(handoff) + values = {k: v for k, v in item.values.items() if k != "observed_at"} + return {**item.line, "values": values} + + +def _write_json(path: Path, payload: Any, *, private: bool) -> None: + tmp = path.with_name(path.name + ".tmp") + fd = os.open( + tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600 if private else 0o644 + ) + with os.fdopen(fd, "w") as handle: + handle.write(json.dumps(payload, indent=2, sort_keys=True) + "\n") + os.replace(tmp, path) + + +def _sidecar(run_dir: Path) -> dict[str, Any]: + path = run_dir / SIDECAR + if not path.is_file(): + return {"schema": SCHEMA, "records": []} + data = json.loads(path.read_text("utf-8")) + if data.get("schema") != SCHEMA: + raise ValueError(f"{SIDECAR} is not {SCHEMA}") + return data + + +def record_signed(run_dir: Path, file: str, handoffs: Sequence[Handoff]) -> None: + """Remember which handoffs a signed record's lines are, in line order.""" + + data = _sidecar(run_dir) + data["records"].append( + { + "file": file, + "lines": [{"handoff": h.id, "signed": _signature(h)} for h in handoffs], + } + ) + _write_json(run_dir / SIDECAR, data, private=True) + + +def last_signed(run_dir: Path) -> dict[str, dict[str, Any]]: + """Each handoff's latest signed line, across the receipt and its updates.""" + + latest: dict[str, dict[str, Any]] = {} + for record in _sidecar(run_dir)["records"]: + for item in record["lines"]: + latest[item["handoff"]] = item["signed"] + return latest + + +_UPDATE_NAME = re.compile(r"^receipt\.update-(.*)\.json$") + + +def updates(run_dir: Path) -> list[Path]: + """Every ``receipt.update-N.json`` in the run, in order. + + Fails closed (ValueError) on a gap in the numbering or a name that isn't + ``receipt.update-.json`` / ``.private.json`` with N counted from 1, so + no update file is ever silently left out of the history. + """ + numbers: list[int] = [] + private_numbers: set[int] = set() + for path in Path(run_dir).iterdir(): + match = _UPDATE_NAME.match(path.name) + if not match: + continue + stem = match.group(1) + if stem.endswith(".private"): + stem = stem[: -len(".private")] + private = True + else: + private = False + if not re.fullmatch(r"[1-9][0-9]{0,5}", stem): + raise ValueError(f"unexpected update file {path.name}") + (private_numbers.add if private else numbers.append)(int(stem)) + numbers.sort() + if numbers != list(range(1, len(numbers) + 1)): + raise ValueError("the run's update files skip a number") + if not private_numbers <= set(numbers): + raise ValueError("a private update file has no update beside it") + return [Path(run_dir) / update_file(n) for n in numbers] + + +def _pending_path(run_dir: Path) -> Path: + return run_dir / ".receipt-update.pending.json" + + +def _finish_pending(run_dir: Path, registry: Sequence[Any]) -> None: + """Complete or roll back an update whose publication was interrupted. + + The pending note is written before any update file; if the update it + names is now a whole signed record, its sidecar entry is added, and + otherwise the partial files are removed. Either way the note goes.""" + from openadapt_types import receipt as r + + from openadapt_flow.offline_seal import loads_strict + + pending = _pending_path(run_dir) + if not pending.is_file(): + return + note = json.loads(pending.read_text("utf-8")) + out = run_dir / str(note["file"]) + private = run_dir / str(note["private"]) + complete = False + try: + envelope = loads_strict(out.read_text("utf-8")) + complete = r.verify_receipt(envelope, registry).ok and private.is_file() + except (OSError, ValueError): + complete = False + if complete: + data = _sidecar(run_dir) + if note["file"] not in [rec["file"] for rec in data["records"]]: + data["records"].append({"file": note["file"], "lines": note["lines"]}) + _write_json(run_dir / SIDECAR, data, private=True) + else: + for partial in (out, private): + partial.unlink(missing_ok=True) + pending.unlink() + + +def sign_updates( + run_dir: str | Path, + ledgers: Sequence[HandoffLedger], + *, + signer: Any, +) -> Optional[Path]: + """Sign one follow-up for every handoff of the run whose line changed + since it was last signed. None when nothing changed. Needs the run's + receipt (``receipt.json``). + + Race class: one signer at a time per run (an exclusive lock from the + history check through publication), and an interrupted publication is + completed or rolled back by the next call.""" + + run_dir = Path(run_dir) + lock = run_dir / ".receipt-update.lock" + try: + fd = os.open(lock, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + except FileExistsError: + raise ValueError( + f"another signer holds {lock.name}; remove it if no signer is running" + ) from None + os.close(fd) + try: + return _sign_updates_locked(run_dir, ledgers, signer=signer) + finally: + lock.unlink(missing_ok=True) + + +def _sign_updates_locked( + run_dir: Path, + ledgers: Sequence[HandoffLedger], + *, + signer: Any, +) -> Optional[Path]: + from openadapt_types import receipt as r + + from openadapt_flow.offline_seal import loads_strict + + kid = r.key_id(signer.public_raw()) + own = r.RoleKey( + kid, base64.b64encode(signer.public_raw()).decode("ascii"), "this_computer" + ) + _finish_pending(run_dir, [own]) + original = loads_strict((run_dir / r.RECEIPT_FILE).read_text("utf-8")) + # Extend only a chain that verifies as it stands, signed by this key + # alone: the receipt and every update already written. verify_chain + # refuses a follow-up from any other key. + existing = verify_history(run_dir, [own]) + if existing is None or not existing.ok: + reason = existing.reason if existing is not None else "no receipt" + detail = ( + f" ({existing.detail})" if existing is not None and existing.detail else "" + ) + raise ValueError(f"the run's receipt does not verify: {reason}{detail}") + raw_report = (run_dir / "report.json").read_bytes() + statement = r.loads_strict(base64.b64decode(original["payload"])) + subjects = { + x["name"]: x["digest"]["sha256"] for x in statement.get("subject") or [] + } + if subjects.get("report.json") != hashlib.sha256(raw_report).hexdigest(): + # Wrong-subject class: choose the handoffs from the very report the + # receipt signed, never a later or another run's report. + raise ValueError("report.json is not the report the receipt signed") + report = loads_strict(raw_report.decode("utf-8")) + signed = last_signed(run_dir) + changed: list[Handoff] = [] + for handoff in place(statement, handoffs_for_run(report, list(ledgers), run_dir)): + if signed.get(handoff.id) != _signature(handoff): + changed.append(handoff) + if not changed: + return None + sequence = len(updates(run_dir)) + 1 + lines, openings = build_confirmations(changed) + follow_up = r.follow_up_statement(original, sequence, lines) + envelope = r.sign_statement(follow_up, [(kid, signer.sign)]) + out = run_dir / update_file(sequence) + # Race class: a sequence is claimed exclusively, so two signers can't + # write the same update; the loser fails and signs nothing. + if out.exists(): + raise ValueError(f"{out.name} was written by another signer") + # Durable before any update file: what this update is, so an + # interrupted publication can be completed or rolled back. + _write_json( + _pending_path(run_dir), + { + "file": out.name, + "private": update_private_file(sequence), + "lines": [{"handoff": h.id, "signed": _signature(h)} for h in changed], + }, + private=True, + ) + _write_json( + run_dir / update_private_file(sequence), + r.private_openings(envelope, openings), + private=True, + ) + _write_json(out, envelope, private=False) + record_signed(run_dir, out.name, changed) + _pending_path(run_dir).unlink() + return out + + +def verify_history(run_dir: str | Path, registry: Sequence[Any]) -> Any: + """``verify_chain`` over the run's receipt and its follow-ups, with + their private openings when present.""" + + from openadapt_types import receipt as r + + from openadapt_flow.offline_seal import loads_strict + + run_dir = Path(run_dir) + + def load(name: str) -> Optional[Mapping[str, Any]]: + path = run_dir / name + return loads_strict(path.read_text("utf-8")) if path.is_file() else None + + original = load(r.RECEIPT_FILE) + found = updates(run_dir) + if original is None: + if found or (run_dir / SIDECAR).is_file(): + # Missing-evidence class: signed updates without their receipt are + # a broken history, not an unsigned run. + raise ValueError("signed updates are here but receipt.json is missing") + return None + # Missing-evidence class: every update the sidecar says was signed must + # still be here, so a dropped last update can't shorten the history. + recorded = [ + rec["file"] + for rec in _sidecar(run_dir)["records"] + if rec["file"] != r.RECEIPT_FILE + ] + if sorted(recorded) != sorted(p.name for p in found): + raise ValueError("the signed updates don't match the record of what was signed") + chain = [loads_strict(p.read_text("utf-8")) for p in found] + return r.verify_chain( + original, + chain, + registry, + openings=load(r.PRIVATE_FILE), + update_openings=[load(update_private_file(i + 1)) for i in range(len(chain))], + ) + + +__all__ = [ + "SIDECAR", + "last_signed", + "record_signed", + "sign_updates", + "update_file", + "updates", + "verify_history", +] diff --git a/packages/flow/openadapt_flow/handoffs/intake.py b/packages/flow/openadapt_flow/handoffs/intake.py new file mode 100644 index 0000000000..1d34014888 --- /dev/null +++ b/packages/flow/openadapt_flow/handoffs/intake.py @@ -0,0 +1,125 @@ +"""Read a handoff back from the other party's system and record what it shows. + +One comparator for every producer. For the item's key, the reader answers +``found`` (with fields), ``not_found``, ``ambiguous`` or ``unreachable``: + +| Read | Observation | +|---|---| +| found, every field matches | ``recorded_as_intended`` | +| found, some fields differ | ``recorded_differently`` with those field ids | +| not_found | unchanged (``sent`` stays ``sent``), reason ``not_found`` | +| ambiguous | unchanged, reason ``ambiguous_key`` | +| unreachable | unchanged, reason ``receiver_unreachable`` | + +A field matches when the value the other side holds normalizes, for the +field's kind, to the same digest as the value we sent (``text`` ignores case +and runs of whitespace, ``code`` ignores separators, ``date`` compares the +calendar date; see :mod:`openadapt_flow.runtime.effects.readback_values`). +A value the other side doesn't hold, or that doesn't parse, differs. + +A record that was confirmed and then can't be found (or now matches two +records) goes back to ``sent``: nothing confirms it any more. An unreachable +receiver changes nothing it had confirmed. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Optional + +from openadapt_flow.handoffs.ledger import ( + Handoff, + HandoffLedger, + HandoffState, + LedgerError, + Observation, + ReadMethod, + Reason, + Strength, + iso_seconds, + now_utc, +) +from openadapt_flow.handoffs.readers import Reader, ReadResult + +_REASONS: dict[str, Reason] = { + "not_found": "not_found", + "ambiguous": "ambiguous_key", + "unreachable": "receiver_unreachable", +} + + +def judge( + ledger: HandoffLedger, handoff: Handoff, result: ReadResult, method: ReadMethod +) -> Observation: + """The observation one read gives, without writing it.""" + + previous: HandoffState = handoff.state + observed_at = iso_seconds(now_utc()) + if result.status != "found": + reason: Reason = _REASONS[result.status] + state = previous + if reason != "receiver_unreachable" and previous.startswith("recorded_"): + state = "sent" + last = handoff.last + strength: Strength = ( + "none" if state == "sent" or last is None else last.strength + ) + return Observation( + state=state, + observed_at=observed_at, + read_method=method, + strength=strength, + reason=reason, + evidence_sha256=result.evidence_sha256, + ) + differing: list[str] = [] + digests: dict[str, str] = {} + for field_id, spec in sorted(handoff.fields.items()): + value = result.fields.get(field_id) + # Wrong-reading class: the receiver's text is read in the receiver's + # date order. With none declared, a date that reads two ways doesn't + # normalize and counts as differing, never as the sender's date. + order = result.date_orders.get(field_id) + seen = None if value is None else ledger.field_digest(value, spec.kind, order) + digests[field_id] = seen or "missing" + if seen != spec.digest: + differing.append(field_id) + return Observation( + state="recorded_differently" if differing else "recorded_as_intended", + observed_at=observed_at, + read_method=method, + strength="field_readback", + differing_fields=differing, + observed_digests=digests, + evidence_sha256=result.evidence_sha256, + ) + + +def check( + ledger: HandoffLedger, + handoff_id: str, + key: str, + reader: Reader, +) -> Handoff: + """Read the item back through ``reader`` and append the observation.""" + + handoff = ledger.get(handoff_id) + if handoff is None: + raise LedgerError("no such handoff") + if ledger.digest(key) != handoff.key_digest: + raise LedgerError("that key isn't this handoff's key") + if not handoff.fields: + raise LedgerError("this handoff sent no fields to compare") + result = reader.read(key) + return ledger.observe( + handoff_id, judge(ledger, handoff, result, reader.read_method) + ) + + +def needs_follow_up( + ledger: HandoffLedger, now: Optional[datetime] = None +) -> list[Handoff]: + return [h for h in ledger.entries() if h.status(now) == "needs_follow_up"] + + +__all__ = ["check", "judge", "needs_follow_up"] diff --git a/packages/flow/openadapt_flow/handoffs/ledger.py b/packages/flow/openadapt_flow/handoffs/ledger.py new file mode 100644 index 0000000000..4eb4ba95f2 --- /dev/null +++ b/packages/flow/openadapt_flow/handoffs/ledger.py @@ -0,0 +1,376 @@ +"""The handoff ledger: what we sent, to whom, and what they say they recorded. + +One JSON file per handoff in a private directory (0700, files 0600). A +handoff keeps: + +- when it was sent and when someone must follow up (``follow_up_due``); +- who the other party is, as a short label, and who follows up; +- the item's key and each sent field's value, only as HMAC-SHA256 digests of + the normalized value under the ledger's salt, so a read-back can compare + without the ledger ever holding a value; +- every observation, in order. An observation is never edited or removed. + +The handoff's state is its latest observation's state, or ``sent`` with none. +An observation that learned nothing new (the receiver was unreachable, the +key matched two records) carries the previous state with a reason. +""" + +from __future__ import annotations + +import hashlib +import hmac +import json +import os +import re +import secrets +from contextlib import contextmanager +from datetime import datetime, timedelta, timezone +from pathlib import Path +from typing import Iterator, Literal, Mapping, Optional + +from pydantic import BaseModel, ConfigDict, Field + +from openadapt_flow.runtime.effects.readback_values import ValueKind, normalize_value + +SCHEMA: Literal["openadapt.handoff/v1"] = "openadapt.handoff/v1" + +HandoffState = Literal[ + "sent", "acknowledged", "recorded_as_intended", "recorded_differently" +] +#: How the other system was read. +ReadMethod = Literal[ + "x12_999", "x12_277ca", "report_csv", "report_text", "api_readback", "ui_readback" +] +#: ``field_readback``: the fields were read back and compared. +#: ``status_only``: the other side gave a status for the item, not its fields. +Strength = Literal["field_readback", "status_only", "none"] +#: Why an observation needs a person, or learned nothing new. +Reason = Literal[ + "rejected_by_counterparty", + "conflicting_report", + "ambiguous_key", + "receiver_unreachable", + "not_found", + "no_answer_by_deadline", +] +#: The receipt schema's kinds of other system. +SystemKind = Literal[ + "ehr", + "payer_portal", + "bank", + "erp", + "crm", + "government_portal", + "email", + "other", +] +#: Reasons that need a person even before the follow-up time. +ATTENTION: frozenset[str] = frozenset( + {"rejected_by_counterparty", "conflicting_report", "ambiguous_key"} +) +Status = Literal["needs_follow_up", "waiting", "done"] + +_FIELD_ID = re.compile(r"[a-z][a-z0-9_]{0,31}") +_DIGEST = r"^[0-9a-f]{64}$" +_LABEL_MAX = 80 +_SALT_FILE = ".salt" +_LOCK_FILE = ".lock" + + +def now_utc() -> datetime: + return datetime.now(timezone.utc) + + +def iso_seconds(moment: datetime) -> str: + """Whole seconds in UTC with a ``Z``, as the receipt line takes it.""" + return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def parse_iso(text: str) -> datetime: + return datetime.fromisoformat(text.replace("Z", "+00:00")) + + +class _Closed(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class FieldSpec(_Closed): + """One field we sent: how it compares, and its value's digest.""" + + kind: ValueKind = "text" + digest: str = Field(pattern=_DIGEST) + #: For a date written day-first or month-first (``dmy``/``mdy``). + date_order: Optional[Literal["dmy", "mdy"]] = None + + +class Observation(_Closed): + """One look at the other system. Never edited after it is written.""" + + state: HandoffState + observed_at: str + read_method: ReadMethod + strength: Strength + #: Field ids that differ from what we sent (never the values). + differing_fields: list[str] = Field(default_factory=list, max_length=64) + #: For each compared field, the digest of the value the other side holds + #: (``missing`` when it holds none). Private: it opens only in the + #: receipt's private openings. + observed_digests: dict[str, str] = Field(default_factory=dict) + #: A status-only report accepted the item (a 277CA ``A2``). It still says + #: nothing about the fields, so the state stays ``acknowledged``; the + #: handoff needs no follow-up. + counterparty_accepted: bool = False + reason: Optional[Reason] = None + #: SHA-256 of the report or read-back body this came from. + evidence_sha256: Optional[str] = Field(default=None, pattern=_DIGEST) + + +class Handoff(_Closed): + schema_version: Literal["openadapt.handoff/v1"] = SCHEMA + id: str = Field(pattern=r"^handoff:[0-9a-f]{32}$") + sent_at: str + follow_up_due: str + #: The other party, for people ("payer 277CA", "receiving clinic"). + counterparty: str = Field(max_length=_LABEL_MAX) + system_kind: SystemKind = "other" + #: Who follows up when it is overdue or differs ("billing", "referrals desk"). + follow_up: str = Field(default="the sender", max_length=_LABEL_MAX) + key_digest: str = Field(pattern=_DIGEST) + #: At most 31 fields: every compared field must fit on the receipt line. + fields: dict[str, FieldSpec] = Field(default_factory=dict, max_length=31) + #: Where it came from: a deferred check's id, or a run's id. + source: Optional[str] = Field(default=None, max_length=128) + run_id: Optional[str] = Field(default=None, max_length=128) + step: Optional[int] = Field(default=None, ge=0, le=10_000) + observations: list[Observation] = Field(default_factory=list) + + @property + def state(self) -> HandoffState: + evidence = self.evidence + return evidence.state if evidence is not None else "sent" + + @property + def last(self) -> Optional[Observation]: + return self.observations[-1] if self.observations else None + + @property + def evidence(self) -> Optional[Observation]: + """The latest observation that learned something: an unreachable + receiver says nothing about the record, so it never replaces an + earlier read. The latest one when every read failed.""" + + for observation in reversed(self.observations): + if observation.reason != "receiver_unreachable": + return observation + return self.last + + def overdue(self, now: Optional[datetime] = None) -> bool: + return parse_iso(self.follow_up_due) <= (now or now_utc()) + + def status(self, now: Optional[datetime] = None) -> Status: + """``done`` only when recorded as intended (or accepted by a + status-only report) and nothing since says otherwise; ``needs_follow_up`` when it differs, was refused, is + ambiguous, or is past its follow-up time; else ``waiting``.""" + + last = self.evidence + reason = last.reason if last is not None else None + if reason is None and ( + self.state == "recorded_as_intended" + or (last is not None and last.counterparty_accepted) + ): + return "done" + if ( + self.state == "recorded_differently" + or reason in ATTENTION + or self.overdue(now) + ): + return "needs_follow_up" + return "waiting" + + +class LedgerError(ValueError): + """The ledger refused a change. The message carries no record values.""" + + +class HandoffLedger: + """A directory of handoffs, changed only under a file lock.""" + + def __init__(self, directory: str | Path) -> None: + self.directory = Path(directory) + + # -- storage ------------------------------------------------------------ + def _ensure(self) -> None: + self.directory.mkdir(parents=True, exist_ok=True) + os.chmod(self.directory, 0o700) + + @contextmanager + def _locked(self) -> Iterator[None]: + self._ensure() + import fcntl + + with open(self.directory / _LOCK_FILE, "a+") as handle: + os.chmod(self.directory / _LOCK_FILE, 0o600) + fcntl.flock(handle, fcntl.LOCK_EX) + try: + yield + finally: + fcntl.flock(handle, fcntl.LOCK_UN) + + def _salt(self) -> bytes: + path = self.directory / _SALT_FILE + if not path.exists(): + self._ensure() + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, "w") as handle: + handle.write(secrets.token_hex(32)) + return bytes.fromhex(path.read_text().strip()) + + def digest(self, text: str) -> str: + return hmac.new(self._salt(), text.encode("utf-8"), hashlib.sha256).hexdigest() + + def field_digest( + self, value: str, kind: ValueKind, date_order: Optional[str] = None + ) -> Optional[str]: + """The digest of ``value`` normalized for ``kind``; None if it doesn't + parse as that kind (a date that reads two ways, a word for a number).""" + + normal = normalize_value(str(value), kind, date_order=date_order) + return None if normal is None else self.digest(f"{kind}\x00{normal}") + + def _path(self, handoff_id: str) -> Path: + return self.directory / f"{handoff_id.split(':', 1)[1]}.json" + + def _write(self, handoff: Handoff) -> None: + path = self._path(handoff.id) + tmp = path.with_suffix(".tmp") + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w") as handle: + handle.write(handoff.model_dump_json(indent=2)) + os.replace(tmp, path) + + def get(self, handoff_id: str) -> Optional[Handoff]: + path = self._path(handoff_id) + if not path.exists(): + return None + return Handoff.model_validate_json(path.read_text()) + + def entries(self) -> list[Handoff]: + if not self.directory.exists(): + return [] + found = [ + Handoff.model_validate_json(path.read_text()) + for path in sorted(self.directory.glob("*.json")) + ] + return sorted(found, key=lambda h: (h.sent_at, h.id)) + + def with_key(self, key: str) -> list[Handoff]: + digest = self.digest(key) + return [h for h in self.entries() if h.key_digest == digest] + + # -- changes ------------------------------------------------------------ + def send( + self, + key: str, + fields: Mapping[str, tuple[str, ValueKind] | tuple[str, ValueKind, str]], + *, + counterparty: str, + follow_up_hours: float, + system_kind: SystemKind = "other", + follow_up: str = "the sender", + source: Optional[str] = None, + run_id: Optional[str] = None, + step: Optional[int] = None, + now: Optional[datetime] = None, + ) -> Handoff: + """Record that we sent the item ``key`` with these field values. + + ``fields`` maps a field id to ``(value, kind)`` or ``(value, kind, + date_order)``. A value that doesn't normalize for its kind is refused, + since it could never be compared. A key that another open handoff + already uses is refused: a read-back couldn't tell them apart. + """ + + if not key: + raise LedgerError("a handoff needs the item's key") + if follow_up_hours <= 0: + raise LedgerError("follow_up_hours must be positive") + specs: dict[str, FieldSpec] = {} + if len(fields) > 31: + raise LedgerError("a handoff compares at most 31 fields") + for field_id, spec in fields.items(): + if not _FIELD_ID.fullmatch(field_id): + raise LedgerError( + f"field id {field_id!r} must be lower case, digits and _, " + "at most 32 characters" + ) + value, kind = spec[0], spec[1] + order = spec[2] if len(spec) > 2 else None # type: ignore[misc] + if order not in (None, "dmy", "mdy"): + raise LedgerError(f"field {field_id!r}: date order is dmy or mdy") + digest = self.field_digest(value, kind, order) + if digest is None: + raise LedgerError(f"field {field_id!r} doesn't read as a {kind}") + specs[field_id] = FieldSpec( + kind=kind, + digest=digest, + date_order=order, # type: ignore[arg-type] + ) + moment = now or now_utc() + with self._locked(): + key_digest = self.digest(key) + for other in self.entries(): + # Wrong-subject class: a key names one delivery. A done + # handoff's record would otherwise confirm a second delivery + # under the same key that never arrived. + if other.key_digest == key_digest: + raise LedgerError("another handoff already uses this key") + handoff = Handoff( + id=f"handoff:{secrets.token_hex(16)}", + sent_at=iso_seconds(moment), + follow_up_due=iso_seconds(moment + timedelta(hours=follow_up_hours)), + counterparty=counterparty[:_LABEL_MAX], + system_kind=system_kind, + follow_up=follow_up[:_LABEL_MAX], + key_digest=key_digest, + fields=specs, + source=source, + run_id=run_id, + step=step, + ) + self._write(handoff) + from openadapt_flow.handoffs.registry import note_ledger + + note_ledger(self.directory) + return handoff + + def adopt(self, handoff: Handoff) -> Handoff: + """Add a handoff made elsewhere (a deferred check) unless it exists.""" + + with self._locked(): + existing = self.get(handoff.id) + if existing is not None: + return existing + self._write(handoff) + return handoff + + def observe(self, handoff_id: str, observation: Observation) -> Handoff: + """Append one observation. Earlier ones are never changed.""" + + with self._locked(): + current = self.get(handoff_id) + if current is None: + raise LedgerError("no such handoff") + updated = current.model_copy( + update={"observations": [*current.observations, observation]} + ) + self._write(updated) + return updated + + +def evidence_digest(body: str | bytes) -> str: + data = body.encode("utf-8") if isinstance(body, str) else body + return hashlib.sha256(data).hexdigest() + + +def dump_json(handoff: Handoff) -> str: + return json.dumps(handoff.model_dump(mode="json"), sort_keys=True) diff --git a/packages/flow/openadapt_flow/handoffs/line.py b/packages/flow/openadapt_flow/handoffs/line.py new file mode 100644 index 0000000000..eee3378223 --- /dev/null +++ b/packages/flow/openadapt_flow/handoffs/line.py @@ -0,0 +1,270 @@ +"""Turn a handoff into the receipt's ``counterparty_confirmation`` line. + +This is the one place that knows the signed shape +(``openadapt_types.receipt.Confirmation`` in ``record/run/v1``). The ledger +keeps richer, local-only detail; this module maps it onto the closed line +and the values its commitments open to: + +| Ledger | Line | +|---|---| +| ``x12_999``, ``x12_277ca``, ``report_csv``, ``report_text`` | ``read_method: acknowledgment_message`` | +| ``api_readback`` | ``api`` | +| ``ui_readback`` | ``portal_read_back`` | +| ``field_readback`` | ``strength: read_back`` | +| ``status_only`` | ``acknowledgment`` | +| ``sent`` (any) | ``none`` | +| differing field ids | ``differing_count``; each compared field opens as ``:`` with ``:differs`` when it differs | + +The counterparty opens as ``:cp-<16 hex>`` (a digest of its +label, never the label), ``observed_at`` as whole seconds in UTC, and the +reason only when the schema allows it for the state. A reason the schema +doesn't allow there stays in the ledger and is left off the line, so a line +is never inconsistent. + +When ``openadapt_types.receipt`` is installed (it carries the schema from +``record/run/v1`` with confirmations), :func:`build_confirmations` also +commits the values and validates each line against the real model. Without +it, the lines and the values to commit come back unchecked, for a writer +that commits them itself. +""" + +from __future__ import annotations + +import hashlib +from dataclasses import dataclass, field +from typing import Any, Mapping, Optional, Sequence + +from openadapt_flow.handoffs.ledger import Handoff, HandoffLedger + +KIND = "counterparty_confirmation" +#: A line commits to at most 34 values: counterparty, observed_at, reason +#: and up to 31 fields. +_MAX_FIELDS = 31 + +_READ_METHOD = { + "x12_999": "acknowledgment_message", + "x12_277ca": "acknowledgment_message", + "report_csv": "acknowledgment_message", + "report_text": "acknowledgment_message", + "api_readback": "api", + "ui_readback": "portal_read_back", +} +_STRENGTH = {"field_readback": "read_back", "status_only": "acknowledgment"} +#: The schema's rule: which reasons each state may carry. Mirrors +#: ``openadapt_types.receipt.REASONS_FOR_STATE``; a test keeps them equal. +REASONS_FOR_STATE: Mapping[str, frozenset[str]] = { + "sent": frozenset( + { + "rejected_by_counterparty", + "ambiguous_key", + "receiver_unreachable", + "not_found", + "no_answer_by_deadline", + } + ), + "acknowledged": frozenset({"ambiguous_key", "not_found", "no_answer_by_deadline"}), + "recorded_as_intended": frozenset({"conflicting_report"}), + "recorded_differently": frozenset({"conflicting_report"}), +} +#: The read a handoff has before anything came back: nothing, so the line's +#: method is the one the producer will use. +_DEFAULT_METHOD = {"payer_portal": "acknowledgment_message"} + + +@dataclass(frozen=True) +class ConfirmationLine: + """One line and the values its commitments open to (private).""" + + line: dict[str, Any] + #: ``counterparty``, ``observed_at``, ``reason``, ``field.N`` -> value. + values: dict[str, str] + #: Field ids in ``field.N`` order, for the local view only. + field_ids: tuple[str, ...] = field(default=()) + + +def counterparty_ref(handoff: Handoff) -> str: + label = hashlib.sha256(handoff.counterparty.encode("utf-8")).hexdigest()[:16] + return f"{handoff.system_kind}:cp-{label}" + + +def to_line(handoff: Handoff) -> ConfirmationLine: + """The line for ``handoff`` as it stands now (its latest observation).""" + + last = handoff.evidence + state = last.state if last is not None else "sent" + if last is not None: + method = _READ_METHOD[last.read_method] + strength = "none" if state == "sent" else _STRENGTH.get(last.strength, "none") + observed_at = last.observed_at + reason = last.reason if last.reason in REASONS_FOR_STATE[state] else None + else: + method = _DEFAULT_METHOD.get(handoff.system_kind, "api") + strength = "none" + observed_at = handoff.sent_at + reason = None + values: dict[str, str] = { + "counterparty": counterparty_ref(handoff), + "observed_at": observed_at, + } + if reason is not None: + values["reason"] = reason + field_ids: list[str] = [] + differing = 0 + if last is not None and last.strength == "field_readback" and state != "sent": + # Fail closed: every compared field must fit on the line, and every + # differing field must be one of them, so differing_count is never + # short of what judge() found. + if len(handoff.fields) > _MAX_FIELDS: + raise ValueError(f"a handoff line holds at most {_MAX_FIELDS} fields") + unknown = set(last.differing_fields) - set(handoff.fields) + if unknown: + raise ValueError("a differing field is not one the handoff compared") + for index, field_id in enumerate(sorted(handoff.fields)): + seen = ( + last.observed_digests.get(field_id) or handoff.fields[field_id].digest + ) + if seen == "missing": + seen = hashlib.sha256(b"missing").hexdigest() + differs = field_id in last.differing_fields + differing += differs + values[f"field.{index}"] = f"{field_id}:{seen}" + ( + ":differs" if differs else "" + ) + field_ids.append(field_id) + if state == "recorded_differently" and not differing: + raise ValueError( + "a recorded_differently read-back names no differing field" + ) + line = { + "kind": KIND, + "for_step": handoff.step, + "system_kind": handoff.system_kind, + "read_method": method, + "state": state, + "strength": strength, + "differing_count": differing, + } + return ConfirmationLine(line=line, values=values, field_ids=tuple(field_ids)) + + +def build_confirmations( + handoffs: Sequence[Handoff], *, salt: Optional[Any] = None +) -> tuple[list[dict[str, Any]], dict[str, dict[str, str]]]: + """Signed-shape lines for ``predicate.confirmations`` and their openings. + + Needs ``openadapt_types.receipt`` with confirmations; raises ImportError + without it. Each line is validated against the schema's model. + """ + + from openadapt_types import receipt as r + + lines: list[dict[str, Any]] = [] + openings: dict[str, dict[str, str]] = {} + for index, handoff in enumerate(handoffs): + item = to_line(handoff) + values = {r.confirmation_path(index, k): v for k, v in item.values.items()} + commitments, opened = r.make_openings(values, salt=salt) + line = { + **item.line, + "commitments": {k.split(".", 2)[2]: v for k, v in commitments.items()}, + } + r.Confirmation.model_validate(line) + lines.append(line) + openings.update(opened) + return lines, openings + + +def handoffs_for_run( + report: Mapping[str, Any], + ledgers: Sequence[HandoffLedger], + run_dir: Optional[Any] = None, +) -> list[Handoff]: + """The handoffs a run made, each with ``step`` set to its write's index. + + A deferred claim check is found by the ``deferred_check`` id on the + step's effect evidence; any other handoff by its ``run_id``, which names + the report's ``run_id`` or the run directory's resolved path. + """ + + by_source: dict[str, Handoff] = {} + by_run: list[Handoff] = [] + from pathlib import Path + + run_id = report.get("run_id") + # The resolved directory only, never its bare name: two runs can share a + # folder name. + directory = Path(run_dir).resolve() if run_dir is not None else None + + def ours(value: Optional[str]) -> bool: + if not value: + return False + if isinstance(run_id, str) and run_id and value == run_id: + return True + path = Path(value) + return ( + directory is not None and path.is_absolute() and path.resolve() == directory + ) + + for ledger in ledgers: + for handoff in ledger.entries(): + if handoff.source: + by_source[handoff.source] = handoff + if ours(handoff.run_id): + by_run.append(handoff) + found: dict[str, Handoff] = {h.id: h for h in by_run} + results = report.get("results") + for index, result in enumerate(results if isinstance(results, list) else []): + if not isinstance(result, Mapping): + continue + for evidence in result.get("effect_evidence") or []: + entry_id = ( + evidence.get("deferred_check") + if isinstance(evidence, Mapping) + else None + ) + match = by_source.get(entry_id) if entry_id else None + if match is not None: + found[match.id] = match.model_copy(update={"step": index}) + return sorted(found.values(), key=lambda h: (h.step or 0, h.sent_at, h.id)) + + +def place(statement: Mapping[str, Any], handoffs: Sequence[Handoff]) -> list[Handoff]: + """The handoffs as the statement will carry them: a handoff whose step + has no line on the statement goes on without a step.""" + + steps = {line["step"] for line in statement["predicate"].get("lines", [])} + return [ + h if h.step in steps else h.model_copy(update={"step": None}) for h in handoffs + ] + + +def attach_confirmations( + statement: dict[str, Any], + openings: dict[str, dict[str, str]], + handoffs: Sequence[Handoff], + *, + salt: Optional[Any] = None, +) -> tuple[dict[str, Any], dict[str, dict[str, str]]]: + """Put the handoffs' lines into a ``record/run/v1`` statement before it + is signed: ``predicate.confirmations`` and their openings. A handoff + whose step has no line on the statement is attached without a step.""" + + placed = place(statement, handoffs) + lines, opened = build_confirmations(placed, salt=salt) + out = {**statement, "predicate": {**statement["predicate"], "confirmations": lines}} + if not lines: + out["predicate"].pop("confirmations") + return out, {**openings, **opened} + + +__all__ = [ + "KIND", + "attach_confirmations", + "handoffs_for_run", + "place", + "REASONS_FOR_STATE", + "ConfirmationLine", + "build_confirmations", + "counterparty_ref", + "to_line", +] diff --git a/packages/flow/openadapt_flow/handoffs/payer.py b/packages/flow/openadapt_flow/handoffs/payer.py new file mode 100644 index 0000000000..4d23221f03 --- /dev/null +++ b/packages/flow/openadapt_flow/handoffs/payer.py @@ -0,0 +1,238 @@ +"""Payer acknowledgments as handoffs: the deferred claim check, seen from +the other side. + +A claim saved with a deferred check (``effects.kind: deferred_report``) is a +handoff to the payer. Its handoff lives beside the deferred ledger, in +``/handoffs``, with the same id digits (``deferred:`` -> +``handoff:``). ``deferred settle`` records what each report says about +it, including a row that settles nothing yet: + +| The report says | Handoff | +|---|---| +| nothing yet | ``sent``, follow-up due at the check's deadline | +| received (999 ``A`` or ``E``; 277CA ``A1``; any other pending status) | ``acknowledged`` | +| accepted (277CA ``A2``) | ``acknowledged``, accepted: no follow-up | +| rejected (999 ``R``/``M``/``W``/``X``; 277CA ``A3``/``A4``/``A6``/``A7``/``A8``) | ``sent``, reason ``rejected_by_counterparty`` | +| two rows that disagree | ``acknowledged``, reason ``conflicting_report`` | +| two waiting claims on one key | unchanged, reason ``ambiguous_key`` | +| nothing by the deadline | unchanged, reason ``no_answer_by_deadline`` | + +An acknowledgment is never ``recorded_as_intended``: a 277CA ``A2`` says the +payer accepted the claim into adjudication, not what it recorded for each +field. Only a read-back that compares the fields says that. + +Only the X12 formats are a counterparty's own answer. A CSV export or a +saved status page may be the sending system's own report, so those entries +are not handoffs unless the caller says they are (``exports=True``). + +The deferred check's own settlement is unchanged: this only listens. +""" + +from __future__ import annotations + +from datetime import datetime +from pathlib import Path +from typing import Optional + +from openadapt_flow.handoffs.ledger import ( + Handoff, + HandoffLedger, + Observation, + ReadMethod, + iso_seconds, + now_utc, + parse_iso, +) +from openadapt_flow.reports.parse import ReportRow +from openadapt_flow.runtime.effects.deferred_report import PendingCheck, PendingLedger + +COUNTERPARTY_FORMATS = ("x12-999", "x12-277ca") +EXPORT_FORMATS = ("csv", "text") +_METHOD: dict[str, ReadMethod] = { + "x12-999": "x12_999", + "x12-277ca": "x12_277ca", + "csv": "report_csv", + "text": "report_text", +} + + +def handoff_ledger(pending: PendingLedger) -> HandoffLedger: + return HandoffLedger(Path(pending.directory) / "handoffs") + + +def handoff_id(entry: PendingCheck) -> str: + return "handoff:" + entry.id.split(":", 1)[1] + + +def _is_handoff(entry: PendingCheck, exports: bool) -> bool: + formats = COUNTERPARTY_FORMATS + (EXPORT_FORMATS if exports else ()) + return entry.report_format in formats + + +def as_handoff(entry: PendingCheck, *, follow_up: str = "billing") -> Handoff: + return Handoff( + id=handoff_id(entry), + sent_at=iso_seconds(parse_iso(entry.created_at)), + follow_up_due=iso_seconds(parse_iso(entry.deadline)), + counterparty=entry.describe[:80], + system_kind="payer_portal", + follow_up=follow_up, + key_digest=entry.key_digest, + source=entry.id, + ) + + +def observation_for( + current: Handoff, + row: Optional[ReportRow], + waiting_on_key: int, + method: ReadMethod, + *, + evidence_sha256: Optional[str], + now: Optional[datetime] = None, +) -> Observation: + """What one report row (or the deadline) says about a payer handoff.""" + + at = iso_seconds(now or now_utc()) + previous = current.state + last = current.evidence + kept_strength = "none" if previous == "sent" or last is None else last.strength + if row is None: + return Observation( + state=previous, + observed_at=at, + read_method=last.read_method if last is not None else method, + strength=kept_strength, + reason="no_answer_by_deadline", + ) + if waiting_on_key > 1: + return Observation( + state=previous, + observed_at=at, + read_method=method, + strength=kept_strength, + reason="ambiguous_key", + evidence_sha256=evidence_sha256, + ) + if row.status == "rejected": + return Observation( + state="sent", + observed_at=at, + read_method=method, + strength="none", + reason="rejected_by_counterparty", + evidence_sha256=evidence_sha256, + ) + return Observation( + state="acknowledged", + observed_at=at, + read_method=method, + strength="status_only", + reason="conflicting_report" if row.status == "conflicting" else None, + counterparty_accepted=row.status == "accepted", + evidence_sha256=evidence_sha256, + ) + + +def _same(a: Observation, b: Observation, *, evidence: bool = True) -> bool: + keep = ("state", "reason", "counterparty_accepted") + ( + ("evidence_sha256",) if evidence else () + ) + return all(getattr(a, k) == getattr(b, k) for k in keep) + + +class SettleRecorder: + """The observer ``PendingLedger.settle`` calls; records into handoffs. + + The same report read twice adds nothing the second time. + """ + + def __init__( + self, + pending: PendingLedger, + report_format: str, + report_sha256: Optional[str], + *, + exports: bool = False, + follow_up: str = "billing", + ) -> None: + self.handoffs = handoff_ledger(pending) + self.method = _METHOD.get(report_format, "report_text") + self.report_sha256 = report_sha256 + self.exports = exports + self.follow_up = follow_up + self.recorded = 0 + + def __call__( + self, entry: PendingCheck, row: Optional[ReportRow], waiting_on_key: int + ) -> None: + if not _is_handoff(entry, self.exports): + return + current = self.handoffs.adopt(as_handoff(entry, follow_up=self.follow_up)) + observation = observation_for( + current, + row, + waiting_on_key, + self.method, + evidence_sha256=self.report_sha256, + ) + if current.last is not None and _same(current.last, observation): + return + self.handoffs.observe(current.id, observation) + self.recorded += 1 + + +def sync( + pending: PendingLedger, *, exports: bool = False, follow_up: str = "billing" +) -> HandoffLedger: + """Make sure every deferred claim check has its handoff, up to date. + + A claim that settled without the observer hearing it (before handoffs + existed, or expired by another caller of ``settle``) gets one observation + from the settlement (accepted, rejected, expired); the settlement's + reason text names which. A settlement the observer already recorded adds + nothing. + """ + + handoffs = handoff_ledger(pending) + for entry in pending.entries(): + if not _is_handoff(entry, exports): + continue + current = handoffs.adopt(as_handoff(entry, follow_up=follow_up)) + if entry.state == "waiting": + continue + method = _METHOD.get(entry.report_format, "report_text") + at = parse_iso(entry.settled_at) if entry.settled_at else None + reason_text = (entry.reason or "").casefold() + if entry.state == "verified": + row: Optional[ReportRow] = ReportRow("", "accepted", entry.code or "") + count = 1 + elif entry.code == "deadline": + row, count = None, 0 + elif "same report key" in reason_text: + row, count = ReportRow("", "pending", entry.code or ""), 2 + elif "rejected" in reason_text: + row, count = ReportRow("", "rejected", entry.code or ""), 1 + else: + row, count = ReportRow("", "conflicting", entry.code or ""), 1 + observation = observation_for( + current, row, count, method, evidence_sha256=entry.settled_by, now=at + ) + # Already recorded by ``deferred settle``'s observer: nothing new. + if current.last is not None and _same( + current.last, observation, evidence=False + ): + continue + handoffs.observe(current.id, observation) + return handoffs + + +__all__ = [ + "COUNTERPARTY_FORMATS", + "SettleRecorder", + "as_handoff", + "handoff_id", + "handoff_ledger", + "observation_for", + "sync", +] diff --git a/packages/flow/openadapt_flow/handoffs/readers.py b/packages/flow/openadapt_flow/handoffs/readers.py new file mode 100644 index 0000000000..ca8bdfa99d --- /dev/null +++ b/packages/flow/openadapt_flow/handoffs/readers.py @@ -0,0 +1,249 @@ +"""Readers: look up one item in the other party's system. + +A reader takes the item's key and answers with what the other system holds +for it, as flat ``field id -> value`` text: + +- ``found``: exactly one record has the key; +- ``not_found``: none does (it never arrived, or not yet); +- ``ambiguous``: more than one does, so none of them confirms anything; +- ``unreachable``: the read failed (network, a 4xx or 5xx, an expired + token, a body that isn't what the profile says). Never read as + ``not_found``. + +What to read is a profile (data), not code. :class:`FhirSearchProfile` reads +any FHIR R4 server: a search by one parameter and a path per field. A UI +read-back plugs in the same way, by returning a :class:`ReadResult`. +""" + +from __future__ import annotations + +import hashlib +import json +import os +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Literal, Mapping, Optional, Protocol + +from pydantic import BaseModel, ConfigDict, Field + +from openadapt_flow.fhir_read import fhir_read_headers, next_page_url +from openadapt_flow.handoffs.ledger import ReadMethod +from openadapt_flow.runtime.effects.fhir import extract_path +from openadapt_flow.runtime.effects.readback_values import ValueKind + +ReadStatus = Literal["found", "not_found", "ambiguous", "unreachable"] + + +@dataclass(frozen=True) +class ReadResult: + status: ReadStatus + #: For ``found``: each profile field's value as text, None when absent. + fields: dict[str, Optional[str]] = field(default_factory=dict) + #: SHA-256 of the body read, for the observation's evidence digest. + evidence_sha256: Optional[str] = None + #: The receiver's own date order per field (``dmy``/``mdy``), when its + #: profile declares one. The sender's order never reads its values. + date_orders: dict[str, Optional[str]] = field(default_factory=dict) + + +class Reader(Protocol): + read_method: ReadMethod + + def read(self, key: str) -> ReadResult: ... + + +class FieldPath(BaseModel): + model_config = ConfigDict(extra="forbid") + + #: Dotted path in the resource (``birthDate``, ``name.family``, + #: ``telecom[system=phone].value``). + path: str + kind: ValueKind = "text" + date_order: Optional[Literal["dmy", "mdy"]] = None + + +class FhirSearchProfile(BaseModel): + """How to find one item in a FHIR R4 server and read its fields.""" + + model_config = ConfigDict(extra="forbid") + + resource: str = Field(pattern=r"^[A-Z][A-Za-z]{1,63}$") + #: The search parameter that finds the item by its key (``identifier``). + key_param: str = Field(pattern=r"^[a-z][a-z0-9_:.-]{0,63}$") + #: How the key is written into the search (``urn:x|{key}``). + key_template: str = "{key}" + #: Where each returned record holds the key. Every record the search + #: returns is checked here too, so a server that ignores the search + #: parameter (and returns everything) can't make a wrong record "found". + key_path: str + fields: dict[str, FieldPath] = Field(min_length=1, max_length=64) + #: The other party, for people. + counterparty: str = Field(default="the receiver", max_length=80) + system_kind: Literal[ + "ehr", + "payer_portal", + "bank", + "erp", + "crm", + "government_portal", + "email", + "other", + ] = "other" + + @classmethod + def load(cls, path: str | Path) -> "FhirSearchProfile": + import yaml + + return cls.model_validate(yaml.safe_load(Path(path).read_text())) + + +def _text(value: Any) -> Optional[str]: + if value is None or isinstance(value, (dict, list)): + return None + return str(value) + + +class FhirSearchReader: + """Read one item from a FHIR R4 server by a profile. + + ``base_url`` is the FHIR base; the token comes from ``token`` or the + environment variable ``token_env`` and is never logged. Follows ``next`` + links on the same origin, so a second match on page two still counts. + """ + + read_method: ReadMethod = "api_readback" + + def __init__( + self, + profile: FhirSearchProfile, + base_url: str, + *, + token: Optional[str] = None, + token_env: Optional[str] = None, + verify_tls: bool = True, + timeout: float = 20.0, + client: Any = None, + ) -> None: + self.profile = profile + self.base_url = base_url.rstrip("/") + self._token = ( + token + if token is not None + else (os.environ.get(token_env) if token_env else None) + ) + self._verify = verify_tls + self._timeout = timeout + self._client = client + + def _get(self, url: str, params: Optional[Mapping[str, str]]) -> Any: + headers = fhir_read_headers() + if self._token: + headers["Authorization"] = f"Bearer {self._token}" + if self._client is not None: + return self._client.get(url, params=params, headers=headers) + import httpx + + with httpx.Client(verify=self._verify, timeout=self._timeout) as client: + return client.get(url, params=params, headers=headers) + + def read(self, key: str) -> ReadResult: + from urllib.parse import urlsplit + + url: Optional[str] = f"{self.base_url}/{self.profile.resource}" + params: Optional[dict[str, str]] = { + self.profile.key_param: self.profile.key_template.format(key=key) + } + origin = urlsplit(self.base_url)[:2] + matches: list[dict[str, Any]] = [] + digest = hashlib.sha256() + pages = 0 + seen = 0 + declared_total: Optional[int] = None + while url is not None: + pages += 1 + if pages > 20: + return ReadResult("unreachable") + try: + response = self._get(url, params) + except Exception: # noqa: BLE001 - any transport failure + return ReadResult("unreachable") + if not 200 <= int(getattr(response, "status_code", 0)) < 300: + return ReadResult("unreachable") + body = response.content if hasattr(response, "content") else b"" + digest.update(body if isinstance(body, bytes) else str(body).encode()) + try: + bundle = json.loads(body) + except (TypeError, ValueError): + return ReadResult("unreachable") + if not isinstance(bundle, dict) or bundle.get("resourceType") != "Bundle": + return ReadResult("unreachable") + entries = bundle.get("entry", []) + if not isinstance(entries, list): + return ReadResult("unreachable") + for entry in entries: + resource = entry.get("resource") if isinstance(entry, dict) else None + if not isinstance(resource, dict): + return ReadResult("unreachable") + if resource.get("resourceType") == "OperationOutcome": + # Missing-evidence class: an error outcome means the search + # is partial, so its matches prove nothing. + issues = resource.get("issue") or [] + if not isinstance(issues, list) or any( + not isinstance(i, dict) + or i.get("severity") not in ("information", "warning") + for i in issues + ): + return ReadResult("unreachable") + continue + if resource.get("resourceType") != self.profile.resource: + return ReadResult("unreachable") + seen += 1 + if _text(extract_path(resource, self.profile.key_path)) == key: + matches.append(resource) + total = bundle.get("total") + if total is not None: + if type(total) is not int or total < 0: + return ReadResult("unreachable") + if declared_total is not None and total != declared_total: + # Pages that disagree on the total can hide a partial search. + return ReadResult("unreachable") + declared_total = total + try: + url = next_page_url(bundle) + except ValueError: + return ReadResult("unreachable") + if url is not None and urlsplit(url)[:2] != origin: + return ReadResult("unreachable") + params = None + evidence = digest.hexdigest() + if declared_total is not None and declared_total != seen: + # The server says it matched more (or fewer) than it returned. + return ReadResult("unreachable", evidence_sha256=evidence) + if not matches: + return ReadResult("not_found", evidence_sha256=evidence) + if len(matches) > 1: + return ReadResult("ambiguous", evidence_sha256=evidence) + record = matches[0] + fields = { + field_id: _text(extract_path(record, spec.path)) + for field_id, spec in self.profile.fields.items() + } + return ReadResult( + "found", + fields=fields, + evidence_sha256=evidence, + date_orders={ + field_id: spec.date_order + for field_id, spec in self.profile.fields.items() + }, + ) + + +__all__ = [ + "FhirSearchProfile", + "FhirSearchReader", + "FieldPath", + "ReadResult", + "ReadStatus", + "Reader", +] diff --git a/packages/flow/openadapt_flow/handoffs/registry.py b/packages/flow/openadapt_flow/handoffs/registry.py new file mode 100644 index 0000000000..d55420cd3e --- /dev/null +++ b/packages/flow/openadapt_flow/handoffs/registry.py @@ -0,0 +1,45 @@ +"""Which handoff ledgers a run used, so its receipt can carry their lines. + +A deferred claim check and ``HandoffLedger.send`` note their ledger here +while the run is going. The receipt hook (``receipt_record.receipt_after_run``) +reads the noted ledgers, plus any listed in ``OPENADAPT_HANDOFF_LEDGERS`` +(directories separated by the OS path separator), and attaches the lines of +the handoffs that belong to the run. Process-local: a receipt written by a +later process names its ledgers through the variable. +""" + +from __future__ import annotations + +import os +from pathlib import Path +from typing import Mapping, Optional + +from openadapt_flow.handoffs.ledger import HandoffLedger + +ENV = "OPENADAPT_HANDOFF_LEDGERS" +_NOTED: list[Path] = [] + + +def note_ledger(directory: str | Path) -> None: + path = Path(directory).resolve() + if path not in _NOTED: + _NOTED.append(path) + + +def forget() -> None: + """Clear the noted ledgers (tests).""" + _NOTED.clear() + + +def ledgers_for(env: Optional[Mapping[str, str]] = None) -> list[HandoffLedger]: + env = os.environ if env is None else env + paths = list(_NOTED) + for item in (env.get(ENV) or "").split(os.pathsep): + if item.strip(): + path = Path(item.strip()).expanduser().resolve() + if path not in paths: + paths.append(path) + return [HandoffLedger(path) for path in paths if path.is_dir()] + + +__all__ = ["ENV", "forget", "ledgers_for", "note_ledger"] diff --git a/packages/flow/openadapt_flow/receipt_record.py b/packages/flow/openadapt_flow/receipt_record.py index ad88994ecf..c0b46e888e 100644 --- a/packages/flow/openadapt_flow/receipt_record.py +++ b/packages/flow/openadapt_flow/receipt_record.py @@ -443,9 +443,13 @@ def write_receipt_record( flow_version: Optional[str] = None, env: Optional[Mapping[str, str]] = None, expected_report: Optional["RunReport"] = None, + handoff_ledgers: Sequence[Any] = (), ) -> dict[str, Any]: """Write ``receipt.json`` and ``receipt.private.json`` for a finished run. + ``handoff_ledgers`` (``openadapt_flow.handoffs.HandoffLedger``): the run's + handoffs in them go on the receipt as counterparty confirmation lines. + Idempotent: an existing receipt over the same report bytes is kept. A receipt over different bytes is never silently replaced. """ @@ -453,7 +457,13 @@ def write_receipt_record( with mutation_lock(run_dir): return _write_locked( - Path(run_dir), signer, home, flow_version, env, expected_report + Path(run_dir), + signer, + home, + flow_version, + env, + expected_report, + handoff_ledgers, ) @@ -464,6 +474,7 @@ def _write_locked( flow_version: Optional[str], env: Optional[Mapping[str, str]], expected_report: Optional["RunReport"], + handoff_ledgers: Sequence[Any] = (), ) -> dict[str, Any]: from openadapt_types import receipt as r @@ -500,7 +511,8 @@ def _write_locked( ) if not isinstance(report, dict): raise ReceiptRecordError("report_unreadable", "report.json is not an object") - if report.get("transaction_outcome") == "SAVED_AWAITING_CHECK": + awaiting = report.get("transaction_outcome") == "SAVED_AWAITING_CHECK" + if awaiting and not handoff_ledgers: raise ReceiptRecordError("readback_pending") digest = hashlib.sha256(raw).hexdigest() if flow_version is None: @@ -517,6 +529,25 @@ def _write_locked( run_dir=run_dir, evidence_key=evidence_key, ) + placed: list[Any] = [] + if handoff_ledgers: + from openadapt_flow.handoffs.line import ( + attach_confirmations, + handoffs_for_run, + place, + ) + + handoffs = handoffs_for_run(report, list(handoff_ledgers), run_dir) + if handoffs: + try: + placed = place(statement, handoffs) + statement, openings = attach_confirmations( + statement, openings, handoffs + ) + except ValueError as exc: + raise ReceiptRecordError("handoff_unplaceable", str(exc)) from exc + if awaiting: + statement = _awaiting_counterparty(statement, placed) kid = r.key_id(chosen.public_raw()) entry = chosen.registry_entry() registry = [r.RoleKey(kid, entry["public_key"], "this_computer")] @@ -587,6 +618,10 @@ def _write_locked( _write(private, r.private_openings(envelope, openings), private=True) _write(out, envelope) write_public_card(run_dir, envelope, openings) + if placed: + from openadapt_flow.handoffs.followup import record_signed + + record_signed(run_dir, RECEIPT_FILE, placed) return envelope @@ -645,6 +680,39 @@ def write_public_card( return path +AWAITING_REASON = "awaiting_counterparty" + + +def _awaiting_counterparty( + statement: dict[str, Any], placed: Sequence[Any] +) -> dict[str, Any]: + """A receipt for a run whose only unsettled writes are handoffs that went + out and await the other party (permissive-default guarded). + + Allowed only when every unverified write line is a declared handoff line + still in the ``sent`` state; anything else refuses ``readback_pending``. + The outcome is never VERIFIED: it is UNKNOWN with reason + ``awaiting_counterparty``, and follow-ups record the settlement.""" + lines = statement["predicate"].get("lines", []) + pending = [line for line in lines if line["check"] != "confirmed"] + sent_steps = {h.step for h in placed if h.step is not None and h.state == "sent"} + if ( + not pending + or any(line["check"] == "refuted" for line in pending) + or any(line["step"] not in sent_steps for line in pending) + ): + raise ReceiptRecordError("readback_pending") + predicate = statement["predicate"] + return { + **statement, + "predicate": { + **predicate, + "outcome": "UNKNOWN", + "reason_code": AWAITING_REASON, + }, + } + + def save_settled_report(run_dir: Path, report: "RunReport") -> "RunReport": """Save the final read-back before issuing the pooled item's opted-in receipt.""" report.save(run_dir) @@ -677,10 +745,15 @@ def receipt_after_run( if not (Path(run_dir) / "report.json").is_file(): return None try: + from openadapt_flow.handoffs.registry import ledgers_for from openadapt_flow.offline_seal import seal_home write_receipt_record( - Path(run_dir), home=seal_home(env), env=env, expected_report=expected_report + Path(run_dir), + home=seal_home(env), + env=env, + expected_report=expected_report, + handoff_ledgers=ledgers_for(env), ) except ImportError: return "receipt not written: openadapt-types is older than 0.25" diff --git a/packages/flow/openadapt_flow/runtime/effects/deferred_report.py b/packages/flow/openadapt_flow/runtime/effects/deferred_report.py index 62cd0bb3e2..3fe45ab247 100644 --- a/packages/flow/openadapt_flow/runtime/effects/deferred_report.py +++ b/packages/flow/openadapt_flow/runtime/effects/deferred_report.py @@ -43,7 +43,7 @@ from dataclasses import dataclass from datetime import datetime, timedelta, timezone from pathlib import Path -from typing import Any, Iterator, Literal, Mapping, Optional +from typing import Any, Callable, Iterator, Literal, Mapping, Optional from pydantic import BaseModel, ConfigDict, Field, model_validator @@ -137,6 +137,11 @@ class PendingCheck(BaseModel): UI_READBACK_FORMAT = "ui-readback" +#: Hears each waiting entry a report mentions: ``(entry, row, n)``, or +#: ``(entry, None, 0)`` when the entry expired. +SettleObserver = Callable[["PendingCheck", Optional[ReportRow], int], None] + + @dataclass(frozen=True) class Settlement: id: str @@ -359,6 +364,7 @@ def settle( *, issued_at: Optional[datetime] = None, now: Optional[datetime] = None, + observer: Optional[SettleObserver] = None, ) -> list[Settlement]: """Expire overdue entries, then settle waiting ones against a report. @@ -368,6 +374,13 @@ def settle( or the caller's report time for a CSV or text report), and only entries waiting on that exact report format. ``report_text`` None only expires entries. + + ``observer``, when given, hears about every waiting entry the report + mentions, including a row that is still pending (a 999 ``A``, a + 277CA ``A1``), which settles nothing: ``observer(entry, row, n)`` + with ``n`` the number of waiting entries on that key, and + ``observer(entry, None, 0)`` for an entry that expired. It never + changes what settles (:mod:`openadapt_flow.handoffs.payer`). """ moment = now or _now() @@ -398,6 +411,7 @@ def settle( entry.id, "reconciliation_required", "deadline", reason ) ) + _notify(observer, entry, None, 0) else: still.append(entry) if report_text is None or fmt is None: @@ -424,6 +438,9 @@ def settle( by_digest.setdefault(entry.key_digest, []).append(entry) for digest, entries in by_digest.items(): row = rows.get(digest) + if row is not None: + for entry in entries: + _notify(observer, entry, row, len(entries)) if row is None or row.status == "pending": continue if len(entries) > 1: @@ -459,6 +476,23 @@ def settle( return settled +def _notify( + observer: Optional[SettleObserver], + entry: PendingCheck, + row: Optional[ReportRow], + count: int, +) -> None: + """Tell the observer, which never changes what settles: its failure is + swallowed (it can catch up later from the settled entries).""" + + if observer is None: + return + try: + observer(entry, row, count) + except Exception: # noqa: BLE001 - an observer must never stop a settlement + return + + def _issued_after(stamp: datetime, created: datetime) -> bool: """Whether a report issued at ``stamp`` can speak about a save made at ``created``. A report time without a zone (X12) gets the clock slack.""" @@ -584,6 +618,7 @@ def verify( unavailable=True, assurance=UNCHECKED, ) + _record_handoff(self.ledger, entry) return EffectVerdict( verdict=Verdict.INDETERMINATE, kind=expected.kind, @@ -597,6 +632,23 @@ def verify( ) +def _record_handoff(ledger: PendingLedger, entry: PendingCheck) -> None: + """The claim is now a handoff (``sent``), so the run's receipt can carry + its line. Never changes the check: a failure here is ignored, and + ``handoff list`` adds the handoff later from the pending entry.""" + + try: + from openadapt_flow.handoffs import payer + from openadapt_flow.handoffs.registry import note_ledger + + if entry.report_format in payer.COUNTERPARTY_FORMATS: + handoffs = payer.handoff_ledger(ledger) + handoffs.adopt(payer.as_handoff(entry)) + note_ledger(handoffs.directory) + except Exception: # noqa: BLE001 - bookkeeping must never fail the save + return + + def build_deferred_report_verifier( spec: DeferredReportSpec, params: Optional[Mapping[str, object]] = None ) -> DeferredReportVerifier: @@ -615,12 +667,13 @@ def settle_report_file( fmt: ReportFormat, *, issued_at: Optional[datetime] = None, + observer: Optional[SettleObserver] = None, ) -> list[Settlement]: """Settle against a report file. A CSV or text report needs its issue time (``issued_at``); an X12 report carries its own.""" text = Path(report_path).read_text(encoding="utf-8", errors="strict") - return ledger.settle(text, fmt, issued_at=issued_at) + return ledger.settle(text, fmt, issued_at=issued_at, observer=observer) __all__ = [ diff --git a/packages/flow/public-artifacts.json b/packages/flow/public-artifacts.json index 32c9b4bad1..311f27c559 100644 --- a/packages/flow/public-artifacts.json +++ b/packages/flow/public-artifacts.json @@ -803,6 +803,8 @@ "benchmark/grounding_eval/results_sweep.json", "benchmark/halt_cleanup/results/openemr.json", "benchmark/handoff_real_run/2026-11-21/evidence.json", + "benchmark/handoff_receiver/docker-compose.yml", + "benchmark/handoff_receiver/results/2026-11-21.json", "benchmark/harness2_scorer/evidence/base/results.json", "benchmark/harness2_scorer/evidence/harness2/results.json", "benchmark/harness2_scorer/evidence/harness2_readback/results.json", diff --git a/packages/flow/tests/fixtures/handoffs/fhir-patient-intake.yaml b/packages/flow/tests/fixtures/handoffs/fhir-patient-intake.yaml new file mode 100644 index 0000000000..378e16647f --- /dev/null +++ b/packages/flow/tests/fixtures/handoffs/fhir-patient-intake.yaml @@ -0,0 +1,18 @@ +# Counterparty profile: read a referral's patient back from a receiving +# clinic's FHIR R4 server. Data, not code: any FHIR R4 server that keeps the +# sender's reference as the patient's PT identifier reads the same way. +# +# The key is the sender's referral id, which the receiver records as the +# patient's external identifier (identifier type PT). Every returned record +# is checked for that exact value (key_path), so a server that ignores the +# search parameter can't make a wrong record "found". +resource: Patient +key_param: identifier +key_path: identifier[system=http://terminology.hl7.org/CodeSystem/v2-0203].value +counterparty: receiving clinic (synthetic) +system_kind: ehr +fields: + given_name: {path: "name[use=official].given", kind: text} + family_name: {path: "name[use=official].family", kind: text} + birth_date: {path: birthDate, kind: date} + sex: {path: gender, kind: code} diff --git a/packages/flow/tests/test_handoff_receipts.py b/packages/flow/tests/test_handoff_receipts.py new file mode 100644 index 0000000000..fa8b406ac3 --- /dev/null +++ b/packages/flow/tests/test_handoff_receipts.py @@ -0,0 +1,464 @@ +"""Receipts carry handoff lines, and follow-up receipts record later changes. + +A real run through the replayer saves a claim with a deferred check; the +after-run hook writes the receipt with the claim's ``sent`` line. A referral +handoff of the same run is read back later, and ``sign_updates`` signs a +follow-up for each change. ``verify_chain`` checks the chain. Synthetic data. +""" + +from __future__ import annotations + +import base64 +import json +from datetime import datetime, timezone +from pathlib import Path + +import pytest + +r = pytest.importorskip("openadapt_types.receipt") +if not hasattr(r, "verify_chain"): + pytest.skip("openadapt-types without follow-up receipts", allow_module_level=True) +pytest.importorskip("cryptography") + +from openadapt_flow.handoffs import followup, intake, registry # noqa: E402 +from openadapt_flow.handoffs.ledger import HandoffLedger # noqa: E402 +from openadapt_flow.handoffs.payer import SettleRecorder, handoff_ledger # noqa: E402 +from openadapt_flow.handoffs.readers import ReadResult # noqa: E402 +from openadapt_flow.ir import ( # noqa: E402 + ActionKind, + Postcondition, + PostconditionKind, + Step, + Workflow, +) +from openadapt_flow.runtime.effects.deferred_report import ( # noqa: E402 + DeferredReportVerifier, + PendingLedger, +) +from openadapt_flow.runtime.replayer import Replayer # noqa: E402 +from tests.test_deferred_report import ( # noqa: E402 + FMT_277, + _claim_effect, + _spec, + ack_277ca, +) +from tests.test_replayer import FakeBackend, FakeVision, Match # noqa: E402 + +FIELDS = { + "family_name": ("Quill", "text"), + "birth_date": ("1984-03-09", "date"), +} + + +class Fake: + read_method = "api_readback" + + def __init__(self, result: ReadResult) -> None: + self.result = result + + def read(self, key: str) -> ReadResult: + return self.result + + +def _found(**changes: str) -> ReadResult: + fields = {"family_name": "Quill", "birth_date": "1984-03-09", **changes} + return ReadResult("found", fields=fields) + + +@pytest.fixture +def env(tmp_path, monkeypatch): + registry.forget() + monkeypatch.setenv("OPENADAPT_SEAL_HOME", str(tmp_path / "seal")) + monkeypatch.delenv("OPENADAPT_RECEIPT", raising=False) + monkeypatch.delenv(registry.ENV, raising=False) + yield {"OPENADAPT_SEAL_HOME": str(tmp_path / "seal")} + registry.forget() + + +def _run(tmp_path: Path) -> Path: + workflow = Workflow( + name="claim", + steps=[ + Step( + id="submit", + intent="submit claim", + action=ActionKind.KEY, + key="Enter", + risk="irreversible", + expect=[ + Postcondition( + kind=PostconditionKind.TEXT_PRESENT, + text="Submitted", + timeout_s=0.2, + ) + ], + effects=[_claim_effect()], + ) + ], + ) + vision = FakeVision() + vision.text_results = { + "Submitted": Match(point=(50, 10), region=(30, 5, 40, 10), confidence=0.9) + } + bundle = tmp_path / "bundle" + (bundle / "templates").mkdir(parents=True) + run_dir = tmp_path / "run" + verifier = DeferredReportVerifier(_spec(tmp_path), "CLM-1001") + report = Replayer( + FakeBackend(), vision=vision, effect_verifier=verifier, poll_interval_s=0.01 + ).run(workflow, bundle_dir=bundle, run_dir=run_dir) + assert report.transaction_outcome == "SAVED_AWAITING_CHECK" + return run_dir + + +def _registry(tmp_path: Path): + from openadapt_flow.receipt_record import local_registry + + return local_registry(tmp_path / "seal") + + +def _payload(path: Path) -> dict: + envelope = json.loads(path.read_text()) + return json.loads(base64.b64decode(envelope["payload"])) + + +def test_a_real_run_writes_a_receipt_that_carries_the_claims_line(tmp_path, env): + from openadapt_flow.receipt_record import receipt_after_run, verify_run_receipt + + run_dir = _run(tmp_path) + note = receipt_after_run(run_dir, env) + assert note and note.startswith("receipt:"), note + confirmations = _payload(run_dir / "receipt.json")["predicate"]["confirmations"] + assert [ + (c["for_step"], c["system_kind"], c["read_method"], c["state"]) + for c in confirmations + ] == [(0, "payer_portal", "acknowledgment_message", "sent")] + result = verify_run_receipt(run_dir, _registry(tmp_path)) + assert result.ok, (result.reason, result.detail) + assert result.confirmation_lines[0].startswith("Sent to the other party") + # Awaiting the other party: signed, and never VERIFIED. + predicate = _payload(run_dir / "receipt.json")["predicate"] + assert (predicate["outcome"], predicate["reason_code"]) == ( + "UNKNOWN", + "awaiting_counterparty", + ) + assert result.outcome != "VERIFIED" + sidecar = run_dir / followup.SIDECAR + assert sidecar.stat().st_mode & 0o777 == 0o600 + assert "CLM-1001" not in sidecar.read_text() + + +def test_a_pending_receipt_is_only_for_sent_handoff_lines(): + """permissive-default guarded: any other unsettled write refuses.""" + from types import SimpleNamespace + + from openadapt_flow.receipt_record import ReceiptRecordError, _awaiting_counterparty + + def statement(*checks): + return { + "predicate": { + "outcome": "UNKNOWN", + "reason_code": "x", + "lines": [{"step": i, "check": c} for i, c in enumerate(checks)], + } + } + + sent = SimpleNamespace(step=0, state="sent") + ok = _awaiting_counterparty(statement("not_checked", "confirmed"), [sent]) + assert ok["predicate"]["outcome"] == "UNKNOWN" + assert ok["predicate"]["reason_code"] == "awaiting_counterparty" + # A handoff line plus another unverified write refuses. + with pytest.raises(ReceiptRecordError, match="readback_pending"): + _awaiting_counterparty(statement("not_checked", "not_checked"), [sent]) + # A pending write with no handoff line refuses. + with pytest.raises(ReceiptRecordError, match="readback_pending"): + _awaiting_counterparty(statement("not_checked"), []) + # A handoff already answered is not "sent": refuses. + answered = SimpleNamespace(step=0, state="recorded_differently") + with pytest.raises(ReceiptRecordError, match="readback_pending"): + _awaiting_counterparty(statement("not_checked"), [answered]) + # A refuted write refuses. + with pytest.raises(ReceiptRecordError, match="readback_pending"): + _awaiting_counterparty(statement("refuted"), [sent]) + + +def test_a_run_without_handoffs_has_a_receipt_without_confirmations(tmp_path, env): + from openadapt_flow.receipt_record import receipt_after_run + + run_dir = _run(tmp_path) + registry.forget() + # The claim's ledger isn't noted or named: the pending write has no + # handoff line, so the run awaits its check with no receipt yet. + note = receipt_after_run(run_dir, env) + assert note == "receipt not written: readback_pending" + assert not (run_dir / "receipt.json").exists() + + +def test_follow_ups_record_each_change_and_verify_as_a_chain(tmp_path, env): + from openadapt_flow.offline_seal import signer_for + from openadapt_flow.receipt_record import receipt_after_run + + run_dir = _run(tmp_path) + referrals = HandoffLedger(tmp_path / "referrals") + referral = referrals.send( + "REF-1", + FIELDS, + counterparty="receiving clinic", + system_kind="ehr", + follow_up_hours=24, + run_id=str(run_dir), + step=0, + ) + receipt_after_run(run_dir, env) + states = [ + c["state"] + for c in _payload(run_dir / "receipt.json")["predicate"]["confirmations"] + ] + assert sorted(states) == ["sent", "sent"] + signer = signer_for(tmp_path / "seal") + claims = handoff_ledger(PendingLedger(tmp_path / "ledger")) + ledgers = [claims, referrals] + + # Nothing changed yet: no update. + assert followup.sign_updates(run_dir, ledgers, signer=signer) is None + + # The referral is recorded as intended: update 1 carries only its line. + intake.check(referrals, referral.id, "REF-1", Fake(_found())) + first = followup.sign_updates(run_dir, ledgers, signer=signer) + assert first is not None and first.name == "receipt.update-1.json" + p1 = _payload(first)["predicate"] + assert [c["state"] for c in p1["confirmations"]] == ["recorded_as_intended"] + original = _payload(run_dir / "receipt.json") + assert p1["follows"]["sequence"] == 1 + assert p1["lines"] == original["predicate"]["lines"] + + # The payer acknowledges the claim, and the referral now reads + # differently: update 2 carries both changes. + pending = PendingLedger(tmp_path / "ledger") + pending.settle( + ack_277ca(datetime.now(timezone.utc).replace(tzinfo=None)), + FMT_277, + observer=SettleRecorder(pending, "x12-277ca", None), + ) + intake.check(referrals, referral.id, "REF-1", Fake(_found(birth_date="1984-03-10"))) + second = followup.sign_updates(run_dir, ledgers, signer=signer) + assert second is not None and second.name == "receipt.update-2.json" + assert sorted( + c["state"] for c in _payload(second)["predicate"]["confirmations"] + ) == [ + "acknowledged", + "recorded_differently", + ] + assert followup.sign_updates(run_dir, ledgers, signer=signer) is None + + chain = followup.verify_history(run_dir, _registry(tmp_path)) + assert chain.ok, (chain.reason, chain.detail) + assert len(chain.lines) == 5 + assert all(line.startswith("Sent to the other party") for line in chain.lines[:2]) + assert [line.split(":")[0] for line in chain.lines[2:]] == [ + "Update 1", + "Update 2", + "Update 2", + ] + assert chain.lines[2].startswith("Update 1: Confirmed in the other party's system") + assert any("1 field differs" in line for line in chain.lines[3:]) + assert any("Acknowledged by the other party" in line for line in chain.lines[3:]) + + +def _chain_setup(tmp_path, env): + from openadapt_flow.offline_seal import signer_for + from openadapt_flow.receipt_record import receipt_after_run + + run_dir = _run(tmp_path) + referrals = HandoffLedger(tmp_path / "referrals") + referral = referrals.send( + "REF-1", + FIELDS, + counterparty="receiving clinic", + system_kind="ehr", + follow_up_hours=24, + run_id=str(run_dir), + step=0, + ) + receipt_after_run(run_dir, env) + signer = signer_for(tmp_path / "seal") + intake.check(referrals, referral.id, "REF-1", Fake(_found())) + followup.sign_updates(run_dir, [referrals], signer=signer) + intake.check(referrals, referral.id, "REF-1", Fake(_found(birth_date="1984-03-10"))) + followup.sign_updates(run_dir, [referrals], signer=signer) + return run_dir, signer + + +def test_a_broken_chain_is_refused(tmp_path, env): + run_dir, signer = _chain_setup(tmp_path, env) + registry_ = _registry(tmp_path) + original = json.loads((run_dir / "receipt.json").read_text()) + one = json.loads((run_dir / "receipt.update-1.json").read_text()) + two = json.loads((run_dir / "receipt.update-2.json").read_text()) + assert r.verify_chain(original, [one, two], registry_).ok + assert r.verify_chain(original, [two, one], registry_).reason == "out_of_sequence" + assert r.verify_chain(original, [two], registry_).reason == "out_of_sequence" + assert r.verify_chain(one, [], registry_).reason == "original_is_follow_up" + kid = r.key_id(signer.public_raw()) + + def resign(statement): + return r.sign_statement(statement, [(kid, signer.sign)]) + + wrong = _payload(run_dir / "receipt.update-1.json") + wrong["predicate"]["follows"]["receipt"]["sha256"] = "0" * 64 + assert r.verify_chain(original, [resign(wrong)], registry_).reason == ( + "wrong_original" + ) + changed = _payload(run_dir / "receipt.update-1.json") + changed["predicate"]["model_calls"] = 7 + assert r.verify_chain(original, [resign(changed)], registry_).reason == ( + "changed_original" + ) + tampered = dict(one, payload=two["payload"]) + assert r.verify_chain(original, [tampered], registry_).reason == "update_refused" + empty = _payload(run_dir / "receipt.update-1.json") + empty["predicate"]["confirmations"] = [] + with pytest.raises(ValueError, match="at least one confirmation"): + resign(empty) + + +def test_sign_updates_refuses_a_receipt_it_cannot_verify_or_did_not_sign(tmp_path, env): + from openadapt_flow.offline_seal import signer_for + + run_dir, signer = _chain_setup(tmp_path, env) + referrals = HandoffLedger(tmp_path / "referrals") + (referral,) = referrals.entries() + intake.check(referrals, referral.id, "REF-1", Fake(_found())) + receipt = run_dir / "receipt.json" + good = receipt.read_text() + envelope = json.loads(good) + other = _payload(receipt) + other["predicate"]["model_calls"] = 9 + receipt.write_text( + json.dumps( + dict( + envelope, + payload=r.sign_statement( + other, [(r.key_id(signer.public_raw()), signer.sign)] + )["payload"], + ) + ) + ) + with pytest.raises(ValueError, match="does not verify"): + followup.sign_updates(run_dir, [referrals], signer=signer) + receipt.write_text(good) + stranger = signer_for(tmp_path / "stranger-seal") + with pytest.raises(ValueError, match="does not verify"): + followup.sign_updates(run_dir, [referrals], signer=stranger) + assert not (run_dir / "receipt.update-3.json").exists() + # An update past a gap is never ignored: the history fails closed. + one_path = run_dir / "receipt.update-1.json" + saved = one_path.read_text() + one_path.rename(run_dir / "receipt.update-9.json") + with pytest.raises(ValueError, match="skip a number"): + followup.verify_history(run_dir, _registry(tmp_path)) + with pytest.raises(ValueError, match="skip a number"): + followup.sign_updates(run_dir, [referrals], signer=signer) + (run_dir / "receipt.update-9.json").unlink() + one_path.write_text(saved) + (run_dir / "receipt.update-x.json").write_text("{}") + with pytest.raises(ValueError, match="unexpected update file"): + followup.updates(run_dir) + (run_dir / "receipt.update-x.json").unlink() + # A report that isn't the one the receipt signed never picks handoffs. + report = run_dir / "report.json" + signed_report = report.read_bytes() + report.write_bytes(signed_report + b" ") + with pytest.raises(ValueError, match="not the report the receipt signed"): + followup.sign_updates(run_dir, [referrals], signer=signer) + report.write_bytes(signed_report) + # A signed update that went missing (with its openings) breaks the history. + two = run_dir / "receipt.update-2.json" + two_private = run_dir / "receipt.update-2.private.json" + kept = two.read_bytes(), two_private.read_bytes() + two.unlink() + two_private.unlink() + with pytest.raises(ValueError, match="don't match the record"): + followup.verify_history(run_dir, _registry(tmp_path)) + two.write_bytes(kept[0]) + two_private.write_bytes(kept[1]) + # One signer at a time: a held lock refuses, and signs nothing. + lock = run_dir / ".receipt-update.lock" + lock.write_text("") + with pytest.raises(ValueError, match="another signer holds"): + followup.sign_updates(run_dir, [referrals], signer=signer) + lock.unlink() + # A publication interrupted after its files but before the sidecar is + # completed by the next call, never left as a broken history. + import json as _json + + sidecar = run_dir / followup.SIDECAR + data = _json.loads(sidecar.read_text()) + last = data["records"].pop() + sidecar.write_text(_json.dumps(data)) + (run_dir / ".receipt-update.pending.json").write_text( + _json.dumps( + { + "file": last["file"], + "private": last["file"].replace(".json", ".private.json"), + "lines": last["lines"], + } + ) + ) + with pytest.raises(ValueError): # the history doesn't verify meanwhile + followup.verify_history(run_dir, _registry(tmp_path)) + followup._finish_pending(run_dir, _registry(tmp_path)) # what the next call runs + assert not (run_dir / ".receipt-update.pending.json").exists() + assert followup.verify_history(run_dir, _registry(tmp_path)).ok + # A tampered update already in the chain is never extended. + update = run_dir / "receipt.update-2.json" + good_update = update.read_text() + one = json.loads((run_dir / "receipt.update-1.json").read_text()) + update.write_text(json.dumps(dict(json.loads(good_update), payload=one["payload"]))) + with pytest.raises(ValueError, match="does not verify"): + followup.sign_updates(run_dir, [referrals], signer=signer) + assert not (run_dir / "receipt.update-3.json").exists() + + +def test_handoff_list_signs_updates_and_shows_the_history(tmp_path, env, capsys): + from openadapt_flow.__main__ import main + from openadapt_flow.receipt_record import receipt_after_run + + run_dir = _run(tmp_path) + referrals = HandoffLedger(tmp_path / "referrals") + referral = referrals.send( + "REF-1", + FIELDS, + counterparty="receiving clinic", + system_kind="ehr", + follow_up_hours=24, + run_id=str(run_dir), + step=0, + ) + receipt_after_run(run_dir, env) + intake.check(referrals, referral.id, "REF-1", Fake(_found())) + argv = [ + "handoff", + "list", + "--ledger", + str(referrals.directory), + "--run", + str(run_dir), + ] + assert main([*argv, "--sign-updates"]) == 0 + out = capsys.readouterr().out + assert "Signed receipt.update-1.json" in out + assert "Signed history (receipt and 1 update(s), verified)" in out + assert "Update 1: Confirmed in the other party's system" in out + assert main(argv) == 0 + assert "Signed receipt.update" not in capsys.readouterr().out + # A history that no longer verifies fails the command, and nothing new + # is signed on top of it. + update = run_dir / "receipt.update-1.json" + envelope = json.loads(update.read_text()) + update.write_text(json.dumps(dict(envelope, signatures=[]))) + assert main(argv) == 1 + assert "Signed history: not verified" in capsys.readouterr().out + intake.check(referrals, referral.id, "REF-1", Fake(_found(birth_date="1984-03-10"))) + assert main([*argv, "--sign-updates"]) == 2 + assert not (run_dir / "receipt.update-2.json").exists() diff --git a/packages/flow/tests/test_handoffs.py b/packages/flow/tests/test_handoffs.py new file mode 100644 index 0000000000..0f3e8cf125 --- /dev/null +++ b/packages/flow/tests/test_handoffs.py @@ -0,0 +1,701 @@ +"""Handoffs and counterparty confirmations: unit tests. + +Two producers over one mechanism: the deferred claim check seen as payer +handoffs (synthetic X12 999 and 277CA), and a field read-back from the +receiving system (a fake reader here; the real OpenEMR receiver is in +``test_handoffs_live_openemr.py``). Synthetic data only. +""" + +from __future__ import annotations + +import json +from datetime import datetime, timedelta, timezone +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from openadapt_flow.handoffs import intake, line, payer +from openadapt_flow.handoffs.ledger import HandoffLedger, LedgerError +from openadapt_flow.handoffs.readers import ( + FhirSearchProfile, + FhirSearchReader, + ReadResult, +) +from openadapt_flow.reports.parse import ReportFormat +from openadapt_flow.runtime.effects.deferred_report import PendingLedger +from tests.test_deferred_report import ( + ACK_277CA, + ACK_999, + FMT_277, + HASH, + SETTLE_AT, + T0, +) + +FMT_999 = ReportFormat(format="x12-999") +LATER = SETTLE_AT + timedelta(days=5) + + +# -- payer acknowledgments -------------------------------------------------------- + + +def _claims(tmp_path: Path, fmt: ReportFormat, keys: list[str], hours: float = 48): + pending = PendingLedger(tmp_path / "deferred") + entries = { + key: pending.add( + key=key, + effect_contract_hash=HASH, + fmt=fmt, + describe=f"payer {fmt.format}", + deadline_hours=hours, + now=T0, + ) + for key in keys + } + return pending, entries + + +def _settle(pending: PendingLedger, text, fmt, now=SETTLE_AT): + sha = None if text is None else "0" * 64 + recorder = payer.SettleRecorder(pending, fmt.format if fmt else "", sha) + settled = pending.settle(text, fmt, now=now, observer=recorder) + return settled, payer.handoff_ledger(pending) + + +def _h(handoffs: HandoffLedger, entry): + return handoffs.get(payer.handoff_id(entry)) + + +def test_a_submitted_claim_is_sent_with_follow_up_due_at_the_deadline(tmp_path): + pending, entries = _claims(tmp_path, FMT_277, ["CLM-1001"]) + handoffs = payer.sync(pending) + h = _h(handoffs, entries["CLM-1001"]) + assert h.state == "sent" + assert h.follow_up_due == "2026-10-20T06:00:00Z" + assert h.status(SETTLE_AT) == "waiting" + assert h.status(LATER) == "needs_follow_up" + assert h.system_kind == "payer_portal" + assert "CLM-1001" not in (handoffs.directory / f"{h.id[8:]}.json").read_text() + + +def test_277ca_received_accepted_and_rejected(tmp_path): + pending, e = _claims(tmp_path, FMT_277, ["CLM-1001", "CLM-1002", "CLM-1003"]) + settled, handoffs = _settle(pending, ACK_277CA, FMT_277) + # The deferred check settles exactly as before. + assert {s.id: s.state for s in settled} == { + e["CLM-1001"].id: "verified", + e["CLM-1002"].id: "reconciliation_required", + } + accepted = _h(handoffs, e["CLM-1001"]) + rejected = _h(handoffs, e["CLM-1002"]) + received = _h(handoffs, e["CLM-1003"]) + assert (accepted.state, accepted.last.counterparty_accepted) == ( + "acknowledged", + True, + ) + assert accepted.status(LATER) == "done" + assert (rejected.state, rejected.last.reason) == ( + "sent", + "rejected_by_counterparty", + ) + assert rejected.status(SETTLE_AT) == "needs_follow_up" + assert (received.state, received.last.reason) == ("acknowledged", None) + assert received.status(SETTLE_AT) == "waiting" + assert received.status(LATER) == "needs_follow_up" + for h in (accepted, rejected, received): + assert h.last.read_method == "x12_277ca" + assert h.state != "recorded_as_intended" # status only, never fields + + +def test_999_accepted_file_is_acknowledged_and_rejected_file_is_not(tmp_path): + pending, e = _claims(tmp_path, FMT_999, ["17:0001", "17:0002"]) + _, handoffs = _settle(pending, ACK_999, FMT_999) + ok = _h(handoffs, e["17:0001"]) + bad = _h(handoffs, e["17:0002"]) + assert (ok.state, ok.last.counterparty_accepted) == ("acknowledged", False) + assert (bad.state, bad.last.reason) == ("sent", "rejected_by_counterparty") + + +def test_the_same_report_twice_adds_nothing(tmp_path): + pending, e = _claims(tmp_path, FMT_277, ["CLM-1003"]) + _settle(pending, ACK_277CA, FMT_277) + _, handoffs = _settle(pending, ACK_277CA, FMT_277) + assert len(_h(handoffs, e["CLM-1003"]).observations) == 1 + + +def test_no_answer_by_the_deadline_keeps_the_state_and_needs_follow_up(tmp_path): + pending, e = _claims(tmp_path, FMT_277, ["CLM-1003", "CLM-9999"], hours=8) + _settle(pending, ACK_277CA, FMT_277) # CLM-1003 received (A1) + _, handoffs = _settle(pending, None, None, now=LATER) + received = _h(handoffs, e["CLM-1003"]) + silent = _h(handoffs, e["CLM-9999"]) + assert (received.state, received.last.reason) == ( + "acknowledged", + "no_answer_by_deadline", + ) + assert (silent.state, silent.last.reason) == ("sent", "no_answer_by_deadline") + assert received.status(LATER) == silent.status(LATER) == "needs_follow_up" + + +def test_two_claims_on_one_key_are_ambiguous(tmp_path): + pending, _ = _claims(tmp_path, FMT_277, ["CLM-1001"]) + twin = pending.add( + key="CLM-1001", + effect_contract_hash=HASH, + fmt=FMT_277, + describe="payer x12-277ca", + deadline_hours=48, + now=T0, + ) + _, handoffs = _settle(pending, ACK_277CA, FMT_277) + h = _h(handoffs, twin) + assert (h.state, h.last.reason) == ("sent", "ambiguous_key") + assert h.status(SETTLE_AT) == "needs_follow_up" + + +def test_sync_maps_claims_settled_before_handoffs_existed(tmp_path): + pending, e = _claims(tmp_path, FMT_277, ["CLM-1001", "CLM-1002"]) + pending.settle(ACK_277CA, FMT_277, now=SETTLE_AT) # no observer + handoffs = payer.sync(pending) + assert _h(handoffs, e["CLM-1001"]).last.counterparty_accepted + assert _h(handoffs, e["CLM-1002"]).last.reason == "rejected_by_counterparty" + + +def test_export_reports_are_not_counterparty_handoffs_by_default(tmp_path): + fmt = ReportFormat(format="csv", key_column="k", status_column="s", accept=["ok"]) + pending, _ = _claims(tmp_path, fmt, ["ORD-1"]) + assert payer.sync(pending).entries() == [] + assert len(payer.sync(pending, exports=True).entries()) == 1 + + +# -- read-back of what the receiver recorded ----------------------------------- + + +FIELDS = { + "given_name": ("Avery", "text"), + "family_name": ("Quill", "text"), + "birth_date": ("1984-03-09", "date"), + "sex": ("female", "code"), +} +RECORD = { + "given_name": "Avery", + "family_name": "Quill", + "birth_date": "1984-03-09", + "sex": "female", +} + + +class Fake: + read_method = "api_readback" + + def __init__(self, result: ReadResult) -> None: + self.result = result + + def read(self, key: str) -> ReadResult: + return self.result + + +def _referral(tmp_path: Path, key: str = "REF-0001", hours: float = 24): + ledger = HandoffLedger(tmp_path / "handoffs") + h = ledger.send( + key, + FIELDS, + counterparty="receiving clinic", + system_kind="ehr", + follow_up="referrals desk", + follow_up_hours=hours, + run_id="run-1", + step=2, + ) + return ledger, h + + +def _found(**changes): + return ReadResult("found", fields={**RECORD, **changes}, evidence_sha256="1" * 64) + + +def test_recorded_as_intended(tmp_path): + ledger, h = _referral(tmp_path) + after = intake.check(ledger, h.id, "REF-0001", Fake(_found())) + assert after.state == "recorded_as_intended" + assert after.status() == "done" + assert after.last.strength == "field_readback" + + +@pytest.mark.parametrize( + "changes,differs", + [ + ({"birth_date": "1984-03-10"}, ["birth_date"]), + ({"birth_date": "1984-09-03"}, ["birth_date"]), # day and month swapped + ({"family_name": "Quil"}, ["family_name"]), + ({"sex": "male"}, ["sex"]), + ({"given_name": None}, ["given_name"]), # dropped field + ({"birth_date": "unknown"}, ["birth_date"]), # unparseable + ({"birth_date": "1984-03-10", "sex": "male"}, ["birth_date", "sex"]), + ], +) +def test_recorded_differently_names_only_the_field_ids(tmp_path, changes, differs): + ledger, h = _referral(tmp_path) + after = intake.check(ledger, h.id, "REF-0001", Fake(_found(**changes))) + assert after.state == "recorded_differently" + assert after.last.differing_fields == differs + assert after.status() == "needs_follow_up" + text = (ledger.directory / f"{h.id[8:]}.json").read_text() + for value in [*RECORD.values(), *changes.values(), "REF-0001"]: + if value and len(value) > 3: + assert value not in text + + +@pytest.mark.parametrize( + "changes", + [ + {"given_name": "AVERY", "family_name": " quill "}, + {"birth_date": "1984-03-09T00:00:00"}, + {"birth_date": "March 9, 1984"}, + {"sex": "FEMALE"}, + ], +) +def test_benign_formatting_is_no_false_alarm(tmp_path, changes): + ledger, h = _referral(tmp_path) + after = intake.check(ledger, h.id, "REF-0001", Fake(_found(**changes))) + assert after.state == "recorded_as_intended", after.last.differing_fields + + +def test_never_arrived_stays_sent_and_is_due(tmp_path): + ledger, h = _referral(tmp_path, hours=1) + after = intake.check(ledger, h.id, "REF-0001", Fake(ReadResult("not_found"))) + assert (after.state, after.last.reason) == ("sent", "not_found") + assert after.status() == "waiting" + assert after.status(datetime.now(timezone.utc) + timedelta(hours=2)) == ( + "needs_follow_up" + ) + + +def test_ambiguous_and_unreachable_confirm_nothing(tmp_path): + ledger, h = _referral(tmp_path) + after = intake.check(ledger, h.id, "REF-0001", Fake(ReadResult("ambiguous"))) + assert (after.state, after.last.reason) == ("sent", "ambiguous_key") + assert after.status() == "needs_follow_up" + after = intake.check(ledger, h.id, "REF-0001", Fake(ReadResult("unreachable"))) + assert after.last.reason == "receiver_unreachable" + assert after.state == "sent" + + +def test_unreachable_never_undoes_a_confirmation_but_not_found_does(tmp_path): + ledger, h = _referral(tmp_path) + intake.check(ledger, h.id, "REF-0001", Fake(_found())) + after = intake.check(ledger, h.id, "REF-0001", Fake(ReadResult("unreachable"))) + assert after.state == "recorded_as_intended" and after.status() == "done" + after = intake.check(ledger, h.id, "REF-0001", Fake(ReadResult("not_found"))) + assert after.state == "sent" + + +def test_the_ledger_refuses_what_it_could_never_compare(tmp_path): + ledger = HandoffLedger(tmp_path / "handoffs") + with pytest.raises(LedgerError): + ledger.send( + "K", {"d": ("03/04/2020", "date")}, counterparty="x", follow_up_hours=1 + ) + ledger.send("K", {"d": ("2020-03-04", "date")}, counterparty="x", follow_up_hours=1) + with pytest.raises(LedgerError): # a second open handoff on the same key + ledger.send( + "K", {"d": ("2020-03-04", "date")}, counterparty="x", follow_up_hours=1 + ) + ledger2, h = _referral(tmp_path / "b") + with pytest.raises(LedgerError): + intake.check(ledger2, h.id, "REF-OTHER", Fake(_found())) + assert ledger2.directory.stat().st_mode & 0o777 == 0o700 + + +# -- the FHIR reader --------------------------------------------------------------- + +PROFILE = FhirSearchProfile( + resource="Patient", + key_param="identifier", + key_path="identifier.value", + fields={ + "family_name": {"path": "name.family"}, + "birth_date": {"path": "birthDate", "kind": "date"}, + }, +) + + +def _patient(key: str, family: str = "Quill") -> dict: + return { + "resourceType": "Patient", + "identifier": [{"value": key}], + "name": [{"family": family}], + "birthDate": "1984-03-09", + } + + +class Client: + def __init__(self, *pages, status: int = 200) -> None: + self.pages = list(pages) + self.status = status + self.calls: list = [] + + def get(self, url, params=None, headers=None): + self.calls.append((url, params, headers)) + body = self.pages.pop(0) if self.pages else {} + return SimpleNamespace( + status_code=self.status, content=json.dumps(body).encode() + ) + + +def _bundle(*resources, next_url=None): + out = {"resourceType": "Bundle", "entry": [{"resource": r} for r in resources]} + if next_url: + out["link"] = [{"relation": "next", "url": next_url}] + return out + + +def _reader(client): + return FhirSearchReader( + PROFILE, "https://receiver.test/fhir", token="t", client=client + ) + + +def test_fhir_reader_found_not_found_and_key_check(): + found = _reader(Client(_bundle(_patient("REF-1")))).read("REF-1") + assert found.status == "found" + assert found.fields == {"family_name": "Quill", "birth_date": "1984-03-09"} + # A server that ignores the search parameter returns everyone: only the + # record that carries the key counts. + noisy = _reader(Client(_bundle(_patient("REF-2"), _patient("REF-1")))).read("REF-1") + assert noisy.status == "found" + assert _reader(Client(_bundle(_patient("REF-2")))).read("REF-1").status == ( + "not_found" + ) + + +def test_fhir_reader_ambiguous_across_pages_and_fails_closed(): + client = Client( + _bundle(_patient("REF-1"), next_url="https://receiver.test/fhir/Patient?p=2"), + _bundle(_patient("REF-1", "Other")), + ) + assert _reader(client).read("REF-1").status == "ambiguous" + assert client.calls[0][2]["Authorization"] == "Bearer t" + assert _reader(Client(_bundle(), status=401)).read("REF-1").status == "unreachable" + assert _reader(Client({"resourceType": "Patient"})).read("REF-1").status == ( + "unreachable" + ) + off_origin = Client(_bundle(next_url="https://elsewhere.test/fhir/Patient?p=2")) + assert _reader(off_origin).read("REF-1").status == "unreachable" + + +def test_fhir_reader_fails_closed_on_a_partial_search(): + error = {"resourceType": "OperationOutcome", "issue": [{"severity": "error"}]} + assert _reader(Client(_bundle(_patient("REF-1"), error))).read("REF-1").status == ( + "unreachable" + ) + note = {"resourceType": "OperationOutcome", "issue": [{"severity": "warning"}]} + assert _reader(Client(_bundle(_patient("REF-1"), note))).read("REF-1").status == ( + "found" + ) + short = {**_bundle(_patient("REF-1")), "total": 2} + assert _reader(Client(short)).read("REF-1").status == "unreachable" + # Pages that disagree on the total are a partial search. + first = { + **_bundle(_patient("REF-1"), next_url="https://receiver.test/fhir/Patient?p=2"), + "total": 2, + } + second = {**_bundle(_patient("REF-2")), "total": 1} + assert _reader(Client(first, second)).read("REF-1").status == "unreachable" + + +def test_a_key_names_one_delivery(tmp_path): + ledger, h = _referral(tmp_path) + intake.check(ledger, h.id, "REF-0001", Fake(_found())) + with pytest.raises(LedgerError, match="already uses this key"): + _referral(tmp_path) + + +def test_receiver_dates_are_read_in_the_receivers_order(tmp_path): + ledger = HandoffLedger(tmp_path / "handoffs") + h = ledger.send( + "REF-0009", + {**FIELDS, "birth_date": ("03/09/1984", "date", "mdy")}, + counterparty="receiving clinic", + follow_up_hours=24, + system_kind="ehr", + run_id="run-1", + step=2, + ) + # The receiver's text reads two ways and its profile declares no order: + # never read in the sender's order, so it counts as differing. + ambiguous = ReadResult("found", fields={**RECORD, "birth_date": "03/09/1984"}) + after = intake.check(ledger, h.id, "REF-0009", Fake(ambiguous)) + assert after.state == "recorded_differently" + assert after.last.differing_fields == ["birth_date"] + declared = ReadResult( + "found", + fields={**RECORD, "birth_date": "03/09/1984"}, + date_orders={"birth_date": "mdy"}, + ) + assert intake.check(ledger, h.id, "REF-0009", Fake(declared)).state == ( + "recorded_as_intended" + ) + + +# -- the receipt line ---------------------------------------------------------------- + + +def test_lines_follow_the_schema_rules(tmp_path): + ledger, h = _referral(tmp_path) + assert line.to_line(h).line["state"] == "sent" + assert line.to_line(h).line["strength"] == "none" + h = intake.check(ledger, h.id, "REF-0001", Fake(_found(birth_date="1984-03-10"))) + item = line.to_line(h) + assert item.line == { + "kind": "counterparty_confirmation", + "for_step": 2, + "system_kind": "ehr", + "read_method": "api", + "state": "recorded_differently", + "strength": "read_back", + "differing_count": 1, + } + assert item.values["counterparty"].startswith("ehr:cp-") + assert [ + v.endswith(":differs") + for k, v in sorted(item.values.items()) + if k.startswith("field.") + ] == [ + True, + False, + False, + False, + ] + pending, e = _claims(tmp_path, FMT_277, ["CLM-1001", "CLM-1002"]) + _, handoffs = _settle(pending, ACK_277CA, FMT_277) + accepted = line.to_line(_h(handoffs, e["CLM-1001"])).line + rejected = line.to_line(_h(handoffs, e["CLM-1002"])) + assert (accepted["state"], accepted["read_method"], accepted["strength"]) == ( + "acknowledged", + "acknowledgment_message", + "acknowledgment", + ) + assert rejected.line["state"] == "sent" + assert rejected.values["reason"] == "rejected_by_counterparty" + + +def test_a_line_fails_closed_when_a_compared_field_would_not_fit(tmp_path): + ledger, h = _referral(tmp_path) + h = intake.check(ledger, h.id, "REF-0001", Fake(_found(birth_date="1984-03-10"))) + spec = next(iter(h.fields.values())) + wide = h.model_construct( + **{**dict(h), "fields": {f"f{i:02d}": spec for i in range(32)}} + ) + with pytest.raises(ValueError, match="at most 31 fields"): + line.to_line(wide) + with pytest.raises(ValueError): + type(h).model_validate({**h.model_dump(), "fields": dict(wide.fields)}) + last = h.observations[-1].model_copy(update={"differing_fields": ["not_sent"]}) + stray = h.model_copy(update={"observations": [*h.observations[:-1], last]}) + with pytest.raises(ValueError, match="not one the handoff compared"): + line.to_line(stray) + + +def test_run_match_never_by_folder_name(tmp_path): + """A handoff belongs to a run by its run_id or resolved path only.""" + ledger = HandoffLedger(tmp_path / "handoffs") + run_dir = tmp_path / "r" / "run-a" + run_dir.mkdir(parents=True) + for run_id, key in [ + ("run-a", "REF-0001"), # the folder's bare name: another run's id + (str(tmp_path / "o" / "run-a"), "REF-0002"), # same name, other folder + (str(run_dir), "REF-0003"), + ("rpt-1", "REF-0004"), + ]: + ledger.send( + key, + FIELDS, + counterparty="receiving clinic", + system_kind="ehr", + follow_up="referrals desk", + follow_up_hours=24, + run_id=run_id, + step=0, + ) + found = line.handoffs_for_run({"run_id": "rpt-1"}, [ledger], run_dir) + assert sorted(h.run_id for h in found) == sorted(["rpt-1", str(run_dir)]) + + +def test_lines_validate_against_the_receipt_schema_and_sign(tmp_path): + r = pytest.importorskip("openadapt_types.receipt") + if not hasattr(r, "Confirmation"): + pytest.skip("openadapt-types without counterparty confirmations") + pytest.importorskip("cryptography") + assert {k: set(v) for k, v in line.REASONS_FOR_STATE.items()} == { + k: set(v) for k, v in r.REASONS_FOR_STATE.items() + } + import base64 + + from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat + + from openadapt_flow.receipt_record import build_statement + + ledger, h = _referral(tmp_path) + states = [h] + states.append(intake.check(ledger, h.id, "REF-0001", Fake(_found()))) + ledger2, h2 = _referral(tmp_path / "2") + states.append(intake.check(ledger2, h2.id, "REF-0001", Fake(_found(sex="male")))) + pending, e = _claims(tmp_path, FMT_277, ["CLM-1001", "CLM-1002", "CLM-1003"]) + _, handoffs = _settle(pending, ACK_277CA, FMT_277) + states += [_h(handoffs, x) for x in e.values()] + report = { + "run_id": "run-1", + "execution_outcome": "VERIFIED", + "results": [ + {"step_id": "s1", "intent": "open", "ok": True}, + {"step_id": "s2", "intent": "fill", "ok": True}, + {"step_id": "s3", "intent": "save", "ok": True}, + ], + "change_ledger": [], + } + statement, openings = build_statement(report, "a" * 64, flow_version="3.4.0") + statement, openings = line.attach_confirmations(statement, openings, states) + key = Ed25519PrivateKey.generate() + raw = key.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw) + kid = r.key_id(raw) + envelope = r.sign_statement(statement, [(kid, key.sign)]) + registry = r.parse_registry( + { + "schema": r.REGISTRY_SCHEMA, + "keys": [ + { + "key_id": kid, + "public_key": base64.b64encode(raw).decode(), + "role": "this_computer", + } + ], + } + ) + result = r.verify_receipt( + envelope, registry, openings=r.private_openings(envelope, openings) + ) + assert result.ok, (result.reason, result.detail) + assert len(result.confirmation_lines) == 6 + assert result.confirmation_lines[1].startswith( + "Confirmed in the other party's system" + ) + assert "1 field differs" in result.confirmation_lines[2] + assert result.confirmation_lines[3].startswith("Acknowledged by the other party") + assert result.confirmation_lines[4].startswith("Sent to the other party") + + +# -- the CLI ----------------------------------------------------------------------- + + +def test_handoff_list_groups_by_who_must_follow_up(tmp_path, capsys): + from openadapt_flow.__main__ import main + + ledger, h = _referral(tmp_path) + intake.check(ledger, h.id, "REF-0001", Fake(_found(birth_date="1984-03-10"))) + pending, _ = _claims(tmp_path, FMT_277, ["CLM-1001", "CLM-1002", "CLM-1003"]) + _settle(pending, ACK_277CA, FMT_277) + code = main( + [ + "handoff", + "list", + "--ledger", + str(ledger.directory), + "--ledger", + str(pending.directory), + ] + ) + out = capsys.readouterr().out + assert code == 0 + needs = out.split("Needs follow-up")[1].split("Waiting")[0] + assert "recorded differently: birth_date" in needs + assert "who: referrals desk" in needs + assert "they refused it" in needs and "who: billing" in needs + assert "CLM-" not in out and "REF-0001" not in out and "1984" not in out + assert "Done: 1 (--all lists them)" in out + code = main(["handoff", "list", "--ledger", str(ledger.directory), "--json"]) + data = json.loads(capsys.readouterr().out) + assert data[0]["receipt_line"]["state"] == "recorded_differently" + assert data[0]["differing_fields"] == ["birth_date"] + + +def test_handoff_list_for_one_run_sets_the_claims_step(tmp_path, capsys): + from openadapt_flow.__main__ import main + + pending, e = _claims(tmp_path, FMT_277, ["CLM-1001"]) + run = tmp_path / "run" + run.mkdir() + report = { + "run_id": "r", + "results": [ + {"ok": True}, + {"ok": True, "effect_evidence": [{"deferred_check": e["CLM-1001"].id}]}, + ], + } + (run / "report.json").write_text(json.dumps(report)) + assert ( + main( + [ + "handoff", + "list", + "--ledger", + str(pending.directory), + "--run", + str(run), + "--json", + ] + ) + == 0 + ) + data = json.loads(capsys.readouterr().out) + assert [d["receipt_line"]["for_step"] for d in data] == [1] + assert data[0]["state"] == "sent" + + +def test_a_failing_observer_never_changes_what_settles(tmp_path): + pending, e = _claims(tmp_path, FMT_277, ["CLM-1001", "CLM-1002", "CLM-1003"]) + + def broken(entry, row, count): + raise OSError("disk full") + + settled = pending.settle(ACK_277CA, FMT_277, now=SETTLE_AT, observer=broken) + assert {s.id: s.state for s in settled} == { + e["CLM-1001"].id: "verified", + e["CLM-1002"].id: "reconciliation_required", + } + # The handoffs catch up from the settled entries. + handoffs = payer.sync(pending) + assert _h(handoffs, e["CLM-1001"]).last.counterparty_accepted + assert _h(handoffs, e["CLM-1002"]).last.reason == "rejected_by_counterparty" + + +def test_sync_catches_up_a_settlement_the_observer_missed(tmp_path): + pending, e = _claims(tmp_path, FMT_277, ["CLM-1003"], hours=8) + _settle(pending, ACK_277CA, FMT_277) # A1: acknowledged + pending.settle(None, None, now=LATER) # expired by a caller with no observer + handoffs = payer.sync(pending) + h = _h(handoffs, e["CLM-1003"]) + assert (h.state, h.last.reason) == ("acknowledged", "no_answer_by_deadline") + before = len(h.observations) + assert len(_h(payer.sync(pending), e["CLM-1003"]).observations) == before + + +def test_sync_adds_nothing_after_the_observer_recorded_it(tmp_path): + pending, e = _claims(tmp_path, FMT_277, ["CLM-1001", "CLM-1002"]) + _, handoffs = _settle(pending, ACK_277CA, FMT_277) + counts = {k: len(_h(handoffs, v).observations) for k, v in e.items()} + handoffs = payer.sync(pending) + assert {k: len(_h(handoffs, v).observations) for k, v in e.items()} == counts + + +def test_a_refused_claim_reads_as_refused_not_unanswered(tmp_path, capsys): + from openadapt_flow.__main__ import main + + pending, _ = _claims(tmp_path, FMT_277, ["CLM-1002"]) + _settle(pending, ACK_277CA, FMT_277) + assert main(["handoff", "list", "--ledger", str(pending.directory)]) == 0 + out = capsys.readouterr().out + assert "sent; they refused it" in out + assert "no answer yet" not in out diff --git a/packages/flow/tests/test_handoffs_live_openemr.py b/packages/flow/tests/test_handoffs_live_openemr.py new file mode 100644 index 0000000000..8f19c8d4d5 --- /dev/null +++ b/packages/flow/tests/test_handoffs_live_openemr.py @@ -0,0 +1,35 @@ +"""Referral intake read back from a real OpenEMR receiver (synthetic). + +Skipped unless the receiver's variables are set (see +``benchmark/handoff_receiver/README.md``); normal CI never reaches it. The +unit tests in ``test_handoffs.py`` cover the same logic with fakes. +""" + +from __future__ import annotations + +import json +import os +from pathlib import Path + +import pytest + +pytestmark = pytest.mark.skipif( + not os.environ.get("HANDOFF_RECEIVER_FHIR_BASE"), + reason="needs the synthetic OpenEMR receiver (HANDOFF_RECEIVER_*)", +) + + +def test_every_referral_case_against_the_real_receiver(tmp_path: Path) -> None: + from benchmark.handoff_receiver.referral_cases import run_cases, summarize + + repeat = int(os.environ.get("HANDOFF_RECEIVER_REPEAT", "5")) + results = run_cases(tmp_path, repeat=repeat) + summary = summarize(results) + out = os.environ.get("HANDOFF_RESULTS_OUT") + if out: + Path(out).write_text(json.dumps(summary, indent=2) + "\n") + wrong = [r for r in results if not r.ok] + assert not wrong, [(r.case, r.state, r.reason, r.differing) for r in wrong] + # No false alarm: every correctly recorded referral reads as intended. + for case in ("intended", "benign_format"): + assert summary["cases"][case]["as_expected"] == repeat diff --git a/packages/seal-view/src/lib/sealSummary.mjs b/packages/seal-view/src/lib/sealSummary.mjs index 59f9cf8a24..d0d054711f 100644 --- a/packages/seal-view/src/lib/sealSummary.mjs +++ b/packages/seal-view/src/lib/sealSummary.mjs @@ -20,6 +20,14 @@ export function cardFor(outcome, transaction, { readBack = false } = {}) { line: "Every step's checks passed. This run didn't read the saved record back.", } } + if (transaction === 'SAVED_AWAITING_CHECK') { + // Sent, not settled: never shown as saved and checked. + return { + tone: 'halt', + label: 'Awaiting counterparty confirmation', + line: 'The entry was sent. The other party has not confirmed it yet; a signed update records the answer.', + } + } if (transaction === 'HALTED_BEFORE_EFFECT') { return { tone: 'halt', diff --git a/packages/seal-view/test/seal.test.mjs b/packages/seal-view/test/seal.test.mjs index 8d8c8dbe7a..7b702daa5b 100644 --- a/packages/seal-view/test/seal.test.mjs +++ b/packages/seal-view/test/seal.test.mjs @@ -102,3 +102,10 @@ describe('the page props', () => { expect(page.tamper.map((t) => t.id)).toEqual(['report-outcome', 'report-model-calls', 'seal-outcome']) }) }) + +it('a run awaiting its counterparty is never shown as saved and checked', async () => { + const { cardFor } = await import('../src/lib/sealSummary.mjs') + const card = cardFor('COMPLETED_UNVERIFIED', 'SAVED_AWAITING_CHECK') + expect(card.label).toBe('Awaiting counterparty confirmation') + expect(card.tone).not.toBe('ok') +}) diff --git a/tests/snapshots/seal_viewer_size.json b/tests/snapshots/seal_viewer_size.json index 7ed362464f..54a2c4a9b6 100644 --- a/tests/snapshots/seal_viewer_size.json +++ b/tests/snapshots/seal_viewer_size.json @@ -1,5 +1,5 @@ { - "bytes": 253871, - "gzip_bytes": 80778, + "bytes": 254060, + "gzip_bytes": 80863, "budget_bytes": 262144 } diff --git a/tests/test_handoff_launcher.py b/tests/test_handoff_launcher.py new file mode 100644 index 0000000000..2ab6b80f02 --- /dev/null +++ b/tests/test_handoff_launcher.py @@ -0,0 +1,28 @@ +"""``openadapt handoff list`` reaches Flow's ``handoff list`` unchanged.""" + +from __future__ import annotations + +import pytest +from click.testing import CliRunner + +pytest.importorskip("openadapt_flow.handoffs") + +from openadapt import cli # noqa: E402 + + +def test_root_handoff_list_runs_flow_handoff_list(tmp_path): + from openadapt_flow.handoffs.ledger import HandoffLedger + + ledger = HandoffLedger(tmp_path / "handoffs") + ledger.send( + "REF-1", + {"birth_date": ("2001-02-03", "date")}, + counterparty="receiving clinic", + follow_up_hours=1, + ) + result = CliRunner().invoke( + cli.main, ["handoff", "list", "--ledger", str(ledger.directory)] + ) + assert result.exit_code == 0, result.output + assert "Waiting (1)" in result.output + assert "receiving clinic: sent, no answer yet" in result.output