@skyramp/testbot-core 0.13.0-v3.299 → 0.13.0-v3.300
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 +3 -3
- package/dist/post.js +1 -1
- package/dist/runner-client.cjs +1 -1
- package/package.json +1 -1
package/dist/VERSION.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":"0.13.0-v3.
|
|
1
|
+
{"version":"0.13.0-v3.300","commit":"8434aa6659613e7b6bef3241bf3e6392c8c1ff59"}
|
package/dist/main.js
CHANGED
|
@@ -350,7 +350,7 @@ ${r}`}function mZe(e){let t=hZe(e);if(!t)return[];let r=t.rules.find(o=>o.scopes
|
|
|
350
350
|
`).filter(o=>!o.startsWith(`${xx}:`)).join(`
|
|
351
351
|
`).trimEnd(),s=t?`${n}
|
|
352
352
|
${xx}: ${t}`:n;e(["log","-1","--format=%(trailers:key=Signed-off-by,valueonly)"]).split(`
|
|
353
|
-
`).some(o=>o.trim().toLowerCase()===`${gs} <${wi}>`.toLowerCase())&&(s=OG(s,{name:gs,email:wi})),e(["-c",`user.name=${gs}`,"-c",`user.email=${wi}`,"commit","--amend","--allow-empty","-m",s])}function ynr(e,t,r,n){if(n===void 0)return;let
|
|
353
|
+
`).some(o=>o.trim().toLowerCase()===`${gs} <${wi}>`.toLowerCase())&&(s=OG(s,{name:gs,email:wi})),e(["-c",`user.name=${gs}`,"-c",`user.email=${wi}`,"commit","--amend","--allow-empty","-m",s])}function ynr(e,t,r,n,s){if(n===void 0||s)return;let i=QG(e,["-1","HEAD"])[0];if(!i||!vN(i)||i.deliveryOwner!==n||!Tae.test(i.testedRevision))return;let o=i.testedRevision;for(let a of t){let c=a.testedRevision;if(!(!vN(a)||a.deliveryOwner!==n||!Tae.test(c)||o===c)){try{e(["merge-base","--is-ancestor",o,c])}catch{continue}return`This run's tests for revision ${lr(o)} are superseded: tests for newer revision ${lr(c)} are already on '${r}'. The run left that branch unchanged; use the newer run's tests.`}}}function Enr(e,t){let r=t[0],n=vN(r)?"a Testbot run for another pull request":`${r.authorName} <${r.authorEmail}>`,s=t.length>1?` and ${t.length-1} more commit(s)`:"";return`The run did not overwrite the tests branch '${e}': it has commit ${lr(r.sha)} by ${n}${s} that this run did not make. To deliver this run's tests, merge or close the open tests PR, delete the branch, and run again. Commit ${lr(r.sha)}: "${r.subject.slice(0,60)}".`}async function FG(e,t,r){let n=`refs/heads/${r.branch}`,s=`refs/remotes/${r.remote}/${r.branch}`,i;try{if(!(await t(["ls-remote","--heads",r.remote,n])).trim())return{pushFlags:[]};await t(["fetch","--no-tags",r.remote,`+${n}:${s}`]),i=e(["rev-parse",s]).trim()}catch{return{pushFlags:[]}}let o,a;try{let u=xN(e,i);a=QG(e,["--no-merges",i,...u?["--not",u]:[]]),o=QG(e,["--no-merges",i,"--not","HEAD",...u?[u]:[]])}catch{return{pushFlags:[]}}let c=u=>vN(u)&&(u.deliveryOwner===""||r.deliveryOwner!==void 0&&u.deliveryOwner===r.deliveryOwner),l=o.filter(u=>!c(u));if(l.length)return{conflict:Enr(r.branch,l)};try{let u=ynr(e,a,r.branch,r.deliveryOwner,r.firstQualification===!0);if(u)return{conflict:u}}catch{return{pushFlags:[]}}return{pushFlags:[`--force-with-lease=${n}:${i}`]}}var wnr=50;function bZe(e=process.env){let t=e.GITHUB_REPOSITORY,r=e.GITHUB_RUN_ID;return!t||!r?void 0:`${(e.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,"")}/${t}/actions/runs/${r}`}var bnr=6e4,SZe=12e4,Nae=(e,t,r)=>(0,wZe.execFileSync)(e,t,{cwd:r.cwd,encoding:"utf-8",stdio:["ignore","pipe","pipe"],env:r.env??process.env,timeout:r.timeoutMs??SZe}).trim();function Fn(e){return Zl(e)}function gZe(e){let t=Fn(e).split(`
|
|
354
354
|
`).map(n=>n.trim()).filter(Boolean);return(t[0]?.startsWith("Command failed:")&&t.length>1?t.slice(1):t).join(" | ").slice(0,300)}var ZE=/\b(401|403|unauthori[sz]ed|forbidden|permission denied|authentication failed|not logged in(to)?|could not read Username|TF401027|TF401019)\b|not accessible by (integration|personal access token)|not permitted to create/i;function Snr(e){let t=wN(e);return ZE.test(t)||/protected branch|branch protection|GH00[16]|GH013|non-fast-forward|stale info|fetch first|hook declined/i.test(t)?!1:DG.test(t)}var AZe=3;function Pf(e,t=Date.now()){if(e.signal?.aborted)return"Delivery stopped because the stage was cancelled. Delivery is incomplete.";if(e.deadlineMs!==void 0&&t>=e.deadlineMs)return"Delivery stopped because the stage deadline elapsed. Delivery is incomplete."}function Cnr(e,t){return new Promise(r=>{if(t?.aborted)return r(!0);let n=()=>{clearTimeout(s),r(!0)},s=setTimeout(()=>{t?.removeEventListener("abort",n),r(!1)},e);t?.addEventListener("abort",n,{once:!0})})}var vnr=/already exists/i,xnr=/no commits between/i,Inr=/base (ref|sha|branch)|Base ref must be a branch|field.{0,3}base|invalid base/i,Rnr=/^Merge pull request #\d+ from [^/]+\/skyramp-testbot\//;function Bae(e){if(!e)return!1;let t=JW.replace(/\[bot\]$/,"");return e===JW||e===t||e===`app/${t}`}var yZe="@skyramp-testbot",Tnr=/(^|[^\w@])@skyramp-testbot\b/i,knr=new Set(["admin","maintain","write"]),TN="<!-- skyramp-testbot-no-changes-banner -->";function $G(e){return[TN,`> \u26A0\uFE0F The latest push on ${e} did not require any new test changes.`,"> This PR still reflects Skyramp Testbot's analysis from an earlier push; regenerate if the change warrants it, or merge as-is if still relevant.",""].join(`
|
|
355
355
|
`)}function qG(e){return e.replace(new RegExp(`${TN}\\r?\\n(?:> [^\\n]*\\r?\\n){2}\\r?\\n?`,"g"),"")}function Bnr(e,t){let r=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n={...e,GIT_CONFIG_COUNT:String(r+t.length)};return t.forEach(([s,i],o)=>{n[`GIT_CONFIG_KEY_${r+o}`]=s,n[`GIT_CONFIG_VALUE_${r+o}`]=i}),n}async function _ae(){let{DefaultArtifactClient:e}=await Promise.resolve().then(()=>(kG(),TG)),t=new e;return{uploadArtifact:(r,n,s,i)=>t.uploadArtifact(r,n,s,i),downloadArtifact:async(r,n)=>{if(n?.findBy&&!n.findBy.token)throw new Error("the workflow gives Testbot no githubToken to download it with");return t.downloadArtifact(r,n)}}}function IN(e,t){try{e("git",["cherry-pick","--abort"],{cwd:t.repositoryPath})}catch{}try{e("git",["checkout","-q","-B",t.branch,t.commitSha],{cwd:t.repositoryPath})}catch{}}function Pae(e,t){let r=t.at(-1);return r?[`--force-with-lease=refs/heads/${e}:${r}`]:[]}function CZe(e,t,r,n){let s=vae(i=>e("git",i,{cwd:t}));n.commit=s,s&&r.push(s)}var RN=class{constructor(t){this.opts=t;this.log=t.log??(r=>console.log(r)),this.run=t.run??Nae,this.runUrl=t.runUrl??bZe(),this.startedAtMs=t.startedAtMs??Date.now()}opts;name="github";supportsRemote=!0;runUrl;log;run;resolvedSlug;startedAtMs;warnedExpiry=!1;checkRun;async uploadArtifact(t,r,n){if(!(!this.runUrl||!r.length))try{let s=await tZe(t,r,n,{retentionDays:14});return s?`${this.runUrl}/artifacts/${s}`:void 0}catch(s){Te(`could not upload artifact ${t}: ${s instanceof Error?s.message:String(s)}`);return}}artifactStore(){return _ae()}gh(t,r){return this.run("gh",t,{cwd:this.opts.repositoryPath,env:r?{...process.env,GH_TOKEN:r}:process.env})}ghPr(t,r,n=this.slug()){return this.gh(n?[...t,"-R",n]:t,r)}async token(){return this.opts.tokenProvider?this.opts.tokenProvider():this.opts.githubToken}git(t,r,n=this.opts.repositoryPath,s){return this.run("git",t,s===void 0?{cwd:n,env:r}:{cwd:n,env:r,timeoutMs:s})}slug(){if(this.resolvedSlug===void 0){let t=(this.opts.repoSlug??process.env.GITHUB_REPOSITORY??"").trim();if(/^[^/\s]+\/[^/\s]+$/.test(t))this.resolvedSlug=t;else try{this.resolvedSlug=this.gh(["repo","view","--json","nameWithOwner","-q",".nameWithOwner"])||null}catch{this.resolvedSlug=null}}return this.resolvedSlug??void 0}warnIfTokenLikelyExpired(){if(this.opts.tokenProvider||this.warnedExpiry||(this.opts.inActions??process.env.GITHUB_ACTIONS)!=="true")return;let t=Math.round((Date.now()-this.startedAtMs)/6e4);t<wnr||(this.warnedExpiry=!0,this.log(`[warn] this run has been going for ${t} minutes \u2014 the workflow-minted GitHub token expires after 1 hour, so the push / PR / status calls may fail with 401. Set SKYRAMP_GITHUB_APP_ID and SKYRAMP_GITHUB_APP_PRIVATE_KEY so Skyramp Testbot can mint fresh tokens during long runs.`))}createProgressSink(){let t=this.slug();return this.opts.prNumber==null||!t?zT(this.log):ALe({repo:t,prNumber:this.opts.prNumber,cwd:this.opts.repositoryPath,getToken:()=>this.token(),onError:r=>this.log(`[warn] progress comment failed: ${r instanceof Error?r.message:String(r)}`)})}async resolveContext(){let t=this.slug(),r,n,s,i,o,a;if(this.opts.prNumber!=null)try{let c=await this.token().catch(()=>{}),l=JSON.parse(this.ghPr(["pr","view",String(this.opts.prNumber),"--json","headRefName,headRefOid,baseRefName,title,body,isCrossRepository"],c));r=l.headRefName||void 0,n=l.headRefOid||void 0,s=l.baseRefName||void 0,i=l.title||void 0,o=l.body||void 0,a=l.isCrossRepository}catch{}if(!r)try{let c=this.git(["rev-parse","--abbrev-ref","HEAD"]);c&&c!=="HEAD"&&(r=c)}catch{}return{repoSlug:t,prNumber:this.opts.prNumber,headBranch:r,headSha:n,baseBranch:s,prTitle:i,prBody:o,fromFork:a}}eventPayload(){let t=this.opts.eventPath??process.env.GITHUB_EVENT_PATH;if(!(!t||!Hd.existsSync(t)))try{let r=JSON.parse(Hd.readFileSync(t,"utf-8"));return typeof r=="object"&&r!==null?r:void 0}catch{return}}gitRead(t){try{return this.git(t)}catch{return""}}async admitRun(){let t=this.opts.eventName??process.env.GITHUB_EVENT_NAME,r=this.eventPayload(),n=r?.pull_request,s=r?.issue,i=await this.token().catch(()=>{}),o=n?.user?.login??s?.user?.login;if(!o&&this.opts.prNumber!=null)try{o=this.ghPr(["pr","view",String(this.opts.prNumber),"--json","author","-q",".author.login"],i)||void 0}catch{}if(o&&Bae(o))return{admit:!1,reason:`PR was opened by ${o} (a Testbot tests PR) \u2014 skipping to prevent recursion`};if(t==="issue_comment"){let c=r?.comment,l=c?.body??"",u=c?.user?.login??"";if(!s?.pull_request)return{admit:!1,reason:"comment is not on a pull request"};if(!Tnr.test(l))return{admit:!1,reason:`comment does not mention ${yZe}`};if(Bae(u))return{admit:!1,reason:`comment was posted by ${u} (the bot itself)`};let d=this.permissionOf(u,i);if(!d)return{admit:!1,reason:`could not verify @${u}'s repository permission \u2014 refusing rather than assuming write access`};if(!knr.has(d))return{admit:!1,reason:`@${u} has ${d} access; ${yZe} requires write access`};if(this.opts.allowedAuthors?.length){let p=o?.replace(/^app\//,"");if(!p)return{admit:!1,reason:"allowedAuthors is configured but the PR author could not be determined \u2014 refusing"};if(!this.opts.allowedAuthors.includes(p))return{admit:!1,reason:`PR author ${p} is not in allowedAuthors`}}}else if(this.opts.allowedAuthors?.length){let c=o?.replace(/^app\//,"");if(!c)return{admit:!1,reason:"allowedAuthors is configured but the PR author could not be determined \u2014 refusing"};if(!this.opts.allowedAuthors.includes(c))return{admit:!1,reason:`PR author ${c} is not in allowedAuthors`}}if(t==="pull_request"&&r?.action==="synchronize"){let c=n?.head?.sha||"HEAD",l=r?.head_commit,u=l?.author?.name||this.gitRead(["log","-1","--pretty=format:%an",c]),d=l?.author?.email||this.gitRead(["log","-1","--pretty=format:%ae",c]),p=this.gitRead(["log","-1","--pretty=format:%s",c]);if(!u&&!d&&!p)return{admit:!1,reason:"could not resolve the head commit's author on this synchronize \u2014 refusing rather than risking a recursive run"};if(u===gs&&d===wi)return{admit:!1,reason:`head commit is ${gs}'s own (synchronize) \u2014 skipping to prevent recursion`};if(Rnr.test(p)||Bae(u))return{admit:!1,reason:`head commit merges a Testbot tests PR ("${p}") \u2014 tests already generated`}}return{admit:!0}}permissionOf(t,r){let n=this.slug();if(!(!n||!t))try{let s=JSON.parse(this.gh(["api",`repos/${n}/collaborators/${t}/permission`],r));return s.role_name??s.permission}catch{return}}watchRun(t){let r=!1,n=(l,u)=>{r||(r=!0,t(l,u))},s=null,i=!1,o=this.opts.prNumber;if(o!=null){let l=async()=>{if(!(i||r)){i=!0;try{let u=await this.token().catch(()=>{}),d=this.ghPr(["pr","view",String(o),"--json","state,mergedAt"],u),p=JSON.parse(d);p.state==="CLOSED"&&!p.mergedAt&&n("pr-closed",`PR #${o} was closed without merging`)}catch{}finally{i=!1}}};s=setInterval(()=>{l()},this.opts.prPollMs??bnr),s.unref?.()}let a=this.opts.watchSignals===!1?[]:["SIGTERM","SIGINT"],c=l=>{for(let u of a)process.removeListener(u,c);n("cancelled",`received ${l} (workflow cancelled or runner shutting down)`)};for(let l of a)process.on(l,c);return{stop:()=>{s&&clearInterval(s),s=null;for(let l of a)process.removeListener(l,c)}}}checkName(){let t=this.opts.eventName??process.env.GITHUB_EVENT_NAME;return t==="workflow_dispatch"||t==="issue_comment"?`${gs} (retrigger)`:gs}async beginRun(){let t=this.slug();if(this.opts.prNumber==null||!t)return;let r=this.checkName();try{let n=await this.token(),s=this.gh(["pr","view",String(this.opts.prNumber),"--json","headRefOid","-q",".headRefOid"],n);if(!s)return;let i=["api",`repos/${t}/check-runs`,"-X","POST","-f",`name=${r}`,"-f",`head_sha=${s}`,"-f","status=in_progress","-f",`started_at=${new Date().toISOString()}`];this.runUrl&&i.push("-f",`details_url=${this.runUrl}`);try{let o=Number(this.gh([...i,"-q",".id"],n));if(Number.isFinite(o)&&o>0){this.checkRun={id:o,sha:s};return}}catch(o){if(!ZE.test(Fn(o)))throw o}this.checkRun={fallbackSha:s},this.commitStatus(t,s,"pending",r,"Skyramp Testbot is running",n)}catch(n){this.log(`[warn] could not report run start: ${$o(n)}`)}}async endRun(t){let r=this.slug();if(!this.checkRun||!r)return;this.warnIfTokenLikelyExpired();let n=this.checkName();try{let s=await this.token();if("id"in this.checkRun){let i=t.status==="success"?"success":t.status==="neutral"?"neutral":t.status==="cancelled"?"cancelled":"failure",o=["api",`repos/${r}/check-runs/${this.checkRun.id}`,"-X","PATCH","-f","status=completed","-f",`conclusion=${i}`,"-f",`completed_at=${new Date().toISOString()}`];o.push("-f",`output[title]=${n}`,"-f",`output[summary]=${t.summary.slice(0,6e4)}`),this.gh(o,s)}else{let i=t.status==="success"||t.status==="neutral"?"success":t.status==="cancelled"?"error":"failure";this.commitStatus(r,this.checkRun.fallbackSha,i,n,t.summary,s)}}catch(s){this.log(`[warn] could not report run end (${t.status}): ${$o(s)}`)}finally{this.checkRun=void 0}}async listCommitChecks(t){try{let r=await this.token(),n=[],s=JSON.parse(this.gh(["api",`repos/${t.repository}/commits/${t.revision}/check-runs?per_page=100`],r));for(let a of s.check_runs??[])a.name&&a.head_sha&&n.push({repository:t.repository,name:a.name,headSha:a.head_sha,status:a.status??"completed",conclusion:a.conclusion??null,url:a.html_url,summary:a.output?.title??void 0});let i=[],o={};try{o=JSON.parse(this.gh(["api",`repos/${t.repository}/commits/${t.revision}/status`],r))}catch(a){i.push("commit statuses"),this.log(`[warn] could not read commit statuses for ${t.repository}@${t.revision.slice(0,12)}: ${gZe(a)}`)}for(let a of o.statuses??[])a.context&&n.push({repository:t.repository,name:a.context,headSha:o.sha??t.revision,status:a.state==="pending"?"pending":"completed",conclusion:a.state==="pending"?null:a.state??null,url:a.target_url??void 0,summary:a.description??void 0});return{records:n,...i.length?{unreadSources:i}:{}}}catch(r){this.log(`[warn] could not read CI results for ${t.repository}@${t.revision.slice(0,12)}: ${gZe(r)}`);return}}async commitContains(t){try{let r=await this.token(),n=JSON.parse(this.gh(["api",`repos/${t.repository}/compare/${t.ancestor}...${t.descendant}`,"--jq","{status: .status}"],r));return n.status==="identical"||n.status==="ahead"?"contained":n.status==="behind"||n.status==="diverged"?"not_contained":"unknown"}catch(r){return this.log(`[warn] could not compare ${t.repository} ${lr(t.ancestor)}...${lr(t.descendant)}: ${$o(r)}`),"unknown"}}commitStatus(t,r,n,s,i,o){let a=["api",`repos/${t}/statuses/${r}`,"-X","POST","-f",`state=${n}`,"-f",`context=${s}`,"-f",`description=${i.slice(0,140)}`];this.runUrl&&a.push("-f",`target_url=${this.runUrl}`),this.gh(a,o)}async markTestsPrUnchanged(t,r={}){let n=t.repoSlug??this.slug(),s=o=>({action:"skipped",pushed:!1,base:"",url:"",detail:o}),i;try{let o=await this.token(),a=Pf(r);if(a)return s(a);let c=JSON.parse(this.ghPr(["pr","view",t.branch,"--json","number,url,state,body,baseRefName"],o,n));if(c.state!=="OPEN"||!c.number)return s(`no open tests PR for ${t.branch} \u2014 nothing to annotate`);let l=t.devPr===void 0?this.opts.prNumber:t.devPr,u=l!=null?`#${l}`:"the dev branch",d=$G(u)+qG(c.body??"");i=Hd.mkdtempSync(Ix.join(EZe.tmpdir(),"staged-stale-"));let p=Ix.join(i,"body.md");Hd.writeFileSync(p,d);let f=Pf(r);return f?s(f):(this.ghPr(["pr","edit",String(c.number),"--body-file",p],o,n),{action:"unchanged",pushed:!1,base:c.baseRefName??"",url:c.url??"",detail:"no new test changes this run \u2014 existing tests PR annotated"})}catch(o){return s(`could not annotate the tests PR: ${$o(o)}`)}finally{i&&Hd.rmSync(i,{recursive:!0,force:!0})}}async closeTestsPr(t){try{let r=await this.token(),n=JSON.parse(this.ghPr(["pr","view",t.branch,"--json","number,url,state"],r));return n.state!=="OPEN"||!n.number?{closed:!1,url:n.url}:(this.ghPr(["pr","close",String(n.number),"--comment",t.reason],r),{closed:!0,url:n.url})}catch(r){return this.log(`[warn] could not close the tests PR for ${t.branch}: ${$o(r)}`),{closed:!1}}}hasPersistedGitCredential(t){try{return!!this.git(["config","--get-regexp","^http(\\..*)?\\.extraheader$"],void 0,t).trim()}catch{return!1}}async push(t,r,n){let s=`refs/heads/${t.branch}`,i=vae(c=>this.git(c,void 0,t.repositoryPath)),o=[...n],a=i?void 0:"without a verified local commit for retry";for(let c=1;;c++){let l=Pf(t);if(l)throw new Error(l);try{let u=c===1?"HEAD":i;return this.remoteGit(["push",...o,t.remote,`${u}:${s}`],r,t.repositoryPath,t),i}catch(u){if(!Snr(u))throw u;let d=c*1e3,p=a;if(!p&&c===AZe&&(p=`after ${c} attempts`),!p&&t.deadlineMs!==void 0&&Date.now()+d>=t.deadlineMs&&(p="with no stage time left for a retry"),p||(this.log(`[deliver] The tests-branch push encountered a transient Git failure; retrying (${c+1}/${AZe})`),await Cnr(d,t.signal)&&(p="and the stage was stopped before a retry")),p)throw new Error(`The tests-branch push encountered a transient Git failure ${p}. Delivery is incomplete. Generated tests remain in the run artifacts; retry the validation run when GitHub connectivity recovers. ${Fn(u)}`)}}}checkoutAuthHeader;adoptCheckoutAuthHeader(t){this.checkoutAuthHeader=t}remoteGit(t,r,n=this.opts.repositoryPath,s){let i=A=>{let E=Date.now(),g=s&&Pf(s,E);if(g)throw new Error(g);let w=s?.deadlineMs===void 0?void 0:Math.min(SZe,s.deadlineMs-E);return this.git(t,A,n,w)},o=this.opts.tokenProvider?r:void 0,a=this.opts.githubToken,c=o??r??a,l=Ix.resolve(n)===Ix.resolve(this.opts.repositoryPath)?this.checkoutAuthHeader:void 0;if(!l&&!c||this.hasPersistedGitCredential(n))return i();let u=A=>{let E=Buffer.from(`x-access-token:${A}`).toString("base64");return Kr(E),`AUTHORIZATION: basic ${E}`},d=l!==void 0&&a!==void 0&&l===u(a),p=o?u(o):l&&!d?l:u(c),f=(process.env.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,""),m=[[`http.${f}/.extraheader`,p]];if(process.env.GITHUB_ACTIONS==="true"){let A=new URL(f).hostname;m.push([`url.${f}/.insteadOf`,`git@${A}:`],[`url.${f}/.insteadOf`,`ssh://git@${A}/`])}return i(Bnr(process.env,m))}testsPrBody(t,r,n){try{return this.ghPr(["pr","view",t,"--json","body","-q",".body"],r,n)}catch(s){this.log(`[warn] could not read the tests PR for ${t}: ${Fn(s)}`);return}}noteReplaced(t,r,n,s,i){let o=NG({runUrl:t.runUrl,previousBody:r,commit:n});if(!(!o||Pf(t)))try{this.ghPr(["pr","comment",t.branch,"--body",o],s,i)}catch(a){this.log(`[warn] could not comment on the tests PR for ${t.branch}: ${Fn(a)}`)}}pushFailure(t,r){let n=Fn(t);return{action:"failed",pushed:!1,base:r,url:"",failure:ZE.test(wN(t))?"auth":"push",detail:`push failed: ${n}`}}async publishTestsPr(t){let r=[],n={};return{...await this.publish(t,r,n),pushedCommits:r,...n.commit?{deliveredCommit:n.commit}:{}}}async publish(t,r,n){this.warnIfTokenLikelyExpired();let s=t.repositoryPath,i=t.repoSlug??this.slug(),o=t.devPr===void 0?this.opts.prNumber:t.devPr,a=(g,w,S,x=t.base)=>({action:"failed",pushed:S,base:x,url:"",failure:g,detail:w}),c;try{c=await this.token()}catch(g){return a("auth",`could not mint a GitHub App token: ${Fn(g)}`,!1)}let l=Pf(t);if(l)return a("push",l,!1);let u=[],d=!1;if(t.mode==="append"){let g=!1;try{g=!!this.remoteGit(["ls-remote","--heads",t.remote,t.branch],c,s).trim()}catch{}if(g){try{this.remoteGit(["fetch",t.remote,t.branch],c,s);let S=xN(x=>this.git(x,void 0,s),`${t.remote}/${t.branch}`);this.git(["checkout","-B",t.branch,`${t.remote}/${t.branch}`],void 0,s),this.git(["-c",`user.name=${gs}`,"-c",`user.email=${wi}`,"cherry-pick","--keep-redundant-commits",t.commitSha],void 0,s),fg(x=>this.git(x,void 0,s),S)}catch(S){return IN(this.run,t),a("conflict",`append onto the existing tests branch failed (tests kept on the local branch): ${Fn(S)}`,!1)}let w=!1;try{this.git(["diff","--quiet",`${t.remote}/${t.branch}`,"HEAD"],void 0,s),w=!0}catch{w=!1}if(w){let S=await this.markTestsPrUnchanged({branch:t.branch,repositoryPath:s,repoSlug:t.repoSlug,devPr:t.devPr},t);if(S.action==="unchanged"||Pf(t))return S;d=!0;try{n.commit=this.git(["rev-parse",`${t.remote}/${t.branch}`],void 0,s).trim()||void 0}catch(x){this.log(`[warn] could not read the tests-branch commit for ${t.branch}; the PR opens without it: ${$o(x)}`)}}}}else{let g=await FG(w=>this.git(w,void 0,s),w=>this.remoteGit(w,c,s),t);if("conflict"in g)return a("conflict",g.conflict,!1);u=g.pushFlags}if(!d)try{let g=await this.push(t,c,u);g&&r.push(g),n.commit=g}catch(g){return this.pushFailure(g,t.base)}let p=g=>{let w=Pf(t);if(w)throw new Error(w);return this.ghPr(["pr","create","--head",t.branch,"--base",g,"--title",t.title,"--body-file",t.bodyFile],c,i)},f=g=>{let w=t.mode!=="append"&&t.runUrl?{body:this.testsPrBody(t.branch,c,i)}:void 0,S=Pf(t);if(S)throw new Error(S);this.ghPr(["pr","edit",t.branch,"--base",g,"--title",t.title,"--body-file",t.bodyFile],c,i);let x=this.ghPr(["pr","view",t.branch,"--json","url","-q",".url"],c,i);return w&&this.noteReplaced(t,w.body,n.commit,c,i),{action:"updated",pushed:!0,base:g,url:x}},m=(g,w)=>{if(vnr.test(g))try{return f(w)}catch(S){return a("unknown",`tests PR exists but could not be updated: ${Fn(S)}`,!0,w)}if(xnr.test(g))return{action:"skipped",pushed:!0,base:w,url:"",detail:`no commits between ${w} and ${t.branch} \u2014 the tests are already on the base`};if(ZE.test(g))return a("auth",g,!0,w)},A;try{return{action:"created",pushed:!0,base:t.base,url:p(t.base)}}catch(g){A=Fn(g)}let E=m(A,t.base);if(E)return E;if(Inr.test(A)){if(t.mode==="append")return a("unknown",`the dev branch '${t.base}' no longer exists (dev PR merged) and append mode cannot re-cut the tests branch \u2014 re-run in replace mode`,!0);if(o==null)return a("unknown",`the base branch '${t.base}' no longer exists and no dev PR number is known to retarget from`,!0);let g={};try{g=JSON.parse(this.ghPr(["pr","view",String(o),"--json","state,baseRefName"],c,i))}catch{}if(g.state!=="MERGED"||!g.baseRefName)return{action:"skipped",pushed:!0,base:t.base,url:"",detail:`the dev branch '${t.base}' no longer exists and PR #${o} is ${g.state??"unknown"} (not merged) \u2014 nothing to target; tests are on branch ${t.branch}`};let w=g.baseRefName;this.log(`[deliver] tests PR base '${t.base}' no longer exists (dev PR merged) \u2014 re-cutting onto '${w}'`);try{this.remoteGit(["fetch",t.remote,w],c,s),this.git(["checkout","-B",t.branch,`${t.remote}/${w}`],void 0,s),this.git(["-c",`user.name=${gs}`,"-c",`user.email=${wi}`,"cherry-pick","--keep-redundant-commits",t.commitSha],void 0,s),fg(S=>this.git(S,void 0,s),this.git(["rev-parse","HEAD^"],void 0,s).trim())}catch(S){return IN(this.run,t),a("conflict",`re-cut onto '${w}' failed (tests kept on the local branch): ${Fn(S)}`,!0)}try{let S=await this.push(t,c,Pae(t.branch,r));S&&r.push(S),n.commit=S}catch(S){return{...this.pushFailure(S,w),pushed:!0}}try{return{action:"retargeted",retargetedAs:"created",pushed:!0,base:w,url:p(w)}}catch(S){let x=Fn(S),R=m(x,w);return R?R.action==="updated"?{...R,action:"retargeted",retargetedAs:"updated"}:R:a("unknown",`re-cut onto '${w}' pushed, but PR create failed: ${x}`,!0,w)}}return a("unknown",A,!0)}};var oc=X(require("fs")),Fae=X(require("os")),ci=X(require("path"));var vZe=X(require("fs")),kN="SKYRAMP_AZURE_SUPERVISED",Dae=3;function GG(e){return e.replace(/##(?=(?:vso)?\[)/gi,"#\u200B#")}function Oae(e,t=process.env){t[kN]==="1"?vZe.writeSync(Dae,`${JSON.stringify(e)}
|
|
356
356
|
`):process.stdout.write(e.command!==void 0?`${e.command}
|
|
@@ -504,7 +504,7 @@ ${q7e(m.missing)}`};if(!J.reported)return{...J,note:`the runner wrote no report:
|
|
|
504
504
|
`).slice(1).join(`
|
|
505
505
|
`).trim(),n=aZe(r);return n?{prFailure:"hook",prDetail:`${n}
|
|
506
506
|
${r}`}:{prFailure:"unknown",prDetail:t}}async function xar(e,t,r,n,s,i){let o=y7e(n.path,e.runDir),a=process.env.PATH;o.dir&&(process.env.PATH=E7e(o).PATH);try{return await Iar(e,t,r,n,s,i)}finally{o.dir&&(process.env.PATH=a),o.cleanup()}}async function Iar(e,t,r,n,s,i){let o=n.slug,a,c=!1,l;try{let u=n.path,d=fe(e,"finalize.json"),p=fw(e.inputs.requirementItems),f=SN(u),m=Z=>CN(Z,f,s),A=m(pw(d?.commit?.message||r.commitMessage||"Skyramp Testbot: add tests",p)),E=v2(e.outputsDir)??r,g=m(pw(E.commitMessage,p)||pw(r.commitMessage,p)||A).split(`
|
|
507
|
-
`)[0],w={name:gs,email:wi},S=!!f.signOff;if(!S&&t.listCommitChecks){let Z=i?.headSha??Hi(u,["rev-parse","HEAD"]);try{S=(await t.listCommitChecks({repository:o,revision:Z}))?.records.some(U=>U.name.trim().toLowerCase()==="dco"&&U.headSha===Z&&(!U.repository||U.repository.toLowerCase()===o.toLowerCase()))??!1}catch{console.warn(`[deliver] could not read commit checks for ${o}`)}}let x=e.inputs.deliverRemote||"origin",R=itt(u,Gce),I=itt(u,B2);if(R&&!I)throw new Error(`${o}: the checkout records a merged base but not what it merged`);let B=R?$ce(void 0,void 0,u):i?i.headBranch||$ce(e.inputs.headBranch,e.inputs.baseBranch,u):$ce(void 0,void 0,u),T=e.inputs.pullRequests;i?.prNumber!=null&&!T?.some(Z=>Z.repository.toLowerCase()===o.toLowerCase())&&(T=[...T??[],{repository:o,number:String(i.prNumber)}]);let Q=T?.some(Z=>Z.repository.toLowerCase()===o.toLowerCase())?void 0:e.inputs.deliveryOrigin,J=R||!Q?I:void 0,V=J?mar(o,B,J):har(T,o,B,Q),oe=qce(B,e.inputs.deliverBranch)+(J?`-merge-${V}`:Q?`-source-${Q.number}-${V}`:""),ce=rZe(S2(Aar(E,e,n),{audience:"testbot-pr",requestedBy:e.inputs.requestedBy,sourcePullRequest:Q&&`${Q.repository.namespace}/${Q.repository.name}#${Q.number}`}),e.inputs.skyrampRunUrl),D=i?"pr-body.md":`pr-body-${ctt(o)}.md`,P=yg.join(e.outputsDir,D);Xd.writeFileSync(P,ce);let N=Hi(u,["rev-parse","HEAD"]),K=R??N;Hi(u,["checkout","-B",oe]),a=oe,Hi(u,["reset"]);for(let Z of s)gar(yg.join(u,Z),p);let k=[];for(let Z of s)try{Hi(u,["--literal-pathspecs","add","--",Z])}catch{k.push(Z)}try{Hi(u,["diff","--cached","--quiet"])}catch{try{let Z=Hi(u,["interpret-trailers","--trailer",`${MG}: ${V}`,"--trailer",`${xx}: ${N}`,"--trailer",`${kae}: ${K}`],A),Y=S?OG(Z,w):Z;Hi(u,["-c",`user.name=${w.name}`,"-c",`user.email=${w.email}`,"commit","-m",Y])}catch(Z){throw new k2(Z)}c=!0}l=Hi(u,["rev-parse","HEAD"]);let q,L=R??i?.headSha;if(c&&L&&L!==N){let Z=!1;try{Hi(u,["checkout","-q","-B",a,L]),Z=!0,Hi(u,["-c",`user.name=${w.name}`,"-c",`user.email=${w.email}`,"cherry-pick","--keep-redundant-commits",l]),Z=!1,fg(Y=>Hi(u,Y),L),l=Hi(u,["rev-parse","HEAD"])}catch(Y){try{Hi(u,["cherry-pick","--abort"])}catch{}Hi(u,["checkout","-q","-B",a,l]);let U=YE(Zl(Y),1/0);if(R&&!Z)throw Y;if(R)return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:x,base:B,committed:c,commitSha:l,pushed:!1,prAction:"skipped",prTitle:g,unstaged:k,reason:`the tests do not apply to ${B} at ${R.slice(0,12)} without the merged revisions (${U}), so no tests PR was opened`}};q=`tests committed on the checkout's merge commit (re-cut onto ${L.slice(0,12)} failed: ${U})`}}let H=i?{}:{repositoryPath:u,repoSlug:o,devPr:null};if(!c){let Z=await t.markTestsPrUnchanged({branch:a,...H});return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:x,base:B,committed:!1,commitSha:l,pushed:!1,prAction:Z.action==="unchanged"?"unchanged":"skipped",prUrl:Z.url,prTitle:g,unstaged:k,reason:Z.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 W=await t.publishTestsPr({repositoryPath:u,...H,remote:x,branch:a,base:B,commitSha:l,title:g,bodyFile:P,mode:e.inputs.deliverMode,deliveryOwner:V,runUrl:e.inputs.skyrampRunUrl,signal:e.signal,deadlineMs:e.deadlineMs});return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:x,base:W.base,requestedBase:B,committed:c,commitSha:l,pushed:W.pushed,...W.pushedCommits?{pushedCommits:W.pushedCommits}:{},...W.deliveredCommit?{deliveredCommit:W.deliveredCommit}:{},prAction:W.action,...W.retargetedAs?{retargetedAs:W.retargetedAs}:{},prUrl:W.url,prTitle:g,...W.failure?{prFailure:W.failure,prDetail:W.detail}:{},...q?{cutNote:q}:{},...W.action==="skipped"&&W.detail?{reason:W.detail}:{},unstaged:k}}}catch(u){return{thrown:!0,record:{schemaVersion:1,repository:o,branch:a,committed:c,commitSha:l,pushed:!1,prAction:"failed",...Car(u),unstaged:[]}}}}var ltt={name:"deliver",timeoutMinutes:5,execute:Ear,validateInput:e=>{let t=qC(e);return t?{ok:!1,reasons:[t]}:par(e)},requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var Go=require("crypto");var utt=Buffer.from("302a300506032b656e032100","hex"),dtt=e=>e.export({format:"der",type:"spki"}).subarray(utt.length);function ptt(e){let t=Buffer.from(e,"base64");if(t.length!==32)throw new Error("A relay key is 32 bytes of X25519");return(0,Go.createPublicKey)({key:Buffer.concat([utt,t]),format:"der",type:"spki"})}function ftt(e,t,r,n){let s=(0,Go.diffieHellman)({privateKey:e,publicKey:t});return Buffer.from((0,Go.hkdfSync)("sha256",s,Buffer.concat([r,n]),VOe,32))}var N2=class e{constructor(t,r){this.privateKey=t;this.publicKey=r}privateKey;publicKey;static generate(){let{privateKey:t,publicKey:r}=(0,Go.generateKeyPairSync)("x25519");return new e(t,dtt(r).toString("base64"))}open(t,r){let n=Buffer.from(t.ephemeralPublicKey,"base64"),s=ftt(this.privateKey,ptt(t.ephemeralPublicKey),n,Buffer.from(this.publicKey,"base64")),i=(0,Go.createDecipheriv)("aes-256-gcm",s,Buffer.from(t.iv,"base64"));return i.setAAD(Buffer.from(r,"utf8")),i.setAuthTag(Buffer.from(t.tag,"base64")),Buffer.concat([i.update(Buffer.from(t.ciphertext,"base64")),i.final()]).toString("utf8")}};function htt(e,t,r){let n=ptt(t),s=(0,Go.generateKeyPairSync)("x25519"),i=dtt(s.publicKey),o=ftt(s.privateKey,n,i,Buffer.from(t,"base64")),a=(0,Go.randomBytes)(12),c=(0,Go.createCipheriv)("aes-256-gcm",o,a);c.setAAD(Buffer.from(r,"utf8"));let l=Buffer.concat([c.update(e,"utf8"),c.final()]);return{ephemeralPublicKey:i.toString("base64"),iv:a.toString("base64"),ciphertext:l.toString("base64"),tag:c.getAuthTag().toString("base64")}}var Rar=10*6e4;function Tar(e,t){return e.getTime()-t.getTime()-Rar}var mtt="This attempt revoked its scoped GitHub credentials; it mints no more.",kar=10*6e4;var Bar=e=>!!e&&Object.keys(e).length===1&&e.contents==="read",Nar=3e4,_ar=3,gtt=30,nn=class extends Error{constructor(r,n,s,i){super(r);this.status=n;this.code=s;this.path=i}status;code;path},Zd=class extends Error{},$x=class extends Zd{},ZN=class extends $x{};function Jce(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 Stt(e,t){if(!lm.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}function Yce(e,t){return`${e.replace(/\/+$/,"")}/runs/${t}`}function Ctt(e,t,r,n){throw t<500&&t!==429?new nn(e,t,r,n):t===503&&r==="RUNNER_PROVIDER_NOT_READY"?new ZN(e):t===503&&r==="RUN_NOT_READY"?new $x(e):new Zd(e)}async function vtt(e,t,r,n){let s=Jce(e.origin),i,o=0;for(let a=1;a<=_ar||i instanceof $x;a+=1){if(i instanceof $x){if(o===gtt)throw i;o+=1,a-=1,e.log?.(`${i.message}; trying again (${o} of ${gtt}).`),await new Promise(c=>setTimeout(c,e.readyWaitMs??1e4))}else a>1&&await new Promise(c=>setTimeout(c,(e.retryDelayMs??2e3)*(a-1)));try{let c=await e.idToken(s),l=await(e.fetch??fetch)(new URL(t,s).toString(),{...r(c),redirect:"error",signal:AbortSignal.timeout(Nar)}).catch(u=>{throw new Zd(u instanceof Error?u.message:String(u),{cause:u})});return await n(l)}catch(c){if(c instanceof nn)throw c;i=c}}throw i}function xtt(e,t,r,n,s){let i=n.headers.get("cf-ray");e.log?.(`Testbot V3: ${t} ${r} answered ${n.status}${i?`, cf-ray ${i}`:""}: ${s.replace(/\s+/g," ").slice(0,200)}`)}function hw(e,t,r,n){return vtt(e,r,i=>({method:t,headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json",Accept:"application/json"},body:t==="GET"?void 0:JSON.stringify(n)}),async i=>{let o=await i.text().catch(()=>""),a={};try{a=JSON.parse(o)}catch{}if(i.ok)return a.data;xtt(e,t,r,i,o);let c=a.error?.fields,l=typeof c?.path=="string"&&typeof c.reason=="string"?` at ${c.path}: ${c.reason}`:"",u=`The Skyramp app refused ${t} ${r}: ${i.status} ${a.error?.code??"no error code"}${l}`;return Ctt(u,i.status,a.error?.code,typeof c?.path=="string"?c.path:void 0)})}function Par(e,t,r){return vtt(e,t,s=>({method:"GET",headers:{Authorization:`Bearer ${s}`,Accept:"application/octet-stream"}}),async s=>{if(!s.ok)return xtt(e,"GET",t,s,await s.text().catch(()=>"")),Ctt(`The Skyramp app refused GET ${t}: ${s.status}`,s.status);let i=Buffer.from(await s.arrayBuffer());if(i.length>r)throw new nn(`The Skyramp app answered GET ${t} with more than ${r} bytes`,s.status);return i})}var Hce=class{constructor(t,r,n,s,i,o,a,c,l,u=[],d=[],p,f=!1){this.attemptId=t;this.attemptNumber=r;this.deadlineAt=n;this.manifest=s;this.deps=i;this.license=o;this.requestedBy=a;this.writeAllowed=c;this.claudeCodeVersion=l;this.deployedPins=u;this.statedPins=d;this.runSettings=p;this.credentialRelay=f}attemptId;attemptNumber;deadlineAt;manifest;deps;license;requestedBy;writeAllowed;claudeCodeVersion;deployedPins;statedPins;runSettings;credentialRelay;budgetMs(t){return Tar(this.deadlineAt,t)}get skyrampRunUrl(){return Yce(Jce(this.deps.origin),this.manifest.runId)}send(t,r,n){return hw(this.deps,t,r,n)}readBytes(t,r){return Par(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(mtt);let r=(this.deps.now??(()=>new Date))().getTime(),n=this.credentials[t],s=n&&await n.catch(()=>{});if(this.credentials[t]!==n)return(await this.credentials[t]).token;if(s&&s.expiresAt-r>=kar)return s.token;if(this.revocation)throw new Error(mtt);let i=t==="read",o=i?{schemaVersion:1,access:t}:{schemaVersion:1},a=i?"read-only":"scoped",c=this.send("POST",`/api/v1/runner/attempts/${this.attemptId}/credentials`,o).then(l=>{let u={...l,token:l.token??this.jobToken()};if(this.issuedTokens.push(u.token),this.deps.mask?.(u.token),u.anthropicApiKey&&this.deps.mask?.(u.anthropicApiKey),i&&l.token&&!Bar(u.permissions))throw new Error(`The Skyramp app was asked for a read-only GitHub token, but its token grants ${JSON.stringify(u.permissions??null)}`);!i&&!s&&u.anthropicApiKey&&(this.modelKey=u.anthropicApiKey),this.deps.onTokenGranted?.(t);let d=s?"Renewed":"Received";return l.token&&this.deps.log?.(`${d} ${a} GitHub credentials; they expire at ${u.expiresAt}.`),{token:u.token,expiresAt:l.token?new Date(u.expiresAt).getTime():Number.POSITIVE_INFINITY}},l=>{if(this.deps.onTokenRefused?.(l,t),!(l instanceof nn)||l.code!=="CREDENTIALS_UNAVAILABLE")throw l;let u=f=>[...new Set(f.map(m=>m.namespace))].join(", "),d=this.manifest.sources.map(f=>f.repository);if(new Set(d.map(f=>f.providerAccountId)).size>1)throw new nn(`${l.message}. The run's repositories are on more than one GitHub account (${u(d)}), which Skyramp does not support yet.`,l.status,l.code);let p=u([...d,this.manifest.execution.repository]);throw new nn(`${l.message}. Check the Skyramp GitHub App installation on ${p}: 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]=c,(await c).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??rn();return this.revocation??=r.revokeToken?this.revokeIssued(n=>r.revokeToken(n,this.sourceFetch(t))):Promise.resolve([]),this.revocation}async revokeIssued(t){let r=[...this.issuedTokens],n=Promise.all(r.map(o=>this.revokeOne(o,t)));await Promise.all(Object.values(this.credentials).map(o=>o.catch(()=>{})));let s=this.issuedTokens.filter(o=>!r.includes(o));return[...await n,...await Promise.all(s.map(o=>this.revokeOne(o,t)))].filter(o=>o!==void 0)}async revokeOne(t,r){try{await r(t);return}catch(n){return`token ${this.issuedTokens.indexOf(t)+1} of ${this.issuedTokens.length}: ${n instanceof Error?n.message:String(n)}`}}};async function Itt(e,t,r){Stt(e,"run id"),Jce(r.origin);let n=v6(e,t),s=`/api/v1/runner/runs/${e}/attempts`,i;try{i=await hw(r,"POST",s,n)}catch(l){if(!(l instanceof nn&&l.status===400&&l.path==="$.statedPins"))throw l;n=v6(e,t,{statedPins:!1}),i=await hw(r,"POST",s,n)}let o=cQe(i);if(o.manifest.runId!==e)throw new Error(`The app answered the handshake of run ${e} with the manifest of another run (${o.manifest.runId})`);let a=o.manifest.sources.find(l=>l.repository.provider!==n.execution.provider);if(a)throw new Error(`The manifest of run ${e} names ${a.repository.namespace}/${a.repository.name} on ${a.repository.provider}, but this job runs on ${n.execution.provider}`);Dar(o.manifest,[...o.deployedRevisions??[],...o.statedRevisions??[]]),o.runToken&&r.mask?.(o.runToken);let c=o.runToken?{entitlements:o.entitlements??[],runToken:o.runToken}:void 0;return new Hce(o.attempt.id,o.attempt.number,new Date(o.attempt.deadlineAt),o.manifest,r,c,o.requestedBy??void 0,o.writeAllowed,o.claudeCodeVersion??void 0,o.deployedRevisions??[],o.statedRevisions??[],o.runSettings,o.credentialRelay===!0)}function Dar(e,t){if(t.length===0)return;if(e.trigger.kind!=="schedule")throw new Error(`The app pinned an attempt of a ${e.trigger.kind} run; only a scheduled run's retry is pinned to an earlier attempt's read`);let r=new Set(e.sources.map(s=>Lr(s.repository))),n=new Set;for(let s of t){let i=Lr(s.repository);if(!r.has(i))throw new Error(`The app pinned the attempt to repository ${s.repository.providerRepositoryId}, which is not a source of the run`);if(n.has(i))throw new Error(`The app pinned repository ${s.repository.providerRepositoryId} twice`);n.add(i)}}var Oar=6e4;async function Rtt(e){return sQe.parse(await e.send("POST",`/api/v1/runner/attempts/${e.attemptId}/heartbeat`,{schemaVersion:1}))}async function Ttt(e,t=()=>new Date){if(e.closure)return e.closure;let r=await Rtt(e).then(n=>b6(n,t())).catch(()=>null);return r&&(e.closure=r),r}function ktt(e,t,r={}){let n=!1,s,i=async()=>{try{let a=b6(await Rtt(e),(r.now??(()=>new Date))());a&&!n&&(n=!0,e.closure=a,t(a))}catch(a){a instanceof nn&&(n=!0)}n||o(r.intervalMs??Oar)},o=a=>{s=setTimeout(()=>{i()},a),s.unref?.()};return o(0),{stop(){n=!0,clearTimeout(s)}}}var Qar=10*6e4,e_=(e,t,r)=>(0,Ett.execFileSync)("git",t,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"],env:r??process.env,timeout:Qar}).trim(),Mar=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];async function Btt(e,t){let r=t.git??e_,n=t.host??rn(),s=t.cloneUrl??(p=>n.cloneUrl(p)),{sources:i}=e.manifest;for(let p of i){if(!p.merge&&Mar.includes(p.reason)&&!p.change?.base)throw new Error(`${p.repository.namespace}/${p.repository.name} was selected as ${p.reason}, but its change names no base revision to compare it with`);if(p.change?.kind==="pull_request"&&!p.change.base)throw new Error(`${p.repository.namespace}/${p.repository.name} pull request ${p.change.number} names no base revision to compare it with`);n.checkSourceName(p.repository)}if(ds.existsSync(t.workspace)&&ds.lstatSync(t.workspace).isSymbolicLink())throw new Error(`The sources workspace ${t.workspace} is a symlink; refusing to clear it`);ds.rmSync(t.workspace,{recursive:!0,force:!0});let o=new Map((e.manifest.baseline?.sources??[]).map(p=>[Lr(p.repository),p.revision])),a=[];for(let p of i){let{namespace:f,name:m}=p.repository,A=ol.join(t.workspace,f,m);ds.mkdirSync(A,{recursive:!0});let E={...process.env,GIT_TERMINAL_PROMPT:"0",...n.gitAuthEnv(await e.token())};r(A,["init","-q"]),r(A,["remote","add","origin",s(p.repository)]);let g=t.observed?.get(Lr(p.repository))??p.revision,w=p.change?.base??p.compareWith??(p.merge&&p.ref?{ref:p.ref,revision:p.revision}:void 0),S=o.get(Lr(p.repository)),x=(p.merge??[]).map(I=>I.revision);r(A,["fetch","-q","--no-tags","origin",g,...w&&w.revision!==g?[w.revision]:[],...x],E);let R=!0;if(!w&&S!==void 0&&S!==g){let I=!0;try{r(A,["fetch","-q","--no-tags","origin",S],E)}catch(B){if(Kce(B))throw B;I=!1}R=I&&qar(A,S,g,r)}a.push({source:p,dir:A,revision:g,base:w??void 0,baseline:S,contained:R})}let c=a.some(({contained:p})=>!p),l=[],u=Far(i),d=i.filter(p=>p.merge).length;for(let{source:p,dir:f,revision:m,base:A,baseline:E}of a){let{namespace:g,name:w}=p.repository,S=A??(p.ref?{ref:p.ref,revision:c?m:E??m}:null);if(S&&(r(f,["update-ref",`refs/remotes/origin/${S.ref}`,S.revision]),r(f,["symbolic-ref","refs/remotes/origin/HEAD",`refs/remotes/origin/${S.ref}`])),p.ref?r(f,["checkout","-q","-B",p.ref,m]):r(f,["checkout","-q","--detach",m]),p.merge){Uar(f,{repository:p.repository,merge:p.merge},p.ref??m,r),r(f,["config",Gce,m]),r(f,["config",B2,(d>1?u:void 0)??p.merge.map(Ntt).join(" ")]),l.push({repository:p.repository,revision:m,path:f,slug:`${g}/${w}`});continue}u&&!p.change&&!p.compareWith&&r(f,["config",B2,u]),l.push({repository:p.repository,revision:r(f,["rev-parse","HEAD"]),path:f,slug:`${g}/${w}`})}return{sources:l,firstQualification:c}}function Far(e){let t=e.flatMap(r=>r.merge?[{slug:`${r.repository.namespace}/${r.repository.name}`.toLowerCase(),merge:r.merge}]:[]);if(t.length)return t.sort((r,n)=>r.slug<n.slug?-1:r.slug>n.slug?1:0).map(({slug:r,merge:n})=>[`repository:${r}`,...n.map(Ntt)].join(" ")).join(" ")}var t_=class extends Error{constructor(r,n,s,i,o=!0){let{namespace:a,name:c}=r.repository,l=s.map(p=>zce(r.merge[p])),u=l.length===2?`${l[0]} and ${l[1]} do not merge cleanly`:`${l[0]} does not merge cleanly onto ${n}${Lar(s)?" with the revisions merged before it":""}`,d=o?"":"; this git cannot tell which of them it conflicts with";super(`${a}/${c}: ${u} (${i.join(", ")})${d}`);this.source=r;this.base=n;this.positions=s;this.files=i;this.name="MergeConflict"}source;base;positions;files;get detail(){let{provider:r,providerAccountId:n,providerRepositoryId:s}=this.source.repository;return{repository:{provider:r,providerAccountId:n,providerRepositoryId:s},revisions:[...this.positions],files:this.files.slice(0,S6)}}},Lar=e=>e.length===1&&e[0]>0,zce=e=>e.kind==="pull_request"?`PR #${e.number}`:`branch ${e.ref}`,Ntt=e=>e.kind==="pull_request"?`pull_request:${e.number}`:`branch:${e.ref}`;function Uar(e,t,r,n){let s=["-c",`user.name=${gs}`,"-c",`user.email=${wi}`];for(let[i,o]of t.merge.entries())try{n(e,[...s,"merge","-q","--no-ff","--no-edit","-m",`Testbot: merge ${zce(o)}`,o.revision])}catch(a){let c=[];try{c=n(e,["diff","--name-only","--diff-filter=U"]).split(`
|
|
507
|
+
`)[0],w={name:gs,email:wi},S=!!f.signOff;if(!S&&t.listCommitChecks){let Z=i?.headSha??Hi(u,["rev-parse","HEAD"]);try{S=(await t.listCommitChecks({repository:o,revision:Z}))?.records.some(U=>U.name.trim().toLowerCase()==="dco"&&U.headSha===Z&&(!U.repository||U.repository.toLowerCase()===o.toLowerCase()))??!1}catch{console.warn(`[deliver] could not read commit checks for ${o}`)}}let x=e.inputs.deliverRemote||"origin",R=itt(u,Gce),I=itt(u,B2);if(R&&!I)throw new Error(`${o}: the checkout records a merged base but not what it merged`);let B=R?$ce(void 0,void 0,u):i?i.headBranch||$ce(e.inputs.headBranch,e.inputs.baseBranch,u):$ce(void 0,void 0,u),T=e.inputs.pullRequests;i?.prNumber!=null&&!T?.some(Z=>Z.repository.toLowerCase()===o.toLowerCase())&&(T=[...T??[],{repository:o,number:String(i.prNumber)}]);let Q=T?.some(Z=>Z.repository.toLowerCase()===o.toLowerCase())?void 0:e.inputs.deliveryOrigin,J=R||!Q?I:void 0,V=J?mar(o,B,J):har(T,o,B,Q),oe=qce(B,e.inputs.deliverBranch)+(J?`-merge-${V}`:Q?`-source-${Q.number}-${V}`:""),ce=rZe(S2(Aar(E,e,n),{audience:"testbot-pr",requestedBy:e.inputs.requestedBy,sourcePullRequest:Q&&`${Q.repository.namespace}/${Q.repository.name}#${Q.number}`}),e.inputs.skyrampRunUrl),D=i?"pr-body.md":`pr-body-${ctt(o)}.md`,P=yg.join(e.outputsDir,D);Xd.writeFileSync(P,ce);let N=Hi(u,["rev-parse","HEAD"]),K=R??N;Hi(u,["checkout","-B",oe]),a=oe,Hi(u,["reset"]);for(let Z of s)gar(yg.join(u,Z),p);let k=[];for(let Z of s)try{Hi(u,["--literal-pathspecs","add","--",Z])}catch{k.push(Z)}try{Hi(u,["diff","--cached","--quiet"])}catch{try{let Z=Hi(u,["interpret-trailers","--trailer",`${MG}: ${V}`,"--trailer",`${xx}: ${N}`,"--trailer",`${kae}: ${K}`],A),Y=S?OG(Z,w):Z;Hi(u,["-c",`user.name=${w.name}`,"-c",`user.email=${w.email}`,"commit","-m",Y])}catch(Z){throw new k2(Z)}c=!0}l=Hi(u,["rev-parse","HEAD"]);let q,L=R??i?.headSha;if(c&&L&&L!==N){let Z=!1;try{Hi(u,["checkout","-q","-B",a,L]),Z=!0,Hi(u,["-c",`user.name=${w.name}`,"-c",`user.email=${w.email}`,"cherry-pick","--keep-redundant-commits",l]),Z=!1,fg(Y=>Hi(u,Y),L),l=Hi(u,["rev-parse","HEAD"])}catch(Y){try{Hi(u,["cherry-pick","--abort"])}catch{}Hi(u,["checkout","-q","-B",a,l]);let U=YE(Zl(Y),1/0);if(R&&!Z)throw Y;if(R)return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:x,base:B,committed:c,commitSha:l,pushed:!1,prAction:"skipped",prTitle:g,unstaged:k,reason:`the tests do not apply to ${B} at ${R.slice(0,12)} without the merged revisions (${U}), so no tests PR was opened`}};q=`tests committed on the checkout's merge commit (re-cut onto ${L.slice(0,12)} failed: ${U})`}}let H=i?{}:{repositoryPath:u,repoSlug:o,devPr:null};if(!c){let Z=await t.markTestsPrUnchanged({branch:a,...H});return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:x,base:B,committed:!1,commitSha:l,pushed:!1,prAction:Z.action==="unchanged"?"unchanged":"skipped",prUrl:Z.url,prTitle:g,unstaged:k,reason:Z.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 W=await t.publishTestsPr({repositoryPath:u,...H,remote:x,branch:a,base:B,commitSha:l,title:g,bodyFile:P,mode:e.inputs.deliverMode,deliveryOwner:V,...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:x,base:W.base,requestedBase:B,committed:c,commitSha:l,pushed:W.pushed,...W.pushedCommits?{pushedCommits:W.pushedCommits}:{},...W.deliveredCommit?{deliveredCommit:W.deliveredCommit}:{},prAction:W.action,...W.retargetedAs?{retargetedAs:W.retargetedAs}:{},prUrl:W.url,prTitle:g,...W.failure?{prFailure:W.failure,prDetail:W.detail}:{},...q?{cutNote:q}:{},...W.action==="skipped"&&W.detail?{reason:W.detail}:{},unstaged:k}}}catch(u){return{thrown:!0,record:{schemaVersion:1,repository:o,branch:a,committed:c,commitSha:l,pushed:!1,prAction:"failed",...Car(u),unstaged:[]}}}}var ltt={name:"deliver",timeoutMinutes:5,execute:Ear,validateInput:e=>{let t=qC(e);return t?{ok:!1,reasons:[t]}:par(e)},requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var Go=require("crypto");var utt=Buffer.from("302a300506032b656e032100","hex"),dtt=e=>e.export({format:"der",type:"spki"}).subarray(utt.length);function ptt(e){let t=Buffer.from(e,"base64");if(t.length!==32)throw new Error("A relay key is 32 bytes of X25519");return(0,Go.createPublicKey)({key:Buffer.concat([utt,t]),format:"der",type:"spki"})}function ftt(e,t,r,n){let s=(0,Go.diffieHellman)({privateKey:e,publicKey:t});return Buffer.from((0,Go.hkdfSync)("sha256",s,Buffer.concat([r,n]),VOe,32))}var N2=class e{constructor(t,r){this.privateKey=t;this.publicKey=r}privateKey;publicKey;static generate(){let{privateKey:t,publicKey:r}=(0,Go.generateKeyPairSync)("x25519");return new e(t,dtt(r).toString("base64"))}open(t,r){let n=Buffer.from(t.ephemeralPublicKey,"base64"),s=ftt(this.privateKey,ptt(t.ephemeralPublicKey),n,Buffer.from(this.publicKey,"base64")),i=(0,Go.createDecipheriv)("aes-256-gcm",s,Buffer.from(t.iv,"base64"));return i.setAAD(Buffer.from(r,"utf8")),i.setAuthTag(Buffer.from(t.tag,"base64")),Buffer.concat([i.update(Buffer.from(t.ciphertext,"base64")),i.final()]).toString("utf8")}};function htt(e,t,r){let n=ptt(t),s=(0,Go.generateKeyPairSync)("x25519"),i=dtt(s.publicKey),o=ftt(s.privateKey,n,i,Buffer.from(t,"base64")),a=(0,Go.randomBytes)(12),c=(0,Go.createCipheriv)("aes-256-gcm",o,a);c.setAAD(Buffer.from(r,"utf8"));let l=Buffer.concat([c.update(e,"utf8"),c.final()]);return{ephemeralPublicKey:i.toString("base64"),iv:a.toString("base64"),ciphertext:l.toString("base64"),tag:c.getAuthTag().toString("base64")}}var Rar=10*6e4;function Tar(e,t){return e.getTime()-t.getTime()-Rar}var mtt="This attempt revoked its scoped GitHub credentials; it mints no more.",kar=10*6e4;var Bar=e=>!!e&&Object.keys(e).length===1&&e.contents==="read",Nar=3e4,_ar=3,gtt=30,nn=class extends Error{constructor(r,n,s,i){super(r);this.status=n;this.code=s;this.path=i}status;code;path},Zd=class extends Error{},$x=class extends Zd{},ZN=class extends $x{};function Jce(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 Stt(e,t){if(!lm.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}function Yce(e,t){return`${e.replace(/\/+$/,"")}/runs/${t}`}function Ctt(e,t,r,n){throw t<500&&t!==429?new nn(e,t,r,n):t===503&&r==="RUNNER_PROVIDER_NOT_READY"?new ZN(e):t===503&&r==="RUN_NOT_READY"?new $x(e):new Zd(e)}async function vtt(e,t,r,n){let s=Jce(e.origin),i,o=0;for(let a=1;a<=_ar||i instanceof $x;a+=1){if(i instanceof $x){if(o===gtt)throw i;o+=1,a-=1,e.log?.(`${i.message}; trying again (${o} of ${gtt}).`),await new Promise(c=>setTimeout(c,e.readyWaitMs??1e4))}else a>1&&await new Promise(c=>setTimeout(c,(e.retryDelayMs??2e3)*(a-1)));try{let c=await e.idToken(s),l=await(e.fetch??fetch)(new URL(t,s).toString(),{...r(c),redirect:"error",signal:AbortSignal.timeout(Nar)}).catch(u=>{throw new Zd(u instanceof Error?u.message:String(u),{cause:u})});return await n(l)}catch(c){if(c instanceof nn)throw c;i=c}}throw i}function xtt(e,t,r,n,s){let i=n.headers.get("cf-ray");e.log?.(`Testbot V3: ${t} ${r} answered ${n.status}${i?`, cf-ray ${i}`:""}: ${s.replace(/\s+/g," ").slice(0,200)}`)}function hw(e,t,r,n){return vtt(e,r,i=>({method:t,headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json",Accept:"application/json"},body:t==="GET"?void 0:JSON.stringify(n)}),async i=>{let o=await i.text().catch(()=>""),a={};try{a=JSON.parse(o)}catch{}if(i.ok)return a.data;xtt(e,t,r,i,o);let c=a.error?.fields,l=typeof c?.path=="string"&&typeof c.reason=="string"?` at ${c.path}: ${c.reason}`:"",u=`The Skyramp app refused ${t} ${r}: ${i.status} ${a.error?.code??"no error code"}${l}`;return Ctt(u,i.status,a.error?.code,typeof c?.path=="string"?c.path:void 0)})}function Par(e,t,r){return vtt(e,t,s=>({method:"GET",headers:{Authorization:`Bearer ${s}`,Accept:"application/octet-stream"}}),async s=>{if(!s.ok)return xtt(e,"GET",t,s,await s.text().catch(()=>"")),Ctt(`The Skyramp app refused GET ${t}: ${s.status}`,s.status);let i=Buffer.from(await s.arrayBuffer());if(i.length>r)throw new nn(`The Skyramp app answered GET ${t} with more than ${r} bytes`,s.status);return i})}var Hce=class{constructor(t,r,n,s,i,o,a,c,l,u=[],d=[],p,f=!1){this.attemptId=t;this.attemptNumber=r;this.deadlineAt=n;this.manifest=s;this.deps=i;this.license=o;this.requestedBy=a;this.writeAllowed=c;this.claudeCodeVersion=l;this.deployedPins=u;this.statedPins=d;this.runSettings=p;this.credentialRelay=f}attemptId;attemptNumber;deadlineAt;manifest;deps;license;requestedBy;writeAllowed;claudeCodeVersion;deployedPins;statedPins;runSettings;credentialRelay;budgetMs(t){return Tar(this.deadlineAt,t)}get skyrampRunUrl(){return Yce(Jce(this.deps.origin),this.manifest.runId)}send(t,r,n){return hw(this.deps,t,r,n)}readBytes(t,r){return Par(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(mtt);let r=(this.deps.now??(()=>new Date))().getTime(),n=this.credentials[t],s=n&&await n.catch(()=>{});if(this.credentials[t]!==n)return(await this.credentials[t]).token;if(s&&s.expiresAt-r>=kar)return s.token;if(this.revocation)throw new Error(mtt);let i=t==="read",o=i?{schemaVersion:1,access:t}:{schemaVersion:1},a=i?"read-only":"scoped",c=this.send("POST",`/api/v1/runner/attempts/${this.attemptId}/credentials`,o).then(l=>{let u={...l,token:l.token??this.jobToken()};if(this.issuedTokens.push(u.token),this.deps.mask?.(u.token),u.anthropicApiKey&&this.deps.mask?.(u.anthropicApiKey),i&&l.token&&!Bar(u.permissions))throw new Error(`The Skyramp app was asked for a read-only GitHub token, but its token grants ${JSON.stringify(u.permissions??null)}`);!i&&!s&&u.anthropicApiKey&&(this.modelKey=u.anthropicApiKey),this.deps.onTokenGranted?.(t);let d=s?"Renewed":"Received";return l.token&&this.deps.log?.(`${d} ${a} GitHub credentials; they expire at ${u.expiresAt}.`),{token:u.token,expiresAt:l.token?new Date(u.expiresAt).getTime():Number.POSITIVE_INFINITY}},l=>{if(this.deps.onTokenRefused?.(l,t),!(l instanceof nn)||l.code!=="CREDENTIALS_UNAVAILABLE")throw l;let u=f=>[...new Set(f.map(m=>m.namespace))].join(", "),d=this.manifest.sources.map(f=>f.repository);if(new Set(d.map(f=>f.providerAccountId)).size>1)throw new nn(`${l.message}. The run's repositories are on more than one GitHub account (${u(d)}), which Skyramp does not support yet.`,l.status,l.code);let p=u([...d,this.manifest.execution.repository]);throw new nn(`${l.message}. Check the Skyramp GitHub App installation on ${p}: 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]=c,(await c).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??rn();return this.revocation??=r.revokeToken?this.revokeIssued(n=>r.revokeToken(n,this.sourceFetch(t))):Promise.resolve([]),this.revocation}async revokeIssued(t){let r=[...this.issuedTokens],n=Promise.all(r.map(o=>this.revokeOne(o,t)));await Promise.all(Object.values(this.credentials).map(o=>o.catch(()=>{})));let s=this.issuedTokens.filter(o=>!r.includes(o));return[...await n,...await Promise.all(s.map(o=>this.revokeOne(o,t)))].filter(o=>o!==void 0)}async revokeOne(t,r){try{await r(t);return}catch(n){return`token ${this.issuedTokens.indexOf(t)+1} of ${this.issuedTokens.length}: ${n instanceof Error?n.message:String(n)}`}}};async function Itt(e,t,r){Stt(e,"run id"),Jce(r.origin);let n=v6(e,t),s=`/api/v1/runner/runs/${e}/attempts`,i;try{i=await hw(r,"POST",s,n)}catch(l){if(!(l instanceof nn&&l.status===400&&l.path==="$.statedPins"))throw l;n=v6(e,t,{statedPins:!1}),i=await hw(r,"POST",s,n)}let o=cQe(i);if(o.manifest.runId!==e)throw new Error(`The app answered the handshake of run ${e} with the manifest of another run (${o.manifest.runId})`);let a=o.manifest.sources.find(l=>l.repository.provider!==n.execution.provider);if(a)throw new Error(`The manifest of run ${e} names ${a.repository.namespace}/${a.repository.name} on ${a.repository.provider}, but this job runs on ${n.execution.provider}`);Dar(o.manifest,[...o.deployedRevisions??[],...o.statedRevisions??[]]),o.runToken&&r.mask?.(o.runToken);let c=o.runToken?{entitlements:o.entitlements??[],runToken:o.runToken}:void 0;return new Hce(o.attempt.id,o.attempt.number,new Date(o.attempt.deadlineAt),o.manifest,r,c,o.requestedBy??void 0,o.writeAllowed,o.claudeCodeVersion??void 0,o.deployedRevisions??[],o.statedRevisions??[],o.runSettings,o.credentialRelay===!0)}function Dar(e,t){if(t.length===0)return;if(e.trigger.kind!=="schedule")throw new Error(`The app pinned an attempt of a ${e.trigger.kind} run; only a scheduled run's retry is pinned to an earlier attempt's read`);let r=new Set(e.sources.map(s=>Lr(s.repository))),n=new Set;for(let s of t){let i=Lr(s.repository);if(!r.has(i))throw new Error(`The app pinned the attempt to repository ${s.repository.providerRepositoryId}, which is not a source of the run`);if(n.has(i))throw new Error(`The app pinned repository ${s.repository.providerRepositoryId} twice`);n.add(i)}}var Oar=6e4;async function Rtt(e){return sQe.parse(await e.send("POST",`/api/v1/runner/attempts/${e.attemptId}/heartbeat`,{schemaVersion:1}))}async function Ttt(e,t=()=>new Date){if(e.closure)return e.closure;let r=await Rtt(e).then(n=>b6(n,t())).catch(()=>null);return r&&(e.closure=r),r}function ktt(e,t,r={}){let n=!1,s,i=async()=>{try{let a=b6(await Rtt(e),(r.now??(()=>new Date))());a&&!n&&(n=!0,e.closure=a,t(a))}catch(a){a instanceof nn&&(n=!0)}n||o(r.intervalMs??Oar)},o=a=>{s=setTimeout(()=>{i()},a),s.unref?.()};return o(0),{stop(){n=!0,clearTimeout(s)}}}var Qar=10*6e4,e_=(e,t,r)=>(0,Ett.execFileSync)("git",t,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"],env:r??process.env,timeout:Qar}).trim(),Mar=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];async function Btt(e,t){let r=t.git??e_,n=t.host??rn(),s=t.cloneUrl??(p=>n.cloneUrl(p)),{sources:i}=e.manifest;for(let p of i){if(!p.merge&&Mar.includes(p.reason)&&!p.change?.base)throw new Error(`${p.repository.namespace}/${p.repository.name} was selected as ${p.reason}, but its change names no base revision to compare it with`);if(p.change?.kind==="pull_request"&&!p.change.base)throw new Error(`${p.repository.namespace}/${p.repository.name} pull request ${p.change.number} names no base revision to compare it with`);n.checkSourceName(p.repository)}if(ds.existsSync(t.workspace)&&ds.lstatSync(t.workspace).isSymbolicLink())throw new Error(`The sources workspace ${t.workspace} is a symlink; refusing to clear it`);ds.rmSync(t.workspace,{recursive:!0,force:!0});let o=new Map((e.manifest.baseline?.sources??[]).map(p=>[Lr(p.repository),p.revision])),a=[];for(let p of i){let{namespace:f,name:m}=p.repository,A=ol.join(t.workspace,f,m);ds.mkdirSync(A,{recursive:!0});let E={...process.env,GIT_TERMINAL_PROMPT:"0",...n.gitAuthEnv(await e.token())};r(A,["init","-q"]),r(A,["remote","add","origin",s(p.repository)]);let g=t.observed?.get(Lr(p.repository))??p.revision,w=p.change?.base??p.compareWith??(p.merge&&p.ref?{ref:p.ref,revision:p.revision}:void 0),S=o.get(Lr(p.repository)),x=(p.merge??[]).map(I=>I.revision);r(A,["fetch","-q","--no-tags","origin",g,...w&&w.revision!==g?[w.revision]:[],...x],E);let R=!0;if(!w&&S!==void 0&&S!==g){let I=!0;try{r(A,["fetch","-q","--no-tags","origin",S],E)}catch(B){if(Kce(B))throw B;I=!1}R=I&&qar(A,S,g,r)}a.push({source:p,dir:A,revision:g,base:w??void 0,baseline:S,contained:R})}let c=a.some(({contained:p})=>!p),l=[],u=Far(i),d=i.filter(p=>p.merge).length;for(let{source:p,dir:f,revision:m,base:A,baseline:E}of a){let{namespace:g,name:w}=p.repository,S=A??(p.ref?{ref:p.ref,revision:c?m:E??m}:null);if(S&&(r(f,["update-ref",`refs/remotes/origin/${S.ref}`,S.revision]),r(f,["symbolic-ref","refs/remotes/origin/HEAD",`refs/remotes/origin/${S.ref}`])),p.ref?r(f,["checkout","-q","-B",p.ref,m]):r(f,["checkout","-q","--detach",m]),p.merge){Uar(f,{repository:p.repository,merge:p.merge},p.ref??m,r),r(f,["config",Gce,m]),r(f,["config",B2,(d>1?u:void 0)??p.merge.map(Ntt).join(" ")]),l.push({repository:p.repository,revision:m,path:f,slug:`${g}/${w}`});continue}u&&!p.change&&!p.compareWith&&r(f,["config",B2,u]),l.push({repository:p.repository,revision:r(f,["rev-parse","HEAD"]),path:f,slug:`${g}/${w}`})}return{sources:l,firstQualification:c}}function Far(e){let t=e.flatMap(r=>r.merge?[{slug:`${r.repository.namespace}/${r.repository.name}`.toLowerCase(),merge:r.merge}]:[]);if(t.length)return t.sort((r,n)=>r.slug<n.slug?-1:r.slug>n.slug?1:0).map(({slug:r,merge:n})=>[`repository:${r}`,...n.map(Ntt)].join(" ")).join(" ")}var t_=class extends Error{constructor(r,n,s,i,o=!0){let{namespace:a,name:c}=r.repository,l=s.map(p=>zce(r.merge[p])),u=l.length===2?`${l[0]} and ${l[1]} do not merge cleanly`:`${l[0]} does not merge cleanly onto ${n}${Lar(s)?" with the revisions merged before it":""}`,d=o?"":"; this git cannot tell which of them it conflicts with";super(`${a}/${c}: ${u} (${i.join(", ")})${d}`);this.source=r;this.base=n;this.positions=s;this.files=i;this.name="MergeConflict"}source;base;positions;files;get detail(){let{provider:r,providerAccountId:n,providerRepositoryId:s}=this.source.repository;return{repository:{provider:r,providerAccountId:n,providerRepositoryId:s},revisions:[...this.positions],files:this.files.slice(0,S6)}}},Lar=e=>e.length===1&&e[0]>0,zce=e=>e.kind==="pull_request"?`PR #${e.number}`:`branch ${e.ref}`,Ntt=e=>e.kind==="pull_request"?`pull_request:${e.number}`:`branch:${e.ref}`;function Uar(e,t,r,n){let s=["-c",`user.name=${gs}`,"-c",`user.email=${wi}`];for(let[i,o]of t.merge.entries())try{n(e,[...s,"merge","-q","--no-ff","--no-edit","-m",`Testbot: merge ${zce(o)}`,o.revision])}catch(a){let c=[];try{c=n(e,["diff","--name-only","--diff-filter=U"]).split(`
|
|
508
508
|
`).filter(Boolean)}finally{try{n(e,["merge","--abort"])}catch{}}if(!c.length)throw new Error(`could not merge ${zce(o)}: ${YE(Zl(a),200)}`,{cause:a});let l=t.merge.slice(0,i).map(d=>$ar(e,d.revision,o.revision,n)),u=l.indexOf("no");throw new t_(t,r,u>=0?[u,i]:[i],c,u>=0||!l.includes("unknown"))}}function $ar(e,t,r,n){try{return n(e,["merge-tree","--write-tree","--name-only","--no-messages",t,r]),"yes"}catch(s){return s.status===1?"no":"unknown"}}function Kce(e){return e instanceof Zd||e?.code==="ETIMEDOUT"?!0:DG.test(wN(e))}function qar(e,t,r,n=e_){if(t===r)return!1;try{return n(e,["merge-base","--is-ancestor",t,r]),!0}catch(s){if(s.status===1)return!1;throw s}}async function _tt(e,t={}){let r=t.host??rn(),n={token:()=>e.token(),fetch:e.sourceFetch(t)},s=[];for(let i of e.manifest.sources){let o=i.merge?i.merge.flatMap(u=>u.kind==="pull_request"&&u.number?[u.number]:[]):i.change?.kind==="pull_request"?[i.change.number]:[],{namespace:a,name:c}=i.repository,l=`${a}/${c}`;for(let u of o)try{s.push({repository:l,number:u,...await r.pullRequest(i.repository,u,n)})}catch(d){let p=d instanceof Error?d.message:String(d);s.push({repository:l,number:u,note:`could not be read: ${p}`})}}return s}async function Ptt(e,t,r,n={}){let s=await Dtt(e,t,r,n);return"sha"in s?s.sha.toLowerCase()===r.toLowerCase()?"found":"missing":s.lookup}function Dtt(e,t,r,n){return(n.host??rn()).commit(t,r,{token:()=>e.token(),fetch:e.sourceFetch(n)})}async function Ott(e,t,r,n={}){let s=await Dtt(e,t,r,n);if(!("sha"in s&&/^[0-9a-f]{7,64}$/i.test(r)&&s.sha.toLowerCase().startsWith(r.toLowerCase())))return{error:"lookup"in s&&s.lookup==="unknown"?`GitHub did not answer for commit ${r} in ${t}`:`${r} is not a commit of ${t}`};let i=s.sha.toLowerCase(),[o,a]=t.split("/"),c=n.host??rn(),l=await Gar(e,n.cloneUrl?.({namespace:o,name:a})??c.cloneUrl({namespace:o,name:a}),c,i);return l===void 0?{error:`could not list the branches and tags of ${t} to find commit ${r}`}:l?{sha:i}:{error:`${r} is on no branch or tag of ${t} (a deleted branch's or a fork's commit)`,final:!0}}async function Gar(e,t,r,n){let s=await jar(e,t,r);if(s)try{return e_(s,["for-each-ref","--count=1","--contains",n,"--format=%(refname)"],{...process.env,GIT_NO_LAZY_FETCH:"1"})!==""}catch{return!1}}var Att=new WeakMap,jce=new Set,ytt=!1;function jar(e,t,r){let n=Att.get(e);n||Att.set(e,n=new Map);let s=n.get(t);if(s)return s;let i=Har(e,t,r);return n.set(t,i),i.then(o=>{o||n.delete(t)}),i}async function Har(e,t,r){ytt||process.once("exit",()=>{for(let s of jce)ds.rmSync(s,{recursive:!0,force:!0})}),ytt=!0;let n=ds.mkdtempSync(ol.join(btt.tmpdir(),"testbot-refs-"));jce.add(n);try{return e_(n,["init","-q"]),e_(n,["fetch","-q","--no-tags","--filter=tree:0",t,"+refs/heads/*:refs/remotes/origin/*","+refs/tags/*:refs/tags/*"],{...process.env,GIT_TERMINAL_PROMPT:"0",...r.gitAuthEnv(await e.token())}),n}catch{jce.delete(n),ds.rmSync(n,{recursive:!0,force:!0});return}}function Qtt(e,t){let r=e.sources.find(s=>s.reason==="TRIGGER"&&s.change?.kind==="pull_request"),n=r&&t.find(s=>s.repository.providerRepositoryId===r.repository.providerRepositoryId);return n&&r.change?{repository:n.slug,path:n.path,number:Number(r.change.number)}:void 0}function Mtt(e){let t=e.sources.filter(n=>n.change?.kind==="pull_request"&&(n.reason==="TRIGGER"||n.reason==="MANUAL_OVERRIDE"));if(t.length!==1)return;let r=t[0];return{targetId:e.target.id,repository:r.repository,number:r.change.number}}var zar=[".skyramp/sut/setup.sh",".skyramp/workspace.yml"],r_=class extends Error{};function Ftt(e,t){let r=t===void 0?void 0:e.find(s=>s.slug.toLowerCase()===t.toLowerCase());if(t!==void 0&&!r)throw new r_(`The stored SUT recipe was written in ${t}, which is none of this run's sources (${e.map(s=>s.slug).join(", ")}), so Testbot cannot replay it. Run the Target's SUT setup again so it writes the recipe in one of them.`);let n=r??e.find(s=>zar.some(i=>ds.existsSync(ol.join(s.path,i))))??e[0];return{repositoryPath:n.path,repositorySlug:n.slug,relatedRepos:e.filter(s=>s!==n).map(s=>({slug:s.slug,path:s.path,writable:!0}))}}var Var=y.object({tests:y.object({placements:y.array(y.unknown()).optional()}).passthrough().optional()}).passthrough(),War=y.object({repository:a6,testType:y.nativeEnum(yy),directory:y.string()}).passthrough();function Ltt(e,t){let r=Var.safeParse(e.settings.target??{}),n=[];for(let s of(r.success?r.data.tests?.placements:void 0)??[]){let i=War.safeParse(s);if(!i.success)continue;let{repository:o,testType:a}=i.data,c=t.find(d=>d.repository.provider===o.provider&&d.repository.providerRepositoryId===o.providerRepositoryId),l=i.data.directory.trim(),u=!l||ol.isAbsolute(l)||l.split(/[\\/]/).includes("..");!c||u||n.push({repository:c.slug,testType:a,directory:l})}return n}var Jar=y.object({report:y.object({language:y.string()}).passthrough()}).passthrough();function Xce(e){let t=Jar.safeParse(e?.settings.target);return t.success?lO(t.data.report.language):"en"}var Yar=y.object({environment:y.object({components:y.array(y.unknown()).optional(),dependencies:y.array(y.unknown()).optional()}).passthrough()}).passthrough(),Kar=y.object({name:y.string().min(1),provision:y.literal("existing"),url:y.string().min(1),repository:a6.optional(),revisionUrl:y.string().min(1).optional()}).passthrough(),Xar=y.object({name:y.string().min(1),url:y.string().nullable(),versionUrl:y.string().nullable(),notes:y.string().nullable()}).passthrough();function Zce(e,t){let r=Yar.safeParse(e.settings.target),n=r.success?r.data.environment:{},s=(n.components??[]).flatMap(a=>{let c=Kar.safeParse(a);if(!c.success)return[];let{name:l,url:u,repository:d,revisionUrl:p}=c.data;if(!d)return[{name:l,url:u}];let f=t.sources.find(m=>m.repository.provider===d.provider&&m.repository.providerRepositoryId===d.providerRepositoryId);return f?[{name:l,url:u,repository:`${f.repository.namespace}/${f.repository.name}`,expectedRevision:f.revision,...p?{revisionUrl:p}:{},...f.merge?Vce(f,[]):{}}]:[{name:l,url:u,repository:`${d.provider} repository ${d.providerRepositoryId}`}]}),i=(n.dependencies??[]).flatMap(a=>{let c=Xar.safeParse(a);return c.success?[{name:c.data.name,url:c.data.url,versionUrl:c.data.versionUrl,notes:c.data.notes}]:[]});if(s.length===0&&i.length===0)return;let o=y.object({allowSharedEnvironmentMutation:y.boolean()}).passthrough().safeParse(e.settings.policy);return{components:s,dependencies:i,allowMutation:o.success&&o.data.allowSharedEnvironmentMutation}}var Zar=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);function Vce(e,t){if(!Zar.has(e.reason))return{};if(e.merge)return{touched:!0,mergedSource:!0};let r=`${e.repository.namespace}/${e.repository.name}`,n=e.change?.kind==="pull_request"?e.change.number:void 0,s=n===void 0?void 0:t.find(a=>hm(a.repository,r)&&a.number===n),i=s?.merged===!0?s.mergeCommit:void 0,o=i&&s?.mergedHead?{mergedHead:s.mergedHead}:{};return{touched:!0,acceptedRevisions:{frozen:e.revision,...i&&i!==e.revision?{mergeCommit:i,...o}:{}}}}function ele(e,t,r,n,s){let i=u=>r.sources.find(d=>hm(`${d.repository.namespace}/${d.repository.name}`,u)),o=(e?.components??[]).map(u=>{let d=u.expectedRevision?i(u.repository):void 0;return d?{...u,...Vce(d,s)}:u}),a=dm(t.files)!==void 0,c=t.components.map(u=>{if(u.repository===Fr)return{name:u.name,url:t.address};let d=i(u.repository),p=a?void 0:P6(t,u.name);return{name:u.name,url:t.address,repository:u.repository,...d?{expectedRevision:d.revision}:{},...p?{revisionUrl:p}:{},...a?{revisionScript:!0}:{},...d?Vce(d,s):{}}}),l=y.object({allowSharedEnvironmentMutation:y.boolean()}).passthrough().safeParse(n?.settings.policy);return{components:[...o,...c],dependencies:e?.dependencies??[],allowMutation:e?.allowMutation??(l.success&&l.data.allowSharedEnvironmentMutation)}}function Utt(e){let t=r=>e.testResults.filter(n=>n.status===r).length;return{passed:t("Pass"),failed:t("Fail"),skipped:t("Skipped")}}function ecr(e){let{passed:t,failed:r,skipped:n}=Utt(e);return t+r===0?{sufficiency:"insufficient",rationale:n>0?`Every test was skipped (${n}), 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${n?`, ${n} skipped`:""}.`,gaps:[],acceptedEvidence:[],actionRequired:[]}}function tcr({notTranslated:e,...t},r){let n=t.testResults.map(l=>({result:l,repository:l.repository??r,path:l.fileName||l.testType})),s=new Map;for(let l of n){let u=`${l.repository}:${l.result.testType}:${l.path}`;s.set(u,(s.get(u)??0)+1)}let i=n.map(({result:l,repository:u,path:d})=>{let p=(s.get(`${u}:${l.testType}:${d}`)??0)>1;return l.resultId??Ry(u,l.testType,d,p&&l.endpoint||void 0)}),o=new Map;for(let l of i)o.set(l,(o.get(l)??0)+1);let a=new Set(i.filter(l=>o.get(l)===1)),c=n.map(({result:l,repository:u},d)=>{let p=i[d],f=p;if(o.get(p)>1&&a.has(p))for(let m=2;a.has(f)||f===p;m+=1)f=p.includes("#")?`${p}.${m}`:`${p}#${m}`;return a.add(f),{...l,repository:u,resultId:f}});return{...t,testResults:c,...rcr(t,c,r),validation:icr(t,ncr(t,t.validation??ecr(t))),traceVersion:1}}function rcr(e,t,r){if(!e.testExecutionContexts)return{};let n=new Set,s=a=>{let c=a;for(let l=2;n.has(c);l+=1)c=`${a}#${l}`;return n.add(c),c},i=[],o=new Map;for(let{repository:a,...c}of e.testExecutionContexts){let l=c.status==="not_run"?[]:t.filter(u=>u.fileName===c.test&&u.repository===(a?.trim()||r));l.length||i.push(c);for(let{resultId:u}of l){let d=o.get(u),p=d!==void 0&&i[d].cleanup.status==="failed"?i[d].cleanup:c.cleanup,f={...c,cleanup:p,test:u,resultId:u};d===void 0?o.set(u,i.push(f)-1):i[d]=f}}for(let a of i)a.resultId&&n.add(a.resultId);return{testExecutionContexts:i.map(a=>a.resultId?a:{...a,test:s(a.test.slice(0,512))}).slice(0,5e3)}}function ncr(e,t){let{passed:r,failed:n}=Utt(e);return t.sufficiency!=="sufficient"||r+n>0||t.acceptedEvidence.length>0?t:{...t,sufficiency:"insufficient",gaps:["No test ran and no existing evidence was accepted, so nothing was validated."]}}function _2(e){let t=e.modelProviderFailure;return t?Object.entries(e.stages).some(([n,s])=>n!=="report"&&n!=="deliver"&&s?.status==="passed"&&s.attempts.length>0)?void 0:t:void 0}var $tt=e=>e.kind==="permanent"?"model_provider_denied":"model_provider_unavailable",scr={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};function icr(e,t){if(t.sufficiency==="sufficient")return t;let r=(e.caveats??[]).map(s=>scr[s.kind]).filter(s=>s!==void 0),n=[...new Set(r)].filter(s=>!t.actionRequired.includes(s));return n.length?{...t,actionRequired:[...n,...t.actionRequired]}:t}function ocr(e,t,r){let{language:n,report:s}=t;if(n==="en")return;let i={language:n,businessCaseAnalysis:s.businessCaseAnalysis},o=(m,A,E)=>Array.isArray(m)&&Array.isArray(A)&&m.length===A.length?m.map(g=>({[E]:g[E]})):void 0,a=e.validation;s.validation&&a&&a.rationale===r.validation.rationale&&JSON.stringify(a.gaps)===JSON.stringify(r.validation.gaps)&&s.validation.gaps.length===r.validation.gaps.length&&(i.validation={rationale:s.validation.rationale,gaps:[...s.validation.gaps]});let c=new Set((r.changes??[]).map(m=>m.id)),l=(s.changes??[]).filter(m=>c.has(m.id)).map(({id:m,text:A})=>({id:m,text:A}));l.length&&(i.changes=l);let u=o(s.issuesFound,r.issuesFound,"description");u&&(i.issuesFound=u);let d=o(s.newTestsCreated,r.newTestsCreated,"description");d&&(i.newTestsCreated=d);let p=o(s.testResults,r.testResults,"details");p&&(i.testResults=p);let f=o(s.caveats,r.caveats,"text");return f&&(i.caveats=f),i}async function qtt(e,t){let r=$n([...e.issuedTokens,...t.secrets??[]]),n={...tcr(t.report,t.workingSlug),...t.notTranslated?{notTranslated:t.notTranslated}:{}},s=t.translated&&ocr(t.report,t.translated,n),i=a=>lQe({manifest:e.manifest,attemptNumber:e.attemptNumber,checkedOut:t.sources.map(c=>({repository:c.repository,revision:c.revision})),firstQualification:t.firstQualification,generatedTests:_r(t.delivery,r),producer:t.producer,report:_r(a&&s?{...n,display:s}:n,r),githubWrites:t.githubWrites}),o=i(!0);s&&Buffer.byteLength(JSON.stringify(o),"utf8")>FOe&&(o=i(!1)),await e.send("PUT",`/api/v1/runner/attempts/${e.attemptId}/report`,o)}async function P2(e,t,r=[]){let n=UOe(e.manifest,_r(t,$n([...e.issuedTokens,...r])));await e.send("PUT",`/api/v1/runner/attempts/${e.attemptId}/deployed-revisions`,n)}async function tle(e){let t=rQe.parse(await e.send("GET",`/api/v1/runner/attempts/${e.attemptId}/configuration`,void 0)),r=e.manifest.configuration,{configuration:n,capture:s}=t;if(n.captureId!==r.captureId||n.revision!==r.revision||n.hash!==r.hash||s.hash!==r.hash||aQe(s)!==r.hash)throw new Error("The app answered the configuration of another capture than the manifest names");return t}var Wce=class extends Error{};async function D2(e){let{runtimePlan:t,testEnvironment:r}=nQe.parse(await e.send("GET",`/api/v1/runner/attempts/${e.attemptId}/runtime-plan`,void 0));if(t&&iQe(t.files,t.recipeRepository??t.repository)!==t.contentHash)throw new Wce(`Stored SUT recipe version ${t.version} does not match its hash`);return{runtimePlan:t,testEnvironment:r??null}}async function Gtt(e,t,r=()=>{}){try{ds.rmSync(t,{recursive:!0,force:!0})}catch{}let n=e.manifest.requirements??[];if(n.length===0&&!e.manifest.instructions)return{items:[],instructions:[]};let s,i=[];try{let a=MOe.parse(await e.send("GET",`/api/v1/runner/attempts/${e.attemptId}/requirements`,void 0));s=new Map(a.items.map(c=>[Ri(c),c])),i=e.manifest.instructions?a.instructions??[]:[]}catch(a){let c=a instanceof Error?a.message:String(a);r(`Testbot V3: could not read the run's requirement items: ${c}`),s=new Map}try{ds.mkdirSync(t,{recursive:!0,mode:448})}catch{}let o=[];for(let a of n){let c={...Qu(a),..."fileName"in a?{file:{name:a.fileName,mediaType:a.mediaType}}:{}},l=s.get(Ri(c));if(!l)o.push({...c,state:"not_read",reason:gy.test(c.key)?"cannot_open":"unavailable"});else if(l.state==="not_read")o.push({...c,state:"not_read",reason:l.reason});else if(!("text"in l))o.push(await acr(e,t,c,a.contentHash,r));else{let u=ol.join(t,jtt(c));try{ds.writeFileSync(u,l.text,{mode:384}),o.push({...c,state:"read",path:u,contentMatches:l.contentMatches,version:l.version})}catch(d){r(`Testbot V3: could not write the requirement item ${c.key}: ${d instanceof Error?d.message:String(d)}`),o.push({...c,state:"not_read",reason:"unavailable"})}}}return{items:o,instructions:i}}async function acr(e,t,r,n,s){let i=c=>(s(`Testbot V3: could not open the uploaded document ${r.key}: ${c}`),{...r,state:"not_read",reason:"cannot_open"});if(!r.file)return i("the manifest names no file");let o;try{let c=mC.requirementFile.replace(":attemptId",e.attemptId).replace(":key",r.key);o=await e.readBytes(c,FFe)}catch(c){return i(c instanceof Error?c.message:String(c))}if((0,wtt.createHash)("sha256").update(o).digest("hex")!==n)return i("its bytes do not match its hash");let a=ol.join(t,jtt(r));try{ds.writeFileSync(a,o,{mode:384})}catch(c){return i(c instanceof Error?c.message:String(c))}return{...r,state:"read",path:a,contentMatches:!0,version:n}}function jtt(e){let t=e.source==="other"?[]:[new URL(e.site).hostname],r=e.file?MFe(e.file.mediaType):"txt";return`${[e.source,...t,e.key].join("-")}.${r}`}async function rle(e,t){await e.send("POST",`/api/v1/runner/attempts/${e.attemptId}/progress`,$Oe.parse(t))}async function nle(e,t){return YOe.parse(await e.send("POST",`/api/v1/runner/attempts/${e.attemptId}/setup-events`,qOe.parse(t)))}async function Htt(e){let t=N2.generate();return await e.send("PUT",mC.credentialRelayKey.replace(":attemptId",e.attemptId),{schemaVersion:1,publicKey:t.publicKey}),t}async function ztt(e,t){Stt(t,"relay id"),await e.send("POST",mC.credentialRelayDelivered.replace(":attemptId",e.attemptId).replace(":relayId",t),{schemaVersion:1})}async function Vtt(e,t){return KOe.parse(await e.send("POST",`/api/v1/runner/attempts/${e.attemptId}/run-events`,GOe.parse(t)))}async function Wtt(e,t){await e.send("POST",`/api/v1/runner/attempts/${e.attemptId}/setup-checkpoint`,ZOe.parse(t))}async function Jtt(e){return(await Ktt(e,"setup-checkpoint",eQe))?.checkpoint??null}async function Ytt(e){return(await Ktt(e,"setup-context",tQe))?.context??null}async function Ktt(e,t,r){try{return r.parse(await e.send("GET",`/api/v1/runner/attempts/${e.attemptId}/${t}`,void 0))}catch(n){if(n instanceof nn&&n.status===404)return null;throw n}}async function sle(e,t){let r=$n([...e.issuedTokens,...t.secrets??[]]),n=uQe(e.manifest,e.attemptNumber,t.sources.map(s=>({repository:s.repository,revision:s.revision})),_r(t.recipe,r),t.producer);await e.send("PUT",`/api/v1/runner/attempts/${e.attemptId}/sut-recipe`,n)}function Xtt(e,t,r,n=t[0].slug,s,i={}){let{record:o,entries:a}=ert(e,t,n),c=da({outputsDir:e,state:WG(ol.join(ol.dirname(e),"state.json"))});if(!o&&NF(i,r.system,c?.sutRequired).length>0)return{status:"none"};let l=m=>Ztt(t,m),u=[],d=[];for(let{record:m,repository:A,number:E}of a)if(A&&E){let g=ccr(m);u.push({repository:A,number:E,...g?{commitSha:g}:{}})}else if(A&&m.prFailure){let g=m.prDetail?`${m.prFailure}: ${m.prDetail}`:m.prFailure;d.push({repository:A,message:g,slug:m.repository??n})}else A&&m.committed&&d.push({repository:A,message:m.reason??"The tests were committed but no pull request was opened.",slug:m.repository??n});let p=new Set([...u,...d].map(({repository:m})=>m.providerRepositoryId)),f=[...new Set(r.newTestsCreated.map(m=>(m.repository??n).toLowerCase()))];for(let m of f){let A=l(m);A&&!p.has(A.providerRepositoryId)&&d.push({repository:A,message:s??"Generated tests were not proposed in a pull request.",slug:m})}return u.length&&d.length?{status:"partial",pullRequests:u,failures:d.map(({repository:m,message:A})=>({repository:m,message:A}))}:u.length?{status:"delivered",pullRequests:u}:d.length?{status:"failed",message:o?.deliveries?d.map(m=>`${m.slug}: ${m.message}`).join("; "):d[0].message}:r.newTestsCreated.length>0?{status:"failed",message:s??"Generated tests were not proposed in a pull request."}:{status:"none"}}function ccr(e){return e.pushedCommits?e.deliveredCommit:e.pushed?e.commitSha:void 0}function Ztt(e,t){let r=e.find(n=>n.slug.toLowerCase()===t.toLowerCase());return r&&{provider:r.repository.provider,providerAccountId:r.repository.providerAccountId,providerRepositoryId:r.repository.providerRepositoryId}}function ert(e,t,r){let n=ol.join(e,"deliver.json"),s=ds.existsSync(n)?JSON.parse(ds.readFileSync(n,"utf-8")):void 0,i=s?.deliveries??(s?[s]:[]);return{record:s,entries:i.map(o=>({record:o,repository:Ztt(t,o.repository??r),number:/\/pull(?:request)?\/([1-9][0-9]*)$/.exec(o.prUrl??"")?.[1]}))}}function trt(e,t,r=t[0].slug){let n=new Map,s=(i,o)=>{p6.safeParse(i).success&&n.set(`${i.kind}:${i.repository.providerRepositoryId}:${o}`,i)};for(let{record:i,repository:o,number:a}of ert(e,t,r).entries){if(!o||!i.branch)continue;let c=i.pushedCommits??(i.pushed&&i.commitSha?[i.commitSha]:[]);for(let u of c)s({kind:"branch_pushed",repository:o,branch:i.branch,commit:u},`${i.branch}:${u}`);if(!a)continue;let l=i.prAction==="retargeted"?i.retargetedAs??"created":i.prAction;l==="created"?s({kind:"pull_request_opened",repository:o,number:a,branch:i.branch},a):(l==="updated"||l==="unchanged")&&s({kind:"pull_request_edited",repository:o,number:a,branch:i.branch},a)}return[...n.values()].slice(0,d6)}function rrt(e,t){return e.credentials.filter(r=>r.required&&!t[r.name]).map(r=>r.name)}var n_=[/\bgh[pousr]_[A-Za-z0-9]{36,}/g,/\bgithub_pat_[A-Za-z0-9_]{22,}/g,/\bsk-ant-[A-Za-z0-9_-]{20,}/g,/\bsk-[A-Za-z0-9]{32,}/g,/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g],nrt=e=>n_.some(t=>new RegExp(t.source).test(e));var ile=256,O2={discover:"reading the repositories",start:"starting the components",check:"checking that the components answer"},zi=".skyramp/setup-events.ndjson",gw=".skyramp/setup-left-out.json",Aw=".skyramp/setup-inbox.json",ole=".skyramp/setup-inbox-read.json",Q2=".skyramp/setup-hook-ran",o_=".skyramp/setup-notes.json",M2=".skyramp/setup-notices.json",F2=".skyramp/setup-relays-pending.json";function ort(e,t){let r=po.join(e,F2);br.mkdirSync(po.dirname(r),{recursive:!0}),br.writeFileSync(`${r}.tmp`,`${JSON.stringify(t)}
|
|
509
509
|
`),br.renameSync(`${r}.tmp`,r)}function art(e,t){let r=po.join(e,M2),n=[];try{n=JSON.parse(br.readFileSync(r,"utf-8"))}catch(i){if(i.code!=="ENOENT")throw i}let s=Array.isArray(n)?n.filter(i=>i&&typeof i=="object"&&i.id!==t.id):[];br.mkdirSync(po.dirname(r),{recursive:!0}),br.writeFileSync(`${r}.tmp`,`${JSON.stringify([...s,t])}
|
|
510
510
|
`),br.renameSync(`${r}.tmp`,r)}function ale(e){let t=po.join(e,zi);br.mkdirSync(po.dirname(t),{recursive:!0}),br.writeFileSync(t,"");for(let r of[gw,Aw,ole,Q2,o_,M2,F2])br.rmSync(po.join(e,r),{force:!0})}var lcr=6e4,a_=5e3;var ucr={session_ended:"Testbot has finished its setup session, so this setup can't act on messages any more. To change the setup, edit the notes and set it up again.",recheck:"This run only checks the saved setup again with the credentials found, so it takes no messages. To change the setup, edit the notes and set it up again.",awaits_check:"Testbot has finished its setup session, so this setup can't act on messages any more. Skyramp checks the app with the credentials it found once they're added. To change the setup, edit the notes and set it up again."},cle=300,Cs=e=>{let t=typeof e=="string"?e:typeof e=="number"?String(e):"";return t.trim()==="null"?"":t},s_=e=>Array.isArray(e)?e:[],i_=(e,t)=>Object.values(e).find(r=>r===Cs(t).trim().toLowerCase()),dcr={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"},pcr=e=>i_(wC,e)??dcr[Cs(e).trim().toLowerCase()]??"found",srt=e=>y.string().uuid().safeParse(e).success,fcr=e=>vF.test(e)?e:e.replace(/[^A-Za-z0-9_-]+/g,"-").slice(0,64).replace(/^-+|-+$/g,"")||"question",hcr=/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/,mcr=/github\.com[/:]([^/\s]+)\/([^/\s?#]+?)(?:\.git)?(?:[/?#]|$)/i;function gcr(e){if(e.kind!=="question"||e.placeholder===void 0)return e;let{placeholder:t,...r}=e;return r}var irt=new RegExp(yT.source,"g");function crt(e,t){return new qx(e,()=>Promise.reject(new Error("only reads")),{...t,warn:()=>{}}).readAll()}var qx=class{constructor(t,r,n){this.checkout=t;this.send=r;this.opts=n}checkout;send;opts;offset=0;tail=Buffer.alloc(0);seen=new Set;sequence=1;pending=[];started=!1;closed=!1;capped=!1;flushing=0;emptyRefused=!1;placeholderRefused=!1;unreadSince;saidHookSilent=!1;timer;queue=Promise.resolve();phase="discover";messageIds=new Set;stopHeard=!1;channelClosed;answered=new Set;replied=new Set;stopAfter=Promise.resolve();start(){this.timer||(this.started||(this.started=!0,ale(this.checkout)),this.timer=setInterval(()=>{this.flushing===0&&this.flush()},this.opts.intervalMs??a_),this.timer.unref?.())}closeChannel(t){this.channelClosed=t}stopWhen(t){return this.stopAfter=t.catch(()=>{}),this.stop()}async stop(){await this.stopAfter,this.timer&&clearInterval(this.timer),this.timer=void 0,await this.flush()}flush(){return this.flushing+=1,this.queue=this.queue.then(()=>this.drain()).catch(t=>this.opts.warn(`Testbot V3: could not send setup events: ${mw(t)}`)).finally(()=>{this.flushing-=1}),this.queue}async drain(){if(!this.closed&&(this.collect(),!(this.pending.length===0&&!this.emptyRefused&&await this.sendBatch([])==="unanswered")))for(;this.pending.length>0&&!this.closed;){let t=this.pending.slice(0,Ku);if(await this.sendBatch(t)==="unanswered")return;this.pending.splice(0,t.length)}}async sendBatch(t){this.placeholderRefused&&(t=t.map(gcr));let r;try{r=await this.send({schemaVersion:1,events:t})}catch(n){if(n instanceof nn&&n.code==="RUN_CLOSED")return this.closed=!0,this.pending=[],"done";if(n instanceof nn&&t.length===0)return n.status===400&&(this.emptyRefused=!0),this.opts.warn(`Testbot V3: the app refused a setup events check${n.status===400?", so it is not asked again":"; the next one asks again"}: ${n.message}`),"done";if(n instanceof nn){if(t.length>1){for(let i of t){if(this.closed)return"done";if(await this.sendBatch([i])==="unanswered")return"unanswered"}return"done"}if(t[0].kind==="question"&&t[0].placeholder!==void 0)return this.placeholderRefused=!0,this.sendBatch(t);let s=t[0].kind==="log"?void 0:Acr(t[0]);return s?(this.opts.warn(`Testbot V3: the app refused setup event ${t[0].sequence}, so it is sent as a log line: ${n.message}`),this.sendBatch([{sequence:t[0].sequence,at:t[0].at,kind:"log",phase:this.phase,text:s}])):(this.opts.warn(`Testbot V3: the app refused setup event ${t[0].sequence}, so it is dropped: ${n.message}`),"done")}return n instanceof y.ZodError?(this.opts.warn(`Testbot V3: the app's answer to setup events was not understood: ${n.issues[0]?.message}`),"done"):(this.opts.warn(`Testbot V3: could not send setup events, trying again: ${mw(n)}`),"unanswered")}try{this.writeLeftOut(r.leftOut)}catch(n){this.opts.warn(`Testbot V3: could not write ${gw}: ${mw(n)}`)}try{this.writeInbox(r.messages??[])}catch(n){this.opts.warn(`Testbot V3: could not write ${Aw}: ${mw(n)}`)}try{this.channelClosed&&this.answerUnread(r.messages??[])}catch(n){this.opts.warn(`Testbot V3: could not answer the setup's messages: ${mw(n)}`)}try{r.notes&&this.writeNotes(r.notes)}catch(n){this.opts.warn(`Testbot V3: could not write ${o_}: ${mw(n)}`)}try{await this.opts.onRelays?.(r.relays??[])}catch(n){this.opts.warn(`Testbot V3: could not take the credentials fetched for this setup: ${mw(n)}`)}return r.stop&&!this.stopHeard&&(this.stopHeard=!0,this.opts.onStop?.(r.stop.key)),"done"}collect(){if(this.capped)return;let t=po.join(this.checkout,zi),r;try{r=br.statSync(t).size}catch{return}let n=r<this.offset||this.tail.length>0&&!this.tail.equals(this.bytesAt(t,this.offset-this.tail.length,this.tail.length));if(n&&(this.opts.warn("Testbot V3: the setup events file was rewritten, not appended to; it is read again from the start, and lines already sent are not sent again."),this.offset=0),r===this.offset)return;let s=this.bytesAt(t,this.offset,r-this.offset),i=s.lastIndexOf(10);if(i<0)return;let o=s.subarray(0,i).toString("utf-8").split(`
|
|
@@ -802,7 +802,7 @@ ${Not(o,{order:e.stages.map(c=>c.name),wallMinutes:Rj(o)})}
|
|
|
802
802
|
`).filter(Boolean);a.length>0&&i(["checkout","HEAD","--",...a])}var sat=".skyramp/sut/health-check.sh",iat=".skyramp/sut/get-auth-token.sh";function Xue(e){let t=s=>e.files?.some(i=>i.path===s)??!1,r=e.components.map(s=>`${s.name} (${s.repository===Fr?"shared, built by none of the Target's repositories":s.repository})`),n=e.revisionSources.map(s=>`${s.method.replace(/_/g," ")} ${s.detail} for ${s.components.join(" and ")}`);return[`The app is the customer's Test Environment at ${e.address}, already deployed and running.`,"Never start, stop, redeploy or change it: only read from it and test against it.",e.readyWhen&&`It is ready when ${e.readyWhen}.`,e.credentials.length>0&&`Sign in with ${e.credentials.join(", ")}, which the workflow supplies as environment variables of those names.`,r.length>0&&`Its components: ${r.join(", ")}.`,n.length>0&&`What each runs is read from: ${n.join("; ")}.`,t(sat)&&`Check it is ready with \`bash ${sat}\`.`,t(iat)&&`Sign in with the token \`bash ${iat}\` prints, never echoed.`,"Never edit the recipe files."].filter(Boolean).join(" ")}async function Igr(e,t){let{repositoryPath:r,repositorySlug:n}=e.layout,s=t?t.knowledge:await Uj(e.attempt);if(!s)return;let{runtimePlan:i,testEnvironment:o}=s;if(o)return Zue(o),o.files&&eC(r,o.files),be(`Testbot V3: testing the customer's Test Environment at ${o.address} (version ${o.version}, ${o.files?.length??0} files); Testbot does not start or change it`),o;if(!i){be("Testbot V3: no stored SUT recipe for this Target yet; deploy uses a source's own recipe, if one has it.");return}eC(r,i.files),be(`Testbot V3: SUT recipe version ${i.version}, ${i.files.length} files, for ${n} (uncommitted)`)}async function Uj(e){try{return await D2(e)}catch(t){if(!(t instanceof nn&&t.status===404))throw ou(),t;Te(`Testbot V3: this Skyramp app does not serve the stored SUT recipe (${t.message}); deploy uses a source's own recipe, if one has it.`);return}}function Zue(e){if(e.files&&(!e.contentHash||oQe({...e,files:e.files})!==e.contentHash))throw ou(),new Error(`The Test Environment's plan (version ${e.version}) does not match the hash Skyramp stored`)}function Cat(e,t,r){let n=t&&Zce(t,e);return r?ele(n,r,e,t,[]):n}function vat(e,t,r){let n=dm(r?.files);return xQe(t,{...n?{script:()=>nde(e,n.content,r?.credentials??[])}:{},resolveCommit:(s,i)=>Ott(e.attempt,s,i),secrets:$n([...e.attempt.issuedTokens,...fc(e),...pc()])})}async function Rgr(e,t,r=new Map){let n={attempt:e},s=await Kue(n),i=await Uj(e),o=i?.testEnvironment??void 0;o&&Zue(o);let a=E=>e.manifest.sources.find(g=>hm(`${g.repository.namespace}/${g.repository.name}`,E)),c=xat(Cat(e.manifest,s,o)).filter(E=>!r.has(Lr(a(E.repository).repository))),l=E=>{for(let[g,w]of r){E.set(g,w);let S=e.manifest.sources.find(x=>Lr(x.repository)===g);be(`Testbot V3: a person said the environment runs ${w} of ${S?`${S.repository.namespace}/${S.repository.name}`:g}; the run validates that revision without reading it`)}return E},u=e.manifest.trigger.kind==="schedule",d=u?"the earlier attempt's read":"the Rerun",p=t.size>0?c.filter(E=>!t.has(Lr(a(E.repository).repository))):[];if(p.length>0)throw ps("environment_unverified"),new Error(`Testbot V3: ${p.map(E=>`${E.name} (${E.repository})`).join(", ")} runs a source ${d} did not pin, so this attempt could combine two deployments`);let f=await vat(n,c,o),m=f.filter(E=>!E.observedRevision);if(m.length>0)throw u&&t.size===0&&await P2(e,f.map(E=>({...E,observedRevision:E.observedRevision??null})),fc(n)).catch(E=>Te(`Testbot V3: Skyramp did not keep what the environment runs: ${E instanceof Error?E.message:String(E)}`)),ps("environment_unverified"),new Error(`Testbot V3: could not read what ${Iat(m)}`);if(t.size>0){for(let E of f){let{repository:g}=a(E.repository),w=t.get(Lr(g));if(E.observedRevision!==w)throw ps("environment_unverified"),new Error(u?`Testbot V3: the environment was redeployed after an earlier attempt of this run read it: ${E.name} runs ${E.observedRevision}, not ${g.namespace}/${g.name} at ${w.slice(0,7)}. This run stops, so it never combines two deployments; the next night, or a new run, validates the new deployment`:`Testbot V3: the environment no longer runs ${g.namespace}/${g.name} at ${w.slice(0,7)}; the original run can't be repeated (${E.name} runs ${E.observedRevision})`)}for(let[E,g]of t){if(f.some(x=>Lr(a(x.repository).repository)===E))continue;let w=e.manifest.sources.find(x=>Lr(x.repository)===E),S=w?`${w.repository.namespace}/${w.repository.name}`:E;throw ps("environment_unverified"),new Error(`Testbot V3: could not check that the environment still runs ${S} at ${g.slice(0,7)}: no component the runner can read runs it, so ${u?"this run stops":"the original run can't be repeated"}`)}return{capture:s,knowledge:i,observed:l(new Map(t))}}let A=new Map;for(let E of f){let g=Lr(a(E.repository).repository),w=A.get(g);if(w&&w!==E.observedRevision)throw ps("environment_unverified"),new Error(`Testbot V3: the components of ${E.repository} run different commits (${w} and ${E.observedRevision}), so the run has no one revision of it to validate`);A.set(g,E.observedRevision),be(`Testbot V3: ${E.name} runs ${E.observedRevision} of ${E.repository}; the run validates that revision`)}return u&&f.length>0&&await P2(e,f,fc(n)).catch(E=>{if(!(E instanceof nn&&Tgr.includes(E.code??"")))throw E;Te(`Testbot V3: Skyramp did not keep what the environment runs, so a retry of this run reads it again: ${E.message}`)}),{capture:s,knowledge:i,observed:l(A)}}var Tgr=["INVALID_REQUEST","IDEMPOTENCY_CONFLICT"],xat=e=>fm(e).filter(t=>t.revisionUrl||t.revisionScript),Iat=e=>e.map(t=>`${t.name} (${t.repository}) runs: ${t.evidence}`).join("; ");async function kgr(e){Eat({...e.manifest,credentials:e.manifest.credentials.filter(t=>t.purpose!=="model_provider")});try{await Bgr(e)}catch(t){throw ou(),t}}async function Bgr(e){let t={attempt:e},r=await Kue(t),n=(await Uj(e))?.testEnvironment??void 0;n&&Zue(n);let s=await vat(t,xat(Cat(e.manifest,r,n)),n);for(let o of s)be(`Testbot V3: ${o.name} (${o.repository}) runs ${o.observedRevision??"an unknown revision"}`);let i=s.filter(o=>!o.observedRevision);if(i.length>0&&ps("environment_unverified"),await P2(e,s,fc(t)),i.length>0)throw new Error(`Testbot V3: could not read what ${Iat(i)}`);xl(sp.revisionsUploaded,"true"),be(`Testbot V3: uploaded what ${s.length} component${s.length===1?"":"s"} run; Skyramp saves the Initial Baseline.`)}function ede(e){try{let t=JSON.parse(hi.readFileSync(Ji.join(e,"@skyramp","mcp","package.json"),"utf-8")).version;return typeof t=="string"&&/^[0-9A-Za-z.+-]{1,64}$/.test(t)?t:"unknown"}catch{return"unknown"}}function tde(e){if(e.aborted||e.timedOut)return!1;let t=e.stateFilePath?np(e.stateFilePath):void 0,r=t&&_2(t);return r?(ps($tt(r)),r.kind==="permanent"?Te(`Testbot V3: ${Ux()} refused the calls of the ${r.stage} stage. This run produced no validation result. Contact Skyramp support if Skyramp manages provider access; otherwise ask your provider account administrator to resolve access or usage limits before running again. No changes to your code are needed.`):Te(`Validation unavailable: ${Ux()} was unavailable to Testbot during the ${r.stage} stage. This run produced no validation result. No changes to your code or Testbot setup are needed. Please try again later.`),!0):!1}async function Rat(e,t,r){if(e.runEvents?.closeChannel(),await e.runEvents?.stop(),t.aborted?ps("cancelled"):t.timedOut&&ps("timed_out"),tde(t))return;let n=t.outputsDir?Ji.join(t.outputsDir,"report.json"):void 0;if(!n||!hi.existsSync(n)){t.abortReason==="attempt-cancelled"?be("Testbot V3: Skyramp cancelled this run, so Testbot uploads no report."):Te("Testbot V3: the run wrote no report, so Skyramp records it as an infrastructure error.");return}if(!await Jue(e))try{let s=JSON.parse(hi.readFileSync(n,"utf-8"));if(t.timedOut){let i=t.stateFilePath?np(t.stateFilePath):void 0,o=Object.entries(i?.stages??{}),a=o.filter(([,u])=>u.status==="passed").map(([u])=>u),c=o.filter(([,u])=>u.status!=="passed"&&(u.status!=="skipped"||u.reason==="not run \u2014 run budget exhausted")).map(([u])=>u),l=`The Maximum runtime execution budget, capped by the remaining attempt deadline, was exhausted before required validation completed. Completed stages: ${a.join(", ")||"none recorded"}. Unfinished stages: ${c.join(", ")||"see the validation gaps"}.`;s.validation={...s.validation,sufficiency:"insufficient",rationale:[l,s.validation?.rationale].filter(Boolean).join(" "),gaps:[...s.validation?.gaps??[],l],acceptedEvidence:s.validation?.acceptedEvidence??[],actionRequired:[...new Set([...s.validation?.actionRequired??[],"evidence_insufficient"])]},s.caveats=[...(s.caveats??[]).filter(u=>u.kind!=="execution-timeout"),{kind:"execution-timeout",text:l,blocking:!0}],hi.writeFileSync(n,JSON.stringify(s)),FA()!=="en"&&dw(t.outputsDir,"no-time",{info:be,warn:Te,error:Ah})}await qtt(e.attempt,{report:s,sources:e.sources,firstQualification:e.firstQualification,workingSlug:e.layout.repositorySlug,delivery:Xtt(t.outputsDir,e.sources,s,e.layout.repositorySlug,t.deliverWithheld,{...e.testEnvironment?{appRunning:Xue(e.testEnvironment)}:{},sharedEnvironment:e.sharedEnvironment}),githubWrites:trt(t.outputsDir,e.sources,e.layout.repositorySlug),notTranslated:zet(t.outputsDir),translated:t.timedOut?void 0:Vet(t.outputsDir,i=>Te(i)),producer:{testbot:kj().version,mcp:ede(r)},secrets:[...fc(e),...pc()]}),xl(sp.reportUploaded,"true"),be("Testbot V3: report uploaded; Skyramp derives the outcome.")}catch(s){Te(`Testbot V3: the report upload failed: ${s instanceof Error?s.message:String(s)}`)}}function xg(e){return e.attempt.manifest.trigger.kind==="sut_setup"}async function Tat(e){let{capture:t}=await tle(e.attempt);lJ(Xce(t));let{components:r,dependencies:n,runner:s,agentPool:i,...o}=t.settings.target.environment??{},{answerWaitMinutes:a,testEnvironment:c}=t.settings;return{sutEnvironment:Wae(o,"the run's SUT / Environment settings"),...a!==void 0&&{answerWaitMinutes:a},...c&&{testEnvironment:{name:c.name,...c.address&&{address:c.address},...c.readyWhen&&{readyWhen:c.readyWhen},sourceProvider:e.attempt.manifest.execution.provider}}}}function Ngr(e){let t=e.length===1,r=Yae(e);return[`${UN(e)}, so Testbot hasn't started the app with ${t?"it":"them"} yet.`,`Skyramp checks the app with ${t?"its value":"their values"} once ${t?"it's":"they're"} added. The setup is ready when that check passes.`,...r?[`${r}: the check can't pass with Testbot's own names.`]:[]]}function kat(e){return{start:e?"Checking the Test Environment with the recipe.":"Starting the app from the recipe, to prove it works.",again:(t,r)=>`Deploy's try ${t-1} did not pass, so Testbot tries again (try ${t} of ${r}).`,passed:e?"The Test Environment answers its health check.":"The app came up from the recipe and answers its health check.",failed:e?"Testbot could not verify the Test Environment with the recipe.":"Testbot could not show the app comes up from the recipe."}}function Bat(e,t,r,n){try{hi.appendFileSync(Ji.join(e,zi),r.map(s=>`${JSON.stringify({kind:"log",phase:t,text:s})}
|
|
803
803
|
`).join(""))}catch(s){Te(`Testbot V3: could not say ${n}: ${s instanceof Error?s.message:String(s)}`)}}function Nat(e,t=!1){let r=kat(t);return({stage:n,attempt:s,of:i})=>{n==="deploy"&&Bat(e,"start",[s===1?r.start:r.again(s,i)],"that deploy started")}}function _gr(e,t,r,n){let s=e.attempt.manifest.execution.repository,i=new _j({key:t,attemptId:e.attempt.attemptId,checkout:r,host:`${s.namespace}/${s.name}`,script:l_(Ji.join(n,$2)),ack:o=>ztt(e.attempt,o),warn:o=>Te(o)});return o=>i.take(o)}function _at(e,t){return{secrets:()=>$n([...e.attempt.issuedTokens,...fc(e),...pc()]),repositories:[{slug:e.layout.repositorySlug,path:e.layout.repositoryPath},...e.layout.relatedRepos],shared:t}}var Pgr={onboard:"onboard",deploy:"deploy"},Dgr={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"}};function Pat(e,t){return({stage:r,event:n})=>{try{if(n!=="started")return;r==="plan"&&!e.runEvents&&(e.runEvents=new Qj(t,i=>Vtt(e.attempt,i),{secrets:()=>$n([...e.attempt.issuedTokens,...fc(e),...pc()]),warn:i=>Te(i)}),e.runEvents.start());let s=Dgr[r];s&&e.runEvents?.say(s.stage,s.text),r==="report"&&e.runEvents?.closeChannel()}catch(s){Te(`Testbot V3: could not send run events: ${s instanceof Error?s.message:String(s)}`)}}}function Dat(e,t,r=!1,n){return({stage:s,event:i,status:o})=>{if(s==="onboard"&&i==="started"){e.setupEvents??=new qx(t,d=>nle(e.attempt,d),{..._at(e,r),warn:d=>Te(d),onStop:d=>e.requestStop?.(d),...e.relayKey&&n?{onRelays:_gr(e,e.relayKey,t,n)}:{}});try{e.setupEvents.closeChannel(void 0),e.setupEvents.start();let d=e.setupLines?.splice(0)??[];d.length>0&&hi.appendFileSync(Ji.join(t,zi),d.map(p=>`${JSON.stringify({kind:"log",phase:"discover",text:p})}
|
|
804
804
|
`).join(""))}catch(d){Te(`Testbot V3: could not start setup events: ${d instanceof Error?d.message:String(d)}`)}}if(s==="onboard"&&i==="finished"){let d=n&&o==="passed"?np(Ji.join(n,"onboard.json")):void 0,p=d?LN(d,ep(Sc())):[];if(e.setupEvents?.closeChannel(p.length>0?"awaits_check":"session_ended"),p.length>0)try{hi.appendFileSync(Ji.join(t,zi),Ngr(p).map(f=>`${JSON.stringify({kind:"log",phase:"check",text:f})}
|
|
805
|
-
`).join(""))}catch(f){Te(`Testbot V3: could not say that deploy waits for the credential check: ${f instanceof Error?f.message:String(f)}`)}}if(s==="deploy"&&i==="finished"&&(o==="passed"||o==="failed")){let d=kat(r),p=o==="passed"&&n!==void 0&&OF(np(Ji.join(n,"deploy.json")));Bat(t,"check",[p?d.passed:d.failed],"how deploy ended")}let a=Pgr[s],c=i==="finished",l=o==="aborted"?"skipped":o,u=a?rle(e.attempt,{schemaVersion:1,stage:a,event:c?"finished":"started",...c&&l?{status:l}:{}}).catch(d=>Te(`Testbot V3: could not report ${s} ${i}: ${d instanceof Error?d.message:String(d)}`)):Promise.resolve();s==="deploy"&&c&&e.setupEvents?.stopWhen(u)}}var np=e=>{try{return JSON.parse(hi.readFileSync(e,"utf-8"))}catch{return}};async function Oat(e,t,r,n=!1){try{await e.setupEvents?.stop(),e.stopKey?await Qgr(e,e.stopKey,t.outputsDir):await Ogr(e,t,r,n)}finally{await e.setupEvents?.stop()}}async function Ogr(e,t,r,n){if(t.aborted?ps("cancelled"):t.timedOut&&ps("timed_out"),tde(t))return;let s=t.stateFilePath?np(t.stateFilePath):void 0,i=!t.aborted&&(t.timedOut||s?.stages.onboard?.attempts.at(-1)?.timedOut===!0),o=t.outputsDir?np(Ji.join(t.outputsDir,"onboard.json")):void 0,a=e.layout.repositoryPath,c=o??(i&&!n?Zot(a,crt(a,_at(e,!1)),gw):void 0);if(!c){Te("Testbot V3: onboard wrote no answer, so there is no SUT recipe to send; Skyramp records the run as an infrastructure error.");return}if(o||be("Testbot V3: the setup's time ran out before onboard answered; sending what it found as a blocked SUT recipe."),await Jue(e))return;let l=t.outputsDir?np(Ji.join(t.outputsDir,"deploy.json")):void 0,u=s?.stages.onboard?.status==="passed"?LN(c,ep(Sc())):[],d=s?.stages.deploy?.attempts?.reduce((p,f)=>p+(f.totalMs??f.durationMs??0),0);try{let p=l?rw(e.layout.repositoryPath):void 0,f=c.environment&&c.status!=="blocked",m=f?await Qat(e,c,VW(c,l,p)):void 0,A=f&&c.environment&&!m?await vQe(c.environment,c.components.map(g=>g.name),void 0,[...fc(e),...pc()]):void 0,E=WW(c,l,{deployed:A,revisionCheck:m,recipeFiles:p,deployDurationSeconds:d?Math.round(d/1e3):void 0,unsupplied:d7e(c,Pwe(e.attempt.manifest.credentials.map(g=>g.name))),awaitsCredentialCheck:l?[]:u,timeLimit:i,repository:e.layout.repositorySlug});await sle(e.attempt,{recipe:E,sources:e.sources,producer:{testbot:kj().version,mcp:ede(r)},secrets:[...fc(e),...pc()]}),xl(sp.recipeUploaded,"true"),xl(sp.recipeStatus,E.status),be(`Testbot V3: SUT recipe uploaded (${E.status}${E.replay?.outcome===jW?`, its deploy waiting for the check with ${u.join(", ")}`:""}); Skyramp derives the outcome.`)}catch(p){Te(`Testbot V3: the SUT recipe upload failed: ${p instanceof Error?p.message:String(p)}`)}}async function Qat(e,t,r){let n=dm(r.recipeFiles),s=TF(t.components,t.environment?.revisionSources??[]);return n?rde(e)(n.content,s,t.environment?.credentials??[]):void 0}function rde(e){return(t,r,n)=>EQe({content:t,components:r,credentials:n,modelCredentials:e.attempt.modelCredentials,read:s=>nde(e,s,n),resolveCommit:(s,i)=>Ptt(e.attempt,s,i),provider:e.attempt.manifest.execution.provider})}async function nde(e,t,r){let n;try{n=await e.attempt.readOnlyToken()}catch(o){return{ok:!1,error:`deployed-revisions.sh was not run: no read-only token (${o instanceof Error?o.message:String(o)})`}}let s=$n([...e.attempt.issuedTokens,...fc(e),...pc()]),i={...process.env,...Sc()};return gQe({content:t,env:mQe(n,r,e.attempt.modelCredentials,i,e.attempt.manifest.execution.provider),secrets:s})}function Mat(e){let t=dm(e.testEnvironment?.files),r=e.testEnvironment?.credentials??[];return t?{deployedRevisions:()=>nde(e,t.content,r)}:{}}async function Fat(e){return await e.platform?.artifactStore?.()??_ae()}var Lat=e=>[{slug:e.layout.repositorySlug,path:e.layout.repositoryPath},...e.layout.relatedRepos];async function Qgr(e,t,r){ps("cancelled");try{let n=r?np(Ji.join(r,"onboard-session.json"))?.sessionId:void 0;if(!n)throw new Error("onboard had not started a session");let s=rn(),i=await Wot({sessionId:n,key:t,checkouts:Lat(e),secrets:$n([...e.attempt.issuedTokens,...fc(e),...pc()]),artifacts:await Fat(e),name:["skyramp-setup-checkpoint",e.attempt.manifest.runId,s.runAttempt].filter(Boolean).join("-"),providerRunId:s.runId??"",now:new Date});await Wtt(e.attempt,i),be(`Testbot V3: saved where onboard was (${i.bytes} bytes, kept ${ET} days); resume the setup from Skyramp to continue it.`)}catch(n){Te(`Testbot V3: could not save where onboard was, so a resume of this setup starts over: ${n instanceof Error?n.message:String(n)}`)}}var sde="Could not restore where the setup stopped, so it starts over with the notes as they are now.",Mgr="Could not restore where the setup stopped, so it starts from the Target's ready recipe, with the notes as they are now.",Uat="Could not restore where the setup stopped, so it continues from what it found, with the notes as they are now.",Fgr="Could not restore where the setup stopped, so it continues from what it found and the Target's ready recipe, with the notes as they are now.";function Lgr(e){e.setupLines=e.setupLines?.map(t=>t===sde?Mgr:t===Uat?Fgr:t)}async function Ugr(e){if(!(!xg(e)||e.recheck))try{return await Ytt(e.attempt)??void 0}catch(t){Te(`Testbot V3: could not read what the setup before this one found: ${t instanceof Error?t.message:String(t)}`);return}}function $gr(e,t){if(t.kind!=="resume")return;let r=(e.setupLines??[]).filter(n=>n!==sde);e.setupLines=[...r,Uat]}async function qgr(e,t){if(!(!xg(e)||e.recheck))try{let r=await Jtt(e.attempt);if(!r)return;let n=await Jot({checkpoint:r,token:t??"",cwd:e.layout.repositoryPath,checkouts:Lat(e),artifacts:await Fat(e)});return be(`Testbot V3: resuming the stopped setup's onboard session ${n.sessionId.slice(0,8)} where it was.`),n}catch(r){Te(`Testbot V3: could not restore where the stopped setup was, so this setup starts over: ${r instanceof Error?r.message:String(r)}`),(e.setupLines??=[]).push(sde);return}}async function $at(e,t,r={checkpoint:qgr,context:Ugr,base:Sgr}){let n=await r.checkpoint(e,t),s=await r.context(e);s&&!n&&$gr(e,s);let i=!e.recheck&&!n?await r.base(e):void 0;i&&Lgr(e);let o=s?Cgr(e,s,i):void 0;return{...n?{resumeSetup:n}:{},...o?{previousSetup:o}:{},...i?{setupBase:i}:{}}}function Ggr(e){let t=e.split(/[\n,]/).map(r=>r.trim()).filter(Boolean);return t.length?t:void 0}function jgr(e,t={}){if(!t.sutSetup&&(e("onboard")??"").trim().toLowerCase()==="true")return"onboard is not supported on a run that tests a change \u2014 in the two-step pipeline a SUT setup runs on its own (preflight, onboard, deploy) and ends with a recipe, not a report. Set up the SUT from the Skyramp app's Setup page, or locally with the CLI's --onboard, and remove the input.";if((e("testRepoPath")??"").trim())return"testRepoPath is not supported by the staged pipeline (pipeline: staged) \u2014 it writes tests into the application checkout only, and the Action's token has no write access to another repository. Pin skyramp/testbot@v0.11 for cross-repository delivery, or remove the input."}async function Hgr(e,t,r,n=rn().workspace||process.cwd()){let s=(e("relatedRepoPaths")??"").trim();if(!s)return[];let i=[];for(let o of s.split(/[\n,]/).map(a=>a.trim()).filter(Boolean)){let a=Vf.resolve(n,o);if(!Vs(n,o)){r(`relatedRepoPaths: ${o} is outside the workspace \u2014 skipping`);continue}if(!Ig.existsSync(a)){r(`relatedRepoPaths: no checkout at ${o} \u2014 skipping`);continue}let c=await t(a);if(!c){r(`relatedRepoPaths: could not resolve owner/repo for ${o} (no origin remote?) \u2014 skipping`);continue}i.push({slug:c,path:a})}return i}async function zgr(e,t,r=rn()){if(!r.repository)return;let{id:n,slug:s}=r.repository;return(await t(e).catch(()=>{}))?.toLowerCase()===s.toLowerCase()?{[n]:s}:void 0}var ide=class{constructor(t){this.link=t}link;settled=!1;async couldNotStart(t){this.settled||(this.settled=!0,await jue(t,this.link))}runBegins(){this.settled=!0}};async function qat(){let e=We("skyrampRunId").trim(),t=e?new ide({origin:I_(),runId:e}):void 0,r;try{let n=tke();delete process.env.INPUT_SKYRAMPLICENSEFILE;let s=Lot(process.env),i=e?await yat(e,n):void 0;if(r=i,i&&"revisionRead"in i)return;await Vgr(n,s,i,t)}catch(n){throw await t?.couldNotStart(n),n}finally{r&&await Lj(r),r&&Ig.rmSync(Fj(),{recursive:!0,force:!0}),r&&Owe()}}async function Vgr(e,t,r,n){let s=r!==void 0&&xg(r);r&&(r.heldInputs=[e.skyrampLicenseFile].filter(Boolean));let i=r?r.layout.repositoryPath:Vf.resolve(e.workingDirectory||"."),o=r?()=>r.attempt.token():Uot(),a=r?void 0:t;a&&Kr(a);let c=Mot(),l=UZe({repositoryPath:r?.pullRequest?.path??i,prNumber:c.prNumber,tokenProvider:o,githubToken:a,repoSlug:r?r.pullRequest?.repository??r.layout.repositorySlug:void 0,allowedAuthors:!s&&e.allowedAuthors?.length?e.allowedAuthors:void 0,log:Y=>be(Y)},r?.attempt.skyrampRunUrl);r&&(r.platform=l);let u=await l.resolveContext().catch(()=>({}));c=Fot(c,u),be(`Staged pipeline \u2014 event: ${c.eventName??"?"}${c.action?`/${c.action}`:""}${c.prNumber?`, PR #${c.prNumber}`:""}${c.headRef?` (${c.headRef} \u2192 ${c.baseRef??"?"})`:""}`);let d=qb(),p=Vf.join(d,"staged");if(c.eventName==="pull_request"&&c.action==="closed"){let Y=c.merged===!1,U=Y?`PR #${c.prNumber} was closed without merging`:`PR #${c.prNumber} was merged`;if(Y&&c.headRef){let ie=await l.closeTestsPr({branch:qce(c.headRef,We("deliverBranch")||void 0),reason:`Closing: the pull request this tests PR targeted (#${c.prNumber}) was closed without being merged.`});ie.closed&&(U+=`; closed the tests PR ${ie.url??""}`.trimEnd())}be(`Staged pipeline \u2014 ${U}; nothing to run.`);for(let[ie,le]of Object.entries(v_({admission:{admit:!1,reason:U}},{skippedPrClosed:Y})))pR(ie,le);return}let f=await l.admitRun();if(!f.admit){be(`Staged pipeline \u2014 run skipped: ${f.reason}`);for(let[Y,U]of Object.entries(v_({admission:f},{skippedSelfTrigger:!0})))pR(Y,U);return}let m=r?r.layout.relatedRepos:await Hgr(Y=>We(Y),Y=>R4(Y),Y=>Te(Y)),A=jgr(Y=>We(Y),{sutSetup:s});if(A)throw new Error(A);let E=s,g=Oot(We("sutGuidance"),"sutGuidance input"),w=Sj(We("unitPath")),S,x,R;try{s?{sutEnvironment:S,answerWaitMinutes:x,testEnvironment:R}=await Tat(r):S=c7e(We("sutEnvironment"),"sutEnvironment input")}catch(Y){throw r&&ou(),Y}for(let Y of e2(S))Kr(Y);let I=r?Object.fromEntries(r.sources.map(Y=>[Y.repository.providerRepositoryId,Y.slug])):await zgr(i,Y=>R4(Y)),B,T,Q=r?.attempt.license?.runToken,J;try{if(t||o){let U=rn().workspace,ie=[...new Set([i,...m.map(xe=>xe.path),...U?WZe(U):[]].map(xe=>Vf.resolve(xe)))],le;for(let xe of ie){let we=xe===Vf.resolve(i)?$e=>{/^\s*authorization\s*:/i.test($e)&&(le??=$e)}:void 0,Qe=zZe(xe,void 0,we);Qe.length&&be(`Removed the persisted checkout credential from ${xe} (${Qe.length} entr${Qe.length===1?"y":"ies"}).`)}let ge=VZe();ge.length&&be(`Removed ${ge.length} persisted checkout credential(s) from RUNNER_TEMP.`),le&&(Kr(le.replace(/^AUTHORIZATION:\s*\S+\s+/i,"")),l.adoptCheckoutAuthHeader(le),be("Deliver pushes with the credential the checkout was made with."))}else Te("No githubToken or GitHub App credentials: the checkout's persisted git credential (if any) is left in place, and the stage sessions can reach it. Set persist-credentials: false on actions/checkout, or pass githubToken.");if(Ig.mkdirSync(d,{recursive:!0}),!Q){if(J=Vf.join(d,"skyramp_license.lic"),!e.skyrampLicenseFile)throw new Error("skyrampLicenseFile input is required");Ig.writeFileSync(J,e.skyrampLicenseFile,{mode:384})}let Y=await YBe(e);B=await j_e(Y,e,d),T=z_e({effort:Wgr(We("effort"),e.effort),useLocalAuth:e.useLocalAuth&&!e.useBedrock,claudeCodeVersion:r?.attempt.claudeCodeVersion}),await V_e(T),await W_e(T),T.setupAgentEnv(e,Y)}catch(Y){r&&ou(),await n?.couldNotStart(Y);let U=Y instanceof Error?Y.message:String(Y);await l.createProgressSink().render(gL(U,{runUrl:l.runUrl})).catch(()=>{}),await l.endRun({status:"failure",summary:`could not start: ${U}`});for(let[ie,le]of Object.entries(v_({admission:{admit:!0},startupError:Y instanceof Error?Y:new Error(U)})))pR(ie,le);Cl(`Skyramp Testbot could not start: ${U}`);return}if(e.generatedTestsMode!=="separate-branch"&&Te(`pipeline: staged delivers only as a separate tests PR; generatedTestsMode=${e.generatedTestsMode} means nothing is committed or pushed this run`),r&&!s&&(!Number.isFinite(r.timeoutMinutes)||r.timeoutMinutes<=0))throw ou(),new Error("Testbot V3: the frozen Maximum runtime is unavailable; validation cannot start without its execution limit");let V=r?Math.min(r.attempt.budgetMs(new Date),(r.timeoutMinutes??1/0)*6e4):(e.testbotTimeout||60)*6e4;if(V<=0)throw aat(),new Error("Testbot V3: setup used the run's whole budget; no time is left before the attempt deadline");let{stages:oe,planOnly:ce,withheld:D}=r&&!s?hat(r.attempt.license?.entitlements,r.attempt.manifest.sources):{};!s&&c.fromFork&&!D?.deliver&&(D={...D,deliver:Yue}),ce&&be("Testbot V3: this organization's plan does not include test generation, so this run only analyzes the change and recommends tests.");let P=!s&&e.generatedTestsMode==="separate-branch"&&!ce,N=r&&P&&!D?.deliver?gat(r.attempt.writeAllowed):void 0;N&&(be(`Testbot V3: ${N}.`),{stages:oe,planOnly:ce,withheld:D}=mat(D??{},N));let K=r&&!s?fat(r.attempt.manifest,r.sources):void 0;K&&(be(`Testbot V3: ${Sw}; Testbot runs no test and writes none.`),D=K);let{resumeSetup:k,previousSetup:q,setupBase:L}=s?await $at(r,t):{},H={admission:f,platform:l,watch:r?dat(r):void 0,log:$N,skipReport:s,run:{runDir:p,fresh:!0,budgetMs:V,...s?{stages:["onboard","deploy"],skipReport:!0,onStageEvent:Dat(r,i,!!R,Vf.join(p,"outputs")),onStageAttempt:Nat(i,!!R)}:{},...r&&!s?{onStageEvent:Pat(r,i)}:{},...oe?{stages:oe}:{},withheld:D,skyrampRunUrl:r?.attempt.skyrampRunUrl,...r&&!s?Mat(r):{},...r&&s?{checkDeployedRevisions:rde(r)}:{},model:We("model").trim()||void 0,resolveModel:$ot(e),inputs:{repositoryPath:i,repositorySlug:r?.layout.repositorySlug,pullRequestRepository:r?.pullRequest?.repository,...r?{deliveryOrigin:Mtt(r.attempt.manifest)}:{},baseBranch:!r&&c.baseRef?`origin/${c.baseRef}`:void 0,relatedRepos:m,headBranch:r?void 0:c.headRef,prTitle:c.title,prDescription:c.body,...r?.pullRequests?.length?{pullRequests:r.pullRequests}:{},...r?.requirementItems?.length?{requirementItems:r.requirementItems}:{},...r?.instructions?.length?{instructions:r.instructions}:{},...r?.attempt.requestedBy?{requestedBy:r.attempt.requestedBy}:{},...r?{skyrampRunUrl:r.attempt.skyrampRunUrl}:{},...r?.testPlacements?.length?{testPlacements:r.testPlacements}:{},...r?.sharedEnvironment?{sharedEnvironment:r.sharedEnvironment}:{},...r?.scheduledValidation?{scheduledValidation:r.scheduledValidation}:{},...r?.testEnvironment?{appRunning:Xue(r.testEnvironment)}:{},planOnly:ce,unitPath:w,skyrampMcp:{command:B.command,args:B.args.split(" ").filter(Boolean),licensePath:J,runToken:Q,...r?Aat(r):{}},deliver:P&&!N,deliverBranch:We("deliverBranch")||void 0,trustedChecks:Ggr(We("trustedChecks")),deliverMode:c.eventName==="issue_comment"?"append":"replace",provisionRuntime:!0,testPackageDir:We("testPackageDir").trim()||void 0,skyrampHelpers:xst(We("skyrampHelpers")),runnerPlatform:l.name,onboard:E&&!ce,sutGuidance:g,sutEnvironment:S,...r&&!s?{sutCredentials:(r.attempt.manifest.credentials??[]).filter(Y=>Y.purpose!=="model_provider")}:{},setupEvents:s,runEvents:!!(r&&!s),credentialRelay:!!(s&&r?.relayKey),answerWaitMinutes:x,...k?{resumeSetup:k}:{},...q?{previousSetup:q}:{},...L?{setupBase:L}:{},...R?{testEnvironment:R}:{},repositoryIds:I},sessionRunner:Ert(T.binary),sutAuth:{tokenCommand:e.authTokenCommand||void 0,uiCredentials:e.uiCredentials||void 0,sessionEnv:dot(We("sessionEnv")),maskSecret:Y=>Kr(Y),attempts:e.authTokenRetries,retryDelaySec:e.authTokenRetryDelay}}};n?.runBegins();let W;s&&r.recheck?(W=await que({...H,run:{...H.run,stages:["deploy"],skipReport:!0,onStageEvent:bat(r,i),onStageAttempt:void 0,inputs:{...H.run.inputs,onboard:!1,recheck:!0,recheckCredentials:yR(r.recheck.recipe),...r.recheck.recipe.environment?{recheckEnvironment:{address:r.recheck.recipe.environment.address}}:{}}}}),W.summary&&await Sat(r,W.summary,B.nodeModulesDir)):W=await que(H),r&&s?W.summary?r.recheck||await Oat(r,W.summary,B.nodeModulesDir,!!R):Te("Testbot V3: the run ran no stages, so there is no SUT recipe to send; Skyramp records the run as an infrastructure error."):r&&await Rat(r,{...W.summary,deliverWithheld:D?.deliver},B.nodeModulesDir),W.admission.admit&&await qot(p,l);let Z=v_(W,{skippedSelfTrigger:!W.admission.admit});for(let[Y,U]of Object.entries(Z))pR(Y,U);if(W.summary){await Got(W.summary,W.outcome,r?.attempt.skyrampRunUrl,{sutSetup:s,closure:r?.attempt.closure}),be(`Staged run ${W.summary.runId}: ${W.outcome?.summary} (state: ${W.summary.stateFilePath})`);let Y=nI(W.summary.stateFilePath);Y&&(Ib("Stage breakdown (time / cost / context)"),be(Bot(Y,{order:W.summary.stages.map(U=>U.name),wallMinutes:Rj(Y)})),Rb())}n&&W.startupError&&await jue(W.startupError,n.link),W.startupError?Cl(`Skyramp Testbot could not start: ${W.startupError.message}`):W.outcome&&W.outcome.status==="failure"&&Cl(`Skyramp Testbot: ${W.outcome.summary}`)}function Wgr(e,t){return(e??"").trim()?t:XTe}Vt();var Gat="SKYRAMP_RELAY_VALUE",ode=e=>mC.credentialRelay.replace(":relayId",e);async function Jgr(e,t,r){let n=JOe.parse(await hw(r,"GET",ode(e),void 0));if(n.relayId!==e)throw new Error(`The Skyramp app answered relay ${e} with another relay`);let s=t===void 0||t.trim()===""?{schemaVersion:1,status:"empty"}:{schemaVersion:1,status:"sealed",sealed:htt(t,n.publicKey,xF(n.relayId,n.attemptId,n.credentialName))};return await hw(r,"PUT",ode(e),s),s.status}async function jat(e=process.env){let t=e[Gat];delete e[Gat],t!==void 0&&t.trim()!==""&&Kr(t);let r=We("skyrampRelayRun").trim();if(!lm.test(r)){Cl("The credential-relay pipeline needs the skyrampRelayRun input: the relay id Skyramp dispatched the workflow with.");return}let n={origin:I_(),idToken:rn(e).takeIdToken(),mask:s=>Kr(s),log:s=>be(s)};try{let s=await Jgr(r,t,n);be(`Testbot V3: relay ${r} answered: ${s}.`)}catch(s){if(s instanceof nn&&s.status===409){be(`Testbot V3: relay ${r} already has an answer, or closed; nothing more to send.`);return}let i=s instanceof Error?s.message:String(s);try{await hw(n,"PUT",ode(r),{schemaVersion:1,status:"failed"}),Te(`Testbot V3: could not relay the credential, and told Skyramp so: ${i}`)}catch{Cl(`Testbot V3: could not relay the credential: ${i}`)}}}var Ygr={useBedrock:"false",skipTargetTeardown:"false",skyrampMcpSource:"npm",skyrampMcpGithubRef:"main",nodeVersion:"lts/*",skipTargetSetup:"false",targetReadyCheckTimeout:"1800",targetReadyCheckInterval:"30",targetReadyCheckDiagnosticsCommand:`docker ps -a --format 'table {{.Names}} {{.Status}} {{.Ports}}' && docker ps -a --format '{{.Names}}' | while read name; do [ -n "$name" ] && echo "--- logs $name (last 30) ---" && docker logs --tail 30 "$name"; done`,workingDirectory:".",autoCommit:"true",commitMessage:"Skyramp Testbot: test maintenance suggestions",generatedTestsMode:"separate-branch",pipeline:"staged",postPrComment:"true",testbotMaxRetries:"3",testbotRetryDelay:"10",testExecutionTimeout:"300",testbotTimeout:"60",targetSetupRetries:"3",targetSetupRetryDelay:"10",authTokenRetries:"6",authTokenRetryDelay:"10",reportCollapsed:"true",language:"en",enableDebug:"true",sutSetupMode:"none"};function Hat(e=process.env){for(let[t,r]of Object.entries(Ygr)){let n=`INPUT_${t.replace(/ /g,"_").toUpperCase()}`;(e[n]??"").trim()===""&&(e[n]=r)}}var Kgr="1.0.0";function Vat(e,t=Kgr){let r=zat(e??""),n=zat(t);if(!r||!n)return;let s=()=>`This Testbot engine needs the Skyramp Testbot action ${t} or later, and this workflow uses ${e}. Change the workflow to skyramp/testbot@v${n.core[0]}, or set engineVersion to an older engine.`;for(let i=0;i<3;i++){if(r.core[i]>n.core[i])return;if(r.core[i]<n.core[i])return s()}return r.preRelease&&!n.preRelease?s():void 0}function zat(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(-)?/.exec(e.trim());return t?{core:[Number(t[1]),Number(t[2]),Number(t[3])],preRelease:t[4]==="-"}:void 0}var Wat=require("child_process"),ip=X(require("fs")),cde=X(require("path")),lde=require("string_decoder");var Xgr="skyramp-testbot-state",Zgr=/^\$\([^)]*\)$/;function eAr(e){for(let[t,r]of Object.entries(e))r!==void 0&&Zgr.test(r)&&delete e[t]}function tAr(e){let t={},r=ip.existsSync(e)?ip.readFileSync(e,"utf-8"):"",n=/^([^\r\n<]+)<<(\S+)\r?\n([\s\S]*?)\r?\n\2\r?$/gm;for(let s=n.exec(r);s;s=n.exec(r))t[s[1]]=s[3];return t}function Jat(e,t={}){let r=t.env??process.env;if(!ew(r))return!1;eAr(r),QZe(r);let n=r.AGENT_TEMPDIRECTORY||r.RUNNER_TEMP;if(n){r.RUNNER_TEMP??=n;let o=cde.join(n,Xgr);if(e==="main")ip.writeFileSync(o,"",{mode:384});else for(let[a,c]of Object.entries(tAr(o)))r[`STATE_${a}`]=c;r.GITHUB_STATE=o;for(let[a,c]of[["GITHUB_OUTPUT","output"],["GITHUB_ENV","env"],["GITHUB_PATH","path"],["GITHUB_STEP_SUMMARY",`summary-${e}.md`]])r[a]=cde.join(n,`skyramp-testbot-${c}`),ip.writeFileSync(r[a],"",{mode:384})}let s=t.stdout??r===process.env;s&&rAr(r,t.write);let i=r.GITHUB_STEP_SUMMARY;if(s&&i){let o=t.write??(a=>BN(a.replace(/\n$/,"")));process.once("exit",()=>{ip.existsSync(i)&&ip.statSync(i).size>0&&o(`${Tx("task.uploadsummary",{},i)}
|
|
805
|
+
`).join(""))}catch(f){Te(`Testbot V3: could not say that deploy waits for the credential check: ${f instanceof Error?f.message:String(f)}`)}}if(s==="deploy"&&i==="finished"&&(o==="passed"||o==="failed")){let d=kat(r),p=o==="passed"&&n!==void 0&&OF(np(Ji.join(n,"deploy.json")));Bat(t,"check",[p?d.passed:d.failed],"how deploy ended")}let a=Pgr[s],c=i==="finished",l=o==="aborted"?"skipped":o,u=a?rle(e.attempt,{schemaVersion:1,stage:a,event:c?"finished":"started",...c&&l?{status:l}:{}}).catch(d=>Te(`Testbot V3: could not report ${s} ${i}: ${d instanceof Error?d.message:String(d)}`)):Promise.resolve();s==="deploy"&&c&&e.setupEvents?.stopWhen(u)}}var np=e=>{try{return JSON.parse(hi.readFileSync(e,"utf-8"))}catch{return}};async function Oat(e,t,r,n=!1){try{await e.setupEvents?.stop(),e.stopKey?await Qgr(e,e.stopKey,t.outputsDir):await Ogr(e,t,r,n)}finally{await e.setupEvents?.stop()}}async function Ogr(e,t,r,n){if(t.aborted?ps("cancelled"):t.timedOut&&ps("timed_out"),tde(t))return;let s=t.stateFilePath?np(t.stateFilePath):void 0,i=!t.aborted&&(t.timedOut||s?.stages.onboard?.attempts.at(-1)?.timedOut===!0),o=t.outputsDir?np(Ji.join(t.outputsDir,"onboard.json")):void 0,a=e.layout.repositoryPath,c=o??(i&&!n?Zot(a,crt(a,_at(e,!1)),gw):void 0);if(!c){Te("Testbot V3: onboard wrote no answer, so there is no SUT recipe to send; Skyramp records the run as an infrastructure error.");return}if(o||be("Testbot V3: the setup's time ran out before onboard answered; sending what it found as a blocked SUT recipe."),await Jue(e))return;let l=t.outputsDir?np(Ji.join(t.outputsDir,"deploy.json")):void 0,u=s?.stages.onboard?.status==="passed"?LN(c,ep(Sc())):[],d=s?.stages.deploy?.attempts?.reduce((p,f)=>p+(f.totalMs??f.durationMs??0),0);try{let p=l?rw(e.layout.repositoryPath):void 0,f=c.environment&&c.status!=="blocked",m=f?await Qat(e,c,VW(c,l,p)):void 0,A=f&&c.environment&&!m?await vQe(c.environment,c.components.map(g=>g.name),void 0,[...fc(e),...pc()]):void 0,E=WW(c,l,{deployed:A,revisionCheck:m,recipeFiles:p,deployDurationSeconds:d?Math.round(d/1e3):void 0,unsupplied:d7e(c,Pwe(e.attempt.manifest.credentials.map(g=>g.name))),awaitsCredentialCheck:l?[]:u,timeLimit:i,repository:e.layout.repositorySlug});await sle(e.attempt,{recipe:E,sources:e.sources,producer:{testbot:kj().version,mcp:ede(r)},secrets:[...fc(e),...pc()]}),xl(sp.recipeUploaded,"true"),xl(sp.recipeStatus,E.status),be(`Testbot V3: SUT recipe uploaded (${E.status}${E.replay?.outcome===jW?`, its deploy waiting for the check with ${u.join(", ")}`:""}); Skyramp derives the outcome.`)}catch(p){Te(`Testbot V3: the SUT recipe upload failed: ${p instanceof Error?p.message:String(p)}`)}}async function Qat(e,t,r){let n=dm(r.recipeFiles),s=TF(t.components,t.environment?.revisionSources??[]);return n?rde(e)(n.content,s,t.environment?.credentials??[]):void 0}function rde(e){return(t,r,n)=>EQe({content:t,components:r,credentials:n,modelCredentials:e.attempt.modelCredentials,read:s=>nde(e,s,n),resolveCommit:(s,i)=>Ptt(e.attempt,s,i),provider:e.attempt.manifest.execution.provider})}async function nde(e,t,r){let n;try{n=await e.attempt.readOnlyToken()}catch(o){return{ok:!1,error:`deployed-revisions.sh was not run: no read-only token (${o instanceof Error?o.message:String(o)})`}}let s=$n([...e.attempt.issuedTokens,...fc(e),...pc()]),i={...process.env,...Sc()};return gQe({content:t,env:mQe(n,r,e.attempt.modelCredentials,i,e.attempt.manifest.execution.provider),secrets:s})}function Mat(e){let t=dm(e.testEnvironment?.files),r=e.testEnvironment?.credentials??[];return t?{deployedRevisions:()=>nde(e,t.content,r)}:{}}async function Fat(e){return await e.platform?.artifactStore?.()??_ae()}var Lat=e=>[{slug:e.layout.repositorySlug,path:e.layout.repositoryPath},...e.layout.relatedRepos];async function Qgr(e,t,r){ps("cancelled");try{let n=r?np(Ji.join(r,"onboard-session.json"))?.sessionId:void 0;if(!n)throw new Error("onboard had not started a session");let s=rn(),i=await Wot({sessionId:n,key:t,checkouts:Lat(e),secrets:$n([...e.attempt.issuedTokens,...fc(e),...pc()]),artifacts:await Fat(e),name:["skyramp-setup-checkpoint",e.attempt.manifest.runId,s.runAttempt].filter(Boolean).join("-"),providerRunId:s.runId??"",now:new Date});await Wtt(e.attempt,i),be(`Testbot V3: saved where onboard was (${i.bytes} bytes, kept ${ET} days); resume the setup from Skyramp to continue it.`)}catch(n){Te(`Testbot V3: could not save where onboard was, so a resume of this setup starts over: ${n instanceof Error?n.message:String(n)}`)}}var sde="Could not restore where the setup stopped, so it starts over with the notes as they are now.",Mgr="Could not restore where the setup stopped, so it starts from the Target's ready recipe, with the notes as they are now.",Uat="Could not restore where the setup stopped, so it continues from what it found, with the notes as they are now.",Fgr="Could not restore where the setup stopped, so it continues from what it found and the Target's ready recipe, with the notes as they are now.";function Lgr(e){e.setupLines=e.setupLines?.map(t=>t===sde?Mgr:t===Uat?Fgr:t)}async function Ugr(e){if(!(!xg(e)||e.recheck))try{return await Ytt(e.attempt)??void 0}catch(t){Te(`Testbot V3: could not read what the setup before this one found: ${t instanceof Error?t.message:String(t)}`);return}}function $gr(e,t){if(t.kind!=="resume")return;let r=(e.setupLines??[]).filter(n=>n!==sde);e.setupLines=[...r,Uat]}async function qgr(e,t){if(!(!xg(e)||e.recheck))try{let r=await Jtt(e.attempt);if(!r)return;let n=await Jot({checkpoint:r,token:t??"",cwd:e.layout.repositoryPath,checkouts:Lat(e),artifacts:await Fat(e)});return be(`Testbot V3: resuming the stopped setup's onboard session ${n.sessionId.slice(0,8)} where it was.`),n}catch(r){Te(`Testbot V3: could not restore where the stopped setup was, so this setup starts over: ${r instanceof Error?r.message:String(r)}`),(e.setupLines??=[]).push(sde);return}}async function $at(e,t,r={checkpoint:qgr,context:Ugr,base:Sgr}){let n=await r.checkpoint(e,t),s=await r.context(e);s&&!n&&$gr(e,s);let i=!e.recheck&&!n?await r.base(e):void 0;i&&Lgr(e);let o=s?Cgr(e,s,i):void 0;return{...n?{resumeSetup:n}:{},...o?{previousSetup:o}:{},...i?{setupBase:i}:{}}}function Ggr(e){let t=e.split(/[\n,]/).map(r=>r.trim()).filter(Boolean);return t.length?t:void 0}function jgr(e,t={}){if(!t.sutSetup&&(e("onboard")??"").trim().toLowerCase()==="true")return"onboard is not supported on a run that tests a change \u2014 in the two-step pipeline a SUT setup runs on its own (preflight, onboard, deploy) and ends with a recipe, not a report. Set up the SUT from the Skyramp app's Setup page, or locally with the CLI's --onboard, and remove the input.";if((e("testRepoPath")??"").trim())return"testRepoPath is not supported by the staged pipeline (pipeline: staged) \u2014 it writes tests into the application checkout only, and the Action's token has no write access to another repository. Pin skyramp/testbot@v0.11 for cross-repository delivery, or remove the input."}async function Hgr(e,t,r,n=rn().workspace||process.cwd()){let s=(e("relatedRepoPaths")??"").trim();if(!s)return[];let i=[];for(let o of s.split(/[\n,]/).map(a=>a.trim()).filter(Boolean)){let a=Vf.resolve(n,o);if(!Vs(n,o)){r(`relatedRepoPaths: ${o} is outside the workspace \u2014 skipping`);continue}if(!Ig.existsSync(a)){r(`relatedRepoPaths: no checkout at ${o} \u2014 skipping`);continue}let c=await t(a);if(!c){r(`relatedRepoPaths: could not resolve owner/repo for ${o} (no origin remote?) \u2014 skipping`);continue}i.push({slug:c,path:a})}return i}async function zgr(e,t,r=rn()){if(!r.repository)return;let{id:n,slug:s}=r.repository;return(await t(e).catch(()=>{}))?.toLowerCase()===s.toLowerCase()?{[n]:s}:void 0}var ide=class{constructor(t){this.link=t}link;settled=!1;async couldNotStart(t){this.settled||(this.settled=!0,await jue(t,this.link))}runBegins(){this.settled=!0}};async function qat(){let e=We("skyrampRunId").trim(),t=e?new ide({origin:I_(),runId:e}):void 0,r;try{let n=tke();delete process.env.INPUT_SKYRAMPLICENSEFILE;let s=Lot(process.env),i=e?await yat(e,n):void 0;if(r=i,i&&"revisionRead"in i)return;await Vgr(n,s,i,t)}catch(n){throw await t?.couldNotStart(n),n}finally{r&&await Lj(r),r&&Ig.rmSync(Fj(),{recursive:!0,force:!0}),r&&Owe()}}async function Vgr(e,t,r,n){let s=r!==void 0&&xg(r);r&&(r.heldInputs=[e.skyrampLicenseFile].filter(Boolean));let i=r?r.layout.repositoryPath:Vf.resolve(e.workingDirectory||"."),o=r?()=>r.attempt.token():Uot(),a=r?void 0:t;a&&Kr(a);let c=Mot(),l=UZe({repositoryPath:r?.pullRequest?.path??i,prNumber:c.prNumber,tokenProvider:o,githubToken:a,repoSlug:r?r.pullRequest?.repository??r.layout.repositorySlug:void 0,allowedAuthors:!s&&e.allowedAuthors?.length?e.allowedAuthors:void 0,log:Y=>be(Y)},r?.attempt.skyrampRunUrl);r&&(r.platform=l);let u=await l.resolveContext().catch(()=>({}));c=Fot(c,u),be(`Staged pipeline \u2014 event: ${c.eventName??"?"}${c.action?`/${c.action}`:""}${c.prNumber?`, PR #${c.prNumber}`:""}${c.headRef?` (${c.headRef} \u2192 ${c.baseRef??"?"})`:""}`);let d=qb(),p=Vf.join(d,"staged");if(c.eventName==="pull_request"&&c.action==="closed"){let Y=c.merged===!1,U=Y?`PR #${c.prNumber} was closed without merging`:`PR #${c.prNumber} was merged`;if(Y&&c.headRef){let ie=await l.closeTestsPr({branch:qce(c.headRef,We("deliverBranch")||void 0),reason:`Closing: the pull request this tests PR targeted (#${c.prNumber}) was closed without being merged.`});ie.closed&&(U+=`; closed the tests PR ${ie.url??""}`.trimEnd())}be(`Staged pipeline \u2014 ${U}; nothing to run.`);for(let[ie,le]of Object.entries(v_({admission:{admit:!1,reason:U}},{skippedPrClosed:Y})))pR(ie,le);return}let f=await l.admitRun();if(!f.admit){be(`Staged pipeline \u2014 run skipped: ${f.reason}`);for(let[Y,U]of Object.entries(v_({admission:f},{skippedSelfTrigger:!0})))pR(Y,U);return}let m=r?r.layout.relatedRepos:await Hgr(Y=>We(Y),Y=>R4(Y),Y=>Te(Y)),A=jgr(Y=>We(Y),{sutSetup:s});if(A)throw new Error(A);let E=s,g=Oot(We("sutGuidance"),"sutGuidance input"),w=Sj(We("unitPath")),S,x,R;try{s?{sutEnvironment:S,answerWaitMinutes:x,testEnvironment:R}=await Tat(r):S=c7e(We("sutEnvironment"),"sutEnvironment input")}catch(Y){throw r&&ou(),Y}for(let Y of e2(S))Kr(Y);let I=r?Object.fromEntries(r.sources.map(Y=>[Y.repository.providerRepositoryId,Y.slug])):await zgr(i,Y=>R4(Y)),B,T,Q=r?.attempt.license?.runToken,J;try{if(t||o){let U=rn().workspace,ie=[...new Set([i,...m.map(xe=>xe.path),...U?WZe(U):[]].map(xe=>Vf.resolve(xe)))],le;for(let xe of ie){let we=xe===Vf.resolve(i)?$e=>{/^\s*authorization\s*:/i.test($e)&&(le??=$e)}:void 0,Qe=zZe(xe,void 0,we);Qe.length&&be(`Removed the persisted checkout credential from ${xe} (${Qe.length} entr${Qe.length===1?"y":"ies"}).`)}let ge=VZe();ge.length&&be(`Removed ${ge.length} persisted checkout credential(s) from RUNNER_TEMP.`),le&&(Kr(le.replace(/^AUTHORIZATION:\s*\S+\s+/i,"")),l.adoptCheckoutAuthHeader(le),be("Deliver pushes with the credential the checkout was made with."))}else Te("No githubToken or GitHub App credentials: the checkout's persisted git credential (if any) is left in place, and the stage sessions can reach it. Set persist-credentials: false on actions/checkout, or pass githubToken.");if(Ig.mkdirSync(d,{recursive:!0}),!Q){if(J=Vf.join(d,"skyramp_license.lic"),!e.skyrampLicenseFile)throw new Error("skyrampLicenseFile input is required");Ig.writeFileSync(J,e.skyrampLicenseFile,{mode:384})}let Y=await YBe(e);B=await j_e(Y,e,d),T=z_e({effort:Wgr(We("effort"),e.effort),useLocalAuth:e.useLocalAuth&&!e.useBedrock,claudeCodeVersion:r?.attempt.claudeCodeVersion}),await V_e(T),await W_e(T),T.setupAgentEnv(e,Y)}catch(Y){r&&ou(),await n?.couldNotStart(Y);let U=Y instanceof Error?Y.message:String(Y);await l.createProgressSink().render(gL(U,{runUrl:l.runUrl})).catch(()=>{}),await l.endRun({status:"failure",summary:`could not start: ${U}`});for(let[ie,le]of Object.entries(v_({admission:{admit:!0},startupError:Y instanceof Error?Y:new Error(U)})))pR(ie,le);Cl(`Skyramp Testbot could not start: ${U}`);return}if(e.generatedTestsMode!=="separate-branch"&&Te(`pipeline: staged delivers only as a separate tests PR; generatedTestsMode=${e.generatedTestsMode} means nothing is committed or pushed this run`),r&&!s&&(!Number.isFinite(r.timeoutMinutes)||r.timeoutMinutes<=0))throw ou(),new Error("Testbot V3: the frozen Maximum runtime is unavailable; validation cannot start without its execution limit");let V=r?Math.min(r.attempt.budgetMs(new Date),(r.timeoutMinutes??1/0)*6e4):(e.testbotTimeout||60)*6e4;if(V<=0)throw aat(),new Error("Testbot V3: setup used the run's whole budget; no time is left before the attempt deadline");let{stages:oe,planOnly:ce,withheld:D}=r&&!s?hat(r.attempt.license?.entitlements,r.attempt.manifest.sources):{};!s&&c.fromFork&&!D?.deliver&&(D={...D,deliver:Yue}),ce&&be("Testbot V3: this organization's plan does not include test generation, so this run only analyzes the change and recommends tests.");let P=!s&&e.generatedTestsMode==="separate-branch"&&!ce,N=r&&P&&!D?.deliver?gat(r.attempt.writeAllowed):void 0;N&&(be(`Testbot V3: ${N}.`),{stages:oe,planOnly:ce,withheld:D}=mat(D??{},N));let K=r&&!s?fat(r.attempt.manifest,r.sources):void 0;K&&(be(`Testbot V3: ${Sw}; Testbot runs no test and writes none.`),D=K);let{resumeSetup:k,previousSetup:q,setupBase:L}=s?await $at(r,t):{},H={admission:f,platform:l,watch:r?dat(r):void 0,log:$N,skipReport:s,run:{runDir:p,fresh:!0,budgetMs:V,...s?{stages:["onboard","deploy"],skipReport:!0,onStageEvent:Dat(r,i,!!R,Vf.join(p,"outputs")),onStageAttempt:Nat(i,!!R)}:{},...r&&!s?{onStageEvent:Pat(r,i)}:{},...oe?{stages:oe}:{},withheld:D,skyrampRunUrl:r?.attempt.skyrampRunUrl,...r&&!s?Mat(r):{},...r&&s?{checkDeployedRevisions:rde(r)}:{},model:We("model").trim()||void 0,resolveModel:$ot(e),inputs:{repositoryPath:i,repositorySlug:r?.layout.repositorySlug,pullRequestRepository:r?.pullRequest?.repository,...r?{deliveryOrigin:Mtt(r.attempt.manifest)}:{},baseBranch:!r&&c.baseRef?`origin/${c.baseRef}`:void 0,relatedRepos:m,headBranch:r?void 0:c.headRef,prTitle:c.title,prDescription:c.body,...r?.pullRequests?.length?{pullRequests:r.pullRequests}:{},...r?.requirementItems?.length?{requirementItems:r.requirementItems}:{},...r?.instructions?.length?{instructions:r.instructions}:{},...r?.attempt.requestedBy?{requestedBy:r.attempt.requestedBy}:{},...r?{skyrampRunUrl:r.attempt.skyrampRunUrl}:{},...r?.testPlacements?.length?{testPlacements:r.testPlacements}:{},...r?.sharedEnvironment?{sharedEnvironment:r.sharedEnvironment}:{},...r?.scheduledValidation?{scheduledValidation:r.scheduledValidation}:{},...r?.testEnvironment?{appRunning:Xue(r.testEnvironment)}:{},planOnly:ce,unitPath:w,skyrampMcp:{command:B.command,args:B.args.split(" ").filter(Boolean),licensePath:J,runToken:Q,...r?Aat(r):{}},deliver:P&&!N,deliverBranch:We("deliverBranch")||void 0,trustedChecks:Ggr(We("trustedChecks")),deliverMode:c.eventName==="issue_comment"?"append":"replace",...r?.firstQualification?{firstQualification:!0}:{},provisionRuntime:!0,testPackageDir:We("testPackageDir").trim()||void 0,skyrampHelpers:xst(We("skyrampHelpers")),runnerPlatform:l.name,onboard:E&&!ce,sutGuidance:g,sutEnvironment:S,...r&&!s?{sutCredentials:(r.attempt.manifest.credentials??[]).filter(Y=>Y.purpose!=="model_provider")}:{},setupEvents:s,runEvents:!!(r&&!s),credentialRelay:!!(s&&r?.relayKey),answerWaitMinutes:x,...k?{resumeSetup:k}:{},...q?{previousSetup:q}:{},...L?{setupBase:L}:{},...R?{testEnvironment:R}:{},repositoryIds:I},sessionRunner:Ert(T.binary),sutAuth:{tokenCommand:e.authTokenCommand||void 0,uiCredentials:e.uiCredentials||void 0,sessionEnv:dot(We("sessionEnv")),maskSecret:Y=>Kr(Y),attempts:e.authTokenRetries,retryDelaySec:e.authTokenRetryDelay}}};n?.runBegins();let W;s&&r.recheck?(W=await que({...H,run:{...H.run,stages:["deploy"],skipReport:!0,onStageEvent:bat(r,i),onStageAttempt:void 0,inputs:{...H.run.inputs,onboard:!1,recheck:!0,recheckCredentials:yR(r.recheck.recipe),...r.recheck.recipe.environment?{recheckEnvironment:{address:r.recheck.recipe.environment.address}}:{}}}}),W.summary&&await Sat(r,W.summary,B.nodeModulesDir)):W=await que(H),r&&s?W.summary?r.recheck||await Oat(r,W.summary,B.nodeModulesDir,!!R):Te("Testbot V3: the run ran no stages, so there is no SUT recipe to send; Skyramp records the run as an infrastructure error."):r&&await Rat(r,{...W.summary,deliverWithheld:D?.deliver},B.nodeModulesDir),W.admission.admit&&await qot(p,l);let Z=v_(W,{skippedSelfTrigger:!W.admission.admit});for(let[Y,U]of Object.entries(Z))pR(Y,U);if(W.summary){await Got(W.summary,W.outcome,r?.attempt.skyrampRunUrl,{sutSetup:s,closure:r?.attempt.closure}),be(`Staged run ${W.summary.runId}: ${W.outcome?.summary} (state: ${W.summary.stateFilePath})`);let Y=nI(W.summary.stateFilePath);Y&&(Ib("Stage breakdown (time / cost / context)"),be(Bot(Y,{order:W.summary.stages.map(U=>U.name),wallMinutes:Rj(Y)})),Rb())}n&&W.startupError&&await jue(W.startupError,n.link),W.startupError?Cl(`Skyramp Testbot could not start: ${W.startupError.message}`):W.outcome&&W.outcome.status==="failure"&&Cl(`Skyramp Testbot: ${W.outcome.summary}`)}function Wgr(e,t){return(e??"").trim()?t:XTe}Vt();var Gat="SKYRAMP_RELAY_VALUE",ode=e=>mC.credentialRelay.replace(":relayId",e);async function Jgr(e,t,r){let n=JOe.parse(await hw(r,"GET",ode(e),void 0));if(n.relayId!==e)throw new Error(`The Skyramp app answered relay ${e} with another relay`);let s=t===void 0||t.trim()===""?{schemaVersion:1,status:"empty"}:{schemaVersion:1,status:"sealed",sealed:htt(t,n.publicKey,xF(n.relayId,n.attemptId,n.credentialName))};return await hw(r,"PUT",ode(e),s),s.status}async function jat(e=process.env){let t=e[Gat];delete e[Gat],t!==void 0&&t.trim()!==""&&Kr(t);let r=We("skyrampRelayRun").trim();if(!lm.test(r)){Cl("The credential-relay pipeline needs the skyrampRelayRun input: the relay id Skyramp dispatched the workflow with.");return}let n={origin:I_(),idToken:rn(e).takeIdToken(),mask:s=>Kr(s),log:s=>be(s)};try{let s=await Jgr(r,t,n);be(`Testbot V3: relay ${r} answered: ${s}.`)}catch(s){if(s instanceof nn&&s.status===409){be(`Testbot V3: relay ${r} already has an answer, or closed; nothing more to send.`);return}let i=s instanceof Error?s.message:String(s);try{await hw(n,"PUT",ode(r),{schemaVersion:1,status:"failed"}),Te(`Testbot V3: could not relay the credential, and told Skyramp so: ${i}`)}catch{Cl(`Testbot V3: could not relay the credential: ${i}`)}}}var Ygr={useBedrock:"false",skipTargetTeardown:"false",skyrampMcpSource:"npm",skyrampMcpGithubRef:"main",nodeVersion:"lts/*",skipTargetSetup:"false",targetReadyCheckTimeout:"1800",targetReadyCheckInterval:"30",targetReadyCheckDiagnosticsCommand:`docker ps -a --format 'table {{.Names}} {{.Status}} {{.Ports}}' && docker ps -a --format '{{.Names}}' | while read name; do [ -n "$name" ] && echo "--- logs $name (last 30) ---" && docker logs --tail 30 "$name"; done`,workingDirectory:".",autoCommit:"true",commitMessage:"Skyramp Testbot: test maintenance suggestions",generatedTestsMode:"separate-branch",pipeline:"staged",postPrComment:"true",testbotMaxRetries:"3",testbotRetryDelay:"10",testExecutionTimeout:"300",testbotTimeout:"60",targetSetupRetries:"3",targetSetupRetryDelay:"10",authTokenRetries:"6",authTokenRetryDelay:"10",reportCollapsed:"true",language:"en",enableDebug:"true",sutSetupMode:"none"};function Hat(e=process.env){for(let[t,r]of Object.entries(Ygr)){let n=`INPUT_${t.replace(/ /g,"_").toUpperCase()}`;(e[n]??"").trim()===""&&(e[n]=r)}}var Kgr="1.0.0";function Vat(e,t=Kgr){let r=zat(e??""),n=zat(t);if(!r||!n)return;let s=()=>`This Testbot engine needs the Skyramp Testbot action ${t} or later, and this workflow uses ${e}. Change the workflow to skyramp/testbot@v${n.core[0]}, or set engineVersion to an older engine.`;for(let i=0;i<3;i++){if(r.core[i]>n.core[i])return;if(r.core[i]<n.core[i])return s()}return r.preRelease&&!n.preRelease?s():void 0}function zat(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(-)?/.exec(e.trim());return t?{core:[Number(t[1]),Number(t[2]),Number(t[3])],preRelease:t[4]==="-"}:void 0}var Wat=require("child_process"),ip=X(require("fs")),cde=X(require("path")),lde=require("string_decoder");var Xgr="skyramp-testbot-state",Zgr=/^\$\([^)]*\)$/;function eAr(e){for(let[t,r]of Object.entries(e))r!==void 0&&Zgr.test(r)&&delete e[t]}function tAr(e){let t={},r=ip.existsSync(e)?ip.readFileSync(e,"utf-8"):"",n=/^([^\r\n<]+)<<(\S+)\r?\n([\s\S]*?)\r?\n\2\r?$/gm;for(let s=n.exec(r);s;s=n.exec(r))t[s[1]]=s[3];return t}function Jat(e,t={}){let r=t.env??process.env;if(!ew(r))return!1;eAr(r),QZe(r);let n=r.AGENT_TEMPDIRECTORY||r.RUNNER_TEMP;if(n){r.RUNNER_TEMP??=n;let o=cde.join(n,Xgr);if(e==="main")ip.writeFileSync(o,"",{mode:384});else for(let[a,c]of Object.entries(tAr(o)))r[`STATE_${a}`]=c;r.GITHUB_STATE=o;for(let[a,c]of[["GITHUB_OUTPUT","output"],["GITHUB_ENV","env"],["GITHUB_PATH","path"],["GITHUB_STEP_SUMMARY",`summary-${e}.md`]])r[a]=cde.join(n,`skyramp-testbot-${c}`),ip.writeFileSync(r[a],"",{mode:384})}let s=t.stdout??r===process.env;s&&rAr(r,t.write);let i=r.GITHUB_STEP_SUMMARY;if(s&&i){let o=t.write??(a=>BN(a.replace(/\n$/,"")));process.once("exit",()=>{ip.existsSync(i)&&ip.statSync(i).size>0&&o(`${Tx("task.uploadsummary",{},i)}
|
|
806
806
|
`)})}return!0}function rAr(e,t){let r=process.stdout.write.bind(process.stdout),n=o=>e[kN]==="1"?Oae(o,e):void r(o.command!==void 0?`${o.command}
|
|
807
807
|
`:o.text??""),s=t??(o=>n({command:o.replace(/\n$/,"")})),i=t??(o=>n({text:o}));process.stdout.write=((o,...a)=>{let c=typeof o=="string"?o:Buffer.from(o).toString("utf-8"),l="";for(let d of c.split(/(?<=\n)/)){let p=d.startsWith("::")?TZe(d):void 0;if(!p){l+=d;continue}l&&i(l),l="";for(let f of p)s(`${f}
|
|
808
808
|
`)}return l&&i(l),a.find(d=>typeof d=="function")?.(),!0})}var nAr=64*1024;function ade(e){let t=new lde.StringDecoder("utf8"),r="",n=s=>e(GG(s));return{push(s){r+=typeof s=="string"?s:t.write(s);let i=r.lastIndexOf(`
|
package/dist/post.js
CHANGED
|
@@ -158,7 +158,7 @@ ${Qc}: ${e}`:r;t(["log","-1","--format=%(trailers:key=Signed-off-by,valueonly)"]
|
|
|
158
158
|
`).slice(1).join(`
|
|
159
159
|
`).trim(),r=UD(n);return r?{prFailure:"hook",prDetail:`${r}
|
|
160
160
|
${n}`}:{prFailure:"unknown",prDetail:e}}async function e4(t,e,n,r,s,i){let o=rF(r.path,t.runDir),c=process.env.PATH;o.dir&&(process.env.PATH=sF(o).PATH);try{return await t4(t,e,n,r,s,i)}finally{o.dir&&(process.env.PATH=c),o.cleanup()}}async function t4(t,e,n,r,s,i){let o=r.slug,c,l=!1,d;try{let A=r.path,f=Ze(t,"finalize.json"),h=wF(t.inputs.requirementItems),y=jD(A),B=Se=>HD(Se,y,s),v=B(Rc(f?.commit?.message||n.commitMessage||"Skyramp Testbot: add tests",h)),D=tF(t.outputsDir)??n,k=B(Rc(D.commitMessage,h)||Rc(n.commitMessage,h)||v).split(`
|
|
161
|
-
`)[0],_={name:Cs,email:oi},T=!!y.signOff;if(!T&&e.listCommitChecks){let Se=i?.headSha??Ft(A,["rev-parse","HEAD"]);try{T=(await e.listCommitChecks({repository:o,revision:Se}))?.records.some(Fe=>Fe.name.trim().toLowerCase()==="dco"&&Fe.headSha===Se&&(!Fe.repository||Fe.repository.toLowerCase()===o.toLowerCase()))??!1}catch{console.warn(`[deliver] could not read commit checks for ${o}`)}}let F=t.inputs.deliverRemote||"origin",U=BF(A,RF),K=BF(A,kF);if(U&&!K)throw new Error(`${o}: the checkout records a merged base but not what it merged`);let ee=U?LC(void 0,void 0,A):i?i.headBranch||LC(t.inputs.headBranch,t.inputs.baseBranch,A):LC(void 0,void 0,A),V=t.inputs.pullRequests;i?.prNumber!=null&&!V?.some(Se=>Se.repository.toLowerCase()===o.toLowerCase())&&(V=[...V??[],{repository:o,number:String(i.prNumber)}]);let le=V?.some(Se=>Se.repository.toLowerCase()===o.toLowerCase())?void 0:t.inputs.deliveryOrigin,$e=U||!le?K:void 0,Re=$e?HZ(o,ee,$e):jZ(V,o,ee,le),_e=GZ(ee,t.inputs.deliverBranch)+($e?`-merge-${Re}`:le?`-source-${le.number}-${Re}`:""),Ue=ND(gF(JZ(D,t,r),{audience:"testbot-pr",requestedBy:t.inputs.requestedBy,sourcePullRequest:le&&`${le.repository.namespace}/${le.repository.name}#${le.number}`}),t.inputs.skyrampRunUrl),de=i?"pr-body.md":`pr-body-${vF(o)}.md`,ze=gi.join(t.outputsDir,de);Lr.writeFileSync(ze,Ue);let N=Ft(A,["rev-parse","HEAD"]),at=U??N;Ft(A,["checkout","-B",_e]),c=_e,Ft(A,["reset"]);for(let Se of s)qZ(gi.join(A,Se),h);let Oe=[];for(let Se of s)try{Ft(A,["--literal-pathspecs","add","--",Se])}catch{Oe.push(Se)}try{Ft(A,["diff","--cached","--quiet"])}catch{try{let Se=Ft(A,["interpret-trailers","--trailer",`${lf}: ${Re}`,"--trailer",`${Qc}: ${N}`,"--trailer",`${RC}: ${at}`],v),It=T?uf(Se,_):Se;Ft(A,["-c",`user.name=${_.name}`,"-c",`user.email=${_.email}`,"commit","-m",It])}catch(Se){throw new gf(Se)}l=!0}d=Ft(A,["rev-parse","HEAD"]);let Ot,ct=U??i?.headSha;if(l&&ct&&ct!==N){let Se=!1;try{Ft(A,["checkout","-q","-B",c,ct]),Se=!0,Ft(A,["-c",`user.name=${_.name}`,"-c",`user.email=${_.email}`,"cherry-pick","--keep-redundant-commits",d]),Se=!1,kC(It=>Ft(A,It),ct),d=Ft(A,["rev-parse","HEAD"])}catch(It){try{Ft(A,["cherry-pick","--abort"])}catch{}Ft(A,["checkout","-q","-B",c,d]);let Fe=af(qo(It),1/0);if(U&&!Se)throw It;if(U)return{thrown:!1,record:{schemaVersion:1,repository:o,branch:c,remote:F,base:ee,committed:l,commitSha:d,pushed:!1,prAction:"skipped",prTitle:k,unstaged:Oe,reason:`the tests do not apply to ${ee} at ${U.slice(0,12)} without the merged revisions (${Fe}), so no tests PR was opened`}};Ot=`tests committed on the checkout's merge commit (re-cut onto ${ct.slice(0,12)} failed: ${Fe})`}}let yr=i?{}:{repositoryPath:A,repoSlug:o,devPr:null};if(!l){let Se=await e.markTestsPrUnchanged({branch:c,...yr});return{thrown:!1,record:{schemaVersion:1,repository:o,branch:c,remote:F,base:ee,committed:!1,commitSha:d,pushed:!1,prAction:Se.action==="unchanged"?"unchanged":"skipped",prUrl:Se.url,prTitle:k,unstaged:Oe,reason:Se.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 Je=await e.publishTestsPr({repositoryPath:A,...yr,remote:F,branch:c,base:ee,commitSha:d,title:k,bodyFile:ze,mode:t.inputs.deliverMode,deliveryOwner:Re,runUrl:t.inputs.skyrampRunUrl,signal:t.signal,deadlineMs:t.deadlineMs});return{thrown:!1,record:{schemaVersion:1,repository:o,branch:c,remote:F,base:Je.base,requestedBase:ee,committed:l,commitSha:d,pushed:Je.pushed,...Je.pushedCommits?{pushedCommits:Je.pushedCommits}:{},...Je.deliveredCommit?{deliveredCommit:Je.deliveredCommit}:{},prAction:Je.action,...Je.retargetedAs?{retargetedAs:Je.retargetedAs}:{},prUrl:Je.url,prTitle:k,...Je.failure?{prFailure:Je.failure,prDetail:Je.detail}:{},...Ot?{cutNote:Ot}:{},...Je.action==="skipped"&&Je.detail?{reason:Je.detail}:{},unstaged:Oe}}}catch(A){return{thrown:!0,record:{schemaVersion:1,repository:o,branch:c,committed:l,commitSha:d,pushed:!1,prAction:"failed",...XZ(A),unstaged:[]}}}}var spe={name:"deliver",timeoutMinutes:5,execute:WZ,validateInput:t=>{let e=BC(t);return e?{ok:!1,reasons:[e]}:OZ(t)},requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var xF=ie(require("fs")),_l="SKYRAMP_AZURE_SUPERVISED",$C=3;function mf(t){return t.replace(/##(?=(?:vso)?\[)/gi,"#\u200B#")}function OC(t,e=process.env){e[_l]==="1"?xF.writeSync($C,`${JSON.stringify(t)}
|
|
161
|
+
`)[0],_={name:Cs,email:oi},T=!!y.signOff;if(!T&&e.listCommitChecks){let Se=i?.headSha??Ft(A,["rev-parse","HEAD"]);try{T=(await e.listCommitChecks({repository:o,revision:Se}))?.records.some(Fe=>Fe.name.trim().toLowerCase()==="dco"&&Fe.headSha===Se&&(!Fe.repository||Fe.repository.toLowerCase()===o.toLowerCase()))??!1}catch{console.warn(`[deliver] could not read commit checks for ${o}`)}}let F=t.inputs.deliverRemote||"origin",U=BF(A,RF),K=BF(A,kF);if(U&&!K)throw new Error(`${o}: the checkout records a merged base but not what it merged`);let ee=U?LC(void 0,void 0,A):i?i.headBranch||LC(t.inputs.headBranch,t.inputs.baseBranch,A):LC(void 0,void 0,A),V=t.inputs.pullRequests;i?.prNumber!=null&&!V?.some(Se=>Se.repository.toLowerCase()===o.toLowerCase())&&(V=[...V??[],{repository:o,number:String(i.prNumber)}]);let le=V?.some(Se=>Se.repository.toLowerCase()===o.toLowerCase())?void 0:t.inputs.deliveryOrigin,$e=U||!le?K:void 0,Re=$e?HZ(o,ee,$e):jZ(V,o,ee,le),_e=GZ(ee,t.inputs.deliverBranch)+($e?`-merge-${Re}`:le?`-source-${le.number}-${Re}`:""),Ue=ND(gF(JZ(D,t,r),{audience:"testbot-pr",requestedBy:t.inputs.requestedBy,sourcePullRequest:le&&`${le.repository.namespace}/${le.repository.name}#${le.number}`}),t.inputs.skyrampRunUrl),de=i?"pr-body.md":`pr-body-${vF(o)}.md`,ze=gi.join(t.outputsDir,de);Lr.writeFileSync(ze,Ue);let N=Ft(A,["rev-parse","HEAD"]),at=U??N;Ft(A,["checkout","-B",_e]),c=_e,Ft(A,["reset"]);for(let Se of s)qZ(gi.join(A,Se),h);let Oe=[];for(let Se of s)try{Ft(A,["--literal-pathspecs","add","--",Se])}catch{Oe.push(Se)}try{Ft(A,["diff","--cached","--quiet"])}catch{try{let Se=Ft(A,["interpret-trailers","--trailer",`${lf}: ${Re}`,"--trailer",`${Qc}: ${N}`,"--trailer",`${RC}: ${at}`],v),It=T?uf(Se,_):Se;Ft(A,["-c",`user.name=${_.name}`,"-c",`user.email=${_.email}`,"commit","-m",It])}catch(Se){throw new gf(Se)}l=!0}d=Ft(A,["rev-parse","HEAD"]);let Ot,ct=U??i?.headSha;if(l&&ct&&ct!==N){let Se=!1;try{Ft(A,["checkout","-q","-B",c,ct]),Se=!0,Ft(A,["-c",`user.name=${_.name}`,"-c",`user.email=${_.email}`,"cherry-pick","--keep-redundant-commits",d]),Se=!1,kC(It=>Ft(A,It),ct),d=Ft(A,["rev-parse","HEAD"])}catch(It){try{Ft(A,["cherry-pick","--abort"])}catch{}Ft(A,["checkout","-q","-B",c,d]);let Fe=af(qo(It),1/0);if(U&&!Se)throw It;if(U)return{thrown:!1,record:{schemaVersion:1,repository:o,branch:c,remote:F,base:ee,committed:l,commitSha:d,pushed:!1,prAction:"skipped",prTitle:k,unstaged:Oe,reason:`the tests do not apply to ${ee} at ${U.slice(0,12)} without the merged revisions (${Fe}), so no tests PR was opened`}};Ot=`tests committed on the checkout's merge commit (re-cut onto ${ct.slice(0,12)} failed: ${Fe})`}}let yr=i?{}:{repositoryPath:A,repoSlug:o,devPr:null};if(!l){let Se=await e.markTestsPrUnchanged({branch:c,...yr});return{thrown:!1,record:{schemaVersion:1,repository:o,branch:c,remote:F,base:ee,committed:!1,commitSha:d,pushed:!1,prAction:Se.action==="unchanged"?"unchanged":"skipped",prUrl:Se.url,prTitle:k,unstaged:Oe,reason:Se.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 Je=await e.publishTestsPr({repositoryPath:A,...yr,remote:F,branch:c,base:ee,commitSha:d,title:k,bodyFile:ze,mode:t.inputs.deliverMode,deliveryOwner:Re,...t.inputs.firstQualification?{firstQualification:!0}:{},runUrl:t.inputs.skyrampRunUrl,signal:t.signal,deadlineMs:t.deadlineMs});return{thrown:!1,record:{schemaVersion:1,repository:o,branch:c,remote:F,base:Je.base,requestedBase:ee,committed:l,commitSha:d,pushed:Je.pushed,...Je.pushedCommits?{pushedCommits:Je.pushedCommits}:{},...Je.deliveredCommit?{deliveredCommit:Je.deliveredCommit}:{},prAction:Je.action,...Je.retargetedAs?{retargetedAs:Je.retargetedAs}:{},prUrl:Je.url,prTitle:k,...Je.failure?{prFailure:Je.failure,prDetail:Je.detail}:{},...Ot?{cutNote:Ot}:{},...Je.action==="skipped"&&Je.detail?{reason:Je.detail}:{},unstaged:Oe}}}catch(A){return{thrown:!0,record:{schemaVersion:1,repository:o,branch:c,committed:l,commitSha:d,pushed:!1,prAction:"failed",...XZ(A),unstaged:[]}}}}var spe={name:"deliver",timeoutMinutes:5,execute:WZ,validateInput:t=>{let e=BC(t);return e?{ok:!1,reasons:[e]}:OZ(t)},requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var xF=ie(require("fs")),_l="SKYRAMP_AZURE_SUPERVISED",$C=3;function mf(t){return t.replace(/##(?=(?:vso)?\[)/gi,"#\u200B#")}function OC(t,e=process.env){e[_l]==="1"?xF.writeSync($C,`${JSON.stringify(t)}
|
|
162
162
|
`):process.stdout.write(t.command!==void 0?`${t.command}
|
|
163
163
|
`:t.text??"")}function VC(t){OC({command:t})}function TF(t){return t.replace(/%/g,"%AZP25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function n4(t){return TF(t).replace(/;/g,"%3B").replace(/]/g,"%5D")}function yf(t,e,n){let r=Object.entries(e).map(([s,i])=>`${s}=${n4(i)}`).join(";");return`##vso[${t}${r?` ${r}`:""}]${TF(n)}`}function NF(t){if(!t)return[];let e=t.split(/\r?\n/).filter(n=>n.trim()&&n!==t);return[t,...e].map(n=>yf("task.setsecret",{},n))}function DF(t,e=VC){for(let n of NF(t))e(n)}function r4(t){return t.replace(/%0D/g,"\r").replace(/%0A/g,`
|
|
164
164
|
`).replace(/%25/g,"%")}function FF(t){let e=/^::([a-z-]+)(?: [^:]*)?::(.*)$/s.exec(t.replace(/\r?\n$/,""));if(!e)return;let[,n,r]=e,s=r4(r),i=mf(s);switch(n){case"add-mask":return NF(s);case"warning":case"error":return[yf("task.logissue",{type:n},i)];case"notice":return[i];case"debug":return i.split(`
|
package/dist/runner-client.cjs
CHANGED
|
@@ -123,7 +123,7 @@ ${Po}: ${t}`:r;e(["log","-1","--format=%(trailers:key=Signed-off-by,valueonly)"]
|
|
|
123
123
|
`).slice(1).join(`
|
|
124
124
|
`).trim(),r=XR(n);return r?{prFailure:"hook",prDetail:`${r}
|
|
125
125
|
${n}`}:{prFailure:"unknown",prDetail:t}}o(LY,"thrownFailure");async function _Y(e,t,n,r,s,i){let a=nx(r.path,e.runDir),A=process.env.PATH;a.dir&&(process.env.PATH=rx(a).PATH);try{return await $Y(e,t,n,r,s,i)}finally{a.dir&&(process.env.PATH=A),a.cleanup()}}o(_Y,"deliverOne");async function $Y(e,t,n,r,s,i){let a=r.slug,A,u=!1,d;try{let p=r.path,g=$e(e,"finalize.json"),f=_x(e.inputs.requirementItems),m=xx(p),y=o(Ie=>Tx(Ie,m,s),"conform"),I=y(Oo(g?.commit?.message||n.commitMessage||"Skyramp Testbot: add tests",f)),S=Bx(e.outputsDir)??n,E=y(Oo(S.commitMessage,f)||Oo(n.commitMessage,f)||I).split(`
|
|
126
|
-
`)[0],T={name:Xr,email:ri},Q=!!m.signOff;if(!Q&&t.listCommitChecks){let Ie=i?.headSha??lt(p,["rev-parse","HEAD"]);try{Q=(await t.listCommitChecks({repository:a,revision:Ie}))?.records.some(We=>We.name.trim().toLowerCase()==="dco"&&We.headSha===Ie&&(!We.repository||We.repository.toLowerCase()===a.toLowerCase()))??!1}catch{console.warn(`[deliver] could not read commit checks for ${a}`)}}let k=e.inputs.deliverRemote||"origin",F=Px(p,Vx),V=Px(p,Hx);if(F&&!V)throw new Error(`${a}: the checkout records a merged base but not what it merged`);let Y=F?Fm(void 0,void 0,p):i?i.headBranch||Fm(e.inputs.headBranch,e.inputs.baseBranch,p):Fm(void 0,void 0,p),_=e.inputs.pullRequests;i?.prNumber!=null&&!_?.some(Ie=>Ie.repository.toLowerCase()===a.toLowerCase())&&(_=[..._??[],{repository:a,number:String(i.prNumber)}]);let Ae=_?.some(Ie=>Ie.repository.toLowerCase()===a.toLowerCase())?void 0:e.inputs.deliveryOrigin,Te=F||!Ae?V:void 0,we=Te?kY(a,Y,Te):vY(_,a,Y,Ae),ve=SY(Y,e.inputs.deliverBranch)+(Te?`-merge-${we}`:Ae?`-source-${Ae.number}-${we}`:""),Fe=Qx(Ix(TY(S,e,r),{audience:"testbot-pr",requestedBy:e.inputs.requestedBy,sourcePullRequest:Ae&&`${Ae.repository.namespace}/${Ae.repository.name}#${Ae.number}`}),e.inputs.skyrampRunUrl),be=i?"pr-body.md":`pr-body-${jx(a)}.md`,je=cs.join(e.outputsDir,be);Yn.writeFileSync(je,Fe);let P=lt(p,["rev-parse","HEAD"]),wt=F??P;lt(p,["checkout","-B",ve]),A=ve,lt(p,["reset"]);for(let Ie of s)xY(cs.join(p,Ie),f);let Ye=[];for(let Ie of s)try{lt(p,["--literal-pathspecs","add","--",Ie])}catch{Ye.push(Ie)}try{lt(p,["diff","--cached","--quiet"])}catch{try{let Ie=lt(p,["interpret-trailers","--trailer",`${td}: ${we}`,"--trailer",`${Po}: ${P}`,"--trailer",`${Dm}: ${wt}`],I),Kt=Q?ed(Ie,T):Ie;lt(p,["-c",`user.name=${T.name}`,"-c",`user.email=${T.email}`,"commit","-m",Kt])}catch(Ie){throw new sd(Ie)}u=!0}d=lt(p,["rev-parse","HEAD"]);let hn,Ut=F??i?.headSha;if(u&&Ut&&Ut!==P){let Ie=!1;try{lt(p,["checkout","-q","-B",A,Ut]),Ie=!0,lt(p,["-c",`user.name=${T.name}`,"-c",`user.email=${T.email}`,"cherry-pick","--keep-redundant-commits",d]),Ie=!1,Dx(Kt=>lt(p,Kt),Ut),d=lt(p,["rev-parse","HEAD"])}catch(Kt){try{lt(p,["cherry-pick","--abort"])}catch{}lt(p,["checkout","-q","-B",A,d]);let We=nl(ho(Kt),1/0);if(F&&!Ie)throw Kt;if(F)return{thrown:!1,record:{schemaVersion:1,repository:a,branch:A,remote:k,base:Y,committed:u,commitSha:d,pushed:!1,prAction:"skipped",prTitle:E,unstaged:Ye,reason:`the tests do not apply to ${Y} at ${F.slice(0,12)} without the merged revisions (${We}), so no tests PR was opened`}};hn=`tests committed on the checkout's merge commit (re-cut onto ${Ut.slice(0,12)} failed: ${We})`}}let gi=i?{}:{repositoryPath:p,repoSlug:a,devPr:null};if(!u){let Ie=await t.markTestsPrUnchanged({branch:A,...gi});return{thrown:!1,record:{schemaVersion:1,repository:a,branch:A,remote:k,base:Y,committed:!1,commitSha:d,pushed:!1,prAction:Ie.action==="unchanged"?"unchanged":"skipped",prUrl:Ie.url,prTitle:E,unstaged:Ye,reason:Ie.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 Ve=await t.publishTestsPr({repositoryPath:p,...gi,remote:k,branch:A,base:Y,commitSha:d,title:E,bodyFile:je,mode:e.inputs.deliverMode,deliveryOwner:we,runUrl:e.inputs.skyrampRunUrl,signal:e.signal,deadlineMs:e.deadlineMs});return{thrown:!1,record:{schemaVersion:1,repository:a,branch:A,remote:k,base:Ve.base,requestedBase:Y,committed:u,commitSha:d,pushed:Ve.pushed,...Ve.pushedCommits?{pushedCommits:Ve.pushedCommits}:{},...Ve.deliveredCommit?{deliveredCommit:Ve.deliveredCommit}:{},prAction:Ve.action,...Ve.retargetedAs?{retargetedAs:Ve.retargetedAs}:{},prUrl:Ve.url,prTitle:E,...Ve.failure?{prFailure:Ve.failure,prDetail:Ve.detail}:{},...hn?{cutNote:hn}:{},...Ve.action==="skipped"&&Ve.detail?{reason:Ve.detail}:{},unstaged:Ye}}}catch(p){return{thrown:!0,record:{schemaVersion:1,repository:a,branch:A,committed:u,commitSha:d,pushed:!1,prAction:"failed",...LY(p),unstaged:[]}}}}o($Y,"deliverRepository");var Vae={name:"deliver",timeoutMinutes:5,execute:NY,validateInput:o(e=>{let t=Cm(e);return t?{ok:!1,reasons:[t]}:bY(e)},"validateInput"),requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var qx=he(require("fs"));var PY="SKYRAMP_AZURE_SUPERVISED",OY=3;function GY(e,t=process.env){t[PY]==="1"?qx.writeSync(OY,`${JSON.stringify(e)}
|
|
126
|
+
`)[0],T={name:Xr,email:ri},Q=!!m.signOff;if(!Q&&t.listCommitChecks){let Ie=i?.headSha??lt(p,["rev-parse","HEAD"]);try{Q=(await t.listCommitChecks({repository:a,revision:Ie}))?.records.some(We=>We.name.trim().toLowerCase()==="dco"&&We.headSha===Ie&&(!We.repository||We.repository.toLowerCase()===a.toLowerCase()))??!1}catch{console.warn(`[deliver] could not read commit checks for ${a}`)}}let k=e.inputs.deliverRemote||"origin",F=Px(p,Vx),V=Px(p,Hx);if(F&&!V)throw new Error(`${a}: the checkout records a merged base but not what it merged`);let Y=F?Fm(void 0,void 0,p):i?i.headBranch||Fm(e.inputs.headBranch,e.inputs.baseBranch,p):Fm(void 0,void 0,p),_=e.inputs.pullRequests;i?.prNumber!=null&&!_?.some(Ie=>Ie.repository.toLowerCase()===a.toLowerCase())&&(_=[..._??[],{repository:a,number:String(i.prNumber)}]);let Ae=_?.some(Ie=>Ie.repository.toLowerCase()===a.toLowerCase())?void 0:e.inputs.deliveryOrigin,Te=F||!Ae?V:void 0,we=Te?kY(a,Y,Te):vY(_,a,Y,Ae),ve=SY(Y,e.inputs.deliverBranch)+(Te?`-merge-${we}`:Ae?`-source-${Ae.number}-${we}`:""),Fe=Qx(Ix(TY(S,e,r),{audience:"testbot-pr",requestedBy:e.inputs.requestedBy,sourcePullRequest:Ae&&`${Ae.repository.namespace}/${Ae.repository.name}#${Ae.number}`}),e.inputs.skyrampRunUrl),be=i?"pr-body.md":`pr-body-${jx(a)}.md`,je=cs.join(e.outputsDir,be);Yn.writeFileSync(je,Fe);let P=lt(p,["rev-parse","HEAD"]),wt=F??P;lt(p,["checkout","-B",ve]),A=ve,lt(p,["reset"]);for(let Ie of s)xY(cs.join(p,Ie),f);let Ye=[];for(let Ie of s)try{lt(p,["--literal-pathspecs","add","--",Ie])}catch{Ye.push(Ie)}try{lt(p,["diff","--cached","--quiet"])}catch{try{let Ie=lt(p,["interpret-trailers","--trailer",`${td}: ${we}`,"--trailer",`${Po}: ${P}`,"--trailer",`${Dm}: ${wt}`],I),Kt=Q?ed(Ie,T):Ie;lt(p,["-c",`user.name=${T.name}`,"-c",`user.email=${T.email}`,"commit","-m",Kt])}catch(Ie){throw new sd(Ie)}u=!0}d=lt(p,["rev-parse","HEAD"]);let hn,Ut=F??i?.headSha;if(u&&Ut&&Ut!==P){let Ie=!1;try{lt(p,["checkout","-q","-B",A,Ut]),Ie=!0,lt(p,["-c",`user.name=${T.name}`,"-c",`user.email=${T.email}`,"cherry-pick","--keep-redundant-commits",d]),Ie=!1,Dx(Kt=>lt(p,Kt),Ut),d=lt(p,["rev-parse","HEAD"])}catch(Kt){try{lt(p,["cherry-pick","--abort"])}catch{}lt(p,["checkout","-q","-B",A,d]);let We=nl(ho(Kt),1/0);if(F&&!Ie)throw Kt;if(F)return{thrown:!1,record:{schemaVersion:1,repository:a,branch:A,remote:k,base:Y,committed:u,commitSha:d,pushed:!1,prAction:"skipped",prTitle:E,unstaged:Ye,reason:`the tests do not apply to ${Y} at ${F.slice(0,12)} without the merged revisions (${We}), so no tests PR was opened`}};hn=`tests committed on the checkout's merge commit (re-cut onto ${Ut.slice(0,12)} failed: ${We})`}}let gi=i?{}:{repositoryPath:p,repoSlug:a,devPr:null};if(!u){let Ie=await t.markTestsPrUnchanged({branch:A,...gi});return{thrown:!1,record:{schemaVersion:1,repository:a,branch:A,remote:k,base:Y,committed:!1,commitSha:d,pushed:!1,prAction:Ie.action==="unchanged"?"unchanged":"skipped",prUrl:Ie.url,prTitle:E,unstaged:Ye,reason:Ie.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 Ve=await t.publishTestsPr({repositoryPath:p,...gi,remote:k,branch:A,base:Y,commitSha:d,title:E,bodyFile:je,mode:e.inputs.deliverMode,deliveryOwner:we,...e.inputs.firstQualification?{firstQualification:!0}:{},runUrl:e.inputs.skyrampRunUrl,signal:e.signal,deadlineMs:e.deadlineMs});return{thrown:!1,record:{schemaVersion:1,repository:a,branch:A,remote:k,base:Ve.base,requestedBase:Y,committed:u,commitSha:d,pushed:Ve.pushed,...Ve.pushedCommits?{pushedCommits:Ve.pushedCommits}:{},...Ve.deliveredCommit?{deliveredCommit:Ve.deliveredCommit}:{},prAction:Ve.action,...Ve.retargetedAs?{retargetedAs:Ve.retargetedAs}:{},prUrl:Ve.url,prTitle:E,...Ve.failure?{prFailure:Ve.failure,prDetail:Ve.detail}:{},...hn?{cutNote:hn}:{},...Ve.action==="skipped"&&Ve.detail?{reason:Ve.detail}:{},unstaged:Ye}}}catch(p){return{thrown:!0,record:{schemaVersion:1,repository:a,branch:A,committed:u,commitSha:d,pushed:!1,prAction:"failed",...LY(p),unstaged:[]}}}}o($Y,"deliverRepository");var Vae={name:"deliver",timeoutMinutes:5,execute:NY,validateInput:o(e=>{let t=Cm(e);return t?{ok:!1,reasons:[t]}:bY(e)},"validateInput"),requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var qx=he(require("fs"));var PY="SKYRAMP_AZURE_SUPERVISED",OY=3;function GY(e,t=process.env){t[PY]==="1"?qx.writeSync(OY,`${JSON.stringify(e)}
|
|
127
127
|
`):process.stdout.write(e.command!==void 0?`${e.command}
|
|
128
128
|
`:e.text??"")}o(GY,"writeFrame");function jY(e){GY({command:e})}o(jY,"writeAzureCommand");function Jx(e){return e.replace(/%/g,"%AZP25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}o(Jx,"escapeData");function VY(e){return Jx(e).replace(/;/g,"%3B").replace(/]/g,"%5D")}o(VY,"escapeProperty");function HY(e,t,n){let r=Object.entries(t).map(([s,i])=>`${s}=${VY(i)}`).join(";");return`##vso[${e}${r?` ${r}`:""}]${Jx(n)}`}o(HY,"vsoCommand");function qY(e){if(!e)return[];let t=e.split(/\r?\n/).filter(n=>n.trim()&&n!==e);return[e,...t].map(n=>HY("task.setsecret",{},n))}o(qY,"setSecretLines");function Yx(e,t=jY){for(let n of qY(e))t(n)}o(Yx,"azureSetSecret");function $c(e){return e.replace(/\/+$/,"")}o($c,"withoutTrailingSlash");function Mm(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`)}o(Mm,"azureOrganization");var JY=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,48}[A-Za-z0-9])?$/,YY=/[\\/:*?"<>|;#${},+=[\]%\p{Cc}\p{Cf}]/u;function Wx(e){return e.length>0&&e.length<=64&&e===e.trim()&&!YY.test(e)&&!/[^\S ]/u.test(e)&&!/^[._]/.test(e)&&!e.endsWith(".")}o(Wx,"isName");function id(e){return Um(`${e.namespace}/${e.name}`)}o(id,"azureRepositoryOfSource");function Um(e){let t=e.indexOf("/"),n=e.lastIndexOf("/"),r=e.slice(0,t),s=e.slice(t+1,n),i=e.slice(n+1);if(t<0||t===n||!JY.test(r)||!Wx(s)||!Wx(i))throw new Error(`"${e}" is not an Azure DevOps organization/project/repository`);return{organization:r,project:s,name:i}}o(Um,"azureRepositoryOf");function zx(e,t){let n=Mm(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`)}o(zx,"inOrganization");function Kx(e,t){return zx(e,t),`${$c(e)}/${encodeURIComponent(t.project)}/_git/${encodeURIComponent(t.name)}`}o(Kx,"azureCloneUrl");function Lm(e,t){return zx(e,t),`${$c(e)}/${encodeURIComponent(t.project)}/_apis/git/repositories/${encodeURIComponent(t.name)}`}o(Lm,"azureRepositoryApi");var WY="7.1",_c=class extends Error{constructor(n,r){super(n);this.status=r}status;static{o(this,"AzureRestError")}};async function _m(e){let t=e.accept??"application/json",n=new URL(e.url);n.searchParams.has("api-version")||n.searchParams.set("api-version",WY);let r=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(!r.ok){let s=(await r.json().catch(()=>({}))).message;throw new _c(`Azure DevOps answered ${r.status}${typeof s=="string"?`: ${s}`:""}`,r.status)}return t!=="application/json"?Buffer.from(await r.arrayBuffer()):r.status===204?{}:await r.json()}o(_m,"azureRest");function zY(e){return`AUTHORIZATION: bearer ${e}`}o(zY,"azureGitAuthorization");function Zx(e,t){return{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${$c(e)}/.extraheader`,GIT_CONFIG_VALUE_0:zY(t)}}o(Zx,"azureGitAuthEnv");var KY="7.1-preview.1",ZY=".azure-pipelines/skyramp-testbot-v3.yml";function $m(e){return e.GITHUB_ACTIONS!=="true"&&/^true$/i.test(e.TF_BUILD??"")}o($m,"isAzurePipelines");function t0(e,t={}){let n=o(g=>{let f=e[g];if(!f)throw new Error(`${g} is not set; the V3 runner handshake needs it`);return f},"read"),r=$c(e.SYSTEM_COLLECTIONURI??""),s=o(()=>Mm(n("SYSTEM_COLLECTIONURI")),"organization"),i=e.SYSTEM_TEAMPROJECT,a=e.BUILD_REPOSITORY_NAME,A=e.BUILD_REPOSITORY_ID?.toLowerCase(),u=e.SYSTEM_ACCESSTOKEN,d=t.mask??(g=>Yx(g)),p=o(g=>async()=>{if(!g)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 f=new URL(g);if(f.protocol!=="https:")throw new Error("SYSTEM_OIDCREQUESTURI is not an https URL");f.searchParams.set("api-version",KY);let m=await(t.fetch??fetch)(f.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"Content-Type":"application/json",Accept:"application/json"},body:"{}",redirect:"error",signal:AbortSignal.timeout(3e4)});if(!m.ok)throw new Error(`Azure DevOps refused the OIDC token request: ${m.status}`);let y=(await m.json().catch(()=>({}))).oidcToken;if(typeof y!="string"||!y)throw new Error("Azure DevOps's OIDC token response carried no token");return d(y),y},"mint");return{runnerPlatform:$m(e)?"azure":void 0,workspace:e.BUILD_SOURCESDIRECTORY||void 0,serverUrl:r,apiUrl:r,repository:A&&i&&a&&r?{id:A,slug:`${s()}/${i}/${a}`}:void 0,runId:e.BUILD_BUILDID||void 0,runAttempt:e.SYSTEM_STAGEATTEMPT||void 0,job:e.SYSTEM_JOBNAME||void 0,execution(){let g=n("SYSTEM_STAGEATTEMPT");if(!/^[1-9][0-9]*$/.test(g))throw new Error(`SYSTEM_STAGEATTEMPT is "${g}", not a positive whole number`);let f=n("SYSTEM_COLLECTIONID").toLowerCase();if(!ko.test(f))throw new Error(`SYSTEM_COLLECTIONID is "${f}", not a GUID`);let m=n("BUILD_REPOSITORY_ID").toLowerCase();if(!ko.test(m))throw new Error(`BUILD_REPOSITORY_ID is "${m}", not a GUID`);let y=[s(),n("SYSTEM_TEAMPROJECT"),n("SYSTEM_DEFINITIONID"),n("BUILD_BUILDID")].map(encodeURIComponent).join("/");return{provider:"azure-devops",repository:{provider:"azure-devops",providerAccountId:f,providerRepositoryId:m},providerRunId:y,providerRunAttempt:Number(g),workflowRef:`${ZY}@${n("BUILD_SOURCEBRANCH")}`}},takeIdToken(){let g=e.SYSTEM_OIDCREQUESTURI;delete e.SYSTEM_OIDCREQUESTURI;let f=p(g);return()=>f()},takeSourceToken(){return delete e.SYSTEM_ACCESSTOKEN,u||void 0},webIdentity(){if(!e.SYSTEM_OIDCREQUESTURI?.trim()||!u)return;let g=p(e.SYSTEM_OIDCREQUESTURI);return{token:o(()=>g(),"token"),runId:e.BUILD_BUILDID}},v3RunsOnly:!0,assumesBedrockRole:!0,namesSourceToMcp:!0,runSettingsFromApp:!0,checkSourceName(g){id(g)},cloneUrl(g){return Kx(r,id(g))},gitAuthEnv(g){return Zx(r,g)},async pullRequest(g,f,m){let y=await _m({token:await m.token(),url:`${Lm(r,id(g))}/pullrequests/${f}`,fetch:m.fetch}),I=y.status==="completed";return{...typeof y.title=="string"?{title:y.title}:{},...typeof y.description=="string"?{body:y.description}:{},...typeof y.status=="string"?{merged:I}:{},...I&&typeof y.lastMergeCommit?.commitId=="string"?{mergeCommit:y.lastMergeCommit.commitId}:{},...I&&typeof y.lastMergeSourceCommit?.commitId=="string"?{mergedHead:y.lastMergeSourceCommit.commitId}:{}}},async commit(g,f,m){let y;try{y=Lm(r,Um(g))}catch{return{lookup:"unknown"}}try{let I=await _m({token:await m.token(),url:`${y}/commits/${encodeURIComponent(f)}`,fetch:m.fetch});return typeof I.commitId=="string"?{sha:I.commitId}:{lookup:"missing"}}catch(I){return{lookup:I instanceof _c&&(I.status===404||I.status===400)?"missing":"unknown"}}}}}o(t0,"azureRunnerHost");po();var XY=5e3,Pm=/^(?!\.\.?$)[A-Za-z0-9._-]{1,100}$/;function eW(e){let t=Buffer.from(`x-access-token:${e}`).toString("base64");return rc(t),`AUTHORIZATION: basic ${t}`}o(eW,"githubGitAuthorization");function n0(e,t={}){let n=o(u=>{let d=e[u];if(!d)throw new Error(`${u} is not set; the V3 runner handshake needs it`);return d},"read"),r=e.GITHUB_REPOSITORY_ID,s=e.GITHUB_REPOSITORY,i=(e.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,""),a=(e.GITHUB_API_URL||"https://api.github.com").replace(/\/+$/,""),A=o(async(u,d)=>d.fetch(u,{headers:{Authorization:`Bearer ${await d.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:i,apiUrl:a,repository:r&&s?{id:r,slug:s}: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=n("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:n("GITHUB_REPOSITORY_OWNER_ID"),providerRepositoryId:n("GITHUB_REPOSITORY_ID")},providerRunId:n("GITHUB_RUN_ID"),providerRunAttempt:Number(u),workflowRef:n("GITHUB_WORKFLOW_REF")}},takeIdToken(){let u=e.ACTIONS_ID_TOKEN_REQUEST_URL,d=e.ACTIONS_ID_TOKEN_REQUEST_TOKEN;return delete e.ACTIONS_ID_TOKEN_REQUEST_URL,delete e.ACTIONS_ID_TOKEN_REQUEST_TOKEN,async p=>{if(!u||!d)throw new Error("The job cannot request an OIDC token. Give it the `id-token: write` permission.");let g=new URL(u);g.searchParams.set("audience",p);let f=await fetch(g,{headers:{Authorization:`Bearer ${d}`,Accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!f.ok)throw new Error(`GitHub refused the OIDC token request: ${f.status}`);let m=(await f.json().catch(()=>({}))).value;if(typeof m!="string"||!m)throw new Error("GitHub's OIDC token response carried no token");return rc(m),m}},webIdentity(){return!e.ACTIONS_ID_TOKEN_REQUEST_TOKEN?.trim()||!e.ACTIONS_ID_TOKEN_REQUEST_URL?.trim()?void 0:{token:t.getIDToken??(d=>jR(d)),runId:e.GITHUB_RUN_ID}},v3RunsOnly:!1,assumesBedrockRole:!1,namesSourceToMcp:!1,runSettingsFromApp:!1,checkSourceName(u){for(let d of[u.namespace,u.name])if(!Pm.test(d))throw new Error(`"${d}" is not a repository name`)},cloneUrl(u){return`${i}/${u.namespace}/${u.name}.git`},gitAuthEnv(u){return u?{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${i}/.extraheader`,GIT_CONFIG_VALUE_0:eW(u)}:{}},async pullRequest({namespace:u,name:d},p,g){if(![u,d].every(y=>Pm.test(y)))throw new Error("the repository name is not valid");let f=await A(`${a}/repos/${u}/${d}/pulls/${p}`,g);if(!f.ok)throw new Error(`GitHub answered ${f.status}`);let m=await f.json();return{...typeof m.title=="string"?{title:m.title}:{},...typeof m.body=="string"?{body:m.body}:{},...typeof m.merged=="boolean"?{merged:m.merged}:{},...m.merged===!0&&typeof m.merge_commit_sha=="string"?{mergeCommit:m.merge_commit_sha}:{},...m.merged===!0&&typeof m.head?.sha=="string"?{mergedHead:m.head.sha}:{}}},async commit(u,d,p){let[g,f,...m]=u.split("/");if(m.length||![g,f].every(y=>y!==void 0&&Pm.test(y)))return{lookup:"unknown"};try{let y=await A(`${a}/repos/${g}/${f}/commits/${encodeURIComponent(d)}`,p);if(y.status===404||y.status===422)return{lookup:"missing"};if(!y.ok)return{lookup:"unknown"};let I=await y.json();return typeof I.sha=="string"?{sha:I.sha}:{lookup:"missing"}}catch{return{lookup:"unknown"}}},async revokeToken(u,d){let p=await d(`${a}/installation/token`,{method:"DELETE",headers:{Authorization:`Bearer ${u}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(XY)});if(!p.ok&&p.status!==401)throw new Error(`GitHub answered ${p.status}`)}}}o(n0,"githubRunnerHost");function r0(e=process.env){return $m(e)?t0(e):n0(e)}o(r0,"runnerHost");var yce=Buffer.from("302a300506032b656e032100","hex");var tW=10*6e4;function nW(e,t){return e.getTime()-t.getTime()-tW}o(nW,"remainingBudgetMs");var s0="This attempt revoked its scoped GitHub credentials; it mints no more.",rW=10*6e4;var sW=o(e=>!!e&&Object.keys(e).length===1&&e.contents==="read","onlyReads"),iW=3e4,oW=3,i0=30,vn=class extends Error{constructor(n,r,s,i){super(n);this.status=r;this.code=s;this.path=i}status;code;path;static{o(this,"AppRefusal")}},pi=class extends Error{static{o(this,"AppUnreachable")}},jo=class extends pi{static{o(this,"AppNotReady")}},Om=class extends jo{static{o(this,"RunnerProviderNotReady")}};function Gm(e){let t;try{t=new URL(e)}catch{throw new Error(`skyrampAppOrigin "${e}" is not a URL`)}if(t.protocol!=="https:"||t.origin!==e.replace(/\/+$/,""))throw new Error(`skyrampAppOrigin must be an https origin, got "${e}"`);return t.origin}o(Gm,"appOrigin");function o0(e,t){if(!ko.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}o(o0,"routeId");function aW(e,t){return`${e.replace(/\/+$/,"")}/runs/${t}`}o(aW,"skyrampRunPageUrl");function a0(e,t,n,r){throw t<500&&t!==429?new vn(e,t,n,r):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new Om(e):t===503&&n==="RUN_NOT_READY"?new jo(e):new pi(e)}o(a0,"refusedOrUnreachable");async function c0(e,t,n,r){let s=Gm(e.origin),i,a=0;for(let A=1;A<=oW||i instanceof jo;A+=1){if(i instanceof jo){if(a===i0)throw i;a+=1,A-=1,e.log?.(`${i.message}; trying again (${a} of ${i0}).`),await new Promise(u=>setTimeout(u,e.readyWaitMs??1e4))}else A>1&&await new Promise(u=>setTimeout(u,(e.retryDelayMs??2e3)*(A-1)));try{let u=await e.idToken(s),d=await(e.fetch??fetch)(new URL(t,s).toString(),{...n(u),redirect:"error",signal:AbortSignal.timeout(iW)}).catch(p=>{throw new pi(p instanceof Error?p.message:String(p),{cause:p})});return await r(d)}catch(u){if(u instanceof vn)throw u;i=u}}throw i}o(c0,"callWithRetries");function A0(e,t,n,r,s){let i=r.headers.get("cf-ray");e.log?.(`Testbot V3: ${t} ${n} answered ${r.status}${i?`, cf-ray ${i}`:""}: ${s.replace(/\s+/g," ").slice(0,200)}`)}o(A0,"logRefusal");function od(e,t,n,r){return c0(e,n,o(i=>({method:t,headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json",Accept:"application/json"},body:t==="GET"?void 0:JSON.stringify(r)}),"request"),async i=>{let a=await i.text().catch(()=>""),A={};try{A=JSON.parse(a)}catch{}if(i.ok)return A.data;A0(e,t,n,i,a);let u=A.error?.fields,d=typeof u?.path=="string"&&typeof u.reason=="string"?` at ${u.path}: ${u.reason}`:"",p=`The Skyramp app refused ${t} ${n}: ${i.status} ${A.error?.code??"no error code"}${d}`;return a0(p,i.status,A.error?.code,typeof u?.path=="string"?u.path:void 0)})}o(od,"callApp");function cW(e,t,n){return c0(e,t,o(s=>({method:"GET",headers:{Authorization:`Bearer ${s}`,Accept:"application/octet-stream"}}),"request"),async s=>{if(!s.ok)return A0(e,"GET",t,s,await s.text().catch(()=>"")),a0(`The Skyramp app refused GET ${t}: ${s.status}`,s.status);let i=Buffer.from(await s.arrayBuffer());if(i.length>n)throw new vn(`The Skyramp app answered GET ${t} with more than ${n} bytes`,s.status);return i})}o(cW,"callAppBytes");var Pc=class{constructor(t,n,r,s,i,a,A,u,d,p=[],g=[],f,m=!1){this.attemptId=t;this.attemptNumber=n;this.deadlineAt=r;this.manifest=s;this.deps=i;this.license=a;this.requestedBy=A;this.writeAllowed=u;this.claudeCodeVersion=d;this.deployedPins=p;this.statedPins=g;this.runSettings=f;this.credentialRelay=m}attemptId;attemptNumber;deadlineAt;manifest;deps;license;requestedBy;writeAllowed;claudeCodeVersion;deployedPins;statedPins;runSettings;credentialRelay;static{o(this,"V3Attempt")}budgetMs(t){return nW(this.deadlineAt,t)}get skyrampRunUrl(){return aW(Gm(this.deps.origin),this.manifest.runId)}send(t,n,r){return od(this.deps,t,n,r)}readBytes(t,n){return cW(this.deps,t,n)}issuedTokens=[];closure;modelKey;modelCredentials=[];credentials={};revocation;token(){return this.cachedToken("run")}readOnlyToken(){return this.cachedToken("read")}async cachedToken(t){if(this.revocation)throw new Error(s0);let n=(this.deps.now??(()=>new Date))().getTime(),r=this.credentials[t],s=r&&await r.catch(()=>{});if(this.credentials[t]!==r)return(await this.credentials[t]).token;if(s&&s.expiresAt-n>=rW)return s.token;if(this.revocation)throw new Error(s0);let i=t==="read",a=i?{schemaVersion:1,access:t}:{schemaVersion:1},A=i?"read-only":"scoped",u=this.send("POST",`/api/v1/runner/attempts/${this.attemptId}/credentials`,a).then(d=>{let p={...d,token:d.token??this.jobToken()};if(this.issuedTokens.push(p.token),this.deps.mask?.(p.token),p.anthropicApiKey&&this.deps.mask?.(p.anthropicApiKey),i&&d.token&&!sW(p.permissions))throw new Error(`The Skyramp app was asked for a read-only GitHub token, but its token grants ${JSON.stringify(p.permissions??null)}`);!i&&!s&&p.anthropicApiKey&&(this.modelKey=p.anthropicApiKey),this.deps.onTokenGranted?.(t);let g=s?"Renewed":"Received";return d.token&&this.deps.log?.(`${g} ${A} GitHub credentials; they expire at ${p.expiresAt}.`),{token:p.token,expiresAt:d.token?new Date(p.expiresAt).getTime():Number.POSITIVE_INFINITY}},d=>{if(this.deps.onTokenRefused?.(d,t),!(d instanceof vn)||d.code!=="CREDENTIALS_UNAVAILABLE")throw d;let p=o(m=>[...new Set(m.map(y=>y.namespace))].join(", "),"unique"),g=this.manifest.sources.map(m=>m.repository);if(new Set(g.map(m=>m.providerAccountId)).size>1)throw new vn(`${d.message}. The run's repositories are on more than one GitHub account (${p(g)}), which Skyramp does not support yet.`,d.status,d.code);let f=p([...g,this.manifest.execution.repository]);throw new vn(`${d.message}. Check the Skyramp GitHub App installation on ${f}: 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.`,d.status,d.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 n=t.host??r0();return this.revocation??=n.revokeToken?this.revokeIssued(r=>n.revokeToken(r,this.sourceFetch(t))):Promise.resolve([]),this.revocation}async revokeIssued(t){let n=[...this.issuedTokens],r=Promise.all(n.map(a=>this.revokeOne(a,t)));await Promise.all(Object.values(this.credentials).map(a=>a.catch(()=>{})));let s=this.issuedTokens.filter(a=>!n.includes(a));return[...await r,...await Promise.all(s.map(a=>this.revokeOne(a,t)))].filter(a=>a!==void 0)}async revokeOne(t,n){try{await n(t);return}catch(r){return`token ${this.issuedTokens.indexOf(t)+1} of ${this.issuedTokens.length}: ${r instanceof Error?r.message:String(r)}`}}};async function u0(e,t,n){o0(e,"run id"),Gm(n.origin);let r=yf(e,t),s=`/api/v1/runner/runs/${e}/attempts`,i;try{i=await od(n,"POST",s,r)}catch(d){if(!(d instanceof vn&&d.status===400&&d.path==="$.statedPins"))throw d;r=yf(e,t,{statedPins:!1}),i=await od(n,"POST",s,r)}let a=iv(i);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 A=a.manifest.sources.find(d=>d.repository.provider!==r.execution.provider);if(A)throw new Error(`The manifest of run ${e} names ${A.repository.namespace}/${A.repository.name} on ${A.repository.provider}, but this job runs on ${r.execution.provider}`);AW(a.manifest,[...a.deployedRevisions??[],...a.statedRevisions??[]]),a.runToken&&n.mask?.(a.runToken);let u=a.runToken?{entitlements:a.entitlements??[],runToken:a.runToken}:void 0;return new Pc(a.attempt.id,a.attempt.number,new Date(a.attempt.deadlineAt),a.manifest,n,u,a.requestedBy??void 0,a.writeAllowed,a.claudeCodeVersion??void 0,a.deployedRevisions??[],a.statedRevisions??[],a.runSettings,a.credentialRelay===!0)}o(u0,"startV3Attempt");function AW(e,t){if(t.length===0)return;if(e.trigger.kind!=="schedule")throw new Error(`The app pinned an attempt of a ${e.trigger.kind} run; only a scheduled run's retry is pinned to an earlier attempt's read`);let n=new Set(e.sources.map(s=>fr(s.repository))),r=new Set;for(let s of t){let i=fr(s.repository);if(!n.has(i))throw new Error(`The app pinned the attempt to repository ${s.repository.providerRepositoryId}, which is not a source of the run`);if(r.has(i))throw new Error(`The app pinned repository ${s.repository.providerRepositoryId} twice`);r.add(i)}}o(AW,"checkAttemptPins");async function jm(e){return tv.parse(await e.send("POST",`/api/v1/runner/attempts/${e.attemptId}/heartbeat`,{schemaVersion:1}))}o(jm,"heartbeatV3Attempt");async function l0(e,t=()=>new Date){if(e.closure)return e.closure;let n=await jm(e).then(r=>nv(r,t())).catch(()=>null);return n&&(e.closure=n),n}o(l0,"closedV3Attempt");var tAe=10*6e4;var nAe=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var rAe=c.object({tests:c.object({placements:c.array(c.unknown()).optional()}).passthrough().optional()}).passthrough(),sAe=c.object({repository:hf,testType:c.nativeEnum(Sl),directory:c.string()}).passthrough();var iAe=c.object({report:c.object({language:c.string()}).passthrough()}).passthrough();var oAe=c.object({environment:c.object({components:c.array(c.unknown()).optional(),dependencies:c.array(c.unknown()).optional()}).passthrough()}).passthrough(),aAe=c.object({name:c.string().min(1),provision:c.literal("existing"),url:c.string().min(1),repository:hf.optional(),revisionUrl:c.string().min(1).optional()}).passthrough(),cAe=c.object({name:c.string().min(1),url:c.string().nullable(),versionUrl:c.string().nullable(),notes:c.string().nullable()}).passthrough();var AAe=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);function d0(e){let t=o(n=>e.testResults.filter(r=>r.status===n).length,"count");return{passed:t("Pass"),failed:t("Fail"),skipped:t("Skipped")}}o(d0,"statusCounts");function uW(e){let{passed:t,failed:n,skipped:r}=d0(e);return t+n===0?{sufficiency:"insufficient",rationale:r>0?`Every test was skipped (${r}), so nothing was validated.`:"No test ran, so nothing was validated.",gaps:["No test ran against the frozen sources."],acceptedEvidence:[],actionRequired:[]}:{sufficiency:"sufficient",rationale:`${t+n} tests ran against the frozen sources: ${t} passed, ${n} failed${r?`, ${r} skipped`:""}.`,gaps:[],acceptedEvidence:[],actionRequired:[]}}o(uW,"executedTestsValidation");function lW({notTranslated:e,...t},n){let r=t.testResults.map(d=>({result:d,repository:d.repository??n,path:d.fileName||d.testType})),s=new Map;for(let d of r){let p=`${d.repository}:${d.result.testType}:${d.path}`;s.set(p,(s.get(p)??0)+1)}let i=r.map(({result:d,repository:p,path:g})=>{let f=(s.get(`${p}:${d.testType}:${g}`)??0)>1;return d.resultId??mf(p,d.testType,g,f&&d.endpoint||void 0)}),a=new Map;for(let d of i)a.set(d,(a.get(d)??0)+1);let A=new Set(i.filter(d=>a.get(d)===1)),u=r.map(({result:d,repository:p},g)=>{let f=i[g],m=f;if(a.get(f)>1&&A.has(f))for(let y=2;A.has(m)||m===f;y+=1)m=f.includes("#")?`${f}.${y}`:`${f}#${y}`;return A.add(m),{...d,repository:p,resultId:m}});return{...t,testResults:u,...dW(t,u,n),validation:hW(t,pW(t,t.validation??uW(t))),traceVersion:1}}o(lW,"v3Report");function dW(e,t,n){if(!e.testExecutionContexts)return{};let r=new Set,s=o(A=>{let u=A;for(let d=2;r.has(u);d+=1)u=`${A}#${d}`;return r.add(u),u},"unique"),i=[],a=new Map;for(let{repository:A,...u}of e.testExecutionContexts){let d=u.status==="not_run"?[]:t.filter(p=>p.fileName===u.test&&p.repository===(A?.trim()||n));d.length||i.push(u);for(let{resultId:p}of d){let g=a.get(p),f=g!==void 0&&i[g].cleanup.status==="failed"?i[g].cleanup:u.cleanup,m={...u,cleanup:f,test:p,resultId:p};g===void 0?a.set(p,i.push(m)-1):i[g]=m}}for(let A of i)A.resultId&&r.add(A.resultId);return{testExecutionContexts:i.map(A=>A.resultId?A:{...A,test:s(A.test.slice(0,512))}).slice(0,5e3)}}o(dW,"linkedContexts");function pW(e,t){let{passed:n,failed:r}=d0(e);return t.sufficiency!=="sufficient"||n+r>0||t.acceptedEvidence.length>0?t:{...t,sufficiency:"insufficient",gaps:["No test ran and no existing evidence was accepted, so nothing was validated."]}}o(pW,"withEvidence");var gW={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};function hW(e,t){if(t.sufficiency==="sufficient")return t;let n=(e.caveats??[]).map(s=>gW[s.kind]).filter(s=>s!==void 0),r=[...new Set(n)].filter(s=>!t.actionRequired.includes(s));return r.length?{...t,actionRequired:[...r,...t.actionRequired]}:t}o(hW,"withModelProviderFailure");function fW(e,t,n){let{language:r,report:s}=t;if(r==="en")return;let i={language:r,businessCaseAnalysis:s.businessCaseAnalysis},a=o((y,I,S)=>Array.isArray(y)&&Array.isArray(I)&&y.length===I.length?y.map(E=>({[S]:E[S]})):void 0,"rows"),A=e.validation;s.validation&&A&&A.rationale===n.validation.rationale&&JSON.stringify(A.gaps)===JSON.stringify(n.validation.gaps)&&s.validation.gaps.length===n.validation.gaps.length&&(i.validation={rationale:s.validation.rationale,gaps:[...s.validation.gaps]});let u=new Set((n.changes??[]).map(y=>y.id)),d=(s.changes??[]).filter(y=>u.has(y.id)).map(({id:y,text:I})=>({id:y,text:I}));d.length&&(i.changes=d);let p=a(s.issuesFound,n.issuesFound,"description");p&&(i.issuesFound=p);let g=a(s.newTestsCreated,n.newTestsCreated,"description");g&&(i.newTestsCreated=g);let f=a(s.testResults,n.testResults,"details");f&&(i.testResults=f);let m=a(s.caveats,n.caveats,"text");return m&&(i.caveats=m),i}o(fW,"v3Display");async function p0(e,t){let n=YR([...e.issuedTokens,...t.secrets??[]]),r={...lW(t.report,t.workingSlug),...t.notTranslated?{notTranslated:t.notTranslated}:{}},s=t.translated&&fW(t.report,t.translated,r),i=o(A=>ov({manifest:e.manifest,attemptNumber:e.attemptNumber,checkedOut:t.sources.map(u=>({repository:u.repository,revision:u.revision})),firstQualification:t.firstQualification,generatedTests:go(t.delivery,n),producer:t.producer,report:go(A&&s?{...r,display:s}:r,n),githubWrites:t.githubWrites}),"build"),a=i(!0);s&&Buffer.byteLength(JSON.stringify(a),"utf8")>GS&&(a=i(!1)),await e.send("PUT",`/api/v1/runner/attempts/${e.attemptId}/report`,a)}o(p0,"uploadV3Report");async function g0(e,t){return o0(e.attemptId,"attempt id"),od(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,av({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"}))}o(g0,"endV3Attempt");0&&(module.exports={AppRefusal,AppUnreachable,AttemptEndReason,DeliveryStatus,GitHubWriteKind,NoReportCause,SourceProvider,V3Attempt,ValidationSufficiency,closedV3Attempt,endV3Attempt,heartbeatV3Attempt,startV3Attempt,uploadV3Report});
|
|
129
129
|
/*! Bundled license information:
|
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.300",
|
|
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.",
|