@skyramp/testbot-core 0.13.3-v3.555 → 0.13.3-v3.556
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/VERSION.json +1 -1
- package/dist/main.js +514 -514
- package/dist/post.js +8 -8
- package/dist/runner-client.cjs +4 -4
- package/package.json +1 -1
package/dist/post.js
CHANGED
|
@@ -267,7 +267,7 @@ else require("node:test").test(spec.name, () => { throw new Error("required shar
|
|
|
267
267
|
`)+1||r.length),o=r6(i);for(let a of n)o.delete(a);return{name:fz(s.key,ZD([s])),key:s.key,runs:o,words:KD(i).map(a=>a.word)}})}var xze=cm/2;var aSe=e=>e.criteria.size?`${e.text.name} ${[...e.criteria].sort((t,n)=>t-n).map(t=>`AC${t}`).join(", ")}`:e.text.name,cSe=new RegExp("(?<![\\p{L}\\p{N}])\\p{L}[\\p{L}\\p{N}+.-]*:\\/\\/(?:[^\\s\"'`<>|\\u2018\\u2019\\u201C\\u201D\\u3000-\\u303F\\uFF01-\\uFF0F\\uFF1A-\\uFF20]|<[\\p{L}\\p{N}_-]+>)*(?:[^\\s\"'`<>|\\u2018\\u2019\\u201C\\u201D\\u3000-\\u303F\\uFF01-\\uFF0F\\uFF1A-\\uFF20.,;:!?)\\]]|<[\\p{L}\\p{N}_-]+>)","gu");function uSe(e){let t=[...e.matchAll(cSe)].map(s=>({start:s.index,end:s.index+s[0].length})),n=[[]];for(let s of KD(e))t.some(r=>s.start>=r.start&&s.start<r.end)?n.at(-1).length&&n.push([]):n.at(-1).push(s);return n}function lSe(e,t){if(t.length===0)return[];let n=[];for(let s of uSe(e))for(let r=0;r+cm<=s.length;r++){let i=a6(s,r),o=t.find(p=>p.runs.has(i));if(!o)continue;let a=s[r].start,c=s[r+cm-1].end,u=o.criteria?.get(i)??[],d=n.at(-1);if(d&&a<=d.end){if(d.end=Math.max(d.end,c),d.text===o)for(let p of u)d.criteria.add(p)}else n.push({start:a,end:c,text:o,criteria:new Set(u)})}return n.map(s=>({start:s.start,end:s.end,name:aSe(s)}))}function ap(e,t,n=!1){let s=e;for(let r of lSe(e,t).reverse()){let i=s.slice(0,r.start).trimEnd(),o=i===""||/[.!?\n]$/.test(s.slice(0,r.start).replace(/[ \t]+$/,"")),c=n&&(o||/[:;—–-]$/.test(i))&&/^\s+[\p{L}\d]/u.test(s.slice(r.end))?`${o?"The":"the"} case (see ${r.name})`:`(see ${r.name})`;s=`${s.slice(0,r.start)}${c}${s.slice(r.end)}`}return s}function dSe(e,t,n){for(let s=t+1;s<e.length;s++){let r=e[s];if(r==="\\")s++;else{if(r===n)return s+1;if(r===`
|
|
268
268
|
`&&n!=="`")return s}}return e.length}function pSe(e,t){let n=e.lastIndexOf(`
|
|
269
269
|
`,t-1)+1;if(e.slice(n,t).trim()!=="")return!1;let s=e.slice(0,n).trimEnd();return s===""||s.endsWith(":")}function fSe(e){let t=[],n=r=>(e.indexOf(`
|
|
270
|
-
`,r)+1||e.length+1)-1,s=0;for(;s<e.length;){let r=e[s],i=e[s+1],o=s+1;if(r==="/"&&i==="*")o=e.indexOf("*/",s+2)<0?e.length:e.indexOf("*/",s+2)+2,t.push({start:s,end:o});else if(r==="/"&&i==="/"&&!/[:\w]/.test(e[s-1]??"")||r==="#"&&/^\s?$/.test(e[s-1]??"")&&!/[!{[]/.test(i??""))o=n(s),t.push({start:s,end:o});else if((r==='"'||r==="'")&&e.startsWith(r.repeat(3),s)){let a=e.indexOf(r.repeat(3),s+3);o=a<0?e.length:a+3,pSe(e,s)&&t.push({start:s,end:o})}else(r==='"'||r==="'"||r==="`")&&(o=dSe(e,s,r));s=o}return t}var hSe=/\b(?:test|it|describe|context|suite|scenario|specify|Run|DisplayName)(?:\.\w+)*(?:\.each\s*(?:\((?:[^()]|\([^()]*\))*\)|`[^`]*`))?\s*\(\s*("(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`)/g;function gSe(e,t){return[...e.matchAll(hSe)].flatMap(n=>{if(t.some(r=>n.index>=r.start&&n.index<r.end))return[];let s=n.index+n[0].length;return[{start:s-n[1].length,end:s}]})}function Qu(e,t){if(t.length===0)return{content:e,cleaned:!1};let n=fSe(e),s=[];for(let a of n){let c=e.slice(a.start,a.end),u=ap(c,t);u!==c&&s.push({...a,text:u})}let r=gSe(e,n),i=new Set(r.map(a=>e.slice(a.start+1,a.end-1)));for(let a of r){let c=e[a.start],u=e.slice(a.start+1,a.end-1),d=ap(u,t);if(d===u)continue;let p=d;for(let h=2;i.has(p);h++)p=`${d} (${h})`;i.add(p),s.push({...a,text:`${c}${p}${c}`})}let o=e;for(let a of s.sort((c,u)=>u.start-c.start))o=`${o.slice(0,a.start)}${a.text}${o.slice(a.end)}`;return{content:o,cleaned:o!==e}}var Yze=new Set(["requirement-reference","spec","pr-description"]);var um="generate-unit.json";function bSe(e){let{value:t,error:n}=Yt(e);if(n)return{errors:[n]};let{value:s,errors:r}=Vn(YD,t);return r.length?{errors:r}:{output:s,errors:[]}}function wSe(e){return bSe(e.stdout)}var Tqe=Ir("generate-unit-schema",(e,t)=>wSe(t));var Fw=String.raw`(?:node:)?(?:http|https|http2|net|tls|dgram)`,Qqe=[[/\b(localhost|127\.0\.0\.1|0\.0\.0\.0)\b/,"a local server address"],[/^\s*(import|from)\s+(requests|aiohttp|urllib3|websockets?)\b/m,"an HTTP client"],[/^\s*(?:import|from)\s+(?:urllib\.request|http\.client|http\.server|socket|ssl|ftplib|smtplib|telnetlib)\b|^\s*from\s+urllib\s+import\b[^\n]*\brequest\b|\burlopen\s*\(/m,"a standard-library network client"],[/\bfrom\s+["'](axios|node-fetch|undici|ws)["']|require\(\s*["'](axios|node-fetch|undici|ws)["']\s*\)/,"an HTTP client"],[new RegExp(String.raw`\bfrom\s+["']${Fw}["']|\bimport\s+["']${Fw}["']|require\(\s*["']${Fw}["']\s*\)|\bimport\(\s*["']${Fw}["']\s*\)`),"Node's network modules"],[/\bfetch\s*\(|\bnew\s+(XMLHttpRequest|WebSocket)\b/,"a network call (fetch, XMLHttpRequest, WebSocket)"],[/\bskyramp\b/i,"the Skyramp runtime (a runtime mock or client)"]];var Xqe=new Set(["targeted_unit","existing_evidence_sufficient"]);var BSe="triage.json";var
|
|
270
|
+
`,r)+1||e.length+1)-1,s=0;for(;s<e.length;){let r=e[s],i=e[s+1],o=s+1;if(r==="/"&&i==="*")o=e.indexOf("*/",s+2)<0?e.length:e.indexOf("*/",s+2)+2,t.push({start:s,end:o});else if(r==="/"&&i==="/"&&!/[:\w]/.test(e[s-1]??"")||r==="#"&&/^\s?$/.test(e[s-1]??"")&&!/[!{[]/.test(i??""))o=n(s),t.push({start:s,end:o});else if((r==='"'||r==="'")&&e.startsWith(r.repeat(3),s)){let a=e.indexOf(r.repeat(3),s+3);o=a<0?e.length:a+3,pSe(e,s)&&t.push({start:s,end:o})}else(r==='"'||r==="'"||r==="`")&&(o=dSe(e,s,r));s=o}return t}var hSe=/\b(?:test|it|describe|context|suite|scenario|specify|Run|DisplayName)(?:\.\w+)*(?:\.each\s*(?:\((?:[^()]|\([^()]*\))*\)|`[^`]*`))?\s*\(\s*("(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`)/g;function gSe(e,t){return[...e.matchAll(hSe)].flatMap(n=>{if(t.some(r=>n.index>=r.start&&n.index<r.end))return[];let s=n.index+n[0].length;return[{start:s-n[1].length,end:s}]})}function Qu(e,t){if(t.length===0)return{content:e,cleaned:!1};let n=fSe(e),s=[];for(let a of n){let c=e.slice(a.start,a.end),u=ap(c,t);u!==c&&s.push({...a,text:u})}let r=gSe(e,n),i=new Set(r.map(a=>e.slice(a.start+1,a.end-1)));for(let a of r){let c=e[a.start],u=e.slice(a.start+1,a.end-1),d=ap(u,t);if(d===u)continue;let p=d;for(let h=2;i.has(p);h++)p=`${d} (${h})`;i.add(p),s.push({...a,text:`${c}${p}${c}`})}let o=e;for(let a of s.sort((c,u)=>u.start-c.start))o=`${o.slice(0,a.start)}${a.text}${o.slice(a.end)}`;return{content:o,cleaned:o!==e}}var Yze=new Set(["requirement-reference","spec","pr-description"]);var um="generate-unit.json";function bSe(e){let{value:t,error:n}=Yt(e);if(n)return{errors:[n]};let{value:s,errors:r}=Vn(YD,t);return r.length?{errors:r}:{output:s,errors:[]}}function wSe(e){return bSe(e.stdout)}var Tqe=Ir("generate-unit-schema",(e,t)=>wSe(t));var Fw=String.raw`(?:node:)?(?:http|https|http2|net|tls|dgram)`,Qqe=[[/\b(localhost|127\.0\.0\.1|0\.0\.0\.0)\b/,"a local server address"],[/^\s*(import|from)\s+(requests|aiohttp|urllib3|websockets?)\b/m,"an HTTP client"],[/^\s*(?:import|from)\s+(?:urllib\.request|http\.client|http\.server|socket|ssl|ftplib|smtplib|telnetlib)\b|^\s*from\s+urllib\s+import\b[^\n]*\brequest\b|\burlopen\s*\(/m,"a standard-library network client"],[/\bfrom\s+["'](axios|node-fetch|undici|ws)["']|require\(\s*["'](axios|node-fetch|undici|ws)["']\s*\)/,"an HTTP client"],[new RegExp(String.raw`\bfrom\s+["']${Fw}["']|\bimport\s+["']${Fw}["']|require\(\s*["']${Fw}["']\s*\)|\bimport\(\s*["']${Fw}["']\s*\)`),"Node's network modules"],[/\bfetch\s*\(|\bnew\s+(XMLHttpRequest|WebSocket)\b/,"a network call (fetch, XMLHttpRequest, WebSocket)"],[/\bskyramp\b/i,"the Skyramp runtime (a runtime mock or client)"]];var Xqe=new Set(["targeted_unit","existing_evidence_sufficient"]);var BSe="triage.json";var hHe=new Set(["existing_evidence","unaffected","existing_unit","new_unit","runtime"]),gHe={existing_evidence:"existing evidence",unaffected:"showing the change cannot reach it",existing_unit:"running the existing unit tests",new_unit:"a new unit test",runtime:"tests against the running application"};function xSe(e){let{value:t,error:n}=Yt(e);if(n)return{errors:[n]};let{value:s,errors:r}=Vn(em,t);return r.length?{errors:r}:{triage:s,errors:[]}}function $Se(e){return xSe(e.stdout)}var mHe=Ir("triage-schema",(e,t)=>$Se(t));var AHe={requirements:"this run has no change, so its requirement references set the scope; unchanged code still needs evidence or a gap",instructions:"this run has no change, so its Instructions set the scope; unchanged code still needs evidence or a gap"};function TSe(e){let t=e.inputs?.pipeline;return t?e.state.stages[t==="two-step"?"plan":"triage"]:e.state.stages.triage??e.state.stages.plan}function XD(e){if(TSe(e)?.status==="passed")return js(g6.join(e.outputsDir,BSe))}function eN(e){if(!gw(e))return sK(SD(e.inputs,Ae(e,`${rp}.json`),XD(e)?.sutRequired))}var yHe=new Set(["deploy","recommend","generate","generate-ui","adapt","generate-unit","native-run","finalize","deliver"]);On();On();function m6(e,t){return t?`<!-- skyramp-testbot-run: ${t} -->
|
|
271
271
|
${e}`:e}var y6=600,Lw=300;function A6(e){return typeof e=="string"?e.trim():e instanceof Buffer?e.toString("utf-8").trim():""}function _Se(e){let t=e,n=(typeof t?.message=="string"?t.message:String(e)).trim(),s=[A6(t?.stderr),A6(t?.stdout)].filter(Boolean);return s.length?[n.split(`
|
|
272
272
|
`)[0],...s].join(`
|
|
273
273
|
`):n}function E6(e,t,n,s=0){let r=e.join(t);if(r.length<=n)return r;let[i="",...o]=e;if(!o.length)return`${i.slice(0,n-1)}\u2026`;let a=i.length<=s?i:i.slice(0,Math.floor(n/3)),c=n-a.length-t.length-1;return`${a}${t}\u2026${o.join(t).slice(-c)}`}function v6(e,t){return E6(e.trim().split(`
|
|
@@ -289,19 +289,19 @@ ${n}`}function N6(e){let t=[],n=!1;for(let s of e.split(`
|
|
|
289
289
|
`))/^\s*signed-off-by:/i.test(s)?n=!0:n&&s.trim()===""&&t.at(-1)?.trim()===""||(t.push(s),n=!1);return t.join(`
|
|
290
290
|
`).replace(/\s+$/,"")}function nN(e){let t=/\b(claude|anthropic)\b/i;return e.split(`
|
|
291
291
|
`).filter(s=>{let r=s.trim();return!(/^co-authored-by:/i.test(r)&&t.test(r))&&!(/^[^\w\s]*\s*generated (?:with|by) /i.test(r)&&t.test(r))}).join(`
|
|
292
|
-
`).replace(/\s+$/,"")}var zw="Skyramp-Pull-Request",lp="Skyramp-Delivery-Base",rN="Skyramp-Tested-Revision",sN="Skyramp-Delivery-Run";var
|
|
292
|
+
`).replace(/\s+$/,"")}var zw="Skyramp-Pull-Request",lp="Skyramp-Delivery-Base",rN="Skyramp-Tested-Revision",sN="Skyramp-Delivery-Run";var YHe=["%H","%P","%an","%ae","%ce",`%(trailers:key=${zw},valueonly,separator=%x2C)`,"%s",`%(trailers:key=${lp},valueonly,separator=%x2C)`,`%(trailers:key=${rN},valueonly,separator=%x2C)`,`%(trailers:key=${sN},valueonly,separator=%x2C)`];function iN(e,t){let n=e(["log","-1","--format=%B"]);if(!n.includes(`${zw}:`)&&!n.includes(`${lp}:`))return;let s=n.split(`
|
|
293
293
|
`).filter(o=>!o.startsWith(`${lp}:`)).join(`
|
|
294
294
|
`).trimEnd(),r=t?`${s}
|
|
295
295
|
${lp}: ${t}`:s;e(["log","-1","--format=%(trailers:key=Signed-off-by,valueonly)"]).split(`
|
|
296
|
-
`).some(o=>o.trim().toLowerCase()===`${ao} <${da}>`.toLowerCase())&&(r=Gw(r,{name:ao,email:da})),e(["-c",`user.name=${ao}`,"-c",`user.email=${da}`,"commit","--amend","--allow-empty","-m",r])}var Ma=G(require("fs")),AN=G(require("path"));function Kt(e){let t=Math.max(0,...(e.match(/`+/g)??[]).map(r=>r.length)),n="`".repeat(t+1),s=e.startsWith("`")||e.endsWith("`")?" ":"";return`${n}${s}${e}${s}${n}`}var nI=G(require("fs")),Ht=G(require("path"));var
|
|
296
|
+
`).some(o=>o.trim().toLowerCase()===`${ao} <${da}>`.toLowerCase())&&(r=Gw(r,{name:ao,email:da})),e(["-c",`user.name=${ao}`,"-c",`user.email=${da}`,"commit","--amend","--allow-empty","-m",r])}var Ma=G(require("fs")),AN=G(require("path"));function Kt(e){let t=Math.max(0,...(e.match(/`+/g)??[]).map(r=>r.length)),n="`".repeat(t+1),s=e.startsWith("`")||e.endsWith("`")?" ":"";return`${n}${s}${e}${s}${n}`}var nI=G(require("fs")),Ht=G(require("path"));var PJe=[...zl,"AWS_REGION","AWS_DEFAULT_REGION","AWS_ENDPOINT_URL","AWS_ENDPOINT_URL_BEDROCK_RUNTIME","AWS_ENDPOINT_URL_STS","AWS_SHARED_CREDENTIALS_FILE","AWS_CONFIG_FILE","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BASE_URL","ANTHROPIC_BEDROCK_BASE_URL"].filter((e,t,n)=>n.indexOf(e)===t);var wo=G(Ax());var aN=require("child_process"),dp=G(require("fs")),U6=G(require("os")),qw=G(require("path"));var ake={onPath:e=>(0,aN.spawnSync)("sh",["-c",`command -v ${e}`],{stdio:"ignore"}).status===0,run:(e,t)=>(0,aN.spawnSync)(e[0],e.slice(1),{cwd:t,stdio:"ignore",timeout:6e4}).status??1},fm={cleanup:()=>{}},cke=new Set(["pnpm","yarn"]);function cN(e,t=U6.tmpdir(),n=ake,s=lD(e)){if(process.platform==="win32")return fm;try{if(Gr(e)||!cke.has(s)||n.onPath(s)||!n.onPath("corepack"))return fm;dp.mkdirSync(t,{recursive:!0});let r=dp.mkdtempSync(qw.join(t,"testbot-pm-")),i=()=>dp.rmSync(r,{recursive:!0,force:!0});return n.run(["corepack","enable","--install-directory",r,s],e)!==0?(i(),fm):{dir:r,cleanup:i}}catch{return fm}}function F6(e,t=process.env){return e.dir?{...t,PATH:[e.dir,t.PATH].filter(Boolean).join(qw.delimiter)}:t}var fWe={jest:"jest",vitest:"vitest"};var gke=[["target","surefire-reports"],["target","failsafe-reports"],["build","test-results"]],AYe=new Set(gke.map(([e])=>e));var yYe=["jest","vitest","npm-test","playwright"];var yke="ci-collect";var QYe=5*6e4;function Hw(e,t){let n=new Set(t.tests.map(s=>s.file));return(Ae(e,`${yke}.json`)?.checks??[]).filter(s=>n.has(s.file))}function uN(e){let t=Ae(e,"write.json");if(!Array.isArray(t?.tests))return new Set;let n=new Set(t.tests.filter(s=>s.change==="added").map(s=>s.file));return new Set(Hw(e,t).filter(s=>s.verdict==="unprovisioned"&&n.has(s.file)).map(s=>s.file))}var rn=G(require("node:fs")),Xt=G(require("node:path")),Yw=require("node:child_process");var Jw=G(require("fs")),ts=G(require("path")),Eke={lf:`
|
|
297
297
|
`,crlf:`\r
|
|
298
298
|
`,cr:"\r"},vke=5*1024*1024,L6=e=>e.replace(/[.+^$()|\\/{}[\]*?]/g,"\\$&");function bke(e,t){let n=0;for(let s=t;s<e.length;s++)if(e[s]==="\\")s++;else if(e[s]==="{")n++;else if(e[s]==="}"&&--n===0)return s;return-1}function wke(e){let t=[],n=0,s="";for(let r=0;r<e.length;r++){let i=e[r];if(i==="\\"){s+=i+(e[++r]??"");continue}i==="{"&&n++,i==="}"&&n--,i===","&&!n?(t.push(s),s=""):s+=i}return[...t,s]}function lN(e){let t="";for(let n=0;n<e.length;n++){let s=e[n];if(s==="\\")t+=L6(e[++n]??"\\");else if(s==="*"&&e[n+1]==="*"){let r=(n===0||e[n-1]==="/")&&e[n+2]==="/";t+=r?"(?:.*/)?":".*",n+=r?2:1}else if(s==="*")t+="[^/]*";else if(s==="?")t+="[^/]";else if(s==="["){let r=e.indexOf("]",n+2);if(r<0||e.slice(n,r).includes("/"))t+="\\[";else{let i=e.slice(n+1,r);t+=`[${i.replace(/^!/,"^").replace(/\\(?!\])/g,"\\\\")}]`,n=r}}else if(s==="{"){let r=bke(e,n),i=r<0?"":e.slice(n+1,r),o=/^(-?\d+)\.\.(-?\d+)$/.exec(i),a=wke(i);if(o){let[c,u]=[Number(o[1]),Number(o[2])].sort((d,p)=>d-p);t+=`(?:${Array.from({length:Math.min(u-c+1,1e4)},(d,p)=>String(c+p)).join("|")})`,n=r}else a.length>1?(t+=`(?:${a.map(lN).join("|")})`,n=r):t+="\\{"}else t+=L6(s)}return t}function Ike(e){return e.includes("/")?new RegExp(`^${lN(e.replace(/^\//,""))}$`):new RegExp(`^(?:.*/)?${lN(e)}$`)}function Cke(e){let t={root:!1,sections:[]},n;for(let s of e.split(/\r\n|\r|\n/)){let r=s.trim();if(!r||r.startsWith("#")||r.startsWith(";"))continue;let i=/^\[(.+)\]$/.exec(r);if(i){n={matches:Ike(i[1]),props:{}},t.sections.push(n);continue}let o=r.indexOf("=");if(o<0)continue;let a=r.slice(0,o).trim().toLowerCase(),c=r.slice(o+1).trim().toLowerCase();n?n.props[a]=c:a==="root"&&(t.root=c==="true")}return t}function Ske(e,t,n){let s=[];for(let i=ts.dirname(t);;i=ts.dirname(i)){let o=n(i);if(o&&s.unshift({dir:i,config:o}),o?.root||i===e||i===ts.dirname(i))break}let r={};for(let{dir:i,config:o}of s){let a=ts.relative(i,t).split(ts.sep).join("/");for(let c of o.sections)c.matches.test(a)&&Object.assign(r,c.props)}return Object.fromEntries(Object.entries(r).filter(([,i])=>i!=="unset"))}function kke(e,t){let n=e.startsWith("#!"),s=t.end_of_line?Eke[t.end_of_line]:void 0,r=s&&!(n&&s!==`
|
|
299
299
|
`)?s:void 0,i=r?e.replace(/\r\n|\r|\n/g,r):e;return t.insert_final_newline==="true"&&i.length&&!/[\r\n]$/.test(i)&&(i+=r??/\r\n|\r|\n/.exec(i)?.[0]??`
|
|
300
|
-
`),i}function pp(e,t,n){if(n.length>vke||n.includes(0))return n;let s=ts.resolve(e),r=Ske(s,ts.resolve(s,t),i=>{try{return Cke(Jw.readFileSync(ts.join(i,".editorconfig"),"utf-8"))}catch{return}});return Buffer.from(kke(n.toString("latin1"),r),"latin1")}var Nu=G(require("node:fs")),Pu=G(require("node:path"));function dN(e,t){let n=Pu.relative(e,t);try{let s=Nu.lstatSync(t);if(s.isSymbolicLink())return"test entry is a symlink";if(!s.isFile())return"test entry is not a regular file";let r=Nu.realpathSync(e),i=Nu.realpathSync(t),o=Pu.relative(r,i);return!o||o.startsWith("..")||Pu.isAbsolute(o)?`test entry's real path is outside the checkout (${o})`:o!==n?`test entry's real path is ${o}, not ${n}, after canonicalisation`:void 0}catch(s){return s.code==="ENOENT"?`test entry is missing: no file is at ${n} in the checkout`:`test entry cannot be read: ${hp(s,e)}`}}function fp(e,t){let n=dN(e,t);if(n)return n;try{return Nu.readFileSync(t)}catch(s){return`test entry cannot be read: ${hp(s,e)}`}}function hp(e,t){return(e instanceof Error?e.message:String(e)).split(t+Pu.sep).join("")}function Rke(e){return Ae(e,`${Y_}.json`)?.guardUnavailable===!0}function j6(e){let t=Ae(e,"recommend.json"),n=Ae(e,`${Y_}.json`),s=new Map(Rke(e)?(t?.generate??[]).map(({id:r})=>[r,fw]):[]);for(let{id:r,reason:i}of t?.withheld??[])s.has(r)||s.set(r,`off-limits execution (${i??"environment policy"})`);if(n?.browserWithheld)for(let r of t?.generate??[])r.type==="ui"&&!s.has(r.id)&&s.set(r.id,"the shared-environment browser guard is unavailable");return s}function V6(e,t){let n=new Set((e.covers??[]).flatMap(s=>{let r=t.get(s);return r?[r]:[]}));return n.size?`environment restriction: ${[...n].join("; ")}`:void 0}function xke(e){return!!e.guardedDelivery||!!e.context?.some(t=>t.safety?.route==="persistence")}function gp(e,t){let n=e.inputs.sharedEnvironment?.environmentAddress;return!!n&&(t.result?.cases??[]).some(s=>s.runtimeTargets?.some(r=>nu(n,r)))}function gm(e,t,n=ro().version){if(!vn(e.inputs))return[];let s=e.inputs.sharedEnvironment,r=s?.environmentAddress,i=Ae(e,tB),o=Ez.safeParse(i),a=o.success&&o.data.environmentId===s?.environmentId&&o.data.environmentAddress===r?o.data:void 0,c=vz.safeParse(i),u=c.success?fh(c.data.refusal):o.success?fh("changed"):fh("unavailable"),d=j6(e),p=new Map(Hw(e,t).map(E=>[E.file,E.verdict])),h=TD(xD(e)),g=Ae(e,"recommend.json"),m=new Map((g?.generate??[]).map(({id:E,target:b})=>[E,b])),y=bn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),v=new Map;for(let E of t.tests){if(E.change==="deleted")continue;let b=y(E.file);if(!es(b)||uo(b.rel))continue;let I=co(e.inputs,b.repository);if("error"in I)continue;let C=I.source,w=Xt.resolve(C.path,b.rel),x=V6(E,d)??$ke(h,b),S=xke(E),Y=gp(e,E),ae;if(!x&&!Y&&!S){if(!w.endsWith(".test.cjs"))continue;try{if(!pN(C.path,w))continue;ae=bo(rn.readFileSync(w,"utf8"))}catch{continue}if(!ae||"restriction"in ae)continue}let J=(E.covers??[]).flatMap(Ft=>{let ut=m.get(Ft)?.match(/^(GET|HEAD|OPTIONS|POST|PUT|PATCH|DELETE)\s+(\S+?)[,;]?(?:\s|$)/i);return!ut||!r?[]:ut[2].startsWith("/")||nu(r,ut[2])?[{method:ut[1].toUpperCase(),route:ut[2]}]:[]}),be=Oke(e,C.path,b.rel);if(!x&&E.change!=="added"&&(be===!1||be===void 0&&!e.inputs.deliver))continue;let Me=Ft=>`${E.file}: shared-environment delivery is blocked: ${Ft}`,Ge={repository:C.slug,file:b.rel,sourceAsset:`${b.rel}.source`},ke=fp(C.path,w);if(typeof ke=="string"){v.set(w,{record:Ge,source:C,original:Buffer.alloc(0),problems:[Me(`${ke} (planGuardedDelivery)`)]});continue}if(E.change!=="added"&&Xs(e,C.path,b.rel)){x&&(Ge.reason=x,v.set(w,{record:Ge,source:C,original:ke,problems:[]}));continue}if(be===!1||E.change!=="added"&&be!==!0){v.set(w,{record:Ge,source:C,original:ke,problems:[Me(be===!1?"the file changes an existing test; retain the assertions in a new file":"cannot prove whether the shared test already exists; use a host-pinned checkout")]});continue}if(ae??=bo(ke.toString("utf8")),!x&&ae&&"restriction"in ae)continue;let X,z=Uw.safeParse(E.guardedDelivery),Je=a&&s?{environmentId:a.environmentId,environmentAddress:a.environmentAddress,persistenceRevision:a.revision,offLimits:s.offLimits??[],route:{kind:"persistence"}}:void 0,at=`environment restriction: persistence permission was not confirmed at generation: ${u}`;if(x)X=x;else if(S&&!Je)X=at;else if(!z.success||!Je)X="no guarded HTTP representation preserves the test's assertions";else if(!E.covers?.length||(E.functions?.length??1)!==1)X="guarded HTTP delivery requires one test function";else if(!/\.test\.cjs$/.test(b.rel)||!Dke(E.ci))X="the test has no compatible Node CI entry";else if(!E.ci?.collected&&p.get(E.file)!=="not-collected")X="Testbot could not confirm that the repo's CI leaves it out, and only node --test can run the entry";else if(!Nke(C.path,w,n))X=`the CI package does not declare @skyramp/testbot-core ${n}, the released guarded runtime the entry needs`;else{let{steps:Ft}=z.data,ut=Je.offLimits.length?H_(e.inputs.skyrampMcp,Je.offLimits):void 0,Dn=new Map,St=Ft.flatMap(vt=>{if(vt.op==="create"){let se=Tke(Je.environmentAddress,vt.collection);return se&&Dn.set(vt.as,se),[{method:"POST",url:se,child:!1}]}if(vt.op!=="read"&&vt.op!=="update")return[];let Oe=Dn.get(vt.resource);return Oe&&Dn.set(vt.as,Oe),[{method:vt.op==="read"?"GET":vt.method??"PATCH",url:Oe,child:!0}]});St.some(({url:vt})=>!vt)?X="the guarded HTTP steps name an unknown resource or a collection outside the Test Environment":ut&&s&&St.some(({url:vt,child:Oe})=>!Oe&&fZ(vt.href,s,ut))?X="the guarded HTTP steps name an off-limits collection":J.length&&!J.some(({method:vt,route:Oe})=>St.some(se=>se.url&&se.method===vt&&Qke(Je.environmentAddress,se.url,se.child,Oe)))&&(X="the guarded HTTP steps do not represent the planned HTTP operation")}let sn;if(X)Ge.reason=X;else if(z.success&&Je){let{bearerTokenEnv:Ft,...ut}=z.data;sn={...ut,definition:{...Je,...Ft?{bearerTokenEnv:Ft}:{}}},Ge.entry=b.rel}let Et=Xt.resolve(C.path,Ge.sourceAsset),In=Zw(Et)&&!hm(C.path,Et,ke)?[Me("the inert source asset path already contains different bytes")]:[];v.set(w,{record:Ge,source:C,original:ke,spec:sn,problems:In})}return[...v.values()]}function $ke(e,t){return e.find(n=>$D(n,{file:t.rel,repository:t.repository}))?.environmentRestriction}function Tke(e,t){try{let n=new URL(t,`${e.replace(/\/$/,"")}/`);return!n.search&&!n.hash&&!n.username&&!n.password&&!/[\\]|%(?:2f|5c|2e|25)/i.test(t)&&nu(e,n.href)?n:void 0}catch{return}}function Qke(e,t,n,s){try{let r=new URL(s,t.origin),i=s.startsWith("/")&&!s.startsWith("//")&&!nu(e,r.href)?new URL(s.slice(1),`${e.replace(/\/$/,"")}/`):r;if(!nu(e,i.href))return!1;let o=t.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");if(!n)return a===o;if(!a.startsWith(`${o}/`))return!1;let c=decodeURIComponent(a.slice(o.length+1));return/^(:[\w-]+|\{[^/{}]+\}|<[^/<>]+>)$/.test(c)}catch{return!1}}function _ke(e){return!!e&&/^(?:node|node:test|node\s+(?:.*\s)?--test(?:\s.*)?)$/i.test(e.trim())}function Dke(e){return e?.collected===!1||!!e?.collected&&_ke(e.runner)}function pN(e,t){let n=rn.realpathSync(e);return rn.lstatSync(t).isFile()&&rn.realpathSync(t)===Xt.join(n,Xt.relative(e,t))}function hm(e,t,n){try{return pN(e,t)&&rn.readFileSync(t).equals(n)}catch{return!1}}function Zw(e){try{return rn.lstatSync(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Nke(e,t,n){if(n==="unknown")return!1;for(let s=Xt.dirname(t);;s=Xt.dirname(s)){let r=Xt.join(s,"package.json");if(Zw(r))try{if(!pN(e,r))return!1;let i=JSON.parse(rn.readFileSync(r,"utf-8"));return(i.devDependencies?.["@skyramp/testbot-core"]??i.dependencies?.["@skyramp/testbot-core"])===n}catch{return!1}if(s===e)return!1}}function Pke(e){let t=Ae(e,"write.json");return t?gm(e,t):[]}function G6(e,t=Pke(e),n=[],s=[]){return t.flatMap(({record:r,source:i,original:o,spec:a,problems:c})=>{if(c.length)return c;let u=Xt.join(i.path,r.sourceAsset),d=Xt.join(i.path,r.file),p=`reading ${r.file}`;try{let h=fp(i.path,d);if(typeof h=="string")return[`${r.file}: ${h} (writeGuardedDeliveryFiles)`];if(!h.equals(o))return[`${r.file}: native source changed before guarded delivery`];p=`preparing ${r.sourceAsset}`;let g=Qu(o.toString("utf-8"),n).content;if(Si(g,e.secretValues??[])!==g)return[`${r.file}: the retained source contains a credential`];let m=pp(i.path,r.sourceAsset,Buffer.from(g));if(p=`writing ${r.sourceAsset}`,Zw(u)){if(!hm(i.path,u,o)&&!hm(i.path,u,m))return[`${r.file}: the inert source asset path already contains different bytes`];hm(i.path,u,m)||(s.push(()=>rn.writeFileSync(u,o)),rn.writeFileSync(u,m))}else rn.writeFileSync(u,m,{flag:"wx"}),s.push(()=>rn.rmSync(u,{force:!0}));if(r.entry&&a){let y=sm({...a,name:ap(a.name,n)}),v=pp(i.path,r.entry,Buffer.from(y));if(!bo(v.toString("utf-8")))return[`${r.file}: the repository's file conventions changed the guarded entry`];if(Si(v.toString("utf-8"),e.secretValues??[])!==v.toString("utf-8"))return[`${r.file}: guarded delivery steps include a credential`];p=`writing ${r.entry}`,s.push(()=>rn.writeFileSync(d,o)),rn.writeFileSync(d,v)}return[]}catch(h){return[`${r.file}: could not assemble its guarded delivery files (writeGuardedDeliveryFiles): ${p} failed: ${hp(h,i.path)}`]}})}function Oke(e,t,n){let s=e.executionSafetySources?.find(r=>Xt.resolve(r.path)===Xt.resolve(t));if(s)try{return(0,Yw.execFileSync)("git",["--literal-pathspecs","ls-tree",s.head,"--",n],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]})===""}catch{return}}function Xs(e,t,n){let s=e.executionSafetySources?.find(r=>Xt.resolve(r.path)===Xt.resolve(t));if(!s||!/^[a-f0-9]{40,64}$/.test(s.head))return!1;try{let r=Xt.join(t,n),i=rn.lstatSync(r);if(!i.isFile()||rn.realpathSync(r)!==r)return!1;let o=Kw(t,s.head,n);return!o||(i.mode&73)!==0!==o.executable?!1:rn.readFileSync(r).equals(o.bytes)}catch{return!1}}var Ww=new Map;function Kw(e,t,n){let s=`${Xt.resolve(e)}\0${t}\0${n}`,r=Ww.get(s);if(r!==void 0)return r;let i=null;try{let o=(0,Yw.execFileSync)("git",["--literal-pathspecs","ls-tree",t,"--",n],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]});/^100(?:644|755) blob /.test(o)&&(i={executable:o.startsWith("100755"),bytes:(0,Yw.execFileSync)("git",["show",`${t}:${n}`],{cwd:e,stdio:["ignore","pipe","ignore"]})})}catch{i=null}return Ww.size>=1e4&&Ww.clear(),Ww.set(s,i),i}function z6(e,t,n,s){if(!s.size)return[...n];let r=new Map(n.map(o=>[Xt.resolve(o.source.path,o.record.file),o])),i=bn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]);for(let o of t.tests){if(o.change==="deleted")continue;let a=i(o.file);if(!es(a)||uo(a.rel))continue;let c=co(e.inputs,a.repository);if("error"in c)continue;let u=c.source,d=Xt.resolve(u.path,a.rel),p=s.get(d);if(!p)continue;let h=r.get(d);if(h){if(h.record.reason)continue;let b={...h.record,reason:p};delete b.entry,r.set(d,{...h,record:b,spec:void 0});continue}let g={repository:u.slug,file:a.rel,sourceAsset:`${a.rel}.source`,reason:p},m=b=>[`${o.file}: shared-environment delivery is blocked: ${b}`],y=fp(u.path,d);if(typeof y=="string"){r.set(d,{record:g,source:u,original:Buffer.alloc(0),problems:m(`${y} (holdDependents)`)});continue}let v=Xt.resolve(u.path,g.sourceAsset),E=Zw(v)&&!hm(u.path,v,y)?m("the inert source asset path already contains different bytes"):[];r.set(d,{record:g,source:u,original:y,problems:E})}return[...r.values()]}var Rs=G(require("node:fs")),$e=G(require("node:path"));var Ou=G(require("path"));var c4e={python:"pytest",typescript:"playwright",javascript:"playwright"},u4e={pytest:"pytest",playwright:"playwright"};var jke=new Set(["package.json","package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb","pyproject.toml","poetry.lock","uv.lock","pdm.lock","Pipfile","Pipfile.lock","setup.py","setup.cfg","go.mod","go.sum","Gemfile","Gemfile.lock","pom.xml","build.gradle","build.gradle.kts"]);function mm(e){let t=Ou.basename(e);return jke.has(t)||/^requirements[^/\\]*\.(txt|in)$/.test(t)}var J6="shared-environment delivery cannot verify it for guarded execution",W6=(e,t)=>`${Es(e.inputs,t.source.slug)}${t.file}`;function Xw(e,t,n){let s=bn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),r=new Set(n.map(i=>$e.resolve(i.source.path,i.record.file)));return t.tests.filter(i=>{let o=s(i.file);return!r.has($e.resolve(o.root,o.rel))&&i.change!=="updated"&&gp(e,i)})}function eI(e,t,n,s){let r=bn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),i=new Map(n.map(c=>[$e.resolve(c.source.path,c.record.file),c])),o=new Set,a=[];for(let c of t.tests){let u=r(c.file),d=$e.resolve(u.root,u.rel),p=i.get(d);if(p){o.add($e.resolve(u.root,p.record.sourceAsset)),p.record.entry&&o.add(d);continue}if(c.change==="deleted"){nRe(e,u.root,u.rel)?o.add(d):a.push(`${c.file}: a deleted shared-environment test must actually be absent and be a tracked regular file in the host-pinned source`);continue}if(c.change==="updated"||!gp(e,c)){o.add(d);continue}if(Xs(e,u.root,u.rel)){o.add(d);continue}try{let h=bo(Rs.readFileSync(d,"utf-8"));if(!h)continue;if(o.add(d),"restriction"in h){let g=$e.resolve($e.dirname(d),h.sourceAsset.path);o.add(g),!s.has(g)&&!Xs(e,u.root,$e.relative(u.root,g))&&a.push(`${c.file}: its restricted source asset is missing from the actual delivery commit`)}}catch{}}return{allowed:o,problems:a}}function tI(e,t,n,s){let r=[];for(let[i,o]of t)for(let a of o)n.has($e.resolve(i.path,a))||!s.length&&!e.inputs.deliver&&ro().version==="unknown"||tRe(e,i.path,a)||Xs(e,i.path,a)||r.push({source:i,file:a});return r}var Y6=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".json"],Z6=/(?:\bfrom\s*|\bimport(?:\s*\()?\s*|\brequire\s*\(\s*)["'`]([^"'`\n]+)["'`]/g,Vke=/^[ \t]*from[ \t]+([.\w]+)[ \t]+import[ \t]+\(?([\w\t ,*]+)/gm,Gke=/^[ \t]*import[ \t]+([\w.]+)/gm;function zke(e,t){if(!/^\.\.?(?:\/|$)/.test(t))return[];let n=$e.resolve(e,t),s=/\.[cm]?jsx?$/.test(n)?[n.replace(/\.([cm]?)js(x?)$/,".$1ts$2")]:[];return[n,...s,...Y6.flatMap(r=>[n+r,$e.join(n,`index${r}`)])]}function q6(e,t,n,s){let r=/^\.*/.exec(n)[0].length,i=n.slice(r).split(".").filter(Boolean);return(r?[$e.resolve(t,...Array(r-1).fill(".."))]:[e,t]).flatMap(a=>{let c=$e.join(a,...i);return[`${c}.py`,$e.join(c,"__init__.py"),...s.map(u=>$e.join(c,`${u}.py`))]})}function qke(e,t,n){let s=$e.dirname(t),r=new Set;if(t.endsWith(".py")){for(let[,i,o]of n.matchAll(Vke))for(let a of q6(e,s,i,o.split(/[\s,]+/).filter(c=>/^\w+$/.test(c))))r.add(a);for(let[,i]of n.matchAll(Gke))for(let o of q6(e,s,i,[]))r.add(o)}else for(let[,i]of n.matchAll(Z6))for(let o of zke(s,i))r.add(o);return r}function Hke(e,t){let n=new Set;if(e.endsWith(".py")||e.endsWith(".go"))return n;for(let[,s]of t.matchAll(Z6)){if(/^\.\.?(?:\/|$)/.test(s)||/^[a-z][\w+.-]*:/i.test(s))continue;let r=s.split("/").pop()??"";r&&n.add(r.replace(/\.[cm]?[jt]sx?$/,""))}return n}function Jke(e,t){let n=$e.extname(t);if(!Y6.includes(n))return!1;let s=$e.basename(t,n);return e.has(s)||s==="index"&&e.has($e.basename($e.dirname(t)))}function Wke(e,t){let n=$e.basename(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?<![\\w.-])${n}(?![\\w.-])`).test(e)}function H6(e,t){for(let n=$e.dirname(t);;n=$e.dirname(n)){if(Rs.existsSync($e.join(n,"go.mod")))return n;if(n===e||$e.dirname(n)===n)return e}}function Yke(e,t){let n=[];t.isolatedRun&&n.push({cwd:".",text:t.isolatedRun}),t.run&&n.push({cwd:t.run.cwd,text:t.run.argv.join(" ")}),t.ci?.list&&n.push({cwd:t.ci.list.cwd,text:t.ci.list.argv.join(" ")});for(let r of t.ci?.steps??[])n.push({cwd:".",text:r.line});for(let r of t.context??[])r.cleanup&&n.push({cwd:".",text:r.cleanup});let s=new Set;for(let{cwd:r,text:i}of n)for(let o of i.split(/[\s"'`;&|()<>=,]+/))o&&!/^[a-z][\w+.-]*:/i.test(o)&&s.add($e.resolve(e,r,o));return s}var Zke={".py":"python",".js":"node",".cjs":"node",".mjs":"node",".jsx":"node",".ts":"node",".cts":"node",".mts":"node",".tsx":"node",".go":"go",".rb":"ruby",".java":"jvm",".kt":"jvm",".kts":"jvm",".scala":"jvm",".groovy":"jvm"},Kke=[[/^(?:playwright|vitest|jest)\.config\.(?:[cm]?[jt]s|json)$/,"node"],[/^tsconfig\.json$/,"node"],[/^(?:pytest|tox)\.ini$/,"python"]];function Xke(e){let t=$e.basename(e);if(["conftest.py","__init__.py"].includes(t))return"python";let n=Kke.find(([s])=>s.test(t));if(n)return n[1];if(mm(e))return/^(?:package\.json|package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lockb?)$/.test(t)?"node":/^go\.(?:mod|sum)$/.test(t)?"go":/^Gemfile(?:\.lock)?$/.test(t)?"ruby":/^(?:pom\.xml|build\.gradle(?:\.kts)?)$/.test(t)?"jvm":"python"}function eRe(e,t,n){let s=Zke[$e.extname(t)];if(s==="go"&&$e.extname(n)===".go"&&H6(e,n)===H6(e,t))return!0;let r=Xke(n);if(!r||s&&s!==r)return!1;let i=$e.relative($e.dirname(n),t);return!i.startsWith("..")&&!$e.isAbsolute(i)}function K6(e,t,n){let s=new Map;if(!n.length)return s;let r=bn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]);for(let i of t.tests){if(i.change==="deleted")continue;let o=r(i.file);if(!es(o)||Xs(e,o.root,o.rel))continue;let a=$e.resolve(o.root),c=$e.resolve(a,o.rel),u=n.filter(y=>$e.resolve(y.source.path)===a);if(!u.length)continue;let d="";try{d=Rs.readFileSync(c,"utf-8")}catch{}let p=qke(a,c,d),h=Hke(c,d),g=Yke(a,i),m=u.filter(y=>{let v=$e.resolve(a,y.file);return p.has(v)||g.has(v)||Jke(h,v)||Wke(d,v)||eRe(a,c,v)});m.length&&s.set(c,`needs ${m.map(y=>W6(e,y)).join(", ")}, which is not in the tests PR: ${J6}`)}return s}function Ua(e){return Array.isArray(e)?`[${e.map(Ua).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Ua(n)}`).join(",")}}`:JSON.stringify(e)??"undefined"}function tRe(e,t,n){let s=$e.basename(n);if(s!=="package.json"&&s!=="package-lock.json")return!1;let r=ro().version;if(r==="unknown")return!1;let i,o;try{let a=$e.resolve(t,n);if(!Rs.lstatSync(a).isFile()||Rs.realpathSync(a)!==a)return!1;i=JSON.parse(Rs.readFileSync(a,"utf-8"));let c=e.executionSafetySources?.find(h=>$e.resolve(h.path)===$e.resolve(t));if(c){let h=Kw(t,c.head,n);h&&(o=JSON.parse(h.bytes.toString("utf-8")))}else if(Rs.existsSync($e.join(t,".git")))return!1;let u=h=>{let g=structuredClone(h);for(let m of["dependencies","devDependencies"])g[m]&&(delete g[m]["@skyramp/testbot-core"],Object.keys(g[m]).length||delete g[m]);return g};if(s==="package.json")return(i.devDependencies?.["@skyramp/testbot-core"]??i.dependencies?.["@skyramp/testbot-core"])!==r?!1:o?Ua(u(i))===Ua(u(o)):Object.keys(i).every(h=>["name","version","private","type","scripts","dependencies","devDependencies"].includes(h))&&(!i.scripts||Ua(i.scripts)===Ua({test:"node --test"}))&&Object.keys(i.dependencies??{}).every(h=>h==="@skyramp/testbot-core")&&Object.keys(i.devDependencies??{}).every(h=>h==="@skyramp/testbot-core");let d=i.packages?.["node_modules/@skyramp/testbot-core"];if(!d||d.version!==r||d.link||d.hasInstallScript||d.resolved!==`https://registry.npmjs.org/@skyramp/testbot-core/-/testbot-core-${r}.tgz`||!/^sha512-[A-Za-z0-9+/=]+$/.test(d.integrity??""))return!1;let p=h=>{let g=structuredClone(h);return g.packages&&(delete g.packages["node_modules/@skyramp/testbot-core"],g.packages[""]&&(g.packages[""]=u(g.packages[""]))),g};return o?Ua(p(i))===Ua(p(o)):Object.keys(i.packages??{}).every(h=>h===""||h==="node_modules/@skyramp/testbot-core")&&!i.packages?.[""]?.scripts}catch{return!1}}function nRe(e,t,n){try{return Rs.lstatSync($e.join(t,n)),!1}catch(r){if(r.code!=="ENOENT")return!1}let s=e.executionSafetySources?.find(r=>$e.resolve(r.path)===$e.resolve(t));return!s||!/^[a-f0-9]{40,64}$/.test(s.head)?!1:Kw(t,s.head,n)!==null}function rRe(e){try{return nI.lstatSync(e),!0}catch{return!1}}function rI(e,t=Am(e)){let n=new Set(t.omitted.map(({source:s,file:r})=>Ht.resolve(s.path,r)));return new Map([...X6(e,t.assemblies)].map(([s,r])=>[s,r.filter(i=>!n.has(Ht.resolve(s.path,i)))]))}function Am(e,t=Ae(e,"write.json")){if(!t||!vn(e.inputs))return{assemblies:[],omitted:[],hasSharedTests:!1};let n=gm(e,t),s=bn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),r=new Set(t.tests.map(a=>{let c=s(a.file);return Ht.resolve(c.root,c.rel)})),i=[],o=n;for(;;){let a=o.length>0||Xw(e,t,o).length>0;if(!a)return{assemblies:o,omitted:i,hasSharedTests:a};let c=X6(e,o),u=new Set([...c].flatMap(([g,m])=>m.map(y=>Ht.resolve(g.path,y)))),{allowed:d}=eI(e,t,o,u),p=new Set(i.map(({source:g,file:m})=>Ht.resolve(g.path,m))),h=tI(e,c,d,o).filter(({source:g,file:m})=>{let y=Ht.resolve(g.path,m);return!p.has(y)&&!r.has(y)});if(!h.length)return{assemblies:o,omitted:i,hasSharedTests:a};i.push(...h),o=z6(e,t,n,K6(e,t,i))}}function X6(e,t){let n=new Set(t.filter(({record:v})=>!v.entry).map(({source:v,record:E})=>Ht.join(v.path,E.file))),s=Ae(e,"adapt.json"),r=Ae(e,"finalize.json"),i=Ae(e,um),o=new Map,a=v=>{let E=co(e.inputs,v);if("error"in E)return;let b=o.get(E.source.path)??{source:E.source,paths:new Set};return o.set(E.source.path,b),{repo:b.source.path,paths:b.paths}},c=(v,E)=>Ht.relative(v,Ht.resolve(v,E.trim())).replace(/\/+$/,""),u=(v,E)=>{let b=E?.trim()&&a(v);if(!b)return;let I=c(b.repo,E);b.paths.add(I);for(let C of["__init__.py","conftest.py"]){let w=Ht.join(Ht.dirname(I),C);nI.existsSync(Ht.join(b.repo,w))&&(!n.has(Ht.join(b.repo,I))||!Xs(e,b.repo,w))&&b.paths.add(w)}},d=(v,E)=>{if(typeof E!="string"||!E.trim())return;let b=a(v);if(!b)return;let I=c(b.repo,E);if(np(Ht.join(b.repo,I)))return b.paths.add(I),{...b,rel:I}},p=uN(e),h=(s?.items??[]).filter(v=>v.action==="place"&&p.has(v.from??v.file??"")),g=(v,E)=>h.some(b=>b.repository===v&&b.file&&Ht.normalize(b.file)===E),m=(s?.items??[]).filter(v=>!h.includes(v));for(let v of[...m,...i?.tests??[],...i?.maintained??[]])u(v.repository,v.file);for(let v of r?.dependencies?.added??[]){let E=d(v.repository,v.manifest);if(E)for(let b of fD(E.repo,Iw(E.repo,E.rel)))E.paths.add(b)}for(let v of r?.lint??[])for(let E of v.fixed??[])d(v.repository,E);for(let v of r?.support??[])d(v.repository,v.file);let y=Ae(e,kw)?.packages??[];for(let v of new Set(y.map(E=>E.repository))){let E=a(v),b=y.filter(I=>I.repository===v).map(I=>I.dir);if(E)for(let{path:I}of nm(E.repo)){let C=c(E.repo,I),w=Ht.join(E.repo,C);Hg(C,b)&&!ED(C)&&!g(v,C)&&(!rRe(w)||np(w))&&E.paths.add(C)}}for(let{record:v,source:E,problems:b}of t){let I=o.get(E.path)?.paths;I?.has(v.file)&&(I.delete(v.file),!b.length&&(v.entry&&I.add(v.entry),I.add(v.sourceAsset)))}return new Map([...o.values()].map(({source:v,paths:E})=>[v,[...E].filter(b=>b&&b!==".."&&!b.startsWith(`..${Ht.sep}`)&&!uo(b))]))}var gZe=5*6e4,mZe=12*6e4,AZe=2*6e4;var IZe=["class TestbotProjectBrowsers {"," onBegin(config) {",' const projects = config.projects.map((p) => ({ browserName: p.use.browserName ?? p.use.defaultBrowserType ?? "chromium", channel: p.use.channel ?? null }));',' process.stdout.write("TESTBOT_PROJECT_BROWSERS " + JSON.stringify(projects) + "\\n");'," }"," printsToStdio() { return true; }","}","module.exports = TestbotProjectBrowsers;",""].join(`
|
|
300
|
+
`),i}function pp(e,t,n){if(n.length>vke||n.includes(0))return n;let s=ts.resolve(e),r=Ske(s,ts.resolve(s,t),i=>{try{return Cke(Jw.readFileSync(ts.join(i,".editorconfig"),"utf-8"))}catch{return}});return Buffer.from(kke(n.toString("latin1"),r),"latin1")}var Nu=G(require("node:fs")),Pu=G(require("node:path"));function dN(e,t){let n=Pu.relative(e,t);try{let s=Nu.lstatSync(t);if(s.isSymbolicLink())return"test entry is a symlink";if(!s.isFile())return"test entry is not a regular file";let r=Nu.realpathSync(e),i=Nu.realpathSync(t),o=Pu.relative(r,i);return!o||o.startsWith("..")||Pu.isAbsolute(o)?`test entry's real path is outside the checkout (${o})`:o!==n?`test entry's real path is ${o}, not ${n}, after canonicalisation`:void 0}catch(s){return s.code==="ENOENT"?`test entry is missing: no file is at ${n} in the checkout`:`test entry cannot be read: ${hp(s,e)}`}}function fp(e,t){let n=dN(e,t);if(n)return n;try{return Nu.readFileSync(t)}catch(s){return`test entry cannot be read: ${hp(s,e)}`}}function hp(e,t){return(e instanceof Error?e.message:String(e)).split(t+Pu.sep).join("")}function Rke(e){return Ae(e,`${Y_}.json`)?.guardUnavailable===!0}function j6(e){let t=Ae(e,"recommend.json"),n=Ae(e,`${Y_}.json`),s=new Map(Rke(e)?(t?.generate??[]).map(({id:r})=>[r,fw]):[]);for(let{id:r,reason:i}of t?.withheld??[])s.has(r)||s.set(r,`off-limits execution (${i??"environment policy"})`);if(n?.browserWithheld)for(let r of t?.generate??[])r.type==="ui"&&!s.has(r.id)&&s.set(r.id,"the shared-environment browser guard is unavailable");return s}function V6(e,t){let n=new Set((e.covers??[]).flatMap(s=>{let r=t.get(s);return r?[r]:[]}));return n.size?`environment restriction: ${[...n].join("; ")}`:void 0}function xke(e){return!!e.guardedDelivery||!!e.context?.some(t=>t.safety?.route==="persistence")}function gp(e,t){let n=e.inputs.sharedEnvironment?.environmentAddress;return!!n&&(t.result?.cases??[]).some(s=>s.runtimeTargets?.some(r=>nu(n,r)))}function gm(e,t,n=ro().version){if(!vn(e.inputs))return[];let s=e.inputs.sharedEnvironment,r=s?.environmentAddress,i=Ae(e,tB),o=Ez.safeParse(i),a=o.success&&o.data.environmentId===s?.environmentId&&o.data.environmentAddress===r?o.data:void 0,c=vz.safeParse(i),u=c.success?fh(c.data.refusal):o.success?fh("changed"):fh("unavailable"),d=j6(e),p=new Map(Hw(e,t).map(E=>[E.file,E.verdict])),h=TD(xD(e)),g=Ae(e,"recommend.json"),m=new Map((g?.generate??[]).map(({id:E,target:b})=>[E,b])),y=bn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),v=new Map;for(let E of t.tests){if(E.change==="deleted")continue;let b=y(E.file);if(!es(b)||uo(b.rel))continue;let I=co(e.inputs,b.repository);if("error"in I)continue;let C=I.source,w=Xt.resolve(C.path,b.rel),x=V6(E,d)??$ke(h,b),S=xke(E),Y=gp(e,E),ae;if(!x&&!Y&&!S){if(!w.endsWith(".test.cjs"))continue;try{if(!pN(C.path,w))continue;ae=bo(rn.readFileSync(w,"utf8"))}catch{continue}if(!ae||"restriction"in ae)continue}let J=(E.covers??[]).flatMap(Ft=>{let ut=m.get(Ft)?.match(/^(GET|HEAD|OPTIONS|POST|PUT|PATCH|DELETE)\s+(\S+?)[,;]?(?:\s|$)/i);return!ut||!r?[]:ut[2].startsWith("/")||nu(r,ut[2])?[{method:ut[1].toUpperCase(),route:ut[2]}]:[]}),be=Oke(e,C.path,b.rel);if(!x&&E.change!=="added"&&(be===!1||be===void 0&&!e.inputs.deliver))continue;let Me=Ft=>`${E.file}: shared-environment delivery is blocked: ${Ft}`,Ge={repository:C.slug,file:b.rel,sourceAsset:`${b.rel}.source`},ke=fp(C.path,w);if(typeof ke=="string"){v.set(w,{record:Ge,source:C,original:Buffer.alloc(0),problems:[Me(`${ke} (planGuardedDelivery)`)]});continue}if(E.change!=="added"&&Xs(e,C.path,b.rel)){x&&(Ge.reason=x,v.set(w,{record:Ge,source:C,original:ke,problems:[]}));continue}if(be===!1||E.change!=="added"&&be!==!0){v.set(w,{record:Ge,source:C,original:ke,problems:[Me(be===!1?"the file changes an existing test; retain the assertions in a new file":"cannot prove whether the shared test already exists; use a host-pinned checkout")]});continue}if(ae??=bo(ke.toString("utf8")),!x&&ae&&"restriction"in ae)continue;let X,z=Uw.safeParse(E.guardedDelivery),Je=a&&s?{environmentId:a.environmentId,environmentAddress:a.environmentAddress,persistenceRevision:a.revision,offLimits:s.offLimits??[],route:{kind:"persistence"}}:void 0,at=`environment restriction: persistence permission was not confirmed at generation: ${u}`;if(x)X=x;else if(S&&!Je)X=at;else if(!z.success||!Je)X="no guarded HTTP representation preserves the test's assertions";else if(!E.covers?.length||(E.functions?.length??1)!==1)X="guarded HTTP delivery requires one test function";else if(!/\.test\.cjs$/.test(b.rel)||!Dke(E.ci))X="the test has no compatible Node CI entry";else if(!E.ci?.collected&&p.get(E.file)!=="not-collected")X="Testbot could not confirm that the repo's CI leaves it out, and only node --test can run the entry";else if(!Nke(C.path,w,n))X=`the CI package does not declare @skyramp/testbot-core ${n}, the released guarded runtime the entry needs`;else{let{steps:Ft}=z.data,ut=Je.offLimits.length?H_(e.inputs.skyrampMcp,Je.offLimits):void 0,Dn=new Map,St=Ft.flatMap(vt=>{if(vt.op==="create"){let se=Tke(Je.environmentAddress,vt.collection);return se&&Dn.set(vt.as,se),[{method:"POST",url:se,child:!1}]}if(vt.op!=="read"&&vt.op!=="update")return[];let Oe=Dn.get(vt.resource);return Oe&&Dn.set(vt.as,Oe),[{method:vt.op==="read"?"GET":vt.method??"PATCH",url:Oe,child:!0}]});St.some(({url:vt})=>!vt)?X="the guarded HTTP steps name an unknown resource or a collection outside the Test Environment":ut&&s&&St.some(({url:vt,child:Oe})=>!Oe&&fZ(vt.href,s,ut))?X="the guarded HTTP steps name an off-limits collection":J.length&&!J.some(({method:vt,route:Oe})=>St.some(se=>se.url&&se.method===vt&&Qke(Je.environmentAddress,se.url,se.child,Oe)))&&(X="the guarded HTTP steps do not represent the planned HTTP operation")}let sn;if(X)Ge.reason=X;else if(z.success&&Je){let{bearerTokenEnv:Ft,...ut}=z.data;sn={...ut,definition:{...Je,...Ft?{bearerTokenEnv:Ft}:{}}},Ge.entry=b.rel}let Et=Xt.resolve(C.path,Ge.sourceAsset),In=Zw(Et)&&!hm(C.path,Et,ke)?[Me("the inert source asset path already contains different bytes")]:[];v.set(w,{record:Ge,source:C,original:ke,spec:sn,problems:In})}return[...v.values()]}function $ke(e,t){return e.find(n=>$D(n,{file:t.rel,repository:t.repository}))?.environmentRestriction}function Tke(e,t){try{let n=new URL(t,`${e.replace(/\/$/,"")}/`);return!n.search&&!n.hash&&!n.username&&!n.password&&!/[\\]|%(?:2f|5c|2e|25)/i.test(t)&&nu(e,n.href)?n:void 0}catch{return}}function Qke(e,t,n,s){try{let r=new URL(s,t.origin),i=s.startsWith("/")&&!s.startsWith("//")&&!nu(e,r.href)?new URL(s.slice(1),`${e.replace(/\/$/,"")}/`):r;if(!nu(e,i.href))return!1;let o=t.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");if(!n)return a===o;if(!a.startsWith(`${o}/`))return!1;let c=decodeURIComponent(a.slice(o.length+1));return/^(:[\w-]+|\{[^/{}]+\}|<[^/<>]+>)$/.test(c)}catch{return!1}}function _ke(e){return!!e&&/^(?:node|node:test|node\s+(?:.*\s)?--test(?:\s.*)?)$/i.test(e.trim())}function Dke(e){return e?.collected===!1||!!e?.collected&&_ke(e.runner)}function pN(e,t){let n=rn.realpathSync(e);return rn.lstatSync(t).isFile()&&rn.realpathSync(t)===Xt.join(n,Xt.relative(e,t))}function hm(e,t,n){try{return pN(e,t)&&rn.readFileSync(t).equals(n)}catch{return!1}}function Zw(e){try{return rn.lstatSync(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Nke(e,t,n){if(n==="unknown")return!1;for(let s=Xt.dirname(t);;s=Xt.dirname(s)){let r=Xt.join(s,"package.json");if(Zw(r))try{if(!pN(e,r))return!1;let i=JSON.parse(rn.readFileSync(r,"utf-8"));return(i.devDependencies?.["@skyramp/testbot-core"]??i.dependencies?.["@skyramp/testbot-core"])===n}catch{return!1}if(s===e)return!1}}function Pke(e){let t=Ae(e,"write.json");return t?gm(e,t):[]}function G6(e,t=Pke(e),n=[],s=[]){return t.flatMap(({record:r,source:i,original:o,spec:a,problems:c})=>{if(c.length)return c;let u=Xt.join(i.path,r.sourceAsset),d=Xt.join(i.path,r.file),p=`reading ${r.file}`;try{let h=fp(i.path,d);if(typeof h=="string")return[`${r.file}: ${h} (writeGuardedDeliveryFiles)`];if(!h.equals(o))return[`${r.file}: native source changed before guarded delivery`];p=`preparing ${r.sourceAsset}`;let g=Qu(o.toString("utf-8"),n).content;if(Si(g,e.secretValues??[])!==g)return[`${r.file}: the retained source contains a credential`];let m=pp(i.path,r.sourceAsset,Buffer.from(g));if(p=`writing ${r.sourceAsset}`,Zw(u)){if(!hm(i.path,u,o)&&!hm(i.path,u,m))return[`${r.file}: the inert source asset path already contains different bytes`];hm(i.path,u,m)||(s.push(()=>rn.writeFileSync(u,o)),rn.writeFileSync(u,m))}else rn.writeFileSync(u,m,{flag:"wx"}),s.push(()=>rn.rmSync(u,{force:!0}));if(r.entry&&a){let y=sm({...a,name:ap(a.name,n)}),v=pp(i.path,r.entry,Buffer.from(y));if(!bo(v.toString("utf-8")))return[`${r.file}: the repository's file conventions changed the guarded entry`];if(Si(v.toString("utf-8"),e.secretValues??[])!==v.toString("utf-8"))return[`${r.file}: guarded delivery steps include a credential`];p=`writing ${r.entry}`,s.push(()=>rn.writeFileSync(d,o)),rn.writeFileSync(d,v)}return[]}catch(h){return[`${r.file}: could not assemble its guarded delivery files (writeGuardedDeliveryFiles): ${p} failed: ${hp(h,i.path)}`]}})}function Oke(e,t,n){let s=e.executionSafetySources?.find(r=>Xt.resolve(r.path)===Xt.resolve(t));if(s)try{return(0,Yw.execFileSync)("git",["--literal-pathspecs","ls-tree",s.head,"--",n],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]})===""}catch{return}}function Xs(e,t,n){let s=e.executionSafetySources?.find(r=>Xt.resolve(r.path)===Xt.resolve(t));if(!s||!/^[a-f0-9]{40,64}$/.test(s.head))return!1;try{let r=Xt.join(t,n),i=rn.lstatSync(r);if(!i.isFile()||rn.realpathSync(r)!==r)return!1;let o=Kw(t,s.head,n);return!o||(i.mode&73)!==0!==o.executable?!1:rn.readFileSync(r).equals(o.bytes)}catch{return!1}}var Ww=new Map;function Kw(e,t,n){let s=`${Xt.resolve(e)}\0${t}\0${n}`,r=Ww.get(s);if(r!==void 0)return r;let i=null;try{let o=(0,Yw.execFileSync)("git",["--literal-pathspecs","ls-tree",t,"--",n],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]});/^100(?:644|755) blob /.test(o)&&(i={executable:o.startsWith("100755"),bytes:(0,Yw.execFileSync)("git",["show",`${t}:${n}`],{cwd:e,stdio:["ignore","pipe","ignore"]})})}catch{i=null}return Ww.size>=1e4&&Ww.clear(),Ww.set(s,i),i}function z6(e,t,n,s){if(!s.size)return[...n];let r=new Map(n.map(o=>[Xt.resolve(o.source.path,o.record.file),o])),i=bn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]);for(let o of t.tests){if(o.change==="deleted")continue;let a=i(o.file);if(!es(a)||uo(a.rel))continue;let c=co(e.inputs,a.repository);if("error"in c)continue;let u=c.source,d=Xt.resolve(u.path,a.rel),p=s.get(d);if(!p)continue;let h=r.get(d);if(h){if(h.record.reason)continue;let b={...h.record,reason:p};delete b.entry,r.set(d,{...h,record:b,spec:void 0});continue}let g={repository:u.slug,file:a.rel,sourceAsset:`${a.rel}.source`,reason:p},m=b=>[`${o.file}: shared-environment delivery is blocked: ${b}`],y=fp(u.path,d);if(typeof y=="string"){r.set(d,{record:g,source:u,original:Buffer.alloc(0),problems:m(`${y} (holdDependents)`)});continue}let v=Xt.resolve(u.path,g.sourceAsset),E=Zw(v)&&!hm(u.path,v,y)?m("the inert source asset path already contains different bytes"):[];r.set(d,{record:g,source:u,original:y,problems:E})}return[...r.values()]}var Rs=G(require("node:fs")),$e=G(require("node:path"));var Ou=G(require("path"));var l4e={python:"pytest",typescript:"playwright",javascript:"playwright"},d4e={pytest:"pytest",playwright:"playwright"};var jke=new Set(["package.json","package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb","pyproject.toml","poetry.lock","uv.lock","pdm.lock","Pipfile","Pipfile.lock","setup.py","setup.cfg","go.mod","go.sum","Gemfile","Gemfile.lock","pom.xml","build.gradle","build.gradle.kts"]);function mm(e){let t=Ou.basename(e);return jke.has(t)||/^requirements[^/\\]*\.(txt|in)$/.test(t)}var J6="shared-environment delivery cannot verify it for guarded execution",W6=(e,t)=>`${Es(e.inputs,t.source.slug)}${t.file}`;function Xw(e,t,n){let s=bn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),r=new Set(n.map(i=>$e.resolve(i.source.path,i.record.file)));return t.tests.filter(i=>{let o=s(i.file);return!r.has($e.resolve(o.root,o.rel))&&i.change!=="updated"&&gp(e,i)})}function eI(e,t,n,s){let r=bn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),i=new Map(n.map(c=>[$e.resolve(c.source.path,c.record.file),c])),o=new Set,a=[];for(let c of t.tests){let u=r(c.file),d=$e.resolve(u.root,u.rel),p=i.get(d);if(p){o.add($e.resolve(u.root,p.record.sourceAsset)),p.record.entry&&o.add(d);continue}if(c.change==="deleted"){nRe(e,u.root,u.rel)?o.add(d):a.push(`${c.file}: a deleted shared-environment test must actually be absent and be a tracked regular file in the host-pinned source`);continue}if(c.change==="updated"||!gp(e,c)){o.add(d);continue}if(Xs(e,u.root,u.rel)){o.add(d);continue}try{let h=bo(Rs.readFileSync(d,"utf-8"));if(!h)continue;if(o.add(d),"restriction"in h){let g=$e.resolve($e.dirname(d),h.sourceAsset.path);o.add(g),!s.has(g)&&!Xs(e,u.root,$e.relative(u.root,g))&&a.push(`${c.file}: its restricted source asset is missing from the actual delivery commit`)}}catch{}}return{allowed:o,problems:a}}function tI(e,t,n,s){let r=[];for(let[i,o]of t)for(let a of o)n.has($e.resolve(i.path,a))||!s.length&&!e.inputs.deliver&&ro().version==="unknown"||tRe(e,i.path,a)||Xs(e,i.path,a)||r.push({source:i,file:a});return r}var Y6=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".json"],Z6=/(?:\bfrom\s*|\bimport(?:\s*\()?\s*|\brequire\s*\(\s*)["'`]([^"'`\n]+)["'`]/g,Vke=/^[ \t]*from[ \t]+([.\w]+)[ \t]+import[ \t]+\(?([\w\t ,*]+)/gm,Gke=/^[ \t]*import[ \t]+([\w.]+)/gm;function zke(e,t){if(!/^\.\.?(?:\/|$)/.test(t))return[];let n=$e.resolve(e,t),s=/\.[cm]?jsx?$/.test(n)?[n.replace(/\.([cm]?)js(x?)$/,".$1ts$2")]:[];return[n,...s,...Y6.flatMap(r=>[n+r,$e.join(n,`index${r}`)])]}function q6(e,t,n,s){let r=/^\.*/.exec(n)[0].length,i=n.slice(r).split(".").filter(Boolean);return(r?[$e.resolve(t,...Array(r-1).fill(".."))]:[e,t]).flatMap(a=>{let c=$e.join(a,...i);return[`${c}.py`,$e.join(c,"__init__.py"),...s.map(u=>$e.join(c,`${u}.py`))]})}function qke(e,t,n){let s=$e.dirname(t),r=new Set;if(t.endsWith(".py")){for(let[,i,o]of n.matchAll(Vke))for(let a of q6(e,s,i,o.split(/[\s,]+/).filter(c=>/^\w+$/.test(c))))r.add(a);for(let[,i]of n.matchAll(Gke))for(let o of q6(e,s,i,[]))r.add(o)}else for(let[,i]of n.matchAll(Z6))for(let o of zke(s,i))r.add(o);return r}function Hke(e,t){let n=new Set;if(e.endsWith(".py")||e.endsWith(".go"))return n;for(let[,s]of t.matchAll(Z6)){if(/^\.\.?(?:\/|$)/.test(s)||/^[a-z][\w+.-]*:/i.test(s))continue;let r=s.split("/").pop()??"";r&&n.add(r.replace(/\.[cm]?[jt]sx?$/,""))}return n}function Jke(e,t){let n=$e.extname(t);if(!Y6.includes(n))return!1;let s=$e.basename(t,n);return e.has(s)||s==="index"&&e.has($e.basename($e.dirname(t)))}function Wke(e,t){let n=$e.basename(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?<![\\w.-])${n}(?![\\w.-])`).test(e)}function H6(e,t){for(let n=$e.dirname(t);;n=$e.dirname(n)){if(Rs.existsSync($e.join(n,"go.mod")))return n;if(n===e||$e.dirname(n)===n)return e}}function Yke(e,t){let n=[];t.isolatedRun&&n.push({cwd:".",text:t.isolatedRun}),t.run&&n.push({cwd:t.run.cwd,text:t.run.argv.join(" ")}),t.ci?.list&&n.push({cwd:t.ci.list.cwd,text:t.ci.list.argv.join(" ")});for(let r of t.ci?.steps??[])n.push({cwd:".",text:r.line});for(let r of t.context??[])r.cleanup&&n.push({cwd:".",text:r.cleanup});let s=new Set;for(let{cwd:r,text:i}of n)for(let o of i.split(/[\s"'`;&|()<>=,]+/))o&&!/^[a-z][\w+.-]*:/i.test(o)&&s.add($e.resolve(e,r,o));return s}var Zke={".py":"python",".js":"node",".cjs":"node",".mjs":"node",".jsx":"node",".ts":"node",".cts":"node",".mts":"node",".tsx":"node",".go":"go",".rb":"ruby",".java":"jvm",".kt":"jvm",".kts":"jvm",".scala":"jvm",".groovy":"jvm"},Kke=[[/^(?:playwright|vitest|jest)\.config\.(?:[cm]?[jt]s|json)$/,"node"],[/^tsconfig\.json$/,"node"],[/^(?:pytest|tox)\.ini$/,"python"]];function Xke(e){let t=$e.basename(e);if(["conftest.py","__init__.py"].includes(t))return"python";let n=Kke.find(([s])=>s.test(t));if(n)return n[1];if(mm(e))return/^(?:package\.json|package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lockb?)$/.test(t)?"node":/^go\.(?:mod|sum)$/.test(t)?"go":/^Gemfile(?:\.lock)?$/.test(t)?"ruby":/^(?:pom\.xml|build\.gradle(?:\.kts)?)$/.test(t)?"jvm":"python"}function eRe(e,t,n){let s=Zke[$e.extname(t)];if(s==="go"&&$e.extname(n)===".go"&&H6(e,n)===H6(e,t))return!0;let r=Xke(n);if(!r||s&&s!==r)return!1;let i=$e.relative($e.dirname(n),t);return!i.startsWith("..")&&!$e.isAbsolute(i)}function K6(e,t,n){let s=new Map;if(!n.length)return s;let r=bn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]);for(let i of t.tests){if(i.change==="deleted")continue;let o=r(i.file);if(!es(o)||Xs(e,o.root,o.rel))continue;let a=$e.resolve(o.root),c=$e.resolve(a,o.rel),u=n.filter(y=>$e.resolve(y.source.path)===a);if(!u.length)continue;let d="";try{d=Rs.readFileSync(c,"utf-8")}catch{}let p=qke(a,c,d),h=Hke(c,d),g=Yke(a,i),m=u.filter(y=>{let v=$e.resolve(a,y.file);return p.has(v)||g.has(v)||Jke(h,v)||Wke(d,v)||eRe(a,c,v)});m.length&&s.set(c,`needs ${m.map(y=>W6(e,y)).join(", ")}, which is not in the tests PR: ${J6}`)}return s}function Ua(e){return Array.isArray(e)?`[${e.map(Ua).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Ua(n)}`).join(",")}}`:JSON.stringify(e)??"undefined"}function tRe(e,t,n){let s=$e.basename(n);if(s!=="package.json"&&s!=="package-lock.json")return!1;let r=ro().version;if(r==="unknown")return!1;let i,o;try{let a=$e.resolve(t,n);if(!Rs.lstatSync(a).isFile()||Rs.realpathSync(a)!==a)return!1;i=JSON.parse(Rs.readFileSync(a,"utf-8"));let c=e.executionSafetySources?.find(h=>$e.resolve(h.path)===$e.resolve(t));if(c){let h=Kw(t,c.head,n);h&&(o=JSON.parse(h.bytes.toString("utf-8")))}else if(Rs.existsSync($e.join(t,".git")))return!1;let u=h=>{let g=structuredClone(h);for(let m of["dependencies","devDependencies"])g[m]&&(delete g[m]["@skyramp/testbot-core"],Object.keys(g[m]).length||delete g[m]);return g};if(s==="package.json")return(i.devDependencies?.["@skyramp/testbot-core"]??i.dependencies?.["@skyramp/testbot-core"])!==r?!1:o?Ua(u(i))===Ua(u(o)):Object.keys(i).every(h=>["name","version","private","type","scripts","dependencies","devDependencies"].includes(h))&&(!i.scripts||Ua(i.scripts)===Ua({test:"node --test"}))&&Object.keys(i.dependencies??{}).every(h=>h==="@skyramp/testbot-core")&&Object.keys(i.devDependencies??{}).every(h=>h==="@skyramp/testbot-core");let d=i.packages?.["node_modules/@skyramp/testbot-core"];if(!d||d.version!==r||d.link||d.hasInstallScript||d.resolved!==`https://registry.npmjs.org/@skyramp/testbot-core/-/testbot-core-${r}.tgz`||!/^sha512-[A-Za-z0-9+/=]+$/.test(d.integrity??""))return!1;let p=h=>{let g=structuredClone(h);return g.packages&&(delete g.packages["node_modules/@skyramp/testbot-core"],g.packages[""]&&(g.packages[""]=u(g.packages[""]))),g};return o?Ua(p(i))===Ua(p(o)):Object.keys(i.packages??{}).every(h=>h===""||h==="node_modules/@skyramp/testbot-core")&&!i.packages?.[""]?.scripts}catch{return!1}}function nRe(e,t,n){try{return Rs.lstatSync($e.join(t,n)),!1}catch(r){if(r.code!=="ENOENT")return!1}let s=e.executionSafetySources?.find(r=>$e.resolve(r.path)===$e.resolve(t));return!s||!/^[a-f0-9]{40,64}$/.test(s.head)?!1:Kw(t,s.head,n)!==null}function rRe(e){try{return nI.lstatSync(e),!0}catch{return!1}}function rI(e,t=Am(e)){let n=new Set(t.omitted.map(({source:s,file:r})=>Ht.resolve(s.path,r)));return new Map([...X6(e,t.assemblies)].map(([s,r])=>[s,r.filter(i=>!n.has(Ht.resolve(s.path,i)))]))}function Am(e,t=Ae(e,"write.json")){if(!t||!vn(e.inputs))return{assemblies:[],omitted:[],hasSharedTests:!1};let n=gm(e,t),s=bn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),r=new Set(t.tests.map(a=>{let c=s(a.file);return Ht.resolve(c.root,c.rel)})),i=[],o=n;for(;;){let a=o.length>0||Xw(e,t,o).length>0;if(!a)return{assemblies:o,omitted:i,hasSharedTests:a};let c=X6(e,o),u=new Set([...c].flatMap(([g,m])=>m.map(y=>Ht.resolve(g.path,y)))),{allowed:d}=eI(e,t,o,u),p=new Set(i.map(({source:g,file:m})=>Ht.resolve(g.path,m))),h=tI(e,c,d,o).filter(({source:g,file:m})=>{let y=Ht.resolve(g.path,m);return!p.has(y)&&!r.has(y)});if(!h.length)return{assemblies:o,omitted:i,hasSharedTests:a};i.push(...h),o=z6(e,t,n,K6(e,t,i))}}function X6(e,t){let n=new Set(t.filter(({record:v})=>!v.entry).map(({source:v,record:E})=>Ht.join(v.path,E.file))),s=Ae(e,"adapt.json"),r=Ae(e,"finalize.json"),i=Ae(e,um),o=new Map,a=v=>{let E=co(e.inputs,v);if("error"in E)return;let b=o.get(E.source.path)??{source:E.source,paths:new Set};return o.set(E.source.path,b),{repo:b.source.path,paths:b.paths}},c=(v,E)=>Ht.relative(v,Ht.resolve(v,E.trim())).replace(/\/+$/,""),u=(v,E)=>{let b=E?.trim()&&a(v);if(!b)return;let I=c(b.repo,E);b.paths.add(I);for(let C of["__init__.py","conftest.py"]){let w=Ht.join(Ht.dirname(I),C);nI.existsSync(Ht.join(b.repo,w))&&(!n.has(Ht.join(b.repo,I))||!Xs(e,b.repo,w))&&b.paths.add(w)}},d=(v,E)=>{if(typeof E!="string"||!E.trim())return;let b=a(v);if(!b)return;let I=c(b.repo,E);if(np(Ht.join(b.repo,I)))return b.paths.add(I),{...b,rel:I}},p=uN(e),h=(s?.items??[]).filter(v=>v.action==="place"&&p.has(v.from??v.file??"")),g=(v,E)=>h.some(b=>b.repository===v&&b.file&&Ht.normalize(b.file)===E),m=(s?.items??[]).filter(v=>!h.includes(v));for(let v of[...m,...i?.tests??[],...i?.maintained??[]])u(v.repository,v.file);for(let v of r?.dependencies?.added??[]){let E=d(v.repository,v.manifest);if(E)for(let b of fD(E.repo,Iw(E.repo,E.rel)))E.paths.add(b)}for(let v of r?.lint??[])for(let E of v.fixed??[])d(v.repository,E);for(let v of r?.support??[])d(v.repository,v.file);let y=Ae(e,kw)?.packages??[];for(let v of new Set(y.map(E=>E.repository))){let E=a(v),b=y.filter(I=>I.repository===v).map(I=>I.dir);if(E)for(let{path:I}of nm(E.repo)){let C=c(E.repo,I),w=Ht.join(E.repo,C);Hg(C,b)&&!ED(C)&&!g(v,C)&&(!rRe(w)||np(w))&&E.paths.add(C)}}for(let{record:v,source:E,problems:b}of t){let I=o.get(E.path)?.paths;I?.has(v.file)&&(I.delete(v.file),!b.length&&(v.entry&&I.add(v.entry),I.add(v.sourceAsset)))}return new Map([...o.values()].map(({source:v,paths:E})=>[v,[...E].filter(b=>b&&b!==".."&&!b.startsWith(`..${Ht.sep}`)&&!uo(b))]))}var AZe=5*6e4,yZe=12*6e4,EZe=2*6e4;var SZe=["class TestbotProjectBrowsers {"," onBegin(config) {",' const projects = config.projects.map((p) => ({ browserName: p.use.browserName ?? p.use.defaultBrowserType ?? "chromium", channel: p.use.channel ?? null }));',' process.stdout.write("TESTBOT_PROJECT_BROWSERS " + JSON.stringify(projects) + "\\n");'," }"," printsToStdio() { return true; }","}","module.exports = TestbotProjectBrowsers;",""].join(`
|
|
301
301
|
`);var Qr=G(require("fs")),Io=G(require("path"));var Fa=G(require("fs")),sI=G(require("path"));var aRe="change-inputs",cRe=(e,t)=>`${t}-${e.replace(/[^\w.-]+/g,n=>n==="/"?"__":"-")}.md`;function uRe(e){return[...(e.pullRequests??[]).map(t=>({label:`${t.repository}#${t.number}`,body:t.body?.trim()??""})),...(e.relatedRepos??[]).map(t=>({label:t.slug,body:t.prDescription?.trim()??""}))].map((t,n)=>({...t,file:cRe(t.label,n)})).filter(t=>t.body.length>mq)}function e9(e,t,n){let s=sI.join(t,aRe);Fa.rmSync(s,{recursive:!0,force:!0}),Fa.mkdirSync(s,{recursive:!0}),Fa.writeFileSync(sI.join(s,su),n,{mode:292});for(let r of uRe(e))Fa.writeFileSync(sI.join(s,r.file),`${r.body}
|
|
302
302
|
`,{mode:292})}var lRe=[/^\.github\//,/^\.gitlab(-ci)?/,/^\.circleci\//,/(^|\/)Jenkinsfile$/,/^docs?\//,/\.(md|mdx|rst)$/i,/(^|\/)LICENSE([._-].*)?$/i,/(^|\/)CODEOWNERS$/,/(^|\/)\.gitignore$/,/(^|\/)\.gitattributes$/,/(^|\/)\.editorconfig$/,/(^|\/)\.prettierrc[^/]*$/,/(^|\/)\.eslintrc[^/]*$/,/(^|\/)eslint\.config\.[^/]+$/,/(^|\/)package-lock\.json$/,/(^|\/)yarn\.lock$/,/(^|\/)pnpm-lock\.yaml$/,/(^|\/)poetry\.lock$/,/(^|\/)Pipfile\.lock$/,/(^|\/)Cargo\.lock$/,/(^|\/)go\.sum$/,/(^|\/)composer\.lock$/,/(^|\/)Gemfile\.lock$/,/\.(png|jpe?g|gif|svg|ico|webp)$/i];function t9(e){return lRe.some(t=>t.test(e))}function dRe(e){let t=[],n=e.inputs.repositoryPath;return!n||!Qr.existsSync(n)?t.push(`repository path does not exist: ${n}`):WR(n)?nd(n,e.inputs.baseBranch)||t.push(e.inputs.baseBranch?`base branch "${e.inputs.baseBranch}" does not resolve`:"could not auto-detect a base branch (origin/HEAD, main, master)"):t.push(`not a git repository: ${n}`),{ok:t.length===0,reasons:t}}function pRe(e){return(e.inputs.relatedRepos??[]).map(t=>{let n=Qr.existsSync(t.path)?wE(t.path,t.base):void 0;return n?{repository:t.slug,changedFiles:n.changedFiles}:{repository:t.slug,changedFiles:[],note:`could not read the change in ${t.path}`}})}function fRe(e){Qr.rmSync(Io.join(e.runDir,vB),{recursive:!0,force:!0});for(let t of e.inputs.relatedRepos??[]){let n=Qr.existsSync(t.path)?YR(t.path,t.base):void 0;if(!n)continue;let s=Io.join(e.runDir,bB(t.slug));Qr.mkdirSync(Io.dirname(s),{recursive:!0}),Qr.writeFileSync(s,n.diffContent)}}function hRe(e){let{repositoryPath:t,baseBranch:n}=e.inputs;Qr.rmSync(Io.join(t,VD),{recursive:!0,force:!0});let s=wE(t,n);if(!s)throw new Error(`could not compute git facts for ${t}`);let r=YR(t,n);if(!r)throw new Error(`could not compute the PR diff for ${t}`);let i=pRe(e),o=[s.changedFiles,...i.map(p=>p.changedFiles)].flat(),a=o.map(p=>p.path).filter(t9),c=!ud(e)&&o.length>0&&a.length===o.length,u={schemaVersion:1,repository:{path:t,currentBranch:s.currentBranch,baseBranch:s.baseBranch},changedFiles:s.changedFiles,...i.length?{relatedChanges:i}:{},newFiles:r.newFiles,deletedFiles:r.deletedFiles,diffStat:r.diffStat,diffBytes:r.diffContent.length,nonApplicationFiles:a,nonApplicationOnly:c,sutRequired:!c};Qr.writeFileSync(Io.join(e.runDir,su),r.diffContent),e9(e.inputs,e.runDir,r.diffContent),fRe(e);let d=Io.join(e.runDir,EB);return Qr.mkdirSync(Io.dirname(d),{recursive:!0}),Qr.writeFileSync(d,JSON.stringify(u,null,2)+`
|
|
303
|
-
`),e.prepared={preflight:u},{preflight:EB,diff:su}}var
|
|
304
|
-
`).filter(Boolean).flatMap(s=>{let[r,i]=s.split(" "),o=DRe.exec(i??"");if(!o)return[];let a=new Set(e(["diff","--name-only","-z",`${r}^1`,r]).split("\0").filter(Boolean));return[{...o[1]?{pullRequest:o[1]}:{branch:o[2]},files:a}]})}var _9=require("node:zlib");var P8e=["clean","recipe-drift"];var _n=G(require("node:fs")),Ut=G(require("node:path")),oI=require("node:crypto");function NRe(e,t,n=ro().version){if(!vn(e.inputs))return[];let s=bn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),r=gm(e,t,n),i=new Map(r.map(o=>[Ut.resolve(o.source.path,o.record.file),o.problems]));return t.tests.flatMap(o=>{let a=s(o.file),c=i.get(Ut.resolve(a.root,a.rel));if(c)return c;if(o.change!=="added")return[];if(!gp(e,o))return[];let d=m=>[`${o.file}: shared-environment delivery is blocked: ${m}`];if(!es(a))return d("test file is outside its checkout");let p=fp(a.root,Ut.join(a.root,a.rel));if(typeof p=="string")return d(`${p} (restrictedDeliveryProblems)`);let h=bo(p.toString("utf-8"));if(!h)return d("use the exact supported delivered harness; preserve unsupported assertions in an inactive source asset, never unrestricted executable code");if("restriction"in h){if(!h.sourceAsset.path.endsWith(".source"))return d("restricted source asset must use an inactive .source extension");let m=Ut.resolve(Ut.dirname(Ut.join(a.root,a.rel)),h.sourceAsset.path),y=Ut.relative(a.root,m);if(!y||y.startsWith("..")||Ut.isAbsolute(y))return d("restricted source asset must remain inside its checkout");try{if(!_n.lstatSync(m).isFile()||_n.realpathSync(m)!==m||(0,oI.createHash)("sha256").update(_n.readFileSync(m)).digest("hex")!==h.sourceAsset.sha256)return d("restricted source asset is missing, changed or a symlink")}catch{return d("restricted source asset is unavailable")}if(!(t.supportFiles??[]).some(v=>{let E=s(v);return Ut.join(E.root,E.rel)===m}))return d("restricted source asset must be delivered in supportFiles")}else{let m=e.inputs.sharedEnvironment;if(h.definition.environmentId!==m?.environmentId||h.definition.environmentAddress!==m?.environmentAddress)return d("harness identity/address differs from the selected Test Environment");if((m.offLimits??[]).some(y=>!h.definition.offLimits.includes(y)))return d("harness omits a configured off-limits route")}if(n==="unknown")return e.inputs.deliver?d("guarded CI delivery is unavailable from an unreleased engine build"):[];let g=Ut.dirname(Ut.join(a.root,a.rel));for(;g.startsWith(a.root);){let m=Ut.join(g,"package.json");if(_n.existsSync(m))try{let y=JSON.parse(_n.readFileSync(m,"utf-8"));return(y.devDependencies?.["@skyramp/testbot-core"]??y.dependencies?.["@skyramp/testbot-core"])===n?[]:d("declare the exact released engine version containing this harness; an unavailable or older runtime cannot protect direct invocation")}catch{return d("test package manifest is unreadable")}if(g===a.root)break;g=Ut.dirname(g)}return d("the delivered test has no package manifest declaring its guarded runtime")})}function EN(e,t){if(!vn(e.inputs))return[];let n=Ae(e,"write.json");if(!n)return["shared-environment delivery requires its generated-test record"];let s=bn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),r=t??Am(e,n),{assemblies:i}=r;if(!r.hasSharedTests)return n.tests.flatMap(d=>{if(d.change!=="deleted")return[];let p=s(d.file);return es(p)&&_n.existsSync(Ut.join(p.root,p.rel))?[`${d.file}: a deleted test must actually be absent`]:[]});let o=Xw(e,n,i).filter(d=>{let p=s(d.file);return d.change!=="deleted"&&!Xs(e,p.root,p.rel)}).map(d=>({...d,change:"added"})),a=rI(e,r),c=new Set([...a].flatMap(([d,p])=>p.map(h=>Ut.resolve(d.path,h)))),u=eI(e,n,i,c);return[...i.flatMap(d=>d.problems),...NRe(e,{...n,tests:o}),...u.problems,...tI(e,a,u.allowed,i).map(({file:d})=>`${d}: shared-environment delivery refuses an unverified executable/support/manifest path`)]}function c9(e,t,n=[]){if(!vn(e.inputs))return[];let s=[],r=bn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]);for(let i of t.tests){if(i.change==="deleted")continue;let o=r(i.file),a=Ut.join(o.root,o.rel);if(Xs(e,o.root,o.rel)||!es(o)||dN(o.root,a))continue;let c=`reading ${o.rel}`;try{let u=bo(_n.readFileSync(a,"utf-8"));if(!u)continue;if("restriction"in u){let p=Ut.resolve(Ut.dirname(a),u.sourceAsset.path),h=Ut.relative(o.root,p);if(c=`reading ${h}`,!h||h.startsWith("..")||Ut.isAbsolute(h)||!_n.lstatSync(p).isFile()||_n.realpathSync(p)!==p){s.push(`${i.file}: restricted source asset is not a regular file in its checkout`);continue}let g=_n.readFileSync(p);if((0,oI.createHash)("sha256").update(g).digest("hex")!==u.sourceAsset.sha256){s.push(`${i.file}: restricted source asset changed before trusted formatting; not refreshing its hash`);continue}let m=Qu(g.toString("utf-8"),n).content,y=pp(o.root,h,Buffer.from(m));c=`writing ${h}`,_n.writeFileSync(p,y),u.sourceAsset.sha256=(0,oI.createHash)("sha256").update(y).digest("hex")}let d=Qu(sm(u),n).content;c=`writing ${o.rel}`,_n.writeFileSync(a,pp(o.root,o.rel,Buffer.from(d)))}catch(u){s.push(`${i.file}: could not assemble its guarded entry after trusted formatting (prepareSharedDeliveryFiles): ${c} failed: ${hp(u,o.root)}`)}}return s}var wn=G(require("fs")),ei=G(require("path")),S9=G(require("crypto")),k9=require("child_process");var Cm=require("crypto");var vN="<!-- skyramp-testbot -->",bN=gN,ORe=new Set(["lint","type","config"]),u9={critical:0,high:1,medium:2,low:3},A9=new Set(["Pass","Fail"]);var wN=e=>ea(ne().statusLabels,e),cI=e=>ea(ne().testTypeCellLabels,e);function dt(e){return(e??"").replace(/\|/g,"\\|").replace(/\r?\n/g,"<br>").trim()}function l9(e){return e.inferred?" (inferred)":""}function d9(e,t){return!e||!A9.has(e)?"\u2014":t?`${wN(e)} (${dt(y9(t))})`:wN(e)}function y9(e){let t=s=>{let r=s.indexOf(": ");return r<0?s:ea(ne().staged.maintenanceActions,s.slice(0,r))+s.slice(r)};if(e.startsWith(Em))return ne().staged.keptNot+t(e.slice(Em.length));let n=e.indexOf(vm);return n<0?e:e.slice(0,n)+ne().staged.declinedPlanned+t(e.slice(n+vm.length))}function p9(e){return e.category!==void 0&&ORe.has(e.category.toLowerCase())}function f9(e,t){return(u9[(e.severity??"").toLowerCase()]??4)-(u9[(t.severity??"").toLowerCase()]??4)}var uI=e=>e?.length?` (${e.join(", ")})`:"";function h9(e){return`- ${e.severity?`**[${ea(ne().severityLabels,e.severity.toLowerCase()).toUpperCase()}]** `:""}${e.description.trim()}${uI(e.pullRequests)}`}function URe(e){let t=e.resultId?.split("#").slice(1).join("#");if(e.testType!=="unit"||!t)return;let n=t;try{n=decodeURIComponent(t)}catch{}let s=/^(.*?)(\[.*\])$/.exec(n);return s?{fn:s[1],kase:s[2]}:{fn:n}}var E9=(e,t)=>e!==void 0&&t!==void 0&&e.replace(/^\.\//,"")===t.replace(/^\.\//,"");function v9(e,t){return(e.testVideos??[]).find(n=>n.url&&t(n))?.url}function IN(e,t){return v9(e,n=>E9(n.fileName,t.fileName)&&(!n.repository||!t.repository||n.repository.toLowerCase()===t.repository.toLowerCase()))}function CN(e,t){return v9(e,n=>E9(n.writtenAs??n.fileName,t))}function FRe(e,t,n){return n?IN(e,{fileName:t,repository:n}):CN(e,t)}function MRe(e){let t=[],n=new Map;for(let o of e.newTestsCreated)o.testType==="unit"&&n.set(o.fileName,[...n.get(o.fileName)??[],o.testId.split("::").slice(1).join("::")]);let s=new Map,r=(o,a)=>(n.get(o??"")??[]).find(c=>c!==a&&YZ(a,c)),i=new Map;for(let o of e.testResults){let a=URe(o),c=a&&!a.kase?r(o.fileName,a.fn):void 0;if(a&&c&&(a={fn:c,kase:`"${a.fn}"`}),a?.kase&&s.set(o,a.kase),!a){t.push({testId:o.testId,testType:o.testType,endpoint:o.endpoint,status:o.status,details:o.details??"",...o.fileName?{fileName:o.fileName}:{},...o.repository?{repository:o.repository}:{}});continue}let u=`${o.fileName??""}#${a.fn}`,d=i.get(u);d||(d={row:{testId:o.testId,testType:o.testType,endpoint:o.endpoint,status:o.status,details:"",test:a.fn,...o.fileName?{fileName:o.fileName}:{},...o.repository?{repository:o.repository}:{}},cases:[]},i.set(u,d),t.push(d.row)),d.cases.push(o)}for(let{row:o,cases:a}of i.values()){let c=a.filter(h=>h.status==="Fail"),u=a.filter(h=>h.status==="Pass").length,d=a.filter(h=>h.status==="Skipped").length;o.cases=a.length,o.status=c.length?"Fail":d?"Skipped":"Pass";let p=c[0];o.details=a.length===1?a[0].details??"":ne().staged.casesPassed(u,a.length,d)+(p?`; ${s.get(p)??""} ${p.details??""}`.replace(/; +/,"; ").trimEnd():"")}return t}function LRe(e){return hN(e).map(t=>t.expected===void 0?t.expectation:`${t.expectation}: ${Kt(t.expected)}`)}function Im(e){return e.newTestsCreated.some(t=>t.testType!=="unit")&&e.testResults.every(t=>t.status==="Skipped")&&e.testResults.some(t=>t.failureCause?.kind==="environment"&&(t.failureCause.family==="app_not_started"||t.failureCause.family==="secret"))}function b9(e){let t=e.pullRequests??[];return t.length<2?[]:[ne().staged.validatedTogether(t.map(n=>`${Kt(`${n.repository}#${n.number}`)}${n.title?` ${Bs(n.title,120)}`:""}`).join("; "))]}function w9(e,t=1/0){let n=Array.from(e.name.replace(/\s+/g," ").trim()).slice(0,t).join("").replace(/[<>[\]()*_`\\|#]/g,"\\$&").replace(/@/g,"@\u200D");return e.kind==="person"?ne().staged.requestedByPerson(n):ne().staged.requestedByPolicy(n)}function I9(e,t={}){if(t.audience==="testbot-pr")return WRe(e,t);let{audience:n,collapsed:s=!1,existingEvidence:r=[],requestedBy:i,sourcePullRequest:o}=t,a=n!=="comment",c=(e.requirements??[]).filter(w=>/^file-[a-f0-9]{16}-/i.test(w.id)).sort((w,x)=>x.id.length-w.id.length),u=w=>{let x=c.find(S=>w.toLowerCase().startsWith(S.id.toLowerCase()));return x?x.label+w.slice(x.id.length):w},d=[vN];o&&d.push(ne().staged.testsSourcePullRequest(Kt(o)),"");for(let w of b9(e))d.push(w,"");i&&d.push(w9(i),""),e.notTranslated&&d.push(ea(ne().staged.notTranslated,e.notTranslated),"");let p=w=>{s?d.push("<details>",`<summary>${w}</summary>`,""):d.push(`### ${w}`)},h=()=>{s&&d.push("","</details>"),d.push("")};for(let w of e.businessCaseAnalysis.trim().split(/\r?\n/))d.push(`> ${w}`);if(d.push(""),Im(e)&&d.push(ne().staged.noLiveApp(mp(e.newTestsCreated)),""),a&&e.newTestsCreated.length){let w=new Map;for(let S of e.newTestsCreated){if(S.testType!=="unit")continue;let Y=fN(S)[0],ae=w.get(S.fileName)??{functions:new Set,endpoints:[],descriptions:new Map};S.endpoint&&!ae.endpoints.includes(S.endpoint)&&ae.endpoints.push(S.endpoint);let J=S.description?.trim()??"",be=ae.descriptions.get(Y)??[];be.includes(J)||be.push(J),ae.functions.add(Y),ae.descriptions.set(Y,be),w.set(S.fileName,ae)}let x=e.newTestsCreated.filter(S=>S.testType!=="unit");p(ne().testRecommendationsImplementedHeader(mp(e.newTestsCreated),x.length+mp(e.newTestsCreated.filter(S=>S.testType==="unit"))));for(let[S,{functions:Y,endpoints:ae,descriptions:J}]of w){let be=Y.size;d.push(ne().staged.unitTestsInFile(`\`${S}\``,be,ae.map(ke=>`\`${ke}\``).join(", ")),"");let Me=new Map;for(let[ke,X]of J){let z=X.join("\0"),Je=Me.get(z)??{fns:[],descriptions:X};Je.fns.push(ke),Me.set(z,Je)}let Ge=0;for(let{fns:ke,descriptions:X}of Me.values()){d.push(`${++Ge}. ${ke.map(Je=>`\`${Je}\``).join(", ")}`);let z=[...new Set(X.flatMap(Je=>LRe(Je)))];for(let Je of z)d.push(` - ${Je}`)}d.push("")}for(let S of x){let Y=S.testId?Kt(u(S.testId)):cI(S.testType),ae=S.fileName?` (\`${S.fileName}\`)`:"",J=S.endpoint?`
|
|
303
|
+
`),e.prepared={preflight:u},{preflight:EB,diff:su}}var RKe={name:"preflight",timeoutMinutes:1,requires:[],validateInput:dRe,execute:hRe};var ym=G(require("path"));function mRe(e){return Vn(PD,e).errors}function ARe(e,t=[]){let{value:n,error:s}=Yt(e,t);if(s)return{errors:[s]};let r=mRe(n);return r.length>0?{errors:r}:{finalize:n,errors:[]}}var yRe="finalize-scratch";function ERe(e,t){let n=ARe(e.stdout,t?.secretValues);if(!n.finalize||!t?.outputsDir)return n;let s=(r,i)=>r.trim()&&iE(r.trim(),ym.join(t.outputsDir,yRe,i),"finalize")||r;return{...n,finalize:{...n.finalize,lint:n.finalize.lint.map((r,i)=>({...r,command:s(r.command??"",`lint-${i+1}.sh`)}))}}}var G6e=Ir("finalize-schema",(e,t)=>ERe(t,e));function fN(e){return e.functions?.length?e.functions:[(e.testType==="unit"?e.testId.split("::").slice(1).join("::").replace(/\[.*\]$/,""):"")||e.testId]}function mp(e){return new Set(e.flatMap(t=>fN(t).map(n=>`${t.repository??""}\0${t.fileName}\0${n}`))).size}function vRe(e){return Vn(ND,e).errors}function n9(e,t=[]){let{value:n,error:s}=Yt(e,t);if(s)return{errors:[s]};let r=vRe(n);return r.length>0?{errors:r}:{analysis:n,errors:[]}}function bRe(e,t=[]){return n9(e.stdout,t)}var d9e=Ir("analysis-schema",(e,t)=>bRe(t,e.secretValues));var c8e=Xy.rows.notRun(!0);var Em="kept, not ";var vm="(declined the planned ";function hN(e){if(!e)return[];let t=[],n=0,s=0;for(let r=0;r<e.length;r++){let i=e[r];i==="("?n++:i===")"?n=Math.max(0,n-1):n===0&&i===";"&&e[r+1]===" "&&e[r-1]===")"&&(t.push(e.slice(s,r)),s=r+2)}return t.push(e.slice(s)),t.map(r=>{let i=r.trim();if(!i.endsWith(")"))return{expectation:i};let o=0;for(let a=i.length-1;a>=0;a--)if(i[a]===")")o++;else if(i[a]==="("&&--o===0){let c=i.slice(0,a).trim(),u=i.slice(a+1,-1).trim();return c&&u?{expectation:c,expected:u}:{expectation:i}}return{expectation:i}})}var gN=new Set(["update","regenerate","delete"]);var u8e={update:"updated",regenerate:"regenerated",delete:"deleted",verify:"verified",none:"touched"};var r9=l.string().trim().min(1),mN=l.object({schemaVersion:l.literal(1).optional(),businessCaseAnalysis:r9.describe("1-2 sentences: what this change means for a user, and whether the evidence shows it working; no count of tests, which the report gives"),issuesFound:l.array(l.object({description:r9,severity:l.string().optional().describe("critical | high | medium | low"),category:l.string().optional().describe("bug | lint | type | config"),sourceFile:l.string().optional(),sourceLine:l.number().optional(),findingId:l.string().optional(),requirementIds:l.array(l.string()).optional()})).describe("every real problem this run exposed \u2014 cause, file:line, severity"),nextSteps:l.array(l.string()).describe("concrete follow-ups the author can act on; required non-empty when a disclosure is BLOCKING")});function BRe(e){return Vn(mN,e).errors}function xRe(e,t=[]){let{value:n,error:s}=Yt(e.stdout,t);if(s)return{errors:[s]};let r=BRe(n);return r.length>0?{errors:r}:{prose:n,errors:[]}}var v8e=Ir("report-schema",(e,t)=>xRe(t,e.secretValues));var QRe="report.json",_Re="report-display.json",T8e={en:"English",ja:"Japanese"};function i9(e){let t=AN.join(e,_Re);if(Ma.existsSync(t))try{return JSON.parse(Ma.readFileSync(t,"utf-8"))}catch{}let n=AN.join(e,QRe);return Ma.existsSync(n)?JSON.parse(Ma.readFileSync(n,"utf-8")):void 0}var o9="testbot.deliverFrom";var DRe=/^Testbot: merge (?:PR #(\d+)|branch (.+))$/;function a9(e,t,n){return e(["log","--merges","--first-parent","--reverse","--format=%H%x09%s",`${t}..${n}`]).split(`
|
|
304
|
+
`).filter(Boolean).flatMap(s=>{let[r,i]=s.split(" "),o=DRe.exec(i??"");if(!o)return[];let a=new Set(e(["diff","--name-only","-z",`${r}^1`,r]).split("\0").filter(Boolean));return[{...o[1]?{pullRequest:o[1]}:{branch:o[2]},files:a}]})}var _9=require("node:zlib");var U8e=["clean","recipe-drift"];var _n=G(require("node:fs")),Ut=G(require("node:path")),oI=require("node:crypto");function NRe(e,t,n=ro().version){if(!vn(e.inputs))return[];let s=bn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),r=gm(e,t,n),i=new Map(r.map(o=>[Ut.resolve(o.source.path,o.record.file),o.problems]));return t.tests.flatMap(o=>{let a=s(o.file),c=i.get(Ut.resolve(a.root,a.rel));if(c)return c;if(o.change!=="added")return[];if(!gp(e,o))return[];let d=m=>[`${o.file}: shared-environment delivery is blocked: ${m}`];if(!es(a))return d("test file is outside its checkout");let p=fp(a.root,Ut.join(a.root,a.rel));if(typeof p=="string")return d(`${p} (restrictedDeliveryProblems)`);let h=bo(p.toString("utf-8"));if(!h)return d("use the exact supported delivered harness; preserve unsupported assertions in an inactive source asset, never unrestricted executable code");if("restriction"in h){if(!h.sourceAsset.path.endsWith(".source"))return d("restricted source asset must use an inactive .source extension");let m=Ut.resolve(Ut.dirname(Ut.join(a.root,a.rel)),h.sourceAsset.path),y=Ut.relative(a.root,m);if(!y||y.startsWith("..")||Ut.isAbsolute(y))return d("restricted source asset must remain inside its checkout");try{if(!_n.lstatSync(m).isFile()||_n.realpathSync(m)!==m||(0,oI.createHash)("sha256").update(_n.readFileSync(m)).digest("hex")!==h.sourceAsset.sha256)return d("restricted source asset is missing, changed or a symlink")}catch{return d("restricted source asset is unavailable")}if(!(t.supportFiles??[]).some(v=>{let E=s(v);return Ut.join(E.root,E.rel)===m}))return d("restricted source asset must be delivered in supportFiles")}else{let m=e.inputs.sharedEnvironment;if(h.definition.environmentId!==m?.environmentId||h.definition.environmentAddress!==m?.environmentAddress)return d("harness identity/address differs from the selected Test Environment");if((m.offLimits??[]).some(y=>!h.definition.offLimits.includes(y)))return d("harness omits a configured off-limits route")}if(n==="unknown")return e.inputs.deliver?d("guarded CI delivery is unavailable from an unreleased engine build"):[];let g=Ut.dirname(Ut.join(a.root,a.rel));for(;g.startsWith(a.root);){let m=Ut.join(g,"package.json");if(_n.existsSync(m))try{let y=JSON.parse(_n.readFileSync(m,"utf-8"));return(y.devDependencies?.["@skyramp/testbot-core"]??y.dependencies?.["@skyramp/testbot-core"])===n?[]:d("declare the exact released engine version containing this harness; an unavailable or older runtime cannot protect direct invocation")}catch{return d("test package manifest is unreadable")}if(g===a.root)break;g=Ut.dirname(g)}return d("the delivered test has no package manifest declaring its guarded runtime")})}function EN(e,t){if(!vn(e.inputs))return[];let n=Ae(e,"write.json");if(!n)return["shared-environment delivery requires its generated-test record"];let s=bn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),r=t??Am(e,n),{assemblies:i}=r;if(!r.hasSharedTests)return n.tests.flatMap(d=>{if(d.change!=="deleted")return[];let p=s(d.file);return es(p)&&_n.existsSync(Ut.join(p.root,p.rel))?[`${d.file}: a deleted test must actually be absent`]:[]});let o=Xw(e,n,i).filter(d=>{let p=s(d.file);return d.change!=="deleted"&&!Xs(e,p.root,p.rel)}).map(d=>({...d,change:"added"})),a=rI(e,r),c=new Set([...a].flatMap(([d,p])=>p.map(h=>Ut.resolve(d.path,h)))),u=eI(e,n,i,c);return[...i.flatMap(d=>d.problems),...NRe(e,{...n,tests:o}),...u.problems,...tI(e,a,u.allowed,i).map(({file:d})=>`${d}: shared-environment delivery refuses an unverified executable/support/manifest path`)]}function c9(e,t,n=[]){if(!vn(e.inputs))return[];let s=[],r=bn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]);for(let i of t.tests){if(i.change==="deleted")continue;let o=r(i.file),a=Ut.join(o.root,o.rel);if(Xs(e,o.root,o.rel)||!es(o)||dN(o.root,a))continue;let c=`reading ${o.rel}`;try{let u=bo(_n.readFileSync(a,"utf-8"));if(!u)continue;if("restriction"in u){let p=Ut.resolve(Ut.dirname(a),u.sourceAsset.path),h=Ut.relative(o.root,p);if(c=`reading ${h}`,!h||h.startsWith("..")||Ut.isAbsolute(h)||!_n.lstatSync(p).isFile()||_n.realpathSync(p)!==p){s.push(`${i.file}: restricted source asset is not a regular file in its checkout`);continue}let g=_n.readFileSync(p);if((0,oI.createHash)("sha256").update(g).digest("hex")!==u.sourceAsset.sha256){s.push(`${i.file}: restricted source asset changed before trusted formatting; not refreshing its hash`);continue}let m=Qu(g.toString("utf-8"),n).content,y=pp(o.root,h,Buffer.from(m));c=`writing ${h}`,_n.writeFileSync(p,y),u.sourceAsset.sha256=(0,oI.createHash)("sha256").update(y).digest("hex")}let d=Qu(sm(u),n).content;c=`writing ${o.rel}`,_n.writeFileSync(a,pp(o.root,o.rel,Buffer.from(d)))}catch(u){s.push(`${i.file}: could not assemble its guarded entry after trusted formatting (prepareSharedDeliveryFiles): ${c} failed: ${hp(u,o.root)}`)}}return s}var wn=G(require("fs")),ei=G(require("path")),S9=G(require("crypto")),k9=require("child_process");var Cm=require("crypto");var vN="<!-- skyramp-testbot -->",bN=gN,ORe=new Set(["lint","type","config"]),u9={critical:0,high:1,medium:2,low:3},A9=new Set(["Pass","Fail"]);var wN=e=>ea(ne().statusLabels,e),cI=e=>ea(ne().testTypeCellLabels,e);function dt(e){return(e??"").replace(/\|/g,"\\|").replace(/\r?\n/g,"<br>").trim()}function l9(e){return e.inferred?" (inferred)":""}function d9(e,t){return!e||!A9.has(e)?"\u2014":t?`${wN(e)} (${dt(y9(t))})`:wN(e)}function y9(e){let t=s=>{let r=s.indexOf(": ");return r<0?s:ea(ne().staged.maintenanceActions,s.slice(0,r))+s.slice(r)};if(e.startsWith(Em))return ne().staged.keptNot+t(e.slice(Em.length));let n=e.indexOf(vm);return n<0?e:e.slice(0,n)+ne().staged.declinedPlanned+t(e.slice(n+vm.length))}function p9(e){return e.category!==void 0&&ORe.has(e.category.toLowerCase())}function f9(e,t){return(u9[(e.severity??"").toLowerCase()]??4)-(u9[(t.severity??"").toLowerCase()]??4)}var uI=e=>e?.length?` (${e.join(", ")})`:"";function h9(e){return`- ${e.severity?`**[${ea(ne().severityLabels,e.severity.toLowerCase()).toUpperCase()}]** `:""}${e.description.trim()}${uI(e.pullRequests)}`}function URe(e){let t=e.resultId?.split("#").slice(1).join("#");if(e.testType!=="unit"||!t)return;let n=t;try{n=decodeURIComponent(t)}catch{}let s=/^(.*?)(\[.*\])$/.exec(n);return s?{fn:s[1],kase:s[2]}:{fn:n}}var E9=(e,t)=>e!==void 0&&t!==void 0&&e.replace(/^\.\//,"")===t.replace(/^\.\//,"");function v9(e,t){return(e.testVideos??[]).find(n=>n.url&&t(n))?.url}function IN(e,t){return v9(e,n=>E9(n.fileName,t.fileName)&&(!n.repository||!t.repository||n.repository.toLowerCase()===t.repository.toLowerCase()))}function CN(e,t){return v9(e,n=>E9(n.writtenAs??n.fileName,t))}function FRe(e,t,n){return n?IN(e,{fileName:t,repository:n}):CN(e,t)}function MRe(e){let t=[],n=new Map;for(let o of e.newTestsCreated)o.testType==="unit"&&n.set(o.fileName,[...n.get(o.fileName)??[],o.testId.split("::").slice(1).join("::")]);let s=new Map,r=(o,a)=>(n.get(o??"")??[]).find(c=>c!==a&&YZ(a,c)),i=new Map;for(let o of e.testResults){let a=URe(o),c=a&&!a.kase?r(o.fileName,a.fn):void 0;if(a&&c&&(a={fn:c,kase:`"${a.fn}"`}),a?.kase&&s.set(o,a.kase),!a){t.push({testId:o.testId,testType:o.testType,endpoint:o.endpoint,status:o.status,details:o.details??"",...o.fileName?{fileName:o.fileName}:{},...o.repository?{repository:o.repository}:{}});continue}let u=`${o.fileName??""}#${a.fn}`,d=i.get(u);d||(d={row:{testId:o.testId,testType:o.testType,endpoint:o.endpoint,status:o.status,details:"",test:a.fn,...o.fileName?{fileName:o.fileName}:{},...o.repository?{repository:o.repository}:{}},cases:[]},i.set(u,d),t.push(d.row)),d.cases.push(o)}for(let{row:o,cases:a}of i.values()){let c=a.filter(h=>h.status==="Fail"),u=a.filter(h=>h.status==="Pass").length,d=a.filter(h=>h.status==="Skipped").length;o.cases=a.length,o.status=c.length?"Fail":d?"Skipped":"Pass";let p=c[0];o.details=a.length===1?a[0].details??"":ne().staged.casesPassed(u,a.length,d)+(p?`; ${s.get(p)??""} ${p.details??""}`.replace(/; +/,"; ").trimEnd():"")}return t}function LRe(e){return hN(e).map(t=>t.expected===void 0?t.expectation:`${t.expectation}: ${Kt(t.expected)}`)}function Im(e){return e.newTestsCreated.some(t=>t.testType!=="unit")&&e.testResults.every(t=>t.status==="Skipped")&&e.testResults.some(t=>t.failureCause?.kind==="environment"&&(t.failureCause.family==="app_not_started"||t.failureCause.family==="secret"))}function b9(e){let t=e.pullRequests??[];return t.length<2?[]:[ne().staged.validatedTogether(t.map(n=>`${Kt(`${n.repository}#${n.number}`)}${n.title?` ${Bs(n.title,120)}`:""}`).join("; "))]}function w9(e,t=1/0){let n=Array.from(e.name.replace(/\s+/g," ").trim()).slice(0,t).join("").replace(/[<>[\]()*_`\\|#]/g,"\\$&").replace(/@/g,"@\u200D");return e.kind==="person"?ne().staged.requestedByPerson(n):ne().staged.requestedByPolicy(n)}function I9(e,t={}){if(t.audience==="testbot-pr")return WRe(e,t);let{audience:n,collapsed:s=!1,existingEvidence:r=[],requestedBy:i,sourcePullRequest:o}=t,a=n!=="comment",c=(e.requirements??[]).filter(w=>/^file-[a-f0-9]{16}-/i.test(w.id)).sort((w,x)=>x.id.length-w.id.length),u=w=>{let x=c.find(S=>w.toLowerCase().startsWith(S.id.toLowerCase()));return x?x.label+w.slice(x.id.length):w},d=[vN];o&&d.push(ne().staged.testsSourcePullRequest(Kt(o)),"");for(let w of b9(e))d.push(w,"");i&&d.push(w9(i),""),e.notTranslated&&d.push(ea(ne().staged.notTranslated,e.notTranslated),"");let p=w=>{s?d.push("<details>",`<summary>${w}</summary>`,""):d.push(`### ${w}`)},h=()=>{s&&d.push("","</details>"),d.push("")};for(let w of e.businessCaseAnalysis.trim().split(/\r?\n/))d.push(`> ${w}`);if(d.push(""),Im(e)&&d.push(ne().staged.noLiveApp(mp(e.newTestsCreated)),""),a&&e.newTestsCreated.length){let w=new Map;for(let S of e.newTestsCreated){if(S.testType!=="unit")continue;let Y=fN(S)[0],ae=w.get(S.fileName)??{functions:new Set,endpoints:[],descriptions:new Map};S.endpoint&&!ae.endpoints.includes(S.endpoint)&&ae.endpoints.push(S.endpoint);let J=S.description?.trim()??"",be=ae.descriptions.get(Y)??[];be.includes(J)||be.push(J),ae.functions.add(Y),ae.descriptions.set(Y,be),w.set(S.fileName,ae)}let x=e.newTestsCreated.filter(S=>S.testType!=="unit");p(ne().testRecommendationsImplementedHeader(mp(e.newTestsCreated),x.length+mp(e.newTestsCreated.filter(S=>S.testType==="unit"))));for(let[S,{functions:Y,endpoints:ae,descriptions:J}]of w){let be=Y.size;d.push(ne().staged.unitTestsInFile(`\`${S}\``,be,ae.map(ke=>`\`${ke}\``).join(", ")),"");let Me=new Map;for(let[ke,X]of J){let z=X.join("\0"),Je=Me.get(z)??{fns:[],descriptions:X};Je.fns.push(ke),Me.set(z,Je)}let Ge=0;for(let{fns:ke,descriptions:X}of Me.values()){d.push(`${++Ge}. ${ke.map(Je=>`\`${Je}\``).join(", ")}`);let z=[...new Set(X.flatMap(Je=>LRe(Je)))];for(let Je of z)d.push(` - ${Je}`)}d.push("")}for(let S of x){let Y=S.testId?Kt(u(S.testId)):cI(S.testType),ae=S.fileName?` (\`${S.fileName}\`)`:"",J=S.endpoint?`
|
|
305
305
|
\`${S.endpoint}\``:"",be=S.description?`
|
|
306
306
|
${S.description.trim()}`:"";d.push(`- ${Y}${ae}${uI(S.pullRequests)}${J}${be}`)}h()}let g=(e.testMaintenance??[]).filter(w=>bN.has(w.action));if(a&&g.length){p(ne().staged.testMaintenanceHeader),d.push(ne().maintenanceTableHeader),d.push("|-----------|----------|------|--------|--------|-------|");for(let w of g)d.push(`| ${dt(cI(w.testType))} | ${dt(w.endpoint)} | \`${dt(w.fileName)}\` | ${dt(w.description)} | ${d9(w.beforeStatus,w.beforeDetails)} | ${d9(w.afterStatus,w.afterDetails)} |`);h()}let m=w=>w.startsWith(Em)||w.includes(vm),y=(e.testMaintenance??[]).filter(w=>m(w.afterDetails)&&(!bN.has(w.action)||!A9.has(w.afterStatus??"")));if(a&&y.length){p(ne().staged.declinedMaintenanceHeader);for(let w of y)d.push(`- \`${dt(w.fileName)}\`: ${dt(y9(w.afterDetails))}`);h()}if(a&&r.length){p(ne().staged.existingEvidenceHeader);let w=new Map;for(let x of r){let S=`${x.check}\0${x.url??""}\0${x.revision??""}`;w.set(S,[...w.get(S)??[],x])}for(let[,[x,...S]]of w){let Y=x.url?`[${Kt(x.check)}](${x.url})`:Kt(x.check);d.push(ne().staged.trustedCheckPassed(Y,x.revision?Kt(x.revision.slice(0,7)):""),"");for(let ae of[x,...S])d.push(`- ${Kt(ae.behavior)}`);d.push("")}h()}if(a&&e.testResults.length){p(ne().staged.testResultsHeader);let w=MRe(e),x=w.some(J=>J.test),S=w.some(J=>IN(e,J)),Y=x?ne().staged.unitResultsTableHeader:ne().staged.resultsTableHeader;d.push(S?`${Y} ${ne().columnVideo} |`:Y),d.push(`${x?"|---------|-----------|----------|------|-------|--------|---------|":"|---------|-----------|----------|--------|---------|"}${S?"-------|":""}`);for(let J of w){let be=J.details.replace(/(\S+\.(?:py|ts|js|spec\.\w+))/gi,"`$1`"),Me=J.testId?Kt(dt(u(J.testId))):"\u2014",Ge=x?` ${J.test?`\`${dt(J.test)}\``:""} | ${J.cases??""} |`:"",ke=IN(e,J),X=S?` ${ke?ne().videoDownloadLink(ke):"\u2014"} |`:"";d.push(`| ${Me} | ${dt(cI(J.testType))} | ${dt(J.endpoint)} |${Ge} ${dt(wN(J.status))} | ${dt(be)} |${X}`)}let ae=(e.testVideos??[]).find(J=>J.artifactsUrl)?.artifactsUrl;!S&&ae&&d.push("",ne().videosArtifactFallback(ae)),h()}if(e.requirements?.length){let w=e.requirements.flatMap(J=>J.clauses),x=J=>J.status==="Pass"||J.status==="Passed, test not kept",S=w.filter(x).length;p(ne().staged.requirementsHeader(S,w.length));let Y=J=>ea(ne().staged.clauseStatuses,J.status),ae=J=>(J.status==="Not tested"||J.status==="Passed, test not kept")&&J.notTested?`${Y(J)}: ${J.notTested}`:J.findings.length?`${Y(J)} \u2014 ${J.findings.join(", ")}`:Y(J);if(a){d.push(ne().staged.requirementsTableHeader),d.push("|-------------|--------|-------|--------|");for(let J of e.requirements)J.clauses.forEach((be,Me)=>{let Ge=Me===0?`**${dt(J.label)}**${J.statement?` ${dt(J.statement)}`:""}${uI(J.pullRequests)}`:"",ke=`${Kt(dt(u(be.id)))}${l9(be)}${be.text?` ${dt(be.text)}`:""}`,X=new Map;for(let at of be.tests){let sn=at.fileName??u(at.testId),Et=X.get(sn)??{fns:new Set};for(let In of at.functions)Et.fns.add(In);Et.video??=at.fileName?FRe(e,at.fileName,at.repository):void 0,X.set(sn,Et)}let z=X.size?[...X].map(([at,{fns:sn,video:Et}])=>`${Kt(dt(at))}${sn.size?` \u2014 ${[...sn].map(In=>`\`${dt(In)}\``).join(", ")}`:""}${Et?` ${ne().videoDownloadLink(Et)}`:""}`).join("<br>"):"\u2014",Je=J.source==="could-break"&&be.status==="Pass"?ne().staged.regressionGuard:"";d.push(`| ${Ge} | ${ke} | ${z} | ${dt(ae(be)+Je)} |`)})}else{d.push(ne().staged.requirementsSummaryTableHeader),d.push("|-------------|-----------------|-------------|");for(let J of e.requirements){let be=J.clauses.filter(x).length,Me=J.clauses.filter(Ge=>!x(Ge)).map(Ge=>`${Kt(dt(u(Ge.id)))}${l9(Ge)} ${dt(ae(Ge))}`);d.push(`| **${dt(J.label)}**${J.statement?` ${dt(J.statement)}`:""}${uI(J.pullRequests)} | ${be}/${J.clauses.length} | ${Me.join("<br>")||"\u2014"} |`)}}h()}if(a&&e.changes?.length&&!e.requirements?.length){let w=e.executionCoverage,x=w?ne().staged.coverageCaption(w.generated,w.modified,w.verified,w.executed):"";p(`${ne().staged.behaviourCoverageHeader}${x}`),d.push(ne().staged.coverageTableHeader),d.push("|-----------|--------|-----------|----------------|");for(let S of e.changes){let Y=S.testedBy.length?S.testedBy.map(J=>`\`${dt(J)}\``).join(", "):S.writtenBy.length?ne().staged.writtenNotRun:"\u2014",ae=S.maintainedBy.length?S.maintainedBy.map(J=>`\`${dt(J)}\``).join(", "):"\u2014";d.push(`| ${dt(S.text)} | \`${dt(S.source)}\` | ${Y} | ${ae} |`)}h()}if(e.userJourneys?.length){let w=e.userJourneys.filter(S=>S.status==="Pass"&&!S.problems.length).length;p(`\u{1F9ED} User Journeys Covered (${w}/${e.userJourneys.length} walked end to end)`);let x=e.userJourneys.some(S=>CN(e,S.fileName));d.push(`| Journey | Test | Status | Notes |${x?` ${ne().columnVideo} |`:""}`),d.push(`|---------|------|--------|-------|${x?"-------|":""}`);for(let S of e.userJourneys){let Y=S.fileName?`\`${dt(S.fileName)}\`${S.test?` \u2014 ${dt(S.test)}`:""}`:"\u2014",ae=S.source&&S.source!=="inferred"?`; described in the ${S.source==="spec"?"spec":"PR description"}`:"; inferred from the app",J=(S.uncovered?`not covered: ${S.uncovered}`:S.problems.length?`does not walk it end to end: ${S.problems.join("; ")}`:`from ${S.entry}, ${S.steps} steps`)+ae,be=x?CN(e,S.fileName):void 0;d.push(`| ${dt(S.name)} | ${Y} | ${dt(S.status)} | ${dt(J)} |${x?` ${be?ne().videoDownloadLink(be):"\u2014"} |`:""}`)}h()}let v=e.issuesFound.filter(w=>!p9(w)).sort(f9),E=e.issuesFound.filter(p9).sort(f9);if(v.length){p(ne().staged.issuesFoundHeader);for(let w of v)d.push(h9(w));h()}if(E.length){d.push(`### ${ne().configErrorsHeader}`);for(let w of E)d.push(h9(w));d.push("")}let b=e.testPackages??[],I=e.dependencyChanges??[];if(b.length){d.push(ne().staged.testPackagesHeader,"");for(let w of b)d.push(`- ${ne().staged.testPackageLine(w.directory,w.entrypoint,Object.entries(w.dependencies??{}).map(([x,S])=>w.runner==="pytest"?`${x}==${S}`:`${x}@${S}`).join(", "))}`);I.length||d.push(`- ${ne().staged.appManifestsUntouched}`),d.push("")}if(I.length){d.push(ne().staged.dependencyChangesHeader,"");for(let w of I)d.push(`- ${ne().staged.dependencyChangeLine(w.package,w.repository?`${w.repository}: ${w.manifest}`:w.manifest,(w.reason??"").replace(/\s+/g," ").trim())}`);d.push("")}let C=(e.caveats??[]).filter(w=>w.kind!=="tests-not-executed"||w.subject==="written-cases"||!Im(e));if(C.length){d.push(ne().staged.caveatsHeader,"");for(let w of C)d.push(`- ${w.text}`);d.push("")}if(e.nextSteps.length){d.push(ne().nextStepsHeader,"");for(let w of e.nextSteps)d.push(`- ${w.trim()}`);d.push("")}return d.join(`
|
|
307
307
|
`).replace(/\n{3,}/g,`
|
|
@@ -332,12 +332,12 @@ ${n}`}:{prFailure:"unknown",prDetail:t}}async function pBe(e,t,n,s,r,i){let o=s.
|
|
|
332
332
|
`}catch{return""}}var $9=e=>e.map(t=>t.dependsOn.length?`${t.file} (needs ${t.dependsOn.join(", ")})`:t.file).join("; ");async function ABe(e,t,n,s,r,i){let o=cN(s.path,e.runDir),a=process.env.PATH;o.dir&&(process.env.PATH=F6(o).PATH);try{return await yBe(e,t,n,s,r,i)}finally{o.dir&&(process.env.PATH=a),o.cleanup()}}async function yBe(e,t,n,s,r,i){let o=s.slug,a,c=!1,u,d=[];try{let p=s.path,h=await pBe(e,t,n,s,r,i),{texts:g,shown:m,title:y,bot:v,remote:E,base:b,owner:I,testsBranch:C,origin:w,mergedBase:x}=h,S=(se=[])=>nN(m6(sBe(se,b)+I9(rBe(nBe(m,e,s),se.map(kt=>kt.file)),{audience:"testbot-pr",runUrl:e.inputs.skyrampRunUrl,requestedBy:e.inputs.requestedBy,sourcePullRequest:w&&`${w.repository.namespace}/${w.repository.name}#${w.number}`}),e.inputs.skyrampRunUrl))+`
|
|
333
333
|
`,Y=i?"pr-body.md":`pr-body-${R9(o)}.md`,ae=ei.join(e.outputsDir,Y);wn.writeFileSync(ae,S());let J=ft(p,["rev-parse","HEAD"]),be=x??J;ft(p,["checkout","-B",C]),a=C,ft(p,["reset"]);let Me=Ae(e,"write.json"),Ge=Am(e,Me),ke=Ge.assemblies.filter(se=>se.source.path===s.path&&r.includes(se.record.sourceAsset)),X=EN(e,Ge);if(X.length)throw new Error(X.join("; "));let z=Me?c9(e,Me,g):[];if(z.length)throw new Error(z.join("; "));let Je=new Set(ke.flatMap(({record:se})=>[se.sourceAsset,...se.entry?[se.entry]:[]]));for(let se of r)Je.has(se)||tBe(ei.join(p,se),g);let at=G6(e,ke,g,d);if(at.length)throw new Error(at.join("; "));let sn=new Map([...Je].map(se=>{let kt=wn.readFileSync(ei.join(p,se)),We=Uu=>ft(p,["hash-object","--no-filters","--stdin"],Uu),$t=new Set([We(kt)]),ns=kt.toString("latin1");return!kt.includes(0)&&ns.includes(`\r
|
|
334
334
|
`)&&$t.add(We(Buffer.from(ns.replace(/\r\n/g,`
|
|
335
|
-
`),"latin1"))),[se,$t]})),Et=[];for(let se of r)try{ft(p,["--literal-pathspecs","add","--",se])}catch{Et.push(se)}if(Et.some(se=>Je.has(se)))throw new Error("could not stage every guarded delivery file");let In=new Map([...sn].map(([se,kt])=>{let We=ft(p,["--literal-pathspecs","ls-files","--stage","--",se]),$t=/^100(?:644|755) ([a-f0-9]+) 0\t/.exec(We)?.[1];if(!$t||!kt.has($t))throw new Error(`the staged guarded file differs from the generated file: ${se}`);return[se,$t]}));try{ft(p,["diff","--cached","--quiet"])}catch{try{let se=fBe(p,h,J,be,e.inputs.skyrampRunUrl);ft(p,["-c",`user.name=${v.name}`,"-c",`user.email=${v.email}`,"commit","-m",se])}catch(se){throw new lI(se)}c=!0}c&&(d.length=0),u=ft(p,["rev-parse","HEAD"]);let Ft,ut,Dn,St=x??i?.headSha;if(c&&St&&St!==J){let se=!1,kt=u;try{ft(p,["checkout","-q","-B",a,St]),se=!0;try{ft(p,["-c",`user.name=${v.name}`,"-c",`user.email=${v.email}`,"cherry-pick","--keep-redundant-commits",u])}catch(We){let $t=x?gBe(p,v,kt):void 0;if(!$t||(ut=$t.files.map(ns=>({file:ns,dependsOn:hBe(p,o,x,J,ns)})),Dn={repository:o,base:b,files:ut,patch:mBe(p,J,kt,$t.files)},!$t.delivered))throw We}se=!1,iN(We=>ft(p,We),St),u=ft(p,["rev-parse","HEAD"])}catch(We){try{ft(p,["cherry-pick","--abort"])}catch{}ft(p,["checkout","-q","-B",a,u]);let $t=pm(Oa(We),1/0);if(x&&!se)throw We;if(x)return{thrown:!1,held:Dn,record:{schemaVersion:1,repository:o,branch:a,remote:E,base:b,committed:c,commitSha:u,pushed:!1,prAction:"skipped",prTitle:y,unstaged:Et,...ut?{heldBack:ut}:{},reason:ut?`every test change needs a merged revision ${b} does not have yet, so no tests PR was opened: ${$9(ut)}`:`the tests do not apply to ${b} at ${x.slice(0,12)} without the merged revisions (${$t}), so no tests PR was opened`}};Ft=`tests committed on the checkout's merge commit (re-cut onto ${St.slice(0,12)} failed: ${$t})`}}ut&&wn.writeFileSync(ae,S(ut));for(let[se,kt]of In){if(ut?.some($t=>$t.file===se))continue;let We=ft(p,["--literal-pathspecs","ls-tree",u,"--",se]);if(/^100(?:644|755) blob ([a-f0-9]+)\t/.exec(We)?.[1]!==kt)throw new Error(`the committed guarded file differs from the generated file: ${se}`)}for(let{record:se}of ke){if(se.entry)continue;let kt=ft(p,["--literal-pathspecs","ls-tree",u,"--",se.file]);if(kt&&kt!==ft(p,["--literal-pathspecs","ls-tree",J,"--",se.file]))throw new Error(`the delivery included executable source for a held test: ${se.file}`)}let vt=i?{}:{repositoryPath:p,repoSlug:o,devPr:null};if(!c){let se=await t.markTestsPrUnchanged({branch:a,...vt});return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:E,base:b,committed:!1,commitSha:u,pushed:!1,prAction:se.action==="unchanged"?"unchanged":"skipped",prUrl:se.url,prTitle:y,unstaged:Et,reason:se.action==="unchanged"?"no test changes to commit \u2014 existing tests PR annotated as unchanged":"no test changes to commit \u2014 nothing pushed, no PR opened"}}}let Oe=await t.publishTestsPr({repositoryPath:p,...vt,remote:E,branch:a,base:b,commitSha:u,title:y,bodyFile:ae,mode:e.inputs.deliverMode,deliveryOwner:I,...e.inputs.firstQualification?{firstQualification:!0}:{},runUrl:e.inputs.skyrampRunUrl,signal:e.signal,deadlineMs:e.deadlineMs});return{thrown:!1,held:Dn,record:{schemaVersion:1,repository:o,branch:a,remote:E,base:Oe.base,requestedBase:b,committed:c,commitSha:u,pushed:Oe.pushed,...Oe.pushedCommits?{pushedCommits:Oe.pushedCommits}:{},...Oe.deliveredCommit?{deliveredCommit:Oe.deliveredCommit}:{},prAction:Oe.action,...Oe.retargetedAs?{retargetedAs:Oe.retargetedAs}:{},prUrl:Oe.url,prTitle:y,...Oe.failure?{prFailure:Oe.failure,prDetail:Oe.detail}:{},...Ft?{cutNote:Ft}:{},...Oe.action==="skipped"&&Oe.detail?{reason:Oe.detail}:{},unstaged:Et,...ut?{heldBack:ut}:{}}}}catch(p){return{thrown:!0,record:{schemaVersion:1,repository:o,branch:a,committed:c,commitSha:u,pushed:!1,prAction:"failed",...dBe(p),unstaged:[]}}}finally{if(d.length){try{ft(s.path,["reset"])}catch{}for(let p of d.reverse())try{p()}catch{}}}}var NXe={name:"deliver",timeoutMinutes:5,execute:aBe,validateInput:e=>{let t=eN(e);return t?{ok:!1,reasons:[t]}:YRe(e)},requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var U5e=10*6e4,F5e=4*6e4;var M5e=10*6e4;var vBe=3e4,bBe=3,T9=30,Co=class extends Error{constructor(n,s,r,i){super(n);this.status=s;this.code=r;this.path=i}status;code;path},Qi=class extends Error{},Ap=class extends Qi{},dI=class extends Ap{};function wBe(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 IBe(e,t){if(!sd.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}function CBe(e,t,n,s){throw t<500&&t!==429?new Co(e,t,n,s):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new dI(e):t===503&&n==="RUN_NOT_READY"?new Ap(e):new Qi(e)}async function SBe(e,t,n,s,r,i=1/0){let o=wBe(e.origin),a=`The time limit for ${t} ${n} to the Skyramp web app was reached`,c,u=0;for(let d=1;d<=bBe||c instanceof Ap;d+=1){if(c instanceof Ap){if(u===T9)throw c;u+=1,d-=1,e.log?.(`${c.message}; trying again (${u} of ${T9}).`),await new Promise(p=>setTimeout(p,Math.max(0,Math.min(e.readyWaitMs??1e4,i-Date.now()))))}else d>1&&await new Promise(p=>setTimeout(p,Math.max(0,Math.min((e.retryDelayMs??2e3)*(d-1),i-Date.now()))));if(Date.now()>=i)throw new Qi(a);try{let p,h=await(Number.isFinite(i)?Promise.race([e.idToken(o),new Promise((m,y)=>{p=setTimeout(()=>y(new Qi(a)),Math.max(1,i-Date.now()))})]).finally(()=>{p&&clearTimeout(p)}):e.idToken(o));if(Date.now()>=i)throw new Qi(a);let g=await(e.fetch??fetch)(new URL(n,o).toString(),{...s(h),redirect:"error",signal:AbortSignal.timeout(Math.max(1,Math.min(vBe,i-Date.now())))}).catch(m=>{let y=m instanceof Error?m.message:String(m);throw new Qi(`The Skyramp web app did not answer ${t} ${n}: ${y}`,{cause:m})});return await r(g)}catch(p){if(p instanceof Co||Date.now()>=i)throw p;c=p}}throw c}function kBe(e,t,n,s,r){let i=s.headers.get("cf-ray");e.log?.(`Testbot V3: the Skyramp web app answered ${t} ${n} with ${s.status}${i?`, cf-ray ${i}`:""}: ${r.replace(/\s+/g," ").slice(0,200)}`)}var pI=class extends Error{};function RBe(e){let t=Buffer.byteLength(e,"utf8");if(t<=pB)return{body:e};if(t>jz)throw new pI("The report exceeds the Skyramp web app's 16 MiB expanded report limit");let n=new Uint8Array((0,_9.gzipSync)(e));if(n.length>pB)throw new pI("The compressed report exceeds the Skyramp web app's 1 MiB report upload limit");return{body:n,gzip:!0}}function BBe(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?RBe(i):{body:i};return xBe(e,t,n,o,r)}function xBe(e,t,n,s,r){return SBe(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;kBe(e,t,n,o,a);let u=c.error?.fields,d=typeof u?.path=="string"&&typeof u.reason=="string"?` at ${u.path}: ${u.reason}`:"",p=`The Skyramp web app refused ${t} ${n}: ${o.status} ${c.error?.code??"no error code"}${d}`;return CBe(p,o.status,c.error?.code,typeof u?.path=="string"?u.path:void 0)},r)}var L5e=10*6e4;var j5e=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var V5e=l.object({tests:l.object({placements:l.array(l.unknown()).optional()}).passthrough().optional()}).passthrough(),G5e=l.object({repository:uB,testType:l.string(),directory:l.string()}).passthrough();var z5e=l.object({report:l.object({language:l.string()}).passthrough()}).passthrough();var q5e=l.object({environment:l.object({components:l.array(l.unknown()).optional(),dependencies:l.array(l.unknown()).optional()}).passthrough()}).passthrough(),H5e=l.object({environment:l.object({offLimits:l.unknown().optional()}).passthrough()}).passthrough();var J5e=l.object({environment:l.object({allowedEgress:l.unknown().optional()}).passthrough()}).passthrough();var W5e=l.object({name:l.string().min(1),provision:l.literal("existing"),url:l.string().min(1),repository:uB.optional(),revisionUrl:l.string().min(1).optional()}).passthrough(),Y5e=l.object({name:l.string().min(1),url:l.string().nullable(),versionUrl:l.string().nullable(),notes:l.string().nullable()}).passthrough();var Z5e=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);var K5e={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};async function RN(e,t){return IBe(e.attemptId,"attempt id"),BBe(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,pq({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",sharedEnvironmentRecords:e.sharedEnvironmentRecords}))}var TBe={discover:"reading the repositories",start:"starting the components",check:"checking that the components answer"};var a7e={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 c7e=new RegExp(od.source,"g");function QBe(e){let t=ep(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 _Be=90,DBe={CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",CLAUDE_BYTE_STREAM_IDLE_TIMEOUT_MS:String(_Be*1e3)},D9=30,N9={BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:String(D9*6e4)},P9=["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 ${D9}`,"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 NBe(e,t){return QBe(pt(e,{...DBe,...t},"session"))}function fI(e){return NBe(process.env,e)}On();var O9=".skyramp/sut/health.json",eet={[O9]:`${O9} (with a url or command)`};function BN(e,t){return!Jf(e.status)||e.environment?[]:[...new Set(e.components.flatMap(n=>n.credentials??[]))].filter(n=>!hD(n,t))}function xN(e){let t=e.filter(Mf);if(t.length!==0)return`Rename ${t.join(", ")} in the recipe and on the workflow host, for example to APP_${t[0]}`}function hI(e){if(e.state.stages.onboard?.status==="passed")return Ae(e,"onboard.json")}var mI=G(require("fs")),Sm=G(require("path"));var M9=["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"],set=[...M9,"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 iet=["skyramp_ui_test_generation","skyramp_mock_generation","skyramp_fix_errors","skyramp_start_trace_collection","skyramp_stop_trace_collection","skyramp_export_zip",...M9];var L9=["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 gI=G(require("fs"));var MBe={name:"output-produced",verify(e,t,n){let s=e.outputFileFor(n.name);return(gI.existsSync(s)?gI.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)`}}},LBe=["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 j9(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??LBe,exitGates:e.exitGates??[MBe],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,putsBackTrackedFiles:e.putsBackTrackedFiles,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 jBe=["Bash(docker:*)","Bash(docker compose:*)","Bash(docker-compose:*)","Bash(bash:*)","Bash(sh:*)","Bash(.skyramp/sut/*)","Bash(./.skyramp/sut/*)","Bash(curl:*)","Bash(sleep:*)",...L9,"Read","Write","Edit"];function VBe(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=Gs(e),s=hI(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?BN(s,fI()):[];return r.length>0?{ok:!1,planned:!0,reasons:[[`onboard found the credentials the SUT needs (${r.join(", ")}); Testbot adds the ones on the repository and the next run starts the app with them`,xN(r)].filter(Boolean).join("; ")]}:n&&!n.sutRequired&&!(s&&Jf(s.status))&&!e.inputs.recheck?{ok:!1,reasons:["preflight determined no SUT is required (non-application change)"]}:xa(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 GBe(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 zBe(e){let t=Gs(e);return{recipe:xa(e.inputs.repositoryPath,t?.changedFiles.map(s=>s.path))}}function qBe(e,t){return[t.setupScript,t.teardownScript,t.authTokenScript].filter(n=>!!n).map(n=>Sm.relative(e,n))}function HBe(e,t="revisions"){let n=xw(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 $N(e){return hI(e)?.environment??e.inputs.recheckEnvironment}function JBe(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 WBe(e){let t=hI(e),n=e.inputs.recheck?e.inputs.recheckCredentials??[]:t?zR(t):[];if(n.length===0)return[];let s=e.inputs.sharedEnvironment,r=jf(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.`]:[],...YBe(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 YBe=e=>!!(e.inputs.recheck||e.inputs.setupEvents);function ZBe(e){let{recipe:t}=e.prepared,n=e.inputs.repositoryPath,s=qBe(n,t),r=$N(e),i=e.inputs.sharedEnvironment,o=jf(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)"}`,"",...P9,t.stale?`
|
|
335
|
+
`),"latin1"))),[se,$t]})),Et=[];for(let se of r)try{ft(p,["--literal-pathspecs","add","--",se])}catch{Et.push(se)}if(Et.some(se=>Je.has(se)))throw new Error("could not stage every guarded delivery file");let In=new Map([...sn].map(([se,kt])=>{let We=ft(p,["--literal-pathspecs","ls-files","--stage","--",se]),$t=/^100(?:644|755) ([a-f0-9]+) 0\t/.exec(We)?.[1];if(!$t||!kt.has($t))throw new Error(`the staged guarded file differs from the generated file: ${se}`);return[se,$t]}));try{ft(p,["diff","--cached","--quiet"])}catch{try{let se=fBe(p,h,J,be,e.inputs.skyrampRunUrl);ft(p,["-c",`user.name=${v.name}`,"-c",`user.email=${v.email}`,"commit","-m",se])}catch(se){throw new lI(se)}c=!0}c&&(d.length=0),u=ft(p,["rev-parse","HEAD"]);let Ft,ut,Dn,St=x??i?.headSha;if(c&&St&&St!==J){let se=!1,kt=u;try{ft(p,["checkout","-q","-B",a,St]),se=!0;try{ft(p,["-c",`user.name=${v.name}`,"-c",`user.email=${v.email}`,"cherry-pick","--keep-redundant-commits",u])}catch(We){let $t=x?gBe(p,v,kt):void 0;if(!$t||(ut=$t.files.map(ns=>({file:ns,dependsOn:hBe(p,o,x,J,ns)})),Dn={repository:o,base:b,files:ut,patch:mBe(p,J,kt,$t.files)},!$t.delivered))throw We}se=!1,iN(We=>ft(p,We),St),u=ft(p,["rev-parse","HEAD"])}catch(We){try{ft(p,["cherry-pick","--abort"])}catch{}ft(p,["checkout","-q","-B",a,u]);let $t=pm(Oa(We),1/0);if(x&&!se)throw We;if(x)return{thrown:!1,held:Dn,record:{schemaVersion:1,repository:o,branch:a,remote:E,base:b,committed:c,commitSha:u,pushed:!1,prAction:"skipped",prTitle:y,unstaged:Et,...ut?{heldBack:ut}:{},reason:ut?`every test change needs a merged revision ${b} does not have yet, so no tests PR was opened: ${$9(ut)}`:`the tests do not apply to ${b} at ${x.slice(0,12)} without the merged revisions (${$t}), so no tests PR was opened`}};Ft=`tests committed on the checkout's merge commit (re-cut onto ${St.slice(0,12)} failed: ${$t})`}}ut&&wn.writeFileSync(ae,S(ut));for(let[se,kt]of In){if(ut?.some($t=>$t.file===se))continue;let We=ft(p,["--literal-pathspecs","ls-tree",u,"--",se]);if(/^100(?:644|755) blob ([a-f0-9]+)\t/.exec(We)?.[1]!==kt)throw new Error(`the committed guarded file differs from the generated file: ${se}`)}for(let{record:se}of ke){if(se.entry)continue;let kt=ft(p,["--literal-pathspecs","ls-tree",u,"--",se.file]);if(kt&&kt!==ft(p,["--literal-pathspecs","ls-tree",J,"--",se.file]))throw new Error(`the delivery included executable source for a held test: ${se.file}`)}let vt=i?{}:{repositoryPath:p,repoSlug:o,devPr:null};if(!c){let se=await t.markTestsPrUnchanged({branch:a,...vt});return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:E,base:b,committed:!1,commitSha:u,pushed:!1,prAction:se.action==="unchanged"?"unchanged":"skipped",prUrl:se.url,prTitle:y,unstaged:Et,reason:se.action==="unchanged"?"no test changes to commit \u2014 existing tests PR annotated as unchanged":"no test changes to commit \u2014 nothing pushed, no PR opened"}}}let Oe=await t.publishTestsPr({repositoryPath:p,...vt,remote:E,branch:a,base:b,commitSha:u,title:y,bodyFile:ae,mode:e.inputs.deliverMode,deliveryOwner:I,...e.inputs.firstQualification?{firstQualification:!0}:{},runUrl:e.inputs.skyrampRunUrl,signal:e.signal,deadlineMs:e.deadlineMs});return{thrown:!1,held:Dn,record:{schemaVersion:1,repository:o,branch:a,remote:E,base:Oe.base,requestedBase:b,committed:c,commitSha:u,pushed:Oe.pushed,...Oe.pushedCommits?{pushedCommits:Oe.pushedCommits}:{},...Oe.deliveredCommit?{deliveredCommit:Oe.deliveredCommit}:{},prAction:Oe.action,...Oe.retargetedAs?{retargetedAs:Oe.retargetedAs}:{},prUrl:Oe.url,prTitle:y,...Oe.failure?{prFailure:Oe.failure,prDetail:Oe.detail}:{},...Ft?{cutNote:Ft}:{},...Oe.action==="skipped"&&Oe.detail?{reason:Oe.detail}:{},unstaged:Et,...ut?{heldBack:ut}:{}}}}catch(p){return{thrown:!0,record:{schemaVersion:1,repository:o,branch:a,committed:c,commitSha:u,pushed:!1,prAction:"failed",...dBe(p),unstaged:[]}}}finally{if(d.length){try{ft(s.path,["reset"])}catch{}for(let p of d.reverse())try{p()}catch{}}}}var OXe={name:"deliver",timeoutMinutes:5,execute:aBe,validateInput:e=>{let t=eN(e);return t?{ok:!1,reasons:[t]}:YRe(e)},requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var M5e=10*6e4,L5e=4*6e4;var j5e=10*6e4;var vBe=3e4,bBe=3,T9=30,Co=class extends Error{constructor(n,s,r,i){super(n);this.status=s;this.code=r;this.path=i}status;code;path},Qi=class extends Error{},Ap=class extends Qi{},dI=class extends Ap{};function wBe(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 IBe(e,t){if(!sd.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}function CBe(e,t,n,s){throw t<500&&t!==429?new Co(e,t,n,s):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new dI(e):t===503&&n==="RUN_NOT_READY"?new Ap(e):new Qi(e)}async function SBe(e,t,n,s,r,i=1/0){let o=wBe(e.origin),a=`The time limit for ${t} ${n} to the Skyramp web app was reached`,c,u=0;for(let d=1;d<=bBe||c instanceof Ap;d+=1){if(c instanceof Ap){if(u===T9)throw c;u+=1,d-=1,e.log?.(`${c.message}; trying again (${u} of ${T9}).`),await new Promise(p=>setTimeout(p,Math.max(0,Math.min(e.readyWaitMs??1e4,i-Date.now()))))}else d>1&&await new Promise(p=>setTimeout(p,Math.max(0,Math.min((e.retryDelayMs??2e3)*(d-1),i-Date.now()))));if(Date.now()>=i)throw new Qi(a);try{let p,h=await(Number.isFinite(i)?Promise.race([e.idToken(o),new Promise((m,y)=>{p=setTimeout(()=>y(new Qi(a)),Math.max(1,i-Date.now()))})]).finally(()=>{p&&clearTimeout(p)}):e.idToken(o));if(Date.now()>=i)throw new Qi(a);let g=await(e.fetch??fetch)(new URL(n,o).toString(),{...s(h),redirect:"error",signal:AbortSignal.timeout(Math.max(1,Math.min(vBe,i-Date.now())))}).catch(m=>{let y=m instanceof Error?m.message:String(m);throw new Qi(`The Skyramp web app did not answer ${t} ${n}: ${y}`,{cause:m})});return await r(g)}catch(p){if(p instanceof Co||Date.now()>=i)throw p;c=p}}throw c}function kBe(e,t,n,s,r){let i=s.headers.get("cf-ray");e.log?.(`Testbot V3: the Skyramp web app answered ${t} ${n} with ${s.status}${i?`, cf-ray ${i}`:""}: ${r.replace(/\s+/g," ").slice(0,200)}`)}var pI=class extends Error{};function RBe(e){let t=Buffer.byteLength(e,"utf8");if(t<=pB)return{body:e};if(t>jz)throw new pI("The report exceeds the Skyramp web app's 16 MiB expanded report limit");let n=new Uint8Array((0,_9.gzipSync)(e));if(n.length>pB)throw new pI("The compressed report exceeds the Skyramp web app's 1 MiB report upload limit");return{body:n,gzip:!0}}function BBe(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?RBe(i):{body:i};return xBe(e,t,n,o,r)}function xBe(e,t,n,s,r){return SBe(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;kBe(e,t,n,o,a);let u=c.error?.fields,d=typeof u?.path=="string"&&typeof u.reason=="string"?` at ${u.path}: ${u.reason}`:"",p=`The Skyramp web app refused ${t} ${n}: ${o.status} ${c.error?.code??"no error code"}${d}`;return CBe(p,o.status,c.error?.code,typeof u?.path=="string"?u.path:void 0)},r)}var V5e=10*6e4;var G5e=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var z5e=l.object({tests:l.object({placements:l.array(l.unknown()).optional()}).passthrough().optional()}).passthrough(),q5e=l.object({repository:uB,testType:l.string(),directory:l.string()}).passthrough();var H5e=l.object({report:l.object({language:l.string()}).passthrough()}).passthrough();var J5e=l.object({environment:l.object({components:l.array(l.unknown()).optional(),dependencies:l.array(l.unknown()).optional()}).passthrough()}).passthrough(),W5e=l.object({environment:l.object({offLimits:l.unknown().optional()}).passthrough()}).passthrough();var Y5e=l.object({environment:l.object({allowedEgress:l.unknown().optional()}).passthrough()}).passthrough();var Z5e=l.object({name:l.string().min(1),provision:l.literal("existing"),url:l.string().min(1),repository:uB.optional(),revisionUrl:l.string().min(1).optional()}).passthrough(),K5e=l.object({name:l.string().min(1),url:l.string().nullable(),versionUrl:l.string().nullable(),notes:l.string().nullable()}).passthrough();var X5e=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);var e7e={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};async function RN(e,t){return IBe(e.attemptId,"attempt id"),BBe(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,pq({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",sharedEnvironmentRecords:e.sharedEnvironmentRecords}))}var TBe={discover:"reading the repositories",start:"starting the components",check:"checking that the components answer"};var u7e={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 l7e=new RegExp(od.source,"g");function QBe(e){let t=ep(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 _Be=90,DBe={CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",CLAUDE_BYTE_STREAM_IDLE_TIMEOUT_MS:String(_Be*1e3)},D9=30,N9={BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:String(D9*6e4)},P9=["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 ${D9}`,"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 NBe(e,t){return QBe(pt(e,{...DBe,...t},"session"))}function fI(e){return NBe(process.env,e)}On();var O9=".skyramp/sut/health.json",net={[O9]:`${O9} (with a url or command)`};function BN(e,t){return!Jf(e.status)||e.environment?[]:[...new Set(e.components.flatMap(n=>n.credentials??[]))].filter(n=>!hD(n,t))}function xN(e){let t=e.filter(Mf);if(t.length!==0)return`Rename ${t.join(", ")} in the recipe and on the workflow host, for example to APP_${t[0]}`}function hI(e){if(e.state.stages.onboard?.status==="passed")return Ae(e,"onboard.json")}var mI=G(require("fs")),Sm=G(require("path"));var M9=["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"],oet=[...M9,"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 aet=["skyramp_ui_test_generation","skyramp_mock_generation","skyramp_fix_errors","skyramp_start_trace_collection","skyramp_stop_trace_collection","skyramp_export_zip",...M9];var L9=["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 gI=G(require("fs"));var MBe={name:"output-produced",verify(e,t,n){let s=e.outputFileFor(n.name);return(gI.existsSync(s)?gI.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)`}}},LBe=["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 j9(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??LBe,exitGates:e.exitGates??[MBe],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,putsBackTrackedFiles:e.putsBackTrackedFiles,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 jBe=["Bash(docker:*)","Bash(docker compose:*)","Bash(docker-compose:*)","Bash(bash:*)","Bash(sh:*)","Bash(.skyramp/sut/*)","Bash(./.skyramp/sut/*)","Bash(curl:*)","Bash(sleep:*)",...L9,"Read","Write","Edit"];function VBe(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=Gs(e),s=hI(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?BN(s,fI()):[];return r.length>0?{ok:!1,planned:!0,reasons:[[`onboard found the credentials the SUT needs (${r.join(", ")}); Testbot adds the ones on the repository and the next run starts the app with them`,xN(r)].filter(Boolean).join("; ")]}:n&&!n.sutRequired&&!(s&&Jf(s.status))&&!e.inputs.recheck?{ok:!1,reasons:["preflight determined no SUT is required (non-application change)"]}:xa(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 GBe(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 zBe(e){let t=Gs(e);return{recipe:xa(e.inputs.repositoryPath,t?.changedFiles.map(s=>s.path))}}function qBe(e,t){return[t.setupScript,t.teardownScript,t.authTokenScript].filter(n=>!!n).map(n=>Sm.relative(e,n))}function HBe(e,t="revisions"){let n=xw(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 $N(e){return hI(e)?.environment??e.inputs.recheckEnvironment}function JBe(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 WBe(e){let t=hI(e),n=e.inputs.recheck?e.inputs.recheckCredentials??[]:t?zR(t):[];if(n.length===0)return[];let s=e.inputs.sharedEnvironment,r=jf(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.`]:[],...YBe(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 YBe=e=>!!(e.inputs.recheck||e.inputs.setupEvents);function ZBe(e){let{recipe:t}=e.prepared,n=e.inputs.repositoryPath,s=qBe(n,t),r=$N(e),i=e.inputs.sharedEnvironment,o=jf(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)"}`,"",...P9,t.stale?`
|
|
336
336
|
STALENESS WARNING: this PR changed recipe/infra files (${t.staleFiles.join(", ")}).
|
|
337
337
|
The recorded recipe may no longer match. If bring-up fails, first decide
|
|
338
338
|
WHY: recipe drift (infra moved, recipe is behind) vs the change itself
|
|
339
339
|
breaking bring-up. Do NOT paper over a PR that broke the app.`:"","",...r?JBe(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".'],...HBe(e),...WBe(e),"","Output: end with one JSON object matching:","",Iq(Kf)," // 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(`
|
|
340
|
-
`)}function G9(e){let t=Sm.join(e.outputsDir,"deploy.txt");if(mI.existsSync(t)){let{deploy:s}=Bu({exitCode:0,stdout:mI.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}=xa(e.inputs.repositoryPath);if(n)return{argv:["bash",n],label:Sm.join(".skyramp","sut","teardown.sh")}}function z9(e,t){return Aw(t,e.inputs.repositoryPath,{env:pt(),secretValues:e.secretValues})}async function V9(e){let t=G9(e);if(t){let n=await z9(e,t);if(n&&AZ(e))throw new Error(`SUT teardown failed: ${n}`)}}async function KBe(e,t){let n=t.passed?void 0:q9(e);if(!n)return;let s=await z9(e,n);return s&&`${s} (if nothing was running, a teardown must exit 0)`}function q9(e){return $N(e)?void 0:G9(e)}function XBe(e){if(q9(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 exe(e,t){let{deploy:n}=Bu(t,e.inputs.repositoryPath,e.secretValues);if(!n)return;if(n.outcome==="bringup-failed"){let r=Vt(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=Yg(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 H9=j9({name:"deploy",model:"opus",timeoutMinutes:25,requires:["preflight"],softRequires:["onboard"],startsApp:e=>!e.inputs.appRunning&&!(e.inputs.testEnvironment&&$N(e)),triageBranch:"runtime",validateInput:VBe,prepare:zBe,scaleTimeout:GBe,buildPrompt:ZBe,allowedTools:jBe,buildSessionEnv:()=>({...N9}),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:[Qw(),AK()],onPassed:async(e,t)=>({...EK(e,t),...await yK(e,t)}),passReason:exe,afterAttempt:KBe,retryNote:XBe,onAbort:V9,teardown:V9});On();var
|
|
340
|
+
`)}function G9(e){let t=Sm.join(e.outputsDir,"deploy.txt");if(mI.existsSync(t)){let{deploy:s}=Bu({exitCode:0,stdout:mI.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}=xa(e.inputs.repositoryPath);if(n)return{argv:["bash",n],label:Sm.join(".skyramp","sut","teardown.sh")}}function z9(e,t){return Aw(t,e.inputs.repositoryPath,{env:pt(),secretValues:e.secretValues})}async function V9(e){let t=G9(e);if(t){let n=await z9(e,t);if(n&&AZ(e))throw new Error(`SUT teardown failed: ${n}`)}}async function KBe(e,t){let n=t.passed?void 0:q9(e);if(!n)return;let s=await z9(e,n);return s&&`${s} (if nothing was running, a teardown must exit 0)`}function q9(e){return $N(e)?void 0:G9(e)}function XBe(e){if(q9(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 exe(e,t){let{deploy:n}=Bu(t,e.inputs.repositoryPath,e.secretValues);if(!n)return;if(n.outcome==="bringup-failed"){let r=Vt(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=Yg(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 H9=j9({name:"deploy",model:"opus",timeoutMinutes:25,requires:["preflight"],softRequires:["onboard"],startsApp:e=>!e.inputs.appRunning&&!(e.inputs.testEnvironment&&$N(e)),triageBranch:"runtime",validateInput:VBe,prepare:zBe,scaleTimeout:GBe,buildPrompt:ZBe,allowedTools:jBe,buildSessionEnv:()=>({...N9}),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:[Qw(),AK()],onPassed:async(e,t)=>({...EK(e,t),...await yK(e,t)}),passReason:exe,afterAttempt:KBe,retryNote:XBe,onAbort:V9,teardown:V9});On();var Get=20*1024*1024;var So=G(require("fs"));var W9=G(require("path"));var ttt=W9.join(".skyramp","sut","get-auth-token.sh");var TN="\\$([A-Z][A-Z0-9_]{0,99})",ntt=new RegExp(`^${TN}$`),rtt=new RegExp(`^${TN}:${TN}$`);var ktt=new Set([...yD,"coverage",".nyc_output","htmlcov","TestResults"]);var Int=3*6e4;var Cnt=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;var rxe=["GH_TOKEN","GITHUB_TOKEN","ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_BEARER_TOKEN_BEDROCK","AWS_CONTAINER_AUTHORIZATION_TOKEN"],sxe=["AWS_WEB_IDENTITY_TOKEN_FILE","AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"];function ixe(e){if(e)try{return So.statSync(e).size>64*1024?void 0:So.readFileSync(e,"utf8").trim()||void 0}catch{return}}function Y9(e=process.env){return Rh([...rxe.map(t=>e[t]),...sxe.map(t=>ixe(e[t]))])}var AI=G(require("fs")),QN=G(require("path"));function oxe(e){let t;try{t=AI.readdirSync(e)}catch{return[]}let n=t.filter(s=>/^session-[0-9a-f-]{36}$/.test(s)).map(s=>QN.join(e,s)).filter(s=>AI.lstatSync(s,{throwIfNoEntry:!1})?.isDirectory());return[e,...n.sort()]}function axe(e,t){let n;try{n=new URL(e)}catch{return}if(n.protocol!=="http:"&&n.protocol!=="https:")return;let s=xh(Si(`${n.protocol}//${n.host}${n.pathname}`,t),t);return Jz.safeParse({records:[s],unlisted:0}).success?s:void 0}function Z9(e,t){let n=QN.join(e,Fg),s=oxe(n).flatMap(c=>[W_(c,!0,new Set),W_(c,!1,new Set)]),{leftovers:r,unparsedCreates:i}=mZ(s.flatMap(c=>c.ledgers)),o=[],a=i.length+s.flatMap(c=>c.failures).length;for(let c of new Set(r)){let u=axe(c,t);u===void 0||o.includes(u)||o.length>=fB?a+=1:o.push(u)}return o.length+a>0?{records:o,unlisted:a}:void 0}var Wnt=new RegExp(od.source,"g");var uxe="https://testbot.skyramp.dev",_i={attemptId:"v3AttemptId",deadlineAt:"v3DeadlineAt",reportUploaded:"v3ReportUploaded",recipeUploaded:"v3RecipeUploaded",recipeStatus:"v3RecipeStatus",revisionsUploaded:"v3RevisionsUploaded",cause:"v3Cause",conflict:"v3Conflict",githubWrites:"v3GithubWrites",credentialNames:"v3CredentialNames"};function K9(e,t,n){return{origin:e,idToken:t,sourceToken:n,mask:s=>Ji(s),log:s=>ls(s),onTokenRefused:(s,r)=>{dxe(s)&&X9.set(r,s)},onTokenGranted:s=>{X9.delete(s)}}}var X9=new Map;var Bit=["setup_failed","checkout_failed","environment_unverified"];function lxe(e,t){return t.getTime()>=e.getTime()}function dxe(e){return e instanceof Qi||e instanceof Co&&e.code!=="CREDENTIALS_UNAVAILABLE"}var xit={cancelled:"Skyramp cancelled this run",expired:"this attempt passed its deadline in Skyramp",ended:"Skyramp already ended this attempt"},$it={cancelled:"attempt-cancelled",expired:"attempt-closed",ended:"attempt-closed"},Tit={cancelled:"cancelled",expired:"timed_out",ended:"agent_failed"};var Qit={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"},_it={analyze:"change analysis",recommend:"test recommendations",generate:"test generation",execute:"test execution",deliver:"opening a pull request with the tests"};function e3(){return je("skyrampAppOrigin").trim()||uxe}var Dit=["sut_access","other"];var Nit=10*6e4;var Pit={onboard:"onboard",deploy:"deploy"},Oit={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"}},Uit=new Set(["write","native-run"]);function pxe(){let e=Us(_i.conflict);if(!e)return;let t;try{t=dq.safeParse(JSON.parse(e))}catch(n){Nt(`Testbot V3: the saved merge conflict is not JSON (${n instanceof Error?n.message:String(n)})`);return}if(t.success)return t.data;Nt(`Testbot V3: the saved merge conflict breaks the contract (${t.error.issues.map(n=>`${n.path.join(".")}: ${n.message}`).join("; ")})`)}function fxe(){let e=Us(_i.githubWrites);if(!e)return[];let t;try{t=JSON.parse(e)}catch(n){return Nt(`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=LE.safeParse(n);return s.success?[s.data]:[]}).slice(0,ME):[]}function hxe(){let e=Us(_i.credentialNames).split(",").filter(Boolean),t=Rh([...e.map(n=>process.env[n]),...Object.values(Lf()),...Y9()]);try{let n=Z9(t3.join(hq(),"outputs"),t);return n&&ls(`Testbot V3: this run uploaded nothing and created ${n.records.length+n.unlisted} record(s) in the shared environment that it did not see removed; sending them to Skyramp.`),n}catch(n){let s=n instanceof Error?n.message:String(n);Nt(`Testbot V3: could not read what this run created in the shared environment (${s})`);return}}async function n3(){let e=Us(_i.attemptId);if(!e)return;let t=Us(_i.reportUploaded)==="true",n=Us(_i.recipeUploaded)==="true",s=Us(_i.revisionsUploaded)==="true",r=Us(_i.deadlineAt),i=Us(_i.cause)||void 0;!i&&!t&&!n&&!s&&r&&lxe(new Date(r),new Date)&&(i="timed_out");let o=ep().takeIdToken(),a=pxe(),c={attemptId:e,reportUploaded:t,recipeUploaded:n,revisionsUploaded:s,cause:i,...a?{conflict:a}:{},githubWrites:fxe()},u=!t&&!n&&!s?hxe():void 0,d;try{d=await RN({...c,...u?{sharedEnvironmentRecords:u}:{}},K9(e3(),o))}catch(h){if(!u||!(h instanceof Co)||h.status!==400)throw h;Nt(`Testbot V3: Skyramp refused the end; ending again without the shared-environment records (${h.message}); the attempt ends without them.`),d=await RN(c,K9(e3(),o))}let p=Us(_i.recipeStatus);n&&p?ls(`Testbot V3: attempt ended; the setup ended ${p==="ready"?"Ready":"blocked (Needs input)"}.`):ls(`Testbot V3: attempt ended; the run's outcome in Skyramp is ${d.outcome??"not final yet"}.`)}var r3=require("child_process"),Di=G(require("fs")),DN=G(require("path")),NN=require("string_decoder");var gxe="skyramp-testbot-state",mxe=/^\$\([^)]*\)$/;function Axe(e){for(let[t,n]of Object.entries(e))n!==void 0&&mxe.test(n)&&delete e[t]}function yxe(e){let t={},n=Di.existsSync(e)?Di.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 s3(e,t={}){let n=t.env??process.env;if(!$a(n))return!1;Axe(n),_Z(n);let s=n.AGENT_TEMPDIRECTORY||n.RUNNER_TEMP;if(s){n.RUNNER_TEMP??=s;let o=DN.join(s,gxe);if(e==="main")Di.writeFileSync(o,"",{mode:384});else for(let[a,c]of Object.entries(yxe(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]=DN.join(s,`skyramp-testbot-${c}`),Di.writeFileSync(n[a],"",{mode:384})}let r=t.stdout??n===process.env;r&&Exe(n,t.write);let i=n.GITHUB_STEP_SUMMARY;if(r&&i){let o=t.write??(a=>tD(a.replace(/\n$/,"")));process.once("exit",()=>{Di.existsSync(i)&&Di.statSync(i).size>0&&o(`${Ew("task.uploadsummary",{},i)}
|
|
341
341
|
`)})}return!0}function Exe(e,t){let n=process.stdout.write.bind(process.stdout),s=o=>e[Lg]==="1"?eD(o,e):void n(o.command!==void 0?`${o.command}
|
|
342
342
|
`: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("::")?kZ(p):void 0;if(!h){u+=p;continue}u&&i(u),u="";for(let g of h)r(`${g}
|
|
343
343
|
`)}return u&&i(u),a.find(p=>typeof p=="function")?.(),!0})}var vxe=64*1024;function _N(e){let t=new NN.StringDecoder("utf8"),n="",s=r=>e(yw(r));return{push(r){n+=typeof r=="string"?r:t.write(r);let i=n.lastIndexOf(`
|