@skyramp/testbot-core 0.13.0-v3.325 → 0.13.0-v3.326
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.
- package/dist/VERSION.json +1 -1
- package/dist/main.js +398 -388
- package/dist/post.js +7 -7
- package/dist/runner-client.cjs +4 -4
- package/package.json +1 -1
package/dist/post.js
CHANGED
|
@@ -224,8 +224,8 @@ ${ld}: ${t}`:i;e(["log","-1","--format=%(trailers:key=Signed-off-by,valueonly)"]
|
|
|
224
224
|
`).replace(/\n{3,}/g,`
|
|
225
225
|
|
|
226
226
|
`).trim()+`
|
|
227
|
-
`}var mv=ce(require("fs")),xr=ce(require("path"));function xhe(e){try{return mv.lstatSync(e),!0}catch{return!1}}function UH(e){let t=rt(e,"adapt.json"),n=rt(e,"finalize.json"),i=rt(e,av),r=new Map,s=d=>{let f=nf(e.inputs,d);if("error"in f)return;let h=r.get(f.source.path)??{source:f.source,paths:new Set};return r.set(f.source.path,h),{repo:h.source.path,paths:h.paths}},o=(d,f)=>xr.relative(d,xr.resolve(d,f.trim())).replace(/\/+$/,""),a=(d,f)=>{let h=f?.trim()&&s(d);if(!h)return;let g=o(h.repo,f);h.paths.add(g);for(let m of["__init__.py","conftest.py"]){let E=xr.join(xr.dirname(g),m);mv.existsSync(xr.join(h.repo,E))&&h.paths.add(E)}},c=(d,f)=>{if(typeof f!="string"||!f.trim())return;let h=s(d);if(!h)return;let g=o(h.repo,f);if($m(xr.join(h.repo,g)))return h.paths.add(g),{...h,rel:g}};for(let d of[...t?.items??[],...i?.tests??[],...i?.maintained??[]])a(d.repository,d.file);for(let d of n?.dependencies?.added??[]){let f=c(d.repository,d.manifest);if(f)for(let h of MV(f.repo,ak(f.repo,f.rel)))f.paths.add(h)}for(let d of n?.lint??[])for(let f of d.fixed??[])c(d.repository,f);for(let d of n?.support??[])c(d.repository,d.file);let u=rt(e,ck)?.packages??[];for(let d of new Set(u.map(f=>f.repository))){let f=s(d),h=u.filter(g=>g.repository===d).map(g=>g.dir);if(f)for(let{path:g}of Dq(f.repo)){let m=o(f.repo,g),E=xr.join(f.repo,m);uk(m,h)&&!VV(m)&&(!xhe(E)||$m(E))&&f.paths.add(m)}}return new Map([...r.values()].map(({source:d,paths:f})=>[d,[...f].filter(h=>h&&h!==".."&&!h.startsWith(`..${xr.sep}`)&&!ek(h))]))}var OH=ce(require("fs"));var MH=2*1024*1024;function The(e){let t=[];for(let n of e??[])if(n.state==="read")try{t.push({item:n,text:OH.readFileSync(zq(n),"utf-8")})}catch{}return t}var EA=6,_he=/[\p{L}\p{N}]+/gu,$he=new RegExp("(?<=\\p{Ll})(?=\\p{Lu})|(?<=\\p{Lu})(?=\\p{Lu}\\p{Ll})","u");function S_(e){let t=[];for(let n of e.matchAll(_he)){let i=n.index;for(let r of n[0].split($he))t.push({word:r.toLowerCase(),start:i,end:i+r.length}),i+=r.length}return t}var LH=(e,t)=>e.slice(t,t+EA).map(n=>n.word).join(" ");function FH(e){let t=S_(e),n=new Set;for(let i=0;i+EA<=t.length;i++)n.add(LH(t,i));return n}function jH(e,t=[]){let n=new Set(t.flatMap(i=>[...FH(i)]));return The(e).map(({item:i,text:r})=>{let s=i.source==="other"?r:r.slice(r.indexOf(`
|
|
228
|
-
`)+1||r.length),o=FH(s);for(let a of n)o.delete(a);return{name:Ej(i.key,u_([i])),key:i.key,runs:o,words:S_(s).map(a=>a.word)}})}var
|
|
227
|
+
`}var mv=ce(require("fs")),xr=ce(require("path"));var hFe=5*1024*1024;function xhe(e){try{return mv.lstatSync(e),!0}catch{return!1}}function UH(e){let t=rt(e,"adapt.json"),n=rt(e,"finalize.json"),i=rt(e,av),r=new Map,s=d=>{let f=nf(e.inputs,d);if("error"in f)return;let h=r.get(f.source.path)??{source:f.source,paths:new Set};return r.set(f.source.path,h),{repo:h.source.path,paths:h.paths}},o=(d,f)=>xr.relative(d,xr.resolve(d,f.trim())).replace(/\/+$/,""),a=(d,f)=>{let h=f?.trim()&&s(d);if(!h)return;let g=o(h.repo,f);h.paths.add(g);for(let m of["__init__.py","conftest.py"]){let E=xr.join(xr.dirname(g),m);mv.existsSync(xr.join(h.repo,E))&&h.paths.add(E)}},c=(d,f)=>{if(typeof f!="string"||!f.trim())return;let h=s(d);if(!h)return;let g=o(h.repo,f);if($m(xr.join(h.repo,g)))return h.paths.add(g),{...h,rel:g}};for(let d of[...t?.items??[],...i?.tests??[],...i?.maintained??[]])a(d.repository,d.file);for(let d of n?.dependencies?.added??[]){let f=c(d.repository,d.manifest);if(f)for(let h of MV(f.repo,ak(f.repo,f.rel)))f.paths.add(h)}for(let d of n?.lint??[])for(let f of d.fixed??[])c(d.repository,f);for(let d of n?.support??[])c(d.repository,d.file);let u=rt(e,ck)?.packages??[];for(let d of new Set(u.map(f=>f.repository))){let f=s(d),h=u.filter(g=>g.repository===d).map(g=>g.dir);if(f)for(let{path:g}of Dq(f.repo)){let m=o(f.repo,g),E=xr.join(f.repo,m);uk(m,h)&&!VV(m)&&(!xhe(E)||$m(E))&&f.paths.add(m)}}return new Map([...r.values()].map(({source:d,paths:f})=>[d,[...f].filter(h=>h&&h!==".."&&!h.startsWith(`..${xr.sep}`)&&!ek(h))]))}var OH=ce(require("fs"));var MH=2*1024*1024;function The(e){let t=[];for(let n of e??[])if(n.state==="read")try{t.push({item:n,text:OH.readFileSync(zq(n),"utf-8")})}catch{}return t}var EA=6,_he=/[\p{L}\p{N}]+/gu,$he=new RegExp("(?<=\\p{Ll})(?=\\p{Lu})|(?<=\\p{Lu})(?=\\p{Lu}\\p{Ll})","u");function S_(e){let t=[];for(let n of e.matchAll(_he)){let i=n.index;for(let r of n[0].split($he))t.push({word:r.toLowerCase(),start:i,end:i+r.length}),i+=r.length}return t}var LH=(e,t)=>e.slice(t,t+EA).map(n=>n.word).join(" ");function FH(e){let t=S_(e),n=new Set;for(let i=0;i+EA<=t.length;i++)n.add(LH(t,i));return n}function jH(e,t=[]){let n=new Set(t.flatMap(i=>[...FH(i)]));return The(e).map(({item:i,text:r})=>{let s=i.source==="other"?r:r.slice(r.indexOf(`
|
|
228
|
+
`)+1||r.length),o=FH(s);for(let a of n)o.delete(a);return{name:Ej(i.key,u_([i])),key:i.key,runs:o,words:S_(s).map(a=>a.word)}})}var QFe=EA/2;var Dhe=e=>e.criteria.size?`${e.text.name} ${[...e.criteria].sort((t,n)=>t-n).map(t=>`AC${t}`).join(", ")}`:e.text.name;function Nhe(e,t){if(t.length===0)return[];let n=S_(e),i=[];for(let r=0;r+EA<=n.length;r++){let s=LH(n,r),o=t.find(f=>f.runs.has(s));if(!o)continue;let a=n[r].start,c=n[r+EA-1].end,u=o.criteria?.get(s)??[],d=i.at(-1);if(d&&a<=d.end){if(d.end=Math.max(d.end,c),d.text===o)for(let f of u)d.criteria.add(f)}else i.push({start:a,end:c,text:o,criteria:new Set(u)})}return i.map(r=>({start:r.start,end:r.end,name:Dhe(r)}))}function yv(e,t){let n=e;for(let i of Nhe(e,t).reverse())n=`${n.slice(0,i.start)}(see ${i.name})${n.slice(i.end)}`;return n}function Phe(e,t,n){for(let i=t+1;i<e.length;i++){let r=e[i];if(r==="\\")i++;else{if(r===n)return i+1;if(r===`
|
|
229
229
|
`&&n!=="`")return i}}return e.length}function Uhe(e,t){let n=e.lastIndexOf(`
|
|
230
230
|
`,t-1)+1;if(e.slice(n,t).trim()!=="")return!1;let i=e.slice(0,n).trimEnd();return i===""||i.endsWith(":")}function Fhe(e){let t=[],n=r=>(e.indexOf(`
|
|
231
231
|
`,r)+1||e.length+1)-1,i=0;for(;i<e.length;){let r=e[i],s=e[i+1],o=i+1;if(r==="/"&&s==="*")o=e.indexOf("*/",i+2)<0?e.length:e.indexOf("*/",i+2)+2,t.push({start:i,end:o});else if(r==="/"&&s==="/"&&!/[:\w]/.test(e[i-1]??"")||r==="#"&&/^\s?$/.test(e[i-1]??"")&&!/[!{[]/.test(s??""))o=n(i),t.push({start:i,end:o});else if((r==='"'||r==="'")&&e.startsWith(r.repeat(3),i)){let a=e.indexOf(r.repeat(3),i+3);o=a<0?e.length:a+3,Uhe(e,i)&&t.push({start:i,end:o})}else(r==='"'||r==="'"||r==="`")&&(o=Phe(e,i,r));i=o}return t}var Ohe=/\b(?:test|it|describe|context|suite|scenario|specify|Run|DisplayName)(?:\.\w+)*(?:\.each\s*(?:\((?:[^()]|\([^()]*\))*\)|`[^`]*`))?\s*\(\s*("(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`)/g;function Mhe(e,t){return[...e.matchAll(Ohe)].flatMap(n=>{if(t.some(r=>n.index>=r.start&&n.index<r.end))return[];let i=n.index+n[0].length;return[{start:i-n[1].length,end:i}]})}function VH(e,t){if(t.length===0)return{content:e,cleaned:!1};let n=Fhe(e),i=[];for(let a of n){let c=e.slice(a.start,a.end),u=yv(c,t);u!==c&&i.push({...a,text:u})}let r=Mhe(e,n),s=new Set(r.map(a=>e.slice(a.start+1,a.end-1)));for(let a of r){let c=e[a.start],u=e.slice(a.start+1,a.end-1),d=yv(u,t);if(d===u)continue;let f=d;for(let h=2;s.has(f);h++)f=`${d} (${h})`;s.add(f),i.push({...a,text:`${c}${f}${c}`})}let o=e;for(let a of i.sort((c,u)=>u.start-c.start))o=`${o.slice(0,a.start)}${a.text}${o.slice(a.end)}`;return{content:o,cleaned:o!==e}}function Lhe(e){if(!e.inputs.deliver)return{ok:!1,reasons:["deliver not requested (pass --deliver to push)"]};if(!e.platform?.supportsRemote)return{ok:!1,reasons:["deliver needs a remote platform driver (pass --runner-platform github)"]};let t=rt(e,"finalize.json");return t?t.ready!==!0?{ok:!1,reasons:[`finalize reported ready:false \u2014 not pushing (blockers: ${(t.blockers??[]).slice(0,3).join("; ")||"unspecified"})`]}:{ok:!0,reasons:[]}:{ok:!1,reasons:["finalize.json not found \u2014 refusing to push unverified tests"]}}function qH(e){return e.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"tests"}var jhe="skyramp-testbot/";function Vhe(e,t){return t||`${jhe}${qH(e)}-tests`}function Ghe(e,t,n,i){let r=(e??[]).filter(o=>o.repository.toLowerCase()===t.toLowerCase());if(!r.length&&i){let o=i.repository,a=[i.targetId,o.provider,o.providerAccountId,o.providerRepositoryId,i.number,t.toLowerCase(),n];return(0,vA.createHash)("sha256").update(JSON.stringify(a)).digest("hex").slice(0,32)}let s=r.length?[...new Set(r.map(o=>`${o.repository.toLowerCase()}#${o.number}`))].sort():[`branch ${n}`];return(0,vA.createHash)("sha256").update(s.join(`
|
|
@@ -237,18 +237,18 @@ ${ld}: ${t}`:i;e(["log","-1","--format=%(trailers:key=Signed-off-by,valueonly)"]
|
|
|
237
237
|
${n}`}:{prFailure:"unknown",prDetail:t}}async function ege(e,t,n,i,r,s){let o=bH(i.path,e.runDir),a=process.env.PATH;o.dir&&(process.env.PATH=CH(o).PATH);try{return await tge(e,t,n,i,r,s)}finally{o.dir&&(process.env.PATH=a),o.cleanup()}}async function tge(e,t,n,i,r,s){let o=i.slug,a,c=!1,u;try{let d=i.path,f=rt(e,"finalize.json"),h=jH(e.inputs.requirementItems),g=cH(d),m=rt(e,"write.json"),E=m?.commit?.message||rt(e,"generate-unit.json")?.commitMessage,R=i.working,w=_e=>_e.split(`
|
|
238
238
|
`)[0],k=_e=>yv(f_(_e),h),S=(_e,xt)=>R&&!!xt&&k(_e).trim()===k(xt).trim(),D=(_e,xt,Zt)=>{let fr=k(_e);return Zt&&dH(fr,xt)?fr:pH(fr,xt,r)},F=f?.commit?.message||n.commitMessage||"Skyramp Testbot: add tests",V=D(F,{commitlint:g.commitlint},S(F,E)),te=vH(e.outputsDir)??n,J=R?f?.pr?.title||n.prTitle||m?.commit?.prTitle:void 0,be=J||F,We=R?te.prTitle:void 0,Fe=w(k(be))===w(k(F)),He=(!R||!n.prTitle)&&Fe?te.commitMessage:void 0,Ye=We||He||be,Ee=m?.commit?.prTitle||(E?w(E):void 0),At=S(be,Ee),U=g.prTitle?{prTitle:g.prTitle}:At&&J&&!Fe?{}:{commitlint:g.commitlint},It=w(D(Ye,U,At)),et={name:ks,email:Io},bn=!!g.signOff;if(!bn&&t.listCommitChecks){let _e=s?.headSha??ln(d,["rev-parse","HEAD"]);try{bn=(await t.listCommitChecks({repository:o,revision:_e}))?.records.some(Zt=>Zt.name.trim().toLowerCase()==="dco"&&Zt.headSha===_e&&(!Zt.repository||Zt.repository.toLowerCase()===o.toLowerCase()))??!1}catch{console.warn(`[deliver] could not read commit checks for ${o}`)}}let Ft=e.inputs.deliverRemote||"origin",dn=GH(d,HH),On=GH(d,YH);if(dn&&!On)throw new Error(`${o}: the checkout records a merged base but not what it merged`);let Bt=dn?k_(void 0,void 0,d):s?s.headBranch||k_(e.inputs.headBranch,e.inputs.baseBranch,d):k_(void 0,void 0,d),Cn=e.inputs.pullRequests;s?.prNumber!=null&&!Cn?.some(_e=>_e.repository.toLowerCase()===o.toLowerCase())&&(Cn=[...Cn??[],{repository:o,number:String(s.prNumber)}]);let Je=Cn?.some(_e=>_e.repository.toLowerCase()===o.toLowerCase())?void 0:e.inputs.deliveryOrigin,Dt=dn||!Je?On:void 0,wn=e.inputs.scheduledDelivery,yt=wn?(0,vA.createHash)("sha256").update(JSON.stringify([wn,o.toLowerCase(),Bt])).digest("hex"):Dt?zhe(o,Bt,Dt):Ghe(Cn,o,Bt,Je),Mn=Vhe(Bt,e.inputs.deliverBranch)+(wn?`-scheduled-${yt}`:Dt?`-merge-${yt}`:Je?`-source-${Je.number}-${yt}`:""),Re=f_(Hq(PH(qhe(te,e,i),{audience:"testbot-pr",requestedBy:e.inputs.requestedBy,sourcePullRequest:Je&&`${Je.repository.namespace}/${Je.repository.name}#${Je.number}`}),e.inputs.skyrampRunUrl))+`
|
|
239
239
|
`,Rt=s?"pr-body.md":`pr-body-${qH(o)}.md`,pn=Jo.join(e.outputsDir,Rt);Ki.writeFileSync(pn,Re);let lr=ln(d,["rev-parse","HEAD"]),dr=dn??lr;ln(d,["checkout","-B",Mn]),a=Mn,ln(d,["reset"]);for(let _e of r)Jhe(Jo.join(d,_e),h);let Ln=[];for(let _e of r)try{ln(d,["--literal-pathspecs","add","--",_e])}catch{Ln.push(_e)}try{ln(d,["diff","--cached","--quiet"])}catch{try{let _e=ln(d,["interpret-trailers","--trailer",`${fv}: ${yt}`,"--trailer",`${ld}: ${lr}`,"--trailer",`${A_}: ${dr}`],`${V}
|
|
240
|
-
`),xt=bn?pv(_e,et):_e;ln(d,["-c",`user.name=${et.name}`,"-c",`user.email=${et.email}`,"commit","-m",xt])}catch(_e){throw new Ev(_e)}c=!0}u=ln(d,["rev-parse","HEAD"]);let pr,Qt=dn??s?.headSha;if(c&&Qt&&Qt!==lr){let _e=!1;try{ln(d,["checkout","-q","-B",a,Qt]),_e=!0,ln(d,["-c",`user.name=${et.name}`,"-c",`user.email=${et.email}`,"cherry-pick","--keep-redundant-commits",u]),_e=!1,h_(xt=>ln(d,xt),Qt),u=ln(d,["rev-parse","HEAD"])}catch(xt){try{ln(d,["cherry-pick","--abort"])}catch{}ln(d,["checkout","-q","-B",a,u]);let Zt=gA(Go(xt),1/0);if(dn&&!_e)throw xt;if(dn)return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:Ft,base:Bt,committed:c,commitSha:u,pushed:!1,prAction:"skipped",prTitle:It,unstaged:Ln,reason:`the tests do not apply to ${Bt} at ${dn.slice(0,12)} without the merged revisions (${Zt}), so no tests PR was opened`}};pr=`tests committed on the checkout's merge commit (re-cut onto ${Qt.slice(0,12)} failed: ${Zt})`}}let Tr=s?{}:{repositoryPath:d,repoSlug:o,devPr:null};if(!c){let _e=await t.markTestsPrUnchanged({branch:a,...Tr});return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:Ft,base:Bt,committed:!1,commitSha:u,pushed:!1,prAction:_e.action==="unchanged"?"unchanged":"skipped",prUrl:_e.url,prTitle:It,unstaged:Ln,reason:_e.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 ht=await t.publishTestsPr({repositoryPath:d,...Tr,remote:Ft,branch:a,base:Bt,commitSha:u,title:It,bodyFile:pn,mode:e.inputs.deliverMode,deliveryOwner:yt,...e.inputs.firstQualification?{firstQualification:!0}:{},runUrl:e.inputs.skyrampRunUrl,signal:e.signal,deadlineMs:e.deadlineMs});return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:Ft,base:ht.base,requestedBase:Bt,committed:c,commitSha:u,pushed:ht.pushed,...ht.pushedCommits?{pushedCommits:ht.pushedCommits}:{},...ht.deliveredCommit?{deliveredCommit:ht.deliveredCommit}:{},prAction:ht.action,...ht.retargetedAs?{retargetedAs:ht.retargetedAs}:{},prUrl:ht.url,prTitle:It,...ht.failure?{prFailure:ht.failure,prDetail:ht.detail}:{},...pr?{cutNote:pr}:{},...ht.action==="skipped"&&ht.detail?{reason:ht.detail}:{},unstaged:Ln}}}catch(d){return{thrown:!0,record:{schemaVersion:1,repository:o,branch:a,committed:c,commitSha:u,pushed:!1,prAction:"failed",...Xhe(d),unstaged:[]}}}}var
|
|
240
|
+
`),xt=bn?pv(_e,et):_e;ln(d,["-c",`user.name=${et.name}`,"-c",`user.email=${et.email}`,"commit","-m",xt])}catch(_e){throw new Ev(_e)}c=!0}u=ln(d,["rev-parse","HEAD"]);let pr,Qt=dn??s?.headSha;if(c&&Qt&&Qt!==lr){let _e=!1;try{ln(d,["checkout","-q","-B",a,Qt]),_e=!0,ln(d,["-c",`user.name=${et.name}`,"-c",`user.email=${et.email}`,"cherry-pick","--keep-redundant-commits",u]),_e=!1,h_(xt=>ln(d,xt),Qt),u=ln(d,["rev-parse","HEAD"])}catch(xt){try{ln(d,["cherry-pick","--abort"])}catch{}ln(d,["checkout","-q","-B",a,u]);let Zt=gA(Go(xt),1/0);if(dn&&!_e)throw xt;if(dn)return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:Ft,base:Bt,committed:c,commitSha:u,pushed:!1,prAction:"skipped",prTitle:It,unstaged:Ln,reason:`the tests do not apply to ${Bt} at ${dn.slice(0,12)} without the merged revisions (${Zt}), so no tests PR was opened`}};pr=`tests committed on the checkout's merge commit (re-cut onto ${Qt.slice(0,12)} failed: ${Zt})`}}let Tr=s?{}:{repositoryPath:d,repoSlug:o,devPr:null};if(!c){let _e=await t.markTestsPrUnchanged({branch:a,...Tr});return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:Ft,base:Bt,committed:!1,commitSha:u,pushed:!1,prAction:_e.action==="unchanged"?"unchanged":"skipped",prUrl:_e.url,prTitle:It,unstaged:Ln,reason:_e.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 ht=await t.publishTestsPr({repositoryPath:d,...Tr,remote:Ft,branch:a,base:Bt,commitSha:u,title:It,bodyFile:pn,mode:e.inputs.deliverMode,deliveryOwner:yt,...e.inputs.firstQualification?{firstQualification:!0}:{},runUrl:e.inputs.skyrampRunUrl,signal:e.signal,deadlineMs:e.deadlineMs});return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:Ft,base:ht.base,requestedBase:Bt,committed:c,commitSha:u,pushed:ht.pushed,...ht.pushedCommits?{pushedCommits:ht.pushedCommits}:{},...ht.deliveredCommit?{deliveredCommit:ht.deliveredCommit}:{},prAction:ht.action,...ht.retargetedAs?{retargetedAs:ht.retargetedAs}:{},prUrl:ht.url,prTitle:It,...ht.failure?{prFailure:ht.failure,prDetail:ht.detail}:{},...pr?{cutNote:pr}:{},...ht.action==="skipped"&&ht.detail?{reason:ht.detail}:{},unstaged:Ln}}}catch(d){return{thrown:!0,record:{schemaVersion:1,repository:o,branch:a,committed:c,commitSha:u,pushed:!1,prAction:"failed",...Xhe(d),unstaged:[]}}}}var HFe={name:"deliver",timeoutMinutes:5,execute:Yhe,validateInput:e=>{let t=d_(e);return t?{ok:!1,reasons:[t]}:Lhe(e)},requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var WH=ce(require("fs")),IA="SKYRAMP_AZURE_SUPERVISED",B_=3;function vv(e){return e.replace(/##(?=(?:vso)?\[)/gi,"#\u200B#")}function R_(e,t=process.env){t[IA]==="1"?WH.writeSync(B_,`${JSON.stringify(e)}
|
|
241
241
|
`):process.stdout.write(e.command!==void 0?`${e.command}
|
|
242
242
|
`:e.text??"")}function Q_(e){R_({command:e})}function ZH(e){return e.replace(/%/g,"%AZP25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function nge(e){return ZH(e).replace(/;/g,"%3B").replace(/]/g,"%5D")}function Iv(e,t,n){let i=Object.entries(t).map(([r,s])=>`${r}=${nge(s)}`).join(";");return`##vso[${e}${i?` ${i}`:""}]${ZH(n)}`}function KH(e){if(!e)return[];let t=e.split(/\r?\n/).filter(n=>n.trim()&&n!==e);return[e,...t].map(n=>Iv("task.setsecret",{},n))}function XH(e,t=Q_){for(let n of KH(e))t(n)}function rge(e){return e.replace(/%0D/g,"\r").replace(/%0A/g,`
|
|
243
243
|
`).replace(/%25/g,"%")}function eY(e){let t=/^::([a-z-]+)(?: [^:]*)?::(.*)$/s.exec(e.replace(/\r?\n$/,""));if(!t)return;let[,n,i]=t,r=rge(i),s=vv(r);switch(n){case"add-mask":return KH(r);case"warning":case"error":return[Iv("task.logissue",{type:n},s)];case"notice":return[s];case"debug":return s.split(`
|
|
244
244
|
`).map(o=>`##[debug]${o}`);case"group":return[`##[group]${s.split(`
|
|
245
|
-
`)[0]}`];case"endgroup":return["##[endgroup]"];default:return[]}}function CA(e){return e.replace(/\/+$/,"")}function x_(e){let t=new URL(e),n=t.pathname.split("/").filter(Boolean);if(n.length)return decodeURIComponent(n[n.length-1]);if(t.hostname.endsWith(".visualstudio.com"))return t.hostname.split(".")[0];throw new Error(`SYSTEM_COLLECTIONURI "${e}" names no organization`)}var ige=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,48}[A-Za-z0-9])?$/,sge=/[\\/:*?"<>|;#${},+=[\]%\p{Cc}\p{Cf}]/u;function tY(e){return e.length>0&&e.length<=64&&e===e.trim()&&!sge.test(e)&&!/[^\S ]/u.test(e)&&!/^[._]/.test(e)&&!e.endsWith(".")}function bv(e){return T_(`${e.namespace}/${e.name}`)}function T_(e){let t=e.indexOf("/"),n=e.lastIndexOf("/"),i=e.slice(0,t),r=e.slice(t+1,n),s=e.slice(n+1);if(t<0||t===n||!ige.test(i)||!tY(r)||!tY(s))throw new Error(`"${e}" is not an Azure DevOps organization/project/repository`);return{organization:i,project:r,name:s}}function nY(e,t){let n=x_(e);if(n.toLowerCase()!==t.organization.toLowerCase())throw new Error(`${t.organization}/${t.project}/${t.name} is not in ${n}, the Azure DevOps organization this job runs in`)}function rY(e,t){return nY(e,t),`${CA(e)}/${encodeURIComponent(t.project)}/_git/${encodeURIComponent(t.name)}`}function __(e,t){return nY(e,t),`${CA(e)}/${encodeURIComponent(t.project)}/_apis/git/repositories/${encodeURIComponent(t.name)}`}var oge="7.1",bA=class extends Error{constructor(n,i){super(n);this.status=i}status};async function $_(e){let t=e.accept??"application/json",n=new URL(e.url);n.searchParams.has("api-version")||n.searchParams.set("api-version",oge);let i=await(e.fetch??fetch)(n.toString(),{method:e.method??"GET",headers:{Authorization:`Bearer ${e.token}`,Accept:t,...e.body!==void 0?{"Content-Type":"application/json"}:{}},...e.body!==void 0?{body:JSON.stringify(e.body)}:{},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!i.ok){let r=(await i.json().catch(()=>({}))).message;throw new bA(`Azure DevOps answered ${i.status}${typeof r=="string"?`: ${r}`:""}`,i.status)}return t!=="application/json"?Buffer.from(await i.arrayBuffer()):i.status===204?{}:await i.json()}function age(e){return`AUTHORIZATION: bearer ${e}`}function iY(e,t){return{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${CA(e)}/.extraheader`,GIT_CONFIG_VALUE_0:age(t)}}var cge="7.1-preview.1",uge=".azure-pipelines/skyramp-testbot-v3.yml";function Vc(e){return e.GITHUB_ACTIONS!=="true"&&/^true$/i.test(e.TF_BUILD??"")}var lge={INPUT_SKYRAMPRUNID:"SKYRAMP_RUN_ID",INPUT_SKYRAMPAPPORIGIN:"SKYRAMP_APP_ORIGIN",INPUT_SKYRAMPMCPGITHUBTOKEN:"SKYRAMP_MCP_GITHUB_TOKEN"};function aY(e=process.env){if(Vc(e))for(let[t,n]of Object.entries(lge))!e[t]&&e[n]!==void 0&&(e[t]=e[n])}function cY(e,t={}){let n=f=>{let h=e[f];if(!h)throw new Error(`${f} is not set; the V3 runner handshake needs it`);return h},i=CA(e.SYSTEM_COLLECTIONURI??""),r=()=>x_(n("SYSTEM_COLLECTIONURI")),s=e.SYSTEM_TEAMPROJECT,o=e.BUILD_REPOSITORY_NAME,a=e.BUILD_REPOSITORY_ID?.toLowerCase(),c=e.SYSTEM_ACCESSTOKEN,u=t.mask??(f=>XH(f)),d=f=>async()=>{if(!f)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_OIDCREQUESTURI to $(System.OidcRequestUri).");if(!c)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_ACCESSTOKEN to $(System.AccessToken).");let h=new URL(f);if(h.protocol!=="https:")throw new Error("SYSTEM_OIDCREQUESTURI is not an https URL");h.searchParams.set("api-version",cge);let g=await(t.fetch??fetch)(h.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json",Accept:"application/json"},body:"{}",redirect:"error",signal:AbortSignal.timeout(3e4)});if(!g.ok)throw new Error(`Azure DevOps refused the OIDC token request: ${g.status}`);let m=(await g.json().catch(()=>({}))).oidcToken;if(typeof m!="string"||!m)throw new Error("Azure DevOps's OIDC token response carried no token");return u(m),m};return{runnerPlatform:Vc(e)?"azure":void 0,workspace:e.BUILD_SOURCESDIRECTORY||void 0,serverUrl:i,apiUrl:i,repository:a&&s&&o&&i?{id:a,slug:`${r()}/${s}/${o}`}:void 0,runId:e.BUILD_BUILDID||void 0,runAttempt:e.SYSTEM_STAGEATTEMPT||void 0,job:e.SYSTEM_JOBNAME||void 0,execution(){let f=n("SYSTEM_STAGEATTEMPT");if(!/^[1-9][0-9]*$/.test(f))throw new Error(`SYSTEM_STAGEATTEMPT is "${f}", not a positive whole number`);let h=n("SYSTEM_COLLECTIONID").toLowerCase();if(!pl.test(h))throw new Error(`SYSTEM_COLLECTIONID is "${h}", not a GUID`);let g=n("BUILD_REPOSITORY_ID").toLowerCase();if(!pl.test(g))throw new Error(`BUILD_REPOSITORY_ID is "${g}", not a GUID`);let m=[r(),n("SYSTEM_TEAMPROJECT"),n("SYSTEM_DEFINITIONID"),n("BUILD_BUILDID")].map(encodeURIComponent).join("/");return{provider:"azure-devops",repository:{provider:"azure-devops",providerAccountId:h,providerRepositoryId:g},providerRunId:m,providerRunAttempt:Number(f),workflowRef:`${uge}@${n("BUILD_SOURCEBRANCH")}`}},takeIdToken(){let f=e.SYSTEM_OIDCREQUESTURI;delete e.SYSTEM_OIDCREQUESTURI;let h=d(f);return()=>h()},takeSourceToken(){return delete e.SYSTEM_ACCESSTOKEN,c||void 0},webIdentity(){if(!e.SYSTEM_OIDCREQUESTURI?.trim()||!c)return;let f=d(e.SYSTEM_OIDCREQUESTURI);return{token:()=>f(),runId:e.BUILD_BUILDID}},v3RunsOnly:!0,assumesBedrockRole:!0,namesSourceToMcp:!0,runSettingsFromApp:!0,checkSourceName(f){bv(f)},cloneUrl(f){return rY(i,bv(f))},gitAuthEnv(f){return iY(i,f)},async pullRequest(f,h,g){let m=await $_({token:await g.token(),url:`${__(i,bv(f))}/pullrequests/${h}`,fetch:g.fetch}),E=m.status==="completed";return{...typeof m.title=="string"?{title:m.title}:{},...typeof m.description=="string"?{body:m.description}:{},...typeof m.status=="string"?{merged:E}:{},...E&&typeof m.lastMergeCommit?.commitId=="string"?{mergeCommit:m.lastMergeCommit.commitId}:{},...E&&typeof m.lastMergeSourceCommit?.commitId=="string"?{mergedHead:m.lastMergeSourceCommit.commitId}:{}}},async commit(f,h,g){let m;try{m=__(i,T_(f))}catch{return{lookup:"unknown"}}try{let E=await $_({token:await g.token(),url:`${m}/commits/${encodeURIComponent(h)}`,fetch:g.fetch});return typeof E.commitId=="string"?{sha:E.commitId}:{lookup:"missing"}}catch(E){return{lookup:E instanceof bA&&(E.status===404||E.status===400)?"missing":"unknown"}}}}}hn();var dge=5e3,D_=/^(?!\.\.?$)[A-Za-z0-9._-]{1,100}$/;function pge(e){let t=Buffer.from(`x-access-token:${e}`).toString("base64");return As(t),`AUTHORIZATION: basic ${t}`}function uY(e,t={}){let n=c=>{let u=e[c];if(!u)throw new Error(`${c} is not set; the V3 runner handshake needs it`);return u},i=e.GITHUB_REPOSITORY_ID,r=e.GITHUB_REPOSITORY,s=(e.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,""),o=(e.GITHUB_API_URL||"https://api.github.com").replace(/\/+$/,""),a=async(c,u)=>u.fetch(c,{headers:{Authorization:`Bearer ${await u.token()}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(3e4)});return{runnerPlatform:e.GITHUB_ACTIONS==="true"?"github":void 0,workspace:e.GITHUB_WORKSPACE||void 0,serverUrl:s,apiUrl:o,repository:i&&r?{id:i,slug:r}:void 0,runId:e.GITHUB_RUN_ID||void 0,runAttempt:e.GITHUB_RUN_ATTEMPT||void 0,job:e.GITHUB_JOB||void 0,execution(){let c=n("GITHUB_RUN_ATTEMPT");if(!/^[1-9][0-9]*$/.test(c))throw new Error(`GITHUB_RUN_ATTEMPT is "${c}", not a positive whole number`);return{provider:"github",repository:{provider:"github",providerAccountId:n("GITHUB_REPOSITORY_OWNER_ID"),providerRepositoryId:n("GITHUB_REPOSITORY_ID")},providerRunId:n("GITHUB_RUN_ID"),providerRunAttempt:Number(c),workflowRef:n("GITHUB_WORKFLOW_REF")}},takeIdToken(){let c=e.ACTIONS_ID_TOKEN_REQUEST_URL,u=e.ACTIONS_ID_TOKEN_REQUEST_TOKEN;return delete e.ACTIONS_ID_TOKEN_REQUEST_URL,delete e.ACTIONS_ID_TOKEN_REQUEST_TOKEN,async d=>{if(!c||!u)throw new Error("The job cannot request an OIDC token. Give it the `id-token: write` permission.");let f=new URL(c);f.searchParams.set("audience",d);let h=await fetch(f,{headers:{Authorization:`Bearer ${u}`,Accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!h.ok)throw new Error(`GitHub refused the OIDC token request: ${h.status}`);let g=(await h.json().catch(()=>({}))).value;if(typeof g!="string"||!g)throw new Error("GitHub's OIDC token response carried no token");return As(g),g}},webIdentity(){return!e.ACTIONS_ID_TOKEN_REQUEST_TOKEN?.trim()||!e.ACTIONS_ID_TOKEN_REQUEST_URL?.trim()?void 0:{token:t.getIDToken??(u=>eL(u)),runId:e.GITHUB_RUN_ID}},v3RunsOnly:!1,assumesBedrockRole:!1,namesSourceToMcp:!1,runSettingsFromApp:!1,checkSourceName(c){for(let u of[c.namespace,c.name])if(!D_.test(u))throw new Error(`"${u}" is not a repository name`)},cloneUrl(c){return`${s}/${c.namespace}/${c.name}.git`},gitAuthEnv(c){return c?{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${s}/.extraheader`,GIT_CONFIG_VALUE_0:pge(c)}:{}},async pullRequest({namespace:c,name:u},d,f){if(![c,u].every(m=>D_.test(m)))throw new Error("the repository name is not valid");let h=await a(`${o}/repos/${c}/${u}/pulls/${d}`,f);if(!h.ok)throw new Error(`GitHub answered ${h.status}`);let g=await h.json();return{...typeof g.title=="string"?{title:g.title}:{},...typeof g.body=="string"?{body:g.body}:{},...typeof g.merged=="boolean"?{merged:g.merged}:{},...g.merged===!0&&typeof g.merge_commit_sha=="string"?{mergeCommit:g.merge_commit_sha}:{},...g.merged===!0&&typeof g.head?.sha=="string"?{mergedHead:g.head.sha}:{}}},async commit(c,u,d){let[f,h,...g]=c.split("/");if(g.length||![f,h].every(m=>m!==void 0&&D_.test(m)))return{lookup:"unknown"};try{let m=await a(`${o}/repos/${f}/${h}/commits/${encodeURIComponent(u)}`,d);if(m.status===404||m.status===422)return{lookup:"missing"};if(!m.ok)return{lookup:"unknown"};let E=await m.json();return typeof E.sha=="string"?{sha:E.sha}:{lookup:"missing"}}catch{return{lookup:"unknown"}}},async revokeToken(c,u){let d=await u(`${o}/installation/token`,{method:"DELETE",headers:{Authorization:`Bearer ${c}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(dge)});if(!d.ok&&d.status!==401)throw new Error(`GitHub answered ${d.status}`)}}}function wA(e=process.env){return Vc(e)?cY(e):uY(e)}var pOe=Buffer.from("302a300506032b656e032100","hex");var tMe=10*6e4;var nMe=10*6e4;var Age=3e4,hge=3,lY=30,qo=class extends Error{constructor(n,i,r,s){super(n);this.status=i;this.code=r;this.path=s}status;code;path},Xi=class extends Error{},fd=class extends Xi{},Cv=class extends fd{};function gge(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}function mge(e,t){if(!pl.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}function yge(e,t,n,i){throw t<500&&t!==429?new qo(e,t,n,i):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new Cv(e):t===503&&n==="RUN_NOT_READY"?new fd(e):new Xi(e)}async function Ege(e,t,n,i,r,s=1/0){let o=gge(e.origin),a=`The time limit for ${t} ${n} was reached`,c,u=0;for(let d=1;d<=hge||c instanceof fd;d+=1){if(c instanceof fd){if(u===lY)throw c;u+=1,d-=1,e.log?.(`${c.message}; trying again (${u} of ${lY}).`),await new Promise(f=>setTimeout(f,Math.max(0,Math.min(e.readyWaitMs??1e4,s-Date.now()))))}else d>1&&await new Promise(f=>setTimeout(f,Math.max(0,Math.min((e.retryDelayMs??2e3)*(d-1),s-Date.now()))));if(Date.now()>=s)throw new Xi(a);try{let f,h=await(Number.isFinite(s)?Promise.race([e.idToken(o),new Promise((m,E)=>{f=setTimeout(()=>E(new Xi(a)),Math.max(1,s-Date.now()))})]).finally(()=>{f&&clearTimeout(f)}):e.idToken(o));if(Date.now()>=s)throw new Xi(a);let g=await(e.fetch??fetch)(new URL(n,o).toString(),{...i(h),redirect:"error",signal:AbortSignal.timeout(Math.max(1,Math.min(Age,s-Date.now())))}).catch(m=>{throw new Xi(m instanceof Error?m.message:String(m),{cause:m})});return await r(g)}catch(f){if(f instanceof qo||Date.now()>=s)throw f;c=f}}throw c}function vge(e,t,n,i,r){let s=i.headers.get("cf-ray");e.log?.(`Testbot V3: ${t} ${n} answered ${i.status}${s?`, cf-ray ${s}`:""}: ${r.replace(/\s+/g," ").slice(0,200)}`)}function Ige(e,t,n,i,r){return Ege(e,t,n,o=>({method:t,headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json",Accept:"application/json"},body:t==="GET"?void 0:JSON.stringify(i)}),async o=>{let a=await o.text().catch(()=>""),c={};try{c=JSON.parse(a)}catch{}if(o.ok)return c.data;vge(e,t,n,o,a);let u=c.error?.fields,d=typeof u?.path=="string"&&typeof u.reason=="string"?` at ${u.path}: ${u.reason}`:"",f=`The Skyramp app refused ${t} ${n}: ${o.status} ${c.error?.code??"no error code"}${d}`;return yge(f,o.status,c.error?.code,typeof u?.path=="string"?u.path:void 0)},r)}var rMe=10*6e4;var iMe=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var sMe=p.object({tests:p.object({placements:p.array(p.unknown()).optional()}).passthrough().optional()}).passthrough(),oMe=p.object({repository:GS,testType:p.string(),directory:p.string()}).passthrough();var aMe=p.object({report:p.object({language:p.string()}).passthrough()}).passthrough();var cMe=p.object({environment:p.object({components:p.array(p.unknown()).optional(),dependencies:p.array(p.unknown()).optional()}).passthrough()}).passthrough(),uMe=p.object({environment:p.object({offLimits:p.unknown().optional()}).passthrough()}).passthrough();var lMe=p.object({name:p.string().min(1),provision:p.literal("existing"),url:p.string().min(1),repository:GS.optional(),revisionUrl:p.string().min(1).optional()}).passthrough(),dMe=p.object({name:p.string().min(1),url:p.string().nullable(),versionUrl:p.string().nullable(),notes:p.string().nullable()}).passthrough();var pMe=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);var fMe={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};async function pY(e,t){return mge(e.attemptId,"attempt id"),Ige(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,SV({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"}))}var SA=ce(require("fs")),Ci=ce(require("path")),fY=require("child_process"),Ad=Ci.join(".skyramp","sut"),AY=Ci.join(".skyramp","workspace.yml");function bge(e){return e.startsWith(`${Ad}${Ci.sep}`)||e.startsWith(".skyramp/sut/")||e===AY||e===".skyramp/workspace.yml"||/(^|\/)(docker-compose|compose)[^/]*\.ya?ml$/.test(e)||/(^|\/)Dockerfile[^/]*$/.test(e)||/^\.github\/workflows\//.test(e)}function N_(e,t,n={}){let i=t.split(/[\\/]+/).filter(Boolean),r=e;for(let[s,o]of i.entries()){r=Ci.join(r,o);let a=SA.lstatSync(r,{throwIfNoEntry:!1}),c=s===i.length-1;if(!a||a.isSymbolicLink()||(c?n.directory?!a.isDirectory():!a.isFile():!a.isDirectory()))return}return i.length?r:void 0}function Gc(e,t=[]){let n=h=>N_(e,h),i=n(Ci.join(Ad,"setup.sh")),r=n(Ci.join(Ad,"teardown.sh")),s=n(Ci.join(Ad,"get-auth-token.sh")),o=n(AY),a,c=n(Ci.join(Ad,"health.json"));if(c)try{let h=JSON.parse(SA.readFileSync(c,"utf-8"));h&&(h.url||h.command)&&(a=h)}catch{}let u,d=n(Ci.join(Ad,"deploy-budget.json"));if(d)try{let h=JSON.parse(SA.readFileSync(d,"utf-8"));typeof h?.minutes=="number"&&Number.isFinite(h.minutes)&&h.minutes>0&&(u=h.minutes)}catch{}let f=t.filter(bge);return{setupScript:i,teardownScript:r,authTokenScript:s,workspaceFile:o,healthHint:a,budgetMinutes:u,present:!!(i||o),staleFiles:f,stale:f.length>0}}var hY=12e4;function P_(e,t,n){let i=n.timeoutMs??hY;if(n.signal?.aborted)return Promise.resolve(`${e.label} failed (cancelled)`);let[r,...s]=e.argv;return new Promise(o=>{let a="",c=!1,u=!1,d,f=(0,fY.spawn)(r,s,{cwd:t,env:n.env,stdio:["ignore","pipe","pipe"],detached:!0}),h=S=>{a=(a+S.toString("utf-8")).slice(-4096)};f.stdout?.on("data",h),f.stderr?.on("data",h);let g=()=>{try{f.pid!==void 0&&process.kill(-f.pid,"SIGKILL")}catch{f.kill("SIGKILL")}},m=S=>{let D=a.trim().split(`
|
|
246
|
-
`).pop()?.trim().slice(0,300)??"";return`${e.label} failed (${S})${D?`: ${D}`:""}`},E=S=>{u||(u=!0,clearTimeout(w),clearTimeout(d),n.signal?.removeEventListener("abort",R),S!==void 0&&g(),f.stdout?.destroy(),f.stderr?.destroy(),o(S))},R=()=>E(m("cancelled")),w=setTimeout(()=>{c=!0,E(m(`timed out after ${i/1e3} s`))},i);n.signal?.addEventListener("abort",R,{once:!0}),n.signal?.aborted&&R();let k=(S,D)=>{if(c)return m(`timed out after ${i/1e3} s`);if(S!==0)return m(S===null?`killed by ${D}`:`exit ${S}`)};f.on("error",S=>E(m(`could not start: ${S.message}`))),f.on("close",(S,D)=>E(k(S,D))),f.on("exit",(S,D)=>{u||(S!==0?E(k(S,D)):d=setTimeout(()=>E(k(S,D)),1e3))})})}var Cge=50,wge=50,Sge=4096,kge=8e3,Bge=2048,Rge=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/,Qge=/^(?!\/)(?!.*(?:^|\/)\.\.?(?:\/|$))[A-Za-z0-9._/ -]{1,255}$/,xge=/^\.github\/workflows\/[A-Za-z0-9._-]+\.ya?ml$/,Tge=/^(?!GITHUB_)(?!SKYRAMP_RUNNER_)[A-Z][A-Z0-9_]{0,99}$/,mY=(s=>(s.Command="command",s.ComposeFile="compose_file",s.DeploymentWorkflow="deployment_workflow",s.Url="url",s.Guidance="guidance",s))(mY||{}),_ge={command:"optional",compose_file:"required",deployment_workflow:"required",url:"none",guidance:"none"},gY=e=>p.string().max(e).refine(t=>t.trim().length>0&&!Rge.test(t),"must be non-blank text with no control characters other than tab, LF and CR");function $ge(e){let t;try{t=new URL(e)}catch{return"invalid URL"}if(t.protocol!=="https:"&&t.protocol!=="http:")return"only http and https URLs";if(t.username||t.password)return"a URL cannot carry a login"}var Dge={command:gY(Sge),compose_file:p.string().regex(Qge,"must be a relative path inside the repository"),deployment_workflow:p.string().regex(xge,"must be a .github/workflows/*.yml path"),url:p.string().max(Bge).superRefine((e,t)=>{let n=$ge(e);n&&t.addIssue({code:p.ZodIssueCode.custom,message:n})}),guidance:gY(kge)},Nge=p.object({kind:p.nativeEnum(mY),value:p.string(),repository:kr.nullable()}).strict().superRefine((e,t)=>{let n=_ge[e.kind];n==="required"&&!e.repository&&t.addIssue({code:p.ZodIssueCode.custom,path:["repository"],message:"a file belongs to a repository"}),n==="none"&&e.repository&&t.addIssue({code:p.ZodIssueCode.custom,path:["repository"],message:`a ${e.kind} names no repository`});let i=Dge[e.kind].safeParse(e.value);if(!i.success)for(let r of i.error.issues)t.addIssue({code:p.ZodIssueCode.custom,path:["value"],message:r.message})}),Pge=p.object({name:p.string().regex(Tge,"must be a GitHub Actions secret name (A-Z, 0-9, _; not GITHUB_ or SKYRAMP_RUNNER_)"),purpose:p.nativeEnum(Wp),required:p.boolean()}).strict(),yMe=p.object({knowledge:p.array(Nge).max(Cge),credentials:p.array(Pge).max(wge)}).strict().superRefine((e,t)=>{let n=new Set;e.credentials.forEach((i,r)=>{n.has(i.name)&&t.addIssue({code:p.ZodIssueCode.custom,path:["credentials",r,"name"],message:"named twice"}),n.add(i.name)})});function yY(e,t){return!!t[e]?.trim()}var EMe={model_provider:"model provider",sut_access:"SUT access",skyramp:"Skyramp",other:"other"};var EY=".skyramp/sut/health.json",NMe={[EY]:`${EY} (with a url or command)`,".skyramp/workspace.yml":".skyramp/workspace.yml (create it with skyramp_init_scan and skyramp_init_workspace)"};function U_(e,t){return e.status!=="ready"||e.environment?[]:[...new Set(e.components.flatMap(n=>n.credentials??[]))].filter(n=>!yY(n,t))}function F_(e){let t=e.filter(XS),n=e.filter(i=>!XS(i));return[n.length>0&&`${n.join(", ")} ${n.length===1?"has":"have"} no value in this setup`,t.length>0&&`${t.join(", ")} ${t.length===1?"is a name":"are names"} Testbot keeps for its own tokens`].filter(Boolean).join("; ")}function wv(e){if(e.state.stages.onboard?.status==="passed")return rt(e,"onboard.json")}function Oge(e){let t=wA(e).serverUrl,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0;return{...e,GIT_CONFIG_COUNT:String(n+2),[`GIT_CONFIG_KEY_${n}`]:`http.${t}/.extraheader`,[`GIT_CONFIG_VALUE_${n}`]:"",[`GIT_CONFIG_KEY_${n+1}`]:"http.extraheader",[`GIT_CONFIG_VALUE_${n+1}`]:""}}var Mge=90,Lge={CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",CLAUDE_BYTE_STREAM_IDLE_TIMEOUT_MS:String(Mge*1e3)},vY=30,IY={BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:String(vY*6e4)},bY=["This session is non-interactive: it ends as soon as you stop, and a background command can",`never notify you. Wait for long builds in the foreground (one Bash call may run up to ${vY}`,"minutes) and keep checking until they finish; never end your turn while setup is running. A server that must keep","running after setup is detached inside the command itself, with the redirect of both stdout and stderr","(`> log 2>&1`) on the whole backgrounded command (`docker compose up -d`, or `{ cmd; } </dev/null > log 2>&1 &`).","Without `2>&1` the server keeps the call's stderr open, and in `a || nohup cmd > log &` or","`(cd dir && nohup cmd > log &)` the redirect covers only `cmd`, and the shell that runs it keeps the call's output","open until the server exits. Run a setup script as a command of its own, never piped or chained:","`bash .skyramp/sut/setup.sh`. The call returns its output and exit status when the script exits, even if a server","it started still holds its output; through a pipe (`| tail`), it waits for that server."];function jge(e,t){return Oge(St(e,{...Lge,...t},"session"))}function O_(e){return jge(process.env,e)}var kv=ce(require("fs")),kA=ce(require("path"));var CY=["browser_assert","browser_assert_api_request","browser_assert_hidden","browser_assert_table_cell","browser_blueprint","browser_click","browser_drag","browser_evaluate","browser_file_upload","browser_gojs_add_node","browser_gojs_link","browser_hover","browser_mouse_action","browser_navigate","browser_navigate_back","browser_press_key","browser_select_option","browser_snapshot","browser_tabs","browser_take_screenshot","browser_type","browser_visual_snapshot","browser_wait_for"],GMe=[...CY,"skyramp_export_zip","skyramp_actions","skyramp_analyze_changes","skyramp_analyze_test_health","skyramp_batch_mock_generation","skyramp_batch_scenario_test_generation","skyramp_contract_test_generation","skyramp_e2e_test_generation","skyramp_enhance_assertions","skyramp_enrich_test_with_mocks","skyramp_execute_test","skyramp_fix_errors","skyramp_fuzz_test_generation","skyramp_generate_enriched_integration_test","skyramp_init_scan","skyramp_init_workspace","skyramp_integration_test_generation","skyramp_load_test_generation","skyramp_login","skyramp_logout","skyramp_mock_generation","skyramp_modularization","skyramp_one_click_tool","skyramp_preflight_mock_check","skyramp_query_proxy_mocks","skyramp_recommend_tests","skyramp_register_test_plan","skyramp_reuse_code","skyramp_run_existing_tests","skyramp_setup_local_dev_worker","skyramp_smoke_test_generation","skyramp_start_trace_collection","skyramp_stop_trace_collection","skyramp_submit_report","skyramp_ui_test_generation"];var zMe=["skyramp_init_workspace","skyramp_ui_test_generation","skyramp_mock_generation","skyramp_fix_errors","skyramp_start_trace_collection","skyramp_stop_trace_collection","skyramp_export_zip",...CY];var wY=["Bash(ls:*)","Bash(cat:*)","Bash(head:*)","Bash(tail:*)","Bash(wc:*)","Bash(find:*)","Bash(grep:*)","Bash(rg:*)","Bash(diff:*)","Bash(sort:*)","Bash(env:*)","Bash(echo:*)","Bash(pwd:*)","Bash(which:*)","Bash(cp:*)","Bash(curl:*)","Bash(jq:*)","Bash(true:*)"];var Sv=ce(require("fs"));var Gge={name:"output-produced",verify(e,t,n){let i=e.outputFileFor(n.name);return(Sv.existsSync(i)?Sv.readFileSync(i,"utf-8"):"").trim().length>0?{name:this.name,passed:!0}:{name:this.name,passed:!1,details:`stage produced no output (${i} empty or missing)`}}},zge=["Re-read the stage instructions above and confirm every task was completed.","If you find a mistake or an incomplete task, fix it now before finishing.","End your response with a one-line summary of what this stage accomplished."];function SY(e){let t=e.requires??[];return{name:e.name,model:e.model??"sonnet",maxAttempts:e.maxAttempts,effort:e.effort,timeoutMinutes:e.timeoutMinutes??15,scaleTimeout:e.scaleTimeout,requires:t,softRequires:e.softRequires,validateInput:e.validateInput??(()=>({ok:!0,reasons:[]})),buildPrompt:e.buildPrompt??(()=>`You are the "${e.name}" stage of the Skyramp Testbot.`),selfVerification:e.selfVerification??zge,exitGates:e.exitGates??[Gge],prepare:e.prepare,abortIf:e.abortIf,onAbort:e.onAbort,teardown:e.teardown,releaseAtRunEnd:e.releaseAtRunEnd,buildMcpServers:e.buildMcpServers,buildReadDirs:e.buildReadDirs,buildPluginDirs:e.buildPluginDirs,buildSettings:e.buildSettings,renderTimeLimit:e.renderTimeLimit,namesSession:e.namesSession,resumeFrom:e.resumeFrom,requiredSkills:e.requiredSkills,buildSessionEnv:e.buildSessionEnv,allowedTools:e.allowedTools,buildDisallowedTools:e.buildDisallowedTools,captureTrace:e.captureTrace,onPassed:e.onPassed,passReason:e.passReason,adversarialReview:e.adversarialReview,retryHint:e.retryHint,beforeGates:e.beforeGates,afterAttempt:e.afterAttempt,retryNote:e.retryNote,salvage:e.salvage,checkpoint:e.checkpoint,needsSutAuth:e.needsSutAuth,triageBranch:e.triageBranch,branchSkipClears:e.branchSkipClears,branchRequires:e.branchRequires}}var Jge=["Bash(docker:*)","Bash(docker compose:*)","Bash(docker-compose:*)","Bash(bash:*)","Bash(sh:*)","Bash(.skyramp/sut/*)","Bash(./.skyramp/sut/*)","Bash(curl:*)","Bash(sleep:*)",...wY,"Read","Write","Edit"];function qge(e){let t=e.state.stages.onboard;if(t&&(t.status==="failed"||t.status==="aborted")){let o=t.reason?` \u2014 ${t.reason.length>300?`${t.reason.slice(0,300)}\u2026`:t.reason}`:"";return{ok:!1,reasons:[`onboarding ran and did not pass (${t.status}${o}) \u2014 deploy does not replay its recipe; fix that and onboard again`]}}let n=Gi(e),i=wv(e);if(i?.status==="blocked")return{ok:!1,reasons:[`onboarding reported blocked (${i.blockers.length} blocker(s)) \u2014 see outputs/onboard.json`]};let r=e.inputs.setupEvents&&t?.status==="passed"&&i&&!e.inputs.recheck?U_(i,O_(wo())):[];return r.length>0?{ok:!1,reasons:[`the recipe reads ${r.join(", ")}: ${F_(r)} \u2014 deploy waits for the check Skyramp runs once the setup ends`]}:n&&!n.sutRequired&&i?.status!=="ready"&&!e.inputs.recheck?{ok:!1,reasons:["preflight determined no SUT is required (non-application change)"]}:Gc(e.inputs.repositoryPath,n?.changedFiles.map(o=>o.path)).present?{ok:!0,reasons:[]}:{ok:!1,reasons:["no deploy recipe found (.skyramp/sut/setup.sh or .skyramp/workspace.yml) \u2014 run onboarding first"]}}function Hge(e){let t=e.prepared?.recipe?.budgetMinutes;if(t===void 0)return;let n=Math.min(t+5,90);return n>25?n:void 0}function Yge(e){let t=Gi(e);return{recipe:Gc(e.inputs.repositoryPath,t?.changedFiles.map(i=>i.path))}}function Wge(e,t){return[t.setupScript,t.teardownScript,t.authTokenScript,t.workspaceFile].filter(n=>!!n).map(n=>kA.relative(e,n))}function Zge(e,t="revisions"){let n=JE(e.inputs);return n.length===0?[]:["","Shared components: these run in an existing environment that this run does not deploy.",...n.map(i=>` - ${i.name} at ${i.url}, running ${i.repository}`),"For each, find the URL on its host where the RUNNING component reports its commit (a version,",`build-info or health endpoint) and record it in "${t}": the url, and what it returned,`,"VERBATIM. This gate fetches each url and reads the commit from what it returns. A checkout's","commit is not the deployed one. Cite only the components listed; leave out one you cannot","check \u2014 it is then reported unverifiable, and no runtime test runs against it."]}function BY(e){return wv(e)?.environment??e.inputs.recheckEnvironment}function Kge(e,t){return[`Tasks: the SUT is the customer's existing deployment at ${e}, already running. Never start, stop, redeploy or`,"change it, and write no setup.sh or teardown.sh: this recipe has none on purpose.","1. Sign in the way the recipe records (.skyramp/sut/get-auth-token.sh), when it has one \u2014 never echo it.","2. Health-check: run the recipe's check (.skyramp/sut/health.json) and confirm it answers with real data. Record the"," exact url/command and what it returned.",...t.healthHint?[` The recorded check: ${JSON.stringify(t.healthHint)}`]:[],'3. Record the outcome: "clean" when the check passes; "bringup-failed", with bringupError, when the deployment does',` not answer or is not ready. baseUrls: each component's address. teardown: "true", since nothing was started.`]}function Xge(e){let t=wv(e),n=e.inputs.recheck?e.inputs.recheckCredentials??[]:t?Fj(t):[];if(n.length===0)return[];let i=e.inputs.sharedEnvironment,r=gl(i).map(s=>s.name);return["",`Credentials: the recipe reads ${n.join(", ")}, each from the environment variable of its name. Test each one that`,"has a value with a request that changes nothing, such as signing in with it (.skyramp/sut/get-auth-token.sh) or a GET","of an authenticated route: never one that creates, changes or deletes data.",...r.length>0?[`The shared components ${r.join(", ")} stay unchanged: test a credential they take only with a read.`]:[],"Record each one that is refused, such as with a 401 or 403 or a sign-in that fails, in",'"credentialsRefused": its name, the component that refused it, the HTTP status, and the request or command with what',"came back. Never write a value, there or anywhere. Leave out one with no value: Testbot reports it. A refused","credential is not drift: never change the recipe to get around it. When it stops the app coming up or its check",'passing, the outcome is "bringup-failed", as for any other failure.']}function eme(e){let{recipe:t}=e.prepared,n=e.inputs.repositoryPath,i=Wge(n,t),r=BY(e),s=e.inputs.sharedEnvironment,o=gl(s).map(a=>a.name);return['You are the "deploy" stage of the Skyramp Testbot.',"",...r?["Purpose: confirm, from a fresh session, that the existing deployment onboard found is reachable and ready, so the","recipe is proven the way every run will use it. The recipe already exists; change nothing."]:["Purpose: bring the system under test (SUT) up from its recorded recipe so","later stages can run tests against it. You do NOT design the deployment \u2014 the","recipe already exists. Execute it, verify it works, and if it has drifted","slightly out of date, correct it and continue (rather than reverting)."],"",`Repository: ${n} \u2014 work inside it.`,`Recipe files present: ${i.join(", ")||"(workspace only)"}`,"",...bY,t.stale?`
|
|
245
|
+
`)[0]}`];case"endgroup":return["##[endgroup]"];default:return[]}}function CA(e){return e.replace(/\/+$/,"")}function x_(e){let t=new URL(e),n=t.pathname.split("/").filter(Boolean);if(n.length)return decodeURIComponent(n[n.length-1]);if(t.hostname.endsWith(".visualstudio.com"))return t.hostname.split(".")[0];throw new Error(`SYSTEM_COLLECTIONURI "${e}" names no organization`)}var ige=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,48}[A-Za-z0-9])?$/,sge=/[\\/:*?"<>|;#${},+=[\]%\p{Cc}\p{Cf}]/u;function tY(e){return e.length>0&&e.length<=64&&e===e.trim()&&!sge.test(e)&&!/[^\S ]/u.test(e)&&!/^[._]/.test(e)&&!e.endsWith(".")}function bv(e){return T_(`${e.namespace}/${e.name}`)}function T_(e){let t=e.indexOf("/"),n=e.lastIndexOf("/"),i=e.slice(0,t),r=e.slice(t+1,n),s=e.slice(n+1);if(t<0||t===n||!ige.test(i)||!tY(r)||!tY(s))throw new Error(`"${e}" is not an Azure DevOps organization/project/repository`);return{organization:i,project:r,name:s}}function nY(e,t){let n=x_(e);if(n.toLowerCase()!==t.organization.toLowerCase())throw new Error(`${t.organization}/${t.project}/${t.name} is not in ${n}, the Azure DevOps organization this job runs in`)}function rY(e,t){return nY(e,t),`${CA(e)}/${encodeURIComponent(t.project)}/_git/${encodeURIComponent(t.name)}`}function __(e,t){return nY(e,t),`${CA(e)}/${encodeURIComponent(t.project)}/_apis/git/repositories/${encodeURIComponent(t.name)}`}var oge="7.1",bA=class extends Error{constructor(n,i){super(n);this.status=i}status};async function $_(e){let t=e.accept??"application/json",n=new URL(e.url);n.searchParams.has("api-version")||n.searchParams.set("api-version",oge);let i=await(e.fetch??fetch)(n.toString(),{method:e.method??"GET",headers:{Authorization:`Bearer ${e.token}`,Accept:t,...e.body!==void 0?{"Content-Type":"application/json"}:{}},...e.body!==void 0?{body:JSON.stringify(e.body)}:{},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!i.ok){let r=(await i.json().catch(()=>({}))).message;throw new bA(`Azure DevOps answered ${i.status}${typeof r=="string"?`: ${r}`:""}`,i.status)}return t!=="application/json"?Buffer.from(await i.arrayBuffer()):i.status===204?{}:await i.json()}function age(e){return`AUTHORIZATION: bearer ${e}`}function iY(e,t){return{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${CA(e)}/.extraheader`,GIT_CONFIG_VALUE_0:age(t)}}var cge="7.1-preview.1",uge=".azure-pipelines/skyramp-testbot-v3.yml";function Vc(e){return e.GITHUB_ACTIONS!=="true"&&/^true$/i.test(e.TF_BUILD??"")}var lge={INPUT_SKYRAMPRUNID:"SKYRAMP_RUN_ID",INPUT_SKYRAMPAPPORIGIN:"SKYRAMP_APP_ORIGIN",INPUT_SKYRAMPMCPGITHUBTOKEN:"SKYRAMP_MCP_GITHUB_TOKEN"};function aY(e=process.env){if(Vc(e))for(let[t,n]of Object.entries(lge))!e[t]&&e[n]!==void 0&&(e[t]=e[n])}function cY(e,t={}){let n=f=>{let h=e[f];if(!h)throw new Error(`${f} is not set; the V3 runner handshake needs it`);return h},i=CA(e.SYSTEM_COLLECTIONURI??""),r=()=>x_(n("SYSTEM_COLLECTIONURI")),s=e.SYSTEM_TEAMPROJECT,o=e.BUILD_REPOSITORY_NAME,a=e.BUILD_REPOSITORY_ID?.toLowerCase(),c=e.SYSTEM_ACCESSTOKEN,u=t.mask??(f=>XH(f)),d=f=>async()=>{if(!f)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_OIDCREQUESTURI to $(System.OidcRequestUri).");if(!c)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_ACCESSTOKEN to $(System.AccessToken).");let h=new URL(f);if(h.protocol!=="https:")throw new Error("SYSTEM_OIDCREQUESTURI is not an https URL");h.searchParams.set("api-version",cge);let g=await(t.fetch??fetch)(h.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json",Accept:"application/json"},body:"{}",redirect:"error",signal:AbortSignal.timeout(3e4)});if(!g.ok)throw new Error(`Azure DevOps refused the OIDC token request: ${g.status}`);let m=(await g.json().catch(()=>({}))).oidcToken;if(typeof m!="string"||!m)throw new Error("Azure DevOps's OIDC token response carried no token");return u(m),m};return{runnerPlatform:Vc(e)?"azure":void 0,workspace:e.BUILD_SOURCESDIRECTORY||void 0,serverUrl:i,apiUrl:i,repository:a&&s&&o&&i?{id:a,slug:`${r()}/${s}/${o}`}:void 0,runId:e.BUILD_BUILDID||void 0,runAttempt:e.SYSTEM_STAGEATTEMPT||void 0,job:e.SYSTEM_JOBNAME||void 0,execution(){let f=n("SYSTEM_STAGEATTEMPT");if(!/^[1-9][0-9]*$/.test(f))throw new Error(`SYSTEM_STAGEATTEMPT is "${f}", not a positive whole number`);let h=n("SYSTEM_COLLECTIONID").toLowerCase();if(!pl.test(h))throw new Error(`SYSTEM_COLLECTIONID is "${h}", not a GUID`);let g=n("BUILD_REPOSITORY_ID").toLowerCase();if(!pl.test(g))throw new Error(`BUILD_REPOSITORY_ID is "${g}", not a GUID`);let m=[r(),n("SYSTEM_TEAMPROJECT"),n("SYSTEM_DEFINITIONID"),n("BUILD_BUILDID")].map(encodeURIComponent).join("/");return{provider:"azure-devops",repository:{provider:"azure-devops",providerAccountId:h,providerRepositoryId:g},providerRunId:m,providerRunAttempt:Number(f),workflowRef:`${uge}@${n("BUILD_SOURCEBRANCH")}`}},takeIdToken(){let f=e.SYSTEM_OIDCREQUESTURI;delete e.SYSTEM_OIDCREQUESTURI;let h=d(f);return()=>h()},takeSourceToken(){return delete e.SYSTEM_ACCESSTOKEN,c||void 0},webIdentity(){if(!e.SYSTEM_OIDCREQUESTURI?.trim()||!c)return;let f=d(e.SYSTEM_OIDCREQUESTURI);return{token:()=>f(),runId:e.BUILD_BUILDID}},v3RunsOnly:!0,assumesBedrockRole:!0,namesSourceToMcp:!0,runSettingsFromApp:!0,checkSourceName(f){bv(f)},cloneUrl(f){return rY(i,bv(f))},gitAuthEnv(f){return iY(i,f)},async pullRequest(f,h,g){let m=await $_({token:await g.token(),url:`${__(i,bv(f))}/pullrequests/${h}`,fetch:g.fetch}),E=m.status==="completed";return{...typeof m.title=="string"?{title:m.title}:{},...typeof m.description=="string"?{body:m.description}:{},...typeof m.status=="string"?{merged:E}:{},...E&&typeof m.lastMergeCommit?.commitId=="string"?{mergeCommit:m.lastMergeCommit.commitId}:{},...E&&typeof m.lastMergeSourceCommit?.commitId=="string"?{mergedHead:m.lastMergeSourceCommit.commitId}:{}}},async commit(f,h,g){let m;try{m=__(i,T_(f))}catch{return{lookup:"unknown"}}try{let E=await $_({token:await g.token(),url:`${m}/commits/${encodeURIComponent(h)}`,fetch:g.fetch});return typeof E.commitId=="string"?{sha:E.commitId}:{lookup:"missing"}}catch(E){return{lookup:E instanceof bA&&(E.status===404||E.status===400)?"missing":"unknown"}}}}}hn();var dge=5e3,D_=/^(?!\.\.?$)[A-Za-z0-9._-]{1,100}$/;function pge(e){let t=Buffer.from(`x-access-token:${e}`).toString("base64");return As(t),`AUTHORIZATION: basic ${t}`}function uY(e,t={}){let n=c=>{let u=e[c];if(!u)throw new Error(`${c} is not set; the V3 runner handshake needs it`);return u},i=e.GITHUB_REPOSITORY_ID,r=e.GITHUB_REPOSITORY,s=(e.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,""),o=(e.GITHUB_API_URL||"https://api.github.com").replace(/\/+$/,""),a=async(c,u)=>u.fetch(c,{headers:{Authorization:`Bearer ${await u.token()}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(3e4)});return{runnerPlatform:e.GITHUB_ACTIONS==="true"?"github":void 0,workspace:e.GITHUB_WORKSPACE||void 0,serverUrl:s,apiUrl:o,repository:i&&r?{id:i,slug:r}:void 0,runId:e.GITHUB_RUN_ID||void 0,runAttempt:e.GITHUB_RUN_ATTEMPT||void 0,job:e.GITHUB_JOB||void 0,execution(){let c=n("GITHUB_RUN_ATTEMPT");if(!/^[1-9][0-9]*$/.test(c))throw new Error(`GITHUB_RUN_ATTEMPT is "${c}", not a positive whole number`);return{provider:"github",repository:{provider:"github",providerAccountId:n("GITHUB_REPOSITORY_OWNER_ID"),providerRepositoryId:n("GITHUB_REPOSITORY_ID")},providerRunId:n("GITHUB_RUN_ID"),providerRunAttempt:Number(c),workflowRef:n("GITHUB_WORKFLOW_REF")}},takeIdToken(){let c=e.ACTIONS_ID_TOKEN_REQUEST_URL,u=e.ACTIONS_ID_TOKEN_REQUEST_TOKEN;return delete e.ACTIONS_ID_TOKEN_REQUEST_URL,delete e.ACTIONS_ID_TOKEN_REQUEST_TOKEN,async d=>{if(!c||!u)throw new Error("The job cannot request an OIDC token. Give it the `id-token: write` permission.");let f=new URL(c);f.searchParams.set("audience",d);let h=await fetch(f,{headers:{Authorization:`Bearer ${u}`,Accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!h.ok)throw new Error(`GitHub refused the OIDC token request: ${h.status}`);let g=(await h.json().catch(()=>({}))).value;if(typeof g!="string"||!g)throw new Error("GitHub's OIDC token response carried no token");return As(g),g}},webIdentity(){return!e.ACTIONS_ID_TOKEN_REQUEST_TOKEN?.trim()||!e.ACTIONS_ID_TOKEN_REQUEST_URL?.trim()?void 0:{token:t.getIDToken??(u=>eL(u)),runId:e.GITHUB_RUN_ID}},v3RunsOnly:!1,assumesBedrockRole:!1,namesSourceToMcp:!1,runSettingsFromApp:!1,checkSourceName(c){for(let u of[c.namespace,c.name])if(!D_.test(u))throw new Error(`"${u}" is not a repository name`)},cloneUrl(c){return`${s}/${c.namespace}/${c.name}.git`},gitAuthEnv(c){return c?{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${s}/.extraheader`,GIT_CONFIG_VALUE_0:pge(c)}:{}},async pullRequest({namespace:c,name:u},d,f){if(![c,u].every(m=>D_.test(m)))throw new Error("the repository name is not valid");let h=await a(`${o}/repos/${c}/${u}/pulls/${d}`,f);if(!h.ok)throw new Error(`GitHub answered ${h.status}`);let g=await h.json();return{...typeof g.title=="string"?{title:g.title}:{},...typeof g.body=="string"?{body:g.body}:{},...typeof g.merged=="boolean"?{merged:g.merged}:{},...g.merged===!0&&typeof g.merge_commit_sha=="string"?{mergeCommit:g.merge_commit_sha}:{},...g.merged===!0&&typeof g.head?.sha=="string"?{mergedHead:g.head.sha}:{}}},async commit(c,u,d){let[f,h,...g]=c.split("/");if(g.length||![f,h].every(m=>m!==void 0&&D_.test(m)))return{lookup:"unknown"};try{let m=await a(`${o}/repos/${f}/${h}/commits/${encodeURIComponent(u)}`,d);if(m.status===404||m.status===422)return{lookup:"missing"};if(!m.ok)return{lookup:"unknown"};let E=await m.json();return typeof E.sha=="string"?{sha:E.sha}:{lookup:"missing"}}catch{return{lookup:"unknown"}}},async revokeToken(c,u){let d=await u(`${o}/installation/token`,{method:"DELETE",headers:{Authorization:`Bearer ${c}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(dge)});if(!d.ok&&d.status!==401)throw new Error(`GitHub answered ${d.status}`)}}}function wA(e=process.env){return Vc(e)?cY(e):uY(e)}var gOe=Buffer.from("302a300506032b656e032100","hex");var sMe=10*6e4;var oMe=10*6e4;var Age=3e4,hge=3,lY=30,qo=class extends Error{constructor(n,i,r,s){super(n);this.status=i;this.code=r;this.path=s}status;code;path},Xi=class extends Error{},fd=class extends Xi{},Cv=class extends fd{};function gge(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}function mge(e,t){if(!pl.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}function yge(e,t,n,i){throw t<500&&t!==429?new qo(e,t,n,i):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new Cv(e):t===503&&n==="RUN_NOT_READY"?new fd(e):new Xi(e)}async function Ege(e,t,n,i,r,s=1/0){let o=gge(e.origin),a=`The time limit for ${t} ${n} was reached`,c,u=0;for(let d=1;d<=hge||c instanceof fd;d+=1){if(c instanceof fd){if(u===lY)throw c;u+=1,d-=1,e.log?.(`${c.message}; trying again (${u} of ${lY}).`),await new Promise(f=>setTimeout(f,Math.max(0,Math.min(e.readyWaitMs??1e4,s-Date.now()))))}else d>1&&await new Promise(f=>setTimeout(f,Math.max(0,Math.min((e.retryDelayMs??2e3)*(d-1),s-Date.now()))));if(Date.now()>=s)throw new Xi(a);try{let f,h=await(Number.isFinite(s)?Promise.race([e.idToken(o),new Promise((m,E)=>{f=setTimeout(()=>E(new Xi(a)),Math.max(1,s-Date.now()))})]).finally(()=>{f&&clearTimeout(f)}):e.idToken(o));if(Date.now()>=s)throw new Xi(a);let g=await(e.fetch??fetch)(new URL(n,o).toString(),{...i(h),redirect:"error",signal:AbortSignal.timeout(Math.max(1,Math.min(Age,s-Date.now())))}).catch(m=>{throw new Xi(m instanceof Error?m.message:String(m),{cause:m})});return await r(g)}catch(f){if(f instanceof qo||Date.now()>=s)throw f;c=f}}throw c}function vge(e,t,n,i,r){let s=i.headers.get("cf-ray");e.log?.(`Testbot V3: ${t} ${n} answered ${i.status}${s?`, cf-ray ${s}`:""}: ${r.replace(/\s+/g," ").slice(0,200)}`)}function Ige(e,t,n,i,r){return Ege(e,t,n,o=>({method:t,headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json",Accept:"application/json"},body:t==="GET"?void 0:JSON.stringify(i)}),async o=>{let a=await o.text().catch(()=>""),c={};try{c=JSON.parse(a)}catch{}if(o.ok)return c.data;vge(e,t,n,o,a);let u=c.error?.fields,d=typeof u?.path=="string"&&typeof u.reason=="string"?` at ${u.path}: ${u.reason}`:"",f=`The Skyramp app refused ${t} ${n}: ${o.status} ${c.error?.code??"no error code"}${d}`;return yge(f,o.status,c.error?.code,typeof u?.path=="string"?u.path:void 0)},r)}var aMe=10*6e4;var cMe=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var uMe=p.object({tests:p.object({placements:p.array(p.unknown()).optional()}).passthrough().optional()}).passthrough(),lMe=p.object({repository:GS,testType:p.string(),directory:p.string()}).passthrough();var dMe=p.object({report:p.object({language:p.string()}).passthrough()}).passthrough();var pMe=p.object({environment:p.object({components:p.array(p.unknown()).optional(),dependencies:p.array(p.unknown()).optional()}).passthrough()}).passthrough(),fMe=p.object({environment:p.object({offLimits:p.unknown().optional()}).passthrough()}).passthrough();var AMe=p.object({name:p.string().min(1),provision:p.literal("existing"),url:p.string().min(1),repository:GS.optional(),revisionUrl:p.string().min(1).optional()}).passthrough(),hMe=p.object({name:p.string().min(1),url:p.string().nullable(),versionUrl:p.string().nullable(),notes:p.string().nullable()}).passthrough();var gMe=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);var mMe={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};async function pY(e,t){return mge(e.attemptId,"attempt id"),Ige(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,SV({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"}))}var SA=ce(require("fs")),Ci=ce(require("path")),fY=require("child_process"),Ad=Ci.join(".skyramp","sut"),AY=Ci.join(".skyramp","workspace.yml");function bge(e){return e.startsWith(`${Ad}${Ci.sep}`)||e.startsWith(".skyramp/sut/")||e===AY||e===".skyramp/workspace.yml"||/(^|\/)(docker-compose|compose)[^/]*\.ya?ml$/.test(e)||/(^|\/)Dockerfile[^/]*$/.test(e)||/^\.github\/workflows\//.test(e)}function N_(e,t,n={}){let i=t.split(/[\\/]+/).filter(Boolean),r=e;for(let[s,o]of i.entries()){r=Ci.join(r,o);let a=SA.lstatSync(r,{throwIfNoEntry:!1}),c=s===i.length-1;if(!a||a.isSymbolicLink()||(c?n.directory?!a.isDirectory():!a.isFile():!a.isDirectory()))return}return i.length?r:void 0}function Gc(e,t=[]){let n=h=>N_(e,h),i=n(Ci.join(Ad,"setup.sh")),r=n(Ci.join(Ad,"teardown.sh")),s=n(Ci.join(Ad,"get-auth-token.sh")),o=n(AY),a,c=n(Ci.join(Ad,"health.json"));if(c)try{let h=JSON.parse(SA.readFileSync(c,"utf-8"));h&&(h.url||h.command)&&(a=h)}catch{}let u,d=n(Ci.join(Ad,"deploy-budget.json"));if(d)try{let h=JSON.parse(SA.readFileSync(d,"utf-8"));typeof h?.minutes=="number"&&Number.isFinite(h.minutes)&&h.minutes>0&&(u=h.minutes)}catch{}let f=t.filter(bge);return{setupScript:i,teardownScript:r,authTokenScript:s,workspaceFile:o,healthHint:a,budgetMinutes:u,present:!!(i||o),staleFiles:f,stale:f.length>0}}var hY=12e4;function P_(e,t,n){let i=n.timeoutMs??hY;if(n.signal?.aborted)return Promise.resolve(`${e.label} failed (cancelled)`);let[r,...s]=e.argv;return new Promise(o=>{let a="",c=!1,u=!1,d,f=(0,fY.spawn)(r,s,{cwd:t,env:n.env,stdio:["ignore","pipe","pipe"],detached:!0}),h=S=>{a=(a+S.toString("utf-8")).slice(-4096)};f.stdout?.on("data",h),f.stderr?.on("data",h);let g=()=>{try{f.pid!==void 0&&process.kill(-f.pid,"SIGKILL")}catch{f.kill("SIGKILL")}},m=S=>{let D=a.trim().split(`
|
|
246
|
+
`).pop()?.trim().slice(0,300)??"";return`${e.label} failed (${S})${D?`: ${D}`:""}`},E=S=>{u||(u=!0,clearTimeout(w),clearTimeout(d),n.signal?.removeEventListener("abort",R),S!==void 0&&g(),f.stdout?.destroy(),f.stderr?.destroy(),o(S))},R=()=>E(m("cancelled")),w=setTimeout(()=>{c=!0,E(m(`timed out after ${i/1e3} s`))},i);n.signal?.addEventListener("abort",R,{once:!0}),n.signal?.aborted&&R();let k=(S,D)=>{if(c)return m(`timed out after ${i/1e3} s`);if(S!==0)return m(S===null?`killed by ${D}`:`exit ${S}`)};f.on("error",S=>E(m(`could not start: ${S.message}`))),f.on("close",(S,D)=>E(k(S,D))),f.on("exit",(S,D)=>{u||(S!==0?E(k(S,D)):d=setTimeout(()=>E(k(S,D)),1e3))})})}var Cge=50,wge=50,Sge=4096,kge=8e3,Bge=2048,Rge=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/,Qge=/^(?!\/)(?!.*(?:^|\/)\.\.?(?:\/|$))[A-Za-z0-9._/ -]{1,255}$/,xge=/^\.github\/workflows\/[A-Za-z0-9._-]+\.ya?ml$/,Tge=/^(?!GITHUB_)(?!SKYRAMP_RUNNER_)[A-Z][A-Z0-9_]{0,99}$/,mY=(s=>(s.Command="command",s.ComposeFile="compose_file",s.DeploymentWorkflow="deployment_workflow",s.Url="url",s.Guidance="guidance",s))(mY||{}),_ge={command:"optional",compose_file:"required",deployment_workflow:"required",url:"none",guidance:"none"},gY=e=>p.string().max(e).refine(t=>t.trim().length>0&&!Rge.test(t),"must be non-blank text with no control characters other than tab, LF and CR");function $ge(e){let t;try{t=new URL(e)}catch{return"invalid URL"}if(t.protocol!=="https:"&&t.protocol!=="http:")return"only http and https URLs";if(t.username||t.password)return"a URL cannot carry a login"}var Dge={command:gY(Sge),compose_file:p.string().regex(Qge,"must be a relative path inside the repository"),deployment_workflow:p.string().regex(xge,"must be a .github/workflows/*.yml path"),url:p.string().max(Bge).superRefine((e,t)=>{let n=$ge(e);n&&t.addIssue({code:p.ZodIssueCode.custom,message:n})}),guidance:gY(kge)},Nge=p.object({kind:p.nativeEnum(mY),value:p.string(),repository:kr.nullable()}).strict().superRefine((e,t)=>{let n=_ge[e.kind];n==="required"&&!e.repository&&t.addIssue({code:p.ZodIssueCode.custom,path:["repository"],message:"a file belongs to a repository"}),n==="none"&&e.repository&&t.addIssue({code:p.ZodIssueCode.custom,path:["repository"],message:`a ${e.kind} names no repository`});let i=Dge[e.kind].safeParse(e.value);if(!i.success)for(let r of i.error.issues)t.addIssue({code:p.ZodIssueCode.custom,path:["value"],message:r.message})}),Pge=p.object({name:p.string().regex(Tge,"must be a GitHub Actions secret name (A-Z, 0-9, _; not GITHUB_ or SKYRAMP_RUNNER_)"),purpose:p.nativeEnum(Wp),required:p.boolean()}).strict(),bMe=p.object({knowledge:p.array(Nge).max(Cge),credentials:p.array(Pge).max(wge)}).strict().superRefine((e,t)=>{let n=new Set;e.credentials.forEach((i,r)=>{n.has(i.name)&&t.addIssue({code:p.ZodIssueCode.custom,path:["credentials",r,"name"],message:"named twice"}),n.add(i.name)})});function yY(e,t){return!!t[e]?.trim()}var CMe={model_provider:"model provider",sut_access:"SUT access",skyramp:"Skyramp",other:"other"};var EY=".skyramp/sut/health.json",OMe={[EY]:`${EY} (with a url or command)`,".skyramp/workspace.yml":".skyramp/workspace.yml (create it with skyramp_init_scan and skyramp_init_workspace)"};function U_(e,t){return e.status!=="ready"||e.environment?[]:[...new Set(e.components.flatMap(n=>n.credentials??[]))].filter(n=>!yY(n,t))}function F_(e){let t=e.filter(XS),n=e.filter(i=>!XS(i));return[n.length>0&&`${n.join(", ")} ${n.length===1?"has":"have"} no value in this setup`,t.length>0&&`${t.join(", ")} ${t.length===1?"is a name":"are names"} Testbot keeps for its own tokens`].filter(Boolean).join("; ")}function wv(e){if(e.state.stages.onboard?.status==="passed")return rt(e,"onboard.json")}function Oge(e){let t=wA(e).serverUrl,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0;return{...e,GIT_CONFIG_COUNT:String(n+2),[`GIT_CONFIG_KEY_${n}`]:`http.${t}/.extraheader`,[`GIT_CONFIG_VALUE_${n}`]:"",[`GIT_CONFIG_KEY_${n+1}`]:"http.extraheader",[`GIT_CONFIG_VALUE_${n+1}`]:""}}var Mge=90,Lge={CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",CLAUDE_BYTE_STREAM_IDLE_TIMEOUT_MS:String(Mge*1e3)},vY=30,IY={BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:String(vY*6e4)},bY=["This session is non-interactive: it ends as soon as you stop, and a background command can",`never notify you. Wait for long builds in the foreground (one Bash call may run up to ${vY}`,"minutes) and keep checking until they finish; never end your turn while setup is running. A server that must keep","running after setup is detached inside the command itself, with the redirect of both stdout and stderr","(`> log 2>&1`) on the whole backgrounded command (`docker compose up -d`, or `{ cmd; } </dev/null > log 2>&1 &`).","Without `2>&1` the server keeps the call's stderr open, and in `a || nohup cmd > log &` or","`(cd dir && nohup cmd > log &)` the redirect covers only `cmd`, and the shell that runs it keeps the call's output","open until the server exits. Run a setup script as a command of its own, never piped or chained:","`bash .skyramp/sut/setup.sh`. The call returns its output and exit status when the script exits, even if a server","it started still holds its output; through a pipe (`| tail`), it waits for that server."];function jge(e,t){return Oge(St(e,{...Lge,...t},"session"))}function O_(e){return jge(process.env,e)}var kv=ce(require("fs")),kA=ce(require("path"));var CY=["browser_assert","browser_assert_api_request","browser_assert_hidden","browser_assert_table_cell","browser_blueprint","browser_click","browser_drag","browser_evaluate","browser_file_upload","browser_gojs_add_node","browser_gojs_link","browser_hover","browser_mouse_action","browser_navigate","browser_navigate_back","browser_press_key","browser_select_option","browser_snapshot","browser_tabs","browser_take_screenshot","browser_type","browser_visual_snapshot","browser_wait_for"],HMe=[...CY,"skyramp_export_zip","skyramp_actions","skyramp_analyze_changes","skyramp_analyze_test_health","skyramp_batch_mock_generation","skyramp_batch_scenario_test_generation","skyramp_contract_test_generation","skyramp_e2e_test_generation","skyramp_enhance_assertions","skyramp_enrich_test_with_mocks","skyramp_execute_test","skyramp_fix_errors","skyramp_fuzz_test_generation","skyramp_generate_enriched_integration_test","skyramp_init_scan","skyramp_init_workspace","skyramp_integration_test_generation","skyramp_load_test_generation","skyramp_login","skyramp_logout","skyramp_mock_generation","skyramp_modularization","skyramp_one_click_tool","skyramp_preflight_mock_check","skyramp_query_proxy_mocks","skyramp_recommend_tests","skyramp_register_test_plan","skyramp_reuse_code","skyramp_run_existing_tests","skyramp_setup_local_dev_worker","skyramp_smoke_test_generation","skyramp_start_trace_collection","skyramp_stop_trace_collection","skyramp_submit_report","skyramp_ui_test_generation"];var YMe=["skyramp_init_workspace","skyramp_ui_test_generation","skyramp_mock_generation","skyramp_fix_errors","skyramp_start_trace_collection","skyramp_stop_trace_collection","skyramp_export_zip",...CY];var wY=["Bash(ls:*)","Bash(cat:*)","Bash(head:*)","Bash(tail:*)","Bash(wc:*)","Bash(find:*)","Bash(grep:*)","Bash(rg:*)","Bash(diff:*)","Bash(sort:*)","Bash(env:*)","Bash(echo:*)","Bash(pwd:*)","Bash(which:*)","Bash(cp:*)","Bash(curl:*)","Bash(jq:*)","Bash(true:*)"];var Sv=ce(require("fs"));var Gge={name:"output-produced",verify(e,t,n){let i=e.outputFileFor(n.name);return(Sv.existsSync(i)?Sv.readFileSync(i,"utf-8"):"").trim().length>0?{name:this.name,passed:!0}:{name:this.name,passed:!1,details:`stage produced no output (${i} empty or missing)`}}},zge=["Re-read the stage instructions above and confirm every task was completed.","If you find a mistake or an incomplete task, fix it now before finishing.","End your response with a one-line summary of what this stage accomplished."];function SY(e){let t=e.requires??[];return{name:e.name,model:e.model??"sonnet",maxAttempts:e.maxAttempts,effort:e.effort,timeoutMinutes:e.timeoutMinutes??15,scaleTimeout:e.scaleTimeout,requires:t,softRequires:e.softRequires,validateInput:e.validateInput??(()=>({ok:!0,reasons:[]})),buildPrompt:e.buildPrompt??(()=>`You are the "${e.name}" stage of the Skyramp Testbot.`),selfVerification:e.selfVerification??zge,exitGates:e.exitGates??[Gge],prepare:e.prepare,abortIf:e.abortIf,onAbort:e.onAbort,teardown:e.teardown,releaseAtRunEnd:e.releaseAtRunEnd,buildMcpServers:e.buildMcpServers,buildReadDirs:e.buildReadDirs,buildPluginDirs:e.buildPluginDirs,buildSettings:e.buildSettings,renderTimeLimit:e.renderTimeLimit,namesSession:e.namesSession,resumeFrom:e.resumeFrom,requiredSkills:e.requiredSkills,buildSessionEnv:e.buildSessionEnv,allowedTools:e.allowedTools,buildDisallowedTools:e.buildDisallowedTools,captureTrace:e.captureTrace,onPassed:e.onPassed,passReason:e.passReason,adversarialReview:e.adversarialReview,retryHint:e.retryHint,beforeGates:e.beforeGates,afterAttempt:e.afterAttempt,retryNote:e.retryNote,salvage:e.salvage,checkpoint:e.checkpoint,needsSutAuth:e.needsSutAuth,triageBranch:e.triageBranch,branchSkipClears:e.branchSkipClears,branchRequires:e.branchRequires}}var Jge=["Bash(docker:*)","Bash(docker compose:*)","Bash(docker-compose:*)","Bash(bash:*)","Bash(sh:*)","Bash(.skyramp/sut/*)","Bash(./.skyramp/sut/*)","Bash(curl:*)","Bash(sleep:*)",...wY,"Read","Write","Edit"];function qge(e){let t=e.state.stages.onboard;if(t&&(t.status==="failed"||t.status==="aborted")){let o=t.reason?` \u2014 ${t.reason.length>300?`${t.reason.slice(0,300)}\u2026`:t.reason}`:"";return{ok:!1,reasons:[`onboarding ran and did not pass (${t.status}${o}) \u2014 deploy does not replay its recipe; fix that and onboard again`]}}let n=Gi(e),i=wv(e);if(i?.status==="blocked")return{ok:!1,reasons:[`onboarding reported blocked (${i.blockers.length} blocker(s)) \u2014 see outputs/onboard.json`]};let r=e.inputs.setupEvents&&t?.status==="passed"&&i&&!e.inputs.recheck?U_(i,O_(wo())):[];return r.length>0?{ok:!1,reasons:[`the recipe reads ${r.join(", ")}: ${F_(r)} \u2014 deploy waits for the check Skyramp runs once the setup ends`]}:n&&!n.sutRequired&&i?.status!=="ready"&&!e.inputs.recheck?{ok:!1,reasons:["preflight determined no SUT is required (non-application change)"]}:Gc(e.inputs.repositoryPath,n?.changedFiles.map(o=>o.path)).present?{ok:!0,reasons:[]}:{ok:!1,reasons:["no deploy recipe found (.skyramp/sut/setup.sh or .skyramp/workspace.yml) \u2014 run onboarding first"]}}function Hge(e){let t=e.prepared?.recipe?.budgetMinutes;if(t===void 0)return;let n=Math.min(t+5,90);return n>25?n:void 0}function Yge(e){let t=Gi(e);return{recipe:Gc(e.inputs.repositoryPath,t?.changedFiles.map(i=>i.path))}}function Wge(e,t){return[t.setupScript,t.teardownScript,t.authTokenScript,t.workspaceFile].filter(n=>!!n).map(n=>kA.relative(e,n))}function Zge(e,t="revisions"){let n=JE(e.inputs);return n.length===0?[]:["","Shared components: these run in an existing environment that this run does not deploy.",...n.map(i=>` - ${i.name} at ${i.url}, running ${i.repository}`),"For each, find the URL on its host where the RUNNING component reports its commit (a version,",`build-info or health endpoint) and record it in "${t}": the url, and what it returned,`,"VERBATIM. This gate fetches each url and reads the commit from what it returns. A checkout's","commit is not the deployed one. Cite only the components listed; leave out one you cannot","check \u2014 it is then reported unverifiable, and no runtime test runs against it."]}function BY(e){return wv(e)?.environment??e.inputs.recheckEnvironment}function Kge(e,t){return[`Tasks: the SUT is the customer's existing deployment at ${e}, already running. Never start, stop, redeploy or`,"change it, and write no setup.sh or teardown.sh: this recipe has none on purpose.","1. Sign in the way the recipe records (.skyramp/sut/get-auth-token.sh), when it has one \u2014 never echo it.","2. Health-check: run the recipe's check (.skyramp/sut/health.json) and confirm it answers with real data. Record the"," exact url/command and what it returned.",...t.healthHint?[` The recorded check: ${JSON.stringify(t.healthHint)}`]:[],'3. Record the outcome: "clean" when the check passes; "bringup-failed", with bringupError, when the deployment does',` not answer or is not ready. baseUrls: each component's address. teardown: "true", since nothing was started.`]}function Xge(e){let t=wv(e),n=e.inputs.recheck?e.inputs.recheckCredentials??[]:t?Fj(t):[];if(n.length===0)return[];let i=e.inputs.sharedEnvironment,r=gl(i).map(s=>s.name);return["",`Credentials: the recipe reads ${n.join(", ")}, each from the environment variable of its name. Test each one that`,"has a value with a request that changes nothing, such as signing in with it (.skyramp/sut/get-auth-token.sh) or a GET","of an authenticated route: never one that creates, changes or deletes data.",...r.length>0?[`The shared components ${r.join(", ")} stay unchanged: test a credential they take only with a read.`]:[],"Record each one that is refused, such as with a 401 or 403 or a sign-in that fails, in",'"credentialsRefused": its name, the component that refused it, the HTTP status, and the request or command with what',"came back. Never write a value, there or anywhere. Leave out one with no value: Testbot reports it. A refused","credential is not drift: never change the recipe to get around it. When it stops the app coming up or its check",'passing, the outcome is "bringup-failed", as for any other failure.']}function eme(e){let{recipe:t}=e.prepared,n=e.inputs.repositoryPath,i=Wge(n,t),r=BY(e),s=e.inputs.sharedEnvironment,o=gl(s).map(a=>a.name);return['You are the "deploy" stage of the Skyramp Testbot.',"",...r?["Purpose: confirm, from a fresh session, that the existing deployment onboard found is reachable and ready, so the","recipe is proven the way every run will use it. The recipe already exists; change nothing."]:["Purpose: bring the system under test (SUT) up from its recorded recipe so","later stages can run tests against it. You do NOT design the deployment \u2014 the","recipe already exists. Execute it, verify it works, and if it has drifted","slightly out of date, correct it and continue (rather than reverting)."],"",`Repository: ${n} \u2014 work inside it.`,`Recipe files present: ${i.join(", ")||"(workspace only)"}`,"",...bY,t.stale?`
|
|
247
247
|
STALENESS WARNING: this PR changed recipe/infra files (${t.staleFiles.join(", ")}).
|
|
248
248
|
The recorded recipe may no longer match. If bring-up fails, first decide
|
|
249
249
|
WHY: recipe drift (infra moved, recipe is behind) vs the change itself
|
|
250
250
|
breaking bring-up. Do NOT paper over a PR that broke the app.`:"","",...r?Kge(r.address,t):["Tasks:","1. Replay the recipe: run .skyramp/sut/setup.sh (or the workspace bring-up)"," even when the SUT already answers: never skip it because something is running."," Bring up every dependency you can; mock one only when deploying it here"," is genuinely infeasible. If the recipe has drifted, correct it so it works"," and update the recipe files to what actually worked. teardown.sh exits 0"," when nothing runs.","2. Seed or reset state per the recipe. Acquire the auth token the way the"," recipe records (.skyramp/sut/get-auth-token.sh) \u2014 never echo it.",...o.length?[` Leave the shared components ${o.join(", ")} unchanged: do not seed or reset them.`]:[],"3. Health-check: confirm application logic answers with real data (seeded",' data readable via a real endpoint) \u2014 NOT "port open", NOT "any HTTP',' status". Record the exact url/command and what it returned.',...t.healthHint?[" Recommended health check (recorded by onboarding \u2014 prefer it, and",` record its real output): ${JSON.stringify(t.healthHint)}`]:[],'4. Record the outcome honestly (see the schema): "change-broke-bringup" is',' published to the author as "your change broke the app" and needs evidence'," \u2014 bringupError plus suspectFiles that THIS PR changed; without a changed",' file to point at, it is "bringup-failed".'],...Zge(e),...Xge(e),"","Output: end with one JSON object matching:","",_V(zp)," // health.output is evidence, not narration: the exact bytes, with NOTHING"," // appended \u2014 no gloss on what the response proves, no list of the other probes"," // you ran. This gate RE-RUNS the check and matches the fresh output against this"," // field, so a sentence added here describes a run nobody can reproduce. Say what"," // it means in your prose answer instead."," // On a failed bring-up, baseUrls/health may be omitted \u2014 never invent a URL for an app that didn't start."].filter(a=>a!==void 0).join(`
|
|
251
|
-
`)}function RY(e){let t=kA.join(e.outputsDir,"deploy.txt");if(kv.existsSync(t)){let{deploy:i}=Pc({exitCode:0,stdout:kv.readFileSync(t,"utf-8"),stderr:"",timedOut:!1,durationMs:0});if(i?.teardown)return{argv:["sh","-c",i.teardown],label:"deploy.json's teardown"}}let{teardownScript:n}=Gc(e.inputs.repositoryPath);if(n)return{argv:["bash",n],label:kA.join(".skyramp","sut","teardown.sh")}}function QY(e,t){return P_(t,e.inputs.repositoryPath,{env:St(process.env,wo())})}async function kY(e){let t=RY(e);t&&await QY(e,t)}async function tme(e,t){let n=t.passed?void 0:xY(e);if(!n)return;let i=await QY(e,n);return i&&`${i} (if nothing was running, a teardown must exit 0)`}function xY(e){return BY(e)?void 0:RY(e)}function nme(e){if(xY(e))return"Testbot tore down the SUT the previous attempt started. Bring it up again from the start: run .skyramp/sut/setup.sh (or the workspace bring-up), even if something still answers. Never reuse what is running."}function rme(e,t){let{deploy:n}=Pc(t,e.inputs.repositoryPath,e.secretValues);if(!n)return;if(n.outcome==="bringup-failed"){let r=vn(n.bringupError?.output?.trim()??"",e.secretValues??[]);return`bring-up failed (environment) \u2014 no live app for later stages${r?`: ${r.slice(0,160)}`:""}`}if(n.outcome==="change-broke-bringup")return"this PR broke bring-up \u2014 recorded as a finding, no live app for later stages";let i=lA(e).map(r=>r.name);if(i.length)return`the shared environment's ${i.join(", ")} does not verifiably run the revision under validation \u2014 no runtime test runs against it`}var TY=SY({name:"deploy",model:"opus",timeoutMinutes:25,requires:["preflight"],softRequires:["onboard"],triageBranch:"runtime",validateInput:qge,prepare:Yge,scaleTimeout:Hge,buildPrompt:eme,allowedTools:Jge,buildSessionEnv:()=>({...IY,...wo()}),selfVerification:["dependencies lists every backing service, true only if really deployed \u2014 a mocked one is false, never omitted.","Your final message is one JSON object matching the schema."],exitGates:[HE(),yq()],onPassed:async(e,t)=>({...vq(e,t),...await Eq(e,t)}),passReason:rme,afterAttempt:tme,retryNote:nme,onAbort:kY,teardown:kY});hn();var
|
|
251
|
+
`)}function RY(e){let t=kA.join(e.outputsDir,"deploy.txt");if(kv.existsSync(t)){let{deploy:i}=Pc({exitCode:0,stdout:kv.readFileSync(t,"utf-8"),stderr:"",timedOut:!1,durationMs:0});if(i?.teardown)return{argv:["sh","-c",i.teardown],label:"deploy.json's teardown"}}let{teardownScript:n}=Gc(e.inputs.repositoryPath);if(n)return{argv:["bash",n],label:kA.join(".skyramp","sut","teardown.sh")}}function QY(e,t){return P_(t,e.inputs.repositoryPath,{env:St(process.env,wo())})}async function kY(e){let t=RY(e);t&&await QY(e,t)}async function tme(e,t){let n=t.passed?void 0:xY(e);if(!n)return;let i=await QY(e,n);return i&&`${i} (if nothing was running, a teardown must exit 0)`}function xY(e){return BY(e)?void 0:RY(e)}function nme(e){if(xY(e))return"Testbot tore down the SUT the previous attempt started. Bring it up again from the start: run .skyramp/sut/setup.sh (or the workspace bring-up), even if something still answers. Never reuse what is running."}function rme(e,t){let{deploy:n}=Pc(t,e.inputs.repositoryPath,e.secretValues);if(!n)return;if(n.outcome==="bringup-failed"){let r=vn(n.bringupError?.output?.trim()??"",e.secretValues??[]);return`bring-up failed (environment) \u2014 no live app for later stages${r?`: ${r.slice(0,160)}`:""}`}if(n.outcome==="change-broke-bringup")return"this PR broke bring-up \u2014 recorded as a finding, no live app for later stages";let i=lA(e).map(r=>r.name);if(i.length)return`the shared environment's ${i.join(", ")} does not verifiably run the revision under validation \u2014 no runtime test runs against it`}var TY=SY({name:"deploy",model:"opus",timeoutMinutes:25,requires:["preflight"],softRequires:["onboard"],triageBranch:"runtime",validateInput:qge,prepare:Yge,scaleTimeout:Hge,buildPrompt:eme,allowedTools:Jge,buildSessionEnv:()=>({...IY,...wo()}),selfVerification:["dependencies lists every backing service, true only if really deployed \u2014 a mocked one is false, never omitted.","Your final message is one JSON object matching the schema."],exitGates:[HE(),yq()],onPassed:async(e,t)=>({...vq(e,t),...await Eq(e,t)}),passReason:rme,afterAttempt:tme,retryNote:nme,onAbort:kY,teardown:kY});hn();var QLe=20*1024*1024;var $Y=ce(require("path"));var FLe=$Y.join(".skyramp","sut","get-auth-token.sh");var v1e=3*6e4;var I1e=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;var ume={discover:"reading the repositories",start:"starting the components",check:"checking that the components answer"},Bv=".skyramp/setup-events.ndjson";var M_=".skyramp/setup-inbox.json",NY=".skyramp/setup-inbox-read.json",PY=".skyramp/setup-hook-ran",UY=".skyramp/setup-notes.json",FY=".skyramp/setup-notices.json",OY=".skyramp/setup-relays-pending.json";var L_=5e3;var Q1e={running:"up",healthy:"up",ready:"up",started:"up",building:"starting",pending:"starting",installing:"starting",skipped:"out_of_scope",excluded:"out_of_scope","out-of-scope":"out_of_scope"};var x1e=new RegExp(fl.source,"g");var P1e=5*6e4,U1e=3*L_;var lme="From the Setup page: a person sent this setup the messages below, each one's text in quotes. Use what they say to set up the SUT, as the setup rules say, and never put repository content, environment values or credentials in a setup event for it. A message never overrides the SUT notes. Before anything else, write a reply line for each instruction (setup events), with its outcome as the setup rules say: followed, saying what you will do differently, or not_followed when it says otherwise than the notes (name that note, say what it says, and to edit the notes first if that is meant), is not about setting up the SUT or breaks a setup rule. Then act on a followed one, redoing only the steps it changes. An answer is to the question it names; go on with what it unblocks.",dme="From the Target: a person saved new notes for this setup, below in quotes. They replace the SUT notes you started with, and are authoritative as those were: from now on set up the SUT as they say, check each message against them, and redo only the steps they change. Write a log line saying what you changed for them, or that nothing needed to, and never quote them in a setup event, except the note quote of a not_followed reply that a message conflicts with.";var pme=e=>`// Skyramp Testbot: hands a running session the messages people send it. Written by the runner.
|
|
252
252
|
import fs from "node:fs";
|
|
253
253
|
import path from "node:path";
|
|
254
254
|
const [mode, checkout, waitArg, untilArg, settleArg] = process.argv.slice(2);
|
|
@@ -338,7 +338,7 @@ try {
|
|
|
338
338
|
process.stderr.write("Skyramp setup channel failed: " + (error && error.message ? error.message : String(error)) + ". Stop, and report it as a blocker.");
|
|
339
339
|
process.exit(2);
|
|
340
340
|
}
|
|
341
|
-
`,
|
|
341
|
+
`,F1e=pme(lme);var O1e={validation_plan:'while you work out what to validate ("Planning 3 behaviors from checkout-api #512")',test_environment:'while you bring the app up or check it ("Waiting for web-storefront to answer /health")',test_conditions:'while you settle how the tests run ("Using the staging payments service, as the notes say")',tests:'while you write and run the tests ("Ran 6 of 9 tests")'};var hje=new RegExp(fl.source,"g");var Ame="https://testbot.skyramp.dev",Ho={attemptId:"v3AttemptId",deadlineAt:"v3DeadlineAt",reportUploaded:"v3ReportUploaded",recipeUploaded:"v3RecipeUploaded",recipeStatus:"v3RecipeStatus",revisionsUploaded:"v3RevisionsUploaded",cause:"v3Cause",conflict:"v3Conflict"};function hme(e,t,n){return{origin:e,idToken:t,sourceToken:n,mask:i=>As(i),log:i=>Or(i),onTokenRefused:(i,r)=>{mme(i)&&MY.set(r,i)},onTokenGranted:i=>{MY.delete(i)}}}var MY=new Map;var _Ge=["setup_failed","checkout_failed","environment_unverified"];function gme(e,t){return t.getTime()>=e.getTime()}function mme(e){return e instanceof Xi||e instanceof qo&&e.code!=="CREDENTIALS_UNAVAILABLE"}var $Ge={cancelled:"Skyramp cancelled this run",expired:"this attempt passed its deadline in Skyramp",ended:"Skyramp already ended this attempt"},DGe={cancelled:"attempt-cancelled",expired:"attempt-closed",ended:"attempt-closed"},NGe={cancelled:"cancelled",expired:"timed_out",ended:"agent_failed"};var PGe={analyze:"analyze",triage:"analyze",recommend:"recommend",generate:"generate","generate-ui":"generate","generate-unit":"generate",adapt:"generate",write:"generate",onboard:"execute",deploy:"execute","native-run":"execute",deliver:"deliver"},UGe={analyze:"change analysis",recommend:"test recommendations",generate:"test generation",execute:"test execution",deliver:"opening a pull request with the tests"};function yme(){return xe("skyrampAppOrigin").trim()||Ame}var FGe=10*6e4;var OGe={onboard:"onboard",deploy:"deploy"},MGe={plan:{stage:"validation_plan",text:"Working out what to validate, and bringing up what it needs"},write:{stage:"tests",text:"Writing and running the tests"},"generate-unit":{stage:"tests",text:"Writing unit tests"},"native-run":{stage:"tests",text:"Running the unit tests"}},LGe=new Set(["write","native-run"]);function Eme(){let e=hs(Ho.conflict);if(!e)return;let t;try{t=wV.safeParse(JSON.parse(e))}catch(n){ct(`Testbot V3: the saved merge conflict is not JSON (${n instanceof Error?n.message:String(n)})`);return}if(t.success)return t.data;ct(`Testbot V3: the saved merge conflict breaks the contract (${t.error.issues.map(n=>`${n.path.join(".")}: ${n.message}`).join("; ")})`)}async function LY(){let e=hs(Ho.attemptId);if(!e)return;let t=hs(Ho.reportUploaded)==="true",n=hs(Ho.recipeUploaded)==="true",i=hs(Ho.revisionsUploaded)==="true",r=hs(Ho.deadlineAt),s=hs(Ho.cause)||void 0;!s&&!t&&!n&&!i&&r&&gme(new Date(r),new Date)&&(s="timed_out");let o=wA().takeIdToken(),a=Eme(),c=await pY({attemptId:e,reportUploaded:t,recipeUploaded:n,revisionsUploaded:i,cause:s,...a?{conflict:a}:{}},hme(yme(),o)),u=hs(Ho.recipeStatus);n&&u?Or(`Testbot V3: attempt ended; the setup ended ${u==="ready"?"Ready":"blocked (Needs input)"}.`):Or(`Testbot V3: attempt ended; the run's outcome in Skyramp is ${c.outcome??"not final yet"}.`)}var jY=require("child_process"),es=ce(require("fs")),V_=ce(require("path")),G_=require("string_decoder");var vme="skyramp-testbot-state",Ime=/^\$\([^)]*\)$/;function bme(e){for(let[t,n]of Object.entries(e))n!==void 0&&Ime.test(n)&&delete e[t]}function Cme(e){let t={},n=es.existsSync(e)?es.readFileSync(e,"utf-8"):"",i=/^([^\r\n<]+)<<(\S+)\r?\n([\s\S]*?)\r?\n\2\r?$/gm;for(let r=i.exec(n);r;r=i.exec(n))t[r[1]]=r[3];return t}function VY(e,t={}){let n=t.env??process.env;if(!Vc(n))return!1;bme(n),aY(n);let i=n.AGENT_TEMPDIRECTORY||n.RUNNER_TEMP;if(i){n.RUNNER_TEMP??=i;let o=V_.join(i,vme);if(e==="main")es.writeFileSync(o,"",{mode:384});else for(let[a,c]of Object.entries(Cme(o)))n[`STATE_${a}`]=c;n.GITHUB_STATE=o;for(let[a,c]of[["GITHUB_OUTPUT","output"],["GITHUB_ENV","env"],["GITHUB_PATH","path"],["GITHUB_STEP_SUMMARY",`summary-${e}.md`]])n[a]=V_.join(i,`skyramp-testbot-${c}`),es.writeFileSync(n[a],"",{mode:384})}let r=t.stdout??n===process.env;r&&wme(n,t.write);let s=n.GITHUB_STEP_SUMMARY;if(r&&s){let o=t.write??(a=>Q_(a.replace(/\n$/,"")));process.once("exit",()=>{es.existsSync(s)&&es.statSync(s).size>0&&o(`${Iv("task.uploadsummary",{},s)}
|
|
342
342
|
`)})}return!0}function wme(e,t){let n=process.stdout.write.bind(process.stdout),i=o=>e[IA]==="1"?R_(o,e):void n(o.command!==void 0?`${o.command}
|
|
343
343
|
`:o.text??""),r=t??(o=>i({command:o.replace(/\n$/,"")})),s=t??(o=>i({text:o}));process.stdout.write=((o,...a)=>{let c=typeof o=="string"?o:Buffer.from(o).toString("utf-8"),u="";for(let f of c.split(/(?<=\n)/)){let h=f.startsWith("::")?eY(f):void 0;if(!h){u+=f;continue}u&&s(u),u="";for(let g of h)r(`${g}
|
|
344
344
|
`)}return u&&s(u),a.find(f=>typeof f=="function")?.(),!0})}var Sme=64*1024;function j_(e){let t=new G_.StringDecoder("utf8"),n="",i=r=>e(vv(r));return{push(r){n+=typeof r=="string"?r:t.write(r);let s=n.lastIndexOf(`
|
package/dist/runner-client.cjs
CHANGED
|
@@ -176,8 +176,8 @@ ${r}`}s(Sm,"withSignOff");function OR(e){let t=/\b(claude|anthropic)\b/i;return
|
|
|
176
176
|
`).filter(a=>!a.startsWith(`${Iu}:`)).join(`
|
|
177
177
|
`).trimEnd(),n=t?`${i}
|
|
178
178
|
${Iu}: ${t}`:i;e(["log","-1","--format=%(trailers:key=Signed-off-by,valueonly)"]).split(`
|
|
179
|
-
`).some(a=>a.trim().toLowerCase()===`${ho} <${Ns}>`.toLowerCase())&&(n=Sm(n,{name:ho,email:Ns})),e(["-c",`user.name=${ho}`,"-c",`user.email=${Ns}`,"commit","--amend","--allow-empty","-m",n])}s(jV,"amendDeliveryBase");var xm=ke(require("fs")),On=ke(require("path"));function hae(e){try{return xm.lstatSync(e),!0}catch{return!1}}s(hae,"lexists");function VV(e){let t=Ke(e,"adapt.json"),r=Ke(e,"finalize.json"),i=Ke(e,vm),n=new Map,o=s(A=>{let p=Xl(e.inputs,A);if("error"in p)return;let g=n.get(p.source.path)??{source:p.source,paths:new Set};return n.set(p.source.path,g),{repo:g.source.path,paths:g.paths}},"pathsOf"),a=s((A,p)=>On.relative(A,On.resolve(A,p.trim())).replace(/\/+$/,""),"norm"),c=s((A,p)=>{let g=p?.trim()&&o(A);if(!g)return;let h=a(g.repo,p);g.paths.add(h);for(let y of["__init__.py","conftest.py"]){let E=On.join(On.dirname(h),y);xm.existsSync(On.join(g.repo,E))&&g.paths.add(E)}},"addTest"),u=s((A,p)=>{if(typeof p!="string"||!p.trim())return;let g=o(A);if(!g)return;let h=a(g.repo,p);if(um(On.join(g.repo,h)))return g.paths.add(h),{...g,rel:h}},"addEdited");for(let A of[...t?.items??[],...i?.tests??[],...i?.maintained??[]])c(A.repository,A.file);for(let A of r?.dependencies?.added??[]){let p=u(A.repository,A.manifest);if(p)for(let g of Sj(p.repo,dR(p.repo,p.rel)))p.paths.add(g)}for(let A of r?.lint??[])for(let p of A.fixed??[])u(A.repository,p);for(let A of r?.support??[])u(A.repository,A.file);let l=Ke(e,AR)?.packages??[];for(let A of new Set(l.map(p=>p.repository))){let p=o(A),g=l.filter(h=>h.repository===A).map(h=>h.dir);if(p)for(let{path:h}of Yj(p.repo)){let y=a(p.repo,h),E=On.join(p.repo,y);pR(y,g)&&!$j(y)&&(!hae(E)||um(E))&&p.paths.add(y)}}return new Map([...n.values()].map(({source:A,paths:p})=>[A,[...p].filter(g=>g&&g!==".."&&!g.startsWith(`..${On.sep}`)&&!FS(g))]))}s(VV,"deliverAllowlist");var zV=ke(require("fs"));var JV=2*1024*1024;function mae(e){let t=[];for(let r of e??[])if(r.state==="read")try{t.push({item:r,text:zV.readFileSync(QP(r),"utf-8")})}catch{}return t}s(mae,"readItemTexts");var EA=6,yae=/[\p{L}\p{N}]+/gu,Eae=new RegExp("(?<=\\p{Ll})(?=\\p{Lu})|(?<=\\p{Lu})(?=\\p{Lu}\\p{Ll})","u");function VR(e){let t=[];for(let r of e.matchAll(yae)){let i=r.index;for(let n of r[0].split(Eae))t.push({word:n.toLowerCase(),start:i,end:i+n.length}),i+=n.length}return t}s(VR,"wordsOf");var qV=s((e,t)=>e.slice(t,t+EA).map(r=>r.word).join(" "),"runAt");function GV(e){let t=VR(e),r=new Set;for(let i=0;i+EA<=t.length;i++)r.add(qV(t,i));return r}s(GV,"runsOf");function HV(e,t=[]){let r=new Set(t.flatMap(i=>[...GV(i)]));return mae(e).map(({item:i,text:n})=>{let o=i.source==="other"?n:n.slice(n.indexOf(`
|
|
180
|
-
`)+1||n.length),a=GV(o);for(let c of r)a.delete(c);return{name:bM(i.key,YC([i])),key:i.key,runs:a,words:VR(o).map(c=>c.word)}})}s(HV,"requirementTexts");var
|
|
179
|
+
`).some(a=>a.trim().toLowerCase()===`${ho} <${Ns}>`.toLowerCase())&&(n=Sm(n,{name:ho,email:Ns})),e(["-c",`user.name=${ho}`,"-c",`user.email=${Ns}`,"commit","--amend","--allow-empty","-m",n])}s(jV,"amendDeliveryBase");var xm=ke(require("fs")),On=ke(require("path"));var TTe=5*1024*1024;function hae(e){try{return xm.lstatSync(e),!0}catch{return!1}}s(hae,"lexists");function VV(e){let t=Ke(e,"adapt.json"),r=Ke(e,"finalize.json"),i=Ke(e,vm),n=new Map,o=s(A=>{let p=Xl(e.inputs,A);if("error"in p)return;let g=n.get(p.source.path)??{source:p.source,paths:new Set};return n.set(p.source.path,g),{repo:g.source.path,paths:g.paths}},"pathsOf"),a=s((A,p)=>On.relative(A,On.resolve(A,p.trim())).replace(/\/+$/,""),"norm"),c=s((A,p)=>{let g=p?.trim()&&o(A);if(!g)return;let h=a(g.repo,p);g.paths.add(h);for(let y of["__init__.py","conftest.py"]){let E=On.join(On.dirname(h),y);xm.existsSync(On.join(g.repo,E))&&g.paths.add(E)}},"addTest"),u=s((A,p)=>{if(typeof p!="string"||!p.trim())return;let g=o(A);if(!g)return;let h=a(g.repo,p);if(um(On.join(g.repo,h)))return g.paths.add(h),{...g,rel:h}},"addEdited");for(let A of[...t?.items??[],...i?.tests??[],...i?.maintained??[]])c(A.repository,A.file);for(let A of r?.dependencies?.added??[]){let p=u(A.repository,A.manifest);if(p)for(let g of Sj(p.repo,dR(p.repo,p.rel)))p.paths.add(g)}for(let A of r?.lint??[])for(let p of A.fixed??[])u(A.repository,p);for(let A of r?.support??[])u(A.repository,A.file);let l=Ke(e,AR)?.packages??[];for(let A of new Set(l.map(p=>p.repository))){let p=o(A),g=l.filter(h=>h.repository===A).map(h=>h.dir);if(p)for(let{path:h}of Yj(p.repo)){let y=a(p.repo,h),E=On.join(p.repo,y);pR(y,g)&&!$j(y)&&(!hae(E)||um(E))&&p.paths.add(y)}}return new Map([...n.values()].map(({source:A,paths:p})=>[A,[...p].filter(g=>g&&g!==".."&&!g.startsWith(`..${On.sep}`)&&!FS(g))]))}s(VV,"deliverAllowlist");var zV=ke(require("fs"));var JV=2*1024*1024;function mae(e){let t=[];for(let r of e??[])if(r.state==="read")try{t.push({item:r,text:zV.readFileSync(QP(r),"utf-8")})}catch{}return t}s(mae,"readItemTexts");var EA=6,yae=/[\p{L}\p{N}]+/gu,Eae=new RegExp("(?<=\\p{Ll})(?=\\p{Lu})|(?<=\\p{Lu})(?=\\p{Lu}\\p{Ll})","u");function VR(e){let t=[];for(let r of e.matchAll(yae)){let i=r.index;for(let n of r[0].split(Eae))t.push({word:n.toLowerCase(),start:i,end:i+n.length}),i+=n.length}return t}s(VR,"wordsOf");var qV=s((e,t)=>e.slice(t,t+EA).map(r=>r.word).join(" "),"runAt");function GV(e){let t=VR(e),r=new Set;for(let i=0;i+EA<=t.length;i++)r.add(qV(t,i));return r}s(GV,"runsOf");function HV(e,t=[]){let r=new Set(t.flatMap(i=>[...GV(i)]));return mae(e).map(({item:i,text:n})=>{let o=i.source==="other"?n:n.slice(n.indexOf(`
|
|
180
|
+
`)+1||n.length),a=GV(o);for(let c of r)a.delete(c);return{name:bM(i.key,YC([i])),key:i.key,runs:a,words:VR(o).map(c=>c.word)}})}s(HV,"requirementTexts");var HTe=EA/2;var Iae=s(e=>e.criteria.size?`${e.text.name} ${[...e.criteria].sort((t,r)=>t-r).map(t=>`AC${t}`).join(", ")}`:e.text.name,"copyName");function Cae(e,t){if(t.length===0)return[];let r=VR(e),i=[];for(let n=0;n+EA<=r.length;n++){let o=qV(r,n),a=t.find(p=>p.runs.has(o));if(!a)continue;let c=r[n].start,u=r[n+EA-1].end,l=a.criteria?.get(o)??[],A=i.at(-1);if(A&&c<=A.end){if(A.end=Math.max(A.end,u),A.text===a)for(let p of l)A.criteria.add(p)}else i.push({start:c,end:u,text:a,criteria:new Set(l)})}return i.map(n=>({start:n.start,end:n.end,name:Iae(n)}))}s(Cae,"copies");function $m(e,t){let r=e;for(let i of Cae(e,t).reverse())r=`${r.slice(0,i.start)}(see ${i.name})${r.slice(i.end)}`;return r}s($m,"withoutRequirementText");function vae(e,t,r){for(let i=t+1;i<e.length;i++){let n=e[i];if(n==="\\")i++;else{if(n===r)return i+1;if(n===`
|
|
181
181
|
`&&r!=="`")return i}}return e.length}s(vae,"stringEnd");function bae(e,t){let r=e.lastIndexOf(`
|
|
182
182
|
`,t-1)+1;if(e.slice(r,t).trim()!=="")return!1;let i=e.slice(0,r).trimEnd();return i===""||i.endsWith(":")}s(bae,"isDocstring");function wae(e){let t=[],r=s(n=>(e.indexOf(`
|
|
183
183
|
`,n)+1||e.length+1)-1,"lineEnd"),i=0;for(;i<e.length;){let n=e[i],o=e[i+1],a=i+1;if(n==="/"&&o==="*")a=e.indexOf("*/",i+2)<0?e.length:e.indexOf("*/",i+2)+2,t.push({start:i,end:a});else if(n==="/"&&o==="/"&&!/[:\w]/.test(e[i-1]??"")||n==="#"&&/^\s?$/.test(e[i-1]??"")&&!/[!{[]/.test(o??""))a=r(i),t.push({start:i,end:a});else if((n==='"'||n==="'")&&e.startsWith(n.repeat(3),i)){let c=e.indexOf(n.repeat(3),i+3);a=c<0?e.length:c+3,bae(e,i)&&t.push({start:i,end:a})}else(n==='"'||n==="'"||n==="`")&&(a=vae(e,i,n));i=a}return t}s(wae,"commentRanges");var Bae=/\b(?:test|it|describe|context|suite|scenario|specify|Run|DisplayName)(?:\.\w+)*(?:\.each\s*(?:\((?:[^()]|\([^()]*\))*\)|`[^`]*`))?\s*\(\s*("(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`)/g;function Qae(e,t){return[...e.matchAll(Bae)].flatMap(r=>{if(t.some(n=>r.index>=n.start&&r.index<n.end))return[];let i=r.index+r[0].length;return[{start:i-r[1].length,end:i}]})}s(Qae,"titleRanges");function YV(e,t){if(t.length===0)return{content:e,cleaned:!1};let r=wae(e),i=[];for(let c of r){let u=e.slice(c.start,c.end),l=$m(u,t);l!==u&&i.push({...c,text:l})}let n=Qae(e,r),o=new Set(n.map(c=>e.slice(c.start+1,c.end-1)));for(let c of n){let u=e[c.start],l=e.slice(c.start+1,c.end-1),A=$m(l,t);if(A===l)continue;let p=A;for(let g=2;o.has(p);g++)p=`${A} (${g})`;o.add(p),i.push({...c,text:`${u}${p}${u}`})}let a=e;for(let c of i.sort((u,l)=>l.start-u.start))a=`${a.slice(0,c.start)}${c.text}${a.slice(c.end)}`;return{content:a,cleaned:a!==e}}s(YV,"withoutRequirementTextInTestFile");function Sae(e){if(!e.inputs.deliver)return{ok:!1,reasons:["deliver not requested (pass --deliver to push)"]};if(!e.platform?.supportsRemote)return{ok:!1,reasons:["deliver needs a remote platform driver (pass --runner-platform github)"]};let t=Ke(e,"finalize.json");return t?t.ready!==!0?{ok:!1,reasons:[`finalize reported ready:false \u2014 not pushing (blockers: ${(t.blockers??[]).slice(0,3).join("; ")||"unspecified"})`]}:{ok:!0,reasons:[]}:{ok:!1,reasons:["finalize.json not found \u2014 refusing to push unverified tests"]}}s(Sae,"validateDeliverInput");function XV(e){return e.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"tests"}s(XV,"slug");var Rae="skyramp-testbot/";function xae(e,t){return t||`${Rae}${XV(e)}-tests`}s(xae,"testsBranchName");function $ae(e,t,r,i){let n=(e??[]).filter(a=>a.repository.toLowerCase()===t.toLowerCase());if(!n.length&&i){let a=i.repository,c=[i.targetId,a.provider,a.providerAccountId,a.providerRepositoryId,i.number,t.toLowerCase(),r];return(0,IA.createHash)("sha256").update(JSON.stringify(c)).digest("hex").slice(0,32)}let o=n.length?[...new Set(n.map(a=>`${a.repository.toLowerCase()}#${a.number}`))].sort():[`branch ${r}`];return(0,IA.createHash)("sha256").update(o.join(`
|
|
@@ -189,9 +189,9 @@ ${Iu}: ${t}`:i;e(["log","-1","--format=%(trailers:key=Signed-off-by,valueonly)"]
|
|
|
189
189
|
${r}`}:{prFailure:"unknown",prDetail:t}}s(Lae,"thrownFailure");async function Oae(e,t,r,i,n,o){let a=sV(i.path,e.runDir),c=process.env.PATH;a.dir&&(process.env.PATH=aV(a).PATH);try{return await jae(e,t,r,i,n,o)}finally{a.dir&&(process.env.PATH=c),a.cleanup()}}s(Oae,"deliverOne");async function jae(e,t,r,i,n,o){let a=i.slug,c,u=!1,l;try{let A=i.path,p=Ke(e,"finalize.json"),g=HV(e.inputs.requirementItems),h=FV(A),y=Ke(e,"write.json"),E=y?.commit?.message||Ke(e,"generate-unit.json")?.commitMessage,C=i.working,I=s(xe=>xe.split(`
|
|
190
190
|
`)[0],"subjectOf"),b=s(xe=>$m(OR(xe),g),"publicText"),v=s((xe,Qt)=>C&&!!Qt&&b(xe).trim()===b(Qt).trim(),"authored"),S=s((xe,Qt,wn)=>{let Oi=b(xe);return wn&&LV(Oi,Qt)?Oi:OV(Oi,Qt,n)},"conform"),D=p?.commit?.message||r.commitMessage||"Skyramp Testbot: add tests",M=S(D,{commitlint:h.commitlint},v(D,E)),K=kV(e.outputsDir)??r,V=C?p?.pr?.title||r.prTitle||y?.commit?.prTitle:void 0,Ee=V||D,Le=C?K.prTitle:void 0,_e=I(b(Ee))===I(b(D)),Oe=(!C||!r.prTitle)&&_e?K.commitMessage:void 0,Je=Le||Oe||Ee,Me=y?.commit?.prTitle||(E?I(E):void 0),ut=v(Ee,Me),q=h.prTitle?{prTitle:h.prTitle}:ut&&V&&!_e?{}:{commitlint:h.commitlint},xt=I(S(Je,q,ut)),lt={name:ho,email:Ns},lr=!!h.signOff;if(!lr&&t.listCommitChecks){let xe=o?.headSha??Pt(A,["rev-parse","HEAD"]);try{lr=(await t.listCommitChecks({repository:a,revision:xe}))?.records.some(wn=>wn.name.trim().toLowerCase()==="dco"&&wn.headSha===xe&&(!wn.repository||wn.repository.toLowerCase()===a.toLowerCase()))??!1}catch{console.warn(`[deliver] could not read commit checks for ${a}`)}}let jn=e.inputs.deliverRemote||"origin",Vn=WV(A,eG),Fi=WV(A,tG);if(Vn&&!Fi)throw new Error(`${a}: the checkout records a merged base but not what it merged`);let Lt=Vn?GR(void 0,void 0,A):o?o.headBranch||GR(e.inputs.headBranch,e.inputs.baseBranch,A):GR(void 0,void 0,A),xr=e.inputs.pullRequests;o?.prNumber!=null&&!xr?.some(xe=>xe.repository.toLowerCase()===a.toLowerCase())&&(xr=[...xr??[],{repository:a,number:String(o.prNumber)}]);let dt=xr?.some(xe=>xe.repository.toLowerCase()===a.toLowerCase())?void 0:e.inputs.deliveryOrigin,Gn=Vn||!dt?Fi:void 0,ri=e.inputs.scheduledDelivery,qt=ri?(0,IA.createHash)("sha256").update(JSON.stringify([ri,a.toLowerCase(),Lt])).digest("hex"):Gn?Tae(a,Lt,Gn):$ae(xr,a,Lt,dt),Mi=xae(Lt,e.inputs.deliverBranch)+(ri?`-scheduled-${qt}`:Gn?`-merge-${qt}`:dt?`-source-${dt.number}-${qt}`:""),it=OR(SV(QV(_ae(K,e,i),{audience:"testbot-pr",requestedBy:e.inputs.requestedBy,sourcePullRequest:dt&&`${dt.repository.namespace}/${dt.repository.name}#${dt.number}`}),e.inputs.skyrampRunUrl))+`
|
|
191
191
|
`,zn=o?"pr-body.md":`pr-body-${XV(a)}.md`,ii=Uo.join(e.outputsDir,zn);ti.writeFileSync(ii,it);let Pi=Pt(A,["rev-parse","HEAD"]),Fo=Vn??Pi;Pt(A,["checkout","-B",Mi]),c=Mi,Pt(A,["reset"]);for(let xe of n)Dae(Uo.join(A,xe),g);let oi=[];for(let xe of n)try{Pt(A,["--literal-pathspecs","add","--",xe])}catch{oi.push(xe)}try{Pt(A,["diff","--cached","--quiet"])}catch{try{let xe=Pt(A,["interpret-trailers","--trailer",`${Rm}: ${qt}`,"--trailer",`${Iu}: ${Pi}`,"--trailer",`${jR}: ${Fo}`],`${M}
|
|
192
|
-
`),Qt=lr?Sm(xe,lt):xe;Pt(A,["-c",`user.name=${lt.name}`,"-c",`user.email=${lt.email}`,"commit","-m",Qt])}catch(xe){throw new Tm(xe)}u=!0}l=Pt(A,["rev-parse","HEAD"]);let Li,cn=Vn??o?.headSha;if(u&&cn&&cn!==Pi){let xe=!1;try{Pt(A,["checkout","-q","-B",c,cn]),xe=!0,Pt(A,["-c",`user.name=${lt.name}`,"-c",`user.email=${lt.email}`,"cherry-pick","--keep-redundant-commits",l]),xe=!1,jV(Qt=>Pt(A,Qt),cn),l=Pt(A,["rev-parse","HEAD"])}catch(Qt){try{Pt(A,["cherry-pick","--abort"])}catch{}Pt(A,["checkout","-q","-B",c,l]);let wn=Nl(fs(Qt),1/0);if(Vn&&!xe)throw Qt;if(Vn)return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:jn,base:Lt,committed:u,commitSha:l,pushed:!1,prAction:"skipped",prTitle:xt,unstaged:oi,reason:`the tests do not apply to ${Lt} at ${Vn.slice(0,12)} without the merged revisions (${wn}), so no tests PR was opened`}};Li=`tests committed on the checkout's merge commit (re-cut onto ${cn.slice(0,12)} failed: ${wn})`}}let Mo=o?{}:{repositoryPath:A,repoSlug:a,devPr:null};if(!u){let xe=await t.markTestsPrUnchanged({branch:c,...Mo});return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:jn,base:Lt,committed:!1,commitSha:l,pushed:!1,prAction:xe.action==="unchanged"?"unchanged":"skipped",prUrl:xe.url,prTitle:xt,unstaged:oi,reason:xe.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 gt=await t.publishTestsPr({repositoryPath:A,...Mo,remote:jn,branch:c,base:Lt,commitSha:l,title:xt,bodyFile:ii,mode:e.inputs.deliverMode,deliveryOwner:qt,...e.inputs.firstQualification?{firstQualification:!0}:{},runUrl:e.inputs.skyrampRunUrl,signal:e.signal,deadlineMs:e.deadlineMs});return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:jn,base:gt.base,requestedBase:Lt,committed:u,commitSha:l,pushed:gt.pushed,...gt.pushedCommits?{pushedCommits:gt.pushedCommits}:{},...gt.deliveredCommit?{deliveredCommit:gt.deliveredCommit}:{},prAction:gt.action,...gt.retargetedAs?{retargetedAs:gt.retargetedAs}:{},prUrl:gt.url,prTitle:xt,...gt.failure?{prFailure:gt.failure,prDetail:gt.detail}:{},...Li?{cutNote:Li}:{},...gt.action==="skipped"&>.detail?{reason:gt.detail}:{},unstaged:oi}}}catch(A){return{thrown:!0,record:{schemaVersion:1,repository:a,branch:c,committed:u,commitSha:l,pushed:!1,prAction:"failed",...Lae(A),unstaged:[]}}}}s(jae,"deliverRepository");var
|
|
192
|
+
`),Qt=lr?Sm(xe,lt):xe;Pt(A,["-c",`user.name=${lt.name}`,"-c",`user.email=${lt.email}`,"commit","-m",Qt])}catch(xe){throw new Tm(xe)}u=!0}l=Pt(A,["rev-parse","HEAD"]);let Li,cn=Vn??o?.headSha;if(u&&cn&&cn!==Pi){let xe=!1;try{Pt(A,["checkout","-q","-B",c,cn]),xe=!0,Pt(A,["-c",`user.name=${lt.name}`,"-c",`user.email=${lt.email}`,"cherry-pick","--keep-redundant-commits",l]),xe=!1,jV(Qt=>Pt(A,Qt),cn),l=Pt(A,["rev-parse","HEAD"])}catch(Qt){try{Pt(A,["cherry-pick","--abort"])}catch{}Pt(A,["checkout","-q","-B",c,l]);let wn=Nl(fs(Qt),1/0);if(Vn&&!xe)throw Qt;if(Vn)return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:jn,base:Lt,committed:u,commitSha:l,pushed:!1,prAction:"skipped",prTitle:xt,unstaged:oi,reason:`the tests do not apply to ${Lt} at ${Vn.slice(0,12)} without the merged revisions (${wn}), so no tests PR was opened`}};Li=`tests committed on the checkout's merge commit (re-cut onto ${cn.slice(0,12)} failed: ${wn})`}}let Mo=o?{}:{repositoryPath:A,repoSlug:a,devPr:null};if(!u){let xe=await t.markTestsPrUnchanged({branch:c,...Mo});return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:jn,base:Lt,committed:!1,commitSha:l,pushed:!1,prAction:xe.action==="unchanged"?"unchanged":"skipped",prUrl:xe.url,prTitle:xt,unstaged:oi,reason:xe.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 gt=await t.publishTestsPr({repositoryPath:A,...Mo,remote:jn,branch:c,base:Lt,commitSha:l,title:xt,bodyFile:ii,mode:e.inputs.deliverMode,deliveryOwner:qt,...e.inputs.firstQualification?{firstQualification:!0}:{},runUrl:e.inputs.skyrampRunUrl,signal:e.signal,deadlineMs:e.deadlineMs});return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:jn,base:gt.base,requestedBase:Lt,committed:u,commitSha:l,pushed:gt.pushed,...gt.pushedCommits?{pushedCommits:gt.pushedCommits}:{},...gt.deliveredCommit?{deliveredCommit:gt.deliveredCommit}:{},prAction:gt.action,...gt.retargetedAs?{retargetedAs:gt.retargetedAs}:{},prUrl:gt.url,prTitle:xt,...gt.failure?{prFailure:gt.failure,prDetail:gt.detail}:{},...Li?{cutNote:Li}:{},...gt.action==="skipped"&>.detail?{reason:gt.detail}:{},unstaged:oi}}}catch(A){return{thrown:!0,record:{schemaVersion:1,repository:a,branch:c,committed:u,commitSha:l,pushed:!1,prAction:"failed",...Lae(A),unstaged:[]}}}}s(jae,"deliverRepository");var gDe={name:"deliver",timeoutMinutes:5,execute:Uae,validateInput:s(e=>{let t=$R(e);return t?{ok:!1,reasons:[t]}:Sae(e)},"validateInput"),requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var nG=ke(require("fs"));var Vae="SKYRAMP_AZURE_SUPERVISED",Gae=3;function zae(e,t=process.env){t[Vae]==="1"?nG.writeSync(Gae,`${JSON.stringify(e)}
|
|
193
193
|
`):process.stdout.write(e.command!==void 0?`${e.command}
|
|
194
|
-
`:e.text??"")}s(zae,"writeFrame");function Jae(e){zae({command:e})}s(Jae,"writeAzureCommand");function rG(e){return e.replace(/%/g,"%AZP25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}s(rG,"escapeData");function qae(e){return rG(e).replace(/;/g,"%3B").replace(/]/g,"%5D")}s(qae,"escapeProperty");function Hae(e,t,r){let i=Object.entries(t).map(([n,o])=>`${n}=${qae(o)}`).join(";");return`##vso[${e}${i?` ${i}`:""}]${rG(r)}`}s(Hae,"vsoCommand");function Yae(e){if(!e)return[];let t=e.split(/\r?\n/).filter(r=>r.trim()&&r!==e);return[e,...t].map(r=>Hae("task.setsecret",{},r))}s(Yae,"setSecretLines");function iG(e,t=Jae){for(let r of Yae(e))t(r)}s(iG,"azureSetSecret");function vA(e){return e.replace(/\/+$/,"")}s(vA,"withoutTrailingSlash");function zR(e){let t=new URL(e),r=t.pathname.split("/").filter(Boolean);if(r.length)return decodeURIComponent(r[r.length-1]);if(t.hostname.endsWith(".visualstudio.com"))return t.hostname.split(".")[0];throw new Error(`SYSTEM_COLLECTIONURI "${e}" names no organization`)}s(zR,"azureOrganization");var Wae=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,48}[A-Za-z0-9])?$/,Zae=/[\\/:*?"<>|;#${},+=[\]%\p{Cc}\p{Cf}]/u;function oG(e){return e.length>0&&e.length<=64&&e===e.trim()&&!Zae.test(e)&&!/[^\S ]/u.test(e)&&!/^[._]/.test(e)&&!e.endsWith(".")}s(oG,"isName");function Dm(e){return JR(`${e.namespace}/${e.name}`)}s(Dm,"azureRepositoryOfSource");function JR(e){let t=e.indexOf("/"),r=e.lastIndexOf("/"),i=e.slice(0,t),n=e.slice(t+1,r),o=e.slice(r+1);if(t<0||t===r||!Wae.test(i)||!oG(n)||!oG(o))throw new Error(`"${e}" is not an Azure DevOps organization/project/repository`);return{organization:i,project:n,name:o}}s(JR,"azureRepositoryOf");function sG(e,t){let r=zR(e);if(r.toLowerCase()!==t.organization.toLowerCase())throw new Error(`${t.organization}/${t.project}/${t.name} is not in ${r}, the Azure DevOps organization this job runs in`)}s(sG,"inOrganization");function aG(e,t){return sG(e,t),`${vA(e)}/${encodeURIComponent(t.project)}/_git/${encodeURIComponent(t.name)}`}s(aG,"azureCloneUrl");function qR(e,t){return sG(e,t),`${vA(e)}/${encodeURIComponent(t.project)}/_apis/git/repositories/${encodeURIComponent(t.name)}`}s(qR,"azureRepositoryApi");var Kae="7.1",CA=class extends Error{constructor(r,i){super(r);this.status=i}status;static{s(this,"AzureRestError")}};async function HR(e){let t=e.accept??"application/json",r=new URL(e.url);r.searchParams.has("api-version")||r.searchParams.set("api-version",Kae);let i=await(e.fetch??fetch)(r.toString(),{method:e.method??"GET",headers:{Authorization:`Bearer ${e.token}`,Accept:t,...e.body!==void 0?{"Content-Type":"application/json"}:{}},...e.body!==void 0?{body:JSON.stringify(e.body)}:{},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!i.ok){let n=(await i.json().catch(()=>({}))).message;throw new CA(`Azure DevOps answered ${i.status}${typeof n=="string"?`: ${n}`:""}`,i.status)}return t!=="application/json"?Buffer.from(await i.arrayBuffer()):i.status===204?{}:await i.json()}s(HR,"azureRest");function Xae(e){return`AUTHORIZATION: bearer ${e}`}s(Xae,"azureGitAuthorization");function cG(e,t){return{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${vA(e)}/.extraheader`,GIT_CONFIG_VALUE_0:Xae(t)}}s(cG,"azureGitAuthEnv");var ece="7.1-preview.1",tce=".azure-pipelines/skyramp-testbot-v3.yml";function YR(e){return e.GITHUB_ACTIONS!=="true"&&/^true$/i.test(e.TF_BUILD??"")}s(YR,"isAzurePipelines");function dG(e,t={}){let r=s(p=>{let g=e[p];if(!g)throw new Error(`${p} is not set; the V3 runner handshake needs it`);return g},"read"),i=vA(e.SYSTEM_COLLECTIONURI??""),n=s(()=>zR(r("SYSTEM_COLLECTIONURI")),"organization"),o=e.SYSTEM_TEAMPROJECT,a=e.BUILD_REPOSITORY_NAME,c=e.BUILD_REPOSITORY_ID?.toLowerCase(),u=e.SYSTEM_ACCESSTOKEN,l=t.mask??(p=>iG(p)),A=s(p=>async()=>{if(!p)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_OIDCREQUESTURI to $(System.OidcRequestUri).");if(!u)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_ACCESSTOKEN to $(System.AccessToken).");let g=new URL(p);if(g.protocol!=="https:")throw new Error("SYSTEM_OIDCREQUESTURI is not an https URL");g.searchParams.set("api-version",ece);let h=await(t.fetch??fetch)(g.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"Content-Type":"application/json",Accept:"application/json"},body:"{}",redirect:"error",signal:AbortSignal.timeout(3e4)});if(!h.ok)throw new Error(`Azure DevOps refused the OIDC token request: ${h.status}`);let y=(await h.json().catch(()=>({}))).oidcToken;if(typeof y!="string"||!y)throw new Error("Azure DevOps's OIDC token response carried no token");return l(y),y},"mint");return{runnerPlatform:YR(e)?"azure":void 0,workspace:e.BUILD_SOURCESDIRECTORY||void 0,serverUrl:i,apiUrl:i,repository:c&&o&&a&&i?{id:c,slug:`${n()}/${o}/${a}`}:void 0,runId:e.BUILD_BUILDID||void 0,runAttempt:e.SYSTEM_STAGEATTEMPT||void 0,job:e.SYSTEM_JOBNAME||void 0,execution(){let p=r("SYSTEM_STAGEATTEMPT");if(!/^[1-9][0-9]*$/.test(p))throw new Error(`SYSTEM_STAGEATTEMPT is "${p}", not a positive whole number`);let g=r("SYSTEM_COLLECTIONID").toLowerCase();if(!Cc.test(g))throw new Error(`SYSTEM_COLLECTIONID is "${g}", not a GUID`);let h=r("BUILD_REPOSITORY_ID").toLowerCase();if(!Cc.test(h))throw new Error(`BUILD_REPOSITORY_ID is "${h}", not a GUID`);let y=[n(),r("SYSTEM_TEAMPROJECT"),r("SYSTEM_DEFINITIONID"),r("BUILD_BUILDID")].map(encodeURIComponent).join("/");return{provider:"azure-devops",repository:{provider:"azure-devops",providerAccountId:g,providerRepositoryId:h},providerRunId:y,providerRunAttempt:Number(p),workflowRef:`${tce}@${r("BUILD_SOURCEBRANCH")}`}},takeIdToken(){let p=e.SYSTEM_OIDCREQUESTURI;delete e.SYSTEM_OIDCREQUESTURI;let g=A(p);return()=>g()},takeSourceToken(){return delete e.SYSTEM_ACCESSTOKEN,u||void 0},webIdentity(){if(!e.SYSTEM_OIDCREQUESTURI?.trim()||!u)return;let p=A(e.SYSTEM_OIDCREQUESTURI);return{token:s(()=>p(),"token"),runId:e.BUILD_BUILDID}},v3RunsOnly:!0,assumesBedrockRole:!0,namesSourceToMcp:!0,runSettingsFromApp:!0,checkSourceName(p){Dm(p)},cloneUrl(p){return aG(i,Dm(p))},gitAuthEnv(p){return cG(i,p)},async pullRequest(p,g,h){let y=await HR({token:await h.token(),url:`${qR(i,Dm(p))}/pullrequests/${g}`,fetch:h.fetch}),E=y.status==="completed";return{...typeof y.title=="string"?{title:y.title}:{},...typeof y.description=="string"?{body:y.description}:{},...typeof y.status=="string"?{merged:E}:{},...E&&typeof y.lastMergeCommit?.commitId=="string"?{mergeCommit:y.lastMergeCommit.commitId}:{},...E&&typeof y.lastMergeSourceCommit?.commitId=="string"?{mergedHead:y.lastMergeSourceCommit.commitId}:{}}},async commit(p,g,h){let y;try{y=qR(i,JR(p))}catch{return{lookup:"unknown"}}try{let E=await HR({token:await h.token(),url:`${y}/commits/${encodeURIComponent(g)}`,fetch:h.fetch});return typeof E.commitId=="string"?{sha:E.commitId}:{lookup:"missing"}}catch(E){return{lookup:E instanceof CA&&(E.status===404||E.status===400)?"missing":"unknown"}}}}}s(dG,"azureRunnerHost");sc();var nce=5e3,WR=/^(?!\.\.?$)[A-Za-z0-9._-]{1,100}$/;function rce(e){let t=Buffer.from(`x-access-token:${e}`).toString("base64");return Dl(t),`AUTHORIZATION: basic ${t}`}s(rce,"githubGitAuthorization");function AG(e,t={}){let r=s(u=>{let l=e[u];if(!l)throw new Error(`${u} is not set; the V3 runner handshake needs it`);return l},"read"),i=e.GITHUB_REPOSITORY_ID,n=e.GITHUB_REPOSITORY,o=(e.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,""),a=(e.GITHUB_API_URL||"https://api.github.com").replace(/\/+$/,""),c=s(async(u,l)=>l.fetch(u,{headers:{Authorization:`Bearer ${await l.token()}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(3e4)}),"get");return{runnerPlatform:e.GITHUB_ACTIONS==="true"?"github":void 0,workspace:e.GITHUB_WORKSPACE||void 0,serverUrl:o,apiUrl:a,repository:i&&n?{id:i,slug:n}:void 0,runId:e.GITHUB_RUN_ID||void 0,runAttempt:e.GITHUB_RUN_ATTEMPT||void 0,job:e.GITHUB_JOB||void 0,execution(){let u=r("GITHUB_RUN_ATTEMPT");if(!/^[1-9][0-9]*$/.test(u))throw new Error(`GITHUB_RUN_ATTEMPT is "${u}", not a positive whole number`);return{provider:"github",repository:{provider:"github",providerAccountId:r("GITHUB_REPOSITORY_OWNER_ID"),providerRepositoryId:r("GITHUB_REPOSITORY_ID")},providerRunId:r("GITHUB_RUN_ID"),providerRunAttempt:Number(u),workflowRef:r("GITHUB_WORKFLOW_REF")}},takeIdToken(){let u=e.ACTIONS_ID_TOKEN_REQUEST_URL,l=e.ACTIONS_ID_TOKEN_REQUEST_TOKEN;return delete e.ACTIONS_ID_TOKEN_REQUEST_URL,delete e.ACTIONS_ID_TOKEN_REQUEST_TOKEN,async A=>{if(!u||!l)throw new Error("The job cannot request an OIDC token. Give it the `id-token: write` permission.");let p=new URL(u);p.searchParams.set("audience",A);let g=await fetch(p,{headers:{Authorization:`Bearer ${l}`,Accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!g.ok)throw new Error(`GitHub refused the OIDC token request: ${g.status}`);let h=(await g.json().catch(()=>({}))).value;if(typeof h!="string"||!h)throw new Error("GitHub's OIDC token response carried no token");return Dl(h),h}},webIdentity(){return!e.ACTIONS_ID_TOKEN_REQUEST_TOKEN?.trim()||!e.ACTIONS_ID_TOKEN_REQUEST_URL?.trim()?void 0:{token:t.getIDToken??(l=>KF(l)),runId:e.GITHUB_RUN_ID}},v3RunsOnly:!1,assumesBedrockRole:!1,namesSourceToMcp:!1,runSettingsFromApp:!1,checkSourceName(u){for(let l of[u.namespace,u.name])if(!WR.test(l))throw new Error(`"${l}" is not a repository name`)},cloneUrl(u){return`${o}/${u.namespace}/${u.name}.git`},gitAuthEnv(u){return u?{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${o}/.extraheader`,GIT_CONFIG_VALUE_0:rce(u)}:{}},async pullRequest({namespace:u,name:l},A,p){if(![u,l].every(y=>WR.test(y)))throw new Error("the repository name is not valid");let g=await c(`${a}/repos/${u}/${l}/pulls/${A}`,p);if(!g.ok)throw new Error(`GitHub answered ${g.status}`);let h=await g.json();return{...typeof h.title=="string"?{title:h.title}:{},...typeof h.body=="string"?{body:h.body}:{},...typeof h.merged=="boolean"?{merged:h.merged}:{},...h.merged===!0&&typeof h.merge_commit_sha=="string"?{mergeCommit:h.merge_commit_sha}:{},...h.merged===!0&&typeof h.head?.sha=="string"?{mergedHead:h.head.sha}:{}}},async commit(u,l,A){let[p,g,...h]=u.split("/");if(h.length||![p,g].every(y=>y!==void 0&&WR.test(y)))return{lookup:"unknown"};try{let y=await c(`${a}/repos/${p}/${g}/commits/${encodeURIComponent(l)}`,A);if(y.status===404||y.status===422)return{lookup:"missing"};if(!y.ok)return{lookup:"unknown"};let E=await y.json();return typeof E.sha=="string"?{sha:E.sha}:{lookup:"missing"}}catch{return{lookup:"unknown"}}},async revokeToken(u,l){let A=await l(`${a}/installation/token`,{method:"DELETE",headers:{Authorization:`Bearer ${u}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(nce)});if(!A.ok&&A.status!==401)throw new Error(`GitHub answered ${A.status}`)}}}s(AG,"githubRunnerHost");function pG(e=process.env){return YR(e)?dG(e):AG(e)}s(pG,"runnerHost");var MDe=Buffer.from("302a300506032b656e032100","hex");var ice=10*6e4;function oce(e,t){return e.getTime()-t.getTime()-ice}s(oce,"remainingBudgetMs");var fG="This attempt revoked its scoped GitHub credentials; it mints no more.",sce=10*6e4;var ace=s(e=>!!e&&Object.keys(e).length===1&&e.contents==="read","onlyReads"),cce=3e4,uce=3,gG=30,Rr=class extends Error{constructor(r,i,n,o){super(r);this.status=i;this.code=n;this.path=o}status;code;path;static{s(this,"AppRefusal")}},ni=class extends Error{static{s(this,"AppUnreachable")}},vu=class extends ni{static{s(this,"AppNotReady")}},ZR=class extends vu{static{s(this,"RunnerProviderNotReady")}};function KR(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}s(KR,"appOrigin");function hG(e,t){if(!Cc.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}s(hG,"routeId");function lce(e,t){return`${e.replace(/\/+$/,"")}/runs/${t}`}s(lce,"skyrampRunPageUrl");function mG(e,t,r,i){throw t<500&&t!==429?new Rr(e,t,r,i):t===503&&r==="RUNNER_PROVIDER_NOT_READY"?new ZR(e):t===503&&r==="RUN_NOT_READY"?new vu(e):new ni(e)}s(mG,"refusedOrUnreachable");async function yG(e,t,r,i,n,o=1/0){let a=KR(e.origin),c=`The time limit for ${t} ${r} was reached`,u,l=0;for(let A=1;A<=uce||u instanceof vu;A+=1){if(u instanceof vu){if(l===gG)throw u;l+=1,A-=1,e.log?.(`${u.message}; trying again (${l} of ${gG}).`),await new Promise(p=>setTimeout(p,Math.max(0,Math.min(e.readyWaitMs??1e4,o-Date.now()))))}else A>1&&await new Promise(p=>setTimeout(p,Math.max(0,Math.min((e.retryDelayMs??2e3)*(A-1),o-Date.now()))));if(Date.now()>=o)throw new ni(c);try{let p,g=await(Number.isFinite(o)?Promise.race([e.idToken(a),new Promise((y,E)=>{p=setTimeout(()=>E(new ni(c)),Math.max(1,o-Date.now()))})]).finally(()=>{p&&clearTimeout(p)}):e.idToken(a));if(Date.now()>=o)throw new ni(c);let h=await(e.fetch??fetch)(new URL(r,a).toString(),{...i(g),redirect:"error",signal:AbortSignal.timeout(Math.max(1,Math.min(cce,o-Date.now())))}).catch(y=>{throw new ni(y instanceof Error?y.message:String(y),{cause:y})});return await n(h)}catch(p){if(p instanceof Rr||Date.now()>=o)throw p;u=p}}throw u}s(yG,"callWithRetries");function EG(e,t,r,i,n){let o=i.headers.get("cf-ray");e.log?.(`Testbot V3: ${t} ${r} answered ${i.status}${o?`, cf-ray ${o}`:""}: ${n.replace(/\s+/g," ").slice(0,200)}`)}s(EG,"logRefusal");function _m(e,t,r,i,n){return yG(e,t,r,s(a=>({method:t,headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json",Accept:"application/json"},body:t==="GET"?void 0:JSON.stringify(i)}),"request"),async a=>{let c=await a.text().catch(()=>""),u={};try{u=JSON.parse(c)}catch{}if(a.ok)return u.data;EG(e,t,r,a,c);let l=u.error?.fields,A=typeof l?.path=="string"&&typeof l.reason=="string"?` at ${l.path}: ${l.reason}`:"",p=`The Skyramp app refused ${t} ${r}: ${a.status} ${u.error?.code??"no error code"}${A}`;return mG(p,a.status,u.error?.code,typeof l?.path=="string"?l.path:void 0)},n)}s(_m,"callApp");function dce(e,t,r){return yG(e,"GET",t,s(n=>({method:"GET",headers:{Authorization:`Bearer ${n}`,Accept:"application/octet-stream"}}),"request"),async n=>{if(!n.ok)return EG(e,"GET",t,n,await n.text().catch(()=>"")),mG(`The Skyramp app refused GET ${t}: ${n.status}`,n.status);let o=Buffer.from(await n.arrayBuffer());if(o.length>r)throw new Rr(`The Skyramp app answered GET ${t} with more than ${r} bytes`,n.status);return o})}s(dce,"callAppBytes");var bA=class{constructor(t,r,i,n,o,a,c,u,l,A=[],p=[],g,h=!1){this.attemptId=t;this.attemptNumber=r;this.deadlineAt=i;this.manifest=n;this.deps=o;this.license=a;this.requestedBy=c;this.writeAllowed=u;this.claudeCodeVersion=l;this.deployedPins=A;this.statedPins=p;this.runSettings=g;this.credentialRelay=h}attemptId;attemptNumber;deadlineAt;manifest;deps;license;requestedBy;writeAllowed;claudeCodeVersion;deployedPins;statedPins;runSettings;credentialRelay;static{s(this,"V3Attempt")}budgetMs(t){return oce(this.deadlineAt,t)}get skyrampRunUrl(){return lce(KR(this.deps.origin),this.manifest.runId)}send(t,r,i,n){return _m(this.deps,t,r,i,n)}readBytes(t,r){return dce(this.deps,t,r)}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(fG);let r=(this.deps.now??(()=>new Date))().getTime(),i=this.credentials[t],n=i&&await i.catch(()=>{});if(this.credentials[t]!==i)return(await this.credentials[t]).token;if(n&&n.expiresAt-r>=sce)return n.token;if(this.revocation)throw new Error(fG);let o=t==="read",a=o?{schemaVersion:1,access:t}:{schemaVersion:1},c=o?"read-only":"scoped",u=this.send("POST",`/api/v1/runner/attempts/${this.attemptId}/credentials`,a).then(l=>{let A={...l,token:l.token??this.jobToken()};if(this.issuedTokens.push(A.token),this.deps.mask?.(A.token),A.anthropicApiKey&&this.deps.mask?.(A.anthropicApiKey),o&&l.token&&!ace(A.permissions))throw new Error(`The Skyramp app was asked for a read-only GitHub token, but its token grants ${JSON.stringify(A.permissions??null)}`);!o&&!n&&A.anthropicApiKey&&(this.modelKey=A.anthropicApiKey),this.deps.onTokenGranted?.(t);let p=n?"Renewed":"Received";return l.token&&this.deps.log?.(`${p} ${c} GitHub credentials; they expire at ${A.expiresAt}.`),{token:A.token,expiresAt:l.token?new Date(A.expiresAt).getTime():Number.POSITIVE_INFINITY}},l=>{if(this.deps.onTokenRefused?.(l,t),!(l instanceof Rr)||l.code!=="CREDENTIALS_UNAVAILABLE")throw l;let A=s(h=>[...new Set(h.map(y=>y.namespace))].join(", "),"unique"),p=this.manifest.sources.map(h=>h.repository);if(new Set(p.map(h=>h.providerAccountId)).size>1)throw new Rr(`${l.message}. The run's repositories are on more than one GitHub account (${A(p)}), which Skyramp does not support yet.`,l.status,l.code);let g=A([...p,this.manifest.execution.repository]);throw new Rr(`${l.message}. Check the Skyramp GitHub App installation on ${g}: 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 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 r=t.host??pG();return this.revocation??=r.revokeToken?this.revokeIssued(i=>r.revokeToken(i,this.sourceFetch(t))):Promise.resolve([]),this.revocation}async revokeIssued(t){let r=[...this.issuedTokens],i=Promise.all(r.map(a=>this.revokeOne(a,t)));await Promise.all(Object.values(this.credentials).map(a=>a.catch(()=>{})));let n=this.issuedTokens.filter(a=>!r.includes(a));return[...await i,...await Promise.all(n.map(a=>this.revokeOne(a,t)))].filter(a=>a!==void 0)}async revokeOne(t,r){try{await r(t);return}catch(i){return`token ${this.issuedTokens.indexOf(t)+1} of ${this.issuedTokens.length}: ${i instanceof Error?i.message:String(i)}`}}};async function IG(e,t,r){hG(e,"run id"),KR(r.origin);let i=HC(e,t),n=`/api/v1/runner/runs/${e}/attempts`,o;try{o=await _m(r,"POST",n,i)}catch(l){if(!(l instanceof Rr&&l.status===400&&l.path==="$.statedPins"))throw l;i=HC(e,t,{statedPins:!1}),o=await _m(r,"POST",n,i)}let a=CP(o);if(a.manifest.runId!==e)throw new Error(`The app answered the handshake of run ${e} with the manifest of another run (${a.manifest.runId})`);let c=a.manifest.sources.find(l=>l.repository.provider!==i.execution.provider);if(c)throw new Error(`The manifest of run ${e} names ${c.repository.namespace}/${c.repository.name} on ${c.repository.provider}, but this job runs on ${i.execution.provider}`);Ace(a.manifest,[...a.deployedRevisions??[],...a.statedRevisions??[]]),a.runToken&&r.mask?.(a.runToken);let u=a.runToken?{entitlements:a.entitlements??[],runToken:a.runToken}:void 0;return new bA(a.attempt.id,a.attempt.number,new Date(a.attempt.deadlineAt),a.manifest,r,u,a.requestedBy??void 0,a.writeAllowed,a.claudeCodeVersion??void 0,a.deployedRevisions??[],a.statedRevisions??[],a.runSettings,a.credentialRelay===!0)}s(IG,"startV3Attempt");function Ace(e,t){if(t.length===0)return;if(!sP(e))throw new Error(`The 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 r=new Set(e.sources.map(n=>qr(n.repository))),i=new Set;for(let n of t){let o=qr(n.repository);if(!r.has(o))throw new Error(`The app pinned the attempt to repository ${n.repository.providerRepositoryId}, which is not a source of the run`);if(i.has(o))throw new Error(`The app pinned repository ${n.repository.providerRepositoryId} twice`);i.add(o)}}s(Ace,"checkAttemptPins");async function XR(e,t){return mP.parse(await e.send("POST",`/api/v1/runner/attempts/${e.attemptId}/heartbeat`,{schemaVersion:1},t))}s(XR,"heartbeatV3Attempt");async function CG(e,t=()=>new Date,r){if(e.closure)return e.closure;let i=await XR(e,r).then(n=>yP(n,t())).catch(()=>null);return i&&(e.closure=i),i}s(CG,"closedV3Attempt");var B_e=10*6e4;var Q_e=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var k_e=d.object({tests:d.object({placements:d.array(d.unknown()).optional()}).passthrough().optional()}).passthrough(),S_e=d.object({repository:zC,testType:d.string(),directory:d.string()}).passthrough();var R_e=d.object({report:d.object({language:d.string()}).passthrough()}).passthrough();var x_e=d.object({environment:d.object({components:d.array(d.unknown()).optional(),dependencies:d.array(d.unknown()).optional()}).passthrough()}).passthrough(),$_e=d.object({environment:d.object({offLimits:d.unknown().optional()}).passthrough()}).passthrough();var T_e=d.object({name:d.string().min(1),provision:d.literal("existing"),url:d.string().min(1),repository:zC.optional(),revisionUrl:d.string().min(1).optional()}).passthrough(),D_e=d.object({name:d.string().min(1),url:d.string().nullable(),versionUrl:d.string().nullable(),notes:d.string().nullable()}).passthrough();var __e=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);function vG(e){let t=s(r=>e.testResults.filter(i=>i.status===r).length,"count");return{passed:t("Pass"),failed:t("Fail"),skipped:t("Skipped")}}s(vG,"statusCounts");function pce(e){let{passed:t,failed:r,skipped:i}=vG(e);return t+r===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+r} tests ran against the frozen sources: ${t} passed, ${r} failed${i?`, ${i} skipped`:""}.`,gaps:[],acceptedEvidence:[],actionRequired:[]}}s(pce,"executedTestsValidation");function fce(e,t){let r=e.map(c=>({result:c,repository:c.repository??t,path:c.fileName||c.testType})),i=new Map;for(let c of r){let u=`${c.repository}:${c.result.testType}:${c.path}`;i.set(u,(i.get(u)??0)+1)}let n=r.map(({result:c,repository:u,path:l})=>{let A=(i.get(`${u}:${c.testType}:${l}`)??0)>1;return c.resultId??qC(u,c.testType,l,A&&c.endpoint||void 0)}),o=new Map;for(let c of n)o.set(c,(o.get(c)??0)+1);let a=new Set(n.filter(c=>o.get(c)===1));return r.map(({result:c,repository:u},l)=>{let A=n[l],p=A;if(o.get(A)>1&&a.has(A))for(let g=2;a.has(p)||p===A;g+=1)p=A.includes("#")?`${A}.${g}`:`${A}#${g}`;return a.add(p),{...c,repository:u,resultId:p}})}s(fce,"withResultIds");function gce({notTranslated:e,...t},r){let i=fce(t.testResults,r);return{...t,testResults:i,...hce(t,i,r),validation:Ece(t,mce(t,t.validation??pce(t))),traceVersion:1}}s(gce,"v3Report");function hce(e,t,r){if(!e.testExecutionContexts)return{};let i=new Set,n=s(c=>{let u=c;for(let l=2;i.has(u);l+=1)u=`${c}#${l}`;return i.add(u),u},"unique"),o=[],a=new Map;for(let{repository:c,...u}of e.testExecutionContexts){let l=u.status==="not_run"?[]:t.filter(A=>A.fileName===u.test&&A.repository===(c?.trim()||r));l.length||o.push(u);for(let{resultId:A}of l){let p=a.get(A),g=p!==void 0&&o[p].cleanup.status==="failed"?o[p].cleanup:u.cleanup,h={...u,cleanup:g,test:A,resultId:A};p===void 0?a.set(A,o.push(h)-1):o[p]=h}}for(let c of o)c.resultId&&i.add(c.resultId);return{testExecutionContexts:o.map(c=>c.resultId?c:{...c,test:n(c.test.slice(0,512))}).slice(0,5e3)}}s(hce,"linkedContexts");function mce(e,t){let{passed:r,failed:i}=vG(e);return t.sufficiency!=="sufficient"||r+i>0||t.acceptedEvidence.length>0?t:{...t,sufficiency:"insufficient",gaps:["No test ran and no existing evidence was accepted, so nothing was validated."]}}s(mce,"withEvidence");var yce={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};function Ece(e,t){if(t.sufficiency==="sufficient")return t;let r=(e.caveats??[]).map(n=>yce[n.kind]).filter(n=>n!==void 0),i=[...new Set(r)].filter(n=>!t.actionRequired.includes(n));return i.length?{...t,actionRequired:[...i,...t.actionRequired]}:t}s(Ece,"withModelProviderFailure");function Ice(e,t,r){let{language:i,report:n}=t;if(i==="en")return;let o={language:i,businessCaseAnalysis:n.businessCaseAnalysis},a=s((y,E,C)=>Array.isArray(y)&&Array.isArray(E)&&y.length===E.length?y.map(I=>({[C]:I[C]})):void 0,"rows"),c=e.validation;n.validation&&c&&c.rationale===r.validation.rationale&&JSON.stringify(c.gaps)===JSON.stringify(r.validation.gaps)&&n.validation.gaps.length===r.validation.gaps.length&&(o.validation={rationale:n.validation.rationale,gaps:[...n.validation.gaps]});let u=new Set((r.changes??[]).map(y=>y.id)),l=(n.changes??[]).filter(y=>u.has(y.id)).map(({id:y,text:E})=>({id:y,text:E}));l.length&&(o.changes=l);let A=a(n.issuesFound,r.issuesFound,"description");A&&(o.issuesFound=A);let p=a(n.newTestsCreated,r.newTestsCreated,"description");p&&(o.newTestsCreated=p);let g=a(n.testResults,r.testResults,"details");g&&(o.testResults=g);let h=a(n.caveats,r.caveats,"text");return h&&(o.caveats=h),o}s(Ice,"v3Display");async function bG(e,t){let r=wC([...e.issuedTokens,...t.secrets??[]]),i={...gce(t.report,t.workingSlug),...t.notTranslated?{notTranslated:t.notTranslated}:{}},n=t.translated&&Ice(t.report,t.translated,i),o=s(c=>vP({manifest:e.manifest,attemptNumber:e.attemptNumber,checkedOut:t.sources.map(u=>({repository:u.repository,revision:u.revision})),firstQualification:t.firstQualification,generatedTests:ac(t.delivery,r),producer:t.producer,report:ac(c&&n?{...i,display:n}:i,r),githubWrites:t.githubWrites}),"build"),a=o(!0);n&&Buffer.byteLength(JSON.stringify(a),"utf8")>XM&&(a=o(!1)),await e.send("PUT",`/api/v1/runner/attempts/${e.attemptId}/report`,a)}s(bG,"uploadV3Report");async function wG(e,t){return hG(e.attemptId,"attempt id"),_m(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,bP({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"}))}s(wG,"endV3Attempt");0&&(module.exports={AppRefusal,AppUnreachable,AttemptEndReason,DeliveryStatus,GitHubWriteKind,NoReportCause,SourceProvider,V3Attempt,ValidationSufficiency,closedV3Attempt,endV3Attempt,heartbeatV3Attempt,startV3Attempt,uploadV3Report});
|
|
194
|
+
`:e.text??"")}s(zae,"writeFrame");function Jae(e){zae({command:e})}s(Jae,"writeAzureCommand");function rG(e){return e.replace(/%/g,"%AZP25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}s(rG,"escapeData");function qae(e){return rG(e).replace(/;/g,"%3B").replace(/]/g,"%5D")}s(qae,"escapeProperty");function Hae(e,t,r){let i=Object.entries(t).map(([n,o])=>`${n}=${qae(o)}`).join(";");return`##vso[${e}${i?` ${i}`:""}]${rG(r)}`}s(Hae,"vsoCommand");function Yae(e){if(!e)return[];let t=e.split(/\r?\n/).filter(r=>r.trim()&&r!==e);return[e,...t].map(r=>Hae("task.setsecret",{},r))}s(Yae,"setSecretLines");function iG(e,t=Jae){for(let r of Yae(e))t(r)}s(iG,"azureSetSecret");function vA(e){return e.replace(/\/+$/,"")}s(vA,"withoutTrailingSlash");function zR(e){let t=new URL(e),r=t.pathname.split("/").filter(Boolean);if(r.length)return decodeURIComponent(r[r.length-1]);if(t.hostname.endsWith(".visualstudio.com"))return t.hostname.split(".")[0];throw new Error(`SYSTEM_COLLECTIONURI "${e}" names no organization`)}s(zR,"azureOrganization");var Wae=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,48}[A-Za-z0-9])?$/,Zae=/[\\/:*?"<>|;#${},+=[\]%\p{Cc}\p{Cf}]/u;function oG(e){return e.length>0&&e.length<=64&&e===e.trim()&&!Zae.test(e)&&!/[^\S ]/u.test(e)&&!/^[._]/.test(e)&&!e.endsWith(".")}s(oG,"isName");function Dm(e){return JR(`${e.namespace}/${e.name}`)}s(Dm,"azureRepositoryOfSource");function JR(e){let t=e.indexOf("/"),r=e.lastIndexOf("/"),i=e.slice(0,t),n=e.slice(t+1,r),o=e.slice(r+1);if(t<0||t===r||!Wae.test(i)||!oG(n)||!oG(o))throw new Error(`"${e}" is not an Azure DevOps organization/project/repository`);return{organization:i,project:n,name:o}}s(JR,"azureRepositoryOf");function sG(e,t){let r=zR(e);if(r.toLowerCase()!==t.organization.toLowerCase())throw new Error(`${t.organization}/${t.project}/${t.name} is not in ${r}, the Azure DevOps organization this job runs in`)}s(sG,"inOrganization");function aG(e,t){return sG(e,t),`${vA(e)}/${encodeURIComponent(t.project)}/_git/${encodeURIComponent(t.name)}`}s(aG,"azureCloneUrl");function qR(e,t){return sG(e,t),`${vA(e)}/${encodeURIComponent(t.project)}/_apis/git/repositories/${encodeURIComponent(t.name)}`}s(qR,"azureRepositoryApi");var Kae="7.1",CA=class extends Error{constructor(r,i){super(r);this.status=i}status;static{s(this,"AzureRestError")}};async function HR(e){let t=e.accept??"application/json",r=new URL(e.url);r.searchParams.has("api-version")||r.searchParams.set("api-version",Kae);let i=await(e.fetch??fetch)(r.toString(),{method:e.method??"GET",headers:{Authorization:`Bearer ${e.token}`,Accept:t,...e.body!==void 0?{"Content-Type":"application/json"}:{}},...e.body!==void 0?{body:JSON.stringify(e.body)}:{},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!i.ok){let n=(await i.json().catch(()=>({}))).message;throw new CA(`Azure DevOps answered ${i.status}${typeof n=="string"?`: ${n}`:""}`,i.status)}return t!=="application/json"?Buffer.from(await i.arrayBuffer()):i.status===204?{}:await i.json()}s(HR,"azureRest");function Xae(e){return`AUTHORIZATION: bearer ${e}`}s(Xae,"azureGitAuthorization");function cG(e,t){return{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${vA(e)}/.extraheader`,GIT_CONFIG_VALUE_0:Xae(t)}}s(cG,"azureGitAuthEnv");var ece="7.1-preview.1",tce=".azure-pipelines/skyramp-testbot-v3.yml";function YR(e){return e.GITHUB_ACTIONS!=="true"&&/^true$/i.test(e.TF_BUILD??"")}s(YR,"isAzurePipelines");function dG(e,t={}){let r=s(p=>{let g=e[p];if(!g)throw new Error(`${p} is not set; the V3 runner handshake needs it`);return g},"read"),i=vA(e.SYSTEM_COLLECTIONURI??""),n=s(()=>zR(r("SYSTEM_COLLECTIONURI")),"organization"),o=e.SYSTEM_TEAMPROJECT,a=e.BUILD_REPOSITORY_NAME,c=e.BUILD_REPOSITORY_ID?.toLowerCase(),u=e.SYSTEM_ACCESSTOKEN,l=t.mask??(p=>iG(p)),A=s(p=>async()=>{if(!p)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_OIDCREQUESTURI to $(System.OidcRequestUri).");if(!u)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_ACCESSTOKEN to $(System.AccessToken).");let g=new URL(p);if(g.protocol!=="https:")throw new Error("SYSTEM_OIDCREQUESTURI is not an https URL");g.searchParams.set("api-version",ece);let h=await(t.fetch??fetch)(g.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"Content-Type":"application/json",Accept:"application/json"},body:"{}",redirect:"error",signal:AbortSignal.timeout(3e4)});if(!h.ok)throw new Error(`Azure DevOps refused the OIDC token request: ${h.status}`);let y=(await h.json().catch(()=>({}))).oidcToken;if(typeof y!="string"||!y)throw new Error("Azure DevOps's OIDC token response carried no token");return l(y),y},"mint");return{runnerPlatform:YR(e)?"azure":void 0,workspace:e.BUILD_SOURCESDIRECTORY||void 0,serverUrl:i,apiUrl:i,repository:c&&o&&a&&i?{id:c,slug:`${n()}/${o}/${a}`}:void 0,runId:e.BUILD_BUILDID||void 0,runAttempt:e.SYSTEM_STAGEATTEMPT||void 0,job:e.SYSTEM_JOBNAME||void 0,execution(){let p=r("SYSTEM_STAGEATTEMPT");if(!/^[1-9][0-9]*$/.test(p))throw new Error(`SYSTEM_STAGEATTEMPT is "${p}", not a positive whole number`);let g=r("SYSTEM_COLLECTIONID").toLowerCase();if(!Cc.test(g))throw new Error(`SYSTEM_COLLECTIONID is "${g}", not a GUID`);let h=r("BUILD_REPOSITORY_ID").toLowerCase();if(!Cc.test(h))throw new Error(`BUILD_REPOSITORY_ID is "${h}", not a GUID`);let y=[n(),r("SYSTEM_TEAMPROJECT"),r("SYSTEM_DEFINITIONID"),r("BUILD_BUILDID")].map(encodeURIComponent).join("/");return{provider:"azure-devops",repository:{provider:"azure-devops",providerAccountId:g,providerRepositoryId:h},providerRunId:y,providerRunAttempt:Number(p),workflowRef:`${tce}@${r("BUILD_SOURCEBRANCH")}`}},takeIdToken(){let p=e.SYSTEM_OIDCREQUESTURI;delete e.SYSTEM_OIDCREQUESTURI;let g=A(p);return()=>g()},takeSourceToken(){return delete e.SYSTEM_ACCESSTOKEN,u||void 0},webIdentity(){if(!e.SYSTEM_OIDCREQUESTURI?.trim()||!u)return;let p=A(e.SYSTEM_OIDCREQUESTURI);return{token:s(()=>p(),"token"),runId:e.BUILD_BUILDID}},v3RunsOnly:!0,assumesBedrockRole:!0,namesSourceToMcp:!0,runSettingsFromApp:!0,checkSourceName(p){Dm(p)},cloneUrl(p){return aG(i,Dm(p))},gitAuthEnv(p){return cG(i,p)},async pullRequest(p,g,h){let y=await HR({token:await h.token(),url:`${qR(i,Dm(p))}/pullrequests/${g}`,fetch:h.fetch}),E=y.status==="completed";return{...typeof y.title=="string"?{title:y.title}:{},...typeof y.description=="string"?{body:y.description}:{},...typeof y.status=="string"?{merged:E}:{},...E&&typeof y.lastMergeCommit?.commitId=="string"?{mergeCommit:y.lastMergeCommit.commitId}:{},...E&&typeof y.lastMergeSourceCommit?.commitId=="string"?{mergedHead:y.lastMergeSourceCommit.commitId}:{}}},async commit(p,g,h){let y;try{y=qR(i,JR(p))}catch{return{lookup:"unknown"}}try{let E=await HR({token:await h.token(),url:`${y}/commits/${encodeURIComponent(g)}`,fetch:h.fetch});return typeof E.commitId=="string"?{sha:E.commitId}:{lookup:"missing"}}catch(E){return{lookup:E instanceof CA&&(E.status===404||E.status===400)?"missing":"unknown"}}}}}s(dG,"azureRunnerHost");sc();var nce=5e3,WR=/^(?!\.\.?$)[A-Za-z0-9._-]{1,100}$/;function rce(e){let t=Buffer.from(`x-access-token:${e}`).toString("base64");return Dl(t),`AUTHORIZATION: basic ${t}`}s(rce,"githubGitAuthorization");function AG(e,t={}){let r=s(u=>{let l=e[u];if(!l)throw new Error(`${u} is not set; the V3 runner handshake needs it`);return l},"read"),i=e.GITHUB_REPOSITORY_ID,n=e.GITHUB_REPOSITORY,o=(e.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,""),a=(e.GITHUB_API_URL||"https://api.github.com").replace(/\/+$/,""),c=s(async(u,l)=>l.fetch(u,{headers:{Authorization:`Bearer ${await l.token()}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(3e4)}),"get");return{runnerPlatform:e.GITHUB_ACTIONS==="true"?"github":void 0,workspace:e.GITHUB_WORKSPACE||void 0,serverUrl:o,apiUrl:a,repository:i&&n?{id:i,slug:n}:void 0,runId:e.GITHUB_RUN_ID||void 0,runAttempt:e.GITHUB_RUN_ATTEMPT||void 0,job:e.GITHUB_JOB||void 0,execution(){let u=r("GITHUB_RUN_ATTEMPT");if(!/^[1-9][0-9]*$/.test(u))throw new Error(`GITHUB_RUN_ATTEMPT is "${u}", not a positive whole number`);return{provider:"github",repository:{provider:"github",providerAccountId:r("GITHUB_REPOSITORY_OWNER_ID"),providerRepositoryId:r("GITHUB_REPOSITORY_ID")},providerRunId:r("GITHUB_RUN_ID"),providerRunAttempt:Number(u),workflowRef:r("GITHUB_WORKFLOW_REF")}},takeIdToken(){let u=e.ACTIONS_ID_TOKEN_REQUEST_URL,l=e.ACTIONS_ID_TOKEN_REQUEST_TOKEN;return delete e.ACTIONS_ID_TOKEN_REQUEST_URL,delete e.ACTIONS_ID_TOKEN_REQUEST_TOKEN,async A=>{if(!u||!l)throw new Error("The job cannot request an OIDC token. Give it the `id-token: write` permission.");let p=new URL(u);p.searchParams.set("audience",A);let g=await fetch(p,{headers:{Authorization:`Bearer ${l}`,Accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!g.ok)throw new Error(`GitHub refused the OIDC token request: ${g.status}`);let h=(await g.json().catch(()=>({}))).value;if(typeof h!="string"||!h)throw new Error("GitHub's OIDC token response carried no token");return Dl(h),h}},webIdentity(){return!e.ACTIONS_ID_TOKEN_REQUEST_TOKEN?.trim()||!e.ACTIONS_ID_TOKEN_REQUEST_URL?.trim()?void 0:{token:t.getIDToken??(l=>KF(l)),runId:e.GITHUB_RUN_ID}},v3RunsOnly:!1,assumesBedrockRole:!1,namesSourceToMcp:!1,runSettingsFromApp:!1,checkSourceName(u){for(let l of[u.namespace,u.name])if(!WR.test(l))throw new Error(`"${l}" is not a repository name`)},cloneUrl(u){return`${o}/${u.namespace}/${u.name}.git`},gitAuthEnv(u){return u?{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${o}/.extraheader`,GIT_CONFIG_VALUE_0:rce(u)}:{}},async pullRequest({namespace:u,name:l},A,p){if(![u,l].every(y=>WR.test(y)))throw new Error("the repository name is not valid");let g=await c(`${a}/repos/${u}/${l}/pulls/${A}`,p);if(!g.ok)throw new Error(`GitHub answered ${g.status}`);let h=await g.json();return{...typeof h.title=="string"?{title:h.title}:{},...typeof h.body=="string"?{body:h.body}:{},...typeof h.merged=="boolean"?{merged:h.merged}:{},...h.merged===!0&&typeof h.merge_commit_sha=="string"?{mergeCommit:h.merge_commit_sha}:{},...h.merged===!0&&typeof h.head?.sha=="string"?{mergedHead:h.head.sha}:{}}},async commit(u,l,A){let[p,g,...h]=u.split("/");if(h.length||![p,g].every(y=>y!==void 0&&WR.test(y)))return{lookup:"unknown"};try{let y=await c(`${a}/repos/${p}/${g}/commits/${encodeURIComponent(l)}`,A);if(y.status===404||y.status===422)return{lookup:"missing"};if(!y.ok)return{lookup:"unknown"};let E=await y.json();return typeof E.sha=="string"?{sha:E.sha}:{lookup:"missing"}}catch{return{lookup:"unknown"}}},async revokeToken(u,l){let A=await l(`${a}/installation/token`,{method:"DELETE",headers:{Authorization:`Bearer ${u}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(nce)});if(!A.ok&&A.status!==401)throw new Error(`GitHub answered ${A.status}`)}}}s(AG,"githubRunnerHost");function pG(e=process.env){return YR(e)?dG(e):AG(e)}s(pG,"runnerHost");var VDe=Buffer.from("302a300506032b656e032100","hex");var ice=10*6e4;function oce(e,t){return e.getTime()-t.getTime()-ice}s(oce,"remainingBudgetMs");var fG="This attempt revoked its scoped GitHub credentials; it mints no more.",sce=10*6e4;var ace=s(e=>!!e&&Object.keys(e).length===1&&e.contents==="read","onlyReads"),cce=3e4,uce=3,gG=30,Rr=class extends Error{constructor(r,i,n,o){super(r);this.status=i;this.code=n;this.path=o}status;code;path;static{s(this,"AppRefusal")}},ni=class extends Error{static{s(this,"AppUnreachable")}},vu=class extends ni{static{s(this,"AppNotReady")}},ZR=class extends vu{static{s(this,"RunnerProviderNotReady")}};function KR(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}s(KR,"appOrigin");function hG(e,t){if(!Cc.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}s(hG,"routeId");function lce(e,t){return`${e.replace(/\/+$/,"")}/runs/${t}`}s(lce,"skyrampRunPageUrl");function mG(e,t,r,i){throw t<500&&t!==429?new Rr(e,t,r,i):t===503&&r==="RUNNER_PROVIDER_NOT_READY"?new ZR(e):t===503&&r==="RUN_NOT_READY"?new vu(e):new ni(e)}s(mG,"refusedOrUnreachable");async function yG(e,t,r,i,n,o=1/0){let a=KR(e.origin),c=`The time limit for ${t} ${r} was reached`,u,l=0;for(let A=1;A<=uce||u instanceof vu;A+=1){if(u instanceof vu){if(l===gG)throw u;l+=1,A-=1,e.log?.(`${u.message}; trying again (${l} of ${gG}).`),await new Promise(p=>setTimeout(p,Math.max(0,Math.min(e.readyWaitMs??1e4,o-Date.now()))))}else A>1&&await new Promise(p=>setTimeout(p,Math.max(0,Math.min((e.retryDelayMs??2e3)*(A-1),o-Date.now()))));if(Date.now()>=o)throw new ni(c);try{let p,g=await(Number.isFinite(o)?Promise.race([e.idToken(a),new Promise((y,E)=>{p=setTimeout(()=>E(new ni(c)),Math.max(1,o-Date.now()))})]).finally(()=>{p&&clearTimeout(p)}):e.idToken(a));if(Date.now()>=o)throw new ni(c);let h=await(e.fetch??fetch)(new URL(r,a).toString(),{...i(g),redirect:"error",signal:AbortSignal.timeout(Math.max(1,Math.min(cce,o-Date.now())))}).catch(y=>{throw new ni(y instanceof Error?y.message:String(y),{cause:y})});return await n(h)}catch(p){if(p instanceof Rr||Date.now()>=o)throw p;u=p}}throw u}s(yG,"callWithRetries");function EG(e,t,r,i,n){let o=i.headers.get("cf-ray");e.log?.(`Testbot V3: ${t} ${r} answered ${i.status}${o?`, cf-ray ${o}`:""}: ${n.replace(/\s+/g," ").slice(0,200)}`)}s(EG,"logRefusal");function _m(e,t,r,i,n){return yG(e,t,r,s(a=>({method:t,headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json",Accept:"application/json"},body:t==="GET"?void 0:JSON.stringify(i)}),"request"),async a=>{let c=await a.text().catch(()=>""),u={};try{u=JSON.parse(c)}catch{}if(a.ok)return u.data;EG(e,t,r,a,c);let l=u.error?.fields,A=typeof l?.path=="string"&&typeof l.reason=="string"?` at ${l.path}: ${l.reason}`:"",p=`The Skyramp app refused ${t} ${r}: ${a.status} ${u.error?.code??"no error code"}${A}`;return mG(p,a.status,u.error?.code,typeof l?.path=="string"?l.path:void 0)},n)}s(_m,"callApp");function dce(e,t,r){return yG(e,"GET",t,s(n=>({method:"GET",headers:{Authorization:`Bearer ${n}`,Accept:"application/octet-stream"}}),"request"),async n=>{if(!n.ok)return EG(e,"GET",t,n,await n.text().catch(()=>"")),mG(`The Skyramp app refused GET ${t}: ${n.status}`,n.status);let o=Buffer.from(await n.arrayBuffer());if(o.length>r)throw new Rr(`The Skyramp app answered GET ${t} with more than ${r} bytes`,n.status);return o})}s(dce,"callAppBytes");var bA=class{constructor(t,r,i,n,o,a,c,u,l,A=[],p=[],g,h=!1){this.attemptId=t;this.attemptNumber=r;this.deadlineAt=i;this.manifest=n;this.deps=o;this.license=a;this.requestedBy=c;this.writeAllowed=u;this.claudeCodeVersion=l;this.deployedPins=A;this.statedPins=p;this.runSettings=g;this.credentialRelay=h}attemptId;attemptNumber;deadlineAt;manifest;deps;license;requestedBy;writeAllowed;claudeCodeVersion;deployedPins;statedPins;runSettings;credentialRelay;static{s(this,"V3Attempt")}budgetMs(t){return oce(this.deadlineAt,t)}get skyrampRunUrl(){return lce(KR(this.deps.origin),this.manifest.runId)}send(t,r,i,n){return _m(this.deps,t,r,i,n)}readBytes(t,r){return dce(this.deps,t,r)}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(fG);let r=(this.deps.now??(()=>new Date))().getTime(),i=this.credentials[t],n=i&&await i.catch(()=>{});if(this.credentials[t]!==i)return(await this.credentials[t]).token;if(n&&n.expiresAt-r>=sce)return n.token;if(this.revocation)throw new Error(fG);let o=t==="read",a=o?{schemaVersion:1,access:t}:{schemaVersion:1},c=o?"read-only":"scoped",u=this.send("POST",`/api/v1/runner/attempts/${this.attemptId}/credentials`,a).then(l=>{let A={...l,token:l.token??this.jobToken()};if(this.issuedTokens.push(A.token),this.deps.mask?.(A.token),A.anthropicApiKey&&this.deps.mask?.(A.anthropicApiKey),o&&l.token&&!ace(A.permissions))throw new Error(`The Skyramp app was asked for a read-only GitHub token, but its token grants ${JSON.stringify(A.permissions??null)}`);!o&&!n&&A.anthropicApiKey&&(this.modelKey=A.anthropicApiKey),this.deps.onTokenGranted?.(t);let p=n?"Renewed":"Received";return l.token&&this.deps.log?.(`${p} ${c} GitHub credentials; they expire at ${A.expiresAt}.`),{token:A.token,expiresAt:l.token?new Date(A.expiresAt).getTime():Number.POSITIVE_INFINITY}},l=>{if(this.deps.onTokenRefused?.(l,t),!(l instanceof Rr)||l.code!=="CREDENTIALS_UNAVAILABLE")throw l;let A=s(h=>[...new Set(h.map(y=>y.namespace))].join(", "),"unique"),p=this.manifest.sources.map(h=>h.repository);if(new Set(p.map(h=>h.providerAccountId)).size>1)throw new Rr(`${l.message}. The run's repositories are on more than one GitHub account (${A(p)}), which Skyramp does not support yet.`,l.status,l.code);let g=A([...p,this.manifest.execution.repository]);throw new Rr(`${l.message}. Check the Skyramp GitHub App installation on ${g}: 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 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 r=t.host??pG();return this.revocation??=r.revokeToken?this.revokeIssued(i=>r.revokeToken(i,this.sourceFetch(t))):Promise.resolve([]),this.revocation}async revokeIssued(t){let r=[...this.issuedTokens],i=Promise.all(r.map(a=>this.revokeOne(a,t)));await Promise.all(Object.values(this.credentials).map(a=>a.catch(()=>{})));let n=this.issuedTokens.filter(a=>!r.includes(a));return[...await i,...await Promise.all(n.map(a=>this.revokeOne(a,t)))].filter(a=>a!==void 0)}async revokeOne(t,r){try{await r(t);return}catch(i){return`token ${this.issuedTokens.indexOf(t)+1} of ${this.issuedTokens.length}: ${i instanceof Error?i.message:String(i)}`}}};async function IG(e,t,r){hG(e,"run id"),KR(r.origin);let i=HC(e,t),n=`/api/v1/runner/runs/${e}/attempts`,o;try{o=await _m(r,"POST",n,i)}catch(l){if(!(l instanceof Rr&&l.status===400&&l.path==="$.statedPins"))throw l;i=HC(e,t,{statedPins:!1}),o=await _m(r,"POST",n,i)}let a=CP(o);if(a.manifest.runId!==e)throw new Error(`The app answered the handshake of run ${e} with the manifest of another run (${a.manifest.runId})`);let c=a.manifest.sources.find(l=>l.repository.provider!==i.execution.provider);if(c)throw new Error(`The manifest of run ${e} names ${c.repository.namespace}/${c.repository.name} on ${c.repository.provider}, but this job runs on ${i.execution.provider}`);Ace(a.manifest,[...a.deployedRevisions??[],...a.statedRevisions??[]]),a.runToken&&r.mask?.(a.runToken);let u=a.runToken?{entitlements:a.entitlements??[],runToken:a.runToken}:void 0;return new bA(a.attempt.id,a.attempt.number,new Date(a.attempt.deadlineAt),a.manifest,r,u,a.requestedBy??void 0,a.writeAllowed,a.claudeCodeVersion??void 0,a.deployedRevisions??[],a.statedRevisions??[],a.runSettings,a.credentialRelay===!0)}s(IG,"startV3Attempt");function Ace(e,t){if(t.length===0)return;if(!sP(e))throw new Error(`The 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 r=new Set(e.sources.map(n=>qr(n.repository))),i=new Set;for(let n of t){let o=qr(n.repository);if(!r.has(o))throw new Error(`The app pinned the attempt to repository ${n.repository.providerRepositoryId}, which is not a source of the run`);if(i.has(o))throw new Error(`The app pinned repository ${n.repository.providerRepositoryId} twice`);i.add(o)}}s(Ace,"checkAttemptPins");async function XR(e,t){return mP.parse(await e.send("POST",`/api/v1/runner/attempts/${e.attemptId}/heartbeat`,{schemaVersion:1},t))}s(XR,"heartbeatV3Attempt");async function CG(e,t=()=>new Date,r){if(e.closure)return e.closure;let i=await XR(e,r).then(n=>yP(n,t())).catch(()=>null);return i&&(e.closure=i),i}s(CG,"closedV3Attempt");var x_e=10*6e4;var $_e=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var T_e=d.object({tests:d.object({placements:d.array(d.unknown()).optional()}).passthrough().optional()}).passthrough(),D_e=d.object({repository:zC,testType:d.string(),directory:d.string()}).passthrough();var __e=d.object({report:d.object({language:d.string()}).passthrough()}).passthrough();var N_e=d.object({environment:d.object({components:d.array(d.unknown()).optional(),dependencies:d.array(d.unknown()).optional()}).passthrough()}).passthrough(),U_e=d.object({environment:d.object({offLimits:d.unknown().optional()}).passthrough()}).passthrough();var F_e=d.object({name:d.string().min(1),provision:d.literal("existing"),url:d.string().min(1),repository:zC.optional(),revisionUrl:d.string().min(1).optional()}).passthrough(),M_e=d.object({name:d.string().min(1),url:d.string().nullable(),versionUrl:d.string().nullable(),notes:d.string().nullable()}).passthrough();var P_e=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);function vG(e){let t=s(r=>e.testResults.filter(i=>i.status===r).length,"count");return{passed:t("Pass"),failed:t("Fail"),skipped:t("Skipped")}}s(vG,"statusCounts");function pce(e){let{passed:t,failed:r,skipped:i}=vG(e);return t+r===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+r} tests ran against the frozen sources: ${t} passed, ${r} failed${i?`, ${i} skipped`:""}.`,gaps:[],acceptedEvidence:[],actionRequired:[]}}s(pce,"executedTestsValidation");function fce(e,t){let r=e.map(c=>({result:c,repository:c.repository??t,path:c.fileName||c.testType})),i=new Map;for(let c of r){let u=`${c.repository}:${c.result.testType}:${c.path}`;i.set(u,(i.get(u)??0)+1)}let n=r.map(({result:c,repository:u,path:l})=>{let A=(i.get(`${u}:${c.testType}:${l}`)??0)>1;return c.resultId??qC(u,c.testType,l,A&&c.endpoint||void 0)}),o=new Map;for(let c of n)o.set(c,(o.get(c)??0)+1);let a=new Set(n.filter(c=>o.get(c)===1));return r.map(({result:c,repository:u},l)=>{let A=n[l],p=A;if(o.get(A)>1&&a.has(A))for(let g=2;a.has(p)||p===A;g+=1)p=A.includes("#")?`${A}.${g}`:`${A}#${g}`;return a.add(p),{...c,repository:u,resultId:p}})}s(fce,"withResultIds");function gce({notTranslated:e,...t},r){let i=fce(t.testResults,r);return{...t,testResults:i,...hce(t,i,r),validation:Ece(t,mce(t,t.validation??pce(t))),traceVersion:1}}s(gce,"v3Report");function hce(e,t,r){if(!e.testExecutionContexts)return{};let i=new Set,n=s(c=>{let u=c;for(let l=2;i.has(u);l+=1)u=`${c}#${l}`;return i.add(u),u},"unique"),o=[],a=new Map;for(let{repository:c,...u}of e.testExecutionContexts){let l=u.status==="not_run"?[]:t.filter(A=>A.fileName===u.test&&A.repository===(c?.trim()||r));l.length||o.push(u);for(let{resultId:A}of l){let p=a.get(A),g=p!==void 0&&o[p].cleanup.status==="failed"?o[p].cleanup:u.cleanup,h={...u,cleanup:g,test:A,resultId:A};p===void 0?a.set(A,o.push(h)-1):o[p]=h}}for(let c of o)c.resultId&&i.add(c.resultId);return{testExecutionContexts:o.map(c=>c.resultId?c:{...c,test:n(c.test.slice(0,512))}).slice(0,5e3)}}s(hce,"linkedContexts");function mce(e,t){let{passed:r,failed:i}=vG(e);return t.sufficiency!=="sufficient"||r+i>0||t.acceptedEvidence.length>0?t:{...t,sufficiency:"insufficient",gaps:["No test ran and no existing evidence was accepted, so nothing was validated."]}}s(mce,"withEvidence");var yce={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};function Ece(e,t){if(t.sufficiency==="sufficient")return t;let r=(e.caveats??[]).map(n=>yce[n.kind]).filter(n=>n!==void 0),i=[...new Set(r)].filter(n=>!t.actionRequired.includes(n));return i.length?{...t,actionRequired:[...i,...t.actionRequired]}:t}s(Ece,"withModelProviderFailure");function Ice(e,t,r){let{language:i,report:n}=t;if(i==="en")return;let o={language:i,businessCaseAnalysis:n.businessCaseAnalysis},a=s((y,E,C)=>Array.isArray(y)&&Array.isArray(E)&&y.length===E.length?y.map(I=>({[C]:I[C]})):void 0,"rows"),c=e.validation;n.validation&&c&&c.rationale===r.validation.rationale&&JSON.stringify(c.gaps)===JSON.stringify(r.validation.gaps)&&n.validation.gaps.length===r.validation.gaps.length&&(o.validation={rationale:n.validation.rationale,gaps:[...n.validation.gaps]});let u=new Set((r.changes??[]).map(y=>y.id)),l=(n.changes??[]).filter(y=>u.has(y.id)).map(({id:y,text:E})=>({id:y,text:E}));l.length&&(o.changes=l);let A=a(n.issuesFound,r.issuesFound,"description");A&&(o.issuesFound=A);let p=a(n.newTestsCreated,r.newTestsCreated,"description");p&&(o.newTestsCreated=p);let g=a(n.testResults,r.testResults,"details");g&&(o.testResults=g);let h=a(n.caveats,r.caveats,"text");return h&&(o.caveats=h),o}s(Ice,"v3Display");async function bG(e,t){let r=wC([...e.issuedTokens,...t.secrets??[]]),i={...gce(t.report,t.workingSlug),...t.notTranslated?{notTranslated:t.notTranslated}:{}},n=t.translated&&Ice(t.report,t.translated,i),o=s(c=>vP({manifest:e.manifest,attemptNumber:e.attemptNumber,checkedOut:t.sources.map(u=>({repository:u.repository,revision:u.revision})),firstQualification:t.firstQualification,generatedTests:ac(t.delivery,r),producer:t.producer,report:ac(c&&n?{...i,display:n}:i,r),githubWrites:t.githubWrites}),"build"),a=o(!0);n&&Buffer.byteLength(JSON.stringify(a),"utf8")>XM&&(a=o(!1)),await e.send("PUT",`/api/v1/runner/attempts/${e.attemptId}/report`,a)}s(bG,"uploadV3Report");async function wG(e,t){return hG(e.attemptId,"attempt id"),_m(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,bP({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"}))}s(wG,"endV3Attempt");0&&(module.exports={AppRefusal,AppUnreachable,AttemptEndReason,DeliveryStatus,GitHubWriteKind,NoReportCause,SourceProvider,V3Attempt,ValidationSufficiency,closedV3Attempt,endV3Attempt,heartbeatV3Attempt,startV3Attempt,uploadV3Report});
|
|
195
195
|
/*! Bundled license information:
|
|
196
196
|
|
|
197
197
|
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.0-v3.
|
|
3
|
+
"version": "0.13.0-v3.326",
|
|
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.",
|