@skyramp/testbot-core 0.13.2-v3.543 → 0.13.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/VERSION.json +1 -1
- package/dist/main.js +482 -481
- package/dist/post.js +13 -13
- package/dist/runner-client.cjs +9 -9
- package/package.json +1 -1
package/dist/post.js
CHANGED
|
@@ -254,20 +254,20 @@ health check cancelled`,u(1)},h=setTimeout(l,Math.max(1,t.deadlineMs-Date.now())
|
|
|
254
254
|
%{http_code}
|
|
255
255
|
%{redirect_url}`,...vIe(i),r],{cwd:n,deadlineMs:Math.min(e,Date.now()+25e3),signal:t});if(a.exitCode!==0)return{error:(a.stderr||"curl failed").trim()};let c=a.stdout??"",u=c.lastIndexOf(`
|
|
256
256
|
`),l=c.lastIndexOf(`
|
|
257
|
-
`,u-1),p=Number(c.slice(l+1,u).trim()),h=c.slice(u+1);return{status:Number.isFinite(p)?p:0,body:c.slice(0,l),...h?{redirect:h}:{}}},async runCommand(r,i){let{steps:o,reason:a}=Qc(r);if(!o)return{exitCode:1,output:`${aK}${a}`};let c="";for(let u of o){if(Date.now()>=e)return{exitCode:1,output:"health check time limit reached"};let l=await iK(u,{cwd:i,deadlineMs:Math.min(e,Date.now()+6e4),env:pt(),signal:t});if(c+=`${l.stdout??""}${l.stderr??""}`,l.exitCode!==0)return{exitCode:l.exitCode,output:c}}return{exitCode:0,output:c}}}}function vIe(e){return e?Object.entries(e).flatMap(([t,n])=>["-H",`${t}: ${n}`]):[]}function cK(e){return e.trim().replace(/^\.\//,"").replace(/\/+$/,"")}function bIe(e){if(!e.inputs)return[];let t=Gs(e),n=r=>{let i=typeof r=="string"?r:r?.path??r?.file;return typeof i=="string"&&i.trim()?cK(i):void 0},s=(r,i)=>r?(i??[]).flatMap(o=>{let a=n(o);return a?[{repository:r,path:a}]:[]}):[];return[...s(Si(e.inputs).slug,[...t?.changedFiles??[],...t?.newFiles??[]]),...(t?.relatedChanges??[]).flatMap(r=>s(r.repository,r.changedFiles))]}function wIe(e,t){let n=Ta.resolve(e.inputs.repositoryPath,t.trim()),s=IB(e.inputs,n),r=s&&Ta.relative(s.path,n);return s&&r?{repository:s.slug,path:r.split(Ta.sep).join("/")}:void 0}function _w(e,t={}){let n=t.budgetMs??fIe,s=t.intervalMs??hIe;return{name:"deploy-health",async verify(r,i){if(r.signal?.aborted)return{name:this.name,passed:!1,details:"health check cancelled"};let o=e??Qw(r.deadlineMs??1/0,r.signal,r.inputs.repositoryPath),{deploy:a,errors:c}=Ru(i,r.inputs?.repositoryPath,r.secretValues);if(!a)return{name:this.name,passed:!1,details:c.slice(0,6).join("; ")};if(a.outcome==="bringup-failed")return{name:this.name,passed:!0};if(a.outcome==="change-broke-bringup"){let I=bIe(r),C=(a.suspectFiles??[]).map(cK),w=C.filter(x=>{let S=wIe(r,x);return!!S&&GE(I,S.repository,S.path)});return I.length>0&&w.length===0?{name:this.name,passed:!1,details:`change-broke-bringup claimed, but none of suspectFiles [${C.slice(0,4).join(", ")}] is a file this PR changed \u2014 that is not attributable to the PR. Re-run bring-up; if it still fails for a reason outside the diff, record outcome "bringup-failed" (with bringupError) instead.`}:{name:this.name,passed:!0}}let u=a.health;if(!u)return{name:this.name,passed:!1,details:"health is missing although the app is recorded as up"};let l=yIe(u.headers),p=(I,C=!1)=>({ok:!1,details:I,transient:C}),h=async()=>{if(!kw(u.url,mD(r)))return p(`health url ${u.url} is not the app under test \u2014 this gate probes only loopback, the Test Environment's address or an address the Target's settings give, never an arbitrary destination. Record the URL the deployed app actually answers on.`);let I=await o.httpGet(u.url,u.headers);if("error"in I)return p(`health url ${u.url} unreachable: ${I.error}`,!0);let C=Number(u.status??200);if(I.status!==C)return p(`health url returned ${I.status}, expected ${C}`,!0);if(!I.body.trim())return p("health url returned empty body \u2014 must return data",!0);let w=(u.output??"").trim();if(w){let x=rK(w,I.body);if(!x.ok)return p(`health url ${u.url} no longer answers as recorded \u2014 ${x.why}. Either the app is not answering as it did at deploy time, or health.output is not verbatim: record ONLY the response body, with no commentary appended.`)}return{ok:!0}},g=async()=>{let I=await o.runCommand(u.command,r.inputs.repositoryPath),C=I.output.startsWith(aK);if(I.exitCode!==0)return p(`health command exited ${I.exitCode}: ${I.output.slice(0,200)}`,!C);if(!I.output.trim())return p("health command produced no output",!0);let w=(u.output??"").trim();if(w.length<16)return p(`health command output "${w}" is too thin to be a data check \u2014 the check must return real application data, not a status token`);let x=rK(w,I.output);return x.ok?{ok:!0}:p(`health command did not reproduce its recorded check \u2014 ${x.why}. Either the app is not answering as it did at deploy time, or health.output is not verbatim: record ONLY what the command wrote, with no commentary appended.`)},m;if(u.command&&(l||!u.url))m=g;else{if(u.url&&l)return{name:this.name,passed:!1,details:`health.headers contains a documented placeholder (${Object.entries(u.headers??{}).filter(([,I])=>/<[^>]+>/.test(String(I))).map(([I])=>I).join(", ")}), and this gate RE-EXECUTES the probe \u2014 a placeholder cannot authenticate. Record a health.command instead (a script that fetches its own token and hits the URL); do not put a real credential in the artifact.`};u.url?m=h:u.command&&(m=g)}if(!m)return{name:this.name,passed:!1,details:"health has neither url nor command"};let y=Date.now(),v=y+n,E=await m();for(;!E.ok&&E.transient&&!r.signal?.aborted&&Date.now()+s<v&&(await new Promise((I,C)=>{let w,x=Y=>{clearTimeout(w),r.signal?.removeEventListener("abort",S),Y?C(Y):I()},S=()=>x();if(r.signal?.addEventListener("abort",S,{once:!0}),r.signal?.aborted){x();return}t.sleep?t.sleep(s).then(()=>x(),x):w=setTimeout(()=>x(),s)}),!r.signal?.aborted);)E=await m();if(r.signal?.aborted)return{name:this.name,passed:!1,details:"health check cancelled"};if(E.ok)return{name:this.name,passed:!0};let b=Math.round((Date.now()-y)/1e3);return{name:this.name,passed:!1,details:E.transient&&b>0?`${E.details} (still failing after ${b}s)`:E.details}}}}function kD(e){return uK(e)&&Yg(e).length===0&&SD(e.inputs?.sharedEnvironment).length===0}function uK(e){let t=IIe(e);if(!t&&e.state.stages.deploy?.status!=="passed")return!1;let n=Ae(e,"deploy.json");return n?lK(n):!t}function lK(e){return e?.outcome==="clean"||e?.outcome==="recipe-drift"}function IIe(e){let t=e.state.stages.plan,n=e.state.stages.deploy;return!(e.inputs?.pipeline?e.inputs.pipeline==="two-step":!n)||t?.status!=="passed"?!1:!n||n.updatedAt<=t.updatedAt}async function CIe(e,t,n){let s=new URL(t.url).origin;return(URL.canParse(e.url)?new URL(e.url).origin:e.url)===s?xw(e.url,n):{error:`${e.url} is not on ${s}, where ${t.name} runs`}}async function SIe(e,t,n){let s=$w(e.inputs??{}),r=[];for(let i of t){let o=s.find(l=>l.name===i.component);if(!o){r.push(`revisions names "${i.component}", which is not a shared component listed for a revision check`);continue}let a=await CIe(i,o,n);if("error"in a){r.push(`the revision check of ${o.name} could not be re-run: ${Hs(a.error,e.secretValues??[]).slice(0,200)}`);continue}let c=Bw(o.expectedRevision,{body:i.output}),u=Bw(o.expectedRevision,a);c.observedRevision!==u.observedRevision&&r.push(`the revision check of ${o.name} names ${u.observedRevision??"no commit"} when re-run, but its recorded output names ${c.observedRevision??"no commit"} \u2014 record what the check returned, verbatim, or leave the component out`)}return r}function dK(e,t=1/0,n){return async(s,r)=>{if(!Vr(e))throw new Error("the guarded setup network boundary is unavailable");let i=n&&r?.signal?AbortSignal.any([n,r.signal]):n??r?.signal??void 0,o=await Qw(t,i,e).httpGet(String(s));if("error"in o)throw new Error(o.error);return new Response([204,205,304].includes(o.status)?null:o.body,{status:o.status,headers:o.redirect?{Location:o.redirect}:void 0})}}function pK(e){let t=e.inputs;return t?.setupEvents&&!t.recheck&&En(t)?dK(t.repositoryPath,e.deadlineMs,e.signal):void 0}function fK(e){return{name:"shared-revisions",async verify(t,n){let{deploy:s}=Ru(n,t.inputs?.repositoryPath,t.secretValues),r=await SIe(t,s?.revisions??[],e??pK(t));return r.length?{name:this.name,passed:!1,details:r.join("; ")}:{name:this.name,passed:!0}}}}async function hK(e,t,n){let s=e.inputs?.sharedEnvironment;if(!ID(s))return{};let{deploy:r}=Ru(t,e.inputs.repositoryPath,e.secretValues),i=await YZ(s,r?.revisions??[],n??pK(e),e.secretValues??[]);return Ln(e,np,Hs(i,e.secretValues??[]),[])}function gK(e,t){let{deploy:n,errors:s}=Ru(t,e.inputs?.repositoryPath,e.secretValues),r=n?.health?.headers?{...n,health:{...n.health,headers:Object.fromEntries(Object.keys(n.health.headers).map(a=>[a,"<redacted>"]))}}:n,i=e.secretValues??[],o=r&&kIe(r,Hs(r,i),i.filter(a=>a.length>=Sh));return Ln(e,"deploy",o,s)}function kIe(e,t,n){let s=r=>Lt(r,n);return{...t,teardown:s(e.teardown),...e.baseUrls?{baseUrls:Object.fromEntries(Object.entries(e.baseUrls).map(([r,i])=>[r,s(i)]))}:{},...e.health&&t.health?{health:{...t.health,...e.health.url!==void 0?{url:s(e.health.url)}:{},...e.health.command!==void 0?{command:s(e.health.command)}:{}}}:{},...e.revisions&&t.revisions?{revisions:t.revisions.map((r,i)=>({...r,url:s(e.revisions[i].url)}))}:{}}}var yK=G(require("path"));var _Ie="test-execution-contexts.json";var y1e=10*6e4;function BD(e){let t=Vs(yK.join(e.outputsDir,_Ie));return Array.isArray(t)?t:[]}var xD=(e,t)=>e.file===t.file&&(e.repository??"")===(t.repository??"");function $D(e){return e.filter((t,n)=>!e.slice(n+1).some(s=>xD(t,s)))}var Dw=(r=>(r.RestApi="rest-api",r.Frontend="frontend",r.FullStack="full-stack",r.Other="other",r))(Dw||{}),Qa=(r=>(r.Critical="critical",r.High="high",r.Medium="medium",r.Low="low",r))(Qa||{}),Bu=(s=>(s.Suspected="suspected",s.Latent="latent",s.Refuted="refuted",s))(Bu||{}),QD=(s=>(s.Skyramp="skyramp",s.External="external",s.Unknown="unknown",s))(QD||{}),_D=(r=>(r.Cascade="cascade",r.Restrict="restrict",r.Orphan="orphan",r.Unknown="unknown",r))(_D||{}),ks=(r=>(r.RequirementReference="requirement-reference",r.Spec="spec",r.PrDescription="pr-description",r.CouldBreak="could-break",r))(ks||{}),It=d.string().trim().min(1),rp=It.describe("file:line"),EK=e=>It.refine(t=>t.length<=400,t=>({message:`is ${t.length} characters, over the 400 cap \u2014 ${e}`})),Zg=It.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'),TD=d.object({method:It,path:It,service:d.string().optional(),evidence:rp,repository:Zg}),DIe=d.object({id:It.describe("short-slug, e.g. R9"),statement:It.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(ks).describe("spec outranks pr-description when both state it"),evidence:It.describe("spec: file:line or a section locator. pr-description: the quoted phrase it comes from.")}),NIe=d.object({id:It.describe("short-slug"),statement:It.max(400,"exceeds 400 characters \u2014 state the behaviour, do not paste the code").describe("what the change makes true"),surface:It.describe("METHOD /path, or a component/page name"),evidence:It.describe("file:line from the diff that introduces it"),repository:Zg,satisfies:d.array(It).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)")}),PIe=d.object({id:It.describe("short-slug"),file:It,line:d.number().optional(),claim:EK("shorten it to the one sentence that states the defect, and move the supporting detail into `evidence`"),severity:d.nativeEnum(Qa),evidence:EK("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(Bu),repository:Zg,conflictsWith:d.array(It).optional().describe("requirement ids (from `requirements`) this defect contradicts or leaves unimplemented \u2014 a lower-precedence source (the diff, or the PR description) lost")}),OIe=d.object({name:It,language:d.string().optional(),framework:d.string().optional(),evidence:rp,repository:Zg}),UIe=d.object({dir:It,framework:d.string().optional(),kind:d.nativeEnum(QD),evidence:rp,repository:Zg}),FIe=d.object({from:It,to:It,onDelete:d.nativeEnum(_D),evidence:rp}),MIe=d.object({entity:It,field:It,values:d.array(d.string()),evidence:rp}),LIe=d.object({entities:d.array(d.object({name:It,evidence:rp})),references:d.array(FIe).describe("INBOUND references \u2014 what still points at an entity when it is deleted"),stateFields:d.array(MIe)}),DD=d.object({schemaVersion:d.literal(1),repository:d.object({path:It.describe("absolute repo path"),currentBranch:It,baseBranch:It}),project:d.object({type:d.nativeEnum(Dw),primaryLanguage:It,languages:d.array(d.string()),frameworks:d.array(d.string())}),services:d.array(OIe),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:It.describe("\u2264400 chars")}),endpoints:d.object({new:d.array(TD),modified:d.array(TD),removed:d.array(TD)}),existingTests:d.object({locations:d.array(UIe)}),entityMap:LIe,requirements:d.array(DIe).describe("from a spec (attached or linked) and/or the PR description; empty when neither states a testable obligation"),behaviors:d.array(NIe),findings:d.array(PIe),unexamined:d.array(d.string()).describe("files or areas outside this change you did not open"),summary:It.describe("one paragraph on what this change does and its test-relevant risk")});var GIe=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")}),Kg=(n=>(n.InProcess="in-process",n.Browser="browser",n))(Kg||{}),bK=(s=>(s.Spec="spec",s.PrDescription="pr-description",s.Inferred="inferred",s))(bK||{}),wK=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(GIe).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(Kg).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(bK).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")}),Nw=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 _1e=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 D1e=["stale_test","open_question"],N1e=["low","medium","high","critical"];var IK=String.raw`(?:\[[^\]]*\]|\([^)]*\))`,zIe=String.raw`(?:["'\u201c\u2018\x60]|\*{1,2})?[^\s:"'\u201c\u201d\u2018\u2019\x60*()[\],]+(?:["'\u201d\u2019\x60]|\*{1,2})?`,CK=String.raw`(?:${IK}|${zIe}(?:\s*${IK})?)`,SK=String.raw`(?:\s*:|\s+[\u2014\u2013-])`,U1e=new RegExp(String.raw`^\s*(?:${CK}(?:,\s*${CK})*(?::L?\d+(?:[-\u2013]\d+)?${SK}?|${SK})|\[[^\]\s]+\]|\([^)\s]+\))\s+`);var op=G(require("fs")),nn=G(require("path"));var yo=d.string().trim().min(1),Eo=72,qIe=d.object({repository:yo.optional().describe("owner/repo of the checkout this lint ran in, when the run has several; omit for the working checkout"),tool:d.string(),command:d.string().describe("the exact command you ran, scoped to the changed files"),clean:d.boolean(),notRun:d.string().optional().describe("why no linter checked the files, when none could (SKYR-5827): then `clean` is false and does not hold the tests back"),fixed:d.array(d.string()).optional().describe("files you fixed"),uncovered:d.array(d.string()).describe("changed/new files this linter's own config does not match (wrong extension, wrong directory) \u2014 so `clean` never examined them, even though CI may still execute them. Empty array, not omitted, when every changed/new file IS covered.")});var ND=d.object({schemaVersion:d.literal(1),lint:d.array(qIe).min(1).describe("one entry per checkout this run wrote tests in, each run from that checkout"),fileConventions:d.object({ok:d.boolean(),notes:d.string().optional()}),ciReadiness:d.object({covered:d.boolean().describe("will the repo's CI run these tests?"),notes:d.string().optional(),unrecorded:d.array(d.string()).optional().describe("tests with no record of whether CI runs them: not covered, and not known to be left out")}),dependencies:d.object({added:d.array(d.object({package:d.string(),manifest:d.string(),repository:yo.optional().describe("owner/repo of the manifest's checkout; omit for the working checkout"),reason:yo.optional().describe("why the test must run inside the application's own test environment, so its manifest had to change \u2014 required for every entry")})).describe("every package added to an APPLICATION manifest (an exception, surfaced in the report); never the Testbot test package's own")}),support:d.array(d.object({file:yo,repository:yo.optional().describe("owner/repo of the file's checkout; omit for the working checkout")})).optional().describe("the files the tests need besides themselves (helper modules, page objects, fixtures, snapshots), delivered with them"),commit:d.object({message:yo.refine(e=>e.split(`
|
|
258
|
-
`)[0].length<=Eo,{message:`subject line must be <= ${Eo} chars`})}),pr:d.object({title:yo.max(Eo,`must be <= ${Eo} chars`),body:yo}),ready:d.boolean().describe("a statement of fact: true only if the tests are fit to commit as they stand"),blockers:d.array(d.string()).describe("what blocks the commit \u2014 required non-empty when ready is false"),summary:yo.describe("one paragraph")});function Xg(e){return(e?.blockers??[]).slice(0,3).join("; ")}var Da=G(require("fs")),ip=G(require("path"));var zn="{junit}",Pw=(i=>(i.Junit="junit",i.Trx="trx",i.GoTestJson="go-test-json",i.JestJson="jest-json",i.PlaywrightList="playwright-list",i))(Pw||{}),PD=(t=>(t.Minitest="minitest",t))(PD||{}),kK=d.string().trim().min(1),xu=d.object({cwd:kK.describe('repo-relative directory the command starts in ("." for the root)'),argv:d.array(kK).min(1).describe(`the command as separate arguments, run without a shell; for a junit or trx report an argument or env value holds ${zn}, 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(Pw).describe(`junit (JUnit XML to ${zn}), trx (to ${zn}), jest-json (Jest's --json or Vitest's --reporter=json, --outputFile=${zn}), or go-test-json (go test -json on the command's output)`),reporter:d.nativeEnum(PD).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 sp="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)";var G1e=`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 ${zn} in the reporter's argument or env setting), trx (a TRX file to ${zn}, which every dotnet test writes with its built-in logger), jest-json (Jest's --json --outputFile=${zn}, or Vitest's --reporter=json --outputFile=${zn}: 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 ${zn}: 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 ${zn} itself. A setting the tests or reporter read goes in "env" (RAILS_ENV=test, or PLAYWRIGHT_JUNIT_OUTPUT_FILE=${zn} with playwright test --reporter=junit): the run sets it, so never wrap the command in a shell to set one. The run sets CI=1, as a CI job does: if your own run needed CI unset or set otherwise, give CI that value in "env" (empty when unset). The run replaces ${zn} in argv and env with its report path, executes the command, and reads that report.`;var vo=(r=>(r.ExistingEvidenceSufficient="existing_evidence_sufficient",r.TargetedUnit="targeted_unit",r.RuntimeRequired="runtime_required",r.BlockedPreflight="blocked_preflight",r))(vo||{}),bo=(i=>(i.ExistingEvidence="existing_evidence",i.Unaffected="unaffected",i.ExistingUnit="existing_unit",i.NewUnit="new_unit",i.Runtime="runtime",i))(bo||{}),OD=(n=>(n.Repository="repository",n.Testbot="testbot",n))(OD||{}),UD=(s=>(s.Identified="identified",s.Passed="passed",s.Failed="failed",s))(UD||{}),xr=d.string().trim().min(1),HIe=d.string().regex(/^[a-z0-9][a-z0-9-]*$/,"must be a short lowercase slug").describe("short-slug");var JIe=d.object({id:HIe,source:d.nativeEnum(OD),kind:d.nativeEnum(ua),outcome:d.nativeEnum(UD),summary:xr.max(400).describe("one line: what it shows"),tests:d.array(xr).optional().describe("source repository: the existing tests, as repo-relative paths, optionally path::test-name"),repository:xr.optional().describe("source repository: owner/repo the tests live in, when the run has several checkouts; omit for the working checkout"),command:xr.optional().describe("source testbot: the exact command you ran, as you ran it"),run:xu.optional().describe(`source repository, for tests in ${sp}: 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`)}),WIe=d.object({behaviorId:xr.describe("an id from analyze's behaviors"),mechanism:d.nativeEnum(bo),evidenceIds:d.array(xr).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')}),FD=(s=>(s.Browser="browser",s.RunningApp="running-app",s.Outside="outside",s))(FD||{}),YIe=d.object({behaviorId:d.string().trim().optional().describe("an id from analyze's behaviors, when it is about one"),missing:xr.max(600).describe("the evidence that is required and cannot be obtained in this run"),needs:d.nativeEnum(FD).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)")}),ZIe=d.object({file:xr.describe("the changed file the failure is in"),repository:xr.optional().describe("owner/repo the file is in, when the run has several checkouts; omit for the working checkout"),reason:xr.max(300).describe("what prerequisite the change fails"),evidence:xr.max(400).describe("the error line, quoted")}),KIe=d.object({behaviorId:xr.describe("an id from analyze's behaviors"),reason:xr.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)")}),em=d.object({schemaVersion:d.literal(1),decision:d.nativeEnum(vo),evidence:d.array(JIe).describe("evidence this session found or produced; CI results are the ci-<n> items and are not restated here"),plan:d.array(WIe).describe("how each changed behavior's evidence is obtained"),gaps:d.array(YIe),outOfScope:d.array(KIe).optional().describe("behaviors analyze found that this change neither changes nor states"),blocked:ZIe.optional().describe("only for blocked_preflight"),rationale:xr.max(1200).describe("\u22641200 characters: why this evidence is enough, or what it still lacks \u2014 the scope you chose and why")});function _a(e){let t=Ae(e,"recommend.json");if(!t||!Array.isArray(t.generate)||!Array.isArray(t.maintenance))return;let n=t;return{...n,maintenance:n.maintenance.map(({repository:s,...r})=>({...r,test:r.test.trim().replace(/^\.\//,""),...s?.trim()?{repository:s.trim()}:{}}))}}var jD=".skyramp/staged";function nCe(e){return jn(ZR,e).errors}function rCe(e,t=[]){let{value:n,error:s}=Wt(e,t);if(s)return{errors:[s]};let r=nCe(n);return r.length>0?{errors:r}:{generate:n,errors:[]}}function Ow(e,t=[]){return rCe(e.stdout,t)}function sCe(e){return e.generate.filter(t=>t.type!=="ui").map(t=>t.id)}function VD(e){return e.generate.filter(t=>t.type==="ui").map(t=>t.id)}var Uw={backend:{stage:"generate",cases:sCe,noRecommendCoverage:"recommend.json missing or malformed \u2014 cannot check coverage",noRecommendIntent:"recommend.json missing or malformed \u2014 cannot check intent",uncovered:e=>`recommend case "${e}" is not covered by any generated test`,unknownCovered:e=>`test covers unknown recommend id "${e}"`,unasserted:e=>`case "${e}" has no verified assertion enforcing its expected_observable`,usedCodegen:X4,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:VD,noRecommendCoverage:"recommend.json not found \u2014 cannot check UI coverage",noRecommendIntent:"recommend.json not found \u2014 cannot check UI intent",uncovered:e=>`UI case "${e}" is not covered by any generated UI test`,unknownCovered:e=>`test covers "${e}" which is not a recommend UI case`,unasserted:e=>`UI case "${e}" has no verified assertion enforcing its expected_observable`,usedCodegen:eZ,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."}},IVe=wr("generate-schema",(e,t)=>Ow(t,e.secretValues));function iCe(e){let t=Uw[e];return{name:`${t.stage}-coverage`,verify(n,s){let{generate:r,errors:i}=Ow(s,n.secretValues);if(!r)return An(this.name,i);let o=_a(n);if(!o)return An(this.name,[t.noRecommendCoverage]);let a=new Set(r.tests.flatMap(p=>p.covers)),c=[],u=t.cases(o);for(let p of u)a.has(p)||c.push(t.uncovered(p));let l=new Set(e==="ui"?u:o.generate.map(p=>p.id));for(let p of a)l.has(p)||c.push(t.unknownCovered(p));if(e==="backend"){let p=new Set(r.deferredUi),h=new Set(VD(o));for(let g of h)!p.has(g)&&!a.has(g)&&c.push(`UI case "${g}" is neither covered nor deferred to the UI stage`);for(let g of p)h.has(g)||c.push(`deferredUi lists "${g}" which is not a UI case`)}return c.length===0?{name:this.name,passed:!0}:An(this.name,c)}}}function oCe(e){let t=Uw[e];return{name:`${t.stage}-intent`,verify(n,s){let{generate:r,errors:i}=Ow(s,n.secretValues);if(!r)return An(this.name,i);let o=_a(n);if(!o)return An(this.name,[t.noRecommendIntent]);let{asserted:a,errors:c,badFiles:u}=fCe(r,n.inputs.repositoryPath),l=c.length;for(let h of t.cases(o))a.has(h)||c.push(t.unasserted(h));if(c.length===0)return{name:this.name,passed:!0};let p=An(this.name,c);return l>0&&l===c.length&&u.size>0?{...p,droppable:[...u]}:p}}}function aCe(e){let t=Uw[e];return n=>{if(!n.inputs.skyrampMcp?.command||e==="backend"&&!kD(n))return;let s=ip.join(n.outputsDir,`${t.stage}-stream.ndjson`);if(!(!Da.existsSync(s)||t.usedCodegen(s)))return tZ(s)?t.codegenHint:"Skyramp codegen tools were configured but the MCP server did not connect this session, so they were not available. Hand-authoring was the only option; this is an environment problem, not yours."}}var CVe=iCe("backend"),SVe=oCe("backend"),kVe=aCe("backend");var RK=e=>e.replace(/\s+/g,"");var MD={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"]])MD[e]=MD[t];function cCe(e,t){if(e.includes(wh(t))||RK(e).includes(RK(t)))return!0;let n=t.split(/\r?\n/).map(s=>s.trim()).filter(s=>s&&!/^(\/\/|#|\*|\/\*)/.test(s));return n.length>0&&n.every(s=>e.includes(wh(s)))?!0:pCe(e,t)}var uCe=/\bassert\w*\b|\bexpect\s*\(|\.should\b|\brequire\s*\(/i,lCe=12,dCe=/,\s*\(\s*#|,\s*f?["'`]|\s+#\s|\s+\/\/|\s*\((?:line|lines|at line)\b|\s*,\s*$/i;function pCe(e,t){let n=t.split(/\s*;\s*|\s*\.\.\.\s*|\r?\n/),s=0;for(let r of n){let i=uCe.exec(r);if(!i)continue;let o=r.slice(i.index),a=dCe.exec(o);if(a&&(o=o.slice(0,a.index)),o=wh(o).replace(/[,\s]+$/,""),o.length<lCe||!e.includes(o))return!1;s++}return s>0}function fCe(e,t){let n=new Set,s=[],r=new Set;for(let i of e.tests){let o=ip.resolve(t,i.file);if(!Da.existsSync(o))continue;let a=wh(Da.readFileSync(o,"utf-8"));for(let c of i.assertions??[]){if(!cCe(a,c.evidence)){s.push(`assertion evidence for "${c.case}" not found in ${i.file} \u2014 cite the real assertion line`),r.add(i.file);continue}i.covers.includes(c.case)?n.add(c.case):(s.push(`assertion cites case "${c.case}" not in that test's covers[]`),r.add(i.file))}}return{asserted:n,errors:s,badFiles:r}}var hCe=/\.(spec|test)\.[cm]?[jt]sx?$/i;function BK(e){let t;try{t=Gt([...Zn,"status","--porcelain","--untracked-files=all"],{env:pt(),cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]})}catch{return}let n=r=>/_scaffold/i.test(r)||Ih.test(r),s=[];for(let r of t.split(`
|
|
259
|
-
`)){if(!r.trim()||r.length>1&&r[1]==="D")continue;let i=r.slice(3).trim(),o=i.indexOf(" -> ");if(o!==-1&&(i=i.slice(o+4).trim()),i=i.replace(/^"|"$/g,""),!i)continue;let a=i.replace(/^\.\//,"");a.startsWith(".skyramp/")||!n(a)||s.push(a)}return s}function gCe(e){let t=Uw[e],n=e==="ui";return{name:`${t.stage}-no-litter`,verify(s){let r=BK(s.inputs.repositoryPath);if(r===void 0)return{name:this.name,passed:!0};let i=r.filter(o=>hCe.test(o)===n);return i.length===0?{name:this.name,passed:!0}:An(this.name,[`${t.stage} left files outside .skyramp/ \u2014 move the staged test into .skyramp/staged/ and delete any codegen draft (e.g. *_scaffold.*): ${i.slice(0,6).join(", ")}`])}}}var
|
|
257
|
+
`,u-1),p=Number(c.slice(l+1,u).trim()),h=c.slice(u+1);return{status:Number.isFinite(p)?p:0,body:c.slice(0,l),...h?{redirect:h}:{}}},async runCommand(r,i){let{steps:o,reason:a}=Qc(r);if(!o)return{exitCode:1,output:`${aK}${a}`};let c="";for(let u of o){if(Date.now()>=e)return{exitCode:1,output:"health check time limit reached"};let l=await iK(u,{cwd:i,deadlineMs:Math.min(e,Date.now()+6e4),env:pt(),signal:t});if(c+=`${l.stdout??""}${l.stderr??""}`,l.exitCode!==0)return{exitCode:l.exitCode,output:c}}return{exitCode:0,output:c}}}}function vIe(e){return e?Object.entries(e).flatMap(([t,n])=>["-H",`${t}: ${n}`]):[]}function cK(e){return e.trim().replace(/^\.\//,"").replace(/\/+$/,"")}function bIe(e){if(!e.inputs)return[];let t=Gs(e),n=r=>{let i=typeof r=="string"?r:r?.path??r?.file;return typeof i=="string"&&i.trim()?cK(i):void 0},s=(r,i)=>r?(i??[]).flatMap(o=>{let a=n(o);return a?[{repository:r,path:a}]:[]}):[];return[...s(Si(e.inputs).slug,[...t?.changedFiles??[],...t?.newFiles??[]]),...(t?.relatedChanges??[]).flatMap(r=>s(r.repository,r.changedFiles))]}function wIe(e,t){let n=Ta.resolve(e.inputs.repositoryPath,t.trim()),s=IB(e.inputs,n),r=s&&Ta.relative(s.path,n);return s&&r?{repository:s.slug,path:r.split(Ta.sep).join("/")}:void 0}function _w(e,t={}){let n=t.budgetMs??fIe,s=t.intervalMs??hIe;return{name:"deploy-health",async verify(r,i){if(r.signal?.aborted)return{name:this.name,passed:!1,details:"health check cancelled"};let o=e??Qw(r.deadlineMs??1/0,r.signal,r.inputs.repositoryPath),{deploy:a,errors:c}=Ru(i,r.inputs?.repositoryPath,r.secretValues);if(!a)return{name:this.name,passed:!1,details:c.slice(0,6).join("; ")};if(a.outcome==="bringup-failed")return{name:this.name,passed:!0};if(a.outcome==="change-broke-bringup"){let I=bIe(r),C=(a.suspectFiles??[]).map(cK),w=C.filter(x=>{let S=wIe(r,x);return!!S&&GE(I,S.repository,S.path)});return I.length>0&&w.length===0?{name:this.name,passed:!1,details:`change-broke-bringup claimed, but none of suspectFiles [${C.slice(0,4).join(", ")}] is a file this PR changed \u2014 that is not attributable to the PR. Re-run bring-up; if it still fails for a reason outside the diff, record outcome "bringup-failed" (with bringupError) instead.`}:{name:this.name,passed:!0}}let u=a.health;if(!u)return{name:this.name,passed:!1,details:"health is missing although the app is recorded as up"};let l=yIe(u.headers),p=(I,C=!1)=>({ok:!1,details:I,transient:C}),h=async()=>{if(!kw(u.url,mD(r)))return p(`health url ${u.url} is not the app under test \u2014 this gate probes only loopback, the Test Environment's address or an address the Target's settings give, never an arbitrary destination. Record the URL the deployed app actually answers on.`);let I=await o.httpGet(u.url,u.headers);if("error"in I)return p(`health url ${u.url} unreachable: ${I.error}`,!0);let C=Number(u.status??200);if(I.status!==C)return p(`health url returned ${I.status}, expected ${C}`,!0);if(!I.body.trim())return p("health url returned empty body \u2014 must return data",!0);let w=(u.output??"").trim();if(w){let x=rK(w,I.body);if(!x.ok)return p(`health url ${u.url} no longer answers as recorded \u2014 ${x.why}. Either the app is not answering as it did at deploy time, or health.output is not verbatim: record ONLY the response body, with no commentary appended.`)}return{ok:!0}},g=async()=>{let I=await o.runCommand(u.command,r.inputs.repositoryPath),C=I.output.startsWith(aK);if(I.exitCode!==0)return p(`health command exited ${I.exitCode}: ${I.output.slice(0,200)}`,!C);if(!I.output.trim())return p("health command produced no output",!0);let w=(u.output??"").trim();if(w.length<16)return p(`health command output "${w}" is too thin to be a data check \u2014 the check must return real application data, not a status token`);let x=rK(w,I.output);return x.ok?{ok:!0}:p(`health command did not reproduce its recorded check \u2014 ${x.why}. Either the app is not answering as it did at deploy time, or health.output is not verbatim: record ONLY what the command wrote, with no commentary appended.`)},m;if(u.command&&(l||!u.url))m=g;else{if(u.url&&l)return{name:this.name,passed:!1,details:`health.headers contains a documented placeholder (${Object.entries(u.headers??{}).filter(([,I])=>/<[^>]+>/.test(String(I))).map(([I])=>I).join(", ")}), and this gate RE-EXECUTES the probe \u2014 a placeholder cannot authenticate. Record a health.command instead (a script that fetches its own token and hits the URL); do not put a real credential in the artifact.`};u.url?m=h:u.command&&(m=g)}if(!m)return{name:this.name,passed:!1,details:"health has neither url nor command"};let y=Date.now(),v=y+n,E=await m();for(;!E.ok&&E.transient&&!r.signal?.aborted&&Date.now()+s<v&&(await new Promise((I,C)=>{let w,x=Y=>{clearTimeout(w),r.signal?.removeEventListener("abort",S),Y?C(Y):I()},S=()=>x();if(r.signal?.addEventListener("abort",S,{once:!0}),r.signal?.aborted){x();return}t.sleep?t.sleep(s).then(()=>x(),x):w=setTimeout(()=>x(),s)}),!r.signal?.aborted);)E=await m();if(r.signal?.aborted)return{name:this.name,passed:!1,details:"health check cancelled"};if(E.ok)return{name:this.name,passed:!0};let b=Math.round((Date.now()-y)/1e3);return{name:this.name,passed:!1,details:E.transient&&b>0?`${E.details} (still failing after ${b}s)`:E.details}}}}function kD(e){return uK(e)&&Yg(e).length===0&&SD(e.inputs?.sharedEnvironment).length===0}function uK(e){let t=IIe(e);if(!t&&e.state.stages.deploy?.status!=="passed")return!1;let n=Ae(e,"deploy.json");return n?lK(n):!t}function lK(e){return e?.outcome==="clean"||e?.outcome==="recipe-drift"}function IIe(e){let t=e.state.stages.plan,n=e.state.stages.deploy;return!(e.inputs?.pipeline?e.inputs.pipeline==="two-step":!n)||t?.status!=="passed"?!1:!n||n.updatedAt<=t.updatedAt}async function CIe(e,t,n){let s=new URL(t.url).origin;return(URL.canParse(e.url)?new URL(e.url).origin:e.url)===s?xw(e.url,n):{error:`${e.url} is not on ${s}, where ${t.name} runs`}}async function SIe(e,t,n){let s=$w(e.inputs??{}),r=[];for(let i of t){let o=s.find(l=>l.name===i.component);if(!o){r.push(`revisions names "${i.component}", which is not a shared component listed for a revision check`);continue}let a=await CIe(i,o,n);if("error"in a){r.push(`the revision check of ${o.name} could not be re-run: ${Hs(a.error,e.secretValues??[]).slice(0,200)}`);continue}let c=Bw(o.expectedRevision,{body:i.output}),u=Bw(o.expectedRevision,a);c.observedRevision!==u.observedRevision&&r.push(`the revision check of ${o.name} names ${u.observedRevision??"no commit"} when re-run, but its recorded output names ${c.observedRevision??"no commit"} \u2014 record what the check returned, verbatim, or leave the component out`)}return r}function dK(e,t=1/0,n){return async(s,r)=>{if(!Vr(e))throw new Error("the guarded setup network boundary is unavailable");let i=n&&r?.signal?AbortSignal.any([n,r.signal]):n??r?.signal??void 0,o=await Qw(t,i,e).httpGet(String(s));if("error"in o)throw new Error(o.error);return new Response([204,205,304].includes(o.status)?null:o.body,{status:o.status,headers:o.redirect?{Location:o.redirect}:void 0})}}function pK(e){let t=e.inputs;return t?.setupEvents&&!t.recheck&&En(t)?dK(t.repositoryPath,e.deadlineMs,e.signal):void 0}function fK(e){return{name:"shared-revisions",async verify(t,n){let{deploy:s}=Ru(n,t.inputs?.repositoryPath,t.secretValues),r=await SIe(t,s?.revisions??[],e??pK(t));return r.length?{name:this.name,passed:!1,details:r.join("; ")}:{name:this.name,passed:!0}}}}async function hK(e,t,n){let s=e.inputs?.sharedEnvironment;if(!ID(s))return{};let{deploy:r}=Ru(t,e.inputs.repositoryPath,e.secretValues),i=await YZ(s,r?.revisions??[],n??pK(e),e.secretValues??[]);return Ln(e,np,Hs(i,e.secretValues??[]),[])}function gK(e,t){let{deploy:n,errors:s}=Ru(t,e.inputs?.repositoryPath,e.secretValues),r=n?.health?.headers?{...n,health:{...n.health,headers:Object.fromEntries(Object.keys(n.health.headers).map(a=>[a,"<redacted>"]))}}:n,i=e.secretValues??[],o=r&&kIe(r,Hs(r,i),i.filter(a=>a.length>=Sh));return Ln(e,"deploy",o,s)}function kIe(e,t,n){let s=r=>Lt(r,n);return{...t,teardown:s(e.teardown),...e.baseUrls?{baseUrls:Object.fromEntries(Object.entries(e.baseUrls).map(([r,i])=>[r,s(i)]))}:{},...e.health&&t.health?{health:{...t.health,...e.health.url!==void 0?{url:s(e.health.url)}:{},...e.health.command!==void 0?{command:s(e.health.command)}:{}}}:{},...e.revisions&&t.revisions?{revisions:t.revisions.map((r,i)=>({...r,url:s(e.revisions[i].url)}))}:{}}}var yK=G(require("path"));var _Ie="test-execution-contexts.json";var I1e=10*6e4;function BD(e){let t=Vs(yK.join(e.outputsDir,_Ie));return Array.isArray(t)?t:[]}var xD=(e,t)=>e.file===t.file&&(e.repository??"")===(t.repository??"");function $D(e){return e.filter((t,n)=>!e.slice(n+1).some(s=>xD(t,s)))}var Dw=(r=>(r.RestApi="rest-api",r.Frontend="frontend",r.FullStack="full-stack",r.Other="other",r))(Dw||{}),Qa=(r=>(r.Critical="critical",r.High="high",r.Medium="medium",r.Low="low",r))(Qa||{}),Bu=(s=>(s.Suspected="suspected",s.Latent="latent",s.Refuted="refuted",s))(Bu||{}),QD=(s=>(s.Skyramp="skyramp",s.External="external",s.Unknown="unknown",s))(QD||{}),_D=(r=>(r.Cascade="cascade",r.Restrict="restrict",r.Orphan="orphan",r.Unknown="unknown",r))(_D||{}),ks=(r=>(r.RequirementReference="requirement-reference",r.Spec="spec",r.PrDescription="pr-description",r.CouldBreak="could-break",r))(ks||{}),It=d.string().trim().min(1),rp=It.describe("file:line"),EK=e=>It.refine(t=>t.length<=400,t=>({message:`is ${t.length} characters, over the 400 cap \u2014 ${e}`})),Zg=It.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'),TD=d.object({method:It,path:It,service:d.string().optional(),evidence:rp,repository:Zg}),DIe=d.object({id:It.describe("short-slug, e.g. R9"),statement:It.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(ks).describe("spec outranks pr-description when both state it"),evidence:It.describe("spec: file:line or a section locator. pr-description: the quoted phrase it comes from.")}),NIe=d.object({id:It.describe("short-slug"),statement:It.max(400,"exceeds 400 characters \u2014 state the behaviour, do not paste the code").describe("what the change makes true"),surface:It.describe("METHOD /path, or a component/page name"),evidence:It.describe("file:line from the diff that introduces it"),repository:Zg,satisfies:d.array(It).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)")}),PIe=d.object({id:It.describe("short-slug"),file:It,line:d.number().optional(),claim:EK("shorten it to the one sentence that states the defect, and move the supporting detail into `evidence`"),severity:d.nativeEnum(Qa),evidence:EK("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(Bu),repository:Zg,conflictsWith:d.array(It).optional().describe("requirement ids (from `requirements`) this defect contradicts or leaves unimplemented \u2014 a lower-precedence source (the diff, or the PR description) lost")}),OIe=d.object({name:It,language:d.string().optional(),framework:d.string().optional(),evidence:rp,repository:Zg}),UIe=d.object({dir:It,framework:d.string().optional(),kind:d.nativeEnum(QD),evidence:rp,repository:Zg}),FIe=d.object({from:It,to:It,onDelete:d.nativeEnum(_D),evidence:rp}),MIe=d.object({entity:It,field:It,values:d.array(d.string()),evidence:rp}),LIe=d.object({entities:d.array(d.object({name:It,evidence:rp})),references:d.array(FIe).describe("INBOUND references \u2014 what still points at an entity when it is deleted"),stateFields:d.array(MIe)}),DD=d.object({schemaVersion:d.literal(1),repository:d.object({path:It.describe("absolute repo path"),currentBranch:It,baseBranch:It}),project:d.object({type:d.nativeEnum(Dw),primaryLanguage:It,languages:d.array(d.string()),frameworks:d.array(d.string())}),services:d.array(OIe),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:It.describe("\u2264400 chars")}),endpoints:d.object({new:d.array(TD),modified:d.array(TD),removed:d.array(TD)}),existingTests:d.object({locations:d.array(UIe)}),entityMap:LIe,requirements:d.array(DIe).describe("from a spec (attached or linked) and/or the PR description; empty when neither states a testable obligation"),behaviors:d.array(NIe),findings:d.array(PIe),unexamined:d.array(d.string()).describe("files or areas outside this change you did not open"),summary:It.describe("one paragraph on what this change does and its test-relevant risk")});var GIe=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")}),Kg=(n=>(n.InProcess="in-process",n.Browser="browser",n))(Kg||{}),bK=(s=>(s.Spec="spec",s.PrDescription="pr-description",s.Inferred="inferred",s))(bK||{}),wK=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(GIe).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(Kg).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(bK).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")}),Nw=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 U1e=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 F1e=["stale_test","open_question"],M1e=["low","medium","high","critical"];var IK=String.raw`(?:\[[^\]]*\]|\([^)]*\))`,zIe=String.raw`(?:["'\u201c\u2018\x60]|\*{1,2})?[^\s:"'\u201c\u201d\u2018\u2019\x60*()[\],]+(?:["'\u201d\u2019\x60]|\*{1,2})?`,CK=String.raw`(?:${IK}|${zIe}(?:\s*${IK})?)`,SK=String.raw`(?:\s*:|\s+[\u2014\u2013-])`,V1e=new RegExp(String.raw`^\s*(?:${CK}(?:,\s*${CK})*(?::L?\d+(?:[-\u2013]\d+)?${SK}?|${SK})|\[[^\]\s]+\]|\([^)\s]+\))\s+`);var op=G(require("fs")),nn=G(require("path"));var yo=d.string().trim().min(1),Eo=72,qIe=d.object({repository:yo.optional().describe("owner/repo of the checkout this lint ran in, when the run has several; omit for the working checkout"),tool:d.string(),command:d.string().describe("the exact command you ran, scoped to the changed files"),clean:d.boolean(),notRun:d.string().optional().describe("why no linter checked the files, when none could (SKYR-5827): then `clean` is false and does not hold the tests back"),fixed:d.array(d.string()).optional().describe("files you fixed"),uncovered:d.array(d.string()).describe("changed/new files this linter's own config does not match (wrong extension, wrong directory) \u2014 so `clean` never examined them, even though CI may still execute them. Empty array, not omitted, when every changed/new file IS covered.")});var ND=d.object({schemaVersion:d.literal(1),lint:d.array(qIe).min(1).describe("one entry per checkout this run wrote tests in, each run from that checkout"),fileConventions:d.object({ok:d.boolean(),notes:d.string().optional()}),ciReadiness:d.object({covered:d.boolean().describe("will the repo's CI run these tests?"),notes:d.string().optional(),unrecorded:d.array(d.string()).optional().describe("tests with no record of whether CI runs them: not covered, and not known to be left out")}),dependencies:d.object({added:d.array(d.object({package:d.string(),manifest:d.string(),repository:yo.optional().describe("owner/repo of the manifest's checkout; omit for the working checkout"),reason:yo.optional().describe("why the test must run inside the application's own test environment, so its manifest had to change \u2014 required for every entry")})).describe("every package added to an APPLICATION manifest (an exception, surfaced in the report); never the Testbot test package's own")}),support:d.array(d.object({file:yo,repository:yo.optional().describe("owner/repo of the file's checkout; omit for the working checkout")})).optional().describe("the files the tests need besides themselves (helper modules, page objects, fixtures, snapshots), delivered with them"),commit:d.object({message:yo.refine(e=>e.split(`
|
|
258
|
+
`)[0].length<=Eo,{message:`subject line must be <= ${Eo} chars`})}),pr:d.object({title:yo.max(Eo,`must be <= ${Eo} chars`),body:yo}),ready:d.boolean().describe("a statement of fact: true only if the tests are fit to commit as they stand"),blockers:d.array(d.string()).describe("what blocks the commit \u2014 required non-empty when ready is false"),summary:yo.describe("one paragraph")});function Xg(e){return(e?.blockers??[]).slice(0,3).join("; ")}var Da=G(require("fs")),ip=G(require("path"));var zn="{junit}",Pw=(i=>(i.Junit="junit",i.Trx="trx",i.GoTestJson="go-test-json",i.JestJson="jest-json",i.PlaywrightList="playwright-list",i))(Pw||{}),PD=(t=>(t.Minitest="minitest",t))(PD||{}),kK=d.string().trim().min(1),xu=d.object({cwd:kK.describe('repo-relative directory the command starts in ("." for the root)'),argv:d.array(kK).min(1).describe(`the command as separate arguments, run without a shell; for a junit or trx report an argument or env value holds ${zn}, 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(Pw).describe(`junit (JUnit XML to ${zn}), trx (to ${zn}), jest-json (Jest's --json or Vitest's --reporter=json, --outputFile=${zn}), or go-test-json (go test -json on the command's output)`),reporter:d.nativeEnum(PD).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 sp="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)";var W1e=`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 ${zn} in the reporter's argument or env setting), trx (a TRX file to ${zn}, which every dotnet test writes with its built-in logger), jest-json (Jest's --json --outputFile=${zn}, or Vitest's --reporter=json --outputFile=${zn}: 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 ${zn}: 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 ${zn} itself. A setting the tests or reporter read goes in "env" (RAILS_ENV=test, or PLAYWRIGHT_JUNIT_OUTPUT_FILE=${zn} with playwright test --reporter=junit): the run sets it, so never wrap the command in a shell to set one. The run sets CI=1, as a CI job does: if your own run needed CI unset or set otherwise, give CI that value in "env" (empty when unset). The run replaces ${zn} in argv and env with its report path, executes the command, and reads that report.`;var vo=(r=>(r.ExistingEvidenceSufficient="existing_evidence_sufficient",r.TargetedUnit="targeted_unit",r.RuntimeRequired="runtime_required",r.BlockedPreflight="blocked_preflight",r))(vo||{}),bo=(i=>(i.ExistingEvidence="existing_evidence",i.Unaffected="unaffected",i.ExistingUnit="existing_unit",i.NewUnit="new_unit",i.Runtime="runtime",i))(bo||{}),OD=(n=>(n.Repository="repository",n.Testbot="testbot",n))(OD||{}),UD=(s=>(s.Identified="identified",s.Passed="passed",s.Failed="failed",s))(UD||{}),xr=d.string().trim().min(1),HIe=d.string().regex(/^[a-z0-9][a-z0-9-]*$/,"must be a short lowercase slug").describe("short-slug");var JIe=d.object({id:HIe,source:d.nativeEnum(OD),kind:d.nativeEnum(ua),outcome:d.nativeEnum(UD),summary:xr.max(400).describe("one line: what it shows"),tests:d.array(xr).optional().describe("source repository: the existing tests, as repo-relative paths, optionally path::test-name"),repository:xr.optional().describe("source repository: owner/repo the tests live in, when the run has several checkouts; omit for the working checkout"),command:xr.optional().describe("source testbot: the exact command you ran, as you ran it"),run:xu.optional().describe(`source repository, for tests in ${sp}: 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`)}),WIe=d.object({behaviorId:xr.describe("an id from analyze's behaviors"),mechanism:d.nativeEnum(bo),evidenceIds:d.array(xr).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')}),FD=(s=>(s.Browser="browser",s.RunningApp="running-app",s.Outside="outside",s))(FD||{}),YIe=d.object({behaviorId:d.string().trim().optional().describe("an id from analyze's behaviors, when it is about one"),missing:xr.max(600).describe("the evidence that is required and cannot be obtained in this run"),needs:d.nativeEnum(FD).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)")}),ZIe=d.object({file:xr.describe("the changed file the failure is in"),repository:xr.optional().describe("owner/repo the file is in, when the run has several checkouts; omit for the working checkout"),reason:xr.max(300).describe("what prerequisite the change fails"),evidence:xr.max(400).describe("the error line, quoted")}),KIe=d.object({behaviorId:xr.describe("an id from analyze's behaviors"),reason:xr.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)")}),em=d.object({schemaVersion:d.literal(1),decision:d.nativeEnum(vo),evidence:d.array(JIe).describe("evidence this session found or produced; CI results are the ci-<n> items and are not restated here"),plan:d.array(WIe).describe("how each changed behavior's evidence is obtained"),gaps:d.array(YIe),outOfScope:d.array(KIe).optional().describe("behaviors analyze found that this change neither changes nor states"),blocked:ZIe.optional().describe("only for blocked_preflight"),rationale:xr.max(1200).describe("\u22641200 characters: why this evidence is enough, or what it still lacks \u2014 the scope you chose and why")});function _a(e){let t=Ae(e,"recommend.json");if(!t||!Array.isArray(t.generate)||!Array.isArray(t.maintenance))return;let n=t;return{...n,maintenance:n.maintenance.map(({repository:s,...r})=>({...r,test:r.test.trim().replace(/^\.\//,""),...s?.trim()?{repository:s.trim()}:{}}))}}var jD=".skyramp/staged";function nCe(e){return jn(ZR,e).errors}function rCe(e,t=[]){let{value:n,error:s}=Wt(e,t);if(s)return{errors:[s]};let r=nCe(n);return r.length>0?{errors:r}:{generate:n,errors:[]}}function Ow(e,t=[]){return rCe(e.stdout,t)}function sCe(e){return e.generate.filter(t=>t.type!=="ui").map(t=>t.id)}function VD(e){return e.generate.filter(t=>t.type==="ui").map(t=>t.id)}var Uw={backend:{stage:"generate",cases:sCe,noRecommendCoverage:"recommend.json missing or malformed \u2014 cannot check coverage",noRecommendIntent:"recommend.json missing or malformed \u2014 cannot check intent",uncovered:e=>`recommend case "${e}" is not covered by any generated test`,unknownCovered:e=>`test covers unknown recommend id "${e}"`,unasserted:e=>`case "${e}" has no verified assertion enforcing its expected_observable`,usedCodegen:X4,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:VD,noRecommendCoverage:"recommend.json not found \u2014 cannot check UI coverage",noRecommendIntent:"recommend.json not found \u2014 cannot check UI intent",uncovered:e=>`UI case "${e}" is not covered by any generated UI test`,unknownCovered:e=>`test covers "${e}" which is not a recommend UI case`,unasserted:e=>`UI case "${e}" has no verified assertion enforcing its expected_observable`,usedCodegen:eZ,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."}},BVe=wr("generate-schema",(e,t)=>Ow(t,e.secretValues));function iCe(e){let t=Uw[e];return{name:`${t.stage}-coverage`,verify(n,s){let{generate:r,errors:i}=Ow(s,n.secretValues);if(!r)return An(this.name,i);let o=_a(n);if(!o)return An(this.name,[t.noRecommendCoverage]);let a=new Set(r.tests.flatMap(p=>p.covers)),c=[],u=t.cases(o);for(let p of u)a.has(p)||c.push(t.uncovered(p));let l=new Set(e==="ui"?u:o.generate.map(p=>p.id));for(let p of a)l.has(p)||c.push(t.unknownCovered(p));if(e==="backend"){let p=new Set(r.deferredUi),h=new Set(VD(o));for(let g of h)!p.has(g)&&!a.has(g)&&c.push(`UI case "${g}" is neither covered nor deferred to the UI stage`);for(let g of p)h.has(g)||c.push(`deferredUi lists "${g}" which is not a UI case`)}return c.length===0?{name:this.name,passed:!0}:An(this.name,c)}}}function oCe(e){let t=Uw[e];return{name:`${t.stage}-intent`,verify(n,s){let{generate:r,errors:i}=Ow(s,n.secretValues);if(!r)return An(this.name,i);let o=_a(n);if(!o)return An(this.name,[t.noRecommendIntent]);let{asserted:a,errors:c,badFiles:u}=fCe(r,n.inputs.repositoryPath),l=c.length;for(let h of t.cases(o))a.has(h)||c.push(t.unasserted(h));if(c.length===0)return{name:this.name,passed:!0};let p=An(this.name,c);return l>0&&l===c.length&&u.size>0?{...p,droppable:[...u]}:p}}}function aCe(e){let t=Uw[e];return n=>{if(!n.inputs.skyrampMcp?.command||e==="backend"&&!kD(n))return;let s=ip.join(n.outputsDir,`${t.stage}-stream.ndjson`);if(!(!Da.existsSync(s)||t.usedCodegen(s)))return tZ(s)?t.codegenHint:"Skyramp codegen tools were configured but the MCP server did not connect this session, so they were not available. Hand-authoring was the only option; this is an environment problem, not yours."}}var xVe=iCe("backend"),$Ve=oCe("backend"),TVe=aCe("backend");var RK=e=>e.replace(/\s+/g,"");var MD={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"]])MD[e]=MD[t];function cCe(e,t){if(e.includes(wh(t))||RK(e).includes(RK(t)))return!0;let n=t.split(/\r?\n/).map(s=>s.trim()).filter(s=>s&&!/^(\/\/|#|\*|\/\*)/.test(s));return n.length>0&&n.every(s=>e.includes(wh(s)))?!0:pCe(e,t)}var uCe=/\bassert\w*\b|\bexpect\s*\(|\.should\b|\brequire\s*\(/i,lCe=12,dCe=/,\s*\(\s*#|,\s*f?["'`]|\s+#\s|\s+\/\/|\s*\((?:line|lines|at line)\b|\s*,\s*$/i;function pCe(e,t){let n=t.split(/\s*;\s*|\s*\.\.\.\s*|\r?\n/),s=0;for(let r of n){let i=uCe.exec(r);if(!i)continue;let o=r.slice(i.index),a=dCe.exec(o);if(a&&(o=o.slice(0,a.index)),o=wh(o).replace(/[,\s]+$/,""),o.length<lCe||!e.includes(o))return!1;s++}return s>0}function fCe(e,t){let n=new Set,s=[],r=new Set;for(let i of e.tests){let o=ip.resolve(t,i.file);if(!Da.existsSync(o))continue;let a=wh(Da.readFileSync(o,"utf-8"));for(let c of i.assertions??[]){if(!cCe(a,c.evidence)){s.push(`assertion evidence for "${c.case}" not found in ${i.file} \u2014 cite the real assertion line`),r.add(i.file);continue}i.covers.includes(c.case)?n.add(c.case):(s.push(`assertion cites case "${c.case}" not in that test's covers[]`),r.add(i.file))}}return{asserted:n,errors:s,badFiles:r}}var hCe=/\.(spec|test)\.[cm]?[jt]sx?$/i;function BK(e){let t;try{t=Gt([...Zn,"status","--porcelain","--untracked-files=all"],{env:pt(),cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]})}catch{return}let n=r=>/_scaffold/i.test(r)||Ih.test(r),s=[];for(let r of t.split(`
|
|
259
|
+
`)){if(!r.trim()||r.length>1&&r[1]==="D")continue;let i=r.slice(3).trim(),o=i.indexOf(" -> ");if(o!==-1&&(i=i.slice(o+4).trim()),i=i.replace(/^"|"$/g,""),!i)continue;let a=i.replace(/^\.\//,"");a.startsWith(".skyramp/")||!n(a)||s.push(a)}return s}function gCe(e){let t=Uw[e],n=e==="ui";return{name:`${t.stage}-no-litter`,verify(s){let r=BK(s.inputs.repositoryPath);if(r===void 0)return{name:this.name,passed:!0};let i=r.filter(o=>hCe.test(o)===n);return i.length===0?{name:this.name,passed:!0}:An(this.name,[`${t.stage} left files outside .skyramp/ \u2014 move the staged test into .skyramp/staged/ and delete any codegen draft (e.g. *_scaffold.*): ${i.slice(0,6).join(", ")}`])}}}var QVe=gCe("backend");var yCe="write-stale-updates",ECe={[yCe]:"stale test updates"};var tm=G(require("fs")),$u=G(require("path"));function QK(e){return jn(XR,e).errors}function wCe(e,t=[]){let{value:n,error:s}=Wt(e,t);if(s)return{errors:[s]};let r=QK(n);return r.length>0?{errors:r}:{adapt:n,errors:[]}}var ICe="adapt-scratch",$K=`${ICe}/adapt-result.json`;function _K(e,t){let n=$u.join(e.outputsDir,$K),s;try{s=tm.readFileSync(n,"utf-8")}catch{s=void 0}if(s!==void 0&&(e.secretValues??[]).some(o=>s.includes(o)))return{errors:[`${$K} contains a secret value (token / credential) \u2014 never write it anywhere`]};let r=wCe(t.stdout,e.secretValues);if(r.adapt)return r;let i=s!==void 0?Vs(n):void 0;return i!==void 0&&QK(i).length===0?{adapt:i,errors:[]}:r}var iGe=wr("adapt-schema",_K);function DK(e){return nm(e).map(t=>t.path)}function nm(e){return GD(e)??[]}function GD(e){let t;try{t=Gt([...Zn,"status","--porcelain","-z","--untracked-files=all"],{env:pt(),cwd:e,encoding:"utf-8",maxBuffer:16*1024*1024})}catch{return}let n=t.split("\0"),s=[];for(let r=0;r<n.length;r++){let i=n[r];if(i.length<4)continue;let o=i.slice(0,2);s.push({code:o,path:i.slice(3)}),(o[0]==="R"||o[0]==="C")&&r++}return s}var gGe=2*1024*1024;var zD=(n=>(n.Patch="PATCH",n.Put="PUT",n))(zD||{});var rm=d.lazy(()=>d.union([d.string(),d.number().finite(),d.boolean(),d.null(),d.array(rm),d.record(rm)])),fn=d.string().trim().min(1),PK=d.string().regex(/^[A-Za-z_]\w*$/).optional(),qD=d.number().int().refine(e=>e>=200&&e<300||e>=400&&e<500,"Expected an explicit success or client rejection status").optional(),NK=d.array(fn).min(1).max(20).optional(),CCe=d.object({environmentId:d.string().uuid(),environmentAddress:d.string().url(),targetId:fn.optional(),appOrigin:d.string().url().optional(),persistenceRevision:dh.optional(),offLimits:d.array(fn),bearerTokenEnv:PK,route:d.object({kind:d.literal("persistence")}).strict()}).strict().refine(e=>!e.persistenceRevision||!e.targetId&&!e.appOrigin,"A generated persistence decision cannot include legacy policy lookup fields"),OK=d.array(d.discriminatedUnion("op",[d.object({op:d.literal("create"),collection:fn,body:d.record(rm),uniqueField:fn,expectedStatus:qD,responseIdPath:NK,responseUniqueFieldPath:NK,as:fn}).strict(),d.object({op:d.literal("read"),resource:fn,as:fn,expectedStatus:qD,query:d.record(d.string()).optional()}).strict(),d.object({op:d.literal("update"),resource:fn,method:d.nativeEnum(zD).optional(),expectedStatus:qD,body:d.record(rm),as:fn}).strict(),d.object({op:d.literal("assert"),resource:fn,path:d.array(fn),equals:rm}).strict(),d.object({op:d.literal("assertStatus"),resource:fn,equals:d.number().int().min(200).max(499)}).strict(),d.object({op:d.literal("assertHeader"),resource:fn,name:d.string().regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/),equals:d.string().nullable()}).strict()])).min(1).refine(e=>e.some(t=>t.op==="assert"||t.op==="assertStatus"||t.op==="assertHeader"),"A runnable test must retain a planned assertion"),Fw=d.object({name:fn,bearerTokenEnv:PK,steps:OK.describe("ordered objects with op: create (collection, body, uniqueField, as; optional expectedStatus, responseIdPath, responseUniqueFieldPath), read (resource, as; optional expectedStatus, query), update (resource, body, as; optional expectedStatus, method PUT or PATCH), assert (resource, path, equals), assertStatus (resource, equals), or assertHeader (resource, name, equals). Resource names an earlier request alias and paths are arrays of JSON keys")}).strict(),UK=d.union([d.object({name:fn,definition:CCe,steps:OK}).strict(),d.object({name:fn,restriction:fn,sourceAsset:d.object({path:fn.regex(/^(?!\/)(?!.*(?:^|\/)\.\.?(?:\/|$))[^\\]+\.source$/),sha256:d.string().regex(/^[a-f0-9]{64}$/)}).strict()}).strict()]),HD=`"use strict";
|
|
260
260
|
const spec = `,JD=`;
|
|
261
261
|
let runtime;
|
|
262
262
|
try { runtime = require("@skyramp/testbot-core/dist/shared-environment-test.cjs"); } catch {}
|
|
263
263
|
if (runtime && typeof runtime.sharedEnvironmentTest === "function") runtime.sharedEnvironmentTest(spec, __filename);
|
|
264
264
|
else require("node:test").test(spec.name, () => { throw new Error("required shared-environment guard runtime is unavailable"); });
|
|
265
265
|
`;function sm(e){return HD+JSON.stringify(UK.parse(e),null,2)+JD}function wo(e){if(e.includes("\r")){if(/(?:^|[^\r])\n|\r(?!\n)/.test(e))return;e=e.replace(/\r\n/g,`
|
|
266
|
-
`)}if(!(!e.startsWith(HD)||!e.endsWith(JD)))try{let t=UK.safeParse(JSON.parse(e.slice(HD.length,-JD.length)));return t.success&&sm(t.data)===e?t.data:void 0}catch{return}}var im=d.string().trim().min(1),SCe=d.object({cwd:im.describe(`directory the command starts in, relative to the test's checkout ("." for its root)`),argv:d.array(im).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")}),FK=d.object({file:im.describe("a file of the test's checkout, relative to its root"),line:im.describe("a line of that file, quoted exactly from where its command starts to its end")}),MK=d.object({collected:d.boolean().describe("whether the repo's CI runs this test as it is"),steps:d.array(FK).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:SCe.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"),needs:d.array(im).optional().describe("what the test needs running outside its own process (the app, a database, another service), one entry each; omit when it needs none"),starts:d.array(FK).optional().describe("when collected and it needs any: the line that starts each of those in the CI job that runs it, in a file of ci.steps")});var pe=d.string().trim().min(1),DCe=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},NCe=d.preprocess(DCe,d.object({id:pe.describe(`its requirement's id plus a letter, e.g. "R1a", "AC-3a"`),clause:pe.describe("one testable part of the requirement"),expected:pe.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(Zs).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)")})),jK=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:pe.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`}),PCe=d.object({id:pe.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:pe,source:d.nativeEnum(ks).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:pe.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:pe.regex(io).describe("the key of another uploaded document stating the same obligation"),says:pe.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 PR description or the item defers this criterion to a later change, the words that defer it, copied exactly; give it no clauses. Never for words that only say what this change covers, or only because no changed file holds its code"),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(jK).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(NCe)}),VK=(r=>(r.ServerError="server-error",r.DataLost="data-lost",r.FinalState="final-state",r.DerivedValues="derived-values",r))(VK||{}),OCe=d.object({id:pe.describe('e.g. "F1"'),file:pe,line:d.number().optional(),claim:pe.describe("the defect, in one sentence"),severity:d.nativeEnum(Qa),evidence:pe.describe("the code line, or the probe request and response, that shows it"),conflictsWith:d.array(pe).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(VK).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)")}),UCe=d.object({id:pe.describe('e.g. "Q1"'),question:pe.describe("what is unsettled, as a question the PR author can answer"),readings:d.array(pe).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(jK).optional().describe("when sources of the same rank disagree on it: each of them")}),FCe=d.object({id:pe.describe('unique, a short kebab-case name for what the case checks, e.g. "ship-twice-409"'),type:d.nativeEnum(Zs).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:pe.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:pe.describe("what the test does"),expected:pe.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")}),MCe=d.object({test:pe.describe("existing test file"),action:d.nativeEnum(Qi),reason:pe,mutates:d.boolean().optional().describe("true when the maintained test changes state"),clauses:d.array(pe).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")}),LK=d.array(EE).optional(),LCe=d.object({components:d.preprocess(e=>LK.safeParse(e).success?e:void 0,LK).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(zr).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(Wf)).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:pe,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:MR.optional()}),WGe=d.object({schemaVersion:d.literal(1),requirements:d.array(PCe),findings:d.array(OCe),cases:d.array(FCe).describe("a second test for a clause, and one case per finding that fails on this branch"),questions:d.array(UCe).optional().describe("behaviours the change leaves unsettled; no case asserts any of them"),maintenance:d.array(MCe),journeys:d.array(wK).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:pe,why:pe})).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"),browserSuites:d.array(d.object({repository:pe.optional().describe("owner/repo, for a checkout other than the working one"),path:pe.describe("the folder its browser tests are in, relative to that checkout"),framework:pe.describe("what runs them")})).default([]).describe("the repository's own browser test suites; empty when it has none"),unplannedComponents:d.array(d.object({components:d.array(pe).min(1).describe("changed components, as the change lists them"),why:pe})).optional().describe("changed components no clause reaches, and why their change needs no test; several may share one reason"),triage:em.optional().describe("the validation triage decision, made before the app is started; its behaviorIds are clause ids"),app:LCe.optional().describe("omit when no app was needed or none was started"),summary:pe.describe("one paragraph: what the change does and where the risk is")});var om=(n=>(n.Backend="backend",n.Ui="ui",n))(om||{});var Xr=(r=>(r.Added="added",r.Updated="updated",r.Deleted="deleted",r.Unchanged="unchanged",r))(Xr||{}),jCe=d.object({file:pe.describe("repo-relative path; in another repo of the change, that repo's directory name then its path"),kind:d.nativeEnum(om),change:d.nativeEnum(Xr).describe("added: a file you created; updated / deleted / unchanged: an existing test"),covers:d.array(d.string()).describe("the plan case or maintenance clause ids this file tests, each with its own result under result.cases"),guardedDelivery:Fw.optional().describe("for a new test that calls the shared app: supply equivalent ordered HTTP requests and assertions for its one test function (which can check several planned cases) in a .test.cjs file that node --test runs. The destination package must declare the exact released version of @skyramp/testbot-core used by this run. Use only CI variable names for credentials. Omit when the setup or steps cannot preserve the test; Testbot retains the source without a CI entry. The entry reaches only the deployed Test Environment and makes no request to Testbot: name nothing under ci.needs for it. Where CI does not collect it yet, still give ci.steps, ci.runner and a ci.list whose output does not name it"),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:pe.describe("a stated requirement or clause id"),line:pe.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"),failsOnBase:d.array(d.object({test:pe.describe("its name, as its framework reports it"),failure:pe.describe("the failure message it gave on the base branch")})).optional().describe("for a file that was there before this run, which you left as it was or only added tests to: the tests already in it that fail here and fail the same way on the base branch, so this change did not make them fail. Never a test you wrote or changed"),result:d.object({started:d.boolean().optional().describe("with exit null: true if this file's test command started (it was interrupted or timed out), false if it never started. Left out, Testbot counts it as possibly started, with its cleanup unknown"),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:pe,status:d.nativeEnum(er),environmentRestriction:pe.optional().describe("for a skipped case whose test you wrote and could not run here: what this run lacks to run it (a build, a service, a database, a browser, an app). The test is still written; Testbot reports the case as not run. Never set it on a case that ran or for a time limit."),runtimeTargets:lh.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:BE.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")}).refine(e=>!e.environmentRestriction||e.status==="skip"&&!e.runtimeTargets?.length,{message:"an environment-restricted case must be skipped and have no runtimeTargets"})).describe("one entry per covered case, from the runner's own output; a case you could not run here has none: record it as skipped with its environmentRestriction"),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:pe,evidence:pe})).optional().describe("per covered case, the assertion line that checks its expected outcome"),functions:d.array(d.object({name:pe.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(pe).describe("the plan case or maintenance clause ids it checks"),testProblem:BE.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, or an existing test to maintain that lists clauses: each test function in it and the plan case or maintenance clause 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(uh).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:pe.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:MK.optional().describe("for a file you added or updated: whether the repo's CI will run it, and how you know"),run:xu.optional().describe(`for a file in ${sp}, 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 ${zn}, or go-test-json); Testbot runs it before write ends and re-runs the tests with it`)}),VCe=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},GCe=d.preprocess(VCe,d.object({description:pe.describe("what is wrong and how to reproduce it: endpoint or page, input, what you got vs what was expected"),severity:d.nativeEnum(Qa).optional(),sourceFile:d.string().optional().describe("the app file at fault"),sourceLine:d.number().optional(),tests:d.array(pe).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(pe).optional().describe("the plan's requirement or clause ids it violates")})),YGe=d.object({schemaVersion:d.literal(1),tests:d.array(jCe),notWritten:d.array(d.object({case:pe,reason:pe,coveredBy:d.object({file:pe.describe("the test file, relative to the working checkout; prefix a related checkout as for tests[].file"),name:pe.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; also a maintenance clause that no function of its existing test asserts (it stays unproven)"),journeys:d.array(Nw).optional().describe("one entry per planned user journey: the browser test that walks it end to end"),checks:d.array(d.object({command:d.string().describe("the exact command you ran on your files, with their paths, as run from the repository root: cd <folder> && first when you ran it in a folder"),source:d.string().describe("where the repository runs or configures this check: path:line, then its words copied exactly"),clean:d.boolean().describe("false when it still reports something in your files, or stopped before checking any")})).optional().describe("each lint, format or type check the repository runs or keeps a config for on files like yours; Testbot runs each again"),dependenciesAdded:d.array(d.object({package:pe,manifest:pe.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:pe.optional().describe("owner/repo of the manifest's checkout; omit for the repo under test"),reason:pe.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(pe).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"),importerRun:xu.optional().describe("when you changed a module other test files import: the repository's own command for running its test files (its runner, its config, its folder); Testbot loads the files that reach your change with it and reports each; omit when you changed none"),commit:d.object({message:pe.describe("subject line at most 72 characters, following the repository's commit-message checks"),prTitle:pe.describe("at most 72 characters, following the repository's PR-title checks"),prBody:pe.describe("what the tests cover and what they found")}),report:d.object({summary:pe.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(GCe).describe("every defect the tests found"),nextSteps:d.array(d.string()),noTests:d.array(d.object({repository:pe,reason:pe.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 ZGe={added:"place",updated:"update",deleted:"delete",unchanged:"verify"};function es(e){return e.rel!==""&&!e.rel.startsWith("..")&&!nn.isAbsolute(e.rel)}function vn(e,t,n=DK){let s=t.map(l=>({name:CB(l),root:nn.resolve(l.path),slug:l.slug})),r=new Map([...s].reverse().map(l=>[l.name,l])),i=t.length?[{real:qE(nn.resolve(e))},...s.map(l=>({...l,real:qE(l.root)}))].sort((l,p)=>p.real.length-l.real.length):[],o=new Map,a=l=>o.get(l)??o.set(l,new Set(n(l))).get(l),c=l=>{let p=nn.resolve(e,l),h=op.existsSync(p),g=C=>({root:e,rel:Ci(e,l),ambiguous:C,exists:h});if(!t.length)return g(!1);let m=!1,y=l.replace(/^\.\//,""),v=y.split("/")[0],E=r.get(v);if(E){let C=y.slice(v.length+1),w=op.existsSync(nn.join(E.root,C)),x=!op.existsSync(nn.join(e,v))||!h&&w;if(w&&h&&nn.join(E.root,C)!==p){let S=a(E.root).has(Ci(E.root,C)),Y=a(e).has(Ci(e,l));S&&!Y?x=!0:S===Y&&(m=!0)}if(x)return{root:E.root,rel:Ci(E.root,C),repository:E.slug,dir:E.name,ambiguous:m,exists:w}}if(!h&&!nn.isAbsolute(y)){let C=s.filter(w=>op.existsSync(nn.join(w.root,y)));if(C.length===1){let[w]=C;return{root:w.root,rel:Ci(w.root,y),repository:w.slug,dir:w.name,ambiguous:m,exists:!0}}}let b=nn.join(qE(nn.dirname(p)),nn.basename(p)),I=i.find(C=>es({rel:nn.relative(C.real,b)}));return I?"slug"in I?{root:I.root,rel:nn.relative(I.real,b),repository:I.slug,dir:I.name,ambiguous:m,exists:h}:{...g(m),rel:nn.relative(I.real,b)}:g(m)},u=new Map;return l=>u.get(l)??u.set(l,c(l)).get(l)}var HK=(s=>(s.Requirement="requirement",s.PrDescription="pr_description",s.Code="code",s))(HK||{}),Qn=d.string().trim().min(1),HCe=d.object({expectation:Qn.max(300).describe("the behavior this assertion pins, in words"),source:d.nativeEnum(HK),expected:Qn.max(200).describe("the exact value or outcome asserted, as the test asserts it")}),JCe=d.object({file:Qn.describe("path of the NEW test file you wrote, relative to its repository"),repository:Qn.optional().describe("owner/repo the file lives in, when the run has several checkouts; omit for the working checkout"),framework:Qn.describe("the framework the repository runs this file with: pytest, jest, vitest, node-test, or the name of any other"),run:xu.optional().describe(`for ${sp}: how the run executes only the tests in names, with the repository's own runner writing JUnit XML to {junit}`),covers:d.array(Qn).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(Qn).min(1).describe("the test functions/cases in the file that provide evidence for that behavior, as the framework names them"),assertions:d.array(HCe).min(1)}),am=(n=>(n.Updated="updated",n.Deleted="deleted",n))(am||{}),qK=300,WCe=d.object({file:Qn.describe("path of the EXISTING test file you updated or deleted, relative to its repository"),repository:Qn.optional().describe("owner/repo the file lives in, when the run has several checkouts; omit for the working checkout"),change:d.nativeEnum(am),staleBecause:d.object({requirement:Qn.describe("a stated requirement or clause id"),line:Qn.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"),reason:d.preprocess(e=>typeof e=="string"?e.trim().slice(0,qK):e,Qn.max(qK)).describe("what the change deliberately altered that made the test wrong")}),WD=d.object({schemaVersion:d.literal(1),tests:d.array(JCe),maintained:d.array(WCe).optional().describe("existing tests the change made stale that you updated or deleted; omit when there were none"),defectsNotTested:d.array(d.object({id:Qn,reason:Qn.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(Nw).optional().describe("one entry per planned user journey: the in-process test that walks it end to end"),journeysNotWritten:d.array(d.object({journey:Qn,missing:Qn.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:Qn.optional().describe("the commit message for your tests: a subject line of at most 72 characters, then what they cover")});var Na=G(require("path"));var hze={"application/pdf":"PDF","text/csv":"CSV","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX"};var YD=e=>new Map((e??[]).flatMap(t=>t.file?[[Xc(t.key),t.file.name]]:[])),YCe=10*1024*1024,WK=e=>e?.mediaType==="application/vnd.openxmlformats-officedocument.wordprocessingml.document"||e?.mediaType==="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",YK=(e,t)=>Na.join(Na.dirname(e),`${Na.basename(e,Na.extname(e))}${t}`),ZK=e=>YK(e,".extracted.txt");var ZCe=e=>YK(e,".quotes.txt");function KK(e){return WK(e.file)?ZK(e.path):e.file?.mediaType==="application/pdf"?ZCe(e.path):e.path}var e6=G(require("fs"));var t6=2*1024*1024;function n6(e){let t=[];for(let n of e??[])if(n.state==="read")try{t.push({item:n,text:e6.readFileSync(KK(n),"utf-8")})}catch{}return t}var cm=6,KCe=/[\p{L}\p{N}]+/gu,XCe=new RegExp("(?<=\\p{Ll})(?=\\p{Lu})|(?<=\\p{Lu})(?=\\p{Lu}\\p{Ll})","u");function ZD(e){let t=[];for(let n of e.matchAll(KCe)){let s=n.index;for(let r of n[0].split(XCe))t.push({word:r.toLowerCase(),start:s,end:s+r.length}),s+=r.length}return t}var r6=(e,t)=>e.slice(t,t+cm).map(n=>n.word).join(" ");function XK(e){let t=ZD(e),n=new Set;for(let s=0;s+cm<=t.length;s++)n.add(r6(t,s));return n}function s6(e,t=[]){let n=new Set(t.flatMap(s=>[...XK(s)]));return n6(e).map(({item:s,text:r})=>{let i=s.source==="other"?r:r.slice(r.indexOf(`
|
|
267
|
-
`)+1||r.length),o=XK(i);for(let a of n)o.delete(a);return{name:lz(s.key,YD([s])),key:s.key,runs:o,words:ZD(i).map(a=>a.word)}})}var
|
|
266
|
+
`)}if(!(!e.startsWith(HD)||!e.endsWith(JD)))try{let t=UK.safeParse(JSON.parse(e.slice(HD.length,-JD.length)));return t.success&&sm(t.data)===e?t.data:void 0}catch{return}}var im=d.string().trim().min(1),SCe=d.object({cwd:im.describe(`directory the command starts in, relative to the test's checkout ("." for its root)`),argv:d.array(im).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")}),FK=d.object({file:im.describe("a file of the test's checkout, relative to its root"),line:im.describe("a line of that file, quoted exactly from where its command starts to its end")}),MK=d.object({collected:d.boolean().describe("whether the repo's CI runs this test as it is"),steps:d.array(FK).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:SCe.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"),needs:d.array(im).optional().describe("what the test needs running outside its own process (the app, a database, another service), one entry each; omit when it needs none"),starts:d.array(FK).optional().describe("when collected and it needs any: the line that starts each of those in the CI job that runs it, in a file of ci.steps")});var pe=d.string().trim().min(1),DCe=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},NCe=d.preprocess(DCe,d.object({id:pe.describe(`its requirement's id plus a letter, e.g. "R1a", "AC-3a"`),clause:pe.describe("one testable part of the requirement"),expected:pe.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(Zs).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)")})),jK=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:pe.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`}),PCe=d.object({id:pe.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:pe,source:d.nativeEnum(ks).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:pe.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:pe.regex(io).describe("the key of another uploaded document stating the same obligation"),says:pe.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 PR description or the item defers this criterion to a later change, the words that defer it, copied exactly; give it no clauses. Never for words that only say what this change covers, or only because no changed file holds its code"),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(jK).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(NCe)}),VK=(r=>(r.ServerError="server-error",r.DataLost="data-lost",r.FinalState="final-state",r.DerivedValues="derived-values",r))(VK||{}),OCe=d.object({id:pe.describe('e.g. "F1"'),file:pe,line:d.number().optional(),claim:pe.describe("the defect, in one sentence"),severity:d.nativeEnum(Qa),evidence:pe.describe("the code line, or the probe request and response, that shows it"),conflictsWith:d.array(pe).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(VK).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)")}),UCe=d.object({id:pe.describe('e.g. "Q1"'),question:pe.describe("what is unsettled, as a question the PR author can answer"),readings:d.array(pe).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(jK).optional().describe("when sources of the same rank disagree on it: each of them")}),FCe=d.object({id:pe.describe('unique, a short kebab-case name for what the case checks, e.g. "ship-twice-409"'),type:d.nativeEnum(Zs).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:pe.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:pe.describe("what the test does"),expected:pe.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")}),MCe=d.object({test:pe.describe("existing test file"),action:d.nativeEnum(Qi),reason:pe,mutates:d.boolean().optional().describe("true when the maintained test changes state"),clauses:d.array(pe).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")}),LK=d.array(EE).optional(),LCe=d.object({components:d.preprocess(e=>LK.safeParse(e).success?e:void 0,LK).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(zr).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(Wf)).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:pe,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:MR.optional()}),eze=d.object({schemaVersion:d.literal(1),requirements:d.array(PCe),findings:d.array(OCe),cases:d.array(FCe).describe("a second test for a clause, and one case per finding that fails on this branch"),questions:d.array(UCe).optional().describe("behaviours the change leaves unsettled; no case asserts any of them"),maintenance:d.array(MCe),journeys:d.array(wK).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:pe,why:pe})).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"),browserSuites:d.array(d.object({repository:pe.optional().describe("owner/repo, for a checkout other than the working one"),path:pe.describe("the folder its browser tests are in, relative to that checkout"),framework:pe.describe("what runs them")})).default([]).describe("the repository's own browser test suites; empty when it has none"),unplannedComponents:d.array(d.object({components:d.array(pe).min(1).describe("changed components, as the change lists them"),why:pe})).optional().describe("changed components no clause reaches, and why their change needs no test; several may share one reason"),triage:em.optional().describe("the validation triage decision, made before the app is started; its behaviorIds are clause ids"),app:LCe.optional().describe("omit when no app was needed or none was started"),summary:pe.describe("one paragraph: what the change does and where the risk is")});var om=(n=>(n.Backend="backend",n.Ui="ui",n))(om||{});var Xr=(r=>(r.Added="added",r.Updated="updated",r.Deleted="deleted",r.Unchanged="unchanged",r))(Xr||{}),jCe=d.object({file:pe.describe("repo-relative path; in another repo of the change, that repo's directory name then its path"),kind:d.nativeEnum(om),change:d.nativeEnum(Xr).describe("added: a file you created; updated / deleted / unchanged: an existing test"),covers:d.array(d.string()).describe("the plan case or maintenance clause ids this file tests, each with its own result under result.cases"),guardedDelivery:Fw.optional().describe("for a new test that calls the shared app: supply equivalent ordered HTTP requests and assertions for its one test function (which can check several planned cases) in a .test.cjs file that node --test runs. The destination package must declare the exact released version of @skyramp/testbot-core used by this run. Use only CI variable names for credentials. Omit when the setup or steps cannot preserve the test; Testbot retains the source without a CI entry. The entry reaches only the deployed Test Environment and makes no request to Testbot: name nothing under ci.needs for it. Where CI does not collect it yet, still give ci.steps, ci.runner and a ci.list whose output does not name it"),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:pe.describe("a stated requirement or clause id"),line:pe.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"),failsOnBase:d.array(d.object({test:pe.describe("its name, as its framework reports it"),failure:pe.describe("the failure message it gave on the base branch")})).optional().describe("for a file that was there before this run, which you left as it was or only added tests to: the tests already in it that fail here and fail the same way on the base branch, so this change did not make them fail. Never a test you wrote or changed"),result:d.object({started:d.boolean().optional().describe("with exit null: true if this file's test command started (it was interrupted or timed out), false if it never started. Left out, Testbot counts it as possibly started, with its cleanup unknown"),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:pe,status:d.nativeEnum(er),environmentRestriction:pe.optional().describe("for a skipped case whose test you wrote and could not run here: what this run lacks to run it (a build, a service, a database, a browser, an app). The test is still written; Testbot reports the case as not run. Never set it on a case that ran or for a time limit."),runtimeTargets:lh.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:BE.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")}).refine(e=>!e.environmentRestriction||e.status==="skip"&&!e.runtimeTargets?.length,{message:"an environment-restricted case must be skipped and have no runtimeTargets"})).describe("one entry per covered case, from the runner's own output; a case you could not run here has none: record it as skipped with its environmentRestriction"),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:pe,evidence:pe})).optional().describe("per covered case, the assertion line that checks its expected outcome"),functions:d.array(d.object({name:pe.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(pe).describe("the plan case or maintenance clause ids it checks"),testProblem:BE.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, or an existing test to maintain that lists clauses: each test function in it and the plan case or maintenance clause 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(uh).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:pe.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:MK.optional().describe("for a file you added or updated: whether the repo's CI will run it, and how you know"),run:xu.optional().describe(`for a file in ${sp}, 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 ${zn}, or go-test-json); Testbot runs it before write ends and re-runs the tests with it`)}),VCe=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},GCe=d.preprocess(VCe,d.object({description:pe.describe("what is wrong and how to reproduce it: endpoint or page, input, what you got vs what was expected"),severity:d.nativeEnum(Qa).optional(),sourceFile:d.string().optional().describe("the app file at fault"),sourceLine:d.number().optional(),tests:d.array(pe).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(pe).optional().describe("the plan's requirement or clause ids it violates")})),tze=d.object({schemaVersion:d.literal(1),tests:d.array(jCe),notWritten:d.array(d.object({case:pe,reason:pe,coveredBy:d.object({file:pe.describe("the test file, relative to the working checkout; prefix a related checkout as for tests[].file"),name:pe.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; also a maintenance clause that no function of its existing test asserts (it stays unproven)"),journeys:d.array(Nw).optional().describe("one entry per planned user journey: the browser test that walks it end to end"),checks:d.array(d.object({command:d.string().describe("the exact command you ran on your files, with their paths, as run from the repository root: cd <folder> && first when you ran it in a folder"),source:d.string().describe("where the repository runs or configures this check: path:line, then its words copied exactly"),clean:d.boolean().describe("false when it still reports something in your files, or stopped before checking any")})).optional().describe("each lint, format or type check the repository runs or keeps a config for on files like yours; Testbot runs each again"),dependenciesAdded:d.array(d.object({package:pe,manifest:pe.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:pe.optional().describe("owner/repo of the manifest's checkout; omit for the repo under test"),reason:pe.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(pe).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"),importerRun:xu.optional().describe("when you changed a module other test files import: the repository's own command for running its test files (its runner, its config, its folder); Testbot loads the files that reach your change with it and reports each; omit when you changed none"),commit:d.object({message:pe.describe("subject line at most 72 characters, following the repository's commit-message checks"),prTitle:pe.describe("at most 72 characters, following the repository's PR-title checks"),prBody:pe.describe("what the tests cover and what they found")}),report:d.object({summary:pe.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(GCe).describe("every defect the tests found"),nextSteps:d.array(d.string()),noTests:d.array(d.object({repository:pe,reason:pe.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 nze={added:"place",updated:"update",deleted:"delete",unchanged:"verify"};function es(e){return e.rel!==""&&!e.rel.startsWith("..")&&!nn.isAbsolute(e.rel)}function vn(e,t,n=DK){let s=t.map(l=>({name:CB(l),root:nn.resolve(l.path),slug:l.slug})),r=new Map([...s].reverse().map(l=>[l.name,l])),i=t.length?[{real:qE(nn.resolve(e))},...s.map(l=>({...l,real:qE(l.root)}))].sort((l,p)=>p.real.length-l.real.length):[],o=new Map,a=l=>o.get(l)??o.set(l,new Set(n(l))).get(l),c=l=>{let p=nn.resolve(e,l),h=op.existsSync(p),g=C=>({root:e,rel:Ci(e,l),ambiguous:C,exists:h});if(!t.length)return g(!1);let m=!1,y=l.replace(/^\.\//,""),v=y.split("/")[0],E=r.get(v);if(E){let C=y.slice(v.length+1),w=op.existsSync(nn.join(E.root,C)),x=!op.existsSync(nn.join(e,v))||!h&&w;if(w&&h&&nn.join(E.root,C)!==p){let S=a(E.root).has(Ci(E.root,C)),Y=a(e).has(Ci(e,l));S&&!Y?x=!0:S===Y&&(m=!0)}if(x)return{root:E.root,rel:Ci(E.root,C),repository:E.slug,dir:E.name,ambiguous:m,exists:w}}if(!h&&!nn.isAbsolute(y)){let C=s.filter(w=>op.existsSync(nn.join(w.root,y)));if(C.length===1){let[w]=C;return{root:w.root,rel:Ci(w.root,y),repository:w.slug,dir:w.name,ambiguous:m,exists:!0}}}let b=nn.join(qE(nn.dirname(p)),nn.basename(p)),I=i.find(C=>es({rel:nn.relative(C.real,b)}));return I?"slug"in I?{root:I.root,rel:nn.relative(I.real,b),repository:I.slug,dir:I.name,ambiguous:m,exists:h}:{...g(m),rel:nn.relative(I.real,b)}:g(m)},u=new Map;return l=>u.get(l)??u.set(l,c(l)).get(l)}var HK=(s=>(s.Requirement="requirement",s.PrDescription="pr_description",s.Code="code",s))(HK||{}),Qn=d.string().trim().min(1),HCe=d.object({expectation:Qn.max(300).describe("the behavior this assertion pins, in words"),source:d.nativeEnum(HK),expected:Qn.max(200).describe("the exact value or outcome asserted, as the test asserts it")}),JCe=d.object({file:Qn.describe("path of the NEW test file you wrote, relative to its repository"),repository:Qn.optional().describe("owner/repo the file lives in, when the run has several checkouts; omit for the working checkout"),framework:Qn.describe("the framework the repository runs this file with: pytest, jest, vitest, node-test, or the name of any other"),run:xu.optional().describe(`for ${sp}: how the run executes only the tests in names, with the repository's own runner writing JUnit XML to {junit}`),covers:d.array(Qn).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(Qn).min(1).describe("the test functions/cases in the file that provide evidence for that behavior, as the framework names them"),assertions:d.array(HCe).min(1)}),am=(n=>(n.Updated="updated",n.Deleted="deleted",n))(am||{}),qK=300,WCe=d.object({file:Qn.describe("path of the EXISTING test file you updated or deleted, relative to its repository"),repository:Qn.optional().describe("owner/repo the file lives in, when the run has several checkouts; omit for the working checkout"),change:d.nativeEnum(am),staleBecause:d.object({requirement:Qn.describe("a stated requirement or clause id"),line:Qn.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"),reason:d.preprocess(e=>typeof e=="string"?e.trim().slice(0,qK):e,Qn.max(qK)).describe("what the change deliberately altered that made the test wrong")}),WD=d.object({schemaVersion:d.literal(1),tests:d.array(JCe),maintained:d.array(WCe).optional().describe("existing tests the change made stale that you updated or deleted; omit when there were none"),defectsNotTested:d.array(d.object({id:Qn,reason:Qn.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(Nw).optional().describe("one entry per planned user journey: the in-process test that walks it end to end"),journeysNotWritten:d.array(d.object({journey:Qn,missing:Qn.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:Qn.optional().describe("the commit message for your tests: a subject line of at most 72 characters, then what they cover")});var Na=G(require("path"));var Eze={"application/pdf":"PDF","text/csv":"CSV","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX"};var YD=e=>new Map((e??[]).flatMap(t=>t.file?[[Xc(t.key),t.file.name]]:[])),YCe=10*1024*1024,WK=e=>e?.mediaType==="application/vnd.openxmlformats-officedocument.wordprocessingml.document"||e?.mediaType==="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",YK=(e,t)=>Na.join(Na.dirname(e),`${Na.basename(e,Na.extname(e))}${t}`),ZK=e=>YK(e,".extracted.txt");var ZCe=e=>YK(e,".quotes.txt");function KK(e){return WK(e.file)?ZK(e.path):e.file?.mediaType==="application/pdf"?ZCe(e.path):e.path}var e6=G(require("fs"));var t6=2*1024*1024;function n6(e){let t=[];for(let n of e??[])if(n.state==="read")try{t.push({item:n,text:e6.readFileSync(KK(n),"utf-8")})}catch{}return t}var cm=6,KCe=/[\p{L}\p{N}]+/gu,XCe=new RegExp("(?<=\\p{Ll})(?=\\p{Lu})|(?<=\\p{Lu})(?=\\p{Lu}\\p{Ll})","u");function ZD(e){let t=[];for(let n of e.matchAll(KCe)){let s=n.index;for(let r of n[0].split(XCe))t.push({word:r.toLowerCase(),start:s,end:s+r.length}),s+=r.length}return t}var r6=(e,t)=>e.slice(t,t+cm).map(n=>n.word).join(" ");function XK(e){let t=ZD(e),n=new Set;for(let s=0;s+cm<=t.length;s++)n.add(r6(t,s));return n}function s6(e,t=[]){let n=new Set(t.flatMap(s=>[...XK(s)]));return n6(e).map(({item:s,text:r})=>{let i=s.source==="other"?r:r.slice(r.indexOf(`
|
|
267
|
+
`)+1||r.length),o=XK(i);for(let a of n)o.delete(a);return{name:lz(s.key,YD([s])),key:s.key,runs:o,words:ZD(i).map(a=>a.word)}})}var Ize=cm/2;var eSe=e=>e.criteria.size?`${e.text.name} ${[...e.criteria].sort((t,n)=>t-n).map(t=>`AC${t}`).join(", ")}`:e.text.name,tSe=new RegExp("(?<![\\p{L}\\p{N}])\\p{L}[\\p{L}\\p{N}+.-]*:\\/\\/(?:[^\\s\"'`<>|\\u2018\\u2019\\u201C\\u201D\\u3000-\\u303F\\uFF01-\\uFF0F\\uFF1A-\\uFF20]|<[\\p{L}\\p{N}_-]+>)*(?:[^\\s\"'`<>|\\u2018\\u2019\\u201C\\u201D\\u3000-\\u303F\\uFF01-\\uFF0F\\uFF1A-\\uFF20.,;:!?)\\]]|<[\\p{L}\\p{N}_-]+>)","gu");function nSe(e){let t=[...e.matchAll(tSe)].map(s=>({start:s.index,end:s.index+s[0].length})),n=[[]];for(let s of ZD(e))t.some(r=>s.start>=r.start&&s.start<r.end)?n.at(-1).length&&n.push([]):n.at(-1).push(s);return n}function rSe(e,t){if(t.length===0)return[];let n=[];for(let s of nSe(e))for(let r=0;r+cm<=s.length;r++){let i=r6(s,r),o=t.find(p=>p.runs.has(i));if(!o)continue;let a=s[r].start,c=s[r+cm-1].end,u=o.criteria?.get(i)??[],l=n.at(-1);if(l&&a<=l.end){if(l.end=Math.max(l.end,c),l.text===o)for(let p of u)l.criteria.add(p)}else n.push({start:a,end:c,text:o,criteria:new Set(u)})}return n.map(s=>({start:s.start,end:s.end,name:eSe(s)}))}function ap(e,t,n=!1){let s=e;for(let r of rSe(e,t).reverse()){let i=s.slice(0,r.start).trimEnd(),o=i===""||/[.!?\n]$/.test(s.slice(0,r.start).replace(/[ \t]+$/,"")),c=n&&(o||/[:;—–-]$/.test(i))&&/^\s+[\p{L}\d]/u.test(s.slice(r.end))?`${o?"The":"the"} case (see ${r.name})`:`(see ${r.name})`;s=`${s.slice(0,r.start)}${c}${s.slice(r.end)}`}return s}function sSe(e,t,n){for(let s=t+1;s<e.length;s++){let r=e[s];if(r==="\\")s++;else{if(r===n)return s+1;if(r===`
|
|
268
268
|
`&&n!=="`")return s}}return e.length}function iSe(e,t){let n=e.lastIndexOf(`
|
|
269
269
|
`,t-1)+1;if(e.slice(n,t).trim()!=="")return!1;let s=e.slice(0,n).trimEnd();return s===""||s.endsWith(":")}function oSe(e){let t=[],n=r=>(e.indexOf(`
|
|
270
|
-
`,r)+1||e.length+1)-1,s=0;for(;s<e.length;){let r=e[s],i=e[s+1],o=s+1;if(r==="/"&&i==="*")o=e.indexOf("*/",s+2)<0?e.length:e.indexOf("*/",s+2)+2,t.push({start:s,end:o});else if(r==="/"&&i==="/"&&!/[:\w]/.test(e[s-1]??"")||r==="#"&&/^\s?$/.test(e[s-1]??"")&&!/[!{[]/.test(i??""))o=n(s),t.push({start:s,end:o});else if((r==='"'||r==="'")&&e.startsWith(r.repeat(3),s)){let a=e.indexOf(r.repeat(3),s+3);o=a<0?e.length:a+3,iSe(e,s)&&t.push({start:s,end:o})}else(r==='"'||r==="'"||r==="`")&&(o=sSe(e,s,r));s=o}return t}var aSe=/\b(?:test|it|describe|context|suite|scenario|specify|Run|DisplayName)(?:\.\w+)*(?:\.each\s*(?:\((?:[^()]|\([^()]*\))*\)|`[^`]*`))?\s*\(\s*("(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`)/g;function cSe(e,t){return[...e.matchAll(aSe)].flatMap(n=>{if(t.some(r=>n.index>=r.start&&n.index<r.end))return[];let s=n.index+n[0].length;return[{start:s-n[1].length,end:s}]})}function Tu(e,t){if(t.length===0)return{content:e,cleaned:!1};let n=oSe(e),s=[];for(let a of n){let c=e.slice(a.start,a.end),u=ap(c,t);u!==c&&s.push({...a,text:u})}let r=cSe(e,n),i=new Set(r.map(a=>e.slice(a.start+1,a.end-1)));for(let a of r){let c=e[a.start],u=e.slice(a.start+1,a.end-1),l=ap(u,t);if(l===u)continue;let p=l;for(let h=2;i.has(p);h++)p=`${l} (${h})`;i.add(p),s.push({...a,text:`${c}${p}${c}`})}let o=e;for(let a of s.sort((c,u)=>u.start-c.start))o=`${o.slice(0,a.start)}${a.text}${o.slice(a.end)}`;return{content:o,cleaned:o!==e}}var
|
|
270
|
+
`,r)+1||e.length+1)-1,s=0;for(;s<e.length;){let r=e[s],i=e[s+1],o=s+1;if(r==="/"&&i==="*")o=e.indexOf("*/",s+2)<0?e.length:e.indexOf("*/",s+2)+2,t.push({start:s,end:o});else if(r==="/"&&i==="/"&&!/[:\w]/.test(e[s-1]??"")||r==="#"&&/^\s?$/.test(e[s-1]??"")&&!/[!{[]/.test(i??""))o=n(s),t.push({start:s,end:o});else if((r==='"'||r==="'")&&e.startsWith(r.repeat(3),s)){let a=e.indexOf(r.repeat(3),s+3);o=a<0?e.length:a+3,iSe(e,s)&&t.push({start:s,end:o})}else(r==='"'||r==="'"||r==="`")&&(o=sSe(e,s,r));s=o}return t}var aSe=/\b(?:test|it|describe|context|suite|scenario|specify|Run|DisplayName)(?:\.\w+)*(?:\.each\s*(?:\((?:[^()]|\([^()]*\))*\)|`[^`]*`))?\s*\(\s*("(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`)/g;function cSe(e,t){return[...e.matchAll(aSe)].flatMap(n=>{if(t.some(r=>n.index>=r.start&&n.index<r.end))return[];let s=n.index+n[0].length;return[{start:s-n[1].length,end:s}]})}function Tu(e,t){if(t.length===0)return{content:e,cleaned:!1};let n=oSe(e),s=[];for(let a of n){let c=e.slice(a.start,a.end),u=ap(c,t);u!==c&&s.push({...a,text:u})}let r=cSe(e,n),i=new Set(r.map(a=>e.slice(a.start+1,a.end-1)));for(let a of r){let c=e[a.start],u=e.slice(a.start+1,a.end-1),l=ap(u,t);if(l===u)continue;let p=l;for(let h=2;i.has(p);h++)p=`${l} (${h})`;i.add(p),s.push({...a,text:`${c}${p}${c}`})}let o=e;for(let a of s.sort((c,u)=>u.start-c.start))o=`${o.slice(0,a.start)}${a.text}${o.slice(a.end)}`;return{content:o,cleaned:o!==e}}var Gze=new Set(["requirement-reference","spec","pr-description"]);var um="generate-unit.json";function hSe(e){let{value:t,error:n}=Wt(e);if(n)return{errors:[n]};let{value:s,errors:r}=jn(WD,t);return r.length?{errors:r}:{output:s,errors:[]}}function gSe(e){return hSe(e.stdout)}var Sqe=wr("generate-unit-schema",(e,t)=>gSe(t));var Mw=String.raw`(?:node:)?(?:http|https|http2|net|tls|dgram)`,kqe=[[/\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+["']${Mw}["']|\bimport\s+["']${Mw}["']|require\(\s*["']${Mw}["']\s*\)|\bimport\(\s*["']${Mw}["']\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 Hqe=new Set(["targeted_unit","existing_evidence_sufficient"]);var bSe="triage.json";var aHe=new Set(["existing_evidence","unaffected","existing_unit","new_unit","runtime"]),cHe={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 wSe(e){let{value:t,error:n}=Wt(e);if(n)return{errors:[n]};let{value:s,errors:r}=jn(em,t);return r.length?{errors:r}:{triage:s,errors:[]}}function ISe(e){return wSe(e.stdout)}var uHe=wr("triage-schema",(e,t)=>ISe(t));function CSe(e){let t=e.inputs?.pipeline;return t?e.state.stages[t==="two-step"?"plan":"triage"]:e.state.stages.triage??e.state.stages.plan}function KD(e){if(CSe(e)?.status==="passed")return Vs(d6.join(e.outputsDir,bSe))}function XD(e){if(!mw(e))return eK(CD(e.inputs,Ae(e,`${np}.json`),KD(e)?.sutRequired))}var lHe=new Set(["deploy","recommend","generate","generate-ui","adapt","generate-unit","native-run","finalize","deliver"]);On();On();function p6(e,t){return t?`<!-- skyramp-testbot-run: ${t} -->
|
|
271
271
|
${e}`:e}var h6=600,jw=300;function f6(e){return typeof e=="string"?e.trim():e instanceof Buffer?e.toString("utf-8").trim():""}function kSe(e){let t=e,n=(typeof t?.message=="string"?t.message:String(e)).trim(),s=[f6(t?.stderr),f6(t?.stdout)].filter(Boolean);return s.length?[n.split(`
|
|
272
272
|
`)[0],...s].join(`
|
|
273
273
|
`):n}function g6(e,t,n,s=0){let r=e.join(t);if(r.length<=n)return r;let[i="",...o]=e;if(!o.length)return`${i.slice(0,n-1)}\u2026`;let a=i.length<=s?i:i.slice(0,Math.floor(n/3)),c=n-a.length-t.length-1;return`${a}${t}\u2026${o.join(t).slice(-c)}`}function m6(e,t){return g6(e.trim().split(`
|
|
@@ -289,19 +289,19 @@ ${n}`}function T6(e){let t=[],n=!1;for(let s of e.split(`
|
|
|
289
289
|
`))/^\s*signed-off-by:/i.test(s)?n=!0:n&&s.trim()===""&&t.at(-1)?.trim()===""||(t.push(s),n=!1);return t.join(`
|
|
290
290
|
`).replace(/\s+$/,"")}function tN(e){let t=/\b(claude|anthropic)\b/i;return e.split(`
|
|
291
291
|
`).filter(s=>{let r=s.trim();return!(/^co-authored-by:/i.test(r)&&t.test(r))&&!(/^[^\w\s]*\s*generated (?:with|by) /i.test(r)&&t.test(r))}).join(`
|
|
292
|
-
`).replace(/\s+$/,"")}var qw="Skyramp-Pull-Request",lp="Skyramp-Delivery-Base",nN="Skyramp-Tested-Revision",rN="Skyramp-Delivery-Run";var
|
|
292
|
+
`).replace(/\s+$/,"")}var qw="Skyramp-Pull-Request",lp="Skyramp-Delivery-Base",nN="Skyramp-Tested-Revision",rN="Skyramp-Delivery-Run";var jHe=["%H","%P","%an","%ae","%ce",`%(trailers:key=${qw},valueonly,separator=%x2C)`,"%s",`%(trailers:key=${lp},valueonly,separator=%x2C)`,`%(trailers:key=${nN},valueonly,separator=%x2C)`,`%(trailers:key=${rN},valueonly,separator=%x2C)`];function sN(e,t){let n=e(["log","-1","--format=%B"]);if(!n.includes(`${qw}:`)&&!n.includes(`${lp}:`))return;let s=n.split(`
|
|
293
293
|
`).filter(o=>!o.startsWith(`${lp}:`)).join(`
|
|
294
294
|
`).trimEnd(),r=t?`${s}
|
|
295
295
|
${lp}: ${t}`:s;e(["log","-1","--format=%(trailers:key=Signed-off-by,valueonly)"]).split(`
|
|
296
|
-
`).some(o=>o.trim().toLowerCase()===`${co} <${da}>`.toLowerCase())&&(r=zw(r,{name:co,email:da})),e(["-c",`user.name=${co}`,"-c",`user.email=${da}`,"commit","--amend","--allow-empty","-m",r])}var Fa=G(require("fs")),mN=G(require("path"));function Zt(e){let t=Math.max(0,...(e.match(/`+/g)??[]).map(r=>r.length)),n="`".repeat(t+1),s=e.startsWith("`")||e.endsWith("`")?" ":"";return`${n}${s}${e}${s}${n}`}var rI=G(require("fs")),qt=G(require("path"));var
|
|
296
|
+
`).some(o=>o.trim().toLowerCase()===`${co} <${da}>`.toLowerCase())&&(r=zw(r,{name:co,email:da})),e(["-c",`user.name=${co}`,"-c",`user.email=${da}`,"commit","--amend","--allow-empty","-m",r])}var Fa=G(require("fs")),mN=G(require("path"));function Zt(e){let t=Math.max(0,...(e.match(/`+/g)??[]).map(r=>r.length)),n="`".repeat(t+1),s=e.startsWith("`")||e.endsWith("`")?" ":"";return`${n}${s}${e}${s}${n}`}var rI=G(require("fs")),qt=G(require("path"));var BJe=[...Gl,"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 Io=G(mx());var oN=require("child_process"),dp=G(require("fs")),D6=G(require("os")),Hw=G(require("path"));var eke={onPath:e=>(0,oN.spawnSync)("sh",["-c",`command -v ${e}`],{stdio:"ignore"}).status===0,run:(e,t)=>(0,oN.spawnSync)(e[0],e.slice(1),{cwd:t,stdio:"ignore",timeout:6e4}).status??1},fm={cleanup:()=>{}},tke=new Set(["pnpm","yarn"]);function aN(e,t=D6.tmpdir(),n=eke,s=uD(e)){if(process.platform==="win32")return fm;try{if(Vr(e)||!tke.has(s)||n.onPath(s)||!n.onPath("corepack"))return fm;dp.mkdirSync(t,{recursive:!0});let r=dp.mkdtempSync(Hw.join(t,"testbot-pm-")),i=()=>dp.rmSync(r,{recursive:!0,force:!0});return n.run(["corepack","enable","--install-directory",r,s],e)!==0?(i(),fm):{dir:r,cleanup:i}}catch{return fm}}function N6(e,t=process.env){return e.dir?{...t,PATH:[e.dir,t.PATH].filter(Boolean).join(Hw.delimiter)}:t}var iWe={jest:"jest",vitest:"vitest"};var cke=[["target","surefire-reports"],["target","failsafe-reports"],["build","test-results"]],uYe=new Set(cke.map(([e])=>e));var lYe=["jest","vitest","npm-test","playwright"];var dke="ci-collect";var CYe=5*6e4;function Jw(e,t){let n=new Set(t.tests.map(s=>s.file));return(Ae(e,`${dke}.json`)?.checks??[]).filter(s=>n.has(s.file))}function cN(e){let t=Ae(e,"write.json");if(!Array.isArray(t?.tests))return new Set;let n=new Set(t.tests.filter(s=>s.change==="added").map(s=>s.file));return new Set(Jw(e,t).filter(s=>s.verdict==="unprovisioned"&&n.has(s.file)).map(s=>s.file))}var rn=G(require("node:fs")),Kt=G(require("node:path")),Zw=require("node:child_process");var Ww=G(require("fs")),ts=G(require("path")),pke={lf:`
|
|
297
297
|
`,crlf:`\r
|
|
298
298
|
`,cr:"\r"},fke=5*1024*1024,O6=e=>e.replace(/[.+^$()|\\/{}[\]*?]/g,"\\$&");function hke(e,t){let n=0;for(let s=t;s<e.length;s++)if(e[s]==="\\")s++;else if(e[s]==="{")n++;else if(e[s]==="}"&&--n===0)return s;return-1}function gke(e){let t=[],n=0,s="";for(let r=0;r<e.length;r++){let i=e[r];if(i==="\\"){s+=i+(e[++r]??"");continue}i==="{"&&n++,i==="}"&&n--,i===","&&!n?(t.push(s),s=""):s+=i}return[...t,s]}function uN(e){let t="";for(let n=0;n<e.length;n++){let s=e[n];if(s==="\\")t+=O6(e[++n]??"\\");else if(s==="*"&&e[n+1]==="*"){let r=(n===0||e[n-1]==="/")&&e[n+2]==="/";t+=r?"(?:.*/)?":".*",n+=r?2:1}else if(s==="*")t+="[^/]*";else if(s==="?")t+="[^/]";else if(s==="["){let r=e.indexOf("]",n+2);if(r<0||e.slice(n,r).includes("/"))t+="\\[";else{let i=e.slice(n+1,r);t+=`[${i.replace(/^!/,"^").replace(/\\(?!\])/g,"\\\\")}]`,n=r}}else if(s==="{"){let r=hke(e,n),i=r<0?"":e.slice(n+1,r),o=/^(-?\d+)\.\.(-?\d+)$/.exec(i),a=gke(i);if(o){let[c,u]=[Number(o[1]),Number(o[2])].sort((l,p)=>l-p);t+=`(?:${Array.from({length:Math.min(u-c+1,1e4)},(l,p)=>String(c+p)).join("|")})`,n=r}else a.length>1?(t+=`(?:${a.map(uN).join("|")})`,n=r):t+="\\{"}else t+=O6(s)}return t}function mke(e){return e.includes("/")?new RegExp(`^${uN(e.replace(/^\//,""))}$`):new RegExp(`^(?:.*/)?${uN(e)}$`)}function Ake(e){let t={root:!1,sections:[]},n;for(let s of e.split(/\r\n|\r|\n/)){let r=s.trim();if(!r||r.startsWith("#")||r.startsWith(";"))continue;let i=/^\[(.+)\]$/.exec(r);if(i){n={matches:mke(i[1]),props:{}},t.sections.push(n);continue}let o=r.indexOf("=");if(o<0)continue;let a=r.slice(0,o).trim().toLowerCase(),c=r.slice(o+1).trim().toLowerCase();n?n.props[a]=c:a==="root"&&(t.root=c==="true")}return t}function yke(e,t,n){let s=[];for(let i=ts.dirname(t);;i=ts.dirname(i)){let o=n(i);if(o&&s.unshift({dir:i,config:o}),o?.root||i===e||i===ts.dirname(i))break}let r={};for(let{dir:i,config:o}of s){let a=ts.relative(i,t).split(ts.sep).join("/");for(let c of o.sections)c.matches.test(a)&&Object.assign(r,c.props)}return Object.fromEntries(Object.entries(r).filter(([,i])=>i!=="unset"))}function Eke(e,t){let n=e.startsWith("#!"),s=t.end_of_line?pke[t.end_of_line]:void 0,r=s&&!(n&&s!==`
|
|
299
299
|
`)?s:void 0,i=r?e.replace(/\r\n|\r|\n/g,r):e;return t.insert_final_newline==="true"&&i.length&&!/[\r\n]$/.test(i)&&(i+=r??/\r\n|\r|\n/.exec(i)?.[0]??`
|
|
300
|
-
`),i}function pp(e,t,n){if(n.length>fke||n.includes(0))return n;let s=ts.resolve(e),r=yke(s,ts.resolve(s,t),i=>{try{return Ake(Ww.readFileSync(ts.join(i,".editorconfig"),"utf-8"))}catch{return}});return Buffer.from(Eke(n.toString("latin1"),r),"latin1")}var Du=G(require("node:fs")),Nu=G(require("node:path"));function lN(e,t){let n=Nu.relative(e,t);try{let s=Du.lstatSync(t);if(s.isSymbolicLink())return"test entry is a symlink";if(!s.isFile())return"test entry is not a regular file";let r=Du.realpathSync(e),i=Du.realpathSync(t),o=Nu.relative(r,i);return!o||o.startsWith("..")||Nu.isAbsolute(o)?`test entry's real path is outside the checkout (${o})`:o!==n?`test entry's real path is ${o}, not ${n}, after canonicalisation`:void 0}catch(s){return s.code==="ENOENT"?`test entry is missing: no file is at ${n} in the checkout`:`test entry cannot be read: ${hp(s,e)}`}}function fp(e,t){let n=lN(e,t);if(n)return n;try{return Du.readFileSync(t)}catch(s){return`test entry cannot be read: ${hp(s,e)}`}}function hp(e,t){return(e instanceof Error?e.message:String(e)).split(t+Nu.sep).join("")}function vke(e){return Ae(e,`${W_}.json`)?.guardUnavailable===!0}function U6(e){let t=Ae(e,"recommend.json"),n=Ae(e,`${W_}.json`),s=new Map(vke(e)?(t?.generate??[]).map(({id:r})=>[r,hw]):[]);for(let{id:r,reason:i}of t?.withheld??[])s.has(r)||s.set(r,`off-limits execution (${i??"environment policy"})`);if(n?.browserWithheld)for(let r of t?.generate??[])r.type==="ui"&&!s.has(r.id)&&s.set(r.id,"the shared-environment browser guard is unavailable");return s}function F6(e,t){let n=new Set((e.covers??[]).flatMap(s=>{let r=t.get(s);return r?[r]:[]}));return n.size?`environment restriction: ${[...n].join("; ")}`:void 0}function wke(e){return!!e.guardedDelivery||!!e.context?.some(t=>t.safety?.route==="persistence")}function gp(e,t){let n=e.inputs.sharedEnvironment?.environmentAddress;return!!n&&(t.result?.cases??[]).some(s=>s.runtimeTargets?.some(r=>tu(n,r)))}function gm(e,t,n=so().version){if(!En(e.inputs))return[];let s=e.inputs.sharedEnvironment,r=s?.environmentAddress,i=Ae(e,eB),o=mz.safeParse(i),a=o.success&&o.data.environmentId===s?.environmentId&&o.data.environmentAddress===r?o.data:void 0,c=Az.safeParse(i),u=c.success?fh(c.data.refusal):o.success?fh("changed"):fh("unavailable"),l=U6(e),p=new Map(Jw(e,t).map(E=>[E.file,E.verdict])),h=$D(BD(e)),g=Ae(e,"recommend.json"),m=new Map((g?.generate??[]).map(({id:E,target:b})=>[E,b])),y=vn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),v=new Map;for(let E of t.tests){if(E.change==="deleted")continue;let b=y(E.file);if(!es(b)||lo(b.rel))continue;let I=uo(e.inputs,b.repository);if("error"in I)continue;let C=I.source,w=Kt.resolve(C.path,b.rel),x=F6(E,l)??Ike(h,b),S=wke(E),Y=gp(e,E),ue;if(!x&&!Y&&!S){if(!w.endsWith(".test.cjs"))continue;try{if(!dN(C.path,w))continue;ue=wo(rn.readFileSync(w,"utf8"))}catch{continue}if(!ue||"restriction"in ue)continue}let J=(E.covers??[]).flatMap(Ot=>{let ut=m.get(Ot)?.match(/^(GET|HEAD|OPTIONS|POST|PUT|PATCH|DELETE)\s+(\S+?)[,;]?(?:\s|$)/i);return!ut||!r?[]:ut[2].startsWith("/")||tu(r,ut[2])?[{method:ut[1].toUpperCase(),route:ut[2]}]:[]}),be=$ke(e,C.path,b.rel);if(!x&&E.change!=="added"&&(be===!1||be===void 0&&!e.inputs.deliver))continue;let Me=Ot=>`${E.file}: shared-environment delivery is blocked: ${Ot}`,Ge={repository:C.slug,file:b.rel,sourceAsset:`${b.rel}.source`},ke=fp(C.path,w);if(typeof ke=="string"){v.set(w,{record:Ge,source:C,original:Buffer.alloc(0),problems:[Me(`${ke} (planGuardedDelivery)`)]});continue}if(E.change!=="added"&&Xs(e,C.path,b.rel)){x&&(Ge.reason=x,v.set(w,{record:Ge,source:C,original:ke,problems:[]}));continue}if(be===!1||E.change!=="added"&&be!==!0){v.set(w,{record:Ge,source:C,original:ke,problems:[Me(be===!1?"the file changes an existing test; retain the assertions in a new file":"cannot prove whether the shared test already exists; use a host-pinned checkout")]});continue}if(ue??=wo(ke.toString("utf8")),!x&&ue&&"restriction"in ue)continue;let X,z=Fw.safeParse(E.guardedDelivery),Je=a&&s?{environmentId:a.environmentId,environmentAddress:a.environmentAddress,persistenceRevision:a.revision,offLimits:s.offLimits??[],route:{kind:"persistence"}}:void 0,at=`environment restriction: persistence permission was not confirmed at generation: ${u}`;if(x)X=x;else if(S&&!Je)X=at;else if(!z.success||!Je)X="no guarded HTTP representation preserves the test's assertions";else if(!E.covers?.length||(E.functions?.length??1)!==1)X="guarded HTTP delivery requires one test function";else if(!/\.test\.cjs$/.test(b.rel)||!Rke(E.ci))X="the test has no compatible Node CI entry";else if(!E.ci?.collected&&p.get(E.file)!=="not-collected")X="Testbot could not confirm that the repo's CI leaves it out, and only node --test can run the entry";else if(!Bke(C.path,w,n))X=`the CI package does not declare @skyramp/testbot-core ${n}, the released guarded runtime the entry needs`;else{let{steps:Ot}=z.data,ut=Je.offLimits.length?q_(e.inputs.skyrampMcp,Je.offLimits):void 0,Dn=new Map,Ct=Ot.flatMap(vt=>{if(vt.op==="create"){let se=Cke(Je.environmentAddress,vt.collection);return se&&Dn.set(vt.as,se),[{method:"POST",url:se,child:!1}]}if(vt.op!=="read"&&vt.op!=="update")return[];let Oe=Dn.get(vt.resource);return Oe&&Dn.set(vt.as,Oe),[{method:vt.op==="read"?"GET":vt.method??"PATCH",url:Oe,child:!0}]});Ct.some(({url:vt})=>!vt)?X="the guarded HTTP steps name an unknown resource or a collection outside the Test Environment":ut&&s&&Ct.some(({url:vt,child:Oe})=>!Oe&&lZ(vt.href,s,ut))?X="the guarded HTTP steps name an off-limits collection":J.length&&!J.some(({method:vt,route:Oe})=>Ct.some(se=>se.url&&se.method===vt&&Ske(Je.environmentAddress,se.url,se.child,Oe)))&&(X="the guarded HTTP steps do not represent the planned HTTP operation")}let sn;if(X)Ge.reason=X;else if(z.success&&Je){let{bearerTokenEnv:Ot,...ut}=z.data;sn={...ut,definition:{...Je,...Ot?{bearerTokenEnv:Ot}:{}}},Ge.entry=b.rel}let Et=Kt.resolve(C.path,Ge.sourceAsset),wn=Kw(Et)&&!hm(C.path,Et,ke)?[Me("the inert source asset path already contains different bytes")]:[];v.set(w,{record:Ge,source:C,original:ke,spec:sn,problems:wn})}return[...v.values()]}function Ike(e,t){return e.find(n=>xD(n,{file:t.rel,repository:t.repository}))?.environmentRestriction}function Cke(e,t){try{let n=new URL(t,`${e.replace(/\/$/,"")}/`);return!n.search&&!n.hash&&!n.username&&!n.password&&!/[\\]|%(?:2f|5c|2e|25)/i.test(t)&&tu(e,n.href)?n:void 0}catch{return}}function Ske(e,t,n,s){try{let r=new URL(s,t.origin),i=s.startsWith("/")&&!s.startsWith("//")&&!tu(e,r.href)?new URL(s.slice(1),`${e.replace(/\/$/,"")}/`):r;if(!tu(e,i.href))return!1;let o=t.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");if(!n)return a===o;if(!a.startsWith(`${o}/`))return!1;let c=decodeURIComponent(a.slice(o.length+1));return/^(:[\w-]+|\{[^/{}]+\}|<[^/<>]+>)$/.test(c)}catch{return!1}}function kke(e){return!!e&&/^(?:node|node:test|node\s+(?:.*\s)?--test(?:\s.*)?)$/i.test(e.trim())}function Rke(e){return e?.collected===!1||!!e?.collected&&kke(e.runner)}function dN(e,t){let n=rn.realpathSync(e);return rn.lstatSync(t).isFile()&&rn.realpathSync(t)===Kt.join(n,Kt.relative(e,t))}function hm(e,t,n){try{return dN(e,t)&&rn.readFileSync(t).equals(n)}catch{return!1}}function Kw(e){try{return rn.lstatSync(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Bke(e,t,n){if(n==="unknown")return!1;for(let s=Kt.dirname(t);;s=Kt.dirname(s)){let r=Kt.join(s,"package.json");if(Kw(r))try{if(!dN(e,r))return!1;let i=JSON.parse(rn.readFileSync(r,"utf-8"));return(i.devDependencies?.["@skyramp/testbot-core"]??i.dependencies?.["@skyramp/testbot-core"])===n}catch{return!1}if(s===e)return!1}}function xke(e){let t=Ae(e,"write.json");return t?gm(e,t):[]}function M6(e,t=xke(e),n=[],s=[]){return t.flatMap(({record:r,source:i,original:o,spec:a,problems:c})=>{if(c.length)return c;let u=Kt.join(i.path,r.sourceAsset),l=Kt.join(i.path,r.file),p=`reading ${r.file}`;try{let h=fp(i.path,l);if(typeof h=="string")return[`${r.file}: ${h} (writeGuardedDeliveryFiles)`];if(!h.equals(o))return[`${r.file}: native source changed before guarded delivery`];p=`preparing ${r.sourceAsset}`;let g=Tu(o.toString("utf-8"),n).content;if(ki(g,e.secretValues??[])!==g)return[`${r.file}: the retained source contains a credential`];let m=pp(i.path,r.sourceAsset,Buffer.from(g));if(p=`writing ${r.sourceAsset}`,Kw(u)){if(!hm(i.path,u,o)&&!hm(i.path,u,m))return[`${r.file}: the inert source asset path already contains different bytes`];hm(i.path,u,m)||(s.push(()=>rn.writeFileSync(u,o)),rn.writeFileSync(u,m))}else rn.writeFileSync(u,m,{flag:"wx"}),s.push(()=>rn.rmSync(u,{force:!0}));if(r.entry&&a){let y=sm({...a,name:ap(a.name,n)}),v=pp(i.path,r.entry,Buffer.from(y));if(!wo(v.toString("utf-8")))return[`${r.file}: the repository's file conventions changed the guarded entry`];if(ki(v.toString("utf-8"),e.secretValues??[])!==v.toString("utf-8"))return[`${r.file}: guarded delivery steps include a credential`];p=`writing ${r.entry}`,s.push(()=>rn.writeFileSync(l,o)),rn.writeFileSync(l,v)}return[]}catch(h){return[`${r.file}: could not assemble its guarded delivery files (writeGuardedDeliveryFiles): ${p} failed: ${hp(h,i.path)}`]}})}function $ke(e,t,n){let s=e.executionSafetySources?.find(r=>Kt.resolve(r.path)===Kt.resolve(t));if(s)try{return(0,Zw.execFileSync)("git",["--literal-pathspecs","ls-tree",s.head,"--",n],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]})===""}catch{return}}function Xs(e,t,n){let s=e.executionSafetySources?.find(r=>Kt.resolve(r.path)===Kt.resolve(t));if(!s||!/^[a-f0-9]{40,64}$/.test(s.head))return!1;try{let r=Kt.join(t,n),i=rn.lstatSync(r);if(!i.isFile()||rn.realpathSync(r)!==r)return!1;let o=Xw(t,s.head,n);return!o||(i.mode&73)!==0!==o.executable?!1:rn.readFileSync(r).equals(o.bytes)}catch{return!1}}var Yw=new Map;function Xw(e,t,n){let s=`${Kt.resolve(e)}\0${t}\0${n}`,r=Yw.get(s);if(r!==void 0)return r;let i=null;try{let o=(0,Zw.execFileSync)("git",["--literal-pathspecs","ls-tree",t,"--",n],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]});/^100(?:644|755) blob /.test(o)&&(i={executable:o.startsWith("100755"),bytes:(0,Zw.execFileSync)("git",["show",`${t}:${n}`],{cwd:e,stdio:["ignore","pipe","ignore"]})})}catch{i=null}return Yw.size>=1e4&&Yw.clear(),Yw.set(s,i),i}function L6(e,t,n,s){if(!s.size)return[...n];let r=new Map(n.map(o=>[Kt.resolve(o.source.path,o.record.file),o])),i=vn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]);for(let o of t.tests){if(o.change==="deleted")continue;let a=i(o.file);if(!es(a)||lo(a.rel))continue;let c=uo(e.inputs,a.repository);if("error"in c)continue;let u=c.source,l=Kt.resolve(u.path,a.rel),p=s.get(l);if(!p)continue;let h=r.get(l);if(h){if(h.record.reason)continue;let b={...h.record,reason:p};delete b.entry,r.set(l,{...h,record:b,spec:void 0});continue}let g={repository:u.slug,file:a.rel,sourceAsset:`${a.rel}.source`,reason:p},m=b=>[`${o.file}: shared-environment delivery is blocked: ${b}`],y=fp(u.path,l);if(typeof y=="string"){r.set(l,{record:g,source:u,original:Buffer.alloc(0),problems:m(`${y} (holdDependents)`)});continue}let v=Kt.resolve(u.path,g.sourceAsset),E=Kw(v)&&!hm(u.path,v,y)?m("the inert source asset path already contains different bytes"):[];r.set(l,{record:g,source:u,original:y,problems:E})}return[...r.values()]}var Rs=G(require("node:fs")),$e=G(require("node:path"));var Pu=G(require("path"));var ZYe={python:"pytest",typescript:"playwright",javascript:"playwright"},KYe={pytest:"pytest",playwright:"playwright"};var Nke=new Set(["package.json","package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb","pyproject.toml","poetry.lock","uv.lock","pdm.lock","Pipfile","Pipfile.lock","setup.py","setup.cfg","go.mod","go.sum","Gemfile","Gemfile.lock","pom.xml","build.gradle","build.gradle.kts"]);function mm(e){let t=Pu.basename(e);return Nke.has(t)||/^requirements[^/\\]*\.(txt|in)$/.test(t)}var G6="shared-environment delivery cannot verify it for guarded execution",z6=(e,t)=>`${Es(e.inputs,t.source.slug)}${t.file}`;function eI(e,t,n){let s=vn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),r=new Set(n.map(i=>$e.resolve(i.source.path,i.record.file)));return t.tests.filter(i=>{let o=s(i.file);return!r.has($e.resolve(o.root,o.rel))&&i.change!=="updated"&&gp(e,i)})}function tI(e,t,n,s){let r=vn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),i=new Map(n.map(c=>[$e.resolve(c.source.path,c.record.file),c])),o=new Set,a=[];for(let c of t.tests){let u=r(c.file),l=$e.resolve(u.root,u.rel),p=i.get(l);if(p){o.add($e.resolve(u.root,p.record.sourceAsset)),p.record.entry&&o.add(l);continue}if(c.change==="deleted"){Wke(e,u.root,u.rel)?o.add(l):a.push(`${c.file}: a deleted shared-environment test must actually be absent and be a tracked regular file in the host-pinned source`);continue}if(c.change==="updated"||!gp(e,c)){o.add(l);continue}if(Xs(e,u.root,u.rel)){o.add(l);continue}try{let h=wo(Rs.readFileSync(l,"utf-8"));if(!h)continue;if(o.add(l),"restriction"in h){let g=$e.resolve($e.dirname(l),h.sourceAsset.path);o.add(g),!s.has(g)&&!Xs(e,u.root,$e.relative(u.root,g))&&a.push(`${c.file}: its restricted source asset is missing from the actual delivery commit`)}}catch{}}return{allowed:o,problems:a}}function nI(e,t,n,s){let r=[];for(let[i,o]of t)for(let a of o)n.has($e.resolve(i.path,a))||!s.length&&!e.inputs.deliver&&so().version==="unknown"||Jke(e,i.path,a)||Xs(e,i.path,a)||r.push({source:i,file:a});return r}var q6=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".json"],H6=/(?:\bfrom\s*|\bimport(?:\s*\()?\s*|\brequire\s*\(\s*)["'`]([^"'`\n]+)["'`]/g,Pke=/^[ \t]*from[ \t]+([.\w]+)[ \t]+import[ \t]+\(?([\w\t ,*]+)/gm,Oke=/^[ \t]*import[ \t]+([\w.]+)/gm;function Uke(e,t){if(!/^\.\.?(?:\/|$)/.test(t))return[];let n=$e.resolve(e,t),s=/\.[cm]?jsx?$/.test(n)?[n.replace(/\.([cm]?)js(x?)$/,".$1ts$2")]:[];return[n,...s,...q6.flatMap(r=>[n+r,$e.join(n,`index${r}`)])]}function j6(e,t,n,s){let r=/^\.*/.exec(n)[0].length,i=n.slice(r).split(".").filter(Boolean);return(r?[$e.resolve(t,...Array(r-1).fill(".."))]:[e,t]).flatMap(a=>{let c=$e.join(a,...i);return[`${c}.py`,$e.join(c,"__init__.py"),...s.map(u=>$e.join(c,`${u}.py`))]})}function Fke(e,t,n){let s=$e.dirname(t),r=new Set;if(t.endsWith(".py")){for(let[,i,o]of n.matchAll(Pke))for(let a of j6(e,s,i,o.split(/[\s,]+/).filter(c=>/^\w+$/.test(c))))r.add(a);for(let[,i]of n.matchAll(Oke))for(let o of j6(e,s,i,[]))r.add(o)}else for(let[,i]of n.matchAll(H6))for(let o of Uke(s,i))r.add(o);return r}function Mke(e,t){let n=new Set;if(e.endsWith(".py")||e.endsWith(".go"))return n;for(let[,s]of t.matchAll(H6)){if(/^\.\.?(?:\/|$)/.test(s)||/^[a-z][\w+.-]*:/i.test(s))continue;let r=s.split("/").pop()??"";r&&n.add(r.replace(/\.[cm]?[jt]sx?$/,""))}return n}function Lke(e,t){let n=$e.extname(t);if(!q6.includes(n))return!1;let s=$e.basename(t,n);return e.has(s)||s==="index"&&e.has($e.basename($e.dirname(t)))}function jke(e,t){let n=$e.basename(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?<![\\w.-])${n}(?![\\w.-])`).test(e)}function V6(e,t){for(let n=$e.dirname(t);;n=$e.dirname(n)){if(Rs.existsSync($e.join(n,"go.mod")))return n;if(n===e||$e.dirname(n)===n)return e}}function Vke(e,t){let n=[];t.isolatedRun&&n.push({cwd:".",text:t.isolatedRun}),t.run&&n.push({cwd:t.run.cwd,text:t.run.argv.join(" ")}),t.ci?.list&&n.push({cwd:t.ci.list.cwd,text:t.ci.list.argv.join(" ")});for(let r of t.ci?.steps??[])n.push({cwd:".",text:r.line});for(let r of t.context??[])r.cleanup&&n.push({cwd:".",text:r.cleanup});let s=new Set;for(let{cwd:r,text:i}of n)for(let o of i.split(/[\s"'`;&|()<>=,]+/))o&&!/^[a-z][\w+.-]*:/i.test(o)&&s.add($e.resolve(e,r,o));return s}var Gke={".py":"python",".js":"node",".cjs":"node",".mjs":"node",".jsx":"node",".ts":"node",".cts":"node",".mts":"node",".tsx":"node",".go":"go",".rb":"ruby",".java":"jvm",".kt":"jvm",".kts":"jvm",".scala":"jvm",".groovy":"jvm"},zke=[[/^(?:playwright|vitest|jest)\.config\.(?:[cm]?[jt]s|json)$/,"node"],[/^tsconfig\.json$/,"node"],[/^(?:pytest|tox)\.ini$/,"python"]];function qke(e){let t=$e.basename(e);if(["conftest.py","__init__.py"].includes(t))return"python";let n=zke.find(([s])=>s.test(t));if(n)return n[1];if(mm(e))return/^(?:package\.json|package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lockb?)$/.test(t)?"node":/^go\.(?:mod|sum)$/.test(t)?"go":/^Gemfile(?:\.lock)?$/.test(t)?"ruby":/^(?:pom\.xml|build\.gradle(?:\.kts)?)$/.test(t)?"jvm":"python"}function Hke(e,t,n){let s=Gke[$e.extname(t)];if(s==="go"&&$e.extname(n)===".go"&&V6(e,n)===V6(e,t))return!0;let r=qke(n);if(!r||s&&s!==r)return!1;let i=$e.relative($e.dirname(n),t);return!i.startsWith("..")&&!$e.isAbsolute(i)}function J6(e,t,n){let s=new Map;if(!n.length)return s;let r=vn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]);for(let i of t.tests){if(i.change==="deleted")continue;let o=r(i.file);if(!es(o)||Xs(e,o.root,o.rel))continue;let a=$e.resolve(o.root),c=$e.resolve(a,o.rel),u=n.filter(y=>$e.resolve(y.source.path)===a);if(!u.length)continue;let l="";try{l=Rs.readFileSync(c,"utf-8")}catch{}let p=Fke(a,c,l),h=Mke(c,l),g=Vke(a,i),m=u.filter(y=>{let v=$e.resolve(a,y.file);return p.has(v)||g.has(v)||Lke(h,v)||jke(l,v)||Hke(a,c,v)});m.length&&s.set(c,`needs ${m.map(y=>z6(e,y)).join(", ")}, which is not in the tests PR: ${G6}`)}return s}function Oa(e){return Array.isArray(e)?`[${e.map(Oa).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Oa(n)}`).join(",")}}`:JSON.stringify(e)??"undefined"}function Jke(e,t,n){let s=$e.basename(n);if(s!=="package.json"&&s!=="package-lock.json")return!1;let r=so().version;if(r==="unknown")return!1;let i,o;try{let a=$e.resolve(t,n);if(!Rs.lstatSync(a).isFile()||Rs.realpathSync(a)!==a)return!1;i=JSON.parse(Rs.readFileSync(a,"utf-8"));let c=e.executionSafetySources?.find(h=>$e.resolve(h.path)===$e.resolve(t));if(c){let h=Xw(t,c.head,n);h&&(o=JSON.parse(h.bytes.toString("utf-8")))}else if(Rs.existsSync($e.join(t,".git")))return!1;let u=h=>{let g=structuredClone(h);for(let m of["dependencies","devDependencies"])g[m]&&(delete g[m]["@skyramp/testbot-core"],Object.keys(g[m]).length||delete g[m]);return g};if(s==="package.json")return(i.devDependencies?.["@skyramp/testbot-core"]??i.dependencies?.["@skyramp/testbot-core"])!==r?!1:o?Oa(u(i))===Oa(u(o)):Object.keys(i).every(h=>["name","version","private","type","scripts","dependencies","devDependencies"].includes(h))&&(!i.scripts||Oa(i.scripts)===Oa({test:"node --test"}))&&Object.keys(i.dependencies??{}).every(h=>h==="@skyramp/testbot-core")&&Object.keys(i.devDependencies??{}).every(h=>h==="@skyramp/testbot-core");let l=i.packages?.["node_modules/@skyramp/testbot-core"];if(!l||l.version!==r||l.link||l.hasInstallScript||l.resolved!==`https://registry.npmjs.org/@skyramp/testbot-core/-/testbot-core-${r}.tgz`||!/^sha512-[A-Za-z0-9+/=]+$/.test(l.integrity??""))return!1;let p=h=>{let g=structuredClone(h);return g.packages&&(delete g.packages["node_modules/@skyramp/testbot-core"],g.packages[""]&&(g.packages[""]=u(g.packages[""]))),g};return o?Oa(p(i))===Oa(p(o)):Object.keys(i.packages??{}).every(h=>h===""||h==="node_modules/@skyramp/testbot-core")&&!i.packages?.[""]?.scripts}catch{return!1}}function Wke(e,t,n){try{return Rs.lstatSync($e.join(t,n)),!1}catch(r){if(r.code!=="ENOENT")return!1}let s=e.executionSafetySources?.find(r=>$e.resolve(r.path)===$e.resolve(t));return!s||!/^[a-f0-9]{40,64}$/.test(s.head)?!1:Xw(t,s.head,n)!==null}function Yke(e){try{return rI.lstatSync(e),!0}catch{return!1}}function sI(e,t=Am(e)){let n=new Set(t.omitted.map(({source:s,file:r})=>qt.resolve(s.path,r)));return new Map([...W6(e,t.assemblies)].map(([s,r])=>[s,r.filter(i=>!n.has(qt.resolve(s.path,i)))]))}function Am(e,t=Ae(e,"write.json")){if(!t||!En(e.inputs))return{assemblies:[],omitted:[],hasSharedTests:!1};let n=gm(e,t),s=vn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),r=new Set(t.tests.map(a=>{let c=s(a.file);return qt.resolve(c.root,c.rel)})),i=[],o=n;for(;;){let a=o.length>0||eI(e,t,o).length>0;if(!a)return{assemblies:o,omitted:i,hasSharedTests:a};let c=W6(e,o),u=new Set([...c].flatMap(([g,m])=>m.map(y=>qt.resolve(g.path,y)))),{allowed:l}=tI(e,t,o,u),p=new Set(i.map(({source:g,file:m})=>qt.resolve(g.path,m))),h=nI(e,c,l,o).filter(({source:g,file:m})=>{let y=qt.resolve(g.path,m);return!p.has(y)&&!r.has(y)});if(!h.length)return{assemblies:o,omitted:i,hasSharedTests:a};i.push(...h),o=L6(e,t,n,J6(e,t,i))}}function W6(e,t){let n=new Set(t.filter(({record:v})=>!v.entry).map(({source:v,record:E})=>qt.join(v.path,E.file))),s=Ae(e,"adapt.json"),r=Ae(e,"finalize.json"),i=Ae(e,um),o=new Map,a=v=>{let E=uo(e.inputs,v);if("error"in E)return;let b=o.get(E.source.path)??{source:E.source,paths:new Set};return o.set(E.source.path,b),{repo:b.source.path,paths:b.paths}},c=(v,E)=>qt.relative(v,qt.resolve(v,E.trim())).replace(/\/+$/,""),u=(v,E)=>{let b=E?.trim()&&a(v);if(!b)return;let I=c(b.repo,E);b.paths.add(I);for(let C of["__init__.py","conftest.py"]){let w=qt.join(qt.dirname(I),C);rI.existsSync(qt.join(b.repo,w))&&(!n.has(qt.join(b.repo,I))||!Xs(e,b.repo,w))&&b.paths.add(w)}},l=(v,E)=>{if(typeof E!="string"||!E.trim())return;let b=a(v);if(!b)return;let I=c(b.repo,E);if(tp(qt.join(b.repo,I)))return b.paths.add(I),{...b,rel:I}},p=cN(e),h=(s?.items??[]).filter(v=>v.action==="place"&&p.has(v.from??v.file??"")),g=(v,E)=>h.some(b=>b.repository===v&&b.file&&qt.normalize(b.file)===E),m=(s?.items??[]).filter(v=>!h.includes(v));for(let v of[...m,...i?.tests??[],...i?.maintained??[]])u(v.repository,v.file);for(let v of r?.dependencies?.added??[]){let E=l(v.repository,v.manifest);if(E)for(let b of pD(E.repo,Cw(E.repo,E.rel)))E.paths.add(b)}for(let v of r?.lint??[])for(let E of v.fixed??[])l(v.repository,E);for(let v of r?.support??[])l(v.repository,v.file);let y=Ae(e,Rw)?.packages??[];for(let v of new Set(y.map(E=>E.repository))){let E=a(v),b=y.filter(I=>I.repository===v).map(I=>I.dir);if(E)for(let{path:I}of nm(E.repo)){let C=c(E.repo,I),w=qt.join(E.repo,C);Hg(C,b)&&!yD(C)&&!g(v,C)&&(!Yke(w)||tp(w))&&E.paths.add(C)}}for(let{record:v,source:E,problems:b}of t){let I=o.get(E.path)?.paths;I?.has(v.file)&&(I.delete(v.file),!b.length&&(v.entry&&I.add(v.entry),I.add(v.sourceAsset)))}return new Map([...o.values()].map(({source:v,paths:E})=>[v,[...E].filter(b=>b&&b!==".."&&!b.startsWith(`..${qt.sep}`)&&!lo(b))]))}var sZe=5*6e4,iZe=12*6e4,oZe=2*6e4;var pZe=["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(`
|
|
300
|
+
`),i}function pp(e,t,n){if(n.length>fke||n.includes(0))return n;let s=ts.resolve(e),r=yke(s,ts.resolve(s,t),i=>{try{return Ake(Ww.readFileSync(ts.join(i,".editorconfig"),"utf-8"))}catch{return}});return Buffer.from(Eke(n.toString("latin1"),r),"latin1")}var Du=G(require("node:fs")),Nu=G(require("node:path"));function lN(e,t){let n=Nu.relative(e,t);try{let s=Du.lstatSync(t);if(s.isSymbolicLink())return"test entry is a symlink";if(!s.isFile())return"test entry is not a regular file";let r=Du.realpathSync(e),i=Du.realpathSync(t),o=Nu.relative(r,i);return!o||o.startsWith("..")||Nu.isAbsolute(o)?`test entry's real path is outside the checkout (${o})`:o!==n?`test entry's real path is ${o}, not ${n}, after canonicalisation`:void 0}catch(s){return s.code==="ENOENT"?`test entry is missing: no file is at ${n} in the checkout`:`test entry cannot be read: ${hp(s,e)}`}}function fp(e,t){let n=lN(e,t);if(n)return n;try{return Du.readFileSync(t)}catch(s){return`test entry cannot be read: ${hp(s,e)}`}}function hp(e,t){return(e instanceof Error?e.message:String(e)).split(t+Nu.sep).join("")}function vke(e){return Ae(e,`${W_}.json`)?.guardUnavailable===!0}function U6(e){let t=Ae(e,"recommend.json"),n=Ae(e,`${W_}.json`),s=new Map(vke(e)?(t?.generate??[]).map(({id:r})=>[r,hw]):[]);for(let{id:r,reason:i}of t?.withheld??[])s.has(r)||s.set(r,`off-limits execution (${i??"environment policy"})`);if(n?.browserWithheld)for(let r of t?.generate??[])r.type==="ui"&&!s.has(r.id)&&s.set(r.id,"the shared-environment browser guard is unavailable");return s}function F6(e,t){let n=new Set((e.covers??[]).flatMap(s=>{let r=t.get(s);return r?[r]:[]}));return n.size?`environment restriction: ${[...n].join("; ")}`:void 0}function wke(e){return!!e.guardedDelivery||!!e.context?.some(t=>t.safety?.route==="persistence")}function gp(e,t){let n=e.inputs.sharedEnvironment?.environmentAddress;return!!n&&(t.result?.cases??[]).some(s=>s.runtimeTargets?.some(r=>tu(n,r)))}function gm(e,t,n=so().version){if(!En(e.inputs))return[];let s=e.inputs.sharedEnvironment,r=s?.environmentAddress,i=Ae(e,eB),o=mz.safeParse(i),a=o.success&&o.data.environmentId===s?.environmentId&&o.data.environmentAddress===r?o.data:void 0,c=Az.safeParse(i),u=c.success?fh(c.data.refusal):o.success?fh("changed"):fh("unavailable"),l=U6(e),p=new Map(Jw(e,t).map(E=>[E.file,E.verdict])),h=$D(BD(e)),g=Ae(e,"recommend.json"),m=new Map((g?.generate??[]).map(({id:E,target:b})=>[E,b])),y=vn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),v=new Map;for(let E of t.tests){if(E.change==="deleted")continue;let b=y(E.file);if(!es(b)||lo(b.rel))continue;let I=uo(e.inputs,b.repository);if("error"in I)continue;let C=I.source,w=Kt.resolve(C.path,b.rel),x=F6(E,l)??Ike(h,b),S=wke(E),Y=gp(e,E),ue;if(!x&&!Y&&!S){if(!w.endsWith(".test.cjs"))continue;try{if(!dN(C.path,w))continue;ue=wo(rn.readFileSync(w,"utf8"))}catch{continue}if(!ue||"restriction"in ue)continue}let J=(E.covers??[]).flatMap(Ot=>{let ut=m.get(Ot)?.match(/^(GET|HEAD|OPTIONS|POST|PUT|PATCH|DELETE)\s+(\S+?)[,;]?(?:\s|$)/i);return!ut||!r?[]:ut[2].startsWith("/")||tu(r,ut[2])?[{method:ut[1].toUpperCase(),route:ut[2]}]:[]}),be=$ke(e,C.path,b.rel);if(!x&&E.change!=="added"&&(be===!1||be===void 0&&!e.inputs.deliver))continue;let Me=Ot=>`${E.file}: shared-environment delivery is blocked: ${Ot}`,Ge={repository:C.slug,file:b.rel,sourceAsset:`${b.rel}.source`},ke=fp(C.path,w);if(typeof ke=="string"){v.set(w,{record:Ge,source:C,original:Buffer.alloc(0),problems:[Me(`${ke} (planGuardedDelivery)`)]});continue}if(E.change!=="added"&&Xs(e,C.path,b.rel)){x&&(Ge.reason=x,v.set(w,{record:Ge,source:C,original:ke,problems:[]}));continue}if(be===!1||E.change!=="added"&&be!==!0){v.set(w,{record:Ge,source:C,original:ke,problems:[Me(be===!1?"the file changes an existing test; retain the assertions in a new file":"cannot prove whether the shared test already exists; use a host-pinned checkout")]});continue}if(ue??=wo(ke.toString("utf8")),!x&&ue&&"restriction"in ue)continue;let X,z=Fw.safeParse(E.guardedDelivery),Je=a&&s?{environmentId:a.environmentId,environmentAddress:a.environmentAddress,persistenceRevision:a.revision,offLimits:s.offLimits??[],route:{kind:"persistence"}}:void 0,at=`environment restriction: persistence permission was not confirmed at generation: ${u}`;if(x)X=x;else if(S&&!Je)X=at;else if(!z.success||!Je)X="no guarded HTTP representation preserves the test's assertions";else if(!E.covers?.length||(E.functions?.length??1)!==1)X="guarded HTTP delivery requires one test function";else if(!/\.test\.cjs$/.test(b.rel)||!Rke(E.ci))X="the test has no compatible Node CI entry";else if(!E.ci?.collected&&p.get(E.file)!=="not-collected")X="Testbot could not confirm that the repo's CI leaves it out, and only node --test can run the entry";else if(!Bke(C.path,w,n))X=`the CI package does not declare @skyramp/testbot-core ${n}, the released guarded runtime the entry needs`;else{let{steps:Ot}=z.data,ut=Je.offLimits.length?q_(e.inputs.skyrampMcp,Je.offLimits):void 0,Dn=new Map,Ct=Ot.flatMap(vt=>{if(vt.op==="create"){let se=Cke(Je.environmentAddress,vt.collection);return se&&Dn.set(vt.as,se),[{method:"POST",url:se,child:!1}]}if(vt.op!=="read"&&vt.op!=="update")return[];let Oe=Dn.get(vt.resource);return Oe&&Dn.set(vt.as,Oe),[{method:vt.op==="read"?"GET":vt.method??"PATCH",url:Oe,child:!0}]});Ct.some(({url:vt})=>!vt)?X="the guarded HTTP steps name an unknown resource or a collection outside the Test Environment":ut&&s&&Ct.some(({url:vt,child:Oe})=>!Oe&&lZ(vt.href,s,ut))?X="the guarded HTTP steps name an off-limits collection":J.length&&!J.some(({method:vt,route:Oe})=>Ct.some(se=>se.url&&se.method===vt&&Ske(Je.environmentAddress,se.url,se.child,Oe)))&&(X="the guarded HTTP steps do not represent the planned HTTP operation")}let sn;if(X)Ge.reason=X;else if(z.success&&Je){let{bearerTokenEnv:Ot,...ut}=z.data;sn={...ut,definition:{...Je,...Ot?{bearerTokenEnv:Ot}:{}}},Ge.entry=b.rel}let Et=Kt.resolve(C.path,Ge.sourceAsset),wn=Kw(Et)&&!hm(C.path,Et,ke)?[Me("the inert source asset path already contains different bytes")]:[];v.set(w,{record:Ge,source:C,original:ke,spec:sn,problems:wn})}return[...v.values()]}function Ike(e,t){return e.find(n=>xD(n,{file:t.rel,repository:t.repository}))?.environmentRestriction}function Cke(e,t){try{let n=new URL(t,`${e.replace(/\/$/,"")}/`);return!n.search&&!n.hash&&!n.username&&!n.password&&!/[\\]|%(?:2f|5c|2e|25)/i.test(t)&&tu(e,n.href)?n:void 0}catch{return}}function Ske(e,t,n,s){try{let r=new URL(s,t.origin),i=s.startsWith("/")&&!s.startsWith("//")&&!tu(e,r.href)?new URL(s.slice(1),`${e.replace(/\/$/,"")}/`):r;if(!tu(e,i.href))return!1;let o=t.pathname.replace(/\/$/,""),a=i.pathname.replace(/\/$/,"");if(!n)return a===o;if(!a.startsWith(`${o}/`))return!1;let c=decodeURIComponent(a.slice(o.length+1));return/^(:[\w-]+|\{[^/{}]+\}|<[^/<>]+>)$/.test(c)}catch{return!1}}function kke(e){return!!e&&/^(?:node|node:test|node\s+(?:.*\s)?--test(?:\s.*)?)$/i.test(e.trim())}function Rke(e){return e?.collected===!1||!!e?.collected&&kke(e.runner)}function dN(e,t){let n=rn.realpathSync(e);return rn.lstatSync(t).isFile()&&rn.realpathSync(t)===Kt.join(n,Kt.relative(e,t))}function hm(e,t,n){try{return dN(e,t)&&rn.readFileSync(t).equals(n)}catch{return!1}}function Kw(e){try{return rn.lstatSync(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Bke(e,t,n){if(n==="unknown")return!1;for(let s=Kt.dirname(t);;s=Kt.dirname(s)){let r=Kt.join(s,"package.json");if(Kw(r))try{if(!dN(e,r))return!1;let i=JSON.parse(rn.readFileSync(r,"utf-8"));return(i.devDependencies?.["@skyramp/testbot-core"]??i.dependencies?.["@skyramp/testbot-core"])===n}catch{return!1}if(s===e)return!1}}function xke(e){let t=Ae(e,"write.json");return t?gm(e,t):[]}function M6(e,t=xke(e),n=[],s=[]){return t.flatMap(({record:r,source:i,original:o,spec:a,problems:c})=>{if(c.length)return c;let u=Kt.join(i.path,r.sourceAsset),l=Kt.join(i.path,r.file),p=`reading ${r.file}`;try{let h=fp(i.path,l);if(typeof h=="string")return[`${r.file}: ${h} (writeGuardedDeliveryFiles)`];if(!h.equals(o))return[`${r.file}: native source changed before guarded delivery`];p=`preparing ${r.sourceAsset}`;let g=Tu(o.toString("utf-8"),n).content;if(ki(g,e.secretValues??[])!==g)return[`${r.file}: the retained source contains a credential`];let m=pp(i.path,r.sourceAsset,Buffer.from(g));if(p=`writing ${r.sourceAsset}`,Kw(u)){if(!hm(i.path,u,o)&&!hm(i.path,u,m))return[`${r.file}: the inert source asset path already contains different bytes`];hm(i.path,u,m)||(s.push(()=>rn.writeFileSync(u,o)),rn.writeFileSync(u,m))}else rn.writeFileSync(u,m,{flag:"wx"}),s.push(()=>rn.rmSync(u,{force:!0}));if(r.entry&&a){let y=sm({...a,name:ap(a.name,n)}),v=pp(i.path,r.entry,Buffer.from(y));if(!wo(v.toString("utf-8")))return[`${r.file}: the repository's file conventions changed the guarded entry`];if(ki(v.toString("utf-8"),e.secretValues??[])!==v.toString("utf-8"))return[`${r.file}: guarded delivery steps include a credential`];p=`writing ${r.entry}`,s.push(()=>rn.writeFileSync(l,o)),rn.writeFileSync(l,v)}return[]}catch(h){return[`${r.file}: could not assemble its guarded delivery files (writeGuardedDeliveryFiles): ${p} failed: ${hp(h,i.path)}`]}})}function $ke(e,t,n){let s=e.executionSafetySources?.find(r=>Kt.resolve(r.path)===Kt.resolve(t));if(s)try{return(0,Zw.execFileSync)("git",["--literal-pathspecs","ls-tree",s.head,"--",n],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]})===""}catch{return}}function Xs(e,t,n){let s=e.executionSafetySources?.find(r=>Kt.resolve(r.path)===Kt.resolve(t));if(!s||!/^[a-f0-9]{40,64}$/.test(s.head))return!1;try{let r=Kt.join(t,n),i=rn.lstatSync(r);if(!i.isFile()||rn.realpathSync(r)!==r)return!1;let o=Xw(t,s.head,n);return!o||(i.mode&73)!==0!==o.executable?!1:rn.readFileSync(r).equals(o.bytes)}catch{return!1}}var Yw=new Map;function Xw(e,t,n){let s=`${Kt.resolve(e)}\0${t}\0${n}`,r=Yw.get(s);if(r!==void 0)return r;let i=null;try{let o=(0,Zw.execFileSync)("git",["--literal-pathspecs","ls-tree",t,"--",n],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]});/^100(?:644|755) blob /.test(o)&&(i={executable:o.startsWith("100755"),bytes:(0,Zw.execFileSync)("git",["show",`${t}:${n}`],{cwd:e,stdio:["ignore","pipe","ignore"]})})}catch{i=null}return Yw.size>=1e4&&Yw.clear(),Yw.set(s,i),i}function L6(e,t,n,s){if(!s.size)return[...n];let r=new Map(n.map(o=>[Kt.resolve(o.source.path,o.record.file),o])),i=vn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]);for(let o of t.tests){if(o.change==="deleted")continue;let a=i(o.file);if(!es(a)||lo(a.rel))continue;let c=uo(e.inputs,a.repository);if("error"in c)continue;let u=c.source,l=Kt.resolve(u.path,a.rel),p=s.get(l);if(!p)continue;let h=r.get(l);if(h){if(h.record.reason)continue;let b={...h.record,reason:p};delete b.entry,r.set(l,{...h,record:b,spec:void 0});continue}let g={repository:u.slug,file:a.rel,sourceAsset:`${a.rel}.source`,reason:p},m=b=>[`${o.file}: shared-environment delivery is blocked: ${b}`],y=fp(u.path,l);if(typeof y=="string"){r.set(l,{record:g,source:u,original:Buffer.alloc(0),problems:m(`${y} (holdDependents)`)});continue}let v=Kt.resolve(u.path,g.sourceAsset),E=Kw(v)&&!hm(u.path,v,y)?m("the inert source asset path already contains different bytes"):[];r.set(l,{record:g,source:u,original:y,problems:E})}return[...r.values()]}var Rs=G(require("node:fs")),$e=G(require("node:path"));var Pu=G(require("path"));var n4e={python:"pytest",typescript:"playwright",javascript:"playwright"},r4e={pytest:"pytest",playwright:"playwright"};var Nke=new Set(["package.json","package-lock.json","npm-shrinkwrap.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb","pyproject.toml","poetry.lock","uv.lock","pdm.lock","Pipfile","Pipfile.lock","setup.py","setup.cfg","go.mod","go.sum","Gemfile","Gemfile.lock","pom.xml","build.gradle","build.gradle.kts"]);function mm(e){let t=Pu.basename(e);return Nke.has(t)||/^requirements[^/\\]*\.(txt|in)$/.test(t)}var G6="shared-environment delivery cannot verify it for guarded execution",z6=(e,t)=>`${Es(e.inputs,t.source.slug)}${t.file}`;function eI(e,t,n){let s=vn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),r=new Set(n.map(i=>$e.resolve(i.source.path,i.record.file)));return t.tests.filter(i=>{let o=s(i.file);return!r.has($e.resolve(o.root,o.rel))&&i.change!=="updated"&&gp(e,i)})}function tI(e,t,n,s){let r=vn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),i=new Map(n.map(c=>[$e.resolve(c.source.path,c.record.file),c])),o=new Set,a=[];for(let c of t.tests){let u=r(c.file),l=$e.resolve(u.root,u.rel),p=i.get(l);if(p){o.add($e.resolve(u.root,p.record.sourceAsset)),p.record.entry&&o.add(l);continue}if(c.change==="deleted"){Wke(e,u.root,u.rel)?o.add(l):a.push(`${c.file}: a deleted shared-environment test must actually be absent and be a tracked regular file in the host-pinned source`);continue}if(c.change==="updated"||!gp(e,c)){o.add(l);continue}if(Xs(e,u.root,u.rel)){o.add(l);continue}try{let h=wo(Rs.readFileSync(l,"utf-8"));if(!h)continue;if(o.add(l),"restriction"in h){let g=$e.resolve($e.dirname(l),h.sourceAsset.path);o.add(g),!s.has(g)&&!Xs(e,u.root,$e.relative(u.root,g))&&a.push(`${c.file}: its restricted source asset is missing from the actual delivery commit`)}}catch{}}return{allowed:o,problems:a}}function nI(e,t,n,s){let r=[];for(let[i,o]of t)for(let a of o)n.has($e.resolve(i.path,a))||!s.length&&!e.inputs.deliver&&so().version==="unknown"||Jke(e,i.path,a)||Xs(e,i.path,a)||r.push({source:i,file:a});return r}var q6=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".json"],H6=/(?:\bfrom\s*|\bimport(?:\s*\()?\s*|\brequire\s*\(\s*)["'`]([^"'`\n]+)["'`]/g,Pke=/^[ \t]*from[ \t]+([.\w]+)[ \t]+import[ \t]+\(?([\w\t ,*]+)/gm,Oke=/^[ \t]*import[ \t]+([\w.]+)/gm;function Uke(e,t){if(!/^\.\.?(?:\/|$)/.test(t))return[];let n=$e.resolve(e,t),s=/\.[cm]?jsx?$/.test(n)?[n.replace(/\.([cm]?)js(x?)$/,".$1ts$2")]:[];return[n,...s,...q6.flatMap(r=>[n+r,$e.join(n,`index${r}`)])]}function j6(e,t,n,s){let r=/^\.*/.exec(n)[0].length,i=n.slice(r).split(".").filter(Boolean);return(r?[$e.resolve(t,...Array(r-1).fill(".."))]:[e,t]).flatMap(a=>{let c=$e.join(a,...i);return[`${c}.py`,$e.join(c,"__init__.py"),...s.map(u=>$e.join(c,`${u}.py`))]})}function Fke(e,t,n){let s=$e.dirname(t),r=new Set;if(t.endsWith(".py")){for(let[,i,o]of n.matchAll(Pke))for(let a of j6(e,s,i,o.split(/[\s,]+/).filter(c=>/^\w+$/.test(c))))r.add(a);for(let[,i]of n.matchAll(Oke))for(let o of j6(e,s,i,[]))r.add(o)}else for(let[,i]of n.matchAll(H6))for(let o of Uke(s,i))r.add(o);return r}function Mke(e,t){let n=new Set;if(e.endsWith(".py")||e.endsWith(".go"))return n;for(let[,s]of t.matchAll(H6)){if(/^\.\.?(?:\/|$)/.test(s)||/^[a-z][\w+.-]*:/i.test(s))continue;let r=s.split("/").pop()??"";r&&n.add(r.replace(/\.[cm]?[jt]sx?$/,""))}return n}function Lke(e,t){let n=$e.extname(t);if(!q6.includes(n))return!1;let s=$e.basename(t,n);return e.has(s)||s==="index"&&e.has($e.basename($e.dirname(t)))}function jke(e,t){let n=$e.basename(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?<![\\w.-])${n}(?![\\w.-])`).test(e)}function V6(e,t){for(let n=$e.dirname(t);;n=$e.dirname(n)){if(Rs.existsSync($e.join(n,"go.mod")))return n;if(n===e||$e.dirname(n)===n)return e}}function Vke(e,t){let n=[];t.isolatedRun&&n.push({cwd:".",text:t.isolatedRun}),t.run&&n.push({cwd:t.run.cwd,text:t.run.argv.join(" ")}),t.ci?.list&&n.push({cwd:t.ci.list.cwd,text:t.ci.list.argv.join(" ")});for(let r of t.ci?.steps??[])n.push({cwd:".",text:r.line});for(let r of t.context??[])r.cleanup&&n.push({cwd:".",text:r.cleanup});let s=new Set;for(let{cwd:r,text:i}of n)for(let o of i.split(/[\s"'`;&|()<>=,]+/))o&&!/^[a-z][\w+.-]*:/i.test(o)&&s.add($e.resolve(e,r,o));return s}var Gke={".py":"python",".js":"node",".cjs":"node",".mjs":"node",".jsx":"node",".ts":"node",".cts":"node",".mts":"node",".tsx":"node",".go":"go",".rb":"ruby",".java":"jvm",".kt":"jvm",".kts":"jvm",".scala":"jvm",".groovy":"jvm"},zke=[[/^(?:playwright|vitest|jest)\.config\.(?:[cm]?[jt]s|json)$/,"node"],[/^tsconfig\.json$/,"node"],[/^(?:pytest|tox)\.ini$/,"python"]];function qke(e){let t=$e.basename(e);if(["conftest.py","__init__.py"].includes(t))return"python";let n=zke.find(([s])=>s.test(t));if(n)return n[1];if(mm(e))return/^(?:package\.json|package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lockb?)$/.test(t)?"node":/^go\.(?:mod|sum)$/.test(t)?"go":/^Gemfile(?:\.lock)?$/.test(t)?"ruby":/^(?:pom\.xml|build\.gradle(?:\.kts)?)$/.test(t)?"jvm":"python"}function Hke(e,t,n){let s=Gke[$e.extname(t)];if(s==="go"&&$e.extname(n)===".go"&&V6(e,n)===V6(e,t))return!0;let r=qke(n);if(!r||s&&s!==r)return!1;let i=$e.relative($e.dirname(n),t);return!i.startsWith("..")&&!$e.isAbsolute(i)}function J6(e,t,n){let s=new Map;if(!n.length)return s;let r=vn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]);for(let i of t.tests){if(i.change==="deleted")continue;let o=r(i.file);if(!es(o)||Xs(e,o.root,o.rel))continue;let a=$e.resolve(o.root),c=$e.resolve(a,o.rel),u=n.filter(y=>$e.resolve(y.source.path)===a);if(!u.length)continue;let l="";try{l=Rs.readFileSync(c,"utf-8")}catch{}let p=Fke(a,c,l),h=Mke(c,l),g=Vke(a,i),m=u.filter(y=>{let v=$e.resolve(a,y.file);return p.has(v)||g.has(v)||Lke(h,v)||jke(l,v)||Hke(a,c,v)});m.length&&s.set(c,`needs ${m.map(y=>z6(e,y)).join(", ")}, which is not in the tests PR: ${G6}`)}return s}function Oa(e){return Array.isArray(e)?`[${e.map(Oa).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Oa(n)}`).join(",")}}`:JSON.stringify(e)??"undefined"}function Jke(e,t,n){let s=$e.basename(n);if(s!=="package.json"&&s!=="package-lock.json")return!1;let r=so().version;if(r==="unknown")return!1;let i,o;try{let a=$e.resolve(t,n);if(!Rs.lstatSync(a).isFile()||Rs.realpathSync(a)!==a)return!1;i=JSON.parse(Rs.readFileSync(a,"utf-8"));let c=e.executionSafetySources?.find(h=>$e.resolve(h.path)===$e.resolve(t));if(c){let h=Xw(t,c.head,n);h&&(o=JSON.parse(h.bytes.toString("utf-8")))}else if(Rs.existsSync($e.join(t,".git")))return!1;let u=h=>{let g=structuredClone(h);for(let m of["dependencies","devDependencies"])g[m]&&(delete g[m]["@skyramp/testbot-core"],Object.keys(g[m]).length||delete g[m]);return g};if(s==="package.json")return(i.devDependencies?.["@skyramp/testbot-core"]??i.dependencies?.["@skyramp/testbot-core"])!==r?!1:o?Oa(u(i))===Oa(u(o)):Object.keys(i).every(h=>["name","version","private","type","scripts","dependencies","devDependencies"].includes(h))&&(!i.scripts||Oa(i.scripts)===Oa({test:"node --test"}))&&Object.keys(i.dependencies??{}).every(h=>h==="@skyramp/testbot-core")&&Object.keys(i.devDependencies??{}).every(h=>h==="@skyramp/testbot-core");let l=i.packages?.["node_modules/@skyramp/testbot-core"];if(!l||l.version!==r||l.link||l.hasInstallScript||l.resolved!==`https://registry.npmjs.org/@skyramp/testbot-core/-/testbot-core-${r}.tgz`||!/^sha512-[A-Za-z0-9+/=]+$/.test(l.integrity??""))return!1;let p=h=>{let g=structuredClone(h);return g.packages&&(delete g.packages["node_modules/@skyramp/testbot-core"],g.packages[""]&&(g.packages[""]=u(g.packages[""]))),g};return o?Oa(p(i))===Oa(p(o)):Object.keys(i.packages??{}).every(h=>h===""||h==="node_modules/@skyramp/testbot-core")&&!i.packages?.[""]?.scripts}catch{return!1}}function Wke(e,t,n){try{return Rs.lstatSync($e.join(t,n)),!1}catch(r){if(r.code!=="ENOENT")return!1}let s=e.executionSafetySources?.find(r=>$e.resolve(r.path)===$e.resolve(t));return!s||!/^[a-f0-9]{40,64}$/.test(s.head)?!1:Xw(t,s.head,n)!==null}function Yke(e){try{return rI.lstatSync(e),!0}catch{return!1}}function sI(e,t=Am(e)){let n=new Set(t.omitted.map(({source:s,file:r})=>qt.resolve(s.path,r)));return new Map([...W6(e,t.assemblies)].map(([s,r])=>[s,r.filter(i=>!n.has(qt.resolve(s.path,i)))]))}function Am(e,t=Ae(e,"write.json")){if(!t||!En(e.inputs))return{assemblies:[],omitted:[],hasSharedTests:!1};let n=gm(e,t),s=vn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),r=new Set(t.tests.map(a=>{let c=s(a.file);return qt.resolve(c.root,c.rel)})),i=[],o=n;for(;;){let a=o.length>0||eI(e,t,o).length>0;if(!a)return{assemblies:o,omitted:i,hasSharedTests:a};let c=W6(e,o),u=new Set([...c].flatMap(([g,m])=>m.map(y=>qt.resolve(g.path,y)))),{allowed:l}=tI(e,t,o,u),p=new Set(i.map(({source:g,file:m})=>qt.resolve(g.path,m))),h=nI(e,c,l,o).filter(({source:g,file:m})=>{let y=qt.resolve(g.path,m);return!p.has(y)&&!r.has(y)});if(!h.length)return{assemblies:o,omitted:i,hasSharedTests:a};i.push(...h),o=L6(e,t,n,J6(e,t,i))}}function W6(e,t){let n=new Set(t.filter(({record:v})=>!v.entry).map(({source:v,record:E})=>qt.join(v.path,E.file))),s=Ae(e,"adapt.json"),r=Ae(e,"finalize.json"),i=Ae(e,um),o=new Map,a=v=>{let E=uo(e.inputs,v);if("error"in E)return;let b=o.get(E.source.path)??{source:E.source,paths:new Set};return o.set(E.source.path,b),{repo:b.source.path,paths:b.paths}},c=(v,E)=>qt.relative(v,qt.resolve(v,E.trim())).replace(/\/+$/,""),u=(v,E)=>{let b=E?.trim()&&a(v);if(!b)return;let I=c(b.repo,E);b.paths.add(I);for(let C of["__init__.py","conftest.py"]){let w=qt.join(qt.dirname(I),C);rI.existsSync(qt.join(b.repo,w))&&(!n.has(qt.join(b.repo,I))||!Xs(e,b.repo,w))&&b.paths.add(w)}},l=(v,E)=>{if(typeof E!="string"||!E.trim())return;let b=a(v);if(!b)return;let I=c(b.repo,E);if(tp(qt.join(b.repo,I)))return b.paths.add(I),{...b,rel:I}},p=cN(e),h=(s?.items??[]).filter(v=>v.action==="place"&&p.has(v.from??v.file??"")),g=(v,E)=>h.some(b=>b.repository===v&&b.file&&qt.normalize(b.file)===E),m=(s?.items??[]).filter(v=>!h.includes(v));for(let v of[...m,...i?.tests??[],...i?.maintained??[]])u(v.repository,v.file);for(let v of r?.dependencies?.added??[]){let E=l(v.repository,v.manifest);if(E)for(let b of pD(E.repo,Cw(E.repo,E.rel)))E.paths.add(b)}for(let v of r?.lint??[])for(let E of v.fixed??[])l(v.repository,E);for(let v of r?.support??[])l(v.repository,v.file);let y=Ae(e,Rw)?.packages??[];for(let v of new Set(y.map(E=>E.repository))){let E=a(v),b=y.filter(I=>I.repository===v).map(I=>I.dir);if(E)for(let{path:I}of nm(E.repo)){let C=c(E.repo,I),w=qt.join(E.repo,C);Hg(C,b)&&!yD(C)&&!g(v,C)&&(!Yke(w)||tp(w))&&E.paths.add(C)}}for(let{record:v,source:E,problems:b}of t){let I=o.get(E.path)?.paths;I?.has(v.file)&&(I.delete(v.file),!b.length&&(v.entry&&I.add(v.entry),I.add(v.sourceAsset)))}return new Map([...o.values()].map(({source:v,paths:E})=>[v,[...E].filter(b=>b&&b!==".."&&!b.startsWith(`..${qt.sep}`)&&!lo(b))]))}var uZe=5*6e4,lZe=12*6e4,dZe=2*6e4;var AZe=["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(`
|
|
301
301
|
`);var Tr=G(require("fs")),Co=G(require("path"));var Ua=G(require("fs")),iI=G(require("path"));var eRe="change-inputs",tRe=(e,t)=>`${t}-${e.replace(/[^\w.-]+/g,n=>n==="/"?"__":"-")}.md`;function nRe(e){return[...(e.pullRequests??[]).map(t=>({label:`${t.repository}#${t.number}`,body:t.body?.trim()??""})),...(e.relatedRepos??[]).map(t=>({label:t.slug,body:t.prDescription?.trim()??""}))].map((t,n)=>({...t,file:tRe(t.label,n)})).filter(t=>t.body.length>fq)}function Y6(e,t,n){let s=iI.join(t,eRe);Ua.rmSync(s,{recursive:!0,force:!0}),Ua.mkdirSync(s,{recursive:!0}),Ua.writeFileSync(iI.join(s,ru),n,{mode:292});for(let r of nRe(e))Ua.writeFileSync(iI.join(s,r.file),`${r.body}
|
|
302
302
|
`,{mode:292})}var rRe=[/^\.github\//,/^\.gitlab(-ci)?/,/^\.circleci\//,/(^|\/)Jenkinsfile$/,/^docs?\//,/\.(md|mdx|rst)$/i,/(^|\/)LICENSE([._-].*)?$/i,/(^|\/)CODEOWNERS$/,/(^|\/)\.gitignore$/,/(^|\/)\.gitattributes$/,/(^|\/)\.editorconfig$/,/(^|\/)\.prettierrc[^/]*$/,/(^|\/)\.eslintrc[^/]*$/,/(^|\/)eslint\.config\.[^/]+$/,/(^|\/)package-lock\.json$/,/(^|\/)yarn\.lock$/,/(^|\/)pnpm-lock\.yaml$/,/(^|\/)poetry\.lock$/,/(^|\/)Pipfile\.lock$/,/(^|\/)Cargo\.lock$/,/(^|\/)go\.sum$/,/(^|\/)composer\.lock$/,/(^|\/)Gemfile\.lock$/,/\.(png|jpe?g|gif|svg|ico|webp)$/i];function Z6(e){return rRe.some(t=>t.test(e))}function sRe(e){let t=[],n=e.inputs.repositoryPath;return!n||!Tr.existsSync(n)?t.push(`repository path does not exist: ${n}`):JR(n)?td(n,e.inputs.baseBranch)||t.push(e.inputs.baseBranch?`base branch "${e.inputs.baseBranch}" does not resolve`:"could not auto-detect a base branch (origin/HEAD, main, master)"):t.push(`not a git repository: ${n}`),{ok:t.length===0,reasons:t}}function iRe(e){return(e.inputs.relatedRepos??[]).map(t=>{let n=Tr.existsSync(t.path)?IE(t.path,t.base):void 0;return n?{repository:t.slug,changedFiles:n.changedFiles}:{repository:t.slug,changedFiles:[],note:`could not read the change in ${t.path}`}})}function oRe(e){Tr.rmSync(Co.join(e.runDir,EB),{recursive:!0,force:!0});for(let t of e.inputs.relatedRepos??[]){let n=Tr.existsSync(t.path)?WR(t.path,t.base):void 0;if(!n)continue;let s=Co.join(e.runDir,vB(t.slug));Tr.mkdirSync(Co.dirname(s),{recursive:!0}),Tr.writeFileSync(s,n.diffContent)}}function aRe(e){let{repositoryPath:t,baseBranch:n}=e.inputs;Tr.rmSync(Co.join(t,jD),{recursive:!0,force:!0});let s=IE(t,n);if(!s)throw new Error(`could not compute git facts for ${t}`);let r=WR(t,n);if(!r)throw new Error(`could not compute the PR diff for ${t}`);let i=iRe(e),o=[s.changedFiles,...i.map(p=>p.changedFiles)].flat(),a=o.map(p=>p.path).filter(Z6),c=!cd(e)&&o.length>0&&a.length===o.length,u={schemaVersion:1,repository:{path:t,currentBranch:s.currentBranch,baseBranch:s.baseBranch},changedFiles:s.changedFiles,...i.length?{relatedChanges:i}:{},newFiles:r.newFiles,deletedFiles:r.deletedFiles,diffStat:r.diffStat,diffBytes:r.diffContent.length,nonApplicationFiles:a,nonApplicationOnly:c,sutRequired:!c};Tr.writeFileSync(Co.join(e.runDir,ru),r.diffContent),Y6(e.inputs,e.runDir,r.diffContent),oRe(e);let l=Co.join(e.runDir,yB);return Tr.mkdirSync(Co.dirname(l),{recursive:!0}),Tr.writeFileSync(l,JSON.stringify(u,null,2)+`
|
|
303
|
-
`),e.prepared={preflight:u},{preflight:yB,diff:ru}}var
|
|
304
|
-
`).filter(Boolean).flatMap(s=>{let[r,i]=s.split(" "),o=RRe.exec(i??"");if(!o)return[];let a=new Set(e(["diff","--name-only","-z",`${r}^1`,r]).split("\0").filter(Boolean));return[{...o[1]?{pullRequest:o[1]}:{branch:o[2]},files:a}]})}var x9=require("node:zlib");var C8e=["clean","recipe-drift"];var _n=G(require("node:fs")),Pt=G(require("node:path")),aI=require("node:crypto");function BRe(e,t,n=so().version){if(!En(e.inputs))return[];let s=vn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),r=gm(e,t,n),i=new Map(r.map(o=>[Pt.resolve(o.source.path,o.record.file),o.problems]));return t.tests.flatMap(o=>{let a=s(o.file),c=i.get(Pt.resolve(a.root,a.rel));if(c)return c;if(o.change!=="added")return[];if(!gp(e,o))return[];let l=m=>[`${o.file}: shared-environment delivery is blocked: ${m}`];if(!es(a))return l("test file is outside its checkout");let p=fp(a.root,Pt.join(a.root,a.rel));if(typeof p=="string")return l(`${p} (restrictedDeliveryProblems)`);let h=wo(p.toString("utf-8"));if(!h)return l("use the exact supported delivered harness; preserve unsupported assertions in an inactive source asset, never unrestricted executable code");if("restriction"in h){if(!h.sourceAsset.path.endsWith(".source"))return l("restricted source asset must use an inactive .source extension");let m=Pt.resolve(Pt.dirname(Pt.join(a.root,a.rel)),h.sourceAsset.path),y=Pt.relative(a.root,m);if(!y||y.startsWith("..")||Pt.isAbsolute(y))return l("restricted source asset must remain inside its checkout");try{if(!_n.lstatSync(m).isFile()||_n.realpathSync(m)!==m||(0,aI.createHash)("sha256").update(_n.readFileSync(m)).digest("hex")!==h.sourceAsset.sha256)return l("restricted source asset is missing, changed or a symlink")}catch{return l("restricted source asset is unavailable")}if(!(t.supportFiles??[]).some(v=>{let E=s(v);return Pt.join(E.root,E.rel)===m}))return l("restricted source asset must be delivered in supportFiles")}else{let m=e.inputs.sharedEnvironment;if(h.definition.environmentId!==m?.environmentId||h.definition.environmentAddress!==m?.environmentAddress)return l("harness identity/address differs from the selected Test Environment");if((m.offLimits??[]).some(y=>!h.definition.offLimits.includes(y)))return l("harness omits a configured off-limits route")}if(n==="unknown")return e.inputs.deliver?l("guarded CI delivery is unavailable from an unreleased engine build"):[];let g=Pt.dirname(Pt.join(a.root,a.rel));for(;g.startsWith(a.root);){let m=Pt.join(g,"package.json");if(_n.existsSync(m))try{let y=JSON.parse(_n.readFileSync(m,"utf-8"));return(y.devDependencies?.["@skyramp/testbot-core"]??y.dependencies?.["@skyramp/testbot-core"])===n?[]:l("declare the exact released engine version containing this harness; an unavailable or older runtime cannot protect direct invocation")}catch{return l("test package manifest is unreadable")}if(g===a.root)break;g=Pt.dirname(g)}return l("the delivered test has no package manifest declaring its guarded runtime")})}function yN(e,t){if(!En(e.inputs))return[];let n=Ae(e,"write.json");if(!n)return["shared-environment delivery requires its generated-test record"];let s=vn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),r=t??Am(e,n),{assemblies:i}=r;if(!r.hasSharedTests)return n.tests.flatMap(l=>{if(l.change!=="deleted")return[];let p=s(l.file);return es(p)&&_n.existsSync(Pt.join(p.root,p.rel))?[`${l.file}: a deleted test must actually be absent`]:[]});let o=eI(e,n,i).filter(l=>{let p=s(l.file);return l.change!=="deleted"&&!Xs(e,p.root,p.rel)}).map(l=>({...l,change:"added"})),a=sI(e,r),c=new Set([...a].flatMap(([l,p])=>p.map(h=>Pt.resolve(l.path,h)))),u=tI(e,n,i,c);return[...i.flatMap(l=>l.problems),...BRe(e,{...n,tests:o}),...u.problems,...nI(e,a,u.allowed,i).map(({file:l})=>`${l}: shared-environment delivery refuses an unverified executable/support/manifest path`)]}function s9(e,t,n=[]){if(!En(e.inputs))return[];let s=[],r=vn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]);for(let i of t.tests){if(i.change==="deleted")continue;let o=r(i.file),a=Pt.join(o.root,o.rel);if(Xs(e,o.root,o.rel)||!es(o)||lN(o.root,a))continue;let c=`reading ${o.rel}`;try{let u=wo(_n.readFileSync(a,"utf-8"));if(!u)continue;if("restriction"in u){let p=Pt.resolve(Pt.dirname(a),u.sourceAsset.path),h=Pt.relative(o.root,p);if(c=`reading ${h}`,!h||h.startsWith("..")||Pt.isAbsolute(h)||!_n.lstatSync(p).isFile()||_n.realpathSync(p)!==p){s.push(`${i.file}: restricted source asset is not a regular file in its checkout`);continue}let g=_n.readFileSync(p);if((0,aI.createHash)("sha256").update(g).digest("hex")!==u.sourceAsset.sha256){s.push(`${i.file}: restricted source asset changed before trusted formatting; not refreshing its hash`);continue}let m=Tu(g.toString("utf-8"),n).content,y=pp(o.root,h,Buffer.from(m));c=`writing ${h}`,_n.writeFileSync(p,y),u.sourceAsset.sha256=(0,aI.createHash)("sha256").update(y).digest("hex")}let l=Tu(sm(u),n).content;c=`writing ${o.rel}`,_n.writeFileSync(a,pp(o.root,o.rel,Buffer.from(l)))}catch(u){s.push(`${i.file}: could not assemble its guarded entry after trusted formatting (prepareSharedDeliveryFiles): ${c} failed: ${hp(u,o.root)}`)}}return s}var bn=G(require("fs")),ei=G(require("path")),b9=G(require("crypto")),w9=require("child_process");var Cm=require("crypto");var EN="<!-- skyramp-testbot -->",vN=hN,$Re=new Set(["lint","type","config"]),i9={critical:0,high:1,medium:2,low:3},f9=new Set(["Pass","Fail"]);var bN=e=>ta(ne().statusLabels,e),uI=e=>ta(ne().testTypeCellLabels,e);function dt(e){return(e??"").replace(/\|/g,"\\|").replace(/\r?\n/g,"<br>").trim()}function o9(e){return e.inferred?" (inferred)":""}function a9(e,t){return!e||!f9.has(e)?"\u2014":t?`${bN(e)} (${dt(h9(t))})`:bN(e)}function h9(e){let t=s=>{let r=s.indexOf(": ");return r<0?s:ta(ne().staged.maintenanceActions,s.slice(0,r))+s.slice(r)};if(e.startsWith(Em))return ne().staged.keptNot+t(e.slice(Em.length));let n=e.indexOf(vm);return n<0?e:e.slice(0,n)+ne().staged.declinedPlanned+t(e.slice(n+vm.length))}function c9(e){return e.category!==void 0&&$Re.has(e.category.toLowerCase())}function u9(e,t){return(i9[(e.severity??"").toLowerCase()]??4)-(i9[(t.severity??"").toLowerCase()]??4)}var lI=e=>e?.length?` (${e.join(", ")})`:"";function l9(e){return`- ${e.severity?`**[${ta(ne().severityLabels,e.severity.toLowerCase()).toUpperCase()}]** `:""}${e.description.trim()}${lI(e.pullRequests)}`}function TRe(e){let t=e.resultId?.split("#").slice(1).join("#");if(e.testType!=="unit"||!t)return;let n=t;try{n=decodeURIComponent(t)}catch{}let s=/^(.*?)(\[.*\])$/.exec(n);return s?{fn:s[1],kase:s[2]}:{fn:n}}var g9=(e,t)=>e!==void 0&&t!==void 0&&e.replace(/^\.\//,"")===t.replace(/^\.\//,"");function m9(e,t){return(e.testVideos??[]).find(n=>n.url&&t(n))?.url}function wN(e,t){return m9(e,n=>g9(n.fileName,t.fileName)&&(!n.repository||!t.repository||n.repository.toLowerCase()===t.repository.toLowerCase()))}function IN(e,t){return m9(e,n=>g9(n.writtenAs??n.fileName,t))}function QRe(e,t,n){return n?wN(e,{fileName:t,repository:n}):IN(e,t)}function _Re(e){let t=[],n=new Map;for(let o of e.newTestsCreated)o.testType==="unit"&&n.set(o.fileName,[...n.get(o.fileName)??[],o.testId.split("::").slice(1).join("::")]);let s=new Map,r=(o,a)=>(n.get(o??"")??[]).find(c=>c!==a&&qZ(a,c)),i=new Map;for(let o of e.testResults){let a=TRe(o),c=a&&!a.kase?r(o.fileName,a.fn):void 0;if(a&&c&&(a={fn:c,kase:`"${a.fn}"`}),a?.kase&&s.set(o,a.kase),!a){t.push({testId:o.testId,testType:o.testType,endpoint:o.endpoint,status:o.status,details:o.details??"",...o.fileName?{fileName:o.fileName}:{},...o.repository?{repository:o.repository}:{}});continue}let u=`${o.fileName??""}#${a.fn}`,l=i.get(u);l||(l={row:{testId:o.testId,testType:o.testType,endpoint:o.endpoint,status:o.status,details:"",test:a.fn,...o.fileName?{fileName:o.fileName}:{},...o.repository?{repository:o.repository}:{}},cases:[]},i.set(u,l),t.push(l.row)),l.cases.push(o)}for(let{row:o,cases:a}of i.values()){let c=a.filter(h=>h.status==="Fail"),u=a.filter(h=>h.status==="Pass").length,l=a.filter(h=>h.status==="Skipped").length;o.cases=a.length,o.status=c.length?"Fail":l?"Skipped":"Pass";let p=c[0];o.details=a.length===1?a[0].details??"":ne().staged.casesPassed(u,a.length,l)+(p?`; ${s.get(p)??""} ${p.details??""}`.replace(/; +/,"; ").trimEnd():"")}return t}function DRe(e){return fN(e).map(t=>t.expected===void 0?t.expectation:`${t.expectation}: ${Zt(t.expected)}`)}function Im(e){return e.newTestsCreated.some(t=>t.testType!=="unit")&&e.testResults.every(t=>t.status==="Skipped")&&e.testResults.some(t=>t.failureCause?.kind==="environment"&&(t.failureCause.family==="app_not_started"||t.failureCause.family==="secret"))}function A9(e){let t=e.pullRequests??[];return t.length<2?[]:[ne().staged.validatedTogether(t.map(n=>`${Zt(`${n.repository}#${n.number}`)}${n.title?` ${Bs(n.title,120)}`:""}`).join("; "))]}function y9(e,t=1/0){let n=Array.from(e.name.replace(/\s+/g," ").trim()).slice(0,t).join("").replace(/[<>[\]()*_`\\|#]/g,"\\$&").replace(/@/g,"@\u200D");return e.kind==="person"?ne().staged.requestedByPerson(n):ne().staged.requestedByPolicy(n)}function E9(e,t={}){if(t.audience==="testbot-pr")return jRe(e,t);let{audience:n,collapsed:s=!1,existingEvidence:r=[],requestedBy:i,sourcePullRequest:o}=t,a=n!=="comment",c=(e.requirements??[]).filter(w=>/^file-[a-f0-9]{16}-/i.test(w.id)).sort((w,x)=>x.id.length-w.id.length),u=w=>{let x=c.find(S=>w.toLowerCase().startsWith(S.id.toLowerCase()));return x?x.label+w.slice(x.id.length):w},l=[EN];o&&l.push(ne().staged.testsSourcePullRequest(Zt(o)),"");for(let w of A9(e))l.push(w,"");i&&l.push(y9(i),""),e.notTranslated&&l.push(ta(ne().staged.notTranslated,e.notTranslated),"");let p=w=>{s?l.push("<details>",`<summary>${w}</summary>`,""):l.push(`### ${w}`)},h=()=>{s&&l.push("","</details>"),l.push("")};for(let w of e.businessCaseAnalysis.trim().split(/\r?\n/))l.push(`> ${w}`);if(l.push(""),Im(e)&&l.push(ne().staged.noLiveApp(mp(e.newTestsCreated)),""),a&&e.newTestsCreated.length){let w=new Map;for(let S of e.newTestsCreated){if(S.testType!=="unit")continue;let Y=pN(S)[0],ue=w.get(S.fileName)??{functions:new Set,endpoints:[],descriptions:new Map};S.endpoint&&!ue.endpoints.includes(S.endpoint)&&ue.endpoints.push(S.endpoint);let J=S.description?.trim()??"",be=ue.descriptions.get(Y)??[];be.includes(J)||be.push(J),ue.functions.add(Y),ue.descriptions.set(Y,be),w.set(S.fileName,ue)}let x=e.newTestsCreated.filter(S=>S.testType!=="unit");p(ne().testRecommendationsImplementedHeader(mp(e.newTestsCreated),x.length+mp(e.newTestsCreated.filter(S=>S.testType==="unit"))));for(let[S,{functions:Y,endpoints:ue,descriptions:J}]of w){let be=Y.size;l.push(ne().staged.unitTestsInFile(`\`${S}\``,be,ue.map(ke=>`\`${ke}\``).join(", ")),"");let Me=new Map;for(let[ke,X]of J){let z=X.join("\0"),Je=Me.get(z)??{fns:[],descriptions:X};Je.fns.push(ke),Me.set(z,Je)}let Ge=0;for(let{fns:ke,descriptions:X}of Me.values()){l.push(`${++Ge}. ${ke.map(Je=>`\`${Je}\``).join(", ")}`);let z=[...new Set(X.flatMap(Je=>DRe(Je)))];for(let Je of z)l.push(` - ${Je}`)}l.push("")}for(let S of x){let Y=S.testId?Zt(u(S.testId)):uI(S.testType),ue=S.fileName?` (\`${S.fileName}\`)`:"",J=S.endpoint?`
|
|
303
|
+
`),e.prepared={preflight:u},{preflight:yB,diff:ru}}var EKe={name:"preflight",timeoutMinutes:1,requires:[],validateInput:sRe,execute:aRe};var ym=G(require("path"));function uRe(e){return jn(ND,e).errors}function lRe(e,t=[]){let{value:n,error:s}=Wt(e,t);if(s)return{errors:[s]};let r=uRe(n);return r.length>0?{errors:r}:{finalize:n,errors:[]}}var dRe="finalize-scratch";function pRe(e,t){let n=lRe(e.stdout,t?.secretValues);if(!n.finalize||!t?.outputsDir)return n;let s=(r,i)=>r.trim()&&iE(r.trim(),ym.join(t.outputsDir,dRe,i),"finalize")||r;return{...n,finalize:{...n.finalize,lint:n.finalize.lint.map((r,i)=>({...r,command:s(r.command??"",`lint-${i+1}.sh`)}))}}}var P6e=wr("finalize-schema",(e,t)=>pRe(t,e));function pN(e){return e.functions?.length?e.functions:[(e.testType==="unit"?e.testId.split("::").slice(1).join("::").replace(/\[.*\]$/,""):"")||e.testId]}function mp(e){return new Set(e.flatMap(t=>pN(t).map(n=>`${t.repository??""}\0${t.fileName}\0${n}`))).size}function fRe(e){return jn(DD,e).errors}function K6(e,t=[]){let{value:n,error:s}=Wt(e,t);if(s)return{errors:[s]};let r=fRe(n);return r.length>0?{errors:r}:{analysis:n,errors:[]}}function hRe(e,t=[]){return K6(e.stdout,t)}var r9e=wr("analysis-schema",(e,t)=>hRe(t,e.secretValues));var X3e=Xy.rows.notRun(!0);var Em="kept, not ";var vm="(declined the planned ";function fN(e){if(!e)return[];let t=[],n=0,s=0;for(let r=0;r<e.length;r++){let i=e[r];i==="("?n++:i===")"?n=Math.max(0,n-1):n===0&&i===";"&&e[r+1]===" "&&e[r-1]===")"&&(t.push(e.slice(s,r)),s=r+2)}return t.push(e.slice(s)),t.map(r=>{let i=r.trim();if(!i.endsWith(")"))return{expectation:i};let o=0;for(let a=i.length-1;a>=0;a--)if(i[a]===")")o++;else if(i[a]==="("&&--o===0){let c=i.slice(0,a).trim(),u=i.slice(a+1,-1).trim();return c&&u?{expectation:c,expected:u}:{expectation:i}}return{expectation:i}})}var hN=new Set(["update","regenerate","delete"]);var e8e={update:"updated",regenerate:"regenerated",delete:"deleted",verify:"verified",none:"touched"};var X6=d.string().trim().min(1),gN=d.object({schemaVersion:d.literal(1).optional(),businessCaseAnalysis:X6.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:X6,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 bRe(e){return jn(gN,e).errors}function wRe(e,t=[]){let{value:n,error:s}=Wt(e.stdout,t);if(s)return{errors:[s]};let r=bRe(n);return r.length>0?{errors:r}:{prose:n,errors:[]}}var d8e=wr("report-schema",(e,t)=>wRe(t,e.secretValues));var SRe="report.json",kRe="report-display.json",w8e={en:"English",ja:"Japanese"};function t9(e){let t=mN.join(e,kRe);if(Fa.existsSync(t))try{return JSON.parse(Fa.readFileSync(t,"utf-8"))}catch{}let n=mN.join(e,SRe);return Fa.existsSync(n)?JSON.parse(Fa.readFileSync(n,"utf-8")):void 0}var n9="testbot.deliverFrom";var RRe=/^Testbot: merge (?:PR #(\d+)|branch (.+))$/;function r9(e,t,n){return e(["log","--merges","--first-parent","--reverse","--format=%H%x09%s",`${t}..${n}`]).split(`
|
|
304
|
+
`).filter(Boolean).flatMap(s=>{let[r,i]=s.split(" "),o=RRe.exec(i??"");if(!o)return[];let a=new Set(e(["diff","--name-only","-z",`${r}^1`,r]).split("\0").filter(Boolean));return[{...o[1]?{pullRequest:o[1]}:{branch:o[2]},files:a}]})}var x9=require("node:zlib");var x8e=["clean","recipe-drift"];var _n=G(require("node:fs")),Pt=G(require("node:path")),aI=require("node:crypto");function BRe(e,t,n=so().version){if(!En(e.inputs))return[];let s=vn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),r=gm(e,t,n),i=new Map(r.map(o=>[Pt.resolve(o.source.path,o.record.file),o.problems]));return t.tests.flatMap(o=>{let a=s(o.file),c=i.get(Pt.resolve(a.root,a.rel));if(c)return c;if(o.change!=="added")return[];if(!gp(e,o))return[];let l=m=>[`${o.file}: shared-environment delivery is blocked: ${m}`];if(!es(a))return l("test file is outside its checkout");let p=fp(a.root,Pt.join(a.root,a.rel));if(typeof p=="string")return l(`${p} (restrictedDeliveryProblems)`);let h=wo(p.toString("utf-8"));if(!h)return l("use the exact supported delivered harness; preserve unsupported assertions in an inactive source asset, never unrestricted executable code");if("restriction"in h){if(!h.sourceAsset.path.endsWith(".source"))return l("restricted source asset must use an inactive .source extension");let m=Pt.resolve(Pt.dirname(Pt.join(a.root,a.rel)),h.sourceAsset.path),y=Pt.relative(a.root,m);if(!y||y.startsWith("..")||Pt.isAbsolute(y))return l("restricted source asset must remain inside its checkout");try{if(!_n.lstatSync(m).isFile()||_n.realpathSync(m)!==m||(0,aI.createHash)("sha256").update(_n.readFileSync(m)).digest("hex")!==h.sourceAsset.sha256)return l("restricted source asset is missing, changed or a symlink")}catch{return l("restricted source asset is unavailable")}if(!(t.supportFiles??[]).some(v=>{let E=s(v);return Pt.join(E.root,E.rel)===m}))return l("restricted source asset must be delivered in supportFiles")}else{let m=e.inputs.sharedEnvironment;if(h.definition.environmentId!==m?.environmentId||h.definition.environmentAddress!==m?.environmentAddress)return l("harness identity/address differs from the selected Test Environment");if((m.offLimits??[]).some(y=>!h.definition.offLimits.includes(y)))return l("harness omits a configured off-limits route")}if(n==="unknown")return e.inputs.deliver?l("guarded CI delivery is unavailable from an unreleased engine build"):[];let g=Pt.dirname(Pt.join(a.root,a.rel));for(;g.startsWith(a.root);){let m=Pt.join(g,"package.json");if(_n.existsSync(m))try{let y=JSON.parse(_n.readFileSync(m,"utf-8"));return(y.devDependencies?.["@skyramp/testbot-core"]??y.dependencies?.["@skyramp/testbot-core"])===n?[]:l("declare the exact released engine version containing this harness; an unavailable or older runtime cannot protect direct invocation")}catch{return l("test package manifest is unreadable")}if(g===a.root)break;g=Pt.dirname(g)}return l("the delivered test has no package manifest declaring its guarded runtime")})}function yN(e,t){if(!En(e.inputs))return[];let n=Ae(e,"write.json");if(!n)return["shared-environment delivery requires its generated-test record"];let s=vn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]),r=t??Am(e,n),{assemblies:i}=r;if(!r.hasSharedTests)return n.tests.flatMap(l=>{if(l.change!=="deleted")return[];let p=s(l.file);return es(p)&&_n.existsSync(Pt.join(p.root,p.rel))?[`${l.file}: a deleted test must actually be absent`]:[]});let o=eI(e,n,i).filter(l=>{let p=s(l.file);return l.change!=="deleted"&&!Xs(e,p.root,p.rel)}).map(l=>({...l,change:"added"})),a=sI(e,r),c=new Set([...a].flatMap(([l,p])=>p.map(h=>Pt.resolve(l.path,h)))),u=tI(e,n,i,c);return[...i.flatMap(l=>l.problems),...BRe(e,{...n,tests:o}),...u.problems,...nI(e,a,u.allowed,i).map(({file:l})=>`${l}: shared-environment delivery refuses an unverified executable/support/manifest path`)]}function s9(e,t,n=[]){if(!En(e.inputs))return[];let s=[],r=vn(e.inputs.repositoryPath,e.inputs.relatedRepos??[]);for(let i of t.tests){if(i.change==="deleted")continue;let o=r(i.file),a=Pt.join(o.root,o.rel);if(Xs(e,o.root,o.rel)||!es(o)||lN(o.root,a))continue;let c=`reading ${o.rel}`;try{let u=wo(_n.readFileSync(a,"utf-8"));if(!u)continue;if("restriction"in u){let p=Pt.resolve(Pt.dirname(a),u.sourceAsset.path),h=Pt.relative(o.root,p);if(c=`reading ${h}`,!h||h.startsWith("..")||Pt.isAbsolute(h)||!_n.lstatSync(p).isFile()||_n.realpathSync(p)!==p){s.push(`${i.file}: restricted source asset is not a regular file in its checkout`);continue}let g=_n.readFileSync(p);if((0,aI.createHash)("sha256").update(g).digest("hex")!==u.sourceAsset.sha256){s.push(`${i.file}: restricted source asset changed before trusted formatting; not refreshing its hash`);continue}let m=Tu(g.toString("utf-8"),n).content,y=pp(o.root,h,Buffer.from(m));c=`writing ${h}`,_n.writeFileSync(p,y),u.sourceAsset.sha256=(0,aI.createHash)("sha256").update(y).digest("hex")}let l=Tu(sm(u),n).content;c=`writing ${o.rel}`,_n.writeFileSync(a,pp(o.root,o.rel,Buffer.from(l)))}catch(u){s.push(`${i.file}: could not assemble its guarded entry after trusted formatting (prepareSharedDeliveryFiles): ${c} failed: ${hp(u,o.root)}`)}}return s}var bn=G(require("fs")),ei=G(require("path")),b9=G(require("crypto")),w9=require("child_process");var Cm=require("crypto");var EN="<!-- skyramp-testbot -->",vN=hN,$Re=new Set(["lint","type","config"]),i9={critical:0,high:1,medium:2,low:3},f9=new Set(["Pass","Fail"]);var bN=e=>ta(ne().statusLabels,e),uI=e=>ta(ne().testTypeCellLabels,e);function dt(e){return(e??"").replace(/\|/g,"\\|").replace(/\r?\n/g,"<br>").trim()}function o9(e){return e.inferred?" (inferred)":""}function a9(e,t){return!e||!f9.has(e)?"\u2014":t?`${bN(e)} (${dt(h9(t))})`:bN(e)}function h9(e){let t=s=>{let r=s.indexOf(": ");return r<0?s:ta(ne().staged.maintenanceActions,s.slice(0,r))+s.slice(r)};if(e.startsWith(Em))return ne().staged.keptNot+t(e.slice(Em.length));let n=e.indexOf(vm);return n<0?e:e.slice(0,n)+ne().staged.declinedPlanned+t(e.slice(n+vm.length))}function c9(e){return e.category!==void 0&&$Re.has(e.category.toLowerCase())}function u9(e,t){return(i9[(e.severity??"").toLowerCase()]??4)-(i9[(t.severity??"").toLowerCase()]??4)}var lI=e=>e?.length?` (${e.join(", ")})`:"";function l9(e){return`- ${e.severity?`**[${ta(ne().severityLabels,e.severity.toLowerCase()).toUpperCase()}]** `:""}${e.description.trim()}${lI(e.pullRequests)}`}function TRe(e){let t=e.resultId?.split("#").slice(1).join("#");if(e.testType!=="unit"||!t)return;let n=t;try{n=decodeURIComponent(t)}catch{}let s=/^(.*?)(\[.*\])$/.exec(n);return s?{fn:s[1],kase:s[2]}:{fn:n}}var g9=(e,t)=>e!==void 0&&t!==void 0&&e.replace(/^\.\//,"")===t.replace(/^\.\//,"");function m9(e,t){return(e.testVideos??[]).find(n=>n.url&&t(n))?.url}function wN(e,t){return m9(e,n=>g9(n.fileName,t.fileName)&&(!n.repository||!t.repository||n.repository.toLowerCase()===t.repository.toLowerCase()))}function IN(e,t){return m9(e,n=>g9(n.writtenAs??n.fileName,t))}function QRe(e,t,n){return n?wN(e,{fileName:t,repository:n}):IN(e,t)}function _Re(e){let t=[],n=new Map;for(let o of e.newTestsCreated)o.testType==="unit"&&n.set(o.fileName,[...n.get(o.fileName)??[],o.testId.split("::").slice(1).join("::")]);let s=new Map,r=(o,a)=>(n.get(o??"")??[]).find(c=>c!==a&&qZ(a,c)),i=new Map;for(let o of e.testResults){let a=TRe(o),c=a&&!a.kase?r(o.fileName,a.fn):void 0;if(a&&c&&(a={fn:c,kase:`"${a.fn}"`}),a?.kase&&s.set(o,a.kase),!a){t.push({testId:o.testId,testType:o.testType,endpoint:o.endpoint,status:o.status,details:o.details??"",...o.fileName?{fileName:o.fileName}:{},...o.repository?{repository:o.repository}:{}});continue}let u=`${o.fileName??""}#${a.fn}`,l=i.get(u);l||(l={row:{testId:o.testId,testType:o.testType,endpoint:o.endpoint,status:o.status,details:"",test:a.fn,...o.fileName?{fileName:o.fileName}:{},...o.repository?{repository:o.repository}:{}},cases:[]},i.set(u,l),t.push(l.row)),l.cases.push(o)}for(let{row:o,cases:a}of i.values()){let c=a.filter(h=>h.status==="Fail"),u=a.filter(h=>h.status==="Pass").length,l=a.filter(h=>h.status==="Skipped").length;o.cases=a.length,o.status=c.length?"Fail":l?"Skipped":"Pass";let p=c[0];o.details=a.length===1?a[0].details??"":ne().staged.casesPassed(u,a.length,l)+(p?`; ${s.get(p)??""} ${p.details??""}`.replace(/; +/,"; ").trimEnd():"")}return t}function DRe(e){return fN(e).map(t=>t.expected===void 0?t.expectation:`${t.expectation}: ${Zt(t.expected)}`)}function Im(e){return e.newTestsCreated.some(t=>t.testType!=="unit")&&e.testResults.every(t=>t.status==="Skipped")&&e.testResults.some(t=>t.failureCause?.kind==="environment"&&(t.failureCause.family==="app_not_started"||t.failureCause.family==="secret"))}function A9(e){let t=e.pullRequests??[];return t.length<2?[]:[ne().staged.validatedTogether(t.map(n=>`${Zt(`${n.repository}#${n.number}`)}${n.title?` ${Bs(n.title,120)}`:""}`).join("; "))]}function y9(e,t=1/0){let n=Array.from(e.name.replace(/\s+/g," ").trim()).slice(0,t).join("").replace(/[<>[\]()*_`\\|#]/g,"\\$&").replace(/@/g,"@\u200D");return e.kind==="person"?ne().staged.requestedByPerson(n):ne().staged.requestedByPolicy(n)}function E9(e,t={}){if(t.audience==="testbot-pr")return jRe(e,t);let{audience:n,collapsed:s=!1,existingEvidence:r=[],requestedBy:i,sourcePullRequest:o}=t,a=n!=="comment",c=(e.requirements??[]).filter(w=>/^file-[a-f0-9]{16}-/i.test(w.id)).sort((w,x)=>x.id.length-w.id.length),u=w=>{let x=c.find(S=>w.toLowerCase().startsWith(S.id.toLowerCase()));return x?x.label+w.slice(x.id.length):w},l=[EN];o&&l.push(ne().staged.testsSourcePullRequest(Zt(o)),"");for(let w of A9(e))l.push(w,"");i&&l.push(y9(i),""),e.notTranslated&&l.push(ta(ne().staged.notTranslated,e.notTranslated),"");let p=w=>{s?l.push("<details>",`<summary>${w}</summary>`,""):l.push(`### ${w}`)},h=()=>{s&&l.push("","</details>"),l.push("")};for(let w of e.businessCaseAnalysis.trim().split(/\r?\n/))l.push(`> ${w}`);if(l.push(""),Im(e)&&l.push(ne().staged.noLiveApp(mp(e.newTestsCreated)),""),a&&e.newTestsCreated.length){let w=new Map;for(let S of e.newTestsCreated){if(S.testType!=="unit")continue;let Y=pN(S)[0],ue=w.get(S.fileName)??{functions:new Set,endpoints:[],descriptions:new Map};S.endpoint&&!ue.endpoints.includes(S.endpoint)&&ue.endpoints.push(S.endpoint);let J=S.description?.trim()??"",be=ue.descriptions.get(Y)??[];be.includes(J)||be.push(J),ue.functions.add(Y),ue.descriptions.set(Y,be),w.set(S.fileName,ue)}let x=e.newTestsCreated.filter(S=>S.testType!=="unit");p(ne().testRecommendationsImplementedHeader(mp(e.newTestsCreated),x.length+mp(e.newTestsCreated.filter(S=>S.testType==="unit"))));for(let[S,{functions:Y,endpoints:ue,descriptions:J}]of w){let be=Y.size;l.push(ne().staged.unitTestsInFile(`\`${S}\``,be,ue.map(ke=>`\`${ke}\``).join(", ")),"");let Me=new Map;for(let[ke,X]of J){let z=X.join("\0"),Je=Me.get(z)??{fns:[],descriptions:X};Je.fns.push(ke),Me.set(z,Je)}let Ge=0;for(let{fns:ke,descriptions:X}of Me.values()){l.push(`${++Ge}. ${ke.map(Je=>`\`${Je}\``).join(", ")}`);let z=[...new Set(X.flatMap(Je=>DRe(Je)))];for(let Je of z)l.push(` - ${Je}`)}l.push("")}for(let S of x){let Y=S.testId?Zt(u(S.testId)):uI(S.testType),ue=S.fileName?` (\`${S.fileName}\`)`:"",J=S.endpoint?`
|
|
305
305
|
\`${S.endpoint}\``:"",be=S.description?`
|
|
306
306
|
${S.description.trim()}`:"";l.push(`- ${Y}${ue}${lI(S.pullRequests)}${J}${be}`)}h()}let g=(e.testMaintenance??[]).filter(w=>vN.has(w.action));if(a&&g.length){p(ne().staged.testMaintenanceHeader),l.push(ne().maintenanceTableHeader),l.push("|-----------|----------|------|--------|--------|-------|");for(let w of g)l.push(`| ${dt(uI(w.testType))} | ${dt(w.endpoint)} | \`${dt(w.fileName)}\` | ${dt(w.description)} | ${a9(w.beforeStatus,w.beforeDetails)} | ${a9(w.afterStatus,w.afterDetails)} |`);h()}let m=w=>w.startsWith(Em)||w.includes(vm),y=(e.testMaintenance??[]).filter(w=>m(w.afterDetails)&&(!vN.has(w.action)||!f9.has(w.afterStatus??"")));if(a&&y.length){p(ne().staged.declinedMaintenanceHeader);for(let w of y)l.push(`- \`${dt(w.fileName)}\`: ${dt(h9(w.afterDetails))}`);h()}if(a&&r.length){p(ne().staged.existingEvidenceHeader);let w=new Map;for(let x of r){let S=`${x.check}\0${x.url??""}\0${x.revision??""}`;w.set(S,[...w.get(S)??[],x])}for(let[,[x,...S]]of w){let Y=x.url?`[${Zt(x.check)}](${x.url})`:Zt(x.check);l.push(ne().staged.trustedCheckPassed(Y,x.revision?Zt(x.revision.slice(0,7)):""),"");for(let ue of[x,...S])l.push(`- ${Zt(ue.behavior)}`);l.push("")}h()}if(a&&e.testResults.length){p(ne().staged.testResultsHeader);let w=_Re(e),x=w.some(J=>J.test),S=w.some(J=>wN(e,J)),Y=x?ne().staged.unitResultsTableHeader:ne().staged.resultsTableHeader;l.push(S?`${Y} ${ne().columnVideo} |`:Y),l.push(`${x?"|---------|-----------|----------|------|-------|--------|---------|":"|---------|-----------|----------|--------|---------|"}${S?"-------|":""}`);for(let J of w){let be=J.details.replace(/(\S+\.(?:py|ts|js|spec\.\w+))/gi,"`$1`"),Me=J.testId?Zt(dt(u(J.testId))):"\u2014",Ge=x?` ${J.test?`\`${dt(J.test)}\``:""} | ${J.cases??""} |`:"",ke=wN(e,J),X=S?` ${ke?ne().videoDownloadLink(ke):"\u2014"} |`:"";l.push(`| ${Me} | ${dt(uI(J.testType))} | ${dt(J.endpoint)} |${Ge} ${dt(bN(J.status))} | ${dt(be)} |${X}`)}let ue=(e.testVideos??[]).find(J=>J.artifactsUrl)?.artifactsUrl;!S&&ue&&l.push("",ne().videosArtifactFallback(ue)),h()}if(e.requirements?.length){let w=e.requirements.flatMap(J=>J.clauses),x=J=>J.status==="Pass"||J.status==="Passed, test not kept",S=w.filter(x).length;p(ne().staged.requirementsHeader(S,w.length));let Y=J=>ta(ne().staged.clauseStatuses,J.status),ue=J=>(J.status==="Not tested"||J.status==="Passed, test not kept")&&J.notTested?`${Y(J)}: ${J.notTested}`:J.findings.length?`${Y(J)} \u2014 ${J.findings.join(", ")}`:Y(J);if(a){l.push(ne().staged.requirementsTableHeader),l.push("|-------------|--------|-------|--------|");for(let J of e.requirements)J.clauses.forEach((be,Me)=>{let Ge=Me===0?`**${dt(J.label)}**${J.statement?` ${dt(J.statement)}`:""}${lI(J.pullRequests)}`:"",ke=`${Zt(dt(u(be.id)))}${o9(be)}${be.text?` ${dt(be.text)}`:""}`,X=new Map;for(let at of be.tests){let sn=at.fileName??u(at.testId),Et=X.get(sn)??{fns:new Set};for(let wn of at.functions)Et.fns.add(wn);Et.video??=at.fileName?QRe(e,at.fileName,at.repository):void 0,X.set(sn,Et)}let z=X.size?[...X].map(([at,{fns:sn,video:Et}])=>`${Zt(dt(at))}${sn.size?` \u2014 ${[...sn].map(wn=>`\`${dt(wn)}\``).join(", ")}`:""}${Et?` ${ne().videoDownloadLink(Et)}`:""}`).join("<br>"):"\u2014",Je=J.source==="could-break"&&be.status==="Pass"?ne().staged.regressionGuard:"";l.push(`| ${Ge} | ${ke} | ${z} | ${dt(ue(be)+Je)} |`)})}else{l.push(ne().staged.requirementsSummaryTableHeader),l.push("|-------------|-----------------|-------------|");for(let J of e.requirements){let be=J.clauses.filter(x).length,Me=J.clauses.filter(Ge=>!x(Ge)).map(Ge=>`${Zt(dt(u(Ge.id)))}${o9(Ge)} ${dt(ue(Ge))}`);l.push(`| **${dt(J.label)}**${J.statement?` ${dt(J.statement)}`:""}${lI(J.pullRequests)} | ${be}/${J.clauses.length} | ${Me.join("<br>")||"\u2014"} |`)}}h()}if(a&&e.changes?.length&&!e.requirements?.length){let w=e.executionCoverage,x=w?ne().staged.coverageCaption(w.generated,w.modified,w.verified,w.executed):"";p(`${ne().staged.behaviourCoverageHeader}${x}`),l.push(ne().staged.coverageTableHeader),l.push("|-----------|--------|-----------|----------------|");for(let S of e.changes){let Y=S.testedBy.length?S.testedBy.map(J=>`\`${dt(J)}\``).join(", "):S.writtenBy.length?ne().staged.writtenNotRun:"\u2014",ue=S.maintainedBy.length?S.maintainedBy.map(J=>`\`${dt(J)}\``).join(", "):"\u2014";l.push(`| ${dt(S.text)} | \`${dt(S.source)}\` | ${Y} | ${ue} |`)}h()}if(e.userJourneys?.length){let w=e.userJourneys.filter(S=>S.status==="Pass"&&!S.problems.length).length;p(`\u{1F9ED} User Journeys Covered (${w}/${e.userJourneys.length} walked end to end)`);let x=e.userJourneys.some(S=>IN(e,S.fileName));l.push(`| Journey | Test | Status | Notes |${x?` ${ne().columnVideo} |`:""}`),l.push(`|---------|------|--------|-------|${x?"-------|":""}`);for(let S of e.userJourneys){let Y=S.fileName?`\`${dt(S.fileName)}\`${S.test?` \u2014 ${dt(S.test)}`:""}`:"\u2014",ue=S.source&&S.source!=="inferred"?`; described in the ${S.source==="spec"?"spec":"PR description"}`:"; inferred from the app",J=(S.uncovered?`not covered: ${S.uncovered}`:S.problems.length?`does not walk it end to end: ${S.problems.join("; ")}`:`from ${S.entry}, ${S.steps} steps`)+ue,be=x?IN(e,S.fileName):void 0;l.push(`| ${dt(S.name)} | ${Y} | ${dt(S.status)} | ${dt(J)} |${x?` ${be?ne().videoDownloadLink(be):"\u2014"} |`:""}`)}h()}let v=e.issuesFound.filter(w=>!c9(w)).sort(u9),E=e.issuesFound.filter(c9).sort(u9);if(v.length){p(ne().staged.issuesFoundHeader);for(let w of v)l.push(l9(w));h()}if(E.length){l.push(`### ${ne().configErrorsHeader}`);for(let w of E)l.push(l9(w));l.push("")}let b=e.testPackages??[],I=e.dependencyChanges??[];if(b.length){l.push(ne().staged.testPackagesHeader,"");for(let w of b)l.push(`- ${ne().staged.testPackageLine(w.directory,w.entrypoint,Object.entries(w.dependencies??{}).map(([x,S])=>w.runner==="pytest"?`${x}==${S}`:`${x}@${S}`).join(", "))}`);I.length||l.push(`- ${ne().staged.appManifestsUntouched}`),l.push("")}if(I.length){l.push(ne().staged.dependencyChangesHeader,"");for(let w of I)l.push(`- ${ne().staged.dependencyChangeLine(w.package,w.repository?`${w.repository}: ${w.manifest}`:w.manifest,(w.reason??"").replace(/\s+/g," ").trim())}`);l.push("")}let C=(e.caveats??[]).filter(w=>w.kind!=="tests-not-executed"||w.subject==="written-cases"||!Im(e));if(C.length){l.push(ne().staged.caveatsHeader,"");for(let w of C)l.push(`- ${w.text}`);l.push("")}if(e.nextSteps.length){l.push(ne().nextStepsHeader,"");for(let w of e.nextSteps)l.push(`- ${w.trim()}`);l.push("")}return l.join(`
|
|
307
307
|
`).replace(/\n{3,}/g,`
|
|
@@ -332,12 +332,12 @@ ${n}`}:{prFailure:"unknown",prDetail:t}}async function iBe(e,t,n,s,r,i){let o=s.
|
|
|
332
332
|
`}catch{return""}}var k9=e=>e.map(t=>t.dependsOn.length?`${t.file} (needs ${t.dependsOn.join(", ")})`:t.file).join("; ");async function lBe(e,t,n,s,r,i){let o=aN(s.path,e.runDir),a=process.env.PATH;o.dir&&(process.env.PATH=N6(o).PATH);try{return await dBe(e,t,n,s,r,i)}finally{o.dir&&(process.env.PATH=a),o.cleanup()}}async function dBe(e,t,n,s,r,i){let o=s.slug,a,c=!1,u,l=[];try{let p=s.path,h=await iBe(e,t,n,s,r,i),{texts:g,shown:m,title:y,bot:v,remote:E,base:b,owner:I,testsBranch:C,origin:w,mergedBase:x}=h,S=(se=[])=>tN(p6(ZRe(se,b)+E9(YRe(WRe(m,e,s),se.map(St=>St.file)),{audience:"testbot-pr",runUrl:e.inputs.skyrampRunUrl,requestedBy:e.inputs.requestedBy,sourcePullRequest:w&&`${w.repository.namespace}/${w.repository.name}#${w.number}`}),e.inputs.skyrampRunUrl))+`
|
|
333
333
|
`,Y=i?"pr-body.md":`pr-body-${I9(o)}.md`,ue=ei.join(e.outputsDir,Y);bn.writeFileSync(ue,S());let J=ft(p,["rev-parse","HEAD"]),be=x??J;ft(p,["checkout","-B",C]),a=C,ft(p,["reset"]);let Me=Ae(e,"write.json"),Ge=Am(e,Me),ke=Ge.assemblies.filter(se=>se.source.path===s.path&&r.includes(se.record.sourceAsset)),X=yN(e,Ge);if(X.length)throw new Error(X.join("; "));let z=Me?s9(e,Me,g):[];if(z.length)throw new Error(z.join("; "));let Je=new Set(ke.flatMap(({record:se})=>[se.sourceAsset,...se.entry?[se.entry]:[]]));for(let se of r)Je.has(se)||JRe(ei.join(p,se),g);let at=M6(e,ke,g,l);if(at.length)throw new Error(at.join("; "));let sn=new Map([...Je].map(se=>{let St=bn.readFileSync(ei.join(p,se)),We=Ou=>ft(p,["hash-object","--no-filters","--stdin"],Ou),xt=new Set([We(St)]),ns=St.toString("latin1");return!St.includes(0)&&ns.includes(`\r
|
|
334
334
|
`)&&xt.add(We(Buffer.from(ns.replace(/\r\n/g,`
|
|
335
|
-
`),"latin1"))),[se,xt]})),Et=[];for(let se of r)try{ft(p,["--literal-pathspecs","add","--",se])}catch{Et.push(se)}if(Et.some(se=>Je.has(se)))throw new Error("could not stage every guarded delivery file");let wn=new Map([...sn].map(([se,St])=>{let We=ft(p,["--literal-pathspecs","ls-files","--stage","--",se]),xt=/^100(?:644|755) ([a-f0-9]+) 0\t/.exec(We)?.[1];if(!xt||!St.has(xt))throw new Error(`the staged guarded file differs from the generated file: ${se}`);return[se,xt]}));try{ft(p,["diff","--cached","--quiet"])}catch{try{let se=oBe(p,h,J,be,e.inputs.skyrampRunUrl);ft(p,["-c",`user.name=${v.name}`,"-c",`user.email=${v.email}`,"commit","-m",se])}catch(se){throw new dI(se)}c=!0}c&&(l.length=0),u=ft(p,["rev-parse","HEAD"]);let Ot,ut,Dn,Ct=x??i?.headSha;if(c&&Ct&&Ct!==J){let se=!1,St=u;try{ft(p,["checkout","-q","-B",a,Ct]),se=!0;try{ft(p,["-c",`user.name=${v.name}`,"-c",`user.email=${v.email}`,"cherry-pick","--keep-redundant-commits",u])}catch(We){let xt=x?cBe(p,v,St):void 0;if(!xt||(ut=xt.files.map(ns=>({file:ns,dependsOn:aBe(p,o,x,J,ns)})),Dn={repository:o,base:b,files:ut,patch:uBe(p,J,St,xt.files)},!xt.delivered))throw We}se=!1,sN(We=>ft(p,We),Ct),u=ft(p,["rev-parse","HEAD"])}catch(We){try{ft(p,["cherry-pick","--abort"])}catch{}ft(p,["checkout","-q","-B",a,u]);let xt=pm(Pa(We),1/0);if(x&&!se)throw We;if(x)return{thrown:!1,held:Dn,record:{schemaVersion:1,repository:o,branch:a,remote:E,base:b,committed:c,commitSha:u,pushed:!1,prAction:"skipped",prTitle:y,unstaged:Et,...ut?{heldBack:ut}:{},reason:ut?`every test change needs a merged revision ${b} does not have yet, so no tests PR was opened: ${k9(ut)}`:`the tests do not apply to ${b} at ${x.slice(0,12)} without the merged revisions (${xt}), so no tests PR was opened`}};Ot=`tests committed on the checkout's merge commit (re-cut onto ${Ct.slice(0,12)} failed: ${xt})`}}ut&&bn.writeFileSync(ue,S(ut));for(let[se,St]of wn){if(ut?.some(xt=>xt.file===se))continue;let We=ft(p,["--literal-pathspecs","ls-tree",u,"--",se]);if(/^100(?:644|755) blob ([a-f0-9]+)\t/.exec(We)?.[1]!==St)throw new Error(`the committed guarded file differs from the generated file: ${se}`)}for(let{record:se}of ke){if(se.entry)continue;let St=ft(p,["--literal-pathspecs","ls-tree",u,"--",se.file]);if(St&&St!==ft(p,["--literal-pathspecs","ls-tree",J,"--",se.file]))throw new Error(`the delivery included executable source for a held test: ${se.file}`)}let vt=i?{}:{repositoryPath:p,repoSlug:o,devPr:null};if(!c){let se=await t.markTestsPrUnchanged({branch:a,...vt});return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:E,base:b,committed:!1,commitSha:u,pushed:!1,prAction:se.action==="unchanged"?"unchanged":"skipped",prUrl:se.url,prTitle:y,unstaged:Et,reason:se.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 Oe=await t.publishTestsPr({repositoryPath:p,...vt,remote:E,branch:a,base:b,commitSha:u,title:y,bodyFile:ue,mode:e.inputs.deliverMode,deliveryOwner:I,...e.inputs.firstQualification?{firstQualification:!0}:{},runUrl:e.inputs.skyrampRunUrl,signal:e.signal,deadlineMs:e.deadlineMs});return{thrown:!1,held:Dn,record:{schemaVersion:1,repository:o,branch:a,remote:E,base:Oe.base,requestedBase:b,committed:c,commitSha:u,pushed:Oe.pushed,...Oe.pushedCommits?{pushedCommits:Oe.pushedCommits}:{},...Oe.deliveredCommit?{deliveredCommit:Oe.deliveredCommit}:{},prAction:Oe.action,...Oe.retargetedAs?{retargetedAs:Oe.retargetedAs}:{},prUrl:Oe.url,prTitle:y,...Oe.failure?{prFailure:Oe.failure,prDetail:Oe.detail}:{},...Ot?{cutNote:Ot}:{},...Oe.action==="skipped"&&Oe.detail?{reason:Oe.detail}:{},unstaged:Et,...ut?{heldBack:ut}:{}}}}catch(p){return{thrown:!0,record:{schemaVersion:1,repository:o,branch:a,committed:c,commitSha:u,pushed:!1,prAction:"failed",...sBe(p),unstaged:[]}}}finally{if(l.length){try{ft(s.path,["reset"])}catch{}for(let p of l.reverse())try{p()}catch{}}}}var IXe={name:"deliver",timeoutMinutes:5,execute:eBe,validateInput:e=>{let t=XD(e);return t?{ok:!1,reasons:[t]}:VRe(e)},requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var k5e=10*6e4,R5e=4*6e4;var B5e=10*6e4;var fBe=3e4,hBe=3,R9=30,So=class extends Error{constructor(n,s,r,i){super(n);this.status=s;this.code=r;this.path=i}status;code;path},_i=class extends Error{},Ap=class extends _i{},pI=class extends Ap{};function gBe(e){let t;try{t=new URL(e)}catch{throw new Error(`skyrampAppOrigin "${e}" is not a URL`)}if(t.protocol!=="https:"||t.origin!==e.replace(/\/+$/,""))throw new Error(`skyrampAppOrigin must be an https origin, got "${e}"`);return t.origin}function mBe(e,t){if(!rd.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}function ABe(e,t,n,s){throw t<500&&t!==429?new So(e,t,n,s):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new pI(e):t===503&&n==="RUN_NOT_READY"?new Ap(e):new _i(e)}async function yBe(e,t,n,s,r,i=1/0){let o=gBe(e.origin),a=`The time limit for ${t} ${n} to the Skyramp web app was reached`,c,u=0;for(let l=1;l<=hBe||c instanceof Ap;l+=1){if(c instanceof Ap){if(u===R9)throw c;u+=1,l-=1,e.log?.(`${c.message}; trying again (${u} of ${R9}).`),await new Promise(p=>setTimeout(p,Math.max(0,Math.min(e.readyWaitMs??1e4,i-Date.now()))))}else l>1&&await new Promise(p=>setTimeout(p,Math.max(0,Math.min((e.retryDelayMs??2e3)*(l-1),i-Date.now()))));if(Date.now()>=i)throw new _i(a);try{let p,h=await(Number.isFinite(i)?Promise.race([e.idToken(o),new Promise((m,y)=>{p=setTimeout(()=>y(new _i(a)),Math.max(1,i-Date.now()))})]).finally(()=>{p&&clearTimeout(p)}):e.idToken(o));if(Date.now()>=i)throw new _i(a);let g=await(e.fetch??fetch)(new URL(n,o).toString(),{...s(h),redirect:"error",signal:AbortSignal.timeout(Math.max(1,Math.min(fBe,i-Date.now())))}).catch(m=>{let y=m instanceof Error?m.message:String(m);throw new _i(`The Skyramp web app did not answer ${t} ${n}: ${y}`,{cause:m})});return await r(g)}catch(p){if(p instanceof So||Date.now()>=i)throw p;c=p}}throw c}function EBe(e,t,n,s,r){let i=s.headers.get("cf-ray");e.log?.(`Testbot V3: the Skyramp web app answered ${t} ${n} with ${s.status}${i?`, cf-ray ${i}`:""}: ${r.replace(/\s+/g," ").slice(0,200)}`)}var fI=class extends Error{};function vBe(e){let t=Buffer.byteLength(e,"utf8");if(t<=dB)return{body:e};if(t>Fz)throw new fI("The report exceeds the Skyramp web app's 16 MiB expanded report limit");let n=new Uint8Array((0,x9.gzipSync)(e));if(n.length>dB)throw new fI("The compressed report exceeds the Skyramp web app's 1 MiB report upload limit");return{body:n,gzip:!0}}function bBe(e,t,n,s,r){let i=t==="GET"?void 0:JSON.stringify(s),o=t==="PUT"&&/^\/api\/v1\/runner\/attempts\/[^/]+\/report$/.test(n)&&i!==void 0?vBe(i):{body:i};return wBe(e,t,n,o,r)}function wBe(e,t,n,s,r){return yBe(e,t,n,o=>({method:t,headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json",Accept:"application/json",...s.gzip?{"Content-Encoding":"gzip"}:{}},body:s.body}),async o=>{let a=await o.text().catch(()=>""),c={};try{c=JSON.parse(a)}catch{}if(o.ok)return c.data;EBe(e,t,n,o,a);let u=c.error?.fields,l=typeof u?.path=="string"&&typeof u.reason=="string"?` at ${u.path}: ${u.reason}`:"",p=`The Skyramp web app refused ${t} ${n}: ${o.status} ${c.error?.code??"no error code"}${l}`;return ABe(p,o.status,c.error?.code,typeof u?.path=="string"?u.path:void 0)},r)}var x5e=10*6e4;var $5e=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var T5e=d.object({tests:d.object({placements:d.array(d.unknown()).optional()}).passthrough().optional()}).passthrough(),Q5e=d.object({repository:cB,testType:d.string(),directory:d.string()}).passthrough();var _5e=d.object({report:d.object({language:d.string()}).passthrough()}).passthrough();var D5e=d.object({environment:d.object({components:d.array(d.unknown()).optional(),dependencies:d.array(d.unknown()).optional()}).passthrough()}).passthrough(),N5e=d.object({environment:d.object({offLimits:d.unknown().optional()}).passthrough()}).passthrough();var P5e=d.object({environment:d.object({allowedEgress:d.unknown().optional()}).passthrough()}).passthrough();var O5e=d.object({name:d.string().min(1),provision:d.literal("existing"),url:d.string().min(1),repository:cB.optional(),revisionUrl:d.string().min(1).optional()}).passthrough(),U5e=d.object({name:d.string().min(1),url:d.string().nullable(),versionUrl:d.string().nullable(),notes:d.string().nullable()}).passthrough();var F5e=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);var M5e={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};async function kN(e,t){return mBe(e.attemptId,"attempt id"),bBe(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,uq({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",githubWrites:e.githubWrites,environmentUnavailable:e.cause==="environment_unavailable",sharedEnvironmentRecords:e.sharedEnvironmentRecords}))}var CBe={discover:"reading the repositories",start:"starting the components",check:"checking that the components answer"};var W5e={running:"up",healthy:"up",ready:"up",started:"up",building:"starting",pending:"starting",installing:"starting",skipped:"out_of_scope",excluded:"out_of_scope","out-of-scope":"out_of_scope"};var Y5e=new RegExp(id.source,"g");function SBe(e){let t=Xd(e).serverUrl,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0;return{...e,GIT_CONFIG_COUNT:String(n+2),[`GIT_CONFIG_KEY_${n}`]:`http.${t}/.extraheader`,[`GIT_CONFIG_VALUE_${n}`]:"",[`GIT_CONFIG_KEY_${n+1}`]:"http.extraheader",[`GIT_CONFIG_VALUE_${n+1}`]:""}}var kBe=90,RBe={CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",CLAUDE_BYTE_STREAM_IDLE_TIMEOUT_MS:String(kBe*1e3)},$9=30,T9={BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:String($9*6e4)},Q9=["This session is non-interactive: it ends as soon as you stop, and a background command can",`never notify you. Wait for long builds in the foreground (one Bash call may run up to ${$9}`,"minutes) and keep checking until they finish; never end your turn while setup is running. A server that must keep","running after setup is detached inside the command itself, with the redirect of both stdout and stderr","(`> log 2>&1`) on the whole backgrounded command (`docker compose up -d`, or `{ cmd; } </dev/null > log 2>&1 &`).","Without `2>&1` the server keeps the call's stderr open, and in `a || nohup cmd > log &` or","`(cd dir && nohup cmd > log &)` the redirect covers only `cmd`, and the shell that runs it keeps the call's output","open until the server exits. Run a setup script as a command of its own, never piped or chained:","`bash .skyramp/sut/setup.sh`. The call returns its output and exit status when the script exits, even if a server","it started still holds its output; through a pipe (`| tail`), it waits for that server."];function BBe(e,t){return SBe(pt(e,{...RBe,...t},"session"))}function hI(e){return BBe(process.env,e)}On();var _9=".skyramp/sut/health.json",j7e={[_9]:`${_9} (with a url or command)`};function RN(e,t){return!Jf(e.status)||e.environment?[]:[...new Set(e.components.flatMap(n=>n.credentials??[]))].filter(n=>!fD(n,t))}function BN(e){let t=e.filter(Mf);if(t.length!==0)return`Rename ${t.join(", ")} in the recipe and on the workflow host, for example to APP_${t[0]}`}function gI(e){if(e.state.stages.onboard?.status==="passed")return Ae(e,"onboard.json")}var AI=G(require("fs")),Sm=G(require("path"));var P9=["browser_assert","browser_assert_api_request","browser_assert_hidden","browser_assert_table_cell","browser_blueprint","browser_click","browser_drag","browser_evaluate","browser_file_upload","browser_gojs_add_node","browser_gojs_link","browser_hover","browser_mouse_action","browser_navigate","browser_navigate_back","browser_press_key","browser_select_option","browser_snapshot","browser_tabs","browser_take_screenshot","browser_type","browser_visual_snapshot","browser_wait_for"],q7e=[...P9,"skyramp_export_zip","skyramp_actions","skyramp_analyze_changes","skyramp_analyze_test_health","skyramp_batch_mock_generation","skyramp_batch_scenario_test_generation","skyramp_contract_test_generation","skyramp_e2e_test_generation","skyramp_enhance_assertions","skyramp_enrich_test_with_mocks","skyramp_execute_test","skyramp_fix_errors","skyramp_fuzz_test_generation","skyramp_generate_enriched_integration_test","skyramp_init_scan","skyramp_init_workspace","skyramp_integration_test_generation","skyramp_load_test_generation","skyramp_login","skyramp_logout","skyramp_mock_generation","skyramp_modularization","skyramp_one_click_tool","skyramp_preflight_mock_check","skyramp_query_proxy_mocks","skyramp_recommend_tests","skyramp_register_test_plan","skyramp_reuse_code","skyramp_run_existing_tests","skyramp_setup_local_dev_worker","skyramp_smoke_test_generation","skyramp_start_trace_collection","skyramp_stop_trace_collection","skyramp_submit_report","skyramp_ui_test_generation"];var H7e=["skyramp_ui_test_generation","skyramp_mock_generation","skyramp_fix_errors","skyramp_start_trace_collection","skyramp_stop_trace_collection","skyramp_export_zip",...P9];var O9=["Bash(ls:*)","Bash(cat:*)","Bash(head:*)","Bash(tail:*)","Bash(wc:*)","Bash(find:*)","Bash(grep:*)","Bash(rg:*)","Bash(diff:*)","Bash(sort:*)","Bash(env:*)","Bash(echo:*)","Bash(pwd:*)","Bash(which:*)","Bash(cp:*)","Bash(curl:*)","Bash(jq:*)","Bash(true:*)"];var mI=G(require("fs"));var _Be={name:"output-produced",verify(e,t,n){let s=e.outputFileFor(n.name);return(mI.existsSync(s)?mI.readFileSync(s,"utf-8"):"").trim().length>0?{name:this.name,passed:!0}:{name:this.name,passed:!1,details:`stage produced no output (${s} empty or missing)`}}},DBe=["Re-read the stage instructions above and confirm every task was completed.","If you find a mistake or an incomplete task, fix it now before finishing.","End your response with a one-line summary of what this stage accomplished."];function U9(e){let t=e.requires??[];return{name:e.name,model:e.model??"sonnet",maxAttempts:e.maxAttempts,effort:e.effort,timeoutMinutes:e.timeoutMinutes??15,scaleTimeout:e.scaleTimeout,requires:t,softRequires:e.softRequires,validateInput:e.validateInput??(()=>({ok:!0,reasons:[]})),buildPrompt:e.buildPrompt??(()=>`You are the "${e.name}" stage of the Skyramp Testbot.`),selfVerification:e.selfVerification??DBe,exitGates:e.exitGates??[_Be],prepare:e.prepare,abortIf:e.abortIf,onAbort:e.onAbort,beforeReset:e.beforeReset,teardown:e.teardown,releaseAtRunEnd:e.releaseAtRunEnd,buildMcpServers:e.buildMcpServers,buildReadDirs:e.buildReadDirs,buildPluginDirs:e.buildPluginDirs,buildSettings:e.buildSettings,renderTimeLimit:e.renderTimeLimit,namesSession:e.namesSession,resumeFrom:e.resumeFrom,requiredSkills:e.requiredSkills,buildSessionEnv:e.buildSessionEnv,dataSafetyProxy:e.dataSafetyProxy,startsApp:e.startsApp,putsBackTrackedFiles:e.putsBackTrackedFiles,allowedTools:e.allowedTools,buildDisallowedTools:e.buildDisallowedTools,captureTrace:e.captureTrace,onPassed:e.onPassed,passReason:e.passReason,adversarialReview:e.adversarialReview,retryHint:e.retryHint,beforeGates:e.beforeGates,afterAttempt:e.afterAttempt,retryNote:e.retryNote,salvage:e.salvage,checkpoint:e.checkpoint,needsSutAuth:e.needsSutAuth,triageBranch:e.triageBranch,branchSkipClears:e.branchSkipClears,branchRequires:e.branchRequires}}var NBe=["Bash(docker:*)","Bash(docker compose:*)","Bash(docker-compose:*)","Bash(bash:*)","Bash(sh:*)","Bash(.skyramp/sut/*)","Bash(./.skyramp/sut/*)","Bash(curl:*)","Bash(sleep:*)",...O9,"Read","Write","Edit"];function PBe(e){let t=e.state.stages.onboard;if(t&&(t.status==="failed"||t.status==="aborted")){let o=t.reason?` \u2014 ${t.reason.length>300?`${t.reason.slice(0,300)}\u2026`:t.reason}`:"";return{ok:!1,reasons:[`onboarding ran and did not pass (${t.status}${o}) \u2014 deploy does not replay its recipe; fix that and onboard again`]}}let n=Gs(e),s=gI(e);if(s?.status==="blocked")return{ok:!1,reasons:[`onboarding reported blocked (${s.blockers.length} blocker(s)) \u2014 see outputs/onboard.json`]};let r=e.inputs.setupEvents&&t?.status==="passed"&&s&&!e.inputs.recheck?RN(s,hI()):[];return r.length>0?{ok:!1,planned:!0,reasons:[[`onboard found the credentials the SUT needs (${r.join(", ")}); Testbot adds the ones on the repository and the next run starts the app with them`,BN(r)].filter(Boolean).join("; ")]}:n&&!n.sutRequired&&!(s&&Jf(s.status))&&!e.inputs.recheck?{ok:!1,reasons:["preflight determined no SUT is required (non-application change)"]}:xa(e.inputs.repositoryPath,n?.changedFiles.map(o=>o.path)).present?{ok:!0,reasons:[]}:{ok:!1,reasons:["no deploy recipe found (.skyramp/sut/setup.sh or health.json) \u2014 run onboarding first"]}}function OBe(e){let t=e.prepared?.recipe?.budgetMinutes;if(t===void 0)return;let n=Math.min(t+5,90);return n>25?n:void 0}function UBe(e){let t=Gs(e);return{recipe:xa(e.inputs.repositoryPath,t?.changedFiles.map(s=>s.path))}}function FBe(e,t){return[t.setupScript,t.teardownScript,t.authTokenScript].filter(n=>!!n).map(n=>Sm.relative(e,n))}function MBe(e,t="revisions"){let n=$w(e.inputs);return n.length===0?[]:["","Shared components: these run in an existing environment that this run does not deploy.",...n.map(s=>` - ${s.name} at ${s.url}, running ${s.repository}`),"For each, find the URL on its host where the RUNNING component reports its commit (a version,",`build-info or health endpoint) and record it in "${t}": the url, and what it returned,`,"VERBATIM. This gate fetches each url and reads the commit from what it returns. A checkout's","commit is not the deployed one. Cite only the components listed; leave out one you cannot","check \u2014 it is then reported unverifiable, and no runtime test runs against it."]}function xN(e){return gI(e)?.environment??e.inputs.recheckEnvironment}function LBe(e,t){return[`Tasks: the SUT is the customer's existing deployment at ${e}, already running. Never start, stop, redeploy or`,"change it, and write no setup.sh or teardown.sh: this recipe has none on purpose.","1. Sign in the way the recipe records (.skyramp/sut/get-auth-token.sh), when it has one \u2014 never echo it.","2. Health-check: run the recipe's check (.skyramp/sut/health.json) and confirm it answers with real data. Record the"," exact url/command and what it returned.",...t.healthHint?[` The recorded check: ${JSON.stringify(t.healthHint)}`]:[],'3. Record the outcome: "clean" when the check passes; "bringup-failed", with bringupError, when the deployment does',` not answer or is not ready. baseUrls: each component's address. teardown: "true", since nothing was started.`]}function jBe(e){let t=gI(e),n=e.inputs.recheck?e.inputs.recheckCredentials??[]:t?GR(t):[];if(n.length===0)return[];let s=e.inputs.sharedEnvironment,r=jf(s).map(i=>i.name);return["",`Credentials: the recipe reads ${n.join(", ")}, each from the environment variable of its name. Test each one that`,"has a value with a request that changes nothing, such as signing in with it (.skyramp/sut/get-auth-token.sh) or a GET","of an authenticated route: never one that creates, changes or deletes data.",...r.length>0?[`The shared components ${r.join(", ")} stay unchanged: test a credential they take only with a read.`]:[],...VBe(e)?["Record each one that is refused, such as with a 401 or 403 or a sign-in that fails, or that the app rejects at",'startup or bootstrap, such as a password it finds too short, in "credentialsRefused": its name, the component that',"refused it, the HTTP status when there was one, and the request or command with what came back. For one with no",'HTTP status, start that evidence with one short phrase saying why and a colon, such as "password shorter than 8','characters: <command and what came back>". Never write a value, there or anywhere. Leave out one with no value:',"Testbot reports it. A refused credential is not drift: never change the recipe to get around it. Never replace a","credential that has a value with a stand-in or a value written into the recipe, and never stop the recipe reading","it: Testbot refuses a recipe that does. When it stops the app coming up or its check passing, the outcome is",'"bringup-failed", and the credential is named.']:["Record each one that is refused, such as with a 401 or 403 or a sign-in that fails, in",'"credentialsRefused": its name, the component that refused it, the HTTP status, and the request or command with what',"came back. Never write a value, there or anywhere. Leave out one with no value: Testbot reports it. A refused","credential is not drift: never change the recipe to get around it. When it stops the app coming up or its check",'passing, the outcome is "bringup-failed", as for any other failure.']]}var VBe=e=>!!(e.inputs.recheck||e.inputs.setupEvents);function GBe(e){let{recipe:t}=e.prepared,n=e.inputs.repositoryPath,s=FBe(n,t),r=xN(e),i=e.inputs.sharedEnvironment,o=jf(i).map(a=>a.name);return['You are the "deploy" stage of the Skyramp Testbot.',"",...r?["Purpose: confirm, from a fresh session, that the existing deployment onboard found is reachable and ready, so the","recipe is proven the way every run will use it. The recipe already exists; change nothing."]:["Purpose: bring the system under test (SUT) up from its recorded recipe so","later stages can run tests against it. You do NOT design the deployment \u2014 the","recipe already exists. Execute it, verify it works, and if it has drifted","slightly out of date, correct it and continue (rather than reverting)."],"",`Repository: ${n} \u2014 work inside it.`,`Recipe files present: ${s.join(", ")||"(workspace only)"}`,"",...Q9,t.stale?`
|
|
335
|
+
`),"latin1"))),[se,xt]})),Et=[];for(let se of r)try{ft(p,["--literal-pathspecs","add","--",se])}catch{Et.push(se)}if(Et.some(se=>Je.has(se)))throw new Error("could not stage every guarded delivery file");let wn=new Map([...sn].map(([se,St])=>{let We=ft(p,["--literal-pathspecs","ls-files","--stage","--",se]),xt=/^100(?:644|755) ([a-f0-9]+) 0\t/.exec(We)?.[1];if(!xt||!St.has(xt))throw new Error(`the staged guarded file differs from the generated file: ${se}`);return[se,xt]}));try{ft(p,["diff","--cached","--quiet"])}catch{try{let se=oBe(p,h,J,be,e.inputs.skyrampRunUrl);ft(p,["-c",`user.name=${v.name}`,"-c",`user.email=${v.email}`,"commit","-m",se])}catch(se){throw new dI(se)}c=!0}c&&(l.length=0),u=ft(p,["rev-parse","HEAD"]);let Ot,ut,Dn,Ct=x??i?.headSha;if(c&&Ct&&Ct!==J){let se=!1,St=u;try{ft(p,["checkout","-q","-B",a,Ct]),se=!0;try{ft(p,["-c",`user.name=${v.name}`,"-c",`user.email=${v.email}`,"cherry-pick","--keep-redundant-commits",u])}catch(We){let xt=x?cBe(p,v,St):void 0;if(!xt||(ut=xt.files.map(ns=>({file:ns,dependsOn:aBe(p,o,x,J,ns)})),Dn={repository:o,base:b,files:ut,patch:uBe(p,J,St,xt.files)},!xt.delivered))throw We}se=!1,sN(We=>ft(p,We),Ct),u=ft(p,["rev-parse","HEAD"])}catch(We){try{ft(p,["cherry-pick","--abort"])}catch{}ft(p,["checkout","-q","-B",a,u]);let xt=pm(Pa(We),1/0);if(x&&!se)throw We;if(x)return{thrown:!1,held:Dn,record:{schemaVersion:1,repository:o,branch:a,remote:E,base:b,committed:c,commitSha:u,pushed:!1,prAction:"skipped",prTitle:y,unstaged:Et,...ut?{heldBack:ut}:{},reason:ut?`every test change needs a merged revision ${b} does not have yet, so no tests PR was opened: ${k9(ut)}`:`the tests do not apply to ${b} at ${x.slice(0,12)} without the merged revisions (${xt}), so no tests PR was opened`}};Ot=`tests committed on the checkout's merge commit (re-cut onto ${Ct.slice(0,12)} failed: ${xt})`}}ut&&bn.writeFileSync(ue,S(ut));for(let[se,St]of wn){if(ut?.some(xt=>xt.file===se))continue;let We=ft(p,["--literal-pathspecs","ls-tree",u,"--",se]);if(/^100(?:644|755) blob ([a-f0-9]+)\t/.exec(We)?.[1]!==St)throw new Error(`the committed guarded file differs from the generated file: ${se}`)}for(let{record:se}of ke){if(se.entry)continue;let St=ft(p,["--literal-pathspecs","ls-tree",u,"--",se.file]);if(St&&St!==ft(p,["--literal-pathspecs","ls-tree",J,"--",se.file]))throw new Error(`the delivery included executable source for a held test: ${se.file}`)}let vt=i?{}:{repositoryPath:p,repoSlug:o,devPr:null};if(!c){let se=await t.markTestsPrUnchanged({branch:a,...vt});return{thrown:!1,record:{schemaVersion:1,repository:o,branch:a,remote:E,base:b,committed:!1,commitSha:u,pushed:!1,prAction:se.action==="unchanged"?"unchanged":"skipped",prUrl:se.url,prTitle:y,unstaged:Et,reason:se.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 Oe=await t.publishTestsPr({repositoryPath:p,...vt,remote:E,branch:a,base:b,commitSha:u,title:y,bodyFile:ue,mode:e.inputs.deliverMode,deliveryOwner:I,...e.inputs.firstQualification?{firstQualification:!0}:{},runUrl:e.inputs.skyrampRunUrl,signal:e.signal,deadlineMs:e.deadlineMs});return{thrown:!1,held:Dn,record:{schemaVersion:1,repository:o,branch:a,remote:E,base:Oe.base,requestedBase:b,committed:c,commitSha:u,pushed:Oe.pushed,...Oe.pushedCommits?{pushedCommits:Oe.pushedCommits}:{},...Oe.deliveredCommit?{deliveredCommit:Oe.deliveredCommit}:{},prAction:Oe.action,...Oe.retargetedAs?{retargetedAs:Oe.retargetedAs}:{},prUrl:Oe.url,prTitle:y,...Oe.failure?{prFailure:Oe.failure,prDetail:Oe.detail}:{},...Ot?{cutNote:Ot}:{},...Oe.action==="skipped"&&Oe.detail?{reason:Oe.detail}:{},unstaged:Et,...ut?{heldBack:ut}:{}}}}catch(p){return{thrown:!0,record:{schemaVersion:1,repository:o,branch:a,committed:c,commitSha:u,pushed:!1,prAction:"failed",...sBe(p),unstaged:[]}}}finally{if(l.length){try{ft(s.path,["reset"])}catch{}for(let p of l.reverse())try{p()}catch{}}}}var BXe={name:"deliver",timeoutMinutes:5,execute:eBe,validateInput:e=>{let t=XD(e);return t?{ok:!1,reasons:[t]}:VRe(e)},requires:["report"],branchRequires:{runtime:["write"],"no-runtime":["generate-unit"]}};var T5e=10*6e4,Q5e=4*6e4;var _5e=10*6e4;var fBe=3e4,hBe=3,R9=30,So=class extends Error{constructor(n,s,r,i){super(n);this.status=s;this.code=r;this.path=i}status;code;path},_i=class extends Error{},Ap=class extends _i{},pI=class extends Ap{};function gBe(e){let t;try{t=new URL(e)}catch{throw new Error(`skyrampAppOrigin "${e}" is not a URL`)}if(t.protocol!=="https:"||t.origin!==e.replace(/\/+$/,""))throw new Error(`skyrampAppOrigin must be an https origin, got "${e}"`);return t.origin}function mBe(e,t){if(!rd.test(e))throw new Error(`The ${t} "${e}" is not a uuid`);return e}function ABe(e,t,n,s){throw t<500&&t!==429?new So(e,t,n,s):t===503&&n==="RUNNER_PROVIDER_NOT_READY"?new pI(e):t===503&&n==="RUN_NOT_READY"?new Ap(e):new _i(e)}async function yBe(e,t,n,s,r,i=1/0){let o=gBe(e.origin),a=`The time limit for ${t} ${n} to the Skyramp web app was reached`,c,u=0;for(let l=1;l<=hBe||c instanceof Ap;l+=1){if(c instanceof Ap){if(u===R9)throw c;u+=1,l-=1,e.log?.(`${c.message}; trying again (${u} of ${R9}).`),await new Promise(p=>setTimeout(p,Math.max(0,Math.min(e.readyWaitMs??1e4,i-Date.now()))))}else l>1&&await new Promise(p=>setTimeout(p,Math.max(0,Math.min((e.retryDelayMs??2e3)*(l-1),i-Date.now()))));if(Date.now()>=i)throw new _i(a);try{let p,h=await(Number.isFinite(i)?Promise.race([e.idToken(o),new Promise((m,y)=>{p=setTimeout(()=>y(new _i(a)),Math.max(1,i-Date.now()))})]).finally(()=>{p&&clearTimeout(p)}):e.idToken(o));if(Date.now()>=i)throw new _i(a);let g=await(e.fetch??fetch)(new URL(n,o).toString(),{...s(h),redirect:"error",signal:AbortSignal.timeout(Math.max(1,Math.min(fBe,i-Date.now())))}).catch(m=>{let y=m instanceof Error?m.message:String(m);throw new _i(`The Skyramp web app did not answer ${t} ${n}: ${y}`,{cause:m})});return await r(g)}catch(p){if(p instanceof So||Date.now()>=i)throw p;c=p}}throw c}function EBe(e,t,n,s,r){let i=s.headers.get("cf-ray");e.log?.(`Testbot V3: the Skyramp web app answered ${t} ${n} with ${s.status}${i?`, cf-ray ${i}`:""}: ${r.replace(/\s+/g," ").slice(0,200)}`)}var fI=class extends Error{};function vBe(e){let t=Buffer.byteLength(e,"utf8");if(t<=dB)return{body:e};if(t>Fz)throw new fI("The report exceeds the Skyramp web app's 16 MiB expanded report limit");let n=new Uint8Array((0,x9.gzipSync)(e));if(n.length>dB)throw new fI("The compressed report exceeds the Skyramp web app's 1 MiB report upload limit");return{body:n,gzip:!0}}function bBe(e,t,n,s,r){let i=t==="GET"?void 0:JSON.stringify(s),o=t==="PUT"&&/^\/api\/v1\/runner\/attempts\/[^/]+\/report$/.test(n)&&i!==void 0?vBe(i):{body:i};return wBe(e,t,n,o,r)}function wBe(e,t,n,s,r){return yBe(e,t,n,o=>({method:t,headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json",Accept:"application/json",...s.gzip?{"Content-Encoding":"gzip"}:{}},body:s.body}),async o=>{let a=await o.text().catch(()=>""),c={};try{c=JSON.parse(a)}catch{}if(o.ok)return c.data;EBe(e,t,n,o,a);let u=c.error?.fields,l=typeof u?.path=="string"&&typeof u.reason=="string"?` at ${u.path}: ${u.reason}`:"",p=`The Skyramp web app refused ${t} ${n}: ${o.status} ${c.error?.code??"no error code"}${l}`;return ABe(p,o.status,c.error?.code,typeof u?.path=="string"?u.path:void 0)},r)}var D5e=10*6e4;var N5e=["TRIGGER","AUTHORITATIVE_RELATED_CHANGE"];var P5e=d.object({tests:d.object({placements:d.array(d.unknown()).optional()}).passthrough().optional()}).passthrough(),O5e=d.object({repository:cB,testType:d.string(),directory:d.string()}).passthrough();var U5e=d.object({report:d.object({language:d.string()}).passthrough()}).passthrough();var F5e=d.object({environment:d.object({components:d.array(d.unknown()).optional(),dependencies:d.array(d.unknown()).optional()}).passthrough()}).passthrough(),M5e=d.object({environment:d.object({offLimits:d.unknown().optional()}).passthrough()}).passthrough();var L5e=d.object({environment:d.object({allowedEgress:d.unknown().optional()}).passthrough()}).passthrough();var j5e=d.object({name:d.string().min(1),provision:d.literal("existing"),url:d.string().min(1),repository:cB.optional(),revisionUrl:d.string().min(1).optional()}).passthrough(),V5e=d.object({name:d.string().min(1),url:d.string().nullable(),versionUrl:d.string().nullable(),notes:d.string().nullable()}).passthrough();var G5e=new Set(["TRIGGER","AUTHORITATIVE_RELATED_CHANGE","MANUAL_OVERRIDE"]);var z5e={"model-provider-denied":"model_provider_denied","model-provider-unavailable":"model_provider_unavailable"};async function kN(e,t){return mBe(e.attemptId,"attempt id"),bBe(t,"POST",`/api/v1/runner/attempts/${e.attemptId}/end`,uq({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",githubWrites:e.githubWrites,environmentUnavailable:e.cause==="environment_unavailable",sharedEnvironmentRecords:e.sharedEnvironmentRecords}))}var CBe={discover:"reading the repositories",start:"starting the components",check:"checking that the components answer"};var e7e={running:"up",healthy:"up",ready:"up",started:"up",building:"starting",pending:"starting",installing:"starting",skipped:"out_of_scope",excluded:"out_of_scope","out-of-scope":"out_of_scope"};var t7e=new RegExp(id.source,"g");function SBe(e){let t=Xd(e).serverUrl,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0;return{...e,GIT_CONFIG_COUNT:String(n+2),[`GIT_CONFIG_KEY_${n}`]:`http.${t}/.extraheader`,[`GIT_CONFIG_VALUE_${n}`]:"",[`GIT_CONFIG_KEY_${n+1}`]:"http.extraheader",[`GIT_CONFIG_VALUE_${n+1}`]:""}}var kBe=90,RBe={CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",CLAUDE_BYTE_STREAM_IDLE_TIMEOUT_MS:String(kBe*1e3)},$9=30,T9={BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:String($9*6e4)},Q9=["This session is non-interactive: it ends as soon as you stop, and a background command can",`never notify you. Wait for long builds in the foreground (one Bash call may run up to ${$9}`,"minutes) and keep checking until they finish; never end your turn while setup is running. A server that must keep","running after setup is detached inside the command itself, with the redirect of both stdout and stderr","(`> log 2>&1`) on the whole backgrounded command (`docker compose up -d`, or `{ cmd; } </dev/null > log 2>&1 &`).","Without `2>&1` the server keeps the call's stderr open, and in `a || nohup cmd > log &` or","`(cd dir && nohup cmd > log &)` the redirect covers only `cmd`, and the shell that runs it keeps the call's output","open until the server exits. Run a setup script as a command of its own, never piped or chained:","`bash .skyramp/sut/setup.sh`. The call returns its output and exit status when the script exits, even if a server","it started still holds its output; through a pipe (`| tail`), it waits for that server."];function BBe(e,t){return SBe(pt(e,{...RBe,...t},"session"))}function hI(e){return BBe(process.env,e)}On();var _9=".skyramp/sut/health.json",H7e={[_9]:`${_9} (with a url or command)`};function RN(e,t){return!Jf(e.status)||e.environment?[]:[...new Set(e.components.flatMap(n=>n.credentials??[]))].filter(n=>!fD(n,t))}function BN(e){let t=e.filter(Mf);if(t.length!==0)return`Rename ${t.join(", ")} in the recipe and on the workflow host, for example to APP_${t[0]}`}function gI(e){if(e.state.stages.onboard?.status==="passed")return Ae(e,"onboard.json")}var AI=G(require("fs")),Sm=G(require("path"));var P9=["browser_assert","browser_assert_api_request","browser_assert_hidden","browser_assert_table_cell","browser_blueprint","browser_click","browser_drag","browser_evaluate","browser_file_upload","browser_gojs_add_node","browser_gojs_link","browser_hover","browser_mouse_action","browser_navigate","browser_navigate_back","browser_press_key","browser_select_option","browser_snapshot","browser_tabs","browser_take_screenshot","browser_type","browser_visual_snapshot","browser_wait_for"],Z7e=[...P9,"skyramp_export_zip","skyramp_actions","skyramp_analyze_changes","skyramp_analyze_test_health","skyramp_batch_mock_generation","skyramp_batch_scenario_test_generation","skyramp_contract_test_generation","skyramp_e2e_test_generation","skyramp_enhance_assertions","skyramp_enrich_test_with_mocks","skyramp_execute_test","skyramp_fix_errors","skyramp_fuzz_test_generation","skyramp_generate_enriched_integration_test","skyramp_init_scan","skyramp_init_workspace","skyramp_integration_test_generation","skyramp_load_test_generation","skyramp_login","skyramp_logout","skyramp_mock_generation","skyramp_modularization","skyramp_one_click_tool","skyramp_preflight_mock_check","skyramp_query_proxy_mocks","skyramp_recommend_tests","skyramp_register_test_plan","skyramp_reuse_code","skyramp_run_existing_tests","skyramp_setup_local_dev_worker","skyramp_smoke_test_generation","skyramp_start_trace_collection","skyramp_stop_trace_collection","skyramp_submit_report","skyramp_ui_test_generation"];var K7e=["skyramp_ui_test_generation","skyramp_mock_generation","skyramp_fix_errors","skyramp_start_trace_collection","skyramp_stop_trace_collection","skyramp_export_zip",...P9];var O9=["Bash(ls:*)","Bash(cat:*)","Bash(head:*)","Bash(tail:*)","Bash(wc:*)","Bash(find:*)","Bash(grep:*)","Bash(rg:*)","Bash(diff:*)","Bash(sort:*)","Bash(env:*)","Bash(echo:*)","Bash(pwd:*)","Bash(which:*)","Bash(cp:*)","Bash(curl:*)","Bash(jq:*)","Bash(true:*)"];var mI=G(require("fs"));var _Be={name:"output-produced",verify(e,t,n){let s=e.outputFileFor(n.name);return(mI.existsSync(s)?mI.readFileSync(s,"utf-8"):"").trim().length>0?{name:this.name,passed:!0}:{name:this.name,passed:!1,details:`stage produced no output (${s} empty or missing)`}}},DBe=["Re-read the stage instructions above and confirm every task was completed.","If you find a mistake or an incomplete task, fix it now before finishing.","End your response with a one-line summary of what this stage accomplished."];function U9(e){let t=e.requires??[];return{name:e.name,model:e.model??"sonnet",maxAttempts:e.maxAttempts,effort:e.effort,timeoutMinutes:e.timeoutMinutes??15,scaleTimeout:e.scaleTimeout,requires:t,softRequires:e.softRequires,validateInput:e.validateInput??(()=>({ok:!0,reasons:[]})),buildPrompt:e.buildPrompt??(()=>`You are the "${e.name}" stage of the Skyramp Testbot.`),selfVerification:e.selfVerification??DBe,exitGates:e.exitGates??[_Be],prepare:e.prepare,abortIf:e.abortIf,onAbort:e.onAbort,beforeReset:e.beforeReset,teardown:e.teardown,releaseAtRunEnd:e.releaseAtRunEnd,buildMcpServers:e.buildMcpServers,buildReadDirs:e.buildReadDirs,buildPluginDirs:e.buildPluginDirs,buildSettings:e.buildSettings,renderTimeLimit:e.renderTimeLimit,namesSession:e.namesSession,resumeFrom:e.resumeFrom,requiredSkills:e.requiredSkills,buildSessionEnv:e.buildSessionEnv,dataSafetyProxy:e.dataSafetyProxy,startsApp:e.startsApp,putsBackTrackedFiles:e.putsBackTrackedFiles,allowedTools:e.allowedTools,buildDisallowedTools:e.buildDisallowedTools,captureTrace:e.captureTrace,onPassed:e.onPassed,passReason:e.passReason,adversarialReview:e.adversarialReview,retryHint:e.retryHint,beforeGates:e.beforeGates,afterAttempt:e.afterAttempt,retryNote:e.retryNote,salvage:e.salvage,checkpoint:e.checkpoint,needsSutAuth:e.needsSutAuth,triageBranch:e.triageBranch,branchSkipClears:e.branchSkipClears,branchRequires:e.branchRequires}}var NBe=["Bash(docker:*)","Bash(docker compose:*)","Bash(docker-compose:*)","Bash(bash:*)","Bash(sh:*)","Bash(.skyramp/sut/*)","Bash(./.skyramp/sut/*)","Bash(curl:*)","Bash(sleep:*)",...O9,"Read","Write","Edit"];function PBe(e){let t=e.state.stages.onboard;if(t&&(t.status==="failed"||t.status==="aborted")){let o=t.reason?` \u2014 ${t.reason.length>300?`${t.reason.slice(0,300)}\u2026`:t.reason}`:"";return{ok:!1,reasons:[`onboarding ran and did not pass (${t.status}${o}) \u2014 deploy does not replay its recipe; fix that and onboard again`]}}let n=Gs(e),s=gI(e);if(s?.status==="blocked")return{ok:!1,reasons:[`onboarding reported blocked (${s.blockers.length} blocker(s)) \u2014 see outputs/onboard.json`]};let r=e.inputs.setupEvents&&t?.status==="passed"&&s&&!e.inputs.recheck?RN(s,hI()):[];return r.length>0?{ok:!1,planned:!0,reasons:[[`onboard found the credentials the SUT needs (${r.join(", ")}); Testbot adds the ones on the repository and the next run starts the app with them`,BN(r)].filter(Boolean).join("; ")]}:n&&!n.sutRequired&&!(s&&Jf(s.status))&&!e.inputs.recheck?{ok:!1,reasons:["preflight determined no SUT is required (non-application change)"]}:xa(e.inputs.repositoryPath,n?.changedFiles.map(o=>o.path)).present?{ok:!0,reasons:[]}:{ok:!1,reasons:["no deploy recipe found (.skyramp/sut/setup.sh or health.json) \u2014 run onboarding first"]}}function OBe(e){let t=e.prepared?.recipe?.budgetMinutes;if(t===void 0)return;let n=Math.min(t+5,90);return n>25?n:void 0}function UBe(e){let t=Gs(e);return{recipe:xa(e.inputs.repositoryPath,t?.changedFiles.map(s=>s.path))}}function FBe(e,t){return[t.setupScript,t.teardownScript,t.authTokenScript].filter(n=>!!n).map(n=>Sm.relative(e,n))}function MBe(e,t="revisions"){let n=$w(e.inputs);return n.length===0?[]:["","Shared components: these run in an existing environment that this run does not deploy.",...n.map(s=>` - ${s.name} at ${s.url}, running ${s.repository}`),"For each, find the URL on its host where the RUNNING component reports its commit (a version,",`build-info or health endpoint) and record it in "${t}": the url, and what it returned,`,"VERBATIM. This gate fetches each url and reads the commit from what it returns. A checkout's","commit is not the deployed one. Cite only the components listed; leave out one you cannot","check \u2014 it is then reported unverifiable, and no runtime test runs against it."]}function xN(e){return gI(e)?.environment??e.inputs.recheckEnvironment}function LBe(e,t){return[`Tasks: the SUT is the customer's existing deployment at ${e}, already running. Never start, stop, redeploy or`,"change it, and write no setup.sh or teardown.sh: this recipe has none on purpose.","1. Sign in the way the recipe records (.skyramp/sut/get-auth-token.sh), when it has one \u2014 never echo it.","2. Health-check: run the recipe's check (.skyramp/sut/health.json) and confirm it answers with real data. Record the"," exact url/command and what it returned.",...t.healthHint?[` The recorded check: ${JSON.stringify(t.healthHint)}`]:[],'3. Record the outcome: "clean" when the check passes; "bringup-failed", with bringupError, when the deployment does',` not answer or is not ready. baseUrls: each component's address. teardown: "true", since nothing was started.`]}function jBe(e){let t=gI(e),n=e.inputs.recheck?e.inputs.recheckCredentials??[]:t?GR(t):[];if(n.length===0)return[];let s=e.inputs.sharedEnvironment,r=jf(s).map(i=>i.name);return["",`Credentials: the recipe reads ${n.join(", ")}, each from the environment variable of its name. Test each one that`,"has a value with a request that changes nothing, such as signing in with it (.skyramp/sut/get-auth-token.sh) or a GET","of an authenticated route: never one that creates, changes or deletes data.",...r.length>0?[`The shared components ${r.join(", ")} stay unchanged: test a credential they take only with a read.`]:[],...VBe(e)?["Record each one that is refused, such as with a 401 or 403 or a sign-in that fails, or that the app rejects at",'startup or bootstrap, such as a password it finds too short, in "credentialsRefused": its name, the component that',"refused it, the HTTP status when there was one, and the request or command with what came back. For one with no",'HTTP status, start that evidence with one short phrase saying why and a colon, such as "password shorter than 8','characters: <command and what came back>". Never write a value, there or anywhere. Leave out one with no value:',"Testbot reports it. A refused credential is not drift: never change the recipe to get around it. Never replace a","credential that has a value with a stand-in or a value written into the recipe, and never stop the recipe reading","it: Testbot refuses a recipe that does. When it stops the app coming up or its check passing, the outcome is",'"bringup-failed", and the credential is named.']:["Record each one that is refused, such as with a 401 or 403 or a sign-in that fails, in",'"credentialsRefused": its name, the component that refused it, the HTTP status, and the request or command with what',"came back. Never write a value, there or anywhere. Leave out one with no value: Testbot reports it. A refused","credential is not drift: never change the recipe to get around it. When it stops the app coming up or its check",'passing, the outcome is "bringup-failed", as for any other failure.']]}var VBe=e=>!!(e.inputs.recheck||e.inputs.setupEvents);function GBe(e){let{recipe:t}=e.prepared,n=e.inputs.repositoryPath,s=FBe(n,t),r=xN(e),i=e.inputs.sharedEnvironment,o=jf(i).map(a=>a.name);return['You are the "deploy" stage of the Skyramp Testbot.',"",...r?["Purpose: confirm, from a fresh session, that the existing deployment onboard found is reachable and ready, so the","recipe is proven the way every run will use it. The recipe already exists; change nothing."]:["Purpose: bring the system under test (SUT) up from its recorded recipe so","later stages can run tests against it. You do NOT design the deployment \u2014 the","recipe already exists. Execute it, verify it works, and if it has drifted","slightly out of date, correct it and continue (rather than reverting)."],"",`Repository: ${n} \u2014 work inside it.`,`Recipe files present: ${s.join(", ")||"(workspace only)"}`,"",...Q9,t.stale?`
|
|
336
336
|
STALENESS WARNING: this PR changed recipe/infra files (${t.staleFiles.join(", ")}).
|
|
337
337
|
The recorded recipe may no longer match. If bring-up fails, first decide
|
|
338
338
|
WHY: recipe drift (infra moved, recipe is behind) vs the change itself
|
|
339
339
|
breaking bring-up. Do NOT paper over a PR that broke the app.`:"","",...r?LBe(r.address,t):["Tasks:","1. Replay the recipe: run .skyramp/sut/setup.sh (or the workspace bring-up)"," even when the SUT already answers: never skip it because something is running."," Bring up every dependency you can; mock one only when deploying it here"," is genuinely infeasible. If the recipe has drifted, correct it so it works"," and update the recipe files to what actually worked. teardown.sh exits 0"," when nothing runs.","2. Seed or reset state per the recipe. Acquire the auth token the way the"," recipe records (.skyramp/sut/get-auth-token.sh) \u2014 never echo it.",...o.length?[` Leave the shared components ${o.join(", ")} unchanged: do not seed or reset them.`]:[],"3. Health-check: confirm application logic answers with real data (seeded",' data readable via a real endpoint) \u2014 NOT "port open", NOT "any HTTP',' status". Record the exact url/command and what it returned.',...t.healthHint?[" Recommended health check (recorded by onboarding \u2014 prefer it, and",` record its real output): ${JSON.stringify(t.healthHint)}`]:[],'4. Record the outcome honestly (see the schema): "change-broke-bringup" is',' published to the author as "your change broke the app" and needs evidence'," \u2014 bringupError plus suspectFiles that THIS PR changed; without a changed",' file to point at, it is "bringup-failed".'],...MBe(e),...jBe(e),"","Output: end with one JSON object matching:","",vq(Kf)," // health.output is evidence, not narration: the exact bytes, with NOTHING"," // appended \u2014 no gloss on what the response proves, no list of the other probes"," // you ran. This gate RE-RUNS the check and matches the fresh output against this"," // field, so a sentence added here describes a run nobody can reproduce. Say what"," // it means in your prose answer instead."," // On a failed bring-up, baseUrls/health may be omitted \u2014 never invent a URL for an app that didn't start."].filter(a=>a!==void 0).join(`
|
|
340
|
-
`)}function M9(e){let t=Sm.join(e.outputsDir,"deploy.txt");if(AI.existsSync(t)){let{deploy:s}=Ru({exitCode:0,stdout:AI.readFileSync(t,"utf-8"),stderr:"",timedOut:!1,durationMs:0});if(s?.teardown)return{argv:["sh","-c",s.teardown],label:"deploy.json's teardown"}}let{teardownScript:n}=xa(e.inputs.repositoryPath);if(n)return{argv:["bash",n],label:Sm.join(".skyramp","sut","teardown.sh")}}function L9(e,t){return yw(t,e.inputs.repositoryPath,{env:pt(),secretValues:e.secretValues})}async function F9(e){let t=M9(e);if(t){let n=await L9(e,t);if(n&&hZ(e))throw new Error(`SUT teardown failed: ${n}`)}}async function zBe(e,t){let n=t.passed?void 0:j9(e);if(!n)return;let s=await L9(e,n);return s&&`${s} (if nothing was running, a teardown must exit 0)`}function j9(e){return xN(e)?void 0:M9(e)}function qBe(e){if(j9(e))return"Testbot tore down the SUT the previous attempt started. Bring it up again from the start: run .skyramp/sut/setup.sh (or the workspace bring-up), even if something still answers. Never reuse what is running."}function HBe(e,t){let{deploy:n}=Ru(t,e.inputs.repositoryPath,e.secretValues);if(!n)return;if(n.outcome==="bringup-failed"){let r=Lt(n.bringupError?.output?.trim()??"",e.secretValues??[]);return`bring-up failed (environment) \u2014 no live app for later stages${r?`: ${r.slice(0,160)}`:""}`}if(n.outcome==="change-broke-bringup")return"this PR broke bring-up \u2014 recorded as a finding, no live app for later stages";let s=Yg(e).map(r=>r.name);if(s.length)return`the shared environment's ${s.join(", ")} does not verifiably run the revision under validation \u2014 no runtime test runs against it`}var V9=U9({name:"deploy",model:"opus",timeoutMinutes:25,requires:["preflight"],softRequires:["onboard"],startsApp:e=>!e.inputs.appRunning&&!(e.inputs.testEnvironment&&xN(e)),triageBranch:"runtime",validateInput:PBe,prepare:UBe,scaleTimeout:OBe,buildPrompt:GBe,allowedTools:NBe,buildSessionEnv:()=>({...T9}),selfVerification:["dependencies lists every backing service, true only if really deployed \u2014 a mocked one is false, never omitted.","Your final message is one JSON object matching the schema."],exitGates:[_w(),fK()],onPassed:async(e,t)=>({...gK(e,t),...await hK(e,t)}),passReason:HBe,afterAttempt:zBe,retryNote:qBe,onAbort:F9,teardown:F9});On();var
|
|
340
|
+
`)}function M9(e){let t=Sm.join(e.outputsDir,"deploy.txt");if(AI.existsSync(t)){let{deploy:s}=Ru({exitCode:0,stdout:AI.readFileSync(t,"utf-8"),stderr:"",timedOut:!1,durationMs:0});if(s?.teardown)return{argv:["sh","-c",s.teardown],label:"deploy.json's teardown"}}let{teardownScript:n}=xa(e.inputs.repositoryPath);if(n)return{argv:["bash",n],label:Sm.join(".skyramp","sut","teardown.sh")}}function L9(e,t){return yw(t,e.inputs.repositoryPath,{env:pt(),secretValues:e.secretValues})}async function F9(e){let t=M9(e);if(t){let n=await L9(e,t);if(n&&hZ(e))throw new Error(`SUT teardown failed: ${n}`)}}async function zBe(e,t){let n=t.passed?void 0:j9(e);if(!n)return;let s=await L9(e,n);return s&&`${s} (if nothing was running, a teardown must exit 0)`}function j9(e){return xN(e)?void 0:M9(e)}function qBe(e){if(j9(e))return"Testbot tore down the SUT the previous attempt started. Bring it up again from the start: run .skyramp/sut/setup.sh (or the workspace bring-up), even if something still answers. Never reuse what is running."}function HBe(e,t){let{deploy:n}=Ru(t,e.inputs.repositoryPath,e.secretValues);if(!n)return;if(n.outcome==="bringup-failed"){let r=Lt(n.bringupError?.output?.trim()??"",e.secretValues??[]);return`bring-up failed (environment) \u2014 no live app for later stages${r?`: ${r.slice(0,160)}`:""}`}if(n.outcome==="change-broke-bringup")return"this PR broke bring-up \u2014 recorded as a finding, no live app for later stages";let s=Yg(e).map(r=>r.name);if(s.length)return`the shared environment's ${s.join(", ")} does not verifiably run the revision under validation \u2014 no runtime test runs against it`}var V9=U9({name:"deploy",model:"opus",timeoutMinutes:25,requires:["preflight"],softRequires:["onboard"],startsApp:e=>!e.inputs.appRunning&&!(e.inputs.testEnvironment&&xN(e)),triageBranch:"runtime",validateInput:PBe,prepare:UBe,scaleTimeout:OBe,buildPrompt:GBe,allowedTools:NBe,buildSessionEnv:()=>({...T9}),selfVerification:["dependencies lists every backing service, true only if really deployed \u2014 a mocked one is false, never omitted.","Your final message is one JSON object matching the schema."],exitGates:[_w(),fK()],onPassed:async(e,t)=>({...gK(e,t),...await hK(e,t)}),passReason:HBe,afterAttempt:zBe,retryNote:qBe,onAbort:F9,teardown:F9});On();var Net=20*1024*1024;var ko=G(require("fs"));var z9=G(require("path"));var qet=z9.join(".skyramp","sut","get-auth-token.sh");var $N="\\$([A-Z][A-Z0-9_]{0,99})",Het=new RegExp(`^${$N}$`),Jet=new RegExp(`^${$N}:${$N}$`);var Att=new Set([...AD,"coverage",".nyc_output","htmlcov","TestResults"]);var hnt=3*6e4;var gnt=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;var YBe=["GH_TOKEN","GITHUB_TOKEN","ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_BEARER_TOKEN_BEDROCK","AWS_CONTAINER_AUTHORIZATION_TOKEN"],ZBe=["AWS_WEB_IDENTITY_TOKEN_FILE","AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"];function KBe(e){if(e)try{return ko.statSync(e).size>64*1024?void 0:ko.readFileSync(e,"utf8").trim()||void 0}catch{return}}function q9(e=process.env){return Rh([...YBe.map(t=>e[t]),...ZBe.map(t=>KBe(e[t]))])}var yI=G(require("fs")),TN=G(require("path"));function XBe(e){let t;try{t=yI.readdirSync(e)}catch{return[]}let n=t.filter(s=>/^session-[0-9a-f-]{36}$/.test(s)).map(s=>TN.join(e,s)).filter(s=>yI.lstatSync(s,{throwIfNoEntry:!1})?.isDirectory());return[e,...n.sort()]}function exe(e,t){let n;try{n=new URL(e)}catch{return}if(n.protocol!=="http:"&&n.protocol!=="https:")return;let s=xh(ki(`${n.protocol}//${n.host}${n.pathname}`,t),t);return zz.safeParse({records:[s],unlisted:0}).success?s:void 0}function H9(e,t){let n=TN.join(e,Fg),s=XBe(n).flatMap(c=>[J_(c,!0,new Set),J_(c,!1,new Set)]),{leftovers:r,unparsedCreates:i}=fZ(s.flatMap(c=>c.ledgers)),o=[],a=i.length+s.flatMap(c=>c.failures).length;for(let c of new Set(r)){let u=exe(c,t);u===void 0||o.includes(u)||o.length>=pB?a+=1:o.push(u)}return o.length+a>0?{records:o,unlisted:a}:void 0}var Mnt=new RegExp(id.source,"g");var nxe="https://testbot.skyramp.dev",Di={attemptId:"v3AttemptId",deadlineAt:"v3DeadlineAt",reportUploaded:"v3ReportUploaded",recipeUploaded:"v3RecipeUploaded",recipeStatus:"v3RecipeStatus",revisionsUploaded:"v3RevisionsUploaded",cause:"v3Cause",conflict:"v3Conflict",githubWrites:"v3GithubWrites",credentialNames:"v3CredentialNames"};function J9(e,t,n){return{origin:e,idToken:t,sourceToken:n,mask:s=>Wi(s),log:s=>ls(s),onTokenRefused:(s,r)=>{sxe(s)&&W9.set(r,s)},onTokenGranted:s=>{W9.delete(s)}}}var W9=new Map;var Eit=["setup_failed","checkout_failed","environment_unverified"];function rxe(e,t){return t.getTime()>=e.getTime()}function sxe(e){return e instanceof _i||e instanceof So&&e.code!=="CREDENTIALS_UNAVAILABLE"}var vit={cancelled:"Skyramp cancelled this run",expired:"this attempt passed its deadline in Skyramp",ended:"Skyramp already ended this attempt"},bit={cancelled:"attempt-cancelled",expired:"attempt-closed",ended:"attempt-closed"},wit={cancelled:"cancelled",expired:"timed_out",ended:"agent_failed"};var Iit={analyze:"analyze",triage:"analyze",recommend:"recommend",generate:"generate","generate-ui":"generate","generate-unit":"generate",adapt:"generate",write:"generate",onboard:"execute",deploy:"execute","native-run":"execute",deliver:"deliver"},Cit={analyze:"change analysis",recommend:"test recommendations",generate:"test generation",execute:"test execution",deliver:"opening a pull request with the tests"};function Y9(){return je("skyrampAppOrigin").trim()||nxe}var Sit=10*6e4;var kit={onboard:"onboard",deploy:"deploy"},Rit={plan:{stage:"validation_plan",text:"Working out what to validate, and bringing up what it needs"},write:{stage:"tests",text:"Writing and running the tests"},"generate-unit":{stage:"tests",text:"Writing unit tests"},"native-run":{stage:"tests",text:"Running the unit tests"}},Bit=new Set(["write","native-run"]);function ixe(){let e=Us(Di.conflict);if(!e)return;let t;try{t=cq.safeParse(JSON.parse(e))}catch(n){Dt(`Testbot V3: the saved merge conflict is not JSON (${n instanceof Error?n.message:String(n)})`);return}if(t.success)return t.data;Dt(`Testbot V3: the saved merge conflict breaks the contract (${t.error.issues.map(n=>`${n.path.join(".")}: ${n.message}`).join("; ")})`)}function oxe(){let e=Us(Di.githubWrites);if(!e)return[];let t;try{t=JSON.parse(e)}catch(n){return Dt(`Testbot V3: the saved GitHub writes are not JSON (${n instanceof Error?n.message:String(n)})`),[]}return Array.isArray(t)?t.flatMap(n=>{let s=jE.safeParse(n);return s.success?[s.data]:[]}).slice(0,LE):[]}function axe(){let e=Us(Di.credentialNames).split(",").filter(Boolean),t=Rh([...e.map(n=>process.env[n]),...Object.values(Lf()),...q9()]);try{let n=H9(Z9.join(dq(),"outputs"),t);return n&&ls(`Testbot V3: this run uploaded nothing and created ${n.records.length+n.unlisted} record(s) in the shared environment that it did not see removed; sending them to Skyramp.`),n}catch(n){let s=n instanceof Error?n.message:String(n);Dt(`Testbot V3: could not read what this run created in the shared environment (${s})`);return}}async function K9(){let e=Us(Di.attemptId);if(!e)return;let t=Us(Di.reportUploaded)==="true",n=Us(Di.recipeUploaded)==="true",s=Us(Di.revisionsUploaded)==="true",r=Us(Di.deadlineAt),i=Us(Di.cause)||void 0;!i&&!t&&!n&&!s&&r&&rxe(new Date(r),new Date)&&(i="timed_out");let o=Xd().takeIdToken(),a=ixe(),c={attemptId:e,reportUploaded:t,recipeUploaded:n,revisionsUploaded:s,cause:i,...a?{conflict:a}:{},githubWrites:oxe()},u=!t&&!n&&!s?axe():void 0,l;try{l=await kN({...c,...u?{sharedEnvironmentRecords:u}:{}},J9(Y9(),o))}catch(h){if(!u||!(h instanceof So)||h.status!==400)throw h;Dt(`Testbot V3: Skyramp refused the end; ending again without the shared-environment records (${h.message}); the attempt ends without them.`),l=await kN(c,J9(Y9(),o))}let p=Us(Di.recipeStatus);n&&p?ls(`Testbot V3: attempt ended; the setup ended ${p==="ready"?"Ready":"blocked (Needs input)"}.`):ls(`Testbot V3: attempt ended; the run's outcome in Skyramp is ${l.outcome??"not final yet"}.`)}var X9=require("child_process"),Ni=G(require("fs")),_N=G(require("path")),DN=require("string_decoder");var cxe="skyramp-testbot-state",uxe=/^\$\([^)]*\)$/;function lxe(e){for(let[t,n]of Object.entries(e))n!==void 0&&uxe.test(n)&&delete e[t]}function dxe(e){let t={},n=Ni.existsSync(e)?Ni.readFileSync(e,"utf-8"):"",s=/^([^\r\n<]+)<<(\S+)\r?\n([\s\S]*?)\r?\n\2\r?$/gm;for(let r=s.exec(n);r;r=s.exec(n))t[r[1]]=r[3];return t}function e3(e,t={}){let n=t.env??process.env;if(!$a(n))return!1;lxe(n),$Z(n);let s=n.AGENT_TEMPDIRECTORY||n.RUNNER_TEMP;if(s){n.RUNNER_TEMP??=s;let o=_N.join(s,cxe);if(e==="main")Ni.writeFileSync(o,"",{mode:384});else for(let[a,c]of Object.entries(dxe(o)))n[`STATE_${a}`]=c;n.GITHUB_STATE=o;for(let[a,c]of[["GITHUB_OUTPUT","output"],["GITHUB_ENV","env"],["GITHUB_PATH","path"],["GITHUB_STEP_SUMMARY",`summary-${e}.md`]])n[a]=_N.join(s,`skyramp-testbot-${c}`),Ni.writeFileSync(n[a],"",{mode:384})}let r=t.stdout??n===process.env;r&&pxe(n,t.write);let i=n.GITHUB_STEP_SUMMARY;if(r&&i){let o=t.write??(a=>eD(a.replace(/\n$/,"")));process.once("exit",()=>{Ni.existsSync(i)&&Ni.statSync(i).size>0&&o(`${vw("task.uploadsummary",{},i)}
|
|
341
341
|
`)})}return!0}function pxe(e,t){let n=process.stdout.write.bind(process.stdout),s=o=>e[Lg]==="1"?X_(o,e):void n(o.command!==void 0?`${o.command}
|
|
342
342
|
`:o.text??""),r=t??(o=>s({command:o.replace(/\n$/,"")})),i=t??(o=>s({text:o}));process.stdout.write=((o,...a)=>{let c=typeof o=="string"?o:Buffer.from(o).toString("utf-8"),u="";for(let p of c.split(/(?<=\n)/)){let h=p.startsWith("::")?IZ(p):void 0;if(!h){u+=p;continue}u&&i(u),u="";for(let g of h)r(`${g}
|
|
343
343
|
`)}return u&&i(u),a.find(p=>typeof p=="function")?.(),!0})}var fxe=64*1024;function QN(e){let t=new DN.StringDecoder("utf8"),n="",s=r=>e(Ew(r));return{push(r){n+=typeof r=="string"?r:t.write(r);let i=n.lastIndexOf(`
|