@skyramp/testbot-core 0.13.0-v3.418 → 0.13.0-v3.421

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 @@ ${wd}: ${t}`:i;e(["log","-1","--format=%(trailers:key=Signed-off-by,valueonly)"]
227
227
  ${n}`}:{prFailure:"unknown",prDetail:t}}async function lIe(e,t,n,i,r,s){let o=i.slug,a=i.path,c=He(e,"finalize.json"),u=rZ(e.inputs.requirementItems),d=E4(a),p=He(e,"write.json"),h=p?.commit?.message||He(e,"generate-unit.json")?.commitMessage,g=i.working,A=xt=>xt.split(`
228
228
  `)[0],y=xt=>Db(C4(n_(xt)),u),E=(xt,hn)=>g&&!!hn&&y(xt).trim()===y(hn).trim(),v=(xt,hn,xr)=>{let Et=y(xt);return xr&&w4(Et,hn)?Et:I4(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=D4(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},Pe=A(v(K,et,Le)),Z={name:$s,email:Qo},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(xr=>xr.name.trim().toLowerCase()==="dco"&&xr.headSha===xt&&(!xr.repository||xr.repository.toLowerCase()===o.toLowerCase()))??!1}catch{console.warn(`[deliver] could not read commit checks for ${o}`)}}let rt=e.inputs.deliverRemote||"origin",ot=sZ(a,uZ),Rn=sZ(a,lZ);if(ot&&!Rn)throw new Error(`${o}: the checkout records a merged base but not what it merged`);let Ft=ot?v_(void 0,void 0,a):s?s.headBranch||v_(e.inputs.headBranch,e.inputs.baseBranch,a):v_(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 ei=pr?.some(xt=>xt.repository.toLowerCase()===o.toLowerCase())?void 0:e.inputs.deliveryOrigin,Ii=ot||!ei?Rn:void 0,Gs=e.inputs.scheduledDelivery,Yt=Gs?(0,dg.createHash)("sha256").update(JSON.stringify([Gs,o.toLowerCase(),Ft])).digest("hex"):Ii?eIe(o,Ft,Ii):Xwe(pr,o,Ft,ei),Ci=Kwe(Ft,e.inputs.deliverBranch)+(Gs?`-scheduled-${Yt}`:Ii?`-merge-${Yt}`:ei?`-source-${ei.number}-${Yt}`:"");return{texts:u,shown:R,title:Pe,unsigned:I,bot:Z,signOff:M,remote:rt,base:Ft,owner:Yt,testsBranch:Ci,origin:ei,mergedBase:ot}}function dIe(e,t,n,i,r){let s=fn(e,["interpret-trailers","--trailer",`${kb}: ${t.owner}`,"--trailer",`${wd}: ${n}`,"--trailer",`${r_}: ${i}`,...r?["--trailer",`${i_}: ${r}`]:[]],`${t.unsigned}
229
229
  `);return t.signOff?Sb(s,t.bot):s}async function pIe(e,t,n,i,r,s){let o=P4(i.path,e.runDir),a=process.env.PATH;o.dir&&(process.env.PATH=O4(o).PATH);try{return await fIe(e,t,n,i,r,s)}finally{o.dir&&(process.env.PATH=a),o.cleanup()}}async function fIe(e,t,n,i,r,s){let o=i.slug,a,c=!1,u;try{let d=i.path,p=await lIe(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=n_(s4(Z4(nIe(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-${cZ(o)}.md`,W=ia.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)tIe(ia.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=dIe(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 Nb(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,s_(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=tg(ea(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 Pe=s?{}:{repositoryPath:d,repoSlug:o,devPr:null};if(!c){let M=await t.markTestsPrUnchanged({branch:a,...Pe});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,...Pe,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",...uIe(d),unstaged:[]}}}}var jYe={name:"deliver",timeoutMinutes:5,execute:sIe,validateInput:e=>{let t=e_(e);return t?{ok:!1,reasons:[t]}:Wwe(e)},requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var NWe=10*6e4;var PWe=10*6e4;var gIe=3e4,AIe=3,dZ=30,sa=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{},Sd=class extends ns{},Pb=class extends Sd{};function mIe(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 yIe(e,t){if(!bl.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}function EIe(e,t,n,i){throw t<500&&t!==429?new sa(e,t,n,i):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new Pb(e):t===503&&n==="RUN_NOT_READY"?new Sd(e):new ns(e)}async function vIe(e,t,n,i,r,s=1/0){let o=mIe(e.origin),a=`The time limit for ${t} ${n} was reached`,c,u=0;for(let d=1;d<=AIe||c instanceof Sd;d+=1){if(c instanceof Sd){if(u===dZ)throw c;u+=1,d-=1,e.log?.(`${c.message}; trying again (${u} of ${dZ}).`),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(gIe,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 sa||Date.now()>=s)throw p;c=p}}throw c}function bIe(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 wIe(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")>xk;if(o&&Buffer.byteLength(s,"utf8")>gV)throw new Error("The report exceeds the app's 16 MiB expanded report limit");let a=o?new Uint8Array((0,hZ.gzipSync)(s)):s;if(o&&a.length>xk)throw new Error("The compressed report exceeds the app's 1 MiB report upload limit");return vIe(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;bIe(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 EIe(A,u.status,p.error?.code,typeof h?.path=="string"?h.path:void 0)},r)}var OWe=10*6e4;var UWe=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var FWe=l.object({tests:l.object({placements:l.array(l.unknown()).optional()}).passthrough().optional()}).passthrough(),MWe=l.object({repository:Rk,testType:l.string(),directory:l.string()}).passthrough();var LWe=l.object({report:l.object({language:l.string()}).passthrough()}).passthrough();var jWe=l.object({environment:l.object({components:l.array(l.unknown()).optional(),dependencies:l.array(l.unknown()).optional()}).passthrough()}).passthrough(),VWe=l.object({environment:l.object({offLimits:l.unknown().optional()}).passthrough()}).passthrough();var GWe=l.object({environment:l.object({allowedEgress:l.unknown().optional()}).passthrough()}).passthrough();var zWe=l.object({name:l.string().min(1),provision:l.literal("existing"),url:l.string().min(1),repository:Rk.optional(),revisionUrl:l.string().min(1).optional()}).passthrough(),HWe=l.object({name:l.string().min(1),url:l.string().nullable(),versionUrl:l.string().nullable(),notes:l.string().nullable()}).passthrough();var JWe=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);var qWe={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};async function gZ(e,t){return yIe(e.attemptId,"attempt id"),wIe(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,FV({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 pg=se(require("fs")),rs=se(require("path")),AZ=require("child_process");var kd=rs.join(".skyramp","sut");function IIe(e){return e.startsWith(`${kd}${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=pg.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(kd,"setup.sh")),r=n(rs.join(kd,"teardown.sh")),s=n(rs.join(kd,"get-auth-token.sh")),o,a=n(rs.join(kd,"health.json"));if(a)try{let p=JSON.parse(pg.readFileSync(a,"utf-8"));p&&(p.url||p.command)&&(o=p)}catch{}let c,u=n(rs.join(kd,"deploy-budget.json"));if(u)try{let p=JSON.parse(pg.readFileSync(u,"utf-8"));typeof p?.minutes=="number"&&Number.isFinite(p.minutes)&&p.minutes>0&&(c=p.minutes)}catch{}let d=t.filter(IIe);return{setupScript:i,teardownScript:r,authTokenScript:s,healthHint:o,budgetMinutes:c,present:!!(i||a),staleFiles:d,stale:d.length>0}}var mZ=12e4;function Ob(e,t,n){let i=n.timeoutMs??mZ;if(n.signal?.aborted)return Promise.resolve(`${e.label} failed (cancelled)`);let r=o=>If(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,AZ.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(jk(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(),tc(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 yZ=".skyramp/sut/health.json",p4e={[yZ]:`${yZ} (with a url or command)`};function w_(e,t){return!Xp(e.status)||e.environment?[]:[...new Set(e.components.flatMap(n=>n.credentials??[]))].filter(n=>!eW(n,t))}function I_(e){let t=e.filter(Jm),n=e.filter(i=>!Jm(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 Ub(e){if(e.state.stages.onboard?.status==="passed")return He(e,"onboard.json")}function RIe(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 BIe=90,xIe={CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",CLAUDE_BYTE_STREAM_IDLE_TIMEOUT_MS:String(BIe*1e3)},EZ=30,vZ={BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:String(EZ*6e4)},bZ=["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 ${EZ}`,"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 QIe(e,t){return RIe(mt(e,{...xIe,...t},"session"))}function C_(e){return QIe(process.env,e)}var Mb=se(require("fs")),fg=se(require("path"));var wZ=["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"],C4e=[...wZ,"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 S4e=["skyramp_ui_test_generation","skyramp_mock_generation","skyramp_fix_errors","skyramp_start_trace_collection","skyramp_stop_trace_collection","skyramp_export_zip",...wZ];var IZ=["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 Fb=se(require("fs"));var TIe={name:"output-produced",verify(e,t,n){let i=e.outputFileFor(n.name);return(Fb.existsSync(i)?Fb.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)`}}},_Ie=["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 CZ(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??_Ie,exitGates:e.exitGates??[TIe],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 DIe=["Bash(docker:*)","Bash(docker compose:*)","Bash(docker-compose:*)","Bash(bash:*)","Bash(sh:*)","Bash(.skyramp/sut/*)","Bash(./.skyramp/sut/*)","Bash(curl:*)","Bash(sleep:*)",...IZ,"Read","Write","Edit"];function NIe(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=Ub(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?w_(i,C_()):[];return r.length>0?{ok:!1,reasons:[`the recipe reads ${r.join(", ")}: ${I_(r)} \u2014 deploy waits for the check Skyramp runs once the setup ends`]}:n&&!n.sutRequired&&!(i&&Xp(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 PIe(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 OIe(e){let t=Ai(e);return{recipe:Kc(e.inputs.repositoryPath,t?.changedFiles.map(i=>i.path))}}function UIe(e,t){return[t.setupScript,t.teardownScript,t.authTokenScript].filter(n=>!!n).map(n=>fg.relative(e,n))}function FIe(e,t="revisions"){let n=pb(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 kZ(e){return Ub(e)?.environment??e.inputs.recheckEnvironment}function MIe(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 LIe(e){let t=Ub(e),n=e.inputs.recheck?e.inputs.recheckCredentials??[]:t?dk(t):[];if(n.length===0)return[];let i=e.inputs.sharedEnvironment,r=zp(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.`]:[],...jIe(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 jIe=e=>!!(e.inputs.recheck||e.inputs.setupEvents);function VIe(e){let{recipe:t}=e.prepared,n=e.inputs.repositoryPath,i=UIe(n,t),r=kZ(e),s=e.inputs.sharedEnvironment,o=zp(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)"}`,"",...bZ,t.stale?`
230
+ `,k=s?"pr-body.md":`pr-body-${cZ(o)}.md`,W=ia.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)tIe(ia.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=dIe(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 Nb(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,s_(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=tg(ea(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 Pe=s?{}:{repositoryPath:d,repoSlug:o,devPr:null};if(!c){let M=await t.markTestsPrUnchanged({branch:a,...Pe});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,...Pe,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",...uIe(d),unstaged:[]}}}}var jYe={name:"deliver",timeoutMinutes:5,execute:sIe,validateInput:e=>{let t=e_(e);return t?{ok:!1,reasons:[t]}:Wwe(e)},requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var PWe=10*6e4;var OWe=10*6e4;var gIe=3e4,AIe=3,dZ=30,sa=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{},Sd=class extends ns{},Pb=class extends Sd{};function mIe(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 yIe(e,t){if(!bl.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}function EIe(e,t,n,i){throw t<500&&t!==429?new sa(e,t,n,i):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new Pb(e):t===503&&n==="RUN_NOT_READY"?new Sd(e):new ns(e)}async function vIe(e,t,n,i,r,s=1/0){let o=mIe(e.origin),a=`The time limit for ${t} ${n} was reached`,c,u=0;for(let d=1;d<=AIe||c instanceof Sd;d+=1){if(c instanceof Sd){if(u===dZ)throw c;u+=1,d-=1,e.log?.(`${c.message}; trying again (${u} of ${dZ}).`),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(gIe,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 sa||Date.now()>=s)throw p;c=p}}throw c}function bIe(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 wIe(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")>xk;if(o&&Buffer.byteLength(s,"utf8")>gV)throw new Error("The report exceeds the app's 16 MiB expanded report limit");let a=o?new Uint8Array((0,hZ.gzipSync)(s)):s;if(o&&a.length>xk)throw new Error("The compressed report exceeds the app's 1 MiB report upload limit");return vIe(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;bIe(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 EIe(A,u.status,p.error?.code,typeof h?.path=="string"?h.path:void 0)},r)}var UWe=10*6e4;var FWe=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var MWe=l.object({tests:l.object({placements:l.array(l.unknown()).optional()}).passthrough().optional()}).passthrough(),LWe=l.object({repository:Rk,testType:l.string(),directory:l.string()}).passthrough();var jWe=l.object({report:l.object({language:l.string()}).passthrough()}).passthrough();var VWe=l.object({environment:l.object({components:l.array(l.unknown()).optional(),dependencies:l.array(l.unknown()).optional()}).passthrough()}).passthrough(),GWe=l.object({environment:l.object({offLimits:l.unknown().optional()}).passthrough()}).passthrough();var zWe=l.object({environment:l.object({allowedEgress:l.unknown().optional()}).passthrough()}).passthrough();var HWe=l.object({name:l.string().min(1),provision:l.literal("existing"),url:l.string().min(1),repository:Rk.optional(),revisionUrl:l.string().min(1).optional()}).passthrough(),JWe=l.object({name:l.string().min(1),url:l.string().nullable(),versionUrl:l.string().nullable(),notes:l.string().nullable()}).passthrough();var qWe=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);var YWe={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};async function gZ(e,t){return yIe(e.attemptId,"attempt id"),wIe(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,FV({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 pg=se(require("fs")),rs=se(require("path")),AZ=require("child_process");var kd=rs.join(".skyramp","sut");function IIe(e){return e.startsWith(`${kd}${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=pg.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(kd,"setup.sh")),r=n(rs.join(kd,"teardown.sh")),s=n(rs.join(kd,"get-auth-token.sh")),o,a=n(rs.join(kd,"health.json"));if(a)try{let p=JSON.parse(pg.readFileSync(a,"utf-8"));p&&(p.url||p.command)&&(o=p)}catch{}let c,u=n(rs.join(kd,"deploy-budget.json"));if(u)try{let p=JSON.parse(pg.readFileSync(u,"utf-8"));typeof p?.minutes=="number"&&Number.isFinite(p.minutes)&&p.minutes>0&&(c=p.minutes)}catch{}let d=t.filter(IIe);return{setupScript:i,teardownScript:r,authTokenScript:s,healthHint:o,budgetMinutes:c,present:!!(i||a),staleFiles:d,stale:d.length>0}}var mZ=12e4;function Ob(e,t,n){let i=n.timeoutMs??mZ;if(n.signal?.aborted)return Promise.resolve(`${e.label} failed (cancelled)`);let r=o=>If(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,AZ.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(jk(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(),tc(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 yZ=".skyramp/sut/health.json",f4e={[yZ]:`${yZ} (with a url or command)`};function w_(e,t){return!Xp(e.status)||e.environment?[]:[...new Set(e.components.flatMap(n=>n.credentials??[]))].filter(n=>!eW(n,t))}function I_(e){let t=e.filter(Jm),n=e.filter(i=>!Jm(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 Ub(e){if(e.state.stages.onboard?.status==="passed")return He(e,"onboard.json")}function RIe(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 BIe=90,xIe={CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",CLAUDE_BYTE_STREAM_IDLE_TIMEOUT_MS:String(BIe*1e3)},EZ=30,vZ={BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:String(EZ*6e4)},bZ=["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 ${EZ}`,"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 QIe(e,t){return RIe(mt(e,{...xIe,...t},"session"))}function C_(e){return QIe(process.env,e)}var Mb=se(require("fs")),fg=se(require("path"));var wZ=["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"],S4e=[...wZ,"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 k4e=["skyramp_ui_test_generation","skyramp_mock_generation","skyramp_fix_errors","skyramp_start_trace_collection","skyramp_stop_trace_collection","skyramp_export_zip",...wZ];var IZ=["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 Fb=se(require("fs"));var TIe={name:"output-produced",verify(e,t,n){let i=e.outputFileFor(n.name);return(Fb.existsSync(i)?Fb.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)`}}},_Ie=["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 CZ(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??_Ie,exitGates:e.exitGates??[TIe],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 DIe=["Bash(docker:*)","Bash(docker compose:*)","Bash(docker-compose:*)","Bash(bash:*)","Bash(sh:*)","Bash(.skyramp/sut/*)","Bash(./.skyramp/sut/*)","Bash(curl:*)","Bash(sleep:*)",...IZ,"Read","Write","Edit"];function NIe(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=Ub(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?w_(i,C_()):[];return r.length>0?{ok:!1,reasons:[`the recipe reads ${r.join(", ")}: ${I_(r)} \u2014 deploy waits for the check Skyramp runs once the setup ends`]}:n&&!n.sutRequired&&!(i&&Xp(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 PIe(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 OIe(e){let t=Ai(e);return{recipe:Kc(e.inputs.repositoryPath,t?.changedFiles.map(i=>i.path))}}function UIe(e,t){return[t.setupScript,t.teardownScript,t.authTokenScript].filter(n=>!!n).map(n=>fg.relative(e,n))}function FIe(e,t="revisions"){let n=pb(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 kZ(e){return Ub(e)?.environment??e.inputs.recheckEnvironment}function MIe(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 LIe(e){let t=Ub(e),n=e.inputs.recheck?e.inputs.recheckCredentials??[]:t?dk(t):[];if(n.length===0)return[];let i=e.inputs.sharedEnvironment,r=zp(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.`]:[],...jIe(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 jIe=e=>!!(e.inputs.recheck||e.inputs.setupEvents);function VIe(e){let{recipe:t}=e.prepared,n=e.inputs.repositoryPath,i=UIe(n,t),r=kZ(e),s=e.inputs.sharedEnvironment,o=zp(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)"}`,"",...bZ,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?MIe(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".'],...FIe(e),...LIe(e),"","Output: end with one JSON object matching:","",zV(rf)," // 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 RZ(e){let t=fg.join(e.outputsDir,"deploy.txt");if(Mb.existsSync(t)){let{deploy:i}=zc({exitCode:0,stdout:Mb.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:fg.join(".skyramp","sut","teardown.sh")}}function BZ(e,t){return Ob(t,e.inputs.repositoryPath,{env:mt(),secretValues:e.secretValues})}async function SZ(e){let t=RZ(e);if(t){let n=await BZ(e,t);if(n&&xY(e))throw new Error(`SUT teardown failed: ${n}`)}}async function GIe(e,t){let n=t.passed?void 0:xZ(e);if(!n)return;let i=await BZ(e,n);return i&&`${i} (if nothing was running, a teardown must exit 0)`}function xZ(e){return kZ(e)?void 0:RZ(e)}function zIe(e){if(xZ(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 HIe(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=Gh(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 QZ=CZ({name:"deploy",model:"opus",timeoutMinutes:25,requires:["preflight"],softRequires:["onboard"],startsApp:e=>!e.inputs.appRunning,triageBranch:"runtime",validateInput:NIe,prepare:OIe,scaleTimeout:PIe,buildPrompt:VIe,allowedTools:DIe,buildSessionEnv:()=>({...vZ}),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:[hb(),wW()],onPassed:async(e,t)=>({...CW(e,t),...await IW(e,t)}),passReason:HIe,afterAttempt:GIe,retryNote:zIe,onAbort:SZ,teardown:SZ});mn();mn();var cZe=20*1024*1024;var TZ=se(require("path"));var yZe=TZ.join(".skyramp","sut","get-auth-token.sh");var S_="\\$([A-Z][A-Z0-9_]{0,99})",EZe=new RegExp(`^${S_}$`),vZe=new RegExp(`^${S_}:${S_}$`);var AKe=3*6e4;var mKe=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;var ZIe={discover:"reading the repositories",start:"starting the components",check:"checking that the components answer"};var kKe={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 RKe=new RegExp(Il.source,"g");var qKe=new RegExp(Il.source,"g");var eCe="https://testbot.skyramp.dev",oa={attemptId:"v3AttemptId",deadlineAt:"v3DeadlineAt",reportUploaded:"v3ReportUploaded",recipeUploaded:"v3RecipeUploaded",recipeStatus:"v3RecipeStatus",revisionsUploaded:"v3RevisionsUploaded",cause:"v3Cause",conflict:"v3Conflict"};function tCe(e,t,n){return{origin:e,idToken:t,sourceToken:n,mask:i=>ys(i),log:i=>li(i),onTokenRefused:(i,r)=>{rCe(i)&&_Z.set(r,i)},onTokenGranted:i=>{_Z.delete(i)}}}var _Z=new Map;var E3e=["setup_failed","checkout_failed","environment_unverified"];function nCe(e,t){return t.getTime()>=e.getTime()}function rCe(e){return e instanceof ns||e instanceof sa&&e.code!=="CREDENTIALS_UNAVAILABLE"}var v3e={cancelled:"Skyramp cancelled this run",expired:"this attempt passed its deadline in Skyramp",ended:"Skyramp already ended this attempt"},b3e={cancelled:"attempt-cancelled",expired:"attempt-closed",ended:"attempt-closed"},w3e={cancelled:"cancelled",expired:"timed_out",ended:"agent_failed"};var I3e={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"},C3e={analyze:"change analysis",recommend:"test recommendations",generate:"test generation",execute:"test execution",deliver:"opening a pull request with the tests"};function iCe(){return De("skyrampAppOrigin").trim()||eCe}var S3e=10*6e4;var k3e={onboard:"onboard",deploy:"deploy"},R3e={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"}},B3e=new Set(["write","native-run"]);function sCe(){let e=Es(oa.conflict);if(!e)return;let t;try{t=UV.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 DZ(){let e=Es(oa.attemptId);if(!e)return;let t=Es(oa.reportUploaded)==="true",n=Es(oa.recipeUploaded)==="true",i=Es(oa.revisionsUploaded)==="true",r=Es(oa.deadlineAt),s=Es(oa.cause)||void 0;!s&&!t&&!n&&!i&&r&&nCe(new Date(r),new Date)&&(s="timed_out");let o=Ad().takeIdToken(),a=sCe(),c=await gZ({attemptId:e,reportUploaded:t,recipeUploaded:n,revisionsUploaded:i,cause:s,...a?{conflict:a}:{}},tCe(iCe(),o)),u=Es(oa.recipeStatus);n&&u?li(`Testbot V3: attempt ended; the setup ended ${u==="ready"?"Ready":"blocked (Needs input)"}.`):li(`Testbot V3: attempt ended; the run's outcome in Skyramp is ${c.outcome??"not final yet"}.`)}var NZ=require("child_process"),is=se(require("fs")),R_=se(require("path")),B_=require("string_decoder");var oCe="skyramp-testbot-state",aCe=/^\$\([^)]*\)$/;function cCe(e){for(let[t,n]of Object.entries(e))n!==void 0&&aCe.test(n)&&delete e[t]}function uCe(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 PZ(e,t={}){let n=t.env??process.env;if(!Jo(n))return!1;cCe(n),VY(n);let i=n.AGENT_TEMPDIRECTORY||n.RUNNER_TEMP;if(i){n.RUNNER_TEMP??=i;let o=R_.join(i,oCe);if(e==="main")is.writeFileSync(o,"",{mode:384});else for(let[a,c]of Object.entries(uCe(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]=R_.join(i,`skyramp-testbot-${c}`),is.writeFileSync(n[a],"",{mode:384})}let r=t.stdout??n===process.env;r&&lCe(n,t.write);let s=n.GITHUB_STEP_SUMMARY;if(r&&s){let o=t.write??(a=>l0(a.replace(/\n$/,"")));process.once("exit",()=>{is.existsSync(s)&&is.statSync(s).size>0&&o(`${nb("task.uploadsummary",{},s)}
236
+ `)}function RZ(e){let t=fg.join(e.outputsDir,"deploy.txt");if(Mb.existsSync(t)){let{deploy:i}=zc({exitCode:0,stdout:Mb.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:fg.join(".skyramp","sut","teardown.sh")}}function BZ(e,t){return Ob(t,e.inputs.repositoryPath,{env:mt(),secretValues:e.secretValues})}async function SZ(e){let t=RZ(e);if(t){let n=await BZ(e,t);if(n&&xY(e))throw new Error(`SUT teardown failed: ${n}`)}}async function GIe(e,t){let n=t.passed?void 0:xZ(e);if(!n)return;let i=await BZ(e,n);return i&&`${i} (if nothing was running, a teardown must exit 0)`}function xZ(e){return kZ(e)?void 0:RZ(e)}function zIe(e){if(xZ(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 HIe(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=Gh(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 QZ=CZ({name:"deploy",model:"opus",timeoutMinutes:25,requires:["preflight"],softRequires:["onboard"],startsApp:e=>!e.inputs.appRunning,triageBranch:"runtime",validateInput:NIe,prepare:OIe,scaleTimeout:PIe,buildPrompt:VIe,allowedTools:DIe,buildSessionEnv:()=>({...vZ}),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:[hb(),wW()],onPassed:async(e,t)=>({...CW(e,t),...await IW(e,t)}),passReason:HIe,afterAttempt:GIe,retryNote:zIe,onAbort:SZ,teardown:SZ});mn();mn();var uZe=20*1024*1024;var TZ=se(require("path"));var EZe=TZ.join(".skyramp","sut","get-auth-token.sh");var S_="\\$([A-Z][A-Z0-9_]{0,99})",vZe=new RegExp(`^${S_}$`),bZe=new RegExp(`^${S_}:${S_}$`);var mKe=3*6e4;var yKe=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;var ZIe={discover:"reading the repositories",start:"starting the components",check:"checking that the components answer"};var RKe={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 BKe=new RegExp(Il.source,"g");var YKe=new RegExp(Il.source,"g");var eCe="https://testbot.skyramp.dev",oa={attemptId:"v3AttemptId",deadlineAt:"v3DeadlineAt",reportUploaded:"v3ReportUploaded",recipeUploaded:"v3RecipeUploaded",recipeStatus:"v3RecipeStatus",revisionsUploaded:"v3RevisionsUploaded",cause:"v3Cause",conflict:"v3Conflict"};function tCe(e,t,n){return{origin:e,idToken:t,sourceToken:n,mask:i=>ys(i),log:i=>li(i),onTokenRefused:(i,r)=>{rCe(i)&&_Z.set(r,i)},onTokenGranted:i=>{_Z.delete(i)}}}var _Z=new Map;var v3e=["setup_failed","checkout_failed","environment_unverified"];function nCe(e,t){return t.getTime()>=e.getTime()}function rCe(e){return e instanceof ns||e instanceof sa&&e.code!=="CREDENTIALS_UNAVAILABLE"}var b3e={cancelled:"Skyramp cancelled this run",expired:"this attempt passed its deadline in Skyramp",ended:"Skyramp already ended this attempt"},w3e={cancelled:"attempt-cancelled",expired:"attempt-closed",ended:"attempt-closed"},I3e={cancelled:"cancelled",expired:"timed_out",ended:"agent_failed"};var C3e={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"},S3e={analyze:"change analysis",recommend:"test recommendations",generate:"test generation",execute:"test execution",deliver:"opening a pull request with the tests"};function iCe(){return De("skyrampAppOrigin").trim()||eCe}var k3e=10*6e4;var R3e={onboard:"onboard",deploy:"deploy"},B3e={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"}},x3e=new Set(["write","native-run"]);function sCe(){let e=Es(oa.conflict);if(!e)return;let t;try{t=UV.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 DZ(){let e=Es(oa.attemptId);if(!e)return;let t=Es(oa.reportUploaded)==="true",n=Es(oa.recipeUploaded)==="true",i=Es(oa.revisionsUploaded)==="true",r=Es(oa.deadlineAt),s=Es(oa.cause)||void 0;!s&&!t&&!n&&!i&&r&&nCe(new Date(r),new Date)&&(s="timed_out");let o=Ad().takeIdToken(),a=sCe(),c=await gZ({attemptId:e,reportUploaded:t,recipeUploaded:n,revisionsUploaded:i,cause:s,...a?{conflict:a}:{}},tCe(iCe(),o)),u=Es(oa.recipeStatus);n&&u?li(`Testbot V3: attempt ended; the setup ended ${u==="ready"?"Ready":"blocked (Needs input)"}.`):li(`Testbot V3: attempt ended; the run's outcome in Skyramp is ${c.outcome??"not final yet"}.`)}var NZ=require("child_process"),is=se(require("fs")),R_=se(require("path")),B_=require("string_decoder");var oCe="skyramp-testbot-state",aCe=/^\$\([^)]*\)$/;function cCe(e){for(let[t,n]of Object.entries(e))n!==void 0&&aCe.test(n)&&delete e[t]}function uCe(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 PZ(e,t={}){let n=t.env??process.env;if(!Jo(n))return!1;cCe(n),VY(n);let i=n.AGENT_TEMPDIRECTORY||n.RUNNER_TEMP;if(i){n.RUNNER_TEMP??=i;let o=R_.join(i,oCe);if(e==="main")is.writeFileSync(o,"",{mode:384});else for(let[a,c]of Object.entries(uCe(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]=R_.join(i,`skyramp-testbot-${c}`),is.writeFileSync(n[a],"",{mode:384})}let r=t.stdout??n===process.env;r&&lCe(n,t.write);let s=n.GITHUB_STEP_SUMMARY;if(r&&s){let o=t.write??(a=>l0(a.replace(/\n$/,"")));process.once("exit",()=>{is.existsSync(s)&&is.statSync(s).size>0&&o(`${nb("task.uploadsummary",{},s)}
237
237
  `)})}return!0}function lCe(e,t){let n=process.stdout.write.bind(process.stdout),i=o=>e[Nh]==="1"?u0(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("::")?PY(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 dCe=64*1024;function k_(e){let t=new B_.StringDecoder("utf8"),n="",i=r=>e(tb(r));return{push(r){n+=typeof r=="string"?r:t.write(r);let s=n.lastIndexOf(`