@skyramp/testbot-core 0.13.3-v3.555 → 0.13.3-v3.556

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -265,7 +265,7 @@ else require("node:test").test(spec.name, () => { throw new Error("required shar
265
265
  `),s}o(mEe,"conformed");function _l(e,t,n){if(n.length>dEe||n.includes(0))return n;let i=xr.resolve(e),r=hEe(i,xr.resolve(i,t),s=>{try{return AEe(ab.readFileSync(xr.join(s,".editorconfig"),"utf-8"))}catch{return}});return Buffer.from(mEe(n.toString("latin1"),r),"latin1")}o(_l,"conformDeliveredBytes");var VY=ee(require("fs")),zY=ee(require("path"));function Uo(e=__dirname){try{let t=VY.readFileSync(zY.join(e,"VERSION.json"),"utf-8"),n=JSON.parse(t);if(typeof n.version=="string"&&typeof n.commit=="string")return{version:n.version,commit:n.commit}}catch{}return{version:"unknown",commit:"unknown"}}o(Uo,"getTestbotVersion");var lc=ee(require("node:fs")),dc=ee(require("node:path"));function V0(e,t){let n=dc.relative(e,t);try{let i=lc.lstatSync(t);if(i.isSymbolicLink())return"test entry is a symlink";if(!i.isFile())return"test entry is not a regular file";let r=lc.realpathSync(e),s=lc.realpathSync(t),a=dc.relative(r,s);return!a||a.startsWith("..")||dc.isAbsolute(a)?`test entry's real path is outside the checkout (${a})`:a!==n?`test entry's real path is ${a}, not ${n}, after canonicalisation`:void 0}catch(i){return i.code==="ENOENT"?`test entry is missing: no file is at ${n} in the checkout`:`test entry cannot be read: ${Pl(i,e)}`}}o(V0,"guardedEntryProblem");function Nl(e,t){let n=V0(e,t);if(n)return n;try{return lc.readFileSync(t)}catch(i){return`test entry cannot be read: ${Pl(i,e)}`}}o(Nl,"readGuardedEntry");function Pl(e,t){return(e instanceof Error?e.message:String(e)).split(t+dc.sep).join("")}o(Pl,"errorWithoutCheckout");function yEe(e){return ve(e,`${Z$}.json`)?.guardUnavailable===!0}o(yEe,"writeGuardUnavailable");function qY(e){let t=ve(e,"recommend.json"),n=ve(e,`${Z$}.json`),i=new Map(yEe(e)?(t?.generate??[]).map(({id:r})=>[r,wE]):[]);for(let{id:r,reason:s}of t?.withheld??[])i.has(r)||i.set(r,`off-limits execution (${s??"environment policy"})`);if(n?.browserWithheld)for(let r of t?.generate??[])r.type==="ui"&&!i.has(r.id)&&i.set(r.id,"the shared-environment browser guard is unavailable");return i}o(qY,"writeExecutionRestrictions");function HY(e,t){let n=new Set((e.covers??[]).flatMap(i=>{let r=t.get(i);return r?[r]:[]}));return n.size?`environment restriction: ${[...n].join("; ")}`:void 0}o(HY,"writtenRestriction");function bEe(e){return!!e.guardedDelivery||!!e.context?.some(t=>t.safety?.route==="persistence")}o(bEe,"keepsSharedData");function Ul(e,t){let n=e.inputs.sharedEnvironment?.environmentAddress;return!!n&&(t.result?.cases??[]).some(i=>i.runtimeTargets?.some(r=>uo(n,r)))}o(Ul,"usesSharedRuntime");function hg(e,t,n=Uo().version){if(!On(e.inputs))return[];let i=e.inputs.sharedEnvironment,r=i?.environmentAddress,s=ve(e,GC),a=f1.safeParse(s),c=a.success&&a.data.environmentId===i?.environmentId&&a.data.environmentAddress===r?a.data:void 0,u=g1.safeParse(s),l=u.success?wp(u.data.refusal):a.success?wp("changed"):wp("unavailable"),p=qY(e),f=new Map(sb(e,t).map(v=>[v.file,v.verdict])),A=Q0(R0(e)),h=ve(e,"recommend.json"),m=new Map((h?.generate??[]).map(({id:v,target:I})=>[v,I])),E=An(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),b=new Map;for(let v of t.tests){if(v.change==="deleted")continue;let I=E(v.file);if(!Zr(I)||Qo(I.rel))continue;let C=Es(e.inputs,I.repository);if("error"in C)continue;let x=C.source,w=Ut.resolve(x.path,I.rel),$=HY(v,p)??vEe(A,I),B=bEe(v),Z=Ul(e,v),ie;if(!$&&!Z&&!B){if(!w.endsWith(".test.cjs"))continue;try{if(!z0(x.path,w))continue;ie=$s(Lt.readFileSync(w,"utf8"))}catch{continue}if(!ie||"restriction"in ie)continue}let H=(v.covers??[]).flatMap(Bt=>{let Xe=m.get(Bt)?.match(/^(GET|HEAD|OPTIONS|POST|PUT|PATCH|DELETE)\s+(\S+?)[,;]?(?:\s|$)/i);return!Xe||!r?[]:Xe[2].startsWith("/")||uo(r,Xe[2])?[{method:Xe[1].toUpperCase(),route:Xe[2]}]:[]}),me=REe(e,x.path,I.rel);if(!$&&v.change!=="added"&&(me===!1||me===void 0&&!e.inputs.deliver))continue;let _e=o(Bt=>`${v.file}: shared-environment delivery is blocked: ${Bt}`,"problem"),Ue={repository:x.slug,file:I.rel,sourceAsset:`${I.rel}.source`},Ie=Nl(x.path,w);if(typeof Ie=="string"){b.set(w,{record:Ue,source:x,original:Buffer.alloc(0),problems:[_e(`${Ie} (planGuardedDelivery)`)]});continue}if(v.change!=="added"&&Ei(e,x.path,I.rel)){$&&(Ue.reason=$,b.set(w,{record:Ue,source:x,original:Ie,problems:[]}));continue}if(me===!1||v.change!=="added"&&me!==!0){b.set(w,{record:Ue,source:x,original:Ie,problems:[_e(me===!1?"the file changes an existing test; retain the assertions in a new file":"cannot prove whether the shared test already exists; use a host-pinned checkout")]});continue}if(ie??=$s(Ie.toString("utf8")),!$&&ie&&"restriction"in ie)continue;let K,V=rb.safeParse(v.guardedDelivery),Me=c&&i?{environmentId:c.environmentId,environmentAddress:c.environmentAddress,persistenceRevision:c.revision,offLimits:i.offLimits??[],route:{kind:"persistence"}}:void 0,Ze=`environment restriction: persistence permission was not confirmed at generation: ${l}`;if($)K=$;else if(B&&!Me)K=Ze;else if(!V.success||!Me)K="no guarded HTTP representation preserves the test's assertions";else if(!v.covers?.length||(v.functions?.length??1)!==1)K="guarded HTTP delivery requires one test function";else if(!/\.test\.cjs$/.test(I.rel)||!SEe(v.ci))K="the test has no compatible Node CI entry";else if(!v.ci?.collected&&f.get(v.file)!=="not-collected")K="Testbot could not confirm that the repo's CI leaves it out, and only node --test can run the entry";else if(!kEe(x.path,w,n))K=`the CI package does not declare @skyramp/testbot-core ${n}, the released guarded runtime the entry needs`;else{let{steps:Bt}=V.data,Xe=Me.offLimits.length?Y$(e.inputs.skyrampMcp,Me.offLimits):void 0,yn=new Map,gt=Bt.flatMap(ut=>{if(ut.op==="create"){let ne=IEe(Me.environmentAddress,ut.collection);return ne&&yn.set(ut.as,ne),[{method:"POST",url:ne,child:!1}]}if(ut.op!=="read"&&ut.op!=="update")return[];let $e=yn.get(ut.resource);return $e&&yn.set(ut.as,$e),[{method:ut.op==="read"?"GET":ut.method??"PATCH",url:$e,child:!0}]});gt.some(({url:ut})=>!ut)?K="the guarded HTTP steps name an unknown resource or a collection outside the Test Environment":Xe&&i&&gt.some(({url:ut,child:$e})=>!$e&&Qq(ut.href,i,Xe))?K="the guarded HTTP steps name an off-limits collection":H.length&&!H.some(({method:ut,route:$e})=>gt.some(ne=>ne.url&&ne.method===ut&&wEe(Me.environmentAddress,ne.url,ne.child,$e)))&&(K="the guarded HTTP steps do not represent the planned HTTP operation")}let jt;if(K)Ue.reason=K;else if(V.success&&Me){let{bearerTokenEnv:Bt,...Xe}=V.data;jt={...Xe,definition:{...Me,...Bt?{bearerTokenEnv:Bt}:{}}},Ue.entry=I.rel}let ct=Ut.resolve(x.path,Ue.sourceAsset),on=lb(ct)&&!Ag(x.path,ct,Ie)?[_e("the inert source asset path already contains different bytes")]:[];b.set(w,{record:Ue,source:x,original:Ie,spec:jt,problems:on})}return[...b.values()]}o(hg,"planGuardedDelivery");function vEe(e,t){return e.find(n=>x0(n,{file:t.rel,repository:t.repository}))?.environmentRestriction}o(vEe,"restrictionRecordedAtRun");function IEe(e,t){try{let n=new URL(t,`${e.replace(/\/$/,"")}/`);return!n.search&&!n.hash&&!n.username&&!n.password&&!/[\\]|%(?:2f|5c|2e|25)/i.test(t)&&uo(e,n.href)?n:void 0}catch{return}}o(IEe,"guardedCollection");function wEe(e,t,n,i){try{let r=new URL(i,t.origin),s=i.startsWith("/")&&!i.startsWith("//")&&!uo(e,r.href)?new URL(i.slice(1),`${e.replace(/\/$/,"")}/`):r;if(!uo(e,s.href))return!1;let a=t.pathname.replace(/\/$/,""),c=s.pathname.replace(/\/$/,"");if(!n)return c===a;if(!c.startsWith(`${a}/`))return!1;let u=decodeURIComponent(c.slice(a.length+1));return/^(:[\w-]+|\{[^/{}]+\}|<[^/<>]+>)$/.test(u)}catch{return!1}}o(wEe,"representsRoute");function CEe(e){return!!e&&/^(?:node|node:test|node\s+(?:.*\s)?--test(?:\s.*)?)$/i.test(e.trim())}o(CEe,"nodeTestRunner");function SEe(e){return e?.collected===!1||!!e?.collected&&CEe(e.runner)}o(SEe,"nodeTestEntry");function z0(e,t){let n=Lt.realpathSync(e);return Lt.lstatSync(t).isFile()&&Lt.realpathSync(t)===Ut.join(n,Ut.relative(e,t))}o(z0,"regularFileIn");function Ag(e,t,n){try{return z0(e,t)&&Lt.readFileSync(t).equals(n)}catch{return!1}}o(Ag,"sameRegularBytes");function lb(e){try{return Lt.lstatSync(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}o(lb,"pathExists");function kEe(e,t,n){if(n==="unknown")return!1;for(let i=Ut.dirname(t);;i=Ut.dirname(i)){let r=Ut.join(i,"package.json");if(lb(r))try{if(!z0(e,r))return!1;let s=JSON.parse(Lt.readFileSync(r,"utf-8"));return(s.devDependencies?.["@skyramp/testbot-core"]??s.dependencies?.["@skyramp/testbot-core"])===n}catch{return!1}if(i===e)return!1}}o(kEe,"hasGuardRuntime");function BEe(e){let t=ve(e,"write.json");return t?hg(e,t):[]}o(BEe,"guardedDeliveryPlan");function JY(e,t=BEe(e),n=[],i=[]){return t.flatMap(({record:r,source:s,original:a,spec:c,problems:u})=>{if(u.length)return u;let l=Ut.join(s.path,r.sourceAsset),p=Ut.join(s.path,r.file),f=`reading ${r.file}`;try{let A=Nl(s.path,p);if(typeof A=="string")return[`${r.file}: ${A} (writeGuardedDeliveryFiles)`];if(!A.equals(a))return[`${r.file}: native source changed before guarded delivery`];f=`preparing ${r.sourceAsset}`;let h=uc(a.toString("utf-8"),n).content;if(no(h,e.secretValues??[])!==h)return[`${r.file}: the retained source contains a credential`];let m=_l(s.path,r.sourceAsset,Buffer.from(h));if(f=`writing ${r.sourceAsset}`,lb(l)){if(!Ag(s.path,l,a)&&!Ag(s.path,l,m))return[`${r.file}: the inert source asset path already contains different bytes`];Ag(s.path,l,m)||(i.push(()=>Lt.writeFileSync(l,a)),Lt.writeFileSync(l,m))}else Lt.writeFileSync(l,m,{flag:"wx"}),i.push(()=>Lt.rmSync(l,{force:!0}));if(r.entry&&c){let E=cg({...c,name:Dl(c.name,n)}),b=_l(s.path,r.entry,Buffer.from(E));if(!$s(b.toString("utf-8")))return[`${r.file}: the repository's file conventions changed the guarded entry`];if(no(b.toString("utf-8"),e.secretValues??[])!==b.toString("utf-8"))return[`${r.file}: guarded delivery steps include a credential`];f=`writing ${r.entry}`,i.push(()=>Lt.writeFileSync(p,a)),Lt.writeFileSync(p,b)}return[]}catch(A){return[`${r.file}: could not assemble its guarded delivery files (writeGuardedDeliveryFiles): ${f} failed: ${Pl(A,s.path)}`]}})}o(JY,"writeGuardedDeliveryFiles");function REe(e,t,n){let i=e.executionSafetySources?.find(r=>Ut.resolve(r.path)===Ut.resolve(t));if(i)try{return(0,ub.execFileSync)("git",["--literal-pathspecs","ls-tree",i.head,"--",n],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]})===""}catch{return}}o(REe,"newAtSourcePin");function Ei(e,t,n){let i=e.executionSafetySources?.find(r=>Ut.resolve(r.path)===Ut.resolve(t));if(!i||!/^[a-f0-9]{40,64}$/.test(i.head))return!1;try{let r=Ut.join(t,n),s=Lt.lstatSync(r);if(!s.isFile()||Lt.realpathSync(r)!==r)return!1;let a=db(t,i.head,n);return!a||(s.mode&73)!==0!==a.executable?!1:Lt.readFileSync(r).equals(a.bytes)}catch{return!1}}o(Ei,"unchangedSource");var cb=new Map;function db(e,t,n){let i=`${Ut.resolve(e)}\0${t}\0${n}`,r=cb.get(i);if(r!==void 0)return r;let s=null;try{let a=(0,ub.execFileSync)("git",["--literal-pathspecs","ls-tree",t,"--",n],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]});/^100(?:644|755) blob /.test(a)&&(s={executable:a.startsWith("100755"),bytes:(0,ub.execFileSync)("git",["show",`${t}:${n}`],{cwd:e,stdio:["ignore","pipe","ignore"]})})}catch{s=null}return cb.size>=1e4&&cb.clear(),cb.set(i,s),s}o(db,"pinnedBlob");function YY(e,t,n,i){if(!i.size)return[...n];let r=new Map(n.map(a=>[Ut.resolve(a.source.path,a.record.file),a])),s=An(e.inputs.repositoryPath,e.inputs.relatedRepos??[]);for(let a of t.tests){if(a.change==="deleted")continue;let c=s(a.file);if(!Zr(c)||Qo(c.rel))continue;let u=Es(e.inputs,c.repository);if("error"in u)continue;let l=u.source,p=Ut.resolve(l.path,c.rel),f=i.get(p);if(!f)continue;let A=r.get(p);if(A){if(A.record.reason)continue;let I={...A.record,reason:f};delete I.entry,r.set(p,{...A,record:I,spec:void 0});continue}let h={repository:l.slug,file:c.rel,sourceAsset:`${c.rel}.source`,reason:f},m=o(I=>[`${a.file}: shared-environment delivery is blocked: ${I}`],"problem"),E=Nl(l.path,p);if(typeof E=="string"){r.set(p,{record:h,source:l,original:Buffer.alloc(0),problems:m(`${E} (holdDependents)`)});continue}let b=Ut.resolve(l.path,h.sourceAsset),v=lb(b)&&!Ag(l.path,b,E)?m("the inert source asset path already contains different bytes"):[];r.set(p,{record:h,source:l,original:E,problems:v})}return[...r.values()]}o(YY,"holdDependents");var Kr=ee(require("node:fs")),Se=ee(require("node:path"));var pc=ee(require("path"));var q2e={python:"pytest",typescript:"playwright",javascript:"playwright"},H2e={pytest:"pytest",playwright:"playwright"};var DEe=new Set(["package.json","package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb","pyproject.toml","poetry.lock","uv.lock","pdm.lock","Pipfile","Pipfile.lock","setup.py","setup.cfg","go.mod","go.sum","Gemfile","Gemfile.lock","pom.xml","build.gradle","build.gradle.kts"]);function pb(e){let t=pc.basename(e);return DEe.has(t)||/^requirements[^/\\]*\.(txt|in)$/.test(t)}o(pb,"isDependencyFile");var KY="shared-environment delivery cannot verify it for guarded execution",XY=o((e,t)=>`${fi(e.inputs,t.source.slug)}${t.file}`,"omittedLabel");function fb(e,t,n){let i=An(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),r=new Set(n.map(s=>Se.resolve(s.source.path,s.record.file)));return t.tests.filter(s=>{let a=i(s.file);return!r.has(Se.resolve(a.root,a.rel))&&s.change!=="updated"&&Ul(e,s)})}o(fb,"unplannedSharedTests");function gb(e,t,n,i){let r=An(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),s=new Map(n.map(u=>[Se.resolve(u.source.path,u.record.file),u])),a=new Set,c=[];for(let u of t.tests){let l=r(u.file),p=Se.resolve(l.root,l.rel),f=s.get(p);if(f){a.add(Se.resolve(l.root,f.record.sourceAsset)),f.record.entry&&a.add(p);continue}if(u.change==="deleted"){HEe(e,l.root,l.rel)?a.add(p):c.push(`${u.file}: a deleted shared-environment test must actually be absent and be a tracked regular file in the host-pinned source`);continue}if(u.change==="updated"||!Ul(e,u)){a.add(p);continue}if(Ei(e,l.root,l.rel)){a.add(p);continue}try{let A=$s(Kr.readFileSync(p,"utf-8"));if(!A)continue;if(a.add(p),"restriction"in A){let h=Se.resolve(Se.dirname(p),A.sourceAsset.path);a.add(h),!i.has(h)&&!Ei(e,l.root,Se.relative(l.root,h))&&c.push(`${u.file}: its restricted source asset is missing from the actual delivery commit`)}}catch{}}return{allowed:a,problems:c}}o(gb,"verifiedDeliveryPaths");function Ab(e,t,n,i){let r=[];for(let[s,a]of t)for(let c of a)n.has(Se.resolve(s.path,c))||!i.length&&!e.inputs.deliver&&Uo().version==="unknown"||qEe(e,s.path,c)||Ei(e,s.path,c)||r.push({source:s,file:c});return r}o(Ab,"unverifiedDeliveryPaths");var eW=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".json"],tW=/(?:\bfrom\s*|\bimport(?:\s*\()?\s*|\brequire\s*\(\s*)["'`]([^"'`\n]+)["'`]/g,_Ee=/^[ \t]*from[ \t]+([.\w]+)[ \t]+import[ \t]+\(?([\w\t ,*]+)/gm,NEe=/^[ \t]*import[ \t]+([\w.]+)/gm;function PEe(e,t){if(!/^\.\.?(?:\/|$)/.test(t))return[];let n=Se.resolve(e,t),i=/\.[cm]?jsx?$/.test(n)?[n.replace(/\.([cm]?)js(x?)$/,".$1ts$2")]:[];return[n,...i,...eW.flatMap(r=>[n+r,Se.join(n,`index${r}`)])]}o(PEe,"jsCandidates");function WY(e,t,n,i){let r=/^\.*/.exec(n)[0].length,s=n.slice(r).split(".").filter(Boolean);return(r?[Se.resolve(t,...Array(r-1).fill(".."))]:[e,t]).flatMap(c=>{let u=Se.join(c,...s);return[`${u}.py`,Se.join(u,"__init__.py"),...i.map(l=>Se.join(u,`${l}.py`))]})}o(WY,"pyCandidates");function UEe(e,t,n){let i=Se.dirname(t),r=new Set;if(t.endsWith(".py")){for(let[,s,a]of n.matchAll(_Ee))for(let c of WY(e,i,s,a.split(/[\s,]+/).filter(u=>/^\w+$/.test(u))))r.add(c);for(let[,s]of n.matchAll(NEe))for(let a of WY(e,i,s,[]))r.add(a)}else for(let[,s]of n.matchAll(tW))for(let a of PEe(i,s))r.add(a);return r}o(UEe,"importedFiles");function FEe(e,t){let n=new Set;if(e.endsWith(".py")||e.endsWith(".go"))return n;for(let[,i]of t.matchAll(tW)){if(/^\.\.?(?:\/|$)/.test(i)||/^[a-z][\w+.-]*:/i.test(i))continue;let r=i.split("/").pop()??"";r&&n.add(r.replace(/\.[cm]?[jt]sx?$/,""))}return n}o(FEe,"aliasedStems");function OEe(e,t){let n=Se.extname(t);if(!eW.includes(n))return!1;let i=Se.basename(t,n);return e.has(i)||i==="index"&&e.has(Se.basename(Se.dirname(t)))}o(OEe,"aliasNeeds");function MEe(e,t){let n=Se.basename(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?<![\\w.-])${n}(?![\\w.-])`).test(e)}o(MEe,"mentions");function ZY(e,t){for(let n=Se.dirname(t);;n=Se.dirname(n)){if(Kr.existsSync(Se.join(n,"go.mod")))return n;if(n===e||Se.dirname(n)===n)return e}}o(ZY,"goModule");function LEe(e,t){let n=[];t.isolatedRun&&n.push({cwd:".",text:t.isolatedRun}),t.run&&n.push({cwd:t.run.cwd,text:t.run.argv.join(" ")}),t.ci?.list&&n.push({cwd:t.ci.list.cwd,text:t.ci.list.argv.join(" ")});for(let r of t.ci?.steps??[])n.push({cwd:".",text:r.line});for(let r of t.context??[])r.cleanup&&n.push({cwd:".",text:r.cleanup});let i=new Set;for(let{cwd:r,text:s}of n)for(let a of s.split(/[\s"'`;&|()<>=,]+/))a&&!/^[a-z][\w+.-]*:/i.test(a)&&i.add(Se.resolve(e,r,a));return i}o(LEe,"commandFiles");var jEe={".py":"python",".js":"node",".cjs":"node",".mjs":"node",".jsx":"node",".ts":"node",".cts":"node",".mts":"node",".tsx":"node",".go":"go",".rb":"ruby",".java":"jvm",".kt":"jvm",".kts":"jvm",".scala":"jvm",".groovy":"jvm"},GEe=[[/^(?:playwright|vitest|jest)\.config\.(?:[cm]?[jt]s|json)$/,"node"],[/^tsconfig\.json$/,"node"],[/^(?:pytest|tox)\.ini$/,"python"]];function VEe(e){let t=Se.basename(e);if(["conftest.py","__init__.py"].includes(t))return"python";let n=GEe.find(([i])=>i.test(t));if(n)return n[1];if(pb(e))return/^(?:package\.json|package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lockb?)$/.test(t)?"node":/^go\.(?:mod|sum)$/.test(t)?"go":/^Gemfile(?:\.lock)?$/.test(t)?"ruby":/^(?:pom\.xml|build\.gradle(?:\.kts)?)$/.test(t)?"jvm":"python"}o(VEe,"implicitEcosystem");function zEe(e,t,n){let i=jEe[Se.extname(t)];if(i==="go"&&Se.extname(n)===".go"&&ZY(e,n)===ZY(e,t))return!0;let r=VEe(n);if(!r||i&&i!==r)return!1;let s=Se.relative(Se.dirname(n),t);return!s.startsWith("..")&&!Se.isAbsolute(s)}o(zEe,"implicitlyNeeds");function nW(e,t,n){let i=new Map;if(!n.length)return i;let r=An(e.inputs.repositoryPath,e.inputs.relatedRepos??[]);for(let s of t.tests){if(s.change==="deleted")continue;let a=r(s.file);if(!Zr(a)||Ei(e,a.root,a.rel))continue;let c=Se.resolve(a.root),u=Se.resolve(c,a.rel),l=n.filter(E=>Se.resolve(E.source.path)===c);if(!l.length)continue;let p="";try{p=Kr.readFileSync(u,"utf-8")}catch{}let f=UEe(c,u,p),A=FEe(u,p),h=LEe(c,s),m=l.filter(E=>{let b=Se.resolve(c,E.file);return f.has(b)||h.has(b)||OEe(A,b)||MEe(p,b)||zEe(c,u,b)});m.length&&i.set(u,`needs ${m.map(E=>XY(e,E)).join(", ")}, which is not in the tests PR: ${KY}`)}return i}o(nW,"supportDependents");function Fo(e){return Array.isArray(e)?`[${e.map(Fo).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Fo(n)}`).join(",")}}`:JSON.stringify(e)??"undefined"}o(Fo,"stable");function qEe(e,t,n){let i=Se.basename(n);if(i!=="package.json"&&i!=="package-lock.json")return!1;let r=Uo().version;if(r==="unknown")return!1;let s,a;try{let c=Se.resolve(t,n);if(!Kr.lstatSync(c).isFile()||Kr.realpathSync(c)!==c)return!1;s=JSON.parse(Kr.readFileSync(c,"utf-8"));let u=e.executionSafetySources?.find(A=>Se.resolve(A.path)===Se.resolve(t));if(u){let A=db(t,u.head,n);A&&(a=JSON.parse(A.bytes.toString("utf-8")))}else if(Kr.existsSync(Se.join(t,".git")))return!1;let l=o(A=>{let h=structuredClone(A);for(let m of["dependencies","devDependencies"])h[m]&&(delete h[m]["@skyramp/testbot-core"],Object.keys(h[m]).length||delete h[m]);return h},"withoutCore");if(i==="package.json")return(s.devDependencies?.["@skyramp/testbot-core"]??s.dependencies?.["@skyramp/testbot-core"])!==r?!1:a?Fo(l(s))===Fo(l(a)):Object.keys(s).every(A=>["name","version","private","type","scripts","dependencies","devDependencies"].includes(A))&&(!s.scripts||Fo(s.scripts)===Fo({test:"node --test"}))&&Object.keys(s.dependencies??{}).every(A=>A==="@skyramp/testbot-core")&&Object.keys(s.devDependencies??{}).every(A=>A==="@skyramp/testbot-core");let p=s.packages?.["node_modules/@skyramp/testbot-core"];if(!p||p.version!==r||p.link||p.hasInstallScript||p.resolved!==`https://registry.npmjs.org/@skyramp/testbot-core/-/testbot-core-${r}.tgz`||!/^sha512-[A-Za-z0-9+/=]+$/.test(p.integrity??""))return!1;let f=o(A=>{let h=structuredClone(A);return h.packages&&(delete h.packages["node_modules/@skyramp/testbot-core"],h.packages[""]&&(h.packages[""]=l(h.packages[""]))),h},"stripped");return a?Fo(f(s))===Fo(f(a)):Object.keys(s.packages??{}).every(A=>A===""||A==="node_modules/@skyramp/testbot-core")&&!s.packages?.[""]?.scripts}catch{return!1}}o(qEe,"safeRuntimeManifest");function HEe(e,t,n){try{return Kr.lstatSync(Se.join(t,n)),!1}catch(r){if(r.code!=="ENOENT")return!1}let i=e.executionSafetySources?.find(r=>Se.resolve(r.path)===Se.resolve(t));return!i||!/^[a-f0-9]{40,64}$/.test(i.head)?!1:db(t,i.head,n)!==null}o(HEe,"trackedDeletion");function JEe(e){try{return hb.lstatSync(e),!0}catch{return!1}}o(JEe,"lexists");function mb(e,t=mg(e)){let n=new Set(t.omitted.map(({source:i,file:r})=>Dt.resolve(i.path,r)));return new Map([...rW(e,t.assemblies)].map(([i,r])=>[i,r.filter(s=>!n.has(Dt.resolve(i.path,s)))]))}o(mb,"deliverAllowlist");function mg(e,t=ve(e,"write.json")){if(!t||!On(e.inputs))return{assemblies:[],omitted:[],hasSharedTests:!1};let n=hg(e,t),i=An(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),r=new Set(t.tests.map(c=>{let u=i(c.file);return Dt.resolve(u.root,u.rel)})),s=[],a=n;for(;;){let c=a.length>0||fb(e,t,a).length>0;if(!c)return{assemblies:a,omitted:s,hasSharedTests:c};let u=rW(e,a),l=new Set([...u].flatMap(([h,m])=>m.map(E=>Dt.resolve(h.path,E)))),{allowed:p}=gb(e,t,a,l),f=new Set(s.map(({source:h,file:m})=>Dt.resolve(h.path,m))),A=Ab(e,u,p,a).filter(({source:h,file:m})=>{let E=Dt.resolve(h.path,m);return!f.has(E)&&!r.has(E)});if(!A.length)return{assemblies:a,omitted:s,hasSharedTests:c};s.push(...A),a=YY(e,t,n,nW(e,t,s))}}o(mg,"sharedDeliveryPlan");function rW(e,t){let n=new Set(t.filter(({record:b})=>!b.entry).map(({source:b,record:v})=>Dt.join(b.path,v.file))),i=ve(e,"adapt.json"),r=ve(e,"finalize.json"),s=ve(e,gg),a=new Map,c=o(b=>{let v=Es(e.inputs,b);if("error"in v)return;let I=a.get(v.source.path)??{source:v.source,paths:new Set};return a.set(v.source.path,I),{repo:I.source.path,paths:I.paths}},"pathsOf"),u=o((b,v)=>Dt.relative(b,Dt.resolve(b,v.trim())).replace(/\/+$/,""),"norm"),l=o((b,v)=>{let I=v?.trim()&&c(b);if(!I)return;let C=u(I.repo,v);I.paths.add(C);for(let x of["__init__.py","conftest.py"]){let w=Dt.join(Dt.dirname(C),x);hb.existsSync(Dt.join(I.repo,w))&&(!n.has(Dt.join(I.repo,C))||!Ei(e,I.repo,w))&&I.paths.add(w)}},"addTest"),p=o((b,v)=>{if(typeof v!="string"||!v.trim())return;let I=c(b);if(!I)return;let C=u(I.repo,v);if(eg(Dt.join(I.repo,C)))return I.paths.add(C),{...I,rel:C}},"addEdited"),f=M0(e),A=(i?.items??[]).filter(b=>b.action==="place"&&f.has(b.from??b.file??"")),h=o((b,v)=>A.some(I=>I.repository===b&&I.file&&Dt.normalize(I.file)===v),"heldIn"),m=(i?.items??[]).filter(b=>!A.includes(b));for(let b of[...m,...s?.tests??[],...s?.maintained??[]])l(b.repository,b.file);for(let b of r?.dependencies?.added??[]){let v=p(b.repository,b.manifest);if(v)for(let I of d0(v.repo,JE(v.repo,v.rel)))v.paths.add(I)}for(let b of r?.lint??[])for(let v of b.fixed??[])p(b.repository,v);for(let b of r?.support??[])p(b.repository,b.file);let E=ve(e,YE)?.packages??[];for(let b of new Set(E.map(v=>v.repository))){let v=c(b),I=E.filter(C=>C.repository===b).map(C=>C.dir);if(v)for(let{path:C}of tb(v.repo)){let x=u(v.repo,C),w=Dt.join(v.repo,x);WE(x,I)&&!p0(x)&&!h(b,x)&&(!JEe(w)||eg(w))&&v.paths.add(x)}}for(let{record:b,source:v,problems:I}of t){let C=a.get(v.path)?.paths;C?.has(b.file)&&(C.delete(b.file),!I.length&&(b.entry&&C.add(b.entry),C.add(b.sourceAsset)))}return new Map([...a.values()].map(({source:b,paths:v})=>[b,[...v].filter(I=>I&&I!==".."&&!I.startsWith(`..${Dt.sep}`)&&!Qo(I))]))}o(rW,"candidateAllowlist");mu();var uJe=5*6e4,lJe=12*6e4,dJe=2*6e4;var yJe=["class TestbotProjectBrowsers {"," onBegin(config) {",' const projects = config.projects.map((p) => ({ browserName: p.use.browserName ?? p.use.defaultBrowserType ?? "chromium", channel: p.use.channel ?? null }));',' process.stdout.write("TESTBOT_PROJECT_BROWSERS " + JSON.stringify(projects) + "\\n");'," }"," printsToStdio() { return true; }","}","module.exports = TestbotProjectBrowsers;",""].join(`
266
266
  `);var cr=ee(require("fs")),Ts=ee(require("path"));var Oo=ee(require("fs")),yb=ee(require("path"));var ZEe="change-inputs",KEe=o((e,t)=>`${t}-${e.replace(/[^\w.-]+/g,n=>n==="/"?"__":"-")}.md`,"fileName");function XEe(e){return[...(e.pullRequests??[]).map(t=>({label:`${t.repository}#${t.number}`,body:t.body?.trim()??""})),...(e.relatedRepos??[]).map(t=>({label:t.slug,body:t.prDescription?.trim()??""}))].map((t,n)=>({...t,file:KEe(t.label,n)})).filter(t=>t.body.length>wG)}o(XEe,"longDescriptions");function iW(e,t,n){let i=yb.join(t,ZEe);Oo.rmSync(i,{recursive:!0,force:!0}),Oo.mkdirSync(i,{recursive:!0}),Oo.writeFileSync(yb.join(i,Fa),n,{mode:292});for(let r of XEe(e))Oo.writeFileSync(yb.join(i,r.file),`${r.body}
267
267
  `,{mode:292})}o(iW,"writeChangeInputs");var ebe=[/^\.github\//,/^\.gitlab(-ci)?/,/^\.circleci\//,/(^|\/)Jenkinsfile$/,/^docs?\//,/\.(md|mdx|rst)$/i,/(^|\/)LICENSE([._-].*)?$/i,/(^|\/)CODEOWNERS$/,/(^|\/)\.gitignore$/,/(^|\/)\.gitattributes$/,/(^|\/)\.editorconfig$/,/(^|\/)\.prettierrc[^/]*$/,/(^|\/)\.eslintrc[^/]*$/,/(^|\/)eslint\.config\.[^/]+$/,/(^|\/)package-lock\.json$/,/(^|\/)yarn\.lock$/,/(^|\/)pnpm-lock\.yaml$/,/(^|\/)poetry\.lock$/,/(^|\/)Pipfile\.lock$/,/(^|\/)Cargo\.lock$/,/(^|\/)go\.sum$/,/(^|\/)composer\.lock$/,/(^|\/)Gemfile\.lock$/,/\.(png|jpe?g|gif|svg|ico|webp)$/i];function sW(e){return ebe.some(t=>t.test(e))}o(sW,"isNonApplicationFile");function tbe(e){let t=[],n=e.inputs.repositoryPath;return!n||!cr.existsSync(n)?t.push(`repository path does not exist: ${n}`):JT(n)?Jf(n,e.inputs.baseBranch)||t.push(e.inputs.baseBranch?`base branch "${e.inputs.baseBranch}" does not resolve`:"could not auto-detect a base branch (origin/HEAD, main, master)"):t.push(`not a git repository: ${n}`),{ok:t.length===0,reasons:t}}o(tbe,"validatePreflightInput");function nbe(e){return(e.inputs.relatedRepos??[]).map(t=>{let n=cr.existsSync(t.path)?GE(t.path,t.base):void 0;return n?{repository:t.slug,changedFiles:n.changedFiles}:{repository:t.slug,changedFiles:[],note:`could not read the change in ${t.path}`}})}o(nbe,"collectRelatedChanges");function rbe(e){cr.rmSync(Ts.join(e.runDir,cS),{recursive:!0,force:!0});for(let t of e.inputs.relatedRepos??[]){let n=cr.existsSync(t.path)?YT(t.path,t.base):void 0;if(!n)continue;let i=Ts.join(e.runDir,uS(t.slug));cr.mkdirSync(Ts.dirname(i),{recursive:!0}),cr.writeFileSync(i,n.diffContent)}}o(rbe,"writeRelatedDiffs");function ibe(e){let{repositoryPath:t,baseBranch:n}=e.inputs;cr.rmSync(Ts.join(t,S0),{recursive:!0,force:!0});let i=GE(t,n);if(!i)throw new Error(`could not compute git facts for ${t}`);let r=YT(t,n);if(!r)throw new Error(`could not compute the PR diff for ${t}`);let s=nbe(e),a=[i.changedFiles,...s.map(f=>f.changedFiles)].flat(),c=a.map(f=>f.path).filter(sW),u=!Uu(e)&&a.length>0&&c.length===a.length,l={schemaVersion:1,repository:{path:t,currentBranch:i.currentBranch,baseBranch:i.baseBranch},changedFiles:i.changedFiles,...s.length?{relatedChanges:s}:{},newFiles:r.newFiles,deletedFiles:r.deletedFiles,diffStat:r.diffStat,diffBytes:r.diffContent.length,nonApplicationFiles:c,nonApplicationOnly:u,sutRequired:!u};cr.writeFileSync(Ts.join(e.runDir,Fa),r.diffContent),iW(e.inputs,e.runDir,r.diffContent),rbe(e);let p=Ts.join(e.runDir,aS);return cr.mkdirSync(Ts.dirname(p),{recursive:!0}),cr.writeFileSync(p,JSON.stringify(l,null,2)+`
268
- `),e.prepared={preflight:l},{preflight:aS,diff:Fa}}o(ibe,"executePreflight");var QYe={name:"preflight",timeoutMinutes:1,requires:[],validateInput:tbe,execute:ibe};var yg=ee(require("path"));function sbe(e){return jn(N0,e).errors}o(sbe,"validateFinalizeOutput");function obe(e,t=[]){let{value:n,error:i}=Kt(e,t);if(i)return{errors:[i]};let r=sbe(n);return r.length>0?{errors:r}:{finalize:n,errors:[]}}o(obe,"parseFinalizeText");var abe="finalize-scratch";function cbe(e,t){let n=obe(e.stdout,t?.secretValues);if(!n.finalize||!t?.outputsDir)return n;let i=o((r,s)=>r.trim()&&Db(r.trim(),yg.join(t.outputsDir,abe,s),"finalize")||r,"script");return{...n,finalize:{...n.finalize,lint:n.finalize.lint.map((r,s)=>({...r,command:i(r.command??"",`lint-${s+1}.sh`)}))}}}o(cbe,"parseFinalizeFromSession");var ZWe=Xn("finalize-schema",(e,t)=>cbe(t,e));var aW=ee(require("path"));var x4e=new Set(["targeted_unit","existing_evidence_sufficient"]);var gbe="triage.json";var JZe=new Set(["existing_evidence","unaffected","existing_unit","new_unit","runtime"]),YZe={existing_evidence:"existing evidence",unaffected:"showing the change cannot reach it",existing_unit:"running the existing unit tests",new_unit:"a new unit test",runtime:"tests against the running application"};function Abe(e){let{value:t,error:n}=Kt(e);if(n)return{errors:[n]};let{value:i,errors:r}=jn(ng,t);return r.length?{errors:r}:{triage:i,errors:[]}}o(Abe,"parseTriageText");function hbe(e){return Abe(e.stdout)}o(hbe,"parseTriageFromSession");var WZe=Xn("triage-schema",(e,t)=>hbe(t));function mbe(e){let t=e.inputs?.pipeline;return t?e.state.stages[t==="two-step"?"plan":"triage"]:e.state.stages.triage??e.state.stages.plan}o(mbe,"triageDecider");function H0(e){if(mbe(e)?.status==="passed")return Gi(aW.join(e.outputsDir,gbe))}o(H0,"readTriage");function J0(e){if(!SE(e))return XJ(b0(e.inputs,ve(e,`${rg}.json`),H0(e)?.sutRequired))}o(J0,"revisionBlockReason");var ZZe=new Set(["deploy","recommend","generate","generate-ui","adapt","generate-unit","native-run","finalize","deliver"]);function Y0(e){return e.functions?.length?e.functions:[(e.testType==="unit"?e.testId.split("::").slice(1).join("::").replace(/\[.*\]$/,""):"")||e.testId]}o(Y0,"rowFunctions");function Fl(e){return new Set(e.flatMap(t=>Y0(t).map(n=>`${t.repository??""}\0${t.fileName}\0${n}`))).size}o(Fl,"testCount");function ybe(e){return jn(_0,e).errors}o(ybe,"validateAnalysisOutput");function cW(e,t=[]){let{value:n,error:i}=Kt(e,t);if(i)return{errors:[i]};let r=ybe(n);return r.length>0?{errors:r}:{analysis:n,errors:[]}}o(cW,"parseAnalysisText");function Ebe(e,t=[]){return cW(e.stdout,t)}o(Ebe,"parseAnalysisFromSession");var y6e=Xn("analysis-schema",(e,t)=>Ebe(t,e.secretValues));var E9e=zh.rows.notRun(!0);var Eg="kept, not ";var bg="(declined the planned ";function W0(e){if(!e)return[];let t=[],n=0,i=0;for(let r=0;r<e.length;r++){let s=e[r];s==="("?n++:s===")"?n=Math.max(0,n-1):n===0&&s===";"&&e[r+1]===" "&&e[r-1]===")"&&(t.push(e.slice(i,r)),i=r+2)}return t.push(e.slice(i)),t.map(r=>{let s=r.trim();if(!s.endsWith(")"))return{expectation:s};let a=0;for(let c=s.length-1;c>=0;c--)if(s[c]===")")a++;else if(s[c]==="("&&--a===0){let u=s.slice(0,c).trim(),l=s.slice(c+1,-1).trim();return u&&l?{expectation:u,expected:l}:{expectation:s}}return{expectation:s}})}o(W0,"assertionParts");var Z0=new Set(["update","regenerate","delete"]);var b9e={update:"updated",regenerate:"regenerated",delete:"deleted",verify:"verified",none:"touched"};var mn=ee(require("node:fs")),kt=ee(require("node:path")),bb=require("node:crypto");function Ibe(e,t,n=Uo().version){if(!On(e.inputs))return[];let i=An(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),r=hg(e,t,n),s=new Map(r.map(a=>[kt.resolve(a.source.path,a.record.file),a.problems]));return t.tests.flatMap(a=>{let c=i(a.file),u=s.get(kt.resolve(c.root,c.rel));if(u)return u;if(a.change!=="added")return[];if(!Ul(e,a))return[];let p=o(m=>[`${a.file}: shared-environment delivery is blocked: ${m}`],"problem");if(!Zr(c))return p("test file is outside its checkout");let f=Nl(c.root,kt.join(c.root,c.rel));if(typeof f=="string")return p(`${f} (restrictedDeliveryProblems)`);let A=$s(f.toString("utf-8"));if(!A)return p("use the exact supported delivered harness; preserve unsupported assertions in an inactive source asset, never unrestricted executable code");if("restriction"in A){if(!A.sourceAsset.path.endsWith(".source"))return p("restricted source asset must use an inactive .source extension");let m=kt.resolve(kt.dirname(kt.join(c.root,c.rel)),A.sourceAsset.path),E=kt.relative(c.root,m);if(!E||E.startsWith("..")||kt.isAbsolute(E))return p("restricted source asset must remain inside its checkout");try{if(!mn.lstatSync(m).isFile()||mn.realpathSync(m)!==m||(0,bb.createHash)("sha256").update(mn.readFileSync(m)).digest("hex")!==A.sourceAsset.sha256)return p("restricted source asset is missing, changed or a symlink")}catch{return p("restricted source asset is unavailable")}if(!(t.supportFiles??[]).some(b=>{let v=i(b);return kt.join(v.root,v.rel)===m}))return p("restricted source asset must be delivered in supportFiles")}else{let m=e.inputs.sharedEnvironment;if(A.definition.environmentId!==m?.environmentId||A.definition.environmentAddress!==m?.environmentAddress)return p("harness identity/address differs from the selected Test Environment");if((m.offLimits??[]).some(E=>!A.definition.offLimits.includes(E)))return p("harness omits a configured off-limits route")}if(n==="unknown")return e.inputs.deliver?p("guarded CI delivery is unavailable from an unreleased engine build"):[];let h=kt.dirname(kt.join(c.root,c.rel));for(;h.startsWith(c.root);){let m=kt.join(h,"package.json");if(mn.existsSync(m))try{let E=JSON.parse(mn.readFileSync(m,"utf-8"));return(E.devDependencies?.["@skyramp/testbot-core"]??E.dependencies?.["@skyramp/testbot-core"])===n?[]:p("declare the exact released engine version containing this harness; an unavailable or older runtime cannot protect direct invocation")}catch{return p("test package manifest is unreadable")}if(h===c.root)break;h=kt.dirname(h)}return p("the delivered test has no package manifest declaring its guarded runtime")})}o(Ibe,"restrictedDeliveryProblems");function K0(e,t){if(!On(e.inputs))return[];let n=ve(e,"write.json");if(!n)return["shared-environment delivery requires its generated-test record"];let i=An(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),r=t??mg(e,n),{assemblies:s}=r;if(!r.hasSharedTests)return n.tests.flatMap(p=>{if(p.change!=="deleted")return[];let f=i(p.file);return Zr(f)&&mn.existsSync(kt.join(f.root,f.rel))?[`${p.file}: a deleted test must actually be absent`]:[]});let a=fb(e,n,s).filter(p=>{let f=i(p.file);return p.change!=="deleted"&&!Ei(e,f.root,f.rel)}).map(p=>({...p,change:"added"})),c=mb(e,r),u=new Set([...c].flatMap(([p,f])=>f.map(A=>kt.resolve(p.path,A)))),l=gb(e,n,s,u);return[...s.flatMap(p=>p.problems),...Ibe(e,{...n,tests:a}),...l.problems,...Ab(e,c,l.allowed,s).map(({file:p})=>`${p}: shared-environment delivery refuses an unverified executable/support/manifest path`)]}o(K0,"sharedDeliveryAllowlistProblems");function uW(e,t,n=[]){if(!On(e.inputs))return[];let i=[],r=An(e.inputs.repositoryPath,e.inputs.relatedRepos??[]);for(let s of t.tests){if(s.change==="deleted")continue;let a=r(s.file),c=kt.join(a.root,a.rel);if(Ei(e,a.root,a.rel)||!Zr(a)||V0(a.root,c))continue;let u=`reading ${a.rel}`;try{let l=$s(mn.readFileSync(c,"utf-8"));if(!l)continue;if("restriction"in l){let f=kt.resolve(kt.dirname(c),l.sourceAsset.path),A=kt.relative(a.root,f);if(u=`reading ${A}`,!A||A.startsWith("..")||kt.isAbsolute(A)||!mn.lstatSync(f).isFile()||mn.realpathSync(f)!==f){i.push(`${s.file}: restricted source asset is not a regular file in its checkout`);continue}let h=mn.readFileSync(f);if((0,bb.createHash)("sha256").update(h).digest("hex")!==l.sourceAsset.sha256){i.push(`${s.file}: restricted source asset changed before trusted formatting; not refreshing its hash`);continue}let m=uc(h.toString("utf-8"),n).content,E=_l(a.root,A,Buffer.from(m));u=`writing ${A}`,mn.writeFileSync(f,E),l.sourceAsset.sha256=(0,bb.createHash)("sha256").update(E).digest("hex")}let p=uc(cg(l),n).content;u=`writing ${a.rel}`,mn.writeFileSync(c,_l(a.root,a.rel,Buffer.from(p)))}catch(l){i.push(`${s.file}: could not assemble its guarded entry after trusted formatting (prepareSharedDeliveryFiles): ${u} failed: ${Pl(l,a.root)}`)}}return i}o(uW,"prepareSharedDeliveryFiles");var sn=ee(require("fs")),bi=ee(require("path")),VW=ee(require("crypto")),zW=require("child_process");var Cg=require("crypto");var lW=d.string().trim().min(1),X0=d.object({schemaVersion:d.literal(1).optional(),businessCaseAnalysis:lW.describe("1-2 sentences: what this change means for a user, and whether the evidence shows it working; no count of tests, which the report gives"),issuesFound:d.array(d.object({description:lW,severity:d.string().optional().describe("critical | high | medium | low"),category:d.string().optional().describe("bug | lint | type | config"),sourceFile:d.string().optional(),sourceLine:d.number().optional(),findingId:d.string().optional(),requirementIds:d.array(d.string()).optional()})).describe("every real problem this run exposed \u2014 cause, file:line, severity"),nextSteps:d.array(d.string()).describe("concrete follow-ups the author can act on; required non-empty when a disclosure is BLOCKING")});function Cbe(e){return jn(X0,e).errors}o(Cbe,"validateProseOutput");function Sbe(e,t=[]){let{value:n,error:i}=Kt(e.stdout,t);if(i)return{errors:[i]};let r=Cbe(n);return r.length>0?{errors:r}:{prose:n,errors:[]}}o(Sbe,"parseProseFromSession");var Y9e=Xn("report-schema",(e,t)=>Sbe(t,e.secretValues));var eD="<!-- skyramp-testbot -->",tD=Z0,Bbe=new Set(["lint","type","config"]),dW={critical:0,high:1,medium:2,low:3},EW=new Set(["Pass","Fail"]);var nD=o(e=>to(ue().statusLabels,e),"statusLabel"),Ib=o(e=>to(ue().testTypeCellLabels,e),"testTypeLabel");function tt(e){return(e??"").replace(/\|/g,"\\|").replace(/\r?\n/g,"<br>").trim()}o(tt,"escCell");function pW(e){return e.inferred?" (inferred)":""}o(pW,"inferredMark");function fW(e,t){return!e||!EW.has(e)?"\u2014":t?`${nD(e)} (${tt(bW(t))})`:nD(e)}o(fW,"maintStatus");function bW(e){let t=o(i=>{let r=i.indexOf(": ");return r<0?i:to(ue().staged.maintenanceActions,i.slice(0,r))+i.slice(r)},"action");if(e.startsWith(Eg))return ue().staged.keptNot+t(e.slice(Eg.length));let n=e.indexOf(bg);return n<0?e:e.slice(0,n)+ue().staged.declinedPlanned+t(e.slice(n+bg.length))}o(bW,"declineNote");function gW(e){return e.category!==void 0&&Bbe.has(e.category.toLowerCase())}o(gW,"isTooling");function AW(e,t){return(dW[(e.severity??"").toLowerCase()]??4)-(dW[(t.severity??"").toLowerCase()]??4)}o(AW,"bySeverity");var wb=o(e=>e?.length?` (${e.join(", ")})`:"","forPullRequests");function hW(e){return`- ${e.severity?`**[${to(ue().severityLabels,e.severity.toLowerCase()).toUpperCase()}]** `:""}${e.description.trim()}${wb(e.pullRequests)}`}o(hW,"issueLine");function Rbe(e){let t=e.resultId?.split("#").slice(1).join("#");if(e.testType!=="unit"||!t)return;let n=t;try{n=decodeURIComponent(t)}catch{}let i=/^(.*?)(\[.*\])$/.exec(n);return i?{fn:i[1],kase:i[2]}:{fn:n}}o(Rbe,"unitTestOf");var vW=o((e,t)=>e!==void 0&&t!==void 0&&e.replace(/^\.\//,"")===t.replace(/^\.\//,""),"samePath");function IW(e,t){return(e.testVideos??[]).find(n=>n.url&&t(n))?.url}o(IW,"videoLink");function rD(e,t){return IW(e,n=>vW(n.fileName,t.fileName)&&(!n.repository||!t.repository||n.repository.toLowerCase()===t.repository.toLowerCase()))}o(rD,"resultVideoLink");function iD(e,t){return IW(e,n=>vW(n.writtenAs??n.fileName,t))}o(iD,"journeyVideoLink");function xbe(e,t,n){return n?rD(e,{fileName:t,repository:n}):iD(e,t)}o(xbe,"requirementVideoLink");function Qbe(e){let t=[],n=new Map;for(let a of e.newTestsCreated)a.testType==="unit"&&n.set(a.fileName,[...n.get(a.fileName)??[],a.testId.split("::").slice(1).join("::")]);let i=new Map,r=o((a,c)=>(n.get(a??"")??[]).find(u=>u!==c&&jJ(c,u)),"parentOf"),s=new Map;for(let a of e.testResults){let c=Rbe(a),u=c&&!c.kase?r(a.fileName,c.fn):void 0;if(c&&u&&(c={fn:u,kase:`"${c.fn}"`}),c?.kase&&i.set(a,c.kase),!c){t.push({testId:a.testId,testType:a.testType,endpoint:a.endpoint,status:a.status,details:a.details??"",...a.fileName?{fileName:a.fileName}:{},...a.repository?{repository:a.repository}:{}});continue}let l=`${a.fileName??""}#${c.fn}`,p=s.get(l);p||(p={row:{testId:a.testId,testType:a.testType,endpoint:a.endpoint,status:a.status,details:"",test:c.fn,...a.fileName?{fileName:a.fileName}:{},...a.repository?{repository:a.repository}:{}},cases:[]},s.set(l,p),t.push(p.row)),p.cases.push(a)}for(let{row:a,cases:c}of s.values()){let u=c.filter(A=>A.status==="Fail"),l=c.filter(A=>A.status==="Pass").length,p=c.filter(A=>A.status==="Skipped").length;a.cases=c.length,a.status=u.length?"Fail":p?"Skipped":"Pass";let f=u[0];a.details=c.length===1?c[0].details??"":ue().staged.casesPassed(l,c.length,p)+(f?`; ${i.get(f)??""} ${f.details??""}`.replace(/; +/,"; ").trimEnd():"")}return t}o(Qbe,"resultRows");function $be(e){return W0(e).map(t=>t.expected===void 0?t.expectation:`${t.expectation}: ${Nt(t.expected)}`)}o($be,"unitAssertions");function wg(e){return e.newTestsCreated.some(t=>t.testType!=="unit")&&e.testResults.every(t=>t.status==="Skipped")&&e.testResults.some(t=>t.failureCause?.kind==="environment"&&(t.failureCause.family==="app_not_started"||t.failureCause.family==="secret"))}o(wg,"nothingExecuted");function wW(e){let t=e.pullRequests??[];return t.length<2?[]:[ue().staged.validatedTogether(t.map(n=>`${Nt(`${n.repository}#${n.number}`)}${n.title?` ${Xr(n.title,120)}`:""}`).join("; "))]}o(wW,"pullRequestsLine");function CW(e,t=1/0){let n=Array.from(e.name.replace(/\s+/g," ").trim()).slice(0,t).join("").replace(/[<>[\]()*_`\\|#]/g,"\\$&").replace(/@/g,"@\u200D");return e.kind==="person"?ue().staged.requestedByPerson(n):ue().staged.requestedByPolicy(n)}o(CW,"requesterLine");function SW(e,t={}){if(t.audience==="testbot-pr")return Obe(e,t);let{audience:n,collapsed:i=!1,existingEvidence:r=[],requestedBy:s,sourcePullRequest:a}=t,c=n!=="comment",u=(e.requirements??[]).filter(w=>/^file-[a-f0-9]{16}-/i.test(w.id)).sort((w,$)=>$.id.length-w.id.length),l=o(w=>{let $=u.find(B=>w.toLowerCase().startsWith(B.id.toLowerCase()));return $?$.label+w.slice($.id.length):w},"displayId"),p=[eD];a&&p.push(ue().staged.testsSourcePullRequest(Nt(a)),"");for(let w of wW(e))p.push(w,"");s&&p.push(CW(s),""),e.notTranslated&&p.push(to(ue().staged.notTranslated,e.notTranslated),"");let f=o(w=>{i?p.push("<details>",`<summary>${w}</summary>`,""):p.push(`### ${w}`)},"sectionStart"),A=o(()=>{i&&p.push("","</details>"),p.push("")},"sectionEnd");for(let w of e.businessCaseAnalysis.trim().split(/\r?\n/))p.push(`> ${w}`);if(p.push(""),wg(e)&&p.push(ue().staged.noLiveApp(Fl(e.newTestsCreated)),""),c&&e.newTestsCreated.length){let w=new Map;for(let B of e.newTestsCreated){if(B.testType!=="unit")continue;let Z=Y0(B)[0],ie=w.get(B.fileName)??{functions:new Set,endpoints:[],descriptions:new Map};B.endpoint&&!ie.endpoints.includes(B.endpoint)&&ie.endpoints.push(B.endpoint);let H=B.description?.trim()??"",me=ie.descriptions.get(Z)??[];me.includes(H)||me.push(H),ie.functions.add(Z),ie.descriptions.set(Z,me),w.set(B.fileName,ie)}let $=e.newTestsCreated.filter(B=>B.testType!=="unit");f(ue().testRecommendationsImplementedHeader(Fl(e.newTestsCreated),$.length+Fl(e.newTestsCreated.filter(B=>B.testType==="unit"))));for(let[B,{functions:Z,endpoints:ie,descriptions:H}]of w){let me=Z.size;p.push(ue().staged.unitTestsInFile(`\`${B}\``,me,ie.map(Ie=>`\`${Ie}\``).join(", ")),"");let _e=new Map;for(let[Ie,K]of H){let V=K.join("\0"),Me=_e.get(V)??{fns:[],descriptions:K};Me.fns.push(Ie),_e.set(V,Me)}let Ue=0;for(let{fns:Ie,descriptions:K}of _e.values()){p.push(`${++Ue}. ${Ie.map(Me=>`\`${Me}\``).join(", ")}`);let V=[...new Set(K.flatMap(Me=>$be(Me)))];for(let Me of V)p.push(` - ${Me}`)}p.push("")}for(let B of $){let Z=B.testId?Nt(l(B.testId)):Ib(B.testType),ie=B.fileName?` (\`${B.fileName}\`)`:"",H=B.endpoint?`
268
+ `),e.prepared={preflight:l},{preflight:aS,diff:Fa}}o(ibe,"executePreflight");var QYe={name:"preflight",timeoutMinutes:1,requires:[],validateInput:tbe,execute:ibe};var yg=ee(require("path"));function sbe(e){return jn(N0,e).errors}o(sbe,"validateFinalizeOutput");function obe(e,t=[]){let{value:n,error:i}=Kt(e,t);if(i)return{errors:[i]};let r=sbe(n);return r.length>0?{errors:r}:{finalize:n,errors:[]}}o(obe,"parseFinalizeText");var abe="finalize-scratch";function cbe(e,t){let n=obe(e.stdout,t?.secretValues);if(!n.finalize||!t?.outputsDir)return n;let i=o((r,s)=>r.trim()&&Db(r.trim(),yg.join(t.outputsDir,abe,s),"finalize")||r,"script");return{...n,finalize:{...n.finalize,lint:n.finalize.lint.map((r,s)=>({...r,command:i(r.command??"",`lint-${s+1}.sh`)}))}}}o(cbe,"parseFinalizeFromSession");var ZWe=Xn("finalize-schema",(e,t)=>cbe(t,e));var aW=ee(require("path"));var x4e=new Set(["targeted_unit","existing_evidence_sufficient"]);var gbe="triage.json";var YZe=new Set(["existing_evidence","unaffected","existing_unit","new_unit","runtime"]),WZe={existing_evidence:"existing evidence",unaffected:"showing the change cannot reach it",existing_unit:"running the existing unit tests",new_unit:"a new unit test",runtime:"tests against the running application"};function Abe(e){let{value:t,error:n}=Kt(e);if(n)return{errors:[n]};let{value:i,errors:r}=jn(ng,t);return r.length?{errors:r}:{triage:i,errors:[]}}o(Abe,"parseTriageText");function hbe(e){return Abe(e.stdout)}o(hbe,"parseTriageFromSession");var ZZe=Xn("triage-schema",(e,t)=>hbe(t));var KZe={requirements:"this run has no change, so its requirement references set the scope; unchanged code still needs evidence or a gap",instructions:"this run has no change, so its Instructions set the scope; unchanged code still needs evidence or a gap"};function mbe(e){let t=e.inputs?.pipeline;return t?e.state.stages[t==="two-step"?"plan":"triage"]:e.state.stages.triage??e.state.stages.plan}o(mbe,"triageDecider");function H0(e){if(mbe(e)?.status==="passed")return Gi(aW.join(e.outputsDir,gbe))}o(H0,"readTriage");function J0(e){if(!SE(e))return XJ(b0(e.inputs,ve(e,`${rg}.json`),H0(e)?.sutRequired))}o(J0,"revisionBlockReason");var XZe=new Set(["deploy","recommend","generate","generate-ui","adapt","generate-unit","native-run","finalize","deliver"]);function Y0(e){return e.functions?.length?e.functions:[(e.testType==="unit"?e.testId.split("::").slice(1).join("::").replace(/\[.*\]$/,""):"")||e.testId]}o(Y0,"rowFunctions");function Fl(e){return new Set(e.flatMap(t=>Y0(t).map(n=>`${t.repository??""}\0${t.fileName}\0${n}`))).size}o(Fl,"testCount");function ybe(e){return jn(_0,e).errors}o(ybe,"validateAnalysisOutput");function cW(e,t=[]){let{value:n,error:i}=Kt(e,t);if(i)return{errors:[i]};let r=ybe(n);return r.length>0?{errors:r}:{analysis:n,errors:[]}}o(cW,"parseAnalysisText");function Ebe(e,t=[]){return cW(e.stdout,t)}o(Ebe,"parseAnalysisFromSession");var b6e=Xn("analysis-schema",(e,t)=>Ebe(t,e.secretValues));var v9e=zh.rows.notRun(!0);var Eg="kept, not ";var bg="(declined the planned ";function W0(e){if(!e)return[];let t=[],n=0,i=0;for(let r=0;r<e.length;r++){let s=e[r];s==="("?n++:s===")"?n=Math.max(0,n-1):n===0&&s===";"&&e[r+1]===" "&&e[r-1]===")"&&(t.push(e.slice(i,r)),i=r+2)}return t.push(e.slice(i)),t.map(r=>{let s=r.trim();if(!s.endsWith(")"))return{expectation:s};let a=0;for(let c=s.length-1;c>=0;c--)if(s[c]===")")a++;else if(s[c]==="("&&--a===0){let u=s.slice(0,c).trim(),l=s.slice(c+1,-1).trim();return u&&l?{expectation:u,expected:l}:{expectation:s}}return{expectation:s}})}o(W0,"assertionParts");var Z0=new Set(["update","regenerate","delete"]);var I9e={update:"updated",regenerate:"regenerated",delete:"deleted",verify:"verified",none:"touched"};var mn=ee(require("node:fs")),kt=ee(require("node:path")),bb=require("node:crypto");function Ibe(e,t,n=Uo().version){if(!On(e.inputs))return[];let i=An(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),r=hg(e,t,n),s=new Map(r.map(a=>[kt.resolve(a.source.path,a.record.file),a.problems]));return t.tests.flatMap(a=>{let c=i(a.file),u=s.get(kt.resolve(c.root,c.rel));if(u)return u;if(a.change!=="added")return[];if(!Ul(e,a))return[];let p=o(m=>[`${a.file}: shared-environment delivery is blocked: ${m}`],"problem");if(!Zr(c))return p("test file is outside its checkout");let f=Nl(c.root,kt.join(c.root,c.rel));if(typeof f=="string")return p(`${f} (restrictedDeliveryProblems)`);let A=$s(f.toString("utf-8"));if(!A)return p("use the exact supported delivered harness; preserve unsupported assertions in an inactive source asset, never unrestricted executable code");if("restriction"in A){if(!A.sourceAsset.path.endsWith(".source"))return p("restricted source asset must use an inactive .source extension");let m=kt.resolve(kt.dirname(kt.join(c.root,c.rel)),A.sourceAsset.path),E=kt.relative(c.root,m);if(!E||E.startsWith("..")||kt.isAbsolute(E))return p("restricted source asset must remain inside its checkout");try{if(!mn.lstatSync(m).isFile()||mn.realpathSync(m)!==m||(0,bb.createHash)("sha256").update(mn.readFileSync(m)).digest("hex")!==A.sourceAsset.sha256)return p("restricted source asset is missing, changed or a symlink")}catch{return p("restricted source asset is unavailable")}if(!(t.supportFiles??[]).some(b=>{let v=i(b);return kt.join(v.root,v.rel)===m}))return p("restricted source asset must be delivered in supportFiles")}else{let m=e.inputs.sharedEnvironment;if(A.definition.environmentId!==m?.environmentId||A.definition.environmentAddress!==m?.environmentAddress)return p("harness identity/address differs from the selected Test Environment");if((m.offLimits??[]).some(E=>!A.definition.offLimits.includes(E)))return p("harness omits a configured off-limits route")}if(n==="unknown")return e.inputs.deliver?p("guarded CI delivery is unavailable from an unreleased engine build"):[];let h=kt.dirname(kt.join(c.root,c.rel));for(;h.startsWith(c.root);){let m=kt.join(h,"package.json");if(mn.existsSync(m))try{let E=JSON.parse(mn.readFileSync(m,"utf-8"));return(E.devDependencies?.["@skyramp/testbot-core"]??E.dependencies?.["@skyramp/testbot-core"])===n?[]:p("declare the exact released engine version containing this harness; an unavailable or older runtime cannot protect direct invocation")}catch{return p("test package manifest is unreadable")}if(h===c.root)break;h=kt.dirname(h)}return p("the delivered test has no package manifest declaring its guarded runtime")})}o(Ibe,"restrictedDeliveryProblems");function K0(e,t){if(!On(e.inputs))return[];let n=ve(e,"write.json");if(!n)return["shared-environment delivery requires its generated-test record"];let i=An(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),r=t??mg(e,n),{assemblies:s}=r;if(!r.hasSharedTests)return n.tests.flatMap(p=>{if(p.change!=="deleted")return[];let f=i(p.file);return Zr(f)&&mn.existsSync(kt.join(f.root,f.rel))?[`${p.file}: a deleted test must actually be absent`]:[]});let a=fb(e,n,s).filter(p=>{let f=i(p.file);return p.change!=="deleted"&&!Ei(e,f.root,f.rel)}).map(p=>({...p,change:"added"})),c=mb(e,r),u=new Set([...c].flatMap(([p,f])=>f.map(A=>kt.resolve(p.path,A)))),l=gb(e,n,s,u);return[...s.flatMap(p=>p.problems),...Ibe(e,{...n,tests:a}),...l.problems,...Ab(e,c,l.allowed,s).map(({file:p})=>`${p}: shared-environment delivery refuses an unverified executable/support/manifest path`)]}o(K0,"sharedDeliveryAllowlistProblems");function uW(e,t,n=[]){if(!On(e.inputs))return[];let i=[],r=An(e.inputs.repositoryPath,e.inputs.relatedRepos??[]);for(let s of t.tests){if(s.change==="deleted")continue;let a=r(s.file),c=kt.join(a.root,a.rel);if(Ei(e,a.root,a.rel)||!Zr(a)||V0(a.root,c))continue;let u=`reading ${a.rel}`;try{let l=$s(mn.readFileSync(c,"utf-8"));if(!l)continue;if("restriction"in l){let f=kt.resolve(kt.dirname(c),l.sourceAsset.path),A=kt.relative(a.root,f);if(u=`reading ${A}`,!A||A.startsWith("..")||kt.isAbsolute(A)||!mn.lstatSync(f).isFile()||mn.realpathSync(f)!==f){i.push(`${s.file}: restricted source asset is not a regular file in its checkout`);continue}let h=mn.readFileSync(f);if((0,bb.createHash)("sha256").update(h).digest("hex")!==l.sourceAsset.sha256){i.push(`${s.file}: restricted source asset changed before trusted formatting; not refreshing its hash`);continue}let m=uc(h.toString("utf-8"),n).content,E=_l(a.root,A,Buffer.from(m));u=`writing ${A}`,mn.writeFileSync(f,E),l.sourceAsset.sha256=(0,bb.createHash)("sha256").update(E).digest("hex")}let p=uc(cg(l),n).content;u=`writing ${a.rel}`,mn.writeFileSync(c,_l(a.root,a.rel,Buffer.from(p)))}catch(l){i.push(`${s.file}: could not assemble its guarded entry after trusted formatting (prepareSharedDeliveryFiles): ${u} failed: ${Pl(l,a.root)}`)}}return i}o(uW,"prepareSharedDeliveryFiles");var sn=ee(require("fs")),bi=ee(require("path")),VW=ee(require("crypto")),zW=require("child_process");var Cg=require("crypto");var lW=d.string().trim().min(1),X0=d.object({schemaVersion:d.literal(1).optional(),businessCaseAnalysis:lW.describe("1-2 sentences: what this change means for a user, and whether the evidence shows it working; no count of tests, which the report gives"),issuesFound:d.array(d.object({description:lW,severity:d.string().optional().describe("critical | high | medium | low"),category:d.string().optional().describe("bug | lint | type | config"),sourceFile:d.string().optional(),sourceLine:d.number().optional(),findingId:d.string().optional(),requirementIds:d.array(d.string()).optional()})).describe("every real problem this run exposed \u2014 cause, file:line, severity"),nextSteps:d.array(d.string()).describe("concrete follow-ups the author can act on; required non-empty when a disclosure is BLOCKING")});function Cbe(e){return jn(X0,e).errors}o(Cbe,"validateProseOutput");function Sbe(e,t=[]){let{value:n,error:i}=Kt(e.stdout,t);if(i)return{errors:[i]};let r=Cbe(n);return r.length>0?{errors:r}:{prose:n,errors:[]}}o(Sbe,"parseProseFromSession");var Z9e=Xn("report-schema",(e,t)=>Sbe(t,e.secretValues));var eD="<!-- skyramp-testbot -->",tD=Z0,Bbe=new Set(["lint","type","config"]),dW={critical:0,high:1,medium:2,low:3},EW=new Set(["Pass","Fail"]);var nD=o(e=>to(ue().statusLabels,e),"statusLabel"),Ib=o(e=>to(ue().testTypeCellLabels,e),"testTypeLabel");function tt(e){return(e??"").replace(/\|/g,"\\|").replace(/\r?\n/g,"<br>").trim()}o(tt,"escCell");function pW(e){return e.inferred?" (inferred)":""}o(pW,"inferredMark");function fW(e,t){return!e||!EW.has(e)?"\u2014":t?`${nD(e)} (${tt(bW(t))})`:nD(e)}o(fW,"maintStatus");function bW(e){let t=o(i=>{let r=i.indexOf(": ");return r<0?i:to(ue().staged.maintenanceActions,i.slice(0,r))+i.slice(r)},"action");if(e.startsWith(Eg))return ue().staged.keptNot+t(e.slice(Eg.length));let n=e.indexOf(bg);return n<0?e:e.slice(0,n)+ue().staged.declinedPlanned+t(e.slice(n+bg.length))}o(bW,"declineNote");function gW(e){return e.category!==void 0&&Bbe.has(e.category.toLowerCase())}o(gW,"isTooling");function AW(e,t){return(dW[(e.severity??"").toLowerCase()]??4)-(dW[(t.severity??"").toLowerCase()]??4)}o(AW,"bySeverity");var wb=o(e=>e?.length?` (${e.join(", ")})`:"","forPullRequests");function hW(e){return`- ${e.severity?`**[${to(ue().severityLabels,e.severity.toLowerCase()).toUpperCase()}]** `:""}${e.description.trim()}${wb(e.pullRequests)}`}o(hW,"issueLine");function Rbe(e){let t=e.resultId?.split("#").slice(1).join("#");if(e.testType!=="unit"||!t)return;let n=t;try{n=decodeURIComponent(t)}catch{}let i=/^(.*?)(\[.*\])$/.exec(n);return i?{fn:i[1],kase:i[2]}:{fn:n}}o(Rbe,"unitTestOf");var vW=o((e,t)=>e!==void 0&&t!==void 0&&e.replace(/^\.\//,"")===t.replace(/^\.\//,""),"samePath");function IW(e,t){return(e.testVideos??[]).find(n=>n.url&&t(n))?.url}o(IW,"videoLink");function rD(e,t){return IW(e,n=>vW(n.fileName,t.fileName)&&(!n.repository||!t.repository||n.repository.toLowerCase()===t.repository.toLowerCase()))}o(rD,"resultVideoLink");function iD(e,t){return IW(e,n=>vW(n.writtenAs??n.fileName,t))}o(iD,"journeyVideoLink");function xbe(e,t,n){return n?rD(e,{fileName:t,repository:n}):iD(e,t)}o(xbe,"requirementVideoLink");function Qbe(e){let t=[],n=new Map;for(let a of e.newTestsCreated)a.testType==="unit"&&n.set(a.fileName,[...n.get(a.fileName)??[],a.testId.split("::").slice(1).join("::")]);let i=new Map,r=o((a,c)=>(n.get(a??"")??[]).find(u=>u!==c&&jJ(c,u)),"parentOf"),s=new Map;for(let a of e.testResults){let c=Rbe(a),u=c&&!c.kase?r(a.fileName,c.fn):void 0;if(c&&u&&(c={fn:u,kase:`"${c.fn}"`}),c?.kase&&i.set(a,c.kase),!c){t.push({testId:a.testId,testType:a.testType,endpoint:a.endpoint,status:a.status,details:a.details??"",...a.fileName?{fileName:a.fileName}:{},...a.repository?{repository:a.repository}:{}});continue}let l=`${a.fileName??""}#${c.fn}`,p=s.get(l);p||(p={row:{testId:a.testId,testType:a.testType,endpoint:a.endpoint,status:a.status,details:"",test:c.fn,...a.fileName?{fileName:a.fileName}:{},...a.repository?{repository:a.repository}:{}},cases:[]},s.set(l,p),t.push(p.row)),p.cases.push(a)}for(let{row:a,cases:c}of s.values()){let u=c.filter(A=>A.status==="Fail"),l=c.filter(A=>A.status==="Pass").length,p=c.filter(A=>A.status==="Skipped").length;a.cases=c.length,a.status=u.length?"Fail":p?"Skipped":"Pass";let f=u[0];a.details=c.length===1?c[0].details??"":ue().staged.casesPassed(l,c.length,p)+(f?`; ${i.get(f)??""} ${f.details??""}`.replace(/; +/,"; ").trimEnd():"")}return t}o(Qbe,"resultRows");function $be(e){return W0(e).map(t=>t.expected===void 0?t.expectation:`${t.expectation}: ${Nt(t.expected)}`)}o($be,"unitAssertions");function wg(e){return e.newTestsCreated.some(t=>t.testType!=="unit")&&e.testResults.every(t=>t.status==="Skipped")&&e.testResults.some(t=>t.failureCause?.kind==="environment"&&(t.failureCause.family==="app_not_started"||t.failureCause.family==="secret"))}o(wg,"nothingExecuted");function wW(e){let t=e.pullRequests??[];return t.length<2?[]:[ue().staged.validatedTogether(t.map(n=>`${Nt(`${n.repository}#${n.number}`)}${n.title?` ${Xr(n.title,120)}`:""}`).join("; "))]}o(wW,"pullRequestsLine");function CW(e,t=1/0){let n=Array.from(e.name.replace(/\s+/g," ").trim()).slice(0,t).join("").replace(/[<>[\]()*_`\\|#]/g,"\\$&").replace(/@/g,"@\u200D");return e.kind==="person"?ue().staged.requestedByPerson(n):ue().staged.requestedByPolicy(n)}o(CW,"requesterLine");function SW(e,t={}){if(t.audience==="testbot-pr")return Obe(e,t);let{audience:n,collapsed:i=!1,existingEvidence:r=[],requestedBy:s,sourcePullRequest:a}=t,c=n!=="comment",u=(e.requirements??[]).filter(w=>/^file-[a-f0-9]{16}-/i.test(w.id)).sort((w,$)=>$.id.length-w.id.length),l=o(w=>{let $=u.find(B=>w.toLowerCase().startsWith(B.id.toLowerCase()));return $?$.label+w.slice($.id.length):w},"displayId"),p=[eD];a&&p.push(ue().staged.testsSourcePullRequest(Nt(a)),"");for(let w of wW(e))p.push(w,"");s&&p.push(CW(s),""),e.notTranslated&&p.push(to(ue().staged.notTranslated,e.notTranslated),"");let f=o(w=>{i?p.push("<details>",`<summary>${w}</summary>`,""):p.push(`### ${w}`)},"sectionStart"),A=o(()=>{i&&p.push("","</details>"),p.push("")},"sectionEnd");for(let w of e.businessCaseAnalysis.trim().split(/\r?\n/))p.push(`> ${w}`);if(p.push(""),wg(e)&&p.push(ue().staged.noLiveApp(Fl(e.newTestsCreated)),""),c&&e.newTestsCreated.length){let w=new Map;for(let B of e.newTestsCreated){if(B.testType!=="unit")continue;let Z=Y0(B)[0],ie=w.get(B.fileName)??{functions:new Set,endpoints:[],descriptions:new Map};B.endpoint&&!ie.endpoints.includes(B.endpoint)&&ie.endpoints.push(B.endpoint);let H=B.description?.trim()??"",me=ie.descriptions.get(Z)??[];me.includes(H)||me.push(H),ie.functions.add(Z),ie.descriptions.set(Z,me),w.set(B.fileName,ie)}let $=e.newTestsCreated.filter(B=>B.testType!=="unit");f(ue().testRecommendationsImplementedHeader(Fl(e.newTestsCreated),$.length+Fl(e.newTestsCreated.filter(B=>B.testType==="unit"))));for(let[B,{functions:Z,endpoints:ie,descriptions:H}]of w){let me=Z.size;p.push(ue().staged.unitTestsInFile(`\`${B}\``,me,ie.map(Ie=>`\`${Ie}\``).join(", ")),"");let _e=new Map;for(let[Ie,K]of H){let V=K.join("\0"),Me=_e.get(V)??{fns:[],descriptions:K};Me.fns.push(Ie),_e.set(V,Me)}let Ue=0;for(let{fns:Ie,descriptions:K}of _e.values()){p.push(`${++Ue}. ${Ie.map(Me=>`\`${Me}\``).join(", ")}`);let V=[...new Set(K.flatMap(Me=>$be(Me)))];for(let Me of V)p.push(` - ${Me}`)}p.push("")}for(let B of $){let Z=B.testId?Nt(l(B.testId)):Ib(B.testType),ie=B.fileName?` (\`${B.fileName}\`)`:"",H=B.endpoint?`
269
269
  \`${B.endpoint}\``:"",me=B.description?`
270
270
  ${B.description.trim()}`:"";p.push(`- ${Z}${ie}${wb(B.pullRequests)}${H}${me}`)}A()}let h=(e.testMaintenance??[]).filter(w=>tD.has(w.action));if(c&&h.length){f(ue().staged.testMaintenanceHeader),p.push(ue().maintenanceTableHeader),p.push("|-----------|----------|------|--------|--------|-------|");for(let w of h)p.push(`| ${tt(Ib(w.testType))} | ${tt(w.endpoint)} | \`${tt(w.fileName)}\` | ${tt(w.description)} | ${fW(w.beforeStatus,w.beforeDetails)} | ${fW(w.afterStatus,w.afterDetails)} |`);A()}let m=o(w=>w.startsWith(Eg)||w.includes(bg),"hasDeclineNote"),E=(e.testMaintenance??[]).filter(w=>m(w.afterDetails)&&(!tD.has(w.action)||!EW.has(w.afterStatus??"")));if(c&&E.length){f(ue().staged.declinedMaintenanceHeader);for(let w of E)p.push(`- \`${tt(w.fileName)}\`: ${tt(bW(w.afterDetails))}`);A()}if(c&&r.length){f(ue().staged.existingEvidenceHeader);let w=new Map;for(let $ of r){let B=`${$.check}\0${$.url??""}\0${$.revision??""}`;w.set(B,[...w.get(B)??[],$])}for(let[,[$,...B]]of w){let Z=$.url?`[${Nt($.check)}](${$.url})`:Nt($.check);p.push(ue().staged.trustedCheckPassed(Z,$.revision?Nt($.revision.slice(0,7)):""),"");for(let ie of[$,...B])p.push(`- ${Nt(ie.behavior)}`);p.push("")}A()}if(c&&e.testResults.length){f(ue().staged.testResultsHeader);let w=Qbe(e),$=w.some(H=>H.test),B=w.some(H=>rD(e,H)),Z=$?ue().staged.unitResultsTableHeader:ue().staged.resultsTableHeader;p.push(B?`${Z} ${ue().columnVideo} |`:Z),p.push(`${$?"|---------|-----------|----------|------|-------|--------|---------|":"|---------|-----------|----------|--------|---------|"}${B?"-------|":""}`);for(let H of w){let me=H.details.replace(/(\S+\.(?:py|ts|js|spec\.\w+))/gi,"`$1`"),_e=H.testId?Nt(tt(l(H.testId))):"\u2014",Ue=$?` ${H.test?`\`${tt(H.test)}\``:""} | ${H.cases??""} |`:"",Ie=rD(e,H),K=B?` ${Ie?ue().videoDownloadLink(Ie):"\u2014"} |`:"";p.push(`| ${_e} | ${tt(Ib(H.testType))} | ${tt(H.endpoint)} |${Ue} ${tt(nD(H.status))} | ${tt(me)} |${K}`)}let ie=(e.testVideos??[]).find(H=>H.artifactsUrl)?.artifactsUrl;!B&&ie&&p.push("",ue().videosArtifactFallback(ie)),A()}if(e.requirements?.length){let w=e.requirements.flatMap(H=>H.clauses),$=o(H=>H.status==="Pass"||H.status==="Passed, test not kept","passes"),B=w.filter($).length;f(ue().staged.requirementsHeader(B,w.length));let Z=o(H=>to(ue().staged.clauseStatuses,H.status),"status"),ie=o(H=>(H.status==="Not tested"||H.status==="Passed, test not kept")&&H.notTested?`${Z(H)}: ${H.notTested}`:H.findings.length?`${Z(H)} \u2014 ${H.findings.join(", ")}`:Z(H),"result");if(c){p.push(ue().staged.requirementsTableHeader),p.push("|-------------|--------|-------|--------|");for(let H of e.requirements)H.clauses.forEach((me,_e)=>{let Ue=_e===0?`**${tt(H.label)}**${H.statement?` ${tt(H.statement)}`:""}${wb(H.pullRequests)}`:"",Ie=`${Nt(tt(l(me.id)))}${pW(me)}${me.text?` ${tt(me.text)}`:""}`,K=new Map;for(let Ze of me.tests){let jt=Ze.fileName??l(Ze.testId),ct=K.get(jt)??{fns:new Set};for(let on of Ze.functions)ct.fns.add(on);ct.video??=Ze.fileName?xbe(e,Ze.fileName,Ze.repository):void 0,K.set(jt,ct)}let V=K.size?[...K].map(([Ze,{fns:jt,video:ct}])=>`${Nt(tt(Ze))}${jt.size?` \u2014 ${[...jt].map(on=>`\`${tt(on)}\``).join(", ")}`:""}${ct?` ${ue().videoDownloadLink(ct)}`:""}`).join("<br>"):"\u2014",Me=H.source==="could-break"&&me.status==="Pass"?ue().staged.regressionGuard:"";p.push(`| ${Ue} | ${Ie} | ${V} | ${tt(ie(me)+Me)} |`)})}else{p.push(ue().staged.requirementsSummaryTableHeader),p.push("|-------------|-----------------|-------------|");for(let H of e.requirements){let me=H.clauses.filter($).length,_e=H.clauses.filter(Ue=>!$(Ue)).map(Ue=>`${Nt(tt(l(Ue.id)))}${pW(Ue)} ${tt(ie(Ue))}`);p.push(`| **${tt(H.label)}**${H.statement?` ${tt(H.statement)}`:""}${wb(H.pullRequests)} | ${me}/${H.clauses.length} | ${_e.join("<br>")||"\u2014"} |`)}}A()}if(c&&e.changes?.length&&!e.requirements?.length){let w=e.executionCoverage,$=w?ue().staged.coverageCaption(w.generated,w.modified,w.verified,w.executed):"";f(`${ue().staged.behaviourCoverageHeader}${$}`),p.push(ue().staged.coverageTableHeader),p.push("|-----------|--------|-----------|----------------|");for(let B of e.changes){let Z=B.testedBy.length?B.testedBy.map(H=>`\`${tt(H)}\``).join(", "):B.writtenBy.length?ue().staged.writtenNotRun:"\u2014",ie=B.maintainedBy.length?B.maintainedBy.map(H=>`\`${tt(H)}\``).join(", "):"\u2014";p.push(`| ${tt(B.text)} | \`${tt(B.source)}\` | ${Z} | ${ie} |`)}A()}if(e.userJourneys?.length){let w=e.userJourneys.filter(B=>B.status==="Pass"&&!B.problems.length).length;f(`\u{1F9ED} User Journeys Covered (${w}/${e.userJourneys.length} walked end to end)`);let $=e.userJourneys.some(B=>iD(e,B.fileName));p.push(`| Journey | Test | Status | Notes |${$?` ${ue().columnVideo} |`:""}`),p.push(`|---------|------|--------|-------|${$?"-------|":""}`);for(let B of e.userJourneys){let Z=B.fileName?`\`${tt(B.fileName)}\`${B.test?` \u2014 ${tt(B.test)}`:""}`:"\u2014",ie=B.source&&B.source!=="inferred"?`; described in the ${B.source==="spec"?"spec":"PR description"}`:"; inferred from the app",H=(B.uncovered?`not covered: ${B.uncovered}`:B.problems.length?`does not walk it end to end: ${B.problems.join("; ")}`:`from ${B.entry}, ${B.steps} steps`)+ie,me=$?iD(e,B.fileName):void 0;p.push(`| ${tt(B.name)} | ${Z} | ${tt(B.status)} | ${tt(H)} |${$?` ${me?ue().videoDownloadLink(me):"\u2014"} |`:""}`)}A()}let b=e.issuesFound.filter(w=>!gW(w)).sort(AW),v=e.issuesFound.filter(gW).sort(AW);if(b.length){f(ue().staged.issuesFoundHeader);for(let w of b)p.push(hW(w));A()}if(v.length){p.push(`### ${ue().configErrorsHeader}`);for(let w of v)p.push(hW(w));p.push("")}let I=e.testPackages??[],C=e.dependencyChanges??[];if(I.length){p.push(ue().staged.testPackagesHeader,"");for(let w of I)p.push(`- ${ue().staged.testPackageLine(w.directory,w.entrypoint,Object.entries(w.dependencies??{}).map(([$,B])=>w.runner==="pytest"?`${$}==${B}`:`${$}@${B}`).join(", "))}`);C.length||p.push(`- ${ue().staged.appManifestsUntouched}`),p.push("")}if(C.length){p.push(ue().staged.dependencyChangesHeader,"");for(let w of C)p.push(`- ${ue().staged.dependencyChangeLine(w.package,w.repository?`${w.repository}: ${w.manifest}`:w.manifest,(w.reason??"").replace(/\s+/g," ").trim())}`);p.push("")}let x=(e.caveats??[]).filter(w=>w.kind!=="tests-not-executed"||w.subject==="written-cases"||!wg(e));if(x.length){p.push(ue().staged.caveatsHeader,"");for(let w of x)p.push(`- ${w.text}`);p.push("")}if(e.nextSteps.length){p.push(ue().nextStepsHeader,"");for(let w of e.nextSteps)p.push(`- ${w.trim()}`);p.push("")}return p.join(`
271
271
  `).replace(/\n{3,}/g,`
@@ -281,7 +281,7 @@ else require("node:test").test(spec.name, () => { throw new Error("required shar
281
281
  `;return $.length<=i?$:[eD,...l,...c,n.filesChanged].join(`
282
282
 
283
283
  `)+`
284
- `}o(Obe,"renderTestsPrBody");var Mo=ee(require("fs")),sD=ee(require("path"));var Lbe="report.json",jbe="report-display.json",S8e={en:"English",ja:"Japanese"};function kW(e){let t=sD.join(e,jbe);if(Mo.existsSync(t))try{return JSON.parse(Mo.readFileSync(t,"utf-8"))}catch{}let n=sD.join(e,Lbe);return Mo.existsSync(n)?JSON.parse(Mo.readFileSync(n,"utf-8")):void 0}o(kW,"readDisplayReport");function BW(e,t){return t?`<!-- skyramp-testbot-run: ${t} -->
284
+ `}o(Obe,"renderTestsPrBody");var Mo=ee(require("fs")),sD=ee(require("path"));var Lbe="report.json",jbe="report-display.json",B8e={en:"English",ja:"Japanese"};function kW(e){let t=sD.join(e,jbe);if(Mo.existsSync(t))try{return JSON.parse(Mo.readFileSync(t,"utf-8"))}catch{}let n=sD.join(e,Lbe);return Mo.existsSync(n)?JSON.parse(Mo.readFileSync(n,"utf-8")):void 0}o(kW,"readDisplayReport");function BW(e,t){return t?`<!-- skyramp-testbot-run: ${t} -->
285
285
  ${e}`:e}o(BW,"withRunMarker");var gc=ee(require("fs")),fc=ee(require("path"));var Cb=["build","chore","ci","docs","feat","fix","perf","refactor","revert","style","test"],Vbe=["build","ci","docs","feat","fix","perf","refactor","revert","style","test"],zbe="amannn/action-semantic-pull-request",ur=o(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObj");function RW(e){return typeof e!="string"?!1:e.split("@")[0].split("/").some(n=>n.toLowerCase().split(/[-_.]/).includes("dco"))}o(RW,"usesDco");function xW(e){return typeof e=="string"&&(/\bdco-check\b/.test(e)||/signed-off-by/i.test(e))}o(xW,"scriptChecksDco");function qbe(e){if(!ur(e)||!ur(e.jobs))return!1;for(let t of Object.values(e.jobs))if(ur(t)){if(RW(t.uses))return!0;if(Array.isArray(t.steps)){for(let n of t.steps)if(ur(n)&&(RW(n.uses)||xW(n.run)||ur(n.with)&&Object.values(n.with).some(xW)))return!0}}return!1}o(qbe,"workflowChecksDco");function DW(e){let t=fc.join(e,".github","workflows"),n;try{n=gc.readdirSync(t).filter(i=>/\.ya?ml$/i.test(i)).sort()}catch{return[]}return n.flatMap(i=>{try{return[{file:fc.join(".github","workflows",i),doc:Ro(gc.readFileSync(fc.join(t,i),"utf-8"))}]}catch{return[]}})}o(DW,"workflows");function Hbe(e){return!ur(e)||!ur(e.jobs)?[]:Object.values(e.jobs).flatMap(t=>ur(t)&&Array.isArray(t.steps)?t.steps.filter(ur):[])}o(Hbe,"steps");function Jbe(e){let t=fc.join(".github","dco.yml");if(gc.existsSync(fc.join(e,t)))return{file:t};let n=DW(e).find(i=>qbe(i.doc));return n&&{file:n.file}}o(Jbe,"signOffRule");var QW=o(e=>typeof e=="string"?e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean):void 0,"inputList");function Ybe(e){for(let t of DW(e)){let n=Hbe(t.doc).find(s=>typeof s.uses=="string"&&s.uses.split("@")[0].trim().toLowerCase()===zbe);if(!n)continue;let i=ur(n.with)?n.with:{},r=QW(i.scopes);return{file:t.file,types:QW(i.types)??Cb,...r?.length?{scopes:r}:{},scopeRequired:i.requireScope===!0||String(i.requireScope).trim()==="true"}}}o(Ybe,"semanticPrTitleRule");var Wbe=["package.json",".commitlintrc",".commitlintrc.json",".commitlintrc.yaml",".commitlintrc.yml",".commitlintrc.js",".commitlintrc.cjs",".commitlintrc.mjs",".commitlintrc.ts",".commitlintrc.cts","commitlint.config.js","commitlint.config.cjs","commitlint.config.mjs","commitlint.config.ts","commitlint.config.cts","commitlint.config.mts"],Zbe=["type-enum","scope-enum","scope-empty","subject-case","header-max-length","body-max-line-length"];function _W(e){let t=[];for(let n of e)n==="@commitlint/config-conventional"||n==="@commitlint/config-angular"?t.push(n):t.length=0;return t}o(_W,"knownPresets");var Kbe={Disabled:"0",Warning:"1",Error:"2"};function Xbe(e){return e.replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`|\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g,t=>t.startsWith("/")?t.replace(/[^\r\n]/g," "):t)}o(Xbe,"withoutComments");function $W(e,t){let n=new RegExp(`["']?${t}["']?\\s*:\\s*`).exec(e);if(!n)return;let i=n.index+n[0].length;if(e[i]!=="[")return null;let r=0;for(let s=i;s<e.length;s++)if(e[s]==="[")r++;else if(e[s]==="]"&&--r===0){if(!/^\s*(?:as\s+const\s*)?(?:[,}]|$)/.test(e.slice(s+1)))return null;let a=e.slice(i,s+1).replace(/\bRuleConfigSeverity\.(\w+)/g,(u,l)=>Kbe[l]??u).replace(/,(\s*\])/g,"$1"),c=a.replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/g,'""');try{return JSON.parse(c),Ro(a)}catch{return null}}}o($W,"ruleFromSource");var NW=o(e=>Object.fromEntries(Zbe.map(t=>[t,e(t)])),"pickRules");function TW(e,t){if(!ur(t))return;let n=[].concat(t.extends??[]),i=ur(t.rules)?t.rules:{};return{file:e,presets:_W(n),rules:NW(r=>i[r])}}o(TW,"configFromObject");function eve(e){for(let t of Wbe){let n;try{n=gc.readFileSync(fc.join(e,t),"utf-8")}catch{continue}if(/\.[cm]?[jt]s$/.test(t)){let r=Xbe(n),s=/(?:^|[,{])\s*["']?extends["']?\s*:\s*/.exec(r),a=s?$W(r.slice(s.index),"extends"):void 0,c=s?/^(["'])([^"']+)\1\s*(?:[,}]|$)/.exec(r.slice(s.index+s[0].length))?.[2]:void 0,u=Array.isArray(a)?a:c?[c]:[];return{file:t,presets:_W(u),rules:NW(l=>$W(r,l))}}let i;try{i=Ro(n)}catch{return}if(t!=="package.json")return TW(t,i);if(ur(i)&&ur(i.commitlint))return TW(t,i.commitlint)}}o(eve,"commitlintConfig");function Ol(e){if(!Array.isArray(e))return;let t=Number(e[0]);if(t===1||t===2)return[String(e[1]??"always"),e[2]]}o(Ol,"ruleWhenOn");var oD=o(e=>Array.isArray(e)&&e.every(t=>typeof t=="string")?e:void 0,"stringList");function tve(e,t){if(!e)return t?"not-capitalized":void 0;let[n,i]=e,r=typeof i=="string"?[i]:oD(i)??[];if(n==="always"&&r.length===1&&r[0]==="lower-case")return"lower-case";if(n==="always"&&r.length===1&&r[0]==="sentence-case")return"sentence-case";if(n==="never"&&r.some(s=>["sentence-case","start-case","pascal-case","upper-case"].includes(s)))return"not-capitalized"}o(tve,"subjectCaseOf");function nve(e){let t=eve(e);if(!t)return;let{file:n,rules:i}=t,r=t.presets.at(-1)==="@commitlint/config-angular",s=o(b=>t.presets.length>0&&i[b]===void 0,"preset"),a=Ol(i["type-enum"]),c=a?.[0]==="always"?oD(a[1]):s("type-enum")?r?Vbe:Cb:void 0,u=c===void 0,l=c??Cb;u&&console.warn(`[commit-rules] ${n}: allowed commit types could not be read; using a conventional header fallback. Additional preset rules may still reject it.`);let p=Ol(i["scope-enum"]),f=p?.[0]==="always"?oD(p[1]):void 0,A=o((b,v)=>{let I=Ol(i[b]);return I?typeof I[1]=="number"?I[1]:void 0:s(b)?v:void 0},"limit"),h=tve(Ol(i["subject-case"]),s("subject-case")),m=A("header-max-length",r?72:100)??(u&&i["header-max-length"]===void 0?Qs:void 0),E=A("body-max-line-length",t.presets.includes("@commitlint/config-conventional")?100:void 0);return{file:n,types:l,...u?{typesFromFallback:!0}:{},...u&&!h&&i["subject-case"]===void 0?{fallbackSubjectCase:"not-capitalized"}:{},...f?.length?{scopes:f}:{},scopeRequired:Ol(i["scope-empty"])?.[0]==="never",...Ol(i["scope-empty"])?.[0]==="always"?{scopeForbidden:!0}:{},...h?{subjectCase:h}:{},...m?{headerMaxLength:m}:{},...E?{bodyMaxLineLength:E}:{}}}o(nve,"commitlintRule");function PW(e){let t=Jbe(e),n=nve(e),i=Ybe(e);return{...t?{signOff:t}:{},...n?{commitlint:n}:{},...i?{prTitle:i}:{}}}o(PW,"readCommitRules");function rve(e){let t=[e.commitlint,e.prTitle].filter(a=>!!a);if(!t.length)return;let n=t.map(a=>a.types).reduce((a,c)=>a.filter(u=>c.includes(u)));n.length||console.warn(`[commit-rules] ${t.map(a=>a.file).join(", ")}: no common commit type; using ${t[0].types.join(", ")} from ${t[0].file}. This may fail another rule.`);let i=t.map(a=>a.subjectCase),r=i.includes("lower-case")?"lower-case":i.find(a=>a!==void 0)??t.find(a=>a.fallbackSubjectCase)?.fallbackSubjectCase,s=Math.min(...t.map(a=>a.bodyMaxLineLength??1/0));return{rules:t,types:n.length?n:t[0].types,scopeRequired:t.some(a=>a.scopeRequired),...r?{subjectCase:r}:{},headerMaxLength:Math.min(Qs,...t.map(a=>a.headerMaxLength??1/0)),...Number.isFinite(s)?{bodyMaxLineLength:s}:{}}}o(rve,"mergedHeaderRules");function Sb(e,t){return e.scopeForbidden?!1:e.scopes?e.scopes.some(n=>{if(n===t)return!0;try{return new RegExp(`^(?:${n})$`).test(t)}catch{return!1}}):!0}o(Sb,"allowsScope");function ive(e,t){let n=e.find(s=>s.scopes)?.scopes??[],i=n.filter(s=>/^[\w./-]+$/.test(s)&&e.every(a=>Sb(a,s)));if(!i.length)return e.every(s=>Sb(s,"tests"))||console.warn(`[commit-rules] ${e.map(s=>s.file).join(", ")}: no usable required scope; using tests, which may fail the declared scope rules (${n.join(", ")}).`),"tests";let r=o(s=>t.some(a=>a.startsWith(`${s}/`)||a.split("/").slice(0,-1).includes(s)),"under");return[...i].filter(r).sort((s,a)=>a.length-s.length)[0]??i[0]}o(ive,"pickScope");var UW=/^([A-Za-z][\w-]*)(?:\(([^)]*)\))?!?:\s*(.*)$/,sve=o(e=>e.split(/(`.*?`|".*?"|'.*?')/).map((t,n)=>n%2?t:t.toLowerCase()).join(""),"lowerOutsideQuotes");function FW(e,t){return t==="lower-case"?sve(e):t==="sentence-case"?e.charAt(0).toUpperCase()+e.slice(1):t==="not-capitalized"&&/^[A-Z]/.test(e)?e.replace(/^\S+/,n=>n.toLowerCase()):e}o(FW,"withSubjectCase");function ove(e,t){return FW(e.trim().replace(/\.+$/,"").trim()||"add tests",t)}o(ove,"conformSubject");function OW(e,t){let[n,...i]=e.replace(/\s+$/,"").split(`
