@skyramp/testbot-core 0.13.0-v3.372 → 0.13.0-v3.374
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 +491 -491
- package/dist/post.js +72 -72
- package/dist/runner-client.cjs +10 -10
- package/package.json +1 -1
package/dist/runner-client.cjs
CHANGED
|
@@ -150,13 +150,13 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
150
150
|
`+m.slice(_+1):ie+=m.slice(L),ie.slice(1)}o(XA,"foldLine");function Yi(m){let k="",Q=0;for(let O=0;O<m.length;Q>=65536?O+=2:O++){Q=Or(m,O);let L=ye[Q];!L&&Cn(Q)?(k+=m[O],Q>=65536&&(k+=m[O+1])):k+=L||ze(Q)}return k}o(Yi,"escapeString");function By(m,k,Q){let O="",L=m.tag;for(let V=0,_=Q.length;V<_;V+=1){let J=Q[V];m.replacer&&(J=m.replacer.call(Q,String(V),J)),(B(m,k,J,!1,!1)||typeof J>"u"&&B(m,k,null,!1,!1))&&(O!==""&&(O+=","+(m.condenseFlow?"":" ")),O+=m.dump)}m.tag=L,m.dump="["+O+"]"}o(By,"writeFlowSequence");function $u(m,k,Q,O){let L="",V=m.tag;for(let _=0,J=Q.length;_<J;_+=1){let ie=Q[_];m.replacer&&(ie=m.replacer.call(Q,String(_),ie)),(B(m,k+1,ie,!0,!0,!1,!0)||typeof ie>"u"&&B(m,k+1,null,!0,!0,!1,!0))&&((!O||L!=="")&&(L+=tt(m,k)),m.dump&&c===m.dump.charCodeAt(0)?L+="-":L+="- ",L+=m.dump)}m.tag=V,m.dump=L||"[]"}o($u,"writeBlockSequence");function ky(m,k,Q){let O="",L=m.tag,V=Object.keys(Q);for(let _=0,J=V.length;_<J;_+=1){let ie="";O!==""&&(ie+=", "),m.condenseFlow&&(ie+='"');let he=V[_],Ee=Q[he];m.replacer&&(Ee=m.replacer.call(Q,he,Ee)),B(m,k,he,!1,!1)&&(m.dump.length>1024&&(ie+="? "),ie+=m.dump+(m.condenseFlow?'"':"")+":"+(m.condenseFlow?"":" "),B(m,k,Ee,!1,!1)&&(ie+=m.dump,O+=ie))}m.tag=L,m.dump="{"+O+"}"}o(ky,"writeFlowMapping");function Sy(m,k,Q,O){let L="",V=m.tag,_=Object.keys(Q);if(m.sortKeys===!0)_.sort();else if(typeof m.sortKeys=="function")_.sort(m.sortKeys);else if(m.sortKeys)throw new t("sortKeys must be a boolean or a function");for(let J=0,ie=_.length;J<ie;J+=1){let he="";(!O||L!=="")&&(he+=tt(m,k));let Ee=_[J],ke=Q[Ee];if(m.replacer&&(ke=m.replacer.call(Q,Ee,ke)),!B(m,k+1,Ee,!0,!0,!0))continue;let _e=m.tag!==null&&m.tag!=="?"||m.dump&&m.dump.length>1024;_e&&(m.dump&&c===m.dump.charCodeAt(0)?he+="?":he+="? "),he+=m.dump,_e&&(he+=tt(m,k)),B(m,k+1,ke,!0,_e)&&(m.dump&&c===m.dump.charCodeAt(0)?he+=":":he+=": ",he+=m.dump,L+=he)}m.tag=V,m.dump=L||"{}"}o(Sy,"writeBlockMapping");function f(m,k,Q){let O=Q?m.explicitTypes:m.implicitTypes;for(let L=0,V=O.length;L<V;L+=1){let _=O[L];if((_.instanceOf||_.predicate)&&(!_.instanceOf||typeof k=="object"&&k instanceof _.instanceOf)&&(!_.predicate||_.predicate(k))){if(Q?_.multi&&_.representName?m.tag=_.representName(k):m.tag=_.tag:m.tag="?",_.represent){let J=m.styleMap[_.tag]||_.defaultStyle,ie;if(i.call(_.represent)==="[object Function]")ie=_.represent(k,J);else if(r.call(_.represent,J))ie=_.represent[J](k,J);else throw new t("!<"+_.tag+'> tag resolver accepts not "'+J+'" style');m.dump=ie}return!0}}return!1}o(f,"detectType");function B(m,k,Q,O,L,V,_){m.tag=null,m.dump=Q,f(m,Q,!1)||f(m,Q,!0);let J=i.call(m.dump),ie=O;O&&(O=m.flowLevel<0||m.flowLevel>k);let he=J==="[object Object]"||J==="[object Array]",Ee,ke;if(he&&(Ee=m.duplicates.indexOf(Q),ke=Ee!==-1),(m.tag!==null&&m.tag!=="?"||ke||m.indent!==2&&k>0)&&(L=!1),ke&&m.usedDuplicates[Ee])m.dump="*ref_"+Ee;else{if(he&&ke&&!m.usedDuplicates[Ee]&&(m.usedDuplicates[Ee]=!0),J==="[object Object]")O&&Object.keys(m.dump).length!==0?(Sy(m,k,m.dump,L),ke&&(m.dump="&ref_"+Ee+m.dump)):(ky(m,k,m.dump),ke&&(m.dump="&ref_"+Ee+" "+m.dump));else if(J==="[object Array]")O&&m.dump.length!==0?(m.noArrayIndent&&!_&&k>0?$u(m,k-1,m.dump,L):$u(m,k,m.dump,L),ke&&(m.dump="&ref_"+Ee+m.dump)):(By(m,k,m.dump),ke&&(m.dump="&ref_"+Ee+" "+m.dump));else if(J==="[object String]")m.tag!=="?"&&WA(m,m.dump,k,V,ie);else{if(J==="[object Undefined]")return!1;if(m.skipInvalid)return!1;throw new t("unacceptable kind of an object to dump "+J)}if(m.tag!==null&&m.tag!=="?"){let _e=encodeURI(m.tag[0]==="!"?m.tag.slice(1):m.tag).replace(/!/g,"%21");m.tag[0]==="!"?_e="!"+_e:_e.slice(0,18)==="tag:yaml.org,2002:"?_e="!!"+_e.slice(18):_e="!<"+_e+">",m.dump=_e+" "+m.dump}}return!0}o(B,"writeNode");function U(m,k){let Q=[],O=[];F(m,Q,O);let L=O.length;for(let V=0;V<L;V+=1)k.duplicates.push(Q[O[V]]);k.usedDuplicates=new Array(L)}o(U,"getDuplicateReferences");function F(m,k,Q){if(m!==null&&typeof m=="object"){let O=k.indexOf(m);if(O!==-1)Q.indexOf(O)===-1&&Q.push(O);else if(k.push(m),Array.isArray(m))for(let L=0,V=m.length;L<V;L+=1)F(m[L],k,Q);else{let L=Object.keys(m);for(let V=0,_=L.length;V<_;V+=1)F(m[L[V]],k,Q)}}}o(F,"inspectNode");function R(m,k){k=k||{};let Q=new Yt(k);Q.noRefs||U(m,Q);let O=m;return Q.replacer&&(O=Q.replacer.call({"":O},"",O)),B(Q,0,O,!0,!0)?Q.dump+`
|
|
151
151
|
`:""}return o(R,"dump2"),tx.dump=R,tx}o(ece,"requireDumper");var xG;function tce(){if(xG)return rn;xG=1;let e=Xae(),t=ece();function n(i,r){return function(){throw new Error("Function yaml."+i+" is removed in js-yaml 4. Use yaml."+r+" instead, which is now safe by default.")}}return o(n,"renamed"),rn.Type=yn(),rn.Schema=$G(),rn.FAILSAFE_SCHEMA=NG(),rn.JSON_SCHEMA=OG(),rn.CORE_SCHEMA=LG(),rn.DEFAULT_SCHEMA=nx(),rn.load=e.load,rn.loadAll=e.loadAll,rn.dump=t.dump,rn.YAMLException=IA(),rn.types={binary:VG(),float:MG(),map:_G(),null:UG(),pairs:qG(),set:JG(),timestamp:jG(),bool:FG(),int:PG(),merge:GG(),omap:zG(),seq:DG(),str:TG()},rn.safeLoad=n("safeLoad","load"),rn.safeLoadAll=n("safeLoadAll","loadAll"),rn.safeDump=n("safeDump","dump"),rn}o(tce,"requireJsYaml");var nce=tce(),rce=Zae(nce),{Type:iRe,Schema:sRe,FAILSAFE_SCHEMA:oRe,JSON_SCHEMA:aRe,CORE_SCHEMA:cRe,DEFAULT_SCHEMA:uRe,load:Vi,loadAll:ice,dump:lRe,YAMLException:dRe,types:ARe,safeLoad:pRe,safeLoadAll:fRe,safeDump:gRe}=rce;var Sx=Se(vx());var Zm=Se(require("fs")),ca=Se(require("path"));var Eu=Se(require("path"));var Kxe=Eu.join(".skyramp","workspace.yml");var Ade={py:"python",go:"go",java:"java",kt:"kotlin",rb:"ruby",cs:"csharp",ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",kts:"kotlin",rs:"rust",php:"php",scala:"scala",swift:"swift",ex:"elixir",exs:"elixir",dart:"dart",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp",hpp:"cpp",hh:"cpp",groovy:"groovy"};var Xxe=new Set(Object.values(Ade));var a$e=5*6e4;function Bx(e){try{let i=JSON.parse(Zm.readFileSync(ca.join(e,"package.json"),"utf-8")).packageManager,r=typeof i=="string"?i.match(/^(pnpm|yarn|bun|npm)\b/):null;if(r)return r[1]}catch{}let t=[["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["bun.lockb","bun"],["bun.lock","bun"],["package-lock.json","npm"]],n=ca.resolve(e);for(let i=0;i<6;i++){for(let[s,a]of t)if(Zm.existsSync(ca.join(n,s)))return a;let r=ca.dirname(n);if(r===n)break;n=r}return"npm"}o(Bx,"packageManagerOf");var Mz=["package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb"],gde={"package.json":Mz,"pyproject.toml":["poetry.lock","uv.lock","pdm.lock"],Pipfile:["Pipfile.lock"]};function Km(e,t){let n=ut.basename(t),i=gde[n];if(!i)return[];let r=ut.resolve(e),s=ut.dirname(ut.resolve(r,t)),a=ut.relative(r,s);if(a===".."||a.startsWith(`..${ut.sep}`)||ut.isAbsolute(a))return[];let c=o((l,A)=>A.map(p=>ut.join(ut.relative(r,l),p)).filter(p=>DR(r,p)),"trackedIn"),u=c(s,i);if(u.length)return u;for(let l=s;l!==r;){l=ut.dirname(l);let A=hde(l,ut.relative(l,s).split(ut.sep).join("/"),n);if(A)return c(l,A)}return[]}o(Km,"trackedLockfiles");function Qx(e,t){return t.filter(n=>TR(e,n)&&QA(ut.join(e,n)))}o(Qx,"updatedLockfiles");function hde(e,t,n){if(n==="package.json"){let i=Cde(ut.join(e,"pnpm-workspace.yaml"));if(kx(i?.packages,t))return["pnpm-lock.yaml"];let s=yde(ut.join(e,"package.json"))?.workspaces,a=Array.isArray(s)?s:s?.packages;return kx(a,t)?Mz.filter(c=>c!=="pnpm-lock.yaml"):void 0}if(n==="pyproject.toml"){let i=mde(ut.join(e,"pyproject.toml"));if(i&&kx([...i.members,...i.exclude.map(r=>`!${r}`)],t))return["uv.lock"]}}o(hde,"workspaceLockfiles");function kx(e,t){if(!Array.isArray(e))return!1;let n=o(a=>a.trim().replace(/^\.\//,"").replace(/\/+$/,""),"norm"),i=e.filter(a=>typeof a=="string"),r=i.filter(a=>!a.startsWith("!")).map(n),s=i.filter(a=>a.startsWith("!")).map(a=>n(a.slice(1)));return r.some(a=>ut.matchesGlob(t,a))&&!s.some(a=>ut.matchesGlob(t,a))}o(kx,"lists");function mde(e){let t;try{t=SA.readFileSync(e,"utf-8")}catch{return}let n=t.split(`
|
|
152
152
|
`),i=n.findIndex(c=>c.trim()==="[tool.uv.workspace]");if(i<0)return;let r=n.findIndex((c,u)=>u>i&&c.trim().startsWith("[")),s=n.slice(i+1,r<0?void 0:r).join(`
|
|
153
|
-
`),a=o(c=>{let u=s.match(new RegExp(`^\\s*${c}\\s*=\\s*\\[([^\\]]*)\\]`,"m"));return u?[...u[1].matchAll(/["']([^"']+)["']/g)].map(l=>l[1]):[]},"array");return{members:a("members"),exclude:a("exclude")}}o(mde,"uvWorkspace");function yde(e){return Ede(Oz(e))}o(yde,"readJson");function Ede(e){try{return JSON.parse(e)}catch{return}}o(Ede,"parseJson");function Ide(e){try{return Vi(e)}catch{return}}o(Ide,"parseYaml");function Cde(e){return Ide(Oz(e))}o(Cde,"readYaml");function Oz(e){try{return SA.readFileSync(e,"utf-8")}catch{return""}}o(Oz,"readText");function QA(e){try{return SA.lstatSync(e).isFile()}catch{return!1}}o(QA,"isFile");var wde="SKYRAMP_TEST_SERVICE_URL_";var Bde=`${wde}UI`;var Xm="test-package.json";var kde=["node_modules",".venv","test-results","playwright-report","blob-report","__pycache__",".pytest_cache"];var Lz=o(e=>e.split(zi.sep).join("/"),"posix");function ey(e,t){let n=Lz(e);return t.some(i=>n===i||n.startsWith(`${i}/`))}o(ey,"insidePackage");function Rx(e){return Lz(e).split("/").some(t=>kde.includes(t))}o(Rx,"producedByPackage");var Sde=o(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"escapeRegex"),Vz=/%[psdifjo#]|\$[A-Za-z_][\w.]*/g;var Qde=/ (?:>|›) /;function Rde(e){return e.split(Vz).map(t=>t.split(Qde).map(Sde).join("(?: > | \u203A | )")).join(".+?")}o(Rde,"testNamePattern");function zz(e,t){return new RegExp(Vz.source).test(t)?new RegExp(`^(?:.* )?${Rde(t)}$`).test(e):!1}o(zz,"isEachCaseOf");var ty=Se(require("fs")),Jz=Se(require("path"));var $de=/[;|`$<>(){}\n\r]|(?<!&)&(?!&)|\|\|/,Tde=/`|\$[\w{(@*#?!$-]|\\[$`"\\\n]/;function Dde(e){let t="";for(let i=0;i<e.length;){let r=e[i];if(r==="\\"&&(e[i+1]==='"'||e[i+1]==="'"))return{syntax:"a backslash before a quote",quoted:!1};if(r!=='"'&&r!=="'"){t+=r,i++;continue}let s=e.indexOf(r,i+1);if(s<0)return;let a=r==='"'?Tde.exec(e.slice(i+1,s+(e[s-1]==="\\"?1:0))):null;if(a)return{syntax:`${qz(a[0])} inside double quotes`,quoted:!0};t+=" ",i=s+1}let n=$de.exec(t);return n?{syntax:qz(n[0]),quoted:!1}:void 0}o(Dde,"shellSyntax");var qz=o(e=>e==="`"?"a backtick":/[\n\r]/.test(e)?"a line break":`\`${e}\``,"shown");function ny(e){let t=(e??"").trim();if(!t)return{kind:"empty",reason:"the command is empty"};let n=Dde(t);if(n)return{kind:"shell-syntax",reason:`it uses shell syntax (${n.syntax}), and this is re-executed WITHOUT a shell so the recorded string cannot be interpreted \u2014 put the logic in a script and record the script invocation instead, or put an argument that holds such characters in ${n.quoted?"single quotes":"quotes"}`};let i=[],r=[],s="",a,c=!1,u=o(()=>{(s||c)&&r.push(s),s="",c=!1},"endToken"),l=o(()=>{u(),r.length>0&&i.push(r),r=[]},"endStep");for(let p=0;p<t.length;p++){let g=t[p];if(a){g===a?a=void 0:s+=g;continue}if(g==='"'||g==="'"){a=g,c=!0;continue}if(g==="&"&&t[p+1]==="&"){l(),p+=1;continue}if(/\s/.test(g)){u();continue}s+=g}if(a)return{kind:"unterminated-quote",reason:"it has an unterminated quote"};if(l(),i.length===0)return{kind:"empty",reason:"the command is empty"};if(i.some(p=>p.length===0))return{kind:"empty-step",reason:"it has an empty step between && operators"};let A=i.find(p=>["cd","export","source","."].includes(p[0]));return A?{kind:"builtin",reason:`it runs the shell builtin "${A[0]}", which cannot be executed as a program \u2014 record a script that does this instead`}:{argv:i[0],steps:i}}o(ny,"parseCommand");function xx(e,t,n){let i=(e??"").trim(),{steps:r,kind:s}=ny(i);if(!r&&!(s!=="shell-syntax"&&s!=="builtin")){try{ty.mkdirSync(Jz.dirname(t),{recursive:!0}),ty.writeFileSync(t,`#!/usr/bin/env bash
|
|
153
|
+
`),a=o(c=>{let u=s.match(new RegExp(`^\\s*${c}\\s*=\\s*\\[([^\\]]*)\\]`,"m"));return u?[...u[1].matchAll(/["']([^"']+)["']/g)].map(l=>l[1]):[]},"array");return{members:a("members"),exclude:a("exclude")}}o(mde,"uvWorkspace");function yde(e){return Ede(Oz(e))}o(yde,"readJson");function Ede(e){try{return JSON.parse(e)}catch{return}}o(Ede,"parseJson");function Ide(e){try{return Vi(e)}catch{return}}o(Ide,"parseYaml");function Cde(e){return Ide(Oz(e))}o(Cde,"readYaml");function Oz(e){try{return SA.readFileSync(e,"utf-8")}catch{return""}}o(Oz,"readText");function QA(e){try{return SA.lstatSync(e).isFile()}catch{return!1}}o(QA,"isFile");var wde="SKYRAMP_TEST_SERVICE_URL_";var Bde=`${wde}UI`;var Xm="test-package.json";var kde=["node_modules",".venv","test-results","playwright-report","blob-report","__pycache__",".pytest_cache"];var Lz=o(e=>e.split(zi.sep).join("/"),"posix");function ey(e,t){let n=Lz(e);return t.some(i=>n===i||n.startsWith(`${i}/`))}o(ey,"insidePackage");function Rx(e){return Lz(e).split("/").some(t=>kde.includes(t))}o(Rx,"producedByPackage");var O$e=new RegExp([String.raw`\bECONNREFUSED\b`,String.raw`\bconnect ETIMEDOUT\b`,String.raw`\bconnection refused\b`,String.raw`\bconnection to \S+ refused\b`,String.raw`\bactively refused\b`,String.raw`\bcould not connect to\b`,String.raw`\bunable to (?:create|establish|open|obtain) (?:a |an |the )?(?:\w+ )?connection\b`,String.raw`\bcan't connect to (?:local )?(?:MySQL|MariaDB) server\b`,String.raw`\bconnection to server (?:at|on) .+ failed\b`,String.raw`\bCommunications link failure\b`,String.raw`\berror \d+ connecting to \S+`,String.raw`\b(?:timed out|timeout) (?:while |when )?(?:trying to )?connect(?:ing)? to\b`,String.raw`\bconnect(?:ion)? (?:attempt )?timed out\b`,String.raw`\bdial tcp \S+: (?:connect: )?i/o timeout\b`].join("|"),"i"),L$e=new RegExp([String.raw`\bAssertion(?:Failed)?Error\b|\bComparisonFailure\b|Error Trace:|\bNot equal:`,String.raw`\bexpect\(|\b[Ee]xpected\b|\bbut was\b|\bassert(?:_\w+|[A-Z]\w*)?\b|\.to(?:Be|Equal|Match|Throw|Contain|Have)\w*\b`].join("|"));var j$e=String.raw`localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|\[::1?\]|::1`;var Sde=o(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"escapeRegex"),Vz=/%[psdifjo#]|\$[A-Za-z_][\w.]*/g;var Qde=/ (?:>|›) /;function Rde(e){return e.split(Vz).map(t=>t.split(Qde).map(Sde).join("(?: > | \u203A | )")).join(".+?")}o(Rde,"testNamePattern");function zz(e,t){return new RegExp(Vz.source).test(t)?new RegExp(`^(?:.* )?${Rde(t)}$`).test(e):!1}o(zz,"isEachCaseOf");var ty=Se(require("fs")),Jz=Se(require("path"));var $de=/[;|`$<>(){}\n\r]|(?<!&)&(?!&)|\|\|/,Tde=/`|\$[\w{(@*#?!$-]|\\[$`"\\\n]/;function Dde(e){let t="";for(let i=0;i<e.length;){let r=e[i];if(r==="\\"&&(e[i+1]==='"'||e[i+1]==="'"))return{syntax:"a backslash before a quote",quoted:!1};if(r!=='"'&&r!=="'"){t+=r,i++;continue}let s=e.indexOf(r,i+1);if(s<0)return;let a=r==='"'?Tde.exec(e.slice(i+1,s+(e[s-1]==="\\"?1:0))):null;if(a)return{syntax:`${qz(a[0])} inside double quotes`,quoted:!0};t+=" ",i=s+1}let n=$de.exec(t);return n?{syntax:qz(n[0]),quoted:!1}:void 0}o(Dde,"shellSyntax");var qz=o(e=>e==="`"?"a backtick":/[\n\r]/.test(e)?"a line break":`\`${e}\``,"shown");function ny(e){let t=(e??"").trim();if(!t)return{kind:"empty",reason:"the command is empty"};let n=Dde(t);if(n)return{kind:"shell-syntax",reason:`it uses shell syntax (${n.syntax}), and this is re-executed WITHOUT a shell so the recorded string cannot be interpreted \u2014 put the logic in a script and record the script invocation instead, or put an argument that holds such characters in ${n.quoted?"single quotes":"quotes"}`};let i=[],r=[],s="",a,c=!1,u=o(()=>{(s||c)&&r.push(s),s="",c=!1},"endToken"),l=o(()=>{u(),r.length>0&&i.push(r),r=[]},"endStep");for(let p=0;p<t.length;p++){let g=t[p];if(a){g===a?a=void 0:s+=g;continue}if(g==='"'||g==="'"){a=g,c=!0;continue}if(g==="&"&&t[p+1]==="&"){l(),p+=1;continue}if(/\s/.test(g)){u();continue}s+=g}if(a)return{kind:"unterminated-quote",reason:"it has an unterminated quote"};if(l(),i.length===0)return{kind:"empty",reason:"the command is empty"};if(i.some(p=>p.length===0))return{kind:"empty-step",reason:"it has an empty step between && operators"};let A=i.find(p=>["cd","export","source","."].includes(p[0]));return A?{kind:"builtin",reason:`it runs the shell builtin "${A[0]}", which cannot be executed as a program \u2014 record a script that does this instead`}:{argv:i[0],steps:i}}o(ny,"parseCommand");function xx(e,t,n){let i=(e??"").trim(),{steps:r,kind:s}=ny(i);if(!r&&!(s!=="shell-syntax"&&s!=="builtin")){try{ty.mkdirSync(Jz.dirname(t),{recursive:!0}),ty.writeFileSync(t,`#!/usr/bin/env bash
|
|
154
154
|
# Written by ${n}: the recorded command, which needed a shell to run.
|
|
155
155
|
set -euo pipefail
|
|
156
156
|
${i}
|
|
157
|
-
`,{mode:493})}catch{return}return`bash ${$x(t)}`}}o(xx,"scriptedCommand");function $x(e){return`'${e.split("'").join("'\\''")}'`}o($x,"shQuote");function Tx(e){return Dx(e)&&QR(e).length===0&&xR(e.inputs?.sharedEnvironment).length===0}o(Tx,"sutIsHealthy");function Dx(e){let t=Mde(e);if(!t&&e.state.stages.deploy?.status!=="passed")return!1;let n=Ve(e,"deploy.json");return n?Pde(n):!t}o(Dx,"sutCameUp");function Pde(e){return e?.outcome==="clean"||e?.outcome==="recipe-drift"}o(Pde,"deployCameUp");function Mde(e){let t=e.state.stages.plan,n=e.state.stages.deploy;return!(e.inputs?.pipeline?e.inputs.pipeline==="two-step":!n)||t?.status!=="passed"?!1:!n||n.updatedAt<=t.updatedAt}o(Mde,"broughtUpByPlan");var Q0e=10*6e4;var iy=(r=>(r.RestApi="rest-api",r.Frontend="frontend",r.FullStack="full-stack",r.Other="other",r))(iy||{}),la=(r=>(r.Critical="critical",r.High="high",r.Medium="medium",r.Low="low",r))(la||{}),da=(i=>(i.Suspected="suspected",i.Latent="latent",i.Refuted="refuted",i))(da||{}),Ux=(i=>(i.Skyramp="skyramp",i.External="external",i.Unknown="unknown",i))(Ux||{}),Fx=(r=>(r.Cascade="cascade",r.Restrict="restrict",r.Orphan="orphan",r.Unknown="unknown",r))(Fx||{}),pi=(r=>(r.RequirementReference="requirement-reference",r.Spec="spec",r.PrDescription="pr-description",r.CouldBreak="could-break",r))(pi||{}),Xe=d.string().trim().min(1),Iu=Xe.describe("file:line"),Yz=o(e=>Xe.refine(t=>t.length<=400,t=>({message:`is ${t.length} characters, over the 400 cap \u2014 ${e}`})),"cap400"),RA=Xe.optional().describe('multi-repo only: the OTHER checkout this lives in \u2014 its "owner/repo" slug, or the directory name if the run discovered it; omit for the working checkout'),Nx=d.object({method:Xe,path:Xe,service:d.string().optional(),evidence:Iu,repository:RA}),Vde=d.object({id:Xe.describe("short-slug, e.g. R9"),statement:Xe.max(400,"exceeds 400 characters \u2014 state the requirement, do not paste the spec section").describe("a testable obligation, not a summary"),source:d.nativeEnum(pi).describe("spec outranks pr-description when both state it"),evidence:Xe.describe("spec: file:line or a section locator. pr-description: the quoted phrase it comes from.")}),zde=d.object({id:Xe.describe("short-slug"),statement:Xe.max(400,"exceeds 400 characters \u2014 state the behaviour, do not paste the code").describe("what the change makes true"),surface:Xe.describe("METHOD /path, or a component/page name"),evidence:Xe.describe("file:line from the diff that introduces it"),repository:RA,satisfies:d.array(Xe).optional().describe("requirement ids (from `requirements`) this behaviour correctly implements \u2014 a requirement met only in part is ALSO named by the finding that shows the rest (conflictsWith)")}),qde=d.object({id:Xe.describe("short-slug"),file:Xe,line:d.number().optional(),claim:Yz("shorten it to the one sentence that states the defect, and move the supporting detail into `evidence`"),severity:d.nativeEnum(la),evidence:Yz("cite the file:line and the one line that shows it, rather than reproducing the surrounding code").describe("quoted diff/code line"),status:d.nativeEnum(da),repository:RA,conflictsWith:d.array(Xe).optional().describe("requirement ids (from `requirements`) this defect contradicts or leaves unimplemented \u2014 a lower-precedence source (the diff, or the PR description) lost")}),Jde=d.object({name:Xe,language:d.string().optional(),framework:d.string().optional(),evidence:Iu,repository:RA}),Hde=d.object({dir:Xe,framework:d.string().optional(),kind:d.nativeEnum(Ux),evidence:Iu,repository:RA}),Yde=d.object({from:Xe,to:Xe,onDelete:d.nativeEnum(Fx),evidence:Iu}),Wde=d.object({entity:Xe,field:Xe,values:d.array(d.string()),evidence:Iu}),Zde=d.object({entities:d.array(d.object({name:Xe,evidence:Iu})),references:d.array(Yde).describe("INBOUND references \u2014 what still points at an entity when it is deleted"),stateFields:d.array(Wde)}),Px=d.object({schemaVersion:d.literal(1),repository:d.object({path:Xe.describe("absolute repo path"),currentBranch:Xe,baseBranch:Xe}),project:d.object({type:d.nativeEnum(iy),primaryLanguage:Xe,languages:d.array(d.string()),frameworks:d.array(d.string())}),services:d.array(Jde),infrastructure:d.object({containerized:d.boolean(),hasDockerCompose:d.boolean(),composeFiles:d.array(d.string()),hasCiCd:d.boolean()}),diff:d.object({changedFiles:d.array(d.string()).describe("as git reports them; a file in another checkout may carry that repo's name"),nonApplicationOnly:d.boolean(),summary:Xe.describe("\u2264400 chars")}),endpoints:d.object({new:d.array(Nx),modified:d.array(Nx),removed:d.array(Nx)}),existingTests:d.object({locations:d.array(Hde)}),entityMap:Zde,requirements:d.array(Vde).describe("from a spec (attached or linked) and/or the PR description; empty when neither states a testable obligation"),behaviors:d.array(zde),findings:d.array(qde),unexamined:d.array(d.string()).describe("files or areas outside this change you did not open"),summary:Xe.describe("one paragraph on what this change does and its test-relevant risk")});var tAe=d.object({route:d.string().describe('the page this step happens on, e.g. "/products/:id"'),action:d.string().describe('what the user does there, through the UI, e.g. "clicks Add to cart"'),clauses:d.array(d.string()).optional().describe("the plan clause ids this step exercises"),check:d.string().optional().describe("what the user then sees that shows the step worked; the test asserts it")}),xA=(n=>(n.InProcess="in-process",n.Browser="browser",n))(xA||{}),Wz=(i=>(i.Spec="spec",i.PrDescription="pr-description",i.Inferred="inferred",i))(Wz||{}),Zz=d.object({id:d.string().describe('e.g. "J1"'),name:d.string().describe(`the flow in a user's words, e.g. "buy a product with a coupon"`),entry:d.string().describe("the route the user starts the flow on: the app's normal starting page for it, never a deep link into its middle"),steps:d.array(tAe).describe("every step, in order, from the entry page to the outcome: at least two"),outcome:d.string().describe("what the user sees at the end that shows the flow worked: every part of it"),finishes:d.string().optional().describe('the user action that completes the task, verb first, e.g. "places the order"; the journey walks on to it'),kind:d.nativeEnum(xA).optional().describe("in-process when the repo's in-process tests (components, app routes) can walk the whole flow and check it; else browser"),source:d.nativeEnum(Wz).optional().describe("spec or pr-description when one describes this flow (quote it under evidence), else inferred"),evidence:d.string().optional().describe("for spec or pr-description: its words that describe the flow"),testFile:d.string().describe("the browser test file it goes in, beside the repo's existing e2e tests")}),sy=d.object({journey:d.string().describe("the plan's journey id"),file:d.string().describe("the browser test file that walks it"),brokeAt:d.object({step:d.number().int().describe("the 1-based step whose check failed first"),expected:d.string(),actual:d.string().describe("what the app did instead, from the runner's output"),notReached:d.array(d.number().int()).optional().describe("later steps the test could not get to")}).optional().describe("only when the journey's test failed on a check: where"),test:d.string().describe("the title of the one test in that file that walks it end to end")});var j0e=Object.fromEntries([...["ts","tsx","mts","cts","js","jsx","mjs","cjs"].map(e=>[e,"node"]),...["java","kt","kts","groovy","scala"].map(e=>[e,"jvm"]),["py","python"],["go","go"]]);var G0e=["stale_test","open_question"],V0e=["low","medium","high","critical"];var Kz=String.raw`(?:\[[^\]]*\]|\([^)]*\))`,nAe=String.raw`(?:["'\u201c\u2018\x60]|\*{1,2})?[^\s:"'\u201c\u201d\u2018\u2019\x60*()[\],]+(?:["'\u201d\u2019\x60]|\*{1,2})?`,Xz=String.raw`(?:${Kz}|${nAe}(?:\s*${Kz})?)`,e2=String.raw`(?:\s*:|\s+[\u2014\u2013-])`,H0e=new RegExp(String.raw`^\s*(?:${Xz}(?:,\s*${Xz})*(?::L?\d+(?:[-\u2013]\d+)?${e2}?|${e2})|\[[^\]\s]+\]|\([^)\s]+\))\s+`);var $A=(n=>(n.Skyramp="skyramp",n.Llm="llm",n))($A||{}),qi=d.string().trim().min(1),rAe=d.object({case:qi.describe("recommend id this assertion enforces"),evidence:qi.describe("the exact assertion line from the file that checks that case's observable")}),Mx=d.object({kind:d.nativeEnum(hg).describe("seed: data the test creates in the app; runtime_mock: a mock on a Skyramp worker, which other tests reach too; env_override: an env value the app runs with. A stub inside the test's own process, such as a browser page's route, is none of these"),target:qi.describe("the dependency, endpoint or data it affects"),mechanism:d.nativeEnum(mg).describe("test_code: the test applies and undoes it; skyramp_mocker: a mock the test applies on a Skyramp worker; recipe_override: the mocker cannot reach the dependency (its URL is fixed in the build)"),detail:qi.describe("what it sets up"),worker:qi.optional().describe("skyramp_mocker: host:port of the worker the test applies the mock to (default localhost:35142)"),cleanup:qi.optional().describe("seed: a command that removes the data when the test does not, run as written and without a shell: give real values, not a placeholder such as <id>, single-quote an argument that holds shell syntax, or put the logic in a script in the repository and run that")}),iAe=d.object({file:qi.describe("staged path under .skyramp/staged/"),source:d.nativeEnum($A),language:qi,covers:d.array(d.string()).min(1,"must be a non-empty array of recommend ids").describe("recommend ids this test covers"),assertions:d.array(rAe).min(1,"must be a non-empty array").describe("one per case covered, citing the real line"),context:d.array(Mx).optional().describe("what the test sets up against the running app, in order: data it seeds, Skyramp mocks it applies, env overrides; omit when none")}),Ox=d.object({schemaVersion:d.literal(1),tests:d.array(iAe),deferredUi:d.array(d.string()).describe("recommend ui ids left for the UI stage (generate) \u2014 [] for generate-ui"),summary:qi.describe("one paragraph")});var Ls=Se(require("fs")),vu=Se(require("path")),i2=require("child_process");var sn="{junit}",oy=(r=>(r.Junit="junit",r.Trx="trx",r.GoTestJson="go-test-json",r.JestJson="jest-json",r))(oy||{}),Lx=(t=>(t.Minitest="minitest",t))(Lx||{}),t2=d.string().trim().min(1),Cu=d.object({cwd:t2.describe('repo-relative directory the command starts in ("." for the root)'),argv:d.array(t2).min(1).describe(`the command as separate arguments, run without a shell; for a junit or trx report an argument or env value holds ${sn}, where the report is written (not for Maven or Gradle, whose build writes its own)`),env:d.record(d.string(),d.string()).optional().describe("plain test or reporter settings beyond the repository's CI test job (RAILS_ENV=test, PLAYWRIGHT_JUNIT_OUTPUT_FILE={junit}); never a credential, PATH, or a tool's install path"),report:d.object({format:d.nativeEnum(oy).describe(`junit (JUnit XML to ${sn}), trx (to ${sn}), jest-json (Jest's --json or Vitest's --reporter=json, --outputFile=${sn}), or go-test-json (go test -json on the command's output)`),reporter:d.nativeEnum(Lx).optional().describe("a reporter Testbot loads for a runner that writes no report: minitest")}).optional().describe("the report the command writes; junit when omitted")});var bu="a framework other than pytest, jest, vitest and node --test (go test, rails test, mvn, dotnet test), or one the repository's test script runs through another command (ng test, nx test)",nTe=`pytest, Jest, Vitest and node --test tests run as the run already knows them, unless the repository's test script runs them through another command (ng test, nx test), which may be the only one that compiles them. A test in any other framework, or one run that way, also gives "run": the repository's own command for only those tests, from the directory the repository runs it in, as separate arguments without a shell. Its "report" says what the runner writes: junit (JUnit XML to ${sn} in the reporter's argument or env setting), trx (a TRX file to ${sn}, which every dotnet test writes with its built-in logger), jest-json (Jest's --json --outputFile=${sn}, or Vitest's --reporter=json --outputFile=${sn}: built in, no reporter package), or go-test-json (go test -json, read from the command's output). A Maven or Gradle command names no ${sn}: its build writes JUnit XML to its own report directory, which the run reads. Use a reporter the repository already has, or one of those; a reporter or converter the command fetches is the version the repository pins, or else its latest release (an older one may not build with the repository's toolchain). For minitest, which writes none, give report.reporter "minitest" and the run fills ${sn} itself. A setting the tests or reporter read goes in "env" (RAILS_ENV=test, or PLAYWRIGHT_JUNIT_OUTPUT_FILE=${sn} with playwright test --reporter=junit): the run sets it, so never wrap the command in a shell to set one. The run replaces ${sn} in argv and env with its report path, executes the command, and reads that report.`;var Os=(r=>(r.ExistingEvidenceSufficient="existing_evidence_sufficient",r.TargetedUnit="targeted_unit",r.RuntimeRequired="runtime_required",r.BlockedPreflight="blocked_preflight",r))(Os||{}),Ji=(s=>(s.ExistingEvidence="existing_evidence",s.Unaffected="unaffected",s.ExistingUnit="existing_unit",s.NewUnit="new_unit",s.Runtime="runtime",s))(Ji||{}),jx=(n=>(n.Repository="repository",n.Testbot="testbot",n))(jx||{}),Gx=(i=>(i.Identified="identified",i.Passed="passed",i.Failed="failed",i))(Gx||{}),Fn=d.string().trim().min(1),sAe=d.string().regex(/^[a-z0-9][a-z0-9-]*$/,"must be a short lowercase slug").describe("short-slug");var oAe=d.object({id:sAe,source:d.nativeEnum(jx),kind:d.nativeEnum(bs),outcome:d.nativeEnum(Gx),summary:Fn.max(400).describe("one line: what it shows"),tests:d.array(Fn).optional().describe("source repository: the existing tests, as repo-relative paths, optionally path::test-name"),repository:Fn.optional().describe("source repository: owner/repo the tests live in, when the run has several checkouts; omit for the working checkout"),command:Fn.optional().describe("source testbot: the exact command you ran, as you ran it"),run:Cu.optional().describe(`source repository, for tests in ${bu}: how the run executes the whole of each of these test files, all of them in one command, never narrowed to the named tests and never only listed, with the repository's own runner writing JUnit XML to {junit}. A test is credited to a file only by its name or by a report that names the file`)}),aAe=d.object({behaviorId:Fn.describe("an id from analyze's behaviors"),mechanism:d.nativeEnum(Ji),evidenceIds:d.array(Fn).default([]).describe("existing_evidence: the ci-<n> or evidence ids that establish it; existing_unit: the evidence id naming the tests to run"),covers:d.string().trim().optional().describe('new_unit / runtime: the missing evidence this obtains, e.g. "the boundary the change moved"; unaffected: why the change cannot reach it, citing path:line')}),Vx=(i=>(i.Browser="browser",i.RunningApp="running-app",i.Outside="outside",i))(Vx||{}),cAe=d.object({behaviorId:d.string().trim().optional().describe("an id from analyze's behaviors, when it is about one"),missing:Fn.max(600).describe("the evidence that is required and cannot be obtained in this run"),needs:d.nativeEnum(Vx).optional().describe("what that evidence needs: browser (only a real browser shows it), running-app (only the running app or its server shows it: its real requests, sign-in and permissions, what it saves), or outside (something the running app here could not give either: a third-party service it calls, hardware)")}),uAe=d.object({file:Fn.describe("the changed file the failure is in"),repository:Fn.optional().describe("owner/repo the file is in, when the run has several checkouts; omit for the working checkout"),reason:Fn.max(300).describe("what prerequisite the change fails"),evidence:Fn.max(400).describe("the error line, quoted")}),lAe=d.object({behaviorId:Fn.describe("an id from analyze's behaviors"),reason:Fn.max(600).describe("\u2264600 characters: why this change leaves the behavior's result as it was, citing the unchanged line that decides it (path:line)")}),TA=d.object({schemaVersion:d.literal(1),decision:d.nativeEnum(Os),evidence:d.array(oAe).describe("evidence this session found or produced; CI results are the ci-<n> items and are not restated here"),plan:d.array(aAe).describe("how each changed behavior's evidence is obtained"),gaps:d.array(cAe),outOfScope:d.array(lAe).optional().describe("behaviors analyze found that this change neither changes nor states"),blocked:uAe.optional().describe("only for blocked_preflight"),rationale:Fn.max(1200).describe("\u22641200 characters: why this evidence is enough, or what it still lacks \u2014 the scope you chose and why")});function DA(e){let t=Ve(e,"recommend.json");if(!t||!Array.isArray(t.generate)||!Array.isArray(t.maintenance))return;let n=t;return{...n,maintenance:n.maintenance.map(({repository:i,...r})=>({...r,test:r.test.trim().replace(/^\.\//,""),...i?.trim()?{repository:i.trim()}:{}}))}}o(DA,"readRecommend");function fAe(e){return mn(Ox,e).errors}o(fAe,"validateGenerateOutput");function gAe(e,t=[]){let{value:n,error:i}=$t(e,t);if(i)return{errors:[i]};let r=fAe(n);return r.length>0?{errors:r}:{generate:n,errors:[]}}o(gAe,"parseGenerateText");function ay(e,t=[]){return gAe(e.stdout,t)}o(ay,"parseGenerateFromSession");function hAe(e){return e.generate.filter(t=>t.type!=="ui").map(t=>t.id)}o(hAe,"backendCases");function s2(e){return e.generate.filter(t=>t.type==="ui").map(t=>t.id)}o(s2,"uiCases");var cy={backend:{stage:"generate",cases:hAe,noRecommendCoverage:"recommend.json missing or malformed \u2014 cannot check coverage",noRecommendIntent:"recommend.json missing or malformed \u2014 cannot check intent",uncovered:o(e=>`recommend case "${e}" is not covered by any generated test`,"uncovered"),unknownCovered:o(e=>`test covers unknown recommend id "${e}"`,"unknownCovered"),unasserted:o(e=>`case "${e}" has no verified assertion enforcing its expected_observable`,"unasserted"),usedCodegen:O1,codegenHint:"These tests were hand-written. Skyramp codegen (skyramp_contract_test_generation / skyramp_integration_test_generation) was available but not used \u2014 it computes valid sample data and response correlations. Prefer scaffolding with it and then refining, especially for the failures above."},ui:{stage:"generate-ui",cases:s2,noRecommendCoverage:"recommend.json not found \u2014 cannot check UI coverage",noRecommendIntent:"recommend.json not found \u2014 cannot check UI intent",uncovered:o(e=>`UI case "${e}" is not covered by any generated UI test`,"uncovered"),unknownCovered:o(e=>`test covers "${e}" which is not a recommend UI case`,"unknownCovered"),unasserted:o(e=>`UI case "${e}" has no verified assertion enforcing its expected_observable`,"unasserted"),usedCodegen:L1,codegenHint:"This UI test was hand-authored. Skyramp UI codegen (skyramp_ui_test_generation) was available but not used. Prefer scaffolding with it and then refining, especially for the failures above."}},FTe=$n("generate-schema",(e,t)=>ay(t,e.secretValues));function mAe(e){let t=cy[e];return{name:`${t.stage}-coverage`,verify(n,i){let{generate:r,errors:s}=ay(i,n.secretValues);if(!r)return Lt(this.name,s);let a=DA(n);if(!a)return Lt(this.name,[t.noRecommendCoverage]);let c=new Set(r.tests.flatMap(p=>p.covers)),u=[],l=t.cases(a);for(let p of l)c.has(p)||u.push(t.uncovered(p));let A=new Set(e==="ui"?l:a.generate.map(p=>p.id));for(let p of c)A.has(p)||u.push(t.unknownCovered(p));if(e==="backend"){let p=new Set(r.deferredUi),g=new Set(s2(a));for(let h of g)!p.has(h)&&!c.has(h)&&u.push(`UI case "${h}" is neither covered nor deferred to the UI stage`);for(let h of p)g.has(h)||u.push(`deferredUi lists "${h}" which is not a UI case`)}return u.length===0?{name:this.name,passed:!0}:Lt(this.name,u)}}}o(mAe,"generateCoverageGateFor");function yAe(e){let t=cy[e];return{name:`${t.stage}-intent`,verify(n,i){let{generate:r,errors:s}=ay(i,n.secretValues);if(!r)return Lt(this.name,s);let a=DA(n);if(!a)return Lt(this.name,[t.noRecommendIntent]);let{asserted:c,errors:u,badFiles:l}=BAe(r,n.inputs.repositoryPath),A=u.length;for(let g of t.cases(a))c.has(g)||u.push(t.unasserted(g));if(u.length===0)return{name:this.name,passed:!0};let p=Lt(this.name,u);return A>0&&A===u.length&&l.size>0?{...p,droppable:[...l]}:p}}}o(yAe,"generateIntentGateFor");function EAe(e){let t=cy[e];return n=>{if(!n.inputs.skyrampMcp?.command||e==="backend"&&!Tx(n))return;let i=vu.join(n.outputsDir,`${t.stage}-stream.ndjson`);if(!(!Ls.existsSync(i)||t.usedCodegen(i)))return j1(i)?t.codegenHint:"Skyramp codegen tools were configured but the MCP server did not connect this session, so they were not available. Hand-authoring was the only option; this is an environment problem, not yours."}}o(EAe,"codegenRetryHintFor");var PTe=mAe("backend"),MTe=yAe("backend"),OTe=EAe("backend");var n2=o(e=>e.replace(/\s+/g,""),"squeeze");var zx={python:[/\bassert\s*[({\w"'`]/g,/\bpytest\.raises\s*\(/g,/\bself\.assert\w*\s*\(/g],typescript:[/\bexpect\s*\(/g,/\.should\b/g,/\bassert\s*[.(]/g],go:[/\bt\.(Error|Errorf|Fatal|Fatalf|Fail|FailNow)\s*\(/g,/\b(assert|require)\.\w+\s*\(/g],java:[/\bassert\w*\s*\(/g,/\bassertThat\s*\(/g],ruby:[/\bexpect\s*[({]/g,/\bassert\w*\b/g,/\.should\b/g]};for(let[e,t]of[["javascript","typescript"],["kotlin","java"]])zx[e]=zx[t];function IAe(e,t){if(e.includes(dd(t))||n2(e).includes(n2(t)))return!0;let n=t.split(/\r?\n/).map(i=>i.trim()).filter(i=>i&&!/^(\/\/|#|\*|\/\*)/.test(i));return n.length>0&&n.every(i=>e.includes(dd(i)))?!0:wAe(e,t)}o(IAe,"evidenceFound");var CAe=/\bassert\w*\b|\bexpect\s*\(|\.should\b|\brequire\s*\(/i,bAe=12,vAe=/,\s*\(\s*#|,\s*f?["'`]|\s+#\s|\s+\/\/|\s*\((?:line|lines|at line)\b|\s*,\s*$/i;function wAe(e,t){let n=t.split(/\s*;\s*|\s*\.\.\.\s*|\r?\n/),i=0;for(let r of n){let s=CAe.exec(r);if(!s)continue;let a=r.slice(s.index),c=vAe.exec(a);if(c&&(a=a.slice(0,c.index)),a=dd(a).replace(/[,\s]+$/,""),a.length<bAe||!e.includes(a))return!1;i++}return i>0}o(wAe,"annotatedAssertionFound");function BAe(e,t){let n=new Set,i=[],r=new Set;for(let s of e.tests){let a=vu.resolve(t,s.file);if(!Ls.existsSync(a))continue;let c=dd(Ls.readFileSync(a,"utf-8"));for(let u of s.assertions??[]){if(!IAe(c,u.evidence)){i.push(`assertion evidence for "${u.case}" not found in ${s.file} \u2014 cite the real assertion line`),r.add(s.file);continue}s.covers.includes(u.case)?n.add(u.case):(i.push(`assertion cites case "${u.case}" not in that test's covers[]`),r.add(s.file))}}return{asserted:n,errors:i,badFiles:r}}o(BAe,"verifiedAssertions");var kAe=/\.(spec|test)\.[cm]?[jt]sx?$/i;function o2(e){let t;try{t=(0,i2.execFileSync)("git",[...Ri,"status","--porcelain","--untracked-files=all"],{env:Xt(),cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]})}catch{return}let n=o(r=>/_scaffold/i.test(r)||Ad.test(r),"isTestLitter"),i=[];for(let r of t.split(`
|
|
158
|
-
`)){if(!r.trim()||r.length>1&&r[1]==="D")continue;let s=r.slice(3).trim(),a=s.indexOf(" -> ");if(a!==-1&&(s=s.slice(a+4).trim()),s=s.replace(/^"|"$/g,""),!s)continue;let c=s.replace(/^\.\//,"");c.startsWith(".skyramp/")||!n(c)||i.push(c)}return i}o(o2,"testLitter");function SAe(e){let t=cy[e],n=e==="ui";return{name:`${t.stage}-no-litter`,verify(i){let r=o2(i.inputs.repositoryPath);if(r===void 0)return{name:this.name,passed:!0};let s=r.filter(a=>kAe.test(a)===n);return s.length===0?{name:this.name,passed:!0}:Lt(this.name,[`${t.stage} left files outside .skyramp/ \u2014 move the staged test into .skyramp/staged/ and delete any codegen draft (e.g. *_scaffold.*): ${s.slice(0,6).join(", ")}`])}}}o(SAe,"noLitterGateFor");var LTe=SAe("backend");var xAe="write-stale-updates",$Ae={[xAe]:"stale test updates"};var _A=Se(require("fs")),Aa=Se(require("path"));function l2(e){return mn(kb,e).errors}o(l2,"validateAdaptOutput");function _Ae(e,t=[]){let{value:n,error:i}=$t(e,t);if(i)return{errors:[i]};let r=l2(n);return r.length>0?{errors:r}:{adapt:n,errors:[]}}o(_Ae,"parseAdaptText");var NAe="adapt-scratch",c2=`${NAe}/adapt-result.json`;function d2(e,t){let n=Aa.join(e.outputsDir,c2),i;try{i=_A.readFileSync(n,"utf-8")}catch{i=void 0}if(i!==void 0&&(e.secretValues??[]).some(a=>i.includes(a)))return{errors:[`${c2} contains a secret value (token / credential) \u2014 never write it anywhere`]};let r=_Ae(t.stdout,e.secretValues);if(r.adapt)return r;let s=i!==void 0?jo(n):void 0;return s!==void 0&&l2(s).length===0?{adapt:s,errors:[]}:r}o(d2,"parseAdaptFromSession");var mDe=$n("adapt-schema",d2);var A2=require("child_process");function qx(e){return UAe(e)??[]}o(qx,"statusEntries");function UAe(e){let t;try{t=(0,A2.execFileSync)("git",[...Ri,"status","--porcelain","-z","--untracked-files=all"],{env:Xt(),cwd:e,encoding:"utf-8",maxBuffer:16*1024*1024})}catch{return}let n=t.split("\0"),i=[];for(let r=0;r<n.length;r++){let s=n[r];if(s.length<4)continue;let a=s.slice(0,2);i.push({code:a,path:s.slice(3)}),(a[0]==="R"||a[0]==="C")&&r++}return i}o(UAe,"readStatusEntries");var SDe=2*1024*1024;var uy=d.string().trim().min(1),FAe=d.object({cwd:uy.describe(`directory the command starts in, relative to the test's checkout ("." for its root)`),argv:d.array(uy).min(1).describe("the command as separate arguments, run without a shell"),env:d.record(d.string(),d.string()).optional().describe("plain settings the listing needs beyond the CI step's own; never a credential or PATH")}),PAe=d.object({file:uy.describe("a file of the test's checkout, relative to its root"),line:uy.describe("a line of that file, quoted exactly from where its command starts to its end")}),p2=d.object({collected:d.boolean().describe("whether the repo's CI runs this test as it is"),steps:d.array(PAe).optional().describe("when collected: the line in a CI file that starts the tests, then each line it runs on the way to the test runner"),runner:d.string().optional().describe("when collected: the test runner the last of those lines starts, by the name that line and the list command both use"),list:FAe.optional().describe("when collected: a command that lists the tests that runner collects without running them; Testbot runs it, and its output must name this file"),why:d.string().optional().describe("when not collected: why the repo's CI will not run it")});var ce=d.string().trim().min(1),VAe=o(e=>{if(!e||typeof e!="object")return e;let t=e;return typeof t.skip=="string"&&t.skip.trim()&&(t.expected===void 0||t.expected===null)?{...t,expected:"(not tested)"}:e},"skippedNeedsNoExpected"),zAe=d.preprocess(VAe,d.object({id:ce.describe(`its requirement's id plus a letter, e.g. "R1a", "AC-3a"`),clause:ce.describe("one testable part of the requirement"),expected:ce.describe("the outcome the requirement calls for \u2014 taken from the requirement, never from what the code does"),skip:d.string().optional().describe("only when no test can check this clause here: why"),type:d.nativeEnum(Gi).optional().describe("the test that checks this clause: contract / integration (the API, or code called directly in-process: a function, hook or module) or ui (a page)"),target:d.string().optional().describe('its "METHOD /path", or the page / flow'),steps:d.string().optional().describe("what that test does; its expected outcome is this clause's"),finding:d.string().optional().describe("the finding id, when this clause's test also catches that defect (the defect still gets a case of its own)"),code:d.string().optional().describe("path:line of the code that decides this clause, when there is one; in another repo of the change, that repo's directory name then its path"),stated:d.string().optional().describe("the description's or spec's own words that state this clause, copied exactly, when they do"),mutates:d.boolean().optional().describe("true when its test changes state, in the test or its setup: an API POST, PUT, PATCH or DELETE, or a UI flow that submits, creates, edits or deletes"),browserOnly:d.boolean().optional().describe("true when its behaviour happens only in a browser: real clicks or keys driving page script, client-side sorting or filtering, script-driven DOM updates, focus, drag-and-drop, navigation, rendering that depends on CSS or JavaScript"),browserHarness:d.string().optional().describe("browserOnly, off the runtime path: the path of the repo's in-process browser suite its test goes in (e.g. a Django StaticLiveServerTestCase test that drives Selenium)"),quote:d.string().optional().describe("the words of the spec, plan, ticket, PR description or a test the change adds or edits that state this clause, copied exactly; a file of the repository: its path:line first. Leave it out when no source states it"),inferred:d.boolean().optional().describe("leave it out: Testbot sets it when no source states this clause (contracts/clause-grounding.ts)")})),g2=d.object({spec:d.string().optional().describe("file:line of a spec in the repository"),prDescription:d.boolean().optional().describe("or true when a pull request description says otherwise"),reference:d.string().optional().describe("or the key of an item the run was given, as listed"),says:ce.describe("what it says there, in its own words, copied exactly"),criterion:d.number().int().positive().optional().describe("an item's only: leave it out; Testbot numbers it")}).refine(e=>[!!e.prDescription,!!e.spec?.trim(),!!e.reference?.trim()].filter(Boolean).length===1,{message:`names no source, or more than one: give "spec" its file:line or "reference" an item's key, or set "prDescription", one of them; list each source as its own entry`}),qAe=d.object({id:ce.describe('the label its source gives it ("AC-3", "REQ-12"; item 4 of a numbered list is "R4"), else "R1", "R2"\u2026 in order'),statement:ce,source:d.nativeEnum(pi).describe("requirement-reference (an item the run was given), spec, pr-description (also for what the change is evidently meant to do when nothing is written down), or could-break (what the change could break that no requirement mentions)"),reference:d.string().optional().describe('requirement-reference only: the key of its item as listed, e.g. "PAY-184", or a Confluence page id such as "3021"'),evidence:ce.describe("where it is stated: for requirement-reference, the item's own words, copied exactly; else file:line, a doc section, or the quoted phrase"),criterion:d.number().int().positive().optional().describe("requirement-reference only: leave it out; Testbot numbers each criterion by the item's own label (AC2, 2.), else after the item's labels"),alsoFrom:d.array(d.object({reference:ce.regex(Cs).describe("the key of another uploaded document stating the same obligation"),says:ce.describe("that document's own words, copied exactly; never infer equivalence from a shared criterion number"),criterion:d.number().int().positive().optional().describe("leave out; Testbot grounds and numbers this source separately")})).optional().describe("equivalent uploaded source criteria sharing this requirement's planned cases; retain every source with its own quote. Different conditions or boundaries need distinct requirements"),notInChange:d.string().optional().describe("requirement-reference only: when the change does not touch this criterion at all (e.g. a later step of a staged rollout), why; give it no clauses"),unchanged:d.boolean().optional().describe("true when it asks only that behaviour stay as it was (an update or refactor that must not change how something works), whatever its source"),overrules:d.array(g2).optional().describe("requirement-reference only: each lower-ranked source that says otherwise, a spec in the repository, a PR description or another item; this requirement wins, so test what it says"),clauses:d.array(zAe)}),h2=(r=>(r.ServerError="server-error",r.DataLost="data-lost",r.FinalState="final-state",r.DerivedValues="derived-values",r))(h2||{}),JAe=d.object({id:ce.describe('e.g. "F1"'),file:ce,line:d.number().optional(),claim:ce.describe("the defect, in one sentence"),severity:d.nativeEnum(la),evidence:ce.describe("the code line, or the probe request and response, that shows it"),conflictsWith:d.array(ce).optional().describe("requirement or clause ids it violates"),keeps:d.string().optional().describe("for a defect no requirement or clause states: path:line of the code beside the change that keeps the rule it breaks"),rule:d.nativeEnum(h2).optional().describe("for a defect that breaks a rule every app keeps, which nothing needs to state: which one"),existing:d.string().optional().describe("only when the base already does this, in code the change left as it was, and the change does not say it fixes it: where the base does it (its file:line); such a defect gets no case"),needsApp:d.enum(["browser","live-api"]).optional().describe("only when the running app alone can show this defect and the repo has no in-process test that can: browser (page script, what the user sees after a click or a save) or live-api (code the repo tests only against the running app's API)")}),HAe=d.object({id:ce.describe('e.g. "Q1"'),question:ce.describe("what is unsettled, as a question the PR author can answer"),readings:d.array(ce).min(2).describe("each reasonable behaviour, with what points to it (file:line, or the words that suggest it)"),about:d.string().optional().describe("the requirement or clause id it is about, when there is one"),sources:d.array(g2).optional().describe("when sources of the same rank disagree on it: each of them")}),YAe=d.object({id:ce.describe('unique, a short kebab-case name for what the case checks, e.g. "ship-twice-409"'),type:d.nativeEnum(Gi).describe("contract / integration: checks the API, or calls code directly in-process (a function, hook or module); ui: checks what a user sees or does on a page"),target:ce.describe('"METHOD /path", or the page / flow'),clause:d.string().optional().describe("the clause id this case checks"),finding:d.string().optional().describe("the finding id this case catches"),steps:ce.describe("what the test does"),expected:ce.describe("the expected outcome, from the clause"),mutates:d.boolean().optional().describe("true when its test changes state, in the test or its setup: an API POST, PUT, PATCH or DELETE, or a UI flow that submits, creates, edits or deletes")}),WAe=d.object({test:ce.describe("existing test file"),action:d.nativeEnum(li),reason:ce,mutates:d.boolean().optional().describe("true when the maintained test changes state"),clauses:d.array(ce).optional().describe("the clause ids this test checks"),staleOnBase:d.boolean().optional().describe("true when the test's own expectation was already wrong before this change: it fails the same way on the base branch, where the app does what it should. Not one the base app's own bug fails (that is an existing defect). It is verify, never update: re-run as it is, its failure the test's own. A delete the change justifies stays a delete")}),f2=d.array(bb).optional(),ZAe=d.object({components:d.preprocess(e=>f2.safeParse(e).success?e:void 0,f2).describe("when saving a new or changed recipe: every app and backing service actually brought up, its source repository, and whether it is healthy"),outcome:d.nativeEnum(ri).describe("clean | recipe-drift (you had to fix the recipe) | change-broke-bringup (this PR broke start-up) | bringup-failed (the environment, not the PR)"),baseUrls:d.record(d.string()).optional().describe("service \u2192 base URL of the running app"),health:d.object({url:d.string().optional(),command:d.string().optional(),output:d.string().optional()}).optional().describe("the check that shows the app serves real data, and what it returned"),teardown:d.string().optional().describe("command that stops the app"),dependencies:d.record(d.boolean()).optional().describe("every backing service: true = really running, false = mocked"),recipeFixes:d.array(d.string()).optional().describe("what you changed in the recipe"),error:d.string().optional().describe("when it did not come up: the failing command and what it printed"),suspectFiles:d.array(d.string()).optional().describe("change-broke-bringup: the changed files to blame"),missingSecrets:d.array(d.string().regex(Yl)).optional().describe("bringup-failed only: each secret, key, token or password the app cannot start without that this run has no value for, by its environment variable name; never a value"),login:d.object({username:ce,password:d.string()}).optional().describe("the account the tests sign in as, when they sign in: each a literal value the recipe seeds, or $VARIABLE when a secret in the environment holds it"),revisions:Bb.optional()}),l_e=d.object({schemaVersion:d.literal(1),requirements:d.array(qAe),findings:d.array(JAe),cases:d.array(YAe).describe("a second test for a clause, and one case per finding that fails on this branch"),questions:d.array(HAe).optional().describe("behaviours the change leaves unsettled; no case asserts any of them"),maintenance:d.array(WAe),journeys:d.array(Zz).optional().describe("the user journeys that, together, pass through everything the change alters that a user sees or does; empty when it alters nothing a user sees"),notInJourney:d.array(d.object({clause:ce,why:ce})).optional().describe("a clause a user sees or does that no journey walks, and why: none can reach it through the UI, or it is downstream of this change and not walked here"),unplannedComponents:d.array(d.object({components:d.array(ce).min(1).describe("changed components, as the change lists them"),why:ce})).optional().describe("changed components no clause reaches, and why their change needs no test; several may share one reason"),triage:TA.optional().describe("the validation triage decision, made before the app is started; its behaviorIds are clause ids"),app:ZAe.optional().describe("omit when no app was needed or none was started"),summary:ce.describe("one paragraph: what the change does and where the risk is")});var NA=(n=>(n.Backend="backend",n.Ui="ui",n))(NA||{});var js=(r=>(r.Added="added",r.Updated="updated",r.Deleted="deleted",r.Unchanged="unchanged",r))(js||{}),KAe=d.object({file:ce.describe("repo-relative path; in another repo of the change, that repo's directory name then its path"),kind:d.nativeEnum(NA),change:d.nativeEnum(js).describe("added: a file you created; updated / deleted / unchanged: an existing test"),covers:d.array(d.string()).describe("the plan case ids this file tests, each with its own result under result.cases"),defect:d.boolean().optional().describe("true when a case of it fails because the app is wrong and the test is right \u2014 kept failing on purpose"),staleBecause:d.object({requirement:ce.describe("the requirement or clause id the change deliberately alters"),line:ce.describe("path:line (or path) of the application code the change altered that makes this test's old expectation wrong")}).optional().describe("for an existing test you updated or deleted: why it is out of date"),staleOnBase:d.boolean().optional().describe("for an existing test that fails: true when it fails the same way on the base branch because its own expectation is wrong (the app there does what it should), so this change did not make it wrong. Not when the base app's own bug fails it: that is an existing defect. Leave it as it is (unchanged): its failure is the test's own"),result:d.object({exit:d.number().nullable().describe("exit code of your last run of this file; null if it could not be run"),cases:d.array(d.object({case:ce,status:d.nativeEnum(pr),runtimeTargets:Wl.optional().describe("HTTP(S) URLs this case actually exercised in its current run, from its request or browser evidence; omit for local in-process/mocked checks, never list the shared app merely because it is configured"),defect:d.boolean().optional().describe("for a failing case: true when the app is wrong and the test is right; false when the test is at fault and you could not fix it"),testProblem:pg.optional().describe("for a failing case marked defect: false: what in the test is at fault"),failure:d.string().optional().describe("for a failing case: the runner's failure for it as printed (the error and the line it was raised at), not a summary"),cause:d.string().optional().describe("for a case you keep as a defect: path:line of the application code that makes it fail"),requires:d.string().optional().describe("for a case you keep as a defect: the words of the PR description, a requirement or clause of the plan, or the code a finding's keeps names, that state what its failing check expects, quoted exactly")})).describe("one entry per covered case, from the runner's own output"),details:d.string().optional().describe("what failed and why, or why it was not run"),noCases:d.string().optional().describe("for a failed run whose runner reported none of this file's tests (it failed to compile, import or collect): why")}),assertions:d.array(d.object({case:ce,evidence:ce})).optional().describe("per covered case, the assertion line that checks its expected outcome"),functions:d.array(d.object({name:ce.describe("the test function as the runner names it within its file, without the file (test_x, TestClass::test_x, TestSuite/TestCase)"),cases:d.array(ce).describe("the plan case ids it checks"),testProblem:pg.optional().describe("for a function that fails because of the test itself, while another function keeps a case it checks as a defect: what in it is at fault")})).optional().describe("for a file you added or updated: each test function in it and the plan case ids it checks"),skyramp:d.object({draft:d.union([d.string(),d.array(d.string())]).optional().describe("the draft path the Skyramp helper returned for this test, or each path when the test was made from several drafts"),handWritten:d.string().optional().describe("why it is written by hand: the helper call you made and what it returned")}).optional().describe("only for a test of a case the Skyramp API block lists: where it came from"),context:d.array(Mx).optional().describe("what the test sets up outside its own process that another test could run into: data it creates in the app, a Skyramp mock, an env override; omit when none"),isolatedRun:ce.optional().describe("for a test with a context: the command, from its checkout's root and without a shell, that runs only this file"),ci:p2.optional().describe("for a file you added or updated: whether the repo's CI will run it, and how you know"),run:Cu.optional().describe(`for a file in ${bu}, added, updated or re-run: how the run executes only this file's tests, with the repository's own runner and the report it writes (junit, trx or jest-json to ${sn}, or go-test-json); Testbot runs it before write ends and re-runs the tests with it`)}),XAe=o(e=>{if(!e||typeof e!="object")return e;let{test:t,...n}=e;return typeof t=="string"&&t.trim()&&n.tests===void 0?{...n,tests:[t]}:e},"oneTestIsTests"),epe=d.preprocess(XAe,d.object({description:ce.describe("what is wrong and how to reproduce it: endpoint or page, input, what you got vs what was expected"),severity:d.nativeEnum(la).optional(),sourceFile:d.string().optional().describe("the app file at fault"),sourceLine:d.number().optional(),tests:d.array(ce).optional().describe("every test file that fails because of it: a defect several tests show is one issue"),finding:d.string().optional().describe("the plan's finding id, when it is one"),requirements:d.array(ce).optional().describe("the plan's requirement or clause ids it violates")})),d_e=d.object({schemaVersion:d.literal(1),tests:d.array(KAe),notWritten:d.array(d.object({case:ce,reason:ce,coveredBy:d.object({file:ce.describe("the test file, relative to the working checkout; prefix a related checkout as for tests[].file"),name:ce.describe("the test function as the runner names it within its file, without the file (test_x, TestClass::test_x, TestSuite/TestCase)")}).optional().describe("only for an existing test triage independently linked to this exact case: its exact runner name (including class or describe titles). Testbot must finish re-running it with every result passed. If your own test covers the case, include the case in its covers and function cases instead")})).describe("every plan case no test covers, and why"),journeys:d.array(sy).optional().describe("one entry per planned user journey: the browser test that walks it end to end"),lint:d.object({command:d.string(),clean:d.boolean()}).optional().describe("the linter/formatter you ran on your test files, if the repo has one: the exact command, with its file paths (Testbot re-runs it)"),dependenciesAdded:d.array(d.object({package:ce,manifest:ce.describe("the manifest file's path relative to its checkout (e.g. package.json, pom.xml or pyproject.toml), and nothing else; name another checkout in repository"),repository:ce.optional().describe("owner/repo of the manifest's checkout; omit for the repo under test"),reason:ce.optional().describe("why the test must run inside the application's own test environment, so its manifest had to change \u2014 required for every entry")})).optional().describe("every package you added to an APPLICATION manifest (an exception, surfaced in the report); never the Testbot test package's own"),supportFiles:d.array(ce).optional().describe("every file that is not a test you created or changed for your tests, which they need to compile or run (a helper module, page object, fixture, or a snapshot the runner wrote for them), named as you name a test; Testbot delivers only the tests you list and the files under supportFiles"),ciNotes:d.string().optional().describe("for each test whose ci says the repo's CI will not run it: the test, and the exact change the author must make for CI to run it"),commit:d.object({message:ce.describe("subject line at most 72 characters, following the repository's commit-message checks"),prTitle:ce.describe("at most 72 characters, following the repository's PR-title checks"),prBody:ce.describe("what the tests cover and what they found")}),report:d.object({summary:ce.describe("1-2 sentences for the PR author: does the change do what it says?"),issues:d.array(epe).describe("every defect the tests found"),nextSteps:d.array(d.string()),noTests:d.array(d.object({repository:ce,reason:ce.max(4096)})).max(1e3).optional().describe("each Change Set repository where no test was added or updated: its owner/repo and why, naming the other repository when its tests went there"),notesDeviation:d.string().trim().max(4096).optional().describe("when the Target notes say where tests go and a test you added went elsewhere: where it went, and why; omit otherwise")})});var A_e={added:"place",updated:"update",deleted:"delete",unchanged:"verify"};var y2=(i=>(i.Requirement="requirement",i.PrDescription="pr_description",i.Code="code",i))(y2||{}),qt=d.string().trim().min(1),tpe=d.object({expectation:qt.max(300).describe("the behavior this assertion pins, in words"),source:d.nativeEnum(y2),expected:qt.max(200).describe("the exact value or outcome asserted, as the test asserts it")}),npe=d.object({file:qt.describe("path of the NEW test file you wrote, relative to its repository"),repository:qt.optional().describe("owner/repo the file lives in, when the run has several checkouts; omit for the working checkout"),framework:qt.describe("the framework the repository runs this file with: pytest, jest, vitest, node-test, or the name of any other"),run:Cu.optional().describe(`for ${bu}: how the run executes only the tests in names, with the repository's own runner writing JUnit XML to {junit}`),covers:d.array(qt).length(1).describe("the ONE behavior id, or defect id, from the plan that the tests in names provide evidence for; a file covering several is listed once per id"),names:d.array(qt).min(1).describe("the test functions/cases in the file that provide evidence for that behavior, as the framework names them"),assertions:d.array(tpe).min(1)}),UA=(n=>(n.Updated="updated",n.Deleted="deleted",n))(UA||{}),m2=300,rpe=d.object({file:qt.describe("path of the EXISTING test file you updated or deleted, relative to its repository"),repository:qt.optional().describe("owner/repo the file lives in, when the run has several checkouts; omit for the working checkout"),change:d.nativeEnum(UA),staleBecause:d.object({requirement:qt.describe("the requirement or clause id the change deliberately alters"),line:qt.describe("path:line (or path) of the application code the change altered that makes this test's old expectation wrong")}).optional().describe("for an existing test you updated: why it is out of date"),reason:d.preprocess(e=>typeof e=="string"?e.trim().slice(0,m2):e,qt.max(m2)).describe("what the change deliberately altered that made the test wrong")}),Jx=d.object({schemaVersion:d.literal(1),tests:d.array(npe),maintained:d.array(rpe).optional().describe("existing tests the change made stale that you updated or deleted; omit when there were none"),defectsNotTested:d.array(d.object({id:qt,reason:qt.max(300)})).optional().describe("defects the plan found that no in-process test can reach, each with why; omit when every defect has a test"),journeys:d.array(sy).optional().describe("one entry per planned user journey: the in-process test that walks it end to end"),journeysNotWritten:d.array(d.object({journey:qt,missing:qt.transform(e=>e.length>300?`${e.slice(0,299)}\u2026`:e)})).optional().describe("a planned journey no in-process test can walk here, with what it needs that is missing; it is reported as not covered"),lint:d.object({command:d.string(),clean:d.boolean()}).optional().describe("the linter/formatter you ran on your test files, if the repository has one you can run; omit otherwise"),commitMessage:qt.optional().describe("the commit message for your tests: a subject line of at most 72 characters, then what they cover")});var FA="generate-unit.json";function spe(e){let{value:t,error:n}=$t(e);if(n)return{errors:[n]};let{value:i,errors:r}=mn(Jx,t);return r.length?{errors:r}:{output:i,errors:[]}}o(spe,"parseGenerateUnitText");function ope(e){return spe(e.stdout)}o(ope,"parseGenerateUnitFromSession");var nNe=$n("generate-unit-schema",(e,t)=>ope(t));var ly=String.raw`(?:node:)?(?:http|https|http2|net|tls|dgram)`,rNe=[[/\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+["']${ly}["']|\bimport\s+["']${ly}["']|require\(\s*["']${ly}["']\s*\)|\bimport\(\s*["']${ly}["']\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 wNe=new Set(["targeted_unit","existing_evidence_sufficient"]);var fpe="triage.json";var TUe=new Set(["existing_evidence","unaffected","existing_unit","new_unit","runtime"]),DUe={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 gpe(e){let{value:t,error:n}=$t(e);if(n)return{errors:[n]};let{value:i,errors:r}=mn(TA,t);return r.length?{errors:r}:{triage:i,errors:[]}}o(gpe,"parseTriageText");function hpe(e){return gpe(e.stdout)}o(hpe,"parseTriageFromSession");var _Ue=$n("triage-schema",(e,t)=>hpe(t));function mpe(e){let t=e.inputs?.pipeline;return t?e.state.stages[t==="two-step"?"plan":"triage"]:e.state.stages.triage??e.state.stages.plan}o(mpe,"triageDecider");function Yx(e){if(mpe(e)?.status==="passed")return jo(w2.join(e.outputsDir,fpe))}o(Yx,"readTriage");function Wx(e){return K1(RR(e.inputs,Ve(e,`${mA}.json`),Yx(e)?.sutRequired))}o(Wx,"revisionBlockReason");var NUe=new Set(["deploy","recommend","generate","generate-ui","adapt","generate-unit","native-run","finalize","deliver"]);var Pr=Se(require("fs")),Vs=Se(require("path")),mq=Se(require("crypto")),yq=require("child_process");var Zx=require("child_process"),Bu=Se(require("fs")),B2=Se(require("os")),py=Se(require("path"));var ype={onPath:o(e=>(0,Zx.spawnSync)("sh",["-c",`command -v ${e}`],{stdio:"ignore"}).status===0,"onPath"),run:o((e,t)=>(0,Zx.spawnSync)(e[0],e.slice(1),{cwd:t,stdio:"ignore",timeout:6e4}).status??1,"run")},Ay={cleanup:o(()=>{},"cleanup")},Epe=new Set(["pnpm","yarn"]);function k2(e,t=B2.tmpdir(),n=ype){if(process.platform==="win32")return Ay;try{let i=Bx(e);if(!Epe.has(i)||n.onPath(i)||!n.onPath("corepack"))return Ay;Bu.mkdirSync(t,{recursive:!0});let r=Bu.mkdtempSync(py.join(t,"testbot-pm-")),s=o(()=>Bu.rmSync(r,{recursive:!0,force:!0}),"cleanup");return n.run(["corepack","enable","--install-directory",r,i],e)!==0?(s(),Ay):{dir:r,cleanup:s}}catch{return Ay}}o(k2,"packageManagerShims");function S2(e,t=process.env){return e.dir?{...t,PATH:[e.dir,t.PATH].filter(Boolean).join(py.delimiter)}:t}o(S2,"withShims");var jA=require("crypto");function Jt(e){let t=Math.max(0,...(e.match(/`+/g)??[]).map(r=>r.length)),n="`".repeat(t+1),i=e.startsWith("`")||e.endsWith("`")?" ":"";return`${n}${i}${e}${i}${n}`}o(Jt,"codeSpan");Ac();var oFe=5*6e4,aFe=12*6e4,cFe=2*6e4;var gFe=["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(`
|
|
159
|
-
`);var
|
|
157
|
+
`,{mode:493})}catch{return}return`bash ${$x(t)}`}}o(xx,"scriptedCommand");function $x(e){return`'${e.split("'").join("'\\''")}'`}o($x,"shQuote");function Tx(e){return Dx(e)&&QR(e).length===0&&xR(e.inputs?.sharedEnvironment).length===0}o(Tx,"sutIsHealthy");function Dx(e){let t=Mde(e);if(!t&&e.state.stages.deploy?.status!=="passed")return!1;let n=Ve(e,"deploy.json");return n?Pde(n):!t}o(Dx,"sutCameUp");function Pde(e){return e?.outcome==="clean"||e?.outcome==="recipe-drift"}o(Pde,"deployCameUp");function Mde(e){let t=e.state.stages.plan,n=e.state.stages.deploy;return!(e.inputs?.pipeline?e.inputs.pipeline==="two-step":!n)||t?.status!=="passed"?!1:!n||n.updatedAt<=t.updatedAt}o(Mde,"broughtUpByPlan");var $0e=10*6e4;var iy=(r=>(r.RestApi="rest-api",r.Frontend="frontend",r.FullStack="full-stack",r.Other="other",r))(iy||{}),la=(r=>(r.Critical="critical",r.High="high",r.Medium="medium",r.Low="low",r))(la||{}),da=(i=>(i.Suspected="suspected",i.Latent="latent",i.Refuted="refuted",i))(da||{}),Ux=(i=>(i.Skyramp="skyramp",i.External="external",i.Unknown="unknown",i))(Ux||{}),Fx=(r=>(r.Cascade="cascade",r.Restrict="restrict",r.Orphan="orphan",r.Unknown="unknown",r))(Fx||{}),pi=(r=>(r.RequirementReference="requirement-reference",r.Spec="spec",r.PrDescription="pr-description",r.CouldBreak="could-break",r))(pi||{}),Xe=d.string().trim().min(1),Iu=Xe.describe("file:line"),Yz=o(e=>Xe.refine(t=>t.length<=400,t=>({message:`is ${t.length} characters, over the 400 cap \u2014 ${e}`})),"cap400"),RA=Xe.optional().describe('multi-repo only: the OTHER checkout this lives in \u2014 its "owner/repo" slug, or the directory name if the run discovered it; omit for the working checkout'),Nx=d.object({method:Xe,path:Xe,service:d.string().optional(),evidence:Iu,repository:RA}),Vde=d.object({id:Xe.describe("short-slug, e.g. R9"),statement:Xe.max(400,"exceeds 400 characters \u2014 state the requirement, do not paste the spec section").describe("a testable obligation, not a summary"),source:d.nativeEnum(pi).describe("spec outranks pr-description when both state it"),evidence:Xe.describe("spec: file:line or a section locator. pr-description: the quoted phrase it comes from.")}),zde=d.object({id:Xe.describe("short-slug"),statement:Xe.max(400,"exceeds 400 characters \u2014 state the behaviour, do not paste the code").describe("what the change makes true"),surface:Xe.describe("METHOD /path, or a component/page name"),evidence:Xe.describe("file:line from the diff that introduces it"),repository:RA,satisfies:d.array(Xe).optional().describe("requirement ids (from `requirements`) this behaviour correctly implements \u2014 a requirement met only in part is ALSO named by the finding that shows the rest (conflictsWith)")}),qde=d.object({id:Xe.describe("short-slug"),file:Xe,line:d.number().optional(),claim:Yz("shorten it to the one sentence that states the defect, and move the supporting detail into `evidence`"),severity:d.nativeEnum(la),evidence:Yz("cite the file:line and the one line that shows it, rather than reproducing the surrounding code").describe("quoted diff/code line"),status:d.nativeEnum(da),repository:RA,conflictsWith:d.array(Xe).optional().describe("requirement ids (from `requirements`) this defect contradicts or leaves unimplemented \u2014 a lower-precedence source (the diff, or the PR description) lost")}),Jde=d.object({name:Xe,language:d.string().optional(),framework:d.string().optional(),evidence:Iu,repository:RA}),Hde=d.object({dir:Xe,framework:d.string().optional(),kind:d.nativeEnum(Ux),evidence:Iu,repository:RA}),Yde=d.object({from:Xe,to:Xe,onDelete:d.nativeEnum(Fx),evidence:Iu}),Wde=d.object({entity:Xe,field:Xe,values:d.array(d.string()),evidence:Iu}),Zde=d.object({entities:d.array(d.object({name:Xe,evidence:Iu})),references:d.array(Yde).describe("INBOUND references \u2014 what still points at an entity when it is deleted"),stateFields:d.array(Wde)}),Px=d.object({schemaVersion:d.literal(1),repository:d.object({path:Xe.describe("absolute repo path"),currentBranch:Xe,baseBranch:Xe}),project:d.object({type:d.nativeEnum(iy),primaryLanguage:Xe,languages:d.array(d.string()),frameworks:d.array(d.string())}),services:d.array(Jde),infrastructure:d.object({containerized:d.boolean(),hasDockerCompose:d.boolean(),composeFiles:d.array(d.string()),hasCiCd:d.boolean()}),diff:d.object({changedFiles:d.array(d.string()).describe("as git reports them; a file in another checkout may carry that repo's name"),nonApplicationOnly:d.boolean(),summary:Xe.describe("\u2264400 chars")}),endpoints:d.object({new:d.array(Nx),modified:d.array(Nx),removed:d.array(Nx)}),existingTests:d.object({locations:d.array(Hde)}),entityMap:Zde,requirements:d.array(Vde).describe("from a spec (attached or linked) and/or the PR description; empty when neither states a testable obligation"),behaviors:d.array(zde),findings:d.array(qde),unexamined:d.array(d.string()).describe("files or areas outside this change you did not open"),summary:Xe.describe("one paragraph on what this change does and its test-relevant risk")});var tAe=d.object({route:d.string().describe('the page this step happens on, e.g. "/products/:id"'),action:d.string().describe('what the user does there, through the UI, e.g. "clicks Add to cart"'),clauses:d.array(d.string()).optional().describe("the plan clause ids this step exercises"),check:d.string().optional().describe("what the user then sees that shows the step worked; the test asserts it")}),xA=(n=>(n.InProcess="in-process",n.Browser="browser",n))(xA||{}),Wz=(i=>(i.Spec="spec",i.PrDescription="pr-description",i.Inferred="inferred",i))(Wz||{}),Zz=d.object({id:d.string().describe('e.g. "J1"'),name:d.string().describe(`the flow in a user's words, e.g. "buy a product with a coupon"`),entry:d.string().describe("the route the user starts the flow on: the app's normal starting page for it, never a deep link into its middle"),steps:d.array(tAe).describe("every step, in order, from the entry page to the outcome: at least two"),outcome:d.string().describe("what the user sees at the end that shows the flow worked: every part of it"),finishes:d.string().optional().describe('the user action that completes the task, verb first, e.g. "places the order"; the journey walks on to it'),kind:d.nativeEnum(xA).optional().describe("in-process when the repo's in-process tests (components, app routes) can walk the whole flow and check it; else browser"),source:d.nativeEnum(Wz).optional().describe("spec or pr-description when one describes this flow (quote it under evidence), else inferred"),evidence:d.string().optional().describe("for spec or pr-description: its words that describe the flow"),testFile:d.string().describe("the browser test file it goes in, beside the repo's existing e2e tests")}),sy=d.object({journey:d.string().describe("the plan's journey id"),file:d.string().describe("the browser test file that walks it"),brokeAt:d.object({step:d.number().int().describe("the 1-based step whose check failed first"),expected:d.string(),actual:d.string().describe("what the app did instead, from the runner's output"),notReached:d.array(d.number().int()).optional().describe("later steps the test could not get to")}).optional().describe("only when the journey's test failed on a check: where"),test:d.string().describe("the title of the one test in that file that walks it end to end")});var z0e=Object.fromEntries([...["ts","tsx","mts","cts","js","jsx","mjs","cjs"].map(e=>[e,"node"]),...["java","kt","kts","groovy","scala"].map(e=>[e,"jvm"]),["py","python"],["go","go"]]);var q0e=["stale_test","open_question"],J0e=["low","medium","high","critical"];var Kz=String.raw`(?:\[[^\]]*\]|\([^)]*\))`,nAe=String.raw`(?:["'\u201c\u2018\x60]|\*{1,2})?[^\s:"'\u201c\u201d\u2018\u2019\x60*()[\],]+(?:["'\u201d\u2019\x60]|\*{1,2})?`,Xz=String.raw`(?:${Kz}|${nAe}(?:\s*${Kz})?)`,e2=String.raw`(?:\s*:|\s+[\u2014\u2013-])`,Z0e=new RegExp(String.raw`^\s*(?:${Xz}(?:,\s*${Xz})*(?::L?\d+(?:[-\u2013]\d+)?${e2}?|${e2})|\[[^\]\s]+\]|\([^)\s]+\))\s+`);var $A=(n=>(n.Skyramp="skyramp",n.Llm="llm",n))($A||{}),qi=d.string().trim().min(1),rAe=d.object({case:qi.describe("recommend id this assertion enforces"),evidence:qi.describe("the exact assertion line from the file that checks that case's observable")}),Mx=d.object({kind:d.nativeEnum(hg).describe("seed: data the test creates in the app; runtime_mock: a mock on a Skyramp worker, which other tests reach too; env_override: an env value the app runs with. A stub inside the test's own process, such as a browser page's route, is none of these"),target:qi.describe("the dependency, endpoint or data it affects"),mechanism:d.nativeEnum(mg).describe("test_code: the test applies and undoes it; skyramp_mocker: a mock the test applies on a Skyramp worker; recipe_override: the mocker cannot reach the dependency (its URL is fixed in the build)"),detail:qi.describe("what it sets up"),worker:qi.optional().describe("skyramp_mocker: host:port of the worker the test applies the mock to (default localhost:35142)"),cleanup:qi.optional().describe("seed: a command that removes the data when the test does not, run as written and without a shell: give real values, not a placeholder such as <id>, single-quote an argument that holds shell syntax, or put the logic in a script in the repository and run that")}),iAe=d.object({file:qi.describe("staged path under .skyramp/staged/"),source:d.nativeEnum($A),language:qi,covers:d.array(d.string()).min(1,"must be a non-empty array of recommend ids").describe("recommend ids this test covers"),assertions:d.array(rAe).min(1,"must be a non-empty array").describe("one per case covered, citing the real line"),context:d.array(Mx).optional().describe("what the test sets up against the running app, in order: data it seeds, Skyramp mocks it applies, env overrides; omit when none")}),Ox=d.object({schemaVersion:d.literal(1),tests:d.array(iAe),deferredUi:d.array(d.string()).describe("recommend ui ids left for the UI stage (generate) \u2014 [] for generate-ui"),summary:qi.describe("one paragraph")});var Ls=Se(require("fs")),vu=Se(require("path")),i2=require("child_process");var sn="{junit}",oy=(r=>(r.Junit="junit",r.Trx="trx",r.GoTestJson="go-test-json",r.JestJson="jest-json",r))(oy||{}),Lx=(t=>(t.Minitest="minitest",t))(Lx||{}),t2=d.string().trim().min(1),Cu=d.object({cwd:t2.describe('repo-relative directory the command starts in ("." for the root)'),argv:d.array(t2).min(1).describe(`the command as separate arguments, run without a shell; for a junit or trx report an argument or env value holds ${sn}, where the report is written (not for Maven or Gradle, whose build writes its own)`),env:d.record(d.string(),d.string()).optional().describe("plain test or reporter settings beyond the repository's CI test job (RAILS_ENV=test, PLAYWRIGHT_JUNIT_OUTPUT_FILE={junit}); never a credential, PATH, or a tool's install path"),report:d.object({format:d.nativeEnum(oy).describe(`junit (JUnit XML to ${sn}), trx (to ${sn}), jest-json (Jest's --json or Vitest's --reporter=json, --outputFile=${sn}), or go-test-json (go test -json on the command's output)`),reporter:d.nativeEnum(Lx).optional().describe("a reporter Testbot loads for a runner that writes no report: minitest")}).optional().describe("the report the command writes; junit when omitted")});var bu="a framework other than pytest, jest, vitest and node --test (go test, rails test, mvn, dotnet test), or one the repository's test script runs through another command (ng test, nx test)",sTe=`pytest, Jest, Vitest and node --test tests run as the run already knows them, unless the repository's test script runs them through another command (ng test, nx test), which may be the only one that compiles them. A test in any other framework, or one run that way, also gives "run": the repository's own command for only those tests, from the directory the repository runs it in, as separate arguments without a shell. Its "report" says what the runner writes: junit (JUnit XML to ${sn} in the reporter's argument or env setting), trx (a TRX file to ${sn}, which every dotnet test writes with its built-in logger), jest-json (Jest's --json --outputFile=${sn}, or Vitest's --reporter=json --outputFile=${sn}: built in, no reporter package), or go-test-json (go test -json, read from the command's output). A Maven or Gradle command names no ${sn}: its build writes JUnit XML to its own report directory, which the run reads. Use a reporter the repository already has, or one of those; a reporter or converter the command fetches is the version the repository pins, or else its latest release (an older one may not build with the repository's toolchain). For minitest, which writes none, give report.reporter "minitest" and the run fills ${sn} itself. A setting the tests or reporter read goes in "env" (RAILS_ENV=test, or PLAYWRIGHT_JUNIT_OUTPUT_FILE=${sn} with playwright test --reporter=junit): the run sets it, so never wrap the command in a shell to set one. The run replaces ${sn} in argv and env with its report path, executes the command, and reads that report.`;var Os=(r=>(r.ExistingEvidenceSufficient="existing_evidence_sufficient",r.TargetedUnit="targeted_unit",r.RuntimeRequired="runtime_required",r.BlockedPreflight="blocked_preflight",r))(Os||{}),Ji=(s=>(s.ExistingEvidence="existing_evidence",s.Unaffected="unaffected",s.ExistingUnit="existing_unit",s.NewUnit="new_unit",s.Runtime="runtime",s))(Ji||{}),jx=(n=>(n.Repository="repository",n.Testbot="testbot",n))(jx||{}),Gx=(i=>(i.Identified="identified",i.Passed="passed",i.Failed="failed",i))(Gx||{}),Fn=d.string().trim().min(1),sAe=d.string().regex(/^[a-z0-9][a-z0-9-]*$/,"must be a short lowercase slug").describe("short-slug");var oAe=d.object({id:sAe,source:d.nativeEnum(jx),kind:d.nativeEnum(bs),outcome:d.nativeEnum(Gx),summary:Fn.max(400).describe("one line: what it shows"),tests:d.array(Fn).optional().describe("source repository: the existing tests, as repo-relative paths, optionally path::test-name"),repository:Fn.optional().describe("source repository: owner/repo the tests live in, when the run has several checkouts; omit for the working checkout"),command:Fn.optional().describe("source testbot: the exact command you ran, as you ran it"),run:Cu.optional().describe(`source repository, for tests in ${bu}: how the run executes the whole of each of these test files, all of them in one command, never narrowed to the named tests and never only listed, with the repository's own runner writing JUnit XML to {junit}. A test is credited to a file only by its name or by a report that names the file`)}),aAe=d.object({behaviorId:Fn.describe("an id from analyze's behaviors"),mechanism:d.nativeEnum(Ji),evidenceIds:d.array(Fn).default([]).describe("existing_evidence: the ci-<n> or evidence ids that establish it; existing_unit: the evidence id naming the tests to run"),covers:d.string().trim().optional().describe('new_unit / runtime: the missing evidence this obtains, e.g. "the boundary the change moved"; unaffected: why the change cannot reach it, citing path:line')}),Vx=(i=>(i.Browser="browser",i.RunningApp="running-app",i.Outside="outside",i))(Vx||{}),cAe=d.object({behaviorId:d.string().trim().optional().describe("an id from analyze's behaviors, when it is about one"),missing:Fn.max(600).describe("the evidence that is required and cannot be obtained in this run"),needs:d.nativeEnum(Vx).optional().describe("what that evidence needs: browser (only a real browser shows it), running-app (only the running app or its server shows it: its real requests, sign-in and permissions, what it saves), or outside (something the running app here could not give either: a third-party service it calls, hardware)")}),uAe=d.object({file:Fn.describe("the changed file the failure is in"),repository:Fn.optional().describe("owner/repo the file is in, when the run has several checkouts; omit for the working checkout"),reason:Fn.max(300).describe("what prerequisite the change fails"),evidence:Fn.max(400).describe("the error line, quoted")}),lAe=d.object({behaviorId:Fn.describe("an id from analyze's behaviors"),reason:Fn.max(600).describe("\u2264600 characters: why this change leaves the behavior's result as it was, citing the unchanged line that decides it (path:line)")}),TA=d.object({schemaVersion:d.literal(1),decision:d.nativeEnum(Os),evidence:d.array(oAe).describe("evidence this session found or produced; CI results are the ci-<n> items and are not restated here"),plan:d.array(aAe).describe("how each changed behavior's evidence is obtained"),gaps:d.array(cAe),outOfScope:d.array(lAe).optional().describe("behaviors analyze found that this change neither changes nor states"),blocked:uAe.optional().describe("only for blocked_preflight"),rationale:Fn.max(1200).describe("\u22641200 characters: why this evidence is enough, or what it still lacks \u2014 the scope you chose and why")});function DA(e){let t=Ve(e,"recommend.json");if(!t||!Array.isArray(t.generate)||!Array.isArray(t.maintenance))return;let n=t;return{...n,maintenance:n.maintenance.map(({repository:i,...r})=>({...r,test:r.test.trim().replace(/^\.\//,""),...i?.trim()?{repository:i.trim()}:{}}))}}o(DA,"readRecommend");function fAe(e){return mn(Ox,e).errors}o(fAe,"validateGenerateOutput");function gAe(e,t=[]){let{value:n,error:i}=$t(e,t);if(i)return{errors:[i]};let r=fAe(n);return r.length>0?{errors:r}:{generate:n,errors:[]}}o(gAe,"parseGenerateText");function ay(e,t=[]){return gAe(e.stdout,t)}o(ay,"parseGenerateFromSession");function hAe(e){return e.generate.filter(t=>t.type!=="ui").map(t=>t.id)}o(hAe,"backendCases");function s2(e){return e.generate.filter(t=>t.type==="ui").map(t=>t.id)}o(s2,"uiCases");var cy={backend:{stage:"generate",cases:hAe,noRecommendCoverage:"recommend.json missing or malformed \u2014 cannot check coverage",noRecommendIntent:"recommend.json missing or malformed \u2014 cannot check intent",uncovered:o(e=>`recommend case "${e}" is not covered by any generated test`,"uncovered"),unknownCovered:o(e=>`test covers unknown recommend id "${e}"`,"unknownCovered"),unasserted:o(e=>`case "${e}" has no verified assertion enforcing its expected_observable`,"unasserted"),usedCodegen:O1,codegenHint:"These tests were hand-written. Skyramp codegen (skyramp_contract_test_generation / skyramp_integration_test_generation) was available but not used \u2014 it computes valid sample data and response correlations. Prefer scaffolding with it and then refining, especially for the failures above."},ui:{stage:"generate-ui",cases:s2,noRecommendCoverage:"recommend.json not found \u2014 cannot check UI coverage",noRecommendIntent:"recommend.json not found \u2014 cannot check UI intent",uncovered:o(e=>`UI case "${e}" is not covered by any generated UI test`,"uncovered"),unknownCovered:o(e=>`test covers "${e}" which is not a recommend UI case`,"unknownCovered"),unasserted:o(e=>`UI case "${e}" has no verified assertion enforcing its expected_observable`,"unasserted"),usedCodegen:L1,codegenHint:"This UI test was hand-authored. Skyramp UI codegen (skyramp_ui_test_generation) was available but not used. Prefer scaffolding with it and then refining, especially for the failures above."}},OTe=$n("generate-schema",(e,t)=>ay(t,e.secretValues));function mAe(e){let t=cy[e];return{name:`${t.stage}-coverage`,verify(n,i){let{generate:r,errors:s}=ay(i,n.secretValues);if(!r)return Lt(this.name,s);let a=DA(n);if(!a)return Lt(this.name,[t.noRecommendCoverage]);let c=new Set(r.tests.flatMap(p=>p.covers)),u=[],l=t.cases(a);for(let p of l)c.has(p)||u.push(t.uncovered(p));let A=new Set(e==="ui"?l:a.generate.map(p=>p.id));for(let p of c)A.has(p)||u.push(t.unknownCovered(p));if(e==="backend"){let p=new Set(r.deferredUi),g=new Set(s2(a));for(let h of g)!p.has(h)&&!c.has(h)&&u.push(`UI case "${h}" is neither covered nor deferred to the UI stage`);for(let h of p)g.has(h)||u.push(`deferredUi lists "${h}" which is not a UI case`)}return u.length===0?{name:this.name,passed:!0}:Lt(this.name,u)}}}o(mAe,"generateCoverageGateFor");function yAe(e){let t=cy[e];return{name:`${t.stage}-intent`,verify(n,i){let{generate:r,errors:s}=ay(i,n.secretValues);if(!r)return Lt(this.name,s);let a=DA(n);if(!a)return Lt(this.name,[t.noRecommendIntent]);let{asserted:c,errors:u,badFiles:l}=BAe(r,n.inputs.repositoryPath),A=u.length;for(let g of t.cases(a))c.has(g)||u.push(t.unasserted(g));if(u.length===0)return{name:this.name,passed:!0};let p=Lt(this.name,u);return A>0&&A===u.length&&l.size>0?{...p,droppable:[...l]}:p}}}o(yAe,"generateIntentGateFor");function EAe(e){let t=cy[e];return n=>{if(!n.inputs.skyrampMcp?.command||e==="backend"&&!Tx(n))return;let i=vu.join(n.outputsDir,`${t.stage}-stream.ndjson`);if(!(!Ls.existsSync(i)||t.usedCodegen(i)))return j1(i)?t.codegenHint:"Skyramp codegen tools were configured but the MCP server did not connect this session, so they were not available. Hand-authoring was the only option; this is an environment problem, not yours."}}o(EAe,"codegenRetryHintFor");var LTe=mAe("backend"),jTe=yAe("backend"),GTe=EAe("backend");var n2=o(e=>e.replace(/\s+/g,""),"squeeze");var zx={python:[/\bassert\s*[({\w"'`]/g,/\bpytest\.raises\s*\(/g,/\bself\.assert\w*\s*\(/g],typescript:[/\bexpect\s*\(/g,/\.should\b/g,/\bassert\s*[.(]/g],go:[/\bt\.(Error|Errorf|Fatal|Fatalf|Fail|FailNow)\s*\(/g,/\b(assert|require)\.\w+\s*\(/g],java:[/\bassert\w*\s*\(/g,/\bassertThat\s*\(/g],ruby:[/\bexpect\s*[({]/g,/\bassert\w*\b/g,/\.should\b/g]};for(let[e,t]of[["javascript","typescript"],["kotlin","java"]])zx[e]=zx[t];function IAe(e,t){if(e.includes(dd(t))||n2(e).includes(n2(t)))return!0;let n=t.split(/\r?\n/).map(i=>i.trim()).filter(i=>i&&!/^(\/\/|#|\*|\/\*)/.test(i));return n.length>0&&n.every(i=>e.includes(dd(i)))?!0:wAe(e,t)}o(IAe,"evidenceFound");var CAe=/\bassert\w*\b|\bexpect\s*\(|\.should\b|\brequire\s*\(/i,bAe=12,vAe=/,\s*\(\s*#|,\s*f?["'`]|\s+#\s|\s+\/\/|\s*\((?:line|lines|at line)\b|\s*,\s*$/i;function wAe(e,t){let n=t.split(/\s*;\s*|\s*\.\.\.\s*|\r?\n/),i=0;for(let r of n){let s=CAe.exec(r);if(!s)continue;let a=r.slice(s.index),c=vAe.exec(a);if(c&&(a=a.slice(0,c.index)),a=dd(a).replace(/[,\s]+$/,""),a.length<bAe||!e.includes(a))return!1;i++}return i>0}o(wAe,"annotatedAssertionFound");function BAe(e,t){let n=new Set,i=[],r=new Set;for(let s of e.tests){let a=vu.resolve(t,s.file);if(!Ls.existsSync(a))continue;let c=dd(Ls.readFileSync(a,"utf-8"));for(let u of s.assertions??[]){if(!IAe(c,u.evidence)){i.push(`assertion evidence for "${u.case}" not found in ${s.file} \u2014 cite the real assertion line`),r.add(s.file);continue}s.covers.includes(u.case)?n.add(u.case):(i.push(`assertion cites case "${u.case}" not in that test's covers[]`),r.add(s.file))}}return{asserted:n,errors:i,badFiles:r}}o(BAe,"verifiedAssertions");var kAe=/\.(spec|test)\.[cm]?[jt]sx?$/i;function o2(e){let t;try{t=(0,i2.execFileSync)("git",[...Ri,"status","--porcelain","--untracked-files=all"],{env:Xt(),cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]})}catch{return}let n=o(r=>/_scaffold/i.test(r)||Ad.test(r),"isTestLitter"),i=[];for(let r of t.split(`
|
|
158
|
+
`)){if(!r.trim()||r.length>1&&r[1]==="D")continue;let s=r.slice(3).trim(),a=s.indexOf(" -> ");if(a!==-1&&(s=s.slice(a+4).trim()),s=s.replace(/^"|"$/g,""),!s)continue;let c=s.replace(/^\.\//,"");c.startsWith(".skyramp/")||!n(c)||i.push(c)}return i}o(o2,"testLitter");function SAe(e){let t=cy[e],n=e==="ui";return{name:`${t.stage}-no-litter`,verify(i){let r=o2(i.inputs.repositoryPath);if(r===void 0)return{name:this.name,passed:!0};let s=r.filter(a=>kAe.test(a)===n);return s.length===0?{name:this.name,passed:!0}:Lt(this.name,[`${t.stage} left files outside .skyramp/ \u2014 move the staged test into .skyramp/staged/ and delete any codegen draft (e.g. *_scaffold.*): ${s.slice(0,6).join(", ")}`])}}}o(SAe,"noLitterGateFor");var VTe=SAe("backend");var xAe="write-stale-updates",$Ae={[xAe]:"stale test updates"};var _A=Se(require("fs")),Aa=Se(require("path"));function l2(e){return mn(kb,e).errors}o(l2,"validateAdaptOutput");function _Ae(e,t=[]){let{value:n,error:i}=$t(e,t);if(i)return{errors:[i]};let r=l2(n);return r.length>0?{errors:r}:{adapt:n,errors:[]}}o(_Ae,"parseAdaptText");var NAe="adapt-scratch",c2=`${NAe}/adapt-result.json`;function d2(e,t){let n=Aa.join(e.outputsDir,c2),i;try{i=_A.readFileSync(n,"utf-8")}catch{i=void 0}if(i!==void 0&&(e.secretValues??[]).some(a=>i.includes(a)))return{errors:[`${c2} contains a secret value (token / credential) \u2014 never write it anywhere`]};let r=_Ae(t.stdout,e.secretValues);if(r.adapt)return r;let s=i!==void 0?jo(n):void 0;return s!==void 0&&l2(s).length===0?{adapt:s,errors:[]}:r}o(d2,"parseAdaptFromSession");var IDe=$n("adapt-schema",d2);var A2=require("child_process");function qx(e){return UAe(e)??[]}o(qx,"statusEntries");function UAe(e){let t;try{t=(0,A2.execFileSync)("git",[...Ri,"status","--porcelain","-z","--untracked-files=all"],{env:Xt(),cwd:e,encoding:"utf-8",maxBuffer:16*1024*1024})}catch{return}let n=t.split("\0"),i=[];for(let r=0;r<n.length;r++){let s=n[r];if(s.length<4)continue;let a=s.slice(0,2);i.push({code:a,path:s.slice(3)}),(a[0]==="R"||a[0]==="C")&&r++}return i}o(UAe,"readStatusEntries");var xDe=2*1024*1024;var uy=d.string().trim().min(1),FAe=d.object({cwd:uy.describe(`directory the command starts in, relative to the test's checkout ("." for its root)`),argv:d.array(uy).min(1).describe("the command as separate arguments, run without a shell"),env:d.record(d.string(),d.string()).optional().describe("plain settings the listing needs beyond the CI step's own; never a credential or PATH")}),PAe=d.object({file:uy.describe("a file of the test's checkout, relative to its root"),line:uy.describe("a line of that file, quoted exactly from where its command starts to its end")}),p2=d.object({collected:d.boolean().describe("whether the repo's CI runs this test as it is"),steps:d.array(PAe).optional().describe("when collected: the line in a CI file that starts the tests, then each line it runs on the way to the test runner"),runner:d.string().optional().describe("when collected: the test runner the last of those lines starts, by the name that line and the list command both use"),list:FAe.optional().describe("when collected: a command that lists the tests that runner collects without running them; Testbot runs it, and its output must name this file"),why:d.string().optional().describe("when not collected: why the repo's CI will not run it")});var ce=d.string().trim().min(1),VAe=o(e=>{if(!e||typeof e!="object")return e;let t=e;return typeof t.skip=="string"&&t.skip.trim()&&(t.expected===void 0||t.expected===null)?{...t,expected:"(not tested)"}:e},"skippedNeedsNoExpected"),zAe=d.preprocess(VAe,d.object({id:ce.describe(`its requirement's id plus a letter, e.g. "R1a", "AC-3a"`),clause:ce.describe("one testable part of the requirement"),expected:ce.describe("the outcome the requirement calls for \u2014 taken from the requirement, never from what the code does"),skip:d.string().optional().describe("only when no test can check this clause here: why"),type:d.nativeEnum(Gi).optional().describe("the test that checks this clause: contract / integration (the API, or code called directly in-process: a function, hook or module) or ui (a page)"),target:d.string().optional().describe('its "METHOD /path", or the page / flow'),steps:d.string().optional().describe("what that test does; its expected outcome is this clause's"),finding:d.string().optional().describe("the finding id, when this clause's test also catches that defect (the defect still gets a case of its own)"),code:d.string().optional().describe("path:line of the code that decides this clause, when there is one; in another repo of the change, that repo's directory name then its path"),stated:d.string().optional().describe("the description's or spec's own words that state this clause, copied exactly, when they do"),mutates:d.boolean().optional().describe("true when its test changes state, in the test or its setup: an API POST, PUT, PATCH or DELETE, or a UI flow that submits, creates, edits or deletes"),browserOnly:d.boolean().optional().describe("true when its behaviour happens only in a browser: real clicks or keys driving page script, client-side sorting or filtering, script-driven DOM updates, focus, drag-and-drop, navigation, rendering that depends on CSS or JavaScript"),browserHarness:d.string().optional().describe("browserOnly, off the runtime path: the path of the repo's in-process browser suite its test goes in (e.g. a Django StaticLiveServerTestCase test that drives Selenium)"),quote:d.string().optional().describe("the words of the spec, plan, ticket, PR description or a test the change adds or edits that state this clause, copied exactly; a file of the repository: its path:line first. Leave it out when no source states it"),inferred:d.boolean().optional().describe("leave it out: Testbot sets it when no source states this clause (contracts/clause-grounding.ts)")})),g2=d.object({spec:d.string().optional().describe("file:line of a spec in the repository"),prDescription:d.boolean().optional().describe("or true when a pull request description says otherwise"),reference:d.string().optional().describe("or the key of an item the run was given, as listed"),says:ce.describe("what it says there, in its own words, copied exactly"),criterion:d.number().int().positive().optional().describe("an item's only: leave it out; Testbot numbers it")}).refine(e=>[!!e.prDescription,!!e.spec?.trim(),!!e.reference?.trim()].filter(Boolean).length===1,{message:`names no source, or more than one: give "spec" its file:line or "reference" an item's key, or set "prDescription", one of them; list each source as its own entry`}),qAe=d.object({id:ce.describe('the label its source gives it ("AC-3", "REQ-12"; item 4 of a numbered list is "R4"), else "R1", "R2"\u2026 in order'),statement:ce,source:d.nativeEnum(pi).describe("requirement-reference (an item the run was given), spec, pr-description (also for what the change is evidently meant to do when nothing is written down), or could-break (what the change could break that no requirement mentions)"),reference:d.string().optional().describe('requirement-reference only: the key of its item as listed, e.g. "PAY-184", or a Confluence page id such as "3021"'),evidence:ce.describe("where it is stated: for requirement-reference, the item's own words, copied exactly; else file:line, a doc section, or the quoted phrase"),criterion:d.number().int().positive().optional().describe("requirement-reference only: leave it out; Testbot numbers each criterion by the item's own label (AC2, 2.), else after the item's labels"),alsoFrom:d.array(d.object({reference:ce.regex(Cs).describe("the key of another uploaded document stating the same obligation"),says:ce.describe("that document's own words, copied exactly; never infer equivalence from a shared criterion number"),criterion:d.number().int().positive().optional().describe("leave out; Testbot grounds and numbers this source separately")})).optional().describe("equivalent uploaded source criteria sharing this requirement's planned cases; retain every source with its own quote. Different conditions or boundaries need distinct requirements"),notInChange:d.string().optional().describe("requirement-reference only: when the change does not touch this criterion at all (e.g. a later step of a staged rollout), why; give it no clauses"),unchanged:d.boolean().optional().describe("true when it asks only that behaviour stay as it was (an update or refactor that must not change how something works), whatever its source"),overrules:d.array(g2).optional().describe("requirement-reference only: each lower-ranked source that says otherwise, a spec in the repository, a PR description or another item; this requirement wins, so test what it says"),clauses:d.array(zAe)}),h2=(r=>(r.ServerError="server-error",r.DataLost="data-lost",r.FinalState="final-state",r.DerivedValues="derived-values",r))(h2||{}),JAe=d.object({id:ce.describe('e.g. "F1"'),file:ce,line:d.number().optional(),claim:ce.describe("the defect, in one sentence"),severity:d.nativeEnum(la),evidence:ce.describe("the code line, or the probe request and response, that shows it"),conflictsWith:d.array(ce).optional().describe("requirement or clause ids it violates"),keeps:d.string().optional().describe("for a defect no requirement or clause states: path:line of the code beside the change that keeps the rule it breaks"),rule:d.nativeEnum(h2).optional().describe("for a defect that breaks a rule every app keeps, which nothing needs to state: which one"),existing:d.string().optional().describe("only when the base already does this, in code the change left as it was, and the change does not say it fixes it: where the base does it (its file:line); such a defect gets no case"),needsApp:d.enum(["browser","live-api"]).optional().describe("only when the running app alone can show this defect and the repo has no in-process test that can: browser (page script, what the user sees after a click or a save) or live-api (code the repo tests only against the running app's API)")}),HAe=d.object({id:ce.describe('e.g. "Q1"'),question:ce.describe("what is unsettled, as a question the PR author can answer"),readings:d.array(ce).min(2).describe("each reasonable behaviour, with what points to it (file:line, or the words that suggest it)"),about:d.string().optional().describe("the requirement or clause id it is about, when there is one"),sources:d.array(g2).optional().describe("when sources of the same rank disagree on it: each of them")}),YAe=d.object({id:ce.describe('unique, a short kebab-case name for what the case checks, e.g. "ship-twice-409"'),type:d.nativeEnum(Gi).describe("contract / integration: checks the API, or calls code directly in-process (a function, hook or module); ui: checks what a user sees or does on a page"),target:ce.describe('"METHOD /path", or the page / flow'),clause:d.string().optional().describe("the clause id this case checks"),finding:d.string().optional().describe("the finding id this case catches"),steps:ce.describe("what the test does"),expected:ce.describe("the expected outcome, from the clause"),mutates:d.boolean().optional().describe("true when its test changes state, in the test or its setup: an API POST, PUT, PATCH or DELETE, or a UI flow that submits, creates, edits or deletes")}),WAe=d.object({test:ce.describe("existing test file"),action:d.nativeEnum(li),reason:ce,mutates:d.boolean().optional().describe("true when the maintained test changes state"),clauses:d.array(ce).optional().describe("the clause ids this test checks"),staleOnBase:d.boolean().optional().describe("true when the test's own expectation was already wrong before this change: it fails the same way on the base branch, where the app does what it should. Not one the base app's own bug fails (that is an existing defect). It is verify, never update: re-run as it is, its failure the test's own. A delete the change justifies stays a delete")}),f2=d.array(bb).optional(),ZAe=d.object({components:d.preprocess(e=>f2.safeParse(e).success?e:void 0,f2).describe("when saving a new or changed recipe: every app and backing service actually brought up, its source repository, and whether it is healthy"),outcome:d.nativeEnum(ri).describe("clean | recipe-drift (you had to fix the recipe) | change-broke-bringup (this PR broke start-up) | bringup-failed (the environment, not the PR)"),baseUrls:d.record(d.string()).optional().describe("service \u2192 base URL of the running app"),health:d.object({url:d.string().optional(),command:d.string().optional(),output:d.string().optional()}).optional().describe("the check that shows the app serves real data, and what it returned"),teardown:d.string().optional().describe("command that stops the app"),dependencies:d.record(d.boolean()).optional().describe("every backing service: true = really running, false = mocked"),recipeFixes:d.array(d.string()).optional().describe("what you changed in the recipe"),error:d.string().optional().describe("when it did not come up: the failing command and what it printed"),suspectFiles:d.array(d.string()).optional().describe("change-broke-bringup: the changed files to blame"),missingSecrets:d.array(d.string().regex(Yl)).optional().describe("bringup-failed only: each secret, key, token or password the app cannot start without that this run has no value for, by its environment variable name; never a value"),login:d.object({username:ce,password:d.string()}).optional().describe("the account the tests sign in as, when they sign in: each a literal value the recipe seeds, or $VARIABLE when a secret in the environment holds it"),revisions:Bb.optional()}),p_e=d.object({schemaVersion:d.literal(1),requirements:d.array(qAe),findings:d.array(JAe),cases:d.array(YAe).describe("a second test for a clause, and one case per finding that fails on this branch"),questions:d.array(HAe).optional().describe("behaviours the change leaves unsettled; no case asserts any of them"),maintenance:d.array(WAe),journeys:d.array(Zz).optional().describe("the user journeys that, together, pass through everything the change alters that a user sees or does; empty when it alters nothing a user sees"),notInJourney:d.array(d.object({clause:ce,why:ce})).optional().describe("a clause a user sees or does that no journey walks, and why: none can reach it through the UI, or it is downstream of this change and not walked here"),unplannedComponents:d.array(d.object({components:d.array(ce).min(1).describe("changed components, as the change lists them"),why:ce})).optional().describe("changed components no clause reaches, and why their change needs no test; several may share one reason"),triage:TA.optional().describe("the validation triage decision, made before the app is started; its behaviorIds are clause ids"),app:ZAe.optional().describe("omit when no app was needed or none was started"),summary:ce.describe("one paragraph: what the change does and where the risk is")});var NA=(n=>(n.Backend="backend",n.Ui="ui",n))(NA||{});var js=(r=>(r.Added="added",r.Updated="updated",r.Deleted="deleted",r.Unchanged="unchanged",r))(js||{}),KAe=d.object({file:ce.describe("repo-relative path; in another repo of the change, that repo's directory name then its path"),kind:d.nativeEnum(NA),change:d.nativeEnum(js).describe("added: a file you created; updated / deleted / unchanged: an existing test"),covers:d.array(d.string()).describe("the plan case ids this file tests, each with its own result under result.cases"),defect:d.boolean().optional().describe("true when a case of it fails because the app is wrong and the test is right \u2014 kept failing on purpose"),staleBecause:d.object({requirement:ce.describe("the requirement or clause id the change deliberately alters"),line:ce.describe("path:line (or path) of the application code the change altered that makes this test's old expectation wrong")}).optional().describe("for an existing test you updated or deleted: why it is out of date"),staleOnBase:d.boolean().optional().describe("for an existing test that fails: true when it fails the same way on the base branch because its own expectation is wrong (the app there does what it should), so this change did not make it wrong. Not when the base app's own bug fails it: that is an existing defect. Leave it as it is (unchanged): its failure is the test's own"),result:d.object({exit:d.number().nullable().describe("exit code of your last run of this file; null if it could not be run"),cases:d.array(d.object({case:ce,status:d.nativeEnum(pr),runtimeTargets:Wl.optional().describe("HTTP(S) URLs this case actually exercised in its current run, from its request or browser evidence; omit for local in-process/mocked checks, never list the shared app merely because it is configured"),defect:d.boolean().optional().describe("for a failing case: true when the app is wrong and the test is right; false when the test is at fault and you could not fix it"),testProblem:pg.optional().describe("for a failing case marked defect: false: what in the test is at fault"),failure:d.string().optional().describe("for a failing case: the runner's failure for it as printed (the error and the line it was raised at), not a summary"),cause:d.string().optional().describe("for a case you keep as a defect: path:line of the application code that makes it fail"),requires:d.string().optional().describe("for a case you keep as a defect: the words of the PR description, a requirement or clause of the plan, or the code a finding's keeps names, that state what its failing check expects, quoted exactly")})).describe("one entry per covered case, from the runner's own output"),details:d.string().optional().describe("what failed and why, or why it was not run"),noCases:d.string().optional().describe("for a failed run whose runner reported none of this file's tests (it failed to compile, import or collect): why")}),assertions:d.array(d.object({case:ce,evidence:ce})).optional().describe("per covered case, the assertion line that checks its expected outcome"),functions:d.array(d.object({name:ce.describe("the test function as the runner names it within its file, without the file (test_x, TestClass::test_x, TestSuite/TestCase)"),cases:d.array(ce).describe("the plan case ids it checks"),testProblem:pg.optional().describe("for a function that fails because of the test itself, while another function keeps a case it checks as a defect: what in it is at fault")})).optional().describe("for a file you added or updated: each test function in it and the plan case ids it checks"),skyramp:d.object({draft:d.union([d.string(),d.array(d.string())]).optional().describe("the draft path the Skyramp helper returned for this test, or each path when the test was made from several drafts"),handWritten:d.string().optional().describe("why it is written by hand: the helper call you made and what it returned")}).optional().describe("only for a test of a case the Skyramp API block lists: where it came from"),context:d.array(Mx).optional().describe("what the test sets up outside its own process that another test could run into: data it creates in the app, a Skyramp mock, an env override; omit when none"),isolatedRun:ce.optional().describe("for a test with a context: the command, from its checkout's root and without a shell, that runs only this file"),ci:p2.optional().describe("for a file you added or updated: whether the repo's CI will run it, and how you know"),run:Cu.optional().describe(`for a file in ${bu}, added, updated or re-run: how the run executes only this file's tests, with the repository's own runner and the report it writes (junit, trx or jest-json to ${sn}, or go-test-json); Testbot runs it before write ends and re-runs the tests with it`)}),XAe=o(e=>{if(!e||typeof e!="object")return e;let{test:t,...n}=e;return typeof t=="string"&&t.trim()&&n.tests===void 0?{...n,tests:[t]}:e},"oneTestIsTests"),epe=d.preprocess(XAe,d.object({description:ce.describe("what is wrong and how to reproduce it: endpoint or page, input, what you got vs what was expected"),severity:d.nativeEnum(la).optional(),sourceFile:d.string().optional().describe("the app file at fault"),sourceLine:d.number().optional(),tests:d.array(ce).optional().describe("every test file that fails because of it: a defect several tests show is one issue"),finding:d.string().optional().describe("the plan's finding id, when it is one"),requirements:d.array(ce).optional().describe("the plan's requirement or clause ids it violates")})),f_e=d.object({schemaVersion:d.literal(1),tests:d.array(KAe),notWritten:d.array(d.object({case:ce,reason:ce,coveredBy:d.object({file:ce.describe("the test file, relative to the working checkout; prefix a related checkout as for tests[].file"),name:ce.describe("the test function as the runner names it within its file, without the file (test_x, TestClass::test_x, TestSuite/TestCase)")}).optional().describe("only for an existing test triage independently linked to this exact case: its exact runner name (including class or describe titles). Testbot must finish re-running it with every result passed. If your own test covers the case, include the case in its covers and function cases instead")})).describe("every plan case no test covers, and why"),journeys:d.array(sy).optional().describe("one entry per planned user journey: the browser test that walks it end to end"),lint:d.object({command:d.string(),clean:d.boolean()}).optional().describe("the linter/formatter you ran on your test files, if the repo has one: the exact command, with its file paths (Testbot re-runs it)"),dependenciesAdded:d.array(d.object({package:ce,manifest:ce.describe("the manifest file's path relative to its checkout (e.g. package.json, pom.xml or pyproject.toml), and nothing else; name another checkout in repository"),repository:ce.optional().describe("owner/repo of the manifest's checkout; omit for the repo under test"),reason:ce.optional().describe("why the test must run inside the application's own test environment, so its manifest had to change \u2014 required for every entry")})).optional().describe("every package you added to an APPLICATION manifest (an exception, surfaced in the report); never the Testbot test package's own"),supportFiles:d.array(ce).optional().describe("every file that is not a test you created or changed for your tests, which they need to compile or run (a helper module, page object, fixture, or a snapshot the runner wrote for them), named as you name a test; Testbot delivers only the tests you list and the files under supportFiles"),ciNotes:d.string().optional().describe("for each test whose ci says the repo's CI will not run it: the test, and the exact change the author must make for CI to run it"),commit:d.object({message:ce.describe("subject line at most 72 characters, following the repository's commit-message checks"),prTitle:ce.describe("at most 72 characters, following the repository's PR-title checks"),prBody:ce.describe("what the tests cover and what they found")}),report:d.object({summary:ce.describe("1-2 sentences for the PR author: does the change do what it says?"),issues:d.array(epe).describe("every defect the tests found"),nextSteps:d.array(d.string()),noTests:d.array(d.object({repository:ce,reason:ce.max(4096)})).max(1e3).optional().describe("each Change Set repository where no test was added or updated: its owner/repo and why, naming the other repository when its tests went there"),notesDeviation:d.string().trim().max(4096).optional().describe("when the Target notes say where tests go and a test you added went elsewhere: where it went, and why; omit otherwise")})});var g_e={added:"place",updated:"update",deleted:"delete",unchanged:"verify"};var y2=(i=>(i.Requirement="requirement",i.PrDescription="pr_description",i.Code="code",i))(y2||{}),qt=d.string().trim().min(1),tpe=d.object({expectation:qt.max(300).describe("the behavior this assertion pins, in words"),source:d.nativeEnum(y2),expected:qt.max(200).describe("the exact value or outcome asserted, as the test asserts it")}),npe=d.object({file:qt.describe("path of the NEW test file you wrote, relative to its repository"),repository:qt.optional().describe("owner/repo the file lives in, when the run has several checkouts; omit for the working checkout"),framework:qt.describe("the framework the repository runs this file with: pytest, jest, vitest, node-test, or the name of any other"),run:Cu.optional().describe(`for ${bu}: how the run executes only the tests in names, with the repository's own runner writing JUnit XML to {junit}`),covers:d.array(qt).length(1).describe("the ONE behavior id, or defect id, from the plan that the tests in names provide evidence for; a file covering several is listed once per id"),names:d.array(qt).min(1).describe("the test functions/cases in the file that provide evidence for that behavior, as the framework names them"),assertions:d.array(tpe).min(1)}),UA=(n=>(n.Updated="updated",n.Deleted="deleted",n))(UA||{}),m2=300,rpe=d.object({file:qt.describe("path of the EXISTING test file you updated or deleted, relative to its repository"),repository:qt.optional().describe("owner/repo the file lives in, when the run has several checkouts; omit for the working checkout"),change:d.nativeEnum(UA),staleBecause:d.object({requirement:qt.describe("the requirement or clause id the change deliberately alters"),line:qt.describe("path:line (or path) of the application code the change altered that makes this test's old expectation wrong")}).optional().describe("for an existing test you updated: why it is out of date"),reason:d.preprocess(e=>typeof e=="string"?e.trim().slice(0,m2):e,qt.max(m2)).describe("what the change deliberately altered that made the test wrong")}),Jx=d.object({schemaVersion:d.literal(1),tests:d.array(npe),maintained:d.array(rpe).optional().describe("existing tests the change made stale that you updated or deleted; omit when there were none"),defectsNotTested:d.array(d.object({id:qt,reason:qt.max(300)})).optional().describe("defects the plan found that no in-process test can reach, each with why; omit when every defect has a test"),journeys:d.array(sy).optional().describe("one entry per planned user journey: the in-process test that walks it end to end"),journeysNotWritten:d.array(d.object({journey:qt,missing:qt.transform(e=>e.length>300?`${e.slice(0,299)}\u2026`:e)})).optional().describe("a planned journey no in-process test can walk here, with what it needs that is missing; it is reported as not covered"),lint:d.object({command:d.string(),clean:d.boolean()}).optional().describe("the linter/formatter you ran on your test files, if the repository has one you can run; omit otherwise"),commitMessage:qt.optional().describe("the commit message for your tests: a subject line of at most 72 characters, then what they cover")});var FA="generate-unit.json";function spe(e){let{value:t,error:n}=$t(e);if(n)return{errors:[n]};let{value:i,errors:r}=mn(Jx,t);return r.length?{errors:r}:{output:i,errors:[]}}o(spe,"parseGenerateUnitText");function ope(e){return spe(e.stdout)}o(ope,"parseGenerateUnitFromSession");var sNe=$n("generate-unit-schema",(e,t)=>ope(t));var ly=String.raw`(?:node:)?(?:http|https|http2|net|tls|dgram)`,oNe=[[/\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+["']${ly}["']|\bimport\s+["']${ly}["']|require\(\s*["']${ly}["']\s*\)|\bimport\(\s*["']${ly}["']\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 SNe=new Set(["targeted_unit","existing_evidence_sufficient"]);var fpe="triage.json";var NUe=new Set(["existing_evidence","unaffected","existing_unit","new_unit","runtime"]),UUe={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 gpe(e){let{value:t,error:n}=$t(e);if(n)return{errors:[n]};let{value:i,errors:r}=mn(TA,t);return r.length?{errors:r}:{triage:i,errors:[]}}o(gpe,"parseTriageText");function hpe(e){return gpe(e.stdout)}o(hpe,"parseTriageFromSession");var FUe=$n("triage-schema",(e,t)=>hpe(t));function mpe(e){let t=e.inputs?.pipeline;return t?e.state.stages[t==="two-step"?"plan":"triage"]:e.state.stages.triage??e.state.stages.plan}o(mpe,"triageDecider");function Yx(e){if(mpe(e)?.status==="passed")return jo(w2.join(e.outputsDir,fpe))}o(Yx,"readTriage");function Wx(e){return K1(RR(e.inputs,Ve(e,`${mA}.json`),Yx(e)?.sutRequired))}o(Wx,"revisionBlockReason");var PUe=new Set(["deploy","recommend","generate","generate-ui","adapt","generate-unit","native-run","finalize","deliver"]);var Pr=Se(require("fs")),Vs=Se(require("path")),mq=Se(require("crypto")),yq=require("child_process");var Zx=require("child_process"),Bu=Se(require("fs")),B2=Se(require("os")),py=Se(require("path"));var ype={onPath:o(e=>(0,Zx.spawnSync)("sh",["-c",`command -v ${e}`],{stdio:"ignore"}).status===0,"onPath"),run:o((e,t)=>(0,Zx.spawnSync)(e[0],e.slice(1),{cwd:t,stdio:"ignore",timeout:6e4}).status??1,"run")},Ay={cleanup:o(()=>{},"cleanup")},Epe=new Set(["pnpm","yarn"]);function k2(e,t=B2.tmpdir(),n=ype){if(process.platform==="win32")return Ay;try{let i=Bx(e);if(!Epe.has(i)||n.onPath(i)||!n.onPath("corepack"))return Ay;Bu.mkdirSync(t,{recursive:!0});let r=Bu.mkdtempSync(py.join(t,"testbot-pm-")),s=o(()=>Bu.rmSync(r,{recursive:!0,force:!0}),"cleanup");return n.run(["corepack","enable","--install-directory",r,i],e)!==0?(s(),Ay):{dir:r,cleanup:s}}catch{return Ay}}o(k2,"packageManagerShims");function S2(e,t=process.env){return e.dir?{...t,PATH:[e.dir,t.PATH].filter(Boolean).join(py.delimiter)}:t}o(S2,"withShims");var jA=require("crypto");function Jt(e){let t=Math.max(0,...(e.match(/`+/g)??[]).map(r=>r.length)),n="`".repeat(t+1),i=e.startsWith("`")||e.endsWith("`")?" ":"";return`${n}${i}${e}${i}${n}`}o(Jt,"codeSpan");Ac();var uFe=5*6e4,lFe=12*6e4,dFe=2*6e4;var yFe=["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(`
|
|
159
|
+
`);var xFe=[...gb,"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 fy=Se(vx());var sPe={jest:"jest",vitest:"vitest"};var OPe=new Set(["jest","vitest","npm-test","playwright"]);var eMe=5*6e4;var PA=Se(require("path"));var BMe={python:"pytest",typescript:"playwright",javascript:"playwright"},kMe={pytest:"pytest",playwright:"playwright"};function vpe(e){return mn(zb,e).errors}o(vpe,"validateFinalizeOutput");function wpe(e,t=[]){let{value:n,error:i}=$t(e,t);if(i)return{errors:[i]};let r=vpe(n);return r.length>0?{errors:r}:{finalize:n,errors:[]}}o(wpe,"parseFinalizeText");var Bpe="finalize-scratch";function kpe(e,t){let n=wpe(e.stdout,t?.secretValues);if(!n.finalize||!t?.outputsDir)return n;let i=o((r,s)=>r.trim()&&xx(r.trim(),PA.join(t.outputsDir,Bpe,s),"finalize")||r,"script");return{...n,finalize:{...n.finalize,lint:n.finalize.lint.map((r,s)=>({...r,command:i(r.command??"",`lint-${s+1}.sh`)}))}}}o(kpe,"parseFinalizeFromSession");var mOe=$n("finalize-schema",(e,t)=>kpe(t,e));function Spe(e){return mn(Px,e).errors}o(Spe,"validateAnalysisOutput");function $2(e,t=[]){let{value:n,error:i}=$t(e,t);if(i)return{errors:[i]};let r=Spe(n);return r.length>0?{errors:r}:{analysis:n,errors:[]}}o($2,"parseAnalysisText");function Qpe(e,t=[]){return $2(e.stdout,t)}o(Qpe,"parseAnalysisFromSession");var LOe=$n("analysis-schema",(e,t)=>Qpe(t,e.secretValues));var cje=sg.rows.notRun(!0);var MA="kept, not ";var OA="(declined the planned ";function Kx(e){if(!e)return[];let t=[],n=0,i=0;for(let r=0;r<e.length;r++){let s=e[r];s==="("?n++:s===")"?n=Math.max(0,n-1):n===0&&s===";"&&e[r+1]===" "&&e[r-1]===")"&&(t.push(e.slice(i,r)),i=r+2)}return t.push(e.slice(i)),t.map(r=>{let s=r.trim();if(!s.endsWith(")"))return{expectation:s};let a=0;for(let c=s.length-1;c>=0;c--)if(s[c]===")")a++;else if(s[c]==="("&&--a===0){let u=s.slice(0,c).trim(),l=s.slice(c+1,-1).trim();return u&&l?{expectation:u,expected:l}:{expectation:s}}return{expectation:s}})}o(Kx,"assertionParts");var T2=new Set(["update","regenerate","delete"]);var uje={update:"updated",regenerate:"regenerated",delete:"deleted",verify:"verified",none:"touched"};var D2=d.string().trim().min(1),Xx=d.object({schemaVersion:d.literal(1).optional(),businessCaseAnalysis:D2.describe("1-2 sentences: what this change means for a user, and whether the evidence shows it working"),issuesFound:d.array(d.object({description:D2,severity:d.string().optional().describe("critical | high | medium | low"),category:d.string().optional().describe("bug | lint | type | config"),sourceFile:d.string().optional(),sourceLine:d.number().optional(),findingId:d.string().optional(),requirementIds:d.array(d.string()).optional()})).describe("every real problem this run exposed \u2014 cause, file:line, severity"),nextSteps:d.array(d.string()).describe("concrete follow-ups the author can act on; required non-empty when a disclosure is BLOCKING")});function Tpe(e){return mn(Xx,e).errors}o(Tpe,"validateProseOutput");function Dpe(e,t=[]){let{value:n,error:i}=$t(e.stdout,t);if(i)return{errors:[i]};let r=Tpe(n);return r.length>0?{errors:r}:{prose:n,errors:[]}}o(Dpe,"parseProseFromSession");var vje=$n("report-schema",(e,t)=>Dpe(t,e.secretValues));var _2="<!-- skyramp-testbot -->",N2=T2,_pe=new Set(["lint","type","config"]),U2={critical:0,high:1,medium:2,low:3},j2=new Set(["Pass","Fail"]);var n$=o(e=>Io(ae().statusLabels,e),"statusLabel"),e$=o(e=>Io(ae().testTypeCellLabels,e),"testTypeLabel");function Ge(e){return(e??"").replace(/\|/g,"\\|").replace(/\r?\n/g,"<br>").trim()}o(Ge,"escCell");function F2(e){return e.inferred?" (inferred)":""}o(F2,"inferredMark");function P2(e,t){return!e||!j2.has(e)?"\u2014":t?`${n$(e)} (${Ge(G2(t))})`:n$(e)}o(P2,"maintStatus");function G2(e){let t=o(i=>{let r=i.indexOf(": ");return r<0?i:Io(ae().staged.maintenanceActions,i.slice(0,r))+i.slice(r)},"action");if(e.startsWith(MA))return ae().staged.keptNot+t(e.slice(MA.length));let n=e.indexOf(OA);return n<0?e:e.slice(0,n)+ae().staged.declinedPlanned+t(e.slice(n+OA.length))}o(G2,"declineNote");function M2(e){return e.category!==void 0&&_pe.has(e.category.toLowerCase())}o(M2,"isTooling");function O2(e,t){return(U2[(e.severity??"").toLowerCase()]??4)-(U2[(t.severity??"").toLowerCase()]??4)}o(O2,"bySeverity");function L2(e){return`- ${e.severity?`**[${Io(ae().severityLabels,e.severity.toLowerCase()).toUpperCase()}]** `:""}${e.description.trim()}`}o(L2,"issueLine");function Npe(e){let t=e.resultId?.split("#").slice(1).join("#");if(e.testType!=="unit"||!t)return;let n=t;try{n=decodeURIComponent(t)}catch{}let i=/^(.*?)(\[.*\])$/.exec(n);return i?{fn:i[1],kase:i[2]}:{fn:n}}o(Npe,"unitTestOf");var V2=o((e,t)=>e!==void 0&&t!==void 0&&e.replace(/^\.\//,"")===t.replace(/^\.\//,""),"samePath");function z2(e,t){return(e.testVideos??[]).find(n=>n.url&&t(n))?.url}o(z2,"videoLink");function r$(e,t){return z2(e,n=>V2(n.fileName,t.fileName)&&(!n.repository||!t.repository||n.repository.toLowerCase()===t.repository.toLowerCase()))}o(r$,"resultVideoLink");function i$(e,t){return z2(e,n=>V2(n.writtenAs??n.fileName,t))}o(i$,"journeyVideoLink");function Upe(e,t,n){return n?r$(e,{fileName:t,repository:n}):i$(e,t)}o(Upe,"requirementVideoLink");function Fpe(e){let t=[],n=new Map;for(let a of e.newTestsCreated)a.testType==="unit"&&n.set(a.fileName,[...n.get(a.fileName)??[],a.testId.split("::").slice(1).join("::")]);let i=new Map,r=o((a,c)=>(n.get(a??"")??[]).find(u=>u!==c&&zz(c,u)),"parentOf"),s=new Map;for(let a of e.testResults){let c=Npe(a),u=c&&!c.kase?r(a.fileName,c.fn):void 0;if(c&&u&&(c={fn:u,kase:`"${c.fn}"`}),c?.kase&&i.set(a,c.kase),!c){t.push({testId:a.testId,testType:a.testType,endpoint:a.endpoint,status:a.status,details:a.details??"",...a.fileName?{fileName:a.fileName}:{},...a.repository?{repository:a.repository}:{}});continue}let l=`${a.fileName??""}#${c.fn}`,A=s.get(l);A||(A={row:{testId:a.testId,testType:a.testType,endpoint:a.endpoint,status:a.status,details:"",test:c.fn,...a.fileName?{fileName:a.fileName}:{},...a.repository?{repository:a.repository}:{}},cases:[]},s.set(l,A),t.push(A.row)),A.cases.push(a)}for(let{row:a,cases:c}of s.values()){let u=c.filter(g=>g.status==="Fail"),l=c.filter(g=>g.status==="Pass").length,A=c.filter(g=>g.status==="Skipped").length;a.cases=c.length,a.status=u.length?"Fail":A?"Skipped":"Pass";let p=u[0];a.details=c.length===1?c[0].details??"":ae().staged.casesPassed(l,c.length,A)+(p?`; ${i.get(p)??""} ${p.details??""}`.replace(/; +/,"; ").trimEnd():"")}return t}o(Fpe,"resultRows");function Ppe(e){return Kx(e).map(t=>t.expected===void 0?t.expectation:`${t.expectation}: ${Jt(t.expected)}`)}o(Ppe,"unitAssertions");function t$(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"))}o(t$,"nothingExecuted");function q2(e,t={}){let{audience:n,collapsed:i=!1,existingEvidence:r=[],requestedBy:s,sourcePullRequest:a}=t,c=n!=="testbot-pr",u=n!=="comment",l=n!=="testbot-pr",A=(e.requirements??[]).filter(P=>/^file-[a-f0-9]{16}-/i.test(P.id)).sort((P,ee)=>ee.id.length-P.id.length),p=o(P=>{let ee=A.find(Y=>P.toLowerCase().startsWith(Y.id.toLowerCase()));return ee?ee.label+P.slice(ee.id.length):P},"displayId"),g=[_2];if(a&&g.push(ae().staged.testsSourcePullRequest(Jt(a)),""),s){let P=s.name.replace(/\s+/g," ").trim().replace(/[<>[\]()*_`\\|#]/g,"\\$&").replace(/@/g,"@\u200D");g.push(s.kind==="person"?ae().staged.requestedByPerson(P):ae().staged.requestedByPolicy(P),"")}e.notTranslated&&g.push(Io(ae().staged.notTranslated,e.notTranslated),"");let h=o(P=>{i?g.push("<details>",`<summary>${P}</summary>`,""):g.push(`### ${P}`)},"sectionStart"),y=o(()=>{i&&g.push("","</details>"),g.push("")},"sectionEnd");if(c){for(let P of e.businessCaseAnalysis.trim().split(/\r?\n/))g.push(`> ${P}`);g.push("")}if(t$(e)&&g.push(ae().staged.noLiveApp(e.newTestsCreated.length),""),u&&e.newTestsCreated.length){let P=new Map;for(let se of e.newTestsCreated){if(se.testType!=="unit")continue;let ye=(se.testId.split("::").slice(1).join("::")||se.testId).replace(/\[.*\]$/,""),G=P.get(se.fileName)??{functions:new Set,endpoints:[],descriptions:new Map};se.endpoint&&!G.endpoints.includes(se.endpoint)&&G.endpoints.push(se.endpoint);let M=se.description?.trim()??"",st=G.descriptions.get(ye)??[];st.includes(M)||st.push(M),G.functions.add(ye),G.descriptions.set(ye,st),P.set(se.fileName,G)}let ee=e.newTestsCreated.filter(se=>se.testType!=="unit"),Y=ee.length+[...P.values()].reduce((se,ye)=>se+ye.functions.size,0);h(ae().testRecommendationsImplementedHeader(Y));for(let[se,{functions:ye,endpoints:G,descriptions:M}]of P){let st=ye.size;g.push(ae().staged.unitTestsInFile(`\`${se}\``,st,G.map(ot=>`\`${ot}\``).join(", ")),"");let ze=new Map;for(let[ot,Yt]of M){let Dt=Yt.join("\0"),tt=ze.get(Dt)??{fns:[],descriptions:Yt};tt.fns.push(ot),ze.set(Dt,tt)}let Mn=0;for(let{fns:ot,descriptions:Yt}of ze.values()){g.push(`${++Mn}. ${ot.map(tt=>`\`${tt}\``).join(", ")}`);let Dt=[...new Set(Yt.flatMap(tt=>Ppe(tt)))];for(let tt of Dt)g.push(` - ${tt}`)}g.push("")}for(let se of ee){let ye=se.testId?Jt(p(se.testId)):e$(se.testType),G=se.fileName?` (\`${se.fileName}\`)`:"",M=se.endpoint?`
|
|
160
160
|
\`${se.endpoint}\``:"",st=se.description?`
|
|
161
161
|
${se.description.trim()}`:"";g.push(`- ${ye}${G}${M}${st}`)}y()}let E=(e.testMaintenance??[]).filter(P=>N2.has(P.action));if(u&&E.length){h(ae().staged.testMaintenanceHeader),g.push(ae().maintenanceTableHeader),g.push("|-----------|----------|------|--------|--------|-------|");for(let P of E)g.push(`| ${Ge(e$(P.testType))} | ${Ge(P.endpoint)} | \`${Ge(P.fileName)}\` | ${Ge(P.description)} | ${P2(P.beforeStatus,P.beforeDetails)} | ${P2(P.afterStatus,P.afterDetails)} |`);y()}let C=o(P=>P.startsWith(MA)||P.includes(OA),"hasDeclineNote"),I=(e.testMaintenance??[]).filter(P=>C(P.afterDetails)&&(!N2.has(P.action)||!j2.has(P.afterStatus??"")));if(u&&I.length){h(ae().staged.declinedMaintenanceHeader);for(let P of I)g.push(`- \`${Ge(P.fileName)}\`: ${Ge(G2(P.afterDetails))}`);y()}if(u&&r.length){h(ae().staged.existingEvidenceHeader);let P=new Map;for(let ee of r){let Y=`${ee.check}\0${ee.url??""}\0${ee.revision??""}`;P.set(Y,[...P.get(Y)??[],ee])}for(let[,[ee,...Y]]of P){let se=ee.url?`[${Jt(ee.check)}](${ee.url})`:Jt(ee.check);g.push(ae().staged.trustedCheckPassed(se,ee.revision?Jt(ee.revision.slice(0,7)):""),"");for(let ye of[ee,...Y])g.push(`- ${Jt(ye.behavior)}`);g.push("")}y()}if(u&&e.testResults.length){h(ae().staged.testResultsHeader);let P=Fpe(e),ee=P.some(G=>G.test),Y=P.some(G=>r$(e,G)),se=ee?ae().staged.unitResultsTableHeader:ae().staged.resultsTableHeader;g.push(Y?`${se} ${ae().columnVideo} |`:se),g.push(`${ee?"|---------|-----------|----------|------|-------|--------|---------|":"|---------|-----------|----------|--------|---------|"}${Y?"-------|":""}`);for(let G of P){let M=G.details.replace(/(\S+\.(?:py|ts|js|spec\.\w+))/gi,"`$1`"),st=G.testId?Jt(Ge(p(G.testId))):"\u2014",ze=ee?` ${G.test?`\`${Ge(G.test)}\``:""} | ${G.cases??""} |`:"",Mn=r$(e,G),ot=Y?` ${Mn?ae().videoDownloadLink(Mn):"\u2014"} |`:"";g.push(`| ${st} | ${Ge(e$(G.testType))} | ${Ge(G.endpoint)} |${ze} ${Ge(n$(G.status))} | ${Ge(M)} |${ot}`)}let ye=(e.testVideos??[]).find(G=>G.artifactsUrl)?.artifactsUrl;!Y&&ye&&g.push("",ae().videosArtifactFallback(ye)),y()}if(e.requirements?.length){let P=e.requirements.flatMap(G=>G.clauses),ee=o(G=>G.status==="Pass"||G.status==="Passed, test not kept","passes"),Y=P.filter(ee).length;h(ae().staged.requirementsHeader(Y,P.length));let se=o(G=>Io(ae().staged.clauseStatuses,G.status),"status"),ye=o(G=>(G.status==="Not tested"||G.status==="Passed, test not kept")&&G.notTested?`${se(G)}: ${G.notTested}`:G.findings.length?`${se(G)} \u2014 ${G.findings.join(", ")}`:se(G),"result");if(u){g.push(ae().staged.requirementsTableHeader),g.push("|-------------|--------|-------|--------|");for(let G of e.requirements)G.clauses.forEach((M,st)=>{let ze=st===0?`**${Ge(G.label)}**${G.statement?` ${Ge(G.statement)}`:""}`:"",Mn=`${Jt(Ge(p(M.id)))}${F2(M)}${M.text?` ${Ge(M.text)}`:""}`,ot=new Map;for(let tt of M.tests){let In=tt.fileName??p(tt.testId),lt=ot.get(In)??{fns:new Set};for(let Cn of tt.functions)lt.fns.add(Cn);lt.video??=tt.fileName?Upe(e,tt.fileName,tt.repository):void 0,ot.set(In,lt)}let Yt=ot.size?[...ot].map(([tt,{fns:In,video:lt}])=>`${Jt(Ge(tt))}${In.size?` \u2014 ${[...In].map(Cn=>`\`${Ge(Cn)}\``).join(", ")}`:""}${lt?` ${ae().videoDownloadLink(lt)}`:""}`).join("<br>"):"\u2014",Dt=G.source==="could-break"&&M.status==="Pass"?ae().staged.regressionGuard:"";g.push(`| ${ze} | ${Mn} | ${Yt} | ${Ge(ye(M)+Dt)} |`)})}else{g.push(ae().staged.requirementsSummaryTableHeader),g.push("|-------------|-----------------|-------------|");for(let G of e.requirements){let M=G.clauses.filter(ee).length,st=G.clauses.filter(ze=>!ee(ze)).map(ze=>`${Jt(Ge(p(ze.id)))}${F2(ze)} ${Ge(ye(ze))}`);g.push(`| **${Ge(G.label)}**${G.statement?` ${Ge(G.statement)}`:""} | ${M}/${G.clauses.length} | ${st.join("<br>")||"\u2014"} |`)}}y()}if(u&&e.changes?.length&&!e.requirements?.length){let P=e.executionCoverage,ee=P?ae().staged.coverageCaption(P.generated,P.modified,P.verified,P.executed):"";h(`${ae().staged.behaviourCoverageHeader}${ee}`),g.push(ae().staged.coverageTableHeader),g.push("|-----------|--------|-----------|----------------|");for(let Y of e.changes){let se=Y.testedBy.length?Y.testedBy.map(G=>`\`${Ge(G)}\``).join(", "):Y.writtenBy.length?ae().staged.writtenNotRun:"\u2014",ye=Y.maintainedBy.length?Y.maintainedBy.map(G=>`\`${Ge(G)}\``).join(", "):"\u2014";g.push(`| ${Ge(Y.text)} | \`${Ge(Y.source)}\` | ${se} | ${ye} |`)}y()}if(e.userJourneys?.length){let P=e.userJourneys.filter(Y=>Y.status==="Pass"&&!Y.problems.length).length;h(`\u{1F9ED} User Journeys Covered (${P}/${e.userJourneys.length} walked end to end)`);let ee=e.userJourneys.some(Y=>i$(e,Y.fileName));g.push(`| Journey | Test | Status | Notes |${ee?` ${ae().columnVideo} |`:""}`),g.push(`|---------|------|--------|-------|${ee?"-------|":""}`);for(let Y of e.userJourneys){let se=Y.fileName?`\`${Ge(Y.fileName)}\`${Y.test?` \u2014 ${Ge(Y.test)}`:""}`:"\u2014",ye=Y.source&&Y.source!=="inferred"?`; described in the ${Y.source==="spec"?"spec":"PR description"}`:"; inferred from the app",G=(Y.uncovered?`not covered: ${Y.uncovered}`:Y.problems.length?`does not walk it end to end: ${Y.problems.join("; ")}`:`from ${Y.entry}, ${Y.steps} steps`)+ye,M=ee?i$(e,Y.fileName):void 0;g.push(`| ${Ge(Y.name)} | ${se} | ${Ge(Y.status)} | ${Ge(G)} |${ee?` ${M?ae().videoDownloadLink(M):"\u2014"} |`:""}`)}y()}if(l){let P=e.issuesFound.filter(Y=>!M2(Y)).sort(O2),ee=e.issuesFound.filter(M2).sort(O2);if(P.length){h(ae().staged.issuesFoundHeader);for(let Y of P)g.push(L2(Y));y()}if(ee.length){g.push(`### ${ae().configErrorsHeader}`);for(let Y of ee)g.push(L2(Y));g.push("")}}let b=e.testPackages??[],D=e.dependencyChanges??[];if(b.length){g.push(ae().staged.testPackagesHeader,"");for(let P of b)g.push(`- ${ae().staged.testPackageLine(P.directory,P.entrypoint,Object.entries(P.dependencies??{}).map(([ee,Y])=>P.runner==="pytest"?`${ee}==${Y}`:`${ee}@${Y}`).join(", "))}`);D.length||g.push(`- ${ae().staged.appManifestsUntouched}`),g.push("")}if(D.length){g.push(ae().staged.dependencyChangesHeader,"");for(let P of D)g.push(`- ${ae().staged.dependencyChangeLine(P.package,P.repository?`${P.repository}: ${P.manifest}`:P.manifest,(P.reason??"").replace(/\s+/g," ").trim())}`);g.push("")}let N=(e.caveats??[]).filter(P=>P.kind!=="tests-not-executed"||P.subject==="written-cases"||!t$(e));if(N.length){g.push(ae().staged.caveatsHeader,"");for(let P of N)g.push(`- ${P.text}`);g.push("")}if(l&&e.nextSteps.length){g.push(ae().nextStepsHeader,"");for(let P of e.nextSteps)g.push(`- ${P.trim()}`);g.push("")}let W=g.join(`
|
|
162
162
|
`).replace(/\n{3,}/g,`
|
|
@@ -164,7 +164,7 @@ ${i}
|
|
|
164
164
|
`).trim()+`
|
|
165
165
|
`;if(n!=="testbot-pr"||Buffer.byteLength(W,"utf8")<=64e3)return W;let K=o(P=>e.testResults.filter(ee=>ee.status===P).length,"counts"),pe=e.requirements?.flatMap(P=>P.clauses)??[],Fe=o(P=>Array.from(P.replace(/\s+/g," ").trim()).slice(0,300).join(""),"snippet"),et=o(P=>Fe(P).replace(/[&<>\\`*_[\]{}()#+.!|~-]/g,ee=>`&#${ee.charCodeAt(0)};`),"plainSnippet");return[_2,...a?[ae().staged.testsSourcePullRequest(Jt(Fe(a)))]:[],ae().staged.largeReportSummary(e.requirements?.length??0,pe.length,K("Pass"),K("Fail"),K("Skipped")),ae().staged.largeReportNotice,...e.validation?[ae().staged.largeReportValidation(et(e.validation.sufficiency),et(e.validation.rationale),e.validation.gaps.length)]:[],...(e.caveats??[]).slice(0,3).map(P=>`> \u26A0\uFE0F ${et(P.text)}`),...t$(e)?[ae().staged.noLiveApp(e.newTestsCreated.length)]:[],...t.runUrl?[ae().staged.viewRun(t.runUrl)]:[],""].join(`
|
|
166
166
|
|
|
167
|
-
`)}o(q2,"renderPrBody");var Gs=Se(require("fs")),s$=Se(require("path"));var Ope="report.json",Lpe="report-display.json",
|
|
167
|
+
`)}o(q2,"renderPrBody");var Gs=Se(require("fs")),s$=Se(require("path"));var Ope="report.json",Lpe="report-display.json",Wje={en:"English",ja:"Japanese"};function J2(e){let t=s$.join(e,Lpe);if(Gs.existsSync(t))try{return JSON.parse(Gs.readFileSync(t,"utf-8"))}catch{}let n=s$.join(e,Ope);return Gs.existsSync(n)?JSON.parse(Gs.readFileSync(n,"utf-8")):void 0}o(J2,"readDisplayReport");function H2(e,t){return t?`<!-- skyramp-testbot-run: ${t} -->
|
|
168
168
|
${e}`:e}o(H2,"withRunMarker");var fa=Se(require("fs")),pa=Se(require("path"));var gy=["build","chore","ci","docs","feat","fix","perf","refactor","revert","style","test"],jpe=["build","ci","docs","feat","fix","perf","refactor","revert","style","test"],Gpe="amannn/action-semantic-pull-request",Pn=o(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObj");function Y2(e){return typeof e!="string"?!1:e.split("@")[0].split("/").some(n=>n.toLowerCase().split(/[-_.]/).includes("dco"))}o(Y2,"usesDco");function W2(e){return typeof e=="string"&&(/\bdco-check\b/.test(e)||/signed-off-by/i.test(e))}o(W2,"scriptChecksDco");function Vpe(e){if(!Pn(e)||!Pn(e.jobs))return!1;for(let t of Object.values(e.jobs))if(Pn(t)){if(Y2(t.uses))return!0;if(Array.isArray(t.steps)){for(let n of t.steps)if(Pn(n)&&(Y2(n.uses)||W2(n.run)||Pn(n.with)&&Object.values(n.with).some(W2)))return!0}}return!1}o(Vpe,"workflowChecksDco");function eq(e){let t=pa.join(e,".github","workflows"),n;try{n=fa.readdirSync(t).filter(i=>/\.ya?ml$/i.test(i)).sort()}catch{return[]}return n.flatMap(i=>{try{return[{file:pa.join(".github","workflows",i),doc:Vi(fa.readFileSync(pa.join(t,i),"utf-8"))}]}catch{return[]}})}o(eq,"workflows");function zpe(e){return!Pn(e)||!Pn(e.jobs)?[]:Object.values(e.jobs).flatMap(t=>Pn(t)&&Array.isArray(t.steps)?t.steps.filter(Pn):[])}o(zpe,"steps");function qpe(e){let t=pa.join(".github","dco.yml");if(fa.existsSync(pa.join(e,t)))return{file:t};let n=eq(e).find(i=>Vpe(i.doc));return n&&{file:n.file}}o(qpe,"signOffRule");var Z2=o(e=>typeof e=="string"?e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean):void 0,"inputList");function Jpe(e){for(let t of eq(e)){let n=zpe(t.doc).find(s=>typeof s.uses=="string"&&s.uses.split("@")[0].trim().toLowerCase()===Gpe);if(!n)continue;let i=Pn(n.with)?n.with:{},r=Z2(i.scopes);return{file:t.file,types:Z2(i.types)??gy,...r?.length?{scopes:r}:{},scopeRequired:i.requireScope===!0||String(i.requireScope).trim()==="true"}}}o(Jpe,"semanticPrTitleRule");var Hpe=["package.json",".commitlintrc",".commitlintrc.json",".commitlintrc.yaml",".commitlintrc.yml",".commitlintrc.js",".commitlintrc.cjs",".commitlintrc.mjs",".commitlintrc.ts",".commitlintrc.cts","commitlint.config.js","commitlint.config.cjs","commitlint.config.mjs","commitlint.config.ts","commitlint.config.cts","commitlint.config.mts"],Ype=["type-enum","scope-enum","scope-empty","subject-case","header-max-length","body-max-line-length"];function tq(e){let t=[];for(let n of e)n==="@commitlint/config-conventional"||n==="@commitlint/config-angular"?t.push(n):t.length=0;return t}o(tq,"knownPresets");var Wpe={Disabled:"0",Warning:"1",Error:"2"};function Zpe(e){return e.replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`|\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g,t=>t.startsWith("/")?t.replace(/[^\r\n]/g," "):t)}o(Zpe,"withoutComments");function K2(e,t){let n=new RegExp(`["']?${t}["']?\\s*:\\s*`).exec(e);if(!n)return;let i=n.index+n[0].length;if(e[i]!=="[")return null;let r=0;for(let s=i;s<e.length;s++)if(e[s]==="[")r++;else if(e[s]==="]"&&--r===0){if(!/^\s*(?:as\s+const\s*)?(?:[,}]|$)/.test(e.slice(s+1)))return null;let a=e.slice(i,s+1).replace(/\bRuleConfigSeverity\.(\w+)/g,(u,l)=>Wpe[l]??u).replace(/,(\s*\])/g,"$1"),c=a.replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/g,'""');try{return JSON.parse(c),Vi(a)}catch{return null}}}o(K2,"ruleFromSource");var nq=o(e=>Object.fromEntries(Ype.map(t=>[t,e(t)])),"pickRules");function X2(e,t){if(!Pn(t))return;let n=[].concat(t.extends??[]),i=Pn(t.rules)?t.rules:{};return{file:e,presets:tq(n),rules:nq(r=>i[r])}}o(X2,"configFromObject");function Kpe(e){for(let t of Hpe){let n;try{n=fa.readFileSync(pa.join(e,t),"utf-8")}catch{continue}if(/\.[cm]?[jt]s$/.test(t)){let r=Zpe(n),s=/(?:^|[,{])\s*["']?extends["']?\s*:\s*/.exec(r),a=s?K2(r.slice(s.index),"extends"):void 0,c=s?/^(["'])([^"']+)\1\s*(?:[,}]|$)/.exec(r.slice(s.index+s[0].length))?.[2]:void 0,u=Array.isArray(a)?a:c?[c]:[];return{file:t,presets:tq(u),rules:nq(l=>K2(r,l))}}let i;try{i=Vi(n)}catch{return}if(t!=="package.json")return X2(t,i);if(Pn(i)&&Pn(i.commitlint))return X2(t,i.commitlint)}}o(Kpe,"commitlintConfig");function ku(e){if(!Array.isArray(e))return;let t=Number(e[0]);if(t===1||t===2)return[String(e[1]??"always"),e[2]]}o(ku,"ruleWhenOn");var o$=o(e=>Array.isArray(e)&&e.every(t=>typeof t=="string")?e:void 0,"stringList");function Xpe(e,t){if(!e)return t?"not-capitalized":void 0;let[n,i]=e,r=typeof i=="string"?[i]:o$(i)??[];if(n==="always"&&r.length===1&&r[0]==="lower-case")return"lower-case";if(n==="always"&&r.length===1&&r[0]==="sentence-case")return"sentence-case";if(n==="never"&&r.some(s=>["sentence-case","start-case","pascal-case","upper-case"].includes(s)))return"not-capitalized"}o(Xpe,"subjectCaseOf");function efe(e){let t=Kpe(e);if(!t)return;let{file:n,rules:i}=t,r=t.presets.at(-1)==="@commitlint/config-angular",s=o(C=>t.presets.length>0&&i[C]===void 0,"preset"),a=ku(i["type-enum"]),c=a?.[0]==="always"?o$(a[1]):s("type-enum")?r?jpe:gy:void 0,u=c===void 0,l=c??gy;u&&console.warn(`[commit-rules] ${n}: allowed commit types could not be read; using a conventional header fallback. Additional preset rules may still reject it.`);let A=ku(i["scope-enum"]),p=A?.[0]==="always"?o$(A[1]):void 0,g=o((C,I)=>{let b=ku(i[C]);return b?typeof b[1]=="number"?b[1]:void 0:s(C)?I:void 0},"limit"),h=Xpe(ku(i["subject-case"]),s("subject-case")),y=g("header-max-length",r?72:100)??(u&&i["header-max-length"]===void 0?Ui:void 0),E=g("body-max-line-length",t.presets.includes("@commitlint/config-conventional")?100:void 0);return{file:n,types:l,...u?{typesFromFallback:!0}:{},...u&&!h&&i["subject-case"]===void 0?{fallbackSubjectCase:"not-capitalized"}:{},...p?.length?{scopes:p}:{},scopeRequired:ku(i["scope-empty"])?.[0]==="never",...ku(i["scope-empty"])?.[0]==="always"?{scopeForbidden:!0}:{},...h?{subjectCase:h}:{},...y?{headerMaxLength:y}:{},...E?{bodyMaxLineLength:E}:{}}}o(efe,"commitlintRule");function rq(e){let t=qpe(e),n=efe(e),i=Jpe(e);return{...t?{signOff:t}:{},...n?{commitlint:n}:{},...i?{prTitle:i}:{}}}o(rq,"readCommitRules");function tfe(e){let t=[e.commitlint,e.prTitle].filter(a=>!!a);if(!t.length)return;let n=t.map(a=>a.types).reduce((a,c)=>a.filter(u=>c.includes(u)));n.length||console.warn(`[commit-rules] ${t.map(a=>a.file).join(", ")}: no common commit type; using ${t[0].types.join(", ")} from ${t[0].file}. This may fail another rule.`);let i=t.map(a=>a.subjectCase),r=i.includes("lower-case")?"lower-case":i.find(a=>a!==void 0)??t.find(a=>a.fallbackSubjectCase)?.fallbackSubjectCase,s=Math.min(...t.map(a=>a.bodyMaxLineLength??1/0));return{rules:t,types:n.length?n:t[0].types,scopeRequired:t.some(a=>a.scopeRequired),...r?{subjectCase:r}:{},headerMaxLength:Math.min(Ui,...t.map(a=>a.headerMaxLength??1/0)),...Number.isFinite(s)?{bodyMaxLineLength:s}:{}}}o(tfe,"mergedHeaderRules");function hy(e,t){return e.scopeForbidden?!1:e.scopes?e.scopes.some(n=>{if(n===t)return!0;try{return new RegExp(`^(?:${n})$`).test(t)}catch{return!1}}):!0}o(hy,"allowsScope");function nfe(e,t){let n=e.find(s=>s.scopes)?.scopes??[],i=n.filter(s=>/^[\w./-]+$/.test(s)&&e.every(a=>hy(a,s)));if(!i.length)return e.every(s=>hy(s,"tests"))||console.warn(`[commit-rules] ${e.map(s=>s.file).join(", ")}: no usable required scope; using tests, which may fail the declared scope rules (${n.join(", ")}).`),"tests";let r=o(s=>t.some(a=>a.startsWith(`${s}/`)||a.split("/").slice(0,-1).includes(s)),"under");return[...i].filter(r).sort((s,a)=>a.length-s.length)[0]??i[0]}o(nfe,"pickScope");var iq=/^([A-Za-z][\w-]*)(?:\(([^)]*)\))?!?:\s*(.*)$/,rfe=o(e=>e.split(/(`.*?`|".*?"|'.*?')/).map((t,n)=>n%2?t:t.toLowerCase()).join(""),"lowerOutsideQuotes");function sq(e,t){return t==="lower-case"?rfe(e):t==="sentence-case"?e.charAt(0).toUpperCase()+e.slice(1):t==="not-capitalized"&&/^[A-Z]/.test(e)?e.replace(/^\S+/,n=>n.toLowerCase()):e}o(sq,"withSubjectCase");function ife(e,t){return sq(e.trim().replace(/\.+$/,"").trim()||"add tests",t)}o(ife,"conformSubject");function oq(e,t){let[n,...i]=e.replace(/\s+$/,"").split(`
|
|
169
169
|
`),r=iq.exec(n);return[t.commitlint,t.prTitle].every(s=>{if(!s)return!0;if(!s.typesFromFallback&&(!r||!s.types.includes(r[1]))||s.headerMaxLength&&n.length>s.headerMaxLength)return!1;let a=s.bodyMaxLineLength;if(a&&i.some(u=>u.length>a&&!/\bhttps?:\/\/\S+/.test(u)))return!1;let c=r?.[2];if(s.scopeRequired&&!c||c&&!hy(s,c)||r&&!r[3].trim())return!1;if(s.subjectCase){if(!r)return!1;let u=r[3],l=u.replace(/`.*?`|".*?"|'.*?'/g,"").trim();if(/^[\p{Ll}\p{Lu}\p{Lt}]/u.test(u)&&!/^\d/.test(l)&&sq(l,s.subjectCase)!==l)return!1}return!0})}o(oq,"matchesCommitRules");function sfe(e,t){if(e.length<=t)return e;let n=e.slice(0,t-1),i=n.lastIndexOf(" ");return`${(i>0?n.slice(0,i):n).replace(/[\s.,;:]+$/,"")}\u2026`}o(sfe,"fitSubject");function ofe(e,t){if(e.length<=t)return[e];let n=/^\s*/.exec(e)?.[0]??"",i=[],r="";for(let s of e.trim().split(/\s+/))r&&r.length+1+s.length>t?(i.push(r),r=n+s):r?r=`${r} ${s}`:r=n+s;return r&&i.push(r),i}o(ofe,"wrap");function aq(e,t,n){let i=tfe(t);if(!i)return e;let[r,...s]=e.replace(/\s+$/,"").split(`
|
|
170
170
|
`),a=iq.exec(r.trim()),c=a&&[...gy,...i.types].some(b=>b.toLowerCase()===a[1].toLowerCase())?a:null,u=c?.[1].toLowerCase(),l=c?c[3]:r.replace(/^\s*Skyramp Testbot:\s*/i,""),A=c?.[2]?.trim()||void 0;A&&t.commitlint&&!t.commitlint.scopes&&(A=A.toLowerCase());let p=[u,"test","chore"].find(b=>!!b&&i.types.includes(b))??i.types[0],g=A&&i.rules.every(b=>hy(b,A))?A:void 0;!g&&i.scopeRequired&&(g=nfe(i.rules,n));let h=g?`${p}(${g}): `:`${p}: `,y=h+sfe(ife(l,i.subjectCase),i.headerMaxLength-h.length),E=s.join(`
|
|
@@ -178,12 +178,12 @@ ${I.join(`
|
|
|
178
178
|
|
|
179
179
|
${n}`}o(my,"withSignOff");function a$(e){let t=/\b(claude|anthropic)\b/i;return e.split(`
|
|
180
180
|
`).filter(i=>{let r=i.trim();return!(/^co-authored-by:/i.test(r)&&t.test(r))&&!(/^[^\w\s]*\s*generated (?:with|by) /i.test(r)&&t.test(r))}).join(`
|
|
181
|
-
`).replace(/\s+$/,"")}o(a$,"stripAgentAttribution");var yy="Skyramp-Pull-Request",Su="Skyramp-Delivery-Base",c$="Skyramp-Tested-Revision";var
|
|
181
|
+
`).replace(/\s+$/,"")}o(a$,"stripAgentAttribution");var yy="Skyramp-Pull-Request",Su="Skyramp-Delivery-Base",c$="Skyramp-Tested-Revision";var A1e=["%H","%P","%an","%ae","%ce",`%(trailers:key=${yy},valueonly,separator=%x2C)`,"%s",`%(trailers:key=${Su},valueonly,separator=%x2C)`,`%(trailers:key=${c$},valueonly,separator=%x2C)`];function cq(e,t){let n=e(["log","-1","--format=%B"]);if(!n.includes(`${yy}:`)&&!n.includes(`${Su}:`))return;let i=n.split(`
|
|
182
182
|
`).filter(a=>!a.startsWith(`${Su}:`)).join(`
|
|
183
183
|
`).trimEnd(),r=t?`${i}
|
|
184
184
|
${Su}: ${t}`:i;e(["log","-1","--format=%(trailers:key=Signed-off-by,valueonly)"]).split(`
|
|
185
|
-
`).some(a=>a.trim().toLowerCase()===`${ws} <${Lo}>`.toLowerCase())&&(r=my(r,{name:ws,email:Lo})),e(["-c",`user.name=${ws}`,"-c",`user.email=${Lo}`,"commit","--amend","--allow-empty","-m",r])}o(cq,"amendDeliveryBase");var Ey=Se(require("fs")),nr=Se(require("path"));var
|
|
186
|
-
`)+1||r.length),a=lq(s);for(let c of n)a.delete(c);return{name:qM(i.key,Vb([i])),key:i.key,runs:a,words:u$(s).map(c=>c.word)}})}o(fq,"requirementTexts");var
|
|
185
|
+
`).some(a=>a.trim().toLowerCase()===`${ws} <${Lo}>`.toLowerCase())&&(r=my(r,{name:ws,email:Lo})),e(["-c",`user.name=${ws}`,"-c",`user.email=${Lo}`,"commit","--amend","--allow-empty","-m",r])}o(cq,"amendDeliveryBase");var Ey=Se(require("fs")),nr=Se(require("path"));var g1e=5*1024*1024;function cfe(e){try{return Ey.lstatSync(e),!0}catch{return!1}}o(cfe,"lexists");function uq(e){let t=Ve(e,"adapt.json"),n=Ve(e,"finalize.json"),i=Ve(e,FA),r=new Map,s=o(A=>{let p=Rc(e.inputs,A);if("error"in p)return;let g=r.get(p.source.path)??{source:p.source,paths:new Set};return r.set(p.source.path,g),{repo:g.source.path,paths:g.paths}},"pathsOf"),a=o((A,p)=>nr.relative(A,nr.resolve(A,p.trim())).replace(/\/+$/,""),"norm"),c=o((A,p)=>{let g=p?.trim()&&s(A);if(!g)return;let h=a(g.repo,p);g.paths.add(h);for(let y of["__init__.py","conftest.py"]){let E=nr.join(nr.dirname(h),y);Ey.existsSync(nr.join(g.repo,E))&&g.paths.add(E)}},"addTest"),u=o((A,p)=>{if(typeof p!="string"||!p.trim())return;let g=s(A);if(!g)return;let h=a(g.repo,p);if(QA(nr.join(g.repo,h)))return g.paths.add(h),{...g,rel:h}},"addEdited");for(let A of[...t?.items??[],...i?.tests??[],...i?.maintained??[]])c(A.repository,A.file);for(let A of n?.dependencies?.added??[]){let p=u(A.repository,A.manifest);if(p)for(let g of Qx(p.repo,Km(p.repo,p.rel)))p.paths.add(g)}for(let A of n?.lint??[])for(let p of A.fixed??[])u(A.repository,p);for(let A of n?.support??[])u(A.repository,A.file);let l=Ve(e,Xm)?.packages??[];for(let A of new Set(l.map(p=>p.repository))){let p=s(A),g=l.filter(h=>h.repository===A).map(h=>h.dir);if(p)for(let{path:h}of qx(p.repo)){let y=a(p.repo,h),E=nr.join(p.repo,y);ey(y,g)&&!Rx(y)&&(!cfe(E)||QA(E))&&p.paths.add(y)}}return new Map([...r.values()].map(({source:A,paths:p})=>[A,[...p].filter(g=>g&&g!==".."&&!g.startsWith(`..${nr.sep}`)&&!Fm(g))]))}o(uq,"deliverAllowlist");var dq=Se(require("fs"));var Aq=2*1024*1024;function ufe(e){let t=[];for(let n of e??[])if(n.state==="read")try{t.push({item:n,text:dq.readFileSync(zO(n),"utf-8")})}catch{}return t}o(ufe,"readItemTexts");var LA=6,lfe=/[\p{L}\p{N}]+/gu,dfe=new RegExp("(?<=\\p{Ll})(?=\\p{Lu})|(?<=\\p{Lu})(?=\\p{Lu}\\p{Ll})","u");function u$(e){let t=[];for(let n of e.matchAll(lfe)){let i=n.index;for(let r of n[0].split(dfe))t.push({word:r.toLowerCase(),start:i,end:i+r.length}),i+=r.length}return t}o(u$,"wordsOf");var pq=o((e,t)=>e.slice(t,t+LA).map(n=>n.word).join(" "),"runAt");function lq(e){let t=u$(e),n=new Set;for(let i=0;i+LA<=t.length;i++)n.add(pq(t,i));return n}o(lq,"runsOf");function fq(e,t=[]){let n=new Set(t.flatMap(i=>[...lq(i)]));return ufe(e).map(({item:i,text:r})=>{let s=i.source==="other"?r:r.slice(r.indexOf(`
|
|
186
|
+
`)+1||r.length),a=lq(s);for(let c of n)a.delete(c);return{name:qM(i.key,Vb([i])),key:i.key,runs:a,words:u$(s).map(c=>c.word)}})}o(fq,"requirementTexts");var $1e=LA/2;var Afe=o(e=>e.criteria.size?`${e.text.name} ${[...e.criteria].sort((t,n)=>t-n).map(t=>`AC${t}`).join(", ")}`:e.text.name,"copyName");function pfe(e,t){if(t.length===0)return[];let n=u$(e),i=[];for(let r=0;r+LA<=n.length;r++){let s=pq(n,r),a=t.find(p=>p.runs.has(s));if(!a)continue;let c=n[r].start,u=n[r+LA-1].end,l=a.criteria?.get(s)??[],A=i.at(-1);if(A&&c<=A.end){if(A.end=Math.max(A.end,u),A.text===a)for(let p of l)A.criteria.add(p)}else i.push({start:c,end:u,text:a,criteria:new Set(l)})}return i.map(r=>({start:r.start,end:r.end,name:Afe(r)}))}o(pfe,"copies");function Iy(e,t){let n=e;for(let i of pfe(e,t).reverse())n=`${n.slice(0,i.start)}(see ${i.name})${n.slice(i.end)}`;return n}o(Iy,"withoutRequirementText");function ffe(e,t,n){for(let i=t+1;i<e.length;i++){let r=e[i];if(r==="\\")i++;else{if(r===n)return i+1;if(r===`
|
|
187
187
|
`&&n!=="`")return i}}return e.length}o(ffe,"stringEnd");function gfe(e,t){let n=e.lastIndexOf(`
|
|
188
188
|
`,t-1)+1;if(e.slice(n,t).trim()!=="")return!1;let i=e.slice(0,n).trimEnd();return i===""||i.endsWith(":")}o(gfe,"isDocstring");function hfe(e){let t=[],n=o(r=>(e.indexOf(`
|
|
189
189
|
`,r)+1||e.length+1)-1,"lineEnd"),i=0;for(;i<e.length;){let r=e[i],s=e[i+1],a=i+1;if(r==="/"&&s==="*")a=e.indexOf("*/",i+2)<0?e.length:e.indexOf("*/",i+2)+2,t.push({start:i,end:a});else if(r==="/"&&s==="/"&&!/[:\w]/.test(e[i-1]??"")||r==="#"&&/^\s?$/.test(e[i-1]??"")&&!/[!{[]/.test(s??""))a=n(i),t.push({start:i,end:a});else if((r==='"'||r==="'")&&e.startsWith(r.repeat(3),i)){let c=e.indexOf(r.repeat(3),i+3);a=c<0?e.length:c+3,gfe(e,i)&&t.push({start:i,end:a})}else(r==='"'||r==="'"||r==="`")&&(a=ffe(e,i,r));i=a}return t}o(hfe,"commentRanges");var mfe=/\b(?:test|it|describe|context|suite|scenario|specify|Run|DisplayName)(?:\.\w+)*(?:\.each\s*(?:\((?:[^()]|\([^()]*\))*\)|`[^`]*`))?\s*\(\s*("(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`)/g;function yfe(e,t){return[...e.matchAll(mfe)].flatMap(n=>{if(t.some(r=>n.index>=r.start&&n.index<r.end))return[];let i=n.index+n[0].length;return[{start:i-n[1].length,end:i}]})}o(yfe,"titleRanges");function gq(e,t){if(t.length===0)return{content:e,cleaned:!1};let n=hfe(e),i=[];for(let c of n){let u=e.slice(c.start,c.end),l=Iy(u,t);l!==u&&i.push({...c,text:l})}let r=yfe(e,n),s=new Set(r.map(c=>e.slice(c.start+1,c.end-1)));for(let c of r){let u=e[c.start],l=e.slice(c.start+1,c.end-1),A=Iy(l,t);if(A===l)continue;let p=A;for(let g=2;s.has(p);g++)p=`${A} (${g})`;s.add(p),i.push({...c,text:`${u}${p}${u}`})}let a=e;for(let c of i.sort((u,l)=>l.start-u.start))a=`${a.slice(0,c.start)}${c.text}${a.slice(c.end)}`;return{content:a,cleaned:a!==e}}o(gq,"withoutRequirementTextInTestFile");function Ife(e){if(!e.inputs.deliver)return{ok:!1,reasons:["deliver not requested (pass --deliver to push)"]};if(!e.platform?.supportsRemote)return{ok:!1,reasons:["deliver needs a remote platform driver (pass --runner-platform github)"]};let t=Ve(e,"finalize.json");return t?t.ready!==!0?{ok:!1,reasons:[`finalize reported ready:false \u2014 not pushing (blockers: ${ad(t)||"unspecified"})`]}:{ok:!0,reasons:[]}:{ok:!1,reasons:["finalize.json not found \u2014 refusing to push unverified tests"]}}o(Ife,"validateDeliverInput");function Eq(e){return e.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"tests"}o(Eq,"slug");var Cfe="skyramp-testbot/";function bfe(e,t){return t||`${Cfe}${Eq(e)}-tests`}o(bfe,"testsBranchName");function vfe(e,t,n,i){let r=(e??[]).filter(a=>a.repository.toLowerCase()===t.toLowerCase());if(!r.length&&i){let a=i.repository,c=[i.targetId,a.provider,a.providerAccountId,a.providerRepositoryId,i.number,t.toLowerCase(),n];return(0,jA.createHash)("sha256").update(JSON.stringify(c)).digest("hex").slice(0,32)}let s=r.length?[...new Set(r.map(a=>`${a.repository.toLowerCase()}#${a.number}`))].sort():[`branch ${n}`];return(0,jA.createHash)("sha256").update(s.join(`
|
|
@@ -195,9 +195,9 @@ ${Su}: ${t}`:i;e(["log","-1","--format=%(trailers:key=Signed-off-by,valueonly)"]
|
|
|
195
195
|
${n}`}:{prFailure:"unknown",prDetail:t}}o(Dfe,"thrownFailure");async function _fe(e,t,n,i,r,s){let a=i.slug,c=i.path,u=Ve(e,"finalize.json"),l=fq(e.inputs.requirementItems),A=rq(c),p=Ve(e,"write.json"),g=p?.commit?.message||Ve(e,"generate-unit.json")?.commitMessage,h=i.working,y=o(wt=>wt.split(`
|
|
196
196
|
`)[0],"subjectOf"),E=o(wt=>Iy(a$(wt),l),"publicText"),C=o((wt,Wt)=>h&&!!Wt&&E(wt).trim()===E(Wt).trim(),"authored"),I=o((wt,Wt,rr)=>{let at=E(wt);return rr&&oq(at,Wt)?at:aq(at,Wt,r)},"conform"),b=u?.commit?.message||n.commitMessage||"Skyramp Testbot: add tests",D=I(b,{commitlint:A.commitlint},C(b,g)),N=J2(e.outputsDir)??n,W=h?u?.pr?.title||n.prTitle||p?.commit?.prTitle:void 0,K=W||b,pe=h?N.prTitle:void 0,Fe=y(E(K))===y(E(b)),et=(!h||!n.prTitle)&&Fe?N.commitMessage:void 0,P=pe||et||K,ee=p?.commit?.prTitle||(g?y(g):void 0),Y=C(K,ee),se=A.prTitle?{prTitle:A.prTitle}:Y&&W&&!Fe?{}:{commitlint:A.commitlint},ye=y(I(P,se,Y)),G={name:ws,email:Lo},M=!!A.signOff;if(!M&&t?.listCommitChecks){let wt=s?.headSha??Ht(c,["rev-parse","HEAD"]);try{M=(await t.listCommitChecks({repository:a,revision:wt}))?.records.some(rr=>rr.name.trim().toLowerCase()==="dco"&&rr.headSha===wt&&(!rr.repository||rr.repository.toLowerCase()===a.toLowerCase()))??!1}catch{console.warn(`[deliver] could not read commit checks for ${a}`)}}let st=e.inputs.deliverRemote||"origin",ze=hq(c,Iq),Mn=hq(c,Cq);if(ze&&!Mn)throw new Error(`${a}: the checkout records a merged base but not what it merged`);let ot=ze?l$(void 0,void 0,c):s?s.headBranch||l$(e.inputs.headBranch,e.inputs.baseBranch,c):l$(void 0,void 0,c),Yt=e.inputs.pullRequests;s?.prNumber!=null&&!Yt?.some(wt=>wt.repository.toLowerCase()===a.toLowerCase())&&(Yt=[...Yt??[],{repository:a,number:String(s.prNumber)}]);let Dt=Yt?.some(wt=>wt.repository.toLowerCase()===a.toLowerCase())?void 0:e.inputs.deliveryOrigin,tt=ze||!Dt?Mn:void 0,In=e.inputs.scheduledDelivery,lt=In?(0,jA.createHash)("sha256").update(JSON.stringify([In,a.toLowerCase(),ot])).digest("hex"):tt?wfe(a,ot,tt):vfe(Yt,a,ot,Dt),Cn=bfe(ot,e.inputs.deliverBranch)+(In?`-scheduled-${lt}`:tt?`-merge-${lt}`:Dt?`-source-${Dt.number}-${lt}`:"");return{texts:l,shown:N,title:ye,unsigned:D,bot:G,signOff:M,remote:st,base:ot,owner:lt,testsBranch:Cn,origin:Dt,mergedBase:ze}}o(_fe,"planCommit");function Nfe(e,t,n,i){let r=Ht(e,["interpret-trailers","--trailer",`${yy}: ${t.owner}`,"--trailer",`${Su}: ${n}`,"--trailer",`${c$}: ${i}`],`${t.unsigned}
|
|
197
197
|
`);return t.signOff?my(r,t.bot):r}o(Nfe,"trailedMessage");async function Ufe(e,t,n,i,r,s){let a=k2(i.path,e.runDir),c=process.env.PATH;a.dir&&(process.env.PATH=S2(a).PATH);try{return await Ffe(e,t,n,i,r,s)}finally{a.dir&&(process.env.PATH=c),a.cleanup()}}o(Ufe,"deliverOne");async function Ffe(e,t,n,i,r,s){let a=i.slug,c,u=!1,l;try{let A=i.path,p=await _fe(e,t,n,i,r,s),{texts:g,shown:h,title:y,bot:E,remote:C,base:I,owner:b,testsBranch:D,origin:N,mergedBase:W}=p,K=a$(H2(q2(kfe(h,e,i),{audience:"testbot-pr",runUrl:e.inputs.skyrampRunUrl??t.runUrl,requestedBy:e.inputs.requestedBy,sourcePullRequest:N&&`${N.repository.namespace}/${N.repository.name}#${N.number}`}),e.inputs.skyrampRunUrl))+`
|
|
198
|
-
`,pe=s?"pr-body.md":`pr-body-${Eq(a)}.md`,Fe=Vs.join(e.outputsDir,pe);Pr.writeFileSync(Fe,K);let et=Ht(A,["rev-parse","HEAD"]),P=W??et;Ht(A,["checkout","-B",D]),c=D,Ht(A,["reset"]);for(let M of r)Bfe(Vs.join(A,M),g);let ee=[];for(let M of r)try{Ht(A,["--literal-pathspecs","add","--",M])}catch{ee.push(M)}try{Ht(A,["diff","--cached","--quiet"])}catch{try{let M=Nfe(A,p,et,P);Ht(A,["-c",`user.name=${E.name}`,"-c",`user.email=${E.email}`,"commit","-m",M])}catch(M){throw new Cy(M)}u=!0}l=Ht(A,["rev-parse","HEAD"]);let Y,se=W??s?.headSha;if(u&&se&&se!==et){let M=!1;try{Ht(A,["checkout","-q","-B",c,se]),M=!0,Ht(A,["-c",`user.name=${E.name}`,"-c",`user.email=${E.email}`,"cherry-pick","--keep-redundant-commits",l]),M=!1,cq(st=>Ht(A,st),se),l=Ht(A,["rev-parse","HEAD"])}catch(st){try{Ht(A,["cherry-pick","--abort"])}catch{}Ht(A,["checkout","-q","-B",c,l]);let ze=Vl(Co(st),1/0);if(W&&!M)throw st;if(W)return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:C,base:I,committed:u,commitSha:l,pushed:!1,prAction:"skipped",prTitle:y,unstaged:ee,reason:`the tests do not apply to ${I} at ${W.slice(0,12)} without the merged revisions (${ze}), so no tests PR was opened`}};Y=`tests committed on the checkout's merge commit (re-cut onto ${se.slice(0,12)} failed: ${ze})`}}let ye=s?{}:{repositoryPath:A,repoSlug:a,devPr:null};if(!u){let M=await t.markTestsPrUnchanged({branch:c,...ye});return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:C,base:I,committed:!1,commitSha:l,pushed:!1,prAction:M.action==="unchanged"?"unchanged":"skipped",prUrl:M.url,prTitle:y,unstaged:ee,reason:M.action==="unchanged"?"no test changes to commit \u2014 existing tests PR annotated as unchanged":"no test changes to commit \u2014 nothing pushed, no PR opened"}}}let G=await t.publishTestsPr({repositoryPath:A,...ye,remote:C,branch:c,base:I,commitSha:l,title:y,bodyFile:Fe,mode:e.inputs.deliverMode,deliveryOwner:b,...e.inputs.firstQualification?{firstQualification:!0}:{},runUrl:e.inputs.skyrampRunUrl,signal:e.signal,deadlineMs:e.deadlineMs});return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:C,base:G.base,requestedBase:I,committed:u,commitSha:l,pushed:G.pushed,...G.pushedCommits?{pushedCommits:G.pushedCommits}:{},...G.deliveredCommit?{deliveredCommit:G.deliveredCommit}:{},prAction:G.action,...G.retargetedAs?{retargetedAs:G.retargetedAs}:{},prUrl:G.url,prTitle:y,...G.failure?{prFailure:G.failure,prDetail:G.detail}:{},...Y?{cutNote:Y}:{},...G.action==="skipped"&&G.detail?{reason:G.detail}:{},unstaged:ee}}}catch(A){return{thrown:!0,record:{schemaVersion:1,repository:a,branch:c,committed:u,commitSha:l,pushed:!1,prAction:"failed",...Dfe(A),unstaged:[]}}}}o(Ffe,"deliverRepository");var
|
|
198
|
+
`,pe=s?"pr-body.md":`pr-body-${Eq(a)}.md`,Fe=Vs.join(e.outputsDir,pe);Pr.writeFileSync(Fe,K);let et=Ht(A,["rev-parse","HEAD"]),P=W??et;Ht(A,["checkout","-B",D]),c=D,Ht(A,["reset"]);for(let M of r)Bfe(Vs.join(A,M),g);let ee=[];for(let M of r)try{Ht(A,["--literal-pathspecs","add","--",M])}catch{ee.push(M)}try{Ht(A,["diff","--cached","--quiet"])}catch{try{let M=Nfe(A,p,et,P);Ht(A,["-c",`user.name=${E.name}`,"-c",`user.email=${E.email}`,"commit","-m",M])}catch(M){throw new Cy(M)}u=!0}l=Ht(A,["rev-parse","HEAD"]);let Y,se=W??s?.headSha;if(u&&se&&se!==et){let M=!1;try{Ht(A,["checkout","-q","-B",c,se]),M=!0,Ht(A,["-c",`user.name=${E.name}`,"-c",`user.email=${E.email}`,"cherry-pick","--keep-redundant-commits",l]),M=!1,cq(st=>Ht(A,st),se),l=Ht(A,["rev-parse","HEAD"])}catch(st){try{Ht(A,["cherry-pick","--abort"])}catch{}Ht(A,["checkout","-q","-B",c,l]);let ze=Vl(Co(st),1/0);if(W&&!M)throw st;if(W)return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:C,base:I,committed:u,commitSha:l,pushed:!1,prAction:"skipped",prTitle:y,unstaged:ee,reason:`the tests do not apply to ${I} at ${W.slice(0,12)} without the merged revisions (${ze}), so no tests PR was opened`}};Y=`tests committed on the checkout's merge commit (re-cut onto ${se.slice(0,12)} failed: ${ze})`}}let ye=s?{}:{repositoryPath:A,repoSlug:a,devPr:null};if(!u){let M=await t.markTestsPrUnchanged({branch:c,...ye});return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:C,base:I,committed:!1,commitSha:l,pushed:!1,prAction:M.action==="unchanged"?"unchanged":"skipped",prUrl:M.url,prTitle:y,unstaged:ee,reason:M.action==="unchanged"?"no test changes to commit \u2014 existing tests PR annotated as unchanged":"no test changes to commit \u2014 nothing pushed, no PR opened"}}}let G=await t.publishTestsPr({repositoryPath:A,...ye,remote:C,branch:c,base:I,commitSha:l,title:y,bodyFile:Fe,mode:e.inputs.deliverMode,deliveryOwner:b,...e.inputs.firstQualification?{firstQualification:!0}:{},runUrl:e.inputs.skyrampRunUrl,signal:e.signal,deadlineMs:e.deadlineMs});return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:C,base:G.base,requestedBase:I,committed:u,commitSha:l,pushed:G.pushed,...G.pushedCommits?{pushedCommits:G.pushedCommits}:{},...G.deliveredCommit?{deliveredCommit:G.deliveredCommit}:{},prAction:G.action,...G.retargetedAs?{retargetedAs:G.retargetedAs}:{},prUrl:G.url,prTitle:y,...G.failure?{prFailure:G.failure,prDetail:G.detail}:{},...Y?{cutNote:Y}:{},...G.action==="skipped"&&G.detail?{reason:G.detail}:{},unstaged:ee}}}catch(A){return{thrown:!0,record:{schemaVersion:1,repository:a,branch:c,committed:u,commitSha:l,pushed:!1,prAction:"failed",...Dfe(A),unstaged:[]}}}}o(Ffe,"deliverRepository");var X1e={name:"deliver",timeoutMinutes:5,execute:Rfe,validateInput:o(e=>{let t=Wx(e);return t?{ok:!1,reasons:[t]}:Ife(e)},"validateInput"),requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var bq=Se(require("fs"));var Pfe="SKYRAMP_AZURE_SUPERVISED",Mfe=3;function Ofe(e,t=process.env){t[Pfe]==="1"?bq.writeSync(Mfe,`${JSON.stringify(e)}
|
|
199
199
|
`):process.stdout.write(e.command!==void 0?`${e.command}
|
|
200
|
-
`:e.text??"")}o(Ofe,"writeFrame");function Lfe(e){Ofe({command:e})}o(Lfe,"writeAzureCommand");function vq(e){return e.replace(/%/g,"%AZP25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}o(vq,"escapeData");function jfe(e){return vq(e).replace(/;/g,"%3B").replace(/]/g,"%5D")}o(jfe,"escapeProperty");function Gfe(e,t,n){let i=Object.entries(t).map(([r,s])=>`${r}=${jfe(s)}`).join(";");return`##vso[${e}${i?` ${i}`:""}]${vq(n)}`}o(Gfe,"vsoCommand");function Vfe(e){if(!e)return[];let t=e.split(/\r?\n/).filter(n=>n.trim()&&n!==e);return[e,...t].map(n=>Gfe("task.setsecret",{},n))}o(Vfe,"setSecretLines");function wq(e,t=Lfe){for(let n of Vfe(e))t(n)}o(wq,"azureSetSecret");function VA(e){return e.replace(/\/+$/,"")}o(VA,"withoutTrailingSlash");function d$(e){let t=new URL(e),n=t.pathname.split("/").filter(Boolean);if(n.length)return decodeURIComponent(n[n.length-1]);if(t.hostname.endsWith(".visualstudio.com"))return t.hostname.split(".")[0];throw new Error(`SYSTEM_COLLECTIONURI "${e}" names no organization`)}o(d$,"azureOrganization");var zfe=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,48}[A-Za-z0-9])?$/,qfe=/[\\/:*?"<>|;#${},+=[\]%\p{Cc}\p{Cf}]/u;function Bq(e){return e.length>0&&e.length<=64&&e===e.trim()&&!qfe.test(e)&&!/[^\S ]/u.test(e)&&!/^[._]/.test(e)&&!e.endsWith(".")}o(Bq,"isName");function by(e){return A$(`${e.namespace}/${e.name}`)}o(by,"azureRepositoryOfSource");function A$(e){let t=e.indexOf("/"),n=e.lastIndexOf("/"),i=e.slice(0,t),r=e.slice(t+1,n),s=e.slice(n+1);if(t<0||t===n||!zfe.test(i)||!Bq(r)||!Bq(s))throw new Error(`"${e}" is not an Azure DevOps organization/project/repository`);return{organization:i,project:r,name:s}}o(A$,"azureRepositoryOf");function kq(e,t){let n=d$(e);if(n.toLowerCase()!==t.organization.toLowerCase())throw new Error(`${t.organization}/${t.project}/${t.name} is not in ${n}, the Azure DevOps organization this job runs in`)}o(kq,"inOrganization");function Sq(e,t){return kq(e,t),`${VA(e)}/${encodeURIComponent(t.project)}/_git/${encodeURIComponent(t.name)}`}o(Sq,"azureCloneUrl");function p$(e,t){return kq(e,t),`${VA(e)}/${encodeURIComponent(t.project)}/_apis/git/repositories/${encodeURIComponent(t.name)}`}o(p$,"azureRepositoryApi");var Jfe="7.1",GA=class extends Error{constructor(n,i){super(n);this.status=i}status;static{o(this,"AzureRestError")}};async function f$(e){let t=e.accept??"application/json",n=new URL(e.url);n.searchParams.has("api-version")||n.searchParams.set("api-version",Jfe);let i=await(e.fetch??fetch)(n.toString(),{method:e.method??"GET",headers:{Authorization:`Bearer ${e.token}`,Accept:t,...e.body!==void 0?{"Content-Type":"application/json"}:{}},...e.body!==void 0?{body:JSON.stringify(e.body)}:{},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!i.ok){let r=(await i.json().catch(()=>({}))).message;throw new GA(`Azure DevOps answered ${i.status}${typeof r=="string"?`: ${r}`:""}`,i.status)}return t!=="application/json"?Buffer.from(await i.arrayBuffer()):i.status===204?{}:await i.json()}o(f$,"azureRest");function Hfe(e){return`AUTHORIZATION: bearer ${e}`}o(Hfe,"azureGitAuthorization");function Qq(e,t){return{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${VA(e)}/.extraheader`,GIT_CONFIG_VALUE_0:Hfe(t)}}o(Qq,"azureGitAuthEnv");var Yfe="7.1-preview.1",Wfe=".azure-pipelines/skyramp-testbot-v3.yml";function g$(e){return e.GITHUB_ACTIONS!=="true"&&/^true$/i.test(e.TF_BUILD??"")}o(g$,"isAzurePipelines");function $q(e,t={}){let n=o(p=>{let g=e[p];if(!g)throw new Error(`${p} is not set; the V3 runner handshake needs it`);return g},"read"),i=VA(e.SYSTEM_COLLECTIONURI??""),r=o(()=>d$(n("SYSTEM_COLLECTIONURI")),"organization"),s=e.SYSTEM_TEAMPROJECT,a=e.BUILD_REPOSITORY_NAME,c=e.BUILD_REPOSITORY_ID?.toLowerCase(),u=e.SYSTEM_ACCESSTOKEN,l=t.mask??(p=>wq(p)),A=o(p=>async()=>{if(!p)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_OIDCREQUESTURI to $(System.OidcRequestUri).");if(!u)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_ACCESSTOKEN to $(System.AccessToken).");let g=new URL(p);if(g.protocol!=="https:")throw new Error("SYSTEM_OIDCREQUESTURI is not an https URL");g.searchParams.set("api-version",Yfe);let h=await(t.fetch??fetch)(g.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"Content-Type":"application/json",Accept:"application/json"},body:"{}",redirect:"error",signal:AbortSignal.timeout(3e4)});if(!h.ok)throw new Error(`Azure DevOps refused the OIDC token request: ${h.status}`);let y=(await h.json().catch(()=>({}))).oidcToken;if(typeof y!="string"||!y)throw new Error("Azure DevOps's OIDC token response carried no token");return l(y),y},"mint");return{runnerPlatform:g$(e)?"azure":void 0,workspace:e.BUILD_SOURCESDIRECTORY||void 0,serverUrl:i,apiUrl:i,repository:c&&s&&a&&i?{id:c,slug:`${r()}/${s}/${a}`}:void 0,runId:e.BUILD_BUILDID||void 0,runAttempt:e.SYSTEM_STAGEATTEMPT||void 0,job:e.SYSTEM_JOBNAME||void 0,execution(){let p=n("SYSTEM_STAGEATTEMPT");if(!/^[1-9][0-9]*$/.test(p))throw new Error(`SYSTEM_STAGEATTEMPT is "${p}", not a positive whole number`);let g=n("SYSTEM_COLLECTIONID").toLowerCase();if(!kc.test(g))throw new Error(`SYSTEM_COLLECTIONID is "${g}", not a GUID`);let h=n("BUILD_REPOSITORY_ID").toLowerCase();if(!kc.test(h))throw new Error(`BUILD_REPOSITORY_ID is "${h}", not a GUID`);let y=[r(),n("SYSTEM_TEAMPROJECT"),n("SYSTEM_DEFINITIONID"),n("BUILD_BUILDID")].map(encodeURIComponent).join("/");return{provider:"azure-devops",repository:{provider:"azure-devops",providerAccountId:g,providerRepositoryId:h},providerRunId:y,providerRunAttempt:Number(p),workflowRef:`${Wfe}@${n("BUILD_SOURCEBRANCH")}`}},takeIdToken(){let p=e.SYSTEM_OIDCREQUESTURI;delete e.SYSTEM_OIDCREQUESTURI;let g=A(p);return()=>g()},takeSourceToken(){return delete e.SYSTEM_ACCESSTOKEN,u||void 0},webIdentity(){if(!e.SYSTEM_OIDCREQUESTURI?.trim()||!u)return;let p=A(e.SYSTEM_OIDCREQUESTURI);return{token:o(()=>p(),"token"),runId:e.BUILD_BUILDID}},v3RunsOnly:!0,assumesBedrockRole:!0,namesSourceToMcp:!0,runSettingsFromApp:!0,checkSourceName(p){by(p)},cloneUrl(p){return Sq(i,by(p))},gitAuthEnv(p){return Qq(i,p)},async pullRequest(p,g,h){let y=await f$({token:await h.token(),url:`${p$(i,by(p))}/pullrequests/${g}`,fetch:h.fetch}),E=y.status==="completed";return{...typeof y.title=="string"?{title:y.title}:{},...typeof y.description=="string"?{body:y.description}:{},...typeof y.status=="string"?{merged:E}:{},...E&&typeof y.lastMergeCommit?.commitId=="string"?{mergeCommit:y.lastMergeCommit.commitId}:{},...E&&typeof y.lastMergeSourceCommit?.commitId=="string"?{mergedHead:y.lastMergeSourceCommit.commitId}:{}}},async commit(p,g,h){let y;try{y=p$(i,A$(p))}catch{return{lookup:"unknown"}}try{let E=await f$({token:await h.token(),url:`${y}/commits/${encodeURIComponent(g)}`,fetch:h.fetch});return typeof E.commitId=="string"?{sha:E.commitId}:{lookup:"missing"}}catch(E){return{lookup:E instanceof GA&&(E.status===404||E.status===400)?"missing":"unknown"}}}}}o($q,"azureRunnerHost");Ac();var Zfe=5e3,h$=/^(?!\.\.?$)[A-Za-z0-9._-]{1,100}$/;function Kfe(e){let t=Buffer.from(`x-access-token:${e}`).toString("base64");return Ll(t),`AUTHORIZATION: basic ${t}`}o(Kfe,"githubGitAuthorization");function Tq(e,t={}){let n=o(u=>{let l=e[u];if(!l)throw new Error(`${u} is not set; the V3 runner handshake needs it`);return l},"read"),i=e.GITHUB_REPOSITORY_ID,r=e.GITHUB_REPOSITORY,s=(e.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,""),a=(e.GITHUB_API_URL||"https://api.github.com").replace(/\/+$/,""),c=o(async(u,l)=>l.fetch(u,{headers:{Authorization:`Bearer ${await l.token()}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(3e4)}),"get");return{runnerPlatform:e.GITHUB_ACTIONS==="true"?"github":void 0,workspace:e.GITHUB_WORKSPACE||void 0,serverUrl:s,apiUrl:a,repository:i&&r?{id:i,slug:r}:void 0,runId:e.GITHUB_RUN_ID||void 0,runAttempt:e.GITHUB_RUN_ATTEMPT||void 0,job:e.GITHUB_JOB||void 0,execution(){let u=n("GITHUB_RUN_ATTEMPT");if(!/^[1-9][0-9]*$/.test(u))throw new Error(`GITHUB_RUN_ATTEMPT is "${u}", not a positive whole number`);return{provider:"github",repository:{provider:"github",providerAccountId:n("GITHUB_REPOSITORY_OWNER_ID"),providerRepositoryId:n("GITHUB_REPOSITORY_ID")},providerRunId:n("GITHUB_RUN_ID"),providerRunAttempt:Number(u),workflowRef:n("GITHUB_WORKFLOW_REF")}},takeIdToken(){let u=e.ACTIONS_ID_TOKEN_REQUEST_URL,l=e.ACTIONS_ID_TOKEN_REQUEST_TOKEN;return delete e.ACTIONS_ID_TOKEN_REQUEST_URL,delete e.ACTIONS_ID_TOKEN_REQUEST_TOKEN,async A=>{if(!u||!l)throw new Error("The job cannot request an OIDC token. Give it the `id-token: write` permission.");let p=new URL(u);p.searchParams.set("audience",A);let g=await fetch(p,{headers:{Authorization:`Bearer ${l}`,Accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!g.ok)throw new Error(`GitHub refused the OIDC token request: ${g.status}`);let h=(await g.json().catch(()=>({}))).value;if(typeof h!="string"||!h)throw new Error("GitHub's OIDC token response carried no token");return Ll(h),h}},webIdentity(){return!e.ACTIONS_ID_TOKEN_REQUEST_TOKEN?.trim()||!e.ACTIONS_ID_TOKEN_REQUEST_URL?.trim()?void 0:{token:t.getIDToken??(l=>yM(l)),runId:e.GITHUB_RUN_ID}},v3RunsOnly:!1,assumesBedrockRole:!1,namesSourceToMcp:!1,runSettingsFromApp:!1,checkSourceName(u){for(let l of[u.namespace,u.name])if(!h$.test(l))throw new Error(`"${l}" is not a repository name`)},cloneUrl(u){return`${s}/${u.namespace}/${u.name}.git`},gitAuthEnv(u){return u?{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${s}/.extraheader`,GIT_CONFIG_VALUE_0:Kfe(u)}:{}},async pullRequest({namespace:u,name:l},A,p){if(![u,l].every(y=>h$.test(y)))throw new Error("the repository name is not valid");let g=await c(`${a}/repos/${u}/${l}/pulls/${A}`,p);if(!g.ok)throw new Error(`GitHub answered ${g.status}`);let h=await g.json();return{...typeof h.title=="string"?{title:h.title}:{},...typeof h.body=="string"?{body:h.body}:{},...typeof h.merged=="boolean"?{merged:h.merged}:{},...h.merged===!0&&typeof h.merge_commit_sha=="string"?{mergeCommit:h.merge_commit_sha}:{},...h.merged===!0&&typeof h.head?.sha=="string"?{mergedHead:h.head.sha}:{}}},async commit(u,l,A){let[p,g,...h]=u.split("/");if(h.length||![p,g].every(y=>y!==void 0&&h$.test(y)))return{lookup:"unknown"};try{let y=await c(`${a}/repos/${p}/${g}/commits/${encodeURIComponent(l)}`,A);if(y.status===404||y.status===422)return{lookup:"missing"};if(!y.ok)return{lookup:"unknown"};let E=await y.json();return typeof E.sha=="string"?{sha:E.sha}:{lookup:"missing"}}catch{return{lookup:"unknown"}}},async revokeToken(u,l){let A=await l(`${a}/installation/token`,{method:"DELETE",headers:{Authorization:`Bearer ${u}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(Zfe)});if(!A.ok&&A.status!==401)throw new Error(`GitHub answered ${A.status}`)}}}o(Tq,"githubRunnerHost");function Dq(e=process.env){return g$(e)?$q(e):Tq(e)}o(Dq,"runnerHost");var Xfe=10*6e4;function ege(e,t){return e.getTime()-t.getTime()-Xfe}o(ege,"remainingBudgetMs");var _q="This attempt revoked its scoped GitHub credentials; it mints no more.",tge=10*6e4;var nge=o(e=>!!e&&Object.keys(e).length===1&&e.contents==="read","onlyReads"),rge=3e4,ige=3,Nq=30,Mr=class extends Error{constructor(n,i,r,s){super(n);this.status=i;this.code=r;this.path=s}status;code;path;static{o(this,"AppRefusal")}},fi=class extends Error{static{o(this,"AppUnreachable")}},Ru=class extends fi{static{o(this,"AppNotReady")}},m$=class extends Ru{static{o(this,"RunnerProviderNotReady")}};function y$(e){let t;try{t=new URL(e)}catch{throw new Error(`skyrampAppOrigin "${e}" is not a URL`)}if(t.protocol!=="https:"||t.origin!==e.replace(/\/+$/,""))throw new Error(`skyrampAppOrigin must be an https origin, got "${e}"`);return t.origin}o(y$,"appOrigin");function Fq(e,t){if(!kc.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}o(Fq,"routeId");function sge(e,t){return`${e.replace(/\/+$/,"")}/runs/${t}`}o(sge,"skyrampRunPageUrl");function Pq(e,t,n,i){throw t<500&&t!==429?new Mr(e,t,n,i):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new m$(e):t===503&&n==="RUN_NOT_READY"?new Ru(e):new fi(e)}o(Pq,"refusedOrUnreachable");async function Mq(e,t,n,i,r,s=1/0){let a=y$(e.origin),c=`The time limit for ${t} ${n} was reached`,u,l=0;for(let A=1;A<=ige||u instanceof Ru;A+=1){if(u instanceof Ru){if(l===Nq)throw u;l+=1,A-=1,e.log?.(`${u.message}; trying again (${l} of ${Nq}).`),await new Promise(p=>setTimeout(p,Math.max(0,Math.min(e.readyWaitMs??1e4,s-Date.now()))))}else A>1&&await new Promise(p=>setTimeout(p,Math.max(0,Math.min((e.retryDelayMs??2e3)*(A-1),s-Date.now()))));if(Date.now()>=s)throw new fi(c);try{let p,g=await(Number.isFinite(s)?Promise.race([e.idToken(a),new Promise((y,E)=>{p=setTimeout(()=>E(new fi(c)),Math.max(1,s-Date.now()))})]).finally(()=>{p&&clearTimeout(p)}):e.idToken(a));if(Date.now()>=s)throw new fi(c);let h=await(e.fetch??fetch)(new URL(n,a).toString(),{...i(g),redirect:"error",signal:AbortSignal.timeout(Math.max(1,Math.min(rge,s-Date.now())))}).catch(y=>{throw new fi(y instanceof Error?y.message:String(y),{cause:y})});return await r(h)}catch(p){if(p instanceof Mr||Date.now()>=s)throw p;u=p}}throw u}o(Mq,"callWithRetries");function Oq(e,t,n,i,r){let s=i.headers.get("cf-ray");e.log?.(`Testbot V3: ${t} ${n} answered ${i.status}${s?`, cf-ray ${s}`:""}: ${r.replace(/\s+/g," ").slice(0,200)}`)}o(Oq,"logRefusal");function vy(e,t,n,i,r){let s=t==="GET"?void 0:JSON.stringify(i),a=t==="PUT"&&/^\/api\/v1\/runner\/attempts\/[^/]+\/report$/.test(n)&&s!==void 0&&Buffer.byteLength(s,"utf8")>Rg;if(a&&Buffer.byteLength(s,"utf8")>IO)throw new Error("The report exceeds the app's 16 MiB expanded report limit");let c=a?new Uint8Array((0,Uq.gzipSync)(s)):s;if(a&&c.length>Rg)throw new Error("The compressed report exceeds the app's 1 MiB report upload limit");return Mq(e,t,n,o(l=>({method:t,headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json",Accept:"application/json",...a?{"Content-Encoding":"gzip"}:{}},body:c}),"request"),async l=>{let A=await l.text().catch(()=>""),p={};try{p=JSON.parse(A)}catch{}if(l.ok)return p.data;Oq(e,t,n,l,A);let g=p.error?.fields,h=typeof g?.path=="string"&&typeof g.reason=="string"?` at ${g.path}: ${g.reason}`:"",y=`The Skyramp app refused ${t} ${n}: ${l.status} ${p.error?.code??"no error code"}${h}`;return Pq(y,l.status,p.error?.code,typeof g?.path=="string"?g.path:void 0)},r)}o(vy,"callApp");function oge(e,t,n){return Mq(e,"GET",t,o(r=>({method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/octet-stream"}}),"request"),async r=>{if(!r.ok)return Oq(e,"GET",t,r,await r.text().catch(()=>"")),Pq(`The Skyramp app refused GET ${t}: ${r.status}`,r.status);let s=Buffer.from(await r.arrayBuffer());if(s.length>n)throw new Mr(`The Skyramp app answered GET ${t} with more than ${n} bytes`,r.status);return s})}o(oge,"callAppBytes");var zA=class{constructor(t,n,i,r,s,a,c,u,l,A=[],p=[],g){this.attemptId=t;this.attemptNumber=n;this.deadlineAt=i;this.manifest=r;this.deps=s;this.license=a;this.requestedBy=c;this.writeAllowed=u;this.claudeCodeVersion=l;this.deployedPins=A;this.statedPins=p;this.runSettings=g}attemptId;attemptNumber;deadlineAt;manifest;deps;license;requestedBy;writeAllowed;claudeCodeVersion;deployedPins;statedPins;runSettings;static{o(this,"V3Attempt")}budgetMs(t){return ege(this.deadlineAt,t)}get skyrampRunUrl(){return sge(y$(this.deps.origin),this.manifest.runId)}log(t){this.deps.log?.(t)}send(t,n,i,r){return vy(this.deps,t,n,i,r)}readBytes(t,n){return oge(this.deps,t,n)}issuedTokens=[];closure;modelKey;modelCredentials=[];credentials={};revocation;token(){return this.cachedToken("run")}readOnlyToken(){return this.cachedToken("read")}async cachedToken(t){if(this.revocation)throw new Error(_q);let n=(this.deps.now??(()=>new Date))().getTime(),i=this.credentials[t],r=i&&await i.catch(()=>{});if(this.credentials[t]!==i)return(await this.credentials[t]).token;if(r&&r.expiresAt-n>=tge)return r.token;if(this.revocation)throw new Error(_q);let s=t==="read",a=s?{schemaVersion:1,access:t}:{schemaVersion:1},c=s?"read-only":"scoped",u=this.send("POST",`/api/v1/runner/attempts/${this.attemptId}/credentials`,a).then(l=>{let A={...l,token:l.token??this.jobToken()};if(this.issuedTokens.push(A.token),this.deps.mask?.(A.token),A.anthropicApiKey&&this.deps.mask?.(A.anthropicApiKey),s&&l.token&&!nge(A.permissions))throw new Error(`The Skyramp app was asked for a read-only GitHub token, but its token grants ${JSON.stringify(A.permissions??null)}`);!s&&!r&&A.anthropicApiKey&&(this.modelKey=A.anthropicApiKey),this.deps.onTokenGranted?.(t);let p=r?"Renewed":"Received";return l.token&&this.deps.log?.(`${p} ${c} GitHub credentials; they expire at ${A.expiresAt}.`),{token:A.token,expiresAt:l.token?new Date(A.expiresAt).getTime():Number.POSITIVE_INFINITY}},l=>{if(this.deps.onTokenRefused?.(l,t),!(l instanceof Mr)||l.code!=="CREDENTIALS_UNAVAILABLE")throw l;let A=o(h=>[...new Set(h.map(y=>y.namespace))].join(", "),"unique"),p=this.manifest.sources.map(h=>h.repository);if(new Set(p.map(h=>h.providerAccountId)).size>1)throw new Mr(`${l.message}. The run's repositories are on more than one GitHub account (${A(p)}), which Skyramp does not support yet.`,l.status,l.code);let g=A([...p,this.manifest.execution.repository]);throw new Mr(`${l.message}. Check the Skyramp GitHub App installation on ${g}: it must be installed and not suspended, have access to these repositories, and have accepted the App's current permissions. Each account must also be connected to your Skyramp organization.`,l.status,l.code)});return this.credentials[t]=u,(await u).token}jobToken(){if(this.deps.sourceToken)return this.deps.sourceToken;throw new Error("The app answered the credentials request without a token, and the job gave Testbot none of its own: on Azure Pipelines, set SYSTEM_ACCESSTOKEN to $(System.AccessToken) in the Testbot step's env.")}sourceFetch(t){return t.fetch??this.deps.fetch??fetch}revokeTokens(t={}){let n=t.host??Dq();return this.revocation??=n.revokeToken?this.revokeIssued(i=>n.revokeToken(i,this.sourceFetch(t))):Promise.resolve([]),this.revocation}async revokeIssued(t){let n=[...this.issuedTokens],i=Promise.all(n.map(a=>this.revokeOne(a,t)));await Promise.all(Object.values(this.credentials).map(a=>a.catch(()=>{})));let r=this.issuedTokens.filter(a=>!n.includes(a));return[...await i,...await Promise.all(r.map(a=>this.revokeOne(a,t)))].filter(a=>a!==void 0)}async revokeOne(t,n){try{await n(t);return}catch(i){return`token ${this.issuedTokens.indexOf(t)+1} of ${this.issuedTokens.length}: ${i instanceof Error?i.message:String(i)}`}}};async function Lq(e,t,n){Fq(e,"run id"),y$(n.origin);let i=Gb(e,t),r=`/api/v1/runner/runs/${e}/attempts`,s;try{s=await vy(n,"POST",r,i)}catch(l){if(!(l instanceof Mr&&l.status===400&&l.path==="$.statedPins"))throw l;i=Gb(e,t,{statedPins:!1}),s=await vy(n,"POST",r,i)}let a=OO(s);if(a.manifest.runId!==e)throw new Error(`The app answered the handshake of run ${e} with the manifest of another run (${a.manifest.runId})`);let c=a.manifest.sources.find(l=>l.repository.provider!==i.execution.provider);if(c)throw new Error(`The manifest of run ${e} names ${c.repository.namespace}/${c.repository.name} on ${c.repository.provider}, but this job runs on ${i.execution.provider}`);age(a.manifest,[...a.deployedRevisions??[],...a.statedRevisions??[]]),a.runToken&&n.mask?.(a.runToken);let u=a.runToken?{entitlements:a.entitlements??[],runToken:a.runToken}:void 0;return new zA(a.attempt.id,a.attempt.number,new Date(a.attempt.deadlineAt),a.manifest,n,u,a.requestedBy??void 0,a.writeAllowed,a.claudeCodeVersion??void 0,a.deployedRevisions??[],a.statedRevisions??[],a.runSettings)}o(Lq,"startV3Attempt");function age(e,t){if(t.length===0)return;if(!SO(e))throw new Error(`The app pinned an attempt of a ${e.trigger.kind} run; only a scheduled run or unchosen manual run's retry is pinned to an earlier attempt's read`);let n=new Set(e.sources.map(r=>si(r.repository))),i=new Set;for(let r of t){let s=si(r.repository);if(!n.has(s))throw new Error(`The app pinned the attempt to repository ${r.repository.providerRepositoryId}, which is not a source of the run`);if(i.has(s))throw new Error(`The app pinned repository ${r.repository.providerRepositoryId} twice`);i.add(s)}}o(age,"checkAttemptPins");async function E$(e,t){return UO.parse(await e.send("POST",`/api/v1/runner/attempts/${e.attemptId}/heartbeat`,{schemaVersion:1},t))}o(E$,"heartbeatV3Attempt");async function jq(e,t=()=>new Date,n){if(e.closure)return e.closure;let i=await E$(e,n).then(r=>FO(r,t())).catch(()=>null);return i&&(e.closure=i),i}o(jq,"closedV3Attempt");var aVe=10*6e4;var cVe=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var uVe=d.object({tests:d.object({placements:d.array(d.unknown()).optional()}).passthrough().optional()}).passthrough(),lVe=d.object({repository:Pb,testType:d.string(),directory:d.string()}).passthrough();var dVe=d.object({report:d.object({language:d.string()}).passthrough()}).passthrough();var AVe=d.object({environment:d.object({components:d.array(d.unknown()).optional(),dependencies:d.array(d.unknown()).optional()}).passthrough()}).passthrough(),pVe=d.object({environment:d.object({offLimits:d.unknown().optional()}).passthrough()}).passthrough();var fVe=d.object({name:d.string().min(1),provision:d.literal("existing"),url:d.string().min(1),repository:Pb.optional(),revisionUrl:d.string().min(1).optional()}).passthrough(),gVe=d.object({name:d.string().min(1),url:d.string().nullable(),versionUrl:d.string().nullable(),notes:d.string().nullable()}).passthrough();var hVe=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);function Gq(e){let t=o(n=>e.testResults.filter(i=>i.status===n).length,"count");return{passed:t("Pass"),failed:t("Fail"),skipped:t("Skipped")}}o(Gq,"statusCounts");function cge(e){let{passed:t,failed:n,skipped:i}=Gq(e);return t+n===0?{sufficiency:"insufficient",rationale:i>0?`Every test was skipped (${i}), so nothing was validated.`:"No test ran, so nothing was validated.",gaps:["No test ran against the frozen sources."],acceptedEvidence:[],actionRequired:[]}:{sufficiency:"sufficient",rationale:`${t+n} tests ran against the frozen sources: ${t} passed, ${n} failed${i?`, ${i} skipped`:""}.`,gaps:[],acceptedEvidence:[],actionRequired:[]}}o(cge,"executedTestsValidation");function uge(e,t){let n=e.map(c=>({result:c,repository:c.repository??t,path:c.fileName||c.testType})),i=new Map;for(let c of n){let u=`${c.repository}:${c.result.testType}:${c.path}`;i.set(u,(i.get(u)??0)+1)}let r=n.map(({result:c,repository:u,path:l})=>{let A=(i.get(`${u}:${c.testType}:${l}`)??0)>1;return c.resultId??Ob(u,c.testType,l,A&&c.endpoint||void 0)}),s=new Map;for(let c of r)s.set(c,(s.get(c)??0)+1);let a=new Set(r.filter(c=>s.get(c)===1));return n.map(({result:c,repository:u},l)=>{let A=r[l],p=A;if(s.get(A)>1&&a.has(A))for(let g=2;a.has(p)||p===A;g+=1)p=A.includes("#")?`${A}.${g}`:`${A}#${g}`;return a.add(p),{...c,repository:u,resultId:p}})}o(uge,"withResultIds");function lge({notTranslated:e,...t},n){let i=uge(t.testResults,n);return{...t,testResults:i,...dge(t,i,n),validation:fge(t,Age(t,t.validation??cge(t))),traceVersion:1}}o(lge,"v3Report");function dge(e,t,n){if(!e.testExecutionContexts)return{};let i=new Set,r=o(c=>{let u=c;for(let l=2;i.has(u);l+=1)u=`${c}#${l}`;return i.add(u),u},"unique"),s=[],a=new Map;for(let{repository:c,...u}of e.testExecutionContexts){let l=u.status==="not_run"?[]:t.filter(A=>A.fileName===u.test&&A.repository===(c?.trim()||n));l.length||s.push(u);for(let{resultId:A}of l){let p=a.get(A),g=p!==void 0&&s[p].cleanup.status==="failed"?s[p].cleanup:u.cleanup,h={...u,cleanup:g,test:A,resultId:A};p===void 0?a.set(A,s.push(h)-1):s[p]=h}}for(let c of s)c.resultId&&i.add(c.resultId);return{testExecutionContexts:s.map(c=>c.resultId?c:{...c,test:r(c.test.slice(0,512))}).slice(0,5e3)}}o(dge,"linkedContexts");function Age(e,t){let{passed:n,failed:i}=Gq(e);return t.sufficiency!=="sufficient"||n+i>0||t.acceptedEvidence.length>0?t:{...t,sufficiency:"insufficient",gaps:["No test ran and no existing evidence was accepted, so nothing was validated."]}}o(Age,"withEvidence");var pge={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};function fge(e,t){if(t.sufficiency==="sufficient")return t;let n=(e.caveats??[]).map(r=>pge[r.kind]).filter(r=>r!==void 0),i=[...new Set(n)].filter(r=>!t.actionRequired.includes(r));return i.length?{...t,actionRequired:[...i,...t.actionRequired]}:t}o(fge,"withModelProviderFailure");function gge(e,t,n){let{language:i,report:r}=t;if(i==="en")return;let s={language:i,businessCaseAnalysis:r.businessCaseAnalysis},a=o((y,E,C)=>Array.isArray(y)&&Array.isArray(E)&&y.length===E.length?y.map(I=>({[C]:I[C]})):void 0,"rows"),c=e.validation;r.validation&&c&&c.rationale===n.validation.rationale&&JSON.stringify(c.gaps)===JSON.stringify(n.validation.gaps)&&r.validation.gaps.length===n.validation.gaps.length&&(s.validation={rationale:r.validation.rationale,gaps:[...r.validation.gaps]});let u=new Set((n.changes??[]).map(y=>y.id)),l=(r.changes??[]).filter(y=>u.has(y.id)).map(({id:y,text:E})=>({id:y,text:E}));l.length&&(s.changes=l);let A=a(r.issuesFound,n.issuesFound,"description");A&&(s.issuesFound=A);let p=a(r.newTestsCreated,n.newTestsCreated,"description");p&&(s.newTestsCreated=p);let g=a(r.testResults,n.testResults,"details");g&&(s.testResults=g);let h=a(r.caveats,n.caveats,"text");return h&&(s.caveats=h),s}o(gge,"v3Display");async function Vq(e,t){let n=fb([...e.issuedTokens,...t.secrets??[]]),i={...lge(t.report,t.workingSlug),...t.notTranslated?{notTranslated:t.notTranslated}:{}},r=t.translated&&gge(t.report,t.translated,i),s=o(c=>LO({manifest:e.manifest,attemptNumber:e.attemptNumber,checkedOut:t.sources.map(u=>({repository:u.repository,revision:u.revision})),firstQualification:t.firstQualification,generatedTests:pc(t.delivery,n),producer:t.producer,report:pc(c&&r?{...i,display:r}:i,n),githubWrites:t.githubWrites}),"build"),a=s(!0);r&&Buffer.byteLength(JSON.stringify(a),"utf8")>Rg&&(a=s(!1)),await e.send("PUT",`/api/v1/runner/attempts/${e.attemptId}/report`,a)}o(Vq,"uploadV3Report");async function zq(e,t){return Fq(e.attemptId,"attempt id"),vy(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,jO({reportUploaded:e.reportUploaded,recipeUploaded:e.recipeUploaded,revisionsUploaded:e.revisionsUploaded,cancelled:e.cause==="cancelled",timedOut:e.cause==="timed_out",setupFailed:e.cause==="setup_failed",checkoutFailed:e.cause==="checkout_failed"||e.cause==="merge_conflict"&&!e.conflict,mergeConflict:e.cause==="merge_conflict"?e.conflict:void 0,environmentUnverified:e.cause==="environment_unverified",runnerProviderNotReady:e.cause==="runner_provider_not_ready",credentialMissing:e.cause==="credential_missing",modelProviderDenied:e.cause==="model_provider_denied",modelProviderUnavailable:e.cause==="model_provider_unavailable"}))}o(zq,"endV3Attempt");0&&(module.exports={AppRefusal,AppUnreachable,AttemptEndReason,DeliveryStatus,GitHubWriteKind,NoReportCause,SourceProvider,V3Attempt,ValidationSufficiency,closedV3Attempt,endV3Attempt,heartbeatV3Attempt,startV3Attempt,uploadV3Report});
|
|
200
|
+
`:e.text??"")}o(Ofe,"writeFrame");function Lfe(e){Ofe({command:e})}o(Lfe,"writeAzureCommand");function vq(e){return e.replace(/%/g,"%AZP25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}o(vq,"escapeData");function jfe(e){return vq(e).replace(/;/g,"%3B").replace(/]/g,"%5D")}o(jfe,"escapeProperty");function Gfe(e,t,n){let i=Object.entries(t).map(([r,s])=>`${r}=${jfe(s)}`).join(";");return`##vso[${e}${i?` ${i}`:""}]${vq(n)}`}o(Gfe,"vsoCommand");function Vfe(e){if(!e)return[];let t=e.split(/\r?\n/).filter(n=>n.trim()&&n!==e);return[e,...t].map(n=>Gfe("task.setsecret",{},n))}o(Vfe,"setSecretLines");function wq(e,t=Lfe){for(let n of Vfe(e))t(n)}o(wq,"azureSetSecret");function VA(e){return e.replace(/\/+$/,"")}o(VA,"withoutTrailingSlash");function d$(e){let t=new URL(e),n=t.pathname.split("/").filter(Boolean);if(n.length)return decodeURIComponent(n[n.length-1]);if(t.hostname.endsWith(".visualstudio.com"))return t.hostname.split(".")[0];throw new Error(`SYSTEM_COLLECTIONURI "${e}" names no organization`)}o(d$,"azureOrganization");var zfe=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,48}[A-Za-z0-9])?$/,qfe=/[\\/:*?"<>|;#${},+=[\]%\p{Cc}\p{Cf}]/u;function Bq(e){return e.length>0&&e.length<=64&&e===e.trim()&&!qfe.test(e)&&!/[^\S ]/u.test(e)&&!/^[._]/.test(e)&&!e.endsWith(".")}o(Bq,"isName");function by(e){return A$(`${e.namespace}/${e.name}`)}o(by,"azureRepositoryOfSource");function A$(e){let t=e.indexOf("/"),n=e.lastIndexOf("/"),i=e.slice(0,t),r=e.slice(t+1,n),s=e.slice(n+1);if(t<0||t===n||!zfe.test(i)||!Bq(r)||!Bq(s))throw new Error(`"${e}" is not an Azure DevOps organization/project/repository`);return{organization:i,project:r,name:s}}o(A$,"azureRepositoryOf");function kq(e,t){let n=d$(e);if(n.toLowerCase()!==t.organization.toLowerCase())throw new Error(`${t.organization}/${t.project}/${t.name} is not in ${n}, the Azure DevOps organization this job runs in`)}o(kq,"inOrganization");function Sq(e,t){return kq(e,t),`${VA(e)}/${encodeURIComponent(t.project)}/_git/${encodeURIComponent(t.name)}`}o(Sq,"azureCloneUrl");function p$(e,t){return kq(e,t),`${VA(e)}/${encodeURIComponent(t.project)}/_apis/git/repositories/${encodeURIComponent(t.name)}`}o(p$,"azureRepositoryApi");var Jfe="7.1",GA=class extends Error{constructor(n,i){super(n);this.status=i}status;static{o(this,"AzureRestError")}};async function f$(e){let t=e.accept??"application/json",n=new URL(e.url);n.searchParams.has("api-version")||n.searchParams.set("api-version",Jfe);let i=await(e.fetch??fetch)(n.toString(),{method:e.method??"GET",headers:{Authorization:`Bearer ${e.token}`,Accept:t,...e.body!==void 0?{"Content-Type":"application/json"}:{}},...e.body!==void 0?{body:JSON.stringify(e.body)}:{},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!i.ok){let r=(await i.json().catch(()=>({}))).message;throw new GA(`Azure DevOps answered ${i.status}${typeof r=="string"?`: ${r}`:""}`,i.status)}return t!=="application/json"?Buffer.from(await i.arrayBuffer()):i.status===204?{}:await i.json()}o(f$,"azureRest");function Hfe(e){return`AUTHORIZATION: bearer ${e}`}o(Hfe,"azureGitAuthorization");function Qq(e,t){return{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${VA(e)}/.extraheader`,GIT_CONFIG_VALUE_0:Hfe(t)}}o(Qq,"azureGitAuthEnv");var Yfe="7.1-preview.1",Wfe=".azure-pipelines/skyramp-testbot-v3.yml";function g$(e){return e.GITHUB_ACTIONS!=="true"&&/^true$/i.test(e.TF_BUILD??"")}o(g$,"isAzurePipelines");function $q(e,t={}){let n=o(p=>{let g=e[p];if(!g)throw new Error(`${p} is not set; the V3 runner handshake needs it`);return g},"read"),i=VA(e.SYSTEM_COLLECTIONURI??""),r=o(()=>d$(n("SYSTEM_COLLECTIONURI")),"organization"),s=e.SYSTEM_TEAMPROJECT,a=e.BUILD_REPOSITORY_NAME,c=e.BUILD_REPOSITORY_ID?.toLowerCase(),u=e.SYSTEM_ACCESSTOKEN,l=t.mask??(p=>wq(p)),A=o(p=>async()=>{if(!p)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_OIDCREQUESTURI to $(System.OidcRequestUri).");if(!u)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_ACCESSTOKEN to $(System.AccessToken).");let g=new URL(p);if(g.protocol!=="https:")throw new Error("SYSTEM_OIDCREQUESTURI is not an https URL");g.searchParams.set("api-version",Yfe);let h=await(t.fetch??fetch)(g.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"Content-Type":"application/json",Accept:"application/json"},body:"{}",redirect:"error",signal:AbortSignal.timeout(3e4)});if(!h.ok)throw new Error(`Azure DevOps refused the OIDC token request: ${h.status}`);let y=(await h.json().catch(()=>({}))).oidcToken;if(typeof y!="string"||!y)throw new Error("Azure DevOps's OIDC token response carried no token");return l(y),y},"mint");return{runnerPlatform:g$(e)?"azure":void 0,workspace:e.BUILD_SOURCESDIRECTORY||void 0,serverUrl:i,apiUrl:i,repository:c&&s&&a&&i?{id:c,slug:`${r()}/${s}/${a}`}:void 0,runId:e.BUILD_BUILDID||void 0,runAttempt:e.SYSTEM_STAGEATTEMPT||void 0,job:e.SYSTEM_JOBNAME||void 0,execution(){let p=n("SYSTEM_STAGEATTEMPT");if(!/^[1-9][0-9]*$/.test(p))throw new Error(`SYSTEM_STAGEATTEMPT is "${p}", not a positive whole number`);let g=n("SYSTEM_COLLECTIONID").toLowerCase();if(!kc.test(g))throw new Error(`SYSTEM_COLLECTIONID is "${g}", not a GUID`);let h=n("BUILD_REPOSITORY_ID").toLowerCase();if(!kc.test(h))throw new Error(`BUILD_REPOSITORY_ID is "${h}", not a GUID`);let y=[r(),n("SYSTEM_TEAMPROJECT"),n("SYSTEM_DEFINITIONID"),n("BUILD_BUILDID")].map(encodeURIComponent).join("/");return{provider:"azure-devops",repository:{provider:"azure-devops",providerAccountId:g,providerRepositoryId:h},providerRunId:y,providerRunAttempt:Number(p),workflowRef:`${Wfe}@${n("BUILD_SOURCEBRANCH")}`}},takeIdToken(){let p=e.SYSTEM_OIDCREQUESTURI;delete e.SYSTEM_OIDCREQUESTURI;let g=A(p);return()=>g()},takeSourceToken(){return delete e.SYSTEM_ACCESSTOKEN,u||void 0},webIdentity(){if(!e.SYSTEM_OIDCREQUESTURI?.trim()||!u)return;let p=A(e.SYSTEM_OIDCREQUESTURI);return{token:o(()=>p(),"token"),runId:e.BUILD_BUILDID}},v3RunsOnly:!0,assumesBedrockRole:!0,namesSourceToMcp:!0,runSettingsFromApp:!0,checkSourceName(p){by(p)},cloneUrl(p){return Sq(i,by(p))},gitAuthEnv(p){return Qq(i,p)},async pullRequest(p,g,h){let y=await f$({token:await h.token(),url:`${p$(i,by(p))}/pullrequests/${g}`,fetch:h.fetch}),E=y.status==="completed";return{...typeof y.title=="string"?{title:y.title}:{},...typeof y.description=="string"?{body:y.description}:{},...typeof y.status=="string"?{merged:E}:{},...E&&typeof y.lastMergeCommit?.commitId=="string"?{mergeCommit:y.lastMergeCommit.commitId}:{},...E&&typeof y.lastMergeSourceCommit?.commitId=="string"?{mergedHead:y.lastMergeSourceCommit.commitId}:{}}},async commit(p,g,h){let y;try{y=p$(i,A$(p))}catch{return{lookup:"unknown"}}try{let E=await f$({token:await h.token(),url:`${y}/commits/${encodeURIComponent(g)}`,fetch:h.fetch});return typeof E.commitId=="string"?{sha:E.commitId}:{lookup:"missing"}}catch(E){return{lookup:E instanceof GA&&(E.status===404||E.status===400)?"missing":"unknown"}}}}}o($q,"azureRunnerHost");Ac();var Zfe=5e3,h$=/^(?!\.\.?$)[A-Za-z0-9._-]{1,100}$/;function Kfe(e){let t=Buffer.from(`x-access-token:${e}`).toString("base64");return Ll(t),`AUTHORIZATION: basic ${t}`}o(Kfe,"githubGitAuthorization");function Tq(e,t={}){let n=o(u=>{let l=e[u];if(!l)throw new Error(`${u} is not set; the V3 runner handshake needs it`);return l},"read"),i=e.GITHUB_REPOSITORY_ID,r=e.GITHUB_REPOSITORY,s=(e.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,""),a=(e.GITHUB_API_URL||"https://api.github.com").replace(/\/+$/,""),c=o(async(u,l)=>l.fetch(u,{headers:{Authorization:`Bearer ${await l.token()}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(3e4)}),"get");return{runnerPlatform:e.GITHUB_ACTIONS==="true"?"github":void 0,workspace:e.GITHUB_WORKSPACE||void 0,serverUrl:s,apiUrl:a,repository:i&&r?{id:i,slug:r}:void 0,runId:e.GITHUB_RUN_ID||void 0,runAttempt:e.GITHUB_RUN_ATTEMPT||void 0,job:e.GITHUB_JOB||void 0,execution(){let u=n("GITHUB_RUN_ATTEMPT");if(!/^[1-9][0-9]*$/.test(u))throw new Error(`GITHUB_RUN_ATTEMPT is "${u}", not a positive whole number`);return{provider:"github",repository:{provider:"github",providerAccountId:n("GITHUB_REPOSITORY_OWNER_ID"),providerRepositoryId:n("GITHUB_REPOSITORY_ID")},providerRunId:n("GITHUB_RUN_ID"),providerRunAttempt:Number(u),workflowRef:n("GITHUB_WORKFLOW_REF")}},takeIdToken(){let u=e.ACTIONS_ID_TOKEN_REQUEST_URL,l=e.ACTIONS_ID_TOKEN_REQUEST_TOKEN;return delete e.ACTIONS_ID_TOKEN_REQUEST_URL,delete e.ACTIONS_ID_TOKEN_REQUEST_TOKEN,async A=>{if(!u||!l)throw new Error("The job cannot request an OIDC token. Give it the `id-token: write` permission.");let p=new URL(u);p.searchParams.set("audience",A);let g=await fetch(p,{headers:{Authorization:`Bearer ${l}`,Accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!g.ok)throw new Error(`GitHub refused the OIDC token request: ${g.status}`);let h=(await g.json().catch(()=>({}))).value;if(typeof h!="string"||!h)throw new Error("GitHub's OIDC token response carried no token");return Ll(h),h}},webIdentity(){return!e.ACTIONS_ID_TOKEN_REQUEST_TOKEN?.trim()||!e.ACTIONS_ID_TOKEN_REQUEST_URL?.trim()?void 0:{token:t.getIDToken??(l=>yM(l)),runId:e.GITHUB_RUN_ID}},v3RunsOnly:!1,assumesBedrockRole:!1,namesSourceToMcp:!1,runSettingsFromApp:!1,checkSourceName(u){for(let l of[u.namespace,u.name])if(!h$.test(l))throw new Error(`"${l}" is not a repository name`)},cloneUrl(u){return`${s}/${u.namespace}/${u.name}.git`},gitAuthEnv(u){return u?{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${s}/.extraheader`,GIT_CONFIG_VALUE_0:Kfe(u)}:{}},async pullRequest({namespace:u,name:l},A,p){if(![u,l].every(y=>h$.test(y)))throw new Error("the repository name is not valid");let g=await c(`${a}/repos/${u}/${l}/pulls/${A}`,p);if(!g.ok)throw new Error(`GitHub answered ${g.status}`);let h=await g.json();return{...typeof h.title=="string"?{title:h.title}:{},...typeof h.body=="string"?{body:h.body}:{},...typeof h.merged=="boolean"?{merged:h.merged}:{},...h.merged===!0&&typeof h.merge_commit_sha=="string"?{mergeCommit:h.merge_commit_sha}:{},...h.merged===!0&&typeof h.head?.sha=="string"?{mergedHead:h.head.sha}:{}}},async commit(u,l,A){let[p,g,...h]=u.split("/");if(h.length||![p,g].every(y=>y!==void 0&&h$.test(y)))return{lookup:"unknown"};try{let y=await c(`${a}/repos/${p}/${g}/commits/${encodeURIComponent(l)}`,A);if(y.status===404||y.status===422)return{lookup:"missing"};if(!y.ok)return{lookup:"unknown"};let E=await y.json();return typeof E.sha=="string"?{sha:E.sha}:{lookup:"missing"}}catch{return{lookup:"unknown"}}},async revokeToken(u,l){let A=await l(`${a}/installation/token`,{method:"DELETE",headers:{Authorization:`Bearer ${u}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(Zfe)});if(!A.ok&&A.status!==401)throw new Error(`GitHub answered ${A.status}`)}}}o(Tq,"githubRunnerHost");function Dq(e=process.env){return g$(e)?$q(e):Tq(e)}o(Dq,"runnerHost");var Xfe=10*6e4;function ege(e,t){return e.getTime()-t.getTime()-Xfe}o(ege,"remainingBudgetMs");var _q="This attempt revoked its scoped GitHub credentials; it mints no more.",tge=10*6e4;var nge=o(e=>!!e&&Object.keys(e).length===1&&e.contents==="read","onlyReads"),rge=3e4,ige=3,Nq=30,Mr=class extends Error{constructor(n,i,r,s){super(n);this.status=i;this.code=r;this.path=s}status;code;path;static{o(this,"AppRefusal")}},fi=class extends Error{static{o(this,"AppUnreachable")}},Ru=class extends fi{static{o(this,"AppNotReady")}},m$=class extends Ru{static{o(this,"RunnerProviderNotReady")}};function y$(e){let t;try{t=new URL(e)}catch{throw new Error(`skyrampAppOrigin "${e}" is not a URL`)}if(t.protocol!=="https:"||t.origin!==e.replace(/\/+$/,""))throw new Error(`skyrampAppOrigin must be an https origin, got "${e}"`);return t.origin}o(y$,"appOrigin");function Fq(e,t){if(!kc.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}o(Fq,"routeId");function sge(e,t){return`${e.replace(/\/+$/,"")}/runs/${t}`}o(sge,"skyrampRunPageUrl");function Pq(e,t,n,i){throw t<500&&t!==429?new Mr(e,t,n,i):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new m$(e):t===503&&n==="RUN_NOT_READY"?new Ru(e):new fi(e)}o(Pq,"refusedOrUnreachable");async function Mq(e,t,n,i,r,s=1/0){let a=y$(e.origin),c=`The time limit for ${t} ${n} was reached`,u,l=0;for(let A=1;A<=ige||u instanceof Ru;A+=1){if(u instanceof Ru){if(l===Nq)throw u;l+=1,A-=1,e.log?.(`${u.message}; trying again (${l} of ${Nq}).`),await new Promise(p=>setTimeout(p,Math.max(0,Math.min(e.readyWaitMs??1e4,s-Date.now()))))}else A>1&&await new Promise(p=>setTimeout(p,Math.max(0,Math.min((e.retryDelayMs??2e3)*(A-1),s-Date.now()))));if(Date.now()>=s)throw new fi(c);try{let p,g=await(Number.isFinite(s)?Promise.race([e.idToken(a),new Promise((y,E)=>{p=setTimeout(()=>E(new fi(c)),Math.max(1,s-Date.now()))})]).finally(()=>{p&&clearTimeout(p)}):e.idToken(a));if(Date.now()>=s)throw new fi(c);let h=await(e.fetch??fetch)(new URL(n,a).toString(),{...i(g),redirect:"error",signal:AbortSignal.timeout(Math.max(1,Math.min(rge,s-Date.now())))}).catch(y=>{throw new fi(y instanceof Error?y.message:String(y),{cause:y})});return await r(h)}catch(p){if(p instanceof Mr||Date.now()>=s)throw p;u=p}}throw u}o(Mq,"callWithRetries");function Oq(e,t,n,i,r){let s=i.headers.get("cf-ray");e.log?.(`Testbot V3: ${t} ${n} answered ${i.status}${s?`, cf-ray ${s}`:""}: ${r.replace(/\s+/g," ").slice(0,200)}`)}o(Oq,"logRefusal");function vy(e,t,n,i,r){let s=t==="GET"?void 0:JSON.stringify(i),a=t==="PUT"&&/^\/api\/v1\/runner\/attempts\/[^/]+\/report$/.test(n)&&s!==void 0&&Buffer.byteLength(s,"utf8")>Rg;if(a&&Buffer.byteLength(s,"utf8")>IO)throw new Error("The report exceeds the app's 16 MiB expanded report limit");let c=a?new Uint8Array((0,Uq.gzipSync)(s)):s;if(a&&c.length>Rg)throw new Error("The compressed report exceeds the app's 1 MiB report upload limit");return Mq(e,t,n,o(l=>({method:t,headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json",Accept:"application/json",...a?{"Content-Encoding":"gzip"}:{}},body:c}),"request"),async l=>{let A=await l.text().catch(()=>""),p={};try{p=JSON.parse(A)}catch{}if(l.ok)return p.data;Oq(e,t,n,l,A);let g=p.error?.fields,h=typeof g?.path=="string"&&typeof g.reason=="string"?` at ${g.path}: ${g.reason}`:"",y=`The Skyramp app refused ${t} ${n}: ${l.status} ${p.error?.code??"no error code"}${h}`;return Pq(y,l.status,p.error?.code,typeof g?.path=="string"?g.path:void 0)},r)}o(vy,"callApp");function oge(e,t,n){return Mq(e,"GET",t,o(r=>({method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/octet-stream"}}),"request"),async r=>{if(!r.ok)return Oq(e,"GET",t,r,await r.text().catch(()=>"")),Pq(`The Skyramp app refused GET ${t}: ${r.status}`,r.status);let s=Buffer.from(await r.arrayBuffer());if(s.length>n)throw new Mr(`The Skyramp app answered GET ${t} with more than ${n} bytes`,r.status);return s})}o(oge,"callAppBytes");var zA=class{constructor(t,n,i,r,s,a,c,u,l,A=[],p=[],g){this.attemptId=t;this.attemptNumber=n;this.deadlineAt=i;this.manifest=r;this.deps=s;this.license=a;this.requestedBy=c;this.writeAllowed=u;this.claudeCodeVersion=l;this.deployedPins=A;this.statedPins=p;this.runSettings=g}attemptId;attemptNumber;deadlineAt;manifest;deps;license;requestedBy;writeAllowed;claudeCodeVersion;deployedPins;statedPins;runSettings;static{o(this,"V3Attempt")}budgetMs(t){return ege(this.deadlineAt,t)}get skyrampRunUrl(){return sge(y$(this.deps.origin),this.manifest.runId)}log(t){this.deps.log?.(t)}send(t,n,i,r){return vy(this.deps,t,n,i,r)}readBytes(t,n){return oge(this.deps,t,n)}issuedTokens=[];closure;modelKey;modelCredentials=[];credentials={};revocation;token(){return this.cachedToken("run")}readOnlyToken(){return this.cachedToken("read")}async cachedToken(t){if(this.revocation)throw new Error(_q);let n=(this.deps.now??(()=>new Date))().getTime(),i=this.credentials[t],r=i&&await i.catch(()=>{});if(this.credentials[t]!==i)return(await this.credentials[t]).token;if(r&&r.expiresAt-n>=tge)return r.token;if(this.revocation)throw new Error(_q);let s=t==="read",a=s?{schemaVersion:1,access:t}:{schemaVersion:1},c=s?"read-only":"scoped",u=this.send("POST",`/api/v1/runner/attempts/${this.attemptId}/credentials`,a).then(l=>{let A={...l,token:l.token??this.jobToken()};if(this.issuedTokens.push(A.token),this.deps.mask?.(A.token),A.anthropicApiKey&&this.deps.mask?.(A.anthropicApiKey),s&&l.token&&!nge(A.permissions))throw new Error(`The Skyramp app was asked for a read-only GitHub token, but its token grants ${JSON.stringify(A.permissions??null)}`);!s&&!r&&A.anthropicApiKey&&(this.modelKey=A.anthropicApiKey),this.deps.onTokenGranted?.(t);let p=r?"Renewed":"Received";return l.token&&this.deps.log?.(`${p} ${c} GitHub credentials; they expire at ${A.expiresAt}.`),{token:A.token,expiresAt:l.token?new Date(A.expiresAt).getTime():Number.POSITIVE_INFINITY}},l=>{if(this.deps.onTokenRefused?.(l,t),!(l instanceof Mr)||l.code!=="CREDENTIALS_UNAVAILABLE")throw l;let A=o(h=>[...new Set(h.map(y=>y.namespace))].join(", "),"unique"),p=this.manifest.sources.map(h=>h.repository);if(new Set(p.map(h=>h.providerAccountId)).size>1)throw new Mr(`${l.message}. The run's repositories are on more than one GitHub account (${A(p)}), which Skyramp does not support yet.`,l.status,l.code);let g=A([...p,this.manifest.execution.repository]);throw new Mr(`${l.message}. Check the Skyramp GitHub App installation on ${g}: it must be installed and not suspended, have access to these repositories, and have accepted the App's current permissions. Each account must also be connected to your Skyramp organization.`,l.status,l.code)});return this.credentials[t]=u,(await u).token}jobToken(){if(this.deps.sourceToken)return this.deps.sourceToken;throw new Error("The app answered the credentials request without a token, and the job gave Testbot none of its own: on Azure Pipelines, set SYSTEM_ACCESSTOKEN to $(System.AccessToken) in the Testbot step's env.")}sourceFetch(t){return t.fetch??this.deps.fetch??fetch}revokeTokens(t={}){let n=t.host??Dq();return this.revocation??=n.revokeToken?this.revokeIssued(i=>n.revokeToken(i,this.sourceFetch(t))):Promise.resolve([]),this.revocation}async revokeIssued(t){let n=[...this.issuedTokens],i=Promise.all(n.map(a=>this.revokeOne(a,t)));await Promise.all(Object.values(this.credentials).map(a=>a.catch(()=>{})));let r=this.issuedTokens.filter(a=>!n.includes(a));return[...await i,...await Promise.all(r.map(a=>this.revokeOne(a,t)))].filter(a=>a!==void 0)}async revokeOne(t,n){try{await n(t);return}catch(i){return`token ${this.issuedTokens.indexOf(t)+1} of ${this.issuedTokens.length}: ${i instanceof Error?i.message:String(i)}`}}};async function Lq(e,t,n){Fq(e,"run id"),y$(n.origin);let i=Gb(e,t),r=`/api/v1/runner/runs/${e}/attempts`,s;try{s=await vy(n,"POST",r,i)}catch(l){if(!(l instanceof Mr&&l.status===400&&l.path==="$.statedPins"))throw l;i=Gb(e,t,{statedPins:!1}),s=await vy(n,"POST",r,i)}let a=OO(s);if(a.manifest.runId!==e)throw new Error(`The app answered the handshake of run ${e} with the manifest of another run (${a.manifest.runId})`);let c=a.manifest.sources.find(l=>l.repository.provider!==i.execution.provider);if(c)throw new Error(`The manifest of run ${e} names ${c.repository.namespace}/${c.repository.name} on ${c.repository.provider}, but this job runs on ${i.execution.provider}`);age(a.manifest,[...a.deployedRevisions??[],...a.statedRevisions??[]]),a.runToken&&n.mask?.(a.runToken);let u=a.runToken?{entitlements:a.entitlements??[],runToken:a.runToken}:void 0;return new zA(a.attempt.id,a.attempt.number,new Date(a.attempt.deadlineAt),a.manifest,n,u,a.requestedBy??void 0,a.writeAllowed,a.claudeCodeVersion??void 0,a.deployedRevisions??[],a.statedRevisions??[],a.runSettings)}o(Lq,"startV3Attempt");function age(e,t){if(t.length===0)return;if(!SO(e))throw new Error(`The app pinned an attempt of a ${e.trigger.kind} run; only a scheduled run or unchosen manual run's retry is pinned to an earlier attempt's read`);let n=new Set(e.sources.map(r=>si(r.repository))),i=new Set;for(let r of t){let s=si(r.repository);if(!n.has(s))throw new Error(`The app pinned the attempt to repository ${r.repository.providerRepositoryId}, which is not a source of the run`);if(i.has(s))throw new Error(`The app pinned repository ${r.repository.providerRepositoryId} twice`);i.add(s)}}o(age,"checkAttemptPins");async function E$(e,t){return UO.parse(await e.send("POST",`/api/v1/runner/attempts/${e.attemptId}/heartbeat`,{schemaVersion:1},t))}o(E$,"heartbeatV3Attempt");async function jq(e,t=()=>new Date,n){if(e.closure)return e.closure;let i=await E$(e,n).then(r=>FO(r,t())).catch(()=>null);return i&&(e.closure=i),i}o(jq,"closedV3Attempt");var lVe=10*6e4;var dVe=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var AVe=d.object({tests:d.object({placements:d.array(d.unknown()).optional()}).passthrough().optional()}).passthrough(),pVe=d.object({repository:Pb,testType:d.string(),directory:d.string()}).passthrough();var fVe=d.object({report:d.object({language:d.string()}).passthrough()}).passthrough();var gVe=d.object({environment:d.object({components:d.array(d.unknown()).optional(),dependencies:d.array(d.unknown()).optional()}).passthrough()}).passthrough(),hVe=d.object({environment:d.object({offLimits:d.unknown().optional()}).passthrough()}).passthrough();var mVe=d.object({name:d.string().min(1),provision:d.literal("existing"),url:d.string().min(1),repository:Pb.optional(),revisionUrl:d.string().min(1).optional()}).passthrough(),yVe=d.object({name:d.string().min(1),url:d.string().nullable(),versionUrl:d.string().nullable(),notes:d.string().nullable()}).passthrough();var EVe=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);function Gq(e){let t=o(n=>e.testResults.filter(i=>i.status===n).length,"count");return{passed:t("Pass"),failed:t("Fail"),skipped:t("Skipped")}}o(Gq,"statusCounts");function cge(e){let{passed:t,failed:n,skipped:i}=Gq(e);return t+n===0?{sufficiency:"insufficient",rationale:i>0?`Every test was skipped (${i}), so nothing was validated.`:"No test ran, so nothing was validated.",gaps:["No test ran against the frozen sources."],acceptedEvidence:[],actionRequired:[]}:{sufficiency:"sufficient",rationale:`${t+n} tests ran against the frozen sources: ${t} passed, ${n} failed${i?`, ${i} skipped`:""}.`,gaps:[],acceptedEvidence:[],actionRequired:[]}}o(cge,"executedTestsValidation");function uge(e,t){let n=e.map(c=>({result:c,repository:c.repository??t,path:c.fileName||c.testType})),i=new Map;for(let c of n){let u=`${c.repository}:${c.result.testType}:${c.path}`;i.set(u,(i.get(u)??0)+1)}let r=n.map(({result:c,repository:u,path:l})=>{let A=(i.get(`${u}:${c.testType}:${l}`)??0)>1;return c.resultId??Ob(u,c.testType,l,A&&c.endpoint||void 0)}),s=new Map;for(let c of r)s.set(c,(s.get(c)??0)+1);let a=new Set(r.filter(c=>s.get(c)===1));return n.map(({result:c,repository:u},l)=>{let A=r[l],p=A;if(s.get(A)>1&&a.has(A))for(let g=2;a.has(p)||p===A;g+=1)p=A.includes("#")?`${A}.${g}`:`${A}#${g}`;return a.add(p),{...c,repository:u,resultId:p}})}o(uge,"withResultIds");function lge({notTranslated:e,...t},n){let i=uge(t.testResults,n);return{...t,testResults:i,...dge(t,i,n),validation:fge(t,Age(t,t.validation??cge(t))),traceVersion:1}}o(lge,"v3Report");function dge(e,t,n){if(!e.testExecutionContexts)return{};let i=new Set,r=o(c=>{let u=c;for(let l=2;i.has(u);l+=1)u=`${c}#${l}`;return i.add(u),u},"unique"),s=[],a=new Map;for(let{repository:c,...u}of e.testExecutionContexts){let l=u.status==="not_run"?[]:t.filter(A=>A.fileName===u.test&&A.repository===(c?.trim()||n));l.length||s.push(u);for(let{resultId:A}of l){let p=a.get(A),g=p!==void 0&&s[p].cleanup.status==="failed"?s[p].cleanup:u.cleanup,h={...u,cleanup:g,test:A,resultId:A};p===void 0?a.set(A,s.push(h)-1):s[p]=h}}for(let c of s)c.resultId&&i.add(c.resultId);return{testExecutionContexts:s.map(c=>c.resultId?c:{...c,test:r(c.test.slice(0,512))}).slice(0,5e3)}}o(dge,"linkedContexts");function Age(e,t){let{passed:n,failed:i}=Gq(e);return t.sufficiency!=="sufficient"||n+i>0||t.acceptedEvidence.length>0?t:{...t,sufficiency:"insufficient",gaps:["No test ran and no existing evidence was accepted, so nothing was validated."]}}o(Age,"withEvidence");var pge={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};function fge(e,t){if(t.sufficiency==="sufficient")return t;let n=(e.caveats??[]).map(r=>pge[r.kind]).filter(r=>r!==void 0),i=[...new Set(n)].filter(r=>!t.actionRequired.includes(r));return i.length?{...t,actionRequired:[...i,...t.actionRequired]}:t}o(fge,"withModelProviderFailure");function gge(e,t,n){let{language:i,report:r}=t;if(i==="en")return;let s={language:i,businessCaseAnalysis:r.businessCaseAnalysis},a=o((y,E,C)=>Array.isArray(y)&&Array.isArray(E)&&y.length===E.length?y.map(I=>({[C]:I[C]})):void 0,"rows"),c=e.validation;r.validation&&c&&c.rationale===n.validation.rationale&&JSON.stringify(c.gaps)===JSON.stringify(n.validation.gaps)&&r.validation.gaps.length===n.validation.gaps.length&&(s.validation={rationale:r.validation.rationale,gaps:[...r.validation.gaps]});let u=new Set((n.changes??[]).map(y=>y.id)),l=(r.changes??[]).filter(y=>u.has(y.id)).map(({id:y,text:E})=>({id:y,text:E}));l.length&&(s.changes=l);let A=a(r.issuesFound,n.issuesFound,"description");A&&(s.issuesFound=A);let p=a(r.newTestsCreated,n.newTestsCreated,"description");p&&(s.newTestsCreated=p);let g=a(r.testResults,n.testResults,"details");g&&(s.testResults=g);let h=a(r.caveats,n.caveats,"text");return h&&(s.caveats=h),s}o(gge,"v3Display");async function Vq(e,t){let n=fb([...e.issuedTokens,...t.secrets??[]]),i={...lge(t.report,t.workingSlug),...t.notTranslated?{notTranslated:t.notTranslated}:{}},r=t.translated&&gge(t.report,t.translated,i),s=o(c=>LO({manifest:e.manifest,attemptNumber:e.attemptNumber,checkedOut:t.sources.map(u=>({repository:u.repository,revision:u.revision})),firstQualification:t.firstQualification,generatedTests:pc(t.delivery,n),producer:t.producer,report:pc(c&&r?{...i,display:r}:i,n),githubWrites:t.githubWrites}),"build"),a=s(!0);r&&Buffer.byteLength(JSON.stringify(a),"utf8")>Rg&&(a=s(!1)),await e.send("PUT",`/api/v1/runner/attempts/${e.attemptId}/report`,a)}o(Vq,"uploadV3Report");async function zq(e,t){return Fq(e.attemptId,"attempt id"),vy(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,jO({reportUploaded:e.reportUploaded,recipeUploaded:e.recipeUploaded,revisionsUploaded:e.revisionsUploaded,cancelled:e.cause==="cancelled",timedOut:e.cause==="timed_out",setupFailed:e.cause==="setup_failed",checkoutFailed:e.cause==="checkout_failed"||e.cause==="merge_conflict"&&!e.conflict,mergeConflict:e.cause==="merge_conflict"?e.conflict:void 0,environmentUnverified:e.cause==="environment_unverified",runnerProviderNotReady:e.cause==="runner_provider_not_ready",credentialMissing:e.cause==="credential_missing",modelProviderDenied:e.cause==="model_provider_denied",modelProviderUnavailable:e.cause==="model_provider_unavailable"}))}o(zq,"endV3Attempt");0&&(module.exports={AppRefusal,AppUnreachable,AttemptEndReason,DeliveryStatus,GitHubWriteKind,NoReportCause,SourceProvider,V3Attempt,ValidationSufficiency,closedV3Attempt,endV3Attempt,heartbeatV3Attempt,startV3Attempt,uploadV3Report});
|
|
201
201
|
/*! Bundled license information:
|
|
202
202
|
|
|
203
203
|
undici/lib/web/fetch/body.js:
|