@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/post.js CHANGED
@@ -226,12 +226,12 @@ ${e.message??""}`));function YH(e){if(!e.length||!e.every(Hfe))return;let t=e.fi
226
226
  `).find(A=>A.trim());r.push({file:i,name:l.fullName||l.title||"(unnamed)",...l.ancestorTitles?.length?{suite:l.ancestorTitles.join(" > ")}:{},status:d,details:d==="Fail"?h?.trim().slice(0,300)??"failed":d==="Pass"?"passed":c?`not run: the file failed before its tests ran (${u})`:"skipped by the test"})}}return r}var Yfe=new Set(["node_modules",".git","dist","build",".venv","venv","__pycache__",".skyramp","coverage",".next"]);function Fw(e,t,n,r=3){return zH(e,s=>Ep(t,s),n,r)}function WH(e,t){let n=eo(e,t);if(!n||to(n)||Fw(e,n,[t],1).length)return n?[n]:[];let{stem:r}=CQ(t),s=ue.posix.dirname(t),o=zH(e,c=>LH(c)&&(Jfe(c)===r||ue.posix.dirname(c)===s),[t],1)[0],a=o&&eo(e,o);return a?[a]:[n]}function Jfe(e){let[t,n]=PA(e).split("*"),r=ue.basename(e);return r.slice(t.length,r.length-n.length)}function zH(e,t,n,r){let s=[],i=5e3,o=u=>{if(i--<=0)return;let l;try{l=Kt.readdirSync(u,{withFileTypes:!0})}catch{return}for(let d of l){if(i--<=0)return;let h=ue.join(u,d.name);if(d.isDirectory()){Yfe.has(d.name)||o(h);continue}let A=ue.relative(e,h).split(ue.sep).join("/");t(A)&&s.push(A)}};o(ue.resolve(e));let a=(u,l)=>{let d=u.split("/"),h=l.split("/"),A=0;for(;A<d.length&&A<h.length&&d[A]===h[A];)A++;return A},c=u=>Math.max(0,...n.map(l=>a(u,l)));return s.sort((u,l)=>c(l)-c(u)||u.localeCompare(l)).slice(0,r)}var KH=require("child_process"),_w=j(require("path")),wp="maintenance-flags.json",ZH=3;function bQ(e){let t=e.trim().match(/^(.+):(\d+)$/);return t?{file:t[1].replace(/^\.\//,""),line:Number(t[2])}:void 0}function Wfe(e,t){return e.split(/[^A-Za-z0-9_.-]+/).filter(n=>t.has(n))}function Mw(e,t){let n=[];for(let r of e){let s=r.staleBecause;if(!s){n.push(`${r.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}Wfe(s.requirement,t.requirementIds).length||n.push(`${r.file}: staleBecause names "${s.requirement}", and no requirement or clause id of the plan is in it`);let i=bQ(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)<=ZH))&&n.push(`${r.file}: ${s.line} is not code this change altered, so the change does not replace what the test asserts`)}return n}function XH(e,t){let n=new Map;for(let r of e){let s=r.staleBecause?bQ(r.staleBecause.line):void 0;if(!s)continue;let i=[...t.defectLines].find(([a])=>{let c=bQ(a);return c&&c.file===s.file&&Math.abs(c.line-s.line)<=ZH});if(!i)continue;let o=n.get(i[1])??{at:i[0],files:[]};o.files.includes(r.file)||o.files.push(r.file),n.set(i[1],o)}return[...n].map(([r,{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 ${r} (${o}): check the updates do not hide it.`})}function e2(e,t){let n=[],r=o=>o.trim().replace(/^\.\//,""),s=new Map(t.map(o=>[r(o.file),o])),i=new Set(e.map(r));for(let o of t)(o.changed||i.has(r(o.file)))&&!o.ran&&n.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)||n.push(`${o} is an existing test you changed and is not in your result: re-run it and list it with its result`);return n}function zfe(e,t=""){let n=new Map,r,s;for(let i of e.split(`
227
227
  `)){let o=i.match(/^--- a\/(.+)$/);o&&(s=o[1]);let a=i.match(/^\+\+\+ b\/(.+)$/);if(a){r=t+a[1];continue}if(i.startsWith("+++ /dev/null")){s&&!n.has(t+s)&&n.set(t+s,new Set),r=void 0;continue}let c=i.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/);if(!c||!r)continue;let u=Number(c[1]),l=c[2]===void 0?1:Number(c[2]),d=n.get(r)??new Set;for(let h=u;h<u+Math.max(l,1);h++)d.add(h);n.set(r,d)}return n}function $w(e,t){return SQ([{path:e.repositoryPath,base:t,related:!1},...(e.relatedRepos??[]).map(n=>({path:n.path,base:n.base??"origin/main",related:!0}))])}function SQ(e){let t=new Map;for(let n of e){let r="";try{r=(0,KH.execFileSync)("git",["-C",n.path,"diff","-U0","--no-color",`${n.base}...HEAD`],{encoding:"utf-8",maxBuffer:64*1024*1024})}catch{continue}let s=n.related?`${_w.basename(_w.resolve(n.path))}/`:"";for(let[i,o]of zfe(r,s))t.set(i,o)}return t}function Ow(e){let t=/^(.*?)(?:^|\/)__snapshots__\/([^/]+)\.snap$/.exec(e);return t?`${t[1]?`${t[1]}/`:""}${t[2]}`:e}var Zt="generate-unit.json";function Kfe(e){let{value:t,error:n}=ft(e);if(n)return{errors:[n]};let{value:r,errors:s}=_t(gA,t);return s.length?{errors:s}:{output:r,errors:[]}}function Lu(e){return Kfe(e.stdout)}var r2=yn("generate-unit-schema",(e,t)=>Lu(t)),Zfe=/(^|\/)(__pycache__|\.pytest_cache|node_modules|coverage|\.vitest)(\/|$)|\.pyc$/;function vQ(e){let t="";try{t=(0,n2.execFileSync)("git",["status","--porcelain","--untracked-files=all"],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]})}catch{return{modified:[],added:[]}}let n=[],r=[];for(let s of t.split(`
228
228
  `)){if(!s.trim())continue;let i=s.slice(3).trim().replace(/^"|"$/g,"");Zfe.test(i)||i.startsWith(".skyramp/")||(s.startsWith("??")?r:n).push(i)}return{modified:n,added:r}}var Uw=String.raw`(?:node:)?(?:http|https|http2|net|tls|dgram)`,Xfe=[[/\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+["']${Uw}["']|\bimport\s+["']${Uw}["']|require\(\s*["']${Uw}["']\s*\)|\bimport\(\s*["']${Uw}["']\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 Lw(e){return Xfe.filter(([t])=>t.test(e)).map(([,t])=>t)}var eAe=/@playwright\/test|\bfrom\s+playwright\b|\bimport\s+playwright\b|["']playwright["']|\bselenium\b|\bpuppeteer\b|\bcypress\b|\bwebdriverio\b|\bpage\.goto\s*\(/;function s2(e){return Lw(e).length===0&&!eAe.test(e)}function tAe(e){let t=[],n=/\b(?:test|it|describe)(?:\.\w+)*\(\s*(['"`])((?:\\.|(?!\1)[^\\])*)\1/g;for(let r=n.exec(e);r;r=n.exec(e))t.push(r[2]);return t}function nAe(e){let t=[],n=/(["'`])((?:\\.|(?!\1)[^\\\n])*)\1/g;for(let r=n.exec(e);r;r=n.exec(e))r[2].trim()&&t.push(r[2]);return t}function rAe(e,t,n,r){if(!to(e)){let i=r.replace(/(?:\[[^\]]*\]|\([^)]*\)|<[^>]*>)+$/,"").split(/::|#/).pop().trim(),a=(/\s/.test(i)?i:i.split(".").pop()).replace(/\/.*$/,"").trim();return a&&t.includes(a)?!0:nAe(t).some(c=>r===c||r.endsWith(` ${c}`))}if(e==="pytest"){let s=r.split("::").pop().replace(/\[.*\]$/,"");return new RegExp(`\\bdef\\s+${s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*\\(`).test(t)}return/\.each\s*[(`]/.test(t)?!0:n.some(s=>s&&(r===s||r.endsWith(` ${s}`)))}function sAe(e,t,n=[],r=[],s=new Set){let i=[],o=new Set(e.tests.flatMap(h=>h.covers)),a=new Set((e.journeysNotWritten??[]).map(h=>h.journey.trim()));for(let h of r)!o.has(h)&&!a.has(h)&&i.push(`journey "${h}" 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(h=>h.id));for(let h of n)!o.has(h)&&!c.has(h)&&i.push(`defect "${h}" 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 h of e.defectsNotTested??[])n.includes(h.id)||i.push(`defectsNotTested names "${h.id}", which is not a defect the plan found (${n.join(", ")||"none"})`);let u=[...t,...n,...r];for(let h of t)!o.has(h)&&!s.has(h)&&i.push(`behavior "${h}" was planned a new unit test and no file covers it \u2014 every planned new unit test is written`);for(let h of e.tests)for(let A of h.covers)u.includes(A)||i.push(`${h.file}: covers "${A}", which is neither a behavior planned a new unit test nor a defect the plan found (${u.join(", ")||"none"})`);let l=new Set(e.tests.flatMap(h=>h.names.map(A=>`${h.file}::${A.replace(/\[.*\]$/,"")}`))),d=Math.max(2,2*u.length);return l.size>d&&i.push(`${l.size} test functions for ${u.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 iAe=/(^|\/)(fixtures?|__fixtures__|testdata|test_data|data|snapshots?|__snapshots__|mocks?|__mocks__)\//i;function t2(e,t){if(iAe.test(t))return!1;let n=eo(e,t);return n?Ep(n,t):cc(t)}function oAe(e,t){let n=[],r=new Set(e.map(a=>a.file).filter(a=>t.modified.includes(a)&&t2(t.repo,a))),s=new Set([...t.maintained??[],...r]);for(let a of t.modified)/(^|\/)__snapshots__\/[^/]+\.snap$/.test(a)&&s.has(Ow(a))||(s.has(a)?t2(t.repo,a)||n.push(`${a} is listed in "maintained" but is not a test file \u2014 source and fixtures stay as they are`):n.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)&&n.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=cs.resolve(t.repo,a.file);if(!wn(t.repo,a.file)){n.push(`${a.file} is outside the repository \u2014 write only new test files, in the repository`);continue}if(!Cp.existsSync(c)){n.push(`${a.file} does not exist`);continue}!t.added.includes(a.file)&&!r.has(a.file)&&n.push(`${a.file} is not a new file \u2014 write only new test files`);let u=ar(t.repo,a.file),l=to(a.framework)||u!==void 0,d=to(a.framework)?a.framework:u?.framework??eo(t.repo,a.file);if(l)to(a.framework)&&!Ep(a.framework,a.file)&&n.push(`${a.file} is not named the way ${a.framework} discovers tests \u2014 follow the repository's test naming`),u?.framework!==a.framework&&n.push(`${a.file} is ${a.framework}, but the repository runs it with ${u?.framework??"no test framework we can run"} \u2014 use the framework the repository already uses`),u?.wrappedBy&&(a.run?n.push(...Ho(t.repo,a.run).map(w=>`${a.file}: its run ${w}`)):n.push(`${a.file}: the repository runs its ${u.framework} tests with \`${u.wrappedBy}\`, not ${u.framework} itself \u2014 give "run": the repository's own command for only these tests, writing JUnit XML to {junit}`));else{a.run?n.push(...Ho(t.repo,a.run).map(C=>`${a.file}: its run ${C}`)):n.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 w=d?t.testAffixes?.get(d):void 0;w?.size&&!w.has(PA(a.file))&&n.push(`${a.file} is not named like the repository's existing ${d} tests (${[...w].join(", ")}) \u2014 follow the repository's test naming`)}let h=cs.dirname(a.file).split(cs.sep).join("/")||".",A=d&&t.testDirs.get(d)||new Set,m=t.placedDir;m!==void 0?m!=="."&&h!==m&&!h.startsWith(`${m}/`)&&n.push(`${a.file} is not in ${m}, where the Target puts unit tests for this repository`):aAe(t.repo,h,A,a.file)||n.push(`${a.file} is not beside any existing ${l?a.framework:`${a.framework} (${d})`} test (${[...A].join(", ")||"none found"}) \u2014 place each test beside the existing tests`);let y=Cp.readFileSync(c,"utf-8"),E=tAe(y);for(let w of a.names)rAe(a.framework,y,E,w)||n.push(`${a.file} declares test "${w}", which is not in the file \u2014 names lists the test functions`);for(let w of Lw(y))n.push(`${a.file} uses ${w} \u2014 a unit test runs in one process: no network, no running app; mock with the framework's own tools inside the test`)}return n}function aAe(e,t,n,r){if(n.has(t))return!0;let s=o=>{let a=o.split("/"),c=a.findIndex(u=>cAe.test(u));return c<0?void 0:a.slice(0,c+1).join("/")},i=s(t);if(i&&[...n].some(o=>s(o)===i))return!0;if([...n].some(o=>s(o)===void 0)){let o=cs.extname(r);try{return Cp.readdirSync(cs.join(e,t)).some(a=>cs.extname(a)===o&&!cc(a))}catch{return!1}}return!1}var cAe=/^(tests?|spec|specs|__tests__|e2e|testing|integration_tests?)$/i;function uAe(e,t){return i2(e,t,n=>cs.dirname(n).split(cs.sep).join("/")||".")}function lAe(e,t){return i2(e,t,PA)}function i2(e,t,n){let r=new Map;for(let s of t){let i=eo(e,s);!i||!to(i)&&!cc(s)||(r.has(i)||r.set(i,new Set),r.get(i).add(n(s)))}return r}function lc(e){return Y(e,"triage.json")?.decision!=="targeted_unit"?[]:(Y(e,"analyze.json")?.findings??[]).filter(n=>n.status!=="refuted"&&n.status!=="latent").map(n=>({id:n.id,claim:n.claim,file:n.file,line:n.line,repository:n.repository,severity:n.severity,...n.conflictsWith?.length?{conflictsWith:n.conflictsWith}:{}}))}function no(e){return Y(e,"triage.json")?.decision!=="targeted_unit"?[]:Ka(Y(e,"plan.json")?.journeys).filter(t=>t.kind==="in-process")}function MA(e){let t=Y(e,"triage.json");return[...new Set((t?.plan??[]).filter(n=>n.mechanism==="new_unit").map(n=>n.behaviorId))]}var o2={name:"generate-unit-grounded",verify(e,t){let{output:n}=Lu(t);if(!n)return{name:this.name,passed:!0};let r=e.prepared,s=no(e),i=Y(e,"plan.json"),o=sAe(n,MA(e),lc(e).map(c=>c.id),s.map(c=>c.id),i?new Set(AA(i).keys()):new Set);s.length&&o.push(...VE(zf(s,{journeys:n.journeys,tests:n.tests,notWritten:(n.journeysNotWritten??[]).map(c=>({case:c.journey,reason:c.missing}))},Ds(e.inputs.repositoryPath,e.inputs.relatedRepos??[]))));for(let c of n.tests){let u=Bs(e.inputs,c.repository);"error"in u&&o.push(`${c.file}: ${u.error}`)}for(let c of ye(e.inputs).filter(u=>u.writable)){let u=n.tests.filter(y=>Xe(e.inputs,y.repository)?.path===c.path),l=(n.maintained??[]).filter(y=>Xe(e.inputs,y.repository)?.path===c.path).map(y=>y.file),d=r?.checkouts?.[c.slug],{modified:h,added:A}=vQ(c.path),m=xe(e.inputs,c.slug);o.push(...oAe(u,{repo:c.path,testDirs:uAe(c.path,d?.existingTests??[]),testAffixes:lAe(c.path,d?.existingTests??[]),modified:h,added:A,maintained:l,addedBefore:d?.addedBefore,placedDir:ja(e.inputs,c.slug,"unit")}).map(y=>`${m}${y}`))}let a=(n.maintained??[]).filter(c=>c.change==="updated");if(a.length){let c=Y(e,"plan.json"),u=Y(e,"analyze.json"),l=new Set([...(c?.requirements??[]).flatMap(A=>[A.id,...(A.clauses??[]).map(m=>m.id)]),...(u?.behaviors??[]).map(A=>A.id),...(u?.requirements??[]).map(A=>A.id)]),d=ct(e)?.repository.baseBranch??e.inputs.baseBranch??"origin/main",h=SQ([{path:e.inputs.repositoryPath,base:d,related:!1},...(e.inputs.relatedRepos??[]).map(A=>({path:A.path,base:A.base??"origin/main",related:!0}))]);o.push(...Mw(a,{requirementIds:l,changedLines:h,defectLines:new Map}))}return o.length?{...se(this.name,o),repairable:!0}:{name:this.name,passed:!0}}};function kQ(e,t){if(!t.some(r=>r.gates.some(s=>!s.passed&&/secrets|checkout-intact/.test(s.name))))for(let r of[...t].reverse()){if(!r.session)continue;let{output:s,errors:i}=Lu(r.session);if(s)return Fe(e,"generate-unit",s,i)}}function RQ(e,t){let{output:n,errors:r}=Lu(t);return Fe(e,"generate-unit",n,r)}var jw="native-run.json",Wo=e=>Y(e,jw),c2="no selected unit test ran";function Gw(e){if(e.results.some(r=>r.status==="Pass"||r.status==="Fail"))return;let t=new Set([...e.results.map(r=>`${r.file}\0${r.selectedName??r.name}`),...e.notRun.map(r=>`${r.file}\0${r.name??""}`)]).size;if(!t)return;let n=e.notRun.length?[...new Set(e.notRun.map(r=>r.reason))]:["every test that reported was skipped"];return`${c2} (${t} selected): ${n.slice(0,3).join("; ").slice(0,600)}`}var BQ=e=>e.origin==="written"||!!e.written;function u2(e,t){let n=e.inputs?.unitPath==="write"&&t.decision==="targeted_unit",r=t.plan.filter(i=>i.mechanism==="existing_unit"||i.mechanism==="new_unit"&&!n),s=n?dAe(e,t.plan.filter(i=>i.mechanism==="new_unit")):[];return r.length===0?s:[...new Set([...s,...pAe(e,r)])]}function dAe(e,t){if(!t.length)return[];let n=Y(e,"write.json");if(!n)return["the planned unit tests were not written (write did not finish)"];let r=new Set((Wo(e)?.results??[]).filter(i=>BQ(i)&&!i.fromFile&&(i.status==="Pass"||i.status==="Fail")).flatMap(i=>i.behaviorIds)),s=[];for(let i of t){let o=n.tests.filter(c=>c.covers.includes(i.behaviorId)),a=o.some(c=>c.result.cases.some(u=>u.case===i.behaviorId&&(u.status==="pass"||u.status==="fail"))||!c.result.cases.length&&c.result.exit!==null&&c.covers.every(u=>u===i.behaviorId));o.length?!r.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 pAe(e,t){let n=e.state.stages["native-run"],r=Wo(e),s=n?.status==="failed"&&!!n.reason?.includes(c2);if(n?.status!=="passed"&&!s||!r)return[`the planned unit tests did not run${n?.reason?` (${n.reason})`:n?` (${n.status})`:""}`];let i=r.notRun.filter(d=>d.origin!=="written").map(d=>`${d.file}${d.name?`::${d.name}`:""} did not run: ${d.reason}`),o=(d,h)=>new Set(r.results.filter(A=>A.origin===d&&(A.status==="Pass"||A.status==="Fail")===h).flatMap(A=>A.behaviorIds)),a={existing:o("existing",!0),generated:o("generated",!0)},c={existing:o("existing",!1),generated:o("generated",!1)},u=Y(e,Zt),l=new Set((u?.tests??[]).flatMap(d=>d.covers));for(let d of t)if(d.mechanism==="new_unit"&&!l.has(d.behaviorId))i.push(`${d.behaviorId}: no new unit test was written${d.covers?` for ${d.covers}`:""}`);else{let h=d.mechanism==="new_unit"?"generated":"existing",A=h==="generated"?"new":"existing";a[h].has(d.behaviorId)||i.push(c[h].has(d.behaviorId)?`${d.behaviorId}: every ${A} unit test for it was skipped`:`${d.behaviorId}: no ${A} unit test for it produced a result`)}return[...new Set(i)]}var ju=j(require("fs")),Pn=j(require("path"));var hAe=/"(?:@testing-library\/(?:react|vue|svelte|angular|preact|dom|user-event)|jsdom|happy-dom|@vue\/test-utils|enzyme|react-test-renderer)"\s*:/,qw=e=>{try{return ju.statSync(e).size<1e6?ju.readFileSync(e,"utf-8"):""}catch{return""}};function QQ(e,t){let n=Pn.resolve(e),r=Pn.dirname(Pn.resolve(n,t));if(Pn.relative(n,r).startsWith(".."))return!1;for(;;){if(hAe.test(qw(Pn.join(r,"package.json"))))return!0;if(r===n)return!1;r=Pn.dirname(r)}}var TQ=/(^|\/)(e2e|cypress|playwright|selenium)\/|\.(cy|e2e)\.[cm]?[jt]sx?$/i,f2=/["']@playwright\/test["']|["']cypress["']|\bcy\.(?:visit|request)\(|\b(?:from|import)\s+selenium\b|\bfrom\s+playwright\b|\bwebdriverio\b|\bpuppeteer\b|\bApplicationSystemTestCase\b/,A2=/\b(?:Static|Channels)?LiveServerTestCase\b|\blive_server\b/,fAe=/["']@skyramp\/skyramp["']|\b(?:from|import)\s+skyramp\b/,AAe=/https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0)[:/]|\b(?:BASE_URL|API_URL|APP_URL|SUT_URL|baseURL|base_url)\b/,gAe=/\b(?:requests|httpx|aiohttp|urllib|axios|fetch|got|superagent|HttpClient|RestAssured|Faraday|Net::HTTP)\b/,mAe=/\b(?:jest\.mock|vi\.mock|nock|msw|setupServer|responses|respx|requests_mock|httpretty|fetchMock|fetch-mock|MockAdapter|WebMock|mock\.patch)\b/,yAe=/\b(?:BASE_URL|API_URL|APP_URL|SUT_URL)\b/;function xQ(e,t){let n=t.split("::")[0].trim().replace(/\\/g,"/"),r=qw(Pn.resolve(e,n));if(!(A2.test(r)&&!yAe.test(r))){if(f2.test(r)||TQ.test(n))return"a browser test of the running app";if(fAe.test(r)||AAe.test(r)&&gAe.test(r)&&!mAe.test(r))return"a test that calls the running app"}}function g2(e,t){let n=t.split("::")[0].trim().replace(/\\/g,"/"),r=qw(Pn.resolve(e,n));return f2.test(r)||TQ.test(n)?"ui":xQ(e,n)?"integration":r&&ar(e,n)?"unit":void 0}var l2=String.raw`\b(?:real browser|browser|javascript|js|htmx|client-side)\b`,d2=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`,EAe=[new RegExp(`${l2}[^.;\\n]{0,100}(?:${d2})`,"i"),new RegExp(`(?:${d2})[^.;\\n]{0,100}${l2}`,"i")];function wAe(e){return e.filter(t=>!!t?.trim()&&EAe.some(n=>n.test(t))).map(t=>t.trim().slice(0,160))}var CAe=/\b(?:from|import)\s+(?:selenium|playwright)\b/,p2={depth:6,files:2e3},m2=e=>{if(!e.endsWith(".py"))return!1;let t=qw(e);return A2.test(t)&&CAe.test(t)};function IAe(e){let t=p2.files,n=(r,s)=>{let i;try{i=ju.readdirSync(r,{withFileTypes:!0})}catch{return!1}for(let o of i){if(--t<0)return!1;let a=Pn.join(r,o.name);if(o.isFile()&&m2(a)||o.isDirectory()&&s>0&&!o.name.startsWith(".")&&o.name!=="node_modules"&&n(a,s-1))return!0}return!1};return n(e,p2.depth)}function h2(e,t){let n=Pn.resolve(e),r=t.split("::")[0].trim().replace(/\\/g,"/").replace(/\/+$/,""),s=Pn.resolve(n,r);if(!r||Pn.relative(n,s).startsWith(".."))return!1;let i;try{i=ju.statSync(s).isDirectory()}catch{return!1}return(i?IAe(s):m2(s))?!0:TQ.test(`${r}${i?"/":""}`)?!1:QQ(n,i?Pn.join(r,"_"):r)}var bAe=/\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,SAe=/\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 vAe(e){let t=e.filter(n=>!!n?.trim());if(!(!t.length||t.some(n=>bAe.test(n))))return t.every(n=>SAe.test(n))?t[0].trim().slice(0,160):void 0}function kAe(e){return new Set(e.filter(t=>t.mechanism==="existing_unit"||t.mechanism==="new_unit").map(t=>t.behaviorId))}function y2(e,t){let n=kAe(t);return e.action==="verify"&&!!e.clauses?.length&&e.clauses.every(r=>n.has(r))}function E2(e,t,n){return!e?.maintenance||!t?new Set:new Set(e.maintenance.filter(r=>y2(r,t.plan)).filter(r=>{let{root:s,rel:i}=n(r.test);return xQ(s,i)&&!t.gaps.some(o=>o.missing.includes(i)||o.missing.includes(r.test))}).map(r=>r.test))}var RAe=e=>e.trim().replace(/:\d+(?:-\d+)?$/,"");function BAe(e,t){let n=RAe(e);return n?t.some(r=>r===n||r.endsWith(`/${n}`)||n.endsWith(`/${r}`)||n.endsWith("/")&&(r.startsWith(n)||r.includes(`/${n}`))):!1}function Vw(e,t,n){let r=new Set;for(let s of e.requirements)for(let i of s.clauses)s.source!=="could-break"&&(n||!i.code?.trim()||BAe(i.code,t))&&r.add(i.id);return r}var w2=/\b[A-Z][A-Za-z0-9-]*\d+[a-z]\b/g;function C2(e,t,n){let r=e.behaviorId?.trim()?[e.behaviorId.trim()]:e.missing.match(w2)??[];return r.length>0&&r.every(s=>t.has(s)&&!n.has(s))}var QAe=new Set(["targeted_unit","existing_evidence_sufficient"]);function I2(e,t){let n=e.triage?.decision;if(!n||!QAe.has(n))return[];let r=[],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 u=c.steps.flatMap(l=>l.clauses??[]);return!!t.own&&u.length>0&&!u.some(l=>i(l)&&!o.has(l))};for(let c of e.journeys??[]){if(t.runtimePossible&&c.kind!=="in-process"&&a(c)){r.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"&&r.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"){r.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:u,rel:l}=t.locate(c.testFile);if(a(c)&&!QQ(u,l)){r.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}QQ(u,l)||r.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=wAe([s.rationale,...s.gaps.filter(u=>!u.behaviorId||i(u.behaviorId)).map(u=>u.missing),...(e.notInJourney??[]).filter(u=>i(u.clause)).map(u=>u.why),...e.requirements.flatMap(u=>u.clauses.filter(l=>i(l.id)).map(l=>l.skip))]).filter(u=>{let l=u.match(w2)??[];return!(l.length&&l.every(d=>!i(d)))});for(let u of c)r.push(`the plan says "${u}": 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:u,rel:l}=t.locate(c.test),d=xQ(u,l);if(!d||t.runtimePossible&&y2(c,s.plan))continue;let h=()=>s.gaps.some(A=>A.missing.includes(l)||A.missing.includes(c.test));if(t.own&&c.clauses?.length&&!c.clauses.some(A=>i(A))){h()||r.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){h()||r.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}r.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 u=c.needsApp==="browser"?"a browser":"the running app's API";if(!t.runtimePossible){if(s.gaps.some(l=>l.behaviorId===c.id||l.missing.includes(c.id)))continue;r.push(`finding ${c.id} needs ${u} 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}r.push(`finding ${c.id} needs ${u} 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 r.push(...TAe(e,t)),r}function TAe(e,t){let n=[],r=e.triage?.gaps??[],s=i=>r.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(l=>l.clause===i.id).map(l=>l.steps)],a=vAe(o);if(t.own&&!t.own.has(i.id)){let l=i.browserHarness?.trim(),d=l?t.locate(l):void 0;if(d&&!a&&h2(d.root,d.rel)||s(i.id))continue;n.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){n.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:l,rel:d}=t.locate(c);if(h2(l,d))continue}let u=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(r.some(l=>l.behaviorId===i.id||l.missing.includes(i.id)))continue;n.push(`clause ${i.id} is browser-only, ${u}, 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}n.push(`clause ${i.id} is browser-only and ${u}: 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 n}var xAe="triage.json",NAe=new Set(["existing_evidence","unaffected","existing_unit","new_unit","runtime"]),DAe={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 Sp(e){return e.some(t=>iB.has(t.mechanism))}function PAe(e){let{value:t,error:n}=ft(e);if(n)return{errors:[n]};let{value:r,errors:s}=_t(Pu,t);return s.length?{errors:s}:{triage:r,errors:[]}}function NQ(e){return PAe(e.stdout)}var b2=yn("triage-schema",(e,t)=>NQ(t)),Hw=e=>e.trim().replace(/\s+/g," ");function S2(e,t){let n=[],r=new Set(t.behaviorIds),s=new Map(t.ci.map(y=>[y.id,y])),i=new Map(e.evidence.map(y=>[y.id,y])),o=new Set(e.plan.map(y=>y.mechanism)),a=e.decision==="blocked_preflight",c=new Set;for(let y of e.evidence)(c.has(y.id)||s.has(y.id))&&n.push(`evidence id "${y.id}" is used twice (every id is unique, and ci-<n> ids belong to the CI results)`),c.add(y.id);let u=e.outOfScope??[];for(let y of[...e.plan,...e.gaps,...u])y.behaviorId!==void 0&&!r.has(y.behaviorId)&&n.push(`behaviorId "${y.behaviorId}" is not one of analyze's behaviors (${[...r].join(", ")||"none"})`);if(!a){let y=new Set([...e.plan.map(E=>E.behaviorId),...e.gaps.map(E=>E.behaviorId??""),...u.map(E=>E.behaviorId)]);for(let E of r)y.has(E)||n.push(`behavior "${E}" 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 l=new Set([...e.plan.map(y=>y.behaviorId),...e.gaps.map(y=>y.behaviorId??"")]);for(let y of u){let E=`outOfScope "${y.behaviorId}"`;l.has(y.behaviorId)&&n.push(`${E} is also planned or listed in gaps: a behavior out of scope plans nothing`);let w=b=>t.sources.some(I=>bp.existsSync(Ip.join(I.path,b)))?b:t.changedFiles.map(I=>I.path).find(I=>I.endsWith(`/${b}`)),C=b=>{let I=t.sources.map(S=>S.path).find(S=>bp.existsSync(Ip.join(S,b)));return I?bp.readFileSync(Ip.join(I,b),"utf-8").split(`
229
- `).length:0},k=[...y.reason.matchAll(/([\w./@+-]+\.[A-Za-z]\w*):(\d+)/g)].flatMap(b=>{let I=w(b[1].replace(/^\.\//,"")),S=Number(b[2]);return I&&S>=1&&S<=C(I)?[`${I}:${S}`]:[]});k.length===0?n.push(`${E}: cite the unchanged line that decides it (path:line of a file in the repository) in its reason`):t.changedRanges&&k.every(b=>Dj(b,t.changedRanges))&&n.push(`${E} cites ${k.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(E=>E==="existing_evidence"||E==="unaffected")&&e.gaps.length===0||n.push(`existing_evidence_sufficient means every behavior in scope is established by existing evidence, with no gaps \u2014 this plan also needs ${[...o].filter(E=>E!=="existing_evidence"&&E!=="unaffected").join(", ")||"the evidence named in gaps"}`);break}case"targeted_unit":(![...o].some(y=>Sq.has(y))||Sp(e.plan))&&n.push(`targeted_unit plans unit tests and nothing that needs a running app \u2014 this plan has ${[...o].join(", ")||"nothing"}`);break;case"runtime_required":Sp(e.plan)||n.push(`runtime_required marks at least one behavior runtime \u2014 this plan has ${[...o].join(", ")||"nothing"}`),o.has("new_unit")&&n.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&&n.push('blocked_preflight names the changed file the failure is in, under "blocked"'),!a&&e.blocked&&n.push('"blocked" is only for blocked_preflight'),a&&e.plan.length>0&&n.push("blocked_preflight plans nothing: a change that cannot meet its prerequisites is not validated further");let d=(y,E)=>{let w=Iu(t.sources,y);return!!w&&Id(t.changedFiles,w.slug,E)},h=(y,E)=>bp.existsSync(Ip.join(y,E));e.blocked&&!d(e.blocked.repository,e.blocked.file)&&n.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 y of e.plan){let E=`plan item for "${y.behaviorId}" (${y.mechanism})`;for(let w of y.evidenceIds)!s.has(w)&&!i.has(w)&&n.push(`${E} cites "${w}", which is neither a ci-<n> result nor an evidence id`);if(y.mechanism==="unaffected"){let w=t.behaviorFiles?.get(y.behaviorId),C=/([\w./-]+\.[\w]+):\d+/.exec(y.covers??"")?.[1];if(w&&d(w.repository,w.file)){let k=`${kR(t.sources,w.repository)}${w.file}`;n.push(`${E}: ${k} is changed by this PR, so the change can reach this behavior \u2014 unaffected is never for a behavior in a changed file`)}(!C||!t.sources.some(k=>h(k.path,C)))&&n.push(`${E}: 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(y.mechanism==="existing_evidence"){let w=y.evidenceIds.filter(b=>{let I=s.get(b);if(I)return I.status==="accepted"&&I.kind!=="code_review";let S=i.get(b);return S?.source==="testbot"&&S.outcome==="passed"&&S.kind!=="code_review"}),C=y.evidenceIds.map(b=>s.has(b)?`${b} is ${s.get(b).status}`:`${b} is ${i.get(b)?.outcome??"unknown"}`);w.length===0&&n.push(`${E}: only accepted ci-<n> items and checks you ran that passed can establish a behavior${C.length?` \u2014 ${C.join(", ")}`:" \u2014 it cites nothing"}`),w.length===0&&y.evidenceIds.some(b=>s.get(b)?.kind==="code_review"||i.get(b)?.kind==="code_review")&&n.push(`${E}: AI review is advisory \u2014 it cannot establish a behavior on its own`)}y.mechanism==="existing_unit"&&y.evidenceIds.map(C=>i.get(C)).filter(C=>C?.source==="repository"&&(C.tests?.length??0)>0).length===0&&n.push(`${E}: existing_unit names the repository evidence listing the tests to run`),(y.mechanism==="new_unit"||iB.has(y.mechanism))&&!y.covers?.trim()&&n.push(`${E}: say under "covers" the missing evidence this obtains`)}let A=t.ranCommands.map(Hw),m=new Set(e.plan.filter(y=>y.mechanism==="existing_evidence").flatMap(y=>y.evidenceIds));for(let y of e.evidence){if(y.source==="repository"){if(!y.tests?.length){n.push(`evidence "${y.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 E=e.plan.some(I=>I.mechanism==="existing_unit"&&I.evidenceIds.includes(y.id)),w=e.decision==="existing_evidence_sufficient";!(E||w&&m.has(y.id))&&e.decision!=="blocked_preflight"&&n.push(w?`evidence "${y.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 "${y.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 k=Iu(t.sources,y.repository);k||n.push(`evidence "${y.id}" names ${y.repository}, which is not a repository of this run (${t.sources.map(I=>I.slug).join(", ")}) \u2014 name the owner/repo the tests live in`);let b=t.sources.length>1?'; a test in another checkout: name its "repository"':"";for(let I of y.tests??[]){let S=I.split("::")[0];if(k&&!h(k.path,S))n.push(`evidence "${y.id}" names ${S}, which does not exist in ${k.slug} (tests are repo-relative paths${b})`);else if(k&&E&&!y.run){let B=ar(k.path,S);B?B.wrappedBy&&n.push(`evidence "${y.id}" runs ${S}, which the repository runs with \`${B.wrappedBy}\`, not ${B.framework} itself \u2014 give "run": the repository's own command for only these tests, writing JUnit XML to {junit}`):n.push(`evidence "${y.id}" runs ${S}, 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}`)}}k&&E&&y.run&&n.push(...Ho(k.path,y.run).map(I=>`evidence "${y.id}": its run ${I}`))}if(y.source==="testbot"&&m.has(y.id)&&!v2(y.command,A)){let E=Hw(y.command??"");n.push(`evidence "${y.id}" establishes a behavior but is a check this session never ran${E?` ("${E.slice(0,80)}")`:""} \u2014 give the exact command you ran`)}}return n}function v2(e,t){let n=s=>s.replace(/\\/g,""),r=n(Hw(e??""));return!!r&&t.map(n).some(s=>s===r||s.includes(r)||r.includes(s))}function FAe(e,t){let n=t.map(Hw);return e.evidence.filter(r=>r.source!=="testbot"||v2(r.command,n))}function Jw(e,t="triage",n){let r=n??Y(e,"analyze.json")?.behaviors;if(!r)return;let s=Y(e,hE),i=ye(e.inputs);return{behaviorIds:r.map(o=>o.id),behaviorFiles:new Map(r.map(o=>[o.id,{repository:o.repository,file:o.evidence.split(":")[0]}])),ci:s?.items??[],changedFiles:Rs(ct(e)??{changedFiles:[]},Mt(e.inputs).slug),sources:i,ranCommands:jG(e.outputsDir,t).flatMap(LE),changedRanges:Nj(e)}}var k2={name:"triage-grounded",verify(e,t){let{triage:n}=NQ(t);if(!n)return{name:this.name,passed:!0};let r=Jw(e);if(!r)return se(this.name,["analyze.json is missing \u2014 nothing to ground the decision against"],{fatal:!0});let s=S2(n,r);return s.length?se(this.name,s):{name:this.name,passed:!0}}};function R2(e,t,n){return{...t,evidence:FAe(t,n),sutRequired:Sp(t.plan),budgetMinutes:e.inputs.budgetMinutes,ciEvidence:Y(e,hE)?.items??[]}}function B2(e,t){let{triage:n,errors:r}=NQ(t),s=Jw(e)?.ranCommands??[];return Fe(e,"triage",n&&R2(e,n,s),r)}function Q2(e,t){let n=new Set(t),r=e.outOfScope?.filter(i=>n.has(i.behaviorId)),s=e.gaps.map(i=>i.behaviorId===void 0||n.has(i.behaviorId)?i:{missing:`${i.behaviorId}: ${i.missing}`});return{...e,gaps:s,...e.outOfScope?{outOfScope:r}:{}}}function DQ(e,t,n,r){if(!t)return['save the validation triage decision as "triage" in the plan'];let s=Jw(e,"plan",r);if(!s)return["analyze.json is missing \u2014 nothing to ground the decision against"];let i=Q2(t,s.behaviorIds),o=S2(i,s);return n&&!Sp(i.plan)&&o.push(`the plan brought the app up, though its decision (${i.decision}) needs no running application`),o}function PQ(e,t,n,r){if(!t)return["the plan made no validation triage decision"];let s=DQ(e,t,n,r);return s.length?[`the plan's validation triage does not hold: ${s.join("; ")}`]:[]}function T2(e,t){let n=Jw(e,"plan"),r=Q2(t,n?.behaviorIds??[]);return Fe(e,"triage",R2(e,r,n?.ranCommands??[]),[])}function x2(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 FQ(e,t=Ai(e)){let n=Y(e,"plan.json"),r=ct(e);if(!t?.gaps.length||!n?.requirements?.length||!r)return[];let s=Rs(r,"").map(a=>a.path),i=Vw(n,s,Wf(s).length>0),o=new Set(n.requirements.flatMap(a=>a.clauses.map(c=>c.id)));return t.gaps.filter(a=>C2(a,o,i))}function Ai(e){if(x2(e)?.status==="passed")return ji(Ip.join(e.outputsDir,xAe))}function Xt(e){return e.inputs?.unitPath==="write"&&Ai(e)?.decision==="targeted_unit"}function _Ae(e){let t=Ai(e);if(!t?.sutRequired||Xt(e))return!1;let n=new Set(t.plan.filter(r=>r.mechanism==="runtime").map(r=>r.behaviorId));for(let r of Y(e,"plan.json")?.cases??[])r.clause&&n.has(r.clause)&&n.add(r.id);return(Y(e,"adapt.json")?.items??[]).some(r=>r.reran?.tests?.length?r.reran.tests.some(s=>s.status==="pass"&&n.has(s.case)):r.reran?.exit===0&&(r.covers??[]).some(s=>n.has(s)))}function Ww(e){return Y(e,"deploy.json")?.outcome==="bringup-failed"&&_Ae(e)}function vp(e){return tG(OR(e.inputs,Y(e,`${un}.json`),Ai(e)?.sutRequired))}var L_e=new Set(["deploy","recommend","generate","generate-ui","adapt","generate-unit","native-run","finalize","deliver"]);var MAe=/run budget exhausted/;function _Q(e,t){let n=x2(e);if(!n)return;let r=Ai(e);if(!r)return{sufficiency:"insufficient",rationale:"Validation triage did not complete, so nothing established what evidence this change needs.",gaps:[`validation triage did not complete (${n.reason??n.status})`],acceptedEvidence:[],actionRequired:[]};let s=new Set(FQ(e,r)),i=r.gaps.filter(y=>!s.has(y)).map(y=>y.behaviorId?`${y.behaviorId}: ${y.missing}`:y.missing),o=new Set;for(let y of r.plan)NAe.has(y.mechanism)||i.push(`${y.behaviorId}: ${DAe[y.mechanism]} is not available in this run${y.covers?` (${y.covers})`:""}`);r.blocked&&i.push(`the change does not meet a prerequisite: ${r.blocked.reason} (${r.blocked.file})`),i.push(...u2(e,r));let a=r.sutRequired?Od(e):[],c=r.sutRequired?QE(e.inputs?.sharedEnvironment):[],u=!!e.inputs?.appRunning;i.push(...a.map(y=>sG(y,u)),...c.map(y=>nG(y,u))),(a.length||c.length)&&o.add("sut_revision_mismatch");let l=TE(e);i.push(...l.map(iG));let d=r.sutRequired?MG(e):[];if(i.push(...d),(l.length||d.length)&&o.add("isolation_unavailable"),r.sutRequired&&!jf(e)&&!Ww(e)){let y=e.state.stages.deploy;i.push(`the running application was needed and was not available${y?.reason?` (${y.reason})`:""}`),o.add("deployment_review")}else t.some(y=>y.kind==="tests-not-executed")&&i.push("the planned tests were written but not run");let h=Object.entries(e.state.stages).filter(([,y])=>y&&MAe.test(y.reason??"")).map(([y])=>y);h.length&&i.push(`the execution budget ran out before ${h.join(", ")} finished`);let A=new Set(r.plan.filter(y=>y.mechanism==="existing_evidence").flatMap(y=>y.evidenceIds)),m=r.ciEvidence.filter(y=>y.status==="accepted"&&A.has(y.id)).map(y=>({kind:y.kind,repository:y.repository,revision:y.revision,reference:y.reference,summary:y.summary}));return{sufficiency:i.length?"insufficient":"sufficient",rationale:r.rationale,gaps:i,acceptedEvidence:m,actionRequired:[...o]}}tr();tr();var zw=j(require("fs")),N2=j(require("path"));function D2(e){if(!zw.existsSync(e))return[];let t=[],n=r=>{let s;try{s=zw.readdirSync(r,{withFileTypes:!0})}catch(i){pt(`Skipping unreadable video dir ${r}: ${i instanceof Error?i.message:String(i)}`);return}for(let i of s){let o=N2.join(r,i.name);i.isDirectory()?n(o):i.isFile()&&i.name.endsWith(".webm")&&t.push(o)}};return n(e),t}var F2=600,Kw=300;function P2(e){return typeof e=="string"?e.trim():e instanceof Buffer?e.toString("utf-8").trim():""}function $Ae(e){let t=e,n=(typeof t?.message=="string"?t.message:String(e)).trim(),r=[P2(t?.stderr),P2(t?.stdout)].filter(Boolean);return r.length?[n.split(`
229
+ `).length:0},k=[...y.reason.matchAll(/([\w./@+-]+\.[A-Za-z]\w*):(\d+)/g)].flatMap(b=>{let I=w(b[1].replace(/^\.\//,"")),S=Number(b[2]);return I&&S>=1&&S<=C(I)?[`${I}:${S}`]:[]});k.length===0?n.push(`${E}: cite the unchanged line that decides it (path:line of a file in the repository) in its reason`):t.changedRanges&&k.every(b=>Dj(b,t.changedRanges))&&n.push(`${E} cites ${k.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(E=>E==="existing_evidence"||E==="unaffected")&&e.gaps.length===0||n.push(`existing_evidence_sufficient means every behavior in scope is established by existing evidence, with no gaps \u2014 this plan also needs ${[...o].filter(E=>E!=="existing_evidence"&&E!=="unaffected").join(", ")||"the evidence named in gaps"}`);break}case"targeted_unit":(![...o].some(y=>Sq.has(y))||Sp(e.plan))&&n.push(`targeted_unit plans unit tests and nothing that needs a running app \u2014 this plan has ${[...o].join(", ")||"nothing"}`);break;case"runtime_required":Sp(e.plan)||n.push(`runtime_required marks at least one behavior runtime \u2014 this plan has ${[...o].join(", ")||"nothing"}`),o.has("new_unit")&&n.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&&n.push('blocked_preflight names the changed file the failure is in, under "blocked"'),!a&&e.blocked&&n.push('"blocked" is only for blocked_preflight'),a&&e.plan.length>0&&n.push("blocked_preflight plans nothing: a change that cannot meet its prerequisites is not validated further");let d=(y,E)=>{let w=Iu(t.sources,y);return!!w&&Id(t.changedFiles,w.slug,E)},h=(y,E)=>bp.existsSync(Ip.join(y,E));e.blocked&&!d(e.blocked.repository,e.blocked.file)&&n.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 y of e.plan){let E=`plan item for "${y.behaviorId}" (${y.mechanism})`;for(let w of y.evidenceIds)!s.has(w)&&!i.has(w)&&n.push(`${E} cites "${w}", which is neither a ci-<n> result nor an evidence id`);if(y.mechanism==="unaffected"){let w=t.behaviorFiles?.get(y.behaviorId),C=/([\w./-]+\.[\w]+):\d+/.exec(y.covers??"")?.[1];if(w&&d(w.repository,w.file)){let k=`${kR(t.sources,w.repository)}${w.file}`;n.push(`${E}: ${k} is changed by this PR, so the change can reach this behavior \u2014 unaffected is never for a behavior in a changed file`)}(!C||!t.sources.some(k=>h(k.path,C)))&&n.push(`${E}: 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(y.mechanism==="existing_evidence"){let w=y.evidenceIds.filter(b=>{let I=s.get(b);if(I)return I.status==="accepted"&&I.kind!=="code_review";let S=i.get(b);return S?.source==="testbot"&&S.outcome==="passed"&&S.kind!=="code_review"}),C=y.evidenceIds.map(b=>s.has(b)?`${b} is ${s.get(b).status}`:`${b} is ${i.get(b)?.outcome??"unknown"}`);w.length===0&&n.push(`${E}: only accepted ci-<n> items and checks you ran that passed can establish a behavior${C.length?` \u2014 ${C.join(", ")}`:" \u2014 it cites nothing"}`),w.length===0&&y.evidenceIds.some(b=>s.get(b)?.kind==="code_review"||i.get(b)?.kind==="code_review")&&n.push(`${E}: AI review is advisory \u2014 it cannot establish a behavior on its own`)}y.mechanism==="existing_unit"&&y.evidenceIds.map(C=>i.get(C)).filter(C=>C?.source==="repository"&&(C.tests?.length??0)>0).length===0&&n.push(`${E}: existing_unit names the repository evidence listing the tests to run`),(y.mechanism==="new_unit"||iB.has(y.mechanism))&&!y.covers?.trim()&&n.push(`${E}: say under "covers" the missing evidence this obtains`)}let A=t.ranCommands.map(Hw),m=new Set(e.plan.filter(y=>y.mechanism==="existing_evidence").flatMap(y=>y.evidenceIds));for(let y of e.evidence){if(y.source==="repository"){if(!y.tests?.length){n.push(`evidence "${y.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 E=e.plan.some(I=>I.mechanism==="existing_unit"&&I.evidenceIds.includes(y.id)),w=e.decision==="existing_evidence_sufficient";!(E||w&&m.has(y.id))&&e.decision!=="blocked_preflight"&&n.push(w?`evidence "${y.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 "${y.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 k=Iu(t.sources,y.repository);k||n.push(`evidence "${y.id}" names ${y.repository}, which is not a repository of this run (${t.sources.map(I=>I.slug).join(", ")}) \u2014 name the owner/repo the tests live in`);let b=t.sources.length>1?'; a test in another checkout: name its "repository"':"";for(let I of y.tests??[]){let S=I.split("::")[0];if(k&&!h(k.path,S))n.push(`evidence "${y.id}" names ${S}, which does not exist in ${k.slug} (tests are repo-relative paths${b})`);else if(k&&E&&!y.run){let B=ar(k.path,S);B?B.wrappedBy&&n.push(`evidence "${y.id}" runs ${S}, which the repository runs with \`${B.wrappedBy}\`, not ${B.framework} itself \u2014 give "run": the repository's own command for only these tests, writing JUnit XML to {junit}`):n.push(`evidence "${y.id}" runs ${S}, 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}`)}}k&&E&&y.run&&n.push(...Ho(k.path,y.run).map(I=>`evidence "${y.id}": its run ${I}`))}if(y.source==="testbot"&&m.has(y.id)&&!v2(y.command,A)){let E=Hw(y.command??"");n.push(`evidence "${y.id}" establishes a behavior but is a check this session never ran${E?` ("${E.slice(0,80)}")`:""} \u2014 give the exact command you ran`)}}return n}function v2(e,t){let n=s=>s.replace(/\\/g,""),r=n(Hw(e??""));return!!r&&t.map(n).some(s=>s===r||s.includes(r)||r.includes(s))}function FAe(e,t){let n=t.map(Hw);return e.evidence.filter(r=>r.source!=="testbot"||v2(r.command,n))}function Jw(e,t="triage",n){let r=n??Y(e,"analyze.json")?.behaviors;if(!r)return;let s=Y(e,hE),i=ye(e.inputs);return{behaviorIds:r.map(o=>o.id),behaviorFiles:new Map(r.map(o=>[o.id,{repository:o.repository,file:o.evidence.split(":")[0]}])),ci:s?.items??[],changedFiles:Rs(ct(e)??{changedFiles:[]},Mt(e.inputs).slug),sources:i,ranCommands:jG(e.outputsDir,t).flatMap(LE),changedRanges:Nj(e)}}var k2={name:"triage-grounded",verify(e,t){let{triage:n}=NQ(t);if(!n)return{name:this.name,passed:!0};let r=Jw(e);if(!r)return se(this.name,["analyze.json is missing \u2014 nothing to ground the decision against"],{fatal:!0});let s=S2(n,r);return s.length?se(this.name,s):{name:this.name,passed:!0}}};function R2(e,t,n){return{...t,evidence:FAe(t,n),sutRequired:Sp(t.plan),budgetMinutes:e.inputs.budgetMinutes,ciEvidence:Y(e,hE)?.items??[]}}function B2(e,t){let{triage:n,errors:r}=NQ(t),s=Jw(e)?.ranCommands??[];return Fe(e,"triage",n&&R2(e,n,s),r)}function Q2(e,t){let n=new Set(t),r=e.outOfScope?.filter(i=>n.has(i.behaviorId)),s=e.gaps.map(i=>i.behaviorId===void 0||n.has(i.behaviorId)?i:{missing:`${i.behaviorId}: ${i.missing}`});return{...e,gaps:s,...e.outOfScope?{outOfScope:r}:{}}}function DQ(e,t,n,r){if(!t)return['save the validation triage decision as "triage" in the plan'];let s=Jw(e,"plan",r);if(!s)return["analyze.json is missing \u2014 nothing to ground the decision against"];let i=Q2(t,s.behaviorIds),o=S2(i,s);return n&&!Sp(i.plan)&&o.push(`the plan brought the app up, though its decision (${i.decision}) needs no running application`),o}function PQ(e,t,n,r){if(!t)return["the plan made no validation triage decision"];let s=DQ(e,t,n,r);return s.length?[`the plan's validation triage does not hold: ${s.join("; ")}`]:[]}function T2(e,t){let n=Jw(e,"plan"),r=Q2(t,n?.behaviorIds??[]);return Fe(e,"triage",R2(e,r,n?.ranCommands??[]),[])}function x2(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 FQ(e,t=Ai(e)){let n=Y(e,"plan.json"),r=ct(e);if(!t?.gaps.length||!n?.requirements?.length||!r)return[];let s=Rs(r,"").map(a=>a.path),i=Vw(n,s,Wf(s).length>0),o=new Set(n.requirements.flatMap(a=>a.clauses.map(c=>c.id)));return t.gaps.filter(a=>C2(a,o,i))}function Ai(e){if(x2(e)?.status==="passed")return ji(Ip.join(e.outputsDir,xAe))}function Xt(e){return e.inputs?.unitPath==="write"&&Ai(e)?.decision==="targeted_unit"}function _Ae(e){let t=Ai(e);if(!t?.sutRequired||Xt(e))return!1;let n=new Set(t.plan.filter(r=>r.mechanism==="runtime").map(r=>r.behaviorId));for(let r of Y(e,"plan.json")?.cases??[])r.clause&&n.has(r.clause)&&n.add(r.id);return(Y(e,"adapt.json")?.items??[]).some(r=>r.reran?.tests?.length?r.reran.tests.some(s=>s.status==="pass"&&n.has(s.case)):r.reran?.exit===0&&(r.covers??[]).some(s=>n.has(s)))}function Ww(e){return Y(e,"deploy.json")?.outcome==="bringup-failed"&&_Ae(e)}function vp(e){return tG(OR(e.inputs,Y(e,`${un}.json`),Ai(e)?.sutRequired))}var L_e=new Set(["deploy","recommend","generate","generate-ui","adapt","generate-unit","native-run","finalize","deliver"]);var MAe=/run budget exhausted/;function _Q(e,t){let n=x2(e);if(!n)return;let r=Ai(e);if(!r)return{sufficiency:"insufficient",rationale:"Validation triage did not complete, so nothing established what evidence this change needs.",gaps:[`validation triage did not complete (${n.reason??n.status})`],acceptedEvidence:[],actionRequired:[]};if(r.decision==="blocked_preflight"&&r.blocked)return{sufficiency:"insufficient",rationale:r.rationale,gaps:[`the change does not meet a prerequisite: ${r.blocked.reason} (${r.blocked.file})`],acceptedEvidence:[],actionRequired:[],blockedPreflight:r.blocked};let s=new Set(FQ(e,r)),i=r.gaps.filter(y=>!s.has(y)).map(y=>y.behaviorId?`${y.behaviorId}: ${y.missing}`:y.missing),o=new Set;for(let y of r.plan)NAe.has(y.mechanism)||i.push(`${y.behaviorId}: ${DAe[y.mechanism]} is not available in this run${y.covers?` (${y.covers})`:""}`);r.blocked&&i.push(`the change does not meet a prerequisite: ${r.blocked.reason} (${r.blocked.file})`),i.push(...u2(e,r));let a=r.sutRequired?Od(e):[],c=r.sutRequired?QE(e.inputs?.sharedEnvironment):[],u=!!e.inputs?.appRunning;i.push(...a.map(y=>sG(y,u)),...c.map(y=>nG(y,u))),(a.length||c.length)&&o.add("sut_revision_mismatch");let l=TE(e);i.push(...l.map(iG));let d=r.sutRequired?MG(e):[];if(i.push(...d),(l.length||d.length)&&o.add("isolation_unavailable"),r.sutRequired&&!jf(e)&&!Ww(e)){let y=e.state.stages.deploy;i.push(`the running application was needed and was not available${y?.reason?` (${y.reason})`:""}`),o.add("deployment_review")}else t.some(y=>y.kind==="tests-not-executed")&&i.push("the planned tests were written but not run");let h=Object.entries(e.state.stages).filter(([,y])=>y&&MAe.test(y.reason??"")).map(([y])=>y);h.length&&i.push(`the execution budget ran out before ${h.join(", ")} finished`);let A=new Set(r.plan.filter(y=>y.mechanism==="existing_evidence").flatMap(y=>y.evidenceIds)),m=r.ciEvidence.filter(y=>y.status==="accepted"&&A.has(y.id)).map(y=>({kind:y.kind,repository:y.repository,revision:y.revision,reference:y.reference,summary:y.summary}));return{sufficiency:i.length?"insufficient":"sufficient",rationale:r.rationale,gaps:i,acceptedEvidence:m,actionRequired:[...o]}}tr();tr();var zw=j(require("fs")),N2=j(require("path"));function D2(e){if(!zw.existsSync(e))return[];let t=[],n=r=>{let s;try{s=zw.readdirSync(r,{withFileTypes:!0})}catch(i){pt(`Skipping unreadable video dir ${r}: ${i instanceof Error?i.message:String(i)}`);return}for(let i of s){let o=N2.join(r,i.name);i.isDirectory()?n(o):i.isFile()&&i.name.endsWith(".webm")&&t.push(o)}};return n(e),t}var F2=600,Kw=300;function P2(e){return typeof e=="string"?e.trim():e instanceof Buffer?e.toString("utf-8").trim():""}function $Ae(e){let t=e,n=(typeof t?.message=="string"?t.message:String(e)).trim(),r=[P2(t?.stderr),P2(t?.stdout)].filter(Boolean);return r.length?[n.split(`
230
230
  `)[0],...r].join(`
231
231
  `):n}function _2(e,t,n){let r=e.join(t);if(r.length<=n)return r;let[s="",...i]=e;if(!i.length)return`${s.slice(0,n-1)}\u2026`;let o=s.slice(0,Math.floor(n/3)),a=n-o.length-t.length-1;return`${o}${t}\u2026${i.join(t).slice(-a)}`}function M2(e,t){return _2(e.trim().split(`
232
232
  `),`
233
233
  `,t)}function Zw(e){return uE($Ae(e),[]).trim()}var UAe=/^(.*?:\s*)?Command failed: (?:git|gh)\b.*$/;function MQ(e,t=Kw){let[n="",...r]=e.split(`
234
- `).map(o=>o.trim()).filter(Boolean),s=r.length?UAe.exec(n):null,i=s?[`${s[1]??""}${r[0]}`,...r.slice(1)]:[n,...r];return _2(i," ",t)}var U2=j(require("path"));var Vn=f.string().trim().min(1),$Q=(n=>(n.TestbotManaged="testbot_managed",n.CustomerDeployed="customer_deployed",n))($Q||{}),$A=[".skyramp/sut/setup.sh",".skyramp/sut/teardown.sh"],UQ=f.object({schemaVersion:f.literal(1),type:f.nativeEnum($Q).optional(),status:f.enum(["ready","blocked"]),environment:Pd.optional(),components:f.array(f.object({name:Vn,repository:Vn.describe(`owner/repo, or "${cn}" for a customer-deployed component no repository builds`),healthy:f.boolean(),url:f.string().min(1).nullable(),...NR,credentials:f.array(f.string().regex(Nd)).max(50).optional(),deployed:Vn.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:f.array(f.object({framework:Vn,file:Vn,result:f.enum(["pass","fail","error"])}).strict()),inputsUsed:f.array(Vn),inputsUsedHow:f.array(f.object({input:Vn,how:Vn}).strict()).optional(),inputsNotUsed:f.array(f.object({input:Vn,reason:Vn}).strict()),blockers:f.array(f.object({component:Vn,problem:Vn,evidence:Vn,fix:Vn}).strict()),replay:f.object({outcome:Vn,durationSeconds:f.number().nonnegative().nullable()}).strict().nullable(),files:f.array(f.object({path:Vn,content:f.string()}).strict())}).strict().superRefine((e,t)=>{e.inputsUsedHow?.forEach((s,i)=>{e.inputsUsed.includes(s.input)||t.addIssue({code:f.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:f.ZodIssueCode.custom,path:["components",i,"credentials"],message:"names a credential twice"})});let n=e.type==="customer_deployed";n!==(e.environment!==void 0)&&t.addIssue({code:f.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:f.ZodIssueCode.custom,path:["environment","credentials"],message:"names a credential twice"});let r=new Set(e.components.map(s=>s.name));if(e.environment?.revisionSources.forEach((s,i)=>{s.components.forEach((o,a)=>{r.has(o)||t.addIssue({code:f.ZodIssueCode.custom,path:["environment","revisionSources",i,"components",a],message:"not one of components"})})}),e.components.forEach((s,i)=>{s.deployed!==void 0!==n&&t.addIssue({code:f.ZodIssueCode.custom,path:["components",i,"deployed"],message:"what a component runs exactly when the plan is customer_deployed"}),s.repository===cn&&!n&&t.addIssue({code:f.ZodIssueCode.custom,path:["components",i,"repository"],message:`only a customer_deployed component is ${cn}`})}),n&&(e.components.forEach((s,i)=>{e.components.findIndex(o=>o.name===s.name)!==i&&t.addIssue({code:f.ZodIssueCode.custom,path:["components",i,"name"],message:"names a component twice"})}),e.replay!==null&&t.addIssue({code:f.ZodIssueCode.custom,path:["replay"],message:"a customer_deployed plan is never replayed"}),e.files.forEach((s,i)=>{$A.includes(s.path)&&t.addIssue({code:f.ZodIssueCode.custom,path:["files",i,"path"],message:"a customer_deployed plan has no script that starts or stops the system"})})),n&&e.status==="ready"){let s=new Set(e.environment?.revisionSources.flatMap(i=>i.components));e.components.forEach((i,o)=>{i.repository!==cn&&!s.has(i.name)&&t.addIssue({code:f.ZodIssueCode.custom,path:["components",o,"name"],message:"a ready customer_deployed plan reads what every component a repository builds runs"})})}});var Xw="Time limit reached";var vMe=["clean","recipe-drift"];function UA(e){let t=U2.posix.normalize(e);return t===e&&(t===".skyramp/workspace.yml"||t.startsWith(".skyramp/sut/")&&t.length>13)}var OQ="a GitHub Actions secret, or on Azure DevOps a secret variable in the host repository's skyramp-testbot variable group under Pipelines \u203A Library";var O2=[".skyramp/sut/setup.sh",".skyramp/sut/teardown.sh",".skyramp/sut/health.json",".skyramp/workspace.yml"],L2=[".skyramp/sut/health.json",".skyramp/workspace.yml"];var tC=(n=>(n.GitHub="github",n.AzureDevOps="azure-devops",n))(tC||{}),jQ=(i=>(i.Trigger="TRIGGER",i.Baseline="BASELINE",i.AuthoritativeRelatedChange="AUTHORITATIVE_RELATED_CHANGE",i.ConfiguredSharedDependency="CONFIGURED_SHARED_DEPENDENCY",i.ManualOverride="MANUAL_OVERRIDE",i))(jQ||{}),LA=(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))(LA||{}),jAe=["sut_setup"],GAe=["sut_setup","schedule","revision_read"];var nC=(t=>(t.PullRequest="pull_request",t))(nC||{}),jA=(s=>(s.ModelProvider="model_provider",s.SutAccess="sut_access",s.Skyramp="skyramp",s.Other="other",s))(jA||{});var rC=(i=>(i.ReportUploaded="report_uploaded",i.NoReport="no_report",i.Cancelled="cancelled",i.RecipeUploaded="recipe_uploaded",i.RevisionsUploaded="revisions_uploaded",i))(rC||{}),eY=(n=>(n.Running="running",n.Ended="ended",n))(eY||{}),sC=(u=>(u.TimedOut="timed_out",u.AgentFailed="agent_failed",u.SetupFailed="setup_failed",u.CredentialMissing="credential_missing",u.RunnerLost="runner_lost",u.CheckoutFailed="checkout_failed",u.EnvironmentUnverified="environment_unverified",u.ModelProviderDenied="model_provider_denied",u.ModelProviderUnavailable="model_provider_unavailable",u))(sC||{}),GQ=(r=>(r.Onboard="onboard",r.Deploy="deploy",r.Recheck="recheck",r))(GQ||{}),qQ=(n=>(n.Started="started",n.Finished="finished",n))(qQ||{}),VQ=(r=>(r.Passed="passed",r.Failed="failed",r.Skipped="skipped",r))(VQ||{});var HQ=(r=>(r.ChooseCredential="choose_credential",r.FreeText="free_text",r.ChooseSource="choose_source",r))(HQ||{});var iC=(r=>(r.Discover="discover",r.Start="start",r.Check="check",r))(iC||{}),qu=(s=>(s.ValidationPlan="validation_plan",s.TestEnvironment="test_environment",s.TestConditions="test_conditions",s.Tests="tests",s))(qu||{}),GA=(s=>(s.Found="found",s.Starting="starting",s.Up="up",s.OutOfScope="out_of_scope",s))(GA||{}),gi=f.string().regex(/^[1-9][0-9]{0,18}$/),Zo=f.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/),Bp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,cr=f.string().regex(Bp),ur=f.string().regex(/^[0-9a-f]{64}$/),eC=f.object({id:cr,revision:gi}).strict(),oC={provider:f.literal("github"),providerAccountId:gi,providerRepositoryId:gi},aC={provider:f.literal("azure-devops"),providerAccountId:cr,providerRepositoryId:cr},mi=f.discriminatedUnion("provider",[f.object(oC).strict(),f.object(aC).strict()]),YQ=f.discriminatedUnion("provider",[f.object(oC).passthrough(),f.object(aC).passthrough()]),Gu=e=>`${e.provider}:${e.providerRepositoryId}`,j2={namespace:f.string().min(1),name:f.string().min(1)},tY=f.discriminatedUnion("provider",[f.object({...oC,...j2}).strict(),f.object({...aC,...j2}).strict()]),G2=f.object({ref:f.string().min(1),revision:Zo}).strict(),qAe=f.object({repository:tY,revision:Zo,ref:f.string().nullable(),reason:f.nativeEnum(jQ),change:f.object({kind:f.nativeEnum(nC),number:gi,base:G2.optional()}).strict().nullable(),compareWith:G2.optional()}).strict();function VAe(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:n,sources:r}=e.baseline;if(t!==null&&n!==void 0)return"a run compares with one baseline";let s=e.trigger.kind==="schedule"&&t!==null||n!==void 0;if(!r)return s?"names every source of the snapshot, once":null;if(t===null&&n===void 0)return"a run with no Confirmed Baseline names no baseline sources";let i=new Set(e.sources.map(c=>Gu(c.repository))),o=new Set(r.map(c=>Gu(c.repository)));return o.size===r.length&&o.size===i.size&&[...o].every(c=>i.has(c))?null:"names every source of the snapshot, once"}var nY=/^[A-Z][A-Z0-9_]+-[1-9][0-9]*$/,rY=/^[1-9][0-9]{0,18}$/,q2=new RegExp(`${nY.source}|${rY.source}`),V2=/^https:\/\/[a-z0-9-]+(\.[a-z0-9-]+)+$/,HAe=f.union([f.object({source:f.literal("jira"),site:f.string().regex(V2),key:f.string().regex(nY),updated:f.string().datetime(),contentHash:ur}).strict(),f.object({source:f.literal("confluence"),site:f.string().regex(V2),key:f.string().regex(rY),version:f.number().int().positive(),contentHash:ur}).strict(),f.object({source:f.literal("other"),key:f.string().regex(If),contentHash:ur}).strict(),f.object({source:f.literal("other"),key:f.string().regex(gd),contentHash:ur,fileName:f.string().min(1).max(255),mediaType:f.nativeEnum(md)}).strict()]),H2=f.union([f.literal("jira"),f.literal("confluence")]),YAe=f.object({schemaVersion:f.literal(1),items:f.array(f.union([f.object({source:H2,site:f.string(),key:f.string().regex(q2),state:f.literal("read"),text:f.string(),version:f.string().min(1),contentMatches:f.boolean()}).strict(),f.object({source:H2,site:f.string(),key:f.string().regex(q2),state:f.literal("not_read"),reason:f.nativeEnum(yu)}).strict(),f.object({source:f.literal("other"),key:f.string().regex(If),state:f.literal("read"),text:f.string(),version:f.string().min(1),contentMatches:f.boolean()}).strict(),f.object({source:f.literal("other"),key:f.string().regex(If),state:f.literal("not_read"),reason:f.nativeEnum(yu)}).strict(),f.object({source:f.literal("other"),key:f.string().regex(gd),state:f.literal("read"),version:ur,fileName:f.string().min(1).max(255),mediaType:f.nativeEnum(md)}).strict(),f.object({source:f.literal("other"),key:f.string().regex(gd),state:f.literal("not_read"),reason:f.nativeEnum(yu)}).strict()])),instructions:f.array(f.string()).optional()}).strict(),JAe=f.object({schemaVersion:f.literal(1),runId:cr,skyrampOrgId:cr,target:eC,policy:eC.nullable(),trigger:f.object({kind:f.nativeEnum(LA),requestedAt:f.string().datetime()}).strict(),configuration:f.object({captureId:cr,revision:gi.nullable(),hash:ur}).strict(),baseline:f.object({confirmedRunId:cr.nullable(),initialBaselineId:cr.optional(),sources:f.array(f.object({repository:mi,revision:Zo}).strict()).optional()}).strict().optional(),sources:f.array(qAe).min(1),execution:f.object({provider:f.nativeEnum(tC),repository:tY,workflowPath:f.string(),ref:f.string()}).strict(),credentials:f.array(f.object({name:f.string(),purpose:f.nativeEnum(jA),required:f.boolean()}).strict()),requirements:f.array(HAe).min(1).optional(),instructions:f.object({contentHash:ur}).strict().optional(),deployedRevisions:f.array(f.object({repository:mi,revision:Zo}).strict()).min(1).optional()}).strict().superRefine((e,t)=>{let n=new Set;(e.requirements??[]).forEach((c,u)=>{let l="fileName"in c?"file":"pasted";c.source==="other"&&c.key!==`${l}-${c.contentHash.slice(0,16)}`&&t.addIssue({code:f.ZodIssueCode.custom,message:"is not the key of its content hash",path:["requirements",u,"key"]});let d=ai({source:c.source,key:c.key});n.has(d)&&t.addIssue({code:f.ZodIssueCode.custom,message:"names an item that the run already names",path:["requirements",u,"key"]}),n.add(d)});let r=e.trigger.kind,s=jAe.includes(r);s!==(e.policy===null)&&t.addIssue({code:f.ZodIssueCode.custom,path:["policy"],message:s?`a ${r} run has no policy`:"names the policy revision"});let i=VAe(e);i&&t.addIssue({code:f.ZodIssueCode.custom,path:e.baseline?["baseline","sources"]:["baseline"],message:i}),GAe.includes(r)&&e.sources.forEach((c,u)=>{c.reason!=="BASELINE"&&t.addIssue({code:f.ZodIssueCode.custom,path:["sources",u,"reason"],message:`a ${r} run selects only BASELINE sources`})}),e.deployedRevisions&&r!=="manual"&&t.addIssue({code:f.ZodIssueCode.custom,path:["deployedRevisions"],message:"only a manual run pins deployed revisions"});let o=new Set(e.sources.map(c=>Gu(c.repository))),a=new Set;(e.deployedRevisions??[]).forEach((c,u)=>{let l=Gu(c.repository);o.has(l)?a.has(l)&&t.addIssue({code:f.ZodIssueCode.custom,path:["deployedRevisions",u,"repository"],message:"repository appears twice"}):t.addIssue({code:f.ZodIssueCode.custom,path:["deployedRevisions",u,"repository"],message:"names a repository outside the snapshot"}),a.add(l)}),e.sources.forEach((c,u)=>{c.compareWith&&(c.reason!=="MANUAL_OVERRIDE"||c.change)&&t.addIssue({code:f.ZodIssueCode.custom,path:["sources",u,"compareWith"],message:"only a MANUAL_OVERRIDE source without a change names a revision to compare with"})})});var JQ=(n=>(n.Person="person",n.Policy="policy",n))(JQ||{}),WAe=f.object({kind:f.nativeEnum(JQ),name:f.string().min(1).max(256)}).strict(),NMe=f.object({schemaVersion:f.literal(1),attempt:f.object({id:cr,number:f.number().int().positive(),deadlineAt:f.string().datetime()}).strict(),manifest:JAe,manifestHash:ur,entitlements:f.array(f.string()).optional(),runToken:f.string().min(1).optional(),requestedBy:WAe.nullable().optional(),writeAllowed:f.boolean().optional(),claudeCodeVersion:f.string().regex(/^[0-9]+\.[0-9]+\.[0-9]+$/,"an exact version, such as 2.1.290").nullable().optional(),deployedRevisions:f.array(f.object({repository:mi,revision:Zo}).strict()).optional(),statedRevisions:f.array(f.object({repository:mi,revision:Zo}).strict()).optional()}).strict(),Y2={providerRunAttempt:f.number().int().positive(),workflowRef:f.string().min(1)},zAe=f.string().regex(/^[^/]+\/[^/]+\/[1-9][0-9]{0,15}\/[1-9][0-9]{0,15}$/),DMe=f.object({schemaVersion:f.literal(1),runId:cr,execution:f.discriminatedUnion("provider",[f.object({...Y2,provider:f.literal("github"),repository:f.object(oC).strict(),providerRunId:gi}).strict(),f.object({...Y2,provider:f.literal("azure-devops"),repository:f.object(aC).strict(),providerRunId:zAe}).strict()]),requester:f.literal(!0).optional(),writeCheck:f.literal(!0).optional(),claudeCodePin:f.literal(!0).optional(),deployedPins:f.literal(!0).optional(),statedPins:f.literal(!0).optional()}).strict(),J2=f.object({repository:mi,number:gi}).strict(),KAe=f.discriminatedUnion("status",[f.object({status:f.literal("none")}).strict(),f.object({status:f.literal("delivered"),pullRequests:f.array(J2).min(1)}).strict(),f.object({status:f.literal("partial"),pullRequests:f.array(J2).min(1),failures:f.array(f.object({repository:mi,message:f.string()}).strict()).min(1)}).strict(),f.object({status:f.literal("failed"),message:f.string()}).strict()]),ZAe=f.object({sufficiency:f.nativeEnum($a),rationale:f.string().min(1),gaps:f.array(f.string().min(1)),acceptedEvidence:f.array(f.object({kind:f.nativeEnum(Ua),repository:f.string().min(1),revision:Zo,reference:f.string().min(1),summary:f.string().min(1)}).strict()),actionRequired:f.array(f.nativeEnum(yd))}).strict().superRefine((e,t)=>{e.sufficiency==="insufficient"!=e.gaps.length>0&&t.addIssue({code:f.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:f.ZodIssueCode.custom,path:["actionRequired"],message:"a reason appears twice"})}),Rp=500,WQ=2048,zQ=1e3,XAe=/[\\/:*?"<>|;#$*{},+=[\]%\p{Cc}\p{Cf}]/u,W2=e=>e.length>0&&e.length<=64&&e===e.trim()&&!XAe.test(e)&&!/[^\S ]/u.test(e)&&!/^[._]/.test(e)&&!e.endsWith("."),ege=e=>{if(/^[A-Za-z0-9._-]{1,100}\/[A-Za-z0-9._-]{1,100}$/.test(e))return!0;let[t,n,r,...s]=e.split("/");return e.length<=201&&s.length===0&&r!==void 0&&/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,48}[A-Za-z0-9])?$/.test(t)&&W2(n)&&W2(r)},tge=f.object({testResults:f.array(f.object({resultId:f.string().regex(/^[^\u0000-\u001f]{1,512}$/),repository:f.string().refine(ege,"Invalid"),testType:f.string(),endpoint:f.string(),status:f.enum(["Pass","Fail","Skipped"]),details:f.string(),fileName:f.string().optional(),testId:f.string().regex(/^[^\u0000-\u001f]{1,512}$/).optional(),failureCause:f.object({kind:f.nativeEnum(bf),family:f.nativeEnum(sE).optional()}).strict().optional(),origin:f.nativeEnum(rE).optional()}).strict()),validation:ZAe,changes:f.array(f.object({id:f.string().min(1).max(512),text:f.string().max(16384),source:f.string().max(WQ),testedBy:f.array(f.string().min(1).max(1024)).max(Rp),writtenBy:f.array(f.string().min(1).max(1024)).max(Rp),maintainedBy:f.array(f.string().min(1).max(1024)).max(Rp)}).strict()).max(zQ).optional(),traceVersion:f.literal(1)}).passthrough().superRefine((e,t)=>{let n=new Set;e.testResults.forEach((r,s)=>{let i=r.failureCause;i&&r.status==="Pass"&&t.addIssue({code:f.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:f.ZodIssueCode.custom,path:["testResults",s,"failureCause"],message:"an environment cause names its family, and no other cause does"});let o=["testResults",s,"resultId"],a=r.resultId.slice(`${r.repository}:${r.testType}:`.length);(!r.resultId.startsWith(`${r.repository}:${r.testType}:`)||a===""||a.startsWith("/")||a.startsWith("#"))&&t.addIssue({code:f.ZodIssueCode.custom,path:o,message:"is not repository:testType:path for this result"}),n.has(r.resultId)&&t.addIssue({code:f.ZodIssueCode.custom,path:o,message:"stable identity repeated"}),n.add(r.resultId)})}),z2=e=>e.replace(/[%:#]/g,t=>encodeURIComponent(t));function KQ(e,t,n,r){let s=n.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 "${n}"`);let o=i.join("/"),a=`${e}:${t}:${z2(o)}`;return r?`${a}#${z2(r)}`:a}var sY=50,K2=f.string().regex(/^(?!.*\.\.)(?!\/)(?!.*\/$)[A-Za-z0-9._/-]{1,255}$/),iY=f.discriminatedUnion("kind",[f.object({kind:f.literal("branch_pushed"),repository:mi,branch:K2,commit:Zo}).strict(),f.object({kind:f.enum(["pull_request_opened","pull_request_edited"]),repository:mi,number:gi,branch:K2}).strict()]),nge=f.object({schemaVersion:f.literal(1),run:f.object({runId:cr,attemptNumber:f.number().int().positive(),manifestHash:ur}).strict(),target:eC,policy:eC,provenance:f.object({sources:f.array(f.object({repository:mi,revision:Zo}).strict()),firstQualification:f.literal(!0).optional()}).strict(),delivery:f.object({generatedTests:KAe}).strict(),producer:f.object({testbot:f.string().regex(/^[0-9A-Za-z.+-]{1,64}$/),mcp:f.string().regex(/^[0-9A-Za-z.+-]{1,64}$/)}).strict(),report:tge,githubWrites:f.array(iY).max(sY).optional()}).strict(),PMe=nge.pick({schemaVersion:!0,run:!0,target:!0,provenance:!0,producer:!0}).extend({recipe:UQ}).strict().superRefine(({recipe:e},t)=>{let n=(i,o)=>t.addIssue({code:f.ZodIssueCode.custom,path:["recipe",...i],message:o});e.status==="blocked"&&e.blockers.length===0&&n(["blockers"],"a blocked recipe names at least one blocker");let r=new Set,s=0;e.files.forEach((i,o)=>{UA(i.path)||n(["files",o,"path"],"is not .skyramp/workspace.yml or a file under .skyramp/sut/"),r.has(i.path)&&n(["files",o,"path"],"file repeated"),r.add(i.path),vE.test(i.content)&&n(["files",o,"content"],"is not text");let a=Buffer.byteLength(i.content,"utf8");s+=a,a>bu&&n(["files",o,"content"],`larger than ${bu} bytes`)}),s>Su&&n(["files"],`recipe text over ${Su} bytes in total`)}),FMe=f.object({components:f.array(f.object({name:f.string().min(1),repository:f.string().regex(/^[A-Za-z0-9._-]{1,100}\/[A-Za-z0-9._-]{1,100}$/),observedRevision:f.string().regex(/^[0-9a-f]{7,64}$/).nullable(),source:f.nativeEnum(Sf),evidence:f.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();var rge=f.object({schemaVersion:f.literal(1),stage:f.nativeEnum(GQ),event:f.nativeEnum(qQ),status:f.nativeEnum(VQ).optional()}).strict().refine(e=>e.status===void 0||e.event==="finished",{path:["status"],message:"only a finished stage has a status"}),dc=100,ZQ=5e3,OA=2e3,LQ=100,XQ=/^[A-Za-z0-9_-]{1,64}$/,oY=20,aY=200,cY=100,uY=100,sge=200,Z2="[^/\\s](?:(?:[^/\\s]| )*[^/\\s])?",ige=new RegExp(`^(?:[^/\\s]+/[^/\\s]+|[^/\\s]+/${Z2}/${Z2})$`),lY=500,dY=50,qA=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/,$s=e=>f.string().max(e).refine(t=>t.trim().length>0&&!qA.test(t),"blank, or not text"),Ko={sequence:f.number().int().min(1).max(ZQ),at:f.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?Z$/)},pY=f.discriminatedUnion("kind",[f.object({...Ko,kind:f.literal("log"),phase:f.nativeEnum(iC),text:$s(OA)}).strict(),f.object({...Ko,kind:f.literal("component"),name:$s(LQ),repository:$s(sge).refine(e=>ige.test(e)||e===cn,"not owner/name"),file:$s(lY).nullable(),status:f.nativeEnum(GA),version:$s(uY).optional()}).strict(),f.object({...Ko,kind:f.literal("reply"),to:f.string().uuid(),accepted:f.boolean(),text:$s(OA)}).strict(),f.object({...Ko,kind:f.literal("question"),id:f.string().regex(XQ),type:f.nativeEnum(HQ),text:$s(OA),component:$s(LQ).nullable(),choices:f.array($s(aY)).max(oY),placeholder:$s(cY).optional()}).strict(),f.object({...Ko,kind:f.literal("delivered"),ids:f.array(f.string().uuid()).max(dc)}).strict(),f.object({...Ko,kind:f.literal("credentials"),names:f.array(f.string().regex(Nd)).min(1).max(dY)}).strict()]).superRefine((e,t)=>{e.kind==="credentials"&&new Set(e.names).size!==e.names.length&&t.addIssue({code:f.ZodIssueCode.custom,path:["names"],message:"a name twice"}),e.kind==="question"&&(e.type==="free_text"!=(e.choices.length===0)&&t.addIssue({code:f.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:f.ZodIssueCode.custom,path:["choices"],message:"a choice twice"}))}),oge=f.object({schemaVersion:f.literal(1),events:f.array(pY).max(dc)}).strict(),hY=f.discriminatedUnion("kind",[f.object({...Ko,kind:f.literal("log"),stage:f.nativeEnum(qu),text:$s(OA)}).strict(),f.object({...Ko,kind:f.literal("reply"),to:f.string().uuid(),accepted:f.boolean(),text:$s(OA)}).strict(),f.object({...Ko,kind:f.literal("delivered"),ids:f.array(f.string().uuid()).max(dc)}).strict()]),age=f.object({schemaVersion:f.literal(1),events:f.array(hY).max(dc)}).strict(),X2={id:f.string().uuid(),text:f.string(),by:f.string().nullable(),at:f.string(),replied:f.literal(!0).optional()},fY=f.discriminatedUnion("kind",[f.object({...X2,kind:f.literal("instruction"),question:f.null()}),f.object({...X2,kind:f.literal("answer"),question:f.string().regex(XQ)})]),AY=f.string().regex(/^[A-Za-z0-9+/]{43}=$/),cge=f.object({id:f.string().uuid(),revision:f.string(),by:f.string().nullable(),at:f.string(),target:f.string(),own:f.object({source:f.enum(["policy","test_environment"]),text:f.string()}).nullable()}),uge=f.object({schemaVersion:f.literal(1),leftOut:f.array(f.string()),messages:f.array(fY).optional(),stop:f.object({key:AY}).optional(),notes:cge.optional()}),lge=f.object({schemaVersion:f.literal(1),messages:f.array(fY).optional()});var gY=500*1024*1024,mY=f.object({id:gi,name:f.string().regex(/^[A-Za-z0-9._-]{1,200}$/),providerRunId:gi,expiresAt:f.string().datetime()}).strict(),dge=f.object({schemaVersion:f.literal(1),artifact:mY,sessionId:cr,contentHash:ur,bytes:f.number().int().min(1).max(gY)}).strict(),pge=f.object({schemaVersion:f.literal(1),checkpoint:f.object({artifact:mY,repository:f.object({namespace:f.string().min(1),name:f.string().min(1)}).strict(),sessionId:cr,contentHash:ur,key:AY}).strict().nullable()}).strict(),hge=200,kp=100,cC=(r=>(r.Resume="resume",r.Retry="retry",r.Update="update",r))(cC||{}),fge=f.object({kind:f.nativeEnum(cC),setup:f.object({runId:cr,endedAt:f.string().nullable(),outcome:f.string().nullable()}).strict(),components:f.array(f.object({name:f.string().min(1),repository:f.string().min(1),status:f.nativeEnum(GA)}).strict()).max(kp),credentials:f.array(f.string().min(1)).max(kp),answers:f.array(f.object({question:f.string(),answer:f.string().nullable()}).strict()).max(kp),instructions:f.array(f.object({text:f.string(),reply:f.string().nullable()}).strict()).max(kp),log:f.array(f.object({phase:f.nativeEnum(iC),text:f.string()}).strict()).max(hge),recipe:f.object({files:f.array(f.object({path:f.string().min(1),content:f.string()}).strict()).max(kp),blockers:f.array(f.object({component:f.string(),problem:f.string(),evidence:f.string(),fix:f.string()}).strict()).max(kp)}).strict().optional()}).strict(),Age=f.object({schemaVersion:f.literal(1),context:fge.nullable()}).strict(),gge=f.object({schemaVersion:f.literal(1),configuration:f.object({captureId:cr,revision:gi.nullable(),hash:ur}).strict(),capture:f.object({schemaVersion:f.literal(1),settings:f.object({target:f.object({environment:f.unknown()}).passthrough(),timeoutMinutes:f.number().int().positive(),answerWaitMinutes:f.number().int().positive().optional(),testEnvironment:f.object({name:f.string().min(1),address:f.string().min(1).optional(),readyWhen:f.string().min(1).optional()}).passthrough().optional()}).passthrough(),provenance:f.object({}).passthrough(),hash:ur}).strict()}).strict(),mge=Pd.extend({version:f.number().int().positive(),components:f.array(f.object({name:f.string().min(1),repository:f.string().min(1)}).strict()),contentHash:ur.optional(),files:f.array(f.object({path:f.string().refine(e=>UA(e)&&!$A.includes(e),"not a file of a customer_deployed plan"),content:f.string()}).strict()).optional()}).strict(),yge=f.object({schemaVersion:f.literal(1),testEnvironment:mge.nullable().optional(),runtimePlan:f.object({version:f.number().int().positive(),contentHash:ur,files:f.array(f.object({path:f.string().refine(UA,"not a recipe file path"),content:f.string()}).strict()).min(1),recipe:f.record(f.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"]}),Ege=f.object({schemaVersion:f.literal(1),state:f.nativeEnum(eY),ending:f.nativeEnum(rC).nullable(),cause:f.nativeEnum(sC).nullable(),deadlineAt:f.string().datetime()}).strict();function yY(e){return e.reportUploaded?{schemaVersion:1,reason:"report_uploaded",cause:null}:e.recipeUploaded?{schemaVersion:1,reason:"recipe_uploaded",cause:null}:e.revisionsUploaded?{schemaVersion:1,reason:"revisions_uploaded",cause:null}:e.cancelled?{schemaVersion:1,reason:"cancelled",cause:null}:{schemaVersion:1,reason:"no_report",cause:wge(e)}}function wge(e){return e.credentialMissing?"credential_missing":e.checkoutFailed?"checkout_failed":e.environmentUnverified?"environment_unverified":e.setupFailed?"setup_failed":e.timedOut?"timed_out":e.modelProviderDenied?"model_provider_denied":e.modelProviderUnavailable?"model_provider_unavailable":"agent_failed"}var EY=j(require("fs")),pc=j(require("path"));var wY={"application/pdf":"PDF","text/csv":"CSV","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX"};var Hn=e=>new Map((e??[]).flatMap(t=>t.file?[[gn(t.key),t.file.name]]:[])),Cge=10*1024*1024,Vu=e=>e?.mediaType==="application/vnd.openxmlformats-officedocument.wordprocessingml.document"||e?.mediaType==="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",CY=(e,t)=>pc.join(pc.dirname(e),`${pc.basename(e,pc.extname(e))}${t}`),Hu=e=>CY(e,".extracted.txt");function eT(e){try{return/\S/.test(EY.readFileSync(Hu(e),"utf-8"))}catch{return!1}}var tT=e=>CY(e,".quotes.txt");function IY(e){return Vu(e.file)?Hu(e.path):e.file?.mediaType==="application/pdf"?tT(e.path):e.path}function uC(e){return e.map(t=>t.state!=="read"||!Vu(t.file)||eT(t.path)?t:{...Eu(t),file:t.file,state:"not_read",reason:"cannot_open"})}var bY=j(require("fs")),VA="SKYRAMP_AZURE_SUPERVISED",nT=3;function lC(e){return e.replace(/##(?=(?:vso)?\[)/gi,"#\u200B#")}function rT(e,t=process.env){t[VA]==="1"?bY.writeSync(nT,`${JSON.stringify(e)}
234
+ `).map(o=>o.trim()).filter(Boolean),s=r.length?UAe.exec(n):null,i=s?[`${s[1]??""}${r[0]}`,...r.slice(1)]:[n,...r];return _2(i," ",t)}var U2=j(require("path"));var Vn=f.string().trim().min(1),$Q=(n=>(n.TestbotManaged="testbot_managed",n.CustomerDeployed="customer_deployed",n))($Q||{}),$A=[".skyramp/sut/setup.sh",".skyramp/sut/teardown.sh"],UQ=f.object({schemaVersion:f.literal(1),type:f.nativeEnum($Q).optional(),status:f.enum(["ready","blocked"]),environment:Pd.optional(),components:f.array(f.object({name:Vn,repository:Vn.describe(`owner/repo, or "${cn}" for a customer-deployed component no repository builds`),healthy:f.boolean(),url:f.string().min(1).nullable(),...NR,credentials:f.array(f.string().regex(Nd)).max(50).optional(),deployed:Vn.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:f.array(f.object({framework:Vn,file:Vn,result:f.enum(["pass","fail","error"])}).strict()),inputsUsed:f.array(Vn),inputsUsedHow:f.array(f.object({input:Vn,how:Vn}).strict()).optional(),inputsNotUsed:f.array(f.object({input:Vn,reason:Vn}).strict()),blockers:f.array(f.object({component:Vn,problem:Vn,evidence:Vn,fix:Vn}).strict()),replay:f.object({outcome:Vn,durationSeconds:f.number().nonnegative().nullable()}).strict().nullable(),files:f.array(f.object({path:Vn,content:f.string()}).strict())}).strict().superRefine((e,t)=>{e.inputsUsedHow?.forEach((s,i)=>{e.inputsUsed.includes(s.input)||t.addIssue({code:f.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:f.ZodIssueCode.custom,path:["components",i,"credentials"],message:"names a credential twice"})});let n=e.type==="customer_deployed";n!==(e.environment!==void 0)&&t.addIssue({code:f.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:f.ZodIssueCode.custom,path:["environment","credentials"],message:"names a credential twice"});let r=new Set(e.components.map(s=>s.name));if(e.environment?.revisionSources.forEach((s,i)=>{s.components.forEach((o,a)=>{r.has(o)||t.addIssue({code:f.ZodIssueCode.custom,path:["environment","revisionSources",i,"components",a],message:"not one of components"})})}),e.components.forEach((s,i)=>{s.deployed!==void 0!==n&&t.addIssue({code:f.ZodIssueCode.custom,path:["components",i,"deployed"],message:"what a component runs exactly when the plan is customer_deployed"}),s.repository===cn&&!n&&t.addIssue({code:f.ZodIssueCode.custom,path:["components",i,"repository"],message:`only a customer_deployed component is ${cn}`})}),n&&(e.components.forEach((s,i)=>{e.components.findIndex(o=>o.name===s.name)!==i&&t.addIssue({code:f.ZodIssueCode.custom,path:["components",i,"name"],message:"names a component twice"})}),e.replay!==null&&t.addIssue({code:f.ZodIssueCode.custom,path:["replay"],message:"a customer_deployed plan is never replayed"}),e.files.forEach((s,i)=>{$A.includes(s.path)&&t.addIssue({code:f.ZodIssueCode.custom,path:["files",i,"path"],message:"a customer_deployed plan has no script that starts or stops the system"})})),n&&e.status==="ready"){let s=new Set(e.environment?.revisionSources.flatMap(i=>i.components));e.components.forEach((i,o)=>{i.repository!==cn&&!s.has(i.name)&&t.addIssue({code:f.ZodIssueCode.custom,path:["components",o,"name"],message:"a ready customer_deployed plan reads what every component a repository builds runs"})})}});var Xw="Time limit reached";var vMe=["clean","recipe-drift"];function UA(e){let t=U2.posix.normalize(e);return t===e&&(t===".skyramp/workspace.yml"||t.startsWith(".skyramp/sut/")&&t.length>13)}var OQ="a GitHub Actions secret, or on Azure DevOps a secret variable in the host repository's skyramp-testbot variable group under Pipelines \u203A Library";var O2=[".skyramp/sut/setup.sh",".skyramp/sut/teardown.sh",".skyramp/sut/health.json",".skyramp/workspace.yml"],L2=[".skyramp/sut/health.json",".skyramp/workspace.yml"];var tC=(n=>(n.GitHub="github",n.AzureDevOps="azure-devops",n))(tC||{}),jQ=(i=>(i.Trigger="TRIGGER",i.Baseline="BASELINE",i.AuthoritativeRelatedChange="AUTHORITATIVE_RELATED_CHANGE",i.ConfiguredSharedDependency="CONFIGURED_SHARED_DEPENDENCY",i.ManualOverride="MANUAL_OVERRIDE",i))(jQ||{}),LA=(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))(LA||{}),jAe=["sut_setup"],GAe=["sut_setup","schedule","revision_read"];var nC=(t=>(t.PullRequest="pull_request",t))(nC||{}),jA=(s=>(s.ModelProvider="model_provider",s.SutAccess="sut_access",s.Skyramp="skyramp",s.Other="other",s))(jA||{});var rC=(i=>(i.ReportUploaded="report_uploaded",i.NoReport="no_report",i.Cancelled="cancelled",i.RecipeUploaded="recipe_uploaded",i.RevisionsUploaded="revisions_uploaded",i))(rC||{}),eY=(n=>(n.Running="running",n.Ended="ended",n))(eY||{}),sC=(u=>(u.TimedOut="timed_out",u.AgentFailed="agent_failed",u.SetupFailed="setup_failed",u.CredentialMissing="credential_missing",u.RunnerLost="runner_lost",u.CheckoutFailed="checkout_failed",u.EnvironmentUnverified="environment_unverified",u.ModelProviderDenied="model_provider_denied",u.ModelProviderUnavailable="model_provider_unavailable",u))(sC||{}),GQ=(r=>(r.Onboard="onboard",r.Deploy="deploy",r.Recheck="recheck",r))(GQ||{}),qQ=(n=>(n.Started="started",n.Finished="finished",n))(qQ||{}),VQ=(r=>(r.Passed="passed",r.Failed="failed",r.Skipped="skipped",r))(VQ||{});var HQ=(r=>(r.ChooseCredential="choose_credential",r.FreeText="free_text",r.ChooseSource="choose_source",r))(HQ||{});var iC=(r=>(r.Discover="discover",r.Start="start",r.Check="check",r))(iC||{}),qu=(s=>(s.ValidationPlan="validation_plan",s.TestEnvironment="test_environment",s.TestConditions="test_conditions",s.Tests="tests",s))(qu||{}),GA=(s=>(s.Found="found",s.Starting="starting",s.Up="up",s.OutOfScope="out_of_scope",s))(GA||{}),gi=f.string().regex(/^[1-9][0-9]{0,18}$/),Zo=f.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/),Bp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,cr=f.string().regex(Bp),ur=f.string().regex(/^[0-9a-f]{64}$/),eC=f.object({id:cr,revision:gi}).strict(),oC={provider:f.literal("github"),providerAccountId:gi,providerRepositoryId:gi},aC={provider:f.literal("azure-devops"),providerAccountId:cr,providerRepositoryId:cr},mi=f.discriminatedUnion("provider",[f.object(oC).strict(),f.object(aC).strict()]),YQ=f.discriminatedUnion("provider",[f.object(oC).passthrough(),f.object(aC).passthrough()]),Gu=e=>`${e.provider}:${e.providerRepositoryId}`,j2={namespace:f.string().min(1),name:f.string().min(1)},tY=f.discriminatedUnion("provider",[f.object({...oC,...j2}).strict(),f.object({...aC,...j2}).strict()]),G2=f.object({ref:f.string().min(1),revision:Zo}).strict(),qAe=f.object({repository:tY,revision:Zo,ref:f.string().nullable(),reason:f.nativeEnum(jQ),change:f.object({kind:f.nativeEnum(nC),number:gi,base:G2.optional()}).strict().nullable(),compareWith:G2.optional()}).strict();function VAe(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:n,sources:r}=e.baseline;if(t!==null&&n!==void 0)return"a run compares with one baseline";let s=e.trigger.kind==="schedule"&&t!==null||n!==void 0;if(!r)return s?"names every source of the snapshot, once":null;if(t===null&&n===void 0)return"a run with no Confirmed Baseline names no baseline sources";let i=new Set(e.sources.map(c=>Gu(c.repository))),o=new Set(r.map(c=>Gu(c.repository)));return o.size===r.length&&o.size===i.size&&[...o].every(c=>i.has(c))?null:"names every source of the snapshot, once"}var nY=/^[A-Z][A-Z0-9_]+-[1-9][0-9]*$/,rY=/^[1-9][0-9]{0,18}$/,q2=new RegExp(`${nY.source}|${rY.source}`),V2=/^https:\/\/[a-z0-9-]+(\.[a-z0-9-]+)+$/,HAe=f.union([f.object({source:f.literal("jira"),site:f.string().regex(V2),key:f.string().regex(nY),updated:f.string().datetime(),contentHash:ur}).strict(),f.object({source:f.literal("confluence"),site:f.string().regex(V2),key:f.string().regex(rY),version:f.number().int().positive(),contentHash:ur}).strict(),f.object({source:f.literal("other"),key:f.string().regex(If),contentHash:ur}).strict(),f.object({source:f.literal("other"),key:f.string().regex(gd),contentHash:ur,fileName:f.string().min(1).max(255),mediaType:f.nativeEnum(md)}).strict()]),H2=f.union([f.literal("jira"),f.literal("confluence")]),YAe=f.object({schemaVersion:f.literal(1),items:f.array(f.union([f.object({source:H2,site:f.string(),key:f.string().regex(q2),state:f.literal("read"),text:f.string(),version:f.string().min(1),contentMatches:f.boolean()}).strict(),f.object({source:H2,site:f.string(),key:f.string().regex(q2),state:f.literal("not_read"),reason:f.nativeEnum(yu)}).strict(),f.object({source:f.literal("other"),key:f.string().regex(If),state:f.literal("read"),text:f.string(),version:f.string().min(1),contentMatches:f.boolean()}).strict(),f.object({source:f.literal("other"),key:f.string().regex(If),state:f.literal("not_read"),reason:f.nativeEnum(yu)}).strict(),f.object({source:f.literal("other"),key:f.string().regex(gd),state:f.literal("read"),version:ur,fileName:f.string().min(1).max(255),mediaType:f.nativeEnum(md)}).strict(),f.object({source:f.literal("other"),key:f.string().regex(gd),state:f.literal("not_read"),reason:f.nativeEnum(yu)}).strict()])),instructions:f.array(f.string()).optional()}).strict(),JAe=f.object({schemaVersion:f.literal(1),runId:cr,skyrampOrgId:cr,target:eC,policy:eC.nullable(),trigger:f.object({kind:f.nativeEnum(LA),requestedAt:f.string().datetime()}).strict(),configuration:f.object({captureId:cr,revision:gi.nullable(),hash:ur}).strict(),baseline:f.object({confirmedRunId:cr.nullable(),initialBaselineId:cr.optional(),sources:f.array(f.object({repository:mi,revision:Zo}).strict()).optional()}).strict().optional(),sources:f.array(qAe).min(1),execution:f.object({provider:f.nativeEnum(tC),repository:tY,workflowPath:f.string(),ref:f.string()}).strict(),credentials:f.array(f.object({name:f.string(),purpose:f.nativeEnum(jA),required:f.boolean()}).strict()),requirements:f.array(HAe).min(1).optional(),instructions:f.object({contentHash:ur}).strict().optional(),deployedRevisions:f.array(f.object({repository:mi,revision:Zo}).strict()).min(1).optional()}).strict().superRefine((e,t)=>{let n=new Set;(e.requirements??[]).forEach((c,u)=>{let l="fileName"in c?"file":"pasted";c.source==="other"&&c.key!==`${l}-${c.contentHash.slice(0,16)}`&&t.addIssue({code:f.ZodIssueCode.custom,message:"is not the key of its content hash",path:["requirements",u,"key"]});let d=ai({source:c.source,key:c.key});n.has(d)&&t.addIssue({code:f.ZodIssueCode.custom,message:"names an item that the run already names",path:["requirements",u,"key"]}),n.add(d)});let r=e.trigger.kind,s=jAe.includes(r);s!==(e.policy===null)&&t.addIssue({code:f.ZodIssueCode.custom,path:["policy"],message:s?`a ${r} run has no policy`:"names the policy revision"});let i=VAe(e);i&&t.addIssue({code:f.ZodIssueCode.custom,path:e.baseline?["baseline","sources"]:["baseline"],message:i}),GAe.includes(r)&&e.sources.forEach((c,u)=>{c.reason!=="BASELINE"&&t.addIssue({code:f.ZodIssueCode.custom,path:["sources",u,"reason"],message:`a ${r} run selects only BASELINE sources`})}),e.deployedRevisions&&r!=="manual"&&t.addIssue({code:f.ZodIssueCode.custom,path:["deployedRevisions"],message:"only a manual run pins deployed revisions"});let o=new Set(e.sources.map(c=>Gu(c.repository))),a=new Set;(e.deployedRevisions??[]).forEach((c,u)=>{let l=Gu(c.repository);o.has(l)?a.has(l)&&t.addIssue({code:f.ZodIssueCode.custom,path:["deployedRevisions",u,"repository"],message:"repository appears twice"}):t.addIssue({code:f.ZodIssueCode.custom,path:["deployedRevisions",u,"repository"],message:"names a repository outside the snapshot"}),a.add(l)}),e.sources.forEach((c,u)=>{c.compareWith&&(c.reason!=="MANUAL_OVERRIDE"||c.change)&&t.addIssue({code:f.ZodIssueCode.custom,path:["sources",u,"compareWith"],message:"only a MANUAL_OVERRIDE source without a change names a revision to compare with"})})});var JQ=(n=>(n.Person="person",n.Policy="policy",n))(JQ||{}),WAe=f.object({kind:f.nativeEnum(JQ),name:f.string().min(1).max(256)}).strict(),NMe=f.object({schemaVersion:f.literal(1),attempt:f.object({id:cr,number:f.number().int().positive(),deadlineAt:f.string().datetime()}).strict(),manifest:JAe,manifestHash:ur,entitlements:f.array(f.string()).optional(),runToken:f.string().min(1).optional(),requestedBy:WAe.nullable().optional(),writeAllowed:f.boolean().optional(),claudeCodeVersion:f.string().regex(/^[0-9]+\.[0-9]+\.[0-9]+$/,"an exact version, such as 2.1.290").nullable().optional(),deployedRevisions:f.array(f.object({repository:mi,revision:Zo}).strict()).optional(),statedRevisions:f.array(f.object({repository:mi,revision:Zo}).strict()).optional()}).strict(),Y2={providerRunAttempt:f.number().int().positive(),workflowRef:f.string().min(1)},zAe=f.string().regex(/^[^/]+\/[^/]+\/[1-9][0-9]{0,15}\/[1-9][0-9]{0,15}$/),DMe=f.object({schemaVersion:f.literal(1),runId:cr,execution:f.discriminatedUnion("provider",[f.object({...Y2,provider:f.literal("github"),repository:f.object(oC).strict(),providerRunId:gi}).strict(),f.object({...Y2,provider:f.literal("azure-devops"),repository:f.object(aC).strict(),providerRunId:zAe}).strict()]),requester:f.literal(!0).optional(),writeCheck:f.literal(!0).optional(),claudeCodePin:f.literal(!0).optional(),deployedPins:f.literal(!0).optional(),statedPins:f.literal(!0).optional()}).strict(),J2=f.object({repository:mi,number:gi}).strict(),KAe=f.discriminatedUnion("status",[f.object({status:f.literal("none")}).strict(),f.object({status:f.literal("delivered"),pullRequests:f.array(J2).min(1)}).strict(),f.object({status:f.literal("partial"),pullRequests:f.array(J2).min(1),failures:f.array(f.object({repository:mi,message:f.string()}).strict()).min(1)}).strict(),f.object({status:f.literal("failed"),message:f.string()}).strict()]),ZAe=f.object({blockedPreflight:f.object({file:f.string().min(1),repository:f.string().min(1).optional(),reason:f.string().min(1).max(300),evidence:f.string().min(1).max(400)}).strict().optional(),sufficiency:f.nativeEnum($a),rationale:f.string().min(1),gaps:f.array(f.string().min(1)),acceptedEvidence:f.array(f.object({kind:f.nativeEnum(Ua),repository:f.string().min(1),revision:Zo,reference:f.string().min(1),summary:f.string().min(1)}).strict()),actionRequired:f.array(f.nativeEnum(yd))}).strict().superRefine((e,t)=>{e.sufficiency==="insufficient"!=e.gaps.length>0&&t.addIssue({code:f.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:f.ZodIssueCode.custom,path:["actionRequired"],message:"a reason appears twice"})}),Rp=500,WQ=2048,zQ=1e3,XAe=/[\\/:*?"<>|;#$*{},+=[\]%\p{Cc}\p{Cf}]/u,W2=e=>e.length>0&&e.length<=64&&e===e.trim()&&!XAe.test(e)&&!/[^\S ]/u.test(e)&&!/^[._]/.test(e)&&!e.endsWith("."),ege=e=>{if(/^[A-Za-z0-9._-]{1,100}\/[A-Za-z0-9._-]{1,100}$/.test(e))return!0;let[t,n,r,...s]=e.split("/");return e.length<=201&&s.length===0&&r!==void 0&&/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,48}[A-Za-z0-9])?$/.test(t)&&W2(n)&&W2(r)},tge=f.object({testResults:f.array(f.object({resultId:f.string().regex(/^[^\u0000-\u001f]{1,512}$/),repository:f.string().refine(ege,"Invalid"),testType:f.string(),endpoint:f.string(),status:f.enum(["Pass","Fail","Skipped"]),details:f.string(),fileName:f.string().optional(),testId:f.string().regex(/^[^\u0000-\u001f]{1,512}$/).optional(),failureCause:f.object({kind:f.nativeEnum(bf),family:f.nativeEnum(sE).optional()}).strict().optional(),origin:f.nativeEnum(rE).optional()}).strict()),validation:ZAe,changes:f.array(f.object({id:f.string().min(1).max(512),text:f.string().max(16384),source:f.string().max(WQ),testedBy:f.array(f.string().min(1).max(1024)).max(Rp),writtenBy:f.array(f.string().min(1).max(1024)).max(Rp),maintainedBy:f.array(f.string().min(1).max(1024)).max(Rp)}).strict()).max(zQ).optional(),traceVersion:f.literal(1)}).passthrough().superRefine((e,t)=>{let n=new Set;e.testResults.forEach((r,s)=>{let i=r.failureCause;i&&r.status==="Pass"&&t.addIssue({code:f.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:f.ZodIssueCode.custom,path:["testResults",s,"failureCause"],message:"an environment cause names its family, and no other cause does"});let o=["testResults",s,"resultId"],a=r.resultId.slice(`${r.repository}:${r.testType}:`.length);(!r.resultId.startsWith(`${r.repository}:${r.testType}:`)||a===""||a.startsWith("/")||a.startsWith("#"))&&t.addIssue({code:f.ZodIssueCode.custom,path:o,message:"is not repository:testType:path for this result"}),n.has(r.resultId)&&t.addIssue({code:f.ZodIssueCode.custom,path:o,message:"stable identity repeated"}),n.add(r.resultId)})}),z2=e=>e.replace(/[%:#]/g,t=>encodeURIComponent(t));function KQ(e,t,n,r){let s=n.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 "${n}"`);let o=i.join("/"),a=`${e}:${t}:${z2(o)}`;return r?`${a}#${z2(r)}`:a}var sY=50,K2=f.string().regex(/^(?!.*\.\.)(?!\/)(?!.*\/$)[A-Za-z0-9._/-]{1,255}$/),iY=f.discriminatedUnion("kind",[f.object({kind:f.literal("branch_pushed"),repository:mi,branch:K2,commit:Zo}).strict(),f.object({kind:f.enum(["pull_request_opened","pull_request_edited"]),repository:mi,number:gi,branch:K2}).strict()]),nge=f.object({schemaVersion:f.literal(1),run:f.object({runId:cr,attemptNumber:f.number().int().positive(),manifestHash:ur}).strict(),target:eC,policy:eC,provenance:f.object({sources:f.array(f.object({repository:mi,revision:Zo}).strict()),firstQualification:f.literal(!0).optional()}).strict(),delivery:f.object({generatedTests:KAe}).strict(),producer:f.object({testbot:f.string().regex(/^[0-9A-Za-z.+-]{1,64}$/),mcp:f.string().regex(/^[0-9A-Za-z.+-]{1,64}$/)}).strict(),report:tge,githubWrites:f.array(iY).max(sY).optional()}).strict(),PMe=nge.pick({schemaVersion:!0,run:!0,target:!0,provenance:!0,producer:!0}).extend({recipe:UQ}).strict().superRefine(({recipe:e},t)=>{let n=(i,o)=>t.addIssue({code:f.ZodIssueCode.custom,path:["recipe",...i],message:o});e.status==="blocked"&&e.blockers.length===0&&n(["blockers"],"a blocked recipe names at least one blocker");let r=new Set,s=0;e.files.forEach((i,o)=>{UA(i.path)||n(["files",o,"path"],"is not .skyramp/workspace.yml or a file under .skyramp/sut/"),r.has(i.path)&&n(["files",o,"path"],"file repeated"),r.add(i.path),vE.test(i.content)&&n(["files",o,"content"],"is not text");let a=Buffer.byteLength(i.content,"utf8");s+=a,a>bu&&n(["files",o,"content"],`larger than ${bu} bytes`)}),s>Su&&n(["files"],`recipe text over ${Su} bytes in total`)}),FMe=f.object({components:f.array(f.object({name:f.string().min(1),repository:f.string().regex(/^[A-Za-z0-9._-]{1,100}\/[A-Za-z0-9._-]{1,100}$/),observedRevision:f.string().regex(/^[0-9a-f]{7,64}$/).nullable(),source:f.nativeEnum(Sf),evidence:f.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();var rge=f.object({schemaVersion:f.literal(1),stage:f.nativeEnum(GQ),event:f.nativeEnum(qQ),status:f.nativeEnum(VQ).optional()}).strict().refine(e=>e.status===void 0||e.event==="finished",{path:["status"],message:"only a finished stage has a status"}),dc=100,ZQ=5e3,OA=2e3,LQ=100,XQ=/^[A-Za-z0-9_-]{1,64}$/,oY=20,aY=200,cY=100,uY=100,sge=200,Z2="[^/\\s](?:(?:[^/\\s]| )*[^/\\s])?",ige=new RegExp(`^(?:[^/\\s]+/[^/\\s]+|[^/\\s]+/${Z2}/${Z2})$`),lY=500,dY=50,qA=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/,$s=e=>f.string().max(e).refine(t=>t.trim().length>0&&!qA.test(t),"blank, or not text"),Ko={sequence:f.number().int().min(1).max(ZQ),at:f.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?Z$/)},pY=f.discriminatedUnion("kind",[f.object({...Ko,kind:f.literal("log"),phase:f.nativeEnum(iC),text:$s(OA)}).strict(),f.object({...Ko,kind:f.literal("component"),name:$s(LQ),repository:$s(sge).refine(e=>ige.test(e)||e===cn,"not owner/name"),file:$s(lY).nullable(),status:f.nativeEnum(GA),version:$s(uY).optional()}).strict(),f.object({...Ko,kind:f.literal("reply"),to:f.string().uuid(),accepted:f.boolean(),text:$s(OA)}).strict(),f.object({...Ko,kind:f.literal("question"),id:f.string().regex(XQ),type:f.nativeEnum(HQ),text:$s(OA),component:$s(LQ).nullable(),choices:f.array($s(aY)).max(oY),placeholder:$s(cY).optional()}).strict(),f.object({...Ko,kind:f.literal("delivered"),ids:f.array(f.string().uuid()).max(dc)}).strict(),f.object({...Ko,kind:f.literal("credentials"),names:f.array(f.string().regex(Nd)).min(1).max(dY)}).strict()]).superRefine((e,t)=>{e.kind==="credentials"&&new Set(e.names).size!==e.names.length&&t.addIssue({code:f.ZodIssueCode.custom,path:["names"],message:"a name twice"}),e.kind==="question"&&(e.type==="free_text"!=(e.choices.length===0)&&t.addIssue({code:f.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:f.ZodIssueCode.custom,path:["choices"],message:"a choice twice"}))}),oge=f.object({schemaVersion:f.literal(1),events:f.array(pY).max(dc)}).strict(),hY=f.discriminatedUnion("kind",[f.object({...Ko,kind:f.literal("log"),stage:f.nativeEnum(qu),text:$s(OA)}).strict(),f.object({...Ko,kind:f.literal("reply"),to:f.string().uuid(),accepted:f.boolean(),text:$s(OA)}).strict(),f.object({...Ko,kind:f.literal("delivered"),ids:f.array(f.string().uuid()).max(dc)}).strict()]),age=f.object({schemaVersion:f.literal(1),events:f.array(hY).max(dc)}).strict(),X2={id:f.string().uuid(),text:f.string(),by:f.string().nullable(),at:f.string(),replied:f.literal(!0).optional()},fY=f.discriminatedUnion("kind",[f.object({...X2,kind:f.literal("instruction"),question:f.null()}),f.object({...X2,kind:f.literal("answer"),question:f.string().regex(XQ)})]),AY=f.string().regex(/^[A-Za-z0-9+/]{43}=$/),cge=f.object({id:f.string().uuid(),revision:f.string(),by:f.string().nullable(),at:f.string(),target:f.string(),own:f.object({source:f.enum(["policy","test_environment"]),text:f.string()}).nullable()}),uge=f.object({schemaVersion:f.literal(1),leftOut:f.array(f.string()),messages:f.array(fY).optional(),stop:f.object({key:AY}).optional(),notes:cge.optional()}),lge=f.object({schemaVersion:f.literal(1),messages:f.array(fY).optional()});var gY=500*1024*1024,mY=f.object({id:gi,name:f.string().regex(/^[A-Za-z0-9._-]{1,200}$/),providerRunId:gi,expiresAt:f.string().datetime()}).strict(),dge=f.object({schemaVersion:f.literal(1),artifact:mY,sessionId:cr,contentHash:ur,bytes:f.number().int().min(1).max(gY)}).strict(),pge=f.object({schemaVersion:f.literal(1),checkpoint:f.object({artifact:mY,repository:f.object({namespace:f.string().min(1),name:f.string().min(1)}).strict(),sessionId:cr,contentHash:ur,key:AY}).strict().nullable()}).strict(),hge=200,kp=100,cC=(r=>(r.Resume="resume",r.Retry="retry",r.Update="update",r))(cC||{}),fge=f.object({kind:f.nativeEnum(cC),setup:f.object({runId:cr,endedAt:f.string().nullable(),outcome:f.string().nullable()}).strict(),components:f.array(f.object({name:f.string().min(1),repository:f.string().min(1),status:f.nativeEnum(GA)}).strict()).max(kp),credentials:f.array(f.string().min(1)).max(kp),answers:f.array(f.object({question:f.string(),answer:f.string().nullable()}).strict()).max(kp),instructions:f.array(f.object({text:f.string(),reply:f.string().nullable()}).strict()).max(kp),log:f.array(f.object({phase:f.nativeEnum(iC),text:f.string()}).strict()).max(hge),recipe:f.object({files:f.array(f.object({path:f.string().min(1),content:f.string()}).strict()).max(kp),blockers:f.array(f.object({component:f.string(),problem:f.string(),evidence:f.string(),fix:f.string()}).strict()).max(kp)}).strict().optional()}).strict(),Age=f.object({schemaVersion:f.literal(1),context:fge.nullable()}).strict(),gge=f.object({schemaVersion:f.literal(1),configuration:f.object({captureId:cr,revision:gi.nullable(),hash:ur}).strict(),capture:f.object({schemaVersion:f.literal(1),settings:f.object({target:f.object({environment:f.unknown()}).passthrough(),timeoutMinutes:f.number().int().positive(),answerWaitMinutes:f.number().int().positive().optional(),testEnvironment:f.object({name:f.string().min(1),address:f.string().min(1).optional(),readyWhen:f.string().min(1).optional()}).passthrough().optional()}).passthrough(),provenance:f.object({}).passthrough(),hash:ur}).strict()}).strict(),mge=Pd.extend({version:f.number().int().positive(),components:f.array(f.object({name:f.string().min(1),repository:f.string().min(1)}).strict()),contentHash:ur.optional(),files:f.array(f.object({path:f.string().refine(e=>UA(e)&&!$A.includes(e),"not a file of a customer_deployed plan"),content:f.string()}).strict()).optional()}).strict(),yge=f.object({schemaVersion:f.literal(1),testEnvironment:mge.nullable().optional(),runtimePlan:f.object({version:f.number().int().positive(),contentHash:ur,files:f.array(f.object({path:f.string().refine(UA,"not a recipe file path"),content:f.string()}).strict()).min(1),recipe:f.record(f.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"]}),Ege=f.object({schemaVersion:f.literal(1),state:f.nativeEnum(eY),ending:f.nativeEnum(rC).nullable(),cause:f.nativeEnum(sC).nullable(),deadlineAt:f.string().datetime()}).strict();function yY(e){return e.reportUploaded?{schemaVersion:1,reason:"report_uploaded",cause:null}:e.recipeUploaded?{schemaVersion:1,reason:"recipe_uploaded",cause:null}:e.revisionsUploaded?{schemaVersion:1,reason:"revisions_uploaded",cause:null}:e.cancelled?{schemaVersion:1,reason:"cancelled",cause:null}:{schemaVersion:1,reason:"no_report",cause:wge(e)}}function wge(e){return e.credentialMissing?"credential_missing":e.checkoutFailed?"checkout_failed":e.environmentUnverified?"environment_unverified":e.setupFailed?"setup_failed":e.timedOut?"timed_out":e.modelProviderDenied?"model_provider_denied":e.modelProviderUnavailable?"model_provider_unavailable":"agent_failed"}var EY=j(require("fs")),pc=j(require("path"));var wY={"application/pdf":"PDF","text/csv":"CSV","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX"};var Hn=e=>new Map((e??[]).flatMap(t=>t.file?[[gn(t.key),t.file.name]]:[])),Cge=10*1024*1024,Vu=e=>e?.mediaType==="application/vnd.openxmlformats-officedocument.wordprocessingml.document"||e?.mediaType==="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",CY=(e,t)=>pc.join(pc.dirname(e),`${pc.basename(e,pc.extname(e))}${t}`),Hu=e=>CY(e,".extracted.txt");function eT(e){try{return/\S/.test(EY.readFileSync(Hu(e),"utf-8"))}catch{return!1}}var tT=e=>CY(e,".quotes.txt");function IY(e){return Vu(e.file)?Hu(e.path):e.file?.mediaType==="application/pdf"?tT(e.path):e.path}function uC(e){return e.map(t=>t.state!=="read"||!Vu(t.file)||eT(t.path)?t:{...Eu(t),file:t.file,state:"not_read",reason:"cannot_open"})}var bY=j(require("fs")),VA="SKYRAMP_AZURE_SUPERVISED",nT=3;function lC(e){return e.replace(/##(?=(?:vso)?\[)/gi,"#\u200B#")}function rT(e,t=process.env){t[VA]==="1"?bY.writeSync(nT,`${JSON.stringify(e)}
235
235
  `):process.stdout.write(e.command!==void 0?`${e.command}
236
236
  `:e.text??"")}function sT(e){rT({command:e})}function SY(e){return e.replace(/%/g,"%AZP25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function Ige(e){return SY(e).replace(/;/g,"%3B").replace(/]/g,"%5D")}function dC(e,t,n){let r=Object.entries(t).map(([s,i])=>`${s}=${Ige(i)}`).join(";");return`##vso[${e}${r?` ${r}`:""}]${SY(n)}`}function vY(e){if(!e)return[];let t=e.split(/\r?\n/).filter(n=>n.trim()&&n!==e);return[e,...t].map(n=>dC("task.setsecret",{},n))}function kY(e,t=sT){for(let n of vY(e))t(n)}function bge(e){return e.replace(/%0D/g,"\r").replace(/%0A/g,`
237
237
  `).replace(/%25/g,"%")}function RY(e){let t=/^::([a-z-]+)(?: [^:]*)?::(.*)$/s.exec(e.replace(/\r?\n$/,""));if(!t)return;let[,n,r]=t,s=bge(r),i=lC(s);switch(n){case"add-mask":return vY(s);case"warning":case"error":return[dC("task.logissue",{type:n},i)];case"notice":return[i];case"debug":return i.split(`
@@ -543,8 +543,8 @@ except Exception:
543
543
  `),y),h.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 ${u.join(", ")}'s expected outcome`))}return{problems:o,tests:a}}function Cz(e){try{return JSON.parse(ZC.readFileSync(Ez.join(e,hg),"utf-8")).decision}catch{return}}function wx(e,t){ZC.writeFileSync(e,JSON.stringify(t,null,2)+`
544
544
  `)}var ACe=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 Cx(e){let t=ot.basename(e);return ACe.has(t)||/^requirements[^/\\]*\.(txt|in)$/.test(t)}var gCe={"go.mod":"go.sum",Gemfile:"Gemfile.lock"},Iz={"package.json":["@playwright/test","playwright","@skyramp/skyramp"],python:["skyramp","pytest"]},mCe=["@skyramp/skyramp","skyramp"];function yCe(e,t,n){if(mz(t))return!0;let r=Cz(e.outputsDir);if(!r?.use||r.placement!=="beside-tests"||!r.dir)return!1;let s=ot.resolve(t)===ot.resolve(e.inputs.repositoryPath)?"":`${ot.basename(ot.resolve(t))}/`;if(s&&!r.dir.startsWith(s))return!1;let i=r.dir.slice(s.length),o=ot.posix.dirname(n.split(ot.sep).join("/"));return o==="."||i===o||i.startsWith(`${o}/`)}function ECe(e){let t=ot.basename(e);return t==="package.json"?Iz["package.json"]:t==="pyproject.toml"||t==="Pipfile"||t==="setup.py"||t==="setup.cfg"||/^requirements/.test(t)?Iz.python:[]}function wCe(e,t,n){let r=YG(e,t);if(r===void 0)return!1;if(ot.basename(t)==="package.json")try{let s=JSON.parse(r);return["dependencies","devDependencies","optionalDependencies","peerDependencies"].some(i=>s[i]&&typeof s[i]=="object"&&Object.hasOwn(s[i],n))}catch{return!1}return new RegExp(`(^|[\\s"'\\[,])${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w-])`,"im").test(r)}function CCe(e,t){let n=Y(e,as),r=ot.resolve(t.path)===ot.resolve(e.inputs.repositoryPath)?(n?.packages??[]).map(s=>s.dir):[];return[...new Set([...xA(t.path).map(s=>s.dir),...r])]}function fg(e){let t=new Map;return n=>t.get(n.path)??t.set(n.path,CCe(e,n)).get(n.path)}function XC(e,t,n=new Set){let r=fg(e);return[...t.flatMap(s=>ICe(e,s,r)),...bCe(e,t,n,r)]}function ICe(e,t,n=fg(e)){let r=[],s=Bs(e.inputs,t.repository);if("error"in s)return r.push(`${t.package}: ${s.error}`),r;let{source:i}=s,o=xe(e.inputs,i.slug),a=ot.relative(i.path,ot.resolve(i.path,t.manifest.trim()));if(a===".."||a.startsWith(`..${ot.sep}`)||!ic(ot.join(i.path,a))||Nu(i.path,a)!==a)return r.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`),r;if(Yi(a))return r.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/`),r;if(hi(a,n(i)))return r.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`),r;if(!jE(i.path,a))return r.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`),r;let c=hp(t.package.trim());ECe(a).includes(c)&&!wCe(i.path,a,c)&&!(e.inputs.skyrampHelpers!==!1&&mCe.includes(c)&&yCe(e,i.path,a))&&r.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()||r.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 u=Ou(i.path,a),l=new Set(vw(i.path,u));for(let d of u)l.has(d)?pH(i.path,d,a,t.package)||r.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`):r.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 r}function bCe(e,t,n=new Set,r=fg(e)){let s=[];for(let i of ye(e.inputs).filter(o=>o.writable)){let o=xe(e.inputs,i.slug),a=r(i),c=new Set;for(let u of t){if(Xe(e.inputs,u.repository)?.path!==i.path)continue;let l=ot.relative(i.path,ot.resolve(i.path,u.manifest.trim())).split(ot.sep).join("/");c.add(l);for(let h of Ou(i.path,l))c.add(h.split(ot.sep).join("/"));let d=gCe[ot.basename(l)];d&&c.add(ot.posix.join(ot.posix.dirname(l),d))}for(let{path:u}of zi(i.path)){let l=u.replace(/\/+$/,"");!Cx(l)||Yi(l)||NA(l)||hi(l,a)||n.has(ot.resolve(i.path,l))||c.has(l)||s.push(`${o}${l} 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 -- ${l}, 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 Sz(e){let t=Y(e,as),n=e.inputs.repositoryPath;return(t?.packages??[]).filter(r=>bz.existsSync(ot.join(n,r.dir))).flatMap(r=>bH(n,r.dir))}function SCe(e){return _t(nA,e).errors}function vCe(e,t=[]){let{value:n,error:r}=ft(e,t);if(r)return{errors:[r]};let s=SCe(n);return s.length>0?{errors:s}:{finalize:n,errors:[]}}var kCe="finalize-scratch";function Vp(e,t){let n=vCe(e.stdout,t?.secretValues);if(!n.finalize||!t?.outputsDir)return n;let r=(s,i)=>s.trim()&&wE(s.trim(),Br.join(t.outputsDir,kCe,i),"finalize")||s;return{...n,finalize:{...n.finalize,lint:n.finalize.lint.map((s,i)=>({...s,command:r(s.command??"",`lint-${i+1}.sh`)}))}}}var kz=yn("finalize-schema",(e,t)=>Vp(t,e)),Rz={name:"finalize-ready",verify(e,t){let{finalize:n,errors:r}=Vp(t,e);if(!n)return se(this.name,r);let s=[],i=[n.blockers.length?`blockers listed: ${n.blockers.slice(0,4).join("; ")}`:void 0,...n.lint.map(o=>{let a=o.repository?` in ${o.repository}`:"";return o.clean?void 0:`lint.clean is false${a}`}),n.fileConventions.ok?void 0:`fileConventions.ok is false${n.fileConventions.notes?` (${n.fileConventions.notes})`:""}`].filter(o=>!!o);return n.ready&&i.length&&s.push(`ready:true contradicts the checks \u2014 ${i.join("; ")}`),!n.ready&&!n.blockers.length&&s.push("ready:false but blockers is empty \u2014 name what blocks the commit"),s.length===0?{name:this.name,passed:!0}:se(this.name,s)}},Bz={name:"finalize-dependencies",verify(e,t){let{finalize:n,errors:r}=Vp(t);if(!n)return se(this.name,r);let s=new Set(e.prepared?.writtenBefore??[]),i=XC(e,n.dependencies.added,s);return i.length===0?{name:this.name,passed:!0}:se(this.name,i)}};function Qz(e,t){let n={};for(let r of t){let s=Br.resolve(e,r),i=Yo(Br.dirname(s),Br.basename(s),ec);i!==void 0&&i>0&&(n[s]=i)}return n}var RCe=e=>e.prepared?.unitAssertionBaseline??{},Tz={name:"finalize-intent",verify(e){let t=Y(e,"adapt.json"),n=[];for(let[r,s]of Object.entries(RCe(e))){let i=Yo(Br.dirname(r),Br.basename(r),ec)??0;i<s&&n.push(`${r} makes ${i} assertion(s); it made ${s} when generate-unit wrote it \u2014 a lint/format fix dropped ${s-i}`)}if(!t)return n.length===0?{name:this.name,passed:!0}:se(this.name,n);for(let r of t.items){if(!r.file||r.action==="delete")continue;let s=r.assertionCount;if(s===void 0||s===0)continue;let i=Jt(e.inputs,r.repository),o=Yo(i,it(i,r.file),ec);if(o===void 0){n.push(`${r.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&&n.push(`${r.file} makes ${o} assertion(s); it made ${s} when adapt placed it \u2014 a lint/format/convention fix dropped ${s-o}`)}return n.length===0?{name:this.name,passed:!0}:se(this.name,n)}},xz={name:"finalize-unit-tests-kept",verify(e){let n=(e.prepared?.unitTestFiles??[]).filter(r=>!eI.existsSync(Br.resolve(e.inputs.repositoryPath,r)));return n.length===0?{name:this.name,passed:!0}:se(this.name,n.map(r=>`${r} is gone \u2014 lint and format the native unit tests in place; do not move, rename or delete them`))}},BCe=/(^|\/)node_modules\//;function Ix(e){let t=e.prepared?.writtenBefore;if(!t)return[];let n=new Set(t),r=Y(e,"adapt.json"),s=Y(e,Zt);for(let o of[...r?.items??[],...s?.tests??[]])o.file&&n.add(Br.resolve(Jt(e.inputs,o.repository),o.file));let i=[];for(let o of ye(e.inputs).filter(a=>a.writable))for(let a of aV(o.path))n.has(Br.resolve(o.path,a))||a.startsWith(".skyramp/")||a.startsWith(".testbot/")||BCe.test(a)||!Bn.test(a)||i.push({source:o,rel:a});return i}function Nz(e){let t=[];for(let{source:n,rel:r}of Ix(e))try{eI.rmSync(Br.join(n.path,r),{force:!0})}catch(s){t.push(`${xe(e.inputs,n.slug)}${r} (${s instanceof Error?s.message:String(s)})`)}return t.length?`could not delete stray test file(s): ${t.join("; ")}`:void 0}function Dz(e,t){let n=t.at(-1),r=n?.gates.filter(s=>!s.passed).map(s=>s.name)??[];if(!(!n?.session||r.length!==1||r[0]!==bx.name)&&!Ix(e).length)return Sx(e,n.session)}var bx={name:"finalize-no-stray-tests",verify(e){let t=[];for(let{source:n,rel:r}of Ix(e))t.push(`${xe(e.inputs,n.slug)}${r} 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}:se(this.name,t)}},Pz={name:"finalize-lint",verify(e,t){let{finalize:n,errors:r}=Vp(t,e);if(!n)return se(this.name,r);let s=[],i=new Set(n.lint.map(o=>Xe(e.inputs,o.repository)?.path));for(let o of QCe(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 n.lint){let a=Xe(e.inputs,o.repository);a?s.push(...TCe(o,a.path,xe(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}:se(this.name,s)}};function QCe(e){let t=Y(e,"adapt.json"),n=Y(e,Zt),r=[...t?.items??[],...n?.tests??[],...n?.maintained??[]].map(s=>Xe(e.inputs,s.repository));return[...new Map(r.filter(s=>!!s).map(s=>[s.path,s])).values()]}function TCe(e,t,n){let r=e.command?.trim();if(!r)return e.clean?[]:[`${n}lint.clean is false and no lint command was recorded to re-run`];let{steps:s,reason:i}=wr(r);if(!s)return[`${n}lint command '${r}' cannot be re-executed: ${i}`];try{for(let o of s)(0,vz.execFileSync)(o[0],o.slice(1),{cwd:t,stdio:"ignore",timeout:12e4,env:Be()});return[]}catch(o){let a=o;return a.code==="ENOENT"||a.status===127?[]:[`${n}lint command '${r}' failed \u2014 the changed files are not clean`]}}var Fz={name:"finalize-lint-coverage",verify(e,t){let{finalize:n,errors:r}=Vp(t,e);if(!n)return se(this.name,r);let s=new Set(["place","update","regenerate"]),i=Y(e,"adapt.json"),o=Y(e,Zt),a=(l,d)=>`${Xe(e.inputs,l)?.path}\0${d}`,c=new Set([...(i?.items??[]).filter(l=>s.has(l.action)).map(l=>a(l.repository,l.file)),...(o?.tests??[]).map(l=>a(l.repository,l.file)),...(o?.maintained??[]).filter(l=>l.change==="updated").map(l=>a(l.repository,l.file))]),u=n.lint.flatMap(l=>l.uncovered.filter(d=>!c.has(a(l.repository,d))).map(d=>`${xe(e.inputs,l.repository)}${d}`));return u.length===0?{name:this.name,passed:!0}:se(this.name,[`lint.uncovered names file(s) this run never placed or maintained: ${u.join(", ")} \u2014 only a changed/new file can be uncovered`])}};function Sx(e,t){let{finalize:n,errors:r}=Vp(t,e);return Fe(e,"finalize",n,r)}var xCe=new Set(["place","update","regenerate"]),_z=e=>t=>`${xe(e.inputs,t.repository)}${t.file}`;function NCe(e){let t=Hp.join(e.outputsDir,"adapt.json");if(!tI.existsSync(t))return[];try{let n=JSON.parse(tI.readFileSync(t,"utf-8"));return[...new Set((n.items??[]).filter(r=>xCe.has(r.action??"")).map(_z(e)))]}catch{return[]}}function DCe(e){let t=Y(e,Zt);return[...new Set((t?.tests??[]).map(n=>Hp.resolve(Jt(e.inputs,n.repository),n.file)))]}function PCe(e){let t=Y(e,Zt),n=(t?.maintained??[]).filter(r=>r.change==="updated");return[...new Set([...t?.tests??[],...n].map(_z(e)))]}function FCe(e){let t=PCe(e),n=Vr(Hp.join(Hp.resolve(e.inputs.repositoryPath),lQ,"python")),r=[...new Set([...NCe(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:",r.length?r.map(s=>` - ${s}`).join(`
545
545
  `):" (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 ${n} <tool>\`, and run it from there:`,` \`env PYTHONPATH=${n} python3 -m poetry -C <dir> lock\`,`,` \`env PYTHONPATH=${n} python3 -m uv lock --project <dir>\`,`,` \`env PYTHONPATH=${n} python3 -m pdm lock -p <dir>\` (pdm.lock),`,` \`env PYTHONPATH=${n} 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.","",...Vi(e.inputs),"","Output: end with one JSON object matching:","",bt(nA)].join(`
546
- `)}var Mz=St({name:"finalize",model:"opus",timeoutMinutes:20,requires:[],branchRequires:{runtime:["adapt"],"no-runtime":["generate-unit"]},softRequires:["native-run"],prepare:e=>{let t=DCe(e);return{unitTestFiles:t,unitAssertionBaseline:Qz(e.inputs.repositoryPath,t),writtenBefore:[...ns(rs(e.inputs))]}},buildPrompt:FCe,buildReadDirs:e=>qi(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:*)",...SC],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:[kz,Rz,Pz,Fz,Bz,Tz,xz,bx],onPassed:Sx,afterAttempt:Nz,salvage:Dz});var wK=j(require("crypto")),bi=j(require("fs")),js=j(require("path"));function nI(e=process.env){return e.CLAUDE_CODE_USE_BEDROCK==="1"?"AWS Bedrock":"Anthropic"}var ZVe=ht.rows.notRun(!0),Ag=e=>({deployed:jf(e)||Ww(e),expected:Ai(e)?.sutRequired!==!1}),$z={deployed:!0,expected:!0},Rx="could not run here";function Uz(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(r=>r.test(t))))return t.replace(/^(?:not run|could not run here)[:.]?\s*/i,"")}var Oz=e=>({status:"Skipped",details:`${Rx}: ${e}`.slice(0,400),failureCause:{kind:"environment",family:"external_dependency"}}),gc="kept, not ",Yp="(declined the planned ";function Lz(e){return e.map(t=>t.expected===void 0?t.expectation:`${t.expectation} (${t.expected})`).join("; ")}function Qx(e){if(!e)return[];let t=[],n=0,r=0;for(let s=0;s<e.length;s++){let i=e[s];i==="("?n++:i===")"?n=Math.max(0,n-1):n===0&&i===";"&&e[s+1]===" "&&e[s-1]===")"&&(t.push(e.slice(r,s)),r=s+2)}return t.push(e.slice(r)),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(),u=i.slice(a+1,-1).trim();return c&&u?{expectation:c,expected:u}:{expectation:i}}return{expectation:i}})}var oa=new Set(["update","regenerate","delete"]),vx=e=>e==null?"Skipped":e===0?"Pass":"Fail";function Wn(e,t){return t?.trim()||Mt(e.inputs).slug}var _Ce={update:"updated",regenerate:"regenerated",delete:"deleted",verify:"verified",none:"touched"},MCe=e=>_Ce[e]??`${e}d`;function $Ce(e,t,n,r=$z){let s=ht.rows.notRun(r.expected),i=u=>Wn(n,u).toLowerCase(),o=(e?.maintenance??[]).map(u=>{let l=t.find(w=>i(w.repository)===i(u.repository)&&(w.file===u.test||w.from&&w.from===u.test)),d=!!l&&oa.has(l.action),h=u.action!=="verify",A=l?.action??u.action,m=d?A:oa.has(A)||A==="none"?"verify":A,y=l?.reran?.exit!=null?vx(l.reran.exit):void 0,E=(()=>{if(d){let w=l.action==="delete"?"removed":l.reran?.details??(l.reran?.exit==null?s:`exit ${l.reran.exit}`);if(!l.keptReason)return w;let C=`${Yp}${u.action}: ${l.keptReason})`.slice(0,200);return`${w.slice(0,300-C.length-1)} ${C}`}return l?.keptReason?`${gc}${MCe(A)}: ${l.keptReason}`.slice(0,300):h?`recommended ${u.action}, not applied this run`:"not applied this run"})();return{repository:Wn(n,u.repository),testType:"existing",endpoint:"n/a",fileName:l?.file??u.test,description:u.evidence,action:m,beforeStatus:"Unknown",beforeDetails:u.evidence,afterStatus:d?l.action==="delete"?"Skipped":vx(l.reran?.exit):y??"Unknown",afterDetails:E}}),a=u=>(e?.maintenance??[]).some(l=>i(u.repository)===i(l.repository)&&(u.file===l.test||u.from&&u.from===l.test)),c=t.filter(u=>oa.has(u.action)&&!a(u)).map(u=>({repository:Wn(n,u.repository),testType:"existing",endpoint:"n/a",fileName:u.file,description:"found stale while running the existing tests",action:u.action,beforeStatus:"Unknown",beforeDetails:"not in the plan's maintenance list",afterStatus:u.action==="delete"?"Skipped":vx(u.reran?.exit),afterDetails:u.action==="delete"?"removed":u.reran?.details??(u.reran?.exit==null?s:`exit ${u.reran.exit}`)}));return[...o,...c]}function UCe(e,t,n){let r=s=>Wn(n,s).toLowerCase();return(e??[]).map(s=>{let i=s.change==="deleted",o=Ow(s.file),a=i?[]:t.filter(y=>r(y.repository)===r(s.repository)&&y.file===o),c=a.filter(y=>y.status==="Fail"),u=a.filter(y=>y.status==="Pass").length,l=i?"Skipped":c.length?"Fail":u?"Pass":a.length?"Skipped":"Unknown",d=a.length-c.length-u,h=[c.length&&`${c.length} failed`,u&&`${u} passed`,d&&`${d} skipped`].filter(Boolean).join(", "),A=o===s.file?"":` (run by ${o})`,m=i?"removed":a.length?`${h}${A}${c.length?`: ${c[0].details}`:""}`:"not re-run by this run's unit test run";return{repository:Wn(n,s.repository),testType:"existing",endpoint:"n/a",fileName:s.file,description:s.reason,action:i?"delete":"update",beforeStatus:"Unknown",beforeDetails:s.reason,afterStatus:l,afterDetails:m.slice(0,300)}})}function OCe(e,t){let n=i=>`${(i.repository??"").toLowerCase()}\0${i.fileName}`,r=new Set(e.filter(i=>oa.has(i.action)).map(n)),s=new Set(t.map(n));return[...e.filter(i=>r.has(n(i))||!s.has(n(i))),...t.filter(i=>!r.has(n(i)))]}function LCe(e,t,n,r,s,i,o=[]){let a=e?.behaviors??[];if(!a.length)return[];let c=new Set(r.filter(w=>w.testId&&w.status!=="Skipped").map(w=>w.testId)),u=new Set(s.map(w=>w.testId)),l=new Map,d=new Map;for(let w of t?.generate??[]){if(!w.from_behavior||!u.has(w.id))continue;let C=d.get(w.from_behavior)??[];if(C.includes(w.id)||C.push(w.id),d.set(w.from_behavior,C),!c.has(w.id))continue;let k=l.get(w.from_behavior)??[];k.includes(w.id)||k.push(w.id),l.set(w.from_behavior,k)}let h=w=>i?Wn(i,w).toLowerCase():"",A=w=>i?xe(i.inputs,w):"",m=new Map;for(let w of t?.maintenance??[]){let C=n.find(b=>h(b.repository)===h(w.repository)&&(b.file===w.test||b.from&&b.from===w.test));if(!C||!oa.has(C.action))continue;let k=`${A(C.repository)}${C.file}`;for(let b of w.covers_behaviors??[]){let I=m.get(b)??[];I.includes(k)||I.push(k),m.set(b,I)}}let y=(w,C)=>o.filter(k=>C(k)&&k.behaviorIds.includes(w)).map(k=>k.testId),E=(w,C)=>[...new Set([...w,...C])].slice(0,Rp);return a.slice(0,zQ).map(w=>({id:w.id,text:w.statement,source:w.evidence.slice(0,WQ),testedBy:E(l.get(w.id)??[],y(w.id,C=>C.tested)),writtenBy:E(d.get(w.id)??[],y(w.id,C=>C.written)),maintainedBy:(m.get(w.id)??[]).slice(0,Rp)}))}var kx=(e,t)=>`${Oa(e)}::${t}`;function jCe(e,t,n,r=[]){let s=i=>!(i.action==="delete"&&i.from);return{generated:e.length,modified:t.filter(i=>oa.has(i.action)&&s(i)).length+(r??[]).length,verified:t.filter(i=>s(i)&&(i.action==="verify"||!!i.keptReason)&&!oa.has(i.action)).length,executed:n.filter(i=>i.status!=="Skipped").length}}function GCe(e,t,n,r){let s=[],i=Y(e,"deploy.json"),o=E=>e.state.stages[E]?.status==="failed",a=e.state.modelProviderFailure,c=E=>o(E)&&a?.stage!==E&&!e.state.stages[E]?.reason?.startsWith("not run \u2014 the model provider refused");(c("deploy")||c("plan"))&&!i&&s.push({kind:"deploy-failed",text:ht.caveats.deployFailed,blocking:!0});let u=(t?.items??[]).filter(E=>E.action!=="delete"),l=u.filter(E=>E.reran?.exit===null||E.reran?.exit===void 0);u.length>0&&l.length===u.length&&s.push({kind:"tests-not-executed",text:ht.caveats.testsNotExecuted,blocking:!0}),i?.outcome&&i.outcome!=="clean"&&!Ww(e)&&s.push(i.outcome==="change-broke-bringup"?{kind:"deploy-failed",subject:"change",text:ht.caveats.changeBrokeBringup,blocking:!0}:i.outcome==="bringup-failed"?{kind:"deploy-failed",text:ht.caveats.bringupFailed,blocking:!0}:{kind:"recipe-drift",text:ht.caveats.recipeDrift,blocking:!1});for(let[E,w]of Object.entries(i?.dependencies??{}))w===!1&&s.push({kind:"mocked-dependency",subject:E,text:ht.caveats.mockedDependency(E),blocking:!1});if(n?.ready===!1||o("finalize")||o("write")){let E=(n?.blockers??[]).slice(0,3).join("; ");s.push({kind:"finalize-not-ready",text:ht.caveats.finalizeNotReady(E),blocking:!0})}Ai(e)?.sutRequired===!1&&s.push({kind:"sut-not-required",text:ht.caveats.sutNotRequired,blocking:!1});let d=Fp(e);d.length&&s.push({kind:"analysis-unverified",text:ht.caveats.analysisUnverified(d.length),blocking:!1});let h=Gw(Wo(e)??{results:[],notRun:[]});h&&s.push({kind:"unit-tests-not-run",text:ht.caveats.unitTestsNotRun(h),blocking:!1});let A=(r??[]).filter(E=>E.status==="Skipped"&&E.details?.startsWith(`${Rx}:`));A.length&&s.push({kind:"tests-could-not-run-here",text:ht.caveats.testsCouldNotRunHere(A.length,A[0].details.slice(Rx.length+2)),blocking:!1});let m=FQ(e).map(E=>E.behaviorId?`${E.behaviorId}: ${E.missing}`:E.missing);if(m.length&&s.push({kind:"downstream-not-checked",text:ht.caveats.downstreamNotChecked(m.join("; ")),blocking:!1}),a){let E=_Q(e,s),w=(r??[]).some(k=>k.status==="Pass"||k.status==="Fail"),C=E?E.sufficiency==="sufficient"&&(E.acceptedEvidence.length>0||w):w;s.push(a.kind==="permanent"?{kind:"model-provider-denied",text:ht.caveats.modelProviderDenied(nI(),C),blocking:!C}:{kind:"model-provider-unavailable",text:ht.caveats.modelProviderUnavailable(nI(),C),blocking:!C})}n?.ciReadiness?.covered===!1&&s.push({kind:"ci-not-covered",text:ht.caveats.ciNotCovered,blocking:!1});let y=(n?.lint??[]).flatMap(E=>(E.uncovered??[]).map(w=>`${xe(e.inputs,E.repository)}${w}`));return y.length>0&&s.push({kind:"lint-not-covered",subject:y.join(", "),text:ht.caveats.lintNotCovered(y.join(", ")),blocking:!1}),s}function qCe(e,t,n,r,s,i=$z,o=()=>{}){let a=[];for(let c of e.filter(u=>u.action!=="delete")){let u=c.reran?.exit,l=jz(c.action),d=c.from?r.get(c.from):void 0,h=[...new Set([...c.covers??[],...d??[]])],A=h.length?h:[void 0];if(c.placementBroken){for(let _ of A){let L=_?t.get(_):void 0;a.push({testId:_,testType:Bx(L?.type,o(c)),endpoint:L?.target??"n/a",fileName:c.file,repository:s?.(c),origin:l,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},y=new Map;for(let _ of c.reran?.tests??[]){let L=y.get(_.case);(!L||m[_.status]<m[L.status])&&y.set(_.case,_)}let E=y.size>0,w=_=>_===void 0?void 0:_.status==="skip"?"Skipped":_.status==="pass"?"Pass":"Fail",C=u==null?"Skipped":u===0?"Pass":"Fail",k=u!=null&&!E&&A.length>1,b=l==="existing"&&E&&!A.some(_=>_&&y.has(_)),I=[...y.values()],S=I.some(_=>_.status==="fail")?"Fail":I.some(_=>_.status==="pass")?"Pass":"Skipped",B=_=>{if(b)return S;let L=w(_?y.get(_):void 0);return L||(E||k?"Skipped":C)},q=[...y.entries()].filter(([,_])=>_.status==="fail").map(([_])=>_),N=I.filter(_=>_.status==="pass").length,O=[q.length&&`${q.length} failed (${q.slice(0,5).join(", ")})`,N&&`${N} passed`].filter(Boolean).join(", "),$=A.filter(_=>B(_)==="Fail").length,z=$===1&&c.finding?"failed \u2014 caught a real bug in the change":$===1&&c.repro?"fails as intended \u2014 reproduces the reported bug":"failed",J=$===1&&!!(c.finding||c.repro);for(let _ of A){let L=_?t.get(_):void 0,Q={testId:_,testType:Bx(L?.type,o(c)),endpoint:L?.target??"n/a",fileName:c.file,repository:s?.(c),origin:l},K=_?y.get(_):void 0,oe=B(_);if(b&&oe!=="Skipped")a.push({...Q,status:oe,details:`${oe==="Fail"?"failed":"passed"}: ${O}`.slice(0,400)});else if(oe==="Skipped"){let de=K===void 0&&!b&&(E||k),Ue=de?"no result recorded for this case":c.reran?.details?.slice(0,300)||ht.rows.notRun(i.expected),kt=de?void 0:Uz(c.reran?.details),H=!kt&&K===void 0&&!de&&u===null;kt?a.push({...Q,...Oz(kt)}):a.push({...Q,status:"Skipped",details:Ue,...H?{failureCause:{kind:"environment",family:"app_not_started"}}:{}})}else if(oe==="Pass")a.push({...Q,status:"Pass",details:K?ht.rows.passed(i.deployed):c.reran?.details?.slice(0,300)||ht.rows.passed(i.deployed)});else{let de=K?$===1&&c.reran?.details?c.reran.details.slice(0,200):c.from?n.get(`${c.from}::${_}`):void 0:c.reran?.details?c.reran.details.slice(0,200):void 0;a.push({...Q,status:"Fail",details:`${z}${de?`: ${de}`:""}`.slice(0,400),...J?{failureCause:{kind:"application"}}:{}})}}}return a}function Bx(e,t){return t==="ui"||t==="unit"?t:e??t??"integration"}function jz(e){return e==="place"?"new":e==="update"||e==="regenerate"?"updated":"existing"}function VCe(e,t){let n=(t?.results??[]).filter(BQ),r=(t?.notRun??[]).filter(i=>i.origin==="written");if(!n.length&&!r.length)return e;let s=(i,o,a)=>o===i.fileName&&(!a||!i.repository||a===i.repository);return e.map(i=>{let o=n.filter(A=>s(i,A.file,A.repository)),a=o.filter(A=>!!i.testId&&A.behaviorIds.includes(i.testId)),c=a.filter(A=>A.status==="Pass"||A.status==="Fail"),{failureCause:u,...l}=i;if(c.length){let A=c.find(m=>m.status==="Fail");return A?{...l,status:"Fail",details:`failed when Testbot re-ran it${i.status==="Fail"?"":" (write's own run reported it passing)"}: ${A.details}`.slice(0,400),...i.status==="Fail"&&u&&!A.fromFile?{failureCause:u}:{}}:{...l,status:"Pass",details:`passed when Testbot re-ran it${i.status==="Fail"?" (write's own run reported a failure)":""}`}}let d=r.find(A=>s(i,A.file,A.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 h=i.status==="Skipped"?Uz(d):void 0;return h?{...l,...Oz(h)}:{...i,details:`${i.details} \u2014 write's own run; Testbot could not re-run it: ${d}`.slice(0,400)}})}function mc(e){let t=Y(e,"analyze.json"),n=Y(e,"recommend.json"),r=Y(e,"generate.json"),s=Y(e,"generate-ui.json"),i=Y(e,"adapt.json"),o=Y(e,"finalize.json"),a=new Map((n?.generate??[]).map(H=>[H.id,H])),c=[...r?.tests??[],...s?.tests??[]],u=(i?.items??[]).filter(H=>H.file),l=(H,be)=>{let Ft=Xe(e.inputs,be)?.path??e.inputs.repositoryPath;return Ft?g2(Ft,H):void 0},d=[],h=new Set,A=(H,be,Ft)=>{let Ye=`${Ft}:${H}`;if(h.has(Ye))return;h.add(Ye);let Gt=be?.length?be:[Oa(H)];for(let dr of Gt){let Tt=a.get(dr);d.push({testId:dr,testType:Bx(Tt?.type,l(H,Ft)),endpoint:Tt?.target??"n/a",fileName:H,description:Tt?.rationale??`Generated test ${H}`,reasoning:Tt?.expected_observable??"covers a recommended case",repository:Ft})}};for(let H of c){let be=u.find(Ft=>Ft.from===H.file);!be||be.action!=="place"||A(be.file,H.covers,Wn(e,be.repository))}for(let H of u.filter(be=>be.from&&be.action==="place"))A(H.file,H.covers,Wn(e,H.repository));let m=new Map;for(let H of c)for(let be of H.assertions??[])m.set(`${H.file}::${be.case}`,be.evidence);let y=new Map(c.map(H=>[H.file,H.covers??[]])),E=Ag(e),w=VCe(qCe(u,a,m,y,H=>Wn(e,H.repository),E,H=>l(H.file,H.repository)),Wo(e)),C=new Map((t?.behaviors??[]).map(H=>[H.id,H.surface])),k=H=>H.map(be=>C.get(be)).find(Boolean)??"n/a",b=Y(e,Zt),I=b?.tests??[];for(let H of I)for(let be of H.names)d.push({testId:kx(H.file,be),testType:"unit",endpoint:k(H.covers),fileName:H.file,description:Lz(H.assertions).slice(0,400),reasoning:`native ${H.framework} unit test for ${H.covers.join(", ")}`,repository:Wn(e,H.repository)});let S=new Map;for(let H of I)for(let be of H.covers){let Ft=`${H.file}\0${be}`,Ye=S.get(Ft)??new Set;for(let Gt of H.assertions)Ye.add(Gt.source.replace(/_/g," "));S.set(Ft,Ye)}let B=H=>{let be=[...new Set(H.behaviorIds.flatMap(Ft=>[...S.get(`${H.file}\0${Ft}`)??[]]))];return H.status!=="Fail"||H.origin!=="generated"||!be?.length?H.details:`fails \u2014 the code disagrees with what this new test asserts (from the ${be.join(", ")}): ${H.details}`.slice(0,300)},q=Wo(e)?.results??[],N=b?.maintained??[],O=OCe($Ce(n,u,e,E),UCe(N,q,e)),$=H=>kx(H.file,H.selectedName??H.name),z=(H,be)=>`${Wn(e,H).toLowerCase()}\0${be}`,J=new Set(q.filter(H=>H.origin!=="written"&&H.name!==Lt).map(H=>z(H.repository,H.file))),_=[];for(let H=w.length-1;H>=0;H--)w[H].origin==="existing"&&J.has(z(w[H].repository,w[H].fileName))&&_.unshift(...w.splice(H,1).filter(be=>be.testId));let L=new Set([...N.filter(H=>H.change==="updated").map(H=>`${Wn(e,H.repository).toLowerCase()}\0${Ow(H.file)}`),...u.filter(H=>jz(H.action)==="updated").map(H=>`${Wn(e,H.repository).toLowerCase()}\0${H.file}`)]),Q=H=>H.origin==="generated"?"new":H.written||L.has(`${Wn(e,H.repository).toLowerCase()}\0${H.file}`)?"updated":"existing";for(let H of q.filter(be=>be.origin!=="written"))w.push({...H.name!==Lt?{testId:$(H)}:{},testType:"unit",endpoint:k(H.behaviorIds),status:H.status,details:B(H),fileName:H.file,repository:H.repository,resultId:KQ(H.repository,"unit",H.file,H.name),origin:Q(H),...H.status==="Fail"&&H.origin==="generated"&&H.name!==Lt&&!H.fromFile?{failureCause:{kind:"application"}}:{}});let K=[...I.flatMap(H=>H.names.map(be=>({testId:kx(H.file,be),behaviorIds:H.covers,written:!0,tested:!1}))),...q.filter(H=>H.origin!=="written"&&H.name!==Lt&&!H.fromFile&&H.status!=="Skipped").map(H=>({testId:$(H),behaviorIds:H.behaviorIds,written:!1,tested:!0}))],oe=GCe(e,i,o,w),Ue=(Y(e,as)?.packages??[]).filter(H=>u.some(be=>!be.repository&&be.action!=="delete"&&hi(be.file,[H.dir]))).map(H=>({directory:H.dir,runner:H.runner,entrypoint:H.entrypoint,created:H.created,...e.inputs.repositorySlug?{repository:e.inputs.repositorySlug}:{}})),kt=(o?.dependencies?.added??[]).map(H=>({package:H.package,manifest:H.manifest,...H.reason?{reason:H.reason}:{},...H.repository?{repository:H.repository}:{}}));return{testPackages:Ue,dependencyChanges:kt,caseEvidence:_,newTestsCreated:d,testMaintenance:O,testResults:w,caveats:oe,changes:LCe(t,n,u,[...w,..._],d,e,K),executionCoverage:jCe(d,u,w,N),commitMessage:o?.commit?.message?.trim()||"Skyramp Testbot: add generated tests",validation:_Q(e,oe),system:Ai(e)?.sutRequired||Y(e,`${un}.json`)||vp(e)?UR(e):void 0,testExecutionContexts:Ai(e)?.sutRequired===!1?void 0:_G(e,u,c)}}var Gz=f.string().trim().min(1),gg=f.object({schemaVersion:f.literal(1).optional(),businessCaseAnalysis:Gz.describe("1-2 sentences: what this change means for a user, and whether the evidence shows it working"),issuesFound:f.array(f.object({description:Gz,severity:f.string().optional().describe("critical | high | medium | low"),category:f.string().optional().describe("bug | lint | type | config"),sourceFile:f.string().optional(),sourceLine:f.number().optional(),findingId:f.string().optional(),requirementIds:f.array(f.string()).optional()})).describe("every real problem this run exposed \u2014 cause, file:line, severity"),nextSteps:f.array(f.string()).describe("concrete follow-ups the author can act on; required non-empty when a disclosure is BLOCKING")});function HCe(e){return _t(gg,e).errors}function mg(e,t=[]){let{value:n,error:r}=ft(e.stdout,t);if(r)return{errors:[r]};let s=HCe(n);return s.length>0?{errors:s}:{prose:n,errors:[]}}function rl(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(n=>n>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 qz=yn("report-schema",(e,t)=>mg(t,e.secretValues)),YCe=/\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,JCe=/\bmcp__[a-z0-9_]+\b|\bskyramp_[a-z][a-z0-9_]*\b/,Vz={name:"report-visibility",verify(e,t){let{prose:n,errors:r}=mg(t,e.secretValues);if(!n)return se(this.name,r);let s=rI(e,rl(mc(e),n));return s.length===0?{name:this.name,passed:!0}:se(this.name,s)}};function rI(e,t){let n=[],r=Y(e,"deploy.json");e.state.stages.deploy?.status==="passed"&&!r&&n.push("deploy passed but deploy.json is unreadable \u2014 cannot verify its outcome / mocked deps were surfaced");let s=Y(e,"adapt.json");for(let u of(s?.items??[]).filter(l=>l.finding&&l.file)){let l=Oa(u.file);t.issuesFound.some(h=>`${h.description} ${h.sourceFile??""}`.toLowerCase().includes(l))||n.push(`adapt marked "${u.file}" finding:true (a real bug caught) but no issuesFound entry names that test \u2014 surface the bug`)}let i=Y(e,"recommend.json");if(e.state.stages.recommend?.status==="passed"&&i?.generate){let u=new Set(t.newTestsCreated.map(d=>d.testId.toLowerCase())),l=(t.nextSteps.join(" ")+" "+t.issuesFound.map(d=>d.description).join(" ")).toLowerCase();for(let d of i.generate){let h=d.id?.trim();h&&!u.has(h.toLowerCase())&&!l.includes(h.toLowerCase())&&n.push(`recommended case "${h}" is neither a test in newTestsCreated nor named in nextSteps/issuesFound \u2014 say what happened to it`)}}let o=(t.caveats??[]).filter(u=>u.blocking);o.length>0&&t.nextSteps.length===0&&n.push(`this run is not evidence the change works (${o.map(u=>u.kind).join(", ")}) and nextSteps is empty \u2014 say what the author should do about it`);let a=`${t.businessCaseAnalysis} ${t.issuesFound.map(u=>u.description).join(" ")} ${t.nextSteps.join(" ")}`,c=a.match(YCe)??a.match(JCe);return c&&n.push(`user-facing text leaks internal machinery ("${c[0]}") \u2014 describe the code/repo, not the testbot's stages, gates, tools or artifact files`),n}function Hz(e,t){let{prose:n,errors:r}=mg(t,e.secretValues);return Fe(e,"report",n?rl(mc(e),n):void 0,r)}var $x=j(require("fs")),sl=j(require("path"));var Yz=j(require("fs"));var iI=2*1024*1024;function Nx(e){let t=[];for(let n of e??[])if(n.state==="read")try{t.push({item:n,text:Yz.readFileSync(IY(n),"utf-8")})}catch{}return t}var sI=6,WCe=/[\p{L}\p{N}]+/gu,zCe=new RegExp("(?<=\\p{Ll})(?=\\p{Lu})|(?<=\\p{Lu})(?=\\p{Lu}\\p{Ll})","u");function Jz(e){let t=[];for(let n of e.matchAll(WCe)){let r=n.index;for(let s of n[0].split(zCe))t.push({word:s.toLowerCase(),start:r,end:r+s.length}),r+=s.length}return t}var Wz=(e,t)=>e.slice(t,t+sI).map(n=>n.word).join(" ");function yc(e){return Nx(e).map(({item:t,text:n})=>{let r=Jz(t.source==="other"?n:n.slice(n.indexOf(`
547
- `)+1||n.length)),s=new Set;for(let i=0;i+sI<=r.length;i++)s.add(Wz(r,i));return{name:Ad(t.key,Hn([t])),runs:s}})}function Dx(e,t){if(t.length===0)return[];let n=Jz(e),r=[];for(let s=0;s+sI<=n.length;s++){let i=Wz(n,s),o=t.find(l=>l.runs.has(i));if(!o)continue;let a=n[s].start,c=n[s+sI-1].end,u=r.at(-1);u&&a<=u.end?u.end=Math.max(u.end,c):r.push({start:a,end:c,name:o.name})}return r}function KCe(e,t){return[...new Set(Dx(e,t).map(n=>n.name))]}function Jp(e,t){let n=e;for(let r of Dx(e,t).reverse())n=`${n.slice(0,r.start)}(see ${r.name})${n.slice(r.end)}`;return n}var zz=new Set(["testId","testedBy","writtenBy","coveredBy","id"]),ZCe=new Set(["resultId","test","fileName","sourceFile","repository","maintainedBy"]);function Tx(e,t){return t!==void 0&&zz.has(t)?(Array.isArray(e)?e:[e]).filter(n=>typeof n=="string"):Array.isArray(e)?e.flatMap(n=>Tx(n)):e&&typeof e=="object"?Object.entries(e).flatMap(([n,r])=>Tx(r,n)):[]}function XCe(e,t){let n=new Set(Tx(e)),r=new Set(n),s=new Map;for(let i of n){let o=Dx(i,t);if(o.length===0)continue;let a=i;for(let u of[...o].reverse())a=`${a.slice(0,u.start)}${eIe(u.name)}${a.slice(u.end)}`;let c=a;for(let u=2;r.has(c);u++)c=`${a}-${u}`;r.add(c),s.set(i,c)}return s}var eIe=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");function xx(e,t,n,r,s=!1){return r!==void 0&&ZCe.has(r)?e:r!==void 0&&zz.has(r)?Array.isArray(e)?e.map(i=>n.get(i)??i):typeof e=="string"?n.get(e)??e:e:typeof e=="string"?s?e:Jp(e,t):Array.isArray(e)?e.map(i=>xx(i,t,n,void 0,s)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([i,o])=>[i,xx(o,t,n,i,s||i==="requirementReferences")])):e}function oI(e,t){return t.length===0?e:xx(e,t,XCe(e,t))}function tIe(e,t,n){for(let r=t+1;r<e.length;r++){let s=e[r];if(s==="\\")r++;else{if(s===n)return r+1;if(s===`
546
+ `)}var Mz=St({name:"finalize",model:"opus",timeoutMinutes:20,requires:[],branchRequires:{runtime:["adapt"],"no-runtime":["generate-unit"]},softRequires:["native-run"],prepare:e=>{let t=DCe(e);return{unitTestFiles:t,unitAssertionBaseline:Qz(e.inputs.repositoryPath,t),writtenBefore:[...ns(rs(e.inputs))]}},buildPrompt:FCe,buildReadDirs:e=>qi(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:*)",...SC],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:[kz,Rz,Pz,Fz,Bz,Tz,xz,bx],onPassed:Sx,afterAttempt:Nz,salvage:Dz});var wK=j(require("crypto")),bi=j(require("fs")),js=j(require("path"));function nI(e=process.env){return e.CLAUDE_CODE_USE_BEDROCK==="1"?"AWS Bedrock":"Anthropic"}var ZVe=ht.rows.notRun(!0),Ag=e=>({deployed:jf(e)||Ww(e),expected:Ai(e)?.sutRequired!==!1}),$z={deployed:!0,expected:!0},Rx="could not run here";function Uz(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(r=>r.test(t))))return t.replace(/^(?:not run|could not run here)[:.]?\s*/i,"")}var Oz=e=>({status:"Skipped",details:`${Rx}: ${e}`.slice(0,400),failureCause:{kind:"environment",family:"external_dependency"}}),gc="kept, not ",Yp="(declined the planned ";function Lz(e){return e.map(t=>t.expected===void 0?t.expectation:`${t.expectation} (${t.expected})`).join("; ")}function Qx(e){if(!e)return[];let t=[],n=0,r=0;for(let s=0;s<e.length;s++){let i=e[s];i==="("?n++:i===")"?n=Math.max(0,n-1):n===0&&i===";"&&e[s+1]===" "&&e[s-1]===")"&&(t.push(e.slice(r,s)),r=s+2)}return t.push(e.slice(r)),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(),u=i.slice(a+1,-1).trim();return c&&u?{expectation:c,expected:u}:{expectation:i}}return{expectation:i}})}var oa=new Set(["update","regenerate","delete"]),vx=e=>e==null?"Skipped":e===0?"Pass":"Fail";function Wn(e,t){return t?.trim()||Mt(e.inputs).slug}var _Ce={update:"updated",regenerate:"regenerated",delete:"deleted",verify:"verified",none:"touched"},MCe=e=>_Ce[e]??`${e}d`;function $Ce(e,t,n,r=$z){let s=ht.rows.notRun(r.expected),i=u=>Wn(n,u).toLowerCase(),o=(e?.maintenance??[]).map(u=>{let l=t.find(w=>i(w.repository)===i(u.repository)&&(w.file===u.test||w.from&&w.from===u.test)),d=!!l&&oa.has(l.action),h=u.action!=="verify",A=l?.action??u.action,m=d?A:oa.has(A)||A==="none"?"verify":A,y=l?.reran?.exit!=null?vx(l.reran.exit):void 0,E=(()=>{if(d){let w=l.action==="delete"?"removed":l.reran?.details??(l.reran?.exit==null?s:`exit ${l.reran.exit}`);if(!l.keptReason)return w;let C=`${Yp}${u.action}: ${l.keptReason})`.slice(0,200);return`${w.slice(0,300-C.length-1)} ${C}`}return l?.keptReason?`${gc}${MCe(A)}: ${l.keptReason}`.slice(0,300):h?`recommended ${u.action}, not applied this run`:"not applied this run"})();return{repository:Wn(n,u.repository),testType:"existing",endpoint:"n/a",fileName:l?.file??u.test,description:u.evidence,action:m,beforeStatus:"Unknown",beforeDetails:u.evidence,afterStatus:d?l.action==="delete"?"Skipped":vx(l.reran?.exit):y??"Unknown",afterDetails:E}}),a=u=>(e?.maintenance??[]).some(l=>i(u.repository)===i(l.repository)&&(u.file===l.test||u.from&&u.from===l.test)),c=t.filter(u=>oa.has(u.action)&&!a(u)).map(u=>({repository:Wn(n,u.repository),testType:"existing",endpoint:"n/a",fileName:u.file,description:"found stale while running the existing tests",action:u.action,beforeStatus:"Unknown",beforeDetails:"not in the plan's maintenance list",afterStatus:u.action==="delete"?"Skipped":vx(u.reran?.exit),afterDetails:u.action==="delete"?"removed":u.reran?.details??(u.reran?.exit==null?s:`exit ${u.reran.exit}`)}));return[...o,...c]}function UCe(e,t,n){let r=s=>Wn(n,s).toLowerCase();return(e??[]).map(s=>{let i=s.change==="deleted",o=Ow(s.file),a=i?[]:t.filter(y=>r(y.repository)===r(s.repository)&&y.file===o),c=a.filter(y=>y.status==="Fail"),u=a.filter(y=>y.status==="Pass").length,l=i?"Skipped":c.length?"Fail":u?"Pass":a.length?"Skipped":"Unknown",d=a.length-c.length-u,h=[c.length&&`${c.length} failed`,u&&`${u} passed`,d&&`${d} skipped`].filter(Boolean).join(", "),A=o===s.file?"":` (run by ${o})`,m=i?"removed":a.length?`${h}${A}${c.length?`: ${c[0].details}`:""}`:"not re-run by this run's unit test run";return{repository:Wn(n,s.repository),testType:"existing",endpoint:"n/a",fileName:s.file,description:s.reason,action:i?"delete":"update",beforeStatus:"Unknown",beforeDetails:s.reason,afterStatus:l,afterDetails:m.slice(0,300)}})}function OCe(e,t){let n=i=>`${(i.repository??"").toLowerCase()}\0${i.fileName}`,r=new Set(e.filter(i=>oa.has(i.action)).map(n)),s=new Set(t.map(n));return[...e.filter(i=>r.has(n(i))||!s.has(n(i))),...t.filter(i=>!r.has(n(i)))]}function LCe(e,t,n,r,s,i,o=[]){let a=e?.behaviors??[];if(!a.length)return[];let c=new Set(r.filter(w=>w.testId&&w.status!=="Skipped").map(w=>w.testId)),u=new Set(s.map(w=>w.testId)),l=new Map,d=new Map;for(let w of t?.generate??[]){if(!w.from_behavior||!u.has(w.id))continue;let C=d.get(w.from_behavior)??[];if(C.includes(w.id)||C.push(w.id),d.set(w.from_behavior,C),!c.has(w.id))continue;let k=l.get(w.from_behavior)??[];k.includes(w.id)||k.push(w.id),l.set(w.from_behavior,k)}let h=w=>i?Wn(i,w).toLowerCase():"",A=w=>i?xe(i.inputs,w):"",m=new Map;for(let w of t?.maintenance??[]){let C=n.find(b=>h(b.repository)===h(w.repository)&&(b.file===w.test||b.from&&b.from===w.test));if(!C||!oa.has(C.action))continue;let k=`${A(C.repository)}${C.file}`;for(let b of w.covers_behaviors??[]){let I=m.get(b)??[];I.includes(k)||I.push(k),m.set(b,I)}}let y=(w,C)=>o.filter(k=>C(k)&&k.behaviorIds.includes(w)).map(k=>k.testId),E=(w,C)=>[...new Set([...w,...C])].slice(0,Rp);return a.slice(0,zQ).map(w=>({id:w.id,text:w.statement,source:w.evidence.slice(0,WQ),testedBy:E(l.get(w.id)??[],y(w.id,C=>C.tested)),writtenBy:E(d.get(w.id)??[],y(w.id,C=>C.written)),maintainedBy:(m.get(w.id)??[]).slice(0,Rp)}))}var kx=(e,t)=>`${Oa(e)}::${t}`;function jCe(e,t,n,r=[]){let s=i=>!(i.action==="delete"&&i.from);return{generated:e.length,modified:t.filter(i=>oa.has(i.action)&&s(i)).length+(r??[]).length,verified:t.filter(i=>s(i)&&(i.action==="verify"||!!i.keptReason)&&!oa.has(i.action)).length,executed:n.filter(i=>i.status!=="Skipped").length}}function GCe(e,t,n,r){let s=[],i=Y(e,"deploy.json"),o=E=>e.state.stages[E]?.status==="failed",a=e.state.modelProviderFailure,c=E=>o(E)&&a?.stage!==E&&!e.state.stages[E]?.reason?.startsWith("not run \u2014 the model provider refused");(c("deploy")||c("plan"))&&!i&&s.push({kind:"deploy-failed",text:ht.caveats.deployFailed,blocking:!0});let u=(t?.items??[]).filter(E=>E.action!=="delete"),l=u.filter(E=>E.reran?.exit===null||E.reran?.exit===void 0);u.length>0&&l.length===u.length&&s.push({kind:"tests-not-executed",text:ht.caveats.testsNotExecuted,blocking:!0}),i?.outcome&&i.outcome!=="clean"&&!Ww(e)&&s.push(i.outcome==="change-broke-bringup"?{kind:"deploy-failed",subject:"change",text:ht.caveats.changeBrokeBringup,blocking:!0}:i.outcome==="bringup-failed"?{kind:"deploy-failed",text:ht.caveats.bringupFailed,blocking:!0}:{kind:"recipe-drift",text:ht.caveats.recipeDrift,blocking:!1});for(let[E,w]of Object.entries(i?.dependencies??{}))w===!1&&s.push({kind:"mocked-dependency",subject:E,text:ht.caveats.mockedDependency(E),blocking:!1});if(n?.ready===!1||o("finalize")||o("write")){let E=(n?.blockers??[]).slice(0,3).join("; ");s.push({kind:"finalize-not-ready",text:ht.caveats.finalizeNotReady(E),blocking:!0})}Ai(e)?.sutRequired===!1&&s.push({kind:"sut-not-required",text:ht.caveats.sutNotRequired,blocking:!1});let d=Fp(e);d.length&&s.push({kind:"analysis-unverified",text:ht.caveats.analysisUnverified(d.length),blocking:!1});let h=Gw(Wo(e)??{results:[],notRun:[]});h&&s.push({kind:"unit-tests-not-run",text:ht.caveats.unitTestsNotRun(h),blocking:!1});let A=(r??[]).filter(E=>E.status==="Skipped"&&E.details?.startsWith(`${Rx}:`));A.length&&s.push({kind:"tests-could-not-run-here",text:ht.caveats.testsCouldNotRunHere(A.length,A[0].details.slice(Rx.length+2)),blocking:!1});let m=FQ(e).map(E=>E.behaviorId?`${E.behaviorId}: ${E.missing}`:E.missing);if(m.length&&s.push({kind:"downstream-not-checked",text:ht.caveats.downstreamNotChecked(m.join("; ")),blocking:!1}),a){let E=_Q(e,s),w=(r??[]).some(k=>k.status==="Pass"||k.status==="Fail"),C=E?E.sufficiency==="sufficient"&&(E.acceptedEvidence.length>0||w):w;s.push(a.kind==="permanent"?{kind:"model-provider-denied",text:ht.caveats.modelProviderDenied(nI(),C),blocking:!C}:{kind:"model-provider-unavailable",text:ht.caveats.modelProviderUnavailable(nI(),C),blocking:!C})}n?.ciReadiness?.covered===!1&&s.push({kind:"ci-not-covered",text:ht.caveats.ciNotCovered,blocking:!1});let y=(n?.lint??[]).flatMap(E=>(E.uncovered??[]).map(w=>`${xe(e.inputs,E.repository)}${w}`));return y.length>0&&s.push({kind:"lint-not-covered",subject:y.join(", "),text:ht.caveats.lintNotCovered(y.join(", ")),blocking:!1}),s}function qCe(e,t,n,r,s,i=$z,o=()=>{}){let a=[];for(let c of e.filter(u=>u.action!=="delete")){let u=c.reran?.exit,l=jz(c.action),d=c.from?r.get(c.from):void 0,h=[...new Set([...c.covers??[],...d??[]])],A=h.length?h:[void 0];if(c.placementBroken){for(let _ of A){let L=_?t.get(_):void 0;a.push({testId:_,testType:Bx(L?.type,o(c)),endpoint:L?.target??"n/a",fileName:c.file,repository:s?.(c),origin:l,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},y=new Map;for(let _ of c.reran?.tests??[]){let L=y.get(_.case);(!L||m[_.status]<m[L.status])&&y.set(_.case,_)}let E=y.size>0,w=_=>_===void 0?void 0:_.status==="skip"?"Skipped":_.status==="pass"?"Pass":"Fail",C=u==null?"Skipped":u===0?"Pass":"Fail",k=u!=null&&!E&&A.length>1,b=l==="existing"&&E&&!A.some(_=>_&&y.has(_)),I=[...y.values()],S=I.some(_=>_.status==="fail")?"Fail":I.some(_=>_.status==="pass")?"Pass":"Skipped",B=_=>{if(b)return S;let L=w(_?y.get(_):void 0);return L||(E||k?"Skipped":C)},q=[...y.entries()].filter(([,_])=>_.status==="fail").map(([_])=>_),N=I.filter(_=>_.status==="pass").length,O=[q.length&&`${q.length} failed (${q.slice(0,5).join(", ")})`,N&&`${N} passed`].filter(Boolean).join(", "),$=A.filter(_=>B(_)==="Fail").length,z=$===1&&c.finding?"failed \u2014 caught a real bug in the change":$===1&&c.repro?"fails as intended \u2014 reproduces the reported bug":"failed",J=$===1&&!!(c.finding||c.repro);for(let _ of A){let L=_?t.get(_):void 0,Q={testId:_,testType:Bx(L?.type,o(c)),endpoint:L?.target??"n/a",fileName:c.file,repository:s?.(c),origin:l},K=_?y.get(_):void 0,oe=B(_);if(b&&oe!=="Skipped")a.push({...Q,status:oe,details:`${oe==="Fail"?"failed":"passed"}: ${O}`.slice(0,400)});else if(oe==="Skipped"){let de=K===void 0&&!b&&(E||k),Ue=de?"no result recorded for this case":c.reran?.details?.slice(0,300)||ht.rows.notRun(i.expected),kt=de?void 0:Uz(c.reran?.details),H=!kt&&K===void 0&&!de&&u===null;kt?a.push({...Q,...Oz(kt)}):a.push({...Q,status:"Skipped",details:Ue,...H?{failureCause:{kind:"environment",family:"app_not_started"}}:{}})}else if(oe==="Pass")a.push({...Q,status:"Pass",details:K?ht.rows.passed(i.deployed):c.reran?.details?.slice(0,300)||ht.rows.passed(i.deployed)});else{let de=K?$===1&&c.reran?.details?c.reran.details.slice(0,200):c.from?n.get(`${c.from}::${_}`):void 0:c.reran?.details?c.reran.details.slice(0,200):void 0;a.push({...Q,status:"Fail",details:`${z}${de?`: ${de}`:""}`.slice(0,400),...J?{failureCause:{kind:"application"}}:{}})}}}return a}function Bx(e,t){return t==="ui"||t==="unit"?t:e??t??"integration"}function jz(e){return e==="place"?"new":e==="update"||e==="regenerate"?"updated":"existing"}function VCe(e,t){let n=(t?.results??[]).filter(BQ),r=(t?.notRun??[]).filter(i=>i.origin==="written");if(!n.length&&!r.length)return e;let s=(i,o,a)=>o===i.fileName&&(!a||!i.repository||a===i.repository);return e.map(i=>{let o=n.filter(A=>s(i,A.file,A.repository)),a=o.filter(A=>!!i.testId&&A.behaviorIds.includes(i.testId)),c=a.filter(A=>A.status==="Pass"||A.status==="Fail"),{failureCause:u,...l}=i;if(c.length){let A=c.find(m=>m.status==="Fail");return A?{...l,status:"Fail",details:`failed when Testbot re-ran it${i.status==="Fail"?"":" (write's own run reported it passing)"}: ${A.details}`.slice(0,400),...i.status==="Fail"&&u&&!A.fromFile?{failureCause:u}:{}}:{...l,status:"Pass",details:`passed when Testbot re-ran it${i.status==="Fail"?" (write's own run reported a failure)":""}`}}let d=r.find(A=>s(i,A.file,A.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 h=i.status==="Skipped"?Uz(d):void 0;return h?{...l,...Oz(h)}:{...i,details:`${i.details} \u2014 write's own run; Testbot could not re-run it: ${d}`.slice(0,400)}})}function mc(e){let t=Y(e,"analyze.json"),n=Y(e,"recommend.json"),r=Y(e,"generate.json"),s=Y(e,"generate-ui.json"),i=Y(e,"adapt.json"),o=Y(e,"finalize.json"),a=new Map((n?.generate??[]).map(H=>[H.id,H])),c=[...r?.tests??[],...s?.tests??[]],u=(i?.items??[]).filter(H=>H.file),l=(H,be)=>{let Ft=Xe(e.inputs,be)?.path??e.inputs.repositoryPath;return Ft?g2(Ft,H):void 0},d=[],h=new Set,A=(H,be,Ft)=>{let Ye=`${Ft}:${H}`;if(h.has(Ye))return;h.add(Ye);let Gt=be?.length?be:[Oa(H)];for(let dr of Gt){let Tt=a.get(dr);d.push({testId:dr,testType:Bx(Tt?.type,l(H,Ft)),endpoint:Tt?.target??"n/a",fileName:H,description:Tt?.rationale??`Generated test ${H}`,reasoning:Tt?.expected_observable??"covers a recommended case",repository:Ft})}};for(let H of c){let be=u.find(Ft=>Ft.from===H.file);!be||be.action!=="place"||A(be.file,H.covers,Wn(e,be.repository))}for(let H of u.filter(be=>be.from&&be.action==="place"))A(H.file,H.covers,Wn(e,H.repository));let m=new Map;for(let H of c)for(let be of H.assertions??[])m.set(`${H.file}::${be.case}`,be.evidence);let y=new Map(c.map(H=>[H.file,H.covers??[]])),E=Ag(e),w=VCe(qCe(u,a,m,y,H=>Wn(e,H.repository),E,H=>l(H.file,H.repository)),Wo(e)),C=new Map((t?.behaviors??[]).map(H=>[H.id,H.surface])),k=H=>H.map(be=>C.get(be)).find(Boolean)??"n/a",b=Y(e,Zt),I=b?.tests??[];for(let H of I)for(let be of H.names)d.push({testId:kx(H.file,be),testType:"unit",endpoint:k(H.covers),fileName:H.file,description:Lz(H.assertions).slice(0,400),reasoning:`native ${H.framework} unit test for ${H.covers.join(", ")}`,repository:Wn(e,H.repository)});let S=new Map;for(let H of I)for(let be of H.covers){let Ft=`${H.file}\0${be}`,Ye=S.get(Ft)??new Set;for(let Gt of H.assertions)Ye.add(Gt.source.replace(/_/g," "));S.set(Ft,Ye)}let B=H=>{let be=[...new Set(H.behaviorIds.flatMap(Ft=>[...S.get(`${H.file}\0${Ft}`)??[]]))];return H.status!=="Fail"||H.origin!=="generated"||!be?.length?H.details:`fails \u2014 the code disagrees with what this new test asserts (from the ${be.join(", ")}): ${H.details}`.slice(0,300)},q=Wo(e)?.results??[],N=b?.maintained??[],O=OCe($Ce(n,u,e,E),UCe(N,q,e)),$=H=>kx(H.file,H.selectedName??H.name),z=(H,be)=>`${Wn(e,H).toLowerCase()}\0${be}`,J=new Set(q.filter(H=>H.origin!=="written"&&H.name!==Lt).map(H=>z(H.repository,H.file))),_=[];for(let H=w.length-1;H>=0;H--)w[H].origin==="existing"&&J.has(z(w[H].repository,w[H].fileName))&&_.unshift(...w.splice(H,1).filter(be=>be.testId));let L=new Set([...N.filter(H=>H.change==="updated").map(H=>`${Wn(e,H.repository).toLowerCase()}\0${Ow(H.file)}`),...u.filter(H=>jz(H.action)==="updated").map(H=>`${Wn(e,H.repository).toLowerCase()}\0${H.file}`)]),Q=H=>H.origin==="generated"?"new":H.written||L.has(`${Wn(e,H.repository).toLowerCase()}\0${H.file}`)?"updated":"existing";for(let H of q.filter(be=>be.origin!=="written"))w.push({...H.name!==Lt?{testId:$(H)}:{},testType:"unit",endpoint:k(H.behaviorIds),status:H.status,details:B(H),fileName:H.file,repository:H.repository,resultId:KQ(H.repository,"unit",H.file,H.name),origin:Q(H),...H.status==="Fail"&&H.origin==="generated"&&H.name!==Lt&&!H.fromFile?{failureCause:{kind:"application"}}:{}});let K=[...I.flatMap(H=>H.names.map(be=>({testId:kx(H.file,be),behaviorIds:H.covers,written:!0,tested:!1}))),...q.filter(H=>H.origin!=="written"&&H.name!==Lt&&!H.fromFile&&H.status!=="Skipped").map(H=>({testId:$(H),behaviorIds:H.behaviorIds,written:!1,tested:!0}))],oe=GCe(e,i,o,w),Ue=(Y(e,as)?.packages??[]).filter(H=>u.some(be=>!be.repository&&be.action!=="delete"&&hi(be.file,[H.dir]))).map(H=>({directory:H.dir,runner:H.runner,entrypoint:H.entrypoint,created:H.created,...e.inputs.repositorySlug?{repository:e.inputs.repositorySlug}:{}})),kt=(o?.dependencies?.added??[]).map(H=>({package:H.package,manifest:H.manifest,...H.reason?{reason:H.reason}:{},...H.repository?{repository:H.repository}:{}}));return{testPackages:Ue,dependencyChanges:kt,caseEvidence:_,newTestsCreated:d,testMaintenance:O,testResults:w,caveats:oe,changes:LCe(t,n,u,[...w,..._],d,e,K),executionCoverage:jCe(d,u,w,N),commitMessage:o?.commit?.message?.trim()||"Skyramp Testbot: add generated tests",validation:_Q(e,oe),system:Ai(e)?.sutRequired||Y(e,`${un}.json`)||vp(e)?UR(e):void 0,testExecutionContexts:Ai(e)?.sutRequired===!1?void 0:_G(e,u,c)}}var Gz=f.string().trim().min(1),gg=f.object({schemaVersion:f.literal(1).optional(),businessCaseAnalysis:Gz.describe("1-2 sentences: what this change means for a user, and whether the evidence shows it working"),issuesFound:f.array(f.object({description:Gz,severity:f.string().optional().describe("critical | high | medium | low"),category:f.string().optional().describe("bug | lint | type | config"),sourceFile:f.string().optional(),sourceLine:f.number().optional(),findingId:f.string().optional(),requirementIds:f.array(f.string()).optional()})).describe("every real problem this run exposed \u2014 cause, file:line, severity"),nextSteps:f.array(f.string()).describe("concrete follow-ups the author can act on; required non-empty when a disclosure is BLOCKING")});function HCe(e){return _t(gg,e).errors}function mg(e,t=[]){let{value:n,error:r}=ft(e.stdout,t);if(r)return{errors:[r]};let s=HCe(n);return s.length>0?{errors:s}:{prose:n,errors:[]}}function rl(e,t){let n={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}:{}},r=n.validation?.blockedPreflight;if(r){let s=r.repository?`${r.repository}/${r.file}`:r.file,i=`The change cannot build or start: ${r.reason} (${s}). ${r.evidence}`,o=`Correct the code in ${s}, then rerun validation.`;n.businessCaseAnalysis=`${i} ${o} No tests ran.`,n.issuesFound.some(a=>a.sourceFile===r.file&&a.description.includes(r.evidence))||n.issuesFound.push({description:i,severity:"high",category:"bug",sourceFile:r.file}),n.nextSteps.includes(o)||n.nextSteps.unshift(o)}return n}var qz=yn("report-schema",(e,t)=>mg(t,e.secretValues)),YCe=/\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,JCe=/\bmcp__[a-z0-9_]+\b|\bskyramp_[a-z][a-z0-9_]*\b/,Vz={name:"report-visibility",verify(e,t){let{prose:n,errors:r}=mg(t,e.secretValues);if(!n)return se(this.name,r);let s=rI(e,rl(mc(e),n));return s.length===0?{name:this.name,passed:!0}:se(this.name,s)}};function rI(e,t){let n=[],r=Y(e,"deploy.json");e.state.stages.deploy?.status==="passed"&&!r&&n.push("deploy passed but deploy.json is unreadable \u2014 cannot verify its outcome / mocked deps were surfaced");let s=Y(e,"adapt.json");for(let u of(s?.items??[]).filter(l=>l.finding&&l.file)){let l=Oa(u.file);t.issuesFound.some(h=>`${h.description} ${h.sourceFile??""}`.toLowerCase().includes(l))||n.push(`adapt marked "${u.file}" finding:true (a real bug caught) but no issuesFound entry names that test \u2014 surface the bug`)}let i=Y(e,"recommend.json");if(e.state.stages.recommend?.status==="passed"&&i?.generate){let u=new Set(t.newTestsCreated.map(d=>d.testId.toLowerCase())),l=(t.nextSteps.join(" ")+" "+t.issuesFound.map(d=>d.description).join(" ")).toLowerCase();for(let d of i.generate){let h=d.id?.trim();h&&!u.has(h.toLowerCase())&&!l.includes(h.toLowerCase())&&n.push(`recommended case "${h}" is neither a test in newTestsCreated nor named in nextSteps/issuesFound \u2014 say what happened to it`)}}let o=(t.caveats??[]).filter(u=>u.blocking);o.length>0&&t.nextSteps.length===0&&n.push(`this run is not evidence the change works (${o.map(u=>u.kind).join(", ")}) and nextSteps is empty \u2014 say what the author should do about it`);let a=`${t.businessCaseAnalysis} ${t.issuesFound.map(u=>u.description).join(" ")} ${t.nextSteps.join(" ")}`,c=a.match(YCe)??a.match(JCe);return c&&n.push(`user-facing text leaks internal machinery ("${c[0]}") \u2014 describe the code/repo, not the testbot's stages, gates, tools or artifact files`),n}function Hz(e,t){let{prose:n,errors:r}=mg(t,e.secretValues);return Fe(e,"report",n?rl(mc(e),n):void 0,r)}var $x=j(require("fs")),sl=j(require("path"));var Yz=j(require("fs"));var iI=2*1024*1024;function Nx(e){let t=[];for(let n of e??[])if(n.state==="read")try{t.push({item:n,text:Yz.readFileSync(IY(n),"utf-8")})}catch{}return t}var sI=6,WCe=/[\p{L}\p{N}]+/gu,zCe=new RegExp("(?<=\\p{Ll})(?=\\p{Lu})|(?<=\\p{Lu})(?=\\p{Lu}\\p{Ll})","u");function Jz(e){let t=[];for(let n of e.matchAll(WCe)){let r=n.index;for(let s of n[0].split(zCe))t.push({word:s.toLowerCase(),start:r,end:r+s.length}),r+=s.length}return t}var Wz=(e,t)=>e.slice(t,t+sI).map(n=>n.word).join(" ");function yc(e){return Nx(e).map(({item:t,text:n})=>{let r=Jz(t.source==="other"?n:n.slice(n.indexOf(`
547
+ `)+1||n.length)),s=new Set;for(let i=0;i+sI<=r.length;i++)s.add(Wz(r,i));return{name:Ad(t.key,Hn([t])),runs:s}})}function Dx(e,t){if(t.length===0)return[];let n=Jz(e),r=[];for(let s=0;s+sI<=n.length;s++){let i=Wz(n,s),o=t.find(l=>l.runs.has(i));if(!o)continue;let a=n[s].start,c=n[s+sI-1].end,u=r.at(-1);u&&a<=u.end?u.end=Math.max(u.end,c):r.push({start:a,end:c,name:o.name})}return r}function KCe(e,t){return[...new Set(Dx(e,t).map(n=>n.name))]}function Jp(e,t){let n=e;for(let r of Dx(e,t).reverse())n=`${n.slice(0,r.start)}(see ${r.name})${n.slice(r.end)}`;return n}var zz=new Set(["testId","testedBy","writtenBy","coveredBy","id"]),ZCe=new Set(["resultId","test","file","fileName","sourceFile","repository","maintainedBy"]);function Tx(e,t){return t!==void 0&&zz.has(t)?(Array.isArray(e)?e:[e]).filter(n=>typeof n=="string"):Array.isArray(e)?e.flatMap(n=>Tx(n)):e&&typeof e=="object"?Object.entries(e).flatMap(([n,r])=>Tx(r,n)):[]}function XCe(e,t){let n=new Set(Tx(e)),r=new Set(n),s=new Map;for(let i of n){let o=Dx(i,t);if(o.length===0)continue;let a=i;for(let u of[...o].reverse())a=`${a.slice(0,u.start)}${eIe(u.name)}${a.slice(u.end)}`;let c=a;for(let u=2;r.has(c);u++)c=`${a}-${u}`;r.add(c),s.set(i,c)}return s}var eIe=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");function xx(e,t,n,r,s=!1){return r!==void 0&&ZCe.has(r)?e:r!==void 0&&zz.has(r)?Array.isArray(e)?e.map(i=>n.get(i)??i):typeof e=="string"?n.get(e)??e:e:typeof e=="string"?s?e:Jp(e,t):Array.isArray(e)?e.map(i=>xx(i,t,n,void 0,s)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([i,o])=>[i,xx(o,t,n,i,s||i==="requirementReferences")])):e}function oI(e,t){return t.length===0?e:xx(e,t,XCe(e,t))}function tIe(e,t,n){for(let r=t+1;r<e.length;r++){let s=e[r];if(s==="\\")r++;else{if(s===n)return r+1;if(s===`
548
548
  `&&n!=="`")return r}}return e.length}function nIe(e,t){let n=e.lastIndexOf(`
549
549
  `,t-1)+1;if(e.slice(n,t).trim()!=="")return!1;let r=e.slice(0,n).trimEnd();return r===""||r.endsWith(":")}function Kz(e){let t=[],n=s=>(e.indexOf(`
550
550
  `,s)+1||e.length+1)-1,r=0;for(;r<e.length;){let s=e[r],i=e[r+1],o=r+1;if(s==="/"&&i==="*")o=e.indexOf("*/",r+2)<0?e.length:e.indexOf("*/",r+2)+2,t.push({start:r,end:o});else if(s==="/"&&i==="/"&&!/[:\w]/.test(e[r-1]??"")||s==="#"&&/^\s?$/.test(e[r-1]??"")&&!/[!{[]/.test(i??""))o=n(r),t.push({start:r,end:o});else if((s==='"'||s==="'")&&e.startsWith(s.repeat(3),r)){let a=e.indexOf(s.repeat(3),r+3);o=a<0?e.length:a+3,nIe(e,r)&&t.push({start:r,end:o})}else(s==='"'||s==="'"||s==="`")&&(o=tIe(e,r,s));r=o}return t}var rIe=/\b(?:test|it|describe|context|suite|scenario|specify|Run|DisplayName)(?:\.\w+)*(?:\.each\s*(?:\((?:[^()]|\([^()]*\))*\)|`[^`]*`))?\s*\(\s*("(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`)/g;function Zz(e,t){return[...e.matchAll(rIe)].flatMap(n=>{if(t.some(s=>n.index>=s.start&&n.index<s.end))return[];let r=n.index+n[0].length;return[{start:r-n[1].length,end:r}]})}function Xz(e,t){if(t.length===0)return{content:e,cleaned:!1};let n=Kz(e),r=[];for(let a of n){let c=e.slice(a.start,a.end),u=Jp(c,t);u!==c&&r.push({...a,text:u})}let s=Zz(e,n),i=new Set(s.map(a=>e.slice(a.start+1,a.end-1)));for(let a of s){let c=e[a.start],u=e.slice(a.start+1,a.end-1),l=Jp(u,t);if(l===u)continue;let d=l;for(let h=2;i.has(d);h++)d=`${l} (${h})`;i.add(d),r.push({...a,text:`${c}${d}${c}`})}let o=e;for(let a of r.sort((c,u)=>u.start-c.start))o=`${o.slice(0,a.start)}${a.text}${o.slice(a.end)}`;return{content:o,cleaned:o!==e}}var sIe=/\b(?:def|func|function|fun|void|async\s+def)\s+([Tt]est\w*)/g;function eK(e,t){let n=Kz(e),r=[...n,...Zz(e,n)].map(s=>e.slice(s.start,s.end));for(let s of e.matchAll(sIe))r.push(s[1]);return[...new Set(r.flatMap(s=>KCe(s,t)))]}var aI=j(require("fs")),yg=j(require("path"));var tK=12,iIe=/^(?:Description|Acceptance criteria):[ \t]*$/gm;function Px(e){return Nx(e).map(({item:t,text:n})=>({item:t,text:t.source==="jira"?n.replace(iIe,""):n}))}var nK=e=>new Map(Px(e).map(({item:t,text:n})=>[gn(t.key),n])),rK=e=>Ps(e).replace(/^["']+|["']+$/g,"").trim(),sK=e=>[e.evidence,_u(e.evidence)].filter(t=>!!(t&&rK(t).length>=tK));function Wp(e,t){return sK(e).find(r=>Xf(t,r))?.trim().replace(/^["'\u201c\u2018]+|["'\u201d\u2019]+$/g,"").trim()}var oIe=e=>new Map((e??[]).flatMap(t=>t.state==="read"&&Vu(t.file)&&!eT(t.path)?[[gn(t.key),Hu(t.path)]]:[]));function aIe(e,t,n){let r=e.reference?.trim();if(!n||!r||(t??[]).some(o=>gn(o.key)===gn(r)))return!1;let s=yg.resolve(n),i=yg.resolve(s,r.replace(/:\d+(?:-\d+)?$/,""));if(!i.startsWith(s+yg.sep))return!1;try{if(!aI.statSync(i).isFile())return!1;let o=aI.readFileSync(i,"utf8");return Wp(e,o)!==void 0}catch{return!1}}function cIe(e){return iK({...e,source:"spec",evidence:`${e.reference}: ${e.evidence}`})}function iK(e){let t={...e};return delete t.reference,delete t.criterion,delete t.notInChange,t}function uIe(e,t,n){let r=e.reference?.trim();return r&&(t??[]).some(s=>gn(s.key)===gn(r))?!1:n.some(s=>Wp(e,s)!==void 0)}function oK(e,t,n,r){if(e.source==="requirement-reference"){if(aIe(e,t,n))return cIe(e);if(uIe(e,t,r))return iK({...e,source:"pr-description"})}}function aK(e,t,n=new Map){let r=e.reference===void 0?void 0:gn(e.reference);if(!r)return'names no item: give "reference", the key of the item it comes from';let s=t.get(r);return n.has(r)?`names ${r}, an uploaded document with no extracted text: write the text you extracted to ${n.get(r)}`:s===void 0?`names ${r}, which is not an item this run read`:sK(e).length?Wp(e,s)!==void 0?void 0:`its evidence is not in ${r}: copy the item's own words`:`its evidence is not a quote of ${r} of at least ${tK} characters`}function Fx(e,t,n,r=[]){let s=e.requirements.filter(a=>a.source==="requirement-reference"&&!oK(a,t,n,r));if(!s.length)return[];let i=nK(t),o=oIe(t);return s.flatMap(a=>{let c=aK(a,i,o);return c?[{id:a.id,why:c}]:[]})}var lIe=/^\s*(?:[-*+•]\s+)?(?:\*\*)?(?:AC\s*[-#]?\s*(\d+)(?=[\s.):*,-]|$)|(\d+)[.)](?=\s))/i,cK=e=>{let t=lIe.exec(e),n=t?Number(t[1]??t[2]):0;return n>0?n:void 0};function dIe(e,t){let n=e.split(`