286
286
  `),r=UW.exec(n);return[t.commitlint,t.prTitle].every(s=>{if(!s)return!0;if(!s.typesFromFallback&&(!r||!s.types.includes(r[1]))||s.headerMaxLength&&n.length>s.headerMaxLength)return!1;let a=s.bodyMaxLineLength;if(a&&i.some(u=>u.length>a&&!/\bhttps?:\/\/\S+/.test(u)))return!1;let c=r?.[2];if(s.scopeRequired&&!c||c&&!Sb(s,c)||r&&!r[3].trim())return!1;if(s.subjectCase){if(!r)return!1;let u=r[3],l=u.replace(/`.*?`|".*?"|'.*?'/g,"").trim();if(/^[\p{Ll}\p{Lu}\p{Lt}]/u.test(u)&&!/^\d/.test(l)&&FW(l,s.subjectCase)!==l)return!1}return!0})}o(OW,"matchesCommitRules");function ave(e,t){if(e.length<=t)return e;let n=e.slice(0,t-1),i=n.lastIndexOf(" ");return`${(i>0?n.slice(0,i):n).replace(/[\s.,;:]+$/,"")}\u2026`}o(ave,"fitSubject");function cve(e,t){if(e.length<=t)return[e];let n=/^\s*/.exec(e)?.[0]??"",i=[],r="";for(let s of e.trim().split(/\s+/))r&&r.length+1+s.length>t?(i.push(r),r=n+s):r?r=`${r} ${s}`:r=n+s;return r&&i.push(r),i}o(cve,"wrap");function MW(e,t,n){let i=rve(t);if(!i)return e;let[r,...s]=e.replace(/\s+$/,"").split(`
