From 641cb3bd08b0a96e8e6f873d8aba8114ad0c0612 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 17:49:40 -0500 Subject: [PATCH 01/17] feat(receipts): the post-save screen check earns VERIFIED with basis post_save_screen --- openadapt/receipt_verify.py | 23 +++ openadapt/seal_view/viewer.html | 4 +- openadapt/wrap_sdk.py | 42 ++++ packages/flow/openadapt_flow/check_level.py | 8 + .../effect_location/evaluator.py | 2 +- .../flow/openadapt_flow/evidence_basis.py | 75 ++++++- packages/flow/openadapt_flow/verify_run.py | 4 +- packages/flow/tests/test_effect_location.py | 15 +- packages/flow/tests/test_one_ladder.py | 59 ++++-- packages/flow/tests/test_post_save_screen.py | 82 ++++++++ .../kernel/src/openadapt_kernel/copilot.py | 2 + .../kernel/src/openadapt_kernel/ledger.py | 29 ++- .../src/openadapt_kernel/receipt_bridge.py | 84 +++++++- .../tests/test_post_save_screen_bridge.py | 122 ++++++++++++ packages/seal-view/src/lib/receiptRecord.mjs | 7 +- packages/types/openadapt_types/check_level.py | 187 +++++++++++++++--- .../types/openadapt_types/evidence_scope.py | 33 +++- packages/types/tests/test_post_save_screen.py | 119 +++++++++++ .../tests/vectors/screen-check/cases.json | 15 ++ tests/test_post_save_screen_parity.py | 164 +++++++++++++++ 20 files changed, 1001 insertions(+), 75 deletions(-) create mode 100644 packages/flow/tests/test_post_save_screen.py create mode 100644 packages/kernel/tests/test_post_save_screen_bridge.py create mode 100644 packages/types/tests/test_post_save_screen.py create mode 100644 packages/types/tests/vectors/screen-check/cases.json create mode 100644 tests/test_post_save_screen_parity.py diff --git a/openadapt/receipt_verify.py b/openadapt/receipt_verify.py index 8dd799709b..b3a9546d31 100644 --- a/openadapt/receipt_verify.py +++ b/openadapt/receipt_verify.py @@ -69,6 +69,9 @@ def _describe(result: Any, say: Say, indent: str = " ") -> None: + (f" ({reason})" if reason else "") + ", as the run recorded it. A receipt doesn't grade the run." ) + scope = predicate.get("evidence_scope") + if isinstance(scope, dict): + say(f"{indent}{_check_line(scope)}") checks = predicate.get("checks", {}) lines = predicate.get("lines", []) say( @@ -81,6 +84,26 @@ def _describe(result: Any, say: Say, indent: str = " ") -> None: say(f"{indent}{name}: {value}") +def _check_line(scope: dict[str, Any]) -> str: + """One line naming how the run's writes were checked, from its + evidence-scope block. An older ``SHOWN`` block says it is the older + format.""" + + from openadapt_types.evidence_scope import legacy_word + + word = _one_line(scope.get("word")) + level = _one_line(scope.get("check_level")) + if legacy_word(scope) is not None: + return ( + f"Check: {word} ({OLDER}: the acting screen was read again; " + f"level {level})" + ) + basis = scope.get("basis") + return f"Check: {word} (level {level}" + ( + f", basis {_one_line(basis)})" if basis else ")" + ) + + def verify_record_file( path: Path, registry: Sequence[Any], diff --git a/openadapt/seal_view/viewer.html b/openadapt/seal_view/viewer.html index 0b6c9678d6..707c024164 100644 --- a/openadapt/seal_view/viewer.html +++ b/openadapt/seal_view/viewer.html @@ -24,7 +24,7 @@ `);if(n<0)return null;let o=e.slice(0,n),r=e.slice(n+2),a=o.split(` `);if(a.length<3||!/^\d+$/.test(a[1]))return null;let i;try{i=xt(a[2])}catch{return null}let l=eo(`${o} `),p=a[0].indexOf(" - "),c=p>=0?a[0].slice(0,p):a[0],g=p>=0?a[0].slice(p+3):null;if(g!==null&&!/^\d+$/.test(g))return null;let h=g===null?null:BigInt(g);for(let d of r.split(` -`)){if(!d.startsWith("— "))continue;let f=d.slice(2).split(" ");if(f.length<2)continue;let u=f.slice(0,-1).join(" "),v;try{v=xt(f.at(-1))}catch{continue}let m=At(v.slice(0,4));for(let b of t)if(!(c!==b.origin||u!==b.origin)&&b.logId.slice(0,8)===m&&await Ts(b,v.slice(4),l))return{origin:a[0],size:BigInt(a[1]),root:i,treeId:h}}return null}var yn=async e=>At(await bn(eo(Ce(e)))),Ic=(e,t)=>eo(`${Ss}\0${Ce({nonce:t,...e})}`);async function Cc(e){try{let t=Ns(new TextDecoder().decode(e));return t.length!==44||At(t.slice(0,12))!==Nc?null:t.slice(12)}catch{return null}}async function to(e,t,n,o){return no({seal_sha256:await yn(e)},t,n,o)}async function $s(e,t,n,o){let r;try{if(typeof e?.payload!="string")throw new Error("payload");r=xt(e.payload)}catch{return{ok:!1,reason:"anchor_malformed",steps:[{id:"anchorEntry",result:"fail"}]}}let a=At(await bn(r));return no({receipt_payload_sha256:a},t,n,o)}async function no(e,t,n,o){let r=[],a=(H,G,V={})=>({ok:H,reason:G,steps:r,...V});if(t==null)return a(!1,"anchor_missing");let i,l,p;try{if(t.schema!==Ss)throw new Error("schema");if(i=String(t.nonce),l=t.entry,p=Object.fromEntries(Object.keys(e).map(H=>[H,t[H]])),!ks.test(i)||!l||!Object.values(p).every(H=>typeof H=="string"&&ks.test(H)))throw new Error("format")}catch{return r.push({id:"anchorEntry",result:"fail"}),a(!1,"anchor_malformed")}let c=At(new Uint8Array(await Qn().digest("SHA-512",Ic(e,i))));if(Object.keys(e).some(H=>p[H]!==e[H])||t.statement_sha512!==c)return r.push({id:"anchorEntry",result:"fail"}),a(!1,"anchor_mismatch");let g,h,d,f,u,v,m,b,_,x,w,E;try{if(g=String(l.uuid),h=String(l.body),d=xt(h),f=JSON.parse(new TextDecoder().decode(d)),u=l.integratedTime,v=String(l.logID),m=l.logIndex,!Number.isInteger(u)||!Number.isInteger(m))throw new Error("int");b=xt(l.verification.signedEntryTimestamp),_=l.verification.inclusionProof,x=f.spec.data.hash,w=xt(f.spec.signature.content),E=xt(f.spec.signature.publicKey.content)}catch{return r.push({id:"anchorEntry",result:"fail"}),a(!1,"anchor_malformed")}let R={uuid:g,logIndex:m,integratedTime:u,logId:v},S=(H,G)=>(r.push({id:H,result:"fail"}),a(!1,G,R));if(f.kind!=="hashedrekord"||f.apiVersion!=="0.0.1")return S("anchorEntry","anchor_malformed");if(x?.algorithm!=="sha512"||x?.value!==c)return S("anchorEntry","anchor_mismatch");r.push({id:"anchorEntry",result:"pass"});let A=await Cc(E);if(!A||!lr(A,n))return S("anchorKey","anchor_key_mismatch");if(!await as(n,ir(c),w))return S("anchorKey","anchor_bad_signature");r.push({id:"anchorKey",result:"pass"});let L=o.find(H=>H.logId===v);if(!L)return S("anchorTime","anchor_unknown_log");let P=eo(Ce({body:h,integratedTime:u,logID:v,logIndex:m}));if(!await Ts(L,b,P))return S("anchorTime","anchor_bad_timestamp");r.push({id:"anchorTime",result:"pass"});let $=await Ac(d);if(!g.endsWith(At($)))return S("anchorInclusion","anchor_bad_inclusion");let O,M,k;try{k=BigInt(_.treeSize),O=await Rc(_.logIndex,_.treeSize,$,_.hashes.map(ir)),M=ir(_.rootHash)}catch{return S("anchorInclusion","anchor_malformed")}if(!O||!lr(O,M))return S("anchorInclusion","anchor_bad_inclusion");r.push({id:"anchorInclusion",result:"pass"});let B=await Mc(String(_.checkpoint),[L]);return!B||!lr(B.root,M)||B.size!==k||g.length===80&&B.treeId!==null&&g.slice(0,16)!==B.treeId.toString(16).padStart(16,"0")?S("anchorCheckpoint","anchor_bad_checkpoint"):(r.push({id:"anchorCheckpoint",result:"pass"}),a(!0,null,R))}var Pc=(e,t)=>!!(t&&e?.scope?.seal_key_ids?.includes(t.key_id));function As(e){if(e==null||et(e)!==null)return null;try{return JSON.parse(e)}catch{return null}}async function Rs(e,t,{requireAnchor:n=!1,requireAuthorization:o=!1,logKeys:r=null}={}){let a=await ps(e.sealText,e.report,t,"report.json"),i=[...a.steps],l=(_,x,w={})=>({...a,ok:_,reason:x,steps:i,sealOk:a.ok,...w});if(!a.ok)return l(!1,a.reason);let p=r||[await vn(mn)],c=_=>{let x=Gt(t).filter(w=>w.key_id===_&&w.status==="active");return x.length===1?Pe(x[0].public_key):null},g=null,h=null,d=null;if(e.auth){let _=await bs(e.auth.statement,e.auth.sig);if(i=[...i,..._.steps],!_.ok)return l(!1,_.reason);let x=null;try{x=JSON.parse(new TextDecoder().decode(e.report))}catch{x=null}d=x?.started_at??null;let w=ys(a.seal,x,_),E={auth_not_referenced:"authRef",auth_reference_mismatch:"authRef",auth_scope_mismatch:"authScope",auth_bundle_mismatch:"authBundle"};if(w){let R=E[w]||"authRef";for(let S of["authRef","authScope","authBundle"]){if(S===R)break;i=[...i,{id:S,result:"pass"}]}return i=[...i,{id:R,result:"fail"}],l(!1,w)}if(i=[...i,{id:"authRef",result:"pass"},{id:"authScope",result:"pass"},{id:"authBundle",result:"pass"}],g={login:_.login,fingerprint:_.fingerprint,sha256:_.sha256,publicKey:_.publicKey},e.auth.anchorText!=null){let R=As(e.auth.anchorText),A=Pc(_.statement,R)?c(R.key_id):null,L=R?A?await no({run_authorization_sha256:_.sha256,signature_sha256:_.signatureSha256},R,A,p):{ok:!1,reason:"anchor_key_mismatch"}:{ok:!1,reason:"anchor_malformed"};if(i=[...i,{id:"authLogged",result:L.ok?"pass":"fail"}],!L.ok)return l(!1,`authorization_${L.reason}`,{authorizedBy:g});h=L.integratedTime}}else if(o)return i=[...i,{id:"authShape",result:"fail"}],l(!1,"auth_missing");if(e.anchorText==null){let _=sr(h,d,null);return n?(i=[...i,{id:"anchorEntry",result:"fail"}],l(!1,"anchor_missing",{authorizedBy:g,timing:_})):l(!0,null,{authorizedBy:g,timing:_})}let f=As(e.anchorText);if(!f)return i=[...i,{id:"anchorEntry",result:"fail"}],l(!1,"anchor_malformed",{authorizedBy:g});let u=c(a.seal.key_id),v=await to(a.seal,f,u,p);i=[...i,...v.steps];let m=sr(h,d,v.ok?v.integratedTime:null),b=_s(h,v.ok?v.integratedTime:null);return l(v.ok,v.reason,{authorizedBy:g,timing:m,authAnchorTime:h,authorizationVsSeal:b,anchor:v.ok?{uuid:v.uuid,logIndex:v.logIndex,integratedTime:v.integratedTime,logId:v.logId}:null})}var Oc="https://in-toto.io/Statement/v1",Lc="https://openadapt.ai/record/run/v1",Ms="application/vnd.in-toto+json",zc="openadapt.receipt-card/v1",Dc="openadapt.receipt-openings/v1",Fc="openadapt.receipt-keys/v1",Ds="openadapt.public-disclosure/v1",Hc="openadapt.receipt-commitment/v1",Is=256,_n=2**53-1,jc=65536,Gc=["this_computer","customer_key","openadapt_cloud","public_log","demo"],Cs=["this_computer","customer_key","openadapt_cloud","public_log"],Uc={this_computer:"Signed by this computer",customer_key:"Signed by {org}'s key",openadapt_cloud:"Countersigned by OpenAdapt Cloud",public_log:"Logged publicly",demo:"Demo key: checks only in this demo"},Bc={unknown_signer:"Not verified: unknown signer",unknown_role:"Not verified: unknown signer role",unknown_schema:"Not verified: unknown receipt format",unsigned:"Not verified: no signature",revoked_key:"Not verified: the signing key was revoked",bad_signature:"Not verified: the receipt was changed after it was signed",mixed_demo:"Not verified: a demo key signed alongside a real one",embedded_content:"Not verified: the receipt holds embedded content",opening_mismatch:"Not verified: a disclosed value doesn't match the receipt",disclosure_not_allowed:"Not verified: the card reveals a field it may not",inconsistent:"Not verified: the receipt contradicts itself",malformed:"Not verified: malformed receipt",verifier_unavailable:"Not verified: this browser can't check Ed25519 signatures"},Kc=e=>Bc[e]||"Not verified",Rt=/^[a-f0-9]{64}$/,Wc=/^[a-f0-9]{64}$/,Vc=/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:00:00Z$/,oo=/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$/,qc=/^prog-[a-f0-9]{16}$/,Zc=/^[a-z][a-z0-9_]{0,47}$/,Yc=/^[A-Za-z0-9 ._-]{1,48}$/,cr=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Fs={program_name:/^[A-Za-z0-9 ._-]{1,48}$/,flow_version:/^[0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,6}$/,github_login:/^[A-Za-z0-9-]{1,39}$/,run_id:/^[A-Za-z0-9._:-]{1,128}$/},Jc={[Ds]:["program_name","flow_version","github_login"]},Xc=["VERIFIED","STOPPED","UNKNOWN","FAILED"],Qc=["report.json","report.canonical","bundle","evidence","payload"],ed=["application/json","application/cbor","text/plain","text/csv","application/pdf","application/octet-stream"],td=["tx_receipt","write_receipt"],nd=["ehr","payer_portal","bank","erp","crm","government_portal","email","other"],od=["portal_read_back","api","acknowledgment_message"],Hs=["portal_read_back","api"],rd=["sent","acknowledged","recorded_as_intended","recorded_differently"],ad=["read_back","acknowledgment","none"],sd=["each_item","problems_only","not_gated"],id=["person","agent","none"],ld={sent:["rejected_by_counterparty","ambiguous_key","receiver_unreachable","not_found","no_answer_by_deadline"],acknowledged:["ambiguous_key","not_found","no_answer_by_deadline"],recorded_as_intended:["conflicting_report"],recorded_differently:["conflicting_report"]},cd=/^(?:counterparty|observed_at|reason|field\.[0-9]{1,2})$/,dd=/^(?:principal|scope|approved_at)$/,pd=/^confirmations\.([0-9]{1,2})\.(counterparty|observed_at|reason|field\.[0-9]{1,2})$/,ud=/^approval\.(principal|scope|approved_at)$/,fd={counterparty:/^(?:ehr|payer_portal|bank|erp|crm|government_portal|email|other):cp-[a-f0-9]{16}$/,observed_at:oo,reason:/^(?:rejected_by_counterparty|conflicting_report|ambiguous_key|receiver_unreachable|not_found|no_answer_by_deadline)$/,field:/^[a-z][a-z0-9_]{0,31}:[a-f0-9]{64}(?::differs)?$/,principal:/^(?:person|agent):pr-[a-f0-9]{16}$/,scope:Rt,approved_at:oo},hd=["gui","api"],gd=["write","irreversible_write"],md=["confirmed","refuted","not_checked"],bd=["read_back","same_screen","none"],vd=["effect_not_declared","approved_unverified","field_values","postconditions","uncertain"],yd="openadapt.evidence-scope/v1",_d=["unchecked","same_screen","reopened","separate_session","system_of_record","counterparty_confirmed"],xd=["VERIFIED","SHOWN","CONFIRMED","ATTESTED","RECORDED"],Ps={separate_session:"separate_session",system_api:"system_of_record",activity_log:"system_of_record",db_frame:"system_of_record",owned_connection:"system_of_record"},kd=["none","browser_network","http_proxy","api_client","db_connection"],wd=["http","graphql","fhir","sql","websocket","grpc","smtp"],Sd=["server_side_async_effects","outbound_effects","changes_after_read_back","fields_not_read","other_records","other_actors","read_back_time"],Ed=["server_side_async_effects","outbound_effects"],Nd=720*3600,Os=/^(?!.*:\/\/)[A-Za-z0-9][A-Za-z0-9._:@+/ -]{0,127}$/,Td={VERIFIED:["VERIFIED"],CONFIRMED:["VERIFIED"],SHOWN:["UNKNOWN","STOPPED","FAILED"],ATTESTED:["UNKNOWN","STOPPED","FAILED"],RECORDED:["UNKNOWN","STOPPED","FAILED"]},C=class extends Error{constructor(t,n=""){super(n||t),this.reason=t}},Ls=(e,t="")=>({ok:!1,reason:e,detail:t,signerLines:[Kc(e)],outcome:null,demo:!1,disclosed:{}}),$d=/data:[a-z]+\//i,Ad=/[a-z][a-z0-9+.-]*:\/\//i,Rd=/[A-Za-z0-9+/_-]{96,}={0,2}/,Md=["iVBORw0KGgo","/9j/","R0lGOD","UklGR","PHN2Zy"];function dr(e){let t=e.toLowerCase();return[...e].length>256||$d.test(e)||Ad.test(e)||Rd.test(e)||Md.some(n=>e.startsWith(n))||t.includes("e!==null&&typeof e=="object"&&!Array.isArray(e);function De(e,t,n=[],o=""){if(!je(e))throw new C("malformed",`${o} is an object`);for(let r of Object.keys(e))if(!t.includes(r)&&!n.includes(r))throw new C("malformed",`${o}.${r} is not a field`);for(let r of t)if(!(r in e))throw new C("malformed",`${o}.${r} is missing`)}function lt(e,t,n,o){if(!Number.isInteger(e)||en)throw new C("malformed",`${o} is an integer from ${t} to ${n}`)}function J(e,t,n){if(!(typeof e=="string"&&(Array.isArray(t)?t.includes(e):t.test(e))))throw new C("malformed",`${n} is not valid`)}function Id(e,t){De(e,["required","confirmed"],[],t),lt(e.required,0,_n,`${t}.required`),lt(e.confirmed,0,_n,`${t}.confirmed`)}function Cd(e){if(De(e,["_type","subject","predicateType","predicate"],[],"$"),!Array.isArray(e.subject)||e.subject.length<1||e.subject.length>4)throw new C("malformed","subject has 1 to 4 entries");for(let[o,r]of e.subject.entries())De(r,["name","digest"],["media_type"],`subject[${o}]`),J(r.name,Qc,`subject[${o}].name`),"media_type"in r&&J(r.media_type,ed,`subject[${o}].media_type`),De(r.digest,["sha256"],[],`subject[${o}].digest`),J(r.digest.sha256,Rt,`subject[${o}].digest.sha256`);let t=e.predicate;if(De(t,["program","started_hour","outcome","steps","lines","checks","model_calls","disclosure"],["reason_code","confirmations","approval","evidence_scope"],"predicate"),De(t.program,["id","version_sha256"],[],"predicate.program"),J(t.program.id,qc,"predicate.program.id"),J(t.program.version_sha256,Rt,"predicate.program.version_sha256"),J(t.started_hour,Vc,"predicate.started_hour"),J(t.outcome,Xc,"predicate.outcome"),t.reason_code!=null&&J(t.reason_code,Zc,"predicate.reason_code"),De(t.steps,["total","ok"],[],"predicate.steps"),lt(t.steps.total,0,_n,"predicate.steps.total"),lt(t.steps.ok,0,_n,"predicate.steps.ok"),!Array.isArray(t.lines)||t.lines.length>Is)throw new C("malformed","predicate.lines");for(let[o,r]of t.lines.entries()){let a=`predicate.lines[${o}]`;if(De(r,["step","target_kind","operation","check","strength","not_checked"],["evidence"],a),"evidence"in r&&(De(r.evidence,["kind","sha256"],[],`${a}.evidence`),J(r.evidence.kind,td,`${a}.evidence.kind`),J(r.evidence.sha256,Rt,`${a}.evidence.sha256`)),lt(r.step,0,1e4,`${a}.step`),J(r.target_kind,hd,`${a}.target_kind`),J(r.operation,gd,`${a}.operation`),J(r.check,md,`${a}.check`),J(r.strength,bd,`${a}.strength`),!Array.isArray(r.not_checked)||r.not_checked.length>5)throw new C("malformed",`${a}.not_checked`);r.not_checked.forEach((i,l)=>J(i,vd,`${a}.not_checked[${l}]`))}let n=t.checks;De(n,["identity","postconditions","effects","authorization","lines_confirmed","lines_refuted","lines_not_checked"],[],"predicate.checks");for(let o of["identity","postconditions","effects","authorization"])Id(n[o],`predicate.checks.${o}`);for(let o of["lines_confirmed","lines_refuted","lines_not_checked"])lt(n[o],0,Is,`predicate.checks.${o}`);if(lt(t.model_calls,0,_n,"predicate.model_calls"),De(t.disclosure,["version","commitments"],[],"predicate.disclosure"),J(t.disclosure.version,[Ds],"predicate.disclosure.version"),!je(t.disclosure.commitments)||Object.keys(t.disclosure.commitments).length>16)throw new C("malformed","predicate.disclosure.commitments");for(let o of Object.values(t.disclosure.commitments))if(typeof o!="string")throw new C("malformed","a commitment is a string");if("confirmations"in t){if(!Array.isArray(t.confirmations)||t.confirmations.length>64)throw new C("malformed","predicate.confirmations");for(let[o,r]of t.confirmations.entries()){let a=`predicate.confirmations[${o}]`;if(De(r,["kind","system_kind","read_method","state","strength","differing_count","commitments"],["for_step"],a),J(r.kind,["counterparty_confirmation"],`${a}.kind`),r.for_step!=null&<(r.for_step,0,1e4,`${a}.for_step`),J(r.system_kind,nd,`${a}.system_kind`),J(r.read_method,od,`${a}.read_method`),J(r.state,rd,`${a}.state`),J(r.strength,ad,`${a}.strength`),lt(r.differing_count,0,64,`${a}.differing_count`),!je(r.commitments)||Object.keys(r.commitments).length<2||Object.keys(r.commitments).length>34)throw new C("malformed",`${a}.commitments`)}}if("approval"in t&&(De(t.approval,["mode","approver_kind","commitments"],[],"predicate.approval"),J(t.approval.mode,sd,"predicate.approval.mode"),J(t.approval.approver_kind,id,"predicate.approval.approver_kind"),!je(t.approval.commitments)||Object.keys(t.approval.commitments).length>3))throw new C("malformed","predicate.approval.commitments");if("evidence_scope"in t){let o=t.evidence_scope;De(o,["schema","check_level","word","wire","not_covered"],["basis","read_back_at","recheck_window_s","agent_used","verifier_adapter"],"predicate.evidence_scope"),J(o.schema,[yd],"predicate.evidence_scope.schema"),J(o.check_level,_d,"predicate.evidence_scope.check_level"),J(o.word,xd,"predicate.evidence_scope.word"),"basis"in o&&J(o.basis,Object.keys(Ps),"predicate.evidence_scope.basis"),De(o.wire,["channel","protocols_parsed"],[],"predicate.evidence_scope.wire"),J(o.wire.channel,kd,"predicate.evidence_scope.wire.channel");let r=o.wire.protocols_parsed;if(!Array.isArray(r)||r.length>7)throw new C("malformed","predicate.evidence_scope.wire.protocols_parsed");if(r.forEach((a,i)=>J(a,wd,`predicate.evidence_scope.wire.protocols_parsed[${i}]`)),new Set(r).size!==r.length)throw new C("malformed","wire.protocols_parsed repeats a protocol");if(o.wire.channel==="none"&&r.length)throw new C("malformed","a run that watched no wire parsed no protocol");if("read_back_at"in o&&J(o.read_back_at,oo,"predicate.evidence_scope.read_back_at"),"recheck_window_s"in o&<(o.recheck_window_s,0,Nd,"predicate.evidence_scope.recheck_window_s"),"agent_used"in o&&J(o.agent_used,Os,"predicate.evidence_scope.agent_used"),"verifier_adapter"in o&&J(o.verifier_adapter,Os,"predicate.evidence_scope.verifier_adapter"),!Array.isArray(o.not_covered)||o.not_covered.length<2||o.not_covered.length>7)throw new C("malformed","predicate.evidence_scope.not_covered");if(o.not_covered.forEach((a,i)=>J(a,Sd,`predicate.evidence_scope.not_covered[${i}]`)),new Set(o.not_covered).size!==o.not_covered.length)throw new C("malformed","not_covered repeats a code");if(!Ed.every(a=>o.not_covered.includes(a)))throw new C("malformed","not_covered must list server_side_async_effects and outbound_effects");if(o.basis!=null&&Ps[o.basis]!==o.check_level)throw new C("malformed",`basis ${o.basis} does not reach ${o.check_level}`);if(o.word==="VERIFIED"){if(!["separate_session","system_of_record"].includes(o.check_level)||o.basis==null)throw new C("malformed","VERIFIED needs level 3 or 4 and a basis");if(o.read_back_at==null&&!o.not_covered.includes("read_back_time"))throw new C("malformed","VERIFIED needs read_back_at, or says it has none")}if(o.word==="SHOWN"&&!["same_screen","reopened"].includes(o.check_level))throw new C("malformed","SHOWN is a level 1 or 2 re-read of the acting screen");if(o.word==="CONFIRMED"&&o.check_level!=="counterparty_confirmed")throw new C("malformed","CONFIRMED is level 5, the counterparty acknowledgment");if(o.read_back_at!=null&&o.not_covered.includes("read_back_time"))throw new C("malformed","a block with read_back_at covers the read-back time");if(o.recheck_window_s!=null&&o.read_back_at==null)throw new C("malformed","a recheck window needs read_back_at")}return{...e,predicate:{...t,reason_code:t.reason_code??null}}}function Pd(e){let t=e.predicate,n=e.subject.map(a=>a.name);if(new Set(n).size!==n.length||!(n.includes("report.json")||n.includes("report.canonical")))return"subject names repeat, or the report is missing";for(let a of e.subject)if(a.name==="payload"!="media_type"in a)return"only the payload subject has a media type, and it always has one";if(t.approval){let a=t.approval;for(let[i,l]of Object.entries(a.commitments))if(!dd.test(i)||!Rt.test(l))return`approval commitment ${i} is not a known field`;if(a.mode==="not_gated"&&a.approver_kind!=="none")return"a not_gated run names no approver";if(a.approver_kind==="none"){if(Object.keys(a.commitments).length)return"an approval with no approver commits to nothing"}else if(!("principal"in a.commitments&&"scope"in a.commitments))return"an approval names its approver's principal and scope"}for(let[a,i]of Object.entries(t.disclosure.commitments))if(!Fs[a]||!Rt.test(i))return`disclosure path ${a} is not a known field`;if(t.steps.ok>t.steps.total)return"steps.ok is more than steps.total";for(let a of["identity","postconditions","effects","authorization"])if(t.checks[a].confirmed>t.checks[a].required)return`checks.${a} confirms more than it requires`;let o={confirmed:0,refuted:0,not_checked:0};for(let a of t.lines){if(o[a.check]+=1,a.check==="confirmed"&&a.strength==="none")return"a confirmed line has no strength";if(new Set(a.not_checked).size!==a.not_checked.length)return"a line repeats a not_checked code"}if(t.checks.lines_confirmed!==o.confirmed||t.checks.lines_refuted!==o.refuted||t.checks.lines_not_checked!==o.not_checked)return"check counts disagree with the lines";if(t.outcome==="VERIFIED"&&o.refuted)return"a VERIFIED receipt has a refuted line";if(t.evidence_scope&&!Td[t.evidence_scope.word].includes(t.outcome))return"the evidence scope's word disagrees with the outcome";let r=t.lines.map(a=>a.step);for(let a=1;a0)return"differing_count disagrees with the state";if(!("counterparty"in a.commitments&&"observed_at"in a.commitments))return"a confirmation commits to its counterparty and observed_at";for(let[l,p]of Object.entries(a.commitments))if(!cd.test(l)||!Rt.test(p))return`confirmation commitment ${l} is not a known field`;let i=Object.keys(a.commitments).filter(l=>l.startsWith("field.")).length;if(a.differing_count>i)return"more differing fields than observed fields"}return null}var Ut=e=>new TextEncoder().encode(e);function js(...e){let t=new Uint8Array(e.reduce((o,r)=>o+r.length,0)),n=0;for(let o of e)t.set(o,n),n+=o.length;return t}var Od=e=>Uint8Array.from(e.match(/../g),t=>parseInt(t,16));async function Ld(e,t,n){let o=new Uint8Array([0]);return Re(js(Ut(Hc),o,Ut(e),o,Od(t),o,Ut(Ce(n))))}function zd(e,t){let n=pd.exec(e)||ud.exec(e);if(n){let r=(n[2]||n[1]).split(".")[0];return typeof t=="string"&&fd[r].test(t)?null:`${e} does not match its field's pattern`}let o=Fs[e];return o?typeof t!="string"?`${e} is not a string`:dr(t)?`${e} holds embedded content`:o.test(t)?null:`${e} does not match its field's pattern`:`${e} is not a disclosure field`}async function zs(e,t,n){if(!je(e))throw new C("malformed","openings are an object");let o=ro(e);if(o)throw new C("embedded_content",o);let r={};for(let[a,i]of Object.entries(e)){if(n&&!n.includes(a))throw new C("disclosure_not_allowed",a);if(!je(i)||Object.keys(i).length!==2||!("salt"in i)||!("value"in i))throw new C("malformed",`the opening for ${a}`);let l=zd(a,i.value);if(l)throw new C("malformed",l);if(!(typeof i.salt=="string"&&Wc.test(i.salt)))throw new C("malformed",`the salt for ${a}`);if(t[a]!==await Ld(a,i.salt,i.value))throw new C("opening_mismatch",a);r[a]=i.value}return r}async function Dd(e){if(!je(e)||e.schema!==Fc)throw new C("unknown_schema","not an openadapt.receipt-keys/v1 registry");if(!Array.isArray(e.keys))throw new C("malformed","a registry has a keys list");let t=[];for(let n of e.keys){if(!je(n))throw new C("malformed","a registry entry is an object");if(Object.keys(n).some(a=>!["key_id","public_key","role","status","revoked_at","org"].includes(a)))throw new C("malformed","a registry entry has an unknown field");if(!Gc.includes(n.role))throw new C("unknown_role",`unknown signer role ${n.role}`);if(typeof n.public_key!="string"||!cr.test(n.public_key))throw new C("malformed","a public key is base64");let o=Pe(n.public_key);if(o.length!==32||n.key_id!==`seal-ed25519-${(await Re(o)).slice(0,16)}`)throw new C("malformed","a key id doesn't match its public key");let r=n.status??"active";if(!["active","revoked"].includes(r)||r==="revoked"&&!(typeof n.revoked_at=="string"&&oo.test(n.revoked_at)))throw new C("malformed","a key is active, or revoked with revoked_at");if(n.role==="customer_key"&&!(typeof n.org=="string"&&Yc.test(n.org)))throw new C("malformed","a customer key names its org");t.push({keyId:n.key_id,raw:o,role:n.role,status:r,revokedAt:r==="revoked"?n.revoked_at:null,org:n.role==="customer_key"?n.org:null})}if(new Set(t.map(n=>n.keyId)).size!==t.length)throw new C("malformed","a registry lists one key id twice");return t}function Fd(e,t){let n=Ut(e);return js(Ut(`DSSEv1 ${n.length} `),n,Ut(` ${t.length} `),t)}var Hd=e=>je(e)&&e.schema===zc;function jd(e){if(et(e)!==null)throw new C("malformed","duplicate key");try{return JSON.parse(e)}catch{throw new C("malformed","the payload is not JSON")}}async function Gd(e,t,n){let o;try{o=await globalThis.crypto.subtle.importKey("raw",e,{name:"Ed25519"},!1,["verify"])}catch{throw new C("verifier_unavailable")}return globalThis.crypto.subtle.verify({name:"Ed25519"},o,t,n)}async function Gs(e,t,{openings:n=null}={}){try{let o=await Dd(t),r=null,a=null,i=e;if(Hd(e)){if(Object.keys(e).sort().join(",")!=="disclosure_version,envelope,openings,schema")throw new C("malformed","a card has exactly four fields");if(a=Jc[e.disclosure_version],!a)throw new C("unknown_schema","unknown public disclosure version");if(r=e.openings,!je(r))throw new C("malformed","a card's openings are an object");if(i=e.envelope,n!=null)throw new C("malformed","a card carries its own openings")}if(!je(i)||Object.keys(i).sort().join(",")!=="payload,payloadType,signatures")throw new C("malformed","a DSSE envelope has payloadType, payload, signatures");if(i.payloadType!==Ms)throw new C("unknown_schema","the payload is not an in-toto statement");if(typeof i.payload!="string"||!cr.test(i.payload))throw new C("malformed","the payload is not base64");let l=Pe(i.payload);if(l.length>jc)throw new C("malformed","the payload is too large");let p=i.signatures;if(!Array.isArray(p)||!p.length)throw new C("unsigned");let c=new Map(o.map($=>[$.keyId,$])),g=Fd(Ms,l),h=[],d=new Set;for(let $ of p){if(!je($)||Object.keys($).sort().join(",")!=="keyid,sig")throw new C("malformed","a signature has keyid and sig");let O=$.keyid;if(typeof O!="string"||d.has(O))throw new C("malformed","a signature's keyid is missing or repeated");d.add(O);let M=c.get(O);if(!M)throw new C("unknown_signer",`${O} is not in the pinned registry`);if(typeof $.sig!="string"||!cr.test($.sig))throw new C("bad_signature",`${O}'s signature`);if(!await Gd(M.raw,Pe($.sig),g))throw new C("bad_signature",`${O}'s signature`);if(M.status==="revoked")throw new C("revoked_key",`${O} was revoked at ${M.revokedAt}`);h.push({keyId:O,role:M.role,line:Uc[M.role].replace("{org}",M.org||"the customer")})}let f=new Set(h.map($=>$.role)),u=f.has("demo");if(u&&f.size!==1)throw new C("mixed_demo");let v;try{v=new TextDecoder("utf-8",{fatal:!0}).decode(l)}catch{throw new C("malformed","the payload is not UTF-8")}let m=jd(v);if(!je(m))throw new C("malformed","the payload is not an object");if(m._type!==Oc||m.predicateType!==Lc)throw new C("unknown_schema","not a record/run/v1 statement");let b=Object.fromEntries(Object.entries(m).filter(([$])=>$!=="_type"&&$!=="predicateType")),_=ro(b);if(_)throw new C("embedded_content",_);let x=Cd(m);if(Ce(x)!==v)throw new C("malformed","the payload is not canonical JSON");let w=Pd(x);if(w)throw new C("inconsistent",w);let E={...x.predicate.disclosure.commitments};for(let[$,O]of(x.predicate.confirmations||[]).entries())for(let[M,k]of Object.entries(O.commitments))E[`confirmations.${$}.${M}`]=k;if(x.predicate.approval)for(let[$,O]of Object.entries(x.predicate.approval.commitments))E[`approval.${$}`]=O;let R={},S=!1;if(r)R=await zs(r,E,a);else if(n!=null){if(!je(n)||Object.keys(n).sort().join(",")!=="openings,payload_sha256,schema")throw new C("malformed","a private openings file has three fields");if(n.schema!==Dc)throw new C("unknown_schema","not an openadapt.receipt-openings/v1 file");if(n.payload_sha256!==await Re(l))throw new C("opening_mismatch","the openings belong to another receipt");R=await zs(n.openings,E,null),S=!0;for(let[$,O]of(x.predicate.confirmations||[]).entries()){let M=R[`confirmations.${$}.reason`];if(M!=null&&!ld[O.state].includes(M))throw new C("inconsistent",`a ${O.state} confirmation can't have reason ${M}`)}}let A=[...h].sort(($,O)=>Cs.indexOf($.role)-Cs.indexOf(O.role)),L=[...new Set(A.map($=>$.line))],P=x.predicate.confirmations||[];return{ok:!0,reason:null,detail:"",signers:A,signerLines:L,confirmationLines:P.map(($,O)=>Bd($,R[`confirmations.${O}.observed_at`])),independent:P.map($=>Hs.includes($.read_method)),approvalLine:Ud(x.predicate.approval),outcome:x.predicate.outcome,demo:u,disclosed:R,private:S,statement:x}}catch(o){return o instanceof C?Ls(o.reason,o.message):Ls("malformed",String(o?.message||o))}}function Ud(e){return e?e.mode==="not_gated"?"Not gated: no approval was required for these writes":e.approver_kind==="none"?`Approval required for ${e.mode==="each_item"?"each item":"items that fail a check"}; no item was approved`:`Approved by ${e.approver_kind==="person"?"a person":"an agent delegate"}: ${e.mode==="each_item"?"each item":"items that failed a check"}`:"No approval recorded"}function Bd(e,t){let n=t?` at ${t}`:"";return e.state==="recorded_as_intended"?`Confirmed in the other party's system${n}`:e.state==="recorded_differently"?`Recorded differently in the other party's system${n}: ${e.differing_count} ${e.differing_count===1?"field differs":"fields differ"}`:e.state==="acknowledged"?`Acknowledged by the other party${n}`:`Sent to the other party${n}, not confirmed`}async function ht(e,t=!1){let n=await fetch(e,{cache:"no-store"});if(!n.ok)throw new Error(`${e}: ${n.status}`);return t?new Uint8Array(await n.arrayBuffer()):n.text()}async function Us(e,t=null){let[n,o,r,a,i,l]=await Promise.all([ht(e.report,!0),ht(e.seal),e.anchor?ht(e.anchor):null,e.tsa?ht(e.tsa):null,e.tsr?ht(e.tsr,!0):null,t?Promise.all([ht(t.statement),ht(t.sig),ht(t.signers),t.anchor?ht(t.anchor):null]):null]);return{report:n,sealText:o,anchorText:r,tsaText:a,tsrBytes:i,auth:l?{statement:l[0],sig:l[1],signers:l[2],anchorText:l[3]}:null}}var Bs={VERIFIED:"HALTED",HALTED:"VERIFIED"};function Ws(e,t){let n=t||e,o=Bs[n]||"VERIFIED",r=Bs[e]||"VERIFIED";return[{id:"report-outcome",target:"report",label:"Change the outcome in the report",field:"execution_outcome",from:n,to:o,text:[`"execution_outcome": "${n}"`,`"execution_outcome": "${o}"`]},{id:"report-model-calls",target:"report",label:"Add one AI model call to the report",field:"model_calls",from:"0",to:"1",text:['"model_calls": 0','"model_calls": 1']},{id:"seal-outcome",target:"seal",label:"Change the outcome in the receipt",field:"outcome",from:e,to:r}]}function Vs(e,t){if(t.target==="seal"){if(e.sealText!=null){let a=JSON.parse(e.sealText);if(a[t.field]!==t.from)throw new Error("The value to change is not in the receipt.");return{...e,sealText:JSON.stringify({...a,[t.field]:t.to},null,2),receiptText:e.receiptText?Ks(e.receiptText):e.receiptText}}if(e.receiptText!=null)return{...e,receiptText:Ks(e.receiptText)};throw new Error("The value to change is not in the receipt.")}let n=new TextDecoder().decode(e.report),[o,r]=t.text;if(!n.includes(o))throw new Error("The value to change is not in the report.");return{...e,report:new TextEncoder().encode(n.replace(o,r))}}function Ks(e){let t=JSON.parse(e),o=new TextDecoder().decode(Uint8Array.from(atob(t.payload),i=>i.charCodeAt(0))).replace(/"outcome":"(VERIFIED|STOPPED|UNKNOWN|FAILED)"/,(i,l)=>`"outcome":"${l==="VERIFIED"?"STOPPED":"VERIFIED"}"`),r=new TextEncoder().encode(o),a="";for(let i of r)a+=String.fromCharCode(i);return JSON.stringify({...t,payload:btoa(a)})}var Kd=`-----BEGIN CERTIFICATE----- +`)){if(!d.startsWith("— "))continue;let f=d.slice(2).split(" ");if(f.length<2)continue;let u=f.slice(0,-1).join(" "),v;try{v=xt(f.at(-1))}catch{continue}let m=At(v.slice(0,4));for(let b of t)if(!(c!==b.origin||u!==b.origin)&&b.logId.slice(0,8)===m&&await Ts(b,v.slice(4),l))return{origin:a[0],size:BigInt(a[1]),root:i,treeId:h}}return null}var yn=async e=>At(await bn(eo(Ce(e)))),Ic=(e,t)=>eo(`${Ss}\0${Ce({nonce:t,...e})}`);async function Cc(e){try{let t=Ns(new TextDecoder().decode(e));return t.length!==44||At(t.slice(0,12))!==Nc?null:t.slice(12)}catch{return null}}async function to(e,t,n,o){return no({seal_sha256:await yn(e)},t,n,o)}async function $s(e,t,n,o){let r;try{if(typeof e?.payload!="string")throw new Error("payload");r=xt(e.payload)}catch{return{ok:!1,reason:"anchor_malformed",steps:[{id:"anchorEntry",result:"fail"}]}}let a=At(await bn(r));return no({receipt_payload_sha256:a},t,n,o)}async function no(e,t,n,o){let r=[],a=(H,G,V={})=>({ok:H,reason:G,steps:r,...V});if(t==null)return a(!1,"anchor_missing");let i,l,p;try{if(t.schema!==Ss)throw new Error("schema");if(i=String(t.nonce),l=t.entry,p=Object.fromEntries(Object.keys(e).map(H=>[H,t[H]])),!ks.test(i)||!l||!Object.values(p).every(H=>typeof H=="string"&&ks.test(H)))throw new Error("format")}catch{return r.push({id:"anchorEntry",result:"fail"}),a(!1,"anchor_malformed")}let c=At(new Uint8Array(await Qn().digest("SHA-512",Ic(e,i))));if(Object.keys(e).some(H=>p[H]!==e[H])||t.statement_sha512!==c)return r.push({id:"anchorEntry",result:"fail"}),a(!1,"anchor_mismatch");let g,h,d,f,u,v,m,b,_,x,w,E;try{if(g=String(l.uuid),h=String(l.body),d=xt(h),f=JSON.parse(new TextDecoder().decode(d)),u=l.integratedTime,v=String(l.logID),m=l.logIndex,!Number.isInteger(u)||!Number.isInteger(m))throw new Error("int");b=xt(l.verification.signedEntryTimestamp),_=l.verification.inclusionProof,x=f.spec.data.hash,w=xt(f.spec.signature.content),E=xt(f.spec.signature.publicKey.content)}catch{return r.push({id:"anchorEntry",result:"fail"}),a(!1,"anchor_malformed")}let R={uuid:g,logIndex:m,integratedTime:u,logId:v},S=(H,G)=>(r.push({id:H,result:"fail"}),a(!1,G,R));if(f.kind!=="hashedrekord"||f.apiVersion!=="0.0.1")return S("anchorEntry","anchor_malformed");if(x?.algorithm!=="sha512"||x?.value!==c)return S("anchorEntry","anchor_mismatch");r.push({id:"anchorEntry",result:"pass"});let A=await Cc(E);if(!A||!lr(A,n))return S("anchorKey","anchor_key_mismatch");if(!await as(n,ir(c),w))return S("anchorKey","anchor_bad_signature");r.push({id:"anchorKey",result:"pass"});let L=o.find(H=>H.logId===v);if(!L)return S("anchorTime","anchor_unknown_log");let P=eo(Ce({body:h,integratedTime:u,logID:v,logIndex:m}));if(!await Ts(L,b,P))return S("anchorTime","anchor_bad_timestamp");r.push({id:"anchorTime",result:"pass"});let $=await Ac(d);if(!g.endsWith(At($)))return S("anchorInclusion","anchor_bad_inclusion");let O,M,k;try{k=BigInt(_.treeSize),O=await Rc(_.logIndex,_.treeSize,$,_.hashes.map(ir)),M=ir(_.rootHash)}catch{return S("anchorInclusion","anchor_malformed")}if(!O||!lr(O,M))return S("anchorInclusion","anchor_bad_inclusion");r.push({id:"anchorInclusion",result:"pass"});let B=await Mc(String(_.checkpoint),[L]);return!B||!lr(B.root,M)||B.size!==k||g.length===80&&B.treeId!==null&&g.slice(0,16)!==B.treeId.toString(16).padStart(16,"0")?S("anchorCheckpoint","anchor_bad_checkpoint"):(r.push({id:"anchorCheckpoint",result:"pass"}),a(!0,null,R))}var Pc=(e,t)=>!!(t&&e?.scope?.seal_key_ids?.includes(t.key_id));function As(e){if(e==null||et(e)!==null)return null;try{return JSON.parse(e)}catch{return null}}async function Rs(e,t,{requireAnchor:n=!1,requireAuthorization:o=!1,logKeys:r=null}={}){let a=await ps(e.sealText,e.report,t,"report.json"),i=[...a.steps],l=(_,x,w={})=>({...a,ok:_,reason:x,steps:i,sealOk:a.ok,...w});if(!a.ok)return l(!1,a.reason);let p=r||[await vn(mn)],c=_=>{let x=Gt(t).filter(w=>w.key_id===_&&w.status==="active");return x.length===1?Pe(x[0].public_key):null},g=null,h=null,d=null;if(e.auth){let _=await bs(e.auth.statement,e.auth.sig);if(i=[...i,..._.steps],!_.ok)return l(!1,_.reason);let x=null;try{x=JSON.parse(new TextDecoder().decode(e.report))}catch{x=null}d=x?.started_at??null;let w=ys(a.seal,x,_),E={auth_not_referenced:"authRef",auth_reference_mismatch:"authRef",auth_scope_mismatch:"authScope",auth_bundle_mismatch:"authBundle"};if(w){let R=E[w]||"authRef";for(let S of["authRef","authScope","authBundle"]){if(S===R)break;i=[...i,{id:S,result:"pass"}]}return i=[...i,{id:R,result:"fail"}],l(!1,w)}if(i=[...i,{id:"authRef",result:"pass"},{id:"authScope",result:"pass"},{id:"authBundle",result:"pass"}],g={login:_.login,fingerprint:_.fingerprint,sha256:_.sha256,publicKey:_.publicKey},e.auth.anchorText!=null){let R=As(e.auth.anchorText),A=Pc(_.statement,R)?c(R.key_id):null,L=R?A?await no({run_authorization_sha256:_.sha256,signature_sha256:_.signatureSha256},R,A,p):{ok:!1,reason:"anchor_key_mismatch"}:{ok:!1,reason:"anchor_malformed"};if(i=[...i,{id:"authLogged",result:L.ok?"pass":"fail"}],!L.ok)return l(!1,`authorization_${L.reason}`,{authorizedBy:g});h=L.integratedTime}}else if(o)return i=[...i,{id:"authShape",result:"fail"}],l(!1,"auth_missing");if(e.anchorText==null){let _=sr(h,d,null);return n?(i=[...i,{id:"anchorEntry",result:"fail"}],l(!1,"anchor_missing",{authorizedBy:g,timing:_})):l(!0,null,{authorizedBy:g,timing:_})}let f=As(e.anchorText);if(!f)return i=[...i,{id:"anchorEntry",result:"fail"}],l(!1,"anchor_malformed",{authorizedBy:g});let u=c(a.seal.key_id),v=await to(a.seal,f,u,p);i=[...i,...v.steps];let m=sr(h,d,v.ok?v.integratedTime:null),b=_s(h,v.ok?v.integratedTime:null);return l(v.ok,v.reason,{authorizedBy:g,timing:m,authAnchorTime:h,authorizationVsSeal:b,anchor:v.ok?{uuid:v.uuid,logIndex:v.logIndex,integratedTime:v.integratedTime,logId:v.logId}:null})}var Oc="https://in-toto.io/Statement/v1",Lc="https://openadapt.ai/record/run/v1",Ms="application/vnd.in-toto+json",zc="openadapt.receipt-card/v1",Dc="openadapt.receipt-openings/v1",Fc="openadapt.receipt-keys/v1",Ds="openadapt.public-disclosure/v1",Hc="openadapt.receipt-commitment/v1",Is=256,_n=2**53-1,jc=65536,Gc=["this_computer","customer_key","openadapt_cloud","public_log","demo"],Cs=["this_computer","customer_key","openadapt_cloud","public_log"],Uc={this_computer:"Signed by this computer",customer_key:"Signed by {org}'s key",openadapt_cloud:"Countersigned by OpenAdapt Cloud",public_log:"Logged publicly",demo:"Demo key: checks only in this demo"},Bc={unknown_signer:"Not verified: unknown signer",unknown_role:"Not verified: unknown signer role",unknown_schema:"Not verified: unknown receipt format",unsigned:"Not verified: no signature",revoked_key:"Not verified: the signing key was revoked",bad_signature:"Not verified: the receipt was changed after it was signed",mixed_demo:"Not verified: a demo key signed alongside a real one",embedded_content:"Not verified: the receipt holds embedded content",opening_mismatch:"Not verified: a disclosed value doesn't match the receipt",disclosure_not_allowed:"Not verified: the card reveals a field it may not",inconsistent:"Not verified: the receipt contradicts itself",malformed:"Not verified: malformed receipt",verifier_unavailable:"Not verified: this browser can't check Ed25519 signatures"},Kc=e=>Bc[e]||"Not verified",Rt=/^[a-f0-9]{64}$/,Wc=/^[a-f0-9]{64}$/,Vc=/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:00:00Z$/,oo=/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$/,qc=/^prog-[a-f0-9]{16}$/,Zc=/^[a-z][a-z0-9_]{0,47}$/,Yc=/^[A-Za-z0-9 ._-]{1,48}$/,cr=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Fs={program_name:/^[A-Za-z0-9 ._-]{1,48}$/,flow_version:/^[0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,6}$/,github_login:/^[A-Za-z0-9-]{1,39}$/,run_id:/^[A-Za-z0-9._:-]{1,128}$/},Jc={[Ds]:["program_name","flow_version","github_login"]},Xc=["VERIFIED","STOPPED","UNKNOWN","FAILED"],Qc=["report.json","report.canonical","bundle","evidence","payload"],ed=["application/json","application/cbor","text/plain","text/csv","application/pdf","application/octet-stream"],td=["tx_receipt","write_receipt"],nd=["ehr","payer_portal","bank","erp","crm","government_portal","email","other"],od=["portal_read_back","api","acknowledgment_message"],Hs=["portal_read_back","api"],rd=["sent","acknowledged","recorded_as_intended","recorded_differently"],ad=["read_back","acknowledgment","none"],sd=["each_item","problems_only","not_gated"],id=["person","agent","none"],ld={sent:["rejected_by_counterparty","ambiguous_key","receiver_unreachable","not_found","no_answer_by_deadline"],acknowledged:["ambiguous_key","not_found","no_answer_by_deadline"],recorded_as_intended:["conflicting_report"],recorded_differently:["conflicting_report"]},cd=/^(?:counterparty|observed_at|reason|field\.[0-9]{1,2})$/,dd=/^(?:principal|scope|approved_at)$/,pd=/^confirmations\.([0-9]{1,2})\.(counterparty|observed_at|reason|field\.[0-9]{1,2})$/,ud=/^approval\.(principal|scope|approved_at)$/,fd={counterparty:/^(?:ehr|payer_portal|bank|erp|crm|government_portal|email|other):cp-[a-f0-9]{16}$/,observed_at:oo,reason:/^(?:rejected_by_counterparty|conflicting_report|ambiguous_key|receiver_unreachable|not_found|no_answer_by_deadline)$/,field:/^[a-z][a-z0-9_]{0,31}:[a-f0-9]{64}(?::differs)?$/,principal:/^(?:person|agent):pr-[a-f0-9]{16}$/,scope:Rt,approved_at:oo},hd=["gui","api"],gd=["write","irreversible_write"],md=["confirmed","refuted","not_checked"],bd=["read_back","same_screen","none"],vd=["effect_not_declared","approved_unverified","field_values","postconditions","uncertain"],yd="openadapt.evidence-scope/v1",_d=["unchecked","same_screen","reopened","separate_session","system_of_record","counterparty_confirmed"],xd=["VERIFIED","SHOWN","CONFIRMED","ATTESTED","RECORDED"],Ps={post_save_screen:"same_screen",reopened_record:"reopened",separate_session:"separate_session",fresh_reload:"separate_session",system_api:"system_of_record",activity_log:"system_of_record",db_frame:"system_of_record",owned_connection:"system_of_record"},kd=["none","browser_network","http_proxy","api_client","db_connection"],wd=["http","graphql","fhir","sql","websocket","grpc","smtp"],Sd=["server_side_async_effects","outbound_effects","changes_after_read_back","fields_not_read","other_records","other_actors","read_back_time"],Ed=["server_side_async_effects","outbound_effects"],Nd=720*3600,Os=/^(?!.*:\/\/)[A-Za-z0-9][A-Za-z0-9._:@+/ -]{0,127}$/,Td={VERIFIED:["VERIFIED"],CONFIRMED:["VERIFIED"],SHOWN:["UNKNOWN","STOPPED","FAILED"],ATTESTED:["UNKNOWN","STOPPED","FAILED"],RECORDED:["UNKNOWN","STOPPED","FAILED"]},I=class extends Error{constructor(t,n=""){super(n||t),this.reason=t}},Ls=(e,t="")=>({ok:!1,reason:e,detail:t,signerLines:[Kc(e)],outcome:null,demo:!1,disclosed:{}}),$d=/data:[a-z]+\//i,Ad=/[a-z][a-z0-9+.-]*:\/\//i,Rd=/[A-Za-z0-9+/_-]{96,}={0,2}/,Md=["iVBORw0KGgo","/9j/","R0lGOD","UklGR","PHN2Zy"];function dr(e){let t=e.toLowerCase();return[...e].length>256||$d.test(e)||Ad.test(e)||Rd.test(e)||Md.some(n=>e.startsWith(n))||t.includes("e!==null&&typeof e=="object"&&!Array.isArray(e);function De(e,t,n=[],o=""){if(!je(e))throw new I("malformed",`${o} is an object`);for(let r of Object.keys(e))if(!t.includes(r)&&!n.includes(r))throw new I("malformed",`${o}.${r} is not a field`);for(let r of t)if(!(r in e))throw new I("malformed",`${o}.${r} is missing`)}function lt(e,t,n,o){if(!Number.isInteger(e)||en)throw new I("malformed",`${o} is an integer from ${t} to ${n}`)}function J(e,t,n){if(!(typeof e=="string"&&(Array.isArray(t)?t.includes(e):t.test(e))))throw new I("malformed",`${n} is not valid`)}function Id(e,t){De(e,["required","confirmed"],[],t),lt(e.required,0,_n,`${t}.required`),lt(e.confirmed,0,_n,`${t}.confirmed`)}function Cd(e){if(De(e,["_type","subject","predicateType","predicate"],[],"$"),!Array.isArray(e.subject)||e.subject.length<1||e.subject.length>4)throw new I("malformed","subject has 1 to 4 entries");for(let[o,r]of e.subject.entries())De(r,["name","digest"],["media_type"],`subject[${o}]`),J(r.name,Qc,`subject[${o}].name`),"media_type"in r&&J(r.media_type,ed,`subject[${o}].media_type`),De(r.digest,["sha256"],[],`subject[${o}].digest`),J(r.digest.sha256,Rt,`subject[${o}].digest.sha256`);let t=e.predicate;if(De(t,["program","started_hour","outcome","steps","lines","checks","model_calls","disclosure"],["reason_code","confirmations","approval","evidence_scope"],"predicate"),De(t.program,["id","version_sha256"],[],"predicate.program"),J(t.program.id,qc,"predicate.program.id"),J(t.program.version_sha256,Rt,"predicate.program.version_sha256"),J(t.started_hour,Vc,"predicate.started_hour"),J(t.outcome,Xc,"predicate.outcome"),t.reason_code!=null&&J(t.reason_code,Zc,"predicate.reason_code"),De(t.steps,["total","ok"],[],"predicate.steps"),lt(t.steps.total,0,_n,"predicate.steps.total"),lt(t.steps.ok,0,_n,"predicate.steps.ok"),!Array.isArray(t.lines)||t.lines.length>Is)throw new I("malformed","predicate.lines");for(let[o,r]of t.lines.entries()){let a=`predicate.lines[${o}]`;if(De(r,["step","target_kind","operation","check","strength","not_checked"],["evidence"],a),"evidence"in r&&(De(r.evidence,["kind","sha256"],[],`${a}.evidence`),J(r.evidence.kind,td,`${a}.evidence.kind`),J(r.evidence.sha256,Rt,`${a}.evidence.sha256`)),lt(r.step,0,1e4,`${a}.step`),J(r.target_kind,hd,`${a}.target_kind`),J(r.operation,gd,`${a}.operation`),J(r.check,md,`${a}.check`),J(r.strength,bd,`${a}.strength`),!Array.isArray(r.not_checked)||r.not_checked.length>5)throw new I("malformed",`${a}.not_checked`);r.not_checked.forEach((i,l)=>J(i,vd,`${a}.not_checked[${l}]`))}let n=t.checks;De(n,["identity","postconditions","effects","authorization","lines_confirmed","lines_refuted","lines_not_checked"],[],"predicate.checks");for(let o of["identity","postconditions","effects","authorization"])Id(n[o],`predicate.checks.${o}`);for(let o of["lines_confirmed","lines_refuted","lines_not_checked"])lt(n[o],0,Is,`predicate.checks.${o}`);if(lt(t.model_calls,0,_n,"predicate.model_calls"),De(t.disclosure,["version","commitments"],[],"predicate.disclosure"),J(t.disclosure.version,[Ds],"predicate.disclosure.version"),!je(t.disclosure.commitments)||Object.keys(t.disclosure.commitments).length>16)throw new I("malformed","predicate.disclosure.commitments");for(let o of Object.values(t.disclosure.commitments))if(typeof o!="string")throw new I("malformed","a commitment is a string");if("confirmations"in t){if(!Array.isArray(t.confirmations)||t.confirmations.length>64)throw new I("malformed","predicate.confirmations");for(let[o,r]of t.confirmations.entries()){let a=`predicate.confirmations[${o}]`;if(De(r,["kind","system_kind","read_method","state","strength","differing_count","commitments"],["for_step"],a),J(r.kind,["counterparty_confirmation"],`${a}.kind`),r.for_step!=null&<(r.for_step,0,1e4,`${a}.for_step`),J(r.system_kind,nd,`${a}.system_kind`),J(r.read_method,od,`${a}.read_method`),J(r.state,rd,`${a}.state`),J(r.strength,ad,`${a}.strength`),lt(r.differing_count,0,64,`${a}.differing_count`),!je(r.commitments)||Object.keys(r.commitments).length<2||Object.keys(r.commitments).length>34)throw new I("malformed",`${a}.commitments`)}}if("approval"in t&&(De(t.approval,["mode","approver_kind","commitments"],[],"predicate.approval"),J(t.approval.mode,sd,"predicate.approval.mode"),J(t.approval.approver_kind,id,"predicate.approval.approver_kind"),!je(t.approval.commitments)||Object.keys(t.approval.commitments).length>3))throw new I("malformed","predicate.approval.commitments");if("evidence_scope"in t){let o=t.evidence_scope;De(o,["schema","check_level","word","wire","not_covered"],["basis","read_back_at","recheck_window_s","agent_used","verifier_adapter"],"predicate.evidence_scope"),J(o.schema,[yd],"predicate.evidence_scope.schema"),J(o.check_level,_d,"predicate.evidence_scope.check_level"),J(o.word,xd,"predicate.evidence_scope.word"),"basis"in o&&J(o.basis,Object.keys(Ps),"predicate.evidence_scope.basis"),De(o.wire,["channel","protocols_parsed"],[],"predicate.evidence_scope.wire"),J(o.wire.channel,kd,"predicate.evidence_scope.wire.channel");let r=o.wire.protocols_parsed;if(!Array.isArray(r)||r.length>7)throw new I("malformed","predicate.evidence_scope.wire.protocols_parsed");if(r.forEach((a,i)=>J(a,wd,`predicate.evidence_scope.wire.protocols_parsed[${i}]`)),new Set(r).size!==r.length)throw new I("malformed","wire.protocols_parsed repeats a protocol");if(o.wire.channel==="none"&&r.length)throw new I("malformed","a run that watched no wire parsed no protocol");if("read_back_at"in o&&J(o.read_back_at,oo,"predicate.evidence_scope.read_back_at"),"recheck_window_s"in o&<(o.recheck_window_s,0,Nd,"predicate.evidence_scope.recheck_window_s"),"agent_used"in o&&J(o.agent_used,Os,"predicate.evidence_scope.agent_used"),"verifier_adapter"in o&&J(o.verifier_adapter,Os,"predicate.evidence_scope.verifier_adapter"),!Array.isArray(o.not_covered)||o.not_covered.length<2||o.not_covered.length>7)throw new I("malformed","predicate.evidence_scope.not_covered");if(o.not_covered.forEach((a,i)=>J(a,Sd,`predicate.evidence_scope.not_covered[${i}]`)),new Set(o.not_covered).size!==o.not_covered.length)throw new I("malformed","not_covered repeats a code");if(!Ed.every(a=>o.not_covered.includes(a)))throw new I("malformed","not_covered must list server_side_async_effects and outbound_effects");if(o.basis!=null&&Ps[o.basis]!==o.check_level)throw new I("malformed",`basis ${o.basis} does not reach ${o.check_level}`);if(o.word==="VERIFIED"){if(!["same_screen","reopened","separate_session","system_of_record"].includes(o.check_level)||o.basis==null)throw new I("malformed","VERIFIED needs level 1 to 4 and a basis");if(o.read_back_at==null&&!o.not_covered.includes("read_back_time"))throw new I("malformed","VERIFIED needs read_back_at, or says it has none")}if(o.word==="SHOWN"&&!["same_screen","reopened"].includes(o.check_level))throw new I("malformed","SHOWN is a level 1 or 2 re-read of the acting screen");if(o.word==="SHOWN"&&o.basis!=null)throw new I("malformed","an older SHOWN block names no basis");if(o.word==="CONFIRMED"&&o.check_level!=="counterparty_confirmed")throw new I("malformed","CONFIRMED is level 5, the counterparty acknowledgment");if(o.read_back_at!=null&&o.not_covered.includes("read_back_time"))throw new I("malformed","a block with read_back_at covers the read-back time");if(o.recheck_window_s!=null&&o.read_back_at==null)throw new I("malformed","a recheck window needs read_back_at")}return{...e,predicate:{...t,reason_code:t.reason_code??null}}}function Pd(e){let t=e.predicate,n=e.subject.map(a=>a.name);if(new Set(n).size!==n.length||!(n.includes("report.json")||n.includes("report.canonical")))return"subject names repeat, or the report is missing";for(let a of e.subject)if(a.name==="payload"!="media_type"in a)return"only the payload subject has a media type, and it always has one";if(t.approval){let a=t.approval;for(let[i,l]of Object.entries(a.commitments))if(!dd.test(i)||!Rt.test(l))return`approval commitment ${i} is not a known field`;if(a.mode==="not_gated"&&a.approver_kind!=="none")return"a not_gated run names no approver";if(a.approver_kind==="none"){if(Object.keys(a.commitments).length)return"an approval with no approver commits to nothing"}else if(!("principal"in a.commitments&&"scope"in a.commitments))return"an approval names its approver's principal and scope"}for(let[a,i]of Object.entries(t.disclosure.commitments))if(!Fs[a]||!Rt.test(i))return`disclosure path ${a} is not a known field`;if(t.steps.ok>t.steps.total)return"steps.ok is more than steps.total";for(let a of["identity","postconditions","effects","authorization"])if(t.checks[a].confirmed>t.checks[a].required)return`checks.${a} confirms more than it requires`;let o={confirmed:0,refuted:0,not_checked:0};for(let a of t.lines){if(o[a.check]+=1,a.check==="confirmed"&&a.strength==="none")return"a confirmed line has no strength";if(new Set(a.not_checked).size!==a.not_checked.length)return"a line repeats a not_checked code"}if(t.checks.lines_confirmed!==o.confirmed||t.checks.lines_refuted!==o.refuted||t.checks.lines_not_checked!==o.not_checked)return"check counts disagree with the lines";if(t.outcome==="VERIFIED"&&o.refuted)return"a VERIFIED receipt has a refuted line";if(t.evidence_scope&&!Td[t.evidence_scope.word].includes(t.outcome))return"the evidence scope's word disagrees with the outcome";let r=t.lines.map(a=>a.step);for(let a=1;a0)return"differing_count disagrees with the state";if(!("counterparty"in a.commitments&&"observed_at"in a.commitments))return"a confirmation commits to its counterparty and observed_at";for(let[l,p]of Object.entries(a.commitments))if(!cd.test(l)||!Rt.test(p))return`confirmation commitment ${l} is not a known field`;let i=Object.keys(a.commitments).filter(l=>l.startsWith("field.")).length;if(a.differing_count>i)return"more differing fields than observed fields"}return null}var Ut=e=>new TextEncoder().encode(e);function js(...e){let t=new Uint8Array(e.reduce((o,r)=>o+r.length,0)),n=0;for(let o of e)t.set(o,n),n+=o.length;return t}var Od=e=>Uint8Array.from(e.match(/../g),t=>parseInt(t,16));async function Ld(e,t,n){let o=new Uint8Array([0]);return Re(js(Ut(Hc),o,Ut(e),o,Od(t),o,Ut(Ce(n))))}function zd(e,t){let n=pd.exec(e)||ud.exec(e);if(n){let r=(n[2]||n[1]).split(".")[0];return typeof t=="string"&&fd[r].test(t)?null:`${e} does not match its field's pattern`}let o=Fs[e];return o?typeof t!="string"?`${e} is not a string`:dr(t)?`${e} holds embedded content`:o.test(t)?null:`${e} does not match its field's pattern`:`${e} is not a disclosure field`}async function zs(e,t,n){if(!je(e))throw new I("malformed","openings are an object");let o=ro(e);if(o)throw new I("embedded_content",o);let r={};for(let[a,i]of Object.entries(e)){if(n&&!n.includes(a))throw new I("disclosure_not_allowed",a);if(!je(i)||Object.keys(i).length!==2||!("salt"in i)||!("value"in i))throw new I("malformed",`the opening for ${a}`);let l=zd(a,i.value);if(l)throw new I("malformed",l);if(!(typeof i.salt=="string"&&Wc.test(i.salt)))throw new I("malformed",`the salt for ${a}`);if(t[a]!==await Ld(a,i.salt,i.value))throw new I("opening_mismatch",a);r[a]=i.value}return r}async function Dd(e){if(!je(e)||e.schema!==Fc)throw new I("unknown_schema","not an openadapt.receipt-keys/v1 registry");if(!Array.isArray(e.keys))throw new I("malformed","a registry has a keys list");let t=[];for(let n of e.keys){if(!je(n))throw new I("malformed","a registry entry is an object");if(Object.keys(n).some(a=>!["key_id","public_key","role","status","revoked_at","org"].includes(a)))throw new I("malformed","a registry entry has an unknown field");if(!Gc.includes(n.role))throw new I("unknown_role",`unknown signer role ${n.role}`);if(typeof n.public_key!="string"||!cr.test(n.public_key))throw new I("malformed","a public key is base64");let o=Pe(n.public_key);if(o.length!==32||n.key_id!==`seal-ed25519-${(await Re(o)).slice(0,16)}`)throw new I("malformed","a key id doesn't match its public key");let r=n.status??"active";if(!["active","revoked"].includes(r)||r==="revoked"&&!(typeof n.revoked_at=="string"&&oo.test(n.revoked_at)))throw new I("malformed","a key is active, or revoked with revoked_at");if(n.role==="customer_key"&&!(typeof n.org=="string"&&Yc.test(n.org)))throw new I("malformed","a customer key names its org");t.push({keyId:n.key_id,raw:o,role:n.role,status:r,revokedAt:r==="revoked"?n.revoked_at:null,org:n.role==="customer_key"?n.org:null})}if(new Set(t.map(n=>n.keyId)).size!==t.length)throw new I("malformed","a registry lists one key id twice");return t}function Fd(e,t){let n=Ut(e);return js(Ut(`DSSEv1 ${n.length} `),n,Ut(` ${t.length} `),t)}var Hd=e=>je(e)&&e.schema===zc;function jd(e){if(et(e)!==null)throw new I("malformed","duplicate key");try{return JSON.parse(e)}catch{throw new I("malformed","the payload is not JSON")}}async function Gd(e,t,n){let o;try{o=await globalThis.crypto.subtle.importKey("raw",e,{name:"Ed25519"},!1,["verify"])}catch{throw new I("verifier_unavailable")}return globalThis.crypto.subtle.verify({name:"Ed25519"},o,t,n)}async function Gs(e,t,{openings:n=null}={}){try{let o=await Dd(t),r=null,a=null,i=e;if(Hd(e)){if(Object.keys(e).sort().join(",")!=="disclosure_version,envelope,openings,schema")throw new I("malformed","a card has exactly four fields");if(a=Jc[e.disclosure_version],!a)throw new I("unknown_schema","unknown public disclosure version");if(r=e.openings,!je(r))throw new I("malformed","a card's openings are an object");if(i=e.envelope,n!=null)throw new I("malformed","a card carries its own openings")}if(!je(i)||Object.keys(i).sort().join(",")!=="payload,payloadType,signatures")throw new I("malformed","a DSSE envelope has payloadType, payload, signatures");if(i.payloadType!==Ms)throw new I("unknown_schema","the payload is not an in-toto statement");if(typeof i.payload!="string"||!cr.test(i.payload))throw new I("malformed","the payload is not base64");let l=Pe(i.payload);if(l.length>jc)throw new I("malformed","the payload is too large");let p=i.signatures;if(!Array.isArray(p)||!p.length)throw new I("unsigned");let c=new Map(o.map($=>[$.keyId,$])),g=Fd(Ms,l),h=[],d=new Set;for(let $ of p){if(!je($)||Object.keys($).sort().join(",")!=="keyid,sig")throw new I("malformed","a signature has keyid and sig");let O=$.keyid;if(typeof O!="string"||d.has(O))throw new I("malformed","a signature's keyid is missing or repeated");d.add(O);let M=c.get(O);if(!M)throw new I("unknown_signer",`${O} is not in the pinned registry`);if(typeof $.sig!="string"||!cr.test($.sig))throw new I("bad_signature",`${O}'s signature`);if(!await Gd(M.raw,Pe($.sig),g))throw new I("bad_signature",`${O}'s signature`);if(M.status==="revoked")throw new I("revoked_key",`${O} was revoked at ${M.revokedAt}`);h.push({keyId:O,role:M.role,line:Uc[M.role].replace("{org}",M.org||"the customer")})}let f=new Set(h.map($=>$.role)),u=f.has("demo");if(u&&f.size!==1)throw new I("mixed_demo");let v;try{v=new TextDecoder("utf-8",{fatal:!0}).decode(l)}catch{throw new I("malformed","the payload is not UTF-8")}let m=jd(v);if(!je(m))throw new I("malformed","the payload is not an object");if(m._type!==Oc||m.predicateType!==Lc)throw new I("unknown_schema","not a record/run/v1 statement");let b=Object.fromEntries(Object.entries(m).filter(([$])=>$!=="_type"&&$!=="predicateType")),_=ro(b);if(_)throw new I("embedded_content",_);let x=Cd(m);if(Ce(x)!==v)throw new I("malformed","the payload is not canonical JSON");let w=Pd(x);if(w)throw new I("inconsistent",w);let E={...x.predicate.disclosure.commitments};for(let[$,O]of(x.predicate.confirmations||[]).entries())for(let[M,k]of Object.entries(O.commitments))E[`confirmations.${$}.${M}`]=k;if(x.predicate.approval)for(let[$,O]of Object.entries(x.predicate.approval.commitments))E[`approval.${$}`]=O;let R={},S=!1;if(r)R=await zs(r,E,a);else if(n!=null){if(!je(n)||Object.keys(n).sort().join(",")!=="openings,payload_sha256,schema")throw new I("malformed","a private openings file has three fields");if(n.schema!==Dc)throw new I("unknown_schema","not an openadapt.receipt-openings/v1 file");if(n.payload_sha256!==await Re(l))throw new I("opening_mismatch","the openings belong to another receipt");R=await zs(n.openings,E,null),S=!0;for(let[$,O]of(x.predicate.confirmations||[]).entries()){let M=R[`confirmations.${$}.reason`];if(M!=null&&!ld[O.state].includes(M))throw new I("inconsistent",`a ${O.state} confirmation can't have reason ${M}`)}}let A=[...h].sort(($,O)=>Cs.indexOf($.role)-Cs.indexOf(O.role)),L=[...new Set(A.map($=>$.line))],P=x.predicate.confirmations||[];return{ok:!0,reason:null,detail:"",signers:A,signerLines:L,confirmationLines:P.map(($,O)=>Bd($,R[`confirmations.${O}.observed_at`])),independent:P.map($=>Hs.includes($.read_method)),approvalLine:Ud(x.predicate.approval),outcome:x.predicate.outcome,demo:u,disclosed:R,private:S,statement:x}}catch(o){return o instanceof I?Ls(o.reason,o.message):Ls("malformed",String(o?.message||o))}}function Ud(e){return e?e.mode==="not_gated"?"Not gated: no approval was required for these writes":e.approver_kind==="none"?`Approval required for ${e.mode==="each_item"?"each item":"items that fail a check"}; no item was approved`:`Approved by ${e.approver_kind==="person"?"a person":"an agent delegate"}: ${e.mode==="each_item"?"each item":"items that failed a check"}`:"No approval recorded"}function Bd(e,t){let n=t?` at ${t}`:"";return e.state==="recorded_as_intended"?`Confirmed in the other party's system${n}`:e.state==="recorded_differently"?`Recorded differently in the other party's system${n}: ${e.differing_count} ${e.differing_count===1?"field differs":"fields differ"}`:e.state==="acknowledged"?`Acknowledged by the other party${n}`:`Sent to the other party${n}, not confirmed`}async function ht(e,t=!1){let n=await fetch(e,{cache:"no-store"});if(!n.ok)throw new Error(`${e}: ${n.status}`);return t?new Uint8Array(await n.arrayBuffer()):n.text()}async function Us(e,t=null){let[n,o,r,a,i,l]=await Promise.all([ht(e.report,!0),ht(e.seal),e.anchor?ht(e.anchor):null,e.tsa?ht(e.tsa):null,e.tsr?ht(e.tsr,!0):null,t?Promise.all([ht(t.statement),ht(t.sig),ht(t.signers),t.anchor?ht(t.anchor):null]):null]);return{report:n,sealText:o,anchorText:r,tsaText:a,tsrBytes:i,auth:l?{statement:l[0],sig:l[1],signers:l[2],anchorText:l[3]}:null}}var Bs={VERIFIED:"HALTED",HALTED:"VERIFIED"};function Ws(e,t){let n=t||e,o=Bs[n]||"VERIFIED",r=Bs[e]||"VERIFIED";return[{id:"report-outcome",target:"report",label:"Change the outcome in the report",field:"execution_outcome",from:n,to:o,text:[`"execution_outcome": "${n}"`,`"execution_outcome": "${o}"`]},{id:"report-model-calls",target:"report",label:"Add one AI model call to the report",field:"model_calls",from:"0",to:"1",text:['"model_calls": 0','"model_calls": 1']},{id:"seal-outcome",target:"seal",label:"Change the outcome in the receipt",field:"outcome",from:e,to:r}]}function Vs(e,t){if(t.target==="seal"){if(e.sealText!=null){let a=JSON.parse(e.sealText);if(a[t.field]!==t.from)throw new Error("The value to change is not in the receipt.");return{...e,sealText:JSON.stringify({...a,[t.field]:t.to},null,2),receiptText:e.receiptText?Ks(e.receiptText):e.receiptText}}if(e.receiptText!=null)return{...e,receiptText:Ks(e.receiptText)};throw new Error("The value to change is not in the receipt.")}let n=new TextDecoder().decode(e.report),[o,r]=t.text;if(!n.includes(o))throw new Error("The value to change is not in the report.");return{...e,report:new TextEncoder().encode(n.replace(o,r))}}function Ks(e){let t=JSON.parse(e),o=new TextDecoder().decode(Uint8Array.from(atob(t.payload),i=>i.charCodeAt(0))).replace(/"outcome":"(VERIFIED|STOPPED|UNKNOWN|FAILED)"/,(i,l)=>`"outcome":"${l==="VERIFIED"?"STOPPED":"VERIFIED"}"`),r=new TextEncoder().encode(o),a="";for(let i of r)a+=String.fromCharCode(i);return JSON.stringify({...t,payload:btoa(a)})}var Kd=`-----BEGIN CERTIFICATE----- MIIB9zCCAXygAwIBAgIUV7f0GLDOoEzIh8LXSW80OJiUp14wCgYIKoZIzj0EAwMw OTEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MSAwHgYDVQQDExdzaWdzdG9yZS10c2Et c2VsZnNpZ25lZDAeFw0yNTA0MDgwNjU5NDNaFw0zNTA0MDYwNjU5NDNaMDkxFTAT @@ -36,7 +36,7 @@ B4nOvzAKBggqhkjOPQQDAwNpADBmAjEAwGEGrfGZR1cen1R8/DTVMI943LssZmJR tDp/i7SfGHmGRP6gRbuj9vOK3b67Z0QQAjEAuT2H673LQEaHTcyQSZrkp4mX7Wwk mF+sVbkYY5mXN+RMH13KUEHHOqASaemYWK/E ------END CERTIFICATE-----`,Wd="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"},qs={[Ne.sha256]:"SHA-256",[Ne.sha384]:"SHA-384",[Ne.sha512]:"SHA-512"},Vd={[Ne.ecdsaSha256]:"SHA-256",[Ne.ecdsaSha384]:"SHA-384",[Ne.ecdsaSha512]:"SHA-512"},qd={[Ne.p256]:["P-256",32],[Ne.p384]:["P-384",48]},ao=class extends Error{},qe=e=>{throw new ao(e)};function Bt(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 ie(e){let t=[],n=e.start;for(;ne&&e.tag===t?e:qe(`tag ${t}`);function Be(e){ye(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 ur(e){let t=Zd(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 Yd=e=>Array.from(e,t=>t.toString(16).padStart(2,"0")).join(""),pr=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]);function Jd(e){let t=String(e).replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=atob(t);return Uint8Array.from(n,o=>o.charCodeAt(0))}function Js(e){let[t,n,o]=ie(ye(e,48)),r=ie(ye(t,48)),a=r[0].tag===160?1:0,i=r[a+2],l=ie(r[a+3]),p=r[a+4],c=ye(r[a+5],48),[g]=ie(c),[h,d]=ie(g),f=!1;for(let u of r.slice(a+6))if(u.tag===163)for(let v of ie(ie(u)[0])){let m=ie(v);if(Be(m[0])!==Ne.extKeyUsage)continue;f=ie(Bt(m.at(-1).content,0)).some(_=>Be(_)===Ne.timeStamping)}return{tbs:t.raw,sigAlg:Be(ie(n)[0]),signature:ye(o,3).content.subarray(1),issuer:i.raw,subject:p.raw,notBefore:ur(l[0]),notAfter:ur(l[1]),spki:c.raw,keyAlg:Be(h),curve:d&&d.tag===6?Be(d):null,timestamping:f,serial:r[a].content}}function Xd(e,t){let[n,o]=ie(ye(Bt(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 p=new Uint8Array(t);return p.set(l,t-l.length),p},a=new Uint8Array(t*2);return a.set(r(n),0),a.set(r(o),t),a}async function Zs(e,t,n,o){let r=Vd[t],a=qd[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,Xd(n,a[1]),o)}function Qd(e){let t=ie(ye(Bt(e,0),48));Be(t[0])!==Ne.signedData&&qe("not signed data");let n=ie(ye(ie(ye(t[1],160))[0],48)),o=ie(ye(n[2],48));Be(o[0])!==Ne.tstInfo&&qe("not a timestamp");let r=ye(ie(ye(o[1],160))[0],4).content,a=3,i=[];if(n[a]&&n[a].tag===160){for(let w of ie(n[a]))i.push(Js(w));a+=1}n[a]&&n[a].tag===161&&(a+=1);let l=ie(ye(n[a],49));l.length!==1&&qe("signers");let p=ie(ye(l[0],48)),c=p[1],g=Be(ie(p[2])[0]),h=ye(p[3],160),d=Be(ie(p[4])[0]),f=ye(p[5],4).content,u={};for(let w of ie(h)){let[E,R]=ie(w);u[Be(E)]=ie(R)[0]}let v=ie(ye(Bt(r,0),48)),[m,b]=ie(ye(v[2],48)),_=c.tag===48?ie(c)[1].content:null,x=Uint8Array.from(h.raw);return x[0]=49,{eContent:r,certs:i,signerSerial:_,digestAlg:g,sigAlg:d,signature:f,signedBytes:x,contentType:u[Ne.contentType]?Be(u[Ne.contentType]):null,messageDigest:u[Ne.messageDigest]?ye(u[Ne.messageDigest],4).content:null,policy:Be(v[1]),imprintAlg:Be(ie(m)[0]),imprint:Yd(ye(b,4).content),genTime:ur(v[4])}}async function ep(e,t=Kd){let n;try{n=Qd(e)}catch{return{ok:!1,reason:"tsa_malformed"}}let o={genTime:n.genTime,imprint:n.imprint,imprintAlg:qs[n.imprintAlg]||n.imprintAlg},r=(a,i)=>({ok:a,reason:i,...o});try{let a=qs[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(!pr(i,n.messageDigest))return r(!1,"tsa_content_mismatch");let l=Js(Bt(Jd(t),0)),p=n.certs.find(g=>n.signerSerial&&pr(g.serial,n.signerSerial))||(n.certs.length===1?n.certs[0]:null);if(!p)return r(!1,"tsa_untrusted");if(!await Zs(p,n.sigAlg,n.signature,n.signedBytes))return r(!1,"tsa_bad_signature");if(!pr(p.issuer,l.subject)||!await Zs(l,p.sigAlg,p.signature,p.tbs))return r(!1,"tsa_untrusted");if(!p.timestamping)return r(!1,"tsa_not_timestamping");let c=Date.parse(n.genTime);for(let g of[p,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 ao?"tsa_malformed":"tsa_bad_signature")}}var tp=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}\.tsr$/,Ys=/^[a-f0-9]{64}$/;async function np(e){return[...new Uint8Array(await crypto.subtle.digest("SHA-256",e))].map(n=>n.toString(16).padStart(2,"0")).join("")}function Xs(e){if(typeof e!="string"||et(e)!==null)return null;let t;try{t=JSON.parse(e)}catch{return null}return!t||typeof t!="object"||Array.isArray(t)||t.schema!==Wd||typeof t.tsr_file!="string"||!tp.test(t.tsr_file)||!Ys.test(t.tsr_sha256)||!Ys.test(t.imprint_sha256)||"token"in t?null:t}async function op(e,t,n){let o=Xs(e);if(!o)return{ok:!1,reason:"tsa_malformed"};if(!t||!t.length)return{ok:!1,reason:"tsa_token_missing"};if(await np(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 ep(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 Qs(e,t,n){let o=Xs(e);return o?o.seal_sha256!==t?{ok:!1,reason:"tsa_imprint_mismatch",matches:!1}:op(e,n,t):{ok:!1,reason:"tsa_malformed"}}function so(e){if(e==null||et(e)!==null)return null;try{return JSON.parse(e)}catch{return null}}async function fr(e,t,n,o=null,{logKeys:r=null}={}){let a=so(t);if(!e||!a)return{ok:!1,reason:"anchor_malformed",entry:null};let i=Array.isArray(n?.keys)?n.keys:Gt(n),l=o?new Set(o.map(h=>h.keyId)):new Set((Array.isArray(e.signatures)?e.signatures:[]).map(h=>h?.keyid).filter(Boolean)),p=i.filter(h=>l.has(h.key_id)&&(h.status??"active")==="active");if(!p.length)return{ok:!1,reason:"anchor_key_mismatch",entry:null};let c=r||[await vn(mn)],g={ok:!1,reason:"anchor_mismatch",entry:null};for(let h of p){let d=await $s(e,a,Pe(h.public_key),c);if(d.ok&&d.integratedTime!=null)return{...d,entry:a.entry};g={...d,entry:null}}return g}async function ei(e,t,{logKeys:n=null}={}){let o=so(e.sealText),r=null,a=null;if(e.receiptText!=null&&e.receiptAnchorText!=null)r=await fr(so(e.receiptText),e.receiptAnchorText,e.receiptKeys,null,{logKeys:n});else if(e.anchorText!=null){let i=so(e.anchorText),l=o?Gt(t).filter(p=>p.key_id===o.key_id&&p.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 p=n||[await vn(mn)],c=await to(o,i,Pe(l[0].public_key),p);r={...c,entry:c.ok?i.entry:null}}}return e.tsaText!=null&&(a=o?await Qs(e.tsaText,await yn(o),e.tsrBytes??null):{ok:!1,reason:"tsa_malformed"}),{rekor:r,tsa:a}}var rp="https://rekor.sigstore.dev/api/v1/log/entries",ti=e=>`https://search.sigstore.dev/?logIndex=${Number(e)}`;async function ni(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(`${rp}?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 p=i[l[0]];return String(l[0]).slice(-64)===String(e.uuid).slice(-64)&&p?.body===e.body&&p?.integratedTime===e.integratedTime&&p?.logID===e.logID&&p?.logIndex===e.logIndex?"match":"differs"}catch{return"unavailable"}finally{r&&clearTimeout(r)}}var oi=[700,1500],Kt={identity:2600,checks:2200,save:1800,readback:650,stop:4200,done:1600};function ri(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(oi[1],Math.max(oi[0],((i.t1??0)-(i.t0??0))*.5)),p=e.readbacks.filter(g=>g.step===i.i&&g.result!=="not_reached"),c=p.length>0;if(n({step:i.i,stage:"step",dwell:c?Kt.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?Kt.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?Kt.checks:Math.max(350,Math.round(l*.45)),spotlight:g?"checks":null,highlight:g})}p.forEach((g,h)=>n({step:i.i,stage:"readback",readbacks:h+1,dwell:Kt.readback,spotlight:"save"})),i.status==="stopped"&&n({step:i.i,stage:"stop",dwell:Kt.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:Kt.done}),t}var ap={step:0,identity:1,checks:2,readback:3,stop:3,done:4};function ai(e,t){if(!e)return null;let n=ap[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 si(e,t){let n=e.filter(r=>r.highlight);return(n.find(r=>r.i>t)||n[0]||e[0]).i}var sp=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function ii(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()} ${sp[t.getUTCMonth()]} ${t.getUTCFullYear()}, ${n(t.getUTCHours())}:${n(t.getUTCMinutes())} UTC`}function lo(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 li(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":""}`}ut();var ae={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},me=e=>Math.round(e*100)/100;function Me(e,t){let n=t*Math.PI/180;return[me(300+e*Math.sin(n)),me(300-e*Math.cos(n))]}function xn(e,t,n){let[o,r]=Me(e,t),[a,i]=Me(e,n),l=n-t>180?1:0;return`M${o} ${r}A${e} ${e} 0 ${l} 1 ${a} ${i}`}function kn(e,t){let n=Math.sin(e*12.9898+t*78.233)*43758.5453;return n-Math.floor(n)}function co(e,t,n,o){let r=e*Math.PI/180,a=o*(.5+kn(t,n)),i=(kn(t,n+1)-.5)*o*.8;return{bx:me(Math.sin(r)*a+Math.cos(r)*i),by:me(-Math.cos(r)*a+Math.sin(r)*i),br:me((kn(t,n+2)-.5)*16)}}function ci(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[_,x]=r(b);return{i:b,d:xn(ae.step,_,x),hit:xn(ae.step,b*n,(b+1)*n),status:m.status,at:me((_+x)/2/360),t:m.t0,...co((_+x)/2,b,1,26)}}),i=[];e.steps.forEach((m,b)=>{let _=i.at(-1);_&&_.title===m.section?_.to=b:i.push({title:m.section,from:b,to:b})});let l=i.filter(m=>m.title).map((m,b)=>{let _=m.from*n+o,x=(m.to+1)*n-o,w=(_+x)/2,E=w>90&&w<270,R=Math.max((x-_)/2,40);return{k:b,title:m.title,from:m.from,to:m.to,d:xn(ae.section,_,x),text:E?ip(ae.section+9,w-R,w+R):xn(ae.section-4,w-R,w+R),mark:[Me(ae.step+12,m.from*n),Me(ae.step+20,m.from*n)],at:me(_/360)}}),p=[];e.steps.forEach((m,b)=>{let _=e.checks.filter(E=>E.step===b),[x,w]=r(b);_.forEach((E,R)=>{let S=x+(R+1)/(_.length+1)*(w-x),A=E.result!=="passed",[L,P]=Me(A?ae.tickFailIn:ae.tickIn,S),[$,O]=Me(A?ae.tickFailOut:ae.tickOut,S);p.push({i:p.length,step:b,x1:L,y1:P,x2:$,y2:O,result:E.result,at:me(S/360),t:E.t,...co(S,p.length,2,18)})})});let c=e.readbacks.length,g=e.readbacks.map((m,b)=>{let _=b/c*360,[x,w]=Me(ae.dot,_);return{i:b,cx:x,cy:w,result:m.result,label:m.label,at:me(_/360),t:m.t,...co(_,b,3,16)}}),h=e.identity.length,d=360/Math.max(1,h),f=Math.min(4,d*.28),u=e.identity.map((m,b)=>{let _=b*d+f/2,x=(b+1)*d-f/2;return{i:b,step:m.step,d:xn(ae.petal,_,x),result:m.result,at:me((_+x)/2/360),t:m.t,...co((_+x)/2,b,4,12)}}),v=e.stoppedAt==null?null:(()=>{let m=(e.stoppedAt+1)*n,[b,_]=Me(ae.step-24,m),[x,w]=Me(ae.step+18,m);return{x1:b,y1:_,x2:x,y2:w,deg:me(m),at:me(m/360)}})();return{steps:a,bands:l,ticks:p,dots:g,petals:u,stop:v,per:n}}function ip(e,t,n){let[o,r]=Me(e,n),[a,i]=Me(e,t),l=n-t>180?1:0;return`M${o} ${r}A${e} ${e} 0 ${l} 0 ${a} ${i}`}function hr(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 p=1+l*8,c=5+a[p]%9,g=a[p+1]/255*Math.PI*2,h=t*(.5+.2*l+a[p+2]/255*.08),d=.16+a[p+3]/255*.24,f=(a[p+4]/255-.5)*.7,u=1.2+a[p+6]/255*.8,v=u*(2.4+a[p+5]/255*1.6),m=x=>{let w=h*(1-d+d*Math.cos(c*x+g)),E=x+f*Math.sin(c*x);return[t+w*Math.cos(E),t+w*Math.sin(E)]},b=[],_=0;for(let x=0;x=E;){let O=1-($-E)/Math.max(1e-9,Math.hypot(P[0]-R[0],P[1]-R[1])),M=R[0]+(P[0]-R[0])*O,k=R[1]+(P[1]-R[1])*O;n&&(M+=(kn(x*97+S,l+11)-.5)*5*n,k+=(kn(x*89+S,l+23)-.5)*5*n),M=me(M),k=me(k),w+=`M${me(M-u)} ${k}a${me(u)} ${me(u)} 0 1 0 ${me(u*2)} 0a${me(u)} ${me(u)} 0 1 0 ${me(-u*2)} 0`,S+=1,$-=E,E=v}E-=$,R=P}_=Math.max(_,S),b.push({d:w,at:me(x/c)})}i.push({petals:b,count:c,dots:_,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"};Ft();Ft();var cp=0;function s(e,t,n,o,r,a){t||(t={});var i,l,p=t;if("ref"in p)for(l in p={},t)l=="ref"?i=t[l]:p[l]=t[l];var c={type:e,props:p,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--cp,__i:-1,__u:0,__source:r,__self:a};if(typeof e=="function"&&(i=e.defaultProps))for(l in i)p[l]===void 0&&(p[l]=i[l]);return j.vnode&&j.vnode(c),c}var dp=.94;function pp(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 po({rings:e,tone:t,digest:n,phase:o="rest",still:r=!1,variant:a="full",buildMs:i=3200,active:l=null,focusIndex:p=0,onActive:c,onPick:g,onKey:h,ringFocus:d=null,witnesses:f=null,lit:u=null,spot:v=null,label:m}){let b=re(()=>ci(e),[e]),_=a==="full",x=o==="broken",w=re(()=>_?hr(n,{radius:100,disorder:x?1:0}):null,[n,x,_]),E=e.anchor,R=!!(u&&E&&u.step===E.step&&["done","stop","readback"].includes(u.stage)),A=`s${it().replace(/[^a-zA-Z0-9]/g,"")}`,L=Math.max(1,e.runMs),P=k=>k==null?0:Math.round(Math.min(k/L,1)*dp*i),$=k=>l!=null&&k===l?"1":void 0,O=k=>u?k?"1":"0":void 0,M=(k,B={})=>({"--d":`${P(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":d||void 0,"data-spot":v||void 0,"data-anchored":R?"1":void 0,style:{"--build":`${i}ms`},children:[s("div",{className:F.halo,"aria-hidden":"true"}),w?s(di,{layers:w,phase:o,broken:x,tone:t},n):null,s("svg",{className:F.svg,viewBox:"0 0 600 600",role:_?"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:ae.section+16,pathLength:"1"}),s("circle",{className:F.hair,cx:300,cy:300,r:ae.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]}),_?s(se,{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))]}),f?s(fp,{witnesses:f}):null,E?s(hp,{deg:(E.step+.5)*b.per,kind:E.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":O(u?.steps(k.i)),d:k.d,pathLength:"1",style:M(k)},`b${k.i}`)),b.steps.map(k=>s("path",{className:F.step,"data-status":k.status,"data-on":$(k.i),"data-lit":O(u?.steps(k.i)),"data-current":u&&u.step===k.i?"1":void 0,"data-anchor":E&&E.step===k.i?E.kind:void 0,"data-i":k.i,d:k.d,pathLength:"1",stroke:k.status==="passed"?`url(#${A}g)`:void 0,style:M(k)},k.i)),b.stop?s("g",{"data-lit":O(u&&u.stage==="stop"),className:F.stop,style:{"--d":`${P(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:ae.dot+16}),b.ticks.map(k=>s("line",{className:F.tick,"data-result":k.result,"data-on":$(k.step),"data-lit":O(u?.checks(k.step)),x1:k.x1,y1:k.y1,x2:k.x2,y2:k.y2,style:M(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":O(u?.readback(k.i)),"data-on":l!=null&&e.readbacks[k.i].step===l?"1":void 0,cx:k.cx,cy:k.cy,r:ae.dotSize,style:M(k),onMouseEnter:_&&c?()=>c(e.readbacks[k.i].step,{readback:k.i}):void 0},k.i)),s("circle",{className:F.hair,cx:300,cy:300,r:ae.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":O(u?.identity(k.step)),d:k.d,pathLength:"1",style:M(k),onMouseEnter:_&&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:ae.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"})]})]}),u?s("g",{className:F.playhead,style:{"--deg":`${((u.step+.5)*b.per).toFixed(2)}deg`},"aria-hidden":"true",children:[s("line",{x1:300,y1:300-ae.core-6,x2:300,y2:300-ae.step-22}),s("circle",{cx:300,cy:300-ae.step-22,r:"4.5"})]}):null,_?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===p?0:-1,"aria-label":pp(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 up={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 fp({witnesses:e}){return s("g",{className:F.layer,style:{"--z":1.15},children:Object.entries(up).map(([t,n])=>{let o=e[t];if(!o)return null;let[r,a]=Me(ae.section+32,n.deg),[i,l]=Me(ae.section+6,n.deg),[p,c]=Me(ae.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:p,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 hp({deg:e,kind:t}){let[n,o]=Me(ae.section+2,e),[r,a]=Me(ae.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 gp=1700;function di({layers:e,phase:t,broken:n,tone:o}){let r=ee(null),a=ee([]);return U(()=>{let i=r.current;if(!i)return;let l=[],p="#ffffff",c=()=>{let m=getComputedStyle(i),b=(_,x)=>m.getPropertyValue(_).trim()||x;l=n?[b("--fail","#ff4d6a"),b("--fail","#ff4d6a"),b("--fail","#ff4d6a")]:[b("--t0","#4cf0b8"),b("--soft","#b9fbe5"),b("--t0","#4cf0b8")],p=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}))),d=m=>{a.current.forEach((b,_)=>{if(!b)return;let x=b.clientWidth,w=Math.min(2,window.devicePixelRatio||1);b.width!==Math.round(x*w)&&(b.width=Math.round(x*w),b.height=Math.round(x*w));let E=b.getContext("2d");E.setTransform(x*w/200,0,0,x*w/200,0,0),E.clearRect(0,0,200,200);for(let R of h[_]){let S=m==null?0:Math.max(0,1-Math.abs(m-R.at)*6);E.globalAlpha=Math.min(1,g[_]+S*.6),E.fillStyle=S>.3?p:l[_],E.fill(R.path)}})};d(null);let f=new MutationObserver(()=>requestAnimationFrame(()=>{c(),d(null)}));if(f.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),t!=="verify"||window.matchMedia("(prefers-reduced-motion: reduce)").matches)return()=>f.disconnect();let u=performance.now(),v=requestAnimationFrame(function m(b){let _=(b-u)/gp;d(_>1.1?null:_),_<=1.1&&(v=requestAnimationFrame(m))});return()=>{cancelAnimationFrame(v),f.disconnect()}},[e,t,n,o]),s("div",{className:F.iris,ref:r,"aria-hidden":"true",children:[e.map((i,l)=>s("canvas",{ref:p=>{a.current[l]=p},className:F.irisLayer,style:{"--spin":`${i.dir*(140+l*50)}s`}},l)),s("div",{className:F.irisGlow})]})}function pi({seed:e,tone:t,size:n=64}){let o=re(()=>hr(e,{radius:100}),[e]);return s("span",{className:F.mini,"data-tone":t,style:{width:n,height:n},"aria-hidden":"true",children:s(di,{layers:o,phase:"rest",broken:!1,tone:t})})}ut();var N={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 bp="0123456789abcdef",Wt=64,vp=1100;function gr({label:e,from:t,to:n,against:o,running:r,still:a}){let[i,l]=D(()=>(t||"").slice(0,Wt)),[p,c]=D(!1),g=ee(n);g.current=n,U(()=>{if(!r){n&&(l(n),c(!0));return}if(c(!1),a){n&&(l(n),c(!0));return}let u=(t||"").slice(0,Wt).padEnd(Wt,"0"),v=0,m=0,b=null,_=x=>{let w=g.current;w&&b==null&&(b=x);let E=b==null?0:Math.min(1,(x-b)/vp);if(x-m>45||E===1){m=x;let R=Math.floor(E*Wt),S="";for(let A=0;AcancelAnimationFrame(v)},[r,a]),U(()=>{!r&&n&&(l(n),c(!0))},[n,r]);let h=p&&n,d=h&&n===o,f=!r&&!n;return s("div",{className:N.hashRow,"data-state":f?"idle":h?d?"match":"differs":"running",children:[s("span",{className:N.proofLabel,children:[e,h?s("b",{children:d?" · matches":" · differs"}):null]}),s("code",{className:N.hex,"aria-label":h?`SHA-256 ${n}`:f?"Not computed":"Computing the SHA-256",children:f?"not computed":h?[...n].map((u,v)=>s("span",{"data-diff":u!==o[v]?"1":void 0,children:u},v)):i})]})}function uo({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"})})})}ut();ut();var de=e=>e.kind??"action",Mt=e=>e.kind??"sequence",Ge=e=>e.halts??[],ct=e=>e.effects??[],wn=e=>e.postconditions??[],_e=e=>e.nodes??[],Ke=e=>e.edges??[];var Ze="__opg_stop__",Sn=e=>String(e).padStart(2,"0");var yp=e=>e.index+1;function _p(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=>de(i)==="action")?"action":de(t[0]),title:e.title??`Steps ${Sn(o(t[0]))}–${Sn(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(ct),postconditions:t.flatMap(wn),halts:t.flatMap(i=>Ge(i).map(l=>`step ${Sn(o(i))}: ${l}`)),badges:a(t.flatMap(i=>i.badges??[]))}}function ui(e,t={}){let n=t.numberOf??yp,o=_e(e),r=new Map(o.map(d=>[d.id,d])),a=new Map(o.map(d=>[d.id,d.id])),i=new Map,l=new Map;for(let d of t.folds?.groups??[]){if(t.expanded?.has(d.id)||r.has(d.id))continue;let f=d.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(f.length===0)continue;let u=_p(d,f,n);for(let v of f)a.set(v.id,d.id);l.set(f[0].id,u),i.set(d.id,{id:d.id,title:u.title,subtitle:d.subtitle,members:f,first:n(f[0])??f[0].index+1,last:n(f[f.length-1])??f[f.length-1].index+1})}let p=[];for(let d of o)a.get(d.id)===d.id?p.push(d):l.get(d.id)&&p.push(l.get(d.id));let c=[],g=new Set;for(let d of Ke(e)){let f=a.get(d.source),u=a.get(d.target);if(!f||!u||f===u&&i.has(f))continue;let v=Mt(d),m=`${f}>${u}>${v}>${d.label??""}`;g.has(m)||(g.add(m),c.push({...d,source:f,target:u,kind:v}))}let h=(t.stopExits??[]).filter(d=>a.has(d.node));if(h.length){let d=Math.max(-1,...p.map(f=>f.index))+1;p.push({id:Ze,index:d,kind:"terminal",title:t.stopLabel??"Stop the run",outcome:"halt",halts:[],effects:[],postconditions:[]});for(let f of h){let u=a.get(f.node),v=`${u}>${Ze}`;g.has(v)||(g.add(v),c.push({source:u,target:Ze,kind:"exception",label:f.label??"stops"}))}}return{spec:{...e,nodes:p,edges:c},folds:i,ownerOf:a}}function fi(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 mr(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=_e(e),p=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:p?i:void 0,splitAt:a.kind!=="save"&&c>0?a.steps[c]:void 0}}function hi(e,t={}){let n=t.minLength??6,o=t.maxLength??10,r=[..._e(e)].sort((h,d)=>h.index-d.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,d)=>{let f=i.get(h.id)??[],u=a.get(d.id)??[];return f.length===1&&u.length===1&&f[0].target===d.id&&Mt(f[0])==="sequence"&&de(h)==="action"&&de(d)==="action"},p=[],c=[];for(let h of r)c.length&&l(c[c.length-1],h)?c.push(h):(c.length&&p.push(c),c=de(h)==="action"?[h]:[]);c.length&&p.push(c);let g=[];for(let h of p){if(h.lengthm.id)})}}return{groups:g}}var xp={nodeWidth:194,nodeHeight:70,xGap:42,yGap:48,margin:34,minWidth:0,laneGap:14,laneInset:22},kt=6;function gi(e){return new Map(e.map((t,n)=>[t.id,Number.isFinite(t.index)?t.index:n]))}function mi(e,t){let n=t.get(e.source),o=t.get(e.target);return n===void 0||o===void 0?!1:o<=n}function kp(e){let t=[..._e(e)],n=gi(t);t.sort((h,d)=>n.get(h.id)-n.get(d.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=>!mi(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 p=h=>{let d=new Set([h]),f=[h];for(;f.length;){let u=f.shift();for(let v of r)v.target===u&&!d.has(v.source)&&(d.add(v.source),f.push(v.source))}return d},c=[];for(let h of t){let d=l.get(h.id).filter(_=>Mt(_)==="loop_body");if(de(h)!=="loop"&&d.length===0)continue;let f=l.get(h.id).filter(_=>Mt(_)!=="loop_body").map(_=>_.target);if(d.length===0||f.length===0)continue;let u=new Set([h.id,...f]),v=p(h.id),m=new Set,b=d.map(_=>_.target).filter(_=>!u.has(_));for(;b.length;){let _=b.shift();if(!m.has(_)){m.add(_);for(let x of l.get(_))u.has(x.target)||b.push(x.target)}}for(let _ of m)v.has(_)||m.delete(_);c.push({exits:f,body:m})}let g=new Map(t.map(h=>[h.id,0]));for(let h=0;h<=t.length;h+=1){let d=!1,f=(u,v)=>{v>g.get(u)&&(g.set(u,v),d=!0)};for(let u of t)for(let v of i.get(u.id))f(u.id,g.get(v.source)+1);for(let u of c){if(u.body.size===0)continue;let v=Math.max(...[...u.body].map(m=>g.get(m)));for(let m of u.exits)f(m,v+1)}if(!d)break}return g}function wp(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 bi(e,t={}){let n={...xp,...t},o=_e(e),r=gi(o),a=kp(e),i=new Set(o.map(S=>S.id)),l=Ke(e).filter(S=>i.has(S.source)&&i.has(S.target)),p=new Map;for(let S of o){let A=a.get(S.id)??0,L=p.get(A)??[];L.push(S),p.set(A,L)}for(let S of p.values())S.sort((A,L)=>r.get(A.id)-r.get(L.id));let c=Math.max(0,...a.values()),g=Math.max(1,...[...p.values()].map(S=>S.length)),h=S=>n.margin+S*(n.nodeHeight+n.yGap),d=l.map((S,A)=>{let L=mi(S,r),P=(a.get(S.target)??0)-(a.get(S.source)??0);return{edge:S,index:A,back:L,lane:L?"right":P===1?null:"left",slot:0}}),f=[],u=[];for(let S of d){if(S.lane===null)continue;let A=a.get(S.edge.source)??0,L=a.get(S.edge.target)??0;S.slot=wp(S.lane==="left"?f:u,A,L)}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(f.length),v(u.length))),_=n.margin*2+(c+1)*n.nodeHeight+c*n.yGap,x=[];for(let[S,A]of[...p.entries()].sort((L,P)=>L[0]-P[0])){let L=A.length*n.nodeWidth+(A.length-1)*n.xGap,P=(b-L)/2;A.forEach(($,O)=>{x.push({id:$.id,x:P+O*(n.nodeWidth+n.xGap),y:h(S),width:n.nodeWidth,height:n.nodeHeight,rank:S})})}let w=new Map(x.map(S=>[S.id,S])),E=(S,A)=>{let L=Math.min(S,A),P=Math.max(S,A),$=x.filter(O=>O.rank>=L&&O.rank<=P);return{left:Math.min(...$.map(O=>O.x)),right:Math.max(...$.map(O=>O.x+O.width))}},R=d.map(({edge:S,index:A,back:L,lane:P,slot:$})=>{let O=w.get(S.source),M=w.get(S.target),k=Mt(S),B=S.label??"",H=`${S.source}:${S.target}:${k}:${A}`,G=O.y+O.height/2,V=M.y+M.height/2;if(P===null){let oe=O.x+O.width/2,X=M.x+M.width/2,K=O.y+O.height,xe=M.y,Se=(K+xe)/2;return{id:H,source:S.source,target:S.target,kind:k,label:B,path:`M ${oe} ${K} C ${oe} ${Se}, ${X} ${Se}, ${X} ${xe}`,labelX:(oe+X)/2+6,labelY:Se+3,labelRotate:!1,backEdge:L,lane:P}}let ve=E(O.rank,M.rank);if(P==="right"){let oe=ve.right+n.laneInset+$*n.laneGap,X=O.x+O.width,K=M.x+M.width,xe=VG;return{id:H,source:S.source,target:S.target,kind:k,label:B,path:`M ${Ie} ${G} H ${te+pe} Q ${te} ${G} ${te} ${G+(Te?pe:-pe)} V ${V+(Te?-pe:pe)} Q ${te} ${V} ${te+pe} ${V} H ${ne}`,labelX:te-8,labelY:(G+V)/2,labelRotate:!0,backEdge:L,lane:P}});return{width:b,height:_,nodes:x,edges:R}}function br(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 vr(e){let t=de(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||ct(e).length>0?"governed":"default"}var Sp=e=>String(e).padStart(2,"0"),En=e=>e.index+1;function vi(e,t="index"){if(t==="index")return En;let n=new Map;return[..._e(e)].sort((o,r)=>o.index-r.index).filter(o=>de(o)==="action").forEach((o,r)=>n.set(o.id,r+1)),o=>n.get(o.id)??null}var Ep={loop:"LOOP",branch:"IF",business_decision:"ASK",subflow_call:"CALL",child_bundle:"SUB",action:"STEP"};function fo(e,t=En){if(de(e)==="terminal")return vr(e)==="stop"?"STOP":"END";let n=t(e);return n===null?Ep[de(e)]??"STEP":Sp(n)}function Vt(e){return de(e).replaceAll("_"," ")}function ho(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:wn(e).length?"present":"none",count:wn(e).length},readback:{state:ct(e).length?"present":"none",count:ct(e).length}}}function yi(e,t=br(e),n=En){let o=fo(e,n),a=[`${/^\d+$/.test(o)?`step ${o}, ${Vt(e)}`:o==="END"||o==="STOP"?`${o.toLowerCase()}, ${Vt(e)}`:Vt(e)}: ${t}.`];e.identity?.armed&&a.push("Checks the right record."),ct(e).length&&a.push("Reads the saved record back.");let i=Ge(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 qt(e){let t=Ge(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=de(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=ct(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])]:[],p=[...r,...l,...a];return p.length===t.length-1&&!e.wait_until&&(p=[...r,n(Ye[3][0]),...a]),p.length!==t.length?t.map(()=>({kind:"run",text:"Stops if a declared check fails."})):p}function go(e){return e?.events.find(t=>t.status==="halted")??null}function _i(e,t,n){let o=Math.max(0,Math.min(t,e.events.length)),r=f=>n?.get(f)??f,a=new Map,i=new Map,l=new Set,p=null,c=null,g=null,h=null;for(let f=0;f${v}`,l.add(p)):p=null,c=v,g===u&&(p=`${v}>${Ze}`,l.add(p),a.set(Ze,{status:"halted",visits:1,iterations:0,last:u,events:[u]}))}let d=o>0?e.events[o-1]:null;if(d){let f=a.get(r(d.node));f.status!=="halted"&&(f.status="active")}return{cursor:o,nodes:a,taken:l,latestEdge:p,current:d,iteration:h,halted:g,finished:o===e.events.length}}function xi(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 ki(e,t,n){let o=d=>n?.get(d)??d,r=_e(e),a=o(t.node),i=r.find(d=>d.id===a),l=t.iteration??null,p={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 d of r){if(d.index>=i.index||d.id===Ze||de(d)==="terminal")continue;let f=de(d)==="loop";c.set(d.id,{status:"done",visits:1,iterations:f&&l?l:0,events:[]})}c.set(a,{status:t.status==="stopped"?"halted":"active",visits:1,iterations:de(i)==="loop"&&l?l:0,last:p,events:[p]});for(let d of Ke(e)){let f=r.find(v=>v.id===d.source),u=r.find(v=>v.id===d.target);f&&u&&f.indexf.index&&g.add(`${f.id}>${u.id}`)}if(de(i)==="loop"&&(l??1)>1){let d=Ke(e).find(f=>{let u=r.find(v=>v.id===f.source);return f.target===a&&u!==void 0&&u.index>i.index});d&&(h=`${d.source}>${a}`)}else{let d=Ke(e).find(f=>{let u=r.find(v=>v.id===f.source);return f.target===a&&u!==void 0&&u.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:p,events:[p]}))}return{cursor:0,nodes:c,taken:g,latestEdge:h,current:p,iteration:l,halted:t.status==="stopped"?p:null,finished:t.status==="stopped"}}var wi=(e,t)=>{for(let n=0;nf.title),r=[..._e(e)].sort((f,u)=>f.index-u.index),a=r.filter(f=>de(f)==="action"),i=[],l=f=>n?wi(n,u=>n.events[u].node===f):-1,p=f=>{let u=l(f);return u>=0?u+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(f=>(f.resolution?.rungs??[]).filter(u=>u.present).length>=2);if(c){let f=(c.resolution?.rungs??[]).filter(u=>u.present).map(u=>u.label.toLowerCase());i.push({id:"step",title:"One step",body:`“${o(c)}” recorded ${f.length} ways to find its target: ${f.join(", ")}. A run tries the strongest first.`,select:c.id,cursor:p(c.id),view:"program"})}let g=r.find(f=>de(f)==="loop");if(g){let f=n?new Set(n.events.map(v=>v.iteration).filter(v=>v!=null)).size:0,u=n?wi(n,v=>n.events[v].node===g.id&&n.events[v].iteration===2):-1;i.push({id:"loop",title:"The loop",body:f>1?`The steps run once for each item in the list. This run reached ${f} 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:u>=0?u+1:p(g.id),view:"program"})}let h=a.find(f=>f.identity?.armed&&f.id!==c?.id)??a.find(f=>f.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:p(h.id),view:"program"});let d=go(n);if(n&&d)i.push({id:"stop",title:"A stop",body:d.reason??"The run stopped here, where a check failed.",select:d.node,cursor:n.events.indexOf(d)+1,view:"program"});else{let f=a.find(u=>Ge(u).length>0);f&&i.push({id:"stop",title:"A stop rule",body:qt(f).map(u=>u.text).join(" "),select:f.id,cursor:p(f.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:d?.node??null,cursor:n.events.length,view:"program"}),i}ut();var Np={program:"Program map",evidence:"Evidence lanes",stops:"Stop rules"},Tp="The map follows the emitted edge targets. It keeps each loop and exception route visible.",$p="These rows show the declared contract. They do not report a live verdict.",yr=e=>String(e).padStart(2,"0"),bo=Dt(En);function Ap(){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 gt({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 _r(e,t,n){return t?t.first===t.last?yr(t.first):`${yr(t.first)}–${yr(t.last)}`:fo(e,n)}function Rp({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(gt,{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 Mp({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,p=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!p&&!g?null:s("div",{className:"opg-media",children:[s("span",{children:"Pictures"}),s("div",{className:"opg-media-pair",children:[p&&s("figure",{children:[s("a",{href:p,target:"_blank",rel:"noopener noreferrer",children:s("img",{src:p,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 Ip({review:e,folded:t,onEditSection:n}){let{section:o,mergeWith:r,splitAt:a}=e,[i,l]=D(!1),[p,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 d=p.replace(/\s+/g," ").trim();d&&d!==o.title&&n({op:"rename",section:o.section,title:d}),l(!1)},children:[s("input",{"aria-label":"Section title",value:p,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 Cp({node:e,fold:t,partOf:n,run:o,titleFor:r,onUnfold:a,onRefold:i,onPickMember:l,plainStopRules:p,resolveMedia:c,onClose:g,review:h,onEditSection:d}){let f=_t(bo),u=ho(e),v=t?.members.map(ho)??[],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:_r(e,t,f)}),g&&s("button",{type:"button",className:"opg-icon-button",onClick:g,"aria-label":"Close the step details",children:s(Nn,{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(se,{children:[s(gt,{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(gt,{label:"Right record",state:u.identity.state,value:`${v.filter(b=>b.identity.text==="Checked").length} checked`}),s(gt,{label:"Screen check",state:u.screen.state,value:u.screen.count?`${u.screen.count} checks`:"Not declared"}),s(gt,{label:"Read-back",state:u.readback.state,value:u.readback.count?`${u.readback.count} independent checks`:"Not declared"})]}):s(se,{children:[s(gt,{label:"Finds the field",state:u.resolve.state,value:u.resolve.count?`${u.resolve.count} evidence types`:"Not applicable"}),s(gt,{label:"Right record",state:u.identity.state,value:u.identity.text}),s(gt,{label:"Screen check",state:u.screen.state,value:u.screen.count?`${u.screen.count} checks`:"Not declared"}),s(gt,{label:"Read-back",state:u.readback.state,value:u.readback.count?`${u.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:fo(b,f)}),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&&d&&s(Ip,{review:h,folded:!!t,onEditSection:d}),Ge(e).length>0&&(p?s("div",{className:"opg-stop-rule",children:[s("span",{children:"Stop rules"}),(t?t.members.flatMap(qt):qt(e)).filter((b,_,x)=>x.findIndex(w=>w.text===b.text)===_).map((b,_)=>s("strong",{"data-kind":b.kind,children:b.text},_))]}):s("div",{className:"opg-stop-rule",children:[s("span",{children:"Stops before acting if"}),s("strong",{children:Ge(e).join("; ")})]})),s(Mp,{node:e,fold:t,run:o,resolveMedia:c,title:r(e)}),o&&o.status!=="pending"&&s(Rp,{state:o})]})}function Pp(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 Op({display:e,fullSpec:t,folds:n,expanded:o,setExpanded:r,traceState:a,selectedId:i,setSelectedId:l,titleFor:p,canvasNote:c,layoutOptions:g,showInspector:h=!0,plainStopRules:d,compact:f=!1,resolveMedia:u,inspectorOpen:v,setInspectorOpen:m,onEditSection:b}){let _=_t(bo),x=re(()=>bi(e.spec,g),[e.spec,g]),w=_e(e.spec),E=re(()=>new Map(w.map(T=>[T.id,T])),[w]),R=`opg-arrow-${it().replace(/[^a-zA-Z0-9_-]/g,"")}`,S=ee(new Map),A=ee(null),L=e.ownerOf.get(i)??(E.has(i)?i:w[0]?.id),P=E.get(L??"")??w[0],[$,O]=D(1),M=Ee(T=>O(Math.round(Math.max(.4,Math.min(1.6,T))*100)/100),[]),[k,B]=D(!1),H=f&&!k,G=ee(null),V=ee(new Map),[ve,te]=D(0);U(()=>{let T=new Set,z=q=>{let Y=V.current.get(q.pointerId);if(!Y)return;let $e=requestAnimationFrame(()=>{T.delete($e),V.current.get(q.pointerId)===Y&&(V.current.delete(q.pointerId),V.current.size||te(Oe=>Oe+1))});T.add($e)},ue=()=>{V.current.clear(),te(q=>q+1)};return window.addEventListener("pointerup",z),window.addEventListener("pointercancel",z),window.addEventListener("blur",ue),()=>{window.removeEventListener("pointerup",z),window.removeEventListener("pointercancel",z),window.removeEventListener("blur",ue);for(let q of T)cancelAnimationFrame(q);V.current.clear()}},[]);let Ie=a?.current?e.ownerOf.get(a.current.node):void 0;U(()=>{let T=G.current,z=x.nodes.find(Jt=>Jt.id===Ie);if(!T||!z||V.current.size)return;let q=T.firstElementChild?.offsetLeft??0,Y=z.x*$+q,$e=z.y*$,Oe=z.width*$,Le=z.height*$,Q=$e>=T.scrollTop&&$e+Le<=T.scrollTop+T.clientHeight,he=Y>=T.scrollLeft&&Y+Oe<=T.scrollLeft+T.clientWidth;if(Q&&he)return;let nt=Q?T.scrollTop:Math.max(0,$e-(T.clientHeight-Le)/2),wt=he?T.scrollLeft:Math.max(0,Y-(T.clientWidth-Oe)/2);typeof T.scrollTo=="function"?T.scrollTo({top:nt,left:wt}):(T.scrollTop=nt,T.scrollLeft=wt)},[Ie,a?.cursor,x,$,ve]),U(()=>{let T=G.current;if(!T||!f)return;let z=ue=>{!ue.ctrlKey&&!ue.metaKey||(ue.preventDefault(),O(q=>Math.round(Math.max(.4,Math.min(1.6,q*(ue.deltaY>0?.9:1.1)))*100)/100))};return T.addEventListener("wheel",z,{passive:!1}),()=>T.removeEventListener("wheel",z)},[f]);let ne=ee(null),pe=f?{onPointerDown:T=>{if(T.target.closest("button")||T.button!==0)return;let z=G.current;ne.current={x:T.clientX,y:T.clientY,left:z.scrollLeft,top:z.scrollTop},z.setPointerCapture?.(T.pointerId)},onPointerMove:T=>{let z=ne.current,ue=G.current;!z||!ue||(ue.scrollLeft=z.left-(T.clientX-z.x),ue.scrollTop=z.top-(T.clientY-z.y))},onPointerUp:()=>{ne.current=null},onPointerCancel:()=>{ne.current=null}}:{},Te=()=>{let T=G.current;T&&M(Math.min(1,(T.clientWidth-16)/x.width,(T.clientHeight-16)/x.height))};if(U(()=>{let T=A.current;T&&(A.current=null,S.current.get(T)?.focus())}),!P)return s("p",{className:"opg-empty",children:"The compiled graph is empty."});let oe=n?.groups.find(T=>o.has(T.id)&&T.nodes.includes(P.id)),X=b?e.folds.has(P.id)?mr(t,P.id):oe?mr(t,oe.id,P.id):null:null,K=s(Cp,{node:P,fold:e.folds.get(P.id),partOf:oe?{id:oe.id,title:oe.title??oe.id}:void 0,review:X,onEditSection:b,run:a?.nodes.get(P.id),titleFor:p,plainStopRules:d,resolveMedia:u,onClose:f?()=>m(!1):void 0,onUnfold:T=>{let z=e.folds.get(T);r(new Set([...o,T])),z&&(l(z.members[0].id,"user"),A.current=z.members[0].id)},onRefold:T=>{let z=new Set(o);z.delete(T),r(z),l(T,"user"),A.current=T},onPickMember:(T,z)=>{r(new Set([...o,T])),l(z,"user"),A.current=z}}),xe=T=>a?.nodes.get(T),Se=Ke(t).length,tt=_e(t).length,yo=w.filter(T=>T.id!==Ze).length,Yt=(T,z)=>{let ue=x.nodes.find(Q=>Q.id===z);if(!ue)return;let q,Y=Q=>x.nodes.filter(he=>he.rank===Q).sort((he,nt)=>he.x-nt.x),$e=Q=>Y(Q).sort((he,nt)=>Math.abs(he.x-ue.x)-Math.abs(nt.x-ue.x))[0]?.id,Oe=[...new Set(x.nodes.map(Q=>Q.rank))].sort((Q,he)=>Q-he),Le=Oe.indexOf(ue.rank);switch(T.key){case"ArrowDown":q=x.edges.find(Q=>Q.source===z&&!Q.backEdge)?.target??(LeQ.target===z&&!Q.backEdge)?.source??(Le>0?$e(Oe[Le-1]):void 0);break;case"ArrowRight":case"ArrowLeft":{let Q=Y(ue.rank),he=Q.findIndex(nt=>nt.id===z)+(T.key==="ArrowRight"?1:-1);q=Q[he]?.id;break}case"Home":q=x.nodes.slice().sort((Q,he)=>Q.rank-he.rank||Q.x-he.x)[0]?.id;break;case"End":q=x.nodes.slice().sort((Q,he)=>he.rank-Q.rank||he.x-Q.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:[tt," nodes · ",Se," exact edges",e.folds.size>0&&` · ${yo} cards`]})]}),f&&s("div",{className:"opg-stage-tools",role:"toolbar","aria-label":"Map view",children:[s("button",{type:"button",onClick:()=>M($-.1),"aria-label":"Zoom out",disabled:$<=.4,children:s(Nn,{d:"M3 7h8"})}),s("span",{"aria-live":"polite",children:[Math.round($*100),"%"]}),s("button",{type:"button",onClick:()=>M($+.1),"aria-label":"Zoom in",disabled:$>=1.6,children:s(Nn,{d:"M3 7h8M7 3v8"})}),s("button",{type:"button",onClick:Te,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":f||void 0,...pe,children:s("div",{className:"opg-canvas-sizer",style:{width:x.width*$,height:x.height*$},children:s("div",{className:"opg-canvas",style:{width:x.width,height:x.height,transform:$===1?void 0:`scale(${$})`},children:[s("svg",{className:"opg-edges",viewBox:`0 0 ${x.width} ${x.height}`,width:x.width,height:x.height,role:"img","aria-label":`${x.edges.length} compiled program edges`,children:[s("defs",{children:s("marker",{id:R,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"})})}),x.edges.map(T=>s("g",{"data-kind":T.kind,"data-back-edge":T.backEdge||void 0,"data-lane":T.lane??void 0,"data-run":Pp(T,a),children:[s("path",{d:T.path,markerEnd:`url(#${R})`}),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))]}),x.nodes.map(T=>{let z=E.get(T.id),ue=z.id===P.id,q=e.folds.get(z.id),Y=xe(z.id),$e=p(z),Oe=Y&&Y.status!=="pending"?` This run: ${Y.status==="halted"?"stopped here":Y.status==="active"?"here now":"reached"}${Y.iterations>1?`, ${Y.iterations} iterations`:""}.`:"";return s("button",{ref:Le=>{Le?S.current.set(z.id,Le):S.current.delete(z.id)},type:"button",className:"opg-node","data-tone":vr(z),"data-fold":q?"folded":void 0,"data-selected":ue||void 0,"data-run":Y?.status,style:{left:T.x,top:T.y,width:T.width,height:T.height},"aria-pressed":ue,"aria-label":q?`Steps ${_r(z,q,_)}, ${q.members.length} steps: ${$e}.${Oe}`:`${yi(z,$e,_)}${Oe}`,tabIndex:ue?0:-1,onClick:()=>{l(z.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:Le=>Yt(Le,z.id),children:[s("span",{className:"opg-node-index",children:_r(z,q,_)}),s("span",{className:"opg-node-copy",children:[s("small",{children:q?q.subtitle??`${q.members.length} steps`:Vt(z)}),s("strong",{title:q?$e:void 0,children:$e})]}),s("span",{className:"opg-node-signals","aria-hidden":"true",children:[de(z)==="loop"&&Y&&Y.iterations>0&&s("b",{children:["×",Y.iterations]}),z.identity?.armed&&s("i",{title:"Checks the right record",children:"R"}),ct(z).length>0&&s("i",{title:"Reads the saved record back",children:"C"}),Ge(z).length>0&&s("i",{title:"Stop rules",children:"H"})]})]},z.id)})]})})}),s("ul",{className:"opg-sr-only","aria-label":"Program edges",children:x.edges.map(T=>s("li",{children:[p(E.get(T.source))," to ",p(E.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 Lp({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:_e(e).map(o=>{let r=ho(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 zp({spec:e,titleFor:t,halt:n,plain:o}){let r=_t(bo),a=_e(e).filter(l=>Ge(l).length>0||de(l)==="terminal"),i=n?_e(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:de(l)==="terminal"?"terminal":r(l)===null?Vt(l):`step ${r(l)}`}),s("strong",{children:t(l)}),s("p",{children:Ge(l).length?o?qt(l).map(p=>p.text).join(" "):Ge(l).join("; "):"Declared terminal program state."})]},`stop-${l.id}`))]})}function Nn({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 Dp({trace:e,state:t,playing:n,setPlaying:o,setCursor:r,iterationNoun:a,liveFrame:i}){let l=e.events.length,p=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 ${p}`:`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(Nn,{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(Nn,{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 Fp({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 Hp({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 jp({stop:e,at:t,count:n,focus:o,onBack:r,onNext:a,onSkip:i}){let l=`opg-tour-${it().replace(/[^a-zA-Z0-9_-]/g,"")}`,p=ee(null);return U(()=>{o.current&&p.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:p,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 Gp(e){let{spec:t,folds:n,stopExits:o,trace:r,playhead:a,autoPlay:i=!1,initialCursor:l=0,speed:p=14,numbering:c}=e,g=re(()=>vi(t,c),[t,c]),[h,d]=D(e.initialSelectedId??_e(t)[0]?.id??""),f=e.selectedId??h,[u,v]=D(()=>new Set),m=re(()=>e.expanded?new Set(e.expanded):u,[e.expanded,u]),b=Ap(),[_,x]=D(l),w=e.cursor??_,[E,R]=D(!1),S=r?.events.length??0,{onSelect:A,onCursorChange:L,onExpandedChange:P}=e,$=Ee((ne,pe)=>{d(ne),A?.(ne,pe)},[A]),O=Ee(ne=>{v(ne),P?.([...ne])},[P]),M=ee(w);M.current=w;let k=Ee(ne=>{let pe=Math.max(0,Math.min(S,ne));x(pe),L?.(pe)},[S,L]);U(()=>{e.cursor===void 0&&x(Math.max(0,Math.min(r?.events.length??0,l))),R(!!r&&i&&!b)},[r,i,b,l]),U(()=>{if(!E||!r)return;if(w>=S){R(!1);return}let ne=setTimeout(()=>k(M.current+1),xi(r,w,p));return()=>clearTimeout(ne)},[E,w,S,r,p,k]);let B=r?go(r):a?.status==="stopped"?{node:a.node,status:"halted"}:null,H=re(()=>{let ne=[...o??[]];return B&&!ne.some(pe=>pe.node===B.node)&&ne.push({node:B.node,label:"stopped"}),ne},[o,B?.node]),G=re(()=>ui(t,{folds:n,expanded:m,stopExits:H,numberOf:g}),[t,n,m,H,g]),V=re(()=>r?_i(r,w,G.ownerOf):a?ki(G.spec,a,G.ownerOf):null,[r,w,a,G]),ve=ee(null),te=Ee(ne=>{ve.current=`c${ne}`},[]),Ie=r?`c${w}`:a?`p${a.node}:${a.iteration??""}:${a.status}`:null;return U(()=>{if(!V?.current||Ie===null||ve.current===Ie)return;let ne=ve.current===null&&w===0&&!!r;ve.current=Ie,ne||$(V.current.node,"follow")},[V,Ie,w,r,$]),{selectedId:f,setSelectedId:$,expanded:m,setExpanded:O,cursor:w,setCursor:k,playing:E,setPlaying:R,display:G,traceState:V,numberOf:g,suppressFollow:te}}function xr(e){let{spec:t,title:n,kicker:o="The steps",trace:r,iterationNoun:a="iteration",views:i=["program","evidence","stops"],initialView:l,titleFor:p=br,notes:c,layout:g,theme:h="dark",className:d,style:f,showHeader:u=!0,showPlayer:v=!0,showInspector:m=!0,plainStopRules:b=!1,compact:_=!1,resolveMedia:x,tour:w,tourSeen:E=!1,onTourEnd:R}=e,S=re(()=>e.folds!==void 0?e.folds:fi(t)??(_?hi(t):null),[e.folds,_,t]),A=Gp({...e,folds:S}),[L,P]=D(l??i[0]??"program"),{traceState:$}=A,[O,M]=D(!0),k=re(()=>w===!0?mo(t,{trace:r,title:p}):Array.isArray(w)?w:[],[w,t,r,p]),[B,H]=D(()=>k.length&&!E?0:null),G=ee(!1);U(()=>{if(B===null)return;let K=k[B];K&&(A.setPlaying(!1),K.view&&P(K.view),K.cursor!=null&&r&&(A.suppressFollow(K.cursor),A.setCursor(K.cursor)),K.select&&A.setSelectedId(K.select,"tour"),M(!0))},[B,k]);let V=K=>{H(null),R?.(K)},ve=k.length>0&&B===null?s("button",{type:"button",className:"opg-tour-launch",onClick:()=>{G.current=!0,H(0)},children:"Take the tour"}):null,te=r?.receipt&&$?.finished?r.receipt:null,Ie=x&&$?.current?.frame?x($.current.frame,{node:$.current.node,kind:"live",iteration:$.current.iteration}):null,ne=it().replace(/[^a-zA-Z0-9_-]/g,""),pe=ee(new Map),Te=i.length>1,oe=(K,xe)=>{let Se=i.indexOf(xe),tt=K.key==="ArrowRight"?i[(Se+1)%i.length]:K.key==="ArrowLeft"?i[(Se-1+i.length)%i.length]:K.key==="Home"?i[0]:K.key==="End"?i[i.length-1]:void 0;tt&&(K.preventDefault(),P(tt),pe.current.get(tt)?.focus())},X=(K,xe)=>Te?s("div",{role:"tabpanel",id:`${ne}-panel-${K}`,"aria-labelledby":`${ne}-tab-${K}`,hidden:L!==K,tabIndex:-1,children:L===K&&xe}):L===K&&s("div",{children:xe});return s(bo.Provider,{value:A.numberOf,children:s("div",{className:`opg-root${d?` ${d}`:""}`,"data-theme":h,"data-compact":_||void 0,style:f,children:[u&&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:[ve,s(Fp,{trace:r,state:r?$:null,playing:A.playing})]})]}),!u&&ve&&s("div",{className:"opg-tour-bar",children:ve}),v&&r&&$&&s(Dp,{trace:r,state:$,playing:A.playing,setPlaying:A.setPlaying,setCursor:A.setCursor,iterationNoun:a,liveFrame:Ie}),B!==null&&k[B]&&s(jp,{stop:k[B],at:B,count:k.length,focus:G,onBack:()=>H(Math.max(0,B-1)),onNext:()=>B+1V("skipped")}),te&&s(Hp,{receipt:te}),Te&&s("div",{className:"opg-tabs",role:"tablist","aria-label":"Program workbench views",children:i.map(K=>s("button",{ref:xe=>{xe&&pe.current.set(K,xe)},id:`${ne}-tab-${K}`,type:"button",role:"tab","aria-selected":L===K,"aria-controls":`${ne}-panel-${K}`,tabIndex:L===K?0:-1,onClick:()=>P(K),onKeyDown:xe=>oe(xe,K),children:Np[K]},K))}),i.includes("program")&&X("program",s(Op,{display:A.display,fullSpec:t,folds:S,expanded:A.expanded,setExpanded:A.setExpanded,traceState:$,selectedId:A.selectedId,setSelectedId:A.setSelectedId,titleFor:p,canvasNote:c?.canvas===void 0?Tp:c.canvas,layoutOptions:g,showInspector:m,plainStopRules:b,compact:_,resolveMedia:x,inspectorOpen:O,setInspectorOpen:M,onEditSection:e.onEditSection})),i.includes("evidence")&&X("evidence",s(Lp,{spec:t,titleFor:p,note:c?.evidence===void 0?$p:c.evidence})),i.includes("stops")&&X("stops",s(zp,{spec:t,titleFor:p,halt:$?.finished?$.halted:null,plain:b}))]})})}ut();var mt={host:"Qo",card:"V",cardIn:"do",body:"Vo",kicker:"Wo",line:"Zo",sub:"ar",action:"W",others:"ma"};function Bp(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 Kp(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 Si(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(" "),p=null,c="",g=()=>{let d=i.querySelector(".opg-inspector"),f=d?Kp(Bp(d),l,n):[];if(!f.length){p&&(p.remove(),p=null,c="",r({host:null,ids:[]}));return}p||(p=document.createElement("div"),p.className=mt.host,p.dataset.sealCardHost=""),d.firstChild!==p&&d.prepend(p);let u=f.join(" ");u!==c&&(c=u,r({host:p,ids:f}))},h=new MutationObserver(g);return h.observe(i,{childList:!0,subtree:!0,characterData:!0}),g(),()=>{h.disconnect(),p?.remove(),r({host:null,ids:[]})}},[e,a,n]),o}function Ei({seals:e,here:t=!1,Link:n="a"}){let[o,...r]=e,a=o.anchor?.kind==="stop",i=!t;return s("section",{className:mt.card,"data-tone":o.tone,"data-seal-card":i?"open":"here","aria-label":"This step's receipt",children:[s(pi,{seed:o.irisSeed,tone:o.tone,size:58}),s("div",{className:mt.body,children:[s("p",{className:mt.kicker,children:i?`Signed here${o.n?` · referral ${o.n}`:""}`:"This is the step the receipt covers"}),s("p",{className:mt.line,children:o.line}),s("p",{className:mt.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:mt.action,"data-seal-open":"",href:o.href,children:"Open the receipt →"}):null,r.length?s("p",{className:mt.others,children:[s("span",{children:"Also signed here:"}),r.map(l=>s(n,{href:l.href,children:["Referral ",l.n]},l.n))]}):null]})]})}var Wp=[];function kr({program:e,map:t={},step:n,status:o,onPick:r,anchor:a=null,sealRun:i=null,sealLine:l="",theme:p="dark",fill:c=!1}){let{spec:g,folds:h=null,titles:d={}}=e,f=h?.groups||Wp,u=re(()=>g.nodes.filter(M=>M.kind==="action").map(M=>M.id),[g]),v=re(()=>Object.fromEntries(f.flatMap(M=>M.nodes.map(k=>[k,M.id]))),[f]),m=re(()=>M=>d[M.id]||M.title,[d]),b=re(()=>mo(g,{title:m}),[g,m]),_=ee(null);U(()=>{let M=_.current;if(!M)return;for(let te of M.querySelectorAll("[data-seal-anchor]"))delete te.dataset.sealAnchor;if(!a)return;let k=u[a.step],B=d[k],H=f.find(te=>te.nodes.includes(k)),G=[...M.querySelectorAll(".opg-node")],V=te=>te.getAttribute("aria-label")||"",ve=(B?G.find(te=>!te.dataset.fold&&V(te).includes(B)):null)||(H?G.find(te=>te.dataset.fold&&V(te).includes(`: ${H.title}.`)):null);ve&&(ve.dataset.sealAnchor=a.kind)}),U(()=>{let M=_.current;if(!M||!c||typeof ResizeObserver>"u")return;let k=0,B=()=>{k=0;let G=M.querySelector(".opg-root"),V=M.querySelector(".opg-canvas-viewport");if(!G||!V)return;let ve=G.offsetHeight-V.offsetHeight,te=Math.max(240,Math.floor(M.clientHeight-ve-2));M.style.getPropertyValue("--seal-stage-h")!==`${te}px`&&M.style.setProperty("--seal-stage-h",`${te}px`)},H=new ResizeObserver(()=>{k||(k=requestAnimationFrame(B))});return H.observe(M),B(),()=>{H.disconnect(),cancelAnimationFrame(k),M.style.removeProperty("--seal-stage-h")}},[c]);let x=n!=null?u[n]:null,[w,E]=D(null);U(()=>E(null),[x]);let[R,S]=D([]),A=re(()=>[...new Set([...R,...x&&v[x]?[v[x]]:[]])],[R,x,v]),L=re(()=>x?{node:x,iteration:1,status:o||"running"}:null,[x,o]),P=a?u[a.step]:null,$=re(()=>P?[P]:[],[P]),O=Si(_,$,f).host;return s("div",{className:N.map,"data-step":n??"","data-fill":c?"1":void 0,ref:_,children:[s(xr,{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:p,playhead:L,selectedId:w||x||u[0],onSelect:(M,k)=>{if(k==="follow")return;if(P&&v[P]===M&&f.some(H=>H.id===M)){E(null),r(a.step);return}let B=u.indexOf(M);B>=0?(E(null),r(B)):E(M)},expanded:A,onExpandedChange:S}),O&&i?Kn(s(Ei,{seals:[{...i,line:l,anchor:a}],here:!0}),O):null]})}var Ni=3400,Vp=1700,qp=[1,2,4],Zp={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."},Yp=new Set(["unknown_key","key_mismatch","ambiguous_key"]),Ti=e=>Zp[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."),Zt=e=>`${(e/1e3).toFixed(1)} s`,Jp=(e,t)=>`${e} of ${t} record checks confirmed`,Xp=e=>e&&e.charAt(0).toUpperCase()+e.slice(1);function Qp(){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 eu(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 Ci="oa-theme",$i=()=>{try{let e=window.localStorage.getItem(Ci);return e==="light"||e==="dark"?e:null}catch{return null}},Ai=()=>window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark",Ri=()=>{let e=document.documentElement.getAttribute("data-theme");return e==="light"||e==="dark"?e:null};function tu(e){let[t,n]=D("dark");U(()=>{let r=()=>Ri()||$i()||Ai(),a=()=>{let c=r();e&&!Ri()&&document.documentElement.setAttribute("data-theme",c),n(c)};a();let i=window.matchMedia("(prefers-color-scheme: light)"),l=()=>{$i()||(e&&document.documentElement.setAttribute("data-theme",Ai()),a())};i.addEventListener("change",l);let p=new MutationObserver(()=>n(r()));return p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>{i.removeEventListener("change",l),p.disconnect()}},[e]);let o=Ee(()=>{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(Ci,r)}catch{}n(r)},[t]);return[t,o]}var Pi=["summary","steps","evidence","raw"],nu={summary:"Summary",program:"Program",steps:"Steps",evidence:"Evidence",raw:"Raw"};function ou(e){let t=new URLSearchParams(window.location.hash.replace(/^#/,"")),n=t.get("tab"),o=Number.parseInt(t.get("step")||"",10);return{tab:Pi.includes(n)||n==="program"?n:null,step:Number.isInteger(o)&&o>=1&&o<=e?o-1:null}}function Mi(e,t){let n=[];return e&&e!=="summary"&&n.push(`tab=${e}`),t!=null&&n.push(`step=${t+1}`),n.length?`#${n.join("&")}`:""}function ru(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,p=()=>{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(p):0},c=h=>{let d=n.getBoundingClientRect();o=Math.max(-1,Math.min(1,(h.clientX-d.left)/d.width*2-1)),r=Math.max(-1,Math.min(1,(h.clientY-d.top)/d.height*2-1)),l||(l=requestAnimationFrame(p))},g=()=>{o=0,r=0,l||(l=requestAnimationFrame(p))};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 Oi(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 Er({seal:e,host:t={}}){let{loadFiles:n=null,Link:o="a",links:r={},copyHref:a=null,live:i=!0,kicker:l=null,footer:p=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:d=!0,map:f={},signer:u=null,mediaNote:v="From this computer's run folder: not part of the receipt, never uploaded"}=t,{rings:m,seal:b,tone:_,label:x,line:w,job:E,app:R,startedAt:S,stopReason:A,media:L,tamper:P,runs:$,referral:O,referrals:M,files:k,keys:B,authorization:H,authorizedLine:G,authTiming:V,stopNote:ve,program:te,commands:Ie=null,irisSeed:ne}=e,pe=Qp(),[Te,oe]=D("build"),[X,K]=D(null),[xe,Se]=D(null),[tt,yo]=D(ne),Yt=!!(k.anchor||k.receiptAnchor||k.tsa),[T,z]=D(null),[ue,q]=D(null),[Y,$e]=D(null),[Oe,Le]=D(!1),[Q,he]=D(null),[nt,wt]=D(null),[Jt,Tn]=D(0),[Wi,Tr]=D(null),[$r,_o]=D(!1),[$n,Vi]=D(Ie),[Xt,qi]=tu(d),bt=eu("(min-width: 900px)"),[An,Ct]=D("summary"),[Zi,Yi]=D(!1),[xo,Ar]=D(!1),[ko,Rr]=D(50),[Mr,Ji]=D(!1),Rn=ee(null),wo=ee(null),Qt=ee(0);ru(wo,!pe);let Xi=ee(null),Ae=re(()=>ri(m),[m]),[Je,en]=D(null),[ot,vt]=D(!1),[So,Qi]=D(1),Fe=Je!==null,rt=Fe?Ae[Je]:null,el=re(()=>rt?ai(rt,m):null,[rt,m]);U(()=>{if(!d)return;let{body:y,documentElement:I}=document,W=[y.style.background,I.style.background];return y.style.background="var(--oa-canvas)",I.style.background="var(--oa-canvas)",()=>{y.style.background=W[0],I.style.background=W[1]}},[d]),U(()=>{try{let y=Number(window.localStorage.getItem("oa-seal-split"));y>=30&&y<=70&&Rr(y)}catch{}},[]);let tn=Ee(y=>{let I=Math.max(30,Math.min(70,Math.round(y)));Rr(I);try{window.localStorage.setItem("oa-seal-split",String(I))}catch{}},[]);U(()=>{let y=()=>{let I=ou(m.steps.length);I.tab&&Ct(I.tab),I.step!=null&&(he(I.step),Tn(I.step),I.tab||Ct("evidence"))};return y(),Ji(!0),window.addEventListener("hashchange",y),()=>window.removeEventListener("hashchange",y)},[m.steps.length]),U(()=>{An==="program"&&Yi(!0)},[An]),U(()=>{let y=window.location.origin;Ie&&h&&/^https?:/.test(y)&&y!==h&&Vi(Ie.split(h).join(y))},[Ie,h]);let tl=async(y,I,W)=>{if(y.sealOk&&!y.ok)return{...y,record:null};if(!y.sealOk&&(W.anchor||W.authorization))return{...y,ok:!1,reason:W.authorization?"auth_missing":"anchor_missing",record:null};if(!I.receiptKeys)return{...y,ok:!1,reason:"unknown_key",record:null};let Z;try{Z=JSON.parse(I.receiptText)}catch{return{...y,ok:!1,reason:"malformed",record:null}}let be=await Gs(Z,I.receiptKeys);if(!be.ok)return{...y,ok:!1,reason:be.reason,record:be};let le=await Re(I.report),Xe=be.statement.subject.find(Qe=>Qe.name==="report.json");if(!Xe||Xe.digest.sha256!==le)return{...y,ok:!1,reason:"subject_mismatch",subject:{sha256:le},record:be};if(I.receiptAnchorText!=null){let Qe=await fr(Z,I.receiptAnchorText,I.receiptKeys,be.signers);if(!Qe.ok){let Vr=Qe.reason||"inconsistent";return{...y,ok:!1,reason:Vr,subject:{sha256:le},record:{...be,ok:!1,reason:Vr,signerLines:["Not verified: the public log entry doesn't verify for this receipt"]},receiptAnchor:Qe}}let Ro=new Date(Qe.integratedTime*1e3).toISOString().replace(/\.\d+Z$/,"Z");return{...y,ok:!0,reason:null,subject:{sha256:le},record:{...be,signerLines:[...be.signerLines,`Logged publicly at ${Ro}`]},receiptAnchor:Qe}}return{...y,ok:!0,reason:null,subject:{sha256:le},record:be}},nn=Ee(async y=>{let I=++Qt.current;$e(y||null),K(null),Se(null),z(null),en(null),vt(!1),oe("verify");let W=new Promise(le=>setTimeout(le,pe?0:Vp)),Z,be=null;try{Rn.current=Rn.current||await(n?n():Us(k,H));let le=y?Vs(Rn.current,y):Rn.current,Xe={anchor:!!k.anchor,authorization:!!H};Z=le.sealText!=null?await Rs(le,B,{requireAnchor:Xe.anchor,requireAuthorization:Xe.authorization}):{ok:!1,sealOk:!1,reason:"malformed",steps:[]},le.receiptText&&(Z=await tl(Z,le,Xe)),Yt&&(Z.receiptAnchor&&!le.tsaText?be={rekor:Z.receiptAnchor,tsa:null}:(be=await ei(le,B),Z.receiptAnchor&&(be={...be,rekor:Z.receiptAnchor})));try{let Qe=le.sealText!=null?await yn(JSON.parse(le.sealText)):await Re(new TextEncoder().encode(Ce(JSON.parse(le.receiptText)))),Ro=await Re(new TextEncoder().encode(`${await Re(le.report)}${Qe}`));I===Qt.current&&yo(Ro)}catch{}}catch{Z={ok:!1,reason:"not_loaded",steps:[]}}I===Qt.current&&Se(Z.subject?.sha256??null),await W,I===Qt.current&&(z(be),K(Z),oe(Z.ok?"valid":Z.reason==="unsupported"||Z.reason==="not_loaded"?"rest":"broken"))},[k,B,H,pe,Yt,n]),[nl,ol]=D("unverified");U(()=>{if(!i||!H||!X?.ok||!X.authorizedBy?.publicKey)return;let y=!1;return vs(H.login,X.authorizedBy.publicKey).then(I=>{y||ol(I)}),()=>{y=!0}},[H,X,i]);let Eo=V??X?.timing??null,No=H&&(G||(Eo==="before_run"||Eo==="after_run")&&X?.ok)?xs(H.login,Eo,H.anchorTime??X?.authAnchorTime,nl):null,Ir=ee(!1);U(()=>{!i||!T?.rekor?.ok||Y||Ir.current||(Ir.current=!0,q("checking"),ni(T.rekor.entry).then(q))},[T,Y,i]),U(()=>{pe&&oe("rest");let y=setTimeout(()=>nn(null),pe?0:Ni+450);return()=>clearTimeout(y)},[pe]),U(()=>{if(!Fe||!ot)return;if(Je>=Ae.length-1){vt(!1);return}let y=setTimeout(()=>en(I=>Math.min(Ae.length-1,I+1)),Ae[Je].dwell/So);return()=>clearTimeout(y)},[Fe,ot,Je,Ae,So]);let To=Ee(()=>{Qt.current+=1,$e(null),oe("replay"),he(null),wt(null),Ct(y=>y==="program"?y:"evidence"),en(y=>y===null||y>=Ae.length-1?0:y),vt(!0)},[Ae.length]),St=Ee((y,I=!1)=>{oe("replay"),en(Math.max(0,Math.min(Ae.length-1,y))),I||vt(!1)},[Ae.length]),Cr=()=>{en(null),vt(!1),oe(X?.ok?"valid":X?"broken":"rest")},Pr=()=>St(si(Ae,Je??-1),ot),on=y=>{let I=rt?rt.step:-1,W=Math.max(0,Math.min(Ae.at(-1).step,I+y));St(io(Ae,W))};U(()=>{let y=I=>{let W=I.target;if(W&&(W.closest?.("input, textarea, select, [contenteditable]")||I.metaKey||I.ctrlKey||I.altKey))return;let Z=!!W?.closest?.('[role="tablist"], [role="separator"], [data-steplist], .opg-root'),be=W?.closest?.("button, a, summary");if(!(Z&&I.key!=="j"&&I.key!=="k")){if(I.key===" "&&!be&&!W?.closest?.("[data-step]"))I.preventDefault(),ot?vt(!1):To();else if(Fe&&I.key==="ArrowRight"&&!W?.closest?.("[data-step]"))I.preventDefault(),I.shiftKey?Pr():on(1);else if(Fe&&I.key==="ArrowLeft"&&!W?.closest?.("[data-step]"))I.preventDefault(),on(-1);else if(Fe&&I.key==="Escape")Cr();else if((I.key==="j"||I.key==="k")&&!I.shiftKey){I.preventDefault();let le=I.key==="j"?1:-1;if(Fe)on(le);else{let Xe=m.steps.length,Qe=Q??(le>0?-1:Xe);dt(Math.max(0,Math.min(Xe-1,Qe+le)))}}}};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)});let Mn=Fe?rt.step:Q??nt,rn=Mn!=null?m.steps[Mn]:null,Or=Ee((y,I={})=>{I.focus&&Tn(y),Je!==null?St(io(Ae,y)):wt(y)},[Je,Ae,St]),dt=Ee((y,{keepTab:I=!1}={})=>{Je!==null?St(io(Ae,y)):he(y),Tn(y),I||Ct(W=>W==="program"?W:"evidence")},[Je,Ae,St]),rl=y=>{let I=m.steps.length,W={ArrowRight:1,ArrowDown:1,ArrowLeft:-1,ArrowUp:-1},Z=null;if(y.key in W)Z=(Jt+W[y.key]+I)%I;else if(y.key==="Home")Z=0;else if(y.key==="End")Z=I-1;else if(y.key==="Escape"){he(null),wt(null),y.currentTarget.blur();return}else if(y.key==="Enter"||y.key===" "){y.preventDefault(),dt(Jt);return}else return;y.preventDefault(),Tn(Z),Or(Z),wo.current?.querySelector(`[data-step="${Z}"]`)?.focus()},We=An==="program"&&bt?"summary":An,$o=Fe?null:Q;U(()=>{if(!Mr||ot)return;let y=Mi(We,$o);if(!(y===window.location.hash||!y&&!window.location.hash))try{window.history.replaceState(window.history.state,"",`${window.location.pathname}${window.location.search}${y}`)}catch{}},[We,$o,Mr,ot]);let al=async()=>{try{await navigator.clipboard.writeText(`${a}${Mi(We,$o)}`),_o(!0),setTimeout(()=>_o(!1),2200)}catch{_o(!1)}},ze=m.counts,Lr=[{ring:"steps",big:`${ze.stepsPassed}/${ze.steps}`,small:m.stoppedAt==null?"steps passed":`steps, stopped at ${m.stoppedAt+1}`},{ring:"checks",big:`${ze.checksPassed}/${ze.checks}`,small:ze.checksFailed?`screen checks, ${ze.checksFailed} failed`:"screen checks"},{ring:"readbacks",big:`${ze.readbacksPassed}/${ze.readbacks}`,small:ze.readbacksFailed?`record checks, ${ze.readbacksFailed} failed`:ze.readbacksPassed?"record checks confirmed":"record checks, not reached"},{ring:"identity",big:`${ze.identityPassed}/${ze.identity}`,small:"right-record checks"}],zr=S?ii(S):null,Dr=l??(O?`Referral ${O} of ${M}`:null),an=!!Y,ke=Te==="verify"||Te==="build"?null:X?.ok?"valid":X?.reason==="unsupported"?"unsupported":X?.reason==="not_loaded"?"not_loaded":X?"fails":null,Fr=(y,I)=>y?I?I.ok?"pass":"fail":"pending":null,Hr=Yt?{rekor:Fr(k.anchor||k.receiptAnchor,T?.rekor),tsa:Fr(k.tsa,T?.tsa)}:null,sl=`The receipt of this run: ${Lr.map(y=>`${y.big} ${y.small}`).join("; ")}.`,Pt=Te==="verify"||Te==="build",Ot=rn,il=Ot?`Step ${Ot.i+1} of ${m.steps.length}${Ot.section?` · ${Ot.section}`:""}${Ot.t0!=null?` · at ${Zt(Ot.t0)}`:""}`:null,Ao=Fe?rt.step:Q,He=Ao!=null?m.steps[Ao]:null,ll=m.steps.filter(y=>y.status!=="not_reached").length,jr=ke===null?{state:"pending",text:Te==="build"?"Assembling":"Checking signature"}:ke==="valid"?{state:"valid",text:an?"Restored · signature valid":"Signature valid"}:ke==="fails"?{state:"fails",text:an?"Changed copy fails":"Signature check fails"}:ke==="unsupported"?{state:"unchecked",text:"Report matches · signature not checked here"}:{state:"unchecked",text:"Not checked here"},Gr=["summary","program","steps","evidence","raw"],Et=bt?Pi:Gr,cl=y=>{let I=Et.indexOf(We),W={ArrowRight:1,ArrowLeft:-1},Z=null;if(y.key in W)Z=Et[(I+W[y.key]+Et.length)%Et.length];else if(y.key==="Home")Z=Et[0];else if(y.key==="End")Z=Et[Et.length-1];else return;y.preventDefault(),Ct(Z),y.currentTarget.querySelector(`[data-tab="${Z}"]`)?.focus()},Ur=ee(null),Br=ee(null),Kr=ee(null);U(()=>{let y=Br.current,I=Kr.current;if(!y||!I||typeof ResizeObserver>"u")return;let W=new ResizeObserver(()=>I.style.setProperty("--top-h",`${y.offsetHeight}px`));return W.observe(y),()=>W.disconnect()},[]);let dl=y=>{let I={ArrowLeft:-2,ArrowRight:2};if(y.key in I)tn(ko+I[y.key]);else if(y.key==="Home")tn(30);else if(y.key==="End")tn(70);else if(y.key==="Enter")Ar(W=>!W);else return;y.preventDefault()},pl=y=>{let I=Ur.current;if(!I||y.button!==0)return;y.preventDefault();let W=y.currentTarget;W.setPointerCapture?.(y.pointerId);let Z=I.getBoundingClientRect(),be=Xe=>tn((Xe.clientX-Z.left)/Z.width*100),le=()=>{W.removeEventListener("pointermove",be),W.removeEventListener("pointerup",le),W.removeEventListener("pointercancel",le)};W.addEventListener("pointermove",be),W.addEventListener("pointerup",le),W.addEventListener("pointercancel",le)},ul=bt||We==="program"||Zi,fl=u==="demo"||b?.issuer==="demo",Lt=X?.record??null,Wr=Lt?ke===null?{state:"pending",text:"Checking who signed it"}:Lt.ok&&ke==="valid"?{state:Lt.demo?"demo":"signed",text:Lt.signerLines.join(" · ")}:Lt.reason==="unknown_signer"?{state:"unknown",text:"Not verified: unknown signer"}:{state:"fails",text:Lt.signerLines?.[0]||"Not verified"}:ke===null?{state:"pending",text:"Checking who signed it"}:ke==="valid"?fl?{state:"demo",text:"Demo key: checks only in this demo"}:u==="this_computer"?{state:"signed",text:"Signed by this computer"}:{state:"signed",text:"Signed by a pinned key"}:Yp.has(X?.reason)?{state:"unknown",text:"Not verified: unknown signer"}:ke==="fails"?{state:"fails",text:"Not verified: the signature check failed"}:{state:"unchecked",text:"Not verified here"},In=!!(e.receiptRecord||k?.receipt||k?.receiptText||X?.record),Cn=In&&e.receiptRecord?e.receiptRecord:b,hl=!In&&typeof b?.schema=="string"&&/^openadapt\.(local-seal|public-seal)\//.test(b.schema),gl=ke===null?s("span",{className:N.pending,children:Te==="build"?"Assembling the receipt from the report":"Checking the Ed25519 signature in your browser"}):ke==="valid"?s(se,{children:[s("b",{children:"Valid."})," This is the report exactly as the run wrote it, ",c,"."]}):ke==="unsupported"?s(se,{children:[s("b",{children:"The report matches."})," This browser can't check Ed25519 signatures; ",$n?"use the commands under Raw.":"check it from a terminal: openadapt verify RUN_FOLDER."]}):ke==="not_loaded"?s(se,{children:[s("b",{children:"The files didn't load,"})," so nothing was checked here. ",$n?"Use the commands under Raw.":"Check it from a terminal: openadapt verify RUN_FOLDER."]}):s(se,{children:[s("b",{children:"Fails."})," ",Ti(X.reason)," ",s("code",{className:N.code,children:X.reason})]});return s(se,{children:[s("a",{className:N.skip,href:"#main",onClick:y=>{y.preventDefault(),document.getElementById("main")?.focus()},children:"Skip to content"}),s("div",{ref:Kr,className:N.page,"data-tone":_,"data-phase":Te,"data-theme":d?void 0:Xt,"data-layout":bt?"split":"stack","data-expanded":bt&&xo?"1":void 0,"data-view":We,style:{"--split":`${ko}%`},children:[s("header",{className:N.top,ref:Br,children:[r.home?s(o,{href:r.home.href,className:N.home,"aria-label":r.home.label,children:[s(uo,{className:N.mark}),s("span",{children:r.home.label})]}):s("span",{className:N.home,children:[s(uo,{className:N.mark}),s("span",{children:"OpenAdapt"})]}),s("span",{className:N.crumb,children:[s("span",{children:"Signed run report"}),Dr?s("span",{children:Dr}):null]}),$?.length?s("nav",{className:N.runs,"aria-label":"The other runs",children:$.map(y=>s(o,{href:y.href,className:N.run,"data-tone":y.tone,"aria-current":y.sealId===e.sealId?"page":void 0,title:`Referral ${y.referral}: ${y.label}`,children:[s("span",{className:N.runSeal,"aria-hidden":"true",children:s(po,{rings:y.rings,tone:y.tone,digest:y.digest,variant:"emblem",phase:"rest",still:!0,label:""})}),s("span",{className:N.runText,children:[s("b",{children:y.referral}),s("span",{children:y.label})]})]},y.sealId))}):null,s("span",{className:N.topEnd,children:[s("span",{className:N.chip,"data-chip":jr.state,role:"status",children:[s("span",{className:N.chipDot,"aria-hidden":"true"}),jr.text]}),a?s("button",{type:"button",className:N.iconBtn,onClick:al,title:"Copy a link to this view","aria-label":$r?"Link copied":"Copy link",children:[s(au,{}),s("span",{className:N.wideOnly,children:$r?"Copied":"Copy link"})]}):null,s("button",{type:"button",className:N.iconBtn,onClick:qi,"aria-label":`Switch to the ${Xt==="dark"?"light":"dark"} theme`,title:`Switch to the ${Xt==="dark"?"light":"dark"} theme`,children:s(su,{theme:Xt})})]})]}),s("div",{className:N.app,ref:Ur,children:[s("main",{id:"main",tabIndex:-1,className:N.hero,"aria-labelledby":"seal-h1",children:[s("section",{className:N.stage,ref:wo,"aria-label":"The receipt",tabIndex:-1,onMouseLeave:()=>wt(null),children:s("div",{className:N.tilt,ref:Xi,children:s(po,{rings:m,tone:_,digest:tt,phase:Te,buildMs:Ni,active:Fe?null:Mn,focusIndex:Jt,onActive:Or,onPick:dt,onKey:rl,ringFocus:Wi,witnesses:Hr,lit:el,spot:rt?.spotlight||null,label:sl})})}),s("div",{className:N.heading,children:[s("h1",{id:"seal-h1",className:N.outcome,children:x}),A?s("p",{className:N.reason,children:Xp(A)}):null,s("p",{className:N.meta,children:[s("span",{children:E}),s("span",{children:R}),zr?s("span",{children:zr}):null]}),s("p",{className:N.verdict,"data-verdict":ke||"pending","aria-live":"polite",children:gl}),s("p",{className:N.signer,"data-signer":Wr.state,children:s("span",{children:Wr.text})}),an&&ke==="fails"?s("div",{className:N.changed,"data-changed":"",children:[s("p",{className:N.changeHead,children:[s("b",{children:"This changed copy fails:"})," ",Y.field==="model_calls"?"model calls":"outcome"," ",Y.from," → ",Y.to,". The receipt no longer matches."]}),s("p",{className:N.change,children:["Changed in a copy of the ",Y.target==="seal"?"receipt":"report",": ",s("code",{children:Y.field})," ",s("del",{children:Y.from})," → ",s("ins",{children:Y.to}),"."]}),s("p",{className:N.change,children:g}),s("div",{className:N.actions,children:[s("button",{type:"button",className:N.primary,onClick:()=>nn(null),disabled:Pt,children:"Restore"}),s("button",{type:"button",className:N.ghost,"aria-expanded":Oe,"aria-controls":"receipt-changes",onClick:()=>Le(y=>!y),children:"Try another change"})]}),s("div",{id:"receipt-changes",className:N.another,role:"group","aria-label":"Other changes",hidden:!Oe,children:P.filter(y=>y.id!==Y.id).map(y=>s("button",{type:"button",className:N.tchip,disabled:Pt,onClick:()=>nn(y),children:[s("span",{children:y.label}),s("code",{children:[y.from," → ",y.to]})]},y.id))})]}):null,s("div",{className:N.actions,children:[s("button",{type:"button",className:N.primary,onClick:ot?()=>vt(!1):To,disabled:Pt,children:[s("span",{"aria-hidden":"true",children:ot?"❚❚":"▶"}),ot?"Pause the run":Fe?"Resume the run":"Play the run"]}),s("button",{type:"button",className:N.ghost,onClick:()=>nn(null),disabled:Pt,children:"Verify"}),an&&ke==="fails"?null:s("button",{type:"button",className:N.ghost,onClick:()=>{Le(!1),nn(P[0])},disabled:Pt||!P.length,children:"Try changing it"})]})]}),s("div",{className:N.dock,children:[s(lu,{frames:Ae,frame:Je,playing:ot,speed:So,busy:Pt,rings:m,onPlay:To,onPause:()=>vt(!1),onSeek:St,onNext:Pr,onSpeed:Qi,onClose:Cr}),s("p",{className:N.stepLine,"data-step":rn?rn.i:"","aria-live":"polite",children:il||(ke==="valid"?`✓ Signature valid over this exact report · ${ll} steps`:ke==="fails"?`✗ ${Ti(X?.reason)}`:" ")})]})]}),s("section",{className:N.mapPane,"aria-labelledby":"map-h",id:"seal-panel-program",role:bt?void 0:"tabpanel",children:[s("div",{className:N.paneHead,children:[s("h2",{id:"map-h",children:"Program steps for this run"}),bt?s("button",{type:"button",className:N.iconBtn,"aria-pressed":xo,onClick:()=>Ar(y=>!y),children:xo?"Show details":"Expand map"}):null]}),ul?s(kr,{program:te,map:{title:`${E} · ${R}`,...f},step:Mn,status:rn?rn.status==="stopped"?"stopped":rt?.stage==="done"?"saved":"running":null,onPick:y=>dt(y),anchor:m.anchor,sealRun:{rings:m,tone:_,irisSeed:tt,referral:O},sealLine:li({rings:m,label:x,stopReason:A},ke==="valid"),theme:Xt,fill:bt}):null]}),s("div",{className:N.resizer,role:"separator","aria-orientation":"vertical","aria-label":"Resize the program map","aria-valuenow":ko,"aria-valuemin":30,"aria-valuemax":70,tabIndex:0,onKeyDown:dl,onPointerDown:pl,onDoubleClick:()=>tn(50),title:"Drag, or use the arrow keys. Enter expands the map."}),s("div",{className:N.tabs,role:"tablist","aria-label":"Details",onKeyDown:cl,children:Gr.map(y=>s("button",{type:"button",role:"tab",id:`seal-tab-${y}`,"data-tab":y,"aria-selected":We===y,"aria-controls":`seal-panel-${y}`,tabIndex:We===y?0:-1,onClick:()=>Ct(y),children:[nu[y],y==="steps"?s("span",{className:N.count,children:m.steps.length}):null,y==="evidence"&&He?s("span",{className:N.count,children:He.i+1}):null]},y))}),s("div",{className:N.panels,children:[s("section",{id:"seal-panel-summary",role:"tabpanel","aria-labelledby":"seal-tab-summary",hidden:We!=="summary",className:N.panel,children:[s("p",{className:N.line,children:w}),H&&No?s("p",{className:N.by,children:s("a",{href:`https://github.com/${H.login}`,rel:"noopener noreferrer",children:No})}):null,s("dl",{className:N.stats,"aria-label":"What the receipt shows",children:Lr.map(y=>s("div",{"data-ring":y.ring,onMouseEnter:()=>Tr(y.ring),onMouseLeave:()=>Tr(null),children:[s("dt",{children:[s("span",{className:N.swatch,"aria-hidden":"true"}),y.small]}),s("dd",{children:y.big})]},y.ring))}),s("p",{className:N.calls,children:ze.modelCalls==null?`The program ran for ${Zt(m.runMs)}.`:`The program ran for ${Zt(m.runMs)} and made ${ze.modelCalls} AI model calls.`}),s("h2",{className:N.sub,children:"The signature check"}),s("div",{className:N.proof,children:[s(gr,{label:an&&Y.target==="report"?"This copy of report.json":"report.json, in this browser",from:Cn.signature,to:xe,against:Cn.subject_sha256,running:Te==="verify",still:pe}),s("div",{className:N.signed,children:[s("span",{className:N.proofLabel,children:"Signed in the receipt"}),s("code",{className:N.hex,children:Cn.subject_sha256})]})]}),s("p",{className:N.foot,children:[p||"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:N.panel,children:s(iu,{rings:m,active:Ao,onPick:y=>dt(y),onFocusStep:y=>dt(y,{keepTab:!0})})}),s("section",{id:"seal-panel-evidence",role:"tabpanel","aria-labelledby":"seal-tab-evidence",hidden:We!=="evidence",className:N.panel,children:He?s(se,{children:[s("div",{className:N.evHead,children:[s("p",{className:N.evTitle,children:[s("span",{className:N.evNum,children:["Step ",He.i+1," of ",m.steps.length]}),He.section?s("span",{children:He.section}):null,He.t0!=null?s("span",{children:["at ",Zt(He.t0)]}):null]}),s("span",{className:N.evNav,children:[s("button",{type:"button",className:N.iconBtn,onClick:()=>Fe?on(-1):dt(Math.max(0,He.i-1)),disabled:He.i===0,"aria-label":"Previous step",title:"Previous step (k)",children:"‹"}),s("button",{type:"button",className:N.iconBtn,onClick:()=>Fe?on(1):dt(Math.min(m.steps.length-1,He.i+1)),disabled:He.i===m.steps.length-1,"aria-label":"Next step",title:"Next step (j)",children:"›"})]})]}),s(cu,{step:He,rings:m,media:L[He.i],frame:rt,stopReason:A,stopNote:ve,mediaNote:v})]}):s("div",{className:N.empty,children:[s("p",{children:["Pick a step on the map, on the receipt or in Steps to see its checks",L.some(y=>y&&(y.crop||y.frame))?", its pictures":""," and its record checks."]}),m.anchor?s("button",{type:"button",className:N.ghost,onClick:()=>dt(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:N.panel,children:[hl?s("p",{className:N.older,"data-format":"",children:["Format: ",b.schema.replace(/^openadapt\./,""),", still verifies"]}):In?s("p",{className:N.older,"data-format":"",children:"Format: record/run/v1"}):null,s(pu,{seal:Cn,isRecord:In,files:k,links:r,witnesses:Hr,witness:T,live:Y?null:ue,authorization:H,authorizedLine:No}),$n?s(se,{children:[s("h2",{className:N.sub,children:e.commandsLabel||"Check the same files on your computer"}),s("pre",{className:N.cmds,tabIndex:0,children:s("code",{children:$n})})]}):null]})]})]})]})]})}function au(){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 su({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 iu({rings:e,active:t,onPick:n,onFocusStep:o}){let r=ee(null),[a,i]=D(t??0);U(()=>{t!=null&&i(t)},[t]);let l=e.steps.length,p=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:N.steps,ref:r,"data-steplist":"",onKeyDown:p,"aria-label":"The run's steps",children:e.steps.map(c=>{let g=e.identity.find(f=>f.step===c.i),h=e.readbacks.filter(f=>f.step===c.i),d=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:N.sNum,children:String(c.i+1).padStart(2,"0")}),s("span",{className:N.sMark,"aria-hidden":"true",children:c.status==="passed"?"✓":c.status==="stopped"?"■":"·"}),s("span",{className:N.sName,children:[c.name,c.section?s("small",{children:c.section}):null]}),s("span",{className:N.sTags,children:[g?s("span",{"data-ok":g.result==="passed"?"1":"0",children:"record"}):null,d?s("span",{"data-ok":c.checks.failed?"0":"1",children:[d," ",d===1?"check":"checks"]}):null,h.length?s("span",{"data-ok":h.some(f=>f.result==="failed")?"0":"1",children:[h.length," record ",h.length===1?"check":"checks"]}):null]}),s("span",{className:N.srOnly,children:[c.status==="passed"?", passed":c.status==="stopped"?", stopped here":", not reached",g?", checks the right record":""]})]})},c.i)})})}function lu({frames:e,frame:t,playing:n,speed:o,busy:r,rings:a,onPlay:i,onPause:l,onSeek:p,onNext:c,onSpeed:g,onClose:h}){let d=t??0,f=e[d],u=f?a.steps[f.step]?.t0??0:0;return s("div",{className:N.player,"data-active":t!==null?"1":void 0,children:[s("button",{type:"button",className:N.pBtn,onClick:n?l:i,disabled:r,"aria-label":n?"Pause":"Play the run",children:n?"❚❚":"▶"}),s("button",{type:"button",className:N.pBtn,onClick:c,disabled:r,"aria-label":"Next highlight",title:"Next highlight (Shift + →)",children:"⏭"}),s("input",{className:N.scrub,type:"range",min:"0",max:e.length-1,value:d,disabled:r,"aria-label":"Position in the run","aria-valuetext":f?`Step ${f.step+1} of ${a.steps.length}`:void 0,onChange:v=>p(Number(v.target.value))}),s("span",{className:N.pTime,children:[Zt(u)," / ",Zt(a.runMs)]}),s("span",{className:N.speeds,role:"group","aria-label":"Speed",children:qp.map(v=>s("button",{type:"button","aria-pressed":o===v,onClick:()=>g(v),children:[v,"×"]},v))}),t!==null?s("button",{type:"button",className:N.pBtn,onClick:h,"aria-label":"Leave the replay",children:"×"}):null]})}function cu({step:e,rings:t,media:n,frame:o,stopReason:r,stopNote:a,mediaNote:i}){let l=t.readbacks.filter(u=>u.step===e.i),p=t.identity.find(u=>u.step===e.i),c=e.checks.passed+e.checks.failed,g=!!o,h=g?o.step===e.i?o.readbacks:0:l.length,d=g?o.spotlight:null,f=[["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"],p?["Right record",p.result==="passed"?"✓ Confirmed before acting":p.result==="not_reached"?"Not reached":"✗ Not confirmed",p.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",Jp(l.filter(u=>u.result==="passed").length,l.length),l.some(u=>u.result==="failed")?"halt":l.every(u=>u.result==="passed")?"ok":"ghost","save"]:null].filter(Boolean);return s("aside",{className:N.inspector,"data-status":e.status,"data-step":e.i,"data-spot":d||void 0,"aria-live":"polite",children:[s("div",{className:N.inMain,children:[s("table",{className:N.kv,children:s("tbody",{children:f.map(([u,v,m,b])=>s("tr",{"data-tone":m,"data-spot":d&&d===b?"1":void 0,children:[s("th",{scope:"row",children:u}),s("td",{children:v})]},u))})}),d==="stop"&&a?s("p",{className:N.spotNote,children:a}):null,n&&(n.crop||n.frame)?s("div",{className:N.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:N.shotsNote,"data-media-note":"",children:i}):null]}):null]}),l.length?s("table",{className:N.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((u,v)=>{let m=vnew Date(e*1e3).toISOString().replace("T"," ").replace(/\.\d+Z$/," UTC"),wr=e=>String(e).replace("T"," ").replace(/(\.\d+)?Z$/," UTC"),Sr=(e,t=16)=>`${String(e).slice(0,t)}…`,Ii={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 pu({seal:e,isRecord:t=!1,files:n,links:o,witnesses:r,witness:a,live:i,authorization:l,authorizedLine:p}){let c=a?.rekor,g=a?.tsa,h=[["Outcome",s("code",{children:e.outcome},"o"),null],["Report SHA-256",s("code",{title:e.subject_sha256,children:Sr(e.subject_sha256,24)},"d"),null],["Signed by",s("code",{children:e.key_id},"k"),null],["Signature",s("code",{title:e.signature,children:Sr(e.signature,24)},"s"),"Ed25519"],...t?[...e.started_hour?[["Started",wr(e.started_hour),null]]:[],...e.program_id?[["Program",s("code",{children:e.program_id},"pr"),null]]:[]]:[["Issued",wr(e.issued_at),null],...e.scope_item?[["Scope",s("code",{children:e.scope_item},"sc"),null]]:[]]];return r?.rekor&&h.push(["Public log",r.rekor==="pending"?"Checking…":c?.ok?s("span",{children:["Sigstore Rekor entry"," ",s("a",{href:ti(c.logIndex),rel:"noopener noreferrer",children:c.logIndex}),", logged ",du(c.integratedTime),", log ",s("code",{children:Sr(c.logId,8)}),". The inclusion proof, signed timestamp and checkpoint verify against the pinned Rekor key.",i==="match"?" This entry matches the public log.":i==="differs"?" The public log serves a different entry.":""]},"r"):s("span",{children:[Ii[c?.reason]||"The log entry doesn't verify."," ",s("code",{children:c?.reason})]},"rf"),r.rekor]),r?.tsa&&h.push(["Timestamp",r.tsa==="pending"?"Checking…":g?.ok?s("span",{children:["Sigstore Timestamp Authority (RFC 3161): ",wr(g.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:[Ii[g?.reason]||"The timestamp doesn't verify."," ",s("code",{children:g?.reason})]},"tf"),r.tsa]),l&&p&&h.push(["Authorized",s("span",{children:[p,", with an SSH key"," ",s("a",{href:`https://github.com/${l.login}.keys`,rel:"noopener noreferrer",children:["GitHub lists for @",l.login]}),"."]},"a"),"pass"]),s("section",{className:N.record,"aria-labelledby":"record-h",children:[s("h2",{id:"record-h",className:N.recordH,children:"The signed record"}),s("table",{className:N.recordTable,children:s("tbody",{children:h.map(([d,f,u])=>s("tr",{"data-state":u||void 0,children:[s("th",{scope:"row",children:[u==="pass"||u==="fail"||u==="pending"?s("span",{className:N.wMark,"aria-hidden":"true"}):null,d]}),s("td",{children:f})]},d))})}),o.file?s("p",{className:N.fileLinks,children:[["report.json",n.receipt?"receipt.json":null,n.receiptAnchor?"receipt.anchor.json":null,n.seal?"seal.json":null,n.anchor?"seal.anchor.json":null,n.tsa?"seal.tsa.json":null,n.tsr?"seal.tsr":null].filter(Boolean).map(d=>[d,lo(o.file(d))]).filter(([,d])=>d).map(([d,f])=>s("a",{href:f,children:d},d)),o.keys&&lo(o.keys.href)?s("a",{href:lo(o.keys.href),children:o.keys.label}):null]}):null]})}var Li={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 Nr(e){if(Li[e])return Li[e];let t=String(e).replace(/[_-]+/g," ").trim();return t.charAt(0).toUpperCase()+t.slice(1)}function zi(e){let t=e.match(/^type <(\w+)>$/);if(t)return`Type ${Nr(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 uu={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"},It=e=>String(e).replace(/^.*::/,"");function fu(e){let t=/field '(\w+)' equals/.exec(e||"");return t?`${uu[t[1]]||Nr(t[1])} matches`:/record_written/.test(e||"")?"The new record exists":null}function Di(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,E)=>{if(It(w.step_id)!==It(t.steps[E].id))throw new Error(`step ${E+1}: the report and the program differ`)});let o=0,r=n.map(w=>{let E=Math.max(0,Number(w.elapsed_ms)||0),R={t0:o,t1:o+E};return o+=E,R}),a=o,i=e.outcome_envelope?.postcondition_evidence||[],l=new Map;for(let w of i){let E=l.get(w.result_index)||[];E.push(w),l.set(w.result_index,E)}let p=t.steps.map((w,E)=>{let R=n[E],S=R?R.ok?"passed":"stopped":"not_reached",A=l.get(E)||[];return{i:E,id:It(w.id),name:w.name,section:w.section,status:S,t0:R?r[E].t0:null,t1:R?r[E].t1:null,checks:{passed:A.filter(L=>L.verdict==="passed").length,failed:A.filter(L=>L.verdict!=="passed").length},identity:R?R.identity?.status==="verified"?"passed":R.identity?"failed":null:null}}),c=i.map(w=>{let E=p[w.result_index];if(!E||E.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:E.t1}}),g=Array.isArray(e.governed_qualified_effect_requirements)?e.governed_qualified_effect_requirements:[],h=g.length?g.map(w=>({step:p.findIndex(E=>E.id===It(w.step_id??"")),at:Number.isInteger(w.effect_index)?w.effect_index:-1})):n.flatMap((w,E)=>(Array.isArray(w.effect_evidence)?w.effect_evidence:[]).map((R,S)=>({step:E,at:S}))),d=h.map((w,E)=>{let R=n[w.step],S=Array.isArray(R?.effect_evidence)?R.effect_evidence:[],A=Array.isArray(R?.effect_results)?R.effect_results:[],L=S[w.at],P=R?r[w.step]:null,$=h.filter(M=>M.step===w.step),O=$.indexOf(w);return{i:E,step:w.step,result:L?L.final_verdict==="confirmed"?"passed":"failed":"not_reached",label:w.at>=0&&fu(A[w.at])||null,t:L&&P?P.t0+(P.t1-P.t0)*(.55+.45*O/$.length):null}}),u=(Array.isArray(e.required_identity_step_ids)?e.required_identity_step_ids.map(It):[]).map(w=>{let E=p.find(R=>R.id===w);if(!E)throw new Error(`a right-record check on an unknown step ${w}`);return{step:E.i,result:E.identity??"not_reached",t:E.t0==null?null:E.t0+(E.t1-E.t0)*.3}}),v=p.find(w=>w.status==="stopped")||null,m=(w,E)=>w.filter(R=>R.result===E).length,b=d.find(w=>w.result==="passed"),_=[...p].reverse().find(w=>w.status!=="not_reached"),x=v?{step:v.i,kind:"stop"}:b?{step:b.step,kind:"save"}:_?{step:_.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:x,steps:p,checks:c,readbacks:d,identity:u,counts:{steps:p.length,stepsPassed:p.filter(w=>w.status==="passed").length,checks:c.length,checksPassed:m(c,"passed"),checksFailed:m(c,"failed"),readbacks:d.length,readbacksPassed:m(d,"passed"),readbacksFailed:m(d,"failed"),identity:u.length,identityPassed:m(u,"passed"),modelCalls:e.model_calls??null}}}function Fi(e,{folds:t=null,report:n=null,titles:o=null,digest:r=null}={}){let a=(e?.nodes||[]).filter(p=>p.kind==="action"),i=new Map((Array.isArray(n?.results)?n.results:[]).map(p=>[It(p.step_id),p.intent])),l=new Map;for(let p of t?.groups||[])for(let c of p.nodes)l.set(c,p.title);return{digest:r||e?.bundle?.provenance?.content_digest||t?.source?.body_content_digest||null,steps:a.map(p=>{let c=i.get(It(p.id));return{id:p.id,name:o?.[p.id]||(c?zi(c):p.title),section:l.get(p.id)||null}})}}function hu(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 gu=[[/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"]],mu={"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 bu(e){let t=[e?.halt?.reason,e?.halt?.intent].filter(Boolean).join(" "),n=gu.find(([o])=>o.test(t));return n?n[1]:null}function Hi(e,t,n){let o=hu(t?.outcome,e?.transaction_outcome,{readBack:!!n?.counts?.readbacksPassed}),r=t?.outcome==="VERIFIED"?null:bu(e);return{...o,headline:r?`${o.label}: ${r}`:o.label,reason:r,note:r&&mu[r]||null}}var ji=e=>new TextDecoder().decode(e),vo=async e=>Re(new TextEncoder().encode(e));function vu(e){let t=JSON.parse(e),n=JSON.parse(ji(Pe(t.payload))),o=n.predicate||{},r=(n.subject||[]).find(i=>i?.name==="report.json"),a=Array.isArray(t.signatures)?t.signatures:[];return{envelope:t,record:{outcome:o.outcome??"",subject_sha256:r?.digest?.sha256??"",key_id:a.map(i=>i?.keyid).filter(Boolean).join(", "),signature:a[0]?.sig??"",started_hour:o.started_hour??null,program_id:o.program?.id??null,schema:"record/run/v1"}}}var yu=async e=>vo(e.subject_sha256+await vo(Ce(e)));async function Gi({files:e,keys:t,program:n,about:o={},authorization:r=null}){let a=e.sealText!=null?JSON.parse(e.sealText):null,i=e.receiptText!=null?vu(e.receiptText):null,l=i?.record??null;if(!a&&!l)throw new Error("the run has no seal or receipt");let p=a||l,c=JSON.parse(ji(e.report)),g=Fi(n.spec,{folds:n.folds||null,titles:n.titles||null,digest:n.digest||null,report:c}),h=Di(c,g),d=Hi(c,l||a,h),f=a?await yu(a):await vo(l.subject_sha256+await vo(Ce(i.envelope)));return{files:e,page:{id:o.id||a?.run_id||c.run_id||"",tone:d.tone,label:d.label,headline:d.headline,line:d.line,job:o.job||c.workflow_name||"Run",app:o.app||"Test copy",startedAt:c.started_at??null,stopReason:d.reason,stopNote:d.note,rings:h,irisSeed:f,media:h.steps.map(()=>({crop:null,frame:null})),seal:p,receiptRecord:l,keys:t,files:{report:"report.json",seal:e.sealText!=null?"seal.json":null,receipt:e.receiptText!=null?"receipt.json":null,anchor:e.anchorText!=null?"seal.anchor.json":null,receiptAnchor:e.receiptAnchorText!=null?"receipt.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:Ws(p.outcome,c.execution_outcome),program:{spec:n.spec,folds:n.folds||null,titles:Object.fromEntries(g.steps.map(u=>[u.id,u.name]))},runs:[]}}}var Ui=e=>Uint8Array.from(atob(e),t=>t.charCodeAt(0));function Bi({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 _u(){let e=(0,Ki.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&&!n.receipt_text){e.render(s(Bi,{text:"The page has no run in it. Write one with: openadapt receipt view RUN_FOLDER"}));return}let o={report:Ui(n.report_b64),sealText:n.seal_text??null,anchorText:n.anchor_text??null,tsaText:n.tsa_text??null,tsrBytes:n.tsr_b64?Ui(n.tsr_b64):null,auth:n.auth??null,receiptText:n.receipt_text??null,receiptAnchorText:n.receipt_anchor_text??null,receiptKeys:n.receipt_keys??null},r;try{r=await Gi({files:o,keys:n.keys,program:n.program,about:n.about||{},authorization:n.authorization??null})}catch(l){e.render(s(Bi,{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=Oi(a).title;let i=n.host||{};e.render(s(Er,{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/"}}}))}_u();})(); +-----END CERTIFICATE-----`,Wd="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"},qs={[Ne.sha256]:"SHA-256",[Ne.sha384]:"SHA-384",[Ne.sha512]:"SHA-512"},Vd={[Ne.ecdsaSha256]:"SHA-256",[Ne.ecdsaSha384]:"SHA-384",[Ne.ecdsaSha512]:"SHA-512"},qd={[Ne.p256]:["P-256",32],[Ne.p384]:["P-384",48]},ao=class extends Error{},qe=e=>{throw new ao(e)};function Bt(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 ie(e){let t=[],n=e.start;for(;ne&&e.tag===t?e:qe(`tag ${t}`);function Be(e){ye(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 ur(e){let t=Zd(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 Yd=e=>Array.from(e,t=>t.toString(16).padStart(2,"0")).join(""),pr=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]);function Jd(e){let t=String(e).replace(/-----[^-]+-----/g,"").replace(/\s+/g,""),n=atob(t);return Uint8Array.from(n,o=>o.charCodeAt(0))}function Js(e){let[t,n,o]=ie(ye(e,48)),r=ie(ye(t,48)),a=r[0].tag===160?1:0,i=r[a+2],l=ie(r[a+3]),p=r[a+4],c=ye(r[a+5],48),[g]=ie(c),[h,d]=ie(g),f=!1;for(let u of r.slice(a+6))if(u.tag===163)for(let v of ie(ie(u)[0])){let m=ie(v);if(Be(m[0])!==Ne.extKeyUsage)continue;f=ie(Bt(m.at(-1).content,0)).some(_=>Be(_)===Ne.timeStamping)}return{tbs:t.raw,sigAlg:Be(ie(n)[0]),signature:ye(o,3).content.subarray(1),issuer:i.raw,subject:p.raw,notBefore:ur(l[0]),notAfter:ur(l[1]),spki:c.raw,keyAlg:Be(h),curve:d&&d.tag===6?Be(d):null,timestamping:f,serial:r[a].content}}function Xd(e,t){let[n,o]=ie(ye(Bt(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 p=new Uint8Array(t);return p.set(l,t-l.length),p},a=new Uint8Array(t*2);return a.set(r(n),0),a.set(r(o),t),a}async function Zs(e,t,n,o){let r=Vd[t],a=qd[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,Xd(n,a[1]),o)}function Qd(e){let t=ie(ye(Bt(e,0),48));Be(t[0])!==Ne.signedData&&qe("not signed data");let n=ie(ye(ie(ye(t[1],160))[0],48)),o=ie(ye(n[2],48));Be(o[0])!==Ne.tstInfo&&qe("not a timestamp");let r=ye(ie(ye(o[1],160))[0],4).content,a=3,i=[];if(n[a]&&n[a].tag===160){for(let w of ie(n[a]))i.push(Js(w));a+=1}n[a]&&n[a].tag===161&&(a+=1);let l=ie(ye(n[a],49));l.length!==1&&qe("signers");let p=ie(ye(l[0],48)),c=p[1],g=Be(ie(p[2])[0]),h=ye(p[3],160),d=Be(ie(p[4])[0]),f=ye(p[5],4).content,u={};for(let w of ie(h)){let[E,R]=ie(w);u[Be(E)]=ie(R)[0]}let v=ie(ye(Bt(r,0),48)),[m,b]=ie(ye(v[2],48)),_=c.tag===48?ie(c)[1].content:null,x=Uint8Array.from(h.raw);return x[0]=49,{eContent:r,certs:i,signerSerial:_,digestAlg:g,sigAlg:d,signature:f,signedBytes:x,contentType:u[Ne.contentType]?Be(u[Ne.contentType]):null,messageDigest:u[Ne.messageDigest]?ye(u[Ne.messageDigest],4).content:null,policy:Be(v[1]),imprintAlg:Be(ie(m)[0]),imprint:Yd(ye(b,4).content),genTime:ur(v[4])}}async function ep(e,t=Kd){let n;try{n=Qd(e)}catch{return{ok:!1,reason:"tsa_malformed"}}let o={genTime:n.genTime,imprint:n.imprint,imprintAlg:qs[n.imprintAlg]||n.imprintAlg},r=(a,i)=>({ok:a,reason:i,...o});try{let a=qs[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(!pr(i,n.messageDigest))return r(!1,"tsa_content_mismatch");let l=Js(Bt(Jd(t),0)),p=n.certs.find(g=>n.signerSerial&&pr(g.serial,n.signerSerial))||(n.certs.length===1?n.certs[0]:null);if(!p)return r(!1,"tsa_untrusted");if(!await Zs(p,n.sigAlg,n.signature,n.signedBytes))return r(!1,"tsa_bad_signature");if(!pr(p.issuer,l.subject)||!await Zs(l,p.sigAlg,p.signature,p.tbs))return r(!1,"tsa_untrusted");if(!p.timestamping)return r(!1,"tsa_not_timestamping");let c=Date.parse(n.genTime);for(let g of[p,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 ao?"tsa_malformed":"tsa_bad_signature")}}var tp=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}\.tsr$/,Ys=/^[a-f0-9]{64}$/;async function np(e){return[...new Uint8Array(await crypto.subtle.digest("SHA-256",e))].map(n=>n.toString(16).padStart(2,"0")).join("")}function Xs(e){if(typeof e!="string"||et(e)!==null)return null;let t;try{t=JSON.parse(e)}catch{return null}return!t||typeof t!="object"||Array.isArray(t)||t.schema!==Wd||typeof t.tsr_file!="string"||!tp.test(t.tsr_file)||!Ys.test(t.tsr_sha256)||!Ys.test(t.imprint_sha256)||"token"in t?null:t}async function op(e,t,n){let o=Xs(e);if(!o)return{ok:!1,reason:"tsa_malformed"};if(!t||!t.length)return{ok:!1,reason:"tsa_token_missing"};if(await np(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 ep(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 Qs(e,t,n){let o=Xs(e);return o?o.seal_sha256!==t?{ok:!1,reason:"tsa_imprint_mismatch",matches:!1}:op(e,n,t):{ok:!1,reason:"tsa_malformed"}}function so(e){if(e==null||et(e)!==null)return null;try{return JSON.parse(e)}catch{return null}}async function fr(e,t,n,o=null,{logKeys:r=null}={}){let a=so(t);if(!e||!a)return{ok:!1,reason:"anchor_malformed",entry:null};let i=Array.isArray(n?.keys)?n.keys:Gt(n),l=o?new Set(o.map(h=>h.keyId)):new Set((Array.isArray(e.signatures)?e.signatures:[]).map(h=>h?.keyid).filter(Boolean)),p=i.filter(h=>l.has(h.key_id)&&(h.status??"active")==="active");if(!p.length)return{ok:!1,reason:"anchor_key_mismatch",entry:null};let c=r||[await vn(mn)],g={ok:!1,reason:"anchor_mismatch",entry:null};for(let h of p){let d=await $s(e,a,Pe(h.public_key),c);if(d.ok&&d.integratedTime!=null)return{...d,entry:a.entry};g={...d,entry:null}}return g}async function ei(e,t,{logKeys:n=null}={}){let o=so(e.sealText),r=null,a=null;if(e.receiptText!=null&&e.receiptAnchorText!=null)r=await fr(so(e.receiptText),e.receiptAnchorText,e.receiptKeys,null,{logKeys:n});else if(e.anchorText!=null){let i=so(e.anchorText),l=o?Gt(t).filter(p=>p.key_id===o.key_id&&p.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 p=n||[await vn(mn)],c=await to(o,i,Pe(l[0].public_key),p);r={...c,entry:c.ok?i.entry:null}}}return e.tsaText!=null&&(a=o?await Qs(e.tsaText,await yn(o),e.tsrBytes??null):{ok:!1,reason:"tsa_malformed"}),{rekor:r,tsa:a}}var rp="https://rekor.sigstore.dev/api/v1/log/entries",ti=e=>`https://search.sigstore.dev/?logIndex=${Number(e)}`;async function ni(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(`${rp}?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 p=i[l[0]];return String(l[0]).slice(-64)===String(e.uuid).slice(-64)&&p?.body===e.body&&p?.integratedTime===e.integratedTime&&p?.logID===e.logID&&p?.logIndex===e.logIndex?"match":"differs"}catch{return"unavailable"}finally{r&&clearTimeout(r)}}var oi=[700,1500],Kt={identity:2600,checks:2200,save:1800,readback:650,stop:4200,done:1600};function ri(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(oi[1],Math.max(oi[0],((i.t1??0)-(i.t0??0))*.5)),p=e.readbacks.filter(g=>g.step===i.i&&g.result!=="not_reached"),c=p.length>0;if(n({step:i.i,stage:"step",dwell:c?Kt.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?Kt.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?Kt.checks:Math.max(350,Math.round(l*.45)),spotlight:g?"checks":null,highlight:g})}p.forEach((g,h)=>n({step:i.i,stage:"readback",readbacks:h+1,dwell:Kt.readback,spotlight:"save"})),i.status==="stopped"&&n({step:i.i,stage:"stop",dwell:Kt.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:Kt.done}),t}var ap={step:0,identity:1,checks:2,readback:3,stop:3,done:4};function ai(e,t){if(!e)return null;let n=ap[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 si(e,t){let n=e.filter(r=>r.highlight);return(n.find(r=>r.i>t)||n[0]||e[0]).i}var sp=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function ii(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()} ${sp[t.getUTCMonth()]} ${t.getUTCFullYear()}, ${n(t.getUTCHours())}:${n(t.getUTCMinutes())} UTC`}function lo(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 li(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":""}`}ut();var ae={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},me=e=>Math.round(e*100)/100;function Me(e,t){let n=t*Math.PI/180;return[me(300+e*Math.sin(n)),me(300-e*Math.cos(n))]}function xn(e,t,n){let[o,r]=Me(e,t),[a,i]=Me(e,n),l=n-t>180?1:0;return`M${o} ${r}A${e} ${e} 0 ${l} 1 ${a} ${i}`}function kn(e,t){let n=Math.sin(e*12.9898+t*78.233)*43758.5453;return n-Math.floor(n)}function co(e,t,n,o){let r=e*Math.PI/180,a=o*(.5+kn(t,n)),i=(kn(t,n+1)-.5)*o*.8;return{bx:me(Math.sin(r)*a+Math.cos(r)*i),by:me(-Math.cos(r)*a+Math.sin(r)*i),br:me((kn(t,n+2)-.5)*16)}}function ci(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[_,x]=r(b);return{i:b,d:xn(ae.step,_,x),hit:xn(ae.step,b*n,(b+1)*n),status:m.status,at:me((_+x)/2/360),t:m.t0,...co((_+x)/2,b,1,26)}}),i=[];e.steps.forEach((m,b)=>{let _=i.at(-1);_&&_.title===m.section?_.to=b:i.push({title:m.section,from:b,to:b})});let l=i.filter(m=>m.title).map((m,b)=>{let _=m.from*n+o,x=(m.to+1)*n-o,w=(_+x)/2,E=w>90&&w<270,R=Math.max((x-_)/2,40);return{k:b,title:m.title,from:m.from,to:m.to,d:xn(ae.section,_,x),text:E?ip(ae.section+9,w-R,w+R):xn(ae.section-4,w-R,w+R),mark:[Me(ae.step+12,m.from*n),Me(ae.step+20,m.from*n)],at:me(_/360)}}),p=[];e.steps.forEach((m,b)=>{let _=e.checks.filter(E=>E.step===b),[x,w]=r(b);_.forEach((E,R)=>{let S=x+(R+1)/(_.length+1)*(w-x),A=E.result!=="passed",[L,P]=Me(A?ae.tickFailIn:ae.tickIn,S),[$,O]=Me(A?ae.tickFailOut:ae.tickOut,S);p.push({i:p.length,step:b,x1:L,y1:P,x2:$,y2:O,result:E.result,at:me(S/360),t:E.t,...co(S,p.length,2,18)})})});let c=e.readbacks.length,g=e.readbacks.map((m,b)=>{let _=b/c*360,[x,w]=Me(ae.dot,_);return{i:b,cx:x,cy:w,result:m.result,label:m.label,at:me(_/360),t:m.t,...co(_,b,3,16)}}),h=e.identity.length,d=360/Math.max(1,h),f=Math.min(4,d*.28),u=e.identity.map((m,b)=>{let _=b*d+f/2,x=(b+1)*d-f/2;return{i:b,step:m.step,d:xn(ae.petal,_,x),result:m.result,at:me((_+x)/2/360),t:m.t,...co((_+x)/2,b,4,12)}}),v=e.stoppedAt==null?null:(()=>{let m=(e.stoppedAt+1)*n,[b,_]=Me(ae.step-24,m),[x,w]=Me(ae.step+18,m);return{x1:b,y1:_,x2:x,y2:w,deg:me(m),at:me(m/360)}})();return{steps:a,bands:l,ticks:p,dots:g,petals:u,stop:v,per:n}}function ip(e,t,n){let[o,r]=Me(e,n),[a,i]=Me(e,t),l=n-t>180?1:0;return`M${o} ${r}A${e} ${e} 0 ${l} 0 ${a} ${i}`}function hr(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 p=1+l*8,c=5+a[p]%9,g=a[p+1]/255*Math.PI*2,h=t*(.5+.2*l+a[p+2]/255*.08),d=.16+a[p+3]/255*.24,f=(a[p+4]/255-.5)*.7,u=1.2+a[p+6]/255*.8,v=u*(2.4+a[p+5]/255*1.6),m=x=>{let w=h*(1-d+d*Math.cos(c*x+g)),E=x+f*Math.sin(c*x);return[t+w*Math.cos(E),t+w*Math.sin(E)]},b=[],_=0;for(let x=0;x=E;){let O=1-($-E)/Math.max(1e-9,Math.hypot(P[0]-R[0],P[1]-R[1])),M=R[0]+(P[0]-R[0])*O,k=R[1]+(P[1]-R[1])*O;n&&(M+=(kn(x*97+S,l+11)-.5)*5*n,k+=(kn(x*89+S,l+23)-.5)*5*n),M=me(M),k=me(k),w+=`M${me(M-u)} ${k}a${me(u)} ${me(u)} 0 1 0 ${me(u*2)} 0a${me(u)} ${me(u)} 0 1 0 ${me(-u*2)} 0`,S+=1,$-=E,E=v}E-=$,R=P}_=Math.max(_,S),b.push({d:w,at:me(x/c)})}i.push({petals:b,count:c,dots:_,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"};Ft();Ft();var cp=0;function s(e,t,n,o,r,a){t||(t={});var i,l,p=t;if("ref"in p)for(l in p={},t)l=="ref"?i=t[l]:p[l]=t[l];var c={type:e,props:p,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--cp,__i:-1,__u:0,__source:r,__self:a};if(typeof e=="function"&&(i=e.defaultProps))for(l in i)p[l]===void 0&&(p[l]=i[l]);return j.vnode&&j.vnode(c),c}var dp=.94;function pp(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 po({rings:e,tone:t,digest:n,phase:o="rest",still:r=!1,variant:a="full",buildMs:i=3200,active:l=null,focusIndex:p=0,onActive:c,onPick:g,onKey:h,ringFocus:d=null,witnesses:f=null,lit:u=null,spot:v=null,label:m}){let b=re(()=>ci(e),[e]),_=a==="full",x=o==="broken",w=re(()=>_?hr(n,{radius:100,disorder:x?1:0}):null,[n,x,_]),E=e.anchor,R=!!(u&&E&&u.step===E.step&&["done","stop","readback"].includes(u.stage)),A=`s${it().replace(/[^a-zA-Z0-9]/g,"")}`,L=Math.max(1,e.runMs),P=k=>k==null?0:Math.round(Math.min(k/L,1)*dp*i),$=k=>l!=null&&k===l?"1":void 0,O=k=>u?k?"1":"0":void 0,M=(k,B={})=>({"--d":`${P(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":d||void 0,"data-spot":v||void 0,"data-anchored":R?"1":void 0,style:{"--build":`${i}ms`},children:[s("div",{className:F.halo,"aria-hidden":"true"}),w?s(di,{layers:w,phase:o,broken:x,tone:t},n):null,s("svg",{className:F.svg,viewBox:"0 0 600 600",role:_?"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:ae.section+16,pathLength:"1"}),s("circle",{className:F.hair,cx:300,cy:300,r:ae.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]}),_?s(se,{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))]}),f?s(fp,{witnesses:f}):null,E?s(hp,{deg:(E.step+.5)*b.per,kind:E.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":O(u?.steps(k.i)),d:k.d,pathLength:"1",style:M(k)},`b${k.i}`)),b.steps.map(k=>s("path",{className:F.step,"data-status":k.status,"data-on":$(k.i),"data-lit":O(u?.steps(k.i)),"data-current":u&&u.step===k.i?"1":void 0,"data-anchor":E&&E.step===k.i?E.kind:void 0,"data-i":k.i,d:k.d,pathLength:"1",stroke:k.status==="passed"?`url(#${A}g)`:void 0,style:M(k)},k.i)),b.stop?s("g",{"data-lit":O(u&&u.stage==="stop"),className:F.stop,style:{"--d":`${P(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:ae.dot+16}),b.ticks.map(k=>s("line",{className:F.tick,"data-result":k.result,"data-on":$(k.step),"data-lit":O(u?.checks(k.step)),x1:k.x1,y1:k.y1,x2:k.x2,y2:k.y2,style:M(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":O(u?.readback(k.i)),"data-on":l!=null&&e.readbacks[k.i].step===l?"1":void 0,cx:k.cx,cy:k.cy,r:ae.dotSize,style:M(k),onMouseEnter:_&&c?()=>c(e.readbacks[k.i].step,{readback:k.i}):void 0},k.i)),s("circle",{className:F.hair,cx:300,cy:300,r:ae.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":O(u?.identity(k.step)),d:k.d,pathLength:"1",style:M(k),onMouseEnter:_&&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:ae.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"})]})]}),u?s("g",{className:F.playhead,style:{"--deg":`${((u.step+.5)*b.per).toFixed(2)}deg`},"aria-hidden":"true",children:[s("line",{x1:300,y1:300-ae.core-6,x2:300,y2:300-ae.step-22}),s("circle",{cx:300,cy:300-ae.step-22,r:"4.5"})]}):null,_?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===p?0:-1,"aria-label":pp(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 up={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 fp({witnesses:e}){return s("g",{className:F.layer,style:{"--z":1.15},children:Object.entries(up).map(([t,n])=>{let o=e[t];if(!o)return null;let[r,a]=Me(ae.section+32,n.deg),[i,l]=Me(ae.section+6,n.deg),[p,c]=Me(ae.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:p,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 hp({deg:e,kind:t}){let[n,o]=Me(ae.section+2,e),[r,a]=Me(ae.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 gp=1700;function di({layers:e,phase:t,broken:n,tone:o}){let r=ee(null),a=ee([]);return U(()=>{let i=r.current;if(!i)return;let l=[],p="#ffffff",c=()=>{let m=getComputedStyle(i),b=(_,x)=>m.getPropertyValue(_).trim()||x;l=n?[b("--fail","#ff4d6a"),b("--fail","#ff4d6a"),b("--fail","#ff4d6a")]:[b("--t0","#4cf0b8"),b("--soft","#b9fbe5"),b("--t0","#4cf0b8")],p=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}))),d=m=>{a.current.forEach((b,_)=>{if(!b)return;let x=b.clientWidth,w=Math.min(2,window.devicePixelRatio||1);b.width!==Math.round(x*w)&&(b.width=Math.round(x*w),b.height=Math.round(x*w));let E=b.getContext("2d");E.setTransform(x*w/200,0,0,x*w/200,0,0),E.clearRect(0,0,200,200);for(let R of h[_]){let S=m==null?0:Math.max(0,1-Math.abs(m-R.at)*6);E.globalAlpha=Math.min(1,g[_]+S*.6),E.fillStyle=S>.3?p:l[_],E.fill(R.path)}})};d(null);let f=new MutationObserver(()=>requestAnimationFrame(()=>{c(),d(null)}));if(f.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),t!=="verify"||window.matchMedia("(prefers-reduced-motion: reduce)").matches)return()=>f.disconnect();let u=performance.now(),v=requestAnimationFrame(function m(b){let _=(b-u)/gp;d(_>1.1?null:_),_<=1.1&&(v=requestAnimationFrame(m))});return()=>{cancelAnimationFrame(v),f.disconnect()}},[e,t,n,o]),s("div",{className:F.iris,ref:r,"aria-hidden":"true",children:[e.map((i,l)=>s("canvas",{ref:p=>{a.current[l]=p},className:F.irisLayer,style:{"--spin":`${i.dir*(140+l*50)}s`}},l)),s("div",{className:F.irisGlow})]})}function pi({seed:e,tone:t,size:n=64}){let o=re(()=>hr(e,{radius:100}),[e]);return s("span",{className:F.mini,"data-tone":t,style:{width:n,height:n},"aria-hidden":"true",children:s(di,{layers:o,phase:"rest",broken:!1,tone:t})})}ut();var N={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 bp="0123456789abcdef",Wt=64,vp=1100;function gr({label:e,from:t,to:n,against:o,running:r,still:a}){let[i,l]=D(()=>(t||"").slice(0,Wt)),[p,c]=D(!1),g=ee(n);g.current=n,U(()=>{if(!r){n&&(l(n),c(!0));return}if(c(!1),a){n&&(l(n),c(!0));return}let u=(t||"").slice(0,Wt).padEnd(Wt,"0"),v=0,m=0,b=null,_=x=>{let w=g.current;w&&b==null&&(b=x);let E=b==null?0:Math.min(1,(x-b)/vp);if(x-m>45||E===1){m=x;let R=Math.floor(E*Wt),S="";for(let A=0;AcancelAnimationFrame(v)},[r,a]),U(()=>{!r&&n&&(l(n),c(!0))},[n,r]);let h=p&&n,d=h&&n===o,f=!r&&!n;return s("div",{className:N.hashRow,"data-state":f?"idle":h?d?"match":"differs":"running",children:[s("span",{className:N.proofLabel,children:[e,h?s("b",{children:d?" · matches":" · differs"}):null]}),s("code",{className:N.hex,"aria-label":h?`SHA-256 ${n}`:f?"Not computed":"Computing the SHA-256",children:f?"not computed":h?[...n].map((u,v)=>s("span",{"data-diff":u!==o[v]?"1":void 0,children:u},v)):i})]})}function uo({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"})})})}ut();ut();var de=e=>e.kind??"action",Mt=e=>e.kind??"sequence",Ge=e=>e.halts??[],ct=e=>e.effects??[],wn=e=>e.postconditions??[],_e=e=>e.nodes??[],Ke=e=>e.edges??[];var Ze="__opg_stop__",Sn=e=>String(e).padStart(2,"0");var yp=e=>e.index+1;function _p(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=>de(i)==="action")?"action":de(t[0]),title:e.title??`Steps ${Sn(o(t[0]))}–${Sn(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(ct),postconditions:t.flatMap(wn),halts:t.flatMap(i=>Ge(i).map(l=>`step ${Sn(o(i))}: ${l}`)),badges:a(t.flatMap(i=>i.badges??[]))}}function ui(e,t={}){let n=t.numberOf??yp,o=_e(e),r=new Map(o.map(d=>[d.id,d])),a=new Map(o.map(d=>[d.id,d.id])),i=new Map,l=new Map;for(let d of t.folds?.groups??[]){if(t.expanded?.has(d.id)||r.has(d.id))continue;let f=d.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(f.length===0)continue;let u=_p(d,f,n);for(let v of f)a.set(v.id,d.id);l.set(f[0].id,u),i.set(d.id,{id:d.id,title:u.title,subtitle:d.subtitle,members:f,first:n(f[0])??f[0].index+1,last:n(f[f.length-1])??f[f.length-1].index+1})}let p=[];for(let d of o)a.get(d.id)===d.id?p.push(d):l.get(d.id)&&p.push(l.get(d.id));let c=[],g=new Set;for(let d of Ke(e)){let f=a.get(d.source),u=a.get(d.target);if(!f||!u||f===u&&i.has(f))continue;let v=Mt(d),m=`${f}>${u}>${v}>${d.label??""}`;g.has(m)||(g.add(m),c.push({...d,source:f,target:u,kind:v}))}let h=(t.stopExits??[]).filter(d=>a.has(d.node));if(h.length){let d=Math.max(-1,...p.map(f=>f.index))+1;p.push({id:Ze,index:d,kind:"terminal",title:t.stopLabel??"Stop the run",outcome:"halt",halts:[],effects:[],postconditions:[]});for(let f of h){let u=a.get(f.node),v=`${u}>${Ze}`;g.has(v)||(g.add(v),c.push({source:u,target:Ze,kind:"exception",label:f.label??"stops"}))}}return{spec:{...e,nodes:p,edges:c},folds:i,ownerOf:a}}function fi(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 mr(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=_e(e),p=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:p?i:void 0,splitAt:a.kind!=="save"&&c>0?a.steps[c]:void 0}}function hi(e,t={}){let n=t.minLength??6,o=t.maxLength??10,r=[..._e(e)].sort((h,d)=>h.index-d.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,d)=>{let f=i.get(h.id)??[],u=a.get(d.id)??[];return f.length===1&&u.length===1&&f[0].target===d.id&&Mt(f[0])==="sequence"&&de(h)==="action"&&de(d)==="action"},p=[],c=[];for(let h of r)c.length&&l(c[c.length-1],h)?c.push(h):(c.length&&p.push(c),c=de(h)==="action"?[h]:[]);c.length&&p.push(c);let g=[];for(let h of p){if(h.lengthm.id)})}}return{groups:g}}var xp={nodeWidth:194,nodeHeight:70,xGap:42,yGap:48,margin:34,minWidth:0,laneGap:14,laneInset:22},kt=6;function gi(e){return new Map(e.map((t,n)=>[t.id,Number.isFinite(t.index)?t.index:n]))}function mi(e,t){let n=t.get(e.source),o=t.get(e.target);return n===void 0||o===void 0?!1:o<=n}function kp(e){let t=[..._e(e)],n=gi(t);t.sort((h,d)=>n.get(h.id)-n.get(d.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=>!mi(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 p=h=>{let d=new Set([h]),f=[h];for(;f.length;){let u=f.shift();for(let v of r)v.target===u&&!d.has(v.source)&&(d.add(v.source),f.push(v.source))}return d},c=[];for(let h of t){let d=l.get(h.id).filter(_=>Mt(_)==="loop_body");if(de(h)!=="loop"&&d.length===0)continue;let f=l.get(h.id).filter(_=>Mt(_)!=="loop_body").map(_=>_.target);if(d.length===0||f.length===0)continue;let u=new Set([h.id,...f]),v=p(h.id),m=new Set,b=d.map(_=>_.target).filter(_=>!u.has(_));for(;b.length;){let _=b.shift();if(!m.has(_)){m.add(_);for(let x of l.get(_))u.has(x.target)||b.push(x.target)}}for(let _ of m)v.has(_)||m.delete(_);c.push({exits:f,body:m})}let g=new Map(t.map(h=>[h.id,0]));for(let h=0;h<=t.length;h+=1){let d=!1,f=(u,v)=>{v>g.get(u)&&(g.set(u,v),d=!0)};for(let u of t)for(let v of i.get(u.id))f(u.id,g.get(v.source)+1);for(let u of c){if(u.body.size===0)continue;let v=Math.max(...[...u.body].map(m=>g.get(m)));for(let m of u.exits)f(m,v+1)}if(!d)break}return g}function wp(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 bi(e,t={}){let n={...xp,...t},o=_e(e),r=gi(o),a=kp(e),i=new Set(o.map(S=>S.id)),l=Ke(e).filter(S=>i.has(S.source)&&i.has(S.target)),p=new Map;for(let S of o){let A=a.get(S.id)??0,L=p.get(A)??[];L.push(S),p.set(A,L)}for(let S of p.values())S.sort((A,L)=>r.get(A.id)-r.get(L.id));let c=Math.max(0,...a.values()),g=Math.max(1,...[...p.values()].map(S=>S.length)),h=S=>n.margin+S*(n.nodeHeight+n.yGap),d=l.map((S,A)=>{let L=mi(S,r),P=(a.get(S.target)??0)-(a.get(S.source)??0);return{edge:S,index:A,back:L,lane:L?"right":P===1?null:"left",slot:0}}),f=[],u=[];for(let S of d){if(S.lane===null)continue;let A=a.get(S.edge.source)??0,L=a.get(S.edge.target)??0;S.slot=wp(S.lane==="left"?f:u,A,L)}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(f.length),v(u.length))),_=n.margin*2+(c+1)*n.nodeHeight+c*n.yGap,x=[];for(let[S,A]of[...p.entries()].sort((L,P)=>L[0]-P[0])){let L=A.length*n.nodeWidth+(A.length-1)*n.xGap,P=(b-L)/2;A.forEach(($,O)=>{x.push({id:$.id,x:P+O*(n.nodeWidth+n.xGap),y:h(S),width:n.nodeWidth,height:n.nodeHeight,rank:S})})}let w=new Map(x.map(S=>[S.id,S])),E=(S,A)=>{let L=Math.min(S,A),P=Math.max(S,A),$=x.filter(O=>O.rank>=L&&O.rank<=P);return{left:Math.min(...$.map(O=>O.x)),right:Math.max(...$.map(O=>O.x+O.width))}},R=d.map(({edge:S,index:A,back:L,lane:P,slot:$})=>{let O=w.get(S.source),M=w.get(S.target),k=Mt(S),B=S.label??"",H=`${S.source}:${S.target}:${k}:${A}`,G=O.y+O.height/2,V=M.y+M.height/2;if(P===null){let oe=O.x+O.width/2,X=M.x+M.width/2,K=O.y+O.height,xe=M.y,Se=(K+xe)/2;return{id:H,source:S.source,target:S.target,kind:k,label:B,path:`M ${oe} ${K} C ${oe} ${Se}, ${X} ${Se}, ${X} ${xe}`,labelX:(oe+X)/2+6,labelY:Se+3,labelRotate:!1,backEdge:L,lane:P}}let ve=E(O.rank,M.rank);if(P==="right"){let oe=ve.right+n.laneInset+$*n.laneGap,X=O.x+O.width,K=M.x+M.width,xe=VG;return{id:H,source:S.source,target:S.target,kind:k,label:B,path:`M ${Ie} ${G} H ${te+pe} Q ${te} ${G} ${te} ${G+(Te?pe:-pe)} V ${V+(Te?-pe:pe)} Q ${te} ${V} ${te+pe} ${V} H ${ne}`,labelX:te-8,labelY:(G+V)/2,labelRotate:!0,backEdge:L,lane:P}});return{width:b,height:_,nodes:x,edges:R}}function br(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 vr(e){let t=de(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||ct(e).length>0?"governed":"default"}var Sp=e=>String(e).padStart(2,"0"),En=e=>e.index+1;function vi(e,t="index"){if(t==="index")return En;let n=new Map;return[..._e(e)].sort((o,r)=>o.index-r.index).filter(o=>de(o)==="action").forEach((o,r)=>n.set(o.id,r+1)),o=>n.get(o.id)??null}var Ep={loop:"LOOP",branch:"IF",business_decision:"ASK",subflow_call:"CALL",child_bundle:"SUB",action:"STEP"};function fo(e,t=En){if(de(e)==="terminal")return vr(e)==="stop"?"STOP":"END";let n=t(e);return n===null?Ep[de(e)]??"STEP":Sp(n)}function Vt(e){return de(e).replaceAll("_"," ")}function ho(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:wn(e).length?"present":"none",count:wn(e).length},readback:{state:ct(e).length?"present":"none",count:ct(e).length}}}function yi(e,t=br(e),n=En){let o=fo(e,n),a=[`${/^\d+$/.test(o)?`step ${o}, ${Vt(e)}`:o==="END"||o==="STOP"?`${o.toLowerCase()}, ${Vt(e)}`:Vt(e)}: ${t}.`];e.identity?.armed&&a.push("Checks the right record."),ct(e).length&&a.push("Reads the saved record back.");let i=Ge(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 qt(e){let t=Ge(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=de(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=ct(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])]:[],p=[...r,...l,...a];return p.length===t.length-1&&!e.wait_until&&(p=[...r,n(Ye[3][0]),...a]),p.length!==t.length?t.map(()=>({kind:"run",text:"Stops if a declared check fails."})):p}function go(e){return e?.events.find(t=>t.status==="halted")??null}function _i(e,t,n){let o=Math.max(0,Math.min(t,e.events.length)),r=f=>n?.get(f)??f,a=new Map,i=new Map,l=new Set,p=null,c=null,g=null,h=null;for(let f=0;f${v}`,l.add(p)):p=null,c=v,g===u&&(p=`${v}>${Ze}`,l.add(p),a.set(Ze,{status:"halted",visits:1,iterations:0,last:u,events:[u]}))}let d=o>0?e.events[o-1]:null;if(d){let f=a.get(r(d.node));f.status!=="halted"&&(f.status="active")}return{cursor:o,nodes:a,taken:l,latestEdge:p,current:d,iteration:h,halted:g,finished:o===e.events.length}}function xi(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 ki(e,t,n){let o=d=>n?.get(d)??d,r=_e(e),a=o(t.node),i=r.find(d=>d.id===a),l=t.iteration??null,p={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 d of r){if(d.index>=i.index||d.id===Ze||de(d)==="terminal")continue;let f=de(d)==="loop";c.set(d.id,{status:"done",visits:1,iterations:f&&l?l:0,events:[]})}c.set(a,{status:t.status==="stopped"?"halted":"active",visits:1,iterations:de(i)==="loop"&&l?l:0,last:p,events:[p]});for(let d of Ke(e)){let f=r.find(v=>v.id===d.source),u=r.find(v=>v.id===d.target);f&&u&&f.indexf.index&&g.add(`${f.id}>${u.id}`)}if(de(i)==="loop"&&(l??1)>1){let d=Ke(e).find(f=>{let u=r.find(v=>v.id===f.source);return f.target===a&&u!==void 0&&u.index>i.index});d&&(h=`${d.source}>${a}`)}else{let d=Ke(e).find(f=>{let u=r.find(v=>v.id===f.source);return f.target===a&&u!==void 0&&u.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:p,events:[p]}))}return{cursor:0,nodes:c,taken:g,latestEdge:h,current:p,iteration:l,halted:t.status==="stopped"?p:null,finished:t.status==="stopped"}}var wi=(e,t)=>{for(let n=0;nf.title),r=[..._e(e)].sort((f,u)=>f.index-u.index),a=r.filter(f=>de(f)==="action"),i=[],l=f=>n?wi(n,u=>n.events[u].node===f):-1,p=f=>{let u=l(f);return u>=0?u+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(f=>(f.resolution?.rungs??[]).filter(u=>u.present).length>=2);if(c){let f=(c.resolution?.rungs??[]).filter(u=>u.present).map(u=>u.label.toLowerCase());i.push({id:"step",title:"One step",body:`“${o(c)}” recorded ${f.length} ways to find its target: ${f.join(", ")}. A run tries the strongest first.`,select:c.id,cursor:p(c.id),view:"program"})}let g=r.find(f=>de(f)==="loop");if(g){let f=n?new Set(n.events.map(v=>v.iteration).filter(v=>v!=null)).size:0,u=n?wi(n,v=>n.events[v].node===g.id&&n.events[v].iteration===2):-1;i.push({id:"loop",title:"The loop",body:f>1?`The steps run once for each item in the list. This run reached ${f} 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:u>=0?u+1:p(g.id),view:"program"})}let h=a.find(f=>f.identity?.armed&&f.id!==c?.id)??a.find(f=>f.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:p(h.id),view:"program"});let d=go(n);if(n&&d)i.push({id:"stop",title:"A stop",body:d.reason??"The run stopped here, where a check failed.",select:d.node,cursor:n.events.indexOf(d)+1,view:"program"});else{let f=a.find(u=>Ge(u).length>0);f&&i.push({id:"stop",title:"A stop rule",body:qt(f).map(u=>u.text).join(" "),select:f.id,cursor:p(f.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:d?.node??null,cursor:n.events.length,view:"program"}),i}ut();var Np={program:"Program map",evidence:"Evidence lanes",stops:"Stop rules"},Tp="The map follows the emitted edge targets. It keeps each loop and exception route visible.",$p="These rows show the declared contract. They do not report a live verdict.",yr=e=>String(e).padStart(2,"0"),bo=Dt(En);function Ap(){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 gt({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 _r(e,t,n){return t?t.first===t.last?yr(t.first):`${yr(t.first)}–${yr(t.last)}`:fo(e,n)}function Rp({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(gt,{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 Mp({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,p=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!p&&!g?null:s("div",{className:"opg-media",children:[s("span",{children:"Pictures"}),s("div",{className:"opg-media-pair",children:[p&&s("figure",{children:[s("a",{href:p,target:"_blank",rel:"noopener noreferrer",children:s("img",{src:p,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 Ip({review:e,folded:t,onEditSection:n}){let{section:o,mergeWith:r,splitAt:a}=e,[i,l]=D(!1),[p,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 d=p.replace(/\s+/g," ").trim();d&&d!==o.title&&n({op:"rename",section:o.section,title:d}),l(!1)},children:[s("input",{"aria-label":"Section title",value:p,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 Cp({node:e,fold:t,partOf:n,run:o,titleFor:r,onUnfold:a,onRefold:i,onPickMember:l,plainStopRules:p,resolveMedia:c,onClose:g,review:h,onEditSection:d}){let f=_t(bo),u=ho(e),v=t?.members.map(ho)??[],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:_r(e,t,f)}),g&&s("button",{type:"button",className:"opg-icon-button",onClick:g,"aria-label":"Close the step details",children:s(Nn,{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(se,{children:[s(gt,{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(gt,{label:"Right record",state:u.identity.state,value:`${v.filter(b=>b.identity.text==="Checked").length} checked`}),s(gt,{label:"Screen check",state:u.screen.state,value:u.screen.count?`${u.screen.count} checks`:"Not declared"}),s(gt,{label:"Read-back",state:u.readback.state,value:u.readback.count?`${u.readback.count} independent checks`:"Not declared"})]}):s(se,{children:[s(gt,{label:"Finds the field",state:u.resolve.state,value:u.resolve.count?`${u.resolve.count} evidence types`:"Not applicable"}),s(gt,{label:"Right record",state:u.identity.state,value:u.identity.text}),s(gt,{label:"Screen check",state:u.screen.state,value:u.screen.count?`${u.screen.count} checks`:"Not declared"}),s(gt,{label:"Read-back",state:u.readback.state,value:u.readback.count?`${u.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:fo(b,f)}),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&&d&&s(Ip,{review:h,folded:!!t,onEditSection:d}),Ge(e).length>0&&(p?s("div",{className:"opg-stop-rule",children:[s("span",{children:"Stop rules"}),(t?t.members.flatMap(qt):qt(e)).filter((b,_,x)=>x.findIndex(w=>w.text===b.text)===_).map((b,_)=>s("strong",{"data-kind":b.kind,children:b.text},_))]}):s("div",{className:"opg-stop-rule",children:[s("span",{children:"Stops before acting if"}),s("strong",{children:Ge(e).join("; ")})]})),s(Mp,{node:e,fold:t,run:o,resolveMedia:c,title:r(e)}),o&&o.status!=="pending"&&s(Rp,{state:o})]})}function Pp(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 Op({display:e,fullSpec:t,folds:n,expanded:o,setExpanded:r,traceState:a,selectedId:i,setSelectedId:l,titleFor:p,canvasNote:c,layoutOptions:g,showInspector:h=!0,plainStopRules:d,compact:f=!1,resolveMedia:u,inspectorOpen:v,setInspectorOpen:m,onEditSection:b}){let _=_t(bo),x=re(()=>bi(e.spec,g),[e.spec,g]),w=_e(e.spec),E=re(()=>new Map(w.map(T=>[T.id,T])),[w]),R=`opg-arrow-${it().replace(/[^a-zA-Z0-9_-]/g,"")}`,S=ee(new Map),A=ee(null),L=e.ownerOf.get(i)??(E.has(i)?i:w[0]?.id),P=E.get(L??"")??w[0],[$,O]=D(1),M=Ee(T=>O(Math.round(Math.max(.4,Math.min(1.6,T))*100)/100),[]),[k,B]=D(!1),H=f&&!k,G=ee(null),V=ee(new Map),[ve,te]=D(0);U(()=>{let T=new Set,z=q=>{let Y=V.current.get(q.pointerId);if(!Y)return;let $e=requestAnimationFrame(()=>{T.delete($e),V.current.get(q.pointerId)===Y&&(V.current.delete(q.pointerId),V.current.size||te(Oe=>Oe+1))});T.add($e)},ue=()=>{V.current.clear(),te(q=>q+1)};return window.addEventListener("pointerup",z),window.addEventListener("pointercancel",z),window.addEventListener("blur",ue),()=>{window.removeEventListener("pointerup",z),window.removeEventListener("pointercancel",z),window.removeEventListener("blur",ue);for(let q of T)cancelAnimationFrame(q);V.current.clear()}},[]);let Ie=a?.current?e.ownerOf.get(a.current.node):void 0;U(()=>{let T=G.current,z=x.nodes.find(Jt=>Jt.id===Ie);if(!T||!z||V.current.size)return;let q=T.firstElementChild?.offsetLeft??0,Y=z.x*$+q,$e=z.y*$,Oe=z.width*$,Le=z.height*$,Q=$e>=T.scrollTop&&$e+Le<=T.scrollTop+T.clientHeight,he=Y>=T.scrollLeft&&Y+Oe<=T.scrollLeft+T.clientWidth;if(Q&&he)return;let nt=Q?T.scrollTop:Math.max(0,$e-(T.clientHeight-Le)/2),wt=he?T.scrollLeft:Math.max(0,Y-(T.clientWidth-Oe)/2);typeof T.scrollTo=="function"?T.scrollTo({top:nt,left:wt}):(T.scrollTop=nt,T.scrollLeft=wt)},[Ie,a?.cursor,x,$,ve]),U(()=>{let T=G.current;if(!T||!f)return;let z=ue=>{!ue.ctrlKey&&!ue.metaKey||(ue.preventDefault(),O(q=>Math.round(Math.max(.4,Math.min(1.6,q*(ue.deltaY>0?.9:1.1)))*100)/100))};return T.addEventListener("wheel",z,{passive:!1}),()=>T.removeEventListener("wheel",z)},[f]);let ne=ee(null),pe=f?{onPointerDown:T=>{if(T.target.closest("button")||T.button!==0)return;let z=G.current;ne.current={x:T.clientX,y:T.clientY,left:z.scrollLeft,top:z.scrollTop},z.setPointerCapture?.(T.pointerId)},onPointerMove:T=>{let z=ne.current,ue=G.current;!z||!ue||(ue.scrollLeft=z.left-(T.clientX-z.x),ue.scrollTop=z.top-(T.clientY-z.y))},onPointerUp:()=>{ne.current=null},onPointerCancel:()=>{ne.current=null}}:{},Te=()=>{let T=G.current;T&&M(Math.min(1,(T.clientWidth-16)/x.width,(T.clientHeight-16)/x.height))};if(U(()=>{let T=A.current;T&&(A.current=null,S.current.get(T)?.focus())}),!P)return s("p",{className:"opg-empty",children:"The compiled graph is empty."});let oe=n?.groups.find(T=>o.has(T.id)&&T.nodes.includes(P.id)),X=b?e.folds.has(P.id)?mr(t,P.id):oe?mr(t,oe.id,P.id):null:null,K=s(Cp,{node:P,fold:e.folds.get(P.id),partOf:oe?{id:oe.id,title:oe.title??oe.id}:void 0,review:X,onEditSection:b,run:a?.nodes.get(P.id),titleFor:p,plainStopRules:d,resolveMedia:u,onClose:f?()=>m(!1):void 0,onUnfold:T=>{let z=e.folds.get(T);r(new Set([...o,T])),z&&(l(z.members[0].id,"user"),A.current=z.members[0].id)},onRefold:T=>{let z=new Set(o);z.delete(T),r(z),l(T,"user"),A.current=T},onPickMember:(T,z)=>{r(new Set([...o,T])),l(z,"user"),A.current=z}}),xe=T=>a?.nodes.get(T),Se=Ke(t).length,tt=_e(t).length,yo=w.filter(T=>T.id!==Ze).length,Yt=(T,z)=>{let ue=x.nodes.find(Q=>Q.id===z);if(!ue)return;let q,Y=Q=>x.nodes.filter(he=>he.rank===Q).sort((he,nt)=>he.x-nt.x),$e=Q=>Y(Q).sort((he,nt)=>Math.abs(he.x-ue.x)-Math.abs(nt.x-ue.x))[0]?.id,Oe=[...new Set(x.nodes.map(Q=>Q.rank))].sort((Q,he)=>Q-he),Le=Oe.indexOf(ue.rank);switch(T.key){case"ArrowDown":q=x.edges.find(Q=>Q.source===z&&!Q.backEdge)?.target??(LeQ.target===z&&!Q.backEdge)?.source??(Le>0?$e(Oe[Le-1]):void 0);break;case"ArrowRight":case"ArrowLeft":{let Q=Y(ue.rank),he=Q.findIndex(nt=>nt.id===z)+(T.key==="ArrowRight"?1:-1);q=Q[he]?.id;break}case"Home":q=x.nodes.slice().sort((Q,he)=>Q.rank-he.rank||Q.x-he.x)[0]?.id;break;case"End":q=x.nodes.slice().sort((Q,he)=>he.rank-Q.rank||he.x-Q.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:[tt," nodes · ",Se," exact edges",e.folds.size>0&&` · ${yo} cards`]})]}),f&&s("div",{className:"opg-stage-tools",role:"toolbar","aria-label":"Map view",children:[s("button",{type:"button",onClick:()=>M($-.1),"aria-label":"Zoom out",disabled:$<=.4,children:s(Nn,{d:"M3 7h8"})}),s("span",{"aria-live":"polite",children:[Math.round($*100),"%"]}),s("button",{type:"button",onClick:()=>M($+.1),"aria-label":"Zoom in",disabled:$>=1.6,children:s(Nn,{d:"M3 7h8M7 3v8"})}),s("button",{type:"button",onClick:Te,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":f||void 0,...pe,children:s("div",{className:"opg-canvas-sizer",style:{width:x.width*$,height:x.height*$},children:s("div",{className:"opg-canvas",style:{width:x.width,height:x.height,transform:$===1?void 0:`scale(${$})`},children:[s("svg",{className:"opg-edges",viewBox:`0 0 ${x.width} ${x.height}`,width:x.width,height:x.height,role:"img","aria-label":`${x.edges.length} compiled program edges`,children:[s("defs",{children:s("marker",{id:R,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"})})}),x.edges.map(T=>s("g",{"data-kind":T.kind,"data-back-edge":T.backEdge||void 0,"data-lane":T.lane??void 0,"data-run":Pp(T,a),children:[s("path",{d:T.path,markerEnd:`url(#${R})`}),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))]}),x.nodes.map(T=>{let z=E.get(T.id),ue=z.id===P.id,q=e.folds.get(z.id),Y=xe(z.id),$e=p(z),Oe=Y&&Y.status!=="pending"?` This run: ${Y.status==="halted"?"stopped here":Y.status==="active"?"here now":"reached"}${Y.iterations>1?`, ${Y.iterations} iterations`:""}.`:"";return s("button",{ref:Le=>{Le?S.current.set(z.id,Le):S.current.delete(z.id)},type:"button",className:"opg-node","data-tone":vr(z),"data-fold":q?"folded":void 0,"data-selected":ue||void 0,"data-run":Y?.status,style:{left:T.x,top:T.y,width:T.width,height:T.height},"aria-pressed":ue,"aria-label":q?`Steps ${_r(z,q,_)}, ${q.members.length} steps: ${$e}.${Oe}`:`${yi(z,$e,_)}${Oe}`,tabIndex:ue?0:-1,onClick:()=>{l(z.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:Le=>Yt(Le,z.id),children:[s("span",{className:"opg-node-index",children:_r(z,q,_)}),s("span",{className:"opg-node-copy",children:[s("small",{children:q?q.subtitle??`${q.members.length} steps`:Vt(z)}),s("strong",{title:q?$e:void 0,children:$e})]}),s("span",{className:"opg-node-signals","aria-hidden":"true",children:[de(z)==="loop"&&Y&&Y.iterations>0&&s("b",{children:["×",Y.iterations]}),z.identity?.armed&&s("i",{title:"Checks the right record",children:"R"}),ct(z).length>0&&s("i",{title:"Reads the saved record back",children:"C"}),Ge(z).length>0&&s("i",{title:"Stop rules",children:"H"})]})]},z.id)})]})})}),s("ul",{className:"opg-sr-only","aria-label":"Program edges",children:x.edges.map(T=>s("li",{children:[p(E.get(T.source))," to ",p(E.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 Lp({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:_e(e).map(o=>{let r=ho(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 zp({spec:e,titleFor:t,halt:n,plain:o}){let r=_t(bo),a=_e(e).filter(l=>Ge(l).length>0||de(l)==="terminal"),i=n?_e(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:de(l)==="terminal"?"terminal":r(l)===null?Vt(l):`step ${r(l)}`}),s("strong",{children:t(l)}),s("p",{children:Ge(l).length?o?qt(l).map(p=>p.text).join(" "):Ge(l).join("; "):"Declared terminal program state."})]},`stop-${l.id}`))]})}function Nn({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 Dp({trace:e,state:t,playing:n,setPlaying:o,setCursor:r,iterationNoun:a,liveFrame:i}){let l=e.events.length,p=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 ${p}`:`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(Nn,{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(Nn,{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 Fp({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 Hp({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 jp({stop:e,at:t,count:n,focus:o,onBack:r,onNext:a,onSkip:i}){let l=`opg-tour-${it().replace(/[^a-zA-Z0-9_-]/g,"")}`,p=ee(null);return U(()=>{o.current&&p.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:p,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 Gp(e){let{spec:t,folds:n,stopExits:o,trace:r,playhead:a,autoPlay:i=!1,initialCursor:l=0,speed:p=14,numbering:c}=e,g=re(()=>vi(t,c),[t,c]),[h,d]=D(e.initialSelectedId??_e(t)[0]?.id??""),f=e.selectedId??h,[u,v]=D(()=>new Set),m=re(()=>e.expanded?new Set(e.expanded):u,[e.expanded,u]),b=Ap(),[_,x]=D(l),w=e.cursor??_,[E,R]=D(!1),S=r?.events.length??0,{onSelect:A,onCursorChange:L,onExpandedChange:P}=e,$=Ee((ne,pe)=>{d(ne),A?.(ne,pe)},[A]),O=Ee(ne=>{v(ne),P?.([...ne])},[P]),M=ee(w);M.current=w;let k=Ee(ne=>{let pe=Math.max(0,Math.min(S,ne));x(pe),L?.(pe)},[S,L]);U(()=>{e.cursor===void 0&&x(Math.max(0,Math.min(r?.events.length??0,l))),R(!!r&&i&&!b)},[r,i,b,l]),U(()=>{if(!E||!r)return;if(w>=S){R(!1);return}let ne=setTimeout(()=>k(M.current+1),xi(r,w,p));return()=>clearTimeout(ne)},[E,w,S,r,p,k]);let B=r?go(r):a?.status==="stopped"?{node:a.node,status:"halted"}:null,H=re(()=>{let ne=[...o??[]];return B&&!ne.some(pe=>pe.node===B.node)&&ne.push({node:B.node,label:"stopped"}),ne},[o,B?.node]),G=re(()=>ui(t,{folds:n,expanded:m,stopExits:H,numberOf:g}),[t,n,m,H,g]),V=re(()=>r?_i(r,w,G.ownerOf):a?ki(G.spec,a,G.ownerOf):null,[r,w,a,G]),ve=ee(null),te=Ee(ne=>{ve.current=`c${ne}`},[]),Ie=r?`c${w}`:a?`p${a.node}:${a.iteration??""}:${a.status}`:null;return U(()=>{if(!V?.current||Ie===null||ve.current===Ie)return;let ne=ve.current===null&&w===0&&!!r;ve.current=Ie,ne||$(V.current.node,"follow")},[V,Ie,w,r,$]),{selectedId:f,setSelectedId:$,expanded:m,setExpanded:O,cursor:w,setCursor:k,playing:E,setPlaying:R,display:G,traceState:V,numberOf:g,suppressFollow:te}}function xr(e){let{spec:t,title:n,kicker:o="The steps",trace:r,iterationNoun:a="iteration",views:i=["program","evidence","stops"],initialView:l,titleFor:p=br,notes:c,layout:g,theme:h="dark",className:d,style:f,showHeader:u=!0,showPlayer:v=!0,showInspector:m=!0,plainStopRules:b=!1,compact:_=!1,resolveMedia:x,tour:w,tourSeen:E=!1,onTourEnd:R}=e,S=re(()=>e.folds!==void 0?e.folds:fi(t)??(_?hi(t):null),[e.folds,_,t]),A=Gp({...e,folds:S}),[L,P]=D(l??i[0]??"program"),{traceState:$}=A,[O,M]=D(!0),k=re(()=>w===!0?mo(t,{trace:r,title:p}):Array.isArray(w)?w:[],[w,t,r,p]),[B,H]=D(()=>k.length&&!E?0:null),G=ee(!1);U(()=>{if(B===null)return;let K=k[B];K&&(A.setPlaying(!1),K.view&&P(K.view),K.cursor!=null&&r&&(A.suppressFollow(K.cursor),A.setCursor(K.cursor)),K.select&&A.setSelectedId(K.select,"tour"),M(!0))},[B,k]);let V=K=>{H(null),R?.(K)},ve=k.length>0&&B===null?s("button",{type:"button",className:"opg-tour-launch",onClick:()=>{G.current=!0,H(0)},children:"Take the tour"}):null,te=r?.receipt&&$?.finished?r.receipt:null,Ie=x&&$?.current?.frame?x($.current.frame,{node:$.current.node,kind:"live",iteration:$.current.iteration}):null,ne=it().replace(/[^a-zA-Z0-9_-]/g,""),pe=ee(new Map),Te=i.length>1,oe=(K,xe)=>{let Se=i.indexOf(xe),tt=K.key==="ArrowRight"?i[(Se+1)%i.length]:K.key==="ArrowLeft"?i[(Se-1+i.length)%i.length]:K.key==="Home"?i[0]:K.key==="End"?i[i.length-1]:void 0;tt&&(K.preventDefault(),P(tt),pe.current.get(tt)?.focus())},X=(K,xe)=>Te?s("div",{role:"tabpanel",id:`${ne}-panel-${K}`,"aria-labelledby":`${ne}-tab-${K}`,hidden:L!==K,tabIndex:-1,children:L===K&&xe}):L===K&&s("div",{children:xe});return s(bo.Provider,{value:A.numberOf,children:s("div",{className:`opg-root${d?` ${d}`:""}`,"data-theme":h,"data-compact":_||void 0,style:f,children:[u&&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:[ve,s(Fp,{trace:r,state:r?$:null,playing:A.playing})]})]}),!u&&ve&&s("div",{className:"opg-tour-bar",children:ve}),v&&r&&$&&s(Dp,{trace:r,state:$,playing:A.playing,setPlaying:A.setPlaying,setCursor:A.setCursor,iterationNoun:a,liveFrame:Ie}),B!==null&&k[B]&&s(jp,{stop:k[B],at:B,count:k.length,focus:G,onBack:()=>H(Math.max(0,B-1)),onNext:()=>B+1V("skipped")}),te&&s(Hp,{receipt:te}),Te&&s("div",{className:"opg-tabs",role:"tablist","aria-label":"Program workbench views",children:i.map(K=>s("button",{ref:xe=>{xe&&pe.current.set(K,xe)},id:`${ne}-tab-${K}`,type:"button",role:"tab","aria-selected":L===K,"aria-controls":`${ne}-panel-${K}`,tabIndex:L===K?0:-1,onClick:()=>P(K),onKeyDown:xe=>oe(xe,K),children:Np[K]},K))}),i.includes("program")&&X("program",s(Op,{display:A.display,fullSpec:t,folds:S,expanded:A.expanded,setExpanded:A.setExpanded,traceState:$,selectedId:A.selectedId,setSelectedId:A.setSelectedId,titleFor:p,canvasNote:c?.canvas===void 0?Tp:c.canvas,layoutOptions:g,showInspector:m,plainStopRules:b,compact:_,resolveMedia:x,inspectorOpen:O,setInspectorOpen:M,onEditSection:e.onEditSection})),i.includes("evidence")&&X("evidence",s(Lp,{spec:t,titleFor:p,note:c?.evidence===void 0?$p:c.evidence})),i.includes("stops")&&X("stops",s(zp,{spec:t,titleFor:p,halt:$?.finished?$.halted:null,plain:b}))]})})}ut();var mt={host:"Qo",card:"V",cardIn:"do",body:"Vo",kicker:"Wo",line:"Zo",sub:"ar",action:"W",others:"ma"};function Bp(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 Kp(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 Si(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(" "),p=null,c="",g=()=>{let d=i.querySelector(".opg-inspector"),f=d?Kp(Bp(d),l,n):[];if(!f.length){p&&(p.remove(),p=null,c="",r({host:null,ids:[]}));return}p||(p=document.createElement("div"),p.className=mt.host,p.dataset.sealCardHost=""),d.firstChild!==p&&d.prepend(p);let u=f.join(" ");u!==c&&(c=u,r({host:p,ids:f}))},h=new MutationObserver(g);return h.observe(i,{childList:!0,subtree:!0,characterData:!0}),g(),()=>{h.disconnect(),p?.remove(),r({host:null,ids:[]})}},[e,a,n]),o}function Ei({seals:e,here:t=!1,Link:n="a"}){let[o,...r]=e,a=o.anchor?.kind==="stop",i=!t;return s("section",{className:mt.card,"data-tone":o.tone,"data-seal-card":i?"open":"here","aria-label":"This step's receipt",children:[s(pi,{seed:o.irisSeed,tone:o.tone,size:58}),s("div",{className:mt.body,children:[s("p",{className:mt.kicker,children:i?`Signed here${o.n?` · referral ${o.n}`:""}`:"This is the step the receipt covers"}),s("p",{className:mt.line,children:o.line}),s("p",{className:mt.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:mt.action,"data-seal-open":"",href:o.href,children:"Open the receipt →"}):null,r.length?s("p",{className:mt.others,children:[s("span",{children:"Also signed here:"}),r.map(l=>s(n,{href:l.href,children:["Referral ",l.n]},l.n))]}):null]})]})}var Wp=[];function kr({program:e,map:t={},step:n,status:o,onPick:r,anchor:a=null,sealRun:i=null,sealLine:l="",theme:p="dark",fill:c=!1}){let{spec:g,folds:h=null,titles:d={}}=e,f=h?.groups||Wp,u=re(()=>g.nodes.filter(M=>M.kind==="action").map(M=>M.id),[g]),v=re(()=>Object.fromEntries(f.flatMap(M=>M.nodes.map(k=>[k,M.id]))),[f]),m=re(()=>M=>d[M.id]||M.title,[d]),b=re(()=>mo(g,{title:m}),[g,m]),_=ee(null);U(()=>{let M=_.current;if(!M)return;for(let te of M.querySelectorAll("[data-seal-anchor]"))delete te.dataset.sealAnchor;if(!a)return;let k=u[a.step],B=d[k],H=f.find(te=>te.nodes.includes(k)),G=[...M.querySelectorAll(".opg-node")],V=te=>te.getAttribute("aria-label")||"",ve=(B?G.find(te=>!te.dataset.fold&&V(te).includes(B)):null)||(H?G.find(te=>te.dataset.fold&&V(te).includes(`: ${H.title}.`)):null);ve&&(ve.dataset.sealAnchor=a.kind)}),U(()=>{let M=_.current;if(!M||!c||typeof ResizeObserver>"u")return;let k=0,B=()=>{k=0;let G=M.querySelector(".opg-root"),V=M.querySelector(".opg-canvas-viewport");if(!G||!V)return;let ve=G.offsetHeight-V.offsetHeight,te=Math.max(240,Math.floor(M.clientHeight-ve-2));M.style.getPropertyValue("--seal-stage-h")!==`${te}px`&&M.style.setProperty("--seal-stage-h",`${te}px`)},H=new ResizeObserver(()=>{k||(k=requestAnimationFrame(B))});return H.observe(M),B(),()=>{H.disconnect(),cancelAnimationFrame(k),M.style.removeProperty("--seal-stage-h")}},[c]);let x=n!=null?u[n]:null,[w,E]=D(null);U(()=>E(null),[x]);let[R,S]=D([]),A=re(()=>[...new Set([...R,...x&&v[x]?[v[x]]:[]])],[R,x,v]),L=re(()=>x?{node:x,iteration:1,status:o||"running"}:null,[x,o]),P=a?u[a.step]:null,$=re(()=>P?[P]:[],[P]),O=Si(_,$,f).host;return s("div",{className:N.map,"data-step":n??"","data-fill":c?"1":void 0,ref:_,children:[s(xr,{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:p,playhead:L,selectedId:w||x||u[0],onSelect:(M,k)=>{if(k==="follow")return;if(P&&v[P]===M&&f.some(H=>H.id===M)){E(null),r(a.step);return}let B=u.indexOf(M);B>=0?(E(null),r(B)):E(M)},expanded:A,onExpandedChange:S}),O&&i?Kn(s(Ei,{seals:[{...i,line:l,anchor:a}],here:!0}),O):null]})}var Ni=3400,Vp=1700,qp=[1,2,4],Zp={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."},Yp=new Set(["unknown_key","key_mismatch","ambiguous_key"]),Ti=e=>Zp[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."),Zt=e=>`${(e/1e3).toFixed(1)} s`,Jp=(e,t)=>`${e} of ${t} record checks confirmed`,Xp=e=>e&&e.charAt(0).toUpperCase()+e.slice(1);function Qp(){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 eu(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 Ci="oa-theme",$i=()=>{try{let e=window.localStorage.getItem(Ci);return e==="light"||e==="dark"?e:null}catch{return null}},Ai=()=>window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark",Ri=()=>{let e=document.documentElement.getAttribute("data-theme");return e==="light"||e==="dark"?e:null};function tu(e){let[t,n]=D("dark");U(()=>{let r=()=>Ri()||$i()||Ai(),a=()=>{let c=r();e&&!Ri()&&document.documentElement.setAttribute("data-theme",c),n(c)};a();let i=window.matchMedia("(prefers-color-scheme: light)"),l=()=>{$i()||(e&&document.documentElement.setAttribute("data-theme",Ai()),a())};i.addEventListener("change",l);let p=new MutationObserver(()=>n(r()));return p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>{i.removeEventListener("change",l),p.disconnect()}},[e]);let o=Ee(()=>{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(Ci,r)}catch{}n(r)},[t]);return[t,o]}var Pi=["summary","steps","evidence","raw"],nu={summary:"Summary",program:"Program",steps:"Steps",evidence:"Evidence",raw:"Raw"};function ou(e){let t=new URLSearchParams(window.location.hash.replace(/^#/,"")),n=t.get("tab"),o=Number.parseInt(t.get("step")||"",10);return{tab:Pi.includes(n)||n==="program"?n:null,step:Number.isInteger(o)&&o>=1&&o<=e?o-1:null}}function Mi(e,t){let n=[];return e&&e!=="summary"&&n.push(`tab=${e}`),t!=null&&n.push(`step=${t+1}`),n.length?`#${n.join("&")}`:""}function ru(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,p=()=>{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(p):0},c=h=>{let d=n.getBoundingClientRect();o=Math.max(-1,Math.min(1,(h.clientX-d.left)/d.width*2-1)),r=Math.max(-1,Math.min(1,(h.clientY-d.top)/d.height*2-1)),l||(l=requestAnimationFrame(p))},g=()=>{o=0,r=0,l||(l=requestAnimationFrame(p))};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 Oi(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 Er({seal:e,host:t={}}){let{loadFiles:n=null,Link:o="a",links:r={},copyHref:a=null,live:i=!0,kicker:l=null,footer:p=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:d=!0,map:f={},signer:u=null,mediaNote:v="From this computer's run folder: not part of the receipt, never uploaded"}=t,{rings:m,seal:b,tone:_,label:x,line:w,job:E,app:R,startedAt:S,stopReason:A,media:L,tamper:P,runs:$,referral:O,referrals:M,files:k,keys:B,authorization:H,authorizedLine:G,authTiming:V,stopNote:ve,program:te,commands:Ie=null,irisSeed:ne}=e,pe=Qp(),[Te,oe]=D("build"),[X,K]=D(null),[xe,Se]=D(null),[tt,yo]=D(ne),Yt=!!(k.anchor||k.receiptAnchor||k.tsa),[T,z]=D(null),[ue,q]=D(null),[Y,$e]=D(null),[Oe,Le]=D(!1),[Q,he]=D(null),[nt,wt]=D(null),[Jt,Tn]=D(0),[Wi,Tr]=D(null),[$r,_o]=D(!1),[$n,Vi]=D(Ie),[Xt,qi]=tu(d),bt=eu("(min-width: 900px)"),[An,Ct]=D("summary"),[Zi,Yi]=D(!1),[xo,Ar]=D(!1),[ko,Rr]=D(50),[Mr,Ji]=D(!1),Rn=ee(null),wo=ee(null),Qt=ee(0);ru(wo,!pe);let Xi=ee(null),Ae=re(()=>ri(m),[m]),[Je,en]=D(null),[ot,vt]=D(!1),[So,Qi]=D(1),Fe=Je!==null,rt=Fe?Ae[Je]:null,el=re(()=>rt?ai(rt,m):null,[rt,m]);U(()=>{if(!d)return;let{body:y,documentElement:C}=document,W=[y.style.background,C.style.background];return y.style.background="var(--oa-canvas)",C.style.background="var(--oa-canvas)",()=>{y.style.background=W[0],C.style.background=W[1]}},[d]),U(()=>{try{let y=Number(window.localStorage.getItem("oa-seal-split"));y>=30&&y<=70&&Rr(y)}catch{}},[]);let tn=Ee(y=>{let C=Math.max(30,Math.min(70,Math.round(y)));Rr(C);try{window.localStorage.setItem("oa-seal-split",String(C))}catch{}},[]);U(()=>{let y=()=>{let C=ou(m.steps.length);C.tab&&Ct(C.tab),C.step!=null&&(he(C.step),Tn(C.step),C.tab||Ct("evidence"))};return y(),Ji(!0),window.addEventListener("hashchange",y),()=>window.removeEventListener("hashchange",y)},[m.steps.length]),U(()=>{An==="program"&&Yi(!0)},[An]),U(()=>{let y=window.location.origin;Ie&&h&&/^https?:/.test(y)&&y!==h&&Vi(Ie.split(h).join(y))},[Ie,h]);let tl=async(y,C,W)=>{if(y.sealOk&&!y.ok)return{...y,record:null};if(!y.sealOk&&(W.anchor||W.authorization))return{...y,ok:!1,reason:W.authorization?"auth_missing":"anchor_missing",record:null};if(!C.receiptKeys)return{...y,ok:!1,reason:"unknown_key",record:null};let Z;try{Z=JSON.parse(C.receiptText)}catch{return{...y,ok:!1,reason:"malformed",record:null}}let be=await Gs(Z,C.receiptKeys);if(!be.ok)return{...y,ok:!1,reason:be.reason,record:be};let le=await Re(C.report),Xe=be.statement.subject.find(Qe=>Qe.name==="report.json");if(!Xe||Xe.digest.sha256!==le)return{...y,ok:!1,reason:"subject_mismatch",subject:{sha256:le},record:be};if(C.receiptAnchorText!=null){let Qe=await fr(Z,C.receiptAnchorText,C.receiptKeys,be.signers);if(!Qe.ok){let Vr=Qe.reason||"inconsistent";return{...y,ok:!1,reason:Vr,subject:{sha256:le},record:{...be,ok:!1,reason:Vr,signerLines:["Not verified: the public log entry doesn't verify for this receipt"]},receiptAnchor:Qe}}let Ro=new Date(Qe.integratedTime*1e3).toISOString().replace(/\.\d+Z$/,"Z");return{...y,ok:!0,reason:null,subject:{sha256:le},record:{...be,signerLines:[...be.signerLines,`Logged publicly at ${Ro}`]},receiptAnchor:Qe}}return{...y,ok:!0,reason:null,subject:{sha256:le},record:be}},nn=Ee(async y=>{let C=++Qt.current;$e(y||null),K(null),Se(null),z(null),en(null),vt(!1),oe("verify");let W=new Promise(le=>setTimeout(le,pe?0:Vp)),Z,be=null;try{Rn.current=Rn.current||await(n?n():Us(k,H));let le=y?Vs(Rn.current,y):Rn.current,Xe={anchor:!!k.anchor,authorization:!!H};Z=le.sealText!=null?await Rs(le,B,{requireAnchor:Xe.anchor,requireAuthorization:Xe.authorization}):{ok:!1,sealOk:!1,reason:"malformed",steps:[]},le.receiptText&&(Z=await tl(Z,le,Xe)),Yt&&(Z.receiptAnchor&&!le.tsaText?be={rekor:Z.receiptAnchor,tsa:null}:(be=await ei(le,B),Z.receiptAnchor&&(be={...be,rekor:Z.receiptAnchor})));try{let Qe=le.sealText!=null?await yn(JSON.parse(le.sealText)):await Re(new TextEncoder().encode(Ce(JSON.parse(le.receiptText)))),Ro=await Re(new TextEncoder().encode(`${await Re(le.report)}${Qe}`));C===Qt.current&&yo(Ro)}catch{}}catch{Z={ok:!1,reason:"not_loaded",steps:[]}}C===Qt.current&&Se(Z.subject?.sha256??null),await W,C===Qt.current&&(z(be),K(Z),oe(Z.ok?"valid":Z.reason==="unsupported"||Z.reason==="not_loaded"?"rest":"broken"))},[k,B,H,pe,Yt,n]),[nl,ol]=D("unverified");U(()=>{if(!i||!H||!X?.ok||!X.authorizedBy?.publicKey)return;let y=!1;return vs(H.login,X.authorizedBy.publicKey).then(C=>{y||ol(C)}),()=>{y=!0}},[H,X,i]);let Eo=V??X?.timing??null,No=H&&(G||(Eo==="before_run"||Eo==="after_run")&&X?.ok)?xs(H.login,Eo,H.anchorTime??X?.authAnchorTime,nl):null,Ir=ee(!1);U(()=>{!i||!T?.rekor?.ok||Y||Ir.current||(Ir.current=!0,q("checking"),ni(T.rekor.entry).then(q))},[T,Y,i]),U(()=>{pe&&oe("rest");let y=setTimeout(()=>nn(null),pe?0:Ni+450);return()=>clearTimeout(y)},[pe]),U(()=>{if(!Fe||!ot)return;if(Je>=Ae.length-1){vt(!1);return}let y=setTimeout(()=>en(C=>Math.min(Ae.length-1,C+1)),Ae[Je].dwell/So);return()=>clearTimeout(y)},[Fe,ot,Je,Ae,So]);let To=Ee(()=>{Qt.current+=1,$e(null),oe("replay"),he(null),wt(null),Ct(y=>y==="program"?y:"evidence"),en(y=>y===null||y>=Ae.length-1?0:y),vt(!0)},[Ae.length]),St=Ee((y,C=!1)=>{oe("replay"),en(Math.max(0,Math.min(Ae.length-1,y))),C||vt(!1)},[Ae.length]),Cr=()=>{en(null),vt(!1),oe(X?.ok?"valid":X?"broken":"rest")},Pr=()=>St(si(Ae,Je??-1),ot),on=y=>{let C=rt?rt.step:-1,W=Math.max(0,Math.min(Ae.at(-1).step,C+y));St(io(Ae,W))};U(()=>{let y=C=>{let W=C.target;if(W&&(W.closest?.("input, textarea, select, [contenteditable]")||C.metaKey||C.ctrlKey||C.altKey))return;let Z=!!W?.closest?.('[role="tablist"], [role="separator"], [data-steplist], .opg-root'),be=W?.closest?.("button, a, summary");if(!(Z&&C.key!=="j"&&C.key!=="k")){if(C.key===" "&&!be&&!W?.closest?.("[data-step]"))C.preventDefault(),ot?vt(!1):To();else if(Fe&&C.key==="ArrowRight"&&!W?.closest?.("[data-step]"))C.preventDefault(),C.shiftKey?Pr():on(1);else if(Fe&&C.key==="ArrowLeft"&&!W?.closest?.("[data-step]"))C.preventDefault(),on(-1);else if(Fe&&C.key==="Escape")Cr();else if((C.key==="j"||C.key==="k")&&!C.shiftKey){C.preventDefault();let le=C.key==="j"?1:-1;if(Fe)on(le);else{let Xe=m.steps.length,Qe=Q??(le>0?-1:Xe);dt(Math.max(0,Math.min(Xe-1,Qe+le)))}}}};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)});let Mn=Fe?rt.step:Q??nt,rn=Mn!=null?m.steps[Mn]:null,Or=Ee((y,C={})=>{C.focus&&Tn(y),Je!==null?St(io(Ae,y)):wt(y)},[Je,Ae,St]),dt=Ee((y,{keepTab:C=!1}={})=>{Je!==null?St(io(Ae,y)):he(y),Tn(y),C||Ct(W=>W==="program"?W:"evidence")},[Je,Ae,St]),rl=y=>{let C=m.steps.length,W={ArrowRight:1,ArrowDown:1,ArrowLeft:-1,ArrowUp:-1},Z=null;if(y.key in W)Z=(Jt+W[y.key]+C)%C;else if(y.key==="Home")Z=0;else if(y.key==="End")Z=C-1;else if(y.key==="Escape"){he(null),wt(null),y.currentTarget.blur();return}else if(y.key==="Enter"||y.key===" "){y.preventDefault(),dt(Jt);return}else return;y.preventDefault(),Tn(Z),Or(Z),wo.current?.querySelector(`[data-step="${Z}"]`)?.focus()},We=An==="program"&&bt?"summary":An,$o=Fe?null:Q;U(()=>{if(!Mr||ot)return;let y=Mi(We,$o);if(!(y===window.location.hash||!y&&!window.location.hash))try{window.history.replaceState(window.history.state,"",`${window.location.pathname}${window.location.search}${y}`)}catch{}},[We,$o,Mr,ot]);let al=async()=>{try{await navigator.clipboard.writeText(`${a}${Mi(We,$o)}`),_o(!0),setTimeout(()=>_o(!1),2200)}catch{_o(!1)}},ze=m.counts,Lr=[{ring:"steps",big:`${ze.stepsPassed}/${ze.steps}`,small:m.stoppedAt==null?"steps passed":`steps, stopped at ${m.stoppedAt+1}`},{ring:"checks",big:`${ze.checksPassed}/${ze.checks}`,small:ze.checksFailed?`screen checks, ${ze.checksFailed} failed`:"screen checks"},{ring:"readbacks",big:`${ze.readbacksPassed}/${ze.readbacks}`,small:ze.readbacksFailed?`record checks, ${ze.readbacksFailed} failed`:ze.readbacksPassed?"record checks confirmed":"record checks, not reached"},{ring:"identity",big:`${ze.identityPassed}/${ze.identity}`,small:"right-record checks"}],zr=S?ii(S):null,Dr=l??(O?`Referral ${O} of ${M}`:null),an=!!Y,ke=Te==="verify"||Te==="build"?null:X?.ok?"valid":X?.reason==="unsupported"?"unsupported":X?.reason==="not_loaded"?"not_loaded":X?"fails":null,Fr=(y,C)=>y?C?C.ok?"pass":"fail":"pending":null,Hr=Yt?{rekor:Fr(k.anchor||k.receiptAnchor,T?.rekor),tsa:Fr(k.tsa,T?.tsa)}:null,sl=`The receipt of this run: ${Lr.map(y=>`${y.big} ${y.small}`).join("; ")}.`,Pt=Te==="verify"||Te==="build",Ot=rn,il=Ot?`Step ${Ot.i+1} of ${m.steps.length}${Ot.section?` · ${Ot.section}`:""}${Ot.t0!=null?` · at ${Zt(Ot.t0)}`:""}`:null,Ao=Fe?rt.step:Q,He=Ao!=null?m.steps[Ao]:null,ll=m.steps.filter(y=>y.status!=="not_reached").length,jr=ke===null?{state:"pending",text:Te==="build"?"Assembling":"Checking signature"}:ke==="valid"?{state:"valid",text:an?"Restored · signature valid":"Signature valid"}:ke==="fails"?{state:"fails",text:an?"Changed copy fails":"Signature check fails"}:ke==="unsupported"?{state:"unchecked",text:"Report matches · signature not checked here"}:{state:"unchecked",text:"Not checked here"},Gr=["summary","program","steps","evidence","raw"],Et=bt?Pi:Gr,cl=y=>{let C=Et.indexOf(We),W={ArrowRight:1,ArrowLeft:-1},Z=null;if(y.key in W)Z=Et[(C+W[y.key]+Et.length)%Et.length];else if(y.key==="Home")Z=Et[0];else if(y.key==="End")Z=Et[Et.length-1];else return;y.preventDefault(),Ct(Z),y.currentTarget.querySelector(`[data-tab="${Z}"]`)?.focus()},Ur=ee(null),Br=ee(null),Kr=ee(null);U(()=>{let y=Br.current,C=Kr.current;if(!y||!C||typeof ResizeObserver>"u")return;let W=new ResizeObserver(()=>C.style.setProperty("--top-h",`${y.offsetHeight}px`));return W.observe(y),()=>W.disconnect()},[]);let dl=y=>{let C={ArrowLeft:-2,ArrowRight:2};if(y.key in C)tn(ko+C[y.key]);else if(y.key==="Home")tn(30);else if(y.key==="End")tn(70);else if(y.key==="Enter")Ar(W=>!W);else return;y.preventDefault()},pl=y=>{let C=Ur.current;if(!C||y.button!==0)return;y.preventDefault();let W=y.currentTarget;W.setPointerCapture?.(y.pointerId);let Z=C.getBoundingClientRect(),be=Xe=>tn((Xe.clientX-Z.left)/Z.width*100),le=()=>{W.removeEventListener("pointermove",be),W.removeEventListener("pointerup",le),W.removeEventListener("pointercancel",le)};W.addEventListener("pointermove",be),W.addEventListener("pointerup",le),W.addEventListener("pointercancel",le)},ul=bt||We==="program"||Zi,fl=u==="demo"||b?.issuer==="demo",Lt=X?.record??null,Wr=Lt?ke===null?{state:"pending",text:"Checking who signed it"}:Lt.ok&&ke==="valid"?{state:Lt.demo?"demo":"signed",text:Lt.signerLines.join(" · ")}:Lt.reason==="unknown_signer"?{state:"unknown",text:"Not verified: unknown signer"}:{state:"fails",text:Lt.signerLines?.[0]||"Not verified"}:ke===null?{state:"pending",text:"Checking who signed it"}:ke==="valid"?fl?{state:"demo",text:"Demo key: checks only in this demo"}:u==="this_computer"?{state:"signed",text:"Signed by this computer"}:{state:"signed",text:"Signed by a pinned key"}:Yp.has(X?.reason)?{state:"unknown",text:"Not verified: unknown signer"}:ke==="fails"?{state:"fails",text:"Not verified: the signature check failed"}:{state:"unchecked",text:"Not verified here"},In=!!(e.receiptRecord||k?.receipt||k?.receiptText||X?.record),Cn=In&&e.receiptRecord?e.receiptRecord:b,hl=!In&&typeof b?.schema=="string"&&/^openadapt\.(local-seal|public-seal)\//.test(b.schema),gl=ke===null?s("span",{className:N.pending,children:Te==="build"?"Assembling the receipt from the report":"Checking the Ed25519 signature in your browser"}):ke==="valid"?s(se,{children:[s("b",{children:"Valid."})," This is the report exactly as the run wrote it, ",c,"."]}):ke==="unsupported"?s(se,{children:[s("b",{children:"The report matches."})," This browser can't check Ed25519 signatures; ",$n?"use the commands under Raw.":"check it from a terminal: openadapt verify RUN_FOLDER."]}):ke==="not_loaded"?s(se,{children:[s("b",{children:"The files didn't load,"})," so nothing was checked here. ",$n?"Use the commands under Raw.":"Check it from a terminal: openadapt verify RUN_FOLDER."]}):s(se,{children:[s("b",{children:"Fails."})," ",Ti(X.reason)," ",s("code",{className:N.code,children:X.reason})]});return s(se,{children:[s("a",{className:N.skip,href:"#main",onClick:y=>{y.preventDefault(),document.getElementById("main")?.focus()},children:"Skip to content"}),s("div",{ref:Kr,className:N.page,"data-tone":_,"data-phase":Te,"data-theme":d?void 0:Xt,"data-layout":bt?"split":"stack","data-expanded":bt&&xo?"1":void 0,"data-view":We,style:{"--split":`${ko}%`},children:[s("header",{className:N.top,ref:Br,children:[r.home?s(o,{href:r.home.href,className:N.home,"aria-label":r.home.label,children:[s(uo,{className:N.mark}),s("span",{children:r.home.label})]}):s("span",{className:N.home,children:[s(uo,{className:N.mark}),s("span",{children:"OpenAdapt"})]}),s("span",{className:N.crumb,children:[s("span",{children:"Signed run report"}),Dr?s("span",{children:Dr}):null]}),$?.length?s("nav",{className:N.runs,"aria-label":"The other runs",children:$.map(y=>s(o,{href:y.href,className:N.run,"data-tone":y.tone,"aria-current":y.sealId===e.sealId?"page":void 0,title:`Referral ${y.referral}: ${y.label}`,children:[s("span",{className:N.runSeal,"aria-hidden":"true",children:s(po,{rings:y.rings,tone:y.tone,digest:y.digest,variant:"emblem",phase:"rest",still:!0,label:""})}),s("span",{className:N.runText,children:[s("b",{children:y.referral}),s("span",{children:y.label})]})]},y.sealId))}):null,s("span",{className:N.topEnd,children:[s("span",{className:N.chip,"data-chip":jr.state,role:"status",children:[s("span",{className:N.chipDot,"aria-hidden":"true"}),jr.text]}),a?s("button",{type:"button",className:N.iconBtn,onClick:al,title:"Copy a link to this view","aria-label":$r?"Link copied":"Copy link",children:[s(au,{}),s("span",{className:N.wideOnly,children:$r?"Copied":"Copy link"})]}):null,s("button",{type:"button",className:N.iconBtn,onClick:qi,"aria-label":`Switch to the ${Xt==="dark"?"light":"dark"} theme`,title:`Switch to the ${Xt==="dark"?"light":"dark"} theme`,children:s(su,{theme:Xt})})]})]}),s("div",{className:N.app,ref:Ur,children:[s("main",{id:"main",tabIndex:-1,className:N.hero,"aria-labelledby":"seal-h1",children:[s("section",{className:N.stage,ref:wo,"aria-label":"The receipt",tabIndex:-1,onMouseLeave:()=>wt(null),children:s("div",{className:N.tilt,ref:Xi,children:s(po,{rings:m,tone:_,digest:tt,phase:Te,buildMs:Ni,active:Fe?null:Mn,focusIndex:Jt,onActive:Or,onPick:dt,onKey:rl,ringFocus:Wi,witnesses:Hr,lit:el,spot:rt?.spotlight||null,label:sl})})}),s("div",{className:N.heading,children:[s("h1",{id:"seal-h1",className:N.outcome,children:x}),A?s("p",{className:N.reason,children:Xp(A)}):null,s("p",{className:N.meta,children:[s("span",{children:E}),s("span",{children:R}),zr?s("span",{children:zr}):null]}),s("p",{className:N.verdict,"data-verdict":ke||"pending","aria-live":"polite",children:gl}),s("p",{className:N.signer,"data-signer":Wr.state,children:s("span",{children:Wr.text})}),an&&ke==="fails"?s("div",{className:N.changed,"data-changed":"",children:[s("p",{className:N.changeHead,children:[s("b",{children:"This changed copy fails:"})," ",Y.field==="model_calls"?"model calls":"outcome"," ",Y.from," → ",Y.to,". The receipt no longer matches."]}),s("p",{className:N.change,children:["Changed in a copy of the ",Y.target==="seal"?"receipt":"report",": ",s("code",{children:Y.field})," ",s("del",{children:Y.from})," → ",s("ins",{children:Y.to}),"."]}),s("p",{className:N.change,children:g}),s("div",{className:N.actions,children:[s("button",{type:"button",className:N.primary,onClick:()=>nn(null),disabled:Pt,children:"Restore"}),s("button",{type:"button",className:N.ghost,"aria-expanded":Oe,"aria-controls":"receipt-changes",onClick:()=>Le(y=>!y),children:"Try another change"})]}),s("div",{id:"receipt-changes",className:N.another,role:"group","aria-label":"Other changes",hidden:!Oe,children:P.filter(y=>y.id!==Y.id).map(y=>s("button",{type:"button",className:N.tchip,disabled:Pt,onClick:()=>nn(y),children:[s("span",{children:y.label}),s("code",{children:[y.from," → ",y.to]})]},y.id))})]}):null,s("div",{className:N.actions,children:[s("button",{type:"button",className:N.primary,onClick:ot?()=>vt(!1):To,disabled:Pt,children:[s("span",{"aria-hidden":"true",children:ot?"❚❚":"▶"}),ot?"Pause the run":Fe?"Resume the run":"Play the run"]}),s("button",{type:"button",className:N.ghost,onClick:()=>nn(null),disabled:Pt,children:"Verify"}),an&&ke==="fails"?null:s("button",{type:"button",className:N.ghost,onClick:()=>{Le(!1),nn(P[0])},disabled:Pt||!P.length,children:"Try changing it"})]})]}),s("div",{className:N.dock,children:[s(lu,{frames:Ae,frame:Je,playing:ot,speed:So,busy:Pt,rings:m,onPlay:To,onPause:()=>vt(!1),onSeek:St,onNext:Pr,onSpeed:Qi,onClose:Cr}),s("p",{className:N.stepLine,"data-step":rn?rn.i:"","aria-live":"polite",children:il||(ke==="valid"?`✓ Signature valid over this exact report · ${ll} steps`:ke==="fails"?`✗ ${Ti(X?.reason)}`:" ")})]})]}),s("section",{className:N.mapPane,"aria-labelledby":"map-h",id:"seal-panel-program",role:bt?void 0:"tabpanel",children:[s("div",{className:N.paneHead,children:[s("h2",{id:"map-h",children:"Program steps for this run"}),bt?s("button",{type:"button",className:N.iconBtn,"aria-pressed":xo,onClick:()=>Ar(y=>!y),children:xo?"Show details":"Expand map"}):null]}),ul?s(kr,{program:te,map:{title:`${E} · ${R}`,...f},step:Mn,status:rn?rn.status==="stopped"?"stopped":rt?.stage==="done"?"saved":"running":null,onPick:y=>dt(y),anchor:m.anchor,sealRun:{rings:m,tone:_,irisSeed:tt,referral:O},sealLine:li({rings:m,label:x,stopReason:A},ke==="valid"),theme:Xt,fill:bt}):null]}),s("div",{className:N.resizer,role:"separator","aria-orientation":"vertical","aria-label":"Resize the program map","aria-valuenow":ko,"aria-valuemin":30,"aria-valuemax":70,tabIndex:0,onKeyDown:dl,onPointerDown:pl,onDoubleClick:()=>tn(50),title:"Drag, or use the arrow keys. Enter expands the map."}),s("div",{className:N.tabs,role:"tablist","aria-label":"Details",onKeyDown:cl,children:Gr.map(y=>s("button",{type:"button",role:"tab",id:`seal-tab-${y}`,"data-tab":y,"aria-selected":We===y,"aria-controls":`seal-panel-${y}`,tabIndex:We===y?0:-1,onClick:()=>Ct(y),children:[nu[y],y==="steps"?s("span",{className:N.count,children:m.steps.length}):null,y==="evidence"&&He?s("span",{className:N.count,children:He.i+1}):null]},y))}),s("div",{className:N.panels,children:[s("section",{id:"seal-panel-summary",role:"tabpanel","aria-labelledby":"seal-tab-summary",hidden:We!=="summary",className:N.panel,children:[s("p",{className:N.line,children:w}),H&&No?s("p",{className:N.by,children:s("a",{href:`https://github.com/${H.login}`,rel:"noopener noreferrer",children:No})}):null,s("dl",{className:N.stats,"aria-label":"What the receipt shows",children:Lr.map(y=>s("div",{"data-ring":y.ring,onMouseEnter:()=>Tr(y.ring),onMouseLeave:()=>Tr(null),children:[s("dt",{children:[s("span",{className:N.swatch,"aria-hidden":"true"}),y.small]}),s("dd",{children:y.big})]},y.ring))}),s("p",{className:N.calls,children:ze.modelCalls==null?`The program ran for ${Zt(m.runMs)}.`:`The program ran for ${Zt(m.runMs)} and made ${ze.modelCalls} AI model calls.`}),s("h2",{className:N.sub,children:"The signature check"}),s("div",{className:N.proof,children:[s(gr,{label:an&&Y.target==="report"?"This copy of report.json":"report.json, in this browser",from:Cn.signature,to:xe,against:Cn.subject_sha256,running:Te==="verify",still:pe}),s("div",{className:N.signed,children:[s("span",{className:N.proofLabel,children:"Signed in the receipt"}),s("code",{className:N.hex,children:Cn.subject_sha256})]})]}),s("p",{className:N.foot,children:[p||"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:N.panel,children:s(iu,{rings:m,active:Ao,onPick:y=>dt(y),onFocusStep:y=>dt(y,{keepTab:!0})})}),s("section",{id:"seal-panel-evidence",role:"tabpanel","aria-labelledby":"seal-tab-evidence",hidden:We!=="evidence",className:N.panel,children:He?s(se,{children:[s("div",{className:N.evHead,children:[s("p",{className:N.evTitle,children:[s("span",{className:N.evNum,children:["Step ",He.i+1," of ",m.steps.length]}),He.section?s("span",{children:He.section}):null,He.t0!=null?s("span",{children:["at ",Zt(He.t0)]}):null]}),s("span",{className:N.evNav,children:[s("button",{type:"button",className:N.iconBtn,onClick:()=>Fe?on(-1):dt(Math.max(0,He.i-1)),disabled:He.i===0,"aria-label":"Previous step",title:"Previous step (k)",children:"‹"}),s("button",{type:"button",className:N.iconBtn,onClick:()=>Fe?on(1):dt(Math.min(m.steps.length-1,He.i+1)),disabled:He.i===m.steps.length-1,"aria-label":"Next step",title:"Next step (j)",children:"›"})]})]}),s(cu,{step:He,rings:m,media:L[He.i],frame:rt,stopReason:A,stopNote:ve,mediaNote:v})]}):s("div",{className:N.empty,children:[s("p",{children:["Pick a step on the map, on the receipt or in Steps to see its checks",L.some(y=>y&&(y.crop||y.frame))?", its pictures":""," and its record checks."]}),m.anchor?s("button",{type:"button",className:N.ghost,onClick:()=>dt(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:N.panel,children:[hl?s("p",{className:N.older,"data-format":"",children:["Format: ",b.schema.replace(/^openadapt\./,""),", still verifies"]}):In?s("p",{className:N.older,"data-format":"",children:"Format: record/run/v1"}):null,s(pu,{seal:Cn,isRecord:In,files:k,links:r,witnesses:Hr,witness:T,live:Y?null:ue,authorization:H,authorizedLine:No}),$n?s(se,{children:[s("h2",{className:N.sub,children:e.commandsLabel||"Check the same files on your computer"}),s("pre",{className:N.cmds,tabIndex:0,children:s("code",{children:$n})})]}):null]})]})]})]})]})}function au(){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 su({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 iu({rings:e,active:t,onPick:n,onFocusStep:o}){let r=ee(null),[a,i]=D(t??0);U(()=>{t!=null&&i(t)},[t]);let l=e.steps.length,p=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:N.steps,ref:r,"data-steplist":"",onKeyDown:p,"aria-label":"The run's steps",children:e.steps.map(c=>{let g=e.identity.find(f=>f.step===c.i),h=e.readbacks.filter(f=>f.step===c.i),d=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:N.sNum,children:String(c.i+1).padStart(2,"0")}),s("span",{className:N.sMark,"aria-hidden":"true",children:c.status==="passed"?"✓":c.status==="stopped"?"■":"·"}),s("span",{className:N.sName,children:[c.name,c.section?s("small",{children:c.section}):null]}),s("span",{className:N.sTags,children:[g?s("span",{"data-ok":g.result==="passed"?"1":"0",children:"record"}):null,d?s("span",{"data-ok":c.checks.failed?"0":"1",children:[d," ",d===1?"check":"checks"]}):null,h.length?s("span",{"data-ok":h.some(f=>f.result==="failed")?"0":"1",children:[h.length," record ",h.length===1?"check":"checks"]}):null]}),s("span",{className:N.srOnly,children:[c.status==="passed"?", passed":c.status==="stopped"?", stopped here":", not reached",g?", checks the right record":""]})]})},c.i)})})}function lu({frames:e,frame:t,playing:n,speed:o,busy:r,rings:a,onPlay:i,onPause:l,onSeek:p,onNext:c,onSpeed:g,onClose:h}){let d=t??0,f=e[d],u=f?a.steps[f.step]?.t0??0:0;return s("div",{className:N.player,"data-active":t!==null?"1":void 0,children:[s("button",{type:"button",className:N.pBtn,onClick:n?l:i,disabled:r,"aria-label":n?"Pause":"Play the run",children:n?"❚❚":"▶"}),s("button",{type:"button",className:N.pBtn,onClick:c,disabled:r,"aria-label":"Next highlight",title:"Next highlight (Shift + →)",children:"⏭"}),s("input",{className:N.scrub,type:"range",min:"0",max:e.length-1,value:d,disabled:r,"aria-label":"Position in the run","aria-valuetext":f?`Step ${f.step+1} of ${a.steps.length}`:void 0,onChange:v=>p(Number(v.target.value))}),s("span",{className:N.pTime,children:[Zt(u)," / ",Zt(a.runMs)]}),s("span",{className:N.speeds,role:"group","aria-label":"Speed",children:qp.map(v=>s("button",{type:"button","aria-pressed":o===v,onClick:()=>g(v),children:[v,"×"]},v))}),t!==null?s("button",{type:"button",className:N.pBtn,onClick:h,"aria-label":"Leave the replay",children:"×"}):null]})}function cu({step:e,rings:t,media:n,frame:o,stopReason:r,stopNote:a,mediaNote:i}){let l=t.readbacks.filter(u=>u.step===e.i),p=t.identity.find(u=>u.step===e.i),c=e.checks.passed+e.checks.failed,g=!!o,h=g?o.step===e.i?o.readbacks:0:l.length,d=g?o.spotlight:null,f=[["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"],p?["Right record",p.result==="passed"?"✓ Confirmed before acting":p.result==="not_reached"?"Not reached":"✗ Not confirmed",p.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",Jp(l.filter(u=>u.result==="passed").length,l.length),l.some(u=>u.result==="failed")?"halt":l.every(u=>u.result==="passed")?"ok":"ghost","save"]:null].filter(Boolean);return s("aside",{className:N.inspector,"data-status":e.status,"data-step":e.i,"data-spot":d||void 0,"aria-live":"polite",children:[s("div",{className:N.inMain,children:[s("table",{className:N.kv,children:s("tbody",{children:f.map(([u,v,m,b])=>s("tr",{"data-tone":m,"data-spot":d&&d===b?"1":void 0,children:[s("th",{scope:"row",children:u}),s("td",{children:v})]},u))})}),d==="stop"&&a?s("p",{className:N.spotNote,children:a}):null,n&&(n.crop||n.frame)?s("div",{className:N.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:N.shotsNote,"data-media-note":"",children:i}):null]}):null]}),l.length?s("table",{className:N.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((u,v)=>{let m=vnew Date(e*1e3).toISOString().replace("T"," ").replace(/\.\d+Z$/," UTC"),wr=e=>String(e).replace("T"," ").replace(/(\.\d+)?Z$/," UTC"),Sr=(e,t=16)=>`${String(e).slice(0,t)}…`,Ii={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 pu({seal:e,isRecord:t=!1,files:n,links:o,witnesses:r,witness:a,live:i,authorization:l,authorizedLine:p}){let c=a?.rekor,g=a?.tsa,h=[["Outcome",s("code",{children:e.outcome},"o"),null],["Report SHA-256",s("code",{title:e.subject_sha256,children:Sr(e.subject_sha256,24)},"d"),null],["Signed by",s("code",{children:e.key_id},"k"),null],["Signature",s("code",{title:e.signature,children:Sr(e.signature,24)},"s"),"Ed25519"],...t?[...e.started_hour?[["Started",wr(e.started_hour),null]]:[],...e.program_id?[["Program",s("code",{children:e.program_id},"pr"),null]]:[]]:[["Issued",wr(e.issued_at),null],...e.scope_item?[["Scope",s("code",{children:e.scope_item},"sc"),null]]:[]]];return r?.rekor&&h.push(["Public log",r.rekor==="pending"?"Checking…":c?.ok?s("span",{children:["Sigstore Rekor entry"," ",s("a",{href:ti(c.logIndex),rel:"noopener noreferrer",children:c.logIndex}),", logged ",du(c.integratedTime),", log ",s("code",{children:Sr(c.logId,8)}),". The inclusion proof, signed timestamp and checkpoint verify against the pinned Rekor key.",i==="match"?" This entry matches the public log.":i==="differs"?" The public log serves a different entry.":""]},"r"):s("span",{children:[Ii[c?.reason]||"The log entry doesn't verify."," ",s("code",{children:c?.reason})]},"rf"),r.rekor]),r?.tsa&&h.push(["Timestamp",r.tsa==="pending"?"Checking…":g?.ok?s("span",{children:["Sigstore Timestamp Authority (RFC 3161): ",wr(g.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:[Ii[g?.reason]||"The timestamp doesn't verify."," ",s("code",{children:g?.reason})]},"tf"),r.tsa]),l&&p&&h.push(["Authorized",s("span",{children:[p,", with an SSH key"," ",s("a",{href:`https://github.com/${l.login}.keys`,rel:"noopener noreferrer",children:["GitHub lists for @",l.login]}),"."]},"a"),"pass"]),s("section",{className:N.record,"aria-labelledby":"record-h",children:[s("h2",{id:"record-h",className:N.recordH,children:"The signed record"}),s("table",{className:N.recordTable,children:s("tbody",{children:h.map(([d,f,u])=>s("tr",{"data-state":u||void 0,children:[s("th",{scope:"row",children:[u==="pass"||u==="fail"||u==="pending"?s("span",{className:N.wMark,"aria-hidden":"true"}):null,d]}),s("td",{children:f})]},d))})}),o.file?s("p",{className:N.fileLinks,children:[["report.json",n.receipt?"receipt.json":null,n.receiptAnchor?"receipt.anchor.json":null,n.seal?"seal.json":null,n.anchor?"seal.anchor.json":null,n.tsa?"seal.tsa.json":null,n.tsr?"seal.tsr":null].filter(Boolean).map(d=>[d,lo(o.file(d))]).filter(([,d])=>d).map(([d,f])=>s("a",{href:f,children:d},d)),o.keys&&lo(o.keys.href)?s("a",{href:lo(o.keys.href),children:o.keys.label}):null]}):null]})}var Li={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 Nr(e){if(Li[e])return Li[e];let t=String(e).replace(/[_-]+/g," ").trim();return t.charAt(0).toUpperCase()+t.slice(1)}function zi(e){let t=e.match(/^type <(\w+)>$/);if(t)return`Type ${Nr(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 uu={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"},It=e=>String(e).replace(/^.*::/,"");function fu(e){let t=/field '(\w+)' equals/.exec(e||"");return t?`${uu[t[1]]||Nr(t[1])} matches`:/record_written/.test(e||"")?"The new record exists":null}function Di(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,E)=>{if(It(w.step_id)!==It(t.steps[E].id))throw new Error(`step ${E+1}: the report and the program differ`)});let o=0,r=n.map(w=>{let E=Math.max(0,Number(w.elapsed_ms)||0),R={t0:o,t1:o+E};return o+=E,R}),a=o,i=e.outcome_envelope?.postcondition_evidence||[],l=new Map;for(let w of i){let E=l.get(w.result_index)||[];E.push(w),l.set(w.result_index,E)}let p=t.steps.map((w,E)=>{let R=n[E],S=R?R.ok?"passed":"stopped":"not_reached",A=l.get(E)||[];return{i:E,id:It(w.id),name:w.name,section:w.section,status:S,t0:R?r[E].t0:null,t1:R?r[E].t1:null,checks:{passed:A.filter(L=>L.verdict==="passed").length,failed:A.filter(L=>L.verdict!=="passed").length},identity:R?R.identity?.status==="verified"?"passed":R.identity?"failed":null:null}}),c=i.map(w=>{let E=p[w.result_index];if(!E||E.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:E.t1}}),g=Array.isArray(e.governed_qualified_effect_requirements)?e.governed_qualified_effect_requirements:[],h=g.length?g.map(w=>({step:p.findIndex(E=>E.id===It(w.step_id??"")),at:Number.isInteger(w.effect_index)?w.effect_index:-1})):n.flatMap((w,E)=>(Array.isArray(w.effect_evidence)?w.effect_evidence:[]).map((R,S)=>({step:E,at:S}))),d=h.map((w,E)=>{let R=n[w.step],S=Array.isArray(R?.effect_evidence)?R.effect_evidence:[],A=Array.isArray(R?.effect_results)?R.effect_results:[],L=S[w.at],P=R?r[w.step]:null,$=h.filter(M=>M.step===w.step),O=$.indexOf(w);return{i:E,step:w.step,result:L?L.final_verdict==="confirmed"?"passed":"failed":"not_reached",label:w.at>=0&&fu(A[w.at])||null,t:L&&P?P.t0+(P.t1-P.t0)*(.55+.45*O/$.length):null}}),u=(Array.isArray(e.required_identity_step_ids)?e.required_identity_step_ids.map(It):[]).map(w=>{let E=p.find(R=>R.id===w);if(!E)throw new Error(`a right-record check on an unknown step ${w}`);return{step:E.i,result:E.identity??"not_reached",t:E.t0==null?null:E.t0+(E.t1-E.t0)*.3}}),v=p.find(w=>w.status==="stopped")||null,m=(w,E)=>w.filter(R=>R.result===E).length,b=d.find(w=>w.result==="passed"),_=[...p].reverse().find(w=>w.status!=="not_reached"),x=v?{step:v.i,kind:"stop"}:b?{step:b.step,kind:"save"}:_?{step:_.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:x,steps:p,checks:c,readbacks:d,identity:u,counts:{steps:p.length,stepsPassed:p.filter(w=>w.status==="passed").length,checks:c.length,checksPassed:m(c,"passed"),checksFailed:m(c,"failed"),readbacks:d.length,readbacksPassed:m(d,"passed"),readbacksFailed:m(d,"failed"),identity:u.length,identityPassed:m(u,"passed"),modelCalls:e.model_calls??null}}}function Fi(e,{folds:t=null,report:n=null,titles:o=null,digest:r=null}={}){let a=(e?.nodes||[]).filter(p=>p.kind==="action"),i=new Map((Array.isArray(n?.results)?n.results:[]).map(p=>[It(p.step_id),p.intent])),l=new Map;for(let p of t?.groups||[])for(let c of p.nodes)l.set(c,p.title);return{digest:r||e?.bundle?.provenance?.content_digest||t?.source?.body_content_digest||null,steps:a.map(p=>{let c=i.get(It(p.id));return{id:p.id,name:o?.[p.id]||(c?zi(c):p.title),section:l.get(p.id)||null}})}}function hu(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 gu=[[/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"]],mu={"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 bu(e){let t=[e?.halt?.reason,e?.halt?.intent].filter(Boolean).join(" "),n=gu.find(([o])=>o.test(t));return n?n[1]:null}function Hi(e,t,n){let o=hu(t?.outcome,e?.transaction_outcome,{readBack:!!n?.counts?.readbacksPassed}),r=t?.outcome==="VERIFIED"?null:bu(e);return{...o,headline:r?`${o.label}: ${r}`:o.label,reason:r,note:r&&mu[r]||null}}var ji=e=>new TextDecoder().decode(e),vo=async e=>Re(new TextEncoder().encode(e));function vu(e){let t=JSON.parse(e),n=JSON.parse(ji(Pe(t.payload))),o=n.predicate||{},r=(n.subject||[]).find(i=>i?.name==="report.json"),a=Array.isArray(t.signatures)?t.signatures:[];return{envelope:t,record:{outcome:o.outcome??"",subject_sha256:r?.digest?.sha256??"",key_id:a.map(i=>i?.keyid).filter(Boolean).join(", "),signature:a[0]?.sig??"",started_hour:o.started_hour??null,program_id:o.program?.id??null,schema:"record/run/v1"}}}var yu=async e=>vo(e.subject_sha256+await vo(Ce(e)));async function Gi({files:e,keys:t,program:n,about:o={},authorization:r=null}){let a=e.sealText!=null?JSON.parse(e.sealText):null,i=e.receiptText!=null?vu(e.receiptText):null,l=i?.record??null;if(!a&&!l)throw new Error("the run has no seal or receipt");let p=a||l,c=JSON.parse(ji(e.report)),g=Fi(n.spec,{folds:n.folds||null,titles:n.titles||null,digest:n.digest||null,report:c}),h=Di(c,g),d=Hi(c,l||a,h),f=a?await yu(a):await vo(l.subject_sha256+await vo(Ce(i.envelope)));return{files:e,page:{id:o.id||a?.run_id||c.run_id||"",tone:d.tone,label:d.label,headline:d.headline,line:d.line,job:o.job||c.workflow_name||"Run",app:o.app||"Test copy",startedAt:c.started_at??null,stopReason:d.reason,stopNote:d.note,rings:h,irisSeed:f,media:h.steps.map(()=>({crop:null,frame:null})),seal:p,receiptRecord:l,keys:t,files:{report:"report.json",seal:e.sealText!=null?"seal.json":null,receipt:e.receiptText!=null?"receipt.json":null,anchor:e.anchorText!=null?"seal.anchor.json":null,receiptAnchor:e.receiptAnchorText!=null?"receipt.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:Ws(p.outcome,c.execution_outcome),program:{spec:n.spec,folds:n.folds||null,titles:Object.fromEntries(g.steps.map(u=>[u.id,u.name]))},runs:[]}}}var Ui=e=>Uint8Array.from(atob(e),t=>t.charCodeAt(0));function Bi({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 _u(){let e=(0,Ki.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&&!n.receipt_text){e.render(s(Bi,{text:"The page has no run in it. Write one with: openadapt receipt view RUN_FOLDER"}));return}let o={report:Ui(n.report_b64),sealText:n.seal_text??null,anchorText:n.anchor_text??null,tsaText:n.tsa_text??null,tsrBytes:n.tsr_b64?Ui(n.tsr_b64):null,auth:n.auth??null,receiptText:n.receipt_text??null,receiptAnchorText:n.receipt_anchor_text??null,receiptKeys:n.receipt_keys??null},r;try{r=await Gi({files:o,keys:n.keys,program:n.program,about:n.about||{},authorization:n.authorization??null})}catch(l){e.render(s(Bi,{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=Oi(a).title;let i=n.host||{};e.render(s(Er,{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/"}}}))}_u();})(); diff --git a/openadapt/wrap_sdk.py b/openadapt/wrap_sdk.py index 8f266dea40..ab5367f99d 100644 --- a/openadapt/wrap_sdk.py +++ b/openadapt/wrap_sdk.py @@ -58,6 +58,7 @@ "check_wrap_receipt", "verify_wrap_receipt", "wrap", + "wrap_receipt_word", ] F = TypeVar("F", bound=Callable[..., Any]) @@ -627,6 +628,47 @@ def _receipt_names(data: Mapping[str, Any]) -> set[str]: return names +def wrap_receipt_word( + receipt: WrapReceipt | Mapping[str, Any], + contract_receipt: Mapping[str, Any] | None = None, +) -> str: + """The receipt word for a wrap receipt, the same word every path uses. + + A wrap receipt carries no evidence of its own: ``checked_how`` is what the + caller declared for its check, not what was read. So only a Contract's + read-back can earn a word stronger than ``RECORDED``. Pass that read-back's + receipt (``contract_receipt``, a ``verify-run`` receipt whose digest is the + wrap receipt's ``contract_receipt_sha256``) and the word is the one its + evidence-scope block states, for example ``VERIFIED`` with basis + ``post_save_screen`` or ``system_api``. Anything else is ``RECORDED``: an + outcome other than confirmed, no contract receipt, a digest that does not + match, or a block that does not validate. + + The word is derived, never signed, so receipts keep their exact bytes. + """ + + data = receipt.to_dict() if isinstance(receipt, WrapReceipt) else receipt + if not isinstance(data, Mapping) or data.get("outcome") != WrapOutcome.CONFIRMED.value: + return "RECORDED" + digest = data.get("contract_receipt_sha256") + if not isinstance(contract_receipt, Mapping) or not isinstance(digest, str): + return "RECORDED" + try: + from openadapt_flow.verify_run import receipt_sha256 + from openadapt_types.evidence_scope import evidence_scope_problem + except ImportError: # pragma: no cover - the flow extra is not installed + return "RECORDED" + try: + if receipt_sha256(contract_receipt) != digest: + return "RECORDED" + except (TypeError, ValueError): + return "RECORDED" + block = contract_receipt.get("evidence_scope") + if evidence_scope_problem(block) is not None: + return "RECORDED" + return str(block["word"]) # type: ignore[index] + + def check_wrap_receipt( receipt: WrapReceipt | Mapping[str, Any], *, diff --git a/packages/flow/openadapt_flow/check_level.py b/packages/flow/openadapt_flow/check_level.py index 0a04804c44..8c7b8877ca 100644 --- a/packages/flow/openadapt_flow/check_level.py +++ b/packages/flow/openadapt_flow/check_level.py @@ -109,11 +109,19 @@ def to_effect_strength(level: CheckLevel) -> Optional[str]: return None +try: + from openadapt_types.check_level import ( # type: ignore[attr-defined] + INDEPENDENT_LEVELS as INDEPENDENT_LEVELS, + ) +except ImportError: # pragma: no cover - openadapt-types before 0.25 + INDEPENDENT_LEVELS = (CheckLevel.SEPARATE_SESSION, CheckLevel.SYSTEM_OF_RECORD) + __all__ = [ "Basis", "CONFIRMED_WORD", "CheckLevel", "ReadbackLabel", + "INDEPENDENT_LEVELS", "VERIFIED_LEVELS", "VERIFIED_WORD", "from_effect_strength", diff --git a/packages/flow/openadapt_flow/effect_location/evaluator.py b/packages/flow/openadapt_flow/effect_location/evaluator.py index 135f0c8e40..7e7d294736 100644 --- a/packages/flow/openadapt_flow/effect_location/evaluator.py +++ b/packages/flow/openadapt_flow/effect_location/evaluator.py @@ -192,7 +192,7 @@ def _level_and_basis( ) -> tuple[CheckLevel, Optional[str]]: """The level and basis a held check reaches from ``start``. - A fresh navigation is level 2 (``reopened``, SHOWN) unless the adapter + A fresh navigation is level 2 (``reopened``, no basis) unless the adapter names the ``fresh_reload`` basis and the ladder lists it at level 3; then it is level 3, which the ladder words VERIFIED. Another channel is level 4 with the basis the adapter names, if the ladder lists that basis diff --git a/packages/flow/openadapt_flow/evidence_basis.py b/packages/flow/openadapt_flow/evidence_basis.py index c7a0137e55..b199aac03c 100644 --- a/packages/flow/openadapt_flow/evidence_basis.py +++ b/packages/flow/openadapt_flow/evidence_basis.py @@ -14,13 +14,18 @@ basis ``system_api`` (:mod:`openadapt_flow.tx.api_readback`); - an atomic SQLite row read by the ``tx`` engine is level 4, basis ``owned_connection``; -- tiers 3 and 4 (the acting session) have no basis and are never - ``VERIFIED``. +- tiers 3 and 4 (the acting session's screen) earn a basis only from a + complete post-save screen check (:class:`~openadapt_types.check_level.ScreenCheck`): + the form left edit mode, no error is shown, and every intended value was + read field by field and matched. Then it is ``post_save_screen`` at level 1, + or ``reopened_record`` at level 2. The tier alone never earns it: other + evidence also lands at tier 4 (a server's answer, an artifact's default + provenance), so without the per-save record the check is ``RECORDED``. """ from __future__ import annotations -from typing import Any, Iterable, Mapping, Optional +from typing import Any, Iterable, Mapping, Optional, Sequence from openadapt_flow.check_level import ( Basis, @@ -34,6 +39,7 @@ "basis_for_tier", "evidence_scope_for_run", "level_and_basis", + "screen_basis", ] #: Verifier kinds that read the database directly. @@ -75,11 +81,47 @@ def level_and_basis( return level, basis_for_tier(tier, kinds) +def screen_basis(level: CheckLevel, checks: Sequence[Any]) -> Optional[Basis]: + """The basis a level 1 or 2 run earns from its saves' screen checks. + + ``checks`` holds one :class:`~openadapt_types.check_level.ScreenCheck` + (or a mapping of one) per save. The basis is earned only when there is + one per save, every one is complete, and they all name ``level`` + (``post_save_screen`` at level 1, ``reopened_record`` at level 2). None + otherwise, and None when the installed ``openadapt-types`` predates the + screen bases. + """ + + try: + from openadapt_types.check_level import ( # type: ignore[attr-defined] + ScreenCheck, + level_for_basis, + post_save_screen_basis, + ) + except ImportError: # pragma: no cover - older openadapt-types + return None + level = CheckLevel(level) + if level not in (CheckLevel.SAME_SCREEN, CheckLevel.REOPENED) or not checks: + return None + bases = set() + for item in checks: + check = item if isinstance(item, ScreenCheck) else ScreenCheck.from_mapping(item) + basis = post_save_screen_basis(check) + if basis is None: + return None + bases.add(basis) + if len(bases) != 1: + return None + basis = bases.pop() + return basis if level_for_basis(basis) == level else None # type: ignore[return-value] + + def evidence_scope_for_run( readback: Optional[Mapping[str, Any]], outcome: str, *, read_back_at: Optional[str] = None, + screen_checks: Sequence[Any] = (), ) -> dict[str, Any]: """The evidence-scope block for a Flow run, from its ``report.json``. @@ -88,8 +130,10 @@ def evidence_scope_for_run( run that made no save; ``outcome`` is the run's ``ExecutionOutcome`` value. The receipt for the run (``record/run/v1``) carries this block as ``evidence_scope``. Only a ``VERIFIED`` run names a basis, so only a - ``VERIFIED`` run gets the word ``VERIFIED``; a confirmed level 1 or 2 - re-read is ``SHOWN`` whatever the run's outcome. + ``VERIFIED`` run gets the word ``VERIFIED``. A level 1 or 2 run names + ``post_save_screen`` or ``reopened_record`` only with a complete + ``screen_checks`` entry for every save (:func:`screen_basis`); without + them it is ``RECORDED``. """ from openadapt_types.check_level import VERIFIED_WORD @@ -106,7 +150,11 @@ def evidence_scope_for_run( except ValueError: level = CheckLevel.UNCHECKED verified = str(outcome).upper() == VERIFIED_WORD - basis = basis_for_tier(to_verification_tier(level)) if verified else None + basis: Optional[Basis] = None + if verified: + basis = basis_for_tier(to_verification_tier(level)) + if basis is None: + basis = screen_basis(level, screen_checks) return build_evidence_scope( level, basis=basis, @@ -117,7 +165,22 @@ def evidence_scope_for_run( read_back_at=read_back_at if level > CheckLevel.UNCHECKED else None, not_covered=( "changes_after_read_back", + *(("fields_not_read",) if _any_field_not_read(screen_checks) else ()), # A run report records no per-read time yet. *(("read_back_time",) if read_back_at is None else ()), ), ) + + +def _any_field_not_read(checks: Sequence[Any]) -> bool: + """Whether a screen check says an intended value was not read.""" + + try: + from openadapt_types.check_level import ScreenCheck # type: ignore[attr-defined] + except ImportError: # pragma: no cover - older openadapt-types + return False + for item in checks: + check = item if isinstance(item, ScreenCheck) else ScreenCheck.from_mapping(item) + if check is None or check.fields_not_read: + return True + return False diff --git a/packages/flow/openadapt_flow/verify_run.py b/packages/flow/openadapt_flow/verify_run.py index 23af27d0ca..618a768bb8 100644 --- a/packages/flow/openadapt_flow/verify_run.py +++ b/packages/flow/openadapt_flow/verify_run.py @@ -67,7 +67,7 @@ from openadapt_flow.check_level import ( CONFIRMED_WORD, - VERIFIED_LEVELS, + INDEPENDENT_LEVELS, VERIFIED_WORD, CheckLevel, from_effect_strength, @@ -3574,7 +3574,7 @@ def verify_run( minimum_level = from_effect_strength(cfg.minimum_effect_strength) read_proves_delta = ( delta_verdict == "CONFIRMED" - and level in VERIFIED_LEVELS + and level in INDEPENDENT_LEVELS and level >= minimum_level and strong_enough ) diff --git a/packages/flow/tests/test_effect_location.py b/packages/flow/tests/test_effect_location.py index f355cf23cd..aba0a6af7c 100644 --- a/packages/flow/tests/test_effect_location.py +++ b/packages/flow/tests/test_effect_location.py @@ -425,15 +425,18 @@ def test_a_missing_run_id_never_passes() -> None: @pytest.mark.parametrize( ("start", "basis", "word"), [ - ("same_screen", None, "SHOWN"), - ("fresh_navigation", None, "SHOWN"), + # A screen reading earns no basis here (no per-save screen check + # record), so it claims no check; SHOWN is never written. + ("same_screen", None, "RECORDED"), + ("fresh_navigation", None, "RECORDED"), + ("same_screen", "post_save_screen", "RECORDED"), ("new_session", None, "VERIFIED"), ("other_channel", None, "RECORDED"), ("other_channel", "db_frame", "VERIFIED"), ("other_channel", "separate_session", "RECORDED"), - ("same_screen", "db_frame", "SHOWN"), - ("fresh_navigation", "db_frame", "SHOWN"), - ("same_screen", "fresh_reload", "SHOWN"), + ("same_screen", "db_frame", "RECORDED"), + ("fresh_navigation", "db_frame", "RECORDED"), + ("same_screen", "fresh_reload", "RECORDED"), ("other_channel", "fresh_reload", "RECORDED"), ], ) @@ -543,7 +546,7 @@ def test_a_fresh_navigation_without_proof_stays_reopened() -> None: assert plain.level is CheckLevel.REOPENED assert plain.basis is None if _compat.has_ladder_words(): - assert plain.word == "SHOWN" + assert plain.word == "RECORDED" def test_a_reload_claim_never_meets_a_new_session_requirement() -> None: diff --git a/packages/flow/tests/test_one_ladder.py b/packages/flow/tests/test_one_ladder.py index 8c1981b624..a285912eb3 100644 --- a/packages/flow/tests/test_one_ladder.py +++ b/packages/flow/tests/test_one_ladder.py @@ -13,8 +13,10 @@ import pytest from openadapt_types.check_level import ( BASES, + INDEPENDENT_LEVELS, VERIFIED_LEVELS, CheckLevel, + ScreenCheck, from_effect_strength, level_for_basis, outcome_word, @@ -33,6 +35,7 @@ basis_for_tier, evidence_scope_for_run, level_and_basis, + screen_basis, ) from openadapt_flow.readback_ladder import summarize_report, tier_floor from openadapt_flow.tx.api_readback import ( @@ -63,16 +66,20 @@ def test_path_tables_are_derived_from_check_level() -> None: assert verify_run_mod._STRENGTH_RANK[strength] == int(level) for strength, rank in _EFFECT_STRENGTH_RANK.items(): assert from_effect_strength(strength) == rank - # The runtime's VERIFIED floor is the ladder's weakest VERIFIED level. - assert VERIFIED_EFFECT_TIER.check_level is min(VERIFIED_LEVELS) + # The runtime's independent floor is the ladder's weakest independent level. + assert VERIFIED_EFFECT_TIER.check_level is min(INDEPENDENT_LEVELS) + # VERIFIED names every level from the post-save screen check up. + assert min(VERIFIED_LEVELS) is CheckLevel.SAME_SCREEN assert tier_floor("separate_session").check_level is CheckLevel.SEPARATE_SESSION assert tier_floor("system_of_record").check_level is CheckLevel.SYSTEM_OF_RECORD def test_each_basis_names_one_level() -> None: + assert level_for_basis("post_save_screen") is CheckLevel.SAME_SCREEN + assert level_for_basis("reopened_record") is CheckLevel.REOPENED assert level_for_basis("separate_session") is CheckLevel.SEPARATE_SESSION assert level_for_basis("fresh_reload") is CheckLevel.SEPARATE_SESSION - for basis in BASES[2:]: + for basis in BASES[4:]: assert level_for_basis(basis) is CheckLevel.SYSTEM_OF_RECORD with pytest.raises(ValueError): level_for_basis("screen") @@ -91,8 +98,13 @@ def test_each_basis_names_one_level() -> None: (CheckLevel.SEPARATE_SESSION, "fresh_reload", False, False, "RECORDED"), # No basis: a level 3 or 4 read is never VERIFIED. (CheckLevel.SYSTEM_OF_RECORD, None, True, False, "RECORDED"), - (CheckLevel.REOPENED, None, True, False, "SHOWN"), - (CheckLevel.SAME_SCREEN, None, True, False, "SHOWN"), + # A screen read is VERIFIED only with the basis a complete post-save + # check earns; without it, it claims no check. SHOWN is never written. + (CheckLevel.SAME_SCREEN, "post_save_screen", True, False, "VERIFIED"), + (CheckLevel.REOPENED, "reopened_record", True, False, "VERIFIED"), + (CheckLevel.SAME_SCREEN, "post_save_screen", False, False, "RECORDED"), + (CheckLevel.REOPENED, None, True, False, "RECORDED"), + (CheckLevel.SAME_SCREEN, None, True, False, "RECORDED"), (CheckLevel.COUNTERPARTY_CONFIRMED, None, True, False, "CONFIRMED"), (CheckLevel.UNCHECKED, None, True, True, "ATTESTED"), (CheckLevel.UNCHECKED, None, True, False, "RECORDED"), @@ -112,10 +124,18 @@ def test_a_raised_minimum_keeps_a_separate_session_read_from_verified() -> None: ) == "RECORDED" ) - # A minimum can raise the floor, never lower it below separate_session. + # A regulated floor keeps a complete post-save screen check from VERIFIED. assert ( - outcome_word(CheckLevel.REOPENED, None, minimum=CheckLevel.SAME_SCREEN) - == "SHOWN" + outcome_word( + CheckLevel.SAME_SCREEN, + "post_save_screen", + minimum=CheckLevel.SEPARATE_SESSION, + ) + == "RECORDED" + ) + assert ( + outcome_word(CheckLevel.SAME_SCREEN, "post_save_screen", minimum=CheckLevel.SAME_SCREEN) + == "VERIFIED" ) @@ -207,14 +227,17 @@ def test_same_evidence_same_level_word_and_basis_on_every_path( assert runtime == verify == direct == expected -def test_screen_reads_are_shown_and_never_verified_on_every_path(tmp_path) -> None: +def test_a_screen_tier_alone_never_earns_verified_on_any_path(tmp_path) -> None: + # Without a per-save screen check record, a tier 3 or 4 read claims no + # check: the tier alone never earns post_save_screen. for tier in ( VerificationTier.PERSISTED_STATE_REACQUISITION, VerificationTier.IMMEDIATE_SCREEN, ): runtime = _key(_runtime_scope(int(tier))) verify = _key(_verify_run_scope(tier, tmp_path)) - assert runtime == verify == (tier.check_level.label, "SHOWN", None) + assert runtime == verify == (tier.check_level.label, "RECORDED", None) + assert basis_for_tier(int(tier)) is None def test_verify_run_names_db_frame_for_a_sql_read() -> None: @@ -390,12 +413,14 @@ def test_run_receipt_states_its_evidence_scope(checked_how, word, basis) -> None ) -def test_run_receipt_never_says_verified_below_level_3() -> None: +def test_run_receipt_without_a_screen_check_record_is_not_verified() -> None: predicate = _statement(_run_report("reopened")) assert predicate["outcome"] == "UNKNOWN" assert predicate["reason_code"] == "below_verified_level" - # A confirmed level 2 re-read is SHOWN, never VERIFIED. - assert predicate["evidence_scope"]["word"] == "SHOWN" + # The runtime's report carries no per-save screen check yet, so a + # confirmed level 2 re-read earns no basis and claims no check. + assert predicate["evidence_scope"]["word"] == "RECORDED" + assert "basis" not in predicate["evidence_scope"] def test_run_receipt_without_a_readback_block_keeps_its_old_shape() -> None: @@ -419,9 +444,11 @@ def test_stopped_run_receipt_is_recorded() -> None: def test_a_fresh_reload_is_never_level_2_or_4() -> None: - # A reopen without the reload proof has no basis and stays SHOWN; the - # reload basis can't be claimed for a reopen or a system-of-record read. - assert outcome_word(CheckLevel.REOPENED, None) == "SHOWN" + # A reopen without the reload proof is level 2; the reload basis can't be + # claimed for a reopen or a system-of-record read. + assert outcome_word(CheckLevel.REOPENED, None) == "RECORDED" + with pytest.raises(ValueError): + outcome_word(CheckLevel.SEPARATE_SESSION, "reopened_record") with pytest.raises(ValueError): outcome_word(CheckLevel.REOPENED, "fresh_reload") with pytest.raises(ValueError): diff --git a/packages/flow/tests/test_post_save_screen.py b/packages/flow/tests/test_post_save_screen.py new file mode 100644 index 0000000000..6592f167fe --- /dev/null +++ b/packages/flow/tests/test_post_save_screen.py @@ -0,0 +1,82 @@ +"""The post-save screen check on Flow's paths. + +A level 1 or 2 run earns ``post_save_screen`` (or ``reopened_record``) only +from a complete screen check per save, never from its tier. The execution +profile's floor decides whether that counts: ``Standard`` accepts it, +``Regulated`` requires a separate session or the system of record. The cases +are shared with the types, kernel and launcher tests. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from openadapt_types.check_level import CheckLevel, outcome_word + +from openadapt_flow.evidence_basis import evidence_scope_for_run, screen_basis +from openadapt_flow.execution_profiles import ExecutionProfile, verified_tier_floor +from openadapt_flow.verification import VerificationTier + +CASES = json.loads( + ( + Path(__file__).resolve().parents[2] + / "types" + / "tests" + / "vectors" + / "screen-check" + / "cases.json" + ).read_text() +)["cases"] +T = "2026-11-30T12:00:00Z" + + +def _floor(profile: ExecutionProfile) -> str: + return VerificationTier(int(verified_tier_floor(None, profile))).check_level.label + + +def _scope(level: str, checks, minimum: str = "same_screen", outcome: str = "VERIFIED"): + readback = {"checked_how": level, "minimum": minimum} + return evidence_scope_for_run(readback, outcome, read_back_at=T, screen_checks=checks) + + +@pytest.mark.parametrize("case", CASES, ids=[c["name"] for c in CASES]) +def test_run_scope_matches_the_shared_cases(case) -> None: + scope = _scope(case["level"], [case["check"]]) + assert (scope["word"], scope.get("basis")) == (case["word"], case["basis"]) + level = CheckLevel.from_label(case["level"]) + assert scope["word"] == outcome_word(level, case["basis"]) + + +def test_every_save_needs_a_complete_check() -> None: + good = CASES[0]["check"] + unread = next(c["check"] for c in CASES if c["name"] == "one_field_not_read") + assert _scope("same_screen", [good, good])["word"] == "VERIFIED" + mixed = _scope("same_screen", [good, unread]) + assert mixed["word"] == "RECORDED" + assert "fields_not_read" in mixed["not_covered"] + # No record at all: the tier alone earns nothing. + assert _scope("same_screen", [])["word"] == "RECORDED" + # A reopen check can't stand in for a same-screen level, or the reverse. + reopened = next(c["check"] for c in CASES if c["name"] == "complete_after_reopen") + assert screen_basis(CheckLevel.SAME_SCREEN, [reopened]) is None + assert screen_basis(CheckLevel.REOPENED, [good]) is None + + +def test_a_run_that_did_not_verify_names_no_basis() -> None: + scope = _scope("same_screen", [CASES[0]["check"]], outcome="COMPLETED_UNVERIFIED") + assert scope["word"] == "RECORDED" and "basis" not in scope + + +def test_standard_accepts_the_screen_check_and_regulated_does_not() -> None: + complete = [CASES[0]["check"]] + standard = _floor(ExecutionProfile.STANDARD) + regulated = _floor(ExecutionProfile.REGULATED) + assert standard == "same_screen" + assert regulated == "separate_session" + assert _scope("same_screen", complete, minimum=standard)["word"] == "VERIFIED" + assert _scope("same_screen", complete, minimum=regulated)["word"] == "RECORDED" + # Under Regulated, a separate-session read still verifies. + stronger = _scope("separate_session", [], minimum=regulated) + assert (stronger["word"], stronger["basis"]) == ("VERIFIED", "separate_session") diff --git a/packages/kernel/src/openadapt_kernel/copilot.py b/packages/kernel/src/openadapt_kernel/copilot.py index ba5e55186a..8d9e68c24e 100644 --- a/packages/kernel/src/openadapt_kernel/copilot.py +++ b/packages/kernel/src/openadapt_kernel/copilot.py @@ -294,6 +294,8 @@ def mint_receipt( ), "observed_at_utc": ob.readback_proof.observed_at_utc, } + if ob.readback_proof.screen_check is not None: + proof_obj["screen_check"] = dict(ob.readback_proof.screen_check) target_sys = ob.target_system if include_plaintext_values else _origin_host_only(ob.target_system) obligations_payload[oid] = { "state": ob.state, diff --git a/packages/kernel/src/openadapt_kernel/ledger.py b/packages/kernel/src/openadapt_kernel/ledger.py index 5d1e3b1f76..4f65c0d4ff 100644 --- a/packages/kernel/src/openadapt_kernel/ledger.py +++ b/packages/kernel/src/openadapt_kernel/ledger.py @@ -59,14 +59,39 @@ def _normalize_literal(value: str) -> str: @dataclass class ReadBackProof: - channel: Literal["fresh_reload", "cross_tab", "api_read", "sql_read", "pdf_stream", "artifact_file"] + channel: Literal[ + "fresh_reload", + "cross_tab", + "api_read", + "sql_read", + "pdf_stream", + "artifact_file", + "post_save_screen", + ] url_or_locator: str cited_substrings: List[str] external_ref: Optional[str] = None observed_at_utc: str = field(default_factory=_utc_now) + #: For ``post_save_screen`` only: what the check saw after the save, as + #: counts and booleans (``fields_intended``, ``fields_read``, + #: ``fields_matched``, ``left_edit_mode``, ``error_shown``, + #: ``banner_only``, ``reopened``). The receipt bridge earns a level from + #: it only when every intended value was read and matched, the form left + #: edit mode and no error is shown. + screen_check: Optional[Dict[str, Any]] = None def is_valid(self) -> bool: - return bool(self.url_or_locator and any(len(s.strip()) >= 2 for s in self.cited_substrings)) + if not (self.url_or_locator and any(len(s.strip()) >= 2 for s in self.cited_substrings)): + return False + if self.channel == "post_save_screen": + # A screen check proves the save only when it is complete. + from openadapt_kernel.receipt_bridge import ( + _screen_check_summary, + _screen_level_and_basis, + ) + + return _screen_level_and_basis(_screen_check_summary(self.screen_check)) is not None + return True @dataclass diff --git a/packages/kernel/src/openadapt_kernel/receipt_bridge.py b/packages/kernel/src/openadapt_kernel/receipt_bridge.py index df0d59f471..7b4bf29fda 100644 --- a/packages/kernel/src/openadapt_kernel/receipt_bridge.py +++ b/packages/kernel/src/openadapt_kernel/receipt_bridge.py @@ -65,6 +65,10 @@ } # Maps kernel ReadBackProof.channel to (check_level, basis) in openadapt_types.check_level. +# A channel not listed here earns no level: the line is not checked, so the +# receipt is never VERIFIED on a channel this bridge does not know. +# ``post_save_screen`` is not listed: it earns its level only from a complete +# screen check (see :func:`_screen_level_and_basis`). _CHANNEL_LEVEL_AND_BASIS: Final[Mapping[str, Tuple[int, str, str]]] = { "fresh_reload": (3, "separate_session", "fresh_reload"), "cross_tab": (3, "separate_session", "separate_session"), @@ -75,6 +79,65 @@ } +#: The channel of a post-save screen check (``openadapt_types`` basis +#: ``post_save_screen``, or ``reopened_record`` after a reopen). +POST_SAVE_SCREEN_CHANNEL: Final = "post_save_screen" +_SCREEN_COUNTS: Final = ("fields_intended", "fields_read", "fields_matched") + + +def _screen_check_summary(raw: Any) -> Optional[Dict[str, Any]]: + """The counts and flags of a proof's ``screen_check``; None when malformed. + + Holds no value, only counts and booleans, so it may go in the receipt. + """ + + if not isinstance(raw, Mapping): + return None + out: Dict[str, Any] = {} + for key in _SCREEN_COUNTS: + value = raw.get(key) + if not isinstance(value, int) or isinstance(value, bool) or value < 0: + return None + out[key] = value + for key in ("left_edit_mode", "error_shown"): + value = raw.get(key) + if value is not None and not isinstance(value, bool): + return None + out[key] = value + for key in ("banner_only", "reopened"): + value = raw.get(key, False) + if not isinstance(value, bool): + return None + out[key] = value + return out + + +def _screen_level_and_basis(summary: Optional[Mapping[str, Any]]) -> Optional[Tuple[int, str, str]]: + """The level a post-save screen check earns, the same rule as + ``openadapt_types.check_level.post_save_screen_basis``. + + Only when every intended value was read on the screen field by field and + matched, the form left edit mode, no error is shown and the sign of the + save is not only a banner. Anything less earns nothing. + """ + + if summary is None: + return None + intended = summary["fields_intended"] + if not ( + intended >= 1 + and summary["fields_read"] == intended + and summary["fields_matched"] == intended + and summary["left_edit_mode"] is True + and summary["error_shown"] is False + and summary["banner_only"] is False + ): + return None + if summary["reopened"]: + return (2, "reopened", "reopened_record") + return (1, "same_screen", "post_save_screen") + + def canonical_json(value: Any) -> str: """Return compact sorted-key UTF-8 JSON matching ``openadapt_types.receipt.canonical_json``.""" return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False) @@ -265,13 +328,16 @@ def _extract_proof_summary(proof: Any) -> Optional[Dict[str, Any]]: if not cited_hashes: return None - return { + summary: Dict[str, Any] = { "channel": channel, "cited_value_sha256": cited_hashes, "external_ref_sha256": resolved_ext_hash, "origin_sha256": origin_hash, "observed_at_utc": valid_ts, } + if channel == POST_SAVE_SCREEN_CHANNEL: + summary["screen_check"] = _screen_check_summary(proof.get("screen_check")) + return summary def kernel_receipt_to_dsse_record( @@ -353,14 +419,18 @@ def kernel_receipt_to_dsse_record( channel = proof_summary["channel"] if proof_summary is not None else "" target_kind = "api" if channel in ("api_read", "sql_read") else "gui" - if state in ("COMMITTED", "EXEMPT") and proof_summary is not None: + level_tuple: Optional[Tuple[int, str, str]] = None + if proof_summary is not None: + if channel == POST_SAVE_SCREEN_CHANNEL: + level_tuple = _screen_level_and_basis(proof_summary.get("screen_check")) + else: + level_tuple = _CHANNEL_LEVEL_AND_BASIS.get(channel) + not_checked: List[str] + if state in ("COMMITTED", "EXEMPT") and level_tuple is not None: check = "confirmed" - strength = "read_back" - not_checked: List[str] = [] + strength = "same_screen" if level_tuple[0] <= 2 else "read_back" + not_checked = [] confirmed_count += 1 - level_tuple = _CHANNEL_LEVEL_AND_BASIS.get( - channel, (3, "separate_session", "fresh_reload") - ) if weakest_proof_level is None or level_tuple[0] < weakest_proof_level[0]: weakest_proof_level = level_tuple obs_ts = proof_summary.get("observed_at_utc") diff --git a/packages/kernel/tests/test_post_save_screen_bridge.py b/packages/kernel/tests/test_post_save_screen_bridge.py new file mode 100644 index 0000000000..321e1985b2 --- /dev/null +++ b/packages/kernel/tests/test_post_save_screen_bridge.py @@ -0,0 +1,122 @@ +"""The kernel's receipt bridge gives a post-save screen check the same word +as every other path. + +The cases live in ``packages/types/tests/vectors/screen-check/cases.json``, +shared with the types, Flow and launcher tests. A complete check (every +intended value read and matched, the form closed, no error, not only a +banner) is ``VERIFIED`` with basis ``post_save_screen`` (``reopened_record`` +after a reopen); anything less is not checked, and the receipt is not +``VERIFIED``. A channel the bridge does not know earns nothing. +""" + +from __future__ import annotations + +import base64 +import copy +import json +from pathlib import Path +from typing import Any, Dict + +import pytest + +from openadapt_kernel import ( + ObligationLedger, + ReadBackProof, + generate_ephemeral_ed25519_keypair, + kernel_receipt_to_dsse_record, + mint_receipt, + verify_unified_dsse_receipt, +) + +_VECTORS = ( + Path(__file__).resolve().parents[2] / "types" / "tests" / "vectors" / "screen-check" / "cases.json" +) +CASES = json.loads(_VECTORS.read_text())["cases"] if _VECTORS.is_file() else [] +COMPLETE = { + "fields_intended": 2, + "fields_read": 2, + "fields_matched": 2, + "left_edit_mode": True, + "error_shown": False, +} + + +def _proof(channel: str, screen_check: Any = None) -> ReadBackProof: + return ReadBackProof( + channel=channel, # type: ignore[arg-type] + url_or_locator="https://records.example.test/r/REC-1", + cited_substrings=["REC-1", "425.00"], + screen_check=screen_check, + ) + + +def _complete_receipt(priv: bytes) -> Dict[str, Any]: + ledger = ObligationLedger(episode_id="ep-screen-001") + ledger.add_obligation("save", "Save the record", target_system="https://records.example.test") + ledger.mark_committed("save", _proof("post_save_screen", dict(COMPLETE))) + assert ledger.finalize("done").outcome == "VERIFIED" + return mint_receipt(ledger, "screen-save-v1", priv) + + +def _with_proof(receipt: Dict[str, Any], **proof_changes: Any) -> Dict[str, Any]: + """The receipt with its one proof changed (and its digest dropped).""" + + out = copy.deepcopy(receipt) + out.pop("sha256", None) + ob = next(iter(out["payload"]["obligations"].values())) + ob["proof"].update(proof_changes) + return out + + +def _scope(receipt: Dict[str, Any], priv: bytes, pub: bytes) -> Dict[str, Any]: + envelope = kernel_receipt_to_dsse_record(receipt, priv, surface="dom") + ok, statement, reason = verify_unified_dsse_receipt(envelope, pub) + assert ok, reason + predicate = statement["predicate"] + scope = predicate["evidence_scope"] + assert scope["not_covered"][:2] == ["server_side_async_effects", "outbound_effects"] + raw = base64.b64decode(envelope["payload"]).decode("utf-8") + assert "REC-1" not in raw # still zero-PHI + return {"outcome": predicate["outcome"], **scope} + + +@pytest.mark.skipif(not CASES, reason="shared vectors not present") +@pytest.mark.parametrize("case", CASES, ids=[c["name"] for c in CASES]) +def test_bridge_matches_the_shared_cases(case: Dict[str, Any]) -> None: + priv, pub = generate_ephemeral_ed25519_keypair() + receipt = _with_proof(_complete_receipt(priv), screen_check=case["check"]) + scope = _scope(receipt, priv, pub) + assert scope["word"] == case["word"] + assert scope.get("basis") == case["basis"] + if case["word"] == "VERIFIED": + assert scope["outcome"] == "VERIFIED" + assert scope["check_level"] == case["level"] + else: + assert scope["outcome"] != "VERIFIED" + + +def test_the_ledger_refuses_an_incomplete_screen_check() -> None: + assert _proof("post_save_screen", dict(COMPLETE)).is_valid() + assert not _proof("post_save_screen", None).is_valid() + assert not _proof("post_save_screen", dict(COMPLETE, error_shown=None)).is_valid() + assert not _proof("post_save_screen", dict(COMPLETE, banner_only=True)).is_valid() + + +def test_an_unknown_channel_earns_nothing() -> None: + priv, pub = generate_ephemeral_ed25519_keypair() + receipt = _with_proof(_complete_receipt(priv), channel="screen_glance") + scope = _scope(receipt, priv, pub) + assert scope["outcome"] != "VERIFIED" + assert scope["word"] == "RECORDED" + + +def test_stronger_channels_keep_their_bases() -> None: + priv, pub = generate_ephemeral_ed25519_keypair() + for channel, level, basis in ( + ("cross_tab", "separate_session", "separate_session"), + ("fresh_reload", "separate_session", "fresh_reload"), + ("api_read", "system_of_record", "system_api"), + ): + receipt = _with_proof(_complete_receipt(priv), channel=channel) + scope = _scope(receipt, priv, pub) + assert (scope["word"], scope["check_level"], scope["basis"]) == ("VERIFIED", level, basis) diff --git a/packages/seal-view/src/lib/receiptRecord.mjs b/packages/seal-view/src/lib/receiptRecord.mjs index 50825b982c..5afef1c51a 100644 --- a/packages/seal-view/src/lib/receiptRecord.mjs +++ b/packages/seal-view/src/lib/receiptRecord.mjs @@ -105,7 +105,10 @@ const EVIDENCE_SCOPE_SCHEMA = 'openadapt.evidence-scope/v1' const CHECK_LEVELS = ['unchecked', 'same_screen', 'reopened', 'separate_session', 'system_of_record', 'counterparty_confirmed'] const OUTCOME_WORDS = ['VERIFIED', 'SHOWN', 'CONFIRMED', 'ATTESTED', 'RECORDED'] const BASIS_LEVEL = { + post_save_screen: 'same_screen', + reopened_record: 'reopened', separate_session: 'separate_session', + fresh_reload: 'separate_session', system_api: 'system_of_record', activity_log: 'system_of_record', db_frame: 'system_of_record', @@ -277,10 +280,12 @@ function validateStatement(s) { if (!ALWAYS_NOT_COVERED.every((k) => es.not_covered.includes(k))) throw new Refusal('malformed', 'not_covered must list server_side_async_effects and outbound_effects') if (es.basis != null && BASIS_LEVEL[es.basis] !== es.check_level) throw new Refusal('malformed', `basis ${es.basis} does not reach ${es.check_level}`) if (es.word === 'VERIFIED') { - if (!['separate_session', 'system_of_record'].includes(es.check_level) || es.basis == null) throw new Refusal('malformed', 'VERIFIED needs level 3 or 4 and a basis') + if (!['same_screen', 'reopened', 'separate_session', 'system_of_record'].includes(es.check_level) || es.basis == null) throw new Refusal('malformed', 'VERIFIED needs level 1 to 4 and a basis') if (es.read_back_at == null && !es.not_covered.includes('read_back_time')) throw new Refusal('malformed', 'VERIFIED needs read_back_at, or says it has none') } if (es.word === 'SHOWN' && !['same_screen', 'reopened'].includes(es.check_level)) throw new Refusal('malformed', 'SHOWN is a level 1 or 2 re-read of the acting screen') + // SHOWN is the older word; receipts that carry it still verify. + if (es.word === 'SHOWN' && es.basis != null) throw new Refusal('malformed', 'an older SHOWN block names no basis') if (es.word === 'CONFIRMED' && es.check_level !== 'counterparty_confirmed') throw new Refusal('malformed', 'CONFIRMED is level 5, the counterparty acknowledgment') if (es.read_back_at != null && es.not_covered.includes('read_back_time')) throw new Refusal('malformed', 'a block with read_back_at covers the read-back time') if (es.recheck_window_s != null && es.read_back_at == null) throw new Refusal('malformed', 'a recheck window needs read_back_at') diff --git a/packages/types/openadapt_types/check_level.py b/packages/types/openadapt_types/check_level.py index 7600808b43..c2d1159cb7 100644 --- a/packages/types/openadapt_types/check_level.py +++ b/packages/types/openadapt_types/check_level.py @@ -38,25 +38,42 @@ --------------------------- A receipt names its outcome with one word, chosen by :func:`outcome_word` -from the level and the basis (who produced the evidence, not its type): - -- ``VERIFIED``: levels 3 and 4 only, always with a basis. Level 3 has basis - ``separate_session`` or ``fresh_reload`` (a new navigation in the acting - session that is proven to have fetched from the server: the request was - sent with the cache bypassed and the response shows no cache, with the - request kept as evidence). A reopen without that proof is level 2, - ``SHOWN``. Level 4 has ``system_api`` (a cache-bypassed, - version-checked API read), ``activity_log`` (the system's own log), - ``db_frame`` (a database read of the record and its frame) or - ``owned_connection`` (a connection the verifier owns, such as its own SQL - or file read). It means "as of the read-back time, the read-back showed - this value", never "persisted". -- ``SHOWN``: levels 1 and 2, the acting screen re-read. +from the level and the basis (who produced the evidence, not its type). The +baseline is the check a careful person does after a save; stronger evidence +is a stronger basis on the same word, not a better word. + +- ``VERIFIED``: levels 1 to 4, always with a basis that reaches exactly that + level. + + - Level 1, ``post_save_screen``: after the save the form left edit mode, + no error is shown, and every intended value was read on the screen, + field by field, and matched. :func:`post_save_screen_basis` decides it + from a :class:`ScreenCheck`. A banner or toast alone never qualifies, and + a field that was not read means no basis. + - Level 2, ``reopened_record``: the same field-by-field check after the + acting session reopened the record. + - Level 3, ``separate_session`` or ``fresh_reload`` (a new navigation in + the acting session that is proven to have fetched from the server: the + request was sent with the cache bypassed and the response shows no + cache, with the request kept as evidence). + - Level 4, ``system_api`` (a cache-bypassed, version-checked API read), + ``activity_log`` (the system's own log), ``db_frame`` (a database read of + the record and its frame) or ``owned_connection`` (a connection the + verifier owns, such as its own SQL or file read). + + It means "as of the read-back time, the read-back showed this value", + never "persisted". A run or policy can require a stronger level (the + ``minimum`` argument); a check below it is not ``VERIFIED``. - ``CONFIRMED``: level 5, the counterparty acknowledged the item. - ``ATTESTED``: an operator confirmed it. - ``RECORDED``: the receipt records the run and claims no check. A check that - did not confirm, or a level 3 or 4 read below the run's required level, is - ``RECORDED``. + did not confirm, a level 1 or 2 read without its basis (a field not read, + no proof the form closed without an error, or only a banner), or a read + below the run's required level is ``RECORDED``. +- ``SHOWN``: the older word for a level 1 or 2 re-read of the acting screen. + No producer writes it any more. Receipts that carry it still parse and + verify; :data:`LEGACY_WORDS` names it so tools can label it as the older + format. ``openadapt_types.evidence_scope`` builds the receipt block that states the level, basis, word and what the evidence did not cover. @@ -67,6 +84,8 @@ from __future__ import annotations +from collections.abc import Mapping +from dataclasses import dataclass from enum import IntEnum from typing import Iterable, Literal, Optional @@ -75,7 +94,11 @@ "Basis", "CheckLevel", "CONFIRMED_WORD", + "INDEPENDENT_LEVELS", + "LEGACY_WORDS", "OUTCOME_WORDS", + "SCREEN_BASES", + "ScreenCheck", "OutcomeWord", "ReadbackLabel", "VERIFIED_LEVELS", @@ -85,6 +108,7 @@ "from_verification_tier", "level_for_basis", "outcome_word", + "post_save_screen_basis", "to_effect_strength", "to_oracle_tier", "to_readback_label", @@ -245,6 +269,8 @@ def to_effect_strength(level: CheckLevel) -> Optional[str]: #: Who produced the evidence for a ``VERIFIED`` read-back. Basis = Literal[ + "post_save_screen", + "reopened_record", "separate_session", "fresh_reload", "system_api", @@ -253,6 +279,8 @@ def to_effect_strength(level: CheckLevel) -> Optional[str]: "owned_connection", ] BASES: tuple[Basis, ...] = ( + "post_save_screen", + "reopened_record", "separate_session", "fresh_reload", "system_api", @@ -260,7 +288,12 @@ def to_effect_strength(level: CheckLevel) -> Optional[str]: "db_frame", "owned_connection", ) +#: The bases a screen check earns (levels 1 and 2). Only +#: :func:`post_save_screen_basis` hands them out. +SCREEN_BASES: tuple[Basis, ...] = ("post_save_screen", "reopened_record") _BASIS_LEVEL: dict[str, CheckLevel] = { + "post_save_screen": CheckLevel.SAME_SCREEN, + "reopened_record": CheckLevel.REOPENED, "separate_session": CheckLevel.SEPARATE_SESSION, "fresh_reload": CheckLevel.SEPARATE_SESSION, "system_api": CheckLevel.SYSTEM_OF_RECORD, @@ -269,7 +302,7 @@ def to_effect_strength(level: CheckLevel) -> Optional[str]: "owned_connection": CheckLevel.SYSTEM_OF_RECORD, } -#: The receipt outcome words. +#: The receipt outcome words. ``SHOWN`` is kept so older receipts parse. OutcomeWord = Literal["VERIFIED", "SHOWN", "CONFIRMED", "ATTESTED", "RECORDED"] VERIFIED_WORD: OutcomeWord = "VERIFIED" CONFIRMED_WORD: OutcomeWord = "CONFIRMED" @@ -280,11 +313,112 @@ def to_effect_strength(level: CheckLevel) -> Optional[str]: "ATTESTED", "RECORDED", ) -#: The only levels a ``VERIFIED`` word may name. +#: Words older receipts carry that no producer writes any more. +LEGACY_WORDS: frozenset[str] = frozenset({"SHOWN"}) +#: The levels a ``VERIFIED`` word may name (each with its basis). VERIFIED_LEVELS: tuple[CheckLevel, ...] = ( + CheckLevel.SAME_SCREEN, + CheckLevel.REOPENED, CheckLevel.SEPARATE_SESSION, CheckLevel.SYSTEM_OF_RECORD, ) +#: The levels whose read does not go through the acting session's screens. +INDEPENDENT_LEVELS: tuple[CheckLevel, ...] = ( + CheckLevel.SEPARATE_SESSION, + CheckLevel.SYSTEM_OF_RECORD, +) + + +@dataclass(frozen=True) +class ScreenCheck: + """What a post-save screen check saw, for one save. + + ``fields_intended``: the values the save meant to write. + ``fields_read``: how many of them were read on the screen, field by + field (not found in a banner or toast). + ``fields_matched``: how many of those read values matched exactly. + ``left_edit_mode``: the form or editor closed after the save (True), + stayed open (False), or nobody looked (None). + ``error_shown``: an error was on the screen (True), none was (False), or + nobody looked (None). + ``banner_only``: the only sign of the save was a banner, toast or + "saved" message. + ``reopened``: the acting session reopened the record before reading. + """ + + fields_intended: int + fields_read: int + fields_matched: int + left_edit_mode: Optional[bool] + error_shown: Optional[bool] + banner_only: bool = False + reopened: bool = False + + @property + def complete(self) -> bool: + """Every intended value was read and matched, with the form closed + and no error shown.""" + + return ( + not isinstance(self.fields_intended, bool) + and isinstance(self.fields_intended, int) + and self.fields_intended >= 1 + and self.fields_read == self.fields_intended + and self.fields_matched == self.fields_intended + and self.left_edit_mode is True + and self.error_shown is False + and self.banner_only is False + ) + + @property + def fields_not_read(self) -> bool: + """Some intended value was not read on the screen.""" + + return not ( + isinstance(self.fields_intended, int) + and self.fields_intended >= 1 + and self.fields_read >= self.fields_intended + ) + + @classmethod + def from_mapping(cls, data: object) -> Optional["ScreenCheck"]: + """The check a ``screen_check`` mapping records; None when it is not + one (a missing or mistyped key).""" + + if not isinstance(data, Mapping): + return None + counts = [data.get(k) for k in ("fields_intended", "fields_read", "fields_matched")] + if not all(isinstance(c, int) and not isinstance(c, bool) and c >= 0 for c in counts): + return None + flags = [data.get(k) for k in ("left_edit_mode", "error_shown")] + if not all(f is None or isinstance(f, bool) for f in flags): + return None + extra = [data.get(k, False) for k in ("banner_only", "reopened")] + if not all(isinstance(f, bool) for f in extra): + return None + return cls( + fields_intended=counts[0], + fields_read=counts[1], + fields_matched=counts[2], + left_edit_mode=flags[0], + error_shown=flags[1], + banner_only=extra[0], + reopened=extra[1], + ) + + +def post_save_screen_basis(check: Optional[ScreenCheck]) -> Optional[Basis]: + """The basis a screen check earns, or None when it earns none. + + ``post_save_screen`` (level 1), or ``reopened_record`` (level 2) when the + acting session reopened the record first, only when :attr:`ScreenCheck.complete` + holds. Anything less (a field not read or not matching, the form still + open, an error, nobody looked, or only a banner) earns no basis. + """ + + if not isinstance(check, ScreenCheck) or not check.complete: + return None + return "reopened_record" if check.reopened else "post_save_screen" def level_for_basis(basis: str) -> CheckLevel: @@ -302,18 +436,20 @@ def outcome_word( *, confirmed: bool = True, attested: bool = False, - minimum: CheckLevel = CheckLevel.SEPARATE_SESSION, + minimum: CheckLevel = CheckLevel.SAME_SCREEN, ) -> OutcomeWord: """The receipt word for one check, the same on every path. ``level`` is the level the check reached, ``basis`` who produced the evidence, ``confirmed`` whether the read-back matched, ``attested`` whether an operator confirmed it, and ``minimum`` the weakest level the - run accepts for ``VERIFIED`` (never below ``separate_session``). + run or its policy accepts for ``VERIFIED`` (``same_screen`` by default; + a regulated policy raises it to ``separate_session``). - A level 3 or 4 check is ``VERIFIED`` only with a basis that reaches that - exact level. A basis that names a different level is a producer bug and - raises ``ValueError``; a missing basis fails closed to ``RECORDED``. + A level 1 to 4 check is ``VERIFIED`` only with a basis that reaches that + exact level, at or above ``minimum``. A basis that names a different + level is a producer bug and raises ``ValueError``; a missing basis fails + closed to ``RECORDED``. This function never returns ``SHOWN``. """ level = CheckLevel(level) @@ -324,10 +460,7 @@ def outcome_word( if level is CheckLevel.COUNTERPARTY_CONFIRMED: return "CONFIRMED" if level in VERIFIED_LEVELS: - floor = max(CheckLevel(minimum), CheckLevel.SEPARATE_SESSION) + floor = max(CheckLevel(minimum), CheckLevel.SAME_SCREEN) if basis is not None and level >= floor: return "VERIFIED" - return "ATTESTED" if attested else "RECORDED" - if level >= CheckLevel.SAME_SCREEN: - return "SHOWN" return "ATTESTED" if attested else "RECORDED" diff --git a/packages/types/openadapt_types/evidence_scope.py b/packages/types/openadapt_types/evidence_scope.py index 7dc517ec78..2ba0cc38c0 100644 --- a/packages/types/openadapt_types/evidence_scope.py +++ b/packages/types/openadapt_types/evidence_scope.py @@ -5,9 +5,12 @@ - ``check_level``: the level on the one ladder (:mod:`openadapt_types.check_level`). -- ``word``: the receipt word (``VERIFIED``, ``SHOWN``, ``CONFIRMED``, - ``ATTESTED`` or ``RECORDED``), from :func:`~openadapt_types.check_level.outcome_word`. -- ``basis``: who produced the evidence. Required for ``VERIFIED``. +- ``word``: the receipt word (``VERIFIED``, ``CONFIRMED``, ``ATTESTED`` or + ``RECORDED``), from :func:`~openadapt_types.check_level.outcome_word`. + Older receipts may carry ``SHOWN`` for a level 1 or 2 re-read; they still + verify, and :func:`legacy_word` names them as the older format. +- ``basis``: who produced the evidence. Required for ``VERIFIED``; at level 1 + it is ``post_save_screen``, the check a careful person does after a save. - ``wire``: the channel the run observed and the protocols it parsed. Watching the wire is not a read-back: it never makes a word stronger. - ``read_back_at``: when the read-back ran. ``VERIFIED`` means "as of this @@ -41,6 +44,7 @@ ) from openadapt_types.check_level import ( + LEGACY_WORDS, Basis, CheckLevel, OutcomeWord, @@ -60,6 +64,7 @@ "WireScope", "build_evidence_scope", "evidence_scope_problem", + "legacy_word", "predicate_evidence_scope_problem", "with_evidence_scope", ] @@ -155,13 +160,16 @@ def _consistent(self) -> "EvidenceScopeV1": raise ValueError(f"basis {self.basis} does not reach {self.check_level}") if self.word == "VERIFIED": if level not in VERIFIED_LEVELS or self.basis is None: - raise ValueError("VERIFIED needs level 3 or 4 and a basis") + raise ValueError("VERIFIED needs level 1 to 4 and a basis") if self.read_back_at is None and "read_back_time" not in self.not_covered: raise ValueError("VERIFIED needs read_back_at, or says it has none") if self.word == "SHOWN" and not ( CheckLevel.SAME_SCREEN <= level <= CheckLevel.REOPENED ): + # The older word, kept so receipts written before 0.25 verify. raise ValueError("SHOWN is a level 1 or 2 re-read of the acting screen") + if self.word == "SHOWN" and self.basis is not None: + raise ValueError("an older SHOWN block names no basis") if self.word == "CONFIRMED" and level is not CheckLevel.COUNTERPARTY_CONFIRMED: raise ValueError("CONFIRMED is level 5, the counterparty's acknowledgment") if self.read_back_at is not None and "read_back_time" in self.not_covered: @@ -186,7 +194,7 @@ def build_evidence_scope( basis: Optional[str] = None, confirmed: bool = True, attested: bool = False, - minimum: CheckLevel = CheckLevel.SEPARATE_SESSION, + minimum: CheckLevel = CheckLevel.SAME_SCREEN, wire_channel: str = "none", protocols_parsed: Iterable[str] = (), read_back_at: Optional[str] = None, @@ -232,6 +240,21 @@ def build_evidence_scope( return block.wire_dict() +def legacy_word(block: object) -> Optional[str]: + """The older word a block carries (``SHOWN``), or None. + + Receipts written before ``post_save_screen`` existed call a re-read of + the acting screen ``SHOWN``. They still verify; a tool that prints the + word says it is the older format. + """ + + if isinstance(block, Mapping): + word = block.get("word") + if isinstance(word, str) and word in LEGACY_WORDS: + return word + return None + + def evidence_scope_problem(block: object) -> Optional[str]: """None when ``block`` is a valid evidence-scope block; else the reason.""" diff --git a/packages/types/tests/test_post_save_screen.py b/packages/types/tests/test_post_save_screen.py new file mode 100644 index 0000000000..247d636097 --- /dev/null +++ b/packages/types/tests/test_post_save_screen.py @@ -0,0 +1,119 @@ +"""The post-save screen check earns VERIFIED, with its evidence in the basis. + +The baseline is what a careful person does after a save: the form closed, no +error is shown, and every value they meant to enter is on the screen. That +check is ``VERIFIED`` with basis ``post_save_screen``; stronger evidence is a +stronger basis on the same word. ``vectors/screen-check/cases.json`` is shared +with the Flow, kernel and launcher tests, so every path gives each check the +same word. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from openadapt_types.check_level import ( + LEGACY_WORDS, + SCREEN_BASES, + CheckLevel, + ScreenCheck, + outcome_word, + post_save_screen_basis, +) +from openadapt_types.evidence_scope import ( + build_evidence_scope, + evidence_scope_problem, + legacy_word, + predicate_evidence_scope_problem, +) + +CASES = json.loads( + (Path(__file__).parent / "vectors" / "screen-check" / "cases.json").read_text() +)["cases"] +T = "2026-11-30T12:00:00Z" + + +@pytest.mark.parametrize("case", CASES, ids=[c["name"] for c in CASES]) +def test_each_case_gets_its_word_and_basis(case) -> None: + check = ScreenCheck.from_mapping(case["check"]) + basis = post_save_screen_basis(check) + level = CheckLevel.from_label(case["level"]) + assert basis == case["basis"] + assert outcome_word(level, basis) == case["word"] + block = build_evidence_scope(level, basis=basis, read_back_at=T) + assert (block["word"], block.get("basis")) == (case["word"], case["basis"]) + # Every receipt still lists what no read-back sees. + assert block["not_covered"][:2] == ["server_side_async_effects", "outbound_effects"] + + +def test_a_banner_alone_never_qualifies() -> None: + banner = ScreenCheck(1, 1, 1, left_edit_mode=True, error_shown=False, banner_only=True) + assert not banner.complete + assert post_save_screen_basis(banner) is None + + +def test_an_unread_field_says_so() -> None: + check = ScreenCheck(3, 2, 2, left_edit_mode=True, error_shown=False) + assert check.fields_not_read + assert not ScreenCheck(3, 3, 2, left_edit_mode=True, error_shown=False).fields_not_read + + +def test_only_the_predicate_hands_out_screen_bases() -> None: + assert SCREEN_BASES == ("post_save_screen", "reopened_record") + assert post_save_screen_basis(None) is None + # A screen basis can't be claimed at another level. + with pytest.raises(ValueError): + outcome_word(CheckLevel.SEPARATE_SESSION, "post_save_screen") + with pytest.raises(ValueError): + outcome_word(CheckLevel.SAME_SCREEN, "reopened_record") + + +@pytest.mark.parametrize( + ("level", "basis"), + [ + (CheckLevel.SAME_SCREEN, "post_save_screen"), + (CheckLevel.REOPENED, "reopened_record"), + (CheckLevel.SEPARATE_SESSION, "separate_session"), + (CheckLevel.SYSTEM_OF_RECORD, "system_api"), + ], +) +def test_one_word_every_basis(level, basis) -> None: + # Stronger evidence is a stronger basis on the same word. + assert outcome_word(level, basis) == "VERIFIED" + + +def test_a_policy_floor_keeps_the_screen_check_from_verified() -> None: + # A regulated policy requires a separate session or the system of record. + regulated = CheckLevel.SEPARATE_SESSION + assert outcome_word(CheckLevel.SAME_SCREEN, "post_save_screen", minimum=regulated) == "RECORDED" + assert outcome_word(CheckLevel.REOPENED, "reopened_record", minimum=regulated) == "RECORDED" + assert outcome_word(CheckLevel.SEPARATE_SESSION, "separate_session", minimum=regulated) == "VERIFIED" + assert outcome_word(CheckLevel.SYSTEM_OF_RECORD, "db_frame", minimum=regulated) == "VERIFIED" + + +def test_shown_is_never_written() -> None: + for level in CheckLevel: + for confirmed in (True, False): + assert outcome_word(level, None, confirmed=confirmed) != "SHOWN" + + +def test_an_older_shown_block_still_verifies_and_is_labelled() -> None: + older = { + "schema": "openadapt.evidence-scope/v1", + "check_level": "same_screen", + "word": "SHOWN", + "wire": {"channel": "none", "protocols_parsed": []}, + "not_covered": ["server_side_async_effects", "outbound_effects", "read_back_time"], + } + assert "SHOWN" in LEGACY_WORDS + assert evidence_scope_problem(older) is None + assert predicate_evidence_scope_problem({"outcome": "UNKNOWN", "evidence_scope": older}) is None + assert legacy_word(older) == "SHOWN" + # SHOWN never meant VERIFIED and never names a basis. + assert predicate_evidence_scope_problem({"outcome": "VERIFIED", "evidence_scope": older}) + assert evidence_scope_problem(dict(older, basis="post_save_screen")) == "evidence_scope" + current = build_evidence_scope(CheckLevel.SAME_SCREEN, basis="post_save_screen", read_back_at=T) + assert legacy_word(current) is None diff --git a/packages/types/tests/vectors/screen-check/cases.json b/packages/types/tests/vectors/screen-check/cases.json new file mode 100644 index 0000000000..239e05ae6a --- /dev/null +++ b/packages/types/tests/vectors/screen-check/cases.json @@ -0,0 +1,15 @@ +{ + "about": "One post-save screen check, the word and basis every path must give it. Read by the types, Flow, kernel and launcher tests.", + "cases": [ + {"name": "complete", "check": {"fields_intended": 3, "fields_read": 3, "fields_matched": 3, "left_edit_mode": true, "error_shown": false}, "level": "same_screen", "word": "VERIFIED", "basis": "post_save_screen"}, + {"name": "complete_after_reopen", "check": {"fields_intended": 2, "fields_read": 2, "fields_matched": 2, "left_edit_mode": true, "error_shown": false, "reopened": true}, "level": "reopened", "word": "VERIFIED", "basis": "reopened_record"}, + {"name": "one_field_not_read", "check": {"fields_intended": 3, "fields_read": 2, "fields_matched": 2, "left_edit_mode": true, "error_shown": false}, "level": "same_screen", "word": "RECORDED", "basis": null}, + {"name": "one_field_differs", "check": {"fields_intended": 3, "fields_read": 3, "fields_matched": 2, "left_edit_mode": true, "error_shown": false}, "level": "same_screen", "word": "RECORDED", "basis": null}, + {"name": "form_still_open", "check": {"fields_intended": 1, "fields_read": 1, "fields_matched": 1, "left_edit_mode": false, "error_shown": false}, "level": "same_screen", "word": "RECORDED", "basis": null}, + {"name": "error_on_screen", "check": {"fields_intended": 1, "fields_read": 1, "fields_matched": 1, "left_edit_mode": true, "error_shown": true}, "level": "same_screen", "word": "RECORDED", "basis": null}, + {"name": "nobody_looked_for_an_error", "check": {"fields_intended": 1, "fields_read": 1, "fields_matched": 1, "left_edit_mode": true, "error_shown": null}, "level": "same_screen", "word": "RECORDED", "basis": null}, + {"name": "banner_only", "check": {"fields_intended": 1, "fields_read": 1, "fields_matched": 1, "left_edit_mode": true, "error_shown": false, "banner_only": true}, "level": "same_screen", "word": "RECORDED", "basis": null}, + {"name": "no_intended_fields", "check": {"fields_intended": 0, "fields_read": 0, "fields_matched": 0, "left_edit_mode": true, "error_shown": false}, "level": "same_screen", "word": "RECORDED", "basis": null}, + {"name": "malformed_count", "check": {"fields_intended": "3", "fields_read": 3, "fields_matched": 3, "left_edit_mode": true, "error_shown": false}, "level": "same_screen", "word": "RECORDED", "basis": null} + ] +} diff --git a/tests/test_post_save_screen_parity.py b/tests/test_post_save_screen_parity.py new file mode 100644 index 0000000000..c9cffdd1a4 --- /dev/null +++ b/tests/test_post_save_screen_parity.py @@ -0,0 +1,164 @@ +"""One word per check, the same on every path. + +Each shared case (``packages/types/tests/vectors/screen-check/cases.json``) +goes through the types ladder, Flow's run receipt block, the kernel's receipt +bridge and ``openadapt.wrap``'s receipt word. All four must give the same word +and basis, and every block must validate against ``openadapt_types``. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +openadapt_types = pytest.importorskip("openadapt_types") +from openadapt_types.check_level import ( # noqa: E402 + CheckLevel, + ScreenCheck, + outcome_word, + post_save_screen_basis, +) +from openadapt_types.evidence_scope import ( # noqa: E402 + build_evidence_scope, + evidence_scope_problem, +) + +ROOT = Path(__file__).resolve().parents[1] +CASES = json.loads( + (ROOT / "packages/types/tests/vectors/screen-check/cases.json").read_text() +)["cases"] +T = "2026-11-30T12:00:00Z" + + +def _types_path(case): + basis = post_save_screen_basis(ScreenCheck.from_mapping(case["check"])) + return outcome_word(CheckLevel.from_label(case["level"]), basis), basis + + +def _flow_path(case): + flow = pytest.importorskip("openadapt_flow.evidence_basis") + scope = flow.evidence_scope_for_run( + {"checked_how": case["level"], "minimum": "same_screen"}, + "VERIFIED", + read_back_at=T, + screen_checks=[case["check"]], + ) + assert evidence_scope_problem(scope) is None + return scope["word"], scope.get("basis") + + +def _kernel_path(case): + kernel = pytest.importorskip("openadapt_kernel") + priv, pub = kernel.generate_ephemeral_ed25519_keypair() + ledger = kernel.ObligationLedger(episode_id="ep-parity") + ledger.add_obligation("save", "Save", target_system="https://records.example.test") + complete = { + "fields_intended": 1, + "fields_read": 1, + "fields_matched": 1, + "left_edit_mode": True, + "error_shown": False, + } + ledger.mark_committed( + "save", + kernel.ReadBackProof( + channel="post_save_screen", + url_or_locator="https://records.example.test/r/1", + cited_substrings=["REC-1"], + screen_check=complete, + ), + ) + ledger.finalize("done") + receipt = kernel.mint_receipt(ledger, "parity-v1", priv) + receipt.pop("sha256", None) + ob = next(iter(receipt["payload"]["obligations"].values())) + ob["proof"]["screen_check"] = case["check"] + envelope = kernel.kernel_receipt_to_dsse_record(receipt, priv) + ok, statement, reason = kernel.verify_unified_dsse_receipt(envelope, pub) + assert ok, reason + scope = statement["predicate"]["evidence_scope"] + assert evidence_scope_problem(scope) is None + return scope["word"], scope.get("basis") + + +def _wrap_path(case): + pytest.importorskip("openadapt_flow.verify_run") + from openadapt_flow.verify_run import receipt_sha256 + + from openadapt.wrap_sdk import WrapOutcome, _build_receipt, wrap_receipt_word + + word, basis = _types_path(case) + level = CheckLevel.from_label(case["level"]) + contract = { + "schema_version": "test", + "evidence_scope": build_evidence_scope(level, basis=basis, read_back_at=T), + } + receipt = _build_receipt( + outcome=WrapOutcome.CONFIRMED, + checked_how=case["level"], + action="save", + request_key="k", + arguments_sha256="0" * 64, + dispatched=True, + contract_receipt_sha256=receipt_sha256(contract), + ) + got = wrap_receipt_word(receipt, contract) + return got, contract["evidence_scope"].get("basis") if got == "VERIFIED" else None + + +@pytest.mark.parametrize("case", CASES, ids=[c["name"] for c in CASES]) +def test_every_path_gives_the_same_word(case) -> None: + expected = (case["word"], case["basis"]) + assert _types_path(case) == expected + assert _flow_path(case) == expected + assert _kernel_path(case) == expected + assert _wrap_path(case) == expected + + +def test_a_wrap_check_alone_never_earns_a_basis() -> None: + from openadapt.wrap_sdk import WrapOutcome, _build_receipt, wrap_receipt_word + + for how in ("same_screen", "reopened", "separate_session", "system_of_record"): + receipt = _build_receipt( + outcome=WrapOutcome.CONFIRMED, + checked_how=how, + action="save", + request_key="k", + arguments_sha256="0" * 64, + dispatched=True, + ) + # A declared checked_how is a claim, not evidence. + assert wrap_receipt_word(receipt) == "RECORDED" + # A contract receipt whose digest does not match earns nothing either. + contract = { + "evidence_scope": build_evidence_scope( + CheckLevel.SYSTEM_OF_RECORD, basis="system_api", read_back_at=T + ) + } + receipt = _build_receipt( + outcome=WrapOutcome.CONFIRMED, + checked_how="system_of_record", + action="save", + request_key="k", + arguments_sha256="0" * 64, + dispatched=True, + contract_receipt_sha256="f" * 64, + ) + assert wrap_receipt_word(receipt, contract) == "RECORDED" + + +def test_verify_prints_the_check_and_labels_shown_as_older() -> None: + from openadapt.receipt_verify import _check_line + + current = build_evidence_scope( + CheckLevel.SAME_SCREEN, basis="post_save_screen", read_back_at=T + ) + assert _check_line(current) == "Check: VERIFIED (level same_screen, basis post_save_screen)" + older = dict( + build_evidence_scope(CheckLevel.SAME_SCREEN, read_back_at=T), word="SHOWN" + ) + assert evidence_scope_problem(older) is None + line = _check_line(older) + assert line.startswith("Check: SHOWN (older format") From caa81b94960cc8fb55c7103d24c459db85518875 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 17:50:26 -0500 Subject: [PATCH 02/17] test(receipts): signed vectors for a post-save-screen VERIFIED receipt and an older SHOWN one --- .../tests/vectors/record-run-v1/generate.py | 17 +++++++++++++ .../older-evidence-scope-shown.json | 24 +++++++++++++++++++ ...valid-evidence-scope-post-save-screen.json | 24 +++++++++++++++++++ 3 files changed, 65 insertions(+) create mode 100644 packages/types/tests/vectors/record-run-v1/older-evidence-scope-shown.json create mode 100644 packages/types/tests/vectors/record-run-v1/valid-evidence-scope-post-save-screen.json diff --git a/packages/types/tests/vectors/record-run-v1/generate.py b/packages/types/tests/vectors/record-run-v1/generate.py index ca63943c75..534766e761 100644 --- a/packages/types/tests/vectors/record-run-v1/generate.py +++ b/packages/types/tests/vectors/record-run-v1/generate.py @@ -242,6 +242,23 @@ def add(name, description, document, expected, openings=None): "A run that states what its evidence covered: a separate-session read, VERIFIED with its basis.", r.sign_statement(scoped, [signer("this_computer")]), {**ok_local, "outcome": "VERIFIED", "disclosed": {}}) + screen = copy.deepcopy(scoped) + screen["predicate"]["evidence_scope"].update( + {"check_level": "same_screen", "basis": "post_save_screen"}) + add("valid-evidence-scope-post-save-screen", + "A run checked the way a careful person checks: after the save the form closed, no error " + "showed and every value was read on the screen. VERIFIED with basis post_save_screen.", + r.sign_statement(screen, [signer("this_computer")]), + {**ok_local, "outcome": "VERIFIED", "disclosed": {}}) + older = statement("UNKNOWN") + older["predicate"]["evidence_scope"] = copy.deepcopy(scoped["predicate"]["evidence_scope"]) + older["predicate"]["evidence_scope"].update({"check_level": "same_screen", "word": "SHOWN"}) + del older["predicate"]["evidence_scope"]["basis"] + add("older-evidence-scope-shown", + "An older receipt whose evidence scope says SHOWN (the acting screen re-read, no basis) " + "on an UNKNOWN run: still verifies; tools label the word as the older format.", + _signed_raw(older), + {**ok_local, "outcome": "UNKNOWN", "disclosed": {}}) shown = copy.deepcopy(scoped) shown["predicate"]["evidence_scope"].update( {"check_level": "same_screen", "word": "SHOWN"}) diff --git a/packages/types/tests/vectors/record-run-v1/older-evidence-scope-shown.json b/packages/types/tests/vectors/record-run-v1/older-evidence-scope-shown.json new file mode 100644 index 0000000000..d13f30c4ca --- /dev/null +++ b/packages/types/tests/vectors/record-run-v1/older-evidence-scope-shown.json @@ -0,0 +1,24 @@ +{ + "description": "An older receipt whose evidence scope says SHOWN (the acting screen re-read, no basis) on an UNKNOWN run: still verifies; tools label the word as the older format.", + "document": { + "payload": "eyJfdHlwZSI6Imh0dHBzOi8vaW4tdG90by5pby9TdGF0ZW1lbnQvdjEiLCJwcmVkaWNhdGUiOnsiY2hlY2tzIjp7ImF1dGhvcml6YXRpb24iOnsiY29uZmlybWVkIjowLCJyZXF1aXJlZCI6MH0sImVmZmVjdHMiOnsiY29uZmlybWVkIjoxLCJyZXF1aXJlZCI6Mn0sImlkZW50aXR5Ijp7ImNvbmZpcm1lZCI6NSwicmVxdWlyZWQiOjV9LCJsaW5lc19jb25maXJtZWQiOjEsImxpbmVzX25vdF9jaGVja2VkIjowLCJsaW5lc19yZWZ1dGVkIjoxLCJwb3N0Y29uZGl0aW9ucyI6eyJjb25maXJtZWQiOjMsInJlcXVpcmVkIjozfX0sImRpc2Nsb3N1cmUiOnsiY29tbWl0bWVudHMiOnt9LCJ2ZXJzaW9uIjoib3BlbmFkYXB0LnB1YmxpYy1kaXNjbG9zdXJlL3YxIn0sImV2aWRlbmNlX3Njb3BlIjp7ImNoZWNrX2xldmVsIjoic2FtZV9zY3JlZW4iLCJub3RfY292ZXJlZCI6WyJzZXJ2ZXJfc2lkZV9hc3luY19lZmZlY3RzIiwib3V0Ym91bmRfZWZmZWN0cyIsImNoYW5nZXNfYWZ0ZXJfcmVhZF9iYWNrIiwicmVhZF9iYWNrX3RpbWUiXSwic2NoZW1hIjoib3BlbmFkYXB0LmV2aWRlbmNlLXNjb3BlL3YxIiwid2lyZSI6eyJjaGFubmVsIjoibm9uZSIsInByb3RvY29sc19wYXJzZWQiOltdfSwid29yZCI6IlNIT1dOIn0sImxpbmVzIjpbeyJjaGVjayI6ImNvbmZpcm1lZCIsIm5vdF9jaGVja2VkIjpbXSwib3BlcmF0aW9uIjoid3JpdGUiLCJzdGVwIjoyLCJzdHJlbmd0aCI6InJlYWRfYmFjayIsInRhcmdldF9raW5kIjoiZ3VpIn0seyJjaGVjayI6InJlZnV0ZWQiLCJub3RfY2hlY2tlZCI6WyJmaWVsZF92YWx1ZXMiXSwib3BlcmF0aW9uIjoiaXJyZXZlcnNpYmxlX3dyaXRlIiwic3RlcCI6NCwic3RyZW5ndGgiOiJyZWFkX2JhY2siLCJ0YXJnZXRfa2luZCI6Imd1aSJ9XSwibW9kZWxfY2FsbHMiOjAsIm91dGNvbWUiOiJVTktOT1dOIiwicHJvZ3JhbSI6eyJpZCI6InByb2ctNWJiMjFhYTBmMmU2YWMzMiIsInZlcnNpb25fc2hhMjU2IjoiMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMiJ9LCJyZWFzb25fY29kZSI6ImhhbHRlZCIsInN0YXJ0ZWRfaG91ciI6IjIwMjYtMTEtMjBUMjM6MDA6MDBaIiwic3RlcHMiOnsib2siOjQsInRvdGFsIjo1fX0sInByZWRpY2F0ZVR5cGUiOiJodHRwczovL29wZW5hZGFwdC5haS9yZWNvcmQvcnVuL3YxIiwic3ViamVjdCI6W3siZGlnZXN0Ijp7InNoYTI1NiI6IjExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTEifSwibmFtZSI6InJlcG9ydC5qc29uIn0seyJkaWdlc3QiOnsic2hhMjU2IjoiMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMiJ9LCJuYW1lIjoiYnVuZGxlIn1dfQ==", + "payloadType": "application/vnd.in-toto+json", + "signatures": [ + { + "keyid": "seal-ed25519-b7a5ba90250d87f2", + "sig": "9LZHM5wgBJDUtdfLqifhe+hwFdJYlTXeMsTmmVzu9VlMLD/2gIKWn1awDcvsWlPL90wU3rmwId7U6OBjWrHFAQ==" + } + ] + }, + "expected": { + "demo": false, + "disclosed": {}, + "ok": true, + "outcome": "UNKNOWN", + "reason": null, + "signer_lines": [ + "Signed by this computer" + ] + }, + "registry": "registry.json" +} diff --git a/packages/types/tests/vectors/record-run-v1/valid-evidence-scope-post-save-screen.json b/packages/types/tests/vectors/record-run-v1/valid-evidence-scope-post-save-screen.json new file mode 100644 index 0000000000..6fe4ce9faa --- /dev/null +++ b/packages/types/tests/vectors/record-run-v1/valid-evidence-scope-post-save-screen.json @@ -0,0 +1,24 @@ +{ + "description": "A run checked the way a careful person checks: after the save the form closed, no error showed and every value was read on the screen. VERIFIED with basis post_save_screen.", + "document": { + "payload": "eyJfdHlwZSI6Imh0dHBzOi8vaW4tdG90by5pby9TdGF0ZW1lbnQvdjEiLCJwcmVkaWNhdGUiOnsiY2hlY2tzIjp7ImF1dGhvcml6YXRpb24iOnsiY29uZmlybWVkIjowLCJyZXF1aXJlZCI6MH0sImVmZmVjdHMiOnsiY29uZmlybWVkIjoyLCJyZXF1aXJlZCI6Mn0sImlkZW50aXR5Ijp7ImNvbmZpcm1lZCI6NSwicmVxdWlyZWQiOjV9LCJsaW5lc19jb25maXJtZWQiOjIsImxpbmVzX25vdF9jaGVja2VkIjowLCJsaW5lc19yZWZ1dGVkIjowLCJwb3N0Y29uZGl0aW9ucyI6eyJjb25maXJtZWQiOjMsInJlcXVpcmVkIjozfX0sImRpc2Nsb3N1cmUiOnsiY29tbWl0bWVudHMiOnt9LCJ2ZXJzaW9uIjoib3BlbmFkYXB0LnB1YmxpYy1kaXNjbG9zdXJlL3YxIn0sImV2aWRlbmNlX3Njb3BlIjp7ImJhc2lzIjoicG9zdF9zYXZlX3NjcmVlbiIsImNoZWNrX2xldmVsIjoic2FtZV9zY3JlZW4iLCJub3RfY292ZXJlZCI6WyJzZXJ2ZXJfc2lkZV9hc3luY19lZmZlY3RzIiwib3V0Ym91bmRfZWZmZWN0cyIsImNoYW5nZXNfYWZ0ZXJfcmVhZF9iYWNrIiwicmVhZF9iYWNrX3RpbWUiXSwic2NoZW1hIjoib3BlbmFkYXB0LmV2aWRlbmNlLXNjb3BlL3YxIiwid2lyZSI6eyJjaGFubmVsIjoibm9uZSIsInByb3RvY29sc19wYXJzZWQiOltdfSwid29yZCI6IlZFUklGSUVEIn0sImxpbmVzIjpbeyJjaGVjayI6ImNvbmZpcm1lZCIsIm5vdF9jaGVja2VkIjpbXSwib3BlcmF0aW9uIjoid3JpdGUiLCJzdGVwIjoyLCJzdHJlbmd0aCI6InJlYWRfYmFjayIsInRhcmdldF9raW5kIjoiZ3VpIn0seyJjaGVjayI6ImNvbmZpcm1lZCIsIm5vdF9jaGVja2VkIjpbImZpZWxkX3ZhbHVlcyJdLCJvcGVyYXRpb24iOiJpcnJldmVyc2libGVfd3JpdGUiLCJzdGVwIjo0LCJzdHJlbmd0aCI6InJlYWRfYmFjayIsInRhcmdldF9raW5kIjoiZ3VpIn1dLCJtb2RlbF9jYWxscyI6MCwib3V0Y29tZSI6IlZFUklGSUVEIiwicHJvZ3JhbSI6eyJpZCI6InByb2ctNWJiMjFhYTBmMmU2YWMzMiIsInZlcnNpb25fc2hhMjU2IjoiMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMiJ9LCJyZWFzb25fY29kZSI6InZlcmlmaWVkIiwic3RhcnRlZF9ob3VyIjoiMjAyNi0xMS0yMFQyMzowMDowMFoiLCJzdGVwcyI6eyJvayI6NSwidG90YWwiOjV9fSwicHJlZGljYXRlVHlwZSI6Imh0dHBzOi8vb3BlbmFkYXB0LmFpL3JlY29yZC9ydW4vdjEiLCJzdWJqZWN0IjpbeyJkaWdlc3QiOnsic2hhMjU2IjoiMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMSJ9LCJuYW1lIjoicmVwb3J0Lmpzb24ifSx7ImRpZ2VzdCI6eyJzaGEyNTYiOiIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyIn0sIm5hbWUiOiJidW5kbGUifV19", + "payloadType": "application/vnd.in-toto+json", + "signatures": [ + { + "keyid": "seal-ed25519-b7a5ba90250d87f2", + "sig": "Ths6W6pYCrKEi0oaXeyEy25pXqi2GFCtyNVUlDsomsc74jHgefZYfr+jfYf003zXungwhAL8uWX6pvxFXYR2AQ==" + } + ] + }, + "expected": { + "demo": false, + "disclosed": {}, + "ok": true, + "outcome": "VERIFIED", + "reason": null, + "signer_lines": [ + "Signed by this computer" + ] + }, + "registry": "registry.json" +} From ddd42a148645ae3f3ddf35e5ff1d7df7b95a10b5 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 17:53:48 -0500 Subject: [PATCH 03/17] style: ruff format and mypy fixes for the post-save screen basis --- openadapt/receipt_verify.py | 3 +- openadapt/wrap_sdk.py | 5 +- .../flow/openadapt_flow/evidence_basis.py | 8 ++- packages/flow/tests/test_one_ladder.py | 6 +-- packages/flow/tests/test_post_save_screen.py | 4 +- .../src/openadapt_kernel/receipt_bridge.py | 6 ++- .../tests/test_post_save_screen_bridge.py | 7 ++- packages/types/openadapt_types/check_level.py | 27 ++++++---- packages/types/tests/test_post_save_screen.py | 54 +++++++++++++++---- tests/test_post_save_screen_parity.py | 5 +- 10 files changed, 93 insertions(+), 32 deletions(-) diff --git a/openadapt/receipt_verify.py b/openadapt/receipt_verify.py index b3a9546d31..c648587dcf 100644 --- a/openadapt/receipt_verify.py +++ b/openadapt/receipt_verify.py @@ -95,8 +95,7 @@ def _check_line(scope: dict[str, Any]) -> str: level = _one_line(scope.get("check_level")) if legacy_word(scope) is not None: return ( - f"Check: {word} ({OLDER}: the acting screen was read again; " - f"level {level})" + f"Check: {word} ({OLDER}: the acting screen was read again; level {level})" ) basis = scope.get("basis") return f"Check: {word} (level {level}" + ( diff --git a/openadapt/wrap_sdk.py b/openadapt/wrap_sdk.py index ab5367f99d..ee04275c94 100644 --- a/openadapt/wrap_sdk.py +++ b/openadapt/wrap_sdk.py @@ -648,7 +648,10 @@ def wrap_receipt_word( """ data = receipt.to_dict() if isinstance(receipt, WrapReceipt) else receipt - if not isinstance(data, Mapping) or data.get("outcome") != WrapOutcome.CONFIRMED.value: + if ( + not isinstance(data, Mapping) + or data.get("outcome") != WrapOutcome.CONFIRMED.value + ): return "RECORDED" digest = data.get("contract_receipt_sha256") if not isinstance(contract_receipt, Mapping) or not isinstance(digest, str): diff --git a/packages/flow/openadapt_flow/evidence_basis.py b/packages/flow/openadapt_flow/evidence_basis.py index b199aac03c..490f2d1beb 100644 --- a/packages/flow/openadapt_flow/evidence_basis.py +++ b/packages/flow/openadapt_flow/evidence_basis.py @@ -105,7 +105,9 @@ def screen_basis(level: CheckLevel, checks: Sequence[Any]) -> Optional[Basis]: return None bases = set() for item in checks: - check = item if isinstance(item, ScreenCheck) else ScreenCheck.from_mapping(item) + check = ( + item if isinstance(item, ScreenCheck) else ScreenCheck.from_mapping(item) + ) basis = post_save_screen_basis(check) if basis is None: return None @@ -180,7 +182,9 @@ def _any_field_not_read(checks: Sequence[Any]) -> bool: except ImportError: # pragma: no cover - older openadapt-types return False for item in checks: - check = item if isinstance(item, ScreenCheck) else ScreenCheck.from_mapping(item) + check = ( + item if isinstance(item, ScreenCheck) else ScreenCheck.from_mapping(item) + ) if check is None or check.fields_not_read: return True return False diff --git a/packages/flow/tests/test_one_ladder.py b/packages/flow/tests/test_one_ladder.py index a285912eb3..7327f70775 100644 --- a/packages/flow/tests/test_one_ladder.py +++ b/packages/flow/tests/test_one_ladder.py @@ -16,7 +16,6 @@ INDEPENDENT_LEVELS, VERIFIED_LEVELS, CheckLevel, - ScreenCheck, from_effect_strength, level_for_basis, outcome_word, @@ -35,7 +34,6 @@ basis_for_tier, evidence_scope_for_run, level_and_basis, - screen_basis, ) from openadapt_flow.readback_ladder import summarize_report, tier_floor from openadapt_flow.tx.api_readback import ( @@ -134,7 +132,9 @@ def test_a_raised_minimum_keeps_a_separate_session_read_from_verified() -> None: == "RECORDED" ) assert ( - outcome_word(CheckLevel.SAME_SCREEN, "post_save_screen", minimum=CheckLevel.SAME_SCREEN) + outcome_word( + CheckLevel.SAME_SCREEN, "post_save_screen", minimum=CheckLevel.SAME_SCREEN + ) == "VERIFIED" ) diff --git a/packages/flow/tests/test_post_save_screen.py b/packages/flow/tests/test_post_save_screen.py index 6592f167fe..554d554d41 100644 --- a/packages/flow/tests/test_post_save_screen.py +++ b/packages/flow/tests/test_post_save_screen.py @@ -38,7 +38,9 @@ def _floor(profile: ExecutionProfile) -> str: def _scope(level: str, checks, minimum: str = "same_screen", outcome: str = "VERIFIED"): readback = {"checked_how": level, "minimum": minimum} - return evidence_scope_for_run(readback, outcome, read_back_at=T, screen_checks=checks) + return evidence_scope_for_run( + readback, outcome, read_back_at=T, screen_checks=checks + ) @pytest.mark.parametrize("case", CASES, ids=[c["name"] for c in CASES]) diff --git a/packages/kernel/src/openadapt_kernel/receipt_bridge.py b/packages/kernel/src/openadapt_kernel/receipt_bridge.py index 7b4bf29fda..5800244f59 100644 --- a/packages/kernel/src/openadapt_kernel/receipt_bridge.py +++ b/packages/kernel/src/openadapt_kernel/receipt_bridge.py @@ -426,7 +426,11 @@ def kernel_receipt_to_dsse_record( else: level_tuple = _CHANNEL_LEVEL_AND_BASIS.get(channel) not_checked: List[str] - if state in ("COMMITTED", "EXEMPT") and level_tuple is not None: + if ( + state in ("COMMITTED", "EXEMPT") + and level_tuple is not None + and proof_summary is not None + ): check = "confirmed" strength = "same_screen" if level_tuple[0] <= 2 else "read_back" not_checked = [] diff --git a/packages/kernel/tests/test_post_save_screen_bridge.py b/packages/kernel/tests/test_post_save_screen_bridge.py index 321e1985b2..83d1f59fb7 100644 --- a/packages/kernel/tests/test_post_save_screen_bridge.py +++ b/packages/kernel/tests/test_post_save_screen_bridge.py @@ -29,7 +29,12 @@ ) _VECTORS = ( - Path(__file__).resolve().parents[2] / "types" / "tests" / "vectors" / "screen-check" / "cases.json" + Path(__file__).resolve().parents[2] + / "types" + / "tests" + / "vectors" + / "screen-check" + / "cases.json" ) CASES = json.loads(_VECTORS.read_text())["cases"] if _VECTORS.is_file() else [] COMPLETE = { diff --git a/packages/types/openadapt_types/check_level.py b/packages/types/openadapt_types/check_level.py index c2d1159cb7..1241bfb294 100644 --- a/packages/types/openadapt_types/check_level.py +++ b/packages/types/openadapt_types/check_level.py @@ -387,15 +387,24 @@ def from_mapping(cls, data: object) -> Optional["ScreenCheck"]: if not isinstance(data, Mapping): return None - counts = [data.get(k) for k in ("fields_intended", "fields_read", "fields_matched")] - if not all(isinstance(c, int) and not isinstance(c, bool) and c >= 0 for c in counts): - return None - flags = [data.get(k) for k in ("left_edit_mode", "error_shown")] - if not all(f is None or isinstance(f, bool) for f in flags): - return None - extra = [data.get(k, False) for k in ("banner_only", "reopened")] - if not all(isinstance(f, bool) for f in extra): - return None + counts: list[int] = [] + for key in ("fields_intended", "fields_read", "fields_matched"): + value = data.get(key) + if not isinstance(value, int) or isinstance(value, bool) or value < 0: + return None + counts.append(value) + flags: list[Optional[bool]] = [] + for key in ("left_edit_mode", "error_shown"): + flag = data.get(key) + if flag is not None and not isinstance(flag, bool): + return None + flags.append(flag) + extra: list[bool] = [] + for key in ("banner_only", "reopened"): + mark = data.get(key, False) + if not isinstance(mark, bool): + return None + extra.append(mark) return cls( fields_intended=counts[0], fields_read=counts[1], diff --git a/packages/types/tests/test_post_save_screen.py b/packages/types/tests/test_post_save_screen.py index 247d636097..0c7c70bfd5 100644 --- a/packages/types/tests/test_post_save_screen.py +++ b/packages/types/tests/test_post_save_screen.py @@ -50,7 +50,9 @@ def test_each_case_gets_its_word_and_basis(case) -> None: def test_a_banner_alone_never_qualifies() -> None: - banner = ScreenCheck(1, 1, 1, left_edit_mode=True, error_shown=False, banner_only=True) + banner = ScreenCheck( + 1, 1, 1, left_edit_mode=True, error_shown=False, banner_only=True + ) assert not banner.complete assert post_save_screen_basis(banner) is None @@ -58,7 +60,9 @@ def test_a_banner_alone_never_qualifies() -> None: def test_an_unread_field_says_so() -> None: check = ScreenCheck(3, 2, 2, left_edit_mode=True, error_shown=False) assert check.fields_not_read - assert not ScreenCheck(3, 3, 2, left_edit_mode=True, error_shown=False).fields_not_read + assert not ScreenCheck( + 3, 3, 2, left_edit_mode=True, error_shown=False + ).fields_not_read def test_only_the_predicate_hands_out_screen_bases() -> None: @@ -88,10 +92,22 @@ def test_one_word_every_basis(level, basis) -> None: def test_a_policy_floor_keeps_the_screen_check_from_verified() -> None: # A regulated policy requires a separate session or the system of record. regulated = CheckLevel.SEPARATE_SESSION - assert outcome_word(CheckLevel.SAME_SCREEN, "post_save_screen", minimum=regulated) == "RECORDED" - assert outcome_word(CheckLevel.REOPENED, "reopened_record", minimum=regulated) == "RECORDED" - assert outcome_word(CheckLevel.SEPARATE_SESSION, "separate_session", minimum=regulated) == "VERIFIED" - assert outcome_word(CheckLevel.SYSTEM_OF_RECORD, "db_frame", minimum=regulated) == "VERIFIED" + assert ( + outcome_word(CheckLevel.SAME_SCREEN, "post_save_screen", minimum=regulated) + == "RECORDED" + ) + assert ( + outcome_word(CheckLevel.REOPENED, "reopened_record", minimum=regulated) + == "RECORDED" + ) + assert ( + outcome_word(CheckLevel.SEPARATE_SESSION, "separate_session", minimum=regulated) + == "VERIFIED" + ) + assert ( + outcome_word(CheckLevel.SYSTEM_OF_RECORD, "db_frame", minimum=regulated) + == "VERIFIED" + ) def test_shown_is_never_written() -> None: @@ -106,14 +122,30 @@ def test_an_older_shown_block_still_verifies_and_is_labelled() -> None: "check_level": "same_screen", "word": "SHOWN", "wire": {"channel": "none", "protocols_parsed": []}, - "not_covered": ["server_side_async_effects", "outbound_effects", "read_back_time"], + "not_covered": [ + "server_side_async_effects", + "outbound_effects", + "read_back_time", + ], } assert "SHOWN" in LEGACY_WORDS assert evidence_scope_problem(older) is None - assert predicate_evidence_scope_problem({"outcome": "UNKNOWN", "evidence_scope": older}) is None + assert ( + predicate_evidence_scope_problem( + {"outcome": "UNKNOWN", "evidence_scope": older} + ) + is None + ) assert legacy_word(older) == "SHOWN" # SHOWN never meant VERIFIED and never names a basis. - assert predicate_evidence_scope_problem({"outcome": "VERIFIED", "evidence_scope": older}) - assert evidence_scope_problem(dict(older, basis="post_save_screen")) == "evidence_scope" - current = build_evidence_scope(CheckLevel.SAME_SCREEN, basis="post_save_screen", read_back_at=T) + assert predicate_evidence_scope_problem( + {"outcome": "VERIFIED", "evidence_scope": older} + ) + assert ( + evidence_scope_problem(dict(older, basis="post_save_screen")) + == "evidence_scope" + ) + current = build_evidence_scope( + CheckLevel.SAME_SCREEN, basis="post_save_screen", read_back_at=T + ) assert legacy_word(current) is None diff --git a/tests/test_post_save_screen_parity.py b/tests/test_post_save_screen_parity.py index c9cffdd1a4..958a53ba8f 100644 --- a/tests/test_post_save_screen_parity.py +++ b/tests/test_post_save_screen_parity.py @@ -155,7 +155,10 @@ def test_verify_prints_the_check_and_labels_shown_as_older() -> None: current = build_evidence_scope( CheckLevel.SAME_SCREEN, basis="post_save_screen", read_back_at=T ) - assert _check_line(current) == "Check: VERIFIED (level same_screen, basis post_save_screen)" + assert ( + _check_line(current) + == "Check: VERIFIED (level same_screen, basis post_save_screen)" + ) older = dict( build_evidence_scope(CheckLevel.SAME_SCREEN, read_back_at=T), word="SHOWN" ) From aaac197765bec38ac54684e5ab3d183a5d58bb1b Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 17:56:47 -0500 Subject: [PATCH 04/17] docs(receipts): careful-operator baseline in THREAT_MODEL, receipt docs and capability row --- ...eceipt-word-per-check-the-same-on-every.md | 2 +- packages/flow/docs/EFFECT_LOCATION.md | 5 ++- packages/flow/docs/READBACK_LADDER.md | 2 + packages/flow/docs/RECEIPTS.md | 35 +++++++++++----- packages/flow/docs/THREAT_MODEL.md | 41 +++++++++++++++---- packages/kernel/CHANGELOG.md | 14 +++++++ packages/seal-view/CHANGELOG.md | 5 +++ packages/types/CHANGELOG.md | 22 ++++++++++ 8 files changed, 105 insertions(+), 21 deletions(-) diff --git a/capabilities/04-the-core-a-checked-entry-every-time/0132-one-receipt-word-per-check-the-same-on-every.md b/capabilities/04-the-core-a-checked-entry-every-time/0132-one-receipt-word-per-check-the-same-on-every.md index d4682fe469..9fc06a53b5 100644 --- a/capabilities/04-the-core-a-checked-entry-every-time/0132-one-receipt-word-per-check-the-same-on-every.md +++ b/capabilities/04-the-core-a-checked-entry-every-time/0132-one-receipt-word-per-check-the-same-on-every.md @@ -1 +1 @@ -| One receipt word per check, the same on every path: `VERIFIED` only at level 3 (a separate session) or 4 (the system of record), always with the basis that produced the evidence (`separate_session`, `system_api`, `activity_log`, `db_frame` or `owned_connection`); `SHOWN` for an acting-screen re-read, `CONFIRMED` for the counterparty, `ATTESTED` for an operator and `RECORDED` for the rest. `VERIFIED` means "as of the read-back time the read-back showed this value", not "persisted". Run receipts (`record/run/v1`, an additive optional field), `verify-run` receipts and `tx` receipts carry an evidence-scope block: level, basis, word, the wire channel watched, the read-back time, the recheck window, and what it did not cover (always server-side async and outbound effects; a run receipt says it has no per-read time). A run receipt never says `VERIFIED` below level 3. Receipts without the block still verify. A `verify-run` contract with `minimum_effect_strength: independent_session` now verifies on a separate-session read | On main | Unit tests (parity across the runtime report, `verify-run`, `tx` and Execute v1; fake verifiers) | `openadapt_types/check_level.py`, `openadapt_types/evidence_scope.py`, `openadapt_flow/evidence_basis.py` | +| One receipt word per check, the same on every path: `VERIFIED` always names the basis that earned it. The baseline is the check a careful person does after a save, basis `post_save_screen` (level 1): the form left edit mode, no error is shown, and every intended value was read on the screen, field by field, and matched; a banner or toast alone never earns it, and a value that was not read means `RECORDED`. The same check after reopening the record is `reopened_record` (level 2); stronger evidence is a stronger basis on the same word (`separate_session` or `fresh_reload` at level 3; `system_api`, `activity_log`, `db_frame` or `owned_connection` at level 4). A run or policy can require a stronger level: under `Regulated` a screen check is not `VERIFIED`. `CONFIRMED` is the counterparty, `ATTESTED` an operator and `RECORDED` the rest. `VERIFIED` means "as of the read-back time the read-back showed this value", not "persisted". Run receipts (`record/run/v1`, an additive optional field), `verify-run` receipts, `tx` receipts and the kernel's receipt bridge carry an evidence-scope block: level, basis, word, the wire channel watched, the read-back time, the recheck window, and what it did not cover (always server-side async and outbound effects). `openadapt.wrap` takes its word from the Contract's read-back receipt; a declared `checked_how` alone is `RECORDED`. The runtime's run report does not yet record whether the form left edit mode or showed an error, so a run checked only on its screen gets a `RECORDED` receipt. Older receipts that say `SHOWN` still verify and are labelled as the older format. Receipts without the block still verify | On main | Unit tests (shared cases across the types ladder, the run receipt block, the kernel bridge and `openadapt.wrap`; signed `record/run/v1` vectors checked by the Python and JavaScript verifiers; fake verifiers) | `openadapt_types/check_level.py`, `openadapt_types/evidence_scope.py`, `openadapt_flow/evidence_basis.py`, `openadapt_kernel/receipt_bridge.py`, `openadapt/wrap_sdk.py` | diff --git a/packages/flow/docs/EFFECT_LOCATION.md b/packages/flow/docs/EFFECT_LOCATION.md index 6f3d0478d6..f5eaaa89a5 100644 --- a/packages/flow/docs/EFFECT_LOCATION.md +++ b/packages/flow/docs/EFFECT_LOCATION.md @@ -80,8 +80,9 @@ The check level comes from the start condition the adapter achieved: The receipt word comes from `openadapt_types.check_level.outcome_word`, so this package never decides what `VERIFIED` means. A same-screen read or a -fresh navigation without the reload proof is `SHOWN`; a proven fresh reload -is `VERIFIED`. A new session is `VERIFIED`. Another channel is +fresh navigation without the reload proof earns no basis here, because a +reading does not record whether the form left edit mode or an error was +shown, so it is `RECORDED`; a proven fresh reload is `VERIFIED`. A new session is `VERIFIED`. Another channel is `VERIFIED` only with a basis, otherwise `RECORDED`. Until `outcome_word` is on main, the word is `None`. diff --git a/packages/flow/docs/READBACK_LADDER.md b/packages/flow/docs/READBACK_LADDER.md index b8600048a8..3daddc11b9 100644 --- a/packages/flow/docs/READBACK_LADDER.md +++ b/packages/flow/docs/READBACK_LADDER.md @@ -23,6 +23,8 @@ Each production execution profile sets a floor for `VERIFIED`: When a run's saves are all confirmed, but at least one was checked below the active floor (for example `same_screen` or `reopened` under `Regulated`, or below a workflow's `minimum_readback`), the run ends `COMPLETED_UNVERIFIED`. The report sets `readback.below_minimum`, and the agent says `not_sure_if_saved` with reason `checked_below_minimum`: a person checks the record. +The run receipt's word follows `openadapt_types.check_level`. A run checked on the acting screen is `VERIFIED` on its receipt only with basis `post_save_screen` (or `reopened_record` after a reopen), which needs a per-save record that the form left edit mode, no error was shown, and every intended value was read and matched. `report.json` does not carry that record yet, so the receipt for such a run says `RECORDED` ([RECEIPTS.md](RECEIPTS.md)). + A workflow or `verify.yaml` can declare `minimum_readback` (`same_screen`, `reopened`, `separate_session`, or `system_of_record`) to raise a profile's floor; it never lowers `Regulated` below `separate_session`. `qualify` enforces the same minimum before the workflow ships (`minimum_readback` in `verify.yaml`, or the older `minimum_effect_strength`), and a workflow that sets a stricter minimum refuses to run with a weaker verifier. ## How Flow reopens a record without configuration diff --git a/packages/flow/docs/RECEIPTS.md b/packages/flow/docs/RECEIPTS.md index a72e8cb94c..0a5418aaa8 100644 --- a/packages/flow/docs/RECEIPTS.md +++ b/packages/flow/docs/RECEIPTS.md @@ -34,16 +34,31 @@ changes the run's exit code and calls no model. - a disclosure map: salted commitments to the program name, Flow version and run id; - an evidence scope (`evidence_scope`, `openadapt.evidence-scope/v1`): the - check level the weakest save reached, the receipt word (`VERIFIED` only at - level 3, a separate session, or level 4, the system of record, and then - with its basis; otherwise `SHOWN` or `RECORDED`), the wire the run watched, - and what the evidence did not cover. It always lists server-side async and - outbound effects, and, because a run report has no per-read time yet, - `read_back_time`. `VERIFIED` means the read-back showed the value when it - ran, not that it persisted. A run whose saves were checked below level 3 - gets `UNKNOWN` (`below_verified_level`), never `VERIFIED`. Receipts written - before this field, and a `VERIFIED` run whose report has no `readback` - block (it made no save), have no evidence scope and still verify. + check level the weakest save reached, the receipt word, its basis, the + wire the run watched, and what the evidence did not cover. `VERIFIED` + always names the basis that earned it. The baseline is the check a careful + person does after a save, basis `post_save_screen` (level 1): the form left + edit mode, no error is shown, and every intended value was read on the + screen, field by field, and matched. A banner or toast alone never earns + it. The same check after reopening the record is `reopened_record` + (level 2). Stronger evidence is a stronger basis on the same word: + `separate_session` or `fresh_reload` (level 3), and `system_api`, + `activity_log`, `db_frame` or `owned_connection` (level 4). Anything less, + such as a field that was not read, is `RECORDED`. The block always lists + server-side async and outbound effects, and, because a run report has no + per-read time yet, `read_back_time`. `VERIFIED` means the read-back showed + the value when it ran, not that it persisted. +- The runtime's `report.json` does not yet record, per save, whether the form + left edit mode and whether an error was shown. So a run whose saves were + checked only on the acting screen earns no basis: its receipt says + `RECORDED`, with outcome `UNKNOWN` (`below_verified_level`). A regulated + profile (`separate_session` or stronger) also gets `UNKNOWN` for a run + checked below its floor. +- Older receipts may say `SHOWN` for a re-read of the acting screen. They + still verify, and `openadapt receipt verify` labels the word as the older + format. Receipts written before the evidence scope existed, and a + `VERIFIED` run whose report has no `readback` block (it made no save), have + no evidence scope and still verify. **A receipt and its public card never contain screenshots, typed values, URLs or page text.** Evidence files, screenshots included, appear only by diff --git a/packages/flow/docs/THREAT_MODEL.md b/packages/flow/docs/THREAT_MODEL.md index 00022d9e46..f900f5c602 100644 --- a/packages/flow/docs/THREAT_MODEL.md +++ b/packages/flow/docs/THREAT_MODEL.md @@ -23,6 +23,27 @@ All data in the tests on this page is synthetic. ## Which layer guarantees what +### The baseline: check like a careful operator + +OpenAdapt checks a save the way a careful person checks their own work, not +the way an all-seeing observer would. After a save, the person sees the form +close, sees no error, and finds every value they meant to enter on the +screen. That post-save screen check is the baseline. When it reads every +intended value field by field and each one matches, the receipt says +`VERIFIED` with basis `post_save_screen`. A banner or toast alone is not +enough, and a value that could not be read means the save was not checked. + +Stronger checks are upgrades on the same word, used when they are available: +reopening the record (`reopened_record`), a separate session +(`separate_session`, `fresh_reload`), and the system of record +(`system_api`, `activity_log`, `db_frame`, `owned_connection`). The wire +check and undo add protection on top. A policy can require one of the +stronger checks: the `Regulated` profile requires a separate session or the +system of record, and a run checked only on the screen is not `VERIFIED` +there. Effects no person could see either (server-side jobs that run later, +outbound messages) are listed on every receipt as not covered; they are out +of scope, not failures. + Safety rests on three layers. Each threat has one owner, and the other checks only reduce how often that owner has to act. @@ -51,12 +72,15 @@ screen postcondition and is not graded. (level 3) is the strongest read available there. Changes to other records that the log does not show, server-side jobs that run later, and outbound messages (HL7, queues, email) are outside it. -- **Reads in the acting session** (`same_screen`, `reopened`) confirm only - what the acting surface showed at the time of the read. Under `Standard` - they reach `VERIFIED` (with `same_screen` or `reopened` recorded on the - report and receipt) unless `minimum_readback` sets a higher floor; under - `Regulated` (or when `minimum_readback` sets a higher floor) they end - `COMPLETED_UNVERIFIED`. +- **Reads in the acting session** (`same_screen`, `reopened`) confirm what + the acting surface showed at the time of the read. Under `Standard` they + reach `VERIFIED` on the run report unless `minimum_readback` sets a higher + floor; under `Regulated` (or when `minimum_readback` sets a higher floor) + they end `COMPLETED_UNVERIFIED`. The receipt names the basis + `post_save_screen` or `reopened_record` only when the check recorded, per + save, that the form left edit mode, no error was shown, and every intended + value was read and matched. The runtime's report does not record the first + two yet, so its receipts for these runs say `RECORDED`. `VERIFIED` means "as of the read-back time, the read showed this value". It does not mean the value persisted after that, and it does not mean the run @@ -66,8 +90,9 @@ are not observed. The wire check (layer 2) is evidence about what was sent. It is not a check level and does not by itself make a run `VERIFIED`. -Everything else, including the identity checks before a click, look-alike -row counting, focus and form checks and pixel grounding, is a **pre-check**. +The post-save screen check is part of layer 1, not a pre-check. Everything +else, including the identity checks before a click, look-alike row counting, +focus and form checks and pixel grounding, is a **pre-check**. A pre-check avoids bad writes and wasted runs. It must fail closed when unsure, but it is never the thing that makes a run safe: if a pre-check is fooled, layer 1 catches a result that its read path covers and layer 3 diff --git a/packages/kernel/CHANGELOG.md b/packages/kernel/CHANGELOG.md index 2fc57845c3..bb93166172 100644 --- a/packages/kernel/CHANGELOG.md +++ b/packages/kernel/CHANGELOG.md @@ -2,6 +2,20 @@ ## Unreleased +- Receipt bridge: a `post_save_screen` proof channel. Its line is confirmed, + and the evidence scope says `VERIFIED` with basis `post_save_screen` + (level 1, or `reopened_record` at level 2 after a reopen), only when the + proof's `screen_check` says every intended value was read on the screen + and matched, the form left edit mode, no error is shown, and the sign of + the save is not only a banner. Otherwise the line is not checked and the + receipt is not `VERIFIED`. The same rule as + `openadapt_types.check_level.post_save_screen_basis`, tested on the shared + cases. `ReadBackProof` gains an optional `screen_check`, and `is_valid` + refuses a `post_save_screen` proof whose check is incomplete. +- Receipt bridge: a proof channel the bridge does not know no longer counts + as a level 3 `fresh_reload` read. Its line is not checked, so the receipt + is not `VERIFIED`. + - `token_boundary_check`, and through it `verify_sqlite_ro`, `verify_pdf_readback`, `verify_cross_tab_dom` and the non-DOM adapter, uses the shared strict evidence matcher (`openadapt_kernel._evidence`, a copy of diff --git a/packages/seal-view/CHANGELOG.md b/packages/seal-view/CHANGELOG.md index 6f2d6c5123..71e68cfe92 100644 --- a/packages/seal-view/CHANGELOG.md +++ b/packages/seal-view/CHANGELOG.md @@ -2,6 +2,11 @@ ## v0.1.0 (unreleased) +- The receipt verifier accepts the bases `post_save_screen` (level 1), + `reopened_record` (level 2) and `fresh_reload` (level 3), and `VERIFIED` at + levels 1 to 4 with a basis, as the Python verifier does. An older `SHOWN` + block still verifies; one that names a basis is refused. + - The receipt verifier refuses an `evidence_scope` the Python verifier refuses: a `null` block, `basis`, `read_back_at` or `recheck_window_s` set to `null`, and a `wire` without `protocols_parsed`. Before, it read those diff --git a/packages/types/CHANGELOG.md b/packages/types/CHANGELOG.md index 6ba81a7bd1..87a1910608 100644 --- a/packages/types/CHANGELOG.md +++ b/packages/types/CHANGELOG.md @@ -3,6 +3,28 @@ ## Unreleased +- `check_level`: the post-save screen check earns `VERIFIED`. New bases + `post_save_screen` (level 1) and `reopened_record` (level 2) are handed out + only by `post_save_screen_basis`, from a `ScreenCheck` that says every + intended value was read on the screen field by field and matched, the form + left edit mode, and no error is shown. A banner or toast alone, a field not + read, or a flag nobody observed earns no basis, and the word is + `RECORDED`. `outcome_word` and `build_evidence_scope` now default + `minimum` to `same_screen` and no longer clamp it to `separate_session`; a + regulated caller passes `separate_session`. `VERIFIED_LEVELS` now lists + levels 1 to 4 (the levels the word may name); the new `INDEPENDENT_LEVELS` + lists levels 3 and 4. `outcome_word` never returns `SHOWN` any more. +- `evidence_scope`: `VERIFIED` is valid at levels 1 to 4 with a basis that + reaches that level. `SHOWN` is kept in `OutcomeWord` and still validates at + levels 1 and 2 so older receipts verify; it may not name a basis. + `legacy_word` and `LEGACY_WORDS` let tools label it as the older format. + A block with a new basis does not validate under openadapt-types 0.24.x. +- Test vectors: `valid-evidence-scope-post-save-screen` (a signed + `VERIFIED` receipt with basis `post_save_screen`) and + `older-evidence-scope-shown` (an older `SHOWN` receipt that still + verifies), plus `vectors/screen-check/cases.json`, shared by the types, + Flow, kernel and launcher tests. + - `evidence`: one strict matcher for deciding whether text on a screen or page proves a value or a commit. `match_field` returns `MATCH`, `MISMATCH` or `AMBIGUOUS`, and only `MATCH` may pass. A value bound to its label is From 6dc8258fd26c2a0b9949824f14a9c73c9a5d7cbb Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 18:22:21 -0500 Subject: [PATCH 05/17] fix(receipts): address review: per-save screen checks, strict ScreenCheck, kernel floor and redaction, wrap integrity --- openadapt/receipt_verify.py | 6 +- openadapt/seal_view/viewer.html | 8 +- openadapt/wrap_sdk.py | 20 +++-- .../openadapt_flow/effect_location/_compat.py | 5 +- .../flow/openadapt_flow/evidence_basis.py | 58 ++++++------ packages/flow/openadapt_flow/verify_run.py | 7 +- packages/flow/tests/test_post_save_screen.py | 35 +++++++- packages/kernel/CHANGELOG.md | 8 +- .../kernel/src/openadapt_kernel/copilot.py | 6 +- .../kernel/src/openadapt_kernel/ledger.py | 14 +-- .../src/openadapt_kernel/receipt_bridge.py | 34 +++++++ .../tests/test_post_save_screen_bridge.py | 45 ++++++++++ packages/seal-view/src/lib/receiptRecord.mjs | 3 + packages/types/CHANGELOG.md | 11 ++- packages/types/openadapt_types/check_level.py | 64 +++++++++++-- .../types/openadapt_types/evidence_scope.py | 18 ++++ packages/types/openadapt_types/receipt.py | 16 +++- packages/types/tests/test_post_save_screen.py | 86 +++++++++++++++++- ...dence-scope-screen-with-unread-fields.json | 21 +++++ .../tests/vectors/record-run-v1/generate.py | 8 ++ ...valid-evidence-scope-post-save-screen.json | 4 +- tests/test_post_save_screen_parity.py | 89 ++++++++++++++++++- 22 files changed, 491 insertions(+), 75 deletions(-) create mode 100644 packages/types/tests/vectors/record-run-v1/evidence-scope-screen-with-unread-fields.json diff --git a/openadapt/receipt_verify.py b/openadapt/receipt_verify.py index c648587dcf..64c4528f23 100644 --- a/openadapt/receipt_verify.py +++ b/openadapt/receipt_verify.py @@ -89,11 +89,11 @@ def _check_line(scope: dict[str, Any]) -> str: evidence-scope block. An older ``SHOWN`` block says it is the older format.""" - from openadapt_types.evidence_scope import legacy_word - word = _one_line(scope.get("word")) level = _one_line(scope.get("check_level")) - if legacy_word(scope) is not None: + # The one older word, named here so the label works with any installed + # openadapt-types (``openadapt_types.evidence_scope.LEGACY_WORDS``). + if scope.get("word") == "SHOWN": return ( f"Check: {word} ({OLDER}: the acting screen was read again; level {level})" ) diff --git a/openadapt/seal_view/viewer.html b/openadapt/seal_view/viewer.html index 707c024164..c8f9410ac9 100644 --- a/openadapt/seal_view/viewer.html +++ b/openadapt/seal_view/viewer.html @@ -15,16 +15,16 @@
- diff --git a/openadapt/wrap_sdk.py b/openadapt/wrap_sdk.py index ee04275c94..dd35e48c59 100644 --- a/openadapt/wrap_sdk.py +++ b/openadapt/wrap_sdk.py @@ -640,9 +640,12 @@ def wrap_receipt_word( receipt (``contract_receipt``, a ``verify-run`` receipt whose digest is the wrap receipt's ``contract_receipt_sha256``) and the word is the one its evidence-scope block states, for example ``VERIFIED`` with basis - ``post_save_screen`` or ``system_api``. Anything else is ``RECORDED``: an - outcome other than confirmed, no contract receipt, a digest that does not - match, or a block that does not validate. + ``system_api``. Anything else is ``RECORDED``: a wrap receipt whose own + digest does not match its fields, an outcome other than confirmed, no + contract receipt, a contract digest that does not match, a contract + receipt that fails ``verify-run``'s own checks, or a block that does not + validate. This checks integrity, not who signed: use + :func:`check_wrap_receipt` for that. The word is derived, never signed, so receipts keep their exact bytes. """ @@ -653,18 +656,25 @@ def wrap_receipt_word( or data.get("outcome") != WrapOutcome.CONFIRMED.value ): return "RECORDED" + try: + if _sha256_hex(_digest_payload(data)) != data.get("sha256"): + return "RECORDED" + except (TypeError, ValueError): + return "RECORDED" digest = data.get("contract_receipt_sha256") if not isinstance(contract_receipt, Mapping) or not isinstance(digest, str): return "RECORDED" try: - from openadapt_flow.verify_run import receipt_sha256 + from openadapt_flow.verify_run import receipt_problem, receipt_sha256 from openadapt_types.evidence_scope import evidence_scope_problem except ImportError: # pragma: no cover - the flow extra is not installed return "RECORDED" try: if receipt_sha256(contract_receipt) != digest: return "RECORDED" - except (TypeError, ValueError): + if receipt_problem(contract_receipt) is not None: + return "RECORDED" + except (TypeError, ValueError, KeyError, AttributeError): return "RECORDED" block = contract_receipt.get("evidence_scope") if evidence_scope_problem(block) is not None: diff --git a/packages/flow/openadapt_flow/effect_location/_compat.py b/packages/flow/openadapt_flow/effect_location/_compat.py index 4b17b26387..70dcef8b04 100644 --- a/packages/flow/openadapt_flow/effect_location/_compat.py +++ b/packages/flow/openadapt_flow/effect_location/_compat.py @@ -64,4 +64,7 @@ def word(level: Any, basis: Optional[str], *, confirmed: bool) -> Optional[str]: if _outcome_word is None: return None - return str(_outcome_word(level, basis, confirmed=confirmed)) + chosen = str(_outcome_word(level, basis, confirmed=confirmed)) + # An older openadapt-types still says SHOWN for a screen read without a + # basis; current receipts say it claims no check. + return "RECORDED" if chosen == "SHOWN" else chosen diff --git a/packages/flow/openadapt_flow/evidence_basis.py b/packages/flow/openadapt_flow/evidence_basis.py index 490f2d1beb..50a7e6eff0 100644 --- a/packages/flow/openadapt_flow/evidence_basis.py +++ b/packages/flow/openadapt_flow/evidence_basis.py @@ -81,41 +81,28 @@ def level_and_basis( return level, basis_for_tier(tier, kinds) -def screen_basis(level: CheckLevel, checks: Sequence[Any]) -> Optional[Basis]: +def screen_basis( + level: CheckLevel, checks: Sequence[Any], saves: Optional[int] = None +) -> Optional[Basis]: """The basis a level 1 or 2 run earns from its saves' screen checks. ``checks`` holds one :class:`~openadapt_types.check_level.ScreenCheck` - (or a mapping of one) per save. The basis is earned only when there is - one per save, every one is complete, and they all name ``level`` - (``post_save_screen`` at level 1, ``reopened_record`` at level 2). None - otherwise, and None when the installed ``openadapt-types`` predates the - screen bases. + (or a mapping of one) per save, and ``saves`` is how many saves the run + made: a check count that differs earns nothing. The rule is + ``openadapt_types.check_level.screen_basis_for``: every check complete + and reaching ``level``. None when the installed ``openadapt-types`` + predates the screen bases. """ try: from openadapt_types.check_level import ( # type: ignore[attr-defined] - ScreenCheck, - level_for_basis, - post_save_screen_basis, + screen_basis_for, ) except ImportError: # pragma: no cover - older openadapt-types return None - level = CheckLevel(level) - if level not in (CheckLevel.SAME_SCREEN, CheckLevel.REOPENED) or not checks: + if saves is not None and len(checks) != saves: return None - bases = set() - for item in checks: - check = ( - item if isinstance(item, ScreenCheck) else ScreenCheck.from_mapping(item) - ) - basis = post_save_screen_basis(check) - if basis is None: - return None - bases.add(basis) - if len(bases) != 1: - return None - basis = bases.pop() - return basis if level_for_basis(basis) == level else None # type: ignore[return-value] + return screen_basis_for(level, checks) # type: ignore[no-any-return] def evidence_scope_for_run( @@ -133,9 +120,10 @@ def evidence_scope_for_run( value. The receipt for the run (``record/run/v1``) carries this block as ``evidence_scope``. Only a ``VERIFIED`` run names a basis, so only a ``VERIFIED`` run gets the word ``VERIFIED``. A level 1 or 2 run names - ``post_save_screen`` or ``reopened_record`` only with a complete - ``screen_checks`` entry for every save (:func:`screen_basis`); without - them it is ``RECORDED``. + ``post_save_screen`` or ``reopened_record`` only with one complete + ``screen_checks`` entry for each save in ``readback["saves"]`` + (:func:`screen_basis`); without them it is ``RECORDED``, also under an + ``openadapt-types`` that predates the screen bases. """ from openadapt_types.check_level import VERIFIED_WORD @@ -152,17 +140,24 @@ def evidence_scope_for_run( except ValueError: level = CheckLevel.UNCHECKED verified = str(outcome).upper() == VERIFIED_WORD + saves = readback.get("saves") if isinstance(readback, Mapping) else None basis: Optional[Basis] = None if verified: basis = basis_for_tier(to_verification_tier(level)) - if basis is None: - basis = screen_basis(level, screen_checks) + if basis is None and isinstance(saves, list): + basis = screen_basis(level, screen_checks, saves=len(saves)) + screen = level in (CheckLevel.SAME_SCREEN, CheckLevel.REOPENED) + extra: dict[str, Any] = {} + if basis is not None and screen: + extra["screen_checks"] = screen_checks return build_evidence_scope( level, basis=basis, # ``checked_how`` is the weakest save's level and is ``unchecked`` - # when any save did not confirm, so any higher level confirmed. - confirmed=level > CheckLevel.UNCHECKED, + # when any save did not confirm, so any higher level confirmed. A + # screen read without its basis claims no check (never the older + # ``SHOWN``, whatever openadapt-types is installed). + confirmed=level > CheckLevel.UNCHECKED and not (screen and basis is None), minimum=minimum, read_back_at=read_back_at if level > CheckLevel.UNCHECKED else None, not_covered=( @@ -171,6 +166,7 @@ def evidence_scope_for_run( # A run report records no per-read time yet. *(("read_back_time",) if read_back_at is None else ()), ), + **extra, ) diff --git a/packages/flow/openadapt_flow/verify_run.py b/packages/flow/openadapt_flow/verify_run.py index 618a768bb8..df803eb364 100644 --- a/packages/flow/openadapt_flow/verify_run.py +++ b/packages/flow/openadapt_flow/verify_run.py @@ -3805,7 +3805,12 @@ def verify_run( level, # Only a verified receipt names a basis, so only it reads VERIFIED. basis=basis if verified else None, - confirmed=delta_verdict == CONFIRMED_WORD, + # A screen read has no basis here, so it claims no check (never + # the older SHOWN, whatever openadapt-types is installed). + confirmed=delta_verdict == CONFIRMED_WORD + and not ( + CheckLevel.SAME_SCREEN <= level <= CheckLevel.REOPENED and basis is None + ), minimum=minimum_level, read_back_at=read_at if not unread else None, recheck_window_s=( diff --git a/packages/flow/tests/test_post_save_screen.py b/packages/flow/tests/test_post_save_screen.py index 554d554d41..4c007ef527 100644 --- a/packages/flow/tests/test_post_save_screen.py +++ b/packages/flow/tests/test_post_save_screen.py @@ -36,8 +36,19 @@ def _floor(profile: ExecutionProfile) -> str: return VerificationTier(int(verified_tier_floor(None, profile))).check_level.label -def _scope(level: str, checks, minimum: str = "same_screen", outcome: str = "VERIFIED"): - readback = {"checked_how": level, "minimum": minimum} +def _scope( + level: str, + checks, + minimum: str = "same_screen", + outcome: str = "VERIFIED", + saves: int | None = None, +): + count = len(checks) if saves is None else saves + readback = { + "checked_how": level, + "minimum": minimum, + "saves": [{"step_id": f"s{i}", "checked_how": level} for i in range(count)], + } return evidence_scope_for_run( readback, outcome, read_back_at=T, screen_checks=checks ) @@ -60,10 +71,26 @@ def test_every_save_needs_a_complete_check() -> None: assert "fields_not_read" in mixed["not_covered"] # No record at all: the tier alone earns nothing. assert _scope("same_screen", [])["word"] == "RECORDED" - # A reopen check can't stand in for a same-screen level, or the reverse. + assert _scope("same_screen", [], saves=1)["word"] == "RECORDED" + # One check per save: one complete check can't cover two saves. + assert _scope("same_screen", [good], saves=2)["word"] == "RECORDED" + # A report without its saves list earns nothing either. + no_saves = evidence_scope_for_run( + {"checked_how": "same_screen", "minimum": "same_screen"}, + "VERIFIED", + read_back_at=T, + screen_checks=[good], + ) + assert no_saves["word"] == "RECORDED" + # A reopen check also reaches level 1, so a level 1 run with one save + # checked each way earns post_save_screen (the weakest level wins); a + # same-screen check never reaches level 2. reopened = next(c["check"] for c in CASES if c["name"] == "complete_after_reopen") - assert screen_basis(CheckLevel.SAME_SCREEN, [reopened]) is None + mixed_ok = _scope("same_screen", [good, reopened]) + assert (mixed_ok["word"], mixed_ok["basis"]) == ("VERIFIED", "post_save_screen") + assert screen_basis(CheckLevel.SAME_SCREEN, [reopened]) == "post_save_screen" assert screen_basis(CheckLevel.REOPENED, [good]) is None + assert screen_basis(CheckLevel.REOPENED, [reopened, good]) is None def test_a_run_that_did_not_verify_names_no_basis() -> None: diff --git a/packages/kernel/CHANGELOG.md b/packages/kernel/CHANGELOG.md index bb93166172..5975ccf9ce 100644 --- a/packages/kernel/CHANGELOG.md +++ b/packages/kernel/CHANGELOG.md @@ -14,7 +14,13 @@ refuses a `post_save_screen` proof whose check is incomplete. - Receipt bridge: a proof channel the bridge does not know no longer counts as a level 3 `fresh_reload` read. Its line is not checked, so the receipt - is not `VERIFIED`. + is not `VERIFIED`. `ReadBackProof.is_valid()` refuses such a channel too, + so the native kernel receipt and the bridge agree. +- Receipt bridge: `minimum_level` (default 1) sets the weakest check level + the caller's policy accepts. A regulated caller passes 3; a run whose + weakest read is below it is `UNKNOWN` (`below_verified_level`). +- A redacted receipt carries only the screen check's counts and flags; a + check with any other key is not carried and does not count. - `token_boundary_check`, and through it `verify_sqlite_ro`, `verify_pdf_readback`, `verify_cross_tab_dom` and the non-DOM adapter, uses diff --git a/packages/kernel/src/openadapt_kernel/copilot.py b/packages/kernel/src/openadapt_kernel/copilot.py index 8d9e68c24e..9dcb7a4421 100644 --- a/packages/kernel/src/openadapt_kernel/copilot.py +++ b/packages/kernel/src/openadapt_kernel/copilot.py @@ -295,7 +295,11 @@ def mint_receipt( "observed_at_utc": ob.readback_proof.observed_at_utc, } if ob.readback_proof.screen_check is not None: - proof_obj["screen_check"] = dict(ob.readback_proof.screen_check) + # Only the validated counts and flags, never other keys: a + # redacted receipt carries no field value. + from openadapt_kernel.receipt_bridge import _screen_check_summary + + proof_obj["screen_check"] = _screen_check_summary(ob.readback_proof.screen_check) target_sys = ob.target_system if include_plaintext_values else _origin_host_only(ob.target_system) obligations_payload[oid] = { "state": ob.state, diff --git a/packages/kernel/src/openadapt_kernel/ledger.py b/packages/kernel/src/openadapt_kernel/ledger.py index 4f65c0d4ff..7ea96ddd53 100644 --- a/packages/kernel/src/openadapt_kernel/ledger.py +++ b/packages/kernel/src/openadapt_kernel/ledger.py @@ -83,13 +83,17 @@ class ReadBackProof: def is_valid(self) -> bool: if not (self.url_or_locator and any(len(s.strip()) >= 2 for s in self.cited_substrings)): return False + from openadapt_kernel.receipt_bridge import ( + KNOWN_CHANNELS, + _screen_check_summary, + _screen_level_and_basis, + ) + + if self.channel not in KNOWN_CHANNELS: + # A channel the receipt bridge does not grade proves nothing. + return False if self.channel == "post_save_screen": # A screen check proves the save only when it is complete. - from openadapt_kernel.receipt_bridge import ( - _screen_check_summary, - _screen_level_and_basis, - ) - return _screen_level_and_basis(_screen_check_summary(self.screen_check)) is not None return True diff --git a/packages/kernel/src/openadapt_kernel/receipt_bridge.py b/packages/kernel/src/openadapt_kernel/receipt_bridge.py index 5800244f59..1a65d82829 100644 --- a/packages/kernel/src/openadapt_kernel/receipt_bridge.py +++ b/packages/kernel/src/openadapt_kernel/receipt_bridge.py @@ -83,6 +83,25 @@ #: ``post_save_screen``, or ``reopened_record`` after a reopen). POST_SAVE_SCREEN_CHANNEL: Final = "post_save_screen" _SCREEN_COUNTS: Final = ("fields_intended", "fields_read", "fields_matched") +_SCREEN_KEYS: Final = ( + *_SCREEN_COUNTS, + "left_edit_mode", + "error_shown", + "banner_only", + "reopened", +) +#: The proof channels the bridge grades; any other earns nothing. +KNOWN_CHANNELS: Final = frozenset( + { + "fresh_reload", + "cross_tab", + "api_read", + "sql_read", + "pdf_stream", + "artifact_file", + "post_save_screen", + } +) def _screen_check_summary(raw: Any) -> Optional[Dict[str, Any]]: @@ -93,6 +112,8 @@ def _screen_check_summary(raw: Any) -> Optional[Dict[str, Any]]: if not isinstance(raw, Mapping): return None + if set(raw) - set(_SCREEN_KEYS): + return None # an unexpected key may hold a value; never carry it out: Dict[str, Any] = {} for key in _SCREEN_COUNTS: value = raw.get(key) @@ -348,9 +369,15 @@ def kernel_receipt_to_dsse_record( surface: str = "dom", pack_digest: Optional[str] = None, model_calls: int = 0, + minimum_level: int = 1, ) -> Dict[str, Any]: """Convert an ``openadapt.kernel.receipt/v1`` receipt into a signed DSSE ``record/run/v1`` envelope. + ``minimum_level`` is the weakest check level (``openadapt_types.check_level``) + the caller's policy accepts for ``VERIFIED``: 1, the post-save screen + check, by default; a regulated caller passes 3 (a separate session). A + run whose weakest read is below it is ``UNKNOWN`` (``below_verified_level``). + The resulting envelope uses ``payloadType`` :data:`DSSE_PAYLOAD_TYPE_RECORD_RUN_V1`, wraps a canonical in-toto ``Statement/v1`` with ``predicateType`` ``https://openadapt.ai/record/run/v1``, and signs ``DSSEv1`` PAE bytes with Ed25519. @@ -491,6 +518,13 @@ def kernel_receipt_to_dsse_record( if mapped_outcome == "VERIFIED" and lines and confirmed_count != len(lines): mapped_outcome = "UNKNOWN" reason_code = "unverified_write" + if ( + mapped_outcome == "VERIFIED" + and weakest_proof_level is not None + and weakest_proof_level[0] < max(1, int(minimum_level)) + ): + mapped_outcome = "UNKNOWN" + reason_code = "below_verified_level" total_steps = len(lines) ok_steps = confirmed_count diff --git a/packages/kernel/tests/test_post_save_screen_bridge.py b/packages/kernel/tests/test_post_save_screen_bridge.py index 83d1f59fb7..46f5403a5b 100644 --- a/packages/kernel/tests/test_post_save_screen_bridge.py +++ b/packages/kernel/tests/test_post_save_screen_bridge.py @@ -125,3 +125,48 @@ def test_stronger_channels_keep_their_bases() -> None: receipt = _with_proof(_complete_receipt(priv), channel=channel) scope = _scope(receipt, priv, pub) assert (scope["word"], scope["check_level"], scope["basis"]) == ("VERIFIED", level, basis) + + +def test_a_redacted_receipt_carries_only_the_counts_and_flags() -> None: + priv, _ = generate_ephemeral_ed25519_keypair() + ledger = ObligationLedger(episode_id="ep-screen-redact") + ledger.add_obligation("save", "Save", target_system="https://records.example.test") + ledger.mark_committed("save", _proof("post_save_screen", dict(COMPLETE))) + ledger.finalize("done") + # A caller adds a key the check does not define after the proof was made. + proof = ledger.obligations["save"].readback_proof + assert proof is not None and proof.screen_check is not None + proof.screen_check["note"] = "Jane Doe" + receipt = mint_receipt(ledger, "screen-save-v1", priv) + raw = json.dumps(receipt) + assert "Jane Doe" not in raw + ob = next(iter(receipt["payload"]["obligations"].values())) + # The unexpected key makes the check unreadable, so nothing is carried. + assert ob["proof"]["screen_check"] is None + + +def test_the_ledger_refuses_an_unknown_channel() -> None: + assert not _proof("screen_glance").is_valid() + ledger = ObligationLedger(episode_id="ep-unknown") + ledger.add_obligation("save", "Save", target_system="https://records.example.test") + with pytest.raises(ValueError): + ledger.mark_committed("save", _proof("screen_glance")) + + +def test_a_policy_floor_keeps_a_screen_check_from_verified() -> None: + priv, pub = generate_ephemeral_ed25519_keypair() + receipt = _complete_receipt(priv) + standard = _scope(receipt, priv, pub) + assert (standard["outcome"], standard["word"]) == ("VERIFIED", "VERIFIED") + envelope = kernel_receipt_to_dsse_record(receipt, priv, surface="dom", minimum_level=3) + ok, statement, reason = verify_unified_dsse_receipt(envelope, pub) + assert ok, reason + predicate = statement["predicate"] + assert predicate["outcome"] == "UNKNOWN" + assert predicate["reason_code"] == "below_verified_level" + assert predicate["evidence_scope"]["word"] == "RECORDED" + # A separate-session read meets the regulated floor. + cross_tab = _with_proof(receipt, channel="cross_tab") + envelope = kernel_receipt_to_dsse_record(cross_tab, priv, surface="dom", minimum_level=3) + ok, statement, _ = verify_unified_dsse_receipt(envelope, pub) + assert ok and statement["predicate"]["outcome"] == "VERIFIED" diff --git a/packages/seal-view/src/lib/receiptRecord.mjs b/packages/seal-view/src/lib/receiptRecord.mjs index 5afef1c51a..34752ec125 100644 --- a/packages/seal-view/src/lib/receiptRecord.mjs +++ b/packages/seal-view/src/lib/receiptRecord.mjs @@ -114,6 +114,7 @@ const BASIS_LEVEL = { db_frame: 'system_of_record', owned_connection: 'system_of_record', } +const SCREEN_BASES = ['post_save_screen', 'reopened_record'] const WIRE_CHANNELS = ['none', 'browser_network', 'http_proxy', 'api_client', 'db_connection'] const WIRE_PROTOCOLS = ['http', 'graphql', 'fhir', 'sql', 'websocket', 'grpc', 'smtp'] const NOT_COVERED = ['server_side_async_effects', 'outbound_effects', 'changes_after_read_back', 'fields_not_read', 'other_records', 'other_actors', 'read_back_time'] @@ -282,6 +283,7 @@ function validateStatement(s) { if (es.word === 'VERIFIED') { if (!['same_screen', 'reopened', 'separate_session', 'system_of_record'].includes(es.check_level) || es.basis == null) throw new Refusal('malformed', 'VERIFIED needs level 1 to 4 and a basis') if (es.read_back_at == null && !es.not_covered.includes('read_back_time')) throw new Refusal('malformed', 'VERIFIED needs read_back_at, or says it has none') + if (SCREEN_BASES.includes(es.basis) && es.not_covered.includes('fields_not_read')) throw new Refusal('malformed', 'a screen check that did not read every field is not VERIFIED') } if (es.word === 'SHOWN' && !['same_screen', 'reopened'].includes(es.check_level)) throw new Refusal('malformed', 'SHOWN is a level 1 or 2 re-read of the acting screen') // SHOWN is the older word; receipts that carry it still verify. @@ -319,6 +321,7 @@ function inconsistency(s) { if (p.checks.lines_confirmed !== tally.confirmed || p.checks.lines_refuted !== tally.refuted || p.checks.lines_not_checked !== tally.not_checked) return 'check counts disagree with the lines' if (p.outcome === 'VERIFIED' && tally.refuted) return 'a VERIFIED receipt has a refuted line' if (p.evidence_scope && !EVIDENCE_SCOPE_OUTCOMES[p.evidence_scope.word].includes(p.outcome)) return "the evidence scope's word disagrees with the outcome" + if (p.evidence_scope && SCREEN_BASES.includes(p.evidence_scope.basis) && p.lines.some((l) => l.not_checked.includes('field_values'))) return 'a screen check says every field was read, a line says not' const steps = p.lines.map((l) => l.step) for (let i = 1; i < steps.length; i += 1) if (steps[i] <= steps[i - 1]) return 'lines are not in step order, or repeat a step' for (const c of p.confirmations || []) { diff --git a/packages/types/CHANGELOG.md b/packages/types/CHANGELOG.md index 87a1910608..feff7fe039 100644 --- a/packages/types/CHANGELOG.md +++ b/packages/types/CHANGELOG.md @@ -14,15 +14,24 @@ regulated caller passes `separate_session`. `VERIFIED_LEVELS` now lists levels 1 to 4 (the levels the word may name); the new `INDEPENDENT_LEVELS` lists levels 3 and 4. `outcome_word` never returns `SHOWN` any more. + `ScreenCheck` refuses a value that is not a count or a flag (a boolean + count, a string flag), and `from_mapping` refuses a mapping with any other + key. `screen_basis_for(level, checks)` is the one rule for a result with + one check per save: every check complete and reaching `level`. + `build_evidence_scope` refuses a screen basis unless `screen_checks` earns + it. - `evidence_scope`: `VERIFIED` is valid at levels 1 to 4 with a basis that reaches that level. `SHOWN` is kept in `OutcomeWord` and still validates at levels 1 and 2 so older receipts verify; it may not name a basis. `legacy_word` and `LEGACY_WORDS` let tools label it as the older format. + A screen basis with `fields_not_read` in `not_covered` does not validate, + and a `record/run/v1` receipt with a screen basis is refused when one of + its lines lists `field_values` as not checked. A block with a new basis does not validate under openadapt-types 0.24.x. - Test vectors: `valid-evidence-scope-post-save-screen` (a signed `VERIFIED` receipt with basis `post_save_screen`) and `older-evidence-scope-shown` (an older `SHOWN` receipt that still - verifies), plus `vectors/screen-check/cases.json`, shared by the types, + verifies), `evidence-scope-screen-with-unread-fields` (refused), plus `vectors/screen-check/cases.json`, shared by the types, Flow, kernel and launcher tests. - `evidence`: one strict matcher for deciding whether text on a screen or diff --git a/packages/types/openadapt_types/check_level.py b/packages/types/openadapt_types/check_level.py index 1241bfb294..78a7e3f857 100644 --- a/packages/types/openadapt_types/check_level.py +++ b/packages/types/openadapt_types/check_level.py @@ -109,6 +109,7 @@ "level_for_basis", "outcome_word", "post_save_screen_basis", + "screen_basis_for", "to_effect_strength", "to_oracle_tier", "to_readback_label", @@ -329,6 +330,19 @@ def to_effect_strength(level: CheckLevel) -> Optional[str]: ) +_SCREEN_CHECK_KEYS = frozenset( + { + "fields_intended", + "fields_read", + "fields_matched", + "left_edit_mode", + "error_shown", + "banner_only", + "reopened", + } +) + + @dataclass(frozen=True) class ScreenCheck: """What a post-save screen check saw, for one save. @@ -354,15 +368,26 @@ class ScreenCheck: banner_only: bool = False reopened: bool = False + def __post_init__(self) -> None: + for name in ("fields_intended", "fields_read", "fields_matched"): + value = getattr(self, name) + if not isinstance(value, int) or isinstance(value, bool) or value < 0: + raise ValueError(f"{name} must be a count, not {value!r}") + for name in ("left_edit_mode", "error_shown"): + value = getattr(self, name) + if value is not None and not isinstance(value, bool): + raise ValueError(f"{name} must be True, False or None") + for name in ("banner_only", "reopened"): + if not isinstance(getattr(self, name), bool): + raise ValueError(f"{name} must be True or False") + @property def complete(self) -> bool: """Every intended value was read and matched, with the form closed and no error shown.""" return ( - not isinstance(self.fields_intended, bool) - and isinstance(self.fields_intended, int) - and self.fields_intended >= 1 + self.fields_intended >= 1 and self.fields_read == self.fields_intended and self.fields_matched == self.fields_intended and self.left_edit_mode is True @@ -375,9 +400,7 @@ def fields_not_read(self) -> bool: """Some intended value was not read on the screen.""" return not ( - isinstance(self.fields_intended, int) - and self.fields_intended >= 1 - and self.fields_read >= self.fields_intended + self.fields_intended >= 1 and self.fields_read >= self.fields_intended ) @classmethod @@ -387,6 +410,8 @@ def from_mapping(cls, data: object) -> Optional["ScreenCheck"]: if not isinstance(data, Mapping): return None + if set(data) - _SCREEN_CHECK_KEYS: + return None counts: list[int] = [] for key in ("fields_intended", "fields_read", "fields_matched"): value = data.get(key) @@ -430,6 +455,33 @@ def post_save_screen_basis(check: Optional[ScreenCheck]) -> Optional[Basis]: return "reopened_record" if check.reopened else "post_save_screen" +def screen_basis_for(level: CheckLevel, checks: Iterable[object]) -> Optional[Basis]: + """The basis a level 1 or 2 result earns from one screen check per save. + + ``checks`` holds one :class:`ScreenCheck` (or a ``screen_check`` mapping) + for each save the result covers; the caller passes exactly one per save. + The basis is earned only when there is at least one, every one is + complete, and every one reaches ``level`` (a reopen check also reaches + level 1). Then it is the basis of ``level``: ``post_save_screen`` at + level 1, ``reopened_record`` at level 2. None otherwise. + """ + + level = CheckLevel(level) + if level not in (CheckLevel.SAME_SCREEN, CheckLevel.REOPENED): + return None + items = list(checks) + if not items: + return None + for item in items: + check = ( + item if isinstance(item, ScreenCheck) else ScreenCheck.from_mapping(item) + ) + basis = post_save_screen_basis(check) + if basis is None or _BASIS_LEVEL[basis] < level: + return None + return "post_save_screen" if level is CheckLevel.SAME_SCREEN else "reopened_record" + + def level_for_basis(basis: str) -> CheckLevel: """The check level ``basis`` reaches; raises ``ValueError`` for others.""" diff --git a/packages/types/openadapt_types/evidence_scope.py b/packages/types/openadapt_types/evidence_scope.py index 2ba0cc38c0..d1cd59e9cf 100644 --- a/packages/types/openadapt_types/evidence_scope.py +++ b/packages/types/openadapt_types/evidence_scope.py @@ -45,12 +45,14 @@ from openadapt_types.check_level import ( LEGACY_WORDS, + SCREEN_BASES, Basis, CheckLevel, OutcomeWord, VERIFIED_LEVELS, level_for_basis, outcome_word, + screen_basis_for, ) __all__ = [ @@ -163,6 +165,10 @@ def _consistent(self) -> "EvidenceScopeV1": raise ValueError("VERIFIED needs level 1 to 4 and a basis") if self.read_back_at is None and "read_back_time" not in self.not_covered: raise ValueError("VERIFIED needs read_back_at, or says it has none") + if self.basis in SCREEN_BASES and "fields_not_read" in self.not_covered: + raise ValueError( + "a screen check that did not read every field is not VERIFIED" + ) if self.word == "SHOWN" and not ( CheckLevel.SAME_SCREEN <= level <= CheckLevel.REOPENED ): @@ -202,6 +208,7 @@ def build_evidence_scope( not_covered: Iterable[str] = (), agent_used: Optional[str] = None, verifier_adapter: Optional[str] = None, + screen_checks: Iterable[Any] = (), ) -> dict[str, Any]: """The evidence-scope block for one check, as a wire dict. @@ -213,6 +220,9 @@ def build_evidence_scope( """ level = CheckLevel(level) + if basis in SCREEN_BASES and screen_basis_for(level, screen_checks) != basis: + # A screen basis is earned from its record, never named on its own. + raise ValueError(f"basis {basis} needs a complete screen check per save") word = outcome_word( level, basis, confirmed=confirmed, attested=attested, minimum=minimum ) @@ -295,6 +305,14 @@ def predicate_evidence_scope_problem(predicate: Mapping[str, Any]) -> Optional[s allowed = _PREDICATE_OUTCOMES[block["word"]] if predicate.get("outcome") not in allowed: return "evidence_scope_outcome" + if block.get("basis") in SCREEN_BASES: + # A screen check reads every intended field, so no line may say + # its field values went unchecked. + for line in predicate.get("lines") or (): + if isinstance(line, Mapping) and "field_values" in ( + line.get("not_checked") or () + ): + return "evidence_scope_lines" return None diff --git a/packages/types/openadapt_types/receipt.py b/packages/types/openadapt_types/receipt.py index e711fe00ee..907fddae3e 100644 --- a/packages/types/openadapt_types/receipt.py +++ b/packages/types/openadapt_types/receipt.py @@ -445,10 +445,18 @@ def _check_consistent(statement: RunStatementV1) -> Optional[str]: return "check counts disagree with the lines" if p.outcome == "VERIFIED" and tally["refuted"]: return "a VERIFIED receipt has a refuted line" - if p.evidence_scope is not None and predicate_evidence_scope_problem( - {"outcome": p.outcome, EVIDENCE_SCOPE_FIELD: p.evidence_scope.wire_dict()} - ): - return "the evidence scope's word disagrees with the outcome" + if p.evidence_scope is not None: + scope_problem = predicate_evidence_scope_problem( + { + "outcome": p.outcome, + "lines": [line.model_dump(mode="json") for line in p.lines], + EVIDENCE_SCOPE_FIELD: p.evidence_scope.wire_dict(), + } + ) + if scope_problem == "evidence_scope_lines": + return "a screen check says every field was read, a line says not" + if scope_problem: + return "the evidence scope's word disagrees with the outcome" steps = [line.step for line in p.lines] if steps != sorted(set(steps)): return "lines are not in step order, or repeat a step" diff --git a/packages/types/tests/test_post_save_screen.py b/packages/types/tests/test_post_save_screen.py index 0c7c70bfd5..f93cbb389a 100644 --- a/packages/types/tests/test_post_save_screen.py +++ b/packages/types/tests/test_post_save_screen.py @@ -34,6 +34,7 @@ (Path(__file__).parent / "vectors" / "screen-check" / "cases.json").read_text() )["cases"] T = "2026-11-30T12:00:00Z" +COMPLETE = ScreenCheck(2, 2, 2, left_edit_mode=True, error_shown=False) @pytest.mark.parametrize("case", CASES, ids=[c["name"] for c in CASES]) @@ -43,7 +44,12 @@ def test_each_case_gets_its_word_and_basis(case) -> None: level = CheckLevel.from_label(case["level"]) assert basis == case["basis"] assert outcome_word(level, basis) == case["word"] - block = build_evidence_scope(level, basis=basis, read_back_at=T) + block = build_evidence_scope( + level, + basis=basis, + read_back_at=T, + screen_checks=[check] if basis else (), + ) assert (block["word"], block.get("basis")) == (case["word"], case["basis"]) # Every receipt still lists what no read-back sees. assert block["not_covered"][:2] == ["server_side_async_effects", "outbound_effects"] @@ -146,6 +152,82 @@ def test_an_older_shown_block_still_verifies_and_is_labelled() -> None: == "evidence_scope" ) current = build_evidence_scope( - CheckLevel.SAME_SCREEN, basis="post_save_screen", read_back_at=T + CheckLevel.SAME_SCREEN, + basis="post_save_screen", + read_back_at=T, + screen_checks=[COMPLETE], ) assert legacy_word(current) is None + + +def test_a_screen_basis_is_never_named_without_its_record() -> None: + with pytest.raises(ValueError): + build_evidence_scope( + CheckLevel.SAME_SCREEN, basis="post_save_screen", read_back_at=T + ) + unread = ScreenCheck(2, 1, 1, left_edit_mode=True, error_shown=False) + with pytest.raises(ValueError): + build_evidence_scope( + CheckLevel.SAME_SCREEN, + basis="post_save_screen", + read_back_at=T, + screen_checks=[COMPLETE, unread], + ) + + +def test_a_screen_basis_with_unread_fields_does_not_validate() -> None: + block = build_evidence_scope( + CheckLevel.SAME_SCREEN, + basis="post_save_screen", + read_back_at=T, + screen_checks=[COMPLETE], + ) + assert evidence_scope_problem(block) is None + contradicts = dict(block, not_covered=[*block["not_covered"], "fields_not_read"]) + assert evidence_scope_problem(contradicts) == "evidence_scope" + unread_line = [{"not_checked": ["field_values"]}] + assert ( + predicate_evidence_scope_problem( + {"outcome": "VERIFIED", "lines": unread_line, "evidence_scope": block} + ) + == "evidence_scope_lines" + ) + read_line = [{"not_checked": []}] + assert ( + predicate_evidence_scope_problem( + {"outcome": "VERIFIED", "lines": read_line, "evidence_scope": block} + ) + is None + ) + + +_BASE = dict( + fields_intended=1, + fields_read=1, + fields_matched=1, + left_edit_mode=True, + error_shown=False, +) + + +@pytest.mark.parametrize( + "kwargs", + [ + {"fields_read": True}, + {"fields_matched": True}, + {"fields_intended": -1}, + {"left_edit_mode": "yes"}, + {"error_shown": 0}, + {"reopened": "false"}, + {"banner_only": None}, + ], +) +def test_a_screen_check_refuses_values_that_are_not_counts_or_flags(kwargs) -> None: + with pytest.raises(ValueError): + ScreenCheck(**{**_BASE, **kwargs}) + assert ScreenCheck.from_mapping({**_BASE, **kwargs}) is None + + +def test_a_screen_check_mapping_with_other_keys_is_refused() -> None: + assert ScreenCheck.from_mapping(_BASE) is not None + assert ScreenCheck.from_mapping({**_BASE, "value": "Jane Doe"}) is None diff --git a/packages/types/tests/vectors/record-run-v1/evidence-scope-screen-with-unread-fields.json b/packages/types/tests/vectors/record-run-v1/evidence-scope-screen-with-unread-fields.json new file mode 100644 index 0000000000..b5b4e7f7ab --- /dev/null +++ b/packages/types/tests/vectors/record-run-v1/evidence-scope-screen-with-unread-fields.json @@ -0,0 +1,21 @@ +{ + "description": "A VERIFIED post_save_screen record whose own line says a field value went unchecked: refused.", + "document": { + "payload": "eyJfdHlwZSI6Imh0dHBzOi8vaW4tdG90by5pby9TdGF0ZW1lbnQvdjEiLCJwcmVkaWNhdGUiOnsiY2hlY2tzIjp7ImF1dGhvcml6YXRpb24iOnsiY29uZmlybWVkIjowLCJyZXF1aXJlZCI6MH0sImVmZmVjdHMiOnsiY29uZmlybWVkIjoyLCJyZXF1aXJlZCI6Mn0sImlkZW50aXR5Ijp7ImNvbmZpcm1lZCI6NSwicmVxdWlyZWQiOjV9LCJsaW5lc19jb25maXJtZWQiOjIsImxpbmVzX25vdF9jaGVja2VkIjowLCJsaW5lc19yZWZ1dGVkIjowLCJwb3N0Y29uZGl0aW9ucyI6eyJjb25maXJtZWQiOjMsInJlcXVpcmVkIjozfX0sImRpc2Nsb3N1cmUiOnsiY29tbWl0bWVudHMiOnt9LCJ2ZXJzaW9uIjoib3BlbmFkYXB0LnB1YmxpYy1kaXNjbG9zdXJlL3YxIn0sImV2aWRlbmNlX3Njb3BlIjp7ImJhc2lzIjoicG9zdF9zYXZlX3NjcmVlbiIsImNoZWNrX2xldmVsIjoic2FtZV9zY3JlZW4iLCJub3RfY292ZXJlZCI6WyJzZXJ2ZXJfc2lkZV9hc3luY19lZmZlY3RzIiwib3V0Ym91bmRfZWZmZWN0cyIsImNoYW5nZXNfYWZ0ZXJfcmVhZF9iYWNrIiwicmVhZF9iYWNrX3RpbWUiXSwic2NoZW1hIjoib3BlbmFkYXB0LmV2aWRlbmNlLXNjb3BlL3YxIiwid2lyZSI6eyJjaGFubmVsIjoibm9uZSIsInByb3RvY29sc19wYXJzZWQiOltdfSwid29yZCI6IlZFUklGSUVEIn0sImxpbmVzIjpbeyJjaGVjayI6ImNvbmZpcm1lZCIsIm5vdF9jaGVja2VkIjpbXSwib3BlcmF0aW9uIjoid3JpdGUiLCJzdGVwIjoyLCJzdHJlbmd0aCI6InNhbWVfc2NyZWVuIiwidGFyZ2V0X2tpbmQiOiJndWkifSx7ImNoZWNrIjoiY29uZmlybWVkIiwibm90X2NoZWNrZWQiOlsiZmllbGRfdmFsdWVzIl0sIm9wZXJhdGlvbiI6ImlycmV2ZXJzaWJsZV93cml0ZSIsInN0ZXAiOjQsInN0cmVuZ3RoIjoic2FtZV9zY3JlZW4iLCJ0YXJnZXRfa2luZCI6Imd1aSJ9XSwibW9kZWxfY2FsbHMiOjAsIm91dGNvbWUiOiJWRVJJRklFRCIsInByb2dyYW0iOnsiaWQiOiJwcm9nLTViYjIxYWEwZjJlNmFjMzIiLCJ2ZXJzaW9uX3NoYTI1NiI6IjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIifSwicmVhc29uX2NvZGUiOiJ2ZXJpZmllZCIsInN0YXJ0ZWRfaG91ciI6IjIwMjYtMTEtMjBUMjM6MDA6MDBaIiwic3RlcHMiOnsib2siOjUsInRvdGFsIjo1fX0sInByZWRpY2F0ZVR5cGUiOiJodHRwczovL29wZW5hZGFwdC5haS9yZWNvcmQvcnVuL3YxIiwic3ViamVjdCI6W3siZGlnZXN0Ijp7InNoYTI1NiI6IjExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTEifSwibmFtZSI6InJlcG9ydC5qc29uIn0seyJkaWdlc3QiOnsic2hhMjU2IjoiMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMiJ9LCJuYW1lIjoiYnVuZGxlIn1dfQ==", + "payloadType": "application/vnd.in-toto+json", + "signatures": [ + { + "keyid": "seal-ed25519-b7a5ba90250d87f2", + "sig": "LONdzSgJK/tIqQpgWzOySek0TpnLd93SpBrNtctD777cwowqXWYVaX4TFuI+Y61PNWcHfA5qmzOZO4uATgytCA==" + } + ] + }, + "expected": { + "ok": false, + "reason": "inconsistent", + "signer_lines": [ + "Not verified: the receipt contradicts itself" + ] + }, + "registry": "registry.json" +} diff --git a/packages/types/tests/vectors/record-run-v1/generate.py b/packages/types/tests/vectors/record-run-v1/generate.py index 534766e761..cb163893dd 100644 --- a/packages/types/tests/vectors/record-run-v1/generate.py +++ b/packages/types/tests/vectors/record-run-v1/generate.py @@ -245,6 +245,14 @@ def add(name, description, document, expected, openings=None): screen = copy.deepcopy(scoped) screen["predicate"]["evidence_scope"].update( {"check_level": "same_screen", "basis": "post_save_screen"}) + for line in screen["predicate"]["lines"]: + line.update(strength="same_screen", not_checked=[]) + unread = copy.deepcopy(screen) + unread["predicate"]["lines"][1]["not_checked"] = ["field_values"] + add("evidence-scope-screen-with-unread-fields", + "A VERIFIED post_save_screen record whose own line says a field value went unchecked: refused.", + _signed_raw(unread), {"ok": False, "reason": "inconsistent", + "signer_lines": [r.refusal_line("inconsistent")]}) add("valid-evidence-scope-post-save-screen", "A run checked the way a careful person checks: after the save the form closed, no error " "showed and every value was read on the screen. VERIFIED with basis post_save_screen.", diff --git a/packages/types/tests/vectors/record-run-v1/valid-evidence-scope-post-save-screen.json b/packages/types/tests/vectors/record-run-v1/valid-evidence-scope-post-save-screen.json index 6fe4ce9faa..06ed76882d 100644 --- a/packages/types/tests/vectors/record-run-v1/valid-evidence-scope-post-save-screen.json +++ b/packages/types/tests/vectors/record-run-v1/valid-evidence-scope-post-save-screen.json @@ -1,12 +1,12 @@ { "description": "A run checked the way a careful person checks: after the save the form closed, no error showed and every value was read on the screen. VERIFIED with basis post_save_screen.", "document": { - "payload": "eyJfdHlwZSI6Imh0dHBzOi8vaW4tdG90by5pby9TdGF0ZW1lbnQvdjEiLCJwcmVkaWNhdGUiOnsiY2hlY2tzIjp7ImF1dGhvcml6YXRpb24iOnsiY29uZmlybWVkIjowLCJyZXF1aXJlZCI6MH0sImVmZmVjdHMiOnsiY29uZmlybWVkIjoyLCJyZXF1aXJlZCI6Mn0sImlkZW50aXR5Ijp7ImNvbmZpcm1lZCI6NSwicmVxdWlyZWQiOjV9LCJsaW5lc19jb25maXJtZWQiOjIsImxpbmVzX25vdF9jaGVja2VkIjowLCJsaW5lc19yZWZ1dGVkIjowLCJwb3N0Y29uZGl0aW9ucyI6eyJjb25maXJtZWQiOjMsInJlcXVpcmVkIjozfX0sImRpc2Nsb3N1cmUiOnsiY29tbWl0bWVudHMiOnt9LCJ2ZXJzaW9uIjoib3BlbmFkYXB0LnB1YmxpYy1kaXNjbG9zdXJlL3YxIn0sImV2aWRlbmNlX3Njb3BlIjp7ImJhc2lzIjoicG9zdF9zYXZlX3NjcmVlbiIsImNoZWNrX2xldmVsIjoic2FtZV9zY3JlZW4iLCJub3RfY292ZXJlZCI6WyJzZXJ2ZXJfc2lkZV9hc3luY19lZmZlY3RzIiwib3V0Ym91bmRfZWZmZWN0cyIsImNoYW5nZXNfYWZ0ZXJfcmVhZF9iYWNrIiwicmVhZF9iYWNrX3RpbWUiXSwic2NoZW1hIjoib3BlbmFkYXB0LmV2aWRlbmNlLXNjb3BlL3YxIiwid2lyZSI6eyJjaGFubmVsIjoibm9uZSIsInByb3RvY29sc19wYXJzZWQiOltdfSwid29yZCI6IlZFUklGSUVEIn0sImxpbmVzIjpbeyJjaGVjayI6ImNvbmZpcm1lZCIsIm5vdF9jaGVja2VkIjpbXSwib3BlcmF0aW9uIjoid3JpdGUiLCJzdGVwIjoyLCJzdHJlbmd0aCI6InJlYWRfYmFjayIsInRhcmdldF9raW5kIjoiZ3VpIn0seyJjaGVjayI6ImNvbmZpcm1lZCIsIm5vdF9jaGVja2VkIjpbImZpZWxkX3ZhbHVlcyJdLCJvcGVyYXRpb24iOiJpcnJldmVyc2libGVfd3JpdGUiLCJzdGVwIjo0LCJzdHJlbmd0aCI6InJlYWRfYmFjayIsInRhcmdldF9raW5kIjoiZ3VpIn1dLCJtb2RlbF9jYWxscyI6MCwib3V0Y29tZSI6IlZFUklGSUVEIiwicHJvZ3JhbSI6eyJpZCI6InByb2ctNWJiMjFhYTBmMmU2YWMzMiIsInZlcnNpb25fc2hhMjU2IjoiMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMiJ9LCJyZWFzb25fY29kZSI6InZlcmlmaWVkIiwic3RhcnRlZF9ob3VyIjoiMjAyNi0xMS0yMFQyMzowMDowMFoiLCJzdGVwcyI6eyJvayI6NSwidG90YWwiOjV9fSwicHJlZGljYXRlVHlwZSI6Imh0dHBzOi8vb3BlbmFkYXB0LmFpL3JlY29yZC9ydW4vdjEiLCJzdWJqZWN0IjpbeyJkaWdlc3QiOnsic2hhMjU2IjoiMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMSJ9LCJuYW1lIjoicmVwb3J0Lmpzb24ifSx7ImRpZ2VzdCI6eyJzaGEyNTYiOiIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyIn0sIm5hbWUiOiJidW5kbGUifV19", + "payload": "eyJfdHlwZSI6Imh0dHBzOi8vaW4tdG90by5pby9TdGF0ZW1lbnQvdjEiLCJwcmVkaWNhdGUiOnsiY2hlY2tzIjp7ImF1dGhvcml6YXRpb24iOnsiY29uZmlybWVkIjowLCJyZXF1aXJlZCI6MH0sImVmZmVjdHMiOnsiY29uZmlybWVkIjoyLCJyZXF1aXJlZCI6Mn0sImlkZW50aXR5Ijp7ImNvbmZpcm1lZCI6NSwicmVxdWlyZWQiOjV9LCJsaW5lc19jb25maXJtZWQiOjIsImxpbmVzX25vdF9jaGVja2VkIjowLCJsaW5lc19yZWZ1dGVkIjowLCJwb3N0Y29uZGl0aW9ucyI6eyJjb25maXJtZWQiOjMsInJlcXVpcmVkIjozfX0sImRpc2Nsb3N1cmUiOnsiY29tbWl0bWVudHMiOnt9LCJ2ZXJzaW9uIjoib3BlbmFkYXB0LnB1YmxpYy1kaXNjbG9zdXJlL3YxIn0sImV2aWRlbmNlX3Njb3BlIjp7ImJhc2lzIjoicG9zdF9zYXZlX3NjcmVlbiIsImNoZWNrX2xldmVsIjoic2FtZV9zY3JlZW4iLCJub3RfY292ZXJlZCI6WyJzZXJ2ZXJfc2lkZV9hc3luY19lZmZlY3RzIiwib3V0Ym91bmRfZWZmZWN0cyIsImNoYW5nZXNfYWZ0ZXJfcmVhZF9iYWNrIiwicmVhZF9iYWNrX3RpbWUiXSwic2NoZW1hIjoib3BlbmFkYXB0LmV2aWRlbmNlLXNjb3BlL3YxIiwid2lyZSI6eyJjaGFubmVsIjoibm9uZSIsInByb3RvY29sc19wYXJzZWQiOltdfSwid29yZCI6IlZFUklGSUVEIn0sImxpbmVzIjpbeyJjaGVjayI6ImNvbmZpcm1lZCIsIm5vdF9jaGVja2VkIjpbXSwib3BlcmF0aW9uIjoid3JpdGUiLCJzdGVwIjoyLCJzdHJlbmd0aCI6InNhbWVfc2NyZWVuIiwidGFyZ2V0X2tpbmQiOiJndWkifSx7ImNoZWNrIjoiY29uZmlybWVkIiwibm90X2NoZWNrZWQiOltdLCJvcGVyYXRpb24iOiJpcnJldmVyc2libGVfd3JpdGUiLCJzdGVwIjo0LCJzdHJlbmd0aCI6InNhbWVfc2NyZWVuIiwidGFyZ2V0X2tpbmQiOiJndWkifV0sIm1vZGVsX2NhbGxzIjowLCJvdXRjb21lIjoiVkVSSUZJRUQiLCJwcm9ncmFtIjp7ImlkIjoicHJvZy01YmIyMWFhMGYyZTZhYzMyIiwidmVyc2lvbl9zaGEyNTYiOiIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyIn0sInJlYXNvbl9jb2RlIjoidmVyaWZpZWQiLCJzdGFydGVkX2hvdXIiOiIyMDI2LTExLTIwVDIzOjAwOjAwWiIsInN0ZXBzIjp7Im9rIjo1LCJ0b3RhbCI6NX19LCJwcmVkaWNhdGVUeXBlIjoiaHR0cHM6Ly9vcGVuYWRhcHQuYWkvcmVjb3JkL3J1bi92MSIsInN1YmplY3QiOlt7ImRpZ2VzdCI6eyJzaGEyNTYiOiIxMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExIn0sIm5hbWUiOiJyZXBvcnQuanNvbiJ9LHsiZGlnZXN0Ijp7InNoYTI1NiI6IjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIifSwibmFtZSI6ImJ1bmRsZSJ9XX0=", "payloadType": "application/vnd.in-toto+json", "signatures": [ { "keyid": "seal-ed25519-b7a5ba90250d87f2", - "sig": "Ths6W6pYCrKEi0oaXeyEy25pXqi2GFCtyNVUlDsomsc74jHgefZYfr+jfYf003zXungwhAL8uWX6pvxFXYR2AQ==" + "sig": "hXj0ITlJ4EjIhneWKhWLnDNHtT2rUrz72aiJh7ZTI8ZwvE0TrJWodVcttC7X6MnSeZogdSauxrQP4/4l/eh3CQ==" } ] }, diff --git a/tests/test_post_save_screen_parity.py b/tests/test_post_save_screen_parity.py index 958a53ba8f..4e51efa867 100644 --- a/tests/test_post_save_screen_parity.py +++ b/tests/test_post_save_screen_parity.py @@ -40,7 +40,11 @@ def _types_path(case): def _flow_path(case): flow = pytest.importorskip("openadapt_flow.evidence_basis") scope = flow.evidence_scope_for_run( - {"checked_how": case["level"], "minimum": "same_screen"}, + { + "checked_how": case["level"], + "minimum": "same_screen", + "saves": [{"step_id": "save", "checked_how": case["level"]}], + }, "VERIFIED", read_back_at=T, screen_checks=[case["check"]], @@ -93,7 +97,12 @@ def _wrap_path(case): level = CheckLevel.from_label(case["level"]) contract = { "schema_version": "test", - "evidence_scope": build_evidence_scope(level, basis=basis, read_back_at=T), + "evidence_scope": build_evidence_scope( + level, + basis=basis, + read_back_at=T, + screen_checks=[case["check"]] if basis else (), + ), } receipt = _build_receipt( outcome=WrapOutcome.CONFIRMED, @@ -109,7 +118,13 @@ def _wrap_path(case): @pytest.mark.parametrize("case", CASES, ids=[c["name"] for c in CASES]) -def test_every_path_gives_the_same_word(case) -> None: +def test_every_path_gives_the_same_word(case, monkeypatch) -> None: + # The wrap path relays a Contract receipt's word. Here the Contract + # receipt is a stand-in, so verify-run's own schema check is stubbed; + # test_a_wrap_word_needs_a_valid_contract_receipt runs it for real. + import openadapt_flow.verify_run as verify_run_mod + + monkeypatch.setattr(verify_run_mod, "receipt_problem", lambda receipt: None) expected = (case["word"], case["basis"]) assert _types_path(case) == expected assert _flow_path(case) == expected @@ -153,7 +168,10 @@ def test_verify_prints_the_check_and_labels_shown_as_older() -> None: from openadapt.receipt_verify import _check_line current = build_evidence_scope( - CheckLevel.SAME_SCREEN, basis="post_save_screen", read_back_at=T + CheckLevel.SAME_SCREEN, + basis="post_save_screen", + read_back_at=T, + screen_checks=[CASES[0]["check"]], ) assert ( _check_line(current) @@ -165,3 +183,66 @@ def test_verify_prints_the_check_and_labels_shown_as_older() -> None: assert evidence_scope_problem(older) is None line = _check_line(older) assert line.startswith("Check: SHOWN (older format") + + +def test_a_wrap_word_needs_a_valid_contract_receipt() -> None: + from openadapt_flow.verify_run import receipt_sha256 + + from openadapt.wrap_sdk import WrapOutcome, _build_receipt, wrap_receipt_word + + # Not a verify-run receipt: verify-run's own checks refuse it. + contract = { + "schema_version": "test", + "evidence_scope": build_evidence_scope( + CheckLevel.SYSTEM_OF_RECORD, basis="system_api", read_back_at=T + ), + } + receipt = _build_receipt( + outcome=WrapOutcome.CONFIRMED, + checked_how="system_of_record", + action="save", + request_key="k", + arguments_sha256="0" * 64, + dispatched=True, + contract_receipt_sha256=receipt_sha256(contract), + ) + assert wrap_receipt_word(receipt, contract) == "RECORDED" + + +def test_a_wrap_word_needs_an_intact_wrap_receipt(monkeypatch) -> None: + import openadapt_flow.verify_run as verify_run_mod + from openadapt_flow.verify_run import receipt_sha256 + + from openadapt.wrap_sdk import WrapOutcome, _build_receipt, wrap_receipt_word + + monkeypatch.setattr(verify_run_mod, "receipt_problem", lambda receipt: None) + contract = { + "evidence_scope": build_evidence_scope( + CheckLevel.SYSTEM_OF_RECORD, basis="system_api", read_back_at=T + ) + } + receipt = _build_receipt( + outcome=WrapOutcome.CONFIRMED, + checked_how="system_of_record", + action="save", + request_key="k", + arguments_sha256="0" * 64, + dispatched=True, + contract_receipt_sha256=receipt_sha256(contract), + ) + assert wrap_receipt_word(receipt, contract) == "VERIFIED" + # Only the outcome and the contract digest: the wrap digest doesn't match. + bare = { + "outcome": "confirmed", + "contract_receipt_sha256": receipt_sha256(contract), + } + assert wrap_receipt_word(bare, contract) == "RECORDED" + edited = dict(receipt.to_dict(), action="other") + assert wrap_receipt_word(edited, contract) == "RECORDED" + + +def test_the_launcher_names_the_same_older_word_as_types() -> None: + # receipt_verify names SHOWN itself so it works with older openadapt-types. + from openadapt_types.check_level import LEGACY_WORDS + + assert LEGACY_WORDS == frozenset({"SHOWN"}) From 176533baa590448e4bfaaf30ec2ccc6da9970047 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 18:36:48 -0500 Subject: [PATCH 06/17] fix(receipts): review round 2: screen basis needs every line confirmed, step-bound checks, kernel verifier and mint rules, wrap outcome --- openadapt/seal_view/viewer.html | 2 +- openadapt/wrap_sdk.py | 9 ++- .../flow/openadapt_flow/evidence_basis.py | 61 +++++++++++---- packages/flow/tests/test_post_save_screen.py | 77 ++++++++++++++----- packages/kernel/CHANGELOG.md | 10 ++- .../kernel/src/openadapt_kernel/copilot.py | 8 ++ .../src/openadapt_kernel/receipt_bridge.py | 15 +++- .../tests/test_post_save_screen_bridge.py | 55 ++++++++++++- packages/seal-view/src/lib/receiptRecord.mjs | 4 +- packages/types/CHANGELOG.md | 10 ++- .../types/openadapt_types/evidence_scope.py | 19 ++--- packages/types/tests/test_post_save_screen.py | 15 +++- ...nce-scope-screen-with-unchecked-write.json | 21 +++++ .../tests/vectors/record-run-v1/generate.py | 8 ++ tests/test_post_save_screen_parity.py | 25 +++++- 15 files changed, 274 insertions(+), 65 deletions(-) create mode 100644 packages/types/tests/vectors/record-run-v1/evidence-scope-screen-with-unchecked-write.json diff --git a/openadapt/seal_view/viewer.html b/openadapt/seal_view/viewer.html index c8f9410ac9..ddd95d8865 100644 --- a/openadapt/seal_view/viewer.html +++ b/openadapt/seal_view/viewer.html @@ -24,7 +24,7 @@ `);if(n<0)return null;let o=e.slice(0,n),r=e.slice(n+2),a=o.split(` `);if(a.length<3||!/^\d+$/.test(a[1]))return null;let i;try{i=xt(a[2])}catch{return null}let l=eo(`${o} `),p=a[0].indexOf(" - "),c=p>=0?a[0].slice(0,p):a[0],g=p>=0?a[0].slice(p+3):null;if(g!==null&&!/^\d+$/.test(g))return null;let h=g===null?null:BigInt(g);for(let d of r.split(` -`)){if(!d.startsWith("— "))continue;let f=d.slice(2).split(" ");if(f.length<2)continue;let u=f.slice(0,-1).join(" "),v;try{v=xt(f.at(-1))}catch{continue}let m=At(v.slice(0,4));for(let b of t)if(!(c!==b.origin||u!==b.origin)&&b.logId.slice(0,8)===m&&await Ts(b,v.slice(4),l))return{origin:a[0],size:BigInt(a[1]),root:i,treeId:h}}return null}var yn=async e=>At(await bn(eo(Ce(e)))),Cc=(e,t)=>eo(`${Ss}\0${Ce({nonce:t,...e})}`);async function Pc(e){try{let t=Ns(new TextDecoder().decode(e));return t.length!==44||At(t.slice(0,12))!==Tc?null:t.slice(12)}catch{return null}}async function to(e,t,n,o){return no({seal_sha256:await yn(e)},t,n,o)}async function $s(e,t,n,o){let r;try{if(typeof e?.payload!="string")throw new Error("payload");r=xt(e.payload)}catch{return{ok:!1,reason:"anchor_malformed",steps:[{id:"anchorEntry",result:"fail"}]}}let a=At(await bn(r));return no({receipt_payload_sha256:a},t,n,o)}async function no(e,t,n,o){let r=[],a=(H,G,V={})=>({ok:H,reason:G,steps:r,...V});if(t==null)return a(!1,"anchor_missing");let i,l,p;try{if(t.schema!==Ss)throw new Error("schema");if(i=String(t.nonce),l=t.entry,p=Object.fromEntries(Object.keys(e).map(H=>[H,t[H]])),!ks.test(i)||!l||!Object.values(p).every(H=>typeof H=="string"&&ks.test(H)))throw new Error("format")}catch{return r.push({id:"anchorEntry",result:"fail"}),a(!1,"anchor_malformed")}let c=At(new Uint8Array(await Qn().digest("SHA-512",Cc(e,i))));if(Object.keys(e).some(H=>p[H]!==e[H])||t.statement_sha512!==c)return r.push({id:"anchorEntry",result:"fail"}),a(!1,"anchor_mismatch");let g,h,d,f,u,v,m,b,_,x,w,E;try{if(g=String(l.uuid),h=String(l.body),d=xt(h),f=JSON.parse(new TextDecoder().decode(d)),u=l.integratedTime,v=String(l.logID),m=l.logIndex,!Number.isInteger(u)||!Number.isInteger(m))throw new Error("int");b=xt(l.verification.signedEntryTimestamp),_=l.verification.inclusionProof,x=f.spec.data.hash,w=xt(f.spec.signature.content),E=xt(f.spec.signature.publicKey.content)}catch{return r.push({id:"anchorEntry",result:"fail"}),a(!1,"anchor_malformed")}let R={uuid:g,logIndex:m,integratedTime:u,logId:v},S=(H,G)=>(r.push({id:H,result:"fail"}),a(!1,G,R));if(f.kind!=="hashedrekord"||f.apiVersion!=="0.0.1")return S("anchorEntry","anchor_malformed");if(x?.algorithm!=="sha512"||x?.value!==c)return S("anchorEntry","anchor_mismatch");r.push({id:"anchorEntry",result:"pass"});let A=await Pc(E);if(!A||!lr(A,n))return S("anchorKey","anchor_key_mismatch");if(!await as(n,ir(c),w))return S("anchorKey","anchor_bad_signature");r.push({id:"anchorKey",result:"pass"});let L=o.find(H=>H.logId===v);if(!L)return S("anchorTime","anchor_unknown_log");let P=eo(Ce({body:h,integratedTime:u,logID:v,logIndex:m}));if(!await Ts(L,b,P))return S("anchorTime","anchor_bad_timestamp");r.push({id:"anchorTime",result:"pass"});let $=await Rc(d);if(!g.endsWith(At($)))return S("anchorInclusion","anchor_bad_inclusion");let O,M,k;try{k=BigInt(_.treeSize),O=await Mc(_.logIndex,_.treeSize,$,_.hashes.map(ir)),M=ir(_.rootHash)}catch{return S("anchorInclusion","anchor_malformed")}if(!O||!lr(O,M))return S("anchorInclusion","anchor_bad_inclusion");r.push({id:"anchorInclusion",result:"pass"});let B=await Ic(String(_.checkpoint),[L]);return!B||!lr(B.root,M)||B.size!==k||g.length===80&&B.treeId!==null&&g.slice(0,16)!==B.treeId.toString(16).padStart(16,"0")?S("anchorCheckpoint","anchor_bad_checkpoint"):(r.push({id:"anchorCheckpoint",result:"pass"}),a(!0,null,R))}var Oc=(e,t)=>!!(t&&e?.scope?.seal_key_ids?.includes(t.key_id));function As(e){if(e==null||et(e)!==null)return null;try{return JSON.parse(e)}catch{return null}}async function Rs(e,t,{requireAnchor:n=!1,requireAuthorization:o=!1,logKeys:r=null}={}){let a=await ps(e.sealText,e.report,t,"report.json"),i=[...a.steps],l=(_,x,w={})=>({...a,ok:_,reason:x,steps:i,sealOk:a.ok,...w});if(!a.ok)return l(!1,a.reason);let p=r||[await vn(mn)],c=_=>{let x=Gt(t).filter(w=>w.key_id===_&&w.status==="active");return x.length===1?Pe(x[0].public_key):null},g=null,h=null,d=null;if(e.auth){let _=await bs(e.auth.statement,e.auth.sig);if(i=[...i,..._.steps],!_.ok)return l(!1,_.reason);let x=null;try{x=JSON.parse(new TextDecoder().decode(e.report))}catch{x=null}d=x?.started_at??null;let w=ys(a.seal,x,_),E={auth_not_referenced:"authRef",auth_reference_mismatch:"authRef",auth_scope_mismatch:"authScope",auth_bundle_mismatch:"authBundle"};if(w){let R=E[w]||"authRef";for(let S of["authRef","authScope","authBundle"]){if(S===R)break;i=[...i,{id:S,result:"pass"}]}return i=[...i,{id:R,result:"fail"}],l(!1,w)}if(i=[...i,{id:"authRef",result:"pass"},{id:"authScope",result:"pass"},{id:"authBundle",result:"pass"}],g={login:_.login,fingerprint:_.fingerprint,sha256:_.sha256,publicKey:_.publicKey},e.auth.anchorText!=null){let R=As(e.auth.anchorText),A=Oc(_.statement,R)?c(R.key_id):null,L=R?A?await no({run_authorization_sha256:_.sha256,signature_sha256:_.signatureSha256},R,A,p):{ok:!1,reason:"anchor_key_mismatch"}:{ok:!1,reason:"anchor_malformed"};if(i=[...i,{id:"authLogged",result:L.ok?"pass":"fail"}],!L.ok)return l(!1,`authorization_${L.reason}`,{authorizedBy:g});h=L.integratedTime}}else if(o)return i=[...i,{id:"authShape",result:"fail"}],l(!1,"auth_missing");if(e.anchorText==null){let _=sr(h,d,null);return n?(i=[...i,{id:"anchorEntry",result:"fail"}],l(!1,"anchor_missing",{authorizedBy:g,timing:_})):l(!0,null,{authorizedBy:g,timing:_})}let f=As(e.anchorText);if(!f)return i=[...i,{id:"anchorEntry",result:"fail"}],l(!1,"anchor_malformed",{authorizedBy:g});let u=c(a.seal.key_id),v=await to(a.seal,f,u,p);i=[...i,...v.steps];let m=sr(h,d,v.ok?v.integratedTime:null),b=_s(h,v.ok?v.integratedTime:null);return l(v.ok,v.reason,{authorizedBy:g,timing:m,authAnchorTime:h,authorizationVsSeal:b,anchor:v.ok?{uuid:v.uuid,logIndex:v.logIndex,integratedTime:v.integratedTime,logId:v.logId}:null})}var Lc="https://in-toto.io/Statement/v1",zc="https://openadapt.ai/record/run/v1",Ms="application/vnd.in-toto+json",Dc="openadapt.receipt-card/v1",Fc="openadapt.receipt-openings/v1",Hc="openadapt.receipt-keys/v1",Ds="openadapt.public-disclosure/v1",jc="openadapt.receipt-commitment/v1",Is=256,_n=2**53-1,Gc=65536,Uc=["this_computer","customer_key","openadapt_cloud","public_log","demo"],Cs=["this_computer","customer_key","openadapt_cloud","public_log"],Bc={this_computer:"Signed by this computer",customer_key:"Signed by {org}'s key",openadapt_cloud:"Countersigned by OpenAdapt Cloud",public_log:"Logged publicly",demo:"Demo key: checks only in this demo"},Kc={unknown_signer:"Not verified: unknown signer",unknown_role:"Not verified: unknown signer role",unknown_schema:"Not verified: unknown receipt format",unsigned:"Not verified: no signature",revoked_key:"Not verified: the signing key was revoked",bad_signature:"Not verified: the receipt was changed after it was signed",mixed_demo:"Not verified: a demo key signed alongside a real one",embedded_content:"Not verified: the receipt holds embedded content",opening_mismatch:"Not verified: a disclosed value doesn't match the receipt",disclosure_not_allowed:"Not verified: the card reveals a field it may not",inconsistent:"Not verified: the receipt contradicts itself",malformed:"Not verified: malformed receipt",verifier_unavailable:"Not verified: this browser can't check Ed25519 signatures"},Wc=e=>Kc[e]||"Not verified",Rt=/^[a-f0-9]{64}$/,Vc=/^[a-f0-9]{64}$/,qc=/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:00:00Z$/,oo=/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$/,Zc=/^prog-[a-f0-9]{16}$/,Yc=/^[a-z][a-z0-9_]{0,47}$/,Jc=/^[A-Za-z0-9 ._-]{1,48}$/,cr=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Fs={program_name:/^[A-Za-z0-9 ._-]{1,48}$/,flow_version:/^[0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,6}$/,github_login:/^[A-Za-z0-9-]{1,39}$/,run_id:/^[A-Za-z0-9._:-]{1,128}$/},Xc={[Ds]:["program_name","flow_version","github_login"]},Qc=["VERIFIED","STOPPED","UNKNOWN","FAILED"],ed=["report.json","report.canonical","bundle","evidence","payload"],td=["application/json","application/cbor","text/plain","text/csv","application/pdf","application/octet-stream"],nd=["tx_receipt","write_receipt"],od=["ehr","payer_portal","bank","erp","crm","government_portal","email","other"],rd=["portal_read_back","api","acknowledgment_message"],Hs=["portal_read_back","api"],ad=["sent","acknowledged","recorded_as_intended","recorded_differently"],sd=["read_back","acknowledgment","none"],id=["each_item","problems_only","not_gated"],ld=["person","agent","none"],cd={sent:["rejected_by_counterparty","ambiguous_key","receiver_unreachable","not_found","no_answer_by_deadline"],acknowledged:["ambiguous_key","not_found","no_answer_by_deadline"],recorded_as_intended:["conflicting_report"],recorded_differently:["conflicting_report"]},dd=/^(?:counterparty|observed_at|reason|field\.[0-9]{1,2})$/,pd=/^(?:principal|scope|approved_at)$/,ud=/^confirmations\.([0-9]{1,2})\.(counterparty|observed_at|reason|field\.[0-9]{1,2})$/,fd=/^approval\.(principal|scope|approved_at)$/,hd={counterparty:/^(?:ehr|payer_portal|bank|erp|crm|government_portal|email|other):cp-[a-f0-9]{16}$/,observed_at:oo,reason:/^(?:rejected_by_counterparty|conflicting_report|ambiguous_key|receiver_unreachable|not_found|no_answer_by_deadline)$/,field:/^[a-z][a-z0-9_]{0,31}:[a-f0-9]{64}(?::differs)?$/,principal:/^(?:person|agent):pr-[a-f0-9]{16}$/,scope:Rt,approved_at:oo},gd=["gui","api"],md=["write","irreversible_write"],bd=["confirmed","refuted","not_checked"],vd=["read_back","same_screen","none"],yd=["effect_not_declared","approved_unverified","field_values","postconditions","uncertain"],_d="openadapt.evidence-scope/v1",xd=["unchecked","same_screen","reopened","separate_session","system_of_record","counterparty_confirmed"],kd=["VERIFIED","SHOWN","CONFIRMED","ATTESTED","RECORDED"],Ps={post_save_screen:"same_screen",reopened_record:"reopened",separate_session:"separate_session",fresh_reload:"separate_session",system_api:"system_of_record",activity_log:"system_of_record",db_frame:"system_of_record",owned_connection:"system_of_record"},js=["post_save_screen","reopened_record"],wd=["none","browser_network","http_proxy","api_client","db_connection"],Sd=["http","graphql","fhir","sql","websocket","grpc","smtp"],Ed=["server_side_async_effects","outbound_effects","changes_after_read_back","fields_not_read","other_records","other_actors","read_back_time"],Nd=["server_side_async_effects","outbound_effects"],Td=720*3600,Os=/^(?!.*:\/\/)[A-Za-z0-9][A-Za-z0-9._:@+/ -]{0,127}$/,$d={VERIFIED:["VERIFIED"],CONFIRMED:["VERIFIED"],SHOWN:["UNKNOWN","STOPPED","FAILED"],ATTESTED:["UNKNOWN","STOPPED","FAILED"],RECORDED:["UNKNOWN","STOPPED","FAILED"]},I=class extends Error{constructor(t,n=""){super(n||t),this.reason=t}},Ls=(e,t="")=>({ok:!1,reason:e,detail:t,signerLines:[Wc(e)],outcome:null,demo:!1,disclosed:{}}),Ad=/data:[a-z]+\//i,Rd=/[a-z][a-z0-9+.-]*:\/\//i,Md=/[A-Za-z0-9+/_-]{96,}={0,2}/,Id=["iVBORw0KGgo","/9j/","R0lGOD","UklGR","PHN2Zy"];function dr(e){let t=e.toLowerCase();return[...e].length>256||Ad.test(e)||Rd.test(e)||Md.test(e)||Id.some(n=>e.startsWith(n))||t.includes("e!==null&&typeof e=="object"&&!Array.isArray(e);function De(e,t,n=[],o=""){if(!je(e))throw new I("malformed",`${o} is an object`);for(let r of Object.keys(e))if(!t.includes(r)&&!n.includes(r))throw new I("malformed",`${o}.${r} is not a field`);for(let r of t)if(!(r in e))throw new I("malformed",`${o}.${r} is missing`)}function lt(e,t,n,o){if(!Number.isInteger(e)||en)throw new I("malformed",`${o} is an integer from ${t} to ${n}`)}function J(e,t,n){if(!(typeof e=="string"&&(Array.isArray(t)?t.includes(e):t.test(e))))throw new I("malformed",`${n} is not valid`)}function Cd(e,t){De(e,["required","confirmed"],[],t),lt(e.required,0,_n,`${t}.required`),lt(e.confirmed,0,_n,`${t}.confirmed`)}function Pd(e){if(De(e,["_type","subject","predicateType","predicate"],[],"$"),!Array.isArray(e.subject)||e.subject.length<1||e.subject.length>4)throw new I("malformed","subject has 1 to 4 entries");for(let[o,r]of e.subject.entries())De(r,["name","digest"],["media_type"],`subject[${o}]`),J(r.name,ed,`subject[${o}].name`),"media_type"in r&&J(r.media_type,td,`subject[${o}].media_type`),De(r.digest,["sha256"],[],`subject[${o}].digest`),J(r.digest.sha256,Rt,`subject[${o}].digest.sha256`);let t=e.predicate;if(De(t,["program","started_hour","outcome","steps","lines","checks","model_calls","disclosure"],["reason_code","confirmations","approval","evidence_scope"],"predicate"),De(t.program,["id","version_sha256"],[],"predicate.program"),J(t.program.id,Zc,"predicate.program.id"),J(t.program.version_sha256,Rt,"predicate.program.version_sha256"),J(t.started_hour,qc,"predicate.started_hour"),J(t.outcome,Qc,"predicate.outcome"),t.reason_code!=null&&J(t.reason_code,Yc,"predicate.reason_code"),De(t.steps,["total","ok"],[],"predicate.steps"),lt(t.steps.total,0,_n,"predicate.steps.total"),lt(t.steps.ok,0,_n,"predicate.steps.ok"),!Array.isArray(t.lines)||t.lines.length>Is)throw new I("malformed","predicate.lines");for(let[o,r]of t.lines.entries()){let a=`predicate.lines[${o}]`;if(De(r,["step","target_kind","operation","check","strength","not_checked"],["evidence"],a),"evidence"in r&&(De(r.evidence,["kind","sha256"],[],`${a}.evidence`),J(r.evidence.kind,nd,`${a}.evidence.kind`),J(r.evidence.sha256,Rt,`${a}.evidence.sha256`)),lt(r.step,0,1e4,`${a}.step`),J(r.target_kind,gd,`${a}.target_kind`),J(r.operation,md,`${a}.operation`),J(r.check,bd,`${a}.check`),J(r.strength,vd,`${a}.strength`),!Array.isArray(r.not_checked)||r.not_checked.length>5)throw new I("malformed",`${a}.not_checked`);r.not_checked.forEach((i,l)=>J(i,yd,`${a}.not_checked[${l}]`))}let n=t.checks;De(n,["identity","postconditions","effects","authorization","lines_confirmed","lines_refuted","lines_not_checked"],[],"predicate.checks");for(let o of["identity","postconditions","effects","authorization"])Cd(n[o],`predicate.checks.${o}`);for(let o of["lines_confirmed","lines_refuted","lines_not_checked"])lt(n[o],0,Is,`predicate.checks.${o}`);if(lt(t.model_calls,0,_n,"predicate.model_calls"),De(t.disclosure,["version","commitments"],[],"predicate.disclosure"),J(t.disclosure.version,[Ds],"predicate.disclosure.version"),!je(t.disclosure.commitments)||Object.keys(t.disclosure.commitments).length>16)throw new I("malformed","predicate.disclosure.commitments");for(let o of Object.values(t.disclosure.commitments))if(typeof o!="string")throw new I("malformed","a commitment is a string");if("confirmations"in t){if(!Array.isArray(t.confirmations)||t.confirmations.length>64)throw new I("malformed","predicate.confirmations");for(let[o,r]of t.confirmations.entries()){let a=`predicate.confirmations[${o}]`;if(De(r,["kind","system_kind","read_method","state","strength","differing_count","commitments"],["for_step"],a),J(r.kind,["counterparty_confirmation"],`${a}.kind`),r.for_step!=null&<(r.for_step,0,1e4,`${a}.for_step`),J(r.system_kind,od,`${a}.system_kind`),J(r.read_method,rd,`${a}.read_method`),J(r.state,ad,`${a}.state`),J(r.strength,sd,`${a}.strength`),lt(r.differing_count,0,64,`${a}.differing_count`),!je(r.commitments)||Object.keys(r.commitments).length<2||Object.keys(r.commitments).length>34)throw new I("malformed",`${a}.commitments`)}}if("approval"in t&&(De(t.approval,["mode","approver_kind","commitments"],[],"predicate.approval"),J(t.approval.mode,id,"predicate.approval.mode"),J(t.approval.approver_kind,ld,"predicate.approval.approver_kind"),!je(t.approval.commitments)||Object.keys(t.approval.commitments).length>3))throw new I("malformed","predicate.approval.commitments");if("evidence_scope"in t){let o=t.evidence_scope;De(o,["schema","check_level","word","wire","not_covered"],["basis","read_back_at","recheck_window_s","agent_used","verifier_adapter"],"predicate.evidence_scope"),J(o.schema,[_d],"predicate.evidence_scope.schema"),J(o.check_level,xd,"predicate.evidence_scope.check_level"),J(o.word,kd,"predicate.evidence_scope.word"),"basis"in o&&J(o.basis,Object.keys(Ps),"predicate.evidence_scope.basis"),De(o.wire,["channel","protocols_parsed"],[],"predicate.evidence_scope.wire"),J(o.wire.channel,wd,"predicate.evidence_scope.wire.channel");let r=o.wire.protocols_parsed;if(!Array.isArray(r)||r.length>7)throw new I("malformed","predicate.evidence_scope.wire.protocols_parsed");if(r.forEach((a,i)=>J(a,Sd,`predicate.evidence_scope.wire.protocols_parsed[${i}]`)),new Set(r).size!==r.length)throw new I("malformed","wire.protocols_parsed repeats a protocol");if(o.wire.channel==="none"&&r.length)throw new I("malformed","a run that watched no wire parsed no protocol");if("read_back_at"in o&&J(o.read_back_at,oo,"predicate.evidence_scope.read_back_at"),"recheck_window_s"in o&<(o.recheck_window_s,0,Td,"predicate.evidence_scope.recheck_window_s"),"agent_used"in o&&J(o.agent_used,Os,"predicate.evidence_scope.agent_used"),"verifier_adapter"in o&&J(o.verifier_adapter,Os,"predicate.evidence_scope.verifier_adapter"),!Array.isArray(o.not_covered)||o.not_covered.length<2||o.not_covered.length>7)throw new I("malformed","predicate.evidence_scope.not_covered");if(o.not_covered.forEach((a,i)=>J(a,Ed,`predicate.evidence_scope.not_covered[${i}]`)),new Set(o.not_covered).size!==o.not_covered.length)throw new I("malformed","not_covered repeats a code");if(!Nd.every(a=>o.not_covered.includes(a)))throw new I("malformed","not_covered must list server_side_async_effects and outbound_effects");if(o.basis!=null&&Ps[o.basis]!==o.check_level)throw new I("malformed",`basis ${o.basis} does not reach ${o.check_level}`);if(o.word==="VERIFIED"){if(!["same_screen","reopened","separate_session","system_of_record"].includes(o.check_level)||o.basis==null)throw new I("malformed","VERIFIED needs level 1 to 4 and a basis");if(o.read_back_at==null&&!o.not_covered.includes("read_back_time"))throw new I("malformed","VERIFIED needs read_back_at, or says it has none");if(js.includes(o.basis)&&o.not_covered.includes("fields_not_read"))throw new I("malformed","a screen check that did not read every field is not VERIFIED")}if(o.word==="SHOWN"&&!["same_screen","reopened"].includes(o.check_level))throw new I("malformed","SHOWN is a level 1 or 2 re-read of the acting screen");if(o.word==="SHOWN"&&o.basis!=null)throw new I("malformed","an older SHOWN block names no basis");if(o.word==="CONFIRMED"&&o.check_level!=="counterparty_confirmed")throw new I("malformed","CONFIRMED is level 5, the counterparty acknowledgment");if(o.read_back_at!=null&&o.not_covered.includes("read_back_time"))throw new I("malformed","a block with read_back_at covers the read-back time");if(o.recheck_window_s!=null&&o.read_back_at==null)throw new I("malformed","a recheck window needs read_back_at")}return{...e,predicate:{...t,reason_code:t.reason_code??null}}}function Od(e){let t=e.predicate,n=e.subject.map(a=>a.name);if(new Set(n).size!==n.length||!(n.includes("report.json")||n.includes("report.canonical")))return"subject names repeat, or the report is missing";for(let a of e.subject)if(a.name==="payload"!="media_type"in a)return"only the payload subject has a media type, and it always has one";if(t.approval){let a=t.approval;for(let[i,l]of Object.entries(a.commitments))if(!pd.test(i)||!Rt.test(l))return`approval commitment ${i} is not a known field`;if(a.mode==="not_gated"&&a.approver_kind!=="none")return"a not_gated run names no approver";if(a.approver_kind==="none"){if(Object.keys(a.commitments).length)return"an approval with no approver commits to nothing"}else if(!("principal"in a.commitments&&"scope"in a.commitments))return"an approval names its approver's principal and scope"}for(let[a,i]of Object.entries(t.disclosure.commitments))if(!Fs[a]||!Rt.test(i))return`disclosure path ${a} is not a known field`;if(t.steps.ok>t.steps.total)return"steps.ok is more than steps.total";for(let a of["identity","postconditions","effects","authorization"])if(t.checks[a].confirmed>t.checks[a].required)return`checks.${a} confirms more than it requires`;let o={confirmed:0,refuted:0,not_checked:0};for(let a of t.lines){if(o[a.check]+=1,a.check==="confirmed"&&a.strength==="none")return"a confirmed line has no strength";if(new Set(a.not_checked).size!==a.not_checked.length)return"a line repeats a not_checked code"}if(t.checks.lines_confirmed!==o.confirmed||t.checks.lines_refuted!==o.refuted||t.checks.lines_not_checked!==o.not_checked)return"check counts disagree with the lines";if(t.outcome==="VERIFIED"&&o.refuted)return"a VERIFIED receipt has a refuted line";if(t.evidence_scope&&!$d[t.evidence_scope.word].includes(t.outcome))return"the evidence scope's word disagrees with the outcome";if(t.evidence_scope&&js.includes(t.evidence_scope.basis)&&t.lines.some(a=>a.not_checked.includes("field_values")))return"a screen check says every field was read, a line says not";let r=t.lines.map(a=>a.step);for(let a=1;a0)return"differing_count disagrees with the state";if(!("counterparty"in a.commitments&&"observed_at"in a.commitments))return"a confirmation commits to its counterparty and observed_at";for(let[l,p]of Object.entries(a.commitments))if(!dd.test(l)||!Rt.test(p))return`confirmation commitment ${l} is not a known field`;let i=Object.keys(a.commitments).filter(l=>l.startsWith("field.")).length;if(a.differing_count>i)return"more differing fields than observed fields"}return null}var Ut=e=>new TextEncoder().encode(e);function Gs(...e){let t=new Uint8Array(e.reduce((o,r)=>o+r.length,0)),n=0;for(let o of e)t.set(o,n),n+=o.length;return t}var Ld=e=>Uint8Array.from(e.match(/../g),t=>parseInt(t,16));async function zd(e,t,n){let o=new Uint8Array([0]);return Re(Gs(Ut(jc),o,Ut(e),o,Ld(t),o,Ut(Ce(n))))}function Dd(e,t){let n=ud.exec(e)||fd.exec(e);if(n){let r=(n[2]||n[1]).split(".")[0];return typeof t=="string"&&hd[r].test(t)?null:`${e} does not match its field's pattern`}let o=Fs[e];return o?typeof t!="string"?`${e} is not a string`:dr(t)?`${e} holds embedded content`:o.test(t)?null:`${e} does not match its field's pattern`:`${e} is not a disclosure field`}async function zs(e,t,n){if(!je(e))throw new I("malformed","openings are an object");let o=ro(e);if(o)throw new I("embedded_content",o);let r={};for(let[a,i]of Object.entries(e)){if(n&&!n.includes(a))throw new I("disclosure_not_allowed",a);if(!je(i)||Object.keys(i).length!==2||!("salt"in i)||!("value"in i))throw new I("malformed",`the opening for ${a}`);let l=Dd(a,i.value);if(l)throw new I("malformed",l);if(!(typeof i.salt=="string"&&Vc.test(i.salt)))throw new I("malformed",`the salt for ${a}`);if(t[a]!==await zd(a,i.salt,i.value))throw new I("opening_mismatch",a);r[a]=i.value}return r}async function Fd(e){if(!je(e)||e.schema!==Hc)throw new I("unknown_schema","not an openadapt.receipt-keys/v1 registry");if(!Array.isArray(e.keys))throw new I("malformed","a registry has a keys list");let t=[];for(let n of e.keys){if(!je(n))throw new I("malformed","a registry entry is an object");if(Object.keys(n).some(a=>!["key_id","public_key","role","status","revoked_at","org"].includes(a)))throw new I("malformed","a registry entry has an unknown field");if(!Uc.includes(n.role))throw new I("unknown_role",`unknown signer role ${n.role}`);if(typeof n.public_key!="string"||!cr.test(n.public_key))throw new I("malformed","a public key is base64");let o=Pe(n.public_key);if(o.length!==32||n.key_id!==`seal-ed25519-${(await Re(o)).slice(0,16)}`)throw new I("malformed","a key id doesn't match its public key");let r=n.status??"active";if(!["active","revoked"].includes(r)||r==="revoked"&&!(typeof n.revoked_at=="string"&&oo.test(n.revoked_at)))throw new I("malformed","a key is active, or revoked with revoked_at");if(n.role==="customer_key"&&!(typeof n.org=="string"&&Jc.test(n.org)))throw new I("malformed","a customer key names its org");t.push({keyId:n.key_id,raw:o,role:n.role,status:r,revokedAt:r==="revoked"?n.revoked_at:null,org:n.role==="customer_key"?n.org:null})}if(new Set(t.map(n=>n.keyId)).size!==t.length)throw new I("malformed","a registry lists one key id twice");return t}function Hd(e,t){let n=Ut(e);return Gs(Ut(`DSSEv1 ${n.length} `),n,Ut(` ${t.length} `),t)}var jd=e=>je(e)&&e.schema===Dc;function Gd(e){if(et(e)!==null)throw new I("malformed","duplicate key");try{return JSON.parse(e)}catch{throw new I("malformed","the payload is not JSON")}}async function Ud(e,t,n){let o;try{o=await globalThis.crypto.subtle.importKey("raw",e,{name:"Ed25519"},!1,["verify"])}catch{throw new I("verifier_unavailable")}return globalThis.crypto.subtle.verify({name:"Ed25519"},o,t,n)}async function Us(e,t,{openings:n=null}={}){try{let o=await Fd(t),r=null,a=null,i=e;if(jd(e)){if(Object.keys(e).sort().join(",")!=="disclosure_version,envelope,openings,schema")throw new I("malformed","a card has exactly four fields");if(a=Xc[e.disclosure_version],!a)throw new I("unknown_schema","unknown public disclosure version");if(r=e.openings,!je(r))throw new I("malformed","a card's openings are an object");if(i=e.envelope,n!=null)throw new I("malformed","a card carries its own openings")}if(!je(i)||Object.keys(i).sort().join(",")!=="payload,payloadType,signatures")throw new I("malformed","a DSSE envelope has payloadType, payload, signatures");if(i.payloadType!==Ms)throw new I("unknown_schema","the payload is not an in-toto statement");if(typeof i.payload!="string"||!cr.test(i.payload))throw new I("malformed","the payload is not base64");let l=Pe(i.payload);if(l.length>Gc)throw new I("malformed","the payload is too large");let p=i.signatures;if(!Array.isArray(p)||!p.length)throw new I("unsigned");let c=new Map(o.map($=>[$.keyId,$])),g=Hd(Ms,l),h=[],d=new Set;for(let $ of p){if(!je($)||Object.keys($).sort().join(",")!=="keyid,sig")throw new I("malformed","a signature has keyid and sig");let O=$.keyid;if(typeof O!="string"||d.has(O))throw new I("malformed","a signature's keyid is missing or repeated");d.add(O);let M=c.get(O);if(!M)throw new I("unknown_signer",`${O} is not in the pinned registry`);if(typeof $.sig!="string"||!cr.test($.sig))throw new I("bad_signature",`${O}'s signature`);if(!await Ud(M.raw,Pe($.sig),g))throw new I("bad_signature",`${O}'s signature`);if(M.status==="revoked")throw new I("revoked_key",`${O} was revoked at ${M.revokedAt}`);h.push({keyId:O,role:M.role,line:Bc[M.role].replace("{org}",M.org||"the customer")})}let f=new Set(h.map($=>$.role)),u=f.has("demo");if(u&&f.size!==1)throw new I("mixed_demo");let v;try{v=new TextDecoder("utf-8",{fatal:!0}).decode(l)}catch{throw new I("malformed","the payload is not UTF-8")}let m=Gd(v);if(!je(m))throw new I("malformed","the payload is not an object");if(m._type!==Lc||m.predicateType!==zc)throw new I("unknown_schema","not a record/run/v1 statement");let b=Object.fromEntries(Object.entries(m).filter(([$])=>$!=="_type"&&$!=="predicateType")),_=ro(b);if(_)throw new I("embedded_content",_);let x=Pd(m);if(Ce(x)!==v)throw new I("malformed","the payload is not canonical JSON");let w=Od(x);if(w)throw new I("inconsistent",w);let E={...x.predicate.disclosure.commitments};for(let[$,O]of(x.predicate.confirmations||[]).entries())for(let[M,k]of Object.entries(O.commitments))E[`confirmations.${$}.${M}`]=k;if(x.predicate.approval)for(let[$,O]of Object.entries(x.predicate.approval.commitments))E[`approval.${$}`]=O;let R={},S=!1;if(r)R=await zs(r,E,a);else if(n!=null){if(!je(n)||Object.keys(n).sort().join(",")!=="openings,payload_sha256,schema")throw new I("malformed","a private openings file has three fields");if(n.schema!==Fc)throw new I("unknown_schema","not an openadapt.receipt-openings/v1 file");if(n.payload_sha256!==await Re(l))throw new I("opening_mismatch","the openings belong to another receipt");R=await zs(n.openings,E,null),S=!0;for(let[$,O]of(x.predicate.confirmations||[]).entries()){let M=R[`confirmations.${$}.reason`];if(M!=null&&!cd[O.state].includes(M))throw new I("inconsistent",`a ${O.state} confirmation can't have reason ${M}`)}}let A=[...h].sort(($,O)=>Cs.indexOf($.role)-Cs.indexOf(O.role)),L=[...new Set(A.map($=>$.line))],P=x.predicate.confirmations||[];return{ok:!0,reason:null,detail:"",signers:A,signerLines:L,confirmationLines:P.map(($,O)=>Kd($,R[`confirmations.${O}.observed_at`])),independent:P.map($=>Hs.includes($.read_method)),approvalLine:Bd(x.predicate.approval),outcome:x.predicate.outcome,demo:u,disclosed:R,private:S,statement:x}}catch(o){return o instanceof I?Ls(o.reason,o.message):Ls("malformed",String(o?.message||o))}}function Bd(e){return e?e.mode==="not_gated"?"Not gated: no approval was required for these writes":e.approver_kind==="none"?`Approval required for ${e.mode==="each_item"?"each item":"items that fail a check"}; no item was approved`:`Approved by ${e.approver_kind==="person"?"a person":"an agent delegate"}: ${e.mode==="each_item"?"each item":"items that failed a check"}`:"No approval recorded"}function Kd(e,t){let n=t?` at ${t}`:"";return e.state==="recorded_as_intended"?`Confirmed in the other party's system${n}`:e.state==="recorded_differently"?`Recorded differently in the other party's system${n}: ${e.differing_count} ${e.differing_count===1?"field differs":"fields differ"}`:e.state==="acknowledged"?`Acknowledged by the other party${n}`:`Sent to the other party${n}, not confirmed`}async function ht(e,t=!1){let n=await fetch(e,{cache:"no-store"});if(!n.ok)throw new Error(`${e}: ${n.status}`);return t?new Uint8Array(await n.arrayBuffer()):n.text()}async function Bs(e,t=null){let[n,o,r,a,i,l]=await Promise.all([ht(e.report,!0),ht(e.seal),e.anchor?ht(e.anchor):null,e.tsa?ht(e.tsa):null,e.tsr?ht(e.tsr,!0):null,t?Promise.all([ht(t.statement),ht(t.sig),ht(t.signers),t.anchor?ht(t.anchor):null]):null]);return{report:n,sealText:o,anchorText:r,tsaText:a,tsrBytes:i,auth:l?{statement:l[0],sig:l[1],signers:l[2],anchorText:l[3]}:null}}var Ks={VERIFIED:"HALTED",HALTED:"VERIFIED"};function Vs(e,t){let n=t||e,o=Ks[n]||"VERIFIED",r=Ks[e]||"VERIFIED";return[{id:"report-outcome",target:"report",label:"Change the outcome in the report",field:"execution_outcome",from:n,to:o,text:[`"execution_outcome": "${n}"`,`"execution_outcome": "${o}"`]},{id:"report-model-calls",target:"report",label:"Add one AI model call to the report",field:"model_calls",from:"0",to:"1",text:['"model_calls": 0','"model_calls": 1']},{id:"seal-outcome",target:"seal",label:"Change the outcome in the receipt",field:"outcome",from:e,to:r}]}function qs(e,t){if(t.target==="seal"){if(e.sealText!=null){let a=JSON.parse(e.sealText);if(a[t.field]!==t.from)throw new Error("The value to change is not in the receipt.");return{...e,sealText:JSON.stringify({...a,[t.field]:t.to},null,2),receiptText:e.receiptText?Ws(e.receiptText):e.receiptText}}if(e.receiptText!=null)return{...e,receiptText:Ws(e.receiptText)};throw new Error("The value to change is not in the receipt.")}let n=new TextDecoder().decode(e.report),[o,r]=t.text;if(!n.includes(o))throw new Error("The value to change is not in the report.");return{...e,report:new TextEncoder().encode(n.replace(o,r))}}function Ws(e){let t=JSON.parse(e),o=new TextDecoder().decode(Uint8Array.from(atob(t.payload),i=>i.charCodeAt(0))).replace(/"outcome":"(VERIFIED|STOPPED|UNKNOWN|FAILED)"/,(i,l)=>`"outcome":"${l==="VERIFIED"?"STOPPED":"VERIFIED"}"`),r=new TextEncoder().encode(o),a="";for(let i of r)a+=String.fromCharCode(i);return JSON.stringify({...t,payload:btoa(a)})}var Wd=`-----BEGIN CERTIFICATE----- +`)){if(!d.startsWith("— "))continue;let f=d.slice(2).split(" ");if(f.length<2)continue;let u=f.slice(0,-1).join(" "),v;try{v=xt(f.at(-1))}catch{continue}let m=At(v.slice(0,4));for(let b of t)if(!(c!==b.origin||u!==b.origin)&&b.logId.slice(0,8)===m&&await Ts(b,v.slice(4),l))return{origin:a[0],size:BigInt(a[1]),root:i,treeId:h}}return null}var yn=async e=>At(await bn(eo(Ce(e)))),Cc=(e,t)=>eo(`${Ss}\0${Ce({nonce:t,...e})}`);async function Pc(e){try{let t=Ns(new TextDecoder().decode(e));return t.length!==44||At(t.slice(0,12))!==Tc?null:t.slice(12)}catch{return null}}async function to(e,t,n,o){return no({seal_sha256:await yn(e)},t,n,o)}async function $s(e,t,n,o){let r;try{if(typeof e?.payload!="string")throw new Error("payload");r=xt(e.payload)}catch{return{ok:!1,reason:"anchor_malformed",steps:[{id:"anchorEntry",result:"fail"}]}}let a=At(await bn(r));return no({receipt_payload_sha256:a},t,n,o)}async function no(e,t,n,o){let r=[],a=(H,G,V={})=>({ok:H,reason:G,steps:r,...V});if(t==null)return a(!1,"anchor_missing");let i,l,p;try{if(t.schema!==Ss)throw new Error("schema");if(i=String(t.nonce),l=t.entry,p=Object.fromEntries(Object.keys(e).map(H=>[H,t[H]])),!ks.test(i)||!l||!Object.values(p).every(H=>typeof H=="string"&&ks.test(H)))throw new Error("format")}catch{return r.push({id:"anchorEntry",result:"fail"}),a(!1,"anchor_malformed")}let c=At(new Uint8Array(await Qn().digest("SHA-512",Cc(e,i))));if(Object.keys(e).some(H=>p[H]!==e[H])||t.statement_sha512!==c)return r.push({id:"anchorEntry",result:"fail"}),a(!1,"anchor_mismatch");let g,h,d,f,u,v,m,b,_,x,w,E;try{if(g=String(l.uuid),h=String(l.body),d=xt(h),f=JSON.parse(new TextDecoder().decode(d)),u=l.integratedTime,v=String(l.logID),m=l.logIndex,!Number.isInteger(u)||!Number.isInteger(m))throw new Error("int");b=xt(l.verification.signedEntryTimestamp),_=l.verification.inclusionProof,x=f.spec.data.hash,w=xt(f.spec.signature.content),E=xt(f.spec.signature.publicKey.content)}catch{return r.push({id:"anchorEntry",result:"fail"}),a(!1,"anchor_malformed")}let R={uuid:g,logIndex:m,integratedTime:u,logId:v},S=(H,G)=>(r.push({id:H,result:"fail"}),a(!1,G,R));if(f.kind!=="hashedrekord"||f.apiVersion!=="0.0.1")return S("anchorEntry","anchor_malformed");if(x?.algorithm!=="sha512"||x?.value!==c)return S("anchorEntry","anchor_mismatch");r.push({id:"anchorEntry",result:"pass"});let A=await Pc(E);if(!A||!lr(A,n))return S("anchorKey","anchor_key_mismatch");if(!await as(n,ir(c),w))return S("anchorKey","anchor_bad_signature");r.push({id:"anchorKey",result:"pass"});let L=o.find(H=>H.logId===v);if(!L)return S("anchorTime","anchor_unknown_log");let P=eo(Ce({body:h,integratedTime:u,logID:v,logIndex:m}));if(!await Ts(L,b,P))return S("anchorTime","anchor_bad_timestamp");r.push({id:"anchorTime",result:"pass"});let $=await Rc(d);if(!g.endsWith(At($)))return S("anchorInclusion","anchor_bad_inclusion");let O,M,k;try{k=BigInt(_.treeSize),O=await Mc(_.logIndex,_.treeSize,$,_.hashes.map(ir)),M=ir(_.rootHash)}catch{return S("anchorInclusion","anchor_malformed")}if(!O||!lr(O,M))return S("anchorInclusion","anchor_bad_inclusion");r.push({id:"anchorInclusion",result:"pass"});let B=await Ic(String(_.checkpoint),[L]);return!B||!lr(B.root,M)||B.size!==k||g.length===80&&B.treeId!==null&&g.slice(0,16)!==B.treeId.toString(16).padStart(16,"0")?S("anchorCheckpoint","anchor_bad_checkpoint"):(r.push({id:"anchorCheckpoint",result:"pass"}),a(!0,null,R))}var Oc=(e,t)=>!!(t&&e?.scope?.seal_key_ids?.includes(t.key_id));function As(e){if(e==null||et(e)!==null)return null;try{return JSON.parse(e)}catch{return null}}async function Rs(e,t,{requireAnchor:n=!1,requireAuthorization:o=!1,logKeys:r=null}={}){let a=await ps(e.sealText,e.report,t,"report.json"),i=[...a.steps],l=(_,x,w={})=>({...a,ok:_,reason:x,steps:i,sealOk:a.ok,...w});if(!a.ok)return l(!1,a.reason);let p=r||[await vn(mn)],c=_=>{let x=Gt(t).filter(w=>w.key_id===_&&w.status==="active");return x.length===1?Pe(x[0].public_key):null},g=null,h=null,d=null;if(e.auth){let _=await bs(e.auth.statement,e.auth.sig);if(i=[...i,..._.steps],!_.ok)return l(!1,_.reason);let x=null;try{x=JSON.parse(new TextDecoder().decode(e.report))}catch{x=null}d=x?.started_at??null;let w=ys(a.seal,x,_),E={auth_not_referenced:"authRef",auth_reference_mismatch:"authRef",auth_scope_mismatch:"authScope",auth_bundle_mismatch:"authBundle"};if(w){let R=E[w]||"authRef";for(let S of["authRef","authScope","authBundle"]){if(S===R)break;i=[...i,{id:S,result:"pass"}]}return i=[...i,{id:R,result:"fail"}],l(!1,w)}if(i=[...i,{id:"authRef",result:"pass"},{id:"authScope",result:"pass"},{id:"authBundle",result:"pass"}],g={login:_.login,fingerprint:_.fingerprint,sha256:_.sha256,publicKey:_.publicKey},e.auth.anchorText!=null){let R=As(e.auth.anchorText),A=Oc(_.statement,R)?c(R.key_id):null,L=R?A?await no({run_authorization_sha256:_.sha256,signature_sha256:_.signatureSha256},R,A,p):{ok:!1,reason:"anchor_key_mismatch"}:{ok:!1,reason:"anchor_malformed"};if(i=[...i,{id:"authLogged",result:L.ok?"pass":"fail"}],!L.ok)return l(!1,`authorization_${L.reason}`,{authorizedBy:g});h=L.integratedTime}}else if(o)return i=[...i,{id:"authShape",result:"fail"}],l(!1,"auth_missing");if(e.anchorText==null){let _=sr(h,d,null);return n?(i=[...i,{id:"anchorEntry",result:"fail"}],l(!1,"anchor_missing",{authorizedBy:g,timing:_})):l(!0,null,{authorizedBy:g,timing:_})}let f=As(e.anchorText);if(!f)return i=[...i,{id:"anchorEntry",result:"fail"}],l(!1,"anchor_malformed",{authorizedBy:g});let u=c(a.seal.key_id),v=await to(a.seal,f,u,p);i=[...i,...v.steps];let m=sr(h,d,v.ok?v.integratedTime:null),b=_s(h,v.ok?v.integratedTime:null);return l(v.ok,v.reason,{authorizedBy:g,timing:m,authAnchorTime:h,authorizationVsSeal:b,anchor:v.ok?{uuid:v.uuid,logIndex:v.logIndex,integratedTime:v.integratedTime,logId:v.logId}:null})}var Lc="https://in-toto.io/Statement/v1",zc="https://openadapt.ai/record/run/v1",Ms="application/vnd.in-toto+json",Dc="openadapt.receipt-card/v1",Fc="openadapt.receipt-openings/v1",Hc="openadapt.receipt-keys/v1",Ds="openadapt.public-disclosure/v1",jc="openadapt.receipt-commitment/v1",Is=256,_n=2**53-1,Gc=65536,Uc=["this_computer","customer_key","openadapt_cloud","public_log","demo"],Cs=["this_computer","customer_key","openadapt_cloud","public_log"],Bc={this_computer:"Signed by this computer",customer_key:"Signed by {org}'s key",openadapt_cloud:"Countersigned by OpenAdapt Cloud",public_log:"Logged publicly",demo:"Demo key: checks only in this demo"},Kc={unknown_signer:"Not verified: unknown signer",unknown_role:"Not verified: unknown signer role",unknown_schema:"Not verified: unknown receipt format",unsigned:"Not verified: no signature",revoked_key:"Not verified: the signing key was revoked",bad_signature:"Not verified: the receipt was changed after it was signed",mixed_demo:"Not verified: a demo key signed alongside a real one",embedded_content:"Not verified: the receipt holds embedded content",opening_mismatch:"Not verified: a disclosed value doesn't match the receipt",disclosure_not_allowed:"Not verified: the card reveals a field it may not",inconsistent:"Not verified: the receipt contradicts itself",malformed:"Not verified: malformed receipt",verifier_unavailable:"Not verified: this browser can't check Ed25519 signatures"},Wc=e=>Kc[e]||"Not verified",Rt=/^[a-f0-9]{64}$/,Vc=/^[a-f0-9]{64}$/,qc=/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:00:00Z$/,oo=/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$/,Zc=/^prog-[a-f0-9]{16}$/,Yc=/^[a-z][a-z0-9_]{0,47}$/,Jc=/^[A-Za-z0-9 ._-]{1,48}$/,cr=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Fs={program_name:/^[A-Za-z0-9 ._-]{1,48}$/,flow_version:/^[0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,6}$/,github_login:/^[A-Za-z0-9-]{1,39}$/,run_id:/^[A-Za-z0-9._:-]{1,128}$/},Xc={[Ds]:["program_name","flow_version","github_login"]},Qc=["VERIFIED","STOPPED","UNKNOWN","FAILED"],ed=["report.json","report.canonical","bundle","evidence","payload"],td=["application/json","application/cbor","text/plain","text/csv","application/pdf","application/octet-stream"],nd=["tx_receipt","write_receipt"],od=["ehr","payer_portal","bank","erp","crm","government_portal","email","other"],rd=["portal_read_back","api","acknowledgment_message"],Hs=["portal_read_back","api"],ad=["sent","acknowledged","recorded_as_intended","recorded_differently"],sd=["read_back","acknowledgment","none"],id=["each_item","problems_only","not_gated"],ld=["person","agent","none"],cd={sent:["rejected_by_counterparty","ambiguous_key","receiver_unreachable","not_found","no_answer_by_deadline"],acknowledged:["ambiguous_key","not_found","no_answer_by_deadline"],recorded_as_intended:["conflicting_report"],recorded_differently:["conflicting_report"]},dd=/^(?:counterparty|observed_at|reason|field\.[0-9]{1,2})$/,pd=/^(?:principal|scope|approved_at)$/,ud=/^confirmations\.([0-9]{1,2})\.(counterparty|observed_at|reason|field\.[0-9]{1,2})$/,fd=/^approval\.(principal|scope|approved_at)$/,hd={counterparty:/^(?:ehr|payer_portal|bank|erp|crm|government_portal|email|other):cp-[a-f0-9]{16}$/,observed_at:oo,reason:/^(?:rejected_by_counterparty|conflicting_report|ambiguous_key|receiver_unreachable|not_found|no_answer_by_deadline)$/,field:/^[a-z][a-z0-9_]{0,31}:[a-f0-9]{64}(?::differs)?$/,principal:/^(?:person|agent):pr-[a-f0-9]{16}$/,scope:Rt,approved_at:oo},gd=["gui","api"],md=["write","irreversible_write"],bd=["confirmed","refuted","not_checked"],vd=["read_back","same_screen","none"],yd=["effect_not_declared","approved_unverified","field_values","postconditions","uncertain"],_d="openadapt.evidence-scope/v1",xd=["unchecked","same_screen","reopened","separate_session","system_of_record","counterparty_confirmed"],kd=["VERIFIED","SHOWN","CONFIRMED","ATTESTED","RECORDED"],Ps={post_save_screen:"same_screen",reopened_record:"reopened",separate_session:"separate_session",fresh_reload:"separate_session",system_api:"system_of_record",activity_log:"system_of_record",db_frame:"system_of_record",owned_connection:"system_of_record"},js=["post_save_screen","reopened_record"],wd=["none","browser_network","http_proxy","api_client","db_connection"],Sd=["http","graphql","fhir","sql","websocket","grpc","smtp"],Ed=["server_side_async_effects","outbound_effects","changes_after_read_back","fields_not_read","other_records","other_actors","read_back_time"],Nd=["server_side_async_effects","outbound_effects"],Td=720*3600,Os=/^(?!.*:\/\/)[A-Za-z0-9][A-Za-z0-9._:@+/ -]{0,127}$/,$d={VERIFIED:["VERIFIED"],CONFIRMED:["VERIFIED"],SHOWN:["UNKNOWN","STOPPED","FAILED"],ATTESTED:["UNKNOWN","STOPPED","FAILED"],RECORDED:["UNKNOWN","STOPPED","FAILED"]},I=class extends Error{constructor(t,n=""){super(n||t),this.reason=t}},Ls=(e,t="")=>({ok:!1,reason:e,detail:t,signerLines:[Wc(e)],outcome:null,demo:!1,disclosed:{}}),Ad=/data:[a-z]+\//i,Rd=/[a-z][a-z0-9+.-]*:\/\//i,Md=/[A-Za-z0-9+/_-]{96,}={0,2}/,Id=["iVBORw0KGgo","/9j/","R0lGOD","UklGR","PHN2Zy"];function dr(e){let t=e.toLowerCase();return[...e].length>256||Ad.test(e)||Rd.test(e)||Md.test(e)||Id.some(n=>e.startsWith(n))||t.includes("e!==null&&typeof e=="object"&&!Array.isArray(e);function De(e,t,n=[],o=""){if(!je(e))throw new I("malformed",`${o} is an object`);for(let r of Object.keys(e))if(!t.includes(r)&&!n.includes(r))throw new I("malformed",`${o}.${r} is not a field`);for(let r of t)if(!(r in e))throw new I("malformed",`${o}.${r} is missing`)}function lt(e,t,n,o){if(!Number.isInteger(e)||en)throw new I("malformed",`${o} is an integer from ${t} to ${n}`)}function J(e,t,n){if(!(typeof e=="string"&&(Array.isArray(t)?t.includes(e):t.test(e))))throw new I("malformed",`${n} is not valid`)}function Cd(e,t){De(e,["required","confirmed"],[],t),lt(e.required,0,_n,`${t}.required`),lt(e.confirmed,0,_n,`${t}.confirmed`)}function Pd(e){if(De(e,["_type","subject","predicateType","predicate"],[],"$"),!Array.isArray(e.subject)||e.subject.length<1||e.subject.length>4)throw new I("malformed","subject has 1 to 4 entries");for(let[o,r]of e.subject.entries())De(r,["name","digest"],["media_type"],`subject[${o}]`),J(r.name,ed,`subject[${o}].name`),"media_type"in r&&J(r.media_type,td,`subject[${o}].media_type`),De(r.digest,["sha256"],[],`subject[${o}].digest`),J(r.digest.sha256,Rt,`subject[${o}].digest.sha256`);let t=e.predicate;if(De(t,["program","started_hour","outcome","steps","lines","checks","model_calls","disclosure"],["reason_code","confirmations","approval","evidence_scope"],"predicate"),De(t.program,["id","version_sha256"],[],"predicate.program"),J(t.program.id,Zc,"predicate.program.id"),J(t.program.version_sha256,Rt,"predicate.program.version_sha256"),J(t.started_hour,qc,"predicate.started_hour"),J(t.outcome,Qc,"predicate.outcome"),t.reason_code!=null&&J(t.reason_code,Yc,"predicate.reason_code"),De(t.steps,["total","ok"],[],"predicate.steps"),lt(t.steps.total,0,_n,"predicate.steps.total"),lt(t.steps.ok,0,_n,"predicate.steps.ok"),!Array.isArray(t.lines)||t.lines.length>Is)throw new I("malformed","predicate.lines");for(let[o,r]of t.lines.entries()){let a=`predicate.lines[${o}]`;if(De(r,["step","target_kind","operation","check","strength","not_checked"],["evidence"],a),"evidence"in r&&(De(r.evidence,["kind","sha256"],[],`${a}.evidence`),J(r.evidence.kind,nd,`${a}.evidence.kind`),J(r.evidence.sha256,Rt,`${a}.evidence.sha256`)),lt(r.step,0,1e4,`${a}.step`),J(r.target_kind,gd,`${a}.target_kind`),J(r.operation,md,`${a}.operation`),J(r.check,bd,`${a}.check`),J(r.strength,vd,`${a}.strength`),!Array.isArray(r.not_checked)||r.not_checked.length>5)throw new I("malformed",`${a}.not_checked`);r.not_checked.forEach((i,l)=>J(i,yd,`${a}.not_checked[${l}]`))}let n=t.checks;De(n,["identity","postconditions","effects","authorization","lines_confirmed","lines_refuted","lines_not_checked"],[],"predicate.checks");for(let o of["identity","postconditions","effects","authorization"])Cd(n[o],`predicate.checks.${o}`);for(let o of["lines_confirmed","lines_refuted","lines_not_checked"])lt(n[o],0,Is,`predicate.checks.${o}`);if(lt(t.model_calls,0,_n,"predicate.model_calls"),De(t.disclosure,["version","commitments"],[],"predicate.disclosure"),J(t.disclosure.version,[Ds],"predicate.disclosure.version"),!je(t.disclosure.commitments)||Object.keys(t.disclosure.commitments).length>16)throw new I("malformed","predicate.disclosure.commitments");for(let o of Object.values(t.disclosure.commitments))if(typeof o!="string")throw new I("malformed","a commitment is a string");if("confirmations"in t){if(!Array.isArray(t.confirmations)||t.confirmations.length>64)throw new I("malformed","predicate.confirmations");for(let[o,r]of t.confirmations.entries()){let a=`predicate.confirmations[${o}]`;if(De(r,["kind","system_kind","read_method","state","strength","differing_count","commitments"],["for_step"],a),J(r.kind,["counterparty_confirmation"],`${a}.kind`),r.for_step!=null&<(r.for_step,0,1e4,`${a}.for_step`),J(r.system_kind,od,`${a}.system_kind`),J(r.read_method,rd,`${a}.read_method`),J(r.state,ad,`${a}.state`),J(r.strength,sd,`${a}.strength`),lt(r.differing_count,0,64,`${a}.differing_count`),!je(r.commitments)||Object.keys(r.commitments).length<2||Object.keys(r.commitments).length>34)throw new I("malformed",`${a}.commitments`)}}if("approval"in t&&(De(t.approval,["mode","approver_kind","commitments"],[],"predicate.approval"),J(t.approval.mode,id,"predicate.approval.mode"),J(t.approval.approver_kind,ld,"predicate.approval.approver_kind"),!je(t.approval.commitments)||Object.keys(t.approval.commitments).length>3))throw new I("malformed","predicate.approval.commitments");if("evidence_scope"in t){let o=t.evidence_scope;De(o,["schema","check_level","word","wire","not_covered"],["basis","read_back_at","recheck_window_s","agent_used","verifier_adapter"],"predicate.evidence_scope"),J(o.schema,[_d],"predicate.evidence_scope.schema"),J(o.check_level,xd,"predicate.evidence_scope.check_level"),J(o.word,kd,"predicate.evidence_scope.word"),"basis"in o&&J(o.basis,Object.keys(Ps),"predicate.evidence_scope.basis"),De(o.wire,["channel","protocols_parsed"],[],"predicate.evidence_scope.wire"),J(o.wire.channel,wd,"predicate.evidence_scope.wire.channel");let r=o.wire.protocols_parsed;if(!Array.isArray(r)||r.length>7)throw new I("malformed","predicate.evidence_scope.wire.protocols_parsed");if(r.forEach((a,i)=>J(a,Sd,`predicate.evidence_scope.wire.protocols_parsed[${i}]`)),new Set(r).size!==r.length)throw new I("malformed","wire.protocols_parsed repeats a protocol");if(o.wire.channel==="none"&&r.length)throw new I("malformed","a run that watched no wire parsed no protocol");if("read_back_at"in o&&J(o.read_back_at,oo,"predicate.evidence_scope.read_back_at"),"recheck_window_s"in o&<(o.recheck_window_s,0,Td,"predicate.evidence_scope.recheck_window_s"),"agent_used"in o&&J(o.agent_used,Os,"predicate.evidence_scope.agent_used"),"verifier_adapter"in o&&J(o.verifier_adapter,Os,"predicate.evidence_scope.verifier_adapter"),!Array.isArray(o.not_covered)||o.not_covered.length<2||o.not_covered.length>7)throw new I("malformed","predicate.evidence_scope.not_covered");if(o.not_covered.forEach((a,i)=>J(a,Ed,`predicate.evidence_scope.not_covered[${i}]`)),new Set(o.not_covered).size!==o.not_covered.length)throw new I("malformed","not_covered repeats a code");if(!Nd.every(a=>o.not_covered.includes(a)))throw new I("malformed","not_covered must list server_side_async_effects and outbound_effects");if(o.basis!=null&&Ps[o.basis]!==o.check_level)throw new I("malformed",`basis ${o.basis} does not reach ${o.check_level}`);if(o.word==="VERIFIED"){if(!["same_screen","reopened","separate_session","system_of_record"].includes(o.check_level)||o.basis==null)throw new I("malformed","VERIFIED needs level 1 to 4 and a basis");if(o.read_back_at==null&&!o.not_covered.includes("read_back_time"))throw new I("malformed","VERIFIED needs read_back_at, or says it has none")}if(js.includes(o.basis)&&o.not_covered.includes("fields_not_read"))throw new I("malformed","a screen check that did not read every field earns no basis");if(o.word==="SHOWN"&&!["same_screen","reopened"].includes(o.check_level))throw new I("malformed","SHOWN is a level 1 or 2 re-read of the acting screen");if(o.word==="SHOWN"&&o.basis!=null)throw new I("malformed","an older SHOWN block names no basis");if(o.word==="CONFIRMED"&&o.check_level!=="counterparty_confirmed")throw new I("malformed","CONFIRMED is level 5, the counterparty acknowledgment");if(o.read_back_at!=null&&o.not_covered.includes("read_back_time"))throw new I("malformed","a block with read_back_at covers the read-back time");if(o.recheck_window_s!=null&&o.read_back_at==null)throw new I("malformed","a recheck window needs read_back_at")}return{...e,predicate:{...t,reason_code:t.reason_code??null}}}function Od(e){let t=e.predicate,n=e.subject.map(a=>a.name);if(new Set(n).size!==n.length||!(n.includes("report.json")||n.includes("report.canonical")))return"subject names repeat, or the report is missing";for(let a of e.subject)if(a.name==="payload"!="media_type"in a)return"only the payload subject has a media type, and it always has one";if(t.approval){let a=t.approval;for(let[i,l]of Object.entries(a.commitments))if(!pd.test(i)||!Rt.test(l))return`approval commitment ${i} is not a known field`;if(a.mode==="not_gated"&&a.approver_kind!=="none")return"a not_gated run names no approver";if(a.approver_kind==="none"){if(Object.keys(a.commitments).length)return"an approval with no approver commits to nothing"}else if(!("principal"in a.commitments&&"scope"in a.commitments))return"an approval names its approver's principal and scope"}for(let[a,i]of Object.entries(t.disclosure.commitments))if(!Fs[a]||!Rt.test(i))return`disclosure path ${a} is not a known field`;if(t.steps.ok>t.steps.total)return"steps.ok is more than steps.total";for(let a of["identity","postconditions","effects","authorization"])if(t.checks[a].confirmed>t.checks[a].required)return`checks.${a} confirms more than it requires`;let o={confirmed:0,refuted:0,not_checked:0};for(let a of t.lines){if(o[a.check]+=1,a.check==="confirmed"&&a.strength==="none")return"a confirmed line has no strength";if(new Set(a.not_checked).size!==a.not_checked.length)return"a line repeats a not_checked code"}if(t.checks.lines_confirmed!==o.confirmed||t.checks.lines_refuted!==o.refuted||t.checks.lines_not_checked!==o.not_checked)return"check counts disagree with the lines";if(t.outcome==="VERIFIED"&&o.refuted)return"a VERIFIED receipt has a refuted line";if(t.evidence_scope&&!$d[t.evidence_scope.word].includes(t.outcome))return"the evidence scope's word disagrees with the outcome";if(t.evidence_scope&&js.includes(t.evidence_scope.basis)&&t.lines.some(a=>a.check!=="confirmed"||a.not_checked.includes("field_values")))return"a screen check says every field was read, a line says not";let r=t.lines.map(a=>a.step);for(let a=1;a0)return"differing_count disagrees with the state";if(!("counterparty"in a.commitments&&"observed_at"in a.commitments))return"a confirmation commits to its counterparty and observed_at";for(let[l,p]of Object.entries(a.commitments))if(!dd.test(l)||!Rt.test(p))return`confirmation commitment ${l} is not a known field`;let i=Object.keys(a.commitments).filter(l=>l.startsWith("field.")).length;if(a.differing_count>i)return"more differing fields than observed fields"}return null}var Ut=e=>new TextEncoder().encode(e);function Gs(...e){let t=new Uint8Array(e.reduce((o,r)=>o+r.length,0)),n=0;for(let o of e)t.set(o,n),n+=o.length;return t}var Ld=e=>Uint8Array.from(e.match(/../g),t=>parseInt(t,16));async function zd(e,t,n){let o=new Uint8Array([0]);return Re(Gs(Ut(jc),o,Ut(e),o,Ld(t),o,Ut(Ce(n))))}function Dd(e,t){let n=ud.exec(e)||fd.exec(e);if(n){let r=(n[2]||n[1]).split(".")[0];return typeof t=="string"&&hd[r].test(t)?null:`${e} does not match its field's pattern`}let o=Fs[e];return o?typeof t!="string"?`${e} is not a string`:dr(t)?`${e} holds embedded content`:o.test(t)?null:`${e} does not match its field's pattern`:`${e} is not a disclosure field`}async function zs(e,t,n){if(!je(e))throw new I("malformed","openings are an object");let o=ro(e);if(o)throw new I("embedded_content",o);let r={};for(let[a,i]of Object.entries(e)){if(n&&!n.includes(a))throw new I("disclosure_not_allowed",a);if(!je(i)||Object.keys(i).length!==2||!("salt"in i)||!("value"in i))throw new I("malformed",`the opening for ${a}`);let l=Dd(a,i.value);if(l)throw new I("malformed",l);if(!(typeof i.salt=="string"&&Vc.test(i.salt)))throw new I("malformed",`the salt for ${a}`);if(t[a]!==await zd(a,i.salt,i.value))throw new I("opening_mismatch",a);r[a]=i.value}return r}async function Fd(e){if(!je(e)||e.schema!==Hc)throw new I("unknown_schema","not an openadapt.receipt-keys/v1 registry");if(!Array.isArray(e.keys))throw new I("malformed","a registry has a keys list");let t=[];for(let n of e.keys){if(!je(n))throw new I("malformed","a registry entry is an object");if(Object.keys(n).some(a=>!["key_id","public_key","role","status","revoked_at","org"].includes(a)))throw new I("malformed","a registry entry has an unknown field");if(!Uc.includes(n.role))throw new I("unknown_role",`unknown signer role ${n.role}`);if(typeof n.public_key!="string"||!cr.test(n.public_key))throw new I("malformed","a public key is base64");let o=Pe(n.public_key);if(o.length!==32||n.key_id!==`seal-ed25519-${(await Re(o)).slice(0,16)}`)throw new I("malformed","a key id doesn't match its public key");let r=n.status??"active";if(!["active","revoked"].includes(r)||r==="revoked"&&!(typeof n.revoked_at=="string"&&oo.test(n.revoked_at)))throw new I("malformed","a key is active, or revoked with revoked_at");if(n.role==="customer_key"&&!(typeof n.org=="string"&&Jc.test(n.org)))throw new I("malformed","a customer key names its org");t.push({keyId:n.key_id,raw:o,role:n.role,status:r,revokedAt:r==="revoked"?n.revoked_at:null,org:n.role==="customer_key"?n.org:null})}if(new Set(t.map(n=>n.keyId)).size!==t.length)throw new I("malformed","a registry lists one key id twice");return t}function Hd(e,t){let n=Ut(e);return Gs(Ut(`DSSEv1 ${n.length} `),n,Ut(` ${t.length} `),t)}var jd=e=>je(e)&&e.schema===Dc;function Gd(e){if(et(e)!==null)throw new I("malformed","duplicate key");try{return JSON.parse(e)}catch{throw new I("malformed","the payload is not JSON")}}async function Ud(e,t,n){let o;try{o=await globalThis.crypto.subtle.importKey("raw",e,{name:"Ed25519"},!1,["verify"])}catch{throw new I("verifier_unavailable")}return globalThis.crypto.subtle.verify({name:"Ed25519"},o,t,n)}async function Us(e,t,{openings:n=null}={}){try{let o=await Fd(t),r=null,a=null,i=e;if(jd(e)){if(Object.keys(e).sort().join(",")!=="disclosure_version,envelope,openings,schema")throw new I("malformed","a card has exactly four fields");if(a=Xc[e.disclosure_version],!a)throw new I("unknown_schema","unknown public disclosure version");if(r=e.openings,!je(r))throw new I("malformed","a card's openings are an object");if(i=e.envelope,n!=null)throw new I("malformed","a card carries its own openings")}if(!je(i)||Object.keys(i).sort().join(",")!=="payload,payloadType,signatures")throw new I("malformed","a DSSE envelope has payloadType, payload, signatures");if(i.payloadType!==Ms)throw new I("unknown_schema","the payload is not an in-toto statement");if(typeof i.payload!="string"||!cr.test(i.payload))throw new I("malformed","the payload is not base64");let l=Pe(i.payload);if(l.length>Gc)throw new I("malformed","the payload is too large");let p=i.signatures;if(!Array.isArray(p)||!p.length)throw new I("unsigned");let c=new Map(o.map($=>[$.keyId,$])),g=Hd(Ms,l),h=[],d=new Set;for(let $ of p){if(!je($)||Object.keys($).sort().join(",")!=="keyid,sig")throw new I("malformed","a signature has keyid and sig");let O=$.keyid;if(typeof O!="string"||d.has(O))throw new I("malformed","a signature's keyid is missing or repeated");d.add(O);let M=c.get(O);if(!M)throw new I("unknown_signer",`${O} is not in the pinned registry`);if(typeof $.sig!="string"||!cr.test($.sig))throw new I("bad_signature",`${O}'s signature`);if(!await Ud(M.raw,Pe($.sig),g))throw new I("bad_signature",`${O}'s signature`);if(M.status==="revoked")throw new I("revoked_key",`${O} was revoked at ${M.revokedAt}`);h.push({keyId:O,role:M.role,line:Bc[M.role].replace("{org}",M.org||"the customer")})}let f=new Set(h.map($=>$.role)),u=f.has("demo");if(u&&f.size!==1)throw new I("mixed_demo");let v;try{v=new TextDecoder("utf-8",{fatal:!0}).decode(l)}catch{throw new I("malformed","the payload is not UTF-8")}let m=Gd(v);if(!je(m))throw new I("malformed","the payload is not an object");if(m._type!==Lc||m.predicateType!==zc)throw new I("unknown_schema","not a record/run/v1 statement");let b=Object.fromEntries(Object.entries(m).filter(([$])=>$!=="_type"&&$!=="predicateType")),_=ro(b);if(_)throw new I("embedded_content",_);let x=Pd(m);if(Ce(x)!==v)throw new I("malformed","the payload is not canonical JSON");let w=Od(x);if(w)throw new I("inconsistent",w);let E={...x.predicate.disclosure.commitments};for(let[$,O]of(x.predicate.confirmations||[]).entries())for(let[M,k]of Object.entries(O.commitments))E[`confirmations.${$}.${M}`]=k;if(x.predicate.approval)for(let[$,O]of Object.entries(x.predicate.approval.commitments))E[`approval.${$}`]=O;let R={},S=!1;if(r)R=await zs(r,E,a);else if(n!=null){if(!je(n)||Object.keys(n).sort().join(",")!=="openings,payload_sha256,schema")throw new I("malformed","a private openings file has three fields");if(n.schema!==Fc)throw new I("unknown_schema","not an openadapt.receipt-openings/v1 file");if(n.payload_sha256!==await Re(l))throw new I("opening_mismatch","the openings belong to another receipt");R=await zs(n.openings,E,null),S=!0;for(let[$,O]of(x.predicate.confirmations||[]).entries()){let M=R[`confirmations.${$}.reason`];if(M!=null&&!cd[O.state].includes(M))throw new I("inconsistent",`a ${O.state} confirmation can't have reason ${M}`)}}let A=[...h].sort(($,O)=>Cs.indexOf($.role)-Cs.indexOf(O.role)),L=[...new Set(A.map($=>$.line))],P=x.predicate.confirmations||[];return{ok:!0,reason:null,detail:"",signers:A,signerLines:L,confirmationLines:P.map(($,O)=>Kd($,R[`confirmations.${O}.observed_at`])),independent:P.map($=>Hs.includes($.read_method)),approvalLine:Bd(x.predicate.approval),outcome:x.predicate.outcome,demo:u,disclosed:R,private:S,statement:x}}catch(o){return o instanceof I?Ls(o.reason,o.message):Ls("malformed",String(o?.message||o))}}function Bd(e){return e?e.mode==="not_gated"?"Not gated: no approval was required for these writes":e.approver_kind==="none"?`Approval required for ${e.mode==="each_item"?"each item":"items that fail a check"}; no item was approved`:`Approved by ${e.approver_kind==="person"?"a person":"an agent delegate"}: ${e.mode==="each_item"?"each item":"items that failed a check"}`:"No approval recorded"}function Kd(e,t){let n=t?` at ${t}`:"";return e.state==="recorded_as_intended"?`Confirmed in the other party's system${n}`:e.state==="recorded_differently"?`Recorded differently in the other party's system${n}: ${e.differing_count} ${e.differing_count===1?"field differs":"fields differ"}`:e.state==="acknowledged"?`Acknowledged by the other party${n}`:`Sent to the other party${n}, not confirmed`}async function ht(e,t=!1){let n=await fetch(e,{cache:"no-store"});if(!n.ok)throw new Error(`${e}: ${n.status}`);return t?new Uint8Array(await n.arrayBuffer()):n.text()}async function Bs(e,t=null){let[n,o,r,a,i,l]=await Promise.all([ht(e.report,!0),ht(e.seal),e.anchor?ht(e.anchor):null,e.tsa?ht(e.tsa):null,e.tsr?ht(e.tsr,!0):null,t?Promise.all([ht(t.statement),ht(t.sig),ht(t.signers),t.anchor?ht(t.anchor):null]):null]);return{report:n,sealText:o,anchorText:r,tsaText:a,tsrBytes:i,auth:l?{statement:l[0],sig:l[1],signers:l[2],anchorText:l[3]}:null}}var Ks={VERIFIED:"HALTED",HALTED:"VERIFIED"};function Vs(e,t){let n=t||e,o=Ks[n]||"VERIFIED",r=Ks[e]||"VERIFIED";return[{id:"report-outcome",target:"report",label:"Change the outcome in the report",field:"execution_outcome",from:n,to:o,text:[`"execution_outcome": "${n}"`,`"execution_outcome": "${o}"`]},{id:"report-model-calls",target:"report",label:"Add one AI model call to the report",field:"model_calls",from:"0",to:"1",text:['"model_calls": 0','"model_calls": 1']},{id:"seal-outcome",target:"seal",label:"Change the outcome in the receipt",field:"outcome",from:e,to:r}]}function qs(e,t){if(t.target==="seal"){if(e.sealText!=null){let a=JSON.parse(e.sealText);if(a[t.field]!==t.from)throw new Error("The value to change is not in the receipt.");return{...e,sealText:JSON.stringify({...a,[t.field]:t.to},null,2),receiptText:e.receiptText?Ws(e.receiptText):e.receiptText}}if(e.receiptText!=null)return{...e,receiptText:Ws(e.receiptText)};throw new Error("The value to change is not in the receipt.")}let n=new TextDecoder().decode(e.report),[o,r]=t.text;if(!n.includes(o))throw new Error("The value to change is not in the report.");return{...e,report:new TextEncoder().encode(n.replace(o,r))}}function Ws(e){let t=JSON.parse(e),o=new TextDecoder().decode(Uint8Array.from(atob(t.payload),i=>i.charCodeAt(0))).replace(/"outcome":"(VERIFIED|STOPPED|UNKNOWN|FAILED)"/,(i,l)=>`"outcome":"${l==="VERIFIED"?"STOPPED":"VERIFIED"}"`),r=new TextEncoder().encode(o),a="";for(let i of r)a+=String.fromCharCode(i);return JSON.stringify({...t,payload:btoa(a)})}var Wd=`-----BEGIN CERTIFICATE----- MIIB9zCCAXygAwIBAgIUV7f0GLDOoEzIh8LXSW80OJiUp14wCgYIKoZIzj0EAwMw OTEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MSAwHgYDVQQDExdzaWdzdG9yZS10c2Et c2VsZnNpZ25lZDAeFw0yNTA0MDgwNjU5NDNaFw0zNTA0MDYwNjU5NDNaMDkxFTAT diff --git a/openadapt/wrap_sdk.py b/openadapt/wrap_sdk.py index dd35e48c59..61fece64b7 100644 --- a/openadapt/wrap_sdk.py +++ b/openadapt/wrap_sdk.py @@ -643,8 +643,8 @@ def wrap_receipt_word( ``system_api``. Anything else is ``RECORDED``: a wrap receipt whose own digest does not match its fields, an outcome other than confirmed, no contract receipt, a contract digest that does not match, a contract - receipt that fails ``verify-run``'s own checks, or a block that does not - validate. This checks integrity, not who signed: use + receipt that fails ``verify-run``'s own checks or whose outcome is not + ``verified``, or a block that does not validate. This checks integrity, not who signed: use :func:`check_wrap_receipt` for that. The word is derived, never signed, so receipts keep their exact bytes. @@ -653,6 +653,7 @@ def wrap_receipt_word( data = receipt.to_dict() if isinstance(receipt, WrapReceipt) else receipt if ( not isinstance(data, Mapping) + or data.get("schema") != RECEIPT_SCHEMA or data.get("outcome") != WrapOutcome.CONFIRMED.value ): return "RECORDED" @@ -674,6 +675,10 @@ def wrap_receipt_word( return "RECORDED" if receipt_problem(contract_receipt) is not None: return "RECORDED" + # Only a verified write supports the wrapper's "confirmed" (a + # verified rollback, for one, does not). + if contract_receipt.get("outcome") != "verified": + return "RECORDED" except (TypeError, ValueError, KeyError, AttributeError): return "RECORDED" block = contract_receipt.get("evidence_scope") diff --git a/packages/flow/openadapt_flow/evidence_basis.py b/packages/flow/openadapt_flow/evidence_basis.py index 50a7e6eff0..632ff06e4a 100644 --- a/packages/flow/openadapt_flow/evidence_basis.py +++ b/packages/flow/openadapt_flow/evidence_basis.py @@ -82,16 +82,21 @@ def level_and_basis( def screen_basis( - level: CheckLevel, checks: Sequence[Any], saves: Optional[int] = None + level: CheckLevel, + checks: Mapping[str, Any], + saves: Sequence[Mapping[str, Any]], ) -> Optional[Basis]: """The basis a level 1 or 2 run earns from its saves' screen checks. - ``checks`` holds one :class:`~openadapt_types.check_level.ScreenCheck` - (or a mapping of one) per save, and ``saves`` is how many saves the run - made: a check count that differs earns nothing. The rule is - ``openadapt_types.check_level.screen_basis_for``: every check complete - and reaching ``level``. None when the installed ``openadapt-types`` - predates the screen bases. + ``checks`` maps a save's ``step_id`` to its + :class:`~openadapt_types.check_level.ScreenCheck` (or a mapping of one); + ``saves`` is the report's ``readback["saves"]``. Every save checked at + level 1 or 2 needs its own check, keyed by its ``step_id``, that is + complete and reaches that save's level; a save checked at level 3 or 4 + needs none. A check for a step that is not such a save, a repeated + ``step_id``, or a save below level 1 earns nothing. The rule for each + check is ``openadapt_types.check_level.screen_basis_for``. None when the + installed ``openadapt-types`` predates the screen bases. """ try: @@ -100,9 +105,32 @@ def screen_basis( ) except ImportError: # pragma: no cover - older openadapt-types return None - if saves is not None and len(checks) != saves: + level = CheckLevel(level) + if level not in (CheckLevel.SAME_SCREEN, CheckLevel.REOPENED): return None - return screen_basis_for(level, checks) # type: ignore[no-any-return] + if not isinstance(checks, Mapping) or not saves: + return None + seen: set[str] = set() + screen_steps: set[str] = set() + for save in saves: + if not isinstance(save, Mapping): + return None + step = save.get("step_id") + try: + save_level = CheckLevel.from_label(str(save.get("checked_how"))) + except ValueError: + return None + if not isinstance(step, str) or step in seen or save_level < level: + return None + seen.add(step) + if save_level >= CheckLevel.SEPARATE_SESSION: + continue + screen_steps.add(step) + if step not in checks or screen_basis_for(save_level, [checks[step]]) is None: + return None + if set(checks) != screen_steps: + return None + return screen_basis_for(level, [checks[step] for step in screen_steps]) # type: ignore[no-any-return] def evidence_scope_for_run( @@ -110,7 +138,7 @@ def evidence_scope_for_run( outcome: str, *, read_back_at: Optional[str] = None, - screen_checks: Sequence[Any] = (), + screen_checks: Optional[Mapping[str, Any]] = None, ) -> dict[str, Any]: """The evidence-scope block for a Flow run, from its ``report.json``. @@ -121,7 +149,8 @@ def evidence_scope_for_run( ``evidence_scope``. Only a ``VERIFIED`` run names a basis, so only a ``VERIFIED`` run gets the word ``VERIFIED``. A level 1 or 2 run names ``post_save_screen`` or ``reopened_record`` only with one complete - ``screen_checks`` entry for each save in ``readback["saves"]`` + ``screen_checks`` entry, keyed by ``step_id``, for each screen-level + save in ``readback["saves"]`` (:func:`screen_basis`); without them it is ``RECORDED``, also under an ``openadapt-types`` that predates the screen bases. """ @@ -145,11 +174,11 @@ def evidence_scope_for_run( if verified: basis = basis_for_tier(to_verification_tier(level)) if basis is None and isinstance(saves, list): - basis = screen_basis(level, screen_checks, saves=len(saves)) + basis = screen_basis(level, screen_checks or {}, saves) screen = level in (CheckLevel.SAME_SCREEN, CheckLevel.REOPENED) extra: dict[str, Any] = {} if basis is not None and screen: - extra["screen_checks"] = screen_checks + extra["screen_checks"] = list((screen_checks or {}).values()) return build_evidence_scope( level, basis=basis, @@ -162,7 +191,11 @@ def evidence_scope_for_run( read_back_at=read_back_at if level > CheckLevel.UNCHECKED else None, not_covered=( "changes_after_read_back", - *(("fields_not_read",) if _any_field_not_read(screen_checks) else ()), + *( + ("fields_not_read",) + if _any_field_not_read(list((screen_checks or {}).values())) + else () + ), # A run report records no per-read time yet. *(("read_back_time",) if read_back_at is None else ()), ), diff --git a/packages/flow/tests/test_post_save_screen.py b/packages/flow/tests/test_post_save_screen.py index 4c007ef527..44be1b8e7b 100644 --- a/packages/flow/tests/test_post_save_screen.py +++ b/packages/flow/tests/test_post_save_screen.py @@ -41,19 +41,27 @@ def _scope( checks, minimum: str = "same_screen", outcome: str = "VERIFIED", - saves: int | None = None, + saves=None, ): - count = len(checks) if saves is None else saves - readback = { - "checked_how": level, - "minimum": minimum, - "saves": [{"step_id": f"s{i}", "checked_how": level} for i in range(count)], - } + """A run scope for saves ``s0``, ``s1``, ... with ``checks`` keyed to them.""" + + keyed = ( + {f"s{i}": c for i, c in enumerate(checks)} + if isinstance(checks, list) + else checks + ) + if saves is None: + saves = [{"step_id": step, "checked_how": level} for step in keyed] + readback = {"checked_how": level, "minimum": minimum, "saves": saves} return evidence_scope_for_run( - readback, outcome, read_back_at=T, screen_checks=checks + readback, outcome, read_back_at=T, screen_checks=keyed ) +def _saves(*levels: str) -> list: + return [{"step_id": f"s{i}", "checked_how": lv} for i, lv in enumerate(levels)] + + @pytest.mark.parametrize("case", CASES, ids=[c["name"] for c in CASES]) def test_run_scope_matches_the_shared_cases(case) -> None: scope = _scope(case["level"], [case["check"]]) @@ -62,35 +70,62 @@ def test_run_scope_matches_the_shared_cases(case) -> None: assert scope["word"] == outcome_word(level, case["basis"]) -def test_every_save_needs_a_complete_check() -> None: +def test_every_save_needs_its_own_complete_check() -> None: good = CASES[0]["check"] unread = next(c["check"] for c in CASES if c["name"] == "one_field_not_read") + reopened = next(c["check"] for c in CASES if c["name"] == "complete_after_reopen") assert _scope("same_screen", [good, good])["word"] == "VERIFIED" mixed = _scope("same_screen", [good, unread]) assert mixed["word"] == "RECORDED" assert "fields_not_read" in mixed["not_covered"] # No record at all: the tier alone earns nothing. assert _scope("same_screen", [])["word"] == "RECORDED" - assert _scope("same_screen", [], saves=1)["word"] == "RECORDED" - # One check per save: one complete check can't cover two saves. - assert _scope("same_screen", [good], saves=2)["word"] == "RECORDED" + assert _scope("same_screen", {}, saves=_saves("same_screen"))["word"] == "RECORDED" + # One check per save, bound by step_id. + two = _saves("same_screen", "same_screen") + assert _scope("same_screen", {"s0": good}, saves=two)["word"] == "RECORDED" + assert ( + _scope("same_screen", {"s0": good, "s9": good}, saves=two)["word"] == "RECORDED" + ) + # A check for a save that was not confirmed earns nothing. + unchecked = _saves("same_screen", "unchecked") + assert ( + _scope("same_screen", {"s0": good, "s1": good}, saves=unchecked)["word"] + == "RECORDED" + ) + # A repeated step_id earns nothing. + repeated = [{"step_id": "s0", "checked_how": "same_screen"}] * 2 + assert _scope("same_screen", {"s0": good}, saves=repeated)["word"] == "RECORDED" # A report without its saves list earns nothing either. no_saves = evidence_scope_for_run( {"checked_how": "same_screen", "minimum": "same_screen"}, "VERIFIED", read_back_at=T, - screen_checks=[good], + screen_checks={"s0": good}, ) assert no_saves["word"] == "RECORDED" - # A reopen check also reaches level 1, so a level 1 run with one save - # checked each way earns post_save_screen (the weakest level wins); a - # same-screen check never reaches level 2. - reopened = next(c["check"] for c in CASES if c["name"] == "complete_after_reopen") - mixed_ok = _scope("same_screen", [good, reopened]) + # The weakest save decides: a reopened save and a same-screen save earn + # post_save_screen; a level 3 save needs no screen check. + mixed_ok = _scope( + "same_screen", + {"s0": good, "s1": reopened}, + saves=_saves("same_screen", "reopened"), + ) assert (mixed_ok["word"], mixed_ok["basis"]) == ("VERIFIED", "post_save_screen") - assert screen_basis(CheckLevel.SAME_SCREEN, [reopened]) == "post_save_screen" - assert screen_basis(CheckLevel.REOPENED, [good]) is None - assert screen_basis(CheckLevel.REOPENED, [reopened, good]) is None + with_session = _scope( + "same_screen", {"s0": good}, saves=_saves("same_screen", "separate_session") + ) + assert (with_session["word"], with_session["basis"]) == ( + "VERIFIED", + "post_save_screen", + ) + # A save the report calls reopened needs a reopen check. + assert ( + _scope("reopened", {"s0": good}, saves=_saves("reopened"))["word"] == "RECORDED" + ) + assert screen_basis(CheckLevel.REOPENED, {"s0": reopened}, _saves("reopened")) == ( + "reopened_record" + ) def test_a_run_that_did_not_verify_names_no_basis() -> None: diff --git a/packages/kernel/CHANGELOG.md b/packages/kernel/CHANGELOG.md index 5975ccf9ce..6ef09c7ec2 100644 --- a/packages/kernel/CHANGELOG.md +++ b/packages/kernel/CHANGELOG.md @@ -19,8 +19,14 @@ - Receipt bridge: `minimum_level` (default 1) sets the weakest check level the caller's policy accepts. A regulated caller passes 3; a run whose weakest read is below it is `UNKNOWN` (`below_verified_level`). -- A redacted receipt carries only the screen check's counts and flags; a - check with any other key is not carried and does not count. +- A redacted receipt carries only the screen check's counts and flags. A + check with any other key does not count, and `mint_receipt` refuses to + sign a result whose accepted proof no longer validates. +- `verify_unified_dsse_receipt` refuses a receipt with a screen basis + unless every line is confirmed, no line lists `field_values` and the block + does not list `fields_not_read`, the same rule as the types and JavaScript + verifiers (checked on the shared signed vectors). With `minimum_level` + above 1, a run with no proof is not `VERIFIED`. - `token_boundary_check`, and through it `verify_sqlite_ro`, `verify_pdf_readback`, `verify_cross_tab_dom` and the non-DOM adapter, uses diff --git a/packages/kernel/src/openadapt_kernel/copilot.py b/packages/kernel/src/openadapt_kernel/copilot.py index 9dcb7a4421..1ada4b056a 100644 --- a/packages/kernel/src/openadapt_kernel/copilot.py +++ b/packages/kernel/src/openadapt_kernel/copilot.py @@ -280,6 +280,14 @@ def mint_receipt( obligations_payload: Dict[str, Any] = {} for oid, ob in ledger.obligations.items(): + if ( + ob.state in ("COMMITTED", "EXEMPT") + and ob.readback_proof is not None + and not ob.readback_proof.is_valid() + ): + # The proof changed after it was accepted (a screen check that is + # no longer complete): never sign a result it no longer supports. + raise ValueError(f"read-back proof for {oid!r} is no longer valid") if ob.readback_proof is None: proof_obj: Optional[Dict[str, Any]] = None elif include_plaintext_values: diff --git a/packages/kernel/src/openadapt_kernel/receipt_bridge.py b/packages/kernel/src/openadapt_kernel/receipt_bridge.py index 1a65d82829..d838835ccf 100644 --- a/packages/kernel/src/openadapt_kernel/receipt_bridge.py +++ b/packages/kernel/src/openadapt_kernel/receipt_bridge.py @@ -50,6 +50,7 @@ _VALID_CHECKS = frozenset({"confirmed", "refuted", "not_checked"}) _VALID_STRENGTHS = frozenset({"read_back", "same_screen", "none"}) _VERIFIED_WORDS = frozenset({"VERIFIED", "CONFIRMED"}) +_SCREEN_BASES = frozenset({"post_save_screen", "reopened_record"}) _KERNEL_OUTCOME_MAP: Final[Mapping[str, str]] = { "VERIFIED": "VERIFIED", @@ -520,8 +521,8 @@ def kernel_receipt_to_dsse_record( reason_code = "unverified_write" if ( mapped_outcome == "VERIFIED" - and weakest_proof_level is not None - and weakest_proof_level[0] < max(1, int(minimum_level)) + and int(minimum_level) > 1 + and (weakest_proof_level is None or weakest_proof_level[0] < int(minimum_level)) ): mapped_outcome = "UNKNOWN" reason_code = "below_verified_level" @@ -722,6 +723,16 @@ def _validate_statement_consistency(statement: Mapping[str, Any]) -> Optional[st return "evidence_scope_outcome_mismatch" if outcome != "VERIFIED" and word in _VERIFIED_WORDS: return "evidence_scope_outcome_mismatch" + if scope.get("basis") in _SCREEN_BASES: + # A screen check confirms every write it covers and reads every + # intended field (openadapt_types.evidence_scope). + for line in lines: + if line.get("check") != "confirmed" or "field_values" in ( + line.get("not_checked") or () + ): + return "evidence_scope_lines" + if "fields_not_read" in (scope.get("not_covered") or ()): + return "evidence_scope_lines" return None diff --git a/packages/kernel/tests/test_post_save_screen_bridge.py b/packages/kernel/tests/test_post_save_screen_bridge.py index 46f5403a5b..189965ddac 100644 --- a/packages/kernel/tests/test_post_save_screen_bridge.py +++ b/packages/kernel/tests/test_post_save_screen_bridge.py @@ -137,12 +137,23 @@ def test_a_redacted_receipt_carries_only_the_counts_and_flags() -> None: proof = ledger.obligations["save"].readback_proof assert proof is not None and proof.screen_check is not None proof.screen_check["note"] = "Jane Doe" + # The check no longer validates, so nothing is signed at all. + with pytest.raises(ValueError): + mint_receipt(ledger, "screen-save-v1", priv) + # A complete check is carried as counts and flags only. + del proof.screen_check["note"] receipt = mint_receipt(ledger, "screen-save-v1", priv) - raw = json.dumps(receipt) - assert "Jane Doe" not in raw ob = next(iter(receipt["payload"]["obligations"].values())) - # The unexpected key makes the check unreadable, so nothing is carried. - assert ob["proof"]["screen_check"] is None + assert set(ob["proof"]["screen_check"]) <= { + "fields_intended", + "fields_read", + "fields_matched", + "left_edit_mode", + "error_shown", + "banner_only", + "reopened", + } + assert "Jane Doe" not in json.dumps(receipt) def test_the_ledger_refuses_an_unknown_channel() -> None: @@ -170,3 +181,39 @@ def test_a_policy_floor_keeps_a_screen_check_from_verified() -> None: envelope = kernel_receipt_to_dsse_record(cross_tab, priv, surface="dom", minimum_level=3) ok, statement, _ = verify_unified_dsse_receipt(envelope, pub) assert ok and statement["predicate"]["outcome"] == "VERIFIED" + + +def test_a_policy_floor_needs_a_proof() -> None: + priv, pub = generate_ephemeral_ed25519_keypair() + receipt = _complete_receipt(priv) + empty = copy.deepcopy(receipt) + empty.pop("sha256", None) + empty["payload"]["obligations"] = {} + envelope = kernel_receipt_to_dsse_record(empty, priv, surface="dom", minimum_level=3) + ok, statement, _ = verify_unified_dsse_receipt(envelope, pub) + assert ok and statement["predicate"]["outcome"] == "UNKNOWN" + + +_RECORD_VECTORS = ( + Path(__file__).resolve().parents[2] / "types" / "tests" / "vectors" / "record-run-v1" +) + + +@pytest.mark.skipif(not _RECORD_VECTORS.is_dir(), reason="shared vectors not present") +@pytest.mark.parametrize( + ("name", "ok"), + [ + ("valid-evidence-scope-post-save-screen", True), + ("older-evidence-scope-shown", True), + ("evidence-scope-screen-with-unread-fields", False), + ("evidence-scope-screen-with-unchecked-write", False), + ], +) +def test_the_kernel_verifier_agrees_with_the_shared_vectors(name: str, ok: bool) -> None: + vector = json.loads((_RECORD_VECTORS / f"{name}.json").read_text()) + registry = json.loads((_RECORD_VECTORS / "registry.json").read_text()) + key = next(k for k in registry["keys"] if k["role"] == "this_computer") + got, _, reason = verify_unified_dsse_receipt( + vector["document"], base64.b64decode(key["public_key"]) + ) + assert got is ok, reason diff --git a/packages/seal-view/src/lib/receiptRecord.mjs b/packages/seal-view/src/lib/receiptRecord.mjs index 34752ec125..37743dc351 100644 --- a/packages/seal-view/src/lib/receiptRecord.mjs +++ b/packages/seal-view/src/lib/receiptRecord.mjs @@ -283,8 +283,8 @@ function validateStatement(s) { if (es.word === 'VERIFIED') { if (!['same_screen', 'reopened', 'separate_session', 'system_of_record'].includes(es.check_level) || es.basis == null) throw new Refusal('malformed', 'VERIFIED needs level 1 to 4 and a basis') if (es.read_back_at == null && !es.not_covered.includes('read_back_time')) throw new Refusal('malformed', 'VERIFIED needs read_back_at, or says it has none') - if (SCREEN_BASES.includes(es.basis) && es.not_covered.includes('fields_not_read')) throw new Refusal('malformed', 'a screen check that did not read every field is not VERIFIED') } + if (SCREEN_BASES.includes(es.basis) && es.not_covered.includes('fields_not_read')) throw new Refusal('malformed', 'a screen check that did not read every field earns no basis') if (es.word === 'SHOWN' && !['same_screen', 'reopened'].includes(es.check_level)) throw new Refusal('malformed', 'SHOWN is a level 1 or 2 re-read of the acting screen') // SHOWN is the older word; receipts that carry it still verify. if (es.word === 'SHOWN' && es.basis != null) throw new Refusal('malformed', 'an older SHOWN block names no basis') @@ -321,7 +321,7 @@ function inconsistency(s) { if (p.checks.lines_confirmed !== tally.confirmed || p.checks.lines_refuted !== tally.refuted || p.checks.lines_not_checked !== tally.not_checked) return 'check counts disagree with the lines' if (p.outcome === 'VERIFIED' && tally.refuted) return 'a VERIFIED receipt has a refuted line' if (p.evidence_scope && !EVIDENCE_SCOPE_OUTCOMES[p.evidence_scope.word].includes(p.outcome)) return "the evidence scope's word disagrees with the outcome" - if (p.evidence_scope && SCREEN_BASES.includes(p.evidence_scope.basis) && p.lines.some((l) => l.not_checked.includes('field_values'))) return 'a screen check says every field was read, a line says not' + if (p.evidence_scope && SCREEN_BASES.includes(p.evidence_scope.basis) && p.lines.some((l) => l.check !== 'confirmed' || l.not_checked.includes('field_values'))) return 'a screen check says every field was read, a line says not' const steps = p.lines.map((l) => l.step) for (let i = 1; i < steps.length; i += 1) if (steps[i] <= steps[i - 1]) return 'lines are not in step order, or repeat a step' for (const c of p.confirmations || []) { diff --git a/packages/types/CHANGELOG.md b/packages/types/CHANGELOG.md index feff7fe039..2a37985b1a 100644 --- a/packages/types/CHANGELOG.md +++ b/packages/types/CHANGELOG.md @@ -24,14 +24,16 @@ reaches that level. `SHOWN` is kept in `OutcomeWord` and still validates at levels 1 and 2 so older receipts verify; it may not name a basis. `legacy_word` and `LEGACY_WORDS` let tools label it as the older format. - A screen basis with `fields_not_read` in `not_covered` does not validate, - and a `record/run/v1` receipt with a screen basis is refused when one of - its lines lists `field_values` as not checked. + A block that names a screen basis and lists `fields_not_read` does not + validate, whatever its word. A `record/run/v1` receipt with a screen basis + is refused unless every line is confirmed and none lists `field_values` as + not checked. A block with a new basis does not validate under openadapt-types 0.24.x. - Test vectors: `valid-evidence-scope-post-save-screen` (a signed `VERIFIED` receipt with basis `post_save_screen`) and `older-evidence-scope-shown` (an older `SHOWN` receipt that still - verifies), `evidence-scope-screen-with-unread-fields` (refused), plus `vectors/screen-check/cases.json`, shared by the types, + verifies), `evidence-scope-screen-with-unread-fields` and + `evidence-scope-screen-with-unchecked-write` (both refused), plus `vectors/screen-check/cases.json`, shared by the types, Flow, kernel and launcher tests. - `evidence`: one strict matcher for deciding whether text on a screen or diff --git a/packages/types/openadapt_types/evidence_scope.py b/packages/types/openadapt_types/evidence_scope.py index d1cd59e9cf..22430ecfe6 100644 --- a/packages/types/openadapt_types/evidence_scope.py +++ b/packages/types/openadapt_types/evidence_scope.py @@ -160,15 +160,15 @@ def _consistent(self) -> "EvidenceScopeV1": ) if self.basis is not None and level_for_basis(self.basis) != level: raise ValueError(f"basis {self.basis} does not reach {self.check_level}") + if self.basis in SCREEN_BASES and "fields_not_read" in self.not_covered: + raise ValueError( + "a screen check that did not read every field earns no basis" + ) if self.word == "VERIFIED": if level not in VERIFIED_LEVELS or self.basis is None: raise ValueError("VERIFIED needs level 1 to 4 and a basis") if self.read_back_at is None and "read_back_time" not in self.not_covered: raise ValueError("VERIFIED needs read_back_at, or says it has none") - if self.basis in SCREEN_BASES and "fields_not_read" in self.not_covered: - raise ValueError( - "a screen check that did not read every field is not VERIFIED" - ) if self.word == "SHOWN" and not ( CheckLevel.SAME_SCREEN <= level <= CheckLevel.REOPENED ): @@ -306,12 +306,13 @@ def predicate_evidence_scope_problem(predicate: Mapping[str, Any]) -> Optional[s if predicate.get("outcome") not in allowed: return "evidence_scope_outcome" if block.get("basis") in SCREEN_BASES: - # A screen check reads every intended field, so no line may say - # its field values went unchecked. + # A screen check confirms every write it covers and reads every + # intended field: each line is confirmed, and none says its field + # values went unchecked. for line in predicate.get("lines") or (): - if isinstance(line, Mapping) and "field_values" in ( - line.get("not_checked") or () - ): + if not isinstance(line, Mapping) or line.get("check") != "confirmed": + return "evidence_scope_lines" + if "field_values" in (line.get("not_checked") or ()): return "evidence_scope_lines" return None diff --git a/packages/types/tests/test_post_save_screen.py b/packages/types/tests/test_post_save_screen.py index f93cbb389a..2c55162d0d 100644 --- a/packages/types/tests/test_post_save_screen.py +++ b/packages/types/tests/test_post_save_screen.py @@ -185,20 +185,31 @@ def test_a_screen_basis_with_unread_fields_does_not_validate() -> None: assert evidence_scope_problem(block) is None contradicts = dict(block, not_covered=[*block["not_covered"], "fields_not_read"]) assert evidence_scope_problem(contradicts) == "evidence_scope" - unread_line = [{"not_checked": ["field_values"]}] + unread_line = [{"check": "confirmed", "not_checked": ["field_values"]}] assert ( predicate_evidence_scope_problem( {"outcome": "VERIFIED", "lines": unread_line, "evidence_scope": block} ) == "evidence_scope_lines" ) - read_line = [{"not_checked": []}] + read_line = [{"check": "confirmed", "not_checked": []}] assert ( predicate_evidence_scope_problem( {"outcome": "VERIFIED", "lines": read_line, "evidence_scope": block} ) is None ) + # Every write the screen check covers must be confirmed. + unchecked = [*read_line, {"check": "not_checked", "not_checked": ["uncertain"]}] + assert ( + predicate_evidence_scope_problem( + {"outcome": "VERIFIED", "lines": unchecked, "evidence_scope": block} + ) + == "evidence_scope_lines" + ) + # Even a RECORDED block may not name a screen basis and unread fields. + recorded = dict(contradicts, word="RECORDED") + assert evidence_scope_problem(recorded) == "evidence_scope" _BASE = dict( diff --git a/packages/types/tests/vectors/record-run-v1/evidence-scope-screen-with-unchecked-write.json b/packages/types/tests/vectors/record-run-v1/evidence-scope-screen-with-unchecked-write.json new file mode 100644 index 0000000000..37d400b547 --- /dev/null +++ b/packages/types/tests/vectors/record-run-v1/evidence-scope-screen-with-unchecked-write.json @@ -0,0 +1,21 @@ +{ + "description": "A VERIFIED post_save_screen record with a write it did not check: refused.", + "document": { + "payload": "eyJfdHlwZSI6Imh0dHBzOi8vaW4tdG90by5pby9TdGF0ZW1lbnQvdjEiLCJwcmVkaWNhdGUiOnsiY2hlY2tzIjp7ImF1dGhvcml6YXRpb24iOnsiY29uZmlybWVkIjowLCJyZXF1aXJlZCI6MH0sImVmZmVjdHMiOnsiY29uZmlybWVkIjoxLCJyZXF1aXJlZCI6Mn0sImlkZW50aXR5Ijp7ImNvbmZpcm1lZCI6NSwicmVxdWlyZWQiOjV9LCJsaW5lc19jb25maXJtZWQiOjEsImxpbmVzX25vdF9jaGVja2VkIjoxLCJsaW5lc19yZWZ1dGVkIjowLCJwb3N0Y29uZGl0aW9ucyI6eyJjb25maXJtZWQiOjMsInJlcXVpcmVkIjozfX0sImRpc2Nsb3N1cmUiOnsiY29tbWl0bWVudHMiOnt9LCJ2ZXJzaW9uIjoib3BlbmFkYXB0LnB1YmxpYy1kaXNjbG9zdXJlL3YxIn0sImV2aWRlbmNlX3Njb3BlIjp7ImJhc2lzIjoicG9zdF9zYXZlX3NjcmVlbiIsImNoZWNrX2xldmVsIjoic2FtZV9zY3JlZW4iLCJub3RfY292ZXJlZCI6WyJzZXJ2ZXJfc2lkZV9hc3luY19lZmZlY3RzIiwib3V0Ym91bmRfZWZmZWN0cyIsImNoYW5nZXNfYWZ0ZXJfcmVhZF9iYWNrIiwicmVhZF9iYWNrX3RpbWUiXSwic2NoZW1hIjoib3BlbmFkYXB0LmV2aWRlbmNlLXNjb3BlL3YxIiwid2lyZSI6eyJjaGFubmVsIjoibm9uZSIsInByb3RvY29sc19wYXJzZWQiOltdfSwid29yZCI6IlZFUklGSUVEIn0sImxpbmVzIjpbeyJjaGVjayI6ImNvbmZpcm1lZCIsIm5vdF9jaGVja2VkIjpbXSwib3BlcmF0aW9uIjoid3JpdGUiLCJzdGVwIjoyLCJzdHJlbmd0aCI6InNhbWVfc2NyZWVuIiwidGFyZ2V0X2tpbmQiOiJndWkifSx7ImNoZWNrIjoibm90X2NoZWNrZWQiLCJub3RfY2hlY2tlZCI6WyJ1bmNlcnRhaW4iXSwib3BlcmF0aW9uIjoiaXJyZXZlcnNpYmxlX3dyaXRlIiwic3RlcCI6NCwic3RyZW5ndGgiOiJub25lIiwidGFyZ2V0X2tpbmQiOiJndWkifV0sIm1vZGVsX2NhbGxzIjowLCJvdXRjb21lIjoiVkVSSUZJRUQiLCJwcm9ncmFtIjp7ImlkIjoicHJvZy01YmIyMWFhMGYyZTZhYzMyIiwidmVyc2lvbl9zaGEyNTYiOiIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyIn0sInJlYXNvbl9jb2RlIjoidmVyaWZpZWQiLCJzdGFydGVkX2hvdXIiOiIyMDI2LTExLTIwVDIzOjAwOjAwWiIsInN0ZXBzIjp7Im9rIjo1LCJ0b3RhbCI6NX19LCJwcmVkaWNhdGVUeXBlIjoiaHR0cHM6Ly9vcGVuYWRhcHQuYWkvcmVjb3JkL3J1bi92MSIsInN1YmplY3QiOlt7ImRpZ2VzdCI6eyJzaGEyNTYiOiIxMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExIn0sIm5hbWUiOiJyZXBvcnQuanNvbiJ9LHsiZGlnZXN0Ijp7InNoYTI1NiI6IjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIifSwibmFtZSI6ImJ1bmRsZSJ9XX0=", + "payloadType": "application/vnd.in-toto+json", + "signatures": [ + { + "keyid": "seal-ed25519-b7a5ba90250d87f2", + "sig": "ybWvWCuWbU5qAGUkmFxJybAZApmAHUi9kgqW10aqgfRf7r8DN9Of9ahp52U3lmL/d/gGl2whno87RrQoHiJDBA==" + } + ] + }, + "expected": { + "ok": false, + "reason": "inconsistent", + "signer_lines": [ + "Not verified: the receipt contradicts itself" + ] + }, + "registry": "registry.json" +} diff --git a/packages/types/tests/vectors/record-run-v1/generate.py b/packages/types/tests/vectors/record-run-v1/generate.py index cb163893dd..f1a9ec84c0 100644 --- a/packages/types/tests/vectors/record-run-v1/generate.py +++ b/packages/types/tests/vectors/record-run-v1/generate.py @@ -249,6 +249,14 @@ def add(name, description, document, expected, openings=None): line.update(strength="same_screen", not_checked=[]) unread = copy.deepcopy(screen) unread["predicate"]["lines"][1]["not_checked"] = ["field_values"] + unchecked = copy.deepcopy(screen) + unchecked["predicate"]["lines"][1].update(check="not_checked", strength="none", not_checked=["uncertain"]) + unchecked["predicate"]["checks"].update(lines_confirmed=1, lines_not_checked=1, + effects={"required": 2, "confirmed": 1}) + add("evidence-scope-screen-with-unchecked-write", + "A VERIFIED post_save_screen record with a write it did not check: refused.", + _signed_raw(unchecked), {"ok": False, "reason": "inconsistent", + "signer_lines": [r.refusal_line("inconsistent")]}) add("evidence-scope-screen-with-unread-fields", "A VERIFIED post_save_screen record whose own line says a field value went unchecked: refused.", _signed_raw(unread), {"ok": False, "reason": "inconsistent", diff --git a/tests/test_post_save_screen_parity.py b/tests/test_post_save_screen_parity.py index 4e51efa867..d97ba1d4de 100644 --- a/tests/test_post_save_screen_parity.py +++ b/tests/test_post_save_screen_parity.py @@ -14,6 +14,10 @@ import pytest openadapt_types = pytest.importorskip("openadapt_types") +if not hasattr( + pytest.importorskip("openadapt_types.check_level"), "ScreenCheck" +): # the launcher's lock pins an openadapt-types from before the screen bases + pytest.skip("openadapt-types predates post_save_screen", allow_module_level=True) from openadapt_types.check_level import ( # noqa: E402 CheckLevel, ScreenCheck, @@ -47,7 +51,7 @@ def _flow_path(case): }, "VERIFIED", read_back_at=T, - screen_checks=[case["check"]], + screen_checks={"save": case["check"]}, ) assert evidence_scope_problem(scope) is None return scope["word"], scope.get("basis") @@ -97,6 +101,7 @@ def _wrap_path(case): level = CheckLevel.from_label(case["level"]) contract = { "schema_version": "test", + "outcome": "verified", "evidence_scope": build_evidence_scope( level, basis=basis, @@ -217,9 +222,10 @@ def test_a_wrap_word_needs_an_intact_wrap_receipt(monkeypatch) -> None: monkeypatch.setattr(verify_run_mod, "receipt_problem", lambda receipt: None) contract = { + "outcome": "verified", "evidence_scope": build_evidence_scope( CheckLevel.SYSTEM_OF_RECORD, basis="system_api", read_back_at=T - ) + ), } receipt = _build_receipt( outcome=WrapOutcome.CONFIRMED, @@ -239,6 +245,21 @@ def test_a_wrap_word_needs_an_intact_wrap_receipt(monkeypatch) -> None: assert wrap_receipt_word(bare, contract) == "RECORDED" edited = dict(receipt.to_dict(), action="other") assert wrap_receipt_word(edited, contract) == "RECORDED" + # A verified rollback does not support a confirmed write. + rollback = dict(contract, outcome="rolled_back_verified") + rolled = _build_receipt( + outcome=WrapOutcome.CONFIRMED, + checked_how="system_of_record", + action="save", + request_key="k", + arguments_sha256="0" * 64, + dispatched=True, + contract_receipt_sha256=receipt_sha256(rollback), + ) + assert wrap_receipt_word(rolled, rollback) == "RECORDED" + # A parent with another schema is not a wrap receipt. + other = dict(receipt.to_dict(), schema="openadapt.wrap_receipt/v9") + assert wrap_receipt_word(other, contract) == "RECORDED" def test_the_launcher_names_the_same_older_word_as_types() -> None: From 7f08b90b9dd5abc860423ec78c5582cce76c10eb Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 18:41:02 -0500 Subject: [PATCH 07/17] fix(receipts): refuse a missing kernel proof at mint, keep the kernel verifier total, ignore unkeyed Flow screen checks --- .../flow/openadapt_flow/evidence_basis.py | 3 +++ packages/flow/tests/test_post_save_screen.py | 12 +++++++++ .../kernel/src/openadapt_kernel/copilot.py | 12 ++++----- .../src/openadapt_kernel/receipt_bridge.py | 13 +++++++--- .../tests/test_post_save_screen_bridge.py | 25 +++++++++++++++++++ 5 files changed, 54 insertions(+), 11 deletions(-) diff --git a/packages/flow/openadapt_flow/evidence_basis.py b/packages/flow/openadapt_flow/evidence_basis.py index 632ff06e4a..b043ed590c 100644 --- a/packages/flow/openadapt_flow/evidence_basis.py +++ b/packages/flow/openadapt_flow/evidence_basis.py @@ -169,6 +169,9 @@ def evidence_scope_for_run( except ValueError: level = CheckLevel.UNCHECKED verified = str(outcome).upper() == VERIFIED_WORD + # Checks are keyed by step_id; any other shape earns nothing. + if not isinstance(screen_checks, Mapping): + screen_checks = {} saves = readback.get("saves") if isinstance(readback, Mapping) else None basis: Optional[Basis] = None if verified: diff --git a/packages/flow/tests/test_post_save_screen.py b/packages/flow/tests/test_post_save_screen.py index 44be1b8e7b..85a43dffac 100644 --- a/packages/flow/tests/test_post_save_screen.py +++ b/packages/flow/tests/test_post_save_screen.py @@ -144,3 +144,15 @@ def test_standard_accepts_the_screen_check_and_regulated_does_not() -> None: # Under Regulated, a separate-session read still verifies. stronger = _scope("separate_session", [], minimum=regulated) assert (stronger["word"], stronger["basis"]) == ("VERIFIED", "separate_session") + + +def test_checks_not_keyed_by_step_earn_nothing() -> None: + readback = { + "checked_how": "same_screen", + "minimum": "same_screen", + "saves": _saves("same_screen"), + } + scope = evidence_scope_for_run( + readback, "VERIFIED", read_back_at=T, screen_checks=[CASES[0]["check"]] + ) + assert scope["word"] == "RECORDED" diff --git a/packages/kernel/src/openadapt_kernel/copilot.py b/packages/kernel/src/openadapt_kernel/copilot.py index 1ada4b056a..42548b770c 100644 --- a/packages/kernel/src/openadapt_kernel/copilot.py +++ b/packages/kernel/src/openadapt_kernel/copilot.py @@ -280,14 +280,12 @@ def mint_receipt( obligations_payload: Dict[str, Any] = {} for oid, ob in ledger.obligations.items(): - if ( - ob.state in ("COMMITTED", "EXEMPT") - and ob.readback_proof is not None - and not ob.readback_proof.is_valid() + if ob.state in ("COMMITTED", "EXEMPT") and ( + ob.readback_proof is None or not ob.readback_proof.is_valid() ): - # The proof changed after it was accepted (a screen check that is - # no longer complete): never sign a result it no longer supports. - raise ValueError(f"read-back proof for {oid!r} is no longer valid") + # The proof changed or went missing after it was accepted: never + # sign a result it no longer supports. + raise ValueError(f"read-back proof for {oid!r} is missing or no longer valid") if ob.readback_proof is None: proof_obj: Optional[Dict[str, Any]] = None elif include_plaintext_values: diff --git a/packages/kernel/src/openadapt_kernel/receipt_bridge.py b/packages/kernel/src/openadapt_kernel/receipt_bridge.py index d838835ccf..7f6f81652e 100644 --- a/packages/kernel/src/openadapt_kernel/receipt_bridge.py +++ b/packages/kernel/src/openadapt_kernel/receipt_bridge.py @@ -723,15 +723,20 @@ def _validate_statement_consistency(statement: Mapping[str, Any]) -> Optional[st return "evidence_scope_outcome_mismatch" if outcome != "VERIFIED" and word in _VERIFIED_WORDS: return "evidence_scope_outcome_mismatch" - if scope.get("basis") in _SCREEN_BASES: + basis = scope.get("basis") + if isinstance(basis, str) and basis in _SCREEN_BASES: # A screen check confirms every write it covers and reads every # intended field (openadapt_types.evidence_scope). for line in lines: - if line.get("check") != "confirmed" or "field_values" in ( - line.get("not_checked") or () + skipped = line.get("not_checked") + if ( + line.get("check") != "confirmed" + or not isinstance(skipped, list) + or "field_values" in skipped ): return "evidence_scope_lines" - if "fields_not_read" in (scope.get("not_covered") or ()): + not_covered = scope.get("not_covered") + if not isinstance(not_covered, list) or "fields_not_read" in not_covered: return "evidence_scope_lines" return None diff --git a/packages/kernel/tests/test_post_save_screen_bridge.py b/packages/kernel/tests/test_post_save_screen_bridge.py index 189965ddac..529c21291d 100644 --- a/packages/kernel/tests/test_post_save_screen_bridge.py +++ b/packages/kernel/tests/test_post_save_screen_bridge.py @@ -217,3 +217,28 @@ def test_the_kernel_verifier_agrees_with_the_shared_vectors(name: str, ok: bool) vector["document"], base64.b64decode(key["public_key"]) ) assert got is ok, reason + + +def test_minting_refuses_a_missing_proof() -> None: + priv, _ = generate_ephemeral_ed25519_keypair() + ledger = ObligationLedger(episode_id="ep-missing") + ledger.add_obligation("save", "Save", target_system="https://records.example.test") + ledger.mark_committed("save", _proof("post_save_screen", dict(COMPLETE))) + ledger.finalize("done") + ledger.obligations["save"].readback_proof = None + with pytest.raises(ValueError): + mint_receipt(ledger, "screen-save-v1", priv) + + +def test_a_malformed_screen_receipt_is_refused_not_raised() -> None: + from openadapt_kernel.receipt_bridge import _validate_statement_consistency + + priv, pub = generate_ephemeral_ed25519_keypair() + envelope = kernel_receipt_to_dsse_record(_complete_receipt(priv), priv, surface="dom") + statement = json.loads(base64.b64decode(envelope["payload"])) + odd = copy.deepcopy(statement) + odd["predicate"]["evidence_scope"]["basis"] = ["post_save_screen"] + _validate_statement_consistency(odd) # no exception + odd = copy.deepcopy(statement) + odd["predicate"]["lines"][0]["not_checked"] = 7 + assert _validate_statement_consistency(odd) is not None From 3bd3266803303fb25d729a68273864b65b2c3062 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 19:11:09 -0500 Subject: [PATCH 08/17] feat(flow): record a post-save screen check per save and earn post_save_screen from it The runtime now observes, after each save on a backend that can read the page, what a careful person checks: every value the run typed for the save read in a field (bound to its label, alone on a line, or in a labelled cell), the form no longer holding the values, and no new error (error regions, aria-invalid, or failure words on new lines). Counts and flags only go into report.json (StepResult.post_save_screen, ReadbackSave.screen_check, both omitted when unset), and the run receipt earns post_save_screen from them. MockMed's patient record view now shows each saved encounter's fields with labels (Type: ... | Note: ...), as a real EMR's record view does; the banner is unchanged. --- .../benchmark/post_save_screen/run_proof.py | 145 +++++ .../flow/benchmark/ui_readback/gui_harness.py | 4 +- .../backends/playwright_backend.py | 123 ++++ packages/flow/openadapt_flow/ir.py | 47 ++ .../flow/openadapt_flow/mockmed/static/app.js | 5 +- .../flow/openadapt_flow/readback_ladder.py | 24 +- .../flow/openadapt_flow/receipt_record.py | 18 +- .../runtime/post_save_screen.py | 190 ++++++ .../openadapt_flow/runtime/replay/effects.py | 14 + .../flow/openadapt_flow/runtime/replayer.py | 24 + .../openadapt_flow.deployment.json | 60 ++ .../schema_surface/openadapt_flow.ir.json | 541 +++++++++++++++--- packages/flow/tests/test_mockmed.py | 2 +- .../tests/test_post_save_screen_runtime.py | 184 ++++++ 14 files changed, 1281 insertions(+), 100 deletions(-) create mode 100644 packages/flow/benchmark/post_save_screen/run_proof.py create mode 100644 packages/flow/openadapt_flow/runtime/post_save_screen.py create mode 100644 packages/flow/tests/test_post_save_screen_runtime.py diff --git a/packages/flow/benchmark/post_save_screen/run_proof.py b/packages/flow/benchmark/post_save_screen/run_proof.py new file mode 100644 index 0000000000..34105b3d53 --- /dev/null +++ b/packages/flow/benchmark/post_save_screen/run_proof.py @@ -0,0 +1,145 @@ +"""Prove the post-save screen check on a real headless run. + +The quickstart's MockMed task, compiled the way a customer without database +access gets it: the recording keeps no system-of-record snapshots, so the +compiler mines an on-screen read-back for the save instead of a database +check, and the run uses no effect verifier. The run then signs its receipt. + +Usage (from packages/flow):: + + python benchmark/post_save_screen/run_proof.py OUT_DIR [--fault ok|timeout] + +``--fault ok`` is the clean save. ``--fault timeout`` makes MockMed show +"Save timed out" with the form still open; its receipt must not be VERIFIED. +Writes OUT_DIR/run--