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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 ${_x(t)}`}}o(Dx,"scriptedCommand");function _x(e){return`'${e.split("'").join("'\\''")}'`}o(_x,"shQuote");function Nx(e){return Ux(e)&&xR(e).length===0&&TR(e.inputs?.sharedEnvironment).length===0}o(Nx,"sutIsHealthy");function Ux(e){let t=aAe(e);if(!t&&e.state.stages.deploy?.status!=="passed")return!1;let n=Ge(e,"deploy.json");return n?oAe(n):!t}o(Ux,"sutCameUp");function oAe(e){return e?.outcome==="clean"||e?.outcome==="recipe-drift"}o(oAe,"deployCameUp");function aAe(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(aAe,"broughtUpByPlan");var hTe=10*6e4;var ay=(r=>(r.RestApi="rest-api",r.Frontend="frontend",r.FullStack="full-stack",r.Other="other",r))(ay||{}),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||{}),Mx=(i=>(i.Skyramp="skyramp",i.External="external",i.Unknown="unknown",i))(Mx||{}),Ox=(r=>(r.Cascade="cascade",r.Restrict="restrict",r.Orphan="orphan",r.Unknown="unknown",r))(Ox||{}),gi=(r=>(r.RequirementReference="requirement-reference",r.Spec="spec",r.PrDescription="pr-description",r.CouldBreak="could-break",r))(gi||{}),et=d.string().trim().min(1),Eu=et.describe("file:line"),e2=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'),Px=d.object({method:et,path:et,service:d.string().optional(),evidence:Eu,repository:TA}),pAe=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(gi).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.")}),fAe=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)")}),gAe=d.object({id:et.describe("short-slug"),file:et,line:d.number().optional(),claim:e2("shorten it to the one sentence that states the defect, and move the supporting detail into `evidence`"),severity:d.nativeEnum(da),evidence:e2("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")}),hAe=d.object({name:et,language:d.string().optional(),framework:d.string().optional(),evidence:Eu,repository:TA}),mAe=d.object({dir:et,framework:d.string().optional(),kind:d.nativeEnum(Mx),evidence:Eu,repository:TA}),yAe=d.object({from:et,to:et,onDelete:d.nativeEnum(Ox),evidence:Eu}),EAe=d.object({entity:et,field:et,values:d.array(d.string()),evidence:Eu}),IAe=d.object({entities:d.array(d.object({name:et,evidence:Eu})),references:d.array(yAe).describe("INBOUND references \u2014 what still points at an entity when it is deleted"),stateFields:d.array(EAe)}),Lx=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(ay),primaryLanguage:et,languages:d.array(d.string()),frameworks:d.array(d.string())}),services:d.array(hAe),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(Px),modified:d.array(Px),removed:d.array(Px)}),existingTests:d.object({locations:d.array(mAe)}),entityMap:IAe,requirements:d.array(pAe).describe("from a spec (attached or linked) and/or the PR description; empty when neither states a testable obligation"),behaviors:d.array(fAe),findings:d.array(gAe),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 wAe=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||{}),t2=(i=>(i.Spec="spec",i.PrDescription="pr-description",i.Inferred="inferred",i))(t2||{}),n2=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(wAe).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(t2).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")}),cy=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 xTe=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 $Te=["stale_test","open_question"],TTe=["low","medium","high","critical"];var r2=String.raw`(?:\[[^\]]*\]|\([^)]*\))`,BAe=String.raw`(?:["'\u201c\u2018\x60]|\*{1,2})?[^\s:"'\u201c\u201d\u2018\u2019\x60*()[\],]+(?:["'\u201d\u2019\x60]|\*{1,2})?`,i2=String.raw`(?:${r2}|${BAe}(?:\s*${r2})?)`,s2=String.raw`(?:\s*:|\s+[\u2014\u2013-])`,UTe=new RegExp(String.raw`^\s*(?:${i2}(?:,\s*${i2})*(?::L?\d+(?:[-\u2013]\d+)?${s2}?|${s2})|\[[^\]\s]+\]|\([^)\s]+\))\s+`);var js=Qe(require("fs")),bu=Qe(require("path")),u2=require("child_process");var on="{junit}",uy=(r=>(r.Junit="junit",r.Trx="trx",r.GoTestJson="go-test-json",r.JestJson="jest-json",r))(uy||{}),jx=(t=>(t.Minitest="minitest",t))(jx||{}),o2=d.string().trim().min(1),Iu=d.object({cwd:o2.describe('repo-relative directory the command starts in ("." for the root)'),argv:d.array(o2).min(1).describe(`the command as separate arguments, run without a shell; for a junit or trx report an argument or env value holds ${on}, 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(uy).describe(`junit (JUnit XML to ${on}), trx (to ${on}), jest-json (Jest's --json or Vitest's --reporter=json, --outputFile=${on}), or go-test-json (go test -json on the command's output)`),reporter:d.nativeEnum(jx).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 Cu="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)",LTe=`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 ${on} in the reporter's argument or env setting), trx (a TRX file to ${on}, which every dotnet test writes with its built-in logger), jest-json (Jest's --json --outputFile=${on}, or Vitest's --reporter=json --outputFile=${on}: 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 ${on}: 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 ${on} itself. A setting the tests or reporter read goes in "env" (RAILS_ENV=test, or PLAYWRIGHT_JUNIT_OUTPUT_FILE=${on} with playwright test --reporter=junit): the run sets it, so never wrap the command in a shell to set one. The run replaces ${on} in argv and env with its report path, executes the command, and reads that report.`;var Ls=(r=>(r.ExistingEvidenceSufficient="existing_evidence_sufficient",r.TargetedUnit="targeted_unit",r.RuntimeRequired="runtime_required",r.BlockedPreflight="blocked_preflight",r))(Ls||{}),zi=(s=>(s.ExistingEvidence="existing_evidence",s.Unaffected="unaffected",s.ExistingUnit="existing_unit",s.NewUnit="new_unit",s.Runtime="runtime",s))(zi||{}),Vx=(n=>(n.Repository="repository",n.Testbot="testbot",n))(Vx||{}),Gx=(i=>(i.Identified="identified",i.Passed="passed",i.Failed="failed",i))(Gx||{}),Pn=d.string().trim().min(1),kAe=d.string().regex(/^[a-z0-9][a-z0-9-]*$/,"must be a short lowercase slug").describe("short-slug");var SAe=d.object({id:kAe,source:d.nativeEnum(Vx),kind:d.nativeEnum(Is),outcome:d.nativeEnum(Gx),summary:Pn.max(400).describe("one line: what it shows"),tests:d.array(Pn).optional().describe("source repository: the existing tests, as repo-relative paths, optionally path::test-name"),repository:Pn.optional().describe("source repository: owner/repo the tests live in, when the run has several checkouts; omit for the working checkout"),command:Pn.optional().describe("source testbot: the exact command you ran, as you ran it"),run:Iu.optional().describe(`source repository, for tests in ${Cu}: 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`)}),QAe=d.object({behaviorId:Pn.describe("an id from analyze's behaviors"),mechanism:d.nativeEnum(zi),evidenceIds:d.array(Pn).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')}),zx=(i=>(i.Browser="browser",i.RunningApp="running-app",i.Outside="outside",i))(zx||{}),RAe=d.object({behaviorId:d.string().trim().optional().describe("an id from analyze's behaviors, when it is about one"),missing:Pn.max(600).describe("the evidence that is required and cannot be obtained in this run"),needs:d.nativeEnum(zx).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)")}),xAe=d.object({file:Pn.describe("the changed file the failure is in"),repository:Pn.optional().describe("owner/repo the file is in, when the run has several checkouts; omit for the working checkout"),reason:Pn.max(300).describe("what prerequisite the change fails"),evidence:Pn.max(400).describe("the error line, quoted")}),$Ae=d.object({behaviorId:Pn.describe("an id from analyze's behaviors"),reason:Pn.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(Ls),evidence:d.array(SAe).describe("evidence this session found or produced; CI results are the ci-<n> items and are not restated here"),plan:d.array(QAe).describe("how each changed behavior's evidence is obtained"),gaps:d.array(RAe),outOfScope:d.array($Ae).optional().describe("behaviors analyze found that this change neither changes nor states"),blocked:xAe.optional().describe("only for blocked_preflight"),rationale:Pn.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=Ge(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 NAe(e){return yn(Qb,e).errors}o(NAe,"validateGenerateOutput");function UAe(e,t=[]){let{value:n,error:i}=Tt(e,t);if(i)return{errors:[i]};let r=NAe(n);return r.length>0?{errors:r}:{generate:n,errors:[]}}o(UAe,"parseGenerateText");function ly(e,t=[]){return UAe(e.stdout,t)}o(ly,"parseGenerateFromSession");function FAe(e){return e.generate.filter(t=>t.type!=="ui").map(t=>t.id)}o(FAe,"backendCases");function l2(e){return e.generate.filter(t=>t.type==="ui").map(t=>t.id)}o(l2,"uiCases");var dy={backend:{stage:"generate",cases:FAe,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:z1,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:l2,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:q1,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."}},CDe=Tn("generate-schema",(e,t)=>ly(t,e.secretValues));function PAe(e){let t=dy[e];return{name:`${t.stage}-coverage`,verify(n,i){let{generate:r,errors:s}=ly(i,n.secretValues);if(!r)return jt(this.name,s);let a=NA(n);if(!a)return jt(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(l2(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}:jt(this.name,u)}}}o(PAe,"generateCoverageGateFor");function MAe(e){let t=dy[e];return{name:`${t.stage}-intent`,verify(n,i){let{generate:r,errors:s}=ly(i,n.secretValues);if(!r)return jt(this.name,s);let a=NA(n);if(!a)return jt(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=jt(this.name,u);return A>0&&A===u.length&&l.size>0?{...p,droppable:[...l]}:p}}}o(MAe,"generateIntentGateFor");function OAe(e){let t=dy[e];return n=>{if(!n.inputs.skyrampMcp?.command||e==="backend"&&!Nx(n))return;let i=bu.join(n.outputsDir,`${t.stage}-stream.ndjson`);if(!(!js.existsSync(i)||t.usedCodegen(i)))return J1(i)?t.codegenHint:"Skyramp codegen tools were configured but the MCP server did not connect this session, so they were not available. Hand-authoring was the only option; this is an environment problem, not yours."}}o(OAe,"codegenRetryHintFor");var bDe=PAe("backend"),vDe=MAe("backend"),wDe=OAe("backend");var a2=o(e=>e.replace(/\s+/g,""),"squeeze");var qx={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"]])qx[e]=qx[t];function LAe(e,t){if(e.includes(fd(t))||a2(e).includes(a2(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(fd(i)))?!0:zAe(e,t)}o(LAe,"evidenceFound");var jAe=/\bassert\w*\b|\bexpect\s*\(|\.should\b|\brequire\s*\(/i,VAe=12,GAe=/,\s*\(\s*#|,\s*f?["'`]|\s+#\s|\s+\/\/|\s*\((?:line|lines|at line)\b|\s*,\s*$/i;function zAe(e,t){let n=t.split(/\s*;\s*|\s*\.\.\.\s*|\r?\n/),i=0;for(let r of n){let s=jAe.exec(r);if(!s)continue;let a=r.slice(s.index),c=GAe.exec(a);if(c&&(a=a.slice(0,c.index)),a=fd(a).replace(/[,\s]+$/,""),a.length<VAe||!e.includes(a))return!1;i++}return i>0}o(zAe,"annotatedAssertionFound");function qAe(e,t){let n=new Set,i=[],r=new Set;for(let s of e.tests){let a=bu.resolve(t,s.file);if(!js.existsSync(a))continue;let c=fd(js.readFileSync(a,"utf-8"));for(let u of s.assertions??[]){if(!LAe(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 JAe=/\.(spec|test)\.[cm]?[jt]sx?$/i;function d2(e){let t;try{t=(0,u2.execFileSync)("git",[...xi,"status","--porcelain","--untracked-files=all"],{env:en(),cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]})}catch{return}let n=o(r=>/_scaffold/i.test(r)||gd.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(d2,"testLitter");function HAe(e){let t=dy[e],n=e==="ui";return{name:`${t.stage}-no-litter`,verify(i){let r=d2(i.inputs.repositoryPath);if(r===void 0)return{name:this.name,passed:!0};let s=r.filter(a=>JAe.test(a)===n);return s.length===0?{name:this.name,passed:!0}:jt(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(HAe,"noLitterGateFor");var BDe=HAe("backend");var ZAe="write-stale-updates",KAe={[ZAe]:"stale test updates"};var UA=Qe(require("fs")),pa=Qe(require("path"));function g2(e,t=!1){return yn(WM(t),e).errors}o(g2,"validateAdaptOutput");function tpe(e,t=[],n=!1){let{value:i,error:r}=Tt(e,t);if(r)return{errors:[r]};let s=g2(i,n);return s.length>0?{errors:s}:{adapt:i,errors:[]}}o(tpe,"parseAdaptText");var npe="adapt-scratch",p2=`${npe}/adapt-result.json`;function h2(e,t){let n=pa.join(e.outputsDir,p2),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:[`${p2} contains a secret value (token / credential) \u2014 never write it anywhere`]};let r=hd(e.inputs?.sharedEnvironment).length>0,s=tpe(t.stdout,e.secretValues,r);if(s.adapt)return s;let a=i!==void 0?Vo(n):void 0;return a!==void 0&&g2(a,r).length===0?{adapt:a,errors:[]}:s}o(h2,"parseAdaptFromSession");var n_e=Tn("adapt-schema",h2);var m2=require("child_process");function Jx(e){return rpe(e)??[]}o(Jx,"statusEntries");function rpe(e){let t;try{t=(0,m2.execFileSync)("git",[...xi,"status","--porcelain","-z","--untracked-files=all"],{env:en(),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(rpe,"readStatusEntries");var A_e=2*1024*1024;var Ay=d.string().trim().min(1),ipe=d.object({cwd:Ay.describe(`directory the command starts in, relative to the test's checkout ("." for its root)`),argv:d.array(Ay).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")}),spe=d.object({file:Ay.describe("a file of the test's checkout, relative to its root"),line:Ay.describe("a line of that file, quoted exactly from where its command starts to its end")}),y2=d.object({collected:d.boolean().describe("whether the repo's CI runs this test as it is"),steps:d.array(spe).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:ipe.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 ae=d.string().trim().min(1),dpe=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"),Ape=d.preprocess(dpe,d.object({id:ae.describe(`its requirement's id plus a letter, e.g. "R1a", "AC-3a"`),clause:ae.describe("one testable part of the requirement"),expected:ae.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(Vi).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)")})),I2=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:ae.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`}),ppe=d.object({id:ae.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:ae,source:d.nativeEnum(gi).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:ae.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:ae.regex(Es).describe("the key of another uploaded document stating the same obligation"),says:ae.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(I2).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(Ape)}),C2=(r=>(r.ServerError="server-error",r.DataLost="data-lost",r.FinalState="final-state",r.DerivedValues="derived-values",r))(C2||{}),fpe=d.object({id:ae.describe('e.g. "F1"'),file:ae,line:d.number().optional(),claim:ae.describe("the defect, in one sentence"),severity:d.nativeEnum(da),evidence:ae.describe("the code line, or the probe request and response, that shows it"),conflictsWith:d.array(ae).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(C2).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)")}),gpe=d.object({id:ae.describe('e.g. "Q1"'),question:ae.describe("what is unsettled, as a question the PR author can answer"),readings:d.array(ae).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(I2).optional().describe("when sources of the same rank disagree on it: each of them")}),hpe=d.object({id:ae.describe('unique, a short kebab-case name for what the case checks, e.g. "ship-twice-409"'),type:d.nativeEnum(Vi).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:ae.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:ae.describe("what the test does"),expected:ae.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")}),mpe=d.object({test:ae.describe("existing test file"),action:d.nativeEnum(Ai),reason:ae,mutates:d.boolean().optional().describe("true when the maintained test changes state"),clauses:d.array(ae).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")}),E2=d.array(vb).optional(),ype=d.object({components:d.preprocess(e=>E2.safeParse(e).success?e:void 0,E2).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(Wl)).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:ae,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()}),Y_e=d.object({schemaVersion:d.literal(1),requirements:d.array(ppe),findings:d.array(fpe),cases:d.array(hpe).describe("a second test for a clause, and one case per finding that fails on this branch"),questions:d.array(gpe).optional().describe("behaviours the change leaves unsettled; no case asserts any of them"),maintenance:d.array(mpe),journeys:d.array(n2).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:ae,why:ae})).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(ae).min(1).describe("changed components, as the change lists them"),why:ae})).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:ype.optional().describe("omit when no app was needed or none was started"),summary:ae.describe("one paragraph: what the change does and where the risk is")});var FA=(n=>(n.Backend="backend",n.Ui="ui",n))(FA||{});var Vs=(r=>(r.Added="added",r.Updated="updated",r.Deleted="deleted",r.Unchanged="unchanged",r))(Vs||{}),Epe=d.object({file:ae.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(Vs).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:ae.describe("the requirement or clause id the change deliberately alters"),line:ae.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:ae,status:d.nativeEnum(fr),runtimeTargets:id.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:ae,evidence:ae})).optional().describe("per covered case, the assertion line that checks its expected outcome"),functions:d.array(d.object({name:ae.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(ae).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(rd).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:ae.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:y2.optional().describe("for a file you added or updated: whether the repo's CI will run it, and how you know"),run:Iu.optional().describe(`for a file in ${Cu}, 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 ${on}, or go-test-json); Testbot runs it before write ends and re-runs the tests with it`)}),Ipe=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"),Cpe=d.preprocess(Ipe,d.object({description:ae.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(ae).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(ae).optional().describe("the plan's requirement or clause ids it violates")})),W_e=d.object({schemaVersion:d.literal(1),tests:d.array(Epe),notWritten:d.array(d.object({case:ae,reason:ae,coveredBy:d.object({file:ae.describe("the test file, relative to the working checkout; prefix a related checkout as for tests[].file"),name:ae.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(cy).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:ae,manifest:ae.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:ae.optional().describe("owner/repo of the manifest's checkout; omit for the repo under test"),reason:ae.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(ae).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:ae.describe("subject line at most 72 characters, following the repository's commit-message checks"),prTitle:ae.describe("at most 72 characters, following the repository's PR-title checks"),prBody:ae.describe("what the tests cover and what they found")}),report:d.object({summary:ae.describe("1-2 sentences for the PR author: does the change do what it says? No count of tests: the report gives it"),issues:d.array(Cpe).describe("every defect the tests found"),nextSteps:d.array(d.string()),noTests:d.array(d.object({repository:ae,reason:ae.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 Z_e={added:"place",updated:"update",deleted:"delete",unchanged:"verify"};var v2=(i=>(i.Requirement="requirement",i.PrDescription="pr_description",i.Code="code",i))(v2||{}),Jt=d.string().trim().min(1),bpe=d.object({expectation:Jt.max(300).describe("the behavior this assertion pins, in words"),source:d.nativeEnum(v2),expected:Jt.max(200).describe("the exact value or outcome asserted, as the test asserts it")}),vpe=d.object({file:Jt.describe("path of the NEW test file you wrote, relative to its repository"),repository:Jt.optional().describe("owner/repo the file lives in, when the run has several checkouts; omit for the working checkout"),framework:Jt.describe("the framework the repository runs this file with: pytest, jest, vitest, node-test, or the name of any other"),run:Iu.optional().describe(`for ${Cu}: how the run executes only the tests in names, with the repository's own runner writing JUnit XML to {junit}`),covers:d.array(Jt).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(Jt).min(1).describe("the test functions/cases in the file that provide evidence for that behavior, as the framework names them"),assertions:d.array(bpe).min(1)}),PA=(n=>(n.Updated="updated",n.Deleted="deleted",n))(PA||{}),b2=300,wpe=d.object({file:Jt.describe("path of the EXISTING test file you updated or deleted, relative to its repository"),repository:Jt.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:Jt.describe("the requirement or clause id the change deliberately alters"),line:Jt.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,b2):e,Jt.max(b2)).describe("what the change deliberately altered that made the test wrong")}),Hx=d.object({schemaVersion:d.literal(1),tests:d.array(vpe),maintained:d.array(wpe).optional().describe("existing tests the change made stale that you updated or deleted; omit when there were none"),defectsNotTested:d.array(d.object({id:Jt,reason:Jt.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(cy).optional().describe("one entry per planned user journey: the in-process test that walks it end to end"),journeysNotWritten:d.array(d.object({journey:Jt,missing:Jt.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:Jt.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 kpe(e){let{value:t,error:n}=Tt(e);if(n)return{errors:[n]};let{value:i,errors:r}=yn(Hx,t);return r.length?{errors:r}:{output:i,errors:[]}}o(kpe,"parseGenerateUnitText");function Spe(e){return kpe(e.stdout)}o(Spe,"parseGenerateUnitFromSession");var LNe=Tn("generate-unit-schema",(e,t)=>Spe(t));var py=String.raw`(?:node:)?(?:http|https|http2|net|tls|dgram)`,jNe=[[/\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+["']${py}["']|\bimport\s+["']${py}["']|require\(\s*["']${py}["']\s*\)|\bimport\(\s*["']${py}["']\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 lUe=new Set(["targeted_unit","existing_evidence_sufficient"]);var Upe="triage.json";var EFe=new Set(["existing_evidence","unaffected","existing_unit","new_unit","runtime"]),IFe={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 Fpe(e){let{value:t,error:n}=Tt(e);if(n)return{errors:[n]};let{value:i,errors:r}=yn(_A,t);return r.length?{errors:r}:{triage:i,errors:[]}}o(Fpe,"parseTriageText");function Ppe(e){return Fpe(e.stdout)}o(Ppe,"parseTriageFromSession");var CFe=Tn("triage-schema",(e,t)=>Ppe(t));function Mpe(e){let t=e.inputs?.pipeline;return t?e.state.stages[t==="two-step"?"plan":"triage"]:e.state.stages.triage??e.state.stages.plan}o(Mpe,"triageDecider");function Wx(e){if(Mpe(e)?.status==="passed")return Vo(R2.join(e.outputsDir,Upe))}o(Wx,"readTriage");function Zx(e){return tV($R(e.inputs,Ge(e,`${CA}.json`),Wx(e)?.sutRequired))}o(Zx,"revisionBlockReason");var bFe=new Set(["deploy","recommend","generate","generate-ui","adapt","generate-unit","native-run","finalize","deliver"]);var Pr=Qe(require("fs")),zs=Qe(require("path")),vq=Qe(require("crypto")),wq=require("child_process");var Kx=require("child_process"),vu=Qe(require("fs")),x2=Qe(require("os")),hy=Qe(require("path"));var Ope={onPath:o(e=>(0,Kx.spawnSync)("sh",["-c",`command -v ${e}`],{stdio:"ignore"}).status===0,"onPath"),run:o((e,t)=>(0,Kx.spawnSync)(e[0],e.slice(1),{cwd:t,stdio:"ignore",timeout:6e4}).status??1,"run")},gy={cleanup:o(()=>{},"cleanup")},Lpe=new Set(["pnpm","yarn"]);function $2(e,t=x2.tmpdir(),n=Ope){if(process.platform==="win32")return gy;try{let i=Qx(e);if(!Lpe.has(i)||n.onPath(i)||!n.onPath("corepack"))return gy;vu.mkdirSync(t,{recursive:!0});let r=vu.mkdtempSync(hy.join(t,"testbot-pm-")),s=o(()=>vu.rmSync(r,{recursive:!0,force:!0}),"cleanup");return n.run(["corepack","enable","--install-directory",r,i],e)!==0?(s(),gy):{dir:r,cleanup:s}}catch{return gy}}o($2,"packageManagerShims");function T2(e,t=process.env){return e.dir?{...t,PATH:[e.dir,t.PATH].filter(Boolean).join(hy.delimiter)}:t}o(T2,"withShims");var GA=require("crypto");function Ht(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(Ht,"codeSpan");function Xx(e){return e.functions?.length?e.functions:[(e.testType==="unit"?e.testId.split("::").slice(1).join("::").replace(/\[.*\]$/,""):"")||e.testId]}o(Xx,"rowFunctions");function wu(e){return new Set(e.flatMap(t=>Xx(t).map(n=>`${t.repository??""}\0${t.fileName}\0${n}`))).size}o(wu,"testCount");pc();var YFe=5*6e4,WFe=12*6e4,ZFe=2*6e4;var iPe=["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 hPe=[...mb,"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 my=Qe(kx());var zPe={jest:"jest",vitest:"vitest"};var kMe=new Set(["jest","vitest","npm-test","playwright"]);var OMe=5*6e4;var OA=Qe(require("path"));var dOe={python:"pytest",typescript:"playwright",javascript:"playwright"},AOe={pytest:"pytest",playwright:"playwright"};function zpe(e){return yn(qb,e).errors}o(zpe,"validateFinalizeOutput");function qpe(e,t=[]){let{value:n,error:i}=Tt(e,t);if(i)return{errors:[i]};let r=zpe(n);return r.length>0?{errors:r}:{finalize:n,errors:[]}}o(qpe,"parseFinalizeText");var Jpe="finalize-scratch";function Hpe(e,t){let n=qpe(e.stdout,t?.secretValues);if(!n.finalize||!t?.outputsDir)return n;let i=o((r,s)=>r.trim()&&Dx(r.trim(),OA.join(t.outputsDir,Jpe,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(Hpe,"parseFinalizeFromSession");var rLe=Tn("finalize-schema",(e,t)=>Hpe(t,e));function Ype(e){return yn(Lx,e).errors}o(Ype,"validateAnalysisOutput");function U2(e,t=[]){let{value:n,error:i}=Tt(e,t);if(i)return{errors:[i]};let r=Ype(n);return r.length>0?{errors:r}:{analysis:n,errors:[]}}o(U2,"parseAnalysisText");function Wpe(e,t=[]){return U2(e.stdout,t)}o(Wpe,"parseAnalysisFromSession");var SLe=Tn("analysis-schema",(e,t)=>Wpe(t,e.secretValues));var Yje=ag.rows.notRun(!0);var LA="kept, not ";var jA="(declined the planned ";function e$(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(e$,"assertionParts");var F2=new Set(["update","regenerate","delete"]);var Wje={update:"updated",regenerate:"regenerated",delete:"deleted",verify:"verified",none:"touched"};var P2=d.string().trim().min(1),t$=d.object({schemaVersion:d.literal(1).optional(),businessCaseAnalysis:P2.describe("1-2 sentences: what this change means for a user, and whether the evidence shows it working; no count of tests, which the report gives"),issuesFound:d.array(d.object({description:P2,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 efe(e){return yn(t$,e).errors}o(efe,"validateProseOutput");function tfe(e,t=[]){let{value:n,error:i}=Tt(e.stdout,t);if(i)return{errors:[i]};let r=efe(n);return r.length>0?{errors:r}:{prose:n,errors:[]}}o(tfe,"parseProseFromSession");var l1e=Tn("report-schema",(e,t)=>tfe(t,e.secretValues));var M2="<!-- skyramp-testbot -->",O2=F2,nfe=new Set(["lint","type","config"]),L2={critical:0,high:1,medium:2,low:3},J2=new Set(["Pass","Fail"]);var i$=o(e=>Co(oe().statusLabels,e),"statusLabel"),n$=o(e=>Co(oe().testTypeCellLabels,e),"testTypeLabel");function ze(e){return(e??"").replace(/\|/g,"\\|").replace(/\r?\n/g,"<br>").trim()}o(ze,"escCell");function j2(e){return e.inferred?" (inferred)":""}o(j2,"inferredMark");function V2(e,t){return!e||!J2.has(e)?"\u2014":t?`${i$(e)} (${ze(H2(t))})`:i$(e)}o(V2,"maintStatus");function H2(e){let t=o(i=>{let r=i.indexOf(": ");return r<0?i:Co(oe().staged.maintenanceActions,i.slice(0,r))+i.slice(r)},"action");if(e.startsWith(LA))return oe().staged.keptNot+t(e.slice(LA.length));let n=e.indexOf(jA);return n<0?e:e.slice(0,n)+oe().staged.declinedPlanned+t(e.slice(n+jA.length))}o(H2,"declineNote");function G2(e){return e.category!==void 0&&nfe.has(e.category.toLowerCase())}o(G2,"isTooling");function z2(e,t){return(L2[(e.severity??"").toLowerCase()]??4)-(L2[(t.severity??"").toLowerCase()]??4)}o(z2,"bySeverity");function q2(e){return`- ${e.severity?`**[${Co(oe().severityLabels,e.severity.toLowerCase()).toUpperCase()}]** `:""}${e.description.trim()}`}o(q2,"issueLine");function rfe(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(rfe,"unitTestOf");var Y2=o((e,t)=>e!==void 0&&t!==void 0&&e.replace(/^\.\//,"")===t.replace(/^\.\//,""),"samePath");function W2(e,t){return(e.testVideos??[]).find(n=>n.url&&t(n))?.url}o(W2,"videoLink");function s$(e,t){return W2(e,n=>Y2(n.fileName,t.fileName)&&(!n.repository||!t.repository||n.repository.toLowerCase()===t.repository.toLowerCase()))}o(s$,"resultVideoLink");function o$(e,t){return W2(e,n=>Y2(n.writtenAs??n.fileName,t))}o(o$,"journeyVideoLink");function ife(e,t,n){return n?s$(e,{fileName:t,repository:n}):o$(e,t)}o(ife,"requirementVideoLink");function sfe(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&&Wz(c,u)),"parentOf"),s=new Map;for(let a of e.testResults){let c=rfe(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??"":oe().staged.casesPassed(l,c.length,A)+(p?`; ${i.get(p)??""} ${p.details??""}`.replace(/; +/,"; ").trimEnd():"")}return t}o(sfe,"resultRows");function ofe(e){return e$(e).map(t=>t.expected===void 0?t.expectation:`${t.expectation}: ${Ht(t.expected)}`)}o(ofe,"unitAssertions");function r$(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(r$,"nothingExecuted");function Z2(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(M=>/^file-[a-f0-9]{16}-/i.test(M.id)).sort((M,ee)=>ee.id.length-M.id.length),p=o(M=>{let ee=A.find(O=>M.toLowerCase().startsWith(O.id.toLowerCase()));return ee?ee.label+M.slice(ee.id.length):M},"displayId"),g=[M2];if(a&&g.push(oe().staged.testsSourcePullRequest(Ht(a)),""),s){let M=s.name.replace(/\s+/g," ").trim().replace(/[<>[\]()*_`\\|#]/g,"\\$&").replace(/@/g,"@\u200D");g.push(s.kind==="person"?oe().staged.requestedByPerson(M):oe().staged.requestedByPolicy(M),"")}e.notTranslated&&g.push(Co(oe().staged.notTranslated,e.notTranslated),"");let h=o(M=>{i?g.push("<details>",`<summary>${M}</summary>`,""):g.push(`### ${M}`)},"sectionStart"),y=o(()=>{i&&g.push("","</details>"),g.push("")},"sectionEnd");if(c){for(let M of e.businessCaseAnalysis.trim().split(/\r?\n/))g.push(`> ${M}`);g.push("")}if(r$(e)&&g.push(oe().staged.noLiveApp(wu(e.newTestsCreated)),""),u&&e.newTestsCreated.length){let M=new Map;for(let O of e.newTestsCreated){if(O.testType!=="unit")continue;let ke=Xx(O)[0],ge=M.get(O.fileName)??{functions:new Set,endpoints:[],descriptions:new Map};O.endpoint&&!ge.endpoints.includes(O.endpoint)&&ge.endpoints.push(O.endpoint);let q=O.description?.trim()??"",P=ge.descriptions.get(ke)??[];P.includes(q)||P.push(q),ge.functions.add(ke),ge.descriptions.set(ke,P),M.set(O.fileName,ge)}let ee=e.newTestsCreated.filter(O=>O.testType!=="unit");h(oe().testRecommendationsImplementedHeader(wu(e.newTestsCreated),ee.length+wu(e.newTestsCreated.filter(O=>O.testType==="unit"))));for(let[O,{functions:ke,endpoints:ge,descriptions:q}]of M){let P=ke.size;g.push(oe().staged.unitTestsInFile(`\`${O}\``,P,ge.map(Ft=>`\`${Ft}\``).join(", ")),"");let mt=new Map;for(let[Ft,ct]of q){let Wt=ct.join("\0"),It=mt.get(Wt)??{fns:[],descriptions:ct};It.fns.push(Ft),mt.set(Wt,It)}let Ze=0;for(let{fns:Ft,descriptions:ct}of mt.values()){g.push(`${++Ze}. ${Ft.map(It=>`\`${It}\``).join(", ")}`);let Wt=[...new Set(ct.flatMap(It=>ofe(It)))];for(let It of Wt)g.push(` - ${It}`)}g.push("")}for(let O of ee){let ke=O.testId?Ht(p(O.testId)):n$(O.testType),ge=O.fileName?` (\`${O.fileName}\`)`:"",q=O.endpoint?`
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(d2,"testLitter");function HAe(e){let t=dy[e],n=e==="ui";return{name:`${t.stage}-no-litter`,verify(i){let r=d2(i.inputs.repositoryPath);if(r===void 0)return{name:this.name,passed:!0};let s=r.filter(a=>JAe.test(a)===n);return s.length===0?{name:this.name,passed:!0}:jt(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(HAe,"noLitterGateFor");var BDe=HAe("backend");var ZAe="write-stale-updates",KAe={[ZAe]:"stale test updates"};var UA=Qe(require("fs")),pa=Qe(require("path"));function g2(e,t=!1){return yn(WM(t),e).errors}o(g2,"validateAdaptOutput");function tpe(e,t=[],n=!1){let{value:i,error:r}=Tt(e,t);if(r)return{errors:[r]};let s=g2(i,n);return s.length>0?{errors:s}:{adapt:i,errors:[]}}o(tpe,"parseAdaptText");var npe="adapt-scratch",p2=`${npe}/adapt-result.json`;function h2(e,t){let n=pa.join(e.outputsDir,p2),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:[`${p2} contains a secret value (token / credential) \u2014 never write it anywhere`]};let r=hd(e.inputs?.sharedEnvironment).length>0,s=tpe(t.stdout,e.secretValues,r);if(s.adapt)return s;let a=i!==void 0?Vo(n):void 0;return a!==void 0&&g2(a,r).length===0?{adapt:a,errors:[]}:s}o(h2,"parseAdaptFromSession");var n_e=Tn("adapt-schema",h2);var m2=require("child_process");function Jx(e){return rpe(e)??[]}o(Jx,"statusEntries");function rpe(e){let t;try{t=(0,m2.execFileSync)("git",[...xi,"status","--porcelain","-z","--untracked-files=all"],{env:en(),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(rpe,"readStatusEntries");var A_e=2*1024*1024;var Ay=d.string().trim().min(1),ipe=d.object({cwd:Ay.describe(`directory the command starts in, relative to the test's checkout ("." for its root)`),argv:d.array(Ay).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")}),spe=d.object({file:Ay.describe("a file of the test's checkout, relative to its root"),line:Ay.describe("a line of that file, quoted exactly from where its command starts to its end")}),y2=d.object({collected:d.boolean().describe("whether the repo's CI runs this test as it is"),steps:d.array(spe).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:ipe.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 ae=d.string().trim().min(1),dpe=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"),Ape=d.preprocess(dpe,d.object({id:ae.describe(`its requirement's id plus a letter, e.g. "R1a", "AC-3a"`),clause:ae.describe("one testable part of the requirement"),expected:ae.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(Vi).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)")})),I2=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:ae.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`}),ppe=d.object({id:ae.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:ae,source:d.nativeEnum(gi).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:ae.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:ae.regex(Es).describe("the key of another uploaded document stating the same obligation"),says:ae.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(I2).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(Ape)}),C2=(r=>(r.ServerError="server-error",r.DataLost="data-lost",r.FinalState="final-state",r.DerivedValues="derived-values",r))(C2||{}),fpe=d.object({id:ae.describe('e.g. "F1"'),file:ae,line:d.number().optional(),claim:ae.describe("the defect, in one sentence"),severity:d.nativeEnum(da),evidence:ae.describe("the code line, or the probe request and response, that shows it"),conflictsWith:d.array(ae).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(C2).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)")}),gpe=d.object({id:ae.describe('e.g. "Q1"'),question:ae.describe("what is unsettled, as a question the PR author can answer"),readings:d.array(ae).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(I2).optional().describe("when sources of the same rank disagree on it: each of them")}),hpe=d.object({id:ae.describe('unique, a short kebab-case name for what the case checks, e.g. "ship-twice-409"'),type:d.nativeEnum(Vi).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:ae.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:ae.describe("what the test does"),expected:ae.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")}),mpe=d.object({test:ae.describe("existing test file"),action:d.nativeEnum(Ai),reason:ae,mutates:d.boolean().optional().describe("true when the maintained test changes state"),clauses:d.array(ae).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")}),E2=d.array(vb).optional(),ype=d.object({components:d.preprocess(e=>E2.safeParse(e).success?e:void 0,E2).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(Wl)).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:ae,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()}),Y_e=d.object({schemaVersion:d.literal(1),requirements:d.array(ppe),findings:d.array(fpe),cases:d.array(hpe).describe("a second test for a clause, and one case per finding that fails on this branch"),questions:d.array(gpe).optional().describe("behaviours the change leaves unsettled; no case asserts any of them"),maintenance:d.array(mpe),journeys:d.array(n2).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:ae,why:ae})).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(ae).min(1).describe("changed components, as the change lists them"),why:ae})).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:ype.optional().describe("omit when no app was needed or none was started"),summary:ae.describe("one paragraph: what the change does and where the risk is")});var FA=(n=>(n.Backend="backend",n.Ui="ui",n))(FA||{});var Vs=(r=>(r.Added="added",r.Updated="updated",r.Deleted="deleted",r.Unchanged="unchanged",r))(Vs||{}),Epe=d.object({file:ae.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(Vs).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:ae.describe("the requirement or clause id the change deliberately alters"),line:ae.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:ae,status:d.nativeEnum(fr),runtimeTargets:id.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:ae,evidence:ae})).optional().describe("per covered case, the assertion line that checks its expected outcome"),functions:d.array(d.object({name:ae.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(ae).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(rd).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:ae.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:y2.optional().describe("for a file you added or updated: whether the repo's CI will run it, and how you know"),run:Iu.optional().describe(`for a file in ${Cu}, 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 ${on}, or go-test-json); Testbot runs it before write ends and re-runs the tests with it`)}),Ipe=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"),Cpe=d.preprocess(Ipe,d.object({description:ae.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(ae).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(ae).optional().describe("the plan's requirement or clause ids it violates")})),W_e=d.object({schemaVersion:d.literal(1),tests:d.array(Epe),notWritten:d.array(d.object({case:ae,reason:ae,coveredBy:d.object({file:ae.describe("the test file, relative to the working checkout; prefix a related checkout as for tests[].file"),name:ae.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(cy).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:ae,manifest:ae.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:ae.optional().describe("owner/repo of the manifest's checkout; omit for the repo under test"),reason:ae.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(ae).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:ae.describe("subject line at most 72 characters, following the repository's commit-message checks"),prTitle:ae.describe("at most 72 characters, following the repository's PR-title checks"),prBody:ae.describe("what the tests cover and what they found")}),report:d.object({summary:ae.describe("1-2 sentences for the PR author: does the change do what it says? No count of tests: the report gives it"),issues:d.array(Cpe).describe("every defect the tests found"),nextSteps:d.array(d.string()),noTests:d.array(d.object({repository:ae,reason:ae.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 Z_e={added:"place",updated:"update",deleted:"delete",unchanged:"verify"};var v2=(i=>(i.Requirement="requirement",i.PrDescription="pr_description",i.Code="code",i))(v2||{}),Jt=d.string().trim().min(1),bpe=d.object({expectation:Jt.max(300).describe("the behavior this assertion pins, in words"),source:d.nativeEnum(v2),expected:Jt.max(200).describe("the exact value or outcome asserted, as the test asserts it")}),vpe=d.object({file:Jt.describe("path of the NEW test file you wrote, relative to its repository"),repository:Jt.optional().describe("owner/repo the file lives in, when the run has several checkouts; omit for the working checkout"),framework:Jt.describe("the framework the repository runs this file with: pytest, jest, vitest, node-test, or the name of any other"),run:Iu.optional().describe(`for ${Cu}: how the run executes only the tests in names, with the repository's own runner writing JUnit XML to {junit}`),covers:d.array(Jt).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(Jt).min(1).describe("the test functions/cases in the file that provide evidence for that behavior, as the framework names them"),assertions:d.array(bpe).min(1)}),PA=(n=>(n.Updated="updated",n.Deleted="deleted",n))(PA||{}),b2=300,wpe=d.object({file:Jt.describe("path of the EXISTING test file you updated or deleted, relative to its repository"),repository:Jt.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:Jt.describe("the requirement or clause id the change deliberately alters"),line:Jt.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,b2):e,Jt.max(b2)).describe("what the change deliberately altered that made the test wrong")}),Hx=d.object({schemaVersion:d.literal(1),tests:d.array(vpe),maintained:d.array(wpe).optional().describe("existing tests the change made stale that you updated or deleted; omit when there were none"),defectsNotTested:d.array(d.object({id:Jt,reason:Jt.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(cy).optional().describe("one entry per planned user journey: the in-process test that walks it end to end"),journeysNotWritten:d.array(d.object({journey:Jt,missing:Jt.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:Jt.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 kpe(e){let{value:t,error:n}=Tt(e);if(n)return{errors:[n]};let{value:i,errors:r}=yn(Hx,t);return r.length?{errors:r}:{output:i,errors:[]}}o(kpe,"parseGenerateUnitText");function Spe(e){return kpe(e.stdout)}o(Spe,"parseGenerateUnitFromSession");var LNe=Tn("generate-unit-schema",(e,t)=>Spe(t));var py=String.raw`(?:node:)?(?:http|https|http2|net|tls|dgram)`,jNe=[[/\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+["']${py}["']|\bimport\s+["']${py}["']|require\(\s*["']${py}["']\s*\)|\bimport\(\s*["']${py}["']\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 dUe=new Set(["targeted_unit","existing_evidence_sufficient"]);var Upe="triage.json";var IFe=new Set(["existing_evidence","unaffected","existing_unit","new_unit","runtime"]),CFe={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 Fpe(e){let{value:t,error:n}=Tt(e);if(n)return{errors:[n]};let{value:i,errors:r}=yn(_A,t);return r.length?{errors:r}:{triage:i,errors:[]}}o(Fpe,"parseTriageText");function Ppe(e){return Fpe(e.stdout)}o(Ppe,"parseTriageFromSession");var bFe=Tn("triage-schema",(e,t)=>Ppe(t));function Mpe(e){let t=e.inputs?.pipeline;return t?e.state.stages[t==="two-step"?"plan":"triage"]:e.state.stages.triage??e.state.stages.plan}o(Mpe,"triageDecider");function Wx(e){if(Mpe(e)?.status==="passed")return Vo(R2.join(e.outputsDir,Upe))}o(Wx,"readTriage");function Zx(e){return tV($R(e.inputs,Ge(e,`${CA}.json`),Wx(e)?.sutRequired))}o(Zx,"revisionBlockReason");var vFe=new Set(["deploy","recommend","generate","generate-ui","adapt","generate-unit","native-run","finalize","deliver"]);var Pr=Qe(require("fs")),zs=Qe(require("path")),vq=Qe(require("crypto")),wq=require("child_process");var Kx=require("child_process"),vu=Qe(require("fs")),x2=Qe(require("os")),hy=Qe(require("path"));var Ope={onPath:o(e=>(0,Kx.spawnSync)("sh",["-c",`command -v ${e}`],{stdio:"ignore"}).status===0,"onPath"),run:o((e,t)=>(0,Kx.spawnSync)(e[0],e.slice(1),{cwd:t,stdio:"ignore",timeout:6e4}).status??1,"run")},gy={cleanup:o(()=>{},"cleanup")},Lpe=new Set(["pnpm","yarn"]);function $2(e,t=x2.tmpdir(),n=Ope){if(process.platform==="win32")return gy;try{let i=Qx(e);if(!Lpe.has(i)||n.onPath(i)||!n.onPath("corepack"))return gy;vu.mkdirSync(t,{recursive:!0});let r=vu.mkdtempSync(hy.join(t,"testbot-pm-")),s=o(()=>vu.rmSync(r,{recursive:!0,force:!0}),"cleanup");return n.run(["corepack","enable","--install-directory",r,i],e)!==0?(s(),gy):{dir:r,cleanup:s}}catch{return gy}}o($2,"packageManagerShims");function T2(e,t=process.env){return e.dir?{...t,PATH:[e.dir,t.PATH].filter(Boolean).join(hy.delimiter)}:t}o(T2,"withShims");var GA=require("crypto");function Ht(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(Ht,"codeSpan");function Xx(e){return e.functions?.length?e.functions:[(e.testType==="unit"?e.testId.split("::").slice(1).join("::").replace(/\[.*\]$/,""):"")||e.testId]}o(Xx,"rowFunctions");function wu(e){return new Set(e.flatMap(t=>Xx(t).map(n=>`${t.repository??""}\0${t.fileName}\0${n}`))).size}o(wu,"testCount");pc();var WFe=5*6e4,ZFe=12*6e4,KFe=2*6e4;var sPe=["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 mPe=[...mb,"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 my=Qe(kx());var qPe={jest:"jest",vitest:"vitest"};var SMe=new Set(["jest","vitest","npm-test","playwright"]);var LMe=5*6e4;var OA=Qe(require("path"));var AOe={python:"pytest",typescript:"playwright",javascript:"playwright"},pOe={pytest:"pytest",playwright:"playwright"};function zpe(e){return yn(qb,e).errors}o(zpe,"validateFinalizeOutput");function qpe(e,t=[]){let{value:n,error:i}=Tt(e,t);if(i)return{errors:[i]};let r=zpe(n);return r.length>0?{errors:r}:{finalize:n,errors:[]}}o(qpe,"parseFinalizeText");var Jpe="finalize-scratch";function Hpe(e,t){let n=qpe(e.stdout,t?.secretValues);if(!n.finalize||!t?.outputsDir)return n;let i=o((r,s)=>r.trim()&&Dx(r.trim(),OA.join(t.outputsDir,Jpe,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(Hpe,"parseFinalizeFromSession");var iLe=Tn("finalize-schema",(e,t)=>Hpe(t,e));function Ype(e){return yn(Lx,e).errors}o(Ype,"validateAnalysisOutput");function U2(e,t=[]){let{value:n,error:i}=Tt(e,t);if(i)return{errors:[i]};let r=Ype(n);return r.length>0?{errors:r}:{analysis:n,errors:[]}}o(U2,"parseAnalysisText");function Wpe(e,t=[]){return U2(e.stdout,t)}o(Wpe,"parseAnalysisFromSession");var QLe=Tn("analysis-schema",(e,t)=>Wpe(t,e.secretValues));var Wje=ag.rows.notRun(!0);var LA="kept, not ";var jA="(declined the planned ";function e$(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(e$,"assertionParts");var F2=new Set(["update","regenerate","delete"]);var Zje={update:"updated",regenerate:"regenerated",delete:"deleted",verify:"verified",none:"touched"};var P2=d.string().trim().min(1),t$=d.object({schemaVersion:d.literal(1).optional(),businessCaseAnalysis:P2.describe("1-2 sentences: what this change means for a user, and whether the evidence shows it working; no count of tests, which the report gives"),issuesFound:d.array(d.object({description:P2,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 efe(e){return yn(t$,e).errors}o(efe,"validateProseOutput");function tfe(e,t=[]){let{value:n,error:i}=Tt(e.stdout,t);if(i)return{errors:[i]};let r=efe(n);return r.length>0?{errors:r}:{prose:n,errors:[]}}o(tfe,"parseProseFromSession");var d1e=Tn("report-schema",(e,t)=>tfe(t,e.secretValues));var M2="<!-- skyramp-testbot -->",O2=F2,nfe=new Set(["lint","type","config"]),L2={critical:0,high:1,medium:2,low:3},J2=new Set(["Pass","Fail"]);var i$=o(e=>Co(oe().statusLabels,e),"statusLabel"),n$=o(e=>Co(oe().testTypeCellLabels,e),"testTypeLabel");function ze(e){return(e??"").replace(/\|/g,"\\|").replace(/\r?\n/g,"<br>").trim()}o(ze,"escCell");function j2(e){return e.inferred?" (inferred)":""}o(j2,"inferredMark");function V2(e,t){return!e||!J2.has(e)?"\u2014":t?`${i$(e)} (${ze(H2(t))})`:i$(e)}o(V2,"maintStatus");function H2(e){let t=o(i=>{let r=i.indexOf(": ");return r<0?i:Co(oe().staged.maintenanceActions,i.slice(0,r))+i.slice(r)},"action");if(e.startsWith(LA))return oe().staged.keptNot+t(e.slice(LA.length));let n=e.indexOf(jA);return n<0?e:e.slice(0,n)+oe().staged.declinedPlanned+t(e.slice(n+jA.length))}o(H2,"declineNote");function G2(e){return e.category!==void 0&&nfe.has(e.category.toLowerCase())}o(G2,"isTooling");function z2(e,t){return(L2[(e.severity??"").toLowerCase()]??4)-(L2[(t.severity??"").toLowerCase()]??4)}o(z2,"bySeverity");function q2(e){return`- ${e.severity?`**[${Co(oe().severityLabels,e.severity.toLowerCase()).toUpperCase()}]** `:""}${e.description.trim()}`}o(q2,"issueLine");function rfe(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(rfe,"unitTestOf");var Y2=o((e,t)=>e!==void 0&&t!==void 0&&e.replace(/^\.\//,"")===t.replace(/^\.\//,""),"samePath");function W2(e,t){return(e.testVideos??[]).find(n=>n.url&&t(n))?.url}o(W2,"videoLink");function s$(e,t){return W2(e,n=>Y2(n.fileName,t.fileName)&&(!n.repository||!t.repository||n.repository.toLowerCase()===t.repository.toLowerCase()))}o(s$,"resultVideoLink");function o$(e,t){return W2(e,n=>Y2(n.writtenAs??n.fileName,t))}o(o$,"journeyVideoLink");function ife(e,t,n){return n?s$(e,{fileName:t,repository:n}):o$(e,t)}o(ife,"requirementVideoLink");function sfe(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&&Wz(c,u)),"parentOf"),s=new Map;for(let a of e.testResults){let c=rfe(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??"":oe().staged.casesPassed(l,c.length,A)+(p?`; ${i.get(p)??""} ${p.details??""}`.replace(/; +/,"; ").trimEnd():"")}return t}o(sfe,"resultRows");function ofe(e){return e$(e).map(t=>t.expected===void 0?t.expectation:`${t.expectation}: ${Ht(t.expected)}`)}o(ofe,"unitAssertions");function r$(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(r$,"nothingExecuted");function Z2(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(M=>/^file-[a-f0-9]{16}-/i.test(M.id)).sort((M,ee)=>ee.id.length-M.id.length),p=o(M=>{let ee=A.find(O=>M.toLowerCase().startsWith(O.id.toLowerCase()));return ee?ee.label+M.slice(ee.id.length):M},"displayId"),g=[M2];if(a&&g.push(oe().staged.testsSourcePullRequest(Ht(a)),""),s){let M=s.name.replace(/\s+/g," ").trim().replace(/[<>[\]()*_`\\|#]/g,"\\$&").replace(/@/g,"@\u200D");g.push(s.kind==="person"?oe().staged.requestedByPerson(M):oe().staged.requestedByPolicy(M),"")}e.notTranslated&&g.push(Co(oe().staged.notTranslated,e.notTranslated),"");let h=o(M=>{i?g.push("<details>",`<summary>${M}</summary>`,""):g.push(`### ${M}`)},"sectionStart"),y=o(()=>{i&&g.push("","</details>"),g.push("")},"sectionEnd");if(c){for(let M of e.businessCaseAnalysis.trim().split(/\r?\n/))g.push(`> ${M}`);g.push("")}if(r$(e)&&g.push(oe().staged.noLiveApp(wu(e.newTestsCreated)),""),u&&e.newTestsCreated.length){let M=new Map;for(let O of e.newTestsCreated){if(O.testType!=="unit")continue;let ke=Xx(O)[0],ge=M.get(O.fileName)??{functions:new Set,endpoints:[],descriptions:new Map};O.endpoint&&!ge.endpoints.includes(O.endpoint)&&ge.endpoints.push(O.endpoint);let q=O.description?.trim()??"",P=ge.descriptions.get(ke)??[];P.includes(q)||P.push(q),ge.functions.add(ke),ge.descriptions.set(ke,P),M.set(O.fileName,ge)}let ee=e.newTestsCreated.filter(O=>O.testType!=="unit");h(oe().testRecommendationsImplementedHeader(wu(e.newTestsCreated),ee.length+wu(e.newTestsCreated.filter(O=>O.testType==="unit"))));for(let[O,{functions:ke,endpoints:ge,descriptions:q}]of M){let P=ke.size;g.push(oe().staged.unitTestsInFile(`\`${O}\``,P,ge.map(Ft=>`\`${Ft}\``).join(", ")),"");let mt=new Map;for(let[Ft,ct]of q){let Wt=ct.join("\0"),It=mt.get(Wt)??{fns:[],descriptions:ct};It.fns.push(Ft),mt.set(Wt,It)}let Ze=0;for(let{fns:Ft,descriptions:ct}of mt.values()){g.push(`${++Ze}. ${Ft.map(It=>`\`${It}\``).join(", ")}`);let Wt=[...new Set(ct.flatMap(It=>ofe(It)))];for(let It of Wt)g.push(` - ${It}`)}g.push("")}for(let O of ee){let ke=O.testId?Ht(p(O.testId)):n$(O.testType),ge=O.fileName?` (\`${O.fileName}\`)`:"",q=O.endpoint?`
160
160
  \`${O.endpoint}\``:"",P=O.description?`
161
161
  ${O.description.trim()}`:"";g.push(`- ${ke}${ge}${q}${P}`)}y()}let E=(e.testMaintenance??[]).filter(M=>O2.has(M.action));if(u&&E.length){h(oe().staged.testMaintenanceHeader),g.push(oe().maintenanceTableHeader),g.push("|-----------|----------|------|--------|--------|-------|");for(let M of E)g.push(`| ${ze(n$(M.testType))} | ${ze(M.endpoint)} | \`${ze(M.fileName)}\` | ${ze(M.description)} | ${V2(M.beforeStatus,M.beforeDetails)} | ${V2(M.afterStatus,M.afterDetails)} |`);y()}let C=o(M=>M.startsWith(LA)||M.includes(jA),"hasDeclineNote"),I=(e.testMaintenance??[]).filter(M=>C(M.afterDetails)&&(!O2.has(M.action)||!J2.has(M.afterStatus??"")));if(u&&I.length){h(oe().staged.declinedMaintenanceHeader);for(let M of I)g.push(`- \`${ze(M.fileName)}\`: ${ze(H2(M.afterDetails))}`);y()}if(u&&r.length){h(oe().staged.existingEvidenceHeader);let M=new Map;for(let ee of r){let O=`${ee.check}\0${ee.url??""}\0${ee.revision??""}`;M.set(O,[...M.get(O)??[],ee])}for(let[,[ee,...O]]of M){let ke=ee.url?`[${Ht(ee.check)}](${ee.url})`:Ht(ee.check);g.push(oe().staged.trustedCheckPassed(ke,ee.revision?Ht(ee.revision.slice(0,7)):""),"");for(let ge of[ee,...O])g.push(`- ${Ht(ge.behavior)}`);g.push("")}y()}if(u&&e.testResults.length){h(oe().staged.testResultsHeader);let M=sfe(e),ee=M.some(q=>q.test),O=M.some(q=>s$(e,q)),ke=ee?oe().staged.unitResultsTableHeader:oe().staged.resultsTableHeader;g.push(O?`${ke} ${oe().columnVideo} |`:ke),g.push(`${ee?"|---------|-----------|----------|------|-------|--------|---------|":"|---------|-----------|----------|--------|---------|"}${O?"-------|":""}`);for(let q of M){let P=q.details.replace(/(\S+\.(?:py|ts|js|spec\.\w+))/gi,"`$1`"),mt=q.testId?Ht(ze(p(q.testId))):"\u2014",Ze=ee?` ${q.test?`\`${ze(q.test)}\``:""} | ${q.cases??""} |`:"",Ft=s$(e,q),ct=O?` ${Ft?oe().videoDownloadLink(Ft):"\u2014"} |`:"";g.push(`| ${mt} | ${ze(n$(q.testType))} | ${ze(q.endpoint)} |${Ze} ${ze(i$(q.status))} | ${ze(P)} |${ct}`)}let ge=(e.testVideos??[]).find(q=>q.artifactsUrl)?.artifactsUrl;!O&&ge&&g.push("",oe().videosArtifactFallback(ge)),y()}if(e.requirements?.length){let M=e.requirements.flatMap(q=>q.clauses),ee=o(q=>q.status==="Pass"||q.status==="Passed, test not kept","passes"),O=M.filter(ee).length;h(oe().staged.requirementsHeader(O,M.length));let ke=o(q=>Co(oe().staged.clauseStatuses,q.status),"status"),ge=o(q=>(q.status==="Not tested"||q.status==="Passed, test not kept")&&q.notTested?`${ke(q)}: ${q.notTested}`:q.findings.length?`${ke(q)} \u2014 ${q.findings.join(", ")}`:ke(q),"result");if(u){g.push(oe().staged.requirementsTableHeader),g.push("|-------------|--------|-------|--------|");for(let q of e.requirements)q.clauses.forEach((P,mt)=>{let Ze=mt===0?`**${ze(q.label)}**${q.statement?` ${ze(q.statement)}`:""}`:"",Ft=`${Ht(ze(p(P.id)))}${j2(P)}${P.text?` ${ze(P.text)}`:""}`,ct=new Map;for(let Rt of P.tests){let Cn=Rt.fileName??p(Rt.testId),ut=ct.get(Cn)??{fns:new Set};for(let bn of Rt.functions)ut.fns.add(bn);ut.video??=Rt.fileName?ife(e,Rt.fileName,Rt.repository):void 0,ct.set(Cn,ut)}let Wt=ct.size?[...ct].map(([Rt,{fns:Cn,video:ut}])=>`${Ht(ze(Rt))}${Cn.size?` \u2014 ${[...Cn].map(bn=>`\`${ze(bn)}\``).join(", ")}`:""}${ut?` ${oe().videoDownloadLink(ut)}`:""}`).join("<br>"):"\u2014",It=q.source==="could-break"&&P.status==="Pass"?oe().staged.regressionGuard:"";g.push(`| ${Ze} | ${Ft} | ${Wt} | ${ze(ge(P)+It)} |`)})}else{g.push(oe().staged.requirementsSummaryTableHeader),g.push("|-------------|-----------------|-------------|");for(let q of e.requirements){let P=q.clauses.filter(ee).length,mt=q.clauses.filter(Ze=>!ee(Ze)).map(Ze=>`${Ht(ze(p(Ze.id)))}${j2(Ze)} ${ze(ge(Ze))}`);g.push(`| **${ze(q.label)}**${q.statement?` ${ze(q.statement)}`:""} | ${P}/${q.clauses.length} | ${mt.join("<br>")||"\u2014"} |`)}}y()}if(u&&e.changes?.length&&!e.requirements?.length){let M=e.executionCoverage,ee=M?oe().staged.coverageCaption(M.generated,M.modified,M.verified,M.executed):"";h(`${oe().staged.behaviourCoverageHeader}${ee}`),g.push(oe().staged.coverageTableHeader),g.push("|-----------|--------|-----------|----------------|");for(let O of e.changes){let ke=O.testedBy.length?O.testedBy.map(q=>`\`${ze(q)}\``).join(", "):O.writtenBy.length?oe().staged.writtenNotRun:"\u2014",ge=O.maintainedBy.length?O.maintainedBy.map(q=>`\`${ze(q)}\``).join(", "):"\u2014";g.push(`| ${ze(O.text)} | \`${ze(O.source)}\` | ${ke} | ${ge} |`)}y()}if(e.userJourneys?.length){let M=e.userJourneys.filter(O=>O.status==="Pass"&&!O.problems.length).length;h(`\u{1F9ED} User Journeys Covered (${M}/${e.userJourneys.length} walked end to end)`);let ee=e.userJourneys.some(O=>o$(e,O.fileName));g.push(`| Journey | Test | Status | Notes |${ee?` ${oe().columnVideo} |`:""}`),g.push(`|---------|------|--------|-------|${ee?"-------|":""}`);for(let O of e.userJourneys){let ke=O.fileName?`\`${ze(O.fileName)}\`${O.test?` \u2014 ${ze(O.test)}`:""}`:"\u2014",ge=O.source&&O.source!=="inferred"?`; described in the ${O.source==="spec"?"spec":"PR description"}`:"; inferred from the app",q=(O.uncovered?`not covered: ${O.uncovered}`:O.problems.length?`does not walk it end to end: ${O.problems.join("; ")}`:`from ${O.entry}, ${O.steps} steps`)+ge,P=ee?o$(e,O.fileName):void 0;g.push(`| ${ze(O.name)} | ${ke} | ${ze(O.status)} | ${ze(q)} |${ee?` ${P?oe().videoDownloadLink(P):"\u2014"} |`:""}`)}y()}if(l){let M=e.issuesFound.filter(O=>!G2(O)).sort(z2),ee=e.issuesFound.filter(G2).sort(z2);if(M.length){h(oe().staged.issuesFoundHeader);for(let O of M)g.push(q2(O));y()}if(ee.length){g.push(`### ${oe().configErrorsHeader}`);for(let O of ee)g.push(q2(O));g.push("")}}let b=e.testPackages??[],D=e.dependencyChanges??[];if(b.length){g.push(oe().staged.testPackagesHeader,"");for(let M of b)g.push(`- ${oe().staged.testPackageLine(M.directory,M.entrypoint,Object.entries(M.dependencies??{}).map(([ee,O])=>M.runner==="pytest"?`${ee}==${O}`:`${ee}@${O}`).join(", "))}`);D.length||g.push(`- ${oe().staged.appManifestsUntouched}`),g.push("")}if(D.length){g.push(oe().staged.dependencyChangesHeader,"");for(let M of D)g.push(`- ${oe().staged.dependencyChangeLine(M.package,M.repository?`${M.repository}: ${M.manifest}`:M.manifest,(M.reason??"").replace(/\s+/g," ").trim())}`);g.push("")}let N=(e.caveats??[]).filter(M=>M.kind!=="tests-not-executed"||M.subject==="written-cases"||!r$(e));if(N.length){g.push(oe().staged.caveatsHeader,"");for(let M of N)g.push(`- ${M.text}`);g.push("")}if(l&&e.nextSteps.length){g.push(oe().nextStepsHeader,"");for(let M of e.nextSteps)g.push(`- ${M.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(M=>e.testResults.filter(ee=>ee.status===M).length,"counts"),Ae=e.requirements?.flatMap(M=>M.clauses)??[],Pe=o(M=>Array.from(M.replace(/\s+/g," ").trim()).slice(0,300).join(""),"snippet"),tt=o(M=>Pe(M).replace(/[&<>\\`*_[\]{}()#+.!|~-]/g,ee=>`&#${ee.charCodeAt(0)};`),"plainSnippet");return[M2,...a?[oe().staged.testsSourcePullRequest(Ht(Pe(a)))]:[],oe().staged.largeReportSummary(e.requirements?.length??0,Ae.length,K("Pass"),K("Fail"),K("Skipped")),oe().staged.largeReportNotice,...e.validation?[oe().staged.largeReportValidation(tt(e.validation.sufficiency),tt(e.validation.rationale),e.validation.gaps.length)]:[],...(e.caveats??[]).slice(0,3).map(M=>`> \u26A0\uFE0F ${tt(M.text)}`),...r$(e)?[oe().staged.noLiveApp(wu(e.newTestsCreated))]:[],...t.runUrl?[oe().staged.viewRun(t.runUrl)]:[],""].join(`
166
166
 
167
- `)}o(Z2,"renderPrBody");var Gs=Qe(require("fs")),a$=Qe(require("path"));var cfe="report.json",ufe="report-display.json",P1e={en:"English",ja:"Japanese"};function K2(e){let t=a$.join(e,ufe);if(Gs.existsSync(t))try{return JSON.parse(Gs.readFileSync(t,"utf-8"))}catch{}let n=a$.join(e,cfe);return Gs.existsSync(n)?JSON.parse(Gs.readFileSync(n,"utf-8")):void 0}o(K2,"readDisplayReport");function X2(e,t){return t?`<!-- skyramp-testbot-run: ${t} -->
167
+ `)}o(Z2,"renderPrBody");var Gs=Qe(require("fs")),a$=Qe(require("path"));var cfe="report.json",ufe="report-display.json",M1e={en:"English",ja:"Japanese"};function K2(e){let t=a$.join(e,ufe);if(Gs.existsSync(t))try{return JSON.parse(Gs.readFileSync(t,"utf-8"))}catch{}let n=a$.join(e,cfe);return Gs.existsSync(n)?JSON.parse(Gs.readFileSync(n,"utf-8")):void 0}o(K2,"readDisplayReport");function X2(e,t){return t?`<!-- skyramp-testbot-run: ${t} -->
168
168
  ${e}`:e}o(X2,"withRunMarker");var ga=Qe(require("fs")),fa=Qe(require("path"));var yy=["build","chore","ci","docs","feat","fix","perf","refactor","revert","style","test"],lfe=["build","ci","docs","feat","fix","perf","refactor","revert","style","test"],dfe="amannn/action-semantic-pull-request",Mn=o(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObj");function eq(e){return typeof e!="string"?!1:e.split("@")[0].split("/").some(n=>n.toLowerCase().split(/[-_.]/).includes("dco"))}o(eq,"usesDco");function tq(e){return typeof e=="string"&&(/\bdco-check\b/.test(e)||/signed-off-by/i.test(e))}o(tq,"scriptChecksDco");function Afe(e){if(!Mn(e)||!Mn(e.jobs))return!1;for(let t of Object.values(e.jobs))if(Mn(t)){if(eq(t.uses))return!0;if(Array.isArray(t.steps)){for(let n of t.steps)if(Mn(n)&&(eq(n.uses)||tq(n.run)||Mn(n.with)&&Object.values(n.with).some(tq)))return!0}}return!1}o(Afe,"workflowChecksDco");function sq(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:Ps(ga.readFileSync(fa.join(t,i),"utf-8"))}]}catch{return[]}})}o(sq,"workflows");function pfe(e){return!Mn(e)||!Mn(e.jobs)?[]:Object.values(e.jobs).flatMap(t=>Mn(t)&&Array.isArray(t.steps)?t.steps.filter(Mn):[])}o(pfe,"steps");function ffe(e){let t=fa.join(".github","dco.yml");if(ga.existsSync(fa.join(e,t)))return{file:t};let n=sq(e).find(i=>Afe(i.doc));return n&&{file:n.file}}o(ffe,"signOffRule");var nq=o(e=>typeof e=="string"?e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean):void 0,"inputList");function gfe(e){for(let t of sq(e)){let n=pfe(t.doc).find(s=>typeof s.uses=="string"&&s.uses.split("@")[0].trim().toLowerCase()===dfe);if(!n)continue;let i=Mn(n.with)?n.with:{},r=nq(i.scopes);return{file:t.file,types:nq(i.types)??yy,...r?.length?{scopes:r}:{},scopeRequired:i.requireScope===!0||String(i.requireScope).trim()==="true"}}}o(gfe,"semanticPrTitleRule");var hfe=["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"],mfe=["type-enum","scope-enum","scope-empty","subject-case","header-max-length","body-max-line-length"];function oq(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(oq,"knownPresets");var yfe={Disabled:"0",Warning:"1",Error:"2"};function Efe(e){return e.replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`|\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g,t=>t.startsWith("/")?t.replace(/[^\r\n]/g," "):t)}o(Efe,"withoutComments");function rq(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)=>yfe[l]??u).replace(/,(\s*\])/g,"$1"),c=a.replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/g,'""');try{return JSON.parse(c),Ps(a)}catch{return null}}}o(rq,"ruleFromSource");var aq=o(e=>Object.fromEntries(mfe.map(t=>[t,e(t)])),"pickRules");function iq(e,t){if(!Mn(t))return;let n=[].concat(t.extends??[]),i=Mn(t.rules)?t.rules:{};return{file:e,presets:oq(n),rules:aq(r=>i[r])}}o(iq,"configFromObject");function Ife(e){for(let t of hfe){let n;try{n=ga.readFileSync(fa.join(e,t),"utf-8")}catch{continue}if(/\.[cm]?[jt]s$/.test(t)){let r=Efe(n),s=/(?:^|[,{])\s*["']?extends["']?\s*:\s*/.exec(r),a=s?rq(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:oq(u),rules:aq(l=>rq(r,l))}}let i;try{i=Ps(n)}catch{return}if(t!=="package.json")return iq(t,i);if(Mn(i)&&Mn(i.commitlint))return iq(t,i.commitlint)}}o(Ife,"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 c$=o(e=>Array.isArray(e)&&e.every(t=>typeof t=="string")?e:void 0,"stringList");function Cfe(e,t){if(!e)return t?"not-capitalized":void 0;let[n,i]=e,r=typeof i=="string"?[i]:c$(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(Cfe,"subjectCaseOf");function bfe(e){let t=Ife(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"?c$(a[1]):s("type-enum")?r?lfe:yy:void 0,u=c===void 0,l=c??yy;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"?c$(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=Cfe(Bu(i["subject-case"]),s("subject-case")),y=g("header-max-length",r?72:100)??(u&&i["header-max-length"]===void 0?Fi: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(bfe,"commitlintRule");function cq(e){let t=ffe(e),n=bfe(e),i=gfe(e);return{...t?{signOff:t}:{},...n?{commitlint:n}:{},...i?{prTitle:i}:{}}}o(cq,"readCommitRules");function vfe(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(Fi,...t.map(a=>a.headerMaxLength??1/0)),...Number.isFinite(s)?{bodyMaxLineLength:s}:{}}}o(vfe,"mergedHeaderRules");function Ey(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(Ey,"allowsScope");function wfe(e,t){let n=e.find(s=>s.scopes)?.scopes??[],i=n.filter(s=>/^[\w./-]+$/.test(s)&&e.every(a=>Ey(a,s)));if(!i.length)return e.every(s=>Ey(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(wfe,"pickScope");var uq=/^([A-Za-z][\w-]*)(?:\(([^)]*)\))?!?:\s*(.*)$/,Bfe=o(e=>e.split(/(`.*?`|".*?"|'.*?')/).map((t,n)=>n%2?t:t.toLowerCase()).join(""),"lowerOutsideQuotes");function lq(e,t){return t==="lower-case"?Bfe(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(lq,"withSubjectCase");function kfe(e,t){return lq(e.trim().replace(/\.+$/,"").trim()||"add tests",t)}o(kfe,"conformSubject");function dq(e,t){let[n,...i]=e.replace(/\s+$/,"").split(`
169
169
  `),r=uq.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&&!Ey(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)&&lq(l,s.subjectCase)!==l)return!1}return!0})}o(dq,"matchesCommitRules");function Sfe(e,t){if(e.length<=t)return e;let n=e.slice(0,t-1),i=n.lastIndexOf(" ");return`${(i>0?n.slice(0,i):n).replace(/[\s.,;:]+$/,"")}\u2026`}o(Sfe,"fitSubject");function Qfe(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(Qfe,"wrap");function Aq(e,t,n){let i=vfe(t);if(!i)return e;let[r,...s]=e.replace(/\s+$/,"").split(`
170
170
  `),a=uq.exec(r.trim()),c=a&&[...yy,...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=>Ey(b,A))?A:void 0;!g&&i.scopeRequired&&(g=wfe(i.rules,n));let h=g?`${p}(${g}): `:`${p}: `,y=h+Sfe(kfe(l,i.subjectCase),i.headerMaxLength-h.length),E=s.join(`
@@ -180,12 +180,12 @@ ${n}`}o(Iy,"withSignOff");function pq(e){let t=[],n=!1;for(let i of e.split(`
180
180
  `))/^\s*signed-off-by:/i.test(i)?n=!0:n&&i.trim()===""&&t.at(-1)?.trim()===""||(t.push(i),n=!1);return t.join(`
181
181
  `).replace(/\s+$/,"")}o(pq,"withoutSignOff");function u$(e){let t=/\b(claude|anthropic)\b/i;return e.split(`
182
182
  `).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(`
183
- `).replace(/\s+$/,"")}o(u$,"stripAgentAttribution");var Cy="Skyramp-Pull-Request",ku="Skyramp-Delivery-Base",l$="Skyramp-Tested-Revision";var eVe=["%H","%P","%an","%ae","%ce",`%(trailers:key=${Cy},valueonly,separator=%x2C)`,"%s",`%(trailers:key=${ku},valueonly,separator=%x2C)`,`%(trailers:key=${l$},valueonly,separator=%x2C)`];function fq(e,t){let n=e(["log","-1","--format=%B"]);if(!n.includes(`${Cy}:`)&&!n.includes(`${ku}:`))return;let i=n.split(`
183
+ `).replace(/\s+$/,"")}o(u$,"stripAgentAttribution");var Cy="Skyramp-Pull-Request",ku="Skyramp-Delivery-Base",l$="Skyramp-Tested-Revision";var tVe=["%H","%P","%an","%ae","%ce",`%(trailers:key=${Cy},valueonly,separator=%x2C)`,"%s",`%(trailers:key=${ku},valueonly,separator=%x2C)`,`%(trailers:key=${l$},valueonly,separator=%x2C)`];function fq(e,t){let n=e(["log","-1","--format=%B"]);if(!n.includes(`${Cy}:`)&&!n.includes(`${ku}:`))return;let i=n.split(`
184
184
  `).filter(a=>!a.startsWith(`${ku}:`)).join(`
185
185
  `).trimEnd(),r=t?`${i}
186
186
  ${ku}: ${t}`:i;e(["log","-1","--format=%(trailers:key=Signed-off-by,valueonly)"]).split(`
187
- `).some(a=>a.trim().toLowerCase()===`${vs} <${jo}>`.toLowerCase())&&(r=Iy(r,{name:vs,email:jo})),e(["-c",`user.name=${vs}`,"-c",`user.email=${jo}`,"commit","--amend","--allow-empty","-m",r])}o(fq,"amendDeliveryBase");var by=Qe(require("fs")),rr=Qe(require("path"));var rVe=5*1024*1024;function xfe(e){try{return by.lstatSync(e),!0}catch{return!1}}o(xfe,"lexists");function gq(e){let t=Ge(e,"adapt.json"),n=Ge(e,"finalize.json"),i=Ge(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)=>rr.relative(A,rr.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=rr.join(rr.dirname(h),y);by.existsSync(rr.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(rr.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 $x(p.repo,ty(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=Ge(e,ny)?.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 Jx(p.repo)){let y=a(p.repo,h),E=rr.join(p.repo,y);ry(y,g)&&!Tx(y)&&(!xfe(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(`..${rr.sep}`)&&!Mm(g))]))}o(gq,"deliverAllowlist");var mq=Qe(require("fs"));var yq=2*1024*1024;function $fe(e){let t=[];for(let n of e??[])if(n.state==="read")try{t.push({item:n,text:mq.readFileSync(WO(n),"utf-8")})}catch{}return t}o($fe,"readItemTexts");var VA=6,Tfe=/[\p{L}\p{N}]+/gu,Dfe=new RegExp("(?<=\\p{Ll})(?=\\p{Lu})|(?<=\\p{Lu})(?=\\p{Lu}\\p{Ll})","u");function d$(e){let t=[];for(let n of e.matchAll(Tfe)){let i=n.index;for(let r of n[0].split(Dfe))t.push({word:r.toLowerCase(),start:i,end:i+r.length}),i+=r.length}return t}o(d$,"wordsOf");var Eq=o((e,t)=>e.slice(t,t+VA).map(n=>n.word).join(" "),"runAt");function hq(e){let t=d$(e),n=new Set;for(let i=0;i+VA<=t.length;i++)n.add(Eq(t,i));return n}o(hq,"runsOf");function Iq(e,t=[]){let n=new Set(t.flatMap(i=>[...hq(i)]));return $fe(e).map(({item:i,text:r})=>{let s=i.source==="other"?r:r.slice(r.indexOf(`
188
- `)+1||r.length),a=hq(s);for(let c of n)a.delete(c);return{name:VM(i.key,zb([i])),key:i.key,runs:a,words:d$(s).map(c=>c.word)}})}o(Iq,"requirementTexts");var EVe=VA/2;var _fe=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 Nfe(e,t){if(t.length===0)return[];let n=d$(e),i=[];for(let r=0;r+VA<=n.length;r++){let s=Eq(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:_fe(r)}))}o(Nfe,"copies");function vy(e,t){let n=e;for(let i of Nfe(e,t).reverse())n=`${n.slice(0,i.start)}(see ${i.name})${n.slice(i.end)}`;return n}o(vy,"withoutRequirementText");function Ufe(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
+ `).some(a=>a.trim().toLowerCase()===`${vs} <${jo}>`.toLowerCase())&&(r=Iy(r,{name:vs,email:jo})),e(["-c",`user.name=${vs}`,"-c",`user.email=${jo}`,"commit","--amend","--allow-empty","-m",r])}o(fq,"amendDeliveryBase");var by=Qe(require("fs")),rr=Qe(require("path"));var iVe=5*1024*1024;function xfe(e){try{return by.lstatSync(e),!0}catch{return!1}}o(xfe,"lexists");function gq(e){let t=Ge(e,"adapt.json"),n=Ge(e,"finalize.json"),i=Ge(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)=>rr.relative(A,rr.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=rr.join(rr.dirname(h),y);by.existsSync(rr.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(rr.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 $x(p.repo,ty(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=Ge(e,ny)?.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 Jx(p.repo)){let y=a(p.repo,h),E=rr.join(p.repo,y);ry(y,g)&&!Tx(y)&&(!xfe(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(`..${rr.sep}`)&&!Mm(g))]))}o(gq,"deliverAllowlist");var mq=Qe(require("fs"));var yq=2*1024*1024;function $fe(e){let t=[];for(let n of e??[])if(n.state==="read")try{t.push({item:n,text:mq.readFileSync(WO(n),"utf-8")})}catch{}return t}o($fe,"readItemTexts");var VA=6,Tfe=/[\p{L}\p{N}]+/gu,Dfe=new RegExp("(?<=\\p{Ll})(?=\\p{Lu})|(?<=\\p{Lu})(?=\\p{Lu}\\p{Ll})","u");function d$(e){let t=[];for(let n of e.matchAll(Tfe)){let i=n.index;for(let r of n[0].split(Dfe))t.push({word:r.toLowerCase(),start:i,end:i+r.length}),i+=r.length}return t}o(d$,"wordsOf");var Eq=o((e,t)=>e.slice(t,t+VA).map(n=>n.word).join(" "),"runAt");function hq(e){let t=d$(e),n=new Set;for(let i=0;i+VA<=t.length;i++)n.add(Eq(t,i));return n}o(hq,"runsOf");function Iq(e,t=[]){let n=new Set(t.flatMap(i=>[...hq(i)]));return $fe(e).map(({item:i,text:r})=>{let s=i.source==="other"?r:r.slice(r.indexOf(`
188
+ `)+1||r.length),a=hq(s);for(let c of n)a.delete(c);return{name:VM(i.key,zb([i])),key:i.key,runs:a,words:d$(s).map(c=>c.word)}})}o(Iq,"requirementTexts");var IVe=VA/2;var _fe=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 Nfe(e,t){if(t.length===0)return[];let n=d$(e),i=[];for(let r=0;r+VA<=n.length;r++){let s=Eq(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:_fe(r)}))}o(Nfe,"copies");function vy(e,t){let n=e;for(let i of Nfe(e,t).reverse())n=`${n.slice(0,i.start)}(see ${i.name})${n.slice(i.end)}`;return n}o(vy,"withoutRequirementText");function Ufe(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===`
189
189
  `&&n!=="`")return i}}return e.length}o(Ufe,"stringEnd");function Ffe(e,t){let n=e.lastIndexOf(`
190
190
  `,t-1)+1;if(e.slice(n,t).trim()!=="")return!1;let i=e.slice(0,n).trimEnd();return i===""||i.endsWith(":")}o(Ffe,"isDocstring");function Pfe(e){let t=[],n=o(r=>(e.indexOf(`
191
191
  `,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,Ffe(e,i)&&t.push({start:i,end:a})}else(r==='"'||r==="'"||r==="`")&&(a=Ufe(e,i,r));i=a}return t}o(Pfe,"commentRanges");var Mfe=/\b(?:test|it|describe|context|suite|scenario|specify|Run|DisplayName)(?:\.\w+)*(?:\.each\s*(?:\((?:[^()]|\([^()]*\))*\)|`[^`]*`))?\s*\(\s*("(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`)/g;function Ofe(e,t){return[...e.matchAll(Mfe)].flatMap(n=>{if(t.some(r=>n.index>=r.start&&n.index<r.end))return[];let i=n.index+n[0].length;return[{start:i-n[1].length,end:i}]})}o(Ofe,"titleRanges");function Cq(e,t){if(t.length===0)return{content:e,cleaned:!1};let n=Pfe(e),i=[];for(let c of n){let u=e.slice(c.start,c.end),l=vy(u,t);l!==u&&i.push({...c,text:l})}let r=Ofe(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=vy(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(Cq,"withoutRequirementTextInTestFile");function jfe(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=Ge(e,"finalize.json");return t?t.ready!==!0?{ok:!1,reasons:[`finalize reported ready:false \u2014 not pushing (blockers: ${ld(t)||"unspecified"})`]}:{ok:!0,reasons:[]}:{ok:!1,reasons:["finalize.json not found \u2014 refusing to push unverified tests"]}}o(jfe,"validateDeliverInput");function Bq(e){return e.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"tests"}o(Bq,"slug");var Vfe="skyramp-testbot/";function Gfe(e,t){return t||`${Vfe}${Bq(e)}-tests`}o(Gfe,"testsBranchName");function zfe(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(`
@@ -197,9 +197,9 @@ ${ku}: ${t}`:i;e(["log","-1","--format=%(trailers:key=Signed-off-by,valueonly)"]
197
197
  ${n}`}:{prFailure:"unknown",prDetail:t}}o(tge,"thrownFailure");async function nge(e,t,n,i,r,s){let a=i.slug,c=i.path,u=Ge(e,"finalize.json"),l=Iq(e.inputs.requirementItems),A=cq(c),p=Ge(e,"write.json"),g=p?.commit?.message||Ge(e,"generate-unit.json")?.commitMessage,h=i.working,y=o(yt=>yt.split(`
198
198
  `)[0],"subjectOf"),E=o(yt=>vy(pq(u$(yt)),l),"publicText"),C=o((yt,Zt)=>h&&!!Zt&&E(yt).trim()===E(Zt).trim(),"authored"),I=o((yt,Zt,ir)=>{let st=E(yt);return ir&&dq(st,Zt)?st:Aq(st,Zt,r)},"conform"),b=[u?.commit?.message,n.commitMessage].find(yt=>yt&&E(yt).trim())||"Skyramp Testbot: add tests",D=I(b,{commitlint:A.commitlint},C(b,g)),N=K2(e.outputsDir)??n,W=h?u?.pr?.title||n.prTitle||p?.commit?.prTitle:void 0,K=W||b,Ae=h?N.prTitle:void 0,Pe=y(E(K))===y(E(b)),tt=(!h||!n.prTitle)&&Pe?N.commitMessage:void 0,M=Ae||tt||K,ee=p?.commit?.prTitle||(g?y(g):void 0),O=C(K,ee),ke=A.prTitle?{prTitle:A.prTitle}:O&&W&&!Pe?{}:{commitlint:A.commitlint},ge=y(I(M,ke,O)),q={name:vs,email:jo},P=!!A.signOff;if(!P&&t?.listCommitChecks){let yt=s?.headSha??Yt(c,["rev-parse","HEAD"]);try{P=(await t.listCommitChecks({repository:a,revision:yt}))?.records.some(ir=>ir.name.trim().toLowerCase()==="dco"&&ir.headSha===yt&&(!ir.repository||ir.repository.toLowerCase()===a.toLowerCase()))??!1}catch{console.warn(`[deliver] could not read commit checks for ${a}`)}}let mt=e.inputs.deliverRemote||"origin",Ze=bq(c,kq),Ft=bq(c,Sq);if(Ze&&!Ft)throw new Error(`${a}: the checkout records a merged base but not what it merged`);let ct=Ze?A$(void 0,void 0,c):s?s.headBranch||A$(e.inputs.headBranch,e.inputs.baseBranch,c):A$(void 0,void 0,c),Wt=e.inputs.pullRequests;s?.prNumber!=null&&!Wt?.some(yt=>yt.repository.toLowerCase()===a.toLowerCase())&&(Wt=[...Wt??[],{repository:a,number:String(s.prNumber)}]);let It=Wt?.some(yt=>yt.repository.toLowerCase()===a.toLowerCase())?void 0:e.inputs.deliveryOrigin,Rt=Ze||!It?Ft:void 0,Cn=e.inputs.scheduledDelivery,ut=Cn?(0,GA.createHash)("sha256").update(JSON.stringify([Cn,a.toLowerCase(),ct])).digest("hex"):Rt?qfe(a,ct,Rt):zfe(Wt,a,ct,It),bn=Gfe(ct,e.inputs.deliverBranch)+(Cn?`-scheduled-${ut}`:Rt?`-merge-${ut}`:It?`-source-${It.number}-${ut}`:"");return{texts:l,shown:N,title:ge,unsigned:D,bot:q,signOff:P,remote:mt,base:ct,owner:ut,testsBranch:bn,origin:It,mergedBase:Ze}}o(nge,"planCommit");function rge(e,t,n,i){let r=Yt(e,["interpret-trailers","--trailer",`${Cy}: ${t.owner}`,"--trailer",`${ku}: ${n}`,"--trailer",`${l$}: ${i}`],`${t.unsigned}
199
199
  `);return t.signOff?Iy(r,t.bot):r}o(rge,"trailedMessage");async function ige(e,t,n,i,r,s){let a=$2(i.path,e.runDir),c=process.env.PATH;a.dir&&(process.env.PATH=T2(a).PATH);try{return await sge(e,t,n,i,r,s)}finally{a.dir&&(process.env.PATH=c),a.cleanup()}}o(ige,"deliverOne");async function sge(e,t,n,i,r,s){let a=i.slug,c,u=!1,l;try{let A=i.path,p=await nge(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=u$(X2(Z2(Hfe(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))+`
200
- `,Ae=s?"pr-body.md":`pr-body-${Bq(a)}.md`,Pe=zs.join(e.outputsDir,Ae);Pr.writeFileSync(Pe,K);let tt=Yt(A,["rev-parse","HEAD"]),M=W??tt;Yt(A,["checkout","-B",D]),c=D,Yt(A,["reset"]);for(let P of r)Jfe(zs.join(A,P),g);let ee=[];for(let P of r)try{Yt(A,["--literal-pathspecs","add","--",P])}catch{ee.push(P)}try{Yt(A,["diff","--cached","--quiet"])}catch{try{let P=rge(A,p,tt,M);Yt(A,["-c",`user.name=${E.name}`,"-c",`user.email=${E.email}`,"commit","-m",P])}catch(P){throw new wy(P)}u=!0}l=Yt(A,["rev-parse","HEAD"]);let O,ke=W??s?.headSha;if(u&&ke&&ke!==tt){let P=!1;try{Yt(A,["checkout","-q","-B",c,ke]),P=!0,Yt(A,["-c",`user.name=${E.name}`,"-c",`user.email=${E.email}`,"cherry-pick","--keep-redundant-commits",l]),P=!1,fq(mt=>Yt(A,mt),ke),l=Yt(A,["rev-parse","HEAD"])}catch(mt){try{Yt(A,["cherry-pick","--abort"])}catch{}Yt(A,["checkout","-q","-B",c,l]);let Ze=Gl(bo(mt),1/0);if(W&&!P)throw mt;if(W)return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:C,base:I,committed:u,commitSha:l,pushed:!1,prAction:"skipped",prTitle:y,unstaged:ee,reason:`the tests do not apply to ${I} at ${W.slice(0,12)} without the merged revisions (${Ze}), so no tests PR was opened`}};O=`tests committed on the checkout's merge commit (re-cut onto ${ke.slice(0,12)} failed: ${Ze})`}}let ge=s?{}:{repositoryPath:A,repoSlug:a,devPr:null};if(!u){let P=await t.markTestsPrUnchanged({branch:c,...ge});return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:C,base:I,committed:!1,commitSha:l,pushed:!1,prAction:P.action==="unchanged"?"unchanged":"skipped",prUrl:P.url,prTitle:y,unstaged:ee,reason:P.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 q=await t.publishTestsPr({repositoryPath:A,...ge,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:q.base,requestedBase:I,committed:u,commitSha:l,pushed:q.pushed,...q.pushedCommits?{pushedCommits:q.pushedCommits}:{},...q.deliveredCommit?{deliveredCommit:q.deliveredCommit}:{},prAction:q.action,...q.retargetedAs?{retargetedAs:q.retargetedAs}:{},prUrl:q.url,prTitle:y,...q.failure?{prFailure:q.failure,prDetail:q.detail}:{},...O?{cutNote:O}:{},...q.action==="skipped"&&q.detail?{reason:q.detail}:{},unstaged:ee}}}catch(A){return{thrown:!0,record:{schemaVersion:1,repository:a,branch:c,committed:u,commitSha:l,pushed:!1,prAction:"failed",...tge(A),unstaged:[]}}}}o(sge,"deliverRepository");var LVe={name:"deliver",timeoutMinutes:5,execute:Zfe,validateInput:o(e=>{let t=Zx(e);return t?{ok:!1,reasons:[t]}:jfe(e)},"validateInput"),requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var Qq=Qe(require("fs"));var oge="SKYRAMP_AZURE_SUPERVISED",age=3;function cge(e,t=process.env){t[oge]==="1"?Qq.writeSync(age,`${JSON.stringify(e)}
200
+ `,Ae=s?"pr-body.md":`pr-body-${Bq(a)}.md`,Pe=zs.join(e.outputsDir,Ae);Pr.writeFileSync(Pe,K);let tt=Yt(A,["rev-parse","HEAD"]),M=W??tt;Yt(A,["checkout","-B",D]),c=D,Yt(A,["reset"]);for(let P of r)Jfe(zs.join(A,P),g);let ee=[];for(let P of r)try{Yt(A,["--literal-pathspecs","add","--",P])}catch{ee.push(P)}try{Yt(A,["diff","--cached","--quiet"])}catch{try{let P=rge(A,p,tt,M);Yt(A,["-c",`user.name=${E.name}`,"-c",`user.email=${E.email}`,"commit","-m",P])}catch(P){throw new wy(P)}u=!0}l=Yt(A,["rev-parse","HEAD"]);let O,ke=W??s?.headSha;if(u&&ke&&ke!==tt){let P=!1;try{Yt(A,["checkout","-q","-B",c,ke]),P=!0,Yt(A,["-c",`user.name=${E.name}`,"-c",`user.email=${E.email}`,"cherry-pick","--keep-redundant-commits",l]),P=!1,fq(mt=>Yt(A,mt),ke),l=Yt(A,["rev-parse","HEAD"])}catch(mt){try{Yt(A,["cherry-pick","--abort"])}catch{}Yt(A,["checkout","-q","-B",c,l]);let Ze=Gl(bo(mt),1/0);if(W&&!P)throw mt;if(W)return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:C,base:I,committed:u,commitSha:l,pushed:!1,prAction:"skipped",prTitle:y,unstaged:ee,reason:`the tests do not apply to ${I} at ${W.slice(0,12)} without the merged revisions (${Ze}), so no tests PR was opened`}};O=`tests committed on the checkout's merge commit (re-cut onto ${ke.slice(0,12)} failed: ${Ze})`}}let ge=s?{}:{repositoryPath:A,repoSlug:a,devPr:null};if(!u){let P=await t.markTestsPrUnchanged({branch:c,...ge});return{thrown:!1,record:{schemaVersion:1,repository:a,branch:c,remote:C,base:I,committed:!1,commitSha:l,pushed:!1,prAction:P.action==="unchanged"?"unchanged":"skipped",prUrl:P.url,prTitle:y,unstaged:ee,reason:P.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 q=await t.publishTestsPr({repositoryPath:A,...ge,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:q.base,requestedBase:I,committed:u,commitSha:l,pushed:q.pushed,...q.pushedCommits?{pushedCommits:q.pushedCommits}:{},...q.deliveredCommit?{deliveredCommit:q.deliveredCommit}:{},prAction:q.action,...q.retargetedAs?{retargetedAs:q.retargetedAs}:{},prUrl:q.url,prTitle:y,...q.failure?{prFailure:q.failure,prDetail:q.detail}:{},...O?{cutNote:O}:{},...q.action==="skipped"&&q.detail?{reason:q.detail}:{},unstaged:ee}}}catch(A){return{thrown:!0,record:{schemaVersion:1,repository:a,branch:c,committed:u,commitSha:l,pushed:!1,prAction:"failed",...tge(A),unstaged:[]}}}}o(sge,"deliverRepository");var jVe={name:"deliver",timeoutMinutes:5,execute:Zfe,validateInput:o(e=>{let t=Zx(e);return t?{ok:!1,reasons:[t]}:jfe(e)},"validateInput"),requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var Qq=Qe(require("fs"));var oge="SKYRAMP_AZURE_SUPERVISED",age=3;function cge(e,t=process.env){t[oge]==="1"?Qq.writeSync(age,`${JSON.stringify(e)}
201
201
  `):process.stdout.write(e.command!==void 0?`${e.command}
202
- `:e.text??"")}o(cge,"writeFrame");function uge(e){cge({command:e})}o(uge,"writeAzureCommand");function Rq(e){return e.replace(/%/g,"%AZP25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}o(Rq,"escapeData");function lge(e){return Rq(e).replace(/;/g,"%3B").replace(/]/g,"%5D")}o(lge,"escapeProperty");function dge(e,t,n){let i=Object.entries(t).map(([r,s])=>`${r}=${lge(s)}`).join(";");return`##vso[${e}${i?` ${i}`:""}]${Rq(n)}`}o(dge,"vsoCommand");function Age(e){if(!e)return[];let t=e.split(/\r?\n/).filter(n=>n.trim()&&n!==e);return[e,...t].map(n=>dge("task.setsecret",{},n))}o(Age,"setSecretLines");function xq(e,t=uge){for(let n of Age(e))t(n)}o(xq,"azureSetSecret");function qA(e){return e.replace(/\/+$/,"")}o(qA,"withoutTrailingSlash");function p$(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(p$,"azureOrganization");var pge=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,48}[A-Za-z0-9])?$/,fge=/[\\/:*?"<>|;#${},+=[\]%\p{Cc}\p{Cf}]/u;function $q(e){return e.length>0&&e.length<=64&&e===e.trim()&&!fge.test(e)&&!/[^\S ]/u.test(e)&&!/^[._]/.test(e)&&!e.endsWith(".")}o($q,"isName");function By(e){return f$(`${e.namespace}/${e.name}`)}o(By,"azureRepositoryOfSource");function f$(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||!pge.test(i)||!$q(r)||!$q(s))throw new Error(`"${e}" is not an Azure DevOps organization/project/repository`);return{organization:i,project:r,name:s}}o(f$,"azureRepositoryOf");function Tq(e,t){let n=p$(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(Tq,"inOrganization");function Dq(e,t){return Tq(e,t),`${qA(e)}/${encodeURIComponent(t.project)}/_git/${encodeURIComponent(t.name)}`}o(Dq,"azureCloneUrl");function g$(e,t){return Tq(e,t),`${qA(e)}/${encodeURIComponent(t.project)}/_apis/git/repositories/${encodeURIComponent(t.name)}`}o(g$,"azureRepositoryApi");var gge="7.1",zA=class extends Error{constructor(n,i){super(n);this.status=i}status;static{o(this,"AzureRestError")}};async function h$(e){let t=e.accept??"application/json",n=new URL(e.url);n.searchParams.has("api-version")||n.searchParams.set("api-version",gge);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(h$,"azureRest");function hge(e){return`AUTHORIZATION: bearer ${e}`}o(hge,"azureGitAuthorization");function _q(e,t){return{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${qA(e)}/.extraheader`,GIT_CONFIG_VALUE_0:hge(t)}}o(_q,"azureGitAuthEnv");var mge="7.1-preview.1",yge=".azure-pipelines/skyramp-testbot-v3.yml";function m$(e){return e.GITHUB_ACTIONS!=="true"&&/^true$/i.test(e.TF_BUILD??"")}o(m$,"isAzurePipelines");function Fq(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(()=>p$(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=>xq(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",mge);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:m$(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:`${yge}@${n("BUILD_SOURCEBRANCH")}`}},takeIdToken(){let p=e.SYSTEM_OIDCREQUESTURI;delete e.SYSTEM_OIDCREQUESTURI;let g=A(p);return()=>g()},takeSourceToken(){return delete e.SYSTEM_ACCESSTOKEN,u||void 0},webIdentity(){if(!e.SYSTEM_OIDCREQUESTURI?.trim()||!u)return;let p=A(e.SYSTEM_OIDCREQUESTURI);return{token:o(()=>p(),"token"),runId:e.BUILD_BUILDID}},v3RunsOnly:!0,assumesBedrockRole:!0,namesSourceToMcp:!0,runSettingsFromApp:!0,checkSourceName(p){By(p)},cloneUrl(p){return Dq(i,By(p))},gitAuthEnv(p){return _q(i,p)},async pullRequest(p,g,h){let y=await h$({token:await h.token(),url:`${g$(i,By(p))}/pullrequests/${g}`,fetch:h.fetch}),E=y.status==="completed";return{...typeof y.title=="string"?{title:y.title}:{},...typeof y.description=="string"?{body:y.description}:{},...typeof y.status=="string"?{merged:E}:{},...E&&typeof y.lastMergeCommit?.commitId=="string"?{mergeCommit:y.lastMergeCommit.commitId}:{},...E&&typeof y.lastMergeSourceCommit?.commitId=="string"?{mergedHead:y.lastMergeSourceCommit.commitId}:{}}},async commit(p,g,h){let y;try{y=g$(i,f$(p))}catch{return{lookup:"unknown"}}try{let E=await h$({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(Fq,"azureRunnerHost");pc();var Ege=5e3,y$=/^(?!\.\.?$)[A-Za-z0-9._-]{1,100}$/;function Ige(e){let t=Buffer.from(`x-access-token:${e}`).toString("base64");return Ol(t),`AUTHORIZATION: basic ${t}`}o(Ige,"githubGitAuthorization");function Pq(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=>IM(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(!y$.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:Ige(u)}:{}},async pullRequest({namespace:u,name:l},A,p){if(![u,l].every(y=>y$.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&&y$.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(Ege)});if(!A.ok&&A.status!==401)throw new Error(`GitHub answered ${A.status}`)}}}o(Pq,"githubRunnerHost");function Mq(e=process.env){return m$(e)?Fq(e):Pq(e)}o(Mq,"runnerHost");var Cge=10*6e4;function bge(e,t){return e.getTime()-t.getTime()-Cge}o(bge,"remainingBudgetMs");var Oq="This attempt revoked its scoped GitHub credentials; it mints no more.",vge=10*6e4;var wge=o(e=>!!e&&Object.keys(e).length===1&&e.contents==="read","onlyReads"),Bge=3e4,kge=3,Lq=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")}},hi=class extends Error{static{o(this,"AppUnreachable")}},Qu=class extends hi{static{o(this,"AppNotReady")}},E$=class extends Qu{static{o(this,"RunnerProviderNotReady")}};function I$(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(I$,"appOrigin");function Vq(e,t){if(!kc.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}o(Vq,"routeId");function Sge(e,t){return`${e.replace(/\/+$/,"")}/runs/${t}`}o(Sge,"skyrampRunPageUrl");function Gq(e,t,n,i){throw t<500&&t!==429?new Mr(e,t,n,i):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new E$(e):t===503&&n==="RUN_NOT_READY"?new Qu(e):new hi(e)}o(Gq,"refusedOrUnreachable");async function zq(e,t,n,i,r,s=1/0){let a=I$(e.origin),c=`The time limit for ${t} ${n} was reached`,u,l=0;for(let A=1;A<=kge||u instanceof Qu;A+=1){if(u instanceof Qu){if(l===Lq)throw u;l+=1,A-=1,e.log?.(`${u.message}; trying again (${l} of ${Lq}).`),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 hi(c);try{let p,g=await(Number.isFinite(s)?Promise.race([e.idToken(a),new Promise((y,E)=>{p=setTimeout(()=>E(new hi(c)),Math.max(1,s-Date.now()))})]).finally(()=>{p&&clearTimeout(p)}):e.idToken(a));if(Date.now()>=s)throw new hi(c);let h=await(e.fetch??fetch)(new URL(n,a).toString(),{...i(g),redirect:"error",signal:AbortSignal.timeout(Math.max(1,Math.min(Bge,s-Date.now())))}).catch(y=>{throw new hi(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(zq,"callWithRetries");function qq(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(qq,"logRefusal");function ky(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")>BO)throw new Error("The report exceeds the app's 16 MiB expanded report limit");let c=a?new Uint8Array((0,jq.gzipSync)(s)):s;if(a&&c.length>$g)throw new Error("The compressed report exceeds the app's 1 MiB report upload limit");return zq(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;qq(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 Gq(y,l.status,p.error?.code,typeof g?.path=="string"?g.path:void 0)},r)}o(ky,"callApp");function Qge(e,t,n){return zq(e,"GET",t,o(r=>({method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/octet-stream"}}),"request"),async r=>{if(!r.ok)return qq(e,"GET",t,r,await r.text().catch(()=>"")),Gq(`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(Qge,"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 bge(this.deadlineAt,t)}get skyrampRunUrl(){return Sge(I$(this.deps.origin),this.manifest.runId)}log(t){this.deps.log?.(t)}send(t,n,i,r){return ky(this.deps,t,n,i,r)}readBytes(t,n){return Qge(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(Oq);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>=vge)return r.token;if(this.revocation)throw new Error(Oq);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&&!wge(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??Mq();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){Vq(e,"run id"),I$(n.origin);let i=Gb(e,t),r=`/api/v1/runner/runs/${e}/attempts`,s;try{s=await ky(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 ky(n,"POST",r,i)}let a=zO(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}`);Rge(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 Rge(e,t){if(t.length===0)return;if(!TO(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(Rge,"checkAttemptPins");async function C$(e,t){return LO.parse(await e.send("POST",`/api/v1/runner/attempts/${e.attemptId}/heartbeat`,{schemaVersion:1},t))}o(C$,"heartbeatV3Attempt");async function Hq(e,t=()=>new Date,n){if(e.closure)return e.closure;let i=await C$(e,n).then(r=>jO(r,t())).catch(()=>null);return i&&(e.closure=i),i}o(Hq,"closedV3Attempt");var XGe=10*6e4;var eze=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var tze=d.object({tests:d.object({placements:d.array(d.unknown()).optional()}).passthrough().optional()}).passthrough(),nze=d.object({repository:Mb,testType:d.string(),directory:d.string()}).passthrough();var rze=d.object({report:d.object({language:d.string()}).passthrough()}).passthrough();var ize=d.object({environment:d.object({components:d.array(d.unknown()).optional(),dependencies:d.array(d.unknown()).optional()}).passthrough()}).passthrough(),sze=d.object({environment:d.object({offLimits:d.unknown().optional()}).passthrough()}).passthrough();var oze=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(),aze=d.object({name:d.string().min(1),url:d.string().nullable(),versionUrl:d.string().nullable(),notes:d.string().nullable()}).passthrough();var cze=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);function Yq(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(Yq,"statusCounts");function xge(e){let{passed:t,failed:n,skipped:i}=Yq(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(xge,"executedTestsValidation");function $ge(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($ge,"withResultIds");function Tge({notTranslated:e,...t},n){let i=$ge(t.testResults,n);return{...t,testResults:i,...Dge(t,i,n),validation:Uge(t,_ge(t,t.validation??xge(t))),traceVersion:1}}o(Tge,"v3Report");function Dge(e,t,n){if(!e.testExecutionContexts)return{};let i=new Set,r=o(c=>{let u=c;for(let l=2;i.has(u);l+=1)u=`${c}#${l}`;return i.add(u),u},"unique"),s=[],a=new Map;for(let{repository:c,...u}of e.testExecutionContexts){let l=u.status==="not_run"?[]:t.filter(A=>A.fileName===u.test&&A.repository===(c?.trim()||n));l.length||s.push(u);for(let{resultId:A}of l){let p=a.get(A),g=p!==void 0&&s[p].cleanup.status==="failed"?s[p].cleanup:u.cleanup,h={...u,cleanup:g,test:A,resultId:A};p===void 0?a.set(A,s.push(h)-1):s[p]=h}}for(let c of s)c.resultId&&i.add(c.resultId);return{testExecutionContexts:s.map(c=>c.resultId?c:{...c,test:r(c.test.slice(0,512))}).slice(0,5e3)}}o(Dge,"linkedContexts");function _ge(e,t){let{passed:n,failed:i}=Yq(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(_ge,"withEvidence");var Nge={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};function Uge(e,t){if(t.sufficiency==="sufficient")return t;let n=(e.caveats??[]).map(r=>Nge[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(Uge,"withModelProviderFailure");function Fge(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(Fge,"v3Display");async function Wq(e,t){let n=wM([...e.issuedTokens,...t.secrets??[]]),i={...Tge(t.report,t.workingSlug),...t.notTranslated?{notTranslated:t.notTranslated}:{}},r=t.translated&&Fge(t.report,t.translated,i),s=o(c=>qO({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(Wq,"uploadV3Report");async function Zq(e,t){return Vq(e.attemptId,"attempt id"),ky(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,JO({reportUploaded:e.reportUploaded,recipeUploaded:e.recipeUploaded,revisionsUploaded:e.revisionsUploaded,cancelled:e.cause==="cancelled",timedOut:e.cause==="timed_out",setupFailed:e.cause==="setup_failed",checkoutFailed:e.cause==="checkout_failed"||e.cause==="merge_conflict"&&!e.conflict,mergeConflict:e.cause==="merge_conflict"?e.conflict:void 0,environmentUnverified:e.cause==="environment_unverified",runnerProviderNotReady:e.cause==="runner_provider_not_ready",credentialMissing:e.cause==="credential_missing",modelProviderDenied:e.cause==="model_provider_denied",modelProviderUnavailable:e.cause==="model_provider_unavailable"}))}o(Zq,"endV3Attempt");0&&(module.exports={AppRefusal,AppUnreachable,AttemptEndReason,DeliveryStatus,GitHubWriteKind,NoReportCause,SourceProvider,V3Attempt,ValidationSufficiency,closedV3Attempt,endV3Attempt,heartbeatV3Attempt,startV3Attempt,uploadV3Report});
202
+ `:e.text??"")}o(cge,"writeFrame");function uge(e){cge({command:e})}o(uge,"writeAzureCommand");function Rq(e){return e.replace(/%/g,"%AZP25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}o(Rq,"escapeData");function lge(e){return Rq(e).replace(/;/g,"%3B").replace(/]/g,"%5D")}o(lge,"escapeProperty");function dge(e,t,n){let i=Object.entries(t).map(([r,s])=>`${r}=${lge(s)}`).join(";");return`##vso[${e}${i?` ${i}`:""}]${Rq(n)}`}o(dge,"vsoCommand");function Age(e){if(!e)return[];let t=e.split(/\r?\n/).filter(n=>n.trim()&&n!==e);return[e,...t].map(n=>dge("task.setsecret",{},n))}o(Age,"setSecretLines");function xq(e,t=uge){for(let n of Age(e))t(n)}o(xq,"azureSetSecret");function qA(e){return e.replace(/\/+$/,"")}o(qA,"withoutTrailingSlash");function p$(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(p$,"azureOrganization");var pge=/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,48}[A-Za-z0-9])?$/,fge=/[\\/:*?"<>|;#${},+=[\]%\p{Cc}\p{Cf}]/u;function $q(e){return e.length>0&&e.length<=64&&e===e.trim()&&!fge.test(e)&&!/[^\S ]/u.test(e)&&!/^[._]/.test(e)&&!e.endsWith(".")}o($q,"isName");function By(e){return f$(`${e.namespace}/${e.name}`)}o(By,"azureRepositoryOfSource");function f$(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||!pge.test(i)||!$q(r)||!$q(s))throw new Error(`"${e}" is not an Azure DevOps organization/project/repository`);return{organization:i,project:r,name:s}}o(f$,"azureRepositoryOf");function Tq(e,t){let n=p$(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(Tq,"inOrganization");function Dq(e,t){return Tq(e,t),`${qA(e)}/${encodeURIComponent(t.project)}/_git/${encodeURIComponent(t.name)}`}o(Dq,"azureCloneUrl");function g$(e,t){return Tq(e,t),`${qA(e)}/${encodeURIComponent(t.project)}/_apis/git/repositories/${encodeURIComponent(t.name)}`}o(g$,"azureRepositoryApi");var gge="7.1",zA=class extends Error{constructor(n,i){super(n);this.status=i}status;static{o(this,"AzureRestError")}};async function h$(e){let t=e.accept??"application/json",n=new URL(e.url);n.searchParams.has("api-version")||n.searchParams.set("api-version",gge);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(h$,"azureRest");function hge(e){return`AUTHORIZATION: bearer ${e}`}o(hge,"azureGitAuthorization");function _q(e,t){return{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${qA(e)}/.extraheader`,GIT_CONFIG_VALUE_0:hge(t)}}o(_q,"azureGitAuthEnv");var mge="7.1-preview.1",yge=".azure-pipelines/skyramp-testbot-v3.yml";function m$(e){return e.GITHUB_ACTIONS!=="true"&&/^true$/i.test(e.TF_BUILD??"")}o(m$,"isAzurePipelines");function Fq(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(()=>p$(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=>xq(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",mge);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:m$(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:`${yge}@${n("BUILD_SOURCEBRANCH")}`}},takeIdToken(){let p=e.SYSTEM_OIDCREQUESTURI;delete e.SYSTEM_OIDCREQUESTURI;let g=A(p);return()=>g()},takeSourceToken(){return delete e.SYSTEM_ACCESSTOKEN,u||void 0},webIdentity(){if(!e.SYSTEM_OIDCREQUESTURI?.trim()||!u)return;let p=A(e.SYSTEM_OIDCREQUESTURI);return{token:o(()=>p(),"token"),runId:e.BUILD_BUILDID}},v3RunsOnly:!0,assumesBedrockRole:!0,namesSourceToMcp:!0,runSettingsFromApp:!0,checkSourceName(p){By(p)},cloneUrl(p){return Dq(i,By(p))},gitAuthEnv(p){return _q(i,p)},async pullRequest(p,g,h){let y=await h$({token:await h.token(),url:`${g$(i,By(p))}/pullrequests/${g}`,fetch:h.fetch}),E=y.status==="completed";return{...typeof y.title=="string"?{title:y.title}:{},...typeof y.description=="string"?{body:y.description}:{},...typeof y.status=="string"?{merged:E}:{},...E&&typeof y.lastMergeCommit?.commitId=="string"?{mergeCommit:y.lastMergeCommit.commitId}:{},...E&&typeof y.lastMergeSourceCommit?.commitId=="string"?{mergedHead:y.lastMergeSourceCommit.commitId}:{}}},async commit(p,g,h){let y;try{y=g$(i,f$(p))}catch{return{lookup:"unknown"}}try{let E=await h$({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(Fq,"azureRunnerHost");pc();var Ege=5e3,y$=/^(?!\.\.?$)[A-Za-z0-9._-]{1,100}$/;function Ige(e){let t=Buffer.from(`x-access-token:${e}`).toString("base64");return Ol(t),`AUTHORIZATION: basic ${t}`}o(Ige,"githubGitAuthorization");function Pq(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=>IM(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(!y$.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:Ige(u)}:{}},async pullRequest({namespace:u,name:l},A,p){if(![u,l].every(y=>y$.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&&y$.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(Ege)});if(!A.ok&&A.status!==401)throw new Error(`GitHub answered ${A.status}`)}}}o(Pq,"githubRunnerHost");function Mq(e=process.env){return m$(e)?Fq(e):Pq(e)}o(Mq,"runnerHost");var Cge=10*6e4;function bge(e,t){return e.getTime()-t.getTime()-Cge}o(bge,"remainingBudgetMs");var Oq="This attempt revoked its scoped GitHub credentials; it mints no more.",vge=10*6e4;var wge=o(e=>!!e&&Object.keys(e).length===1&&e.contents==="read","onlyReads"),Bge=3e4,kge=3,Lq=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")}},hi=class extends Error{static{o(this,"AppUnreachable")}},Qu=class extends hi{static{o(this,"AppNotReady")}},E$=class extends Qu{static{o(this,"RunnerProviderNotReady")}};function I$(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(I$,"appOrigin");function Vq(e,t){if(!kc.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}o(Vq,"routeId");function Sge(e,t){return`${e.replace(/\/+$/,"")}/runs/${t}`}o(Sge,"skyrampRunPageUrl");function Gq(e,t,n,i){throw t<500&&t!==429?new Mr(e,t,n,i):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new E$(e):t===503&&n==="RUN_NOT_READY"?new Qu(e):new hi(e)}o(Gq,"refusedOrUnreachable");async function zq(e,t,n,i,r,s=1/0){let a=I$(e.origin),c=`The time limit for ${t} ${n} was reached`,u,l=0;for(let A=1;A<=kge||u instanceof Qu;A+=1){if(u instanceof Qu){if(l===Lq)throw u;l+=1,A-=1,e.log?.(`${u.message}; trying again (${l} of ${Lq}).`),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 hi(c);try{let p,g=await(Number.isFinite(s)?Promise.race([e.idToken(a),new Promise((y,E)=>{p=setTimeout(()=>E(new hi(c)),Math.max(1,s-Date.now()))})]).finally(()=>{p&&clearTimeout(p)}):e.idToken(a));if(Date.now()>=s)throw new hi(c);let h=await(e.fetch??fetch)(new URL(n,a).toString(),{...i(g),redirect:"error",signal:AbortSignal.timeout(Math.max(1,Math.min(Bge,s-Date.now())))}).catch(y=>{throw new hi(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(zq,"callWithRetries");function qq(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(qq,"logRefusal");function ky(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")>BO)throw new Error("The report exceeds the app's 16 MiB expanded report limit");let c=a?new Uint8Array((0,jq.gzipSync)(s)):s;if(a&&c.length>$g)throw new Error("The compressed report exceeds the app's 1 MiB report upload limit");return zq(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;qq(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 Gq(y,l.status,p.error?.code,typeof g?.path=="string"?g.path:void 0)},r)}o(ky,"callApp");function Qge(e,t,n){return zq(e,"GET",t,o(r=>({method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/octet-stream"}}),"request"),async r=>{if(!r.ok)return qq(e,"GET",t,r,await r.text().catch(()=>"")),Gq(`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(Qge,"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 bge(this.deadlineAt,t)}get skyrampRunUrl(){return Sge(I$(this.deps.origin),this.manifest.runId)}log(t){this.deps.log?.(t)}send(t,n,i,r){return ky(this.deps,t,n,i,r)}readBytes(t,n){return Qge(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(Oq);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>=vge)return r.token;if(this.revocation)throw new Error(Oq);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&&!wge(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??Mq();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){Vq(e,"run id"),I$(n.origin);let i=Gb(e,t),r=`/api/v1/runner/runs/${e}/attempts`,s;try{s=await ky(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 ky(n,"POST",r,i)}let a=zO(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}`);Rge(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 Rge(e,t){if(t.length===0)return;if(!TO(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(Rge,"checkAttemptPins");async function C$(e,t){return LO.parse(await e.send("POST",`/api/v1/runner/attempts/${e.attemptId}/heartbeat`,{schemaVersion:1},t))}o(C$,"heartbeatV3Attempt");async function Hq(e,t=()=>new Date,n){if(e.closure)return e.closure;let i=await C$(e,n).then(r=>jO(r,t())).catch(()=>null);return i&&(e.closure=i),i}o(Hq,"closedV3Attempt");var eze=10*6e4;var tze=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var nze=d.object({tests:d.object({placements:d.array(d.unknown()).optional()}).passthrough().optional()}).passthrough(),rze=d.object({repository:Mb,testType:d.string(),directory:d.string()}).passthrough();var ize=d.object({report:d.object({language:d.string()}).passthrough()}).passthrough();var sze=d.object({environment:d.object({components:d.array(d.unknown()).optional(),dependencies:d.array(d.unknown()).optional()}).passthrough()}).passthrough(),oze=d.object({environment:d.object({offLimits:d.unknown().optional()}).passthrough()}).passthrough();var aze=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(),cze=d.object({name:d.string().min(1),url:d.string().nullable(),versionUrl:d.string().nullable(),notes:d.string().nullable()}).passthrough();var uze=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);function Yq(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(Yq,"statusCounts");function xge(e){let{passed:t,failed:n,skipped:i}=Yq(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(xge,"executedTestsValidation");function $ge(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($ge,"withResultIds");function Tge({notTranslated:e,...t},n){let i=$ge(t.testResults,n);return{...t,testResults:i,...Dge(t,i,n),validation:Uge(t,_ge(t,t.validation??xge(t))),traceVersion:1}}o(Tge,"v3Report");function Dge(e,t,n){if(!e.testExecutionContexts)return{};let i=new Set,r=o(c=>{let u=c;for(let l=2;i.has(u);l+=1)u=`${c}#${l}`;return i.add(u),u},"unique"),s=[],a=new Map;for(let{repository:c,...u}of e.testExecutionContexts){let l=u.status==="not_run"?[]:t.filter(A=>A.fileName===u.test&&A.repository===(c?.trim()||n));l.length||s.push(u);for(let{resultId:A}of l){let p=a.get(A),g=p!==void 0&&s[p].cleanup.status==="failed"?s[p].cleanup:u.cleanup,h={...u,cleanup:g,test:A,resultId:A};p===void 0?a.set(A,s.push(h)-1):s[p]=h}}for(let c of s)c.resultId&&i.add(c.resultId);return{testExecutionContexts:s.map(c=>c.resultId?c:{...c,test:r(c.test.slice(0,512))}).slice(0,5e3)}}o(Dge,"linkedContexts");function _ge(e,t){let{passed:n,failed:i}=Yq(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(_ge,"withEvidence");var Nge={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};function Uge(e,t){if(t.sufficiency==="sufficient")return t;let n=(e.caveats??[]).map(r=>Nge[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(Uge,"withModelProviderFailure");function Fge(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(Fge,"v3Display");async function Wq(e,t){let n=wM([...e.issuedTokens,...t.secrets??[]]),i={...Tge(t.report,t.workingSlug),...t.notTranslated?{notTranslated:t.notTranslated}:{}},r=t.translated&&Fge(t.report,t.translated,i),s=o(c=>qO({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(Wq,"uploadV3Report");async function Zq(e,t){return Vq(e.attemptId,"attempt id"),ky(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,JO({reportUploaded:e.reportUploaded,recipeUploaded:e.recipeUploaded,revisionsUploaded:e.revisionsUploaded,cancelled:e.cause==="cancelled",timedOut:e.cause==="timed_out",setupFailed:e.cause==="setup_failed",checkoutFailed:e.cause==="checkout_failed"||e.cause==="merge_conflict"&&!e.conflict,mergeConflict:e.cause==="merge_conflict"?e.conflict:void 0,environmentUnverified:e.cause==="environment_unverified",runnerProviderNotReady:e.cause==="runner_provider_not_ready",credentialMissing:e.cause==="credential_missing",modelProviderDenied:e.cause==="model_provider_denied",modelProviderUnavailable:e.cause==="model_provider_unavailable"}))}o(Zq,"endV3Attempt");0&&(module.exports={AppRefusal,AppUnreachable,AttemptEndReason,DeliveryStatus,GitHubWriteKind,NoReportCause,SourceProvider,V3Attempt,ValidationSufficiency,closedV3Attempt,endV3Attempt,heartbeatV3Attempt,startV3Attempt,uploadV3Report});
203
203
  /*! Bundled license information:
204
204
 
205
205
  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.384",
3
+ "version": "0.13.0-v3.385",
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.",