@skyramp/testbot-core 0.13.0-v3.428 → 0.13.0-v3.430

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/post.js CHANGED
@@ -227,13 +227,13 @@ ${Id}: ${t}`:i;e(["log","-1","--format=%(trailers:key=Signed-off-by,valueonly)"]
227
227
  ${n}`}:{prFailure:"unknown",prDetail:t}}async function vIe(e,t,n,i,r,s){let o=i.slug,a=i.path,c=Ve(e,"finalize.json"),u=pZ(e.inputs.requirementItems),d=B4(a),p=Ve(e,"write.json"),h=p?.commit?.message||Ve(e,"generate-unit.json")?.commitMessage,g=i.working,A=xt=>xt.split(`
228
228
  `)[0],y=xt=>Ub(_4(u_(xt)),u),E=(xt,hn)=>g&&!!hn&&y(xt).trim()===y(hn).trim(),v=(xt,hn,$r)=>{let Et=y(xt);return $r&&$4(Et,hn)?Et:T4(Et,hn,r)},b=[c?.commit?.message,n.commitMessage].find(xt=>xt&&y(xt).trim())||"Skyramp Testbot: add tests",I=v(b,{commitlint:d.commitlint},E(b,h)),R=V4(e.outputsDir)??n,w=g?c?.pr?.title||n.prTitle||p?.commit?.prTitle:void 0,Q=w||b,k=g?R.prTitle:void 0,W=A(y(Q))===A(y(b)),de=(!g||!n.prTitle)&&W?R.commitMessage:void 0,K=k||de||Q,Ce=p?.commit?.prTitle||(h?A(h):void 0),Le=E(Q,Ce),et=d.prTitle?{prTitle:d.prTitle}:Le&&w&&!W?{}:{commitlint:d.commitlint},Oe=A(v(K,et,Le)),Z={name:$s,email:To},M=!!d.signOff;if(!M&&t?.listCommitChecks){let xt=s?.headSha??fn(a,["rev-parse","HEAD"]);try{M=(await t.listCommitChecks({repository:o,revision:xt}))?.records.some($r=>$r.name.trim().toLowerCase()==="dco"&&$r.headSha===xt&&(!$r.repository||$r.repository.toLowerCase()===o.toLowerCase()))??!1}catch{console.warn(`[deliver] could not read commit checks for ${o}`)}}let rt=e.inputs.deliverRemote||"origin",ot=hZ(a,yZ),Rn=hZ(a,EZ);if(ot&&!Rn)throw new Error(`${o}: the checkout records a merged base but not what it merged`);let Mt=ot?R_(void 0,void 0,a):s?s.headBranch||R_(e.inputs.headBranch,e.inputs.baseBranch,a):R_(void 0,void 0,a),pr=e.inputs.pullRequests;s?.prNumber!=null&&!pr?.some(xt=>xt.repository.toLowerCase()===o.toLowerCase())&&(pr=[...pr??[],{repository:o,number:String(s.prNumber)}]);let ti=pr?.some(xt=>xt.repository.toLowerCase()===o.toLowerCase())?void 0:e.inputs.deliveryOrigin,Ii=ot||!ti?Rn:void 0,Hs=e.inputs.scheduledDelivery,Yt=Hs?(0,gg.createHash)("sha256").update(JSON.stringify([Hs,o.toLowerCase(),Mt])).digest("hex"):Ii?lIe(o,Mt,Ii):uIe(pr,o,Mt,ti),Ci=cIe(Mt,e.inputs.deliverBranch)+(Hs?`-scheduled-${Yt}`:Ii?`-merge-${Yt}`:ti?`-source-${ti.number}-${Yt}`:"");return{texts:u,shown:R,title:Oe,unsigned:I,bot:Z,signOff:M,remote:rt,base:Mt,owner:Yt,testsBranch:Ci,origin:ti,mergedBase:ot}}function bIe(e,t,n,i,r){let s=fn(e,["interpret-trailers","--trailer",`${Qb}: ${t.owner}`,"--trailer",`${Id}: ${n}`,"--trailer",`${l_}: ${i}`,...r?["--trailer",`${d_}: ${r}`]:[]],`${t.unsigned}
229
229
  `);return t.signOff?xb(s,t.bot):s}async function wIe(e,t,n,i,r,s){let o=z4(i.path,e.runDir),a=process.env.PATH;o.dir&&(process.env.PATH=H4(o).PATH);try{return await IIe(e,t,n,i,r,s)}finally{o.dir&&(process.env.PATH=a),o.cleanup()}}async function IIe(e,t,n,i,r,s){let o=i.slug,a,c=!1,u;try{let d=i.path,p=await vIe(e,t,n,i,r,s),{texts:h,shown:g,title:A,bot:y,remote:E,base:v,owner:b,testsBranch:I,origin:R,mergedBase:w}=p,Q=u_(h4(oZ(pIe(g,e,i),{audience:"testbot-pr",runUrl:e.inputs.skyrampRunUrl,requestedBy:e.inputs.requestedBy,sourcePullRequest:R&&`${R.repository.namespace}/${R.repository.name}#${R.number}`}),e.inputs.skyrampRunUrl))+`
230
- `,k=s?"pr-body.md":`pr-body-${mZ(o)}.md`,W=sa.join(e.outputsDir,k);wi.writeFileSync(W,Q);let de=fn(d,["rev-parse","HEAD"]),K=w??de;fn(d,["checkout","-B",I]),a=I,fn(d,["reset"]);for(let M of r)dIe(sa.join(d,M),h);let Ce=[];for(let M of r)try{fn(d,["--literal-pathspecs","add","--",M])}catch{Ce.push(M)}try{fn(d,["diff","--cached","--quiet"])}catch{try{let M=bIe(d,p,de,K,e.inputs.skyrampRunUrl);fn(d,["-c",`user.name=${y.name}`,"-c",`user.email=${y.email}`,"commit","-m",M])}catch(M){throw new Fb(M)}c=!0}u=fn(d,["rev-parse","HEAD"]);let Le,et=w??s?.headSha;if(c&&et&&et!==de){let M=!1;try{fn(d,["checkout","-q","-B",a,et]),M=!0,fn(d,["-c",`user.name=${y.name}`,"-c",`user.email=${y.email}`,"cherry-pick","--keep-redundant-commits",u]),M=!1,p_(rt=>fn(d,rt),et),u=fn(d,["rev-parse","HEAD"])}catch(rt){try{fn(d,["cherry-pick","--abort"])}catch{}fn(d,["checkout","-q","-B",a,u]);let ot=sg(ta(rt),1/0);if(w&&!M)throw rt;if(w)return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:E,base:v,committed:c,commitSha:u,pushed:!1,prAction:"skipped",prTitle:A,unstaged:Ce,reason:`the tests do not apply to ${v} at ${w.slice(0,12)} without the merged revisions (${ot}), so no tests PR was opened`}};Le=`tests committed on the checkout's merge commit (re-cut onto ${et.slice(0,12)} failed: ${ot})`}}let Oe=s?{}:{repositoryPath:d,repoSlug:o,devPr:null};if(!c){let M=await t.markTestsPrUnchanged({branch:a,...Oe});return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:E,base:v,committed:!1,commitSha:u,pushed:!1,prAction:M.action==="unchanged"?"unchanged":"skipped",prUrl:M.url,prTitle:A,unstaged:Ce,reason:M.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 Z=await t.publishTestsPr({repositoryPath:d,...Oe,remote:E,branch:a,base:v,commitSha:u,title:A,bodyFile:W,mode:e.inputs.deliverMode,deliveryOwner:b,...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:E,base:Z.base,requestedBase:v,committed:c,commitSha:u,pushed:Z.pushed,...Z.pushedCommits?{pushedCommits:Z.pushedCommits}:{},...Z.deliveredCommit?{deliveredCommit:Z.deliveredCommit}:{},prAction:Z.action,...Z.retargetedAs?{retargetedAs:Z.retargetedAs}:{},prUrl:Z.url,prTitle:A,...Z.failure?{prFailure:Z.failure,prDetail:Z.detail}:{},...Le?{cutNote:Le}:{},...Z.action==="skipped"&&Z.detail?{reason:Z.detail}:{},unstaged:Ce}}}catch(d){return{thrown:!0,record:{schemaVersion:1,repository:o,branch:a,committed:c,commitSha:u,pushed:!1,prAction:"failed",...EIe(d),unstaged:[]}}}}var GWe={name:"deliver",timeoutMinutes:5,execute:gIe,validateInput:e=>{let t=a_(e);return t?{ok:!1,reasons:[t]}:oIe(e)},requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var j4e=10*6e4;var V4e=10*6e4;var SIe=3e4,kIe=3,vZ=30,oa=class extends Error{constructor(n,i,r,s){super(n);this.status=i;this.code=r;this.path=s}status;code;path},ns=class extends Error{},kd=class extends ns{},Mb=class extends kd{};function RIe(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 BIe(e,t){if(!bl.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}function xIe(e,t,n,i){throw t<500&&t!==429?new oa(e,t,n,i):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new Mb(e):t===503&&n==="RUN_NOT_READY"?new kd(e):new ns(e)}async function QIe(e,t,n,i,r,s=1/0){let o=RIe(e.origin),a=`The time limit for ${t} ${n} was reached`,c,u=0;for(let d=1;d<=kIe||c instanceof kd;d+=1){if(c instanceof kd){if(u===vZ)throw c;u+=1,d-=1,e.log?.(`${c.message}; trying again (${u} of ${vZ}).`),await new Promise(p=>setTimeout(p,Math.max(0,Math.min(e.readyWaitMs??1e4,s-Date.now()))))}else d>1&&await new Promise(p=>setTimeout(p,Math.max(0,Math.min((e.retryDelayMs??2e3)*(d-1),s-Date.now()))));if(Date.now()>=s)throw new ns(a);try{let p,h=await(Number.isFinite(s)?Promise.race([e.idToken(o),new Promise((A,y)=>{p=setTimeout(()=>y(new ns(a)),Math.max(1,s-Date.now()))})]).finally(()=>{p&&clearTimeout(p)}):e.idToken(o));if(Date.now()>=s)throw new ns(a);let g=await(e.fetch??fetch)(new URL(n,o).toString(),{...i(h),redirect:"error",signal:AbortSignal.timeout(Math.max(1,Math.min(SIe,s-Date.now())))}).catch(A=>{throw new ns(A instanceof Error?A.message:String(A),{cause:A})});return await r(g)}catch(p){if(p instanceof oa||Date.now()>=s)throw p;c=p}}throw c}function $Ie(e,t,n,i,r){let s=i.headers.get("cf-ray");e.log?.(`Testbot V3: ${t} ${n} answered ${i.status}${s?`, cf-ray ${s}`:""}: ${r.replace(/\s+/g," ").slice(0,200)}`)}function TIe(e,t,n,i,r){let s=t==="GET"?void 0:JSON.stringify(i),o=t==="PUT"&&/^\/api\/v1\/runner\/attempts\/[^/]+\/report$/.test(n)&&s!==void 0&&Buffer.byteLength(s,"utf8")>_k;if(o&&Buffer.byteLength(s,"utf8")>IV)throw new Error("The report exceeds the app's 16 MiB expanded report limit");let a=o?new Uint8Array((0,IZ.gzipSync)(s)):s;if(o&&a.length>_k)throw new Error("The compressed report exceeds the app's 1 MiB report upload limit");return QIe(e,t,n,u=>({method:t,headers:{Authorization:`Bearer ${u}`,"Content-Type":"application/json",Accept:"application/json",...o?{"Content-Encoding":"gzip"}:{}},body:a}),async u=>{let d=await u.text().catch(()=>""),p={};try{p=JSON.parse(d)}catch{}if(u.ok)return p.data;$Ie(e,t,n,u,d);let h=p.error?.fields,g=typeof h?.path=="string"&&typeof h.reason=="string"?` at ${h.path}: ${h.reason}`:"",A=`The Skyramp app refused ${t} ${n}: ${u.status} ${p.error?.code??"no error code"}${g}`;return xIe(A,u.status,p.error?.code,typeof h?.path=="string"?h.path:void 0)},r)}var G4e=10*6e4;var z4e=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var H4e=l.object({tests:l.object({placements:l.array(l.unknown()).optional()}).passthrough().optional()}).passthrough(),J4e=l.object({repository:$k,testType:l.string(),directory:l.string()}).passthrough();var q4e=l.object({report:l.object({language:l.string()}).passthrough()}).passthrough();var Y4e=l.object({environment:l.object({components:l.array(l.unknown()).optional(),dependencies:l.array(l.unknown()).optional()}).passthrough()}).passthrough(),W4e=l.object({environment:l.object({offLimits:l.unknown().optional()}).passthrough()}).passthrough();var Z4e=l.object({environment:l.object({allowedEgress:l.unknown().optional()}).passthrough()}).passthrough();var K4e=l.object({name:l.string().min(1),provision:l.literal("existing"),url:l.string().min(1),repository:$k.optional(),revisionUrl:l.string().min(1).optional()}).passthrough(),X4e=l.object({name:l.string().min(1),url:l.string().nullable(),versionUrl:l.string().nullable(),notes:l.string().nullable()}).passthrough();var eZe=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);var tZe={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};async function CZ(e,t){return BIe(e.attemptId,"attempt id"),TIe(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,JV({reportUploaded:e.reportUploaded,recipeUploaded:e.recipeUploaded,revisionsUploaded:e.revisionsUploaded,cancelled:e.cause==="cancelled",timedOut:e.cause==="timed_out",setupFailed:e.cause==="setup_failed",checkoutFailed:e.cause==="checkout_failed"||e.cause==="merge_conflict"&&!e.conflict,mergeConflict:e.cause==="merge_conflict"?e.conflict:void 0,environmentUnverified:e.cause==="environment_unverified",runnerProviderNotReady:e.cause==="runner_provider_not_ready",credentialMissing:e.cause==="credential_missing",modelProviderDenied:e.cause==="model_provider_denied",modelProviderUnavailable:e.cause==="model_provider_unavailable"}))}var Ag=se(require("fs")),rs=se(require("path")),SZ=require("child_process");var Rd=rs.join(".skyramp","sut");function _Ie(e){return e.startsWith(`${Rd}${rs.sep}`)||e.startsWith(".skyramp/sut/")||/(^|\/)(docker-compose|compose)[^/]*\.ya?ml$/.test(e)||/(^|\/)Dockerfile[^/]*$/.test(e)||/^\.github\/workflows\//.test(e)}function B_(e,t,n={}){let i=t.split(/[\\/]+/).filter(Boolean),r=e;for(let[s,o]of i.entries()){r=rs.join(r,o);let a=Ag.lstatSync(r,{throwIfNoEntry:!1}),c=s===i.length-1;if(!a||a.isSymbolicLink()||(c?n.directory?!a.isDirectory():!a.isFile():!a.isDirectory()))return}return i.length?r:void 0}function Kc(e,t=[]){let n=p=>B_(e,p),i=n(rs.join(Rd,"setup.sh")),r=n(rs.join(Rd,"teardown.sh")),s=n(rs.join(Rd,"get-auth-token.sh")),o,a=n(rs.join(Rd,"health.json"));if(a)try{let p=JSON.parse(Ag.readFileSync(a,"utf-8"));p&&(p.url||p.command)&&(o=p)}catch{}let c,u=n(rs.join(Rd,"deploy-budget.json"));if(u)try{let p=JSON.parse(Ag.readFileSync(u,"utf-8"));typeof p?.minutes=="number"&&Number.isFinite(p.minutes)&&p.minutes>0&&(c=p.minutes)}catch{}let d=t.filter(_Ie);return{setupScript:i,teardownScript:r,authTokenScript:s,healthHint:o,budgetMinutes:c,present:!!(i||a),staleFiles:d,stale:d.length>0}}var kZ=12e4;function Lb(e,t,n){let i=n.timeoutMs??kZ;if(n.signal?.aborted)return Promise.resolve(`${e.label} failed (cancelled)`);let r=o=>Sf(zt(o,n.secretValues??[])),s;try{s=fi(e.argv,t,n.env)}catch(o){return Promise.resolve(r(`${e.label} failed (could not start: ${o instanceof Error?o.message:String(o)})`))}return new Promise(o=>{let a="",c=!1,u=!1,d,p;try{p=(0,SZ.spawn)(s.argv[0],s.argv.slice(1),{cwd:t,env:s.env,stdio:["ignore","pipe","pipe"],detached:!0})}catch(R){let w=R instanceof Error?R.message:String(R);o(r(`${e.label} failed (could not start: ${w})`));return}let h=R=>{let w=Math.max(0,...(n.secretValues??[]).map(Q=>Q.length));a=(a+R.toString("utf-8")).slice(-(4096+w))},g=()=>r(Hk(a,n.secretValues??[],4096));p.stdout?.on("data",h),p.stderr?.on("data",h);let A=()=>{try{p.pid!==void 0&&process.kill(-p.pid,"SIGKILL")}catch{p.kill("SIGKILL")}},y=R=>{let w=g().trim().split(`
231
- `).pop()?.trim().slice(0,300)??"";return`${e.label} failed (${R})${w?`: ${w}`:""}`},E=R=>{u||(u=!0,clearTimeout(b),clearTimeout(d),n.signal?.removeEventListener("abort",v),R!==void 0&&A(),p.stdout?.destroy(),p.stderr?.destroy(),nc(t,R===void 0?0:1),o(R===void 0?void 0:r(R)))},v=()=>E(y("cancelled")),b=setTimeout(()=>{c=!0,E(y(`timed out after ${i/1e3} s`))},i);n.signal?.addEventListener("abort",v,{once:!0}),n.signal?.aborted&&v();let I=(R,w)=>{if(c)return y(`timed out after ${i/1e3} s`);if(R!==0)return y(R===null?`killed by ${w}`:`exit ${R}`)};p.on("error",R=>E(y(`could not start: ${R.message}`))),p.on("close",(R,w)=>E(I(R,w))),p.on("exit",(R,w)=>{u||(R!==0?E(I(R,w)):d=setTimeout(()=>E(I(R,w)),1e3))})})}var RZ=".skyramp/sut/health.json",EZe={[RZ]:`${RZ} (with a url or command)`};function x_(e,t){return!ef(e.status)||e.environment?[]:[...new Set(e.components.flatMap(n=>n.credentials??[]))].filter(n=>!cW(n,t))}function Q_(e){let t=e.filter(Zm),n=e.filter(i=>!Zm(i));return[n.length>0&&`${n.join(", ")} ${n.length===1?"has":"have"} no value in this setup`,t.length>0&&`${t.join(", ")} ${t.length===1?"is a name":"are names"} Testbot keeps for its own tokens`].filter(Boolean).join("; ")}function jb(e){if(e.state.stages.onboard?.status==="passed")return Ve(e,"onboard.json")}function OIe(e){let t=Ad(e).serverUrl,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0;return{...e,GIT_CONFIG_COUNT:String(n+2),[`GIT_CONFIG_KEY_${n}`]:`http.${t}/.extraheader`,[`GIT_CONFIG_VALUE_${n}`]:"",[`GIT_CONFIG_KEY_${n+1}`]:"http.extraheader",[`GIT_CONFIG_VALUE_${n+1}`]:""}}var UIe=90,FIe={CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",CLAUDE_BYTE_STREAM_IDLE_TIMEOUT_MS:String(UIe*1e3)},BZ=30,xZ={BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:String(BZ*6e4)},QZ=["This session is non-interactive: it ends as soon as you stop, and a background command can",`never notify you. Wait for long builds in the foreground (one Bash call may run up to ${BZ}`,"minutes) and keep checking until they finish; never end your turn while setup is running. A server that must keep","running after setup is detached inside the command itself, with the redirect of both stdout and stderr","(`> log 2>&1`) on the whole backgrounded command (`docker compose up -d`, or `{ cmd; } </dev/null > log 2>&1 &`).","Without `2>&1` the server keeps the call's stderr open, and in `a || nohup cmd > log &` or","`(cd dir && nohup cmd > log &)` the redirect covers only `cmd`, and the shell that runs it keeps the call's output","open until the server exits. Run a setup script as a command of its own, never piped or chained:","`bash .skyramp/sut/setup.sh`. The call returns its output and exit status when the script exits, even if a server","it started still holds its output; through a pipe (`| tail`), it waits for that server."];function MIe(e,t){return OIe(ft(e,{...FIe,...t},"session"))}function $_(e){return MIe(process.env,e)}var Gb=se(require("fs")),mg=se(require("path"));var $Z=["browser_assert","browser_assert_api_request","browser_assert_hidden","browser_assert_table_cell","browser_blueprint","browser_click","browser_drag","browser_evaluate","browser_file_upload","browser_gojs_add_node","browser_gojs_link","browser_hover","browser_mouse_action","browser_navigate","browser_navigate_back","browser_press_key","browser_select_option","browser_snapshot","browser_tabs","browser_take_screenshot","browser_type","browser_visual_snapshot","browser_wait_for"],$Ze=[...$Z,"skyramp_export_zip","skyramp_actions","skyramp_analyze_changes","skyramp_analyze_test_health","skyramp_batch_mock_generation","skyramp_batch_scenario_test_generation","skyramp_contract_test_generation","skyramp_e2e_test_generation","skyramp_enhance_assertions","skyramp_enrich_test_with_mocks","skyramp_execute_test","skyramp_fix_errors","skyramp_fuzz_test_generation","skyramp_generate_enriched_integration_test","skyramp_init_scan","skyramp_init_workspace","skyramp_integration_test_generation","skyramp_load_test_generation","skyramp_login","skyramp_logout","skyramp_mock_generation","skyramp_modularization","skyramp_one_click_tool","skyramp_preflight_mock_check","skyramp_query_proxy_mocks","skyramp_recommend_tests","skyramp_register_test_plan","skyramp_reuse_code","skyramp_run_existing_tests","skyramp_setup_local_dev_worker","skyramp_smoke_test_generation","skyramp_start_trace_collection","skyramp_stop_trace_collection","skyramp_submit_report","skyramp_ui_test_generation"];var TZe=["skyramp_ui_test_generation","skyramp_mock_generation","skyramp_fix_errors","skyramp_start_trace_collection","skyramp_stop_trace_collection","skyramp_export_zip",...$Z];var TZ=["Bash(ls:*)","Bash(cat:*)","Bash(head:*)","Bash(tail:*)","Bash(wc:*)","Bash(find:*)","Bash(grep:*)","Bash(rg:*)","Bash(diff:*)","Bash(sort:*)","Bash(env:*)","Bash(echo:*)","Bash(pwd:*)","Bash(which:*)","Bash(cp:*)","Bash(curl:*)","Bash(jq:*)","Bash(true:*)"];var Vb=se(require("fs"));var jIe={name:"output-produced",verify(e,t,n){let i=e.outputFileFor(n.name);return(Vb.existsSync(i)?Vb.readFileSync(i,"utf-8"):"").trim().length>0?{name:this.name,passed:!0}:{name:this.name,passed:!1,details:`stage produced no output (${i} empty or missing)`}}},VIe=["Re-read the stage instructions above and confirm every task was completed.","If you find a mistake or an incomplete task, fix it now before finishing.","End your response with a one-line summary of what this stage accomplished."];function _Z(e){let t=e.requires??[];return{name:e.name,model:e.model??"sonnet",maxAttempts:e.maxAttempts,effort:e.effort,timeoutMinutes:e.timeoutMinutes??15,scaleTimeout:e.scaleTimeout,requires:t,softRequires:e.softRequires,validateInput:e.validateInput??(()=>({ok:!0,reasons:[]})),buildPrompt:e.buildPrompt??(()=>`You are the "${e.name}" stage of the Skyramp Testbot.`),selfVerification:e.selfVerification??VIe,exitGates:e.exitGates??[jIe],prepare:e.prepare,abortIf:e.abortIf,onAbort:e.onAbort,beforeReset:e.beforeReset,teardown:e.teardown,releaseAtRunEnd:e.releaseAtRunEnd,buildMcpServers:e.buildMcpServers,buildReadDirs:e.buildReadDirs,buildPluginDirs:e.buildPluginDirs,buildSettings:e.buildSettings,renderTimeLimit:e.renderTimeLimit,namesSession:e.namesSession,resumeFrom:e.resumeFrom,requiredSkills:e.requiredSkills,buildSessionEnv:e.buildSessionEnv,dataSafetyProxy:e.dataSafetyProxy,startsApp:e.startsApp,allowedTools:e.allowedTools,buildDisallowedTools:e.buildDisallowedTools,captureTrace:e.captureTrace,onPassed:e.onPassed,passReason:e.passReason,adversarialReview:e.adversarialReview,retryHint:e.retryHint,beforeGates:e.beforeGates,afterAttempt:e.afterAttempt,retryNote:e.retryNote,salvage:e.salvage,checkpoint:e.checkpoint,needsSutAuth:e.needsSutAuth,triageBranch:e.triageBranch,branchSkipClears:e.branchSkipClears,branchRequires:e.branchRequires}}var GIe=["Bash(docker:*)","Bash(docker compose:*)","Bash(docker-compose:*)","Bash(bash:*)","Bash(sh:*)","Bash(.skyramp/sut/*)","Bash(./.skyramp/sut/*)","Bash(curl:*)","Bash(sleep:*)",...TZ,"Read","Write","Edit"];function zIe(e){let t=e.state.stages.onboard;if(t&&(t.status==="failed"||t.status==="aborted")){let o=t.reason?` \u2014 ${t.reason.length>300?`${t.reason.slice(0,300)}\u2026`:t.reason}`:"";return{ok:!1,reasons:[`onboarding ran and did not pass (${t.status}${o}) \u2014 deploy does not replay its recipe; fix that and onboard again`]}}let n=Ai(e),i=jb(e);if(i?.status==="blocked")return{ok:!1,reasons:[`onboarding reported blocked (${i.blockers.length} blocker(s)) \u2014 see outputs/onboard.json`]};let r=e.inputs.setupEvents&&t?.status==="passed"&&i&&!e.inputs.recheck?x_(i,$_()):[];return r.length>0?{ok:!1,reasons:[`the recipe reads ${r.join(", ")}: ${Q_(r)} \u2014 deploy waits for the check Skyramp runs once the setup ends`]}:n&&!n.sutRequired&&!(i&&ef(i.status))&&!e.inputs.recheck?{ok:!1,reasons:["preflight determined no SUT is required (non-application change)"]}:Kc(e.inputs.repositoryPath,n?.changedFiles.map(o=>o.path)).present?{ok:!0,reasons:[]}:{ok:!1,reasons:["no deploy recipe found (.skyramp/sut/setup.sh or health.json) \u2014 run onboarding first"]}}function HIe(e){let t=e.prepared?.recipe?.budgetMinutes;if(t===void 0)return;let n=Math.min(t+5,90);return n>25?n:void 0}function JIe(e){let t=Ai(e);return{recipe:Kc(e.inputs.repositoryPath,t?.changedFiles.map(i=>i.path))}}function qIe(e,t){return[t.setupScript,t.teardownScript,t.authTokenScript].filter(n=>!!n).map(n=>mg.relative(e,n))}function YIe(e,t="revisions"){let n=Ab(e.inputs);return n.length===0?[]:["","Shared components: these run in an existing environment that this run does not deploy.",...n.map(i=>` - ${i.name} at ${i.url}, running ${i.repository}`),"For each, find the URL on its host where the RUNNING component reports its commit (a version,",`build-info or health endpoint) and record it in "${t}": the url, and what it returned,`,"VERBATIM. This gate fetches each url and reads the commit from what it returns. A checkout's","commit is not the deployed one. Cite only the components listed; leave out one you cannot","check \u2014 it is then reported unverifiable, and no runtime test runs against it."]}function NZ(e){return jb(e)?.environment??e.inputs.recheckEnvironment}function WIe(e,t){return[`Tasks: the SUT is the customer's existing deployment at ${e}, already running. Never start, stop, redeploy or`,"change it, and write no setup.sh or teardown.sh: this recipe has none on purpose.","1. Sign in the way the recipe records (.skyramp/sut/get-auth-token.sh), when it has one \u2014 never echo it.","2. Health-check: run the recipe's check (.skyramp/sut/health.json) and confirm it answers with real data. Record the"," exact url/command and what it returned.",...t.healthHint?[` The recorded check: ${JSON.stringify(t.healthHint)}`]:[],'3. Record the outcome: "clean" when the check passes; "bringup-failed", with bringupError, when the deployment does',` not answer or is not ready. baseUrls: each component's address. teardown: "true", since nothing was started.`]}function ZIe(e){let t=jb(e),n=e.inputs.recheck?e.inputs.recheckCredentials??[]:t?Ak(t):[];if(n.length===0)return[];let i=e.inputs.sharedEnvironment,r=Hp(i).map(s=>s.name);return["",`Credentials: the recipe reads ${n.join(", ")}, each from the environment variable of its name. Test each one that`,"has a value with a request that changes nothing, such as signing in with it (.skyramp/sut/get-auth-token.sh) or a GET","of an authenticated route: never one that creates, changes or deletes data.",...r.length>0?[`The shared components ${r.join(", ")} stay unchanged: test a credential they take only with a read.`]:[],...KIe(e)?["Record each one that is refused, such as with a 401 or 403 or a sign-in that fails, or that the app rejects at",'startup or bootstrap, such as a password it finds too short, in "credentialsRefused": its name, the component that',"refused it, the HTTP status when there was one, and the request or command with what came back. For one with no",'HTTP status, start that evidence with one short phrase saying why and a colon, such as "password shorter than 8','characters: <command and what came back>". Never write a value, there or anywhere. Leave out one with no value:',"Testbot reports it. A refused credential is not drift: never change the recipe to get around it. Never replace a","credential that has a value with a stand-in or a value written into the recipe, and never stop the recipe reading","it: Testbot refuses a recipe that does. When it stops the app coming up or its check passing, the outcome is",'"bringup-failed", and the credential is named.']:["Record each one that is refused, such as with a 401 or 403 or a sign-in that fails, in",'"credentialsRefused": its name, the component that refused it, the HTTP status, and the request or command with what',"came back. Never write a value, there or anywhere. Leave out one with no value: Testbot reports it. A refused","credential is not drift: never change the recipe to get around it. When it stops the app coming up or its check",'passing, the outcome is "bringup-failed", as for any other failure.']]}var KIe=e=>!!(e.inputs.recheck||e.inputs.setupEvents);function XIe(e){let{recipe:t}=e.prepared,n=e.inputs.repositoryPath,i=qIe(n,t),r=NZ(e),s=e.inputs.sharedEnvironment,o=Hp(s).map(a=>a.name);return['You are the "deploy" stage of the Skyramp Testbot.',"",...r?["Purpose: confirm, from a fresh session, that the existing deployment onboard found is reachable and ready, so the","recipe is proven the way every run will use it. The recipe already exists; change nothing."]:["Purpose: bring the system under test (SUT) up from its recorded recipe so","later stages can run tests against it. You do NOT design the deployment \u2014 the","recipe already exists. Execute it, verify it works, and if it has drifted","slightly out of date, correct it and continue (rather than reverting)."],"",`Repository: ${n} \u2014 work inside it.`,`Recipe files present: ${i.join(", ")||"(workspace only)"}`,"",...QZ,t.stale?`
230
+ `,k=s?"pr-body.md":`pr-body-${mZ(o)}.md`,W=sa.join(e.outputsDir,k);wi.writeFileSync(W,Q);let de=fn(d,["rev-parse","HEAD"]),K=w??de;fn(d,["checkout","-B",I]),a=I,fn(d,["reset"]);for(let M of r)dIe(sa.join(d,M),h);let Ce=[];for(let M of r)try{fn(d,["--literal-pathspecs","add","--",M])}catch{Ce.push(M)}try{fn(d,["diff","--cached","--quiet"])}catch{try{let M=bIe(d,p,de,K,e.inputs.skyrampRunUrl);fn(d,["-c",`user.name=${y.name}`,"-c",`user.email=${y.email}`,"commit","-m",M])}catch(M){throw new Fb(M)}c=!0}u=fn(d,["rev-parse","HEAD"]);let Le,et=w??s?.headSha;if(c&&et&&et!==de){let M=!1;try{fn(d,["checkout","-q","-B",a,et]),M=!0,fn(d,["-c",`user.name=${y.name}`,"-c",`user.email=${y.email}`,"cherry-pick","--keep-redundant-commits",u]),M=!1,p_(rt=>fn(d,rt),et),u=fn(d,["rev-parse","HEAD"])}catch(rt){try{fn(d,["cherry-pick","--abort"])}catch{}fn(d,["checkout","-q","-B",a,u]);let ot=sg(ta(rt),1/0);if(w&&!M)throw rt;if(w)return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:E,base:v,committed:c,commitSha:u,pushed:!1,prAction:"skipped",prTitle:A,unstaged:Ce,reason:`the tests do not apply to ${v} at ${w.slice(0,12)} without the merged revisions (${ot}), so no tests PR was opened`}};Le=`tests committed on the checkout's merge commit (re-cut onto ${et.slice(0,12)} failed: ${ot})`}}let Oe=s?{}:{repositoryPath:d,repoSlug:o,devPr:null};if(!c){let M=await t.markTestsPrUnchanged({branch:a,...Oe});return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:E,base:v,committed:!1,commitSha:u,pushed:!1,prAction:M.action==="unchanged"?"unchanged":"skipped",prUrl:M.url,prTitle:A,unstaged:Ce,reason:M.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 Z=await t.publishTestsPr({repositoryPath:d,...Oe,remote:E,branch:a,base:v,commitSha:u,title:A,bodyFile:W,mode:e.inputs.deliverMode,deliveryOwner:b,...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:E,base:Z.base,requestedBase:v,committed:c,commitSha:u,pushed:Z.pushed,...Z.pushedCommits?{pushedCommits:Z.pushedCommits}:{},...Z.deliveredCommit?{deliveredCommit:Z.deliveredCommit}:{},prAction:Z.action,...Z.retargetedAs?{retargetedAs:Z.retargetedAs}:{},prUrl:Z.url,prTitle:A,...Z.failure?{prFailure:Z.failure,prDetail:Z.detail}:{},...Le?{cutNote:Le}:{},...Z.action==="skipped"&&Z.detail?{reason:Z.detail}:{},unstaged:Ce}}}catch(d){return{thrown:!0,record:{schemaVersion:1,repository:o,branch:a,committed:c,commitSha:u,pushed:!1,prAction:"failed",...EIe(d),unstaged:[]}}}}var GWe={name:"deliver",timeoutMinutes:5,execute:gIe,validateInput:e=>{let t=a_(e);return t?{ok:!1,reasons:[t]}:oIe(e)},requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var V4e=10*6e4;var G4e=10*6e4;var SIe=3e4,kIe=3,vZ=30,oa=class extends Error{constructor(n,i,r,s){super(n);this.status=i;this.code=r;this.path=s}status;code;path},ns=class extends Error{},kd=class extends ns{},Mb=class extends kd{};function RIe(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 BIe(e,t){if(!bl.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}function xIe(e,t,n,i){throw t<500&&t!==429?new oa(e,t,n,i):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new Mb(e):t===503&&n==="RUN_NOT_READY"?new kd(e):new ns(e)}async function QIe(e,t,n,i,r,s=1/0){let o=RIe(e.origin),a=`The time limit for ${t} ${n} was reached`,c,u=0;for(let d=1;d<=kIe||c instanceof kd;d+=1){if(c instanceof kd){if(u===vZ)throw c;u+=1,d-=1,e.log?.(`${c.message}; trying again (${u} of ${vZ}).`),await new Promise(p=>setTimeout(p,Math.max(0,Math.min(e.readyWaitMs??1e4,s-Date.now()))))}else d>1&&await new Promise(p=>setTimeout(p,Math.max(0,Math.min((e.retryDelayMs??2e3)*(d-1),s-Date.now()))));if(Date.now()>=s)throw new ns(a);try{let p,h=await(Number.isFinite(s)?Promise.race([e.idToken(o),new Promise((A,y)=>{p=setTimeout(()=>y(new ns(a)),Math.max(1,s-Date.now()))})]).finally(()=>{p&&clearTimeout(p)}):e.idToken(o));if(Date.now()>=s)throw new ns(a);let g=await(e.fetch??fetch)(new URL(n,o).toString(),{...i(h),redirect:"error",signal:AbortSignal.timeout(Math.max(1,Math.min(SIe,s-Date.now())))}).catch(A=>{throw new ns(A instanceof Error?A.message:String(A),{cause:A})});return await r(g)}catch(p){if(p instanceof oa||Date.now()>=s)throw p;c=p}}throw c}function $Ie(e,t,n,i,r){let s=i.headers.get("cf-ray");e.log?.(`Testbot V3: ${t} ${n} answered ${i.status}${s?`, cf-ray ${s}`:""}: ${r.replace(/\s+/g," ").slice(0,200)}`)}function TIe(e,t,n,i,r){let s=t==="GET"?void 0:JSON.stringify(i),o=t==="PUT"&&/^\/api\/v1\/runner\/attempts\/[^/]+\/report$/.test(n)&&s!==void 0&&Buffer.byteLength(s,"utf8")>_k;if(o&&Buffer.byteLength(s,"utf8")>IV)throw new Error("The report exceeds the app's 16 MiB expanded report limit");let a=o?new Uint8Array((0,IZ.gzipSync)(s)):s;if(o&&a.length>_k)throw new Error("The compressed report exceeds the app's 1 MiB report upload limit");return QIe(e,t,n,u=>({method:t,headers:{Authorization:`Bearer ${u}`,"Content-Type":"application/json",Accept:"application/json",...o?{"Content-Encoding":"gzip"}:{}},body:a}),async u=>{let d=await u.text().catch(()=>""),p={};try{p=JSON.parse(d)}catch{}if(u.ok)return p.data;$Ie(e,t,n,u,d);let h=p.error?.fields,g=typeof h?.path=="string"&&typeof h.reason=="string"?` at ${h.path}: ${h.reason}`:"",A=`The Skyramp app refused ${t} ${n}: ${u.status} ${p.error?.code??"no error code"}${g}`;return xIe(A,u.status,p.error?.code,typeof h?.path=="string"?h.path:void 0)},r)}var z4e=10*6e4;var H4e=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var J4e=l.object({tests:l.object({placements:l.array(l.unknown()).optional()}).passthrough().optional()}).passthrough(),q4e=l.object({repository:$k,testType:l.string(),directory:l.string()}).passthrough();var Y4e=l.object({report:l.object({language:l.string()}).passthrough()}).passthrough();var W4e=l.object({environment:l.object({components:l.array(l.unknown()).optional(),dependencies:l.array(l.unknown()).optional()}).passthrough()}).passthrough(),Z4e=l.object({environment:l.object({offLimits:l.unknown().optional()}).passthrough()}).passthrough();var K4e=l.object({environment:l.object({allowedEgress:l.unknown().optional()}).passthrough()}).passthrough();var X4e=l.object({name:l.string().min(1),provision:l.literal("existing"),url:l.string().min(1),repository:$k.optional(),revisionUrl:l.string().min(1).optional()}).passthrough(),eZe=l.object({name:l.string().min(1),url:l.string().nullable(),versionUrl:l.string().nullable(),notes:l.string().nullable()}).passthrough();var tZe=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);var nZe={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};async function CZ(e,t){return BIe(e.attemptId,"attempt id"),TIe(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,JV({reportUploaded:e.reportUploaded,recipeUploaded:e.recipeUploaded,revisionsUploaded:e.revisionsUploaded,cancelled:e.cause==="cancelled",timedOut:e.cause==="timed_out",setupFailed:e.cause==="setup_failed",checkoutFailed:e.cause==="checkout_failed"||e.cause==="merge_conflict"&&!e.conflict,mergeConflict:e.cause==="merge_conflict"?e.conflict:void 0,environmentUnverified:e.cause==="environment_unverified",runnerProviderNotReady:e.cause==="runner_provider_not_ready",credentialMissing:e.cause==="credential_missing",modelProviderDenied:e.cause==="model_provider_denied",modelProviderUnavailable:e.cause==="model_provider_unavailable"}))}var Ag=se(require("fs")),rs=se(require("path")),SZ=require("child_process");var Rd=rs.join(".skyramp","sut");function _Ie(e){return e.startsWith(`${Rd}${rs.sep}`)||e.startsWith(".skyramp/sut/")||/(^|\/)(docker-compose|compose)[^/]*\.ya?ml$/.test(e)||/(^|\/)Dockerfile[^/]*$/.test(e)||/^\.github\/workflows\//.test(e)}function B_(e,t,n={}){let i=t.split(/[\\/]+/).filter(Boolean),r=e;for(let[s,o]of i.entries()){r=rs.join(r,o);let a=Ag.lstatSync(r,{throwIfNoEntry:!1}),c=s===i.length-1;if(!a||a.isSymbolicLink()||(c?n.directory?!a.isDirectory():!a.isFile():!a.isDirectory()))return}return i.length?r:void 0}function Kc(e,t=[]){let n=p=>B_(e,p),i=n(rs.join(Rd,"setup.sh")),r=n(rs.join(Rd,"teardown.sh")),s=n(rs.join(Rd,"get-auth-token.sh")),o,a=n(rs.join(Rd,"health.json"));if(a)try{let p=JSON.parse(Ag.readFileSync(a,"utf-8"));p&&(p.url||p.command)&&(o=p)}catch{}let c,u=n(rs.join(Rd,"deploy-budget.json"));if(u)try{let p=JSON.parse(Ag.readFileSync(u,"utf-8"));typeof p?.minutes=="number"&&Number.isFinite(p.minutes)&&p.minutes>0&&(c=p.minutes)}catch{}let d=t.filter(_Ie);return{setupScript:i,teardownScript:r,authTokenScript:s,healthHint:o,budgetMinutes:c,present:!!(i||a),staleFiles:d,stale:d.length>0}}var kZ=12e4;function Lb(e,t,n){let i=n.timeoutMs??kZ;if(n.signal?.aborted)return Promise.resolve(`${e.label} failed (cancelled)`);let r=o=>Sf(zt(o,n.secretValues??[])),s;try{s=fi(e.argv,t,n.env)}catch(o){return Promise.resolve(r(`${e.label} failed (could not start: ${o instanceof Error?o.message:String(o)})`))}return new Promise(o=>{let a="",c=!1,u=!1,d,p;try{p=(0,SZ.spawn)(s.argv[0],s.argv.slice(1),{cwd:t,env:s.env,stdio:["ignore","pipe","pipe"],detached:!0})}catch(R){let w=R instanceof Error?R.message:String(R);o(r(`${e.label} failed (could not start: ${w})`));return}let h=R=>{let w=Math.max(0,...(n.secretValues??[]).map(Q=>Q.length));a=(a+R.toString("utf-8")).slice(-(4096+w))},g=()=>r(Hk(a,n.secretValues??[],4096));p.stdout?.on("data",h),p.stderr?.on("data",h);let A=()=>{try{p.pid!==void 0&&process.kill(-p.pid,"SIGKILL")}catch{p.kill("SIGKILL")}},y=R=>{let w=g().trim().split(`
231
+ `).pop()?.trim().slice(0,300)??"";return`${e.label} failed (${R})${w?`: ${w}`:""}`},E=R=>{u||(u=!0,clearTimeout(b),clearTimeout(d),n.signal?.removeEventListener("abort",v),R!==void 0&&A(),p.stdout?.destroy(),p.stderr?.destroy(),nc(t,R===void 0?0:1),o(R===void 0?void 0:r(R)))},v=()=>E(y("cancelled")),b=setTimeout(()=>{c=!0,E(y(`timed out after ${i/1e3} s`))},i);n.signal?.addEventListener("abort",v,{once:!0}),n.signal?.aborted&&v();let I=(R,w)=>{if(c)return y(`timed out after ${i/1e3} s`);if(R!==0)return y(R===null?`killed by ${w}`:`exit ${R}`)};p.on("error",R=>E(y(`could not start: ${R.message}`))),p.on("close",(R,w)=>E(I(R,w))),p.on("exit",(R,w)=>{u||(R!==0?E(I(R,w)):d=setTimeout(()=>E(I(R,w)),1e3))})})}var RZ=".skyramp/sut/health.json",vZe={[RZ]:`${RZ} (with a url or command)`};function x_(e,t){return!ef(e.status)||e.environment?[]:[...new Set(e.components.flatMap(n=>n.credentials??[]))].filter(n=>!cW(n,t))}function Q_(e){let t=e.filter(Zm),n=e.filter(i=>!Zm(i));return[n.length>0&&`${n.join(", ")} ${n.length===1?"has":"have"} no value in this setup`,t.length>0&&`${t.join(", ")} ${t.length===1?"is a name":"are names"} Testbot keeps for its own tokens`].filter(Boolean).join("; ")}function jb(e){if(e.state.stages.onboard?.status==="passed")return Ve(e,"onboard.json")}function OIe(e){let t=Ad(e).serverUrl,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0;return{...e,GIT_CONFIG_COUNT:String(n+2),[`GIT_CONFIG_KEY_${n}`]:`http.${t}/.extraheader`,[`GIT_CONFIG_VALUE_${n}`]:"",[`GIT_CONFIG_KEY_${n+1}`]:"http.extraheader",[`GIT_CONFIG_VALUE_${n+1}`]:""}}var UIe=90,FIe={CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",CLAUDE_BYTE_STREAM_IDLE_TIMEOUT_MS:String(UIe*1e3)},BZ=30,xZ={BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:String(BZ*6e4)},QZ=["This session is non-interactive: it ends as soon as you stop, and a background command can",`never notify you. Wait for long builds in the foreground (one Bash call may run up to ${BZ}`,"minutes) and keep checking until they finish; never end your turn while setup is running. A server that must keep","running after setup is detached inside the command itself, with the redirect of both stdout and stderr","(`> log 2>&1`) on the whole backgrounded command (`docker compose up -d`, or `{ cmd; } </dev/null > log 2>&1 &`).","Without `2>&1` the server keeps the call's stderr open, and in `a || nohup cmd > log &` or","`(cd dir && nohup cmd > log &)` the redirect covers only `cmd`, and the shell that runs it keeps the call's output","open until the server exits. Run a setup script as a command of its own, never piped or chained:","`bash .skyramp/sut/setup.sh`. The call returns its output and exit status when the script exits, even if a server","it started still holds its output; through a pipe (`| tail`), it waits for that server."];function MIe(e,t){return OIe(ft(e,{...FIe,...t},"session"))}function $_(e){return MIe(process.env,e)}var Gb=se(require("fs")),mg=se(require("path"));var $Z=["browser_assert","browser_assert_api_request","browser_assert_hidden","browser_assert_table_cell","browser_blueprint","browser_click","browser_drag","browser_evaluate","browser_file_upload","browser_gojs_add_node","browser_gojs_link","browser_hover","browser_mouse_action","browser_navigate","browser_navigate_back","browser_press_key","browser_select_option","browser_snapshot","browser_tabs","browser_take_screenshot","browser_type","browser_visual_snapshot","browser_wait_for"],TZe=[...$Z,"skyramp_export_zip","skyramp_actions","skyramp_analyze_changes","skyramp_analyze_test_health","skyramp_batch_mock_generation","skyramp_batch_scenario_test_generation","skyramp_contract_test_generation","skyramp_e2e_test_generation","skyramp_enhance_assertions","skyramp_enrich_test_with_mocks","skyramp_execute_test","skyramp_fix_errors","skyramp_fuzz_test_generation","skyramp_generate_enriched_integration_test","skyramp_init_scan","skyramp_init_workspace","skyramp_integration_test_generation","skyramp_load_test_generation","skyramp_login","skyramp_logout","skyramp_mock_generation","skyramp_modularization","skyramp_one_click_tool","skyramp_preflight_mock_check","skyramp_query_proxy_mocks","skyramp_recommend_tests","skyramp_register_test_plan","skyramp_reuse_code","skyramp_run_existing_tests","skyramp_setup_local_dev_worker","skyramp_smoke_test_generation","skyramp_start_trace_collection","skyramp_stop_trace_collection","skyramp_submit_report","skyramp_ui_test_generation"];var _Ze=["skyramp_ui_test_generation","skyramp_mock_generation","skyramp_fix_errors","skyramp_start_trace_collection","skyramp_stop_trace_collection","skyramp_export_zip",...$Z];var TZ=["Bash(ls:*)","Bash(cat:*)","Bash(head:*)","Bash(tail:*)","Bash(wc:*)","Bash(find:*)","Bash(grep:*)","Bash(rg:*)","Bash(diff:*)","Bash(sort:*)","Bash(env:*)","Bash(echo:*)","Bash(pwd:*)","Bash(which:*)","Bash(cp:*)","Bash(curl:*)","Bash(jq:*)","Bash(true:*)"];var Vb=se(require("fs"));var jIe={name:"output-produced",verify(e,t,n){let i=e.outputFileFor(n.name);return(Vb.existsSync(i)?Vb.readFileSync(i,"utf-8"):"").trim().length>0?{name:this.name,passed:!0}:{name:this.name,passed:!1,details:`stage produced no output (${i} empty or missing)`}}},VIe=["Re-read the stage instructions above and confirm every task was completed.","If you find a mistake or an incomplete task, fix it now before finishing.","End your response with a one-line summary of what this stage accomplished."];function _Z(e){let t=e.requires??[];return{name:e.name,model:e.model??"sonnet",maxAttempts:e.maxAttempts,effort:e.effort,timeoutMinutes:e.timeoutMinutes??15,scaleTimeout:e.scaleTimeout,requires:t,softRequires:e.softRequires,validateInput:e.validateInput??(()=>({ok:!0,reasons:[]})),buildPrompt:e.buildPrompt??(()=>`You are the "${e.name}" stage of the Skyramp Testbot.`),selfVerification:e.selfVerification??VIe,exitGates:e.exitGates??[jIe],prepare:e.prepare,abortIf:e.abortIf,onAbort:e.onAbort,beforeReset:e.beforeReset,teardown:e.teardown,releaseAtRunEnd:e.releaseAtRunEnd,buildMcpServers:e.buildMcpServers,buildReadDirs:e.buildReadDirs,buildPluginDirs:e.buildPluginDirs,buildSettings:e.buildSettings,renderTimeLimit:e.renderTimeLimit,namesSession:e.namesSession,resumeFrom:e.resumeFrom,requiredSkills:e.requiredSkills,buildSessionEnv:e.buildSessionEnv,dataSafetyProxy:e.dataSafetyProxy,startsApp:e.startsApp,allowedTools:e.allowedTools,buildDisallowedTools:e.buildDisallowedTools,captureTrace:e.captureTrace,onPassed:e.onPassed,passReason:e.passReason,adversarialReview:e.adversarialReview,retryHint:e.retryHint,beforeGates:e.beforeGates,afterAttempt:e.afterAttempt,retryNote:e.retryNote,salvage:e.salvage,checkpoint:e.checkpoint,needsSutAuth:e.needsSutAuth,triageBranch:e.triageBranch,branchSkipClears:e.branchSkipClears,branchRequires:e.branchRequires}}var GIe=["Bash(docker:*)","Bash(docker compose:*)","Bash(docker-compose:*)","Bash(bash:*)","Bash(sh:*)","Bash(.skyramp/sut/*)","Bash(./.skyramp/sut/*)","Bash(curl:*)","Bash(sleep:*)",...TZ,"Read","Write","Edit"];function zIe(e){let t=e.state.stages.onboard;if(t&&(t.status==="failed"||t.status==="aborted")){let o=t.reason?` \u2014 ${t.reason.length>300?`${t.reason.slice(0,300)}\u2026`:t.reason}`:"";return{ok:!1,reasons:[`onboarding ran and did not pass (${t.status}${o}) \u2014 deploy does not replay its recipe; fix that and onboard again`]}}let n=Ai(e),i=jb(e);if(i?.status==="blocked")return{ok:!1,reasons:[`onboarding reported blocked (${i.blockers.length} blocker(s)) \u2014 see outputs/onboard.json`]};let r=e.inputs.setupEvents&&t?.status==="passed"&&i&&!e.inputs.recheck?x_(i,$_()):[];return r.length>0?{ok:!1,reasons:[`the recipe reads ${r.join(", ")}: ${Q_(r)} \u2014 deploy waits for the check Skyramp runs once the setup ends`]}:n&&!n.sutRequired&&!(i&&ef(i.status))&&!e.inputs.recheck?{ok:!1,reasons:["preflight determined no SUT is required (non-application change)"]}:Kc(e.inputs.repositoryPath,n?.changedFiles.map(o=>o.path)).present?{ok:!0,reasons:[]}:{ok:!1,reasons:["no deploy recipe found (.skyramp/sut/setup.sh or health.json) \u2014 run onboarding first"]}}function HIe(e){let t=e.prepared?.recipe?.budgetMinutes;if(t===void 0)return;let n=Math.min(t+5,90);return n>25?n:void 0}function JIe(e){let t=Ai(e);return{recipe:Kc(e.inputs.repositoryPath,t?.changedFiles.map(i=>i.path))}}function qIe(e,t){return[t.setupScript,t.teardownScript,t.authTokenScript].filter(n=>!!n).map(n=>mg.relative(e,n))}function YIe(e,t="revisions"){let n=Ab(e.inputs);return n.length===0?[]:["","Shared components: these run in an existing environment that this run does not deploy.",...n.map(i=>` - ${i.name} at ${i.url}, running ${i.repository}`),"For each, find the URL on its host where the RUNNING component reports its commit (a version,",`build-info or health endpoint) and record it in "${t}": the url, and what it returned,`,"VERBATIM. This gate fetches each url and reads the commit from what it returns. A checkout's","commit is not the deployed one. Cite only the components listed; leave out one you cannot","check \u2014 it is then reported unverifiable, and no runtime test runs against it."]}function NZ(e){return jb(e)?.environment??e.inputs.recheckEnvironment}function WIe(e,t){return[`Tasks: the SUT is the customer's existing deployment at ${e}, already running. Never start, stop, redeploy or`,"change it, and write no setup.sh or teardown.sh: this recipe has none on purpose.","1. Sign in the way the recipe records (.skyramp/sut/get-auth-token.sh), when it has one \u2014 never echo it.","2. Health-check: run the recipe's check (.skyramp/sut/health.json) and confirm it answers with real data. Record the"," exact url/command and what it returned.",...t.healthHint?[` The recorded check: ${JSON.stringify(t.healthHint)}`]:[],'3. Record the outcome: "clean" when the check passes; "bringup-failed", with bringupError, when the deployment does',` not answer or is not ready. baseUrls: each component's address. teardown: "true", since nothing was started.`]}function ZIe(e){let t=jb(e),n=e.inputs.recheck?e.inputs.recheckCredentials??[]:t?Ak(t):[];if(n.length===0)return[];let i=e.inputs.sharedEnvironment,r=Hp(i).map(s=>s.name);return["",`Credentials: the recipe reads ${n.join(", ")}, each from the environment variable of its name. Test each one that`,"has a value with a request that changes nothing, such as signing in with it (.skyramp/sut/get-auth-token.sh) or a GET","of an authenticated route: never one that creates, changes or deletes data.",...r.length>0?[`The shared components ${r.join(", ")} stay unchanged: test a credential they take only with a read.`]:[],...KIe(e)?["Record each one that is refused, such as with a 401 or 403 or a sign-in that fails, or that the app rejects at",'startup or bootstrap, such as a password it finds too short, in "credentialsRefused": its name, the component that',"refused it, the HTTP status when there was one, and the request or command with what came back. For one with no",'HTTP status, start that evidence with one short phrase saying why and a colon, such as "password shorter than 8','characters: <command and what came back>". Never write a value, there or anywhere. Leave out one with no value:',"Testbot reports it. A refused credential is not drift: never change the recipe to get around it. Never replace a","credential that has a value with a stand-in or a value written into the recipe, and never stop the recipe reading","it: Testbot refuses a recipe that does. When it stops the app coming up or its check passing, the outcome is",'"bringup-failed", and the credential is named.']:["Record each one that is refused, such as with a 401 or 403 or a sign-in that fails, in",'"credentialsRefused": its name, the component that refused it, the HTTP status, and the request or command with what',"came back. Never write a value, there or anywhere. Leave out one with no value: Testbot reports it. A refused","credential is not drift: never change the recipe to get around it. When it stops the app coming up or its check",'passing, the outcome is "bringup-failed", as for any other failure.']]}var KIe=e=>!!(e.inputs.recheck||e.inputs.setupEvents);function XIe(e){let{recipe:t}=e.prepared,n=e.inputs.repositoryPath,i=qIe(n,t),r=NZ(e),s=e.inputs.sharedEnvironment,o=Hp(s).map(a=>a.name);return['You are the "deploy" stage of the Skyramp Testbot.',"",...r?["Purpose: confirm, from a fresh session, that the existing deployment onboard found is reachable and ready, so the","recipe is proven the way every run will use it. The recipe already exists; change nothing."]:["Purpose: bring the system under test (SUT) up from its recorded recipe so","later stages can run tests against it. You do NOT design the deployment \u2014 the","recipe already exists. Execute it, verify it works, and if it has drifted","slightly out of date, correct it and continue (rather than reverting)."],"",`Repository: ${n} \u2014 work inside it.`,`Recipe files present: ${i.join(", ")||"(workspace only)"}`,"",...QZ,t.stale?`
232
232
  STALENESS WARNING: this PR changed recipe/infra files (${t.staleFiles.join(", ")}).
233
233
  The recorded recipe may no longer match. If bring-up fails, first decide
234
234
  WHY: recipe drift (infra moved, recipe is behind) vs the change itself
235
235
  breaking bring-up. Do NOT paper over a PR that broke the app.`:"","",...r?WIe(r.address,t):["Tasks:","1. Replay the recipe: run .skyramp/sut/setup.sh (or the workspace bring-up)"," even when the SUT already answers: never skip it because something is running."," Bring up every dependency you can; mock one only when deploying it here"," is genuinely infeasible. If the recipe has drifted, correct it so it works"," and update the recipe files to what actually worked. teardown.sh exits 0"," when nothing runs.","2. Seed or reset state per the recipe. Acquire the auth token the way the"," recipe records (.skyramp/sut/get-auth-token.sh) \u2014 never echo it.",...o.length?[` Leave the shared components ${o.join(", ")} unchanged: do not seed or reset them.`]:[],"3. Health-check: confirm application logic answers with real data (seeded",' data readable via a real endpoint) \u2014 NOT "port open", NOT "any HTTP',' status". Record the exact url/command and what it returned.',...t.healthHint?[" Recommended health check (recorded by onboarding \u2014 prefer it, and",` record its real output): ${JSON.stringify(t.healthHint)}`]:[],'4. Record the outcome honestly (see the schema): "change-broke-bringup" is',' published to the author as "your change broke the app" and needs evidence'," \u2014 bringupError plus suspectFiles that THIS PR changed; without a changed",' file to point at, it is "bringup-failed".'],...YIe(e),...ZIe(e),"","Output: end with one JSON object matching:","",XV(sf)," // health.output is evidence, not narration: the exact bytes, with NOTHING"," // appended \u2014 no gloss on what the response proves, no list of the other probes"," // you ran. This gate RE-RUNS the check and matches the fresh output against this"," // field, so a sentence added here describes a run nobody can reproduce. Say what"," // it means in your prose answer instead."," // On a failed bring-up, baseUrls/health may be omitted \u2014 never invent a URL for an app that didn't start."].filter(a=>a!==void 0).join(`
236
- `)}function PZ(e){let t=mg.join(e.outputsDir,"deploy.txt");if(Gb.existsSync(t)){let{deploy:i}=zc({exitCode:0,stdout:Gb.readFileSync(t,"utf-8"),stderr:"",timedOut:!1,durationMs:0});if(i?.teardown)return{argv:["sh","-c",i.teardown],label:"deploy.json's teardown"}}let{teardownScript:n}=Kc(e.inputs.repositoryPath);if(n)return{argv:["bash",n],label:mg.join(".skyramp","sut","teardown.sh")}}function OZ(e,t){return Lb(t,e.inputs.repositoryPath,{env:ft(),secretValues:e.secretValues})}async function DZ(e){let t=PZ(e);if(t){let n=await OZ(e,t);if(n&&OY(e))throw new Error(`SUT teardown failed: ${n}`)}}async function eCe(e,t){let n=t.passed?void 0:UZ(e);if(!n)return;let i=await OZ(e,n);return i&&`${i} (if nothing was running, a teardown must exit 0)`}function UZ(e){return NZ(e)?void 0:PZ(e)}function tCe(e){if(UZ(e))return"Testbot tore down the SUT the previous attempt started. Bring it up again from the start: run .skyramp/sut/setup.sh (or the workspace bring-up), even if something still answers. Never reuse what is running."}function nCe(e,t){let{deploy:n}=zc(t,e.inputs.repositoryPath,e.secretValues);if(!n)return;if(n.outcome==="bringup-failed"){let r=zt(n.bringupError?.output?.trim()??"",e.secretValues??[]);return`bring-up failed (environment) \u2014 no live app for later stages${r?`: ${r.slice(0,160)}`:""}`}if(n.outcome==="change-broke-bringup")return"this PR broke bring-up \u2014 recorded as a finding, no live app for later stages";let i=qh(e).map(r=>r.name);if(i.length)return`the shared environment's ${i.join(", ")} does not verifiably run the revision under validation \u2014 no runtime test runs against it`}var FZ=_Z({name:"deploy",model:"opus",timeoutMinutes:25,requires:["preflight"],softRequires:["onboard"],startsApp:e=>!e.inputs.appRunning,triageBranch:"runtime",validateInput:zIe,prepare:JIe,scaleTimeout:HIe,buildPrompt:XIe,allowedTools:GIe,buildSessionEnv:()=>({...xZ}),selfVerification:["dependencies lists every backing service, true only if really deployed \u2014 a mocked one is false, never omitted.","Your final message is one JSON object matching the schema."],exitGates:[yb(),QW()],onPassed:async(e,t)=>({...TW(e,t),...await $W(e,t)}),passReason:nCe,afterAttempt:eCe,retryNote:tCe,onAbort:DZ,teardown:DZ});mn();mn();var gKe=20*1024*1024;var LZ=se(require("path"));var SKe=LZ.join(".skyramp","sut","get-auth-token.sh");var T_="\\$([A-Z][A-Z0-9_]{0,99})",kKe=new RegExp(`^${T_}$`),RKe=new RegExp(`^${T_}:${T_}$`);var I6e=3*6e4;var C6e=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;var aCe={discover:"reading the repositories",start:"starting the components",check:"checking that the components answer"};var _6e={running:"up",healthy:"up",ready:"up",started:"up",building:"starting",pending:"starting",installing:"starting",skipped:"out_of_scope",excluded:"out_of_scope","out-of-scope":"out_of_scope"};var D6e=new RegExp(Il.source,"g");var t9e=new RegExp(Il.source,"g");var lCe="https://testbot.skyramp.dev",aa={attemptId:"v3AttemptId",deadlineAt:"v3DeadlineAt",reportUploaded:"v3ReportUploaded",recipeUploaded:"v3RecipeUploaded",recipeStatus:"v3RecipeStatus",revisionsUploaded:"v3RevisionsUploaded",cause:"v3Cause",conflict:"v3Conflict"};function dCe(e,t,n){return{origin:e,idToken:t,sourceToken:n,mask:i=>ys(i),log:i=>di(i),onTokenRefused:(i,r)=>{fCe(i)&&jZ.set(r,i)},onTokenGranted:i=>{jZ.delete(i)}}}var jZ=new Map;var k8e=["setup_failed","checkout_failed","environment_unverified"];function pCe(e,t){return t.getTime()>=e.getTime()}function fCe(e){return e instanceof ns||e instanceof oa&&e.code!=="CREDENTIALS_UNAVAILABLE"}var R8e={cancelled:"Skyramp cancelled this run",expired:"this attempt passed its deadline in Skyramp",ended:"Skyramp already ended this attempt"},B8e={cancelled:"attempt-cancelled",expired:"attempt-closed",ended:"attempt-closed"},x8e={cancelled:"cancelled",expired:"timed_out",ended:"agent_failed"};var Q8e={analyze:"analyze",triage:"analyze",recommend:"recommend",generate:"generate","generate-ui":"generate","generate-unit":"generate",adapt:"generate",write:"generate",onboard:"execute",deploy:"execute","native-run":"execute",deliver:"deliver"},$8e={analyze:"change analysis",recommend:"test recommendations",generate:"test generation",execute:"test execution",deliver:"opening a pull request with the tests"};function hCe(){return Ne("skyrampAppOrigin").trim()||lCe}var T8e=10*6e4;var _8e={onboard:"onboard",deploy:"deploy"},D8e={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"}},N8e=new Set(["write","native-run"]);function gCe(){let e=Es(aa.conflict);if(!e)return;let t;try{t=HV.safeParse(JSON.parse(e))}catch(n){_t(`Testbot V3: the saved merge conflict is not JSON (${n instanceof Error?n.message:String(n)})`);return}if(t.success)return t.data;_t(`Testbot V3: the saved merge conflict breaks the contract (${t.error.issues.map(n=>`${n.path.join(".")}: ${n.message}`).join("; ")})`)}async function VZ(){let e=Es(aa.attemptId);if(!e)return;let t=Es(aa.reportUploaded)==="true",n=Es(aa.recipeUploaded)==="true",i=Es(aa.revisionsUploaded)==="true",r=Es(aa.deadlineAt),s=Es(aa.cause)||void 0;!s&&!t&&!n&&!i&&r&&pCe(new Date(r),new Date)&&(s="timed_out");let o=Ad().takeIdToken(),a=gCe(),c=await CZ({attemptId:e,reportUploaded:t,recipeUploaded:n,revisionsUploaded:i,cause:s,...a?{conflict:a}:{}},dCe(hCe(),o)),u=Es(aa.recipeStatus);n&&u?di(`Testbot V3: attempt ended; the setup ended ${u==="ready"?"Ready":"blocked (Needs input)"}.`):di(`Testbot V3: attempt ended; the run's outcome in Skyramp is ${c.outcome??"not final yet"}.`)}var GZ=require("child_process"),is=se(require("fs")),D_=se(require("path")),N_=require("string_decoder");var ACe="skyramp-testbot-state",mCe=/^\$\([^)]*\)$/;function yCe(e){for(let[t,n]of Object.entries(e))n!==void 0&&mCe.test(n)&&delete e[t]}function ECe(e){let t={},n=is.existsSync(e)?is.readFileSync(e,"utf-8"):"",i=/^([^\r\n<]+)<<(\S+)\r?\n([\s\S]*?)\r?\n\2\r?$/gm;for(let r=i.exec(n);r;r=i.exec(n))t[r[1]]=r[3];return t}function zZ(e,t={}){let n=t.env??process.env;if(!Wo(n))return!1;yCe(n),ZY(n);let i=n.AGENT_TEMPDIRECTORY||n.RUNNER_TEMP;if(i){n.RUNNER_TEMP??=i;let o=D_.join(i,ACe);if(e==="main")is.writeFileSync(o,"",{mode:384});else for(let[a,c]of Object.entries(ECe(o)))n[`STATE_${a}`]=c;n.GITHUB_STATE=o;for(let[a,c]of[["GITHUB_OUTPUT","output"],["GITHUB_ENV","env"],["GITHUB_PATH","path"],["GITHUB_STEP_SUMMARY",`summary-${e}.md`]])n[a]=D_.join(i,`skyramp-testbot-${c}`),is.writeFileSync(n[a],"",{mode:384})}let r=t.stdout??n===process.env;r&&vCe(n,t.write);let s=n.GITHUB_STEP_SUMMARY;if(r&&s){let o=t.write??(a=>h0(a.replace(/\n$/,"")));process.once("exit",()=>{is.existsSync(s)&&is.statSync(s).size>0&&o(`${ob("task.uploadsummary",{},s)}
236
+ `)}function PZ(e){let t=mg.join(e.outputsDir,"deploy.txt");if(Gb.existsSync(t)){let{deploy:i}=zc({exitCode:0,stdout:Gb.readFileSync(t,"utf-8"),stderr:"",timedOut:!1,durationMs:0});if(i?.teardown)return{argv:["sh","-c",i.teardown],label:"deploy.json's teardown"}}let{teardownScript:n}=Kc(e.inputs.repositoryPath);if(n)return{argv:["bash",n],label:mg.join(".skyramp","sut","teardown.sh")}}function OZ(e,t){return Lb(t,e.inputs.repositoryPath,{env:ft(),secretValues:e.secretValues})}async function DZ(e){let t=PZ(e);if(t){let n=await OZ(e,t);if(n&&OY(e))throw new Error(`SUT teardown failed: ${n}`)}}async function eCe(e,t){let n=t.passed?void 0:UZ(e);if(!n)return;let i=await OZ(e,n);return i&&`${i} (if nothing was running, a teardown must exit 0)`}function UZ(e){return NZ(e)?void 0:PZ(e)}function tCe(e){if(UZ(e))return"Testbot tore down the SUT the previous attempt started. Bring it up again from the start: run .skyramp/sut/setup.sh (or the workspace bring-up), even if something still answers. Never reuse what is running."}function nCe(e,t){let{deploy:n}=zc(t,e.inputs.repositoryPath,e.secretValues);if(!n)return;if(n.outcome==="bringup-failed"){let r=zt(n.bringupError?.output?.trim()??"",e.secretValues??[]);return`bring-up failed (environment) \u2014 no live app for later stages${r?`: ${r.slice(0,160)}`:""}`}if(n.outcome==="change-broke-bringup")return"this PR broke bring-up \u2014 recorded as a finding, no live app for later stages";let i=qh(e).map(r=>r.name);if(i.length)return`the shared environment's ${i.join(", ")} does not verifiably run the revision under validation \u2014 no runtime test runs against it`}var FZ=_Z({name:"deploy",model:"opus",timeoutMinutes:25,requires:["preflight"],softRequires:["onboard"],startsApp:e=>!e.inputs.appRunning,triageBranch:"runtime",validateInput:zIe,prepare:JIe,scaleTimeout:HIe,buildPrompt:XIe,allowedTools:GIe,buildSessionEnv:()=>({...xZ}),selfVerification:["dependencies lists every backing service, true only if really deployed \u2014 a mocked one is false, never omitted.","Your final message is one JSON object matching the schema."],exitGates:[yb(),QW()],onPassed:async(e,t)=>({...TW(e,t),...await $W(e,t)}),passReason:nCe,afterAttempt:eCe,retryNote:tCe,onAbort:DZ,teardown:DZ});mn();mn();var AKe=20*1024*1024;var LZ=se(require("path"));var kKe=LZ.join(".skyramp","sut","get-auth-token.sh");var T_="\\$([A-Z][A-Z0-9_]{0,99})",RKe=new RegExp(`^${T_}$`),BKe=new RegExp(`^${T_}:${T_}$`);var C6e=3*6e4;var S6e=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;var aCe={discover:"reading the repositories",start:"starting the components",check:"checking that the components answer"};var D6e={running:"up",healthy:"up",ready:"up",started:"up",building:"starting",pending:"starting",installing:"starting",skipped:"out_of_scope",excluded:"out_of_scope","out-of-scope":"out_of_scope"};var N6e=new RegExp(Il.source,"g");var n9e=new RegExp(Il.source,"g");var lCe="https://testbot.skyramp.dev",aa={attemptId:"v3AttemptId",deadlineAt:"v3DeadlineAt",reportUploaded:"v3ReportUploaded",recipeUploaded:"v3RecipeUploaded",recipeStatus:"v3RecipeStatus",revisionsUploaded:"v3RevisionsUploaded",cause:"v3Cause",conflict:"v3Conflict"};function dCe(e,t,n){return{origin:e,idToken:t,sourceToken:n,mask:i=>ys(i),log:i=>di(i),onTokenRefused:(i,r)=>{fCe(i)&&jZ.set(r,i)},onTokenGranted:i=>{jZ.delete(i)}}}var jZ=new Map;var R8e=["setup_failed","checkout_failed","environment_unverified"];function pCe(e,t){return t.getTime()>=e.getTime()}function fCe(e){return e instanceof ns||e instanceof oa&&e.code!=="CREDENTIALS_UNAVAILABLE"}var B8e={cancelled:"Skyramp cancelled this run",expired:"this attempt passed its deadline in Skyramp",ended:"Skyramp already ended this attempt"},x8e={cancelled:"attempt-cancelled",expired:"attempt-closed",ended:"attempt-closed"},Q8e={cancelled:"cancelled",expired:"timed_out",ended:"agent_failed"};var $8e={analyze:"analyze",triage:"analyze",recommend:"recommend",generate:"generate","generate-ui":"generate","generate-unit":"generate",adapt:"generate",write:"generate",onboard:"execute",deploy:"execute","native-run":"execute",deliver:"deliver"},T8e={analyze:"change analysis",recommend:"test recommendations",generate:"test generation",execute:"test execution",deliver:"opening a pull request with the tests"};function hCe(){return Ne("skyrampAppOrigin").trim()||lCe}var _8e=10*6e4;var D8e={onboard:"onboard",deploy:"deploy"},N8e={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"}},P8e=new Set(["write","native-run"]);function gCe(){let e=Es(aa.conflict);if(!e)return;let t;try{t=HV.safeParse(JSON.parse(e))}catch(n){_t(`Testbot V3: the saved merge conflict is not JSON (${n instanceof Error?n.message:String(n)})`);return}if(t.success)return t.data;_t(`Testbot V3: the saved merge conflict breaks the contract (${t.error.issues.map(n=>`${n.path.join(".")}: ${n.message}`).join("; ")})`)}async function VZ(){let e=Es(aa.attemptId);if(!e)return;let t=Es(aa.reportUploaded)==="true",n=Es(aa.recipeUploaded)==="true",i=Es(aa.revisionsUploaded)==="true",r=Es(aa.deadlineAt),s=Es(aa.cause)||void 0;!s&&!t&&!n&&!i&&r&&pCe(new Date(r),new Date)&&(s="timed_out");let o=Ad().takeIdToken(),a=gCe(),c=await CZ({attemptId:e,reportUploaded:t,recipeUploaded:n,revisionsUploaded:i,cause:s,...a?{conflict:a}:{}},dCe(hCe(),o)),u=Es(aa.recipeStatus);n&&u?di(`Testbot V3: attempt ended; the setup ended ${u==="ready"?"Ready":"blocked (Needs input)"}.`):di(`Testbot V3: attempt ended; the run's outcome in Skyramp is ${c.outcome??"not final yet"}.`)}var GZ=require("child_process"),is=se(require("fs")),D_=se(require("path")),N_=require("string_decoder");var ACe="skyramp-testbot-state",mCe=/^\$\([^)]*\)$/;function yCe(e){for(let[t,n]of Object.entries(e))n!==void 0&&mCe.test(n)&&delete e[t]}function ECe(e){let t={},n=is.existsSync(e)?is.readFileSync(e,"utf-8"):"",i=/^([^\r\n<]+)<<(\S+)\r?\n([\s\S]*?)\r?\n\2\r?$/gm;for(let r=i.exec(n);r;r=i.exec(n))t[r[1]]=r[3];return t}function zZ(e,t={}){let n=t.env??process.env;if(!Wo(n))return!1;yCe(n),ZY(n);let i=n.AGENT_TEMPDIRECTORY||n.RUNNER_TEMP;if(i){n.RUNNER_TEMP??=i;let o=D_.join(i,ACe);if(e==="main")is.writeFileSync(o,"",{mode:384});else for(let[a,c]of Object.entries(ECe(o)))n[`STATE_${a}`]=c;n.GITHUB_STATE=o;for(let[a,c]of[["GITHUB_OUTPUT","output"],["GITHUB_ENV","env"],["GITHUB_PATH","path"],["GITHUB_STEP_SUMMARY",`summary-${e}.md`]])n[a]=D_.join(i,`skyramp-testbot-${c}`),is.writeFileSync(n[a],"",{mode:384})}let r=t.stdout??n===process.env;r&&vCe(n,t.write);let s=n.GITHUB_STEP_SUMMARY;if(r&&s){let o=t.write??(a=>h0(a.replace(/\n$/,"")));process.once("exit",()=>{is.existsSync(s)&&is.statSync(s).size>0&&o(`${ob("task.uploadsummary",{},s)}
237
237
  `)})}return!0}function vCe(e,t){let n=process.stdout.write.bind(process.stdout),i=o=>e[Uh]==="1"?f0(o,e):void n(o.command!==void 0?`${o.command}
238
238
  `:o.text??""),r=t??(o=>i({command:o.replace(/\n$/,"")})),s=t??(o=>i({text:o}));process.stdout.write=((o,...a)=>{let c=typeof o=="string"?o:Buffer.from(o).toString("utf-8"),u="";for(let p of c.split(/(?<=\n)/)){let h=p.startsWith("::")?GY(p):void 0;if(!h){u+=p;continue}u&&s(u),u="";for(let g of h)r(`${g}
239
239
  `)}return u&&s(u),a.find(p=>typeof p=="function")?.(),!0})}var bCe=64*1024;function __(e){let t=new N_.StringDecoder("utf8"),n="",i=r=>e(sb(r));return{push(r){n+=typeof r=="string"?r:t.write(r);let s=n.lastIndexOf(`
@@ -214,7 +214,7 @@ ${Hu}: ${t}`:i;e(["log","-1","--format=%(trailers:key=Signed-off-by,valueonly)"]
214
214
  ${n}`}:{prFailure:"unknown",prDetail:t}}o(Sme,"thrownFailure");async function kme(e,t,n,i,r,s){let a=i.slug,c=i.path,u=Le(e,"finalize.json"),l=sH(e.inputs.requirementItems),p=qq(c),f=Le(e,"write.json"),g=f?.commit?.message||Le(e,"generate-unit.json")?.commitMessage,h=i.working,m=o(yt=>yt.split(`
215
215
  `)[0],"subjectOf"),E=o(yt=>lE(Kq(v0(yt)),l),"publicText"),I=o((yt,Kt)=>h&&!!Kt&&E(yt).trim()===E(Kt).trim(),"authored"),v=o((yt,Kt,cr)=>{let ct=E(yt);return cr&&Wq(ct,Kt)?ct:Zq(ct,Kt,r)},"conform"),b=[u?.commit?.message,n.commitMessage].find(yt=>yt&&E(yt).trim())||"Skyramp Testbot: add tests",R=v(b,{commitlint:p.commitlint},I(b,g)),$=Uq(e.outputsDir)??n,C=h?u?.pr?.title||n.prTitle||f?.commit?.prTitle:void 0,D=C||b,B=h?$.prTitle:void 0,K=m(E(D))===m(E(b)),ae=(!h||!n.prTitle)&&K?$.commitMessage:void 0,Z=B||ae||D,Ee=f?.commit?.prTitle||(g?m(g):void 0),De=I(D,Ee),Ve=p.prTitle?{prTitle:p.prTitle}:De&&C&&!K?{}:{commitlint:p.commitlint},xe=m(v(Z,Ve,De)),W={name:Ns,email:ra},M=!!p.signOff;if(!M&&t?.listCommitChecks){let yt=s?.headSha??Zt(c,["rev-parse","HEAD"]);try{M=(await t.listCommitChecks({repository:a,revision:yt}))?.records.some(cr=>cr.name.trim().toLowerCase()==="dco"&&cr.headSha===yt&&(!cr.repository||cr.repository.toLowerCase()===a.toLowerCase()))??!1}catch{console.warn(`[deliver] could not read commit checks for ${a}`)}}let qe=e.inputs.deliverRemote||"origin",We=aH(c,dH),cn=aH(c,pH);if(We&&!cn)throw new Error(`${a}: the checkout records a merged base but not what it merged`);let kt=We?S0(void 0,void 0,c):s?s.headBranch||S0(e.inputs.headBranch,e.inputs.baseBranch,c):S0(void 0,void 0,c),jn=e.inputs.pullRequests;s?.prNumber!=null&&!jn?.some(yt=>yt.repository.toLowerCase()===a.toLowerCase())&&(jn=[...jn??[],{repository:a,number:String(s.prNumber)}]);let Br=jn?.some(yt=>yt.repository.toLowerCase()===a.toLowerCase())?void 0:e.inputs.deliveryOrigin,Hr=We||!Br?cn:void 0,rs=e.inputs.scheduledDelivery,Ut=rs?(0,Bf.createHash)("sha256").update(JSON.stringify([rs,a.toLowerCase(),kt])).digest("hex"):Hr?hme(a,kt,Hr):gme(jn,a,kt,Br),Yr=Ame(kt,e.inputs.deliverBranch)+(rs?`-scheduled-${Ut}`:Hr?`-merge-${Ut}`:Br?`-source-${Br.number}-${Ut}`:"");return{texts:l,shown:$,title:xe,unsigned:R,bot:W,signOff:M,remote:qe,base:kt,owner:Ut,testsBranch:Yr,origin:Br,mergedBase:We}}o(kme,"planCommit");function Bme(e,t,n,i,r){let s=Zt(e,["interpret-trailers","--trailer",`${cE}: ${t.owner}`,"--trailer",`${Hu}: ${n}`,"--trailer",`${b0}: ${i}`,...r?["--trailer",`${C0}: ${r}`]:[]],`${t.unsigned}
216
216
  `);return t.signOff?aE(s,t.bot):s}o(Bme,"trailedMessage");async function Rme(e,t,n,i,r,s){let a=fq(i.path,e.runDir),c=process.env.PATH;a.dir&&(process.env.PATH=Aq(a).PATH);try{return await Qme(e,t,n,i,r,s)}finally{a.dir&&(process.env.PATH=c),a.cleanup()}}o(Rme,"deliverOne");async function Qme(e,t,n,i,r,s){let a=i.slug,c,u=!1,l;try{let p=i.path,f=await kme(e,t,n,i,r,s),{texts:g,shown:h,title:m,bot:E,remote:I,base:v,owner:b,testsBranch:R,origin:$,mergedBase:C}=f,D=v0(Fq(Pq(yme(h,e,i),{audience:"testbot-pr",runUrl:e.inputs.skyrampRunUrl,requestedBy:e.inputs.requestedBy,sourcePullRequest:$&&`${$.repository.namespace}/${$.repository.name}#${$.number}`}),e.inputs.skyrampRunUrl))+`
217
- `,B=s?"pr-body.md":`pr-body-${lH(a)}.md`,K=oo.join(e.outputsDir,B);Jr.writeFileSync(K,D);let ae=Zt(p,["rev-parse","HEAD"]),Z=C??ae;Zt(p,["checkout","-B",R]),c=R,Zt(p,["reset"]);for(let M of r)mme(oo.join(p,M),g);let Ee=[];for(let M of r)try{Zt(p,["--literal-pathspecs","add","--",M])}catch{Ee.push(M)}try{Zt(p,["diff","--cached","--quiet"])}catch{try{let M=Bme(p,f,ae,Z,e.inputs.skyrampRunUrl);Zt(p,["-c",`user.name=${E.name}`,"-c",`user.email=${E.email}`,"commit","-m",M])}catch(M){throw new dE(M)}u=!0}l=Zt(p,["rev-parse","HEAD"]);let De,Ve=C??s?.headSha;if(u&&Ve&&Ve!==ae){let M=!1;try{Zt(p,["checkout","-q","-B",c,Ve]),M=!0,Zt(p,["-c",`user.name=${E.name}`,"-c",`user.email=${E.email}`,"cherry-pick","--keep-redundant-commits",l]),M=!1,Xq(qe=>Zt(p,qe),Ve),l=Zt(p,["rev-parse","HEAD"])}catch(qe){try{Zt(p,["cherry-pick","--abort"])}catch{}Zt(p,["checkout","-q","-B",c,l]);let We=Ad(Uo(qe),1/0);if(C&&!M)throw qe;if(C)return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:I,base:v,committed:u,commitSha:l,pushed:!1,prAction:"skipped",prTitle:m,unstaged:Ee,reason:`the tests do not apply to ${v} at ${C.slice(0,12)} without the merged revisions (${We}), so no tests PR was opened`}};De=`tests committed on the checkout's merge commit (re-cut onto ${Ve.slice(0,12)} failed: ${We})`}}let xe=s?{}:{repositoryPath:p,repoSlug:a,devPr:null};if(!u){let M=await t.markTestsPrUnchanged({branch:c,...xe});return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:I,base:v,committed:!1,commitSha:l,pushed:!1,prAction:M.action==="unchanged"?"unchanged":"skipped",prUrl:M.url,prTitle:m,unstaged:Ee,reason:M.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:p,...xe,remote:I,branch:c,base:v,commitSha:l,title:m,bodyFile:K,mode:e.inputs.deliverMode,deliveryOwner:b,...e.inputs.firstQualification?{firstQualification:!0}:{},runUrl:e.inputs.skyrampRunUrl,signal:e.signal,deadlineMs:e.deadlineMs});return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:I,base:W.base,requestedBase:v,committed:u,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:m,...W.failure?{prFailure:W.failure,prDetail:W.detail}:{},...De?{cutNote:De}:{},...W.action==="skipped"&&W.detail?{reason:W.detail}:{},unstaged:Ee}}}catch(p){return{thrown:!0,record:{schemaVersion:1,repository:a,branch:c,committed:u,commitSha:l,pushed:!1,prAction:"failed",...Sme(p),unstaged:[]}}}}o(Qme,"deliverRepository");var LYe={name:"deliver",timeoutMinutes:5,execute:vme,validateInput:o(e=>{let t=a0(e);return t?{ok:!1,reasons:[t]}:pme(e)},"validateInput"),requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var xme=10*6e4;function $me(e,t){return e.getTime()-t.getTime()-xme}o($me,"remainingBudgetMs");var fH="This attempt revoked its scoped GitHub credentials; it mints no more.",Tme=10*6e4;var Dme=o(e=>!!e&&Object.keys(e).length===1&&e.contents==="read","onlyReads"),_me=3e4,Nme=3,AH=30,qr=class extends Error{constructor(n,i,r,s){super(n);this.status=i;this.code=r;this.path=s}status;code;path;static{o(this,"AppRefusal")}},ki=class extends Error{static{o(this,"AppUnreachable")}},Yu=class extends ki{static{o(this,"AppNotReady")}},k0=class extends Yu{static{o(this,"RunnerProviderNotReady")}};function B0(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(B0,"appOrigin");function hH(e,t){if(!qc.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}o(hH,"routeId");function mH(e,t,n,i){throw t<500&&t!==429?new qr(e,t,n,i):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new k0(e):t===503&&n==="RUN_NOT_READY"?new Yu(e):new ki(e)}o(mH,"refusedOrUnreachable");async function yH(e,t,n,i,r,s=1/0){let a=B0(e.origin),c=`The time limit for ${t} ${n} was reached`,u,l=0;for(let p=1;p<=Nme||u instanceof Yu;p+=1){if(u instanceof Yu){if(l===AH)throw u;l+=1,p-=1,e.log?.(`${u.message}; trying again (${l} of ${AH}).`),await new Promise(f=>setTimeout(f,Math.max(0,Math.min(e.readyWaitMs??1e4,s-Date.now()))))}else p>1&&await new Promise(f=>setTimeout(f,Math.max(0,Math.min((e.retryDelayMs??2e3)*(p-1),s-Date.now()))));if(Date.now()>=s)throw new ki(c);try{let f,g=await(Number.isFinite(s)?Promise.race([e.idToken(a),new Promise((m,E)=>{f=setTimeout(()=>E(new ki(c)),Math.max(1,s-Date.now()))})]).finally(()=>{f&&clearTimeout(f)}):e.idToken(a));if(Date.now()>=s)throw new ki(c);let h=await(e.fetch??fetch)(new URL(n,a).toString(),{...i(g),redirect:"error",signal:AbortSignal.timeout(Math.max(1,Math.min(_me,s-Date.now())))}).catch(m=>{throw new ki(m instanceof Error?m.message:String(m),{cause:m})});return await r(h)}catch(f){if(f instanceof qr||Date.now()>=s)throw f;u=f}}throw u}o(yH,"callWithRetries");function EH(e,t,n,i,r){let s=i.headers.get("cf-ray");e.log?.(`Testbot V3: ${t} ${n} answered ${i.status}${s?`, cf-ray ${s}`:""}: ${r.replace(/\s+/g," ").slice(0,200)}`)}o(EH,"logRefusal");function pE(e,t,n,i,r){let s=t==="GET"?void 0:JSON.stringify(i),a=t==="PUT"&&/^\/api\/v1\/runner\/attempts\/[^/]+\/report$/.test(n)&&s!==void 0&&Buffer.byteLength(s,"utf8")>hh;if(a&&Buffer.byteLength(s,"utf8")>qM)throw new Error("The report exceeds the app's 16 MiB expanded report limit");let c=a?new Uint8Array((0,gH.gzipSync)(s)):s;if(a&&c.length>hh)throw new Error("The compressed report exceeds the app's 1 MiB report upload limit");return yH(e,t,n,o(l=>({method:t,headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json",Accept:"application/json",...a?{"Content-Encoding":"gzip"}:{}},body:c}),"request"),async l=>{let p=await l.text().catch(()=>""),f={};try{f=JSON.parse(p)}catch{}if(l.ok)return f.data;EH(e,t,n,l,p);let g=f.error?.fields,h=typeof g?.path=="string"&&typeof g.reason=="string"?` at ${g.path}: ${g.reason}`:"",m=`The Skyramp app refused ${t} ${n}: ${l.status} ${f.error?.code??"no error code"}${h}`;return mH(m,l.status,f.error?.code,typeof g?.path=="string"?g.path:void 0)},r)}o(pE,"callApp");function Pme(e,t,n){return yH(e,"GET",t,o(r=>({method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/octet-stream"}}),"request"),async r=>{if(!r.ok)return EH(e,"GET",t,r,await r.text().catch(()=>"")),mH(`The Skyramp app refused GET ${t}: ${r.status}`,r.status);let s=Buffer.from(await r.arrayBuffer());if(s.length>n)throw new qr(`The Skyramp app answered GET ${t} with more than ${n} bytes`,r.status);return s})}o(Pme,"callAppBytes");var Rf=class{constructor(t,n,i,r,s,a,c,u,l,p=[],f=[],g){this.attemptId=t;this.attemptNumber=n;this.deadlineAt=i;this.manifest=r;this.deps=s;this.license=a;this.requestedBy=c;this.writeAllowed=u;this.claudeCodeVersion=l;this.deployedPins=p;this.statedPins=f;this.runSettings=g}attemptId;attemptNumber;deadlineAt;manifest;deps;license;requestedBy;writeAllowed;claudeCodeVersion;deployedPins;statedPins;runSettings;static{o(this,"V3Attempt")}budgetMs(t){return $me(this.deadlineAt,t)}get skyrampRunUrl(){return jM(B0(this.deps.origin),this.manifest.runId)}log(t){this.deps.log?.(t)}send(t,n,i,r){return pE(this.deps,t,n,i,r)}readBytes(t,n){return Pme(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(fH);let n=(this.deps.now??(()=>new Date))().getTime(),i=this.credentials[t],r=i&&await i.catch(()=>{});if(this.credentials[t]!==i)return(await this.credentials[t]).token;if(r&&r.expiresAt-n>=Tme)return r.token;if(this.revocation)throw new Error(fH);let s=t==="read",a=s?{schemaVersion:1,access:t}:{schemaVersion:1},c=s?"read-only":"scoped",u=this.send("POST",`/api/v1/runner/attempts/${this.attemptId}/credentials`,a).then(l=>{let p={...l,token:l.token??this.jobToken()};if(this.issuedTokens.push(p.token),this.deps.mask?.(p.token),p.anthropicApiKey&&this.deps.mask?.(p.anthropicApiKey),s&&l.token&&!Dme(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)}`);!s&&!r&&p.anthropicApiKey&&(this.modelKey=p.anthropicApiKey),this.deps.onTokenGranted?.(t);let f=r?"Renewed":"Received";return l.token&&this.deps.log?.(`${f} ${c} GitHub credentials; they expire at ${p.expiresAt}.`),{token:p.token,expiresAt:l.token?new Date(p.expiresAt).getTime():Number.POSITIVE_INFINITY}},l=>{if(this.deps.onTokenRefused?.(l,t),!(l instanceof qr)||l.code!=="CREDENTIALS_UNAVAILABLE")throw l;let p=o(h=>[...new Set(h.map(m=>m.namespace))].join(", "),"unique"),f=this.manifest.sources.map(h=>h.repository);if(new Set(f.map(h=>h.providerAccountId)).size>1)throw new qr(`${l.message}. The run's repositories are on more than one GitHub account (${p(f)}), which Skyramp does not support yet.`,l.status,l.code);let g=p([...f,this.manifest.execution.repository]);throw new qr(`${l.message}. Check the Skyramp GitHub App installation on ${g}: it must be installed and not suspended, have access to these repositories, and have accepted the App's current permissions. Each account must also be connected to your Skyramp organization.`,l.status,l.code)});return this.credentials[t]=u,(await u).token}jobToken(){if(this.deps.sourceToken)return this.deps.sourceToken;throw new Error("The app answered the credentials request without a token, and the job gave Testbot none of its own: on Azure Pipelines, set SYSTEM_ACCESSTOKEN to $(System.AccessToken) in the Testbot step's env.")}sourceFetch(t){return t.fetch??this.deps.fetch??fetch}revokeTokens(t={}){let n=t.host??$$();return this.revocation??=n.revokeToken?this.revokeIssued(i=>n.revokeToken(i,this.sourceFetch(t))):Promise.resolve([]),this.revocation}async revokeIssued(t){let n=[...this.issuedTokens],i=Promise.all(n.map(a=>this.revokeOne(a,t)));await Promise.all(Object.values(this.credentials).map(a=>a.catch(()=>{})));let r=this.issuedTokens.filter(a=>!n.includes(a));return[...await i,...await Promise.all(r.map(a=>this.revokeOne(a,t)))].filter(a=>a!==void 0)}async revokeOne(t,n){try{await n(t);return}catch(i){return`token ${this.issuedTokens.indexOf(t)+1} of ${this.issuedTokens.length}: ${i instanceof Error?i.message:String(i)}`}}};async function IH(e,t,n){hH(e,"run id"),B0(n.origin);let i=PC(e,t),r=`/api/v1/runner/runs/${e}/attempts`,s;try{s=await pE(n,"POST",r,i)}catch(l){if(!(l instanceof qr&&l.status===400&&l.path==="$.statedPins"))throw l;i=PC(e,t,{statedPins:!1}),s=await pE(n,"POST",r,i)}let a=Aj(s);if(a.manifest.runId!==e)throw new Error(`The app answered the handshake of run ${e} with the manifest of another run (${a.manifest.runId})`);let c=a.manifest.sources.find(l=>l.repository.provider!==i.execution.provider);if(c)throw new Error(`The manifest of run ${e} names ${c.repository.namespace}/${c.repository.name} on ${c.repository.provider}, but this job runs on ${i.execution.provider}`);Ume(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 Rf(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)}o(IH,"startV3Attempt");function Ume(e,t){if(t.length===0)return;if(!ej(e))throw new Error(`The app pinned an attempt of a ${e.trigger.kind} run; only a scheduled run or unchosen manual run's retry is pinned to an earlier attempt's read`);let n=new Set(e.sources.map(r=>mi(r.repository))),i=new Set;for(let r of t){let s=mi(r.repository);if(!n.has(s))throw new Error(`The app pinned the attempt to repository ${r.repository.providerRepositoryId}, which is not a source of the run`);if(i.has(s))throw new Error(`The app pinned repository ${r.repository.providerRepositoryId} twice`);i.add(s)}}o(Ume,"checkAttemptPins");async function R0(e,t){return lj.parse(await e.send("POST",`/api/v1/runner/attempts/${e.attemptId}/heartbeat`,{schemaVersion:1},t))}o(R0,"heartbeatV3Attempt");async function vH(e,t=()=>new Date,n){if(e.closure)return e.closure;let i=await R0(e,n).then(r=>dj(r,t())).catch(()=>null);return i&&(e.closure=i),i}o(vH,"closedV3Attempt");var TWe=10*6e4;var DWe=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var _We=d.object({tests:d.object({placements:d.array(d.unknown()).optional()}).passthrough().optional()}).passthrough(),NWe=d.object({repository:$C,testType:d.string(),directory:d.string()}).passthrough();var PWe=d.object({report:d.object({language:d.string()}).passthrough()}).passthrough();var UWe=d.object({environment:d.object({components:d.array(d.unknown()).optional(),dependencies:d.array(d.unknown()).optional()}).passthrough()}).passthrough(),FWe=d.object({environment:d.object({offLimits:d.unknown().optional()}).passthrough()}).passthrough();var OWe=d.object({environment:d.object({allowedEgress:d.unknown().optional()}).passthrough()}).passthrough();var LWe=d.object({name:d.string().min(1),provision:d.literal("existing"),url:d.string().min(1),repository:$C.optional(),revisionUrl:d.string().min(1).optional()}).passthrough(),MWe=d.object({name:d.string().min(1),url:d.string().nullable(),versionUrl:d.string().nullable(),notes:d.string().nullable()}).passthrough();var jWe=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);function bH(e){let t=o(n=>e.testResults.filter(i=>i.status===n).length,"count");return{passed:t("Pass"),failed:t("Fail"),skipped:t("Skipped")}}o(bH,"statusCounts");function Fme(e){let{passed:t,failed:n,skipped:i}=bH(e);return t+n===0?{sufficiency:"insufficient",rationale:i>0?`Every test was skipped (${i}), so nothing was validated.`:"No test ran, so nothing was validated.",gaps:["No test ran against the frozen sources."],acceptedEvidence:[],actionRequired:[]}:{sufficiency:"sufficient",rationale:`${t+n} tests ran against the frozen sources: ${t} passed, ${n} failed${i?`, ${i} skipped`:""}.`,gaps:[],acceptedEvidence:[],actionRequired:[]}}o(Fme,"executedTestsValidation");function Ome(e,t){let n=e.map(c=>({result:c,repository:c.repository??t,path:c.fileName||c.testType})),i=new Map;for(let c of n){let u=`${c.repository}:${c.result.testType}:${c.path}`;i.set(u,(i.get(u)??0)+1)}let r=n.map(({result:c,repository:u,path:l})=>{let p=(i.get(`${u}:${c.testType}:${l}`)??0)>1;return c.resultId??DC(u,c.testType,l,p&&c.endpoint||void 0)}),s=new Map;for(let c of r)s.set(c,(s.get(c)??0)+1);let a=new Set(r.filter(c=>s.get(c)===1));return n.map(({result:c,repository:u},l)=>{let p=r[l],f=p;if(s.get(p)>1&&a.has(p))for(let g=2;a.has(f)||f===p;g+=1)f=p.includes("#")?`${p}.${g}`:`${p}#${g}`;return a.add(f),{...c,repository:u,resultId:f}})}o(Ome,"withResultIds");function Lme({notTranslated:e,...t},n){let i=Ome(t.testResults,n);return{...t,testResults:i,...Mme(t,i,n),validation:Vme(zme(t,jme(t,t.validation??Fme(t)))),traceVersion:1}}o(Lme,"v3Report");function Mme(e,t,n){if(!e.testExecutionContexts)return{};let i=new Set,r=o(c=>{let u=c;for(let l=2;i.has(u);l+=1)u=`${c}#${l}`;return i.add(u),u},"unique"),s=[],a=new Map;for(let{repository:c,...u}of e.testExecutionContexts){let l=u.status==="not_run"?[]:t.filter(p=>p.fileName===u.test&&p.repository===(c?.trim()||n));l.length||s.push(u);for(let{resultId:p}of l){let f=a.get(p),g=f!==void 0&&s[f].cleanup.status==="failed"?s[f].cleanup:u.cleanup,h={...u,cleanup:g,test:p,resultId:p};f===void 0?a.set(p,s.push(h)-1):s[f]=h}}for(let c of s)c.resultId&&i.add(c.resultId);return{testExecutionContexts:s.map(c=>c.resultId?c:{...c,test:r(c.test.slice(0,512))}).slice(0,5e3)}}o(Mme,"linkedContexts");function jme(e,t){let{passed:n,failed:i}=bH(e);return t.sufficiency!=="sufficient"||n+i>0||t.acceptedEvidence.length>0?t:{...t,sufficiency:"insufficient",gaps:["No test ran and no existing evidence was accepted, so nothing was validated."]}}o(jme,"withEvidence");var Gme={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};function Vme(e){return{...e,gaps:Jp(e.gaps)}}o(Vme,"boundedGaps");function zme(e,t){if(t.sufficiency==="sufficient")return t;let n=(e.caveats??[]).map(r=>Gme[r.kind]).filter(r=>r!==void 0),i=[...new Set(n)].filter(r=>!t.actionRequired.includes(r));return i.length?{...t,actionRequired:[...i,...t.actionRequired]}:t}o(zme,"withModelProviderFailure");function Jme(e,t,n){let{language:i,report:r}=t;if(i==="en")return;let s={language:i,businessCaseAnalysis:r.businessCaseAnalysis},a=o((m,E,I)=>Array.isArray(m)&&Array.isArray(E)&&m.length===E.length?m.map(v=>({[I]:v[I]})):void 0,"rows"),c=e.validation;r.validation&&c&&c.rationale===n.validation.rationale&&JSON.stringify(Jp(c.gaps))===JSON.stringify(n.validation.gaps)&&Jp(r.validation.gaps).length===n.validation.gaps.length&&(s.validation={rationale:r.validation.rationale,gaps:Jp(r.validation.gaps)});let u=new Set((n.changes??[]).map(m=>m.id)),l=(r.changes??[]).filter(m=>u.has(m.id)).map(({id:m,text:E})=>({id:m,text:E}));l.length&&(s.changes=l);let p=a(r.issuesFound,n.issuesFound,"description");p&&(s.issuesFound=p);let f=a(r.newTestsCreated,n.newTestsCreated,"description");f&&(s.newTestsCreated=f);let g=a(r.testResults,n.testResults,"details");g&&(s.testResults=g);let h=a(r.caveats,n.caveats,"text");return h&&(s.caveats=h),s}o(Jme,"v3Display");async function CH(e,t){let n=GL([...e.issuedTokens,...t.secrets??[]]),i={...Lme(t.report,t.workingSlug),...t.notTranslated?{notTranslated:t.notTranslated}:{}},r=t.translated&&Jme(t.report,t.translated,i),s=o(c=>gj({manifest:e.manifest,attemptNumber:e.attemptNumber,checkedOut:t.sources.map(u=>({repository:u.repository,revision:u.revision})),firstQualification:t.firstQualification,generatedTests:_c(t.delivery,n),producer:t.producer,report:_c(c&&r?{...i,display:r}:i,n),githubWrites:t.githubWrites}),"build"),a=s(!0);r&&Buffer.byteLength(JSON.stringify(a),"utf8")>hh&&(a=s(!1)),await e.send("PUT",`/api/v1/runner/attempts/${e.attemptId}/report`,a)}o(CH,"uploadV3Report");async function Q0(e,t,n){if(!d.string().uuid().safeParse(t).success)return{refusal:"no_environment"};let i;try{i=uj.parse(await e.send("GET",PM.persistentDataPolicy.replace(":attemptId",e.attemptId),void 0))}catch{return{refusal:"unavailable"}}try{if(!i.environmentAddress||new URL(i.environmentAddress).href!==new URL(n).href)return{refusal:"changed"}}catch{return{refusal:"changed"}}if(i.environmentId!==t)return{refusal:"changed"};let r=i.persistentDataPolicy;return r?r.environmentId===t?{policy:r}:{refusal:"changed"}:{refusal:"denied"}}o(Q0,"fetchV3PersistentDataPolicy");async function wH(e,t,n){let{environmentId:i,environmentAddress:r}=t;if(!i||!r)return{allowed:!1,refusal:"no_environment"};let s=t.persistentDataPolicy;if(!s?.allowed||s.environmentId!==i)return{allowed:!1,refusal:"no_recorded_grant"};let a=await Q0(e,i,r);return"refusal"in a?{allowed:!1,refusal:a.refusal}:a.policy.allowed?a.policy.revision!==s.revision?{allowed:!1,refusal:"changed"}:yM(t,a.policy,n)?{allowed:!0}:{allowed:!1,refusal:"out_of_scope"}:{allowed:!1,refusal:"denied"}}o(wH,"currentV3PersistenceDecision");async function SH(e,t){return hH(e.attemptId,"attempt id"),pE(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,hj({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(SH,"endV3Attempt");0&&(module.exports={AppRefusal,AppUnreachable,AttemptEndReason,DeliveryStatus,GitHubWriteKind,NoReportCause,SourceProvider,V3Attempt,ValidationSufficiency,closedV3Attempt,currentV3PersistenceDecision,endV3Attempt,fetchV3PersistentDataPolicy,heartbeatV3Attempt,startV3Attempt,uploadV3Report});
217
+ `,B=s?"pr-body.md":`pr-body-${lH(a)}.md`,K=oo.join(e.outputsDir,B);Jr.writeFileSync(K,D);let ae=Zt(p,["rev-parse","HEAD"]),Z=C??ae;Zt(p,["checkout","-B",R]),c=R,Zt(p,["reset"]);for(let M of r)mme(oo.join(p,M),g);let Ee=[];for(let M of r)try{Zt(p,["--literal-pathspecs","add","--",M])}catch{Ee.push(M)}try{Zt(p,["diff","--cached","--quiet"])}catch{try{let M=Bme(p,f,ae,Z,e.inputs.skyrampRunUrl);Zt(p,["-c",`user.name=${E.name}`,"-c",`user.email=${E.email}`,"commit","-m",M])}catch(M){throw new dE(M)}u=!0}l=Zt(p,["rev-parse","HEAD"]);let De,Ve=C??s?.headSha;if(u&&Ve&&Ve!==ae){let M=!1;try{Zt(p,["checkout","-q","-B",c,Ve]),M=!0,Zt(p,["-c",`user.name=${E.name}`,"-c",`user.email=${E.email}`,"cherry-pick","--keep-redundant-commits",l]),M=!1,Xq(qe=>Zt(p,qe),Ve),l=Zt(p,["rev-parse","HEAD"])}catch(qe){try{Zt(p,["cherry-pick","--abort"])}catch{}Zt(p,["checkout","-q","-B",c,l]);let We=Ad(Uo(qe),1/0);if(C&&!M)throw qe;if(C)return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:I,base:v,committed:u,commitSha:l,pushed:!1,prAction:"skipped",prTitle:m,unstaged:Ee,reason:`the tests do not apply to ${v} at ${C.slice(0,12)} without the merged revisions (${We}), so no tests PR was opened`}};De=`tests committed on the checkout's merge commit (re-cut onto ${Ve.slice(0,12)} failed: ${We})`}}let xe=s?{}:{repositoryPath:p,repoSlug:a,devPr:null};if(!u){let M=await t.markTestsPrUnchanged({branch:c,...xe});return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:I,base:v,committed:!1,commitSha:l,pushed:!1,prAction:M.action==="unchanged"?"unchanged":"skipped",prUrl:M.url,prTitle:m,unstaged:Ee,reason:M.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:p,...xe,remote:I,branch:c,base:v,commitSha:l,title:m,bodyFile:K,mode:e.inputs.deliverMode,deliveryOwner:b,...e.inputs.firstQualification?{firstQualification:!0}:{},runUrl:e.inputs.skyrampRunUrl,signal:e.signal,deadlineMs:e.deadlineMs});return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:I,base:W.base,requestedBase:v,committed:u,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:m,...W.failure?{prFailure:W.failure,prDetail:W.detail}:{},...De?{cutNote:De}:{},...W.action==="skipped"&&W.detail?{reason:W.detail}:{},unstaged:Ee}}}catch(p){return{thrown:!0,record:{schemaVersion:1,repository:a,branch:c,committed:u,commitSha:l,pushed:!1,prAction:"failed",...Sme(p),unstaged:[]}}}}o(Qme,"deliverRepository");var LYe={name:"deliver",timeoutMinutes:5,execute:vme,validateInput:o(e=>{let t=a0(e);return t?{ok:!1,reasons:[t]}:pme(e)},"validateInput"),requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var xme=10*6e4;function $me(e,t){return e.getTime()-t.getTime()-xme}o($me,"remainingBudgetMs");var fH="This attempt revoked its scoped GitHub credentials; it mints no more.";var Tme=10*6e4;var Dme=o(e=>!!e&&Object.keys(e).length===1&&e.contents==="read","onlyReads"),_me=3e4,Nme=3,AH=30,qr=class extends Error{constructor(n,i,r,s){super(n);this.status=i;this.code=r;this.path=s}status;code;path;static{o(this,"AppRefusal")}},ki=class extends Error{static{o(this,"AppUnreachable")}},Yu=class extends ki{static{o(this,"AppNotReady")}},k0=class extends Yu{static{o(this,"RunnerProviderNotReady")}};function B0(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(B0,"appOrigin");function hH(e,t){if(!qc.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}o(hH,"routeId");function mH(e,t,n,i){throw t<500&&t!==429?new qr(e,t,n,i):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new k0(e):t===503&&n==="RUN_NOT_READY"?new Yu(e):new ki(e)}o(mH,"refusedOrUnreachable");async function yH(e,t,n,i,r,s=1/0){let a=B0(e.origin),c=`The time limit for ${t} ${n} was reached`,u,l=0;for(let p=1;p<=Nme||u instanceof Yu;p+=1){if(u instanceof Yu){if(l===AH)throw u;l+=1,p-=1,e.log?.(`${u.message}; trying again (${l} of ${AH}).`),await new Promise(f=>setTimeout(f,Math.max(0,Math.min(e.readyWaitMs??1e4,s-Date.now()))))}else p>1&&await new Promise(f=>setTimeout(f,Math.max(0,Math.min((e.retryDelayMs??2e3)*(p-1),s-Date.now()))));if(Date.now()>=s)throw new ki(c);try{let f,g=await(Number.isFinite(s)?Promise.race([e.idToken(a),new Promise((m,E)=>{f=setTimeout(()=>E(new ki(c)),Math.max(1,s-Date.now()))})]).finally(()=>{f&&clearTimeout(f)}):e.idToken(a));if(Date.now()>=s)throw new ki(c);let h=await(e.fetch??fetch)(new URL(n,a).toString(),{...i(g),redirect:"error",signal:AbortSignal.timeout(Math.max(1,Math.min(_me,s-Date.now())))}).catch(m=>{throw new ki(m instanceof Error?m.message:String(m),{cause:m})});return await r(h)}catch(f){if(f instanceof qr||Date.now()>=s)throw f;u=f}}throw u}o(yH,"callWithRetries");function EH(e,t,n,i,r){let s=i.headers.get("cf-ray");e.log?.(`Testbot V3: ${t} ${n} answered ${i.status}${s?`, cf-ray ${s}`:""}: ${r.replace(/\s+/g," ").slice(0,200)}`)}o(EH,"logRefusal");function pE(e,t,n,i,r){let s=t==="GET"?void 0:JSON.stringify(i),a=t==="PUT"&&/^\/api\/v1\/runner\/attempts\/[^/]+\/report$/.test(n)&&s!==void 0&&Buffer.byteLength(s,"utf8")>hh;if(a&&Buffer.byteLength(s,"utf8")>qM)throw new Error("The report exceeds the app's 16 MiB expanded report limit");let c=a?new Uint8Array((0,gH.gzipSync)(s)):s;if(a&&c.length>hh)throw new Error("The compressed report exceeds the app's 1 MiB report upload limit");return yH(e,t,n,o(l=>({method:t,headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json",Accept:"application/json",...a?{"Content-Encoding":"gzip"}:{}},body:c}),"request"),async l=>{let p=await l.text().catch(()=>""),f={};try{f=JSON.parse(p)}catch{}if(l.ok)return f.data;EH(e,t,n,l,p);let g=f.error?.fields,h=typeof g?.path=="string"&&typeof g.reason=="string"?` at ${g.path}: ${g.reason}`:"",m=`The Skyramp app refused ${t} ${n}: ${l.status} ${f.error?.code??"no error code"}${h}`;return mH(m,l.status,f.error?.code,typeof g?.path=="string"?g.path:void 0)},r)}o(pE,"callApp");function Pme(e,t,n){return yH(e,"GET",t,o(r=>({method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/octet-stream"}}),"request"),async r=>{if(!r.ok)return EH(e,"GET",t,r,await r.text().catch(()=>"")),mH(`The Skyramp app refused GET ${t}: ${r.status}`,r.status);let s=Buffer.from(await r.arrayBuffer());if(s.length>n)throw new qr(`The Skyramp app answered GET ${t} with more than ${n} bytes`,r.status);return s})}o(Pme,"callAppBytes");var Rf=class{constructor(t,n,i,r,s,a,c,u,l,p=[],f=[],g){this.attemptId=t;this.attemptNumber=n;this.deadlineAt=i;this.manifest=r;this.deps=s;this.license=a;this.requestedBy=c;this.writeAllowed=u;this.claudeCodeVersion=l;this.deployedPins=p;this.statedPins=f;this.runSettings=g}attemptId;attemptNumber;deadlineAt;manifest;deps;license;requestedBy;writeAllowed;claudeCodeVersion;deployedPins;statedPins;runSettings;static{o(this,"V3Attempt")}budgetMs(t){return $me(this.deadlineAt,t)}get skyrampRunUrl(){return jM(B0(this.deps.origin),this.manifest.runId)}log(t){this.deps.log?.(t)}send(t,n,i,r){return pE(this.deps,t,n,i,r)}readBytes(t,n){return Pme(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(fH);let n=(this.deps.now??(()=>new Date))().getTime(),i=this.credentials[t],r=i&&await i.catch(()=>{});if(this.credentials[t]!==i)return(await this.credentials[t]).token;if(r&&r.expiresAt-n>=Tme)return r.token;if(this.revocation)throw new Error(fH);let s=t==="read",a=s?{schemaVersion:1,access:t}:{schemaVersion:1},c=s?"read-only":"scoped",u=this.send("POST",`/api/v1/runner/attempts/${this.attemptId}/credentials`,a).then(l=>{let p={...l,token:l.token??this.jobToken()};if(this.issuedTokens.push(p.token),this.deps.mask?.(p.token),p.anthropicApiKey&&this.deps.mask?.(p.anthropicApiKey),s&&l.token&&!Dme(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)}`);!s&&!r&&p.anthropicApiKey&&(this.modelKey=p.anthropicApiKey),this.deps.onTokenGranted?.(t);let f=r?"Renewed":"Received";return l.token&&this.deps.log?.(`${f} ${c} GitHub credentials; they expire at ${p.expiresAt}.`),{token:p.token,expiresAt:l.token?new Date(p.expiresAt).getTime():Number.POSITIVE_INFINITY}},l=>{if(this.deps.onTokenRefused?.(l,t),!(l instanceof qr)||l.code!=="CREDENTIALS_UNAVAILABLE")throw l;let p=o(h=>[...new Set(h.map(m=>m.namespace))].join(", "),"unique"),f=this.manifest.sources.map(h=>h.repository);if(new Set(f.map(h=>h.providerAccountId)).size>1)throw new qr(`${l.message}. The run's repositories are on more than one GitHub account (${p(f)}), which Skyramp does not support yet.`,l.status,l.code);let g=p([...f,this.manifest.execution.repository]);throw new qr(`${l.message}. Check the Skyramp GitHub App installation on ${g}: it must be installed and not suspended, have access to these repositories, and have accepted the App's current permissions. Each account must also be connected to your Skyramp organization.`,l.status,l.code)});return this.credentials[t]=u,(await u).token}jobToken(){if(this.deps.sourceToken)return this.deps.sourceToken;throw new Error("The app answered the credentials request without a token, and the job gave Testbot none of its own: on Azure Pipelines, set SYSTEM_ACCESSTOKEN to $(System.AccessToken) in the Testbot step's env.")}sourceFetch(t){return t.fetch??this.deps.fetch??fetch}revokeTokens(t={}){let n=t.host??$$();return this.revocation??=n.revokeToken?this.revokeIssued(i=>n.revokeToken(i,this.sourceFetch(t))):Promise.resolve([]),this.revocation}async revokeIssued(t){let n=[...this.issuedTokens],i=Promise.all(n.map(a=>this.revokeOne(a,t)));await Promise.all(Object.values(this.credentials).map(a=>a.catch(()=>{})));let r=this.issuedTokens.filter(a=>!n.includes(a));return[...await i,...await Promise.all(r.map(a=>this.revokeOne(a,t)))].filter(a=>a!==void 0)}async revokeOne(t,n){try{await n(t);return}catch(i){return`token ${this.issuedTokens.indexOf(t)+1} of ${this.issuedTokens.length}: ${i instanceof Error?i.message:String(i)}`}}};async function IH(e,t,n){hH(e,"run id"),B0(n.origin);let i=PC(e,t),r=`/api/v1/runner/runs/${e}/attempts`,s;try{s=await pE(n,"POST",r,i)}catch(l){if(!(l instanceof qr&&l.status===400&&l.path==="$.statedPins"))throw l;i=PC(e,t,{statedPins:!1}),s=await pE(n,"POST",r,i)}let a=Aj(s);if(a.manifest.runId!==e)throw new Error(`The app answered the handshake of run ${e} with the manifest of another run (${a.manifest.runId})`);let c=a.manifest.sources.find(l=>l.repository.provider!==i.execution.provider);if(c)throw new Error(`The manifest of run ${e} names ${c.repository.namespace}/${c.repository.name} on ${c.repository.provider}, but this job runs on ${i.execution.provider}`);Ume(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 Rf(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)}o(IH,"startV3Attempt");function Ume(e,t){if(t.length===0)return;if(!ej(e))throw new Error(`The app pinned an attempt of a ${e.trigger.kind} run; only a scheduled run or unchosen manual run's retry is pinned to an earlier attempt's read`);let n=new Set(e.sources.map(r=>mi(r.repository))),i=new Set;for(let r of t){let s=mi(r.repository);if(!n.has(s))throw new Error(`The app pinned the attempt to repository ${r.repository.providerRepositoryId}, which is not a source of the run`);if(i.has(s))throw new Error(`The app pinned repository ${r.repository.providerRepositoryId} twice`);i.add(s)}}o(Ume,"checkAttemptPins");async function R0(e,t){return lj.parse(await e.send("POST",`/api/v1/runner/attempts/${e.attemptId}/heartbeat`,{schemaVersion:1},t))}o(R0,"heartbeatV3Attempt");async function vH(e,t=()=>new Date,n){if(e.closure)return e.closure;let i=await R0(e,n).then(r=>dj(r,t())).catch(()=>null);return i&&(e.closure=i),i}o(vH,"closedV3Attempt");var DWe=10*6e4;var _We=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var NWe=d.object({tests:d.object({placements:d.array(d.unknown()).optional()}).passthrough().optional()}).passthrough(),PWe=d.object({repository:$C,testType:d.string(),directory:d.string()}).passthrough();var UWe=d.object({report:d.object({language:d.string()}).passthrough()}).passthrough();var FWe=d.object({environment:d.object({components:d.array(d.unknown()).optional(),dependencies:d.array(d.unknown()).optional()}).passthrough()}).passthrough(),OWe=d.object({environment:d.object({offLimits:d.unknown().optional()}).passthrough()}).passthrough();var LWe=d.object({environment:d.object({allowedEgress:d.unknown().optional()}).passthrough()}).passthrough();var MWe=d.object({name:d.string().min(1),provision:d.literal("existing"),url:d.string().min(1),repository:$C.optional(),revisionUrl:d.string().min(1).optional()}).passthrough(),jWe=d.object({name:d.string().min(1),url:d.string().nullable(),versionUrl:d.string().nullable(),notes:d.string().nullable()}).passthrough();var GWe=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);function bH(e){let t=o(n=>e.testResults.filter(i=>i.status===n).length,"count");return{passed:t("Pass"),failed:t("Fail"),skipped:t("Skipped")}}o(bH,"statusCounts");function Fme(e){let{passed:t,failed:n,skipped:i}=bH(e);return t+n===0?{sufficiency:"insufficient",rationale:i>0?`Every test was skipped (${i}), so nothing was validated.`:"No test ran, so nothing was validated.",gaps:["No test ran against the frozen sources."],acceptedEvidence:[],actionRequired:[]}:{sufficiency:"sufficient",rationale:`${t+n} tests ran against the frozen sources: ${t} passed, ${n} failed${i?`, ${i} skipped`:""}.`,gaps:[],acceptedEvidence:[],actionRequired:[]}}o(Fme,"executedTestsValidation");function Ome(e,t){let n=e.map(c=>({result:c,repository:c.repository??t,path:c.fileName||c.testType})),i=new Map;for(let c of n){let u=`${c.repository}:${c.result.testType}:${c.path}`;i.set(u,(i.get(u)??0)+1)}let r=n.map(({result:c,repository:u,path:l})=>{let p=(i.get(`${u}:${c.testType}:${l}`)??0)>1;return c.resultId??DC(u,c.testType,l,p&&c.endpoint||void 0)}),s=new Map;for(let c of r)s.set(c,(s.get(c)??0)+1);let a=new Set(r.filter(c=>s.get(c)===1));return n.map(({result:c,repository:u},l)=>{let p=r[l],f=p;if(s.get(p)>1&&a.has(p))for(let g=2;a.has(f)||f===p;g+=1)f=p.includes("#")?`${p}.${g}`:`${p}#${g}`;return a.add(f),{...c,repository:u,resultId:f}})}o(Ome,"withResultIds");function Lme({notTranslated:e,...t},n){let i=Ome(t.testResults,n);return{...t,testResults:i,...Mme(t,i,n),validation:Vme(zme(t,jme(t,t.validation??Fme(t)))),traceVersion:1}}o(Lme,"v3Report");function Mme(e,t,n){if(!e.testExecutionContexts)return{};let i=new Set,r=o(c=>{let u=c;for(let l=2;i.has(u);l+=1)u=`${c}#${l}`;return i.add(u),u},"unique"),s=[],a=new Map;for(let{repository:c,...u}of e.testExecutionContexts){let l=u.status==="not_run"?[]:t.filter(p=>p.fileName===u.test&&p.repository===(c?.trim()||n));l.length||s.push(u);for(let{resultId:p}of l){let f=a.get(p),g=f!==void 0&&s[f].cleanup.status==="failed"?s[f].cleanup:u.cleanup,h={...u,cleanup:g,test:p,resultId:p};f===void 0?a.set(p,s.push(h)-1):s[f]=h}}for(let c of s)c.resultId&&i.add(c.resultId);return{testExecutionContexts:s.map(c=>c.resultId?c:{...c,test:r(c.test.slice(0,512))}).slice(0,5e3)}}o(Mme,"linkedContexts");function jme(e,t){let{passed:n,failed:i}=bH(e);return t.sufficiency!=="sufficient"||n+i>0||t.acceptedEvidence.length>0?t:{...t,sufficiency:"insufficient",gaps:["No test ran and no existing evidence was accepted, so nothing was validated."]}}o(jme,"withEvidence");var Gme={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};function Vme(e){return{...e,gaps:Jp(e.gaps)}}o(Vme,"boundedGaps");function zme(e,t){if(t.sufficiency==="sufficient")return t;let n=(e.caveats??[]).map(r=>Gme[r.kind]).filter(r=>r!==void 0),i=[...new Set(n)].filter(r=>!t.actionRequired.includes(r));return i.length?{...t,actionRequired:[...i,...t.actionRequired]}:t}o(zme,"withModelProviderFailure");function Jme(e,t,n){let{language:i,report:r}=t;if(i==="en")return;let s={language:i,businessCaseAnalysis:r.businessCaseAnalysis},a=o((m,E,I)=>Array.isArray(m)&&Array.isArray(E)&&m.length===E.length?m.map(v=>({[I]:v[I]})):void 0,"rows"),c=e.validation;r.validation&&c&&c.rationale===n.validation.rationale&&JSON.stringify(Jp(c.gaps))===JSON.stringify(n.validation.gaps)&&Jp(r.validation.gaps).length===n.validation.gaps.length&&(s.validation={rationale:r.validation.rationale,gaps:Jp(r.validation.gaps)});let u=new Set((n.changes??[]).map(m=>m.id)),l=(r.changes??[]).filter(m=>u.has(m.id)).map(({id:m,text:E})=>({id:m,text:E}));l.length&&(s.changes=l);let p=a(r.issuesFound,n.issuesFound,"description");p&&(s.issuesFound=p);let f=a(r.newTestsCreated,n.newTestsCreated,"description");f&&(s.newTestsCreated=f);let g=a(r.testResults,n.testResults,"details");g&&(s.testResults=g);let h=a(r.caveats,n.caveats,"text");return h&&(s.caveats=h),s}o(Jme,"v3Display");async function CH(e,t){let n=GL([...e.issuedTokens,...t.secrets??[]]),i={...Lme(t.report,t.workingSlug),...t.notTranslated?{notTranslated:t.notTranslated}:{}},r=t.translated&&Jme(t.report,t.translated,i),s=o(c=>gj({manifest:e.manifest,attemptNumber:e.attemptNumber,checkedOut:t.sources.map(u=>({repository:u.repository,revision:u.revision})),firstQualification:t.firstQualification,generatedTests:_c(t.delivery,n),producer:t.producer,report:_c(c&&r?{...i,display:r}:i,n),githubWrites:t.githubWrites}),"build"),a=s(!0);r&&Buffer.byteLength(JSON.stringify(a),"utf8")>hh&&(a=s(!1)),await e.send("PUT",`/api/v1/runner/attempts/${e.attemptId}/report`,a)}o(CH,"uploadV3Report");async function Q0(e,t,n){if(!d.string().uuid().safeParse(t).success)return{refusal:"no_environment"};let i;try{i=uj.parse(await e.send("GET",PM.persistentDataPolicy.replace(":attemptId",e.attemptId),void 0))}catch{return{refusal:"unavailable"}}try{if(!i.environmentAddress||new URL(i.environmentAddress).href!==new URL(n).href)return{refusal:"changed"}}catch{return{refusal:"changed"}}if(i.environmentId!==t)return{refusal:"changed"};let r=i.persistentDataPolicy;return r?r.environmentId===t?{policy:r}:{refusal:"changed"}:{refusal:"denied"}}o(Q0,"fetchV3PersistentDataPolicy");async function wH(e,t,n){let{environmentId:i,environmentAddress:r}=t;if(!i||!r)return{allowed:!1,refusal:"no_environment"};let s=t.persistentDataPolicy;if(!s?.allowed||s.environmentId!==i)return{allowed:!1,refusal:"no_recorded_grant"};let a=await Q0(e,i,r);return"refusal"in a?{allowed:!1,refusal:a.refusal}:a.policy.allowed?a.policy.revision!==s.revision?{allowed:!1,refusal:"changed"}:yM(t,a.policy,n)?{allowed:!0}:{allowed:!1,refusal:"out_of_scope"}:{allowed:!1,refusal:"denied"}}o(wH,"currentV3PersistenceDecision");async function SH(e,t){return hH(e.attemptId,"attempt id"),pE(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,hj({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(SH,"endV3Attempt");0&&(module.exports={AppRefusal,AppUnreachable,AttemptEndReason,DeliveryStatus,GitHubWriteKind,NoReportCause,SourceProvider,V3Attempt,ValidationSufficiency,closedV3Attempt,currentV3PersistenceDecision,endV3Attempt,fetchV3PersistentDataPolicy,heartbeatV3Attempt,startV3Attempt,uploadV3Report});
218
218
  /*! Bundled license information:
219
219
 
220
220
  undici/lib/web/fetch/body.js:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skyramp/testbot-core",
3
- "version": "0.13.0-v3.428",
3
+ "version": "0.13.0-v3.430",
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.",