@skyramp/testbot-core 0.13.0-v3.203 → 0.13.0-v3.204
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/VERSION.json +1 -1
- package/dist/main.js +4 -4
- package/dist/post.js +4 -4
- package/dist/runner-client.cjs +1 -1
- package/dist/runner-client.d.cts +7 -0
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -346,7 +346,7 @@ ${e.message??""}`));function OOe(e){if(!e.length||!e.every(O_t))return;let t=e.f
|
|
|
346
346
|
`).find(f=>f.trim());n.push({file:i,name:u.fullName||u.title||"(unnamed)",...u.ancestorTitles?.length?{suite:u.ancestorTitles.join(" > ")}:{},status:d,details:d==="Fail"?p?.trim().slice(0,300)??"failed":d==="Pass"?"passed":c?`not run: the file failed before its tests ran (${l})`:"skipped by the test"})}}return n}var Q_t=new Set(["node_modules",".git","dist","build",".venv","venv","__pycache__",".skyramp","coverage",".next"]);function QM(e,t,r,n=3){return FOe(e,s=>CS(t,s),r,n)}function MOe(e,t){let r=Lu(e,t);if(!r||Uu(r)||QM(e,r,[t],1).length)return r?[r]:[];let{stem:n}=SK(t),s=Ge.posix.dirname(t),o=FOe(e,c=>kOe(c)&&(M_t(c)===n||Ge.posix.dirname(c)===s),[t],1)[0],a=o&&Lu(e,o);return a?[a]:[r]}function M_t(e){let[t,r]=D0(e).split("*"),n=Ge.basename(e);return n.slice(t.length,n.length-r.length)}function FOe(e,t,r,n){let s=[],i=5e3,o=l=>{if(i--<=0)return;let u;try{u=es.readdirSync(l,{withFileTypes:!0})}catch{return}for(let d of u){if(i--<=0)return;let p=Ge.join(l,d.name);if(d.isDirectory()){Q_t.has(d.name)||o(p);continue}let f=Ge.relative(e,p).split(Ge.sep).join("/");t(f)&&s.push(f)}};o(Ge.resolve(e));let a=(l,u)=>{let d=l.split("/"),p=u.split("/"),f=0;for(;f<d.length&&f<p.length&&d[f]===p[f];)f++;return f},c=l=>Math.max(0,...r.map(u=>a(l,u)));return s.sort((l,u)=>c(u)-c(l)||l.localeCompare(u)).slice(0,n)}var LOe=require("child_process"),MM=J(require("path")),vS="maintenance-flags.json",UOe=3;function vK(e){let t=e.trim().match(/^(.+):(\d+)$/);return t?{file:t[1].replace(/^\.\//,""),line:Number(t[2])}:void 0}function F_t(e,t){return e.split(/[^A-Za-z0-9_.-]+/).filter(r=>t.has(r))}function FM(e,t){let r=[];for(let n of e){let s=n.staleBecause;if(!s){r.push(`${n.file} is an existing test you changed: give staleBecause \u2014 the requirement the change deliberately alters, and the changed line of application code (path:line) that alters it \u2014 or, if the change is wrong there, restore the test, leave it failing and report it`);continue}F_t(s.requirement,t.requirementIds).length||r.push(`${n.file}: staleBecause names "${s.requirement}", and no requirement or clause id of the plan is in it`);let i=vK(s.line),o=(i?.file??s.line.trim().replace(/^\.\//,"")).replace(/:\d+$/,""),a=t.changedLines.get(o);(!a||i&&a.size>0&&![...a].some(c=>Math.abs(c-i.line)<=UOe))&&r.push(`${n.file}: ${s.line} is not code this change altered, so the change does not replace what the test asserts`)}return r}function $Oe(e,t){let r=new Map;for(let n of e){let s=n.staleBecause?vK(n.staleBecause.line):void 0;if(!s)continue;let i=[...t.defectLines].find(([a])=>{let c=vK(a);return c&&c.file===s.file&&Math.abs(c.line-s.line)<=UOe});if(!i)continue;let o=r.get(i[1])??{at:i[0],files:[]};o.files.includes(n.file)||o.files.push(n.file),r.set(i[1],o)}return[...r].map(([n,{at:s,files:i}])=>{let o=i.length>3?`${i.slice(0,3).join(", ")} and ${i.length-3} more`:i.join(", ");return`${i.length===1?"An existing test was":`${i.length} existing tests were`} updated for a change at ${s}, where the plan also found defect ${n} (${o}): check the updates do not hide it.`})}function qOe(e,t){let r=[],n=o=>o.trim().replace(/^\.\//,""),s=new Map(t.map(o=>[n(o.file),o])),i=new Set(e.map(n));for(let o of t)(o.changed||i.has(n(o.file)))&&!o.ran&&r.push(`${o.file} is an existing test you changed and did not run: re-run it and record its result`);for(let o of i)s.has(o)||r.push(`${o} is an existing test you changed and is not in your result: re-run it and list it with its result`);return r}function L_t(e,t=""){let r=new Map,n,s;for(let i of e.split(`
|
|
347
347
|
`)){let o=i.match(/^--- a\/(.+)$/);o&&(s=o[1]);let a=i.match(/^\+\+\+ b\/(.+)$/);if(a){n=t+a[1];continue}if(i.startsWith("+++ /dev/null")){s&&!r.has(t+s)&&r.set(t+s,new Set),n=void 0;continue}let c=i.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/);if(!c||!n)continue;let l=Number(c[1]),u=c[2]===void 0?1:Number(c[2]),d=r.get(n)??new Set;for(let p=l;p<l+Math.max(u,1);p++)d.add(p);r.set(n,d)}return r}function LM(e,t){return IK([{path:e.repositoryPath,base:t,related:!1},...(e.relatedRepos??[]).map(r=>({path:r.path,base:r.base??"origin/main",related:!0}))])}function IK(e){let t=new Map;for(let r of e){let n="";try{n=(0,LOe.execFileSync)("git",["-C",r.path,"diff","-U0","--no-color",`${r.base}...HEAD`],{encoding:"utf-8",maxBuffer:64*1024*1024})}catch{continue}let s=r.related?`${MM.basename(MM.resolve(r.path))}/`:"";for(let[i,o]of L_t(n,s))t.set(i,o)}return t}function $M(e){let t=/^(.*?)(?:^|\/)__snapshots__\/([^/]+)\.snap$/.exec(e);return t?`${t[1]?`${t[1]}/`:""}${t[2]}`:e}var ts="generate-unit.json";function U_t(e){let{value:t,error:r}=br(e);if(r)return{errors:[r]};let{value:n,errors:s}=xn(g0,t);return s.length?{errors:s}:{output:n,errors:[]}}function ny(e){return U_t(e.stdout)}var HOe=js("generate-unit-schema",(e,t)=>ny(t)),$_t=/(^|\/)(__pycache__|\.pytest_cache|node_modules|coverage|\.vitest)(\/|$)|\.pyc$/;function xK(e){let t="";try{t=(0,jOe.execFileSync)("git",["status","--porcelain","--untracked-files=all"],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]})}catch{return{modified:[],added:[]}}let r=[],n=[];for(let s of t.split(`
|
|
348
348
|
`)){if(!s.trim())continue;let i=s.slice(3).trim().replace(/^"|"$/g,"");$_t.test(i)||i.startsWith(".skyramp/")||(s.startsWith("??")?n:r).push(i)}return{modified:r,added:n}}var UM=String.raw`(?:node:)?(?:http|https|http2|net|tls|dgram)`,q_t=[[/\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+["']${UM}["']|\bimport\s+["']${UM}["']|require\(\s*["']${UM}["']\s*\)|\bimport\(\s*["']${UM}["']\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)"]];function qM(e){return q_t.filter(([t])=>t.test(e)).map(([,t])=>t)}var G_t=/@playwright\/test|\bfrom\s+playwright\b|\bimport\s+playwright\b|["']playwright["']|\bselenium\b|\bpuppeteer\b|\bcypress\b|\bwebdriverio\b|\bpage\.goto\s*\(/;function zOe(e){return qM(e).length===0&&!G_t.test(e)}function j_t(e){let t=[],r=/\b(?:test|it|describe)(?:\.\w+)*\(\s*(['"`])((?:\\.|(?!\1)[^\\])*)\1/g;for(let n=r.exec(e);n;n=r.exec(e))t.push(n[2]);return t}function H_t(e){let t=[],r=/(["'`])((?:\\.|(?!\1)[^\\\n])*)\1/g;for(let n=r.exec(e);n;n=r.exec(e))n[2].trim()&&t.push(n[2]);return t}function z_t(e,t,r,n){if(!Uu(e)){let i=n.replace(/(?:\[[^\]]*\]|\([^)]*\)|<[^>]*>)+$/,"").split(/::|#/).pop().trim(),a=(/\s/.test(i)?i:i.split(".").pop()).replace(/\/.*$/,"").trim();return a&&t.includes(a)?!0:H_t(t).some(c=>n===c||n.endsWith(` ${c}`))}if(e==="pytest"){let s=n.split("::").pop().replace(/\[.*\]$/,"");return new RegExp(`\\bdef\\s+${s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*\\(`).test(t)}return/\.each\s*[(`]/.test(t)?!0:r.some(s=>s&&(n===s||n.endsWith(` ${s}`)))}function V_t(e,t,r=[],n=[],s=new Set){let i=[],o=new Set(e.tests.flatMap(p=>p.covers)),a=new Set((e.journeysNotWritten??[]).map(p=>p.journey.trim()));for(let p of n)!o.has(p)&&!a.has(p)&&i.push(`journey "${p}" has no test and is not in journeysNotWritten \u2014 walk it in one in-process test, or say in journeysNotWritten what it needs that is missing`);let c=new Set((e.defectsNotTested??[]).map(p=>p.id));for(let p of r)!o.has(p)&&!c.has(p)&&i.push(`defect "${p}" has no test and is not in defectsNotTested \u2014 give it a test that reaches it and expects the correct behaviour, or say in defectsNotTested why no in-process test can`);for(let p of e.defectsNotTested??[])r.includes(p.id)||i.push(`defectsNotTested names "${p.id}", which is not a defect the plan found (${r.join(", ")||"none"})`);let l=[...t,...r,...n];for(let p of t)!o.has(p)&&!s.has(p)&&i.push(`behavior "${p}" was planned a new unit test and no file covers it \u2014 every planned new unit test is written`);for(let p of e.tests)for(let f of p.covers)l.includes(f)||i.push(`${p.file}: covers "${f}", which is neither a behavior planned a new unit test nor a defect the plan found (${l.join(", ")||"none"})`);let u=new Set(e.tests.flatMap(p=>p.names.map(f=>`${p.file}::${f.replace(/\[.*\]$/,"")}`))),d=Math.max(2,2*l.length);return u.size>d&&i.push(`${u.size} test functions for ${l.length} planned item(s) \u2014 write the fewest tests that obtain the planned missing evidence (at most ${d}), one focused test per planned item`),i}var W_t=/(^|\/)(fixtures?|__fixtures__|testdata|test_data|data|snapshots?|__snapshots__|mocks?|__mocks__)\//i;function GOe(e,t){if(W_t.test(t))return!1;let r=Lu(e,t);return r?CS(r,t):Vh(t)}function Y_t(e,t){let r=[],n=new Set(e.map(a=>a.file).filter(a=>t.modified.includes(a)&&GOe(t.repo,a))),s=new Set([...t.maintained??[],...n]);for(let a of t.modified)/(^|\/)__snapshots__\/[^/]+\.snap$/.test(a)&&s.has($M(a))||(s.has(a)?GOe(t.repo,a)||r.push(`${a} is listed in "maintained" but is not a test file \u2014 source and fixtures stay as they are`):r.push(`${a} was changed \u2014 change only existing tests the change made stale, each listed in "maintained"; source and fixtures stay as they are`));let i=new Set(e.map(a=>a.file)),o=new Set(t.addedBefore??[]);for(let a of t.added)!i.has(a)&&!o.has(a)&&r.push(`${a} was added but is not a test in tests[] \u2014 write only new test files, and declare each one`);for(let a of e){let c=La.resolve(t.repo,a.file);if(!ds(t.repo,a.file)){r.push(`${a.file} is outside the repository \u2014 write only new test files, in the repository`);continue}if(!IS.existsSync(c)){r.push(`${a.file} does not exist`);continue}!t.added.includes(a.file)&&!n.has(a.file)&&r.push(`${a.file} is not a new file \u2014 write only new test files`);let l=fo(t.repo,a.file),u=Uu(a.framework)||l!==void 0,d=Uu(a.framework)?a.framework:l?.framework??Lu(t.repo,a.file);if(u)Uu(a.framework)&&!CS(a.framework,a.file)&&r.push(`${a.file} is not named the way ${a.framework} discovers tests \u2014 follow the repository's test naming`),l?.framework!==a.framework&&r.push(`${a.file} is ${a.framework}, but the repository runs it with ${l?.framework??"no test framework we can run"} \u2014 use the framework the repository already uses`),l?.wrappedBy&&(a.run?r.push(...Cp(t.repo,a.run).map(A=>`${a.file}: its run ${A}`)):r.push(`${a.file}: the repository runs its ${l.framework} tests with \`${l.wrappedBy}\`, not ${l.framework} itself \u2014 give "run": the repository's own command for only these tests, writing JUnit XML to {junit}`));else{a.run?r.push(...Cp(t.repo,a.run).map(y=>`${a.file}: its run ${y}`)):r.push(`${a.file} is ${a.framework}, which the run has no adapter for \u2014 give "run": the repository's own command for only these tests, writing JUnit XML to {junit}`);let A=d?t.testAffixes?.get(d):void 0;A?.size&&!A.has(D0(a.file))&&r.push(`${a.file} is not named like the repository's existing ${d} tests (${[...A].join(", ")}) \u2014 follow the repository's test naming`)}let p=La.dirname(a.file).split(La.sep).join("/")||".",f=d&&t.testDirs.get(d)||new Set,m=t.placedDir;m!==void 0?m!=="."&&p!==m&&!p.startsWith(`${m}/`)&&r.push(`${a.file} is not in ${m}, where the Target puts unit tests for this repository`):J_t(t.repo,p,f,a.file)||r.push(`${a.file} is not beside any existing ${u?a.framework:`${a.framework} (${d})`} test (${[...f].join(", ")||"none found"}) \u2014 place each test beside the existing tests`);let g=IS.readFileSync(c,"utf-8"),w=j_t(g);for(let A of a.names)z_t(a.framework,g,w,A)||r.push(`${a.file} declares test "${A}", which is not in the file \u2014 names lists the test functions`);for(let A of qM(g))r.push(`${a.file} uses ${A} \u2014 a unit test runs in one process: no network, no running app; mock with the framework's own tools inside the test`)}return r}function J_t(e,t,r,n){if(r.has(t))return!0;let s=o=>{let a=o.split("/"),c=a.findIndex(l=>K_t.test(l));return c<0?void 0:a.slice(0,c+1).join("/")},i=s(t);if(i&&[...r].some(o=>s(o)===i))return!0;if([...r].some(o=>s(o)===void 0)){let o=La.extname(n);try{return IS.readdirSync(La.join(e,t)).some(a=>La.extname(a)===o&&!Vh(a))}catch{return!1}}return!1}var K_t=/^(tests?|spec|specs|__tests__|e2e|testing|integration_tests?)$/i;function X_t(e,t){return VOe(e,t,r=>La.dirname(r).split(La.sep).join("/")||".")}function Z_t(e,t){return VOe(e,t,D0)}function VOe(e,t,r){let n=new Map;for(let s of t){let i=Lu(e,s);!i||!Uu(i)&&!Vh(s)||(n.has(i)||n.set(i,new Set),n.get(i).add(r(s)))}return n}function Yh(e){return fe(e,"triage.json")?.decision!=="targeted_unit"?[]:(fe(e,"analyze.json")?.findings??[]).filter(r=>r.status!=="refuted"&&r.status!=="latent").map(r=>({id:r.id,claim:r.claim,file:r.file,line:r.line,repository:r.repository,severity:r.severity,...r.conflictsWith?.length?{conflictsWith:r.conflictsWith}:{}}))}function $u(e){return fe(e,"triage.json")?.decision!=="targeted_unit"?[]:Qh(fe(e,"plan.json")?.journeys).filter(t=>t.kind==="in-process")}function M0(e){let t=fe(e,"triage.json");return[...new Set((t?.plan??[]).filter(r=>r.mechanism==="new_unit").map(r=>r.behaviorId))]}var WOe={name:"generate-unit-grounded",verify(e,t){let{output:r}=ny(t);if(!r)return{name:this.name,passed:!0};let n=e.prepared,s=$u(e),i=fe(e,"plan.json"),o=V_t(r,M0(e),Yh(e).map(c=>c.id),s.map(c=>c.id),i?new Set(m0(i).keys()):new Set);s.length&&o.push(...GQ(JR(s,{journeys:r.journeys,tests:r.tests,notWritten:(r.journeysNotWritten??[]).map(c=>({case:c.journey,reason:c.missing}))},Tc(e.inputs.repositoryPath,e.inputs.relatedRepos??[]))));for(let c of r.tests){let l=Cc(e.inputs,c.repository);"error"in l&&o.push(`${c.file}: ${l.error}`)}for(let c of ut(e.inputs).filter(l=>l.writable)){let l=r.tests.filter(g=>dr(e.inputs,g.repository)?.path===c.path),u=(r.maintained??[]).filter(g=>dr(e.inputs,g.repository)?.path===c.path).map(g=>g.file),d=n?.checkouts?.[c.slug],{modified:p,added:f}=xK(c.path),m=It(e.inputs,c.slug);o.push(...Y_t(l,{repo:c.path,testDirs:X_t(c.path,d?.existingTests??[]),testAffixes:Z_t(c.path,d?.existingTests??[]),modified:p,added:f,maintained:u,addedBefore:d?.addedBefore,placedDir:vh(e.inputs,c.slug,"unit")}).map(g=>`${m}${g}`))}let a=(r.maintained??[]).filter(c=>c.change==="updated");if(a.length){let c=fe(e,"plan.json"),l=fe(e,"analyze.json"),u=new Set([...(c?.requirements??[]).flatMap(f=>[f.id,...(f.clauses??[]).map(m=>m.id)]),...(l?.behaviors??[]).map(f=>f.id),...(l?.requirements??[]).map(f=>f.id)]),d=Rr(e)?.repository.baseBranch??e.inputs.baseBranch??"origin/main",p=IK([{path:e.inputs.repositoryPath,base:d,related:!1},...(e.inputs.relatedRepos??[]).map(f=>({path:f.path,base:f.base??"origin/main",related:!0}))]);o.push(...FM(a,{requirementIds:u,changedLines:p,defectLines:new Map}))}return o.length?{...Be(this.name,o),repairable:!0}:{name:this.name,passed:!0}}};function RK(e,t){if(!t.some(n=>n.gates.some(s=>!s.passed&&/secrets|checkout-intact/.test(s.name))))for(let n of[...t].reverse()){if(!n.session)continue;let{output:s,errors:i}=ny(n.session);if(s)return Nt(e,"generate-unit",s,i)}}function TK(e,t){let{output:r,errors:n}=ny(t);return Nt(e,"generate-unit",r,n)}var GM="native-run.json",xp=e=>fe(e,GM),kK="no selected unit test ran";function jM(e){if(e.results.some(n=>n.status==="Pass"||n.status==="Fail"))return;let t=new Set([...e.results.map(n=>`${n.file}\0${n.selectedName??n.name}`),...e.notRun.map(n=>`${n.file}\0${n.name??""}`)]).size;if(!t)return;let r=e.notRun.length?[...new Set(e.notRun.map(n=>n.reason))]:["every test that reported was skipped"];return`${kK} (${t} selected): ${r.slice(0,3).join("; ").slice(0,600)}`}var F0=e=>e.name==="native-run"&&e.status==="failed"&&!!e.reason?.includes(kK),BK=e=>e.origin==="written"||!!e.written;function YOe(e,t){let r=e.inputs?.unitPath==="write"&&t.decision==="targeted_unit",n=t.plan.filter(i=>i.mechanism==="existing_unit"||i.mechanism==="new_unit"&&!r),s=r?eDt(e,t.plan.filter(i=>i.mechanism==="new_unit")):[];return n.length===0?s:[...new Set([...s,...tDt(e,n)])]}function eDt(e,t){if(!t.length)return[];let r=fe(e,"write.json");if(!r)return["the planned unit tests were not written (write did not finish)"];let n=new Set((xp(e)?.results??[]).filter(i=>BK(i)&&!i.fromFile&&(i.status==="Pass"||i.status==="Fail")).flatMap(i=>i.behaviorIds)),s=[];for(let i of t){let o=r.tests.filter(c=>c.covers.includes(i.behaviorId)),a=o.some(c=>c.result.cases.some(l=>l.case===i.behaviorId&&(l.status==="pass"||l.status==="fail"))||!c.result.cases.length&&c.result.exit!==null&&c.covers.every(l=>l===i.behaviorId));o.length?!n.has(i.behaviorId)&&!a&&s.push(`${i.behaviorId}: no new unit test for it produced a result`):s.push(`${i.behaviorId}: no new unit test was written${i.covers?` for ${i.covers}`:""}`)}return s}function tDt(e,t){let r=e.state.stages["native-run"],n=xp(e),s=r?.status==="failed"&&!!r.reason?.includes(kK);if(r?.status!=="passed"&&!s||!n)return[`the planned unit tests did not run${r?.reason?` (${r.reason})`:r?` (${r.status})`:""}`];let i=n.notRun.filter(d=>d.origin!=="written").map(d=>`${d.file}${d.name?`::${d.name}`:""} did not run: ${d.reason}`),o=(d,p)=>new Set(n.results.filter(f=>f.origin===d&&(f.status==="Pass"||f.status==="Fail")===p).flatMap(f=>f.behaviorIds)),a={existing:o("existing",!0),generated:o("generated",!0)},c={existing:o("existing",!1),generated:o("generated",!1)},l=fe(e,ts),u=new Set((l?.tests??[]).flatMap(d=>d.covers));for(let d of t)if(d.mechanism==="new_unit"&&!u.has(d.behaviorId))i.push(`${d.behaviorId}: no new unit test was written${d.covers?` for ${d.covers}`:""}`);else{let p=d.mechanism==="new_unit"?"generated":"existing",f=p==="generated"?"new":"existing";a[p].has(d.behaviorId)||i.push(c[p].has(d.behaviorId)?`${d.behaviorId}: every ${f} unit test for it was skipped`:`${d.behaviorId}: no ${f} unit test for it produced a result`)}return[...new Set(i)]}var sy=J(require("fs")),yi=J(require("path"));var rDt=/"(?:@testing-library\/(?:react|vue|svelte|angular|preact|dom|user-event)|jsdom|happy-dom|@vue\/test-utils|enzyme|react-test-renderer)"\s*:/,HM=e=>{try{return sy.statSync(e).size<1e6?sy.readFileSync(e,"utf-8"):""}catch{return""}};function NK(e,t){let r=yi.resolve(e),n=yi.dirname(yi.resolve(r,t));if(yi.relative(r,n).startsWith(".."))return!1;for(;;){if(rDt.test(HM(yi.join(n,"package.json"))))return!0;if(n===r)return!1;n=yi.dirname(n)}}var PK=/(^|\/)(e2e|cypress|playwright|selenium)\/|\.(cy|e2e)\.[cm]?[jt]sx?$/i,eQe=/["']@playwright\/test["']|["']cypress["']|\bcy\.(?:visit|request)\(|\b(?:from|import)\s+selenium\b|\bfrom\s+playwright\b|\bwebdriverio\b|\bpuppeteer\b|\bApplicationSystemTestCase\b/,tQe=/\b(?:Static|Channels)?LiveServerTestCase\b|\blive_server\b/,nDt=/["']@skyramp\/skyramp["']|\b(?:from|import)\s+skyramp\b/,sDt=/https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0)[:/]|\b(?:BASE_URL|API_URL|APP_URL|SUT_URL|baseURL|base_url)\b/,iDt=/\b(?:requests|httpx|aiohttp|urllib|axios|fetch|got|superagent|HttpClient|RestAssured|Faraday|Net::HTTP)\b/,oDt=/\b(?:jest\.mock|vi\.mock|nock|msw|setupServer|responses|respx|requests_mock|httpretty|fetchMock|fetch-mock|MockAdapter|WebMock|mock\.patch)\b/,aDt=/\b(?:BASE_URL|API_URL|APP_URL|SUT_URL)\b/;function _K(e,t){let r=t.split("::")[0].trim().replace(/\\/g,"/"),n=HM(yi.resolve(e,r));if(!(tQe.test(n)&&!aDt.test(n))){if(eQe.test(n)||PK.test(r))return"a browser test of the running app";if(nDt.test(n)||sDt.test(n)&&iDt.test(n)&&!oDt.test(n))return"a test that calls the running app"}}function rQe(e,t){let r=t.split("::")[0].trim().replace(/\\/g,"/"),n=HM(yi.resolve(e,r));return eQe.test(n)||PK.test(r)?"ui":_K(e,r)?"integration":n&&fo(e,r)?"unit":void 0}var JOe=String.raw`\b(?:real browser|browser|javascript|js|htmx|client-side)\b`,KOe=String.raw`\b(?:not|isn't|aren't|never|no)\s+(?:be\s+)?(?:covered|tested|exercised|verified|checked|walked|executed|run)\b|\buncovered\b|\bunverified\b`,cDt=[new RegExp(`${JOe}[^.;\\n]{0,100}(?:${KOe})`,"i"),new RegExp(`(?:${KOe})[^.;\\n]{0,100}${JOe}`,"i")];function lDt(e){return e.filter(t=>!!t?.trim()&&cDt.some(r=>r.test(t))).map(t=>t.trim().slice(0,160))}var uDt=/\b(?:from|import)\s+(?:selenium|playwright)\b/,XOe={depth:6,files:2e3},nQe=e=>{if(!e.endsWith(".py"))return!1;let t=HM(e);return tQe.test(t)&&uDt.test(t)};function dDt(e){let t=XOe.files,r=(n,s)=>{let i;try{i=sy.readdirSync(n,{withFileTypes:!0})}catch{return!1}for(let o of i){if(--t<0)return!1;let a=yi.join(n,o.name);if(o.isFile()&&nQe(a)||o.isDirectory()&&s>0&&!o.name.startsWith(".")&&o.name!=="node_modules"&&r(a,s-1))return!0}return!1};return r(e,XOe.depth)}function ZOe(e,t){let r=yi.resolve(e),n=t.split("::")[0].trim().replace(/\\/g,"/").replace(/\/+$/,""),s=yi.resolve(r,n);if(!n||yi.relative(r,s).startsWith(".."))return!1;let i;try{i=sy.statSync(s).isDirectory()}catch{return!1}return(i?dDt(s):nQe(s))?!0:PK.test(`${n}${i?"/":""}`)?!1:NK(r,i?yi.join(n,"_"):n)}var pDt=/\b(?:selenium|playwright|webdriver|cypress|browser|live[_ -]?server|headless|jsdom|happy-dom|fireEvent|userEvent|user-event|find_element|clicks|presses|types into|drags|hovers|focuses|scrolls)\b|\.click\(|\bsend_keys\b/i,fDt=/\b(?:test client|self\.client|client\.(?:get|post)|assertContains|assertInHTML|response\.content|request-level|markup|html|css class|class(?:es)?|attributes?|rendered|renders|template)\b/i;function hDt(e){let t=e.filter(r=>!!r?.trim());if(!(!t.length||t.some(r=>pDt.test(r))))return t.every(r=>fDt.test(r))?t[0].trim().slice(0,160):void 0}function mDt(e){return new Set(e.filter(t=>t.mechanism==="existing_unit"||t.mechanism==="new_unit").map(t=>t.behaviorId))}function sQe(e,t){let r=mDt(t);return e.action==="verify"&&!!e.clauses?.length&&e.clauses.every(n=>r.has(n))}function iQe(e,t,r){return!e?.maintenance||!t?new Set:new Set(e.maintenance.filter(n=>sQe(n,t.plan)).filter(n=>{let{root:s,rel:i}=r(n.test);return _K(s,i)&&!t.gaps.some(o=>o.missing.includes(i)||o.missing.includes(n.test))}).map(n=>n.test))}var gDt=e=>e.trim().replace(/:\d+(?:-\d+)?$/,"");function ADt(e,t){let r=gDt(e);return r?t.some(n=>n===r||n.endsWith(`/${r}`)||r.endsWith(`/${n}`)||r.endsWith("/")&&(n.startsWith(r)||n.includes(`/${r}`))):!1}function zM(e,t,r){let n=new Set;for(let s of e.requirements)for(let i of s.clauses)s.source!=="could-break"&&(r||!i.code?.trim()||ADt(i.code,t))&&n.add(i.id);return n}var oQe=/\b[A-Z][A-Za-z0-9-]*\d+[a-z]\b/g;function aQe(e,t,r){let n=e.behaviorId?.trim()?[e.behaviorId.trim()]:e.missing.match(oQe)??[];return n.length>0&&n.every(s=>t.has(s)&&!r.has(s))}var yDt=new Set(["targeted_unit","existing_evidence_sufficient"]);function cQe(e,t){let r=e.triage?.decision;if(!r||!yDt.has(r))return[];let n=[],s=e.triage,i=c=>!t.own||t.own.has(c),o=new Set(e.requirements.flatMap(c=>c.clauses).filter(c=>c.type==="contract"||c.type==="integration").map(c=>c.id)),a=c=>{let l=c.steps.flatMap(u=>u.clauses??[]);return!!t.own&&l.length>0&&!l.some(u=>i(u)&&!o.has(u))};for(let c of e.journeys??[]){if(t.runtimePossible&&c.kind!=="in-process"&&a(c)){n.push(`journey ${c.id} walks only what the change could break elsewhere or UI code it does not touch, which does not make the decision runtime_required: off the runtime path list its clauses under notInJourney with why (downstream of this change, not walked here) and drop the journey`);continue}if(!t.runtimePossible){c.kind!=="in-process"&&n.push(`journey ${c.id} needs a browser and this run starts no app: when the app cannot be run here, list each such journey's clauses under notInJourney with what is missing, and drop the journey`);continue}if(c.kind!=="in-process"){n.push(`journey ${c.id} is a browser journey, which needs the running app: decide runtime_required when any journey needs a browser, and mark runtime the clauses its steps exercise`);continue}let{root:l,rel:u}=t.locate(c.testFile);if(a(c)&&!NK(l,u)){n.push(`journey ${c.id} is planned in-process for what the change could break elsewhere, and no in-process UI test harness covers ${c.testFile}: that does not make the decision runtime_required \u2014 list its clauses under notInJourney with why and drop the journey`);continue}NK(l,u)||n.push(`journey ${c.id} is planned in-process, and no in-process UI test harness (Testing Library, jsdom, happy-dom, Vue Test Utils, Enzyme) covers ${c.testFile}: a request-level test client does not walk a journey. Decide runtime_required and make it a browser journey \u2014 in-process only where the repo's own in-process UI tests can walk and check all of it`)}if(t.runtimePossible){let c=lDt([s.rationale,...s.gaps.filter(l=>!l.behaviorId||i(l.behaviorId)).map(l=>l.missing),...(e.notInJourney??[]).filter(l=>i(l.clause)).map(l=>l.why),...e.requirements.flatMap(l=>l.clauses.filter(u=>i(u.id)).map(u=>u.skip))]).filter(l=>{let u=l.match(oQe)??[];return!(u.length&&u.every(d=>!i(d)))});for(let l of c)n.push(`the plan says "${l}": a browser part the plan itself says goes untested needs the running app \u2014 decide runtime_required and mark runtime the clauses it checks`)}for(let c of e.maintenance){let{root:l,rel:u}=t.locate(c.test),d=_K(l,u);if(!d||t.runtimePossible&&sQe(c,s.plan))continue;let p=()=>s.gaps.some(f=>f.missing.includes(u)||f.missing.includes(c.test));if(t.own&&c.clauses?.length&&!c.clauses.some(f=>i(f))){p()||n.push(`maintenance ${c.test} is ${d} and checks only ${c.clauses.join(", ")}, which the change does not itself alter, so it does not make the decision runtime_required: name such a test under gaps with what is missing (the running app, downstream of this change)`);continue}if(!t.runtimePossible){p()||n.push(`maintenance ${c.test} is ${d} and this run starts no app: when the app cannot be run here, name each such test under gaps with what is missing`);continue}n.push(`maintenance ${c.test} is ${d}, which the unit path cannot run: decide runtime_required when any test under "maintenance" calls the deployed app, and mark runtime the clauses it checks, so it is verified against the app (a live-server test that starts its own server in the test process stays on the unit path)`+(c.action==="verify"?'. If it is only to verify, give its "clauses": one whose every clause an existing_unit or new_unit test here establishes keeps the plan on the unit path':""))}for(let c of e.findings??[]){if(!c.needsApp)continue;let l=c.needsApp==="browser"?"a browser":"the running app's API";if(!t.runtimePossible){if(s.gaps.some(u=>u.behaviorId===c.id||u.missing.includes(c.id)))continue;n.push(`finding ${c.id} needs ${l} to show it and this run starts no app: when the app cannot be run here, name it under gaps with what is missing`);continue}n.push(`finding ${c.id} needs ${l} to show it, which the unit path cannot do: a defect you found that only the running app can show makes the decision runtime_required wherever its code is \u2014 decide runtime_required and give it its case`)}return n.push(...EDt(e,t)),n}function EDt(e,t){let r=[],n=e.triage?.gaps??[],s=i=>n.some(o=>o.behaviorId===i||o.missing.includes(i));for(let i of e.requirements.flatMap(o=>o.clauses)){if(!i.browserOnly||i.skip?.trim())continue;let o=[i.steps,...(e.cases??[]).filter(u=>u.clause===i.id).map(u=>u.steps)],a=hDt(o);if(t.own&&!t.own.has(i.id)){let u=i.browserHarness?.trim(),d=u?t.locate(u):void 0;if(d&&!a&&ZOe(d.root,d.rel)||s(i.id))continue;r.push(`clause ${i.id} is browser-only and checks what the change could break elsewhere or UI code it does not touch, which does not make the decision runtime_required: list its clauses under notInJourney and the browser-only ones under gaps, with what is missing (a browser, downstream of this change), unless the repo's in-process browser suite (browserHarness) tests it`);continue}if(a){r.push(`clause ${i.id} is browser-only and its only test checks markup ("${a}"): a browser-only clause needs a browser test; a markup check may be added, not substituted \u2014 drive the behaviour in the repo's in-process browser harness (browserHarness), else decide runtime_required with a browser test of it`);continue}let c=i.browserHarness?.trim();if(c){let{root:u,rel:d}=t.locate(c);if(ZOe(u,d))continue}let l=c?`${c} is no in-process browser suite of the repo's (a Django LiveServerTestCase or StaticLiveServerTestCase, or pytest-django live_server, test that drives Selenium or Playwright; or component tests under a DOM test harness)`:"it names no in-process browser harness (browserHarness)";if(!t.runtimePossible){if(n.some(u=>u.behaviorId===i.id||u.missing.includes(i.id)))continue;r.push(`clause ${i.id} is browser-only, ${l}, and this run starts no app: a browser-only clause with no in-process browser harness: name it under gaps with what is missing`);continue}r.push(`clause ${i.id} is browser-only and ${l}: test it in the repo's in-process browser harness and name that suite as browserHarness, else decide runtime_required with a browser test of it, and mark the clause runtime`)}return r}var bDt="triage.json",SDt=new Set(["existing_evidence","unaffected","existing_unit","new_unit","runtime"]),CDt={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 TS(e){return e.some(t=>Z4.has(t.mechanism))}function vDt(e){let{value:t,error:r}=br(e);if(r)return{errors:[r]};let{value:n,errors:s}=xn(KA,t);return s.length?{errors:s}:{triage:n,errors:[]}}function DK(e){return vDt(e.stdout)}var lQe=js("triage-schema",(e,t)=>DK(t)),VM=e=>e.trim().replace(/\s+/g," ");function uQe(e,t){let r=[],n=new Set(t.behaviorIds),s=new Map(t.ci.map(g=>[g.id,g])),i=new Map(e.evidence.map(g=>[g.id,g])),o=new Set(e.plan.map(g=>g.mechanism)),a=e.decision==="blocked_preflight",c=new Set;for(let g of e.evidence)(c.has(g.id)||s.has(g.id))&&r.push(`evidence id "${g.id}" is used twice (every id is unique, and ci-<n> ids belong to the CI results)`),c.add(g.id);let l=e.outOfScope??[];for(let g of[...e.plan,...e.gaps,...l])g.behaviorId!==void 0&&!n.has(g.behaviorId)&&r.push(`behaviorId "${g.behaviorId}" is not one of analyze's behaviors (${[...n].join(", ")||"none"})`);if(!a){let g=new Set([...e.plan.map(w=>w.behaviorId),...e.gaps.map(w=>w.behaviorId??""),...l.map(w=>w.behaviorId)]);for(let w of n)g.has(w)||r.push(`behavior "${w}" is neither planned, listed in gaps, nor listed under outOfScope \u2014 every behavior analyze found is accounted for, so the scope never shrinks silently`)}let u=new Set([...e.plan.map(g=>g.behaviorId),...e.gaps.map(g=>g.behaviorId??"")]);for(let g of l){let w=`outOfScope "${g.behaviorId}"`;u.has(g.behaviorId)&&r.push(`${w} is also planned or listed in gaps: a behavior out of scope plans nothing`);let A=C=>t.sources.some(v=>RS.existsSync(xS.join(v.path,C)))?C:t.changedFiles.map(v=>v.path).find(v=>v.endsWith(`/${C}`)),y=C=>{let v=t.sources.map(R=>R.path).find(R=>RS.existsSync(xS.join(R,C)));return v?RS.readFileSync(xS.join(v,C),"utf-8").split(`
|
|
349
|
-
`).length:0},S=[...g.reason.matchAll(/([\w./@+-]+\.[A-Za-z]\w*):(\d+)/g)].flatMap(C=>{let v=A(C[1].replace(/^\.\//,"")),R=Number(C[2]);return v&&R>=1&&R<=y(v)?[`${v}:${R}`]:[]});S.length===0?r.push(`${w}: cite the unchanged line that decides it (path:line of a file in the repository) in its reason`):t.changedRanges&&S.every(C=>oNe(C,t.changedRanges))&&r.push(`${w} cites ${S.join(", ")}, lines this change modifies \u2014 a behavior the change alters is never out of scope; move it from outOfScope into the plan`)}switch(e.decision){case"existing_evidence_sufficient":{[...o].every(w=>w==="existing_evidence"||w==="unaffected")&&e.gaps.length===0||r.push(`existing_evidence_sufficient means every behavior in scope is established by existing evidence, with no gaps \u2014 this plan also needs ${[...o].filter(w=>w!=="existing_evidence"&&w!=="unaffected").join(", ")||"the evidence named in gaps"}`);break}case"targeted_unit":(![...o].some(g=>r_e.has(g))||TS(e.plan))&&r.push(`targeted_unit plans unit tests and nothing that needs a running app \u2014 this plan has ${[...o].join(", ")||"nothing"}`);break;case"runtime_required":TS(e.plan)||r.push(`runtime_required marks at least one behavior runtime \u2014 this plan has ${[...o].join(", ")||"nothing"}`),o.has("new_unit")&&r.push("runtime_required plans no new unit tests \u2014 this plan has new_unit; mark those behaviors runtime, and keep existing_unit for the existing tests");break;case"blocked_preflight":break}a&&!e.blocked&&r.push('blocked_preflight names the changed file the failure is in, under "blocked"'),!a&&e.blocked&&r.push('"blocked" is only for blocked_preflight'),a&&e.plan.length>0&&r.push("blocked_preflight plans nothing: a change that cannot meet its prerequisites is not validated further");let d=(g,w)=>{let A=QA(t.sources,g);return!!A&&Bb(t.changedFiles,A.slug,w)},p=(g,w)=>RS.existsSync(xS.join(g,w));e.blocked&&!d(e.blocked.repository,e.blocked.file)&&r.push(`blocked.file "${e.blocked.file}" is not a file this change touches \u2014 a failure elsewhere is not the change's prerequisite`);for(let g of e.plan){let w=`plan item for "${g.behaviorId}" (${g.mechanism})`;for(let A of g.evidenceIds)!s.has(A)&&!i.has(A)&&r.push(`${w} cites "${A}", which is neither a ci-<n> result nor an evidence id`);if(g.mechanism==="unaffected"){let A=t.behaviorFiles?.get(g.behaviorId),y=/([\w./-]+\.[\w]+):\d+/.exec(g.covers??"")?.[1];if(A&&d(A.repository,A.file)){let S=`${m4(t.sources,A.repository)}${A.file}`;r.push(`${w}: ${S} is changed by this PR, so the change can reach this behavior \u2014 unaffected is never for a behavior in a changed file`)}(!y||!t.sources.some(S=>p(S.path,y)))&&r.push(`${w}: say under "covers" why the change cannot reach it, and cite the code that shows it (path:line of a file in the repository)`)}if(g.mechanism==="existing_evidence"){let A=g.evidenceIds.filter(C=>{let v=s.get(C);if(v)return v.status==="accepted"&&v.kind!=="code_review";let R=i.get(C);return R?.source==="testbot"&&R.outcome==="passed"&&R.kind!=="code_review"}),y=g.evidenceIds.map(C=>s.has(C)?`${C} is ${s.get(C).status}`:`${C} is ${i.get(C)?.outcome??"unknown"}`);A.length===0&&r.push(`${w}: only accepted ci-<n> items and checks you ran that passed can establish a behavior${y.length?` \u2014 ${y.join(", ")}`:" \u2014 it cites nothing"}`),A.length===0&&g.evidenceIds.some(C=>s.get(C)?.kind==="code_review"||i.get(C)?.kind==="code_review")&&r.push(`${w}: AI review is advisory \u2014 it cannot establish a behavior on its own`)}g.mechanism==="existing_unit"&&g.evidenceIds.map(y=>i.get(y)).filter(y=>y?.source==="repository"&&(y.tests?.length??0)>0).length===0&&r.push(`${w}: existing_unit names the repository evidence listing the tests to run`),(g.mechanism==="new_unit"||Z4.has(g.mechanism))&&!g.covers?.trim()&&r.push(`${w}: say under "covers" the missing evidence this obtains`)}let f=t.ranCommands.map(VM),m=new Set(e.plan.filter(g=>g.mechanism==="existing_evidence").flatMap(g=>g.evidenceIds));for(let g of e.evidence){if(g.source==="repository"){if(!g.tests?.length){r.push(`evidence "${g.id}" is repository evidence and lists no tests \u2014 list the unit tests that exercise the change, or remove the item, and drop its id from any plan item that cites it. Absence of tests is not evidence: say in the rationale that no tests exist`);continue}let w=e.plan.some(v=>v.mechanism==="existing_unit"&&v.evidenceIds.includes(g.id)),A=e.decision==="existing_evidence_sufficient";!(w||A&&m.has(g.id))&&e.decision!=="blocked_preflight"&&r.push(A?`evidence "${g.id}" identifies existing tests that no existing_evidence item cites \u2014 existing tests you identify are run, and under existing_evidence_sufficient they are cited by the existing_evidence item they support`:`evidence "${g.id}" identifies existing tests that no existing_unit item runs \u2014 existing tests you identify are run: plan existing_unit for the behaviors they exercise, or, if these tests call the running app, move them from evidence to maintenance: they are not evidence`);let S=QA(t.sources,g.repository);S||r.push(`evidence "${g.id}" names ${g.repository}, which is not a repository of this run (${t.sources.map(v=>v.slug).join(", ")}) \u2014 name the owner/repo the tests live in`);let C=t.sources.length>1?'; a test in another checkout: name its "repository"':"";for(let v of g.tests??[]){let R=v.split("::")[0];if(S&&!p(S.path,R))r.push(`evidence "${g.id}" names ${R}, which does not exist in ${S.slug} (tests are repo-relative paths${C})`);else if(S&&w&&!g.run){let T=fo(S.path,R);T?T.wrappedBy&&r.push(`evidence "${g.id}" runs ${R}, which the repository runs with \`${T.wrappedBy}\`, not ${T.framework} itself \u2014 give "run": the repository's own command for only these tests, writing JUnit XML to {junit}`):r.push(`evidence "${g.id}" runs ${R}, which pytest, Jest, Vitest and node --test do not run \u2014 give "run": the repository's own command for only these tests, writing JUnit XML to {junit}`)}}S&&w&&g.run&&r.push(...Cp(S.path,g.run).map(v=>`evidence "${g.id}": its run ${v}`))}if(g.source==="testbot"&&m.has(g.id)&&!dQe(g.command,f)){let w=VM(g.command??"");r.push(`evidence "${g.id}" establishes a behavior but is a check this session never ran${w?` ("${w.slice(0,80)}")`:""} \u2014 give the exact command you ran`)}}return r}function dQe(e,t){let r=s=>s.replace(/\\/g,""),n=r(VM(e??""));return!!n&&t.map(r).some(s=>s===n||s.includes(n)||n.includes(s))}function IDt(e,t){let r=t.map(VM);return e.evidence.filter(n=>n.source!=="testbot"||dQe(n.command,r))}function YM(e,t="triage",r){let n=r??fe(e,"analyze.json")?.behaviors;if(!n)return;let s=fe(e,uQ),i=ut(e.inputs);return{behaviorIds:n.map(o=>o.id),behaviorFiles:new Map(n.map(o=>[o.id,{repository:o.repository,file:o.evidence.split(":")[0]}])),ci:s?.items??[],changedFiles:Sc(Rr(e)??{changedFiles:[]},Rn(e.inputs).slug),sources:i,ranCommands:wPe(e.outputsDir,t).flatMap(LQ),changedRanges:iNe(e)}}var pQe={name:"triage-grounded",verify(e,t){let{triage:r}=DK(t);if(!r)return{name:this.name,passed:!0};let n=YM(e);if(!n)return Be(this.name,["analyze.json is missing \u2014 nothing to ground the decision against"],{fatal:!0});let s=uQe(r,n);return s.length?Be(this.name,s):{name:this.name,passed:!0}}};function fQe(e,t,r){return{...t,evidence:IDt(t,r),sutRequired:TS(t.plan),budgetMinutes:e.inputs.budgetMinutes,ciEvidence:fe(e,uQ)?.items??[]}}function hQe(e,t){let{triage:r,errors:n}=DK(t),s=YM(e)?.ranCommands??[];return Nt(e,"triage",r&&fQe(e,r,s),n)}function mQe(e,t){let r=new Set(t),n=e.outOfScope?.filter(i=>r.has(i.behaviorId)),s=e.gaps.map(i=>i.behaviorId===void 0||r.has(i.behaviorId)?i:{missing:`${i.behaviorId}: ${i.missing}`});return{...e,gaps:s,...e.outOfScope?{outOfScope:n}:{}}}function OK(e,t,r,n){if(!t)return['save the validation triage decision as "triage" in the plan'];let s=YM(e,"plan",n);if(!s)return["analyze.json is missing \u2014 nothing to ground the decision against"];let i=mQe(t,s.behaviorIds),o=uQe(i,s);return r&&!TS(i.plan)&&o.push(`the plan brought the app up, though its decision (${i.decision}) needs no running application`),o}function QK(e,t,r,n){if(!t)return["the plan made no validation triage decision"];let s=OK(e,t,r,n);return s.length?[`the plan's validation triage does not hold: ${s.join("; ")}`]:[]}function gQe(e,t){let r=YM(e,"plan"),n=mQe(t,r?.behaviorIds??[]);return Nt(e,"triage",fQe(e,n,r?.ranCommands??[]),[])}function AQe(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 MK(e,t=Ho(e)){let r=fe(e,"plan.json"),n=Rr(e);if(!t?.gaps.length||!r?.requirements?.length||!n)return[];let s=Sc(n,"").map(a=>a.path),i=zM(r,s,YR(s).length>0),o=new Set(r.requirements.flatMap(a=>a.clauses.map(c=>c.id)));return t.gaps.filter(a=>aQe(a,o,i))}function Ho(e){if(AQe(e)?.status==="passed")return xu(xS.join(e.outputsDir,bDt))}function Fn(e){return e.inputs?.unitPath==="write"&&Ho(e)?.decision==="targeted_unit"}function xDt(e){let t=Ho(e);if(!t?.sutRequired||Fn(e))return!1;let r=new Set(t.plan.filter(n=>n.mechanism==="runtime").map(n=>n.behaviorId));for(let n of fe(e,"plan.json")?.cases??[])n.clause&&r.has(n.clause)&&r.add(n.id);return(fe(e,"adapt.json")?.items??[]).some(n=>n.reran?.tests?.length?n.reran.tests.some(s=>s.status==="pass"&&r.has(s.case)):n.reran?.exit===0&&(n.covers??[]).some(s=>r.has(s)))}function JM(e){return fe(e,"deploy.json")?.outcome==="bringup-failed"&&xDt(e)}function kS(e){return DNe(xQ(e.inputs,fe(e,`${vs}.json`),Ho(e)?.sutRequired))}function yQe(e,t){if(!e.triageBranch&&!(e.name&&RDt.has(e.name)))return;let r=Ho(t);if(r){if(r.decision==="existing_evidence_sufficient")return`${L0.runtime}${r.decision}: existing evidence establishes this change, so no test is written or run`;if(t.inputs?.unitPath==="write"&&r.decision==="targeted_unit"){if(e.name==="write")return;if(e.name==="generate-unit")return`${L0.noRuntime}${r.decision}, and write writes its unit tests (unit path write)`}if(e.triageBranch==="runtime"&&!r.sutRequired)return`${L0.runtime}${r.decision}, which needs no running application`;if(e.triageBranch==="no-runtime"&&r.sutRequired)return`${L0.noRuntime}${r.decision}, which needs the running application`}}var RDt=new Set(["deploy","recommend","generate","generate-ui","adapt","generate-unit","native-run","finalize","deliver"]),L0={runtime:"not needed \u2014 validation triage decided ",noRuntime:"not on this run's path \u2014 validation triage decided "};function EQe(e){return!!e&&Object.values(L0).some(t=>e.startsWith(t))}function wQe(e,t){if(!e.branchRequires)return[...e.requires];let r=Ho(t),n=r&&!r.sutRequired&&!Fn(t)?"no-runtime":"runtime";return[...e.requires,...e.branchRequires[n]??[]]}function FK(e){return[...new Set([...e.requires,...e.softRequires??[],...Object.values(e.branchRequires??{}).flat()])]}var TDt=/run budget exhausted/;function LK(e,t){let r=AQe(e);if(!r)return;let n=Ho(e);if(!n)return{sufficiency:"insufficient",rationale:"Validation triage did not complete, so nothing established what evidence this change needs.",gaps:[`validation triage did not complete (${r.reason??r.status})`],acceptedEvidence:[],actionRequired:[]};let s=new Set(MK(e,n)),i=n.gaps.filter(g=>!s.has(g)).map(g=>g.behaviorId?`${g.behaviorId}: ${g.missing}`:g.missing),o=new Set;for(let g of n.plan)SDt.has(g.mechanism)||i.push(`${g.behaviorId}: ${CDt[g.mechanism]} is not available in this run${g.covers?` (${g.covers})`:""}`);n.blocked&&i.push(`the change does not meet a prerequisite: ${n.blocked.reason} (${n.blocked.file})`),i.push(...YOe(e,n));let a=n.sutRequired?jb(e):[],c=n.sutRequired?RQ(e.inputs?.sharedEnvironment):[],l=!!e.inputs?.appRunning;i.push(...a.map(g=>MNe(g,l)),...c.map(g=>ONe(g,l))),(a.length||c.length)&&o.add("sut_revision_mismatch");let u=TQ(e);i.push(...u.map(FNe));let d=n.sutRequired?mPe(e):[];if(i.push(...d),(u.length||d.length)&&o.add("isolation_unavailable"),n.sutRequired&&!qR(e)&&!JM(e)){let g=e.state.stages.deploy;i.push(`the running application was needed and was not available${g?.reason?` (${g.reason})`:""}`),o.add("deployment_review")}else t.some(g=>g.kind==="tests-not-executed")&&i.push("the planned tests were written but not run");let p=Object.entries(e.state.stages).filter(([,g])=>g&&TDt.test(g.reason??"")).map(([g])=>g);p.length&&i.push(`the execution budget ran out before ${p.join(", ")} finished`);let f=new Set(n.plan.filter(g=>g.mechanism==="existing_evidence").flatMap(g=>g.evidenceIds)),m=n.ciEvidence.filter(g=>g.status==="accepted"&&f.has(g.id)).map(g=>({kind:g.kind,repository:g.repository,revision:g.revision,reference:g.reference,summary:g.summary}));return{sufficiency:i.length?"insufficient":"sufficient",rationale:n.rationale,gaps:i,acceptedEvidence:m,actionRequired:[...o]}}var SQe={async render(){}};function U0(e=t=>console.log(t)){return{async render(t){let r=t.split(`
|
|
349
|
+
`).length:0},S=[...g.reason.matchAll(/([\w./@+-]+\.[A-Za-z]\w*):(\d+)/g)].flatMap(C=>{let v=A(C[1].replace(/^\.\//,"")),R=Number(C[2]);return v&&R>=1&&R<=y(v)?[`${v}:${R}`]:[]});S.length===0?r.push(`${w}: cite the unchanged line that decides it (path:line of a file in the repository) in its reason`):t.changedRanges&&S.every(C=>oNe(C,t.changedRanges))&&r.push(`${w} cites ${S.join(", ")}, lines this change modifies \u2014 a behavior the change alters is never out of scope; move it from outOfScope into the plan`)}switch(e.decision){case"existing_evidence_sufficient":{[...o].every(w=>w==="existing_evidence"||w==="unaffected")&&e.gaps.length===0||r.push(`existing_evidence_sufficient means every behavior in scope is established by existing evidence, with no gaps \u2014 this plan also needs ${[...o].filter(w=>w!=="existing_evidence"&&w!=="unaffected").join(", ")||"the evidence named in gaps"}`);break}case"targeted_unit":(![...o].some(g=>r_e.has(g))||TS(e.plan))&&r.push(`targeted_unit plans unit tests and nothing that needs a running app \u2014 this plan has ${[...o].join(", ")||"nothing"}`);break;case"runtime_required":TS(e.plan)||r.push(`runtime_required marks at least one behavior runtime \u2014 this plan has ${[...o].join(", ")||"nothing"}`),o.has("new_unit")&&r.push("runtime_required plans no new unit tests \u2014 this plan has new_unit; mark those behaviors runtime, and keep existing_unit for the existing tests");break;case"blocked_preflight":break}a&&!e.blocked&&r.push('blocked_preflight names the changed file the failure is in, under "blocked"'),!a&&e.blocked&&r.push('"blocked" is only for blocked_preflight'),a&&e.plan.length>0&&r.push("blocked_preflight plans nothing: a change that cannot meet its prerequisites is not validated further");let d=(g,w)=>{let A=QA(t.sources,g);return!!A&&Bb(t.changedFiles,A.slug,w)},p=(g,w)=>RS.existsSync(xS.join(g,w));e.blocked&&!d(e.blocked.repository,e.blocked.file)&&r.push(`blocked.file "${e.blocked.file}" is not a file this change touches \u2014 a failure elsewhere is not the change's prerequisite`);for(let g of e.plan){let w=`plan item for "${g.behaviorId}" (${g.mechanism})`;for(let A of g.evidenceIds)!s.has(A)&&!i.has(A)&&r.push(`${w} cites "${A}", which is neither a ci-<n> result nor an evidence id`);if(g.mechanism==="unaffected"){let A=t.behaviorFiles?.get(g.behaviorId),y=/([\w./-]+\.[\w]+):\d+/.exec(g.covers??"")?.[1];if(A&&d(A.repository,A.file)){let S=`${m4(t.sources,A.repository)}${A.file}`;r.push(`${w}: ${S} is changed by this PR, so the change can reach this behavior \u2014 unaffected is never for a behavior in a changed file`)}(!y||!t.sources.some(S=>p(S.path,y)))&&r.push(`${w}: say under "covers" why the change cannot reach it, and cite the code that shows it (path:line of a file in the repository)`)}if(g.mechanism==="existing_evidence"){let A=g.evidenceIds.filter(C=>{let v=s.get(C);if(v)return v.status==="accepted"&&v.kind!=="code_review";let R=i.get(C);return R?.source==="testbot"&&R.outcome==="passed"&&R.kind!=="code_review"}),y=g.evidenceIds.map(C=>s.has(C)?`${C} is ${s.get(C).status}`:`${C} is ${i.get(C)?.outcome??"unknown"}`);A.length===0&&r.push(`${w}: only accepted ci-<n> items and checks you ran that passed can establish a behavior${y.length?` \u2014 ${y.join(", ")}`:" \u2014 it cites nothing"}`),A.length===0&&g.evidenceIds.some(C=>s.get(C)?.kind==="code_review"||i.get(C)?.kind==="code_review")&&r.push(`${w}: AI review is advisory \u2014 it cannot establish a behavior on its own`)}g.mechanism==="existing_unit"&&g.evidenceIds.map(y=>i.get(y)).filter(y=>y?.source==="repository"&&(y.tests?.length??0)>0).length===0&&r.push(`${w}: existing_unit names the repository evidence listing the tests to run`),(g.mechanism==="new_unit"||Z4.has(g.mechanism))&&!g.covers?.trim()&&r.push(`${w}: say under "covers" the missing evidence this obtains`)}let f=t.ranCommands.map(VM),m=new Set(e.plan.filter(g=>g.mechanism==="existing_evidence").flatMap(g=>g.evidenceIds));for(let g of e.evidence){if(g.source==="repository"){if(!g.tests?.length){r.push(`evidence "${g.id}" is repository evidence and lists no tests \u2014 list the unit tests that exercise the change, or remove the item, and drop its id from any plan item that cites it. Absence of tests is not evidence: say in the rationale that no tests exist`);continue}let w=e.plan.some(v=>v.mechanism==="existing_unit"&&v.evidenceIds.includes(g.id)),A=e.decision==="existing_evidence_sufficient";!(w||A&&m.has(g.id))&&e.decision!=="blocked_preflight"&&r.push(A?`evidence "${g.id}" identifies existing tests that no existing_evidence item cites \u2014 existing tests you identify are run, and under existing_evidence_sufficient they are cited by the existing_evidence item they support`:`evidence "${g.id}" identifies existing tests that no existing_unit item runs \u2014 existing tests you identify are run: plan existing_unit for the behaviors they exercise, or, if these tests call the running app, move them from evidence to maintenance: they are not evidence`);let S=QA(t.sources,g.repository);S||r.push(`evidence "${g.id}" names ${g.repository}, which is not a repository of this run (${t.sources.map(v=>v.slug).join(", ")}) \u2014 name the owner/repo the tests live in`);let C=t.sources.length>1?'; a test in another checkout: name its "repository"':"";for(let v of g.tests??[]){let R=v.split("::")[0];if(S&&!p(S.path,R))r.push(`evidence "${g.id}" names ${R}, which does not exist in ${S.slug} (tests are repo-relative paths${C})`);else if(S&&w&&!g.run){let T=fo(S.path,R);T?T.wrappedBy&&r.push(`evidence "${g.id}" runs ${R}, which the repository runs with \`${T.wrappedBy}\`, not ${T.framework} itself \u2014 give "run": the repository's own command for only these tests, writing JUnit XML to {junit}`):r.push(`evidence "${g.id}" runs ${R}, which pytest, Jest, Vitest and node --test do not run \u2014 give "run": the repository's own command for only these tests, writing JUnit XML to {junit}`)}}S&&w&&g.run&&r.push(...Cp(S.path,g.run).map(v=>`evidence "${g.id}": its run ${v}`))}if(g.source==="testbot"&&m.has(g.id)&&!dQe(g.command,f)){let w=VM(g.command??"");r.push(`evidence "${g.id}" establishes a behavior but is a check this session never ran${w?` ("${w.slice(0,80)}")`:""} \u2014 give the exact command you ran`)}}return r}function dQe(e,t){let r=s=>s.replace(/\\/g,""),n=r(VM(e??""));return!!n&&t.map(r).some(s=>s===n||s.includes(n)||n.includes(s))}function IDt(e,t){let r=t.map(VM);return e.evidence.filter(n=>n.source!=="testbot"||dQe(n.command,r))}function YM(e,t="triage",r){let n=r??fe(e,"analyze.json")?.behaviors;if(!n)return;let s=fe(e,uQ),i=ut(e.inputs);return{behaviorIds:n.map(o=>o.id),behaviorFiles:new Map(n.map(o=>[o.id,{repository:o.repository,file:o.evidence.split(":")[0]}])),ci:s?.items??[],changedFiles:Sc(Rr(e)??{changedFiles:[]},Rn(e.inputs).slug),sources:i,ranCommands:wPe(e.outputsDir,t).flatMap(LQ),changedRanges:iNe(e)}}var pQe={name:"triage-grounded",verify(e,t){let{triage:r}=DK(t);if(!r)return{name:this.name,passed:!0};let n=YM(e);if(!n)return Be(this.name,["analyze.json is missing \u2014 nothing to ground the decision against"],{fatal:!0});let s=uQe(r,n);return s.length?Be(this.name,s):{name:this.name,passed:!0}}};function fQe(e,t,r){return{...t,evidence:IDt(t,r),sutRequired:TS(t.plan),budgetMinutes:e.inputs.budgetMinutes,ciEvidence:fe(e,uQ)?.items??[]}}function hQe(e,t){let{triage:r,errors:n}=DK(t),s=YM(e)?.ranCommands??[];return Nt(e,"triage",r&&fQe(e,r,s),n)}function mQe(e,t){let r=new Set(t),n=e.outOfScope?.filter(i=>r.has(i.behaviorId)),s=e.gaps.map(i=>i.behaviorId===void 0||r.has(i.behaviorId)?i:{missing:`${i.behaviorId}: ${i.missing}`});return{...e,gaps:s,...e.outOfScope?{outOfScope:n}:{}}}function OK(e,t,r,n){if(!t)return['save the validation triage decision as "triage" in the plan'];let s=YM(e,"plan",n);if(!s)return["analyze.json is missing \u2014 nothing to ground the decision against"];let i=mQe(t,s.behaviorIds),o=uQe(i,s);return r&&!TS(i.plan)&&o.push(`the plan brought the app up, though its decision (${i.decision}) needs no running application`),o}function QK(e,t,r,n){if(!t)return["the plan made no validation triage decision"];let s=OK(e,t,r,n);return s.length?[`the plan's validation triage does not hold: ${s.join("; ")}`]:[]}function gQe(e,t){let r=YM(e,"plan"),n=mQe(t,r?.behaviorIds??[]);return Nt(e,"triage",fQe(e,n,r?.ranCommands??[]),[])}function AQe(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 MK(e,t=Ho(e)){let r=fe(e,"plan.json"),n=Rr(e);if(!t?.gaps.length||!r?.requirements?.length||!n)return[];let s=Sc(n,"").map(a=>a.path),i=zM(r,s,YR(s).length>0),o=new Set(r.requirements.flatMap(a=>a.clauses.map(c=>c.id)));return t.gaps.filter(a=>aQe(a,o,i))}function Ho(e){if(AQe(e)?.status==="passed")return xu(xS.join(e.outputsDir,bDt))}function Fn(e){return e.inputs?.unitPath==="write"&&Ho(e)?.decision==="targeted_unit"}function xDt(e){let t=Ho(e);if(!t?.sutRequired||Fn(e))return!1;let r=new Set(t.plan.filter(n=>n.mechanism==="runtime").map(n=>n.behaviorId));for(let n of fe(e,"plan.json")?.cases??[])n.clause&&r.has(n.clause)&&r.add(n.id);return(fe(e,"adapt.json")?.items??[]).some(n=>n.reran?.tests?.length?n.reran.tests.some(s=>s.status==="pass"&&r.has(s.case)):n.reran?.exit===0&&(n.covers??[]).some(s=>r.has(s)))}function JM(e){return fe(e,"deploy.json")?.outcome==="bringup-failed"&&xDt(e)}function kS(e){return DNe(xQ(e.inputs,fe(e,`${vs}.json`),Ho(e)?.sutRequired))}function yQe(e,t){if(!e.triageBranch&&!(e.name&&RDt.has(e.name)))return;let r=Ho(t);if(r){if(r.decision==="existing_evidence_sufficient")return`${L0.runtime}${r.decision}: existing evidence establishes this change, so no test is written or run`;if(t.inputs?.unitPath==="write"&&r.decision==="targeted_unit"){if(e.name==="write")return;if(e.name==="generate-unit")return`${L0.noRuntime}${r.decision}, and write writes its unit tests (unit path write)`}if(e.triageBranch==="runtime"&&!r.sutRequired)return`${L0.runtime}${r.decision}, which needs no running application`;if(e.triageBranch==="no-runtime"&&r.sutRequired)return`${L0.noRuntime}${r.decision}, which needs the running application`}}var RDt=new Set(["deploy","recommend","generate","generate-ui","adapt","generate-unit","native-run","finalize","deliver"]),L0={runtime:"not needed \u2014 validation triage decided ",noRuntime:"not on this run's path \u2014 validation triage decided "};function EQe(e){return!!e&&Object.values(L0).some(t=>e.startsWith(t))}function wQe(e,t){if(!e.branchRequires)return[...e.requires];let r=Ho(t),n=r&&!r.sutRequired&&!Fn(t)?"no-runtime":"runtime";return[...e.requires,...e.branchRequires[n]??[]]}function FK(e){return[...new Set([...e.requires,...e.softRequires??[],...Object.values(e.branchRequires??{}).flat()])]}var TDt=/run budget exhausted/;function LK(e,t){let r=AQe(e);if(!r)return;let n=Ho(e);if(!n)return{sufficiency:"insufficient",rationale:"Validation triage did not complete, so nothing established what evidence this change needs.",gaps:[`validation triage did not complete (${r.reason??r.status})`],acceptedEvidence:[],actionRequired:[]};if(n.decision==="blocked_preflight"&&n.blocked)return{sufficiency:"insufficient",rationale:n.rationale,gaps:[`the change does not meet a prerequisite: ${n.blocked.reason} (${n.blocked.file})`],acceptedEvidence:[],actionRequired:[],blockedPreflight:n.blocked};let s=new Set(MK(e,n)),i=n.gaps.filter(g=>!s.has(g)).map(g=>g.behaviorId?`${g.behaviorId}: ${g.missing}`:g.missing),o=new Set;for(let g of n.plan)SDt.has(g.mechanism)||i.push(`${g.behaviorId}: ${CDt[g.mechanism]} is not available in this run${g.covers?` (${g.covers})`:""}`);n.blocked&&i.push(`the change does not meet a prerequisite: ${n.blocked.reason} (${n.blocked.file})`),i.push(...YOe(e,n));let a=n.sutRequired?jb(e):[],c=n.sutRequired?RQ(e.inputs?.sharedEnvironment):[],l=!!e.inputs?.appRunning;i.push(...a.map(g=>MNe(g,l)),...c.map(g=>ONe(g,l))),(a.length||c.length)&&o.add("sut_revision_mismatch");let u=TQ(e);i.push(...u.map(FNe));let d=n.sutRequired?mPe(e):[];if(i.push(...d),(u.length||d.length)&&o.add("isolation_unavailable"),n.sutRequired&&!qR(e)&&!JM(e)){let g=e.state.stages.deploy;i.push(`the running application was needed and was not available${g?.reason?` (${g.reason})`:""}`),o.add("deployment_review")}else t.some(g=>g.kind==="tests-not-executed")&&i.push("the planned tests were written but not run");let p=Object.entries(e.state.stages).filter(([,g])=>g&&TDt.test(g.reason??"")).map(([g])=>g);p.length&&i.push(`the execution budget ran out before ${p.join(", ")} finished`);let f=new Set(n.plan.filter(g=>g.mechanism==="existing_evidence").flatMap(g=>g.evidenceIds)),m=n.ciEvidence.filter(g=>g.status==="accepted"&&f.has(g.id)).map(g=>({kind:g.kind,repository:g.repository,revision:g.revision,reference:g.reference,summary:g.summary}));return{sufficiency:i.length?"insufficient":"sufficient",rationale:n.rationale,gaps:i,acceptedEvidence:m,actionRequired:[...o]}}var SQe={async render(){}};function U0(e=t=>console.log(t)){return{async render(t){let r=t.split(`
|
|
350
350
|
`).filter(n=>!n.startsWith("<!--")).join(`
|
|
351
351
|
`);e(`
|
|
352
352
|
${r}`)}}}var BS="<!-- skyramp-testbot-staged -->",kDt={preflight:"Setting up",analyze:"Analyzing the change",triage:"Deciding what evidence is needed",deploy:"Deploying the app",recommend:"Recommending tests",generate:"Generating tests","generate-ui":"Generating UI tests",adapt:"Fitting tests into the repo","generate-unit":"Writing unit tests","native-run":"Running unit tests",finalize:"Finalizing",report:"Writing the report",deliver:"Opening the pull request",plan:"Planning: what needs validating, then the tests and the app",write:"Writing and running the tests"};function BDt(e){return kDt[e]??e}var bQe=220;function KM(e){if(!e)return;let t=e.replace(/exit gate\(s\) failed:\s*[a-z0-9-]+\s*—\s*/gi,"").replace(/skeptic found (\d+) weak\/ineffective assertion\(s\)\s*—\s*/gi,"review found $1 weak assertion(s): ").replace(/\b(?:preflight|analyze|deploy|recommend|generate(?:-ui)?|adapt|finalize|report)\.json\b/g,"its results").replace(/^aborted:\s*/i,"").replace(/^not run — /i,"").replace(/\s+/g," ").trim();if(t.length>bQe){let r=t.slice(0,bQe),n=Math.max(r.lastIndexOf(". "),r.lastIndexOf("; "));t=(n>80?r.slice(0,n+1):r.replace(/\s+\S*$/,"")+"\u2026").trim()}return t||void 0}function XM(e,t={}){let r=[BS,`### ${t.title??"Skyramp Testbot"}`,"",`> \u274C Skyramp Testbot could not start: ${KM(e)??e}`];return t.runUrl&&r.push("",`_[View run](${t.runUrl})_`),r.join(`
|
|
@@ -376,7 +376,7 @@ _\u2026 truncated \u2014 the full report is in the workflow run log._`;d=d.slice
|
|
|
376
376
|
`);if(f.length<=r)return f}let l=["",...k5e(i.slice(0,1)),"",c(1)].join(`
|
|
377
377
|
`),u="";for(let d of i[0]){if(u.length+d.length+l.length>r)break;u+=d}return(u+l).slice(0,r)}var N5e=18e4,MZt=5e3;function bie(e=process.env){let t=pE(e.SYSTEM_COLLECTIONURI??""),r=e.SYSTEM_TEAMPROJECT,n=e.BUILD_BUILDID;return t&&r&&n?{server:t,project:r,buildId:n}:void 0}var vB=class{constructor(t){this.opts=t;this.log=t.log??(i=>console.log(i)),this.run=t.run??mie,this.command=t.command??EB;let{server:r,project:n,buildId:s}=t.pipelineRun;this.runUrl=`${r}/${encodeURIComponent(n)}/_build/results?buildId=${encodeURIComponent(s)}`}opts;name="azure";supportsRemote=!0;runUrl;log;run;command;repository(t=this.opts.repoSlug){return bB(t)}api(t){return SB(this.opts.pipelineRun.server,this.repository(t))}async rest(t,r,n,s){return CB({token:await this.opts.tokenProvider(),url:r,method:t,body:n,accept:s,fetch:this.opts.fetch})}prUrl(t,r){let n=this.repository(t);return`${this.opts.pipelineRun.server}/${encodeURIComponent(n.project)}/_git/${encodeURIComponent(n.name)}/pullrequest/${r}`}async activePr(t,r){let n=new URL(`${this.api(t)}/pullrequests`);return n.searchParams.set("searchCriteria.sourceRefName",`refs/heads/${r}`),n.searchParams.set("searchCriteria.status","active"),(await this.rest("GET",n.toString())).value?.find(i=>typeof i.pullRequestId=="number")}git(t,r,n=this.opts.repositoryPath){return this.run("git",t,{cwd:n,env:r})}async remoteGit(t,r){let n=await this.opts.tokenProvider();return this.git(t,{...process.env,GIT_TERMINAL_PROMPT:"0",...bq(this.opts.pipelineRun.server,n)},r)}adoptCheckoutAuthHeader(t){}async admitRun(){return{admit:!0}}async resolveContext(){let t;try{let r=this.git(["rev-parse","--abbrev-ref","HEAD"]);r&&r!=="HEAD"&&(t=r)}catch{}return{repoSlug:this.opts.repoSlug,headBranch:t}}createProgressSink(){return U0(this.log)}async beginRun(){}watchRun(t){let r=!1,n=this.opts.watchSignals===!1?[]:["SIGTERM","SIGINT"],s=i=>{for(let o of n)process.removeListener(o,s);r||(r=!0,t("cancelled",`received ${i} (pipeline run cancelled or agent shutting down)`))};for(let i of n)process.on(i,s);return{stop:()=>{for(let i of n)process.removeListener(i,s)}}}stageArtifact(t,r,n){if(!/^[A-Za-z0-9._-]{1,200}$/.test(t))throw new Error(`"${t}" is not an artifact name`);let s=this.opts.stagingDir??ti.join(process.env.AGENT_TEMPDIRECTORY||wie.tmpdir(),"skyramp-artifacts"),i=ti.join(s,t);Xa.rmSync(i,{recursive:!0,force:!0});for(let o of r){let a=ti.relative(n,o);if(!a||a.startsWith("..")||ti.isAbsolute(a))throw new Error(`${o} is not under ${n}`);Xa.mkdirSync(ti.dirname(ti.join(i,a)),{recursive:!0}),Xa.copyFileSync(o,ti.join(i,a))}return this.command(gv("artifact.upload",{containerfolder:t,artifactname:t},i)),i}async uploadArtifact(t,r,n){if(r.length)try{return this.stageArtifact(t,r,n),`${this.runUrl}&view=artifacts&pathAsName=false&type=publishedArtifacts`}catch(s){this.log(`[warn] could not upload artifact ${t}: ${ei(s)}`);return}}async uploadRunFiles(t,r,n){return await this.uploadArtifact(t,r,n)!==void 0}async artifactStore(){let{server:t,project:r,buildId:n}=this.opts.pipelineRun,s=(i,o)=>`${t}/${encodeURIComponent(i)}/_apis/build/builds/${encodeURIComponent(o)}/artifacts`;return{uploadArtifact:async(i,o,a)=>{this.stageArtifact(i,o,a);let c=new URL(s(r,n));c.searchParams.set("artifactName",i);let l=Date.now()+(this.opts.artifactWaitMs??N5e);for(;;){let u=await this.rest("GET",c.toString()).catch(()=>{});if(typeof u?.id=="number")return{id:u.id};if(Date.now()>=l)throw new Error(`Azure DevOps listed no artifact ${i} within ${Math.round((this.opts.artifactWaitMs??N5e)/1e3)} s`);await new Promise(d=>setTimeout(d,this.opts.artifactPollMs??MZt))}},downloadArtifact:async(i,o)=>{let a=o?.path??Xa.mkdtempSync(ti.join(wie.tmpdir(),"skyramp-artifact-")),c=o?.findBy?.repositoryOwner,l=c?.includes("/")?c.slice(c.indexOf("/")+1):r,u=String(o?.findBy?.workflowRunId??n),p=(await this.rest("GET",s(l,u))).value?.find(y=>y.id===i),f=/^#\/(\d+)\/(.+)$/.exec(p?.resource?.data??"");if(!p||p.resource?.type?.toLowerCase()!=="container"||!f)throw new Error(`build ${u} has no artifact ${i} the engine can read`);let[,m,g]=f,w=new URL(`${t}/_apis/resources/Containers/${m}`);w.searchParams.set("itemPath",g),w.searchParams.set("api-version","7.1-preview.4");let A=await this.rest("GET",w.toString());for(let y of A.value??[]){if(y.itemType!=="file"||!y.path?.startsWith(`${g}/`))continue;let S=y.path.slice(g.length+1),C=ti.resolve(a,S);if(!C.startsWith(ti.resolve(a)+ti.sep))throw new Error(`the artifact names a path outside its place: ${y.path}`);let v=new URL(w.toString());v.searchParams.set("itemPath",y.path);let R=await this.rest("GET",v.toString(),void 0,"application/octet-stream");Xa.mkdirSync(ti.dirname(C),{recursive:!0}),Xa.writeFileSync(C,R)}return{downloadPath:a}}}}async publishTestsPr(t){let r=[];return{...await this.publish(t,r),pushedCommits:r}}description(t){return B5e(Xa.readFileSync(t,"utf-8"),this.opts.reportUrl)}async publish(t,r){let n=t.repositoryPath,s=t.repoSlug??this.opts.repoSlug,i=(u,d,p,f=t.base)=>({action:"failed",pushed:p,base:f,url:"",failure:u,detail:d});try{this.api(s)}catch(u){return i("unknown",ei(u),!1)}let o=!0;if(t.mode==="append"){let u=!1;try{u=!!(await this.remoteGit(["ls-remote","--heads",t.remote,t.branch],n)).trim()}catch{o=!1}if(u){try{await this.remoteGit(["fetch",t.remote,t.branch],n),this.git(["checkout","-B",t.branch,`${t.remote}/${t.branch}`],void 0,n),this.git(["cherry-pick","--keep-redundant-commits",t.commitSha],void 0,n)}catch(p){return mB(this.run,t),i("conflict",`append onto the existing tests branch failed (tests kept on the local branch): ${ei(p)}`,!1)}let d=!1;try{this.git(["diff","--quiet",`${t.remote}/${t.branch}`,"HEAD"],void 0,n),d=!0}catch{d=!1}if(d)return this.markTestsPrUnchanged({branch:t.branch,repositoryPath:n,repoSlug:t.repoSlug,devPr:t.devPr});o=!1}}let a=async()=>{await this.remoteGit(["push",...o?["--force"]:[],t.remote,`HEAD:refs/heads/${t.branch}`],n),hq(this.run,n,r)};try{await a()}catch(u){let d=ei(u);return i(fv.test(d)?"auth":"push",`push failed: ${d}`,!1)}let c=this.description(t.bodyFile),l=async u=>{let d=await this.activePr(s,t.branch);if(d?.pullRequestId!==void 0){let f=d.pullRequestId;return await this.rest("PATCH",`${this.api(s)}/pullrequests/${f}`,{title:t.title,description:c}),d.targetRefName&&d.targetRefName!==`refs/heads/${u}`&&await this.rest("PATCH",`${this.api(s)}/pullrequests/${f}`,{targetRefName:`refs/heads/${u}`}).catch(m=>this.log(`[warn] could not move tests PR ${f} to ${u}: ${ei(m)}`)),{action:"updated",pushed:!0,base:u,url:this.prUrl(s,f)}}let p=await this.rest("POST",`${this.api(s)}/pullrequests`,{sourceRefName:`refs/heads/${t.branch}`,targetRefName:`refs/heads/${u}`,title:t.title,description:c});if(typeof p.pullRequestId!="number")throw new Error("Azure DevOps created no pull request");return{action:"created",pushed:!0,base:u,url:this.prUrl(s,p.pullRequestId)}};try{return await l(t.base)}catch(u){let d=ei(u);return fv.test(d)?i("auth",d,!0):await this.branchExists(s,t.base).catch(()=>!0)?i("unknown",d,!0):this.retarget(t,s,l,i,a)}}async branchExists(t,r){let n=new URL(`${this.api(t)}/refs`);return n.searchParams.set("filter",`heads/${r}`),((await this.rest("GET",n.toString())).value??[]).some(i=>i.name===`refs/heads/${r}`)}async retarget(t,r,n,s,i){let o=t.devPr;if(t.mode==="append")return s("unknown",`the dev branch '${t.base}' no longer exists and append mode cannot re-cut the tests branch \u2014 re-run in replace mode`,!0);if(o==null)return s("unknown",`the base branch '${t.base}' no longer exists and no dev PR number is known to retarget from`,!0);let a=await this.rest("GET",`${this.api(r)}/pullrequests/${o}`).catch(()=>{}),c=a?.targetRefName?.replace(/^refs\/heads\//,"");if(a?.status!=="completed"||!c)return{action:"skipped",pushed:!0,base:t.base,url:"",detail:`the dev branch '${t.base}' no longer exists and PR ${o} is ${a?.status??"unknown"} (not completed) \u2014 nothing to target; tests are on branch ${t.branch}`};this.log(`[deliver] tests PR base '${t.base}' no longer exists (dev PR completed) \u2014 re-cutting onto '${c}'`);try{await this.remoteGit(["fetch",t.remote,c],t.repositoryPath),this.git(["checkout","-B",t.branch,`${t.remote}/${c}`],void 0,t.repositoryPath),this.git(["cherry-pick","--keep-redundant-commits",t.commitSha],void 0,t.repositoryPath)}catch(l){return mB(this.run,t),s("conflict",`re-cut onto '${c}' failed (tests kept on the local branch): ${ei(l)}`,!0)}try{await i()}catch(l){return s("push",`push failed: ${ei(l)}`,!1,c)}try{let l=await n(c);return{...l,action:"retargeted",retargetedAs:l.action==="updated"?"updated":"created"}}catch(l){return s("unknown",`re-cut onto '${c}' pushed, but PR create failed: ${ei(l)}`,!0,c)}}async markTestsPrUnchanged(t){let r=t.repoSlug??this.opts.repoSlug,n=s=>({action:"skipped",pushed:!1,base:"",url:"",detail:s});try{let s=await this.activePr(r,t.branch);if(s?.pullRequestId===void 0)return n(`no open tests PR for ${t.branch} \u2014 nothing to annotate`);let i=t.devPr!=null?`PR ${t.devPr}`:"the dev branch",o=Aq(i)+yq(s.description??""),a=B5e(o);return a.startsWith(AB)?(await this.rest("PATCH",`${this.api(r)}/pullrequests/${s.pullRequestId}`,{description:a}),{action:"unchanged",pushed:!1,base:(s.targetRefName??"").replace(/^refs\/heads\//,""),url:this.prUrl(r,s.pullRequestId),detail:"no new test changes this run \u2014 existing tests PR annotated"}):n("the tests PR description has no room for the banner")}catch(s){return n(`could not annotate the tests PR: ${Ka(s)}`)}}async closeTestsPr(t){try{let r=await this.activePr(void 0,t.branch);if(r?.pullRequestId===void 0)return{closed:!1};let n=r.pullRequestId;return await this.rest("POST",`${this.api()}/pullRequests/${n}/threads`,{comments:[{parentCommentId:0,content:t.reason,commentType:1}],status:"closed"}),await this.rest("PATCH",`${this.api()}/pullrequests/${n}`,{status:"abandoned"}),{closed:!0,url:this.prUrl(void 0,n)}}catch(r){return this.log(`[warn] could not close the tests PR for ${t.branch}: ${Ka(r)}`),{closed:!1}}}async endRun(){}async listCommitChecks(t){try{return((await this.rest("GET",`${this.api(t.repository)}/commits/${encodeURIComponent(t.revision)}/statuses?latestOnly=true`)).value??[]).filter(n=>n.context?.name).map(n=>({repository:t.repository,name:n.context?.genre?`${n.context.genre}/${n.context.name}`:n.context.name,headSha:t.revision,status:n.state==="pending"?"pending":"completed",conclusion:n.state==="pending"?null:n.state==="succeeded"?"success":n.state==="failed"?"failure":n.state==="notApplicable"?"neutral":n.state??null,url:n.targetUrl,summary:n.description}))}catch(r){this.log(`[warn] could not read CI results for ${t.repository}@${t.revision.slice(0,12)}: ${Ka(r)}`);return}}async commitContains(t){try{let r=new URL(`${this.api(t.repository)}/diffs/commits`);for(let[s,i]of Object.entries({baseVersion:t.ancestor,baseVersionType:"commit",targetVersion:t.descendant,targetVersionType:"commit",$top:"1"}))r.searchParams.set(s,i);let n=await this.rest("GET",r.toString());return n.commonCommit?n.commonCommit.toLowerCase()===t.ancestor.toLowerCase()?"contained":"not_contained":"unknown"}catch(r){return this.log(`[warn] could not compare ${t.repository} ${In(t.ancestor)}...${In(t.descendant)}: ${Ka(r)}`),"unknown"}}};var kB=require("node:crypto");var P5e=J(require("path"));var qi=E.string().trim().min(1),Sie=(r=>(r.TestbotManaged="testbot_managed",r.CustomerDeployed="customer_deployed",r))(Sie||{}),yv=[".skyramp/sut/setup.sh",".skyramp/sut/teardown.sh"],Sq=E.object({schemaVersion:E.literal(1),type:E.nativeEnum(Sie).optional(),status:E.enum(["ready","blocked"]),environment:Ub.optional(),components:E.array(E.object({name:qi,repository:qi.describe(`owner/repo, or "${Tr}" for a customer-deployed component no repository builds`),healthy:E.boolean(),url:E.string().min(1).nullable(),...b4,credentials:E.array(E.string().regex(Bh)).max(50).optional(),deployed:qi.nullable().optional().describe("customer_deployed only: the revision the component runs, as setup read it (WF-SETUP-22's Deployed now), or null when it could not tell")}).strict()),suites:E.array(E.object({framework:qi,file:qi,result:E.enum(["pass","fail","error"])}).strict()),inputsUsed:E.array(qi),inputsUsedHow:E.array(E.object({input:qi,how:qi}).strict()).optional(),inputsNotUsed:E.array(E.object({input:qi,reason:qi}).strict()),blockers:E.array(E.object({component:qi,problem:qi,evidence:qi,fix:qi}).strict()),replay:E.object({outcome:qi,durationSeconds:E.number().nonnegative().nullable()}).strict().nullable(),files:E.array(E.object({path:qi,content:E.string()}).strict())}).strict().superRefine((e,t)=>{e.inputsUsedHow?.forEach((s,i)=>{e.inputsUsed.includes(s.input)||t.addIssue({code:E.ZodIssueCode.custom,path:["inputsUsedHow",i,"input"],message:"not one of inputsUsed"})}),e.components.forEach((s,i)=>{s.credentials&&new Set(s.credentials).size!==s.credentials.length&&t.addIssue({code:E.ZodIssueCode.custom,path:["components",i,"credentials"],message:"names a credential twice"})});let r=e.type==="customer_deployed";r!==(e.environment!==void 0)&&t.addIssue({code:E.ZodIssueCode.custom,path:["environment"],message:"an environment exactly when the plan's type is customer_deployed"}),e.environment&&new Set(e.environment.credentials).size!==e.environment.credentials.length&&t.addIssue({code:E.ZodIssueCode.custom,path:["environment","credentials"],message:"names a credential twice"});let n=new Set(e.components.map(s=>s.name));if(e.environment?.revisionSources.forEach((s,i)=>{s.components.forEach((o,a)=>{n.has(o)||t.addIssue({code:E.ZodIssueCode.custom,path:["environment","revisionSources",i,"components",a],message:"not one of components"})})}),e.components.forEach((s,i)=>{s.deployed!==void 0!==r&&t.addIssue({code:E.ZodIssueCode.custom,path:["components",i,"deployed"],message:"what a component runs exactly when the plan is customer_deployed"}),s.repository===Tr&&!r&&t.addIssue({code:E.ZodIssueCode.custom,path:["components",i,"repository"],message:`only a customer_deployed component is ${Tr}`})}),r&&(e.components.forEach((s,i)=>{e.components.findIndex(o=>o.name===s.name)!==i&&t.addIssue({code:E.ZodIssueCode.custom,path:["components",i,"name"],message:"names a component twice"})}),e.replay!==null&&t.addIssue({code:E.ZodIssueCode.custom,path:["replay"],message:"a customer_deployed plan is never replayed"}),e.files.forEach((s,i)=>{yv.includes(s.path)&&t.addIssue({code:E.ZodIssueCode.custom,path:["files",i,"path"],message:"a customer_deployed plan has no script that starts or stops the system"})})),r&&e.status==="ready"){let s=new Set(e.environment?.revisionSources.flatMap(i=>i.components));e.components.forEach((i,o)=>{i.repository!==Tr&&!s.has(i.name)&&t.addIssue({code:E.ZodIssueCode.custom,path:["components",o,"name"],message:"a ready customer_deployed plan reads what every component a repository builds runs"})})}}),Cie="awaits_credential_check",cf="Time limit reached",_5e="time_limit";var FZt=["clean","recipe-drift"];function $m(e){let t=P5e.posix.normalize(e);return t===e&&(t===".skyramp/workspace.yml"||t.startsWith(".skyramp/sut/")&&t.length>13)}function LZt(e,t,r){let n=t.bringupError;if(e.environment)return{component:e.components.map(i=>i.name).join(", ")||"SUT",problem:`onboard reached the deployment, but deploy's fresh check of it ended ${t.outcome}`,evidence:n?`$ ${n.command}
|
|
378
378
|
${n.output}`:`deploy reported ${t.outcome} without the failing command`,fix:"make .skyramp/sut/health.json's check pass from a fresh session (its address, sign-in and ready route), then set it up again"};let s=t.suspectFiles?.length?` \u2014 it points at ${t.suspectFiles.join(", ")}`:"";return{component:e.components.map(i=>i.name).join(", ")||"SUT",problem:`the recipe worked once but not from nothing: deploy's fresh replay of .skyramp/sut/setup.sh ended ${t.outcome}`,evidence:n?`$ ${n.command}
|
|
379
|
-
${n.output}`:`deploy reported ${t.outcome} without the failing command`,fix:t.outcome==="change-broke-bringup"?`fix the change that broke bring-up${s}, then onboard again`:r.length>0?UZt(r):"make .skyramp/sut/setup.sh bring the SUT up from a clean checkout (what onboard's session had that a fresh run lacks), then onboard again"}}var IB="a GitHub Actions secret, or on Azure DevOps a secret variable in the host repository's skyramp-testbot variable group under Pipelines \u203A Library";function UZt(e){let t=e.length===1;return`add ${t?"a secret":"secrets"} named ${e.join(", ")} on the workflow host, ${t?"as":"each as"} ${IB}, then Retry: Skyramp adds ${t?"it":"them"} to the Target's credentials, and the replay gets ${t?"its value":"their values"}. If it still fails, make .skyramp/sut/setup.sh bring the SUT up from a clean checkout`}function $Zt(e){return e.environment?{component:e.components.map(t=>t.name).join(", ")||"SUT",problem:"the deployment was never checked from a fresh session: deploy did not run or wrote no deploy.json",evidence:"outputs/deploy.json is missing from this run",fix:"run deploy after onboard in the same run so it checks the deployment is ready; if deploy ran, its stage log says why it wrote no deploy.json"}:{component:e.components.map(t=>t.name).join(", ")||"SUT",problem:"the recipe was never replayed: deploy did not run or wrote no deploy.json",evidence:"outputs/deploy.json is missing from this run",fix:"run deploy after onboard in the same run so it replays .skyramp/sut/setup.sh from a clean start; if deploy ran, its stage log says why it wrote no deploy.json"}}function qZt(e){return{component:e.components.map(t=>t.name).join(", ")||"SUT",problem:`${cf}: setup ran out of time while checking ${e.environment?"that the deployment is ready":"that the app comes up from a clean start"}. Every component was up before that.`,evidence:"The check from a fresh session didn't finish.",fix:"Retry: setup carries on from what this one found and finishes checking."}}function GZt(e){return{component:"SUT recipe",problem:"deploy fixed recipe drift, but the recipe it fixed was not collected \u2014 onboard's copy is the recipe from before the fix",evidence:`deploy reported recipe-drift: ${(e.recipeFixes??[]).join("; ")||"no fixes listed"}`,fix:"collect .skyramp/sut/ and .skyramp/workspace.yml after deploy (collectRecipeFiles) and build the plan from that collection"}}var vie=[".skyramp/sut/setup.sh",".skyramp/sut/teardown.sh",".skyramp/sut/health.json",".skyramp/workspace.yml"],Iie=[".skyramp/sut/health.json",".skyramp/workspace.yml"];function jZt(e){return`Onboard again so it leaves the whole recipe in the checkout: ${e.map(r=>r===".skyramp/workspace.yml"?"create .skyramp/workspace.yml with skyramp_init_scan and skyramp_init_workspace":`write ${r} as a regular file (a symlink is not uploaded)`).join("; ")}.`}function xie(e,t,r){return t&&r||e}function Rie(e,t,r={}){let n=t!==void 0&&!FZt.includes(t.outcome),s=xie(e,t,r.recipeFiles),i=t?.outcome==="recipe-drift"&&!r.recipeFiles,o=(s.recipeFilesOmitted??[]).filter(v=>$m(v.path)),a=o.length?[{component:"SUT recipe",problem:`The recipe could not be uploaded whole: ${o.map(v=>v.path).join(", ")} left out.`,evidence:o.map(v=>`${v.path}: ${v.reason}`).join("; "),fix:"Keep each recipe file text-only and under 64 KiB, and the recipe under 512 KiB in total \u2014 move large generated content out of .skyramp/sut/ and have setup.sh produce it."}]:[],c=e.status==="ready",l=e.environment,u=new Set(s.recipeFiles.map(v=>v.path)),d=c?(l?Iie:vie).filter(v=>!u.has(v)):[],p=d.length?[{component:"SUT recipe",problem:`The recipe is missing ${d.join(", ")}, so it cannot be replayed.`,evidence:`collected: ${[...u].sort().join(", ")||"nothing"}`,fix:jZt(d)}]:[],f=c&&!l&&(r.awaitsCredentialCheck?.length??0)>0,m=t?n?[LZt(e,t,r.unsupplied??[])]:[]:c&&!f?[r.timeLimit?qZt(e):$Zt(e)]:[],g=new Set(l?.revisionSources.flatMap(v=>v.components)),w=l&&c?e.components.filter(v=>v.repository!==Tr&&!g.has(v.name)).map(v=>v.name):[],A=w.length?[{component:w.join(", "),problem:`Testbot cannot tell which revision ${w.join(" and ")} ${w.length>1?"run":"runs"}, so a run could not say which changes it tested.`,evidence:`revision sources: ${l.revisionSources.map(v=>`${v.detail} (${v.components.join(", ")})`).join("; ")||"none"}`,fix:"Say in the Test Environment's notes how to tell what is deployed, such as a version route (GET /version), then set it up again."}]:[],y=(c?l?.revisionSources??[]:[]).filter(v=>v.method==="not_tracked").map(v=>({component:v.components.join(", "),problem:`Testbot can't tell which commit ${v.components.join(" and ")} ${v.components.length>1?"run":"runs"}, so a run can't say which of ${v.components.length>1?"their":"its"} changes it tested.`,evidence:v.detail,fix:`Say in the Test Environment's notes how to tell what ${v.components.join(" and ")} ${v.components.length>1?"run":"runs"}, such as a version route (GET /version) or a deploy workflow, then set it up again.`})),S=[...e.blockers,...m,...i&&t?[GZt(t)]:[],...a,...p,...A,...y,...r.revisionCheck?.blockers??[],...r.credentialBlockers??[]],C=t?.baseUrls??{};return{schemaVersion:1,...l?{type:"customer_deployed",environment:D5e(l)}:{},status:c&&(t!==void 0||f)&&!n&&!i&&o.length===0&&d.length===0&&w.length===0&&!r.credentialBlockers?.length?"ready":"blocked",components:e.components.map(v=>({name:v.name,repository:v.repository,healthy:v.healthy&&!n,url:Object.hasOwn(C,v.name)&&C[v.name]||null,...v.steps?{steps:v.steps.map(R=>({action:R.action,text:R.text,source:R.source,file:R.file}))}:{},...v.kind?{kind:v.kind}:{},...v.from?{from:{file:v.from.file,service:v.from.service}}:{},...v.credentials?{credentials:[...new Set(v.credentials)].filter(R=>Bh.test(R))}:{},...l?{deployed:HZt(v,r)}:{}})),suites:e.suites.map(v=>({framework:v.framework,file:v.file,result:v.result})),inputsUsed:[...e.inputsUsed],...e.inputsUsedHow?{inputsUsedHow:e.inputsUsedHow.filter(v=>e.inputsUsed.includes(v.input)).map(v=>({input:v.input,how:v.how}))}:{},inputsNotUsed:e.inputsNotUsed.map(v=>({input:v.input,reason:v.reason})),blockers:S.map(v=>({component:v.component,problem:v.problem,evidence:v.evidence,fix:v.fix})),replay:t&&!l?{outcome:t.outcome,durationSeconds:r.deployDurationSeconds??null}:f?{outcome:Cie,durationSeconds:null}:!l&&S.some(v=>v.problem.startsWith(cf))?{outcome:_5e,durationSeconds:null}:null,files:s.recipeFiles.filter(v=>$m(v.path)&&!(l&&yv.includes(v.path))).map(v=>({path:v.path,content:v.content}))}}function HZt(e,t){return e.repository===Tr?null:t.revisionCheck?t.revisionCheck.deployed[e.name]??null:t.deployed?.[e.name]??e.deployed??null}function D5e(e){return{address:e.address,readyWhen:e.readyWhen,credentials:[...new Set(e.credentials)],revisionSources:e.revisionSources.map(t=>({method:t.method,detail:t.detail,components:[...t.components]}))}}function O5e(e){return{schemaVersion:1,status:"ready",components:e.components.map(({url:t,deployed:r,...n})=>({...n,healthy:!0})),suites:e.suites,inputsUsed:e.inputsUsed,...e.inputsUsedHow?{inputsUsedHow:e.inputsUsedHow}:{},inputsNotUsed:e.inputsNotUsed,blockers:[],recipeFiles:e.files,recipeFilesOmitted:[],...e.environment?{environment:D5e(e.environment)}:{}}}var W5e={handshake:"/api/v1/runner/runs/:runId/attempts",report:"/api/v1/runner/attempts/:attemptId/report",end:"/api/v1/runner/attempts/:attemptId/end",configuration:"/api/v1/runner/attempts/:attemptId/configuration",progress:"/api/v1/runner/attempts/:attemptId/progress",sutRecipe:"/api/v1/runner/attempts/:attemptId/sut-recipe",runtimePlan:"/api/v1/runner/attempts/:attemptId/runtime-plan",heartbeat:"/api/v1/runner/attempts/:attemptId/heartbeat",setupEvents:"/api/v1/runner/attempts/:attemptId/setup-events",runEvents:"/api/v1/runner/attempts/:attemptId/run-events",requirements:"/api/v1/runner/attempts/:attemptId/requirements",requirementFile:"/api/v1/runner/attempts/:attemptId/requirements/:key/file",deployedRevisions:"/api/v1/runner/attempts/:attemptId/deployed-revisions"},vq=(r=>(r.GitHub="github",r.AzureDevOps="azure-devops",r))(vq||{}),Tie=(i=>(i.Trigger="TRIGGER",i.Baseline="BASELINE",i.AuthoritativeRelatedChange="AUTHORITATIVE_RELATED_CHANGE",i.ConfiguredSharedDependency="CONFIGURED_SHARED_DEPENDENCY",i.ManualOverride="MANUAL_OVERRIDE",i))(Tie||{}),BB=(o=>(o.PullRequest="pull_request",o.ReadyForReview="ready_for_review",o.Schedule="schedule",o.Manual="manual",o.SutSetup="sut_setup",o.RevisionRead="revision_read",o))(BB||{}),zZt=["sut_setup"],VZt=["sut_setup","schedule","revision_read"],WZt=["sut_setup"],Iq=(t=>(t.PullRequest="pull_request",t))(Iq||{}),bv=(s=>(s.ModelProvider="model_provider",s.SutAccess="sut_access",s.Skyramp="skyramp",s.Other="other",s))(bv||{});var xq=(i=>(i.ReportUploaded="report_uploaded",i.NoReport="no_report",i.Cancelled="cancelled",i.RecipeUploaded="recipe_uploaded",i.RevisionsUploaded="revisions_uploaded",i))(xq||{}),Y5e=(r=>(r.Running="running",r.Ended="ended",r))(Y5e||{}),Rq=(l=>(l.TimedOut="timed_out",l.AgentFailed="agent_failed",l.SetupFailed="setup_failed",l.CredentialMissing="credential_missing",l.RunnerLost="runner_lost",l.CheckoutFailed="checkout_failed",l.EnvironmentUnverified="environment_unverified",l.ModelProviderDenied="model_provider_denied",l.ModelProviderUnavailable="model_provider_unavailable",l))(Rq||{}),kie=(n=>(n.Onboard="onboard",n.Deploy="deploy",n.Recheck="recheck",n))(kie||{}),Bie=(r=>(r.Started="started",r.Finished="finished",r))(Bie||{}),Nie=(n=>(n.Passed="passed",n.Failed="failed",n.Skipped="skipped",n))(Nie||{}),Sv=(o=>(o.Log="log",o.Component="component",o.Reply="reply",o.Question="question",o.Delivered="delivered",o.Credentials="credentials",o))(Sv||{}),Tq=(n=>(n.ChooseCredential="choose_credential",n.FreeText="free_text",n.ChooseSource="choose_source",n))(Tq||{});var NB=(n=>(n.Discover="discover",n.Start="start",n.Check="check",n))(NB||{}),Gm=(s=>(s.ValidationPlan="validation_plan",s.TestEnvironment="test_environment",s.TestConditions="test_conditions",s.Tests="tests",s))(Gm||{}),Cv=(s=>(s.Found="found",s.Starting="starting",s.Up="up",s.OutOfScope="out_of_scope",s))(Cv||{}),ql=E.string().regex(/^[1-9][0-9]{0,18}$/),uf=E.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/),vv=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,So=E.string().regex(vv),Co=E.string().regex(/^[0-9a-f]{64}$/),Cq=E.object({id:So,revision:ql}).strict(),kq={provider:E.literal("github"),providerAccountId:ql,providerRepositoryId:ql},Bq={provider:E.literal("azure-devops"),providerAccountId:So,providerRepositoryId:So},Gl=E.discriminatedUnion("provider",[E.object(kq).strict(),E.object(Bq).strict()]),Pie=E.discriminatedUnion("provider",[E.object(kq).passthrough(),E.object(Bq).passthrough()]),Pr=e=>`${e.provider}:${e.providerRepositoryId}`,Q5e={namespace:E.string().min(1),name:E.string().min(1)},J5e=E.discriminatedUnion("provider",[E.object({...kq,...Q5e}).strict(),E.object({...Bq,...Q5e}).strict()]),M5e=E.object({ref:E.string().min(1),revision:uf}).strict(),YZt=E.object({repository:J5e,revision:uf,ref:E.string().nullable(),reason:E.nativeEnum(Tie),change:E.object({kind:E.nativeEnum(Iq),number:ql,base:M5e.optional()}).strict().nullable(),compareWith:M5e.optional()}).strict();function JZt(e){if(e.trigger.kind==="revision_read"!=!e.baseline)return e.baseline?"a revision_read run names no baseline":"names its baseline";if(!e.baseline)return null;let{confirmedRunId:t,initialBaselineId:r,sources:n}=e.baseline;if(t!==null&&r!==void 0)return"a run compares with one baseline";let s=e.trigger.kind==="schedule"&&t!==null||r!==void 0;if(!n)return s?"names every source of the snapshot, once":null;if(t===null&&r===void 0)return"a run with no Confirmed Baseline names no baseline sources";let i=new Set(e.sources.map(c=>Pr(c.repository))),o=new Set(n.map(c=>Pr(c.repository)));return o.size===n.length&&o.size===i.size&&[...o].every(c=>i.has(c))?null:"names every source of the snapshot, once"}var K5e=/^[A-Z][A-Z0-9_]+-[1-9][0-9]*$/,X5e=/^[1-9][0-9]{0,18}$/,F5e=new RegExp(`${K5e.source}|${X5e.source}`),L5e=/^https:\/\/[a-z0-9-]+(\.[a-z0-9-]+)+$/,KZt=E.union([E.object({source:E.literal("jira"),site:E.string().regex(L5e),key:E.string().regex(K5e),updated:E.string().datetime(),contentHash:Co}).strict(),E.object({source:E.literal("confluence"),site:E.string().regex(L5e),key:E.string().regex(X5e),version:E.number().int().positive(),contentHash:Co}).strict(),E.object({source:E.literal("other"),key:E.string().regex(vR),contentHash:Co}).strict(),E.object({source:E.literal("other"),key:E.string().regex(BA),contentHash:Co,fileName:E.string().min(1).max(255),mediaType:E.nativeEnum(vb)}).strict()]),U5e=E.union([E.literal("jira"),E.literal("confluence")]),Z5e=E.object({schemaVersion:E.literal(1),items:E.array(E.union([E.object({source:U5e,site:E.string(),key:E.string().regex(F5e),state:E.literal("read"),text:E.string(),version:E.string().min(1),contentMatches:E.boolean()}).strict(),E.object({source:U5e,site:E.string(),key:E.string().regex(F5e),state:E.literal("not_read"),reason:E.nativeEnum(kA)}).strict(),E.object({source:E.literal("other"),key:E.string().regex(vR),state:E.literal("read"),text:E.string(),version:E.string().min(1),contentMatches:E.boolean()}).strict(),E.object({source:E.literal("other"),key:E.string().regex(vR),state:E.literal("not_read"),reason:E.nativeEnum(kA)}).strict(),E.object({source:E.literal("other"),key:E.string().regex(BA),state:E.literal("read"),version:Co,fileName:E.string().min(1).max(255),mediaType:E.nativeEnum(vb)}).strict(),E.object({source:E.literal("other"),key:E.string().regex(BA),state:E.literal("not_read"),reason:E.nativeEnum(kA)}).strict()])),instructions:E.array(E.string()).optional()}).strict(),XZt=E.object({schemaVersion:E.literal(1),runId:So,skyrampOrgId:So,target:Cq,policy:Cq.nullable(),trigger:E.object({kind:E.nativeEnum(BB),requestedAt:E.string().datetime()}).strict(),configuration:E.object({captureId:So,revision:ql.nullable(),hash:Co}).strict(),baseline:E.object({confirmedRunId:So.nullable(),initialBaselineId:So.optional(),sources:E.array(E.object({repository:Gl,revision:uf}).strict()).optional()}).strict().optional(),sources:E.array(YZt).min(1),execution:E.object({provider:E.nativeEnum(vq),repository:J5e,workflowPath:E.string(),ref:E.string()}).strict(),credentials:E.array(E.object({name:E.string(),purpose:E.nativeEnum(bv),required:E.boolean()}).strict()),requirements:E.array(KZt).min(1).optional(),instructions:E.object({contentHash:Co}).strict().optional(),deployedRevisions:E.array(E.object({repository:Gl,revision:uf}).strict()).min(1).optional()}).strict().superRefine((e,t)=>{let r=new Set;(e.requirements??[]).forEach((c,l)=>{let u="fileName"in c?"file":"pasted";c.source==="other"&&c.key!==`${u}-${c.contentHash.slice(0,16)}`&&t.addIssue({code:E.ZodIssueCode.custom,message:"is not the key of its content hash",path:["requirements",l,"key"]});let d=ba({source:c.source,key:c.key});r.has(d)&&t.addIssue({code:E.ZodIssueCode.custom,message:"names an item that the run already names",path:["requirements",l,"key"]}),r.add(d)});let n=e.trigger.kind,s=zZt.includes(n);s!==(e.policy===null)&&t.addIssue({code:E.ZodIssueCode.custom,path:["policy"],message:s?`a ${n} run has no policy`:"names the policy revision"});let i=JZt(e);i&&t.addIssue({code:E.ZodIssueCode.custom,path:e.baseline?["baseline","sources"]:["baseline"],message:i}),VZt.includes(n)&&e.sources.forEach((c,l)=>{c.reason!=="BASELINE"&&t.addIssue({code:E.ZodIssueCode.custom,path:["sources",l,"reason"],message:`a ${n} run selects only BASELINE sources`})}),e.deployedRevisions&&n!=="manual"&&t.addIssue({code:E.ZodIssueCode.custom,path:["deployedRevisions"],message:"only a manual run pins deployed revisions"});let o=new Set(e.sources.map(c=>Pr(c.repository))),a=new Set;(e.deployedRevisions??[]).forEach((c,l)=>{let u=Pr(c.repository);o.has(u)?a.has(u)&&t.addIssue({code:E.ZodIssueCode.custom,path:["deployedRevisions",l,"repository"],message:"repository appears twice"}):t.addIssue({code:E.ZodIssueCode.custom,path:["deployedRevisions",l,"repository"],message:"names a repository outside the snapshot"}),a.add(u)}),e.sources.forEach((c,l)=>{c.compareWith&&(c.reason!=="MANUAL_OVERRIDE"||c.change)&&t.addIssue({code:E.ZodIssueCode.custom,path:["sources",l,"compareWith"],message:"only a MANUAL_OVERRIDE source without a change names a revision to compare with"})})});var _ie=(r=>(r.Person="person",r.Policy="policy",r))(_ie||{}),ZZt=E.object({kind:E.nativeEnum(_ie),name:E.string().min(1).max(256)}).strict(),e7t=E.object({schemaVersion:E.literal(1),attempt:E.object({id:So,number:E.number().int().positive(),deadlineAt:E.string().datetime()}).strict(),manifest:XZt,manifestHash:Co,entitlements:E.array(E.string()).optional(),runToken:E.string().min(1).optional(),requestedBy:ZZt.nullable().optional(),writeAllowed:E.boolean().optional(),claudeCodeVersion:E.string().regex(/^[0-9]+\.[0-9]+\.[0-9]+$/,"an exact version, such as 2.1.290").nullable().optional(),deployedRevisions:E.array(E.object({repository:Gl,revision:uf}).strict()).optional(),statedRevisions:E.array(E.object({repository:Gl,revision:uf}).strict()).optional()}).strict(),$5e={providerRunAttempt:E.number().int().positive(),workflowRef:E.string().min(1)},t7t=E.string().regex(/^[^/]+\/[^/]+\/[1-9][0-9]{0,15}\/[1-9][0-9]{0,15}$/),r7t=E.object({schemaVersion:E.literal(1),runId:So,execution:E.discriminatedUnion("provider",[E.object({...$5e,provider:E.literal("github"),repository:E.object(kq).strict(),providerRunId:ql}).strict(),E.object({...$5e,provider:E.literal("azure-devops"),repository:E.object(Bq).strict(),providerRunId:t7t}).strict()]),requester:E.literal(!0).optional(),writeCheck:E.literal(!0).optional(),claudeCodePin:E.literal(!0).optional(),deployedPins:E.literal(!0).optional(),statedPins:E.literal(!0).optional()}).strict(),q5e=E.object({repository:Gl,number:ql}).strict(),n7t=E.discriminatedUnion("status",[E.object({status:E.literal("none")}).strict(),E.object({status:E.literal("delivered"),pullRequests:E.array(q5e).min(1)}).strict(),E.object({status:E.literal("partial"),pullRequests:E.array(q5e).min(1),failures:E.array(E.object({repository:Gl,message:E.string()}).strict()).min(1)}).strict(),E.object({status:E.literal("failed"),message:E.string()}).strict()]),s7t=E.object({sufficiency:E.nativeEnum(wh),rationale:E.string().min(1),gaps:E.array(E.string().min(1)),acceptedEvidence:E.array(E.object({kind:E.nativeEnum(bh),repository:E.string().min(1),revision:uf,reference:E.string().min(1),summary:E.string().min(1)}).strict()),actionRequired:E.array(E.nativeEnum(Ib))}).strict().superRefine((e,t)=>{e.sufficiency==="insufficient"!=e.gaps.length>0&&t.addIssue({code:E.ZodIssueCode.custom,path:["gaps"],message:"only insufficient evidence names gaps, and it names at least one"}),new Set(e.actionRequired).size!==e.actionRequired.length&&t.addIssue({code:E.ZodIssueCode.custom,path:["actionRequired"],message:"a reason appears twice"})}),wv=500,Die=2048,Oie=1e3,i7t=/[\\/:*?"<>|;#$*{},+=[\]%\p{Cc}\p{Cf}]/u,G5e=e=>e.length>0&&e.length<=64&&e===e.trim()&&!i7t.test(e)&&!/[^\S ]/u.test(e)&&!/^[._]/.test(e)&&!e.endsWith("."),o7t=e=>{if(/^[A-Za-z0-9._-]{1,100}\/[A-Za-z0-9._-]{1,100}$/.test(e))return!0;let[t,r,n,...s]=e.split("/");return e.length<=201&&s.length===0&&n!==void 0&&/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,48}[A-Za-z0-9])?$/.test(t)&&G5e(r)&&G5e(n)},a7t=E.object({testResults:E.array(E.object({resultId:E.string().regex(/^[^\u0000-\u001f]{1,512}$/),repository:E.string().refine(o7t,"Invalid"),testType:E.string(),endpoint:E.string(),status:E.enum(["Pass","Fail","Skipped"]),details:E.string(),fileName:E.string().optional(),testId:E.string().regex(/^[^\u0000-\u001f]{1,512}$/).optional(),failureCause:E.object({kind:E.nativeEnum(IR),family:E.nativeEnum(eQ).optional()}).strict().optional(),origin:E.nativeEnum(ZO).optional()}).strict()),validation:s7t,changes:E.array(E.object({id:E.string().min(1).max(512),text:E.string().max(16384),source:E.string().max(Die),testedBy:E.array(E.string().min(1).max(1024)).max(wv),writtenBy:E.array(E.string().min(1).max(1024)).max(wv),maintainedBy:E.array(E.string().min(1).max(1024)).max(wv)}).strict()).max(Oie).optional(),traceVersion:E.literal(1)}).passthrough().superRefine((e,t)=>{let r=new Set;e.testResults.forEach((n,s)=>{let i=n.failureCause;i&&n.status==="Pass"&&t.addIssue({code:E.ZodIssueCode.custom,path:["testResults",s,"failureCause"],message:"a passing result has no failure cause"}),i&&i.kind==="environment"!=(i.family!==void 0)&&t.addIssue({code:E.ZodIssueCode.custom,path:["testResults",s,"failureCause"],message:"an environment cause names its family, and no other cause does"});let o=["testResults",s,"resultId"],a=n.resultId.slice(`${n.repository}:${n.testType}:`.length);(!n.resultId.startsWith(`${n.repository}:${n.testType}:`)||a===""||a.startsWith("/")||a.startsWith("#"))&&t.addIssue({code:E.ZodIssueCode.custom,path:o,message:"is not repository:testType:path for this result"}),r.has(n.resultId)&&t.addIssue({code:E.ZodIssueCode.custom,path:o,message:"stable identity repeated"}),r.add(n.resultId)})}),j5e=e=>e.replace(/[%:#]/g,t=>encodeURIComponent(t));function Nq(e,t,r,n){let s=r.replace(/\\/g,"/"),i=s.split("/").filter(c=>c!==""&&c!==".");if(s.startsWith("/")||/^[A-Za-z]:/.test(s)||i.length===0||i.includes(".."))throw new Error(`testResultId needs a path relative to the repository root, got "${r}"`);let o=i.join("/"),a=`${e}:${t}:${j5e(o)}`;return n?`${a}#${j5e(n)}`:a}var Qie=50,H5e=E.string().regex(/^(?!.*\.\.)(?!\/)(?!.*\/$)[A-Za-z0-9._/-]{1,255}$/),Mie=E.discriminatedUnion("kind",[E.object({kind:E.literal("branch_pushed"),repository:Gl,branch:H5e,commit:uf}).strict(),E.object({kind:E.enum(["pull_request_opened","pull_request_edited"]),repository:Gl,number:ql,branch:H5e}).strict()]),e9e=E.object({schemaVersion:E.literal(1),run:E.object({runId:So,attemptNumber:E.number().int().positive(),manifestHash:Co}).strict(),target:Cq,policy:Cq,provenance:E.object({sources:E.array(E.object({repository:Gl,revision:uf}).strict()),firstQualification:E.literal(!0).optional()}).strict(),delivery:E.object({generatedTests:n7t}).strict(),producer:E.object({testbot:E.string().regex(/^[0-9A-Za-z.+-]{1,64}$/),mcp:E.string().regex(/^[0-9A-Za-z.+-]{1,64}$/)}).strict(),report:a7t,githubWrites:E.array(Mie).max(Qie).optional()}).strict(),c7t=e9e.pick({schemaVersion:!0,run:!0,target:!0,provenance:!0,producer:!0}).extend({recipe:Sq}).strict().superRefine(({recipe:e},t)=>{let r=(i,o)=>t.addIssue({code:E.ZodIssueCode.custom,path:["recipe",...i],message:o});e.status==="blocked"&&e.blockers.length===0&&r(["blockers"],"a blocked recipe names at least one blocker");let n=new Set,s=0;e.files.forEach((i,o)=>{$m(i.path)||r(["files",o,"path"],"is not .skyramp/workspace.yml or a file under .skyramp/sut/"),n.has(i.path)&&r(["files",o,"path"],"file repeated"),n.add(i.path),SQ.test(i.content)&&r(["files",o,"content"],"is not text");let a=Buffer.byteLength(i.content,"utf8");s+=a,a>MA&&r(["files",o,"content"],`larger than ${MA} bytes`)}),s>FA&&r(["files"],`recipe text over ${FA} bytes in total`)}),l7t=E.object({components:E.array(E.object({name:E.string().min(1),repository:E.string().regex(/^[A-Za-z0-9._-]{1,100}\/[A-Za-z0-9._-]{1,100}$/),observedRevision:E.string().regex(/^[0-9a-f]{7,64}$/).nullable(),source:E.nativeEnum(xR),evidence:E.string()}).strict().refine(e=>e.source!=="agent"||e.observedRevision===null,{path:["observedRevision"],message:"a component only an agent session can read names no revision"}))}).strict();function t9e(e,t){if(e.trigger.kind!=="revision_read"&&e.trigger.kind!=="schedule")throw new Error(`The deployed revisions upload is invalid: only a revision_read or scheduled run sends one, not a ${e.trigger.kind} run`);let r=e.sources.map(s=>`${s.repository.namespace}/${s.repository.name}`),n=l7t.safeParse({components:t.map((s,i)=>{let o=r.find(a=>a.toLowerCase()===s.repository.toLowerCase());if(!o)throw new Error(`The deployed revisions upload is invalid: components.${i}.repository: ${s.repository} is not a source of the run`);return{...s,repository:o,evidence:s.evidence.trim()}})});if(!n.success)throw new Error(`The deployed revisions upload is invalid: ${Yie(n.error)}`);return n.data}var r9e=E.object({schemaVersion:E.literal(1),stage:E.nativeEnum(kie),event:E.nativeEnum(Bie),status:E.nativeEnum(Nie).optional()}).strict().refine(e=>e.status===void 0||e.event==="finished",{path:["status"],message:"only a finished stage has a status"}),_d=100,jm=5e3,xB=2e3,RB=100,Pq=/^[A-Za-z0-9_-]{1,64}$/,Fie=20,Lie=200,Uie=100,$ie=100,u7t=200,z5e="[^/\\s](?:(?:[^/\\s]| )*[^/\\s])?",d7t=new RegExp(`^(?:[^/\\s]+/[^/\\s]+|[^/\\s]+/${z5e}/${z5e})$`),qie=500,Gie=50,PB=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/,Jc=e=>E.string().max(e).refine(t=>t.trim().length>0&&!PB.test(t),"blank, or not text"),lf={sequence:E.number().int().min(1).max(jm),at:E.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?Z$/)},jie=E.discriminatedUnion("kind",[E.object({...lf,kind:E.literal("log"),phase:E.nativeEnum(NB),text:Jc(xB)}).strict(),E.object({...lf,kind:E.literal("component"),name:Jc(RB),repository:Jc(u7t).refine(e=>d7t.test(e)||e===Tr,"not owner/name"),file:Jc(qie).nullable(),status:E.nativeEnum(Cv),version:Jc($ie).optional()}).strict(),E.object({...lf,kind:E.literal("reply"),to:E.string().uuid(),accepted:E.boolean(),text:Jc(xB)}).strict(),E.object({...lf,kind:E.literal("question"),id:E.string().regex(Pq),type:E.nativeEnum(Tq),text:Jc(xB),component:Jc(RB).nullable(),choices:E.array(Jc(Lie)).max(Fie),placeholder:Jc(Uie).optional()}).strict(),E.object({...lf,kind:E.literal("delivered"),ids:E.array(E.string().uuid()).max(_d)}).strict(),E.object({...lf,kind:E.literal("credentials"),names:E.array(E.string().regex(Bh)).min(1).max(Gie)}).strict()]).superRefine((e,t)=>{e.kind==="credentials"&&new Set(e.names).size!==e.names.length&&t.addIssue({code:E.ZodIssueCode.custom,path:["names"],message:"a name twice"}),e.kind==="question"&&(e.type==="free_text"!=(e.choices.length===0)&&t.addIssue({code:E.ZodIssueCode.custom,path:["choices"],message:"choices exactly when the question is not free_text"}),new Set(e.choices).size!==e.choices.length&&t.addIssue({code:E.ZodIssueCode.custom,path:["choices"],message:"a choice twice"}))}),n9e=E.object({schemaVersion:E.literal(1),events:E.array(jie).max(_d)}).strict(),Hie=E.discriminatedUnion("kind",[E.object({...lf,kind:E.literal("log"),stage:E.nativeEnum(Gm),text:Jc(xB)}).strict(),E.object({...lf,kind:E.literal("reply"),to:E.string().uuid(),accepted:E.boolean(),text:Jc(xB)}).strict(),E.object({...lf,kind:E.literal("delivered"),ids:E.array(E.string().uuid()).max(_d)}).strict()]),s9e=E.object({schemaVersion:E.literal(1),events:E.array(Hie).max(_d)}).strict(),V5e={id:E.string().uuid(),text:E.string(),by:E.string().nullable(),at:E.string(),replied:E.literal(!0).optional()},i9e=E.discriminatedUnion("kind",[E.object({...V5e,kind:E.literal("instruction"),question:E.null()}),E.object({...V5e,kind:E.literal("answer"),question:E.string().regex(Pq)})]),o9e=E.string().regex(/^[A-Za-z0-9+/]{43}=$/),p7t=E.object({id:E.string().uuid(),revision:E.string(),by:E.string().nullable(),at:E.string(),target:E.string(),own:E.object({source:E.enum(["policy","test_environment"]),text:E.string()}).nullable()}),a9e=E.object({schemaVersion:E.literal(1),leftOut:E.array(E.string()),messages:E.array(i9e).optional(),stop:E.object({key:o9e}).optional(),notes:p7t.optional()}),c9e=E.object({schemaVersion:E.literal(1),messages:E.array(i9e).optional()}),_B=7,_q=500*1024*1024,l9e=E.object({id:ql,name:E.string().regex(/^[A-Za-z0-9._-]{1,200}$/),providerRunId:ql,expiresAt:E.string().datetime()}).strict(),u9e=E.object({schemaVersion:E.literal(1),artifact:l9e,sessionId:So,contentHash:Co,bytes:E.number().int().min(1).max(_q)}).strict(),d9e=E.object({schemaVersion:E.literal(1),checkpoint:E.object({artifact:l9e,repository:E.object({namespace:E.string().min(1),name:E.string().min(1)}).strict(),sessionId:So,contentHash:Co,key:o9e}).strict().nullable()}).strict(),f7t=200,Ev=100,Dq=(n=>(n.Resume="resume",n.Retry="retry",n.Update="update",n))(Dq||{}),h7t=E.object({kind:E.nativeEnum(Dq),setup:E.object({runId:So,endedAt:E.string().nullable(),outcome:E.string().nullable()}).strict(),components:E.array(E.object({name:E.string().min(1),repository:E.string().min(1),status:E.nativeEnum(Cv)}).strict()).max(Ev),credentials:E.array(E.string().min(1)).max(Ev),answers:E.array(E.object({question:E.string(),answer:E.string().nullable()}).strict()).max(Ev),instructions:E.array(E.object({text:E.string(),reply:E.string().nullable()}).strict()).max(Ev),log:E.array(E.object({phase:E.nativeEnum(NB),text:E.string()}).strict()).max(f7t),recipe:E.object({files:E.array(E.object({path:E.string().min(1),content:E.string()}).strict()).max(Ev),blockers:E.array(E.object({component:E.string(),problem:E.string(),evidence:E.string(),fix:E.string()}).strict()).max(Ev)}).strict().optional()}).strict(),p9e=E.object({schemaVersion:E.literal(1),context:h7t.nullable()}).strict(),f9e=E.object({schemaVersion:E.literal(1),configuration:E.object({captureId:So,revision:ql.nullable(),hash:Co}).strict(),capture:E.object({schemaVersion:E.literal(1),settings:E.object({target:E.object({environment:E.unknown()}).passthrough(),timeoutMinutes:E.number().int().positive(),answerWaitMinutes:E.number().int().positive().optional(),testEnvironment:E.object({name:E.string().min(1),address:E.string().min(1).optional(),readyWhen:E.string().min(1).optional()}).passthrough().optional()}).passthrough(),provenance:E.object({}).passthrough(),hash:Co}).strict()}).strict(),m7t=Ub.extend({version:E.number().int().positive(),components:E.array(E.object({name:E.string().min(1),repository:E.string().min(1)}).strict()),contentHash:Co.optional(),files:E.array(E.object({path:E.string().refine(e=>$m(e)&&!yv.includes(e),"not a file of a customer_deployed plan"),content:E.string()}).strict()).optional()}).strict(),h9e=E.object({schemaVersion:E.literal(1),testEnvironment:m7t.nullable().optional(),runtimePlan:E.object({version:E.number().int().positive(),contentHash:Co,files:E.array(E.object({path:E.string().refine($m,"not a recipe file path"),content:E.string()}).strict()).min(1),recipe:E.record(E.unknown()).optional()}).strict().nullable()}).strict().refine(e=>!(e.runtimePlan&&e.testEnvironment),{message:"a run pins a recipe or a customer's Test Environment, never both",path:["testEnvironment"]}),m9e=E.object({schemaVersion:E.literal(1),state:E.nativeEnum(Y5e),ending:E.nativeEnum(xq).nullable(),cause:E.nativeEnum(Rq).nullable(),deadlineAt:E.string().datetime()}).strict();function zie(e,t){return e.state==="ended"?e.ending==="cancelled"?"cancelled":e.cause==="runner_lost"?"expired":"ended":t.getTime()>=Date.parse(e.deadlineAt)?"expired":null}function qm(e){if(typeof e=="number"&&!Number.isFinite(e))throw new TypeError("Canonical JSON requires JSON values");if(Array.isArray(e))return`[${e.map(qm).join(",")}]`;if(e!==null&&typeof e=="object"){let r=e;return`{${Object.keys(r).sort().map(n=>`${JSON.stringify(n)}:${qm(r[n])}`).join(",")}}`}let t=JSON.stringify(e);if(t===void 0)throw new TypeError("Canonical JSON requires JSON values");return t}function Vie(e){return(0,kB.createHash)("sha256").update(qm(e),"utf8").digest("hex")}function g9e(e){let t=[...e].sort((r,n)=>r.path<n.path?-1:r.path>n.path?1:0).map(r=>({path:r.path,content:r.content}));return(0,kB.createHash)("sha256").update(qm(t),"utf8").digest("hex")}function A9e(e){let t=(i,o)=>i<o?-1:i>o?1:0,r=[...e.files].sort((i,o)=>t(i.path,o.path)).map(i=>({path:i.path,content:i.content})),n={address:e.address,readyWhen:e.readyWhen,credentials:[...e.credentials].sort(t),revisionSources:e.revisionSources.map(i=>qm({method:i.method,detail:i.detail,components:[...i.components].sort(t)})).sort(t)},s=e.components.map(i=>qm({name:i.name,repository:i.repository})).sort(t);return(0,kB.createHash)("sha256").update(qm({type:"customer_deployed",environment:n,components:s,files:r}),"utf8").digest("hex")}function y9e(e){return(0,kB.createHash)("sha256").update(qm({schemaVersion:e.schemaVersion,settings:e.settings,provenance:e.provenance}),"utf8").digest("hex")}var TB=e=>({provider:e.provider,providerAccountId:e.providerAccountId,providerRepositoryId:e.providerRepositoryId});function Wie(e,t,{statedPins:r=!0}={}){return r7t.parse({schemaVersion:1,runId:e,execution:t.execution(),requester:!0,writeCheck:!0,claudeCodePin:!0,deployedPins:!0,...r?{statedPins:!0}:{}})}function E9e(e){let t=e7t.parse(e);if(Vie(t.manifest)!==t.manifestHash)throw new Error("The handshake manifest hash does not match its manifest");return t}function g7t(e){let t=r=>r.map(n=>({repository:TB(n.repository),number:n.number}));return e.status==="delivered"?{status:e.status,pullRequests:t(e.pullRequests)}:e.status==="partial"?{status:e.status,pullRequests:t(e.pullRequests),failures:e.failures.map(r=>({repository:TB(r.repository),message:r.message}))}:e}function Yie(e){return e.issues.map(t=>`${t.path.map((n,s)=>typeof n=="number"?`[${n}]`:s===0?n:`.${n}`).join("")}: ${t.message}`).join("; ")}function w9e(e){let{manifest:t}=e;if(WZt.includes(t.trigger.kind))throw new Error(`The report upload is invalid: a ${t.trigger.kind} run uploads its SUT recipe, never a report`);if(t.trigger.kind==="revision_read")throw new Error("The report upload is invalid: a revision_read run uploads what each component runs, never a report");if(e.firstQualification&&!t.baseline?.sources)throw new Error("The report upload is invalid: only a run whose manifest names baseline sources can be a first qualification");let r=e9e.safeParse({schemaVersion:1,run:{runId:t.runId,attemptNumber:e.attemptNumber,manifestHash:Vie(t)},target:{id:t.target.id,revision:t.target.revision},policy:t.policy&&{id:t.policy.id,revision:t.policy.revision},provenance:{sources:e.checkedOut.map(n=>({repository:TB(n.repository),revision:n.revision})),...e.firstQualification?{firstQualification:!0}:{}},delivery:{generatedTests:g7t(e.generatedTests)},producer:e.producer,report:e.report,...e.githubWrites?.length?{githubWrites:e.githubWrites.map(n=>({...n,repository:TB(n.repository)}))}:{}});if(!r.success)throw new Error(`The report upload is invalid: ${Yie(r.error)}`);return A7t(r.data,t,e.checkedOut),r.data}function b9e(e,t,r,n,s){let i=c7t.safeParse({schemaVersion:1,run:{runId:e.runId,attemptNumber:t,manifestHash:Vie(e)},target:{id:e.target.id,revision:e.target.revision},provenance:{sources:r.map(o=>({repository:TB(o.repository),revision:o.revision}))},producer:s,recipe:n});if(!i.success)throw new Error(`The SUT recipe upload is invalid: ${Yie(i.error)}`);return i.data}function A7t(e,t,r){let n=i=>r.find(o=>Pr(o.repository)===Pr(i.repository))?.revision??i.revision,s=new Map(t.sources.map(i=>[`${i.repository.namespace}/${i.repository.name}`.toLowerCase(),n(i)]));e.report.validation.acceptedEvidence.forEach((i,o)=>{let a=`report.validation.acceptedEvidence[${o}]`,c=s.get(i.repository.toLowerCase());if(!c)throw new Error(`${a}.repository: ${i.repository} is outside the run's snapshot`);if(i.revision!==c)throw new Error(`${a}.revision: evidence is not from the checked-out revision ${c}`)})}var y7t="7.1-preview.1",E7t=".azure-pipelines/skyramp-testbot-v3.yml";function fE(e){return e.GITHUB_ACTIONS!=="true"&&/^true$/i.test(e.TF_BUILD??"")}var w7t={INPUT_PIPELINE:"SKYRAMP_TESTBOT_PIPELINE",INPUT_SKYRAMPRUNID:"SKYRAMP_RUN_ID",INPUT_SKYRAMPAPPORIGIN:"SKYRAMP_APP_ORIGIN",INPUT_SKYRAMPMCPVERSION:"SKYRAMP_MCP_VERSION",INPUT_SKYRAMPMCPSOURCE:"SKYRAMP_MCP_SOURCE",INPUT_SKYRAMPMCPGITHUBREF:"SKYRAMP_MCP_GITHUB_REF",INPUT_SKYRAMPMCPGITHUBTOKEN:"SKYRAMP_MCP_GITHUB_TOKEN",INPUT_USEBEDROCK:"SKYRAMP_USE_BEDROCK",INPUT_AWSREGION:"SKYRAMP_AWS_REGION",INPUT_AWSROLEARN:"SKYRAMP_AWS_ROLE_ARN"};function C9e(e=process.env){if(fE(e))for(let[t,r]of Object.entries(w7t))!e[t]&&e[r]!==void 0&&(e[t]=e[r])}function v9e(e,t={}){let r=d=>{let p=e[d];if(!p)throw new Error(`${d} is not set; the V3 runner handshake needs it`);return p},n=pE(e.SYSTEM_COLLECTIONURI??""),s=()=>Eie(r("SYSTEM_COLLECTIONURI")),i=e.SYSTEM_TEAMPROJECT,o=e.BUILD_REPOSITORY_NAME,a=e.BUILD_REPOSITORY_ID?.toLowerCase(),c=e.SYSTEM_ACCESSTOKEN,l=t.mask??(d=>v5e(d)),u=d=>async()=>{if(!d)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_OIDCREQUESTURI to $(System.OidcRequestUri).");if(!c)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_ACCESSTOKEN to $(System.AccessToken).");let p=new URL(d);if(p.protocol!=="https:")throw new Error("SYSTEM_OIDCREQUESTURI is not an https URL");p.searchParams.set("api-version",y7t);let f=await(t.fetch??fetch)(p.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json",Accept:"application/json"},body:"{}",redirect:"error",signal:AbortSignal.timeout(3e4)});if(!f.ok)throw new Error(`Azure DevOps refused the OIDC token request: ${f.status}`);let m=(await f.json().catch(()=>({}))).oidcToken;if(typeof m!="string"||!m)throw new Error("Azure DevOps's OIDC token response carried no token");return l(m),m};return{runnerPlatform:fE(e)?"azure":void 0,workspace:e.BUILD_SOURCESDIRECTORY||void 0,serverUrl:n,apiUrl:n,repository:a&&i&&o&&n?{id:a,slug:`${s()}/${i}/${o}`}:void 0,runId:e.BUILD_BUILDID||void 0,runAttempt:e.SYSTEM_STAGEATTEMPT||void 0,job:e.SYSTEM_JOBNAME||void 0,execution(){let d=r("SYSTEM_STAGEATTEMPT");if(!/^[1-9][0-9]*$/.test(d))throw new Error(`SYSTEM_STAGEATTEMPT is "${d}", not a positive whole number`);let p=r("SYSTEM_COLLECTIONID").toLowerCase();if(!vv.test(p))throw new Error(`SYSTEM_COLLECTIONID is "${p}", not a GUID`);let f=r("BUILD_REPOSITORY_ID").toLowerCase();if(!vv.test(f))throw new Error(`BUILD_REPOSITORY_ID is "${f}", not a GUID`);let m=[s(),r("SYSTEM_TEAMPROJECT"),r("SYSTEM_DEFINITIONID"),r("BUILD_BUILDID")].map(encodeURIComponent).join("/");return{provider:"azure-devops",repository:{provider:"azure-devops",providerAccountId:p,providerRepositoryId:f},providerRunId:m,providerRunAttempt:Number(d),workflowRef:`${E7t}@${r("BUILD_SOURCEBRANCH")}`}},takeIdToken(){let d=e.SYSTEM_OIDCREQUESTURI;delete e.SYSTEM_OIDCREQUESTURI;let p=u(d);return()=>p()},takeSourceToken(){return delete e.SYSTEM_ACCESSTOKEN,c||void 0},webIdentity(){if(!e.SYSTEM_OIDCREQUESTURI?.trim()||!c)return;let d=u(e.SYSTEM_OIDCREQUESTURI);return{token:()=>d(),runId:e.BUILD_BUILDID}},v3RunsOnly:!0,assumesBedrockRole:!0,namesSourceToMcp:!0,checkSourceName(d){wq(d)},cloneUrl(d){return T5e(n,wq(d))},gitAuthEnv(d){return bq(n,d)},async pullRequest(d,p,f){let m=await CB({token:await f.token(),url:`${SB(n,wq(d))}/pullrequests/${p}`,fetch:f.fetch}),g=m.status==="completed";return{...typeof m.title=="string"?{title:m.title}:{},...typeof m.description=="string"?{body:m.description}:{},...typeof m.status=="string"?{merged:g}:{},...g&&typeof m.lastMergeCommit?.commitId=="string"?{mergeCommit:m.lastMergeCommit.commitId}:{},...g&&typeof m.lastMergeSourceCommit?.commitId=="string"?{mergedHead:m.lastMergeSourceCommit.commitId}:{}}},async commit(d,p,f){let m;try{m=SB(n,bB(d))}catch{return{lookup:"unknown"}}try{let g=await CB({token:await f.token(),url:`${m}/commits/${encodeURIComponent(p)}`,fetch:f.fetch});return typeof g.commitId=="string"?{sha:g.commitId}:{lookup:"missing"}}catch(g){return{lookup:g instanceof wB&&(g.status===404||g.status===400)?"missing":"unknown"}}}}}Gt();var b7t=5e3,Kie=/^(?!\.\.?$)[A-Za-z0-9._-]{1,100}$/;function S7t(e){let t=Buffer.from(`x-access-token:${e}`).toString("base64");return fn(t),`AUTHORIZATION: basic ${t}`}function I9e(e,t={}){let r=c=>{let l=e[c];if(!l)throw new Error(`${c} is not set; the V3 runner handshake needs it`);return l},n=e.GITHUB_REPOSITORY_ID,s=e.GITHUB_REPOSITORY,i=(e.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,""),o=(e.GITHUB_API_URL||"https://api.github.com").replace(/\/+$/,""),a=async(c,l)=>l.fetch(c,{headers:{Authorization:`Bearer ${await l.token()}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(3e4)});return{runnerPlatform:e.GITHUB_ACTIONS==="true"?"github":void 0,workspace:e.GITHUB_WORKSPACE||void 0,serverUrl:i,apiUrl:o,repository:n&&s?{id:n,slug:s}:void 0,runId:e.GITHUB_RUN_ID||void 0,runAttempt:e.GITHUB_RUN_ATTEMPT||void 0,job:e.GITHUB_JOB||void 0,execution(){let c=r("GITHUB_RUN_ATTEMPT");if(!/^[1-9][0-9]*$/.test(c))throw new Error(`GITHUB_RUN_ATTEMPT is "${c}", not a positive whole number`);return{provider:"github",repository:{provider:"github",providerAccountId:r("GITHUB_REPOSITORY_OWNER_ID"),providerRepositoryId:r("GITHUB_REPOSITORY_ID")},providerRunId:r("GITHUB_RUN_ID"),providerRunAttempt:Number(c),workflowRef:r("GITHUB_WORKFLOW_REF")}},takeIdToken(){let c=e.ACTIONS_ID_TOKEN_REQUEST_URL,l=e.ACTIONS_ID_TOKEN_REQUEST_TOKEN;return delete e.ACTIONS_ID_TOKEN_REQUEST_URL,delete e.ACTIONS_ID_TOKEN_REQUEST_TOKEN,async u=>{if(!c||!l)throw new Error("The job cannot request an OIDC token. Give it the `id-token: write` permission.");let d=new URL(c);d.searchParams.set("audience",u);let p=await fetch(d,{headers:{Authorization:`Bearer ${l}`,Accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!p.ok)throw new Error(`GitHub refused the OIDC token request: ${p.status}`);let f=(await p.json().catch(()=>({}))).value;if(typeof f!="string"||!f)throw new Error("GitHub's OIDC token response carried no token");return fn(f),f}},webIdentity(){return!e.ACTIONS_ID_TOKEN_REQUEST_TOKEN?.trim()||!e.ACTIONS_ID_TOKEN_REQUEST_URL?.trim()?void 0:{token:t.getIDToken??(l=>Rye(l)),runId:e.GITHUB_RUN_ID}},v3RunsOnly:!1,assumesBedrockRole:!1,namesSourceToMcp:!1,checkSourceName(c){for(let l of[c.namespace,c.name])if(!Kie.test(l))throw new Error(`"${l}" is not a repository name`)},cloneUrl(c){return`${i}/${c.namespace}/${c.name}.git`},gitAuthEnv(c){return c?{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${i}/.extraheader`,GIT_CONFIG_VALUE_0:S7t(c)}:{}},async pullRequest({namespace:c,name:l},u,d){if(![c,l].every(m=>Kie.test(m)))throw new Error("the repository name is not valid");let p=await a(`${o}/repos/${c}/${l}/pulls/${u}`,d);if(!p.ok)throw new Error(`GitHub answered ${p.status}`);let f=await p.json();return{...typeof f.title=="string"?{title:f.title}:{},...typeof f.body=="string"?{body:f.body}:{},...typeof f.merged=="boolean"?{merged:f.merged}:{},...f.merged===!0&&typeof f.merge_commit_sha=="string"?{mergeCommit:f.merge_commit_sha}:{},...f.merged===!0&&typeof f.head?.sha=="string"?{mergedHead:f.head.sha}:{}}},async commit(c,l,u){let[d,p,...f]=c.split("/");if(f.length||![d,p].every(m=>m!==void 0&&Kie.test(m)))return{lookup:"unknown"};try{let m=await a(`${o}/repos/${d}/${p}/commits/${encodeURIComponent(l)}`,u);if(m.status===404||m.status===422)return{lookup:"missing"};if(!m.ok)return{lookup:"unknown"};let g=await m.json();return typeof g.sha=="string"?{sha:g.sha}:{lookup:"missing"}}catch{return{lookup:"unknown"}}},async revokeToken(c,l){let u=await l(`${o}/installation/token`,{method:"DELETE",headers:{Authorization:`Bearer ${c}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(b7t)});if(!u.ok&&u.status!==401)throw new Error(`GitHub answered ${u.status}`)}}}function cn(e=process.env){return fE(e)?v9e(e):I9e(e)}function x9e(e){if(e!=="staged")return`This Testbot engine runs only the staged pipeline, not "${e}". Set the pipeline input to "staged", or pin skyramp/testbot@v0.11 for the classic pipeline.`}var Tsn=["local","github","azure"];function R9e(e,t,r=cn()){if(r.runnerPlatform!=="azure")return new gB(e);let n=bie();if(!t||!n||!e.repoSlug||!e.tokenProvider)throw new Error("On Azure Pipelines, Testbot runs only the Validation Runs and SUT setups the Skyramp app starts: the step needs INPUT_SKYRAMPRUNID and the job's predefined variables.");return new vB({repositoryPath:e.repositoryPath,repoSlug:e.repoSlug,pipelineRun:n,tokenProvider:e.tokenProvider,log:e.log,reportUrl:t})}var B9e=require("child_process"),df=J(require("fs")),Za=J(require("path")),N9e=(e,t)=>(0,B9e.execFileSync)("git",["-c","safe.directory=*",...Ss,...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"],env:nt()}),P9e="^(http(\\..*)?\\.extraheader|core\\.sshcommand)$",I7t="core.sshcommand",Oq=e=>e instanceof Error?e.message.split(`
|
|
379
|
+
${n.output}`:`deploy reported ${t.outcome} without the failing command`,fix:t.outcome==="change-broke-bringup"?`fix the change that broke bring-up${s}, then onboard again`:r.length>0?UZt(r):"make .skyramp/sut/setup.sh bring the SUT up from a clean checkout (what onboard's session had that a fresh run lacks), then onboard again"}}var IB="a GitHub Actions secret, or on Azure DevOps a secret variable in the host repository's skyramp-testbot variable group under Pipelines \u203A Library";function UZt(e){let t=e.length===1;return`add ${t?"a secret":"secrets"} named ${e.join(", ")} on the workflow host, ${t?"as":"each as"} ${IB}, then Retry: Skyramp adds ${t?"it":"them"} to the Target's credentials, and the replay gets ${t?"its value":"their values"}. If it still fails, make .skyramp/sut/setup.sh bring the SUT up from a clean checkout`}function $Zt(e){return e.environment?{component:e.components.map(t=>t.name).join(", ")||"SUT",problem:"the deployment was never checked from a fresh session: deploy did not run or wrote no deploy.json",evidence:"outputs/deploy.json is missing from this run",fix:"run deploy after onboard in the same run so it checks the deployment is ready; if deploy ran, its stage log says why it wrote no deploy.json"}:{component:e.components.map(t=>t.name).join(", ")||"SUT",problem:"the recipe was never replayed: deploy did not run or wrote no deploy.json",evidence:"outputs/deploy.json is missing from this run",fix:"run deploy after onboard in the same run so it replays .skyramp/sut/setup.sh from a clean start; if deploy ran, its stage log says why it wrote no deploy.json"}}function qZt(e){return{component:e.components.map(t=>t.name).join(", ")||"SUT",problem:`${cf}: setup ran out of time while checking ${e.environment?"that the deployment is ready":"that the app comes up from a clean start"}. Every component was up before that.`,evidence:"The check from a fresh session didn't finish.",fix:"Retry: setup carries on from what this one found and finishes checking."}}function GZt(e){return{component:"SUT recipe",problem:"deploy fixed recipe drift, but the recipe it fixed was not collected \u2014 onboard's copy is the recipe from before the fix",evidence:`deploy reported recipe-drift: ${(e.recipeFixes??[]).join("; ")||"no fixes listed"}`,fix:"collect .skyramp/sut/ and .skyramp/workspace.yml after deploy (collectRecipeFiles) and build the plan from that collection"}}var vie=[".skyramp/sut/setup.sh",".skyramp/sut/teardown.sh",".skyramp/sut/health.json",".skyramp/workspace.yml"],Iie=[".skyramp/sut/health.json",".skyramp/workspace.yml"];function jZt(e){return`Onboard again so it leaves the whole recipe in the checkout: ${e.map(r=>r===".skyramp/workspace.yml"?"create .skyramp/workspace.yml with skyramp_init_scan and skyramp_init_workspace":`write ${r} as a regular file (a symlink is not uploaded)`).join("; ")}.`}function xie(e,t,r){return t&&r||e}function Rie(e,t,r={}){let n=t!==void 0&&!FZt.includes(t.outcome),s=xie(e,t,r.recipeFiles),i=t?.outcome==="recipe-drift"&&!r.recipeFiles,o=(s.recipeFilesOmitted??[]).filter(v=>$m(v.path)),a=o.length?[{component:"SUT recipe",problem:`The recipe could not be uploaded whole: ${o.map(v=>v.path).join(", ")} left out.`,evidence:o.map(v=>`${v.path}: ${v.reason}`).join("; "),fix:"Keep each recipe file text-only and under 64 KiB, and the recipe under 512 KiB in total \u2014 move large generated content out of .skyramp/sut/ and have setup.sh produce it."}]:[],c=e.status==="ready",l=e.environment,u=new Set(s.recipeFiles.map(v=>v.path)),d=c?(l?Iie:vie).filter(v=>!u.has(v)):[],p=d.length?[{component:"SUT recipe",problem:`The recipe is missing ${d.join(", ")}, so it cannot be replayed.`,evidence:`collected: ${[...u].sort().join(", ")||"nothing"}`,fix:jZt(d)}]:[],f=c&&!l&&(r.awaitsCredentialCheck?.length??0)>0,m=t?n?[LZt(e,t,r.unsupplied??[])]:[]:c&&!f?[r.timeLimit?qZt(e):$Zt(e)]:[],g=new Set(l?.revisionSources.flatMap(v=>v.components)),w=l&&c?e.components.filter(v=>v.repository!==Tr&&!g.has(v.name)).map(v=>v.name):[],A=w.length?[{component:w.join(", "),problem:`Testbot cannot tell which revision ${w.join(" and ")} ${w.length>1?"run":"runs"}, so a run could not say which changes it tested.`,evidence:`revision sources: ${l.revisionSources.map(v=>`${v.detail} (${v.components.join(", ")})`).join("; ")||"none"}`,fix:"Say in the Test Environment's notes how to tell what is deployed, such as a version route (GET /version), then set it up again."}]:[],y=(c?l?.revisionSources??[]:[]).filter(v=>v.method==="not_tracked").map(v=>({component:v.components.join(", "),problem:`Testbot can't tell which commit ${v.components.join(" and ")} ${v.components.length>1?"run":"runs"}, so a run can't say which of ${v.components.length>1?"their":"its"} changes it tested.`,evidence:v.detail,fix:`Say in the Test Environment's notes how to tell what ${v.components.join(" and ")} ${v.components.length>1?"run":"runs"}, such as a version route (GET /version) or a deploy workflow, then set it up again.`})),S=[...e.blockers,...m,...i&&t?[GZt(t)]:[],...a,...p,...A,...y,...r.revisionCheck?.blockers??[],...r.credentialBlockers??[]],C=t?.baseUrls??{};return{schemaVersion:1,...l?{type:"customer_deployed",environment:D5e(l)}:{},status:c&&(t!==void 0||f)&&!n&&!i&&o.length===0&&d.length===0&&w.length===0&&!r.credentialBlockers?.length?"ready":"blocked",components:e.components.map(v=>({name:v.name,repository:v.repository,healthy:v.healthy&&!n,url:Object.hasOwn(C,v.name)&&C[v.name]||null,...v.steps?{steps:v.steps.map(R=>({action:R.action,text:R.text,source:R.source,file:R.file}))}:{},...v.kind?{kind:v.kind}:{},...v.from?{from:{file:v.from.file,service:v.from.service}}:{},...v.credentials?{credentials:[...new Set(v.credentials)].filter(R=>Bh.test(R))}:{},...l?{deployed:HZt(v,r)}:{}})),suites:e.suites.map(v=>({framework:v.framework,file:v.file,result:v.result})),inputsUsed:[...e.inputsUsed],...e.inputsUsedHow?{inputsUsedHow:e.inputsUsedHow.filter(v=>e.inputsUsed.includes(v.input)).map(v=>({input:v.input,how:v.how}))}:{},inputsNotUsed:e.inputsNotUsed.map(v=>({input:v.input,reason:v.reason})),blockers:S.map(v=>({component:v.component,problem:v.problem,evidence:v.evidence,fix:v.fix})),replay:t&&!l?{outcome:t.outcome,durationSeconds:r.deployDurationSeconds??null}:f?{outcome:Cie,durationSeconds:null}:!l&&S.some(v=>v.problem.startsWith(cf))?{outcome:_5e,durationSeconds:null}:null,files:s.recipeFiles.filter(v=>$m(v.path)&&!(l&&yv.includes(v.path))).map(v=>({path:v.path,content:v.content}))}}function HZt(e,t){return e.repository===Tr?null:t.revisionCheck?t.revisionCheck.deployed[e.name]??null:t.deployed?.[e.name]??e.deployed??null}function D5e(e){return{address:e.address,readyWhen:e.readyWhen,credentials:[...new Set(e.credentials)],revisionSources:e.revisionSources.map(t=>({method:t.method,detail:t.detail,components:[...t.components]}))}}function O5e(e){return{schemaVersion:1,status:"ready",components:e.components.map(({url:t,deployed:r,...n})=>({...n,healthy:!0})),suites:e.suites,inputsUsed:e.inputsUsed,...e.inputsUsedHow?{inputsUsedHow:e.inputsUsedHow}:{},inputsNotUsed:e.inputsNotUsed,blockers:[],recipeFiles:e.files,recipeFilesOmitted:[],...e.environment?{environment:D5e(e.environment)}:{}}}var W5e={handshake:"/api/v1/runner/runs/:runId/attempts",report:"/api/v1/runner/attempts/:attemptId/report",end:"/api/v1/runner/attempts/:attemptId/end",configuration:"/api/v1/runner/attempts/:attemptId/configuration",progress:"/api/v1/runner/attempts/:attemptId/progress",sutRecipe:"/api/v1/runner/attempts/:attemptId/sut-recipe",runtimePlan:"/api/v1/runner/attempts/:attemptId/runtime-plan",heartbeat:"/api/v1/runner/attempts/:attemptId/heartbeat",setupEvents:"/api/v1/runner/attempts/:attemptId/setup-events",runEvents:"/api/v1/runner/attempts/:attemptId/run-events",requirements:"/api/v1/runner/attempts/:attemptId/requirements",requirementFile:"/api/v1/runner/attempts/:attemptId/requirements/:key/file",deployedRevisions:"/api/v1/runner/attempts/:attemptId/deployed-revisions"},vq=(r=>(r.GitHub="github",r.AzureDevOps="azure-devops",r))(vq||{}),Tie=(i=>(i.Trigger="TRIGGER",i.Baseline="BASELINE",i.AuthoritativeRelatedChange="AUTHORITATIVE_RELATED_CHANGE",i.ConfiguredSharedDependency="CONFIGURED_SHARED_DEPENDENCY",i.ManualOverride="MANUAL_OVERRIDE",i))(Tie||{}),BB=(o=>(o.PullRequest="pull_request",o.ReadyForReview="ready_for_review",o.Schedule="schedule",o.Manual="manual",o.SutSetup="sut_setup",o.RevisionRead="revision_read",o))(BB||{}),zZt=["sut_setup"],VZt=["sut_setup","schedule","revision_read"],WZt=["sut_setup"],Iq=(t=>(t.PullRequest="pull_request",t))(Iq||{}),bv=(s=>(s.ModelProvider="model_provider",s.SutAccess="sut_access",s.Skyramp="skyramp",s.Other="other",s))(bv||{});var xq=(i=>(i.ReportUploaded="report_uploaded",i.NoReport="no_report",i.Cancelled="cancelled",i.RecipeUploaded="recipe_uploaded",i.RevisionsUploaded="revisions_uploaded",i))(xq||{}),Y5e=(r=>(r.Running="running",r.Ended="ended",r))(Y5e||{}),Rq=(l=>(l.TimedOut="timed_out",l.AgentFailed="agent_failed",l.SetupFailed="setup_failed",l.CredentialMissing="credential_missing",l.RunnerLost="runner_lost",l.CheckoutFailed="checkout_failed",l.EnvironmentUnverified="environment_unverified",l.ModelProviderDenied="model_provider_denied",l.ModelProviderUnavailable="model_provider_unavailable",l))(Rq||{}),kie=(n=>(n.Onboard="onboard",n.Deploy="deploy",n.Recheck="recheck",n))(kie||{}),Bie=(r=>(r.Started="started",r.Finished="finished",r))(Bie||{}),Nie=(n=>(n.Passed="passed",n.Failed="failed",n.Skipped="skipped",n))(Nie||{}),Sv=(o=>(o.Log="log",o.Component="component",o.Reply="reply",o.Question="question",o.Delivered="delivered",o.Credentials="credentials",o))(Sv||{}),Tq=(n=>(n.ChooseCredential="choose_credential",n.FreeText="free_text",n.ChooseSource="choose_source",n))(Tq||{});var NB=(n=>(n.Discover="discover",n.Start="start",n.Check="check",n))(NB||{}),Gm=(s=>(s.ValidationPlan="validation_plan",s.TestEnvironment="test_environment",s.TestConditions="test_conditions",s.Tests="tests",s))(Gm||{}),Cv=(s=>(s.Found="found",s.Starting="starting",s.Up="up",s.OutOfScope="out_of_scope",s))(Cv||{}),ql=E.string().regex(/^[1-9][0-9]{0,18}$/),uf=E.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/),vv=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,So=E.string().regex(vv),Co=E.string().regex(/^[0-9a-f]{64}$/),Cq=E.object({id:So,revision:ql}).strict(),kq={provider:E.literal("github"),providerAccountId:ql,providerRepositoryId:ql},Bq={provider:E.literal("azure-devops"),providerAccountId:So,providerRepositoryId:So},Gl=E.discriminatedUnion("provider",[E.object(kq).strict(),E.object(Bq).strict()]),Pie=E.discriminatedUnion("provider",[E.object(kq).passthrough(),E.object(Bq).passthrough()]),Pr=e=>`${e.provider}:${e.providerRepositoryId}`,Q5e={namespace:E.string().min(1),name:E.string().min(1)},J5e=E.discriminatedUnion("provider",[E.object({...kq,...Q5e}).strict(),E.object({...Bq,...Q5e}).strict()]),M5e=E.object({ref:E.string().min(1),revision:uf}).strict(),YZt=E.object({repository:J5e,revision:uf,ref:E.string().nullable(),reason:E.nativeEnum(Tie),change:E.object({kind:E.nativeEnum(Iq),number:ql,base:M5e.optional()}).strict().nullable(),compareWith:M5e.optional()}).strict();function JZt(e){if(e.trigger.kind==="revision_read"!=!e.baseline)return e.baseline?"a revision_read run names no baseline":"names its baseline";if(!e.baseline)return null;let{confirmedRunId:t,initialBaselineId:r,sources:n}=e.baseline;if(t!==null&&r!==void 0)return"a run compares with one baseline";let s=e.trigger.kind==="schedule"&&t!==null||r!==void 0;if(!n)return s?"names every source of the snapshot, once":null;if(t===null&&r===void 0)return"a run with no Confirmed Baseline names no baseline sources";let i=new Set(e.sources.map(c=>Pr(c.repository))),o=new Set(n.map(c=>Pr(c.repository)));return o.size===n.length&&o.size===i.size&&[...o].every(c=>i.has(c))?null:"names every source of the snapshot, once"}var K5e=/^[A-Z][A-Z0-9_]+-[1-9][0-9]*$/,X5e=/^[1-9][0-9]{0,18}$/,F5e=new RegExp(`${K5e.source}|${X5e.source}`),L5e=/^https:\/\/[a-z0-9-]+(\.[a-z0-9-]+)+$/,KZt=E.union([E.object({source:E.literal("jira"),site:E.string().regex(L5e),key:E.string().regex(K5e),updated:E.string().datetime(),contentHash:Co}).strict(),E.object({source:E.literal("confluence"),site:E.string().regex(L5e),key:E.string().regex(X5e),version:E.number().int().positive(),contentHash:Co}).strict(),E.object({source:E.literal("other"),key:E.string().regex(vR),contentHash:Co}).strict(),E.object({source:E.literal("other"),key:E.string().regex(BA),contentHash:Co,fileName:E.string().min(1).max(255),mediaType:E.nativeEnum(vb)}).strict()]),U5e=E.union([E.literal("jira"),E.literal("confluence")]),Z5e=E.object({schemaVersion:E.literal(1),items:E.array(E.union([E.object({source:U5e,site:E.string(),key:E.string().regex(F5e),state:E.literal("read"),text:E.string(),version:E.string().min(1),contentMatches:E.boolean()}).strict(),E.object({source:U5e,site:E.string(),key:E.string().regex(F5e),state:E.literal("not_read"),reason:E.nativeEnum(kA)}).strict(),E.object({source:E.literal("other"),key:E.string().regex(vR),state:E.literal("read"),text:E.string(),version:E.string().min(1),contentMatches:E.boolean()}).strict(),E.object({source:E.literal("other"),key:E.string().regex(vR),state:E.literal("not_read"),reason:E.nativeEnum(kA)}).strict(),E.object({source:E.literal("other"),key:E.string().regex(BA),state:E.literal("read"),version:Co,fileName:E.string().min(1).max(255),mediaType:E.nativeEnum(vb)}).strict(),E.object({source:E.literal("other"),key:E.string().regex(BA),state:E.literal("not_read"),reason:E.nativeEnum(kA)}).strict()])),instructions:E.array(E.string()).optional()}).strict(),XZt=E.object({schemaVersion:E.literal(1),runId:So,skyrampOrgId:So,target:Cq,policy:Cq.nullable(),trigger:E.object({kind:E.nativeEnum(BB),requestedAt:E.string().datetime()}).strict(),configuration:E.object({captureId:So,revision:ql.nullable(),hash:Co}).strict(),baseline:E.object({confirmedRunId:So.nullable(),initialBaselineId:So.optional(),sources:E.array(E.object({repository:Gl,revision:uf}).strict()).optional()}).strict().optional(),sources:E.array(YZt).min(1),execution:E.object({provider:E.nativeEnum(vq),repository:J5e,workflowPath:E.string(),ref:E.string()}).strict(),credentials:E.array(E.object({name:E.string(),purpose:E.nativeEnum(bv),required:E.boolean()}).strict()),requirements:E.array(KZt).min(1).optional(),instructions:E.object({contentHash:Co}).strict().optional(),deployedRevisions:E.array(E.object({repository:Gl,revision:uf}).strict()).min(1).optional()}).strict().superRefine((e,t)=>{let r=new Set;(e.requirements??[]).forEach((c,l)=>{let u="fileName"in c?"file":"pasted";c.source==="other"&&c.key!==`${u}-${c.contentHash.slice(0,16)}`&&t.addIssue({code:E.ZodIssueCode.custom,message:"is not the key of its content hash",path:["requirements",l,"key"]});let d=ba({source:c.source,key:c.key});r.has(d)&&t.addIssue({code:E.ZodIssueCode.custom,message:"names an item that the run already names",path:["requirements",l,"key"]}),r.add(d)});let n=e.trigger.kind,s=zZt.includes(n);s!==(e.policy===null)&&t.addIssue({code:E.ZodIssueCode.custom,path:["policy"],message:s?`a ${n} run has no policy`:"names the policy revision"});let i=JZt(e);i&&t.addIssue({code:E.ZodIssueCode.custom,path:e.baseline?["baseline","sources"]:["baseline"],message:i}),VZt.includes(n)&&e.sources.forEach((c,l)=>{c.reason!=="BASELINE"&&t.addIssue({code:E.ZodIssueCode.custom,path:["sources",l,"reason"],message:`a ${n} run selects only BASELINE sources`})}),e.deployedRevisions&&n!=="manual"&&t.addIssue({code:E.ZodIssueCode.custom,path:["deployedRevisions"],message:"only a manual run pins deployed revisions"});let o=new Set(e.sources.map(c=>Pr(c.repository))),a=new Set;(e.deployedRevisions??[]).forEach((c,l)=>{let u=Pr(c.repository);o.has(u)?a.has(u)&&t.addIssue({code:E.ZodIssueCode.custom,path:["deployedRevisions",l,"repository"],message:"repository appears twice"}):t.addIssue({code:E.ZodIssueCode.custom,path:["deployedRevisions",l,"repository"],message:"names a repository outside the snapshot"}),a.add(u)}),e.sources.forEach((c,l)=>{c.compareWith&&(c.reason!=="MANUAL_OVERRIDE"||c.change)&&t.addIssue({code:E.ZodIssueCode.custom,path:["sources",l,"compareWith"],message:"only a MANUAL_OVERRIDE source without a change names a revision to compare with"})})});var _ie=(r=>(r.Person="person",r.Policy="policy",r))(_ie||{}),ZZt=E.object({kind:E.nativeEnum(_ie),name:E.string().min(1).max(256)}).strict(),e7t=E.object({schemaVersion:E.literal(1),attempt:E.object({id:So,number:E.number().int().positive(),deadlineAt:E.string().datetime()}).strict(),manifest:XZt,manifestHash:Co,entitlements:E.array(E.string()).optional(),runToken:E.string().min(1).optional(),requestedBy:ZZt.nullable().optional(),writeAllowed:E.boolean().optional(),claudeCodeVersion:E.string().regex(/^[0-9]+\.[0-9]+\.[0-9]+$/,"an exact version, such as 2.1.290").nullable().optional(),deployedRevisions:E.array(E.object({repository:Gl,revision:uf}).strict()).optional(),statedRevisions:E.array(E.object({repository:Gl,revision:uf}).strict()).optional()}).strict(),$5e={providerRunAttempt:E.number().int().positive(),workflowRef:E.string().min(1)},t7t=E.string().regex(/^[^/]+\/[^/]+\/[1-9][0-9]{0,15}\/[1-9][0-9]{0,15}$/),r7t=E.object({schemaVersion:E.literal(1),runId:So,execution:E.discriminatedUnion("provider",[E.object({...$5e,provider:E.literal("github"),repository:E.object(kq).strict(),providerRunId:ql}).strict(),E.object({...$5e,provider:E.literal("azure-devops"),repository:E.object(Bq).strict(),providerRunId:t7t}).strict()]),requester:E.literal(!0).optional(),writeCheck:E.literal(!0).optional(),claudeCodePin:E.literal(!0).optional(),deployedPins:E.literal(!0).optional(),statedPins:E.literal(!0).optional()}).strict(),q5e=E.object({repository:Gl,number:ql}).strict(),n7t=E.discriminatedUnion("status",[E.object({status:E.literal("none")}).strict(),E.object({status:E.literal("delivered"),pullRequests:E.array(q5e).min(1)}).strict(),E.object({status:E.literal("partial"),pullRequests:E.array(q5e).min(1),failures:E.array(E.object({repository:Gl,message:E.string()}).strict()).min(1)}).strict(),E.object({status:E.literal("failed"),message:E.string()}).strict()]),s7t=E.object({blockedPreflight:E.object({file:E.string().min(1),repository:E.string().min(1).optional(),reason:E.string().min(1).max(300),evidence:E.string().min(1).max(400)}).strict().optional(),sufficiency:E.nativeEnum(wh),rationale:E.string().min(1),gaps:E.array(E.string().min(1)),acceptedEvidence:E.array(E.object({kind:E.nativeEnum(bh),repository:E.string().min(1),revision:uf,reference:E.string().min(1),summary:E.string().min(1)}).strict()),actionRequired:E.array(E.nativeEnum(Ib))}).strict().superRefine((e,t)=>{e.sufficiency==="insufficient"!=e.gaps.length>0&&t.addIssue({code:E.ZodIssueCode.custom,path:["gaps"],message:"only insufficient evidence names gaps, and it names at least one"}),new Set(e.actionRequired).size!==e.actionRequired.length&&t.addIssue({code:E.ZodIssueCode.custom,path:["actionRequired"],message:"a reason appears twice"})}),wv=500,Die=2048,Oie=1e3,i7t=/[\\/:*?"<>|;#$*{},+=[\]%\p{Cc}\p{Cf}]/u,G5e=e=>e.length>0&&e.length<=64&&e===e.trim()&&!i7t.test(e)&&!/[^\S ]/u.test(e)&&!/^[._]/.test(e)&&!e.endsWith("."),o7t=e=>{if(/^[A-Za-z0-9._-]{1,100}\/[A-Za-z0-9._-]{1,100}$/.test(e))return!0;let[t,r,n,...s]=e.split("/");return e.length<=201&&s.length===0&&n!==void 0&&/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,48}[A-Za-z0-9])?$/.test(t)&&G5e(r)&&G5e(n)},a7t=E.object({testResults:E.array(E.object({resultId:E.string().regex(/^[^\u0000-\u001f]{1,512}$/),repository:E.string().refine(o7t,"Invalid"),testType:E.string(),endpoint:E.string(),status:E.enum(["Pass","Fail","Skipped"]),details:E.string(),fileName:E.string().optional(),testId:E.string().regex(/^[^\u0000-\u001f]{1,512}$/).optional(),failureCause:E.object({kind:E.nativeEnum(IR),family:E.nativeEnum(eQ).optional()}).strict().optional(),origin:E.nativeEnum(ZO).optional()}).strict()),validation:s7t,changes:E.array(E.object({id:E.string().min(1).max(512),text:E.string().max(16384),source:E.string().max(Die),testedBy:E.array(E.string().min(1).max(1024)).max(wv),writtenBy:E.array(E.string().min(1).max(1024)).max(wv),maintainedBy:E.array(E.string().min(1).max(1024)).max(wv)}).strict()).max(Oie).optional(),traceVersion:E.literal(1)}).passthrough().superRefine((e,t)=>{let r=new Set;e.testResults.forEach((n,s)=>{let i=n.failureCause;i&&n.status==="Pass"&&t.addIssue({code:E.ZodIssueCode.custom,path:["testResults",s,"failureCause"],message:"a passing result has no failure cause"}),i&&i.kind==="environment"!=(i.family!==void 0)&&t.addIssue({code:E.ZodIssueCode.custom,path:["testResults",s,"failureCause"],message:"an environment cause names its family, and no other cause does"});let o=["testResults",s,"resultId"],a=n.resultId.slice(`${n.repository}:${n.testType}:`.length);(!n.resultId.startsWith(`${n.repository}:${n.testType}:`)||a===""||a.startsWith("/")||a.startsWith("#"))&&t.addIssue({code:E.ZodIssueCode.custom,path:o,message:"is not repository:testType:path for this result"}),r.has(n.resultId)&&t.addIssue({code:E.ZodIssueCode.custom,path:o,message:"stable identity repeated"}),r.add(n.resultId)})}),j5e=e=>e.replace(/[%:#]/g,t=>encodeURIComponent(t));function Nq(e,t,r,n){let s=r.replace(/\\/g,"/"),i=s.split("/").filter(c=>c!==""&&c!==".");if(s.startsWith("/")||/^[A-Za-z]:/.test(s)||i.length===0||i.includes(".."))throw new Error(`testResultId needs a path relative to the repository root, got "${r}"`);let o=i.join("/"),a=`${e}:${t}:${j5e(o)}`;return n?`${a}#${j5e(n)}`:a}var Qie=50,H5e=E.string().regex(/^(?!.*\.\.)(?!\/)(?!.*\/$)[A-Za-z0-9._/-]{1,255}$/),Mie=E.discriminatedUnion("kind",[E.object({kind:E.literal("branch_pushed"),repository:Gl,branch:H5e,commit:uf}).strict(),E.object({kind:E.enum(["pull_request_opened","pull_request_edited"]),repository:Gl,number:ql,branch:H5e}).strict()]),e9e=E.object({schemaVersion:E.literal(1),run:E.object({runId:So,attemptNumber:E.number().int().positive(),manifestHash:Co}).strict(),target:Cq,policy:Cq,provenance:E.object({sources:E.array(E.object({repository:Gl,revision:uf}).strict()),firstQualification:E.literal(!0).optional()}).strict(),delivery:E.object({generatedTests:n7t}).strict(),producer:E.object({testbot:E.string().regex(/^[0-9A-Za-z.+-]{1,64}$/),mcp:E.string().regex(/^[0-9A-Za-z.+-]{1,64}$/)}).strict(),report:a7t,githubWrites:E.array(Mie).max(Qie).optional()}).strict(),c7t=e9e.pick({schemaVersion:!0,run:!0,target:!0,provenance:!0,producer:!0}).extend({recipe:Sq}).strict().superRefine(({recipe:e},t)=>{let r=(i,o)=>t.addIssue({code:E.ZodIssueCode.custom,path:["recipe",...i],message:o});e.status==="blocked"&&e.blockers.length===0&&r(["blockers"],"a blocked recipe names at least one blocker");let n=new Set,s=0;e.files.forEach((i,o)=>{$m(i.path)||r(["files",o,"path"],"is not .skyramp/workspace.yml or a file under .skyramp/sut/"),n.has(i.path)&&r(["files",o,"path"],"file repeated"),n.add(i.path),SQ.test(i.content)&&r(["files",o,"content"],"is not text");let a=Buffer.byteLength(i.content,"utf8");s+=a,a>MA&&r(["files",o,"content"],`larger than ${MA} bytes`)}),s>FA&&r(["files"],`recipe text over ${FA} bytes in total`)}),l7t=E.object({components:E.array(E.object({name:E.string().min(1),repository:E.string().regex(/^[A-Za-z0-9._-]{1,100}\/[A-Za-z0-9._-]{1,100}$/),observedRevision:E.string().regex(/^[0-9a-f]{7,64}$/).nullable(),source:E.nativeEnum(xR),evidence:E.string()}).strict().refine(e=>e.source!=="agent"||e.observedRevision===null,{path:["observedRevision"],message:"a component only an agent session can read names no revision"}))}).strict();function t9e(e,t){if(e.trigger.kind!=="revision_read"&&e.trigger.kind!=="schedule")throw new Error(`The deployed revisions upload is invalid: only a revision_read or scheduled run sends one, not a ${e.trigger.kind} run`);let r=e.sources.map(s=>`${s.repository.namespace}/${s.repository.name}`),n=l7t.safeParse({components:t.map((s,i)=>{let o=r.find(a=>a.toLowerCase()===s.repository.toLowerCase());if(!o)throw new Error(`The deployed revisions upload is invalid: components.${i}.repository: ${s.repository} is not a source of the run`);return{...s,repository:o,evidence:s.evidence.trim()}})});if(!n.success)throw new Error(`The deployed revisions upload is invalid: ${Yie(n.error)}`);return n.data}var r9e=E.object({schemaVersion:E.literal(1),stage:E.nativeEnum(kie),event:E.nativeEnum(Bie),status:E.nativeEnum(Nie).optional()}).strict().refine(e=>e.status===void 0||e.event==="finished",{path:["status"],message:"only a finished stage has a status"}),_d=100,jm=5e3,xB=2e3,RB=100,Pq=/^[A-Za-z0-9_-]{1,64}$/,Fie=20,Lie=200,Uie=100,$ie=100,u7t=200,z5e="[^/\\s](?:(?:[^/\\s]| )*[^/\\s])?",d7t=new RegExp(`^(?:[^/\\s]+/[^/\\s]+|[^/\\s]+/${z5e}/${z5e})$`),qie=500,Gie=50,PB=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/,Jc=e=>E.string().max(e).refine(t=>t.trim().length>0&&!PB.test(t),"blank, or not text"),lf={sequence:E.number().int().min(1).max(jm),at:E.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?Z$/)},jie=E.discriminatedUnion("kind",[E.object({...lf,kind:E.literal("log"),phase:E.nativeEnum(NB),text:Jc(xB)}).strict(),E.object({...lf,kind:E.literal("component"),name:Jc(RB),repository:Jc(u7t).refine(e=>d7t.test(e)||e===Tr,"not owner/name"),file:Jc(qie).nullable(),status:E.nativeEnum(Cv),version:Jc($ie).optional()}).strict(),E.object({...lf,kind:E.literal("reply"),to:E.string().uuid(),accepted:E.boolean(),text:Jc(xB)}).strict(),E.object({...lf,kind:E.literal("question"),id:E.string().regex(Pq),type:E.nativeEnum(Tq),text:Jc(xB),component:Jc(RB).nullable(),choices:E.array(Jc(Lie)).max(Fie),placeholder:Jc(Uie).optional()}).strict(),E.object({...lf,kind:E.literal("delivered"),ids:E.array(E.string().uuid()).max(_d)}).strict(),E.object({...lf,kind:E.literal("credentials"),names:E.array(E.string().regex(Bh)).min(1).max(Gie)}).strict()]).superRefine((e,t)=>{e.kind==="credentials"&&new Set(e.names).size!==e.names.length&&t.addIssue({code:E.ZodIssueCode.custom,path:["names"],message:"a name twice"}),e.kind==="question"&&(e.type==="free_text"!=(e.choices.length===0)&&t.addIssue({code:E.ZodIssueCode.custom,path:["choices"],message:"choices exactly when the question is not free_text"}),new Set(e.choices).size!==e.choices.length&&t.addIssue({code:E.ZodIssueCode.custom,path:["choices"],message:"a choice twice"}))}),n9e=E.object({schemaVersion:E.literal(1),events:E.array(jie).max(_d)}).strict(),Hie=E.discriminatedUnion("kind",[E.object({...lf,kind:E.literal("log"),stage:E.nativeEnum(Gm),text:Jc(xB)}).strict(),E.object({...lf,kind:E.literal("reply"),to:E.string().uuid(),accepted:E.boolean(),text:Jc(xB)}).strict(),E.object({...lf,kind:E.literal("delivered"),ids:E.array(E.string().uuid()).max(_d)}).strict()]),s9e=E.object({schemaVersion:E.literal(1),events:E.array(Hie).max(_d)}).strict(),V5e={id:E.string().uuid(),text:E.string(),by:E.string().nullable(),at:E.string(),replied:E.literal(!0).optional()},i9e=E.discriminatedUnion("kind",[E.object({...V5e,kind:E.literal("instruction"),question:E.null()}),E.object({...V5e,kind:E.literal("answer"),question:E.string().regex(Pq)})]),o9e=E.string().regex(/^[A-Za-z0-9+/]{43}=$/),p7t=E.object({id:E.string().uuid(),revision:E.string(),by:E.string().nullable(),at:E.string(),target:E.string(),own:E.object({source:E.enum(["policy","test_environment"]),text:E.string()}).nullable()}),a9e=E.object({schemaVersion:E.literal(1),leftOut:E.array(E.string()),messages:E.array(i9e).optional(),stop:E.object({key:o9e}).optional(),notes:p7t.optional()}),c9e=E.object({schemaVersion:E.literal(1),messages:E.array(i9e).optional()}),_B=7,_q=500*1024*1024,l9e=E.object({id:ql,name:E.string().regex(/^[A-Za-z0-9._-]{1,200}$/),providerRunId:ql,expiresAt:E.string().datetime()}).strict(),u9e=E.object({schemaVersion:E.literal(1),artifact:l9e,sessionId:So,contentHash:Co,bytes:E.number().int().min(1).max(_q)}).strict(),d9e=E.object({schemaVersion:E.literal(1),checkpoint:E.object({artifact:l9e,repository:E.object({namespace:E.string().min(1),name:E.string().min(1)}).strict(),sessionId:So,contentHash:Co,key:o9e}).strict().nullable()}).strict(),f7t=200,Ev=100,Dq=(n=>(n.Resume="resume",n.Retry="retry",n.Update="update",n))(Dq||{}),h7t=E.object({kind:E.nativeEnum(Dq),setup:E.object({runId:So,endedAt:E.string().nullable(),outcome:E.string().nullable()}).strict(),components:E.array(E.object({name:E.string().min(1),repository:E.string().min(1),status:E.nativeEnum(Cv)}).strict()).max(Ev),credentials:E.array(E.string().min(1)).max(Ev),answers:E.array(E.object({question:E.string(),answer:E.string().nullable()}).strict()).max(Ev),instructions:E.array(E.object({text:E.string(),reply:E.string().nullable()}).strict()).max(Ev),log:E.array(E.object({phase:E.nativeEnum(NB),text:E.string()}).strict()).max(f7t),recipe:E.object({files:E.array(E.object({path:E.string().min(1),content:E.string()}).strict()).max(Ev),blockers:E.array(E.object({component:E.string(),problem:E.string(),evidence:E.string(),fix:E.string()}).strict()).max(Ev)}).strict().optional()}).strict(),p9e=E.object({schemaVersion:E.literal(1),context:h7t.nullable()}).strict(),f9e=E.object({schemaVersion:E.literal(1),configuration:E.object({captureId:So,revision:ql.nullable(),hash:Co}).strict(),capture:E.object({schemaVersion:E.literal(1),settings:E.object({target:E.object({environment:E.unknown()}).passthrough(),timeoutMinutes:E.number().int().positive(),answerWaitMinutes:E.number().int().positive().optional(),testEnvironment:E.object({name:E.string().min(1),address:E.string().min(1).optional(),readyWhen:E.string().min(1).optional()}).passthrough().optional()}).passthrough(),provenance:E.object({}).passthrough(),hash:Co}).strict()}).strict(),m7t=Ub.extend({version:E.number().int().positive(),components:E.array(E.object({name:E.string().min(1),repository:E.string().min(1)}).strict()),contentHash:Co.optional(),files:E.array(E.object({path:E.string().refine(e=>$m(e)&&!yv.includes(e),"not a file of a customer_deployed plan"),content:E.string()}).strict()).optional()}).strict(),h9e=E.object({schemaVersion:E.literal(1),testEnvironment:m7t.nullable().optional(),runtimePlan:E.object({version:E.number().int().positive(),contentHash:Co,files:E.array(E.object({path:E.string().refine($m,"not a recipe file path"),content:E.string()}).strict()).min(1),recipe:E.record(E.unknown()).optional()}).strict().nullable()}).strict().refine(e=>!(e.runtimePlan&&e.testEnvironment),{message:"a run pins a recipe or a customer's Test Environment, never both",path:["testEnvironment"]}),m9e=E.object({schemaVersion:E.literal(1),state:E.nativeEnum(Y5e),ending:E.nativeEnum(xq).nullable(),cause:E.nativeEnum(Rq).nullable(),deadlineAt:E.string().datetime()}).strict();function zie(e,t){return e.state==="ended"?e.ending==="cancelled"?"cancelled":e.cause==="runner_lost"?"expired":"ended":t.getTime()>=Date.parse(e.deadlineAt)?"expired":null}function qm(e){if(typeof e=="number"&&!Number.isFinite(e))throw new TypeError("Canonical JSON requires JSON values");if(Array.isArray(e))return`[${e.map(qm).join(",")}]`;if(e!==null&&typeof e=="object"){let r=e;return`{${Object.keys(r).sort().map(n=>`${JSON.stringify(n)}:${qm(r[n])}`).join(",")}}`}let t=JSON.stringify(e);if(t===void 0)throw new TypeError("Canonical JSON requires JSON values");return t}function Vie(e){return(0,kB.createHash)("sha256").update(qm(e),"utf8").digest("hex")}function g9e(e){let t=[...e].sort((r,n)=>r.path<n.path?-1:r.path>n.path?1:0).map(r=>({path:r.path,content:r.content}));return(0,kB.createHash)("sha256").update(qm(t),"utf8").digest("hex")}function A9e(e){let t=(i,o)=>i<o?-1:i>o?1:0,r=[...e.files].sort((i,o)=>t(i.path,o.path)).map(i=>({path:i.path,content:i.content})),n={address:e.address,readyWhen:e.readyWhen,credentials:[...e.credentials].sort(t),revisionSources:e.revisionSources.map(i=>qm({method:i.method,detail:i.detail,components:[...i.components].sort(t)})).sort(t)},s=e.components.map(i=>qm({name:i.name,repository:i.repository})).sort(t);return(0,kB.createHash)("sha256").update(qm({type:"customer_deployed",environment:n,components:s,files:r}),"utf8").digest("hex")}function y9e(e){return(0,kB.createHash)("sha256").update(qm({schemaVersion:e.schemaVersion,settings:e.settings,provenance:e.provenance}),"utf8").digest("hex")}var TB=e=>({provider:e.provider,providerAccountId:e.providerAccountId,providerRepositoryId:e.providerRepositoryId});function Wie(e,t,{statedPins:r=!0}={}){return r7t.parse({schemaVersion:1,runId:e,execution:t.execution(),requester:!0,writeCheck:!0,claudeCodePin:!0,deployedPins:!0,...r?{statedPins:!0}:{}})}function E9e(e){let t=e7t.parse(e);if(Vie(t.manifest)!==t.manifestHash)throw new Error("The handshake manifest hash does not match its manifest");return t}function g7t(e){let t=r=>r.map(n=>({repository:TB(n.repository),number:n.number}));return e.status==="delivered"?{status:e.status,pullRequests:t(e.pullRequests)}:e.status==="partial"?{status:e.status,pullRequests:t(e.pullRequests),failures:e.failures.map(r=>({repository:TB(r.repository),message:r.message}))}:e}function Yie(e){return e.issues.map(t=>`${t.path.map((n,s)=>typeof n=="number"?`[${n}]`:s===0?n:`.${n}`).join("")}: ${t.message}`).join("; ")}function w9e(e){let{manifest:t}=e;if(WZt.includes(t.trigger.kind))throw new Error(`The report upload is invalid: a ${t.trigger.kind} run uploads its SUT recipe, never a report`);if(t.trigger.kind==="revision_read")throw new Error("The report upload is invalid: a revision_read run uploads what each component runs, never a report");if(e.firstQualification&&!t.baseline?.sources)throw new Error("The report upload is invalid: only a run whose manifest names baseline sources can be a first qualification");let r=e9e.safeParse({schemaVersion:1,run:{runId:t.runId,attemptNumber:e.attemptNumber,manifestHash:Vie(t)},target:{id:t.target.id,revision:t.target.revision},policy:t.policy&&{id:t.policy.id,revision:t.policy.revision},provenance:{sources:e.checkedOut.map(n=>({repository:TB(n.repository),revision:n.revision})),...e.firstQualification?{firstQualification:!0}:{}},delivery:{generatedTests:g7t(e.generatedTests)},producer:e.producer,report:e.report,...e.githubWrites?.length?{githubWrites:e.githubWrites.map(n=>({...n,repository:TB(n.repository)}))}:{}});if(!r.success)throw new Error(`The report upload is invalid: ${Yie(r.error)}`);return A7t(r.data,t,e.checkedOut),r.data}function b9e(e,t,r,n,s){let i=c7t.safeParse({schemaVersion:1,run:{runId:e.runId,attemptNumber:t,manifestHash:Vie(e)},target:{id:e.target.id,revision:e.target.revision},provenance:{sources:r.map(o=>({repository:TB(o.repository),revision:o.revision}))},producer:s,recipe:n});if(!i.success)throw new Error(`The SUT recipe upload is invalid: ${Yie(i.error)}`);return i.data}function A7t(e,t,r){let n=i=>r.find(o=>Pr(o.repository)===Pr(i.repository))?.revision??i.revision,s=new Map(t.sources.map(i=>[`${i.repository.namespace}/${i.repository.name}`.toLowerCase(),n(i)]));e.report.validation.acceptedEvidence.forEach((i,o)=>{let a=`report.validation.acceptedEvidence[${o}]`,c=s.get(i.repository.toLowerCase());if(!c)throw new Error(`${a}.repository: ${i.repository} is outside the run's snapshot`);if(i.revision!==c)throw new Error(`${a}.revision: evidence is not from the checked-out revision ${c}`)})}var y7t="7.1-preview.1",E7t=".azure-pipelines/skyramp-testbot-v3.yml";function fE(e){return e.GITHUB_ACTIONS!=="true"&&/^true$/i.test(e.TF_BUILD??"")}var w7t={INPUT_PIPELINE:"SKYRAMP_TESTBOT_PIPELINE",INPUT_SKYRAMPRUNID:"SKYRAMP_RUN_ID",INPUT_SKYRAMPAPPORIGIN:"SKYRAMP_APP_ORIGIN",INPUT_SKYRAMPMCPVERSION:"SKYRAMP_MCP_VERSION",INPUT_SKYRAMPMCPSOURCE:"SKYRAMP_MCP_SOURCE",INPUT_SKYRAMPMCPGITHUBREF:"SKYRAMP_MCP_GITHUB_REF",INPUT_SKYRAMPMCPGITHUBTOKEN:"SKYRAMP_MCP_GITHUB_TOKEN",INPUT_USEBEDROCK:"SKYRAMP_USE_BEDROCK",INPUT_AWSREGION:"SKYRAMP_AWS_REGION",INPUT_AWSROLEARN:"SKYRAMP_AWS_ROLE_ARN"};function C9e(e=process.env){if(fE(e))for(let[t,r]of Object.entries(w7t))!e[t]&&e[r]!==void 0&&(e[t]=e[r])}function v9e(e,t={}){let r=d=>{let p=e[d];if(!p)throw new Error(`${d} is not set; the V3 runner handshake needs it`);return p},n=pE(e.SYSTEM_COLLECTIONURI??""),s=()=>Eie(r("SYSTEM_COLLECTIONURI")),i=e.SYSTEM_TEAMPROJECT,o=e.BUILD_REPOSITORY_NAME,a=e.BUILD_REPOSITORY_ID?.toLowerCase(),c=e.SYSTEM_ACCESSTOKEN,l=t.mask??(d=>v5e(d)),u=d=>async()=>{if(!d)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_OIDCREQUESTURI to $(System.OidcRequestUri).");if(!c)throw new Error("The job cannot request an OIDC token: the Testbot step's env must set SYSTEM_ACCESSTOKEN to $(System.AccessToken).");let p=new URL(d);if(p.protocol!=="https:")throw new Error("SYSTEM_OIDCREQUESTURI is not an https URL");p.searchParams.set("api-version",y7t);let f=await(t.fetch??fetch)(p.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json",Accept:"application/json"},body:"{}",redirect:"error",signal:AbortSignal.timeout(3e4)});if(!f.ok)throw new Error(`Azure DevOps refused the OIDC token request: ${f.status}`);let m=(await f.json().catch(()=>({}))).oidcToken;if(typeof m!="string"||!m)throw new Error("Azure DevOps's OIDC token response carried no token");return l(m),m};return{runnerPlatform:fE(e)?"azure":void 0,workspace:e.BUILD_SOURCESDIRECTORY||void 0,serverUrl:n,apiUrl:n,repository:a&&i&&o&&n?{id:a,slug:`${s()}/${i}/${o}`}:void 0,runId:e.BUILD_BUILDID||void 0,runAttempt:e.SYSTEM_STAGEATTEMPT||void 0,job:e.SYSTEM_JOBNAME||void 0,execution(){let d=r("SYSTEM_STAGEATTEMPT");if(!/^[1-9][0-9]*$/.test(d))throw new Error(`SYSTEM_STAGEATTEMPT is "${d}", not a positive whole number`);let p=r("SYSTEM_COLLECTIONID").toLowerCase();if(!vv.test(p))throw new Error(`SYSTEM_COLLECTIONID is "${p}", not a GUID`);let f=r("BUILD_REPOSITORY_ID").toLowerCase();if(!vv.test(f))throw new Error(`BUILD_REPOSITORY_ID is "${f}", not a GUID`);let m=[s(),r("SYSTEM_TEAMPROJECT"),r("SYSTEM_DEFINITIONID"),r("BUILD_BUILDID")].map(encodeURIComponent).join("/");return{provider:"azure-devops",repository:{provider:"azure-devops",providerAccountId:p,providerRepositoryId:f},providerRunId:m,providerRunAttempt:Number(d),workflowRef:`${E7t}@${r("BUILD_SOURCEBRANCH")}`}},takeIdToken(){let d=e.SYSTEM_OIDCREQUESTURI;delete e.SYSTEM_OIDCREQUESTURI;let p=u(d);return()=>p()},takeSourceToken(){return delete e.SYSTEM_ACCESSTOKEN,c||void 0},webIdentity(){if(!e.SYSTEM_OIDCREQUESTURI?.trim()||!c)return;let d=u(e.SYSTEM_OIDCREQUESTURI);return{token:()=>d(),runId:e.BUILD_BUILDID}},v3RunsOnly:!0,assumesBedrockRole:!0,namesSourceToMcp:!0,checkSourceName(d){wq(d)},cloneUrl(d){return T5e(n,wq(d))},gitAuthEnv(d){return bq(n,d)},async pullRequest(d,p,f){let m=await CB({token:await f.token(),url:`${SB(n,wq(d))}/pullrequests/${p}`,fetch:f.fetch}),g=m.status==="completed";return{...typeof m.title=="string"?{title:m.title}:{},...typeof m.description=="string"?{body:m.description}:{},...typeof m.status=="string"?{merged:g}:{},...g&&typeof m.lastMergeCommit?.commitId=="string"?{mergeCommit:m.lastMergeCommit.commitId}:{},...g&&typeof m.lastMergeSourceCommit?.commitId=="string"?{mergedHead:m.lastMergeSourceCommit.commitId}:{}}},async commit(d,p,f){let m;try{m=SB(n,bB(d))}catch{return{lookup:"unknown"}}try{let g=await CB({token:await f.token(),url:`${m}/commits/${encodeURIComponent(p)}`,fetch:f.fetch});return typeof g.commitId=="string"?{sha:g.commitId}:{lookup:"missing"}}catch(g){return{lookup:g instanceof wB&&(g.status===404||g.status===400)?"missing":"unknown"}}}}}Gt();var b7t=5e3,Kie=/^(?!\.\.?$)[A-Za-z0-9._-]{1,100}$/;function S7t(e){let t=Buffer.from(`x-access-token:${e}`).toString("base64");return fn(t),`AUTHORIZATION: basic ${t}`}function I9e(e,t={}){let r=c=>{let l=e[c];if(!l)throw new Error(`${c} is not set; the V3 runner handshake needs it`);return l},n=e.GITHUB_REPOSITORY_ID,s=e.GITHUB_REPOSITORY,i=(e.GITHUB_SERVER_URL||"https://github.com").replace(/\/+$/,""),o=(e.GITHUB_API_URL||"https://api.github.com").replace(/\/+$/,""),a=async(c,l)=>l.fetch(c,{headers:{Authorization:`Bearer ${await l.token()}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(3e4)});return{runnerPlatform:e.GITHUB_ACTIONS==="true"?"github":void 0,workspace:e.GITHUB_WORKSPACE||void 0,serverUrl:i,apiUrl:o,repository:n&&s?{id:n,slug:s}:void 0,runId:e.GITHUB_RUN_ID||void 0,runAttempt:e.GITHUB_RUN_ATTEMPT||void 0,job:e.GITHUB_JOB||void 0,execution(){let c=r("GITHUB_RUN_ATTEMPT");if(!/^[1-9][0-9]*$/.test(c))throw new Error(`GITHUB_RUN_ATTEMPT is "${c}", not a positive whole number`);return{provider:"github",repository:{provider:"github",providerAccountId:r("GITHUB_REPOSITORY_OWNER_ID"),providerRepositoryId:r("GITHUB_REPOSITORY_ID")},providerRunId:r("GITHUB_RUN_ID"),providerRunAttempt:Number(c),workflowRef:r("GITHUB_WORKFLOW_REF")}},takeIdToken(){let c=e.ACTIONS_ID_TOKEN_REQUEST_URL,l=e.ACTIONS_ID_TOKEN_REQUEST_TOKEN;return delete e.ACTIONS_ID_TOKEN_REQUEST_URL,delete e.ACTIONS_ID_TOKEN_REQUEST_TOKEN,async u=>{if(!c||!l)throw new Error("The job cannot request an OIDC token. Give it the `id-token: write` permission.");let d=new URL(c);d.searchParams.set("audience",u);let p=await fetch(d,{headers:{Authorization:`Bearer ${l}`,Accept:"application/json"},redirect:"error",signal:AbortSignal.timeout(3e4)});if(!p.ok)throw new Error(`GitHub refused the OIDC token request: ${p.status}`);let f=(await p.json().catch(()=>({}))).value;if(typeof f!="string"||!f)throw new Error("GitHub's OIDC token response carried no token");return fn(f),f}},webIdentity(){return!e.ACTIONS_ID_TOKEN_REQUEST_TOKEN?.trim()||!e.ACTIONS_ID_TOKEN_REQUEST_URL?.trim()?void 0:{token:t.getIDToken??(l=>Rye(l)),runId:e.GITHUB_RUN_ID}},v3RunsOnly:!1,assumesBedrockRole:!1,namesSourceToMcp:!1,checkSourceName(c){for(let l of[c.namespace,c.name])if(!Kie.test(l))throw new Error(`"${l}" is not a repository name`)},cloneUrl(c){return`${i}/${c.namespace}/${c.name}.git`},gitAuthEnv(c){return c?{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:`http.${i}/.extraheader`,GIT_CONFIG_VALUE_0:S7t(c)}:{}},async pullRequest({namespace:c,name:l},u,d){if(![c,l].every(m=>Kie.test(m)))throw new Error("the repository name is not valid");let p=await a(`${o}/repos/${c}/${l}/pulls/${u}`,d);if(!p.ok)throw new Error(`GitHub answered ${p.status}`);let f=await p.json();return{...typeof f.title=="string"?{title:f.title}:{},...typeof f.body=="string"?{body:f.body}:{},...typeof f.merged=="boolean"?{merged:f.merged}:{},...f.merged===!0&&typeof f.merge_commit_sha=="string"?{mergeCommit:f.merge_commit_sha}:{},...f.merged===!0&&typeof f.head?.sha=="string"?{mergedHead:f.head.sha}:{}}},async commit(c,l,u){let[d,p,...f]=c.split("/");if(f.length||![d,p].every(m=>m!==void 0&&Kie.test(m)))return{lookup:"unknown"};try{let m=await a(`${o}/repos/${d}/${p}/commits/${encodeURIComponent(l)}`,u);if(m.status===404||m.status===422)return{lookup:"missing"};if(!m.ok)return{lookup:"unknown"};let g=await m.json();return typeof g.sha=="string"?{sha:g.sha}:{lookup:"missing"}}catch{return{lookup:"unknown"}}},async revokeToken(c,l){let u=await l(`${o}/installation/token`,{method:"DELETE",headers:{Authorization:`Bearer ${c}`,Accept:"application/vnd.github+json"},redirect:"error",signal:AbortSignal.timeout(b7t)});if(!u.ok&&u.status!==401)throw new Error(`GitHub answered ${u.status}`)}}}function cn(e=process.env){return fE(e)?v9e(e):I9e(e)}function x9e(e){if(e!=="staged")return`This Testbot engine runs only the staged pipeline, not "${e}". Set the pipeline input to "staged", or pin skyramp/testbot@v0.11 for the classic pipeline.`}var Tsn=["local","github","azure"];function R9e(e,t,r=cn()){if(r.runnerPlatform!=="azure")return new gB(e);let n=bie();if(!t||!n||!e.repoSlug||!e.tokenProvider)throw new Error("On Azure Pipelines, Testbot runs only the Validation Runs and SUT setups the Skyramp app starts: the step needs INPUT_SKYRAMPRUNID and the job's predefined variables.");return new vB({repositoryPath:e.repositoryPath,repoSlug:e.repoSlug,pipelineRun:n,tokenProvider:e.tokenProvider,log:e.log,reportUrl:t})}var B9e=require("child_process"),df=J(require("fs")),Za=J(require("path")),N9e=(e,t)=>(0,B9e.execFileSync)("git",["-c","safe.directory=*",...Ss,...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"],env:nt()}),P9e="^(http(\\..*)?\\.extraheader|core\\.sshcommand)$",I7t="core.sshcommand",Oq=e=>e instanceof Error?e.message.split(`
|
|
380
380
|
`)[0]:String(e);function x7t(e){let t=e.split("\0"),r=[];for(let n=0;n+2<t.length;n+=3)r.push({scope:t[n],origin:t[n+1],key:t[n+2]});return r}function T9e(e,t){let r;try{r=t(["config","--show-scope","--show-origin","--name-only","-z","--get-regexp",P9e],e)}catch(i){if(i.status===1)return[];throw new Error(`could not list persisted git credentials in ${e}: ${Oq(i)}`)}let n=[],s=new Set;for(let{scope:i,origin:o,key:a}of x7t(r)){if(i!=="local"&&i!=="worktree"||!o.startsWith("file:")||!a)continue;let c=o.slice(5),l=Za.isAbsolute(c)?c:Za.join(e,c);s.has(`${a}\0${l}`)||(s.add(`${a}\0${l}`),n.push({key:a,file:l}))}return n}function _9e(e,t=N9e,r){let n=R7t(e,t);return[...k9e(e,t,r),...n.flatMap(s=>k9e(s,t))]}function R7t(e,t){let r=!1;try{r=t(["rev-parse","--is-inside-work-tree"],e).trim()==="true"}catch{r=!1}if(!r){if(df.existsSync(Za.join(e,".git")))throw new Error(`could not read the git repository at ${e}`);return[]}let n;try{n=t(["submodule","foreach","--recursive","--quiet",'printf "%s\\0" "$displaypath"'],e)}catch(s){throw new Error(`could not list the submodules of ${e}: ${Oq(s)}`)}return n.split("\0").filter(s=>s.length>0).map(s=>Za.resolve(e,s))}function T7t(e,t=process.env.RUNNER_TEMP){if(!t)return;let r=/(?:^|\s)-i\s*(?:"([^"]+)"|'([^']+)'|(\S+))/.exec(e),n=r?.[1]??r?.[2]??r?.[3];if(!n)return;let s=Za.resolve(n.replace(/^\$\{?RUNNER_TEMP\}?/,t)),i=Za.resolve(t);return s.startsWith(i+Za.sep)?s:void 0}function k9e(e,t,r){let n=[],s=[],i=[];for(let{key:a,file:c}of T9e(e,t)){let l=a===I7t;if(l||r)try{for(let u of t(["config","--file",c,"--get-all",a],e).split(`
|
|
381
381
|
`).filter(Boolean)){l||r?.(u);let d=l?T7t(u):void 0;d&&s.push(d)}}catch{l&&i.push(`${a} (${c})`)}try{t(["config","--file",c,"--unset-all",a],e),n.push(`${a} (${c})`)}catch{}}for(let a of new Set(s))try{df.rmSync(a,{force:!0}),n.push(`ssh key (${a})`)}catch{}let o=[...T9e(e,t).map(a=>`${a.key} (${a.file})`),...[...new Set(s)].filter(a=>df.existsSync(a)).map(a=>`ssh key (${a})`),...i.map(a=>`${a}: could not read which key it names`)];if(o.length)throw new Error(`could not remove the persisted git credential from ${o.join(", ")}`);return n}function D9e(e=process.env.RUNNER_TEMP,t=N9e){if(!e||!df.existsSync(e))return[];let r=[],n=[];for(let s of df.readdirSync(e)){if(!/^git-credentials-.*\.config$/.test(s))continue;let i=Za.join(e,s),o=()=>{try{return t(["config","--file",i,"--name-only","-z","--get-regexp",P9e],e).split("\0").filter(Boolean)}catch(a){if(a.status===1)return[];throw new Error(`could not read the checkout credential file ${i}: ${Oq(a)}`)}};for(let a of new Set(o()))try{t(["config","--file",i,"--unset-all",a],e),r.push(`${a} (${i})`)}catch{}n.push(...o().map(a=>`${a} (${i})`))}if(n.length)throw new Error(`could not remove the persisted git credential from ${n.join(", ")}`);return r}function O9e(e){let t=[],r=n=>{let s;try{s=df.readdirSync(n,{withFileTypes:!0})}catch(i){throw new Error(`could not search ${n} for checkouts: ${Oq(i)}`)}s.some(i=>i.name===".git")&&t.push(n);for(let i of s)i.isDirectory()&&i.name!==".git"&&i.name!=="node_modules"&&r(Za.join(n,i.name))};return r(e),t}var il=J(require("fs")),Ji=J(require("path"));var Dd=J(require("fs")),Q9e=J(require("path")),Xie=J(require("crypto"));function Qq(){return new Date().toISOString()}function k7t(){return{runId:Xie.randomUUID(),createdAt:Qq(),updatedAt:Qq(),stages:{}}}function Mq(e,t={}){if(!t.fresh&&Dd.existsSync(e))try{let r=JSON.parse(Dd.readFileSync(e,"utf-8"));if(r&&typeof r=="object"&&r.stages&&typeof r.stages=="object"&&!Array.isArray(r.stages))return r;t.onWarn?.(`State file ${e} malformed \u2014 starting fresh`)}catch(r){t.onWarn?.(`State file ${e} unreadable (${r instanceof Error?r.message:String(r)}) \u2014 starting fresh`)}return k7t()}function Od(e,t){t.updatedAt=Qq(),Dd.mkdirSync(Q9e.dirname(e),{recursive:!0});let r=`${e}.${process.pid}.${Xie.randomUUID()}.tmp`;Dd.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
382
382
|
`),Dd.renameSync(r,e)}function ri(e,t,r){e.stages[t]={...r,updatedAt:Qq()}}var Qd=J(require("fs")),Iv=J(require("path"));var B7t=[/^\.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 N7t(e){return B7t.some(t=>t.test(e))}function P7t(e){let t=[],r=e.inputs.repositoryPath;return!r||!Qd.existsSync(r)?t.push(`repository path does not exist: ${r}`):VR(r)?zb(r,e.inputs.baseBranch)||t.push(e.inputs.baseBranch?`base branch "${e.inputs.baseBranch}" does not resolve`:"could not auto-detect a base branch (origin/HEAD, main, master)"):t.push(`not a git repository: ${r}`),{ok:t.length===0,reasons:t}}function _7t(e){return(e.inputs.relatedRepos??[]).map(t=>{let r=Qd.existsSync(t.path)?Oh(t.path):void 0;return r?{repository:t.slug,changedFiles:r.changedFiles}:{repository:t.slug,changedFiles:[],note:`could not read the change in ${t.path}`}})}function D7t(e){let{repositoryPath:t,baseBranch:r}=e.inputs;Qd.rmSync(Iv.join(t,Tn),{recursive:!0,force:!0});let n=Oh(t,r);if(!n)throw new Error(`could not compute git facts for ${t}`);let s=WR(t,r);if(!s)throw new Error(`could not compute the PR diff for ${t}`);let i=_7t(e),o=[n.changedFiles,...i.map(d=>d.changedFiles)].flat(),a=o.map(d=>d.path).filter(N7t),c=o.length>0&&a.length===o.length,l={schemaVersion:1,repository:{path:t,currentBranch:n.currentBranch,baseBranch:n.baseBranch},changedFiles:n.changedFiles,...i.length?{relatedChanges:i}:{},newFiles:s.newFiles,deletedFiles:s.deletedFiles,diffStat:s.diffStat,diffBytes:s.diffContent.length,nonApplicationFiles:a,nonApplicationOnly:c,sutRequired:!c};Qd.writeFileSync(Iv.join(e.runDir,OA),s.diffContent);let u=Iv.join(e.runDir,p4);return Qd.mkdirSync(Iv.dirname(u),{recursive:!0}),Qd.writeFileSync(u,JSON.stringify(l,null,2)+`
|
|
@@ -703,8 +703,8 @@ except Exception:
|
|
|
703
703
|
`),g),p.strengthened||o.push(`${c.file} still asserts only what its Skyramp draft did (the status and the response's shape): strengthen its assertions to the case \u2014 assert each field and value of ${l.join(", ")}'s expected outcome`))}return{problems:o,tests:a}}function xet(e){try{return JSON.parse(TG.readFileSync(vet.join(e,aN),"utf-8")).decision}catch{return}}function Iae(e,t){TG.writeFileSync(e,JSON.stringify(t,null,2)+`
|
|
704
704
|
`)}var Zsr=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 xae(e){let t=Ir.basename(e);return Zsr.has(t)||/^requirements[^/\\]*\.(txt|in)$/.test(t)}var eir={"go.mod":"go.sum",Gemfile:"Gemfile.lock"},Ret={"package.json":["@playwright/test","playwright","@skyramp/skyramp"],python:["skyramp","pytest"]},tir=["@skyramp/skyramp","skyramp"];function rir(e,t,r){if(bet(t))return!0;let n=xet(e.outputsDir);if(!n?.use||n.placement!=="beside-tests"||!n.dir)return!1;let s=Ir.resolve(t)===Ir.resolve(e.inputs.repositoryPath)?"":`${Ir.basename(Ir.resolve(t))}/`;if(s&&!n.dir.startsWith(s))return!1;let i=n.dir.slice(s.length),o=Ir.posix.dirname(r.split(Ir.sep).join("/"));return o==="."||i===o||i.startsWith(`${o}/`)}function nir(e){let t=Ir.basename(e);return t==="package.json"?Ret["package.json"]:t==="pyproject.toml"||t==="Pipfile"||t==="setup.py"||t==="setup.cfg"||/^requirements/.test(t)?Ret.python:[]}function sir(e,t,r){let n=IPe(e,t);if(n===void 0)return!1;if(Ir.basename(t)==="package.json")try{let s=JSON.parse(n);return["dependencies","devDependencies","optionalDependencies","peerDependencies"].some(i=>s[i]&&typeof s[i]=="object"&&Object.hasOwn(s[i],r))}catch{return!1}return new RegExp(`(^|[\\s"'\\[,])${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w-])`,"im").test(n)}function iir(e,t){let r=fe(e,Fa),n=Ir.resolve(t.path)===Ir.resolve(e.inputs.repositoryPath)?(r?.packages??[]).map(s=>s.dir):[];return[...new Set([...N0(t.path).map(s=>s.dir),...n])]}function cN(e){let t=new Map;return r=>t.get(r.path)??t.set(r.path,iir(e,r)).get(r.path)}function kG(e,t,r=new Set){let n=cN(e);return[...t.flatMap(s=>oir(e,s,n)),...air(e,t,r,n)]}function oir(e,t,r=cN(e)){let n=[],s=Cc(e.inputs,t.repository);if("error"in s)return n.push(`${t.package}: ${s.error}`),n;let{source:i}=s,o=It(e.inputs,i.slug),a=Ir.relative(i.path,Ir.resolve(i.path,t.manifest.trim()));if(a===".."||a.startsWith(`..${Ir.sep}`)||!jh(Ir.join(i.path,a))||Og(i.path,a)!==a)return n.push(`${t.package}: ${o}${t.manifest} is not a file in the checkout \u2014 add it to the manifest file of the checkout the test is in, and name that file`),n;if(pu(a))return n.push(`${t.package}: ${o}${t.manifest} is in a folder deliver never ships \u2014 add it to the manifest of the checkout the test is in, not one under .skyramp/ or .testbot/`),n;if(xl(a,r(i)))return n.push(`${t.package}: ${o}${t.manifest} is the Testbot test package's own manifest \u2014 install there freely and leave it out of the dependency list, which is only for the application's manifests`),n;if(!UQ(i.path,a))return n.push(`${t.package}: ${o}${t.manifest} is not changed \u2014 add it to the manifest of the checkout the test is in, and name that checkout as the entry's repository`),n;let c=AS(t.package.trim());nir(a).includes(c)&&!sir(i.path,a,c)&&!(e.inputs.skyrampHelpers!==!1&&tir.includes(c)&&rir(e,i.path,a))&&n.push(`${t.package}: ${o}${t.manifest} \u2014 ${c} is tooling Testbot brings for its own tests: it goes in the Testbot test package, never in the application's manifests. Revert this change to ${t.manifest} (and its lockfile) and put the tests that need ${c} in the Testbot test package, or write them with what the repository already declares`),t.reason?.trim()||n.push(`${t.package}: ${o}${t.manifest} \u2014 an application dependency change needs the reason a test must run inside the application's own test environment: give it with the reason, or revert the change`);let l=ry(i.path,a),u=new Set(xM(i.path,l));for(let d of l)u.has(d)?eOe(i.path,d,a,t.package)||n.push(`${t.package}: ${o}${d} changed but does not name ${c} \u2014 the updated lockfile must name the added package; run its package manager after the manifest names it`):n.push(`${t.package}: ${o}${d} is not updated \u2014 update that manifest's lockfile (every one it tracks) with the package manager the lockfile belongs to`);return n}function air(e,t,r=new Set,n=cN(e)){let s=[];for(let i of ut(e.inputs).filter(o=>o.writable)){let o=It(e.inputs,i.slug),a=n(i),c=new Set;for(let l of t){if(dr(e.inputs,l.repository)?.path!==i.path)continue;let u=Ir.relative(i.path,Ir.resolve(i.path,l.manifest.trim())).split(Ir.sep).join("/");c.add(u);for(let p of ry(i.path,u))c.add(p.split(Ir.sep).join("/"));let d=eir[Ir.basename(u)];d&&c.add(Ir.posix.join(Ir.posix.dirname(u),d))}for(let{path:l}of _u(i.path)){let u=l.replace(/\/+$/,"");!xae(u)||pu(u)||P0(u)||xl(u,a)||r.has(Ir.resolve(i.path,u))||c.has(u)||s.push(`${o}${u} changed, and no dependency entry declares it \u2014 never add, upgrade or remove a package in the application's own manifests or lockfiles for Testbot's tests: restore it (git checkout -- ${u}, or delete it if this run created it) and put tests that need tooling the repository does not declare in the Testbot test package. Only if a test must run inside the application's own test environment, declare the change with the reason`)}}return s}function ket(e){let t=fe(e,Fa),r=e.inputs.repositoryPath;return(t?.packages??[]).filter(n=>Tet.existsSync(Ir.join(r,n.dir))).flatMap(n=>dOe(r,n.dir))}function cir(e){return xn(r0,e).errors}function lir(e,t=[]){let{value:r,error:n}=br(e,t);if(n)return{errors:[n]};let s=cir(r);return s.length>0?{errors:s}:{finalize:r,errors:[]}}var uir="finalize-scratch";function Gv(e,t){let r=lir(e.stdout,t?.secretValues);if(!r.finalize||!t?.outputsDir)return r;let n=(s,i)=>s.trim()&&AQ(s.trim(),ea.join(t.outputsDir,uir,i),"finalize")||s;return{...r,finalize:{...r.finalize,lint:r.finalize.lint.map((s,i)=>({...s,command:n(s.command??"",`lint-${i+1}.sh`)}))}}}var Net=js("finalize-schema",(e,t)=>Gv(t,e)),Pet={name:"finalize-ready",verify(e,t){let{finalize:r,errors:n}=Gv(t,e);if(!r)return Be(this.name,n);let s=[],i=[r.blockers.length?`blockers listed: ${r.blockers.slice(0,4).join("; ")}`:void 0,...r.lint.map(o=>{let a=o.repository?` in ${o.repository}`:"";return o.clean?void 0:`lint.clean is false${a}`}),r.fileConventions.ok?void 0:`fileConventions.ok is false${r.fileConventions.notes?` (${r.fileConventions.notes})`:""}`].filter(o=>!!o);return r.ready&&i.length&&s.push(`ready:true contradicts the checks \u2014 ${i.join("; ")}`),!r.ready&&!r.blockers.length&&s.push("ready:false but blockers is empty \u2014 name what blocks the commit"),s.length===0?{name:this.name,passed:!0}:Be(this.name,s)}},_et={name:"finalize-dependencies",verify(e,t){let{finalize:r,errors:n}=Gv(t);if(!r)return Be(this.name,n);let s=new Set(e.prepared?.writtenBefore??[]),i=kG(e,r.dependencies.added,s);return i.length===0?{name:this.name,passed:!0}:Be(this.name,i)}};function Det(e,t){let r={};for(let n of t){let s=ea.resolve(e,n),i=vp(ea.dirname(s),ea.basename(s),Lh);i!==void 0&&i>0&&(r[s]=i)}return r}var dir=e=>e.prepared?.unitAssertionBaseline??{},Oet={name:"finalize-intent",verify(e){let t=fe(e,"adapt.json"),r=[];for(let[n,s]of Object.entries(dir(e))){let i=vp(ea.dirname(n),ea.basename(n),Lh)??0;i<s&&r.push(`${n} makes ${i} assertion(s); it made ${s} when generate-unit wrote it \u2014 a lint/format fix dropped ${s-i}`)}if(!t)return r.length===0?{name:this.name,passed:!0}:Be(this.name,r);for(let n of t.items){if(!n.file||n.action==="delete")continue;let s=n.assertionCount;if(s===void 0||s===0)continue;let i=Kn(e.inputs,n.repository),o=vp(i,Sr(i,n.file),Lh);if(o===void 0){r.push(`${n.file}: adapt counted ${s} assertion(s) but this counter has no heads for the file's language now \u2014 the file was renamed to an extension it cannot read`);continue}o<s&&r.push(`${n.file} makes ${o} assertion(s); it made ${s} when adapt placed it \u2014 a lint/format/convention fix dropped ${s-o}`)}return r.length===0?{name:this.name,passed:!0}:Be(this.name,r)}},Qet={name:"finalize-unit-tests-kept",verify(e){let r=(e.prepared?.unitTestFiles??[]).filter(n=>!BG.existsSync(ea.resolve(e.inputs.repositoryPath,n)));return r.length===0?{name:this.name,passed:!0}:Be(this.name,r.map(n=>`${n} is gone \u2014 lint and format the native unit tests in place; do not move, rename or delete them`))}},pir=/(^|\/)node_modules\//;function Rae(e){let t=e.prepared?.writtenBefore;if(!t)return[];let r=new Set(t),n=fe(e,"adapt.json"),s=fe(e,ts);for(let o of[...n?.items??[],...s?.tests??[]])o.file&&r.add(ea.resolve(Kn(e.inputs,o.repository),o.file));let i=[];for(let o of ut(e.inputs).filter(a=>a.writable))for(let a of L_e(o.path))r.has(ea.resolve(o.path,a))||a.startsWith(".skyramp/")||a.startsWith(".testbot/")||pir.test(a)||!fi.test(a)||i.push({source:o,rel:a});return i}function Met(e){let t=[];for(let{source:r,rel:n}of Rae(e))try{BG.rmSync(ea.join(r.path,n),{force:!0})}catch(s){t.push(`${It(e.inputs,r.slug)}${n} (${s instanceof Error?s.message:String(s)})`)}return t.length?`could not delete stray test file(s): ${t.join("; ")}`:void 0}function Fet(e,t){let r=t.at(-1),n=r?.gates.filter(s=>!s.passed).map(s=>s.name)??[];if(!(!r?.session||n.length!==1||n[0]!==Tae.name)&&!Rae(e).length)return kae(e,r.session)}var Tae={name:"finalize-no-stray-tests",verify(e){let t=[];for(let{source:r,rel:n}of Rae(e))t.push(`${It(e.inputs,r.slug)}${n} is a new test file this run did not place, and the run deletes it after this attempt \u2014 do not copy, move or delete a test: placement was decided before generation, so name a test you think is misplaced in fileConventions.notes; it is not a blocker`);return t.length===0?{name:this.name,passed:!0}:Be(this.name,t)}},Let={name:"finalize-lint",verify(e,t){let{finalize:r,errors:n}=Gv(t,e);if(!r)return Be(this.name,n);let s=[],i=new Set(r.lint.map(o=>dr(e.inputs,o.repository)?.path));for(let o of fir(e))i.has(o.path)||s.push(`${o.slug} has tests from this run and no lint entry \u2014 one entry per checkout this run wrote tests in, each run from that checkout`);for(let o of r.lint){let a=dr(e.inputs,o.repository);a?s.push(...hir(o,a.path,It(e.inputs,o.repository))):s.push(`${o.repository} is not a repository of this run \u2014 lint each checkout you wrote tests in, each run from that checkout`)}return s.length===0?{name:this.name,passed:!0}:Be(this.name,s)}};function fir(e){let t=fe(e,"adapt.json"),r=fe(e,ts),n=[...t?.items??[],...r?.tests??[],...r?.maintained??[]].map(s=>dr(e.inputs,s.repository));return[...new Map(n.filter(s=>!!s).map(s=>[s.path,s])).values()]}function hir(e,t,r){let n=e.command?.trim();if(!n)return e.clean?[]:[`${r}lint.clean is false and no lint command was recorded to re-run`];let{steps:s,reason:i}=Qo(n);if(!s)return[`${r}lint command '${n}' cannot be re-executed: ${i}`];try{for(let o of s)(0,Bet.execFileSync)(o[0],o.slice(1),{cwd:t,stdio:"ignore",timeout:12e4,env:nt()});return[]}catch(o){let a=o;return a.code==="ENOENT"||a.status===127?[]:[`${r}lint command '${n}' failed \u2014 the changed files are not clean`]}}var Uet={name:"finalize-lint-coverage",verify(e,t){let{finalize:r,errors:n}=Gv(t,e);if(!r)return Be(this.name,n);let s=new Set(["place","update","regenerate"]),i=fe(e,"adapt.json"),o=fe(e,ts),a=(u,d)=>`${dr(e.inputs,u)?.path}\0${d}`,c=new Set([...(i?.items??[]).filter(u=>s.has(u.action)).map(u=>a(u.repository,u.file)),...(o?.tests??[]).map(u=>a(u.repository,u.file)),...(o?.maintained??[]).filter(u=>u.change==="updated").map(u=>a(u.repository,u.file))]),l=r.lint.flatMap(u=>u.uncovered.filter(d=>!c.has(a(u.repository,d))).map(d=>`${It(e.inputs,u.repository)}${d}`));return l.length===0?{name:this.name,passed:!0}:Be(this.name,[`lint.uncovered names file(s) this run never placed or maintained: ${l.join(", ")} \u2014 only a changed/new file can be uncovered`])}};function kae(e,t){let{finalize:r,errors:n}=Gv(t,e);return Nt(e,"finalize",r,n)}var mir=new Set(["place","update","regenerate"]),$et=e=>t=>`${It(e.inputs,t.repository)}${t.file}`;function gir(e){let t=jv.join(e.outputsDir,"adapt.json");if(!NG.existsSync(t))return[];try{let r=JSON.parse(NG.readFileSync(t,"utf-8"));return[...new Set((r.items??[]).filter(n=>mir.has(n.action??"")).map($et(e)))]}catch{return[]}}function Air(e){let t=fe(e,ts);return[...new Set((t?.tests??[]).map(r=>jv.resolve(Kn(e.inputs,r.repository),r.file)))]}function yir(e){let t=fe(e,ts),r=(t?.maintained??[]).filter(n=>n.change==="updated");return[...new Set([...t?.tests??[],...r].map($et(e)))]}function Eir(e){let t=yir(e),r=Mo(jv.join(jv.resolve(e.inputs.repositoryPath),dK,"python")),n=[...new Set([...gir(e),...t])];return['You are the "finalize" stage of the Skyramp Testbot. Get the new and',"changed test files ready to commit; a later step pushes and opens the PR,","and the tests were already run. This run wrote or maintained:",n.length?n.map(s=>` - ${s}`).join(`
|
|
705
705
|
`):" (see git status)","",...t.length?[`The native unit tests (${t.join(", ")}) were written in the repository's own`,"framework and placement and already run. Lint and format them, but do not move,","rename or delete them. A unit test that fails is still delivered: it asserts the","requirement, and a failure means the code disagrees with it. Never change what it","asserts to make it pass.",""]:[],"Readiness checks:","","1) LINT/FORMAT: find the linter/formatter this repo uses (read its config"," and any lint scripts). Run it on the changed files and FIX every"," violation. Record the exact command you ran in a lint[] entry's command,"," scoped to the changed files/dirs \u2014 it gets re-run to confirm the tree is"," clean. Lint each checkout this run wrote tests in with THAT repository's"," linter, run from that checkout: one lint[] entry per checkout."," Check the linter's own config against each changed/new file's path: a"," glob or directory list that does not match it means `clean` never"," actually examined that file, whatever the command's exit code said. List"," every such file, by its path in that checkout, in that entry's uncovered \u2014"," this is independent of ciReadiness: a test runner can still execute a"," file its linter never looked at. uncovered is REQUIRED on every lint[]"," entry: write [] when every changed/new file IS covered by the linter's"," config \u2014 omitting the field is not the same as an empty list and will"," fail validation.","2) CONVENTIONS: compare the new files' names and directories to the repo's"," existing tests. Placement was decided before generation, and deliver"," commits each test where it was placed: do not copy, move or delete a test,"," into another checkout or within one, and do not rename it. A test you think"," is misplaced or misnamed is a caveat, not a blocker: say in"," fileConventions.notes where it belongs and why, and keep fileConventions.ok"," true. Set it false only for a convention you could not fix in place.","3) CI READINESS: confirm the repo's CI will actually run the new files \u2014"," whether through the test runner's own discovery or the test paths a CI"," workflow configures. If it will not, set ciReadiness.covered=false and"," name in ciReadiness.notes the exact change the author must make (file,"," step, setting). This is NOT a blocker: a test the author's CI does not"," run yet is still the work they asked for, and wiring their CI is their"," call, not a reason to withhold the tests.","4) DEPENDENCIES: the application's manifests and lockfiles are its owner's."," Tests in the repository's own framework use its existing dependency environment as it is:"," never add, upgrade or remove a package in the application's own manifests or lockfiles for them."," A test that imports a package the repo does not declare is rewritten to use what it declares."," Tooling Testbot brings for its own tests (Playwright, the Skyramp SDK, pytest where the repo has"," none) goes in the Testbot test package, never in the application's manifests. The one exception"," is a test that must run inside the application's existing test environment and cannot without"," the package: then add it to the manifest of the checkout the test is in, keep that manifest's"," existing constraints, upgrade nothing else, run the existing tests of that environment"," afterwards, and record it in dependencies.added with the reason;"," name that checkout as the entry's repository. A missing import that you can resolve neither way"," is a blocker."," When that checkout tracks a lockfile for the manifest (in the manifest's"," folder; else at the root of a workspace that lists it as a member),"," update that manifest's lockfile with the package manager it belongs to:"," every lockfile that folder tracks, each with its own manager. The updated"," lockfile must name the added package: one an earlier install rewrote does"," not count. <dir> is the lockfile's directory, in that"," checkout. Single-quote <dir> when you substitute it. Use the manager on PATH"," when there is one; else its fallback:"," - package-lock.json: `npm install --package-lock-only --prefix <dir>`"," - pnpm-lock.yaml: `pnpm install --lockfile-only --dir <dir>`;"," fallback `npx -y pnpm install --lockfile-only --dir <dir>`"," - yarn.lock, Yarn 1: `yarn --cwd <dir> install`"," - yarn.lock, Yarn 2+ (the checkout has .yarnrc.yml): with CI set, a plain"," install refuses to change the lockfile, so run"," `yarn --cwd <dir> install --mode=update-lockfile`; fallback, with <version>"," from package.json's packageManager:"," `npx -y @yarnpkg/cli-dist@<version> --cwd <dir> install --mode=update-lockfile`"," - bun.lock / bun.lockb: `bun install --lockfile-only --cwd <dir>`;"," fallback `npx -y bun install --lockfile-only --cwd <dir>`"," - poetry.lock: `poetry -C <dir> lock`; uv.lock: `uv lock --project <dir>`;"," pdm.lock: `pdm lock -p <dir>`; Pipfile.lock: `env PIPENV_PIPFILE=<dir>/Pipfile pipenv lock`."," - Python fallback (poetry, uv, pdm, pipenv): the system Python refuses a"," plain `pip install`, so install the tool into a directory deliver never",` ships, \`pip install --target ${r} <tool>\`, and run it from there:`,` \`env PYTHONPATH=${r} python3 -m poetry -C <dir> lock\`,`,` \`env PYTHONPATH=${r} python3 -m uv lock --project <dir>\`,`,` \`env PYTHONPATH=${r} python3 -m pdm lock -p <dir>\` (pdm.lock),`,` \`env PYTHONPATH=${r} PIPENV_PIPFILE=<dir>/Pipfile python3 -m pipenv lock\` (Pipfile.lock).`," CI that installs from the lockfile (`npm ci`) fails before any test runs"," when the manifest and the lockfile disagree. Do not create a lockfile the"," checkout does not already track.",'5) COMMIT + PR TEXT: write a commit message ("Skyramp Testbot: <concise>",'," <= 72 chars) and a PR title (<= 72 chars) + body summarizing the tests"," added and existing tests maintained, and what each guards against.","","ready is a statement of fact, not a goal: true only if the tests themselves","are fit to commit \u2014 they lint clean and every import they need is declared.","A blocker is something WRONG WITH THE TESTS, not something missing in the","author's repo: CI that does not run them yet is reported (step 3), and a test","you think is misplaced is reported (step 2); neither is a blocker. An honest","ready=false is a valid outcome \u2014 the tests then stay unpushed and the report","tells the author what blocks them. Never weaken or remove an assertion to","satisfy a linter or a convention; each cited assertion is re-checked.","",...ku(e.inputs),"","Output: end with one JSON object matching:","",Yr(r0)].join(`
|
|
706
|
-
`)}var qet=Jr({name:"finalize",model:"opus",timeoutMinutes:20,requires:[],branchRequires:{runtime:["adapt"],"no-runtime":["generate-unit"]},softRequires:["native-run"],prepare:e=>{let t=Air(e);return{unitTestFiles:t,unitAssertionBaseline:Det(e.inputs.repositoryPath,t),writtenBefore:[...Pa(_a(e.inputs))]}},buildPrompt:Eir,buildReadDirs:e=>Tu(e.inputs),allowedTools:["Read","Grep","Glob","Edit","Write","Bash(git status:*)","Bash(git diff:*)","Bash(ruff:*)","Bash(black:*)","Bash(flake8:*)","Bash(isort:*)","Bash(mypy:*)","Bash(npx:*)","Bash(npm:*)","Bash(pnpm:*)","Bash(yarn:*)","Bash(bun:*)","Bash(poetry:*)","Bash(uv:*)","Bash(pdm:*)","Bash(pipenv:*)","Bash(prettier:*)","Bash(eslint:*)","Bash(pip:*)","Bash(python:*)","Bash(python3:*)",...Gq],selfVerification:["You ran the repo's linter on the changed files and fixed every violation; each lint[] entry's command is a real re-runnable command, run from its checkout.","Each lint[] entry's uncovered names every changed/new file the linter's own config does not match, checked against the config itself, not assumed from a clean exit code.","You copied, moved, renamed or deleted no test; a test you think is misplaced is named in fileConventions.notes, not a blocker. ciReadiness.covered reflects whether CI will run them.","You changed no application manifest or lockfile except as a dependencies.added entry with its reason; every such entry is one a test cannot run without.","Every manifest you changed whose checkout tracks a lockfile for it has that lockfile updated by its package manager, in the same checkout.","commit.message and pr.title are <= 72 chars; pr.body summarizes what was added/maintained.","Your final message is one JSON object matching the schema."],exitGates:[Net,Pet,Let,Uet,_et,Oet,Qet,Tae],onPassed:kae,afterAttempt:Met,salvage:Fet});var Itt=J(require("crypto")),Yl=J(require("fs")),rl=J(require("path"));var wir=/^\s*(API Error\b|Failed to authenticate\b|Invalid API key\b)/,bir=/API Error(?: \([^)]*\))?: (\d{3})\b|request rejected \((\d{3})\)/i,Sir=/usage limits?|quota|credit balance|billing/i;function Get(e){if(e.timedOut||e.exitCode===0&&e.isError!==!0)return;let t=e.stdout??"";if(e.apiErrorStatus===void 0&&!wir.test(t))return;let r=bir.exec(t),n=e.apiErrorStatus??(r?Number(r[1]??r[2]):void 0);return{kind:n===401||n===403||n!==void 0&&n>=400&&n<500&&n!==429&&Sir.test(t)||/^\s*Invalid API key\b/.test(t)?"permanent":"temporary",...n!==void 0?{status:n}:{}}}function Hv(e=process.env){return e.CLAUDE_CODE_USE_BEDROCK==="1"?"AWS Bedrock":"Anthropic"}var rfn=Or.rows.notRun(!0),lN=e=>({deployed:qR(e)||JM(e),expected:Ho(e)?.sutRequired!==!1}),jet={deployed:!0,expected:!0},Pae="could not run here";function Het(e){let t=(e??"").trim();if(!(!t||![/the runner wrote no report/i,/reported no test:/i,/could not be set up/i,/test environment (?:did not load|lacks)/i,/\bits run cannot start\b/i,/\b(?:node_modules|dependencies|packages?|gems?|modules?) (?:is |are )?not installed\b/i,/\bnot installed\b/i,/\bno `?[\w.-]+`? on (?:its|the) PATH\b/i,/\bcommand not found\b/i,/\b(?:Cannot find module|ModuleNotFoundError|No module named|ImportError)\b/,/\bFailed to import\b/,/\bMissing X server\b|\bheadful browser\b/i,/\bEISDIR\b|\bENOENT\b/,/`(?:bundle|npm|pnpm|yarn|pip|uv|poetry|mvn|gradle)[^`]*` failed/i].some(n=>n.test(t))))return t.replace(/^(?:not run|could not run here)[:.]?\s*/i,"")}var zet=e=>({status:"Skipped",details:`${Pae}: ${e}`.slice(0,400),failureCause:{kind:"environment",family:"external_dependency"}}),Ef="kept, not ",kE="(declined the planned ";function Dae(e){return e.map(t=>t.expected===void 0?t.expectation:`${t.expectation} (${t.expected})`).join("; ")}function PG(e){if(!e)return[];let t=[],r=0,n=0;for(let s=0;s<e.length;s++){let i=e[s];i==="("?r++:i===")"?r=Math.max(0,r-1):r===0&&i===";"&&e[s+1]===" "&&e[s-1]===")"&&(t.push(e.slice(n,s)),n=s+2)}return t.push(e.slice(n)),t.map(s=>{let i=s.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(),l=i.slice(a+1,-1).trim();return c&&l?{expectation:c,expected:l}:{expectation:i}}return{expectation:i}})}var yf=new Set(["update","regenerate","delete"]),Bae=e=>e==null?"Skipped":e===0?"Pass":"Fail";function Wi(e,t){return t?.trim()||Rn(e.inputs).slug}var Cir={update:"updated",regenerate:"regenerated",delete:"deleted",verify:"verified",none:"touched"},vir=e=>Cir[e]??`${e}d`;function Iir(e,t,r,n=jet){let s=Or.rows.notRun(n.expected),i=l=>Wi(r,l).toLowerCase(),o=(e?.maintenance??[]).map(l=>{let u=t.find(A=>i(A.repository)===i(l.repository)&&(A.file===l.test||A.from&&A.from===l.test)),d=!!u&&yf.has(u.action),p=l.action!=="verify",f=u?.action??l.action,m=d?f:yf.has(f)||f==="none"?"verify":f,g=u?.reran?.exit!=null?Bae(u.reran.exit):void 0,w=(()=>{if(d){let A=u.action==="delete"?"removed":u.reran?.details??(u.reran?.exit==null?s:`exit ${u.reran.exit}`);if(!u.keptReason)return A;let y=`${kE}${l.action}: ${u.keptReason})`.slice(0,200);return`${A.slice(0,300-y.length-1)} ${y}`}return u?.keptReason?`${Ef}${vir(f)}: ${u.keptReason}`.slice(0,300):p?`recommended ${l.action}, not applied this run`:"not applied this run"})();return{repository:Wi(r,l.repository),testType:"existing",endpoint:"n/a",fileName:u?.file??l.test,description:l.evidence,action:m,beforeStatus:"Unknown",beforeDetails:l.evidence,afterStatus:d?u.action==="delete"?"Skipped":Bae(u.reran?.exit):g??"Unknown",afterDetails:w}}),a=l=>(e?.maintenance??[]).some(u=>i(l.repository)===i(u.repository)&&(l.file===u.test||l.from&&l.from===u.test)),c=t.filter(l=>yf.has(l.action)&&!a(l)).map(l=>({repository:Wi(r,l.repository),testType:"existing",endpoint:"n/a",fileName:l.file,description:"found stale while running the existing tests",action:l.action,beforeStatus:"Unknown",beforeDetails:"not in the plan's maintenance list",afterStatus:l.action==="delete"?"Skipped":Bae(l.reran?.exit),afterDetails:l.action==="delete"?"removed":l.reran?.details??(l.reran?.exit==null?s:`exit ${l.reran.exit}`)}));return[...o,...c]}function xir(e,t,r){let n=s=>Wi(r,s).toLowerCase();return(e??[]).map(s=>{let i=s.change==="deleted",o=$M(s.file),a=i?[]:t.filter(g=>n(g.repository)===n(s.repository)&&g.file===o),c=a.filter(g=>g.status==="Fail"),l=a.filter(g=>g.status==="Pass").length,u=i?"Skipped":c.length?"Fail":l?"Pass":a.length?"Skipped":"Unknown",d=a.length-c.length-l,p=[c.length&&`${c.length} failed`,l&&`${l} passed`,d&&`${d} skipped`].filter(Boolean).join(", "),f=o===s.file?"":` (run by ${o})`,m=i?"removed":a.length?`${p}${f}${c.length?`: ${c[0].details}`:""}`:"not re-run by this run's unit test run";return{repository:Wi(r,s.repository),testType:"existing",endpoint:"n/a",fileName:s.file,description:s.reason,action:i?"delete":"update",beforeStatus:"Unknown",beforeDetails:s.reason,afterStatus:u,afterDetails:m.slice(0,300)}})}function Rir(e,t){let r=i=>`${(i.repository??"").toLowerCase()}\0${i.fileName}`,n=new Set(e.filter(i=>yf.has(i.action)).map(r)),s=new Set(t.map(r));return[...e.filter(i=>n.has(r(i))||!s.has(r(i))),...t.filter(i=>!n.has(r(i)))]}function Tir(e,t,r,n,s,i,o=[]){let a=e?.behaviors??[];if(!a.length)return[];let c=new Set(n.filter(A=>A.testId&&A.status!=="Skipped").map(A=>A.testId)),l=new Set(s.map(A=>A.testId)),u=new Map,d=new Map;for(let A of t?.generate??[]){if(!A.from_behavior||!l.has(A.id))continue;let y=d.get(A.from_behavior)??[];if(y.includes(A.id)||y.push(A.id),d.set(A.from_behavior,y),!c.has(A.id))continue;let S=u.get(A.from_behavior)??[];S.includes(A.id)||S.push(A.id),u.set(A.from_behavior,S)}let p=A=>i?Wi(i,A).toLowerCase():"",f=A=>i?It(i.inputs,A):"",m=new Map;for(let A of t?.maintenance??[]){let y=r.find(C=>p(C.repository)===p(A.repository)&&(C.file===A.test||C.from&&C.from===A.test));if(!y||!yf.has(y.action))continue;let S=`${f(y.repository)}${y.file}`;for(let C of A.covers_behaviors??[]){let v=m.get(C)??[];v.includes(S)||v.push(S),m.set(C,v)}}let g=(A,y)=>o.filter(S=>y(S)&&S.behaviorIds.includes(A)).map(S=>S.testId),w=(A,y)=>[...new Set([...A,...y])].slice(0,wv);return a.slice(0,Oie).map(A=>({id:A.id,text:A.statement,source:A.evidence.slice(0,Die),testedBy:w(u.get(A.id)??[],g(A.id,y=>y.tested)),writtenBy:w(d.get(A.id)??[],g(A.id,y=>y.written)),maintainedBy:(m.get(A.id)??[]).slice(0,wv)}))}var Nae=(e,t)=>`${Sh(e)}::${t}`;function kir(e,t,r,n=[]){let s=i=>!(i.action==="delete"&&i.from);return{generated:e.length,modified:t.filter(i=>yf.has(i.action)&&s(i)).length+(n??[]).length,verified:t.filter(i=>s(i)&&(i.action==="verify"||!!i.keptReason)&&!yf.has(i.action)).length,executed:r.filter(i=>i.status!=="Skipped").length}}function Bir(e,t,r,n){let s=[],i=fe(e,"deploy.json"),o=w=>e.state.stages[w]?.status==="failed",a=e.state.modelProviderFailure,c=w=>o(w)&&a?.stage!==w&&!e.state.stages[w]?.reason?.startsWith("not run \u2014 the model provider refused");(c("deploy")||c("plan"))&&!i&&s.push({kind:"deploy-failed",text:Or.caveats.deployFailed,blocking:!0});let l=(t?.items??[]).filter(w=>w.action!=="delete"),u=l.filter(w=>w.reran?.exit===null||w.reran?.exit===void 0);l.length>0&&u.length===l.length&&s.push({kind:"tests-not-executed",text:Or.caveats.testsNotExecuted,blocking:!0}),i?.outcome&&i.outcome!=="clean"&&!JM(e)&&s.push(i.outcome==="change-broke-bringup"?{kind:"deploy-failed",subject:"change",text:Or.caveats.changeBrokeBringup,blocking:!0}:i.outcome==="bringup-failed"?{kind:"deploy-failed",text:Or.caveats.bringupFailed,blocking:!0}:{kind:"recipe-drift",text:Or.caveats.recipeDrift,blocking:!1});for(let[w,A]of Object.entries(i?.dependencies??{}))A===!1&&s.push({kind:"mocked-dependency",subject:w,text:Or.caveats.mockedDependency(w),blocking:!1});if(r?.ready===!1||o("finalize")||o("write")){let w=(r?.blockers??[]).slice(0,3).join("; ");s.push({kind:"finalize-not-ready",text:Or.caveats.finalizeNotReady(w),blocking:!0})}Ho(e)?.sutRequired===!1&&s.push({kind:"sut-not-required",text:Or.caveats.sutNotRequired,blocking:!1});let d=Tv(e);d.length&&s.push({kind:"analysis-unverified",text:Or.caveats.analysisUnverified(d.length),blocking:!1});let p=jM(xp(e)??{results:[],notRun:[]});p&&s.push({kind:"unit-tests-not-run",text:Or.caveats.unitTestsNotRun(p),blocking:!1});let f=(n??[]).filter(w=>w.status==="Skipped"&&w.details?.startsWith(`${Pae}:`));f.length&&s.push({kind:"tests-could-not-run-here",text:Or.caveats.testsCouldNotRunHere(f.length,f[0].details.slice(Pae.length+2)),blocking:!1});let m=MK(e).map(w=>w.behaviorId?`${w.behaviorId}: ${w.missing}`:w.missing);if(m.length&&s.push({kind:"downstream-not-checked",text:Or.caveats.downstreamNotChecked(m.join("; ")),blocking:!1}),a){let w=LK(e,s),A=(n??[]).some(S=>S.status==="Pass"||S.status==="Fail"),y=w?w.sufficiency==="sufficient"&&(w.acceptedEvidence.length>0||A):A;s.push(a.kind==="permanent"?{kind:"model-provider-denied",text:Or.caveats.modelProviderDenied(Hv(),y),blocking:!y}:{kind:"model-provider-unavailable",text:Or.caveats.modelProviderUnavailable(Hv(),y),blocking:!y})}r?.ciReadiness?.covered===!1&&s.push({kind:"ci-not-covered",text:Or.caveats.ciNotCovered,blocking:!1});let g=(r?.lint??[]).flatMap(w=>(w.uncovered??[]).map(A=>`${It(e.inputs,w.repository)}${A}`));return g.length>0&&s.push({kind:"lint-not-covered",subject:g.join(", "),text:Or.caveats.lintNotCovered(g.join(", ")),blocking:!1}),s}function Nir(e,t,r,n,s,i=jet,o=()=>{}){let a=[];for(let c of e.filter(l=>l.action!=="delete")){let l=c.reran?.exit,u=Vet(c.action),d=c.from?n.get(c.from):void 0,p=[...new Set([...c.covers??[],...d??[]])],f=p.length?p:[void 0];if(c.placementBroken){for(let $ of f){let P=$?t.get($):void 0;a.push({testId:$,testType:_ae(P?.type,o(c)),endpoint:P?.target??"n/a",fileName:c.file,repository:s?.(c),origin:u,status:"Skipped",details:`could not be placed or run: ${c.reran?.details??"harness problem"}`.slice(0,300),failureCause:{kind:"test_defect"}})}continue}let m={fail:0,skip:1,pass:2},g=new Map;for(let $ of c.reran?.tests??[]){let P=g.get($.case);(!P||m[$.status]<m[P.status])&&g.set($.case,$)}let w=g.size>0,A=$=>$===void 0?void 0:$.status==="skip"?"Skipped":$.status==="pass"?"Pass":"Fail",y=l==null?"Skipped":l===0?"Pass":"Fail",S=l!=null&&!w&&f.length>1,C=u==="existing"&&w&&!f.some($=>$&&g.has($)),v=[...g.values()],R=v.some($=>$.status==="fail")?"Fail":v.some($=>$.status==="pass")?"Pass":"Skipped",T=$=>{if(C)return R;let P=A($?g.get($):void 0);return P||(w||S?"Skipped":y)},G=[...g.entries()].filter(([,$])=>$.status==="fail").map(([$])=>$),B=v.filter($=>$.status==="pass").length,H=[G.length&&`${G.length} failed (${G.slice(0,5).join(", ")})`,B&&`${B} passed`].filter(Boolean).join(", "),z=f.filter($=>T($)==="Fail").length,ne=z===1&&c.finding?"failed \u2014 caught a real bug in the change":z===1&&c.repro?"fails as intended \u2014 reproduces the reported bug":"failed",Z=z===1&&!!(c.finding||c.repro);for(let $ of f){let P=$?t.get($):void 0,N={testId:$,testType:_ae(P?.type,o(c)),endpoint:P?.target??"n/a",fileName:c.file,repository:s?.(c),origin:u},W=$?g.get($):void 0,k=T($);if(C&&k!=="Skipped")a.push({...N,status:k,details:`${k==="Fail"?"failed":"passed"}: ${H}`.slice(0,400)});else if(k==="Skipped"){let F=W===void 0&&!C&&(w||S),j=F?"no result recorded for this case":c.reran?.details?.slice(0,300)||Or.rows.notRun(i.expected),V=F?void 0:Het(c.reran?.details),O=!V&&W===void 0&&!F&&l===null;V?a.push({...N,...zet(V)}):a.push({...N,status:"Skipped",details:j,...O?{failureCause:{kind:"environment",family:"app_not_started"}}:{}})}else if(k==="Pass")a.push({...N,status:"Pass",details:W?Or.rows.passed(i.deployed):c.reran?.details?.slice(0,300)||Or.rows.passed(i.deployed)});else{let F=W?z===1&&c.reran?.details?c.reran.details.slice(0,200):c.from?r.get(`${c.from}::${$}`):void 0:c.reran?.details?c.reran.details.slice(0,200):void 0;a.push({...N,status:"Fail",details:`${ne}${F?`: ${F}`:""}`.slice(0,400),...Z?{failureCause:{kind:"application"}}:{}})}}}return a}function _ae(e,t){return t==="ui"||t==="unit"?t:e??t??"integration"}function Vet(e){return e==="place"?"new":e==="update"||e==="regenerate"?"updated":"existing"}function Pir(e,t){let r=(t?.results??[]).filter(BK),n=(t?.notRun??[]).filter(i=>i.origin==="written");if(!r.length&&!n.length)return e;let s=(i,o,a)=>o===i.fileName&&(!a||!i.repository||a===i.repository);return e.map(i=>{let o=r.filter(f=>s(i,f.file,f.repository)),a=o.filter(f=>!!i.testId&&f.behaviorIds.includes(i.testId)),c=a.filter(f=>f.status==="Pass"||f.status==="Fail"),{failureCause:l,...u}=i;if(c.length){let f=c.find(m=>m.status==="Fail");return f?{...u,status:"Fail",details:`failed when Testbot re-ran it${i.status==="Fail"?"":" (write's own run reported it passing)"}: ${f.details}`.slice(0,400),...i.status==="Fail"&&l&&!f.fromFile?{failureCause:l}:{}}:{...u,status:"Pass",details:`passed when Testbot re-ran it${i.status==="Fail"?" (write's own run reported a failure)":""}`}}let d=n.find(f=>s(i,f.file,f.repository))?.reason??(a.length?"every re-run of it was skipped":o.length?"its re-run reported no result for this case":void 0);if(!d)return i;let p=i.status==="Skipped"?Het(d):void 0;return p?{...u,...zet(p)}:{...i,details:`${i.details} \u2014 write's own run; Testbot could not re-run it: ${d}`.slice(0,400)}})}function Jm(e){let t=fe(e,"analyze.json"),r=fe(e,"recommend.json"),n=fe(e,"generate.json"),s=fe(e,"generate-ui.json"),i=fe(e,"adapt.json"),o=fe(e,"finalize.json"),a=new Map((r?.generate??[]).map(O=>[O.id,O])),c=[...n?.tests??[],...s?.tests??[]],l=(i?.items??[]).filter(O=>O.file),u=(O,K)=>{let te=dr(e.inputs,K)?.path??e.inputs.repositoryPath;return te?rQe(te,O):void 0},d=[],p=new Set,f=(O,K,te)=>{let X=`${te}:${O}`;if(p.has(X))return;p.add(X);let le=K?.length?K:[Sh(O)];for(let he of le){let me=a.get(he);d.push({testId:he,testType:_ae(me?.type,u(O,te)),endpoint:me?.target??"n/a",fileName:O,description:me?.rationale??`Generated test ${O}`,reasoning:me?.expected_observable??"covers a recommended case",repository:te})}};for(let O of c){let K=l.find(te=>te.from===O.file);!K||K.action!=="place"||f(K.file,O.covers,Wi(e,K.repository))}for(let O of l.filter(K=>K.from&&K.action==="place"))f(O.file,O.covers,Wi(e,O.repository));let m=new Map;for(let O of c)for(let K of O.assertions??[])m.set(`${O.file}::${K.case}`,K.evidence);let g=new Map(c.map(O=>[O.file,O.covers??[]])),w=lN(e),A=Pir(Nir(l,a,m,g,O=>Wi(e,O.repository),w,O=>u(O.file,O.repository)),xp(e)),y=new Map((t?.behaviors??[]).map(O=>[O.id,O.surface])),S=O=>O.map(K=>y.get(K)).find(Boolean)??"n/a",C=fe(e,ts),v=C?.tests??[];for(let O of v)for(let K of O.names)d.push({testId:Nae(O.file,K),testType:"unit",endpoint:S(O.covers),fileName:O.file,description:Dae(O.assertions).slice(0,400),reasoning:`native ${O.framework} unit test for ${O.covers.join(", ")}`,repository:Wi(e,O.repository)});let R=new Map;for(let O of v)for(let K of O.covers){let te=`${O.file}\0${K}`,X=R.get(te)??new Set;for(let le of O.assertions)X.add(le.source.replace(/_/g," "));R.set(te,X)}let T=O=>{let K=[...new Set(O.behaviorIds.flatMap(te=>[...R.get(`${O.file}\0${te}`)??[]]))];return O.status!=="Fail"||O.origin!=="generated"||!K?.length?O.details:`fails \u2014 the code disagrees with what this new test asserts (from the ${K.join(", ")}): ${O.details}`.slice(0,300)},G=xp(e)?.results??[],B=C?.maintained??[],H=Rir(Iir(r,l,e,w),xir(B,G,e)),z=O=>Nae(O.file,O.selectedName??O.name),ne=(O,K)=>`${Wi(e,O).toLowerCase()}\0${K}`,Z=new Set(G.filter(O=>O.origin!=="written"&&O.name!==Mn).map(O=>ne(O.repository,O.file))),$=[];for(let O=A.length-1;O>=0;O--)A[O].origin==="existing"&&Z.has(ne(A[O].repository,A[O].fileName))&&$.unshift(...A.splice(O,1).filter(K=>K.testId));let P=new Set([...B.filter(O=>O.change==="updated").map(O=>`${Wi(e,O.repository).toLowerCase()}\0${$M(O.file)}`),...l.filter(O=>Vet(O.action)==="updated").map(O=>`${Wi(e,O.repository).toLowerCase()}\0${O.file}`)]),N=O=>O.origin==="generated"?"new":O.written||P.has(`${Wi(e,O.repository).toLowerCase()}\0${O.file}`)?"updated":"existing";for(let O of G.filter(K=>K.origin!=="written"))A.push({...O.name!==Mn?{testId:z(O)}:{},testType:"unit",endpoint:S(O.behaviorIds),status:O.status,details:T(O),fileName:O.file,repository:O.repository,resultId:Nq(O.repository,"unit",O.file,O.name),origin:N(O),...O.status==="Fail"&&O.origin==="generated"&&O.name!==Mn&&!O.fromFile?{failureCause:{kind:"application"}}:{}});let W=[...v.flatMap(O=>O.names.map(K=>({testId:Nae(O.file,K),behaviorIds:O.covers,written:!0,tested:!1}))),...G.filter(O=>O.origin!=="written"&&O.name!==Mn&&!O.fromFile&&O.status!=="Skipped").map(O=>({testId:z(O),behaviorIds:O.behaviorIds,written:!1,tested:!0}))],k=Bir(e,i,o,A),j=(fe(e,Fa)?.packages??[]).filter(O=>l.some(K=>!K.repository&&K.action!=="delete"&&xl(K.file,[O.dir]))).map(O=>({directory:O.dir,runner:O.runner,entrypoint:O.entrypoint,created:O.created,...e.inputs.repositorySlug?{repository:e.inputs.repositorySlug}:{}})),V=(o?.dependencies?.added??[]).map(O=>({package:O.package,manifest:O.manifest,...O.reason?{reason:O.reason}:{},...O.repository?{repository:O.repository}:{}}));return{testPackages:j,dependencyChanges:V,caseEvidence:$,newTestsCreated:d,testMaintenance:H,testResults:A,caveats:k,changes:Tir(t,r,l,[...A,...$],d,e,W),executionCoverage:kir(d,l,A,B),commitMessage:o?.commit?.message?.trim()||"Skyramp Testbot: add generated tests",validation:LK(e,k),system:Ho(e)?.sutRequired||fe(e,`${vs}.json`)||kS(e)?P4(e):void 0,testExecutionContexts:Ho(e)?.sutRequired===!1?void 0:hPe(e,l,c)}}var Wet=E.string().trim().min(1),uN=E.object({schemaVersion:E.literal(1).optional(),businessCaseAnalysis:Wet.describe("1-2 sentences: what this change means for a user, and whether the evidence shows it working"),issuesFound:E.array(E.object({description:Wet,severity:E.string().optional().describe("critical | high | medium | low"),category:E.string().optional().describe("bug | lint | type | config"),sourceFile:E.string().optional(),sourceLine:E.number().optional(),findingId:E.string().optional(),requirementIds:E.array(E.string()).optional()})).describe("every real problem this run exposed \u2014 cause, file:line, severity"),nextSteps:E.array(E.string()).describe("concrete follow-ups the author can act on; required non-empty when a disclosure is BLOCKING")});function _ir(e){return xn(uN,e).errors}function dN(e,t=[]){let{value:r,error:n}=br(e.stdout,t);if(n)return{errors:[n]};let s=_ir(r);return s.length>0?{errors:s}:{prose:r,errors:[]}}function BE(e,t){return{schemaVersion:1,businessCaseAnalysis:t.businessCaseAnalysis,newTestsCreated:e.newTestsCreated,testMaintenance:e.testMaintenance.length?e.testMaintenance:void 0,testResults:e.testResults,issuesFound:t.issuesFound,nextSteps:t.nextSteps,caveats:e.caveats.length?e.caveats:void 0,changes:e.changes.length?e.changes:void 0,executionCoverage:Object.values(e.executionCoverage).some(r=>r>0)?e.executionCoverage:void 0,commitMessage:e.commitMessage,...e.validation?{validation:e.validation}:{},...e.system?{system:e.system}:{},...e.testExecutionContexts?{testExecutionContexts:e.testExecutionContexts}:{},...e.testPackages.length?{testPackages:e.testPackages}:{},...e.dependencyChanges.length?{dependencyChanges:e.dependencyChanges}:{}}}var Yet=js("report-schema",(e,t)=>dN(t,e.secretValues)),Dir=/\b(preflight|analyze|deploy|recommend|generate(?:-ui)?|adapt|finalize|report)\.json\b|\bexit gate\b|\b(?:stage|gate)s? (?:failed|passed)\b|\bgenerate-ui\b/i,Oir=/\bmcp__[a-z0-9_]+\b|\bskyramp_[a-z][a-z0-9_]*\b/,Jet={name:"report-visibility",verify(e,t){let{prose:r,errors:n}=dN(t,e.secretValues);if(!r)return Be(this.name,n);let s=_G(e,BE(Jm(e),r));return s.length===0?{name:this.name,passed:!0}:Be(this.name,s)}};function _G(e,t){let r=[],n=fe(e,"deploy.json");e.state.stages.deploy?.status==="passed"&&!n&&r.push("deploy passed but deploy.json is unreadable \u2014 cannot verify its outcome / mocked deps were surfaced");let s=fe(e,"adapt.json");for(let l of(s?.items??[]).filter(u=>u.finding&&u.file)){let u=Sh(l.file);t.issuesFound.some(p=>`${p.description} ${p.sourceFile??""}`.toLowerCase().includes(u))||r.push(`adapt marked "${l.file}" finding:true (a real bug caught) but no issuesFound entry names that test \u2014 surface the bug`)}let i=fe(e,"recommend.json");if(e.state.stages.recommend?.status==="passed"&&i?.generate){let l=new Set(t.newTestsCreated.map(d=>d.testId.toLowerCase())),u=(t.nextSteps.join(" ")+" "+t.issuesFound.map(d=>d.description).join(" ")).toLowerCase();for(let d of i.generate){let p=d.id?.trim();p&&!l.has(p.toLowerCase())&&!u.includes(p.toLowerCase())&&r.push(`recommended case "${p}" is neither a test in newTestsCreated nor named in nextSteps/issuesFound \u2014 say what happened to it`)}}let o=(t.caveats??[]).filter(l=>l.blocking);o.length>0&&t.nextSteps.length===0&&r.push(`this run is not evidence the change works (${o.map(l=>l.kind).join(", ")}) and nextSteps is empty \u2014 say what the author should do about it`);let a=`${t.businessCaseAnalysis} ${t.issuesFound.map(l=>l.description).join(" ")} ${t.nextSteps.join(" ")}`,c=a.match(Dir)??a.match(Oir);return c&&r.push(`user-facing text leaks internal machinery ("${c[0]}") \u2014 describe the code/repo, not the testbot's stages, gates, tools or artifact files`),r}function Ket(e,t){let{prose:r,errors:n}=dN(t,e.secretValues);return Nt(e,"report",r?BE(Jm(e),r):void 0,n)}var Gae=J(require("fs")),NE=J(require("path"));var Xet=J(require("fs"));var OG=2*1024*1024;function Mae(e){let t=[];for(let r of e??[])if(r.state==="read")try{t.push({item:r,text:Xet.readFileSync(IXe(r),"utf-8")})}catch{}return t}var DG=6,Qir=/[\p{L}\p{N}]+/gu,Mir=new RegExp("(?<=\\p{Ll})(?=\\p{Lu})|(?<=\\p{Lu})(?=\\p{Lu}\\p{Ll})","u");function Zet(e){let t=[];for(let r of e.matchAll(Qir)){let n=r.index;for(let s of r[0].split(Mir))t.push({word:s.toLowerCase(),start:n,end:n+s.length}),n+=s.length}return t}var ett=(e,t)=>e.slice(t,t+DG).map(r=>r.word).join(" ");function Km(e){return Mae(e).map(({item:t,text:r})=>{let n=Zet(t.source==="other"?r:r.slice(r.indexOf(`
|
|
707
|
-
`)+1||r.length)),s=new Set;for(let i=0;i+DG<=n.length;i++)s.add(ett(n,i));return{name:Cb(t.key,Gi([t])),runs:s}})}function Fae(e,t){if(t.length===0)return[];let r=Zet(e),n=[];for(let s=0;s+DG<=r.length;s++){let i=ett(r,s),o=t.find(u=>u.runs.has(i));if(!o)continue;let a=r[s].start,c=r[s+DG-1].end,l=n.at(-1);l&&a<=l.end?l.end=Math.max(l.end,c):n.push({start:a,end:c,name:o.name})}return n}function Fir(e,t){return[...new Set(Fae(e,t).map(r=>r.name))]}function zv(e,t){let r=e;for(let n of Fae(e,t).reverse())r=`${r.slice(0,n.start)}(see ${n.name})${r.slice(n.end)}`;return r}var ttt=new Set(["testId","testedBy","writtenBy","coveredBy","id"]),Lir=new Set(["resultId","test","fileName","sourceFile","repository","maintainedBy"]);function Oae(e,t){return t!==void 0&&ttt.has(t)?(Array.isArray(e)?e:[e]).filter(r=>typeof r=="string"):Array.isArray(e)?e.flatMap(r=>Oae(r)):e&&typeof e=="object"?Object.entries(e).flatMap(([r,n])=>Oae(n,r)):[]}function Uir(e,t){let r=new Set(Oae(e)),n=new Set(r),s=new Map;for(let i of r){let o=Fae(i,t);if(o.length===0)continue;let a=i;for(let l of[...o].reverse())a=`${a.slice(0,l.start)}${$ir(l.name)}${a.slice(l.end)}`;let c=a;for(let l=2;n.has(c);l++)c=`${a}-${l}`;n.add(c),s.set(i,c)}return s}var $ir=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");function Qae(e,t,r,n,s=!1){return n!==void 0&&Lir.has(n)?e:n!==void 0&&ttt.has(n)?Array.isArray(e)?e.map(i=>r.get(i)??i):typeof e=="string"?r.get(e)??e:e:typeof e=="string"?s?e:zv(e,t):Array.isArray(e)?e.map(i=>Qae(i,t,r,void 0,s)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([i,o])=>[i,Qae(o,t,r,i,s||i==="requirementReferences")])):e}function QG(e,t){return t.length===0?e:Qae(e,t,Uir(e,t))}function qir(e,t,r){for(let n=t+1;n<e.length;n++){let s=e[n];if(s==="\\")n++;else{if(s===r)return n+1;if(s===`
|
|
706
|
+
`)}var qet=Jr({name:"finalize",model:"opus",timeoutMinutes:20,requires:[],branchRequires:{runtime:["adapt"],"no-runtime":["generate-unit"]},softRequires:["native-run"],prepare:e=>{let t=Air(e);return{unitTestFiles:t,unitAssertionBaseline:Det(e.inputs.repositoryPath,t),writtenBefore:[...Pa(_a(e.inputs))]}},buildPrompt:Eir,buildReadDirs:e=>Tu(e.inputs),allowedTools:["Read","Grep","Glob","Edit","Write","Bash(git status:*)","Bash(git diff:*)","Bash(ruff:*)","Bash(black:*)","Bash(flake8:*)","Bash(isort:*)","Bash(mypy:*)","Bash(npx:*)","Bash(npm:*)","Bash(pnpm:*)","Bash(yarn:*)","Bash(bun:*)","Bash(poetry:*)","Bash(uv:*)","Bash(pdm:*)","Bash(pipenv:*)","Bash(prettier:*)","Bash(eslint:*)","Bash(pip:*)","Bash(python:*)","Bash(python3:*)",...Gq],selfVerification:["You ran the repo's linter on the changed files and fixed every violation; each lint[] entry's command is a real re-runnable command, run from its checkout.","Each lint[] entry's uncovered names every changed/new file the linter's own config does not match, checked against the config itself, not assumed from a clean exit code.","You copied, moved, renamed or deleted no test; a test you think is misplaced is named in fileConventions.notes, not a blocker. ciReadiness.covered reflects whether CI will run them.","You changed no application manifest or lockfile except as a dependencies.added entry with its reason; every such entry is one a test cannot run without.","Every manifest you changed whose checkout tracks a lockfile for it has that lockfile updated by its package manager, in the same checkout.","commit.message and pr.title are <= 72 chars; pr.body summarizes what was added/maintained.","Your final message is one JSON object matching the schema."],exitGates:[Net,Pet,Let,Uet,_et,Oet,Qet,Tae],onPassed:kae,afterAttempt:Met,salvage:Fet});var Itt=J(require("crypto")),Yl=J(require("fs")),rl=J(require("path"));var wir=/^\s*(API Error\b|Failed to authenticate\b|Invalid API key\b)/,bir=/API Error(?: \([^)]*\))?: (\d{3})\b|request rejected \((\d{3})\)/i,Sir=/usage limits?|quota|credit balance|billing/i;function Get(e){if(e.timedOut||e.exitCode===0&&e.isError!==!0)return;let t=e.stdout??"";if(e.apiErrorStatus===void 0&&!wir.test(t))return;let r=bir.exec(t),n=e.apiErrorStatus??(r?Number(r[1]??r[2]):void 0);return{kind:n===401||n===403||n!==void 0&&n>=400&&n<500&&n!==429&&Sir.test(t)||/^\s*Invalid API key\b/.test(t)?"permanent":"temporary",...n!==void 0?{status:n}:{}}}function Hv(e=process.env){return e.CLAUDE_CODE_USE_BEDROCK==="1"?"AWS Bedrock":"Anthropic"}var rfn=Or.rows.notRun(!0),lN=e=>({deployed:qR(e)||JM(e),expected:Ho(e)?.sutRequired!==!1}),jet={deployed:!0,expected:!0},Pae="could not run here";function Het(e){let t=(e??"").trim();if(!(!t||![/the runner wrote no report/i,/reported no test:/i,/could not be set up/i,/test environment (?:did not load|lacks)/i,/\bits run cannot start\b/i,/\b(?:node_modules|dependencies|packages?|gems?|modules?) (?:is |are )?not installed\b/i,/\bnot installed\b/i,/\bno `?[\w.-]+`? on (?:its|the) PATH\b/i,/\bcommand not found\b/i,/\b(?:Cannot find module|ModuleNotFoundError|No module named|ImportError)\b/,/\bFailed to import\b/,/\bMissing X server\b|\bheadful browser\b/i,/\bEISDIR\b|\bENOENT\b/,/`(?:bundle|npm|pnpm|yarn|pip|uv|poetry|mvn|gradle)[^`]*` failed/i].some(n=>n.test(t))))return t.replace(/^(?:not run|could not run here)[:.]?\s*/i,"")}var zet=e=>({status:"Skipped",details:`${Pae}: ${e}`.slice(0,400),failureCause:{kind:"environment",family:"external_dependency"}}),Ef="kept, not ",kE="(declined the planned ";function Dae(e){return e.map(t=>t.expected===void 0?t.expectation:`${t.expectation} (${t.expected})`).join("; ")}function PG(e){if(!e)return[];let t=[],r=0,n=0;for(let s=0;s<e.length;s++){let i=e[s];i==="("?r++:i===")"?r=Math.max(0,r-1):r===0&&i===";"&&e[s+1]===" "&&e[s-1]===")"&&(t.push(e.slice(n,s)),n=s+2)}return t.push(e.slice(n)),t.map(s=>{let i=s.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(),l=i.slice(a+1,-1).trim();return c&&l?{expectation:c,expected:l}:{expectation:i}}return{expectation:i}})}var yf=new Set(["update","regenerate","delete"]),Bae=e=>e==null?"Skipped":e===0?"Pass":"Fail";function Wi(e,t){return t?.trim()||Rn(e.inputs).slug}var Cir={update:"updated",regenerate:"regenerated",delete:"deleted",verify:"verified",none:"touched"},vir=e=>Cir[e]??`${e}d`;function Iir(e,t,r,n=jet){let s=Or.rows.notRun(n.expected),i=l=>Wi(r,l).toLowerCase(),o=(e?.maintenance??[]).map(l=>{let u=t.find(A=>i(A.repository)===i(l.repository)&&(A.file===l.test||A.from&&A.from===l.test)),d=!!u&&yf.has(u.action),p=l.action!=="verify",f=u?.action??l.action,m=d?f:yf.has(f)||f==="none"?"verify":f,g=u?.reran?.exit!=null?Bae(u.reran.exit):void 0,w=(()=>{if(d){let A=u.action==="delete"?"removed":u.reran?.details??(u.reran?.exit==null?s:`exit ${u.reran.exit}`);if(!u.keptReason)return A;let y=`${kE}${l.action}: ${u.keptReason})`.slice(0,200);return`${A.slice(0,300-y.length-1)} ${y}`}return u?.keptReason?`${Ef}${vir(f)}: ${u.keptReason}`.slice(0,300):p?`recommended ${l.action}, not applied this run`:"not applied this run"})();return{repository:Wi(r,l.repository),testType:"existing",endpoint:"n/a",fileName:u?.file??l.test,description:l.evidence,action:m,beforeStatus:"Unknown",beforeDetails:l.evidence,afterStatus:d?u.action==="delete"?"Skipped":Bae(u.reran?.exit):g??"Unknown",afterDetails:w}}),a=l=>(e?.maintenance??[]).some(u=>i(l.repository)===i(u.repository)&&(l.file===u.test||l.from&&l.from===u.test)),c=t.filter(l=>yf.has(l.action)&&!a(l)).map(l=>({repository:Wi(r,l.repository),testType:"existing",endpoint:"n/a",fileName:l.file,description:"found stale while running the existing tests",action:l.action,beforeStatus:"Unknown",beforeDetails:"not in the plan's maintenance list",afterStatus:l.action==="delete"?"Skipped":Bae(l.reran?.exit),afterDetails:l.action==="delete"?"removed":l.reran?.details??(l.reran?.exit==null?s:`exit ${l.reran.exit}`)}));return[...o,...c]}function xir(e,t,r){let n=s=>Wi(r,s).toLowerCase();return(e??[]).map(s=>{let i=s.change==="deleted",o=$M(s.file),a=i?[]:t.filter(g=>n(g.repository)===n(s.repository)&&g.file===o),c=a.filter(g=>g.status==="Fail"),l=a.filter(g=>g.status==="Pass").length,u=i?"Skipped":c.length?"Fail":l?"Pass":a.length?"Skipped":"Unknown",d=a.length-c.length-l,p=[c.length&&`${c.length} failed`,l&&`${l} passed`,d&&`${d} skipped`].filter(Boolean).join(", "),f=o===s.file?"":` (run by ${o})`,m=i?"removed":a.length?`${p}${f}${c.length?`: ${c[0].details}`:""}`:"not re-run by this run's unit test run";return{repository:Wi(r,s.repository),testType:"existing",endpoint:"n/a",fileName:s.file,description:s.reason,action:i?"delete":"update",beforeStatus:"Unknown",beforeDetails:s.reason,afterStatus:u,afterDetails:m.slice(0,300)}})}function Rir(e,t){let r=i=>`${(i.repository??"").toLowerCase()}\0${i.fileName}`,n=new Set(e.filter(i=>yf.has(i.action)).map(r)),s=new Set(t.map(r));return[...e.filter(i=>n.has(r(i))||!s.has(r(i))),...t.filter(i=>!n.has(r(i)))]}function Tir(e,t,r,n,s,i,o=[]){let a=e?.behaviors??[];if(!a.length)return[];let c=new Set(n.filter(A=>A.testId&&A.status!=="Skipped").map(A=>A.testId)),l=new Set(s.map(A=>A.testId)),u=new Map,d=new Map;for(let A of t?.generate??[]){if(!A.from_behavior||!l.has(A.id))continue;let y=d.get(A.from_behavior)??[];if(y.includes(A.id)||y.push(A.id),d.set(A.from_behavior,y),!c.has(A.id))continue;let S=u.get(A.from_behavior)??[];S.includes(A.id)||S.push(A.id),u.set(A.from_behavior,S)}let p=A=>i?Wi(i,A).toLowerCase():"",f=A=>i?It(i.inputs,A):"",m=new Map;for(let A of t?.maintenance??[]){let y=r.find(C=>p(C.repository)===p(A.repository)&&(C.file===A.test||C.from&&C.from===A.test));if(!y||!yf.has(y.action))continue;let S=`${f(y.repository)}${y.file}`;for(let C of A.covers_behaviors??[]){let v=m.get(C)??[];v.includes(S)||v.push(S),m.set(C,v)}}let g=(A,y)=>o.filter(S=>y(S)&&S.behaviorIds.includes(A)).map(S=>S.testId),w=(A,y)=>[...new Set([...A,...y])].slice(0,wv);return a.slice(0,Oie).map(A=>({id:A.id,text:A.statement,source:A.evidence.slice(0,Die),testedBy:w(u.get(A.id)??[],g(A.id,y=>y.tested)),writtenBy:w(d.get(A.id)??[],g(A.id,y=>y.written)),maintainedBy:(m.get(A.id)??[]).slice(0,wv)}))}var Nae=(e,t)=>`${Sh(e)}::${t}`;function kir(e,t,r,n=[]){let s=i=>!(i.action==="delete"&&i.from);return{generated:e.length,modified:t.filter(i=>yf.has(i.action)&&s(i)).length+(n??[]).length,verified:t.filter(i=>s(i)&&(i.action==="verify"||!!i.keptReason)&&!yf.has(i.action)).length,executed:r.filter(i=>i.status!=="Skipped").length}}function Bir(e,t,r,n){let s=[],i=fe(e,"deploy.json"),o=w=>e.state.stages[w]?.status==="failed",a=e.state.modelProviderFailure,c=w=>o(w)&&a?.stage!==w&&!e.state.stages[w]?.reason?.startsWith("not run \u2014 the model provider refused");(c("deploy")||c("plan"))&&!i&&s.push({kind:"deploy-failed",text:Or.caveats.deployFailed,blocking:!0});let l=(t?.items??[]).filter(w=>w.action!=="delete"),u=l.filter(w=>w.reran?.exit===null||w.reran?.exit===void 0);l.length>0&&u.length===l.length&&s.push({kind:"tests-not-executed",text:Or.caveats.testsNotExecuted,blocking:!0}),i?.outcome&&i.outcome!=="clean"&&!JM(e)&&s.push(i.outcome==="change-broke-bringup"?{kind:"deploy-failed",subject:"change",text:Or.caveats.changeBrokeBringup,blocking:!0}:i.outcome==="bringup-failed"?{kind:"deploy-failed",text:Or.caveats.bringupFailed,blocking:!0}:{kind:"recipe-drift",text:Or.caveats.recipeDrift,blocking:!1});for(let[w,A]of Object.entries(i?.dependencies??{}))A===!1&&s.push({kind:"mocked-dependency",subject:w,text:Or.caveats.mockedDependency(w),blocking:!1});if(r?.ready===!1||o("finalize")||o("write")){let w=(r?.blockers??[]).slice(0,3).join("; ");s.push({kind:"finalize-not-ready",text:Or.caveats.finalizeNotReady(w),blocking:!0})}Ho(e)?.sutRequired===!1&&s.push({kind:"sut-not-required",text:Or.caveats.sutNotRequired,blocking:!1});let d=Tv(e);d.length&&s.push({kind:"analysis-unverified",text:Or.caveats.analysisUnverified(d.length),blocking:!1});let p=jM(xp(e)??{results:[],notRun:[]});p&&s.push({kind:"unit-tests-not-run",text:Or.caveats.unitTestsNotRun(p),blocking:!1});let f=(n??[]).filter(w=>w.status==="Skipped"&&w.details?.startsWith(`${Pae}:`));f.length&&s.push({kind:"tests-could-not-run-here",text:Or.caveats.testsCouldNotRunHere(f.length,f[0].details.slice(Pae.length+2)),blocking:!1});let m=MK(e).map(w=>w.behaviorId?`${w.behaviorId}: ${w.missing}`:w.missing);if(m.length&&s.push({kind:"downstream-not-checked",text:Or.caveats.downstreamNotChecked(m.join("; ")),blocking:!1}),a){let w=LK(e,s),A=(n??[]).some(S=>S.status==="Pass"||S.status==="Fail"),y=w?w.sufficiency==="sufficient"&&(w.acceptedEvidence.length>0||A):A;s.push(a.kind==="permanent"?{kind:"model-provider-denied",text:Or.caveats.modelProviderDenied(Hv(),y),blocking:!y}:{kind:"model-provider-unavailable",text:Or.caveats.modelProviderUnavailable(Hv(),y),blocking:!y})}r?.ciReadiness?.covered===!1&&s.push({kind:"ci-not-covered",text:Or.caveats.ciNotCovered,blocking:!1});let g=(r?.lint??[]).flatMap(w=>(w.uncovered??[]).map(A=>`${It(e.inputs,w.repository)}${A}`));return g.length>0&&s.push({kind:"lint-not-covered",subject:g.join(", "),text:Or.caveats.lintNotCovered(g.join(", ")),blocking:!1}),s}function Nir(e,t,r,n,s,i=jet,o=()=>{}){let a=[];for(let c of e.filter(l=>l.action!=="delete")){let l=c.reran?.exit,u=Vet(c.action),d=c.from?n.get(c.from):void 0,p=[...new Set([...c.covers??[],...d??[]])],f=p.length?p:[void 0];if(c.placementBroken){for(let $ of f){let P=$?t.get($):void 0;a.push({testId:$,testType:_ae(P?.type,o(c)),endpoint:P?.target??"n/a",fileName:c.file,repository:s?.(c),origin:u,status:"Skipped",details:`could not be placed or run: ${c.reran?.details??"harness problem"}`.slice(0,300),failureCause:{kind:"test_defect"}})}continue}let m={fail:0,skip:1,pass:2},g=new Map;for(let $ of c.reran?.tests??[]){let P=g.get($.case);(!P||m[$.status]<m[P.status])&&g.set($.case,$)}let w=g.size>0,A=$=>$===void 0?void 0:$.status==="skip"?"Skipped":$.status==="pass"?"Pass":"Fail",y=l==null?"Skipped":l===0?"Pass":"Fail",S=l!=null&&!w&&f.length>1,C=u==="existing"&&w&&!f.some($=>$&&g.has($)),v=[...g.values()],R=v.some($=>$.status==="fail")?"Fail":v.some($=>$.status==="pass")?"Pass":"Skipped",T=$=>{if(C)return R;let P=A($?g.get($):void 0);return P||(w||S?"Skipped":y)},G=[...g.entries()].filter(([,$])=>$.status==="fail").map(([$])=>$),B=v.filter($=>$.status==="pass").length,H=[G.length&&`${G.length} failed (${G.slice(0,5).join(", ")})`,B&&`${B} passed`].filter(Boolean).join(", "),z=f.filter($=>T($)==="Fail").length,ne=z===1&&c.finding?"failed \u2014 caught a real bug in the change":z===1&&c.repro?"fails as intended \u2014 reproduces the reported bug":"failed",Z=z===1&&!!(c.finding||c.repro);for(let $ of f){let P=$?t.get($):void 0,N={testId:$,testType:_ae(P?.type,o(c)),endpoint:P?.target??"n/a",fileName:c.file,repository:s?.(c),origin:u},W=$?g.get($):void 0,k=T($);if(C&&k!=="Skipped")a.push({...N,status:k,details:`${k==="Fail"?"failed":"passed"}: ${H}`.slice(0,400)});else if(k==="Skipped"){let F=W===void 0&&!C&&(w||S),j=F?"no result recorded for this case":c.reran?.details?.slice(0,300)||Or.rows.notRun(i.expected),V=F?void 0:Het(c.reran?.details),O=!V&&W===void 0&&!F&&l===null;V?a.push({...N,...zet(V)}):a.push({...N,status:"Skipped",details:j,...O?{failureCause:{kind:"environment",family:"app_not_started"}}:{}})}else if(k==="Pass")a.push({...N,status:"Pass",details:W?Or.rows.passed(i.deployed):c.reran?.details?.slice(0,300)||Or.rows.passed(i.deployed)});else{let F=W?z===1&&c.reran?.details?c.reran.details.slice(0,200):c.from?r.get(`${c.from}::${$}`):void 0:c.reran?.details?c.reran.details.slice(0,200):void 0;a.push({...N,status:"Fail",details:`${ne}${F?`: ${F}`:""}`.slice(0,400),...Z?{failureCause:{kind:"application"}}:{}})}}}return a}function _ae(e,t){return t==="ui"||t==="unit"?t:e??t??"integration"}function Vet(e){return e==="place"?"new":e==="update"||e==="regenerate"?"updated":"existing"}function Pir(e,t){let r=(t?.results??[]).filter(BK),n=(t?.notRun??[]).filter(i=>i.origin==="written");if(!r.length&&!n.length)return e;let s=(i,o,a)=>o===i.fileName&&(!a||!i.repository||a===i.repository);return e.map(i=>{let o=r.filter(f=>s(i,f.file,f.repository)),a=o.filter(f=>!!i.testId&&f.behaviorIds.includes(i.testId)),c=a.filter(f=>f.status==="Pass"||f.status==="Fail"),{failureCause:l,...u}=i;if(c.length){let f=c.find(m=>m.status==="Fail");return f?{...u,status:"Fail",details:`failed when Testbot re-ran it${i.status==="Fail"?"":" (write's own run reported it passing)"}: ${f.details}`.slice(0,400),...i.status==="Fail"&&l&&!f.fromFile?{failureCause:l}:{}}:{...u,status:"Pass",details:`passed when Testbot re-ran it${i.status==="Fail"?" (write's own run reported a failure)":""}`}}let d=n.find(f=>s(i,f.file,f.repository))?.reason??(a.length?"every re-run of it was skipped":o.length?"its re-run reported no result for this case":void 0);if(!d)return i;let p=i.status==="Skipped"?Het(d):void 0;return p?{...u,...zet(p)}:{...i,details:`${i.details} \u2014 write's own run; Testbot could not re-run it: ${d}`.slice(0,400)}})}function Jm(e){let t=fe(e,"analyze.json"),r=fe(e,"recommend.json"),n=fe(e,"generate.json"),s=fe(e,"generate-ui.json"),i=fe(e,"adapt.json"),o=fe(e,"finalize.json"),a=new Map((r?.generate??[]).map(O=>[O.id,O])),c=[...n?.tests??[],...s?.tests??[]],l=(i?.items??[]).filter(O=>O.file),u=(O,K)=>{let te=dr(e.inputs,K)?.path??e.inputs.repositoryPath;return te?rQe(te,O):void 0},d=[],p=new Set,f=(O,K,te)=>{let X=`${te}:${O}`;if(p.has(X))return;p.add(X);let le=K?.length?K:[Sh(O)];for(let he of le){let me=a.get(he);d.push({testId:he,testType:_ae(me?.type,u(O,te)),endpoint:me?.target??"n/a",fileName:O,description:me?.rationale??`Generated test ${O}`,reasoning:me?.expected_observable??"covers a recommended case",repository:te})}};for(let O of c){let K=l.find(te=>te.from===O.file);!K||K.action!=="place"||f(K.file,O.covers,Wi(e,K.repository))}for(let O of l.filter(K=>K.from&&K.action==="place"))f(O.file,O.covers,Wi(e,O.repository));let m=new Map;for(let O of c)for(let K of O.assertions??[])m.set(`${O.file}::${K.case}`,K.evidence);let g=new Map(c.map(O=>[O.file,O.covers??[]])),w=lN(e),A=Pir(Nir(l,a,m,g,O=>Wi(e,O.repository),w,O=>u(O.file,O.repository)),xp(e)),y=new Map((t?.behaviors??[]).map(O=>[O.id,O.surface])),S=O=>O.map(K=>y.get(K)).find(Boolean)??"n/a",C=fe(e,ts),v=C?.tests??[];for(let O of v)for(let K of O.names)d.push({testId:Nae(O.file,K),testType:"unit",endpoint:S(O.covers),fileName:O.file,description:Dae(O.assertions).slice(0,400),reasoning:`native ${O.framework} unit test for ${O.covers.join(", ")}`,repository:Wi(e,O.repository)});let R=new Map;for(let O of v)for(let K of O.covers){let te=`${O.file}\0${K}`,X=R.get(te)??new Set;for(let le of O.assertions)X.add(le.source.replace(/_/g," "));R.set(te,X)}let T=O=>{let K=[...new Set(O.behaviorIds.flatMap(te=>[...R.get(`${O.file}\0${te}`)??[]]))];return O.status!=="Fail"||O.origin!=="generated"||!K?.length?O.details:`fails \u2014 the code disagrees with what this new test asserts (from the ${K.join(", ")}): ${O.details}`.slice(0,300)},G=xp(e)?.results??[],B=C?.maintained??[],H=Rir(Iir(r,l,e,w),xir(B,G,e)),z=O=>Nae(O.file,O.selectedName??O.name),ne=(O,K)=>`${Wi(e,O).toLowerCase()}\0${K}`,Z=new Set(G.filter(O=>O.origin!=="written"&&O.name!==Mn).map(O=>ne(O.repository,O.file))),$=[];for(let O=A.length-1;O>=0;O--)A[O].origin==="existing"&&Z.has(ne(A[O].repository,A[O].fileName))&&$.unshift(...A.splice(O,1).filter(K=>K.testId));let P=new Set([...B.filter(O=>O.change==="updated").map(O=>`${Wi(e,O.repository).toLowerCase()}\0${$M(O.file)}`),...l.filter(O=>Vet(O.action)==="updated").map(O=>`${Wi(e,O.repository).toLowerCase()}\0${O.file}`)]),N=O=>O.origin==="generated"?"new":O.written||P.has(`${Wi(e,O.repository).toLowerCase()}\0${O.file}`)?"updated":"existing";for(let O of G.filter(K=>K.origin!=="written"))A.push({...O.name!==Mn?{testId:z(O)}:{},testType:"unit",endpoint:S(O.behaviorIds),status:O.status,details:T(O),fileName:O.file,repository:O.repository,resultId:Nq(O.repository,"unit",O.file,O.name),origin:N(O),...O.status==="Fail"&&O.origin==="generated"&&O.name!==Mn&&!O.fromFile?{failureCause:{kind:"application"}}:{}});let W=[...v.flatMap(O=>O.names.map(K=>({testId:Nae(O.file,K),behaviorIds:O.covers,written:!0,tested:!1}))),...G.filter(O=>O.origin!=="written"&&O.name!==Mn&&!O.fromFile&&O.status!=="Skipped").map(O=>({testId:z(O),behaviorIds:O.behaviorIds,written:!1,tested:!0}))],k=Bir(e,i,o,A),j=(fe(e,Fa)?.packages??[]).filter(O=>l.some(K=>!K.repository&&K.action!=="delete"&&xl(K.file,[O.dir]))).map(O=>({directory:O.dir,runner:O.runner,entrypoint:O.entrypoint,created:O.created,...e.inputs.repositorySlug?{repository:e.inputs.repositorySlug}:{}})),V=(o?.dependencies?.added??[]).map(O=>({package:O.package,manifest:O.manifest,...O.reason?{reason:O.reason}:{},...O.repository?{repository:O.repository}:{}}));return{testPackages:j,dependencyChanges:V,caseEvidence:$,newTestsCreated:d,testMaintenance:H,testResults:A,caveats:k,changes:Tir(t,r,l,[...A,...$],d,e,W),executionCoverage:kir(d,l,A,B),commitMessage:o?.commit?.message?.trim()||"Skyramp Testbot: add generated tests",validation:LK(e,k),system:Ho(e)?.sutRequired||fe(e,`${vs}.json`)||kS(e)?P4(e):void 0,testExecutionContexts:Ho(e)?.sutRequired===!1?void 0:hPe(e,l,c)}}var Wet=E.string().trim().min(1),uN=E.object({schemaVersion:E.literal(1).optional(),businessCaseAnalysis:Wet.describe("1-2 sentences: what this change means for a user, and whether the evidence shows it working"),issuesFound:E.array(E.object({description:Wet,severity:E.string().optional().describe("critical | high | medium | low"),category:E.string().optional().describe("bug | lint | type | config"),sourceFile:E.string().optional(),sourceLine:E.number().optional(),findingId:E.string().optional(),requirementIds:E.array(E.string()).optional()})).describe("every real problem this run exposed \u2014 cause, file:line, severity"),nextSteps:E.array(E.string()).describe("concrete follow-ups the author can act on; required non-empty when a disclosure is BLOCKING")});function _ir(e){return xn(uN,e).errors}function dN(e,t=[]){let{value:r,error:n}=br(e.stdout,t);if(n)return{errors:[n]};let s=_ir(r);return s.length>0?{errors:s}:{prose:r,errors:[]}}function BE(e,t){let r={schemaVersion:1,businessCaseAnalysis:t.businessCaseAnalysis,newTestsCreated:e.newTestsCreated,testMaintenance:e.testMaintenance.length?e.testMaintenance:void 0,testResults:e.testResults,issuesFound:[...t.issuesFound],nextSteps:[...t.nextSteps],caveats:e.caveats.length?e.caveats:void 0,changes:e.changes.length?e.changes:void 0,executionCoverage:Object.values(e.executionCoverage).some(s=>s>0)?e.executionCoverage:void 0,commitMessage:e.commitMessage,...e.validation?{validation:e.validation}:{},...e.system?{system:e.system}:{},...e.testExecutionContexts?{testExecutionContexts:e.testExecutionContexts}:{},...e.testPackages.length?{testPackages:e.testPackages}:{},...e.dependencyChanges.length?{dependencyChanges:e.dependencyChanges}:{}},n=r.validation?.blockedPreflight;if(n){let s=n.repository?`${n.repository}/${n.file}`:n.file,i=`The change cannot build or start: ${n.reason} (${s}). ${n.evidence}`,o=`Correct the code in ${s}, then rerun validation.`;r.businessCaseAnalysis=`${i} ${o} No tests ran.`,r.issuesFound.some(a=>a.sourceFile===n.file&&a.description.includes(n.evidence))||r.issuesFound.push({description:i,severity:"high",category:"bug",sourceFile:n.file}),r.nextSteps.includes(o)||r.nextSteps.unshift(o)}return r}var Yet=js("report-schema",(e,t)=>dN(t,e.secretValues)),Dir=/\b(preflight|analyze|deploy|recommend|generate(?:-ui)?|adapt|finalize|report)\.json\b|\bexit gate\b|\b(?:stage|gate)s? (?:failed|passed)\b|\bgenerate-ui\b/i,Oir=/\bmcp__[a-z0-9_]+\b|\bskyramp_[a-z][a-z0-9_]*\b/,Jet={name:"report-visibility",verify(e,t){let{prose:r,errors:n}=dN(t,e.secretValues);if(!r)return Be(this.name,n);let s=_G(e,BE(Jm(e),r));return s.length===0?{name:this.name,passed:!0}:Be(this.name,s)}};function _G(e,t){let r=[],n=fe(e,"deploy.json");e.state.stages.deploy?.status==="passed"&&!n&&r.push("deploy passed but deploy.json is unreadable \u2014 cannot verify its outcome / mocked deps were surfaced");let s=fe(e,"adapt.json");for(let l of(s?.items??[]).filter(u=>u.finding&&u.file)){let u=Sh(l.file);t.issuesFound.some(p=>`${p.description} ${p.sourceFile??""}`.toLowerCase().includes(u))||r.push(`adapt marked "${l.file}" finding:true (a real bug caught) but no issuesFound entry names that test \u2014 surface the bug`)}let i=fe(e,"recommend.json");if(e.state.stages.recommend?.status==="passed"&&i?.generate){let l=new Set(t.newTestsCreated.map(d=>d.testId.toLowerCase())),u=(t.nextSteps.join(" ")+" "+t.issuesFound.map(d=>d.description).join(" ")).toLowerCase();for(let d of i.generate){let p=d.id?.trim();p&&!l.has(p.toLowerCase())&&!u.includes(p.toLowerCase())&&r.push(`recommended case "${p}" is neither a test in newTestsCreated nor named in nextSteps/issuesFound \u2014 say what happened to it`)}}let o=(t.caveats??[]).filter(l=>l.blocking);o.length>0&&t.nextSteps.length===0&&r.push(`this run is not evidence the change works (${o.map(l=>l.kind).join(", ")}) and nextSteps is empty \u2014 say what the author should do about it`);let a=`${t.businessCaseAnalysis} ${t.issuesFound.map(l=>l.description).join(" ")} ${t.nextSteps.join(" ")}`,c=a.match(Dir)??a.match(Oir);return c&&r.push(`user-facing text leaks internal machinery ("${c[0]}") \u2014 describe the code/repo, not the testbot's stages, gates, tools or artifact files`),r}function Ket(e,t){let{prose:r,errors:n}=dN(t,e.secretValues);return Nt(e,"report",r?BE(Jm(e),r):void 0,n)}var Gae=J(require("fs")),NE=J(require("path"));var Xet=J(require("fs"));var OG=2*1024*1024;function Mae(e){let t=[];for(let r of e??[])if(r.state==="read")try{t.push({item:r,text:Xet.readFileSync(IXe(r),"utf-8")})}catch{}return t}var DG=6,Qir=/[\p{L}\p{N}]+/gu,Mir=new RegExp("(?<=\\p{Ll})(?=\\p{Lu})|(?<=\\p{Lu})(?=\\p{Lu}\\p{Ll})","u");function Zet(e){let t=[];for(let r of e.matchAll(Qir)){let n=r.index;for(let s of r[0].split(Mir))t.push({word:s.toLowerCase(),start:n,end:n+s.length}),n+=s.length}return t}var ett=(e,t)=>e.slice(t,t+DG).map(r=>r.word).join(" ");function Km(e){return Mae(e).map(({item:t,text:r})=>{let n=Zet(t.source==="other"?r:r.slice(r.indexOf(`
|
|
707
|
+
`)+1||r.length)),s=new Set;for(let i=0;i+DG<=n.length;i++)s.add(ett(n,i));return{name:Cb(t.key,Gi([t])),runs:s}})}function Fae(e,t){if(t.length===0)return[];let r=Zet(e),n=[];for(let s=0;s+DG<=r.length;s++){let i=ett(r,s),o=t.find(u=>u.runs.has(i));if(!o)continue;let a=r[s].start,c=r[s+DG-1].end,l=n.at(-1);l&&a<=l.end?l.end=Math.max(l.end,c):n.push({start:a,end:c,name:o.name})}return n}function Fir(e,t){return[...new Set(Fae(e,t).map(r=>r.name))]}function zv(e,t){let r=e;for(let n of Fae(e,t).reverse())r=`${r.slice(0,n.start)}(see ${n.name})${r.slice(n.end)}`;return r}var ttt=new Set(["testId","testedBy","writtenBy","coveredBy","id"]),Lir=new Set(["resultId","test","file","fileName","sourceFile","repository","maintainedBy"]);function Oae(e,t){return t!==void 0&&ttt.has(t)?(Array.isArray(e)?e:[e]).filter(r=>typeof r=="string"):Array.isArray(e)?e.flatMap(r=>Oae(r)):e&&typeof e=="object"?Object.entries(e).flatMap(([r,n])=>Oae(n,r)):[]}function Uir(e,t){let r=new Set(Oae(e)),n=new Set(r),s=new Map;for(let i of r){let o=Fae(i,t);if(o.length===0)continue;let a=i;for(let l of[...o].reverse())a=`${a.slice(0,l.start)}${$ir(l.name)}${a.slice(l.end)}`;let c=a;for(let l=2;n.has(c);l++)c=`${a}-${l}`;n.add(c),s.set(i,c)}return s}var $ir=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");function Qae(e,t,r,n,s=!1){return n!==void 0&&Lir.has(n)?e:n!==void 0&&ttt.has(n)?Array.isArray(e)?e.map(i=>r.get(i)??i):typeof e=="string"?r.get(e)??e:e:typeof e=="string"?s?e:zv(e,t):Array.isArray(e)?e.map(i=>Qae(i,t,r,void 0,s)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([i,o])=>[i,Qae(o,t,r,i,s||i==="requirementReferences")])):e}function QG(e,t){return t.length===0?e:Qae(e,t,Uir(e,t))}function qir(e,t,r){for(let n=t+1;n<e.length;n++){let s=e[n];if(s==="\\")n++;else{if(s===r)return n+1;if(s===`
|
|
708
708
|
`&&r!=="`")return n}}return e.length}function Gir(e,t){let r=e.lastIndexOf(`
|
|
709
709
|
`,t-1)+1;if(e.slice(r,t).trim()!=="")return!1;let n=e.slice(0,r).trimEnd();return n===""||n.endsWith(":")}function rtt(e){let t=[],r=s=>(e.indexOf(`
|
|
710
710
|
`,s)+1||e.length+1)-1,n=0;for(;n<e.length;){let s=e[n],i=e[n+1],o=n+1;if(s==="/"&&i==="*")o=e.indexOf("*/",n+2)<0?e.length:e.indexOf("*/",n+2)+2,t.push({start:n,end:o});else if(s==="/"&&i==="/"&&!/[:\w]/.test(e[n-1]??"")||s==="#"&&/^\s?$/.test(e[n-1]??"")&&!/[!{[]/.test(i??""))o=r(n),t.push({start:n,end:o});else if((s==='"'||s==="'")&&e.startsWith(s.repeat(3),n)){let a=e.indexOf(s.repeat(3),n+3);o=a<0?e.length:a+3,Gir(e,n)&&t.push({start:n,end:o})}else(s==='"'||s==="'"||s==="`")&&(o=qir(e,n,s));n=o}return t}var jir=/\b(?:test|it|describe|context|suite|scenario|specify|Run|DisplayName)(?:\.\w+)*(?:\.each\s*(?:\((?:[^()]|\([^()]*\))*\)|`[^`]*`))?\s*\(\s*("(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`)/g;function ntt(e,t){return[...e.matchAll(jir)].flatMap(r=>{if(t.some(s=>r.index>=s.start&&r.index<s.end))return[];let n=r.index+r[0].length;return[{start:n-r[1].length,end:n}]})}function stt(e,t){if(t.length===0)return{content:e,cleaned:!1};let r=rtt(e),n=[];for(let a of r){let c=e.slice(a.start,a.end),l=zv(c,t);l!==c&&n.push({...a,text:l})}let s=ntt(e,r),i=new Set(s.map(a=>e.slice(a.start+1,a.end-1)));for(let a of s){let c=e[a.start],l=e.slice(a.start+1,a.end-1),u=zv(l,t);if(u===l)continue;let d=u;for(let p=2;i.has(d);p++)d=`${u} (${p})`;i.add(d),n.push({...a,text:`${c}${d}${c}`})}let o=e;for(let a of n.sort((c,l)=>l.start-c.start))o=`${o.slice(0,a.start)}${a.text}${o.slice(a.end)}`;return{content:o,cleaned:o!==e}}var Hir=/\b(?:def|func|function|fun|void|async\s+def)\s+([Tt]est\w*)/g;function itt(e,t){let r=rtt(e),n=[...r,...ntt(e,r)].map(s=>e.slice(s.start,s.end));for(let s of e.matchAll(Hir))n.push(s[1]);return[...new Set(n.flatMap(s=>Fir(s,t)))]}var MG=J(require("fs")),pN=J(require("path"));var ott=12,zir=/^(?:Description|Acceptance criteria):[ \t]*$/gm;function Lae(e){return Mae(e).map(({item:t,text:r})=>({item:t,text:t.source==="jira"?r.replace(zir,""):r}))}var att=e=>new Map(Lae(e).map(({item:t,text:r})=>[Gs(t.key),r])),ctt=e=>kc(e).replace(/^["']+|["']+$/g,"").trim(),ltt=e=>[e.evidence,ZA(e.evidence)].filter(t=>!!(t&&ctt(t).length>=ott));function Vv(e,t){return ltt(e).find(n=>ZR(t,n))?.trim().replace(/^["'\u201c\u2018]+|["'\u201d\u2019]+$/g,"").trim()}var Vir=e=>new Map((e??[]).flatMap(t=>t.state==="read"&&AE(t.file)&&!uoe(t.path)?[[Gs(t.key),yE(t.path)]]:[]));function Wir(e,t,r){let n=e.reference?.trim();if(!r||!n||(t??[]).some(o=>Gs(o.key)===Gs(n)))return!1;let s=pN.resolve(r),i=pN.resolve(s,n.replace(/:\d+(?:-\d+)?$/,""));if(!i.startsWith(s+pN.sep))return!1;try{if(!MG.statSync(i).isFile())return!1;let o=MG.readFileSync(i,"utf8");return Vv(e,o)!==void 0}catch{return!1}}function Yir(e){return utt({...e,source:"spec",evidence:`${e.reference}: ${e.evidence}`})}function utt(e){let t={...e};return delete t.reference,delete t.criterion,delete t.notInChange,t}function Jir(e,t,r){let n=e.reference?.trim();return n&&(t??[]).some(s=>Gs(s.key)===Gs(n))?!1:r.some(s=>Vv(e,s)!==void 0)}function dtt(e,t,r,n){if(e.source==="requirement-reference"){if(Wir(e,t,r))return Yir(e);if(Jir(e,t,n))return utt({...e,source:"pr-description"})}}function ptt(e,t,r=new Map){let n=e.reference===void 0?void 0:Gs(e.reference);if(!n)return'names no item: give "reference", the key of the item it comes from';let s=t.get(n);return r.has(n)?`names ${n}, an uploaded document with no extracted text: write the text you extracted to ${r.get(n)}`:s===void 0?`names ${n}, which is not an item this run read`:ltt(e).length?Vv(e,s)!==void 0?void 0:`its evidence is not in ${n}: copy the item's own words`:`its evidence is not a quote of ${n} of at least ${ott} characters`}function Uae(e,t,r,n=[]){let s=e.requirements.filter(a=>a.source==="requirement-reference"&&!dtt(a,t,r,n));if(!s.length)return[];let i=att(t),o=Vir(t);return s.flatMap(a=>{let c=ptt(a,i,o);return c?[{id:a.id,why:c}]:[]})}var Kir=/^\s*(?:[-*+•]\s+)?(?:\*\*)?(?:AC\s*[-#]?\s*(\d+)(?=[\s.):*,-]|$)|(\d+)[.)](?=\s))/i,ftt=e=>{let t=Kir.exec(e),r=t?Number(t[1]??t[2]):0;return r>0?r:void 0};function Xir(e,t){let r=e.split(`
|