287
287
  `),a=UW.exec(r.trim()),c=a&&[...Cb,...i.types].some(I=>I.toLowerCase()===a[1].toLowerCase())?a:null,u=c?.[1].toLowerCase(),l=c?c[3]:r.replace(/^\s*Skyramp Testbot:\s*/i,""),p=c?.[2]?.trim()||void 0;p&&t.commitlint&&!t.commitlint.scopes&&(p=p.toLowerCase());let f=[u,"test","chore"].find(I=>!!I&&i.types.includes(I))??i.types[0],A=p&&i.rules.every(I=>Sb(I,p))?p:void 0;!A&&i.scopeRequired&&(A=ive(i.rules,n));let h=A?`${f}(${A}): `:`${f}: `,m=h+ave(ove(l,i.subjectCase),i.headerMaxLength-h.length),E=s.join(`
@@ -297,7 +297,7 @@ ${n}`}o(kb,"withSignOff");function LW(e){let t=[],n=!1;for(let i of e.split(`
297
297
  `))/^\s*signed-off-by:/i.test(i)?n=!0:n&&i.trim()===""&&t.at(-1)?.trim()===""||(t.push(i),n=!1);return t.join(`
298
298
  `).replace(/\s+$/,"")}o(LW,"withoutSignOff");function aD(e){let t=/\b(claude|anthropic)\b/i;return e.split(`
