@skyramp/testbot-core 0.13.0-v3.376 → 0.13.0-v3.378
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/VERSION.json +1 -1
- package/dist/main.js +474 -464
- package/dist/post.js +10 -10
- package/dist/runner-client.cjs +8 -8
- package/package.json +1 -1
package/dist/runner-client.cjs
CHANGED
|
@@ -155,8 +155,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
155
155
|
set -euo pipefail
|
|
156
156
|
${i}
|
|
157
157
|
`,{mode:493})}catch{return}return`bash ${Dx(t)}`}}o(Tx,"scriptedCommand");function Dx(e){return`'${e.split("'").join("'\\''")}'`}o(Dx,"shQuote");function _x(e){return Nx(e)&&xR(e).length===0&&TR(e.inputs?.sharedEnvironment).length===0}o(_x,"sutIsHealthy");function Nx(e){let t=Vde(e);if(!t&&e.state.stages.deploy?.status!=="passed")return!1;let n=ze(e,"deploy.json");return n?jde(n):!t}o(Nx,"sutCameUp");function jde(e){return e?.outcome==="clean"||e?.outcome==="recipe-drift"}o(jde,"deployCameUp");function Vde(e){let t=e.state.stages.plan,n=e.state.stages.deploy;return!(e.inputs?.pipeline?e.inputs.pipeline==="two-step":!n)||t?.status!=="passed"?!1:!n||n.updatedAt<=t.updatedAt}o(Vde,"broughtUpByPlan");var V0e=10*6e4;var oy=(r=>(r.RestApi="rest-api",r.Frontend="frontend",r.FullStack="full-stack",r.Other="other",r))(oy||{}),da=(r=>(r.Critical="critical",r.High="high",r.Medium="medium",r.Low="low",r))(da||{}),Aa=(i=>(i.Suspected="suspected",i.Latent="latent",i.Refuted="refuted",i))(Aa||{}),Px=(i=>(i.Skyramp="skyramp",i.External="external",i.Unknown="unknown",i))(Px||{}),Mx=(r=>(r.Cascade="cascade",r.Restrict="restrict",r.Orphan="orphan",r.Unknown="unknown",r))(Mx||{}),fi=(r=>(r.RequirementReference="requirement-reference",r.Spec="spec",r.PrDescription="pr-description",r.CouldBreak="could-break",r))(fi||{}),et=d.string().trim().min(1),Iu=et.describe("file:line"),Wz=o(e=>et.refine(t=>t.length<=400,t=>({message:`is ${t.length} characters, over the 400 cap \u2014 ${e}`})),"cap400"),TA=et.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'),Fx=d.object({method:et,path:et,service:d.string().optional(),evidence:Iu,repository:TA}),Yde=d.object({id:et.describe("short-slug, e.g. R9"),statement:et.max(400,"exceeds 400 characters \u2014 state the requirement, do not paste the spec section").describe("a testable obligation, not a summary"),source:d.nativeEnum(fi).describe("spec outranks pr-description when both state it"),evidence:et.describe("spec: file:line or a section locator. pr-description: the quoted phrase it comes from.")}),Wde=d.object({id:et.describe("short-slug"),statement:et.max(400,"exceeds 400 characters \u2014 state the behaviour, do not paste the code").describe("what the change makes true"),surface:et.describe("METHOD /path, or a component/page name"),evidence:et.describe("file:line from the diff that introduces it"),repository:TA,satisfies:d.array(et).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)")}),Zde=d.object({id:et.describe("short-slug"),file:et,line:d.number().optional(),claim:Wz("shorten it to the one sentence that states the defect, and move the supporting detail into `evidence`"),severity:d.nativeEnum(da),evidence:Wz("cite the file:line and the one line that shows it, rather than reproducing the surrounding code").describe("quoted diff/code line"),status:d.nativeEnum(Aa),repository:TA,conflictsWith:d.array(et).optional().describe("requirement ids (from `requirements`) this defect contradicts or leaves unimplemented \u2014 a lower-precedence source (the diff, or the PR description) lost")}),Kde=d.object({name:et,language:d.string().optional(),framework:d.string().optional(),evidence:Iu,repository:TA}),Xde=d.object({dir:et,framework:d.string().optional(),kind:d.nativeEnum(Px),evidence:Iu,repository:TA}),eAe=d.object({from:et,to:et,onDelete:d.nativeEnum(Mx),evidence:Iu}),tAe=d.object({entity:et,field:et,values:d.array(d.string()),evidence:Iu}),nAe=d.object({entities:d.array(d.object({name:et,evidence:Iu})),references:d.array(eAe).describe("INBOUND references \u2014 what still points at an entity when it is deleted"),stateFields:d.array(tAe)}),Ox=d.object({schemaVersion:d.literal(1),repository:d.object({path:et.describe("absolute repo path"),currentBranch:et,baseBranch:et}),project:d.object({type:d.nativeEnum(oy),primaryLanguage:et,languages:d.array(d.string()),frameworks:d.array(d.string())}),services:d.array(Kde),infrastructure:d.object({containerized:d.boolean(),hasDockerCompose:d.boolean(),composeFiles:d.array(d.string()),hasCiCd:d.boolean()}),diff:d.object({changedFiles:d.array(d.string()).describe("as git reports them; a file in another checkout may carry that repo's name"),nonApplicationOnly:d.boolean(),summary:et.describe("\u2264400 chars")}),endpoints:d.object({new:d.array(Fx),modified:d.array(Fx),removed:d.array(Fx)}),existingTests:d.object({locations:d.array(Xde)}),entityMap:nAe,requirements:d.array(Yde).describe("from a spec (attached or linked) and/or the PR description; empty when neither states a testable obligation"),behaviors:d.array(Wde),findings:d.array(Zde),unexamined:d.array(d.string()).describe("files or areas outside this change you did not open"),summary:et.describe("one paragraph on what this change does and its test-relevant risk")});var oAe=d.object({route:d.string().describe('the page this step happens on, e.g. "/products/:id"'),action:d.string().describe('what the user does there, through the UI, e.g. "clicks Add to cart"'),clauses:d.array(d.string()).optional().describe("the plan clause ids this step exercises"),check:d.string().optional().describe("what the user then sees that shows the step worked; the test asserts it")}),DA=(n=>(n.InProcess="in-process",n.Browser="browser",n))(DA||{}),Zz=(i=>(i.Spec="spec",i.PrDescription="pr-description",i.Inferred="inferred",i))(Zz||{}),Kz=d.object({id:d.string().describe('e.g. "J1"'),name:d.string().describe(`the flow in a user's words, e.g. "buy a product with a coupon"`),entry:d.string().describe("the route the user starts the flow on: the app's normal starting page for it, never a deep link into its middle"),steps:d.array(oAe).describe("every step, in order, from the entry page to the outcome: at least two"),outcome:d.string().describe("what the user sees at the end that shows the flow worked: every part of it"),finishes:d.string().optional().describe('the user action that completes the task, verb first, e.g. "places the order"; the journey walks on to it'),kind:d.nativeEnum(DA).optional().describe("in-process when the repo's in-process tests (components, app routes) can walk the whole flow and check it; else browser"),source:d.nativeEnum(Zz).optional().describe("spec or pr-description when one describes this flow (quote it under evidence), else inferred"),evidence:d.string().optional().describe("for spec or pr-description: its words that describe the flow"),testFile:d.string().describe("the browser test file it goes in, beside the repo's existing e2e tests")}),ay=d.object({journey:d.string().describe("the plan's journey id"),file:d.string().describe("the browser test file that walks it"),brokeAt:d.object({step:d.number().int().describe("the 1-based step whose check failed first"),expected:d.string(),actual:d.string().describe("what the app did instead, from the runner's output"),notReached:d.array(d.number().int()).optional().describe("later steps the test could not get to")}).optional().describe("only when the journey's test failed on a check: where"),test:d.string().describe("the title of the one test in that file that walks it end to end")});var rTe=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 iTe=["stale_test","open_question"],sTe=["low","medium","high","critical"];var Xz=String.raw`(?:\[[^\]]*\]|\([^)]*\))`,aAe=String.raw`(?:["'\u201c\u2018\x60]|\*{1,2})?[^\s:"'\u201c\u201d\u2018\u2019\x60*()[\],]+(?:["'\u201d\u2019\x60]|\*{1,2})?`,e2=String.raw`(?:${Xz}|${aAe}(?:\s*${Xz})?)`,t2=String.raw`(?:\s*:|\s+[\u2014\u2013-])`,uTe=new RegExp(String.raw`^\s*(?:${e2}(?:,\s*${e2})*(?::L?\d+(?:[-\u2013]\d+)?${t2}?|${t2})|\[[^\]\s]+\]|\([^)\s]+\))\s+`);var Ls=Se(require("fs")),vu=Se(require("path")),s2=require("child_process");var sn="{junit}",cy=(r=>(r.Junit="junit",r.Trx="trx",r.GoTestJson="go-test-json",r.JestJson="jest-json",r))(cy||{}),Lx=(t=>(t.Minitest="minitest",t))(Lx||{}),n2=d.string().trim().min(1),Cu=d.object({cwd:n2.describe('repo-relative directory the command starts in ("." for the root)'),argv:d.array(n2).min(1).describe(`the command as separate arguments, run without a shell; for a junit or trx report an argument or env value holds ${sn}, where the report is written (not for Maven or Gradle, whose build writes its own)`),env:d.record(d.string(),d.string()).optional().describe("plain test or reporter settings beyond the repository's CI test job (RAILS_ENV=test, PLAYWRIGHT_JUNIT_OUTPUT_FILE={junit}); never a credential, PATH, or a tool's install path"),report:d.object({format:d.nativeEnum(cy).describe(`junit (JUnit XML to ${sn}), trx (to ${sn}), jest-json (Jest's --json or Vitest's --reporter=json, --outputFile=${sn}), or go-test-json (go test -json on the command's output)`),reporter:d.nativeEnum(Lx).optional().describe("a reporter Testbot loads for a runner that writes no report: minitest")}).optional().describe("the report the command writes; junit when omitted")});var bu="a framework other than pytest, jest, vitest and node --test (go test, rails test, mvn, dotnet test), or one the repository's test script runs through another command (ng test, nx test)",fTe=`pytest, Jest, Vitest and node --test tests run as the run already knows them, unless the repository's test script runs them through another command (ng test, nx test), which may be the only one that compiles them. A test in any other framework, or one run that way, also gives "run": the repository's own command for only those tests, from the directory the repository runs it in, as separate arguments without a shell. Its "report" says what the runner writes: junit (JUnit XML to ${sn} in the reporter's argument or env setting), trx (a TRX file to ${sn}, which every dotnet test writes with its built-in logger), jest-json (Jest's --json --outputFile=${sn}, or Vitest's --reporter=json --outputFile=${sn}: built in, no reporter package), or go-test-json (go test -json, read from the command's output). A Maven or Gradle command names no ${sn}: its build writes JUnit XML to its own report directory, which the run reads. Use a reporter the repository already has, or one of those; a reporter or converter the command fetches is the version the repository pins, or else its latest release (an older one may not build with the repository's toolchain). For minitest, which writes none, give report.reporter "minitest" and the run fills ${sn} itself. A setting the tests or reporter read goes in "env" (RAILS_ENV=test, or PLAYWRIGHT_JUNIT_OUTPUT_FILE=${sn} with playwright test --reporter=junit): the run sets it, so never wrap the command in a shell to set one. The run replaces ${sn} in argv and env with its report path, executes the command, and reads that report.`;var Os=(r=>(r.ExistingEvidenceSufficient="existing_evidence_sufficient",r.TargetedUnit="targeted_unit",r.RuntimeRequired="runtime_required",r.BlockedPreflight="blocked_preflight",r))(Os||{}),qi=(s=>(s.ExistingEvidence="existing_evidence",s.Unaffected="unaffected",s.ExistingUnit="existing_unit",s.NewUnit="new_unit",s.Runtime="runtime",s))(qi||{}),jx=(n=>(n.Repository="repository",n.Testbot="testbot",n))(jx||{}),Vx=(i=>(i.Identified="identified",i.Passed="passed",i.Failed="failed",i))(Vx||{}),Fn=d.string().trim().min(1),cAe=d.string().regex(/^[a-z0-9][a-z0-9-]*$/,"must be a short lowercase slug").describe("short-slug");var uAe=d.object({id:cAe,source:d.nativeEnum(jx),kind:d.nativeEnum(Cs),outcome:d.nativeEnum(Vx),summary:Fn.max(400).describe("one line: what it shows"),tests:d.array(Fn).optional().describe("source repository: the existing tests, as repo-relative paths, optionally path::test-name"),repository:Fn.optional().describe("source repository: owner/repo the tests live in, when the run has several checkouts; omit for the working checkout"),command:Fn.optional().describe("source testbot: the exact command you ran, as you ran it"),run:Cu.optional().describe(`source repository, for tests in ${bu}: how the run executes the whole of each of these test files, all of them in one command, never narrowed to the named tests and never only listed, with the repository's own runner writing JUnit XML to {junit}. A test is credited to a file only by its name or by a report that names the file`)}),lAe=d.object({behaviorId:Fn.describe("an id from analyze's behaviors"),mechanism:d.nativeEnum(qi),evidenceIds:d.array(Fn).default([]).describe("existing_evidence: the ci-<n> or evidence ids that establish it; existing_unit: the evidence id naming the tests to run"),covers:d.string().trim().optional().describe('new_unit / runtime: the missing evidence this obtains, e.g. "the boundary the change moved"; unaffected: why the change cannot reach it, citing path:line')}),Gx=(i=>(i.Browser="browser",i.RunningApp="running-app",i.Outside="outside",i))(Gx||{}),dAe=d.object({behaviorId:d.string().trim().optional().describe("an id from analyze's behaviors, when it is about one"),missing:Fn.max(600).describe("the evidence that is required and cannot be obtained in this run"),needs:d.nativeEnum(Gx).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)")}),AAe=d.object({file:Fn.describe("the changed file the failure is in"),repository:Fn.optional().describe("owner/repo the file is in, when the run has several checkouts; omit for the working checkout"),reason:Fn.max(300).describe("what prerequisite the change fails"),evidence:Fn.max(400).describe("the error line, quoted")}),pAe=d.object({behaviorId:Fn.describe("an id from analyze's behaviors"),reason:Fn.max(600).describe("\u2264600 characters: why this change leaves the behavior's result as it was, citing the unchanged line that decides it (path:line)")}),_A=d.object({schemaVersion:d.literal(1),decision:d.nativeEnum(Os),evidence:d.array(uAe).describe("evidence this session found or produced; CI results are the ci-<n> items and are not restated here"),plan:d.array(lAe).describe("how each changed behavior's evidence is obtained"),gaps:d.array(dAe),outOfScope:d.array(pAe).optional().describe("behaviors analyze found that this change neither changes nor states"),blocked:AAe.optional().describe("only for blocked_preflight"),rationale:Fn.max(1200).describe("\u22641200 characters: why this evidence is enough, or what it still lacks \u2014 the scope you chose and why")});function NA(e){let t=ze(e,"recommend.json");if(!t||!Array.isArray(t.generate)||!Array.isArray(t.maintenance))return;let n=t;return{...n,maintenance:n.maintenance.map(({repository:i,...r})=>({...r,test:r.test.trim().replace(/^\.\//,""),...i?.trim()?{repository:i.trim()}:{}}))}}o(NA,"readRecommend");function mAe(e){return mn(Qb,e).errors}o(mAe,"validateGenerateOutput");function yAe(e,t=[]){let{value:n,error:i}=$t(e,t);if(i)return{errors:[i]};let r=mAe(n);return r.length>0?{errors:r}:{generate:n,errors:[]}}o(yAe,"parseGenerateText");function uy(e,t=[]){return yAe(e.stdout,t)}o(uy,"parseGenerateFromSession");function EAe(e){return e.generate.filter(t=>t.type!=="ui").map(t=>t.id)}o(EAe,"backendCases");function o2(e){return e.generate.filter(t=>t.type==="ui").map(t=>t.id)}o(o2,"uiCases");var ly={backend:{stage:"generate",cases:EAe,noRecommendCoverage:"recommend.json missing or malformed \u2014 cannot check coverage",noRecommendIntent:"recommend.json missing or malformed \u2014 cannot check intent",uncovered:o(e=>`recommend case "${e}" is not covered by any generated test`,"uncovered"),unknownCovered:o(e=>`test covers unknown recommend id "${e}"`,"unknownCovered"),unasserted:o(e=>`case "${e}" has no verified assertion enforcing its expected_observable`,"unasserted"),usedCodegen:V1,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:o2,noRecommendCoverage:"recommend.json not found \u2014 cannot check UI coverage",noRecommendIntent:"recommend.json not found \u2014 cannot check UI intent",uncovered:o(e=>`UI case "${e}" is not covered by any generated UI test`,"uncovered"),unknownCovered:o(e=>`test covers "${e}" which is not a recommend UI case`,"unknownCovered"),unasserted:o(e=>`UI case "${e}" has no verified assertion enforcing its expected_observable`,"unasserted"),usedCodegen:G1,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."}},YTe=$n("generate-schema",(e,t)=>uy(t,e.secretValues));function IAe(e){let t=ly[e];return{name:`${t.stage}-coverage`,verify(n,i){let{generate:r,errors:s}=uy(i,n.secretValues);if(!r)return Lt(this.name,s);let a=NA(n);if(!a)return Lt(this.name,[t.noRecommendCoverage]);let c=new Set(r.tests.flatMap(p=>p.covers)),u=[],l=t.cases(a);for(let p of l)c.has(p)||u.push(t.uncovered(p));let A=new Set(e==="ui"?l:a.generate.map(p=>p.id));for(let p of c)A.has(p)||u.push(t.unknownCovered(p));if(e==="backend"){let p=new Set(r.deferredUi),g=new Set(o2(a));for(let h of g)!p.has(h)&&!c.has(h)&&u.push(`UI case "${h}" is neither covered nor deferred to the UI stage`);for(let h of p)g.has(h)||u.push(`deferredUi lists "${h}" which is not a UI case`)}return u.length===0?{name:this.name,passed:!0}:Lt(this.name,u)}}}o(IAe,"generateCoverageGateFor");function CAe(e){let t=ly[e];return{name:`${t.stage}-intent`,verify(n,i){let{generate:r,errors:s}=uy(i,n.secretValues);if(!r)return Lt(this.name,s);let a=NA(n);if(!a)return Lt(this.name,[t.noRecommendIntent]);let{asserted:c,errors:u,badFiles:l}=QAe(r,n.inputs.repositoryPath),A=u.length;for(let g of t.cases(a))c.has(g)||u.push(t.unasserted(g));if(u.length===0)return{name:this.name,passed:!0};let p=Lt(this.name,u);return A>0&&A===u.length&&l.size>0?{...p,droppable:[...l]}:p}}}o(CAe,"generateIntentGateFor");function bAe(e){let t=ly[e];return n=>{if(!n.inputs.skyrampMcp?.command||e==="backend"&&!_x(n))return;let i=vu.join(n.outputsDir,`${t.stage}-stream.ndjson`);if(!(!Ls.existsSync(i)||t.usedCodegen(i)))return z1(i)?t.codegenHint:"Skyramp codegen tools were configured but the MCP server did not connect this session, so they were not available. Hand-authoring was the only option; this is an environment problem, not yours."}}o(bAe,"codegenRetryHintFor");var WTe=IAe("backend"),ZTe=CAe("backend"),KTe=bAe("backend");var r2=o(e=>e.replace(/\s+/g,""),"squeeze");var zx={python:[/\bassert\s*[({\w"'`]/g,/\bpytest\.raises\s*\(/g,/\bself\.assert\w*\s*\(/g],typescript:[/\bexpect\s*\(/g,/\.should\b/g,/\bassert\s*[.(]/g],go:[/\bt\.(Error|Errorf|Fatal|Fatalf|Fail|FailNow)\s*\(/g,/\b(assert|require)\.\w+\s*\(/g],java:[/\bassert\w*\s*\(/g,/\bassertThat\s*\(/g],ruby:[/\bexpect\s*[({]/g,/\bassert\w*\b/g,/\.should\b/g]};for(let[e,t]of[["javascript","typescript"],["kotlin","java"]])zx[e]=zx[t];function vAe(e,t){if(e.includes(pd(t))||r2(e).includes(r2(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(pd(i)))?!0:SAe(e,t)}o(vAe,"evidenceFound");var wAe=/\bassert\w*\b|\bexpect\s*\(|\.should\b|\brequire\s*\(/i,BAe=12,kAe=/,\s*\(\s*#|,\s*f?["'`]|\s+#\s|\s+\/\/|\s*\((?:line|lines|at line)\b|\s*,\s*$/i;function SAe(e,t){let n=t.split(/\s*;\s*|\s*\.\.\.\s*|\r?\n/),i=0;for(let r of n){let s=wAe.exec(r);if(!s)continue;let a=r.slice(s.index),c=kAe.exec(a);if(c&&(a=a.slice(0,c.index)),a=pd(a).replace(/[,\s]+$/,""),a.length<BAe||!e.includes(a))return!1;i++}return i>0}o(SAe,"annotatedAssertionFound");function QAe(e,t){let n=new Set,i=[],r=new Set;for(let s of e.tests){let a=vu.resolve(t,s.file);if(!Ls.existsSync(a))continue;let c=pd(Ls.readFileSync(a,"utf-8"));for(let u of s.assertions??[]){if(!vAe(c,u.evidence)){i.push(`assertion evidence for "${u.case}" not found in ${s.file} \u2014 cite the real assertion line`),r.add(s.file);continue}s.covers.includes(u.case)?n.add(u.case):(i.push(`assertion cites case "${u.case}" not in that test's covers[]`),r.add(s.file))}}return{asserted:n,errors:i,badFiles:r}}o(QAe,"verifiedAssertions");var RAe=/\.(spec|test)\.[cm]?[jt]sx?$/i;function a2(e){let t;try{t=(0,s2.execFileSync)("git",[...Ri,"status","--porcelain","--untracked-files=all"],{env:Xt(),cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]})}catch{return}let n=o(r=>/_scaffold/i.test(r)||fd.test(r),"isTestLitter"),i=[];for(let r of t.split(`
|
|
158
|
-
`)){if(!r.trim()||r.length>1&&r[1]==="D")continue;let s=r.slice(3).trim(),a=s.indexOf(" -> ");if(a!==-1&&(s=s.slice(a+4).trim()),s=s.replace(/^"|"$/g,""),!s)continue;let c=s.replace(/^\.\//,"");c.startsWith(".skyramp/")||!n(c)||i.push(c)}return i}o(a2,"testLitter");function xAe(e){let t=ly[e],n=e==="ui";return{name:`${t.stage}-no-litter`,verify(i){let r=a2(i.inputs.repositoryPath);if(r===void 0)return{name:this.name,passed:!0};let s=r.filter(a=>RAe.test(a)===n);return s.length===0?{name:this.name,passed:!0}:Lt(this.name,[`${t.stage} left files outside .skyramp/ \u2014 move the staged test into .skyramp/staged/ and delete any codegen draft (e.g. *_scaffold.*): ${s.slice(0,6).join(", ")}`])}}}o(xAe,"noLitterGateFor");var XTe=xAe("backend");var DAe="write-stale-updates",_Ae={[DAe]:"stale test updates"};var UA=Se(require("fs")),pa=Se(require("path"));function d2(e,t=!1){return mn(HM(t),e).errors}o(d2,"validateAdaptOutput");function FAe(e,t=[],n=!1){let{value:i,error:r}=$t(e,t);if(r)return{errors:[r]};let s=d2(i,n);return s.length>0?{errors:s}:{adapt:i,errors:[]}}o(FAe,"parseAdaptText");var PAe="adapt-scratch",u2=`${PAe}/adapt-result.json`;function A2(e,t){let n=pa.join(e.outputsDir,u2),i;try{i=UA.readFileSync(n,"utf-8")}catch{i=void 0}if(i!==void 0&&(e.secretValues??[]).some(c=>i.includes(c)))return{errors:[`${u2} contains a secret value (token / credential) \u2014 never write it anywhere`]};let r=gd(e.inputs?.sharedEnvironment).length>0,s=FAe(t.stdout,e.secretValues,r);if(s.adapt)return s;let a=i!==void 0?jo(n):void 0;return a!==void 0&&d2(a,r).length===0?{adapt:a,errors:[]}:s}o(A2,"parseAdaptFromSession");var xDe=$n("adapt-schema",A2);var p2=require("child_process");function qx(e){return MAe(e)??[]}o(qx,"statusEntries");function MAe(e){let t;try{t=(0,p2.execFileSync)("git",[...Ri,"status","--porcelain","-z","--untracked-files=all"],{env:Xt(),cwd:e,encoding:"utf-8",maxBuffer:16*1024*1024})}catch{return}let n=t.split("\0"),i=[];for(let r=0;r<n.length;r++){let s=n[r];if(s.length<4)continue;let a=s.slice(0,2);i.push({code:a,path:s.slice(3)}),(a[0]==="R"||a[0]==="C")&&r++}return i}o(MAe,"readStatusEntries");var ODe=2*1024*1024;var dy=d.string().trim().min(1),OAe=d.object({cwd:dy.describe(`directory the command starts in, relative to the test's checkout ("." for its root)`),argv:d.array(dy).min(1).describe("the command as separate arguments, run without a shell"),env:d.record(d.string(),d.string()).optional().describe("plain settings the listing needs beyond the CI step's own; never a credential or PATH")}),LAe=d.object({file:dy.describe("a file of the test's checkout, relative to its root"),line:dy.describe("a line of that file, quoted exactly from where its command starts to its end")}),f2=d.object({collected:d.boolean().describe("whether the repo's CI runs this test as it is"),steps:d.array(LAe).optional().describe("when collected: the line in a CI file that starts the tests, then each line it runs on the way to the test runner"),runner:d.string().optional().describe("when collected: the test runner the last of those lines starts, by the name that line and the list command both use"),list:OAe.optional().describe("when collected: a command that lists the tests that runner collects without running them; Testbot runs it, and its output must name this file"),why:d.string().optional().describe("when not collected: why the repo's CI will not run it")});var ce=d.string().trim().min(1),JAe=o(e=>{if(!e||typeof e!="object")return e;let t=e;return typeof t.skip=="string"&&t.skip.trim()&&(t.expected===void 0||t.expected===null)?{...t,expected:"(not tested)"}:e},"skippedNeedsNoExpected"),HAe=d.preprocess(JAe,d.object({id:ce.describe(`its requirement's id plus a letter, e.g. "R1a", "AC-3a"`),clause:ce.describe("one testable part of the requirement"),expected:ce.describe("the outcome the requirement calls for \u2014 taken from the requirement, never from what the code does"),skip:d.string().optional().describe("only when no test can check this clause here: why"),type:d.nativeEnum(ji).optional().describe("the test that checks this clause: contract / integration (the API, or code called directly in-process: a function, hook or module) or ui (a page)"),target:d.string().optional().describe('its "METHOD /path", or the page / flow'),steps:d.string().optional().describe("what that test does; its expected outcome is this clause's"),finding:d.string().optional().describe("the finding id, when this clause's test also catches that defect (the defect still gets a case of its own)"),code:d.string().optional().describe("path:line of the code that decides this clause, when there is one; in another repo of the change, that repo's directory name then its path"),stated:d.string().optional().describe("the description's or spec's own words that state this clause, copied exactly, when they do"),mutates:d.boolean().optional().describe("true when its test changes state, in the test or its setup: an API POST, PUT, PATCH or DELETE, or a UI flow that submits, creates, edits or deletes"),browserOnly:d.boolean().optional().describe("true when its behaviour happens only in a browser: real clicks or keys driving page script, client-side sorting or filtering, script-driven DOM updates, focus, drag-and-drop, navigation, rendering that depends on CSS or JavaScript"),browserHarness:d.string().optional().describe("browserOnly, off the runtime path: the path of the repo's in-process browser suite its test goes in (e.g. a Django StaticLiveServerTestCase test that drives Selenium)"),quote:d.string().optional().describe("the words of the spec, plan, ticket, PR description or a test the change adds or edits that state this clause, copied exactly; a file of the repository: its path:line first. Leave it out when no source states it"),inferred:d.boolean().optional().describe("leave it out: Testbot sets it when no source states this clause (contracts/clause-grounding.ts)")})),h2=d.object({spec:d.string().optional().describe("file:line of a spec in the repository"),prDescription:d.boolean().optional().describe("or true when a pull request description says otherwise"),reference:d.string().optional().describe("or the key of an item the run was given, as listed"),says:ce.describe("what it says there, in its own words, copied exactly"),criterion:d.number().int().positive().optional().describe("an item's only: leave it out; Testbot numbers it")}).refine(e=>[!!e.prDescription,!!e.spec?.trim(),!!e.reference?.trim()].filter(Boolean).length===1,{message:`names no source, or more than one: give "spec" its file:line or "reference" an item's key, or set "prDescription", one of them; list each source as its own entry`}),YAe=d.object({id:ce.describe('the label its source gives it ("AC-3", "REQ-12"; item 4 of a numbered list is "R4"), else "R1", "R2"\u2026 in order'),statement:ce,source:d.nativeEnum(fi).describe("requirement-reference (an item the run was given), spec, pr-description (also for what the change is evidently meant to do when nothing is written down), or could-break (what the change could break that no requirement mentions)"),reference:d.string().optional().describe('requirement-reference only: the key of its item as listed, e.g. "PAY-184", or a Confluence page id such as "3021"'),evidence:ce.describe("where it is stated: for requirement-reference, the item's own words, copied exactly; else file:line, a doc section, or the quoted phrase"),criterion:d.number().int().positive().optional().describe("requirement-reference only: leave it out; Testbot numbers each criterion by the item's own label (AC2, 2.), else after the item's labels"),alsoFrom:d.array(d.object({reference:ce.regex(Is).describe("the key of another uploaded document stating the same obligation"),says:ce.describe("that document's own words, copied exactly; never infer equivalence from a shared criterion number"),criterion:d.number().int().positive().optional().describe("leave out; Testbot grounds and numbers this source separately")})).optional().describe("equivalent uploaded source criteria sharing this requirement's planned cases; retain every source with its own quote. Different conditions or boundaries need distinct requirements"),notInChange:d.string().optional().describe("requirement-reference only: when the change does not touch this criterion at all (e.g. a later step of a staged rollout), why; give it no clauses"),unchanged:d.boolean().optional().describe("true when it asks only that behaviour stay as it was (an update or refactor that must not change how something works), whatever its source"),overrules:d.array(h2).optional().describe("requirement-reference only: each lower-ranked source that says otherwise, a spec in the repository, a PR description or another item; this requirement wins, so test what it says"),clauses:d.array(HAe)}),m2=(r=>(r.ServerError="server-error",r.DataLost="data-lost",r.FinalState="final-state",r.DerivedValues="derived-values",r))(m2||{}),WAe=d.object({id:ce.describe('e.g. "F1"'),file:ce,line:d.number().optional(),claim:ce.describe("the defect, in one sentence"),severity:d.nativeEnum(da),evidence:ce.describe("the code line, or the probe request and response, that shows it"),conflictsWith:d.array(ce).optional().describe("requirement or clause ids it violates"),keeps:d.string().optional().describe("for a defect no requirement or clause states: path:line of the code beside the change that keeps the rule it breaks"),rule:d.nativeEnum(m2).optional().describe("for a defect that breaks a rule every app keeps, which nothing needs to state: which one"),existing:d.string().optional().describe("only when the base already does this, in code the change left as it was, and the change does not say it fixes it: where the base does it (its file:line); such a defect gets no case"),needsApp:d.enum(["browser","live-api"]).optional().describe("only when the running app alone can show this defect and the repo has no in-process test that can: browser (page script, what the user sees after a click or a save) or live-api (code the repo tests only against the running app's API)")}),ZAe=d.object({id:ce.describe('e.g. "Q1"'),question:ce.describe("what is unsettled, as a question the PR author can answer"),readings:d.array(ce).min(2).describe("each reasonable behaviour, with what points to it (file:line, or the words that suggest it)"),about:d.string().optional().describe("the requirement or clause id it is about, when there is one"),sources:d.array(h2).optional().describe("when sources of the same rank disagree on it: each of them")}),KAe=d.object({id:ce.describe('unique, a short kebab-case name for what the case checks, e.g. "ship-twice-409"'),type:d.nativeEnum(ji).describe("contract / integration: checks the API, or calls code directly in-process (a function, hook or module); ui: checks what a user sees or does on a page"),target:ce.describe('"METHOD /path", or the page / flow'),clause:d.string().optional().describe("the clause id this case checks"),finding:d.string().optional().describe("the finding id this case catches"),steps:ce.describe("what the test does"),expected:ce.describe("the expected outcome, from the clause"),mutates:d.boolean().optional().describe("true when its test changes state, in the test or its setup: an API POST, PUT, PATCH or DELETE, or a UI flow that submits, creates, edits or deletes")}),XAe=d.object({test:ce.describe("existing test file"),action:d.nativeEnum(Ai),reason:ce,mutates:d.boolean().optional().describe("true when the maintained test changes state"),clauses:d.array(ce).optional().describe("the clause ids this test checks"),staleOnBase:d.boolean().optional().describe("true when the test's own expectation was already wrong before this change: it fails the same way on the base branch, where the app does what it should. Not one the base app's own bug fails (that is an existing defect). It is verify, never update: re-run as it is, its failure the test's own. A delete the change justifies stays a delete")}),g2=d.array(vb).optional(),epe=d.object({components:d.preprocess(e=>g2.safeParse(e).success?e:void 0,g2).describe("when saving a new or changed recipe: every app and backing service actually brought up, its source repository, and whether it is healthy"),outcome:d.nativeEnum(ri).describe("clean | recipe-drift (you had to fix the recipe) | change-broke-bringup (this PR broke start-up) | bringup-failed (the environment, not the PR)"),baseUrls:d.record(d.string()).optional().describe("service \u2192 base URL of the running app"),health:d.object({url:d.string().optional(),command:d.string().optional(),output:d.string().optional()}).optional().describe("the check that shows the app serves real data, and what it returned"),teardown:d.string().optional().describe("command that stops the app"),dependencies:d.record(d.boolean()).optional().describe("every backing service: true = really running, false = mocked"),recipeFixes:d.array(d.string()).optional().describe("what you changed in the recipe"),error:d.string().optional().describe("when it did not come up: the failing command and what it printed"),suspectFiles:d.array(d.string()).optional().describe("change-broke-bringup: the changed files to blame"),missingSecrets:d.array(d.string().regex(Yl)).optional().describe("bringup-failed only: each secret, key, token or password the app cannot start without that this run has no value for, by its environment variable name; never a value"),login:d.object({username:ce,password:d.string()}).optional().describe("the account the tests sign in as, when they sign in: each a literal value the recipe seeds, or $VARIABLE when a secret in the environment holds it"),revisions:kb.optional()}),v_e=d.object({schemaVersion:d.literal(1),requirements:d.array(YAe),findings:d.array(WAe),cases:d.array(KAe).describe("a second test for a clause, and one case per finding that fails on this branch"),questions:d.array(ZAe).optional().describe("behaviours the change leaves unsettled; no case asserts any of them"),maintenance:d.array(XAe),journeys:d.array(Kz).optional().describe("the user journeys that, together, pass through everything the change alters that a user sees or does; empty when it alters nothing a user sees"),notInJourney:d.array(d.object({clause:ce,why:ce})).optional().describe("a clause a user sees or does that no journey walks, and why: none can reach it through the UI, or it is downstream of this change and not walked here"),unplannedComponents:d.array(d.object({components:d.array(ce).min(1).describe("changed components, as the change lists them"),why:ce})).optional().describe("changed components no clause reaches, and why their change needs no test; several may share one reason"),triage:_A.optional().describe("the validation triage decision, made before the app is started; its behaviorIds are clause ids"),app:epe.optional().describe("omit when no app was needed or none was started"),summary:ce.describe("one paragraph: what the change does and where the risk is")});var FA=(n=>(n.Backend="backend",n.Ui="ui",n))(FA||{});var js=(r=>(r.Added="added",r.Updated="updated",r.Deleted="deleted",r.Unchanged="unchanged",r))(js||{}),tpe=d.object({file:ce.describe("repo-relative path; in another repo of the change, that repo's directory name then its path"),kind:d.nativeEnum(FA),change:d.nativeEnum(js).describe("added: a file you created; updated / deleted / unchanged: an existing test"),covers:d.array(d.string()).describe("the plan case ids this file tests, each with its own result under result.cases"),defect:d.boolean().optional().describe("true when a case of it fails because the app is wrong and the test is right \u2014 kept failing on purpose"),staleBecause:d.object({requirement:ce.describe("the requirement or clause id the change deliberately alters"),line:ce.describe("path:line (or path) of the application code the change altered that makes this test's old expectation wrong")}).optional().describe("for an existing test you updated or deleted: why it is out of date"),staleOnBase:d.boolean().optional().describe("for an existing test that fails: true when it fails the same way on the base branch because its own expectation is wrong (the app there does what it should), so this change did not make it wrong. Not when the base app's own bug fails it: that is an existing defect. Leave it as it is (unchanged): its failure is the test's own"),result:d.object({started:d.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:d.number().nullable().describe("exit code of your last run of this file; null if it could not be run"),cases:d.array(d.object({case:ce,status:d.nativeEnum(pr),runtimeTargets:rd.optional().describe("HTTP(S) URLs this case actually exercised in its current run, from its request or browser evidence; omit for local in-process/mocked checks, never list the shared app merely because it is configured"),defect:d.boolean().optional().describe("for a failing case: true when the app is wrong and the test is right; false when the test is at fault and you could not fix it"),testProblem:Eg.optional().describe("for a failing case marked defect: false: what in the test is at fault"),failure:d.string().optional().describe("for a failing case: the runner's failure for it as printed (the error and the line it was raised at), not a summary"),cause:d.string().optional().describe("for a case you keep as a defect: path:line of the application code that makes it fail"),requires:d.string().optional().describe("for a case you keep as a defect: the words of the PR description, a requirement or clause of the plan, or the code a finding's keeps names, that state what its failing check expects, quoted exactly")})).describe("one entry per covered case, from the runner's own output"),details:d.string().optional().describe("what failed and why, or why it was not run"),noCases:d.string().optional().describe("for a failed run whose runner reported none of this file's tests (it failed to compile, import or collect): why")}),assertions:d.array(d.object({case:ce,evidence:ce})).optional().describe("per covered case, the assertion line that checks its expected outcome"),functions:d.array(d.object({name:ce.describe("the test function as the runner names it within its file, without the file (test_x, TestClass::test_x, TestSuite/TestCase)"),cases:d.array(ce).describe("the plan case ids it checks"),testProblem:Eg.optional().describe("for a function that fails because of the test itself, while another function keeps a case it checks as a defect: what in it is at fault")})).optional().describe("for a file you added or updated: each test function in it and the plan case ids it checks"),skyramp:d.object({draft:d.union([d.string(),d.array(d.string())]).optional().describe("the draft path the Skyramp helper returned for this test, or each path when the test was made from several drafts"),handWritten:d.string().optional().describe("why it is written by hand: the helper call you made and what it returned")}).optional().describe("only for a test of a case the Skyramp API block lists: where it came from"),context:d.array(nd).optional().describe("what the test sets up outside its own process that another test could run into: data it creates in the app, a Skyramp mock, an env override; omit when none"),isolatedRun:ce.optional().describe("for a test with a context: the command, from its checkout's root and without a shell, that runs only this file"),ci:f2.optional().describe("for a file you added or updated: whether the repo's CI will run it, and how you know"),run:Cu.optional().describe(`for a file in ${bu}, added, updated or re-run: how the run executes only this file's tests, with the repository's own runner and the report it writes (junit, trx or jest-json to ${sn}, or go-test-json); Testbot runs it before write ends and re-runs the tests with it`)}),npe=o(e=>{if(!e||typeof e!="object")return e;let{test:t,...n}=e;return typeof t=="string"&&t.trim()&&n.tests===void 0?{...n,tests:[t]}:e},"oneTestIsTests"),rpe=d.preprocess(npe,d.object({description:ce.describe("what is wrong and how to reproduce it: endpoint or page, input, what you got vs what was expected"),severity:d.nativeEnum(da).optional(),sourceFile:d.string().optional().describe("the app file at fault"),sourceLine:d.number().optional(),tests:d.array(ce).optional().describe("every test file that fails because of it: a defect several tests show is one issue"),finding:d.string().optional().describe("the plan's finding id, when it is one"),requirements:d.array(ce).optional().describe("the plan's requirement or clause ids it violates")})),w_e=d.object({schemaVersion:d.literal(1),tests:d.array(tpe),notWritten:d.array(d.object({case:ce,reason:ce,coveredBy:d.object({file:ce.describe("the test file, relative to the working checkout; prefix a related checkout as for tests[].file"),name:ce.describe("the test function as the runner names it within its file, without the file (test_x, TestClass::test_x, TestSuite/TestCase)")}).optional().describe("only for an existing test triage independently linked to this exact case: its exact runner name (including class or describe titles). Testbot must finish re-running it with every result passed. If your own test covers the case, include the case in its covers and function cases instead")})).describe("every plan case no test covers, and why"),journeys:d.array(ay).optional().describe("one entry per planned user journey: the browser test that walks it end to end"),lint:d.object({command:d.string(),clean:d.boolean()}).optional().describe("the linter/formatter you ran on your test files, if the repo has one: the exact command, with its file paths (Testbot re-runs it)"),dependenciesAdded:d.array(d.object({package:ce,manifest:ce.describe("the manifest file's path relative to its checkout (e.g. package.json, pom.xml or pyproject.toml), and nothing else; name another checkout in repository"),repository:ce.optional().describe("owner/repo of the manifest's checkout; omit for the repo under test"),reason:ce.optional().describe("why the test must run inside the application's own test environment, so its manifest had to change \u2014 required for every entry")})).optional().describe("every package you added to an APPLICATION manifest (an exception, surfaced in the report); never the Testbot test package's own"),supportFiles:d.array(ce).optional().describe("every file that is not a test you created or changed for your tests, which they need to compile or run (a helper module, page object, fixture, or a snapshot the runner wrote for them), named as you name a test; Testbot delivers only the tests you list and the files under supportFiles"),ciNotes:d.string().optional().describe("for each test whose ci says the repo's CI will not run it: the test, and the exact change the author must make for CI to run it"),commit:d.object({message:ce.describe("subject line at most 72 characters, following the repository's commit-message checks"),prTitle:ce.describe("at most 72 characters, following the repository's PR-title checks"),prBody:ce.describe("what the tests cover and what they found")}),report:d.object({summary:ce.describe("1-2 sentences for the PR author: does the change do what it says?"),issues:d.array(rpe).describe("every defect the tests found"),nextSteps:d.array(d.string()),noTests:d.array(d.object({repository:ce,reason:ce.max(4096)})).max(1e3).optional().describe("each Change Set repository where no test was added or updated: its owner/repo and why, naming the other repository when its tests went there"),notesDeviation:d.string().trim().max(4096).optional().describe("when the Target notes say where tests go and a test you added went elsewhere: where it went, and why; omit otherwise")})});var B_e={added:"place",updated:"update",deleted:"delete",unchanged:"verify"};var E2=(i=>(i.Requirement="requirement",i.PrDescription="pr_description",i.Code="code",i))(E2||{}),qt=d.string().trim().min(1),ipe=d.object({expectation:qt.max(300).describe("the behavior this assertion pins, in words"),source:d.nativeEnum(E2),expected:qt.max(200).describe("the exact value or outcome asserted, as the test asserts it")}),spe=d.object({file:qt.describe("path of the NEW test file you wrote, relative to its repository"),repository:qt.optional().describe("owner/repo the file lives in, when the run has several checkouts; omit for the working checkout"),framework:qt.describe("the framework the repository runs this file with: pytest, jest, vitest, node-test, or the name of any other"),run:Cu.optional().describe(`for ${bu}: how the run executes only the tests in names, with the repository's own runner writing JUnit XML to {junit}`),covers:d.array(qt).length(1).describe("the ONE behavior id, or defect id, from the plan that the tests in names provide evidence for; a file covering several is listed once per id"),names:d.array(qt).min(1).describe("the test functions/cases in the file that provide evidence for that behavior, as the framework names them"),assertions:d.array(ipe).min(1)}),PA=(n=>(n.Updated="updated",n.Deleted="deleted",n))(PA||{}),y2=300,ope=d.object({file:qt.describe("path of the EXISTING test file you updated or deleted, relative to its repository"),repository:qt.optional().describe("owner/repo the file lives in, when the run has several checkouts; omit for the working checkout"),change:d.nativeEnum(PA),staleBecause:d.object({requirement:qt.describe("the requirement or clause id the change deliberately alters"),line:qt.describe("path:line (or path) of the application code the change altered that makes this test's old expectation wrong")}).optional().describe("for an existing test you updated: why it is out of date"),reason:d.preprocess(e=>typeof e=="string"?e.trim().slice(0,y2):e,qt.max(y2)).describe("what the change deliberately altered that made the test wrong")}),Jx=d.object({schemaVersion:d.literal(1),tests:d.array(spe),maintained:d.array(ope).optional().describe("existing tests the change made stale that you updated or deleted; omit when there were none"),defectsNotTested:d.array(d.object({id:qt,reason:qt.max(300)})).optional().describe("defects the plan found that no in-process test can reach, each with why; omit when every defect has a test"),journeys:d.array(ay).optional().describe("one entry per planned user journey: the in-process test that walks it end to end"),journeysNotWritten:d.array(d.object({journey:qt,missing:qt.transform(e=>e.length>300?`${e.slice(0,299)}\u2026`:e)})).optional().describe("a planned journey no in-process test can walk here, with what it needs that is missing; it is reported as not covered"),lint:d.object({command:d.string(),clean:d.boolean()}).optional().describe("the linter/formatter you ran on your test files, if the repository has one you can run; omit otherwise"),commitMessage:qt.optional().describe("the commit message for your tests: a subject line of at most 72 characters, then what they cover")});var MA="generate-unit.json";function cpe(e){let{value:t,error:n}=$t(e);if(n)return{errors:[n]};let{value:i,errors:r}=mn(Jx,t);return r.length?{errors:r}:{output:i,errors:[]}}o(cpe,"parseGenerateUnitText");function upe(e){return cpe(e.stdout)}o(upe,"parseGenerateUnitFromSession");var gNe=$n("generate-unit-schema",(e,t)=>upe(t));var Ay=String.raw`(?:node:)?(?:http|https|http2|net|tls|dgram)`,hNe=[[/\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+["']${Ay}["']|\bimport\s+["']${Ay}["']|require\(\s*["']${Ay}["']\s*\)|\bimport\(\s*["']${Ay}["']\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 FNe=new Set(["targeted_unit","existing_evidence_sufficient"]);var ype="triage.json";var zUe=new Set(["existing_evidence","unaffected","existing_unit","new_unit","runtime"]),qUe={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 Epe(e){let{value:t,error:n}=$t(e);if(n)return{errors:[n]};let{value:i,errors:r}=mn(_A,t);return r.length?{errors:r}:{triage:i,errors:[]}}o(Epe,"parseTriageText");function Ipe(e){return Epe(e.stdout)}o(Ipe,"parseTriageFromSession");var JUe=$n("triage-schema",(e,t)=>Ipe(t));function Cpe(e){let t=e.inputs?.pipeline;return t?e.state.stages[t==="two-step"?"plan":"triage"]:e.state.stages.triage??e.state.stages.plan}o(Cpe,"triageDecider");function Yx(e){if(Cpe(e)?.status==="passed")return jo(B2.join(e.outputsDir,ype))}o(Yx,"readTriage");function Wx(e){return X1($R(e.inputs,ze(e,`${IA}.json`),Yx(e)?.sutRequired))}o(Wx,"revisionBlockReason");var HUe=new Set(["deploy","recommend","generate","generate-ui","adapt","generate-unit","native-run","finalize","deliver"]);var Pr=Se(require("fs")),Gs=Se(require("path")),yq=Se(require("crypto")),Eq=require("child_process");var Zx=require("child_process"),wu=Se(require("fs")),k2=Se(require("os")),gy=Se(require("path"));var bpe={onPath:o(e=>(0,Zx.spawnSync)("sh",["-c",`command -v ${e}`],{stdio:"ignore"}).status===0,"onPath"),run:o((e,t)=>(0,Zx.spawnSync)(e[0],e.slice(1),{cwd:t,stdio:"ignore",timeout:6e4}).status??1,"run")},fy={cleanup:o(()=>{},"cleanup")},vpe=new Set(["pnpm","yarn"]);function S2(e,t=k2.tmpdir(),n=bpe){if(process.platform==="win32")return fy;try{let i=Sx(e);if(!vpe.has(i)||n.onPath(i)||!n.onPath("corepack"))return fy;wu.mkdirSync(t,{recursive:!0});let r=wu.mkdtempSync(gy.join(t,"testbot-pm-")),s=o(()=>wu.rmSync(r,{recursive:!0,force:!0}),"cleanup");return n.run(["corepack","enable","--install-directory",r,i],e)!==0?(s(),fy):{dir:r,cleanup:s}}catch{return fy}}o(S2,"packageManagerShims");function Q2(e,t=process.env){return e.dir?{...t,PATH:[e.dir,t.PATH].filter(Boolean).join(gy.delimiter)}:t}o(Q2,"withShims");var GA=require("crypto");function Jt(e){let t=Math.max(0,...(e.match(/`+/g)??[]).map(r=>r.length)),n="`".repeat(t+1),i=e.startsWith("`")||e.endsWith("`")?" ":"";return`${n}${i}${e}${i}${n}`}o(Jt,"codeSpan");pc();var EFe=5*6e4,IFe=12*6e4,CFe=2*6e4;var QFe=["class TestbotProjectBrowsers {"," onBegin(config) {",' const projects = config.projects.map((p) => ({ browserName: p.use.browserName ?? p.use.defaultBrowserType ?? "chromium", channel: p.use.channel ?? null }));',' process.stdout.write("TESTBOT_PROJECT_BROWSERS " + JSON.stringify(projects) + "\\n");'," }"," printsToStdio() { return true; }","}","module.exports = TestbotProjectBrowsers;",""].join(`
|
|
159
|
-
`);var
|
|
158
|
+
`)){if(!r.trim()||r.length>1&&r[1]==="D")continue;let s=r.slice(3).trim(),a=s.indexOf(" -> ");if(a!==-1&&(s=s.slice(a+4).trim()),s=s.replace(/^"|"$/g,""),!s)continue;let c=s.replace(/^\.\//,"");c.startsWith(".skyramp/")||!n(c)||i.push(c)}return i}o(a2,"testLitter");function xAe(e){let t=ly[e],n=e==="ui";return{name:`${t.stage}-no-litter`,verify(i){let r=a2(i.inputs.repositoryPath);if(r===void 0)return{name:this.name,passed:!0};let s=r.filter(a=>RAe.test(a)===n);return s.length===0?{name:this.name,passed:!0}:Lt(this.name,[`${t.stage} left files outside .skyramp/ \u2014 move the staged test into .skyramp/staged/ and delete any codegen draft (e.g. *_scaffold.*): ${s.slice(0,6).join(", ")}`])}}}o(xAe,"noLitterGateFor");var XTe=xAe("backend");var DAe="write-stale-updates",_Ae={[DAe]:"stale test updates"};var UA=Se(require("fs")),pa=Se(require("path"));function d2(e,t=!1){return mn(HM(t),e).errors}o(d2,"validateAdaptOutput");function FAe(e,t=[],n=!1){let{value:i,error:r}=$t(e,t);if(r)return{errors:[r]};let s=d2(i,n);return s.length>0?{errors:s}:{adapt:i,errors:[]}}o(FAe,"parseAdaptText");var PAe="adapt-scratch",u2=`${PAe}/adapt-result.json`;function A2(e,t){let n=pa.join(e.outputsDir,u2),i;try{i=UA.readFileSync(n,"utf-8")}catch{i=void 0}if(i!==void 0&&(e.secretValues??[]).some(c=>i.includes(c)))return{errors:[`${u2} contains a secret value (token / credential) \u2014 never write it anywhere`]};let r=gd(e.inputs?.sharedEnvironment).length>0,s=FAe(t.stdout,e.secretValues,r);if(s.adapt)return s;let a=i!==void 0?jo(n):void 0;return a!==void 0&&d2(a,r).length===0?{adapt:a,errors:[]}:s}o(A2,"parseAdaptFromSession");var xDe=$n("adapt-schema",A2);var p2=require("child_process");function qx(e){return MAe(e)??[]}o(qx,"statusEntries");function MAe(e){let t;try{t=(0,p2.execFileSync)("git",[...Ri,"status","--porcelain","-z","--untracked-files=all"],{env:Xt(),cwd:e,encoding:"utf-8",maxBuffer:16*1024*1024})}catch{return}let n=t.split("\0"),i=[];for(let r=0;r<n.length;r++){let s=n[r];if(s.length<4)continue;let a=s.slice(0,2);i.push({code:a,path:s.slice(3)}),(a[0]==="R"||a[0]==="C")&&r++}return i}o(MAe,"readStatusEntries");var ODe=2*1024*1024;var dy=d.string().trim().min(1),OAe=d.object({cwd:dy.describe(`directory the command starts in, relative to the test's checkout ("." for its root)`),argv:d.array(dy).min(1).describe("the command as separate arguments, run without a shell"),env:d.record(d.string(),d.string()).optional().describe("plain settings the listing needs beyond the CI step's own; never a credential or PATH")}),LAe=d.object({file:dy.describe("a file of the test's checkout, relative to its root"),line:dy.describe("a line of that file, quoted exactly from where its command starts to its end")}),f2=d.object({collected:d.boolean().describe("whether the repo's CI runs this test as it is"),steps:d.array(LAe).optional().describe("when collected: the line in a CI file that starts the tests, then each line it runs on the way to the test runner"),runner:d.string().optional().describe("when collected: the test runner the last of those lines starts, by the name that line and the list command both use"),list:OAe.optional().describe("when collected: a command that lists the tests that runner collects without running them; Testbot runs it, and its output must name this file"),why:d.string().optional().describe("when not collected: why the repo's CI will not run it")});var ce=d.string().trim().min(1),JAe=o(e=>{if(!e||typeof e!="object")return e;let t=e;return typeof t.skip=="string"&&t.skip.trim()&&(t.expected===void 0||t.expected===null)?{...t,expected:"(not tested)"}:e},"skippedNeedsNoExpected"),HAe=d.preprocess(JAe,d.object({id:ce.describe(`its requirement's id plus a letter, e.g. "R1a", "AC-3a"`),clause:ce.describe("one testable part of the requirement"),expected:ce.describe("the outcome the requirement calls for \u2014 taken from the requirement, never from what the code does"),skip:d.string().optional().describe("only when no test can check this clause here: why"),type:d.nativeEnum(ji).optional().describe("the test that checks this clause: contract / integration (the API, or code called directly in-process: a function, hook or module) or ui (a page)"),target:d.string().optional().describe('its "METHOD /path", or the page / flow'),steps:d.string().optional().describe("what that test does; its expected outcome is this clause's"),finding:d.string().optional().describe("the finding id, when this clause's test also catches that defect (the defect still gets a case of its own)"),code:d.string().optional().describe("path:line of the code that decides this clause, when there is one; in another repo of the change, that repo's directory name then its path"),stated:d.string().optional().describe("the description's or spec's own words that state this clause, copied exactly, when they do"),mutates:d.boolean().optional().describe("true when its test changes state, in the test or its setup: an API POST, PUT, PATCH or DELETE, or a UI flow that submits, creates, edits or deletes"),browserOnly:d.boolean().optional().describe("true when its behaviour happens only in a browser: real clicks or keys driving page script, client-side sorting or filtering, script-driven DOM updates, focus, drag-and-drop, navigation, rendering that depends on CSS or JavaScript"),browserHarness:d.string().optional().describe("browserOnly, off the runtime path: the path of the repo's in-process browser suite its test goes in (e.g. a Django StaticLiveServerTestCase test that drives Selenium)"),quote:d.string().optional().describe("the words of the spec, plan, ticket, PR description or a test the change adds or edits that state this clause, copied exactly; a file of the repository: its path:line first. Leave it out when no source states it"),inferred:d.boolean().optional().describe("leave it out: Testbot sets it when no source states this clause (contracts/clause-grounding.ts)")})),h2=d.object({spec:d.string().optional().describe("file:line of a spec in the repository"),prDescription:d.boolean().optional().describe("or true when a pull request description says otherwise"),reference:d.string().optional().describe("or the key of an item the run was given, as listed"),says:ce.describe("what it says there, in its own words, copied exactly"),criterion:d.number().int().positive().optional().describe("an item's only: leave it out; Testbot numbers it")}).refine(e=>[!!e.prDescription,!!e.spec?.trim(),!!e.reference?.trim()].filter(Boolean).length===1,{message:`names no source, or more than one: give "spec" its file:line or "reference" an item's key, or set "prDescription", one of them; list each source as its own entry`}),YAe=d.object({id:ce.describe('the label its source gives it ("AC-3", "REQ-12"; item 4 of a numbered list is "R4"), else "R1", "R2"\u2026 in order'),statement:ce,source:d.nativeEnum(fi).describe("requirement-reference (an item the run was given), spec, pr-description (also for what the change is evidently meant to do when nothing is written down), or could-break (what the change could break that no requirement mentions)"),reference:d.string().optional().describe('requirement-reference only: the key of its item as listed, e.g. "PAY-184", or a Confluence page id such as "3021"'),evidence:ce.describe("where it is stated: for requirement-reference, the item's own words, copied exactly; else file:line, a doc section, or the quoted phrase"),criterion:d.number().int().positive().optional().describe("requirement-reference only: leave it out; Testbot numbers each criterion by the item's own label (AC2, 2.), else after the item's labels"),alsoFrom:d.array(d.object({reference:ce.regex(Is).describe("the key of another uploaded document stating the same obligation"),says:ce.describe("that document's own words, copied exactly; never infer equivalence from a shared criterion number"),criterion:d.number().int().positive().optional().describe("leave out; Testbot grounds and numbers this source separately")})).optional().describe("equivalent uploaded source criteria sharing this requirement's planned cases; retain every source with its own quote. Different conditions or boundaries need distinct requirements"),notInChange:d.string().optional().describe("requirement-reference only: when the change does not touch this criterion at all (e.g. a later step of a staged rollout), why; give it no clauses"),unchanged:d.boolean().optional().describe("true when it asks only that behaviour stay as it was (an update or refactor that must not change how something works), whatever its source"),overrules:d.array(h2).optional().describe("requirement-reference only: each lower-ranked source that says otherwise, a spec in the repository, a PR description or another item; this requirement wins, so test what it says"),clauses:d.array(HAe)}),m2=(r=>(r.ServerError="server-error",r.DataLost="data-lost",r.FinalState="final-state",r.DerivedValues="derived-values",r))(m2||{}),WAe=d.object({id:ce.describe('e.g. "F1"'),file:ce,line:d.number().optional(),claim:ce.describe("the defect, in one sentence"),severity:d.nativeEnum(da),evidence:ce.describe("the code line, or the probe request and response, that shows it"),conflictsWith:d.array(ce).optional().describe("requirement or clause ids it violates"),keeps:d.string().optional().describe("for a defect no requirement or clause states: path:line of the code beside the change that keeps the rule it breaks"),rule:d.nativeEnum(m2).optional().describe("for a defect that breaks a rule every app keeps, which nothing needs to state: which one"),existing:d.string().optional().describe("only when the base already does this, in code the change left as it was, and the change does not say it fixes it: where the base does it (its file:line); such a defect gets no case"),needsApp:d.enum(["browser","live-api"]).optional().describe("only when the running app alone can show this defect and the repo has no in-process test that can: browser (page script, what the user sees after a click or a save) or live-api (code the repo tests only against the running app's API)")}),ZAe=d.object({id:ce.describe('e.g. "Q1"'),question:ce.describe("what is unsettled, as a question the PR author can answer"),readings:d.array(ce).min(2).describe("each reasonable behaviour, with what points to it (file:line, or the words that suggest it)"),about:d.string().optional().describe("the requirement or clause id it is about, when there is one"),sources:d.array(h2).optional().describe("when sources of the same rank disagree on it: each of them")}),KAe=d.object({id:ce.describe('unique, a short kebab-case name for what the case checks, e.g. "ship-twice-409"'),type:d.nativeEnum(ji).describe("contract / integration: checks the API, or calls code directly in-process (a function, hook or module); ui: checks what a user sees or does on a page"),target:ce.describe('"METHOD /path", or the page / flow'),clause:d.string().optional().describe("the clause id this case checks"),finding:d.string().optional().describe("the finding id this case catches"),steps:ce.describe("what the test does"),expected:ce.describe("the expected outcome, from the clause"),mutates:d.boolean().optional().describe("true when its test changes state, in the test or its setup: an API POST, PUT, PATCH or DELETE, or a UI flow that submits, creates, edits or deletes")}),XAe=d.object({test:ce.describe("existing test file"),action:d.nativeEnum(Ai),reason:ce,mutates:d.boolean().optional().describe("true when the maintained test changes state"),clauses:d.array(ce).optional().describe("the clause ids this test checks"),staleOnBase:d.boolean().optional().describe("true when the test's own expectation was already wrong before this change: it fails the same way on the base branch, where the app does what it should. Not one the base app's own bug fails (that is an existing defect). It is verify, never update: re-run as it is, its failure the test's own. A delete the change justifies stays a delete")}),g2=d.array(vb).optional(),epe=d.object({components:d.preprocess(e=>g2.safeParse(e).success?e:void 0,g2).describe("when saving a new or changed recipe: every app and backing service actually brought up, its source repository, and whether it is healthy"),outcome:d.nativeEnum(ri).describe("clean | recipe-drift (you had to fix the recipe) | change-broke-bringup (this PR broke start-up) | bringup-failed (the environment, not the PR)"),baseUrls:d.record(d.string()).optional().describe("service \u2192 base URL of the running app"),health:d.object({url:d.string().optional(),command:d.string().optional(),output:d.string().optional()}).optional().describe("the check that shows the app serves real data, and what it returned"),teardown:d.string().optional().describe("command that stops the app"),dependencies:d.record(d.boolean()).optional().describe("every backing service: true = really running, false = mocked"),recipeFixes:d.array(d.string()).optional().describe("what you changed in the recipe"),error:d.string().optional().describe("when it did not come up: the failing command and what it printed"),suspectFiles:d.array(d.string()).optional().describe("change-broke-bringup: the changed files to blame"),missingSecrets:d.array(d.string().regex(Yl)).optional().describe("bringup-failed only: each secret, key, token or password the app cannot start without that this run has no value for, by its environment variable name; never a value"),login:d.object({username:ce,password:d.string()}).optional().describe("the account the tests sign in as, when they sign in: each a literal value the recipe seeds, or $VARIABLE when a secret in the environment holds it"),revisions:kb.optional()}),v_e=d.object({schemaVersion:d.literal(1),requirements:d.array(YAe),findings:d.array(WAe),cases:d.array(KAe).describe("a second test for a clause, and one case per finding that fails on this branch"),questions:d.array(ZAe).optional().describe("behaviours the change leaves unsettled; no case asserts any of them"),maintenance:d.array(XAe),journeys:d.array(Kz).optional().describe("the user journeys that, together, pass through everything the change alters that a user sees or does; empty when it alters nothing a user sees"),notInJourney:d.array(d.object({clause:ce,why:ce})).optional().describe("a clause a user sees or does that no journey walks, and why: none can reach it through the UI, or it is downstream of this change and not walked here"),unplannedComponents:d.array(d.object({components:d.array(ce).min(1).describe("changed components, as the change lists them"),why:ce})).optional().describe("changed components no clause reaches, and why their change needs no test; several may share one reason"),triage:_A.optional().describe("the validation triage decision, made before the app is started; its behaviorIds are clause ids"),app:epe.optional().describe("omit when no app was needed or none was started"),summary:ce.describe("one paragraph: what the change does and where the risk is")});var FA=(n=>(n.Backend="backend",n.Ui="ui",n))(FA||{});var js=(r=>(r.Added="added",r.Updated="updated",r.Deleted="deleted",r.Unchanged="unchanged",r))(js||{}),tpe=d.object({file:ce.describe("repo-relative path; in another repo of the change, that repo's directory name then its path"),kind:d.nativeEnum(FA),change:d.nativeEnum(js).describe("added: a file you created; updated / deleted / unchanged: an existing test"),covers:d.array(d.string()).describe("the plan case ids this file tests, each with its own result under result.cases"),defect:d.boolean().optional().describe("true when a case of it fails because the app is wrong and the test is right \u2014 kept failing on purpose"),staleBecause:d.object({requirement:ce.describe("the requirement or clause id the change deliberately alters"),line:ce.describe("path:line (or path) of the application code the change altered that makes this test's old expectation wrong")}).optional().describe("for an existing test you updated or deleted: why it is out of date"),staleOnBase:d.boolean().optional().describe("for an existing test that fails: true when it fails the same way on the base branch because its own expectation is wrong (the app there does what it should), so this change did not make it wrong. Not when the base app's own bug fails it: that is an existing defect. Leave it as it is (unchanged): its failure is the test's own"),result:d.object({started:d.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:d.number().nullable().describe("exit code of your last run of this file; null if it could not be run"),cases:d.array(d.object({case:ce,status:d.nativeEnum(pr),runtimeTargets:rd.optional().describe("HTTP(S) URLs this case actually exercised in its current run, from its request or browser evidence; omit for local in-process/mocked checks, never list the shared app merely because it is configured"),defect:d.boolean().optional().describe("for a failing case: true when the app is wrong and the test is right; false when the test is at fault and you could not fix it"),testProblem:Eg.optional().describe("for a failing case marked defect: false: what in the test is at fault"),failure:d.string().optional().describe("for a failing case: the runner's failure for it as printed (the error and the line it was raised at), not a summary"),cause:d.string().optional().describe("for a case you keep as a defect: path:line of the application code that makes it fail"),requires:d.string().optional().describe("for a case you keep as a defect: the words of the PR description, a requirement or clause of the plan, or the code a finding's keeps names, that state what its failing check expects, quoted exactly")})).describe("one entry per covered case, from the runner's own output"),details:d.string().optional().describe("what failed and why, or why it was not run"),noCases:d.string().optional().describe("for a failed run whose runner reported none of this file's tests (it failed to compile, import or collect): why")}),assertions:d.array(d.object({case:ce,evidence:ce})).optional().describe("per covered case, the assertion line that checks its expected outcome"),functions:d.array(d.object({name:ce.describe("the test function as the runner names it within its file, without the file (test_x, TestClass::test_x, TestSuite/TestCase)"),cases:d.array(ce).describe("the plan case ids it checks"),testProblem:Eg.optional().describe("for a function that fails because of the test itself, while another function keeps a case it checks as a defect: what in it is at fault")})).optional().describe("for a file you added or updated: each test function in it and the plan case ids it checks"),skyramp:d.object({draft:d.union([d.string(),d.array(d.string())]).optional().describe("the draft path the Skyramp helper returned for this test, or each path when the test was made from several drafts"),handWritten:d.string().optional().describe("why it is written by hand: the helper call you made and what it returned")}).optional().describe("only for a test of a case the Skyramp API block lists: where it came from"),context:d.array(nd).optional().describe("what the test sets up outside its own process that another test could run into: data it creates in the app, a Skyramp mock, an env override; omit when none"),isolatedRun:ce.optional().describe("for a test with a context: the command, from its checkout's root and without a shell, that runs only this file"),ci:f2.optional().describe("for a file you added or updated: whether the repo's CI will run it, and how you know"),run:Cu.optional().describe(`for a file in ${bu}, added, updated or re-run: how the run executes only this file's tests, with the repository's own runner and the report it writes (junit, trx or jest-json to ${sn}, or go-test-json); Testbot runs it before write ends and re-runs the tests with it`)}),npe=o(e=>{if(!e||typeof e!="object")return e;let{test:t,...n}=e;return typeof t=="string"&&t.trim()&&n.tests===void 0?{...n,tests:[t]}:e},"oneTestIsTests"),rpe=d.preprocess(npe,d.object({description:ce.describe("what is wrong and how to reproduce it: endpoint or page, input, what you got vs what was expected"),severity:d.nativeEnum(da).optional(),sourceFile:d.string().optional().describe("the app file at fault"),sourceLine:d.number().optional(),tests:d.array(ce).optional().describe("every test file that fails because of it: a defect several tests show is one issue"),finding:d.string().optional().describe("the plan's finding id, when it is one"),requirements:d.array(ce).optional().describe("the plan's requirement or clause ids it violates")})),w_e=d.object({schemaVersion:d.literal(1),tests:d.array(tpe),notWritten:d.array(d.object({case:ce,reason:ce,coveredBy:d.object({file:ce.describe("the test file, relative to the working checkout; prefix a related checkout as for tests[].file"),name:ce.describe("the test function as the runner names it within its file, without the file (test_x, TestClass::test_x, TestSuite/TestCase)")}).optional().describe("only for an existing test triage independently linked to this exact case: its exact runner name (including class or describe titles). Testbot must finish re-running it with every result passed. If your own test covers the case, include the case in its covers and function cases instead")})).describe("every plan case no test covers, and why"),journeys:d.array(ay).optional().describe("one entry per planned user journey: the browser test that walks it end to end"),lint:d.object({command:d.string(),clean:d.boolean()}).optional().describe("the linter/formatter you ran on your test files, if the repo has one: the exact command, with its file paths (Testbot re-runs it)"),dependenciesAdded:d.array(d.object({package:ce,manifest:ce.describe("the manifest file's path relative to its checkout (e.g. package.json, pom.xml or pyproject.toml), and nothing else; name another checkout in repository"),repository:ce.optional().describe("owner/repo of the manifest's checkout; omit for the repo under test"),reason:ce.optional().describe("why the test must run inside the application's own test environment, so its manifest had to change \u2014 required for every entry")})).optional().describe("every package you added to an APPLICATION manifest (an exception, surfaced in the report); never the Testbot test package's own"),supportFiles:d.array(ce).optional().describe("every file that is not a test you created or changed for your tests, which they need to compile or run (a helper module, page object, fixture, or a snapshot the runner wrote for them), named as you name a test; Testbot delivers only the tests you list and the files under supportFiles"),ciNotes:d.string().optional().describe("for each test whose ci says the repo's CI will not run it: the test, and the exact change the author must make for CI to run it"),commit:d.object({message:ce.describe("subject line at most 72 characters, following the repository's commit-message checks"),prTitle:ce.describe("at most 72 characters, following the repository's PR-title checks"),prBody:ce.describe("what the tests cover and what they found")}),report:d.object({summary:ce.describe("1-2 sentences for the PR author: does the change do what it says?"),issues:d.array(rpe).describe("every defect the tests found"),nextSteps:d.array(d.string()),noTests:d.array(d.object({repository:ce,reason:ce.max(4096)})).max(1e3).optional().describe("each Change Set repository where no test was added or updated: its owner/repo and why, naming the other repository when its tests went there"),notesDeviation:d.string().trim().max(4096).optional().describe("when the Target notes say where tests go and a test you added went elsewhere: where it went, and why; omit otherwise")})});var B_e={added:"place",updated:"update",deleted:"delete",unchanged:"verify"};var E2=(i=>(i.Requirement="requirement",i.PrDescription="pr_description",i.Code="code",i))(E2||{}),qt=d.string().trim().min(1),ipe=d.object({expectation:qt.max(300).describe("the behavior this assertion pins, in words"),source:d.nativeEnum(E2),expected:qt.max(200).describe("the exact value or outcome asserted, as the test asserts it")}),spe=d.object({file:qt.describe("path of the NEW test file you wrote, relative to its repository"),repository:qt.optional().describe("owner/repo the file lives in, when the run has several checkouts; omit for the working checkout"),framework:qt.describe("the framework the repository runs this file with: pytest, jest, vitest, node-test, or the name of any other"),run:Cu.optional().describe(`for ${bu}: how the run executes only the tests in names, with the repository's own runner writing JUnit XML to {junit}`),covers:d.array(qt).length(1).describe("the ONE behavior id, or defect id, from the plan that the tests in names provide evidence for; a file covering several is listed once per id"),names:d.array(qt).min(1).describe("the test functions/cases in the file that provide evidence for that behavior, as the framework names them"),assertions:d.array(ipe).min(1)}),PA=(n=>(n.Updated="updated",n.Deleted="deleted",n))(PA||{}),y2=300,ope=d.object({file:qt.describe("path of the EXISTING test file you updated or deleted, relative to its repository"),repository:qt.optional().describe("owner/repo the file lives in, when the run has several checkouts; omit for the working checkout"),change:d.nativeEnum(PA),staleBecause:d.object({requirement:qt.describe("the requirement or clause id the change deliberately alters"),line:qt.describe("path:line (or path) of the application code the change altered that makes this test's old expectation wrong")}).optional().describe("for an existing test you updated: why it is out of date"),reason:d.preprocess(e=>typeof e=="string"?e.trim().slice(0,y2):e,qt.max(y2)).describe("what the change deliberately altered that made the test wrong")}),Jx=d.object({schemaVersion:d.literal(1),tests:d.array(spe),maintained:d.array(ope).optional().describe("existing tests the change made stale that you updated or deleted; omit when there were none"),defectsNotTested:d.array(d.object({id:qt,reason:qt.max(300)})).optional().describe("defects the plan found that no in-process test can reach, each with why; omit when every defect has a test"),journeys:d.array(ay).optional().describe("one entry per planned user journey: the in-process test that walks it end to end"),journeysNotWritten:d.array(d.object({journey:qt,missing:qt.transform(e=>e.length>300?`${e.slice(0,299)}\u2026`:e)})).optional().describe("a planned journey no in-process test can walk here, with what it needs that is missing; it is reported as not covered"),lint:d.object({command:d.string(),clean:d.boolean()}).optional().describe("the linter/formatter you ran on your test files, if the repository has one you can run; omit otherwise"),commitMessage:qt.optional().describe("the commit message for your tests: a subject line of at most 72 characters, then what they cover")});var MA="generate-unit.json";function cpe(e){let{value:t,error:n}=$t(e);if(n)return{errors:[n]};let{value:i,errors:r}=mn(Jx,t);return r.length?{errors:r}:{output:i,errors:[]}}o(cpe,"parseGenerateUnitText");function upe(e){return cpe(e.stdout)}o(upe,"parseGenerateUnitFromSession");var gNe=$n("generate-unit-schema",(e,t)=>upe(t));var Ay=String.raw`(?:node:)?(?:http|https|http2|net|tls|dgram)`,hNe=[[/\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+["']${Ay}["']|\bimport\s+["']${Ay}["']|require\(\s*["']${Ay}["']\s*\)|\bimport\(\s*["']${Ay}["']\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 PNe=new Set(["targeted_unit","existing_evidence_sufficient"]);var ype="triage.json";var JUe=new Set(["existing_evidence","unaffected","existing_unit","new_unit","runtime"]),HUe={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 Epe(e){let{value:t,error:n}=$t(e);if(n)return{errors:[n]};let{value:i,errors:r}=mn(_A,t);return r.length?{errors:r}:{triage:i,errors:[]}}o(Epe,"parseTriageText");function Ipe(e){return Epe(e.stdout)}o(Ipe,"parseTriageFromSession");var YUe=$n("triage-schema",(e,t)=>Ipe(t));function Cpe(e){let t=e.inputs?.pipeline;return t?e.state.stages[t==="two-step"?"plan":"triage"]:e.state.stages.triage??e.state.stages.plan}o(Cpe,"triageDecider");function Yx(e){if(Cpe(e)?.status==="passed")return jo(B2.join(e.outputsDir,ype))}o(Yx,"readTriage");function Wx(e){return X1($R(e.inputs,ze(e,`${IA}.json`),Yx(e)?.sutRequired))}o(Wx,"revisionBlockReason");var WUe=new Set(["deploy","recommend","generate","generate-ui","adapt","generate-unit","native-run","finalize","deliver"]);var Pr=Se(require("fs")),Gs=Se(require("path")),yq=Se(require("crypto")),Eq=require("child_process");var Zx=require("child_process"),wu=Se(require("fs")),k2=Se(require("os")),gy=Se(require("path"));var bpe={onPath:o(e=>(0,Zx.spawnSync)("sh",["-c",`command -v ${e}`],{stdio:"ignore"}).status===0,"onPath"),run:o((e,t)=>(0,Zx.spawnSync)(e[0],e.slice(1),{cwd:t,stdio:"ignore",timeout:6e4}).status??1,"run")},fy={cleanup:o(()=>{},"cleanup")},vpe=new Set(["pnpm","yarn"]);function S2(e,t=k2.tmpdir(),n=bpe){if(process.platform==="win32")return fy;try{let i=Sx(e);if(!vpe.has(i)||n.onPath(i)||!n.onPath("corepack"))return fy;wu.mkdirSync(t,{recursive:!0});let r=wu.mkdtempSync(gy.join(t,"testbot-pm-")),s=o(()=>wu.rmSync(r,{recursive:!0,force:!0}),"cleanup");return n.run(["corepack","enable","--install-directory",r,i],e)!==0?(s(),fy):{dir:r,cleanup:s}}catch{return fy}}o(S2,"packageManagerShims");function Q2(e,t=process.env){return e.dir?{...t,PATH:[e.dir,t.PATH].filter(Boolean).join(gy.delimiter)}:t}o(Q2,"withShims");var GA=require("crypto");function Jt(e){let t=Math.max(0,...(e.match(/`+/g)??[]).map(r=>r.length)),n="`".repeat(t+1),i=e.startsWith("`")||e.endsWith("`")?" ":"";return`${n}${i}${e}${i}${n}`}o(Jt,"codeSpan");pc();var CFe=5*6e4,bFe=12*6e4,vFe=2*6e4;var xFe=["class TestbotProjectBrowsers {"," onBegin(config) {",' const projects = config.projects.map((p) => ({ browserName: p.use.browserName ?? p.use.defaultBrowserType ?? "chromium", channel: p.use.channel ?? null }));',' process.stdout.write("TESTBOT_PROJECT_BROWSERS " + JSON.stringify(projects) + "\\n");'," }"," printsToStdio() { return true; }","}","module.exports = TestbotProjectBrowsers;",""].join(`
|
|
159
|
+
`);var jFe=[...hb,"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 hy=Se(Bx());var mPe={jest:"jest",vitest:"vitest"};var KPe=new Set(["jest","vitest","npm-test","playwright"]);var AMe=5*6e4;var OA=Se(require("path"));var FMe={python:"pytest",typescript:"playwright",javascript:"playwright"},PMe={pytest:"pytest",playwright:"playwright"};function Spe(e){return mn(qb,e).errors}o(Spe,"validateFinalizeOutput");function Qpe(e,t=[]){let{value:n,error:i}=$t(e,t);if(i)return{errors:[i]};let r=Spe(n);return r.length>0?{errors:r}:{finalize:n,errors:[]}}o(Qpe,"parseFinalizeText");var Rpe="finalize-scratch";function xpe(e,t){let n=Qpe(e.stdout,t?.secretValues);if(!n.finalize||!t?.outputsDir)return n;let i=o((r,s)=>r.trim()&&Tx(r.trim(),OA.join(t.outputsDir,Rpe,s),"finalize")||r,"script");return{...n,finalize:{...n.finalize,lint:n.finalize.lint.map((r,s)=>({...r,command:i(r.command??"",`lint-${s+1}.sh`)}))}}}o(xpe,"parseFinalizeFromSession");var ROe=$n("finalize-schema",(e,t)=>xpe(t,e));function $pe(e){return mn(Ox,e).errors}o($pe,"validateAnalysisOutput");function T2(e,t=[]){let{value:n,error:i}=$t(e,t);if(i)return{errors:[i]};let r=$pe(n);return r.length>0?{errors:r}:{analysis:n,errors:[]}}o(T2,"parseAnalysisText");function Tpe(e,t=[]){return T2(e.stdout,t)}o(Tpe,"parseAnalysisFromSession");var XOe=$n("analysis-schema",(e,t)=>Tpe(t,e.secretValues));var Ije=ag.rows.notRun(!0);var LA="kept, not ";var jA="(declined the planned ";function Kx(e){if(!e)return[];let t=[],n=0,i=0;for(let r=0;r<e.length;r++){let s=e[r];s==="("?n++:s===")"?n=Math.max(0,n-1):n===0&&s===";"&&e[r+1]===" "&&e[r-1]===")"&&(t.push(e.slice(i,r)),i=r+2)}return t.push(e.slice(i)),t.map(r=>{let s=r.trim();if(!s.endsWith(")"))return{expectation:s};let a=0;for(let c=s.length-1;c>=0;c--)if(s[c]===")")a++;else if(s[c]==="("&&--a===0){let u=s.slice(0,c).trim(),l=s.slice(c+1,-1).trim();return u&&l?{expectation:u,expected:l}:{expectation:s}}return{expectation:s}})}o(Kx,"assertionParts");var D2=new Set(["update","regenerate","delete"]);var Cje={update:"updated",regenerate:"regenerated",delete:"deleted",verify:"verified",none:"touched"};var _2=d.string().trim().min(1),Xx=d.object({schemaVersion:d.literal(1).optional(),businessCaseAnalysis:_2.describe("1-2 sentences: what this change means for a user, and whether the evidence shows it working"),issuesFound:d.array(d.object({description:_2,severity:d.string().optional().describe("critical | high | medium | low"),category:d.string().optional().describe("bug | lint | type | config"),sourceFile:d.string().optional(),sourceLine:d.number().optional(),findingId:d.string().optional(),requirementIds:d.array(d.string()).optional()})).describe("every real problem this run exposed \u2014 cause, file:line, severity"),nextSteps:d.array(d.string()).describe("concrete follow-ups the author can act on; required non-empty when a disclosure is BLOCKING")});function Upe(e){return mn(Xx,e).errors}o(Upe,"validateProseOutput");function Fpe(e,t=[]){let{value:n,error:i}=$t(e.stdout,t);if(i)return{errors:[i]};let r=Upe(n);return r.length>0?{errors:r}:{prose:n,errors:[]}}o(Fpe,"parseProseFromSession");var Nje=$n("report-schema",(e,t)=>Fpe(t,e.secretValues));var N2="<!-- skyramp-testbot -->",U2=D2,Ppe=new Set(["lint","type","config"]),F2={critical:0,high:1,medium:2,low:3},V2=new Set(["Pass","Fail"]);var n$=o(e=>Io(ae().statusLabels,e),"statusLabel"),e$=o(e=>Io(ae().testTypeCellLabels,e),"testTypeLabel");function Ge(e){return(e??"").replace(/\|/g,"\\|").replace(/\r?\n/g,"<br>").trim()}o(Ge,"escCell");function P2(e){return e.inferred?" (inferred)":""}o(P2,"inferredMark");function M2(e,t){return!e||!V2.has(e)?"\u2014":t?`${n$(e)} (${Ge(G2(t))})`:n$(e)}o(M2,"maintStatus");function G2(e){let t=o(i=>{let r=i.indexOf(": ");return r<0?i:Io(ae().staged.maintenanceActions,i.slice(0,r))+i.slice(r)},"action");if(e.startsWith(LA))return ae().staged.keptNot+t(e.slice(LA.length));let n=e.indexOf(jA);return n<0?e:e.slice(0,n)+ae().staged.declinedPlanned+t(e.slice(n+jA.length))}o(G2,"declineNote");function O2(e){return e.category!==void 0&&Ppe.has(e.category.toLowerCase())}o(O2,"isTooling");function L2(e,t){return(F2[(e.severity??"").toLowerCase()]??4)-(F2[(t.severity??"").toLowerCase()]??4)}o(L2,"bySeverity");function j2(e){return`- ${e.severity?`**[${Io(ae().severityLabels,e.severity.toLowerCase()).toUpperCase()}]** `:""}${e.description.trim()}`}o(j2,"issueLine");function Mpe(e){let t=e.resultId?.split("#").slice(1).join("#");if(e.testType!=="unit"||!t)return;let n=t;try{n=decodeURIComponent(t)}catch{}let i=/^(.*?)(\[.*\])$/.exec(n);return i?{fn:i[1],kase:i[2]}:{fn:n}}o(Mpe,"unitTestOf");var z2=o((e,t)=>e!==void 0&&t!==void 0&&e.replace(/^\.\//,"")===t.replace(/^\.\//,""),"samePath");function q2(e,t){return(e.testVideos??[]).find(n=>n.url&&t(n))?.url}o(q2,"videoLink");function r$(e,t){return q2(e,n=>z2(n.fileName,t.fileName)&&(!n.repository||!t.repository||n.repository.toLowerCase()===t.repository.toLowerCase()))}o(r$,"resultVideoLink");function i$(e,t){return q2(e,n=>z2(n.writtenAs??n.fileName,t))}o(i$,"journeyVideoLink");function Ope(e,t,n){return n?r$(e,{fileName:t,repository:n}):i$(e,t)}o(Ope,"requirementVideoLink");function Lpe(e){let t=[],n=new Map;for(let a of e.newTestsCreated)a.testType==="unit"&&n.set(a.fileName,[...n.get(a.fileName)??[],a.testId.split("::").slice(1).join("::")]);let i=new Map,r=o((a,c)=>(n.get(a??"")??[]).find(u=>u!==c&&qz(c,u)),"parentOf"),s=new Map;for(let a of e.testResults){let c=Mpe(a),u=c&&!c.kase?r(a.fileName,c.fn):void 0;if(c&&u&&(c={fn:u,kase:`"${c.fn}"`}),c?.kase&&i.set(a,c.kase),!c){t.push({testId:a.testId,testType:a.testType,endpoint:a.endpoint,status:a.status,details:a.details??"",...a.fileName?{fileName:a.fileName}:{},...a.repository?{repository:a.repository}:{}});continue}let l=`${a.fileName??""}#${c.fn}`,A=s.get(l);A||(A={row:{testId:a.testId,testType:a.testType,endpoint:a.endpoint,status:a.status,details:"",test:c.fn,...a.fileName?{fileName:a.fileName}:{},...a.repository?{repository:a.repository}:{}},cases:[]},s.set(l,A),t.push(A.row)),A.cases.push(a)}for(let{row:a,cases:c}of s.values()){let u=c.filter(g=>g.status==="Fail"),l=c.filter(g=>g.status==="Pass").length,A=c.filter(g=>g.status==="Skipped").length;a.cases=c.length,a.status=u.length?"Fail":A?"Skipped":"Pass";let p=u[0];a.details=c.length===1?c[0].details??"":ae().staged.casesPassed(l,c.length,A)+(p?`; ${i.get(p)??""} ${p.details??""}`.replace(/; +/,"; ").trimEnd():"")}return t}o(Lpe,"resultRows");function jpe(e){return Kx(e).map(t=>t.expected===void 0?t.expectation:`${t.expectation}: ${Jt(t.expected)}`)}o(jpe,"unitAssertions");function t$(e){return e.newTestsCreated.some(t=>t.testType!=="unit")&&e.testResults.every(t=>t.status==="Skipped")&&e.testResults.some(t=>t.failureCause?.kind==="environment"&&(t.failureCause.family==="app_not_started"||t.failureCause.family==="secret"))}o(t$,"nothingExecuted");function J2(e,t={}){let{audience:n,collapsed:i=!1,existingEvidence:r=[],requestedBy:s,sourcePullRequest:a}=t,c=n!=="testbot-pr",u=n!=="comment",l=n!=="testbot-pr",A=(e.requirements??[]).filter(P=>/^file-[a-f0-9]{16}-/i.test(P.id)).sort((P,ee)=>ee.id.length-P.id.length),p=o(P=>{let ee=A.find(Y=>P.toLowerCase().startsWith(Y.id.toLowerCase()));return ee?ee.label+P.slice(ee.id.length):P},"displayId"),g=[N2];if(a&&g.push(ae().staged.testsSourcePullRequest(Jt(a)),""),s){let P=s.name.replace(/\s+/g," ").trim().replace(/[<>[\]()*_`\\|#]/g,"\\$&").replace(/@/g,"@\u200D");g.push(s.kind==="person"?ae().staged.requestedByPerson(P):ae().staged.requestedByPolicy(P),"")}e.notTranslated&&g.push(Io(ae().staged.notTranslated,e.notTranslated),"");let h=o(P=>{i?g.push("<details>",`<summary>${P}</summary>`,""):g.push(`### ${P}`)},"sectionStart"),y=o(()=>{i&&g.push("","</details>"),g.push("")},"sectionEnd");if(c){for(let P of e.businessCaseAnalysis.trim().split(/\r?\n/))g.push(`> ${P}`);g.push("")}if(t$(e)&&g.push(ae().staged.noLiveApp(e.newTestsCreated.length),""),u&&e.newTestsCreated.length){let P=new Map;for(let se of e.newTestsCreated){if(se.testType!=="unit")continue;let ye=(se.testId.split("::").slice(1).join("::")||se.testId).replace(/\[.*\]$/,""),V=P.get(se.fileName)??{functions:new Set,endpoints:[],descriptions:new Map};se.endpoint&&!V.endpoints.includes(se.endpoint)&&V.endpoints.push(se.endpoint);let M=se.description?.trim()??"",ot=V.descriptions.get(ye)??[];ot.includes(M)||ot.push(M),V.functions.add(ye),V.descriptions.set(ye,ot),P.set(se.fileName,V)}let ee=e.newTestsCreated.filter(se=>se.testType!=="unit"),Y=ee.length+[...P.values()].reduce((se,ye)=>se+ye.functions.size,0);h(ae().testRecommendationsImplementedHeader(Y));for(let[se,{functions:ye,endpoints:V,descriptions:M}]of P){let ot=ye.size;g.push(ae().staged.unitTestsInFile(`\`${se}\``,ot,V.map(at=>`\`${at}\``).join(", ")),"");let qe=new Map;for(let[at,Yt]of M){let Dt=Yt.join("\0"),nt=qe.get(Dt)??{fns:[],descriptions:Yt};nt.fns.push(at),qe.set(Dt,nt)}let Mn=0;for(let{fns:at,descriptions:Yt}of qe.values()){g.push(`${++Mn}. ${at.map(nt=>`\`${nt}\``).join(", ")}`);let Dt=[...new Set(Yt.flatMap(nt=>jpe(nt)))];for(let nt of Dt)g.push(` - ${nt}`)}g.push("")}for(let se of ee){let ye=se.testId?Jt(p(se.testId)):e$(se.testType),V=se.fileName?` (\`${se.fileName}\`)`:"",M=se.endpoint?`
|
|
160
160
|
\`${se.endpoint}\``:"",ot=se.description?`
|
|
161
161
|
${se.description.trim()}`:"";g.push(`- ${ye}${V}${M}${ot}`)}y()}let E=(e.testMaintenance??[]).filter(P=>U2.has(P.action));if(u&&E.length){h(ae().staged.testMaintenanceHeader),g.push(ae().maintenanceTableHeader),g.push("|-----------|----------|------|--------|--------|-------|");for(let P of E)g.push(`| ${Ge(e$(P.testType))} | ${Ge(P.endpoint)} | \`${Ge(P.fileName)}\` | ${Ge(P.description)} | ${M2(P.beforeStatus,P.beforeDetails)} | ${M2(P.afterStatus,P.afterDetails)} |`);y()}let C=o(P=>P.startsWith(LA)||P.includes(jA),"hasDeclineNote"),I=(e.testMaintenance??[]).filter(P=>C(P.afterDetails)&&(!U2.has(P.action)||!V2.has(P.afterStatus??"")));if(u&&I.length){h(ae().staged.declinedMaintenanceHeader);for(let P of I)g.push(`- \`${Ge(P.fileName)}\`: ${Ge(G2(P.afterDetails))}`);y()}if(u&&r.length){h(ae().staged.existingEvidenceHeader);let P=new Map;for(let ee of r){let Y=`${ee.check}\0${ee.url??""}\0${ee.revision??""}`;P.set(Y,[...P.get(Y)??[],ee])}for(let[,[ee,...Y]]of P){let se=ee.url?`[${Jt(ee.check)}](${ee.url})`:Jt(ee.check);g.push(ae().staged.trustedCheckPassed(se,ee.revision?Jt(ee.revision.slice(0,7)):""),"");for(let ye of[ee,...Y])g.push(`- ${Jt(ye.behavior)}`);g.push("")}y()}if(u&&e.testResults.length){h(ae().staged.testResultsHeader);let P=Lpe(e),ee=P.some(V=>V.test),Y=P.some(V=>r$(e,V)),se=ee?ae().staged.unitResultsTableHeader:ae().staged.resultsTableHeader;g.push(Y?`${se} ${ae().columnVideo} |`:se),g.push(`${ee?"|---------|-----------|----------|------|-------|--------|---------|":"|---------|-----------|----------|--------|---------|"}${Y?"-------|":""}`);for(let V of P){let M=V.details.replace(/(\S+\.(?:py|ts|js|spec\.\w+))/gi,"`$1`"),ot=V.testId?Jt(Ge(p(V.testId))):"\u2014",qe=ee?` ${V.test?`\`${Ge(V.test)}\``:""} | ${V.cases??""} |`:"",Mn=r$(e,V),at=Y?` ${Mn?ae().videoDownloadLink(Mn):"\u2014"} |`:"";g.push(`| ${ot} | ${Ge(e$(V.testType))} | ${Ge(V.endpoint)} |${qe} ${Ge(n$(V.status))} | ${Ge(M)} |${at}`)}let ye=(e.testVideos??[]).find(V=>V.artifactsUrl)?.artifactsUrl;!Y&&ye&&g.push("",ae().videosArtifactFallback(ye)),y()}if(e.requirements?.length){let P=e.requirements.flatMap(V=>V.clauses),ee=o(V=>V.status==="Pass"||V.status==="Passed, test not kept","passes"),Y=P.filter(ee).length;h(ae().staged.requirementsHeader(Y,P.length));let se=o(V=>Io(ae().staged.clauseStatuses,V.status),"status"),ye=o(V=>(V.status==="Not tested"||V.status==="Passed, test not kept")&&V.notTested?`${se(V)}: ${V.notTested}`:V.findings.length?`${se(V)} \u2014 ${V.findings.join(", ")}`:se(V),"result");if(u){g.push(ae().staged.requirementsTableHeader),g.push("|-------------|--------|-------|--------|");for(let V of e.requirements)V.clauses.forEach((M,ot)=>{let qe=ot===0?`**${Ge(V.label)}**${V.statement?` ${Ge(V.statement)}`:""}`:"",Mn=`${Jt(Ge(p(M.id)))}${P2(M)}${M.text?` ${Ge(M.text)}`:""}`,at=new Map;for(let nt of M.tests){let In=nt.fileName??p(nt.testId),dt=at.get(In)??{fns:new Set};for(let Cn of nt.functions)dt.fns.add(Cn);dt.video??=nt.fileName?Ope(e,nt.fileName,nt.repository):void 0,at.set(In,dt)}let Yt=at.size?[...at].map(([nt,{fns:In,video:dt}])=>`${Jt(Ge(nt))}${In.size?` \u2014 ${[...In].map(Cn=>`\`${Ge(Cn)}\``).join(", ")}`:""}${dt?` ${ae().videoDownloadLink(dt)}`:""}`).join("<br>"):"\u2014",Dt=V.source==="could-break"&&M.status==="Pass"?ae().staged.regressionGuard:"";g.push(`| ${qe} | ${Mn} | ${Yt} | ${Ge(ye(M)+Dt)} |`)})}else{g.push(ae().staged.requirementsSummaryTableHeader),g.push("|-------------|-----------------|-------------|");for(let V of e.requirements){let M=V.clauses.filter(ee).length,ot=V.clauses.filter(qe=>!ee(qe)).map(qe=>`${Jt(Ge(p(qe.id)))}${P2(qe)} ${Ge(ye(qe))}`);g.push(`| **${Ge(V.label)}**${V.statement?` ${Ge(V.statement)}`:""} | ${M}/${V.clauses.length} | ${ot.join("<br>")||"\u2014"} |`)}}y()}if(u&&e.changes?.length&&!e.requirements?.length){let P=e.executionCoverage,ee=P?ae().staged.coverageCaption(P.generated,P.modified,P.verified,P.executed):"";h(`${ae().staged.behaviourCoverageHeader}${ee}`),g.push(ae().staged.coverageTableHeader),g.push("|-----------|--------|-----------|----------------|");for(let Y of e.changes){let se=Y.testedBy.length?Y.testedBy.map(V=>`\`${Ge(V)}\``).join(", "):Y.writtenBy.length?ae().staged.writtenNotRun:"\u2014",ye=Y.maintainedBy.length?Y.maintainedBy.map(V=>`\`${Ge(V)}\``).join(", "):"\u2014";g.push(`| ${Ge(Y.text)} | \`${Ge(Y.source)}\` | ${se} | ${ye} |`)}y()}if(e.userJourneys?.length){let P=e.userJourneys.filter(Y=>Y.status==="Pass"&&!Y.problems.length).length;h(`\u{1F9ED} User Journeys Covered (${P}/${e.userJourneys.length} walked end to end)`);let ee=e.userJourneys.some(Y=>i$(e,Y.fileName));g.push(`| Journey | Test | Status | Notes |${ee?` ${ae().columnVideo} |`:""}`),g.push(`|---------|------|--------|-------|${ee?"-------|":""}`);for(let Y of e.userJourneys){let se=Y.fileName?`\`${Ge(Y.fileName)}\`${Y.test?` \u2014 ${Ge(Y.test)}`:""}`:"\u2014",ye=Y.source&&Y.source!=="inferred"?`; described in the ${Y.source==="spec"?"spec":"PR description"}`:"; inferred from the app",V=(Y.uncovered?`not covered: ${Y.uncovered}`:Y.problems.length?`does not walk it end to end: ${Y.problems.join("; ")}`:`from ${Y.entry}, ${Y.steps} steps`)+ye,M=ee?i$(e,Y.fileName):void 0;g.push(`| ${Ge(Y.name)} | ${se} | ${Ge(Y.status)} | ${Ge(V)} |${ee?` ${M?ae().videoDownloadLink(M):"\u2014"} |`:""}`)}y()}if(l){let P=e.issuesFound.filter(Y=>!O2(Y)).sort(L2),ee=e.issuesFound.filter(O2).sort(L2);if(P.length){h(ae().staged.issuesFoundHeader);for(let Y of P)g.push(j2(Y));y()}if(ee.length){g.push(`### ${ae().configErrorsHeader}`);for(let Y of ee)g.push(j2(Y));g.push("")}}let b=e.testPackages??[],D=e.dependencyChanges??[];if(b.length){g.push(ae().staged.testPackagesHeader,"");for(let P of b)g.push(`- ${ae().staged.testPackageLine(P.directory,P.entrypoint,Object.entries(P.dependencies??{}).map(([ee,Y])=>P.runner==="pytest"?`${ee}==${Y}`:`${ee}@${Y}`).join(", "))}`);D.length||g.push(`- ${ae().staged.appManifestsUntouched}`),g.push("")}if(D.length){g.push(ae().staged.dependencyChangesHeader,"");for(let P of D)g.push(`- ${ae().staged.dependencyChangeLine(P.package,P.repository?`${P.repository}: ${P.manifest}`:P.manifest,(P.reason??"").replace(/\s+/g," ").trim())}`);g.push("")}let N=(e.caveats??[]).filter(P=>P.kind!=="tests-not-executed"||P.subject==="written-cases"||!t$(e));if(N.length){g.push(ae().staged.caveatsHeader,"");for(let P of N)g.push(`- ${P.text}`);g.push("")}if(l&&e.nextSteps.length){g.push(ae().nextStepsHeader,"");for(let P of e.nextSteps)g.push(`- ${P.trim()}`);g.push("")}let W=g.join(`
|
|
162
162
|
`).replace(/\n{3,}/g,`
|
|
@@ -164,7 +164,7 @@ ${i}
|
|
|
164
164
|
`).trim()+`
|
|
165
165
|
`;if(n!=="testbot-pr"||Buffer.byteLength(W,"utf8")<=64e3)return W;let K=o(P=>e.testResults.filter(ee=>ee.status===P).length,"counts"),pe=e.requirements?.flatMap(P=>P.clauses)??[],Pe=o(P=>Array.from(P.replace(/\s+/g," ").trim()).slice(0,300).join(""),"snippet"),tt=o(P=>Pe(P).replace(/[&<>\\`*_[\]{}()#+.!|~-]/g,ee=>`&#${ee.charCodeAt(0)};`),"plainSnippet");return[N2,...a?[ae().staged.testsSourcePullRequest(Jt(Pe(a)))]:[],ae().staged.largeReportSummary(e.requirements?.length??0,pe.length,K("Pass"),K("Fail"),K("Skipped")),ae().staged.largeReportNotice,...e.validation?[ae().staged.largeReportValidation(tt(e.validation.sufficiency),tt(e.validation.rationale),e.validation.gaps.length)]:[],...(e.caveats??[]).slice(0,3).map(P=>`> \u26A0\uFE0F ${tt(P.text)}`),...t$(e)?[ae().staged.noLiveApp(e.newTestsCreated.length)]:[],...t.runUrl?[ae().staged.viewRun(t.runUrl)]:[],""].join(`
|
|
166
166
|
|
|
167
|
-
`)}o(J2,"renderPrBody");var Vs=Se(require("fs")),s$=Se(require("path"));var Gpe="report.json",zpe="report-display.json",
|
|
167
|
+
`)}o(J2,"renderPrBody");var Vs=Se(require("fs")),s$=Se(require("path"));var Gpe="report.json",zpe="report-display.json",c1e={en:"English",ja:"Japanese"};function H2(e){let t=s$.join(e,zpe);if(Vs.existsSync(t))try{return JSON.parse(Vs.readFileSync(t,"utf-8"))}catch{}let n=s$.join(e,Gpe);return Vs.existsSync(n)?JSON.parse(Vs.readFileSync(n,"utf-8")):void 0}o(H2,"readDisplayReport");function Y2(e,t){return t?`<!-- skyramp-testbot-run: ${t} -->
|
|
168
168
|
${e}`:e}o(Y2,"withRunMarker");var ga=Se(require("fs")),fa=Se(require("path"));var my=["build","chore","ci","docs","feat","fix","perf","refactor","revert","style","test"],qpe=["build","ci","docs","feat","fix","perf","refactor","revert","style","test"],Jpe="amannn/action-semantic-pull-request",Pn=o(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObj");function W2(e){return typeof e!="string"?!1:e.split("@")[0].split("/").some(n=>n.toLowerCase().split(/[-_.]/).includes("dco"))}o(W2,"usesDco");function Z2(e){return typeof e=="string"&&(/\bdco-check\b/.test(e)||/signed-off-by/i.test(e))}o(Z2,"scriptChecksDco");function Hpe(e){if(!Pn(e)||!Pn(e.jobs))return!1;for(let t of Object.values(e.jobs))if(Pn(t)){if(W2(t.uses))return!0;if(Array.isArray(t.steps)){for(let n of t.steps)if(Pn(n)&&(W2(n.uses)||Z2(n.run)||Pn(n.with)&&Object.values(n.with).some(Z2)))return!0}}return!1}o(Hpe,"workflowChecksDco");function tq(e){let t=fa.join(e,".github","workflows"),n;try{n=ga.readdirSync(t).filter(i=>/\.ya?ml$/i.test(i)).sort()}catch{return[]}return n.flatMap(i=>{try{return[{file:fa.join(".github","workflows",i),doc:Vi(ga.readFileSync(fa.join(t,i),"utf-8"))}]}catch{return[]}})}o(tq,"workflows");function Ype(e){return!Pn(e)||!Pn(e.jobs)?[]:Object.values(e.jobs).flatMap(t=>Pn(t)&&Array.isArray(t.steps)?t.steps.filter(Pn):[])}o(Ype,"steps");function Wpe(e){let t=fa.join(".github","dco.yml");if(ga.existsSync(fa.join(e,t)))return{file:t};let n=tq(e).find(i=>Hpe(i.doc));return n&&{file:n.file}}o(Wpe,"signOffRule");var K2=o(e=>typeof e=="string"?e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean):void 0,"inputList");function Zpe(e){for(let t of tq(e)){let n=Ype(t.doc).find(s=>typeof s.uses=="string"&&s.uses.split("@")[0].trim().toLowerCase()===Jpe);if(!n)continue;let i=Pn(n.with)?n.with:{},r=K2(i.scopes);return{file:t.file,types:K2(i.types)??my,...r?.length?{scopes:r}:{},scopeRequired:i.requireScope===!0||String(i.requireScope).trim()==="true"}}}o(Zpe,"semanticPrTitleRule");var Kpe=["package.json",".commitlintrc",".commitlintrc.json",".commitlintrc.yaml",".commitlintrc.yml",".commitlintrc.js",".commitlintrc.cjs",".commitlintrc.mjs",".commitlintrc.ts",".commitlintrc.cts","commitlint.config.js","commitlint.config.cjs","commitlint.config.mjs","commitlint.config.ts","commitlint.config.cts","commitlint.config.mts"],Xpe=["type-enum","scope-enum","scope-empty","subject-case","header-max-length","body-max-line-length"];function nq(e){let t=[];for(let n of e)n==="@commitlint/config-conventional"||n==="@commitlint/config-angular"?t.push(n):t.length=0;return t}o(nq,"knownPresets");var efe={Disabled:"0",Warning:"1",Error:"2"};function tfe(e){return e.replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`|\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g,t=>t.startsWith("/")?t.replace(/[^\r\n]/g," "):t)}o(tfe,"withoutComments");function X2(e,t){let n=new RegExp(`["']?${t}["']?\\s*:\\s*`).exec(e);if(!n)return;let i=n.index+n[0].length;if(e[i]!=="[")return null;let r=0;for(let s=i;s<e.length;s++)if(e[s]==="[")r++;else if(e[s]==="]"&&--r===0){if(!/^\s*(?:as\s+const\s*)?(?:[,}]|$)/.test(e.slice(s+1)))return null;let a=e.slice(i,s+1).replace(/\bRuleConfigSeverity\.(\w+)/g,(u,l)=>efe[l]??u).replace(/,(\s*\])/g,"$1"),c=a.replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/g,'""');try{return JSON.parse(c),Vi(a)}catch{return null}}}o(X2,"ruleFromSource");var rq=o(e=>Object.fromEntries(Xpe.map(t=>[t,e(t)])),"pickRules");function eq(e,t){if(!Pn(t))return;let n=[].concat(t.extends??[]),i=Pn(t.rules)?t.rules:{};return{file:e,presets:nq(n),rules:rq(r=>i[r])}}o(eq,"configFromObject");function nfe(e){for(let t of Kpe){let n;try{n=ga.readFileSync(fa.join(e,t),"utf-8")}catch{continue}if(/\.[cm]?[jt]s$/.test(t)){let r=tfe(n),s=/(?:^|[,{])\s*["']?extends["']?\s*:\s*/.exec(r),a=s?X2(r.slice(s.index),"extends"):void 0,c=s?/^(["'])([^"']+)\1\s*(?:[,}]|$)/.exec(r.slice(s.index+s[0].length))?.[2]:void 0,u=Array.isArray(a)?a:c?[c]:[];return{file:t,presets:nq(u),rules:rq(l=>X2(r,l))}}let i;try{i=Vi(n)}catch{return}if(t!=="package.json")return eq(t,i);if(Pn(i)&&Pn(i.commitlint))return eq(t,i.commitlint)}}o(nfe,"commitlintConfig");function Bu(e){if(!Array.isArray(e))return;let t=Number(e[0]);if(t===1||t===2)return[String(e[1]??"always"),e[2]]}o(Bu,"ruleWhenOn");var o$=o(e=>Array.isArray(e)&&e.every(t=>typeof t=="string")?e:void 0,"stringList");function rfe(e,t){if(!e)return t?"not-capitalized":void 0;let[n,i]=e,r=typeof i=="string"?[i]:o$(i)??[];if(n==="always"&&r.length===1&&r[0]==="lower-case")return"lower-case";if(n==="always"&&r.length===1&&r[0]==="sentence-case")return"sentence-case";if(n==="never"&&r.some(s=>["sentence-case","start-case","pascal-case","upper-case"].includes(s)))return"not-capitalized"}o(rfe,"subjectCaseOf");function ife(e){let t=nfe(e);if(!t)return;let{file:n,rules:i}=t,r=t.presets.at(-1)==="@commitlint/config-angular",s=o(C=>t.presets.length>0&&i[C]===void 0,"preset"),a=Bu(i["type-enum"]),c=a?.[0]==="always"?o$(a[1]):s("type-enum")?r?qpe:my:void 0,u=c===void 0,l=c??my;u&&console.warn(`[commit-rules] ${n}: allowed commit types could not be read; using a conventional header fallback. Additional preset rules may still reject it.`);let A=Bu(i["scope-enum"]),p=A?.[0]==="always"?o$(A[1]):void 0,g=o((C,I)=>{let b=Bu(i[C]);return b?typeof b[1]=="number"?b[1]:void 0:s(C)?I:void 0},"limit"),h=rfe(Bu(i["subject-case"]),s("subject-case")),y=g("header-max-length",r?72:100)??(u&&i["header-max-length"]===void 0?Ui:void 0),E=g("body-max-line-length",t.presets.includes("@commitlint/config-conventional")?100:void 0);return{file:n,types:l,...u?{typesFromFallback:!0}:{},...u&&!h&&i["subject-case"]===void 0?{fallbackSubjectCase:"not-capitalized"}:{},...p?.length?{scopes:p}:{},scopeRequired:Bu(i["scope-empty"])?.[0]==="never",...Bu(i["scope-empty"])?.[0]==="always"?{scopeForbidden:!0}:{},...h?{subjectCase:h}:{},...y?{headerMaxLength:y}:{},...E?{bodyMaxLineLength:E}:{}}}o(ife,"commitlintRule");function iq(e){let t=Wpe(e),n=ife(e),i=Zpe(e);return{...t?{signOff:t}:{},...n?{commitlint:n}:{},...i?{prTitle:i}:{}}}o(iq,"readCommitRules");function sfe(e){let t=[e.commitlint,e.prTitle].filter(a=>!!a);if(!t.length)return;let n=t.map(a=>a.types).reduce((a,c)=>a.filter(u=>c.includes(u)));n.length||console.warn(`[commit-rules] ${t.map(a=>a.file).join(", ")}: no common commit type; using ${t[0].types.join(", ")} from ${t[0].file}. This may fail another rule.`);let i=t.map(a=>a.subjectCase),r=i.includes("lower-case")?"lower-case":i.find(a=>a!==void 0)??t.find(a=>a.fallbackSubjectCase)?.fallbackSubjectCase,s=Math.min(...t.map(a=>a.bodyMaxLineLength??1/0));return{rules:t,types:n.length?n:t[0].types,scopeRequired:t.some(a=>a.scopeRequired),...r?{subjectCase:r}:{},headerMaxLength:Math.min(Ui,...t.map(a=>a.headerMaxLength??1/0)),...Number.isFinite(s)?{bodyMaxLineLength:s}:{}}}o(sfe,"mergedHeaderRules");function yy(e,t){return e.scopeForbidden?!1:e.scopes?e.scopes.some(n=>{if(n===t)return!0;try{return new RegExp(`^(?:${n})$`).test(t)}catch{return!1}}):!0}o(yy,"allowsScope");function ofe(e,t){let n=e.find(s=>s.scopes)?.scopes??[],i=n.filter(s=>/^[\w./-]+$/.test(s)&&e.every(a=>yy(a,s)));if(!i.length)return e.every(s=>yy(s,"tests"))||console.warn(`[commit-rules] ${e.map(s=>s.file).join(", ")}: no usable required scope; using tests, which may fail the declared scope rules (${n.join(", ")}).`),"tests";let r=o(s=>t.some(a=>a.startsWith(`${s}/`)||a.split("/").slice(0,-1).includes(s)),"under");return[...i].filter(r).sort((s,a)=>a.length-s.length)[0]??i[0]}o(ofe,"pickScope");var sq=/^([A-Za-z][\w-]*)(?:\(([^)]*)\))?!?:\s*(.*)$/,afe=o(e=>e.split(/(`.*?`|".*?"|'.*?')/).map((t,n)=>n%2?t:t.toLowerCase()).join(""),"lowerOutsideQuotes");function oq(e,t){return t==="lower-case"?afe(e):t==="sentence-case"?e.charAt(0).toUpperCase()+e.slice(1):t==="not-capitalized"&&/^[A-Z]/.test(e)?e.replace(/^\S+/,n=>n.toLowerCase()):e}o(oq,"withSubjectCase");function cfe(e,t){return oq(e.trim().replace(/\.+$/,"").trim()||"add tests",t)}o(cfe,"conformSubject");function aq(e,t){let[n,...i]=e.replace(/\s+$/,"").split(`
|
|
169
169
|
`),r=sq.exec(n);return[t.commitlint,t.prTitle].every(s=>{if(!s)return!0;if(!s.typesFromFallback&&(!r||!s.types.includes(r[1]))||s.headerMaxLength&&n.length>s.headerMaxLength)return!1;let a=s.bodyMaxLineLength;if(a&&i.some(u=>u.length>a&&!/\bhttps?:\/\/\S+/.test(u)))return!1;let c=r?.[2];if(s.scopeRequired&&!c||c&&!yy(s,c)||r&&!r[3].trim())return!1;if(s.subjectCase){if(!r)return!1;let u=r[3],l=u.replace(/`.*?`|".*?"|'.*?'/g,"").trim();if(/^[\p{Ll}\p{Lu}\p{Lt}]/u.test(u)&&!/^\d/.test(l)&&oq(l,s.subjectCase)!==l)return!1}return!0})}o(aq,"matchesCommitRules");function ufe(e,t){if(e.length<=t)return e;let n=e.slice(0,t-1),i=n.lastIndexOf(" ");return`${(i>0?n.slice(0,i):n).replace(/[\s.,;:]+$/,"")}\u2026`}o(ufe,"fitSubject");function lfe(e,t){if(e.length<=t)return[e];let n=/^\s*/.exec(e)?.[0]??"",i=[],r="";for(let s of e.trim().split(/\s+/))r&&r.length+1+s.length>t?(i.push(r),r=n+s):r?r=`${r} ${s}`:r=n+s;return r&&i.push(r),i}o(lfe,"wrap");function cq(e,t,n){let i=sfe(t);if(!i)return e;let[r,...s]=e.replace(/\s+$/,"").split(`
|
|
170
170
|
`),a=sq.exec(r.trim()),c=a&&[...my,...i.types].some(b=>b.toLowerCase()===a[1].toLowerCase())?a:null,u=c?.[1].toLowerCase(),l=c?c[3]:r.replace(/^\s*Skyramp Testbot:\s*/i,""),A=c?.[2]?.trim()||void 0;A&&t.commitlint&&!t.commitlint.scopes&&(A=A.toLowerCase());let p=[u,"test","chore"].find(b=>!!b&&i.types.includes(b))??i.types[0],g=A&&i.rules.every(b=>yy(b,A))?A:void 0;!g&&i.scopeRequired&&(g=ofe(i.rules,n));let h=g?`${p}(${g}): `:`${p}: `,y=h+ufe(cfe(l,i.subjectCase),i.headerMaxLength-h.length),E=s.join(`
|
|
@@ -178,12 +178,12 @@ ${I.join(`
|
|
|
178
178
|
|
|
179
179
|
${n}`}o(Ey,"withSignOff");function a$(e){let t=/\b(claude|anthropic)\b/i;return e.split(`
|
|
180
180
|
`).filter(i=>{let r=i.trim();return!(/^co-authored-by:/i.test(r)&&t.test(r))&&!(/^[^\w\s]*\s*generated (?:with|by) /i.test(r)&&t.test(r))}).join(`
|
|
181
|
-
`).replace(/\s+$/,"")}o(a$,"stripAgentAttribution");var Iy="Skyramp-Pull-Request",ku="Skyramp-Delivery-Base",c$="Skyramp-Tested-Revision";var
|
|
181
|
+
`).replace(/\s+$/,"")}o(a$,"stripAgentAttribution");var Iy="Skyramp-Pull-Request",ku="Skyramp-Delivery-Base",c$="Skyramp-Tested-Revision";var w1e=["%H","%P","%an","%ae","%ce",`%(trailers:key=${Iy},valueonly,separator=%x2C)`,"%s",`%(trailers:key=${ku},valueonly,separator=%x2C)`,`%(trailers:key=${c$},valueonly,separator=%x2C)`];function uq(e,t){let n=e(["log","-1","--format=%B"]);if(!n.includes(`${Iy}:`)&&!n.includes(`${ku}:`))return;let i=n.split(`
|
|
182
182
|
`).filter(a=>!a.startsWith(`${ku}:`)).join(`
|
|
183
183
|
`).trimEnd(),r=t?`${i}
|
|
184
184
|
${ku}: ${t}`:i;e(["log","-1","--format=%(trailers:key=Signed-off-by,valueonly)"]).split(`
|
|
185
|
-
`).some(a=>a.trim().toLowerCase()===`${ws} <${Lo}>`.toLowerCase())&&(r=Ey(r,{name:ws,email:Lo})),e(["-c",`user.name=${ws}`,"-c",`user.email=${Lo}`,"commit","--amend","--allow-empty","-m",r])}o(uq,"amendDeliveryBase");var Cy=Se(require("fs")),nr=Se(require("path"));var
|
|
186
|
-
`)+1||r.length),a=dq(s);for(let c of n)a.delete(c);return{name:LM(i.key,zb([i])),key:i.key,runs:a,words:u$(s).map(c=>c.word)}})}o(gq,"requirementTexts");var
|
|
185
|
+
`).some(a=>a.trim().toLowerCase()===`${ws} <${Lo}>`.toLowerCase())&&(r=Ey(r,{name:ws,email:Lo})),e(["-c",`user.name=${ws}`,"-c",`user.email=${Lo}`,"commit","--amend","--allow-empty","-m",r])}o(uq,"amendDeliveryBase");var Cy=Se(require("fs")),nr=Se(require("path"));var S1e=5*1024*1024;function Afe(e){try{return Cy.lstatSync(e),!0}catch{return!1}}o(Afe,"lexists");function lq(e){let t=ze(e,"adapt.json"),n=ze(e,"finalize.json"),i=ze(e,MA),r=new Map,s=o(A=>{let p=Rc(e.inputs,A);if("error"in p)return;let g=r.get(p.source.path)??{source:p.source,paths:new Set};return r.set(p.source.path,g),{repo:g.source.path,paths:g.paths}},"pathsOf"),a=o((A,p)=>nr.relative(A,nr.resolve(A,p.trim())).replace(/\/+$/,""),"norm"),c=o((A,p)=>{let g=p?.trim()&&s(A);if(!g)return;let h=a(g.repo,p);g.paths.add(h);for(let y of["__init__.py","conftest.py"]){let E=nr.join(nr.dirname(h),y);Cy.existsSync(nr.join(g.repo,E))&&g.paths.add(E)}},"addTest"),u=o((A,p)=>{if(typeof p!="string"||!p.trim())return;let g=s(A);if(!g)return;let h=a(g.repo,p);if($A(nr.join(g.repo,h)))return g.paths.add(h),{...g,rel:h}},"addEdited");for(let A of[...t?.items??[],...i?.tests??[],...i?.maintained??[]])c(A.repository,A.file);for(let A of n?.dependencies?.added??[]){let p=u(A.repository,A.manifest);if(p)for(let g of xx(p.repo,ey(p.repo,p.rel)))p.paths.add(g)}for(let A of n?.lint??[])for(let p of A.fixed??[])u(A.repository,p);for(let A of n?.support??[])u(A.repository,A.file);let l=ze(e,ty)?.packages??[];for(let A of new Set(l.map(p=>p.repository))){let p=s(A),g=l.filter(h=>h.repository===A).map(h=>h.dir);if(p)for(let{path:h}of qx(p.repo)){let y=a(p.repo,h),E=nr.join(p.repo,y);ny(y,g)&&!$x(y)&&(!Afe(E)||$A(E))&&p.paths.add(y)}}return new Map([...r.values()].map(({source:A,paths:p})=>[A,[...p].filter(g=>g&&g!==".."&&!g.startsWith(`..${nr.sep}`)&&!Mm(g))]))}o(lq,"deliverAllowlist");var Aq=Se(require("fs"));var pq=2*1024*1024;function pfe(e){let t=[];for(let n of e??[])if(n.state==="read")try{t.push({item:n,text:Aq.readFileSync(HO(n),"utf-8")})}catch{}return t}o(pfe,"readItemTexts");var VA=6,ffe=/[\p{L}\p{N}]+/gu,gfe=new RegExp("(?<=\\p{Ll})(?=\\p{Lu})|(?<=\\p{Lu})(?=\\p{Lu}\\p{Ll})","u");function u$(e){let t=[];for(let n of e.matchAll(ffe)){let i=n.index;for(let r of n[0].split(gfe))t.push({word:r.toLowerCase(),start:i,end:i+r.length}),i+=r.length}return t}o(u$,"wordsOf");var fq=o((e,t)=>e.slice(t,t+VA).map(n=>n.word).join(" "),"runAt");function dq(e){let t=u$(e),n=new Set;for(let i=0;i+VA<=t.length;i++)n.add(fq(t,i));return n}o(dq,"runsOf");function gq(e,t=[]){let n=new Set(t.flatMap(i=>[...dq(i)]));return pfe(e).map(({item:i,text:r})=>{let s=i.source==="other"?r:r.slice(r.indexOf(`
|
|
186
|
+
`)+1||r.length),a=dq(s);for(let c of n)a.delete(c);return{name:LM(i.key,zb([i])),key:i.key,runs:a,words:u$(s).map(c=>c.word)}})}o(gq,"requirementTexts");var V1e=VA/2;var hfe=o(e=>e.criteria.size?`${e.text.name} ${[...e.criteria].sort((t,n)=>t-n).map(t=>`AC${t}`).join(", ")}`:e.text.name,"copyName");function mfe(e,t){if(t.length===0)return[];let n=u$(e),i=[];for(let r=0;r+VA<=n.length;r++){let s=fq(n,r),a=t.find(p=>p.runs.has(s));if(!a)continue;let c=n[r].start,u=n[r+VA-1].end,l=a.criteria?.get(s)??[],A=i.at(-1);if(A&&c<=A.end){if(A.end=Math.max(A.end,u),A.text===a)for(let p of l)A.criteria.add(p)}else i.push({start:c,end:u,text:a,criteria:new Set(l)})}return i.map(r=>({start:r.start,end:r.end,name:hfe(r)}))}o(mfe,"copies");function by(e,t){let n=e;for(let i of mfe(e,t).reverse())n=`${n.slice(0,i.start)}(see ${i.name})${n.slice(i.end)}`;return n}o(by,"withoutRequirementText");function yfe(e,t,n){for(let i=t+1;i<e.length;i++){let r=e[i];if(r==="\\")i++;else{if(r===n)return i+1;if(r===`
|
|
187
187
|
`&&n!=="`")return i}}return e.length}o(yfe,"stringEnd");function Efe(e,t){let n=e.lastIndexOf(`
|
|
188
188
|
`,t-1)+1;if(e.slice(n,t).trim()!=="")return!1;let i=e.slice(0,n).trimEnd();return i===""||i.endsWith(":")}o(Efe,"isDocstring");function Ife(e){let t=[],n=o(r=>(e.indexOf(`
|
|
189
189
|
`,r)+1||e.length+1)-1,"lineEnd"),i=0;for(;i<e.length;){let r=e[i],s=e[i+1],a=i+1;if(r==="/"&&s==="*")a=e.indexOf("*/",i+2)<0?e.length:e.indexOf("*/",i+2)+2,t.push({start:i,end:a});else if(r==="/"&&s==="/"&&!/[:\w]/.test(e[i-1]??"")||r==="#"&&/^\s?$/.test(e[i-1]??"")&&!/[!{[]/.test(s??""))a=n(i),t.push({start:i,end:a});else if((r==='"'||r==="'")&&e.startsWith(r.repeat(3),i)){let c=e.indexOf(r.repeat(3),i+3);a=c<0?e.length:c+3,Efe(e,i)&&t.push({start:i,end:a})}else(r==='"'||r==="'"||r==="`")&&(a=yfe(e,i,r));i=a}return t}o(Ife,"commentRanges");var Cfe=/\b(?:test|it|describe|context|suite|scenario|specify|Run|DisplayName)(?:\.\w+)*(?:\.each\s*(?:\((?:[^()]|\([^()]*\))*\)|`[^`]*`))?\s*\(\s*("(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`)/g;function bfe(e,t){return[...e.matchAll(Cfe)].flatMap(n=>{if(t.some(r=>n.index>=r.start&&n.index<r.end))return[];let i=n.index+n[0].length;return[{start:i-n[1].length,end:i}]})}o(bfe,"titleRanges");function hq(e,t){if(t.length===0)return{content:e,cleaned:!1};let n=Ife(e),i=[];for(let c of n){let u=e.slice(c.start,c.end),l=by(u,t);l!==u&&i.push({...c,text:l})}let r=bfe(e,n),s=new Set(r.map(c=>e.slice(c.start+1,c.end-1)));for(let c of r){let u=e[c.start],l=e.slice(c.start+1,c.end-1),A=by(l,t);if(A===l)continue;let p=A;for(let g=2;s.has(p);g++)p=`${A} (${g})`;s.add(p),i.push({...c,text:`${u}${p}${u}`})}let a=e;for(let c of i.sort((u,l)=>l.start-u.start))a=`${a.slice(0,c.start)}${c.text}${a.slice(c.end)}`;return{content:a,cleaned:a!==e}}o(hq,"withoutRequirementTextInTestFile");function wfe(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=ze(e,"finalize.json");return t?t.ready!==!0?{ok:!1,reasons:[`finalize reported ready:false \u2014 not pushing (blockers: ${ud(t)||"unspecified"})`]}:{ok:!0,reasons:[]}:{ok:!1,reasons:["finalize.json not found \u2014 refusing to push unverified tests"]}}o(wfe,"validateDeliverInput");function Iq(e){return e.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"tests"}o(Iq,"slug");var Bfe="skyramp-testbot/";function kfe(e,t){return t||`${Bfe}${Iq(e)}-tests`}o(kfe,"testsBranchName");function Sfe(e,t,n,i){let r=(e??[]).filter(a=>a.repository.toLowerCase()===t.toLowerCase());if(!r.length&&i){let a=i.repository,c=[i.targetId,a.provider,a.providerAccountId,a.providerRepositoryId,i.number,t.toLowerCase(),n];return(0,GA.createHash)("sha256").update(JSON.stringify(c)).digest("hex").slice(0,32)}let s=r.length?[...new Set(r.map(a=>`${a.repository.toLowerCase()}#${a.number}`))].sort():[`branch ${n}`];return(0,GA.createHash)("sha256").update(s.join(`
|
|
@@ -195,9 +195,9 @@ ${ku}: ${t}`:i;e(["log","-1","--format=%(trailers:key=Signed-off-by,valueonly)"]
|
|
|
195
195
|
${n}`}:{prFailure:"unknown",prDetail:t}}o(Ffe,"thrownFailure");async function Pfe(e,t,n,i,r,s){let a=i.slug,c=i.path,u=ze(e,"finalize.json"),l=gq(e.inputs.requirementItems),A=iq(c),p=ze(e,"write.json"),g=p?.commit?.message||ze(e,"generate-unit.json")?.commitMessage,h=i.working,y=o(Bt=>Bt.split(`
|
|
196
196
|
`)[0],"subjectOf"),E=o(Bt=>by(a$(Bt),l),"publicText"),C=o((Bt,Wt)=>h&&!!Wt&&E(Bt).trim()===E(Wt).trim(),"authored"),I=o((Bt,Wt,rr)=>{let ct=E(Bt);return rr&&aq(ct,Wt)?ct:cq(ct,Wt,r)},"conform"),b=u?.commit?.message||n.commitMessage||"Skyramp Testbot: add tests",D=I(b,{commitlint:A.commitlint},C(b,g)),N=H2(e.outputsDir)??n,W=h?u?.pr?.title||n.prTitle||p?.commit?.prTitle:void 0,K=W||b,pe=h?N.prTitle:void 0,Pe=y(E(K))===y(E(b)),tt=(!h||!n.prTitle)&&Pe?N.commitMessage:void 0,P=pe||tt||K,ee=p?.commit?.prTitle||(g?y(g):void 0),Y=C(K,ee),se=A.prTitle?{prTitle:A.prTitle}:Y&&W&&!Pe?{}:{commitlint:A.commitlint},ye=y(I(P,se,Y)),V={name:ws,email:Lo},M=!!A.signOff;if(!M&&t?.listCommitChecks){let Bt=s?.headSha??Ht(c,["rev-parse","HEAD"]);try{M=(await t.listCommitChecks({repository:a,revision:Bt}))?.records.some(rr=>rr.name.trim().toLowerCase()==="dco"&&rr.headSha===Bt&&(!rr.repository||rr.repository.toLowerCase()===a.toLowerCase()))??!1}catch{console.warn(`[deliver] could not read commit checks for ${a}`)}}let ot=e.inputs.deliverRemote||"origin",qe=mq(c,Cq),Mn=mq(c,bq);if(qe&&!Mn)throw new Error(`${a}: the checkout records a merged base but not what it merged`);let at=qe?l$(void 0,void 0,c):s?s.headBranch||l$(e.inputs.headBranch,e.inputs.baseBranch,c):l$(void 0,void 0,c),Yt=e.inputs.pullRequests;s?.prNumber!=null&&!Yt?.some(Bt=>Bt.repository.toLowerCase()===a.toLowerCase())&&(Yt=[...Yt??[],{repository:a,number:String(s.prNumber)}]);let Dt=Yt?.some(Bt=>Bt.repository.toLowerCase()===a.toLowerCase())?void 0:e.inputs.deliveryOrigin,nt=qe||!Dt?Mn:void 0,In=e.inputs.scheduledDelivery,dt=In?(0,GA.createHash)("sha256").update(JSON.stringify([In,a.toLowerCase(),at])).digest("hex"):nt?Qfe(a,at,nt):Sfe(Yt,a,at,Dt),Cn=kfe(at,e.inputs.deliverBranch)+(In?`-scheduled-${dt}`:nt?`-merge-${dt}`:Dt?`-source-${Dt.number}-${dt}`:"");return{texts:l,shown:N,title:ye,unsigned:D,bot:V,signOff:M,remote:ot,base:at,owner:dt,testsBranch:Cn,origin:Dt,mergedBase:qe}}o(Pfe,"planCommit");function Mfe(e,t,n,i){let r=Ht(e,["interpret-trailers","--trailer",`${Iy}: ${t.owner}`,"--trailer",`${ku}: ${n}`,"--trailer",`${c$}: ${i}`],`${t.unsigned}
|
|
197
197
|
`);return t.signOff?Ey(r,t.bot):r}o(Mfe,"trailedMessage");async function Ofe(e,t,n,i,r,s){let a=S2(i.path,e.runDir),c=process.env.PATH;a.dir&&(process.env.PATH=Q2(a).PATH);try{return await Lfe(e,t,n,i,r,s)}finally{a.dir&&(process.env.PATH=c),a.cleanup()}}o(Ofe,"deliverOne");async function Lfe(e,t,n,i,r,s){let a=i.slug,c,u=!1,l;try{let A=i.path,p=await Pfe(e,t,n,i,r,s),{texts:g,shown:h,title:y,bot:E,remote:C,base:I,owner:b,testsBranch:D,origin:N,mergedBase:W}=p,K=a$(Y2(J2(xfe(h,e,i),{audience:"testbot-pr",runUrl:e.inputs.skyrampRunUrl??t.runUrl,requestedBy:e.inputs.requestedBy,sourcePullRequest:N&&`${N.repository.namespace}/${N.repository.name}#${N.number}`}),e.inputs.skyrampRunUrl))+`
|
|
198
|
-
`,pe=s?"pr-body.md":`pr-body-${Iq(a)}.md`,Pe=Gs.join(e.outputsDir,pe);Pr.writeFileSync(Pe,K);let tt=Ht(A,["rev-parse","HEAD"]),P=W??tt;Ht(A,["checkout","-B",D]),c=D,Ht(A,["reset"]);for(let M of r)Rfe(Gs.join(A,M),g);let ee=[];for(let M of r)try{Ht(A,["--literal-pathspecs","add","--",M])}catch{ee.push(M)}try{Ht(A,["diff","--cached","--quiet"])}catch{try{let M=Mfe(A,p,tt,P);Ht(A,["-c",`user.name=${E.name}`,"-c",`user.email=${E.email}`,"commit","-m",M])}catch(M){throw new vy(M)}u=!0}l=Ht(A,["rev-parse","HEAD"]);let Y,se=W??s?.headSha;if(u&&se&&se!==tt){let M=!1;try{Ht(A,["checkout","-q","-B",c,se]),M=!0,Ht(A,["-c",`user.name=${E.name}`,"-c",`user.email=${E.email}`,"cherry-pick","--keep-redundant-commits",l]),M=!1,uq(ot=>Ht(A,ot),se),l=Ht(A,["rev-parse","HEAD"])}catch(ot){try{Ht(A,["cherry-pick","--abort"])}catch{}Ht(A,["checkout","-q","-B",c,l]);let qe=Gl(Co(ot),1/0);if(W&&!M)throw ot;if(W)return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:C,base:I,committed:u,commitSha:l,pushed:!1,prAction:"skipped",prTitle:y,unstaged:ee,reason:`the tests do not apply to ${I} at ${W.slice(0,12)} without the merged revisions (${qe}), so no tests PR was opened`}};Y=`tests committed on the checkout's merge commit (re-cut onto ${se.slice(0,12)} failed: ${qe})`}}let ye=s?{}:{repositoryPath:A,repoSlug:a,devPr:null};if(!u){let M=await t.markTestsPrUnchanged({branch:c,...ye});return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:C,base:I,committed:!1,commitSha:l,pushed:!1,prAction:M.action==="unchanged"?"unchanged":"skipped",prUrl:M.url,prTitle:y,unstaged:ee,reason:M.action==="unchanged"?"no test changes to commit \u2014 existing tests PR annotated as unchanged":"no test changes to commit \u2014 nothing pushed, no PR opened"}}}let V=await t.publishTestsPr({repositoryPath:A,...ye,remote:C,branch:c,base:I,commitSha:l,title:y,bodyFile:Pe,mode:e.inputs.deliverMode,deliveryOwner:b,...e.inputs.firstQualification?{firstQualification:!0}:{},runUrl:e.inputs.skyrampRunUrl,signal:e.signal,deadlineMs:e.deadlineMs});return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:C,base:V.base,requestedBase:I,committed:u,commitSha:l,pushed:V.pushed,...V.pushedCommits?{pushedCommits:V.pushedCommits}:{},...V.deliveredCommit?{deliveredCommit:V.deliveredCommit}:{},prAction:V.action,...V.retargetedAs?{retargetedAs:V.retargetedAs}:{},prUrl:V.url,prTitle:y,...V.failure?{prFailure:V.failure,prDetail:V.detail}:{},...Y?{cutNote:Y}:{},...V.action==="skipped"&&V.detail?{reason:V.detail}:{},unstaged:ee}}}catch(A){return{thrown:!0,record:{schemaVersion:1,repository:a,branch:c,committed:u,commitSha:l,pushed:!1,prAction:"failed",...Ffe(A),unstaged:[]}}}}o(Lfe,"deliverRepository");var
|
|
198
|
+
`,pe=s?"pr-body.md":`pr-body-${Iq(a)}.md`,Pe=Gs.join(e.outputsDir,pe);Pr.writeFileSync(Pe,K);let tt=Ht(A,["rev-parse","HEAD"]),P=W??tt;Ht(A,["checkout","-B",D]),c=D,Ht(A,["reset"]);for(let M of r)Rfe(Gs.join(A,M),g);let ee=[];for(let M of r)try{Ht(A,["--literal-pathspecs","add","--",M])}catch{ee.push(M)}try{Ht(A,["diff","--cached","--quiet"])}catch{try{let M=Mfe(A,p,tt,P);Ht(A,["-c",`user.name=${E.name}`,"-c",`user.email=${E.email}`,"commit","-m",M])}catch(M){throw new vy(M)}u=!0}l=Ht(A,["rev-parse","HEAD"]);let Y,se=W??s?.headSha;if(u&&se&&se!==tt){let M=!1;try{Ht(A,["checkout","-q","-B",c,se]),M=!0,Ht(A,["-c",`user.name=${E.name}`,"-c",`user.email=${E.email}`,"cherry-pick","--keep-redundant-commits",l]),M=!1,uq(ot=>Ht(A,ot),se),l=Ht(A,["rev-parse","HEAD"])}catch(ot){try{Ht(A,["cherry-pick","--abort"])}catch{}Ht(A,["checkout","-q","-B",c,l]);let qe=Gl(Co(ot),1/0);if(W&&!M)throw ot;if(W)return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:C,base:I,committed:u,commitSha:l,pushed:!1,prAction:"skipped",prTitle:y,unstaged:ee,reason:`the tests do not apply to ${I} at ${W.slice(0,12)} without the merged revisions (${qe}), so no tests PR was opened`}};Y=`tests committed on the checkout's merge commit (re-cut onto ${se.slice(0,12)} failed: ${qe})`}}let ye=s?{}:{repositoryPath:A,repoSlug:a,devPr:null};if(!u){let M=await t.markTestsPrUnchanged({branch:c,...ye});return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:C,base:I,committed:!1,commitSha:l,pushed:!1,prAction:M.action==="unchanged"?"unchanged":"skipped",prUrl:M.url,prTitle:y,unstaged:ee,reason:M.action==="unchanged"?"no test changes to commit \u2014 existing tests PR annotated as unchanged":"no test changes to commit \u2014 nothing pushed, no PR opened"}}}let V=await t.publishTestsPr({repositoryPath:A,...ye,remote:C,branch:c,base:I,commitSha:l,title:y,bodyFile:Pe,mode:e.inputs.deliverMode,deliveryOwner:b,...e.inputs.firstQualification?{firstQualification:!0}:{},runUrl:e.inputs.skyrampRunUrl,signal:e.signal,deadlineMs:e.deadlineMs});return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:C,base:V.base,requestedBase:I,committed:u,commitSha:l,pushed:V.pushed,...V.pushedCommits?{pushedCommits:V.pushedCommits}:{},...V.deliveredCommit?{deliveredCommit:V.deliveredCommit}:{},prAction:V.action,...V.retargetedAs?{retargetedAs:V.retargetedAs}:{},prUrl:V.url,prTitle:y,...V.failure?{prFailure:V.failure,prDetail:V.detail}:{},...Y?{cutNote:Y}:{},...V.action==="skipped"&&V.detail?{reason:V.detail}:{},unstaged:ee}}}catch(A){return{thrown:!0,record:{schemaVersion:1,repository:a,branch:c,committed:u,commitSha:l,pushed:!1,prAction:"failed",...Ffe(A),unstaged:[]}}}}o(Lfe,"deliverRepository");var dVe={name:"deliver",timeoutMinutes:5,execute:Dfe,validateInput:o(e=>{let t=Wx(e);return t?{ok:!1,reasons:[t]}:wfe(e)},"validateInput"),requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var vq=Se(require("fs"));var jfe="SKYRAMP_AZURE_SUPERVISED",Vfe=3;function Gfe(e,t=process.env){t[jfe]==="1"?vq.writeSync(Vfe,`${JSON.stringify(e)}
|
|
199
199
|
`):process.stdout.write(e.command!==void 0?`${e.command}
|
|
200
|
-
`:e.text??"")}o(Gfe,"writeFrame");function zfe(e){Gfe({command:e})}o(zfe,"writeAzureCommand");function wq(e){return e.replace(/%/g,"%AZP25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}o(wq,"escapeData");function qfe(e){return wq(e).replace(/;/g,"%3B").replace(/]/g,"%5D")}o(qfe,"escapeProperty");function Jfe(e,t,n){let i=Object.entries(t).map(([r,s])=>`${r}=${qfe(s)}`).join(";");return`##vso[${e}${i?` ${i}`:""}]${wq(n)}`}o(Jfe,"vsoCommand");function Hfe(e){if(!e)return[];let t=e.split(/\r?\n/).filter(n=>n.trim()&&n!==e);return[e,...t].map(n=>Jfe("task.setsecret",{},n))}o(Hfe,"setSecretLines");function Bq(e,t=zfe){for(let n of Hfe(e))t(n)}o(Bq,"azureSetSecret");function qA(e){return e.replace(/\/+$/,"")}o(qA,"withoutTrailingSlash");function d$(e){let t=new URL(e),n=t.pathname.split("/").filter(Boolean);if(n.length)return decodeURIComponent(n[n.length-1]);if(t.hostname.endsWith(".visualstudio.com"))return t.hostname.split(".")[0];throw new Error(`SYSTEM_COLLECTIONURI "${e}" names no organization`)}o(d$,"azureOrganization");var Yfe=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,48}[A-Za-z0-9])?$/,Wfe=/[\\/:*?"<>|;#${},+=[\]%\p{Cc}\p{Cf}]/u;function kq(e){return e.length>0&&e.length<=64&&e===e.trim()&&!Wfe.test(e)&&!/[^\S ]/u.test(e)&&!/^[._]/.test(e)&&!e.endsWith(".")}o(kq,"isName");function wy(e){return A$(`${e.namespace}/${e.name}`)}o(wy,"azureRepositoryOfSource");function A$(e){let t=e.indexOf("/"),n=e.lastIndexOf("/"),i=e.slice(0,t),r=e.slice(t+1,n),s=e.slice(n+1);if(t<0||t===n||!Yfe.test(i)||!kq(r)||!kq(s))throw new Error(`"${e}" is not an Azure DevOps organization/project/repository`);return{organization:i,project:r,name:s}}o(A$,"azureRepositoryOf");function Sq(e,t){let n=d$(e);if(n.toLowerCase()!==t.organization.toLowerCase())throw new Error(`${t.organization}/${t.project}/${t.name} is not in ${n}, the Azure DevOps organization this job runs in`)}o(Sq,"inOrganization");function Qq(e,t){return Sq(e,t),`${qA(e)}/${encodeURIComponent(t.project)}/_git/${encodeURIComponent(t.name)}`}o(Qq,"azureCloneUrl");function p$(e,t){return Sq(e,t),`${qA(e)}/${encodeURIComponent(t.project)}/_apis/git/repositories/${encodeURIComponent(t.name)}`}o(p$,"azureRepositoryApi");var Zfe="7.1",zA=class extends Error{constructor(n,i){super(n);this.status=i}status;static{o(this,"AzureRestError")}};async function f$(e){let t=e.accept??"application/json",n=new URL(e.url);n.searchParams.has("api-version")||n.searchParams.set("api-version",Zfe);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 zA(`Azure DevOps answered ${i.status}${typeof r=="string"?`: ${r}`:""}`,i.status)}return t!=="application/json"?Buffer.from(await i.arrayBuffer()):i.status===204?{}:await i.json()}o(f$,"azureRest");function Kfe(e){return`AUTHORIZATION: bearer ${e}`}o(Kfe,"azureGitAuthorization");function Rq(e,t){return{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${qA(e)}/.extraheader`,GIT_CONFIG_VALUE_0:Kfe(t)}}o(Rq,"azureGitAuthEnv");var Xfe="7.1-preview.1",ege=".azure-pipelines/skyramp-testbot-v3.yml";function g$(e){return e.GITHUB_ACTIONS!=="true"&&/^true$/i.test(e.TF_BUILD??"")}o(g$,"isAzurePipelines");function Tq(e,t={}){let n=o(p=>{let g=e[p];if(!g)throw new Error(`${p} is not set; the V3 runner handshake needs it`);return g},"read"),i=qA(e.SYSTEM_COLLECTIONURI??""),r=o(()=>d$(n("SYSTEM_COLLECTIONURI")),"organization"),s=e.SYSTEM_TEAMPROJECT,a=e.BUILD_REPOSITORY_NAME,c=e.BUILD_REPOSITORY_ID?.toLowerCase(),u=e.SYSTEM_ACCESSTOKEN,l=t.mask??(p=>Bq(p)),A=o(p=>async()=>{if(!p)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_OIDCREQUESTURI to $(System.OidcRequestUri).");if(!u)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_ACCESSTOKEN to $(System.AccessToken).");let g=new URL(p);if(g.protocol!=="https:")throw new Error("SYSTEM_OIDCREQUESTURI is not an https URL");g.searchParams.set("api-version",Xfe);let h=await(t.fetch??fetch)(g.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"Content-Type":"application/json",Accept:"application/json"},body:"{}",redirect:"error",signal:AbortSignal.timeout(3e4)});if(!h.ok)throw new Error(`Azure DevOps refused the OIDC token request: ${h.status}`);let y=(await h.json().catch(()=>({}))).oidcToken;if(typeof y!="string"||!y)throw new Error("Azure DevOps's OIDC token response carried no token");return l(y),y},"mint");return{runnerPlatform:g$(e)?"azure":void 0,workspace:e.BUILD_SOURCESDIRECTORY||void 0,serverUrl:i,apiUrl:i,repository:c&&s&&a&&i?{id:c,slug:`${r()}/${s}/${a}`}:void 0,runId:e.BUILD_BUILDID||void 0,runAttempt:e.SYSTEM_STAGEATTEMPT||void 0,job:e.SYSTEM_JOBNAME||void 0,execution(){let p=n("SYSTEM_STAGEATTEMPT");if(!/^[1-9][0-9]*$/.test(p))throw new Error(`SYSTEM_STAGEATTEMPT is "${p}", not a positive whole number`);let g=n("SYSTEM_COLLECTIONID").toLowerCase();if(!kc.test(g))throw new Error(`SYSTEM_COLLECTIONID is "${g}", not a GUID`);let h=n("BUILD_REPOSITORY_ID").toLowerCase();if(!kc.test(h))throw new Error(`BUILD_REPOSITORY_ID is "${h}", not a GUID`);let y=[r(),n("SYSTEM_TEAMPROJECT"),n("SYSTEM_DEFINITIONID"),n("BUILD_BUILDID")].map(encodeURIComponent).join("/");return{provider:"azure-devops",repository:{provider:"azure-devops",providerAccountId:g,providerRepositoryId:h},providerRunId:y,providerRunAttempt:Number(p),workflowRef:`${ege}@${n("BUILD_SOURCEBRANCH")}`}},takeIdToken(){let p=e.SYSTEM_OIDCREQUESTURI;delete e.SYSTEM_OIDCREQUESTURI;let g=A(p);return()=>g()},takeSourceToken(){return delete e.SYSTEM_ACCESSTOKEN,u||void 0},webIdentity(){if(!e.SYSTEM_OIDCREQUESTURI?.trim()||!u)return;let p=A(e.SYSTEM_OIDCREQUESTURI);return{token:o(()=>p(),"token"),runId:e.BUILD_BUILDID}},v3RunsOnly:!0,assumesBedrockRole:!0,namesSourceToMcp:!0,runSettingsFromApp:!0,checkSourceName(p){wy(p)},cloneUrl(p){return Qq(i,wy(p))},gitAuthEnv(p){return Rq(i,p)},async pullRequest(p,g,h){let y=await f$({token:await h.token(),url:`${p$(i,wy(p))}/pullrequests/${g}`,fetch:h.fetch}),E=y.status==="completed";return{...typeof y.title=="string"?{title:y.title}:{},...typeof y.description=="string"?{body:y.description}:{},...typeof y.status=="string"?{merged:E}:{},...E&&typeof y.lastMergeCommit?.commitId=="string"?{mergeCommit:y.lastMergeCommit.commitId}:{},...E&&typeof y.lastMergeSourceCommit?.commitId=="string"?{mergedHead:y.lastMergeSourceCommit.commitId}:{}}},async commit(p,g,h){let y;try{y=p$(i,A$(p))}catch{return{lookup:"unknown"}}try{let E=await f$({token:await h.token(),url:`${y}/commits/${encodeURIComponent(g)}`,fetch:h.fetch});return typeof E.commitId=="string"?{sha:E.commitId}:{lookup:"missing"}}catch(E){return{lookup:E instanceof zA&&(E.status===404||E.status===400)?"missing":"unknown"}}}}}o(Tq,"azureRunnerHost");pc();var tge=5e3,h$=/^(?!\.\.?$)[A-Za-z0-9._-]{1,100}$/;function nge(e){let t=Buffer.from(`x-access-token:${e}`).toString("base64");return Ol(t),`AUTHORIZATION: basic ${t}`}o(nge,"githubGitAuthorization");function Dq(e,t={}){let n=o(u=>{let l=e[u];if(!l)throw new Error(`${u} is not set; the V3 runner handshake needs it`);return l},"read"),i=e.GITHUB_REPOSITORY_ID,r=e.GITHUB_REPOSITORY,s=(e.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,""),a=(e.GITHUB_API_URL||"https://api.github.com").replace(/\/+$/,""),c=o(async(u,l)=>l.fetch(u,{headers:{Authorization:`Bearer ${await l.token()}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(3e4)}),"get");return{runnerPlatform:e.GITHUB_ACTIONS==="true"?"github":void 0,workspace:e.GITHUB_WORKSPACE||void 0,serverUrl:s,apiUrl:a,repository:i&&r?{id:i,slug:r}:void 0,runId:e.GITHUB_RUN_ID||void 0,runAttempt:e.GITHUB_RUN_ATTEMPT||void 0,job:e.GITHUB_JOB||void 0,execution(){let u=n("GITHUB_RUN_ATTEMPT");if(!/^[1-9][0-9]*$/.test(u))throw new Error(`GITHUB_RUN_ATTEMPT is "${u}", not a positive whole number`);return{provider:"github",repository:{provider:"github",providerAccountId:n("GITHUB_REPOSITORY_OWNER_ID"),providerRepositoryId:n("GITHUB_REPOSITORY_ID")},providerRunId:n("GITHUB_RUN_ID"),providerRunAttempt:Number(u),workflowRef:n("GITHUB_WORKFLOW_REF")}},takeIdToken(){let u=e.ACTIONS_ID_TOKEN_REQUEST_URL,l=e.ACTIONS_ID_TOKEN_REQUEST_TOKEN;return delete e.ACTIONS_ID_TOKEN_REQUEST_URL,delete e.ACTIONS_ID_TOKEN_REQUEST_TOKEN,async A=>{if(!u||!l)throw new Error("The job cannot request an OIDC token. Give it the `id-token: write` permission.");let p=new URL(u);p.searchParams.set("audience",A);let g=await fetch(p,{headers:{Authorization:`Bearer ${l}`,Accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!g.ok)throw new Error(`GitHub refused the OIDC token request: ${g.status}`);let h=(await g.json().catch(()=>({}))).value;if(typeof h!="string"||!h)throw new Error("GitHub's OIDC token response carried no token");return Ol(h),h}},webIdentity(){return!e.ACTIONS_ID_TOKEN_REQUEST_TOKEN?.trim()||!e.ACTIONS_ID_TOKEN_REQUEST_URL?.trim()?void 0:{token:t.getIDToken??(l=>yM(l)),runId:e.GITHUB_RUN_ID}},v3RunsOnly:!1,assumesBedrockRole:!1,namesSourceToMcp:!1,runSettingsFromApp:!1,checkSourceName(u){for(let l of[u.namespace,u.name])if(!h$.test(l))throw new Error(`"${l}" is not a repository name`)},cloneUrl(u){return`${s}/${u.namespace}/${u.name}.git`},gitAuthEnv(u){return u?{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${s}/.extraheader`,GIT_CONFIG_VALUE_0:nge(u)}:{}},async pullRequest({namespace:u,name:l},A,p){if(![u,l].every(y=>h$.test(y)))throw new Error("the repository name is not valid");let g=await c(`${a}/repos/${u}/${l}/pulls/${A}`,p);if(!g.ok)throw new Error(`GitHub answered ${g.status}`);let h=await g.json();return{...typeof h.title=="string"?{title:h.title}:{},...typeof h.body=="string"?{body:h.body}:{},...typeof h.merged=="boolean"?{merged:h.merged}:{},...h.merged===!0&&typeof h.merge_commit_sha=="string"?{mergeCommit:h.merge_commit_sha}:{},...h.merged===!0&&typeof h.head?.sha=="string"?{mergedHead:h.head.sha}:{}}},async commit(u,l,A){let[p,g,...h]=u.split("/");if(h.length||![p,g].every(y=>y!==void 0&&h$.test(y)))return{lookup:"unknown"};try{let y=await c(`${a}/repos/${p}/${g}/commits/${encodeURIComponent(l)}`,A);if(y.status===404||y.status===422)return{lookup:"missing"};if(!y.ok)return{lookup:"unknown"};let E=await y.json();return typeof E.sha=="string"?{sha:E.sha}:{lookup:"missing"}}catch{return{lookup:"unknown"}}},async revokeToken(u,l){let A=await l(`${a}/installation/token`,{method:"DELETE",headers:{Authorization:`Bearer ${u}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(tge)});if(!A.ok&&A.status!==401)throw new Error(`GitHub answered ${A.status}`)}}}o(Dq,"githubRunnerHost");function _q(e=process.env){return g$(e)?Tq(e):Dq(e)}o(_q,"runnerHost");var rge=10*6e4;function ige(e,t){return e.getTime()-t.getTime()-rge}o(ige,"remainingBudgetMs");var Nq="This attempt revoked its scoped GitHub credentials; it mints no more.",sge=10*6e4;var oge=o(e=>!!e&&Object.keys(e).length===1&&e.contents==="read","onlyReads"),age=3e4,cge=3,Uq=30,Mr=class extends Error{constructor(n,i,r,s){super(n);this.status=i;this.code=r;this.path=s}status;code;path;static{o(this,"AppRefusal")}},gi=class extends Error{static{o(this,"AppUnreachable")}},Qu=class extends gi{static{o(this,"AppNotReady")}},m$=class extends Qu{static{o(this,"RunnerProviderNotReady")}};function y$(e){let t;try{t=new URL(e)}catch{throw new Error(`skyrampAppOrigin "${e}" is not a URL`)}if(t.protocol!=="https:"||t.origin!==e.replace(/\/+$/,""))throw new Error(`skyrampAppOrigin must be an https origin, got "${e}"`);return t.origin}o(y$,"appOrigin");function Pq(e,t){if(!kc.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}o(Pq,"routeId");function uge(e,t){return`${e.replace(/\/+$/,"")}/runs/${t}`}o(uge,"skyrampRunPageUrl");function Mq(e,t,n,i){throw t<500&&t!==429?new Mr(e,t,n,i):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new m$(e):t===503&&n==="RUN_NOT_READY"?new Qu(e):new gi(e)}o(Mq,"refusedOrUnreachable");async function Oq(e,t,n,i,r,s=1/0){let a=y$(e.origin),c=`The time limit for ${t} ${n} was reached`,u,l=0;for(let A=1;A<=cge||u instanceof Qu;A+=1){if(u instanceof Qu){if(l===Uq)throw u;l+=1,A-=1,e.log?.(`${u.message}; trying again (${l} of ${Uq}).`),await new Promise(p=>setTimeout(p,Math.max(0,Math.min(e.readyWaitMs??1e4,s-Date.now()))))}else A>1&&await new Promise(p=>setTimeout(p,Math.max(0,Math.min((e.retryDelayMs??2e3)*(A-1),s-Date.now()))));if(Date.now()>=s)throw new gi(c);try{let p,g=await(Number.isFinite(s)?Promise.race([e.idToken(a),new Promise((y,E)=>{p=setTimeout(()=>E(new gi(c)),Math.max(1,s-Date.now()))})]).finally(()=>{p&&clearTimeout(p)}):e.idToken(a));if(Date.now()>=s)throw new gi(c);let h=await(e.fetch??fetch)(new URL(n,a).toString(),{...i(g),redirect:"error",signal:AbortSignal.timeout(Math.max(1,Math.min(age,s-Date.now())))}).catch(y=>{throw new gi(y instanceof Error?y.message:String(y),{cause:y})});return await r(h)}catch(p){if(p instanceof Mr||Date.now()>=s)throw p;u=p}}throw u}o(Oq,"callWithRetries");function Lq(e,t,n,i,r){let s=i.headers.get("cf-ray");e.log?.(`Testbot V3: ${t} ${n} answered ${i.status}${s?`, cf-ray ${s}`:""}: ${r.replace(/\s+/g," ").slice(0,200)}`)}o(Lq,"logRefusal");function By(e,t,n,i,r){let s=t==="GET"?void 0:JSON.stringify(i),a=t==="PUT"&&/^\/api\/v1\/runner\/attempts\/[^/]+\/report$/.test(n)&&s!==void 0&&Buffer.byteLength(s,"utf8")>$g;if(a&&Buffer.byteLength(s,"utf8")>vO)throw new Error("The report exceeds the app's 16 MiB expanded report limit");let c=a?new Uint8Array((0,Fq.gzipSync)(s)):s;if(a&&c.length>$g)throw new Error("The compressed report exceeds the app's 1 MiB report upload limit");return Oq(e,t,n,o(l=>({method:t,headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json",Accept:"application/json",...a?{"Content-Encoding":"gzip"}:{}},body:c}),"request"),async l=>{let A=await l.text().catch(()=>""),p={};try{p=JSON.parse(A)}catch{}if(l.ok)return p.data;Lq(e,t,n,l,A);let g=p.error?.fields,h=typeof g?.path=="string"&&typeof g.reason=="string"?` at ${g.path}: ${g.reason}`:"",y=`The Skyramp app refused ${t} ${n}: ${l.status} ${p.error?.code??"no error code"}${h}`;return Mq(y,l.status,p.error?.code,typeof g?.path=="string"?g.path:void 0)},r)}o(By,"callApp");function lge(e,t,n){return Oq(e,"GET",t,o(r=>({method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/octet-stream"}}),"request"),async r=>{if(!r.ok)return Lq(e,"GET",t,r,await r.text().catch(()=>"")),Mq(`The Skyramp app refused GET ${t}: ${r.status}`,r.status);let s=Buffer.from(await r.arrayBuffer());if(s.length>n)throw new Mr(`The Skyramp app answered GET ${t} with more than ${n} bytes`,r.status);return s})}o(lge,"callAppBytes");var JA=class{constructor(t,n,i,r,s,a,c,u,l,A=[],p=[],g){this.attemptId=t;this.attemptNumber=n;this.deadlineAt=i;this.manifest=r;this.deps=s;this.license=a;this.requestedBy=c;this.writeAllowed=u;this.claudeCodeVersion=l;this.deployedPins=A;this.statedPins=p;this.runSettings=g}attemptId;attemptNumber;deadlineAt;manifest;deps;license;requestedBy;writeAllowed;claudeCodeVersion;deployedPins;statedPins;runSettings;static{o(this,"V3Attempt")}budgetMs(t){return ige(this.deadlineAt,t)}get skyrampRunUrl(){return uge(y$(this.deps.origin),this.manifest.runId)}log(t){this.deps.log?.(t)}send(t,n,i,r){return By(this.deps,t,n,i,r)}readBytes(t,n){return lge(this.deps,t,n)}issuedTokens=[];closure;modelKey;modelCredentials=[];credentials={};revocation;token(){return this.cachedToken("run")}readOnlyToken(){return this.cachedToken("read")}async cachedToken(t){if(this.revocation)throw new Error(Nq);let n=(this.deps.now??(()=>new Date))().getTime(),i=this.credentials[t],r=i&&await i.catch(()=>{});if(this.credentials[t]!==i)return(await this.credentials[t]).token;if(r&&r.expiresAt-n>=sge)return r.token;if(this.revocation)throw new Error(Nq);let s=t==="read",a=s?{schemaVersion:1,access:t}:{schemaVersion:1},c=s?"read-only":"scoped",u=this.send("POST",`/api/v1/runner/attempts/${this.attemptId}/credentials`,a).then(l=>{let A={...l,token:l.token??this.jobToken()};if(this.issuedTokens.push(A.token),this.deps.mask?.(A.token),A.anthropicApiKey&&this.deps.mask?.(A.anthropicApiKey),s&&l.token&&!oge(A.permissions))throw new Error(`The Skyramp app was asked for a read-only GitHub token, but its token grants ${JSON.stringify(A.permissions??null)}`);!s&&!r&&A.anthropicApiKey&&(this.modelKey=A.anthropicApiKey),this.deps.onTokenGranted?.(t);let p=r?"Renewed":"Received";return l.token&&this.deps.log?.(`${p} ${c} GitHub credentials; they expire at ${A.expiresAt}.`),{token:A.token,expiresAt:l.token?new Date(A.expiresAt).getTime():Number.POSITIVE_INFINITY}},l=>{if(this.deps.onTokenRefused?.(l,t),!(l instanceof Mr)||l.code!=="CREDENTIALS_UNAVAILABLE")throw l;let A=o(h=>[...new Set(h.map(y=>y.namespace))].join(", "),"unique"),p=this.manifest.sources.map(h=>h.repository);if(new Set(p.map(h=>h.providerAccountId)).size>1)throw new Mr(`${l.message}. The run's repositories are on more than one GitHub account (${A(p)}), which Skyramp does not support yet.`,l.status,l.code);let g=A([...p,this.manifest.execution.repository]);throw new Mr(`${l.message}. Check the Skyramp GitHub App installation on ${g}: it must be installed and not suspended, have access to these repositories, and have accepted the App's current permissions. Each account must also be connected to your Skyramp organization.`,l.status,l.code)});return this.credentials[t]=u,(await u).token}jobToken(){if(this.deps.sourceToken)return this.deps.sourceToken;throw new Error("The app answered the credentials request without a token, and the job gave Testbot none of its own: on Azure Pipelines, set SYSTEM_ACCESSTOKEN to $(System.AccessToken) in the Testbot step's env.")}sourceFetch(t){return t.fetch??this.deps.fetch??fetch}revokeTokens(t={}){let n=t.host??_q();return this.revocation??=n.revokeToken?this.revokeIssued(i=>n.revokeToken(i,this.sourceFetch(t))):Promise.resolve([]),this.revocation}async revokeIssued(t){let n=[...this.issuedTokens],i=Promise.all(n.map(a=>this.revokeOne(a,t)));await Promise.all(Object.values(this.credentials).map(a=>a.catch(()=>{})));let r=this.issuedTokens.filter(a=>!n.includes(a));return[...await i,...await Promise.all(r.map(a=>this.revokeOne(a,t)))].filter(a=>a!==void 0)}async revokeOne(t,n){try{await n(t);return}catch(i){return`token ${this.issuedTokens.indexOf(t)+1} of ${this.issuedTokens.length}: ${i instanceof Error?i.message:String(i)}`}}};async function jq(e,t,n){Pq(e,"run id"),y$(n.origin);let i=Gb(e,t),r=`/api/v1/runner/runs/${e}/attempts`,s;try{s=await By(n,"POST",r,i)}catch(l){if(!(l instanceof Mr&&l.status===400&&l.path==="$.statedPins"))throw l;i=Gb(e,t,{statedPins:!1}),s=await By(n,"POST",r,i)}let a=VO(s);if(a.manifest.runId!==e)throw new Error(`The app answered the handshake of run ${e} with the manifest of another run (${a.manifest.runId})`);let c=a.manifest.sources.find(l=>l.repository.provider!==i.execution.provider);if(c)throw new Error(`The manifest of run ${e} names ${c.repository.namespace}/${c.repository.name} on ${c.repository.provider}, but this job runs on ${i.execution.provider}`);dge(a.manifest,[...a.deployedRevisions??[],...a.statedRevisions??[]]),a.runToken&&n.mask?.(a.runToken);let u=a.runToken?{entitlements:a.entitlements??[],runToken:a.runToken}:void 0;return new JA(a.attempt.id,a.attempt.number,new Date(a.attempt.deadlineAt),a.manifest,n,u,a.requestedBy??void 0,a.writeAllowed,a.claudeCodeVersion??void 0,a.deployedRevisions??[],a.statedRevisions??[],a.runSettings)}o(jq,"startV3Attempt");function dge(e,t){if(t.length===0)return;if(!xO(e))throw new Error(`The app pinned an attempt of a ${e.trigger.kind} run; only a scheduled run or unchosen manual run's retry is pinned to an earlier attempt's read`);let n=new Set(e.sources.map(r=>oi(r.repository))),i=new Set;for(let r of t){let s=oi(r.repository);if(!n.has(s))throw new Error(`The app pinned the attempt to repository ${r.repository.providerRepositoryId}, which is not a source of the run`);if(i.has(s))throw new Error(`The app pinned repository ${r.repository.providerRepositoryId} twice`);i.add(s)}}o(dge,"checkAttemptPins");async function E$(e,t){return MO.parse(await e.send("POST",`/api/v1/runner/attempts/${e.attemptId}/heartbeat`,{schemaVersion:1},t))}o(E$,"heartbeatV3Attempt");async function Vq(e,t=()=>new Date,n){if(e.closure)return e.closure;let i=await E$(e,n).then(r=>OO(r,t())).catch(()=>null);return i&&(e.closure=i),i}o(Vq,"closedV3Attempt");var IGe=10*6e4;var CGe=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var bGe=d.object({tests:d.object({placements:d.array(d.unknown()).optional()}).passthrough().optional()}).passthrough(),vGe=d.object({repository:Mb,testType:d.string(),directory:d.string()}).passthrough();var wGe=d.object({report:d.object({language:d.string()}).passthrough()}).passthrough();var BGe=d.object({environment:d.object({components:d.array(d.unknown()).optional(),dependencies:d.array(d.unknown()).optional()}).passthrough()}).passthrough(),kGe=d.object({environment:d.object({offLimits:d.unknown().optional()}).passthrough()}).passthrough();var SGe=d.object({name:d.string().min(1),provision:d.literal("existing"),url:d.string().min(1),repository:Mb.optional(),revisionUrl:d.string().min(1).optional()}).passthrough(),QGe=d.object({name:d.string().min(1),url:d.string().nullable(),versionUrl:d.string().nullable(),notes:d.string().nullable()}).passthrough();var RGe=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);function Gq(e){let t=o(n=>e.testResults.filter(i=>i.status===n).length,"count");return{passed:t("Pass"),failed:t("Fail"),skipped:t("Skipped")}}o(Gq,"statusCounts");function Age(e){let{passed:t,failed:n,skipped:i}=Gq(e);return t+n===0?{sufficiency:"insufficient",rationale:i>0?`Every test was skipped (${i}), so nothing was validated.`:"No test ran, so nothing was validated.",gaps:["No test ran against the frozen sources."],acceptedEvidence:[],actionRequired:[]}:{sufficiency:"sufficient",rationale:`${t+n} tests ran against the frozen sources: ${t} passed, ${n} failed${i?`, ${i} skipped`:""}.`,gaps:[],acceptedEvidence:[],actionRequired:[]}}o(Age,"executedTestsValidation");function pge(e,t){let n=e.map(c=>({result:c,repository:c.repository??t,path:c.fileName||c.testType})),i=new Map;for(let c of n){let u=`${c.repository}:${c.result.testType}:${c.path}`;i.set(u,(i.get(u)??0)+1)}let r=n.map(({result:c,repository:u,path:l})=>{let A=(i.get(`${u}:${c.testType}:${l}`)??0)>1;return c.resultId??Lb(u,c.testType,l,A&&c.endpoint||void 0)}),s=new Map;for(let c of r)s.set(c,(s.get(c)??0)+1);let a=new Set(r.filter(c=>s.get(c)===1));return n.map(({result:c,repository:u},l)=>{let A=r[l],p=A;if(s.get(A)>1&&a.has(A))for(let g=2;a.has(p)||p===A;g+=1)p=A.includes("#")?`${A}.${g}`:`${A}#${g}`;return a.add(p),{...c,repository:u,resultId:p}})}o(pge,"withResultIds");function fge({notTranslated:e,...t},n){let i=pge(t.testResults,n);return{...t,testResults:i,...gge(t,i,n),validation:yge(t,hge(t,t.validation??Age(t))),traceVersion:1}}o(fge,"v3Report");function gge(e,t,n){if(!e.testExecutionContexts)return{};let i=new Set,r=o(c=>{let u=c;for(let l=2;i.has(u);l+=1)u=`${c}#${l}`;return i.add(u),u},"unique"),s=[],a=new Map;for(let{repository:c,...u}of e.testExecutionContexts){let l=u.status==="not_run"?[]:t.filter(A=>A.fileName===u.test&&A.repository===(c?.trim()||n));l.length||s.push(u);for(let{resultId:A}of l){let p=a.get(A),g=p!==void 0&&s[p].cleanup.status==="failed"?s[p].cleanup:u.cleanup,h={...u,cleanup:g,test:A,resultId:A};p===void 0?a.set(A,s.push(h)-1):s[p]=h}}for(let c of s)c.resultId&&i.add(c.resultId);return{testExecutionContexts:s.map(c=>c.resultId?c:{...c,test:r(c.test.slice(0,512))}).slice(0,5e3)}}o(gge,"linkedContexts");function hge(e,t){let{passed:n,failed:i}=Gq(e);return t.sufficiency!=="sufficient"||n+i>0||t.acceptedEvidence.length>0?t:{...t,sufficiency:"insufficient",gaps:["No test ran and no existing evidence was accepted, so nothing was validated."]}}o(hge,"withEvidence");var mge={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};function yge(e,t){if(t.sufficiency==="sufficient")return t;let n=(e.caveats??[]).map(r=>mge[r.kind]).filter(r=>r!==void 0),i=[...new Set(n)].filter(r=>!t.actionRequired.includes(r));return i.length?{...t,actionRequired:[...i,...t.actionRequired]}:t}o(yge,"withModelProviderFailure");function Ege(e,t,n){let{language:i,report:r}=t;if(i==="en")return;let s={language:i,businessCaseAnalysis:r.businessCaseAnalysis},a=o((y,E,C)=>Array.isArray(y)&&Array.isArray(E)&&y.length===E.length?y.map(I=>({[C]:I[C]})):void 0,"rows"),c=e.validation;r.validation&&c&&c.rationale===n.validation.rationale&&JSON.stringify(c.gaps)===JSON.stringify(n.validation.gaps)&&r.validation.gaps.length===n.validation.gaps.length&&(s.validation={rationale:r.validation.rationale,gaps:[...r.validation.gaps]});let u=new Set((n.changes??[]).map(y=>y.id)),l=(r.changes??[]).filter(y=>u.has(y.id)).map(({id:y,text:E})=>({id:y,text:E}));l.length&&(s.changes=l);let A=a(r.issuesFound,n.issuesFound,"description");A&&(s.issuesFound=A);let p=a(r.newTestsCreated,n.newTestsCreated,"description");p&&(s.newTestsCreated=p);let g=a(r.testResults,n.testResults,"details");g&&(s.testResults=g);let h=a(r.caveats,n.caveats,"text");return h&&(s.caveats=h),s}o(Ege,"v3Display");async function zq(e,t){let n=bM([...e.issuedTokens,...t.secrets??[]]),i={...fge(t.report,t.workingSlug),...t.notTranslated?{notTranslated:t.notTranslated}:{}},r=t.translated&&Ege(t.report,t.translated,i),s=o(c=>GO({manifest:e.manifest,attemptNumber:e.attemptNumber,checkedOut:t.sources.map(u=>({repository:u.repository,revision:u.revision})),firstQualification:t.firstQualification,generatedTests:Vl(t.delivery,n),producer:t.producer,report:Vl(c&&r?{...i,display:r}:i,n),githubWrites:t.githubWrites}),"build"),a=s(!0);r&&Buffer.byteLength(JSON.stringify(a),"utf8")>$g&&(a=s(!1)),await e.send("PUT",`/api/v1/runner/attempts/${e.attemptId}/report`,a)}o(zq,"uploadV3Report");async function qq(e,t){return Pq(e.attemptId,"attempt id"),By(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,zO({reportUploaded:e.reportUploaded,recipeUploaded:e.recipeUploaded,revisionsUploaded:e.revisionsUploaded,cancelled:e.cause==="cancelled",timedOut:e.cause==="timed_out",setupFailed:e.cause==="setup_failed",checkoutFailed:e.cause==="checkout_failed"||e.cause==="merge_conflict"&&!e.conflict,mergeConflict:e.cause==="merge_conflict"?e.conflict:void 0,environmentUnverified:e.cause==="environment_unverified",runnerProviderNotReady:e.cause==="runner_provider_not_ready",credentialMissing:e.cause==="credential_missing",modelProviderDenied:e.cause==="model_provider_denied",modelProviderUnavailable:e.cause==="model_provider_unavailable"}))}o(qq,"endV3Attempt");0&&(module.exports={AppRefusal,AppUnreachable,AttemptEndReason,DeliveryStatus,GitHubWriteKind,NoReportCause,SourceProvider,V3Attempt,ValidationSufficiency,closedV3Attempt,endV3Attempt,heartbeatV3Attempt,startV3Attempt,uploadV3Report});
|
|
200
|
+
`:e.text??"")}o(Gfe,"writeFrame");function zfe(e){Gfe({command:e})}o(zfe,"writeAzureCommand");function wq(e){return e.replace(/%/g,"%AZP25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}o(wq,"escapeData");function qfe(e){return wq(e).replace(/;/g,"%3B").replace(/]/g,"%5D")}o(qfe,"escapeProperty");function Jfe(e,t,n){let i=Object.entries(t).map(([r,s])=>`${r}=${qfe(s)}`).join(";");return`##vso[${e}${i?` ${i}`:""}]${wq(n)}`}o(Jfe,"vsoCommand");function Hfe(e){if(!e)return[];let t=e.split(/\r?\n/).filter(n=>n.trim()&&n!==e);return[e,...t].map(n=>Jfe("task.setsecret",{},n))}o(Hfe,"setSecretLines");function Bq(e,t=zfe){for(let n of Hfe(e))t(n)}o(Bq,"azureSetSecret");function qA(e){return e.replace(/\/+$/,"")}o(qA,"withoutTrailingSlash");function d$(e){let t=new URL(e),n=t.pathname.split("/").filter(Boolean);if(n.length)return decodeURIComponent(n[n.length-1]);if(t.hostname.endsWith(".visualstudio.com"))return t.hostname.split(".")[0];throw new Error(`SYSTEM_COLLECTIONURI "${e}" names no organization`)}o(d$,"azureOrganization");var Yfe=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,48}[A-Za-z0-9])?$/,Wfe=/[\\/:*?"<>|;#${},+=[\]%\p{Cc}\p{Cf}]/u;function kq(e){return e.length>0&&e.length<=64&&e===e.trim()&&!Wfe.test(e)&&!/[^\S ]/u.test(e)&&!/^[._]/.test(e)&&!e.endsWith(".")}o(kq,"isName");function wy(e){return A$(`${e.namespace}/${e.name}`)}o(wy,"azureRepositoryOfSource");function A$(e){let t=e.indexOf("/"),n=e.lastIndexOf("/"),i=e.slice(0,t),r=e.slice(t+1,n),s=e.slice(n+1);if(t<0||t===n||!Yfe.test(i)||!kq(r)||!kq(s))throw new Error(`"${e}" is not an Azure DevOps organization/project/repository`);return{organization:i,project:r,name:s}}o(A$,"azureRepositoryOf");function Sq(e,t){let n=d$(e);if(n.toLowerCase()!==t.organization.toLowerCase())throw new Error(`${t.organization}/${t.project}/${t.name} is not in ${n}, the Azure DevOps organization this job runs in`)}o(Sq,"inOrganization");function Qq(e,t){return Sq(e,t),`${qA(e)}/${encodeURIComponent(t.project)}/_git/${encodeURIComponent(t.name)}`}o(Qq,"azureCloneUrl");function p$(e,t){return Sq(e,t),`${qA(e)}/${encodeURIComponent(t.project)}/_apis/git/repositories/${encodeURIComponent(t.name)}`}o(p$,"azureRepositoryApi");var Zfe="7.1",zA=class extends Error{constructor(n,i){super(n);this.status=i}status;static{o(this,"AzureRestError")}};async function f$(e){let t=e.accept??"application/json",n=new URL(e.url);n.searchParams.has("api-version")||n.searchParams.set("api-version",Zfe);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 zA(`Azure DevOps answered ${i.status}${typeof r=="string"?`: ${r}`:""}`,i.status)}return t!=="application/json"?Buffer.from(await i.arrayBuffer()):i.status===204?{}:await i.json()}o(f$,"azureRest");function Kfe(e){return`AUTHORIZATION: bearer ${e}`}o(Kfe,"azureGitAuthorization");function Rq(e,t){return{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${qA(e)}/.extraheader`,GIT_CONFIG_VALUE_0:Kfe(t)}}o(Rq,"azureGitAuthEnv");var Xfe="7.1-preview.1",ege=".azure-pipelines/skyramp-testbot-v3.yml";function g$(e){return e.GITHUB_ACTIONS!=="true"&&/^true$/i.test(e.TF_BUILD??"")}o(g$,"isAzurePipelines");function Tq(e,t={}){let n=o(p=>{let g=e[p];if(!g)throw new Error(`${p} is not set; the V3 runner handshake needs it`);return g},"read"),i=qA(e.SYSTEM_COLLECTIONURI??""),r=o(()=>d$(n("SYSTEM_COLLECTIONURI")),"organization"),s=e.SYSTEM_TEAMPROJECT,a=e.BUILD_REPOSITORY_NAME,c=e.BUILD_REPOSITORY_ID?.toLowerCase(),u=e.SYSTEM_ACCESSTOKEN,l=t.mask??(p=>Bq(p)),A=o(p=>async()=>{if(!p)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_OIDCREQUESTURI to $(System.OidcRequestUri).");if(!u)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_ACCESSTOKEN to $(System.AccessToken).");let g=new URL(p);if(g.protocol!=="https:")throw new Error("SYSTEM_OIDCREQUESTURI is not an https URL");g.searchParams.set("api-version",Xfe);let h=await(t.fetch??fetch)(g.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"Content-Type":"application/json",Accept:"application/json"},body:"{}",redirect:"error",signal:AbortSignal.timeout(3e4)});if(!h.ok)throw new Error(`Azure DevOps refused the OIDC token request: ${h.status}`);let y=(await h.json().catch(()=>({}))).oidcToken;if(typeof y!="string"||!y)throw new Error("Azure DevOps's OIDC token response carried no token");return l(y),y},"mint");return{runnerPlatform:g$(e)?"azure":void 0,workspace:e.BUILD_SOURCESDIRECTORY||void 0,serverUrl:i,apiUrl:i,repository:c&&s&&a&&i?{id:c,slug:`${r()}/${s}/${a}`}:void 0,runId:e.BUILD_BUILDID||void 0,runAttempt:e.SYSTEM_STAGEATTEMPT||void 0,job:e.SYSTEM_JOBNAME||void 0,execution(){let p=n("SYSTEM_STAGEATTEMPT");if(!/^[1-9][0-9]*$/.test(p))throw new Error(`SYSTEM_STAGEATTEMPT is "${p}", not a positive whole number`);let g=n("SYSTEM_COLLECTIONID").toLowerCase();if(!kc.test(g))throw new Error(`SYSTEM_COLLECTIONID is "${g}", not a GUID`);let h=n("BUILD_REPOSITORY_ID").toLowerCase();if(!kc.test(h))throw new Error(`BUILD_REPOSITORY_ID is "${h}", not a GUID`);let y=[r(),n("SYSTEM_TEAMPROJECT"),n("SYSTEM_DEFINITIONID"),n("BUILD_BUILDID")].map(encodeURIComponent).join("/");return{provider:"azure-devops",repository:{provider:"azure-devops",providerAccountId:g,providerRepositoryId:h},providerRunId:y,providerRunAttempt:Number(p),workflowRef:`${ege}@${n("BUILD_SOURCEBRANCH")}`}},takeIdToken(){let p=e.SYSTEM_OIDCREQUESTURI;delete e.SYSTEM_OIDCREQUESTURI;let g=A(p);return()=>g()},takeSourceToken(){return delete e.SYSTEM_ACCESSTOKEN,u||void 0},webIdentity(){if(!e.SYSTEM_OIDCREQUESTURI?.trim()||!u)return;let p=A(e.SYSTEM_OIDCREQUESTURI);return{token:o(()=>p(),"token"),runId:e.BUILD_BUILDID}},v3RunsOnly:!0,assumesBedrockRole:!0,namesSourceToMcp:!0,runSettingsFromApp:!0,checkSourceName(p){wy(p)},cloneUrl(p){return Qq(i,wy(p))},gitAuthEnv(p){return Rq(i,p)},async pullRequest(p,g,h){let y=await f$({token:await h.token(),url:`${p$(i,wy(p))}/pullrequests/${g}`,fetch:h.fetch}),E=y.status==="completed";return{...typeof y.title=="string"?{title:y.title}:{},...typeof y.description=="string"?{body:y.description}:{},...typeof y.status=="string"?{merged:E}:{},...E&&typeof y.lastMergeCommit?.commitId=="string"?{mergeCommit:y.lastMergeCommit.commitId}:{},...E&&typeof y.lastMergeSourceCommit?.commitId=="string"?{mergedHead:y.lastMergeSourceCommit.commitId}:{}}},async commit(p,g,h){let y;try{y=p$(i,A$(p))}catch{return{lookup:"unknown"}}try{let E=await f$({token:await h.token(),url:`${y}/commits/${encodeURIComponent(g)}`,fetch:h.fetch});return typeof E.commitId=="string"?{sha:E.commitId}:{lookup:"missing"}}catch(E){return{lookup:E instanceof zA&&(E.status===404||E.status===400)?"missing":"unknown"}}}}}o(Tq,"azureRunnerHost");pc();var tge=5e3,h$=/^(?!\.\.?$)[A-Za-z0-9._-]{1,100}$/;function nge(e){let t=Buffer.from(`x-access-token:${e}`).toString("base64");return Ol(t),`AUTHORIZATION: basic ${t}`}o(nge,"githubGitAuthorization");function Dq(e,t={}){let n=o(u=>{let l=e[u];if(!l)throw new Error(`${u} is not set; the V3 runner handshake needs it`);return l},"read"),i=e.GITHUB_REPOSITORY_ID,r=e.GITHUB_REPOSITORY,s=(e.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,""),a=(e.GITHUB_API_URL||"https://api.github.com").replace(/\/+$/,""),c=o(async(u,l)=>l.fetch(u,{headers:{Authorization:`Bearer ${await l.token()}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(3e4)}),"get");return{runnerPlatform:e.GITHUB_ACTIONS==="true"?"github":void 0,workspace:e.GITHUB_WORKSPACE||void 0,serverUrl:s,apiUrl:a,repository:i&&r?{id:i,slug:r}:void 0,runId:e.GITHUB_RUN_ID||void 0,runAttempt:e.GITHUB_RUN_ATTEMPT||void 0,job:e.GITHUB_JOB||void 0,execution(){let u=n("GITHUB_RUN_ATTEMPT");if(!/^[1-9][0-9]*$/.test(u))throw new Error(`GITHUB_RUN_ATTEMPT is "${u}", not a positive whole number`);return{provider:"github",repository:{provider:"github",providerAccountId:n("GITHUB_REPOSITORY_OWNER_ID"),providerRepositoryId:n("GITHUB_REPOSITORY_ID")},providerRunId:n("GITHUB_RUN_ID"),providerRunAttempt:Number(u),workflowRef:n("GITHUB_WORKFLOW_REF")}},takeIdToken(){let u=e.ACTIONS_ID_TOKEN_REQUEST_URL,l=e.ACTIONS_ID_TOKEN_REQUEST_TOKEN;return delete e.ACTIONS_ID_TOKEN_REQUEST_URL,delete e.ACTIONS_ID_TOKEN_REQUEST_TOKEN,async A=>{if(!u||!l)throw new Error("The job cannot request an OIDC token. Give it the `id-token: write` permission.");let p=new URL(u);p.searchParams.set("audience",A);let g=await fetch(p,{headers:{Authorization:`Bearer ${l}`,Accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!g.ok)throw new Error(`GitHub refused the OIDC token request: ${g.status}`);let h=(await g.json().catch(()=>({}))).value;if(typeof h!="string"||!h)throw new Error("GitHub's OIDC token response carried no token");return Ol(h),h}},webIdentity(){return!e.ACTIONS_ID_TOKEN_REQUEST_TOKEN?.trim()||!e.ACTIONS_ID_TOKEN_REQUEST_URL?.trim()?void 0:{token:t.getIDToken??(l=>yM(l)),runId:e.GITHUB_RUN_ID}},v3RunsOnly:!1,assumesBedrockRole:!1,namesSourceToMcp:!1,runSettingsFromApp:!1,checkSourceName(u){for(let l of[u.namespace,u.name])if(!h$.test(l))throw new Error(`"${l}" is not a repository name`)},cloneUrl(u){return`${s}/${u.namespace}/${u.name}.git`},gitAuthEnv(u){return u?{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${s}/.extraheader`,GIT_CONFIG_VALUE_0:nge(u)}:{}},async pullRequest({namespace:u,name:l},A,p){if(![u,l].every(y=>h$.test(y)))throw new Error("the repository name is not valid");let g=await c(`${a}/repos/${u}/${l}/pulls/${A}`,p);if(!g.ok)throw new Error(`GitHub answered ${g.status}`);let h=await g.json();return{...typeof h.title=="string"?{title:h.title}:{},...typeof h.body=="string"?{body:h.body}:{},...typeof h.merged=="boolean"?{merged:h.merged}:{},...h.merged===!0&&typeof h.merge_commit_sha=="string"?{mergeCommit:h.merge_commit_sha}:{},...h.merged===!0&&typeof h.head?.sha=="string"?{mergedHead:h.head.sha}:{}}},async commit(u,l,A){let[p,g,...h]=u.split("/");if(h.length||![p,g].every(y=>y!==void 0&&h$.test(y)))return{lookup:"unknown"};try{let y=await c(`${a}/repos/${p}/${g}/commits/${encodeURIComponent(l)}`,A);if(y.status===404||y.status===422)return{lookup:"missing"};if(!y.ok)return{lookup:"unknown"};let E=await y.json();return typeof E.sha=="string"?{sha:E.sha}:{lookup:"missing"}}catch{return{lookup:"unknown"}}},async revokeToken(u,l){let A=await l(`${a}/installation/token`,{method:"DELETE",headers:{Authorization:`Bearer ${u}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(tge)});if(!A.ok&&A.status!==401)throw new Error(`GitHub answered ${A.status}`)}}}o(Dq,"githubRunnerHost");function _q(e=process.env){return g$(e)?Tq(e):Dq(e)}o(_q,"runnerHost");var rge=10*6e4;function ige(e,t){return e.getTime()-t.getTime()-rge}o(ige,"remainingBudgetMs");var Nq="This attempt revoked its scoped GitHub credentials; it mints no more.",sge=10*6e4;var oge=o(e=>!!e&&Object.keys(e).length===1&&e.contents==="read","onlyReads"),age=3e4,cge=3,Uq=30,Mr=class extends Error{constructor(n,i,r,s){super(n);this.status=i;this.code=r;this.path=s}status;code;path;static{o(this,"AppRefusal")}},gi=class extends Error{static{o(this,"AppUnreachable")}},Qu=class extends gi{static{o(this,"AppNotReady")}},m$=class extends Qu{static{o(this,"RunnerProviderNotReady")}};function y$(e){let t;try{t=new URL(e)}catch{throw new Error(`skyrampAppOrigin "${e}" is not a URL`)}if(t.protocol!=="https:"||t.origin!==e.replace(/\/+$/,""))throw new Error(`skyrampAppOrigin must be an https origin, got "${e}"`);return t.origin}o(y$,"appOrigin");function Pq(e,t){if(!kc.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}o(Pq,"routeId");function uge(e,t){return`${e.replace(/\/+$/,"")}/runs/${t}`}o(uge,"skyrampRunPageUrl");function Mq(e,t,n,i){throw t<500&&t!==429?new Mr(e,t,n,i):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new m$(e):t===503&&n==="RUN_NOT_READY"?new Qu(e):new gi(e)}o(Mq,"refusedOrUnreachable");async function Oq(e,t,n,i,r,s=1/0){let a=y$(e.origin),c=`The time limit for ${t} ${n} was reached`,u,l=0;for(let A=1;A<=cge||u instanceof Qu;A+=1){if(u instanceof Qu){if(l===Uq)throw u;l+=1,A-=1,e.log?.(`${u.message}; trying again (${l} of ${Uq}).`),await new Promise(p=>setTimeout(p,Math.max(0,Math.min(e.readyWaitMs??1e4,s-Date.now()))))}else A>1&&await new Promise(p=>setTimeout(p,Math.max(0,Math.min((e.retryDelayMs??2e3)*(A-1),s-Date.now()))));if(Date.now()>=s)throw new gi(c);try{let p,g=await(Number.isFinite(s)?Promise.race([e.idToken(a),new Promise((y,E)=>{p=setTimeout(()=>E(new gi(c)),Math.max(1,s-Date.now()))})]).finally(()=>{p&&clearTimeout(p)}):e.idToken(a));if(Date.now()>=s)throw new gi(c);let h=await(e.fetch??fetch)(new URL(n,a).toString(),{...i(g),redirect:"error",signal:AbortSignal.timeout(Math.max(1,Math.min(age,s-Date.now())))}).catch(y=>{throw new gi(y instanceof Error?y.message:String(y),{cause:y})});return await r(h)}catch(p){if(p instanceof Mr||Date.now()>=s)throw p;u=p}}throw u}o(Oq,"callWithRetries");function Lq(e,t,n,i,r){let s=i.headers.get("cf-ray");e.log?.(`Testbot V3: ${t} ${n} answered ${i.status}${s?`, cf-ray ${s}`:""}: ${r.replace(/\s+/g," ").slice(0,200)}`)}o(Lq,"logRefusal");function By(e,t,n,i,r){let s=t==="GET"?void 0:JSON.stringify(i),a=t==="PUT"&&/^\/api\/v1\/runner\/attempts\/[^/]+\/report$/.test(n)&&s!==void 0&&Buffer.byteLength(s,"utf8")>$g;if(a&&Buffer.byteLength(s,"utf8")>vO)throw new Error("The report exceeds the app's 16 MiB expanded report limit");let c=a?new Uint8Array((0,Fq.gzipSync)(s)):s;if(a&&c.length>$g)throw new Error("The compressed report exceeds the app's 1 MiB report upload limit");return Oq(e,t,n,o(l=>({method:t,headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json",Accept:"application/json",...a?{"Content-Encoding":"gzip"}:{}},body:c}),"request"),async l=>{let A=await l.text().catch(()=>""),p={};try{p=JSON.parse(A)}catch{}if(l.ok)return p.data;Lq(e,t,n,l,A);let g=p.error?.fields,h=typeof g?.path=="string"&&typeof g.reason=="string"?` at ${g.path}: ${g.reason}`:"",y=`The Skyramp app refused ${t} ${n}: ${l.status} ${p.error?.code??"no error code"}${h}`;return Mq(y,l.status,p.error?.code,typeof g?.path=="string"?g.path:void 0)},r)}o(By,"callApp");function lge(e,t,n){return Oq(e,"GET",t,o(r=>({method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/octet-stream"}}),"request"),async r=>{if(!r.ok)return Lq(e,"GET",t,r,await r.text().catch(()=>"")),Mq(`The Skyramp app refused GET ${t}: ${r.status}`,r.status);let s=Buffer.from(await r.arrayBuffer());if(s.length>n)throw new Mr(`The Skyramp app answered GET ${t} with more than ${n} bytes`,r.status);return s})}o(lge,"callAppBytes");var JA=class{constructor(t,n,i,r,s,a,c,u,l,A=[],p=[],g){this.attemptId=t;this.attemptNumber=n;this.deadlineAt=i;this.manifest=r;this.deps=s;this.license=a;this.requestedBy=c;this.writeAllowed=u;this.claudeCodeVersion=l;this.deployedPins=A;this.statedPins=p;this.runSettings=g}attemptId;attemptNumber;deadlineAt;manifest;deps;license;requestedBy;writeAllowed;claudeCodeVersion;deployedPins;statedPins;runSettings;static{o(this,"V3Attempt")}budgetMs(t){return ige(this.deadlineAt,t)}get skyrampRunUrl(){return uge(y$(this.deps.origin),this.manifest.runId)}log(t){this.deps.log?.(t)}send(t,n,i,r){return By(this.deps,t,n,i,r)}readBytes(t,n){return lge(this.deps,t,n)}issuedTokens=[];closure;modelKey;modelCredentials=[];credentials={};revocation;token(){return this.cachedToken("run")}readOnlyToken(){return this.cachedToken("read")}async cachedToken(t){if(this.revocation)throw new Error(Nq);let n=(this.deps.now??(()=>new Date))().getTime(),i=this.credentials[t],r=i&&await i.catch(()=>{});if(this.credentials[t]!==i)return(await this.credentials[t]).token;if(r&&r.expiresAt-n>=sge)return r.token;if(this.revocation)throw new Error(Nq);let s=t==="read",a=s?{schemaVersion:1,access:t}:{schemaVersion:1},c=s?"read-only":"scoped",u=this.send("POST",`/api/v1/runner/attempts/${this.attemptId}/credentials`,a).then(l=>{let A={...l,token:l.token??this.jobToken()};if(this.issuedTokens.push(A.token),this.deps.mask?.(A.token),A.anthropicApiKey&&this.deps.mask?.(A.anthropicApiKey),s&&l.token&&!oge(A.permissions))throw new Error(`The Skyramp app was asked for a read-only GitHub token, but its token grants ${JSON.stringify(A.permissions??null)}`);!s&&!r&&A.anthropicApiKey&&(this.modelKey=A.anthropicApiKey),this.deps.onTokenGranted?.(t);let p=r?"Renewed":"Received";return l.token&&this.deps.log?.(`${p} ${c} GitHub credentials; they expire at ${A.expiresAt}.`),{token:A.token,expiresAt:l.token?new Date(A.expiresAt).getTime():Number.POSITIVE_INFINITY}},l=>{if(this.deps.onTokenRefused?.(l,t),!(l instanceof Mr)||l.code!=="CREDENTIALS_UNAVAILABLE")throw l;let A=o(h=>[...new Set(h.map(y=>y.namespace))].join(", "),"unique"),p=this.manifest.sources.map(h=>h.repository);if(new Set(p.map(h=>h.providerAccountId)).size>1)throw new Mr(`${l.message}. The run's repositories are on more than one GitHub account (${A(p)}), which Skyramp does not support yet.`,l.status,l.code);let g=A([...p,this.manifest.execution.repository]);throw new Mr(`${l.message}. Check the Skyramp GitHub App installation on ${g}: it must be installed and not suspended, have access to these repositories, and have accepted the App's current permissions. Each account must also be connected to your Skyramp organization.`,l.status,l.code)});return this.credentials[t]=u,(await u).token}jobToken(){if(this.deps.sourceToken)return this.deps.sourceToken;throw new Error("The app answered the credentials request without a token, and the job gave Testbot none of its own: on Azure Pipelines, set SYSTEM_ACCESSTOKEN to $(System.AccessToken) in the Testbot step's env.")}sourceFetch(t){return t.fetch??this.deps.fetch??fetch}revokeTokens(t={}){let n=t.host??_q();return this.revocation??=n.revokeToken?this.revokeIssued(i=>n.revokeToken(i,this.sourceFetch(t))):Promise.resolve([]),this.revocation}async revokeIssued(t){let n=[...this.issuedTokens],i=Promise.all(n.map(a=>this.revokeOne(a,t)));await Promise.all(Object.values(this.credentials).map(a=>a.catch(()=>{})));let r=this.issuedTokens.filter(a=>!n.includes(a));return[...await i,...await Promise.all(r.map(a=>this.revokeOne(a,t)))].filter(a=>a!==void 0)}async revokeOne(t,n){try{await n(t);return}catch(i){return`token ${this.issuedTokens.indexOf(t)+1} of ${this.issuedTokens.length}: ${i instanceof Error?i.message:String(i)}`}}};async function jq(e,t,n){Pq(e,"run id"),y$(n.origin);let i=Gb(e,t),r=`/api/v1/runner/runs/${e}/attempts`,s;try{s=await By(n,"POST",r,i)}catch(l){if(!(l instanceof Mr&&l.status===400&&l.path==="$.statedPins"))throw l;i=Gb(e,t,{statedPins:!1}),s=await By(n,"POST",r,i)}let a=VO(s);if(a.manifest.runId!==e)throw new Error(`The app answered the handshake of run ${e} with the manifest of another run (${a.manifest.runId})`);let c=a.manifest.sources.find(l=>l.repository.provider!==i.execution.provider);if(c)throw new Error(`The manifest of run ${e} names ${c.repository.namespace}/${c.repository.name} on ${c.repository.provider}, but this job runs on ${i.execution.provider}`);dge(a.manifest,[...a.deployedRevisions??[],...a.statedRevisions??[]]),a.runToken&&n.mask?.(a.runToken);let u=a.runToken?{entitlements:a.entitlements??[],runToken:a.runToken}:void 0;return new JA(a.attempt.id,a.attempt.number,new Date(a.attempt.deadlineAt),a.manifest,n,u,a.requestedBy??void 0,a.writeAllowed,a.claudeCodeVersion??void 0,a.deployedRevisions??[],a.statedRevisions??[],a.runSettings)}o(jq,"startV3Attempt");function dge(e,t){if(t.length===0)return;if(!xO(e))throw new Error(`The app pinned an attempt of a ${e.trigger.kind} run; only a scheduled run or unchosen manual run's retry is pinned to an earlier attempt's read`);let n=new Set(e.sources.map(r=>oi(r.repository))),i=new Set;for(let r of t){let s=oi(r.repository);if(!n.has(s))throw new Error(`The app pinned the attempt to repository ${r.repository.providerRepositoryId}, which is not a source of the run`);if(i.has(s))throw new Error(`The app pinned repository ${r.repository.providerRepositoryId} twice`);i.add(s)}}o(dge,"checkAttemptPins");async function E$(e,t){return MO.parse(await e.send("POST",`/api/v1/runner/attempts/${e.attemptId}/heartbeat`,{schemaVersion:1},t))}o(E$,"heartbeatV3Attempt");async function Vq(e,t=()=>new Date,n){if(e.closure)return e.closure;let i=await E$(e,n).then(r=>OO(r,t())).catch(()=>null);return i&&(e.closure=i),i}o(Vq,"closedV3Attempt");var bGe=10*6e4;var vGe=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var wGe=d.object({tests:d.object({placements:d.array(d.unknown()).optional()}).passthrough().optional()}).passthrough(),BGe=d.object({repository:Mb,testType:d.string(),directory:d.string()}).passthrough();var kGe=d.object({report:d.object({language:d.string()}).passthrough()}).passthrough();var SGe=d.object({environment:d.object({components:d.array(d.unknown()).optional(),dependencies:d.array(d.unknown()).optional()}).passthrough()}).passthrough(),QGe=d.object({environment:d.object({offLimits:d.unknown().optional()}).passthrough()}).passthrough();var RGe=d.object({name:d.string().min(1),provision:d.literal("existing"),url:d.string().min(1),repository:Mb.optional(),revisionUrl:d.string().min(1).optional()}).passthrough(),xGe=d.object({name:d.string().min(1),url:d.string().nullable(),versionUrl:d.string().nullable(),notes:d.string().nullable()}).passthrough();var $Ge=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);function Gq(e){let t=o(n=>e.testResults.filter(i=>i.status===n).length,"count");return{passed:t("Pass"),failed:t("Fail"),skipped:t("Skipped")}}o(Gq,"statusCounts");function Age(e){let{passed:t,failed:n,skipped:i}=Gq(e);return t+n===0?{sufficiency:"insufficient",rationale:i>0?`Every test was skipped (${i}), so nothing was validated.`:"No test ran, so nothing was validated.",gaps:["No test ran against the frozen sources."],acceptedEvidence:[],actionRequired:[]}:{sufficiency:"sufficient",rationale:`${t+n} tests ran against the frozen sources: ${t} passed, ${n} failed${i?`, ${i} skipped`:""}.`,gaps:[],acceptedEvidence:[],actionRequired:[]}}o(Age,"executedTestsValidation");function pge(e,t){let n=e.map(c=>({result:c,repository:c.repository??t,path:c.fileName||c.testType})),i=new Map;for(let c of n){let u=`${c.repository}:${c.result.testType}:${c.path}`;i.set(u,(i.get(u)??0)+1)}let r=n.map(({result:c,repository:u,path:l})=>{let A=(i.get(`${u}:${c.testType}:${l}`)??0)>1;return c.resultId??Lb(u,c.testType,l,A&&c.endpoint||void 0)}),s=new Map;for(let c of r)s.set(c,(s.get(c)??0)+1);let a=new Set(r.filter(c=>s.get(c)===1));return n.map(({result:c,repository:u},l)=>{let A=r[l],p=A;if(s.get(A)>1&&a.has(A))for(let g=2;a.has(p)||p===A;g+=1)p=A.includes("#")?`${A}.${g}`:`${A}#${g}`;return a.add(p),{...c,repository:u,resultId:p}})}o(pge,"withResultIds");function fge({notTranslated:e,...t},n){let i=pge(t.testResults,n);return{...t,testResults:i,...gge(t,i,n),validation:yge(t,hge(t,t.validation??Age(t))),traceVersion:1}}o(fge,"v3Report");function gge(e,t,n){if(!e.testExecutionContexts)return{};let i=new Set,r=o(c=>{let u=c;for(let l=2;i.has(u);l+=1)u=`${c}#${l}`;return i.add(u),u},"unique"),s=[],a=new Map;for(let{repository:c,...u}of e.testExecutionContexts){let l=u.status==="not_run"?[]:t.filter(A=>A.fileName===u.test&&A.repository===(c?.trim()||n));l.length||s.push(u);for(let{resultId:A}of l){let p=a.get(A),g=p!==void 0&&s[p].cleanup.status==="failed"?s[p].cleanup:u.cleanup,h={...u,cleanup:g,test:A,resultId:A};p===void 0?a.set(A,s.push(h)-1):s[p]=h}}for(let c of s)c.resultId&&i.add(c.resultId);return{testExecutionContexts:s.map(c=>c.resultId?c:{...c,test:r(c.test.slice(0,512))}).slice(0,5e3)}}o(gge,"linkedContexts");function hge(e,t){let{passed:n,failed:i}=Gq(e);return t.sufficiency!=="sufficient"||n+i>0||t.acceptedEvidence.length>0?t:{...t,sufficiency:"insufficient",gaps:["No test ran and no existing evidence was accepted, so nothing was validated."]}}o(hge,"withEvidence");var mge={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};function yge(e,t){if(t.sufficiency==="sufficient")return t;let n=(e.caveats??[]).map(r=>mge[r.kind]).filter(r=>r!==void 0),i=[...new Set(n)].filter(r=>!t.actionRequired.includes(r));return i.length?{...t,actionRequired:[...i,...t.actionRequired]}:t}o(yge,"withModelProviderFailure");function Ege(e,t,n){let{language:i,report:r}=t;if(i==="en")return;let s={language:i,businessCaseAnalysis:r.businessCaseAnalysis},a=o((y,E,C)=>Array.isArray(y)&&Array.isArray(E)&&y.length===E.length?y.map(I=>({[C]:I[C]})):void 0,"rows"),c=e.validation;r.validation&&c&&c.rationale===n.validation.rationale&&JSON.stringify(c.gaps)===JSON.stringify(n.validation.gaps)&&r.validation.gaps.length===n.validation.gaps.length&&(s.validation={rationale:r.validation.rationale,gaps:[...r.validation.gaps]});let u=new Set((n.changes??[]).map(y=>y.id)),l=(r.changes??[]).filter(y=>u.has(y.id)).map(({id:y,text:E})=>({id:y,text:E}));l.length&&(s.changes=l);let A=a(r.issuesFound,n.issuesFound,"description");A&&(s.issuesFound=A);let p=a(r.newTestsCreated,n.newTestsCreated,"description");p&&(s.newTestsCreated=p);let g=a(r.testResults,n.testResults,"details");g&&(s.testResults=g);let h=a(r.caveats,n.caveats,"text");return h&&(s.caveats=h),s}o(Ege,"v3Display");async function zq(e,t){let n=bM([...e.issuedTokens,...t.secrets??[]]),i={...fge(t.report,t.workingSlug),...t.notTranslated?{notTranslated:t.notTranslated}:{}},r=t.translated&&Ege(t.report,t.translated,i),s=o(c=>GO({manifest:e.manifest,attemptNumber:e.attemptNumber,checkedOut:t.sources.map(u=>({repository:u.repository,revision:u.revision})),firstQualification:t.firstQualification,generatedTests:Vl(t.delivery,n),producer:t.producer,report:Vl(c&&r?{...i,display:r}:i,n),githubWrites:t.githubWrites}),"build"),a=s(!0);r&&Buffer.byteLength(JSON.stringify(a),"utf8")>$g&&(a=s(!1)),await e.send("PUT",`/api/v1/runner/attempts/${e.attemptId}/report`,a)}o(zq,"uploadV3Report");async function qq(e,t){return Pq(e.attemptId,"attempt id"),By(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,zO({reportUploaded:e.reportUploaded,recipeUploaded:e.recipeUploaded,revisionsUploaded:e.revisionsUploaded,cancelled:e.cause==="cancelled",timedOut:e.cause==="timed_out",setupFailed:e.cause==="setup_failed",checkoutFailed:e.cause==="checkout_failed"||e.cause==="merge_conflict"&&!e.conflict,mergeConflict:e.cause==="merge_conflict"?e.conflict:void 0,environmentUnverified:e.cause==="environment_unverified",runnerProviderNotReady:e.cause==="runner_provider_not_ready",credentialMissing:e.cause==="credential_missing",modelProviderDenied:e.cause==="model_provider_denied",modelProviderUnavailable:e.cause==="model_provider_unavailable"}))}o(qq,"endV3Attempt");0&&(module.exports={AppRefusal,AppUnreachable,AttemptEndReason,DeliveryStatus,GitHubWriteKind,NoReportCause,SourceProvider,V3Attempt,ValidationSufficiency,closedV3Attempt,endV3Attempt,heartbeatV3Attempt,startV3Attempt,uploadV3Report});
|
|
201
201
|
/*! Bundled license information:
|
|
202
202
|
|
|
203
203
|
undici/lib/web/fetch/body.js:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@skyramp/testbot-core",
|
|
3
|
-
"version": "0.13.0-v3.
|
|
3
|
+
"version": "0.13.0-v3.378",
|
|
4
4
|
"description": "Skyramp Testbot engine: AI-powered deterministic test generation, execution and maintenance",
|
|
5
5
|
"main": "dist/main.js",
|
|
6
6
|
"//files": "An explicit allowlist, never a glob. `dist/` is gitignored, so without this key npm's .gitignore fallback would publish a package with no engine in it; with a glob it would publish the sourcemaps, whose sourcesContent embeds every src/*.ts verbatim. dist/VERSION.json exists only in a release-engine.yml build.",
|