@skyramp/testbot-core 0.13.0-v3.384 → 0.13.0-v3.385

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/post.js CHANGED
@@ -159,7 +159,7 @@ health check cancelled`,c(1)},p=setTimeout(u,Math.max(1,t.deadlineMs-Date.now())
159
159
  %{http_code}`,...Pme(r),i],{deadlineMs:Math.min(e,Date.now()+25e3),signal:t});if(o.exitCode!==0)return{error:(o.stderr||"curl failed").trim()};let a=o.stdout??"",c=a.lastIndexOf(`
160
160
  `),u=Number(a.slice(c+1).trim());return{status:Number.isFinite(u)?u:0,body:a.slice(0,c)}},async runCommand(i,r){let{steps:s,reason:o}=of(i);if(!s)return{exitCode:1,output:`${qH}${o}`};let a="";for(let c of s){if(Date.now()>=e)return{exitCode:1,output:"health check time limit reached"};let u=await GH(c,{cwd:r,deadlineMs:Math.min(e,Date.now()+6e4),env:It(),signal:t});if(a+=`${u.stdout??""}${u.stderr??""}`,u.exitCode!==0)return{exitCode:u.exitCode,output:a}}return{exitCode:0,output:a}}}}function Pme(e){return e?Object.entries(e).flatMap(([t,n])=>["-H",`${t}: ${n}`]):[]}function JH(e){return e.trim().replace(/^\.\//,"").replace(/\/+$/,"")}function Ume(e){if(!e.inputs)return[];let t=Ui(e),n=r=>{let s=typeof r=="string"?r:r?.path??r?.file;return typeof s=="string"&&s.trim()?JH(s):void 0},i=(r,s)=>r?(s??[]).flatMap(o=>{let a=n(o);return a?[{repository:r,path:a}]:[]}):[];return[...i(yo(e.inputs).slug,[...t?.changedFiles??[],...t?.newFiles??[]]),...(t?.relatedChanges??[]).flatMap(r=>i(r.repository,r.changedFiles))]}function Fme(e,t){let n=Po.resolve(e.inputs.repositoryPath,t.trim()),i=VS(e.inputs,n),r=i&&Po.relative(i.path,n);return i&&r?{repository:i.slug,path:r.split(Po.sep).join("/")}:void 0}function wv(e=ST(),t={}){let n=t.budgetMs??Qme,i=t.intervalMs??$me;return{name:"deploy-health",async verify(r,s){if(r.signal?.aborted)return{name:this.name,passed:!1,details:"health check cancelled"};let{deploy:o,errors:a}=Bc(s,r.inputs?.repositoryPath,r.secretValues);if(!o)return{name:this.name,passed:!1,details:a.slice(0,6).join("; ")};if(o.outcome==="bringup-failed")return{name:this.name,passed:!0};if(o.outcome==="change-broke-bringup"){let v=Ume(r),S=(o.suspectFiles??[]).map(JH),B=S.filter(z=>{let Z=Fme(r,z);return!!Z&&Mm(v,Z.repository,Z.path)});return v.length>0&&B.length===0?{name:this.name,passed:!1,details:`change-broke-bringup claimed, but none of suspectFiles [${S.slice(0,4).join(", ")}] is a file this PR changed \u2014 that is not attributable to the PR. Re-run bring-up; if it still fails for a reason outside the diff, record outcome "bringup-failed" (with bringupError) instead.`}:{name:this.name,passed:!0}}let c=o.health;if(!c)return{name:this.name,passed:!1,details:"health is missing although the app is recorded as up"};let u=Object.values(c.headers??{}).some(v=>/<[^>]+>/.test(String(v))),d=(v,S=!1)=>({ok:!1,details:v,transient:S}),p=async()=>{if(!jk(c.url,Ez(r)))return d(`health url ${c.url} is not the app under test \u2014 this gate probes only loopback, the Test Environment's address or an address the Target's settings give, never an arbitrary destination. Record the URL the deployed app actually answers on.`);let v=await e.httpGet(c.url,c.headers);if("error"in v)return d(`health url ${c.url} unreachable: ${v.error}`,!0);let S=Number(c.status??200);if(v.status!==S)return d(`health url returned ${v.status}, expected ${S}`,!0);if(!v.body.trim())return d("health url returned empty body \u2014 must return data",!0);let B=(c.output??"").trim();if(B){let z=jH(B,v.body);if(!z.ok)return d(`health url ${c.url} no longer answers as recorded \u2014 ${z.why}. Either the app is not answering as it did at deploy time, or health.output is not verbatim: record ONLY the response body, with no commentary appended.`)}return{ok:!0}},A=async()=>{let v=await e.runCommand(c.command,r.inputs.repositoryPath),S=v.output.startsWith(qH);if(v.exitCode!==0)return d(`health command exited ${v.exitCode}: ${v.output.slice(0,200)}`,!S);if(!v.output.trim())return d("health command produced no output",!0);let B=(c.output??"").trim();if(B.length<16)return d(`health command output "${B}" is too thin to be a data check \u2014 the check must return real application data, not a status token`);let z=jH(B,v.output);return z.ok?{ok:!0}:d(`health command did not reproduce its recorded check \u2014 ${z.why}. Either the app is not answering as it did at deploy time, or health.output is not verbatim: record ONLY what the command wrote, with no commentary appended.`)},h;if(c.command&&(u||!c.url))h=A;else{if(c.url&&u)return{name:this.name,passed:!1,details:`health.headers contains a documented placeholder (${Object.entries(c.headers??{}).filter(([,v])=>/<[^>]+>/.test(String(v))).map(([v])=>v).join(", ")}), and this gate RE-EXECUTES the probe \u2014 a placeholder cannot authenticate. Record a health.command instead (a script that fetches its own token and hits the URL); do not put a real credential in the artifact.`};c.url?h=p:c.command&&(h=A)}if(!h)return{name:this.name,passed:!1,details:"health has neither url nor command"};let g=Date.now(),y=g+n,b=await h();for(;!b.ok&&b.transient&&!r.signal?.aborted&&Date.now()+i<y&&(await new Promise((v,S)=>{let B,z=fe=>{clearTimeout(B),r.signal?.removeEventListener("abort",Z),fe?S(fe):v()},Z=()=>z();if(r.signal?.addEventListener("abort",Z,{once:!0}),r.signal?.aborted){z();return}t.sleep?t.sleep(i).then(()=>z(),z):B=setTimeout(()=>z(),i)}),!r.signal?.aborted);)b=await h();if(r.signal?.aborted)return{name:this.name,passed:!1,details:"health check cancelled"};if(b.ok)return{name:this.name,passed:!0};let E=Math.round((Date.now()-g)/1e3);return{name:this.name,passed:!1,details:b.transient&&E>0?`${b.details} (still failing after ${E}s)`:b.details}}}}function kT(e){return BT(e)&&lA(e).length===0&&CT(e.inputs?.sharedEnvironment).length===0}function BT(e){let t=Ome(e);if(!t&&e.state.stages.deploy?.status!=="passed")return!1;let n=Ke(e,"deploy.json");return n?HH(n):!t}function HH(e){return e?.outcome==="clean"||e?.outcome==="recipe-drift"}function Ome(e){let t=e.state.stages.plan,n=e.state.stages.deploy;return!(e.inputs?.pipeline?e.inputs.pipeline==="two-step":!n)||t?.status!=="passed"?!1:!n||n.updatedAt<=t.updatedAt}async function Mme(e,t,n){let i=new URL(t.url).origin;return(URL.canParse(e.url)?new URL(e.url).origin:e.url)===i?vv(e.url,n):{error:`${e.url} is not on ${i}, where ${t.name} runs`}}async function Lme(e,t,n){let i=bv(e.inputs??{}),r=[];for(let s of t){let o=i.find(d=>d.name===s.component);if(!o){r.push(`revisions names "${s.component}", which is not a shared component listed for a revision check`);continue}let a=await Mme(s,o,n);if("error"in a){r.push(`the revision check of ${o.name} could not be re-run: ${Oi(a.error,e.secretValues??[]).slice(0,200)}`);continue}let c=Ev(o.expectedRevision,{body:s.output}),u=Ev(o.expectedRevision,a);c.observedRevision!==u.observedRevision&&r.push(`the revision check of ${o.name} names ${u.observedRevision??"no commit"} when re-run, but its recorded output names ${c.observedRevision??"no commit"} \u2014 record what the check returned, verbatim, or leave the component out`)}return r}function YH(e){return{name:"shared-revisions",async verify(t,n){let{deploy:i}=Bc(n,t.inputs?.repositoryPath,t.secretValues),r=await Lme(t,i?.revisions??[],e);return r.length?{name:this.name,passed:!1,details:r.join("; ")}:{name:this.name,passed:!0}}}}async function WH(e,t,n){let i=e.inputs?.sharedEnvironment;if(!IT(i))return{};let{deploy:r}=Bc(t,e.inputs.repositoryPath,e.secretValues),s=await NH(i,r?.revisions??[],n,e.secretValues??[]);return yn(e,Jl,Oi(s,e.secretValues??[]),[])}function ZH(e,t){let{deploy:n,errors:i}=Bc(t,e.inputs?.repositoryPath,e.secretValues),r=n?.health?.headers?{...n,health:{...n.health,headers:Object.fromEntries(Object.keys(n.health.headers).map(o=>[o,"<redacted>"]))}}:n,s=Oi(r,e.secretValues??[]);return yn(e,"deploy",s,i)}var rDe=10*6e4;var Sv=(r=>(r.RestApi="rest-api",r.Frontend="frontend",r.FullStack="full-stack",r.Other="other",r))(Sv||{}),Rc=(r=>(r.Critical="critical",r.High="high",r.Medium="medium",r.Low="low",r))(Rc||{}),xc=(i=>(i.Suspected="suspected",i.Latent="latent",i.Refuted="refuted",i))(xc||{}),QT=(i=>(i.Skyramp="skyramp",i.External="external",i.Unknown="unknown",i))(QT||{}),$T=(r=>(r.Cascade="cascade",r.Restrict="restrict",r.Orphan="orphan",r.Unknown="unknown",r))($T||{}),qi=(r=>(r.RequirementReference="requirement-reference",r.Spec="spec",r.PrDescription="pr-description",r.CouldBreak="could-break",r))(qi||{}),lt=l.string().trim().min(1),Hl=lt.describe("file:line"),KH=e=>lt.refine(t=>t.length<=400,t=>({message:`is ${t.length} characters, over the 400 cap \u2014 ${e}`})),dA=lt.optional().describe('multi-repo only: the OTHER checkout this lives in \u2014 its "owner/repo" slug, or the directory name if the run discovered it; omit for the working checkout'),xT=l.object({method:lt,path:lt,service:l.string().optional(),evidence:Hl,repository:dA}),Hme=l.object({id:lt.describe("short-slug, e.g. R9"),statement:lt.max(400,"exceeds 400 characters \u2014 state the requirement, do not paste the spec section").describe("a testable obligation, not a summary"),source:l.nativeEnum(qi).describe("spec outranks pr-description when both state it"),evidence:lt.describe("spec: file:line or a section locator. pr-description: the quoted phrase it comes from.")}),Yme=l.object({id:lt.describe("short-slug"),statement:lt.max(400,"exceeds 400 characters \u2014 state the behaviour, do not paste the code").describe("what the change makes true"),surface:lt.describe("METHOD /path, or a component/page name"),evidence:lt.describe("file:line from the diff that introduces it"),repository:dA,satisfies:l.array(lt).optional().describe("requirement ids (from `requirements`) this behaviour correctly implements \u2014 a requirement met only in part is ALSO named by the finding that shows the rest (conflictsWith)")}),Wme=l.object({id:lt.describe("short-slug"),file:lt,line:l.number().optional(),claim:KH("shorten it to the one sentence that states the defect, and move the supporting detail into `evidence`"),severity:l.nativeEnum(Rc),evidence:KH("cite the file:line and the one line that shows it, rather than reproducing the surrounding code").describe("quoted diff/code line"),status:l.nativeEnum(xc),repository:dA,conflictsWith:l.array(lt).optional().describe("requirement ids (from `requirements`) this defect contradicts or leaves unimplemented \u2014 a lower-precedence source (the diff, or the PR description) lost")}),Zme=l.object({name:lt,language:l.string().optional(),framework:l.string().optional(),evidence:Hl,repository:dA}),Kme=l.object({dir:lt,framework:l.string().optional(),kind:l.nativeEnum(QT),evidence:Hl,repository:dA}),Xme=l.object({from:lt,to:lt,onDelete:l.nativeEnum($T),evidence:Hl}),eye=l.object({entity:lt,field:lt,values:l.array(l.string()),evidence:Hl}),tye=l.object({entities:l.array(l.object({name:lt,evidence:Hl})),references:l.array(Xme).describe("INBOUND references \u2014 what still points at an entity when it is deleted"),stateFields:l.array(eye)}),TT=l.object({schemaVersion:l.literal(1),repository:l.object({path:lt.describe("absolute repo path"),currentBranch:lt,baseBranch:lt}),project:l.object({type:l.nativeEnum(Sv),primaryLanguage:lt,languages:l.array(l.string()),frameworks:l.array(l.string())}),services:l.array(Zme),infrastructure:l.object({containerized:l.boolean(),hasDockerCompose:l.boolean(),composeFiles:l.array(l.string()),hasCiCd:l.boolean()}),diff:l.object({changedFiles:l.array(l.string()).describe("as git reports them; a file in another checkout may carry that repo's name"),nonApplicationOnly:l.boolean(),summary:lt.describe("\u2264400 chars")}),endpoints:l.object({new:l.array(xT),modified:l.array(xT),removed:l.array(xT)}),existingTests:l.object({locations:l.array(Kme)}),entityMap:tye,requirements:l.array(Hme).describe("from a spec (attached or linked) and/or the PR description; empty when neither states a testable obligation"),behaviors:l.array(Yme),findings:l.array(Wme),unexamined:l.array(l.string()).describe("files or areas outside this change you did not open"),summary:lt.describe("one paragraph on what this change does and its test-relevant risk")});var sye=l.object({route:l.string().describe('the page this step happens on, e.g. "/products/:id"'),action:l.string().describe('what the user does there, through the UI, e.g. "clicks Add to cart"'),clauses:l.array(l.string()).optional().describe("the plan clause ids this step exercises"),check:l.string().optional().describe("what the user then sees that shows the step worked; the test asserts it")}),pA=(n=>(n.InProcess="in-process",n.Browser="browser",n))(pA||{}),XH=(i=>(i.Spec="spec",i.PrDescription="pr-description",i.Inferred="inferred",i))(XH||{}),eY=l.object({id:l.string().describe('e.g. "J1"'),name:l.string().describe(`the flow in a user's words, e.g. "buy a product with a coupon"`),entry:l.string().describe("the route the user starts the flow on: the app's normal starting page for it, never a deep link into its middle"),steps:l.array(sye).describe("every step, in order, from the entry page to the outcome: at least two"),outcome:l.string().describe("what the user sees at the end that shows the flow worked: every part of it"),finishes:l.string().optional().describe('the user action that completes the task, verb first, e.g. "places the order"; the journey walks on to it'),kind:l.nativeEnum(pA).optional().describe("in-process when the repo's in-process tests (components, app routes) can walk the whole flow and check it; else browser"),source:l.nativeEnum(XH).optional().describe("spec or pr-description when one describes this flow (quote it under evidence), else inferred"),evidence:l.string().optional().describe("for spec or pr-description: its words that describe the flow"),testFile:l.string().describe("the browser test file it goes in, beside the repo's existing e2e tests")}),kv=l.object({journey:l.string().describe("the plan's journey id"),file:l.string().describe("the browser test file that walks it"),brokeAt:l.object({step:l.number().int().describe("the 1-based step whose check failed first"),expected:l.string(),actual:l.string().describe("what the app did instead, from the runner's output"),notReached:l.array(l.number().int()).optional().describe("later steps the test could not get to")}).optional().describe("only when the journey's test failed on a check: where"),test:l.string().describe("the title of the one test in that file that walks it end to end")});var hDe=Object.fromEntries([...["ts","tsx","mts","cts","js","jsx","mjs","cjs"].map(e=>[e,"node"]),...["java","kt","kts","groovy","scala"].map(e=>[e,"jvm"]),["py","python"],["go","go"]]);var gDe=["stale_test","open_question"],mDe=["low","medium","high","critical"];var tY=String.raw`(?:\[[^\]]*\]|\([^)]*\))`,oye=String.raw`(?:["'\u201c\u2018\x60]|\*{1,2})?[^\s:"'\u201c\u201d\u2018\u2019\x60*()[\],]+(?:["'\u201d\u2019\x60]|\*{1,2})?`,nY=String.raw`(?:${tY}|${oye}(?:\s*${tY})?)`,rY=String.raw`(?:\s*:|\s+[\u2014\u2013-])`,vDe=new RegExp(String.raw`^\s*(?:${nY}(?:,\s*${nY})*(?::L?\d+(?:[-\u2013]\d+)?${rY}?|${rY})|\[[^\]\s]+\]|\([^)\s]+\))\s+`);var Rs=l.string().trim().min(1),xs=72,aye=l.object({repository:Rs.optional().describe("owner/repo of the checkout this lint ran in, when the run has several; omit for the working checkout"),tool:l.string(),command:l.string().describe("the exact command you ran, scoped to the changed files"),clean:l.boolean(),fixed:l.array(l.string()).optional().describe("files you fixed"),uncovered:l.array(l.string()).describe("changed/new files this linter's own config does not match (wrong extension, wrong directory) \u2014 so `clean` never examined them, even though CI may still execute them. Empty array, not omitted, when every changed/new file IS covered.")}),_T=l.object({schemaVersion:l.literal(1),lint:l.array(aye).min(1).describe("one entry per checkout this run wrote tests in, each run from that checkout"),fileConventions:l.object({ok:l.boolean(),notes:l.string().optional()}),ciReadiness:l.object({covered:l.boolean().describe("will the repo's CI run these tests?"),notes:l.string().optional()}),dependencies:l.object({added:l.array(l.object({package:l.string(),manifest:l.string(),repository:Rs.optional().describe("owner/repo of the manifest's checkout; omit for the working checkout"),reason:Rs.optional().describe("why the test must run inside the application's own test environment, so its manifest had to change \u2014 required for every entry")})).describe("every package added to an APPLICATION manifest (an exception, surfaced in the report); never the Testbot test package's own")}),support:l.array(l.object({file:Rs,repository:Rs.optional().describe("owner/repo of the file's checkout; omit for the working checkout")})).optional().describe("the files the tests need besides themselves (helper modules, page objects, fixtures, snapshots), delivered with them"),commit:l.object({message:Rs.refine(e=>e.split(`
161
161
  `)[0].length<=xs,{message:`subject line must be <= ${xs} chars`})}),pr:l.object({title:Rs.max(xs,`must be <= ${xs} chars`),body:Rs}),ready:l.boolean().describe("a statement of fact: true only if the tests are fit to commit as they stand"),blockers:l.array(l.string()).describe("what blocks the commit \u2014 required non-empty when ready is false"),summary:Rs.describe("one paragraph")});function fA(e){return(e?.blockers??[]).slice(0,3).join("; ")}var Fo=ce(require("fs")),Zl=ce(require("path")),aY=require("child_process");var wn="{junit}",Bv=(r=>(r.Junit="junit",r.Trx="trx",r.GoTestJson="go-test-json",r.JestJson="jest-json",r))(Bv||{}),DT=(t=>(t.Minitest="minitest",t))(DT||{}),iY=l.string().trim().min(1),Yl=l.object({cwd:iY.describe('repo-relative directory the command starts in ("." for the root)'),argv:l.array(iY).min(1).describe(`the command as separate arguments, run without a shell; for a junit or trx report an argument or env value holds ${wn}, where the report is written (not for Maven or Gradle, whose build writes its own)`),env:l.record(l.string(),l.string()).optional().describe("plain test or reporter settings beyond the repository's CI test job (RAILS_ENV=test, PLAYWRIGHT_JUNIT_OUTPUT_FILE={junit}); never a credential, PATH, or a tool's install path"),report:l.object({format:l.nativeEnum(Bv).describe(`junit (JUnit XML to ${wn}), trx (to ${wn}), jest-json (Jest's --json or Vitest's --reporter=json, --outputFile=${wn}), or go-test-json (go test -json on the command's output)`),reporter:l.nativeEnum(DT).optional().describe("a reporter Testbot loads for a runner that writes no report: minitest")}).optional().describe("the report the command writes; junit when omitted")});var Wl="a framework other than pytest, jest, vitest and node --test (go test, rails test, mvn, dotnet test), or one the repository's test script runs through another command (ng test, nx test)",kDe=`pytest, Jest, Vitest and node --test tests run as the run already knows them, unless the repository's test script runs them through another command (ng test, nx test), which may be the only one that compiles them. A test in any other framework, or one run that way, also gives "run": the repository's own command for only those tests, from the directory the repository runs it in, as separate arguments without a shell. Its "report" says what the runner writes: junit (JUnit XML to ${wn} in the reporter's argument or env setting), trx (a TRX file to ${wn}, which every dotnet test writes with its built-in logger), jest-json (Jest's --json --outputFile=${wn}, or Vitest's --reporter=json --outputFile=${wn}: built in, no reporter package), or go-test-json (go test -json, read from the command's output). A Maven or Gradle command names no ${wn}: its build writes JUnit XML to its own report directory, which the run reads. Use a reporter the repository already has, or one of those; a reporter or converter the command fetches is the version the repository pins, or else its latest release (an older one may not build with the repository's toolchain). For minitest, which writes none, give report.reporter "minitest" and the run fills ${wn} itself. A setting the tests or reporter read goes in "env" (RAILS_ENV=test, or PLAYWRIGHT_JUNIT_OUTPUT_FILE=${wn} with playwright test --reporter=junit): the run sets it, so never wrap the command in a shell to set one. The run replaces ${wn} in argv and env with its report path, executes the command, and reads that report.`;var Uo=(r=>(r.ExistingEvidenceSufficient="existing_evidence_sufficient",r.TargetedUnit="targeted_unit",r.RuntimeRequired="runtime_required",r.BlockedPreflight="blocked_preflight",r))(Uo||{}),Qs=(s=>(s.ExistingEvidence="existing_evidence",s.Unaffected="unaffected",s.ExistingUnit="existing_unit",s.NewUnit="new_unit",s.Runtime="runtime",s))(Qs||{}),NT=(n=>(n.Repository="repository",n.Testbot="testbot",n))(NT||{}),PT=(i=>(i.Identified="identified",i.Passed="passed",i.Failed="failed",i))(PT||{}),or=l.string().trim().min(1),cye=l.string().regex(/^[a-z0-9][a-z0-9-]*$/,"must be a short lowercase slug").describe("short-slug");var uye=l.object({id:cye,source:l.nativeEnum(NT),kind:l.nativeEnum(fo),outcome:l.nativeEnum(PT),summary:or.max(400).describe("one line: what it shows"),tests:l.array(or).optional().describe("source repository: the existing tests, as repo-relative paths, optionally path::test-name"),repository:or.optional().describe("source repository: owner/repo the tests live in, when the run has several checkouts; omit for the working checkout"),command:or.optional().describe("source testbot: the exact command you ran, as you ran it"),run:Yl.optional().describe(`source repository, for tests in ${Wl}: how the run executes the whole of each of these test files, all of them in one command, never narrowed to the named tests and never only listed, with the repository's own runner writing JUnit XML to {junit}. A test is credited to a file only by its name or by a report that names the file`)}),lye=l.object({behaviorId:or.describe("an id from analyze's behaviors"),mechanism:l.nativeEnum(Qs),evidenceIds:l.array(or).default([]).describe("existing_evidence: the ci-<n> or evidence ids that establish it; existing_unit: the evidence id naming the tests to run"),covers:l.string().trim().optional().describe('new_unit / runtime: the missing evidence this obtains, e.g. "the boundary the change moved"; unaffected: why the change cannot reach it, citing path:line')}),UT=(i=>(i.Browser="browser",i.RunningApp="running-app",i.Outside="outside",i))(UT||{}),dye=l.object({behaviorId:l.string().trim().optional().describe("an id from analyze's behaviors, when it is about one"),missing:or.max(600).describe("the evidence that is required and cannot be obtained in this run"),needs:l.nativeEnum(UT).optional().describe("what that evidence needs: browser (only a real browser shows it), running-app (only the running app or its server shows it: its real requests, sign-in and permissions, what it saves), or outside (something the running app here could not give either: a third-party service it calls, hardware)")}),pye=l.object({file:or.describe("the changed file the failure is in"),repository:or.optional().describe("owner/repo the file is in, when the run has several checkouts; omit for the working checkout"),reason:or.max(300).describe("what prerequisite the change fails"),evidence:or.max(400).describe("the error line, quoted")}),fye=l.object({behaviorId:or.describe("an id from analyze's behaviors"),reason:or.max(600).describe("\u2264600 characters: why this change leaves the behavior's result as it was, citing the unchanged line that decides it (path:line)")}),AA=l.object({schemaVersion:l.literal(1),decision:l.nativeEnum(Uo),evidence:l.array(uye).describe("evidence this session found or produced; CI results are the ci-<n> items and are not restated here"),plan:l.array(lye).describe("how each changed behavior's evidence is obtained"),gaps:l.array(dye),outOfScope:l.array(fye).optional().describe("behaviors analyze found that this change neither changes nor states"),blocked:pye.optional().describe("only for blocked_preflight"),rationale:or.max(1200).describe("\u22641200 characters: why this evidence is enough, or what it still lacks \u2014 the scope you chose and why")});function hA(e){let t=Ke(e,"recommend.json");if(!t||!Array.isArray(t.generate)||!Array.isArray(t.maintenance))return;let n=t;return{...n,maintenance:n.maintenance.map(({repository:i,...r})=>({...r,test:r.test.trim().replace(/^\.\//,""),...i?.trim()?{repository:i.trim()}:{}}))}}function mye(e){return vn(BS,e).errors}function yye(e,t=[]){let{value:n,error:i}=_t(e,t);if(i)return{errors:[i]};let r=mye(n);return r.length>0?{errors:r}:{generate:n,errors:[]}}function Rv(e,t=[]){return yye(e.stdout,t)}function Eye(e){return e.generate.filter(t=>t.type!=="ui").map(t=>t.id)}function cY(e){return e.generate.filter(t=>t.type==="ui").map(t=>t.id)}var xv={backend:{stage:"generate",cases:Eye,noRecommendCoverage:"recommend.json missing or malformed \u2014 cannot check coverage",noRecommendIntent:"recommend.json missing or malformed \u2014 cannot check intent",uncovered:e=>`recommend case "${e}" is not covered by any generated test`,unknownCovered:e=>`test covers unknown recommend id "${e}"`,unasserted:e=>`case "${e}" has no verified assertion enforcing its expected_observable`,usedCodegen:SH,codegenHint:"These tests were hand-written. Skyramp codegen (skyramp_contract_test_generation / skyramp_integration_test_generation) was available but not used \u2014 it computes valid sample data and response correlations. Prefer scaffolding with it and then refining, especially for the failures above."},ui:{stage:"generate-ui",cases:cY,noRecommendCoverage:"recommend.json not found \u2014 cannot check UI coverage",noRecommendIntent:"recommend.json not found \u2014 cannot check UI intent",uncovered:e=>`UI case "${e}" is not covered by any generated UI test`,unknownCovered:e=>`test covers "${e}" which is not a recommend UI case`,unasserted:e=>`UI case "${e}" has no verified assertion enforcing its expected_observable`,usedCodegen:kH,codegenHint:"This UI test was hand-authored. Skyramp UI codegen (skyramp_ui_test_generation) was available but not used. Prefer scaffolding with it and then refining, especially for the failures above."}},iNe=Zn("generate-schema",(e,t)=>Rv(t,e.secretValues));function vye(e){let t=xv[e];return{name:`${t.stage}-coverage`,verify(n,i){let{generate:r,errors:s}=Rv(i,n.secretValues);if(!r)return Yt(this.name,s);let o=hA(n);if(!o)return Yt(this.name,[t.noRecommendCoverage]);let a=new Set(r.tests.flatMap(p=>p.covers)),c=[],u=t.cases(o);for(let p of u)a.has(p)||c.push(t.uncovered(p));let d=new Set(e==="ui"?u:o.generate.map(p=>p.id));for(let p of a)d.has(p)||c.push(t.unknownCovered(p));if(e==="backend"){let p=new Set(r.deferredUi),A=new Set(cY(o));for(let h of A)!p.has(h)&&!a.has(h)&&c.push(`UI case "${h}" is neither covered nor deferred to the UI stage`);for(let h of p)A.has(h)||c.push(`deferredUi lists "${h}" which is not a UI case`)}return c.length===0?{name:this.name,passed:!0}:Yt(this.name,c)}}}function bye(e){let t=xv[e];return{name:`${t.stage}-intent`,verify(n,i){let{generate:r,errors:s}=Rv(i,n.secretValues);if(!r)return Yt(this.name,s);let o=hA(n);if(!o)return Yt(this.name,[t.noRecommendIntent]);let{asserted:a,errors:c,badFiles:u}=Rye(r,n.inputs.repositoryPath),d=c.length;for(let A of t.cases(o))a.has(A)||c.push(t.unasserted(A));if(c.length===0)return{name:this.name,passed:!0};let p=Yt(this.name,c);return d>0&&d===c.length&&u.size>0?{...p,droppable:[...u]}:p}}}function Iye(e){let t=xv[e];return n=>{if(!n.inputs.skyrampMcp?.command||e==="backend"&&!kT(n))return;let i=Zl.join(n.outputsDir,`${t.stage}-stream.ndjson`);if(!(!Fo.existsSync(i)||t.usedCodegen(i)))return BH(i)?t.codegenHint:"Skyramp codegen tools were configured but the MCP server did not connect this session, so they were not available. Hand-authoring was the only option; this is an environment problem, not yours."}}var sNe=vye("backend"),oNe=bye("backend"),aNe=Iye("backend");var sY=e=>e.replace(/\s+/g,"");var FT={python:[/\bassert\s*[({\w"'`]/g,/\bpytest\.raises\s*\(/g,/\bself\.assert\w*\s*\(/g],typescript:[/\bexpect\s*\(/g,/\.should\b/g,/\bassert\s*[.(]/g],go:[/\bt\.(Error|Errorf|Fatal|Fatalf|Fail|FailNow)\s*\(/g,/\b(assert|require)\.\w+\s*\(/g],java:[/\bassert\w*\s*\(/g,/\bassertThat\s*\(/g],ruby:[/\bexpect\s*[({]/g,/\bassert\w*\b/g,/\.should\b/g]};for(let[e,t]of[["javascript","typescript"],["kotlin","java"]])FT[e]=FT[t];function wye(e,t){if(e.includes(zp(t))||sY(e).includes(sY(t)))return!0;let n=t.split(/\r?\n/).map(i=>i.trim()).filter(i=>i&&!/^(\/\/|#|\*|\/\*)/.test(i));return n.length>0&&n.every(i=>e.includes(zp(i)))?!0:Bye(e,t)}var Cye=/\bassert\w*\b|\bexpect\s*\(|\.should\b|\brequire\s*\(/i,Sye=12,kye=/,\s*\(\s*#|,\s*f?["'`]|\s+#\s|\s+\/\/|\s*\((?:line|lines|at line)\b|\s*,\s*$/i;function Bye(e,t){let n=t.split(/\s*;\s*|\s*\.\.\.\s*|\r?\n/),i=0;for(let r of n){let s=Cye.exec(r);if(!s)continue;let o=r.slice(s.index),a=kye.exec(o);if(a&&(o=o.slice(0,a.index)),o=zp(o).replace(/[,\s]+$/,""),o.length<Sye||!e.includes(o))return!1;i++}return i>0}function Rye(e,t){let n=new Set,i=[],r=new Set;for(let s of e.tests){let o=Zl.resolve(t,s.file);if(!Fo.existsSync(o))continue;let a=zp(Fo.readFileSync(o,"utf-8"));for(let c of s.assertions??[]){if(!wye(a,c.evidence)){i.push(`assertion evidence for "${c.case}" not found in ${s.file} \u2014 cite the real assertion line`),r.add(s.file);continue}s.covers.includes(c.case)?n.add(c.case):(i.push(`assertion cites case "${c.case}" not in that test's covers[]`),r.add(s.file))}}return{asserted:n,errors:i,badFiles:r}}var xye=/\.(spec|test)\.[cm]?[jt]sx?$/i;function uY(e){let t;try{t=(0,aY.execFileSync)("git",[...$i,"status","--porcelain","--untracked-files=all"],{env:It(),cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]})}catch{return}let n=r=>/_scaffold/i.test(r)||qp.test(r),i=[];for(let r of t.split(`
162
- `)){if(!r.trim()||r.length>1&&r[1]==="D")continue;let s=r.slice(3).trim(),o=s.indexOf(" -> ");if(o!==-1&&(s=s.slice(o+4).trim()),s=s.replace(/^"|"$/g,""),!s)continue;let a=s.replace(/^\.\//,"");a.startsWith(".skyramp/")||!n(a)||i.push(a)}return i}function Qye(e){let t=xv[e],n=e==="ui";return{name:`${t.stage}-no-litter`,verify(i){let r=uY(i.inputs.repositoryPath);if(r===void 0)return{name:this.name,passed:!0};let s=r.filter(o=>xye.test(o)===n);return s.length===0?{name:this.name,passed:!0}:Yt(this.name,[`${t.stage} left files outside .skyramp/ \u2014 move the staged test into .skyramp/staged/ and delete any codegen draft (e.g. *_scaffold.*): ${s.slice(0,6).join(", ")}`])}}}var cNe=Qye("backend");var Dye="write-stale-updates",Nye={[Dye]:"stale test updates"};var gA=ce(require("fs")),Qc=ce(require("path"));function fY(e,t=!1){return vn(Pj(t),e).errors}function Fye(e,t=[],n=!1){let{value:i,error:r}=_t(e,t);if(r)return{errors:[r]};let s=fY(i,n);return s.length>0?{errors:s}:{adapt:i,errors:[]}}var Oye="adapt-scratch",dY=`${Oye}/adapt-result.json`;function AY(e,t){let n=Qc.join(e.outputsDir,dY),i;try{i=gA.readFileSync(n,"utf-8")}catch{i=void 0}if(i!==void 0&&(e.secretValues??[]).some(a=>i.includes(a)))return{errors:[`${dY} contains a secret value (token / credential) \u2014 never write it anywhere`]};let r=Io(e.inputs?.sharedEnvironment).length>0,s=Fye(t.stdout,e.secretValues,r);if(s.adapt)return s;let o=i!==void 0?go(n):void 0;return o!==void 0&&fY(o,r).length===0?{adapt:o,errors:[]}:s}var PNe=Zn("adapt-schema",AY);var hY=require("child_process");function OT(e){return Mye(e)??[]}function Mye(e){let t;try{t=(0,hY.execFileSync)("git",[...$i,"status","--porcelain","-z","--untracked-files=all"],{env:It(),cwd:e,encoding:"utf-8",maxBuffer:16*1024*1024})}catch{return}let n=t.split("\0"),i=[];for(let r=0;r<n.length;r++){let s=n[r];if(s.length<4)continue;let o=s.slice(0,2);i.push({code:o,path:s.slice(3)}),(o[0]==="R"||o[0]==="C")&&r++}return i}var zNe=2*1024*1024;var Qv=l.string().trim().min(1),Lye=l.object({cwd:Qv.describe(`directory the command starts in, relative to the test's checkout ("." for its root)`),argv:l.array(Qv).min(1).describe("the command as separate arguments, run without a shell"),env:l.record(l.string(),l.string()).optional().describe("plain settings the listing needs beyond the CI step's own; never a credential or PATH")}),jye=l.object({file:Qv.describe("a file of the test's checkout, relative to its root"),line:Qv.describe("a line of that file, quoted exactly from where its command starts to its end")}),gY=l.object({collected:l.boolean().describe("whether the repo's CI runs this test as it is"),steps:l.array(jye).optional().describe("when collected: the line in a CI file that starts the tests, then each line it runs on the way to the test runner"),runner:l.string().optional().describe("when collected: the test runner the last of those lines starts, by the name that line and the list command both use"),list:Lye.optional().describe("when collected: a command that lists the tests that runner collects without running them; Testbot runs it, and its output must name this file"),why:l.string().optional().describe("when not collected: why the repo's CI will not run it")});var de=l.string().trim().min(1),Hye=e=>{if(!e||typeof e!="object")return e;let t=e;return typeof t.skip=="string"&&t.skip.trim()&&(t.expected===void 0||t.expected===null)?{...t,expected:"(not tested)"}:e},Yye=l.preprocess(Hye,l.object({id:de.describe(`its requirement's id plus a letter, e.g. "R1a", "AC-3a"`),clause:de.describe("one testable part of the requirement"),expected:de.describe("the outcome the requirement calls for \u2014 taken from the requirement, never from what the code does"),skip:l.string().optional().describe("only when no test can check this clause here: why"),type:l.nativeEnum(Bs).optional().describe("the test that checks this clause: contract / integration (the API, or code called directly in-process: a function, hook or module) or ui (a page)"),target:l.string().optional().describe('its "METHOD /path", or the page / flow'),steps:l.string().optional().describe("what that test does; its expected outcome is this clause's"),finding:l.string().optional().describe("the finding id, when this clause's test also catches that defect (the defect still gets a case of its own)"),code:l.string().optional().describe("path:line of the code that decides this clause, when there is one; in another repo of the change, that repo's directory name then its path"),stated:l.string().optional().describe("the description's or spec's own words that state this clause, copied exactly, when they do"),mutates:l.boolean().optional().describe("true when its test changes state, in the test or its setup: an API POST, PUT, PATCH or DELETE, or a UI flow that submits, creates, edits or deletes"),browserOnly:l.boolean().optional().describe("true when its behaviour happens only in a browser: real clicks or keys driving page script, client-side sorting or filtering, script-driven DOM updates, focus, drag-and-drop, navigation, rendering that depends on CSS or JavaScript"),browserHarness:l.string().optional().describe("browserOnly, off the runtime path: the path of the repo's in-process browser suite its test goes in (e.g. a Django StaticLiveServerTestCase test that drives Selenium)"),quote:l.string().optional().describe("the words of the spec, plan, ticket, PR description or a test the change adds or edits that state this clause, copied exactly; a file of the repository: its path:line first. Leave it out when no source states it"),inferred:l.boolean().optional().describe("leave it out: Testbot sets it when no source states this clause (contracts/clause-grounding.ts)")})),yY=l.object({spec:l.string().optional().describe("file:line of a spec in the repository"),prDescription:l.boolean().optional().describe("or true when a pull request description says otherwise"),reference:l.string().optional().describe("or the key of an item the run was given, as listed"),says:de.describe("what it says there, in its own words, copied exactly"),criterion:l.number().int().positive().optional().describe("an item's only: leave it out; Testbot numbers it")}).refine(e=>[!!e.prDescription,!!e.spec?.trim(),!!e.reference?.trim()].filter(Boolean).length===1,{message:`names no source, or more than one: give "spec" its file:line or "reference" an item's key, or set "prDescription", one of them; list each source as its own entry`}),Wye=l.object({id:de.describe('the label its source gives it ("AC-3", "REQ-12"; item 4 of a numbered list is "R4"), else "R1", "R2"\u2026 in order'),statement:de,source:l.nativeEnum(qi).describe("requirement-reference (an item the run was given), spec, pr-description (also for what the change is evidently meant to do when nothing is written down), or could-break (what the change could break that no requirement mentions)"),reference:l.string().optional().describe('requirement-reference only: the key of its item as listed, e.g. "PAY-184", or a Confluence page id such as "3021"'),evidence:de.describe("where it is stated: for requirement-reference, the item's own words, copied exactly; else file:line, a doc section, or the quoted phrase"),criterion:l.number().int().positive().optional().describe("requirement-reference only: leave it out; Testbot numbers each criterion by the item's own label (AC2, 2.), else after the item's labels"),alsoFrom:l.array(l.object({reference:de.regex(lo).describe("the key of another uploaded document stating the same obligation"),says:de.describe("that document's own words, copied exactly; never infer equivalence from a shared criterion number"),criterion:l.number().int().positive().optional().describe("leave out; Testbot grounds and numbers this source separately")})).optional().describe("equivalent uploaded source criteria sharing this requirement's planned cases; retain every source with its own quote. Different conditions or boundaries need distinct requirements"),notInChange:l.string().optional().describe("requirement-reference only: when the change does not touch this criterion at all (e.g. a later step of a staged rollout), why; give it no clauses"),unchanged:l.boolean().optional().describe("true when it asks only that behaviour stay as it was (an update or refactor that must not change how something works), whatever its source"),overrules:l.array(yY).optional().describe("requirement-reference only: each lower-ranked source that says otherwise, a spec in the repository, a PR description or another item; this requirement wins, so test what it says"),clauses:l.array(Yye)}),EY=(r=>(r.ServerError="server-error",r.DataLost="data-lost",r.FinalState="final-state",r.DerivedValues="derived-values",r))(EY||{}),Zye=l.object({id:de.describe('e.g. "F1"'),file:de,line:l.number().optional(),claim:de.describe("the defect, in one sentence"),severity:l.nativeEnum(Rc),evidence:de.describe("the code line, or the probe request and response, that shows it"),conflictsWith:l.array(de).optional().describe("requirement or clause ids it violates"),keeps:l.string().optional().describe("for a defect no requirement or clause states: path:line of the code beside the change that keeps the rule it breaks"),rule:l.nativeEnum(EY).optional().describe("for a defect that breaks a rule every app keeps, which nothing needs to state: which one"),existing:l.string().optional().describe("only when the base already does this, in code the change left as it was, and the change does not say it fixes it: where the base does it (its file:line); such a defect gets no case"),needsApp:l.enum(["browser","live-api"]).optional().describe("only when the running app alone can show this defect and the repo has no in-process test that can: browser (page script, what the user sees after a click or a save) or live-api (code the repo tests only against the running app's API)")}),Kye=l.object({id:de.describe('e.g. "Q1"'),question:de.describe("what is unsettled, as a question the PR author can answer"),readings:l.array(de).min(2).describe("each reasonable behaviour, with what points to it (file:line, or the words that suggest it)"),about:l.string().optional().describe("the requirement or clause id it is about, when there is one"),sources:l.array(yY).optional().describe("when sources of the same rank disagree on it: each of them")}),Xye=l.object({id:de.describe('unique, a short kebab-case name for what the case checks, e.g. "ship-twice-409"'),type:l.nativeEnum(Bs).describe("contract / integration: checks the API, or calls code directly in-process (a function, hook or module); ui: checks what a user sees or does on a page"),target:de.describe('"METHOD /path", or the page / flow'),clause:l.string().optional().describe("the clause id this case checks"),finding:l.string().optional().describe("the finding id this case catches"),steps:de.describe("what the test does"),expected:de.describe("the expected outcome, from the clause"),mutates:l.boolean().optional().describe("true when its test changes state, in the test or its setup: an API POST, PUT, PATCH or DELETE, or a UI flow that submits, creates, edits or deletes")}),eEe=l.object({test:de.describe("existing test file"),action:l.nativeEnum(zi),reason:de,mutates:l.boolean().optional().describe("true when the maintained test changes state"),clauses:l.array(de).optional().describe("the clause ids this test checks"),staleOnBase:l.boolean().optional().describe("true when the test's own expectation was already wrong before this change: it fails the same way on the base branch, where the app does what it should. Not one the base app's own bug fails (that is an existing defect). It is verify, never update: re-run as it is, its failure the test's own. A delete the change justifies stays a delete")}),mY=l.array(vm).optional(),tEe=l.object({components:l.preprocess(e=>mY.safeParse(e).success?e:void 0,mY).describe("when saving a new or changed recipe: every app and backing service actually brought up, its source repository, and whether it is healthy"),outcome:l.nativeEnum(jr).describe("clean | recipe-drift (you had to fix the recipe) | change-broke-bringup (this PR broke start-up) | bringup-failed (the environment, not the PR)"),baseUrls:l.record(l.string()).optional().describe("service \u2192 base URL of the running app"),health:l.object({url:l.string().optional(),command:l.string().optional(),output:l.string().optional()}).optional().describe("the check that shows the app serves real data, and what it returned"),teardown:l.string().optional().describe("command that stops the app"),dependencies:l.record(l.boolean()).optional().describe("every backing service: true = really running, false = mocked"),recipeFixes:l.array(l.string()).optional().describe("what you changed in the recipe"),error:l.string().optional().describe("when it did not come up: the failing command and what it printed"),suspectFiles:l.array(l.string()).optional().describe("change-broke-bringup: the changed files to blame"),missingSecrets:l.array(l.string().regex(kp)).optional().describe("bringup-failed only: each secret, key, token or password the app cannot start without that this run has no value for, by its environment variable name; never a value"),login:l.object({username:de,password:l.string()}).optional().describe("the account the tests sign in as, when they sign in: each a literal value the recipe seeds, or $VARIABLE when a secret in the environment holds it"),revisions:hS.optional()}),BPe=l.object({schemaVersion:l.literal(1),requirements:l.array(Wye),findings:l.array(Zye),cases:l.array(Xye).describe("a second test for a clause, and one case per finding that fails on this branch"),questions:l.array(Kye).optional().describe("behaviours the change leaves unsettled; no case asserts any of them"),maintenance:l.array(eEe),journeys:l.array(eY).optional().describe("the user journeys that, together, pass through everything the change alters that a user sees or does; empty when it alters nothing a user sees"),notInJourney:l.array(l.object({clause:de,why:de})).optional().describe("a clause a user sees or does that no journey walks, and why: none can reach it through the UI, or it is downstream of this change and not walked here"),unplannedComponents:l.array(l.object({components:l.array(de).min(1).describe("changed components, as the change lists them"),why:de})).optional().describe("changed components no clause reaches, and why their change needs no test; several may share one reason"),triage:AA.optional().describe("the validation triage decision, made before the app is started; its behaviorIds are clause ids"),app:tEe.optional().describe("omit when no app was needed or none was started"),summary:de.describe("one paragraph: what the change does and where the risk is")});var mA=(n=>(n.Backend="backend",n.Ui="ui",n))(mA||{});var Oo=(r=>(r.Added="added",r.Updated="updated",r.Deleted="deleted",r.Unchanged="unchanged",r))(Oo||{}),nEe=l.object({file:de.describe("repo-relative path; in another repo of the change, that repo's directory name then its path"),kind:l.nativeEnum(mA),change:l.nativeEnum(Oo).describe("added: a file you created; updated / deleted / unchanged: an existing test"),covers:l.array(l.string()).describe("the plan case ids this file tests, each with its own result under result.cases"),defect:l.boolean().optional().describe("true when a case of it fails because the app is wrong and the test is right \u2014 kept failing on purpose"),staleBecause:l.object({requirement:de.describe("the requirement or clause id the change deliberately alters"),line:de.describe("path:line (or path) of the application code the change altered that makes this test's old expectation wrong")}).optional().describe("for an existing test you updated or deleted: why it is out of date"),staleOnBase:l.boolean().optional().describe("for an existing test that fails: true when it fails the same way on the base branch because its own expectation is wrong (the app there does what it should), so this change did not make it wrong. Not when the base app's own bug fails it: that is an existing defect. Leave it as it is (unchanged): its failure is the test's own"),result:l.object({started:l.boolean().optional().describe("whether this file's test command started; required for a shared-environment run with exit null: true if interrupted or timed out, false if it never started"),exit:l.number().nullable().describe("exit code of your last run of this file; null if it could not be run"),cases:l.array(l.object({case:de,status:l.nativeEnum(Vr),runtimeTargets:Fp.optional().describe("HTTP(S) URLs this case actually exercised in its current run, from its request or browser evidence; omit for local in-process/mocked checks, never list the shared app merely because it is configured"),defect:l.boolean().optional().describe("for a failing case: true when the app is wrong and the test is right; false when the test is at fault and you could not fix it"),testProblem:Rm.optional().describe("for a failing case marked defect: false: what in the test is at fault"),failure:l.string().optional().describe("for a failing case: the runner's failure for it as printed (the error and the line it was raised at), not a summary"),cause:l.string().optional().describe("for a case you keep as a defect: path:line of the application code that makes it fail"),requires:l.string().optional().describe("for a case you keep as a defect: the words of the PR description, a requirement or clause of the plan, or the code a finding's keeps names, that state what its failing check expects, quoted exactly")})).describe("one entry per covered case, from the runner's own output"),details:l.string().optional().describe("what failed and why, or why it was not run"),noCases:l.string().optional().describe("for a failed run whose runner reported none of this file's tests (it failed to compile, import or collect): why")}),assertions:l.array(l.object({case:de,evidence:de})).optional().describe("per covered case, the assertion line that checks its expected outcome"),functions:l.array(l.object({name:de.describe("the test function as the runner names it within its file, without the file (test_x, TestClass::test_x, TestSuite/TestCase)"),cases:l.array(de).describe("the plan case ids it checks"),testProblem:Rm.optional().describe("for a function that fails because of the test itself, while another function keeps a case it checks as a defect: what in it is at fault")})).optional().describe("for a file you added or updated: each test function in it and the plan case ids it checks"),skyramp:l.object({draft:l.union([l.string(),l.array(l.string())]).optional().describe("the draft path the Skyramp helper returned for this test, or each path when the test was made from several drafts"),handWritten:l.string().optional().describe("why it is written by hand: the helper call you made and what it returned")}).optional().describe("only for a test of a case the Skyramp API block lists: where it came from"),context:l.array(Up).optional().describe("what the test sets up outside its own process that another test could run into: data it creates in the app, a Skyramp mock, an env override; omit when none"),isolatedRun:de.optional().describe("for a test with a context: the command, from its checkout's root and without a shell, that runs only this file"),ci:gY.optional().describe("for a file you added or updated: whether the repo's CI will run it, and how you know"),run:Yl.optional().describe(`for a file in ${Wl}, added, updated or re-run: how the run executes only this file's tests, with the repository's own runner and the report it writes (junit, trx or jest-json to ${wn}, or go-test-json); Testbot runs it before write ends and re-runs the tests with it`)}),rEe=e=>{if(!e||typeof e!="object")return e;let{test:t,...n}=e;return typeof t=="string"&&t.trim()&&n.tests===void 0?{...n,tests:[t]}:e},iEe=l.preprocess(rEe,l.object({description:de.describe("what is wrong and how to reproduce it: endpoint or page, input, what you got vs what was expected"),severity:l.nativeEnum(Rc).optional(),sourceFile:l.string().optional().describe("the app file at fault"),sourceLine:l.number().optional(),tests:l.array(de).optional().describe("every test file that fails because of it: a defect several tests show is one issue"),finding:l.string().optional().describe("the plan's finding id, when it is one"),requirements:l.array(de).optional().describe("the plan's requirement or clause ids it violates")})),RPe=l.object({schemaVersion:l.literal(1),tests:l.array(nEe),notWritten:l.array(l.object({case:de,reason:de,coveredBy:l.object({file:de.describe("the test file, relative to the working checkout; prefix a related checkout as for tests[].file"),name:de.describe("the test function as the runner names it within its file, without the file (test_x, TestClass::test_x, TestSuite/TestCase)")}).optional().describe("only for an existing test triage independently linked to this exact case: its exact runner name (including class or describe titles). Testbot must finish re-running it with every result passed. If your own test covers the case, include the case in its covers and function cases instead")})).describe("every plan case no test covers, and why"),journeys:l.array(kv).optional().describe("one entry per planned user journey: the browser test that walks it end to end"),lint:l.object({command:l.string(),clean:l.boolean()}).optional().describe("the linter/formatter you ran on your test files, if the repo has one: the exact command, with its file paths (Testbot re-runs it)"),dependenciesAdded:l.array(l.object({package:de,manifest:de.describe("the manifest file's path relative to its checkout (e.g. package.json, pom.xml or pyproject.toml), and nothing else; name another checkout in repository"),repository:de.optional().describe("owner/repo of the manifest's checkout; omit for the repo under test"),reason:de.optional().describe("why the test must run inside the application's own test environment, so its manifest had to change \u2014 required for every entry")})).optional().describe("every package you added to an APPLICATION manifest (an exception, surfaced in the report); never the Testbot test package's own"),supportFiles:l.array(de).optional().describe("every file that is not a test you created or changed for your tests, which they need to compile or run (a helper module, page object, fixture, or a snapshot the runner wrote for them), named as you name a test; Testbot delivers only the tests you list and the files under supportFiles"),ciNotes:l.string().optional().describe("for each test whose ci says the repo's CI will not run it: the test, and the exact change the author must make for CI to run it"),commit:l.object({message:de.describe("subject line at most 72 characters, following the repository's commit-message checks"),prTitle:de.describe("at most 72 characters, following the repository's PR-title checks"),prBody:de.describe("what the tests cover and what they found")}),report:l.object({summary:de.describe("1-2 sentences for the PR author: does the change do what it says? No count of tests: the report gives it"),issues:l.array(iEe).describe("every defect the tests found"),nextSteps:l.array(l.string()),noTests:l.array(l.object({repository:de,reason:de.max(4096)})).max(1e3).optional().describe("each Change Set repository where no test was added or updated: its owner/repo and why, naming the other repository when its tests went there"),notesDeviation:l.string().trim().max(4096).optional().describe("when the Target notes say where tests go and a test you added went elsewhere: where it went, and why; omit otherwise")})});var xPe={added:"place",updated:"update",deleted:"delete",unchanged:"verify"};var bY=(i=>(i.Requirement="requirement",i.PrDescription="pr_description",i.Code="code",i))(bY||{}),cn=l.string().trim().min(1),sEe=l.object({expectation:cn.max(300).describe("the behavior this assertion pins, in words"),source:l.nativeEnum(bY),expected:cn.max(200).describe("the exact value or outcome asserted, as the test asserts it")}),oEe=l.object({file:cn.describe("path of the NEW test file you wrote, relative to its repository"),repository:cn.optional().describe("owner/repo the file lives in, when the run has several checkouts; omit for the working checkout"),framework:cn.describe("the framework the repository runs this file with: pytest, jest, vitest, node-test, or the name of any other"),run:Yl.optional().describe(`for ${Wl}: how the run executes only the tests in names, with the repository's own runner writing JUnit XML to {junit}`),covers:l.array(cn).length(1).describe("the ONE behavior id, or defect id, from the plan that the tests in names provide evidence for; a file covering several is listed once per id"),names:l.array(cn).min(1).describe("the test functions/cases in the file that provide evidence for that behavior, as the framework names them"),assertions:l.array(sEe).min(1)}),yA=(n=>(n.Updated="updated",n.Deleted="deleted",n))(yA||{}),vY=300,aEe=l.object({file:cn.describe("path of the EXISTING test file you updated or deleted, relative to its repository"),repository:cn.optional().describe("owner/repo the file lives in, when the run has several checkouts; omit for the working checkout"),change:l.nativeEnum(yA),staleBecause:l.object({requirement:cn.describe("the requirement or clause id the change deliberately alters"),line:cn.describe("path:line (or path) of the application code the change altered that makes this test's old expectation wrong")}).optional().describe("for an existing test you updated: why it is out of date"),reason:l.preprocess(e=>typeof e=="string"?e.trim().slice(0,vY):e,cn.max(vY)).describe("what the change deliberately altered that made the test wrong")}),MT=l.object({schemaVersion:l.literal(1),tests:l.array(oEe),maintained:l.array(aEe).optional().describe("existing tests the change made stale that you updated or deleted; omit when there were none"),defectsNotTested:l.array(l.object({id:cn,reason:cn.max(300)})).optional().describe("defects the plan found that no in-process test can reach, each with why; omit when every defect has a test"),journeys:l.array(kv).optional().describe("one entry per planned user journey: the in-process test that walks it end to end"),journeysNotWritten:l.array(l.object({journey:cn,missing:cn.transform(e=>e.length>300?`${e.slice(0,299)}\u2026`:e)})).optional().describe("a planned journey no in-process test can walk here, with what it needs that is missing; it is reported as not covered"),lint:l.object({command:l.string(),clean:l.boolean()}).optional().describe("the linter/formatter you ran on your test files, if the repository has one you can run; omit otherwise"),commitMessage:cn.optional().describe("the commit message for your tests: a subject line of at most 72 characters, then what they cover")});var EA="generate-unit.json";function uEe(e){let{value:t,error:n}=_t(e);if(n)return{errors:[n]};let{value:i,errors:r}=vn(MT,t);return r.length?{errors:r}:{output:i,errors:[]}}function lEe(e){return uEe(e.stdout)}var gUe=Zn("generate-unit-schema",(e,t)=>lEe(t));var $v=String.raw`(?:node:)?(?:http|https|http2|net|tls|dgram)`,mUe=[[/\b(localhost|127\.0\.0\.1|0\.0\.0\.0)\b/,"a local server address"],[/^\s*(import|from)\s+(requests|aiohttp|urllib3|websockets?)\b/m,"an HTTP client"],[/^\s*(?:import|from)\s+(?:urllib\.request|http\.client|http\.server|socket|ssl|ftplib|smtplib|telnetlib)\b|^\s*from\s+urllib\s+import\b[^\n]*\brequest\b|\burlopen\s*\(/m,"a standard-library network client"],[/\bfrom\s+["'](axios|node-fetch|undici|ws)["']|require\(\s*["'](axios|node-fetch|undici|ws)["']\s*\)/,"an HTTP client"],[new RegExp(String.raw`\bfrom\s+["']${$v}["']|\bimport\s+["']${$v}["']|require\(\s*["']${$v}["']\s*\)|\bimport\(\s*["']${$v}["']\s*\)`),"Node's network modules"],[/\bfetch\s*\(|\bnew\s+(XMLHttpRequest|WebSocket)\b/,"a network call (fetch, XMLHttpRequest, WebSocket)"],[/\bskyramp\b/i,"the Skyramp runtime (a runtime mock or client)"]];var UUe=new Set(["targeted_unit","existing_evidence_sufficient"]);var Mo=ce(require("path"));var WUe={"application/pdf":"PDF","text/csv":"CSV","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX"};var jT=e=>new Map((e??[]).flatMap(t=>t.file?[[_p(t.key),t.file.name]]:[])),hEe=10*1024*1024,gEe=e=>e?.mediaType==="application/vnd.openxmlformats-officedocument.wordprocessingml.document"||e?.mediaType==="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",RY=(e,t)=>Mo.join(Mo.dirname(e),`${Mo.basename(e,Mo.extname(e))}${t}`),mEe=e=>RY(e,".extracted.txt");var yEe=e=>RY(e,".quotes.txt");function xY(e){return gEe(e.file)?mEe(e.path):e.file?.mediaType==="application/pdf"?yEe(e.path):e.path}var IEe="triage.json";var qFe=new Set(["existing_evidence","unaffected","existing_unit","new_unit","runtime"]),JFe={existing_evidence:"existing evidence",unaffected:"showing the change cannot reach it",existing_unit:"running the existing unit tests",new_unit:"a new unit test",runtime:"tests against the running application"};function wEe(e){let{value:t,error:n}=_t(e);if(n)return{errors:[n]};let{value:i,errors:r}=vn(AA,t);return r.length?{errors:r}:{triage:i,errors:[]}}function CEe(e){return wEe(e.stdout)}var HFe=Zn("triage-schema",(e,t)=>CEe(t));function SEe(e){let t=e.inputs?.pipeline;return t?e.state.stages[t==="two-step"?"plan":"triage"]:e.state.stages.triage??e.state.stages.plan}function VT(e){if(SEe(e)?.status==="passed")return go($Y.join(e.outputsDir,IEe))}function GT(e){return OH(wT(e.inputs,Ke(e,`${Jl}.json`),VT(e)?.sutRequired))}var YFe=new Set(["deploy","recommend","generate","generate-ui","adapt","generate-unit","native-run","finalize","deliver"]);xn();xn();function TY(e,t){return t?`<!-- skyramp-testbot-run: ${t} -->
162
+ `)){if(!r.trim()||r.length>1&&r[1]==="D")continue;let s=r.slice(3).trim(),o=s.indexOf(" -> ");if(o!==-1&&(s=s.slice(o+4).trim()),s=s.replace(/^"|"$/g,""),!s)continue;let a=s.replace(/^\.\//,"");a.startsWith(".skyramp/")||!n(a)||i.push(a)}return i}function Qye(e){let t=xv[e],n=e==="ui";return{name:`${t.stage}-no-litter`,verify(i){let r=uY(i.inputs.repositoryPath);if(r===void 0)return{name:this.name,passed:!0};let s=r.filter(o=>xye.test(o)===n);return s.length===0?{name:this.name,passed:!0}:Yt(this.name,[`${t.stage} left files outside .skyramp/ \u2014 move the staged test into .skyramp/staged/ and delete any codegen draft (e.g. *_scaffold.*): ${s.slice(0,6).join(", ")}`])}}}var cNe=Qye("backend");var Dye="write-stale-updates",Nye={[Dye]:"stale test updates"};var gA=ce(require("fs")),Qc=ce(require("path"));function fY(e,t=!1){return vn(Pj(t),e).errors}function Fye(e,t=[],n=!1){let{value:i,error:r}=_t(e,t);if(r)return{errors:[r]};let s=fY(i,n);return s.length>0?{errors:s}:{adapt:i,errors:[]}}var Oye="adapt-scratch",dY=`${Oye}/adapt-result.json`;function AY(e,t){let n=Qc.join(e.outputsDir,dY),i;try{i=gA.readFileSync(n,"utf-8")}catch{i=void 0}if(i!==void 0&&(e.secretValues??[]).some(a=>i.includes(a)))return{errors:[`${dY} contains a secret value (token / credential) \u2014 never write it anywhere`]};let r=Io(e.inputs?.sharedEnvironment).length>0,s=Fye(t.stdout,e.secretValues,r);if(s.adapt)return s;let o=i!==void 0?go(n):void 0;return o!==void 0&&fY(o,r).length===0?{adapt:o,errors:[]}:s}var PNe=Zn("adapt-schema",AY);var hY=require("child_process");function OT(e){return Mye(e)??[]}function Mye(e){let t;try{t=(0,hY.execFileSync)("git",[...$i,"status","--porcelain","-z","--untracked-files=all"],{env:It(),cwd:e,encoding:"utf-8",maxBuffer:16*1024*1024})}catch{return}let n=t.split("\0"),i=[];for(let r=0;r<n.length;r++){let s=n[r];if(s.length<4)continue;let o=s.slice(0,2);i.push({code:o,path:s.slice(3)}),(o[0]==="R"||o[0]==="C")&&r++}return i}var zNe=2*1024*1024;var Qv=l.string().trim().min(1),Lye=l.object({cwd:Qv.describe(`directory the command starts in, relative to the test's checkout ("." for its root)`),argv:l.array(Qv).min(1).describe("the command as separate arguments, run without a shell"),env:l.record(l.string(),l.string()).optional().describe("plain settings the listing needs beyond the CI step's own; never a credential or PATH")}),jye=l.object({file:Qv.describe("a file of the test's checkout, relative to its root"),line:Qv.describe("a line of that file, quoted exactly from where its command starts to its end")}),gY=l.object({collected:l.boolean().describe("whether the repo's CI runs this test as it is"),steps:l.array(jye).optional().describe("when collected: the line in a CI file that starts the tests, then each line it runs on the way to the test runner"),runner:l.string().optional().describe("when collected: the test runner the last of those lines starts, by the name that line and the list command both use"),list:Lye.optional().describe("when collected: a command that lists the tests that runner collects without running them; Testbot runs it, and its output must name this file"),why:l.string().optional().describe("when not collected: why the repo's CI will not run it")});var de=l.string().trim().min(1),Hye=e=>{if(!e||typeof e!="object")return e;let t=e;return typeof t.skip=="string"&&t.skip.trim()&&(t.expected===void 0||t.expected===null)?{...t,expected:"(not tested)"}:e},Yye=l.preprocess(Hye,l.object({id:de.describe(`its requirement's id plus a letter, e.g. "R1a", "AC-3a"`),clause:de.describe("one testable part of the requirement"),expected:de.describe("the outcome the requirement calls for \u2014 taken from the requirement, never from what the code does"),skip:l.string().optional().describe("only when no test can check this clause here: why"),type:l.nativeEnum(Bs).optional().describe("the test that checks this clause: contract / integration (the API, or code called directly in-process: a function, hook or module) or ui (a page)"),target:l.string().optional().describe('its "METHOD /path", or the page / flow'),steps:l.string().optional().describe("what that test does; its expected outcome is this clause's"),finding:l.string().optional().describe("the finding id, when this clause's test also catches that defect (the defect still gets a case of its own)"),code:l.string().optional().describe("path:line of the code that decides this clause, when there is one; in another repo of the change, that repo's directory name then its path"),stated:l.string().optional().describe("the description's or spec's own words that state this clause, copied exactly, when they do"),mutates:l.boolean().optional().describe("true when its test changes state, in the test or its setup: an API POST, PUT, PATCH or DELETE, or a UI flow that submits, creates, edits or deletes"),browserOnly:l.boolean().optional().describe("true when its behaviour happens only in a browser: real clicks or keys driving page script, client-side sorting or filtering, script-driven DOM updates, focus, drag-and-drop, navigation, rendering that depends on CSS or JavaScript"),browserHarness:l.string().optional().describe("browserOnly, off the runtime path: the path of the repo's in-process browser suite its test goes in (e.g. a Django StaticLiveServerTestCase test that drives Selenium)"),quote:l.string().optional().describe("the words of the spec, plan, ticket, PR description or a test the change adds or edits that state this clause, copied exactly; a file of the repository: its path:line first. Leave it out when no source states it"),inferred:l.boolean().optional().describe("leave it out: Testbot sets it when no source states this clause (contracts/clause-grounding.ts)")})),yY=l.object({spec:l.string().optional().describe("file:line of a spec in the repository"),prDescription:l.boolean().optional().describe("or true when a pull request description says otherwise"),reference:l.string().optional().describe("or the key of an item the run was given, as listed"),says:de.describe("what it says there, in its own words, copied exactly"),criterion:l.number().int().positive().optional().describe("an item's only: leave it out; Testbot numbers it")}).refine(e=>[!!e.prDescription,!!e.spec?.trim(),!!e.reference?.trim()].filter(Boolean).length===1,{message:`names no source, or more than one: give "spec" its file:line or "reference" an item's key, or set "prDescription", one of them; list each source as its own entry`}),Wye=l.object({id:de.describe('the label its source gives it ("AC-3", "REQ-12"; item 4 of a numbered list is "R4"), else "R1", "R2"\u2026 in order'),statement:de,source:l.nativeEnum(qi).describe("requirement-reference (an item the run was given), spec, pr-description (also for what the change is evidently meant to do when nothing is written down), or could-break (what the change could break that no requirement mentions)"),reference:l.string().optional().describe('requirement-reference only: the key of its item as listed, e.g. "PAY-184", or a Confluence page id such as "3021"'),evidence:de.describe("where it is stated: for requirement-reference, the item's own words, copied exactly; else file:line, a doc section, or the quoted phrase"),criterion:l.number().int().positive().optional().describe("requirement-reference only: leave it out; Testbot numbers each criterion by the item's own label (AC2, 2.), else after the item's labels"),alsoFrom:l.array(l.object({reference:de.regex(lo).describe("the key of another uploaded document stating the same obligation"),says:de.describe("that document's own words, copied exactly; never infer equivalence from a shared criterion number"),criterion:l.number().int().positive().optional().describe("leave out; Testbot grounds and numbers this source separately")})).optional().describe("equivalent uploaded source criteria sharing this requirement's planned cases; retain every source with its own quote. Different conditions or boundaries need distinct requirements"),notInChange:l.string().optional().describe("requirement-reference only: when the change does not touch this criterion at all (e.g. a later step of a staged rollout), why; give it no clauses"),unchanged:l.boolean().optional().describe("true when it asks only that behaviour stay as it was (an update or refactor that must not change how something works), whatever its source"),overrules:l.array(yY).optional().describe("requirement-reference only: each lower-ranked source that says otherwise, a spec in the repository, a PR description or another item; this requirement wins, so test what it says"),clauses:l.array(Yye)}),EY=(r=>(r.ServerError="server-error",r.DataLost="data-lost",r.FinalState="final-state",r.DerivedValues="derived-values",r))(EY||{}),Zye=l.object({id:de.describe('e.g. "F1"'),file:de,line:l.number().optional(),claim:de.describe("the defect, in one sentence"),severity:l.nativeEnum(Rc),evidence:de.describe("the code line, or the probe request and response, that shows it"),conflictsWith:l.array(de).optional().describe("requirement or clause ids it violates"),keeps:l.string().optional().describe("for a defect no requirement or clause states: path:line of the code beside the change that keeps the rule it breaks"),rule:l.nativeEnum(EY).optional().describe("for a defect that breaks a rule every app keeps, which nothing needs to state: which one"),existing:l.string().optional().describe("only when the base already does this, in code the change left as it was, and the change does not say it fixes it: where the base does it (its file:line); such a defect gets no case"),needsApp:l.enum(["browser","live-api"]).optional().describe("only when the running app alone can show this defect and the repo has no in-process test that can: browser (page script, what the user sees after a click or a save) or live-api (code the repo tests only against the running app's API)")}),Kye=l.object({id:de.describe('e.g. "Q1"'),question:de.describe("what is unsettled, as a question the PR author can answer"),readings:l.array(de).min(2).describe("each reasonable behaviour, with what points to it (file:line, or the words that suggest it)"),about:l.string().optional().describe("the requirement or clause id it is about, when there is one"),sources:l.array(yY).optional().describe("when sources of the same rank disagree on it: each of them")}),Xye=l.object({id:de.describe('unique, a short kebab-case name for what the case checks, e.g. "ship-twice-409"'),type:l.nativeEnum(Bs).describe("contract / integration: checks the API, or calls code directly in-process (a function, hook or module); ui: checks what a user sees or does on a page"),target:de.describe('"METHOD /path", or the page / flow'),clause:l.string().optional().describe("the clause id this case checks"),finding:l.string().optional().describe("the finding id this case catches"),steps:de.describe("what the test does"),expected:de.describe("the expected outcome, from the clause"),mutates:l.boolean().optional().describe("true when its test changes state, in the test or its setup: an API POST, PUT, PATCH or DELETE, or a UI flow that submits, creates, edits or deletes")}),eEe=l.object({test:de.describe("existing test file"),action:l.nativeEnum(zi),reason:de,mutates:l.boolean().optional().describe("true when the maintained test changes state"),clauses:l.array(de).optional().describe("the clause ids this test checks"),staleOnBase:l.boolean().optional().describe("true when the test's own expectation was already wrong before this change: it fails the same way on the base branch, where the app does what it should. Not one the base app's own bug fails (that is an existing defect). It is verify, never update: re-run as it is, its failure the test's own. A delete the change justifies stays a delete")}),mY=l.array(vm).optional(),tEe=l.object({components:l.preprocess(e=>mY.safeParse(e).success?e:void 0,mY).describe("when saving a new or changed recipe: every app and backing service actually brought up, its source repository, and whether it is healthy"),outcome:l.nativeEnum(jr).describe("clean | recipe-drift (you had to fix the recipe) | change-broke-bringup (this PR broke start-up) | bringup-failed (the environment, not the PR)"),baseUrls:l.record(l.string()).optional().describe("service \u2192 base URL of the running app"),health:l.object({url:l.string().optional(),command:l.string().optional(),output:l.string().optional()}).optional().describe("the check that shows the app serves real data, and what it returned"),teardown:l.string().optional().describe("command that stops the app"),dependencies:l.record(l.boolean()).optional().describe("every backing service: true = really running, false = mocked"),recipeFixes:l.array(l.string()).optional().describe("what you changed in the recipe"),error:l.string().optional().describe("when it did not come up: the failing command and what it printed"),suspectFiles:l.array(l.string()).optional().describe("change-broke-bringup: the changed files to blame"),missingSecrets:l.array(l.string().regex(kp)).optional().describe("bringup-failed only: each secret, key, token or password the app cannot start without that this run has no value for, by its environment variable name; never a value"),login:l.object({username:de,password:l.string()}).optional().describe("the account the tests sign in as, when they sign in: each a literal value the recipe seeds, or $VARIABLE when a secret in the environment holds it"),revisions:hS.optional()}),BPe=l.object({schemaVersion:l.literal(1),requirements:l.array(Wye),findings:l.array(Zye),cases:l.array(Xye).describe("a second test for a clause, and one case per finding that fails on this branch"),questions:l.array(Kye).optional().describe("behaviours the change leaves unsettled; no case asserts any of them"),maintenance:l.array(eEe),journeys:l.array(eY).optional().describe("the user journeys that, together, pass through everything the change alters that a user sees or does; empty when it alters nothing a user sees"),notInJourney:l.array(l.object({clause:de,why:de})).optional().describe("a clause a user sees or does that no journey walks, and why: none can reach it through the UI, or it is downstream of this change and not walked here"),unplannedComponents:l.array(l.object({components:l.array(de).min(1).describe("changed components, as the change lists them"),why:de})).optional().describe("changed components no clause reaches, and why their change needs no test; several may share one reason"),triage:AA.optional().describe("the validation triage decision, made before the app is started; its behaviorIds are clause ids"),app:tEe.optional().describe("omit when no app was needed or none was started"),summary:de.describe("one paragraph: what the change does and where the risk is")});var mA=(n=>(n.Backend="backend",n.Ui="ui",n))(mA||{});var Oo=(r=>(r.Added="added",r.Updated="updated",r.Deleted="deleted",r.Unchanged="unchanged",r))(Oo||{}),nEe=l.object({file:de.describe("repo-relative path; in another repo of the change, that repo's directory name then its path"),kind:l.nativeEnum(mA),change:l.nativeEnum(Oo).describe("added: a file you created; updated / deleted / unchanged: an existing test"),covers:l.array(l.string()).describe("the plan case ids this file tests, each with its own result under result.cases"),defect:l.boolean().optional().describe("true when a case of it fails because the app is wrong and the test is right \u2014 kept failing on purpose"),staleBecause:l.object({requirement:de.describe("the requirement or clause id the change deliberately alters"),line:de.describe("path:line (or path) of the application code the change altered that makes this test's old expectation wrong")}).optional().describe("for an existing test you updated or deleted: why it is out of date"),staleOnBase:l.boolean().optional().describe("for an existing test that fails: true when it fails the same way on the base branch because its own expectation is wrong (the app there does what it should), so this change did not make it wrong. Not when the base app's own bug fails it: that is an existing defect. Leave it as it is (unchanged): its failure is the test's own"),result:l.object({started:l.boolean().optional().describe("whether this file's test command started; required for a shared-environment run with exit null: true if interrupted or timed out, false if it never started"),exit:l.number().nullable().describe("exit code of your last run of this file; null if it could not be run"),cases:l.array(l.object({case:de,status:l.nativeEnum(Vr),runtimeTargets:Fp.optional().describe("HTTP(S) URLs this case actually exercised in its current run, from its request or browser evidence; omit for local in-process/mocked checks, never list the shared app merely because it is configured"),defect:l.boolean().optional().describe("for a failing case: true when the app is wrong and the test is right; false when the test is at fault and you could not fix it"),testProblem:Rm.optional().describe("for a failing case marked defect: false: what in the test is at fault"),failure:l.string().optional().describe("for a failing case: the runner's failure for it as printed (the error and the line it was raised at), not a summary"),cause:l.string().optional().describe("for a case you keep as a defect: path:line of the application code that makes it fail"),requires:l.string().optional().describe("for a case you keep as a defect: the words of the PR description, a requirement or clause of the plan, or the code a finding's keeps names, that state what its failing check expects, quoted exactly")})).describe("one entry per covered case, from the runner's own output"),details:l.string().optional().describe("what failed and why, or why it was not run"),noCases:l.string().optional().describe("for a failed run whose runner reported none of this file's tests (it failed to compile, import or collect): why")}),assertions:l.array(l.object({case:de,evidence:de})).optional().describe("per covered case, the assertion line that checks its expected outcome"),functions:l.array(l.object({name:de.describe("the test function as the runner names it within its file, without the file (test_x, TestClass::test_x, TestSuite/TestCase)"),cases:l.array(de).describe("the plan case ids it checks"),testProblem:Rm.optional().describe("for a function that fails because of the test itself, while another function keeps a case it checks as a defect: what in it is at fault")})).optional().describe("for a file you added or updated: each test function in it and the plan case ids it checks"),skyramp:l.object({draft:l.union([l.string(),l.array(l.string())]).optional().describe("the draft path the Skyramp helper returned for this test, or each path when the test was made from several drafts"),handWritten:l.string().optional().describe("why it is written by hand: the helper call you made and what it returned")}).optional().describe("only for a test of a case the Skyramp API block lists: where it came from"),context:l.array(Up).optional().describe("what the test sets up outside its own process that another test could run into: data it creates in the app, a Skyramp mock, an env override; omit when none"),isolatedRun:de.optional().describe("for a test with a context: the command, from its checkout's root and without a shell, that runs only this file"),ci:gY.optional().describe("for a file you added or updated: whether the repo's CI will run it, and how you know"),run:Yl.optional().describe(`for a file in ${Wl}, added, updated or re-run: how the run executes only this file's tests, with the repository's own runner and the report it writes (junit, trx or jest-json to ${wn}, or go-test-json); Testbot runs it before write ends and re-runs the tests with it`)}),rEe=e=>{if(!e||typeof e!="object")return e;let{test:t,...n}=e;return typeof t=="string"&&t.trim()&&n.tests===void 0?{...n,tests:[t]}:e},iEe=l.preprocess(rEe,l.object({description:de.describe("what is wrong and how to reproduce it: endpoint or page, input, what you got vs what was expected"),severity:l.nativeEnum(Rc).optional(),sourceFile:l.string().optional().describe("the app file at fault"),sourceLine:l.number().optional(),tests:l.array(de).optional().describe("every test file that fails because of it: a defect several tests show is one issue"),finding:l.string().optional().describe("the plan's finding id, when it is one"),requirements:l.array(de).optional().describe("the plan's requirement or clause ids it violates")})),RPe=l.object({schemaVersion:l.literal(1),tests:l.array(nEe),notWritten:l.array(l.object({case:de,reason:de,coveredBy:l.object({file:de.describe("the test file, relative to the working checkout; prefix a related checkout as for tests[].file"),name:de.describe("the test function as the runner names it within its file, without the file (test_x, TestClass::test_x, TestSuite/TestCase)")}).optional().describe("only for an existing test triage independently linked to this exact case: its exact runner name (including class or describe titles). Testbot must finish re-running it with every result passed. If your own test covers the case, include the case in its covers and function cases instead")})).describe("every plan case no test covers, and why"),journeys:l.array(kv).optional().describe("one entry per planned user journey: the browser test that walks it end to end"),lint:l.object({command:l.string(),clean:l.boolean()}).optional().describe("the linter/formatter you ran on your test files, if the repo has one: the exact command, with its file paths (Testbot re-runs it)"),dependenciesAdded:l.array(l.object({package:de,manifest:de.describe("the manifest file's path relative to its checkout (e.g. package.json, pom.xml or pyproject.toml), and nothing else; name another checkout in repository"),repository:de.optional().describe("owner/repo of the manifest's checkout; omit for the repo under test"),reason:de.optional().describe("why the test must run inside the application's own test environment, so its manifest had to change \u2014 required for every entry")})).optional().describe("every package you added to an APPLICATION manifest (an exception, surfaced in the report); never the Testbot test package's own"),supportFiles:l.array(de).optional().describe("every file that is not a test you created or changed for your tests, which they need to compile or run (a helper module, page object, fixture, or a snapshot the runner wrote for them), named as you name a test; Testbot delivers only the tests you list and the files under supportFiles"),ciNotes:l.string().optional().describe("for each test whose ci says the repo's CI will not run it: the test, and the exact change the author must make for CI to run it"),commit:l.object({message:de.describe("subject line at most 72 characters, following the repository's commit-message checks"),prTitle:de.describe("at most 72 characters, following the repository's PR-title checks"),prBody:de.describe("what the tests cover and what they found")}),report:l.object({summary:de.describe("1-2 sentences for the PR author: does the change do what it says? No count of tests: the report gives it"),issues:l.array(iEe).describe("every defect the tests found"),nextSteps:l.array(l.string()),noTests:l.array(l.object({repository:de,reason:de.max(4096)})).max(1e3).optional().describe("each Change Set repository where no test was added or updated: its owner/repo and why, naming the other repository when its tests went there"),notesDeviation:l.string().trim().max(4096).optional().describe("when the Target notes say where tests go and a test you added went elsewhere: where it went, and why; omit otherwise")})});var xPe={added:"place",updated:"update",deleted:"delete",unchanged:"verify"};var bY=(i=>(i.Requirement="requirement",i.PrDescription="pr_description",i.Code="code",i))(bY||{}),cn=l.string().trim().min(1),sEe=l.object({expectation:cn.max(300).describe("the behavior this assertion pins, in words"),source:l.nativeEnum(bY),expected:cn.max(200).describe("the exact value or outcome asserted, as the test asserts it")}),oEe=l.object({file:cn.describe("path of the NEW test file you wrote, relative to its repository"),repository:cn.optional().describe("owner/repo the file lives in, when the run has several checkouts; omit for the working checkout"),framework:cn.describe("the framework the repository runs this file with: pytest, jest, vitest, node-test, or the name of any other"),run:Yl.optional().describe(`for ${Wl}: how the run executes only the tests in names, with the repository's own runner writing JUnit XML to {junit}`),covers:l.array(cn).length(1).describe("the ONE behavior id, or defect id, from the plan that the tests in names provide evidence for; a file covering several is listed once per id"),names:l.array(cn).min(1).describe("the test functions/cases in the file that provide evidence for that behavior, as the framework names them"),assertions:l.array(sEe).min(1)}),yA=(n=>(n.Updated="updated",n.Deleted="deleted",n))(yA||{}),vY=300,aEe=l.object({file:cn.describe("path of the EXISTING test file you updated or deleted, relative to its repository"),repository:cn.optional().describe("owner/repo the file lives in, when the run has several checkouts; omit for the working checkout"),change:l.nativeEnum(yA),staleBecause:l.object({requirement:cn.describe("the requirement or clause id the change deliberately alters"),line:cn.describe("path:line (or path) of the application code the change altered that makes this test's old expectation wrong")}).optional().describe("for an existing test you updated: why it is out of date"),reason:l.preprocess(e=>typeof e=="string"?e.trim().slice(0,vY):e,cn.max(vY)).describe("what the change deliberately altered that made the test wrong")}),MT=l.object({schemaVersion:l.literal(1),tests:l.array(oEe),maintained:l.array(aEe).optional().describe("existing tests the change made stale that you updated or deleted; omit when there were none"),defectsNotTested:l.array(l.object({id:cn,reason:cn.max(300)})).optional().describe("defects the plan found that no in-process test can reach, each with why; omit when every defect has a test"),journeys:l.array(kv).optional().describe("one entry per planned user journey: the in-process test that walks it end to end"),journeysNotWritten:l.array(l.object({journey:cn,missing:cn.transform(e=>e.length>300?`${e.slice(0,299)}\u2026`:e)})).optional().describe("a planned journey no in-process test can walk here, with what it needs that is missing; it is reported as not covered"),lint:l.object({command:l.string(),clean:l.boolean()}).optional().describe("the linter/formatter you ran on your test files, if the repository has one you can run; omit otherwise"),commitMessage:cn.optional().describe("the commit message for your tests: a subject line of at most 72 characters, then what they cover")});var EA="generate-unit.json";function uEe(e){let{value:t,error:n}=_t(e);if(n)return{errors:[n]};let{value:i,errors:r}=vn(MT,t);return r.length?{errors:r}:{output:i,errors:[]}}function lEe(e){return uEe(e.stdout)}var gUe=Zn("generate-unit-schema",(e,t)=>lEe(t));var $v=String.raw`(?:node:)?(?:http|https|http2|net|tls|dgram)`,mUe=[[/\b(localhost|127\.0\.0\.1|0\.0\.0\.0)\b/,"a local server address"],[/^\s*(import|from)\s+(requests|aiohttp|urllib3|websockets?)\b/m,"an HTTP client"],[/^\s*(?:import|from)\s+(?:urllib\.request|http\.client|http\.server|socket|ssl|ftplib|smtplib|telnetlib)\b|^\s*from\s+urllib\s+import\b[^\n]*\brequest\b|\burlopen\s*\(/m,"a standard-library network client"],[/\bfrom\s+["'](axios|node-fetch|undici|ws)["']|require\(\s*["'](axios|node-fetch|undici|ws)["']\s*\)/,"an HTTP client"],[new RegExp(String.raw`\bfrom\s+["']${$v}["']|\bimport\s+["']${$v}["']|require\(\s*["']${$v}["']\s*\)|\bimport\(\s*["']${$v}["']\s*\)`),"Node's network modules"],[/\bfetch\s*\(|\bnew\s+(XMLHttpRequest|WebSocket)\b/,"a network call (fetch, XMLHttpRequest, WebSocket)"],[/\bskyramp\b/i,"the Skyramp runtime (a runtime mock or client)"]];var FUe=new Set(["targeted_unit","existing_evidence_sufficient"]);var Mo=ce(require("path"));var ZUe={"application/pdf":"PDF","text/csv":"CSV","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX"};var jT=e=>new Map((e??[]).flatMap(t=>t.file?[[_p(t.key),t.file.name]]:[])),hEe=10*1024*1024,gEe=e=>e?.mediaType==="application/vnd.openxmlformats-officedocument.wordprocessingml.document"||e?.mediaType==="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",RY=(e,t)=>Mo.join(Mo.dirname(e),`${Mo.basename(e,Mo.extname(e))}${t}`),mEe=e=>RY(e,".extracted.txt");var yEe=e=>RY(e,".quotes.txt");function xY(e){return gEe(e.file)?mEe(e.path):e.file?.mediaType==="application/pdf"?yEe(e.path):e.path}var IEe="triage.json";var JFe=new Set(["existing_evidence","unaffected","existing_unit","new_unit","runtime"]),HFe={existing_evidence:"existing evidence",unaffected:"showing the change cannot reach it",existing_unit:"running the existing unit tests",new_unit:"a new unit test",runtime:"tests against the running application"};function wEe(e){let{value:t,error:n}=_t(e);if(n)return{errors:[n]};let{value:i,errors:r}=vn(AA,t);return r.length?{errors:r}:{triage:i,errors:[]}}function CEe(e){return wEe(e.stdout)}var YFe=Zn("triage-schema",(e,t)=>CEe(t));function SEe(e){let t=e.inputs?.pipeline;return t?e.state.stages[t==="two-step"?"plan":"triage"]:e.state.stages.triage??e.state.stages.plan}function VT(e){if(SEe(e)?.status==="passed")return go($Y.join(e.outputsDir,IEe))}function GT(e){return OH(wT(e.inputs,Ke(e,`${Jl}.json`),VT(e)?.sutRequired))}var WFe=new Set(["deploy","recommend","generate","generate-ui","adapt","generate-unit","native-run","finalize","deliver"]);xn();xn();function TY(e,t){return t?`<!-- skyramp-testbot-run: ${t} -->
163
163
  ${e}`:e}var DY=600,Tv=300;function _Y(e){return typeof e=="string"?e.trim():e instanceof Buffer?e.toString("utf-8").trim():""}function kEe(e){let t=e,n=(typeof t?.message=="string"?t.message:String(e)).trim(),i=[_Y(t?.stderr),_Y(t?.stdout)].filter(Boolean);return i.length?[n.split(`
164
164
  `)[0],...i].join(`
165
165
  `):n}function NY(e,t,n,i=0){let r=e.join(t);if(r.length<=n)return r;let[s="",...o]=e;if(!o.length)return`${s.slice(0,n-1)}\u2026`;let a=s.length<=i?s:s.slice(0,Math.floor(n/3)),c=n-a.length-t.length-1;return`${a}${t}\u2026${o.join(t).slice(-c)}`}function PY(e,t){return NY(e.trim().split(`
@@ -181,12 +181,12 @@ ${n}`}function ZY(e){let t=[],n=!1;for(let i of e.split(`
181
181
  `))/^\s*signed-off-by:/i.test(i)?n=!0:n&&i.trim()===""&&t.at(-1)?.trim()===""||(t.push(i),n=!1);return t.join(`
182
182
  `).replace(/\s+$/,"")}function qT(e){let t=/\b(claude|anthropic)\b/i;return e.split(`
183
183
  `).filter(i=>{let r=i.trim();return!(/^co-authored-by:/i.test(r)&&t.test(r))&&!(/^[^\w\s]*\s*generated (?:with|by) /i.test(r)&&t.test(r))}).join(`
184
- `).replace(/\s+$/,"")}var Pv="Skyramp-Pull-Request",Xl="Skyramp-Delivery-Base",JT="Skyramp-Tested-Revision";var COe=["%H","%P","%an","%ae","%ce",`%(trailers:key=${Pv},valueonly,separator=%x2C)`,"%s",`%(trailers:key=${Xl},valueonly,separator=%x2C)`,`%(trailers:key=${JT},valueonly,separator=%x2C)`];function HT(e,t){let n=e(["log","-1","--format=%B"]);if(!n.includes(`${Pv}:`)&&!n.includes(`${Xl}:`))return;let i=n.split(`
184
+ `).replace(/\s+$/,"")}var Pv="Skyramp-Pull-Request",Xl="Skyramp-Delivery-Base",JT="Skyramp-Tested-Revision";var SOe=["%H","%P","%an","%ae","%ce",`%(trailers:key=${Pv},valueonly,separator=%x2C)`,"%s",`%(trailers:key=${Xl},valueonly,separator=%x2C)`,`%(trailers:key=${JT},valueonly,separator=%x2C)`];function HT(e,t){let n=e(["log","-1","--format=%B"]);if(!n.includes(`${Pv}:`)&&!n.includes(`${Xl}:`))return;let i=n.split(`
185
185
  `).filter(o=>!o.startsWith(`${Xl}:`)).join(`
186
186
  `).trimEnd(),r=t?`${i}
187
187
  ${Xl}: ${t}`:i;e(["log","-1","--format=%(trailers:key=Signed-off-by,valueonly)"]).split(`
188
- `).some(o=>o.trim().toLowerCase()===`${Es} <${mo}>`.toLowerCase())&&(r=Nv(r,{name:Es,email:mo})),e(["-c",`user.name=${Es}`,"-c",`user.email=${mo}`,"commit","--amend","--allow-empty","-m",r])}var jo=ce(require("fs")),KT=ce(require("path"));function un(e){let t=Math.max(0,...(e.match(/`+/g)??[]).map(r=>r.length)),n="`".repeat(t+1),i=e.startsWith("`")||e.endsWith("`")?" ":"";return`${n}${i}${e}${i}${n}`}var lMe=5*6e4,dMe=12*6e4,pMe=2*6e4;var yMe=["class TestbotProjectBrowsers {"," onBegin(config) {",' const projects = config.projects.map((p) => ({ browserName: p.use.browserName ?? p.use.defaultBrowserType ?? "chromium", channel: p.use.channel ?? null }));',' process.stdout.write("TESTBOT_PROJECT_BROWSERS " + JSON.stringify(projects) + "\\n");'," }"," printsToStdio() { return true; }","}","module.exports = TestbotProjectBrowsers;",""].join(`
189
- `);var RMe=[...uS,"AWS_REGION","AWS_DEFAULT_REGION","AWS_ENDPOINT_URL","AWS_ENDPOINT_URL_BEDROCK_RUNTIME","AWS_ENDPOINT_URL_STS","AWS_SHARED_CREDENTIALS_FILE","AWS_CONFIG_FILE","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BASE_URL","ANTHROPIC_BEDROCK_BASE_URL"].filter((e,t,n)=>n.indexOf(e)===t);var Uv=ce(Dk());var KMe={jest:"jest",vitest:"vitest"};var TLe=new Set(["jest","vitest","npm-test","playwright"]);var zLe=5*6e4;var wA=ce(require("path"));var pje={python:"pytest",typescript:"playwright",javascript:"playwright"},fje={pytest:"pytest",playwright:"playwright"};function rve(e){return vn(_T,e).errors}function ive(e,t=[]){let{value:n,error:i}=_t(e,t);if(i)return{errors:[i]};let r=rve(n);return r.length>0?{errors:r}:{finalize:n,errors:[]}}var sve="finalize-scratch";function ove(e,t){let n=ive(e.stdout,t?.secretValues);if(!n.finalize||!t?.outputsDir)return n;let i=(r,s)=>r.trim()&&dy(r.trim(),wA.join(t.outputsDir,sve,s),"finalize")||r;return{...n,finalize:{...n.finalize,lint:n.finalize.lint.map((r,s)=>({...r,command:i(r.command??"",`lint-${s+1}.sh`)}))}}}var t1e=Zn("finalize-schema",(e,t)=>ove(t,e));function YT(e){return e.functions?.length?e.functions:[(e.testType==="unit"?e.testId.split("::").slice(1).join("::").replace(/\[.*\]$/,""):"")||e.testId]}function ed(e){return new Set(e.flatMap(t=>YT(t).map(n=>`${t.repository??""}\0${t.fileName}\0${n}`))).size}function ave(e){return vn(TT,e).errors}function tW(e,t=[]){let{value:n,error:i}=_t(e,t);if(i)return{errors:[i]};let r=ave(n);return r.length>0?{errors:r}:{analysis:n,errors:[]}}function cve(e,t=[]){return tW(e.stdout,t)}var C1e=Zn("analysis-schema",(e,t)=>cve(t,e.secretValues));var VVe=cm.rows.notRun(!0);var CA="kept, not ";var SA="(declined the planned ";function WT(e){if(!e)return[];let t=[],n=0,i=0;for(let r=0;r<e.length;r++){let s=e[r];s==="("?n++:s===")"?n=Math.max(0,n-1):n===0&&s===";"&&e[r+1]===" "&&e[r-1]===")"&&(t.push(e.slice(i,r)),i=r+2)}return t.push(e.slice(i)),t.map(r=>{let s=r.trim();if(!s.endsWith(")"))return{expectation:s};let o=0;for(let a=s.length-1;a>=0;a--)if(s[a]===")")o++;else if(s[a]==="("&&--o===0){let c=s.slice(0,a).trim(),u=s.slice(a+1,-1).trim();return c&&u?{expectation:c,expected:u}:{expectation:s}}return{expectation:s}})}var nW=new Set(["update","regenerate","delete"]);var GVe={update:"updated",regenerate:"regenerated",delete:"deleted",verify:"verified",none:"touched"};var rW=l.string().trim().min(1),ZT=l.object({schemaVersion:l.literal(1).optional(),businessCaseAnalysis:rW.describe("1-2 sentences: what this change means for a user, and whether the evidence shows it working; no count of tests, which the report gives"),issuesFound:l.array(l.object({description:rW,severity:l.string().optional().describe("critical | high | medium | low"),category:l.string().optional().describe("bug | lint | type | config"),sourceFile:l.string().optional(),sourceLine:l.number().optional(),findingId:l.string().optional(),requirementIds:l.array(l.string()).optional()})).describe("every real problem this run exposed \u2014 cause, file:line, severity"),nextSteps:l.array(l.string()).describe("concrete follow-ups the author can act on; required non-empty when a disclosure is BLOCKING")});function hve(e){return vn(ZT,e).errors}function gve(e,t=[]){let{value:n,error:i}=_t(e.stdout,t);if(i)return{errors:[i]};let r=hve(n);return r.length>0?{errors:r}:{prose:n,errors:[]}}var tGe=Zn("report-schema",(e,t)=>gve(t,e.secretValues));var Eve="report.json",vve="report-display.json",pGe={en:"English",ja:"Japanese"};function sW(e){let t=KT.join(e,vve);if(jo.existsSync(t))try{return JSON.parse(jo.readFileSync(t,"utf-8"))}catch{}let n=KT.join(e,Eve);return jo.existsSync(n)?JSON.parse(jo.readFileSync(n,"utf-8")):void 0}var KW=require("node:zlib");var mGe=["clean","recipe-drift"];var pi=ce(require("fs")),Vo=ce(require("path")),QW=ce(require("crypto")),$W=require("child_process");var e0=require("child_process"),td=ce(require("fs")),oW=ce(require("os")),Lv=ce(require("path"));var bve={onPath:e=>(0,e0.spawnSync)("sh",["-c",`command -v ${e}`],{stdio:"ignore"}).status===0,run:(e,t)=>(0,e0.spawnSync)(e[0],e.slice(1),{cwd:t,stdio:"ignore",timeout:6e4}).status??1},Mv={cleanup:()=>{}},Ive=new Set(["pnpm","yarn"]);function aW(e,t=oW.tmpdir(),n=bve){if(process.platform==="win32")return Mv;try{let i=Pk(e);if(!Ive.has(i)||n.onPath(i)||!n.onPath("corepack"))return Mv;td.mkdirSync(t,{recursive:!0});let r=td.mkdtempSync(Lv.join(t,"testbot-pm-")),s=()=>td.rmSync(r,{recursive:!0,force:!0});return n.run(["corepack","enable","--install-directory",r,i],e)!==0?(s(),Mv):{dir:r,cleanup:s}}catch{return Mv}}function cW(e,t=process.env){return e.dir?{...t,PATH:[e.dir,t.PATH].filter(Boolean).join(Lv.delimiter)}:t}var BA=require("crypto");var uW="<!-- skyramp-testbot -->",lW=nW,wve=new Set(["lint","type","config"]),dW={critical:0,high:1,medium:2,low:3},mW=new Set(["Pass","Fail"]);var r0=e=>Fa(ie().statusLabels,e),t0=e=>Fa(ie().testTypeCellLabels,e);function tt(e){return(e??"").replace(/\|/g,"\\|").replace(/\r?\n/g,"<br>").trim()}function pW(e){return e.inferred?" (inferred)":""}function fW(e,t){return!e||!mW.has(e)?"\u2014":t?`${r0(e)} (${tt(yW(t))})`:r0(e)}function yW(e){let t=i=>{let r=i.indexOf(": ");return r<0?i:Fa(ie().staged.maintenanceActions,i.slice(0,r))+i.slice(r)};if(e.startsWith(CA))return ie().staged.keptNot+t(e.slice(CA.length));let n=e.indexOf(SA);return n<0?e:e.slice(0,n)+ie().staged.declinedPlanned+t(e.slice(n+SA.length))}function AW(e){return e.category!==void 0&&wve.has(e.category.toLowerCase())}function hW(e,t){return(dW[(e.severity??"").toLowerCase()]??4)-(dW[(t.severity??"").toLowerCase()]??4)}function gW(e){return`- ${e.severity?`**[${Fa(ie().severityLabels,e.severity.toLowerCase()).toUpperCase()}]** `:""}${e.description.trim()}`}function Cve(e){let t=e.resultId?.split("#").slice(1).join("#");if(e.testType!=="unit"||!t)return;let n=t;try{n=decodeURIComponent(t)}catch{}let i=/^(.*?)(\[.*\])$/.exec(n);return i?{fn:i[1],kase:i[2]}:{fn:n}}var EW=(e,t)=>e!==void 0&&t!==void 0&&e.replace(/^\.\//,"")===t.replace(/^\.\//,"");function vW(e,t){return(e.testVideos??[]).find(n=>n.url&&t(n))?.url}function i0(e,t){return vW(e,n=>EW(n.fileName,t.fileName)&&(!n.repository||!t.repository||n.repository.toLowerCase()===t.repository.toLowerCase()))}function s0(e,t){return vW(e,n=>EW(n.writtenAs??n.fileName,t))}function Sve(e,t,n){return n?i0(e,{fileName:t,repository:n}):s0(e,t)}function kve(e){let t=[],n=new Map;for(let o of e.newTestsCreated)o.testType==="unit"&&n.set(o.fileName,[...n.get(o.fileName)??[],o.testId.split("::").slice(1).join("::")]);let i=new Map,r=(o,a)=>(n.get(o??"")??[]).find(c=>c!==a&&Cz(a,c)),s=new Map;for(let o of e.testResults){let a=Cve(o),c=a&&!a.kase?r(o.fileName,a.fn):void 0;if(a&&c&&(a={fn:c,kase:`"${a.fn}"`}),a?.kase&&i.set(o,a.kase),!a){t.push({testId:o.testId,testType:o.testType,endpoint:o.endpoint,status:o.status,details:o.details??"",...o.fileName?{fileName:o.fileName}:{},...o.repository?{repository:o.repository}:{}});continue}let u=`${o.fileName??""}#${a.fn}`,d=s.get(u);d||(d={row:{testId:o.testId,testType:o.testType,endpoint:o.endpoint,status:o.status,details:"",test:a.fn,...o.fileName?{fileName:o.fileName}:{},...o.repository?{repository:o.repository}:{}},cases:[]},s.set(u,d),t.push(d.row)),d.cases.push(o)}for(let{row:o,cases:a}of s.values()){let c=a.filter(A=>A.status==="Fail"),u=a.filter(A=>A.status==="Pass").length,d=a.filter(A=>A.status==="Skipped").length;o.cases=a.length,o.status=c.length?"Fail":d?"Skipped":"Pass";let p=c[0];o.details=a.length===1?a[0].details??"":ie().staged.casesPassed(u,a.length,d)+(p?`; ${i.get(p)??""} ${p.details??""}`.replace(/; +/,"; ").trimEnd():"")}return t}function Bve(e){return WT(e).map(t=>t.expected===void 0?t.expectation:`${t.expectation}: ${un(t.expected)}`)}function n0(e){return e.newTestsCreated.some(t=>t.testType!=="unit")&&e.testResults.every(t=>t.status==="Skipped")&&e.testResults.some(t=>t.failureCause?.kind==="environment"&&(t.failureCause.family==="app_not_started"||t.failureCause.family==="secret"))}function bW(e,t={}){let{audience:n,collapsed:i=!1,existingEvidence:r=[],requestedBy:s,sourcePullRequest:o}=t,a=n!=="testbot-pr",c=n!=="comment",u=n!=="testbot-pr",d=(e.requirements??[]).filter(F=>/^file-[a-f0-9]{16}-/i.test(F.id)).sort((F,te)=>te.id.length-F.id.length),p=F=>{let te=d.find(O=>F.toLowerCase().startsWith(O.id.toLowerCase()));return te?te.label+F.slice(te.id.length):F},A=[uW];if(o&&A.push(ie().staged.testsSourcePullRequest(un(o)),""),s){let F=s.name.replace(/\s+/g," ").trim().replace(/[<>[\]()*_`\\|#]/g,"\\$&").replace(/@/g,"@\u200D");A.push(s.kind==="person"?ie().staged.requestedByPerson(F):ie().staged.requestedByPolicy(F),"")}e.notTranslated&&A.push(Fa(ie().staged.notTranslated,e.notTranslated),"");let h=F=>{i?A.push("<details>",`<summary>${F}</summary>`,""):A.push(`### ${F}`)},g=()=>{i&&A.push("","</details>"),A.push("")};if(a){for(let F of e.businessCaseAnalysis.trim().split(/\r?\n/))A.push(`> ${F}`);A.push("")}if(n0(e)&&A.push(ie().staged.noLiveApp(ed(e.newTestsCreated)),""),c&&e.newTestsCreated.length){let F=new Map;for(let O of e.newTestsCreated){if(O.testType!=="unit")continue;let De=YT(O)[0],ve=F.get(O.fileName)??{functions:new Set,endpoints:[],descriptions:new Map};O.endpoint&&!ve.endpoints.includes(O.endpoint)&&ve.endpoints.push(O.endpoint);let J=O.description?.trim()??"",U=ve.descriptions.get(De)??[];U.includes(J)||U.push(J),ve.functions.add(De),ve.descriptions.set(De,U),F.set(O.fileName,ve)}let te=e.newTestsCreated.filter(O=>O.testType!=="unit");h(ie().testRecommendationsImplementedHeader(ed(e.newTestsCreated),te.length+ed(e.newTestsCreated.filter(O=>O.testType==="unit"))));for(let[O,{functions:De,endpoints:ve,descriptions:J}]of F){let U=De.size;A.push(ie().staged.unitTestsInFile(`\`${O}\``,U,ve.map(Zt=>`\`${Zt}\``).join(", ")),"");let Rt=new Map;for(let[Zt,yt]of J){let dn=yt.join("\0"),$t=Rt.get(dn)??{fns:[],descriptions:yt};$t.fns.push(Zt),Rt.set(dn,$t)}let at=0;for(let{fns:Zt,descriptions:yt}of Rt.values()){A.push(`${++at}. ${Zt.map($t=>`\`${$t}\``).join(", ")}`);let dn=[...new Set(yt.flatMap($t=>Bve($t)))];for(let $t of dn)A.push(` - ${$t}`)}A.push("")}for(let O of te){let De=O.testId?un(p(O.testId)):t0(O.testType),ve=O.fileName?` (\`${O.fileName}\`)`:"",J=O.endpoint?`
188
+ `).some(o=>o.trim().toLowerCase()===`${Es} <${mo}>`.toLowerCase())&&(r=Nv(r,{name:Es,email:mo})),e(["-c",`user.name=${Es}`,"-c",`user.email=${mo}`,"commit","--amend","--allow-empty","-m",r])}var jo=ce(require("fs")),KT=ce(require("path"));function un(e){let t=Math.max(0,...(e.match(/`+/g)??[]).map(r=>r.length)),n="`".repeat(t+1),i=e.startsWith("`")||e.endsWith("`")?" ":"";return`${n}${i}${e}${i}${n}`}var dMe=5*6e4,pMe=12*6e4,fMe=2*6e4;var EMe=["class TestbotProjectBrowsers {"," onBegin(config) {",' const projects = config.projects.map((p) => ({ browserName: p.use.browserName ?? p.use.defaultBrowserType ?? "chromium", channel: p.use.channel ?? null }));',' process.stdout.write("TESTBOT_PROJECT_BROWSERS " + JSON.stringify(projects) + "\\n");'," }"," printsToStdio() { return true; }","}","module.exports = TestbotProjectBrowsers;",""].join(`
189
+ `);var xMe=[...uS,"AWS_REGION","AWS_DEFAULT_REGION","AWS_ENDPOINT_URL","AWS_ENDPOINT_URL_BEDROCK_RUNTIME","AWS_ENDPOINT_URL_STS","AWS_SHARED_CREDENTIALS_FILE","AWS_CONFIG_FILE","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BASE_URL","ANTHROPIC_BEDROCK_BASE_URL"].filter((e,t,n)=>n.indexOf(e)===t);var Uv=ce(Dk());var XMe={jest:"jest",vitest:"vitest"};var _Le=new Set(["jest","vitest","npm-test","playwright"]);var qLe=5*6e4;var wA=ce(require("path"));var fje={python:"pytest",typescript:"playwright",javascript:"playwright"},Aje={pytest:"pytest",playwright:"playwright"};function rve(e){return vn(_T,e).errors}function ive(e,t=[]){let{value:n,error:i}=_t(e,t);if(i)return{errors:[i]};let r=rve(n);return r.length>0?{errors:r}:{finalize:n,errors:[]}}var sve="finalize-scratch";function ove(e,t){let n=ive(e.stdout,t?.secretValues);if(!n.finalize||!t?.outputsDir)return n;let i=(r,s)=>r.trim()&&dy(r.trim(),wA.join(t.outputsDir,sve,s),"finalize")||r;return{...n,finalize:{...n.finalize,lint:n.finalize.lint.map((r,s)=>({...r,command:i(r.command??"",`lint-${s+1}.sh`)}))}}}var n1e=Zn("finalize-schema",(e,t)=>ove(t,e));function YT(e){return e.functions?.length?e.functions:[(e.testType==="unit"?e.testId.split("::").slice(1).join("::").replace(/\[.*\]$/,""):"")||e.testId]}function ed(e){return new Set(e.flatMap(t=>YT(t).map(n=>`${t.repository??""}\0${t.fileName}\0${n}`))).size}function ave(e){return vn(TT,e).errors}function tW(e,t=[]){let{value:n,error:i}=_t(e,t);if(i)return{errors:[i]};let r=ave(n);return r.length>0?{errors:r}:{analysis:n,errors:[]}}function cve(e,t=[]){return tW(e.stdout,t)}var S1e=Zn("analysis-schema",(e,t)=>cve(t,e.secretValues));var GVe=cm.rows.notRun(!0);var CA="kept, not ";var SA="(declined the planned ";function WT(e){if(!e)return[];let t=[],n=0,i=0;for(let r=0;r<e.length;r++){let s=e[r];s==="("?n++:s===")"?n=Math.max(0,n-1):n===0&&s===";"&&e[r+1]===" "&&e[r-1]===")"&&(t.push(e.slice(i,r)),i=r+2)}return t.push(e.slice(i)),t.map(r=>{let s=r.trim();if(!s.endsWith(")"))return{expectation:s};let o=0;for(let a=s.length-1;a>=0;a--)if(s[a]===")")o++;else if(s[a]==="("&&--o===0){let c=s.slice(0,a).trim(),u=s.slice(a+1,-1).trim();return c&&u?{expectation:c,expected:u}:{expectation:s}}return{expectation:s}})}var nW=new Set(["update","regenerate","delete"]);var zVe={update:"updated",regenerate:"regenerated",delete:"deleted",verify:"verified",none:"touched"};var rW=l.string().trim().min(1),ZT=l.object({schemaVersion:l.literal(1).optional(),businessCaseAnalysis:rW.describe("1-2 sentences: what this change means for a user, and whether the evidence shows it working; no count of tests, which the report gives"),issuesFound:l.array(l.object({description:rW,severity:l.string().optional().describe("critical | high | medium | low"),category:l.string().optional().describe("bug | lint | type | config"),sourceFile:l.string().optional(),sourceLine:l.number().optional(),findingId:l.string().optional(),requirementIds:l.array(l.string()).optional()})).describe("every real problem this run exposed \u2014 cause, file:line, severity"),nextSteps:l.array(l.string()).describe("concrete follow-ups the author can act on; required non-empty when a disclosure is BLOCKING")});function hve(e){return vn(ZT,e).errors}function gve(e,t=[]){let{value:n,error:i}=_t(e.stdout,t);if(i)return{errors:[i]};let r=hve(n);return r.length>0?{errors:r}:{prose:n,errors:[]}}var nGe=Zn("report-schema",(e,t)=>gve(t,e.secretValues));var Eve="report.json",vve="report-display.json",fGe={en:"English",ja:"Japanese"};function sW(e){let t=KT.join(e,vve);if(jo.existsSync(t))try{return JSON.parse(jo.readFileSync(t,"utf-8"))}catch{}let n=KT.join(e,Eve);return jo.existsSync(n)?JSON.parse(jo.readFileSync(n,"utf-8")):void 0}var KW=require("node:zlib");var yGe=["clean","recipe-drift"];var pi=ce(require("fs")),Vo=ce(require("path")),QW=ce(require("crypto")),$W=require("child_process");var e0=require("child_process"),td=ce(require("fs")),oW=ce(require("os")),Lv=ce(require("path"));var bve={onPath:e=>(0,e0.spawnSync)("sh",["-c",`command -v ${e}`],{stdio:"ignore"}).status===0,run:(e,t)=>(0,e0.spawnSync)(e[0],e.slice(1),{cwd:t,stdio:"ignore",timeout:6e4}).status??1},Mv={cleanup:()=>{}},Ive=new Set(["pnpm","yarn"]);function aW(e,t=oW.tmpdir(),n=bve){if(process.platform==="win32")return Mv;try{let i=Pk(e);if(!Ive.has(i)||n.onPath(i)||!n.onPath("corepack"))return Mv;td.mkdirSync(t,{recursive:!0});let r=td.mkdtempSync(Lv.join(t,"testbot-pm-")),s=()=>td.rmSync(r,{recursive:!0,force:!0});return n.run(["corepack","enable","--install-directory",r,i],e)!==0?(s(),Mv):{dir:r,cleanup:s}}catch{return Mv}}function cW(e,t=process.env){return e.dir?{...t,PATH:[e.dir,t.PATH].filter(Boolean).join(Lv.delimiter)}:t}var BA=require("crypto");var uW="<!-- skyramp-testbot -->",lW=nW,wve=new Set(["lint","type","config"]),dW={critical:0,high:1,medium:2,low:3},mW=new Set(["Pass","Fail"]);var r0=e=>Fa(ie().statusLabels,e),t0=e=>Fa(ie().testTypeCellLabels,e);function tt(e){return(e??"").replace(/\|/g,"\\|").replace(/\r?\n/g,"<br>").trim()}function pW(e){return e.inferred?" (inferred)":""}function fW(e,t){return!e||!mW.has(e)?"\u2014":t?`${r0(e)} (${tt(yW(t))})`:r0(e)}function yW(e){let t=i=>{let r=i.indexOf(": ");return r<0?i:Fa(ie().staged.maintenanceActions,i.slice(0,r))+i.slice(r)};if(e.startsWith(CA))return ie().staged.keptNot+t(e.slice(CA.length));let n=e.indexOf(SA);return n<0?e:e.slice(0,n)+ie().staged.declinedPlanned+t(e.slice(n+SA.length))}function AW(e){return e.category!==void 0&&wve.has(e.category.toLowerCase())}function hW(e,t){return(dW[(e.severity??"").toLowerCase()]??4)-(dW[(t.severity??"").toLowerCase()]??4)}function gW(e){return`- ${e.severity?`**[${Fa(ie().severityLabels,e.severity.toLowerCase()).toUpperCase()}]** `:""}${e.description.trim()}`}function Cve(e){let t=e.resultId?.split("#").slice(1).join("#");if(e.testType!=="unit"||!t)return;let n=t;try{n=decodeURIComponent(t)}catch{}let i=/^(.*?)(\[.*\])$/.exec(n);return i?{fn:i[1],kase:i[2]}:{fn:n}}var EW=(e,t)=>e!==void 0&&t!==void 0&&e.replace(/^\.\//,"")===t.replace(/^\.\//,"");function vW(e,t){return(e.testVideos??[]).find(n=>n.url&&t(n))?.url}function i0(e,t){return vW(e,n=>EW(n.fileName,t.fileName)&&(!n.repository||!t.repository||n.repository.toLowerCase()===t.repository.toLowerCase()))}function s0(e,t){return vW(e,n=>EW(n.writtenAs??n.fileName,t))}function Sve(e,t,n){return n?i0(e,{fileName:t,repository:n}):s0(e,t)}function kve(e){let t=[],n=new Map;for(let o of e.newTestsCreated)o.testType==="unit"&&n.set(o.fileName,[...n.get(o.fileName)??[],o.testId.split("::").slice(1).join("::")]);let i=new Map,r=(o,a)=>(n.get(o??"")??[]).find(c=>c!==a&&Cz(a,c)),s=new Map;for(let o of e.testResults){let a=Cve(o),c=a&&!a.kase?r(o.fileName,a.fn):void 0;if(a&&c&&(a={fn:c,kase:`"${a.fn}"`}),a?.kase&&i.set(o,a.kase),!a){t.push({testId:o.testId,testType:o.testType,endpoint:o.endpoint,status:o.status,details:o.details??"",...o.fileName?{fileName:o.fileName}:{},...o.repository?{repository:o.repository}:{}});continue}let u=`${o.fileName??""}#${a.fn}`,d=s.get(u);d||(d={row:{testId:o.testId,testType:o.testType,endpoint:o.endpoint,status:o.status,details:"",test:a.fn,...o.fileName?{fileName:o.fileName}:{},...o.repository?{repository:o.repository}:{}},cases:[]},s.set(u,d),t.push(d.row)),d.cases.push(o)}for(let{row:o,cases:a}of s.values()){let c=a.filter(A=>A.status==="Fail"),u=a.filter(A=>A.status==="Pass").length,d=a.filter(A=>A.status==="Skipped").length;o.cases=a.length,o.status=c.length?"Fail":d?"Skipped":"Pass";let p=c[0];o.details=a.length===1?a[0].details??"":ie().staged.casesPassed(u,a.length,d)+(p?`; ${i.get(p)??""} ${p.details??""}`.replace(/; +/,"; ").trimEnd():"")}return t}function Bve(e){return WT(e).map(t=>t.expected===void 0?t.expectation:`${t.expectation}: ${un(t.expected)}`)}function n0(e){return e.newTestsCreated.some(t=>t.testType!=="unit")&&e.testResults.every(t=>t.status==="Skipped")&&e.testResults.some(t=>t.failureCause?.kind==="environment"&&(t.failureCause.family==="app_not_started"||t.failureCause.family==="secret"))}function bW(e,t={}){let{audience:n,collapsed:i=!1,existingEvidence:r=[],requestedBy:s,sourcePullRequest:o}=t,a=n!=="testbot-pr",c=n!=="comment",u=n!=="testbot-pr",d=(e.requirements??[]).filter(F=>/^file-[a-f0-9]{16}-/i.test(F.id)).sort((F,te)=>te.id.length-F.id.length),p=F=>{let te=d.find(O=>F.toLowerCase().startsWith(O.id.toLowerCase()));return te?te.label+F.slice(te.id.length):F},A=[uW];if(o&&A.push(ie().staged.testsSourcePullRequest(un(o)),""),s){let F=s.name.replace(/\s+/g," ").trim().replace(/[<>[\]()*_`\\|#]/g,"\\$&").replace(/@/g,"@\u200D");A.push(s.kind==="person"?ie().staged.requestedByPerson(F):ie().staged.requestedByPolicy(F),"")}e.notTranslated&&A.push(Fa(ie().staged.notTranslated,e.notTranslated),"");let h=F=>{i?A.push("<details>",`<summary>${F}</summary>`,""):A.push(`### ${F}`)},g=()=>{i&&A.push("","</details>"),A.push("")};if(a){for(let F of e.businessCaseAnalysis.trim().split(/\r?\n/))A.push(`> ${F}`);A.push("")}if(n0(e)&&A.push(ie().staged.noLiveApp(ed(e.newTestsCreated)),""),c&&e.newTestsCreated.length){let F=new Map;for(let O of e.newTestsCreated){if(O.testType!=="unit")continue;let De=YT(O)[0],ve=F.get(O.fileName)??{functions:new Set,endpoints:[],descriptions:new Map};O.endpoint&&!ve.endpoints.includes(O.endpoint)&&ve.endpoints.push(O.endpoint);let J=O.description?.trim()??"",U=ve.descriptions.get(De)??[];U.includes(J)||U.push(J),ve.functions.add(De),ve.descriptions.set(De,U),F.set(O.fileName,ve)}let te=e.newTestsCreated.filter(O=>O.testType!=="unit");h(ie().testRecommendationsImplementedHeader(ed(e.newTestsCreated),te.length+ed(e.newTestsCreated.filter(O=>O.testType==="unit"))));for(let[O,{functions:De,endpoints:ve,descriptions:J}]of F){let U=De.size;A.push(ie().staged.unitTestsInFile(`\`${O}\``,U,ve.map(Zt=>`\`${Zt}\``).join(", ")),"");let Rt=new Map;for(let[Zt,yt]of J){let dn=yt.join("\0"),$t=Rt.get(dn)??{fns:[],descriptions:yt};$t.fns.push(Zt),Rt.set(dn,$t)}let at=0;for(let{fns:Zt,descriptions:yt}of Rt.values()){A.push(`${++at}. ${Zt.map($t=>`\`${$t}\``).join(", ")}`);let dn=[...new Set(yt.flatMap($t=>Bve($t)))];for(let $t of dn)A.push(` - ${$t}`)}A.push("")}for(let O of te){let De=O.testId?un(p(O.testId)):t0(O.testType),ve=O.fileName?` (\`${O.fileName}\`)`:"",J=O.endpoint?`
190
190
  \`${O.endpoint}\``:"",U=O.description?`
191
191
  ${O.description.trim()}`:"";A.push(`- ${De}${ve}${J}${U}`)}g()}let y=(e.testMaintenance??[]).filter(F=>lW.has(F.action));if(c&&y.length){h(ie().staged.testMaintenanceHeader),A.push(ie().maintenanceTableHeader),A.push("|-----------|----------|------|--------|--------|-------|");for(let F of y)A.push(`| ${tt(t0(F.testType))} | ${tt(F.endpoint)} | \`${tt(F.fileName)}\` | ${tt(F.description)} | ${fW(F.beforeStatus,F.beforeDetails)} | ${fW(F.afterStatus,F.afterDetails)} |`);g()}let b=F=>F.startsWith(CA)||F.includes(SA),E=(e.testMaintenance??[]).filter(F=>b(F.afterDetails)&&(!lW.has(F.action)||!mW.has(F.afterStatus??"")));if(c&&E.length){h(ie().staged.declinedMaintenanceHeader);for(let F of E)A.push(`- \`${tt(F.fileName)}\`: ${tt(yW(F.afterDetails))}`);g()}if(c&&r.length){h(ie().staged.existingEvidenceHeader);let F=new Map;for(let te of r){let O=`${te.check}\0${te.url??""}\0${te.revision??""}`;F.set(O,[...F.get(O)??[],te])}for(let[,[te,...O]]of F){let De=te.url?`[${un(te.check)}](${te.url})`:un(te.check);A.push(ie().staged.trustedCheckPassed(De,te.revision?un(te.revision.slice(0,7)):""),"");for(let ve of[te,...O])A.push(`- ${un(ve.behavior)}`);A.push("")}g()}if(c&&e.testResults.length){h(ie().staged.testResultsHeader);let F=kve(e),te=F.some(J=>J.test),O=F.some(J=>i0(e,J)),De=te?ie().staged.unitResultsTableHeader:ie().staged.resultsTableHeader;A.push(O?`${De} ${ie().columnVideo} |`:De),A.push(`${te?"|---------|-----------|----------|------|-------|--------|---------|":"|---------|-----------|----------|--------|---------|"}${O?"-------|":""}`);for(let J of F){let U=J.details.replace(/(\S+\.(?:py|ts|js|spec\.\w+))/gi,"`$1`"),Rt=J.testId?un(tt(p(J.testId))):"\u2014",at=te?` ${J.test?`\`${tt(J.test)}\``:""} | ${J.cases??""} |`:"",Zt=i0(e,J),yt=O?` ${Zt?ie().videoDownloadLink(Zt):"\u2014"} |`:"";A.push(`| ${Rt} | ${tt(t0(J.testType))} | ${tt(J.endpoint)} |${at} ${tt(r0(J.status))} | ${tt(U)} |${yt}`)}let ve=(e.testVideos??[]).find(J=>J.artifactsUrl)?.artifactsUrl;!O&&ve&&A.push("",ie().videosArtifactFallback(ve)),g()}if(e.requirements?.length){let F=e.requirements.flatMap(J=>J.clauses),te=J=>J.status==="Pass"||J.status==="Passed, test not kept",O=F.filter(te).length;h(ie().staged.requirementsHeader(O,F.length));let De=J=>Fa(ie().staged.clauseStatuses,J.status),ve=J=>(J.status==="Not tested"||J.status==="Passed, test not kept")&&J.notTested?`${De(J)}: ${J.notTested}`:J.findings.length?`${De(J)} \u2014 ${J.findings.join(", ")}`:De(J);if(c){A.push(ie().staged.requirementsTableHeader),A.push("|-------------|--------|-------|--------|");for(let J of e.requirements)J.clauses.forEach((U,Rt)=>{let at=Rt===0?`**${tt(J.label)}**${J.statement?` ${tt(J.statement)}`:""}`:"",Zt=`${un(tt(p(U.id)))}${pW(U)}${U.text?` ${tt(U.text)}`:""}`,yt=new Map;for(let jt of U.tests){let Fn=jt.fileName??p(jt.testId),Et=yt.get(Fn)??{fns:new Set};for(let On of jt.functions)Et.fns.add(On);Et.video??=jt.fileName?Sve(e,jt.fileName,jt.repository):void 0,yt.set(Fn,Et)}let dn=yt.size?[...yt].map(([jt,{fns:Fn,video:Et}])=>`${un(tt(jt))}${Fn.size?` \u2014 ${[...Fn].map(On=>`\`${tt(On)}\``).join(", ")}`:""}${Et?` ${ie().videoDownloadLink(Et)}`:""}`).join("<br>"):"\u2014",$t=J.source==="could-break"&&U.status==="Pass"?ie().staged.regressionGuard:"";A.push(`| ${at} | ${Zt} | ${dn} | ${tt(ve(U)+$t)} |`)})}else{A.push(ie().staged.requirementsSummaryTableHeader),A.push("|-------------|-----------------|-------------|");for(let J of e.requirements){let U=J.clauses.filter(te).length,Rt=J.clauses.filter(at=>!te(at)).map(at=>`${un(tt(p(at.id)))}${pW(at)} ${tt(ve(at))}`);A.push(`| **${tt(J.label)}**${J.statement?` ${tt(J.statement)}`:""} | ${U}/${J.clauses.length} | ${Rt.join("<br>")||"\u2014"} |`)}}g()}if(c&&e.changes?.length&&!e.requirements?.length){let F=e.executionCoverage,te=F?ie().staged.coverageCaption(F.generated,F.modified,F.verified,F.executed):"";h(`${ie().staged.behaviourCoverageHeader}${te}`),A.push(ie().staged.coverageTableHeader),A.push("|-----------|--------|-----------|----------------|");for(let O of e.changes){let De=O.testedBy.length?O.testedBy.map(J=>`\`${tt(J)}\``).join(", "):O.writtenBy.length?ie().staged.writtenNotRun:"\u2014",ve=O.maintainedBy.length?O.maintainedBy.map(J=>`\`${tt(J)}\``).join(", "):"\u2014";A.push(`| ${tt(O.text)} | \`${tt(O.source)}\` | ${De} | ${ve} |`)}g()}if(e.userJourneys?.length){let F=e.userJourneys.filter(O=>O.status==="Pass"&&!O.problems.length).length;h(`\u{1F9ED} User Journeys Covered (${F}/${e.userJourneys.length} walked end to end)`);let te=e.userJourneys.some(O=>s0(e,O.fileName));A.push(`| Journey | Test | Status | Notes |${te?` ${ie().columnVideo} |`:""}`),A.push(`|---------|------|--------|-------|${te?"-------|":""}`);for(let O of e.userJourneys){let De=O.fileName?`\`${tt(O.fileName)}\`${O.test?` \u2014 ${tt(O.test)}`:""}`:"\u2014",ve=O.source&&O.source!=="inferred"?`; described in the ${O.source==="spec"?"spec":"PR description"}`:"; inferred from the app",J=(O.uncovered?`not covered: ${O.uncovered}`:O.problems.length?`does not walk it end to end: ${O.problems.join("; ")}`:`from ${O.entry}, ${O.steps} steps`)+ve,U=te?s0(e,O.fileName):void 0;A.push(`| ${tt(O.name)} | ${De} | ${tt(O.status)} | ${tt(J)} |${te?` ${U?ie().videoDownloadLink(U):"\u2014"} |`:""}`)}g()}if(u){let F=e.issuesFound.filter(O=>!AW(O)).sort(hW),te=e.issuesFound.filter(AW).sort(hW);if(F.length){h(ie().staged.issuesFoundHeader);for(let O of F)A.push(gW(O));g()}if(te.length){A.push(`### ${ie().configErrorsHeader}`);for(let O of te)A.push(gW(O));A.push("")}}let v=e.testPackages??[],S=e.dependencyChanges??[];if(v.length){A.push(ie().staged.testPackagesHeader,"");for(let F of v)A.push(`- ${ie().staged.testPackageLine(F.directory,F.entrypoint,Object.entries(F.dependencies??{}).map(([te,O])=>F.runner==="pytest"?`${te}==${O}`:`${te}@${O}`).join(", "))}`);S.length||A.push(`- ${ie().staged.appManifestsUntouched}`),A.push("")}if(S.length){A.push(ie().staged.dependencyChangesHeader,"");for(let F of S)A.push(`- ${ie().staged.dependencyChangeLine(F.package,F.repository?`${F.repository}: ${F.manifest}`:F.manifest,(F.reason??"").replace(/\s+/g," ").trim())}`);A.push("")}let B=(e.caveats??[]).filter(F=>F.kind!=="tests-not-executed"||F.subject==="written-cases"||!n0(e));if(B.length){A.push(ie().staged.caveatsHeader,"");for(let F of B)A.push(`- ${F.text}`);A.push("")}if(u&&e.nextSteps.length){A.push(ie().nextStepsHeader,"");for(let F of e.nextSteps)A.push(`- ${F.trim()}`);A.push("")}let z=A.join(`
192
192
  `).replace(/\n{3,}/g,`
@@ -194,8 +194,8 @@ ${Xl}: ${t}`:i;e(["log","-1","--format=%(trailers:key=Signed-off-by,valueonly)"]
194
194
  `).trim()+`
195
195
  `;if(n!=="testbot-pr"||Buffer.byteLength(z,"utf8")<=64e3)return z;let Z=F=>e.testResults.filter(te=>te.status===F).length,fe=e.requirements?.flatMap(F=>F.clauses)??[],Je=F=>Array.from(F.replace(/\s+/g," ").trim()).slice(0,300).join(""),dt=F=>Je(F).replace(/[&<>\\`*_[\]{}()#+.!|~-]/g,te=>`&#${te.charCodeAt(0)};`);return[uW,...o?[ie().staged.testsSourcePullRequest(un(Je(o)))]:[],ie().staged.largeReportSummary(e.requirements?.length??0,fe.length,Z("Pass"),Z("Fail"),Z("Skipped")),ie().staged.largeReportNotice,...e.validation?[ie().staged.largeReportValidation(dt(e.validation.sufficiency),dt(e.validation.rationale),e.validation.gaps.length)]:[],...(e.caveats??[]).slice(0,3).map(F=>`> \u26A0\uFE0F ${dt(F.text)}`),...n0(e)?[ie().staged.noLiveApp(ed(e.newTestsCreated))]:[],...t.runUrl?[ie().staged.viewRun(t.runUrl)]:[],""].join(`
196
196
 
197
- `)}var jv=ce(require("fs")),kr=ce(require("path"));var DGe=5*1024*1024;function Rve(e){try{return jv.lstatSync(e),!0}catch{return!1}}function IW(e){let t=Ke(e,"adapt.json"),n=Ke(e,"finalize.json"),i=Ke(e,EA),r=new Map,s=d=>{let p=il(e.inputs,d);if("error"in p)return;let A=r.get(p.source.path)??{source:p.source,paths:new Set};return r.set(p.source.path,A),{repo:A.source.path,paths:A.paths}},o=(d,p)=>kr.relative(d,kr.resolve(d,p.trim())).replace(/\/+$/,""),a=(d,p)=>{let A=p?.trim()&&s(d);if(!A)return;let h=o(A.repo,p);A.paths.add(h);for(let g of["__init__.py","conftest.py"]){let y=kr.join(kr.dirname(h),g);jv.existsSync(kr.join(A.repo,y))&&A.paths.add(y)}},c=(d,p)=>{if(typeof p!="string"||!p.trim())return;let A=s(d);if(!A)return;let h=o(A.repo,p);if(sf(kr.join(A.repo,h)))return A.paths.add(h),{...A,rel:h}};for(let d of[...t?.items??[],...i?.tests??[],...i?.maintained??[]])a(d.repository,d.file);for(let d of n?.dependencies?.added??[]){let p=c(d.repository,d.manifest);if(p)for(let A of Ok(p.repo,oy(p.repo,p.rel)))p.paths.add(A)}for(let d of n?.lint??[])for(let p of d.fixed??[])c(d.repository,p);for(let d of n?.support??[])c(d.repository,d.file);let u=Ke(e,cy)?.packages??[];for(let d of new Set(u.map(p=>p.repository))){let p=s(d),A=u.filter(h=>h.repository===d).map(h=>h.dir);if(p)for(let{path:h}of OT(p.repo)){let g=o(p.repo,h),y=kr.join(p.repo,g);uy(g,A)&&!Vk(g)&&(!Rve(y)||sf(y))&&p.paths.add(g)}}return new Map([...r.values()].map(({source:d,paths:p})=>[d,[...p].filter(A=>A&&A!==".."&&!A.startsWith(`..${kr.sep}`)&&!Gm(A))]))}var CW=ce(require("fs"));var SW=2*1024*1024;function xve(e){let t=[];for(let n of e??[])if(n.state==="read")try{t.push({item:n,text:CW.readFileSync(xY(n),"utf-8")})}catch{}return t}var kA=6,Qve=/[\p{L}\p{N}]+/gu,$ve=new RegExp("(?<=\\p{Ll})(?=\\p{Lu})|(?<=\\p{Lu})(?=\\p{Lu}\\p{Ll})","u");function o0(e){let t=[];for(let n of e.matchAll(Qve)){let i=n.index;for(let r of n[0].split($ve))t.push({word:r.toLowerCase(),start:i,end:i+r.length}),i+=r.length}return t}var kW=(e,t)=>e.slice(t,t+kA).map(n=>n.word).join(" ");function wW(e){let t=o0(e),n=new Set;for(let i=0;i+kA<=t.length;i++)n.add(kW(t,i));return n}function BW(e,t=[]){let n=new Set(t.flatMap(i=>[...wW(i)]));return xve(e).map(({item:i,text:r})=>{let s=i.source==="other"?r:r.slice(r.indexOf(`
198
- `)+1||r.length),o=wW(s);for(let a of n)o.delete(a);return{name:xj(i.key,jT([i])),key:i.key,runs:o,words:o0(s).map(a=>a.word)}})}var HGe=kA/2;var Tve=e=>e.criteria.size?`${e.text.name} ${[...e.criteria].sort((t,n)=>t-n).map(t=>`AC${t}`).join(", ")}`:e.text.name;function _ve(e,t){if(t.length===0)return[];let n=o0(e),i=[];for(let r=0;r+kA<=n.length;r++){let s=kW(n,r),o=t.find(p=>p.runs.has(s));if(!o)continue;let a=n[r].start,c=n[r+kA-1].end,u=o.criteria?.get(s)??[],d=i.at(-1);if(d&&a<=d.end){if(d.end=Math.max(d.end,c),d.text===o)for(let p of u)d.criteria.add(p)}else i.push({start:a,end:c,text:o,criteria:new Set(u)})}return i.map(r=>({start:r.start,end:r.end,name:Tve(r)}))}function Vv(e,t){let n=e;for(let i of _ve(e,t).reverse())n=`${n.slice(0,i.start)}(see ${i.name})${n.slice(i.end)}`;return n}function Dve(e,t,n){for(let i=t+1;i<e.length;i++){let r=e[i];if(r==="\\")i++;else{if(r===n)return i+1;if(r===`
197
+ `)}var jv=ce(require("fs")),kr=ce(require("path"));var NGe=5*1024*1024;function Rve(e){try{return jv.lstatSync(e),!0}catch{return!1}}function IW(e){let t=Ke(e,"adapt.json"),n=Ke(e,"finalize.json"),i=Ke(e,EA),r=new Map,s=d=>{let p=il(e.inputs,d);if("error"in p)return;let A=r.get(p.source.path)??{source:p.source,paths:new Set};return r.set(p.source.path,A),{repo:A.source.path,paths:A.paths}},o=(d,p)=>kr.relative(d,kr.resolve(d,p.trim())).replace(/\/+$/,""),a=(d,p)=>{let A=p?.trim()&&s(d);if(!A)return;let h=o(A.repo,p);A.paths.add(h);for(let g of["__init__.py","conftest.py"]){let y=kr.join(kr.dirname(h),g);jv.existsSync(kr.join(A.repo,y))&&A.paths.add(y)}},c=(d,p)=>{if(typeof p!="string"||!p.trim())return;let A=s(d);if(!A)return;let h=o(A.repo,p);if(sf(kr.join(A.repo,h)))return A.paths.add(h),{...A,rel:h}};for(let d of[...t?.items??[],...i?.tests??[],...i?.maintained??[]])a(d.repository,d.file);for(let d of n?.dependencies?.added??[]){let p=c(d.repository,d.manifest);if(p)for(let A of Ok(p.repo,oy(p.repo,p.rel)))p.paths.add(A)}for(let d of n?.lint??[])for(let p of d.fixed??[])c(d.repository,p);for(let d of n?.support??[])c(d.repository,d.file);let u=Ke(e,cy)?.packages??[];for(let d of new Set(u.map(p=>p.repository))){let p=s(d),A=u.filter(h=>h.repository===d).map(h=>h.dir);if(p)for(let{path:h}of OT(p.repo)){let g=o(p.repo,h),y=kr.join(p.repo,g);uy(g,A)&&!Vk(g)&&(!Rve(y)||sf(y))&&p.paths.add(g)}}return new Map([...r.values()].map(({source:d,paths:p})=>[d,[...p].filter(A=>A&&A!==".."&&!A.startsWith(`..${kr.sep}`)&&!Gm(A))]))}var CW=ce(require("fs"));var SW=2*1024*1024;function xve(e){let t=[];for(let n of e??[])if(n.state==="read")try{t.push({item:n,text:CW.readFileSync(xY(n),"utf-8")})}catch{}return t}var kA=6,Qve=/[\p{L}\p{N}]+/gu,$ve=new RegExp("(?<=\\p{Ll})(?=\\p{Lu})|(?<=\\p{Lu})(?=\\p{Lu}\\p{Ll})","u");function o0(e){let t=[];for(let n of e.matchAll(Qve)){let i=n.index;for(let r of n[0].split($ve))t.push({word:r.toLowerCase(),start:i,end:i+r.length}),i+=r.length}return t}var kW=(e,t)=>e.slice(t,t+kA).map(n=>n.word).join(" ");function wW(e){let t=o0(e),n=new Set;for(let i=0;i+kA<=t.length;i++)n.add(kW(t,i));return n}function BW(e,t=[]){let n=new Set(t.flatMap(i=>[...wW(i)]));return xve(e).map(({item:i,text:r})=>{let s=i.source==="other"?r:r.slice(r.indexOf(`
198
+ `)+1||r.length),o=wW(s);for(let a of n)o.delete(a);return{name:xj(i.key,jT([i])),key:i.key,runs:o,words:o0(s).map(a=>a.word)}})}var YGe=kA/2;var Tve=e=>e.criteria.size?`${e.text.name} ${[...e.criteria].sort((t,n)=>t-n).map(t=>`AC${t}`).join(", ")}`:e.text.name;function _ve(e,t){if(t.length===0)return[];let n=o0(e),i=[];for(let r=0;r+kA<=n.length;r++){let s=kW(n,r),o=t.find(p=>p.runs.has(s));if(!o)continue;let a=n[r].start,c=n[r+kA-1].end,u=o.criteria?.get(s)??[],d=i.at(-1);if(d&&a<=d.end){if(d.end=Math.max(d.end,c),d.text===o)for(let p of u)d.criteria.add(p)}else i.push({start:a,end:c,text:o,criteria:new Set(u)})}return i.map(r=>({start:r.start,end:r.end,name:Tve(r)}))}function Vv(e,t){let n=e;for(let i of _ve(e,t).reverse())n=`${n.slice(0,i.start)}(see ${i.name})${n.slice(i.end)}`;return n}function Dve(e,t,n){for(let i=t+1;i<e.length;i++){let r=e[i];if(r==="\\")i++;else{if(r===n)return i+1;if(r===`
199
199
  `&&n!=="`")return i}}return e.length}function Nve(e,t){let n=e.lastIndexOf(`
200
200
  `,t-1)+1;if(e.slice(n,t).trim()!=="")return!1;let i=e.slice(0,n).trimEnd();return i===""||i.endsWith(":")}function Pve(e){let t=[],n=r=>(e.indexOf(`
201
201
  `,r)+1||e.length+1)-1,i=0;for(;i<e.length;){let r=e[i],s=e[i+1],o=i+1;if(r==="/"&&s==="*")o=e.indexOf("*/",i+2)<0?e.length:e.indexOf("*/",i+2)+2,t.push({start:i,end:o});else if(r==="/"&&s==="/"&&!/[:\w]/.test(e[i-1]??"")||r==="#"&&/^\s?$/.test(e[i-1]??"")&&!/[!{[]/.test(s??""))o=n(i),t.push({start:i,end:o});else if((r==='"'||r==="'")&&e.startsWith(r.repeat(3),i)){let a=e.indexOf(r.repeat(3),i+3);o=a<0?e.length:a+3,Nve(e,i)&&t.push({start:i,end:o})}else(r==='"'||r==="'"||r==="`")&&(o=Dve(e,i,r));i=o}return t}var Uve=/\b(?:test|it|describe|context|suite|scenario|specify|Run|DisplayName)(?:\.\w+)*(?:\.each\s*(?:\((?:[^()]|\([^()]*\))*\)|`[^`]*`))?\s*\(\s*("(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`)/g;function Fve(e,t){return[...e.matchAll(Uve)].flatMap(n=>{if(t.some(r=>n.index>=r.start&&n.index<r.end))return[];let i=n.index+n[0].length;return[{start:i-n[1].length,end:i}]})}function RW(e,t){if(t.length===0)return{content:e,cleaned:!1};let n=Pve(e),i=[];for(let a of n){let c=e.slice(a.start,a.end),u=Vv(c,t);u!==c&&i.push({...a,text:u})}let r=Fve(e,n),s=new Set(r.map(a=>e.slice(a.start+1,a.end-1)));for(let a of r){let c=e[a.start],u=e.slice(a.start+1,a.end-1),d=Vv(u,t);if(d===u)continue;let p=d;for(let A=2;s.has(p);A++)p=`${d} (${A})`;s.add(p),i.push({...a,text:`${c}${p}${c}`})}let o=e;for(let a of i.sort((c,u)=>u.start-c.start))o=`${o.slice(0,a.start)}${a.text}${o.slice(a.end)}`;return{content:o,cleaned:o!==e}}function Ove(e){if(!e.inputs.deliver)return{ok:!1,reasons:["deliver not requested (pass --deliver to push)"]};if(!e.platform?.supportsRemote)return{ok:!1,reasons:["deliver needs a remote platform driver (pass --runner-platform github)"]};let t=Ke(e,"finalize.json");return t?t.ready!==!0?{ok:!1,reasons:[`finalize reported ready:false \u2014 not pushing (blockers: ${fA(t)||"unspecified"})`]}:{ok:!0,reasons:[]}:{ok:!1,reasons:["finalize.json not found \u2014 refusing to push unverified tests"]}}function TW(e){return e.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"tests"}var Mve="skyramp-testbot/";function Lve(e,t){return t||`${Mve}${TW(e)}-tests`}function jve(e,t,n,i){let r=(e??[]).filter(o=>o.repository.toLowerCase()===t.toLowerCase());if(!r.length&&i){let o=i.repository,a=[i.targetId,o.provider,o.providerAccountId,o.providerRepositoryId,i.number,t.toLowerCase(),n];return(0,BA.createHash)("sha256").update(JSON.stringify(a)).digest("hex").slice(0,32)}let s=r.length?[...new Set(r.map(o=>`${o.repository.toLowerCase()}#${o.number}`))].sort():[`branch ${n}`];return(0,BA.createHash)("sha256").update(s.join(`
@@ -207,18 +207,18 @@ ${Xl}: ${t}`:i;e(["log","-1","--format=%(trailers:key=Signed-off-by,valueonly)"]
207
207
  ${n}`}:{prFailure:"unknown",prDetail:t}}async function Xve(e,t,n,i,r,s){let o=i.slug,a=i.path,c=Ke(e,"finalize.json"),u=BW(e.inputs.requirementItems),d=qY(a),p=Ke(e,"write.json"),A=p?.commit?.message||Ke(e,"generate-unit.json")?.commitMessage,h=i.working,g=xt=>xt.split(`
208
208
  `)[0],y=xt=>Vv(ZY(qT(xt)),u),b=(xt,pn)=>h&&!!pn&&y(xt).trim()===y(pn).trim(),E=(xt,pn,Br)=>{let ht=y(xt);return Br&&YY(ht,pn)?ht:WY(ht,pn,r)},v=[c?.commit?.message,n.commitMessage].find(xt=>xt&&y(xt).trim())||"Skyramp Testbot: add tests",S=E(v,{commitlint:d.commitlint},b(v,A)),B=sW(e.outputsDir)??n,z=h?c?.pr?.title||n.prTitle||p?.commit?.prTitle:void 0,Z=z||v,fe=h?B.prTitle:void 0,Je=g(y(Z))===g(y(v)),dt=(!h||!n.prTitle)&&Je?B.commitMessage:void 0,F=fe||dt||Z,te=p?.commit?.prTitle||(A?g(A):void 0),O=b(Z,te),De=d.prTitle?{prTitle:d.prTitle}:O&&z&&!Je?{}:{commitlint:d.commitlint},ve=g(E(F,De,O)),J={name:Es,email:mo},U=!!d.signOff;if(!U&&t?.listCommitChecks){let xt=s?.headSha??ln(a,["rev-parse","HEAD"]);try{U=(await t.listCommitChecks({repository:o,revision:xt}))?.records.some(Br=>Br.name.trim().toLowerCase()==="dco"&&Br.headSha===xt&&(!Br.repository||Br.repository.toLowerCase()===o.toLowerCase()))??!1}catch{console.warn(`[deliver] could not read commit checks for ${o}`)}}let Rt=e.inputs.deliverRemote||"origin",at=xW(a,_W),Zt=xW(a,DW);if(at&&!Zt)throw new Error(`${o}: the checkout records a merged base but not what it merged`);let yt=at?a0(void 0,void 0,a):s?s.headBranch||a0(e.inputs.headBranch,e.inputs.baseBranch,a):a0(void 0,void 0,a),dn=e.inputs.pullRequests;s?.prNumber!=null&&!dn?.some(xt=>xt.repository.toLowerCase()===o.toLowerCase())&&(dn=[...dn??[],{repository:o,number:String(s.prNumber)}]);let $t=dn?.some(xt=>xt.repository.toLowerCase()===o.toLowerCase())?void 0:e.inputs.deliveryOrigin,jt=at||!$t?Zt:void 0,Fn=e.inputs.scheduledDelivery,Et=Fn?(0,BA.createHash)("sha256").update(JSON.stringify([Fn,o.toLowerCase(),yt])).digest("hex"):jt?Vve(o,yt,jt):jve(dn,o,yt,$t),On=Lve(yt,e.inputs.deliverBranch)+(Fn?`-scheduled-${Et}`:jt?`-merge-${Et}`:$t?`-source-${$t.number}-${Et}`:"");return{texts:u,shown:B,title:ve,unsigned:S,bot:J,signOff:U,remote:Rt,base:yt,owner:Et,testsBranch:On,origin:$t,mergedBase:at}}function ebe(e,t,n,i){let r=ln(e,["interpret-trailers","--trailer",`${Pv}: ${t.owner}`,"--trailer",`${Xl}: ${n}`,"--trailer",`${JT}: ${i}`],`${t.unsigned}
209
209
  `);return t.signOff?Nv(r,t.bot):r}async function tbe(e,t,n,i,r,s){let o=aW(i.path,e.runDir),a=process.env.PATH;o.dir&&(process.env.PATH=cW(o).PATH);try{return await nbe(e,t,n,i,r,s)}finally{o.dir&&(process.env.PATH=a),o.cleanup()}}async function nbe(e,t,n,i,r,s){let o=i.slug,a,c=!1,u;try{let d=i.path,p=await Xve(e,t,n,i,r,s),{texts:A,shown:h,title:g,bot:y,remote:b,base:E,owner:v,testsBranch:S,origin:B,mergedBase:z}=p,Z=qT(TY(bW(zve(h,e,i),{audience:"testbot-pr",runUrl:e.inputs.skyrampRunUrl??t.runUrl,requestedBy:e.inputs.requestedBy,sourcePullRequest:B&&`${B.repository.namespace}/${B.repository.name}#${B.number}`}),e.inputs.skyrampRunUrl))+`
210
- `,fe=s?"pr-body.md":`pr-body-${TW(o)}.md`,Je=Vo.join(e.outputsDir,fe);pi.writeFileSync(Je,Z);let dt=ln(d,["rev-parse","HEAD"]),F=z??dt;ln(d,["checkout","-B",S]),a=S,ln(d,["reset"]);for(let U of r)Gve(Vo.join(d,U),A);let te=[];for(let U of r)try{ln(d,["--literal-pathspecs","add","--",U])}catch{te.push(U)}try{ln(d,["diff","--cached","--quiet"])}catch{try{let U=ebe(d,p,dt,F);ln(d,["-c",`user.name=${y.name}`,"-c",`user.email=${y.email}`,"commit","-m",U])}catch(U){throw new Gv(U)}c=!0}u=ln(d,["rev-parse","HEAD"]);let O,De=z??s?.headSha;if(c&&De&&De!==dt){let U=!1;try{ln(d,["checkout","-q","-B",a,De]),U=!0,ln(d,["-c",`user.name=${y.name}`,"-c",`user.email=${y.email}`,"cherry-pick","--keep-redundant-commits",u]),U=!1,HT(Rt=>ln(d,Rt),De),u=ln(d,["rev-parse","HEAD"])}catch(Rt){try{ln(d,["cherry-pick","--abort"])}catch{}ln(d,["checkout","-q","-B",a,u]);let at=bA(Lo(Rt),1/0);if(z&&!U)throw Rt;if(z)return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:b,base:E,committed:c,commitSha:u,pushed:!1,prAction:"skipped",prTitle:g,unstaged:te,reason:`the tests do not apply to ${E} at ${z.slice(0,12)} without the merged revisions (${at}), so no tests PR was opened`}};O=`tests committed on the checkout's merge commit (re-cut onto ${De.slice(0,12)} failed: ${at})`}}let ve=s?{}:{repositoryPath:d,repoSlug:o,devPr:null};if(!c){let U=await t.markTestsPrUnchanged({branch:a,...ve});return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:b,base:E,committed:!1,commitSha:u,pushed:!1,prAction:U.action==="unchanged"?"unchanged":"skipped",prUrl:U.url,prTitle:g,unstaged:te,reason:U.action==="unchanged"?"no test changes to commit \u2014 existing tests PR annotated as unchanged":"no test changes to commit \u2014 nothing pushed, no PR opened"}}}let J=await t.publishTestsPr({repositoryPath:d,...ve,remote:b,branch:a,base:E,commitSha:u,title:g,bodyFile:Je,mode:e.inputs.deliverMode,deliveryOwner:v,...e.inputs.firstQualification?{firstQualification:!0}:{},runUrl:e.inputs.skyrampRunUrl,signal:e.signal,deadlineMs:e.deadlineMs});return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:b,base:J.base,requestedBase:E,committed:c,commitSha:u,pushed:J.pushed,...J.pushedCommits?{pushedCommits:J.pushedCommits}:{},...J.deliveredCommit?{deliveredCommit:J.deliveredCommit}:{},prAction:J.action,...J.retargetedAs?{retargetedAs:J.retargetedAs}:{},prUrl:J.url,prTitle:g,...J.failure?{prFailure:J.failure,prDetail:J.detail}:{},...O?{cutNote:O}:{},...J.action==="skipped"&&J.detail?{reason:J.detail}:{},unstaged:te}}}catch(d){return{thrown:!0,record:{schemaVersion:1,repository:o,branch:a,committed:c,commitSha:u,pushed:!1,prAction:"failed",...Kve(d),unstaged:[]}}}}var Aze={name:"deliver",timeoutMinutes:5,execute:Hve,validateInput:e=>{let t=GT(e);return t?{ok:!1,reasons:[t]}:Ove(e)},requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var NW=ce(require("fs")),RA="SKYRAMP_AZURE_SUPERVISED",c0=3;function zv(e){return e.replace(/##(?=(?:vso)?\[)/gi,"#\u200B#")}function u0(e,t=process.env){t[RA]==="1"?NW.writeSync(c0,`${JSON.stringify(e)}
210
+ `,fe=s?"pr-body.md":`pr-body-${TW(o)}.md`,Je=Vo.join(e.outputsDir,fe);pi.writeFileSync(Je,Z);let dt=ln(d,["rev-parse","HEAD"]),F=z??dt;ln(d,["checkout","-B",S]),a=S,ln(d,["reset"]);for(let U of r)Gve(Vo.join(d,U),A);let te=[];for(let U of r)try{ln(d,["--literal-pathspecs","add","--",U])}catch{te.push(U)}try{ln(d,["diff","--cached","--quiet"])}catch{try{let U=ebe(d,p,dt,F);ln(d,["-c",`user.name=${y.name}`,"-c",`user.email=${y.email}`,"commit","-m",U])}catch(U){throw new Gv(U)}c=!0}u=ln(d,["rev-parse","HEAD"]);let O,De=z??s?.headSha;if(c&&De&&De!==dt){let U=!1;try{ln(d,["checkout","-q","-B",a,De]),U=!0,ln(d,["-c",`user.name=${y.name}`,"-c",`user.email=${y.email}`,"cherry-pick","--keep-redundant-commits",u]),U=!1,HT(Rt=>ln(d,Rt),De),u=ln(d,["rev-parse","HEAD"])}catch(Rt){try{ln(d,["cherry-pick","--abort"])}catch{}ln(d,["checkout","-q","-B",a,u]);let at=bA(Lo(Rt),1/0);if(z&&!U)throw Rt;if(z)return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:b,base:E,committed:c,commitSha:u,pushed:!1,prAction:"skipped",prTitle:g,unstaged:te,reason:`the tests do not apply to ${E} at ${z.slice(0,12)} without the merged revisions (${at}), so no tests PR was opened`}};O=`tests committed on the checkout's merge commit (re-cut onto ${De.slice(0,12)} failed: ${at})`}}let ve=s?{}:{repositoryPath:d,repoSlug:o,devPr:null};if(!c){let U=await t.markTestsPrUnchanged({branch:a,...ve});return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:b,base:E,committed:!1,commitSha:u,pushed:!1,prAction:U.action==="unchanged"?"unchanged":"skipped",prUrl:U.url,prTitle:g,unstaged:te,reason:U.action==="unchanged"?"no test changes to commit \u2014 existing tests PR annotated as unchanged":"no test changes to commit \u2014 nothing pushed, no PR opened"}}}let J=await t.publishTestsPr({repositoryPath:d,...ve,remote:b,branch:a,base:E,commitSha:u,title:g,bodyFile:Je,mode:e.inputs.deliverMode,deliveryOwner:v,...e.inputs.firstQualification?{firstQualification:!0}:{},runUrl:e.inputs.skyrampRunUrl,signal:e.signal,deadlineMs:e.deadlineMs});return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:b,base:J.base,requestedBase:E,committed:c,commitSha:u,pushed:J.pushed,...J.pushedCommits?{pushedCommits:J.pushedCommits}:{},...J.deliveredCommit?{deliveredCommit:J.deliveredCommit}:{},prAction:J.action,...J.retargetedAs?{retargetedAs:J.retargetedAs}:{},prUrl:J.url,prTitle:g,...J.failure?{prFailure:J.failure,prDetail:J.detail}:{},...O?{cutNote:O}:{},...J.action==="skipped"&&J.detail?{reason:J.detail}:{},unstaged:te}}}catch(d){return{thrown:!0,record:{schemaVersion:1,repository:o,branch:a,committed:c,commitSha:u,pushed:!1,prAction:"failed",...Kve(d),unstaged:[]}}}}var hze={name:"deliver",timeoutMinutes:5,execute:Hve,validateInput:e=>{let t=GT(e);return t?{ok:!1,reasons:[t]}:Ove(e)},requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var NW=ce(require("fs")),RA="SKYRAMP_AZURE_SUPERVISED",c0=3;function zv(e){return e.replace(/##(?=(?:vso)?\[)/gi,"#\u200B#")}function u0(e,t=process.env){t[RA]==="1"?NW.writeSync(c0,`${JSON.stringify(e)}
211
211
  `):process.stdout.write(e.command!==void 0?`${e.command}
212
212
  `:e.text??"")}function l0(e){u0({command:e})}function PW(e){return e.replace(/%/g,"%AZP25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function rbe(e){return PW(e).replace(/;/g,"%3B").replace(/]/g,"%5D")}function qv(e,t,n){let i=Object.entries(t).map(([r,s])=>`${r}=${rbe(s)}`).join(";");return`##vso[${e}${i?` ${i}`:""}]${PW(n)}`}function UW(e){if(!e)return[];let t=e.split(/\r?\n/).filter(n=>n.trim()&&n!==e);return[e,...t].map(n=>qv("task.setsecret",{},n))}function FW(e,t=l0){for(let n of UW(e))t(n)}function ibe(e){return e.replace(/%0D/g,"\r").replace(/%0A/g,`
213
213
  `).replace(/%25/g,"%")}function OW(e){let t=/^::([a-z-]+)(?: [^:]*)?::(.*)$/s.exec(e.replace(/\r?\n$/,""));if(!t)return;let[,n,i]=t,r=ibe(i),s=zv(r);switch(n){case"add-mask":return UW(r);case"warning":case"error":return[qv("task.logissue",{type:n},s)];case"notice":return[s];case"debug":return s.split(`
214
214
  `).map(o=>`##[debug]${o}`);case"group":return[`##[group]${s.split(`
215
- `)[0]}`];case"endgroup":return["##[endgroup]"];default:return[]}}function QA(e){return e.replace(/\/+$/,"")}function d0(e){let t=new URL(e),n=t.pathname.split("/").filter(Boolean);if(n.length)return decodeURIComponent(n[n.length-1]);if(t.hostname.endsWith(".visualstudio.com"))return t.hostname.split(".")[0];throw new Error(`SYSTEM_COLLECTIONURI "${e}" names no organization`)}var sbe=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,48}[A-Za-z0-9])?$/,obe=/[\\/:*?"<>|;#${},+=[\]%\p{Cc}\p{Cf}]/u;function MW(e){return e.length>0&&e.length<=64&&e===e.trim()&&!obe.test(e)&&!/[^\S ]/u.test(e)&&!/^[._]/.test(e)&&!e.endsWith(".")}function Jv(e){return p0(`${e.namespace}/${e.name}`)}function p0(e){let t=e.indexOf("/"),n=e.lastIndexOf("/"),i=e.slice(0,t),r=e.slice(t+1,n),s=e.slice(n+1);if(t<0||t===n||!sbe.test(i)||!MW(r)||!MW(s))throw new Error(`"${e}" is not an Azure DevOps organization/project/repository`);return{organization:i,project:r,name:s}}function LW(e,t){let n=d0(e);if(n.toLowerCase()!==t.organization.toLowerCase())throw new Error(`${t.organization}/${t.project}/${t.name} is not in ${n}, the Azure DevOps organization this job runs in`)}function jW(e,t){return LW(e,t),`${QA(e)}/${encodeURIComponent(t.project)}/_git/${encodeURIComponent(t.name)}`}function f0(e,t){return LW(e,t),`${QA(e)}/${encodeURIComponent(t.project)}/_apis/git/repositories/${encodeURIComponent(t.name)}`}var abe="7.1",xA=class extends Error{constructor(n,i){super(n);this.status=i}status};async function A0(e){let t=e.accept??"application/json",n=new URL(e.url);n.searchParams.has("api-version")||n.searchParams.set("api-version",abe);let i=await(e.fetch??fetch)(n.toString(),{method:e.method??"GET",headers:{Authorization:`Bearer ${e.token}`,Accept:t,...e.body!==void 0?{"Content-Type":"application/json"}:{}},...e.body!==void 0?{body:JSON.stringify(e.body)}:{},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!i.ok){let r=(await i.json().catch(()=>({}))).message;throw new xA(`Azure DevOps answered ${i.status}${typeof r=="string"?`: ${r}`:""}`,i.status)}return t!=="application/json"?Buffer.from(await i.arrayBuffer()):i.status===204?{}:await i.json()}function cbe(e){return`AUTHORIZATION: bearer ${e}`}function VW(e,t){return{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${QA(e)}/.extraheader`,GIT_CONFIG_VALUE_0:cbe(t)}}var ube="7.1-preview.1",lbe=".azure-pipelines/skyramp-testbot-v3.yml";function _c(e){return e.GITHUB_ACTIONS!=="true"&&/^true$/i.test(e.TF_BUILD??"")}var dbe={INPUT_SKYRAMPRUNID:"SKYRAMP_RUN_ID",INPUT_SKYRAMPAPPORIGIN:"SKYRAMP_APP_ORIGIN",INPUT_SKYRAMPMCPGITHUBTOKEN:"SKYRAMP_MCP_GITHUB_TOKEN",INPUT_UICREDENTIALS:"SKYRAMP_UI_LOGINS"};function qW(e=process.env){if(_c(e))for(let[t,n]of Object.entries(dbe))!e[t]&&e[n]!==void 0&&(e[t]=e[n])}function JW(e,t={}){let n=p=>{let A=e[p];if(!A)throw new Error(`${p} is not set; the V3 runner handshake needs it`);return A},i=QA(e.SYSTEM_COLLECTIONURI??""),r=()=>d0(n("SYSTEM_COLLECTIONURI")),s=e.SYSTEM_TEAMPROJECT,o=e.BUILD_REPOSITORY_NAME,a=e.BUILD_REPOSITORY_ID?.toLowerCase(),c=e.SYSTEM_ACCESSTOKEN,u=t.mask??(p=>FW(p)),d=p=>async()=>{if(!p)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_OIDCREQUESTURI to $(System.OidcRequestUri).");if(!c)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_ACCESSTOKEN to $(System.AccessToken).");let A=new URL(p);if(A.protocol!=="https:")throw new Error("SYSTEM_OIDCREQUESTURI is not an https URL");A.searchParams.set("api-version",ube);let h=await(t.fetch??fetch)(A.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json",Accept:"application/json"},body:"{}",redirect:"error",signal:AbortSignal.timeout(3e4)});if(!h.ok)throw new Error(`Azure DevOps refused the OIDC token request: ${h.status}`);let g=(await h.json().catch(()=>({}))).oidcToken;if(typeof g!="string"||!g)throw new Error("Azure DevOps's OIDC token response carried no token");return u(g),g};return{runnerPlatform:_c(e)?"azure":void 0,workspace:e.BUILD_SOURCESDIRECTORY||void 0,serverUrl:i,apiUrl:i,repository:a&&s&&o&&i?{id:a,slug:`${r()}/${s}/${o}`}:void 0,runId:e.BUILD_BUILDID||void 0,runAttempt:e.SYSTEM_STAGEATTEMPT||void 0,job:e.SYSTEM_JOBNAME||void 0,execution(){let p=n("SYSTEM_STAGEATTEMPT");if(!/^[1-9][0-9]*$/.test(p))throw new Error(`SYSTEM_STAGEATTEMPT is "${p}", not a positive whole number`);let A=n("SYSTEM_COLLECTIONID").toLowerCase();if(!Xu.test(A))throw new Error(`SYSTEM_COLLECTIONID is "${A}", not a GUID`);let h=n("BUILD_REPOSITORY_ID").toLowerCase();if(!Xu.test(h))throw new Error(`BUILD_REPOSITORY_ID is "${h}", not a GUID`);let g=[r(),n("SYSTEM_TEAMPROJECT"),n("SYSTEM_DEFINITIONID"),n("BUILD_BUILDID")].map(encodeURIComponent).join("/");return{provider:"azure-devops",repository:{provider:"azure-devops",providerAccountId:A,providerRepositoryId:h},providerRunId:g,providerRunAttempt:Number(p),workflowRef:`${lbe}@${n("BUILD_SOURCEBRANCH")}`}},takeIdToken(){let p=e.SYSTEM_OIDCREQUESTURI;delete e.SYSTEM_OIDCREQUESTURI;let A=d(p);return()=>A()},takeSourceToken(){return delete e.SYSTEM_ACCESSTOKEN,c||void 0},webIdentity(){if(!e.SYSTEM_OIDCREQUESTURI?.trim()||!c)return;let p=d(e.SYSTEM_OIDCREQUESTURI);return{token:()=>p(),runId:e.BUILD_BUILDID}},v3RunsOnly:!0,assumesBedrockRole:!0,namesSourceToMcp:!0,runSettingsFromApp:!0,checkSourceName(p){Jv(p)},cloneUrl(p){return jW(i,Jv(p))},gitAuthEnv(p){return VW(i,p)},async pullRequest(p,A,h){let g=await A0({token:await h.token(),url:`${f0(i,Jv(p))}/pullrequests/${A}`,fetch:h.fetch}),y=g.status==="completed";return{...typeof g.title=="string"?{title:g.title}:{},...typeof g.description=="string"?{body:g.description}:{},...typeof g.status=="string"?{merged:y}:{},...y&&typeof g.lastMergeCommit?.commitId=="string"?{mergeCommit:g.lastMergeCommit.commitId}:{},...y&&typeof g.lastMergeSourceCommit?.commitId=="string"?{mergedHead:g.lastMergeSourceCommit.commitId}:{}}},async commit(p,A,h){let g;try{g=f0(i,p0(p))}catch{return{lookup:"unknown"}}try{let y=await A0({token:await h.token(),url:`${g}/commits/${encodeURIComponent(A)}`,fetch:h.fetch});return typeof y.commitId=="string"?{sha:y.commitId}:{lookup:"missing"}}catch(y){return{lookup:y instanceof xA&&(y.status===404||y.status===400)?"missing":"unknown"}}}}}xn();var pbe=5e3,h0=/^(?!\.\.?$)[A-Za-z0-9._-]{1,100}$/;function fbe(e){let t=Buffer.from(`x-access-token:${e}`).toString("base64");return us(t),`AUTHORIZATION: basic ${t}`}function HW(e,t={}){let n=c=>{let u=e[c];if(!u)throw new Error(`${c} is not set; the V3 runner handshake needs it`);return u},i=e.GITHUB_REPOSITORY_ID,r=e.GITHUB_REPOSITORY,s=(e.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,""),o=(e.GITHUB_API_URL||"https://api.github.com").replace(/\/+$/,""),a=async(c,u)=>u.fetch(c,{headers:{Authorization:`Bearer ${await u.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:s,apiUrl:o,repository:i&&r?{id:i,slug:r}:void 0,runId:e.GITHUB_RUN_ID||void 0,runAttempt:e.GITHUB_RUN_ATTEMPT||void 0,job:e.GITHUB_JOB||void 0,execution(){let c=n("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:n("GITHUB_REPOSITORY_OWNER_ID"),providerRepositoryId:n("GITHUB_REPOSITORY_ID")},providerRunId:n("GITHUB_RUN_ID"),providerRunAttempt:Number(c),workflowRef:n("GITHUB_WORKFLOW_REF")}},takeIdToken(){let c=e.ACTIONS_ID_TOKEN_REQUEST_URL,u=e.ACTIONS_ID_TOKEN_REQUEST_TOKEN;return delete e.ACTIONS_ID_TOKEN_REQUEST_URL,delete e.ACTIONS_ID_TOKEN_REQUEST_TOKEN,async d=>{if(!c||!u)throw new Error("The job cannot request an OIDC token. Give it the `id-token: write` permission.");let p=new URL(c);p.searchParams.set("audience",d);let A=await fetch(p,{headers:{Authorization:`Bearer ${u}`,Accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!A.ok)throw new Error(`GitHub refused the OIDC token request: ${A.status}`);let h=(await A.json().catch(()=>({}))).value;if(typeof h!="string"||!h)throw new Error("GitHub's OIDC token response carried no token");return us(h),h}},webIdentity(){return!e.ACTIONS_ID_TOKEN_REQUEST_TOKEN?.trim()||!e.ACTIONS_ID_TOKEN_REQUEST_URL?.trim()?void 0:{token:t.getIDToken??(u=>_L(u)),runId:e.GITHUB_RUN_ID}},v3RunsOnly:!1,assumesBedrockRole:!1,namesSourceToMcp:!1,runSettingsFromApp:!1,checkSourceName(c){for(let u of[c.namespace,c.name])if(!h0.test(u))throw new Error(`"${u}" is not a repository name`)},cloneUrl(c){return`${s}/${c.namespace}/${c.name}.git`},gitAuthEnv(c){return c?{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${s}/.extraheader`,GIT_CONFIG_VALUE_0:fbe(c)}:{}},async pullRequest({namespace:c,name:u},d,p){if(![c,u].every(g=>h0.test(g)))throw new Error("the repository name is not valid");let A=await a(`${o}/repos/${c}/${u}/pulls/${d}`,p);if(!A.ok)throw new Error(`GitHub answered ${A.status}`);let h=await A.json();return{...typeof h.title=="string"?{title:h.title}:{},...typeof h.body=="string"?{body:h.body}:{},...typeof h.merged=="boolean"?{merged:h.merged}:{},...h.merged===!0&&typeof h.merge_commit_sha=="string"?{mergeCommit:h.merge_commit_sha}:{},...h.merged===!0&&typeof h.head?.sha=="string"?{mergedHead:h.head.sha}:{}}},async commit(c,u,d){let[p,A,...h]=c.split("/");if(h.length||![p,A].every(g=>g!==void 0&&h0.test(g)))return{lookup:"unknown"};try{let g=await a(`${o}/repos/${p}/${A}/commits/${encodeURIComponent(u)}`,d);if(g.status===404||g.status===422)return{lookup:"missing"};if(!g.ok)return{lookup:"unknown"};let y=await g.json();return typeof y.sha=="string"?{sha:y.sha}:{lookup:"missing"}}catch{return{lookup:"unknown"}}},async revokeToken(c,u){let d=await u(`${o}/installation/token`,{method:"DELETE",headers:{Authorization:`Bearer ${c}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(pbe)});if(!d.ok&&d.status!==401)throw new Error(`GitHub answered ${d.status}`)}}}function $A(e=process.env){return _c(e)?JW(e):HW(e)}var w2e=10*6e4;var C2e=10*6e4;var hbe=3e4,gbe=3,YW=30,Go=class extends Error{constructor(n,i,r,s){super(n);this.status=i;this.code=r;this.path=s}status;code;path},Ji=class extends Error{},rd=class extends Ji{},Hv=class extends rd{};function mbe(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 ybe(e,t){if(!Xu.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}function Ebe(e,t,n,i){throw t<500&&t!==429?new Go(e,t,n,i):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new Hv(e):t===503&&n==="RUN_NOT_READY"?new rd(e):new Ji(e)}async function vbe(e,t,n,i,r,s=1/0){let o=mbe(e.origin),a=`The time limit for ${t} ${n} was reached`,c,u=0;for(let d=1;d<=gbe||c instanceof rd;d+=1){if(c instanceof rd){if(u===YW)throw c;u+=1,d-=1,e.log?.(`${c.message}; trying again (${u} of ${YW}).`),await new Promise(p=>setTimeout(p,Math.max(0,Math.min(e.readyWaitMs??1e4,s-Date.now()))))}else d>1&&await new Promise(p=>setTimeout(p,Math.max(0,Math.min((e.retryDelayMs??2e3)*(d-1),s-Date.now()))));if(Date.now()>=s)throw new Ji(a);try{let p,A=await(Number.isFinite(s)?Promise.race([e.idToken(o),new Promise((g,y)=>{p=setTimeout(()=>y(new Ji(a)),Math.max(1,s-Date.now()))})]).finally(()=>{p&&clearTimeout(p)}):e.idToken(o));if(Date.now()>=s)throw new Ji(a);let h=await(e.fetch??fetch)(new URL(n,o).toString(),{...i(A),redirect:"error",signal:AbortSignal.timeout(Math.max(1,Math.min(hbe,s-Date.now())))}).catch(g=>{throw new Ji(g instanceof Error?g.message:String(g),{cause:g})});return await r(h)}catch(p){if(p instanceof Go||Date.now()>=s)throw p;c=p}}throw c}function bbe(e,t,n,i,r){let s=i.headers.get("cf-ray");e.log?.(`Testbot V3: ${t} ${n} answered ${i.status}${s?`, cf-ray ${s}`:""}: ${r.replace(/\s+/g," ").slice(0,200)}`)}function Ibe(e,t,n,i,r){let s=t==="GET"?void 0:JSON.stringify(i),o=t==="PUT"&&/^\/api\/v1\/runner\/attempts\/[^/]+\/report$/.test(n)&&s!==void 0&&Buffer.byteLength(s,"utf8")>PS;if(o&&Buffer.byteLength(s,"utf8")>t1)throw new Error("The report exceeds the app's 16 MiB expanded report limit");let a=o?new Uint8Array((0,KW.gzipSync)(s)):s;if(o&&a.length>PS)throw new Error("The compressed report exceeds the app's 1 MiB report upload limit");return vbe(e,t,n,u=>({method:t,headers:{Authorization:`Bearer ${u}`,"Content-Type":"application/json",Accept:"application/json",...o?{"Content-Encoding":"gzip"}:{}},body:a}),async u=>{let d=await u.text().catch(()=>""),p={};try{p=JSON.parse(d)}catch{}if(u.ok)return p.data;bbe(e,t,n,u,d);let A=p.error?.fields,h=typeof A?.path=="string"&&typeof A.reason=="string"?` at ${A.path}: ${A.reason}`:"",g=`The Skyramp app refused ${t} ${n}: ${u.status} ${p.error?.code??"no error code"}${h}`;return Ebe(g,u.status,p.error?.code,typeof A?.path=="string"?A.path:void 0)},r)}var S2e=10*6e4;var k2e=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var B2e=l.object({tests:l.object({placements:l.array(l.unknown()).optional()}).passthrough().optional()}).passthrough(),R2e=l.object({repository:DS,testType:l.string(),directory:l.string()}).passthrough();var x2e=l.object({report:l.object({language:l.string()}).passthrough()}).passthrough();var Q2e=l.object({environment:l.object({components:l.array(l.unknown()).optional(),dependencies:l.array(l.unknown()).optional()}).passthrough()}).passthrough(),$2e=l.object({environment:l.object({offLimits:l.unknown().optional()}).passthrough()}).passthrough();var T2e=l.object({name:l.string().min(1),provision:l.literal("existing"),url:l.string().min(1),repository:DS.optional(),revisionUrl:l.string().min(1).optional()}).passthrough(),_2e=l.object({name:l.string().min(1),url:l.string().nullable(),versionUrl:l.string().nullable(),notes:l.string().nullable()}).passthrough();var D2e=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);var N2e={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};async function XW(e,t){return ybe(e.attemptId,"attempt id"),Ibe(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,S1({reportUploaded:e.reportUploaded,recipeUploaded:e.recipeUploaded,revisionsUploaded:e.revisionsUploaded,cancelled:e.cause==="cancelled",timedOut:e.cause==="timed_out",setupFailed:e.cause==="setup_failed",checkoutFailed:e.cause==="checkout_failed"||e.cause==="merge_conflict"&&!e.conflict,mergeConflict:e.cause==="merge_conflict"?e.conflict:void 0,environmentUnverified:e.cause==="environment_unverified",runnerProviderNotReady:e.cause==="runner_provider_not_ready",credentialMissing:e.cause==="credential_missing",modelProviderDenied:e.cause==="model_provider_denied",modelProviderUnavailable:e.cause==="model_provider_unavailable"}))}var TA=ce(require("fs")),Hi=ce(require("path")),e4=require("child_process"),id=Hi.join(".skyramp","sut");function wbe(e){return e.startsWith(`${id}${Hi.sep}`)||e.startsWith(".skyramp/sut/")||/(^|\/)(docker-compose|compose)[^/]*\.ya?ml$/.test(e)||/(^|\/)Dockerfile[^/]*$/.test(e)||/^\.github\/workflows\//.test(e)}function g0(e,t,n={}){let i=t.split(/[\\/]+/).filter(Boolean),r=e;for(let[s,o]of i.entries()){r=Hi.join(r,o);let a=TA.lstatSync(r,{throwIfNoEntry:!1}),c=s===i.length-1;if(!a||a.isSymbolicLink()||(c?n.directory?!a.isDirectory():!a.isFile():!a.isDirectory()))return}return i.length?r:void 0}function Dc(e,t=[]){let n=p=>g0(e,p),i=n(Hi.join(id,"setup.sh")),r=n(Hi.join(id,"teardown.sh")),s=n(Hi.join(id,"get-auth-token.sh")),o,a=n(Hi.join(id,"health.json"));if(a)try{let p=JSON.parse(TA.readFileSync(a,"utf-8"));p&&(p.url||p.command)&&(o=p)}catch{}let c,u=n(Hi.join(id,"deploy-budget.json"));if(u)try{let p=JSON.parse(TA.readFileSync(u,"utf-8"));typeof p?.minutes=="number"&&Number.isFinite(p.minutes)&&p.minutes>0&&(c=p.minutes)}catch{}let d=t.filter(wbe);return{setupScript:i,teardownScript:r,authTokenScript:s,healthHint:o,budgetMinutes:c,present:!!(i||a),staleFiles:d,stale:d.length>0}}var t4=12e4;function Yv(e,t,n){let i=n.timeoutMs??t4;if(n.signal?.aborted)return Promise.resolve(`${e.label} failed (cancelled)`);let[r,...s]=e.argv;return new Promise(o=>{let a="",c=!1,u=!1,d,p;try{p=(0,e4.spawn)(r,s,{cwd:t,env:n.env,stdio:["ignore","pipe","pipe"],detached:!0})}catch(S){let B=S instanceof Error?S.message:String(S);o(`${e.label} failed (could not start: ${B})`);return}let A=S=>{a=(a+S.toString("utf-8")).slice(-4096)};p.stdout?.on("data",A),p.stderr?.on("data",A);let h=()=>{try{p.pid!==void 0&&process.kill(-p.pid,"SIGKILL")}catch{p.kill("SIGKILL")}},g=S=>{let B=a.trim().split(`
216
- `).pop()?.trim().slice(0,300)??"";return`${e.label} failed (${S})${B?`: ${B}`:""}`},y=S=>{u||(u=!0,clearTimeout(E),clearTimeout(d),n.signal?.removeEventListener("abort",b),S!==void 0&&h(),p.stdout?.destroy(),p.stderr?.destroy(),o(S))},b=()=>y(g("cancelled")),E=setTimeout(()=>{c=!0,y(g(`timed out after ${i/1e3} s`))},i);n.signal?.addEventListener("abort",b,{once:!0}),n.signal?.aborted&&b();let v=(S,B)=>{if(c)return g(`timed out after ${i/1e3} s`);if(S!==0)return g(S===null?`killed by ${B}`:`exit ${S}`)};p.on("error",S=>y(g(`could not start: ${S.message}`))),p.on("close",(S,B)=>y(v(S,B))),p.on("exit",(S,B)=>{u||(S!==0?y(v(S,B)):d=setTimeout(()=>y(v(S,B)),1e3))})})}var n4=".skyramp/sut/health.json",Z2e={[n4]:`${n4} (with a url or command)`};function m0(e,t){return!Sp(e.status)||e.environment?[]:[...new Set(e.components.flatMap(n=>n.credentials??[]))].filter(n=>!yz(n,t))}function y0(e){let t=e.filter(fm),n=e.filter(i=>!fm(i));return[n.length>0&&`${n.join(", ")} ${n.length===1?"has":"have"} no value in this setup`,t.length>0&&`${t.join(", ")} ${t.length===1?"is a name":"are names"} Testbot keeps for its own tokens`].filter(Boolean).join("; ")}function Wv(e){if(e.state.stages.onboard?.status==="passed")return Ke(e,"onboard.json")}function Bbe(e){let t=$A(e).serverUrl,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0;return{...e,GIT_CONFIG_COUNT:String(n+2),[`GIT_CONFIG_KEY_${n}`]:`http.${t}/.extraheader`,[`GIT_CONFIG_VALUE_${n}`]:"",[`GIT_CONFIG_KEY_${n+1}`]:"http.extraheader",[`GIT_CONFIG_VALUE_${n+1}`]:""}}var Rbe=90,xbe={CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",CLAUDE_BYTE_STREAM_IDLE_TIMEOUT_MS:String(Rbe*1e3)},r4=30,i4={BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:String(r4*6e4)},s4=["This session is non-interactive: it ends as soon as you stop, and a background command can",`never notify you. Wait for long builds in the foreground (one Bash call may run up to ${r4}`,"minutes) and keep checking until they finish; never end your turn while setup is running. A server that must keep","running after setup is detached inside the command itself, with the redirect of both stdout and stderr","(`> log 2>&1`) on the whole backgrounded command (`docker compose up -d`, or `{ cmd; } </dev/null > log 2>&1 &`).","Without `2>&1` the server keeps the call's stderr open, and in `a || nohup cmd > log &` or","`(cd dir && nohup cmd > log &)` the redirect covers only `cmd`, and the shell that runs it keeps the call's output","open until the server exits. Run a setup script as a command of its own, never piped or chained:","`bash .skyramp/sut/setup.sh`. The call returns its output and exit status when the script exits, even if a server","it started still holds its output; through a pipe (`| tail`), it waits for that server."];function Qbe(e,t){return Bbe(It(e,{...xbe,...t},"session"))}function E0(e){return Qbe(process.env,e)}var Kv=ce(require("fs")),_A=ce(require("path"));var o4=["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"],oqe=[...o4,"skyramp_export_zip","skyramp_actions","skyramp_analyze_changes","skyramp_analyze_test_health","skyramp_batch_mock_generation","skyramp_batch_scenario_test_generation","skyramp_contract_test_generation","skyramp_e2e_test_generation","skyramp_enhance_assertions","skyramp_enrich_test_with_mocks","skyramp_execute_test","skyramp_fix_errors","skyramp_fuzz_test_generation","skyramp_generate_enriched_integration_test","skyramp_init_scan","skyramp_init_workspace","skyramp_integration_test_generation","skyramp_load_test_generation","skyramp_login","skyramp_logout","skyramp_mock_generation","skyramp_modularization","skyramp_one_click_tool","skyramp_preflight_mock_check","skyramp_query_proxy_mocks","skyramp_recommend_tests","skyramp_register_test_plan","skyramp_reuse_code","skyramp_run_existing_tests","skyramp_setup_local_dev_worker","skyramp_smoke_test_generation","skyramp_start_trace_collection","skyramp_stop_trace_collection","skyramp_submit_report","skyramp_ui_test_generation"];var aqe=["skyramp_ui_test_generation","skyramp_mock_generation","skyramp_fix_errors","skyramp_start_trace_collection","skyramp_stop_trace_collection","skyramp_export_zip",...o4];var a4=["Bash(ls:*)","Bash(cat:*)","Bash(head:*)","Bash(tail:*)","Bash(wc:*)","Bash(find:*)","Bash(grep:*)","Bash(rg:*)","Bash(diff:*)","Bash(sort:*)","Bash(env:*)","Bash(echo:*)","Bash(pwd:*)","Bash(which:*)","Bash(cp:*)","Bash(curl:*)","Bash(jq:*)","Bash(true:*)"];var Zv=ce(require("fs"));var Tbe={name:"output-produced",verify(e,t,n){let i=e.outputFileFor(n.name);return(Zv.existsSync(i)?Zv.readFileSync(i,"utf-8"):"").trim().length>0?{name:this.name,passed:!0}:{name:this.name,passed:!1,details:`stage produced no output (${i} empty or missing)`}}},_be=["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 c4(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??_be,exitGates:e.exitGates??[Tbe],prepare:e.prepare,abortIf:e.abortIf,onAbort:e.onAbort,beforeReset:e.beforeReset,teardown:e.teardown,releaseAtRunEnd:e.releaseAtRunEnd,buildMcpServers:e.buildMcpServers,buildReadDirs:e.buildReadDirs,buildPluginDirs:e.buildPluginDirs,buildSettings:e.buildSettings,renderTimeLimit:e.renderTimeLimit,namesSession:e.namesSession,resumeFrom:e.resumeFrom,requiredSkills:e.requiredSkills,buildSessionEnv:e.buildSessionEnv,allowedTools:e.allowedTools,buildDisallowedTools:e.buildDisallowedTools,captureTrace:e.captureTrace,onPassed:e.onPassed,passReason:e.passReason,adversarialReview:e.adversarialReview,retryHint:e.retryHint,beforeGates:e.beforeGates,afterAttempt:e.afterAttempt,retryNote:e.retryNote,salvage:e.salvage,checkpoint:e.checkpoint,needsSutAuth:e.needsSutAuth,triageBranch:e.triageBranch,branchSkipClears:e.branchSkipClears,branchRequires:e.branchRequires}}var Dbe=["Bash(docker:*)","Bash(docker compose:*)","Bash(docker-compose:*)","Bash(bash:*)","Bash(sh:*)","Bash(.skyramp/sut/*)","Bash(./.skyramp/sut/*)","Bash(curl:*)","Bash(sleep:*)",...a4,"Read","Write","Edit"];function Nbe(e){let t=e.state.stages.onboard;if(t&&(t.status==="failed"||t.status==="aborted")){let o=t.reason?` \u2014 ${t.reason.length>300?`${t.reason.slice(0,300)}\u2026`:t.reason}`:"";return{ok:!1,reasons:[`onboarding ran and did not pass (${t.status}${o}) \u2014 deploy does not replay its recipe; fix that and onboard again`]}}let n=Ui(e),i=Wv(e);if(i?.status==="blocked")return{ok:!1,reasons:[`onboarding reported blocked (${i.blockers.length} blocker(s)) \u2014 see outputs/onboard.json`]};let r=e.inputs.setupEvents&&t?.status==="passed"&&i&&!e.inputs.recheck?m0(i,E0()):[];return r.length>0?{ok:!1,reasons:[`the recipe reads ${r.join(", ")}: ${y0(r)} \u2014 deploy waits for the check Skyramp runs once the setup ends`]}:n&&!n.sutRequired&&!(i&&Sp(i.status))&&!e.inputs.recheck?{ok:!1,reasons:["preflight determined no SUT is required (non-application change)"]}:Dc(e.inputs.repositoryPath,n?.changedFiles.map(o=>o.path)).present?{ok:!0,reasons:[]}:{ok:!1,reasons:["no deploy recipe found (.skyramp/sut/setup.sh or health.json) \u2014 run onboarding first"]}}function Pbe(e){let t=e.prepared?.recipe?.budgetMinutes;if(t===void 0)return;let n=Math.min(t+5,90);return n>25?n:void 0}function Ube(e){let t=Ui(e);return{recipe:Dc(e.inputs.repositoryPath,t?.changedFiles.map(i=>i.path))}}function Fbe(e,t){return[t.setupScript,t.teardownScript,t.authTokenScript].filter(n=>!!n).map(n=>_A.relative(e,n))}function Obe(e,t="revisions"){let n=bv(e.inputs);return n.length===0?[]:["","Shared components: these run in an existing environment that this run does not deploy.",...n.map(i=>` - ${i.name} at ${i.url}, running ${i.repository}`),"For each, find the URL on its host where the RUNNING component reports its commit (a version,",`build-info or health endpoint) and record it in "${t}": the url, and what it returned,`,"VERBATIM. This gate fetches each url and reads the commit from what it returns. A checkout's","commit is not the deployed one. Cite only the components listed; leave out one you cannot","check \u2014 it is then reported unverifiable, and no runtime test runs against it."]}function l4(e){return Wv(e)?.environment??e.inputs.recheckEnvironment}function Mbe(e,t){return[`Tasks: the SUT is the customer's existing deployment at ${e}, already running. Never start, stop, redeploy or`,"change it, and write no setup.sh or teardown.sh: this recipe has none on purpose.","1. Sign in the way the recipe records (.skyramp/sut/get-auth-token.sh), when it has one \u2014 never echo it.","2. Health-check: run the recipe's check (.skyramp/sut/health.json) and confirm it answers with real data. Record the"," exact url/command and what it returned.",...t.healthHint?[` The recorded check: ${JSON.stringify(t.healthHint)}`]:[],'3. Record the outcome: "clean" when the check passes; "bringup-failed", with bringupError, when the deployment does',` not answer or is not ready. baseUrls: each component's address. teardown: "true", since nothing was started.`]}function Lbe(e){let t=Wv(e),n=e.inputs.recheck?e.inputs.recheckCredentials??[]:t?ES(t):[];if(n.length===0)return[];let i=e.inputs.sharedEnvironment,r=Io(i).map(s=>s.name);return["",`Credentials: the recipe reads ${n.join(", ")}, each from the environment variable of its name. Test each one that`,"has a value with a request that changes nothing, such as signing in with it (.skyramp/sut/get-auth-token.sh) or a GET","of an authenticated route: never one that creates, changes or deletes data.",...r.length>0?[`The shared components ${r.join(", ")} stay unchanged: test a credential they take only with a read.`]:[],...jbe(e)?["Record each one that is refused, such as with a 401 or 403 or a sign-in that fails, or that the app rejects at",'startup or bootstrap, such as a password it finds too short, in "credentialsRefused": its name, the component that',"refused it, the HTTP status when there was one, and the request or command with what came back. For one with no",'HTTP status, start that evidence with one short phrase saying why and a colon, such as "password shorter than 8','characters: <command and what came back>". Never write a value, there or anywhere. Leave out one with no value:',"Testbot reports it. A refused credential is not drift: never change the recipe to get around it. Never replace a","credential that has a value with a stand-in or a value written into the recipe, and never stop the recipe reading","it: Testbot refuses a recipe that does. When it stops the app coming up or its check passing, the outcome is",'"bringup-failed", and the credential is named.']:["Record each one that is refused, such as with a 401 or 403 or a sign-in that fails, in",'"credentialsRefused": its name, the component that refused it, the HTTP status, and the request or command with what',"came back. Never write a value, there or anywhere. Leave out one with no value: Testbot reports it. A refused","credential is not drift: never change the recipe to get around it. When it stops the app coming up or its check",'passing, the outcome is "bringup-failed", as for any other failure.']]}var jbe=e=>!!(e.inputs.recheck||e.inputs.setupEvents);function Vbe(e){let{recipe:t}=e.prepared,n=e.inputs.repositoryPath,i=Fbe(n,t),r=l4(e),s=e.inputs.sharedEnvironment,o=Io(s).map(a=>a.name);return['You are the "deploy" stage of the Skyramp Testbot.',"",...r?["Purpose: confirm, from a fresh session, that the existing deployment onboard found is reachable and ready, so the","recipe is proven the way every run will use it. The recipe already exists; change nothing."]:["Purpose: bring the system under test (SUT) up from its recorded recipe so","later stages can run tests against it. You do NOT design the deployment \u2014 the","recipe already exists. Execute it, verify it works, and if it has drifted","slightly out of date, correct it and continue (rather than reverting)."],"",`Repository: ${n} \u2014 work inside it.`,`Recipe files present: ${i.join(", ")||"(workspace only)"}`,"",...s4,t.stale?`
215
+ `)[0]}`];case"endgroup":return["##[endgroup]"];default:return[]}}function QA(e){return e.replace(/\/+$/,"")}function d0(e){let t=new URL(e),n=t.pathname.split("/").filter(Boolean);if(n.length)return decodeURIComponent(n[n.length-1]);if(t.hostname.endsWith(".visualstudio.com"))return t.hostname.split(".")[0];throw new Error(`SYSTEM_COLLECTIONURI "${e}" names no organization`)}var sbe=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,48}[A-Za-z0-9])?$/,obe=/[\\/:*?"<>|;#${},+=[\]%\p{Cc}\p{Cf}]/u;function MW(e){return e.length>0&&e.length<=64&&e===e.trim()&&!obe.test(e)&&!/[^\S ]/u.test(e)&&!/^[._]/.test(e)&&!e.endsWith(".")}function Jv(e){return p0(`${e.namespace}/${e.name}`)}function p0(e){let t=e.indexOf("/"),n=e.lastIndexOf("/"),i=e.slice(0,t),r=e.slice(t+1,n),s=e.slice(n+1);if(t<0||t===n||!sbe.test(i)||!MW(r)||!MW(s))throw new Error(`"${e}" is not an Azure DevOps organization/project/repository`);return{organization:i,project:r,name:s}}function LW(e,t){let n=d0(e);if(n.toLowerCase()!==t.organization.toLowerCase())throw new Error(`${t.organization}/${t.project}/${t.name} is not in ${n}, the Azure DevOps organization this job runs in`)}function jW(e,t){return LW(e,t),`${QA(e)}/${encodeURIComponent(t.project)}/_git/${encodeURIComponent(t.name)}`}function f0(e,t){return LW(e,t),`${QA(e)}/${encodeURIComponent(t.project)}/_apis/git/repositories/${encodeURIComponent(t.name)}`}var abe="7.1",xA=class extends Error{constructor(n,i){super(n);this.status=i}status};async function A0(e){let t=e.accept??"application/json",n=new URL(e.url);n.searchParams.has("api-version")||n.searchParams.set("api-version",abe);let i=await(e.fetch??fetch)(n.toString(),{method:e.method??"GET",headers:{Authorization:`Bearer ${e.token}`,Accept:t,...e.body!==void 0?{"Content-Type":"application/json"}:{}},...e.body!==void 0?{body:JSON.stringify(e.body)}:{},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!i.ok){let r=(await i.json().catch(()=>({}))).message;throw new xA(`Azure DevOps answered ${i.status}${typeof r=="string"?`: ${r}`:""}`,i.status)}return t!=="application/json"?Buffer.from(await i.arrayBuffer()):i.status===204?{}:await i.json()}function cbe(e){return`AUTHORIZATION: bearer ${e}`}function VW(e,t){return{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${QA(e)}/.extraheader`,GIT_CONFIG_VALUE_0:cbe(t)}}var ube="7.1-preview.1",lbe=".azure-pipelines/skyramp-testbot-v3.yml";function _c(e){return e.GITHUB_ACTIONS!=="true"&&/^true$/i.test(e.TF_BUILD??"")}var dbe={INPUT_SKYRAMPRUNID:"SKYRAMP_RUN_ID",INPUT_SKYRAMPAPPORIGIN:"SKYRAMP_APP_ORIGIN",INPUT_SKYRAMPMCPGITHUBTOKEN:"SKYRAMP_MCP_GITHUB_TOKEN",INPUT_UICREDENTIALS:"SKYRAMP_UI_LOGINS"};function qW(e=process.env){if(_c(e))for(let[t,n]of Object.entries(dbe))!e[t]&&e[n]!==void 0&&(e[t]=e[n])}function JW(e,t={}){let n=p=>{let A=e[p];if(!A)throw new Error(`${p} is not set; the V3 runner handshake needs it`);return A},i=QA(e.SYSTEM_COLLECTIONURI??""),r=()=>d0(n("SYSTEM_COLLECTIONURI")),s=e.SYSTEM_TEAMPROJECT,o=e.BUILD_REPOSITORY_NAME,a=e.BUILD_REPOSITORY_ID?.toLowerCase(),c=e.SYSTEM_ACCESSTOKEN,u=t.mask??(p=>FW(p)),d=p=>async()=>{if(!p)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_OIDCREQUESTURI to $(System.OidcRequestUri).");if(!c)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_ACCESSTOKEN to $(System.AccessToken).");let A=new URL(p);if(A.protocol!=="https:")throw new Error("SYSTEM_OIDCREQUESTURI is not an https URL");A.searchParams.set("api-version",ube);let h=await(t.fetch??fetch)(A.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json",Accept:"application/json"},body:"{}",redirect:"error",signal:AbortSignal.timeout(3e4)});if(!h.ok)throw new Error(`Azure DevOps refused the OIDC token request: ${h.status}`);let g=(await h.json().catch(()=>({}))).oidcToken;if(typeof g!="string"||!g)throw new Error("Azure DevOps's OIDC token response carried no token");return u(g),g};return{runnerPlatform:_c(e)?"azure":void 0,workspace:e.BUILD_SOURCESDIRECTORY||void 0,serverUrl:i,apiUrl:i,repository:a&&s&&o&&i?{id:a,slug:`${r()}/${s}/${o}`}:void 0,runId:e.BUILD_BUILDID||void 0,runAttempt:e.SYSTEM_STAGEATTEMPT||void 0,job:e.SYSTEM_JOBNAME||void 0,execution(){let p=n("SYSTEM_STAGEATTEMPT");if(!/^[1-9][0-9]*$/.test(p))throw new Error(`SYSTEM_STAGEATTEMPT is "${p}", not a positive whole number`);let A=n("SYSTEM_COLLECTIONID").toLowerCase();if(!Xu.test(A))throw new Error(`SYSTEM_COLLECTIONID is "${A}", not a GUID`);let h=n("BUILD_REPOSITORY_ID").toLowerCase();if(!Xu.test(h))throw new Error(`BUILD_REPOSITORY_ID is "${h}", not a GUID`);let g=[r(),n("SYSTEM_TEAMPROJECT"),n("SYSTEM_DEFINITIONID"),n("BUILD_BUILDID")].map(encodeURIComponent).join("/");return{provider:"azure-devops",repository:{provider:"azure-devops",providerAccountId:A,providerRepositoryId:h},providerRunId:g,providerRunAttempt:Number(p),workflowRef:`${lbe}@${n("BUILD_SOURCEBRANCH")}`}},takeIdToken(){let p=e.SYSTEM_OIDCREQUESTURI;delete e.SYSTEM_OIDCREQUESTURI;let A=d(p);return()=>A()},takeSourceToken(){return delete e.SYSTEM_ACCESSTOKEN,c||void 0},webIdentity(){if(!e.SYSTEM_OIDCREQUESTURI?.trim()||!c)return;let p=d(e.SYSTEM_OIDCREQUESTURI);return{token:()=>p(),runId:e.BUILD_BUILDID}},v3RunsOnly:!0,assumesBedrockRole:!0,namesSourceToMcp:!0,runSettingsFromApp:!0,checkSourceName(p){Jv(p)},cloneUrl(p){return jW(i,Jv(p))},gitAuthEnv(p){return VW(i,p)},async pullRequest(p,A,h){let g=await A0({token:await h.token(),url:`${f0(i,Jv(p))}/pullrequests/${A}`,fetch:h.fetch}),y=g.status==="completed";return{...typeof g.title=="string"?{title:g.title}:{},...typeof g.description=="string"?{body:g.description}:{},...typeof g.status=="string"?{merged:y}:{},...y&&typeof g.lastMergeCommit?.commitId=="string"?{mergeCommit:g.lastMergeCommit.commitId}:{},...y&&typeof g.lastMergeSourceCommit?.commitId=="string"?{mergedHead:g.lastMergeSourceCommit.commitId}:{}}},async commit(p,A,h){let g;try{g=f0(i,p0(p))}catch{return{lookup:"unknown"}}try{let y=await A0({token:await h.token(),url:`${g}/commits/${encodeURIComponent(A)}`,fetch:h.fetch});return typeof y.commitId=="string"?{sha:y.commitId}:{lookup:"missing"}}catch(y){return{lookup:y instanceof xA&&(y.status===404||y.status===400)?"missing":"unknown"}}}}}xn();var pbe=5e3,h0=/^(?!\.\.?$)[A-Za-z0-9._-]{1,100}$/;function fbe(e){let t=Buffer.from(`x-access-token:${e}`).toString("base64");return us(t),`AUTHORIZATION: basic ${t}`}function HW(e,t={}){let n=c=>{let u=e[c];if(!u)throw new Error(`${c} is not set; the V3 runner handshake needs it`);return u},i=e.GITHUB_REPOSITORY_ID,r=e.GITHUB_REPOSITORY,s=(e.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,""),o=(e.GITHUB_API_URL||"https://api.github.com").replace(/\/+$/,""),a=async(c,u)=>u.fetch(c,{headers:{Authorization:`Bearer ${await u.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:s,apiUrl:o,repository:i&&r?{id:i,slug:r}:void 0,runId:e.GITHUB_RUN_ID||void 0,runAttempt:e.GITHUB_RUN_ATTEMPT||void 0,job:e.GITHUB_JOB||void 0,execution(){let c=n("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:n("GITHUB_REPOSITORY_OWNER_ID"),providerRepositoryId:n("GITHUB_REPOSITORY_ID")},providerRunId:n("GITHUB_RUN_ID"),providerRunAttempt:Number(c),workflowRef:n("GITHUB_WORKFLOW_REF")}},takeIdToken(){let c=e.ACTIONS_ID_TOKEN_REQUEST_URL,u=e.ACTIONS_ID_TOKEN_REQUEST_TOKEN;return delete e.ACTIONS_ID_TOKEN_REQUEST_URL,delete e.ACTIONS_ID_TOKEN_REQUEST_TOKEN,async d=>{if(!c||!u)throw new Error("The job cannot request an OIDC token. Give it the `id-token: write` permission.");let p=new URL(c);p.searchParams.set("audience",d);let A=await fetch(p,{headers:{Authorization:`Bearer ${u}`,Accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!A.ok)throw new Error(`GitHub refused the OIDC token request: ${A.status}`);let h=(await A.json().catch(()=>({}))).value;if(typeof h!="string"||!h)throw new Error("GitHub's OIDC token response carried no token");return us(h),h}},webIdentity(){return!e.ACTIONS_ID_TOKEN_REQUEST_TOKEN?.trim()||!e.ACTIONS_ID_TOKEN_REQUEST_URL?.trim()?void 0:{token:t.getIDToken??(u=>_L(u)),runId:e.GITHUB_RUN_ID}},v3RunsOnly:!1,assumesBedrockRole:!1,namesSourceToMcp:!1,runSettingsFromApp:!1,checkSourceName(c){for(let u of[c.namespace,c.name])if(!h0.test(u))throw new Error(`"${u}" is not a repository name`)},cloneUrl(c){return`${s}/${c.namespace}/${c.name}.git`},gitAuthEnv(c){return c?{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${s}/.extraheader`,GIT_CONFIG_VALUE_0:fbe(c)}:{}},async pullRequest({namespace:c,name:u},d,p){if(![c,u].every(g=>h0.test(g)))throw new Error("the repository name is not valid");let A=await a(`${o}/repos/${c}/${u}/pulls/${d}`,p);if(!A.ok)throw new Error(`GitHub answered ${A.status}`);let h=await A.json();return{...typeof h.title=="string"?{title:h.title}:{},...typeof h.body=="string"?{body:h.body}:{},...typeof h.merged=="boolean"?{merged:h.merged}:{},...h.merged===!0&&typeof h.merge_commit_sha=="string"?{mergeCommit:h.merge_commit_sha}:{},...h.merged===!0&&typeof h.head?.sha=="string"?{mergedHead:h.head.sha}:{}}},async commit(c,u,d){let[p,A,...h]=c.split("/");if(h.length||![p,A].every(g=>g!==void 0&&h0.test(g)))return{lookup:"unknown"};try{let g=await a(`${o}/repos/${p}/${A}/commits/${encodeURIComponent(u)}`,d);if(g.status===404||g.status===422)return{lookup:"missing"};if(!g.ok)return{lookup:"unknown"};let y=await g.json();return typeof y.sha=="string"?{sha:y.sha}:{lookup:"missing"}}catch{return{lookup:"unknown"}}},async revokeToken(c,u){let d=await u(`${o}/installation/token`,{method:"DELETE",headers:{Authorization:`Bearer ${c}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(pbe)});if(!d.ok&&d.status!==401)throw new Error(`GitHub answered ${d.status}`)}}}function $A(e=process.env){return _c(e)?JW(e):HW(e)}var C2e=10*6e4;var S2e=10*6e4;var hbe=3e4,gbe=3,YW=30,Go=class extends Error{constructor(n,i,r,s){super(n);this.status=i;this.code=r;this.path=s}status;code;path},Ji=class extends Error{},rd=class extends Ji{},Hv=class extends rd{};function mbe(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 ybe(e,t){if(!Xu.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}function Ebe(e,t,n,i){throw t<500&&t!==429?new Go(e,t,n,i):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new Hv(e):t===503&&n==="RUN_NOT_READY"?new rd(e):new Ji(e)}async function vbe(e,t,n,i,r,s=1/0){let o=mbe(e.origin),a=`The time limit for ${t} ${n} was reached`,c,u=0;for(let d=1;d<=gbe||c instanceof rd;d+=1){if(c instanceof rd){if(u===YW)throw c;u+=1,d-=1,e.log?.(`${c.message}; trying again (${u} of ${YW}).`),await new Promise(p=>setTimeout(p,Math.max(0,Math.min(e.readyWaitMs??1e4,s-Date.now()))))}else d>1&&await new Promise(p=>setTimeout(p,Math.max(0,Math.min((e.retryDelayMs??2e3)*(d-1),s-Date.now()))));if(Date.now()>=s)throw new Ji(a);try{let p,A=await(Number.isFinite(s)?Promise.race([e.idToken(o),new Promise((g,y)=>{p=setTimeout(()=>y(new Ji(a)),Math.max(1,s-Date.now()))})]).finally(()=>{p&&clearTimeout(p)}):e.idToken(o));if(Date.now()>=s)throw new Ji(a);let h=await(e.fetch??fetch)(new URL(n,o).toString(),{...i(A),redirect:"error",signal:AbortSignal.timeout(Math.max(1,Math.min(hbe,s-Date.now())))}).catch(g=>{throw new Ji(g instanceof Error?g.message:String(g),{cause:g})});return await r(h)}catch(p){if(p instanceof Go||Date.now()>=s)throw p;c=p}}throw c}function bbe(e,t,n,i,r){let s=i.headers.get("cf-ray");e.log?.(`Testbot V3: ${t} ${n} answered ${i.status}${s?`, cf-ray ${s}`:""}: ${r.replace(/\s+/g," ").slice(0,200)}`)}function Ibe(e,t,n,i,r){let s=t==="GET"?void 0:JSON.stringify(i),o=t==="PUT"&&/^\/api\/v1\/runner\/attempts\/[^/]+\/report$/.test(n)&&s!==void 0&&Buffer.byteLength(s,"utf8")>PS;if(o&&Buffer.byteLength(s,"utf8")>t1)throw new Error("The report exceeds the app's 16 MiB expanded report limit");let a=o?new Uint8Array((0,KW.gzipSync)(s)):s;if(o&&a.length>PS)throw new Error("The compressed report exceeds the app's 1 MiB report upload limit");return vbe(e,t,n,u=>({method:t,headers:{Authorization:`Bearer ${u}`,"Content-Type":"application/json",Accept:"application/json",...o?{"Content-Encoding":"gzip"}:{}},body:a}),async u=>{let d=await u.text().catch(()=>""),p={};try{p=JSON.parse(d)}catch{}if(u.ok)return p.data;bbe(e,t,n,u,d);let A=p.error?.fields,h=typeof A?.path=="string"&&typeof A.reason=="string"?` at ${A.path}: ${A.reason}`:"",g=`The Skyramp app refused ${t} ${n}: ${u.status} ${p.error?.code??"no error code"}${h}`;return Ebe(g,u.status,p.error?.code,typeof A?.path=="string"?A.path:void 0)},r)}var k2e=10*6e4;var B2e=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var R2e=l.object({tests:l.object({placements:l.array(l.unknown()).optional()}).passthrough().optional()}).passthrough(),x2e=l.object({repository:DS,testType:l.string(),directory:l.string()}).passthrough();var Q2e=l.object({report:l.object({language:l.string()}).passthrough()}).passthrough();var $2e=l.object({environment:l.object({components:l.array(l.unknown()).optional(),dependencies:l.array(l.unknown()).optional()}).passthrough()}).passthrough(),T2e=l.object({environment:l.object({offLimits:l.unknown().optional()}).passthrough()}).passthrough();var _2e=l.object({name:l.string().min(1),provision:l.literal("existing"),url:l.string().min(1),repository:DS.optional(),revisionUrl:l.string().min(1).optional()}).passthrough(),D2e=l.object({name:l.string().min(1),url:l.string().nullable(),versionUrl:l.string().nullable(),notes:l.string().nullable()}).passthrough();var N2e=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);var P2e={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};async function XW(e,t){return ybe(e.attemptId,"attempt id"),Ibe(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,S1({reportUploaded:e.reportUploaded,recipeUploaded:e.recipeUploaded,revisionsUploaded:e.revisionsUploaded,cancelled:e.cause==="cancelled",timedOut:e.cause==="timed_out",setupFailed:e.cause==="setup_failed",checkoutFailed:e.cause==="checkout_failed"||e.cause==="merge_conflict"&&!e.conflict,mergeConflict:e.cause==="merge_conflict"?e.conflict:void 0,environmentUnverified:e.cause==="environment_unverified",runnerProviderNotReady:e.cause==="runner_provider_not_ready",credentialMissing:e.cause==="credential_missing",modelProviderDenied:e.cause==="model_provider_denied",modelProviderUnavailable:e.cause==="model_provider_unavailable"}))}var TA=ce(require("fs")),Hi=ce(require("path")),e4=require("child_process"),id=Hi.join(".skyramp","sut");function wbe(e){return e.startsWith(`${id}${Hi.sep}`)||e.startsWith(".skyramp/sut/")||/(^|\/)(docker-compose|compose)[^/]*\.ya?ml$/.test(e)||/(^|\/)Dockerfile[^/]*$/.test(e)||/^\.github\/workflows\//.test(e)}function g0(e,t,n={}){let i=t.split(/[\\/]+/).filter(Boolean),r=e;for(let[s,o]of i.entries()){r=Hi.join(r,o);let a=TA.lstatSync(r,{throwIfNoEntry:!1}),c=s===i.length-1;if(!a||a.isSymbolicLink()||(c?n.directory?!a.isDirectory():!a.isFile():!a.isDirectory()))return}return i.length?r:void 0}function Dc(e,t=[]){let n=p=>g0(e,p),i=n(Hi.join(id,"setup.sh")),r=n(Hi.join(id,"teardown.sh")),s=n(Hi.join(id,"get-auth-token.sh")),o,a=n(Hi.join(id,"health.json"));if(a)try{let p=JSON.parse(TA.readFileSync(a,"utf-8"));p&&(p.url||p.command)&&(o=p)}catch{}let c,u=n(Hi.join(id,"deploy-budget.json"));if(u)try{let p=JSON.parse(TA.readFileSync(u,"utf-8"));typeof p?.minutes=="number"&&Number.isFinite(p.minutes)&&p.minutes>0&&(c=p.minutes)}catch{}let d=t.filter(wbe);return{setupScript:i,teardownScript:r,authTokenScript:s,healthHint:o,budgetMinutes:c,present:!!(i||a),staleFiles:d,stale:d.length>0}}var t4=12e4;function Yv(e,t,n){let i=n.timeoutMs??t4;if(n.signal?.aborted)return Promise.resolve(`${e.label} failed (cancelled)`);let[r,...s]=e.argv;return new Promise(o=>{let a="",c=!1,u=!1,d,p;try{p=(0,e4.spawn)(r,s,{cwd:t,env:n.env,stdio:["ignore","pipe","pipe"],detached:!0})}catch(S){let B=S instanceof Error?S.message:String(S);o(`${e.label} failed (could not start: ${B})`);return}let A=S=>{a=(a+S.toString("utf-8")).slice(-4096)};p.stdout?.on("data",A),p.stderr?.on("data",A);let h=()=>{try{p.pid!==void 0&&process.kill(-p.pid,"SIGKILL")}catch{p.kill("SIGKILL")}},g=S=>{let B=a.trim().split(`
216
+ `).pop()?.trim().slice(0,300)??"";return`${e.label} failed (${S})${B?`: ${B}`:""}`},y=S=>{u||(u=!0,clearTimeout(E),clearTimeout(d),n.signal?.removeEventListener("abort",b),S!==void 0&&h(),p.stdout?.destroy(),p.stderr?.destroy(),o(S))},b=()=>y(g("cancelled")),E=setTimeout(()=>{c=!0,y(g(`timed out after ${i/1e3} s`))},i);n.signal?.addEventListener("abort",b,{once:!0}),n.signal?.aborted&&b();let v=(S,B)=>{if(c)return g(`timed out after ${i/1e3} s`);if(S!==0)return g(S===null?`killed by ${B}`:`exit ${S}`)};p.on("error",S=>y(g(`could not start: ${S.message}`))),p.on("close",(S,B)=>y(v(S,B))),p.on("exit",(S,B)=>{u||(S!==0?y(v(S,B)):d=setTimeout(()=>y(v(S,B)),1e3))})})}var n4=".skyramp/sut/health.json",K2e={[n4]:`${n4} (with a url or command)`};function m0(e,t){return!Sp(e.status)||e.environment?[]:[...new Set(e.components.flatMap(n=>n.credentials??[]))].filter(n=>!yz(n,t))}function y0(e){let t=e.filter(fm),n=e.filter(i=>!fm(i));return[n.length>0&&`${n.join(", ")} ${n.length===1?"has":"have"} no value in this setup`,t.length>0&&`${t.join(", ")} ${t.length===1?"is a name":"are names"} Testbot keeps for its own tokens`].filter(Boolean).join("; ")}function Wv(e){if(e.state.stages.onboard?.status==="passed")return Ke(e,"onboard.json")}function Bbe(e){let t=$A(e).serverUrl,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0;return{...e,GIT_CONFIG_COUNT:String(n+2),[`GIT_CONFIG_KEY_${n}`]:`http.${t}/.extraheader`,[`GIT_CONFIG_VALUE_${n}`]:"",[`GIT_CONFIG_KEY_${n+1}`]:"http.extraheader",[`GIT_CONFIG_VALUE_${n+1}`]:""}}var Rbe=90,xbe={CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",CLAUDE_BYTE_STREAM_IDLE_TIMEOUT_MS:String(Rbe*1e3)},r4=30,i4={BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:String(r4*6e4)},s4=["This session is non-interactive: it ends as soon as you stop, and a background command can",`never notify you. Wait for long builds in the foreground (one Bash call may run up to ${r4}`,"minutes) and keep checking until they finish; never end your turn while setup is running. A server that must keep","running after setup is detached inside the command itself, with the redirect of both stdout and stderr","(`> log 2>&1`) on the whole backgrounded command (`docker compose up -d`, or `{ cmd; } </dev/null > log 2>&1 &`).","Without `2>&1` the server keeps the call's stderr open, and in `a || nohup cmd > log &` or","`(cd dir && nohup cmd > log &)` the redirect covers only `cmd`, and the shell that runs it keeps the call's output","open until the server exits. Run a setup script as a command of its own, never piped or chained:","`bash .skyramp/sut/setup.sh`. The call returns its output and exit status when the script exits, even if a server","it started still holds its output; through a pipe (`| tail`), it waits for that server."];function Qbe(e,t){return Bbe(It(e,{...xbe,...t},"session"))}function E0(e){return Qbe(process.env,e)}var Kv=ce(require("fs")),_A=ce(require("path"));var o4=["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"],aqe=[...o4,"skyramp_export_zip","skyramp_actions","skyramp_analyze_changes","skyramp_analyze_test_health","skyramp_batch_mock_generation","skyramp_batch_scenario_test_generation","skyramp_contract_test_generation","skyramp_e2e_test_generation","skyramp_enhance_assertions","skyramp_enrich_test_with_mocks","skyramp_execute_test","skyramp_fix_errors","skyramp_fuzz_test_generation","skyramp_generate_enriched_integration_test","skyramp_init_scan","skyramp_init_workspace","skyramp_integration_test_generation","skyramp_load_test_generation","skyramp_login","skyramp_logout","skyramp_mock_generation","skyramp_modularization","skyramp_one_click_tool","skyramp_preflight_mock_check","skyramp_query_proxy_mocks","skyramp_recommend_tests","skyramp_register_test_plan","skyramp_reuse_code","skyramp_run_existing_tests","skyramp_setup_local_dev_worker","skyramp_smoke_test_generation","skyramp_start_trace_collection","skyramp_stop_trace_collection","skyramp_submit_report","skyramp_ui_test_generation"];var cqe=["skyramp_ui_test_generation","skyramp_mock_generation","skyramp_fix_errors","skyramp_start_trace_collection","skyramp_stop_trace_collection","skyramp_export_zip",...o4];var a4=["Bash(ls:*)","Bash(cat:*)","Bash(head:*)","Bash(tail:*)","Bash(wc:*)","Bash(find:*)","Bash(grep:*)","Bash(rg:*)","Bash(diff:*)","Bash(sort:*)","Bash(env:*)","Bash(echo:*)","Bash(pwd:*)","Bash(which:*)","Bash(cp:*)","Bash(curl:*)","Bash(jq:*)","Bash(true:*)"];var Zv=ce(require("fs"));var Tbe={name:"output-produced",verify(e,t,n){let i=e.outputFileFor(n.name);return(Zv.existsSync(i)?Zv.readFileSync(i,"utf-8"):"").trim().length>0?{name:this.name,passed:!0}:{name:this.name,passed:!1,details:`stage produced no output (${i} empty or missing)`}}},_be=["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 c4(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??_be,exitGates:e.exitGates??[Tbe],prepare:e.prepare,abortIf:e.abortIf,onAbort:e.onAbort,beforeReset:e.beforeReset,teardown:e.teardown,releaseAtRunEnd:e.releaseAtRunEnd,buildMcpServers:e.buildMcpServers,buildReadDirs:e.buildReadDirs,buildPluginDirs:e.buildPluginDirs,buildSettings:e.buildSettings,renderTimeLimit:e.renderTimeLimit,namesSession:e.namesSession,resumeFrom:e.resumeFrom,requiredSkills:e.requiredSkills,buildSessionEnv:e.buildSessionEnv,allowedTools:e.allowedTools,buildDisallowedTools:e.buildDisallowedTools,captureTrace:e.captureTrace,onPassed:e.onPassed,passReason:e.passReason,adversarialReview:e.adversarialReview,retryHint:e.retryHint,beforeGates:e.beforeGates,afterAttempt:e.afterAttempt,retryNote:e.retryNote,salvage:e.salvage,checkpoint:e.checkpoint,needsSutAuth:e.needsSutAuth,triageBranch:e.triageBranch,branchSkipClears:e.branchSkipClears,branchRequires:e.branchRequires}}var Dbe=["Bash(docker:*)","Bash(docker compose:*)","Bash(docker-compose:*)","Bash(bash:*)","Bash(sh:*)","Bash(.skyramp/sut/*)","Bash(./.skyramp/sut/*)","Bash(curl:*)","Bash(sleep:*)",...a4,"Read","Write","Edit"];function Nbe(e){let t=e.state.stages.onboard;if(t&&(t.status==="failed"||t.status==="aborted")){let o=t.reason?` \u2014 ${t.reason.length>300?`${t.reason.slice(0,300)}\u2026`:t.reason}`:"";return{ok:!1,reasons:[`onboarding ran and did not pass (${t.status}${o}) \u2014 deploy does not replay its recipe; fix that and onboard again`]}}let n=Ui(e),i=Wv(e);if(i?.status==="blocked")return{ok:!1,reasons:[`onboarding reported blocked (${i.blockers.length} blocker(s)) \u2014 see outputs/onboard.json`]};let r=e.inputs.setupEvents&&t?.status==="passed"&&i&&!e.inputs.recheck?m0(i,E0()):[];return r.length>0?{ok:!1,reasons:[`the recipe reads ${r.join(", ")}: ${y0(r)} \u2014 deploy waits for the check Skyramp runs once the setup ends`]}:n&&!n.sutRequired&&!(i&&Sp(i.status))&&!e.inputs.recheck?{ok:!1,reasons:["preflight determined no SUT is required (non-application change)"]}:Dc(e.inputs.repositoryPath,n?.changedFiles.map(o=>o.path)).present?{ok:!0,reasons:[]}:{ok:!1,reasons:["no deploy recipe found (.skyramp/sut/setup.sh or health.json) \u2014 run onboarding first"]}}function Pbe(e){let t=e.prepared?.recipe?.budgetMinutes;if(t===void 0)return;let n=Math.min(t+5,90);return n>25?n:void 0}function Ube(e){let t=Ui(e);return{recipe:Dc(e.inputs.repositoryPath,t?.changedFiles.map(i=>i.path))}}function Fbe(e,t){return[t.setupScript,t.teardownScript,t.authTokenScript].filter(n=>!!n).map(n=>_A.relative(e,n))}function Obe(e,t="revisions"){let n=bv(e.inputs);return n.length===0?[]:["","Shared components: these run in an existing environment that this run does not deploy.",...n.map(i=>` - ${i.name} at ${i.url}, running ${i.repository}`),"For each, find the URL on its host where the RUNNING component reports its commit (a version,",`build-info or health endpoint) and record it in "${t}": the url, and what it returned,`,"VERBATIM. This gate fetches each url and reads the commit from what it returns. A checkout's","commit is not the deployed one. Cite only the components listed; leave out one you cannot","check \u2014 it is then reported unverifiable, and no runtime test runs against it."]}function l4(e){return Wv(e)?.environment??e.inputs.recheckEnvironment}function Mbe(e,t){return[`Tasks: the SUT is the customer's existing deployment at ${e}, already running. Never start, stop, redeploy or`,"change it, and write no setup.sh or teardown.sh: this recipe has none on purpose.","1. Sign in the way the recipe records (.skyramp/sut/get-auth-token.sh), when it has one \u2014 never echo it.","2. Health-check: run the recipe's check (.skyramp/sut/health.json) and confirm it answers with real data. Record the"," exact url/command and what it returned.",...t.healthHint?[` The recorded check: ${JSON.stringify(t.healthHint)}`]:[],'3. Record the outcome: "clean" when the check passes; "bringup-failed", with bringupError, when the deployment does',` not answer or is not ready. baseUrls: each component's address. teardown: "true", since nothing was started.`]}function Lbe(e){let t=Wv(e),n=e.inputs.recheck?e.inputs.recheckCredentials??[]:t?ES(t):[];if(n.length===0)return[];let i=e.inputs.sharedEnvironment,r=Io(i).map(s=>s.name);return["",`Credentials: the recipe reads ${n.join(", ")}, each from the environment variable of its name. Test each one that`,"has a value with a request that changes nothing, such as signing in with it (.skyramp/sut/get-auth-token.sh) or a GET","of an authenticated route: never one that creates, changes or deletes data.",...r.length>0?[`The shared components ${r.join(", ")} stay unchanged: test a credential they take only with a read.`]:[],...jbe(e)?["Record each one that is refused, such as with a 401 or 403 or a sign-in that fails, or that the app rejects at",'startup or bootstrap, such as a password it finds too short, in "credentialsRefused": its name, the component that',"refused it, the HTTP status when there was one, and the request or command with what came back. For one with no",'HTTP status, start that evidence with one short phrase saying why and a colon, such as "password shorter than 8','characters: <command and what came back>". Never write a value, there or anywhere. Leave out one with no value:',"Testbot reports it. A refused credential is not drift: never change the recipe to get around it. Never replace a","credential that has a value with a stand-in or a value written into the recipe, and never stop the recipe reading","it: Testbot refuses a recipe that does. When it stops the app coming up or its check passing, the outcome is",'"bringup-failed", and the credential is named.']:["Record each one that is refused, such as with a 401 or 403 or a sign-in that fails, in",'"credentialsRefused": its name, the component that refused it, the HTTP status, and the request or command with what',"came back. Never write a value, there or anywhere. Leave out one with no value: Testbot reports it. A refused","credential is not drift: never change the recipe to get around it. When it stops the app coming up or its check",'passing, the outcome is "bringup-failed", as for any other failure.']]}var jbe=e=>!!(e.inputs.recheck||e.inputs.setupEvents);function Vbe(e){let{recipe:t}=e.prepared,n=e.inputs.repositoryPath,i=Fbe(n,t),r=l4(e),s=e.inputs.sharedEnvironment,o=Io(s).map(a=>a.name);return['You are the "deploy" stage of the Skyramp Testbot.',"",...r?["Purpose: confirm, from a fresh session, that the existing deployment onboard found is reachable and ready, so the","recipe is proven the way every run will use it. The recipe already exists; change nothing."]:["Purpose: bring the system under test (SUT) up from its recorded recipe so","later stages can run tests against it. You do NOT design the deployment \u2014 the","recipe already exists. Execute it, verify it works, and if it has drifted","slightly out of date, correct it and continue (rather than reverting)."],"",`Repository: ${n} \u2014 work inside it.`,`Recipe files present: ${i.join(", ")||"(workspace only)"}`,"",...s4,t.stale?`
217
217
  STALENESS WARNING: this PR changed recipe/infra files (${t.staleFiles.join(", ")}).
218
218
  The recorded recipe may no longer match. If bring-up fails, first decide
219
219
  WHY: recipe drift (infra moved, recipe is behind) vs the change itself
220
220
  breaking bring-up. Do NOT paper over a PR that broke the app.`:"","",...r?Mbe(r.address,t):["Tasks:","1. Replay the recipe: run .skyramp/sut/setup.sh (or the workspace bring-up)"," even when the SUT already answers: never skip it because something is running."," Bring up every dependency you can; mock one only when deploying it here"," is genuinely infeasible. If the recipe has drifted, correct it so it works"," and update the recipe files to what actually worked. teardown.sh exits 0"," when nothing runs.","2. Seed or reset state per the recipe. Acquire the auth token the way the"," recipe records (.skyramp/sut/get-auth-token.sh) \u2014 never echo it.",...o.length?[` Leave the shared components ${o.join(", ")} unchanged: do not seed or reset them.`]:[],"3. Health-check: confirm application logic answers with real data (seeded",' data readable via a real endpoint) \u2014 NOT "port open", NOT "any HTTP',' status". Record the exact url/command and what it returned.',...t.healthHint?[" Recommended health check (recorded by onboarding \u2014 prefer it, and",` record its real output): ${JSON.stringify(t.healthHint)}`]:[],'4. Record the outcome honestly (see the schema): "change-broke-bringup" is',' published to the author as "your change broke the app" and needs evidence'," \u2014 bringupError plus suspectFiles that THIS PR changed; without a changed",' file to point at, it is "bringup-failed".'],...Obe(e),...Lbe(e),"","Output: end with one JSON object matching:","",T1(xp)," // health.output is evidence, not narration: the exact bytes, with NOTHING"," // appended \u2014 no gloss on what the response proves, no list of the other probes"," // you ran. This gate RE-RUNS the check and matches the fresh output against this"," // field, so a sentence added here describes a run nobody can reproduce. Say what"," // it means in your prose answer instead."," // On a failed bring-up, baseUrls/health may be omitted \u2014 never invent a URL for an app that didn't start."].filter(a=>a!==void 0).join(`
221
- `)}function d4(e){let t=_A.join(e.outputsDir,"deploy.txt");if(Kv.existsSync(t)){let{deploy:i}=Bc({exitCode:0,stdout:Kv.readFileSync(t,"utf-8"),stderr:"",timedOut:!1,durationMs:0});if(i?.teardown)return{argv:["sh","-c",i.teardown],label:"deploy.json's teardown"}}let{teardownScript:n}=Dc(e.inputs.repositoryPath);if(n)return{argv:["bash",n],label:_A.join(".skyramp","sut","teardown.sh")}}function p4(e,t){return Yv(t,e.inputs.repositoryPath,{env:It()})}async function u4(e){let t=d4(e);t&&await p4(e,t)}async function Gbe(e,t){let n=t.passed?void 0:f4(e);if(!n)return;let i=await p4(e,n);return i&&`${i} (if nothing was running, a teardown must exit 0)`}function f4(e){return l4(e)?void 0:d4(e)}function zbe(e){if(f4(e))return"Testbot tore down the SUT the previous attempt started. Bring it up again from the start: run .skyramp/sut/setup.sh (or the workspace bring-up), even if something still answers. Never reuse what is running."}function qbe(e,t){let{deploy:n}=Bc(t,e.inputs.repositoryPath,e.secretValues);if(!n)return;if(n.outcome==="bringup-failed"){let r=Kn(n.bringupError?.output?.trim()??"",e.secretValues??[]);return`bring-up failed (environment) \u2014 no live app for later stages${r?`: ${r.slice(0,160)}`:""}`}if(n.outcome==="change-broke-bringup")return"this PR broke bring-up \u2014 recorded as a finding, no live app for later stages";let i=lA(e).map(r=>r.name);if(i.length)return`the shared environment's ${i.join(", ")} does not verifiably run the revision under validation \u2014 no runtime test runs against it`}var A4=c4({name:"deploy",model:"opus",timeoutMinutes:25,requires:["preflight"],softRequires:["onboard"],triageBranch:"runtime",validateInput:Nbe,prepare:Ube,scaleTimeout:Pbe,buildPrompt:Vbe,allowedTools:Dbe,buildSessionEnv:()=>({...i4}),selfVerification:["dependencies lists every backing service, true only if really deployed \u2014 a mocked one is false, never omitted.","Your final message is one JSON object matching the schema."],exitGates:[wv(),YH()],onPassed:async(e,t)=>({...ZH(e,t),...await WH(e,t)}),passReason:qbe,afterAttempt:Gbe,retryNote:zbe,onAbort:u4,teardown:u4});xn();var Oqe=20*1024*1024;var g4=ce(require("path"));var Hqe=g4.join(".skyramp","sut","get-auth-token.sh");var v0="\\$([A-Z][A-Z0-9_]{0,99})",Yqe=new RegExp(`^${v0}$`),Wqe=new RegExp(`^${v0}:${v0}$`);var _Je=3*6e4;var DJe=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;var Zbe={discover:"reading the repositories",start:"starting the components",check:"checking that the components answer"};var VJe={running:"up",healthy:"up",ready:"up",started:"up",building:"starting",pending:"starting",installing:"starting",skipped:"out_of_scope",excluded:"out_of_scope","out-of-scope":"out_of_scope"};var GJe=new RegExp(tl.source,"g");var dHe=new RegExp(tl.source,"g");var eIe="https://testbot.skyramp.dev",zo={attemptId:"v3AttemptId",deadlineAt:"v3DeadlineAt",reportUploaded:"v3ReportUploaded",recipeUploaded:"v3RecipeUploaded",recipeStatus:"v3RecipeStatus",revisionsUploaded:"v3RevisionsUploaded",cause:"v3Cause",conflict:"v3Conflict"};function tIe(e,t,n){return{origin:e,idToken:t,sourceToken:n,mask:i=>us(i),log:i=>ki(i),onTokenRefused:(i,r)=>{rIe(i)&&m4.set(r,i)},onTokenGranted:i=>{m4.delete(i)}}}var m4=new Map;var xWe=["setup_failed","checkout_failed","environment_unverified"];function nIe(e,t){return t.getTime()>=e.getTime()}function rIe(e){return e instanceof Ji||e instanceof Go&&e.code!=="CREDENTIALS_UNAVAILABLE"}var QWe={cancelled:"Skyramp cancelled this run",expired:"this attempt passed its deadline in Skyramp",ended:"Skyramp already ended this attempt"},$We={cancelled:"attempt-cancelled",expired:"attempt-closed",ended:"attempt-closed"},TWe={cancelled:"cancelled",expired:"timed_out",ended:"agent_failed"};var _We={analyze:"analyze",triage:"analyze",recommend:"recommend",generate:"generate","generate-ui":"generate","generate-unit":"generate",adapt:"generate",write:"generate",onboard:"execute",deploy:"execute","native-run":"execute",deliver:"deliver"},DWe={analyze:"change analysis",recommend:"test recommendations",generate:"test generation",execute:"test execution",deliver:"opening a pull request with the tests"};function iIe(){return _e("skyrampAppOrigin").trim()||eIe}var NWe=10*6e4;var PWe={onboard:"onboard",deploy:"deploy"},UWe={plan:{stage:"validation_plan",text:"Working out what to validate, and bringing up what it needs"},write:{stage:"tests",text:"Writing and running the tests"},"generate-unit":{stage:"tests",text:"Writing unit tests"},"native-run":{stage:"tests",text:"Running the unit tests"}},FWe=new Set(["write","native-run"]);function sIe(){let e=ls(zo.conflict);if(!e)return;let t;try{t=C1.safeParse(JSON.parse(e))}catch(n){Ft(`Testbot V3: the saved merge conflict is not JSON (${n instanceof Error?n.message:String(n)})`);return}if(t.success)return t.data;Ft(`Testbot V3: the saved merge conflict breaks the contract (${t.error.issues.map(n=>`${n.path.join(".")}: ${n.message}`).join("; ")})`)}async function y4(){let e=ls(zo.attemptId);if(!e)return;let t=ls(zo.reportUploaded)==="true",n=ls(zo.recipeUploaded)==="true",i=ls(zo.revisionsUploaded)==="true",r=ls(zo.deadlineAt),s=ls(zo.cause)||void 0;!s&&!t&&!n&&!i&&r&&nIe(new Date(r),new Date)&&(s="timed_out");let o=$A().takeIdToken(),a=sIe(),c=await XW({attemptId:e,reportUploaded:t,recipeUploaded:n,revisionsUploaded:i,cause:s,...a?{conflict:a}:{}},tIe(iIe(),o)),u=ls(zo.recipeStatus);n&&u?ki(`Testbot V3: attempt ended; the setup ended ${u==="ready"?"Ready":"blocked (Needs input)"}.`):ki(`Testbot V3: attempt ended; the run's outcome in Skyramp is ${c.outcome??"not final yet"}.`)}var E4=require("child_process"),Yi=ce(require("fs")),I0=ce(require("path")),w0=require("string_decoder");var oIe="skyramp-testbot-state",aIe=/^\$\([^)]*\)$/;function cIe(e){for(let[t,n]of Object.entries(e))n!==void 0&&aIe.test(n)&&delete e[t]}function uIe(e){let t={},n=Yi.existsSync(e)?Yi.readFileSync(e,"utf-8"):"",i=/^([^\r\n<]+)<<(\S+)\r?\n([\s\S]*?)\r?\n\2\r?$/gm;for(let r=i.exec(n);r;r=i.exec(n))t[r[1]]=r[3];return t}function v4(e,t={}){let n=t.env??process.env;if(!_c(n))return!1;cIe(n),qW(n);let i=n.AGENT_TEMPDIRECTORY||n.RUNNER_TEMP;if(i){n.RUNNER_TEMP??=i;let o=I0.join(i,oIe);if(e==="main")Yi.writeFileSync(o,"",{mode:384});else for(let[a,c]of Object.entries(uIe(o)))n[`STATE_${a}`]=c;n.GITHUB_STATE=o;for(let[a,c]of[["GITHUB_OUTPUT","output"],["GITHUB_ENV","env"],["GITHUB_PATH","path"],["GITHUB_STEP_SUMMARY",`summary-${e}.md`]])n[a]=I0.join(i,`skyramp-testbot-${c}`),Yi.writeFileSync(n[a],"",{mode:384})}let r=t.stdout??n===process.env;r&&lIe(n,t.write);let s=n.GITHUB_STEP_SUMMARY;if(r&&s){let o=t.write??(a=>l0(a.replace(/\n$/,"")));process.once("exit",()=>{Yi.existsSync(s)&&Yi.statSync(s).size>0&&o(`${qv("task.uploadsummary",{},s)}
221
+ `)}function d4(e){let t=_A.join(e.outputsDir,"deploy.txt");if(Kv.existsSync(t)){let{deploy:i}=Bc({exitCode:0,stdout:Kv.readFileSync(t,"utf-8"),stderr:"",timedOut:!1,durationMs:0});if(i?.teardown)return{argv:["sh","-c",i.teardown],label:"deploy.json's teardown"}}let{teardownScript:n}=Dc(e.inputs.repositoryPath);if(n)return{argv:["bash",n],label:_A.join(".skyramp","sut","teardown.sh")}}function p4(e,t){return Yv(t,e.inputs.repositoryPath,{env:It()})}async function u4(e){let t=d4(e);t&&await p4(e,t)}async function Gbe(e,t){let n=t.passed?void 0:f4(e);if(!n)return;let i=await p4(e,n);return i&&`${i} (if nothing was running, a teardown must exit 0)`}function f4(e){return l4(e)?void 0:d4(e)}function zbe(e){if(f4(e))return"Testbot tore down the SUT the previous attempt started. Bring it up again from the start: run .skyramp/sut/setup.sh (or the workspace bring-up), even if something still answers. Never reuse what is running."}function qbe(e,t){let{deploy:n}=Bc(t,e.inputs.repositoryPath,e.secretValues);if(!n)return;if(n.outcome==="bringup-failed"){let r=Kn(n.bringupError?.output?.trim()??"",e.secretValues??[]);return`bring-up failed (environment) \u2014 no live app for later stages${r?`: ${r.slice(0,160)}`:""}`}if(n.outcome==="change-broke-bringup")return"this PR broke bring-up \u2014 recorded as a finding, no live app for later stages";let i=lA(e).map(r=>r.name);if(i.length)return`the shared environment's ${i.join(", ")} does not verifiably run the revision under validation \u2014 no runtime test runs against it`}var A4=c4({name:"deploy",model:"opus",timeoutMinutes:25,requires:["preflight"],softRequires:["onboard"],triageBranch:"runtime",validateInput:Nbe,prepare:Ube,scaleTimeout:Pbe,buildPrompt:Vbe,allowedTools:Dbe,buildSessionEnv:()=>({...i4}),selfVerification:["dependencies lists every backing service, true only if really deployed \u2014 a mocked one is false, never omitted.","Your final message is one JSON object matching the schema."],exitGates:[wv(),YH()],onPassed:async(e,t)=>({...ZH(e,t),...await WH(e,t)}),passReason:qbe,afterAttempt:Gbe,retryNote:zbe,onAbort:u4,teardown:u4});xn();var Mqe=20*1024*1024;var g4=ce(require("path"));var Yqe=g4.join(".skyramp","sut","get-auth-token.sh");var v0="\\$([A-Z][A-Z0-9_]{0,99})",Wqe=new RegExp(`^${v0}$`),Zqe=new RegExp(`^${v0}:${v0}$`);var DJe=3*6e4;var NJe=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;var Zbe={discover:"reading the repositories",start:"starting the components",check:"checking that the components answer"};var GJe={running:"up",healthy:"up",ready:"up",started:"up",building:"starting",pending:"starting",installing:"starting",skipped:"out_of_scope",excluded:"out_of_scope","out-of-scope":"out_of_scope"};var zJe=new RegExp(tl.source,"g");var pHe=new RegExp(tl.source,"g");var eIe="https://testbot.skyramp.dev",zo={attemptId:"v3AttemptId",deadlineAt:"v3DeadlineAt",reportUploaded:"v3ReportUploaded",recipeUploaded:"v3RecipeUploaded",recipeStatus:"v3RecipeStatus",revisionsUploaded:"v3RevisionsUploaded",cause:"v3Cause",conflict:"v3Conflict"};function tIe(e,t,n){return{origin:e,idToken:t,sourceToken:n,mask:i=>us(i),log:i=>ki(i),onTokenRefused:(i,r)=>{rIe(i)&&m4.set(r,i)},onTokenGranted:i=>{m4.delete(i)}}}var m4=new Map;var QWe=["setup_failed","checkout_failed","environment_unverified"];function nIe(e,t){return t.getTime()>=e.getTime()}function rIe(e){return e instanceof Ji||e instanceof Go&&e.code!=="CREDENTIALS_UNAVAILABLE"}var $We={cancelled:"Skyramp cancelled this run",expired:"this attempt passed its deadline in Skyramp",ended:"Skyramp already ended this attempt"},TWe={cancelled:"attempt-cancelled",expired:"attempt-closed",ended:"attempt-closed"},_We={cancelled:"cancelled",expired:"timed_out",ended:"agent_failed"};var DWe={analyze:"analyze",triage:"analyze",recommend:"recommend",generate:"generate","generate-ui":"generate","generate-unit":"generate",adapt:"generate",write:"generate",onboard:"execute",deploy:"execute","native-run":"execute",deliver:"deliver"},NWe={analyze:"change analysis",recommend:"test recommendations",generate:"test generation",execute:"test execution",deliver:"opening a pull request with the tests"};function iIe(){return _e("skyrampAppOrigin").trim()||eIe}var PWe=10*6e4;var UWe={onboard:"onboard",deploy:"deploy"},FWe={plan:{stage:"validation_plan",text:"Working out what to validate, and bringing up what it needs"},write:{stage:"tests",text:"Writing and running the tests"},"generate-unit":{stage:"tests",text:"Writing unit tests"},"native-run":{stage:"tests",text:"Running the unit tests"}},OWe=new Set(["write","native-run"]);function sIe(){let e=ls(zo.conflict);if(!e)return;let t;try{t=C1.safeParse(JSON.parse(e))}catch(n){Ft(`Testbot V3: the saved merge conflict is not JSON (${n instanceof Error?n.message:String(n)})`);return}if(t.success)return t.data;Ft(`Testbot V3: the saved merge conflict breaks the contract (${t.error.issues.map(n=>`${n.path.join(".")}: ${n.message}`).join("; ")})`)}async function y4(){let e=ls(zo.attemptId);if(!e)return;let t=ls(zo.reportUploaded)==="true",n=ls(zo.recipeUploaded)==="true",i=ls(zo.revisionsUploaded)==="true",r=ls(zo.deadlineAt),s=ls(zo.cause)||void 0;!s&&!t&&!n&&!i&&r&&nIe(new Date(r),new Date)&&(s="timed_out");let o=$A().takeIdToken(),a=sIe(),c=await XW({attemptId:e,reportUploaded:t,recipeUploaded:n,revisionsUploaded:i,cause:s,...a?{conflict:a}:{}},tIe(iIe(),o)),u=ls(zo.recipeStatus);n&&u?ki(`Testbot V3: attempt ended; the setup ended ${u==="ready"?"Ready":"blocked (Needs input)"}.`):ki(`Testbot V3: attempt ended; the run's outcome in Skyramp is ${c.outcome??"not final yet"}.`)}var E4=require("child_process"),Yi=ce(require("fs")),I0=ce(require("path")),w0=require("string_decoder");var oIe="skyramp-testbot-state",aIe=/^\$\([^)]*\)$/;function cIe(e){for(let[t,n]of Object.entries(e))n!==void 0&&aIe.test(n)&&delete e[t]}function uIe(e){let t={},n=Yi.existsSync(e)?Yi.readFileSync(e,"utf-8"):"",i=/^([^\r\n<]+)<<(\S+)\r?\n([\s\S]*?)\r?\n\2\r?$/gm;for(let r=i.exec(n);r;r=i.exec(n))t[r[1]]=r[3];return t}function v4(e,t={}){let n=t.env??process.env;if(!_c(n))return!1;cIe(n),qW(n);let i=n.AGENT_TEMPDIRECTORY||n.RUNNER_TEMP;if(i){n.RUNNER_TEMP??=i;let o=I0.join(i,oIe);if(e==="main")Yi.writeFileSync(o,"",{mode:384});else for(let[a,c]of Object.entries(uIe(o)))n[`STATE_${a}`]=c;n.GITHUB_STATE=o;for(let[a,c]of[["GITHUB_OUTPUT","output"],["GITHUB_ENV","env"],["GITHUB_PATH","path"],["GITHUB_STEP_SUMMARY",`summary-${e}.md`]])n[a]=I0.join(i,`skyramp-testbot-${c}`),Yi.writeFileSync(n[a],"",{mode:384})}let r=t.stdout??n===process.env;r&&lIe(n,t.write);let s=n.GITHUB_STEP_SUMMARY;if(r&&s){let o=t.write??(a=>l0(a.replace(/\n$/,"")));process.once("exit",()=>{Yi.existsSync(s)&&Yi.statSync(s).size>0&&o(`${qv("task.uploadsummary",{},s)}
222
222
  `)})}return!0}function lIe(e,t){let n=process.stdout.write.bind(process.stdout),i=o=>e[RA]==="1"?u0(o,e):void n(o.command!==void 0?`${o.command}
223
223
  `:o.text??""),r=t??(o=>i({command:o.replace(/\n$/,"")})),s=t??(o=>i({text:o}));process.stdout.write=((o,...a)=>{let c=typeof o=="string"?o:Buffer.from(o).toString("utf-8"),u="";for(let p of c.split(/(?<=\n)/)){let A=p.startsWith("::")?OW(p):void 0;if(!A){u+=p;continue}u&&s(u),u="";for(let h of A)r(`${h}
224
224
  `)}return u&&s(u),a.find(p=>typeof p=="function")?.(),!0})}var dIe=64*1024;function b0(e){let t=new w0.StringDecoder("utf8"),n="",i=r=>e(zv(r));return{push(r){n+=typeof r=="string"?r:t.write(r);let s=n.lastIndexOf(`