299
299
  `).filter(i=>{let r=i.trim();return!(/^co-authored-by:/i.test(r)&&t.test(r))&&!(/^[^\w\s]*\s*generated (?:with|by) /i.test(r)&&t.test(r))}).join(`
300
- `).replace(/\s+$/,"")}o(aD,"stripAgentAttribution");var Bb="Skyramp-Pull-Request",Ml="Skyramp-Delivery-Base",cD="Skyramp-Tested-Revision",uD="Skyramp-Delivery-Run";var G8e=["%H","%P","%an","%ae","%ce",`%(trailers:key=${Bb},valueonly,separator=%x2C)`,"%s",`%(trailers:key=${Ml},valueonly,separator=%x2C)`,`%(trailers:key=${cD},valueonly,separator=%x2C)`,`%(trailers:key=${uD},valueonly,separator=%x2C)`];function jW(e,t){let n=e(["log","-1","--format=%B"]);if(!n.includes(`${Bb}:`)&&!n.includes(`${Ml}:`))return;let i=n.split(`
300
+ `).replace(/\s+$/,"")}o(aD,"stripAgentAttribution");var Bb="Skyramp-Pull-Request",Ml="Skyramp-Delivery-Base",cD="Skyramp-Tested-Revision",uD="Skyramp-Delivery-Run";var z8e=["%H","%P","%an","%ae","%ce",`%(trailers:key=${Bb},valueonly,separator=%x2C)`,"%s",`%(trailers:key=${Ml},valueonly,separator=%x2C)`,`%(trailers:key=${cD},valueonly,separator=%x2C)`,`%(trailers:key=${uD},valueonly,separator=%x2C)`];function jW(e,t){let n=e(["log","-1","--format=%B"]);if(!n.includes(`${Bb}:`)&&!n.includes(`${Ml}:`))return;let i=n.split(`
301
301
  `).filter(a=>!a.startsWith(`${Ml}:`)).join(`
