@skyramp/testbot-core 0.0.0-pr597.124 → 0.0.0-pr597.125
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 +4 -4
- package/dist/post.js +2 -2
- package/package.json +1 -1
package/dist/VERSION.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":"0.0.0-pr597.
|
|
1
|
+
{"version":"0.0.0-pr597.125","commit":"86716ab8c3a3ee1e30272cc305aaded88713b29a"}
|
package/dist/main.js
CHANGED
|
@@ -312,14 +312,14 @@ Other caches with similar key:`);for(let a of i?.artifactCaches||[])oe(`Cache Ke
|
|
|
312
312
|
pushToolEvent('testbot', '${t}', '', ${JSON.stringify(e)})
|
|
313
313
|
.then(() => process.exit(0))
|
|
314
314
|
.catch(e => { console.error(e.message); process.exit(1); });
|
|
315
|
-
`],{silent:!0,env:{NODE_PATH:process.env.NODE_PATH||"",LICENSE_FILE:r,CI:"true"}})}function S_(t=__dirname){try{let e=PR.readFileSync(_nt.join(t,"VERSION.json"),"utf-8"),r=JSON.parse(e);if(typeof r.version=="string"&&typeof r.commit=="string")return{version:r.version,commit:r.commit}}catch{}return{version:"unknown",commit:"unknown"}}async function Ont(t){if(!PR.existsSync(t))return{usage:null,model:null,skills:[]};let e=Dnt.createInterface({input:PR.createReadStream(t),crlfDelay:1/0}),r=null,n=null,s=[];for await(let i of e)if(i.trim())try{let o=JSON.parse(i);if(o.type==="assistant"){let a=o.message?.model;!n&&typeof a=="string"&&(n=a);let c=o.message?.content;if(Array.isArray(c))for(let l of c){if(l?.type!=="tool_use"||l.name!=="Skill")continue;let u=l.input?.skill;typeof u=="string"&&u.length>0&&s.push(u)}}if(o.type==="result"){let a=o.usage??{};r={inputTokens:a.input_tokens??0,outputTokens:a.output_tokens??0,cacheCreationInputTokens:a.cache_creation_input_tokens??0,cacheReadInputTokens:a.cache_read_input_tokens??0,totalCostUsd:o.total_cost_usd??0,numTurns:o.num_turns??0,durationMs:o.duration_ms??0,durationApiMs:o.duration_api_ms??0}}}catch{continue}return{usage:r,model:n,skills:s}}async function Mnt(t,e,r){for(let n of t){let s={skill:n,agentType:e,...Qme()};vt(`Pushing skill invocation telemetry: ${JSON.stringify(s)}`),await Lme("testbot_skill_invoked",s,r)}}async function Qnt(t,e,r){let n={inputTokens:String(t.inputTokens),outputTokens:String(t.outputTokens),cacheCreationInputTokens:String(t.cacheCreationInputTokens),cacheReadInputTokens:String(t.cacheReadInputTokens),totalCostUsd:String(t.totalCostUsd),numTurns:String(t.numTurns),durationMs:String(t.durationMs),durationApiMs:String(t.durationApiMs),model:e,...Qme()},s=process.env.GITHUB_REF?.match(/^refs\/pull\/(\d+)\//);s&&(n.prNumber=s[1]);let{totalCostUsd:i,...o}=n;vt(`Pushing agent usage telemetry: ${JSON.stringify(o)}`),await Lme("testbot_agent_usage",n,r)}async function Lnt(t,e){let{version:r,commit:n}=S_(),s={testbotVersion:r,testbotCommit:n,actionVersion:process.env.TESTBOT_ACTION_VERSION||"unknown",actionCommit:process.env.TESTBOT_ACTION_COMMIT||"unknown",agentType:t,...Qme()};vt(`Pushing testbot run info telemetry: ${JSON.stringify(s)}`),await Lme("testbot_run_info",s,e)}Ke();var rs=$(require("fs")),j_=$(require("path"));var znt=require("child_process"),DR=$(require("fs")),Gnt=$(require("os")),R_=$(require("path"));var $i=["-c","core.fsmonitor=false"],qcr=new Set(["GH_TOKEN","GITHUB_TOKEN","GH_ENTERPRISE_TOKEN","GITHUB_ENTERPRISE_TOKEN","ACTIONS_RUNTIME_TOKEN","ACTIONS_ID_TOKEN_REQUEST_TOKEN","ACTIONS_ID_TOKEN_REQUEST_URL","SYSTEM_ACCESSTOKEN","SYSTEM_OIDCREQUESTURI","SSH_AUTH_SOCK","GIT_SSH","GIT_SSH_COMMAND","GITHUB_STEP_SUMMARY"]),Ume=new Set(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_BEARER_TOKEN_BEDROCK","AWS_PROFILE","AWS_WEB_IDENTITY_TOKEN_FILE","AWS_ROLE_ARN","AWS_ROLE_SESSION_NAME","AWS_CONTAINER_CREDENTIALS_FULL_URI","AWS_CONTAINER_CREDENTIALS_RELATIVE_URI","AWS_CONTAINER_AUTHORIZATION_TOKEN","AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"]);function wt(t=process.env,e,r="repo-command"){let n={};for(let[s,i]of Object.entries(t))r==="repo-command"&&Ume.has(s)||(n[s]=i);Object.assign(n,e??{});for(let s of Object.keys(n))(qcr.has(s)||s.startsWith("INPUT_"))&&delete n[s];return n}var BR=(r=>(r.Ready="ready",r.Blocked="blocked",r))(BR||{}),Es=y.string().trim().min(1),Hcr=y.object({action:y.enum(["start","run","wait"]),text:Es,source:y.enum(["file","notes","testbot"]).describe("file: a file in the repository; notes: the Target's notes; testbot: Testbot's own finding"),file:Es.nullable().describe("the file the step came from, relative to the component's repository; null unless source is file")}).strict().refine(t=>t.source==="file"==(t.file!==null),{path:["file"],message:"a file exactly when the step came from one"}),zcr=/^[A-Za-z_][A-Za-z0-9_]*$/,WA=/^(?!GITHUB_)(?!SKYRAMP_RUNNER_)[A-Z][A-Z0-9_]{0,99}$/,PG=(i=>(i.VersionEndpoint="version_endpoint",i.DeployWorkflow="deploy_workflow",i.KubernetesLabels="kubernetes_labels",i.Command="command",i.Api="api",i))(PG||{}),yn="shared",Gcr=Es.refine(t=>{try{let e=new URL(t);return["http:","https:"].includes(e.protocol)&&!e.username&&!e.password}catch{return!1}},"an http(s) URL with no login in it"),_R=y.object({address:Gcr,readyWhen:Es.nullable(),credentials:y.array(y.string().regex(WA)).max(50),revisionSources:y.array(y.object({method:y.nativeEnum(PG),detail:Es.describe("what Testbot reads, such as GET /version or the deploy workflow's name"),components:y.array(Es).min(1).describe("the components it tells the revision of, by name")}).strict()).max(50)}).strict(),Fme={steps:y.array(Hcr).max(20).optional().describe("how it starts, in order"),kind:y.enum(["web_app","service","database","external_service"]).optional(),from:y.object({file:Es,service:Es.nullable()}).strict().optional(),credentials:y.array(y.string().max(100).regex(zcr)).max(50).optional().describe("the Target's credentials this component's recipe uses: a sign-in (a test user, password or token) or an API key, which the workflow supplies from a GitHub Actions secret as the environment variable of the credential's name; give each name exactly as the recipe reads it. Names only, never a value, and not a secret the recipe generates itself")},jcr=y.object({name:Es,repository:Es.describe("owner/repo of the Target repository the component is built or started from, such as the one whose compose file starts its database"),healthy:y.boolean(),...Fme,deployed:Es.nullable().optional().describe('only with "environment": the revision the component runs, as you read it from its revision source, or null when you could not tell')}),Vcr=y.object({component:Es,problem:Es,evidence:Es.describe("the exact command and output that shows it"),fix:Es.describe("what the user must provide, and where")}),Wcr=y.object({framework:Es,file:Es.describe("the test file run, relative to its repository root"),result:y.enum(["pass","fail","error"])}),Ycr=y.object({input:Es.describe("the part of the user's SUT input, as given"),reason:Es}),C_=y.object({schemaVersion:y.literal(1),status:y.nativeEnum(BR).describe("ready only if every component came up healthy and the recipe is written"),components:y.array(jcr),suites:y.array(Wcr).default([]).describe("one run per test suite the Target's repositories have; empty when they have none"),inputsUsed:y.array(Es).default([]).describe("the parts of the user's SUT input the recipe used"),inputsUsedHow:y.array(y.object({input:Es.describe("exactly as written in inputsUsed; an entry that is not there is left out"),how:Es.describe("what the recipe did with it")})).optional(),inputsNotUsed:y.array(Ycr).default([]).describe("the parts it did not use, and why"),blockers:y.array(Vcr).describe("required (non-empty) when status is blocked"),environment:_R.optional().describe("only when the whole SUT is an existing deployment you tested where it runs, building and starting nothing: its address, what says it is ready, the credentials that reach it, and how to read what each component runs. Leave it out when any part was built or started on the runner, or reaching it needed something there (a tunnel, port-forward, proxy or client certificate)")});function $me(t){let e=Jcr(t);if(e.length>0)return e;if(t.status==="blocked"&&!(Array.isArray(t.blockers)&&t.blockers.length>0))return['status "blocked" requires at least one blocker { component, problem, evidence, fix } \u2014 say what stopped the bring-up'];if(t.status==="ready"){let r=Array.isArray(t.components)?t.components:[];if(r.length===0)return['status "ready" requires at least one component \u2014 name each component the recipe brought up healthy'];let n=r.filter(s=>s?.healthy!==!0).map(s=>String(s?.name??"?"));if(n.length>0)return[`status "ready" requires every component healthy; not healthy: ${n.join(", ")} \u2014 answer "blocked" with a blocker for each, or bring them up and answer "ready" again`]}return[]}function Jcr(t){let e=Array.isArray(t.components)?t.components:[],r=t.environment;if(!r){let a=e.filter(c=>c?.deployed!==void 0||c?.repository===yn).map(c=>String(c?.name??"?"));return a.length>0?[`"deployed" and a "${yn}" repository belong only to an answer with "environment"; remove them from: ${a.join(", ")}`]:[]}let n=[],s=e.filter(a=>a?.deployed===void 0).map(a=>String(a?.name??"?"));s.length>0&&n.push(`with "environment", every component says what it runs in "deployed" (null when you could not tell); missing for: ${s.join(", ")}`);let i=new Set(e.map(a=>a?.name)),o=(r.revisionSources??[]).flatMap(a=>a?.components??[]).filter(a=>!i.has(a));return o.length>0&&n.push(`each revision source names components of this answer; not one of them: ${o.map(String).join(", ")}`),n}var Ow=64*1024,Mw=512*1024,BG=/[\u0000-\u0008\u000b\u000e-\u001f\u007f]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;var gh=$(require("fs")),DG=$(require("path"));var Unt=$(require("fs")),_G=$(require("path"));function sm(t,e,r={}){let n=r.maxDepth??1/0,s=!1,i=(o,a)=>{let c;try{c=Unt.readdirSync(o,{withFileTypes:!0})}catch{return}for(let l of c){if(s)return;let u=_G.join(o,l.name);if(l.isDirectory())!r.skip?.has(l.name)&&a<n&&i(u,a+1);else if(e(u,_G.relative(t,u))===!1){s=!0;return}}};i(t,0)}var Kcr=4,I_="\xABredacted\xBB";function Wu(t){let e=new Set;for(let r of t){let n=(r??"").trim();n.length>=Kcr&&e.add(n)}return[...e].sort((r,n)=>n.length-r.length)}function Dr(t,e){if(!t||e.length===0)return t;let r=t;for(let n of e)!n||!r.includes(n)||(r=r.split(n).join(I_));return r}function Xr(t,e){if(e.length===0)return t;let r=n=>typeof n=="string"?Dr(n,e):Array.isArray(n)?n.map(r):n&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([s,i])=>[s,r(i)])):n;return r(t)}function qme(t,e){return/\.(json|txt|md)$/.test(t)||e&&t.endsWith(".ndjson")}function $nt(t,e){let r=[];return sm(t,n=>{try{qme(DG.basename(n),e)&&gh.lstatSync(n).isFile()&&r.push(n)}catch{}}),r}function Xcr(t){return t.length>=2&&(t[0]===255&&t[1]===254||t[0]===254&&t[1]===255)}var Zcr=new TextDecoder("utf-8",{fatal:!0});function elr(t){return t.includes(0)||Xcr(t)||!qnt(t)}function qnt(t){try{return Zcr.decode(t),!0}catch{return!1}}function tlr(t,e){let r=Buffer.from(t,"utf16le"),n=Buffer.from("*".repeat(r.length/2),"utf16le"),s=Buffer.from(t),i=[{needle:s,mask:Buffer.alloc(s.length,"*")},{needle:r,mask:n},{needle:Buffer.from(r).swap16(),mask:Buffer.from(n).swap16()}];return e&&/^[\x00-\xff]*$/.test(t)&&/[\x80-\xff]/.test(t)&&i.push({needle:Buffer.from(t,"latin1"),mask:Buffer.alloc(t.length,"*")}),i}function Fnt(t,e){let r=qnt(t),n=r&&!t.includes(0),s=!1;for(let i of e)if(i)for(let{needle:o,mask:a}of tlr(i,!r))for(let c=t.indexOf(o);c!==-1;c=t.indexOf(o,c+o.length))(n?Buffer.alloc(o.length,"*"):a).copy(t,c),s=!0;return s}function Hme(t,e){if(e.length===0)return;let r;try{r=gh.readdirSync(t,{withFileTypes:!0})}catch{return}for(let n of r){let s=DG.join(t,n.name);if(n.isDirectory()){Hme(s,e);continue}if(n.isFile())try{let i=gh.readFileSync(s);if(elr(i)){qme(n.name,!0)&&Fnt(i,e)&&gh.writeFileSync(s,i);continue}let o=i.toString("utf-8"),a=Dr(o,e),c=a===o?i:Buffer.from(a),l=qme(n.name,!0)&&Fnt(c,e);(a!==o||l)&&gh.writeFileSync(s,c)}catch{}}}var $a=".skyramp/sut/deployed-revisions.sh",Gme=(r=>(r.Running="running",r.Requested="requested",r))(Gme||{}),zme=200,rlr=new Set(Object.values(Gme));function nlr(t){let e=t.trim();if(!e)return{ok:!1,error:"deployed-revisions.sh printed nothing"};let r={ok:!1,error:`deployed-revisions.sh printed not one JSON object of component to commit: ${e.slice(0,zme)}`},n;try{n=JSON.parse(e)}catch{return r}if(n===null||typeof n!="object"||Array.isArray(n))return r;let s={};for(let[i,o]of Object.entries(n)){let a=typeof o=="string"?{revision:o}:o,{revision:c,state:l="running",...u}=a??{};if(!(typeof a=="object"&&a!==null&&!Array.isArray(a)&&Object.keys(u).length===0&&typeof c=="string"&&c.trim()!==""&&typeof l=="string"&&rlr.has(l)))return{ok:!1,error:`deployed-revisions.sh printed ${JSON.stringify(o)?.slice(0,zme)} for ${i}: give a commit, or {"revision": "<commit>", "state": "running" or "requested"}`};s[i]={revision:c.trim().toLowerCase(),state:l}}return{ok:!0,revisions:s}}function slr(t){let e=t.map(r=>JSON.stringify(r).slice(1,-1)).filter(r=>!t.includes(r));return[...t,...e].sort((r,n)=>n.length-r.length)}var ilr=6e4,olr=["BASH_ENV","ENV"];function jnt(t,e,r=process.env){let n=Object.fromEntries(e.filter(i=>r[i]!==void 0).map(i=>[i,r[i]])),s={...wt(r,n),GH_TOKEN:t};for(let i of olr)delete s[i];return s}async function Vnt(t){let e=t.timeoutMs??ilr,r=DR.mkdtempSync(R_.join(Gnt.tmpdir(),"skyramp-deployed-revisions-"));try{let n=R_.join(r,R_.basename($a));DR.writeFileSync(n,t.content,{mode:448});let{code:s,stdout:i,timedOut:o}=await new Promise((c,l)=>{let u=(0,znt.spawn)("bash",[n],{cwd:r,env:t.env,stdio:["ignore","pipe","ignore"],detached:!0}),d="",p=!1,m=setTimeout(()=>{p=!0;try{process.kill(-u.pid,"SIGKILL")}catch{u.kill("SIGKILL")}},e);u.stdout.setEncoding("utf-8").on("data",f=>{d+=f}),u.on("error",f=>{clearTimeout(m),l(f)}),u.on("close",f=>{clearTimeout(m),c({code:f,stdout:d,timedOut:p})})}),a=Dr(i,slr(t.secrets));return o?{ok:!1,error:`deployed-revisions.sh did not finish within ${Math.round(e/1e3)} s`}:s!==0?{ok:!1,error:`deployed-revisions.sh exited ${s??"on a signal"}: ${a.trim().slice(0,zme)||"(no output)"}`}:nlr(a)}catch(n){return{ok:!1,error:`deployed-revisions.sh could not run: ${n instanceof Error?n.message:String(n)}`}}finally{DR.rmSync(r,{recursive:!0,force:!0})}}var alr=/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/,jme=t=>alr.test(t);function Qw(t){return t?.find(e=>e.path===$a)}var Hnt=`Fix ${$a} so it prints the full commit each component runs, then set it up again.`;async function clr(t){let e=t.components.filter(c=>c.repository!==yn),[r,n]=t.reads;if(!r.ok||!n.ok){let c=e.map(u=>u.name).join(", "),l=[r,n].flatMap((u,d)=>u.ok?[]:[`run ${d+1}: ${u.error}`]);return{deployed:{},blockers:[{component:c||$a,problem:`${$a} could not tell what ${c||"the Test Environment"} runs.`,evidence:l.join("; "),fix:Hnt}]}}let s={},i=[],o=(c,l,u)=>i.push({component:c,problem:l,evidence:u,fix:Hnt});for(let{name:c,repository:l}of e){let u=r.revisions[c]?.revision,d=n.revisions[c]?.revision,m=Object.keys((u?n:r).revisions).join(", ")||"nothing";if(!u||!d)o(c,`${$a} prints no revision for ${c}.`,`printed for: ${m}`);else if(u!==d)o(c,`The two runs of ${$a} disagree on what ${c} runs.`,`first run ${u}, second run ${d}`);else if(!jme(u))o(c,`${$a} prints ${u} for ${c}, which is not a full commit.`,`printed ${u}; expand a short commit in the script, for example with gh api repos/${l}/commits/<short> --jq .sha`);else{let f=await t.resolveCommit(l,u);f==="found"?s[c]=u:f==="missing"?o(c,`${u} is not a commit of ${l}, which builds ${c}: a config repository's commit is not the app's.`,`GitHub has no commit ${u} in ${l}, or this run cannot read ${l}`):o(c,`Testbot could not check that ${l} has ${u}.`,`GitHub did not answer for commit ${u} in ${l}`)}}let a=new Set(t.components.map(c=>c.name));for(let c of[...new Set([...Object.keys(r.revisions),...Object.keys(n.revisions)])].filter(l=>!a.has(l)))o(c,`${$a} prints a revision for ${c}, which is not a component of the Test Environment.`,`components: ${[...a].join(", ")}`);return{deployed:s,blockers:i}}async function Wnt(t){let e=await t.read(t.content),r=await t.read(t.content);return clr({reads:[e,r],components:t.components,resolveCommit:t.resolveCommit})}var M_=require("node:crypto");var Lw=(i=>(i.NotFound="not_found",i.NoAccess="no_access",i.Unavailable="unavailable",i.AccessLost="access_lost",i.CannotOpen="cannot_open",i))(Lw||{}),YA=t=>t.source==="other"?{source:t.source,key:t.key}:{source:t.source,site:t.site,key:t.key},Oc=t=>`${t.source}:${t.site??""}:${t.key}`;var v_=/^pasted-[0-9a-f]{16}$/,Uw=/^file-[0-9a-f]{16}$/,MR=(s=>(s.Pdf="application/pdf",s.Csv="text/csv",s.Docx="application/vnd.openxmlformats-officedocument.wordprocessingml.document",s.Xlsx="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",s))(MR||{}),qa=t=>t.trim().toUpperCase(),OR=(t,e)=>{let r=t.trim();return v_.test(r.toLowerCase())?"Pasted text":Uw.test(r.toLowerCase())?e?.get(qa(r))??"Uploaded document":/^\d+$/.test(r)?`Confluence page ${r}`:r.toUpperCase()},im=(t,e,r)=>e?`${OR(t,r)} AC${e}`:OR(t,r),T_=(r=>(r.Sufficient="sufficient",r.Insufficient="insufficient",r))(T_||{}),N_=(p=>(p.RelatedChangeConflict="related_change_conflict",p.ReferenceOutsideTarget="reference_outside_target",p.SourceAccessLost="source_access_lost",p.ConfigurationIncomplete="configuration_incomplete",p.CredentialUnavailable="credential_unavailable",p.WorkflowBindingUnverified="workflow_binding_unverified",p.WorkflowRefUnprotected="workflow_ref_unprotected",p.BedrockWorkflowRequired="bedrock_workflow_required",p.DeploymentReview="deployment_review",p.SutRevisionMismatch="sut_revision_mismatch",p.IsolationUnavailable="isolation_unavailable",p.EvidenceInsufficient="evidence_insufficient",p))(N_||{}),JA=(i=>(i.CiCheck="ci_check",i.TestReport="test_report",i.StaticAnalysis="static_analysis",i.CodeReview="code_review",i.Other="other",i))(JA||{}),k_=(n=>(n.Application="application",n.Environment="environment",n.TestDefect="test_defect",n))(k_||{}),OG=(a=>(a.AuthToken="auth_token",a.Secret="secret",a.DataConnection="data_connection",a.AppNotStarted="app_not_started",a.Login="login",a.ExternalDependency="external_dependency",a.RecordingReplay="recording_replay",a))(OG||{});var MG=(n=>(n.Seed="seed",n.RuntimeMock="runtime_mock",n.EnvOverride="env_override",n))(MG||{}),QG=(n=>(n.TestCode="test_code",n.SkyrampMocker="skyramp_mocker",n.RecipeOverride="recipe_override",n))(QG||{});var Ynt=$(require("path"));var om=(s=>(s.Clean="clean",s.RecipeDrift="recipe-drift",s.ChangeBrokeBringup="change-broke-bringup",s.BringupFailed="bringup-failed",s))(om||{}),KA=y.string().trim().min(1),llr=y.object({url:y.string().optional().describe("the URL probed, if the check is an HTTP request"),command:y.string().optional().describe("the command run, if the check is a script \u2014 preferred when auth is needed"),headers:y.record(y.string()).optional(),status:y.union([y.number(),y.string()]).optional().describe("expected HTTP status for a url check (default 200)"),output:KA.describe("what the check returned, VERBATIM \u2014 the bytes, nothing appended; this gate RE-RUNS the check")}),P_=y.object({schemaVersion:y.literal(1),baseUrls:y.record(y.string()).optional().describe("service \u2192 base URL of the running app; omit on a failed bring-up, never invent one"),health:llr.optional(),teardown:KA.describe("command that tears the SUT down"),dependencies:y.record(y.boolean()).optional().describe("EVERY backing service: true = really deployed, false = mocked; REQUIRED when the app came up"),outcome:y.nativeEnum(om).describe("clean | recipe-drift (you corrected the recipe) | change-broke-bringup (the PR broke it) | bringup-failed (environment, not the PR)"),recipeFixes:y.array(y.string()).optional().describe("required when outcome is recipe-drift: what was corrected"),bringupError:y.object({command:KA,output:KA}).optional().describe("required when bring-up failed: the exact failing command and what it printed"),suspectFiles:y.array(y.string()).optional().describe("required for change-broke-bringup: files THIS PR changed that the failure points at, relative to your working directory (a file in another checkout of the run: its absolute path)"),seeded:y.boolean(),startedAt:KA.describe("ISO timestamp"),revisions:y.array(y.object({component:KA.describe("a shared component listed above"),url:KA.describe("the URL on the component's own origin (scheme, host and port) that answers with its deployed commit"),output:KA.describe("what the URL returned, VERBATIM; this gate FETCHES each url")})).optional().describe("only when shared components are listed above: one check per component whose deployed commit you found")});function Vme(t){let e=[],r=s=>!!s&&typeof s=="object"&&!Array.isArray(s);return t.outcome!=="change-broke-bringup"&&t.outcome!=="bringup-failed"?(!r(t.baseUrls)||Object.keys(t.baseUrls).length===0?e.push("baseUrls must be a non-empty object of service \u2192 url"):Object.values(t.baseUrls).every(s=>typeof s=="string"&&s.trim())||e.push("every baseUrls value must be a non-empty url string"),r(t.health)?!(typeof t.health.url=="string"&&t.health.url.trim())&&!(typeof t.health.command=="string"&&t.health.command.trim())&&e.push("health must record a url or a command (what you actually ran)"):e.push("health must be an object"),(!r(t.dependencies)||Object.keys(t.dependencies).length===0)&&e.push("dependencies must be a non-empty object of name \u2192 boolean (real vs mocked) when the SUT came up \u2014 account for every backing service so a mocked one can't be hidden behind a green run")):(r(t.bringupError)||e.push(`outcome "${String(t.outcome)}" requires bringupError { command, output } \u2014 the exact failing bring-up command and what it printed`),t.outcome==="change-broke-bringup"&&!(Array.isArray(t.suspectFiles)&&t.suspectFiles.length>0&&t.suspectFiles.every(s=>typeof s=="string"&&s.trim()))&&e.push("change-broke-bringup requires non-empty suspectFiles[] \u2014 the changed file(s) the failure points at; if you cannot point at a file this PR changed, the outcome is bringup-failed (environment/harness), not the PR's fault")),t.outcome==="recipe-drift"&&!(Array.isArray(t.recipeFixes)&&t.recipeFixes.length>0)&&e.push("recipe-drift outcome requires a non-empty recipeFixes[] describing what was corrected"),e}var To=y.string().trim().min(1),Wme=(r=>(r.TestbotManaged="testbot_managed",r.CustomerDeployed="customer_deployed",r))(Wme||{}),QR=[".skyramp/sut/setup.sh",".skyramp/sut/teardown.sh"],LG=y.object({schemaVersion:y.literal(1),type:y.nativeEnum(Wme).optional(),status:y.enum(["ready","blocked"]),environment:_R.optional(),components:y.array(y.object({name:To,repository:To.describe(`owner/repo, or "${yn}" for a customer-deployed component no repository builds`),healthy:y.boolean(),url:y.string().min(1).nullable(),...Fme,credentials:y.array(y.string().regex(WA)).max(50).optional(),deployed:To.nullable().optional().describe("customer_deployed only: the revision the component runs, as setup read it (WF-SETUP-22's Deployed now), or null when it could not tell")}).strict()),suites:y.array(y.object({framework:To,file:To,result:y.enum(["pass","fail","error"])}).strict()),inputsUsed:y.array(To),inputsUsedHow:y.array(y.object({input:To,how:To}).strict()).optional(),inputsNotUsed:y.array(y.object({input:To,reason:To}).strict()),blockers:y.array(y.object({component:To,problem:To,evidence:To,fix:To}).strict()),replay:y.object({outcome:To,durationSeconds:y.number().nonnegative().nullable()}).strict().nullable(),files:y.array(y.object({path:To,content:y.string()}).strict())}).strict().superRefine((t,e)=>{t.inputsUsedHow?.forEach((s,i)=>{t.inputsUsed.includes(s.input)||e.addIssue({code:y.ZodIssueCode.custom,path:["inputsUsedHow",i,"input"],message:"not one of inputsUsed"})}),t.components.forEach((s,i)=>{s.credentials&&new Set(s.credentials).size!==s.credentials.length&&e.addIssue({code:y.ZodIssueCode.custom,path:["components",i,"credentials"],message:"names a credential twice"})});let r=t.type==="customer_deployed";r!==(t.environment!==void 0)&&e.addIssue({code:y.ZodIssueCode.custom,path:["environment"],message:"an environment exactly when the plan's type is customer_deployed"}),t.environment&&new Set(t.environment.credentials).size!==t.environment.credentials.length&&e.addIssue({code:y.ZodIssueCode.custom,path:["environment","credentials"],message:"names a credential twice"});let n=new Set(t.components.map(s=>s.name));if(t.environment?.revisionSources.forEach((s,i)=>{s.components.forEach((o,a)=>{n.has(o)||e.addIssue({code:y.ZodIssueCode.custom,path:["environment","revisionSources",i,"components",a],message:"not one of components"})})}),t.components.forEach((s,i)=>{s.deployed!==void 0!==r&&e.addIssue({code:y.ZodIssueCode.custom,path:["components",i,"deployed"],message:"what a component runs exactly when the plan is customer_deployed"}),s.repository===yn&&!r&&e.addIssue({code:y.ZodIssueCode.custom,path:["components",i,"repository"],message:`only a customer_deployed component is ${yn}`})}),r&&(t.components.forEach((s,i)=>{t.components.findIndex(o=>o.name===s.name)!==i&&e.addIssue({code:y.ZodIssueCode.custom,path:["components",i,"name"],message:"names a component twice"})}),t.replay!==null&&e.addIssue({code:y.ZodIssueCode.custom,path:["replay"],message:"a customer_deployed plan is never replayed"}),t.files.forEach((s,i)=>{QR.includes(s.path)&&e.addIssue({code:y.ZodIssueCode.custom,path:["files",i,"path"],message:"a customer_deployed plan has no script that starts or stops the system"})})),r&&t.status==="ready"){let s=new Set(t.environment?.revisionSources.flatMap(i=>i.components));t.components.forEach((i,o)=>{i.repository!==yn&&!s.has(i.name)&&e.addIssue({code:y.ZodIssueCode.custom,path:["components",o,"name"],message:"a ready customer_deployed plan reads what every component a repository builds runs"})})}});var ulr=["clean","recipe-drift"];function XA(t){let e=Ynt.posix.normalize(t);return e===t&&(e===".skyramp/workspace.yml"||e.startsWith(".skyramp/sut/")&&e.length>13)}function dlr(t,e){let r=e.bringupError;if(t.environment)return{component:t.components.map(s=>s.name).join(", ")||"SUT",problem:`onboard reached the deployment, but deploy's fresh check of it ended ${e.outcome}`,evidence:r?`$ ${r.command}
|
|
315
|
+
`],{silent:!0,env:{NODE_PATH:process.env.NODE_PATH||"",LICENSE_FILE:r,CI:"true"}})}function S_(t=__dirname){try{let e=PR.readFileSync(_nt.join(t,"VERSION.json"),"utf-8"),r=JSON.parse(e);if(typeof r.version=="string"&&typeof r.commit=="string")return{version:r.version,commit:r.commit}}catch{}return{version:"unknown",commit:"unknown"}}async function Ont(t){if(!PR.existsSync(t))return{usage:null,model:null,skills:[]};let e=Dnt.createInterface({input:PR.createReadStream(t),crlfDelay:1/0}),r=null,n=null,s=[];for await(let i of e)if(i.trim())try{let o=JSON.parse(i);if(o.type==="assistant"){let a=o.message?.model;!n&&typeof a=="string"&&(n=a);let c=o.message?.content;if(Array.isArray(c))for(let l of c){if(l?.type!=="tool_use"||l.name!=="Skill")continue;let u=l.input?.skill;typeof u=="string"&&u.length>0&&s.push(u)}}if(o.type==="result"){let a=o.usage??{};r={inputTokens:a.input_tokens??0,outputTokens:a.output_tokens??0,cacheCreationInputTokens:a.cache_creation_input_tokens??0,cacheReadInputTokens:a.cache_read_input_tokens??0,totalCostUsd:o.total_cost_usd??0,numTurns:o.num_turns??0,durationMs:o.duration_ms??0,durationApiMs:o.duration_api_ms??0}}}catch{continue}return{usage:r,model:n,skills:s}}async function Mnt(t,e,r){for(let n of t){let s={skill:n,agentType:e,...Qme()};vt(`Pushing skill invocation telemetry: ${JSON.stringify(s)}`),await Lme("testbot_skill_invoked",s,r)}}async function Qnt(t,e,r){let n={inputTokens:String(t.inputTokens),outputTokens:String(t.outputTokens),cacheCreationInputTokens:String(t.cacheCreationInputTokens),cacheReadInputTokens:String(t.cacheReadInputTokens),totalCostUsd:String(t.totalCostUsd),numTurns:String(t.numTurns),durationMs:String(t.durationMs),durationApiMs:String(t.durationApiMs),model:e,...Qme()},s=process.env.GITHUB_REF?.match(/^refs\/pull\/(\d+)\//);s&&(n.prNumber=s[1]);let{totalCostUsd:i,...o}=n;vt(`Pushing agent usage telemetry: ${JSON.stringify(o)}`),await Lme("testbot_agent_usage",n,r)}async function Lnt(t,e){let{version:r,commit:n}=S_(),s={testbotVersion:r,testbotCommit:n,actionVersion:process.env.TESTBOT_ACTION_VERSION||"unknown",actionCommit:process.env.TESTBOT_ACTION_COMMIT||"unknown",agentType:t,...Qme()};vt(`Pushing testbot run info telemetry: ${JSON.stringify(s)}`),await Lme("testbot_run_info",s,e)}Ke();var rs=$(require("fs")),j_=$(require("path"));var znt=require("child_process"),DR=$(require("fs")),Gnt=$(require("os")),R_=$(require("path"));var $i=["-c","core.fsmonitor=false"],qcr=new Set(["GH_TOKEN","GITHUB_TOKEN","GH_ENTERPRISE_TOKEN","GITHUB_ENTERPRISE_TOKEN","ACTIONS_RUNTIME_TOKEN","ACTIONS_ID_TOKEN_REQUEST_TOKEN","ACTIONS_ID_TOKEN_REQUEST_URL","SYSTEM_ACCESSTOKEN","SYSTEM_OIDCREQUESTURI","SKYRAMP_MCP_GITHUB_TOKEN","SSH_AUTH_SOCK","GIT_SSH","GIT_SSH_COMMAND","GITHUB_STEP_SUMMARY"]),Ume=new Set(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_BEARER_TOKEN_BEDROCK","AWS_PROFILE","AWS_WEB_IDENTITY_TOKEN_FILE","AWS_ROLE_ARN","AWS_ROLE_SESSION_NAME","AWS_CONTAINER_CREDENTIALS_FULL_URI","AWS_CONTAINER_CREDENTIALS_RELATIVE_URI","AWS_CONTAINER_AUTHORIZATION_TOKEN","AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"]);function wt(t=process.env,e,r="repo-command"){let n={};for(let[s,i]of Object.entries(t))r==="repo-command"&&Ume.has(s)||(n[s]=i);Object.assign(n,e??{});for(let s of Object.keys(n))(qcr.has(s)||s.startsWith("INPUT_"))&&delete n[s];return n}var BR=(r=>(r.Ready="ready",r.Blocked="blocked",r))(BR||{}),Es=y.string().trim().min(1),Hcr=y.object({action:y.enum(["start","run","wait"]),text:Es,source:y.enum(["file","notes","testbot"]).describe("file: a file in the repository; notes: the Target's notes; testbot: Testbot's own finding"),file:Es.nullable().describe("the file the step came from, relative to the component's repository; null unless source is file")}).strict().refine(t=>t.source==="file"==(t.file!==null),{path:["file"],message:"a file exactly when the step came from one"}),zcr=/^[A-Za-z_][A-Za-z0-9_]*$/,WA=/^(?!GITHUB_)(?!SKYRAMP_RUNNER_)[A-Z][A-Z0-9_]{0,99}$/,PG=(i=>(i.VersionEndpoint="version_endpoint",i.DeployWorkflow="deploy_workflow",i.KubernetesLabels="kubernetes_labels",i.Command="command",i.Api="api",i))(PG||{}),yn="shared",Gcr=Es.refine(t=>{try{let e=new URL(t);return["http:","https:"].includes(e.protocol)&&!e.username&&!e.password}catch{return!1}},"an http(s) URL with no login in it"),_R=y.object({address:Gcr,readyWhen:Es.nullable(),credentials:y.array(y.string().regex(WA)).max(50),revisionSources:y.array(y.object({method:y.nativeEnum(PG),detail:Es.describe("what Testbot reads, such as GET /version or the deploy workflow's name"),components:y.array(Es).min(1).describe("the components it tells the revision of, by name")}).strict()).max(50)}).strict(),Fme={steps:y.array(Hcr).max(20).optional().describe("how it starts, in order"),kind:y.enum(["web_app","service","database","external_service"]).optional(),from:y.object({file:Es,service:Es.nullable()}).strict().optional(),credentials:y.array(y.string().max(100).regex(zcr)).max(50).optional().describe("the Target's credentials this component's recipe uses: a sign-in (a test user, password or token) or an API key, which the workflow supplies from a GitHub Actions secret as the environment variable of the credential's name; give each name exactly as the recipe reads it. Names only, never a value, and not a secret the recipe generates itself")},jcr=y.object({name:Es,repository:Es.describe("owner/repo of the Target repository the component is built or started from, such as the one whose compose file starts its database"),healthy:y.boolean(),...Fme,deployed:Es.nullable().optional().describe('only with "environment": the revision the component runs, as you read it from its revision source, or null when you could not tell')}),Vcr=y.object({component:Es,problem:Es,evidence:Es.describe("the exact command and output that shows it"),fix:Es.describe("what the user must provide, and where")}),Wcr=y.object({framework:Es,file:Es.describe("the test file run, relative to its repository root"),result:y.enum(["pass","fail","error"])}),Ycr=y.object({input:Es.describe("the part of the user's SUT input, as given"),reason:Es}),C_=y.object({schemaVersion:y.literal(1),status:y.nativeEnum(BR).describe("ready only if every component came up healthy and the recipe is written"),components:y.array(jcr),suites:y.array(Wcr).default([]).describe("one run per test suite the Target's repositories have; empty when they have none"),inputsUsed:y.array(Es).default([]).describe("the parts of the user's SUT input the recipe used"),inputsUsedHow:y.array(y.object({input:Es.describe("exactly as written in inputsUsed; an entry that is not there is left out"),how:Es.describe("what the recipe did with it")})).optional(),inputsNotUsed:y.array(Ycr).default([]).describe("the parts it did not use, and why"),blockers:y.array(Vcr).describe("required (non-empty) when status is blocked"),environment:_R.optional().describe("only when the whole SUT is an existing deployment you tested where it runs, building and starting nothing: its address, what says it is ready, the credentials that reach it, and how to read what each component runs. Leave it out when any part was built or started on the runner, or reaching it needed something there (a tunnel, port-forward, proxy or client certificate)")});function $me(t){let e=Jcr(t);if(e.length>0)return e;if(t.status==="blocked"&&!(Array.isArray(t.blockers)&&t.blockers.length>0))return['status "blocked" requires at least one blocker { component, problem, evidence, fix } \u2014 say what stopped the bring-up'];if(t.status==="ready"){let r=Array.isArray(t.components)?t.components:[];if(r.length===0)return['status "ready" requires at least one component \u2014 name each component the recipe brought up healthy'];let n=r.filter(s=>s?.healthy!==!0).map(s=>String(s?.name??"?"));if(n.length>0)return[`status "ready" requires every component healthy; not healthy: ${n.join(", ")} \u2014 answer "blocked" with a blocker for each, or bring them up and answer "ready" again`]}return[]}function Jcr(t){let e=Array.isArray(t.components)?t.components:[],r=t.environment;if(!r){let a=e.filter(c=>c?.deployed!==void 0||c?.repository===yn).map(c=>String(c?.name??"?"));return a.length>0?[`"deployed" and a "${yn}" repository belong only to an answer with "environment"; remove them from: ${a.join(", ")}`]:[]}let n=[],s=e.filter(a=>a?.deployed===void 0).map(a=>String(a?.name??"?"));s.length>0&&n.push(`with "environment", every component says what it runs in "deployed" (null when you could not tell); missing for: ${s.join(", ")}`);let i=new Set(e.map(a=>a?.name)),o=(r.revisionSources??[]).flatMap(a=>a?.components??[]).filter(a=>!i.has(a));return o.length>0&&n.push(`each revision source names components of this answer; not one of them: ${o.map(String).join(", ")}`),n}var Ow=64*1024,Mw=512*1024,BG=/[\u0000-\u0008\u000b\u000e-\u001f\u007f]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;var gh=$(require("fs")),DG=$(require("path"));var Unt=$(require("fs")),_G=$(require("path"));function sm(t,e,r={}){let n=r.maxDepth??1/0,s=!1,i=(o,a)=>{let c;try{c=Unt.readdirSync(o,{withFileTypes:!0})}catch{return}for(let l of c){if(s)return;let u=_G.join(o,l.name);if(l.isDirectory())!r.skip?.has(l.name)&&a<n&&i(u,a+1);else if(e(u,_G.relative(t,u))===!1){s=!0;return}}};i(t,0)}var Kcr=4,I_="\xABredacted\xBB";function Wu(t){let e=new Set;for(let r of t){let n=(r??"").trim();n.length>=Kcr&&e.add(n)}return[...e].sort((r,n)=>n.length-r.length)}function Dr(t,e){if(!t||e.length===0)return t;let r=t;for(let n of e)!n||!r.includes(n)||(r=r.split(n).join(I_));return r}function Xr(t,e){if(e.length===0)return t;let r=n=>typeof n=="string"?Dr(n,e):Array.isArray(n)?n.map(r):n&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([s,i])=>[s,r(i)])):n;return r(t)}function qme(t,e){return/\.(json|txt|md)$/.test(t)||e&&t.endsWith(".ndjson")}function $nt(t,e){let r=[];return sm(t,n=>{try{qme(DG.basename(n),e)&&gh.lstatSync(n).isFile()&&r.push(n)}catch{}}),r}function Xcr(t){return t.length>=2&&(t[0]===255&&t[1]===254||t[0]===254&&t[1]===255)}var Zcr=new TextDecoder("utf-8",{fatal:!0});function elr(t){return t.includes(0)||Xcr(t)||!qnt(t)}function qnt(t){try{return Zcr.decode(t),!0}catch{return!1}}function tlr(t,e){let r=Buffer.from(t,"utf16le"),n=Buffer.from("*".repeat(r.length/2),"utf16le"),s=Buffer.from(t),i=[{needle:s,mask:Buffer.alloc(s.length,"*")},{needle:r,mask:n},{needle:Buffer.from(r).swap16(),mask:Buffer.from(n).swap16()}];return e&&/^[\x00-\xff]*$/.test(t)&&/[\x80-\xff]/.test(t)&&i.push({needle:Buffer.from(t,"latin1"),mask:Buffer.alloc(t.length,"*")}),i}function Fnt(t,e){let r=qnt(t),n=r&&!t.includes(0),s=!1;for(let i of e)if(i)for(let{needle:o,mask:a}of tlr(i,!r))for(let c=t.indexOf(o);c!==-1;c=t.indexOf(o,c+o.length))(n?Buffer.alloc(o.length,"*"):a).copy(t,c),s=!0;return s}function Hme(t,e){if(e.length===0)return;let r;try{r=gh.readdirSync(t,{withFileTypes:!0})}catch{return}for(let n of r){let s=DG.join(t,n.name);if(n.isDirectory()){Hme(s,e);continue}if(n.isFile())try{let i=gh.readFileSync(s);if(elr(i)){qme(n.name,!0)&&Fnt(i,e)&&gh.writeFileSync(s,i);continue}let o=i.toString("utf-8"),a=Dr(o,e),c=a===o?i:Buffer.from(a),l=qme(n.name,!0)&&Fnt(c,e);(a!==o||l)&&gh.writeFileSync(s,c)}catch{}}}var $a=".skyramp/sut/deployed-revisions.sh",Gme=(r=>(r.Running="running",r.Requested="requested",r))(Gme||{}),zme=200,rlr=new Set(Object.values(Gme));function nlr(t){let e=t.trim();if(!e)return{ok:!1,error:"deployed-revisions.sh printed nothing"};let r={ok:!1,error:`deployed-revisions.sh printed not one JSON object of component to commit: ${e.slice(0,zme)}`},n;try{n=JSON.parse(e)}catch{return r}if(n===null||typeof n!="object"||Array.isArray(n))return r;let s={};for(let[i,o]of Object.entries(n)){let a=typeof o=="string"?{revision:o}:o,{revision:c,state:l="running",...u}=a??{};if(!(typeof a=="object"&&a!==null&&!Array.isArray(a)&&Object.keys(u).length===0&&typeof c=="string"&&c.trim()!==""&&typeof l=="string"&&rlr.has(l)))return{ok:!1,error:`deployed-revisions.sh printed ${JSON.stringify(o)?.slice(0,zme)} for ${i}: give a commit, or {"revision": "<commit>", "state": "running" or "requested"}`};s[i]={revision:c.trim().toLowerCase(),state:l}}return{ok:!0,revisions:s}}function slr(t){let e=t.map(r=>JSON.stringify(r).slice(1,-1)).filter(r=>!t.includes(r));return[...t,...e].sort((r,n)=>n.length-r.length)}var ilr=6e4,olr=["BASH_ENV","ENV"];function jnt(t,e,r=process.env){let n=Object.fromEntries(e.filter(i=>r[i]!==void 0).map(i=>[i,r[i]])),s={...wt(r,n),GH_TOKEN:t};for(let i of olr)delete s[i];return s}async function Vnt(t){let e=t.timeoutMs??ilr,r=DR.mkdtempSync(R_.join(Gnt.tmpdir(),"skyramp-deployed-revisions-"));try{let n=R_.join(r,R_.basename($a));DR.writeFileSync(n,t.content,{mode:448});let{code:s,stdout:i,timedOut:o}=await new Promise((c,l)=>{let u=(0,znt.spawn)("bash",[n],{cwd:r,env:t.env,stdio:["ignore","pipe","ignore"],detached:!0}),d="",p=!1,m=setTimeout(()=>{p=!0;try{process.kill(-u.pid,"SIGKILL")}catch{u.kill("SIGKILL")}},e);u.stdout.setEncoding("utf-8").on("data",f=>{d+=f}),u.on("error",f=>{clearTimeout(m),l(f)}),u.on("close",f=>{clearTimeout(m),c({code:f,stdout:d,timedOut:p})})}),a=Dr(i,slr(t.secrets));return o?{ok:!1,error:`deployed-revisions.sh did not finish within ${Math.round(e/1e3)} s`}:s!==0?{ok:!1,error:`deployed-revisions.sh exited ${s??"on a signal"}: ${a.trim().slice(0,zme)||"(no output)"}`}:nlr(a)}catch(n){return{ok:!1,error:`deployed-revisions.sh could not run: ${n instanceof Error?n.message:String(n)}`}}finally{DR.rmSync(r,{recursive:!0,force:!0})}}var alr=/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/,jme=t=>alr.test(t);function Qw(t){return t?.find(e=>e.path===$a)}var Hnt=`Fix ${$a} so it prints the full commit each component runs, then set it up again.`;async function clr(t){let e=t.components.filter(c=>c.repository!==yn),[r,n]=t.reads;if(!r.ok||!n.ok){let c=e.map(u=>u.name).join(", "),l=[r,n].flatMap((u,d)=>u.ok?[]:[`run ${d+1}: ${u.error}`]);return{deployed:{},blockers:[{component:c||$a,problem:`${$a} could not tell what ${c||"the Test Environment"} runs.`,evidence:l.join("; "),fix:Hnt}]}}let s={},i=[],o=(c,l,u)=>i.push({component:c,problem:l,evidence:u,fix:Hnt});for(let{name:c,repository:l}of e){let u=r.revisions[c]?.revision,d=n.revisions[c]?.revision,m=Object.keys((u?n:r).revisions).join(", ")||"nothing";if(!u||!d)o(c,`${$a} prints no revision for ${c}.`,`printed for: ${m}`);else if(u!==d)o(c,`The two runs of ${$a} disagree on what ${c} runs.`,`first run ${u}, second run ${d}`);else if(!jme(u))o(c,`${$a} prints ${u} for ${c}, which is not a full commit.`,`printed ${u}; expand a short commit in the script, for example with gh api repos/${l}/commits/<short> --jq .sha`);else{let f=await t.resolveCommit(l,u);f==="found"?s[c]=u:f==="missing"?o(c,`${u} is not a commit of ${l}, which builds ${c}: a config repository's commit is not the app's.`,`GitHub has no commit ${u} in ${l}, or this run cannot read ${l}`):o(c,`Testbot could not check that ${l} has ${u}.`,`GitHub did not answer for commit ${u} in ${l}`)}}let a=new Set(t.components.map(c=>c.name));for(let c of[...new Set([...Object.keys(r.revisions),...Object.keys(n.revisions)])].filter(l=>!a.has(l)))o(c,`${$a} prints a revision for ${c}, which is not a component of the Test Environment.`,`components: ${[...a].join(", ")}`);return{deployed:s,blockers:i}}async function Wnt(t){let e=await t.read(t.content),r=await t.read(t.content);return clr({reads:[e,r],components:t.components,resolveCommit:t.resolveCommit})}var M_=require("node:crypto");var Lw=(i=>(i.NotFound="not_found",i.NoAccess="no_access",i.Unavailable="unavailable",i.AccessLost="access_lost",i.CannotOpen="cannot_open",i))(Lw||{}),YA=t=>t.source==="other"?{source:t.source,key:t.key}:{source:t.source,site:t.site,key:t.key},Oc=t=>`${t.source}:${t.site??""}:${t.key}`;var v_=/^pasted-[0-9a-f]{16}$/,Uw=/^file-[0-9a-f]{16}$/,MR=(s=>(s.Pdf="application/pdf",s.Csv="text/csv",s.Docx="application/vnd.openxmlformats-officedocument.wordprocessingml.document",s.Xlsx="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",s))(MR||{}),qa=t=>t.trim().toUpperCase(),OR=(t,e)=>{let r=t.trim();return v_.test(r.toLowerCase())?"Pasted text":Uw.test(r.toLowerCase())?e?.get(qa(r))??"Uploaded document":/^\d+$/.test(r)?`Confluence page ${r}`:r.toUpperCase()},im=(t,e,r)=>e?`${OR(t,r)} AC${e}`:OR(t,r),T_=(r=>(r.Sufficient="sufficient",r.Insufficient="insufficient",r))(T_||{}),N_=(p=>(p.RelatedChangeConflict="related_change_conflict",p.ReferenceOutsideTarget="reference_outside_target",p.SourceAccessLost="source_access_lost",p.ConfigurationIncomplete="configuration_incomplete",p.CredentialUnavailable="credential_unavailable",p.WorkflowBindingUnverified="workflow_binding_unverified",p.WorkflowRefUnprotected="workflow_ref_unprotected",p.BedrockWorkflowRequired="bedrock_workflow_required",p.DeploymentReview="deployment_review",p.SutRevisionMismatch="sut_revision_mismatch",p.IsolationUnavailable="isolation_unavailable",p.EvidenceInsufficient="evidence_insufficient",p))(N_||{}),JA=(i=>(i.CiCheck="ci_check",i.TestReport="test_report",i.StaticAnalysis="static_analysis",i.CodeReview="code_review",i.Other="other",i))(JA||{}),k_=(n=>(n.Application="application",n.Environment="environment",n.TestDefect="test_defect",n))(k_||{}),OG=(a=>(a.AuthToken="auth_token",a.Secret="secret",a.DataConnection="data_connection",a.AppNotStarted="app_not_started",a.Login="login",a.ExternalDependency="external_dependency",a.RecordingReplay="recording_replay",a))(OG||{});var MG=(n=>(n.Seed="seed",n.RuntimeMock="runtime_mock",n.EnvOverride="env_override",n))(MG||{}),QG=(n=>(n.TestCode="test_code",n.SkyrampMocker="skyramp_mocker",n.RecipeOverride="recipe_override",n))(QG||{});var Ynt=$(require("path"));var om=(s=>(s.Clean="clean",s.RecipeDrift="recipe-drift",s.ChangeBrokeBringup="change-broke-bringup",s.BringupFailed="bringup-failed",s))(om||{}),KA=y.string().trim().min(1),llr=y.object({url:y.string().optional().describe("the URL probed, if the check is an HTTP request"),command:y.string().optional().describe("the command run, if the check is a script \u2014 preferred when auth is needed"),headers:y.record(y.string()).optional(),status:y.union([y.number(),y.string()]).optional().describe("expected HTTP status for a url check (default 200)"),output:KA.describe("what the check returned, VERBATIM \u2014 the bytes, nothing appended; this gate RE-RUNS the check")}),P_=y.object({schemaVersion:y.literal(1),baseUrls:y.record(y.string()).optional().describe("service \u2192 base URL of the running app; omit on a failed bring-up, never invent one"),health:llr.optional(),teardown:KA.describe("command that tears the SUT down"),dependencies:y.record(y.boolean()).optional().describe("EVERY backing service: true = really deployed, false = mocked; REQUIRED when the app came up"),outcome:y.nativeEnum(om).describe("clean | recipe-drift (you corrected the recipe) | change-broke-bringup (the PR broke it) | bringup-failed (environment, not the PR)"),recipeFixes:y.array(y.string()).optional().describe("required when outcome is recipe-drift: what was corrected"),bringupError:y.object({command:KA,output:KA}).optional().describe("required when bring-up failed: the exact failing command and what it printed"),suspectFiles:y.array(y.string()).optional().describe("required for change-broke-bringup: files THIS PR changed that the failure points at, relative to your working directory (a file in another checkout of the run: its absolute path)"),seeded:y.boolean(),startedAt:KA.describe("ISO timestamp"),revisions:y.array(y.object({component:KA.describe("a shared component listed above"),url:KA.describe("the URL on the component's own origin (scheme, host and port) that answers with its deployed commit"),output:KA.describe("what the URL returned, VERBATIM; this gate FETCHES each url")})).optional().describe("only when shared components are listed above: one check per component whose deployed commit you found")});function Vme(t){let e=[],r=s=>!!s&&typeof s=="object"&&!Array.isArray(s);return t.outcome!=="change-broke-bringup"&&t.outcome!=="bringup-failed"?(!r(t.baseUrls)||Object.keys(t.baseUrls).length===0?e.push("baseUrls must be a non-empty object of service \u2192 url"):Object.values(t.baseUrls).every(s=>typeof s=="string"&&s.trim())||e.push("every baseUrls value must be a non-empty url string"),r(t.health)?!(typeof t.health.url=="string"&&t.health.url.trim())&&!(typeof t.health.command=="string"&&t.health.command.trim())&&e.push("health must record a url or a command (what you actually ran)"):e.push("health must be an object"),(!r(t.dependencies)||Object.keys(t.dependencies).length===0)&&e.push("dependencies must be a non-empty object of name \u2192 boolean (real vs mocked) when the SUT came up \u2014 account for every backing service so a mocked one can't be hidden behind a green run")):(r(t.bringupError)||e.push(`outcome "${String(t.outcome)}" requires bringupError { command, output } \u2014 the exact failing bring-up command and what it printed`),t.outcome==="change-broke-bringup"&&!(Array.isArray(t.suspectFiles)&&t.suspectFiles.length>0&&t.suspectFiles.every(s=>typeof s=="string"&&s.trim()))&&e.push("change-broke-bringup requires non-empty suspectFiles[] \u2014 the changed file(s) the failure points at; if you cannot point at a file this PR changed, the outcome is bringup-failed (environment/harness), not the PR's fault")),t.outcome==="recipe-drift"&&!(Array.isArray(t.recipeFixes)&&t.recipeFixes.length>0)&&e.push("recipe-drift outcome requires a non-empty recipeFixes[] describing what was corrected"),e}var To=y.string().trim().min(1),Wme=(r=>(r.TestbotManaged="testbot_managed",r.CustomerDeployed="customer_deployed",r))(Wme||{}),QR=[".skyramp/sut/setup.sh",".skyramp/sut/teardown.sh"],LG=y.object({schemaVersion:y.literal(1),type:y.nativeEnum(Wme).optional(),status:y.enum(["ready","blocked"]),environment:_R.optional(),components:y.array(y.object({name:To,repository:To.describe(`owner/repo, or "${yn}" for a customer-deployed component no repository builds`),healthy:y.boolean(),url:y.string().min(1).nullable(),...Fme,credentials:y.array(y.string().regex(WA)).max(50).optional(),deployed:To.nullable().optional().describe("customer_deployed only: the revision the component runs, as setup read it (WF-SETUP-22's Deployed now), or null when it could not tell")}).strict()),suites:y.array(y.object({framework:To,file:To,result:y.enum(["pass","fail","error"])}).strict()),inputsUsed:y.array(To),inputsUsedHow:y.array(y.object({input:To,how:To}).strict()).optional(),inputsNotUsed:y.array(y.object({input:To,reason:To}).strict()),blockers:y.array(y.object({component:To,problem:To,evidence:To,fix:To}).strict()),replay:y.object({outcome:To,durationSeconds:y.number().nonnegative().nullable()}).strict().nullable(),files:y.array(y.object({path:To,content:y.string()}).strict())}).strict().superRefine((t,e)=>{t.inputsUsedHow?.forEach((s,i)=>{t.inputsUsed.includes(s.input)||e.addIssue({code:y.ZodIssueCode.custom,path:["inputsUsedHow",i,"input"],message:"not one of inputsUsed"})}),t.components.forEach((s,i)=>{s.credentials&&new Set(s.credentials).size!==s.credentials.length&&e.addIssue({code:y.ZodIssueCode.custom,path:["components",i,"credentials"],message:"names a credential twice"})});let r=t.type==="customer_deployed";r!==(t.environment!==void 0)&&e.addIssue({code:y.ZodIssueCode.custom,path:["environment"],message:"an environment exactly when the plan's type is customer_deployed"}),t.environment&&new Set(t.environment.credentials).size!==t.environment.credentials.length&&e.addIssue({code:y.ZodIssueCode.custom,path:["environment","credentials"],message:"names a credential twice"});let n=new Set(t.components.map(s=>s.name));if(t.environment?.revisionSources.forEach((s,i)=>{s.components.forEach((o,a)=>{n.has(o)||e.addIssue({code:y.ZodIssueCode.custom,path:["environment","revisionSources",i,"components",a],message:"not one of components"})})}),t.components.forEach((s,i)=>{s.deployed!==void 0!==r&&e.addIssue({code:y.ZodIssueCode.custom,path:["components",i,"deployed"],message:"what a component runs exactly when the plan is customer_deployed"}),s.repository===yn&&!r&&e.addIssue({code:y.ZodIssueCode.custom,path:["components",i,"repository"],message:`only a customer_deployed component is ${yn}`})}),r&&(t.components.forEach((s,i)=>{t.components.findIndex(o=>o.name===s.name)!==i&&e.addIssue({code:y.ZodIssueCode.custom,path:["components",i,"name"],message:"names a component twice"})}),t.replay!==null&&e.addIssue({code:y.ZodIssueCode.custom,path:["replay"],message:"a customer_deployed plan is never replayed"}),t.files.forEach((s,i)=>{QR.includes(s.path)&&e.addIssue({code:y.ZodIssueCode.custom,path:["files",i,"path"],message:"a customer_deployed plan has no script that starts or stops the system"})})),r&&t.status==="ready"){let s=new Set(t.environment?.revisionSources.flatMap(i=>i.components));t.components.forEach((i,o)=>{i.repository!==yn&&!s.has(i.name)&&e.addIssue({code:y.ZodIssueCode.custom,path:["components",o,"name"],message:"a ready customer_deployed plan reads what every component a repository builds runs"})})}});var ulr=["clean","recipe-drift"];function XA(t){let e=Ynt.posix.normalize(t);return e===t&&(e===".skyramp/workspace.yml"||e.startsWith(".skyramp/sut/")&&e.length>13)}function dlr(t,e){let r=e.bringupError;if(t.environment)return{component:t.components.map(s=>s.name).join(", ")||"SUT",problem:`onboard reached the deployment, but deploy's fresh check of it ended ${e.outcome}`,evidence:r?`$ ${r.command}
|
|
316
316
|
${r.output}`:`deploy reported ${e.outcome} without the failing command`,fix:"make .skyramp/sut/health.json's check pass from a fresh session (its address, sign-in and ready route), then set it up again"};let n=e.suspectFiles?.length?` \u2014 it points at ${e.suspectFiles.join(", ")}`:"";return{component:t.components.map(s=>s.name).join(", ")||"SUT",problem:`the recipe worked once but not from nothing: deploy's fresh replay of .skyramp/sut/setup.sh ended ${e.outcome}`,evidence:r?`$ ${r.command}
|
|
317
317
|
${r.output}`:`deploy reported ${e.outcome} without the failing command`,fix:e.outcome==="change-broke-bringup"?`fix the change that broke bring-up${n}, then onboard again`:"make .skyramp/sut/setup.sh bring the SUT up from a clean checkout (what onboard's session had that a fresh run lacks), then onboard again"}}function plr(t){return t.environment?{component:t.components.map(e=>e.name).join(", ")||"SUT",problem:"the deployment was never checked from a fresh session: deploy did not run or wrote no deploy.json",evidence:"outputs/deploy.json is missing from this run",fix:"run deploy after onboard in the same run so it checks the deployment is ready; if deploy ran, its stage log says why it wrote no deploy.json"}:{component:t.components.map(e=>e.name).join(", ")||"SUT",problem:"the recipe was never replayed: deploy did not run or wrote no deploy.json",evidence:"outputs/deploy.json is missing from this run",fix:"run deploy after onboard in the same run so it replays .skyramp/sut/setup.sh from a clean start; if deploy ran, its stage log says why it wrote no deploy.json"}}function mlr(t){return{component:"SUT recipe",problem:"deploy fixed recipe drift, but the recipe it fixed was not collected \u2014 onboard's copy is the recipe from before the fix",evidence:`deploy reported recipe-drift: ${(t.recipeFixes??[]).join("; ")||"no fixes listed"}`,fix:"collect .skyramp/sut/ and .skyramp/workspace.yml after deploy (collectRecipeFiles) and build the plan from that collection"}}var Yme=[".skyramp/sut/setup.sh",".skyramp/sut/teardown.sh",".skyramp/sut/health.json",".skyramp/workspace.yml"],Jme=[".skyramp/sut/health.json",".skyramp/workspace.yml"];function flr(t){return`Onboard again so it leaves the whole recipe in the checkout: ${t.map(r=>r===".skyramp/workspace.yml"?"create .skyramp/workspace.yml with skyramp_init_scan and skyramp_init_workspace":`write ${r} as a regular file (a symlink is not uploaded)`).join("; ")}.`}function Kme(t,e,r){return e&&r||t}function Xme(t,e,r={}){let n=e!==void 0&&!ulr.includes(e.outcome),s=Kme(t,e,r.recipeFiles),i=e?.outcome==="recipe-drift"&&!r.recipeFiles,o=(s.recipeFilesOmitted??[]).filter(w=>XA(w.path)),a=o.length?[{component:"SUT recipe",problem:`The recipe could not be uploaded whole: ${o.map(w=>w.path).join(", ")} left out.`,evidence:o.map(w=>`${w.path}: ${w.reason}`).join("; "),fix:"Keep each recipe file text-only and under 64 KiB, and the recipe under 512 KiB in total \u2014 move large generated content out of .skyramp/sut/ and have setup.sh produce it."}]:[],c=t.status==="ready",l=t.environment,u=new Set(s.recipeFiles.map(w=>w.path)),d=c?(l?Jme:Yme).filter(w=>!u.has(w)):[],p=d.length?[{component:"SUT recipe",problem:`The recipe is missing ${d.join(", ")}, so it cannot be replayed.`,evidence:`collected: ${[...u].sort().join(", ")||"nothing"}`,fix:flr(d)}]:[],m=e?n?[dlr(t,e)]:[]:c?[plr(t)]:[],f=new Set(l?.revisionSources.flatMap(w=>w.components)),h=l&&c?t.components.filter(w=>w.repository!==yn&&!f.has(w.name)).map(w=>w.name):[],b=h.length?[{component:h.join(", "),problem:`Testbot cannot tell which revision ${h.join(" and ")} ${h.length>1?"run":"runs"}, so a run could not say which changes it tested.`,evidence:`revision sources: ${l.revisionSources.map(w=>`${w.detail} (${w.components.join(", ")})`).join("; ")||"none"}`,fix:"Say in the Test Environment's notes how to tell what is deployed, such as a version route (GET /version), then set it up again."}]:[],E=[...t.blockers,...m,...i&&e?[mlr(e)]:[],...a,...p,...b,...r.revisionCheck?.blockers??[],...r.credentialBlockers??[]],A=e?.baseUrls??{};return{schemaVersion:1,...l?{type:"customer_deployed",environment:Jnt(l)}:{},status:c&&e!==void 0&&!n&&!i&&o.length===0&&d.length===0&&h.length===0&&!r.revisionCheck?.blockers.length&&!r.credentialBlockers?.length?"ready":"blocked",components:t.components.map(w=>({name:w.name,repository:w.repository,healthy:w.healthy&&!n,url:Object.hasOwn(A,w.name)&&A[w.name]||null,...w.steps?{steps:w.steps.map(C=>({action:C.action,text:C.text,source:C.source,file:C.file}))}:{},...w.kind?{kind:w.kind}:{},...w.from?{from:{file:w.from.file,service:w.from.service}}:{},...w.credentials?{credentials:[...new Set(w.credentials)].filter(C=>WA.test(C))}:{},...l?{deployed:hlr(w,r)}:{}})),suites:t.suites.map(w=>({framework:w.framework,file:w.file,result:w.result})),inputsUsed:[...t.inputsUsed],...t.inputsUsedHow?{inputsUsedHow:t.inputsUsedHow.filter(w=>t.inputsUsed.includes(w.input)).map(w=>({input:w.input,how:w.how}))}:{},inputsNotUsed:t.inputsNotUsed.map(w=>({input:w.input,reason:w.reason})),blockers:E.map(w=>({component:w.component,problem:w.problem,evidence:w.evidence,fix:w.fix})),replay:e&&!l?{outcome:e.outcome,durationSeconds:r.deployDurationSeconds??null}:null,files:s.recipeFiles.filter(w=>XA(w.path)&&!(l&&QR.includes(w.path))).map(w=>({path:w.path,content:w.content}))}}function hlr(t,e){return t.repository===yn?null:e.revisionCheck?e.revisionCheck.deployed[t.name]??null:e.deployed?.[t.name]??t.deployed??null}function Jnt(t){return{address:t.address,readyWhen:t.readyWhen,credentials:[...new Set(t.credentials)],revisionSources:t.revisionSources.map(e=>({method:e.method,detail:e.detail,components:[...e.components]}))}}function Knt(t){return{schemaVersion:1,status:"ready",components:t.components.map(({url:e,deployed:r,...n})=>({...n,healthy:!0})),suites:t.suites,inputsUsed:t.inputsUsed,...t.inputsUsedHow?{inputsUsedHow:t.inputsUsedHow}:{},inputsNotUsed:t.inputsNotUsed,blockers:[],recipeFiles:t.files,recipeFilesOmitted:[],...t.environment?{environment:Jnt(t.environment)}:{}}}var cst={handshake:"/api/v1/runner/runs/:runId/attempts",report:"/api/v1/runner/attempts/:attemptId/report",end:"/api/v1/runner/attempts/:attemptId/end",configuration:"/api/v1/runner/attempts/:attemptId/configuration",progress:"/api/v1/runner/attempts/:attemptId/progress",sutRecipe:"/api/v1/runner/attempts/:attemptId/sut-recipe",runtimePlan:"/api/v1/runner/attempts/:attemptId/runtime-plan",heartbeat:"/api/v1/runner/attempts/:attemptId/heartbeat",setupEvents:"/api/v1/runner/attempts/:attemptId/setup-events",requirements:"/api/v1/runner/attempts/:attemptId/requirements",requirementFile:"/api/v1/runner/attempts/:attemptId/requirements/:key/file"},$G=(r=>(r.GitHub="github",r.AzureDevOps="azure-devops",r))($G||{}),efe=(i=>(i.Trigger="TRIGGER",i.Baseline="BASELINE",i.AuthoritativeRelatedChange="AUTHORITATIVE_RELATED_CHANGE",i.ConfiguredSharedDependency="CONFIGURED_SHARED_DEPENDENCY",i.ManualOverride="MANUAL_OVERRIDE",i))(efe||{}),qG=(i=>(i.PullRequest="pull_request",i.ReadyForReview="ready_for_review",i.Schedule="schedule",i.Manual="manual",i.SutSetup="sut_setup",i))(qG||{}),glr=["sut_setup"],Alr=["sut_setup","schedule"],ylr=["sut_setup"],HG=(e=>(e.PullRequest="pull_request",e))(HG||{}),zG=(s=>(s.ModelProvider="model_provider",s.SutAccess="sut_access",s.Skyramp="skyramp",s.Other="other",s))(zG||{});var GG=(s=>(s.ReportUploaded="report_uploaded",s.NoReport="no_report",s.Cancelled="cancelled",s.RecipeUploaded="recipe_uploaded",s))(GG||{}),lst=(r=>(r.Running="running",r.Ended="ended",r))(lst||{}),jG=(o=>(o.TimedOut="timed_out",o.AgentFailed="agent_failed",o.SetupFailed="setup_failed",o.CredentialMissing="credential_missing",o.RunnerLost="runner_lost",o.CheckoutFailed="checkout_failed",o))(jG||{}),tfe=(n=>(n.Onboard="onboard",n.Deploy="deploy",n.Recheck="recheck",n))(tfe||{}),rfe=(r=>(r.Started="started",r.Finished="finished",r))(rfe||{}),nfe=(n=>(n.Passed="passed",n.Failed="failed",n.Skipped="skipped",n))(nfe||{}),sfe=(o=>(o.Log="log",o.Component="component",o.Reply="reply",o.Question="question",o.Delivered="delivered",o.Credentials="credentials",o))(sfe||{}),VG=(n=>(n.ChooseCredential="choose_credential",n.FreeText="free_text",n.ChooseSource="choose_source",n))(VG||{});var FR=(n=>(n.Discover="discover",n.Start="start",n.Check="check",n))(FR||{}),Q_=(s=>(s.Found="found",s.Starting="starting",s.Up="up",s.OutOfScope="out_of_scope",s))(Q_||{}),Yu=y.string().regex(/^[1-9][0-9]{0,18}$/),$R=y.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/),qR=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ha=y.string().regex(qR),da=y.string().regex(/^[0-9a-f]{64}$/),FG=y.object({id:Ha,revision:Yu}).strict(),WG={provider:y.literal("github"),providerAccountId:Yu,providerRepositoryId:Yu},YG={provider:y.literal("azure-devops"),providerAccountId:Ha,providerRepositoryId:Ha},ey=y.discriminatedUnion("provider",[y.object(WG).strict(),y.object(YG).strict()]),ife=y.discriminatedUnion("provider",[y.object(WG).passthrough(),y.object(YG).passthrough()]),B_=t=>`${t.provider}:${t.providerRepositoryId}`,Xnt={namespace:y.string().min(1),name:y.string().min(1)},ust=y.discriminatedUnion("provider",[y.object({...WG,...Xnt}).strict(),y.object({...YG,...Xnt}).strict()]),Znt=y.object({ref:y.string().min(1),revision:$R}).strict(),blr=y.object({repository:ust,revision:$R,ref:y.string().nullable(),reason:y.nativeEnum(efe),change:y.object({kind:y.nativeEnum(HG),number:Yu,base:Znt.optional()}).strict().nullable(),compareWith:Znt.optional()}).strict();function Elr(t){let e=t.baseline.sources,r=t.trigger.kind==="schedule"&&t.baseline.confirmedRunId!==null;if(!e)return r?"names every source of the snapshot, once":null;if(t.baseline.confirmedRunId===null)return"a run with no Confirmed Baseline names no baseline sources";let n=new Set(t.sources.map(o=>B_(o.repository))),s=new Set(e.map(o=>B_(o.repository)));return s.size===e.length&&s.size===n.size&&[...s].every(o=>n.has(o))?null:"names every source of the snapshot, once"}var dst=/^[A-Z][A-Z0-9_]+-[1-9][0-9]*$/,pst=/^[1-9][0-9]{0,18}$/,est=new RegExp(`${dst.source}|${pst.source}`),tst=/^https:\/\/[a-z0-9-]+(\.[a-z0-9-]+)+$/,wlr=y.union([y.object({source:y.literal("jira"),site:y.string().regex(tst),key:y.string().regex(dst),updated:y.string().datetime(),contentHash:da}).strict(),y.object({source:y.literal("confluence"),site:y.string().regex(tst),key:y.string().regex(pst),version:y.number().int().positive(),contentHash:da}).strict(),y.object({source:y.literal("other"),key:y.string().regex(v_),contentHash:da}).strict(),y.object({source:y.literal("other"),key:y.string().regex(Uw),contentHash:da,fileName:y.string().min(1).max(255),mediaType:y.nativeEnum(MR)}).strict()]),rst=y.union([y.literal("jira"),y.literal("confluence")]),mst=y.object({schemaVersion:y.literal(1),items:y.array(y.union([y.object({source:rst,site:y.string(),key:y.string().regex(est),state:y.literal("read"),text:y.string(),version:y.string().min(1),contentMatches:y.boolean()}).strict(),y.object({source:rst,site:y.string(),key:y.string().regex(est),state:y.literal("not_read"),reason:y.nativeEnum(Lw)}).strict(),y.object({source:y.literal("other"),key:y.string().regex(v_),state:y.literal("read"),text:y.string(),version:y.string().min(1),contentMatches:y.boolean()}).strict(),y.object({source:y.literal("other"),key:y.string().regex(v_),state:y.literal("not_read"),reason:y.nativeEnum(Lw)}).strict(),y.object({source:y.literal("other"),key:y.string().regex(Uw),state:y.literal("read"),version:da,fileName:y.string().min(1).max(255),mediaType:y.nativeEnum(MR)}).strict(),y.object({source:y.literal("other"),key:y.string().regex(Uw),state:y.literal("not_read"),reason:y.nativeEnum(Lw)}).strict()])),instructions:y.array(y.string()).optional()}).strict(),xlr=y.object({schemaVersion:y.literal(1),runId:Ha,skyrampOrgId:Ha,target:FG,policy:FG.nullable(),trigger:y.object({kind:y.nativeEnum(qG),requestedAt:y.string().datetime()}).strict(),configuration:y.object({captureId:Ha,revision:Yu.nullable(),hash:da}).strict(),baseline:y.object({confirmedRunId:Ha.nullable(),sources:y.array(y.object({repository:ey,revision:$R}).strict()).optional()}).strict(),sources:y.array(blr).min(1),execution:y.object({provider:y.nativeEnum($G),repository:ust,workflowPath:y.string(),ref:y.string()}).strict(),credentials:y.array(y.object({name:y.string(),purpose:y.nativeEnum(zG),required:y.boolean()}).strict()),requirements:y.array(wlr).min(1).optional(),instructions:y.object({contentHash:da}).strict().optional()}).strict().superRefine((t,e)=>{let r=new Set;(t.requirements??[]).forEach((o,a)=>{let c="fileName"in o?"file":"pasted";o.source==="other"&&o.key!==`${c}-${o.contentHash.slice(0,16)}`&&e.addIssue({code:y.ZodIssueCode.custom,message:"is not the key of its content hash",path:["requirements",a,"key"]});let l=Oc({source:o.source,key:o.key});r.has(l)&&e.addIssue({code:y.ZodIssueCode.custom,message:"names an item that the run already names",path:["requirements",a,"key"]}),r.add(l)});let n=t.trigger.kind,s=glr.includes(n);s!==(t.policy===null)&&e.addIssue({code:y.ZodIssueCode.custom,path:["policy"],message:s?`a ${n} run has no policy`:"names the policy revision"});let i=Elr(t);i&&e.addIssue({code:y.ZodIssueCode.custom,path:["baseline","sources"],message:i}),Alr.includes(n)&&t.sources.forEach((o,a)=>{o.reason!=="BASELINE"&&e.addIssue({code:y.ZodIssueCode.custom,path:["sources",a,"reason"],message:`a ${n} run selects only BASELINE sources`})}),t.sources.forEach((o,a)=>{o.compareWith&&(o.reason!=="MANUAL_OVERRIDE"||o.change)&&e.addIssue({code:y.ZodIssueCode.custom,path:["sources",a,"compareWith"],message:"only a MANUAL_OVERRIDE source without a change names a revision to compare with"})})});var ofe=(r=>(r.Person="person",r.Policy="policy",r))(ofe||{}),Slr=y.object({kind:y.nativeEnum(ofe),name:y.string().min(1).max(256)}).strict(),Clr=y.object({schemaVersion:y.literal(1),attempt:y.object({id:Ha,number:y.number().int().positive(),deadlineAt:y.string().datetime()}).strict(),manifest:xlr,manifestHash:da,entitlements:y.array(y.string()).optional(),runToken:y.string().min(1).optional(),requestedBy:Slr.nullable().optional(),writeAllowed:y.boolean().optional(),claudeCodeVersion:y.string().regex(/^[0-9]+\.[0-9]+\.[0-9]+$/,"an exact version, such as 2.1.290").nullable().optional()}).strict(),nst={providerRunAttempt:y.number().int().positive(),workflowRef:y.string().min(1)},Ilr=y.string().regex(/^[^/]+\/[^/]+\/[1-9][0-9]{0,15}\/[1-9][0-9]{0,15}$/),Rlr=y.object({schemaVersion:y.literal(1),runId:Ha,execution:y.discriminatedUnion("provider",[y.object({...nst,provider:y.literal("github"),repository:y.object(WG).strict(),providerRunId:Yu}).strict(),y.object({...nst,provider:y.literal("azure-devops"),repository:y.object(YG).strict(),providerRunId:Ilr}).strict()]),requester:y.literal(!0).optional(),writeCheck:y.literal(!0).optional(),claudeCodePin:y.literal(!0).optional()}).strict(),sst=y.object({repository:ey,number:Yu}).strict(),vlr=y.discriminatedUnion("status",[y.object({status:y.literal("none")}).strict(),y.object({status:y.literal("delivered"),pullRequests:y.array(sst).min(1)}).strict(),y.object({status:y.literal("partial"),pullRequests:y.array(sst).min(1),failures:y.array(y.object({repository:ey,message:y.string()}).strict()).min(1)}).strict(),y.object({status:y.literal("failed"),message:y.string()}).strict()]),Tlr=y.object({sufficiency:y.nativeEnum(T_),rationale:y.string().min(1),gaps:y.array(y.string().min(1)),acceptedEvidence:y.array(y.object({kind:y.nativeEnum(JA),repository:y.string().min(1),revision:$R,reference:y.string().min(1),summary:y.string().min(1)}).strict()),actionRequired:y.array(y.nativeEnum(N_))}).strict().superRefine((t,e)=>{t.sufficiency==="sufficient"!=(t.gaps.length===0)&&e.addIssue({code:y.ZodIssueCode.custom,path:["gaps"],message:"sufficient evidence has no gaps, and insufficient evidence names at least one"}),new Set(t.actionRequired).size!==t.actionRequired.length&&e.addIssue({code:y.ZodIssueCode.custom,path:["actionRequired"],message:"a reason appears twice"})}),UR=500,afe=2048,cfe=1e3,Nlr=y.object({testResults:y.array(y.object({resultId:y.string().regex(/^[^\u0000-\u001f]{1,512}$/),repository:y.string().regex(/^[A-Za-z0-9._-]{1,100}\/[A-Za-z0-9._-]{1,100}$/),testType:y.string(),endpoint:y.string(),status:y.enum(["Pass","Fail","Skipped"]),details:y.string(),fileName:y.string().optional(),testId:y.string().regex(/^[^\u0000-\u001f]{1,512}$/).optional(),failureCause:y.object({kind:y.nativeEnum(k_),family:y.nativeEnum(OG).optional()}).strict().optional()}).strict()),validation:Tlr,changes:y.array(y.object({id:y.string().min(1).max(512),text:y.string().max(16384),source:y.string().max(afe),testedBy:y.array(y.string().min(1).max(1024)).max(UR),writtenBy:y.array(y.string().min(1).max(1024)).max(UR),maintainedBy:y.array(y.string().min(1).max(1024)).max(UR)}).strict()).max(cfe).optional(),traceVersion:y.literal(1)}).passthrough().superRefine((t,e)=>{let r=new Set;t.testResults.forEach((n,s)=>{let i=n.failureCause;i&&n.status==="Pass"&&e.addIssue({code:y.ZodIssueCode.custom,path:["testResults",s,"failureCause"],message:"a passing result has no failure cause"}),i&&i.kind==="environment"!=(i.family!==void 0)&&e.addIssue({code:y.ZodIssueCode.custom,path:["testResults",s,"failureCause"],message:"an environment cause names its family, and no other cause does"});let o=["testResults",s,"resultId"],a=n.resultId.slice(`${n.repository}:${n.testType}:`.length);(!n.resultId.startsWith(`${n.repository}:${n.testType}:`)||a===""||a.startsWith("/")||a.startsWith("#"))&&e.addIssue({code:y.ZodIssueCode.custom,path:o,message:"is not repository:testType:path for this result"}),r.has(n.resultId)&&e.addIssue({code:y.ZodIssueCode.custom,path:o,message:"stable identity repeated"}),r.add(n.resultId)})}),ist=t=>t.replace(/[%:#]/g,e=>encodeURIComponent(e));function JG(t,e,r,n){let s=r.replace(/\\/g,"/"),i=s.split("/").filter(c=>c!==""&&c!==".");if(s.startsWith("/")||/^[A-Za-z]:/.test(s)||i.length===0||i.includes(".."))throw new Error(`testResultId needs a path relative to the repository root, got "${r}"`);let o=i.join("/"),a=`${t}:${e}:${ist(o)}`;return n?`${a}#${ist(n)}`:a}var lfe=50,ost=y.string().regex(/^(?!.*\.\.)(?!\/)(?!.*\/$)[A-Za-z0-9._/-]{1,255}$/),ufe=y.discriminatedUnion("kind",[y.object({kind:y.literal("branch_pushed"),repository:ey,branch:ost,commit:$R}).strict(),y.object({kind:y.enum(["pull_request_opened","pull_request_edited"]),repository:ey,number:Yu,branch:ost}).strict()]),fst=y.object({schemaVersion:y.literal(1),run:y.object({runId:Ha,attemptNumber:y.number().int().positive(),manifestHash:da}).strict(),target:FG,policy:FG,provenance:y.object({sources:y.array(y.object({repository:ey,revision:$R}).strict())}).strict(),delivery:y.object({generatedTests:vlr}).strict(),producer:y.object({testbot:y.string().regex(/^[0-9A-Za-z.+-]{1,64}$/),mcp:y.string().regex(/^[0-9A-Za-z.+-]{1,64}$/)}).strict(),report:Nlr,githubWrites:y.array(ufe).max(lfe).optional()}).strict(),klr=fst.pick({schemaVersion:!0,run:!0,target:!0,provenance:!0,producer:!0}).extend({recipe:LG}).strict().superRefine(({recipe:t},e)=>{let r=(i,o)=>e.addIssue({code:y.ZodIssueCode.custom,path:["recipe",...i],message:o});t.status==="blocked"&&t.blockers.length===0&&r(["blockers"],"a blocked recipe names at least one blocker");let n=new Set,s=0;t.files.forEach((i,o)=>{XA(i.path)||r(["files",o,"path"],"is not .skyramp/workspace.yml or a file under .skyramp/sut/"),n.has(i.path)&&r(["files",o,"path"],"file repeated"),n.add(i.path),BG.test(i.content)&&r(["files",o,"content"],"is not text");let a=Buffer.byteLength(i.content,"utf8");s+=a,a>Ow&&r(["files",o,"content"],`larger than ${Ow} bytes`)}),s>Mw&&r(["files"],`recipe text over ${Mw} bytes in total`)}),hst=y.object({schemaVersion:y.literal(1),stage:y.nativeEnum(tfe),event:y.nativeEnum(rfe),status:y.nativeEnum(nfe).optional()}).strict().refine(t=>t.status===void 0||t.event==="finished",{path:["status"],message:"only a finished stage has a status"}),HR=100,KG=5e3,Zme=2e3,__=100,XG=/^[A-Za-z0-9_-]{1,64}$/,dfe=20,pfe=200,mfe=100,ffe=100,Plr=200,Blr=/^[^/\s]+\/[^/\s]+$/,hfe=500,gfe=50,Afe=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/,am=t=>y.string().max(t).refine(e=>e.trim().length>0&&!Afe.test(e),"blank, or not text"),LR={sequence:y.number().int().min(1).max(KG),at:y.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?Z$/)},yfe=y.discriminatedUnion("kind",[y.object({...LR,kind:y.literal("log"),phase:y.nativeEnum(FR),text:am(Zme)}).strict(),y.object({...LR,kind:y.literal("component"),name:am(__),repository:am(Plr).refine(t=>Blr.test(t)||t===yn,"not owner/name"),file:am(hfe).nullable(),status:y.nativeEnum(Q_),version:am(ffe).optional()}).strict(),y.object({...LR,kind:y.literal("reply"),to:y.string().uuid(),accepted:y.boolean(),text:am(Zme)}).strict(),y.object({...LR,kind:y.literal("question"),id:y.string().regex(XG),type:y.nativeEnum(VG),text:am(Zme),component:am(__).nullable(),choices:y.array(am(pfe)).max(dfe),placeholder:am(mfe).optional()}).strict(),y.object({...LR,kind:y.literal("delivered"),ids:y.array(y.string().uuid()).max(HR)}).strict(),y.object({...LR,kind:y.literal("credentials"),names:y.array(y.string().regex(WA)).min(1).max(gfe)}).strict()]).superRefine((t,e)=>{t.kind==="credentials"&&new Set(t.names).size!==t.names.length&&e.addIssue({code:y.ZodIssueCode.custom,path:["names"],message:"a name twice"}),t.kind==="question"&&(t.type==="free_text"!=(t.choices.length===0)&&e.addIssue({code:y.ZodIssueCode.custom,path:["choices"],message:"choices exactly when the question is not free_text"}),new Set(t.choices).size!==t.choices.length&&e.addIssue({code:y.ZodIssueCode.custom,path:["choices"],message:"a choice twice"}))}),gst=y.object({schemaVersion:y.literal(1),events:y.array(yfe).max(HR)}).strict(),ast={id:y.string().uuid(),text:y.string(),by:y.string().nullable(),at:y.string()},_lr=y.discriminatedUnion("kind",[y.object({...ast,kind:y.literal("instruction"),question:y.null()}),y.object({...ast,kind:y.literal("answer"),question:y.string().regex(XG)})]),Ast=y.string().regex(/^[A-Za-z0-9+/]{43}=$/),yst=y.object({schemaVersion:y.literal(1),leftOut:y.array(y.string()),messages:y.array(_lr).optional(),stop:y.object({key:Ast}).optional()}),L_=7,ZG=500*1024*1024,bst=y.object({id:Yu,name:y.string().regex(/^[A-Za-z0-9._-]{1,200}$/),providerRunId:Yu,expiresAt:y.string().datetime()}).strict(),Est=y.object({schemaVersion:y.literal(1),artifact:bst,sessionId:Ha,contentHash:da,bytes:y.number().int().min(1).max(ZG)}).strict(),wst=y.object({schemaVersion:y.literal(1),checkpoint:y.object({artifact:bst,repository:y.object({namespace:y.string().min(1),name:y.string().min(1)}).strict(),sessionId:Ha,contentHash:da,key:Ast}).strict().nullable()}).strict(),Dlr=200,UG=100,ej=(n=>(n.Resume="resume",n.Retry="retry",n.Update="update",n))(ej||{}),Olr=y.object({kind:y.nativeEnum(ej),setup:y.object({runId:Ha,endedAt:y.string().nullable(),outcome:y.string().nullable()}).strict(),components:y.array(y.object({name:y.string().min(1),repository:y.string().min(1),status:y.nativeEnum(Q_)}).strict()).max(UG),credentials:y.array(y.string().min(1)).max(UG),answers:y.array(y.object({question:y.string(),answer:y.string().nullable()}).strict()).max(UG),instructions:y.array(y.object({text:y.string(),reply:y.string().nullable()}).strict()).max(UG),log:y.array(y.object({phase:y.nativeEnum(FR),text:y.string()}).strict()).max(Dlr)}).strict(),xst=y.object({schemaVersion:y.literal(1),context:Olr.nullable()}).strict(),Sst=y.object({schemaVersion:y.literal(1),configuration:y.object({captureId:Ha,revision:Yu.nullable(),hash:da}).strict(),capture:y.object({schemaVersion:y.literal(1),settings:y.object({target:y.object({environment:y.unknown()}).passthrough(),timeoutMinutes:y.number().int().positive(),answerWaitMinutes:y.number().int().positive().optional(),testEnvironment:y.object({name:y.string().min(1),address:y.string().min(1).optional(),readyWhen:y.string().min(1).optional()}).passthrough().optional()}).passthrough(),provenance:y.object({}).passthrough(),hash:da}).strict()}).strict(),Mlr=_R.extend({version:y.number().int().positive(),components:y.array(y.object({name:y.string().min(1),repository:y.string().min(1)}).strict()),contentHash:da.optional(),files:y.array(y.object({path:y.string().refine(t=>XA(t)&&!QR.includes(t),"not a file of a customer_deployed plan"),content:y.string()}).strict()).optional()}).strict(),Cst=y.object({schemaVersion:y.literal(1),testEnvironment:Mlr.nullable().optional(),runtimePlan:y.object({version:y.number().int().positive(),contentHash:da,files:y.array(y.object({path:y.string().refine(XA,"not a recipe file path"),content:y.string()}).strict()).min(1),recipe:y.record(y.unknown()).optional()}).strict().nullable()}).strict().refine(t=>!(t.runtimePlan&&t.testEnvironment),{message:"a run pins a recipe or a customer's Test Environment, never both",path:["testEnvironment"]}),Ist=y.object({schemaVersion:y.literal(1),state:y.nativeEnum(lst),ending:y.nativeEnum(GG).nullable(),cause:y.nativeEnum(jG).nullable(),deadlineAt:y.string().datetime()}).strict();function bfe(t,e){return t.state==="ended"?t.ending==="cancelled"?"cancelled":t.cause==="runner_lost"?"expired":"ended":e.getTime()>=Date.parse(t.deadlineAt)?"expired":null}function ZA(t){if(typeof t=="number"&&!Number.isFinite(t))throw new TypeError("Canonical JSON requires JSON values");if(Array.isArray(t))return`[${t.map(ZA).join(",")}]`;if(t!==null&&typeof t=="object"){let r=t;return`{${Object.keys(r).sort().map(n=>`${JSON.stringify(n)}:${ZA(r[n])}`).join(",")}}`}let e=JSON.stringify(t);if(e===void 0)throw new TypeError("Canonical JSON requires JSON values");return e}function Efe(t){return(0,M_.createHash)("sha256").update(ZA(t),"utf8").digest("hex")}function Rst(t){let e=[...t].sort((r,n)=>r.path<n.path?-1:r.path>n.path?1:0).map(r=>({path:r.path,content:r.content}));return(0,M_.createHash)("sha256").update(ZA(e),"utf8").digest("hex")}function vst(t){let e=(i,o)=>i<o?-1:i>o?1:0,r=[...t.files].sort((i,o)=>e(i.path,o.path)).map(i=>({path:i.path,content:i.content})),n={address:t.address,readyWhen:t.readyWhen,credentials:[...t.credentials].sort(e),revisionSources:t.revisionSources.map(i=>ZA({method:i.method,detail:i.detail,components:[...i.components].sort(e)})).sort(e)},s=t.components.map(i=>ZA({name:i.name,repository:i.repository})).sort(e);return(0,M_.createHash)("sha256").update(ZA({type:"customer_deployed",environment:n,components:s,files:r}),"utf8").digest("hex")}function Tst(t){return(0,M_.createHash)("sha256").update(ZA({schemaVersion:t.schemaVersion,settings:t.settings,provenance:t.provenance}),"utf8").digest("hex")}var D_=t=>({provider:t.provider,providerAccountId:t.providerAccountId,providerRepositoryId:t.providerRepositoryId});function Nst(t,e){return Rlr.parse({schemaVersion:1,runId:t,execution:e.execution(),requester:!0,writeCheck:!0,claudeCodePin:!0})}function kst(t){let e=Clr.parse(t);if(Efe(e.manifest)!==e.manifestHash)throw new Error("The handshake manifest hash does not match its manifest");return e}function Qlr(t){let e=r=>r.map(n=>({repository:D_(n.repository),number:n.number}));return t.status==="delivered"?{status:t.status,pullRequests:e(t.pullRequests)}:t.status==="partial"?{status:t.status,pullRequests:e(t.pullRequests),failures:t.failures.map(r=>({repository:D_(r.repository),message:r.message}))}:t}function Pst(t){return t.issues.map(e=>`${e.path.map((n,s)=>typeof n=="number"?`[${n}]`:s===0?n:`.${n}`).join("")}: ${e.message}`).join("; ")}function Bst(t){let{manifest:e}=t;if(ylr.includes(e.trigger.kind))throw new Error(`The report upload is invalid: a ${e.trigger.kind} run uploads its SUT recipe, never a report`);let r=fst.safeParse({schemaVersion:1,run:{runId:e.runId,attemptNumber:t.attemptNumber,manifestHash:Efe(e)},target:{id:e.target.id,revision:e.target.revision},policy:e.policy&&{id:e.policy.id,revision:e.policy.revision},provenance:{sources:t.checkedOut.map(n=>({repository:D_(n.repository),revision:n.revision}))},delivery:{generatedTests:Qlr(t.generatedTests)},producer:t.producer,report:t.report,...t.githubWrites?.length?{githubWrites:t.githubWrites.map(n=>({...n,repository:D_(n.repository)}))}:{}});if(!r.success)throw new Error(`The report upload is invalid: ${Pst(r.error)}`);return Llr(r.data,e),r.data}function _st(t,e,r,n,s){let i=klr.safeParse({schemaVersion:1,run:{runId:t.runId,attemptNumber:e,manifestHash:Efe(t)},target:{id:t.target.id,revision:t.target.revision},provenance:{sources:r.map(o=>({repository:D_(o.repository),revision:o.revision}))},producer:s,recipe:n});if(!i.success)throw new Error(`The SUT recipe upload is invalid: ${Pst(i.error)}`);return i.data}function Llr(t,e){let r=new Map(e.sources.map(n=>[`${n.repository.namespace}/${n.repository.name}`.toLowerCase(),n.revision]));t.report.validation.acceptedEvidence.forEach((n,s)=>{let i=`report.validation.acceptedEvidence[${s}]`,o=r.get(n.repository.toLowerCase());if(!o)throw new Error(`${i}.repository: ${n.repository} is outside the run's snapshot`);if(n.revision!==o)throw new Error(`${i}.revision: evidence is not from the frozen revision ${o}`)})}var Dst=$(require("fs")),U_="SKYRAMP_AZURE_SUPERVISED",wfe=3;function tj(t){return t.replace(/##(?=(?:vso)?\[)/gi,"#\u200B#")}function xfe(t,e=process.env){e[U_]==="1"?Dst.writeSync(wfe,`${JSON.stringify(t)}
|
|
318
318
|
`):process.stdout.write(t.command!==void 0?`${t.command}
|
|
319
319
|
`:t.text??"")}function F_(t){xfe({command:t})}function Ost(t){return t.replace(/%/g,"%AZP25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function Ulr(t){return Ost(t).replace(/;/g,"%3B").replace(/]/g,"%5D")}function zR(t,e,r){let n=Object.entries(e).map(([s,i])=>`${s}=${Ulr(i)}`).join(";");return`##vso[${t}${n?` ${n}`:""}]${Ost(r)}`}function Mst(t){if(!t)return[];let e=t.split(/\r?\n/).filter(r=>r.trim()&&r!==t);return[t,...e].map(r=>zR("task.setsecret",{},r))}function Qst(t,e=F_){for(let r of Mst(t))e(r)}function Flr(t){return t.replace(/%0D/g,"\r").replace(/%0A/g,`
|
|
320
320
|
`).replace(/%25/g,"%")}function Lst(t){let e=/^::([a-z-]+)(?: [^:]*)?::(.*)$/s.exec(t.replace(/\r?\n$/,""));if(!e)return;let[,r,n]=e,s=Flr(n),i=tj(s);switch(r){case"add-mask":return Mst(s);case"warning":case"error":return[zR("task.logissue",{type:r},i)];case"notice":return[i];case"debug":return i.split(`
|
|
321
321
|
`).map(o=>`##[debug]${o}`);case"group":return[`##[group]${i.split(`
|
|
322
|
-
`)[0]}`];case"endgroup":return["##[endgroup]"];default:return[]}}function Fw(t){return t.replace(/\/+$/,"")}function Sfe(t){let e=new URL(t),r=e.pathname.split("/").filter(Boolean);if(r.length)return decodeURIComponent(r[r.length-1]);if(e.hostname.endsWith(".visualstudio.com"))return e.hostname.split(".")[0];throw new Error(`SYSTEM_COLLECTIONURI "${t}" names no organization`)}var $lr=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,48}[A-Za-z0-9])?$/,qlr=/[\\/:*?"<>|;#${},+=[\]%\p{Cc}\p{Cf}]/u;function Ust(t){return t.length>0&&t.length<=64&&t===t.trim()&&!qlr.test(t)&&!/[^\S ]/u.test(t)&&!/^[._]/.test(t)&&!t.endsWith(".")}function rj(t){return q_(`${t.namespace}/${t.name}`)}function q_(t){let e=t.indexOf("/"),r=t.lastIndexOf("/"),n=t.slice(0,e),s=t.slice(e+1,r),i=t.slice(r+1);if(e<0||e===r||!$lr.test(n)||!Ust(s)||!Ust(i))throw new Error(`"${t}" is not an Azure DevOps organization/project/repository`);return{organization:n,project:s,name:i}}function Fst(t,e){let r=Sfe(t);if(r.toLowerCase()!==e.organization.toLowerCase())throw new Error(`${e.organization}/${e.project}/${e.name} is not in ${r}, the Azure DevOps organization this job runs in`)}function $st(t,e){return Fst(t,e),`${Fw(t)}/${encodeURIComponent(e.project)}/_git/${encodeURIComponent(e.name)}`}function H_(t,e){return Fst(t,e),`${Fw(t)}/${encodeURIComponent(e.project)}/_apis/git/repositories/${encodeURIComponent(e.name)}`}var Hlr="7.1",$_=class extends Error{constructor(r,n){super(r);this.status=n}status};async function z_(t){let e=t.accept??"application/json",r=new URL(t.url);r.searchParams.has("api-version")||r.searchParams.set("api-version",Hlr);let n=await(t.fetch??fetch)(r.toString(),{method:t.method??"GET",headers:{Authorization:`Bearer ${t.token}`,Accept:e,...t.body!==void 0?{"Content-Type":"application/json"}:{}},...t.body!==void 0?{body:JSON.stringify(t.body)}:{},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!n.ok){let s=(await n.json().catch(()=>({}))).message;throw new $_(`Azure DevOps answered ${n.status}${typeof s=="string"?`: ${s}`:""}`,n.status)}return e!=="application/json"?Buffer.from(await n.arrayBuffer()):n.status===204?{}:await n.json()}function zlr(t){return`AUTHORIZATION: bearer ${t}`}function nj(t,e){return{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${Fw(t)}/.extraheader`,GIT_CONFIG_VALUE_0:zlr(e)}}var jlr="7.1-preview.1",Vlr=".azure-pipelines/skyramp-testbot-v3.yml";function $w(t){return t.GITHUB_ACTIONS!=="true"&&/^true$/i.test(t.TF_BUILD??"")}var Wlr={INPUT_PIPELINE:"SKYRAMP_PIPELINE",INPUT_SKYRAMPRUNID:"SKYRAMP_RUN_ID",INPUT_SKYRAMPAPPORIGIN:"SKYRAMP_APP_ORIGIN",INPUT_SKYRAMPMCPVERSION:"SKYRAMP_MCP_VERSION",INPUT_SKYRAMPMCPSOURCE:"SKYRAMP_MCP_SOURCE",INPUT_SKYRAMPMCPGITHUBREF:"SKYRAMP_MCP_GITHUB_REF",INPUT_SKYRAMPMCPGITHUBTOKEN:"SKYRAMP_MCP_GITHUB_TOKEN",INPUT_USEBEDROCK:"SKYRAMP_USE_BEDROCK",INPUT_AWSREGION:"SKYRAMP_AWS_REGION",INPUT_AWSROLEARN:"SKYRAMP_AWS_ROLE_ARN"};function qst(t=process.env){if($w(t))for(let[e,r]of Object.entries(Wlr))!t[e]&&t[r]!==void 0&&(t[e]=t[r])}function Hst(t,e={}){let r=d=>{let p=t[d];if(!p)throw new Error(`${d} is not set; the V3 runner handshake needs it`);return p},n=Fw(t.SYSTEM_COLLECTIONURI??""),s=()=>Sfe(r("SYSTEM_COLLECTIONURI")),i=t.SYSTEM_TEAMPROJECT,o=t.BUILD_REPOSITORY_NAME,a=t.BUILD_REPOSITORY_ID?.toLowerCase(),c=t.SYSTEM_ACCESSTOKEN,l=e.mask??(d=>Qst(d)),u=d=>async()=>{if(!d)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_OIDCREQUESTURI to $(System.OidcRequestUri).");if(!c)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_ACCESSTOKEN to $(System.AccessToken).");let p=new URL(d);if(p.protocol!=="https:")throw new Error("SYSTEM_OIDCREQUESTURI is not an https URL");p.searchParams.set("api-version",jlr);let m=await(e.fetch??fetch)(p.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json",Accept:"application/json"},body:"{}",redirect:"error",signal:AbortSignal.timeout(3e4)});if(!m.ok)throw new Error(`Azure DevOps refused the OIDC token request: ${m.status}`);let f=(await m.json().catch(()=>({}))).oidcToken;if(typeof f!="string"||!f)throw new Error("Azure DevOps's OIDC token response carried no token");return l(f),f};return{runnerPlatform:$w(t)?"azure":void 0,workspace:t.BUILD_SOURCESDIRECTORY||void 0,serverUrl:n,apiUrl:n,repository:a&&i&&o&&n?{id:a,slug:`${s()}/${i}/${o}`}:void 0,runId:t.BUILD_BUILDID||void 0,runAttempt:t.SYSTEM_STAGEATTEMPT||void 0,job:t.SYSTEM_JOBNAME||void 0,execution(){let d=r("SYSTEM_STAGEATTEMPT");if(!/^[1-9][0-9]*$/.test(d))throw new Error(`SYSTEM_STAGEATTEMPT is "${d}", not a positive whole number`);let p=r("SYSTEM_COLLECTIONID").toLowerCase();if(!qR.test(p))throw new Error(`SYSTEM_COLLECTIONID is "${p}", not a GUID`);let m=r("BUILD_REPOSITORY_ID").toLowerCase();if(!qR.test(m))throw new Error(`BUILD_REPOSITORY_ID is "${m}", not a GUID`);let f=[s(),r("SYSTEM_TEAMPROJECT"),r("SYSTEM_DEFINITIONID"),r("BUILD_BUILDID")].map(encodeURIComponent).join("/");return{provider:"azure-devops",repository:{provider:"azure-devops",providerAccountId:p,providerRepositoryId:m},providerRunId:f,providerRunAttempt:Number(d),workflowRef:`${Vlr}@${r("BUILD_SOURCEBRANCH")}`}},takeIdToken(){let d=t.SYSTEM_OIDCREQUESTURI;delete t.SYSTEM_OIDCREQUESTURI;let p=u(d);return()=>p()},takeSourceToken(){return delete t.SYSTEM_ACCESSTOKEN,c||void 0},webIdentity(){if(!t.SYSTEM_OIDCREQUESTURI?.trim()||!c)return;let d=u(t.SYSTEM_OIDCREQUESTURI);return{token:()=>d(),runId:t.BUILD_BUILDID}},v3RunsOnly:!0,assumesBedrockRole:!0,namesSourceToMcp:!0,checkSourceName(d){rj(d)},cloneUrl(d){return $st(n,rj(d))},gitAuthEnv(d){return nj(n,d)},async pullRequest(d,p,m){let f=await z_({token:await m.token(),url:`${H_(n,rj(d))}/pullrequests/${p}`,fetch:m.fetch}),h=f.status==="completed";return{...typeof f.title=="string"?{title:f.title}:{},...typeof f.description=="string"?{body:f.description}:{},...typeof f.status=="string"?{merged:h}:{},...h&&typeof f.lastMergeCommit?.commitId=="string"?{mergeCommit:f.lastMergeCommit.commitId}:{},...h&&typeof f.lastMergeSourceCommit?.commitId=="string"?{mergedHead:f.lastMergeSourceCommit.commitId}:{}}},async commitLookup(d,p,m){let f;try{f=H_(n,q_(d))}catch{return"unknown"}try{let h=await z_({token:await m.token(),url:`${f}/commits/${encodeURIComponent(p)}`,fetch:m.fetch});return typeof h.commitId=="string"&&h.commitId.toLowerCase()===p.toLowerCase()?"found":"missing"}catch(h){return h instanceof $_&&(h.status===404||h.status===400)?"missing":"unknown"}}}}Ke();var Ylr=5e3,Ife=/^(?!\.\.?$)[A-Za-z0-9._-]{1,100}$/;function Rfe(t){let e=Buffer.from(`x-access-token:${t}`).toString("base64");return Ot(e),`AUTHORIZATION: basic ${e}`}function zst(t,e={}){let r=c=>{let l=t[c];if(!l)throw new Error(`${c} is not set; the V3 runner handshake needs it`);return l},n=t.GITHUB_REPOSITORY_ID,s=t.GITHUB_REPOSITORY,i=(t.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,""),o=(t.GITHUB_API_URL||"https://api.github.com").replace(/\/+$/,""),a=async(c,l)=>l.fetch(c,{headers:{Authorization:`Bearer ${await l.token()}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(3e4)});return{runnerPlatform:t.GITHUB_ACTIONS==="true"?"github":void 0,workspace:t.GITHUB_WORKSPACE||void 0,serverUrl:i,apiUrl:o,repository:n&&s?{id:n,slug:s}:void 0,runId:t.GITHUB_RUN_ID||void 0,runAttempt:t.GITHUB_RUN_ATTEMPT||void 0,job:t.GITHUB_JOB||void 0,execution(){let c=r("GITHUB_RUN_ATTEMPT");if(!/^[1-9][0-9]*$/.test(c))throw new Error(`GITHUB_RUN_ATTEMPT is "${c}", not a positive whole number`);return{provider:"github",repository:{provider:"github",providerAccountId:r("GITHUB_REPOSITORY_OWNER_ID"),providerRepositoryId:r("GITHUB_REPOSITORY_ID")},providerRunId:r("GITHUB_RUN_ID"),providerRunAttempt:Number(c),workflowRef:r("GITHUB_WORKFLOW_REF")}},takeIdToken(){let c=t.ACTIONS_ID_TOKEN_REQUEST_URL,l=t.ACTIONS_ID_TOKEN_REQUEST_TOKEN;return delete t.ACTIONS_ID_TOKEN_REQUEST_URL,delete t.ACTIONS_ID_TOKEN_REQUEST_TOKEN,async u=>{if(!c||!l)throw new Error("The job cannot request an OIDC token. Give it the `id-token: write` permission.");let d=new URL(c);d.searchParams.set("audience",u);let p=await fetch(d,{headers:{Authorization:`Bearer ${l}`,Accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!p.ok)throw new Error(`GitHub refused the OIDC token request: ${p.status}`);let m=(await p.json().catch(()=>({}))).value;if(typeof m!="string"||!m)throw new Error("GitHub's OIDC token response carried no token");return Ot(m),m}},webIdentity(){return!t.ACTIONS_ID_TOKEN_REQUEST_TOKEN?.trim()||!t.ACTIONS_ID_TOKEN_REQUEST_URL?.trim()?void 0:{token:e.getIDToken??(l=>a0e(l)),runId:t.GITHUB_RUN_ID}},v3RunsOnly:!1,assumesBedrockRole:!1,namesSourceToMcp:!1,checkSourceName(c){for(let l of[c.namespace,c.name])if(!Ife.test(l))throw new Error(`"${l}" is not a repository name`)},cloneUrl(c){return`${i}/${c.namespace}/${c.name}.git`},gitAuthEnv(c){return c?{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${i}/.extraheader`,GIT_CONFIG_VALUE_0:Rfe(c)}:{}},async pullRequest({namespace:c,name:l},u,d){if(![c,l].every(f=>Ife.test(f)))throw new Error("the repository name is not valid");let p=await a(`${o}/repos/${c}/${l}/pulls/${u}`,d);if(!p.ok)throw new Error(`GitHub answered ${p.status}`);let m=await p.json();return{...typeof m.title=="string"?{title:m.title}:{},...typeof m.body=="string"?{body:m.body}:{},...typeof m.merged=="boolean"?{merged:m.merged}:{},...m.merged===!0&&typeof m.merge_commit_sha=="string"?{mergeCommit:m.merge_commit_sha}:{},...m.merged===!0&&typeof m.head?.sha=="string"?{mergedHead:m.head.sha}:{}}},async commitLookup(c,l,u){let[d,p,...m]=c.split("/");if(m.length||![d,p].every(f=>f!==void 0&&Ife.test(f)))return"unknown";try{let f=await a(`${o}/repos/${d}/${p}/commits/${encodeURIComponent(l)}`,u);if(f.status===404||f.status===422)return"missing";if(!f.ok)return"unknown";let h=await f.json();return typeof h.sha=="string"&&h.sha.toLowerCase()===l.toLowerCase()?"found":"missing"}catch{return"unknown"}},async revokeToken(c,l){let u=await l(`${o}/installation/token`,{method:"DELETE",headers:{Authorization:`Bearer ${c}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(Ylr)});if(!u.ok&&u.status!==401)throw new Error(`GitHub answered ${u.status}`)}}}function Zr(t=process.env){return $w(t)?Hst(t):zst(t)}function Gst(t,e=Zr()){if(!(!e.v3RunsOnly||t==="staged"))return`This CI job runs only the Validation Runs and SUT setups the Skyramp app starts: the Testbot step must set the pipeline input to "staged", not "${t||"classic"}".`}Ke();var qw=$(require("fs"));Ke();var sj=$(require("fs")),ty=$(require("path"));function G_(t){return t.match(/\.skyramp\/videos\/([^/]+)\//)?.[1]}function vfe(t){if(!sj.existsSync(t))return[];let e=[],r=n=>{let s;try{s=sj.readdirSync(n,{withFileTypes:!0})}catch(i){Z(`Skipping unreadable video dir ${n}: ${i instanceof Error?i.message:String(i)}`);return}for(let i of s){let o=ty.join(n,i.name);i.isDirectory()?r(o):i.isFile()&&i.name.endsWith(".webm")&&e.push(o)}};return r(t),e}async function jst(t,e,r){let n={};if(r.size===0)return n;let s=ty.resolve(t),i=()=>[...r].flatMap(c=>{let l=ty.resolve(t,c);return l!==s&&!l.startsWith(s+ty.sep)?(Z(`Skipping video subdir outside the videos tree: ${c}`),[]):vfe(ty.join(t,c))}),o=i();if(o.length===0&&(Z(`Expected ${r.size} test video(s) but found none under ${t}; retrying collection once`),await kA(3),o=i()),o.length===0)return n;let a=new Map;for(let c of o){let l=G_(c);if(!l)continue;let u=a.get(l);u?u.push(c):a.set(l,[c])}for(let[c,l]of a)try{let u=await Tfe(`skyramp-video-${c}`,l,t);u&&(n[c]=e.getArtifactUrl(u))}catch(u){Z(`Failed to upload video artifact for ${c} after retry: ${u instanceof Error?u.message:String(u)}`)}return Te(`Uploaded ${Object.keys(n).length} of ${a.size} test execution video artifact(s)`),n}async function Tfe(t,e,r,n){let{DefaultArtifactClient:s}=await Promise.resolve().then(()=>(hP(),Pq)),i=new s,{id:o}=await pi(()=>i.uploadArtifact(t,e,r,n),{retries:2,delay:3,label:`Video artifact upload for ${t}`});return o}function Jlr(t){return qw.existsSync(t.summaryPath)?t.summaryPath:qw.existsSync(t.agentStdoutPath)?(ee("Using agent stdout as fallback (agent did not write to summary file)"),t.agentStdoutPath):null}var Nfe=t=>t.replace(/\s*[\r\n]+\s*/g," ").trim(),kfe=t=>typeof t=="number"&&Number.isInteger(t)&&t>=0?t:void 0;function Klr(t){if(typeof t!="object"||t===null)return;let e=t,r=Object.values(Rp).includes(e.verification)?e.verification:void 0,n=(Array.isArray(e.skipped)?e.skipped:[]).map(o=>typeof o=="object"&&o!==null?o:{}).filter(o=>typeof o.pageObject=="string"&&o.pageObject.trim()!=="").map(o=>({pageObject:Nfe(o.pageObject),member:typeof o.member=="string"?Nfe(o.member):void 0,declinedBy:Object.values(fA).includes(o.declinedBy)?o.declinedBy:void 0,reason:typeof o.reason=="string"?Nfe(o.reason):""})),s={candidatesDetected:kfe(e.candidatesDetected),callsReused:kfe(e.callsReused),callsVerified:kfe(e.callsVerified),verification:r,skipped:n.length>0?n:void 0};return Object.values(s).some(o=>o!==void 0)?s:void 0}function Xlr(t){let e=typeof t=="object"&&t!==null?t:{},{reuse:r,...n}=e,s=Klr(r);return s?{...n,reuse:s}:n}function Zlr(t){try{let e=t.replace(/^```(?:json)?\s*\n?/m,"").replace(/\n?```\s*$/m,"").trim(),r=JSON.parse(e);if(typeof r.businessCaseAnalysis=="string"&&Array.isArray(r.testResults)){for(let n of["newTestsCreated","testMaintenance","issuesFound"])Array.isArray(r[n])||(r[n]=[]);return Array.isArray(r.nextSteps)||(r.nextSteps=[]),r.commitMessage!==void 0&&typeof r.commitMessage!="string"&&delete r.commitMessage,r.newTestsCreated=r.newTestsCreated.map(Xlr),r.testResults=r.testResults.map(n=>{let s=typeof n=="object"&&n!==null?n:{},i={...s,testType:typeof s.testType=="string"?s.testType:"",endpoint:typeof s.endpoint=="string"?s.endpoint:"",status:typeof s.status=="string"?s.status:"",details:typeof s.details=="string"?s.details:""};for(let o of["repository","videoPath"])i[o]!==void 0&&typeof i[o]!="string"&&delete i[o];return i}),r}return null}catch{return null}}var Vst={high:0,medium:1,low:2},Wst={security_boundary:0,breaking_change:1,data_integrity:2,business_rule:3,workflow:4};function Yst(t,e,r,n){let s=r[n(t.testType)]??99,i=r[n(e.testType)]??99;if(s!==i)return s-i;let o=Vst[(t.priority??"").toLowerCase()]??99,a=Vst[(e.priority??"").toLowerCase()]??99;if(o!==a)return o-a;let c=Wst[t.category??""]??99,l=Wst[e.category??""]??99;if(c!==l)return c-l;let u=(t.steps??[]).some(p=>(p.expectedStatusCode??0)>=400)?0:1,d=(e.steps??[]).some(p=>(p.expectedStatusCode??0)>=400)?0:1;return u!==d?u-d:(t.scenarioName??"").localeCompare(e.scenarioName??"")}function eur(t){if(!t)return;let e=ne().reuse,{callsReused:r,callsVerified:n,candidatesDetected:s,verification:i}=t,o=[];r!==void 0&&n!==void 0?(o.push(r===n?e.reusedAndVerified(r):e.reusedThenVerified(r,n)),i===Rp.Passed&&r>n&&o.push(e.unresolved(r-n))):r!==void 0?o.push(e.reused(r)):n!==void 0&&o.push(e.verified(n)),s!==void 0&&o.push(e.candidates(s));let a=r!==void 0&&r===n;i===Rp.SkippedNoPom?o.push(e.noPomLayer):i===Rp.Passed&&!a?o.push(e.verificationPassed):i===Rp.Failed&&o.push(e.verificationFailed);let c=t.skipped??[];if(c.length>0){let l=d=>{let p=d.member||d.pageObject,f=[d.declinedBy?e.gate[d.declinedBy]:"",d.reason].filter(Boolean).join(" \u2014 ");return f?`${p} (${f})`:p},u=[...c].sort((d,p)=>+(p.declinedBy===fA.DemotedByVerify)-+(d.declinedBy===fA.DemotedByVerify));o.push(e.keptInline(u.map(l).join("; ")))}if(o.length!==0)return`${e.label}: ${o.join(" \xB7 ")}`}function Jst(t){return(t.testMaintenance??[]).filter(e=>e.action!==AI.Ignore&&e.action!==AI.Verify)}function Hw(t,e={}){let r=ne(),{collapsed:n=!1,userPrompt:s,autoCommit:i=!1,audience:o,primaryRepo:a}=e,c=[],l=Y=>Y&&Y.toLowerCase()!==a?.toLowerCase()?Y:void 0,u=Y=>{let te=l(Y);return te?` \`[${te}]\``:""},d=t.newTestsCreated.some(Y=>l(Y.repository))||t.testResults.some(Y=>l(Y.repository))||t.issuesFound.some(Y=>l(Y.repository))||!!t.additionalRecommendations?.some(Y=>l(Y.repository)),p=o!=="testbot-pr",m=o!=="comment",f=o!=="testbot-pr",h=o!=="testbot-pr",b=o==="testbot-pr";c.push("<!-- skyramp-testbot -->");let E=Jst(t),A=new Set([Ma.Lint,Ma.Type,Ma.Config]),w=Y=>Y.category!==void 0&&A.has(Y.category),C=t.issuesFound.filter(Y=>!w(Y)),R=t.issuesFound.filter(w),N={critical:0,high:1,medium:2,low:3},T=(Y,te)=>(N[Y.severity??""]??4)-(N[te.severity??""]??4),M=(Y,te)=>(Object.prototype.hasOwnProperty.call(Y,te)?Y[te]:void 0)??te,k=Y=>`- ${Y.severity?`**[${M(r.severityLabels,Y.severity).toUpperCase()}]** `:""}${Y.description}${u(Y.repository)}`;if(t.newTestsCreated.length===0&&t.testResults.length===0&&E.length===0&&t.issuesFound.length>0&&(!t.additionalRecommendations||t.additionalRecommendations.length===0)){c.push(r.minimalReportHeader),c.push("");for(let te of C)c.push(te.description);if(R.length>0){C.length>0&&c.push(""),c.push(`### ${r.configErrorsHeader}`);for(let te of[...R].sort(T))c.push(k(te))}let Y=t.caveats??[];if(Y.length>0){c.push(""),c.push(r.caveatsHeader),c.push("");for(let te of Y)c.push(`- ${te.text}`)}if(t.nextSteps?.length>0){c.push(""),c.push(r.nextStepsHeader),c.push("");for(let te of t.nextSteps)c.push(`- ${te}`)}return Pfe(c.join(`
|
|
322
|
+
`)[0]}`];case"endgroup":return["##[endgroup]"];default:return[]}}function Fw(t){return t.replace(/\/+$/,"")}function Sfe(t){let e=new URL(t),r=e.pathname.split("/").filter(Boolean);if(r.length)return decodeURIComponent(r[r.length-1]);if(e.hostname.endsWith(".visualstudio.com"))return e.hostname.split(".")[0];throw new Error(`SYSTEM_COLLECTIONURI "${t}" names no organization`)}var $lr=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,48}[A-Za-z0-9])?$/,qlr=/[\\/:*?"<>|;#${},+=[\]%\p{Cc}\p{Cf}]/u;function Ust(t){return t.length>0&&t.length<=64&&t===t.trim()&&!qlr.test(t)&&!/[^\S ]/u.test(t)&&!/^[._]/.test(t)&&!t.endsWith(".")}function rj(t){return q_(`${t.namespace}/${t.name}`)}function q_(t){let e=t.indexOf("/"),r=t.lastIndexOf("/"),n=t.slice(0,e),s=t.slice(e+1,r),i=t.slice(r+1);if(e<0||e===r||!$lr.test(n)||!Ust(s)||!Ust(i))throw new Error(`"${t}" is not an Azure DevOps organization/project/repository`);return{organization:n,project:s,name:i}}function Fst(t,e){let r=Sfe(t);if(r.toLowerCase()!==e.organization.toLowerCase())throw new Error(`${e.organization}/${e.project}/${e.name} is not in ${r}, the Azure DevOps organization this job runs in`)}function $st(t,e){return Fst(t,e),`${Fw(t)}/${encodeURIComponent(e.project)}/_git/${encodeURIComponent(e.name)}`}function H_(t,e){return Fst(t,e),`${Fw(t)}/${encodeURIComponent(e.project)}/_apis/git/repositories/${encodeURIComponent(e.name)}`}var Hlr="7.1",$_=class extends Error{constructor(r,n){super(r);this.status=n}status};async function z_(t){let e=t.accept??"application/json",r=new URL(t.url);r.searchParams.has("api-version")||r.searchParams.set("api-version",Hlr);let n=await(t.fetch??fetch)(r.toString(),{method:t.method??"GET",headers:{Authorization:`Bearer ${t.token}`,Accept:e,...t.body!==void 0?{"Content-Type":"application/json"}:{}},...t.body!==void 0?{body:JSON.stringify(t.body)}:{},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!n.ok){let s=(await n.json().catch(()=>({}))).message;throw new $_(`Azure DevOps answered ${n.status}${typeof s=="string"?`: ${s}`:""}`,n.status)}return e!=="application/json"?Buffer.from(await n.arrayBuffer()):n.status===204?{}:await n.json()}function zlr(t){return`AUTHORIZATION: bearer ${t}`}function nj(t,e){return{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${Fw(t)}/.extraheader`,GIT_CONFIG_VALUE_0:zlr(e)}}var jlr="7.1-preview.1",Vlr=".azure-pipelines/skyramp-testbot-v3.yml";function $w(t){return t.GITHUB_ACTIONS!=="true"&&/^true$/i.test(t.TF_BUILD??"")}var Wlr={INPUT_PIPELINE:"SKYRAMP_TESTBOT_PIPELINE",INPUT_SKYRAMPRUNID:"SKYRAMP_RUN_ID",INPUT_SKYRAMPAPPORIGIN:"SKYRAMP_APP_ORIGIN",INPUT_SKYRAMPMCPVERSION:"SKYRAMP_MCP_VERSION",INPUT_SKYRAMPMCPSOURCE:"SKYRAMP_MCP_SOURCE",INPUT_SKYRAMPMCPGITHUBREF:"SKYRAMP_MCP_GITHUB_REF",INPUT_SKYRAMPMCPGITHUBTOKEN:"SKYRAMP_MCP_GITHUB_TOKEN",INPUT_USEBEDROCK:"SKYRAMP_USE_BEDROCK",INPUT_AWSREGION:"SKYRAMP_AWS_REGION",INPUT_AWSROLEARN:"SKYRAMP_AWS_ROLE_ARN"};function qst(t=process.env){if($w(t))for(let[e,r]of Object.entries(Wlr))!t[e]&&t[r]!==void 0&&(t[e]=t[r])}function Hst(t,e={}){let r=d=>{let p=t[d];if(!p)throw new Error(`${d} is not set; the V3 runner handshake needs it`);return p},n=Fw(t.SYSTEM_COLLECTIONURI??""),s=()=>Sfe(r("SYSTEM_COLLECTIONURI")),i=t.SYSTEM_TEAMPROJECT,o=t.BUILD_REPOSITORY_NAME,a=t.BUILD_REPOSITORY_ID?.toLowerCase(),c=t.SYSTEM_ACCESSTOKEN,l=e.mask??(d=>Qst(d)),u=d=>async()=>{if(!d)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_OIDCREQUESTURI to $(System.OidcRequestUri).");if(!c)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_ACCESSTOKEN to $(System.AccessToken).");let p=new URL(d);if(p.protocol!=="https:")throw new Error("SYSTEM_OIDCREQUESTURI is not an https URL");p.searchParams.set("api-version",jlr);let m=await(e.fetch??fetch)(p.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json",Accept:"application/json"},body:"{}",redirect:"error",signal:AbortSignal.timeout(3e4)});if(!m.ok)throw new Error(`Azure DevOps refused the OIDC token request: ${m.status}`);let f=(await m.json().catch(()=>({}))).oidcToken;if(typeof f!="string"||!f)throw new Error("Azure DevOps's OIDC token response carried no token");return l(f),f};return{runnerPlatform:$w(t)?"azure":void 0,workspace:t.BUILD_SOURCESDIRECTORY||void 0,serverUrl:n,apiUrl:n,repository:a&&i&&o&&n?{id:a,slug:`${s()}/${i}/${o}`}:void 0,runId:t.BUILD_BUILDID||void 0,runAttempt:t.SYSTEM_STAGEATTEMPT||void 0,job:t.SYSTEM_JOBNAME||void 0,execution(){let d=r("SYSTEM_STAGEATTEMPT");if(!/^[1-9][0-9]*$/.test(d))throw new Error(`SYSTEM_STAGEATTEMPT is "${d}", not a positive whole number`);let p=r("SYSTEM_COLLECTIONID").toLowerCase();if(!qR.test(p))throw new Error(`SYSTEM_COLLECTIONID is "${p}", not a GUID`);let m=r("BUILD_REPOSITORY_ID").toLowerCase();if(!qR.test(m))throw new Error(`BUILD_REPOSITORY_ID is "${m}", not a GUID`);let f=[s(),r("SYSTEM_TEAMPROJECT"),r("SYSTEM_DEFINITIONID"),r("BUILD_BUILDID")].map(encodeURIComponent).join("/");return{provider:"azure-devops",repository:{provider:"azure-devops",providerAccountId:p,providerRepositoryId:m},providerRunId:f,providerRunAttempt:Number(d),workflowRef:`${Vlr}@${r("BUILD_SOURCEBRANCH")}`}},takeIdToken(){let d=t.SYSTEM_OIDCREQUESTURI;delete t.SYSTEM_OIDCREQUESTURI;let p=u(d);return()=>p()},takeSourceToken(){return delete t.SYSTEM_ACCESSTOKEN,c||void 0},webIdentity(){if(!t.SYSTEM_OIDCREQUESTURI?.trim()||!c)return;let d=u(t.SYSTEM_OIDCREQUESTURI);return{token:()=>d(),runId:t.BUILD_BUILDID}},v3RunsOnly:!0,assumesBedrockRole:!0,namesSourceToMcp:!0,checkSourceName(d){rj(d)},cloneUrl(d){return $st(n,rj(d))},gitAuthEnv(d){return nj(n,d)},async pullRequest(d,p,m){let f=await z_({token:await m.token(),url:`${H_(n,rj(d))}/pullrequests/${p}`,fetch:m.fetch}),h=f.status==="completed";return{...typeof f.title=="string"?{title:f.title}:{},...typeof f.description=="string"?{body:f.description}:{},...typeof f.status=="string"?{merged:h}:{},...h&&typeof f.lastMergeCommit?.commitId=="string"?{mergeCommit:f.lastMergeCommit.commitId}:{},...h&&typeof f.lastMergeSourceCommit?.commitId=="string"?{mergedHead:f.lastMergeSourceCommit.commitId}:{}}},async commitLookup(d,p,m){let f;try{f=H_(n,q_(d))}catch{return"unknown"}try{let h=await z_({token:await m.token(),url:`${f}/commits/${encodeURIComponent(p)}`,fetch:m.fetch});return typeof h.commitId=="string"&&h.commitId.toLowerCase()===p.toLowerCase()?"found":"missing"}catch(h){return h instanceof $_&&(h.status===404||h.status===400)?"missing":"unknown"}}}}Ke();var Ylr=5e3,Ife=/^(?!\.\.?$)[A-Za-z0-9._-]{1,100}$/;function Rfe(t){let e=Buffer.from(`x-access-token:${t}`).toString("base64");return Ot(e),`AUTHORIZATION: basic ${e}`}function zst(t,e={}){let r=c=>{let l=t[c];if(!l)throw new Error(`${c} is not set; the V3 runner handshake needs it`);return l},n=t.GITHUB_REPOSITORY_ID,s=t.GITHUB_REPOSITORY,i=(t.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,""),o=(t.GITHUB_API_URL||"https://api.github.com").replace(/\/+$/,""),a=async(c,l)=>l.fetch(c,{headers:{Authorization:`Bearer ${await l.token()}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(3e4)});return{runnerPlatform:t.GITHUB_ACTIONS==="true"?"github":void 0,workspace:t.GITHUB_WORKSPACE||void 0,serverUrl:i,apiUrl:o,repository:n&&s?{id:n,slug:s}:void 0,runId:t.GITHUB_RUN_ID||void 0,runAttempt:t.GITHUB_RUN_ATTEMPT||void 0,job:t.GITHUB_JOB||void 0,execution(){let c=r("GITHUB_RUN_ATTEMPT");if(!/^[1-9][0-9]*$/.test(c))throw new Error(`GITHUB_RUN_ATTEMPT is "${c}", not a positive whole number`);return{provider:"github",repository:{provider:"github",providerAccountId:r("GITHUB_REPOSITORY_OWNER_ID"),providerRepositoryId:r("GITHUB_REPOSITORY_ID")},providerRunId:r("GITHUB_RUN_ID"),providerRunAttempt:Number(c),workflowRef:r("GITHUB_WORKFLOW_REF")}},takeIdToken(){let c=t.ACTIONS_ID_TOKEN_REQUEST_URL,l=t.ACTIONS_ID_TOKEN_REQUEST_TOKEN;return delete t.ACTIONS_ID_TOKEN_REQUEST_URL,delete t.ACTIONS_ID_TOKEN_REQUEST_TOKEN,async u=>{if(!c||!l)throw new Error("The job cannot request an OIDC token. Give it the `id-token: write` permission.");let d=new URL(c);d.searchParams.set("audience",u);let p=await fetch(d,{headers:{Authorization:`Bearer ${l}`,Accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!p.ok)throw new Error(`GitHub refused the OIDC token request: ${p.status}`);let m=(await p.json().catch(()=>({}))).value;if(typeof m!="string"||!m)throw new Error("GitHub's OIDC token response carried no token");return Ot(m),m}},webIdentity(){return!t.ACTIONS_ID_TOKEN_REQUEST_TOKEN?.trim()||!t.ACTIONS_ID_TOKEN_REQUEST_URL?.trim()?void 0:{token:e.getIDToken??(l=>a0e(l)),runId:t.GITHUB_RUN_ID}},v3RunsOnly:!1,assumesBedrockRole:!1,namesSourceToMcp:!1,checkSourceName(c){for(let l of[c.namespace,c.name])if(!Ife.test(l))throw new Error(`"${l}" is not a repository name`)},cloneUrl(c){return`${i}/${c.namespace}/${c.name}.git`},gitAuthEnv(c){return c?{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${i}/.extraheader`,GIT_CONFIG_VALUE_0:Rfe(c)}:{}},async pullRequest({namespace:c,name:l},u,d){if(![c,l].every(f=>Ife.test(f)))throw new Error("the repository name is not valid");let p=await a(`${o}/repos/${c}/${l}/pulls/${u}`,d);if(!p.ok)throw new Error(`GitHub answered ${p.status}`);let m=await p.json();return{...typeof m.title=="string"?{title:m.title}:{},...typeof m.body=="string"?{body:m.body}:{},...typeof m.merged=="boolean"?{merged:m.merged}:{},...m.merged===!0&&typeof m.merge_commit_sha=="string"?{mergeCommit:m.merge_commit_sha}:{},...m.merged===!0&&typeof m.head?.sha=="string"?{mergedHead:m.head.sha}:{}}},async commitLookup(c,l,u){let[d,p,...m]=c.split("/");if(m.length||![d,p].every(f=>f!==void 0&&Ife.test(f)))return"unknown";try{let f=await a(`${o}/repos/${d}/${p}/commits/${encodeURIComponent(l)}`,u);if(f.status===404||f.status===422)return"missing";if(!f.ok)return"unknown";let h=await f.json();return typeof h.sha=="string"&&h.sha.toLowerCase()===l.toLowerCase()?"found":"missing"}catch{return"unknown"}},async revokeToken(c,l){let u=await l(`${o}/installation/token`,{method:"DELETE",headers:{Authorization:`Bearer ${c}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(Ylr)});if(!u.ok&&u.status!==401)throw new Error(`GitHub answered ${u.status}`)}}}function Zr(t=process.env){return $w(t)?Hst(t):zst(t)}function Gst(t,e=Zr()){if(!(!e.v3RunsOnly||t==="staged"))return`This CI job runs only the Validation Runs and SUT setups the Skyramp app starts: the Testbot step must set the pipeline input to "staged", not "${t||"classic"}".`}Ke();var qw=$(require("fs"));Ke();var sj=$(require("fs")),ty=$(require("path"));function G_(t){return t.match(/\.skyramp\/videos\/([^/]+)\//)?.[1]}function vfe(t){if(!sj.existsSync(t))return[];let e=[],r=n=>{let s;try{s=sj.readdirSync(n,{withFileTypes:!0})}catch(i){Z(`Skipping unreadable video dir ${n}: ${i instanceof Error?i.message:String(i)}`);return}for(let i of s){let o=ty.join(n,i.name);i.isDirectory()?r(o):i.isFile()&&i.name.endsWith(".webm")&&e.push(o)}};return r(t),e}async function jst(t,e,r){let n={};if(r.size===0)return n;let s=ty.resolve(t),i=()=>[...r].flatMap(c=>{let l=ty.resolve(t,c);return l!==s&&!l.startsWith(s+ty.sep)?(Z(`Skipping video subdir outside the videos tree: ${c}`),[]):vfe(ty.join(t,c))}),o=i();if(o.length===0&&(Z(`Expected ${r.size} test video(s) but found none under ${t}; retrying collection once`),await kA(3),o=i()),o.length===0)return n;let a=new Map;for(let c of o){let l=G_(c);if(!l)continue;let u=a.get(l);u?u.push(c):a.set(l,[c])}for(let[c,l]of a)try{let u=await Tfe(`skyramp-video-${c}`,l,t);u&&(n[c]=e.getArtifactUrl(u))}catch(u){Z(`Failed to upload video artifact for ${c} after retry: ${u instanceof Error?u.message:String(u)}`)}return Te(`Uploaded ${Object.keys(n).length} of ${a.size} test execution video artifact(s)`),n}async function Tfe(t,e,r,n){let{DefaultArtifactClient:s}=await Promise.resolve().then(()=>(hP(),Pq)),i=new s,{id:o}=await pi(()=>i.uploadArtifact(t,e,r,n),{retries:2,delay:3,label:`Video artifact upload for ${t}`});return o}function Jlr(t){return qw.existsSync(t.summaryPath)?t.summaryPath:qw.existsSync(t.agentStdoutPath)?(ee("Using agent stdout as fallback (agent did not write to summary file)"),t.agentStdoutPath):null}var Nfe=t=>t.replace(/\s*[\r\n]+\s*/g," ").trim(),kfe=t=>typeof t=="number"&&Number.isInteger(t)&&t>=0?t:void 0;function Klr(t){if(typeof t!="object"||t===null)return;let e=t,r=Object.values(Rp).includes(e.verification)?e.verification:void 0,n=(Array.isArray(e.skipped)?e.skipped:[]).map(o=>typeof o=="object"&&o!==null?o:{}).filter(o=>typeof o.pageObject=="string"&&o.pageObject.trim()!=="").map(o=>({pageObject:Nfe(o.pageObject),member:typeof o.member=="string"?Nfe(o.member):void 0,declinedBy:Object.values(fA).includes(o.declinedBy)?o.declinedBy:void 0,reason:typeof o.reason=="string"?Nfe(o.reason):""})),s={candidatesDetected:kfe(e.candidatesDetected),callsReused:kfe(e.callsReused),callsVerified:kfe(e.callsVerified),verification:r,skipped:n.length>0?n:void 0};return Object.values(s).some(o=>o!==void 0)?s:void 0}function Xlr(t){let e=typeof t=="object"&&t!==null?t:{},{reuse:r,...n}=e,s=Klr(r);return s?{...n,reuse:s}:n}function Zlr(t){try{let e=t.replace(/^```(?:json)?\s*\n?/m,"").replace(/\n?```\s*$/m,"").trim(),r=JSON.parse(e);if(typeof r.businessCaseAnalysis=="string"&&Array.isArray(r.testResults)){for(let n of["newTestsCreated","testMaintenance","issuesFound"])Array.isArray(r[n])||(r[n]=[]);return Array.isArray(r.nextSteps)||(r.nextSteps=[]),r.commitMessage!==void 0&&typeof r.commitMessage!="string"&&delete r.commitMessage,r.newTestsCreated=r.newTestsCreated.map(Xlr),r.testResults=r.testResults.map(n=>{let s=typeof n=="object"&&n!==null?n:{},i={...s,testType:typeof s.testType=="string"?s.testType:"",endpoint:typeof s.endpoint=="string"?s.endpoint:"",status:typeof s.status=="string"?s.status:"",details:typeof s.details=="string"?s.details:""};for(let o of["repository","videoPath"])i[o]!==void 0&&typeof i[o]!="string"&&delete i[o];return i}),r}return null}catch{return null}}var Vst={high:0,medium:1,low:2},Wst={security_boundary:0,breaking_change:1,data_integrity:2,business_rule:3,workflow:4};function Yst(t,e,r,n){let s=r[n(t.testType)]??99,i=r[n(e.testType)]??99;if(s!==i)return s-i;let o=Vst[(t.priority??"").toLowerCase()]??99,a=Vst[(e.priority??"").toLowerCase()]??99;if(o!==a)return o-a;let c=Wst[t.category??""]??99,l=Wst[e.category??""]??99;if(c!==l)return c-l;let u=(t.steps??[]).some(p=>(p.expectedStatusCode??0)>=400)?0:1,d=(e.steps??[]).some(p=>(p.expectedStatusCode??0)>=400)?0:1;return u!==d?u-d:(t.scenarioName??"").localeCompare(e.scenarioName??"")}function eur(t){if(!t)return;let e=ne().reuse,{callsReused:r,callsVerified:n,candidatesDetected:s,verification:i}=t,o=[];r!==void 0&&n!==void 0?(o.push(r===n?e.reusedAndVerified(r):e.reusedThenVerified(r,n)),i===Rp.Passed&&r>n&&o.push(e.unresolved(r-n))):r!==void 0?o.push(e.reused(r)):n!==void 0&&o.push(e.verified(n)),s!==void 0&&o.push(e.candidates(s));let a=r!==void 0&&r===n;i===Rp.SkippedNoPom?o.push(e.noPomLayer):i===Rp.Passed&&!a?o.push(e.verificationPassed):i===Rp.Failed&&o.push(e.verificationFailed);let c=t.skipped??[];if(c.length>0){let l=d=>{let p=d.member||d.pageObject,f=[d.declinedBy?e.gate[d.declinedBy]:"",d.reason].filter(Boolean).join(" \u2014 ");return f?`${p} (${f})`:p},u=[...c].sort((d,p)=>+(p.declinedBy===fA.DemotedByVerify)-+(d.declinedBy===fA.DemotedByVerify));o.push(e.keptInline(u.map(l).join("; ")))}if(o.length!==0)return`${e.label}: ${o.join(" \xB7 ")}`}function Jst(t){return(t.testMaintenance??[]).filter(e=>e.action!==AI.Ignore&&e.action!==AI.Verify)}function Hw(t,e={}){let r=ne(),{collapsed:n=!1,userPrompt:s,autoCommit:i=!1,audience:o,primaryRepo:a}=e,c=[],l=Y=>Y&&Y.toLowerCase()!==a?.toLowerCase()?Y:void 0,u=Y=>{let te=l(Y);return te?` \`[${te}]\``:""},d=t.newTestsCreated.some(Y=>l(Y.repository))||t.testResults.some(Y=>l(Y.repository))||t.issuesFound.some(Y=>l(Y.repository))||!!t.additionalRecommendations?.some(Y=>l(Y.repository)),p=o!=="testbot-pr",m=o!=="comment",f=o!=="testbot-pr",h=o!=="testbot-pr",b=o==="testbot-pr";c.push("<!-- skyramp-testbot -->");let E=Jst(t),A=new Set([Ma.Lint,Ma.Type,Ma.Config]),w=Y=>Y.category!==void 0&&A.has(Y.category),C=t.issuesFound.filter(Y=>!w(Y)),R=t.issuesFound.filter(w),N={critical:0,high:1,medium:2,low:3},T=(Y,te)=>(N[Y.severity??""]??4)-(N[te.severity??""]??4),M=(Y,te)=>(Object.prototype.hasOwnProperty.call(Y,te)?Y[te]:void 0)??te,k=Y=>`- ${Y.severity?`**[${M(r.severityLabels,Y.severity).toUpperCase()}]** `:""}${Y.description}${u(Y.repository)}`;if(t.newTestsCreated.length===0&&t.testResults.length===0&&E.length===0&&t.issuesFound.length>0&&(!t.additionalRecommendations||t.additionalRecommendations.length===0)){c.push(r.minimalReportHeader),c.push("");for(let te of C)c.push(te.description);if(R.length>0){C.length>0&&c.push(""),c.push(`### ${r.configErrorsHeader}`);for(let te of[...R].sort(T))c.push(k(te))}let Y=t.caveats??[];if(Y.length>0){c.push(""),c.push(r.caveatsHeader),c.push("");for(let te of Y)c.push(`- ${te.text}`)}if(t.nextSteps?.length>0){c.push(""),c.push(r.nextStepsHeader),c.push("");for(let te of t.nextSteps)c.push(`- ${te}`)}return Pfe(c.join(`
|
|
323
323
|
`))}let U=Y=>Y.replace(/\|/g,"\\|").replace(/\n/g,"<br>");s&&(c.push(r.followingUserInstruction(s)),c.push(""));let J=Y=>{n?(c.push("<details>"),c.push(`<summary>${Y}</summary>`),c.push("")):c.push(`### ${Y}`)},H=()=>{n&&(c.push(""),c.push("</details>")),c.push("")};if(p){let Y=h?"> ":"";for(let te of t.businessCaseAnalysis.split(/\r?\n/))c.push(`${Y}${te}`);c.push("")}if(m&&t.newTestsCreated.length>0){let Y=r.testRecommendationsImplementedHeader(t.newTestsCreated.length);b?c.push(`### ${Y}`):J(Y);for(let te of t.newTestsCreated){let Ae=te.testId?`\`${te.testId}\``:te.testType,pe=te.endpoint?`
|
|
324
324
|
\`${te.endpoint}\``:"",ye=te.description?`
|
|
325
325
|
${te.description}`:"",Je=te.fileName?` (\`${te.fileName}\`)`:"";c.push(`- ${Ae}${Je}${u(te.repository)}${pe}${ye}`)}b?c.push(""):H()}if(m&&t.additionalRecommendations&&t.additionalRecommendations.length>0){let Y=t.additionalRecommendations,te=Y.length,Ae={contract:0,integration:1,e2e:2,ui:3},pe=at=>at.toLowerCase(),ye=[...Y].sort((at,qe)=>Yst(at,qe,Ae,pe)),Je=new Map;for(let at of ye){let qe=pe(at.testType);Je.has(qe)||Je.set(qe,[]),Je.get(qe).push(at)}J(r.additionalRecommendationsHeader(te)),c.push(r.additionalRecommendationsCta),c.push("");for(let[at,qe]of Je){let we=r.testTypeLabels[at]??at;c.push(`**${we}**`),c.push("");for(let Dt of qe){let Or=Dt.steps&&Dt.steps.length>0&&Dt.steps[0].method&&Dt.steps[0].path?`\`${Dt.steps[0].method} ${Dt.steps[0].path}\``:"",jt=`- ${Dt.testId?`\`${Dt.testId}\``:Dt.scenarioName?`\`${Dt.scenarioName}\``:`\`${Dt.testType} test\``}`,ge=Or?`
|
|
@@ -538,7 +538,7 @@ ${n}`:r).replace(/AUTHORIZATION: (basic|bearer) \S+/gi,"AUTHORIZATION: $1 ***").
|
|
|
538
538
|
`)[0].slice(0,200)}`),{closed:!1}}}hasPersistedGitCredential(e){try{return!!this.git(["config","--get-regexp","^http(\\..*)?\\.extraheader$"],void 0,e).trim()}catch{return!1}}push(e,r,n=!0){let s=`HEAD:refs/heads/${e.branch}`;this.remoteGit(["push",...n?["--force"]:[],e.remote,s],r,e.repositoryPath)}checkoutAuthHeader;adoptCheckoutAuthHeader(e){this.checkoutAuthHeader=e}remoteGit(e,r,n=this.opts.repositoryPath){let s=this.opts.tokenProvider?r:void 0,i=this.opts.githubToken,o=s??r??i,a=qv.resolve(n)===qv.resolve(this.opts.repositoryPath)?this.checkoutAuthHeader:void 0;if(!a&&!o||this.hasPersistedGitCredential(n))return this.git(e,void 0,n);let c=m=>{let f=Buffer.from(`x-access-token:${m}`).toString("base64");return Ot(f),`AUTHORIZATION: basic ${f}`},l=a!==void 0&&i!==void 0&&a===c(i),u=s?c(s):a&&!l?a:c(o),d=(process.env.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,""),p=[[`http.${d}/.extraheader`,u]];if(process.env.GITHUB_ACTIONS==="true"){let m=new URL(d).hostname;p.push([`url.${d}/.insteadOf`,`git@${m}:`],[`url.${d}/.insteadOf`,`ssh://git@${m}/`])}return this.git(e,hgr(process.env,p),n)}pushFailure(e,r){let n=En(e);return{action:"failed",pushed:!1,base:r,url:"",failure:$v.test(n)?"auth":"push",detail:`push failed: ${n}`.slice(0,600)}}async publishTestsPr(e){let r=[];return{...await this.publish(e,r),pushedCommits:r}}async publish(e,r){this.warnIfTokenLikelyExpired();let n=e.repositoryPath,s=e.repoSlug??this.slug(),i=e.devPr===void 0?this.opts.prNumber:e.devPr,o=(f,h,b,E=e.base)=>({action:"failed",pushed:b,base:E,url:"",failure:f,detail:h.slice(0,600)}),a;try{a=await this.token()}catch(f){return o("auth",`could not mint a GitHub App token: ${En(f)}`,!1)}let c=!0;if(e.mode==="append"){let f=!1;try{f=!!this.remoteGit(["ls-remote","--heads",e.remote,e.branch],a,n).trim()}catch{c=!1}if(f){try{this.remoteGit(["fetch",e.remote,e.branch],a,n),this.git(["checkout","-B",e.branch,`${e.remote}/${e.branch}`],void 0,n),this.git(["cherry-pick","--keep-redundant-commits",e.commitSha],void 0,n)}catch(b){return ZD(this.run,e),o("conflict",`append onto the existing tests branch failed (tests kept on the local branch): ${En(b)}`,!1)}let h=!1;try{this.git(["diff","--quiet",`${e.remote}/${e.branch}`,"HEAD"],void 0,n),h=!0}catch{h=!1}if(h)return this.markTestsPrUnchanged({branch:e.branch,repositoryPath:n,repoSlug:e.repoSlug,devPr:e.devPr});c=!1}}try{this.push(e,a,c)}catch(f){return this.pushFailure(f,e.base)}NV(this.run,n,r);let l=f=>this.ghPr(["pr","create","--head",e.branch,"--base",f,"--title",e.title,"--body-file",e.bodyFile],a,s),u=f=>{this.ghPr(["pr","edit",e.branch,"--base",f,"--title",e.title,"--body-file",e.bodyFile],a,s);let h=this.ghPr(["pr","view",e.branch,"--json","url","-q",".url"],a,s);return{action:"updated",pushed:!0,base:f,url:h}},d=(f,h)=>{if(lgr.test(f))try{return u(h)}catch(b){return o("unknown",`tests PR exists but could not be updated: ${En(b)}`,!0,h)}if(ugr.test(f))return{action:"skipped",pushed:!0,base:h,url:"",detail:`no commits between ${h} and ${e.branch} \u2014 the tests are already on the base`};if($v.test(f))return o("auth",f,!0,h)},p;try{return{action:"created",pushed:!0,base:e.base,url:l(e.base)}}catch(f){p=En(f)}let m=d(p,e.base);if(m)return m;if(dgr.test(p)){if(e.mode==="append")return o("unknown",`the dev branch '${e.base}' no longer exists (dev PR merged) and append mode cannot re-cut the tests branch \u2014 re-run in replace mode`,!0);if(i==null)return o("unknown",`the base branch '${e.base}' no longer exists and no dev PR number is known to retarget from`,!0);let f={};try{f=JSON.parse(this.ghPr(["pr","view",String(i),"--json","state,baseRefName"],a,s))}catch{}if(f.state!=="MERGED"||!f.baseRefName)return{action:"skipped",pushed:!0,base:e.base,url:"",detail:`the dev branch '${e.base}' no longer exists and PR #${i} is ${f.state??"unknown"} (not merged) \u2014 nothing to target; tests are on branch ${e.branch}`};let h=f.baseRefName;this.log(`[deliver] tests PR base '${e.base}' no longer exists (dev PR merged) \u2014 re-cutting onto '${h}'`);try{this.remoteGit(["fetch",e.remote,h],a,n),this.git(["checkout","-B",e.branch,`${e.remote}/${h}`],void 0,n),this.git(["cherry-pick","--keep-redundant-commits",e.commitSha],void 0,n)}catch(b){return ZD(this.run,e),o("conflict",`re-cut onto '${h}' failed (tests kept on the local branch): ${En(b)}`,!0)}try{this.push(e,a)}catch(b){return this.pushFailure(b,h)}NV(this.run,n,r);try{return{action:"retargeted",retargetedAs:"created",pushed:!0,base:h,url:l(h)}}catch(b){let E=En(b),A=d(E,h);return A?A.action==="updated"?{...A,action:"retargeted",retargetedAs:"updated"}:A:o("unknown",`re-cut onto '${h}' pushed, but PR create failed: ${E}`,!0,h)}}return o("unknown",p,!0)}};var Wc=$(require("fs")),_ge=$(require("os")),Gi=$(require("path"));var _V=4e3,hut=18e4,ggr=5e3;function DV(t){return En(t).split(`
|
|
539
539
|
`)[0].slice(0,200)}function Dge(t=process.env){let e=Fw(t.SYSTEM_COLLECTIONURI??""),r=t.SYSTEM_TEAMPROJECT,n=t.BUILD_BUILDID;return e&&r&&n?{server:e,project:r,buildId:n}:void 0}var rO=class{constructor(e){this.opts=e;this.log=e.log??(i=>console.log(i)),this.run=e.run??Pge,this.command=e.command??F_;let{server:r,project:n,buildId:s}=e.pipelineRun;this.runUrl=`${r}/${encodeURIComponent(n)}/_build/results?buildId=${encodeURIComponent(s)}`}opts;name="azure";supportsRemote=!0;runUrl;log;run;command;repository(e=this.opts.repoSlug){return q_(e)}api(e){return H_(this.opts.pipelineRun.server,this.repository(e))}async rest(e,r,n,s){return z_({token:await this.opts.tokenProvider(),url:r,method:e,body:n,accept:s,fetch:this.opts.fetch})}prUrl(e,r){let n=this.repository(e);return`${this.opts.pipelineRun.server}/${encodeURIComponent(n.project)}/_git/${encodeURIComponent(n.name)}/pullrequest/${r}`}async activePr(e,r){let n=new URL(`${this.api(e)}/pullrequests`);return n.searchParams.set("searchCriteria.sourceRefName",`refs/heads/${r}`),n.searchParams.set("searchCriteria.status","active"),(await this.rest("GET",n.toString())).value?.find(i=>typeof i.pullRequestId=="number")}git(e,r,n=this.opts.repositoryPath){return this.run("git",e,{cwd:n,env:r})}async remoteGit(e,r){let n=await this.opts.tokenProvider();return this.git(e,{...process.env,GIT_TERMINAL_PROMPT:"0",...nj(this.opts.pipelineRun.server,n)},r)}adoptCheckoutAuthHeader(e){}async admitRun(){return{admit:!0}}async resolveContext(){let e;try{let r=this.git(["rev-parse","--abbrev-ref","HEAD"]);r&&r!=="HEAD"&&(e=r)}catch{}return{repoSlug:this.opts.repoSlug,headBranch:e}}createProgressSink(){return XD(this.log)}async beginRun(){}watchRun(e){let r=!1,n=this.opts.watchSignals===!1?[]:["SIGTERM","SIGINT"],s=i=>{for(let o of n)process.removeListener(o,s);r||(r=!0,e("cancelled",`received ${i} (pipeline run cancelled or agent shutting down)`))};for(let i of n)process.on(i,s);return{stop:()=>{for(let i of n)process.removeListener(i,s)}}}stageArtifact(e,r,n){if(!/^[A-Za-z0-9._-]{1,200}$/.test(e))throw new Error(`"${e}" is not an artifact name`);let s=this.opts.stagingDir??Gi.join(process.env.AGENT_TEMPDIRECTORY||_ge.tmpdir(),"skyramp-artifacts"),i=Gi.join(s,e);Wc.rmSync(i,{recursive:!0,force:!0});for(let o of r){let a=Gi.relative(n,o);if(!a||a.startsWith("..")||Gi.isAbsolute(a))throw new Error(`${o} is not under ${n}`);Wc.mkdirSync(Gi.dirname(Gi.join(i,a)),{recursive:!0}),Wc.copyFileSync(o,Gi.join(i,a))}return this.command(zR("artifact.upload",{containerfolder:e,artifactname:e},i)),i}async uploadArtifact(e,r,n){if(r.length)try{return this.stageArtifact(e,r,n),`${this.runUrl}&view=artifacts&pathAsName=false&type=publishedArtifacts`}catch(s){this.log(`[warn] could not upload artifact ${e}: ${En(s)}`);return}}async uploadRunFiles(e,r,n){return await this.uploadArtifact(e,r,n)!==void 0}async artifactStore(){let{server:e,project:r,buildId:n}=this.opts.pipelineRun,s=(i,o)=>`${e}/${encodeURIComponent(i)}/_apis/build/builds/${encodeURIComponent(o)}/artifacts`;return{uploadArtifact:async(i,o,a)=>{this.stageArtifact(i,o,a);let c=new URL(s(r,n));c.searchParams.set("artifactName",i);let l=Date.now()+(this.opts.artifactWaitMs??hut);for(;;){let u=await this.rest("GET",c.toString()).catch(()=>{});if(typeof u?.id=="number")return{id:u.id};if(Date.now()>=l)throw new Error(`Azure DevOps listed no artifact ${i} within ${Math.round((this.opts.artifactWaitMs??hut)/1e3)} s`);await new Promise(d=>setTimeout(d,this.opts.artifactPollMs??ggr))}},downloadArtifact:async(i,o)=>{let a=o?.path??Wc.mkdtempSync(Gi.join(_ge.tmpdir(),"skyramp-artifact-")),c=o?.findBy?.repositoryOwner,l=c?.includes("/")?c.slice(c.indexOf("/")+1):r,u=String(o?.findBy?.workflowRunId??n),p=(await this.rest("GET",s(l,u))).value?.find(A=>A.id===i),m=/^#\/(\d+)\/(.+)$/.exec(p?.resource?.data??"");if(!p||p.resource?.type?.toLowerCase()!=="container"||!m)throw new Error(`build ${u} has no artifact ${i} the engine can read`);let[,f,h]=m,b=new URL(`${e}/_apis/resources/Containers/${f}`);b.searchParams.set("itemPath",h),b.searchParams.set("api-version","7.1-preview.4");let E=await this.rest("GET",b.toString());for(let A of E.value??[]){if(A.itemType!=="file"||!A.path?.startsWith(`${h}/`))continue;let w=A.path.slice(h.length+1),C=Gi.resolve(a,w);if(!C.startsWith(Gi.resolve(a)+Gi.sep))throw new Error(`the artifact names a path outside its place: ${A.path}`);let R=new URL(b.toString());R.searchParams.set("itemPath",A.path);let N=await this.rest("GET",R.toString(),void 0,"application/octet-stream");Wc.mkdirSync(Gi.dirname(C),{recursive:!0}),Wc.writeFileSync(C,N)}return{downloadPath:a}}}}async publishTestsPr(e){let r=[];return{...await this.publish(e,r),pushedCommits:r}}description(e){let r=Wc.readFileSync(e,"utf-8");if(r.length<=_V)return r;let n=`
|
|
540
540
|
|
|
541
|
-
\u2026 (cut to Azure DevOps's 4000-character limit)`;return r.slice(0,_V-n.length)+n}async publish(e,r){let n=e.repositoryPath,s=e.repoSlug??this.opts.repoSlug,i=(u,d,p,m=e.base)=>({action:"failed",pushed:p,base:m,url:"",failure:u,detail:d.slice(0,600)});try{this.api(s)}catch(u){return i("unknown",En(u),!1)}let o=!0;if(e.mode==="append"){let u=!1;try{u=!!(await this.remoteGit(["ls-remote","--heads",e.remote,e.branch],n)).trim()}catch{o=!1}if(u){try{await this.remoteGit(["fetch",e.remote,e.branch],n),this.git(["checkout","-B",e.branch,`${e.remote}/${e.branch}`],void 0,n),this.git(["cherry-pick","--keep-redundant-commits",e.commitSha],void 0,n)}catch(p){return ZD(this.run,e),i("conflict",`append onto the existing tests branch failed (tests kept on the local branch): ${En(p)}`,!1)}let d=!1;try{this.git(["diff","--quiet",`${e.remote}/${e.branch}`,"HEAD"],void 0,n),d=!0}catch{d=!1}if(d)return this.markTestsPrUnchanged({branch:e.branch,repositoryPath:n,repoSlug:e.repoSlug,devPr:e.devPr});o=!1}}let a=async()=>{await this.remoteGit(["push",...o?["--force"]:[],e.remote,`HEAD:refs/heads/${e.branch}`],n),NV(this.run,n,r)};try{await a()}catch(u){let d=En(u);return i($v.test(d)?"auth":"push",`push failed: ${d}`,!1)}let c=this.description(e.bodyFile),l=async u=>{let d=await this.activePr(s,e.branch);if(d?.pullRequestId!==void 0){let m=d.pullRequestId;return await this.rest("PATCH",`${this.api(s)}/pullrequests/${m}`,{title:e.title,description:c}),d.targetRefName&&d.targetRefName!==`refs/heads/${u}`&&await this.rest("PATCH",`${this.api(s)}/pullrequests/${m}`,{targetRefName:`refs/heads/${u}`}).catch(f=>this.log(`[warn] could not move tests PR ${m} to ${u}: ${En(f)}`)),{action:"updated",pushed:!0,base:u,url:this.prUrl(s,m)}}let p=await this.rest("POST",`${this.api(s)}/pullrequests`,{sourceRefName:`refs/heads/${e.branch}`,targetRefName:`refs/heads/${u}`,title:e.title,description:c});if(typeof p.pullRequestId!="number")throw new Error("Azure DevOps created no pull request");return{action:"created",pushed:!0,base:u,url:this.prUrl(s,p.pullRequestId)}};try{return await l(e.base)}catch(u){let d=En(u);return $v.test(d)?i("auth",d,!0):await this.branchExists(s,e.base).catch(()=>!0)?i("unknown",d,!0):this.retarget(e,s,l,i,a)}}async branchExists(e,r){let n=new URL(`${this.api(e)}/refs`);return n.searchParams.set("filter",`heads/${r}`),((await this.rest("GET",n.toString())).value??[]).some(i=>i.name===`refs/heads/${r}`)}async retarget(e,r,n,s,i){let o=e.devPr;if(e.mode==="append")return s("unknown",`the dev branch '${e.base}' no longer exists and append mode cannot re-cut the tests branch \u2014 re-run in replace mode`,!0);if(o==null)return s("unknown",`the base branch '${e.base}' no longer exists and no dev PR number is known to retarget from`,!0);let a=await this.rest("GET",`${this.api(r)}/pullrequests/${o}`).catch(()=>{}),c=a?.targetRefName?.replace(/^refs\/heads\//,"");if(a?.status!=="completed"||!c)return{action:"skipped",pushed:!0,base:e.base,url:"",detail:`the dev branch '${e.base}' no longer exists and PR ${o} is ${a?.status??"unknown"} (not completed) \u2014 nothing to target; tests are on branch ${e.branch}`};this.log(`[deliver] tests PR base '${e.base}' no longer exists (dev PR completed) \u2014 re-cutting onto '${c}'`);try{await this.remoteGit(["fetch",e.remote,c],e.repositoryPath),this.git(["checkout","-B",e.branch,`${e.remote}/${c}`],void 0,e.repositoryPath),this.git(["cherry-pick","--keep-redundant-commits",e.commitSha],void 0,e.repositoryPath)}catch(l){return ZD(this.run,e),s("conflict",`re-cut onto '${c}' failed (tests kept on the local branch): ${En(l)}`,!0)}try{await i()}catch(l){return s("push",`push failed: ${En(l)}`,!1,c)}try{let l=await n(c);return{...l,action:"retargeted",retargetedAs:l.action==="updated"?"updated":"created"}}catch(l){return s("unknown",`re-cut onto '${c}' pushed, but PR create failed: ${En(l)}`,!0,c)}}async markTestsPrUnchanged(e){let r=e.repoSlug??this.opts.repoSlug,n=s=>({action:"skipped",pushed:!1,base:"",url:"",detail:s});try{let s=await this.activePr(r,e.branch);if(s?.pullRequestId===void 0)return n(`no open tests PR for ${e.branch} \u2014 nothing to annotate`);let i=e.devPr!=null?`PR ${e.devPr}`:"the dev branch",o=PV(i)+BV(s.description??""),a=o.length<=_V?o:o.slice(0,_V);return a.startsWith(tO)?(await this.rest("PATCH",`${this.api(r)}/pullrequests/${s.pullRequestId}`,{description:a}),{action:"unchanged",pushed:!1,base:(s.targetRefName??"").replace(/^refs\/heads\//,""),url:this.prUrl(r,s.pullRequestId),detail:"no new test changes this run \u2014 existing tests PR annotated"}):n("the tests PR description has no room for the banner")}catch(s){return n(`could not annotate the tests PR: ${DV(s)}`)}}async closeTestsPr(e){try{let r=await this.activePr(void 0,e.branch);if(r?.pullRequestId===void 0)return{closed:!1};let n=r.pullRequestId;return await this.rest("POST",`${this.api()}/pullRequests/${n}/threads`,{comments:[{parentCommentId:0,content:e.reason,commentType:1}],status:"closed"}),await this.rest("PATCH",`${this.api()}/pullrequests/${n}`,{status:"abandoned"}),{closed:!0,url:this.prUrl(void 0,n)}}catch(r){return this.log(`[warn] could not close the tests PR for ${e.branch}: ${DV(r)}`),{closed:!1}}}async endRun(){}async listCommitChecks(e){try{return((await this.rest("GET",`${this.api(e.repository)}/commits/${encodeURIComponent(e.revision)}/statuses`)).value??[]).filter(n=>n.context?.name).map(n=>({repository:e.repository,name:n.context?.genre?`${n.context.genre}/${n.context.name}`:n.context.name,headSha:e.revision,status:n.state==="pending"?"pending":"completed",conclusion:n.state==="pending"?null:n.state==="succeeded"?"success":n.state==="failed"?"failure":n.state==="notApplicable"?"neutral":n.state??null,url:n.targetUrl,summary:n.description}))}catch(r){this.log(`[warn] could not read CI results for ${e.repository}@${e.revision.slice(0,12)}: ${DV(r)}`);return}}async commitContains(e){try{let r=new URL(`${this.api(e.repository)}/diffs/commits`);for(let[s,i]of Object.entries({baseVersion:e.ancestor,baseVersionType:"commit",targetVersion:e.descendant,targetVersionType:"commit",$top:"1"}))r.searchParams.set(s,i);let n=await this.rest("GET",r.toString());return n.commonCommit?n.commonCommit.toLowerCase()===e.ancestor.toLowerCase()?"contained":"not_contained":"unknown"}catch(r){return this.log(`[warn] could not compare ${e.repository} ${ns(e.ancestor)}...${ns(e.descendant)}: ${DV(r)}`),"unknown"}}};var T0n=["local","github","azure"];function gut(t,e,r=Zr()){if(r.runnerPlatform!=="azure")return new eO(t);let n=Dge();if(!e||!n||!t.repoSlug||!t.tokenProvider)throw new Error("On Azure Pipelines, Testbot runs only the Validation Runs and SUT setups the Skyramp app starts: the step needs INPUT_SKYRAMPRUNID and the job's predefined variables.");return new rO({repositoryPath:t.repositoryPath,repoSlug:t.repoSlug,pipelineRun:n,tokenProvider:t.tokenProvider,log:t.log})}var but=require("child_process"),_h=$(require("fs")),Yc=$(require("path")),Eut=(t,e)=>(0,but.execFileSync)("git",["-c","safe.directory=*",...$i,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","pipe"],env:wt()}),wut="^(http(\\..*)?\\.extraheader|core\\.sshcommand)$",bgr="core.sshcommand",OV=t=>t instanceof Error?t.message.split(`
|
|
541
|
+
\u2026 (cut to Azure DevOps's 4000-character limit)`;return r.slice(0,_V-n.length)+n}async publish(e,r){let n=e.repositoryPath,s=e.repoSlug??this.opts.repoSlug,i=(u,d,p,m=e.base)=>({action:"failed",pushed:p,base:m,url:"",failure:u,detail:d.slice(0,600)});try{this.api(s)}catch(u){return i("unknown",En(u),!1)}let o=!0;if(e.mode==="append"){let u=!1;try{u=!!(await this.remoteGit(["ls-remote","--heads",e.remote,e.branch],n)).trim()}catch{o=!1}if(u){try{await this.remoteGit(["fetch",e.remote,e.branch],n),this.git(["checkout","-B",e.branch,`${e.remote}/${e.branch}`],void 0,n),this.git(["cherry-pick","--keep-redundant-commits",e.commitSha],void 0,n)}catch(p){return ZD(this.run,e),i("conflict",`append onto the existing tests branch failed (tests kept on the local branch): ${En(p)}`,!1)}let d=!1;try{this.git(["diff","--quiet",`${e.remote}/${e.branch}`,"HEAD"],void 0,n),d=!0}catch{d=!1}if(d)return this.markTestsPrUnchanged({branch:e.branch,repositoryPath:n,repoSlug:e.repoSlug,devPr:e.devPr});o=!1}}let a=async()=>{await this.remoteGit(["push",...o?["--force"]:[],e.remote,`HEAD:refs/heads/${e.branch}`],n),NV(this.run,n,r)};try{await a()}catch(u){let d=En(u);return i($v.test(d)?"auth":"push",`push failed: ${d}`,!1)}let c=this.description(e.bodyFile),l=async u=>{let d=await this.activePr(s,e.branch);if(d?.pullRequestId!==void 0){let m=d.pullRequestId;return await this.rest("PATCH",`${this.api(s)}/pullrequests/${m}`,{title:e.title,description:c}),d.targetRefName&&d.targetRefName!==`refs/heads/${u}`&&await this.rest("PATCH",`${this.api(s)}/pullrequests/${m}`,{targetRefName:`refs/heads/${u}`}).catch(f=>this.log(`[warn] could not move tests PR ${m} to ${u}: ${En(f)}`)),{action:"updated",pushed:!0,base:u,url:this.prUrl(s,m)}}let p=await this.rest("POST",`${this.api(s)}/pullrequests`,{sourceRefName:`refs/heads/${e.branch}`,targetRefName:`refs/heads/${u}`,title:e.title,description:c});if(typeof p.pullRequestId!="number")throw new Error("Azure DevOps created no pull request");return{action:"created",pushed:!0,base:u,url:this.prUrl(s,p.pullRequestId)}};try{return await l(e.base)}catch(u){let d=En(u);return $v.test(d)?i("auth",d,!0):await this.branchExists(s,e.base).catch(()=>!0)?i("unknown",d,!0):this.retarget(e,s,l,i,a)}}async branchExists(e,r){let n=new URL(`${this.api(e)}/refs`);return n.searchParams.set("filter",`heads/${r}`),((await this.rest("GET",n.toString())).value??[]).some(i=>i.name===`refs/heads/${r}`)}async retarget(e,r,n,s,i){let o=e.devPr;if(e.mode==="append")return s("unknown",`the dev branch '${e.base}' no longer exists and append mode cannot re-cut the tests branch \u2014 re-run in replace mode`,!0);if(o==null)return s("unknown",`the base branch '${e.base}' no longer exists and no dev PR number is known to retarget from`,!0);let a=await this.rest("GET",`${this.api(r)}/pullrequests/${o}`).catch(()=>{}),c=a?.targetRefName?.replace(/^refs\/heads\//,"");if(a?.status!=="completed"||!c)return{action:"skipped",pushed:!0,base:e.base,url:"",detail:`the dev branch '${e.base}' no longer exists and PR ${o} is ${a?.status??"unknown"} (not completed) \u2014 nothing to target; tests are on branch ${e.branch}`};this.log(`[deliver] tests PR base '${e.base}' no longer exists (dev PR completed) \u2014 re-cutting onto '${c}'`);try{await this.remoteGit(["fetch",e.remote,c],e.repositoryPath),this.git(["checkout","-B",e.branch,`${e.remote}/${c}`],void 0,e.repositoryPath),this.git(["cherry-pick","--keep-redundant-commits",e.commitSha],void 0,e.repositoryPath)}catch(l){return ZD(this.run,e),s("conflict",`re-cut onto '${c}' failed (tests kept on the local branch): ${En(l)}`,!0)}try{await i()}catch(l){return s("push",`push failed: ${En(l)}`,!1,c)}try{let l=await n(c);return{...l,action:"retargeted",retargetedAs:l.action==="updated"?"updated":"created"}}catch(l){return s("unknown",`re-cut onto '${c}' pushed, but PR create failed: ${En(l)}`,!0,c)}}async markTestsPrUnchanged(e){let r=e.repoSlug??this.opts.repoSlug,n=s=>({action:"skipped",pushed:!1,base:"",url:"",detail:s});try{let s=await this.activePr(r,e.branch);if(s?.pullRequestId===void 0)return n(`no open tests PR for ${e.branch} \u2014 nothing to annotate`);let i=e.devPr!=null?`PR ${e.devPr}`:"the dev branch",o=PV(i)+BV(s.description??""),a=o.length<=_V?o:o.slice(0,_V);return a.startsWith(tO)?(await this.rest("PATCH",`${this.api(r)}/pullrequests/${s.pullRequestId}`,{description:a}),{action:"unchanged",pushed:!1,base:(s.targetRefName??"").replace(/^refs\/heads\//,""),url:this.prUrl(r,s.pullRequestId),detail:"no new test changes this run \u2014 existing tests PR annotated"}):n("the tests PR description has no room for the banner")}catch(s){return n(`could not annotate the tests PR: ${DV(s)}`)}}async closeTestsPr(e){try{let r=await this.activePr(void 0,e.branch);if(r?.pullRequestId===void 0)return{closed:!1};let n=r.pullRequestId;return await this.rest("POST",`${this.api()}/pullRequests/${n}/threads`,{comments:[{parentCommentId:0,content:e.reason,commentType:1}],status:"closed"}),await this.rest("PATCH",`${this.api()}/pullrequests/${n}`,{status:"abandoned"}),{closed:!0,url:this.prUrl(void 0,n)}}catch(r){return this.log(`[warn] could not close the tests PR for ${e.branch}: ${DV(r)}`),{closed:!1}}}async endRun(){}async listCommitChecks(e){try{return((await this.rest("GET",`${this.api(e.repository)}/commits/${encodeURIComponent(e.revision)}/statuses?latestOnly=true`)).value??[]).filter(n=>n.context?.name).map(n=>({repository:e.repository,name:n.context?.genre?`${n.context.genre}/${n.context.name}`:n.context.name,headSha:e.revision,status:n.state==="pending"?"pending":"completed",conclusion:n.state==="pending"?null:n.state==="succeeded"?"success":n.state==="failed"?"failure":n.state==="notApplicable"?"neutral":n.state??null,url:n.targetUrl,summary:n.description}))}catch(r){this.log(`[warn] could not read CI results for ${e.repository}@${e.revision.slice(0,12)}: ${DV(r)}`);return}}async commitContains(e){try{let r=new URL(`${this.api(e.repository)}/diffs/commits`);for(let[s,i]of Object.entries({baseVersion:e.ancestor,baseVersionType:"commit",targetVersion:e.descendant,targetVersionType:"commit",$top:"1"}))r.searchParams.set(s,i);let n=await this.rest("GET",r.toString());return n.commonCommit?n.commonCommit.toLowerCase()===e.ancestor.toLowerCase()?"contained":"not_contained":"unknown"}catch(r){return this.log(`[warn] could not compare ${e.repository} ${ns(e.ancestor)}...${ns(e.descendant)}: ${DV(r)}`),"unknown"}}};var T0n=["local","github","azure"];function gut(t,e,r=Zr()){if(r.runnerPlatform!=="azure")return new eO(t);let n=Dge();if(!e||!n||!t.repoSlug||!t.tokenProvider)throw new Error("On Azure Pipelines, Testbot runs only the Validation Runs and SUT setups the Skyramp app starts: the step needs INPUT_SKYRAMPRUNID and the job's predefined variables.");return new rO({repositoryPath:t.repositoryPath,repoSlug:t.repoSlug,pipelineRun:n,tokenProvider:t.tokenProvider,log:t.log})}var but=require("child_process"),_h=$(require("fs")),Yc=$(require("path")),Eut=(t,e)=>(0,but.execFileSync)("git",["-c","safe.directory=*",...$i,...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","pipe"],env:wt()}),wut="^(http(\\..*)?\\.extraheader|core\\.sshcommand)$",bgr="core.sshcommand",OV=t=>t instanceof Error?t.message.split(`
|
|
542
542
|
`)[0]:String(t);function Egr(t){let e=t.split("\0"),r=[];for(let n=0;n+2<e.length;n+=3)r.push({scope:e[n],origin:e[n+1],key:e[n+2]});return r}function Aut(t,e){let r;try{r=e(["config","--show-scope","--show-origin","--name-only","-z","--get-regexp",wut],t)}catch(i){if(i.status===1)return[];throw new Error(`could not list persisted git credentials in ${t}: ${OV(i)}`)}let n=[],s=new Set;for(let{scope:i,origin:o,key:a}of Egr(r)){if(i!=="local"&&i!=="worktree"||!o.startsWith("file:")||!a)continue;let c=o.slice(5),l=Yc.isAbsolute(c)?c:Yc.join(t,c);s.has(`${a}\0${l}`)||(s.add(`${a}\0${l}`),n.push({key:a,file:l}))}return n}function xut(t,e=Eut,r){let n=wgr(t,e);return[...yut(t,e,r),...n.flatMap(s=>yut(s,e))]}function wgr(t,e){let r=!1;try{r=e(["rev-parse","--is-inside-work-tree"],t).trim()==="true"}catch{r=!1}if(!r){if(_h.existsSync(Yc.join(t,".git")))throw new Error(`could not read the git repository at ${t}`);return[]}let n;try{n=e(["submodule","foreach","--recursive","--quiet",'printf "%s\\0" "$displaypath"'],t)}catch(s){throw new Error(`could not list the submodules of ${t}: ${OV(s)}`)}return n.split("\0").filter(s=>s.length>0).map(s=>Yc.resolve(t,s))}function xgr(t,e=process.env.RUNNER_TEMP){if(!e)return;let r=/(?:^|\s)-i\s*(?:"([^"]+)"|'([^']+)'|(\S+))/.exec(t),n=r?.[1]??r?.[2]??r?.[3];if(!n)return;let s=Yc.resolve(n.replace(/^\$\{?RUNNER_TEMP\}?/,e)),i=Yc.resolve(e);return s.startsWith(i+Yc.sep)?s:void 0}function yut(t,e,r){let n=[],s=[],i=[];for(let{key:a,file:c}of Aut(t,e)){let l=a===bgr;if(l||r)try{for(let u of e(["config","--file",c,"--get-all",a],t).split(`
|
|
543
543
|
`).filter(Boolean)){l||r?.(u);let d=l?xgr(u):void 0;d&&s.push(d)}}catch{l&&i.push(`${a} (${c})`)}try{e(["config","--file",c,"--unset-all",a],t),n.push(`${a} (${c})`)}catch{}}for(let a of new Set(s))try{_h.rmSync(a,{force:!0}),n.push(`ssh key (${a})`)}catch{}let o=[...Aut(t,e).map(a=>`${a.key} (${a.file})`),...[...new Set(s)].filter(a=>_h.existsSync(a)).map(a=>`ssh key (${a})`),...i.map(a=>`${a}: could not read which key it names`)];if(o.length)throw new Error(`could not remove the persisted git credential from ${o.join(", ")}`);return n}function Sut(t=process.env.RUNNER_TEMP,e=Eut){if(!t||!_h.existsSync(t))return[];let r=[],n=[];for(let s of _h.readdirSync(t)){if(!/^git-credentials-.*\.config$/.test(s))continue;let i=Yc.join(t,s),o=()=>{try{return e(["config","--file",i,"--name-only","-z","--get-regexp",wut],t).split("\0").filter(Boolean)}catch(a){if(a.status===1)return[];throw new Error(`could not read the checkout credential file ${i}: ${OV(a)}`)}};for(let a of new Set(o()))try{e(["config","--file",i,"--unset-all",a],t),r.push(`${a} (${i})`)}catch{}n.push(...o().map(a=>`${a} (${i})`))}if(n.length)throw new Error(`could not remove the persisted git credential from ${n.join(", ")}`);return r}function Cut(t){let e=[],r=n=>{let s;try{s=_h.readdirSync(n,{withFileTypes:!0})}catch(i){throw new Error(`could not search ${n} for checkouts: ${OV(i)}`)}s.some(i=>i.name===".git")&&e.push(n);for(let i of s)i.isDirectory()&&i.name!==".git"&&i.name!=="node_modules"&&r(Yc.join(n,i.name))};return r(t),e}var Lm=$(require("fs")),Za=$(require("path"));var Rm=$(require("fs")),Iut=$(require("path")),Oge=$(require("crypto"));function MV(){return new Date().toISOString()}function Sgr(){return{runId:Oge.randomUUID(),createdAt:MV(),updatedAt:MV(),stages:{}}}function QV(t,e={}){if(!e.fresh&&Rm.existsSync(t))try{let r=JSON.parse(Rm.readFileSync(t,"utf-8"));if(r&&typeof r=="object"&&r.stages&&typeof r.stages=="object"&&!Array.isArray(r.stages))return r;e.onWarn?.(`State file ${t} malformed \u2014 starting fresh`)}catch(r){e.onWarn?.(`State file ${t} unreadable (${r instanceof Error?r.message:String(r)}) \u2014 starting fresh`)}return Sgr()}function Dh(t,e){e.updatedAt=MV(),Rm.mkdirSync(Iut.dirname(t),{recursive:!0});let r=`${t}.${process.pid}.${Oge.randomUUID()}.tmp`;Rm.writeFileSync(r,JSON.stringify(e,null,2)+`
|
|
544
544
|
`),Rm.renameSync(r,t)}function Bo(t,e,r){t.stages[e]={...r,updatedAt:MV()}}var vm=$(require("fs")),zv=$(require("path"));var Cgr=[/^\.github\//,/^\.gitlab(-ci)?/,/^\.circleci\//,/(^|\/)Jenkinsfile$/,/^docs?\//,/\.(md|mdx|rst)$/i,/(^|\/)LICENSE([._-].*)?$/i,/(^|\/)CODEOWNERS$/,/(^|\/)\.gitignore$/,/(^|\/)\.gitattributes$/,/(^|\/)\.editorconfig$/,/(^|\/)\.prettierrc[^/]*$/,/(^|\/)\.eslintrc[^/]*$/,/(^|\/)eslint\.config\.[^/]+$/,/(^|\/)package-lock\.json$/,/(^|\/)yarn\.lock$/,/(^|\/)pnpm-lock\.yaml$/,/(^|\/)poetry\.lock$/,/(^|\/)Pipfile\.lock$/,/(^|\/)Cargo\.lock$/,/(^|\/)go\.sum$/,/(^|\/)composer\.lock$/,/(^|\/)Gemfile\.lock$/,/\.(png|jpe?g|gif|svg|ico|webp)$/i];function Igr(t){return Cgr.some(e=>e.test(t))}function Rgr(t){let e=[],r=t.inputs.repositoryPath;return!r||!vm.existsSync(r)?e.push(`repository path does not exist: ${r}`):QD(r)?Sv(r,t.inputs.baseBranch)||e.push(t.inputs.baseBranch?`base branch "${t.inputs.baseBranch}" does not resolve`:"could not auto-detect a base branch (origin/HEAD, main, master)"):e.push(`not a git repository: ${r}`),{ok:e.length===0,reasons:e}}function vgr(t){return(t.inputs.relatedRepos??[]).map(e=>{let r=vm.existsSync(e.path)?my(e.path):void 0;return r?{repository:e.slug,changedFiles:r.changedFiles}:{repository:e.slug,changedFiles:[],note:`could not read the change in ${e.path}`}})}function Tgr(t){let{repositoryPath:e,baseBranch:r}=t.inputs;vm.rmSync(zv.join(e,is),{recursive:!0,force:!0});let n=my(e,r);if(!n)throw new Error(`could not compute git facts for ${e}`);let s=LD(e,r);if(!s)throw new Error(`could not compute the PR diff for ${e}`);let i=vgr(t),o=[n.changedFiles,...i.map(d=>d.changedFiles)].flat(),a=o.map(d=>d.path).filter(Igr),c=o.length>0&&a.length===o.length,l={schemaVersion:1,repository:{path:e,currentBranch:n.currentBranch,baseBranch:n.baseBranch},changedFiles:n.changedFiles,...i.length?{relatedChanges:i}:{},newFiles:s.newFiles,deletedFiles:s.deletedFiles,diffStat:s.diffStat,diffBytes:s.diffContent.length,nonApplicationFiles:a,nonApplicationOnly:c,sutRequired:!c};vm.writeFileSync(zv.join(t.runDir,Jw),s.diffContent);let u=zv.join(t.runDir,Zfe);return vm.mkdirSync(zv.dirname(u),{recursive:!0}),vm.writeFileSync(u,JSON.stringify(l,null,2)+`
|
|
@@ -563,7 +563,7 @@ ${s}`}var nO=require("child_process");var Ax=$(require("fs")),sd=$(require("path
|
|
|
563
563
|
`)}function Ggr(t,e,r){let n=r.map(i=>i.details??"").join(`
|
|
564
564
|
`),s=[];return/over the 400 cap/.test(n)&&s.push("The length caps are the ONLY thing wrong with those findings \u2014 keep each one, keep its id, and trim the named field. Do not drop a finding to get under a cap."),/changed file|changedFiles/.test(n)&&s.push('diff.changedFiles must be paths git reports. A glob is accepted for a run of near-identical files (`dir/<star>/x.json`), but it must match them and any "(N files)" count must be right \u2014 so list them plainly if you are unsure.'),/is not in requirements\[\]/.test(n)&&s.push("Every satisfies/conflictsWith id must be one you declared in requirements[] \u2014 check the spelling, don't invent one."),/nothing satisfies or conflictsWith it/.test(n)&&s.push("Every requirements[] entry needs a link: add its id to a behavior's satisfies when the diff implements it correctly, or to a finding's conflictsWith when the diff doesn't (or implements something else)."),s.length?s.join(`
|
|
565
565
|
`):void 0}var Vut=wn({name:"analyze",requires:["preflight"],model:"opus",timeoutMinutes:20,validateInput:Lgr,prepare:jut,buildPrompt:zgr,allowedTools:["Read","Grep","Glob","Bash(git diff:*)","Bash(git log:*)","Bash(git show:*)","Bash(git blame:*)","Bash(git status:*)"],selfVerification:['Every finding is behavior a test could catch, and one this change causes \u2014 a pre-existing defect is "latent".',"No two behaviors state the same obligation: if ONE test would pin both, they are one entry. Spend the room on a surface nothing describes yet.","You swept every changed file, not only the biggest one \u2014 a file with a single behavior beside one with a dozen is a sweep that stopped early.","Your final message is one JSON object matching the schema."],buildReadDirs:t=>(t.inputs.relatedRepos??[]).map(e=>e.path),exitGates:[But,_ut],retryHint:Ggr,adversarialReview:Out,onPassed:(t,e)=>({...Dut(t,e),diff:Qge}),salvage:(t,e)=>zut(t,e,{diff:Qge})});var Kdt=$(require("fs")),Ex=$(require("path")),Xdt=require("child_process");var sO=["browser_assert","browser_assert_api_request","browser_assert_hidden","browser_assert_table_cell","browser_blueprint","browser_click","browser_drag","browser_evaluate","browser_file_upload","browser_gojs_add_node","browser_gojs_link","browser_hover","browser_mouse_action","browser_navigate","browser_navigate_back","browser_press_key","browser_select_option","browser_snapshot","browser_tabs","browser_take_screenshot","browser_type","browser_visual_snapshot","browser_wait_for"],jgr=[...sO,"skyramp_export_zip","skyramp_actions","skyramp_analyze_changes","skyramp_analyze_test_health","skyramp_batch_mock_generation","skyramp_batch_scenario_test_generation","skyramp_contract_test_generation","skyramp_e2e_test_generation","skyramp_enhance_assertions","skyramp_enrich_test_with_mocks","skyramp_execute_test","skyramp_fix_errors","skyramp_fuzz_test_generation","skyramp_generate_enriched_integration_test","skyramp_init_scan","skyramp_init_workspace","skyramp_integration_test_generation","skyramp_load_test_generation","skyramp_login","skyramp_logout","skyramp_mock_generation","skyramp_modularization","skyramp_one_click_tool","skyramp_preflight_mock_check","skyramp_query_proxy_mocks","skyramp_recommend_tests","skyramp_register_test_plan","skyramp_reuse_code","skyramp_run_existing_tests","skyramp_setup_local_dev_worker","skyramp_smoke_test_generation","skyramp_start_trace_collection","skyramp_stop_trace_collection","skyramp_submit_report","skyramp_ui_test_generation"],Lge=["skyramp_init_workspace","skyramp_contract_test_generation","skyramp_integration_test_generation","skyramp_mock_generation","skyramp_fix_errors"],Uge=["skyramp_init_workspace","skyramp_ui_test_generation","skyramp_mock_generation","skyramp_fix_errors","skyramp_start_trace_collection","skyramp_stop_trace_collection","skyramp_export_zip",...sO],Fge=["skyramp_reuse_code","skyramp_modularization","skyramp_enhance_assertions","skyramp_fix_errors","skyramp_execute_test","skyramp_run_existing_tests"],$ge=["skyramp_init_scan","skyramp_init_workspace"],zV=["Bash(ls:*)","Bash(cat:*)","Bash(head:*)","Bash(tail:*)","Bash(wc:*)","Bash(find:*)","Bash(grep:*)","Bash(rg:*)","Bash(diff:*)","Bash(sort:*)","Bash(env:*)","Bash(echo:*)","Bash(pwd:*)","Bash(which:*)","Bash(cp:*)","Bash(curl:*)","Bash(jq:*)","Bash(true:*)"],Vgr=t=>`mcp__${Iv}__${t}`;function Nm(t){let e=new Set(t);return jgr.filter(r=>!e.has(r)).map(Vgr).sort()}var iO=$(require("fs")),id=$(require("path")),Vv=id.join(".skyramp","sut"),Wut=id.join(".skyramp","workspace.yml");function Wgr(t){return t.startsWith(`${Vv}${id.sep}`)||t.startsWith(".skyramp/sut/")||t===Wut||t===".skyramp/workspace.yml"||/(^|\/)(docker-compose|compose)[^/]*\.ya?ml$/.test(t)||/(^|\/)Dockerfile[^/]*$/.test(t)||/^\.github\/workflows\//.test(t)}function Ja(t,e,r={}){let n=e.split(/[\\/]+/).filter(Boolean),s=t;for(let[i,o]of n.entries()){s=id.join(s,o);let a=iO.lstatSync(s,{throwIfNoEntry:!1}),c=i===n.length-1;if(!a||a.isSymbolicLink()||(c?r.directory?!a.isDirectory():!a.isFile():!a.isDirectory()))return}return n.length?s:void 0}function Jc(t,e=[]){let r=p=>Ja(t,p),n=r(id.join(Vv,"setup.sh")),s=r(id.join(Vv,"teardown.sh")),i=r(id.join(Vv,"get-auth-token.sh")),o=r(Wut),a,c=r(id.join(Vv,"health.json"));if(c)try{let p=JSON.parse(iO.readFileSync(c,"utf-8"));p&&(p.url||p.command)&&(a=p)}catch{}let l,u=r(id.join(Vv,"deploy-budget.json"));if(u)try{let p=JSON.parse(iO.readFileSync(u,"utf-8"));typeof p?.minutes=="number"&&Number.isFinite(p.minutes)&&p.minutes>0&&(l=p.minutes)}catch{}let d=e.filter(Wgr);return{setupScript:n,teardownScript:s,authTokenScript:i,workspaceFile:o,healthHint:a,budgetMinutes:l,present:!!(n||o),staleFiles:d,stale:d.length>0}}var Ygr=50,Jgr=50,Kgr=4096,Xgr=8e3,Zgr=2048,qge=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/,eAr=/^(?!\/)(?!.*(?:^|\/)\.\.?(?:\/|$))[A-Za-z0-9._/ -]{1,255}$/,tAr=/^\.github\/workflows\/[A-Za-z0-9._-]+\.ya?ml$/,rAr=/^(?!GITHUB_)(?!SKYRAMP_RUNNER_)[A-Z][A-Z0-9_]{0,99}$/,Jut=(i=>(i.Command="command",i.ComposeFile="compose_file",i.DeploymentWorkflow="deployment_workflow",i.Url="url",i.Guidance="guidance",i))(Jut||{}),nAr={command:"optional",compose_file:"required",deployment_workflow:"required",url:"none",guidance:"none"},Yut=t=>y.string().max(t).refine(e=>e.trim().length>0&&!qge.test(e),"must be non-blank text with no control characters other than tab, LF and CR");function sAr(t){let e;try{e=new URL(t)}catch{return"invalid URL"}if(e.protocol!=="https:"&&e.protocol!=="http:")return"only http and https URLs";if(e.username||e.password)return"a URL cannot carry a login"}var iAr={command:Yut(Kgr),compose_file:y.string().regex(eAr,"must be a relative path inside the repository"),deployment_workflow:y.string().regex(tAr,"must be a .github/workflows/*.yml path"),url:y.string().max(Zgr).superRefine((t,e)=>{let r=sAr(t);r&&e.addIssue({code:y.ZodIssueCode.custom,message:r})}),guidance:Yut(Xgr)},oAr=y.object({kind:y.nativeEnum(Jut),value:y.string(),repository:ey.nullable()}).strict().superRefine((t,e)=>{let r=nAr[t.kind];r==="required"&&!t.repository&&e.addIssue({code:y.ZodIssueCode.custom,path:["repository"],message:"a file belongs to a repository"}),r==="none"&&t.repository&&e.addIssue({code:y.ZodIssueCode.custom,path:["repository"],message:`a ${t.kind} names no repository`});let n=iAr[t.kind].safeParse(t.value);if(!n.success)for(let s of n.error.issues)e.addIssue({code:y.ZodIssueCode.custom,path:["value"],message:s.message})}),aAr=y.object({name:y.string().regex(rAr,"must be a GitHub Actions secret name (A-Z, 0-9, _; not GITHUB_ or SKYRAMP_RUNNER_)"),purpose:y.nativeEnum(zG),required:y.boolean()}).strict(),cAr=y.object({knowledge:y.array(oAr).max(Ygr),credentials:y.array(aAr).max(Jgr)}).strict().superRefine((t,e)=>{let r=new Set;t.credentials.forEach((n,s)=>{r.has(n.name)&&e.addIssue({code:y.ZodIssueCode.custom,path:["credentials",s,"name"],message:"named twice"}),r.add(n.name)})});function lAr(t){return t.map(e=>`$${e.path.map(r=>typeof r=="number"?`[${r}]`:`.${r}`).join("")}: ${e.message}`).join("; ")}function Hge(t,e="SUT environment"){let r=cAr.safeParse(t);if(!r.success)throw new Error(`${e} is not valid SUT / Environment settings \u2014 ${lAr(r.error.issues)}`);return r.data}function Kut(t,e="SUT environment"){if(!t.trim())return;let r;try{r=JSON.parse(t)}catch(n){throw new Error(`${e} is not JSON: ${n instanceof Error?n.message:String(n)}`)}return Hge(r,e)}function GV(t,e=process.env){return(t?.credentials??[]).map(r=>e[r.name]).filter(r=>!!r?.trim())}var uAr={command:"command",compose_file:"compose file",deployment_workflow:"deployment workflow",url:"URL",guidance:"guidance"},dAr={model_provider:"model provider",sut_access:"SUT access",skyramp:"Skyramp",other:"other"};function Xut(t,e){let r=t.knowledge.map(n=>{let s=n.repository,i=s?` in ${e(s)??`the Target repository with ${s.provider} id ${s.providerRepositoryId}`}`:"";return`- ${uAr[n.kind]}${i}: ${n.value.trim().split(/\r?\n/).join(`
|
|
566
|
-
`)}`});if(t.credentials.length>0){let n=t.credentials.map(s=>`${s.name} (${dAr[s.purpose]}${s.required?"":", optional"})`);r.push(`- Secrets the workflow provides as environment variables: ${n.join(", ")} \u2014 the recipe reads each by exactly that variable name.`)}return r}var Wv=$(require("fs")),VV=$(require("path"));function zge(t,e){let{value:r,error:n}=Yr(t);if(n)return{errors:[n]};let s=e&&!e.testEnvironment?pAr(r,e):r,i=ev(s)&&s.schemaVersion===void 0?{schemaVersion:1,...s}:s,{value:o,errors:a}=tv(C_,$me,i);return o?{onboard:o,errors:[]}:{errors:a}}function pAr(t,e){if(!ev(t))return t;let{environment:r,...n}=t,s=[...e.repositorySlug?[{slug:e.repositorySlug,path:e.repositoryPath}]:[],...(e.relatedRepos??[]).map(a=>({slug:a.slug,path:a.path}))],i=a=>typeof a=="string"?s.find(c=>Ja(c.path,a))?.slug:void 0,o=Array.isArray(n.components)?n.components.map(a=>{if(!ev(a))return a;let{deployed:c,...l}=a;if(l.repository!==yn)return l;let u=ev(l.from)?l.from.file:void 0,d=i(u)??s[0]?.slug;return d?{...l,repository:d}:l}):n.components;return{...n,components:o}}var jV=".skyramp/sut/health.json",mAr={[jV]:`${jV} (with a url or command)`,".skyramp/workspace.yml":".skyramp/workspace.yml (create it with skyramp_init_scan and skyramp_init_workspace)"};function Zut(){return{name:"onboard-recipe",verify(t,e){let{onboard:r,errors:n}=zge(e.stdout,t.inputs);if(!r)return Re(this.name,n,{fatal:!0});let s=r.environment!==void 0;if(r.status==="blocked")return{name:this.name,passed:!0};let i=t.inputs.repositoryPath,o=Jc(i),a=s?QR.filter(u=>Ja(i,u)):[];if(a.length>0)return Re(this.name,[`an answer with "environment" tests a deployment where it runs and never starts or stops it: delete ${a.join(" and ")}, keep the health check, and answer "ready" again`]);let l=(s?Jme:Yme).filter(u=>!Ja(i,u)).map(u=>mAr[u]??u);return Ja(i,jV)&&!o.healthHint&&l.push(`${jV} (with a url or command)`),o.present&&l.length===0?{name:this.name,passed:!0}:Re(this.name,[`status is "ready" but the recipe deploy replays is incomplete in ${t.inputs.repositoryPath} \u2014 missing (each must be a regular file, not a symlink): ${l.join(", ")}. Write the missing files as the skill specifies and answer "ready" again, or answer "blocked" with the blocker that stopped you.`])}}}function edt(t,e,r=process.env){let n=[...t.components.flatMap(s=>s.credentials??[]),...t.environment?.credentials??[]];return[...new Set(n)].filter(s=>e.includes(s)&&!r[s])}function tdt(t,e){let r=t.components.filter(s=>s.credentials?.some(i=>e.includes(i))).map(s=>s.name),n=e.join(", ");return{component:(r.length>0?r:t.components.map(s=>s.name)).join(", ")||"SUT",problem:`${n} ${e.length===1?"has":"have"} no value in this setup`,evidence:`The workflow supplies ${e.length===1?"it":"each"} from a GitHub Actions secret, which is missing or empty.`,fix:`Set that secret in the workflow host's repository, or choose the secret that supplies ${e.length===1?"it":"each"} under Credentials, then run setup again.`}}function rdt(){return{name:"deployed-revisions",async verify(t,e,r,n){let s={name:this.name,passed:!0},i=t.checkDeployedRevisions;if(!i)return s;let{onboard:o}=zge(e.stdout,t.inputs);if(!o?.environment||o.status==="blocked")return s;let a=Qw(oO(t.inputs.repositoryPath).recipeFiles);if(!a)return s;let c=o.components.map(({name:d,repository:p})=>({name:d,repository:p})),{blockers:l}=await i(a.content,c,o.environment.credentials);if(l.length===0)return s;let u=l.map(d=>`${d.component}: ${d.problem} (${d.evidence})`).join("; ");return n?.retryLeft?Re(this.name,[`Testbot ran ${$a} twice, with GH_TOKEN, and it failed the check the setup's plan must pass: ${u}. Your session has no GH_TOKEN, so the part that reads GitHub ran in full only there. Fix the script so each component a repository builds gets the full commit it runs, the same on each run, from its own repository, then answer "ready" again, or answer "blocked" with the blocker that stops you.`]):{...s,details:`${$a} still fails Testbot's check, so the plan is saved blocked: ${u}`}}}}function fAr(t){try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t)}catch{return}}function oO(t){let e=[],r=o=>{let a;try{a=Wv.readdirSync(VV.join(t,o),{withFileTypes:!0})}catch{return}for(let c of a.sort((l,u)=>l.name.localeCompare(u.name))){let l=VV.posix.join(o,c.name);c.isDirectory()&&!c.name.startsWith(".")?r(l):c.isFile()&&e.push(l)}};Ja(t,".skyramp/sut",{directory:!0})&&r(".skyramp/sut"),Ja(t,".skyramp/workspace.yml")&&e.push(".skyramp/workspace.yml");let n=[],s=[],i=0;for(let o of e){let a=Ja(t,o);if(!a)continue;let l=Wv.statSync(a).size;if(l>Ow){s.push({path:o,reason:`larger than ${Ow} bytes`});continue}if(i+l>Mw){s.push({path:o,reason:`recipe text over ${Mw} bytes in total`});continue}let u=fAr(Wv.readFileSync(a));if(u===void 0||BG.test(u)){s.push({path:o,reason:"not text"});continue}n.push({path:o,content:u}),i+=l}return{recipeFiles:n,recipeFilesOmitted:s}}function ndt(t,e){let{onboard:r,errors:n}=zge(e.stdout,t.inputs),s=r&&{...r,...oO(t.inputs.repositoryPath)};return tr(t,"onboard",Xr(s,t.secretValues??[]),n)}function WV(t){if(t.state.stages.onboard?.status==="passed")return ae(t,"onboard.json")}var ws=$(require("fs")),km=$(require("path"));var ddt=require("child_process"),pdt=require("crypto"),po=$(require("fs")),od=$(require("path"));var sdt=$(require("fs")),by=$(require("path"));var Gge={"application/pdf":"PDF","text/csv":"CSV","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX"},idt=t=>Gge[t].toLowerCase(),ga=t=>new Map((t??[]).flatMap(e=>e.file?[[qa(e.key),e.file.name]]:[])),odt=10*1024*1024,yx=t=>t?.mediaType==="application/vnd.openxmlformats-officedocument.wordprocessingml.document"||t?.mediaType==="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",adt=(t,e)=>by.join(by.dirname(t),`${by.basename(t,by.extname(t))}${e}`),bx=t=>adt(t,".extracted.txt");function jge(t){try{return/\S/.test(sdt.readFileSync(bx(t),"utf-8"))}catch{return!1}}var Vge=t=>adt(t,".quotes.txt");function cdt(t){return yx(t.file)?bx(t.path):t.file?.mediaType==="application/pdf"?Vge(t.path):t.path}function YV(t){return t.map(e=>e.state!=="read"||!yx(e.file)||jge(e.path)?e:{...YA(e),file:e.file,state:"not_read",reason:"cannot_open"})}var hAr=10*6e4;function mdt(t,e){return t.getTime()-e.getTime()-hAr}var ldt="This attempt revoked its scoped GitHub credentials; it mints no more.",gAr=10*6e4,AAr=3e4,yAr=3,uo=class extends Error{constructor(r,n,s){super(r);this.status=n;this.code=s}status;code},Yv=class extends Error{};function Jge(t){let e;try{e=new URL(t)}catch{throw new Error(`skyrampAppOrigin "${t}" is not a URL`)}if(e.protocol!=="https:"||e.origin!==t.replace(/\/+$/,""))throw new Error(`skyrampAppOrigin must be an https origin, got "${t}"`);return e.origin}function bAr(t,e){if(!qR.test(t))throw new Error(`The ${e} "${t}" is not a uuid`);return t}function Kge(t,e){return`${t.replace(/\/+$/,"")}/runs/${e}`}function fdt(t,e,r){throw e<500&&e!==429?new uo(t,e,r):new Yv(t)}async function hdt(t,e,r,n){let s=Jge(t.origin),i;for(let o=1;o<=yAr;o+=1){o>1&&await new Promise(a=>setTimeout(a,(t.retryDelayMs??2e3)*(o-1)));try{let a=await t.idToken(s),c=await(t.fetch??fetch)(new URL(e,s).toString(),{...r(a),redirect:"error",signal:AbortSignal.timeout(AAr)}).catch(l=>{throw new Yv(l instanceof Error?l.message:String(l),{cause:l})});return await n(c)}catch(a){if(a instanceof uo)throw a;i=a}}throw i}function gdt(t,e,r,n){return hdt(t,r,i=>({method:e,headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json",Accept:"application/json"},body:e==="GET"?void 0:JSON.stringify(n)}),async i=>{let o=await i.json().catch(()=>({}));if(i.ok)return o.data;let a=o.error?.fields,c=typeof a?.path=="string"&&typeof a.reason=="string"?` at ${a.path}: ${a.reason}`:"",l=`The Skyramp app refused ${e} ${r}: ${i.status} ${o.error?.code??"no error code"}${c}`;return fdt(l,i.status,o.error?.code)})}function EAr(t,e,r){return hdt(t,e,s=>({method:"GET",headers:{Authorization:`Bearer ${s}`,Accept:"application/octet-stream"}}),async s=>{if(!s.ok)return fdt(`The Skyramp app refused GET ${e}: ${s.status}`,s.status);let i=Buffer.from(await s.arrayBuffer());if(i.length>r)throw new uo(`The Skyramp app answered GET ${e} with more than ${r} bytes`,s.status);return i})}var Wge=class{constructor(e,r,n,s,i,o,a,c,l){this.attemptId=e;this.attemptNumber=r;this.deadlineAt=n;this.manifest=s;this.deps=i;this.license=o;this.requestedBy=a;this.writeAllowed=c;this.claudeCodeVersion=l}attemptId;attemptNumber;deadlineAt;manifest;deps;license;requestedBy;writeAllowed;claudeCodeVersion;budgetMs(e){return mdt(this.deadlineAt,e)}get skyrampRunUrl(){return Kge(Jge(this.deps.origin),this.manifest.runId)}send(e,r,n){return gdt(this.deps,e,r,n)}readBytes(e,r){return EAr(this.deps,e,r)}issuedTokens=[];closure;modelKey;credentials;revocation;async token(){if(this.revocation)throw new Error(ldt);let e=(this.deps.now??(()=>new Date))().getTime(),r=this.credentials,n=r&&await r.catch(()=>{});if(this.credentials!==r)return(await this.credentials).token;if(n&&n.expiresAt-e>=gAr)return n.token;if(this.revocation)throw new Error(ldt);let s=this.send("POST",`/api/v1/runner/attempts/${this.attemptId}/credentials`,{schemaVersion:1}).then(i=>{let o={...i,token:i.token??this.jobToken()};this.issuedTokens.push(o.token),this.deps.mask?.(o.token),!n&&o.anthropicApiKey&&(this.modelKey=o.anthropicApiKey,this.deps.mask?.(o.anthropicApiKey));let a=n?"Renewed":"Received";return i.token&&this.deps.log?.(`${a} scoped GitHub credentials; they expire at ${o.expiresAt}.`),{token:o.token,expiresAt:new Date(o.expiresAt).getTime()}},i=>{if(!(i instanceof uo)||i.code!=="CREDENTIALS_UNAVAILABLE")throw i;let o=l=>[...new Set(l.map(u=>u.namespace))].join(", "),a=this.manifest.sources.map(l=>l.repository);if(new Set(a.map(l=>l.providerAccountId)).size>1)throw new uo(`${i.message}. The run's repositories are on more than one GitHub account (${o(a)}), which Skyramp does not support yet.`,i.status,i.code);let c=o([...a,this.manifest.execution.repository]);throw new uo(`${i.message}. Check the Skyramp GitHub App installation on ${c}: 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.`,i.status,i.code)});return this.credentials=s,(await s).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(e){return e.fetch??this.deps.fetch??fetch}revokeTokens(e={}){let r=e.host??Zr();return this.revocation??=r.revokeToken?this.revokeIssued(n=>r.revokeToken(n,this.sourceFetch(e))):Promise.resolve([]),this.revocation}async revokeIssued(e){let r=[...this.issuedTokens],n=Promise.all(r.map(o=>this.revokeOne(o,e)));await this.credentials?.catch(()=>{});let s=this.issuedTokens.filter(o=>!r.includes(o));return[...await n,...await Promise.all(s.map(o=>this.revokeOne(o,e)))].filter(o=>o!==void 0)}async revokeOne(e,r){try{await r(e);return}catch(n){return`token ${this.issuedTokens.indexOf(e)+1} of ${this.issuedTokens.length}: ${n instanceof Error?n.message:String(n)}`}}};async function Adt(t,e,r){bAr(t,"run id"),Jge(r.origin);let n=Nst(t,e),s=kst(await gdt(r,"POST",`/api/v1/runner/runs/${t}/attempts`,n));if(s.manifest.runId!==t)throw new Error(`The app answered the handshake of run ${t} with the manifest of another run (${s.manifest.runId})`);let i=s.manifest.sources.find(a=>a.repository.provider!==n.execution.provider);if(i)throw new Error(`The manifest of run ${t} names ${i.repository.namespace}/${i.repository.name} on ${i.repository.provider}, but this job runs on ${n.execution.provider}`);s.runToken&&r.mask?.(s.runToken);let o=s.runToken?{entitlements:s.entitlements??[],runToken:s.runToken}:void 0;return new Wge(s.attempt.id,s.attempt.number,new Date(s.attempt.deadlineAt),s.manifest,r,o,s.requestedBy??void 0,s.writeAllowed,s.claudeCodeVersion??void 0)}var wAr=6e4;async function ydt(t){return Ist.parse(await t.send("POST",`/api/v1/runner/attempts/${t.attemptId}/heartbeat`,{schemaVersion:1}))}async function bdt(t,e=()=>new Date){if(t.closure)return t.closure;let r=await ydt(t).then(n=>bfe(n,e())).catch(()=>null);return r&&(t.closure=r),r}function Edt(t,e,r={}){let n=!1,s,i=async()=>{try{let a=bfe(await ydt(t),(r.now??(()=>new Date))());a&&!n&&(n=!0,t.closure=a,e(a))}catch(a){a instanceof uo&&(n=!0)}n||o(r.intervalMs??wAr)},o=a=>{s=setTimeout(()=>{i()},a),s.unref?.()};return o(0),{stop(){n=!0,clearTimeout(s)}}}var xAr=10*6e4,SAr=(t,e,r)=>(0,ddt.execFileSync)("git",e,{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","pipe"],env:r??process.env,timeout:xAr}).trim(),CAr=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];async function wdt(t,e){let r=e.git??SAr,n=e.host??Zr(),s=e.cloneUrl??(c=>n.cloneUrl(c)),{sources:i}=t.manifest;for(let c of i){if(CAr.includes(c.reason)&&!c.change?.base)throw new Error(`${c.repository.namespace}/${c.repository.name} was selected as ${c.reason}, but its change names no base revision to compare it with`);if(c.change?.kind==="pull_request"&&!c.change.base)throw new Error(`${c.repository.namespace}/${c.repository.name} pull request ${c.change.number} names no base revision to compare it with`);n.checkSourceName(c.repository)}if(po.existsSync(e.workspace)&&po.lstatSync(e.workspace).isSymbolicLink())throw new Error(`The sources workspace ${e.workspace} is a symlink; refusing to clear it`);po.rmSync(e.workspace,{recursive:!0,force:!0});let o=new Map((t.manifest.baseline.sources??[]).map(c=>[B_(c.repository),c.revision])),a=[];for(let c of i){let{namespace:l,name:u}=c.repository,d=od.join(e.workspace,l,u);po.mkdirSync(d,{recursive:!0});let p={...process.env,GIT_TERMINAL_PROMPT:"0",...n.gitAuthEnv(await t.token())};r(d,["init","-q"]),r(d,["remote","add","origin",s(c.repository)]);let m=c.change?.base??c.compareWith,f=o.get(B_(c.repository)),h=m?.revision??(f!==c.revision?f:void 0);r(d,["fetch","-q","--no-tags","origin",c.revision,...h?[h]:[]],p);let b=m??(c.ref?{ref:c.ref,revision:f??c.revision}:null);b&&(r(d,["update-ref",`refs/remotes/origin/${b.ref}`,b.revision]),r(d,["symbolic-ref","refs/remotes/origin/HEAD",`refs/remotes/origin/${b.ref}`])),c.ref?r(d,["checkout","-q","-B",c.ref,c.revision]):r(d,["checkout","-q","--detach",c.revision]),a.push({repository:c.repository,revision:r(d,["rev-parse","HEAD"]),path:d,slug:`${l}/${u}`})}return a}async function xdt(t,e={}){let r=e.host??Zr(),n={token:()=>t.token(),fetch:t.sourceFetch(e)},s=[];for(let i of t.manifest.sources){if(i.change?.kind!=="pull_request")continue;let{namespace:o,name:a}=i.repository,c=`${o}/${a}`,l=i.change.number;try{s.push({repository:c,number:l,...await r.pullRequest(i.repository,l,n)})}catch(u){let d=u instanceof Error?u.message:String(u);s.push({repository:c,number:l,note:`could not be read: ${d}`})}}return s}async function Sdt(t,e,r,n={}){return(n.host??Zr()).commitLookup(e,r,{token:()=>t.token(),fetch:t.sourceFetch(n)})}function Cdt(t,e){let r=t.sources.find(s=>s.reason==="TRIGGER"&&s.change?.kind==="pull_request"),n=r&&e.find(s=>s.repository.providerRepositoryId===r.repository.providerRepositoryId);return n&&r.change?{repository:n.slug,path:n.path,number:Number(r.change.number)}:void 0}var IAr=[".skyramp/sut/setup.sh",".skyramp/workspace.yml"];function Idt(t){let e=t.find(r=>IAr.some(n=>po.existsSync(od.join(r.path,n))))??t[0];return{repositoryPath:e.path,repositorySlug:e.slug,relatedRepos:t.filter(r=>r!==e).map(r=>({slug:r.slug,path:r.path,writable:!0}))}}var RAr=y.object({tests:y.object({placements:y.array(y.unknown()).optional()}).passthrough().optional()}).passthrough(),vAr=y.object({repository:ife,testType:y.nativeEnum(Yw),directory:y.string()}).passthrough();function Rdt(t,e){let r=RAr.safeParse(t.settings.target??{}),n=[];for(let s of(r.success?r.data.tests?.placements:void 0)??[]){let i=vAr.safeParse(s);if(!i.success)continue;let{repository:o,testType:a}=i.data,c=e.find(d=>d.repository.provider===o.provider&&d.repository.providerRepositoryId===o.providerRepositoryId),l=i.data.directory.trim(),u=!l||od.isAbsolute(l)||l.split(/[\\/]/).includes("..");!c||u||n.push({repository:c.slug,testType:a,directory:l})}return n}var TAr=y.object({report:y.object({language:y.string()}).passthrough()}).passthrough();function Xge(t){let e=TAr.safeParse(t?.settings.target);return e.success?Uq(e.data.report.language):"en"}var NAr=y.object({environment:y.object({components:y.array(y.unknown()).optional(),dependencies:y.array(y.unknown()).optional()}).passthrough()}).passthrough(),kAr=y.object({name:y.string().min(1),provision:y.literal("existing"),url:y.string().min(1),repository:ife.optional(),revisionUrl:y.string().min(1).optional()}).passthrough(),PAr=y.object({name:y.string().min(1),url:y.string().nullable(),versionUrl:y.string().nullable(),notes:y.string().nullable()}).passthrough();function vdt(t,e){let r=NAr.safeParse(t.settings.target),n=r.success?r.data.environment:{},s=(n.components??[]).flatMap(a=>{let c=kAr.safeParse(a);if(!c.success)return[];let{name:l,url:u,repository:d,revisionUrl:p}=c.data;if(!d)return[{name:l,url:u}];let m=e.sources.find(f=>f.repository.provider===d.provider&&f.repository.providerRepositoryId===d.providerRepositoryId);return m?[{name:l,url:u,repository:`${m.repository.namespace}/${m.repository.name}`,expectedRevision:m.revision,...p?{revisionUrl:p}:{}}]:[{name:l,url:u,repository:`${d.provider} repository ${d.providerRepositoryId}`}]}),i=(n.dependencies??[]).flatMap(a=>{let c=PAr.safeParse(a);return c.success?[{name:c.data.name,url:c.data.url,versionUrl:c.data.versionUrl,notes:c.data.notes}]:[]});if(s.length===0&&i.length===0)return;let o=y.object({allowSharedEnvironmentMutation:y.boolean()}).passthrough().safeParse(t.settings.policy);return{components:s,dependencies:i,allowMutation:o.success&&o.data.allowSharedEnvironmentMutation}}var BAr=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);function udt(t,e){if(!BAr.has(t.reason))return{};let r=`${t.repository.namespace}/${t.repository.name}`,n=t.change?.kind==="pull_request"?t.change.number:void 0,s=n===void 0?void 0:e.find(a=>Pj(a.repository,r)&&a.number===n),i=s?.merged===!0?s.mergeCommit:void 0,o=i&&s?.mergedHead?{mergedHead:s.mergedHead}:{};return{touched:!0,acceptedRevisions:{frozen:t.revision,...i&&i!==t.revision?{mergeCommit:i,...o}:{}}}}function Tdt(t,e,r,n,s){let i=u=>r.sources.find(d=>Pj(`${d.repository.namespace}/${d.repository.name}`,u)),o=(t?.components??[]).map(u=>{let d=u.expectedRevision?i(u.repository):void 0;return d?{...u,...udt(d,s)}:u}),a=Qw(e.files)!==void 0,c=e.components.map(u=>{if(u.repository===yn)return{name:u.name,url:e.address};let d=i(u.repository),p=a?void 0:uhe(e,u.name);return{name:u.name,url:e.address,repository:u.repository,...d?{expectedRevision:d.revision}:{},...p?{revisionUrl:p}:{},...a?{revisionScript:!0}:{},...d?udt(d,s):{}}}),l=y.object({allowSharedEnvironmentMutation:y.boolean()}).passthrough().safeParse(n?.settings.policy);return{components:[...o,...c],dependencies:t?.dependencies??[],allowMutation:t?.allowMutation??(l.success&&l.data.allowSharedEnvironmentMutation)}}function Ndt(t){let e=r=>t.testResults.filter(n=>n.status===r).length;return{passed:e("Pass"),failed:e("Fail"),skipped:e("Skipped")}}function _Ar(t){let{passed:e,failed:r,skipped:n}=Ndt(t);return e+r===0?{sufficiency:"insufficient",rationale:n>0?`Every test was skipped (${n}), so nothing was validated.`:"No test ran, so nothing was validated.",gaps:["No test ran against the frozen sources."],acceptedEvidence:[],actionRequired:[]}:{sufficiency:"sufficient",rationale:`${e+r} tests ran against the frozen sources: ${e} passed, ${r} failed${n?`, ${n} skipped`:""}.`,gaps:[],acceptedEvidence:[],actionRequired:[]}}function DAr(t,e){let r=t.testResults.map(c=>({result:c,repository:c.repository??e,path:c.fileName||c.testType})),n=new Map;for(let c of r){let l=`${c.repository}:${c.result.testType}:${c.path}`;n.set(l,(n.get(l)??0)+1)}let s=r.map(({result:c,repository:l,path:u})=>{let d=(n.get(`${l}:${c.testType}:${u}`)??0)>1;return c.resultId??JG(l,c.testType,u,d&&c.endpoint||void 0)}),i=new Map;for(let c of s)i.set(c,(i.get(c)??0)+1);let o=new Set(s.filter(c=>i.get(c)===1)),a=r.map(({result:c,repository:l},u)=>{let d=s[u],p=d;if(i.get(d)>1&&o.has(d))for(let m=2;o.has(p)||p===d;m+=1)p=d.includes("#")?`${d}.${m}`:`${d}#${m}`;return o.add(p),{...c,repository:l,resultId:p}});return{...t,testResults:a,...OAr(t,a,e),validation:MAr(t,t.validation??_Ar(t)),traceVersion:1}}function OAr(t,e,r){if(!t.testExecutionContexts)return{};let n=new Set,s=a=>{let c=a;for(let l=2;n.has(c);l+=1)c=`${a}#${l}`;return n.add(c),c},i=[],o=new Map;for(let{repository:a,...c}of t.testExecutionContexts){let l=c.status==="not_run"?[]:e.filter(u=>u.fileName===c.test&&u.repository===(a?.trim()||r));l.length||i.push(c);for(let{resultId:u}of l){let d=o.get(u),p=d!==void 0&&i[d].cleanup.status==="failed"?i[d].cleanup:c.cleanup,m={...c,cleanup:p,test:u,resultId:u};d===void 0?o.set(u,i.push(m)-1):i[d]=m}}for(let a of i)a.resultId&&n.add(a.resultId);return{testExecutionContexts:i.map(a=>a.resultId?a:{...a,test:s(a.test.slice(0,512))}).slice(0,5e3)}}function MAr(t,e){let{passed:r,failed:n}=Ndt(t);return e.sufficiency!=="sufficient"||r+n>0||e.acceptedEvidence.length>0?e:{...e,sufficiency:"insufficient",gaps:["No test ran and no existing evidence was accepted, so nothing was validated."]}}async function kdt(t,e){let r=Wu([...t.issuedTokens,...e.secrets??[]]),n=Bst({manifest:t.manifest,attemptNumber:t.attemptNumber,checkedOut:e.sources.map(s=>({repository:s.repository,revision:s.revision})),generatedTests:Xr(e.delivery,r),producer:e.producer,report:Xr(DAr(e.report,e.workingSlug),r),githubWrites:e.githubWrites});await t.send("PUT",`/api/v1/runner/attempts/${t.attemptId}/report`,n)}async function Zge(t){let e=Sst.parse(await t.send("GET",`/api/v1/runner/attempts/${t.attemptId}/configuration`,void 0)),r=t.manifest.configuration,{configuration:n,capture:s}=e;if(n.captureId!==r.captureId||n.revision!==r.revision||n.hash!==r.hash||s.hash!==r.hash||Tst(s)!==r.hash)throw new Error("The app answered the configuration of another capture than the manifest names");return e}var Yge=class extends Error{};async function JV(t){let{runtimePlan:e,testEnvironment:r}=Cst.parse(await t.send("GET",`/api/v1/runner/attempts/${t.attemptId}/runtime-plan`,void 0));if(e&&Rst(e.files)!==e.contentHash)throw new Yge(`Stored SUT recipe version ${e.version} does not match its hash`);return{runtimePlan:e,testEnvironment:r??null}}async function Pdt(t,e,r=()=>{}){try{po.rmSync(e,{recursive:!0,force:!0})}catch{}let n=t.manifest.requirements??[];if(n.length===0&&!t.manifest.instructions)return{items:[],instructions:[]};let s,i=[];try{let a=mst.parse(await t.send("GET",`/api/v1/runner/attempts/${t.attemptId}/requirements`,void 0));s=new Map(a.items.map(c=>[Oc(c),c])),i=t.manifest.instructions?a.instructions??[]:[]}catch(a){let c=a instanceof Error?a.message:String(a);r(`Testbot V3: could not read the run's requirement items: ${c}`),s=new Map}try{po.mkdirSync(e,{recursive:!0,mode:448})}catch{}let o=[];for(let a of n){let c={...YA(a),..."fileName"in a?{file:{name:a.fileName,mediaType:a.mediaType}}:{}},l=s.get(Oc(c));if(!l)o.push({...c,state:"not_read",reason:Uw.test(c.key)?"cannot_open":"unavailable"});else if(l.state==="not_read")o.push({...c,state:"not_read",reason:l.reason});else if(!("text"in l))o.push(await QAr(t,e,c,a.contentHash,r));else{let u=od.join(e,Bdt(c));try{po.writeFileSync(u,l.text,{mode:384}),o.push({...c,state:"read",path:u,contentMatches:l.contentMatches,version:l.version})}catch(d){r(`Testbot V3: could not write the requirement item ${c.key}: ${d instanceof Error?d.message:String(d)}`),o.push({...c,state:"not_read",reason:"unavailable"})}}}return{items:o,instructions:i}}async function QAr(t,e,r,n,s){let i=c=>(s(`Testbot V3: could not open the uploaded document ${r.key}: ${c}`),{...r,state:"not_read",reason:"cannot_open"});if(!r.file)return i("the manifest names no file");let o;try{let c=cst.requirementFile.replace(":attemptId",t.attemptId).replace(":key",r.key);o=await t.readBytes(c,odt)}catch(c){return i(c instanceof Error?c.message:String(c))}if((0,pdt.createHash)("sha256").update(o).digest("hex")!==n)return i("its bytes do not match its hash");let a=od.join(e,Bdt(r));try{po.writeFileSync(a,o,{mode:384})}catch(c){return i(c instanceof Error?c.message:String(c))}return{...r,state:"read",path:a,contentMatches:!0,version:n}}function Bdt(t){let e=t.source==="other"?[]:[new URL(t.site).hostname],r=t.file?idt(t.file.mediaType):"txt";return`${[t.source,...e,t.key].join("-")}.${r}`}async function eAe(t,e){await t.send("POST",`/api/v1/runner/attempts/${t.attemptId}/progress`,hst.parse(e))}async function _dt(t,e){return yst.parse(await t.send("POST",`/api/v1/runner/attempts/${t.attemptId}/setup-events`,gst.parse(e)))}async function Ddt(t,e){await t.send("POST",`/api/v1/runner/attempts/${t.attemptId}/setup-checkpoint`,Est.parse(e))}async function Odt(t){return(await Qdt(t,"setup-checkpoint",wst))?.checkpoint??null}async function Mdt(t){return(await Qdt(t,"setup-context",xst))?.context??null}async function Qdt(t,e,r){try{return r.parse(await t.send("GET",`/api/v1/runner/attempts/${t.attemptId}/${e}`,void 0))}catch(n){if(n instanceof uo&&n.status===404)return null;throw n}}async function tAe(t,e){let r=Wu([...t.issuedTokens,...e.secrets??[]]),n=_st(t.manifest,t.attemptNumber,e.sources.map(s=>({repository:s.repository,revision:s.revision})),Xr(e.recipe,r),e.producer);await t.send("PUT",`/api/v1/runner/attempts/${t.attemptId}/sut-recipe`,n)}function Ldt(t,e,r,n=e[0].slug,s,i={}){let{record:o,entries:a}=Fdt(t,e,n),c=tu({outputsDir:t,state:QV(od.join(od.dirname(t),"state.json"))});if(!o&&Dj(i,r.system,c?.sutRequired).length>0)return{status:"none"};let l=f=>Udt(e,f),u=[],d=[];for(let{record:f,repository:h,number:b}of a)if(h&&b)u.push({repository:h,number:b});else if(h&&f.prFailure){let E=f.prDetail?`${f.prFailure}: ${f.prDetail}`:f.prFailure;d.push({repository:h,message:E,slug:f.repository??n})}else h&&f.committed&&d.push({repository:h,message:f.reason??"The tests were committed but no pull request was opened.",slug:f.repository??n});let p=new Set([...u,...d].map(({repository:f})=>f.providerRepositoryId)),m=[...new Set(r.newTestsCreated.map(f=>(f.repository??n).toLowerCase()))];for(let f of m){let h=l(f);h&&!p.has(h.providerRepositoryId)&&d.push({repository:h,message:s??"Generated tests were not proposed in a pull request.",slug:f})}return u.length&&d.length?{status:"partial",pullRequests:u,failures:d.map(({repository:f,message:h})=>({repository:f,message:h}))}:u.length?{status:"delivered",pullRequests:u}:d.length?{status:"failed",message:o?.deliveries?d.map(f=>`${f.slug}: ${f.message}`).join("; "):d[0].message}:r.newTestsCreated.length>0?{status:"failed",message:s??"Generated tests were not proposed in a pull request."}:{status:"none"}}function Udt(t,e){let r=t.find(n=>n.slug.toLowerCase()===e.toLowerCase());return r&&{provider:r.repository.provider,providerAccountId:r.repository.providerAccountId,providerRepositoryId:r.repository.providerRepositoryId}}function Fdt(t,e,r){let n=od.join(t,"deliver.json"),s=po.existsSync(n)?JSON.parse(po.readFileSync(n,"utf-8")):void 0,i=s?.deliveries??(s?[s]:[]);return{record:s,entries:i.map(o=>({record:o,repository:Udt(e,o.repository??r),number:/\/pull\/([1-9][0-9]*)$/.exec(o.prUrl??"")?.[1]}))}}function $dt(t,e,r=e[0].slug){let n=new Map,s=(i,o)=>{ufe.safeParse(i).success&&n.set(`${i.kind}:${i.repository.providerRepositoryId}:${o}`,i)};for(let{record:i,repository:o,number:a}of Fdt(t,e,r).entries){if(!o||!i.branch)continue;let c=i.pushedCommits??(i.pushed&&i.commitSha?[i.commitSha]:[]);for(let u of c)s({kind:"branch_pushed",repository:o,branch:i.branch,commit:u},`${i.branch}:${u}`);if(!a)continue;let l=i.prAction==="retargeted"?i.retargetedAs??"created":i.prAction;l==="created"?s({kind:"pull_request_opened",repository:o,number:a,branch:i.branch},a):(l==="updated"||l==="unchanged")&&s({kind:"pull_request_edited",repository:o,number:a,branch:i.branch},a)}return[...n.values()].slice(0,lfe)}function qdt(t,e){return t.credentials.filter(r=>r.required&&!e[r.name]).map(r=>r.name)}var rAe=[/\bgh[pousr]_[A-Za-z0-9]{36,}/g,/\bgithub_pat_[A-Za-z0-9_]{22,}/g,/\bsk-ant-[A-Za-z0-9_-]{20,}/g,/\bsk-[A-Za-z0-9]{32,}/g,/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g],Hdt=t=>rAe.some(e=>new RegExp(e.source).test(t));var Oh=".skyramp/setup-events.ndjson",aO=".skyramp/setup-left-out.json",cO=".skyramp/setup-inbox.json",nAe=".skyramp/setup-inbox-read.json",eW=".skyramp/setup-hook-ran",LAr=6e4,UAr=5e3,FAr=300,ri=t=>{let e=typeof t=="string"?t:typeof t=="number"?String(t):"";return e.trim()==="null"?"":e},KV=t=>Array.isArray(t)?t:[],ZV=(t,e)=>Object.values(t).find(r=>r===ri(e).trim().toLowerCase()),$Ar={running:"up",healthy:"up",ready:"up",started:"up",building:"starting",pending:"starting",installing:"starting",skipped:"out_of_scope",excluded:"out_of_scope","out-of-scope":"out_of_scope"},qAr=t=>ZV(Q_,t)??$Ar[ri(t).trim().toLowerCase()]??"found",zdt=t=>y.string().uuid().safeParse(t).success,HAr=t=>XG.test(t)?t:t.replace(/[^A-Za-z0-9_-]+/g,"-").slice(0,64).replace(/^-+|-+$/g,"")||"question",zAr=/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/,GAr=/github\.com[/:]([^/\s]+)\/([^/\s?#]+?)(?:\.git)?(?:[/?#]|$)/i;function jAr(t){if(t.kind!=="question"||t.placeholder===void 0)return t;let{placeholder:e,...r}=t;return r}var Gdt=new RegExp(Afe.source,"g"),tW=class{constructor(e,r,n){this.checkout=e;this.send=r;this.opts=n}checkout;send;opts;offset=0;sequence=1;pending=[];started=!1;closed=!1;capped=!1;flushing=0;emptyRefused=!1;placeholderRefused=!1;unreadSince;saidHookSilent=!1;timer;queue=Promise.resolve();phase="discover";messageIds=new Set;stopHeard=!1;start(){if(!this.timer){if(!this.started){this.started=!0;let e=km.join(this.checkout,Oh);ws.mkdirSync(km.dirname(e),{recursive:!0}),ws.writeFileSync(e,"");for(let r of[aO,cO,nAe,eW])ws.rmSync(km.join(this.checkout,r),{force:!0})}this.timer=setInterval(()=>{this.flushing===0&&this.flush()},this.opts.intervalMs??UAr),this.timer.unref?.()}}async stop(){this.timer&&clearInterval(this.timer),this.timer=void 0,await this.flush()}flush(){return this.flushing+=1,this.queue=this.queue.then(()=>this.drain()).catch(e=>this.opts.warn(`Testbot V3: could not send setup events: ${XV(e)}`)).finally(()=>{this.flushing-=1}),this.queue}async drain(){if(!this.closed){if(this.collect(),this.pending.length===0&&!this.emptyRefused){await this.sendBatch([]);return}for(;this.pending.length>0&&!this.closed;){let e=this.pending.slice(0,HR);if(await this.sendBatch(e)==="unanswered")return;this.pending.splice(0,e.length)}}}async sendBatch(e){this.placeholderRefused&&(e=e.map(jAr));let r;try{r=await this.send({schemaVersion:1,events:e})}catch(n){if(n instanceof uo&&n.code==="RUN_CLOSED")return this.closed=!0,this.pending=[],"done";if(n instanceof uo&&e.length===0)return this.emptyRefused=!0,"done";if(n instanceof uo){if(e.length>1){for(let i of e){if(this.closed)return"done";if(await this.sendBatch([i])==="unanswered")return"unanswered"}return"done"}if(e[0].kind==="question"&&e[0].placeholder!==void 0)return this.placeholderRefused=!0,this.sendBatch(e);let s=e[0].kind==="log"?void 0:VAr(e[0]);return s?(this.opts.warn(`Testbot V3: the app refused setup event ${e[0].sequence}, so it is sent as a log line: ${n.message}`),this.sendBatch([{sequence:e[0].sequence,at:e[0].at,kind:"log",phase:this.phase,text:s}])):(this.opts.warn(`Testbot V3: the app refused setup event ${e[0].sequence}, so it is dropped: ${n.message}`),"done")}return n instanceof y.ZodError?(this.opts.warn(`Testbot V3: the app's answer to setup events was not understood: ${n.issues[0]?.message}`),"done"):(this.opts.warn(`Testbot V3: could not send setup events, trying again: ${XV(n)}`),"unanswered")}try{this.writeLeftOut(r.leftOut)}catch(n){this.opts.warn(`Testbot V3: could not write ${aO}: ${XV(n)}`)}try{this.writeInbox(r.messages??[])}catch(n){this.opts.warn(`Testbot V3: could not write ${cO}: ${XV(n)}`)}return r.stop&&!this.stopHeard&&(this.stopHeard=!0,this.opts.onStop?.(r.stop.key)),"done"}collect(){if(this.capped)return;let e=km.join(this.checkout,Oh),r;try{r=ws.statSync(e).size}catch{return}if(r<this.offset&&(this.offset=0),r===this.offset)return;let n=Buffer.alloc(r-this.offset),s=ws.openSync(e,"r");try{ws.readSync(s,n,0,n.length,this.offset)}finally{ws.closeSync(s)}let i=n.lastIndexOf(10);if(i<0)return;let o=n.subarray(0,i).toString("utf-8").split(`
|
|
566
|
+
`)}`});if(t.credentials.length>0){let n=t.credentials.map(s=>`${s.name} (${dAr[s.purpose]}${s.required?"":", optional"})`);r.push(`- Secrets the workflow provides as environment variables: ${n.join(", ")} \u2014 the recipe reads each by exactly that variable name.`)}return r}var Wv=$(require("fs")),VV=$(require("path"));function zge(t,e){let{value:r,error:n}=Yr(t);if(n)return{errors:[n]};let s=e&&!e.testEnvironment?pAr(r,e):r,i=ev(s)&&s.schemaVersion===void 0?{schemaVersion:1,...s}:s,{value:o,errors:a}=tv(C_,$me,i);return o?{onboard:o,errors:[]}:{errors:a}}function pAr(t,e){if(!ev(t))return t;let{environment:r,...n}=t,s=[...e.repositorySlug?[{slug:e.repositorySlug,path:e.repositoryPath}]:[],...(e.relatedRepos??[]).map(a=>({slug:a.slug,path:a.path}))],i=a=>typeof a=="string"?s.find(c=>Ja(c.path,a))?.slug:void 0,o=Array.isArray(n.components)?n.components.map(a=>{if(!ev(a))return a;let{deployed:c,...l}=a;if(l.repository!==yn)return l;let u=ev(l.from)?l.from.file:void 0,d=i(u)??s[0]?.slug;return d?{...l,repository:d}:l}):n.components;return{...n,components:o}}var jV=".skyramp/sut/health.json",mAr={[jV]:`${jV} (with a url or command)`,".skyramp/workspace.yml":".skyramp/workspace.yml (create it with skyramp_init_scan and skyramp_init_workspace)"};function Zut(){return{name:"onboard-recipe",verify(t,e){let{onboard:r,errors:n}=zge(e.stdout,t.inputs);if(!r)return Re(this.name,n,{fatal:!0});let s=r.environment!==void 0;if(r.status==="blocked")return{name:this.name,passed:!0};let i=t.inputs.repositoryPath,o=Jc(i),a=s?QR.filter(u=>Ja(i,u)):[];if(a.length>0)return Re(this.name,[`an answer with "environment" tests a deployment where it runs and never starts or stops it: delete ${a.join(" and ")}, keep the health check, and answer "ready" again`]);let l=(s?Jme:Yme).filter(u=>!Ja(i,u)).map(u=>mAr[u]??u);return Ja(i,jV)&&!o.healthHint&&l.push(`${jV} (with a url or command)`),o.present&&l.length===0?{name:this.name,passed:!0}:Re(this.name,[`status is "ready" but the recipe deploy replays is incomplete in ${t.inputs.repositoryPath} \u2014 missing (each must be a regular file, not a symlink): ${l.join(", ")}. Write the missing files as the skill specifies and answer "ready" again, or answer "blocked" with the blocker that stopped you.`])}}}function edt(t,e,r=process.env){let n=[...t.components.flatMap(s=>s.credentials??[]),...t.environment?.credentials??[]];return[...new Set(n)].filter(s=>e.includes(s)&&!r[s])}function tdt(t,e){let r=t.components.filter(s=>s.credentials?.some(i=>e.includes(i))).map(s=>s.name),n=e.join(", ");return{component:(r.length>0?r:t.components.map(s=>s.name)).join(", ")||"SUT",problem:`${n} ${e.length===1?"has":"have"} no value in this setup`,evidence:`The workflow supplies ${e.length===1?"it":"each"} from a GitHub Actions secret, which is missing or empty.`,fix:`Set that secret in the workflow host's repository, or choose the secret that supplies ${e.length===1?"it":"each"} under Credentials, then run setup again.`}}function rdt(){return{name:"deployed-revisions",async verify(t,e,r,n){let s={name:this.name,passed:!0},i=t.checkDeployedRevisions;if(!i)return s;let{onboard:o}=zge(e.stdout,t.inputs);if(!o?.environment||o.status==="blocked")return s;let a=Qw(oO(t.inputs.repositoryPath).recipeFiles);if(!a)return s;let c=o.components.map(({name:d,repository:p})=>({name:d,repository:p})),{blockers:l}=await i(a.content,c,o.environment.credentials);if(l.length===0)return s;let u=l.map(d=>`${d.component}: ${d.problem} (${d.evidence})`).join("; ");return n?.retryLeft?Re(this.name,[`Testbot ran ${$a} twice, with GH_TOKEN, and it failed the check the setup's plan must pass: ${u}. Your session has no GH_TOKEN, so the part that reads GitHub ran in full only there. Fix the script so each component a repository builds gets the full commit it runs, the same on each run, from its own repository, then answer "ready" again, or answer "blocked" with the blocker that stops you.`]):{...s,details:`${$a} still fails Testbot's check, so the plan is saved blocked: ${u}`}}}}function fAr(t){try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t)}catch{return}}function oO(t){let e=[],r=o=>{let a;try{a=Wv.readdirSync(VV.join(t,o),{withFileTypes:!0})}catch{return}for(let c of a.sort((l,u)=>l.name.localeCompare(u.name))){let l=VV.posix.join(o,c.name);c.isDirectory()&&!c.name.startsWith(".")?r(l):c.isFile()&&e.push(l)}};Ja(t,".skyramp/sut",{directory:!0})&&r(".skyramp/sut"),Ja(t,".skyramp/workspace.yml")&&e.push(".skyramp/workspace.yml");let n=[],s=[],i=0;for(let o of e){let a=Ja(t,o);if(!a)continue;let l=Wv.statSync(a).size;if(l>Ow){s.push({path:o,reason:`larger than ${Ow} bytes`});continue}if(i+l>Mw){s.push({path:o,reason:`recipe text over ${Mw} bytes in total`});continue}let u=fAr(Wv.readFileSync(a));if(u===void 0||BG.test(u)){s.push({path:o,reason:"not text"});continue}n.push({path:o,content:u}),i+=l}return{recipeFiles:n,recipeFilesOmitted:s}}function ndt(t,e){let{onboard:r,errors:n}=zge(e.stdout,t.inputs),s=r&&{...r,...oO(t.inputs.repositoryPath)};return tr(t,"onboard",Xr(s,t.secretValues??[]),n)}function WV(t){if(t.state.stages.onboard?.status==="passed")return ae(t,"onboard.json")}var ws=$(require("fs")),km=$(require("path"));var ddt=require("child_process"),pdt=require("crypto"),po=$(require("fs")),od=$(require("path"));var sdt=$(require("fs")),by=$(require("path"));var Gge={"application/pdf":"PDF","text/csv":"CSV","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX"},idt=t=>Gge[t].toLowerCase(),ga=t=>new Map((t??[]).flatMap(e=>e.file?[[qa(e.key),e.file.name]]:[])),odt=10*1024*1024,yx=t=>t?.mediaType==="application/vnd.openxmlformats-officedocument.wordprocessingml.document"||t?.mediaType==="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",adt=(t,e)=>by.join(by.dirname(t),`${by.basename(t,by.extname(t))}${e}`),bx=t=>adt(t,".extracted.txt");function jge(t){try{return/\S/.test(sdt.readFileSync(bx(t),"utf-8"))}catch{return!1}}var Vge=t=>adt(t,".quotes.txt");function cdt(t){return yx(t.file)?bx(t.path):t.file?.mediaType==="application/pdf"?Vge(t.path):t.path}function YV(t){return t.map(e=>e.state!=="read"||!yx(e.file)||jge(e.path)?e:{...YA(e),file:e.file,state:"not_read",reason:"cannot_open"})}var hAr=10*6e4;function mdt(t,e){return t.getTime()-e.getTime()-hAr}var ldt="This attempt revoked its scoped GitHub credentials; it mints no more.",gAr=10*6e4,AAr=3e4,yAr=3,uo=class extends Error{constructor(r,n,s){super(r);this.status=n;this.code=s}status;code},Yv=class extends Error{};function Jge(t){let e;try{e=new URL(t)}catch{throw new Error(`skyrampAppOrigin "${t}" is not a URL`)}if(e.protocol!=="https:"||e.origin!==t.replace(/\/+$/,""))throw new Error(`skyrampAppOrigin must be an https origin, got "${t}"`);return e.origin}function bAr(t,e){if(!qR.test(t))throw new Error(`The ${e} "${t}" is not a uuid`);return t}function Kge(t,e){return`${t.replace(/\/+$/,"")}/runs/${e}`}function fdt(t,e,r){throw e<500&&e!==429?new uo(t,e,r):new Yv(t)}async function hdt(t,e,r,n){let s=Jge(t.origin),i;for(let o=1;o<=yAr;o+=1){o>1&&await new Promise(a=>setTimeout(a,(t.retryDelayMs??2e3)*(o-1)));try{let a=await t.idToken(s),c=await(t.fetch??fetch)(new URL(e,s).toString(),{...r(a),redirect:"error",signal:AbortSignal.timeout(AAr)}).catch(l=>{throw new Yv(l instanceof Error?l.message:String(l),{cause:l})});return await n(c)}catch(a){if(a instanceof uo)throw a;i=a}}throw i}function gdt(t,e,r,n){return hdt(t,r,i=>({method:e,headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json",Accept:"application/json"},body:e==="GET"?void 0:JSON.stringify(n)}),async i=>{let o=await i.json().catch(()=>({}));if(i.ok)return o.data;let a=o.error?.fields,c=typeof a?.path=="string"&&typeof a.reason=="string"?` at ${a.path}: ${a.reason}`:"",l=`The Skyramp app refused ${e} ${r}: ${i.status} ${o.error?.code??"no error code"}${c}`;return fdt(l,i.status,o.error?.code)})}function EAr(t,e,r){return hdt(t,e,s=>({method:"GET",headers:{Authorization:`Bearer ${s}`,Accept:"application/octet-stream"}}),async s=>{if(!s.ok)return fdt(`The Skyramp app refused GET ${e}: ${s.status}`,s.status);let i=Buffer.from(await s.arrayBuffer());if(i.length>r)throw new uo(`The Skyramp app answered GET ${e} with more than ${r} bytes`,s.status);return i})}var Wge=class{constructor(e,r,n,s,i,o,a,c,l){this.attemptId=e;this.attemptNumber=r;this.deadlineAt=n;this.manifest=s;this.deps=i;this.license=o;this.requestedBy=a;this.writeAllowed=c;this.claudeCodeVersion=l}attemptId;attemptNumber;deadlineAt;manifest;deps;license;requestedBy;writeAllowed;claudeCodeVersion;budgetMs(e){return mdt(this.deadlineAt,e)}get skyrampRunUrl(){return Kge(Jge(this.deps.origin),this.manifest.runId)}send(e,r,n){return gdt(this.deps,e,r,n)}readBytes(e,r){return EAr(this.deps,e,r)}issuedTokens=[];closure;modelKey;credentials;revocation;async token(){if(this.revocation)throw new Error(ldt);let e=(this.deps.now??(()=>new Date))().getTime(),r=this.credentials,n=r&&await r.catch(()=>{});if(this.credentials!==r)return(await this.credentials).token;if(n&&n.expiresAt-e>=gAr)return n.token;if(this.revocation)throw new Error(ldt);let s=this.send("POST",`/api/v1/runner/attempts/${this.attemptId}/credentials`,{schemaVersion:1}).then(i=>{let o={...i,token:i.token??this.jobToken()};this.issuedTokens.push(o.token),this.deps.mask?.(o.token),!n&&o.anthropicApiKey&&(this.modelKey=o.anthropicApiKey,this.deps.mask?.(o.anthropicApiKey));let a=n?"Renewed":"Received";return i.token&&this.deps.log?.(`${a} scoped GitHub credentials; they expire at ${o.expiresAt}.`),{token:o.token,expiresAt:i.token?new Date(o.expiresAt).getTime():Number.POSITIVE_INFINITY}},i=>{if(!(i instanceof uo)||i.code!=="CREDENTIALS_UNAVAILABLE")throw i;let o=l=>[...new Set(l.map(u=>u.namespace))].join(", "),a=this.manifest.sources.map(l=>l.repository);if(new Set(a.map(l=>l.providerAccountId)).size>1)throw new uo(`${i.message}. The run's repositories are on more than one GitHub account (${o(a)}), which Skyramp does not support yet.`,i.status,i.code);let c=o([...a,this.manifest.execution.repository]);throw new uo(`${i.message}. Check the Skyramp GitHub App installation on ${c}: 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.`,i.status,i.code)});return this.credentials=s,(await s).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(e){return e.fetch??this.deps.fetch??fetch}revokeTokens(e={}){let r=e.host??Zr();return this.revocation??=r.revokeToken?this.revokeIssued(n=>r.revokeToken(n,this.sourceFetch(e))):Promise.resolve([]),this.revocation}async revokeIssued(e){let r=[...this.issuedTokens],n=Promise.all(r.map(o=>this.revokeOne(o,e)));await this.credentials?.catch(()=>{});let s=this.issuedTokens.filter(o=>!r.includes(o));return[...await n,...await Promise.all(s.map(o=>this.revokeOne(o,e)))].filter(o=>o!==void 0)}async revokeOne(e,r){try{await r(e);return}catch(n){return`token ${this.issuedTokens.indexOf(e)+1} of ${this.issuedTokens.length}: ${n instanceof Error?n.message:String(n)}`}}};async function Adt(t,e,r){bAr(t,"run id"),Jge(r.origin);let n=Nst(t,e),s=kst(await gdt(r,"POST",`/api/v1/runner/runs/${t}/attempts`,n));if(s.manifest.runId!==t)throw new Error(`The app answered the handshake of run ${t} with the manifest of another run (${s.manifest.runId})`);let i=s.manifest.sources.find(a=>a.repository.provider!==n.execution.provider);if(i)throw new Error(`The manifest of run ${t} names ${i.repository.namespace}/${i.repository.name} on ${i.repository.provider}, but this job runs on ${n.execution.provider}`);s.runToken&&r.mask?.(s.runToken);let o=s.runToken?{entitlements:s.entitlements??[],runToken:s.runToken}:void 0;return new Wge(s.attempt.id,s.attempt.number,new Date(s.attempt.deadlineAt),s.manifest,r,o,s.requestedBy??void 0,s.writeAllowed,s.claudeCodeVersion??void 0)}var wAr=6e4;async function ydt(t){return Ist.parse(await t.send("POST",`/api/v1/runner/attempts/${t.attemptId}/heartbeat`,{schemaVersion:1}))}async function bdt(t,e=()=>new Date){if(t.closure)return t.closure;let r=await ydt(t).then(n=>bfe(n,e())).catch(()=>null);return r&&(t.closure=r),r}function Edt(t,e,r={}){let n=!1,s,i=async()=>{try{let a=bfe(await ydt(t),(r.now??(()=>new Date))());a&&!n&&(n=!0,t.closure=a,e(a))}catch(a){a instanceof uo&&(n=!0)}n||o(r.intervalMs??wAr)},o=a=>{s=setTimeout(()=>{i()},a),s.unref?.()};return o(0),{stop(){n=!0,clearTimeout(s)}}}var xAr=10*6e4,SAr=(t,e,r)=>(0,ddt.execFileSync)("git",e,{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","pipe"],env:r??process.env,timeout:xAr}).trim(),CAr=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];async function wdt(t,e){let r=e.git??SAr,n=e.host??Zr(),s=e.cloneUrl??(c=>n.cloneUrl(c)),{sources:i}=t.manifest;for(let c of i){if(CAr.includes(c.reason)&&!c.change?.base)throw new Error(`${c.repository.namespace}/${c.repository.name} was selected as ${c.reason}, but its change names no base revision to compare it with`);if(c.change?.kind==="pull_request"&&!c.change.base)throw new Error(`${c.repository.namespace}/${c.repository.name} pull request ${c.change.number} names no base revision to compare it with`);n.checkSourceName(c.repository)}if(po.existsSync(e.workspace)&&po.lstatSync(e.workspace).isSymbolicLink())throw new Error(`The sources workspace ${e.workspace} is a symlink; refusing to clear it`);po.rmSync(e.workspace,{recursive:!0,force:!0});let o=new Map((t.manifest.baseline.sources??[]).map(c=>[B_(c.repository),c.revision])),a=[];for(let c of i){let{namespace:l,name:u}=c.repository,d=od.join(e.workspace,l,u);po.mkdirSync(d,{recursive:!0});let p={...process.env,GIT_TERMINAL_PROMPT:"0",...n.gitAuthEnv(await t.token())};r(d,["init","-q"]),r(d,["remote","add","origin",s(c.repository)]);let m=c.change?.base??c.compareWith,f=o.get(B_(c.repository)),h=m?.revision??(f!==c.revision?f:void 0);r(d,["fetch","-q","--no-tags","origin",c.revision,...h?[h]:[]],p);let b=m??(c.ref?{ref:c.ref,revision:f??c.revision}:null);b&&(r(d,["update-ref",`refs/remotes/origin/${b.ref}`,b.revision]),r(d,["symbolic-ref","refs/remotes/origin/HEAD",`refs/remotes/origin/${b.ref}`])),c.ref?r(d,["checkout","-q","-B",c.ref,c.revision]):r(d,["checkout","-q","--detach",c.revision]),a.push({repository:c.repository,revision:r(d,["rev-parse","HEAD"]),path:d,slug:`${l}/${u}`})}return a}async function xdt(t,e={}){let r=e.host??Zr(),n={token:()=>t.token(),fetch:t.sourceFetch(e)},s=[];for(let i of t.manifest.sources){if(i.change?.kind!=="pull_request")continue;let{namespace:o,name:a}=i.repository,c=`${o}/${a}`,l=i.change.number;try{s.push({repository:c,number:l,...await r.pullRequest(i.repository,l,n)})}catch(u){let d=u instanceof Error?u.message:String(u);s.push({repository:c,number:l,note:`could not be read: ${d}`})}}return s}async function Sdt(t,e,r,n={}){return(n.host??Zr()).commitLookup(e,r,{token:()=>t.token(),fetch:t.sourceFetch(n)})}function Cdt(t,e){let r=t.sources.find(s=>s.reason==="TRIGGER"&&s.change?.kind==="pull_request"),n=r&&e.find(s=>s.repository.providerRepositoryId===r.repository.providerRepositoryId);return n&&r.change?{repository:n.slug,path:n.path,number:Number(r.change.number)}:void 0}var IAr=[".skyramp/sut/setup.sh",".skyramp/workspace.yml"];function Idt(t){let e=t.find(r=>IAr.some(n=>po.existsSync(od.join(r.path,n))))??t[0];return{repositoryPath:e.path,repositorySlug:e.slug,relatedRepos:t.filter(r=>r!==e).map(r=>({slug:r.slug,path:r.path,writable:!0}))}}var RAr=y.object({tests:y.object({placements:y.array(y.unknown()).optional()}).passthrough().optional()}).passthrough(),vAr=y.object({repository:ife,testType:y.nativeEnum(Yw),directory:y.string()}).passthrough();function Rdt(t,e){let r=RAr.safeParse(t.settings.target??{}),n=[];for(let s of(r.success?r.data.tests?.placements:void 0)??[]){let i=vAr.safeParse(s);if(!i.success)continue;let{repository:o,testType:a}=i.data,c=e.find(d=>d.repository.provider===o.provider&&d.repository.providerRepositoryId===o.providerRepositoryId),l=i.data.directory.trim(),u=!l||od.isAbsolute(l)||l.split(/[\\/]/).includes("..");!c||u||n.push({repository:c.slug,testType:a,directory:l})}return n}var TAr=y.object({report:y.object({language:y.string()}).passthrough()}).passthrough();function Xge(t){let e=TAr.safeParse(t?.settings.target);return e.success?Uq(e.data.report.language):"en"}var NAr=y.object({environment:y.object({components:y.array(y.unknown()).optional(),dependencies:y.array(y.unknown()).optional()}).passthrough()}).passthrough(),kAr=y.object({name:y.string().min(1),provision:y.literal("existing"),url:y.string().min(1),repository:ife.optional(),revisionUrl:y.string().min(1).optional()}).passthrough(),PAr=y.object({name:y.string().min(1),url:y.string().nullable(),versionUrl:y.string().nullable(),notes:y.string().nullable()}).passthrough();function vdt(t,e){let r=NAr.safeParse(t.settings.target),n=r.success?r.data.environment:{},s=(n.components??[]).flatMap(a=>{let c=kAr.safeParse(a);if(!c.success)return[];let{name:l,url:u,repository:d,revisionUrl:p}=c.data;if(!d)return[{name:l,url:u}];let m=e.sources.find(f=>f.repository.provider===d.provider&&f.repository.providerRepositoryId===d.providerRepositoryId);return m?[{name:l,url:u,repository:`${m.repository.namespace}/${m.repository.name}`,expectedRevision:m.revision,...p?{revisionUrl:p}:{}}]:[{name:l,url:u,repository:`${d.provider} repository ${d.providerRepositoryId}`}]}),i=(n.dependencies??[]).flatMap(a=>{let c=PAr.safeParse(a);return c.success?[{name:c.data.name,url:c.data.url,versionUrl:c.data.versionUrl,notes:c.data.notes}]:[]});if(s.length===0&&i.length===0)return;let o=y.object({allowSharedEnvironmentMutation:y.boolean()}).passthrough().safeParse(t.settings.policy);return{components:s,dependencies:i,allowMutation:o.success&&o.data.allowSharedEnvironmentMutation}}var BAr=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);function udt(t,e){if(!BAr.has(t.reason))return{};let r=`${t.repository.namespace}/${t.repository.name}`,n=t.change?.kind==="pull_request"?t.change.number:void 0,s=n===void 0?void 0:e.find(a=>Pj(a.repository,r)&&a.number===n),i=s?.merged===!0?s.mergeCommit:void 0,o=i&&s?.mergedHead?{mergedHead:s.mergedHead}:{};return{touched:!0,acceptedRevisions:{frozen:t.revision,...i&&i!==t.revision?{mergeCommit:i,...o}:{}}}}function Tdt(t,e,r,n,s){let i=u=>r.sources.find(d=>Pj(`${d.repository.namespace}/${d.repository.name}`,u)),o=(t?.components??[]).map(u=>{let d=u.expectedRevision?i(u.repository):void 0;return d?{...u,...udt(d,s)}:u}),a=Qw(e.files)!==void 0,c=e.components.map(u=>{if(u.repository===yn)return{name:u.name,url:e.address};let d=i(u.repository),p=a?void 0:uhe(e,u.name);return{name:u.name,url:e.address,repository:u.repository,...d?{expectedRevision:d.revision}:{},...p?{revisionUrl:p}:{},...a?{revisionScript:!0}:{},...d?udt(d,s):{}}}),l=y.object({allowSharedEnvironmentMutation:y.boolean()}).passthrough().safeParse(n?.settings.policy);return{components:[...o,...c],dependencies:t?.dependencies??[],allowMutation:t?.allowMutation??(l.success&&l.data.allowSharedEnvironmentMutation)}}function Ndt(t){let e=r=>t.testResults.filter(n=>n.status===r).length;return{passed:e("Pass"),failed:e("Fail"),skipped:e("Skipped")}}function _Ar(t){let{passed:e,failed:r,skipped:n}=Ndt(t);return e+r===0?{sufficiency:"insufficient",rationale:n>0?`Every test was skipped (${n}), so nothing was validated.`:"No test ran, so nothing was validated.",gaps:["No test ran against the frozen sources."],acceptedEvidence:[],actionRequired:[]}:{sufficiency:"sufficient",rationale:`${e+r} tests ran against the frozen sources: ${e} passed, ${r} failed${n?`, ${n} skipped`:""}.`,gaps:[],acceptedEvidence:[],actionRequired:[]}}function DAr(t,e){let r=t.testResults.map(c=>({result:c,repository:c.repository??e,path:c.fileName||c.testType})),n=new Map;for(let c of r){let l=`${c.repository}:${c.result.testType}:${c.path}`;n.set(l,(n.get(l)??0)+1)}let s=r.map(({result:c,repository:l,path:u})=>{let d=(n.get(`${l}:${c.testType}:${u}`)??0)>1;return c.resultId??JG(l,c.testType,u,d&&c.endpoint||void 0)}),i=new Map;for(let c of s)i.set(c,(i.get(c)??0)+1);let o=new Set(s.filter(c=>i.get(c)===1)),a=r.map(({result:c,repository:l},u)=>{let d=s[u],p=d;if(i.get(d)>1&&o.has(d))for(let m=2;o.has(p)||p===d;m+=1)p=d.includes("#")?`${d}.${m}`:`${d}#${m}`;return o.add(p),{...c,repository:l,resultId:p}});return{...t,testResults:a,...OAr(t,a,e),validation:MAr(t,t.validation??_Ar(t)),traceVersion:1}}function OAr(t,e,r){if(!t.testExecutionContexts)return{};let n=new Set,s=a=>{let c=a;for(let l=2;n.has(c);l+=1)c=`${a}#${l}`;return n.add(c),c},i=[],o=new Map;for(let{repository:a,...c}of t.testExecutionContexts){let l=c.status==="not_run"?[]:e.filter(u=>u.fileName===c.test&&u.repository===(a?.trim()||r));l.length||i.push(c);for(let{resultId:u}of l){let d=o.get(u),p=d!==void 0&&i[d].cleanup.status==="failed"?i[d].cleanup:c.cleanup,m={...c,cleanup:p,test:u,resultId:u};d===void 0?o.set(u,i.push(m)-1):i[d]=m}}for(let a of i)a.resultId&&n.add(a.resultId);return{testExecutionContexts:i.map(a=>a.resultId?a:{...a,test:s(a.test.slice(0,512))}).slice(0,5e3)}}function MAr(t,e){let{passed:r,failed:n}=Ndt(t);return e.sufficiency!=="sufficient"||r+n>0||e.acceptedEvidence.length>0?e:{...e,sufficiency:"insufficient",gaps:["No test ran and no existing evidence was accepted, so nothing was validated."]}}async function kdt(t,e){let r=Wu([...t.issuedTokens,...e.secrets??[]]),n=Bst({manifest:t.manifest,attemptNumber:t.attemptNumber,checkedOut:e.sources.map(s=>({repository:s.repository,revision:s.revision})),generatedTests:Xr(e.delivery,r),producer:e.producer,report:Xr(DAr(e.report,e.workingSlug),r),githubWrites:e.githubWrites});await t.send("PUT",`/api/v1/runner/attempts/${t.attemptId}/report`,n)}async function Zge(t){let e=Sst.parse(await t.send("GET",`/api/v1/runner/attempts/${t.attemptId}/configuration`,void 0)),r=t.manifest.configuration,{configuration:n,capture:s}=e;if(n.captureId!==r.captureId||n.revision!==r.revision||n.hash!==r.hash||s.hash!==r.hash||Tst(s)!==r.hash)throw new Error("The app answered the configuration of another capture than the manifest names");return e}var Yge=class extends Error{};async function JV(t){let{runtimePlan:e,testEnvironment:r}=Cst.parse(await t.send("GET",`/api/v1/runner/attempts/${t.attemptId}/runtime-plan`,void 0));if(e&&Rst(e.files)!==e.contentHash)throw new Yge(`Stored SUT recipe version ${e.version} does not match its hash`);return{runtimePlan:e,testEnvironment:r??null}}async function Pdt(t,e,r=()=>{}){try{po.rmSync(e,{recursive:!0,force:!0})}catch{}let n=t.manifest.requirements??[];if(n.length===0&&!t.manifest.instructions)return{items:[],instructions:[]};let s,i=[];try{let a=mst.parse(await t.send("GET",`/api/v1/runner/attempts/${t.attemptId}/requirements`,void 0));s=new Map(a.items.map(c=>[Oc(c),c])),i=t.manifest.instructions?a.instructions??[]:[]}catch(a){let c=a instanceof Error?a.message:String(a);r(`Testbot V3: could not read the run's requirement items: ${c}`),s=new Map}try{po.mkdirSync(e,{recursive:!0,mode:448})}catch{}let o=[];for(let a of n){let c={...YA(a),..."fileName"in a?{file:{name:a.fileName,mediaType:a.mediaType}}:{}},l=s.get(Oc(c));if(!l)o.push({...c,state:"not_read",reason:Uw.test(c.key)?"cannot_open":"unavailable"});else if(l.state==="not_read")o.push({...c,state:"not_read",reason:l.reason});else if(!("text"in l))o.push(await QAr(t,e,c,a.contentHash,r));else{let u=od.join(e,Bdt(c));try{po.writeFileSync(u,l.text,{mode:384}),o.push({...c,state:"read",path:u,contentMatches:l.contentMatches,version:l.version})}catch(d){r(`Testbot V3: could not write the requirement item ${c.key}: ${d instanceof Error?d.message:String(d)}`),o.push({...c,state:"not_read",reason:"unavailable"})}}}return{items:o,instructions:i}}async function QAr(t,e,r,n,s){let i=c=>(s(`Testbot V3: could not open the uploaded document ${r.key}: ${c}`),{...r,state:"not_read",reason:"cannot_open"});if(!r.file)return i("the manifest names no file");let o;try{let c=cst.requirementFile.replace(":attemptId",t.attemptId).replace(":key",r.key);o=await t.readBytes(c,odt)}catch(c){return i(c instanceof Error?c.message:String(c))}if((0,pdt.createHash)("sha256").update(o).digest("hex")!==n)return i("its bytes do not match its hash");let a=od.join(e,Bdt(r));try{po.writeFileSync(a,o,{mode:384})}catch(c){return i(c instanceof Error?c.message:String(c))}return{...r,state:"read",path:a,contentMatches:!0,version:n}}function Bdt(t){let e=t.source==="other"?[]:[new URL(t.site).hostname],r=t.file?idt(t.file.mediaType):"txt";return`${[t.source,...e,t.key].join("-")}.${r}`}async function eAe(t,e){await t.send("POST",`/api/v1/runner/attempts/${t.attemptId}/progress`,hst.parse(e))}async function _dt(t,e){return yst.parse(await t.send("POST",`/api/v1/runner/attempts/${t.attemptId}/setup-events`,gst.parse(e)))}async function Ddt(t,e){await t.send("POST",`/api/v1/runner/attempts/${t.attemptId}/setup-checkpoint`,Est.parse(e))}async function Odt(t){return(await Qdt(t,"setup-checkpoint",wst))?.checkpoint??null}async function Mdt(t){return(await Qdt(t,"setup-context",xst))?.context??null}async function Qdt(t,e,r){try{return r.parse(await t.send("GET",`/api/v1/runner/attempts/${t.attemptId}/${e}`,void 0))}catch(n){if(n instanceof uo&&n.status===404)return null;throw n}}async function tAe(t,e){let r=Wu([...t.issuedTokens,...e.secrets??[]]),n=_st(t.manifest,t.attemptNumber,e.sources.map(s=>({repository:s.repository,revision:s.revision})),Xr(e.recipe,r),e.producer);await t.send("PUT",`/api/v1/runner/attempts/${t.attemptId}/sut-recipe`,n)}function Ldt(t,e,r,n=e[0].slug,s,i={}){let{record:o,entries:a}=Fdt(t,e,n),c=tu({outputsDir:t,state:QV(od.join(od.dirname(t),"state.json"))});if(!o&&Dj(i,r.system,c?.sutRequired).length>0)return{status:"none"};let l=f=>Udt(e,f),u=[],d=[];for(let{record:f,repository:h,number:b}of a)if(h&&b)u.push({repository:h,number:b});else if(h&&f.prFailure){let E=f.prDetail?`${f.prFailure}: ${f.prDetail}`:f.prFailure;d.push({repository:h,message:E,slug:f.repository??n})}else h&&f.committed&&d.push({repository:h,message:f.reason??"The tests were committed but no pull request was opened.",slug:f.repository??n});let p=new Set([...u,...d].map(({repository:f})=>f.providerRepositoryId)),m=[...new Set(r.newTestsCreated.map(f=>(f.repository??n).toLowerCase()))];for(let f of m){let h=l(f);h&&!p.has(h.providerRepositoryId)&&d.push({repository:h,message:s??"Generated tests were not proposed in a pull request.",slug:f})}return u.length&&d.length?{status:"partial",pullRequests:u,failures:d.map(({repository:f,message:h})=>({repository:f,message:h}))}:u.length?{status:"delivered",pullRequests:u}:d.length?{status:"failed",message:o?.deliveries?d.map(f=>`${f.slug}: ${f.message}`).join("; "):d[0].message}:r.newTestsCreated.length>0?{status:"failed",message:s??"Generated tests were not proposed in a pull request."}:{status:"none"}}function Udt(t,e){let r=t.find(n=>n.slug.toLowerCase()===e.toLowerCase());return r&&{provider:r.repository.provider,providerAccountId:r.repository.providerAccountId,providerRepositoryId:r.repository.providerRepositoryId}}function Fdt(t,e,r){let n=od.join(t,"deliver.json"),s=po.existsSync(n)?JSON.parse(po.readFileSync(n,"utf-8")):void 0,i=s?.deliveries??(s?[s]:[]);return{record:s,entries:i.map(o=>({record:o,repository:Udt(e,o.repository??r),number:/\/pull\/([1-9][0-9]*)$/.exec(o.prUrl??"")?.[1]}))}}function $dt(t,e,r=e[0].slug){let n=new Map,s=(i,o)=>{ufe.safeParse(i).success&&n.set(`${i.kind}:${i.repository.providerRepositoryId}:${o}`,i)};for(let{record:i,repository:o,number:a}of Fdt(t,e,r).entries){if(!o||!i.branch)continue;let c=i.pushedCommits??(i.pushed&&i.commitSha?[i.commitSha]:[]);for(let u of c)s({kind:"branch_pushed",repository:o,branch:i.branch,commit:u},`${i.branch}:${u}`);if(!a)continue;let l=i.prAction==="retargeted"?i.retargetedAs??"created":i.prAction;l==="created"?s({kind:"pull_request_opened",repository:o,number:a,branch:i.branch},a):(l==="updated"||l==="unchanged")&&s({kind:"pull_request_edited",repository:o,number:a,branch:i.branch},a)}return[...n.values()].slice(0,lfe)}function qdt(t,e){return t.credentials.filter(r=>r.required&&!e[r.name]).map(r=>r.name)}var rAe=[/\bgh[pousr]_[A-Za-z0-9]{36,}/g,/\bgithub_pat_[A-Za-z0-9_]{22,}/g,/\bsk-ant-[A-Za-z0-9_-]{20,}/g,/\bsk-[A-Za-z0-9]{32,}/g,/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g],Hdt=t=>rAe.some(e=>new RegExp(e.source).test(t));var Oh=".skyramp/setup-events.ndjson",aO=".skyramp/setup-left-out.json",cO=".skyramp/setup-inbox.json",nAe=".skyramp/setup-inbox-read.json",eW=".skyramp/setup-hook-ran",LAr=6e4,UAr=5e3,FAr=300,ri=t=>{let e=typeof t=="string"?t:typeof t=="number"?String(t):"";return e.trim()==="null"?"":e},KV=t=>Array.isArray(t)?t:[],ZV=(t,e)=>Object.values(t).find(r=>r===ri(e).trim().toLowerCase()),$Ar={running:"up",healthy:"up",ready:"up",started:"up",building:"starting",pending:"starting",installing:"starting",skipped:"out_of_scope",excluded:"out_of_scope","out-of-scope":"out_of_scope"},qAr=t=>ZV(Q_,t)??$Ar[ri(t).trim().toLowerCase()]??"found",zdt=t=>y.string().uuid().safeParse(t).success,HAr=t=>XG.test(t)?t:t.replace(/[^A-Za-z0-9_-]+/g,"-").slice(0,64).replace(/^-+|-+$/g,"")||"question",zAr=/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/,GAr=/github\.com[/:]([^/\s]+)\/([^/\s?#]+?)(?:\.git)?(?:[/?#]|$)/i;function jAr(t){if(t.kind!=="question"||t.placeholder===void 0)return t;let{placeholder:e,...r}=t;return r}var Gdt=new RegExp(Afe.source,"g"),tW=class{constructor(e,r,n){this.checkout=e;this.send=r;this.opts=n}checkout;send;opts;offset=0;sequence=1;pending=[];started=!1;closed=!1;capped=!1;flushing=0;emptyRefused=!1;placeholderRefused=!1;unreadSince;saidHookSilent=!1;timer;queue=Promise.resolve();phase="discover";messageIds=new Set;stopHeard=!1;start(){if(!this.timer){if(!this.started){this.started=!0;let e=km.join(this.checkout,Oh);ws.mkdirSync(km.dirname(e),{recursive:!0}),ws.writeFileSync(e,"");for(let r of[aO,cO,nAe,eW])ws.rmSync(km.join(this.checkout,r),{force:!0})}this.timer=setInterval(()=>{this.flushing===0&&this.flush()},this.opts.intervalMs??UAr),this.timer.unref?.()}}async stop(){this.timer&&clearInterval(this.timer),this.timer=void 0,await this.flush()}flush(){return this.flushing+=1,this.queue=this.queue.then(()=>this.drain()).catch(e=>this.opts.warn(`Testbot V3: could not send setup events: ${XV(e)}`)).finally(()=>{this.flushing-=1}),this.queue}async drain(){if(!this.closed){if(this.collect(),this.pending.length===0&&!this.emptyRefused){await this.sendBatch([]);return}for(;this.pending.length>0&&!this.closed;){let e=this.pending.slice(0,HR);if(await this.sendBatch(e)==="unanswered")return;this.pending.splice(0,e.length)}}}async sendBatch(e){this.placeholderRefused&&(e=e.map(jAr));let r;try{r=await this.send({schemaVersion:1,events:e})}catch(n){if(n instanceof uo&&n.code==="RUN_CLOSED")return this.closed=!0,this.pending=[],"done";if(n instanceof uo&&e.length===0)return this.emptyRefused=!0,"done";if(n instanceof uo){if(e.length>1){for(let i of e){if(this.closed)return"done";if(await this.sendBatch([i])==="unanswered")return"unanswered"}return"done"}if(e[0].kind==="question"&&e[0].placeholder!==void 0)return this.placeholderRefused=!0,this.sendBatch(e);let s=e[0].kind==="log"?void 0:VAr(e[0]);return s?(this.opts.warn(`Testbot V3: the app refused setup event ${e[0].sequence}, so it is sent as a log line: ${n.message}`),this.sendBatch([{sequence:e[0].sequence,at:e[0].at,kind:"log",phase:this.phase,text:s}])):(this.opts.warn(`Testbot V3: the app refused setup event ${e[0].sequence}, so it is dropped: ${n.message}`),"done")}return n instanceof y.ZodError?(this.opts.warn(`Testbot V3: the app's answer to setup events was not understood: ${n.issues[0]?.message}`),"done"):(this.opts.warn(`Testbot V3: could not send setup events, trying again: ${XV(n)}`),"unanswered")}try{this.writeLeftOut(r.leftOut)}catch(n){this.opts.warn(`Testbot V3: could not write ${aO}: ${XV(n)}`)}try{this.writeInbox(r.messages??[])}catch(n){this.opts.warn(`Testbot V3: could not write ${cO}: ${XV(n)}`)}return r.stop&&!this.stopHeard&&(this.stopHeard=!0,this.opts.onStop?.(r.stop.key)),"done"}collect(){if(this.capped)return;let e=km.join(this.checkout,Oh),r;try{r=ws.statSync(e).size}catch{return}if(r<this.offset&&(this.offset=0),r===this.offset)return;let n=Buffer.alloc(r-this.offset),s=ws.openSync(e,"r");try{ws.readSync(s,n,0,n.length,this.offset)}finally{ws.closeSync(s)}let i=n.lastIndexOf(10);if(i<0)return;let o=n.subarray(0,i).toString("utf-8").split(`
|
|
567
567
|
`);this.offset+=i+1;for(let a of o){if(a.trim()==="")continue;if(this.sequence>KG){this.opts.warn(`Testbot V3: the setup sent ${KG} events, the most a run may; the rest are not sent.`),this.capped=!0;return}let c=this.toEvent(a);c&&(this.pending.push(c),this.sequence+=1)}}toEvent(e){let r;try{r=JSON.parse(e)}catch{r=void 0}let n=r!==null&&typeof r=="object"&&!Array.isArray(r)?r:void 0,s=this.opts.secrets(),i=(m,f=1/0)=>rAe.reduce((b,E)=>b.replace(E,I_),Dr(m,s)).replace(Gdt," ").trim().slice(0,f).replace(Gdt," ").trim(),o=m=>i(i(m).replace(/\s+/g," "),FAr),a={sequence:this.sequence,at:(this.opts.now?.()??new Date).toISOString()};if(!n)return this.asLog(a,o(e),"a setup event line that is not one JSON event");let c=this.putRight(n,a,i,o),l=c?yfe.safeParse(c):void 0;if(l?.success)return l.data.kind==="log"&&(this.phase=l.data.phase),l.data;let u=l&&!l.success?` (${l.error.issues[0]?.path.join(".")}: ${l.error.issues[0]?.message})`:"",d=KV(n.names).map(ri).filter(Boolean),p=o(ri(n.text)||[ri(n.name),ri(n.status)].filter(Boolean).join(": ")||(d.length?`Needs credentials: ${d.join(", ")}`:""))||o(e);return this.asLog(a,p,`a setup event the app would refuse${u}`)}putRight(e,r,n,s){let i=ZV(sfe,e.kind);if(i==="log")return{...r,kind:i,phase:ZV(FR,e.phase)??this.phase,text:s(ri(e.text))};if(i==="component"){let o=n(ri(e.file),hfe)||null,a=n(ri(e.version),ffe);return{...r,kind:i,name:n(ri(e.name),__),repository:this.repositoryOf(n(ri(e.repository)),o),file:o,status:qAr(e.status),...a&&{version:a}}}if(i==="reply")return{...r,kind:i,to:this.messageIdOf(ri(e.to).trim()),accepted:e.accepted!==!1,text:s(ri(e.text))};if(i==="question"){let o=[...new Set(KV(e.choices).map(d=>n(n(ri(d)).replace(/\s+/g," "),pfe)).filter(Boolean))].slice(0,dfe),a=ZV(VG,e.type)??"free_text";o.length===0&&(a="free_text");let c=ri(e.text);a==="free_text"&&o.length>0&&([c,o]=[`${c} (${o.join(", ")})`,[]]);let l=ri(e.id).trim(),u=n(ri(e.placeholder)).replace(/\s+/g," ");return{...r,kind:i,id:HAr(l),type:a,text:s(c),component:n(ri(e.component),__)||null,choices:o,...u&&u.length<=mfe&&{placeholder:u}}}if(i==="credentials"){let o=[...new Set(KV(e.names).map(a=>ri(a).trim().toUpperCase()).filter(a=>WA.test(a)))].slice(0,gfe);return{...r,kind:i,names:o}}if(i==="delivered")return{...r,kind:i,ids:[...new Set(KV(e.ids).map(o=>this.messageIdOf(ri(o).trim())).filter(zdt))]}}repositoryOf(e,r){let n=this.opts.repositories??[],s=c=>n.find(l=>l.slug.toLowerCase()===c.toLowerCase())?.slug;if(zAr.test(e)){let c=s(e);if(c||n.length===0)return c??e}if(e===yn&&this.opts.shared)return yn;let i=GAr.exec(e);if(i){let c=`${i[1]}/${i[2]}`,l=s(c);if(l||n.length===0)return l??c}let o=n.find(c=>c.slug.split("/").pop()?.toLowerCase()===e.toLowerCase());if(o)return o.slug;let a=r?n.find(c=>ws.existsSync(km.join(c.path,r))):void 0;return a?a.slug:this.opts.shared?yn:n[0]?.slug??e}messageIdOf(e){if(zdt(e))return e;let r=[...this.messageIds],n=e?r.filter(s=>s.startsWith(e.toLowerCase())||e.toLowerCase().includes(s)):[];return n.length===1?n[0]:r.length===1?r[0]:e}asLog(e,r,n){if(!r){this.opts.warn(`Testbot V3: left out ${n}: it says nothing.`);return}return this.opts.warn(`Testbot V3: sent ${n} as a log line.`),{...e,kind:"log",phase:this.phase,text:r}}writeInbox(e){for(let s of e)this.messageIds.add(s.id);let r=km.join(this.checkout,cO);if(ws.writeFileSync(`${r}.tmp`,`${JSON.stringify(e)}
|
|
568
568
|
`),ws.renameSync(`${r}.tmp`,r),e.length===0||ws.existsSync(km.join(this.checkout,eW))){this.unreadSince=void 0;return}let n=(this.opts.now?.()??new Date).getTime();this.unreadSince??=n,!this.saidHookSilent&&n-this.unreadSince>=LAr&&(this.saidHookSilent=!0,this.opts.warn("Testbot V3: people sent this setup messages, but the session's setup hook has not run, so they do not reach it."))}writeLeftOut(e){let r=km.join(this.checkout,aO);ws.writeFileSync(`${r}.tmp`,`${JSON.stringify(e)}
|
|
569
569
|
`),ws.renameSync(`${r}.tmp`,r)}},XV=t=>t instanceof Error?t.message:String(t);function VAr(t){return t.kind==="component"?`${t.name}: ${t.status}`:t.kind==="reply"||t.kind==="question"||t.kind==="log"?t.text:t.kind==="credentials"?`Needs credentials: ${t.names.join(", ")}`:""}var rW=$(require("fs")),jdt=$(require("path"));var WAr=600,YAr=5*6e4,JAr=30,KAr="From the Setup page: a person sent this setup the messages below, each one's text in quotes. Use what they say to set up the SUT, as the setup rules say, and never put repository content, environment values or credentials in a setup event for it. A message is newer than the SUT notes: where they differ, follow the message. Before anything else, write a reply line for each instruction (setup events): what you will do differently, or accepted false only when it is not about setting up the SUT or breaks a setup rule. Then act on it, redoing only the steps it changes. An answer is to the question it names; go on with what it unblocks.",XAr=`// Skyramp Testbot: hands a running setup the Setup page's messages (SKYR-4843). Written by the runner.
|
package/dist/post.js
CHANGED
|
@@ -222,7 +222,7 @@ ${o.map((c,l)=>{let u=i[c],d=u.isOptional()?" (optional)":"",p=u.description?`
|
|
|
222
222
|
`)}
|
|
223
223
|
${$ke(t)}}`}case"ZodArray":{let i=n.element;return`[ ${YI(i,t,r)}, \u2026 ]`}case"ZodEnum":return n.options.map(i=>JSON.stringify(i)).join(" | ");case"ZodNativeEnum":return Object.values(n.enum).map(i=>JSON.stringify(i)).join(" | ");case"ZodLiteral":return JSON.stringify(n.value);case"ZodString":return'"\u2026"';case"ZodNumber":return"<number>";case"ZodBoolean":return"true | false";case"ZodNull":return"null";case"ZodUnion":return n.options.map(i=>YI(i,t,r)).join(" | ");case"ZodRecord":return`{ "<key>": ${YI(n.valueSchema,t,r)} }`;default:return"<value>"}}function Gbt(e){let t=e;for(;;){let r=t._def;if(r.typeName==="ZodOptional"||r.typeName==="ZodNullable"||r.typeName==="ZodDefault"){if(r.typeName==="ZodNullable")return g.union([r.innerType,g.null()]);t=r.innerType}else if(r.typeName==="ZodEffects")t=r.schema;else return t}}function Hbt(e){return e.issues.map(t=>{let r=t.path.map(s=>typeof s=="number"?`[${s}]`:`.${s}`).join("").replace(/^\./,""),n=r||"output";if(!/^(Expected |Required$|Invalid |String must|Array must|Number must)/.test(t.message))return`${n} ${t.message}`;switch(t.code){case"invalid_type":return r?t.expected==="object"?`${n} must be an object`:t.received==="undefined"?`${n} is required`:`${n} must be ${t.expected}, got ${t.received}`:"output is not a JSON object";case"invalid_enum_value":{let s=JSON.stringify(t.received),i=t.options.find(a=>typeof a=="string"&&typeof t.received=="string"&&t.received.startsWith(a)),o=i?` \u2014 you sent ${s}; the value must be exactly ${JSON.stringify(i)}, with any qualifier moved to a field that takes free text`:` \u2014 you sent ${s}`;return`${n} must be one of: ${t.options.join(", ")}${o}`}case"invalid_literal":return`${n} must be ${JSON.stringify(t.expected)}`;case"too_small":return t.type==="string"?`${n} must be a non-empty string`:`${n} must have at least ${t.minimum} item(s)`;case"unrecognized_keys":return`${n} has unknown key(s): ${t.keys.join(", ")}`;default:return`${n}: ${t.message}`}})}function _r(e,t){let r=e.safeParse(t);if(r.success)return{value:r.data,errors:[]};let n=(i,o)=>o.reduce((a,c)=>a&&typeof a=="object"?a[c]:void 0,i),s=r.error.issues.filter(i=>i.path.length&&n(t,i.path)===null);if(s.length===r.error.issues.length)try{let i=e.safeParse(s.reduce((o,{path:a})=>qke(o,a),t));if(i.success)return{value:i.data,errors:[]}}catch{}return{errors:Hbt(r.error)}}function qke(e,t){if(!t.length||!e||typeof e!="object")return e;let[r,...n]=t,s=Array.isArray(e)?e.slice():{...e};return n.length?s[r]=qke(s[r],n):delete s[r],s}function AE(e,t,r){let n=_r(e,r),s=r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,i=[...n.errors,...s?t(s):[]];return i.length?{errors:i}:{value:n.value,errors:[]}}var Gke=z(require("path"));var c4="outputs/preflight.json",xm="pr-diff.txt";function Va(e,t){return[...e.changedFiles.map(r=>({repository:t,path:r.path})),...(e.relatedChanges??[]).flatMap(r=>r.changedFiles.map(n=>({repository:r.repository,path:n.path})))]}function yE(e,t,r){return e.some(n=>n.path===r&&n.repository.toLowerCase()===t.toLowerCase())}function Ir(e){if(e.outputsDir)return yl(Gke.join(e.outputsDir,"preflight.json"))}var nQ=z(require("path"));var jke=require("child_process"),eQ=z(require("fs")),EE=z(require("path"));Wu();var tQ="ci-evidence.json",ZP=(e,t)=>(0,jke.execFileSync)("git",t,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim(),jbt=/^Merge ([0-9a-f]{40}) into [0-9a-f]{40}$/;function zbt(e){try{let t=ZP(e,["rev-parse","HEAD"]);if(ZP(e,["rev-list","--parents","-n","1","HEAD"]).split(/\s+/).slice(1).length===2){let n=jbt.exec(ZP(e,["log","-1","--format=%s","HEAD"]));if(n)return n[1]}return t}catch{return}}function rQ(e){let t="";try{t=ZP(e,["remote","get-url","origin"])}catch{}let r=/[:/]([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+?)(?:\.git)?\/?$/.exec(t);return r&&!t.startsWith("/")&&!t.startsWith(".")?`${r[1]}/${r[2]}`:`local/${EE.basename(EE.resolve(e)).replace(/[^A-Za-z0-9._-]/g,"-")||"repo"}`}var Vbt=new Set(Object.values(zp));function Wbt(e){let t=[];for(let r of e??[]){let n=r.trim();if(!n)continue;let s=n.lastIndexOf("="),i=s>0?n.slice(s+1).trim():"",o=Vbt.has(i),c=(o?n.slice(0,s).trim():n).split("*").map(l=>l.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");t.push({pattern:new RegExp(`^${c}$`,"i"),kind:o?i:"ci_check"})}return t}var Ybt=new Set(["failure","timed_out","action_required","error","startup_failure"]);function Hke(e,t){let r=new Map(t.revisions.map(s=>[s.repository.toLowerCase(),s])),n=[];for(let s of e){if(s.name.startsWith(dE))continue;let i=r.get((s.repository??t.primary).toLowerCase());if(!i)continue;let o=t.trusted.find(l=>l.pattern.test(s.name)),a=s.conclusion??s.status,c=o?s.headSha.toLowerCase()!==i.revision.toLowerCase()?"stale":s.status!=="completed"?"pending":s.conclusion==="success"?"accepted":Ybt.has(s.conclusion??"")?"failing":"inconclusive":"untrusted";n.push({id:`ci-${n.length+1}`,repository:i.repository,revision:i.revision,checkSha:s.headSha,name:s.name,kind:o?.kind??"ci_check",status:c,conclusion:a,reference:s.url||`${i.repository}@${s.headSha.slice(0,12)} ${s.name}`,summary:(s.summary||`${s.name}: ${a}`).slice(0,300)})}return n}var Jbt=g.object({checks:g.array(g.object({repository:g.string().optional(),name:g.string().min(1),headSha:g.string().regex(/^[0-9a-f]{40}$|^[0-9a-f]{64}$/i),status:g.string().default("completed"),conclusion:g.string().nullable().optional(),url:g.string().optional(),summary:g.string().optional()}))});function Kbt(e){let t=Jbt.safeParse(JSON.parse(eQ.readFileSync(e,"utf-8")));if(!t.success)throw new Error(`${e} is not a CI evidence file: ${t.error.issues[0]?.message??"invalid"}`);return t.data.checks}function Xbt(e){let t=[{path:e.inputs.repositoryPath,slug:e.inputs.repositorySlug},...(e.inputs.relatedRepos??[]).map(n=>({path:n.path,slug:n.slug}))],r=[];for(let n of t){let s=zbt(n.path);s&&r.push({repository:n.slug??rQ(n.path),revision:s})}return r}async function zke(e){let t=Xbt(e),r=t[0]?.repository??rQ(e.inputs.repositoryPath),n=Wbt(e.inputs.trustedChecks),s;try{if(e.inputs.ciEvidenceFile){let i=Kbt(e.inputs.ciEvidenceFile);s={source:"file",revisions:t,items:Hke(i,{revisions:t,primary:r,trusted:n})}}else if(e.platform?.listCommitChecks){let i=[];for(let o of t)i.push(...await e.platform.listCommitChecks(o)??[]);s={source:"platform",revisions:t,items:Hke(i,{revisions:t,primary:r,trusted:n})}}else s={source:"none",revisions:t,items:[],note:"this platform keeps no CI results"}}catch(i){s={source:"none",revisions:t,items:[],note:`CI results could not be read: ${i instanceof Error?i.message:String(i)}`}}return s.items.length>0&&n.length===0&&(s.note="no trustedChecks were configured, so no CI result counts as evidence"),eQ.writeFileSync(EE.join(e.outputsDir,tQ),JSON.stringify(s,null,2)+`
|
|
224
224
|
`),s}var l4=8e3,u4=new Map;function Zbt(e){return e.repositorySlug?e.repositorySlug:(u4.has(e.repositoryPath)||u4.set(e.repositoryPath,rQ(e.repositoryPath)),u4.get(e.repositoryPath))}function je(e){return[{slug:Zbt(e),path:e.repositoryPath,writable:!0,working:!0},...(e.relatedRepos??[]).map(t=>({slug:t.slug,path:t.path,writable:t.writable===!0,working:!1}))]}function nn(e){return je(e)[0]}function sQ(e,t){return[...je(e)].sort((r,n)=>n.path.length-r.path.length).find(r=>{let n=nQ.relative(r.path,t);return!n.startsWith("..")&&!nQ.isAbsolute(n)})}var iQ=(e,t)=>e.toLowerCase()===t.toLowerCase();function vm(e,t){return t?.trim()?e.find(r=>iQ(r.slug,t.trim())):e[0]}function sr(e,t){return vm(je(e),t)}var Vke=(e,t)=>`${t} is not a repository of this run (${je(e).map(r=>r.slug).join(", ")})`;function sn(e,t){let r=sr(e,t);if(!r)throw new Error(Vke(e,t));return r.path}function El(e,t){let r=sr(e,t);return r?r.writable?{source:r}:{error:`${r.slug} is read-only in this run: tests are written only to ${je(e).filter(n=>n.writable).map(n=>n.slug).join(", ")}`}:{error:Vke(e,t)}}function Xe(e,t){return d4(je(e),t)}function d4(e,t){return e.length<2?"":`${vm(e,t)?.slug??t}: `}function Wp(e,t,r){let n=e.testPlacements?.find(s=>s.testType===r&&iQ(s.repository,t));return n&&(n.directory.trim().replace(/\/+$/,"")||".")}function bl(e){return(e.relatedRepos??[]).map(t=>t.path)}function wl(e){let t=je(e);if(t.length<2)return[];let r=n=>n.working?"your working directory; writable":n.writable?"writable":"read-only: read it, never write a test there";return["",`This run has ${t.length} checkouts, and none is primary. Every test, maintained test and result lives in exactly one of`,'them: name it by "repository" (owner/repo), with its path relative to that checkout. Place a test in the',"checkout whose test tree it belongs to, which need not be the checkout the change is in.",...t.map(n=>` - ${n.slug}: ${n.path} (${r(n)})`)]}function oQ(e){return e.pullRequest?`the description of ${e.pullRequest}`:"the PR description"}function Rm(e){let t=(e.pullRequests??[]).flatMap(n=>n.body?.trim()?[{pullRequest:`${n.repository}#${n.number}`,body:n.body}]:[]),r=e.prDescription;return r?.trim()&&!t.some(n=>n.body.trim()===r.trim())?[{body:r},...t]:t}function ra(e){let t={label:"PR",title:e.prTitle,body:e.prDescription?.trim(),cut:!1,note:void 0},r=e.pullRequests?.length?[...e.pullRequests.map(o=>({label:`${o.repository}#${o.number}`,title:o.title,body:o.body?.trim().slice(0,l4),cut:(o.body?.trim().length??0)>l4,note:o.note})),...Rm(e).some(o=>!o.pullRequest)?[t]:[]]:t.title||t.body?[t]:[];if(r.length===0)return["","No pull request describes this change."];let n=`This change is ${r.length} pull requests. Read every description: each states part of what the change must do.`;return["",...e.pullRequests?.length||!e.relatedRepos?.length?[r.length>1?n:"This change is 1 pull request. Read its description: it states what the change must do."]:[],...r.flatMap(o=>[`--- ${[o.label,o.title].filter(Boolean).join(": ")} ---`,o.note?`(${o.note})`:o.body||"(no description)",...o.cut?[`(cut at ${l4.toLocaleString("en-US")} characters)`]:[]])]}var aQ=z(require("fs")),Wke=z(require("path"));function ewt(e){let t=new Map,r,n;for(let s of e.split(`
|
|
225
|
-
`)){let i=/^diff --git a\/.+ b\/(.+)$/.exec(s);if(i){r=i[1],n=void 0,t.has(r)||t.set(r,[]);continue}let o=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(s);if(o){n=Number(o[1]);continue}!r||n===void 0||(s.startsWith("+")?t.get(r).push([n,n++]):s.startsWith("-")?t.get(r).push([n,n]):s.startsWith(" ")&&n++)}return t}function Yke(e){let t=Wke.join(e.runDir,xm);if(aQ.existsSync(t))return ewt(aQ.readFileSync(t,"utf-8"))}function twt(e){let t=/([\w./@+-]+\.[\w]+)(?::(\d+)(?:-(\d+))?)?/.exec(e);if(!t)return{};let r=t[1].replace(/^\.\//,"");if(!t[2])return{file:r};let n=Number(t[2]);return{file:r,lines:[n,t[3]?Number(t[3]):n]}}function Jke(e,t){if(!t)return!0;let{file:r,lines:n}=twt(e);if(!r)return!0;let s=t.get(r)??[...t].find(([i])=>i.endsWith(`/${r}`)||r.endsWith(`/${i}`))?.[1];return s?n?s.some(([i,o])=>n[0]<=o&&n[1]>=i):!0:!1}var bs=["-c","core.fsmonitor=false"],rwt=new Set(["GH_TOKEN","GITHUB_TOKEN","GH_ENTERPRISE_TOKEN","GITHUB_ENTERPRISE_TOKEN","ACTIONS_RUNTIME_TOKEN","ACTIONS_ID_TOKEN_REQUEST_TOKEN","ACTIONS_ID_TOKEN_REQUEST_URL","SYSTEM_ACCESSTOKEN","SYSTEM_OIDCREQUESTURI","SSH_AUTH_SOCK","GIT_SSH","GIT_SSH_COMMAND","GITHUB_STEP_SUMMARY"]),p4=new Set(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_BEARER_TOKEN_BEDROCK","AWS_PROFILE","AWS_WEB_IDENTITY_TOKEN_FILE","AWS_ROLE_ARN","AWS_ROLE_SESSION_NAME","AWS_CONTAINER_CREDENTIALS_FULL_URI","AWS_CONTAINER_CREDENTIALS_RELATIVE_URI","AWS_CONTAINER_AUTHORIZATION_TOKEN","AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"]);function Ye(e=process.env,t,r="repo-command"){let n={};for(let[s,i]of Object.entries(e))r==="repo-command"&&p4.has(s)||(n[s]=i);Object.assign(n,t??{});for(let s of Object.keys(n))(rwt.has(s)||s.startsWith("INPUT_"))&&delete n[s];return n}var v4=require("child_process"),Kp=z(require("path"));var cQ=z(require("fs")),Kke=z(require("path")),nwt=/[;|`$<>(){}\n\r]|(?<!&)&(?!&)|\|\|/;function Xu(e){let t=(e??"").trim();if(!t)return{kind:"empty",reason:"the command is empty"};if(nwt.test(t))return{kind:"shell-syntax",reason:"it uses shell syntax (pipe, redirect, substitution, or backgrounding), 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"};let r=[],n=[],s="",i,o=!1,a=()=>{(s||o)&&n.push(s),s="",o=!1},c=()=>{a(),n.length>0&&r.push(n),n=[]};for(let u=0;u<t.length;u++){let d=t[u];if(i){d===i?i=void 0:s+=d;continue}if(d==='"'||d==="'"){i=d,o=!0;continue}if(d==="&"&&t[u+1]==="&"){c(),u+=1;continue}if(/\s/.test(d)){a();continue}s+=d}if(i)return{kind:"unterminated-quote",reason:"it has an unterminated quote"};if(c(),r.length===0)return{kind:"empty",reason:"the command is empty"};if(r.some(u=>u.length===0))return{kind:"empty-step",reason:"it has an empty step between && operators"};let l=r.find(u=>["cd","export","source","."].includes(u[0]));return l?{kind:"builtin",reason:`it runs the shell builtin "${l[0]}", which cannot be executed as a program \u2014 record a script that does this instead`}:{argv:r[0],steps:r}}function lQ(e,t,r){let n=(e??"").trim(),{steps:s,kind:i}=Xu(n);if(!s&&!(i!=="shell-syntax"&&i!=="builtin")){try{cQ.mkdirSync(Kke.dirname(t),{recursive:!0}),cQ.writeFileSync(t,`#!/usr/bin/env bash
|
|
225
|
+
`)){let i=/^diff --git a\/.+ b\/(.+)$/.exec(s);if(i){r=i[1],n=void 0,t.has(r)||t.set(r,[]);continue}let o=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(s);if(o){n=Number(o[1]);continue}!r||n===void 0||(s.startsWith("+")?t.get(r).push([n,n++]):s.startsWith("-")?t.get(r).push([n,n]):s.startsWith(" ")&&n++)}return t}function Yke(e){let t=Wke.join(e.runDir,xm);if(aQ.existsSync(t))return ewt(aQ.readFileSync(t,"utf-8"))}function twt(e){let t=/([\w./@+-]+\.[\w]+)(?::(\d+)(?:-(\d+))?)?/.exec(e);if(!t)return{};let r=t[1].replace(/^\.\//,"");if(!t[2])return{file:r};let n=Number(t[2]);return{file:r,lines:[n,t[3]?Number(t[3]):n]}}function Jke(e,t){if(!t)return!0;let{file:r,lines:n}=twt(e);if(!r)return!0;let s=t.get(r)??[...t].find(([i])=>i.endsWith(`/${r}`)||r.endsWith(`/${i}`))?.[1];return s?n?s.some(([i,o])=>n[0]<=o&&n[1]>=i):!0:!1}var bs=["-c","core.fsmonitor=false"],rwt=new Set(["GH_TOKEN","GITHUB_TOKEN","GH_ENTERPRISE_TOKEN","GITHUB_ENTERPRISE_TOKEN","ACTIONS_RUNTIME_TOKEN","ACTIONS_ID_TOKEN_REQUEST_TOKEN","ACTIONS_ID_TOKEN_REQUEST_URL","SYSTEM_ACCESSTOKEN","SYSTEM_OIDCREQUESTURI","SKYRAMP_MCP_GITHUB_TOKEN","SSH_AUTH_SOCK","GIT_SSH","GIT_SSH_COMMAND","GITHUB_STEP_SUMMARY"]),p4=new Set(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_BEARER_TOKEN_BEDROCK","AWS_PROFILE","AWS_WEB_IDENTITY_TOKEN_FILE","AWS_ROLE_ARN","AWS_ROLE_SESSION_NAME","AWS_CONTAINER_CREDENTIALS_FULL_URI","AWS_CONTAINER_CREDENTIALS_RELATIVE_URI","AWS_CONTAINER_AUTHORIZATION_TOKEN","AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"]);function Ye(e=process.env,t,r="repo-command"){let n={};for(let[s,i]of Object.entries(e))r==="repo-command"&&p4.has(s)||(n[s]=i);Object.assign(n,t??{});for(let s of Object.keys(n))(rwt.has(s)||s.startsWith("INPUT_"))&&delete n[s];return n}var v4=require("child_process"),Kp=z(require("path"));var cQ=z(require("fs")),Kke=z(require("path")),nwt=/[;|`$<>(){}\n\r]|(?<!&)&(?!&)|\|\|/;function Xu(e){let t=(e??"").trim();if(!t)return{kind:"empty",reason:"the command is empty"};if(nwt.test(t))return{kind:"shell-syntax",reason:"it uses shell syntax (pipe, redirect, substitution, or backgrounding), 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"};let r=[],n=[],s="",i,o=!1,a=()=>{(s||o)&&n.push(s),s="",o=!1},c=()=>{a(),n.length>0&&r.push(n),n=[]};for(let u=0;u<t.length;u++){let d=t[u];if(i){d===i?i=void 0:s+=d;continue}if(d==='"'||d==="'"){i=d,o=!0;continue}if(d==="&"&&t[u+1]==="&"){c(),u+=1;continue}if(/\s/.test(d)){a();continue}s+=d}if(i)return{kind:"unterminated-quote",reason:"it has an unterminated quote"};if(c(),r.length===0)return{kind:"empty",reason:"the command is empty"};if(r.some(u=>u.length===0))return{kind:"empty-step",reason:"it has an empty step between && operators"};let l=r.find(u=>["cd","export","source","."].includes(u[0]));return l?{kind:"builtin",reason:`it runs the shell builtin "${l[0]}", which cannot be executed as a program \u2014 record a script that does this instead`}:{argv:r[0],steps:r}}function lQ(e,t,r){let n=(e??"").trim(),{steps:s,kind:i}=Xu(n);if(!s&&!(i!=="shell-syntax"&&i!=="builtin")){try{cQ.mkdirSync(Kke.dirname(t),{recursive:!0}),cQ.writeFileSync(t,`#!/usr/bin/env bash
|
|
226
226
|
# Written by ${r}: the recorded command, which needed a shell to run.
|
|
227
227
|
set -euo pipefail
|
|
228
228
|
${n}
|
|
@@ -331,7 +331,7 @@ ${e.message??""}`));function E_e(e){if(!e.length||!e.every(axt))return;let t=e.f
|
|
|
331
331
|
`:e.text??"")}function o5(e){i5({command:e})}function BPe(e){return e.replace(/%/g,"%AZP25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function Evt(e){return BPe(e).replace(/;/g,"%3B").replace(/]/g,"%5D")}function kD(e,t,r){let n=Object.entries(t).map(([s,i])=>`${s}=${Evt(i)}`).join(";");return`##vso[${e}${n?` ${n}`:""}]${BPe(r)}`}function NPe(e){if(!e)return[];let t=e.split(/\r?\n/).filter(r=>r.trim()&&r!==e);return[e,...t].map(r=>kD("task.setsecret",{},r))}function _Pe(e,t=o5){for(let r of NPe(e))t(r)}function bvt(e){return e.replace(/%0D/g,"\r").replace(/%0A/g,`
|
|
332
332
|
`).replace(/%25/g,"%")}function PPe(e){let t=/^::([a-z-]+)(?: [^:]*)?::(.*)$/s.exec(e.replace(/\r?\n$/,""));if(!t)return;let[,r,n]=t,s=bvt(n),i=RD(s);switch(r){case"add-mask":return NPe(s);case"warning":case"error":return[kD("task.logissue",{type:r},i)];case"notice":return[i];case"debug":return i.split(`
|
|
333
333
|
`).map(o=>`##[debug]${o}`);case"group":return[`##[group]${i.split(`
|
|
334
|
-
`)[0]}`];case"endgroup":return["##[endgroup]"];default:return[]}}function ev(e){return e.replace(/\/+$/,"")}function a5(e){let t=new URL(e),r=t.pathname.split("/").filter(Boolean);if(r.length)return decodeURIComponent(r[r.length-1]);if(t.hostname.endsWith(".visualstudio.com"))return t.hostname.split(".")[0];throw new Error(`SYSTEM_COLLECTIONURI "${e}" names no organization`)}var wvt=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,48}[A-Za-z0-9])?$/,Cvt=/[\\/:*?"<>|;#${},+=[\]%\p{Cc}\p{Cf}]/u;function QPe(e){return e.length>0&&e.length<=64&&e===e.trim()&&!Cvt.test(e)&&!/[^\S ]/u.test(e)&&!/^[._]/.test(e)&&!e.endsWith(".")}function TD(e){return c5(`${e.namespace}/${e.name}`)}function c5(e){let t=e.indexOf("/"),r=e.lastIndexOf("/"),n=e.slice(0,t),s=e.slice(t+1,r),i=e.slice(r+1);if(t<0||t===r||!wvt.test(n)||!QPe(s)||!QPe(i))throw new Error(`"${e}" is not an Azure DevOps organization/project/repository`);return{organization:n,project:s,name:i}}function DPe(e,t){let r=a5(e);if(r.toLowerCase()!==t.organization.toLowerCase())throw new Error(`${t.organization}/${t.project}/${t.name} is not in ${r}, the Azure DevOps organization this job runs in`)}function OPe(e,t){return DPe(e,t),`${ev(e)}/${encodeURIComponent(t.project)}/_git/${encodeURIComponent(t.name)}`}function l5(e,t){return DPe(e,t),`${ev(e)}/${encodeURIComponent(t.project)}/_apis/git/repositories/${encodeURIComponent(t.name)}`}var Svt="7.1",Zx=class extends Error{constructor(r,n){super(r);this.status=n}status};async function u5(e){let t=e.accept??"application/json",r=new URL(e.url);r.searchParams.has("api-version")||r.searchParams.set("api-version",Svt);let n=await(e.fetch??fetch)(r.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(!n.ok){let s=(await n.json().catch(()=>({}))).message;throw new Zx(`Azure DevOps answered ${n.status}${typeof s=="string"?`: ${s}`:""}`,n.status)}return t!=="application/json"?Buffer.from(await n.arrayBuffer()):n.status===204?{}:await n.json()}function Ivt(e){return`AUTHORIZATION: bearer ${e}`}function MPe(e,t){return{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${ev(e)}/.extraheader`,GIT_CONFIG_VALUE_0:Ivt(t)}}var vvt="7.1-preview.1",Rvt=".azure-pipelines/skyramp-testbot-v3.yml";function Zm(e){return e.GITHUB_ACTIONS!=="true"&&/^true$/i.test(e.TF_BUILD??"")}var kvt={INPUT_PIPELINE:"SKYRAMP_PIPELINE",INPUT_SKYRAMPRUNID:"SKYRAMP_RUN_ID",INPUT_SKYRAMPAPPORIGIN:"SKYRAMP_APP_ORIGIN",INPUT_SKYRAMPMCPVERSION:"SKYRAMP_MCP_VERSION",INPUT_SKYRAMPMCPSOURCE:"SKYRAMP_MCP_SOURCE",INPUT_SKYRAMPMCPGITHUBREF:"SKYRAMP_MCP_GITHUB_REF",INPUT_SKYRAMPMCPGITHUBTOKEN:"SKYRAMP_MCP_GITHUB_TOKEN",INPUT_USEBEDROCK:"SKYRAMP_USE_BEDROCK",INPUT_AWSREGION:"SKYRAMP_AWS_REGION",INPUT_AWSROLEARN:"SKYRAMP_AWS_ROLE_ARN"};function LPe(e=process.env){if(Zm(e))for(let[t,r]of Object.entries(kvt))!e[t]&&e[r]!==void 0&&(e[t]=e[r])}function UPe(e,t={}){let r=d=>{let p=e[d];if(!p)throw new Error(`${d} is not set; the V3 runner handshake needs it`);return p},n=ev(e.SYSTEM_COLLECTIONURI??""),s=()=>a5(r("SYSTEM_COLLECTIONURI")),i=e.SYSTEM_TEAMPROJECT,o=e.BUILD_REPOSITORY_NAME,a=e.BUILD_REPOSITORY_ID?.toLowerCase(),c=e.SYSTEM_ACCESSTOKEN,l=t.mask??(d=>_Pe(d)),u=d=>async()=>{if(!d)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_OIDCREQUESTURI to $(System.OidcRequestUri).");if(!c)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_ACCESSTOKEN to $(System.AccessToken).");let p=new URL(d);if(p.protocol!=="https:")throw new Error("SYSTEM_OIDCREQUESTURI is not an https URL");p.searchParams.set("api-version",vvt);let f=await(t.fetch??fetch)(p.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json",Accept:"application/json"},body:"{}",redirect:"error",signal:AbortSignal.timeout(3e4)});if(!f.ok)throw new Error(`Azure DevOps refused the OIDC token request: ${f.status}`);let h=(await f.json().catch(()=>({}))).oidcToken;if(typeof h!="string"||!h)throw new Error("Azure DevOps's OIDC token response carried no token");return l(h),h};return{runnerPlatform:Zm(e)?"azure":void 0,workspace:e.BUILD_SOURCESDIRECTORY||void 0,serverUrl:n,apiUrl:n,repository:a&&i&&o&&n?{id:a,slug:`${s()}/${i}/${o}`}:void 0,runId:e.BUILD_BUILDID||void 0,runAttempt:e.SYSTEM_STAGEATTEMPT||void 0,job:e.SYSTEM_JOBNAME||void 0,execution(){let d=r("SYSTEM_STAGEATTEMPT");if(!/^[1-9][0-9]*$/.test(d))throw new Error(`SYSTEM_STAGEATTEMPT is "${d}", not a positive whole number`);let p=r("SYSTEM_COLLECTIONID").toLowerCase();if(!sb.test(p))throw new Error(`SYSTEM_COLLECTIONID is "${p}", not a GUID`);let f=r("BUILD_REPOSITORY_ID").toLowerCase();if(!sb.test(f))throw new Error(`BUILD_REPOSITORY_ID is "${f}", not a GUID`);let h=[s(),r("SYSTEM_TEAMPROJECT"),r("SYSTEM_DEFINITIONID"),r("BUILD_BUILDID")].map(encodeURIComponent).join("/");return{provider:"azure-devops",repository:{provider:"azure-devops",providerAccountId:p,providerRepositoryId:f},providerRunId:h,providerRunAttempt:Number(d),workflowRef:`${Rvt}@${r("BUILD_SOURCEBRANCH")}`}},takeIdToken(){let d=e.SYSTEM_OIDCREQUESTURI;delete e.SYSTEM_OIDCREQUESTURI;let p=u(d);return()=>p()},takeSourceToken(){return delete e.SYSTEM_ACCESSTOKEN,c||void 0},webIdentity(){if(!e.SYSTEM_OIDCREQUESTURI?.trim()||!c)return;let d=u(e.SYSTEM_OIDCREQUESTURI);return{token:()=>d(),runId:e.BUILD_BUILDID}},v3RunsOnly:!0,assumesBedrockRole:!0,namesSourceToMcp:!0,checkSourceName(d){TD(d)},cloneUrl(d){return OPe(n,TD(d))},gitAuthEnv(d){return MPe(n,d)},async pullRequest(d,p,f){let h=await u5({token:await f.token(),url:`${l5(n,TD(d))}/pullrequests/${p}`,fetch:f.fetch}),A=h.status==="completed";return{...typeof h.title=="string"?{title:h.title}:{},...typeof h.description=="string"?{body:h.description}:{},...typeof h.status=="string"?{merged:A}:{},...A&&typeof h.lastMergeCommit?.commitId=="string"?{mergeCommit:h.lastMergeCommit.commitId}:{},...A&&typeof h.lastMergeSourceCommit?.commitId=="string"?{mergedHead:h.lastMergeSourceCommit.commitId}:{}}},async commitLookup(d,p,f){let h;try{h=l5(n,c5(d))}catch{return"unknown"}try{let A=await u5({token:await f.token(),url:`${h}/commits/${encodeURIComponent(p)}`,fetch:f.fetch});return typeof A.commitId=="string"&&A.commitId.toLowerCase()===p.toLowerCase()?"found":"missing"}catch(A){return A instanceof Zx&&(A.status===404||A.status===400)?"missing":"unknown"}}}}ft();var Tvt=5e3,d5=/^(?!\.\.?$)[A-Za-z0-9._-]{1,100}$/;function $Pe(e){let t=Buffer.from(`x-access-token:${e}`).toString("base64");return Ns(t),`AUTHORIZATION: basic ${t}`}function qPe(e,t={}){let r=c=>{let l=e[c];if(!l)throw new Error(`${c} is not set; the V3 runner handshake needs it`);return l},n=e.GITHUB_REPOSITORY_ID,s=e.GITHUB_REPOSITORY,i=(e.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,""),o=(e.GITHUB_API_URL||"https://api.github.com").replace(/\/+$/,""),a=async(c,l)=>l.fetch(c,{headers:{Authorization:`Bearer ${await l.token()}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(3e4)});return{runnerPlatform:e.GITHUB_ACTIONS==="true"?"github":void 0,workspace:e.GITHUB_WORKSPACE||void 0,serverUrl:i,apiUrl:o,repository:n&&s?{id:n,slug:s}:void 0,runId:e.GITHUB_RUN_ID||void 0,runAttempt:e.GITHUB_RUN_ATTEMPT||void 0,job:e.GITHUB_JOB||void 0,execution(){let c=r("GITHUB_RUN_ATTEMPT");if(!/^[1-9][0-9]*$/.test(c))throw new Error(`GITHUB_RUN_ATTEMPT is "${c}", not a positive whole number`);return{provider:"github",repository:{provider:"github",providerAccountId:r("GITHUB_REPOSITORY_OWNER_ID"),providerRepositoryId:r("GITHUB_REPOSITORY_ID")},providerRunId:r("GITHUB_RUN_ID"),providerRunAttempt:Number(c),workflowRef:r("GITHUB_WORKFLOW_REF")}},takeIdToken(){let c=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 u=>{if(!c||!l)throw new Error("The job cannot request an OIDC token. Give it the `id-token: write` permission.");let d=new URL(c);d.searchParams.set("audience",u);let p=await fetch(d,{headers:{Authorization:`Bearer ${l}`,Accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!p.ok)throw new Error(`GitHub refused the OIDC token request: ${p.status}`);let f=(await p.json().catch(()=>({}))).value;if(typeof f!="string"||!f)throw new Error("GitHub's OIDC token response carried no token");return Ns(f),f}},webIdentity(){return!e.ACTIONS_ID_TOKEN_REQUEST_TOKEN?.trim()||!e.ACTIONS_ID_TOKEN_REQUEST_URL?.trim()?void 0:{token:t.getIDToken??(l=>Zne(l)),runId:e.GITHUB_RUN_ID}},v3RunsOnly:!1,assumesBedrockRole:!1,namesSourceToMcp:!1,checkSourceName(c){for(let l of[c.namespace,c.name])if(!d5.test(l))throw new Error(`"${l}" is not a repository name`)},cloneUrl(c){return`${i}/${c.namespace}/${c.name}.git`},gitAuthEnv(c){return c?{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${i}/.extraheader`,GIT_CONFIG_VALUE_0:$Pe(c)}:{}},async pullRequest({namespace:c,name:l},u,d){if(![c,l].every(h=>d5.test(h)))throw new Error("the repository name is not valid");let p=await a(`${o}/repos/${c}/${l}/pulls/${u}`,d);if(!p.ok)throw new Error(`GitHub answered ${p.status}`);let f=await p.json();return{...typeof f.title=="string"?{title:f.title}:{},...typeof f.body=="string"?{body:f.body}:{},...typeof f.merged=="boolean"?{merged:f.merged}:{},...f.merged===!0&&typeof f.merge_commit_sha=="string"?{mergeCommit:f.merge_commit_sha}:{},...f.merged===!0&&typeof f.head?.sha=="string"?{mergedHead:f.head.sha}:{}}},async commitLookup(c,l,u){let[d,p,...f]=c.split("/");if(f.length||![d,p].every(h=>h!==void 0&&d5.test(h)))return"unknown";try{let h=await a(`${o}/repos/${d}/${p}/commits/${encodeURIComponent(l)}`,u);if(h.status===404||h.status===422)return"missing";if(!h.ok)return"unknown";let A=await h.json();return typeof A.sha=="string"&&A.sha.toLowerCase()===l.toLowerCase()?"found":"missing"}catch{return"unknown"}},async revokeToken(c,l){let u=await l(`${o}/installation/token`,{method:"DELETE",headers:{Authorization:`Bearer ${c}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(Tvt)});if(!u.ok&&u.status!==401)throw new Error(`GitHub answered ${u.status}`)}}}function dd(e=process.env){return Zm(e)?UPe(e):qPe(e)}var Bvt=10*6e4;function HPe(e,t){return e.getTime()-t.getTime()-Bvt}var Wur=10*6e4,Nvt=3e4,_vt=3,ob=class extends Error{constructor(r,n,s){super(r);this.status=n;this.code=s}status;code},BD=class extends Error{};function Pvt(e){let t;try{t=new URL(e)}catch{throw new Error(`skyrampAppOrigin "${e}" is not a URL`)}if(t.protocol!=="https:"||t.origin!==e.replace(/\/+$/,""))throw new Error(`skyrampAppOrigin must be an https origin, got "${e}"`);return t.origin}function Qvt(e,t){if(!sb.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}function Dvt(e,t,r){throw t<500&&t!==429?new ob(e,t,r):new BD(e)}async function Ovt(e,t,r,n){let s=Pvt(e.origin),i;for(let o=1;o<=_vt;o+=1){o>1&&await new Promise(a=>setTimeout(a,(e.retryDelayMs??2e3)*(o-1)));try{let a=await e.idToken(s),c=await(e.fetch??fetch)(new URL(t,s).toString(),{...r(a),redirect:"error",signal:AbortSignal.timeout(Nvt)}).catch(l=>{throw new BD(l instanceof Error?l.message:String(l),{cause:l})});return await n(c)}catch(a){if(a instanceof ob)throw a;i=a}}throw i}function Mvt(e,t,r,n){return Ovt(e,r,i=>({method:t,headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json",Accept:"application/json"},body:t==="GET"?void 0:JSON.stringify(n)}),async i=>{let o=await i.json().catch(()=>({}));if(i.ok)return o.data;let a=o.error?.fields,c=typeof a?.path=="string"&&typeof a.reason=="string"?` at ${a.path}: ${a.reason}`:"",l=`The Skyramp app refused ${t} ${r}: ${i.status} ${o.error?.code??"no error code"}${c}`;return Dvt(l,i.status,o.error?.code)})}var Yur=10*6e4;var Jur=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var Kur=g.object({tests:g.object({placements:g.array(g.unknown()).optional()}).passthrough().optional()}).passthrough(),Xur=g.object({repository:Y8,testType:g.nativeEnum(Im),directory:g.string()}).passthrough();var Zur=g.object({report:g.object({language:g.string()}).passthrough()}).passthrough();var edr=g.object({environment:g.object({components:g.array(g.unknown()).optional(),dependencies:g.array(g.unknown()).optional()}).passthrough()}).passthrough(),tdr=g.object({name:g.string().min(1),provision:g.literal("existing"),url:g.string().min(1),repository:Y8.optional(),revisionUrl:g.string().min(1).optional()}).passthrough(),rdr=g.object({name:g.string().min(1),url:g.string().nullable(),versionUrl:g.string().nullable(),notes:g.string().nullable()}).passthrough();var ndr=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);async function jPe(e,t){return Qvt(e.attemptId,"attempt id"),Mvt(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,IPe({reportUploaded:e.reportUploaded,recipeUploaded:e.recipeUploaded,cancelled:e.cause==="cancelled",timedOut:e.cause==="timed_out",setupFailed:e.cause==="setup_failed",checkoutFailed:e.cause==="checkout_failed",credentialMissing:e.cause==="credential_missing"}))}var Lvt={focused:"Focused",impacted_critical:"Impacted and critical",broad:"Broad"};function _D(e,t){return Va(e,t).length+(e.relatedChanges??[]).filter(r=>r.note).length}function PD(e,t){return e.confirmedRunId===null?"first_qualification":t>0?"delta":"unchanged"}var ND=e=>e.depth?` at depth ${Lvt[e.depth]}`:"",zPe="Sweep the configured scope instead of a diff: every repository of the run, its public surface (endpoints, screens, exported functions) and its existing test suites, and list the behaviors they establish, so triage can plan evidence for them. A finding here is a latent defect of the current state.";function WPe(e,t){switch(PD(e,t)){case"first_qualification":return["This is a scheduled validation, first qualification: the policy has no Confirmed Baseline yet, so this run establishes one. It validates the Target's configured state broadly, not a change.",zPe];case"delta":return[`This is a scheduled validation${ND(e)}. The diff below is everything that changed since the Confirmed Baseline (run ${e.confirmedRunId}), across every source: not one pull request. Review it as the change under validation; there is no PR description.`];case"unchanged":return[`This is a scheduled validation${ND(e)}. Nothing changed since the Confirmed Baseline (run ${e.confirmedRunId}), so there is no diff to review. The state is still under validation: shared services and dependencies can drift.`,zPe]}}var VPe="Plan evidence for the behaviors analyze found: run the existing suites (existing_unit), accept current approved CI evidence, and bring up the SUT only where only runtime evidence will do. The existing suites run under runtime_required too. Do not set a behavior aside as unaffected or out of scope because nothing changed: in a scheduled validation the state itself is under validation. Never conclude success because nothing changed; a run that obtains no evidence validated nothing.";function YPe(e,t){switch(PD(e,t)){case"first_qualification":return["Scheduled validation, first qualification: the policy has no Confirmed Baseline yet. Validate the configured scope broadly; this run's success becomes the Confirmed Baseline.",VPe];case"delta":return[`Scheduled validation${ND(e)}: the files below changed since the Confirmed Baseline (run ${e.confirmedRunId}), across every source. Judge the evidence the policy needs for them, at its depth, as for any change.`];case"unchanged":return[`Change under validation: no change since the Confirmed Baseline (run ${e.confirmedRunId}). This is a scheduled validation${ND(e)}, so decide what evidence the policy needs for the current state now.`,VPe]}}var cb=z(require("fs")),DD=z(require("path"));var tv=z(require("fs")),tc=z(require("path")),ab=tc.join(".skyramp","sut"),JPe=tc.join(".skyramp","workspace.yml");function Uvt(e){return e.startsWith(`${ab}${tc.sep}`)||e.startsWith(".skyramp/sut/")||e===JPe||e===".skyramp/workspace.yml"||/(^|\/)(docker-compose|compose)[^/]*\.ya?ml$/.test(e)||/(^|\/)Dockerfile[^/]*$/.test(e)||/^\.github\/workflows\//.test(e)}function mo(e,t,r={}){let n=t.split(/[\\/]+/).filter(Boolean),s=e;for(let[i,o]of n.entries()){s=tc.join(s,o);let a=tv.lstatSync(s,{throwIfNoEntry:!1}),c=i===n.length-1;if(!a||a.isSymbolicLink()||(c?r.directory?!a.isDirectory():!a.isFile():!a.isDirectory()))return}return n.length?s:void 0}function go(e,t=[]){let r=p=>mo(e,p),n=r(tc.join(ab,"setup.sh")),s=r(tc.join(ab,"teardown.sh")),i=r(tc.join(ab,"get-auth-token.sh")),o=r(JPe),a,c=r(tc.join(ab,"health.json"));if(c)try{let p=JSON.parse(tv.readFileSync(c,"utf-8"));p&&(p.url||p.command)&&(a=p)}catch{}let l,u=r(tc.join(ab,"deploy-budget.json"));if(u)try{let p=JSON.parse(tv.readFileSync(u,"utf-8"));typeof p?.minutes=="number"&&Number.isFinite(p.minutes)&&p.minutes>0&&(l=p.minutes)}catch{}let d=t.filter(Uvt);return{setupScript:n,teardownScript:s,authTokenScript:i,workspaceFile:o,healthHint:a,budgetMinutes:l,present:!!(n||o),staleFiles:d,stale:d.length>0}}function p5(e,t){let{value:r,error:n}=Kt(e);if(n)return{errors:[n]};let s=t&&!t.testEnvironment?$vt(r,t):r,i=gE(s)&&s.schemaVersion===void 0?{schemaVersion:1,...s}:s,{value:o,errors:a}=AE(nx,y4,i);return o?{onboard:o,errors:[]}:{errors:a}}function $vt(e,t){if(!gE(e))return e;let{environment:r,...n}=e,s=[...t.repositorySlug?[{slug:t.repositorySlug,path:t.repositoryPath}]:[],...(t.relatedRepos??[]).map(a=>({slug:a.slug,path:a.path}))],i=a=>typeof a=="string"?s.find(c=>mo(c.path,a))?.slug:void 0,o=Array.isArray(n.components)?n.components.map(a=>{if(!gE(a))return a;let{deployed:c,...l}=a;if(l.repository!==jn)return l;let u=gE(l.from)?l.from.file:void 0,d=i(u)??s[0]?.slug;return d?{...l,repository:d}:l}):n.components;return{...n,components:o}}var QD=".skyramp/sut/health.json",qvt={[QD]:`${QD} (with a url or command)`,".skyramp/workspace.yml":".skyramp/workspace.yml (create it with skyramp_init_scan and skyramp_init_workspace)"};function KPe(){return{name:"onboard-recipe",verify(e,t){let{onboard:r,errors:n}=p5(t.stdout,e.inputs);if(!r)return ce(this.name,n,{fatal:!0});let s=r.environment!==void 0;if(r.status==="blocked")return{name:this.name,passed:!0};let i=e.inputs.repositoryPath,o=go(i),a=s?Wx.filter(u=>mo(i,u)):[];if(a.length>0)return ce(this.name,[`an answer with "environment" tests a deployment where it runs and never starts or stops it: delete ${a.join(" and ")}, keep the health check, and answer "ready" again`]);let l=(s?J_e:Y_e).filter(u=>!mo(i,u)).map(u=>qvt[u]??u);return mo(i,QD)&&!o.healthHint&&l.push(`${QD} (with a url or command)`),o.present&&l.length===0?{name:this.name,passed:!0}:ce(this.name,[`status is "ready" but the recipe deploy replays is incomplete in ${e.inputs.repositoryPath} \u2014 missing (each must be a regular file, not a symlink): ${l.join(", ")}. Write the missing files as the skill specifies and answer "ready" again, or answer "blocked" with the blocker that stopped you.`])}}}function XPe(){return{name:"deployed-revisions",async verify(e,t,r,n){let s={name:this.name,passed:!0},i=e.checkDeployedRevisions;if(!i)return s;let{onboard:o}=p5(t.stdout,e.inputs);if(!o?.environment||o.status==="blocked")return s;let a=gQ(f5(e.inputs.repositoryPath).recipeFiles);if(!a)return s;let c=o.components.map(({name:d,repository:p})=>({name:d,repository:p})),{blockers:l}=await i(a.content,c,o.environment.credentials);if(l.length===0)return s;let u=l.map(d=>`${d.component}: ${d.problem} (${d.evidence})`).join("; ");return n?.retryLeft?ce(this.name,[`Testbot ran ${Pm} twice, with GH_TOKEN, and it failed the check the setup's plan must pass: ${u}. Your session has no GH_TOKEN, so the part that reads GitHub ran in full only there. Fix the script so each component a repository builds gets the full commit it runs, the same on each run, from its own repository, then answer "ready" again, or answer "blocked" with the blocker that stops you.`]):{...s,details:`${Pm} still fails Testbot's check, so the plan is saved blocked: ${u}`}}}}function Gvt(e){try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(e)}catch{return}}function f5(e){let t=[],r=o=>{let a;try{a=cb.readdirSync(DD.join(e,o),{withFileTypes:!0})}catch{return}for(let c of a.sort((l,u)=>l.name.localeCompare(u.name))){let l=DD.posix.join(o,c.name);c.isDirectory()&&!c.name.startsWith(".")?r(l):c.isFile()&&t.push(l)}};mo(e,".skyramp/sut",{directory:!0})&&r(".skyramp/sut"),mo(e,".skyramp/workspace.yml")&&t.push(".skyramp/workspace.yml");let n=[],s=[],i=0;for(let o of t){let a=mo(e,o);if(!a)continue;let l=cb.statSync(a).size;if(l>Nm){s.push({path:o,reason:`larger than ${Nm} bytes`});continue}if(i+l>_m){s.push({path:o,reason:`recipe text over ${_m} bytes in total`});continue}let u=Gvt(cb.readFileSync(a));if(u===void 0||mQ.test(u)){s.push({path:o,reason:"not text"});continue}n.push({path:o,content:u}),i+=l}return{recipeFiles:n,recipeFilesOmitted:s}}function ZPe(e,t){let{onboard:r,errors:n}=p5(t.stdout,e.inputs),s=r&&{...r,...f5(e.inputs.repositoryPath)};return ot(e,"onboard",mr(s,e.secretValues??[]),n)}function OD(e){if(e.state.stages.onboard?.status==="passed")return ee(e,"onboard.json")}var vdr=20*1024*1024;var Dl=z(require("fs")),lb=z(require("path"));var jvt=[/^\.github\//,/^\.gitlab(-ci)?/,/^\.circleci\//,/(^|\/)Jenkinsfile$/,/^docs?\//,/\.(md|mdx|rst)$/i,/(^|\/)LICENSE([._-].*)?$/i,/(^|\/)CODEOWNERS$/,/(^|\/)\.gitignore$/,/(^|\/)\.gitattributes$/,/(^|\/)\.editorconfig$/,/(^|\/)\.prettierrc[^/]*$/,/(^|\/)\.eslintrc[^/]*$/,/(^|\/)eslint\.config\.[^/]+$/,/(^|\/)package-lock\.json$/,/(^|\/)yarn\.lock$/,/(^|\/)pnpm-lock\.yaml$/,/(^|\/)poetry\.lock$/,/(^|\/)Pipfile\.lock$/,/(^|\/)Cargo\.lock$/,/(^|\/)go\.sum$/,/(^|\/)composer\.lock$/,/(^|\/)Gemfile\.lock$/,/\.(png|jpe?g|gif|svg|ico|webp)$/i];function zvt(e){return jvt.some(t=>t.test(e))}function Vvt(e){let t=[],r=e.inputs.repositoryPath;return!r||!Dl.existsSync(r)?t.push(`repository path does not exist: ${r}`):Px(r)?UE(r,e.inputs.baseBranch)||t.push(e.inputs.baseBranch?`base branch "${e.inputs.baseBranch}" does not resolve`:"could not auto-detect a base branch (origin/HEAD, main, master)"):t.push(`not a git repository: ${r}`),{ok:t.length===0,reasons:t}}function Wvt(e){return(e.inputs.relatedRepos??[]).map(t=>{let r=Dl.existsSync(t.path)?of(t.path):void 0;return r?{repository:t.slug,changedFiles:r.changedFiles}:{repository:t.slug,changedFiles:[],note:`could not read the change in ${t.path}`}})}function Yvt(e){let{repositoryPath:t,baseBranch:r}=e.inputs;Dl.rmSync(lb.join(t,Pr),{recursive:!0,force:!0});let n=of(t,r);if(!n)throw new Error(`could not compute git facts for ${t}`);let s=Qx(t,r);if(!s)throw new Error(`could not compute the PR diff for ${t}`);let i=Wvt(e),o=[n.changedFiles,...i.map(d=>d.changedFiles)].flat(),a=o.map(d=>d.path).filter(zvt),c=o.length>0&&a.length===o.length,l={schemaVersion:1,repository:{path:t,currentBranch:n.currentBranch,baseBranch:n.baseBranch},changedFiles:n.changedFiles,...i.length?{relatedChanges:i}:{},newFiles:s.newFiles,deletedFiles:s.deletedFiles,diffStat:s.diffStat,diffBytes:s.diffContent.length,nonApplicationFiles:a,nonApplicationOnly:c,sutRequired:!c};Dl.writeFileSync(lb.join(e.runDir,xm),s.diffContent);let u=lb.join(e.runDir,c4);return Dl.mkdirSync(lb.dirname(u),{recursive:!0}),Dl.writeFileSync(u,JSON.stringify(l,null,2)+`
|
|
334
|
+
`)[0]}`];case"endgroup":return["##[endgroup]"];default:return[]}}function ev(e){return e.replace(/\/+$/,"")}function a5(e){let t=new URL(e),r=t.pathname.split("/").filter(Boolean);if(r.length)return decodeURIComponent(r[r.length-1]);if(t.hostname.endsWith(".visualstudio.com"))return t.hostname.split(".")[0];throw new Error(`SYSTEM_COLLECTIONURI "${e}" names no organization`)}var wvt=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,48}[A-Za-z0-9])?$/,Cvt=/[\\/:*?"<>|;#${},+=[\]%\p{Cc}\p{Cf}]/u;function QPe(e){return e.length>0&&e.length<=64&&e===e.trim()&&!Cvt.test(e)&&!/[^\S ]/u.test(e)&&!/^[._]/.test(e)&&!e.endsWith(".")}function TD(e){return c5(`${e.namespace}/${e.name}`)}function c5(e){let t=e.indexOf("/"),r=e.lastIndexOf("/"),n=e.slice(0,t),s=e.slice(t+1,r),i=e.slice(r+1);if(t<0||t===r||!wvt.test(n)||!QPe(s)||!QPe(i))throw new Error(`"${e}" is not an Azure DevOps organization/project/repository`);return{organization:n,project:s,name:i}}function DPe(e,t){let r=a5(e);if(r.toLowerCase()!==t.organization.toLowerCase())throw new Error(`${t.organization}/${t.project}/${t.name} is not in ${r}, the Azure DevOps organization this job runs in`)}function OPe(e,t){return DPe(e,t),`${ev(e)}/${encodeURIComponent(t.project)}/_git/${encodeURIComponent(t.name)}`}function l5(e,t){return DPe(e,t),`${ev(e)}/${encodeURIComponent(t.project)}/_apis/git/repositories/${encodeURIComponent(t.name)}`}var Svt="7.1",Zx=class extends Error{constructor(r,n){super(r);this.status=n}status};async function u5(e){let t=e.accept??"application/json",r=new URL(e.url);r.searchParams.has("api-version")||r.searchParams.set("api-version",Svt);let n=await(e.fetch??fetch)(r.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(!n.ok){let s=(await n.json().catch(()=>({}))).message;throw new Zx(`Azure DevOps answered ${n.status}${typeof s=="string"?`: ${s}`:""}`,n.status)}return t!=="application/json"?Buffer.from(await n.arrayBuffer()):n.status===204?{}:await n.json()}function Ivt(e){return`AUTHORIZATION: bearer ${e}`}function MPe(e,t){return{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${ev(e)}/.extraheader`,GIT_CONFIG_VALUE_0:Ivt(t)}}var vvt="7.1-preview.1",Rvt=".azure-pipelines/skyramp-testbot-v3.yml";function Zm(e){return e.GITHUB_ACTIONS!=="true"&&/^true$/i.test(e.TF_BUILD??"")}var kvt={INPUT_PIPELINE:"SKYRAMP_TESTBOT_PIPELINE",INPUT_SKYRAMPRUNID:"SKYRAMP_RUN_ID",INPUT_SKYRAMPAPPORIGIN:"SKYRAMP_APP_ORIGIN",INPUT_SKYRAMPMCPVERSION:"SKYRAMP_MCP_VERSION",INPUT_SKYRAMPMCPSOURCE:"SKYRAMP_MCP_SOURCE",INPUT_SKYRAMPMCPGITHUBREF:"SKYRAMP_MCP_GITHUB_REF",INPUT_SKYRAMPMCPGITHUBTOKEN:"SKYRAMP_MCP_GITHUB_TOKEN",INPUT_USEBEDROCK:"SKYRAMP_USE_BEDROCK",INPUT_AWSREGION:"SKYRAMP_AWS_REGION",INPUT_AWSROLEARN:"SKYRAMP_AWS_ROLE_ARN"};function LPe(e=process.env){if(Zm(e))for(let[t,r]of Object.entries(kvt))!e[t]&&e[r]!==void 0&&(e[t]=e[r])}function UPe(e,t={}){let r=d=>{let p=e[d];if(!p)throw new Error(`${d} is not set; the V3 runner handshake needs it`);return p},n=ev(e.SYSTEM_COLLECTIONURI??""),s=()=>a5(r("SYSTEM_COLLECTIONURI")),i=e.SYSTEM_TEAMPROJECT,o=e.BUILD_REPOSITORY_NAME,a=e.BUILD_REPOSITORY_ID?.toLowerCase(),c=e.SYSTEM_ACCESSTOKEN,l=t.mask??(d=>_Pe(d)),u=d=>async()=>{if(!d)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_OIDCREQUESTURI to $(System.OidcRequestUri).");if(!c)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_ACCESSTOKEN to $(System.AccessToken).");let p=new URL(d);if(p.protocol!=="https:")throw new Error("SYSTEM_OIDCREQUESTURI is not an https URL");p.searchParams.set("api-version",vvt);let f=await(t.fetch??fetch)(p.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json",Accept:"application/json"},body:"{}",redirect:"error",signal:AbortSignal.timeout(3e4)});if(!f.ok)throw new Error(`Azure DevOps refused the OIDC token request: ${f.status}`);let h=(await f.json().catch(()=>({}))).oidcToken;if(typeof h!="string"||!h)throw new Error("Azure DevOps's OIDC token response carried no token");return l(h),h};return{runnerPlatform:Zm(e)?"azure":void 0,workspace:e.BUILD_SOURCESDIRECTORY||void 0,serverUrl:n,apiUrl:n,repository:a&&i&&o&&n?{id:a,slug:`${s()}/${i}/${o}`}:void 0,runId:e.BUILD_BUILDID||void 0,runAttempt:e.SYSTEM_STAGEATTEMPT||void 0,job:e.SYSTEM_JOBNAME||void 0,execution(){let d=r("SYSTEM_STAGEATTEMPT");if(!/^[1-9][0-9]*$/.test(d))throw new Error(`SYSTEM_STAGEATTEMPT is "${d}", not a positive whole number`);let p=r("SYSTEM_COLLECTIONID").toLowerCase();if(!sb.test(p))throw new Error(`SYSTEM_COLLECTIONID is "${p}", not a GUID`);let f=r("BUILD_REPOSITORY_ID").toLowerCase();if(!sb.test(f))throw new Error(`BUILD_REPOSITORY_ID is "${f}", not a GUID`);let h=[s(),r("SYSTEM_TEAMPROJECT"),r("SYSTEM_DEFINITIONID"),r("BUILD_BUILDID")].map(encodeURIComponent).join("/");return{provider:"azure-devops",repository:{provider:"azure-devops",providerAccountId:p,providerRepositoryId:f},providerRunId:h,providerRunAttempt:Number(d),workflowRef:`${Rvt}@${r("BUILD_SOURCEBRANCH")}`}},takeIdToken(){let d=e.SYSTEM_OIDCREQUESTURI;delete e.SYSTEM_OIDCREQUESTURI;let p=u(d);return()=>p()},takeSourceToken(){return delete e.SYSTEM_ACCESSTOKEN,c||void 0},webIdentity(){if(!e.SYSTEM_OIDCREQUESTURI?.trim()||!c)return;let d=u(e.SYSTEM_OIDCREQUESTURI);return{token:()=>d(),runId:e.BUILD_BUILDID}},v3RunsOnly:!0,assumesBedrockRole:!0,namesSourceToMcp:!0,checkSourceName(d){TD(d)},cloneUrl(d){return OPe(n,TD(d))},gitAuthEnv(d){return MPe(n,d)},async pullRequest(d,p,f){let h=await u5({token:await f.token(),url:`${l5(n,TD(d))}/pullrequests/${p}`,fetch:f.fetch}),A=h.status==="completed";return{...typeof h.title=="string"?{title:h.title}:{},...typeof h.description=="string"?{body:h.description}:{},...typeof h.status=="string"?{merged:A}:{},...A&&typeof h.lastMergeCommit?.commitId=="string"?{mergeCommit:h.lastMergeCommit.commitId}:{},...A&&typeof h.lastMergeSourceCommit?.commitId=="string"?{mergedHead:h.lastMergeSourceCommit.commitId}:{}}},async commitLookup(d,p,f){let h;try{h=l5(n,c5(d))}catch{return"unknown"}try{let A=await u5({token:await f.token(),url:`${h}/commits/${encodeURIComponent(p)}`,fetch:f.fetch});return typeof A.commitId=="string"&&A.commitId.toLowerCase()===p.toLowerCase()?"found":"missing"}catch(A){return A instanceof Zx&&(A.status===404||A.status===400)?"missing":"unknown"}}}}ft();var Tvt=5e3,d5=/^(?!\.\.?$)[A-Za-z0-9._-]{1,100}$/;function $Pe(e){let t=Buffer.from(`x-access-token:${e}`).toString("base64");return Ns(t),`AUTHORIZATION: basic ${t}`}function qPe(e,t={}){let r=c=>{let l=e[c];if(!l)throw new Error(`${c} is not set; the V3 runner handshake needs it`);return l},n=e.GITHUB_REPOSITORY_ID,s=e.GITHUB_REPOSITORY,i=(e.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,""),o=(e.GITHUB_API_URL||"https://api.github.com").replace(/\/+$/,""),a=async(c,l)=>l.fetch(c,{headers:{Authorization:`Bearer ${await l.token()}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(3e4)});return{runnerPlatform:e.GITHUB_ACTIONS==="true"?"github":void 0,workspace:e.GITHUB_WORKSPACE||void 0,serverUrl:i,apiUrl:o,repository:n&&s?{id:n,slug:s}:void 0,runId:e.GITHUB_RUN_ID||void 0,runAttempt:e.GITHUB_RUN_ATTEMPT||void 0,job:e.GITHUB_JOB||void 0,execution(){let c=r("GITHUB_RUN_ATTEMPT");if(!/^[1-9][0-9]*$/.test(c))throw new Error(`GITHUB_RUN_ATTEMPT is "${c}", not a positive whole number`);return{provider:"github",repository:{provider:"github",providerAccountId:r("GITHUB_REPOSITORY_OWNER_ID"),providerRepositoryId:r("GITHUB_REPOSITORY_ID")},providerRunId:r("GITHUB_RUN_ID"),providerRunAttempt:Number(c),workflowRef:r("GITHUB_WORKFLOW_REF")}},takeIdToken(){let c=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 u=>{if(!c||!l)throw new Error("The job cannot request an OIDC token. Give it the `id-token: write` permission.");let d=new URL(c);d.searchParams.set("audience",u);let p=await fetch(d,{headers:{Authorization:`Bearer ${l}`,Accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!p.ok)throw new Error(`GitHub refused the OIDC token request: ${p.status}`);let f=(await p.json().catch(()=>({}))).value;if(typeof f!="string"||!f)throw new Error("GitHub's OIDC token response carried no token");return Ns(f),f}},webIdentity(){return!e.ACTIONS_ID_TOKEN_REQUEST_TOKEN?.trim()||!e.ACTIONS_ID_TOKEN_REQUEST_URL?.trim()?void 0:{token:t.getIDToken??(l=>Zne(l)),runId:e.GITHUB_RUN_ID}},v3RunsOnly:!1,assumesBedrockRole:!1,namesSourceToMcp:!1,checkSourceName(c){for(let l of[c.namespace,c.name])if(!d5.test(l))throw new Error(`"${l}" is not a repository name`)},cloneUrl(c){return`${i}/${c.namespace}/${c.name}.git`},gitAuthEnv(c){return c?{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${i}/.extraheader`,GIT_CONFIG_VALUE_0:$Pe(c)}:{}},async pullRequest({namespace:c,name:l},u,d){if(![c,l].every(h=>d5.test(h)))throw new Error("the repository name is not valid");let p=await a(`${o}/repos/${c}/${l}/pulls/${u}`,d);if(!p.ok)throw new Error(`GitHub answered ${p.status}`);let f=await p.json();return{...typeof f.title=="string"?{title:f.title}:{},...typeof f.body=="string"?{body:f.body}:{},...typeof f.merged=="boolean"?{merged:f.merged}:{},...f.merged===!0&&typeof f.merge_commit_sha=="string"?{mergeCommit:f.merge_commit_sha}:{},...f.merged===!0&&typeof f.head?.sha=="string"?{mergedHead:f.head.sha}:{}}},async commitLookup(c,l,u){let[d,p,...f]=c.split("/");if(f.length||![d,p].every(h=>h!==void 0&&d5.test(h)))return"unknown";try{let h=await a(`${o}/repos/${d}/${p}/commits/${encodeURIComponent(l)}`,u);if(h.status===404||h.status===422)return"missing";if(!h.ok)return"unknown";let A=await h.json();return typeof A.sha=="string"&&A.sha.toLowerCase()===l.toLowerCase()?"found":"missing"}catch{return"unknown"}},async revokeToken(c,l){let u=await l(`${o}/installation/token`,{method:"DELETE",headers:{Authorization:`Bearer ${c}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(Tvt)});if(!u.ok&&u.status!==401)throw new Error(`GitHub answered ${u.status}`)}}}function dd(e=process.env){return Zm(e)?UPe(e):qPe(e)}var Bvt=10*6e4;function HPe(e,t){return e.getTime()-t.getTime()-Bvt}var Wur=10*6e4,Nvt=3e4,_vt=3,ob=class extends Error{constructor(r,n,s){super(r);this.status=n;this.code=s}status;code},BD=class extends Error{};function Pvt(e){let t;try{t=new URL(e)}catch{throw new Error(`skyrampAppOrigin "${e}" is not a URL`)}if(t.protocol!=="https:"||t.origin!==e.replace(/\/+$/,""))throw new Error(`skyrampAppOrigin must be an https origin, got "${e}"`);return t.origin}function Qvt(e,t){if(!sb.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}function Dvt(e,t,r){throw t<500&&t!==429?new ob(e,t,r):new BD(e)}async function Ovt(e,t,r,n){let s=Pvt(e.origin),i;for(let o=1;o<=_vt;o+=1){o>1&&await new Promise(a=>setTimeout(a,(e.retryDelayMs??2e3)*(o-1)));try{let a=await e.idToken(s),c=await(e.fetch??fetch)(new URL(t,s).toString(),{...r(a),redirect:"error",signal:AbortSignal.timeout(Nvt)}).catch(l=>{throw new BD(l instanceof Error?l.message:String(l),{cause:l})});return await n(c)}catch(a){if(a instanceof ob)throw a;i=a}}throw i}function Mvt(e,t,r,n){return Ovt(e,r,i=>({method:t,headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json",Accept:"application/json"},body:t==="GET"?void 0:JSON.stringify(n)}),async i=>{let o=await i.json().catch(()=>({}));if(i.ok)return o.data;let a=o.error?.fields,c=typeof a?.path=="string"&&typeof a.reason=="string"?` at ${a.path}: ${a.reason}`:"",l=`The Skyramp app refused ${t} ${r}: ${i.status} ${o.error?.code??"no error code"}${c}`;return Dvt(l,i.status,o.error?.code)})}var Yur=10*6e4;var Jur=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var Kur=g.object({tests:g.object({placements:g.array(g.unknown()).optional()}).passthrough().optional()}).passthrough(),Xur=g.object({repository:Y8,testType:g.nativeEnum(Im),directory:g.string()}).passthrough();var Zur=g.object({report:g.object({language:g.string()}).passthrough()}).passthrough();var edr=g.object({environment:g.object({components:g.array(g.unknown()).optional(),dependencies:g.array(g.unknown()).optional()}).passthrough()}).passthrough(),tdr=g.object({name:g.string().min(1),provision:g.literal("existing"),url:g.string().min(1),repository:Y8.optional(),revisionUrl:g.string().min(1).optional()}).passthrough(),rdr=g.object({name:g.string().min(1),url:g.string().nullable(),versionUrl:g.string().nullable(),notes:g.string().nullable()}).passthrough();var ndr=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);async function jPe(e,t){return Qvt(e.attemptId,"attempt id"),Mvt(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,IPe({reportUploaded:e.reportUploaded,recipeUploaded:e.recipeUploaded,cancelled:e.cause==="cancelled",timedOut:e.cause==="timed_out",setupFailed:e.cause==="setup_failed",checkoutFailed:e.cause==="checkout_failed",credentialMissing:e.cause==="credential_missing"}))}var Lvt={focused:"Focused",impacted_critical:"Impacted and critical",broad:"Broad"};function _D(e,t){return Va(e,t).length+(e.relatedChanges??[]).filter(r=>r.note).length}function PD(e,t){return e.confirmedRunId===null?"first_qualification":t>0?"delta":"unchanged"}var ND=e=>e.depth?` at depth ${Lvt[e.depth]}`:"",zPe="Sweep the configured scope instead of a diff: every repository of the run, its public surface (endpoints, screens, exported functions) and its existing test suites, and list the behaviors they establish, so triage can plan evidence for them. A finding here is a latent defect of the current state.";function WPe(e,t){switch(PD(e,t)){case"first_qualification":return["This is a scheduled validation, first qualification: the policy has no Confirmed Baseline yet, so this run establishes one. It validates the Target's configured state broadly, not a change.",zPe];case"delta":return[`This is a scheduled validation${ND(e)}. The diff below is everything that changed since the Confirmed Baseline (run ${e.confirmedRunId}), across every source: not one pull request. Review it as the change under validation; there is no PR description.`];case"unchanged":return[`This is a scheduled validation${ND(e)}. Nothing changed since the Confirmed Baseline (run ${e.confirmedRunId}), so there is no diff to review. The state is still under validation: shared services and dependencies can drift.`,zPe]}}var VPe="Plan evidence for the behaviors analyze found: run the existing suites (existing_unit), accept current approved CI evidence, and bring up the SUT only where only runtime evidence will do. The existing suites run under runtime_required too. Do not set a behavior aside as unaffected or out of scope because nothing changed: in a scheduled validation the state itself is under validation. Never conclude success because nothing changed; a run that obtains no evidence validated nothing.";function YPe(e,t){switch(PD(e,t)){case"first_qualification":return["Scheduled validation, first qualification: the policy has no Confirmed Baseline yet. Validate the configured scope broadly; this run's success becomes the Confirmed Baseline.",VPe];case"delta":return[`Scheduled validation${ND(e)}: the files below changed since the Confirmed Baseline (run ${e.confirmedRunId}), across every source. Judge the evidence the policy needs for them, at its depth, as for any change.`];case"unchanged":return[`Change under validation: no change since the Confirmed Baseline (run ${e.confirmedRunId}). This is a scheduled validation${ND(e)}, so decide what evidence the policy needs for the current state now.`,VPe]}}var cb=z(require("fs")),DD=z(require("path"));var tv=z(require("fs")),tc=z(require("path")),ab=tc.join(".skyramp","sut"),JPe=tc.join(".skyramp","workspace.yml");function Uvt(e){return e.startsWith(`${ab}${tc.sep}`)||e.startsWith(".skyramp/sut/")||e===JPe||e===".skyramp/workspace.yml"||/(^|\/)(docker-compose|compose)[^/]*\.ya?ml$/.test(e)||/(^|\/)Dockerfile[^/]*$/.test(e)||/^\.github\/workflows\//.test(e)}function mo(e,t,r={}){let n=t.split(/[\\/]+/).filter(Boolean),s=e;for(let[i,o]of n.entries()){s=tc.join(s,o);let a=tv.lstatSync(s,{throwIfNoEntry:!1}),c=i===n.length-1;if(!a||a.isSymbolicLink()||(c?r.directory?!a.isDirectory():!a.isFile():!a.isDirectory()))return}return n.length?s:void 0}function go(e,t=[]){let r=p=>mo(e,p),n=r(tc.join(ab,"setup.sh")),s=r(tc.join(ab,"teardown.sh")),i=r(tc.join(ab,"get-auth-token.sh")),o=r(JPe),a,c=r(tc.join(ab,"health.json"));if(c)try{let p=JSON.parse(tv.readFileSync(c,"utf-8"));p&&(p.url||p.command)&&(a=p)}catch{}let l,u=r(tc.join(ab,"deploy-budget.json"));if(u)try{let p=JSON.parse(tv.readFileSync(u,"utf-8"));typeof p?.minutes=="number"&&Number.isFinite(p.minutes)&&p.minutes>0&&(l=p.minutes)}catch{}let d=t.filter(Uvt);return{setupScript:n,teardownScript:s,authTokenScript:i,workspaceFile:o,healthHint:a,budgetMinutes:l,present:!!(n||o),staleFiles:d,stale:d.length>0}}function p5(e,t){let{value:r,error:n}=Kt(e);if(n)return{errors:[n]};let s=t&&!t.testEnvironment?$vt(r,t):r,i=gE(s)&&s.schemaVersion===void 0?{schemaVersion:1,...s}:s,{value:o,errors:a}=AE(nx,y4,i);return o?{onboard:o,errors:[]}:{errors:a}}function $vt(e,t){if(!gE(e))return e;let{environment:r,...n}=e,s=[...t.repositorySlug?[{slug:t.repositorySlug,path:t.repositoryPath}]:[],...(t.relatedRepos??[]).map(a=>({slug:a.slug,path:a.path}))],i=a=>typeof a=="string"?s.find(c=>mo(c.path,a))?.slug:void 0,o=Array.isArray(n.components)?n.components.map(a=>{if(!gE(a))return a;let{deployed:c,...l}=a;if(l.repository!==jn)return l;let u=gE(l.from)?l.from.file:void 0,d=i(u)??s[0]?.slug;return d?{...l,repository:d}:l}):n.components;return{...n,components:o}}var QD=".skyramp/sut/health.json",qvt={[QD]:`${QD} (with a url or command)`,".skyramp/workspace.yml":".skyramp/workspace.yml (create it with skyramp_init_scan and skyramp_init_workspace)"};function KPe(){return{name:"onboard-recipe",verify(e,t){let{onboard:r,errors:n}=p5(t.stdout,e.inputs);if(!r)return ce(this.name,n,{fatal:!0});let s=r.environment!==void 0;if(r.status==="blocked")return{name:this.name,passed:!0};let i=e.inputs.repositoryPath,o=go(i),a=s?Wx.filter(u=>mo(i,u)):[];if(a.length>0)return ce(this.name,[`an answer with "environment" tests a deployment where it runs and never starts or stops it: delete ${a.join(" and ")}, keep the health check, and answer "ready" again`]);let l=(s?J_e:Y_e).filter(u=>!mo(i,u)).map(u=>qvt[u]??u);return mo(i,QD)&&!o.healthHint&&l.push(`${QD} (with a url or command)`),o.present&&l.length===0?{name:this.name,passed:!0}:ce(this.name,[`status is "ready" but the recipe deploy replays is incomplete in ${e.inputs.repositoryPath} \u2014 missing (each must be a regular file, not a symlink): ${l.join(", ")}. Write the missing files as the skill specifies and answer "ready" again, or answer "blocked" with the blocker that stopped you.`])}}}function XPe(){return{name:"deployed-revisions",async verify(e,t,r,n){let s={name:this.name,passed:!0},i=e.checkDeployedRevisions;if(!i)return s;let{onboard:o}=p5(t.stdout,e.inputs);if(!o?.environment||o.status==="blocked")return s;let a=gQ(f5(e.inputs.repositoryPath).recipeFiles);if(!a)return s;let c=o.components.map(({name:d,repository:p})=>({name:d,repository:p})),{blockers:l}=await i(a.content,c,o.environment.credentials);if(l.length===0)return s;let u=l.map(d=>`${d.component}: ${d.problem} (${d.evidence})`).join("; ");return n?.retryLeft?ce(this.name,[`Testbot ran ${Pm} twice, with GH_TOKEN, and it failed the check the setup's plan must pass: ${u}. Your session has no GH_TOKEN, so the part that reads GitHub ran in full only there. Fix the script so each component a repository builds gets the full commit it runs, the same on each run, from its own repository, then answer "ready" again, or answer "blocked" with the blocker that stops you.`]):{...s,details:`${Pm} still fails Testbot's check, so the plan is saved blocked: ${u}`}}}}function Gvt(e){try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(e)}catch{return}}function f5(e){let t=[],r=o=>{let a;try{a=cb.readdirSync(DD.join(e,o),{withFileTypes:!0})}catch{return}for(let c of a.sort((l,u)=>l.name.localeCompare(u.name))){let l=DD.posix.join(o,c.name);c.isDirectory()&&!c.name.startsWith(".")?r(l):c.isFile()&&t.push(l)}};mo(e,".skyramp/sut",{directory:!0})&&r(".skyramp/sut"),mo(e,".skyramp/workspace.yml")&&t.push(".skyramp/workspace.yml");let n=[],s=[],i=0;for(let o of t){let a=mo(e,o);if(!a)continue;let l=cb.statSync(a).size;if(l>Nm){s.push({path:o,reason:`larger than ${Nm} bytes`});continue}if(i+l>_m){s.push({path:o,reason:`recipe text over ${_m} bytes in total`});continue}let u=Gvt(cb.readFileSync(a));if(u===void 0||mQ.test(u)){s.push({path:o,reason:"not text"});continue}n.push({path:o,content:u}),i+=l}return{recipeFiles:n,recipeFilesOmitted:s}}function ZPe(e,t){let{onboard:r,errors:n}=p5(t.stdout,e.inputs),s=r&&{...r,...f5(e.inputs.repositoryPath)};return ot(e,"onboard",mr(s,e.secretValues??[]),n)}function OD(e){if(e.state.stages.onboard?.status==="passed")return ee(e,"onboard.json")}var vdr=20*1024*1024;var Dl=z(require("fs")),lb=z(require("path"));var jvt=[/^\.github\//,/^\.gitlab(-ci)?/,/^\.circleci\//,/(^|\/)Jenkinsfile$/,/^docs?\//,/\.(md|mdx|rst)$/i,/(^|\/)LICENSE([._-].*)?$/i,/(^|\/)CODEOWNERS$/,/(^|\/)\.gitignore$/,/(^|\/)\.gitattributes$/,/(^|\/)\.editorconfig$/,/(^|\/)\.prettierrc[^/]*$/,/(^|\/)\.eslintrc[^/]*$/,/(^|\/)eslint\.config\.[^/]+$/,/(^|\/)package-lock\.json$/,/(^|\/)yarn\.lock$/,/(^|\/)pnpm-lock\.yaml$/,/(^|\/)poetry\.lock$/,/(^|\/)Pipfile\.lock$/,/(^|\/)Cargo\.lock$/,/(^|\/)go\.sum$/,/(^|\/)composer\.lock$/,/(^|\/)Gemfile\.lock$/,/\.(png|jpe?g|gif|svg|ico|webp)$/i];function zvt(e){return jvt.some(t=>t.test(e))}function Vvt(e){let t=[],r=e.inputs.repositoryPath;return!r||!Dl.existsSync(r)?t.push(`repository path does not exist: ${r}`):Px(r)?UE(r,e.inputs.baseBranch)||t.push(e.inputs.baseBranch?`base branch "${e.inputs.baseBranch}" does not resolve`:"could not auto-detect a base branch (origin/HEAD, main, master)"):t.push(`not a git repository: ${r}`),{ok:t.length===0,reasons:t}}function Wvt(e){return(e.inputs.relatedRepos??[]).map(t=>{let r=Dl.existsSync(t.path)?of(t.path):void 0;return r?{repository:t.slug,changedFiles:r.changedFiles}:{repository:t.slug,changedFiles:[],note:`could not read the change in ${t.path}`}})}function Yvt(e){let{repositoryPath:t,baseBranch:r}=e.inputs;Dl.rmSync(lb.join(t,Pr),{recursive:!0,force:!0});let n=of(t,r);if(!n)throw new Error(`could not compute git facts for ${t}`);let s=Qx(t,r);if(!s)throw new Error(`could not compute the PR diff for ${t}`);let i=Wvt(e),o=[n.changedFiles,...i.map(d=>d.changedFiles)].flat(),a=o.map(d=>d.path).filter(zvt),c=o.length>0&&a.length===o.length,l={schemaVersion:1,repository:{path:t,currentBranch:n.currentBranch,baseBranch:n.baseBranch},changedFiles:n.changedFiles,...i.length?{relatedChanges:i}:{},newFiles:s.newFiles,deletedFiles:s.deletedFiles,diffStat:s.diffStat,diffBytes:s.diffContent.length,nonApplicationFiles:a,nonApplicationOnly:c,sutRequired:!c};Dl.writeFileSync(lb.join(e.runDir,xm),s.diffContent);let u=lb.join(e.runDir,c4);return Dl.mkdirSync(lb.dirname(u),{recursive:!0}),Dl.writeFileSync(u,JSON.stringify(l,null,2)+`
|
|
335
335
|
`),e.prepared={preflight:l},{preflight:c4,diff:xm}}var eQe={name:"preflight",timeoutMinutes:1,requires:[],validateInput:Vvt,execute:Yvt};var ff=z(require("fs")),dQe=z(require("path"));var MD=z(require("fs"));var Jvt={name:"output-produced",verify(e,t,r){let n=e.outputFileFor(r.name);return(MD.existsSync(n)?MD.readFileSync(n,"utf-8"):"").trim().length>0?{name:this.name,passed:!0}:{name:this.name,passed:!1,details:`stage produced no output (${n} empty or missing)`}}},Kvt=["Re-read the stage instructions above and confirm every task was completed.","If you find a mistake or an incomplete task, fix it now before finishing.","End your response with a one-line summary of what this stage accomplished."];function ar(e){let t=e.requires??[];return{name:e.name,model:e.model??"sonnet",maxAttempts:e.maxAttempts,effort:e.effort,timeoutMinutes:e.timeoutMinutes??15,scaleTimeout:e.scaleTimeout,requires:t,softRequires:e.softRequires,validateInput:e.validateInput??(()=>({ok:!0,reasons:[]})),buildPrompt:e.buildPrompt??(()=>`You are the "${e.name}" stage of the Skyramp Testbot.`),selfVerification:e.selfVerification??Kvt,exitGates:e.exitGates??[Jvt],prepare:e.prepare,abortIf:e.abortIf,onAbort:e.onAbort,teardown:e.teardown,buildMcpServers:e.buildMcpServers,buildReadDirs:e.buildReadDirs,buildPluginDirs:e.buildPluginDirs,buildSettings:e.buildSettings,namesSession:e.namesSession,resumeFrom:e.resumeFrom,requiredSkills:e.requiredSkills,buildSessionEnv:e.buildSessionEnv,allowedTools:e.allowedTools,buildDisallowedTools:e.buildDisallowedTools,captureTrace:e.captureTrace,onPassed:e.onPassed,passReason:e.passReason,adversarialReview:e.adversarialReview,retryHint:e.retryHint,beforeGates:e.beforeGates,afterAttempt:e.afterAttempt,salvage:e.salvage,checkpoint:e.checkpoint,needsSutAuth:e.needsSutAuth,triageBranch:e.triageBranch,branchSkipClears:e.branchSkipClears,branchRequires:e.branchRequires}}var rv=require("child_process");var eg=z(require("fs")),rc=z(require("path"));function tQe(e,t,r){let n=r.indexOf("/");if(n<=0)return!1;let s=nQe(e,t,r.slice(0,n)),i=r.slice(n+1);return!!(s&&i&&yi(s,i))}function nQe(e,t,r){if(!r||r==="."||r===".."||r.includes("/")||r.includes(rc.sep))return;let n=rc.resolve(e),s=rc.join(rc.dirname(n),r);if(!(s===n||t.some(i=>rc.resolve(i)===s))&&eg.existsSync(rc.join(s,".git")))try{let i=(0,rv.execFileSync)("git",[...bs,"rev-parse","--show-toplevel"],{cwd:s,encoding:"utf-8",env:Ye(),stdio:["ignore","pipe","ignore"]}).trim();return eg.realpathSync(i)===eg.realpathSync(s)?s:void 0}catch{return}}var rQe=6e4;function Xvt(e){return _r(Ax,e).errors}function h5(e,t=[]){let{value:r,error:n}=Kt(e,t);if(n)return{errors:[n]};let s=Xvt(r);return s.length>0?{errors:s}:{analysis:r,errors:[]}}function FD(e,t=[]){return h5(e.stdout,t)}var sQe=Hn("analysis-schema",(e,t)=>FD(t,e.secretValues));function Ol(e){let t=e.split("\u2014")[0].split(" ")[0].trim(),r=t.match(/^(.*?):\d+/);return(r?r[1]:t.replace(/:$/,"")).trim()}function Zvt(e){let t=e.split("#")[0].trim(),r=Ol(t);return/\.[A-Za-z0-9]+$/.test(r)||r.includes("/")||/:\d+$/.test(t)?r:void 0}function eRt(e,t){let r=e.match(/^(.*?)\s*\((\d+)\s*files?\)\s*$/i),n=(r?r[1]:e).trim(),s=r?Number(r[2]):void 0;if(t.has(n))return{isPattern:!1,claimedCount:s,matched:[n]};if(!/[*?]/.test(n))return{isPattern:!1,claimedCount:s,matched:[]};let i=new RegExp("^"+n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\0").replace(/\*/g,"[^/]*").replace(/\0/g,".*").replace(/\?/g,"[^/]")+"$");return{isPattern:!0,claimedCount:s,matched:[...t].filter(o=>i.test(o))}}function ub(e,t,r=[]){for(let i of[...r].sort((o,a)=>a.length-o.length)){let o=i.replace(/\/+$/,"")+"/";if(e.startsWith(o))return e.slice(o.length)}let n=e,s=!1;for(let i of[...t].sort((o,a)=>a.length-o.length)){let o=i.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&"),a=String.raw`(?:\s*(?::|→|->|—|–|-|/)\s*)?`,c=new RegExp(`${a}[\\s([{<]*${o}[\\s)\\]}>]*${a}`,"g"),l=n.replace(c," ");l!==n&&(s=!0),n=l}return n=n.replace(/\s+/g," ").trim(),s?n.replace(/^\/+/,""):n}var iQe={name:"analysis-grounded",async verify(e,t){let{analysis:r,errors:n}=FD(t);if(!r)return ce(this.name,n);let s=e.inputs.repositoryPath,i=of(s,e.inputs.baseBranch);if(!i)return ce(this.name,[`could not compute git facts for ${s}`]);let o=new Set(i.changedFiles.map(V=>V.path)),a=new Set,c=[s,...(e.inputs.relatedRepos??[]).map(V=>V.path)],l=[],u=new Map;for(let V of e.inputs.relatedRepos??[]){for(let X of[V.slug,V.slug.split("/").pop()])X&&a.add(X);let N=of(V.path);if(!N){l.push(V.slug);continue}for(let X of N.changedFiles)o.add(X.path);u.set(V.slug,new Set(N.changedFiles.map(X=>X.path)))}let d=[],p=[...r.endpoints.new,...r.endpoints.modified,...r.endpoints.removed],f=r.endpoints.removed.length>0||p.some(V=>V.method.toUpperCase()==="DELETE"),h=r.unexamined.some(V=>/model|schema|entit|migration/i.test(V));f&&r.entityMap.entities.length>0&&r.entityMap.references.length===0&&!h&&d.push("the change removes or deletes something, entityMap names entities, but entityMap.references is empty \u2014 map the INBOUND references to the affected entity (which other entities point at it, and what happens to them on delete), or list the models/schema files you could not examine in `unexamined`");for(let V of r.diff.changedFiles){let N=ub(V,a,c);if(o.has(N))continue;let X=eRt(N,o);if(X.matched.length===0&&l.length>0){d.push(`could not read ${l.join(", ")} to verify "${N}" \u2014 a related checkout of a multi-repo run must be readable for changedFiles to be grounded`);continue}X.matched.length===0?d.push(X.isPattern?`diff.changedFiles pattern "${N}" matches nothing git reports as changed`:`diff.changedFiles claims "${N}" which git does not report as changed`):X.claimedCount!=null&&X.claimedCount!==X.matched.length&&d.push(`diff.changedFiles says "${N}" but that pattern matches ${X.matched.length} changed file(s), not ${X.claimedCount}`)}let A,C=()=>{if(!A)try{A=(0,rv.execFileSync)("git",[...bs,"ls-files"],{cwd:s,encoding:"utf-8",env:Ye()}).split(`
|
|
336
336
|
`).filter(Boolean)}catch{A=[]}return A},w=(e.inputs.relatedRepos??[]).map(V=>V.path),E=(V,N)=>{if(!V)return;let X=ub(V,a,c);if(o.has(X)||yi(s,X)||w.some(dt=>yi(dt,X))||tQe(s,w,X))return;let se=`/${X}`,ue=C().filter(dt=>dt.endsWith(se));if(ue.length===0&&w.length>0)for(let dt of w)try{if((0,rv.execFileSync)("git",[...bs,"ls-files"],{cwd:dt,encoding:"utf-8",env:Ye()}).split(`
|
|
337
337
|
`).some(vr=>vr&&(vr===X||vr.endsWith(se))))return}catch{}if(ue.length!==1){if(ue.length>1){d.push(`${N} cites "${X}" which matches ${ue.length} files (${ue.slice(0,3).join(", ")}) \u2014 cite the repository-relative path`);return}d.push(`${N} cites "${X}" which does not exist in the repository`)}};for(let V of["new","modified","removed"])r.endpoints[V].forEach((N,X)=>E(Ol(N.evidence),`endpoints.${V}[${X}].evidence`));r.services.forEach((V,N)=>E(Ol(V.evidence),`services[${N}].evidence`)),r.findings.forEach((V,N)=>E(V.file,`findings[${N}].file`)),r.behaviors.forEach((V,N)=>E(Ol(V.evidence),`behaviors[${N}].evidence`));let I=je(e.inputs);if(I.length>1){let V=Va(Ir(e)??{changedFiles:i.changedFiles},I[0].slug);r.behaviors.forEach((N,X)=>{let se=vm(I,N.repository);se||d.push(`behaviors[${X}].repository ${N.repository} is not a repository of this run (${I.map(dt=>dt.slug).join(", ")})`);let ue=ub(Ol(N.evidence),a,c);se&&ue&&!yi(se.path,ue)&&!yE(V,se.slug,ue)&&d.push(`behaviors[${X}].evidence cites "${ue}", which is not in ${se.slug} \u2014 set "repository" to the checkout the file is in, and cite its repository-relative path`)})}let x=r.behaviors.map(V=>(V.surface??"").toLowerCase());for(let V of["new","modified"])for(let N of r.endpoints[V]){let X=`${N.method} ${N.path}`.toLowerCase();!x.some(ue=>ue.includes(N.path.toLowerCase())||X.includes(ue)||ue.includes(X))&&!r.unexamined.some(ue=>ue.includes(N.path))&&d.push(`endpoints.${V} ships "${N.method} ${N.path}" but no behaviors[] entry describes it \u2014 say what the change makes true there, or list it in \`unexamined\``)}r.existingTests.locations.forEach((V,N)=>E(V.dir,`existingTests.locations[${N}].dir`));let v=(V,N)=>{if(yi(V,N))return!0;try{return(0,rv.execFileSync)("git",[...bs,"ls-files"],{cwd:V,encoding:"utf-8",env:Ye()}).split(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@skyramp/testbot-core",
|
|
3
|
-
"version": "0.0.0-pr597.
|
|
3
|
+
"version": "0.0.0-pr597.125",
|
|
4
4
|
"description": "Skyramp Testbot engine: AI-powered deterministic test generation, execution and maintenance",
|
|
5
5
|
"main": "dist/main.js",
|
|
6
6
|
"//files": "An explicit allowlist, never a glob. `dist/` is gitignored, so without this key npm's .gitignore fallback would publish a package with no engine in it; with a glob it would publish the sourcemaps, whose sourcesContent embeds every src/*.ts verbatim. eval-entry.js is a development entry and must not ship. dist/VERSION.json exists only in a release-engine.yml build. assets/gen-reference/ is the staged codegen reference corpus, which generate.ts finds at ../assets from dist/.",
|