@skyramp/testbot-core 0.13.1-v3.475 → 0.13.2-v3.478

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
@@ -250,13 +250,13 @@ ${n}`}:{prFailure:"unknown",prDetail:t}}async function PSe(e,t,n,s,r,i){let o=s.
250
250
  `}catch{return""}}var r6=e=>e.map(t=>t.dependsOn.length?`${t.file} (needs ${t.dependsOn.join(", ")})`:t.file).join("; ");async function LSe(e,t,n,s,r,i){let o=DK(s.path,e.runDir),a=process.env.PATH;o.dir&&(process.env.PATH=NK(o).PATH);try{return await jSe(e,t,n,s,r,i)}finally{o.dir&&(process.env.PATH=a),o.cleanup()}}async function jSe(e,t,n,s,r,i){let o=s.slug,a,c=!1,u,l=[];try{let p=s.path,h=await PSe(e,t,n,s,r,i),{texts:g,shown:m,title:y,bot:v,remote:E,base:b,owner:w,testsBranch:C,origin:I,mergedBase:x}=h,S=(oe=[])=>uD(GZ(BSe(oe,b)+YK(RSe(kSe(m,e,s),oe.map(lt=>lt.file)),{audience:"testbot-pr",runUrl:e.inputs.skyrampRunUrl,requestedBy:e.inputs.requestedBy,sourcePullRequest:I&&`${I.repository.namespace}/${I.repository.name}#${I.number}`}),e.inputs.skyrampRunUrl))+`
251
251
  `,H=i?"pr-body.md":`pr-body-${e6(o)}.md`,de=Ls.join(e.outputsDir,H);gn.writeFileSync(de,S());let J=dt(p,["rev-parse","HEAD"]),Be=x??J;dt(p,["checkout","-B",C]),a=C,dt(p,["reset"]);let xe=Se(e,"write.json"),Oe=Hg(e).filter(oe=>oe.source.path===s.path&&r.includes(oe.record.sourceAsset)),Ne=SD(e);if(Ne.length)throw new Error(Ne.join("; "));let re=xe?TK(e,xe,g):[];if(re.length)throw new Error(re.join("; "));let M=new Set(Oe.flatMap(({record:oe})=>[oe.sourceAsset,...oe.entry?[oe.entry]:[]]));for(let oe of r)M.has(oe)||SSe(Ls.join(p,oe),g);let Xe=$K(e,Oe,g,l);if(Xe.length)throw new Error(Xe.join("; "));let Ye=new Map([...M].map(oe=>{let lt=gn.readFileSync(Ls.join(p,oe)),kt=fo=>dt(p,["hash-object","--no-filters","--stdin"],fo),Le=new Set([kt(lt)]),Bn=lt.toString("latin1");return!lt.includes(0)&&Bn.includes(`\r
252
252
  `)&&Le.add(kt(Buffer.from(Bn.replace(/\r\n/g,`
253
- `),"latin1"))),[oe,Le]})),Ht=[];for(let oe of r)try{dt(p,["--literal-pathspecs","add","--",oe])}catch{Ht.push(oe)}if(Ht.some(oe=>M.has(oe)))throw new Error("could not stage every guarded delivery file");let Mt=new Map([...Ye].map(([oe,lt])=>{let kt=dt(p,["--literal-pathspecs","ls-files","--stage","--",oe]),Le=/^100(?:644|755) ([a-f0-9]+) 0\t/.exec(kt)?.[1];if(!Le||!lt.has(Le))throw new Error(`the staged guarded file differs from the generated file: ${oe}`);return[oe,Le]}));try{dt(p,["diff","--cached","--quiet"])}catch{try{let oe=OSe(p,h,J,Be,e.inputs.skyrampRunUrl);dt(p,["-c",`user.name=${v.name}`,"-c",`user.email=${v.email}`,"commit","-m",oe])}catch(oe){throw new Pw(oe)}c=!0}c&&(l.length=0),u=dt(p,["rev-parse","HEAD"]);let mn,Pt,nr,rr=x??i?.headSha;if(c&&rr&&rr!==J){let oe=!1,lt=u;try{dt(p,["checkout","-q","-B",a,rr]),oe=!0;try{dt(p,["-c",`user.name=${v.name}`,"-c",`user.email=${v.email}`,"cherry-pick","--keep-redundant-commits",u])}catch(kt){let Le=x?FSe(p,v,lt):void 0;if(!Le||(Pt=Le.files.map(Bn=>({file:Bn,dependsOn:USe(p,o,x,J,Bn)})),nr={repository:o,base:b,files:Pt,patch:MSe(p,J,lt,Le.files)},!Le.delivered))throw kt}oe=!1,pD(kt=>dt(p,kt),rr),u=dt(p,["rev-parse","HEAD"])}catch(kt){try{dt(p,["cherry-pick","--abort"])}catch{}dt(p,["checkout","-q","-B",a,u]);let Le=Fg(Sa(kt),1/0);if(x&&!oe)throw kt;if(x)return{thrown:!1,held:nr,record:{schemaVersion:1,repository:o,branch:a,remote:E,base:b,committed:c,commitSha:u,pushed:!1,prAction:"skipped",prTitle:y,unstaged:Ht,...Pt?{heldBack:Pt}:{},reason:Pt?`every test change needs a merged revision ${b} does not have yet, so no tests PR was opened: ${r6(Pt)}`:`the tests do not apply to ${b} at ${x.slice(0,12)} without the merged revisions (${Le}), so no tests PR was opened`}};mn=`tests committed on the checkout's merge commit (re-cut onto ${rr.slice(0,12)} failed: ${Le})`}}Pt&&gn.writeFileSync(de,S(Pt));for(let[oe,lt]of Mt){if(Pt?.some(Le=>Le.file===oe))continue;let kt=dt(p,["--literal-pathspecs","ls-tree",u,"--",oe]);if(/^100(?:644|755) blob ([a-f0-9]+)\t/.exec(kt)?.[1]!==lt)throw new Error(`the committed guarded file differs from the generated file: ${oe}`)}for(let{record:oe}of Oe){if(oe.entry)continue;let lt=dt(p,["--literal-pathspecs","ls-tree",u,"--",oe.file]);if(lt&&lt!==dt(p,["--literal-pathspecs","ls-tree",J,"--",oe.file]))throw new Error(`the delivery included executable source for a held test: ${oe.file}`)}let qt=i?{}:{repositoryPath:p,repoSlug:o,devPr:null};if(!c){let oe=await t.markTestsPrUnchanged({branch:a,...qt});return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:E,base:b,committed:!1,commitSha:u,pushed:!1,prAction:oe.action==="unchanged"?"unchanged":"skipped",prUrl:oe.url,prTitle:y,unstaged:Ht,reason:oe.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 St=await t.publishTestsPr({repositoryPath:p,...qt,remote:E,branch:a,base:b,commitSha:u,title:y,bodyFile:de,mode:e.inputs.deliverMode,deliveryOwner:w,...e.inputs.firstQualification?{firstQualification:!0}:{},runUrl:e.inputs.skyrampRunUrl,signal:e.signal,deadlineMs:e.deadlineMs});return{thrown:!1,held:nr,record:{schemaVersion:1,repository:o,branch:a,remote:E,base:St.base,requestedBase:b,committed:c,commitSha:u,pushed:St.pushed,...St.pushedCommits?{pushedCommits:St.pushedCommits}:{},...St.deliveredCommit?{deliveredCommit:St.deliveredCommit}:{},prAction:St.action,...St.retargetedAs?{retargetedAs:St.retargetedAs}:{},prUrl:St.url,prTitle:y,...St.failure?{prFailure:St.failure,prDetail:St.detail}:{},...mn?{cutNote:mn}:{},...St.action==="skipped"&&St.detail?{reason:St.detail}:{},unstaged:Ht,...Pt?{heldBack:Pt}:{}}}}catch(p){return{thrown:!0,record:{schemaVersion:1,repository:o,branch:a,committed:c,commitSha:u,pushed:!1,prAction:"failed",...NSe(p),unstaged:[]}}}finally{if(l.length){try{dt(s.path,["reset"])}catch{}for(let p of l.reverse())try{p()}catch{}}}}var y6e={name:"deliver",timeoutMinutes:5,execute:$Se,validateInput:e=>{let t=aD(e);return t?{ok:!1,reasons:[t]}:vSe(e)},requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var b9e=10*6e4;var w9e=10*6e4;var GSe=3e4,zSe=3,s6=30,$a=class extends Error{constructor(n,s,r,i){super(n);this.status=s;this.code=r;this.path=i}status;code;path},wi=class extends Error{},Xd=class extends wi{},Ow=class extends Xd{};function HSe(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 qSe(e,t){if(!ql.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}function JSe(e,t,n,s){throw t<500&&t!==429?new $a(e,t,n,s):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new Ow(e):t===503&&n==="RUN_NOT_READY"?new Xd(e):new wi(e)}async function WSe(e,t,n,s,r,i=1/0){let o=HSe(e.origin),a=`The time limit for ${t} ${n} was reached`,c,u=0;for(let l=1;l<=zSe||c instanceof Xd;l+=1){if(c instanceof Xd){if(u===s6)throw c;u+=1,l-=1,e.log?.(`${c.message}; trying again (${u} of ${s6}).`),await new Promise(p=>setTimeout(p,Math.max(0,Math.min(e.readyWaitMs??1e4,i-Date.now()))))}else l>1&&await new Promise(p=>setTimeout(p,Math.max(0,Math.min((e.retryDelayMs??2e3)*(l-1),i-Date.now()))));if(Date.now()>=i)throw new wi(a);try{let p,h=await(Number.isFinite(i)?Promise.race([e.idToken(o),new Promise((m,y)=>{p=setTimeout(()=>y(new wi(a)),Math.max(1,i-Date.now()))})]).finally(()=>{p&&clearTimeout(p)}):e.idToken(o));if(Date.now()>=i)throw new wi(a);let g=await(e.fetch??fetch)(new URL(n,o).toString(),{...s(h),redirect:"error",signal:AbortSignal.timeout(Math.max(1,Math.min(GSe,i-Date.now())))}).catch(m=>{throw new wi(m instanceof Error?m.message:String(m),{cause:m})});return await r(g)}catch(p){if(p instanceof $a||Date.now()>=i)throw p;c=p}}throw c}function YSe(e,t,n,s,r){let i=s.headers.get("cf-ray");e.log?.(`Testbot V3: ${t} ${n} answered ${s.status}${i?`, cf-ray ${i}`:""}: ${r.replace(/\s+/g," ").slice(0,200)}`)}var Uw=class extends Error{};function ZSe(e){let t=Buffer.byteLength(e,"utf8");if(t<=_R)return{body:e};if(t>NG)throw new Uw("The report exceeds the app's 16 MiB expanded report limit");let n=new Uint8Array((0,a6.gzipSync)(e));if(n.length>_R)throw new Uw("The compressed report exceeds the app's 1 MiB report upload limit");return{body:n,gzip:!0}}function KSe(e,t,n,s,r){let i=t==="GET"?void 0:JSON.stringify(s),o=t==="PUT"&&/^\/api\/v1\/runner\/attempts\/[^/]+\/report$/.test(n)&&i!==void 0?ZSe(i):{body:i};return XSe(e,t,n,o,r)}function XSe(e,t,n,s,r){return WSe(e,t,n,o=>({method:t,headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json",Accept:"application/json",...s.gzip?{"Content-Encoding":"gzip"}:{}},body:s.body}),async o=>{let a=await o.text().catch(()=>""),c={};try{c=JSON.parse(a)}catch{}if(o.ok)return c.data;YSe(e,t,n,o,a);let u=c.error?.fields,l=typeof u?.path=="string"&&typeof u.reason=="string"?` at ${u.path}: ${u.reason}`:"",p=`The Skyramp app refused ${t} ${n}: ${o.status} ${c.error?.code??"no error code"}${l}`;return JSe(p,o.status,c.error?.code,typeof u?.path=="string"?u.path:void 0)},r)}var I9e=10*6e4;var C9e=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var S9e=d.object({tests:d.object({placements:d.array(d.unknown()).optional()}).passthrough().optional()}).passthrough(),k9e=d.object({repository:QR,testType:d.string(),directory:d.string()}).passthrough();var R9e=d.object({report:d.object({language:d.string()}).passthrough()}).passthrough();var B9e=d.object({environment:d.object({components:d.array(d.unknown()).optional(),dependencies:d.array(d.unknown()).optional()}).passthrough()}).passthrough(),x9e=d.object({environment:d.object({offLimits:d.unknown().optional()}).passthrough()}).passthrough();var Q9e=d.object({environment:d.object({allowedEgress:d.unknown().optional()}).passthrough()}).passthrough();var $9e=d.object({name:d.string().min(1),provision:d.literal("existing"),url:d.string().min(1),repository:QR.optional(),revisionUrl:d.string().min(1).optional()}).passthrough(),T9e=d.object({name:d.string().min(1),url:d.string().nullable(),versionUrl:d.string().nullable(),notes:d.string().nullable()}).passthrough();var _9e=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);var D9e={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};async function c6(e,t){return qSe(e.attemptId,"attempt id"),KSe(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,iz({reportUploaded:e.reportUploaded,recipeUploaded:e.recipeUploaded,revisionsUploaded:e.revisionsUploaded,cancelled:e.cause==="cancelled",timedOut:e.cause==="timed_out",setupFailed:e.cause==="setup_failed",checkoutFailed:e.cause==="checkout_failed"||e.cause==="merge_conflict"&&!e.conflict,mergeConflict:e.cause==="merge_conflict"?e.conflict:void 0,environmentUnverified:e.cause==="environment_unverified",runnerProviderNotReady:e.cause==="runner_provider_not_ready",credentialMissing:e.cause==="credential_missing",modelProviderDenied:e.cause==="model_provider_denied",modelProviderUnavailable:e.cause==="model_provider_unavailable",githubWrites:e.githubWrites,environmentUnavailable:e.cause==="environment_unavailable"}))}var Kg=Z(require("fs")),Ii=Z(require("path")),u6=require("child_process");var ep=Ii.join(".skyramp","sut");function eke(e){return e.startsWith(`${ep}${Ii.sep}`)||e.startsWith(".skyramp/sut/")||/(^|\/)(docker-compose|compose)[^/]*\.ya?ml$/.test(e)||/(^|\/)Dockerfile[^/]*$/.test(e)||/^\.github\/workflows\//.test(e)}function DD(e,t,n={}){let s=t.split(/[\\/]+/).filter(Boolean),r=e;for(let[i,o]of s.entries()){r=Ii.join(r,o);let a=Kg.lstatSync(r,{throwIfNoEntry:!1}),c=i===s.length-1;if(!a||a.isSymbolicLink()||(c?n.directory?!a.isDirectory():!a.isFile():!a.isDirectory()))return}return s.length?r:void 0}function ku(e,t=[]){let n=p=>DD(e,p),s=n(Ii.join(ep,"setup.sh")),r=n(Ii.join(ep,"teardown.sh")),i=n(Ii.join(ep,"get-auth-token.sh")),o,a=n(Ii.join(ep,"health.json"));if(a)try{let p=JSON.parse(Kg.readFileSync(a,"utf-8"));p&&(p.url||p.command)&&(o=p)}catch{}let c,u=n(Ii.join(ep,"deploy-budget.json"));if(u)try{let p=JSON.parse(Kg.readFileSync(u,"utf-8"));typeof p?.minutes=="number"&&Number.isFinite(p.minutes)&&p.minutes>0&&(c=p.minutes)}catch{}let l=t.filter(eke);return{setupScript:s,teardownScript:r,authTokenScript:i,healthHint:o,budgetMinutes:c,present:!!(s||a),staleFiles:l,stale:l.length>0}}var l6=12e4;function Fw(e,t,n){let s=n.timeoutMs??l6;if(n.signal?.aborted)return Promise.resolve(`${e.label} failed (cancelled)`);let r=o=>rh(tn(o,n.secretValues??[])),i;try{i=xs(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,l,p;try{p=(0,u6.spawn)(i.argv[0],i.argv.slice(1),{cwd:t,env:i.env,stdio:["ignore","pipe","pipe"],detached:!0})}catch(C){let I=C instanceof Error?C.message:String(C);o(r(`${e.label} failed (could not start: ${I})`));return}let h=C=>{let I=Math.max(0,...(n.secretValues??[]).map(x=>x.length));a=(a+C.toString("utf-8")).slice(-(4096+I))},g=()=>r(HR(a,n.secretValues??[],4096));p.stdout?.on("data",h),p.stderr?.on("data",h);let m=()=>{try{p.pid!==void 0&&process.kill(-p.pid,"SIGKILL")}catch{p.kill("SIGKILL")}},y=C=>{let I=g().trim().split(`
254
- `).pop()?.trim().slice(0,300)??"";return`${e.label} failed (${C})${I?`: ${I}`:""}`},v=C=>{u||(u=!0,clearTimeout(b),clearTimeout(l),n.signal?.removeEventListener("abort",E),C!==void 0&&m(),p.stdout?.destroy(),p.stderr?.destroy(),Vo(t,C===void 0?0:1),o(C===void 0?void 0:r(C)))},E=()=>v(y("cancelled")),b=setTimeout(()=>{c=!0,v(y(`timed out after ${s/1e3} s`))},s);n.signal?.addEventListener("abort",E,{once:!0}),n.signal?.aborted&&E();let w=(C,I)=>{if(c)return y(`timed out after ${s/1e3} s`);if(C!==0)return y(C===null?`killed by ${I}`:`exit ${C}`)};p.on("error",C=>v(y(`could not start: ${C.message}`))),p.on("close",(C,I)=>v(w(C,I))),p.on("exit",(C,I)=>{u||(C!==0?v(w(C,I)):l=setTimeout(()=>v(w(C,I)),1e3))})})}var d6=".skyramp/sut/health.json",K9e={[d6]:`${d6} (with a url or command)`};function ND(e,t){return!$f(e.status)||e.environment?[]:[...new Set(e.components.flatMap(n=>n.credentials??[]))].filter(n=>!x4(n,t))}function p6(e){let t=e.filter(vf),n=e.filter(s=>!vf(s));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 Mw(e){if(e.state.stages.onboard?.status==="passed")return Se(e,"onboard.json")}function ske(e){let t=Ld(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 ike=90,oke={CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",CLAUDE_BYTE_STREAM_IDLE_TIMEOUT_MS:String(ike*1e3)},f6=30,h6={BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:String(f6*6e4)},g6=["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 ${f6}`,"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 ake(e,t){return ske(ht(e,{...oke,...t},"session"))}function PD(e){return ake(process.env,e)}var jw=Z(require("fs")),Xg=Z(require("path"));var m6=["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"],l3e=[...m6,"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 d3e=["skyramp_ui_test_generation","skyramp_mock_generation","skyramp_fix_errors","skyramp_start_trace_collection","skyramp_stop_trace_collection","skyramp_export_zip",...m6];var A6=["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 Lw=Z(require("fs"));var uke={name:"output-produced",verify(e,t,n){let s=e.outputFileFor(n.name);return(Lw.existsSync(s)?Lw.readFileSync(s,"utf-8"):"").trim().length>0?{name:this.name,passed:!0}:{name:this.name,passed:!1,details:`stage produced no output (${s} empty or missing)`}}},lke=["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 y6(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??lke,exitGates:e.exitGates??[uke],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 dke=["Bash(docker:*)","Bash(docker compose:*)","Bash(docker-compose:*)","Bash(bash:*)","Bash(sh:*)","Bash(.skyramp/sut/*)","Bash(./.skyramp/sut/*)","Bash(curl:*)","Bash(sleep:*)",...A6,"Read","Write","Edit"];function pke(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=_s(e),s=Mw(e);if(s?.status==="blocked")return{ok:!1,reasons:[`onboarding reported blocked (${s.blockers.length} blocker(s)) \u2014 see outputs/onboard.json`]};let r=e.inputs.setupEvents&&t?.status==="passed"&&s&&!e.inputs.recheck?ND(s,PD()):[];return r.length>0?{ok:!1,reasons:[`the recipe reads ${r.join(", ")}: ${p6(r)} \u2014 deploy waits for the check Skyramp runs once the setup ends`]}:n&&!n.sutRequired&&!(s&&$f(s.status))&&!e.inputs.recheck?{ok:!1,reasons:["preflight determined no SUT is required (non-application change)"]}:ku(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 fke(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 hke(e){let t=_s(e);return{recipe:ku(e.inputs.repositoryPath,t?.changedFiles.map(s=>s.path))}}function gke(e,t){return[t.setupScript,t.teardownScript,t.authTokenScript].filter(n=>!!n).map(n=>Xg.relative(e,n))}function mke(e,t="revisions"){let n=iw(e.inputs);return n.length===0?[]:["","Shared components: these run in an existing environment that this run does not deploy.",...n.map(s=>` - ${s.name} at ${s.url}, running ${s.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 OD(e){return Mw(e)?.environment??e.inputs.recheckEnvironment}function Ake(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 yke(e){let t=Mw(e),n=e.inputs.recheck?e.inputs.recheckCredentials??[]:t?hR(t):[];if(n.length===0)return[];let s=e.inputs.sharedEnvironment,r=bf(s).map(i=>i.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.`]:[],...Eke(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 Eke=e=>!!(e.inputs.recheck||e.inputs.setupEvents);function vke(e){let{recipe:t}=e.prepared,n=e.inputs.repositoryPath,s=gke(n,t),r=OD(e),i=e.inputs.sharedEnvironment,o=bf(i).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: ${s.join(", ")||"(workspace only)"}`,"",...g6,t.stale?`
253
+ `),"latin1"))),[oe,Le]})),Ht=[];for(let oe of r)try{dt(p,["--literal-pathspecs","add","--",oe])}catch{Ht.push(oe)}if(Ht.some(oe=>M.has(oe)))throw new Error("could not stage every guarded delivery file");let Mt=new Map([...Ye].map(([oe,lt])=>{let kt=dt(p,["--literal-pathspecs","ls-files","--stage","--",oe]),Le=/^100(?:644|755) ([a-f0-9]+) 0\t/.exec(kt)?.[1];if(!Le||!lt.has(Le))throw new Error(`the staged guarded file differs from the generated file: ${oe}`);return[oe,Le]}));try{dt(p,["diff","--cached","--quiet"])}catch{try{let oe=OSe(p,h,J,Be,e.inputs.skyrampRunUrl);dt(p,["-c",`user.name=${v.name}`,"-c",`user.email=${v.email}`,"commit","-m",oe])}catch(oe){throw new Pw(oe)}c=!0}c&&(l.length=0),u=dt(p,["rev-parse","HEAD"]);let mn,Pt,nr,rr=x??i?.headSha;if(c&&rr&&rr!==J){let oe=!1,lt=u;try{dt(p,["checkout","-q","-B",a,rr]),oe=!0;try{dt(p,["-c",`user.name=${v.name}`,"-c",`user.email=${v.email}`,"cherry-pick","--keep-redundant-commits",u])}catch(kt){let Le=x?FSe(p,v,lt):void 0;if(!Le||(Pt=Le.files.map(Bn=>({file:Bn,dependsOn:USe(p,o,x,J,Bn)})),nr={repository:o,base:b,files:Pt,patch:MSe(p,J,lt,Le.files)},!Le.delivered))throw kt}oe=!1,pD(kt=>dt(p,kt),rr),u=dt(p,["rev-parse","HEAD"])}catch(kt){try{dt(p,["cherry-pick","--abort"])}catch{}dt(p,["checkout","-q","-B",a,u]);let Le=Fg(Sa(kt),1/0);if(x&&!oe)throw kt;if(x)return{thrown:!1,held:nr,record:{schemaVersion:1,repository:o,branch:a,remote:E,base:b,committed:c,commitSha:u,pushed:!1,prAction:"skipped",prTitle:y,unstaged:Ht,...Pt?{heldBack:Pt}:{},reason:Pt?`every test change needs a merged revision ${b} does not have yet, so no tests PR was opened: ${r6(Pt)}`:`the tests do not apply to ${b} at ${x.slice(0,12)} without the merged revisions (${Le}), so no tests PR was opened`}};mn=`tests committed on the checkout's merge commit (re-cut onto ${rr.slice(0,12)} failed: ${Le})`}}Pt&&gn.writeFileSync(de,S(Pt));for(let[oe,lt]of Mt){if(Pt?.some(Le=>Le.file===oe))continue;let kt=dt(p,["--literal-pathspecs","ls-tree",u,"--",oe]);if(/^100(?:644|755) blob ([a-f0-9]+)\t/.exec(kt)?.[1]!==lt)throw new Error(`the committed guarded file differs from the generated file: ${oe}`)}for(let{record:oe}of Oe){if(oe.entry)continue;let lt=dt(p,["--literal-pathspecs","ls-tree",u,"--",oe.file]);if(lt&&lt!==dt(p,["--literal-pathspecs","ls-tree",J,"--",oe.file]))throw new Error(`the delivery included executable source for a held test: ${oe.file}`)}let qt=i?{}:{repositoryPath:p,repoSlug:o,devPr:null};if(!c){let oe=await t.markTestsPrUnchanged({branch:a,...qt});return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:E,base:b,committed:!1,commitSha:u,pushed:!1,prAction:oe.action==="unchanged"?"unchanged":"skipped",prUrl:oe.url,prTitle:y,unstaged:Ht,reason:oe.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 St=await t.publishTestsPr({repositoryPath:p,...qt,remote:E,branch:a,base:b,commitSha:u,title:y,bodyFile:de,mode:e.inputs.deliverMode,deliveryOwner:w,...e.inputs.firstQualification?{firstQualification:!0}:{},runUrl:e.inputs.skyrampRunUrl,signal:e.signal,deadlineMs:e.deadlineMs});return{thrown:!1,held:nr,record:{schemaVersion:1,repository:o,branch:a,remote:E,base:St.base,requestedBase:b,committed:c,commitSha:u,pushed:St.pushed,...St.pushedCommits?{pushedCommits:St.pushedCommits}:{},...St.deliveredCommit?{deliveredCommit:St.deliveredCommit}:{},prAction:St.action,...St.retargetedAs?{retargetedAs:St.retargetedAs}:{},prUrl:St.url,prTitle:y,...St.failure?{prFailure:St.failure,prDetail:St.detail}:{},...mn?{cutNote:mn}:{},...St.action==="skipped"&&St.detail?{reason:St.detail}:{},unstaged:Ht,...Pt?{heldBack:Pt}:{}}}}catch(p){return{thrown:!0,record:{schemaVersion:1,repository:o,branch:a,committed:c,commitSha:u,pushed:!1,prAction:"failed",...NSe(p),unstaged:[]}}}finally{if(l.length){try{dt(s.path,["reset"])}catch{}for(let p of l.reverse())try{p()}catch{}}}}var y6e={name:"deliver",timeoutMinutes:5,execute:$Se,validateInput:e=>{let t=aD(e);return t?{ok:!1,reasons:[t]}:vSe(e)},requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var b9e=10*6e4,w9e=4*6e4;var I9e=10*6e4;var GSe=3e4,zSe=3,s6=30,$a=class extends Error{constructor(n,s,r,i){super(n);this.status=s;this.code=r;this.path=i}status;code;path},wi=class extends Error{},Xd=class extends wi{},Ow=class extends Xd{};function HSe(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 qSe(e,t){if(!ql.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}function JSe(e,t,n,s){throw t<500&&t!==429?new $a(e,t,n,s):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new Ow(e):t===503&&n==="RUN_NOT_READY"?new Xd(e):new wi(e)}async function WSe(e,t,n,s,r,i=1/0){let o=HSe(e.origin),a=`The time limit for ${t} ${n} was reached`,c,u=0;for(let l=1;l<=zSe||c instanceof Xd;l+=1){if(c instanceof Xd){if(u===s6)throw c;u+=1,l-=1,e.log?.(`${c.message}; trying again (${u} of ${s6}).`),await new Promise(p=>setTimeout(p,Math.max(0,Math.min(e.readyWaitMs??1e4,i-Date.now()))))}else l>1&&await new Promise(p=>setTimeout(p,Math.max(0,Math.min((e.retryDelayMs??2e3)*(l-1),i-Date.now()))));if(Date.now()>=i)throw new wi(a);try{let p,h=await(Number.isFinite(i)?Promise.race([e.idToken(o),new Promise((m,y)=>{p=setTimeout(()=>y(new wi(a)),Math.max(1,i-Date.now()))})]).finally(()=>{p&&clearTimeout(p)}):e.idToken(o));if(Date.now()>=i)throw new wi(a);let g=await(e.fetch??fetch)(new URL(n,o).toString(),{...s(h),redirect:"error",signal:AbortSignal.timeout(Math.max(1,Math.min(GSe,i-Date.now())))}).catch(m=>{throw new wi(m instanceof Error?m.message:String(m),{cause:m})});return await r(g)}catch(p){if(p instanceof $a||Date.now()>=i)throw p;c=p}}throw c}function YSe(e,t,n,s,r){let i=s.headers.get("cf-ray");e.log?.(`Testbot V3: ${t} ${n} answered ${s.status}${i?`, cf-ray ${i}`:""}: ${r.replace(/\s+/g," ").slice(0,200)}`)}var Uw=class extends Error{};function ZSe(e){let t=Buffer.byteLength(e,"utf8");if(t<=_R)return{body:e};if(t>NG)throw new Uw("The report exceeds the app's 16 MiB expanded report limit");let n=new Uint8Array((0,a6.gzipSync)(e));if(n.length>_R)throw new Uw("The compressed report exceeds the app's 1 MiB report upload limit");return{body:n,gzip:!0}}function KSe(e,t,n,s,r){let i=t==="GET"?void 0:JSON.stringify(s),o=t==="PUT"&&/^\/api\/v1\/runner\/attempts\/[^/]+\/report$/.test(n)&&i!==void 0?ZSe(i):{body:i};return XSe(e,t,n,o,r)}function XSe(e,t,n,s,r){return WSe(e,t,n,o=>({method:t,headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json",Accept:"application/json",...s.gzip?{"Content-Encoding":"gzip"}:{}},body:s.body}),async o=>{let a=await o.text().catch(()=>""),c={};try{c=JSON.parse(a)}catch{}if(o.ok)return c.data;YSe(e,t,n,o,a);let u=c.error?.fields,l=typeof u?.path=="string"&&typeof u.reason=="string"?` at ${u.path}: ${u.reason}`:"",p=`The Skyramp app refused ${t} ${n}: ${o.status} ${c.error?.code??"no error code"}${l}`;return JSe(p,o.status,c.error?.code,typeof u?.path=="string"?u.path:void 0)},r)}var C9e=10*6e4;var S9e=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var k9e=d.object({tests:d.object({placements:d.array(d.unknown()).optional()}).passthrough().optional()}).passthrough(),R9e=d.object({repository:QR,testType:d.string(),directory:d.string()}).passthrough();var B9e=d.object({report:d.object({language:d.string()}).passthrough()}).passthrough();var x9e=d.object({environment:d.object({components:d.array(d.unknown()).optional(),dependencies:d.array(d.unknown()).optional()}).passthrough()}).passthrough(),Q9e=d.object({environment:d.object({offLimits:d.unknown().optional()}).passthrough()}).passthrough();var $9e=d.object({environment:d.object({allowedEgress:d.unknown().optional()}).passthrough()}).passthrough();var T9e=d.object({name:d.string().min(1),provision:d.literal("existing"),url:d.string().min(1),repository:QR.optional(),revisionUrl:d.string().min(1).optional()}).passthrough(),_9e=d.object({name:d.string().min(1),url:d.string().nullable(),versionUrl:d.string().nullable(),notes:d.string().nullable()}).passthrough();var D9e=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);var N9e={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};async function c6(e,t){return qSe(e.attemptId,"attempt id"),KSe(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,iz({reportUploaded:e.reportUploaded,recipeUploaded:e.recipeUploaded,revisionsUploaded:e.revisionsUploaded,cancelled:e.cause==="cancelled",timedOut:e.cause==="timed_out",setupFailed:e.cause==="setup_failed",checkoutFailed:e.cause==="checkout_failed"||e.cause==="merge_conflict"&&!e.conflict,mergeConflict:e.cause==="merge_conflict"?e.conflict:void 0,environmentUnverified:e.cause==="environment_unverified",runnerProviderNotReady:e.cause==="runner_provider_not_ready",credentialMissing:e.cause==="credential_missing",modelProviderDenied:e.cause==="model_provider_denied",modelProviderUnavailable:e.cause==="model_provider_unavailable",githubWrites:e.githubWrites,environmentUnavailable:e.cause==="environment_unavailable"}))}var Kg=Z(require("fs")),Ii=Z(require("path")),u6=require("child_process");var ep=Ii.join(".skyramp","sut");function eke(e){return e.startsWith(`${ep}${Ii.sep}`)||e.startsWith(".skyramp/sut/")||/(^|\/)(docker-compose|compose)[^/]*\.ya?ml$/.test(e)||/(^|\/)Dockerfile[^/]*$/.test(e)||/^\.github\/workflows\//.test(e)}function DD(e,t,n={}){let s=t.split(/[\\/]+/).filter(Boolean),r=e;for(let[i,o]of s.entries()){r=Ii.join(r,o);let a=Kg.lstatSync(r,{throwIfNoEntry:!1}),c=i===s.length-1;if(!a||a.isSymbolicLink()||(c?n.directory?!a.isDirectory():!a.isFile():!a.isDirectory()))return}return s.length?r:void 0}function ku(e,t=[]){let n=p=>DD(e,p),s=n(Ii.join(ep,"setup.sh")),r=n(Ii.join(ep,"teardown.sh")),i=n(Ii.join(ep,"get-auth-token.sh")),o,a=n(Ii.join(ep,"health.json"));if(a)try{let p=JSON.parse(Kg.readFileSync(a,"utf-8"));p&&(p.url||p.command)&&(o=p)}catch{}let c,u=n(Ii.join(ep,"deploy-budget.json"));if(u)try{let p=JSON.parse(Kg.readFileSync(u,"utf-8"));typeof p?.minutes=="number"&&Number.isFinite(p.minutes)&&p.minutes>0&&(c=p.minutes)}catch{}let l=t.filter(eke);return{setupScript:s,teardownScript:r,authTokenScript:i,healthHint:o,budgetMinutes:c,present:!!(s||a),staleFiles:l,stale:l.length>0}}var l6=12e4;function Fw(e,t,n){let s=n.timeoutMs??l6;if(n.signal?.aborted)return Promise.resolve(`${e.label} failed (cancelled)`);let r=o=>rh(tn(o,n.secretValues??[])),i;try{i=xs(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,l,p;try{p=(0,u6.spawn)(i.argv[0],i.argv.slice(1),{cwd:t,env:i.env,stdio:["ignore","pipe","pipe"],detached:!0})}catch(C){let I=C instanceof Error?C.message:String(C);o(r(`${e.label} failed (could not start: ${I})`));return}let h=C=>{let I=Math.max(0,...(n.secretValues??[]).map(x=>x.length));a=(a+C.toString("utf-8")).slice(-(4096+I))},g=()=>r(HR(a,n.secretValues??[],4096));p.stdout?.on("data",h),p.stderr?.on("data",h);let m=()=>{try{p.pid!==void 0&&process.kill(-p.pid,"SIGKILL")}catch{p.kill("SIGKILL")}},y=C=>{let I=g().trim().split(`
254
+ `).pop()?.trim().slice(0,300)??"";return`${e.label} failed (${C})${I?`: ${I}`:""}`},v=C=>{u||(u=!0,clearTimeout(b),clearTimeout(l),n.signal?.removeEventListener("abort",E),C!==void 0&&m(),p.stdout?.destroy(),p.stderr?.destroy(),Vo(t,C===void 0?0:1),o(C===void 0?void 0:r(C)))},E=()=>v(y("cancelled")),b=setTimeout(()=>{c=!0,v(y(`timed out after ${s/1e3} s`))},s);n.signal?.addEventListener("abort",E,{once:!0}),n.signal?.aborted&&E();let w=(C,I)=>{if(c)return y(`timed out after ${s/1e3} s`);if(C!==0)return y(C===null?`killed by ${I}`:`exit ${C}`)};p.on("error",C=>v(y(`could not start: ${C.message}`))),p.on("close",(C,I)=>v(w(C,I))),p.on("exit",(C,I)=>{u||(C!==0?v(w(C,I)):l=setTimeout(()=>v(w(C,I)),1e3))})})}var d6=".skyramp/sut/health.json",X9e={[d6]:`${d6} (with a url or command)`};function ND(e,t){return!$f(e.status)||e.environment?[]:[...new Set(e.components.flatMap(n=>n.credentials??[]))].filter(n=>!x4(n,t))}function p6(e){let t=e.filter(vf),n=e.filter(s=>!vf(s));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 Mw(e){if(e.state.stages.onboard?.status==="passed")return Se(e,"onboard.json")}function ske(e){let t=Ld(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 ike=90,oke={CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",CLAUDE_BYTE_STREAM_IDLE_TIMEOUT_MS:String(ike*1e3)},f6=30,h6={BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:String(f6*6e4)},g6=["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 ${f6}`,"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 ake(e,t){return ske(ht(e,{...oke,...t},"session"))}function PD(e){return ake(process.env,e)}var jw=Z(require("fs")),Xg=Z(require("path"));var m6=["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"],d3e=[...m6,"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 p3e=["skyramp_ui_test_generation","skyramp_mock_generation","skyramp_fix_errors","skyramp_start_trace_collection","skyramp_stop_trace_collection","skyramp_export_zip",...m6];var A6=["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 Lw=Z(require("fs"));var uke={name:"output-produced",verify(e,t,n){let s=e.outputFileFor(n.name);return(Lw.existsSync(s)?Lw.readFileSync(s,"utf-8"):"").trim().length>0?{name:this.name,passed:!0}:{name:this.name,passed:!1,details:`stage produced no output (${s} empty or missing)`}}},lke=["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 y6(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??lke,exitGates:e.exitGates??[uke],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 dke=["Bash(docker:*)","Bash(docker compose:*)","Bash(docker-compose:*)","Bash(bash:*)","Bash(sh:*)","Bash(.skyramp/sut/*)","Bash(./.skyramp/sut/*)","Bash(curl:*)","Bash(sleep:*)",...A6,"Read","Write","Edit"];function pke(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=_s(e),s=Mw(e);if(s?.status==="blocked")return{ok:!1,reasons:[`onboarding reported blocked (${s.blockers.length} blocker(s)) \u2014 see outputs/onboard.json`]};let r=e.inputs.setupEvents&&t?.status==="passed"&&s&&!e.inputs.recheck?ND(s,PD()):[];return r.length>0?{ok:!1,reasons:[`the recipe reads ${r.join(", ")}: ${p6(r)} \u2014 deploy waits for the check Skyramp runs once the setup ends`]}:n&&!n.sutRequired&&!(s&&$f(s.status))&&!e.inputs.recheck?{ok:!1,reasons:["preflight determined no SUT is required (non-application change)"]}:ku(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 fke(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 hke(e){let t=_s(e);return{recipe:ku(e.inputs.repositoryPath,t?.changedFiles.map(s=>s.path))}}function gke(e,t){return[t.setupScript,t.teardownScript,t.authTokenScript].filter(n=>!!n).map(n=>Xg.relative(e,n))}function mke(e,t="revisions"){let n=iw(e.inputs);return n.length===0?[]:["","Shared components: these run in an existing environment that this run does not deploy.",...n.map(s=>` - ${s.name} at ${s.url}, running ${s.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 OD(e){return Mw(e)?.environment??e.inputs.recheckEnvironment}function Ake(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 yke(e){let t=Mw(e),n=e.inputs.recheck?e.inputs.recheckCredentials??[]:t?hR(t):[];if(n.length===0)return[];let s=e.inputs.sharedEnvironment,r=bf(s).map(i=>i.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.`]:[],...Eke(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 Eke=e=>!!(e.inputs.recheck||e.inputs.setupEvents);function vke(e){let{recipe:t}=e.prepared,n=e.inputs.repositoryPath,s=gke(n,t),r=OD(e),i=e.inputs.sharedEnvironment,o=bf(i).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: ${s.join(", ")||"(workspace only)"}`,"",...g6,t.stale?`
255
255
  STALENESS WARNING: this PR changed recipe/infra files (${t.staleFiles.join(", ")}).
256
256
  The recorded recipe may no longer match. If bring-up fails, first decide
257
257
  WHY: recipe drift (infra moved, recipe is behind) vs the change itself
258
258
  breaking bring-up. Do NOT paper over a PR that broke the app.`:"","",...r?Ake(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".'],...mke(e),...yke(e),"","Output: end with one JSON object matching:","",dz(Nf)," // 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(`
259
- `)}function v6(e){let t=Xg.join(e.outputsDir,"deploy.txt");if(jw.existsSync(t)){let{deploy:s}=mu({exitCode:0,stdout:jw.readFileSync(t,"utf-8"),stderr:"",timedOut:!1,durationMs:0});if(s?.teardown)return{argv:["sh","-c",s.teardown],label:"deploy.json's teardown"}}let{teardownScript:n}=ku(e.inputs.repositoryPath);if(n)return{argv:["bash",n],label:Xg.join(".skyramp","sut","teardown.sh")}}function b6(e,t){return Fw(t,e.inputs.repositoryPath,{env:ht(),secretValues:e.secretValues})}async function E6(e){let t=v6(e);if(t){let n=await b6(e,t);if(n&&r4(e))throw new Error(`SUT teardown failed: ${n}`)}}async function bke(e,t){let n=t.passed?void 0:w6(e);if(!n)return;let s=await b6(e,n);return s&&`${s} (if nothing was running, a teardown must exit 0)`}function w6(e){return OD(e)?void 0:v6(e)}function wke(e){if(w6(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 Ike(e,t){let{deploy:n}=mu(t,e.inputs.repositoryPath,e.secretValues);if(!n)return;if(n.outcome==="bringup-failed"){let r=tn(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 s=Cg(e).map(r=>r.name);if(s.length)return`the shared environment's ${s.join(", ")} does not verifiably run the revision under validation \u2014 no runtime test runs against it`}var I6=y6({name:"deploy",model:"opus",timeoutMinutes:25,requires:["preflight"],softRequires:["onboard"],startsApp:e=>!e.inputs.appRunning&&!(e.inputs.testEnvironment&&OD(e)),triageBranch:"runtime",validateInput:pke,prepare:hke,scaleTimeout:fke,buildPrompt:vke,allowedTools:dke,buildSessionEnv:()=>({...h6}),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:[cw(),eZ()],onPassed:async(e,t)=>({...nZ(e,t),...await tZ(e,t)}),passReason:Ike,afterAttempt:bke,retryNote:wke,onAbort:E6,teardown:E6});$n();$n();var Y3e=20*1024*1024;var S6=Z(require("path"));var o8e=S6.join(".skyramp","sut","get-auth-token.sh");var UD="\\$([A-Z][A-Z0-9_]{0,99})",a8e=new RegExp(`^${UD}$`),c8e=new RegExp(`^${UD}:${UD}$`);var aXe=3*6e4;var cXe=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;var Bke={discover:"reading the repositories",start:"starting the components",check:"checking that the components answer"};var AXe={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 yXe=new RegExp(Wl.source,"g");var FXe=new RegExp(Wl.source,"g");var $ke="https://testbot.skyramp.dev",po={attemptId:"v3AttemptId",deadlineAt:"v3DeadlineAt",reportUploaded:"v3ReportUploaded",recipeUploaded:"v3RecipeUploaded",recipeStatus:"v3RecipeStatus",revisionsUploaded:"v3RevisionsUploaded",cause:"v3Cause",conflict:"v3Conflict",githubWrites:"v3GithubWrites"};function Tke(e,t,n){return{origin:e,idToken:t,sourceToken:n,mask:s=>Ui(s),log:s=>Rs(s),onTokenRefused:(s,r)=>{Dke(s)&&k6.set(r,s)},onTokenGranted:s=>{k6.delete(s)}}}var k6=new Map;var Eet=["setup_failed","checkout_failed","environment_unverified"];function _ke(e,t){return t.getTime()>=e.getTime()}function Dke(e){return e instanceof wi||e instanceof $a&&e.code!=="CREDENTIALS_UNAVAILABLE"}var vet={cancelled:"Skyramp cancelled this run",expired:"this attempt passed its deadline in Skyramp",ended:"Skyramp already ended this attempt"},bet={cancelled:"attempt-cancelled",expired:"attempt-closed",ended:"attempt-closed"},wet={cancelled:"cancelled",expired:"timed_out",ended:"agent_failed"};var Iet={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"},Cet={analyze:"change analysis",recommend:"test recommendations",generate:"test generation",execute:"test execution",deliver:"opening a pull request with the tests"};function Nke(){return je("skyrampAppOrigin").trim()||$ke}var ket=10*6e4;var Ret={onboard:"onboard",deploy:"deploy"},Bet={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"}},xet=new Set(["write","native-run"]);function Pke(){let e=ei(po.conflict);if(!e)return;let t;try{t=sz.safeParse(JSON.parse(e))}catch(n){Ot(`Testbot V3: the saved merge conflict is not JSON (${n instanceof Error?n.message:String(n)})`);return}if(t.success)return t.data;Ot(`Testbot V3: the saved merge conflict breaks the contract (${t.error.issues.map(n=>`${n.path.join(".")}: ${n.message}`).join("; ")})`)}function Oke(){let e=ei(po.githubWrites);if(!e)return[];let t;try{t=JSON.parse(e)}catch(n){return Ot(`Testbot V3: the saved GitHub writes are not JSON (${n instanceof Error?n.message:String(n)})`),[]}return Array.isArray(t)?t.flatMap(n=>{let s=EE.safeParse(n);return s.success?[s.data]:[]}).slice(0,yE):[]}async function R6(){let e=ei(po.attemptId);if(!e)return;let t=ei(po.reportUploaded)==="true",n=ei(po.recipeUploaded)==="true",s=ei(po.revisionsUploaded)==="true",r=ei(po.deadlineAt),i=ei(po.cause)||void 0;!i&&!t&&!n&&!s&&r&&_ke(new Date(r),new Date)&&(i="timed_out");let o=Ld().takeIdToken(),a=Pke(),c=await c6({attemptId:e,reportUploaded:t,recipeUploaded:n,revisionsUploaded:s,cause:i,...a?{conflict:a}:{},githubWrites:Oke()},Tke(Nke(),o)),u=ei(po.recipeStatus);n&&u?Rs(`Testbot V3: attempt ended; the setup ended ${u==="ready"?"Ready":"blocked (Needs input)"}.`):Rs(`Testbot V3: attempt ended; the run's outcome in Skyramp is ${c.outcome??"not final yet"}.`)}var B6=require("child_process"),Ci=Z(require("fs")),MD=Z(require("path")),LD=require("string_decoder");var Uke="skyramp-testbot-state",Fke=/^\$\([^)]*\)$/;function Mke(e){for(let[t,n]of Object.entries(e))n!==void 0&&Fke.test(n)&&delete e[t]}function Lke(e){let t={},n=Ci.existsSync(e)?Ci.readFileSync(e,"utf-8"):"",s=/^([^\r\n<]+)<<(\S+)\r?\n([\s\S]*?)\r?\n\2\r?$/gm;for(let r=s.exec(n);r;r=s.exec(n))t[r[1]]=r[3];return t}function x6(e,t={}){let n=t.env??process.env;if(!va(n))return!1;Mke(n),A4(n);let s=n.AGENT_TEMPDIRECTORY||n.RUNNER_TEMP;if(s){n.RUNNER_TEMP??=s;let o=MD.join(s,Uke);if(e==="main")Ci.writeFileSync(o,"",{mode:384});else for(let[a,c]of Object.entries(Lke(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]=MD.join(s,`skyramp-testbot-${c}`),Ci.writeFileSync(n[a],"",{mode:384})}let r=t.stdout??n===process.env;r&&jke(n,t.write);let i=n.GITHUB_STEP_SUMMARY;if(r&&i){let o=t.write??(a=>g_(a.replace(/\n$/,"")));process.once("exit",()=>{Ci.existsSync(i)&&Ci.statSync(i).size>0&&o(`${Jb("task.uploadsummary",{},i)}
259
+ `)}function v6(e){let t=Xg.join(e.outputsDir,"deploy.txt");if(jw.existsSync(t)){let{deploy:s}=mu({exitCode:0,stdout:jw.readFileSync(t,"utf-8"),stderr:"",timedOut:!1,durationMs:0});if(s?.teardown)return{argv:["sh","-c",s.teardown],label:"deploy.json's teardown"}}let{teardownScript:n}=ku(e.inputs.repositoryPath);if(n)return{argv:["bash",n],label:Xg.join(".skyramp","sut","teardown.sh")}}function b6(e,t){return Fw(t,e.inputs.repositoryPath,{env:ht(),secretValues:e.secretValues})}async function E6(e){let t=v6(e);if(t){let n=await b6(e,t);if(n&&r4(e))throw new Error(`SUT teardown failed: ${n}`)}}async function bke(e,t){let n=t.passed?void 0:w6(e);if(!n)return;let s=await b6(e,n);return s&&`${s} (if nothing was running, a teardown must exit 0)`}function w6(e){return OD(e)?void 0:v6(e)}function wke(e){if(w6(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 Ike(e,t){let{deploy:n}=mu(t,e.inputs.repositoryPath,e.secretValues);if(!n)return;if(n.outcome==="bringup-failed"){let r=tn(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 s=Cg(e).map(r=>r.name);if(s.length)return`the shared environment's ${s.join(", ")} does not verifiably run the revision under validation \u2014 no runtime test runs against it`}var I6=y6({name:"deploy",model:"opus",timeoutMinutes:25,requires:["preflight"],softRequires:["onboard"],startsApp:e=>!e.inputs.appRunning&&!(e.inputs.testEnvironment&&OD(e)),triageBranch:"runtime",validateInput:pke,prepare:hke,scaleTimeout:fke,buildPrompt:vke,allowedTools:dke,buildSessionEnv:()=>({...h6}),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:[cw(),eZ()],onPassed:async(e,t)=>({...nZ(e,t),...await tZ(e,t)}),passReason:Ike,afterAttempt:bke,retryNote:wke,onAbort:E6,teardown:E6});$n();$n();var Z3e=20*1024*1024;var S6=Z(require("path"));var a8e=S6.join(".skyramp","sut","get-auth-token.sh");var UD="\\$([A-Z][A-Z0-9_]{0,99})",c8e=new RegExp(`^${UD}$`),u8e=new RegExp(`^${UD}:${UD}$`);var cXe=3*6e4;var uXe=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;var Bke={discover:"reading the repositories",start:"starting the components",check:"checking that the components answer"};var yXe={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 EXe=new RegExp(Wl.source,"g");var MXe=new RegExp(Wl.source,"g");var $ke="https://testbot.skyramp.dev",po={attemptId:"v3AttemptId",deadlineAt:"v3DeadlineAt",reportUploaded:"v3ReportUploaded",recipeUploaded:"v3RecipeUploaded",recipeStatus:"v3RecipeStatus",revisionsUploaded:"v3RevisionsUploaded",cause:"v3Cause",conflict:"v3Conflict",githubWrites:"v3GithubWrites"};function Tke(e,t,n){return{origin:e,idToken:t,sourceToken:n,mask:s=>Ui(s),log:s=>Rs(s),onTokenRefused:(s,r)=>{Dke(s)&&k6.set(r,s)},onTokenGranted:s=>{k6.delete(s)}}}var k6=new Map;var vet=["setup_failed","checkout_failed","environment_unverified"];function _ke(e,t){return t.getTime()>=e.getTime()}function Dke(e){return e instanceof wi||e instanceof $a&&e.code!=="CREDENTIALS_UNAVAILABLE"}var bet={cancelled:"Skyramp cancelled this run",expired:"this attempt passed its deadline in Skyramp",ended:"Skyramp already ended this attempt"},wet={cancelled:"attempt-cancelled",expired:"attempt-closed",ended:"attempt-closed"},Iet={cancelled:"cancelled",expired:"timed_out",ended:"agent_failed"};var Cet={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"},ket={analyze:"change analysis",recommend:"test recommendations",generate:"test generation",execute:"test execution",deliver:"opening a pull request with the tests"};function Nke(){return je("skyrampAppOrigin").trim()||$ke}var Ret=10*6e4;var Bet={onboard:"onboard",deploy:"deploy"},xet={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"}},Qet=new Set(["write","native-run"]);function Pke(){let e=ei(po.conflict);if(!e)return;let t;try{t=sz.safeParse(JSON.parse(e))}catch(n){Ot(`Testbot V3: the saved merge conflict is not JSON (${n instanceof Error?n.message:String(n)})`);return}if(t.success)return t.data;Ot(`Testbot V3: the saved merge conflict breaks the contract (${t.error.issues.map(n=>`${n.path.join(".")}: ${n.message}`).join("; ")})`)}function Oke(){let e=ei(po.githubWrites);if(!e)return[];let t;try{t=JSON.parse(e)}catch(n){return Ot(`Testbot V3: the saved GitHub writes are not JSON (${n instanceof Error?n.message:String(n)})`),[]}return Array.isArray(t)?t.flatMap(n=>{let s=EE.safeParse(n);return s.success?[s.data]:[]}).slice(0,yE):[]}async function R6(){let e=ei(po.attemptId);if(!e)return;let t=ei(po.reportUploaded)==="true",n=ei(po.recipeUploaded)==="true",s=ei(po.revisionsUploaded)==="true",r=ei(po.deadlineAt),i=ei(po.cause)||void 0;!i&&!t&&!n&&!s&&r&&_ke(new Date(r),new Date)&&(i="timed_out");let o=Ld().takeIdToken(),a=Pke(),c=await c6({attemptId:e,reportUploaded:t,recipeUploaded:n,revisionsUploaded:s,cause:i,...a?{conflict:a}:{},githubWrites:Oke()},Tke(Nke(),o)),u=ei(po.recipeStatus);n&&u?Rs(`Testbot V3: attempt ended; the setup ended ${u==="ready"?"Ready":"blocked (Needs input)"}.`):Rs(`Testbot V3: attempt ended; the run's outcome in Skyramp is ${c.outcome??"not final yet"}.`)}var B6=require("child_process"),Ci=Z(require("fs")),MD=Z(require("path")),LD=require("string_decoder");var Uke="skyramp-testbot-state",Fke=/^\$\([^)]*\)$/;function Mke(e){for(let[t,n]of Object.entries(e))n!==void 0&&Fke.test(n)&&delete e[t]}function Lke(e){let t={},n=Ci.existsSync(e)?Ci.readFileSync(e,"utf-8"):"",s=/^([^\r\n<]+)<<(\S+)\r?\n([\s\S]*?)\r?\n\2\r?$/gm;for(let r=s.exec(n);r;r=s.exec(n))t[r[1]]=r[3];return t}function x6(e,t={}){let n=t.env??process.env;if(!va(n))return!1;Mke(n),A4(n);let s=n.AGENT_TEMPDIRECTORY||n.RUNNER_TEMP;if(s){n.RUNNER_TEMP??=s;let o=MD.join(s,Uke);if(e==="main")Ci.writeFileSync(o,"",{mode:384});else for(let[a,c]of Object.entries(Lke(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]=MD.join(s,`skyramp-testbot-${c}`),Ci.writeFileSync(n[a],"",{mode:384})}let r=t.stdout??n===process.env;r&&jke(n,t.write);let i=n.GITHUB_STEP_SUMMARY;if(r&&i){let o=t.write??(a=>g_(a.replace(/\n$/,"")));process.once("exit",()=>{Ci.existsSync(i)&&Ci.statSync(i).size>0&&o(`${Jb("task.uploadsummary",{},i)}
260
260
  `)})}return!0}function jke(e,t){let n=process.stdout.write.bind(process.stdout),s=o=>e[hg]==="1"?h_(o,e):void n(o.command!==void 0?`${o.command}
261
261
  `:o.text??""),r=t??(o=>s({command:o.replace(/\n$/,"")})),i=t??(o=>s({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("::")?l4(p):void 0;if(!h){u+=p;continue}u&&i(u),u="";for(let g of h)r(`${g}
262
262
  `)}return u&&i(u),a.find(p=>typeof p=="function")?.(),!0})}var Vke=64*1024;function FD(e){let t=new LD.StringDecoder("utf8"),n="",s=r=>e(qb(r));return{push(r){n+=typeof r=="string"?r:t.write(r);let i=n.lastIndexOf(`