302
302
  `).trimEnd(),r=t?`${i}
303
303
  ${Ml}: ${t}`:i;e(["log","-1","--format=%(trailers:key=Signed-off-by,valueonly)"]).split(`
@@ -316,7 +316,7 @@ ${n}`}:{prFailure:"unknown",prDetail:t}}o(kve,"thrownFailure");async function Bv
316
316
  `}catch{return""}}o($ve,"heldBackPatch");var YW=o(e=>e.map(t=>t.dependsOn.length?`${t.file} (needs ${t.dependsOn.join(", ")})`:t.file).join("; "),"heldBackText");async function Tve(e,t,n,i,r,s){let a=A0(i.path,e.runDir),c=process.env.PATH;a.dir&&(process.env.PATH=VJ(a).PATH);try{return await Dve(e,t,n,i,r,s)}finally{a.dir&&(process.env.PATH=c),a.cleanup()}}o(Tve,"deliverOne");async function Dve(e,t,n,i,r,s){let a=i.slug,c,u=!1,l,p=[];try{let f=i.path,A=await Bve(e,t,n,i,r,s),{texts:h,shown:m,title:E,bot:b,remote:v,base:I,owner:C,testsBranch:x,origin:w,mergedBase:$}=A,B=o((ne=[])=>aD(BW(Eve(ne,I)+SW(yve(mve(m,e,i),ne.map(At=>At.file)),{audience:"testbot-pr",runUrl:e.inputs.skyrampRunUrl,requestedBy:e.inputs.requestedBy,sourcePullRequest:w&&`${w.repository.namespace}/${w.repository.name}#${w.number}`}),e.inputs.skyrampRunUrl))+`
317
317
  `,"bodyOf"),Z=s?"pr-body.md":`pr-body-${qW(a)}.md`,ie=bi.join(e.outputsDir,Z);sn.writeFileSync(ie,B());let H=nt(f,["rev-parse","HEAD"]),me=$??H;nt(f,["checkout","-B",x]),c=x,nt(f,["reset"]);let _e=ve(e,"write.json"),Ue=mg(e,_e),Ie=Ue.assemblies.filter(ne=>ne.source.path===i.path&&r.includes(ne.record.sourceAsset)),K=K0(e,Ue);if(K.length)throw new Error(K.join("; "));let V=_e?uW(e,_e,h):[];if(V.length)throw new Error(V.join("; "));let Me=new Set(Ie.flatMap(({record:ne})=>[ne.sourceAsset,...ne.entry?[ne.entry]:[]]));for(let ne of r)Me.has(ne)||hve(bi.join(f,ne),h);let Ze=JY(e,Ie,h,p);if(Ze.length)throw new Error(Ze.join("; "));let jt=new Map([...Me].map(ne=>{let At=sn.readFileSync(bi.join(f,ne)),Le=o(Ac=>nt(f,["hash-object","--no-filters","--stdin"],Ac),"blobHash"),Et=new Set([Le(At)]),Qr=At.toString("latin1");return!At.includes(0)&&Qr.includes(`\r
318
318
  `)&&Et.add(Le(Buffer.from(Qr.replace(/\r\n/g,`
319
- `),"latin1"))),[ne,Et]})),ct=[];for(let ne of r)try{nt(f,["--literal-pathspecs","add","--",ne])}catch{ct.push(ne)}if(ct.some(ne=>Me.has(ne)))throw new Error("could not stage every guarded delivery file");let on=new Map([...jt].map(([ne,At])=>{let Le=nt(f,["--literal-pathspecs","ls-files","--stage","--",ne]),Et=/^100(?:644|755) ([a-f0-9]+) 0\t/.exec(Le)?.[1];if(!Et||!At.has(Et))throw new Error(`the staged guarded file differs from the generated file: ${ne}`);return[ne,Et]}));try{nt(f,["diff","--cached","--quiet"])}catch{try{let ne=Rve(f,A,H,me,e.inputs.skyrampRunUrl);nt(f,["-c",`user.name=${b.name}`,"-c",`user.email=${b.email}`,"commit","-m",ne])}catch(ne){throw new Rb(ne)}u=!0}u&&(p.length=0),l=nt(f,["rev-parse","HEAD"]);let Bt,Xe,yn,gt=$??s?.headSha;if(u&&gt&&gt!==H){let ne=!1,At=l;try{nt(f,["checkout","-q","-B",c,gt]),ne=!0;try{nt(f,["-c",`user.name=${b.name}`,"-c",`user.email=${b.email}`,"cherry-pick","--keep-redundant-commits",l])}catch(Le){let Et=$?Qve(f,b,At):void 0;if(!Et||(Xe=Et.files.map(Qr=>({file:Qr,dependsOn:xve(f,a,$,H,Qr)})),yn={repository:a,base:I,files:Xe,patch:$ve(f,H,At,Et.files)},!Et.delivered))throw Le}ne=!1,jW(Le=>nt(f,Le),gt),l=nt(f,["rev-parse","HEAD"])}catch(Le){try{nt(f,["cherry-pick","--abort"])}catch{}nt(f,["checkout","-q","-B",c,l]);let Et=sp(ha(Le),1/0);if($&&!ne)throw Le;if($)return{thrown:!1,held:yn,record:{schemaVersion:1,repository:a,branch:c,remote:v,base:I,committed:u,commitSha:l,pushed:!1,prAction:"skipped",prTitle:E,unstaged:ct,...Xe?{heldBack:Xe}:{},reason:Xe?`every test change needs a merged revision ${I} does not have yet, so no tests PR was opened: ${YW(Xe)}`:`the tests do not apply to ${I} at ${$.slice(0,12)} without the merged revisions (${Et}), so no tests PR was opened`}};Bt=`tests committed on the checkout's merge commit (re-cut onto ${gt.slice(0,12)} failed: ${Et})`}}Xe&&sn.writeFileSync(ie,B(Xe));for(let[ne,At]of on){if(Xe?.some(Et=>Et.file===ne))continue;let Le=nt(f,["--literal-pathspecs","ls-tree",l,"--",ne]);if(/^100(?:644|755) blob ([a-f0-9]+)\t/.exec(Le)?.[1]!==At)throw new Error(`the committed guarded file differs from the generated file: ${ne}`)}for(let{record:ne}of Ie){if(ne.entry)continue;let At=nt(f,["--literal-pathspecs","ls-tree",l,"--",ne.file]);if(At&&At!==nt(f,["--literal-pathspecs","ls-tree",H,"--",ne.file]))throw new Error(`the delivery included executable source for a held test: ${ne.file}`)}let ut=s?{}:{repositoryPath:f,repoSlug:a,devPr:null};if(!u){let ne=await t.markTestsPrUnchanged({branch:c,...ut});return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:v,base:I,committed:!1,commitSha:l,pushed:!1,prAction:ne.action==="unchanged"?"unchanged":"skipped",prUrl:ne.url,prTitle:E,unstaged:ct,reason:ne.action==="unchanged"?"no test changes to commit \u2014 existing tests PR annotated as unchanged":"no test changes to commit \u2014 nothing pushed, no PR opened"}}}let $e=await t.publishTestsPr({repositoryPath:f,...ut,remote:v,branch:c,base:I,commitSha:l,title:E,bodyFile:ie,mode:e.inputs.deliverMode,deliveryOwner:C,...e.inputs.firstQualification?{firstQualification:!0}:{},runUrl:e.inputs.skyrampRunUrl,signal:e.signal,deadlineMs:e.deadlineMs});return{thrown:!1,held:yn,record:{schemaVersion:1,repository:a,branch:c,remote:v,base:$e.base,requestedBase:I,committed:u,commitSha:l,pushed:$e.pushed,...$e.pushedCommits?{pushedCommits:$e.pushedCommits}:{},...$e.deliveredCommit?{deliveredCommit:$e.deliveredCommit}:{},prAction:$e.action,...$e.retargetedAs?{retargetedAs:$e.retargetedAs}:{},prUrl:$e.url,prTitle:E,...$e.failure?{prFailure:$e.failure,prDetail:$e.detail}:{},...Bt?{cutNote:Bt}:{},...$e.action==="skipped"&&$e.detail?{reason:$e.detail}:{},unstaged:ct,...Xe?{heldBack:Xe}:{}}}}catch(f){return{thrown:!0,record:{schemaVersion:1,repository:a,branch:c,committed:u,commitSha:l,pushed:!1,prAction:"failed",...kve(f),unstaged:[]}}}finally{if(p.length){try{nt(i.path,["reset"])}catch{}for(let f of p.reverse())try{f()}catch{}}}}o(Dve,"deliverRepository");var m3e={name:"deliver",timeoutMinutes:5,execute:Ive,validateInput:o(e=>{let t=J0(e);return t?{ok:!1,reasons:[t]}:dve(e)},"validateInput"),requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var _ve=10*6e4,Nve=4*6e4,Pve=6e4;function Uve(e,t){return e.getTime()-t.getTime()-_ve}o(Uve,"remainingBudgetMs");var WW="This attempt revoked its scoped GitHub credentials; it mints no more.";var Fve=10*6e4;var Ove=o(e=>!!e&&Object.keys(e).length===1&&e.contents==="read","onlyReads"),Mve=3e4,Lve=3,ZW=30,vi=class extends Error{constructor(n,i,r,s){super(n);this.status=i;this.code=r;this.path=s}status;code;path;static{o(this,"AppRefusal")}},Wi=class extends Error{static{o(this,"AppUnreachable")}},Ll=class extends Wi{static{o(this,"AppNotReady")}},pD=class extends Ll{static{o(this,"RunnerProviderNotReady")}};function fD(e){let t;try{t=new URL(e)}catch{throw new Error(`skyrampAppOrigin "${e}" is not a URL`)}if(t.protocol!=="https:"||t.origin!==e.replace(/\/+$/,""))throw new Error(`skyrampAppOrigin must be an https origin, got "${e}"`);return t.origin}o(fD,"appOrigin");function e4(e,t){if(!Du.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}o(e4,"routeId");function t4(e,t,n,i){throw t<500&&t!==429?new vi(e,t,n,i):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new pD(e):t===503&&n==="RUN_NOT_READY"?new Ll(e):new Wi(e)}o(t4,"refusedOrUnreachable");async function n4(e,t,n,i,r,s=1/0){let a=fD(e.origin),c=`The time limit for ${t} ${n} to the Skyramp web app was reached`,u,l=0;for(let p=1;p<=Lve||u instanceof Ll;p+=1){if(u instanceof Ll){if(l===ZW)throw u;l+=1,p-=1,e.log?.(`${u.message}; trying again (${l} of ${ZW}).`),await new Promise(f=>setTimeout(f,Math.max(0,Math.min(e.readyWaitMs??1e4,s-Date.now()))))}else p>1&&await new Promise(f=>setTimeout(f,Math.max(0,Math.min((e.retryDelayMs??2e3)*(p-1),s-Date.now()))));if(Date.now()>=s)throw new Wi(c);try{let f,A=await(Number.isFinite(s)?Promise.race([e.idToken(a),new Promise((m,E)=>{f=setTimeout(()=>E(new Wi(c)),Math.max(1,s-Date.now()))})]).finally(()=>{f&&clearTimeout(f)}):e.idToken(a));if(Date.now()>=s)throw new Wi(c);let h=await(e.fetch??fetch)(new URL(n,a).toString(),{...i(A),redirect:"error",signal:AbortSignal.timeout(Math.max(1,Math.min(Mve,s-Date.now())))}).catch(m=>{let E=m instanceof Error?m.message:String(m);throw new Wi(`The Skyramp web app did not answer ${t} ${n}: ${E}`,{cause:m})});return await r(h)}catch(f){if(f instanceof vi||Date.now()>=s)throw f;u=f}}throw u}o(n4,"callWithRetries");function r4(e,t,n,i,r){let s=i.headers.get("cf-ray");e.log?.(`Testbot V3: the Skyramp web app answered ${t} ${n} with ${i.status}${s?`, cf-ray ${s}`:""}: ${r.replace(/\s+/g," ").slice(0,200)}`)}o(r4,"logRefusal");var Sg=class extends Error{static{o(this,"ReportUploadSizeError")}};function i4(e){let t=Buffer.byteLength(e,"utf8");if(t<=eS)return{body:e};if(t>q1)throw new Sg("The report exceeds the Skyramp web app's 16 MiB expanded report limit");let n=new Uint8Array((0,XW.gzipSync)(e));if(n.length>eS)throw new Sg("The compressed report exceeds the Skyramp web app's 1 MiB report upload limit");return{body:n,gzip:!0}}o(i4,"encodeReportUpload");function gD(e,t,n,i,r){let s=t==="GET"?void 0:JSON.stringify(i),a=t==="PUT"&&/^\/api\/v1\/runner\/attempts\/[^/]+\/report$/.test(n)&&s!==void 0?i4(s):{body:s};return s4(e,t,n,a,r)}o(gD,"callApp");function s4(e,t,n,i,r){return n4(e,t,n,o(a=>({method:t,headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json",Accept:"application/json",...i.gzip?{"Content-Encoding":"gzip"}:{}},body:i.body}),"request"),async a=>{let c=await a.text().catch(()=>""),u={};try{u=JSON.parse(c)}catch{}if(a.ok)return u.data;r4(e,t,n,a,c);let l=u.error?.fields,p=typeof l?.path=="string"&&typeof l.reason=="string"?` at ${l.path}: ${l.reason}`:"",f=`The Skyramp web app refused ${t} ${n}: ${a.status} ${u.error?.code??"no error code"}${p}`;return t4(f,a.status,u.error?.code,typeof l?.path=="string"?l.path:void 0)},r)}o(s4,"callEncodedApp");function jve(e,t,n){return n4(e,"GET",t,o(r=>({method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/octet-stream"}}),"request"),async r=>{if(!r.ok)return r4(e,"GET",t,r,await r.text().catch(()=>"")),t4(`The Skyramp web app refused GET ${t}: ${r.status}`,r.status);let s=Buffer.from(await r.arrayBuffer());if(s.length>n)throw new vi(`The Skyramp web app answered GET ${t} with more than ${n} bytes`,r.status);return s})}o(jve,"callAppBytes");var kg=class{constructor(t,n,i,r,s,a,c,u,l,p=[],f=[],A,h=!1,m=!1){this.attemptId=t;this.attemptNumber=n;this.deadlineAt=i;this.manifest=r;this.deps=s;this.license=a;this.requestedBy=c;this.writeAllowed=u;this.claudeCodeVersion=l;this.deployedPins=p;this.statedPins=f;this.runSettings=A;this.credentialKinds=h;this.credentialBlockers=m}attemptId;attemptNumber;deadlineAt;manifest;deps;license;requestedBy;writeAllowed;claudeCodeVersion;deployedPins;statedPins;runSettings;credentialKinds;credentialBlockers;static{o(this,"V3Attempt")}budgetMs(t,n){let i=n===void 0?void 0:Date.parse(this.manifest.trigger.requestedAt)+n*6e4;if(this.deadlineAt.getTime()!==i)return Uve(this.deadlineAt,t);let r=this.deadlineAt.getTime()-t.getTime(),s=Math.max(Pve,Math.min(Nve,r/2));return r-s}get skyrampRunUrl(){return M1(fD(this.deps.origin),this.manifest.runId)}log(t){this.deps.log?.(t)}send(t,n,i,r){return gD(this.deps,t,n,i,r)}async sendReport(t){await s4(this.deps,"PUT",`/api/v1/runner/attempts/${this.attemptId}/report`,t)}readBytes(t,n){return jve(this.deps,t,n)}issuedTokens=[];closure;modelKey;modelCredentials=[];credentials={};revocation;token(){return this.cachedToken("run")}readOnlyToken(){return this.cachedToken("read")}async cachedToken(t){if(this.revocation)throw new Error(WW);let n=(this.deps.now??(()=>new Date))().getTime(),i=this.credentials[t],r=i&&await i.catch(()=>{});if(this.credentials[t]!==i)return(await this.credentials[t]).token;if(r&&r.expiresAt-n>=Fve)return r.token;if(this.revocation)throw new Error(WW);let s=t==="read",a=s?{schemaVersion:1,access:t}:{schemaVersion:1},c=s?"read-only":"scoped",u=this.send("POST",`/api/v1/runner/attempts/${this.attemptId}/credentials`,a).then(l=>{let p={...l,token:l.token??this.jobToken()};if(this.issuedTokens.push(p.token),this.deps.mask?.(p.token),p.anthropicApiKey&&this.deps.mask?.(p.anthropicApiKey),s&&l.token&&!Ove(p.permissions))throw new Error(`The Skyramp web app was asked for a read-only GitHub token, but its token grants ${JSON.stringify(p.permissions??null)}`);!s&&!r&&p.anthropicApiKey&&(this.modelKey=p.anthropicApiKey),this.deps.onTokenGranted?.(t);let f=r?"Renewed":"Received";return l.token&&this.deps.log?.(`${f} ${c} GitHub credentials; they expire at ${p.expiresAt}.`),{token:p.token,expiresAt:l.token?new Date(p.expiresAt).getTime():Number.POSITIVE_INFINITY}},l=>{if(this.deps.onTokenRefused?.(l,t),!(l instanceof vi)||l.code!=="CREDENTIALS_UNAVAILABLE")throw l;let p=o(h=>[...new Set(h.map(m=>m.namespace))].join(", "),"unique"),f=this.manifest.sources.map(h=>h.repository);if(new Set(f.map(h=>h.providerAccountId)).size>1)throw new vi(`${l.message}. The run's repositories are on more than one GitHub account (${p(f)}), which Skyramp does not support yet.`,l.status,l.code);let A=p([...f,this.manifest.execution.repository]);throw new vi(`${l.message}. Check the Skyramp GitHub App installation on ${A}: it must be installed and not suspended, have access to these repositories, and have accepted the App's current permissions. Each account must also be connected to your Skyramp organization.`,l.status,l.code)});return this.credentials[t]=u,(await u).token}jobToken(){if(this.deps.sourceToken)return this.deps.sourceToken;throw new Error("The Skyramp web app answered the credentials request without a token, and the job gave Testbot none of its own: on Azure Pipelines, set SYSTEM_ACCESSTOKEN to $(System.AccessToken) in the Testbot step's env.")}sourceFetch(t){return t.fetch??this.deps.fetch??fetch}revokeTokens(t={}){let n=t.host??i0();return this.revocation??=n.revokeToken?this.revokeIssued(i=>n.revokeToken(i,this.sourceFetch(t))):Promise.resolve([]),this.revocation}async revokeIssued(t){let n=[...this.issuedTokens],i=Promise.all(n.map(a=>this.revokeOne(a,t)));await Promise.all(Object.values(this.credentials).map(a=>a.catch(()=>{})));let r=this.issuedTokens.filter(a=>!n.includes(a));return[...await i,...await Promise.all(r.map(a=>this.revokeOne(a,t)))].filter(a=>a!==void 0)}async revokeOne(t,n){try{await n(t);return}catch(i){return`token ${this.issuedTokens.indexOf(t)+1} of ${this.issuedTokens.length}: ${i instanceof Error?i.message:String(i)}`}}};async function o4(e,t,n){e4(e,"run id"),fD(n.origin);let i={statedPins:!0,credentialKinds:!0,credentialBlockers:!0},r=sS(e,t,i),s=`/api/v1/runner/runs/${e}/attempts`,a;for(;;)try{a=await gD(n,"POST",s,r);break}catch(p){let f=p instanceof vi&&p.status===400?Gve(p,i):void 0;if(!f)throw p;i[f]=!1,r=sS(e,t,i)}let c=fG(a);if(c.manifest.runId!==e)throw new Error(`The Skyramp web app answered the handshake of run ${e} with the manifest of another run (${c.manifest.runId})`);let u=c.manifest.sources.find(p=>p.repository.provider!==r.execution.provider);if(u)throw new Error(`The manifest of run ${e} names ${u.repository.namespace}/${u.repository.name} on ${u.repository.provider}, but this job runs on ${r.execution.provider}`);Vve(c.manifest,[...c.deployedRevisions??[],...c.statedRevisions??[]]),c.runToken&&n.mask?.(c.runToken);let l=c.runToken?{entitlements:c.entitlements??[],runToken:c.runToken}:void 0;return new kg(c.attempt.id,c.attempt.number,new Date(c.attempt.deadlineAt),c.manifest,n,l,c.requestedBy??void 0,c.writeAllowed,c.claudeCodeVersion??void 0,c.deployedRevisions??[],c.statedRevisions??[],c.runSettings,r.credentialKinds===!0,r.credentialBlockers===!0)}o(o4,"startV3Attempt");function Gve(e,t){let n=["credentialBlockers","credentialKinds","statedPins"];return e.path===void 0?e.code==="INVALID_REQUEST"?n.find(i=>t[i]):void 0:n.find(i=>t[i]&&e.path===`$.${i}`)}o(Gve,"handshakeFieldRefused");function Vve(e,t){if(t.length===0)return;if(!X1(e))throw new Error(`The Skyramp web app pinned an attempt of a ${e.trigger.kind} run; only a scheduled run or unchosen manual run's retry is pinned to an earlier attempt's read`);let n=new Set(e.sources.map(r=>ji(r.repository))),i=new Set;for(let r of t){let s=ji(r.repository);if(!n.has(s))throw new Error(`The Skyramp web app pinned the attempt to repository ${r.repository.providerRepositoryId}, which is not a source of the run`);if(i.has(s))throw new Error(`The Skyramp web app pinned repository ${r.repository.providerRepositoryId} twice`);i.add(s)}}o(Vve,"checkAttemptPins");async function AD(e,t){return uG.parse(await e.send("POST",`/api/v1/runner/attempts/${e.attemptId}/heartbeat`,{schemaVersion:1},t))}o(AD,"heartbeatV3Attempt");async function a4(e,t=()=>new Date,n){if(e.closure)return e.closure;let i=await AD(e,n).then(r=>lG(r,t())).catch(()=>null);return i&&(e.closure=i),i}o(a4,"closedV3Attempt");var AXe=10*6e4;var hXe=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var mXe=d.object({tests:d.object({placements:d.array(d.unknown()).optional()}).passthrough().optional()}).passthrough(),yXe=d.object({repository:KC,testType:d.string(),directory:d.string()}).passthrough();var EXe=d.object({report:d.object({language:d.string()}).passthrough()}).passthrough();var bXe=d.object({environment:d.object({components:d.array(d.unknown()).optional(),dependencies:d.array(d.unknown()).optional()}).passthrough()}).passthrough(),vXe=d.object({environment:d.object({offLimits:d.unknown().optional()}).passthrough()}).passthrough();var IXe=d.object({environment:d.object({allowedEgress:d.unknown().optional()}).passthrough()}).passthrough();var wXe=d.object({name:d.string().min(1),provision:d.literal("existing"),url:d.string().min(1),repository:KC.optional(),revisionUrl:d.string().min(1).optional()}).passthrough(),CXe=d.object({name:d.string().min(1),url:d.string().nullable(),versionUrl:d.string().nullable(),notes:d.string().nullable()}).passthrough();var SXe=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);function c4(e){let t=o(n=>e.testResults.filter(i=>i.status===n).length,"count");return{passed:t("Pass"),failed:t("Fail"),skipped:t("Skipped")}}o(c4,"statusCounts");function zve(e){let{passed:t,failed:n,skipped:i}=c4(e);return t+n===0?{sufficiency:"insufficient",rationale:i>0?`Every test was skipped (${i}), so nothing was validated.`:"No test ran, so nothing was validated.",gaps:["No test ran against the frozen sources."],acceptedEvidence:[],actionRequired:[]}:{sufficiency:"sufficient",rationale:`${t+n} tests ran against the frozen sources: ${t} passed, ${n} failed${i?`, ${i} skipped`:""}.`,gaps:[],acceptedEvidence:[],actionRequired:[]}}o(zve,"executedTestsValidation");function qve(e,t){let n=e.map(c=>({result:c,repository:c.repository??t,path:c.fileName||c.testType})),i=new Map;for(let c of n){let u=`${c.repository}:${c.result.testType}:${c.path}`;i.set(u,(i.get(u)??0)+1)}let r=n.map(({result:c,repository:u,path:l})=>{let p=(i.get(`${u}:${c.testType}:${l}`)??0)>1;return c.resultId??nS(u,c.testType,l,p&&c.endpoint||void 0)}),s=new Map;for(let c of r)s.set(c,(s.get(c)??0)+1);let a=new Set(r.filter(c=>s.get(c)===1));return n.map(({result:c,repository:u},l)=>{let p=r[l],f=p;if(s.get(p)>1&&a.has(p))for(let A=2;a.has(f)||f===p;A+=1)f=p.includes("#")?`${p}.${A}`:`${p}#${A}`;return a.add(f),{...c,repository:u,resultId:f}})}o(qve,"withResultIds");function Hve({notTranslated:e,...t},n){let i=qve(t.testResults,n);return{...t,testResults:i,...Jve(t,i,n),validation:Zve(Kve(t,Yve(t,t.validation??zve(t)))),traceVersion:1}}o(Hve,"v3Report");function Jve(e,t,n){if(!e.testExecutionContexts)return{};let i=new Set,r=o(c=>{let u=c;for(let l=2;i.has(u);l+=1)u=`${c}#${l}`;return i.add(u),u},"unique"),s=[],a=new Map;for(let{repository:c,...u}of e.testExecutionContexts){let l=u.status==="not_run"?[]:t.filter(p=>p.fileName===u.test&&p.repository===(c?.trim()||n));l.length||s.push(u);for(let{resultId:p}of l){let f=a.get(p),A=f!==void 0&&nm(s[f].cleanup.status)>=Math.max(1,nm(u.cleanup.status))?s[f].cleanup:u.cleanup,h={...u,cleanup:A,test:p,resultId:p};f===void 0?a.set(p,s.push(h)-1):s[f]=h}}for(let c of s)c.resultId&&i.add(c.resultId);return{testExecutionContexts:s.map(c=>c.resultId?c:{...c,test:r(c.test.slice(0,512))}).slice(0,5e3)}}o(Jve,"linkedContexts");function Yve(e,t){let{passed:n,failed:i}=c4(e);return t.sufficiency!=="sufficient"||n+i>0||t.acceptedEvidence.length>0?t:{...t,sufficiency:"insufficient",gaps:["No test ran and no existing evidence was accepted, so nothing was validated."]}}o(Yve,"withEvidence");var Wve={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};function Zve(e){return{...e,gaps:Of(e.gaps)}}o(Zve,"boundedGaps");function Kve(e,t){if(t.sufficiency==="sufficient")return t;let n=(e.caveats??[]).map(r=>Wve[r.kind]).filter(r=>r!==void 0),i=[...new Set(n)].filter(r=>!t.actionRequired.includes(r));return i.length?{...t,actionRequired:[...i,...t.actionRequired]}:t}o(Kve,"withModelProviderFailure");function Xve(e,t,n){let{language:i,report:r}=t;if(i==="en")return;let s={language:i,businessCaseAnalysis:r.businessCaseAnalysis},a=o((b,v,I)=>Array.isArray(b)&&Array.isArray(v)&&b.length===v.length?b.map(C=>({[I]:C[I]})):void 0,"rows"),c=e.validation;r.validation&&c&&c.rationale===n.validation.rationale&&JSON.stringify(Of(c.gaps))===JSON.stringify(n.validation.gaps)&&Of(r.validation.gaps).length===n.validation.gaps.length&&(s.validation={rationale:r.validation.rationale,gaps:Of(r.validation.gaps)});let u=new Set((n.changes??[]).map(b=>b.id)),l=(r.changes??[]).filter(b=>u.has(b.id)).map(({id:b,text:v})=>({id:b,text:v}));l.length&&(s.changes=l);let p=new Set((n.requirements??[]).filter(b=>b.statement!==void 0).map(b=>b.id)),f=(r.requirements??[]).flatMap(({id:b,statement:v})=>p.has(b)&&b.length>0&&b.length<=Rp.id&&v?.trim()?[{id:b,statement:v.slice(0,Rp.statement)}]:[]);f.length&&(s.requirements=f.slice(0,Rp.rows));let A=a(r.issuesFound,n.issuesFound,"description");A&&(s.issuesFound=A);let h=a(r.newTestsCreated,n.newTestsCreated,"description");h&&(s.newTestsCreated=h);let m=a(r.testResults,n.testResults,"details");m&&(s.testResults=m);let E=a(r.caveats,n.caveats,"text");return E&&(s.caveats=E),s}o(Xve,"v3Display");async function u4(e,t){let n=Uj([...e.issuedTokens,...t.secrets??[]]),i={...Hve(t.report,t.workingSlug),...t.notTranslated?{notTranslated:t.notTranslated}:{}},r=t.translated&&Xve(t.report,t.translated,i),s=eIe(Aa(t.delivery,n)),a=t.sources.map(({repository:m,revision:E})=>({repository:m,revision:E})),c=Aa(i,n),u=r&&tS.safeParse(Aa(r,n)),l=u?.success?u.data:void 0;if(u&&!u.success){let m=u.error.issues[0]?.path.join(".");e.log(`Testbot V3: omitted the translated display because ${m?`display.${m}`:"it"} did not meet the report field limits.`)}let p=o((m,E)=>gG({manifest:e.manifest,attemptNumber:e.attemptNumber,checkedOut:a,firstQualification:t.firstQualification,generatedTests:m,producer:t.producer,report:E&&l?{...c,display:l}:c,githubWrites:t.githubWrites}),"build"),f=o((m,E)=>i4(JSON.stringify(p(m,E))),"encode"),A=(s.status==="partial"||s.status==="failed")&&s.failures?.some(m=>m.heldBack)?{...s,failures:s.failures.map(({heldBack:m,...E})=>E)}:void 0,h=[{delivery:s,display:!!l}];A&&h.push({delivery:A,display:!!l}),l&&(h.push({delivery:s,display:!1}),A&&h.push({delivery:A,display:!1}));for(let[m,E]of h.entries()){let b;try{b=f(E.delivery,E.display)}catch(v){if(!(v instanceof Sg)||m===h.length-1)throw v;continue}l&&!E.display&&e.log("Testbot V3: omitted the translated display to fit the report upload."),E.delivery===A&&e.log("Testbot V3: omitted structured held-back files to fit the report upload. See held-back.json for the complete list."),await e.sendReport(b);return}}o(u4,"uploadV3Report");async function hD(e,t,n){if(!d.string().uuid().safeParse(t).success)return{refusal:"no_environment"};let i;try{i=cG.parse(await e.send("GET",_1.persistentDataPolicy.replace(":attemptId",e.attemptId),void 0))}catch{return{refusal:"unavailable"}}try{if(!i.environmentAddress||new URL(i.environmentAddress).href!==new URL(n).href)return{refusal:"changed"}}catch{return{refusal:"changed"}}if(i.environmentId!==t)return{refusal:"changed"};let r=i.persistentDataPolicy;return r?r.environmentId===t?{policy:r}:{refusal:"changed"}:{refusal:"denied"}}o(hD,"fetchV3PersistentDataPolicy");async function l4(e,t,n){let{environmentId:i,environmentAddress:r}=t;if(!i||!r)return{allowed:!1,refusal:"no_environment"};let s=t.persistentDataPolicy;if(!s?.allowed||s.environmentId!==i)return{allowed:!1,refusal:"no_recorded_grant"};let a=await hD(e,i,r);return"refusal"in a?{allowed:!1,refusal:a.refusal}:a.policy.allowed?a.policy.revision!==s.revision?{allowed:!1,refusal:"changed"}:sm(t,a.policy,n)?{allowed:!0,policy:a.policy}:{allowed:!1,refusal:"out_of_scope"}:{allowed:!1,refusal:"denied"}}o(l4,"currentV3PersistenceDecision");var KW=o((e,t=hm)=>e.length>t?`${e.slice(0,t-1)}\u2026`:e,"boundDeliveryMessage");function eIe(e){let t=o(n=>n.map(i=>({...i,message:KW(i.message)})),"bound");return e.status==="partial"?{...e,failures:t(e.failures)}:e.status==="failed"?{...e,message:KW(e.message),...e.failures&&{failures:t(e.failures)}}:e}o(eIe,"boundDeliveryMessages");async function d4(e,t){return e4(e.attemptId,"attempt id"),gD(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,AG({reportUploaded:e.reportUploaded,recipeUploaded:e.recipeUploaded,revisionsUploaded:e.revisionsUploaded,cancelled:e.cause==="cancelled",timedOut:e.cause==="timed_out",setupFailed:e.cause==="setup_failed",checkoutFailed:e.cause==="checkout_failed"||e.cause==="merge_conflict"&&!e.conflict,mergeConflict:e.cause==="merge_conflict"?e.conflict:void 0,environmentUnverified:e.cause==="environment_unverified",runnerProviderNotReady:e.cause==="runner_provider_not_ready",credentialMissing:e.cause==="credential_missing",modelProviderDenied:e.cause==="model_provider_denied",modelProviderUnavailable:e.cause==="model_provider_unavailable",githubWrites:e.githubWrites,environmentUnavailable:e.cause==="environment_unavailable",sharedEnvironmentRecords:e.sharedEnvironmentRecords}))}o(d4,"endV3Attempt");0&&(module.exports={AppRefusal,AppUnreachable,AttemptEndReason,DeliveryStatus,GitHubWriteKind,NoReportCause,SourceProvider,TARGET_ENVIRONMENT_KEYS,V3Attempt,ValidationSufficiency,closedV3Attempt,currentV3PersistenceDecision,endV3Attempt,fetchV3PersistentDataPolicy,heartbeatV3Attempt,startV3Attempt,uploadV3Report});
319
+ `),"latin1"))),[ne,Et]})),ct=[];for(let ne of r)try{nt(f,["--literal-pathspecs","add","--",ne])}catch{ct.push(ne)}if(ct.some(ne=>Me.has(ne)))throw new Error("could not stage every guarded delivery file");let on=new Map([...jt].map(([ne,At])=>{let Le=nt(f,["--literal-pathspecs","ls-files","--stage","--",ne]),Et=/^100(?:644|755) ([a-f0-9]+) 0\t/.exec(Le)?.[1];if(!Et||!At.has(Et))throw new Error(`the staged guarded file differs from the generated file: ${ne}`);return[ne,Et]}));try{nt(f,["diff","--cached","--quiet"])}catch{try{let ne=Rve(f,A,H,me,e.inputs.skyrampRunUrl);nt(f,["-c",`user.name=${b.name}`,"-c",`user.email=${b.email}`,"commit","-m",ne])}catch(ne){throw new Rb(ne)}u=!0}u&&(p.length=0),l=nt(f,["rev-parse","HEAD"]);let Bt,Xe,yn,gt=$??s?.headSha;if(u&&gt&&gt!==H){let ne=!1,At=l;try{nt(f,["checkout","-q","-B",c,gt]),ne=!0;try{nt(f,["-c",`user.name=${b.name}`,"-c",`user.email=${b.email}`,"cherry-pick","--keep-redundant-commits",l])}catch(Le){let Et=$?Qve(f,b,At):void 0;if(!Et||(Xe=Et.files.map(Qr=>({file:Qr,dependsOn:xve(f,a,$,H,Qr)})),yn={repository:a,base:I,files:Xe,patch:$ve(f,H,At,Et.files)},!Et.delivered))throw Le}ne=!1,jW(Le=>nt(f,Le),gt),l=nt(f,["rev-parse","HEAD"])}catch(Le){try{nt(f,["cherry-pick","--abort"])}catch{}nt(f,["checkout","-q","-B",c,l]);let Et=sp(ha(Le),1/0);if($&&!ne)throw Le;if($)return{thrown:!1,held:yn,record:{schemaVersion:1,repository:a,branch:c,remote:v,base:I,committed:u,commitSha:l,pushed:!1,prAction:"skipped",prTitle:E,unstaged:ct,...Xe?{heldBack:Xe}:{},reason:Xe?`every test change needs a merged revision ${I} does not have yet, so no tests PR was opened: ${YW(Xe)}`:`the tests do not apply to ${I} at ${$.slice(0,12)} without the merged revisions (${Et}), so no tests PR was opened`}};Bt=`tests committed on the checkout's merge commit (re-cut onto ${gt.slice(0,12)} failed: ${Et})`}}Xe&&sn.writeFileSync(ie,B(Xe));for(let[ne,At]of on){if(Xe?.some(Et=>Et.file===ne))continue;let Le=nt(f,["--literal-pathspecs","ls-tree",l,"--",ne]);if(/^100(?:644|755) blob ([a-f0-9]+)\t/.exec(Le)?.[1]!==At)throw new Error(`the committed guarded file differs from the generated file: ${ne}`)}for(let{record:ne}of Ie){if(ne.entry)continue;let At=nt(f,["--literal-pathspecs","ls-tree",l,"--",ne.file]);if(At&&At!==nt(f,["--literal-pathspecs","ls-tree",H,"--",ne.file]))throw new Error(`the delivery included executable source for a held test: ${ne.file}`)}let ut=s?{}:{repositoryPath:f,repoSlug:a,devPr:null};if(!u){let ne=await t.markTestsPrUnchanged({branch:c,...ut});return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:v,base:I,committed:!1,commitSha:l,pushed:!1,prAction:ne.action==="unchanged"?"unchanged":"skipped",prUrl:ne.url,prTitle:E,unstaged:ct,reason:ne.action==="unchanged"?"no test changes to commit \u2014 existing tests PR annotated as unchanged":"no test changes to commit \u2014 nothing pushed, no PR opened"}}}let $e=await t.publishTestsPr({repositoryPath:f,...ut,remote:v,branch:c,base:I,commitSha:l,title:E,bodyFile:ie,mode:e.inputs.deliverMode,deliveryOwner:C,...e.inputs.firstQualification?{firstQualification:!0}:{},runUrl:e.inputs.skyrampRunUrl,signal:e.signal,deadlineMs:e.deadlineMs});return{thrown:!1,held:yn,record:{schemaVersion:1,repository:a,branch:c,remote:v,base:$e.base,requestedBase:I,committed:u,commitSha:l,pushed:$e.pushed,...$e.pushedCommits?{pushedCommits:$e.pushedCommits}:{},...$e.deliveredCommit?{deliveredCommit:$e.deliveredCommit}:{},prAction:$e.action,...$e.retargetedAs?{retargetedAs:$e.retargetedAs}:{},prUrl:$e.url,prTitle:E,...$e.failure?{prFailure:$e.failure,prDetail:$e.detail}:{},...Bt?{cutNote:Bt}:{},...$e.action==="skipped"&&$e.detail?{reason:$e.detail}:{},unstaged:ct,...Xe?{heldBack:Xe}:{}}}}catch(f){return{thrown:!0,record:{schemaVersion:1,repository:a,branch:c,committed:u,commitSha:l,pushed:!1,prAction:"failed",...kve(f),unstaged:[]}}}finally{if(p.length){try{nt(i.path,["reset"])}catch{}for(let f of p.reverse())try{f()}catch{}}}}o(Dve,"deliverRepository");var E3e={name:"deliver",timeoutMinutes:5,execute:Ive,validateInput:o(e=>{let t=J0(e);return t?{ok:!1,reasons:[t]}:dve(e)},"validateInput"),requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var _ve=10*6e4,Nve=4*6e4,Pve=6e4;function Uve(e,t){return e.getTime()-t.getTime()-_ve}o(Uve,"remainingBudgetMs");var WW="This attempt revoked its scoped GitHub credentials; it mints no more.";var Fve=10*6e4;var Ove=o(e=>!!e&&Object.keys(e).length===1&&e.contents==="read","onlyReads"),Mve=3e4,Lve=3,ZW=30,vi=class extends Error{constructor(n,i,r,s){super(n);this.status=i;this.code=r;this.path=s}status;code;path;static{o(this,"AppRefusal")}},Wi=class extends Error{static{o(this,"AppUnreachable")}},Ll=class extends Wi{static{o(this,"AppNotReady")}},pD=class extends Ll{static{o(this,"RunnerProviderNotReady")}};function fD(e){let t;try{t=new URL(e)}catch{throw new Error(`skyrampAppOrigin "${e}" is not a URL`)}if(t.protocol!=="https:"||t.origin!==e.replace(/\/+$/,""))throw new Error(`skyrampAppOrigin must be an https origin, got "${e}"`);return t.origin}o(fD,"appOrigin");function e4(e,t){if(!Du.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}o(e4,"routeId");function t4(e,t,n,i){throw t<500&&t!==429?new vi(e,t,n,i):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new pD(e):t===503&&n==="RUN_NOT_READY"?new Ll(e):new Wi(e)}o(t4,"refusedOrUnreachable");async function n4(e,t,n,i,r,s=1/0){let a=fD(e.origin),c=`The time limit for ${t} ${n} to the Skyramp web app was reached`,u,l=0;for(let p=1;p<=Lve||u instanceof Ll;p+=1){if(u instanceof Ll){if(l===ZW)throw u;l+=1,p-=1,e.log?.(`${u.message}; trying again (${l} of ${ZW}).`),await new Promise(f=>setTimeout(f,Math.max(0,Math.min(e.readyWaitMs??1e4,s-Date.now()))))}else p>1&&await new Promise(f=>setTimeout(f,Math.max(0,Math.min((e.retryDelayMs??2e3)*(p-1),s-Date.now()))));if(Date.now()>=s)throw new Wi(c);try{let f,A=await(Number.isFinite(s)?Promise.race([e.idToken(a),new Promise((m,E)=>{f=setTimeout(()=>E(new Wi(c)),Math.max(1,s-Date.now()))})]).finally(()=>{f&&clearTimeout(f)}):e.idToken(a));if(Date.now()>=s)throw new Wi(c);let h=await(e.fetch??fetch)(new URL(n,a).toString(),{...i(A),redirect:"error",signal:AbortSignal.timeout(Math.max(1,Math.min(Mve,s-Date.now())))}).catch(m=>{let E=m instanceof Error?m.message:String(m);throw new Wi(`The Skyramp web app did not answer ${t} ${n}: ${E}`,{cause:m})});return await r(h)}catch(f){if(f instanceof vi||Date.now()>=s)throw f;u=f}}throw u}o(n4,"callWithRetries");function r4(e,t,n,i,r){let s=i.headers.get("cf-ray");e.log?.(`Testbot V3: the Skyramp web app answered ${t} ${n} with ${i.status}${s?`, cf-ray ${s}`:""}: ${r.replace(/\s+/g," ").slice(0,200)}`)}o(r4,"logRefusal");var Sg=class extends Error{static{o(this,"ReportUploadSizeError")}};function i4(e){let t=Buffer.byteLength(e,"utf8");if(t<=eS)return{body:e};if(t>q1)throw new Sg("The report exceeds the Skyramp web app's 16 MiB expanded report limit");let n=new Uint8Array((0,XW.gzipSync)(e));if(n.length>eS)throw new Sg("The compressed report exceeds the Skyramp web app's 1 MiB report upload limit");return{body:n,gzip:!0}}o(i4,"encodeReportUpload");function gD(e,t,n,i,r){let s=t==="GET"?void 0:JSON.stringify(i),a=t==="PUT"&&/^\/api\/v1\/runner\/attempts\/[^/]+\/report$/.test(n)&&s!==void 0?i4(s):{body:s};return s4(e,t,n,a,r)}o(gD,"callApp");function s4(e,t,n,i,r){return n4(e,t,n,o(a=>({method:t,headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json",Accept:"application/json",...i.gzip?{"Content-Encoding":"gzip"}:{}},body:i.body}),"request"),async a=>{let c=await a.text().catch(()=>""),u={};try{u=JSON.parse(c)}catch{}if(a.ok)return u.data;r4(e,t,n,a,c);let l=u.error?.fields,p=typeof l?.path=="string"&&typeof l.reason=="string"?` at ${l.path}: ${l.reason}`:"",f=`The Skyramp web app refused ${t} ${n}: ${a.status} ${u.error?.code??"no error code"}${p}`;return t4(f,a.status,u.error?.code,typeof l?.path=="string"?l.path:void 0)},r)}o(s4,"callEncodedApp");function jve(e,t,n){return n4(e,"GET",t,o(r=>({method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/octet-stream"}}),"request"),async r=>{if(!r.ok)return r4(e,"GET",t,r,await r.text().catch(()=>"")),t4(`The Skyramp web app refused GET ${t}: ${r.status}`,r.status);let s=Buffer.from(await r.arrayBuffer());if(s.length>n)throw new vi(`The Skyramp web app answered GET ${t} with more than ${n} bytes`,r.status);return s})}o(jve,"callAppBytes");var kg=class{constructor(t,n,i,r,s,a,c,u,l,p=[],f=[],A,h=!1,m=!1){this.attemptId=t;this.attemptNumber=n;this.deadlineAt=i;this.manifest=r;this.deps=s;this.license=a;this.requestedBy=c;this.writeAllowed=u;this.claudeCodeVersion=l;this.deployedPins=p;this.statedPins=f;this.runSettings=A;this.credentialKinds=h;this.credentialBlockers=m}attemptId;attemptNumber;deadlineAt;manifest;deps;license;requestedBy;writeAllowed;claudeCodeVersion;deployedPins;statedPins;runSettings;credentialKinds;credentialBlockers;static{o(this,"V3Attempt")}budgetMs(t,n){let i=n===void 0?void 0:Date.parse(this.manifest.trigger.requestedAt)+n*6e4;if(this.deadlineAt.getTime()!==i)return Uve(this.deadlineAt,t);let r=this.deadlineAt.getTime()-t.getTime(),s=Math.max(Pve,Math.min(Nve,r/2));return r-s}get skyrampRunUrl(){return M1(fD(this.deps.origin),this.manifest.runId)}log(t){this.deps.log?.(t)}send(t,n,i,r){return gD(this.deps,t,n,i,r)}async sendReport(t){await s4(this.deps,"PUT",`/api/v1/runner/attempts/${this.attemptId}/report`,t)}readBytes(t,n){return jve(this.deps,t,n)}issuedTokens=[];closure;modelKey;modelCredentials=[];credentials={};revocation;token(){return this.cachedToken("run")}readOnlyToken(){return this.cachedToken("read")}async cachedToken(t){if(this.revocation)throw new Error(WW);let n=(this.deps.now??(()=>new Date))().getTime(),i=this.credentials[t],r=i&&await i.catch(()=>{});if(this.credentials[t]!==i)return(await this.credentials[t]).token;if(r&&r.expiresAt-n>=Fve)return r.token;if(this.revocation)throw new Error(WW);let s=t==="read",a=s?{schemaVersion:1,access:t}:{schemaVersion:1},c=s?"read-only":"scoped",u=this.send("POST",`/api/v1/runner/attempts/${this.attemptId}/credentials`,a).then(l=>{let p={...l,token:l.token??this.jobToken()};if(this.issuedTokens.push(p.token),this.deps.mask?.(p.token),p.anthropicApiKey&&this.deps.mask?.(p.anthropicApiKey),s&&l.token&&!Ove(p.permissions))throw new Error(`The Skyramp web app was asked for a read-only GitHub token, but its token grants ${JSON.stringify(p.permissions??null)}`);!s&&!r&&p.anthropicApiKey&&(this.modelKey=p.anthropicApiKey),this.deps.onTokenGranted?.(t);let f=r?"Renewed":"Received";return l.token&&this.deps.log?.(`${f} ${c} GitHub credentials; they expire at ${p.expiresAt}.`),{token:p.token,expiresAt:l.token?new Date(p.expiresAt).getTime():Number.POSITIVE_INFINITY}},l=>{if(this.deps.onTokenRefused?.(l,t),!(l instanceof vi)||l.code!=="CREDENTIALS_UNAVAILABLE")throw l;let p=o(h=>[...new Set(h.map(m=>m.namespace))].join(", "),"unique"),f=this.manifest.sources.map(h=>h.repository);if(new Set(f.map(h=>h.providerAccountId)).size>1)throw new vi(`${l.message}. The run's repositories are on more than one GitHub account (${p(f)}), which Skyramp does not support yet.`,l.status,l.code);let A=p([...f,this.manifest.execution.repository]);throw new vi(`${l.message}. Check the Skyramp GitHub App installation on ${A}: it must be installed and not suspended, have access to these repositories, and have accepted the App's current permissions. Each account must also be connected to your Skyramp organization.`,l.status,l.code)});return this.credentials[t]=u,(await u).token}jobToken(){if(this.deps.sourceToken)return this.deps.sourceToken;throw new Error("The Skyramp web app answered the credentials request without a token, and the job gave Testbot none of its own: on Azure Pipelines, set SYSTEM_ACCESSTOKEN to $(System.AccessToken) in the Testbot step's env.")}sourceFetch(t){return t.fetch??this.deps.fetch??fetch}revokeTokens(t={}){let n=t.host??i0();return this.revocation??=n.revokeToken?this.revokeIssued(i=>n.revokeToken(i,this.sourceFetch(t))):Promise.resolve([]),this.revocation}async revokeIssued(t){let n=[...this.issuedTokens],i=Promise.all(n.map(a=>this.revokeOne(a,t)));await Promise.all(Object.values(this.credentials).map(a=>a.catch(()=>{})));let r=this.issuedTokens.filter(a=>!n.includes(a));return[...await i,...await Promise.all(r.map(a=>this.revokeOne(a,t)))].filter(a=>a!==void 0)}async revokeOne(t,n){try{await n(t);return}catch(i){return`token ${this.issuedTokens.indexOf(t)+1} of ${this.issuedTokens.length}: ${i instanceof Error?i.message:String(i)}`}}};async function o4(e,t,n){e4(e,"run id"),fD(n.origin);let i={statedPins:!0,credentialKinds:!0,credentialBlockers:!0},r=sS(e,t,i),s=`/api/v1/runner/runs/${e}/attempts`,a;for(;;)try{a=await gD(n,"POST",s,r);break}catch(p){let f=p instanceof vi&&p.status===400?Gve(p,i):void 0;if(!f)throw p;i[f]=!1,r=sS(e,t,i)}let c=fG(a);if(c.manifest.runId!==e)throw new Error(`The Skyramp web app answered the handshake of run ${e} with the manifest of another run (${c.manifest.runId})`);let u=c.manifest.sources.find(p=>p.repository.provider!==r.execution.provider);if(u)throw new Error(`The manifest of run ${e} names ${u.repository.namespace}/${u.repository.name} on ${u.repository.provider}, but this job runs on ${r.execution.provider}`);Vve(c.manifest,[...c.deployedRevisions??[],...c.statedRevisions??[]]),c.runToken&&n.mask?.(c.runToken);let l=c.runToken?{entitlements:c.entitlements??[],runToken:c.runToken}:void 0;return new kg(c.attempt.id,c.attempt.number,new Date(c.attempt.deadlineAt),c.manifest,n,l,c.requestedBy??void 0,c.writeAllowed,c.claudeCodeVersion??void 0,c.deployedRevisions??[],c.statedRevisions??[],c.runSettings,r.credentialKinds===!0,r.credentialBlockers===!0)}o(o4,"startV3Attempt");function Gve(e,t){let n=["credentialBlockers","credentialKinds","statedPins"];return e.path===void 0?e.code==="INVALID_REQUEST"?n.find(i=>t[i]):void 0:n.find(i=>t[i]&&e.path===`$.${i}`)}o(Gve,"handshakeFieldRefused");function Vve(e,t){if(t.length===0)return;if(!X1(e))throw new Error(`The Skyramp web app pinned an attempt of a ${e.trigger.kind} run; only a scheduled run or unchosen manual run's retry is pinned to an earlier attempt's read`);let n=new Set(e.sources.map(r=>ji(r.repository))),i=new Set;for(let r of t){let s=ji(r.repository);if(!n.has(s))throw new Error(`The Skyramp web app pinned the attempt to repository ${r.repository.providerRepositoryId}, which is not a source of the run`);if(i.has(s))throw new Error(`The Skyramp web app pinned repository ${r.repository.providerRepositoryId} twice`);i.add(s)}}o(Vve,"checkAttemptPins");async function AD(e,t){return uG.parse(await e.send("POST",`/api/v1/runner/attempts/${e.attemptId}/heartbeat`,{schemaVersion:1},t))}o(AD,"heartbeatV3Attempt");async function a4(e,t=()=>new Date,n){if(e.closure)return e.closure;let i=await AD(e,n).then(r=>lG(r,t())).catch(()=>null);return i&&(e.closure=i),i}o(a4,"closedV3Attempt");var mXe=10*6e4;var yXe=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var EXe=d.object({tests:d.object({placements:d.array(d.unknown()).optional()}).passthrough().optional()}).passthrough(),bXe=d.object({repository:KC,testType:d.string(),directory:d.string()}).passthrough();var vXe=d.object({report:d.object({language:d.string()}).passthrough()}).passthrough();var IXe=d.object({environment:d.object({components:d.array(d.unknown()).optional(),dependencies:d.array(d.unknown()).optional()}).passthrough()}).passthrough(),wXe=d.object({environment:d.object({offLimits:d.unknown().optional()}).passthrough()}).passthrough();var CXe=d.object({environment:d.object({allowedEgress:d.unknown().optional()}).passthrough()}).passthrough();var SXe=d.object({name:d.string().min(1),provision:d.literal("existing"),url:d.string().min(1),repository:KC.optional(),revisionUrl:d.string().min(1).optional()}).passthrough(),kXe=d.object({name:d.string().min(1),url:d.string().nullable(),versionUrl:d.string().nullable(),notes:d.string().nullable()}).passthrough();var BXe=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);function c4(e){let t=o(n=>e.testResults.filter(i=>i.status===n).length,"count");return{passed:t("Pass"),failed:t("Fail"),skipped:t("Skipped")}}o(c4,"statusCounts");function zve(e){let{passed:t,failed:n,skipped:i}=c4(e);return t+n===0?{sufficiency:"insufficient",rationale:i>0?`Every test was skipped (${i}), so nothing was validated.`:"No test ran, so nothing was validated.",gaps:["No test ran against the frozen sources."],acceptedEvidence:[],actionRequired:[]}:{sufficiency:"sufficient",rationale:`${t+n} tests ran against the frozen sources: ${t} passed, ${n} failed${i?`, ${i} skipped`:""}.`,gaps:[],acceptedEvidence:[],actionRequired:[]}}o(zve,"executedTestsValidation");function qve(e,t){let n=e.map(c=>({result:c,repository:c.repository??t,path:c.fileName||c.testType})),i=new Map;for(let c of n){let u=`${c.repository}:${c.result.testType}:${c.path}`;i.set(u,(i.get(u)??0)+1)}let r=n.map(({result:c,repository:u,path:l})=>{let p=(i.get(`${u}:${c.testType}:${l}`)??0)>1;return c.resultId??nS(u,c.testType,l,p&&c.endpoint||void 0)}),s=new Map;for(let c of r)s.set(c,(s.get(c)??0)+1);let a=new Set(r.filter(c=>s.get(c)===1));return n.map(({result:c,repository:u},l)=>{let p=r[l],f=p;if(s.get(p)>1&&a.has(p))for(let A=2;a.has(f)||f===p;A+=1)f=p.includes("#")?`${p}.${A}`:`${p}#${A}`;return a.add(f),{...c,repository:u,resultId:f}})}o(qve,"withResultIds");function Hve({notTranslated:e,...t},n){let i=qve(t.testResults,n);return{...t,testResults:i,...Jve(t,i,n),validation:Zve(Kve(t,Yve(t,t.validation??zve(t)))),traceVersion:1}}o(Hve,"v3Report");function Jve(e,t,n){if(!e.testExecutionContexts)return{};let i=new Set,r=o(c=>{let u=c;for(let l=2;i.has(u);l+=1)u=`${c}#${l}`;return i.add(u),u},"unique"),s=[],a=new Map;for(let{repository:c,...u}of e.testExecutionContexts){let l=u.status==="not_run"?[]:t.filter(p=>p.fileName===u.test&&p.repository===(c?.trim()||n));l.length||s.push(u);for(let{resultId:p}of l){let f=a.get(p),A=f!==void 0&&nm(s[f].cleanup.status)>=Math.max(1,nm(u.cleanup.status))?s[f].cleanup:u.cleanup,h={...u,cleanup:A,test:p,resultId:p};f===void 0?a.set(p,s.push(h)-1):s[f]=h}}for(let c of s)c.resultId&&i.add(c.resultId);return{testExecutionContexts:s.map(c=>c.resultId?c:{...c,test:r(c.test.slice(0,512))}).slice(0,5e3)}}o(Jve,"linkedContexts");function Yve(e,t){let{passed:n,failed:i}=c4(e);return t.sufficiency!=="sufficient"||n+i>0||t.acceptedEvidence.length>0?t:{...t,sufficiency:"insufficient",gaps:["No test ran and no existing evidence was accepted, so nothing was validated."]}}o(Yve,"withEvidence");var Wve={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};function Zve(e){return{...e,gaps:Of(e.gaps)}}o(Zve,"boundedGaps");function Kve(e,t){if(t.sufficiency==="sufficient")return t;let n=(e.caveats??[]).map(r=>Wve[r.kind]).filter(r=>r!==void 0),i=[...new Set(n)].filter(r=>!t.actionRequired.includes(r));return i.length?{...t,actionRequired:[...i,...t.actionRequired]}:t}o(Kve,"withModelProviderFailure");function Xve(e,t,n){let{language:i,report:r}=t;if(i==="en")return;let s={language:i,businessCaseAnalysis:r.businessCaseAnalysis},a=o((b,v,I)=>Array.isArray(b)&&Array.isArray(v)&&b.length===v.length?b.map(C=>({[I]:C[I]})):void 0,"rows"),c=e.validation;r.validation&&c&&c.rationale===n.validation.rationale&&JSON.stringify(Of(c.gaps))===JSON.stringify(n.validation.gaps)&&Of(r.validation.gaps).length===n.validation.gaps.length&&(s.validation={rationale:r.validation.rationale,gaps:Of(r.validation.gaps)});let u=new Set((n.changes??[]).map(b=>b.id)),l=(r.changes??[]).filter(b=>u.has(b.id)).map(({id:b,text:v})=>({id:b,text:v}));l.length&&(s.changes=l);let p=new Set((n.requirements??[]).filter(b=>b.statement!==void 0).map(b=>b.id)),f=(r.requirements??[]).flatMap(({id:b,statement:v})=>p.has(b)&&b.length>0&&b.length<=Rp.id&&v?.trim()?[{id:b,statement:v.slice(0,Rp.statement)}]:[]);f.length&&(s.requirements=f.slice(0,Rp.rows));let A=a(r.issuesFound,n.issuesFound,"description");A&&(s.issuesFound=A);let h=a(r.newTestsCreated,n.newTestsCreated,"description");h&&(s.newTestsCreated=h);let m=a(r.testResults,n.testResults,"details");m&&(s.testResults=m);let E=a(r.caveats,n.caveats,"text");return E&&(s.caveats=E),s}o(Xve,"v3Display");async function u4(e,t){let n=Uj([...e.issuedTokens,...t.secrets??[]]),i={...Hve(t.report,t.workingSlug),...t.notTranslated?{notTranslated:t.notTranslated}:{}},r=t.translated&&Xve(t.report,t.translated,i),s=eIe(Aa(t.delivery,n)),a=t.sources.map(({repository:m,revision:E})=>({repository:m,revision:E})),c=Aa(i,n),u=r&&tS.safeParse(Aa(r,n)),l=u?.success?u.data:void 0;if(u&&!u.success){let m=u.error.issues[0]?.path.join(".");e.log(`Testbot V3: omitted the translated display because ${m?`display.${m}`:"it"} did not meet the report field limits.`)}let p=o((m,E)=>gG({manifest:e.manifest,attemptNumber:e.attemptNumber,checkedOut:a,firstQualification:t.firstQualification,generatedTests:m,producer:t.producer,report:E&&l?{...c,display:l}:c,githubWrites:t.githubWrites}),"build"),f=o((m,E)=>i4(JSON.stringify(p(m,E))),"encode"),A=(s.status==="partial"||s.status==="failed")&&s.failures?.some(m=>m.heldBack)?{...s,failures:s.failures.map(({heldBack:m,...E})=>E)}:void 0,h=[{delivery:s,display:!!l}];A&&h.push({delivery:A,display:!!l}),l&&(h.push({delivery:s,display:!1}),A&&h.push({delivery:A,display:!1}));for(let[m,E]of h.entries()){let b;try{b=f(E.delivery,E.display)}catch(v){if(!(v instanceof Sg)||m===h.length-1)throw v;continue}l&&!E.display&&e.log("Testbot V3: omitted the translated display to fit the report upload."),E.delivery===A&&e.log("Testbot V3: omitted structured held-back files to fit the report upload. See held-back.json for the complete list."),await e.sendReport(b);return}}o(u4,"uploadV3Report");async function hD(e,t,n){if(!d.string().uuid().safeParse(t).success)return{refusal:"no_environment"};let i;try{i=cG.parse(await e.send("GET",_1.persistentDataPolicy.replace(":attemptId",e.attemptId),void 0))}catch{return{refusal:"unavailable"}}try{if(!i.environmentAddress||new URL(i.environmentAddress).href!==new URL(n).href)return{refusal:"changed"}}catch{return{refusal:"changed"}}if(i.environmentId!==t)return{refusal:"changed"};let r=i.persistentDataPolicy;return r?r.environmentId===t?{policy:r}:{refusal:"changed"}:{refusal:"denied"}}o(hD,"fetchV3PersistentDataPolicy");async function l4(e,t,n){let{environmentId:i,environmentAddress:r}=t;if(!i||!r)return{allowed:!1,refusal:"no_environment"};let s=t.persistentDataPolicy;if(!s?.allowed||s.environmentId!==i)return{allowed:!1,refusal:"no_recorded_grant"};let a=await hD(e,i,r);return"refusal"in a?{allowed:!1,refusal:a.refusal}:a.policy.allowed?a.policy.revision!==s.revision?{allowed:!1,refusal:"changed"}:sm(t,a.policy,n)?{allowed:!0,policy:a.policy}:{allowed:!1,refusal:"out_of_scope"}:{allowed:!1,refusal:"denied"}}o(l4,"currentV3PersistenceDecision");var KW=o((e,t=hm)=>e.length>t?`${e.slice(0,t-1)}\u2026`:e,"boundDeliveryMessage");function eIe(e){let t=o(n=>n.map(i=>({...i,message:KW(i.message)})),"bound");return e.status==="partial"?{...e,failures:t(e.failures)}:e.status==="failed"?{...e,message:KW(e.message),...e.failures&&{failures:t(e.failures)}}:e}o(eIe,"boundDeliveryMessages");async function d4(e,t){return e4(e.attemptId,"attempt id"),gD(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,AG({reportUploaded:e.reportUploaded,recipeUploaded:e.recipeUploaded,revisionsUploaded:e.revisionsUploaded,cancelled:e.cause==="cancelled",timedOut:e.cause==="timed_out",setupFailed:e.cause==="setup_failed",checkoutFailed:e.cause==="checkout_failed"||e.cause==="merge_conflict"&&!e.conflict,mergeConflict:e.cause==="merge_conflict"?e.conflict:void 0,environmentUnverified:e.cause==="environment_unverified",runnerProviderNotReady:e.cause==="runner_provider_not_ready",credentialMissing:e.cause==="credential_missing",modelProviderDenied:e.cause==="model_provider_denied",modelProviderUnavailable:e.cause==="model_provider_unavailable",githubWrites:e.githubWrites,environmentUnavailable:e.cause==="environment_unavailable",sharedEnvironmentRecords:e.sharedEnvironmentRecords}))}o(d4,"endV3Attempt");0&&(module.exports={AppRefusal,AppUnreachable,AttemptEndReason,DeliveryStatus,GitHubWriteKind,NoReportCause,SourceProvider,TARGET_ENVIRONMENT_KEYS,V3Attempt,ValidationSufficiency,closedV3Attempt,currentV3PersistenceDecision,endV3Attempt,fetchV3PersistentDataPolicy,heartbeatV3Attempt,startV3Attempt,uploadV3Report});
320
320
  /*! Bundled license information:
321
321
 
322
322
  undici/lib/web/fetch/body.js:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skyramp/testbot-core",
3
- "version": "0.13.3-v3.555",
3
+ "version": "0.13.3-v3.556",
4
4
  "description": "Skyramp Testbot engine: AI-powered deterministic test generation, execution and maintenance",
5
5
  "main": "dist/main.js",
6
6
  "//files": "An explicit allowlist, never a glob. `dist/` is gitignored, so without this key npm's .gitignore fallback would publish a package with no engine in it; with a glob it would publish the sourcemaps, whose sourcesContent embeds every src/*.ts verbatim. dist/VERSION.json exists only in a release-engine.yml build.",