saffron-ai 0.9.7 → 0.9.8
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/CHANGELOG.md +155 -0
- package/README.md +2 -3
- package/dist-pkg/cli.js +200 -196
- package/package.json +2 -2
- package/skills/saffron/SKILL.md +2 -0
package/dist-pkg/cli.js
CHANGED
|
@@ -1,42 +1,44 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
2
|
+
import fe from"node:fs";import L from"node:path";import ay from"node:readline";import{Command as cy}from"commander";import zf from"node:fs";import Hf from"node:path";import{AstBuilder as qf,dialects as Qi,GherkinClassicTokenMatcher as Jf,Parser as Wf}from"@cucumber/gherkin";import{IdGenerator as Vf,StepKeywordType as Bs}from"@cucumber/messages";import Ji from"node:fs";import Ef from"node:path";import nn from"node:fs";import at from"node:path";var sn=/\{data:([A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+)\}/g,rn=at.resolve("data"),Ke,zi=process.cwd(),yr=new Map;function Ye(e,t="data",n){zi=at.resolve(e),rn=at.isAbsolute(t)?t:at.join(e,t),Ke=n?.trim()||void 0,yr.clear()}var Ae=()=>({dir:rn,env:Ke,root:zi});function Hi(e,t){let n=s=>s!==null&&typeof s=="object"&&!Array.isArray(s);if(!n(e)||!n(t))return t;let r={...e};for(let[s,o]of Object.entries(t))r[s]=s in e?Hi(e[s],o):o;return r}function Ui(e,t){try{return JSON.parse(nn.readFileSync(e,"utf8"))}catch(n){throw new Error(`data file ${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}}function Rf(e){if(yr.has(e))return yr.get(e);let t=at.join(rn,`${e}.json`),n=Ke?at.join(rn,`${e}.${Ke}.json`):void 0,r=nn.existsSync(t),s=n!==void 0&&nn.existsSync(n);if(!r&&!s)throw new Error(`data file ${at.relative(process.cwd(),t)||t} does not exist${Ke?` (nor ${e}.${Ke}.json for the "${Ke}" environment)`:""}`);let o=r?Ui(t,`${e}.json`):void 0;if(s){let i=Ui(n,`${e}.${Ke}.json`);o=r?Hi(o,i):i}return yr.set(e,o),o}function Mt(e){let[t,...n]=e.split("."),r=Rf(t),s=[t];for(let o of n){let i=r,a=i&&typeof i=="object"?Array.isArray(i)?i[Number(o)]:i[o]:void 0;if(a===void 0)throw new Error(`"${o}" does not exist under ${s.join(".")} (in ${t}.json)`);r=a,s.push(o)}return r}function on(e){let t;try{t=Mt(e)}catch(n){throw new Error(`{data:${e}}: ${n instanceof Error?n.message:String(n)}`)}if(t===null||typeof t=="object")throw new Error(`{data:${e}} is ${Array.isArray(t)?"a list":"an object"}, not a single value. Point at one entry, for example {data:${e}.${Array.isArray(t)?"0":Object.keys(t??{})[0]??"key"}}`);return String(t)}function vt(e){let t;try{t=Mt(e)}catch(s){throw new Error(`{data:${e}}: ${s instanceof Error?s.message:String(s)}`)}let n=Array.isArray(t)?t:[t];if(n.length===0)throw new Error(`{data:${e}} is an empty list: there is nothing to check`);let r=n.find(s=>s===null||typeof s=="object");if(r!==void 0)throw new Error(`{data:${e}} must be a list of plain values (text, numbers); it contains ${Array.isArray(r)?"a list":"an object"}`);return n.map(String)}function wr(e){vt(e)}function qi(e){return e.replace(sn,(t,n)=>{let r=vt(n);return Array.isArray(Mt(n))?`${t} (a data list, currently: ${r.map(o=>`"${o}"`).join(", ")})`:r[0]})}function Tf(e){let t=[],n=[],r="",s=!1;for(let o=0;o<e.length;o++){let i=e[o];s?i==='"'&&e[o+1]==='"'?(r+='"',o++):i==='"'?s=!1:r+=i:i==='"'&&r===""?s=!0:i===","?(n.push(r),r=""):i===`
|
|
3
3
|
`||i==="\r"?(i==="\r"&&e[o+1]===`
|
|
4
|
-
`&&o++,n.push(r),r="",n.some(a=>a!=="")&&t.push(n),n=[]):r+=i}return n.push(r),n.some(o=>o!=="")&&t.push(n),t.map(o=>o.map(i=>i.trim()))}function
|
|
5
|
-
`)){let r=n.trim();if(!r||r.startsWith("#"))continue;let s=r.indexOf("=");if(s<=0)continue;let o=r.slice(0,s).trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(o))continue;let i=r.slice(s+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),process.env[o]===void 0&&(process.env[o]=i)}}function
|
|
6
|
-
`),n=new Map,r=new Map;return{source:t.map((
|
|
7
|
-
`),definitions:n,invocations:r}}function
|
|
8
|
-
`).filter(
|
|
9
|
-
${
|
|
10
|
-
`)||(
|
|
11
|
-
`)
|
|
12
|
-
`}
|
|
13
|
-
`)
|
|
14
|
-
`
|
|
4
|
+
`&&o++,n.push(r),r="",n.some(a=>a!=="")&&t.push(n),n=[]):r+=i}return n.push(r),n.some(o=>o!=="")&&t.push(n),t.map(o=>o.map(i=>i.trim()))}function br(e){let t=a=>{throw new Error(`Examples: {data:${e}}: ${a}`)},n=Ke?at.join(rn,`${e}.${Ke}.csv`):void 0,r=n&&nn.existsSync(n)?n:at.join(rn,`${e}.csv`);if(!e.includes(".")&&nn.existsSync(r)){let[a,...c]=Tf(nn.readFileSync(r,"utf8"));return(!a||c.length===0)&&t(`${e}.csv needs a header row and at least one data row`),{headers:a,rows:c.map(l=>Object.fromEntries(a.map((d,p)=>[d,l[p]??""])))}}let s;try{s=Mt(e)}catch(a){return t(`${a instanceof Error?a.message:String(a)} (looked for ${e.split(".")[0]}.csv and ${e.split(".")[0]}.json in the data folder)`)}(!Array.isArray(s)||s.length===0||s.some(a=>a===null||typeof a!="object"||Array.isArray(a)))&&t('must be a non-empty list of records, like [{ "role": "Admin", "menu": "Users" }]');let o=s,i=[...new Set(o.flatMap(a=>Object.keys(a)))];return{headers:i,rows:o.map(a=>Object.fromEntries(i.map(c=>[c,a[c]===void 0||a[c]===null?"":String(a[c])])))}}function vr(e){return e.replace(sn,(t,n)=>on(n))}function ct(e){let t=new Set;for(let n of e)if(n)for(let r of n.matchAll(sn))t.add(r[1]);return t}function Sr(e){let t=new Map;for(let n of ct(e))try{t.set(n,on(n))}catch{}return t}function Cs(e,t,n=new Set){let r=new Map;for(let[i,a]of t)r.set(a,[...r.get(a)??[],i]);let s=[];for(let[i,a]of r){let c=a.length===1?a:a.filter(l=>n.has(l));c.length===1&&s.push([c[0],i])}s.sort((i,a)=>a[1].length-i[1].length);for(let[i,a]of s)if(a!==""&&e===a)return`{data:${i}}`;let o=e;for(let[i,a]of s)a.length<4||(o=o.split(a).join(`{data:${i}}`));return o}var an=/\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g;function $r(e,t){return e.replace(an,(n,r)=>{if(!t.has(r))throw new Error(`{env:${r}} is not referenced by this scenario: a recording can only use the environment variables its scenario names`);let s=process.env[r];if(s===void 0)throw new Error(`environment variable ${r} is not set (referenced as {env:${r}}): export it or add it to .env`);return s})}function Os(e){let t=new Set;for(let n of e)if(n)for(let r of n.matchAll(an))t.add(r[1]);return t}function je(e){let t=[];for(let n of e.steps){t.push(n.text,n.resolvedText),n.docString&&t.push(n.docString),n.resolvedDocString&&t.push(n.resolvedDocString);for(let r of n.table??[])t.push(...r);for(let r of n.resolvedTable??[])t.push(...r)}return t}function js(e){let t=[];for(let n of ct(e))try{t.push(...vt(n))}catch{}return t}function _e(e){let t=je(e);return Os([...t,...js(t)])}function Ze(e){let t=new Map;for(let n of _e(e)){let r=process.env[n];r!==void 0&&t.set(n,r)}return t}var Lt=3,Ps=String.raw`\{(?:env:[A-Za-z_][A-Za-z0-9_]*|data:[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+|unique:[A-Za-z0-9_-]+(?::digits)?)\\?\}`,Af=/\{(env:[A-Za-z_][A-Za-z0-9_]*|data:[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+)\\\}/g,Gi=e=>`${e.slice(0,-1)}\\}`,Ki=e=>e.replace(Af,"{$1}"),xr={'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"};function _f(e,t,n,r){let s="";for(let o of e.split("")){let i=o.charCodeAt(0);if(t?.test(o)||i<32&&!xr[o]){let a=i.toString(16).padStart(4,"0");s+="\\u"+(n?a.toUpperCase():a)}else xr[o]?s+=xr[o]:o==="/"&&r?s+="\\/":s+=o}return s}function If(e){return[e,e.replace(/%[0-9A-F]{2}/g,t=>t.toLowerCase())]}function Wi(e,t,n){return e.replace(/[&<>"'+]|[^\x00-\x7f]/gu,r=>t[r]??(n&&r>"\x7F"?n(r.codePointAt(0)):r))}function Cf(e,t){let n="";for(let r of e){let s=r<=" "||r>="\x7F"||t.test(r);n+=s?[...Buffer.from(r,"utf8")].map(o=>"%"+o.toString(16).toUpperCase().padStart(2,"0")).join(""):r}return n}var Pf=[/["#<>']/,/["#<>?^`{}]/,/["#<>?^`{|}]/,/["#<>?^`{}/:;=@[\\\]|]/,/["#<>?^`{}/:;=@[\\\]|']/];function Of(e){let t=/[^\x00-\x7f]/,n=new Set([e]);for(let[s,o,i]of[[void 0,!1,!1],[void 0,!1,!0],[t,!1,!1],[t,!0,!1],[t,!1,!0],[/[<>&\u2028\u2029]/,!1,!1],[/[^\x00-\x7f]|[<>&'+`"]/,!0,!1]])n.add(_f(e,s,o,i));let r=s=>{try{for(let o of If(s()))n.add(o)}catch{}};r(()=>encodeURIComponent(e)),r(()=>encodeURIComponent(e).replaceAll("'","%27")),r(()=>encodeURI(e)),r(()=>new URLSearchParams([["",e]]).toString().slice(1));for(let s of Pf)r(()=>Cf(e,s));for(let s of[{"&":"&","<":"<",">":">"},{"&":"&","<":"<",">":">",'"':""","'":"'"},{"&":"&","<":"<",">":">",'"':""","'":"'"},{"&":"&","<":"<",">":">",'"':""","'":"'"},{"&":"&","<":"<",">":">",'"':""","'":"'"},{"&":"&","<":"<",">":">",'"':""","'":"'","+":"+"}])n.add(Wi(e,s));return n.add(Wi(e,{"&":"&","<":"<",">":">",'"':""","'":"'","+":"+"},s=>`&#x${s.toString(16).toUpperCase()};`)),[...n]}var On=e=>e.map(t=>`{env:${t}}`).join(""),lt=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),jf=e=>Buffer.from(e,"utf8").toString("latin1");function Dt(e,t={}){let n=[...e.entries()].filter(([,f])=>f.length>=Lt).sort((f,h)=>h[1].length-f[1].length),r=new Map,s=new Set;for(let[f,h]of n){t.standaloneBelow!==void 0&&h.length<t.standaloneBelow&&s.add(h);let w=t.encodings?Of(h):[h];for(let $ of w){let k=t.bytes?[jf($),.../^[\x00-\xff]*$/.test($)?[$]:[]]:[$];for(let y of k)r.has(y)||r.set(y,f)}}let o=new Set(n.map(([,f])=>f)),i=new Set(["u"]);for(let[,f]of n)for(let h of f){let w=xr[h]??(h==="/"?"\\/":void 0);w&&i.add(w.slice(1))}let a=new RegExp(`\\\\[${[...i].map(lt).join("")}]`);if(r.size===0)return{empty:!0,mask:f=>f,matches:()=>[],occursIn:()=>!1,isValue:()=>!1,hiddenByEscape:a};let c=[...r.keys()].sort((f,h)=>h.length-f.length).map(f=>s.has(f)?`(?<![A-Za-z0-9])${lt(f)}(?![A-Za-z0-9])`:lt(f)).join("|"),l=new RegExp(`(${Ps})|${c}`,"g"),d=new RegExp(`(${Ps})|${c}`,"y"),p=new RegExp(c),u=f=>{let h=[];l.lastIndex=0;for(let w=l.exec(f);w!==null;w=l.exec(f)){if(w[1]!==void 0)continue;let $=w.index,k=$+w[0].length,y=[r.get(w[0])];for(let v=$+1;v<k;v++){d.lastIndex=v;let S=d.exec(f);S&&S[1]===void 0&&v+S[0].length>k&&(k=v+S[0].length,y.push(r.get(S[0])))}h.push({start:$,end:k,names:[...new Set(y)]}),l.lastIndex=k}return h};return{empty:!1,hiddenByEscape:a,occursIn:f=>p.test(f),isValue:f=>o.has(f),matches:u,mask(f){let h="",w=0;for(let $ of u(f))h+=f.slice(w,$.start)+On($.names),w=$.end;return w===0?f:h+f.slice(w)}}}function Ns(e,t,n=r=>r){let r=new Map;for(let i of e)for(let a of i.split(/[\s"'`]+/)){let c=a.replace(/^[.,;:!?()[\]]+|[.,;:!?()[\]]+$/g,""),l=[...c.matchAll(an)].map(u=>u[1]);if(l.length===0||l.some(u=>!t.has(u)))continue;let d=c.replace(an,(u,f)=>t.get(f));if(d===c||d.length<Lt||c===`{env:${l[0]}}`)continue;let p=n(d);r.has(p)||r.set(p,c.split(/(\{env:[A-Za-z_][A-Za-z0-9_]*\})/).map((u,f)=>f%2?u:n(u)).join(""))}if(r.size===0)return i=>i;let s=[...r.keys()].sort((i,a)=>a.length-i.length).map(lt).join("|"),o=new RegExp(`(${Ps})|${s}`,"g");return i=>i.replace(o,(a,c)=>c!==void 0?a:r.get(a))}var Vi=new WeakMap;function dt(e,t){let n=Vi.get(t);return n||(n=Dt(t,{encodings:!0}),Vi.set(t,n)),n.mask(e)}function Yi(e){let t=Ef.join(e,".env");if(Ji.existsSync(t))for(let n of Ji.readFileSync(t,"utf8").split(`
|
|
5
|
+
`)){let r=n.trim();if(!r||r.startsWith("#"))continue;let s=r.indexOf("=");if(s<=0)continue;let o=r.slice(0,s).trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(o))continue;let i=r.slice(s+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),process.env[o]===void 0&&(process.env[o]=i)}}function cn(e,t){return e.replace(/<([^<>]+)>/g,(n,r)=>r in t?t[r]:n)}function ke(e){if(!e||e.length===0)return{};let t={};if(e.every(n=>n.length===2)){for(let[n,r]of e)t[`table:${n}`]=r;return t}if(e.length>=2){let[n,...r]=e;if(n.some(s=>!s))return{};r.forEach((s,o)=>{n.forEach((i,a)=>{s[a]!==void 0&&(t[`table:${o+1}:${i}`]=s[a])})})}return t}function Bt(e){return e!==void 0?{docstring:e}:{}}function St(e){let t=new Map;for(let r of e){let s={...ke(r.resolvedTable??r.table),...Bt(r.resolvedDocString??r.docString)};for(let[o,i]of Object.entries(s)){let a=t.get(o);a||t.set(o,a=new Set),a.add(i)}}let n={};for(let[r,s]of t)s.size===1&&(n[r]=[...s][0]);return n}function Fs(e){return e.replace(/\\.|["'`]|>>/g,t=>t[0]==="\\"?t:t===">>"?"\\>\\>":`\\${t}`)}var we={quoted:e=>JSON.stringify(e).slice(1,-1),regex:e=>Fs(lt(e).replaceAll("/","\\/")),pattern:e=>lt(e)};function ln(e,t,n=r=>r){let r="",s=0;for(let o of e.matchAll(/"((?:[^"\\]|\\.)*)"|=\/((?:[^/\\]|\\.)*)\/([a-z]*)/g)){let[i,a,c,l]=o;a===void 0&&/[uv]/.test(l)||(r+=n(e.slice(s,o.index))+(a!==void 0?`"${t(a,"quoted")}"`:`=/${t(c,"regex")}/${l}`),s=o.index+i.length)}return r+n(e.slice(s))}import Ms from"node:fs";import kr from"node:path";import{AstBuilder as Nf,GherkinClassicTokenMatcher as Ff,Parser as Mf}from"@cucumber/gherkin";import{IdGenerator as Lf}from"@cucumber/messages";var be=class extends Error{},Df=/^(\s*)StepSet:\s*(.+?)\s*$/,Bf=/^(\s*)StepSet\s+([^\s:].*?)\s*$/;function Ls(e){let t=e.split(`
|
|
6
|
+
`),n=new Map,r=new Map,s;return{source:t.map((i,a)=>{let c=/^\s*("""|```)/.exec(i)?.[1];if(s)return c===s&&(s=void 0),i;if(c)return s=c,i;let l=i.match(Df);if(l)return n.set(a+1,l[2]),`${l[1]}Scenario: ${l[2]}`;let d=i.match(Bf);return d?(r.set(a+1,d[2]),`${d[1]}* StepSet ${d[2]}`):i}).join(`
|
|
7
|
+
`),definitions:n,invocations:r}}function Uf(e){return new Mf(new Nf(Lf.uuid()),new Ff).parse(e)}function Zi(e,t){for(let n of e)n.scenario?t(n.scenario):"rule"in n&&n.rule&&Zi(n.rule.children,t)}function ft(e,t){let n=new Map;for(let r of e){let s=kr.relative(t,r),o=Ls(Ms.readFileSync(r,"utf8"));if(o.definitions.size===0)continue;let i=Uf(o.source);i.feature&&Zi(i.feature.children,a=>{let c=o.definitions.get(a.location.line);if(c===void 0)return;let l=n.get(c);if(l)throw new be(`StepSet "${c}" is defined twice: ${l.file}:${l.line} and ${s}:${a.location.line}. Set names are unique across the project. If line ${a.location.line} was meant to INVOKE the set inside a scenario, remove the colon: "StepSet ${c}".`);if(a.examples.length>0)throw new be(`StepSet "${c}" (${s}:${a.location.line}) has an Examples table \u2014 step sets take their values from the invoking scenario.`);for(let d of a.steps)if(o.invocations.has(d.location.line))throw new be(`StepSet "${c}" (${s}:${a.location.line}) invokes another step set at line ${d.location.line} \u2014 step sets cannot be nested.`);n.set(c,{name:c,file:s,line:a.location.line,steps:[...a.steps]})})}return n}var Ds=[".feature",".saffron"];function pt(e){return Ds.some(t=>e.endsWith(t))}function Ie(e,t,n){let r=kr.isAbsolute(t.features??"features")?t.features:kr.join(e,t.features??"features"),s=new Set(Ut(r));for(let o of n)o.endsWith(".saffron")&&s.add(o);return ft([...s].sort(),e)}function Ut(e){if(!Ms.existsSync(e))return[];let t=[];for(let n of Ms.readdirSync(e,{recursive:!0})){let r=String(n);r.endsWith(".saffron")&&t.push(kr.join(e,r))}return t.sort()}function Xi(e,t,n){return e.map(({step:r,source:s})=>{let o;switch(r.keywordType){case Bs.OUTCOME:o="assertion";break;case Bs.CONTEXT:case Bs.ACTION:o="action";break;default:o=n.value}n.value=o;let i=r.dataTable?r.dataTable.rows.map(c=>c.cells.map(l=>l.value)):void 0,a=r.docString?.content;return{keyword:r.keyword.trim(),kind:o,text:r.text,resolvedText:cn(r.text,t),table:i,resolvedTable:i?.map(c=>c.map(l=>cn(l,t))),docString:a,resolvedDocString:a!==void 0?cn(a,t):void 0,source:s}})}function ea(e,t,n,r,s){let o=[];for(let i of e){let a=r.get(i.location.line);if(a===void 0){o.push({step:i,source:{file:t,line:i.location.line,fromBackground:n}});continue}let c=s?.get(a);if(!c)throw new be(`${t}:${i.location.line} invokes StepSet "${a}", which is not defined anywhere in the project.`);for(let l of c.steps)o.push({step:l,source:{file:c.file,line:l.location.line,fromStepSet:c.name,fromBackground:n}})}return o}function Gf(e,t,n,r,s,o=!1,i=[]){let a=[...new Set([...i,...e.tags.map(l=>l.name)])],c=[];if(e.examples.length===0)c.push({params:{},label:"",tags:a});else{let l=0;for(let d of e.examples){let p=[...new Set([...a,...d.tags.map(h=>h.name)])],u=d.name.trim().match(/^\{data:([A-Za-z0-9_.-]+)\}$/);if(u&&!d.tableHeader){let h=`${t}:${d.location.line}`;if(!o)throw new be(`${h} reads Examples from a data file, which only .saffron files understand. Rename the file to ${t.replace(/\.feature$/,".saffron")}: nothing else needs to change.`);let w;try{w=br(u[1])}catch(y){throw new be(`${h} ${y instanceof Error?y.message:String(y)}`)}let k=[...new Set([...r,...s].flatMap(y=>[y.step.text,y.step.docString?.content??"",...y.step.dataTable?.rows.flatMap(v=>v.cells.map(S=>S.value))??[]].flatMap(v=>[...v.matchAll(/<([^<>]+)>/g)].map(S=>S[1]))))].filter(y=>!w.headers.includes(y)&&!y.startsWith("table:")&&y!=="docstring");if(k.length>0)throw new be(`${h} the scenario uses <${k.join(">, <")}>, but {data:${u[1]}} has the columns ${w.headers.map(y=>`"${y}"`).join(", ")}.`);for(let y of w.rows)l+=1,c.push({params:y,label:` (example ${l})`,tags:p});continue}let f=d.tableHeader?.cells.map(h=>h.value)??[];for(let h of d.tableBody){l+=1;let w={};h.cells.forEach(($,k)=>{w[f[k]]=$.value}),c.push({params:w,label:` (example ${l})`,line:h.location.line,tags:p})}}}return c.map(({params:l,label:d,line:p,tags:u})=>{let f={value:"action"};return{featurePath:t,featureName:n,name:e.name,displayName:`${e.name}${d}`,tags:u,steps:[...Xi(r,l,f),...Xi(s,l,f)],params:l,line:e.location.line,...p!==void 0?{exampleLine:p}:{}}})}function ta(e,t){let n=zf.readFileSync(e,"utf8"),r=e.endsWith(".saffron"),s=r?Ls(n):{source:n,definitions:new Map,invocations:new Map},o=new Wf(new qf(Vf.uuid()),new Jf),i=Hf.relative(t,e),a;try{a=o.parse(s.source)}catch(c){let l=(c instanceof Error?c.message:String(c)).split(`
|
|
8
|
+
`).filter(p=>/^\(\d+:\d+\)/.test(p)).map(p=>`${i}${p.replace(/^\((\d+):(\d+)\)/,":$1:$2")}`),d=!r&&/^\s*StepSet\b/m.test(n);throw new be(d?`${i} uses StepSet, which only .saffron files understand. Rename it to ${i.replace(/\.feature$/,".saffron")}: nothing else needs to change (a .saffron file accepts everything a .feature file does).`:`${i} is not valid Gherkin:
|
|
9
|
+
${l.join(`
|
|
10
|
+
`)||(c instanceof Error?c.message:String(c))}`)}return{doc:a,pre:s,relPath:i,isSaffron:r,lineCount:n.split(`
|
|
11
|
+
`).length-(n.endsWith(`
|
|
12
|
+
`)?1:0)}}function na(e,t){let{doc:n,pre:r,lineCount:s}=ta(e,t),o=[],i=(c,l)=>Math.min(l,...c.map(d=>d.location.line)),a=c=>{for(let l of c)if(l.background){let{name:d,location:p}=l.background;o.push({kind:"background",name:d,line:p.line,start:p.line,rows:[]})}else if(l.scenario){let{name:d,location:p,tags:u,examples:f}=l.scenario,h=r.definitions.has(p.line)?"stepSet":"scenario",w=f.flatMap($=>$.tableBody.map(k=>k.location.line));o.push({kind:h,name:d,line:p.line,start:i(u,p.line),rows:w})}else if("rule"in l&&l.rule){let{name:d,location:p,tags:u}=l.rule;o.push({kind:"rule",name:d,line:p.line,start:i(u,p.line),rows:[]}),a(l.rule.children)}};return n.feature&&a(n.feature.children),{blocks:o,lineCount:s}}function ra(e){let t=e.split(/\r?\n/),n=t.findIndex(c=>c.trim()!==""&&!c.trim().startsWith("#")),r=(n<0?t:t.slice(0,n)).map(c=>/^\s*#\s*language\s*:\s*([\w-]+)/.exec(c)?.[1]).find(Boolean),s=r&&Qi[r]||Qi.en,o=[...s.scenario,...s.scenarioOutline].map(c=>`${c.trim()}:`),i=[],a;return t.forEach((c,l)=>{let d=c.trim(),p=['"""',"```"].find(f=>d.startsWith(f));if(p){a?a===p&&(a=void 0):a=p;return}if(a)return;let u=o.find(f=>d.startsWith(f));u&&i.push({line:l+1,name:d.slice(u.length).trim()})}),i}function Ce(e,t,n){let{doc:r,pre:s,relPath:o,isSaffron:i}=ta(e,t);if(!r.feature)return[];let a=r.feature.name,c=[],l=(d,p,u)=>{let f=p;for(let h of d)if(h.background)f=[...p,...ea(h.background.steps,o,!0,s.invocations,n)];else if(h.scenario){if(s.definitions.has(h.scenario.location.line))continue;c.push(...Gf(h.scenario,o,a,f,ea(h.scenario.steps,o,!1,s.invocations,n),i,u))}else"rule"in h&&h.rule&&l(h.rule.children,f,[...u,...h.rule.tags.map(w=>w.name)])};return l(r.feature.children,[],r.feature.tags.map(d=>d.name)),c}import ua from"node:fs";import Js from"node:path";import ca from"node:fs";import la from"node:path";import{createHash as rp}from"node:crypto";import Tr from"node:fs";import dn from"node:path";import sa from"node:path";var Ne=new Set(["expectVisible","expectNotVisible","expectText","expectUrl","expectValue","expectDiffers","expectMatches","expectAttribute","expectResponse","expectEach"]);var Rr=1,Kf=new Set(["goto","click","fill","press","selectOption","check","uncheck","hover","waitFor","captureText","handleDialog","uploadFile","dragTo","waitForResponse","switchTab","closeTab","newTab",...Ne]),Yf=["role","name","nameRegex","label","text","testId","placeholder","frame"],Zf=["value","url","saveAs","compareTo","each","pattern","attribute","promptText","urlPattern","method","status","pageFingerprint"],Us=/[\u0000-\u001f\u007f-\u009f]/,oe=class extends Error{constructor(n,r){super(`${n}: ${r}`);this.file=n;this.problem=r}file;problem},Je=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function z(e,t,n){if(!e)throw new oe(t,n)}function oa(e,t,n){z(Je(e),t,`${n} must be an object`);for(let r of Yf)z(e[r]===void 0||typeof e[r]=="string",t,`${n}.${r} must be a string`);e.fallbackSelectors!==void 0&&z(Array.isArray(e.fallbackSelectors)&&e.fallbackSelectors.every(r=>typeof r=="string"),t,`${n}.fallbackSelectors must be a list of selectors`)}var Qf=e=>["role","label","text","testId","placeholder"].some(t=>typeof e[t]=="string"&&e[t]!=="")||Array.isArray(e.fallbackSelectors)&&e.fallbackSelectors.some(t=>typeof t=="string"&&t.trim().length>0),Xf={goto:["url"],click:["target"],fill:["target","value"],press:["value"],selectOption:["target","value"],check:["target"],uncheck:["target"],hover:["target"],waitFor:["targetOrValue"],captureText:["target","saveAs"],handleDialog:[],uploadFile:["value"],dragTo:["target","toTarget"],waitForResponse:["urlPattern"],switchTab:["value"],closeTab:[],newTab:[],expectVisible:["target"],expectNotVisible:["target"],expectText:["target","value"],expectUrl:["urlOrValue"],expectValue:["target","value"],expectDiffers:["compareTo","targetOrValue"],expectMatches:["target","pattern"],expectAttribute:["target","attribute","pattern"],expectResponse:["urlPattern"],expectEach:["target","each"]};function ep(e,t,n){let r=o=>typeof e[o]=="string",s=o=>Je(e[o])&&Qf(e[o]);for(let o of Xf[e.action])switch(o){case"target":case"toTarget":z(s(o),t,`${n} (${e.action}) needs a ${o} with a role, name, label, text, test id, placeholder or selector`);break;case"urlOrValue":z(r("url")||r("value"),t,`${n} (${e.action}) needs a url`);break;case"targetOrValue":z(s("target")||r("value"),t,`${n} (${e.action}) needs a target or a value`);break;default:z(r(o),t,`${n} (${e.action}) needs ${o}`)}for(let o of["target","toTarget"])e[o]!==void 0&&z(s(o),t,`${n}.${o} has no usable locator`);if(e.action==="expectUrl"){let o=e.url??e.value;z(typeof o=="string"&&o.length>0,t,`${n} (expectUrl) needs a non-empty url or value`)}for(let o of["url","saveAs","compareTo","each","pattern","attribute","urlPattern"])e[o]!==void 0&&z(e[o].length>0,t,`${n}.${o} must not be empty`);["press","uploadFile","switchTab","expectText"].includes(e.action)&&z(typeof e.value=="string"&&e.value.length>0,t,`${n} (${e.action}) needs a non-empty value`)}function tp(e,t,n){z(Je(e),t,`${n} must be an object`),z(typeof e.action=="string",t,`${n}.action is missing`),z(Kf.has(e.action),t,`${n}.action "${e.action}" is not an action this runner knows. Recorded by a newer saffron-ai? Update, or re-record with --rerecord`);for(let r of Zf)z(e[r]===void 0||typeof e[r]=="string",t,`${n}.${r} must be a string`);z(e.opensTab===void 0||typeof e.opensTab=="boolean",t,`${n}.opensTab must be true or false`),e.target!==void 0&&oa(e.target,t,`${n}.target`),e.toTarget!==void 0&&oa(e.toTarget,t,`${n}.toTarget`),ep(e,t,n)}function np(e,t,n){z(Je(e),t,`${n} must be an object`),z(typeof e.gherkin=="string"&&e.gherkin.length>0,t,`${n}.gherkin (the step text) is missing`),z(typeof e.keyword=="string",t,`${n}.keyword is missing`),z(e.kind==="action"||e.kind==="assertion",t,`${n}.kind must be "action" or "assertion"`),z(Array.isArray(e.actions),t,`${n}.actions must be a list (empty for a recorded no-op)`),e.actions.forEach((r,s)=>tp(r,t,`${n}.actions[${s}]`)),e.table!==void 0&&z(Array.isArray(e.table)&&e.table.every(r=>Array.isArray(r)&&r.every(s=>typeof s=="string")),t,`${n}.table must be rows of strings`),z(e.docString===void 0||typeof e.docString=="string",t,`${n}.docString must be a string`),z(e.fromStepSet===void 0||typeof e.fromStepSet=="string",t,`${n}.fromStepSet must be a string`)}function zs(e,t){return z(Je(e),t,"is not a JSON object"),z(e.version!==void 0,t,"has no version: not a Saffron recording"),z(e.version===Rr,t,typeof e.version=="number"&&e.version>Rr?`is schema version ${e.version}; this saffron-ai reads version ${Rr}. Update saffron-ai to the release that wrote it`:`has schema version ${JSON.stringify(e.version)}; this saffron-ai reads version ${Rr}`),z(typeof e.feature=="string"&&e.feature.length>0,t,"feature (the feature file path) is missing"),z(!sa.isAbsolute(e.feature)&&!sa.win32.isAbsolute(e.feature)&&!e.feature.split(/[\\/]/).includes(".."),t,`names a feature file outside the project: ${JSON.stringify(e.feature)}`),z(typeof e.scenario=="string"&&e.scenario.length>0,t,"scenario (the scenario name) is missing"),z(e.recordedAt===void 0||typeof e.recordedAt=="string",t,"recordedAt must be a string"),z(e.recordedBy===void 0||e.recordedBy==="agent"||e.recordedBy==="manual",t,'recordedBy must be "agent" or "manual"'),z(Array.isArray(e.steps),t,"steps must be a list"),e.steps.forEach((n,r)=>np(n,t,`steps[${r}]`)),e.data!==void 0&&z(Je(e.data)&&Object.values(e.data).every(n=>typeof n=="string"),t,"data must map references to strings"),e}function ia(e,t){z(Je(e),t,"is not a JSON object"),z(Je(e.meta),t,"meta is missing: not a Saffron proposal");let n=e.meta;z(n.mode==="record"||n.mode==="heal",t,'meta.mode must be "record" or "heal"'),z(typeof n.narrative=="string",t,"meta.narrative must be a string"),z(Array.isArray(n.adaptations)&&n.adaptations.every(r=>typeof r=="string"),t,"meta.adaptations must be a list of strings"),z(n.verified===void 0||typeof n.verified=="boolean",t,"meta.verified must be true or false"),z(Je(n.usage),t,"meta.usage is missing"),n.featureEdits!==void 0&&(z(Array.isArray(n.featureEdits)&&n.featureEdits.every(r=>Je(r)&&typeof r.index=="number"&&typeof r.text=="string"),t,"meta.featureEdits must be a list of { index, text }"),n.featureEdits.forEach((r,s)=>z(!Us.test(r.text),t,`meta.featureEdits[${s}].text holds a line break or another control character`))),n.bound!==void 0&&z(Je(n.bound)&&["scenario","committed","recording"].every(r=>typeof n.bound[r]=="string"),t,"meta.bound must hold the scenario, committed and recording digests"),zs(e.cache,`${t} (cache)`)}var Hs=".saffron";function Er(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function qs(e){let t=e.split(/[\\/]/).filter(Boolean),n=t.pop()??"unnamed",r=t.slice(1),s=Er([...r,dn.basename(n,".feature")].join("-"));if(r.length===0)return s;let o=rp("sha1").update(e.replace(/\\/g,"/")).digest("hex").slice(0,6);return`${s}-${o}`}function re(e,t,n){return dn.join(e,Hs,"cache",qs(t),`${Er(n)}.json`)}function aa(e,t){let n=new Map;for(let r of t){let s=re(e,r.featurePath,r.name),o=n.get(s)??new Set;o.add(`${r.featurePath} \u203A ${r.name}${r.line?` (line ${r.line})`:""}`),n.set(s,o)}return[...n.entries()].filter(([,r])=>r.size>1).map(([r,s])=>`${[...s].join(" and ")} both map to ${dn.relative(e,r)}. Rename one scenario or one file.`)}var fn="owner.json";function Qe(e,t,n){return dn.join(e,Hs,"artifacts",qs(t),Er(n))}function Fe(e,t,n){return dn.join(e,Hs,"proposals",qs(t),`${Er(n)}.json`)}function xt(e,t){try{return Re(e)}catch(n){if(!(n instanceof oe))throw n;t?.(e,n.problem);return}}function Re(e){if(!Tr.existsSync(e))return;let t;try{t=JSON.parse(Tr.readFileSync(e,"utf8"))}catch(n){throw new oe(e,`is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}return zs(t,e)}function pn(e,t){Tr.mkdirSync(dn.dirname(e),{recursive:!0}),Tr.writeFileSync(e,`${JSON.stringify(t,null,2)}
|
|
13
|
+
`)}function jn(e,t){let n=r=>typeof r=="string"?r.includes(t):Array.isArray(r)?r.some(n):r&&typeof r=="object"?Object.entries(r).some(([s,o])=>s!=="pageFingerprint"&&n(o)):!1;return e.some(n)}function un(e,t){if(t.trim()==="")return!1;let n=s=>(s??"").replace(/<[^<>]+>/g,""),r=new Set([t,...Object.values(we).map(s=>s(t))]);return e.some(s=>[s.value,s.url,s.urlPattern,s.pattern,s.promptText,s.compareTo,...[s.target,s.toTarget].flatMap(o=>[o?.name,o?.nameRegex,o?.label,o?.text,o?.placeholder,o?.testId,o?.frame,...o?.fallbackSelectors??[]])].some(o=>[...r].some(i=>n(o).includes(i))))}function Ar(e){let t=[];return{pattern:e.replace(/"((?:[^"\\]|\\.)*)"/g,(r,s)=>(t.push(s),`"\xAB${t.length-1}\xBB"`)),args:t}}function sp(e,t){let n=r=>JSON.stringify(r.map(({pageFingerprint:s,...o})=>o));return n(e)===n(t)}function op(e){let t=new Set,n=r=>{if(r)for(let s of r.matchAll(/<([^<>]+)>/g))t.add(s[1])};for(let r of e.actions)n(r.value),n(r.url),n(r.pattern),n(r.target?.name),n(r.target?.nameRegex),n(r.target?.label),n(r.target?.text),n(r.target?.placeholder);return n(e.gherkin),t}function Xe(e){let t=la.join(e,".saffron","cache"),n=new Map,r=new Map,s=0;if(ca.existsSync(t))for(let a of ca.readdirSync(t,{recursive:!0})){let c=String(a);if(!c.endsWith(".json"))continue;let l=xt(la.join(t,c));if(l){s++;for(let d of l.steps){let p=d.gherkin,u=JSON.stringify(d.actions.map(({pageFingerprint:w,...$})=>$)),f=r.get(p)??[];f.includes(u)||(f.push(u),r.set(p,f));let h=n.get(p);!h||l.recordedAt>h.recordedAt?n.set(p,{gherkin:d.gherkin,table:d.table,docString:d.docString,actions:d.actions,sourceParams:St(l.steps),sourceData:l.data,feature:l.feature,scenario:l.scenario,recordedAt:l.recordedAt,variants:f.length}):h.variants=f.length}}}let o=[...r.entries()].filter(([,a])=>a.length>1).map(([a])=>a),i=new Map;for(let a of n.values()){let{pattern:c,args:l}=Ar(a.gherkin);if(l.length===0)continue;let d=i.get(c);(!d||a.recordedAt>d.recordedAt)&&i.set(c,{...a,args:l})}return{steps:n,patterns:i,divergent:o,scannedCaches:s}}function da(e,t,n){if(!!e.table!=!!t.table)return!1;if(e.table&&t.table){let o=Object.keys(ke(e.table)),i=Object.keys(ke(t.table));if(o.length>0&&i.length>0){if(JSON.stringify(o)!==JSON.stringify(i))return!1}else if(JSON.stringify(e.table)!==JSON.stringify(t.table))return!1}if(e.docString!==void 0!=(t.docString!==void 0)||e.docString!==void 0&&t.docString!==void 0&&e.docString!==t.docString&&!e.actions.some(o=>[o.value,o.url,o.pattern].some(i=>i?.includes("<docstring>"))))return!1;if(e.table&&t.table){let o=ke(e.table),i=ke(t.table);for(let a of Object.keys(o))if(o[a]!==i[a]&&(!jn(e.actions,`<${a}>`)||un(e.actions,o[a])))return!1}for(let[o,i]of Object.entries(e.sourceParams??{}))if(o in n&&n[o]!==i&&un(e.actions,i))return!1;for(let[o,i]of Object.entries(e.sourceData??{})){let a;try{a=on(o)}catch{continue}if(a!==i&&(un(e.actions,i)||e.gherkin.includes(`{data:${o}}`)&&!jn(e.actions,`{data:${o}}`)))return!1}let r={...n,...ke(t.resolvedTable??t.table),...Bt(t.resolvedDocString??t.docString)},s=op({gherkin:e.gherkin,keyword:"",kind:"action",actions:e.actions});for(let o of s)if(!(o in r))return!1;return!0}function fa(e,t,n){let r=e.steps.get(t.text);if(r)return da(r,t,n)?r:void 0;let{pattern:s,args:o}=Ar(t.text);if(o.length===0)return;let i=e.patterns.get(s);if(!i)return;let a=new Map;for(let p=0;p<o.length;p++){let u=i.args[p],f=o[p];if(u===f)continue;let h=a.get(u);if(h!==void 0&&h!==f)return;a.set(u,f)}let c=p=>[p?.name,p?.nameRegex,p?.label,p?.text,p?.placeholder];for(let p of a.keys())if(!i.actions.some(f=>[f.value,f.url,f.pattern,...c(f.target)].includes(p)))return;let l=p=>p!==void 0&&a.has(p)?a.get(p):p,d={...i,gherkin:t.text,actions:i.actions.map(({pageFingerprint:p,...u})=>({...u,value:l(u.value),url:l(u.url),pattern:l(u.pattern),target:u.target?{...u.target,name:l(u.target.name),nameRegex:l(u.target.nameRegex),label:l(u.target.label),text:l(u.target.text),placeholder:l(u.target.placeholder)}:void 0}))};return da(d,t,n)?d:void 0}function pa(e,t){let n=[];return e.forEach((r,s)=>{if(r.actions.length!==0&&!t.steps.has(r.gherkin)){for(let o of t.steps.values())if(!(o.variants>1)&&o.actions.length!==0&&sp(r.actions,o.actions)){n.push({index:s,from:r.gherkin,to:o.gherkin,feature:o.feature,scenario:o.scenario});break}}}),n}function Ws(e){if(!ua.existsSync(e))return[];let t=[];for(let n of ua.readdirSync(e,{recursive:!0})){let r=String(n);pt(r)&&t.push(Js.join(e,r))}return t.sort()}function et(e,t,n,r){let s=Js.isAbsolute(t)?t:Js.join(e,t),o=Ws(s),i=n??ft(o.filter(f=>f.endsWith(".saffron")),e),a=new Map,c=new Map;for(let f of o)for(let h of r?.get(f)??Ce(f,e,i)){let w=`${h.featurePath}::${h.name}`;for(let $ of h.steps){let k=a.get($.text);if(k||(k={text:$.text,keywords:new Map,kind:$.kind,scenarios:new Set,files:new Set,fromStepSet:$.source?.fromStepSet},a.set($.text,k)),k.keywords.set($.keyword,(k.keywords.get($.keyword)??0)+1),k.scenarios.add(w),$.source&&k.files.add($.source.file),$.source?.fromStepSet){let y=c.get($.source.fromStepSet);y||c.set($.source.fromStepSet,y=new Set),y.add(w)}}}let l=Xe(e),d=new Set(l.divergent),p=[...a.values()].map(f=>({text:f.text,keyword:[...f.keywords.entries()].sort((h,w)=>w[1]-h[1])[0][0],kind:f.kind,status:d.has(f.text)?"divergent":l.steps.has(f.text)?"recorded":"unrecorded",usage:f.scenarios.size,files:[...f.files].sort(),fromStepSet:f.fromStepSet})).sort((f,h)=>h.usage-f.usage||f.text.localeCompare(h.text)),u=[...i.values()].map(f=>({name:f.name,file:f.file,line:f.line,steps:f.steps.map(h=>h.text),usage:c.get(f.name)?.size??0})).sort((f,h)=>h.usage-f.usage||f.name.localeCompare(h.name));return{steps:p,stepSets:u,scannedFiles:o.length,scannedCaches:l.scannedCaches}}function _r(e,t){let n=t.toLowerCase();return{...e,steps:e.steps.filter(r=>r.text.toLowerCase().includes(n)),stepSets:e.stepSets.filter(r=>r.name.toLowerCase().includes(n)||r.steps.some(s=>s.toLowerCase().includes(n)))}}function ga(e){let t={},n="saffron,feature,gherkin,cucumber";for(let r of e.steps)t[`step: ${r.text}`]={scope:n,prefix:r.text,body:[r.text.replace(/\$/g,"\\$")],description:`${r.status} \xB7 used in ${r.usage} scenario(s)`};for(let r of e.stepSets)t[`StepSet: ${r.name}`]={scope:n,prefix:`StepSet ${r.name}`,body:[`StepSet ${r.name}`],description:`step set (${r.steps.length} steps) \u2014 ${r.file}`};return JSON.stringify(t,null,2)+`
|
|
14
|
+
`}import{Server as bg}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as vg}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as Sg,ListToolsRequestSchema as xg}from"@modelcontextprotocol/sdk/types.js";import ze from"node:fs";import st from"node:path";import ha from"node:fs";import ip from"node:path";function le(e){Yi(e);let t=ip.join(e,"saffron.config.json"),n=ha.existsSync(t)?JSON.parse(ha.readFileSync(t,"utf8")):{};return Ye(e,n.dataDir,process.env.SAFFRON_ENV??n.env),n}var Vs={provider:"claude",features:"features",dataDir:"data",actionTimeoutMs:5e3,pollIntervalMs:100,retries:1,screenshot:"viewport",maxTurns:100,strict:!1,verifyProposals:!0,snapshotMode:"none",reuseSteps:!0,browser:"chromium",workers:1,assertionPolicy:"strict",hookTimeoutMs:3e5,trace:"off"};function ma(e){return{...Vs,...Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}}import Gs from"node:fs";import Ir from"node:path";import{fileURLToPath as ap}from"node:url";function Cr(){let e=Ir.dirname(ap(import.meta.url));for(let t=0;t<6;t++){let n=Ir.join(e,"package.json");if(Gs.existsSync(n))try{if(JSON.parse(Gs.readFileSync(n,"utf8")).name==="saffron-ai")return e}catch{}e=Ir.dirname(e)}}function We(){let e=Cr();if(!e)return"unknown";try{return JSON.parse(Gs.readFileSync(Ir.join(e,"package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}import Ee from"node:fs";import ge from"node:path";import ve from"node:fs";import{createHash as dp}from"node:crypto";import ya from"node:os";import hn from"node:path";import ut from"node:fs";import $t from"node:path";import{createHash as cp,randomBytes as lp}from"node:crypto";function kt(e,t){try{if(!ut.statSync(t).isFile())return!1;let n=$t.relative(ut.realpathSync(e),ut.realpathSync(t));return n!==""&&n!==".."&&!n.startsWith(".."+$t.sep)&&!$t.isAbsolute(n)}catch{return!1}}var xe=(e,t)=>$t.relative(e,t).split($t.sep).join("/");function Ve(e){return cp("sha256").update(e).digest("hex")}function Te(e,t,n){ut.mkdirSync($t.dirname(e),{recursive:!0});let r=`${e}.${process.pid}-${lp(4).toString("hex")}.partial`;try{ut.writeFileSync(r,t),n!==void 0&&ut.chmodSync(r,n),ut.renameSync(r,e)}catch(s){throw ut.rmSync(r,{force:!0}),s}}function gn(e,t){let n=$t.join(e,t.file);if(kt($t.join(e,".saffron","artifacts"),n))try{let r=ut.readFileSync(n);return t.sha256&&Ve(r)!==t.sha256?void 0:r}catch{return}}function wa(e,t){ve.mkdirSync(hn.dirname(e),{recursive:!0});let n=Buffer.from(`${JSON.stringify(t,null,2)}
|
|
15
|
+
`);return mn(e,()=>Te(e,n)),Zs(n)}var fp=6e4,pp=5e3,up=60*6e4,gp=new Int32Array(new SharedArrayBuffer(4)),zt=class extends Error{};function mn(e,t,n=1e4){let r=`${e}.lock`,s=Date.now()+n,o;for(;;){o=JSON.stringify({pid:process.pid,host:ya.hostname(),at:new Date().toISOString()});try{ve.writeFileSync(r,o,{flag:"wx"});break}catch(i){let a=i.code,c=a==="EPERM"&&process.platform==="win32";if(a!=="EEXIST"&&!c)throw i;if(Date.now()>=s)throw c?i:new zt(`${e} is being decided by another process. Try again.`);hp(r)||Atomics.wait(gp,0,0,25)}}try{return t()}finally{Ks(r)===o&&ve.rmSync(r,{force:!0})}}function Ks(e){try{return ve.readFileSync(e,"utf8")}catch{return}}function hp(e){let t=Ks(e);if(t===void 0)return!1;let n={};try{n=JSON.parse(t)||{}}catch{}let r=Date.parse(n.at??""),s=fp;if(Number.isNaN(r)){try{r=ve.statSync(e).mtimeMs}catch{return!1}s=pp}let o=n.host===ya.hostname()&&typeof n.pid=="number";return o&&mp(n.pid)&&Date.now()-r<up||!o&&Date.now()-r<s||Ks(e)!==t?!1:(ve.rmSync(e,{force:!0}),!0)}function mp(e){try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}function Pr(e,t,n){return ve.existsSync(e)?mn(e,()=>ve.existsSync(e)?t():n()):n()}function Ys(e){let t=/^(.+)#([0-9a-f]{64})$/i.exec(e);return t?{file:t[1],revision:t[2].toLowerCase()}:{file:e}}function Be(e){return Zs(ve.readFileSync(e))}var Zs=e=>dp("sha256").update(e).digest("hex"),ba=e=>hn.join(e,".saffron","reports","filed.json");function va(e){let t;try{t=JSON.parse(ve.readFileSync(ba(e),"utf8"))}catch{return{}}return!t||typeof t!="object"||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([,n])=>typeof n=="string"))}function Sa(e,t,n){return va(e)[xe(e,t)]===n}function xa(e,t,n){let r=va(e);r[xe(e,t)]=n;for(let[s,o]of Object.entries(r)){try{if(Be(hn.join(e,s))===o)continue}catch{}delete r[s]}Te(ba(e),`${JSON.stringify(r,null,2)}
|
|
16
|
+
`)}function yn(e){return Or(e).proposal}function Or(e){return Qs(ve.readFileSync(e),e)}function Qs(e,t){let n;try{n=JSON.parse(e.toString("utf8"))}catch(r){throw new oe(t,`is not valid JSON: ${r instanceof Error?r.message:String(r)}`)}return ia(n,t),{proposal:n,revision:Zs(e),bytes:e}}function tt(e,t){let n=hn.join(e,".saffron","proposals");if(!ve.existsSync(n))return[];let r=[];for(let s of ve.readdirSync(n)){let o=hn.join(n,s);if(ve.statSync(o).isDirectory())for(let i of ve.readdirSync(o)){if(!i.endsWith(".json"))continue;let a=hn.join(o,i);try{r.push({file:a,...Or(a)})}catch(c){if(!t||!(c instanceof oe))throw c;t(a,c.problem)}}}return r}function jr(e,t){let n=yn(t),r=re(e,n.cache.feature,n.cache.scenario);return pn(r,n.cache),ve.rmSync(t),r}function Nr(e){ve.rmSync(e)}var Xs=(e,t)=>ge.relative(e,t).split(ge.sep).join("/");function $a(e){return Ee.existsSync(e)?[...Ee.readdirSync(e,{recursive:!0})].map(String).filter(t=>t.endsWith(".json")).map(t=>ge.join(e,t)).sort():[]}function ka(e){try{let t=JSON.parse(Ee.readFileSync(e,"utf8")),n="cache"in t&&t.cache?t.cache:t;return{feature:n.feature,scenario:n.scenario}}catch{return{}}}function Ra(e){try{let t=JSON.parse(Ee.readFileSync(ge.join(e,fn),"utf8"));return{feature:typeof t.feature=="string"?t.feature:void 0,scenario:typeof t.scenario=="string"?t.scenario:void 0}}catch{return{}}}function Mr(e,t,n){let r=ge.isAbsolute(t)?t:ge.join(e,t),s=new Set(Ee.existsSync(r)?[...Ee.readdirSync(r,{recursive:!0})].map(String).filter(pt).map(l=>ge.join(r,l)):[]);for(let l of["cache","proposals"])for(let d of $a(ge.join(e,".saffron",l))){let{feature:p}=ka(d);if(typeof p=="string"){let u=ge.resolve(e,p);Ee.existsSync(u)&&s.add(u)}}for(let l of Fr(ge.join(e,".saffron","artifacts")))for(let d of Fr(l)){let p=Ra(d).feature;if(p){let u=ge.resolve(e,p);Ee.existsSync(u)&&s.add(u)}}let o=[...n?.unreadable??[]],i=[...s].filter(l=>!n?.parsedFiles.has(l)),a=new Map;if(i.length>0)try{a=ft([...new Set([...Ut(r),...s].filter(l=>l.endsWith(".saffron")))],e)}catch(l){o.push(l instanceof Error?l.message:String(l))}let c=new Set(n?.owned??[]);for(let l of i){let d;try{d=Ce(l,e,a)}catch(p){o.push(`${Xs(e,l)}: ${p instanceof Error?p.message:String(p)}`);continue}for(let p of d)c.add(re(e,p.featurePath,p.name)),c.add(Fe(e,p.featurePath,p.name)),c.add(Qe(e,p.featurePath,p.displayName))}return{...yp(e,c),unreadable:o}}function yp(e,t){let n=[],r=0;for(let o of["cache","proposal"]){let i=ge.join(e,".saffron",o==="cache"?"cache":"proposals");for(let a of $a(i)){if(t.has(a)){r++;continue}let{feature:c,scenario:l}=ka(a),d=c?ge.join(e,c):void 0;n.push({file:Xs(e,a),kind:o,feature:c,scenario:l,reason:c?Ee.existsSync(d)?"scenario-gone":"feature-gone":"unknown"})}}let s=ge.join(e,".saffron","artifacts");for(let o of Fr(s))for(let i of Fr(o)){if(t.has(i)){r++;continue}let{feature:a,scenario:c}=Ra(i);n.push({file:Xs(e,i),kind:"artifact",feature:a,scenario:c,reason:a?Ee.existsSync(ge.join(e,a))?"scenario-gone":"feature-gone":"unknown"})}return{orphans:n,kept:r}}function Fr(e){try{return Ee.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>ge.join(e,t.name)).sort()}catch{return[]}}function Ta(e,t){let n=[],r=new Set;for(let s of t){let o=ge.join(e,s.file);try{s.kind==="proposal"?mn(o,()=>Ee.rmSync(o)):Ee.rmSync(o,{recursive:s.kind==="artifact"}),n.push(s.file),r.add(ge.dirname(o))}catch{}}for(let s of r)try{Ee.readdirSync(s).length===0&&Ee.rmdirSync(s)}catch{}return n}function Ea(e){if(e.kind==="artifact")return`${e.file}/
|
|
15
17
|
failure screenshots of a scenario that no longer exists`;let t=e.feature&&e.scenario?`${e.feature} \u203A ${e.scenario}`:"an unreadable recording",n=e.reason==="feature-gone"?"the feature file is gone":e.reason==="scenario-gone"?"the scenario is gone from that file":"it names no scenario";return`${e.file}
|
|
16
|
-
${e.kind==="proposal"?"pending proposal for ":""}${t}: ${n}`}import
|
|
18
|
+
${e.kind==="proposal"?"pending proposal for ":""}${t}: ${n}`}import mu from"node:path";var wp=/\{date([+-]\d+)?(?::([^}]+))?\}/g;function bp(e,t){let n=String(e.getFullYear()),r=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0");return t.replaceAll("YYYY",n).replaceAll("MM",r).replaceAll("DD",s).replaceAll("M",String(e.getMonth()+1)).replaceAll("D",String(e.getDate()))}function Aa(e,t=new Date){return e.replace(wp,(n,r,s)=>{let o=new Date(t);return o.setDate(o.getDate()+(r?parseInt(r,10):0)),bp(o,s??"YYYY-MM-DD")})}var vp=/\b(\d{4})-(\d{2})-(\d{2})\b/g,Sp=400;function _a(e,t=new Date){let n=new Date(t.getFullYear(),t.getMonth(),t.getDate());return e.replace(vp,(r,s,o,i)=>{let a=new Date(Number(s),Number(o)-1,Number(i));if(Number.isNaN(a.getTime()))return r;let c=Math.round((a.getTime()-n.getTime())/864e5);return Math.abs(c)>Sp?r:c===0?"{date}":`{date${c>0?"+":""}${c}}`})}import{createHash as xp,randomBytes as $p}from"node:crypto";var Ia=/\{unique:([A-Za-z0-9_-]+)(?::(digits))?\}/g,Ue="__saffron_unique_seed",Rt=()=>`${Date.now().toString(36)}${$p(4).toString("hex")}`;function Ca(e,t,n=!1){let r=xp("sha1").update(`${e}:${t}`).digest();if(n){let o=r.readUInt32BE(0)*65536+r.readUInt16BE(4);return String(1e8+o%9e8)}let s=BigInt(`0x${r.subarray(0,8).toString("hex")}`).toString(36).padStart(9,"0").slice(-9);return`${"abcdefghijklmnopqrstuvwxyz"[r[8]%26]}${s}`}function wn(e,t){return e.replace(Ia,(n,r,s)=>Ca(t,r,s==="digits"))}function bn(e,t){let n=new Map;for(let r of e)if(r)for(let s of r.matchAll(Ia))n.set(s[0],Ca(t,s[1],s[2]==="digits"));return n}function Pa(e,t){let n=e;for(let[r,s]of t)n=n.split(s).join(r);return n}import{createHash as kp}from"node:crypto";async function Ht(e){let t;try{t=await e.locator("body").ariaSnapshot({timeout:3e3})}catch{return"sha256:unavailable"}let n=t.replace(/\d+/g,"#").replace(/\s+/g," ").trim();return`sha256:${kp("sha256").update(n).digest("hex")}`}var Rp=/^[a-z][a-z\d+.-]*:|^\/\//i,Oa=e=>e.pathname.replace(/\/+$/,"");function Nn(e,t){if(!t)return e;let n,r;try{n=new URL(e),r=new URL(t)}catch{return e}if(n.origin!==r.origin)return e;let s=Oa(r),o=n.pathname,i;if(o===r.pathname||o===s||o===`${s}/`)i="/";else if(o.startsWith(`${s}/`))i=o.slice(s.length);else return e;let a=n.search===r.search?"":n.search||"?",c=i!=="/"?n.hash:n.hash===r.hash?"":n.hash||(r.hash?"#":"");return`${i}${a}${c}`}function eo(e,t){if(Rp.test(e))return e;if(!t)throw new Error(`relative navigation "${e}" needs a base URL (set baseURL or pass --base-url)`);let n=new URL(t),r=e.indexOf("#"),s=r>=0?e.slice(r):void 0,o=r>=0?e.slice(0,r):e,i=o.indexOf("?"),a=i>=0?o.slice(i):void 0,c=i>=0?o.slice(0,i):o,l=c===""||c==="/",d=new URL(n.href);return d.pathname=l?n.pathname:`${Oa(n)}${c.startsWith("/")?c:`/${c}`}`,d.search=a===void 0?n.search:a==="?"?"":a,d.hash=s==="#"?"":s!==void 0?s:l?n.hash:"",d.toString()}import to from"node:fs";import Tp from"node:os";import Pe from"node:path";import{Client as Ep}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as Ap}from"@modelcontextprotocol/sdk/client/stdio.js";import{McpServer as _p}from"@modelcontextprotocol/sdk/server/mcp.js";import{CallToolRequestSchema as Ip,ListToolsRequestSchema as Cp}from"@modelcontextprotocol/sdk/types.js";var no=6e4;function ja(){return to.mkdtempSync(Pe.join(Tp.tmpdir(),"saffron-mcp-"))}var ro=1e8,Na=new Set(["browser_navigate","browser_click","browser_type","browser_press_sequentially","browser_fill_form","browser_select_option","browser_check","browser_uncheck","browser_press_key","browser_hover","browser_drag","browser_file_upload","browser_handle_dialog","browser_tabs","browser_snapshot","browser_find","browser_wait_for","browser_take_screenshot","browser_console_messages","browser_network_requests","browser_network_request","browser_evaluate"]);function Pp(e){return{...e,tools:e.tools.filter(t=>Na.has(t.name))}}function Op(e){return Na.has(e)?void 0:{isError:!0,content:[{type:"text",text:`${e} is not available in a Saffron session.`}]}}var jp=e=>({isError:!0,content:[{type:"text",text:e}]}),Np=new Set(["http:","https:"]);function Fn(e){if(typeof e!="string"||/^localhost(:\d+)?(\/|$)/i.test(e))return;let t=`${e} is not a web page; a Saffron session only opens http(s) URLs.`,n;try{n=new URL(e)}catch{return/^[a-z][a-z\d+.-]*:/i.test(e.replace(/^[\u0000- ]+/,"").replace(/[\t\n\r]/g,""))?t:void 0}return Np.has(n.protocol)||n.href==="about:blank"?void 0:t}function so(e,t){if(!Array.isArray(e))return;let n=i=>{try{return to.realpathSync(i)}catch{return}},r=n(t)??Pe.resolve(t),s=i=>{let a=Pe.relative(r,i);return a.startsWith("..")||Pe.isAbsolute(a)?void 0:a},o=i=>i.split(Pe.sep).some(a=>a.startsWith(".")&&a!=="..");for(let i of e){if(typeof i!="string")continue;let a=Pe.resolve(i),c=n(a),l=n(Pe.dirname(a)),d=s(c??(l?Pe.join(l,Pe.basename(a)):a));if(d===void 0&&!c&&!l){let p=Pe.relative(Pe.resolve(t),a);!p.startsWith("..")&&!Pe.isAbsolute(p)&&(d=p)}if(d===void 0)return`${i} is outside the project; uploads come from files inside it.`;if(o(d)||o(Pe.relative(Pe.resolve(t),a)))return`${i} is a hidden file; a Saffron session does not upload dotfiles.`;if(!c)return`${i} does not exist; uploads come from files inside the project.`;if(to.statSync(c).isDirectory())return`${i} is a folder; a Saffron session uploads single files only.`}}function Fp(e,t,n=process.cwd()){if(!t)return{args:t};let r=e==="browser_navigate"||e==="browser_tabs"?Fn(t.url):e==="browser_file_upload"?so(t.paths,n):void 0;if(r)return{args:t,refused:jp(r)};if("filename"in t){let{filename:s,...o}=t;return{args:o}}return{args:t}}function Mp(e,t=no){if(!Array.isArray(e.content))return e;let n=!1,r=e.content.map(s=>{if(s.type!=="text"||typeof s.text!="string"||s.text.length<=t)return s;n=!0;let o=`
|
|
17
19
|
|
|
18
|
-
[Saffron cut this result at ${t} of ${s.text.length} characters: whole, it would not fit the agent's context. Ask for less: a snapshot of one region, a filtered request list, or a saffron_assert on the field you need instead of the whole body.]`,i=/[\uD800-\uDBFF]/.test(s.text[t-1])?t-1:t;return{...s,text:s.text.slice(0,i)+o}});return n?{...e,content:r}:e}async function
|
|
19
|
-
`),o=!1;for(let i=0;i<s.length;i++){let a=s[i];if(!a.trim())continue;let c=JSON.parse(a);if(r?.(c),!t.occursIn(a)&&!t.hiddenByEscape.test(a))continue;let l=
|
|
20
|
-
`),"utf8"):void 0}function
|
|
21
|
-
`)?
|
|
22
|
-
`),r=[];for(let s of n){if(!s.trim()){r.push(s);continue}let i=
|
|
23
|
-
`)}var
|
|
24
|
-
`||e==="\r";function
|
|
25
|
-
`)}var
|
|
26
|
-
`))
|
|
27
|
-
`).filter(Boolean).map(g=>
|
|
28
|
-
`)[0]:String(l)}`)}s.length||(a?
|
|
29
|
-
`)[0]}));return{runId:t.toISOString(),startedAt:t.toISOString(),finishedAt:new Date().toISOString(),baseURL:r,green:s.filter(o=>o.status==="green").length,yellow:s.filter(o=>o.status==="yellow").length,red:s.filter(o=>o.status==="red").length,aiCalls:s.reduce((o,i)=>o+i.aiCalls,0),costUsd:s.reduce((o,i)=>o+i.costUsd,0),divergentSteps:n,scenarios:s}}function
|
|
30
|
-
`)}function
|
|
31
|
-
`).filter(i=>i.trim()),s=!1,o=r.map(i=>{try{if(JSON.parse(i).runId===t.runId)return s=!0,JSON.stringify(t)}catch{}return i});s||o.push(JSON.stringify(t)),
|
|
20
|
+
[Saffron cut this result at ${t} of ${s.text.length} characters: whole, it would not fit the agent's context. Ask for less: a snapshot of one region, a filtered request list, or a saffron_assert on the field you need instead of the whole body.]`,i=/[\uD800-\uDBFF]/.test(s.text[t-1])?t-1:t;return{...s,text:s.text.slice(0,i)+o}});return n?{...e,content:r}:e}async function Fa(e,t){let n=new Ep({name:"saffron-cap",version:"1"}),r=Object.fromEntries(Object.entries(process.env).filter(o=>o[1]!==void 0));await n.connect(new Ap({...e,env:r,stderr:"ignore"}));let s=oo(n,void 0,t);return{config:{type:"sdk",name:"playwright",instance:s},close:async()=>{await Promise.allSettled([n.close(),s.close()])}}}function oo(e,t=(r,s,o)=>o(),n){let r=new _p({name:"playwright",version:"1"},{capabilities:{tools:{}}});return r.server.setRequestHandler(Cp,async()=>Pp(await e.listTools())),r.server.setRequestHandler(Ip,async(s,o)=>{let i=Op(s.params.name);if(i)return i;let a=Fp(s.params.name,s.params.arguments,n);if(a.refused)return a.refused;let c={...s.params,arguments:a.args};return Mp(await t(c.name,c.arguments,()=>e.callTool(c,void 0,{timeout:ro,signal:o.signal})))}),r}import Ln from"node:fs";import Hp from"node:os";import io from"node:path";import Oe from"node:fs";import Lp from"node:path";import{createHash as Dp,randomBytes as Bp}from"node:crypto";import Dr from"node:zlib";var Tt=4294967295,La=67324752,Da=33639248,Ba=101010256;function Ua(e){return Mn(e).map(t=>({name:t.name,data:t.read()}))}function za(e,t){let n=Math.max(0,t-22-65535),r=e(n,t-n),s=-1;for(let l=r.length-22;l>=0;l--)if(r.readUInt32LE(l)===Ba){s=l;break}if(s<0)throw new Error("not a zip file: no central directory");let o=r.readUInt16LE(s+10),i=e(r.readUInt32LE(s+16),r.readUInt32LE(s+12)),a=0,c=[];for(let l=0;l<o;l++){if(i.readUInt32LE(a)!==Da)throw new Error("not a zip file: bad central directory entry");let d=i.readUInt16LE(a+10),p=i.readUInt32LE(a+16),u=i.readUInt32LE(a+20),f=i.readUInt32LE(a+24),h=i.readUInt16LE(a+28),w=i.readUInt16LE(a+30),$=i.readUInt16LE(a+32),k=i.readUInt32LE(a+42),y=i.subarray(a+46,a+46+h).toString("utf8");a+=46+h+w+$;let v=e(k,30);if(v.length<30||v.readUInt32LE(0)!==La)throw new Error(`not a zip file: bad local header for ${y}`);let S=k+30+v.readUInt16LE(26)+v.readUInt16LE(28);if(!y.endsWith("/")){if(d!==0&&d!==8)throw new Error(`zip entry ${y} uses compression method ${d}, which is not supported`);c.push({name:y,method:d,crc:p,size:f,compressedSize:u,start:S})}}return c}function Mn(e){return za((t,n)=>e.subarray(t,t+n),e.length).map(({name:t,method:n,crc:r,size:s,compressedSize:o,start:i})=>{let a=e.subarray(i,i+o);return{name:t,method:n,crc:r,size:s,raw:a,read:()=>n===0?Buffer.from(a):Dr.inflateRawSync(a)}})}function Up(e,t,n){let r=Oe.openSync(e,"r");try{let s=Buffer.alloc(n),o=0;for(;o<n;){let i=Oe.readSync(r,s,o,n-o,t+o);if(i===0)break;o+=i}return s.subarray(0,o)}finally{Oe.closeSync(r)}}function Ha(e){let t=Oe.statSync(e).size,n=(r,s)=>Up(e,r,Math.max(0,Math.min(s,t-r)));return za(n,t).map(r=>({...r,raw:()=>n(r.start,r.compressedSize)}))}var zp=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let r=0;r<8;r++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n>>>0}return e})();function Lr(e,t=0){let n=Dr.crc32;if(n)return n(e,t)>>>0;let r=(t^4294967295)>>>0;for(let s of e)r=zp[(r^s)&255]^r>>>8;return(r^4294967295)>>>0}var Ma=1024*1024;function qa(e,t){let n=Oe.openSync(e,"r");try{let r=Buffer.alloc(Ma);for(let s;(s=Oe.readSync(n,r,0,Ma,null))>0;)t(r.subarray(0,s))}finally{Oe.closeSync(n)}}function Br(e){let t=Dp("sha256"),n=0,r=0;return qa(e,s=>{n=Lr(s,n),r+=s.length,t.update(s)}),{crc:n,size:r,sha256:t.digest("hex")}}function Ja(e,t,n,r,s,o){let i=Buffer.alloc(30);i.writeUInt32LE(La,0),i.writeUInt16LE(20,4),i.writeUInt16LE(2048,6),i.writeUInt16LE(t,8),i.writeUInt32LE(0,10),i.writeUInt32LE(n,14),i.writeUInt32LE(r,18),i.writeUInt32LE(s,22),i.writeUInt16LE(e.length,26),i.writeUInt16LE(0,28);let a=Buffer.alloc(46);return a.writeUInt32LE(Da,0),a.writeUInt16LE(20,4),a.writeUInt16LE(20,6),a.writeUInt16LE(2048,8),a.writeUInt16LE(t,10),a.writeUInt32LE(0,12),a.writeUInt32LE(n,16),a.writeUInt32LE(r,20),a.writeUInt32LE(s,24),a.writeUInt16LE(e.length,28),a.writeUInt16LE(0,30),a.writeUInt16LE(0,32),a.writeUInt16LE(0,34),a.writeUInt16LE(0,36),a.writeUInt32LE(0,38),a.writeUInt32LE(o,42),{local:i,central:a}}function Wa(e,t,n){let r=Buffer.alloc(22);return r.writeUInt32LE(Ba,0),r.writeUInt16LE(0,4),r.writeUInt16LE(0,6),r.writeUInt16LE(e,8),r.writeUInt16LE(e,10),r.writeUInt32LE(t,12),r.writeUInt32LE(n,16),r.writeUInt16LE(0,20),r}var Va=e=>new Error(`cannot write a zip of ${e} files: one holds at most 65,535`),Ga=e=>new Error(`cannot write ${e} into a zip: a zip holds at most 4 GB, and this one would be larger`),Ka=()=>new Error("cannot write the zip: a zip holds at most 4 GB, and this one would be larger");function Ya(e){if(e.length>65535)throw Va(e.length);let t=[],n=[],r=0;for(let o of e){let i="raw"in o,a=i?o.raw:Dr.deflateRawSync(o.data),c=i?o.size:o.data.length,l=Buffer.from(o.name,"utf8");if(c>Tt||r+30+l.length+a.length>Tt)throw Ga(o.name);let{local:d,central:p}=Ja(l,i?o.method:8,i?o.crc:Lr(o.data),a.length,c,r);t.push(d,l,a),n.push(p,l),r+=d.length+l.length+a.length}let s=n.reduce((o,i)=>o+i.length,0);if(r+s>Tt)throw Ka();return Buffer.concat([...t,...n,Wa(e.length,s,r)])}function vn(e,t){for(let n=0;n<t.length;)n+=Oe.writeSync(e,t,n,t.length-n)}function Za(e,t){if(t.length>65535)throw Va(t.length);Oe.mkdirSync(Lp.dirname(e),{recursive:!0});let n=`${e}.${process.pid}-${Bp(4).toString("hex")}.partial`,r=Oe.openSync(n,"w");try{let s=[],o=0;for(let a of t){let c=Buffer.from(a.name,"utf8"),l="file"in a,d=l&&(a.crc===void 0||a.size===void 0)?Br(a.file):void 0,p=l?void 0:Dr.deflateRawSync(a.data),u=l?d?.crc??a.crc:Lr(a.data),f=l?d?.size??a.size:a.data.length,h=p?.length??f;if(f>Tt||o+30+c.length+h>Tt)throw Ga(a.name);let{local:w,central:$}=Ja(c,l?0:8,u,h,f,o);if(vn(r,w),vn(r,c),p)vn(r,p);else{let k=0,y=0;if(qa(a.file,v=>{k+v.length>f||(vn(r,v),k+=v.length,y=Lr(v,y))}),k!==f||y!==u)throw new Error(`${a.name} changed while it was being packed`)}s.push($,c),o+=w.length+c.length+h}let i=s.reduce((a,c)=>a+c.length,0);if(o+i>Tt)throw Ka();for(let a of s)vn(r,a);vn(r,Wa(t.length,i,o)),Oe.closeSync(r),Oe.renameSync(n,e)}catch(s){try{Oe.closeSync(r)}catch{}throw Oe.rmSync(n,{force:!0}),s}}var ao=["off","on","retain-on-failure"],co="trace.zip";async function lo(e,t){await e.tracing.start({screenshots:!0,snapshots:!0,sources:!1,title:t})}async function fo(e,t){t&&Ln.mkdirSync(io.dirname(t),{recursive:!0}),await e.tracing.stop(t?{path:t}:void 0)}async function po(e,t,n){let r;try{r=Ln.mkdtempSync(io.join(Hp.tmpdir(),"saffron-trace-"));let s=io.join(r,co);await e.tracing.stop({path:s});let o=tu(Ln.readFileSync(s),n);return Te(t,o),Ve(o)}catch{try{Ln.rmSync(t,{force:!0})}catch{console.warn("Could not remove the execution trace artifact.")}console.warn("Could not save the execution trace; no trace was attached to this run.");return}finally{if(r)try{Ln.rmSync(r,{recursive:!0,force:!0})}catch{console.warn("Could not remove the private temporary trace directory.")}}}async function Xa(e,t,n,r){if(!t)return r();let s=e.context().tracing;await s.group(n).catch(()=>{});try{return await r()}finally{await s.groupEnd().catch(()=>{})}}var qp=new Set(["callId","parentId","pageId","frameId","contextId","pageref","_frameref","snapshotName","beforeSnapshot","afterSnapshot","inputSnapshot","sha1","_sha1"]),Jp=new Set(["before","action","after"]),Wp=/^\[saffron:(?:agent|replay|pending|action):-?\d+\] /,Vp=new Set(["type","class","method"]),Gp=new Set(["__playwright_bounding_rect__","__playwright_scroll_top_","__playwright_scroll_left_","__playwright_target__","__playwright_checked_","__playwright_selected_","__playwright_popover_open_","__playwright_dialog_open_","__playwright_shadow_root_","__playwright_custom_elements__"]),Kp=new Set(["style","__playwright_style_sheet_"]),Yp=new Set(["srcset","imagesrcset"]),Zp=/^(?:image\/(?!svg)|font\/|audio\/|video\/)/i,Qp=/\.(?:jpe?g|png|gif|webp|avif|bmp|ico|woff2?|ttf|otf|eot|mp3|mp4|m4a|wav|ogg|webm)$/i,Xp=/^text\/css\b/i,eu=/\.css$/i;function tu(e,t){let n=Dt(t,{encodings:!0});if(n.empty)return e;let r=Dt(t,{encodings:!0,bytes:!0}),s=Mn(e),o=new Set(s.filter(f=>f.name.includes("/")).map(f=>f.name));for(let f of s)f.name.startsWith("resources/")&&o.add(f.name.slice(10));let i={names:o,pieces:pu(t)},a=new Set,c=new Set,l=f=>{for(let h of[f.snapshot?.response?.content,f.snapshot?.request?.postData]){if(!h)continue;let w=h._file??(h._sha1&&`resources/${h._sha1}`);if(!w)continue;let $=String(h.mimeType??"");Zp.test($)?a.add(w):Xp.test($)&&c.add(w)}},d=[...s],p=!1,u=(f,h)=>{h&&(d[f]={name:s[f].name,data:h},p=!0)};return s.forEach((f,h)=>{/\.(?:trace|network)$/.test(f.name)?u(h,nu(f.read(),n,i,f.name.endsWith(".network")?l:void 0)):f.name.endsWith(".stacks")&&u(h,ru(f.read(),n,i))}),s.forEach((f,h)=>{/\.(?:trace|network|stacks)$/.test(f.name)||a.has(f.name)||Qp.test(f.name)||u(h,su(f.read(),n,r,c.has(f.name)||eu.test(f.name)))}),p?Ya(d):e}function nu(e,t,n,r){let s=e.toString("utf8").split(`
|
|
21
|
+
`),o=!1;for(let i=0;i<s.length;i++){let a=s[i];if(!a.trim())continue;let c=JSON.parse(a);if(r?.(c),!t.occursIn(a)&&!t.hiddenByEscape.test(a))continue;let l=go(a,t,{keys:!1,numbers:!1,playwright:n});l!==a&&(s[i]=l,o=!0)}return o?Buffer.from(s.join(`
|
|
22
|
+
`),"utf8"):void 0}function ru(e,t,n){let r=e.toString("utf8");if(JSON.parse(r),!t.occursIn(r)&&!t.hiddenByEscape.test(r))return;let s=go(r,t,{keys:!1,numbers:!1,playwright:n});return s===r?void 0:Buffer.from(s,"utf8")}function su(e,t,n,r=!1){if(r){let d=e.toString("latin1"),p=rc(d,n);return p===d?void 0:Buffer.from(p,"latin1")}let s=e.toString("utf8"),o=s.startsWith("\uFEFF")?"\uFEFF":"",i=s.slice(o.length);if(!s.includes("\uFFFD")||Buffer.from(s,"utf8").equals(e)){let d=/^\s*[[{"]/.test(i)?ec(i,t):void 0,p=d===void 0&&/^\s*(?:[[{"\d-]|true|false|null)/.test(i)&&i.trim().includes(`
|
|
23
|
+
`)?ou(i,t):void 0,u=d??p;if(u!==void 0)return u===i?void 0:Buffer.from(o+u,"utf8")}let c=e.toString("latin1"),l=n.mask(c);return l===c?void 0:Buffer.from(l,"latin1")}function ec(e,t){try{JSON.parse(e)}catch(n){if(n instanceof SyntaxError)return;throw n}return!t.occursIn(e)&&!t.hiddenByEscape.test(e)?e:go(e,t,{keys:!0,numbers:!0})}function ou(e,t){let n=e.split(`
|
|
24
|
+
`),r=[];for(let s of n){if(!s.trim()){r.push(s);continue}let i=ec(s,t);if(i===void 0)return;r.push(i)}return r.join(`
|
|
25
|
+
`)}var tc=/^([a-z][a-z0-9+.-]*:\/\/)([^/?#]*@)?([^/?#]*)/i;function nc(e,t=0,n=e.length){let r=tc.exec(e.slice(t,n));if(!r)return;let[s,o,i=""]=r,a=t+o.length+i.length;return c=>c>=t&&c<t+o.length||c>=a-(i?1:0)&&c<=t+s.length&&c<n}function iu(e,t,n){let r="",s=0;for(let o of t.matches(e)){let{token:i,kept:a=()=>!1}=n(o),c="";for(let l=o.start;l<o.end;){if(a(l)){c+=e[l++];continue}for(;l<o.end&&!a(l);)l++;c+=i(o.names)}c!==e.slice(o.start,o.end)&&(r+=e.slice(s,o.start)+c,s=o.end)}return s===0?e:r+e.slice(s)}var au=e=>e.map(t=>`%7Benv:${t}%7D`).join(""),cu=e=>e.map(t=>`\\{env\\:${t}\\}`).join("");function uo(e,t,n,r){let s=n.map(([i,a])=>({start:i,end:a,kept:nc(e,i,a)})),o=0;return iu(e,t,i=>{for(;o<s.length&&s[o].end<i.end;)o++;let a=s[o];return a&&a.start<=i.start&&i.end<=a.end?{token:au,kept:a.kept}:{token:r}})}function lu(e,t){return nc(e)?uo(e,t,[[0,e.length]],On):t.mask(e)}var du=/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)\s'"]*))|@import\s+(?:"([^"]*)"|'([^']*)')/dgi;function rc(e,t){if(!t.occursIn(e))return e;let n=[...e.matchAll(du)].map(r=>r.indices.slice(1).find(s=>s!==void 0));return uo(e,t,n,cu)}function fu(e,t){let n=[];for(let r=0;r<e.length;){for(;r<e.length&&/[\s,]/.test(e[r]);)r++;let s=r;for(;s<e.length&&!/\s/.test(e[s]);)s++;let o=s;for(;o>r&&e[o-1]===",";)o--;if(o>r&&n.push([r,o]),r=s,o===s)for(;r<e.length&&e[r]!==",";)r++}return uo(e,t,n,On)}function pu(e){let t=new Map;for(let[n,r]of e)if(!(r.length<Lt||!tc.test(r)||!URL.canParse(r)))for(let s of new URL(r).searchParams.values())s.length>=Lt&&!t.has(s)&&t.set(s,n);return t}var Qa=e=>e===" "||e===" "||e===`
|
|
26
|
+
`||e==="\r";function go(e,t,n){let r=[],s=0,o,i=[],a=c=>{let l=c-1;for(;l>=0&&Qa(e[l]);)l--;return e[l]};for(let c=0;c<e.length;c++){let l=e[c];if(l==="{"||l==="["){let d=i.at(-1),p=a(c)===":"?o:void 0;i.push({dom:(d?.dom??!1)||p==="html",logged:(d?.logged??!1)||p==="value"});continue}if(l==="}"||l==="]"){i.pop();continue}if(l==='"'){let d=c++,p=!1;for(;c<e.length&&e[c]!=='"';c++)e[c]==="\\"&&(p=!0,c++);let u=c+1,f=u;for(;f<e.length&&Qa(e[f]);)f++;let h=e[f]===":",w=p?JSON.parse(e.slice(d,u)):e.slice(d+1,c),$=i.at(-1),k=!h&&a(d)===":"?o:void 0,y=x=>t.mask(x);if(h){if(o=w,!n.keys)continue}else if(n.playwright){if(i.length===1&&k!==void 0&&Vp.has(k)||n.playwright.names.has(w))continue;let{pieces:x}=n.playwright;if(y=b=>x.has(b)?On([x.get(b)]):lu(b,t),$?.dom){if(a(d)==="["){$.tag=w.toUpperCase();continue}let b=k===void 0?$.tag:i.at(-2)?.tag;if(k!==void 0&&Gp.has(k)||k==="src"&&(b==="IFRAME"||b==="FRAME"))continue;k===void 0&&b==="STYLE"||k!==void 0&&Kp.has(k)?y=R=>rc(R,t):k!==void 0&&Yp.has(k)&&(y=R=>fu(R,t))}else if(k!==void 0&&qp.has(k)||k==="phase"&&Jp.has(w))continue}let v=n.playwright&&i.length===1&&k==="title"?Wp.exec(w)?.[0]??"":"",S=v+y(w.slice(v.length));S!==w&&(r.push(e.slice(s,d),JSON.stringify(S)),s=u)}else if(l==="-"||l>="0"&&l<="9"){let d=c+1;for(;d<e.length&&/[0-9eE.+-]/.test(e[d]);)d++;(n.numbers||(i.at(-1)?.logged??!1)||a(c)===":"&&o==="value")&&t.isValue(e.slice(c,d))&&(r.push(e.slice(s,c),JSON.stringify(t.mask(e.slice(c,d)))),s=d),c=d-1}}return r.length?r.join("")+e.slice(s):e}function ie(e,t=200){let n=e.replace(/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)?|\x1b[@-_]?/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"");return n.length>t?`${n.slice(0,t-3)}...`:n}function Bn(e){return Array.isArray(e)?e.map(Bn):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([t,n])=>n!==void 0&&t!=="pageFingerprint").sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Bn(n)])):e}var ho=e=>JSON.stringify(Bn(e));function mo(e,t="",n={}){if(Array.isArray(e))n[t]=e.map(r=>String(r)).join(", ");else if(e&&typeof e=="object")for(let[r,s]of Object.entries(e))mo(s,t?`${t}.${r}`:r,n);else t&&(n[t]=String(e));return n}function uu(e,t){let n=mo(Bn(e)),r=mo(Bn(t)),s=[...new Set([...Object.keys(n),...Object.keys(r)])].sort(),o=[];for(let i of s){if(i==="action"||n[i]===r[i])continue;let a=i.replace(/^target\./,"").replace(/^toTarget\./,"destination ");n[i]===void 0?o.push(`${a}: added "${r[i]}"`):r[i]===void 0?o.push(`${a}: removed "${n[i]}"`):o.push(`${a}: "${n[i]}" \u2192 "${r[i]}"`)}return o}function ac(e,t,n){let r=e.map(n),s=t.map(n),o=Array.from({length:r.length+1},()=>new Array(s.length+1).fill(0));for(let l=r.length-1;l>=0;l--)for(let d=s.length-1;d>=0;d--)o[l][d]=r[l]===s[d]?o[l+1][d+1]+1:Math.max(o[l+1][d],o[l][d+1]);let i=[],a=0,c=0;for(;a<r.length&&c<s.length;)r[a]===s[c]?(i.push({before:e[a],after:t[c]}),a++,c++):o[a+1][c]>=o[a][c+1]?(i.push({before:e[a]}),a++):(i.push({after:t[c]}),c++);for(;a<r.length;a++)i.push({before:e[a]});for(;c<s.length;c++)i.push({after:t[c]});return i}function sc(e){if(!e)return"";let t=[];if(e.role){let n=e.name?` "${e.name}"`:e.nameRegex?` matching /${e.nameRegex}/`:"";t.push(`${e.role}${n}`)}else e.label?t.push(`label "${e.label}"`):e.text?t.push(`text "${e.text}"`):e.placeholder?t.push(`placeholder "${e.placeholder}"`):e.testId&&t.push(`test id ${e.testId}`);return e.fallbackSelectors?.length&&t.push(`[${e.fallbackSelectors.join(", ")}]`),e.frame&&t.push(`inside frame ${e.frame}`),t.join(" ")}var oc=e=>`${e.method??"any"} /${e.urlPattern}/ ${e.status??"2xx"}`+(e.pattern?` with a body matching /${e.pattern}/`:"");function Me(e){let t=sc(e.target),n=e.value??"",r=(()=>{switch(e.action){case"goto":return`go to ${e.url}`;case"click":return`click ${t}`;case"fill":return`fill ${t} with "${n}"`;case"press":return t?`press ${n} on ${t}`:`press ${n}`;case"selectOption":return`select "${n}" in ${t}`;case"check":return`check ${t}`;case"uncheck":return`uncheck ${t}`;case"hover":return`hover ${t}`;case"waitFor":return t?`wait for ${t}`:`wait ${n}ms`;case"captureText":return`remember ${t} as "${e.saveAs}"`;case"handleDialog":return`${n} the dialog${e.promptText?` with "${e.promptText}"`:""}`;case"uploadFile":return`upload ${n}`;case"dragTo":return`drag ${t} onto ${sc(e.toTarget)}`;case"waitForResponse":return`wait for ${oc(e)}`;case"switchTab":return`switch to tab ${n}`;case"closeTab":return`close tab ${n||"(the current one)"}`;case"newTab":return`open a new tab${e.url?` at ${e.url}`:""}`;case"expectVisible":return`expect ${t} to be visible`;case"expectNotVisible":return`expect ${t} to be gone`;case"expectText":return`expect ${t} to contain "${n}"`;case"expectUrl":return`expect the URL to contain "${e.url??n}"`;case"expectValue":return`expect ${t} to hold "${n}"`;case"expectDiffers":return`expect ${t||`"${n}"`} to differ from "${e.compareTo}"`;case"expectMatches":return`expect ${t} to match /${e.pattern}/`;case"expectAttribute":return`expect ${t} ${e.attribute} to match /${e.pattern}/`;case"expectResponse":return`expect a response ${oc(e)}`;case"expectEach":return`expect ${t} to show every value of ${e.each}`;default:return e.action}})();return e.opensTab?`${r}, opening a tab`:r}var Dn=e=>Ne.has(e.action);function gu(e,t){let n=ac(e,t,ho),r=[];for(let s=0;s<n.length;s++){let o=n[s];if(o.before&&o.after){r.push({change:"same",before:Me(o.before),after:Me(o.after),assertion:Dn(o.after)});continue}let i=n[s+1];if(o.before&&i?.after&&!i.before){r.push({change:"changed",before:Me(o.before),after:Me(i.after),details:uu(o.before,i.after),assertion:Dn(o.before)||Dn(i.after)}),s++;continue}o.before&&r.push({change:"removed",before:Me(o.before),assertion:Dn(o.before)}),o.after&&r.push({change:"added",after:Me(o.after),assertion:Dn(o.after)})}return r}var hu=e=>`${e.kind}\0${e.gherkin}`;function Et(e,t,n=[]){let r=ac(e?.steps??[],t.steps,hu),s=[],o={added:0,removed:0,changed:0,assertions:0};for(let i of r){let a=i.after??i.before,c=gu(i.before?.actions??[],i.after?.actions??[]);for(let d of c)d.change==="added"?o.added++:d.change==="removed"?o.removed++:d.change==="changed"&&o.changed++,d.change!=="same"&&d.assertion&&o.assertions++;let l=e&&i.before?i.after?c.some(d=>d.change!=="same")?"changed":"same":"removed":"added";s.push({gherkin:a.gherkin,kind:a.kind,fromStepSet:a.fromStepSet,change:l,actions:c})}return{feature:t.feature,scenario:t.scenario,hasCommitted:e!==void 0,steps:s,summary:o,...n.length>0?{featureEdits:n.map(i=>({index:i.index,from:t.steps[i.index]?.gherkin??`step ${i.index+1}`,to:i.text,fromStepSet:t.steps[i.index]?.fromStepSet}))}:{}}}var ic=new Set(["goto","click","press","newTab","switchTab","closeTab"]);function cc(e,t){let n=[],r=s=>`${s} navigation action${s===1?"":"s"}`;for(let s=0;s<Math.min(e.length,t.length);s++){let o=e[s].actions.filter(p=>ic.has(p.action)),a=[...t[s].actions.filter(p=>ic.has(p.action))],c=[];for(let p of o){let u=a.findIndex(f=>ho(f)===ho(p));u>=0?a.splice(u,1):c.push(p)}let l=a;for(let p=c.length-1;p>=0;p--){let u=l.findIndex(f=>f.action===c[p].action);u>=0&&(l.splice(u,1),c.splice(p,1))}let d=`step ${s+1} ("${e[s].gherkin}")`;c.length>0&&n.push(`flow change: ${d} no longer performs ${r(c.length)} from the committed recording: ${c.map(Me).join("; ")}. A page or navigation step may have been removed or merged.`),l.length>0&&n.push(`flow change: ${d} now performs ${r(l.length)} the committed recording did not: ${l.map(Me).join("; ")}. A page or navigation step may have been added or reordered.`)}return n}function Ur(e){let t=[];t.push(`${e.feature} \u203A ${e.scenario}`),t.push(e.hasCommitted?"Comparing the committed recording with the proposed one.":"First recording for this scenario: there is nothing to compare against."),t.push("");for(let i of e.steps){let a=i.change==="removed"?"- ":i.change==="added"&&e.hasCommitted?"+ ":" ";t.push(`${a}${i.kind==="assertion"?"[assertion] ":""}${i.gherkin}`+(i.fromStepSet?` (from step set "${i.fromStepSet}")`:""));for(let c of i.actions)if(c.change==="same")t.push(` ${c.before}`);else if(c.change==="added")t.push(` + ${c.after}`);else if(c.change==="removed")t.push(` - ${c.before}`);else{t.push(` - ${c.before}`),t.push(` + ${c.after}`);for(let l of c.details??[])t.push(` ${l}`)}t.push("")}if(e.featureEdits?.length){t.push("Feature file edits, applied only by saffron accept --with-feature-edit:");for(let i of e.featureEdits){let a=i.fromStepSet?` (step set "${i.fromStepSet}": every scenario that uses it)`:"";t.push(` - ${i.from}${a}`,` + ${i.to}`)}t.push("")}let{added:n,removed:r,changed:s,assertions:o}=e.summary;return t.push(n+r+s===0?"No action changed.":`${s} changed, ${n} added, ${r} removed.`+(o>0?` ${o} of them ${o===1?"is an assertion":"are assertions"}: read those first.`:"")),t.map(i=>ie(i,1/0)).join(`
|
|
27
|
+
`)}var vo=e=>new Promise(t=>setTimeout(t,e)),wo=class{entries=[];seq=0;prevStepSeq=0;curStepSeq=0;listener;context;attach(t,n){this.context=t,this.listener=r=>{let s={seq:++this.seq,url:r.url(),method:r.request().method(),status:r.status()};if(this.entries.push(s),n){let o=r.headers()["content-type"]??"";/json|text|xml/i.test(o)&&r.text().then(i=>{s.body=i.length>262144?i.slice(0,262144):i}).catch(()=>{})}},t.on("response",this.listener)}detach(){this.context&&this.listener&&this.context.off("response",this.listener)}markStep(){this.prevStepSeq=this.curStepSeq,this.curStepSeq=this.seq}sincePreviousStep(){return this.entries.filter(t=>t.seq>this.prevStepSeq)}all(){return this.entries}};function yu(e,t){if(!t)return e>=200&&e<300;let n=/^([1-5])xx$/i.exec(t.trim());if(n){let r=Number(n[1])*100;return e>=r&&e<r+100}return e===Number(t.trim())}function lc(e,t,n,r,s){return!(!t.test(e.url)||n&&e.method.toUpperCase()!==n.toUpperCase()||!yu(e.status,r)||s&&!s.test(e.body??""))}var wu=(e,t)=>`response matching ${e.method??"any-method"} /${t}/ status ${e.status??"2xx"}${e.pattern?` body /${e.pattern}/`:""}`,dc=new Set(["click","fill","press","selectOption","check","uncheck","hover","dragTo","uploadFile"]),bu=/(?<=(?:^|[^\\])(?:\\\\)*)(\\?)(<[^<>]+>|\{(?:env|data|date)[^{}]*\})/g;function uc(e,t,n){return Ki($r(vr(Aa(cn(e,t))),n))}function bo(e,t,n,r=!1){return e.replace(bu,(s,o,i,a)=>{let c=e.slice(Math.max(0,a-2),a);if(i.startsWith("<")&&(c==="(?"||c==="\\k"))return s;let l=t(i);return l===i?s:(r?"":o)+n(l)})}function fc(e,t,n,r=!1,s=!0,o=new Set){let i=l=>uc(l,n,o),a=[],c=l=>{if(t.role){let d=t.nameRegex?new RegExp(bo(t.nameRegex,i,we.pattern,!0),"i"):t.name?i(t.name):void 0,p=t.role;d===void 0&&!!(t.label||t.placeholder||t.text||t.testId||t.fallbackSelectors?.length)?t.text&&a.push(l.getByRole(p).filter({hasText:i(t.text)})):typeof d=="string"?(a.push(l.getByRole(p,{name:d,exact:!0})),s&&a.push(l.getByRole(p,{name:d,exact:!1}))):a.push(l.getByRole(p,{name:d,exact:!1}))}t.label&&a.push(l.getByLabel(i(t.label))),t.placeholder&&a.push(l.getByPlaceholder(i(t.placeholder))),t.text&&!t.role&&a.push(l.getByText(i(t.text))),t.testId&&a.push(l.getByTestId(i(t.testId)));for(let d of t.fallbackSelectors??[])a.push(l.locator(ln(d,(p,u)=>bo(p,i,we[u],u==="regex"),i)))};if(t.frame)c(e.frameLocator(i(t.frame)));else if(c(e),r)for(let l of e.frames())l!==e.mainFrame()&&c(l);if(a.length===0)throw new Error("Action target has neither role nor fallback selectors");return a}var gc=100;async function vu(e,t,n,r){let s=Date.now()+t,o;for(;Date.now()<s;){try{if(await e())return}catch(i){o=i}await vo(r)}throw new Error(`Timed out waiting for ${n}${o?` (${String(o)})`:""}`)}async function nt(e,t,n=!1){let r;for(let s of e)try{await t(s.first());return}catch(o){if(r=o,n&&await s.first().count().catch(()=>0)>0)throw o}throw r}var yo=e=>e.replace(/\s+/g," ").trim(),Un=new WeakMap;async function Hr(e,t,n,r,s,o=new Map,i,a=gc,c=new Set){let l=(b,R,m)=>vu(b,R,m,a),d=Un.get(e);if(d&&dc.has(t.action)&&t.action!=="uploadFile"){Un.delete(e);let b,R=g=>{b??=g};e.on("filechooser",R);let m;try{if(m=await Hr(e,t,n,r,s,o,i,a,c),b||await e.waitForEvent("filechooser",{timeout:r}).then(R,()=>{}),!b)throw new Error(`uploadFile failed: the ${t.action} after it opened no file chooser within ${r} ms`);try{await b.setFiles(d,{timeout:r})}catch(g){throw new Error(`uploadFile failed: ${g instanceof Error?g.message:String(g)}`)}}catch(g){throw Un.set(e,d),g}finally{e.off("filechooser",R)}return m}o.has(Ue)||o.set(Ue,Rt());let p=o.get(Ue),u=b=>typeof b=="string"?wn(b,p):Array.isArray(b)?b.map(u):b&&typeof b=="object"?Object.fromEntries(Object.entries(b).map(([R,m])=>[R,u(m)])):b;t=u(t),n=u(n);let f=b=>uc(b,n,c),h=b=>bo(b,f,we.pattern,!0),w=t.value!==void 0?f(t.value):void 0,$=t.url!==void 0?f(t.url):void 0,k=t.action==="expectVisible"||t.action==="expectText"||t.action==="expectValue"||t.action==="expectMatches"||t.action==="expectAttribute"||t.action==="expectEach"||t.action==="captureText",y=t.target?fc(e,t.target,n,k,!dc.has(t.action),c):[],v={timeout:r},S={timeout:Math.min(1e3,r)},x=b=>async()=>{for(let R of y)try{if(await b(R.first()))return!0}catch{}return!1};switch(t.action){case"goto":{if(!$)throw new Error("goto requires url");let b=Fn($);if(b)throw new Error(b);await e.goto(eo($,s),v);return}case"click":return nt(y,b=>b.click(v),!0);case"fill":return nt(y,b=>b.fill(w??"",v),!0);case"press":return y.length>0?nt(y,b=>b.press(w??"",v),!0):e.keyboard.press(w??"");case"selectOption":return nt(y,async b=>{await b.selectOption(w??"",v)},!0);case"check":return nt(y,b=>b.check(v),!0);case"uncheck":return nt(y,b=>b.uncheck(v),!0);case"hover":return nt(y,b=>b.hover(v),!0);case"waitFor":return y.length>0?nt(y,b=>b.waitFor({state:"visible",timeout:r})):vo(Math.min(Number(w??"0"),r));case"expectVisible":return l(x(b=>b.isVisible()),r,"target to be visible");case"expectNotVisible":return l(async()=>{for(let b of y){let R=await b.count();for(let m=0;m<R;m++)if(await b.nth(m).isVisible())return!1}return!0},r,`every match of every recorded locator to be hidden (${y.length} locator(s))`);case"expectText":return l(x(async b=>(await b.textContent(S)??"").includes(w??"")),r,`text "${w}"`);case"expectEach":{let b=t.each?.match(/^\{data:([^}]+)\}$/)?.[1];if(!b)throw new Error(`expectEach needs a {data:...} list reference, got ${JSON.stringify(t.each)}`);let R=vt(b),m=async T=>await T.isVisible()?new Set(await T.evaluate(E=>{let A=M=>(M??"").replace(/\s+/g," ").trim(),P=M=>typeof M.checkVisibility=="function"?M.checkVisibility({visibilityProperty:!0,contentVisibilityAuto:!0}):!!(M.offsetWidth||M.offsetHeight||M.getClientRects().length),O=M=>{let B=M.ownerDocument.createTreeWalker(M,4),_="";for(let j=B.nextNode();j;j=B.nextNode())j.parentElement&&P(j.parentElement)&&(_+=j.nodeValue??"");return _},I=new Set,N=M=>{for(let B of Array.from(M.options))B.hidden||I.add(A(B.textContent))};E.tagName==="SELECT"&&N(E);for(let M of Array.from(E.querySelectorAll("*")))P(M)&&(M.tagName==="SELECT"?N(M):M.tagName!=="OPTION"&&I.add(A(O(M))));I.add(A(O(E)));for(let M of String(E.innerText??"").split(`
|
|
28
|
+
`))I.add(A(M));return[...I]},void 0,S)):new Set,g=R;return l(async()=>{for(let T of y)try{let E=await m(T.first()),A=R.filter(P=>!E.has(P.replace(/\s+/g," ").trim()));if(A.length<g.length&&(g=A),A.length===0)return!0}catch{}return!1},r,`every value of ${t.each} to be shown`).catch(()=>{throw new Error(`${g.map(T=>`"${T}"`).join(", ")} from ${t.each} ${g.length===1?"is":"are"} not shown in the target (${R.length-g.length} of ${R.length} found)`)})}case"expectValue":return l(x(async b=>await b.inputValue(S)===(w??"")),r,`input value "${w}"`);case"expectUrl":{let b=$??w??"";return l(async()=>e.url().includes(b),r,`URL containing "${b}" on the active page (${e.url()})`)}case"handleDialog":{let b=(w??"accept")!=="dismiss",R=t.promptText?f(t.promptText):void 0;e.once("dialog",m=>{b?m.accept(R):m.dismiss()});return}case"uploadFile":{let b=Ae().root,R=(w??"").split(`
|
|
29
|
+
`).filter(Boolean).map(g=>mu.resolve(b,g));if(R.length===0)throw new Error("uploadFile requires a path");let m=so(R,b);if(m)throw new Error(m);if(y.length>0)return nt(y,g=>g.setInputFiles(R,v),!0);Un.set(e,R);return}case"dragTo":{if(!t.toTarget)throw new Error("dragTo requires toTarget");let b=fc(e,t.toTarget,n,!1,!1,c);return nt(y,R=>R.dragTo(b[0].first(),v),!0)}case"captureText":{if(!t.saveAs)throw new Error("captureText requires saveAs");return l(x(async b=>{let R=yo(await b.textContent(S)??"");return R===""?!1:(o.set(t.saveAs,R),!0)}),r,`non-empty text to capture as "${t.saveAs}"`)}case"expectDiffers":{if(!t.compareTo)throw new Error("expectDiffers requires compareTo");let b=o.get(t.compareTo);if(b===void 0)throw new Error(`expectDiffers: no captured value named "${t.compareTo}"`);if(y.length>0)return l(x(async g=>yo(await g.textContent(S)??"")!==b),r,`target text to differ from "${t.compareTo}" (${b})`);let R=w??"",m=o.get(R);if(m===void 0)throw new Error(`expectDiffers: no captured value named "${R}"`);if(m===b)throw new Error(`expectDiffers: "${R}" (${m}) equals "${t.compareTo}" (${b})`);return}case"expectAttribute":{if(!t.attribute)throw new Error("expectAttribute requires attribute");if(!t.pattern)throw new Error("expectAttribute requires pattern");let b=new RegExp(h(t.pattern),"i");return l(x(async R=>b.test(await R.getAttribute(t.attribute,S)??"")),r,`attribute ${t.attribute} to match /${t.pattern}/i`)}case"expectMatches":{if(!t.pattern)throw new Error("expectMatches requires pattern");let b=new RegExp(h(t.pattern),"i");return l(x(async R=>b.test(yo(await R.textContent(S)??""))),r,`target text to match /${t.pattern}/i`)}case"switchTab":{let b=Number.parseInt(w??"",10),R=()=>e.context().pages().filter(g=>!g.isClosed());await l(async()=>R().length>b,r,`tab ${w} to exist (${R().length} open: ${R().map(g=>g.url()).join(", ")})`);let m=R()[b];return await m.bringToFront(),m}case"closeTab":{let b=e.context().pages().filter(g=>!g.isClosed()),R=w===void 0?e:b[Number.parseInt(w,10)];if(!R)throw new Error(`tab ${w} does not exist (${b.length} open)`);await R.close();let m=e.context().pages().filter(g=>!g.isClosed());if(m.length===0)throw new Error("closed the last tab; nothing left to drive");return m[m.length-1]}case"newTab":{let b=$?Fn($):void 0;if(b)throw new Error(b);let R=await e.context().newPage();return $&&await R.goto(eo($,s),v),R}case"waitForResponse":case"expectResponse":{if(!t.urlPattern)throw new Error(`${t.action} requires urlPattern`);let b=new RegExp(h(t.urlPattern)),R=t.pattern?new RegExp(h(t.pattern)):void 0;if(!i){await e.waitForResponse(async g=>{let T={seq:0,url:g.url(),method:g.request().method(),status:g.status()};return lc(T,b,t.method,t.status,void 0)?R?R.test(await g.text().catch(()=>"")):!0:!1},v);return}let m=()=>t.action==="expectResponse"?i.all():i.sincePreviousStep();return l(async()=>m().some(g=>lc(g,b,t.method,t.status,R)),r,wu(t,t.urlPattern))}default:throw new Error(`Unknown action type: ${t.action}`)}}var zr=(e,t)=>jn(e.actions,t),pc=(e,t)=>un(e.actions,t);function zn(e,t){if(t.steps.length!==e.steps.length)return!1;for(let[n,r]of Object.entries(t.data??{})){let s;try{s=on(n)}catch{continue}if(s===r)continue;let o=t.steps.some(a=>zr(a,`{data:${n}}`)),i=t.steps.some(a=>pc(a,r));if(!o||i)return!1}return t.steps.every((n,r)=>{let s=e.steps[r];if(n.gherkin!==s.text||n.kind!==s.kind)return!1;let o=n.table,i=s.table;if(!!o!=!!i)return!1;if(o&&i){let a=Object.keys(ke(o)),c=Object.keys(ke(i));if(a.length>0&&c.length>0){if(JSON.stringify(a)!==JSON.stringify(c))return!1;let l=ke(o),d=ke(i);for(let p of a){if(l[p]===d[p])continue;let u=`<${p}>`,f=t.steps.some(w=>zr(w,u)),h=t.steps.some(w=>pc(w,l[p]));if(!f||h)return!1}}else if(JSON.stringify(o)!==JSON.stringify(i))return!1}if(n.docString!==void 0!=(s.docString!==void 0))return!1;if(n.docString!==void 0&&s.docString!==void 0&&n.docString!==s.docString){let a=t.steps.some(l=>zr(l,"<docstring>")),c=t.steps.some(l=>zr(l,n.docString));if(!a||c)return!1}return!0})}function So(e,t){let n=e.steps[t],r=n?.resolvedTable??n?.table;return{...e.params,...St(e.steps),...ke(r),...Bt(n?.resolvedDocString??n?.docString)}}async function Hn(e,t,n,r={}){let s=r.actionTimeoutMs??5e3,o=r.retries??1,i=Math.max(10,r.pollIntervalMs??gc),a=[],c=r.envNames??_e(t),l=r.vars??new Map;r.uniqueSeed&&l.set(Ue,r.uniqueSeed);for(let m of e.context().pages())Un.delete(m);let d=()=>Object.fromEntries(l),p=n.steps.some(m=>m.actions.some(g=>(g.action==="waitForResponse"||g.action==="expectResponse")&&g.pattern!==void 0)),u=new wo;u.attach(e.context(),p);let f=!1,h=()=>(f=r.keepResponseLog===!0,f?{responses:u}:{}),w=e,$=new Set(e.context().pages()),k=[],y=m=>k.push(m);e.context().on("page",y);let v=m=>new Promise(g=>{let T=()=>{clearTimeout(E),e.context().off("page",T),g()},E=setTimeout(T,m);e.context().on("page",T)}),S=[],b=!n.steps.some(m=>m.actions.some(g=>g.opensTab))&&n.steps.some(m=>m.actions.some(g=>g.action==="switchTab"||g.action==="closeTab"||g.action==="newTab")),R=()=>{let m=e.context().pages();for(let g of m)$.has(g)||($.add(g),g.isClosed()||(w=g));if(w.isClosed()){let g=m.filter(T=>!T.isClosed());g.length>0&&(w=g[g.length-1])}};if(!zn(t,n))return u.detach(),e.context().off("page",y),{status:"stale",stepResults:a,captured:d()};try{for(let m=0;m<n.steps.length;m++){let g=n.steps[m],T=So(t,m);u.markStep();let E=!1,A=0;r.trace&&await e.context().tracing.group(`[saffron:${r.tracePhase??"replay"}:${m+(r.traceStepOffset??0)}] ${g.keyword} ${g.gherkin}`).catch(()=>{});let P=async()=>{r.trace&&await e.context().tracing.groupEnd().catch(()=>{})};try{if(g.kind==="assertion"&&!g.actions.some(O=>Ne.has(O.action))){let O=`Assertion step "${g.gherkin}" recorded ${g.actions.length===0?"nothing":"only setup actions"}, so nothing was checked. Re-record the scenario (saffron run --rerecord) so the agent records what must be true.`;a.push({gherkin:g.gherkin,fromStepSet:g.fromStepSet,kind:g.kind,status:"failed",drift:E,error:O});for(let I=m+1;I<n.steps.length;I++)a.push({gherkin:n.steps[I].gherkin,kind:n.steps[I].kind,status:"skipped"});return{status:"failed",failure:{stepIndex:m,actionIndex:0,stepText:g.gherkin,kind:g.kind,error:O},stepResults:a,captured:d(),...h()}}for(let O=0;O<g.actions.length;O++){let I=g.actions[O];R(),I.pageFingerprint&&await Ht(w)!==I.pageFingerprint&&(E=!0);let N,M=!1;for(let B=0;B<=o&&!M;B++){B>0&&(A++,await vo(250*B),R());try{let _=B>0?`${Me(I)} (attempt ${B+1})`:Me(I),j=await Xa(w,r.trace,`[saffron:action:${O}] ${_}`,()=>Hr(w,I,T,s,r.baseURL,l,u,i,c));j&&(w=j,$.add(j));let U=I.action==="click"||I.action==="press";if(k.length===0&&I.opensTab?await e.context().waitForEvent("page",{timeout:s}).catch(()=>{}):k.length===0&&U&&b&&await v(150),I.opensTab&&k.length===0)throw new Error("this action opened a new tab when it was recorded, and none opened now; the flow has changed");for(k.length>0&&S.push({stepIndex:m,actionIndex:O});k.length>0;)await k.shift().waitForLoadState("domcontentloaded",{timeout:s}).catch(()=>{});M=!0}catch(_){N=_}}if(!M){let B=N instanceof Error?N.message:String(N);a.push({gherkin:g.gherkin,fromStepSet:g.fromStepSet,kind:g.kind,status:"failed",drift:E,...A?{retries:A}:{},failedActionIndex:O,error:B});for(let j=m+1;j<n.steps.length;j++)a.push({gherkin:n.steps[j].gherkin,kind:n.steps[j].kind,status:"skipped"});let _={stepIndex:m,actionIndex:O,stepText:g.gherkin,kind:g.kind,error:B,pageUrl:w.isClosed()?void 0:w.url()};return await r.onFailure?.(w,_).catch(()=>{}),{status:"failed",failure:_,stepResults:a,captured:d(),tabOpeners:S,activePage:w.isClosed()?void 0:w,...h()}}}a.push({gherkin:g.gherkin,fromStepSet:g.fromStepSet,kind:g.kind,status:"passed",drift:E,...A?{retries:A}:{}})}finally{await P()}}return{status:"passed",stepResults:a,captured:d(),tabOpeners:S,activePage:w.isClosed()?void 0:w}}finally{e.context().off("page",y),f||u.detach()}}import{createHash as Su}from"node:crypto";import xu from"node:path";var xo=e=>Su("sha1").update(JSON.stringify(e)).digest("hex").slice(0,16);function hc(e){return{steps:e.steps.map(t=>({...t,actions:t.actions.map(({pageFingerprint:n,...r})=>r)})),data:e.data??null}}var mc=e=>xo(e.map(t=>[t.kind,t.text,t.table??null,t.docString??null])),qn=e=>e?xo(hc(e)):"none",yc=(e,t)=>xo({contract:hc(e),featureEdits:t??null});function wc(e,t,n,r){return{scenario:mc(e.steps),committed:qn(t),recording:yc(n,r)}}function Le(e,t,n){let r=t.meta.bound;if(!r)return;let s=[],{feature:o,scenario:i}=t.cache,a;if(n&&!(n instanceof Map))a=n;else try{a=Ce(xu.join(e,o),e,n).find(l=>l.name===i)}catch(l){s.push(`${o} no longer parses: ${l instanceof Error?l.message.split(`
|
|
30
|
+
`)[0]:String(l)}`)}s.length||(a?mc(a.steps)!==r.scenario&&s.push($u(a,t.cache)):s.push(`scenario "${i}" is no longer in ${o}`));let c;try{c=Re(re(e,o,i))}catch(l){if(!(l instanceof oe))throw l;return s.push(`the committed recording cannot be read (${l.problem})`),s.join("; ")}return qn(c)!==r.committed&&s.push(r.committed==="none"?"a recording was committed for this scenario after the proposal was filed, so the diff you would review is not the one that was made":c?"the committed recording changed after the proposal was filed (an accepted heal, a propagated locator fix or a pull), so the diff you would review is not the one that was made":"the committed recording the proposal was diffed against is gone"),yc(t.cache,t.meta.featureEdits)!==r.recording&&s.push("the proposal's recording or feature edits were edited after it was filed"),s.length>0?s.join("; "):void 0}function $u(e,t){let n=e.steps,r=t.steps;if(n.length!==r.length)return`the scenario has ${n.length} steps now and had ${r.length} when the proposal was filed`;let s=n.findIndex((o,i)=>o.text!==r[i].gherkin||o.kind!==r[i].kind);return s<0?"the scenario's steps changed since the proposal was filed":`step ${s+1} now reads "${n[s].text}" and was "${r[s].gherkin}" when the proposal was filed`}var qr="not bound: filed by a runner older than 0.8.5, so changes since cannot be detected";import Wt from"node:fs";import Sc from"node:path";function Jr(e){return`$${e.toFixed(e>=1?2:4)}`}function $o(e,t){let n=e===void 0?"?":`${Math.round(e)}%`,r=t===void 0?"?":`${Math.round(t)}%`;return`${n} \u2192 ${r}`}function De(e){return e.costUsd>0||e.aiCalls===0}function ko(e){return De(e)?e.plan?` \xB7 5-hour window ${$o(e.plan.fiveHourBefore,e.plan.fiveHourAfter)} (${e.plan.subscriptionType} plan) \xB7 \u2248 ${Jr(e.costUsd)} at API rates`:` \xB7 ${Jr(e.costUsd)}`:" \xB7 cost not reported by the provider"}function bc(e,t){return e?t?`\u2248 ${Jr(e)}`:Jr(e):""}function vc(e){if(!e)return"";let t=new Date(e);return Number.isNaN(t.getTime())?"":`resets ${t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`}function Ro(e){let t=e.costUsd===void 0?"":` \xB7 cost ${e.costUsd>=0?"+":"-"}$${Math.abs(e.costUsd).toFixed(4)}`;return`vs previous run: pass rate ${e.passRatePp>=0?"+":""}${e.passRatePp}pp${t} \xB7 AI calls ${e.aiCalls>=0?"+":""}${e.aiCalls}`}var Jn=e=>e.status==="yellow"&&e.verified===!1,To=(e,t)=>e.green+e.yellow-t.filter(Jn).length;function qt(e,t){let n=e.green+e.yellow+e.red;return n===0?0:Math.round(To(e,t)/n*100)}function Jt(e,t){if(e.name)return e.name;let n=e.scenario.replace(/ \(example \d+\)$/,"");return t&&(t(e.scenario)||!t(n))?e.scenario:n}function Ao(e){return Sc.join(e,".saffron","history.jsonl")}function _o(e,t,n,r){let s=e.map(o=>({feature:o.scenario.featurePath,scenario:o.scenario.displayName,name:o.scenario.name,tags:[...o.scenario.tags],status:o.status,source:o.source,durationMs:o.durationMs,verified:o.verified,seededSteps:o.seededSteps,adaptations:o.adaptations.length,driftSteps:o.stepResults.filter(i=>i.drift).length,aiCalls:o.usage.aiCalls,tokensInOut:o.usage.inputTokens+o.usage.outputTokens,cacheRead:o.usage.cacheReadTokens,cacheWrite:o.usage.cacheCreationTokens,costUsd:o.usage.costUsd??0,error:o.error?.split(`
|
|
31
|
+
`)[0]}));return{runId:t.toISOString(),startedAt:t.toISOString(),finishedAt:new Date().toISOString(),baseURL:r,green:s.filter(o=>o.status==="green").length,yellow:s.filter(o=>o.status==="yellow").length,red:s.filter(o=>o.status==="red").length,aiCalls:s.reduce((o,i)=>o+i.aiCalls,0),costUsd:s.reduce((o,i)=>o+i.costUsd,0),divergentSteps:n,scenarios:s}}function Io(e,t){let n=Ao(e);Wt.mkdirSync(Sc.dirname(n),{recursive:!0}),Wt.appendFileSync(n,`${JSON.stringify(t)}
|
|
32
|
+
`)}function xc(e,t){let n=Ao(e);if(!Wt.existsSync(n))return Io(e,t);let r=Wt.readFileSync(n,"utf8").split(`
|
|
33
|
+
`).filter(i=>i.trim()),s=!1,o=r.map(i=>{try{if(JSON.parse(i).runId===t.runId)return s=!0,JSON.stringify(t)}catch{}return i});s||o.push(JSON.stringify(t)),Wt.writeFileSync(n,`${o.join(`
|
|
32
34
|
`)}
|
|
33
|
-
`)}function
|
|
34
|
-
`).filter(Boolean),s=[];for(let
|
|
35
|
-
<path d="${
|
|
36
|
-
<path d="${
|
|
37
|
-
</svg>`}function
|
|
35
|
+
`)}function Wn(e,t=50){let n=Ao(e);if(!Wt.existsSync(n))return[];let r=Wt.readFileSync(n,"utf8").trim().split(`
|
|
36
|
+
`).filter(Boolean),s=[],o=0;for(let i=r.length-1;i>=0&&o<t;i--)try{let a=JSON.parse(r[i]);s.push(a),a.partial||o++}catch{}return s.reverse()}var Eo=e=>qt(e,e.scenarios);function Co(e,t){let n=e.filter(u=>!u.partial),r=[...n,t],s=r.slice(-20),o=r.slice(-10),i=n.at(-1),a=i?{passRatePp:Eo(t)-Eo(i),costUsd:De(t)&&De(i)?t.costUsd-i.costUsd:void 0,aiCalls:t.aiCalls-i.aiCalls,red:t.red-i.red}:void 0,c=new Map;for(let u of o)for(let f of u.scenarios){let h=`${f.feature}::${f.scenario}`,w=c.get(h)??{feature:f.feature,scenario:f.scenario,heals:0,reds:0,runs:0};w.runs++,f.source==="agent-heal"&&f.status==="yellow"&&w.heals++,f.status==="red"&&w.reds++,c.set(h,w)}let l=[...c.values()].filter(u=>u.heals>=2||u.reds>=3).sort((u,f)=>f.heals+f.reds-(u.heals+u.reds)),d=new Map;for(let u of s)for(let f of u.scenarios)f.status==="red"&&f.error&&d.set(f.error,(d.get(f.error)??0)+1);let p=[...d.entries()].sort((u,f)=>f[1]-u[1]).slice(0,3).map(([u,f])=>({message:u,count:f}));return{prev:a,series:{passRate:s.map(Eo),costUsd:s.map(u=>De(u)?Number(u.costUsd.toFixed(4)):null),aiCalls:s.map(u=>u.aiCalls)},chronic:l,divergentSteps:t.divergentSteps,topIssues:p}}var $c=20,ku=10,Ru=e=>e.scenarios.filter(Jn).length,Rc=e=>e.replace(/\\/g,"/"),Vt=(e,t)=>`${Rc(e)}\0${t}`,Tu=(e,t)=>t===0?0:Math.round(e/t*100),kc=e=>Math.max(0,Date.parse(e.finishedAt)-Date.parse(e.startedAt))||0;function Tc(e,t){let n=new Map;for(let E of e)for(let A of E.scenarios)n.set(Vt(E.path,A.name),{feature:E.path,scenario:A.name,tags:A.tags});let r=E=>Jt(E,A=>n.has(Vt(E.feature,A))),s=E=>n.has(Vt(E.feature,r(E))),o=e.flatMap(E=>E.scenarios),i=t.filter(E=>!E.partial),a=E=>i.at(-E)?.startedAt??"",c=i.slice(-$c),l=i.at(-1),d=new Map;for(let E of t.filter(A=>A.startedAt>=a($c)))for(let A of E.scenarios){if(!s(A))continue;let P=Vt(A.feature,A.scenario),O=r(A),I=d.get(P)??{ref:{feature:Rc(A.feature),scenario:A.scenario,...O!==A.scenario?{name:O}:{}},results:[]};I.results.push({at:E.startedAt,s:A,target:E.baseURL??""}),d.set(P,I)}let p=[],u=[],f=[];for(let{ref:E,results:A}of d.values()){let P=new Map,O=0,I=0,N=0;for(let B of A){if(B.s.source==="agent-record")continue;let _=B.s.status==="red";N++,_&&I++;let j=P.get(B.target);j!==void 0&&j!==_&&O++,P.set(B.target,_)}O>=2&&p.push({...E,runs:N,reds:I,flips:O,last:A.at(-1).s.status});let M=A.filter(B=>B.s.source==="agent-heal"&&B.s.status==="yellow");M.length>=2&&u.push({...E,runs:A.length,heals:M.length,unverified:M.filter(B=>Jn(B.s)).length}),f.push({...E,avgMs:Math.round(A.reduce((B,_)=>B+_.s.durationMs,0)/A.length),lastMs:A.at(-1).s.durationMs,runs:A.length})}p.sort((E,A)=>A.flips-E.flips||A.reds-E.reds),u.sort((E,A)=>A.heals-E.heals),f.sort((E,A)=>A.avgMs-E.avgMs);let h=[],w=new Set(t.filter(E=>E.startedAt>=a(ku)).map(E=>E.startedAt));for(let{ref:E,results:A}of d.values()){let P=A.findLast(N=>N.s.status==="red");if(!P||!w.has(P.at))continue;let O=A.at(-1).s.status==="red",I=0;for(let N=A.length-1;N>=0&&A[N].s.status==="red";N--)I++;h.push({...E,at:P.at,error:P.s.error,stillFailing:O,streak:I})}h.sort((E,A)=>Number(A.stillFailing)-Number(E.stillFailing)||A.at.localeCompare(E.at));let $={green:0,yellow:1,unverified:2,red:3},k=new Map;for(let E of t)for(let A of E.scenarios){let P=Vt(A.feature,r(A)),O=k.get(P)??new Map;O.set(A.scenario,Jn(A)?"unverified":A.status),k.set(P,O)}let y=new Map;for(let E of e)for(let A of E.scenarios){let P=Array.from({length:A.rows},(O,I)=>`${A.name} (example ${I+1})`);y.set(Vt(E.path,A.name),new Set(A.outline===!0?P:A.outline===!1?[A.name]:[A.name,...P]))}let v=new Map;for(let[E,A]of k){let P=y.get(E),O=[...A].filter(([I])=>!P||P.has(I)).map(([,I])=>I);O.length>0&&v.set(E,O.reduce((I,N)=>$[N]>$[I]?N:I))}let S=new Set(v.keys()),x=new Set((l?.scenarios??[]).map(E=>Vt(E.feature,r(E)))),b=[],R=[];for(let[E,A]of n){let P={feature:A.feature,scenario:A.scenario};S.has(E)?l&&!x.has(E)&&R.push(P):b.push(P)}let m=l?(()=>{let E=l.scenarios.length,A=Ru(l);return{startedAt:l.startedAt,durationMs:kc(l),ran:E,green:l.green,yellow:l.yellow,red:l.red,unverified:A,passRate:qt(l,l.scenarios),replayRate:Tu(l.scenarios.filter(P=>P.source==="cache"&&P.status==="green").length,E)}})():void 0,g={green:0,yellow:0,unverified:0,red:0,neverRun:0},T=new Map;for(let[E,A]of n){let P=v.get(E)??"neverRun";g[P]++;for(let O of A.tags){let I=T.get(O)??{tag:O,scenarios:0,green:0,yellow:0,unverified:0,red:0,neverRun:0};I.scenarios++,I[P]++,T.set(O,I)}}return{historyRuns:t.length,suite:{features:e.length,scenarios:o.length,tests:o.reduce((E,A)=>E+A.rows,0),recorded:o.filter(E=>E.cacheState===void 0?E.cached:E.cacheState==="valid").length,...g},lastRun:m,trend:c.map(E=>({startedAt:E.startedAt,passRate:qt(E,E.scenarios),durationMs:kc(E),red:E.red,tests:E.green+E.yellow+E.red})),flaky:p,healing:u,recentFailures:h,notInLastRun:R,neverRun:b,slowest:f.slice(0,10),tags:[...T.values()].sort((E,A)=>A.red-E.red||A.scenarios-E.scenarios||E.tag.localeCompare(A.tag))}}import{execFileSync as Ju}from"node:child_process";import{createHash as Wu,randomBytes as Wo}from"node:crypto";import Y from"node:fs";import X from"node:path";import Vu from"node:zlib";var F=e=>String(e).replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',"""),Ac="M11 14 L10 4.5 L17.5 9.5 L24 2.5 L30.5 9.5 L38 4.5 L37 14 Z",Eu="M24.085 45.646L24.085 45.646Q20.719 45.646 18.407 44.575Q16.095 43.504 14.905 41.651Q13.715 39.798 13.715 37.384L13.715 37.384L19.121 37.384Q19.121 38.336 19.648 39.152Q20.175 39.968 21.263 40.461Q22.351 40.954 24.085 40.954L24.085 40.954Q25.649 40.954 26.703 40.546Q27.757 40.138 28.301 39.407Q28.845 38.676 28.845 37.724L28.845 37.724Q28.845 36.534 27.825 35.837Q26.805 35.140 24.527 34.936L24.527 34.936L22.657 34.766Q18.951 34.460 16.741 32.454Q14.531 30.448 14.531 27.150L14.531 27.150Q14.531 24.770 15.670 23.036Q16.809 21.302 18.849 20.367Q20.889 19.432 23.677 19.432L23.677 19.432Q26.601 19.432 28.692 20.435Q30.783 21.438 31.905 23.257Q33.027 25.076 33.027 27.524L33.027 27.524L27.587 27.524Q27.587 26.606 27.145 25.841Q26.703 25.076 25.836 24.600Q24.969 24.124 23.677 24.124L23.677 24.124Q22.453 24.124 21.620 24.532Q20.787 24.940 20.379 25.637Q19.971 26.334 19.971 27.150L19.971 27.150Q19.971 28.204 20.719 28.986Q21.467 29.768 23.167 29.904L23.167 29.904L25.071 30.074Q27.791 30.312 29.865 31.247Q31.939 32.182 33.112 33.797Q34.285 35.412 34.285 37.724L34.285 37.724Q34.285 40.104 33.044 41.889Q31.803 43.674 29.525 44.660Q27.247 45.646 24.085 45.646Z";function Gn(e){return`<svg viewBox="0 0 48 48" width="${e}" height="${e}" aria-hidden="true">
|
|
37
|
+
<path d="${Ac}" fill="#F4A300"/>
|
|
38
|
+
<path d="${Eu}" fill="#E7E9EC"/>
|
|
39
|
+
</svg>`}function Po(e){return`<svg viewBox="8 1 32 15" height="${e}" aria-hidden="true"><path d="${Ac}" fill="#F4A300"/></svg>`}function Au(e){let t=e.imported;if(!t)return"";let n=t.shards?` \xB7 shard${t.shards.imported.length===1?"":"s"} ${t.shards.imported.join(", ")} of ${t.shards.total}`:"",r=t.headCommit??t.commit,s=`imported from ${t.run?`run ${t.run}`:"another machine"}${t.branch?` \xB7 ${t.branch}`:""}${r?` @ ${r.slice(0,7)}`:""}${n}`;return t.url&&/^https?:\/\//i.test(t.url)?`<a class="chip" href="${F(t.url)}" target="_blank" rel="noopener noreferrer">${F(s)}</a>`:`<span class="chip">${F(s)}</span>`}var Oo=`<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
38
40
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
39
|
-
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,500;12..96,600;12..96,700&family=Geist:wght@400;500;600&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">`,
|
|
41
|
+
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,500;12..96,600;12..96,700&family=Geist:wght@400;500;600&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">`,jo=` :root {
|
|
40
42
|
--bg: #131416;
|
|
41
43
|
--card: #1A1B1E;
|
|
42
44
|
--card-2: #16171A;
|
|
@@ -146,20 +148,20 @@ import ce from"node:fs";import L from"node:path";import Pm from"node:readline";i
|
|
|
146
148
|
code { font-family: var(--mono); font-size: 11px; background: var(--bg); border: 1px solid var(--border-2); padding: 1px 6px; border-radius: 4px; color: var(--text-dim); }
|
|
147
149
|
|
|
148
150
|
footer { margin-top: 42px; display: flex; align-items: center; justify-content: center; gap: 8px; color: var(--faint); font-family: var(--mono); font-size: 10.5px; letter-spacing: .08em; }
|
|
149
|
-
`,
|
|
151
|
+
`,_u={green:"passed",yellow:"pending review",red:"failed"};function Iu(e){return e.hooks?.length?`<div class="panel"><div class="panel-title">setup and teardown</div>${e.hooks.map(n=>{let r=n.exitCode===0,s=r?"ok":n.timedOut?"timed out":n.exitCode===null?"could not start":`exit ${n.exitCode}`;return`<div class="mono">${r?"\u2713":"\u2717"} ${F(String(n.phase))} \xB7 ${F(n.command)} \xB7 ${F(s)} \xB7 ${F(rt(n.durationMs))}</div>`}).join("")}</div>`:""}function rt(e){return e>=1e3?`${(e/1e3).toFixed(1)}s`:`${e}ms`}function Vn(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e4?`${(e/1e3).toFixed(1)}k`:Number(e).toLocaleString()}function he(e,t,n,r="",s="",o=""){return`<div class="kpi">
|
|
150
152
|
<div class="kpi-label">${e}</div>
|
|
151
153
|
<div class="kpi-value ${r}">${t}</div>
|
|
152
154
|
<div class="kpi-sub ${s}">${n}</div>${o}
|
|
153
|
-
</div>`}function
|
|
154
|
-
${
|
|
155
|
-
${
|
|
156
|
-
${
|
|
157
|
-
${
|
|
158
|
-
${
|
|
159
|
-
${
|
|
160
|
-
${n.plan?
|
|
161
|
-
</section>`}function
|
|
162
|
-
`)}</section>`:""}function
|
|
155
|
+
</div>`}function Sn(e,t){let n=e.filter(l=>l!==null);if(n.length<2)return"";let r=108,s=22,o=Math.min(...n),a=Math.max(...n)-o||1,c=e.map((l,d)=>{if(l===null)return"";let p=`${(d/(e.length-1)*r).toFixed(1)},${(s-2-(l-o)/a*(s-4)).toFixed(1)}`;return d===0||e[d-1]===null?`M${p}h0`:`L${p}`}).join("");return`<svg class="spark" viewBox="0 0 ${r} ${s}" width="${r}" height="${s}" aria-hidden="true"><path d="${c}" fill="none" stroke="${t}" stroke-width="1.8" stroke-linejoin="round" stroke-linecap="round"/></svg>`}var Ec=(e,t="",n=0)=>`${e>=0?"+":"\u2212"}${Math.abs(e).toFixed(n)}${t} vs prev`;function Cu(e,t){let n=e.totals,r=e.trends,[s,o,i,a]=[n.scenarios,n.green,n.yellow,n.red].map(Number),c=To({green:o,yellow:i},e.scenarios),l=s===0?0:Math.round(c/s*100),d=n.red>0?"red":n.yellow>0?"gold":"green",p=n.inputTokens+n.outputTokens,u=r?.prev?`${Ec(r.prev.passRatePp,"pp")} \xB7 ${c} of ${s}`:`${c} of ${s} scenarios`,f=r?.prev?.costUsd!==void 0?`${Ec(r.prev.costUsd,"",4).replace("+","+$").replace("\u2212","\u2212$")} \xB7 ${rt(t)}`:`${rt(t)} total runtime`;return`<section class="kpis">
|
|
156
|
+
${he("pass rate",`${l}<span class="unit">%</span>`,u,d,r?.prev?r.prev.passRatePp>=0?"green":"red":"",Sn(r?.series.passRate??[],"var(--green)"))}
|
|
157
|
+
${he("passed",String(o),"deterministic replay","green",o>0?"green":"")}
|
|
158
|
+
${he("pending",String(i),i>0?"\u25B2 proposals to review":"nothing to review",i>0?"gold":"",i>0?"gold":"")}
|
|
159
|
+
${he("failed",String(a),a>0?"\u25BC needs attention":"all clear",a>0?"red":"",a>0?"red":"green")}
|
|
160
|
+
${he("ai calls",String(Number(n.aiCalls)),`${Vn(p)} in+out tokens`,n.aiCalls>0?"":"green")}
|
|
161
|
+
${he("cache traffic",Vn(n.cacheReadTokens+n.cacheCreationTokens),n.cacheReadTokens+n.cacheCreationTokens>0?`${Vn(n.cacheReadTokens)} read \xB7 ${Vn(n.cacheCreationTokens)} written`:"zero (fully cached run)","",n.cacheReadTokens+n.cacheCreationTokens>0?"":"green")}
|
|
162
|
+
${n.plan?he("plan usage",`${$o(n.plan.fiveHourBefore,n.plan.fiveHourAfter)}`,[`5-hour window \xB7 ${F(n.plan.subscriptionType)} plan`,vc(n.plan.resetsAt)].filter(Boolean).join(" \xB7 "),"gold","")+he("api-equivalent",`<span class="unit">\u2248 $</span>${n.costUsd.toFixed(n.costUsd>=1?2:4)}`,`what this run costs on an API key \xB7 ${f}`,"","",Sn(r?.series.costUsd??[],"var(--gold)")):he("ai cost",De(n)?`<span class="unit">$</span>${n.costUsd.toFixed(n.costUsd>=1?2:4)}`:"n/a",De(n)?f:"not reported by the provider","","",De(n)?Sn(r?.series.costUsd??[],"var(--gold)"):"")}
|
|
163
|
+
</section>`}function Pu(e){let t=e.trends;if(!t)return"";let n=[];return t.chronic.length>0&&n.push(`<div class="panel accent-gold"><div class="panel-title gold">chronic scenarios: stop paying for heals</div><ul>${t.chronic.map(r=>`<li>${F(r.feature)} \u203A ${F(r.scenario)}: ${Number(r.heals)} heal(s), ${Number(r.reds)} red(s) in the last ${Number(r.runs)} run(s). Re-record it or fix the feature text.</li>`).join("")}</ul></div>`),t.divergentSteps>0&&n.push(`<div class="panel"><div class="panel-title">step divergence (level-2 signal)</div><p>${Number(t.divergentSteps)} step text(s) currently have divergent recordings across caches.</p></div>`),t.topIssues.length>0&&n.push(`<div class="panel accent-red"><div class="panel-title red">recurring failure themes (last 20 runs)</div><ul>${t.topIssues.map(r=>`<li>${Number(r.count)}\xD7: ${F(r.message)}</li>`).join("")}</ul></div>`),n.length>0?`<section class="trends">${n.join(`
|
|
164
|
+
`)}</section>`:""}function Ou(e){return`<ol class="steps">${e.steps.map(n=>{let r=n.status==="passed"?'<span class="dot green"></span>':n.status==="failed"?'<span class="dot red"></span>':'<span class="dot idle"></span>';return`<li class="step ${F(n.status)}">
|
|
163
165
|
${r}
|
|
164
166
|
<div class="step-body">
|
|
165
167
|
<span class="step-text">${F(n.gherkin)}</span>
|
|
@@ -170,52 +172,52 @@ import ce from"node:fs";import L from"node:path";import Pm from"node:readline";i
|
|
|
170
172
|
${n.error?`<div class="step-error">${F(n.error)}</div>`:""}
|
|
171
173
|
</div>
|
|
172
174
|
</li>`}).join(`
|
|
173
|
-
`)}</ol>`}function
|
|
175
|
+
`)}</ol>`}function ju(e){return e.featureEdits&&e.featureEdits.length>0?`<div class="panel">
|
|
174
176
|
<div class="panel-title gold">suggested .feature edit</div>
|
|
175
177
|
<div class="diff">${e.featureEdits.map(n=>{let r=e.steps[n.index]?.gherkin??`step ${n.index}`;return`<div class="diff-line del">\u2212 ${F(r)}</div><div class="diff-line add">+ ${F(n.text)}</div>`}).join("")}</div>
|
|
176
178
|
<div class="panel-hint">apply with <code>saffron accept --with-feature-edit</code></div>
|
|
177
|
-
</div>`:e.suggestedFeatureEdit?`<div class="panel"><div class="panel-title gold">suggested .feature edit</div><pre>${F(e.suggestedFeatureEdit)}</pre></div>`:""}function
|
|
179
|
+
</div>`:e.suggestedFeatureEdit?`<div class="panel"><div class="panel-title gold">suggested .feature edit</div><pre>${F(e.suggestedFeatureEdit)}</pre></div>`:""}function Nu(e){let t=e.proposalDiff;if(!t)return"";let n=t.steps.filter(c=>c.change!=="same"||!t.hasCommitted).map(c=>{let l=`<div class="diff-step">${c.kind==="assertion"?'<span class="pill gold">assertion</span> ':""}${F(c.gherkin)}${c.fromStepSet?` <span class="mono">(step set "${F(c.fromStepSet)}")</span>`:""}</div>`,d=c.actions.flatMap(p=>p.change==="same"?[`<div class="diff-line"> ${F(p.before??"")}</div>`]:p.change==="added"?[`<div class="diff-line add">+ ${F(p.after??"")}</div>`]:p.change==="removed"?[`<div class="diff-line del">\u2212 ${F(p.before??"")}</div>`]:[`<div class="diff-line del">\u2212 ${F(p.before??"")}</div>`,`<div class="diff-line add">+ ${F(p.after??"")}</div>`,...(p.details??[]).map(u=>`<div class="diff-line detail">${F(u)}</div>`)]).join("");return`${l}<div class="diff">${d}</div>`}).join(""),{added:r,removed:s,changed:o,assertions:i}=t.summary,a=r+s+o===0?"No action changed.":`${o} changed, ${r} added, ${s} removed.${i>0?` ${i} touch the scenario's verdict.`:""}`;return`<div class="panel accent-gold"><div class="panel-title gold">what this proposal changes</div>${t.hasCommitted?"":'<p class="panel-hint">First recording: there is nothing to compare against.</p>'}${n}<div class="panel-hint">${F(a)}</div></div>`}function Fu(e,t){let n=e.usage.inputTokens+e.usage.outputTokens;if(e.usage.aiCalls===0)return'<span class="pill green">0 tokens</span>';let r=bc(e.usage.costUsd,t),s=r?` \xB7 ${r}`:"";return`<span class="pill gold">${Number(e.usage.aiCalls)} ai \xB7 ${Vn(n)} tok${s}</span>`}function Mu(e,t,n){return`<details class="card" ${e.status!=="green"?"open":""}>
|
|
178
180
|
<summary>
|
|
179
|
-
<span class="pill ${e.status==="green"?"green":e.status==="yellow"?"gold":"red"}">${
|
|
181
|
+
<span class="pill ${e.status==="green"?"green":e.status==="yellow"?"gold":"red"}">${_u[e.status]}</span>
|
|
180
182
|
<span class="card-title">${F(e.scenario)}</span>
|
|
181
183
|
<span class="card-meta">
|
|
182
184
|
<span class="m">${F(e.feature)}</span>
|
|
183
185
|
<span class="m-sep">\xB7</span>
|
|
184
186
|
<span class="m">${F(e.source)}</span>
|
|
185
187
|
<span class="m-sep">\xB7</span>
|
|
186
|
-
<span class="m">${
|
|
187
|
-
${
|
|
188
|
+
<span class="m">${rt(Number(e.durationMs))}</span>
|
|
189
|
+
${Fu(e,t)}
|
|
188
190
|
</span>
|
|
189
191
|
</summary>
|
|
190
192
|
<div class="card-body">
|
|
191
|
-
${
|
|
193
|
+
${Ou(e)}
|
|
192
194
|
${e.narrative?`<div class="panel"><div class="panel-title">agent narrative</div><p>${F(e.narrative)}</p></div>`:""}
|
|
193
195
|
${e.adaptations.length>0?`<div class="panel accent-gold"><div class="panel-title gold">adaptations</div><ul>${e.adaptations.map(r=>`<li>${F(r)}</li>`).join("")}</ul></div>`:""}
|
|
194
|
-
${
|
|
195
|
-
${
|
|
196
|
+
${ju(e)}
|
|
197
|
+
${Nu(e)}
|
|
196
198
|
${e.proposalFile?`<div class="panel"><div class="panel-title">cache proposal pending${e.verified===!0?' <span class="pill green">verified</span>':e.verified===!1?' <span class="pill red">unverified</span>':""}</div><p class="mono">${F(e.proposalFile)}</p>${e.verified===!1&&e.proofError?`<p class="mono" style="color:var(--red)">proof replay failed: ${F(e.proofError.split(`
|
|
197
199
|
`)[0])}</p>`:""}<div class="panel-hint">review with <code>saffron accept</code> / <code>saffron reject</code></div></div>`:""}
|
|
198
200
|
${e.error&&e.status==="red"?`<div class="panel accent-red"><div class="panel-title red">failure</div><p>${F(e.error)}</p></div>`:""}
|
|
199
201
|
${e.uniques&&e.status!=="green"?`<div class="panel"><div class="panel-title">unique values in this run</div>${Object.entries(e.uniques).map(([r,s])=>`<div class="mono">${F(r)} = ${F(s)}</div>`).join("")}</div>`:""}
|
|
200
202
|
${e.proofUniques&&e.status!=="green"?`<div class="panel"><div class="panel-title">unique values in the proof replay</div>${Object.entries(e.proofUniques).map(([r,s])=>`<div class="mono">${F(r)} = ${F(s)}</div>`).join("")}</div>`:""}
|
|
201
|
-
${
|
|
203
|
+
${Lu(e,n)}
|
|
202
204
|
</div>
|
|
203
|
-
</details>`}function
|
|
205
|
+
</details>`}function Lu(e,t){let n=(e.evidence??[]).find(o=>o.kind==="trace"),r=n?`<div class="panel accent-gold"><div class="panel-title gold">execution replay</div><div>Step through this run with the page inspectable at every action:</div><div class="mono" style="margin-top:6px">npx saffron trace ${F(Du(`${e.feature}:${e.scenario}`))}</div><div class="panel-hint">${F(n.file)}</div></div>`:"",s=(e.evidence??[]).flatMap(o=>{if(!t||o.kind!=="failure"&&o.kind!=="before-heal")return[];let i=gn(t,o);if(!i)return[];try{let a=i.toString("base64"),c=o.kind==="failure"?"the page when it failed":"the page when the cached step stopped working, before the agent took over";return[`<figure class="shot"><figcaption>${F(c)}${o.step?`: <span class="mono">${F(o.step)}</span>`:""}</figcaption><a href="data:image/jpeg;base64,${a}" target="_blank" rel="noopener"><img alt="${F(c)}" src="data:image/jpeg;base64,${a}"/></a><div class="panel-hint">${F(o.file)}</div></figure>`]}catch{return[]}});return s.length===0?r:`<div class="panel ${e.status==="red"?"accent-red":"accent-gold"}"><div class="panel-title ${e.status==="red"?"red":"gold"}">screenshot</div>${s.join("")}</div>${r}`}var Du=e=>/[^A-Za-z0-9_./:-]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e;function At(e,t){let n=e.totals,r=new Date(e.startedAt),s=new Date(e.finishedAt).getTime()-r.getTime(),o=r.toLocaleString("en-GB",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"});return`<!doctype html>
|
|
204
206
|
<html lang="en">
|
|
205
207
|
<head>
|
|
206
208
|
<meta charset="utf-8"/>
|
|
207
209
|
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
|
208
210
|
<title>Saffron run report</title>
|
|
209
|
-
${
|
|
211
|
+
${Oo}
|
|
210
212
|
<style>
|
|
211
|
-
${
|
|
213
|
+
${jo}</style>
|
|
212
214
|
</head>
|
|
213
215
|
<body>
|
|
214
216
|
<div class="topline"></div>
|
|
215
217
|
<div class="wrap">
|
|
216
218
|
<header class="top">
|
|
217
219
|
<div class="brand">
|
|
218
|
-
${
|
|
220
|
+
${Gn(38)}
|
|
219
221
|
<div>
|
|
220
222
|
<div class="brand-name">saffron</div>
|
|
221
223
|
<div class="brand-sub">test run report</div>
|
|
@@ -224,77 +226,79 @@ ${Ro}</style>
|
|
|
224
226
|
<div class="run-meta">
|
|
225
227
|
<span>${F(o)}</span>
|
|
226
228
|
<span>\xB7</span>
|
|
227
|
-
<span>${
|
|
229
|
+
<span>${rt(s)}</span>
|
|
228
230
|
${e.baseURL?`<span class="chip base">${F(e.baseURL)}</span>`:""}
|
|
229
231
|
${e.shards?`<span class="chip">merged from ${Number(e.shards)} shards</span>`:""}
|
|
230
|
-
${
|
|
232
|
+
${Au(e)}
|
|
231
233
|
</div>
|
|
232
234
|
</header>
|
|
233
235
|
|
|
234
|
-
${
|
|
235
|
-
${
|
|
236
|
-
${
|
|
236
|
+
${Cu(e,s)}
|
|
237
|
+
${Pu(e)}
|
|
238
|
+
${Iu(e)}
|
|
237
239
|
|
|
238
240
|
<div class="section-head">
|
|
239
241
|
<span class="section-title">scenarios \xB7 ${Number(n.scenarios)}</span>
|
|
240
242
|
<span class="section-title">saffron v${F(e.version)}</span>
|
|
241
243
|
</div>
|
|
242
|
-
${e.scenarios.map(i=>
|
|
244
|
+
${e.scenarios.map(i=>Mu(i,!!e.totals.plan,t)).join(`
|
|
243
245
|
`)}
|
|
244
246
|
|
|
245
|
-
<footer>${
|
|
247
|
+
<footer>${Po(11)} generated by saffron v${F(e.version)} \xB7 ${F(new Date(e.finishedAt).toLocaleString("en-GB",{dateStyle:"medium",timeStyle:"medium"}))}</footer>
|
|
246
248
|
</div>
|
|
247
249
|
</body>
|
|
248
250
|
</html>
|
|
249
|
-
`}import
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
`)
|
|
254
|
-
`)
|
|
255
|
-
`)
|
|
251
|
+
`}import Wr from"node:fs";import Vr from"node:path";function Gr(e){let t={scenarios:e.length,green:0,yellow:0,red:0,aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0},n=new Set;for(let r of e){for(let s of r.usage.models??[])n.add(s);t[r.status]+=1,t.aiCalls+=r.usage.aiCalls,t.inputTokens+=r.usage.inputTokens,t.outputTokens+=r.usage.outputTokens,t.cacheReadTokens+=r.usage.cacheReadTokens,t.cacheCreationTokens+=r.usage.cacheCreationTokens??0,t.costUsd+=r.usage.costUsd??0}return n.size>0&&(t.models=[...n].sort()),t}function Mo(e,t,n){return{tool:"saffron",version:We(),startedAt:t.toISOString(),finishedAt:new Date().toISOString(),baseURL:n,totals:Gr(e),scenarios:e.map(r=>({feature:r.scenario.featurePath,scenario:r.scenario.displayName,name:r.scenario.name,tags:[...r.scenario.tags],status:r.status,source:r.source,proposalReplay:r.proposalReplay,durationMs:r.durationMs,usage:r.usage,steps:r.stepResults,narrative:r.narrative,adaptations:r.adaptations,suggestedFeatureEdit:r.suggestedFeatureEdit,featureEdits:r.featureEdits,verified:r.verified,proofError:r.proofError,proposalFile:r.proposalFile,proposalRevision:r.proposalRevision,proposalDiff:r.proposalDiff,error:r.error,evidence:r.evidence,uniques:r.uniques,proofUniques:r.proofUniques}))}}var _t=e=>!!e&&typeof e=="object"&&!Array.isArray(e),No=(e,t)=>t.find(n=>typeof e[n]!="number"),Fo=e=>e===void 0||typeof e=="number",Bu=["scenarios","green","yellow","red","aiCalls","inputTokens","outputTokens","cacheReadTokens","costUsd"],Uu=["aiCalls","inputTokens","outputTokens","cacheReadTokens"],_c=e=>typeof e=="string"&&/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(Z|[+-]\d\d:\d\d)$/.test(e)&&!Number.isNaN(Date.parse(e));function Lo(e){if(!_t(e)||e.tool!=="saffron")return"is not a Saffron run report";if(!_c(e.startedAt)||!_c(e.finishedAt))return"has no start or finish time";if(!_t(e.totals))return"has no totals";let t=No(e.totals,Bu);if(t)return`has totals.${t} that is not a number`;if(!Array.isArray(e.scenarios))return"has no list of scenarios";for(let[s,o]of e.scenarios.entries()){let i=`scenarios[${s}]`;if(!_t(o)||typeof o.feature!="string"||typeof o.scenario!="string")return`has ${i} without a feature and scenario name`;if(!["green","yellow","red"].includes(o.status))return`has ${i}.status ${JSON.stringify(o.status)}, which this saffron-ai does not know`;if(!_t(o.usage)||No(o.usage,Uu))return`has ${i}.usage without its token counts`;if(!Array.isArray(o.steps))return`has ${i}.steps that is not a list`;let a=o.steps.findIndex(c=>!_t(c)||typeof c.gherkin!="string"||typeof c.kind!="string"||typeof c.status!="string");if(a>=0)return`has ${i}.steps[${a}] without its gherkin, kind and status`;for(let[c,l]of o.steps.entries()){if(!["passed","failed","skipped"].includes(l.status))return`has ${i}.steps[${c}].status ${JSON.stringify(l.status)}, which this saffron-ai does not know`;let d=["retries","failedActionIndex"].find(p=>!Fo(l[p]));if(d)return`has ${i}.steps[${c}].${d} that is not a number`}if(o.evidence!==void 0&&!(Array.isArray(o.evidence)&&o.evidence.every(c=>_t(c)&&typeof c.file=="string"&&typeof c.kind=="string")))return`has ${i}.evidence that is not a list of files`}let n=e.trends,r=(s,o)=>Array.isArray(s)&&s.every(i=>_t(i)&&!No(i,o));if(n!==void 0&&!(_t(n)&&Fo(n.divergentSteps)&&r(n.chronic,["heals","reds","runs"])&&r(n.topIssues,["count"])&&(n.prev===void 0||r([n.prev],["passRatePp","aiCalls","red"])&&Fo(n.prev.costUsd))))return"has trends whose counts are not numbers"}var Do=e=>Lo(e)===void 0;function Bo(e){try{let t=JSON.parse(Wr.readFileSync(Vr.join(e,".saffron","reports","latest.json"),"utf8"));return Do(t)?t:void 0}catch{return}}function Uo(e,t){if(!e||e.imported||e.baseURL!==t.baseURL)return t;let n=f=>`${f.feature}
|
|
252
|
+
${f.scenario}`,r=new Map(t.scenarios.map(f=>[n(f),f])),s=e.scenarios.filter(f=>!r.has(n(f))),o=t.totals.aiCalls>0;if(o&&s.some(f=>f.usage.aiCalls>0)&&!t.totals.plan!=!e.totals.plan)return t;let i=new Set(e.scenarios.map(n)),a=[...e.scenarios.map(f=>r.get(n(f))??f),...t.scenarios.filter(f=>!i.has(n(f)))],{trends:c,shards:l,hooks:d,...p}=e,u=o?t.totals.plan:e.totals.plan;return{...p,version:t.version,startedAt:t.startedAt,finishedAt:t.finishedAt,totals:{...Gr(a),...u?{plan:u}:{}},scenarios:a,...t.shards?{shards:t.shards}:{},...t.hooks?{hooks:t.hooks}:{}}}function Kn(e,t){let n=Vr.join(e,".saffron","reports");Wr.mkdirSync(n,{recursive:!0});let r=Vr.join(n,"latest.json"),s=Vr.join(n,"latest.html");return Wr.writeFileSync(r,`${JSON.stringify(t,null,2)}
|
|
253
|
+
`),Wr.writeFileSync(s,At(t,e)),{json:r,html:s}}import zu from"node:crypto";import Yn from"node:fs";import Kr from"node:path";var Ic=["scenario","file"];function Cc(e){let t=/^\s*(\d+)\s*\/\s*(\d+)\s*$/.exec(e),n=t?Number(t[1]):NaN,r=t?Number(t[2]):NaN;if(!t||r<1||n<1||n>r)throw new Error(`invalid --shard "${e}": use <index>/<total>, e.g. --shard 2/4 (index from 1 to total)`);return{index:n,total:r}}function Pc(e){if(!Ic.includes(e))throw new Error(`invalid --shard-by "${e}": use ${Ic.map(t=>`"${t}"`).join(" or ")}`);return e}function zo(e){return`shard-${e.index}-of-${e.total}`}var Hu=e=>`${e.featurePath}${e.displayName}`;function Oc(e,t){let n=t.by??"scenario",r=e.map(Hu),s=new Set,o=new Map;e.forEach((d,p)=>{let u=n==="file"?d.featurePath:`${d.featurePath}
|
|
254
|
+
${d.name}`;o.set(u,[...o.get(u)??[],p])});let i=new Array(t.total).fill(0),a=[...o].sort((d,p)=>p[1].length-d[1].length||(d[0]<p[0]?-1:d[0]>p[0]?1:0));for(let[,d]of a){let p=i.indexOf(Math.min(...i));if(i[p]+=d.length,p===t.index-1)for(let u of d)s.add(u)}let c=e.map((d,p)=>p).filter(d=>s.has(d)),l=zu.createHash("sha256").update([...r].sort().join(`
|
|
255
|
+
`)).digest("hex").slice(0,12);return{scenarios:c.map(d=>e[d]),info:{index:t.index,total:t.total,by:n,suite:l,suiteSize:e.length,positions:c}}}function Yr(e=process.env){return e.SAFFRON_RUN_ID||e.GITHUB_RUN_ID&&`github:${e.GITHUB_RUN_ID}`||e.CI_PIPELINE_ID&&`gitlab:${e.CI_PIPELINE_ID}`||e.BUILD_BUILDID&&`azure:${e.BUILD_BUILDID}`||e.CIRCLE_WORKFLOW_ID&&`circleci:${e.CIRCLE_WORKFLOW_ID}`||void 0}var Zr=(e=process.env)=>e.GITHUB_RUN_ATTEMPT||e.SYSTEM_JOBATTEMPT||void 0;function Ho(e,t){let n=Kr.join(e,".saffron","reports");Yn.mkdirSync(n,{recursive:!0});let r=Kr.join(n,`${zo(t.shard)}.json`);return Yn.writeFileSync(r,`${JSON.stringify(t,null,2)}
|
|
256
|
+
`),r}var Qr=e=>{let t=e;return!!t&&t.tool==="saffron"&&!!t.shard&&typeof t.shard.index=="number"&&typeof t.shard.total=="number"&&Array.isArray(t.shard.positions)&&Array.isArray(t.scenarios)&&!!t.history&&Array.isArray(t.history.scenarios)},qu=/^shard-\d+-of-\d+\.json$/;function jc(e){let t=[],n=(r,s)=>{let o=Yn.statSync(r,{throwIfNoEntry:!1});if(!o)throw new Error(`not found: ${r}`);if(o.isDirectory())for(let i of Yn.readdirSync(r).sort())n(Kr.join(r,i),!1);else(s||qu.test(Kr.basename(r)))&&t.push(r)};for(let r of e)n(r,!0);return t.map(r=>{let s;try{s=JSON.parse(Yn.readFileSync(r,"utf8"))}catch(o){throw new Error(`cannot read shard report ${r}: ${o instanceof Error?o.message:String(o)}`)}if(!Qr(s))throw new Error(`${r} is not a shard report (written by saffron run --shard)`);return{file:r,report:s}})}var Gt=class extends Error{};function Xr(e,t={}){if(e.length===0)throw new Gt("no shard reports found. Shards write .saffron/reports/shard-<i>-of-<n>.json");let n=g=>Number(g.report.shard.attempt)||0,r=g=>{let{ciRun:T,index:E,total:A,suite:P,suiteSize:O,by:I}=g.report.shard;return JSON.stringify([T??"",E,A,P,O,I??"scenario",g.report.baseURL??""])},s=new Map;for(let g of e)s.set(r(g),Math.max(s.get(r(g))??0,n(g)));let o=e.filter(g=>n(g)<s.get(r(g)));e=e.filter(g=>!o.includes(g));let i=e[0].report.shard,a=[],c=g=>g.map(T=>T.file).join(", "),l=new Set(e.map(g=>g.report.shard.total));l.size>1&&a.push(`shards disagree on the shard count (${[...l].sort().join(", ")}): ${c(e)}`),new Set(e.map(g=>`${g.report.shard.suite}/${g.report.shard.suiteSize}`)).size>1&&a.push("shards ran different suites (different scenarios or filters). Every shard must run the same paths and --filter");let p=new Set(e.map(g=>g.report.shard.by??"scenario"));p.size>1&&a.push(`shards split the suite in different ways (--shard-by ${[...p].sort().join(" and ")}): every shard must use the same`);let u=new Set(e.map(g=>g.report.shard.ciRun??""));u.size>1&&a.push(`shards come from different CI runs (${[...u].map(g=>g||"none recorded").join(", ")})`);let f=[...new Set(e.map(g=>g.report.baseURL??"(no base URL)"))];f.length>1&&a.push(`the shards ran against different base URLs: ${f.join(", ")}. Merge the shards of one environment at a time`);let h=new Map;for(let g of e)h.set(g.report.shard.index,[...h.get(g.report.shard.index)??[],g]);for(let[g,T]of[...h].sort((E,A)=>E[0]-A[0]))T.length>1&&a.push(`shard ${g}/${i.total} appears ${T.length} times: ${c(T)}`);if(l.size===1&&!t.partial){let g=Array.from({length:i.total},(T,E)=>E+1).filter(T=>!h.has(T));g.length>0&&a.push(`missing ${g.length===1?"shard":"shards"} ${g.map(T=>`${T}/${i.total}`).join(", ")}. A merge without ${g.length===1?"it":"them"} would under-count the run`)}if(a.length===0){let g=new Set,T=0;for(let E of e){let{positions:A}=E.report.shard;(A.length!==E.report.scenarios.length||A.length!==E.report.history.scenarios.length)&&a.push(`${E.file} is inconsistent: ${A.length} positions for ${E.report.scenarios.length} scenarios`);for(let P of A)g.has(P)&&a.push(`two shards both ran scenario ${P+1} of the suite`),g.add(P);T+=A.length}a.length===0&&!t.partial&&T!==i.suiteSize&&a.push(`the shards hold ${T} scenarios but the suite has ${i.suiteSize}`)}if(a.length>0)throw new Gt(a.join(`
|
|
257
|
+
`));let w=e.sort((g,T)=>g.report.shard.index-T.report.shard.index).flatMap(({report:g})=>g.shard.positions.map((T,E)=>({position:T,scenario:g.scenarios[E],history:g.history.scenarios[E]}))).sort((g,T)=>g.position-T.position),$=e.map(g=>g.report),k=$.map(g=>g.startedAt).sort()[0],y=$.map(g=>g.finishedAt).sort().at(-1),v=w.map(g=>g.scenario),S=$.flatMap(g=>g.hooks??[]),x={tool:"saffron",version:$[0].version,startedAt:k,finishedAt:y,baseURL:$.find(g=>g.baseURL)?.baseURL,totals:Gr(v),scenarios:v,shards:e.length};S.length>0&&(x.hooks=S);let b=w.map(g=>g.history),m={runId:i.ciRun?`${i.ciRun}:${i.suite}:${x.baseURL??""}`:k,startedAt:k,finishedAt:y,baseURL:x.baseURL,green:b.filter(g=>g.status==="green").length,yellow:b.filter(g=>g.status==="yellow").length,red:b.filter(g=>g.status==="red").length,aiCalls:b.reduce((g,T)=>g+T.aiCalls,0),costUsd:b.reduce((g,T)=>g+T.costUsd,0),divergentSteps:Math.max(...$.map(g=>g.history.divergentSteps)),...$.some(g=>g.history.partial)?{partial:!0}:{},scenarios:b};return{report:x,history:m,replaced:o.map(g=>g.file)}}var es=1,D=class extends Error{constructor(n,r){super(ie(n,1/0));this.kind=r}kind},Kt=e=>e instanceof Error?e.message:String(e);function gt(e,t){try{return Ju("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim()||void 0}catch{return}}function Uc(e){let t=e.trim();if(/^[a-z]:[\\/]/i.test(t))return;let n,r;if(/^[a-z][a-z0-9+.-]*:\/\//i.test(t)){let o;try{o=new URL(t)}catch{return}if(o.protocol==="file:")return;n=o.hostname,r=o.pathname}else{let o=/^(?:[^@/\s]+@)?([^:/\s]+):(.+)$/.exec(t);if(!o)return;n=o[1],r=o[2]}try{r=decodeURIComponent(r)}catch{}r=r.replace(/^\/+|\/+$/g,"").replace(/\.git$/i,""),n=n.toLowerCase();let s=/^v3\/([^/]+)\/([^/]+)\/([^/]+)$/.exec(r);return s?(n="dev.azure.com",r=`${s[1]}/${s[2]}/_git/${s[3]}`):n.endsWith(".visualstudio.com")&&(r=`${n.slice(0,-17)}/${r.replace(/^DefaultCollection\//i,"")}`,n="dev.azure.com"),r?`${n}/${r}`.toLowerCase():void 0}function ns(e){let n=(gt(e,["remote","-v"])?.split(`
|
|
258
|
+
`)??[]).map(r=>r.split(/\s+/)[1]).filter(Boolean);return[...new Set(n.map(Uc).filter(r=>r!==void 0))]}var Nc=e=>e?.replace(/^refs\/heads\//,"")||void 0,zc=e=>e.GITHUB_EVENT_NAME==="pull_request"||!!e.GITHUB_EVENT_NAME?.startsWith("pull_request_review");function Gu(e){if(!e.GITHUB_EVENT_PATH||!zc(e))return{};let t=n=>typeof n=="string"&&n?n:void 0;try{let n=JSON.parse(Y.readFileSync(e.GITHUB_EVENT_PATH,"utf8"))?.pull_request?.head;return{sha:t(n?.sha),ref:t(n?.ref)}}catch{return{}}}function Vo(e,t){return[...(gt(e,["cat-file","-p",t])??"").split(`
|
|
256
259
|
|
|
257
|
-
`)[0].matchAll(/^parent ([0-9a-f]+)$/gm)].map(r=>r[1])}function
|
|
258
|
-
`)??[],r=n.includes("origin")?"origin":n[0],s=t.GITHUB_SERVER_URL&&t.GITHUB_REPOSITORY?`${t.GITHUB_SERVER_URL}/${t.GITHUB_REPOSITORY}`:void 0,o=[r&&
|
|
259
|
-
`)},...r]),{file:f,manifest:u,proposals:o,missing:l,dropped:d,unreadable:n}}var Jr="[a-z0-9-]+",Ac=new RegExp(`^proposals/${Jr}/${Jr}\\.json$`),_u=new RegExp(`^artifacts/${Jr}/${Jr}/[A-Za-z0-9][A-Za-z0-9._-]*$`),No=1024**3,Lo=8*1024**3,Iu="the bundles to import add up to more than 8 GB unzipped",Sc=Math.min(Lo,xt),xc=100,Cu=1024**2,Pu=6e5;function Ou(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function Bo(e){let t=K.join(e,".saffron","reports");for(let o of W.existsSync(t)?W.readdirSync(t):[]){let i=Number(/^run-download-(\d+)-/.exec(o)?.[1]),a=K.join(t,o),c=i?W.statSync(a,{throwIfNoEntry:!1}):void 0;c&&Date.now()-c.mtimeMs>36e5&&!Ou(i)&&W.rmSync(a,{recursive:!0,force:!0})}let n=K.join(t,`run-download-${process.pid}-${Mo(4).toString("hex")}`),r=W.mkdirSync(n,{recursive:!0});return{dir:n,remove:()=>{W.rmSync(n,{recursive:!0,force:!0});for(let o=t;r&&o.startsWith(r);o=K.dirname(o))try{W.rmdirSync(o)}catch{break}}}}async function ju(e,t){let n=r=>new D(r?.name==="TimeoutError"?`cannot download ${e}: it did not finish within 10 minutes`:`cannot download ${e}: ${zt(r)}`);try{let r=await fetch(e,{redirect:"follow",signal:AbortSignal.timeout(Pu)});if(!r.ok||!r.body)throw new D(`cannot download ${e}: HTTP ${r.status}`);let s=W.openSync(t,"w");try{let o=0;for await(let i of r.body){if(o+=i.length,o>Lo)throw new D(`cannot download ${e}: it is over 8 GB`);W.writeSync(s,i)}}finally{W.closeSync(s)}}catch(r){throw r instanceof D?r:n(r)}}async function Nu(e,t){if(/^https?:\/\//i.test(e)){let s=K.join(t(),`url-${Mo(4).toString("hex")}.zip`);return await ju(e,s),[{source:e,file:s}]}let n=W.statSync(e,{throwIfNoEntry:!1});if(!n)throw new D(`not found: ${e}`);let r=n.isDirectory()?W.readdirSync(e,{recursive:!0}).map(String).filter(s=>/^saffron-bundle.*\.zip$/.test(K.basename(s))).sort().map(s=>K.join(e,s)):[e];if(r.length===0)throw new D(`no saffron-bundle*.zip under ${e}`);return r.map(s=>({source:s,file:s}))}function Fu(e,t){let n;try{n=Ea(t)}catch(s){throw new D(`${e} is not a Saffron bundle: ${zt(s)}`)}let r=new Map;for(let s of n){if(r.has(s.name))throw new D(`${e} is damaged: it holds ${ne(s.name)} twice`);r.set(s.name,s)}return{source:e,file:t,entries:r}}var Mu=1024*1024;function $c(e,t,n){let r=bu("sha256"),s=W.openSync(e,"r");try{let o=Buffer.alloc(Math.max(1,Math.min(Mu,t.size)));for(let i=0;i<t.size;){let a=W.readSync(s,o,0,Math.min(o.length,t.size-i),t.start+i);if(a===0)throw new Error("the file ends early");let c=o.subarray(0,a);r.update(c),n?.(c),i+=a}}finally{W.closeSync(s)}return r.digest("hex")}function Du(e){try{return Or(e).sha256}catch{return}}function Lu({source:e,file:t,entries:n}){let r=f=>new D(`${e} ${f}`);for(let f of n.values()){if(f.size>No||f.compressedSize>No)throw r(`is damaged: ${ne(f.name)} is too large`);if(f.method!==0&&f.size>Cu&&f.size>xc*f.compressedSize)throw r(`is damaged: ${ne(f.name)} claims to unzip to over ${xc} times its size`)}let s=f=>{let y=n.get(f);if(!y)throw r(`is damaged: ${f} is missing`);let b;try{let k=y.raw();if(k.length!==y.compressedSize)throw new Error("the file ends early");b=y.method===0?k:vu.inflateRawSync(k,{maxOutputLength:Math.max(y.size,1)})}catch(k){throw r(`is damaged: ${f} cannot be read (${zt(k)})`)}if(b.length!==y.size)throw r(`is damaged: ${f} is truncated`);return b},o=f=>{let y=n.get(f);if(!(!y||y.method!==0)){if(y.compressedSize!==y.size)throw r(`is damaged: ${f} is truncated`);return y}},i=f=>{let y=o(f);if(!y)return Ue(s(f));try{return $c(t,y)}catch(b){throw r(`is damaged: ${f} cannot be read (${zt(b)})`)}},a=(f,y,b)=>{let k=o(f),T=()=>new Error(ne(`${e} is damaged: ${f} changed while it was imported`,1/0));if(!k){let x=s(f);if(Ue(x)!==b)throw T();be(y,x);return}W.mkdirSync(K.dirname(y),{recursive:!0});let v=`${y}.${process.pid}-${Mo(4).toString("hex")}.partial`,S=W.openSync(v,"w");try{let x;try{x=$c(t,k,$=>{for(let h=0;h<$.length;)h+=W.writeSync(S,$,h,$.length-h)})}finally{W.closeSync(S)}if(x!==b)throw T();W.renameSync(v,y)}catch(x){throw W.rmSync(v,{force:!0}),x}},c=f=>{try{return JSON.parse(s(f).toString("utf8"))}catch(y){throw y instanceof D?y:r(`is damaged: ${f} is not JSON`)}};if(!n.has("manifest.json"))throw r("is not a Saffron bundle: it has no manifest.json");let l=c("manifest.json");if(!l||l.tool!=="saffron"||typeof l.format!="number")throw r("is not a Saffron bundle");for(let f of["runner","createdAt","repository","branch","commit","headCommit","run","attempt","url"])if(l[f]!==void 0){if(typeof l[f]!="string")throw r(`is damaged: its manifest's ${f} is not text`);if(l[f].length>2048)throw r(`is damaged: its manifest's ${f} is over 2048 characters`);l[f]=ne(l[f],2048)}if(l.format>qr)throw r(`is bundle format ${l.format}, made by saffron-ai ${l.runner}; this saffron-ai (${Be()}) reads format ${qr}. Update saffron-ai to import it`);if(l.format!==qr)throw r(`has bundle format ${l.format}, which this saffron-ai does not read`);if(!Array.isArray(l.proposals)||!Array.isArray(l.evidence))throw r("is damaged: its manifest has no proposal or evidence list");let{shard:d}=l;if(d!==void 0&&!(Number.isInteger(d?.index)&&Number.isInteger(d?.total)&&d.index>=1&&d.index<=d.total))throw r("is damaged: its manifest's shard is not <index> of <total>");let p=new Map;for(let f of l.proposals){if(!f||typeof f.entry!="string"||!Ac.test(f.entry)||typeof f.revision!="string")throw r(`is damaged: its manifest lists a proposal at ${ne(JSON.stringify(f?.entry)??"nothing")}`);typeof f.feature=="string"&&(f.feature=ne(f.feature)),typeof f.scenario=="string"&&(f.scenario=ne(f.scenario));let y=s(f.entry);if(Ue(y)!==f.revision)throw r(`is damaged: ${f.entry} is not the proposal its manifest names`);p.set(f.entry,y)}for(let f of l.evidence){if(!f||typeof f.entry!="string"||!_u.test(f.entry)||typeof f.sha256!="string")throw r(`is damaged: its manifest lists evidence at ${ne(JSON.stringify(f?.entry)??"nothing")}`);if(i(f.entry)!==f.sha256)throw r(`is damaged: ${f.entry} is not the file its manifest names`)}let u;if(l.report!==void 0){if(l.report!=="report.json")throw r(`is damaged: its manifest names the report ${JSON.stringify(l.report)}`);let f=c("report.json"),y=Rc(f);if(y)throw r(`is damaged: report.json ${y}`);try{kt(f)}catch(b){throw r(`is damaged: report.json cannot be shown (${zt(b)})`)}u=f}if(d&&!(u&&zr(u)))throw r("is damaged: it is a shard's bundle without the shard's report");return{source:e,manifest:l,report:u,files:p,read:s,write:a}}function Bu(e,t){let n=t.headCommit??t.commit,r=dt(e,["rev-parse","HEAD"]);if(!n||!r||r===n)return;let s=`${n.slice(0,7)}${t.branch?` on ${t.branch}`:""}`;if(!/^[0-9a-f]{7,64}$/i.test(n)||!dt(e,["rev-parse","--verify","--quiet",`${n}^{commit}`]))return`this checkout is at ${r.slice(0,7)}, and the bundle was made at ${s}, which this clone does not have: fetch it to review against the same files`;let[o,i]=(dt(e,["rev-list","--left-right","--count",`HEAD...${n}`,"--"])??"").split(/\s+/).map(Number),a=[o?`${o} commit${o===1?"":"s"} ahead of`:"",i?`${i} commit${i===1?"":"s"} behind`:""].filter(Boolean).join(" and ");return`this checkout (${r.slice(0,7)}) is ${a||"not at"} the commit the bundle was made at, ${s}`}function Fo(e){let{repository:t,branch:n,commit:r,headCommit:s,run:o,attempt:i,url:a}=e;return Object.fromEntries(Object.entries({repository:t,branch:n,commit:r,headCommit:s,run:o,attempt:i,url:a}).filter(([,c])=>typeof c=="string"))}var _c=e=>K.join(e,".saffron","reports","imported.json");function ft(e){let t;try{t=JSON.parse(W.readFileSync(_c(e),"utf8"))}catch{return{}}return!t||typeof t!="object"||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([,n])=>!!n&&typeof n.revision=="string"&&!!n.from&&typeof n.from=="object"))}function Uu(e,t){try{return W.readFileSync(e).equals(t)}catch{return!1}}function Ic(e,t,n,r,s){let o;try{o=Us(t,n)}catch(T){let v={file:`.saffron/${n}`,feature:"",scenario:""},S=`cannot be read: ${T instanceof te?T.problem:zt(T)}`;return{verdict:{...v,outcome:"refused",reason:S},shown:v,file:K.join(e,".saffron",n),revision:"",verified:!1}}let{proposal:i,revision:a}=o,{feature:c,scenario:l}=i.cache,d=Ce(e,c,l),p={file:me(e,d),feature:ne(c),scenario:ne(l)},u=T=>({verdict:T,shown:p,file:d,revision:a,verified:i.meta.verified===!0}),f=T=>u({...p,outcome:"refused",reason:T});if(!i.meta.bound)return f("carries no binding (a runner older than 0.8.5 filed it), so nothing can tell whether it fits this checkout");let y=s?`. ${s}`:"";if(!W.existsSync(K.join(e,c)))return f(`is for ${p.feature}, which is not in this checkout${y}`);let b=wt(ee(e,c,l));if(b&&Nn(b)===Nn(i.cache))return u({...p,outcome:"unchanged",reason:"already accepted here: the committed recording is this proposal's"});let k;try{k=Oe(e,i,r)}catch(T){k=`cannot be checked: ${zt(T)}`}return k?f(`does not fit this checkout: ${ne(k,1e3)}${y}`):u()}function Cc(e,t){if(W.existsSync(e.file)){if(Ne(e.file)===e.revision)return{...e.shown,outcome:"unchanged"};if(!t)return{...e.shown,outcome:"refused",reason:"differs from the proposal already pending here for this scenario: review that one first (saffron diff), or import with --overwrite to replace it"}}}function zu(e,t,n,r,s,o){let i=Ic(e,t,n,r,o);if(i.verdict)return i.verdict;W.mkdirSync(K.dirname(i.file),{recursive:!0});try{return ln(i.file,()=>{let a=Cc(i,s);return a||(be(i.file,t),{...i.shown,outcome:"imported"})})}catch(a){if(a instanceof Dt)return{...i.shown,outcome:"refused",reason:"is being decided by another process. Try again."};throw a}}async function Pc(e,t,n,r={}){let s;try{let o=await Oc(t,()=>(s??=Bo(e)).dir,r.describe);return qu(e,o,n,r)}finally{s?.remove()}}async function Oc(e,t,n){let r=[];for(let s of e)for(let o of await Nu(s,t))r.push(Fu(n?.(o.source)??o.source,o.file));if(r.reduce((s,o)=>s+[...o.entries.values()].reduce((i,a)=>i+a.size,0),0)>Lo)throw new D(Iu);return r.map(Lu)}function Hu(e){let t=[...new Set(e)].sort((n,r)=>n-r);return t.length>1?`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`:String(t[0]??"")}function jc(e,t,n){let r=t;if(r.length===0)throw new D("no bundle to import");let s=new Set,o=Vr(e);for(let u of r){if(n.run!==void 0&&u.manifest.run!==n.run)throw new D(`${u.source} was made by ${u.manifest.run?`run ${u.manifest.run}`:"no CI run"}, not by ${n.run}, the run it was downloaded from. If that is expected, download the artifact and import the file`);let f=u.manifest.repository;if(!f&&!n.allowUnknownRepository)throw new D(`${u.source} does not say which repository it comes from (it was made outside a git checkout). Import it with --allow-unknown-repository to check it by its proposals' bindings only`);if(!f)s.add(`${u.source} does not say which repository it comes from: it is checked by its proposals' bindings only`);else if(o.length===0)s.add(`this project has no git remote to compare ${f} with: the bundle is checked by its proposals' bindings only`);else if(!o.includes(f)){let y=k=>k.slice(k.indexOf("/")),b=o.find(k=>y(k)===y(f));if(!b)throw new D(`${u.source} comes from ${f}, and this checkout is ${o.join(", ")}. Import it into a checkout of ${f}`);s.add(`${r.length===1?"the bundle comes":"the bundles come"} from ${f}, and this checkout is ${b}: the same repository under another host name (an SSH host alias, or a mirror), so each proposal is checked by its binding`)}}if(r.length>1){let u=new Set(r.map(v=>v.manifest.run??""));if(u.size>1)throw new D(`these bundles come from different runs (${[...u].map(v=>v||"none recorded").join(", ")}). Import one run at a time`);let f=v=>Number(v.manifest.attempt)||0,y=v=>v.manifest.shard?.index??0,b=new Map;for(let v of r){let S=b.get(y(v));(!S||f(v)>f(S))&&b.set(y(v),v)}let k=r.filter(v=>f(v)<f(b.get(y(v))));for(let v of k){let S=v.manifest.shard?`shard ${v.manifest.shard.index}`:"the whole run";s.add(`${v.source} is ${S} of attempt ${f(v)}, which attempt ${f(b.get(y(v)))} ran again: left out`)}r=r.filter(v=>!k.includes(v));let T=r.filter(v=>!v.manifest.shard);if(T.length>0&&r.length>1)throw new D(`${T.map(v=>v.source).join(", ")} ${T.length===1?"holds a whole run, not a shard of one":"hold whole runs, not shards of one"}: import one run at a time`)}let i,a=r.filter(u=>u.report);if(r.length===1&&a.length===1){let{shard:u,history:f,...y}=a[0].report;i=y}else if(a.length>0)try{let u=Hr(a.map(f=>({file:f.source,report:f.report})),{partial:!0});if(u.replaced.length>0)throw new Ut(`${u.replaced.join(", ")} holds a shard that another bundle of the same attempt holds too`);i=u.report}catch(u){throw u instanceof Ut?new D(`these shard bundles do not belong together: ${u.message}`):u}let c=r[0].manifest,l=Bu(e,c);l&&s.add(l),c.headCommit&&c.commit&&s.add(`the run tested ${c.commit.slice(0,7)}, a pull request's merge commit, not the head of ${c.branch??"its branch"} (${c.headCommit.slice(0,7)}): each proposal is checked against this checkout by its binding`);let d=c.headCommit??c.commit,p=l&&d?`The bundle was made at ${d.slice(0,7)}${c.branch?` on ${c.branch}`:""}: check that out and import again`:void 0;if(i){let u=r.flatMap(f=>f.manifest.shard?[f.manifest.shard]:[]);i.imported={...Fo(c),...u.length>0?{shards:{imported:u.map(f=>f.index).sort((f,y)=>f-y),total:u[0].total}}:{}}}return{bundles:r,report:i,warnings:s,hint:p}}function Nc(e,t,n){let r={written:0,unchanged:0},s=new Map;for(let o of n?.scenarios??[])for(let i of o.evidence??[])s.set(K.posix.dirname(i.file),{feature:o.feature,scenario:o.scenario});for(let o of t)for(let{entry:i,sha256:a}of o.manifest.evidence){let c=K.join(e,".saffron",...i.split("/"));if(Du(c)===a){r.unchanged++;continue}o.write(i,c,a),r.written++;let l=s.get(`.saffron/${K.posix.dirname(i)}`);l&&W.writeFileSync(K.join(K.dirname(c),rn),JSON.stringify(l,null,2))}return r}function Fc(e){let t=new Map;for(let s of e)for(let o of s.manifest.proposals){let i=t.get(o.entry)??{revisions:new Set,shards:[]};i.revisions.add(o.revision),s.manifest.shard&&i.shards.push(s.manifest.shard.index),t.set(o.entry,i)}let n=[],r=new Set;for(let s of e)for(let o of s.manifest.proposals){let i=t.get(o.entry);if(i.revisions.size===1){n.push({b:s,p:o});continue}r.has(o.entry)||(r.add(o.entry),n.push({b:s,p:o,conflict:{file:`.saffron/${o.entry}`,feature:typeof o.feature=="string"?o.feature:"",scenario:typeof o.scenario=="string"?o.scenario:"",outcome:"refused",reason:`is a conflict between the run's shards: shards ${Hu(i.shards)} filed different proposals for this scenario (a Scenario Outline's rows split across shards), so no proposal for it was imported. Run the scenario again on one machine and import that run`}}))}return n}function qu(e,t,n,r){let{bundles:s,report:o,warnings:i,hint:a}=jc(e,t,r),c=Nc(e,s,o),l;if(o){for(let y of o.scenarios){let b=typeof y.proposalFile=="string"?y.proposalFile.split(/[\\/]/).slice(-2):[];Ac.test(`proposals/${b.join("/")}`)&&(y.proposalFile=`.saffron/proposals/${b.join("/")}`)}let f=K.join(e,".saffron","reports","latest.json");Uu(f,Buffer.from(`${JSON.stringify(o,null,2)}
|
|
260
|
-
`))?l="unchanged":(
|
|
261
|
-
`),{bundles:s.map(f=>{let{runner:
|
|
262
|
-
`),
|
|
263
|
-
`)[0]:void 0,failedStep:(
|
|
264
|
-
`)[0]}`:""}`)}if(e.tags.length&&console.log(`tags: ${e.tags.map(o=>`${o.tag} (${o.scenarios})`).join(", ")}`),console.log(e.proposals.length?`${e.proposals.length} proposal(s) pending review: ${e.proposals.map(o=>o.file).join(", ")}`:"no proposals pending review",...e.unreadableProposals.map(o=>`\u26A0 proposal ${o.file} cannot be read: ${o.problem}`),...e.features.flatMap(o=>o.scenarios.filter(i=>i.cacheProblem).map(i=>`\u26A0 recording of ${o.path} \u203A ${i.name} cannot be read: ${i.cacheProblem}`))),e.lastRun){let o=e.lastRun.totals;console.log(`last run ${e.lastRun.finishedAt}: ${o.green} passed \xB7 ${o.yellow} pending review \xB7 ${o.red} failed \xB7 ${o.costUsd===void 0?"cost not reported":`$${o.costUsd.toFixed(2)}`}`)}let s=e.vocabulary;console.log(`vocabulary: ${s.steps} steps (${s.recorded} recorded, ${s.unrecorded} unrecorded), ${s.stepSets} step sets, ${s.divergent.length} divergent, ${s.duplicateWordings.length} duplicate wording group(s)`),e.orphans.length&&console.log(`${e.orphans.length} recording(s) belong to no scenario: run \`saffron prune\` to see them`),(e.data.files.length||e.data.unresolved.length)&&console.log(`test data: ${e.data.files.length} file(s) in ${e.data.dir}/${e.data.env?` \xB7 environment "${e.data.env}"`:""}`+(e.data.unresolved.length?` \xB7 ${e.data.unresolved.length} reference(s) do not resolve: ${e.data.unresolved.map(o=>`{data:${o.ref}}`).join(", ")}`:"")),console.log(`config: ${e.config.file??"(defaults, no saffron.config.json)"}`)}var
|
|
260
|
+
`)[0].matchAll(/^parent ([0-9a-f]+)$/gm)].map(r=>r[1])}function Ku(e,t=process.env){let n=gt(e,["remote"])?.split(`
|
|
261
|
+
`)??[],r=n.includes("origin")?"origin":n[0],s=t.GITHUB_SERVER_URL&&t.GITHUB_REPOSITORY?`${t.GITHUB_SERVER_URL}/${t.GITHUB_REPOSITORY}`:void 0,o=[r&>(e,["remote","get-url",r]),s,t.BUILD_REPOSITORY_URI].map(h=>h?Uc(h):void 0).find(Boolean),i=gt(e,["rev-parse","--abbrev-ref","HEAD"]),a=Gu(t),c=(zc(t)?t.GITHUB_HEAD_REF||a.ref:void 0)||(t.GITHUB_EVENT_NAME==="pull_request_target"?t.GITHUB_BASE_REF:void 0)||(t.GITHUB_REF_TYPE==="tag"?void 0:t.GITHUB_REF_NAME)||Nc(t.SYSTEM_PULLREQUEST_SOURCEBRANCH)||(t.BUILD_SOURCEBRANCH?.startsWith("refs/heads/")?Nc(t.BUILD_SOURCEBRANCH):void 0)||(i!=="HEAD"?i:void 0),l=gt(e,["rev-parse","HEAD"])||t.GITHUB_SHA||t.BUILD_SOURCEVERSION,d=a.sha||t.SYSTEM_PULLREQUEST_SOURCECOMMITID,p=d&&l&&Vo(e,l)[1]===d?d:void 0,u=t.GITHUB_SERVER_URL&&t.GITHUB_REPOSITORY&&t.GITHUB_RUN_ID?`${t.GITHUB_SERVER_URL}/${t.GITHUB_REPOSITORY}/actions/runs/${t.GITHUB_RUN_ID}`:t.SYSTEM_COLLECTIONURI&&t.SYSTEM_TEAMPROJECT&&t.BUILD_BUILDID?`${t.SYSTEM_COLLECTIONURI.replace(/\/?$/,"/")}${encodeURIComponent(t.SYSTEM_TEAMPROJECT)}/_build/results?buildId=${t.BUILD_BUILDID}`:void 0,f={repository:o,branch:c,commit:l,headCommit:p&&p!==l?p:void 0,run:t.GITHUB_RUN_ID&&`github:${t.GITHUB_RUN_ID}`||t.BUILD_BUILDID&&`azure:${t.BUILD_BUILDID}`||Yr(t),attempt:Zr(t),url:u};return Object.fromEntries(Object.entries(f).filter(([,h])=>h!==void 0))}function Zn(e){let t=e.headCommit??e.commit;return[e.run?`run ${e.run}${e.attempt&&e.attempt!=="1"?` (attempt ${e.attempt})`:""}`:"a local run",e.branch||t?`${e.branch??"detached"}${t?` @ ${t.slice(0,7)}`:""}`:void 0,e.repository].filter(Boolean).join(" \xB7 ")}var Yu=/^(latest|shard-\d+-of-\d+)\.json$/;function Zu(e){let t=X.join(e,".saffron","reports"),n;try{n=Y.readdirSync(t).filter(s=>Yu.test(s)).sort()}catch{return}let r;for(let s of n)try{let o=Y.readFileSync(X.join(t,s)),i=JSON.parse(o.toString("utf8"));Do(i)&&(!r||i.finishedAt>r.report.finishedAt)&&(r={bytes:o,report:i})}catch{}return r}function Qu(e,t){return X.join(e,".saffron","reports",t?`saffron-bundle-${zo(t)}.zip`:"saffron-bundle.zip")}var Fc=e=>`${(e/1024**3).toFixed(1)} GB`,Mc='Keep fewer traces ("trace": "retain-on-failure" in saffron.config.json, or --trace retain-on-failure) and run again';function Hc(e,t={}){let n=[],r=[],s=[],o=[],i=X.join(e,".saffron","proposals");for(let{file:h,proposal:w,revision:$,bytes:k}of tt(e,(y,v)=>n.push({file:xe(e,y),problem:v}))){let y=`proposals/${xe(i,h)}`;r.push({name:y,data:k}),s.push({entry:y,feature:w.cache.feature,scenario:w.cache.scenario,revision:$,bound:w.meta.bound}),o.push({file:h,proposal:w,bytes:k})}let a=Zu(e),c=[],l=[],d=[];if(a){r.push({name:"report.json",data:a.bytes});let h=[],w=new Set;for(let k of a.report.scenarios)for(let y of k.evidence??[]){if(w.has(y.file))continue;w.add(y.file);let v=y.file.startsWith(".saffron/artifacts/")?Y.statSync(X.join(e,y.file),{throwIfNoEntry:!1}):void 0;if(!v?.isFile()){l.push(y.file);continue}let S=k.status==="green"&&y.kind==="trace";if(v.size>qo){if(S){d.push(y.file);continue}throw new D(`${y.file} is ${Fc(v.size)}, over the 1 GB a bundle holds per file. ${Mc}`)}h.push({e:y,size:v.size,greenTrace:S})}let $=()=>r.reduce((k,y)=>k+("data"in y?y.data.length:y.size??0)+1024,0)+h.reduce((k,y)=>k+y.size+1024,0);if($()>Lc)for(let k of h.filter(y=>y.greenTrace))h.splice(h.indexOf(k),1),d.push(k.e.file);if($()>Lc)throw new D(`the bundle would hold ${Fc($())}${d.length?" even without the traces of green scenarios":""}, over the 4 GB one bundle holds. ${Mc}, or split the run into shards (--shard)`);for(let{e:k}of h){let y=X.join(e,k.file),v;try{v=kt(X.join(e,".saffron","artifacts"),y)?Br(y):void 0}catch{v=void 0}if(!v||k.sha256&&v.sha256!==k.sha256){l.push(k.file);continue}let S=k.file.slice(9);r.push({name:S,file:y,crc:v.crc,size:v.size}),c.push({entry:S,sha256:v.sha256})}}if(!a&&s.length===0)throw new D("nothing to export: no run report and no pending proposals under .saffron. Run `saffron run` first.");let p=a&&Qr(a.report)?{index:a.report.shard.index,total:a.report.shard.total}:void 0,u={tool:"saffron",format:es,runner:We(),createdAt:new Date().toISOString(),...Ku(e,t.env),...p?{shard:p}:{},...a?{report:"report.json"}:{},proposals:s,evidence:c},f=t.out??Qu(e,p);if(Y.existsSync(f)&&Y.statSync(f).isDirectory())throw new D(`${f} is a folder: give --out a file name, such as ${X.join(f,"saffron-bundle.zip")}`);return Za(f,[{name:"manifest.json",data:Buffer.from(`${JSON.stringify(u,null,2)}
|
|
262
|
+
`)},...r]),{file:f,manifest:u,proposals:o,missing:l,dropped:d,unreadable:n}}var ts="[a-z0-9-]+",qc=new RegExp(`^proposals/${ts}/${ts}\\.json$`),Xu=new RegExp(`^artifacts/${ts}/${ts}/[A-Za-z0-9][A-Za-z0-9._-]*$`),qo=1024**3,Go=8*1024**3,eg="the bundles to import add up to more than 8 GB unzipped",Lc=Math.min(Go,Tt),Dc=100,tg=1024**2,ng=6e5;function rg(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function Ko(e){let t=X.join(e,".saffron","reports");for(let o of Y.existsSync(t)?Y.readdirSync(t):[]){let i=Number(/^run-download-(\d+)-/.exec(o)?.[1]),a=X.join(t,o),c=i?Y.statSync(a,{throwIfNoEntry:!1}):void 0;c&&Date.now()-c.mtimeMs>36e5&&!rg(i)&&Y.rmSync(a,{recursive:!0,force:!0})}let n=X.join(t,`run-download-${process.pid}-${Wo(4).toString("hex")}`),r=Y.mkdirSync(n,{recursive:!0});return{dir:n,remove:()=>{Y.rmSync(n,{recursive:!0,force:!0});for(let o=t;r&&o.startsWith(r);o=X.dirname(o))try{Y.rmdirSync(o)}catch{break}}}}async function sg(e,t){let n=r=>new D(r?.name==="TimeoutError"?`cannot download ${e}: it did not finish within 10 minutes`:`cannot download ${e}: ${Kt(r)}`);try{let r=await fetch(e,{redirect:"follow",signal:AbortSignal.timeout(ng)});if(!r.ok||!r.body)throw new D(`cannot download ${e}: HTTP ${r.status}`);let s=Y.openSync(t,"w");try{let o=0;for await(let i of r.body){if(o+=i.length,o>Go)throw new D(`cannot download ${e}: it is over 8 GB`);Y.writeSync(s,i)}}finally{Y.closeSync(s)}}catch(r){throw r instanceof D?r:n(r)}}async function og(e,t){if(/^https?:\/\//i.test(e)){let s=X.join(t(),`url-${Wo(4).toString("hex")}.zip`);return await sg(e,s),[{source:e,file:s}]}let n=Y.statSync(e,{throwIfNoEntry:!1});if(!n)throw new D(`not found: ${e}`);let r=n.isDirectory()?Y.readdirSync(e,{recursive:!0}).map(String).filter(s=>/^saffron-bundle.*\.zip$/.test(X.basename(s))).sort().map(s=>X.join(e,s)):[e];if(r.length===0)throw new D(`no saffron-bundle*.zip under ${e}`);return r.map(s=>({source:s,file:s}))}function ig(e,t){let n;try{n=Ha(t)}catch(s){throw new D(`${e} is not a Saffron bundle: ${Kt(s)}`)}let r=new Map;for(let s of n){if(r.has(s.name))throw new D(`${e} is damaged: it holds ${ie(s.name)} twice`);r.set(s.name,s)}return{source:e,file:t,entries:r}}var ag=1024*1024;function Bc(e,t,n){let r=Wu("sha256"),s=Y.openSync(e,"r");try{let o=Buffer.alloc(Math.max(1,Math.min(ag,t.size)));for(let i=0;i<t.size;){let a=Y.readSync(s,o,0,Math.min(o.length,t.size-i),t.start+i);if(a===0)throw new Error("the file ends early");let c=o.subarray(0,a);r.update(c),n?.(c),i+=a}}finally{Y.closeSync(s)}return r.digest("hex")}function cg(e){try{return Br(e).sha256}catch{return}}function lg({source:e,file:t,entries:n}){let r=f=>new D(`${e} ${f}`);for(let f of n.values()){if(f.size>qo||f.compressedSize>qo)throw r(`is damaged: ${ie(f.name)} is too large`);if(f.method!==0&&f.size>tg&&f.size>Dc*f.compressedSize)throw r(`is damaged: ${ie(f.name)} claims to unzip to over ${Dc} times its size`)}let s=f=>{let h=n.get(f);if(!h)throw r(`is damaged: ${f} is missing`);let w;try{let $=h.raw();if($.length!==h.compressedSize)throw new Error("the file ends early");w=h.method===0?$:Vu.inflateRawSync($,{maxOutputLength:Math.max(h.size,1)})}catch($){throw r(`is damaged: ${f} cannot be read (${Kt($)})`)}if(w.length!==h.size)throw r(`is damaged: ${f} is truncated`);return w},o=f=>{let h=n.get(f);if(!(!h||h.method!==0)){if(h.compressedSize!==h.size)throw r(`is damaged: ${f} is truncated`);return h}},i=f=>{let h=o(f);if(!h)return Ve(s(f));try{return Bc(t,h)}catch(w){throw r(`is damaged: ${f} cannot be read (${Kt(w)})`)}},a=(f,h,w)=>{let $=o(f),k=()=>new Error(ie(`${e} is damaged: ${f} changed while it was imported`,1/0));if(!$){let S=s(f);if(Ve(S)!==w)throw k();Te(h,S);return}Y.mkdirSync(X.dirname(h),{recursive:!0});let y=`${h}.${process.pid}-${Wo(4).toString("hex")}.partial`,v=Y.openSync(y,"w");try{let S;try{S=Bc(t,$,x=>{for(let b=0;b<x.length;)b+=Y.writeSync(v,x,b,x.length-b)})}finally{Y.closeSync(v)}if(S!==w)throw k();Y.renameSync(y,h)}catch(S){throw Y.rmSync(y,{force:!0}),S}},c=f=>{try{return JSON.parse(s(f).toString("utf8"))}catch(h){throw h instanceof D?h:r(`is damaged: ${f} is not JSON`)}};if(!n.has("manifest.json"))throw r("is not a Saffron bundle: it has no manifest.json");let l=c("manifest.json");if(!l||l.tool!=="saffron"||typeof l.format!="number")throw r("is not a Saffron bundle");for(let f of["runner","createdAt","repository","branch","commit","headCommit","run","attempt","url"])if(l[f]!==void 0){if(typeof l[f]!="string")throw r(`is damaged: its manifest's ${f} is not text`);if(l[f].length>2048)throw r(`is damaged: its manifest's ${f} is over 2048 characters`);l[f]=ie(l[f],2048)}if(l.format>es)throw r(`is bundle format ${l.format}, made by saffron-ai ${l.runner}; this saffron-ai (${We()}) reads format ${es}. Update saffron-ai to import it`);if(l.format!==es)throw r(`has bundle format ${l.format}, which this saffron-ai does not read`);if(!Array.isArray(l.proposals)||!Array.isArray(l.evidence))throw r("is damaged: its manifest has no proposal or evidence list");let{shard:d}=l;if(d!==void 0&&!(Number.isInteger(d?.index)&&Number.isInteger(d?.total)&&d.index>=1&&d.index<=d.total))throw r("is damaged: its manifest's shard is not <index> of <total>");let p=new Map;for(let f of l.proposals){if(!f||typeof f.entry!="string"||!qc.test(f.entry)||typeof f.revision!="string")throw r(`is damaged: its manifest lists a proposal at ${ie(JSON.stringify(f?.entry)??"nothing")}`);typeof f.feature=="string"&&(f.feature=ie(f.feature)),typeof f.scenario=="string"&&(f.scenario=ie(f.scenario));let h=s(f.entry);if(Ve(h)!==f.revision)throw r(`is damaged: ${f.entry} is not the proposal its manifest names`);p.set(f.entry,h)}for(let f of l.evidence){if(!f||typeof f.entry!="string"||!Xu.test(f.entry)||typeof f.sha256!="string")throw r(`is damaged: its manifest lists evidence at ${ie(JSON.stringify(f?.entry)??"nothing")}`);if(i(f.entry)!==f.sha256)throw r(`is damaged: ${f.entry} is not the file its manifest names`)}let u;if(l.report!==void 0){if(l.report!=="report.json")throw r(`is damaged: its manifest names the report ${JSON.stringify(l.report)}`);let f=c("report.json"),h=Lo(f);if(h)throw r(`is damaged: report.json ${h}`);try{At(f)}catch(w){throw r(`is damaged: report.json cannot be shown (${Kt(w)})`)}u=f}if(d&&!(u&&Qr(u)))throw r("is damaged: it is a shard's bundle without the shard's report");return{source:e,manifest:l,report:u,files:p,read:s,write:a}}function dg(e,t){let n=t.headCommit??t.commit,r=gt(e,["rev-parse","HEAD"]);if(!n||!r||r===n)return;let s=`${n.slice(0,7)}${t.branch?` on ${t.branch}`:""}`;if(!/^[0-9a-f]{7,64}$/i.test(n)||!gt(e,["rev-parse","--verify","--quiet",`${n}^{commit}`]))return`this checkout is at ${r.slice(0,7)}, and the bundle was made at ${s}, which this clone does not have: fetch it to review against the same files`;let[o,i]=(gt(e,["rev-list","--left-right","--count",`HEAD...${n}`,"--"])??"").split(/\s+/).map(Number),a=[o?`${o} commit${o===1?"":"s"} ahead of`:"",i?`${i} commit${i===1?"":"s"} behind`:""].filter(Boolean).join(" and ");return`this checkout (${r.slice(0,7)}) is ${a||"not at"} the commit the bundle was made at, ${s}`}function Jo(e){let{repository:t,branch:n,commit:r,headCommit:s,run:o,attempt:i,url:a}=e;return Object.fromEntries(Object.entries({repository:t,branch:n,commit:r,headCommit:s,run:o,attempt:i,url:a}).filter(([,c])=>typeof c=="string"))}var Jc=e=>X.join(e,".saffron","reports","imported.json");function ht(e){let t;try{t=JSON.parse(Y.readFileSync(Jc(e),"utf8"))}catch{return{}}return!t||typeof t!="object"||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([,n])=>!!n&&typeof n.revision=="string"&&!!n.from&&typeof n.from=="object"))}function fg(e,t){try{return Y.readFileSync(e).equals(t)}catch{return!1}}function Wc(e,t,n,r,s){let o;try{o=Qs(t,n)}catch(k){let y={file:`.saffron/${n}`,feature:"",scenario:""},v=`cannot be read: ${k instanceof oe?k.problem:Kt(k)}`;return{verdict:{...y,outcome:"refused",reason:v},shown:y,file:X.join(e,".saffron",n),revision:"",verified:!1}}let{proposal:i,revision:a}=o,{feature:c,scenario:l}=i.cache,d=Fe(e,c,l),p={file:xe(e,d),feature:ie(c),scenario:ie(l)},u=k=>({verdict:k,shown:p,file:d,revision:a,verified:i.meta.verified===!0}),f=k=>u({...p,outcome:"refused",reason:k});if(!i.meta.bound)return f("carries no binding (a runner older than 0.8.5 filed it), so nothing can tell whether it fits this checkout");let h=s?`. ${s}`:"";if(!Y.existsSync(X.join(e,c)))return f(`is for ${p.feature}, which is not in this checkout${h}`);let w=xt(re(e,c,l));if(w&&qn(w)===qn(i.cache))return u({...p,outcome:"unchanged",reason:"already accepted here: the committed recording is this proposal's"});let $;try{$=Le(e,i,r)}catch(k){$=`cannot be checked: ${Kt(k)}`}return $?f(`does not fit this checkout: ${ie($,1e3)}${h}`):u()}function Vc(e,t){if(Y.existsSync(e.file)){if(Be(e.file)===e.revision)return{...e.shown,outcome:"unchanged"};if(!t)return{...e.shown,outcome:"refused",reason:"differs from the proposal already pending here for this scenario: review that one first (saffron diff), or import with --overwrite to replace it"}}}function pg(e,t,n,r,s,o){let i=Wc(e,t,n,r,o);if(i.verdict)return i.verdict;Y.mkdirSync(X.dirname(i.file),{recursive:!0});try{return mn(i.file,()=>{let a=Vc(i,s);return a||(Te(i.file,t),{...i.shown,outcome:"imported"})})}catch(a){if(a instanceof zt)return{...i.shown,outcome:"refused",reason:"is being decided by another process. Try again."};throw a}}async function Gc(e,t,n,r={}){let s;try{let o=await Kc(t,()=>(s??=Ko(e)).dir,r.describe);return gg(e,o,n,r)}finally{s?.remove()}}async function Kc(e,t,n){let r=[];for(let s of e)for(let o of await og(s,t))r.push(ig(n?.(o.source)??o.source,o.file));if(r.reduce((s,o)=>s+[...o.entries.values()].reduce((i,a)=>i+a.size,0),0)>Go)throw new D(eg);return r.map(lg)}function ug(e){let t=[...new Set(e)].sort((n,r)=>n-r);return t.length>1?`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`:String(t[0]??"")}function Yc(e,t,n){let r=t;if(r.length===0)throw new D("no bundle to import");let s=new Set,o=ns(e);for(let u of r){if(n.run!==void 0&&u.manifest.run!==n.run)throw new D(`${u.source} was made by ${u.manifest.run?`run ${u.manifest.run}`:"no CI run"}, not by ${n.run}, the run it was downloaded from. If that is expected, download the artifact and import the file`);let f=u.manifest.repository;if(!f&&!n.allowUnknownRepository)throw new D(`${u.source} does not say which repository it comes from (it was made outside a git checkout). Import it with --allow-unknown-repository to check it by its proposals' bindings only`);if(!f)s.add(`${u.source} does not say which repository it comes from: it is checked by its proposals' bindings only`);else if(o.length===0)s.add(`this project has no git remote to compare ${f} with: the bundle is checked by its proposals' bindings only`);else if(!o.includes(f)){let h=$=>$.slice($.indexOf("/")),w=o.find($=>h($)===h(f));if(!w)throw new D(`${u.source} comes from ${f}, and this checkout is ${o.join(", ")}. Import it into a checkout of ${f}`);s.add(`${r.length===1?"the bundle comes":"the bundles come"} from ${f}, and this checkout is ${w}: the same repository under another host name (an SSH host alias, or a mirror), so each proposal is checked by its binding`)}}if(r.length>1){let u=new Set(r.map(y=>y.manifest.run??""));if(u.size>1)throw new D(`these bundles come from different runs (${[...u].map(y=>y||"none recorded").join(", ")}). Import one run at a time`);let f=y=>Number(y.manifest.attempt)||0,h=y=>y.manifest.shard?.index??0,w=new Map;for(let y of r){let v=w.get(h(y));(!v||f(y)>f(v))&&w.set(h(y),y)}let $=r.filter(y=>f(y)<f(w.get(h(y))));for(let y of $){let v=y.manifest.shard?`shard ${y.manifest.shard.index}`:"the whole run";s.add(`${y.source} is ${v} of attempt ${f(y)}, which attempt ${f(w.get(h(y)))} ran again: left out`)}r=r.filter(y=>!$.includes(y));let k=r.filter(y=>!y.manifest.shard);if(k.length>0&&r.length>1)throw new D(`${k.map(y=>y.source).join(", ")} ${k.length===1?"holds a whole run, not a shard of one":"hold whole runs, not shards of one"}: import one run at a time`)}let i,a=r.filter(u=>u.report);if(r.length===1&&a.length===1){let{shard:u,history:f,...h}=a[0].report;i=h}else if(a.length>0)try{let u=Xr(a.map(f=>({file:f.source,report:f.report})),{partial:!0});if(u.replaced.length>0)throw new Gt(`${u.replaced.join(", ")} holds a shard that another bundle of the same attempt holds too`);i=u.report}catch(u){throw u instanceof Gt?new D(`these shard bundles do not belong together: ${u.message}`):u}let c=r[0].manifest,l=dg(e,c);l&&s.add(l),c.headCommit&&c.commit&&s.add(`the run tested ${c.commit.slice(0,7)}, a pull request's merge commit, not the head of ${c.branch??"its branch"} (${c.headCommit.slice(0,7)}): each proposal is checked against this checkout by its binding`);let d=c.headCommit??c.commit,p=l&&d?`The bundle was made at ${d.slice(0,7)}${c.branch?` on ${c.branch}`:""}: check that out and import again`:void 0;if(i){let u=r.flatMap(f=>f.manifest.shard?[f.manifest.shard]:[]);i.imported={...Jo(c),...u.length>0?{shards:{imported:u.map(f=>f.index).sort((f,h)=>f-h),total:u[0].total}}:{}}}return{bundles:r,report:i,warnings:s,hint:p}}function Zc(e,t,n){let r={written:0,unchanged:0},s=new Map;for(let o of n?.scenarios??[])for(let i of o.evidence??[])s.set(X.posix.dirname(i.file),{feature:o.feature,scenario:o.scenario});for(let o of t)for(let{entry:i,sha256:a}of o.manifest.evidence){let c=X.join(e,".saffron",...i.split("/"));if(cg(c)===a){r.unchanged++;continue}o.write(i,c,a),r.written++;let l=s.get(`.saffron/${X.posix.dirname(i)}`);l&&Y.writeFileSync(X.join(X.dirname(c),fn),JSON.stringify(l,null,2))}return r}function Qc(e){let t=new Map;for(let s of e)for(let o of s.manifest.proposals){let i=t.get(o.entry)??{revisions:new Set,shards:[]};i.revisions.add(o.revision),s.manifest.shard&&i.shards.push(s.manifest.shard.index),t.set(o.entry,i)}let n=[],r=new Set;for(let s of e)for(let o of s.manifest.proposals){let i=t.get(o.entry);if(i.revisions.size===1){n.push({b:s,p:o});continue}r.has(o.entry)||(r.add(o.entry),n.push({b:s,p:o,conflict:{file:`.saffron/${o.entry}`,feature:typeof o.feature=="string"?o.feature:"",scenario:typeof o.scenario=="string"?o.scenario:"",outcome:"refused",reason:`is a conflict between the run's shards: shards ${ug(i.shards)} filed different proposals for this scenario (a Scenario Outline's rows split across shards), so no proposal for it was imported. Run the scenario again on one machine and import that run`}}))}return n}function gg(e,t,n,r){let{bundles:s,report:o,warnings:i,hint:a}=Yc(e,t,r),c=Zc(e,s,o),l;if(o){for(let h of o.scenarios){let w=typeof h.proposalFile=="string"?h.proposalFile.split(/[\\/]/).slice(-2):[];qc.test(`proposals/${w.join("/")}`)&&(h.proposalFile=`.saffron/proposals/${w.join("/")}`)}let f=X.join(e,".saffron","reports","latest.json");fg(f,Buffer.from(`${JSON.stringify(o,null,2)}
|
|
263
|
+
`))?l="unchanged":(Kn(e,o),l="written")}let d=[],p=ht(e),u=JSON.stringify(p);for(let{b:f,p:h,conflict:w}of Qc(s)){if(w){d.push(w);continue}let $=pg(e,f.files.get(h.entry),h.entry,n,r.overwrite===!0,a),k=$.reason===void 0?$:{...$,reason:ie($.reason,1/0)};d.push(k),(k.outcome==="imported"||k.outcome==="unchanged"&&!k.reason)&&(p[k.file]={revision:h.revision,from:{...Jo(f.manifest),...f.manifest.shard?{shard:f.manifest.shard}:{}}})}for(let[f,h]of Object.entries(p)){let w;try{w=Be(X.join(e,f))}catch{w=void 0}w!==h.revision&&delete p[f]}return JSON.stringify(p)!==u&&Te(Jc(e),`${JSON.stringify(p,null,2)}
|
|
264
|
+
`),{bundles:s.map(f=>{let{runner:h,createdAt:w,shard:$}=f.manifest;return{source:f.source,runner:h,createdAt:w,origin:Jo(f.manifest),...$?{shard:{index:$.index,total:$.total}}:{}}}),warnings:[...i],proposals:d,evidence:c,...l?{report:l}:{}}}async function Xc(e,t,n,r,s={}){let o=await Kc(n,()=>{throw new D("a viewed run is read from its downloaded folder")},s.describe),{bundles:i,report:a,warnings:c,hint:l}=Yc(e,o,{run:s.run});Zc(t,i,a);let d=Qc(i).map(({b:p,p:u,conflict:f})=>{if(f)return{feature:f.feature,scenario:f.scenario,verified:!1,importable:!1,reason:f.reason};let h=Wc(e,p.files.get(u.entry),u.entry,r,l),w=h.verdict??Vc(h,!1),{feature:$,scenario:k}=h.shown,y={feature:$||(typeof u.feature=="string"?u.feature:""),scenario:k||(typeof u.scenario=="string"?u.scenario:""),verified:h.verified};return w?{...y,importable:!1,reason:ie(w.reason??"already pending here",1/0)}:{...y,importable:!0}});return{report:a,warnings:[...c],proposals:d}}var hg=/^\s*StepSet:/;function It(e,t){return st.relative(e,t).split(st.sep).join("/")}function mg(e,t){let n={green:0,yellow:1,red:2};return!e||n[t]>n[e]?t:e}function Qn(e,t,n={}){let r=t.features??"features",s=st.isAbsolute(r)?r:st.join(e,r),o=st.join(e,".saffron","reports","latest.json"),i=st.join(e,".saffron","reports","latest.html"),a;try{a=JSON.parse(ze.readFileSync(o,"utf8"))}catch{a=void 0}let c=new Map;for(let m of a?.scenarios??[])c.set(m.feature,[...c.get(m.feature)??[],m]);let l=new Map,d;try{l=ft(Ut(s),e)}catch(m){d=m instanceof Error?m.message:String(m)}let p=ze.existsSync(s)?[...ze.readdirSync(s,{recursive:!0})].map(String).filter(pt).map(m=>st.join(s,m)).sort():[],u=[],f=new Map,h=new Map,w={parsedFiles:new Set,owned:new Set,unreadable:d?[d]:[]};for(let m of p){let g=It(e,m),T="";try{T=ze.readFileSync(m,"utf8")}catch(_){u.push({path:g,name:g,scenarios:[],stepSets:0,error:String(_)}),w.unreadable.push(`${g}: ${String(_)}`);continue}let E=T.split(`
|
|
265
|
+
`),A=E.filter(_=>hg.test(_)).length,P=E.find(_=>/^\s*Feature:/.test(_)),O=P?P.replace(/^\s*Feature:\s*/,"").trim():g,I;try{I=Ce(m,e,l)}catch(_){u.push({path:g,name:O,scenarios:[],stepSets:A,error:d??(_ instanceof Error?_.message:String(_))}),w.unreadable.push(`${g}: ${_ instanceof Error?_.message:String(_)}`);continue}w.parsedFiles.add(m),h.set(m,I);let N=new Set(I.map(_=>_.name)),M=new Map;for(let _ of(I[0]&&c.get(I[0].featurePath))??[]){let j=Jt(_,U=>N.has(U));M.set(j,mg(M.get(j),_.status))}let B=new Map;for(let _ of I){w.owned.add(Qe(e,_.featurePath,_.displayName));let j=B.get(_.name);if(j){j.rows+=1;for(let Z of _.tags)j.tags.includes(Z)||(j.tags.push(Z),f.set(Z,(f.get(Z)??0)+1));continue}let U=re(e,_.featurePath,_.name);w.owned.add(U),w.owned.add(Fe(e,_.featurePath,_.name));let K="missing",de;if(ze.existsSync(U))try{let Z=Re(U);K=Z&&zn(_,Z)?"valid":"stale"}catch(Z){K="invalid",de=Z instanceof oe?Z.problem:Z instanceof Error?Z.message:String(Z)}B.set(_.name,{name:_.name,line:_.line,tags:[..._.tags],outline:Object.keys(_.params).length>0,rows:1,cached:K!=="missing",cacheState:K,...de?{cacheProblem:de}:{},proposal:ze.existsSync(Fe(e,_.featurePath,_.name)),lastStatus:M.get(_.name)});for(let Z of _.tags)f.set(Z,(f.get(Z)??0)+1)}u.push({path:g,name:O,scenarios:[...B.values()],stepSets:A})}let $=[],k=ht(e),y=tt(e,(m,g)=>$.push({file:It(e,m),problem:g})).map(({file:m,proposal:g,revision:T})=>({file:It(e,m),feature:g.cache.feature,scenario:g.cache.scenario,mode:g.meta.mode,createdAt:g.meta.createdAt,verified:g.meta.verified,proofError:g.meta.proofError,stale:g.meta.bound?Le(e,g,l):void 0,unbound:g.meta.bound?void 0:!0,revision:T,adaptations:g.meta.adaptations??[],narrative:g.meta.narrative,suggestedFeatureEdit:g.meta.suggestedFeatureEdit,recordedFor:g.meta.recordedFor,aiCalls:g.meta.usage?.aiCalls??0,costUsd:g.meta.usage&&De({costUsd:g.meta.usage.costUsd??0,aiCalls:g.meta.usage.aiCalls})?g.meta.usage.costUsd:void 0,importedFrom:k[It(e,m)]?.revision===T?k[It(e,m)].from:void 0})).sort((m,g)=>m.file.localeCompare(g.file)),v;try{v=et(e,r,l,h)}catch{v={steps:[],stepSets:[],scannedFiles:0,scannedCaches:0}}let S=wg(e),x=Wn(e,Math.max(100,n.historyLimit??30)),b=x.filter(m=>!m.partial).slice(-(n.historyLimit??30)).map(m=>({startedAt:m.startedAt,green:m.green,yellow:m.yellow,red:m.red,passRate:qt(m,m.scenarios),aiCalls:m.aiCalls,costUsd:De(m)?m.costUsd:void 0})),R=st.join(e,"saffron.config.json");return{tool:"saffron",version:We(),projectRoot:e,packageInstalled:ze.existsSync(st.join(e,"node_modules","saffron-ai")),config:{file:ze.existsSync(R)?"saffron.config.json":void 0,effective:ma(t)},features:u,tags:[...f.entries()].map(([m,g])=>({tag:m,scenarios:g})).sort((m,g)=>m.tag.localeCompare(g.tag)),proposals:y,unreadableProposals:$,lastRun:a?{startedAt:a.startedAt,finishedAt:a.finishedAt,totals:{...a.totals,costUsd:De(a.totals)?a.totals.costUsd:void 0},reportHtml:ze.existsSync(i)?It(e,i):void 0,attention:a.scenarios.filter(m=>m.status!=="green").map(m=>({feature:m.feature,scenario:m.scenario,baseScenario:Jt(m,g=>u.some(T=>T.path===m.feature&&T.scenarios.some(E=>E.name===g))),status:m.status,error:m.status==="red"?m.error?.split(`
|
|
266
|
+
`)[0]:void 0,failedStep:(m.steps??[]).find(g=>g.status==="failed")?.gherkin??m.evidence?.find(g=>g.step)?.step,evidence:(m.evidence??[]).filter(g=>g.kind==="trace"?ze.existsSync(st.join(e,g.file)):gn(e,g)!==void 0).map(g=>({kind:g.kind,file:g.file,...g.step?{step:g.step}:{},...g.sha256?{sha256:g.sha256}:{}}))})).sort((m,g)=>m.status===g.status?0:m.status==="red"?-1:1)}:void 0,history:b,quality:Tc(u,x),vocabulary:{steps:v.steps.length,recorded:v.steps.filter(m=>m.status==="recorded").length,unrecorded:v.steps.filter(m=>m.status==="unrecorded").length,stepSets:v.stepSets.length,divergent:v.steps.filter(m=>m.status==="divergent").map(m=>m.text),duplicateWordings:S.slice(0,50)},data:(()=>{let m=Ae(),g=[],T=new Set;for(let[E,A]of h)for(let P of A)for(let O of ct(je(P)))if(!T.has(O)){T.add(O);try{wr(O)}catch(I){g.push({ref:O,reason:I instanceof Error?I.message:String(I),feature:It(e,E),scenario:P.name})}}return{dir:It(e,m.dir),env:m.env,files:ze.existsSync(m.dir)?ze.readdirSync(m.dir).filter(E=>/\.(json|csv)$/.test(E)).sort():[],unresolved:g}})(),orphans:(()=>{let m=Mr(e,r,w);return m.unreadable.length?[]:m.orphans})()}}function tl(e){let t=e.features.reduce((o,i)=>o+i.scenarios.length,0),n=e.features.reduce((o,i)=>o+i.scenarios.filter(a=>a.cacheState==="valid").length,0),r=e.features.reduce((o,i)=>o+i.scenarios.filter(a=>a.cacheState==="stale"||a.cacheState==="invalid").length,0);console.log(`saffron ${e.version} \xB7 ${e.features.length} feature file(s) \xB7 ${t} scenario(s), ${n} replay from cache`+(r?`, ${r} stale (\u26A0) and will re-record`:""));for(let o of e.features){let i=o.scenarios.map(a=>a.proposal?"\u25D0":a.cacheState==="valid"?"\u25CF":a.cacheState==="missing"?"\u25CB":"\u26A0").join("");console.log(` ${o.path} ${i}${o.error?` \u2717 ${o.error.split(`
|
|
267
|
+
`)[0]}`:""}`)}if(e.tags.length&&console.log(`tags: ${e.tags.map(o=>`${o.tag} (${o.scenarios})`).join(", ")}`),console.log(e.proposals.length?`${e.proposals.length} proposal(s) pending review: ${e.proposals.map(o=>o.file).join(", ")}`:"no proposals pending review",...e.unreadableProposals.map(o=>`\u26A0 proposal ${o.file} cannot be read: ${o.problem}`),...e.features.flatMap(o=>o.scenarios.filter(i=>i.cacheProblem).map(i=>`\u26A0 recording of ${o.path} \u203A ${i.name} cannot be read: ${i.cacheProblem}`))),e.lastRun){let o=e.lastRun.totals;console.log(`last run ${e.lastRun.finishedAt}: ${o.green} passed \xB7 ${o.yellow} pending review \xB7 ${o.red} failed \xB7 ${o.costUsd===void 0?"cost not reported":`$${o.costUsd.toFixed(2)}`}`)}let s=e.vocabulary;console.log(`vocabulary: ${s.steps} steps (${s.recorded} recorded, ${s.unrecorded} unrecorded), ${s.stepSets} step sets, ${s.divergent.length} divergent, ${s.duplicateWordings.length} duplicate wording group(s)`),e.orphans.length&&console.log(`${e.orphans.length} recording(s) belong to no scenario: run \`saffron prune\` to see them`),(e.data.files.length||e.data.unresolved.length)&&console.log(`test data: ${e.data.files.length} file(s) in ${e.data.dir}/${e.data.env?` \xB7 environment "${e.data.env}"`:""}`+(e.data.unresolved.length?` \xB7 ${e.data.unresolved.length} reference(s) do not resolve: ${e.data.unresolved.map(o=>`{data:${o.ref}}`).join(", ")}`:"")),console.log(`config: ${e.config.file??"(defaults, no saffron.config.json)"}`)}var yg=/^(<[^>]+>|\{env:[^}]+\}|\{date[^}]*\})$/;function el(e){return e?e.role?`${e.role}${e.name?` "${e.name}"`:e.nameRegex?` /${e.nameRegex}/`:""}`:e.label?`label "${e.label}"`:e.text?`text "${e.text}"`:e.testId?`testid ${e.testId}`:e.placeholder?`placeholder "${e.placeholder}"`:e.fallbackSelectors?.length?e.fallbackSelectors[0]:"":""}function wg(e){let t;try{t=Xe(e)}catch{return[]}let n=new Map;for(let r of t.steps.values()){if(r.actions.length===0)continue;let s=Ar(r.gherkin).pattern,o=[...r.gherkin.matchAll(/"([^"]*)"/g)].map(p=>p[1]),i=p=>p!==void 0&&(o.includes(p)||yg.test(p))?"\xABarg\xBB":p,a=r.actions.map(p=>{let{pageFingerprint:u,value:f,promptText:h,...w}=p;return{...w,value:i(f),promptText:i(h)}}),c=JSON.stringify(a),l=r.actions.map(p=>`${p.action}${el(p.target)?` ${el(p.target)}`:p.url?` ${p.url}`:""}`).join(" \xB7 "),d=n.get(c)??{steps:new Map,actions:l};d.steps.has(s)||d.steps.set(s,r.gherkin),n.set(c,d)}return[...n.values()].filter(r=>r.steps.size>1).map(r=>({steps:[...r.steps.values()].sort(),actions:r.actions})).sort((r,s)=>s.steps.length-r.steps.length||r.steps[0].localeCompare(s.steps[0]))}async function nl(e,t){let n=new bg({name:"saffron",version:We()},{capabilities:{tools:{}}});n.setRequestHandler(xg,async()=>({tools:[{name:"search_steps",description:"Search the project's step vocabulary. Returns known Gherkin steps with status (recorded = replays at zero tokens, divergent, unrecorded), usage counts, and source files. ALWAYS reuse an existing wording exactly instead of inventing a near-duplicate: exact step text is the replay-cache identity, so a new wording costs a fresh AI recording.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Case-insensitive substring filter over step text; omit to list everything."}}}},{name:"list_step_sets",description:"List the project's StepSet definitions (named reusable step sequences from .saffron files) with their steps, defining file, and usage. Invoke one inside a scenario with a line reading exactly: StepSet <name>",inputSchema:{type:"object",properties:{}}},{name:"project_status",description:"The project overview (same data as `saffron status --json`): every feature file with its scenarios (header line, tags, outline rows, cached / proposal pending / last run status), the tag list, pending proposals with narrative and proof-replay verdict (and, for one imported from CI with `saffron import`, the run, branch and commit it came from, as importedFrom), the last run's totals, run history, vocabulary health (divergent steps, duplicate wordings proven by identical recordings) and the effective config. Call it before editing tests to see what is already recorded and what awaits review.",inputSchema:{type:"object",properties:{}}}]})),n.setRequestHandler(Sg,async r=>$g(r.params.name,r.params.arguments,e,t)),await n.connect(new vg)}function $g(e,t,n,r){let s=o=>({content:[{type:"text",text:JSON.stringify(o,null,2)}]});if(e==="search_steps"){let o=et(n,r),i=typeof t?.query=="string"?t.query:void 0,a=i?_r(o,i):o;return s({steps:a.steps,scannedFiles:a.scannedFiles,scannedCaches:a.scannedCaches})}if(e==="list_step_sets"){let o=et(n,r);return s({stepSets:o.stepSets})}return e==="project_status"?s(Qn(n,le(n))):{content:[{type:"text",text:`Unknown tool: ${e}`}],isError:!0}}import{query as kg}from"@anthropic-ai/claude-agent-sdk";function rl(e,t){let n=t.steps.map(s=>`- [${s.status}] ${s.keyword} ${s.text}`).join(`
|
|
265
268
|
`),r=t.stepSets.map(s=>`- StepSet ${s.name}
|
|
266
269
|
${s.steps.map(o=>` ${o}`).join(`
|
|
267
270
|
`)}`).join(`
|
|
268
271
|
`);return["Draft a Saffron feature file from the requirements below.","","EXISTING STEP VOCABULARY \u2014 reuse these wordings EXACTLY (character for character) wherever they express what a step needs to do. Steps marked [recorded] or [divergent] already have replay recordings: reusing them makes the new file replay almost for free. Only invent a new wording when nothing in the vocabulary expresses the intent, and then follow the same style:",n.length>0?n:"(none yet \u2014 this is the project's first file)","",t.stepSets.length>0?`EXISTING STEP SETS \u2014 invoke with a line reading exactly \`StepSet <name>\` instead of repeating their steps:
|
|
269
272
|
${r}`:void 0,"","RULES:","1. Output ONLY the feature file content \u2014 no prose, no code fences, no explanations.","2. Gherkin/.saffron syntax: Feature:, Scenario:, Scenario Outline: + Examples, Given/When/Then/And/But. Prefer concrete scenarios; use an Outline only when the requirements list variations of the same flow.","3. Then steps are assertions \u2014 state exactly what must be true, one condition per step. End every scenario with at least one Then.","4. If the same 3+ step sequence would appear in two or more scenarios, define it once as a StepSet (first step a guard, last step an exit assertion) and invoke it. Definition uses a colon (StepSet: Name), invocation does not (StepSet Name).",'5. Use 2-column data tables for key/value input, header tables for lists of records, and """ doc strings for free text.',"6. Steps are natural language for an AI browser agent \u2014 never CSS selectors or code.","","REQUIREMENTS:",e.trim()].filter(s=>s!==void 0).join(`
|
|
270
|
-
`)}var
|
|
271
|
-
`}import
|
|
272
|
-
|
|
273
|
-
`);return{
|
|
273
|
+
`)}var sl="You are Saffron's feature-file author. You write clean, assertive Gherkin that reuses the project's exact step vocabulary. You output only file content.";async function il(e,t,n,r){let s={aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0},o="";if(r)return await r({systemPrompt:sl,prompt:rl(e,t),model:n,maxTurns:1,mcpServers:{},mcpToken:"",usage:s,lastOutput:a=>{o=a},finished:()=>!1}),{content:ol(o),usage:s};let i=kg({prompt:rl(e,t),options:{model:n,maxTurns:1,permissionMode:"bypassPermissions",persistSession:!1,settingSources:[],strictMcpConfig:!0,settings:{disableClaudeAiConnectors:!0},allowedTools:[],systemPrompt:sl}});for await(let a of i)if(a.type==="assistant")for(let c of a.message.content)c.type==="text"&&(o+=c.text);else a.type==="result"&&(s.aiCalls=a.num_turns,s.costUsd=a.total_cost_usd,"usage"in a&&a.usage&&(s.inputTokens=a.usage.input_tokens??0,s.outputTokens=a.usage.output_tokens??0,s.cacheReadTokens=a.usage.cache_read_input_tokens??0,s.cacheCreationTokens=a.usage.cache_creation_input_tokens??0));return{content:ol(o),usage:s}}function ol(e){return e.replace(/^\s*```(?:gherkin|saffron)?\s*\n/,"").replace(/\n```\s*$/,"").trim()+`
|
|
274
|
+
`}import He from"node:fs";import{fileURLToPath as Ct,pathToFileURL as Qo}from"node:url";import ae from"node:path";import{createConnection as Ig,ProposedFeatures as Cg,TextDocuments as Pg,TextDocumentSyncKind as Og,DidChangeWatchedFilesNotification as jg,WatchKind as Ng,CompletionItemKind as Pt,InsertTextFormat as hl,DiagnosticSeverity as er,MarkupKind as ml}from"vscode-languageserver/node";import{TextDocument as Fg}from"vscode-languageserver-textdocument";import al from"node:path";var Xn=class extends Error{},Yo=new Set(["and","or","not","(",")"]);function Rg(e){let t=[...e.matchAll(/[(),|]|[^\s(),|]+(?:\([^\s(),|]*\))*/g)].flatMap(([s])=>{let o=/^(and|or|not)\((.*)\)$/i.exec(s);return o?[o[1],"(",o[2],")"].filter(Boolean):[s]}),n=s=>s===","||s==="|",r=[];return t.forEach((s,o)=>{let i=r.at(-1),a=t[o+1];n(s)&&(i===void 0||n(i)||i==="("||a===void 0||n(a)||a===")")||r.push(s)}),r.map(s=>n(s)?"or":Yo.has(s.toLowerCase())?s.toLowerCase():s.startsWith("@")?s:`@${s}`)}function Tg(e){let t=Rg(e),n=0,r=()=>t[n],s=d=>{throw new Xn(`--filter "${e}": ${d}`)},o=!t.some(d=>d==="and"||d==="not"||d==="("||d===")"),i=()=>{let d=a();for(;r()==="or"||o&&r()!==void 0&&r()!==")";){r()==="or"&&n++;let p=a(),u=d;d=f=>u(f)||p(f)}return d},a=()=>{let d=c();for(;r()==="and";){n++;let p=c(),u=d;d=f=>u(f)&&p(f)}return d},c=()=>{let d=r();if(d===void 0)return s("expected a tag at the end");if(d==="not"){n++;let p=c();return u=>!p(u)}if(d==="("){n++;let p=i();return r()!==")"?s("missing a closing parenthesis"):(n++,p)}return Yo.has(d)?s(`expected a tag, found "${d}"`):(n++,p=>p.has(d))},l=i();return n<t.length?s(Yo.has(t[n])?`unexpected "${t[n]}"`:`unexpected "${t[n]}": with and, not or parentheses, join every tag with and/or`):l}function cl(e){let t=(e===void 0?[]:Array.isArray(e)?e:[e]).map(r=>r.trim()).filter(Boolean);if(t.length===0)return;let n=t.map(Tg);return{text:t.length===1?t[0]:t.map(r=>`(${r})`).join(" or "),matches:r=>{let s=new Set(r);return n.some(o=>o(s))}}}function ll(e,t){return t?e.filter(n=>t.matches(n.tags)):e}function dl(e,t){return[...t??[],e]}var Eg=new RegExp(`^(.+?(?:${Ds.map(e=>e.replace(".","\\.")).join("|")})):(.+)$`),Zo=/^\d+(?::\d+)*$/;function fl(e){let t=[],n=new Map;for(let r of e){let s=Eg.exec(r);if(!s){t.push(r);continue}let o=Zo.test(s[2])?s[2].split(":").map(Number):[s[2]];n.set(s[1],[...n.get(s[1])??[],...o])}return{plain:t,picks:n}}var Yt=class extends Error{};function pl(e,t){let n=o=>`${o.featurePath}
|
|
275
|
+
${o.name}`,r=new Set(e.map(n)),s=new Set(e);return[...e,...t.filter(o=>!s.has(o)&&r.has(n(o)))]}function ul(e){let t=e.length>10?[...e.slice(0,10),`\u2026 (${e.length} in all)`]:e;return t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.at(-1)}`}function Ag(e,t,n,r){let s=n.filter(c=>c.kind==="scenario").map(c=>String(c.line)),o=s.length===0?" It has no scenarios.":` Its scenario${s.length===1?" starts at line":"s start at lines"} ${ul(s)}.`,i=c=>{throw new Yt(`${e}:${t} ${c}.${o}`)};t<1&&i("is not a line: lines count from 1"),t>r&&i(`is past the end of the file, which has ${r} lines`);let a=n.filter(c=>c.start<=t).at(-1);return a?(a.kind==="background"&&i("is in the Background, which runs before every scenario, not in a scenario"),a.kind==="stepSet"&&i(`is in StepSet "${a.name}", which runs where a scenario invokes it, not in a scenario`),a.kind==="rule"&&i(`is the header of Rule "${a.name}", not a scenario`),{line:a.rows.includes(t)?t:a.line,block:a}):i("is in the feature's header, not in a scenario")}function _g(e,t,n){let r=n.filter(i=>i.kind==="scenario"),s=r.find(i=>i.name===t);if(s)return{line:s.line,block:s};let o=r.map(i=>`"${i.name}"`);throw new Yt(`${e}:${t} names no scenario.${o.length===0?" It has no scenarios.":` Its scenario${o.length===1?" is":"s are"} ${ul(o)}.`}`)}function gl(e,t,n,r){let s=new Map,o=new Map;for(let[a,c]of n){let l=al.resolve(t,a);if(r.has(l))continue;let{blocks:d,lineCount:p}=na(l,t),u=al.relative(t,l),f=s.get(u)??new Map;for(let h of c){if(typeof h=="string"&&!d.some(y=>y.kind==="scenario"&&y.name===h)&&e.some(y=>y.featurePath===u&&y.displayName===h)){o.set(u,(o.get(u)??new Set).add(h));continue}let{line:$,block:k}=typeof h=="number"?Ag(a,h,d,p):_g(a,h,d);f.set($,`${a}:${h} is in Scenario Outline "${k.name}", whose Examples have no rows yet: nothing to run`)}s.set(u,f)}let i=e.filter(a=>{let c=s.get(a.featurePath);return!c||c.has(a.line??0)||c.has(a.exampleLine??0)||o.get(a.featurePath)?.has(a.displayName)===!0});for(let[a,c]of s)for(let[l,d]of c)if(!i.some(p=>p.featurePath===a&&(p.line===l||p.exampleLine===l)))throw new Yt(`${d}.`);return i}var yl=/^(\s*)(Given|When|Then|And|But|\*)\s+(.+?)\s*$/,Mg=/^\s*StepSet:\s*(.+?)\s*$/,Xo=/^(\s*)(StepSet)\s+([^\s:].*?)\s*$/,ei={recorded:"\u25CF recorded: replays at zero tokens",divergent:"\u25CF divergent: same text, different recordings",unrecorded:"\u25CB written, not recorded yet"};function Lg(e,t){let n=i=>new Set(i.toLowerCase().replace(/"[^"]*"/g,'"x"').split(/[^a-z0-9"<>]+/).filter(Boolean)),r=n(e),s=n(t);if(r.size===0||s.size===0)return 0;let o=0;for(let i of r)s.has(i)&&o++;return o/(r.size+s.size-o)}function wl(e){try{return JSON.parse(He.readFileSync(ae.join(e,"saffron.config.json"),"utf8"))}catch{return{}}}function bl(e){try{let t=JSON.parse(He.readFileSync(ae.join(e,"saffron.config.json"),"utf8"));return typeof t.features=="string"?t.features:void 0}catch{return}}function xn(e,t){let n=ae.dirname(e),r=ae.resolve(t);for(;;){if(He.existsSync(ae.join(n,"saffron.config.json")))return n;if(n===r||ae.dirname(n)===n)return t;n=ae.dirname(n)}}function $l(e,t,n={}){let r=e,s=t,o=e,i=!1,a=!1,c=m=>{if(!m.startsWith("file:"))return;let g=xn(Ct(m),o);if(g===r)return;y(g);let T=$.get(g);if(!T||!i||k.has(g))return S();({vocab:f,registry:h,files:w}=T);for(let E of u.all())d(E)&&R(E)},l=m=>{if(!m.startsWith("file:"))return;let g=Ct(m),T=xn(g,o);$.get(T)?.files.has(g)||k.add(T)},d=m=>!m.uri.startsWith("file:")||xn(Ct(m.uri),o)===r,p=Ig(Cg.all,process.stdin,process.stdout),u=new Pg(Fg),f={steps:[],stepSets:[],scannedFiles:0,scannedCaches:0},h=new Map,w=new Set,$=new Map,k=new Set,y=m=>{r=m,s=bl(m)??(He.existsSync(ae.join(m,"saffron.config.json"))?"features":t);try{let g=wl(m);Ye(m,g.dataDir,process.env.SAFFRON_ENV??g.env)}catch(g){p.console.warn(`saffron vocabulary rebuild: ${String(g)}`)}},v,S=()=>{try{let m=ae.isAbsolute(s)?s:ae.join(r,s),g=wl(r);Ye(r,g.dataDir,process.env.SAFFRON_ENV??g.env),h=ft(Ut(m),r),f=et(r,s,h),w=new Set(Ws(m)),$.set(r,{vocab:f,registry:h,files:w}),k.delete(r)}catch(m){p.console.warn(`saffron vocabulary rebuild: ${String(m)}`),{vocab:f,registry:h,files:w}=$.get(r)??{vocab:{steps:[],stepSets:[],scannedFiles:0,scannedCaches:0},registry:new Map,files:new Set}}for(let m of u.all())d(m)&&R(m)},x=()=>{clearTimeout(v),v=setTimeout(()=>{let m=r,g=new Set(u.all().filter(T=>T.uri.startsWith("file:")).map(T=>xn(Ct(T.uri),o)));for(let T of $.keys())!g.has(T)&&T!==m&&$.delete(T);g.delete(m);for(let T of[...g,m])y(T),S()},300)};function b(m){return f.steps.find(g=>g.text===m)?.status}function R(m){let g=m.getText().split(`
|
|
276
|
+
`),T=qg(g);if(!m.uri.endsWith(".saffron")){p.sendDiagnostics({uri:m.uri,diagnostics:T});return}let E=new Map;for(let A=0;A<g.length;A++){let P=g[A],O={start:{line:A,character:0},end:{line:A,character:P.length}},I=P.match(Xo);I&&!h.has(I[3])&&T.push({range:O,severity:er.Error,source:"saffron",message:`StepSet "${I[3]}" is not defined anywhere in the project.`});let N=P.match(Mg);if(N){let _=h.get(N[1]),j=ae.relative(r,Ct(m.uri)).replace(/\\/g,"/");(E.has(N[1])||_&&_.file.replace(/\\/g,"/")!==j)&&T.push({range:O,severity:er.Error,source:"saffron",message:`StepSet "${N[1]}" is defined twice. Set names are project-wide. If this line was meant to INVOKE the set, remove the colon: "StepSet ${N[1]}".`}),E.set(N[1],A)}let M=P.trim();if(M&&!I&&!N){for(let[_]of h)if(M.toLowerCase()===_.toLowerCase()){T.push({range:O,severity:er.Warning,source:"saffron",message:`Did you mean "StepSet ${_}"? Invoking a step set needs the StepSet keyword, like a step needs Given/When/Then.`});break}}let B=P.match(yl);if(B&&b(B[3])!=="recorded"){for(let _ of f.steps)if(!(_.text===B[3]||_.status==="unrecorded")&&Lg(_.text,B[3])>=.7){T.push({range:{start:{line:A,character:P.indexOf(B[3])},end:{line:A,character:P.length}},severity:er.Information,source:"saffron",message:`Similar to the ${_.status} step "${_.text}" (\xD7${_.usage}). Reusing the exact wording replays at zero tokens; a new wording costs a fresh AI recording.`});break}}}p.sendDiagnostics({uri:m.uri,diagnostics:T})}p.onInitialize(m=>{if(n.rootFromClient){let g=m.workspaceFolders?.[0]?.uri??m.rootUri??void 0;if(g&&g.startsWith("file:")){let T=Ct(g);He.existsSync(T)&&(o=r=T,s=bl(T)??t)}}return i=m.capabilities.workspace?.didChangeWatchedFiles?.dynamicRegistration===!0,a=m.initializationOptions?.runLenses===!0,S(),{capabilities:{textDocumentSync:Og.Incremental,completionProvider:{triggerCharacters:[" ",":","."]},definitionProvider:!0,hoverProvider:!0,...a?{codeLensProvider:{resolveProvider:!1}}:{}}}}),p.onCodeLens(m=>{let g=u.get(m.textDocument.uri);if(!a||!g||!g.uri.startsWith("file:"))return[];let T=Ct(g.uri),E=Bg(T,o);return E?!T.endsWith(".saffron")&&!He.existsSync(ae.join(E,"saffron.config.json"))?[]:Ug(T,g.getText(),E):[]}),p.onInitialized(()=>{if(!i)return;let m=[...["**/*.saffron","**/*.feature","**/saffron.config.json","**/.saffron/cache/**","**/data/**"].map(g=>({globPattern:g})),{globPattern:"**",kind:Ng.Delete}];p.client.register(jg.type,{watchers:m}).catch(()=>{i=!1})}),p.onCompletion(m=>{let g=u.get(m.textDocument.uri);if(!g)return[];c(g.uri);let T=g.getText({start:{line:m.position.line,character:0},end:m.position}),E=Jg(T);return E||Wg(g.uri,T,m.position.line,f)}),p.onDefinition(m=>{let g=u.get(m.textDocument.uri);if(!g)return;c(g.uri);let T=g.getText({start:{line:m.position.line,character:0},end:{line:m.position.line+1,character:0}}).replace(/\n$/,""),E=vl(T,m.position.character);if(E){let N=Hg(E.ref);return N?{uri:Qo(N.file).href,range:{start:{line:N.line,character:0},end:{line:N.line,character:0}}}:void 0}let A=Sl(T,m.position.character);if(A){let N=xl(r,A.name);return N?{uri:Qo(N.file).href,range:{start:{line:N.line,character:0},end:{line:N.line,character:0}}}:void 0}let P=T.match(Xo);if(!P)return;let O=h.get(P[3]);return O?{uri:Qo(ae.join(r,O.file)).href,range:{start:{line:O.line-1,character:0},end:{line:O.line-1,character:0}}}:void 0}),p.onHover(m=>{let g=u.get(m.textDocument.uri);if(!g)return;c(g.uri);{let P=g.getText({start:{line:m.position.line,character:0},end:{line:m.position.line+1,character:0}}).replace(/\n$/,""),O=vl(P,m.position.character);if(O)return{contents:{kind:"markdown",value:kl(O.ref)}};let I=Sl(P,m.position.character);if(I){let N=xl(r,I.name),M=N?`defined in ${ae.relative(r,N.file)} (line ${N.line+1}); the value is resolved at replay and never shown here`:"not found in .env or .env.example; export it in the shell or add it to a git-ignored .env";return{contents:{kind:"markdown",value:`**{env:${I.name}}** ${M}.`}}}}let T=g.getText({start:{line:m.position.line,character:0},end:{line:m.position.line+1,character:0}}).replace(/\n$/,""),E=T.match(Xo);if(E){let P=f.stepSets.find(I=>I.name===E[3]);if(!P)return;let O=P.steps.map(I=>`- ${ei[b(I)??"unrecorded"][0]} ${I}`).join(`
|
|
277
|
+
`);return{contents:{kind:ml.Markdown,value:`**StepSet ${P.name}** expands to:
|
|
274
278
|
|
|
275
|
-
${
|
|
279
|
+
${O}`}}}let A=T.match(yl);if(A){let P=f.steps.find(O=>O.text===A[3]);return P?{contents:{kind:ml.Markdown,value:`${ei[P.status]}
|
|
276
280
|
|
|
277
|
-
Used in ${
|
|
281
|
+
Used in ${P.usage} place(s): ${P.files.join(", ")}${P.fromStepSet?`
|
|
278
282
|
|
|
279
|
-
Defined in StepSet **${
|
|
280
|
-
`),p=i?d.findIndex(u=>u.includes(`"${i}"`)):0;if(p>=0)return{file:l,line:p};a??={file:l,line:0}}return a}function
|
|
281
|
-
`).findIndex(i=>new RegExp(`^\\s*(?:export\\s+)?${t}\\s*=`).test(i));if(o!==-1)return{file:r,line:o}}}function
|
|
282
|
-
`)}));if(/^\s*(Given|When|Then|And|But|\*)\s+/.test(t))return r.steps.map((a,c)=>({label:a.text,kind:
|
|
283
|
+
Defined in StepSet **${P.fromStepSet}**`:""}`}}:void 0}}),u.onDidOpen(m=>{if(l(m.document.uri),m.document.uri.startsWith("file:")){let g=Ct(m.document.uri);xn(g,o)===r&&!w.has(g)&&x()}c(m.document.uri),R(m.document)}),u.onDidClose(m=>l(m.document.uri)),u.onDidChangeContent(m=>{c(m.document.uri),R(m.document)}),u.onDidSave(()=>x()),p.onDidChangeWatchedFiles(()=>x()),u.listen(p),p.listen()}var Dg="saffron.runScenario";function Bg(e,t){let n=xn(e,t),r=ae.relative(ae.resolve(t),n);return r.split(/[\\/]/)[0]===".."||ae.isAbsolute(r)?void 0:n}function Ug(e,t,n){let r=ae.relative(n,e).split(ae.sep).join("/");return r.startsWith("../")||ae.isAbsolute(r)?[]:ra(t).flatMap(({line:s,name:o})=>{let i={start:{line:s-1,character:0},end:{line:s-1,character:0}},a=(c,l)=>{let d=o&&!Zo.test(o)?`${r}:${o}`:`${r}:${s}`;return{range:i,command:{title:c,command:Dg,arguments:[{root:n,target:d,scenario:o,mode:l}]}}};return[a("\u25B6 Run scenario","run"),a("Replay only","replay"),a("Headed","headed")]})}function vl(e,t){let n=/\{data:([A-Za-z0-9_.-]+)\}/g,r;for(;r=n.exec(e);)if(t>=r.index&&t<=r.index+r[0].length)return{ref:r[1],start:r.index,end:r.index+r[0].length}}var zg=e=>/^\s*Examples:/.test(e);function kl(e,t=!1){let{env:n}=Ae(),r=n?` (environment "${n}")`:"";try{if(t||!e.includes(".")){let{headers:i,rows:a}=br(e);return`**{data:${e}}** ${a.length} Examples row(s), columns ${i.map(c=>`\`${c}\``).join(", ")}${r}.`}let s=vt(e);return Array.isArray(Mt(e))?`**{data:${e}}** a list of ${s.length}: ${s.map(i=>`"${i}"`).join(", ")}${r}. Use it with "every": replay checks each value, so adding one needs no re-record.`:`**{data:${e}}** = "${s[0]}"${r}. Resolved at replay: change the file and the next run uses the new value at zero tokens.`}catch(s){return`**{data:${e}}** does not resolve: ${s instanceof Error?s.message:String(s)}`}}function Hg(e){let{dir:t,env:n}=Ae(),[r,...s]=e.split("."),o=[n&&`${r}.${n}.json`,`${r}.json`,n&&`${r}.${n}.csv`,`${r}.csv`].filter(Boolean),i=[...s].reverse().find(c=>!/^\d+$/.test(c)),a;for(let c of o){let l=ae.join(t,c);if(!He.existsSync(l))continue;let d=He.readFileSync(l,"utf8").split(`
|
|
284
|
+
`),p=i?d.findIndex(u=>u.includes(`"${i}"`)):0;if(p>=0)return{file:l,line:p};a??={file:l,line:0}}return a}function qg(e){let t=[];return e.forEach((n,r)=>{for(let s of n.matchAll(/\{data:([A-Za-z0-9_.-]+)\}/g)){let o=kl(s[1],zg(n));o.includes("does not resolve")&&t.push({range:{start:{line:r,character:s.index??0},end:{line:r,character:(s.index??0)+s[0].length}},severity:er.Error,source:"saffron",message:o.replace(/\*\*/g,"")})}}),t}function Jg(e){let t=e.match(/\{data:([A-Za-z0-9_.-]*)$/);if(!t)return;let n=t[1],{dir:r}=Ae(),s=n.split(".");if(s.length===1)return(He.existsSync(r)?[...new Set(He.readdirSync(r).filter(i=>/\.(json|csv)$/.test(i)).map(i=>i.split(".")[0]))].sort():[]).map(i=>({label:i,kind:Pt.File,detail:"data file",insertText:i}));try{let o=Mt(s.slice(0,-1).join("."));return o===null||typeof o!="object"?[]:Object.entries(o).map(([i,a])=>({label:i,kind:a!==null&&typeof a=="object"?Pt.Module:Pt.Value,detail:Array.isArray(a)?`list of ${a.length}`:a!==null&&typeof a=="object"?"object":JSON.stringify(a),insertText:i}))}catch{return[]}}function Sl(e,t){let n=/\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g,r;for(;r=n.exec(e);)if(t>=r.index&&t<=r.index+r[0].length)return{name:r[1],start:r.index,end:r.index+r[0].length}}function xl(e,t){for(let n of[".env",".env.example"]){let r=ae.join(e,n);if(!He.existsSync(r))continue;let o=He.readFileSync(r,"utf8").split(`
|
|
285
|
+
`).findIndex(i=>new RegExp(`^\\s*(?:export\\s+)?${t}\\s*=`).test(i));if(o!==-1)return{file:r,line:o}}}function Wg(e,t,n,r){let s=e.endsWith(".saffron");if(/^\s*StepSet\s+/.test(t)&&s)return r.stepSets.map(a=>({label:a.name,kind:Pt.Function,detail:`step set \xB7 ${a.steps.length} step(s) \xB7 \xD7${a.usage}`,documentation:a.steps.join(`
|
|
286
|
+
`)}));if(/^\s*(Given|When|Then|And|But|\*)\s+/.test(t))return r.steps.map((a,c)=>({label:a.text,kind:Pt.Text,detail:`${ei[a.status]} \xB7 \xD7${a.usage}`,sortText:String(c).padStart(5,"0"),filterText:a.text}));let i=t.replace(/^\s*/,"").trimEnd().toLowerCase().replace(/\s+/g,"");if(i.length>0&&("stepset:".startsWith(i)||i.startsWith("stepset"))&&s){let a={start:{line:n,character:t.length-t.replace(/^\s*/,"").length},end:{line:n,character:t.length}},c=[{label:"StepSet: \u2026",kind:Pt.Keyword,detail:"define a reusable step set",documentation:`StepSet: Name
|
|
283
287
|
Given \u2026
|
|
284
288
|
When \u2026
|
|
285
289
|
|
|
286
|
-
Invoke it anywhere with: StepSet Name`,filterText:"step set stepset:",sortText:"0",insertTextFormat:
|
|
287
|
-
`),filterText:`step set ${l.name}`,sortText:`1${l.name}`,textEdit:{range:a,newText:`StepSet ${l.name}`}});return c}return[]}import
|
|
290
|
+
Invoke it anywhere with: StepSet Name`,filterText:"step set stepset:",sortText:"0",insertTextFormat:hl.Snippet,textEdit:{range:a,newText:"StepSet: ${1:Name}\n "}}];r.stepSets.length===0&&c.push({label:"StepSet \u2026",kind:Pt.Keyword,detail:"invoke a step set (none defined yet)",filterText:"step set stepset",sortText:"1",insertTextFormat:hl.Snippet,textEdit:{range:a,newText:"StepSet ${1:Name}"}});for(let l of r.stepSets)c.push({label:`StepSet ${l.name}`,kind:Pt.Function,detail:`invoke step set \xB7 ${l.steps.length} step(s)`,documentation:l.steps.join(`
|
|
291
|
+
`),filterText:`step set ${l.name}`,sortText:`1${l.name}`,textEdit:{range:a,newText:`StepSet ${l.name}`}});return c}return[]}import $n from"node:fs";import fh from"node:net";import jt from"node:path";import{chromium as ph,firefox as uh,webkit as gh}from"playwright";import Vg from"node:path";var Gg=5e3,Kg=new Set(["click","press","selectOption","check","uncheck","hover","dragTo"]);function Al(e){return e.mode==="heal"||e.mode==="refine"}function _l(e){return e.mode==="heal"||e.mode==="refine"?e.failedStep?.stepIndex??e.completedSteps?.length??0:e.recordOnly?e.recordOnly.from:e.completedSteps?.length??0}var Rl=e=>`${e} action${e===1?"":"s"}`,Tl=e=>e.map(Me).join("; "),rs=class{firstStep;discardBeforeAnnounce;preAnnounce=[];discarded=[];carried;pendingTabOpen=!1;pendingTabFallback;lastOpener;lastOpenerAt=0;inFlight=new Set;steps;currentStepIndex=-1;done=!1;success=!1;narrative="";adaptations=[];suggestedFeatureEdit;featureEdits=[];announced=new Set;pendingFingerprint;constructor(t,n={}){this.firstStep=Math.max(n.firstStep??0,0),this.discardBeforeAnnounce=n.discardBeforeAnnounce??!1,this.steps=t.steps.map(r=>({gherkin:r.text,keyword:r.keyword,kind:r.kind,table:r.table,docString:r.docString,fromStepSet:r.source?.fromStepSet,actions:[]}))}addArmedAction(t){if(this.done)return;let n=this.destination();if(!n){this.discard([t],this.refusalReason());return}if(n.some(o=>o.action===t.action&&o.value===t.value&&o.promptText===t.promptText))return;let s=Math.max(n.length-1,0);n.splice(s,0,t)}destination(){if(this.currentStepIndex<0)return this.discardBeforeAnnounce?void 0:this.firstStep===0?this.steps[0]?.actions:this.preAnnounce;if(!(this.currentStepIndex<this.firstStep))return this.steps[this.currentStepIndex]?.actions}refusalReason(){let t=this.currentStepIndex;return t<0?`before announcing the failed step (step ${this.firstStep+1}); a heal records nothing until it announces that step, so this exploration was not filed under any step`:`under step ${t+1} ("${this.steps[t]?.gherkin??""}"), which had already run before the agent took over, so its recording was kept`}discard(t,n){if(t.length===0)return;let r=this.discarded.find(s=>s.why===n);r?r.actions.push(...t):this.discarded.push({actions:[...t],why:n})}announce(t,n,r){if(this.currentStepIndex=t,this.announced.add(t),r){let o=`Step ${t+1} (`;this.adaptations=this.adaptations.filter(i=>!i.startsWith(o)),this.adaptations.push(`${o}"${n}"): ${r}`)}let s=this.steps[t];this.preAnnounce.length>0&&t>=this.firstStep&&s&&(s.actions.unshift(...this.preAnnounce),this.carried={index:t,actions:this.preAnnounce},this.preAnnounce=[])}attributionNotes(){let t=[];if(this.carried){let{index:r,actions:s}=this.carried;t.push(`recording: ${Rl(s.length)} the agent performed before announcing a step ${s.length===1?"was":"were"} filed under step ${r+1} ("${this.steps[r]?.gherkin??""}"), the first step it recorded: ${Tl(s)}.`)}let n=this.preAnnounce.length>0?[{actions:this.preAnnounce,why:"before announcing a step this session records"}]:[];for(let{actions:r,why:s}of[...this.discarded,...n])t.push(`recording: discarded ${Rl(r.length)} the agent performed ${s}: ${Tl(r)}.`);return t}beginToolCall(t){this.inFlight.add(t)}endToolCall(t,n){this.inFlight.delete(t)&&(this.pendingTabOpen&&n&&(this.pendingTabFallback=void 0),this.inFlight.size===0&&this.pendingTabOpen&&(this.pendingTabFallback&&(this.pendingTabFallback.opensTab=!0),this.pendingTabOpen=!1,this.pendingTabFallback=void 0))}markTabOpened(){let t=this.inFlight.size===0,n=Date.now()-this.lastOpenerAt<=Gg;if(t){this.lastOpener&&n&&(this.lastOpener.opensTab=!0);return}this.pendingTabOpen=!0,this.pendingTabFallback=n?this.lastOpener:void 0}addActions(t){if(this.done||t.length===0)return;if(this.currentStepIndex<0&&this.firstStep>0&&!this.discardBeforeAnnounce){let s=t.filter(o=>o.action==="switchTab");if(this.discard(s,"before announcing its first step (replay is already on the live page when the agent takes over)"),t=t.filter(o=>o.action!=="switchTab"),t.length===0)return}let n=this.destination();if(!n){this.pendingFingerprint=void 0,this.discard(t,this.refusalReason());return}this.pendingFingerprint&&t[0]&&(t[0].pageFingerprint=this.pendingFingerprint,this.pendingFingerprint=void 0),n.push(...t);let r=[...t].reverse().find(s=>Kg.has(s.action));r&&(this.lastOpener=r,this.lastOpenerAt=Date.now(),this.pendingTabOpen&&(r.opensTab=!0,this.pendingTabOpen=!1,this.pendingTabFallback=void 0))}},ot=e=>e.replace(/\\(['"\\])/g,"$1");function Yg(e){let t=e.match(/'((?:[^'\\]|\\.)*)'/);return t?ot(t[1]):void 0}function Zg(e){let t=[],n=0;for(;n<e.length;){let r=/^\.?([A-Za-z]+)\(/.exec(e.slice(n));if(!r)return;let s=n+r[0].length,o=s,i=1,a;for(;s<e.length&&i>0;s++){let c=e[s];if(a)c==="\\"?s++:c===a&&(a=void 0);else if(c==="'"||c==='"'||c==="`")a=c;else if(c==="/"&&/[(,:]\s*$/.test(e.slice(o-1,s)))for(s++;s<e.length&&e[s]!=="/";s++)e[s]==="\\"&&s++;else c==="("||c==="{"||c==="["?i++:(c===")"||c==="}"||c==="]")&&i--}if(i!==0)return;t.push({method:r[1],args:e.slice(o,s-1)}),n=s}return t}function ti(e,t){let n=/^'((?:[^'\\]|\\.)*)'$/.exec(e.trim());if(n)return`${JSON.stringify(ot(n[1]))}${t?"s":"i"}`;let r=/^\/((?:[^/\\]|\\.)*)\/([a-z]*)$/.exec(e.trim());if(!r)return;let s=Fs(r[1]);return s!==r[1]&&/[uv]/.test(r[2])?void 0:`/${s}/${r[2]}`}var Qg=new Set(["checked","disabled","selected","expanded","includeHidden","level","pressed","busy"]);function El(e,t){let n=/exact:\s*true/.test(t),r=/^\s*('(?:[^'\\]|\\.)*'|\/(?:[^/\\]|\\.)*\/[a-z]*)/.exec(t)?.[1];switch(e){case"locator":{let s=/^\s*'((?:[^'\\]|\\.)*)'\s*$/.exec(t);return s?ot(s[1]):void 0}case"getByRole":{let s=/^\s*'([^']+)'/.exec(t)?.[1];if(!s)return;let o="";for(let[,i,a]of t.matchAll(/(\w+):\s*('(?:[^'\\]|\\.)*'|\/(?:[^/\\]|\\.)*\/[a-z]*|[^,}\s]+)/g))if(i==="name"||i==="description"){let c=ti(a,n);if(c===void 0)return;o+=`[${i}=${c}]`}else if(Qg.has(i))o+=`[${i==="includeHidden"?"include-hidden":i}=${a.replace(/^'(.*)'$/,"$1")}]`;else if(i!=="exact")return;return`internal:role=${s}${o}`}case"getByText":case"getByLabel":case"getByPlaceholder":case"getByAltText":case"getByTitle":{let s=r===void 0?void 0:ti(r,n);return s===void 0?void 0:e==="getByText"?`internal:text=${s}`:e==="getByLabel"?`internal:label=${s}`:`internal:attr=[${{getByPlaceholder:"placeholder",getByAltText:"alt",getByTitle:"title"}[e]}=${s}]`}case"getByTestId":{let s=r&&/^'/.test(r)?ot(r.slice(1,-1)):void 0;return s===void 0?void 0:`internal:testid=[data-testid=${JSON.stringify(s)}s]`}case"first":return"nth=0";case"last":return"nth=-1";case"nth":return/^\s*-?\d+\s*$/.test(t)?`nth=${t.trim()}`:void 0;case"filter":{let s=/hasText:\s*('(?:[^'\\]|\\.)*'|\/(?:[^/\\]|\\.)*\/[a-z]*)/.exec(t);if(!s||!/^\s*\{\s*\}\s*$/.test(t.replace(s[0],"")))return;let o=ti(s[1],!1);return o===void 0?void 0:`internal:has-text=${o}`}default:return}}function Xg({method:e,args:t}){let n=String.raw`'(?:[^'\\]|\\.)*'`;return e==="getByRole"?new RegExp(String.raw`^\s*'[^']+'\s*(?:,\s*\{\s*(?:name:\s*${n}\s*(?:,\s*exact:\s*true\s*)?)?\}\s*)?$`).test(t):["getByText","getByLabel","getByPlaceholder","getByTestId","locator"].includes(e)&&new RegExp(String.raw`^\s*${n}\s*$`).test(t)}function ni(e){let t={},n=e.match(/(?:frameLocator\('((?:[^'\\]|\\.)*)'\)|locator\('((?:[^'\\]|\\.)*)'\)\.contentFrame\(\))/);n&&(t.frame=ot(n[1]??n[2]),e=e.slice((n.index??0)+n[0].length));let r=Zg(e.replace(/^\./,"")),s=r?.filter((c,l)=>!(c.method==="first"&&l===r.length-1));if(s&&s.length>1){let c=s.map(l=>El(l.method,l.args));return c.some(l=>l===void 0)?void 0:{...t,fallbackSelectors:[c.join(" >> ")]}}if(s?.length===1&&!Xg(s[0])){let c=El(s[0].method,s[0].args);return c===void 0?void 0:{...t,fallbackSelectors:[c]}}let o=e.match(/getByRole\('([^']+)'(?:,\s*\{([^}]*)\})?\)/);if(o){t.role=o[1];let c=(o[2]??"").match(/name:\s*'((?:[^'\\]|\\.)*)'/);c&&(t.name=ot(c[1]))}let i=[[/getByLabel\('((?:[^'\\]|\\.)*)'\)/,"label"],[/getByText\('((?:[^'\\]|\\.)*)'\)/,"text"],[/getByTestId\('((?:[^'\\]|\\.)*)'\)/,"testId"],[/getByPlaceholder\('((?:[^'\\]|\\.)*)'\)/,"placeholder"]];for(let[c,l]of i){let d=e.match(c);d&&(t[l]=ot(d[1]))}let a=e.match(/(?:^|\.)locator\('((?:[^'\\]|\\.)*)'\)/);return a&&(t.fallbackSelectors=[ot(a[1])]),Object.keys(t).length>0?t:void 0}var eh={click:"click",dblclick:"click",fill:"fill",pressSequentially:"fill",type:"fill",press:"press",check:"check",uncheck:"uncheck",hover:"hover",selectOption:"selectOption"};function th(e,t){let n=e.match(/page\.goto\('((?:[^'\\]|\\.)*)'\)/);if(n)return{action:"goto",url:Nn(ot(n[1]),t)};let r=e.match(/page\.keyboard\.press\('((?:[^'\\]|\\.)*)'\)/);if(r)return{action:"press",value:ot(r[1])};let s=e.match(/await\s+page\.(.+)\.dragTo\(page\.(.+?)\);?\s*$/);if(s){let u=ni(s[1]),f=ni(s[2]);if(u&&f)return{action:"dragTo",target:u,toTarget:f}}let o=e.match(/await\s+page\.(.+)\.(click|dblclick|fill|pressSequentially|type|press|check|uncheck|hover|selectOption)\((.*)\);?\s*$/);if(!o)return;let[,i,a,c]=o,l=ni(i);if(!l)return;let d={action:eh[a],target:l},p=Yg(c);return p!==void 0&&a!=="click"&&a!=="dblclick"&&(d.value=p),d}function Il(e){let t=Array.isArray(e)?e:e?.content,n=typeof e=="string"?[e]:Array.isArray(t)?t.flatMap(r=>typeof r?.text=="string"?[r.text]:[]):[];for(let r of n){let s=r.split(/^### Open tabs\r?$/m)[1]?.split(/^### /m)[0];if(!s)continue;let o=/^- (\d+): \(current\) /m.exec(s)?.[1];if(o!==void 0)return Number(o)}}function Cl(e,t){let n=[],r=Array.isArray(e)?e:e?.content;if(Array.isArray(r))for(let o of r){let i=o?.text;typeof i=="string"&&n.push(i)}else typeof e=="string"&&n.push(e);let s=[];for(let o of n){let i=o.split(/^### Ran Playwright code[ \t\r]*$/m).slice(1).map(a=>a.split(/^### /m)[0]).join(`
|
|
288
292
|
`);for(let a of i.split(`
|
|
289
|
-
`)){let c=
|
|
290
|
-
`)}}}function
|
|
291
|
-
`):void 0,featureEdits:u,recordedSteps:c,announcedSteps
|
|
292
|
-
Install it (npx playwright install ${t} does that), or use --browser chromium, which Saffron ships with.`):r}this.cdpEndpoint=`http://127.0.0.1:${n}`}else this.browser=await(t==="firefox"?
|
|
293
|
-
`)[0]})`:"")+". A row value is probably baked in as a literal instead of a <placeholder>; inspect the proposal, reject it, and re-record with saffron run --rerecord."}}console.log(` \u21BA pending proposal for "${t.displayName}" did not replay`+(
|
|
294
|
-
`)[0]})`:"")+"; recording again"),await
|
|
295
|
-
`)[0]})`:"")+(
|
|
296
|
-
`)[0]}`}}if(
|
|
297
|
-
`)[0]}`,lr=A.failure.stepIndex,Ai=A.stepResults.map((Gt,vs)=>vs===lr?{...Gt,status:"failed",error:qe}:Gt);return{scenario:t,status:"red",source:"agent-heal",stepResults:Ai,executionStepResults:Ai.map((Gt,vs)=>vs>lr&&Gt.status==="skipped"?{...Gt,status:"passed"}:Gt),narrative:P.narrative,adaptations:P.adaptations,suggestedFeatureEdit:P.suggestedFeatureEdit,usage:P.usage,durationMs:Date.now()-r,error:qe}}finally{E?.detach()}}return E?.detach(),await this.finalizeAgentRun(t,P,B,d,r,N,B?A?.failure:void 0,g)})(),I=R.find(A=>A.kind==="before-heal");if(_.source==="cache"&&I){let A=I.file.replace(/before-heal\.jpg$/,"failure.jpg");try{hn.renameSync(_t.join(s,I.file),_t.join(s,A)),I.file=A}catch{}I.kind="failure"}else if(_.status==="red"){let A=_.stepResults.find(B=>B.status==="failed")?.gherkin,H=await this.screenshot(mn(this.browser)??w,t,"failure",A);H&&R.push(H)}let j=pn(_e(t),g);if(j.size>0&&(_.uniques=Object.fromEntries(j)),R.push(..._.evidence??[]),$){let A=x==="on"||_.status!=="green",H=Ge(s,t.featurePath,t.displayName),B=A?_t.join(H,Zs):void 0;h=!0;let N=m??S;B||await Xs(N).catch(()=>{});let P=B?await eo(N,B,We(t)):void 0;if(B&&P){this.claimArtifactDir(t);let E=We(t);R.unshift({kind:"trace",file:me(s,B),sha256:P,traceSteps:(_.executionStepResults??_.stepResults).map(O=>({...O,error:O.error&&it(O.error,E)}))})}}return R.length>0&&(_.status!=="green"||R.some(A=>A.kind==="trace"))&&(_.evidence=R),_}finally{h||await Xs(S).catch(()=>{}),await m?.close(),await S.close()}}async finalizeAgentRun(t,n,r,s,o,i=0,a,c=St()){let l=r?"agent-heal":"agent-record",d=n.success?n.recordedSteps.map(P=>({gherkin:P.gherkin,kind:P.kind,status:"passed"})):vl(n.recordedSteps,n.announcedSteps??[],a&&{stepIndex:a.stepIndex,error:a.error},n.narrative);if(!n.success)return{scenario:t,status:"red",source:l,stepResults:d,narrative:n.narrative,adaptations:n.adaptations,usage:n.usage,durationMs:Date.now()-o,error:n.narrative};let p=r?hl(s.steps,n.recordedSteps,this.options.assertionPolicy==="adaptable-mid",a?{stepIndex:a.stepIndex,actionIndex:a.actionIndex}:void 0):n.recordedSteps,u=[...n.adaptations,...r&&a?ml(n.recordedSteps,a.stepIndex):[]],f={...n.usage},y,b,k,T,v=[],S=0,x=new Set,$,h=async(P,E,O=E.stepResults)=>{if(!x.has(P)){x.add(P);try{if(this.options.trace&&this.options.trace!=="off"){let M=_t.join(Ge(this.options.projectRoot,t.featurePath,t.displayName),`proof-${++S}.zip`),U=We(t),X=await eo(P,M,U);if(X){this.claimArtifactDir(t);let He=E.captured[Fe],ht=He?pn(_e(t),He):new Map;v.push({kind:"trace",proof:!0,file:me(this.options.projectRoot,M),sha256:X,traceSteps:O.map(qe=>({...qe,error:qe.error&&it(qe.error,U)})),traceUniques:ht.size?Object.fromEntries(ht):void 0})}}}finally{await P.close()}}};if(this.options.verifyProposals!==!1){let P=await this.proofReplay(t,this.buildCandidateCache(t,p),St());T=P.result.captured[Fe];try{if(P.result.status!=="passed"&&P.result.failure){let E=P.result.failure;if(this.options.agent&&!(r&&E.kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||gl(s.steps,E.stepIndex))))try{let M=await Gr(this.browser,P.result.activePage??Wn(P.page.context(),E.pageUrl)??P.page),U=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:this.options.baseURL,traceContext:this.options.trace&&this.options.trace!=="off"?P.context:void 0,mode:"refine",model:r?this.options.healModel:void 0,cdpEndpoint:this.cdpEndpoint,projectRoot:this.options.projectRoot,assertionPolicy:this.options.assertionPolicy,completedSteps:P.result.stepResults.filter(X=>X.status==="passed").map(X=>X.gherkin),failedStep:{text:E.stepText,kind:E.kind,error:E.error,pageUrl:E.pageUrl,stepIndex:E.stepIndex},liveTab:M,uniqueSeed:P.result.captured[Fe],onTabOpened:this.tabWatcher(),takeFingerprint:async()=>Lt(mn(this.browser)??P.page)}));f=yl(f,U.usage),$=Ug(P.result.stepResults,E,U),U.success&&(u.push(...U.adaptations),u.push(...ml(U.recordedSteps,E.stepIndex)),p=r?hl(p,U.recordedSteps,this.options.assertionPolicy==="adaptable-mid",{stepIndex:E.stepIndex,actionIndex:0}):Bg(p,U.recordedSteps,E.stepIndex),await h(P.context,P.result,$),$=void 0,P=await this.proofReplay(t,this.buildCandidateCache(t,p),St()),T=P.result.captured[Fe])}catch{}}for(let E of P.result.tabOpeners??[]){let O=p[E.stepIndex]?.actions[E.actionIndex];O&&(O.opensTab=!0)}y=P.result.status==="passed",y||(b=P.result.failure?.error??`proof replay ${P.result.status}`,k=P.result.stepResults)}finally{await h(P.context,P.result,$).catch(()=>{})}}r&&s&&u.push(...Lg(s.steps,p,a,this.options.baseURL));let m=[...n.featureEdits];for(let P of Yi(p,Ke(this.options.projectRoot)))u.push(`duplicate wording: "${P.from}" recorded exactly the same actions as the existing step "${P.to}" (${P.feature} \u203A ${P.scenario}). Accept with --with-feature-edit to converge on the canonical wording.`),m.some(E=>E.index===P.index)||m.push({index:P.index,text:P.to});let w=ll(p);w.length>0&&(y=!1,b=[b,...w].filter(Boolean).join(" "));let g=We(t),R=P=>g.size>0?it(P,g):P;u=u.map(R);let C=m.map(P=>({index:P.index,text:R(P.text)})),_=R(n.narrative),I=n.suggestedFeatureEdit?R(n.suggestedFeatureEdit):void 0,j={version:1,feature:t.featurePath,scenario:t.name,recordedAt:new Date().toISOString(),recordedBy:"agent",steps:p,...ul(t)},A={meta:{createdAt:j.recordedAt,mode:r?"heal":"record",narrative:_,adaptations:u,suggestedFeatureEdit:I,featureEdits:C.length>0?C:void 0,verified:y,proofError:b?R(b):void 0,seededSteps:i>0?i:void 0,recordedFor:t.displayName,usage:f,bound:nc(t,s,j,C.length>0?C:void 0)},cache:j},H=Ce(this.options.projectRoot,t.featurePath,t.name),B=na(H,A);ia(this.options.projectRoot,H,B);let N=Re(ee(this.options.projectRoot,t.featurePath,t.name));return{proposalDiff:$t(N,A.cache),scenario:t,status:"yellow",source:l,stepResults:k??d,executionStepResults:d,evidence:v,proofUniques:(()=>{let P=T?pn(_e(t),T):void 0;return P&&P.size>0?Object.fromEntries(P):void 0})(),narrative:_,adaptations:u,suggestedFeatureEdit:I,featureEdits:C.length>0?C:void 0,verified:y,proofError:b,seededSteps:i>0?i:void 0,proposalFile:me(this.options.projectRoot,H),proposalRevision:B,usage:f,durationMs:Date.now()-o}}};import ls from"node:fs";import Bh from"node:os";import Gl from"node:path";import{query as fh}from"@anthropic-ai/claude-agent-sdk";import{McpServer as zg}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as V}from"zod";var ye=e=>({content:[{type:"text",text:e}]});function yn(e,t,n,r){let s=async o=>{let i=await r(o);return i.content[0]?.text.startsWith("ERROR:")?{...i,isError:!0}:i};return o=>{o.registerTool(e,{description:t,inputSchema:n},s)}}function Hg(e){let t=new zg({name:e.name,version:e.version});for(let n of e.tools)n(t);return{type:"sdk",name:e.name,instance:t}}function Sl(e){let t={};return e.role&&(t.role=e.role),e.name&&(t.name=e.name),e.nameRegex&&(t.nameRegex=e.nameRegex),e.label&&(t.label=e.label),e.text&&(t.text=e.text),e.selector&&(t.fallbackSelectors=[e.selector]),e.frame&&(t.frame=e.frame),Object.keys(t).length>0?t:void 0}var qg=new Set(["main","banner","contentinfo","status","alert","alertdialog","dialog","search"]);function xl(e){if(!e?.role)return;let{role:t,frame:n,...r}=e;if(!(Object.keys(r).length>0||qg.has(t)))return`ERROR: role="${t}" alone matches every ${t} on the page, and replay would use the first one. Add a name (or nameRegex), text, label or selector that picks exactly the element you checked, then call again.`}function Jg(e,t){return t.index>=e.steps.length?`ERROR: there is no step ${t.index}: this scenario's steps are numbered from 0 to ${e.steps.length-1}. Call saffron_step again with the zero-based index of the step you are about to perform.`:(e.announce(t.index,t.text,t.adaptation),t.index<e.firstStep?`Step ${t.index} already ran before you took over and keeps its recording; nothing you do under it is recorded. Do not redo it: continue from step ${e.firstStep} on the page as it is.`:`Recording step ${t.index}: ${t.text}`)}var $l=new WeakSet;function Vg(e,t){if(t.success&&!$l.has(e)){let n=[...e.announced].filter(r=>r>=e.firstStep&&e.steps[r]?.kind==="assertion"&&!e.steps[r].actions.some(s=>Ie.has(s.action))).sort((r,s)=>r-s);if(n.length>0)return $l.add(e),`ERROR: not finalized. Assertion step ${n.join(", ")} recorded no check, so replay would verify nothing. Record what you verified with saffron_assert under that step (saffron_step first if you moved on), then call saffron_done again. If the condition does not hold, call saffron_done with success=false.`}return e.done=!0,e.success=t.success,e.narrative=t.narrative,e.suggestedFeatureEdit=t.suggestedFeatureEdit,e.featureEdits=(t.featureEdits??[]).filter(n=>!Is.test(n.text)),"Run finalized."}var kl={role:V.string().optional().describe("ARIA role of the element"),name:V.string().optional().describe("Accessible name \u2014 use the SHORTEST stable substring; never include volatile content like prices or dates"),nameRegex:V.string().optional().describe("Regex for the accessible name when it embeds volatile content, e.g. 'Select \\\\{date\\\\+1\\\\} as checkin' cannot work \u2014 instead use nameRegex 'Select .* as checkin'"),label:V.string().optional().describe("Form-label text for getByLabel \u2014 the literal <label> text only, never a free-text description"),text:V.string().optional().describe("getByText locator text"),selector:V.string().optional().describe("CSS fallback selector"),frame:V.string().optional().describe(`CSS selector of the iframe hosting the element, e.g. 'iframe[title="Feedback widget"]' \u2014 REQUIRED whenever the element lives inside an iframe; without it replay looks only at the top-level page`)};function Yr(e){return Hg({name:"saffron",version:"0.1.0",tools:[yn("saffron_step","Announce the Gherkin step you are about to perform. MUST be called before executing browser actions for each step, with the step's zero-based index and exact text.",{index:V.number().int().min(0),text:V.string(),adaptation:V.string().optional().describe("If the written step does not match the real UI and you are deviating from it, describe the deviation in one sentence: the kind of change (a locator or label change on the same page, a page removed or merged, a page added or flow reordered) and the page it happened on.")},async t=>ye(Jg(e,t))),yn("saffron_capture",`Record a captureText action for the current step: at replay time, the target element's text is read and stored under saveAs for later expectDiffers comparisons. Use for steps like 'I record the displayed price as "X"'. The target must select exactly the element whose text is the value.`,{saveAs:V.string().describe("Name to store the captured text under"),...kl},async t=>{let n=Sl(t);if(!n)return ye("ERROR: capture needs a target (role/name, nameRegex, label, text, or selector).");let r=xl(n);return r?ye(r):(e.addActions([{action:"captureText",target:n,saveAs:t.saveAs}]),ye(`Capture recorded as "${t.saveAs}".`))}),yn("saffron_dialog","Record how a native dialog (alert/confirm/prompt) must be handled at replay. Call this IMMEDIATELY whenever an action triggers a native dialog \u2014 whether you handled it via browser_handle_dialog or the browser reported it as already handled. At replay Saffron arms this handler BEFORE the triggering action, so without this call the replay will auto-dismiss the dialog and diverge from what you saw.",{accept:V.boolean().describe("true = accept/OK the dialog, false = dismiss/cancel"),promptText:V.string().optional().describe("Text typed into a prompt() before accepting")},async t=>(e.addArmedAction({action:"handleDialog",value:t.accept?"accept":"dismiss",...t.promptText?{promptText:t.promptText}:{}}),ye(`Dialog handling recorded (${t.accept?"accept":"dismiss"}).`))),yn("saffron_wait_api","Record a network wait for the current step: replay will block until a matching API response is observed (responses from the triggering step count). Call AFTER you verified via browser_network_requests that the response actually occurred with the expected status/body. Use a path-only urlPattern regex and never literal volatile IDs (/api/orders/\\d+, not /api/orders/8842).",{urlPattern:V.string().describe("Regex matched against the response URL \u2014 path-only for portability"),method:V.string().optional().describe("HTTP method to match (any if omitted)"),status:V.string().optional().describe("Expected status \u2014 exact ('201') or class ('2xx'); default any 2xx"),bodyPattern:V.string().optional().describe(`Regex the response body must match, e.g. '"status"\\s*:\\s*"READY"' for polling waits`)},async t=>(e.addActions([{action:"waitForResponse",urlPattern:t.urlPattern,...t.method?{method:t.method}:{},...t.status?{status:t.status}:{},...t.bodyPattern?{pattern:t.bodyPattern}:{}}]),ye("Network wait recorded."))),yn("saffron_assert","Record a verified assertion for the current Then step. Call ONLY after you have confirmed the condition holds via a page snapshot. If the condition does NOT hold, do not call this \u2014 call saffron_done with success=false instead. NEVER record volatile content (prices, dates, counters) as literal expected text \u2014 use kind=matches with a pattern, or kind=differs against captured values.",{kind:V.enum(["visible","notVisible","text","url","value","differs","matches","attribute","response","each"]),...kl,expected:V.string().optional().describe("Expected text/value for kind=text|value \u2014 stable text only, never volatile values"),url:V.string().optional().describe("URL substring for kind=url (path only, no host)"),pattern:V.string().optional().describe("kind=matches|attribute: regex the target's text (or attribute) must match, e.g. 'NOK [\\\\d,]+' for a price"),attribute:V.string().optional().describe("kind=attribute: attribute name to check, e.g. 'href' for link-target assertions \u2014 use this for 'X should link to Y' instead of clicking through"),capture:V.string().optional().describe("kind=differs: name of the captured value on the LEFT of the comparison (omit when comparing the target element's live text)"),urlPattern:V.string().optional().describe("kind=response: regex matched against the response URL \u2014 path-only for portability, never literal volatile IDs (use /api/orders/\\d+)"),method:V.string().optional().describe("kind=response: HTTP method to match (any if omitted)"),status:V.string().optional().describe("kind=response: expected status \u2014 exact ('201') or class ('2xx'); default any 2xx"),bodyPattern:V.string().optional().describe("kind=response: regex the response body must match (verify via browser_network_requests first)"),each:V.string().optional().describe("kind=each: the data-list token exactly as the step writes it, e.g. '{data:enums.OrderStatus}'. The target is the CONTAINER (dropdown, table, list) that must show every value of that list. Never pass the values themselves."),compareTo:V.string().optional().describe("kind=differs: name of the captured value to compare against")},async t=>{let n=Sl(t),r=xl(n);if(r)return ye(r);let s;switch(t.kind){case"visible":s={action:"expectVisible",target:n};break;case"notVisible":s={action:"expectNotVisible",target:n};break;case"text":s={action:"expectText",target:n,value:t.expected??""};break;case"value":s={action:"expectValue",target:n,value:t.expected??""};break;case"url":s={action:"expectUrl",url:t.url??""};break;case"differs":if(!t.compareTo)return ye("ERROR: kind=differs requires compareTo.");if(!t.capture&&!n)return ye("ERROR: kind=differs needs either capture (a stored name) or a target element.");s={action:"expectDiffers",target:n,value:t.capture,compareTo:t.compareTo};break;case"matches":if(!t.pattern)return ye("ERROR: kind=matches requires pattern.");s={action:"expectMatches",target:n,pattern:t.pattern};break;case"attribute":if(!t.attribute||!t.pattern)return ye("ERROR: kind=attribute requires attribute and pattern.");s={action:"expectAttribute",target:n,attribute:t.attribute,pattern:t.pattern};break;case"each":if(!t.each||!/^\{data:[^}]+\}$/.test(t.each))return ye("ERROR: kind=each requires each='{data:file.list}', the token exactly as the step writes it (not the values).");s={action:"expectEach",target:n,each:t.each};break;case"response":if(!t.urlPattern)return ye("ERROR: kind=response requires urlPattern.");s={action:"expectResponse",urlPattern:t.urlPattern,...t.method?{method:t.method}:{},...t.status?{status:t.status}:{},...t.bodyPattern?{pattern:t.bodyPattern}:{}};break}return!["url","differs","response"].includes(t.kind)&&!n?ye("ERROR: assertion needs a target (role/name, nameRegex, label, text, or selector)."):(e.addActions([s]),ye("Assertion recorded."))}),yn("saffron_done","Finalize the run. Call exactly once, after the final step: success=true only if every step's intent was achieved and every assertion verified.",{success:V.boolean(),narrative:V.string().describe("2-4 sentence summary of the run: what happened, and why it failed if it did. After a heal, say what kind of change the app went through (a locator change, or a page removed, merged, added or reordered) and on which page."),suggestedFeatureEdit:V.string().optional().describe("If you adapted any steps: the corrected Gherkin for those steps, as you would rewrite them in the .feature file (free text, for the human report)."),featureEdits:V.array(V.object({index:V.number().int().min(0).describe("zero-based step index"),text:V.string().describe("replacement step text WITHOUT the Given/When/Then keyword")})).optional().describe("Machine-applicable version of the suggested edits: one entry per adapted step. Provide this whenever you adapted a step.")},async t=>ye(Vg(e,t)))]})}function Qr(e={}){let t=e.deliberateSnapshots?`
|
|
293
|
+
`)){let c=th(a.trim(),t);c&&s.push(c)}}return nh(s)}function nh(e){return e.filter((t,n)=>{let r=e[n+1];return!(t.action==="fill"&&(t.value??"")===""&&r?.action==="fill"&&JSON.stringify(r.target)===JSON.stringify(t.target))})}function Pl(e){let t=[];for(let n of e){if(n.kind==="assertion"&&n.actions.length===0){t.push(`Step "${n.gherkin}" is an assertion but recorded no check, so nothing would be verified. Re-record with: saffron run --rerecord`);continue}if(/"[^"]+"|<[^<>]+>/.test(n.gherkin)){for(let s of n.actions)if(s.action==="fill"&&(s.value??"")===""){t.push(`Step "${n.gherkin}" recorded a fill with an empty value although the step passes one; the typed value was lost. Re-record with: saffron run --rerecord`);break}}}return t}function Ot(e,t,n=s=>s,r=!1){let s=e;for(let[o,i]of Object.entries(t).filter(([,a])=>a.length>=3).sort((a,c)=>c[1].length-a[1].length)){let a=n(i);if(!r){s=s.split(a).join(`<${o}>`);continue}if(i.length<5&&!/\p{N}/u.test(i)){s===a&&(s=`<${o}>`);continue}let c=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");s=s.replace(new RegExp(`(?<![\\p{L}\\p{N}])${c}(?![\\p{L}\\p{N}])`,"gu"),()=>`<${o}>`)}return s}function rh(e,t){let n=Object.entries(t).filter(([,l])=>l.length>=3);if(n.length===0)return e;let r=l=>l===void 0?void 0:Ot(l,t),s=[...n].sort((l,d)=>d[1].length-l[1].length),o=l=>{if(l!==void 0){for(let[d,p]of s)if(l.includes(p))return`<${d}>`;return l}},i=l=>l===void 0?void 0:Ot(l,t,we.pattern),a=l=>l===void 0?void 0:Ot(l,t,void 0,!0),c=(l,d)=>l?{...l,name:d?o(l.name):r(l.name),nameRegex:i(l.nameRegex),label:r(l.label),text:d?o(l.text):r(l.text),placeholder:r(l.placeholder),testId:a(l.testId),frame:a(l.frame),fallbackSelectors:l.fallbackSelectors?.map(p=>ln(p,(u,f)=>Ot(u,t,we[f])))}:void 0;return e.map(l=>({...l,actions:l.actions.map(d=>{let p=Ne.has(d.action)&&d.action!=="expectValue";return{...d,value:p?o(d.value):r(d.value),url:r(d.url),pattern:i(d.pattern),urlPattern:i(d.urlPattern),promptText:r(d.promptText),target:c(d.target,p),toTarget:c(d.toTarget,!1)}})}))}function sh(e,t,n=r=>r){let r=St(t.steps);return e.map((s,o)=>{let i=t.steps[o],a=i?.resolvedTable??i?.table,c=i?.resolvedDocString??i?.docString,l=Object.entries({...r,...ke(a),...Bt(c)}).map(([u,f])=>[u,n(f)]).filter(([,u])=>u.length>=3).sort((u,f)=>f[1].length-u[1].length);if(l.length===0)return s;let d=(u,f=w=>w,h=!1)=>u===void 0?void 0:Ot(u,Object.fromEntries(l),f,h),p=u=>u?{...u,name:d(u.name),nameRegex:d(u.nameRegex,we.pattern),label:d(u.label),text:d(u.text),placeholder:d(u.placeholder),testId:d(u.testId,void 0,!0),frame:d(u.frame,void 0,!0),fallbackSelectors:u.fallbackSelectors?.map(f=>ln(f,(h,w)=>d(h,we[w])??h))}:void 0;return{...s,actions:s.actions.map(u=>({...u,value:d(u.value),url:d(u.url),pattern:d(u.pattern,we.pattern),urlPattern:d(u.urlPattern,we.pattern),promptText:d(u.promptText),target:p(u.target),toTarget:p(u.toTarget)}))}})}function oh(e,t=new Date){return e.map(n=>({...n,actions:n.actions.map(r=>tr(r,s=>_a(s,t)))}))}function tr(e,t,n){let r=(a,c,l=t)=>{let d={...a};for(let p of c)typeof a[p]=="string"&&(d[p]=l(a[p]));return d},s=a=>n?n(a,"pattern"):t(a),o=a=>{let c=r(r(a,["name","label","text","placeholder","testId","frame"]),["nameRegex"],s);return a.fallbackSelectors&&(c.fallbackSelectors=a.fallbackSelectors.map(l=>n?ln(l,n,t):t(l))),c},i=r(r(e,["value","url","promptText"]),["pattern","urlPattern"],s);return e.target&&(i.target=o(e.target)),e.toTarget&&(i.toTarget=o(e.toTarget)),i}function ih(e,t){if(t.length===0)return e;let n=new Map(t.map(([o,i])=>[i,o])),r=[...n.keys()].sort((o,i)=>i.length-o.length).map(lt).join("|"),s=new RegExp(String.raw`(?<=^|[^A-Za-z0-9\\]|\\[A-Za-z])(?:${r})(?![A-Za-z0-9])`,"g");return e.split(/(\{(?:env|data|unique|date)[^{}]*\})/).map((o,i)=>i%2?o:o.replace(s,a=>`{env:${n.get(a)}}`)).join("")}function ah(e,t){let n=_e(t),r=ct(je(t)),s=new RegExp(`${an.source}|${sn.source}`,"g"),o=i=>i.replace(s,(a,c,l)=>(c!==void 0?n.has(c):r.has(l))?a:Gi(a));return e.map(i=>({...i,actions:i.actions.map(a=>tr(a,o))}))}function ch(e,t,n=[]){if(t.size===0)return e;let r=Ns(n,t),s=Dt(t,{standaloneBelow:6}),o=l=>s.mask(r(l)),i=[...t].filter(([,l])=>l.length>=Lt),a=l=>{let d=Ns(n,t,we[l]),p=Dt(new Map(i.filter(([,f])=>f.length>=6).map(([f,h])=>[f,we[l](h)]))),u=i.filter(([,f])=>f.length<6).map(([f,h])=>[f,we[l](h)]);return f=>o(ih(p.mask(d(f)),u))},c={quoted:a("quoted"),regex:a("regex"),pattern:a("pattern")};return e.map(l=>({...l,actions:l.actions.map(d=>tr(d,o,(p,u)=>c[u](p)))}))}function Ol(e,t,n=""){let r=je(t),s=ch(lh(dh(oh(rh(sh(ah(e,t),t,a=>vr(wn(a,n))),t.params)),Sr(r)),bn(r,n)),Ze(t),r),o=Object.fromEntries(Object.entries(t.params).filter(([,a])=>a.includes("{env:")));if(Object.keys(o).length===0)return s;let i=a=>Ot(a,o);return s.map(a=>({...a,actions:a.actions.map(c=>tr(c,i))}))}function lh(e,t){if(t.size===0)return e;let n=r=>typeof r=="string"?Pa(r,t):Array.isArray(r)?r.map(n):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([s,o])=>[s,s==="pageFingerprint"?o:n(o)])):r;return e.map(r=>({...r,actions:r.actions.map(s=>n(s))}))}function dh(e,t){return t.size===0?e:e.map(n=>{let r=new Set([...n.gherkin.matchAll(sn)].map(l=>l[1])),s=l=>Cs(l,t,r),o=l=>new Map([...t].filter(([,d])=>d.length>=4).map(([d,p])=>[d,we[l](p)])),i={quoted:o("quoted"),regex:o("regex"),pattern:o("pattern")},a=l=>l.split(/(\{(?:env|data|unique|date)[^{}]*\})/).map((d,p)=>p%2?d:s(d)).join(""),c=(l,d)=>a(Cs(l,i[d],r));return{...n,actions:n.actions.map(l=>tr(l,s,c))}})}function jl(e,t,n){if(e!=="mcp__playwright__browser_tabs")return;let r=t??{},s=typeof r.index=="number"?String(r.index):void 0;switch(r.action){case"select":return s===void 0?void 0:{action:"switchTab",value:s};case"close":return s===void 0?{action:"closeTab"}:{action:"closeTab",value:s};case"new":return typeof r.url=="string"&&r.url?{action:"newTab",url:Nn(r.url,n)}:{action:"newTab"};default:return}}function Nl(e,t){let n=t??{};if(e==="mcp__playwright__browser_handle_dialog"){let r={action:"handleDialog",value:n.accept?"accept":"dismiss"};return typeof n.promptText=="string"&&n.promptText&&(r.promptText=n.promptText),r}if(e==="mcp__playwright__browser_file_upload"){let r=Array.isArray(n.paths)?n.paths:[];if(r.length===0)return;let s=Ae().root+Vg.sep;return{action:"uploadFile",value:r.map(i=>typeof i=="string"&&i.startsWith(s)?i.slice(s.length):i).join(`
|
|
294
|
+
`)}}}function nr(e,t){let n=e.pages().filter(s=>!s.isClosed()),r=s=>[...n].reverse().find(s);return(t?r(s=>s.url()===t):void 0)??r(s=>s.url()!=="about:blank")??n.at(-1)}async function ss(e,t){let n=t.context();for(let s of e.contexts())if(s!==n)for(let o of s.pages())await o.close().catch(()=>{});await t.bringToFront().catch(()=>{});let r=n.pages().filter(s=>!s.isClosed());return{index:Math.max(r.indexOf(t),0),count:r.length,url:t.url()}}var si=["chromium","chrome","msedge","firefox","webkit"],ri={chrome:{label:"Google Chrome"},msedge:{label:"Microsoft Edge"}};function Ul(e){return si.includes(e)}var rr=class extends Error{},Nt={aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0};async function hh(){return new Promise((e,t)=>{let n=fh.createServer();n.listen(0,"127.0.0.1",()=>{let{port:r}=n.address();n.close(()=>e(r))}),n.on("error",t)})}function Fl(e){let t=Sr(je(e));return t.size>0?{data:Object.fromEntries([...t].sort(([n],[r])=>n.localeCompare(r)))}:{}}function kn(e){let t=e.contexts().flatMap(n=>n.pages());return[...t].reverse().find(n=>n.url()!=="about:blank")??t.at(-1)}function zl(e){let t=e.length;for(let n=e.length-1;n>=0&&e[n].kind==="assertion";n--)t=n;return t}function Ml(e,t){return e[t]?.kind==="assertion"&&t>=zl(e)}function Ll(e,t,n=!1,r){let s=zl(e);return e.map((o,i)=>{if(r&&i<r.stepIndex)return o;let a=t[i],c=a&&a.actions.length>0;return o.kind==="assertion"?n&&i<s&&c?a:o:c?r&&i===r.stepIndex&&r.actionIndex>0?{...a,actions:[...o.actions.slice(0,r.actionIndex),...a.actions]}:a:o})}function mh(e,t,n,r){let s=cc(e,t);return s.length===0||!n?.pageUrl?s:[`page at failure: replay stopped at step ${n.stepIndex+1} ("${n.stepText}") on ${Nn(n.pageUrl,r)}, where the heal started.`,...s]}function yh(e,t,n=0){return e.map((r,s)=>{if(s<n)return r;let o=t[s];return o&&o.actions.length>0?o:r})}function Dl(e,t){let n=[];for(let r=0;r<Math.min(t,e.length);r++){let s=e[r].actions.length;s!==0&&n.push(`recording: kept the existing recording of step ${r+1} ("${e[r].gherkin}"), which ran before the agent took over; ignored ${s} action${s===1?"":"s"} the agent's session held for it.`)}return n}function Hl(e,t,n,r){let s=t.filter(c=>c>=0&&c<e.length),o=s.length>0?Math.max(...s):0,i=Math.min(n&&n.stepIndex>=o?n.stepIndex:o,e.length-1),a=n&&i===n.stepIndex?n.error:r;return e.map((c,l)=>({gherkin:c.gherkin,kind:c.kind,status:l<i?"passed":l===i?"failed":"skipped",...l===i&&a?{error:a}:{}}))}function wh(e,t,n){let r=n.success?e.map(s=>({gherkin:s.gherkin,kind:s.kind,status:"passed"})):Hl(e,n.announcedSteps??[],t,n.narrative);return e.map((s,o)=>o<t.stepIndex?s:r[o])}function Bl(e,t){return{aiCalls:e.aiCalls+t.aiCalls,inputTokens:e.inputTokens+t.inputTokens,outputTokens:e.outputTokens+t.outputTokens,cacheReadTokens:e.cacheReadTokens+t.cacheReadTokens,cacheCreationTokens:e.cacheCreationTokens+t.cacheCreationTokens,costUsd:(e.costUsd??0)+(t.costUsd??0),models:e.models||t.models?[...new Set([...e.models??[],...t.models??[]])]:void 0}}var os=class{constructor(t){this.options=t}options;browser;cdpEndpoint;stepIndex;get agent(){return this.options.agent}getStepIndex(){if(!this.stepIndex&&(this.stepIndex=Xe(this.options.projectRoot),this.stepIndex.steps.size>0)){let t=this.stepIndex.divergent.length>0?` \xB7 ${this.stepIndex.divergent.length} step(s) have divergent recordings (Level-2 signal)`:"";console.log(`step index: ${this.stepIndex.steps.size} reusable steps from ${this.stepIndex.scannedCaches} cache(s)${t}`)}return this.stepIndex}async recordWithSeeding(t,n,r){let s=this.getStepIndex(),o=t.steps.length,i={...t.params,...St(t.steps)},a=t.steps.map(S=>{let x=s.steps.size>0?fa(s,S,i):void 0;return x?{gherkin:S.text,keyword:S.keyword,kind:S.kind,table:S.table,docString:S.docString,fromStepSet:S.source?.fromStepSet,actions:x.actions}:void 0}),c=t.steps.map(S=>({gherkin:S.text,keyword:S.keyword,kind:S.kind,table:S.table,docString:S.docString,fromStepSet:S.source?.fromStepSet,actions:[]})),l=new Map;l.set(Ue,r);let d=[],p=[],u=[],f=[],h={...Nt},w=n,$=0,k=0,y=0,v=(S,x)=>({success:S,narrative:p.join(" ")||"Composed entirely from seeded recordings.",adaptations:d,suggestedFeatureEdit:f.length>0?f.join(`
|
|
295
|
+
`):void 0,featureEdits:u,recordedSteps:c,announcedSteps:x===void 0?[]:Array.from({length:x+1},(b,R)=>R),usage:h,seededCount:$});for(;y<o;){if(a[y]){let T=y;for(;T<o&&a[T];)T++;let E=a.slice(y,T),A={...t,steps:t.steps.slice(y,T)},P=await Hn(w.isClosed()?nr(n.context())??n:w,A,this.buildCandidateCache(t,E),{baseURL:this.options.baseURL,actionTimeoutMs:this.options.actionTimeoutMs,retries:this.options.retries,pollIntervalMs:this.options.pollIntervalMs,vars:l,trace:this.options.trace!==void 0&&this.options.trace!=="off",traceStepOffset:y,envNames:_e(t)});w=P.activePage??w;let O=P.status==="passed"?T-y:P.failure?.stepIndex??0;for(let N=0;N<O;N++)c[y+N]=E[N];if($+=O,P.status==="passed"){y=T;continue}let I=y+O;d.push(`Seeded recording for "${t.steps[I].text}" did not replay in this scenario's context; the agent re-recorded it fresh. Divergence signal.`),a[I]=void 0,y=I;continue}if(!this.options.agent)return v(!1,y);k++;let S=y;for(;S<o&&!a[S];)S++;k>=3&&(S=o);let x=await ss(this.browser,w.isClosed()?nr(n.context())??n:w),b=T=>{w=T};n.context().on("page",b);let R;try{R=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:this.options.baseURL,traceContext:this.options.trace&&this.options.trace!=="off"?n.context():void 0,mode:"record",cdpEndpoint:this.cdpEndpoint,projectRoot:this.options.projectRoot,assertionPolicy:this.options.assertionPolicy,completedSteps:y>0?t.steps.slice(0,y).map(T=>T.resolvedText):void 0,recordOnly:S<o?{from:y,to:S-1}:void 0,liveTab:x,onActiveTab:T=>{let E=n.context().pages().filter(A=>!A.isClosed())[T];E&&(w=E)},uniqueSeed:l.get(Ue),onTabOpened:this.tabWatcher(),takeFingerprint:async()=>Ht(kn(this.browser)??n)}))}finally{n.context().off("page",b)}if(h=Bl(h,R.usage),p.push(R.narrative),d.push(...R.adaptations),u.push(...R.featureEdits),R.suggestedFeatureEdit&&f.push(R.suggestedFeatureEdit),!R.success){let T=R.announcedSteps.filter(E=>E>=y&&E<o);return v(!1,T.length>0?Math.max(...T):y)}let m=R.announcedSteps.filter(T=>T>=y&&T<o),g=Math.min(o-1,Math.max(m.length>0?Math.max(...m):S-1,y));for(let T=y;T<=g;T++)c[T]=R.recordedSteps[T];y=g+1}return v(!0)}async withDialogsVisible(t){let n=()=>{},r=[],s=[],o=i=>{i.on("dialog",n),r.push(i)};for(let i of this.browser?.contexts()??[]){i.on("page",o),s.push(i);for(let a of i.pages())o(a)}try{return await t()}finally{for(let i of s)i.off("page",o);for(let i of r)try{i.off("dialog",n)}catch{}}}async start(){let t=this.options.browser??"chromium";if(t==="chromium"||ri[t]){let n=await hh();try{this.browser=await ph.launch({headless:!this.options.headed,channel:ri[t]?t:void 0,args:[`--remote-debugging-port=${n}`]})}catch(r){let s=r instanceof Error?r.message:String(r),o=ri[t];throw o&&/is not found at|distribution .* is not found/i.test(s)?new rr(`${o.label} is not installed on this machine, so --browser ${t} cannot run.
|
|
296
|
+
Install it (npx playwright install ${t} does that), or use --browser chromium, which Saffron ships with.`):r}this.cdpEndpoint=`http://127.0.0.1:${n}`}else this.browser=await(t==="firefox"?uh:gh).launch({headless:!this.options.headed}),this.cdpEndpoint=void 0}async stop(){await this.browser?.close(),this.browser=void 0}resolveStorageState(){if(!this.options.storageState)return;let t=jt.isAbsolute(this.options.storageState)?this.options.storageState:jt.join(this.options.projectRoot,this.options.storageState);if(!$n.existsSync(t))throw new Error(`storageState file not found: ${t}. Generate one with: npx playwright open --save-storage=${this.options.storageState} <url>`);return t}buildCandidateCache(t,n){return{version:1,feature:t.featurePath,scenario:t.name,recordedAt:new Date().toISOString(),recordedBy:"agent",steps:n,...Fl(t)}}tabWatcher(){return t=>{let n=this.browser?.contexts()??[],r=()=>t();for(let s of n)s.on("page",r);return()=>{for(let s of n)s.off("page",r)}}}async proofReplay(t,n,r,s){let o=await this.browser.newContext({storageState:this.resolveStorageState()}),i=this.options.trace!==void 0&&this.options.trace!=="off";i&&await lo(o,s?t.displayName:`${t.displayName} (proof replay)`);let a=await o.newPage();return{result:await Hn(a,t,n,{baseURL:this.options.baseURL,actionTimeoutMs:this.options.actionTimeoutMs,retries:this.options.retries,pollIntervalMs:this.options.pollIntervalMs,uniqueSeed:r,trace:i,tracePhase:s}),context:o,page:a}}async runScenario(t,n={}){let r=await this.runScenarioInner(t,n),s=Ze(t);if(s.size>0){let o=i=>i===void 0?i:dt(i,s);r.error=o(r.error),r.narrative=o(r.narrative),r.proofError=o(r.proofError),r.suggestedFeatureEdit=o(r.suggestedFeatureEdit),r.adaptations=r.adaptations.map(i=>dt(i,s));for(let i of r.stepResults)i.error=o(i.error)}return r}async screenshot(t,n,r,s){let o=this.options.screenshot??"viewport";if(o!=="off")try{let i=Qe(this.options.projectRoot,n.featurePath,n.displayName);this.claimArtifactDir(n);let a=jt.join(i,`${r}.jpg`),c=await t.screenshot({path:a,type:"jpeg",quality:80,fullPage:o==="full-page",timeout:5e3});return{kind:r,file:xe(this.options.projectRoot,a),step:s,sha256:Ve(c)}}catch{return}}claimArtifactDir(t){let n=Qe(this.options.projectRoot,t.featurePath,t.displayName);$n.mkdirSync(n,{recursive:!0}),$n.writeFileSync(jt.join(n,fn),JSON.stringify({feature:t.featurePath,scenario:t.displayName},null,2))}async runScenarioInner(t,n={}){if(!this.browser)throw new Error("Orchestrator not started");let r=Date.now(),{projectRoot:s,baseURL:o,actionTimeoutMs:i,retries:a,pollIntervalMs:c}=this.options,l=re(s,t.featurePath,t.name),d;try{d=Re(l)}catch(A){if(!(A instanceof oe))throw A;return{scenario:t,status:"red",source:"cache",stepResults:[],adaptations:[],usage:Nt,durationMs:Date.now()-r,error:`The recording cannot be read: ${A.problem}. Fix the file, or re-record it with saffron run --rerecord.`}}let p=Fe(s,t.featurePath,t.name),u=xe(s,p),f,h;if($n.existsSync(p))try{({proposal:f,revision:h}=Or(p))}catch(A){if(!(A instanceof oe)&&A.code!=="ENOENT")throw A;f=void 0}let w=!1;f&&!Sa(s,p,h)&&(w=!this.options.rerecord,f=void 0),f&&Le(s,f,t)&&(f=void 0);let $=A=>A.status==="stale"?"the committed recording no longer matches the scenario":`the committed recording failed${A.failure?` at "${A.failure.stepText}"`:""}`,k=A=>{let P=ht(s)[u],O=P?.revision===h?` from ${ie(Zn(P.from))}`:"",I=A?$(A):"";return{scenario:t,status:"yellow",source:d?"cache":"agent-record",stepResults:A?.stepResults??[],narrative:(I?`${I[0].toUpperCase()}${I.slice(1)}. `:"")+`A proposal${O} is pending review at ${u}. It was not filed on this machine, so this run does not replay it, heal or record over it. Review it with saffron diff ${u}, then saffron accept or saffron reject it.`,adaptations:[],proposalFile:u,proposalRevision:h,usage:Nt,durationMs:Date.now()-r}};if($n.rmSync(Qe(s,t.featurePath,t.displayName),{recursive:!0,force:!0}),w&&!d)return k();let y=(A,P)=>({scenario:t,status:"yellow",source:"agent-record",proposalReplay:!0,stepResults:A.stepResults,narrative:`Replayed the pending proposal recorded for "${f.meta.recordedFor??t.name}" at zero AI${P?` instead of ${P.status==="stale"?"recording":"healing"} again: ${$(P)}`:""}; accept it to go green.`,adaptations:[],verified:!0,proposalFile:u,proposalRevision:h,usage:Nt,durationMs:Date.now()-r}),v=await this.browser.newContext({storageState:this.resolveStorageState()}),S=this.options.trace??"off",x=S!=="off";x&&await lo(v,t.displayName);let b=!x,R,m=await v.newPage(),g=Rt(),T=[],E=(A,P)=>this.screenshot(A,t,"before-heal",P.stepText).then(O=>{O&&T.push(O)});try{let A=await(async()=>{let I;if(f&&!d){let U=await Hn(m,t,f.cache,{baseURL:o,actionTimeoutMs:i,retries:a,pollIntervalMs:c,uniqueSeed:g,trace:x,tracePhase:"pending"}),K=f.meta.recordedFor??t.name;if(U.status==="passed")return y(U);if(Object.keys(t.params).length>0&&K!==t.displayName){let Z=U.failure;return{scenario:t,status:"red",source:"agent-record",proposalReplay:!0,stepResults:U.stepResults,adaptations:[],proposalFile:u,proposalRevision:h,usage:Nt,durationMs:Date.now()-r,error:`The pending proposal recorded for "${K}" does not replay for this Examples row`+(Z?` (step "${Z.stepText}": ${Z.error.split(`
|
|
297
|
+
`)[0]})`:"")+". A row value is probably baked in as a literal instead of a <placeholder>; inspect the proposal, reject it, and re-record with saffron run --rerecord."}}console.log(` \u21BA pending proposal for "${t.displayName}" did not replay`+(U.failure?` (step "${U.failure.stepText}": ${U.failure.error.split(`
|
|
298
|
+
`)[0]})`:"")+"; recording again"),await m.goto("about:blank")}if(d){if(I=await Hn(m,t,d,{baseURL:o,actionTimeoutMs:i,retries:a,pollIntervalMs:c,uniqueSeed:g,trace:x,onFailure:E,keepResponseLog:!0}),I.status==="passed")return{scenario:t,status:"green",source:"cache",stepResults:I.stepResults,adaptations:[],usage:Nt,durationMs:Date.now()-r};if(w)return I.responses?.detach(),k(I);if(f){let U=Rt(),K=await this.proofReplay(t,f.cache,U,"pending");if(K.result.status==="passed")return I.responses?.detach(),R=K.context,g=U,y(K.result,I);await K.context.close(),console.log(` \u21BA pending proposal for "${t.displayName}" did not replay`+(K.result.failure?` (step "${K.result.failure.stepText}": ${K.result.failure.error.split(`
|
|
299
|
+
`)[0]})`:"")+(I.status==="failed"?"; healing":"; recording again"))}}if(!(this.options.agent!==void 0&&this.cdpEndpoint!==void 0&&!n.agentDisabled)){let U=this.options.agent!==void 0&&this.cdpEndpoint===void 0&&!n.agentDisabled?`recording/healing needs a Chromium-family browser (the agent attaches over CDP). Record with --browser chromium (the default), chrome or msedge, then replay with --browser ${this.options.browser}.`:"no agent is configured.";return I?.responses?.detach(),{scenario:t,status:"red",source:"cache",stepResults:I?.stepResults??[],adaptations:[],usage:Nt,durationMs:Date.now()-r,error:d?I?.status==="stale"?`Cache is stale (feature file changed) and ${U}`:`Replay failed and ${U} ${I?.failure?.error??""}`.trimEnd():`No cache exists and ${U}`}}let M=d!==void 0&&I!==void 0&&I.status==="failed",B=0,_,j;try{if(M){j=I.responses;let U=await ss(this.browser,I.activePage??nr(m.context(),I.failure.pageUrl)??m);_=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:o,traceContext:x?m.context():void 0,mode:"heal",liveTab:U,model:this.options.healModel,cdpEndpoint:this.cdpEndpoint,projectRoot:this.options.projectRoot,assertionPolicy:this.options.assertionPolicy,completedSteps:I.stepResults.filter(K=>K.status==="passed").map(K=>K.gherkin),failedStep:{text:I.failure.stepText,kind:I.failure.kind,error:I.failure.error,pageUrl:I.failure.pageUrl,stepIndex:I.failure.stepIndex},uniqueSeed:g,onTabOpened:this.tabWatcher(),takeFingerprint:async()=>{let K=kn(this.browser)??m;return Ht(K)}}))}else if(await m.goto("about:blank"),this.options.reuseSteps!==!1){let U=await this.recordWithSeeding(t,m,g);B=U.seededCount,_=U}else _=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:o,traceContext:x?m.context():void 0,mode:"record",cdpEndpoint:this.cdpEndpoint,projectRoot:this.options.projectRoot,assertionPolicy:this.options.assertionPolicy,uniqueSeed:g,onTabOpened:this.tabWatcher(),takeFingerprint:async()=>{let U=kn(this.browser)??m;return Ht(U)}}))}catch(U){j?.detach();let K=U instanceof Error?U.message:String(U);return{scenario:t,status:"red",source:M?"agent-heal":"agent-record",stepResults:I?.stepResults??[],adaptations:[],usage:Nt,durationMs:Date.now()-r,error:`Agent invocation failed: ${K.split(`
|
|
300
|
+
`)[0]}`}}if(_.success&&M&&I.failure.kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||Ml(d.steps,I.failure.stepIndex))){let U=d.steps[I.failure.stepIndex],K=kn(this.browser)??m,de=new Map(Object.entries(I.captured)),Z=So(t,I.failure.stepIndex);try{for(let Ge of U.actions)await Hr(K,Ge,Z,this.options.actionTimeoutMs??5e3,o,de,j,void 0,_e(t))}catch(Ge){let bt=Ge instanceof Error?Ge.message:String(Ge),C=`Assertion failed as written: "${U.gherkin}". Saffron never adapts assertions. If this change is intended, update the .feature file or re-record the scenario (saffron run --rerecord --filter @tag). If the recording itself looks wrong (an empty value, a wrong target), re-record it the same way. Verification error: ${bt.split(`
|
|
301
|
+
`)[0]}`,H=I.failure.stepIndex,q=I.stepResults.map((J,ye)=>ye===H?{...J,status:"failed",error:C}:J);return{scenario:t,status:"red",source:"agent-heal",stepResults:q,executionStepResults:q.map((J,ye)=>ye>H&&J.status==="skipped"?{...J,status:"passed"}:J),narrative:_.narrative,adaptations:_.adaptations,suggestedFeatureEdit:_.suggestedFeatureEdit,usage:_.usage,durationMs:Date.now()-r,error:C}}finally{j?.detach()}}return j?.detach(),await this.finalizeAgentRun(t,_,M,d,r,B,M?I?.failure:void 0,g)})(),P=T.find(I=>I.kind==="before-heal");if(A.source==="cache"&&P){let I=P.file.replace(/before-heal\.jpg$/,"failure.jpg");try{$n.renameSync(jt.join(s,P.file),jt.join(s,I)),P.file=I}catch{}P.kind="failure"}else if(A.status==="red"){let I=A.stepResults.find(M=>M.status==="failed")?.gherkin,N=await this.screenshot(kn(this.browser)??m,t,"failure",I);N&&T.push(N)}let O=bn(je(t),g);if(O.size>0&&(A.uniques=Object.fromEntries(O)),T.push(...A.evidence??[]),x){let I=S==="on"||A.status!=="green",N=Qe(s,t.featurePath,t.displayName),M=I?jt.join(N,co):void 0;b=!0;let B=R??v;M||await fo(B).catch(()=>{});let _=M?await po(B,M,Ze(t)):void 0;if(M&&_){this.claimArtifactDir(t);let j=Ze(t);T.unshift({kind:"trace",file:xe(s,M),sha256:_,traceSteps:(A.executionStepResults??A.stepResults).map(U=>({...U,error:U.error&&dt(U.error,j)}))})}}return T.length>0&&(A.status!=="green"||T.some(I=>I.kind==="trace"))&&(A.evidence=T),A}finally{b||await fo(v).catch(()=>{}),await R?.close(),await v.close()}}async finalizeAgentRun(t,n,r,s,o,i=0,a,c=Rt()){let l=r?"agent-heal":"agent-record",d=n.success?n.recordedSteps.map(_=>({gherkin:_.gherkin,kind:_.kind,status:"passed"})):Hl(n.recordedSteps,n.announcedSteps??[],a&&{stepIndex:a.stepIndex,error:a.error},n.narrative);if(!n.success)return{scenario:t,status:"red",source:l,stepResults:d,narrative:n.narrative,adaptations:n.adaptations,usage:n.usage,durationMs:Date.now()-o,error:n.narrative};let p=r?Ll(s.steps,n.recordedSteps,this.options.assertionPolicy==="adaptable-mid",a?{stepIndex:a.stepIndex,actionIndex:a.actionIndex}:void 0):n.recordedSteps,u=[...n.adaptations,...r&&a?Dl(n.recordedSteps,a.stepIndex):[]],f={...n.usage},h,w,$,k,y=[],v=0,S=new Set,x,b=async(_,j,U=j.stepResults)=>{if(!S.has(_)){S.add(_);try{if(this.options.trace&&this.options.trace!=="off"){let K=jt.join(Qe(this.options.projectRoot,t.featurePath,t.displayName),`proof-${++v}.zip`),de=Ze(t),Z=await po(_,K,de);if(Z){this.claimArtifactDir(t);let Ge=j.captured[Ue],bt=Ge?bn(je(t),Ge):new Map;y.push({kind:"trace",proof:!0,file:xe(this.options.projectRoot,K),sha256:Z,traceSteps:U.map(C=>({...C,error:C.error&&dt(C.error,de)})),traceUniques:bt.size?Object.fromEntries(bt):void 0})}}}finally{await _.close()}}};if(this.options.verifyProposals!==!1){let _=await this.proofReplay(t,this.buildCandidateCache(t,p),Rt());k=_.result.captured[Ue];try{if(_.result.status!=="passed"&&_.result.failure){let j=_.result.failure;if(this.options.agent&&!(r&&j.kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||Ml(s.steps,j.stepIndex))))try{let K=await ss(this.browser,_.result.activePage??nr(_.page.context(),j.pageUrl)??_.page),de=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:this.options.baseURL,traceContext:this.options.trace&&this.options.trace!=="off"?_.context:void 0,mode:"refine",model:r?this.options.healModel:void 0,cdpEndpoint:this.cdpEndpoint,projectRoot:this.options.projectRoot,assertionPolicy:this.options.assertionPolicy,completedSteps:_.result.stepResults.filter(Z=>Z.status==="passed").map(Z=>Z.gherkin),failedStep:{text:j.stepText,kind:j.kind,error:j.error,pageUrl:j.pageUrl,stepIndex:j.stepIndex},liveTab:K,uniqueSeed:_.result.captured[Ue],onTabOpened:this.tabWatcher(),takeFingerprint:async()=>Ht(kn(this.browser)??_.page)}));f=Bl(f,de.usage),x=wh(_.result.stepResults,j,de),de.success&&(u.push(...de.adaptations),u.push(...Dl(de.recordedSteps,j.stepIndex)),p=r?Ll(p,de.recordedSteps,this.options.assertionPolicy==="adaptable-mid",{stepIndex:j.stepIndex,actionIndex:0}):yh(p,de.recordedSteps,j.stepIndex),await b(_.context,_.result,x),x=void 0,_=await this.proofReplay(t,this.buildCandidateCache(t,p),Rt()),k=_.result.captured[Ue])}catch{}}for(let j of _.result.tabOpeners??[]){let U=p[j.stepIndex]?.actions[j.actionIndex];U&&(U.opensTab=!0)}h=_.result.status==="passed",h||(w=_.result.failure?.error??`proof replay ${_.result.status}`,$=_.result.stepResults)}finally{await b(_.context,_.result,x).catch(()=>{})}}r&&s&&u.push(...mh(s.steps,p,a,this.options.baseURL));let R=[...n.featureEdits];for(let _ of pa(p,Xe(this.options.projectRoot)))u.push(`duplicate wording: "${_.from}" recorded exactly the same actions as the existing step "${_.to}" (${_.feature} \u203A ${_.scenario}). Accept with --with-feature-edit to converge on the canonical wording.`),R.some(j=>j.index===_.index)||R.push({index:_.index,text:_.to});let m=Pl(p);m.length>0&&(h=!1,w=[w,...m].filter(Boolean).join(" "));let g=Ze(t),T=_=>g.size>0?dt(_,g):_;u=u.map(T);let E=R.map(_=>({index:_.index,text:T(_.text)})),A=T(n.narrative),P=n.suggestedFeatureEdit?T(n.suggestedFeatureEdit):void 0,O={version:1,feature:t.featurePath,scenario:t.name,recordedAt:new Date().toISOString(),recordedBy:"agent",steps:p,...Fl(t)},I={meta:{createdAt:O.recordedAt,mode:r?"heal":"record",narrative:A,adaptations:u,suggestedFeatureEdit:P,featureEdits:E.length>0?E:void 0,verified:h,proofError:w?T(w):void 0,seededSteps:i>0?i:void 0,recordedFor:t.displayName,usage:f,bound:wc(t,s,O,E.length>0?E:void 0)},cache:O},N=Fe(this.options.projectRoot,t.featurePath,t.name),M=wa(N,I);xa(this.options.projectRoot,N,M);let B=Re(re(this.options.projectRoot,t.featurePath,t.name));return{proposalDiff:Et(B,I.cache),scenario:t,status:"yellow",source:l,stepResults:$??d,executionStepResults:d,evidence:y,proofUniques:(()=>{let _=k?bn(je(t),k):void 0;return _&&_.size>0?Object.fromEntries(_):void 0})(),narrative:A,adaptations:u,suggestedFeatureEdit:P,featureEdits:E.length>0?E:void 0,verified:h,proofError:w,seededSteps:i>0?i:void 0,proposalFile:xe(this.options.projectRoot,N),proposalRevision:M,usage:f,durationMs:Date.now()-o}}};import bs from"node:fs";import ym from"node:os";import yd from"node:path";import{query as zh}from"@anthropic-ai/claude-agent-sdk";import{McpServer as bh}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as G}from"zod";var $e=e=>({content:[{type:"text",text:e}]});function Rn(e,t,n,r){let s=async o=>{let i=await r(o);return i.content[0]?.text.startsWith("ERROR:")?{...i,isError:!0}:i};return o=>{o.registerTool(e,{description:t,inputSchema:n},s)}}function vh(e){let t=new bh({name:e.name,version:e.version});for(let n of e.tools)n(t);return{type:"sdk",name:e.name,instance:t}}function ql(e){let t={};return e.role&&(t.role=e.role),e.name&&(t.name=e.name),e.nameRegex&&(t.nameRegex=e.nameRegex),e.label&&(t.label=e.label),e.text&&(t.text=e.text),e.selector&&(t.fallbackSelectors=[e.selector]),e.frame&&(t.frame=e.frame),Object.keys(t).length>0?t:void 0}var Sh=new Set(["main","banner","contentinfo","status","alert","alertdialog","dialog","search"]);function Jl(e){if(!e?.role)return;let{role:t,frame:n,...r}=e;if(!(Object.keys(r).length>0||Sh.has(t)))return`ERROR: role="${t}" alone matches every ${t} on the page, and replay would use the first one. Add a name (or nameRegex), text, label or selector that picks exactly the element you checked, then call again.`}function xh(e,t){return t.index>=e.steps.length?`ERROR: there is no step ${t.index}: this scenario's steps are numbered from 0 to ${e.steps.length-1}. Call saffron_step again with the zero-based index of the step you are about to perform.`:(e.announce(t.index,t.text,t.adaptation),t.index<e.firstStep?`Step ${t.index} already ran before you took over and keeps its recording; nothing you do under it is recorded. Do not redo it: continue from step ${e.firstStep} on the page as it is.`:`Recording step ${t.index}: ${t.text}`)}var Wl=new WeakSet;function $h(e,t){if(t.success&&!Wl.has(e)){let n=[...e.announced].filter(r=>r>=e.firstStep&&e.steps[r]?.kind==="assertion"&&!e.steps[r].actions.some(s=>Ne.has(s.action))).sort((r,s)=>r-s);if(n.length>0)return Wl.add(e),`ERROR: not finalized. Assertion step ${n.join(", ")} recorded no check, so replay would verify nothing. Record what you verified with saffron_assert under that step (saffron_step first if you moved on), then call saffron_done again. If the condition does not hold, call saffron_done with success=false.`}return e.done=!0,e.success=t.success,e.narrative=t.narrative,e.suggestedFeatureEdit=t.suggestedFeatureEdit,e.featureEdits=(t.featureEdits??[]).filter(n=>!Us.test(n.text)),"Run finalized."}var Vl={role:G.string().optional().describe("ARIA role of the element"),name:G.string().optional().describe("Accessible name \u2014 use the SHORTEST stable substring; never include volatile content like prices or dates"),nameRegex:G.string().optional().describe("Regex for the accessible name when it embeds volatile content, e.g. 'Select \\\\{date\\\\+1\\\\} as checkin' cannot work \u2014 instead use nameRegex 'Select .* as checkin'"),label:G.string().optional().describe("Form-label text for getByLabel \u2014 the literal <label> text only, never a free-text description"),text:G.string().optional().describe("getByText locator text"),selector:G.string().optional().describe("CSS fallback selector"),frame:G.string().optional().describe(`CSS selector of the iframe hosting the element, e.g. 'iframe[title="Feedback widget"]' \u2014 REQUIRED whenever the element lives inside an iframe; without it replay looks only at the top-level page`)};function is(e){return vh({name:"saffron",version:"0.1.0",tools:[Rn("saffron_step","Announce the Gherkin step you are about to perform. MUST be called before executing browser actions for each step, with the step's zero-based index and exact text.",{index:G.number().int().min(0),text:G.string(),adaptation:G.string().optional().describe("If the written step does not match the real UI and you are deviating from it, describe the deviation in one sentence: the kind of change (a locator or label change on the same page, a page removed or merged, a page added or flow reordered) and the page it happened on.")},async t=>$e(xh(e,t))),Rn("saffron_capture",`Record a captureText action for the current step: at replay time, the target element's text is read and stored under saveAs for later expectDiffers comparisons. Use for steps like 'I record the displayed price as "X"'. The target must select exactly the element whose text is the value.`,{saveAs:G.string().describe("Name to store the captured text under"),...Vl},async t=>{let n=ql(t);if(!n)return $e("ERROR: capture needs a target (role/name, nameRegex, label, text, or selector).");let r=Jl(n);return r?$e(r):(e.addActions([{action:"captureText",target:n,saveAs:t.saveAs}]),$e(`Capture recorded as "${t.saveAs}".`))}),Rn("saffron_dialog","Record how a native dialog (alert/confirm/prompt) must be handled at replay. Call this IMMEDIATELY whenever an action triggers a native dialog \u2014 whether you handled it via browser_handle_dialog or the browser reported it as already handled. At replay Saffron arms this handler BEFORE the triggering action, so without this call the replay will auto-dismiss the dialog and diverge from what you saw.",{accept:G.boolean().describe("true = accept/OK the dialog, false = dismiss/cancel"),promptText:G.string().optional().describe("Text typed into a prompt() before accepting")},async t=>(e.addArmedAction({action:"handleDialog",value:t.accept?"accept":"dismiss",...t.promptText?{promptText:t.promptText}:{}}),$e(`Dialog handling recorded (${t.accept?"accept":"dismiss"}).`))),Rn("saffron_wait_api","Record a network wait for the current step: replay will block until a matching API response is observed (responses from the triggering step count). Call AFTER you verified via browser_network_requests that the response actually occurred with the expected status/body. Use a path-only urlPattern regex and never literal volatile IDs (/api/orders/\\d+, not /api/orders/8842).",{urlPattern:G.string().describe("Regex matched against the response URL \u2014 path-only for portability"),method:G.string().optional().describe("HTTP method to match (any if omitted)"),status:G.string().optional().describe("Expected status \u2014 exact ('201') or class ('2xx'); default any 2xx"),bodyPattern:G.string().optional().describe(`Regex the response body must match, e.g. '"status"\\s*:\\s*"READY"' for polling waits`)},async t=>(e.addActions([{action:"waitForResponse",urlPattern:t.urlPattern,...t.method?{method:t.method}:{},...t.status?{status:t.status}:{},...t.bodyPattern?{pattern:t.bodyPattern}:{}}]),$e("Network wait recorded."))),Rn("saffron_assert","Record a verified assertion for the current Then step. Call ONLY after you have confirmed the condition holds via a page snapshot. If the condition does NOT hold, do not call this \u2014 call saffron_done with success=false instead. NEVER record volatile content (prices, dates, counters) as literal expected text \u2014 use kind=matches with a pattern, or kind=differs against captured values.",{kind:G.enum(["visible","notVisible","text","url","value","differs","matches","attribute","response","each"]),...Vl,expected:G.string().optional().describe("Expected text/value for kind=text|value \u2014 stable text only, never volatile values"),url:G.string().optional().describe("URL substring for kind=url (path only, no host)"),pattern:G.string().optional().describe("kind=matches|attribute: regex the target's text (or attribute) must match, e.g. 'NOK [\\\\d,]+' for a price"),attribute:G.string().optional().describe("kind=attribute: attribute name to check, e.g. 'href' for link-target assertions \u2014 use this for 'X should link to Y' instead of clicking through"),capture:G.string().optional().describe("kind=differs: name of the captured value on the LEFT of the comparison (omit when comparing the target element's live text)"),urlPattern:G.string().optional().describe("kind=response: regex matched against the response URL \u2014 path-only for portability, never literal volatile IDs (use /api/orders/\\d+)"),method:G.string().optional().describe("kind=response: HTTP method to match (any if omitted)"),status:G.string().optional().describe("kind=response: expected status \u2014 exact ('201') or class ('2xx'); default any 2xx"),bodyPattern:G.string().optional().describe("kind=response: regex the response body must match (verify via browser_network_requests first)"),each:G.string().optional().describe("kind=each: the data-list token exactly as the step writes it, e.g. '{data:enums.OrderStatus}'. The target is the CONTAINER (dropdown, table, list) that must show every value of that list. Never pass the values themselves."),compareTo:G.string().optional().describe("kind=differs: name of the captured value to compare against")},async t=>{let n=ql(t),r=Jl(n);if(r)return $e(r);let s;switch(t.kind){case"visible":s={action:"expectVisible",target:n};break;case"notVisible":s={action:"expectNotVisible",target:n};break;case"text":s={action:"expectText",target:n,value:t.expected??""};break;case"value":s={action:"expectValue",target:n,value:t.expected??""};break;case"url":s={action:"expectUrl",url:t.url??""};break;case"differs":if(!t.compareTo)return $e("ERROR: kind=differs requires compareTo.");if(!t.capture&&!n)return $e("ERROR: kind=differs needs either capture (a stored name) or a target element.");s={action:"expectDiffers",target:n,value:t.capture,compareTo:t.compareTo};break;case"matches":if(!t.pattern)return $e("ERROR: kind=matches requires pattern.");s={action:"expectMatches",target:n,pattern:t.pattern};break;case"attribute":if(!t.attribute||!t.pattern)return $e("ERROR: kind=attribute requires attribute and pattern.");s={action:"expectAttribute",target:n,attribute:t.attribute,pattern:t.pattern};break;case"each":if(!t.each||!/^\{data:[^}]+\}$/.test(t.each))return $e("ERROR: kind=each requires each='{data:file.list}', the token exactly as the step writes it (not the values).");s={action:"expectEach",target:n,each:t.each};break;case"response":if(!t.urlPattern)return $e("ERROR: kind=response requires urlPattern.");s={action:"expectResponse",urlPattern:t.urlPattern,...t.method?{method:t.method}:{},...t.status?{status:t.status}:{},...t.bodyPattern?{pattern:t.bodyPattern}:{}};break}return!["url","differs","response"].includes(t.kind)&&!n?$e("ERROR: assertion needs a target (role/name, nameRegex, label, text, or selector)."):(e.addActions([s]),$e("Assertion recorded."))}),Rn("saffron_done","Finalize the run. Call exactly once, after the final step: success=true only if every step's intent was achieved and every assertion verified.",{success:G.boolean(),narrative:G.string().describe("2-4 sentence summary of the run: what happened, and why it failed if it did. After a heal, say what kind of change the app went through (a locator change, or a page removed, merged, added or reordered) and on which page."),suggestedFeatureEdit:G.string().optional().describe("If you adapted any steps: the corrected Gherkin for those steps, as you would rewrite them in the .feature file (free text, for the human report)."),featureEdits:G.array(G.object({index:G.number().int().min(0).describe("zero-based step index"),text:G.string().describe("replacement step text WITHOUT the Given/When/Then keyword")})).optional().describe("Machine-applicable version of the suggested edits: one entry per adapted step. Provide this whenever you adapted a step.")},async t=>$e($h(e,t)))]})}function cs(e={}){let t=e.deliberateSnapshots?`
|
|
298
302
|
8. Tool responses do NOT include a page snapshot. Take snapshots deliberately with browser_snapshot, and only when you actually need to see the page: after navigation, before locating an element you haven't seen yet, and when verifying an assertion. Do NOT snapshot after actions whose outcome is predictable (filling a field you just located, pressing Enter, a click whose result you will verify later anyway). Every snapshot is expensive.
|
|
299
303
|
9. Minimize round-trips: batch tool calls in a single response whenever they don't depend on each other's results \u2014 saffron_step together with that step's browser actions, several fills in one turn, bookkeeping calls (saffron_capture, saffron_assert) alongside the actions they belong to. Only stop and wait when you genuinely need a result before deciding your next call. Do not write narration between tool calls.`:"";return`You are Saffron's test execution agent. You execute Gherkin scenarios in a real browser using the playwright MCP tools, while Saffron records your actions into a deterministic replay cache.
|
|
300
304
|
|
|
@@ -312,9 +316,9 @@ Non-negotiable rules:
|
|
|
312
316
|
5a3. DATA LISTS: when a step shows a token followed by '(a data list, currently: \u2026)', e.g. "should list every {data:enums.OrderStatus} (a data list, currently: "New", "Paid")", verify from a snapshot that EVERY listed value is shown inside one container (the dropdown, table, list or menu the step is about), then record ONE assertion: saffron_assert kind=each, each='{data:enums.OrderStatus}' (the token exactly as written, never the values), targeting that container. Do NOT record one assertion per value: replay reads the list from the data file, so values added to it later are checked without recording again. If any listed value is missing, the step FAILS.
|
|
313
317
|
5c. Real-world page furniture is supported: elements inside IFRAMES record and replay fine (interact normally) \u2014 but when a saffron_assert targets an element INSIDE an iframe, you MUST pass the iframe's CSS selector as the 'frame' argument (e.g. frame='iframe[title="Feedback widget"]'); replay cannot see into frames otherwise. File uploads: use browser_file_upload with the file path. Drag-and-drop: use browser_drag. All of these are recorded and replay deterministically.
|
|
314
318
|
5d. NATIVE DIALOGS (alert/confirm/prompt): when an action opens one, the page blocks and the snapshot reports a modal state \u2014 resolve it with browser_handle_dialog (accept true/false; promptText for prompt()). That call is recorded automatically as an armed handler replay places BEFORE the triggering action, so do NOT also call saffron_dialog. After handling, verify the post-dialog state as usual. If a step's wording says to confirm/accept, accept; if it says cancel/dismiss, dismiss.
|
|
315
|
-
5e. NETWORK WAITS: when a step says to wait for an API call ("wait for the order API to succeed", "until the job API reports READY"), do it verify-first: perform the trigger, check via browser_network_requests that the matching response actually occurred with the expected status/body, then record it with saffron_wait_api. For Then steps about API contracts ("the request should have returned 201") verify the same way and record with saffron_assert kind=response. urlPattern is a path-only regex \u2014 NEVER a literal volatile ID (/api/orders/\\d+, not /api/orders/8842) and never the host. browser_network_request returns a whole response body, which Saffron cuts at ${
|
|
319
|
+
5e. NETWORK WAITS: when a step says to wait for an API call ("wait for the order API to succeed", "until the job API reports READY"), do it verify-first: perform the trigger, check via browser_network_requests that the matching response actually occurred with the expected status/body, then record it with saffron_wait_api. For Then steps about API contracts ("the request should have returned 201") verify the same way and record with saffron_assert kind=response. urlPattern is a path-only regex \u2014 NEVER a literal volatile ID (/api/orders/\\d+, not /api/orders/8842) and never the host. browser_network_request returns a whole response body, which Saffron cuts at ${no.toLocaleString("en-US")} characters: fetch a body only when the step is about its content, and prefer a saffron_assert kind=response on the field you need.
|
|
316
320
|
5f. TABS: a click that opens a new tab needs nothing extra, replay follows the new tab by itself. When a step says to switch to another tab, go back to the first tab, or close a tab, do it with browser_tabs (list first if unsure of the index); select, close and new are recorded and replay in the same order. Steps that assert on the other tab's content are ordinary assertions after the switch.
|
|
317
|
-
7. Never ask the user questions; you are unattended.${t}`}function
|
|
321
|
+
7. Never ask the user questions; you are unattended.${t}`}function kh(e,t){if(e[t].kind!=="assertion")return"action";let n=e.length;for(let r=e.length-1;r>=0&&e[r].kind==="assertion";r--)n=r;return t>=n?"assertion:final":"assertion"}var Rh=`When you heal, tell the reviewer WHAT KIND of change you adapted to, in saffron_step's adaptation and again in saffron_done's narrative, and name the page (its URL path) where it happened. Pick the kind that fits: (1) locator or label change: the same control on the same page, found differently (renamed button, new test id, native select instead of a custom one); (2) page removed or merged: a page no longer exists and its fields or controls now live on another page, so a navigation step (e.g. a 'Continue' click) is no longer needed; (3) page added or flow reordered: a new intermediate page, dialog or step order; (4) timing only: nothing changed, the element was slow. When you skip or add a click, key press or navigation the step used to perform, say so explicitly, e.g. "The guest information page is gone: its fields are now on /checkout, so the 'Continue to payment' click was dropped." Never describe a flow change as a locator change.`;function as(e){let t=e.liveTab;if(t)return t.count<=1?`Live page: the only open tab, at ${t.url}. Work on it; do not open or select another tab to start over.`:`Live page: tab ${t.index} of ${t.count} open tabs, at ${t.url}. This is where replay left off. If browser_tabs shows another tab as current, select tab ${t.index} before anything else (Saffron does not record that selection); never start over on another tab.`}function Gl(e){let t=e.failedStep?.stepIndex;return`ANNOUNCE FIRST: call saffron_step for ${t===void 0?"the failed step":`the failed step (index ${t})`} BEFORE any state-changing browser action (click, type, select, key press, navigation, tab change). To diagnose, look with browser_snapshot, never with clicks or navigation: Saffron discards every action made before that announcement, and going back through earlier steps changes the state replay reached.`}function ls(e){let{scenario:t}=e,n=_e(t),r=t.steps.map((o,i)=>{let a=u=>$r(qi(wn(u,e.uniqueSeed??"")),n),c=`${i}. [${kh(t.steps,i)}] ${o.keyword} ${a(o.resolvedText)}`,l=o.resolvedTable??o.table,d=o.resolvedDocString??o.docString,p=c;return l&&(p+=`
|
|
318
322
|
${l.map(u=>` | ${u.map(a).join(" | ")} |`).join(`
|
|
319
323
|
`)}`),d!==void 0&&(p+=`
|
|
320
324
|
"""
|
|
@@ -322,28 +326,28 @@ ${a(d).split(`
|
|
|
322
326
|
`).map(u=>` ${u}`).join(`
|
|
323
327
|
`)}
|
|
324
328
|
"""`),p}).join(`
|
|
325
|
-
`),s=[`Feature: ${t.featureName} (${t.featurePath})`,`Scenario: ${t.displayName}`,e.baseURL?`Base URL: ${e.baseURL}`:void 0,"","Steps (index. [kind] keyword text):",r,""];if(e.mode==="refine")s.push("MODE: REFINE. You (or a previous agent session) just recorded this scenario and it completed successfully \u2014 but the deterministic zero-AI replay of that recording FAILED at the step below. The application is working; the RECORDING is not replayable.","The browser tab shows the state where the proof replay stopped.",
|
|
329
|
+
`),s=[`Feature: ${t.featureName} (${t.featurePath})`,`Scenario: ${t.displayName}`,e.baseURL?`Base URL: ${e.baseURL}`:void 0,"","Steps (index. [kind] keyword text):",r,""];if(e.mode==="refine")s.push("MODE: REFINE. You (or a previous agent session) just recorded this scenario and it completed successfully \u2014 but the deterministic zero-AI replay of that recording FAILED at the step below. The application is working; the RECORDING is not replayable.","The browser tab shows the state where the proof replay stopped.",as(e),"",`Steps that replayed fine:
|
|
326
330
|
${(e.completedSteps??[]).map(o=>` \u2713 ${o}`).join(`
|
|
327
|
-
`)||" (none)"}`,"",`Failed step: [${e.failedStep?.kind}] ${e.failedStep?.text}`,`Replay failure: ${e.failedStep?.error}`,"","Typical causes: a locator that only matched during your session (volatile accessible name \u2014 use nameRegex or a shorter stable name), a literal dynamic value baked into an assertion (use kind=matches/differs/captureText), or an assertion that cannot be checked without navigation (use kind=attribute for link targets).","Re-perform and re-record the failed step and every step after it in a REPLAYABLE form via saffron_step + browser tools / saffron_capture / saffron_assert. Express the SAME conditions the steps state \u2014 do not weaken them.","If a step genuinely cannot be expressed replayably, call saffron_done success=false and explain why.",
|
|
331
|
+
`)||" (none)"}`,"",`Failed step: [${e.failedStep?.kind}] ${e.failedStep?.text}`,`Replay failure: ${e.failedStep?.error}`,"","Typical causes: a locator that only matched during your session (volatile accessible name \u2014 use nameRegex or a shorter stable name), a literal dynamic value baked into an assertion (use kind=matches/differs/captureText), or an assertion that cannot be checked without navigation (use kind=attribute for link targets).","Re-perform and re-record the failed step and every step after it in a REPLAYABLE form via saffron_step + browser tools / saffron_capture / saffron_assert. Express the SAME conditions the steps state \u2014 do not weaken them.","If a step genuinely cannot be expressed replayably, call saffron_done success=false and explain why.",Gl(e));else if(e.mode==="heal")s.push("MODE: HEAL. A cached deterministic replay of this scenario failed mid-run.","The browser tab already holds the page state reached so far \u2014 do NOT restart from step 0; verify where you are with a snapshot and continue from the failed step.",as(e),"",`Steps already completed by replay:
|
|
328
332
|
${(e.completedSteps??[]).map(o=>` \u2713 ${o}`).join(`
|
|
329
|
-
`)||" (none)"}`,"",`Failed step: [${e.failedStep?.kind}] ${e.failedStep?.text}`,`Failure: ${e.failedStep?.error}`,e.failedStep?.pageUrl?`Page when replay failed: ${e.failedStep.pageUrl}`:void 0,"","First diagnose: did the UI legitimately change (heal: adapt the actions, record via saffron_step + browser tools), or is the application broken (fail: saffron_done success=false with your diagnosis)?",
|
|
333
|
+
`)||" (none)"}`,"",`Failed step: [${e.failedStep?.kind}] ${e.failedStep?.text}`,`Failure: ${e.failedStep?.error}`,e.failedStep?.pageUrl?`Page when replay failed: ${e.failedStep.pageUrl}`:void 0,"","First diagnose: did the UI legitimately change (heal: adapt the actions, record via saffron_step + browser tools), or is the application broken (fail: saffron_done success=false with your diagnosis)?",Rh,e.assertionPolicy==="adaptable-mid"?"If the failed step is an [assertion:final]: you may re-verify the SAME condition once against the live page (timing), but if it does not hold AS WRITTEN, the run FAILS \u2014 call saffron_done success=false; never substitute it. If the failed step is a mid-scenario [assertion]: this project's policy allows adapting it \u2014 verify the equivalent condition on the legitimately-changed UI, record it via saffron_assert, and report the deviation via saffron_step's adaptation field plus featureEdits. An application defect still fails.":"If the failed step is an [assertion] or [assertion:final]: you may re-verify the SAME condition once against the live page (it may have been a timing issue). If the condition AS WRITTEN does not hold, the run FAILS \u2014 call saffron_done success=false. Do NOT substitute a different element, text, or URL that 'means the same thing'; suggesting a corrected assertion belongs in suggestedFeatureEdit of your failure report, never in saffron_assert.","Announce (saffron_step) and perform only the failed step and the steps after it. Earlier steps keep their recordings.",Gl(e));else if(e.mode==="record"&&e.recordOnly){let{from:o,to:i}=e.recordOnly;s.push("MODE: RECORD (segment). This scenario is being composed from existing recordings plus your work.",e.completedSteps&&e.completedSteps.length>0?`Already executed against the live browser (do NOT redo):
|
|
330
334
|
${e.completedSteps.map(a=>` \u2713 ${a}`).join(`
|
|
331
|
-
`)}`:"You are starting from a blank page.",
|
|
332
|
-
`),"",`The browser currently shows the state after those ${o} step(s) (verify with a snapshot if unsure). Do NOT redo them and do NOT navigate away from the current state.`,
|
|
333
|
-
`)}import{query as
|
|
334
|
-
`);if(!R.includes(Al))throw new Error(R.replace(/^### Error\s*/,"").trim()||"the browser backend did not start")}catch(m){throw await Promise.allSettled([T.close(),k?.close()]),b(!1),m}let v=Promise.resolve(),S=(m,w,g=t())=>{let R=v.then(()=>Yo(e,g,m,w));return v=R.catch(()=>{}),R},x=Gs(T,(m,w,g)=>S(sh(m,w),g),s.projectRoot),$=async()=>{let m=[...p];if(m.length===0)return;let w=Promise.all(m.map(R=>R.path().then(()=>!0,()=>!0))),g=!await Promise.race([w,ts(nh).then(()=>!1)]);g&&Ko++;try{g&&(await Promise.allSettled(m.map(R=>R.cancel())),await Promise.allSettled(m.map(R=>R.failure()))),await ts(0),await ts(0)}finally{g&&Ko--}};return{config:{type:"sdk",name:"playwright",instance:x},close:async()=>{await Promise.race([v,ts(th)]),await $().catch(()=>{}),await Promise.allSettled([T.close()]),await Promise.allSettled([k.close()]),await Promise.allSettled([x.close()]),b(!0)},grouped:(m,w)=>S(m,w)}}var ah=ih(import.meta.url);function ch(){let e=ah.resolve("@playwright/mcp/package.json");return Cl.join(Cl.dirname(e),"cli.js")}var lh=new Set(["mcp__playwright__browser_navigate","mcp__playwright__browser_click","mcp__playwright__browser_type","mcp__playwright__browser_fill_form","mcp__playwright__browser_select_option","mcp__playwright__browser_press_key"]),dh=new Set(["mcp__playwright__browser_snapshot","mcp__playwright__browser_find","mcp__playwright__browser_wait_for","mcp__playwright__browser_take_screenshot","mcp__playwright__browser_console_messages","mcp__playwright__browser_network_requests","mcp__playwright__browser_network_request","mcp__saffron__saffron_step","mcp__saffron__saffron_capture","mcp__saffron__saffron_dialog","mcp__saffron__saffron_wait_api","mcp__saffron__saffron_assert","mcp__saffron__saffron_done"]);function Zo(e,t){if(dh.has(e))return!1;if(e==="mcp__playwright__browser_tabs"){let n=t?.action;return!(n==="list"||n==="select"||n==="close")}return!0}var wn=class e{constructor(t,n){this.ctx=t;this.snapshotMode=n;this.state=new Wr(t.scenario,{firstStep:il(t),discardBeforeAnnounce:ol(t)})}ctx;snapshotMode;state;usage={aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0};resultText="";traced;capped;outputDir=wa();get projectRoot(){return this.ctx.projectRoot??process.cwd()}stopTabWatch;static async open(t,n,r){let s=new e(t,n);if(t.traceContext&&!r.traceBridgeUnavailable){let o=We(t.scenario);try{s.traced=await Il(t.traceContext,()=>s.currentStep(),n,i=>{let a=i instanceof Error?i.message:String(i);console.warn(`A promise rejected during the agent session and nothing handled it: ${it(a,o)}`)},{outputDir:s.outputDir,projectRoot:s.projectRoot})}catch(i){r.traceBridgeUnavailable=!0;let a=it(i instanceof Error?i.message:String(i),o);console.warn(`Agent tracing could not start (${a}). Continuing through the standard browser connection; agent calls will be absent from these traces.`)}}return s}currentStep(){let t=this.state.currentStepIndex,n=this.ctx.scenario.steps[t];return{index:t,title:n?`${n.keyword} ${n.text}`:"Agent exploration"}}async playwrightServer(){return this.traced?this.traced.config:(this.capped??=await va(this.playwrightStdio(),this.projectRoot),this.capped.config)}playwrightStdio(){return{command:process.execPath,args:[ch(),"--cdp-endpoint",this.ctx.cdpEndpoint,"--snapshot-mode",this.snapshotMode,"--image-responses","omit","--output-dir",this.outputDir]}}noteThePage(t){let n="note the page for the recording";return this.traced?this.traced.grouped(n,t):this.ctx.traceContext?Yo(this.ctx.traceContext,this.currentStep(),n,t):t()}async beforeTool(t,n){if(this.state.beginToolCall(t),lh.has(n)&&this.ctx.takeFingerprint&&!this.state.pendingFingerprint)try{this.state.pendingFingerprint=await this.noteThePage(this.ctx.takeFingerprint)}catch{}}afterTool(t,n,r,s){let o=pl(n,r);o&&this.state.addArmedAction(o);let i=fl(n,r,this.ctx.baseURL);if(i&&this.state.addActions([i]),n.startsWith("mcp__playwright__")){let a=al(s);a!==void 0&&this.ctx.onActiveTab?.(a),this.state.addActions(cl(s,this.ctx.baseURL)),this.state.pendingFingerprint=void 0}this.state.endToolCall(t,Zo(n,r))}failedTool(t,n,r){n.startsWith("mcp__playwright__")&&(this.state.pendingFingerprint=void 0),this.state.endToolCall(t,Zo(n,r))}watchTabs(){this.stopTabWatch=this.ctx.onTabOpened?.(()=>this.state.markTabOpened())}sessionError(t){if(this.state.done)return;let n=t instanceof Error?t.message:String(t);this.state.done=!0,this.state.success=!1,this.state.narrative=`Agent session error: ${n}`}async close(){this.stopTabWatch?.(),this.stopTabWatch=void 0,await this.traced?.close(),await this.capped?.close(),oh.rmSync(this.outputDir,{recursive:!0,force:!0})}result(){let{ctx:t,state:n}=this;return n.done||(n.success=!1,n.narrative=n.narrative||`Agent session ended without finalizing the run. Last output: ${this.resultText.slice(0,500)}`),{success:n.success,narrative:n.narrative,adaptations:[...n.adaptations,...n.attributionNotes()],suggestedFeatureEdit:n.suggestedFeatureEdit,featureEdits:n.featureEdits.map(r=>({index:r.index,text:At(r.text,t.scenario.params)})),recordedSteps:dl(n.steps,t.scenario,t.uniqueSeed),announcedSteps:[...n.announced].sort((r,s)=>r-s),usage:this.usage}}};var ns=class{constructor(t={}){this.opts=t}opts;planBefore;traceBridgeUnavailable=!1;async planUsage(){if(!this.planBefore)return;let t=await this.planBefore;if(!t)return;let n=await Rl();return{subscriptionType:t.subscriptionType,fiveHourBefore:t.utilization,fiveHourAfter:n?.utilization,resetsAt:n?.resetsAt??t.resetsAt}}async run(t){let n=await wn.open(t,this.opts.snapshotMode??"none",this),r;try{r=fh({prompt:Xr(t),options:{systemPrompt:Qr({deliberateSnapshots:n.snapshotMode==="none",adaptableMidAssertions:t.assertionPolicy==="adaptable-mid"}),model:t.model??this.opts.model,maxTurns:this.opts.maxTurns??100,tools:[],permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,persistSession:!1,settingSources:[],strictMcpConfig:!0,settings:{disableClaudeAiConnectors:!0},mcpServers:{playwright:await n.playwrightServer(),saffron:Yr(n.state)},hooks:{PreToolUse:[{hooks:[async s=>{let o=s;return await n.beforeTool(o.tool_use_id,o.tool_name),{continue:!0}}]}],PostToolUse:[{hooks:[async s=>{let o=s;return n.afterTool(o.tool_use_id,o.tool_name,o.tool_input,o.tool_response),{continue:!0}}]}],PostToolUseFailure:[{hooks:[async s=>{let o=s;return n.failedTool(o.tool_use_id,o.tool_name,o.tool_input),{continue:!0}}]}]}}})}catch(s){throw await n.close(),s}this.planBefore||(this.planBefore=Go(r)),n.watchTabs();try{for await(let s of r)s.type==="result"&&(n.usage.aiCalls=s.num_turns,n.usage.costUsd=s.total_cost_usd,"modelUsage"in s&&s.modelUsage&&(n.usage.models=Object.keys(s.modelUsage)),"usage"in s&&s.usage&&(n.usage.inputTokens=s.usage.input_tokens??0,n.usage.outputTokens=s.usage.output_tokens??0,n.usage.cacheReadTokens=s.usage.cache_read_input_tokens??0,n.usage.cacheCreationTokens=s.usage.cache_creation_input_tokens??0),s.subtype==="success"&&(n.resultText=s.result))}catch(s){n.sessionError(s)}finally{await n.close()}return n.result()}};import ph from"node:http";import{randomBytes as uh,randomUUID as gh,timingSafeEqual as hh}from"node:crypto";import{Client as mh}from"@modelcontextprotocol/sdk/client/index.js";import{InMemoryTransport as yh}from"@modelcontextprotocol/sdk/inMemory.js";import{Server as wh}from"@modelcontextprotocol/sdk/server/index.js";import{StreamableHTTPServerTransport as bh}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as vh,ListToolsRequestSchema as Sh}from"@modelcontextprotocol/sdk/types.js";async function xh(e,t){let n=uh(16).toString("hex"),r=Buffer.from(`Bearer ${n}`),s=c=>{let l=Buffer.from(c??"");return l.length===r.length&&hh(l,r)},o=(c,l)=>{let d=new wh({name:c,version:"1"},{capabilities:{tools:{}}});return d.setRequestHandler(Sh,p=>l.listTools(p.params)),d.setRequestHandler(vh,async p=>{let u=gh(),f=`mcp__${c}__${p.params.name}`,y=p.params.arguments??{};await t.beforeTool(u,f);try{let b=await l.callTool(p.params,void 0,{timeout:Vs});return b.isError?t.failedTool(u,f,y):t.afterTool(u,f,y,b),b}catch(b){throw t.failedTool(u,f,y),b}}),d},i=ph.createServer(async(c,l)=>{let d=(c.url??"").split("?")[0].slice(1),p=s(c.headers.authorization)?e[d]:void 0;if(!p)return void l.writeHead(404).end();if(c.method!=="POST")return void l.writeHead(405,{Allow:"POST"}).end();let u=o(d,p),f=new bh({sessionIdGenerator:void 0,enableJsonResponse:!0});l.on("close",()=>{Promise.allSettled([f.close(),u.close()])});try{await u.connect(f),await f.handleRequest(c,l)}catch{l.headersSent||l.writeHead(500).end()}});i.requestTimeout=0,await new Promise((c,l)=>{i.once("error",l),i.listen(0,"127.0.0.1",()=>c())});let{port:a}=i.address();return{urls:Object.fromEntries(Object.keys(e).map(c=>[c,`http://127.0.0.1:${a}/${c}`])),token:n,close:async()=>{i.closeAllConnections(),await new Promise(c=>i.close(()=>c()))}}}async function Pl(e){let[t,n]=yh.createLinkedPair();await e.connect(n);let r=new mh({name:"saffron-gateway",version:"1"});return await r.connect(t),r}async function Ol(e){let t=[];try{let n=await Pl((await e.playwrightServer()).instance);t.push(n);let r=await Pl(Yr(e.state).instance);t.push(r);let s=await xh({playwright:n,saffron:r},e);return{urls:s.urls,token:s.token,close:async()=>{await s.close(),await Promise.allSettled(t.map(o=>o.close()))}}}catch(n){throw await Promise.allSettled(t.map(r=>r.close())),n}}var rs=class{constructor(t,n={},r=()=>{}){this.drive=t;this.opts=n;this.blocker=r}drive;opts;blocker;traceBridgeUnavailable=!1;async run(t){let n=this.blocker();if(n)throw new Error(n);let r=await wn.open(t,this.opts.snapshotMode??"none",this),s;try{s=await Ol(r)}catch(o){throw await r.close(),o}r.watchTabs();try{await this.drive({systemPrompt:Qr({deliberateSnapshots:r.snapshotMode==="none",adaptableMidAssertions:t.assertionPolicy==="adaptable-mid"}),prompt:Xr(t),model:t.model??this.opts.model,maxTurns:this.opts.maxTurns??100,mcpServers:s.urls,mcpToken:s.token,usage:r.usage,lastOutput:o=>{r.resultText=o},finished:()=>r.state.done})}catch(o){r.sessionError(o)}finally{await s.close(),await r.close()}return r.result()}};async function Yn(e,t){try{return await import(e)}catch(n){let r=n.code;throw(r==="ERR_MODULE_NOT_FOUND"||r==="MODULE_NOT_FOUND")&&String(n.message).includes(`'${e}'`)?new Error(`the ${t} provider needs ${e}: npm install --save-dev ${e}`):n}}function bn(e){return`stopped after ${e} tool calls, the session's turn limit: raise maxTurns in saffron.config.json, or look at what the agent kept retrying`}import vn from"node:fs";import Qo from"node:os";import nt from"node:path";import{createHash as $h}from"node:crypto";import{createRequire as jl}from"node:module";function kh(){try{let e=jl(import.meta.resolve("@openai/codex-sdk")).resolve("@openai/codex/package.json"),t=jl(e).resolve(`@openai/codex-${process.platform}-${process.arch}/package.json`),n=nt.join(nt.dirname(t),"vendor");for(let r of vn.readdirSync(n))for(let s of[nt.join(n,r,"bin","codex"),nt.join(n,r,"codex","codex")])if(vn.existsSync(s))return s}catch{}}function ss(e=process.platform){return e==="win32"?"the codex provider is not available on Windows yet: Saffron must run Codex without your ~/.codex/config.toml (your own MCP servers, plugins and hooks), and cannot on Windows":void 0}function Th(e){return`'${e.replaceAll("'","'\\''")}'`}function Rh(){let e=ss();if(e)throw new Error(e);let t=kh();if(!t)throw new Error("the Codex binary is missing from @openai/codex-sdk's install: reinstall it with npm install --save-dev @openai/codex-sdk");let n=nt.join(process.env.XDG_CACHE_HOME||nt.join(Qo.homedir(),".cache"),"saffron");vn.mkdirSync(n,{recursive:!0});let r=nt.join(n,`codex-${$h("sha256").update(t).digest("hex").slice(0,12)}`);return be(r,`#!/bin/sh
|
|
335
|
+
`)}`:"You are starting from a blank page.",as(e),"",`Record ONLY steps ${o} through ${i} (inclusive).`,`CRITICAL STOP RULE: the steps AFTER step ${i} already have recordings and will be replayed automatically the moment you stop. After completing step ${i}, immediately call saffron_done \u2014 do NOT perform, verify, or navigate into any later step. Executing a later step yourself would make the automatic replay run it TWICE.`)}else if(e.completedSteps&&e.completedSteps.length>0){let o=e.completedSteps.length;s.push("MODE: RECORD (seeded). No cache exists for this scenario yet, but its first steps matched existing recordings and were ALREADY EXECUTED against the live browser by zero-AI replay:",e.completedSteps.map(i=>` \u2713 ${i}`).join(`
|
|
336
|
+
`),"",`The browser currently shows the state after those ${o} step(s) (verify with a snapshot if unsure). Do NOT redo them and do NOT navigate away from the current state.`,as(e),`Start with saffron_step for step index ${o} and record from there to the end.`)}else s.push("MODE: RECORD. No cache exists for this scenario yet.","Execute every step in order, starting at step 0. Navigate to the base URL first if the scenario implies a starting page.");return s.filter(o=>o!==void 0).join(`
|
|
337
|
+
`)}import{query as Th}from"@anthropic-ai/claude-agent-sdk";var Eh="usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET";async function oi(e,t=8e3){let n=e?.[Eh];if(typeof n!="function")return;let r;try{let s=await Promise.race([n.call(e),new Promise(o=>{r=setTimeout(()=>o(void 0),t),r.unref?.()})]);return Ah(s)}catch{return}finally{r&&clearTimeout(r)}}function Ah(e){if(!e||!e.rate_limits_available||!e.subscription_type)return;let t=e.rate_limits?.five_hour;return{subscriptionType:e.subscription_type,utilization:typeof t?.utilization=="number"?t.utilization:void 0,resetsAt:t?.resets_at??void 0}}async function Kl(){let e=()=>{},t=new Promise(s=>e=s);async function*n(){await t}let r;try{let s=Th({prompt:n(),options:{maxTurns:1,tools:[],settingSources:[],persistSession:!1}});r=s;let o=(async()=>{try{for await(let a of s);}catch{}})(),i=await oi(s);return e(),r.close?.(),await o,i}catch{e(),r?.close?.();return}}import Fh from"node:fs";import ed from"node:path";import{createRequire as Mh}from"node:module";import{createRequire as Yl}from"node:module";var _h=Yl(import.meta.url),ds=Yl(_h.resolve("playwright/package.json"));import{Client as Ih}from"@modelcontextprotocol/sdk/client/index.js";import{InMemoryTransport as Ch}from"@modelcontextprotocol/sdk/inMemory.js";var Ph=1e4,Oh=5e3,Zl="saffron_connection_check",fs=e=>new Promise(t=>{setTimeout(t,e).unref()}),sr=new Set,ii=0,Ql=e=>{ii===0&&[...sr].at(-1)?.(e)};function jh(e){let t=n=>e(n);return sr.size===0&&process.on("unhandledRejection",Ql),sr.add(t),()=>{sr.delete(t)&&sr.size===0&&process.off("unhandledRejection",Ql)}}async function ai(e,t,n,r){await e.tracing.group(`[saffron:agent:${t.index}] ${t.title}`).catch(()=>{});try{await e.tracing.group(n).catch(()=>{});try{return await r()}finally{await e.tracing.groupEnd().catch(()=>{})}}finally{await e.tracing.groupEnd().catch(()=>{})}}function Nh(e,t={}){let n=o=>typeof o=="string"&&o.trim()?o.trim():void 0,r=n(t.element)??"an element",s=(()=>{switch(e){case"browser_snapshot":return"read the page";case"browser_find":return n(t.text)?`find "${n(t.text)}" on the page`:n(t.regex)?`find ${n(t.regex)} on the page`:"search the page";case"browser_click":return`${t.doubleClick?"double-click":"click"} ${r}`;case"browser_hover":return`hover ${r}`;case"browser_type":return`type into ${r}`;case"browser_fill_form":return"fill in the form";case"browser_select_option":return`select in ${r}`;case"browser_press_key":return n(t.key)?`press ${n(t.key)}`:"press a key";case"browser_navigate":return n(t.url)?`go to ${n(t.url)}`:"navigate";case"browser_navigate_back":return"go back";case"browser_wait_for":return n(t.text)?`wait for "${n(t.text)}"`:n(t.textGone)?`wait for "${n(t.textGone)}" to go`:`wait ${t.time??""}s`.replace(" s","");case"browser_tabs":return n(t.action)?`tabs: ${n(t.action)}`:"list the tabs";case"browser_drag":return`drag ${n(t.startElement)??"an element"} to ${n(t.endElement)??"an element"}`;case"browser_file_upload":return"upload files";case"browser_handle_dialog":return`${t.accept?"accept":"dismiss"} the dialog`;case"browser_evaluate":case"browser_run_code":case"browser_run_code_unsafe":return"run a script in the page";case"browser_take_screenshot":return"take a screenshot";case"browser_console_messages":return"read the console";case"browser_network_requests":return"read the network log";default:return}})();return s?`${s} \xB7 ${e}`:e}async function Xl(e,t,n="none",r=()=>{},s={}){let{createConnection:o,resolveCLIConfigForMCP:i}=ds("playwright-core/lib/coreBundle").tools,a=await i?.({},process.env)??{},c={...a,browser:{...a.browser,isolated:!1},sharedBrowserContext:!0,imageResponses:"omit",...s.outputDir?{outputDir:s.outputDir}:{},snapshot:{...a.snapshot,mode:n}},l=e.browser(),d=new Set(l?.listeners("disconnected")??[]),p=new Set,u=R=>{p.add(R)},f=R=>{R.on("download",u)};for(let R of e.pages())f(R);e.on("page",f);let h=jh(r),w=R=>{e.off("page",f);for(let E of e.pages())E.off("download",u);for(let E of l?.listeners("disconnected")??[])d.has(E)||l.off("disconnected",E);if(!R)return h();let m=()=>{clearTimeout(T),e.off("close",g),h()},g=()=>{setTimeout(m,1e3).unref()},T=setTimeout(m,3e5);T.unref(),e.on("close",g)},$,k=new Ih({name:"saffron-trace",version:"1"});try{$=await o(c,async()=>e);let[R,m]=Ch.createLinkedPair();await $.connect(m),await k.connect(R);let T=((await k.callTool({name:Zl,arguments:{}})).content??[]).map(E=>E.text??"").join(`
|
|
338
|
+
`);if(!T.includes(Zl))throw new Error(T.replace(/^### Error\s*/,"").trim()||"the browser backend did not start")}catch(R){throw await Promise.allSettled([k.close(),$?.close()]),w(!1),R}let y=Promise.resolve(),v=(R,m,g=t())=>{let T=y.then(()=>ai(e,g,R,m));return y=T.catch(()=>{}),T},S=oo(k,(R,m,g)=>v(Nh(R,m),g),s.projectRoot),x=async()=>{let R=[...p];if(R.length===0)return;let m=Promise.all(R.map(T=>T.path().then(()=>!0,()=>!0))),g=!await Promise.race([m,fs(Oh).then(()=>!1)]);g&&ii++;try{g&&(await Promise.allSettled(R.map(T=>T.cancel())),await Promise.allSettled(R.map(T=>T.failure()))),await fs(0),await fs(0)}finally{g&&ii--}};return{config:{type:"sdk",name:"playwright",instance:S},close:async()=>{await Promise.race([y,fs(Ph)]),await x().catch(()=>{}),await Promise.allSettled([k.close()]),await Promise.allSettled([$.close()]),await Promise.allSettled([S.close()]),w(!0)},grouped:(R,m)=>v(R,m)}}var Lh=Mh(import.meta.url);function Dh(){let e=Lh.resolve("@playwright/mcp/package.json");return ed.join(ed.dirname(e),"cli.js")}var Bh=new Set(["mcp__playwright__browser_navigate","mcp__playwright__browser_click","mcp__playwright__browser_type","mcp__playwright__browser_fill_form","mcp__playwright__browser_select_option","mcp__playwright__browser_press_key"]),Uh=new Set(["mcp__playwright__browser_snapshot","mcp__playwright__browser_find","mcp__playwright__browser_wait_for","mcp__playwright__browser_take_screenshot","mcp__playwright__browser_console_messages","mcp__playwright__browser_network_requests","mcp__playwright__browser_network_request","mcp__saffron__saffron_step","mcp__saffron__saffron_capture","mcp__saffron__saffron_dialog","mcp__saffron__saffron_wait_api","mcp__saffron__saffron_assert","mcp__saffron__saffron_done"]);function ci(e,t){if(Uh.has(e))return!1;if(e==="mcp__playwright__browser_tabs"){let n=t?.action;return!(n==="list"||n==="select"||n==="close")}return!0}var Tn=class e{constructor(t,n){this.ctx=t;this.snapshotMode=n;this.state=new rs(t.scenario,{firstStep:_l(t),discardBeforeAnnounce:Al(t)})}ctx;snapshotMode;state;usage={aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0};resultText="";traced;capped;outputDir=ja();get projectRoot(){return this.ctx.projectRoot??process.cwd()}stopTabWatch;static async open(t,n,r){let s=new e(t,n);if(t.traceContext&&!r.traceBridgeUnavailable){let o=Ze(t.scenario);try{s.traced=await Xl(t.traceContext,()=>s.currentStep(),n,i=>{let a=i instanceof Error?i.message:String(i);console.warn(`A promise rejected during the agent session and nothing handled it: ${dt(a,o)}`)},{outputDir:s.outputDir,projectRoot:s.projectRoot})}catch(i){r.traceBridgeUnavailable=!0;let a=dt(i instanceof Error?i.message:String(i),o);console.warn(`Agent tracing could not start (${a}). Continuing through the standard browser connection; agent calls will be absent from these traces.`)}}return s}currentStep(){let t=this.state.currentStepIndex,n=this.ctx.scenario.steps[t];return{index:t,title:n?`${n.keyword} ${n.text}`:"Agent exploration"}}async playwrightServer(){return this.traced?this.traced.config:(this.capped??=await Fa(this.playwrightStdio(),this.projectRoot),this.capped.config)}playwrightStdio(){return{command:process.execPath,args:[Dh(),"--cdp-endpoint",this.ctx.cdpEndpoint,"--snapshot-mode",this.snapshotMode,"--image-responses","omit","--output-dir",this.outputDir]}}noteThePage(t){let n="note the page for the recording";return this.traced?this.traced.grouped(n,t):this.ctx.traceContext?ai(this.ctx.traceContext,this.currentStep(),n,t):t()}async beforeTool(t,n){if(this.state.beginToolCall(t),Bh.has(n)&&this.ctx.takeFingerprint&&!this.state.pendingFingerprint)try{this.state.pendingFingerprint=await this.noteThePage(this.ctx.takeFingerprint)}catch{}}afterTool(t,n,r,s){let o=Nl(n,r);o&&this.state.addArmedAction(o);let i=jl(n,r,this.ctx.baseURL);if(i&&this.state.addActions([i]),n.startsWith("mcp__playwright__")){let a=Il(s);a!==void 0&&this.ctx.onActiveTab?.(a),this.state.addActions(Cl(s,this.ctx.baseURL)),this.state.pendingFingerprint=void 0}this.state.endToolCall(t,ci(n,r))}failedTool(t,n,r){n.startsWith("mcp__playwright__")&&(this.state.pendingFingerprint=void 0),this.state.endToolCall(t,ci(n,r))}watchTabs(){this.stopTabWatch=this.ctx.onTabOpened?.(()=>this.state.markTabOpened())}sessionError(t){if(this.state.done)return;let n=t instanceof Error?t.message:String(t);this.state.done=!0,this.state.success=!1,this.state.narrative=`Agent session error: ${n}`}async close(){this.stopTabWatch?.(),this.stopTabWatch=void 0,await this.traced?.close(),await this.capped?.close(),Fh.rmSync(this.outputDir,{recursive:!0,force:!0})}result(){let{ctx:t,state:n}=this;return n.done||(n.success=!1,n.narrative=n.narrative||`Agent session ended without finalizing the run. Last output: ${this.resultText.slice(0,500)}`),{success:n.success,narrative:n.narrative,adaptations:[...n.adaptations,...n.attributionNotes()],suggestedFeatureEdit:n.suggestedFeatureEdit,featureEdits:n.featureEdits.map(r=>({index:r.index,text:Ot(r.text,t.scenario.params)})),recordedSteps:Ol(n.steps,t.scenario,t.uniqueSeed),announcedSteps:[...n.announced].sort((r,s)=>r-s),usage:this.usage}}};var ps=class{constructor(t={}){this.opts=t}opts;planBefore;traceBridgeUnavailable=!1;async planUsage(){if(!this.planBefore)return;let t=await this.planBefore;if(!t)return;let n=await Kl();return{subscriptionType:t.subscriptionType,fiveHourBefore:t.utilization,fiveHourAfter:n?.utilization,resetsAt:n?.resetsAt??t.resetsAt}}async run(t){let n=await Tn.open(t,this.opts.snapshotMode??"none",this),r;try{r=zh({prompt:ls(t),options:{systemPrompt:cs({deliberateSnapshots:n.snapshotMode==="none",adaptableMidAssertions:t.assertionPolicy==="adaptable-mid"}),model:t.model??this.opts.model,maxTurns:this.opts.maxTurns??100,tools:[],permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,persistSession:!1,settingSources:[],strictMcpConfig:!0,settings:{disableClaudeAiConnectors:!0},mcpServers:{playwright:await n.playwrightServer(),saffron:is(n.state)},hooks:{PreToolUse:[{hooks:[async s=>{let o=s;return await n.beforeTool(o.tool_use_id,o.tool_name),{continue:!0}}]}],PostToolUse:[{hooks:[async s=>{let o=s;return n.afterTool(o.tool_use_id,o.tool_name,o.tool_input,o.tool_response),{continue:!0}}]}],PostToolUseFailure:[{hooks:[async s=>{let o=s;return n.failedTool(o.tool_use_id,o.tool_name,o.tool_input),{continue:!0}}]}]}}})}catch(s){throw await n.close(),s}this.planBefore||(this.planBefore=oi(r)),n.watchTabs();try{for await(let s of r)s.type==="result"&&(n.usage.aiCalls=s.num_turns,n.usage.costUsd=s.total_cost_usd,"modelUsage"in s&&s.modelUsage&&(n.usage.models=Object.keys(s.modelUsage)),"usage"in s&&s.usage&&(n.usage.inputTokens=s.usage.input_tokens??0,n.usage.outputTokens=s.usage.output_tokens??0,n.usage.cacheReadTokens=s.usage.cache_read_input_tokens??0,n.usage.cacheCreationTokens=s.usage.cache_creation_input_tokens??0),s.subtype==="success"&&(n.resultText=s.result))}catch(s){n.sessionError(s)}finally{await n.close()}return n.result()}};import Hh from"node:http";import{randomBytes as qh,randomUUID as Jh,timingSafeEqual as Wh}from"node:crypto";import{Client as Vh}from"@modelcontextprotocol/sdk/client/index.js";import{InMemoryTransport as Gh}from"@modelcontextprotocol/sdk/inMemory.js";import{Server as Kh}from"@modelcontextprotocol/sdk/server/index.js";import{StreamableHTTPServerTransport as Yh}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as Zh,ListToolsRequestSchema as Qh}from"@modelcontextprotocol/sdk/types.js";async function Xh(e,t){let n=qh(16).toString("hex"),r=Buffer.from(`Bearer ${n}`),s=c=>{let l=Buffer.from(c??"");return l.length===r.length&&Wh(l,r)},o=(c,l)=>{let d=new Kh({name:c,version:"1"},{capabilities:{tools:{}}});return d.setRequestHandler(Qh,p=>l.listTools(p.params)),d.setRequestHandler(Zh,async p=>{let u=Jh(),f=`mcp__${c}__${p.params.name}`,h=p.params.arguments??{};await t.beforeTool(u,f);try{let w=await l.callTool(p.params,void 0,{timeout:ro});return w.isError?t.failedTool(u,f,h):t.afterTool(u,f,h,w),w}catch(w){throw t.failedTool(u,f,h),w}}),d},i=Hh.createServer(async(c,l)=>{let d=(c.url??"").split("?")[0].slice(1),p=s(c.headers.authorization)?e[d]:void 0;if(!p)return void l.writeHead(404).end();if(c.method!=="POST")return void l.writeHead(405,{Allow:"POST"}).end();let u=o(d,p),f=new Yh({sessionIdGenerator:void 0,enableJsonResponse:!0});l.on("close",()=>{Promise.allSettled([f.close(),u.close()])});try{await u.connect(f),await f.handleRequest(c,l)}catch{l.headersSent||l.writeHead(500).end()}});i.requestTimeout=0,await new Promise((c,l)=>{i.once("error",l),i.listen(0,"127.0.0.1",()=>c())});let{port:a}=i.address();return{urls:Object.fromEntries(Object.keys(e).map(c=>[c,`http://127.0.0.1:${a}/${c}`])),token:n,close:async()=>{i.closeAllConnections(),await new Promise(c=>i.close(()=>c()))}}}async function td(e){let[t,n]=Gh.createLinkedPair();await e.connect(n);let r=new Vh({name:"saffron-gateway",version:"1"});return await r.connect(t),r}async function nd(e){let t=[];try{let n=await td((await e.playwrightServer()).instance);t.push(n);let r=await td(is(e.state).instance);t.push(r);let s=await Xh({playwright:n,saffron:r},e);return{urls:s.urls,token:s.token,close:async()=>{await s.close(),await Promise.allSettled(t.map(o=>o.close()))}}}catch(n){throw await Promise.allSettled(t.map(r=>r.close())),n}}var us=class{constructor(t,n={},r=()=>{}){this.drive=t;this.opts=n;this.blocker=r}drive;opts;blocker;traceBridgeUnavailable=!1;async run(t){let n=this.blocker();if(n)throw new Error(n);let r=await Tn.open(t,this.opts.snapshotMode??"none",this),s;try{s=await nd(r)}catch(o){throw await r.close(),o}r.watchTabs();try{await this.drive({systemPrompt:cs({deliberateSnapshots:r.snapshotMode==="none",adaptableMidAssertions:t.assertionPolicy==="adaptable-mid"}),prompt:ls(t),model:t.model??this.opts.model,maxTurns:this.opts.maxTurns??100,mcpServers:s.urls,mcpToken:s.token,usage:r.usage,lastOutput:o=>{r.resultText=o},finished:()=>r.state.done})}catch(o){r.sessionError(o)}finally{await s.close(),await r.close()}return r.result()}};async function or(e,t){try{return await import(e)}catch(n){let r=n.code;throw(r==="ERR_MODULE_NOT_FOUND"||r==="MODULE_NOT_FOUND")&&String(n.message).includes(`'${e}'`)?new Error(`the ${t} provider needs ${e}: npm install --save-dev ${e}`):n}}function En(e){return`stopped after ${e} tool calls, the session's turn limit: raise maxTurns in saffron.config.json, or look at what the agent kept retrying`}import An from"node:fs";import li from"node:os";import it from"node:path";import{createHash as em}from"node:crypto";import{createRequire as rd}from"node:module";function tm(){try{let e=rd(import.meta.resolve("@openai/codex-sdk")).resolve("@openai/codex/package.json"),t=rd(e).resolve(`@openai/codex-${process.platform}-${process.arch}/package.json`),n=it.join(it.dirname(t),"vendor");for(let r of An.readdirSync(n))for(let s of[it.join(n,r,"bin","codex"),it.join(n,r,"codex","codex")])if(An.existsSync(s))return s}catch{}}function gs(e=process.platform){return e==="win32"?"the codex provider is not available on Windows yet: Saffron must run Codex without your ~/.codex/config.toml (your own MCP servers, plugins and hooks), and cannot on Windows":void 0}function nm(e){return`'${e.replaceAll("'","'\\''")}'`}function rm(){let e=gs();if(e)throw new Error(e);let t=tm();if(!t)throw new Error("the Codex binary is missing from @openai/codex-sdk's install: reinstall it with npm install --save-dev @openai/codex-sdk");let n=it.join(process.env.XDG_CACHE_HOME||it.join(li.homedir(),".cache"),"saffron");An.mkdirSync(n,{recursive:!0});let r=it.join(n,`codex-${em("sha256").update(t).digest("hex").slice(0,12)}`);return Te(r,`#!/bin/sh
|
|
335
339
|
sub="$1"; shift
|
|
336
|
-
exec ${
|
|
337
|
-
`,493),r}var
|
|
338
|
-
`,c)}catch(l){let d=l.code;throw!i||!["EACCES","EPERM","EROFS"].includes(d??"")?l:new Error(`${e} links to ${a}, which Saffron cannot write: add ${n.join(" and ")} to permissions.allow there, then run npx saffron login antigravity again`)}return n}function
|
|
339
|
-
`).at(-1)||(t.error?.message??"no answer");throw new Error(`agy could not list your models (${r}): run agy once and sign in with your Google AI Pro or Ultra account`)}let n=
|
|
340
|
+
exec ${nm(t)} "$sub" --ignore-user-config --ephemeral "$@"
|
|
341
|
+
`,493),r}var sd="SAFFRON_MCP_TOKEN",sm=["cli_auth_credentials_store","forced_login_method","forced_chatgpt_workspace_id"];function om(e){let t=e.split(/^\s*\[/m)[0],n={};for(let r of sm){let s=new RegExp(`^\\s*${r}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`,"m").exec(t);s&&(n[r]=s[1]??s[2])}return n}function di(){try{return om(An.readFileSync(it.join(process.env.CODEX_HOME??it.join(li.homedir(),".codex"),"config.toml"),"utf8"))}catch{return{}}}var od=async e=>{let{Codex:t}=await or("@openai/codex-sdk","codex"),n=An.mkdtempSync(it.join(li.tmpdir(),"saffron-codex-"));try{let r=Object.fromEntries(Object.entries(process.env).filter(l=>l[1]!==void 0)),o=new t({codexPathOverride:rm(),env:{...r,[sd]:e.mcpToken},config:{...di(),developer_instructions:e.systemPrompt,include_permissions_instructions:!1,include_apps_instructions:!1,include_collaboration_mode_instructions:!1,include_environment_context:!1,project_doc_max_bytes:0,skills:{include_instructions:!1},mcp_servers:Object.fromEntries(Object.entries(e.mcpServers).map(([l,d])=>[l,{url:d,bearer_token_env_var:sd,required:!0,default_tools_approval_mode:"approve",startup_timeout_sec:30,tool_timeout_sec:600}])),features:{shell_tool:!1,view_image:!1,apps:!1,plugins:!1,hooks:!1,memories:!1,goals:!1,image_generation:!1,tool_suggest:!1,browser_use:!1,computer_use:!1,unified_exec:!1,multi_agent:!1,code_mode_host:!1,in_app_browser:!1,browser_use_external:!1}}}).startThread({model:e.model,workingDirectory:n,skipGitRepoCheck:!0,sandboxMode:"read-only",approvalPolicy:"never",webSearchMode:"disabled"}),i=new AbortController,a=0,c;try{let{events:l}=await o.runStreamed(e.prompt,{signal:i.signal});for await(let d of l)if(d.type==="item.started"&&d.item.type==="mcp_tool_call")++a>e.maxTurns&&!i.signal.aborted&&(c=En(e.maxTurns),i.abort());else if(d.type==="item.completed")(d.item.type==="mcp_tool_call"||d.item.type==="agent_message")&&e.usage.aiCalls++,d.item.type==="agent_message"&&e.lastOutput(d.item.text);else if(d.type==="turn.completed"){let p=d.usage;e.usage.inputTokens=p.input_tokens-p.cached_input_tokens,e.usage.cacheReadTokens=p.cached_input_tokens,e.usage.cacheCreationTokens=p.cache_write_input_tokens??0,e.usage.outputTokens=p.output_tokens}else d.type==="turn.failed"&&!i.signal.aborted?c=d.error.message:d.type==="error"&&!i.signal.aborted&&(c??=d.message)}catch(l){if(!i.signal.aborted&&!c)throw l}if(e.usage.models=[`codex/${e.model??"default"}`],c&&!e.finished()){let l=/auth|log ?in|401|unauthori[sz]ed/i.test(c)?". Sign in with your ChatGPT plan: npx @openai/codex login":"";throw new Error(`Codex: ${c}${l}`)}}finally{An.rmSync(n,{recursive:!0,force:!0})}};import{spawn as im,spawnSync as am}from"node:child_process";import pe from"node:fs";import ms from"node:os";import me from"node:path";import cm from"node:readline";var hs="install the Antigravity CLI (curl -fsSL https://antigravity.google/cli/install.sh | bash), then run `agy` once to sign in with your Google account";function ys(){for(let e of[...(process.env.PATH??"").split(me.delimiter),me.join(ms.homedir(),".local","bin")]){let t=me.join(e,process.platform==="win32"?"agy.exe":"agy");if(e&&pe.existsSync(t))return t}}var _n={playwright:"saffron_browser",saffron:"saffron_tools"},id=Object.values(_n).map(e=>`mcp(${e}/*)`),fi=()=>me.join(ms.homedir(),".gemini","antigravity-cli","settings.json");function ad(e){if(!pe.existsSync(e))return{};try{let t=JSON.parse(pe.readFileSync(e,"utf8"));if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}throw new Error(`${e} is not a JSON object Saffron can add to: fix it (or ask agy to rewrite it), then run npx saffron login antigravity again`)}function ws(e=fi()){let t;try{t=ad(e).permissions?.allow}catch{return id}return id.filter(n=>!(Array.isArray(t)&&t.includes(n)))}function lm(e=fi()){let t=ad(e),n=ws(e);if(n.length===0)return[];let r=t.permissions&&typeof t.permissions=="object"?t.permissions:{},s=Array.isArray(r.allow)?r.allow:[],o={...t,permissions:{...r,allow:[...s,...n]}},i=pe.lstatSync(e,{throwIfNoEntry:!1})?.isSymbolicLink()??!1,a=dm(e),c=pe.existsSync(a)?pe.statSync(a).mode&4095:void 0;try{Te(a,JSON.stringify(o,null,2)+`
|
|
342
|
+
`,c)}catch(l){let d=l.code;throw!i||!["EACCES","EPERM","EROFS"].includes(d??"")?l:new Error(`${e} links to ${a}, which Saffron cannot write: add ${n.join(" and ")} to permissions.allow there, then run npx saffron login antigravity again`)}return n}function dm(e){let t=e;for(let n=0;n<40&&pe.lstatSync(t,{throwIfNoEntry:!1})?.isSymbolicLink();n++)t=me.resolve(pe.realpathSync(me.dirname(t)),pe.readlinkSync(t));return pe.existsSync(t)?pe.realpathSync(t):t}async function cd(){let e=ys();if(!e)throw new Error(`the antigravity provider needs the agy command: ${hs}`);let t=am(e,["models"],{encoding:"utf8",timeout:6e4});if(t.status!==0){let r=`${t.stderr??""}${t.stdout??""}`.trim().split(`
|
|
343
|
+
`).at(-1)||(t.error?.message??"no answer");throw new Error(`agy could not list your models (${r}): run agy once and sign in with your Google AI Pro or Ultra account`)}let n=lm();console.log(n.length>0?`Antigravity: allowed Saffron's tools in ${fi()}: ${n.join(", ")}. Remove those lines to take it back.`:"Antigravity: Saffron's tools are already allowed.")}var ld=me.join(ms.homedir(),".gemini","antigravity-cli","mcp"),fm=Object.values(_n).map(e=>me.join(ld,e)),pm=`const path=require("path");const DIRS=${JSON.stringify(fm)};const SERVERS=${JSON.stringify(Object.values(_n))};
|
|
340
344
|
let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{let t={};try{t=JSON.parse(s).toolCall||{}}catch{}const a=t.args||{};
|
|
341
345
|
const file=typeof a.AbsolutePath==="string"?path.resolve(a.AbsolutePath):"";
|
|
342
346
|
const dir=typeof a.DirectoryPath==="string"?path.resolve(a.DirectoryPath):"";
|
|
343
347
|
const ok=(t.name==="call_mcp_tool"&&SERVERS.includes(a.ServerName))||(t.name==="view_file"&&DIRS.includes(path.dirname(file)))||(t.name==="list_dir"&&DIRS.includes(dir));
|
|
344
|
-
process.stdout.write(JSON.stringify(ok?{decision:"allow"}:{decision:"deny",reason:"Only Saffron's browser and saffron tools are available in a Saffron session."}))})`,
|
|
348
|
+
process.stdout.write(JSON.stringify(ok?{decision:"allow"}:{decision:"deny",reason:"Only Saffron's browser and saffron tools are available in a Saffron session."}))})`,um=(e,t)=>`let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{let i=0;try{i=JSON.parse(s).invocationNum}catch{}
|
|
345
349
|
const stop=i+1>=${e};if(stop)require("fs").writeFileSync(${JSON.stringify(t)},"");
|
|
346
|
-
process.stdout.write(JSON.stringify(stop?{terminationBehavior:"terminate"}:{}))})`,
|
|
350
|
+
process.stdout.write(JSON.stringify(stop?{terminationBehavior:"terminate"}:{}))})`,dd=async e=>{let t=ys();if(!t)throw new Error(`the antigravity provider needs the agy command: ${hs}`);if(Object.keys(e.mcpServers).length>0&&ws().length>0)throw new Error("agy does not allow Saffron's tools yet: run npx saffron login antigravity once");let n=pe.mkdtempSync(me.join(ms.tmpdir(),"saffron-agy-"));try{let r=me.join(n,".agents");pe.mkdirSync(me.join(r,"agents"),{recursive:!0}),pe.writeFileSync(me.join(r,"agents","saffron.md"),`---
|
|
347
351
|
name: saffron
|
|
348
352
|
description: Saffron's browser test agent.
|
|
349
353
|
mainAgent: true
|
|
@@ -353,15 +357,15 @@ commandExecutionPolicy: off
|
|
|
353
357
|
|
|
354
358
|
${e.systemPrompt}
|
|
355
359
|
|
|
356
|
-
Your tools are MCP tools, called with call_mcp_tool: the browser_* tools are on the ${
|
|
357
|
-
`),
|
|
358
|
-
`).at(-1)||`agy exited with ${
|
|
360
|
+
Your tools are MCP tools, called with call_mcp_tool: the browser_* tools are on the ${_n.playwright} server and the saffron_* tools on the ${_n.saffron} server. Before a tool's first call, read its parameters with view_file from ${me.join(ld,"<server>","<tool>.json")}. No other tool is available.
|
|
361
|
+
`),pe.writeFileSync(me.join(r,"mcp_config.json"),JSON.stringify({mcpServers:Object.fromEntries(Object.entries(e.mcpServers).map(([$,k])=>[_n[$]??$,{serverUrl:k,headers:{Authorization:`Bearer ${e.mcpToken}`}}]))}));let s=($,k)=>{let y=me.join(n,$);return pe.writeFileSync(y,k),`${JSON.stringify(process.execPath)} ${JSON.stringify(y)}`};pe.writeFileSync(me.join(r,"hooks.json"),JSON.stringify({"saffron-gate":{PreToolUse:[{matcher:"",hooks:[{type:"command",command:s("gate.cjs",pm)}]}]},"saffron-turns":{PostInvocation:[{type:"command",command:s("turns.cjs",um(e.maxTurns,me.join(n,"turn-limit")))}]}}));let i=["--output-format","stream-json","--agent","saffron","--print-timeout",`${Math.max(30,2*e.maxTurns)}m`,"--sandbox"];e.model&&i.push("--model",e.model);let a=im(t,i,{cwd:n,stdio:["pipe","pipe","pipe"]});a.stdin.on("error",()=>{}),a.stdin.end(e.prompt);let c="";a.stderr.on("data",$=>{c=(c+$).slice(-4e3)});let l=new Promise(($,k)=>a.once("error",y=>k(new Error(`Antigravity: could not start ${t}: ${y.message}. ${hs}`)))),d=new Promise($=>a.once("close",$)),p="",u,f,h=(async()=>{for await(let $ of cm.createInterface({input:a.stdout})){let k;try{k=JSON.parse($)}catch{continue}let y=k.step_update;y?(y.state==="DONE"&&y.usage&&e.usage.aiCalls++,y.step_type==="agent_response"&&typeof y.text_delta=="string"&&(y.step_index!==u&&([p,u]=["",y.step_index]),p+=y.text_delta,e.lastOutput(p))):k.event==="result"&&(f=k.result)}})();await Promise.race([h,l]);let w=await Promise.race([d,l]);if(f?.usage&&(e.usage.inputTokens+=Math.max(0,(f.usage.input_tokens??0)-(f.usage.cache_read_tokens??0)),e.usage.outputTokens+=f.usage.output_tokens??0,e.usage.cacheReadTokens+=f.usage.cache_read_tokens??0),e.usage.models=[`antigravity/${e.model??"default"}`],f?.response&&e.lastOutput(f.response),!e.finished()&&pe.existsSync(me.join(n,"turn-limit")))throw new Error(`Antigravity: ${En(e.maxTurns)}`);if((f?.status!=="SUCCESS"||w!==0)&&!e.finished()){let $=typeof f?.error=="string"?f.error:c.trim().split(`
|
|
362
|
+
`).at(-1)||`agy exited with ${w}`;throw new Error(`Antigravity: ${$}${/auth/i.test($)?`. ${hs}`:""}`)}}finally{pe.rmSync(n,{recursive:!0,force:!0})}};import fd from"node:fs";import gm from"node:os";import hm from"node:path";var ud="@cursor/sdk";function ir(e=process.versions.node){let[t,n]=e.split(".").map(Number);return t>22||t===22&&n>=13?void 0:`the cursor provider needs Node.js 22.13 or newer (this is ${e})`}var gd=async e=>{let t=ir();if(t)throw new Error(t);let{Agent:n,JsonlLocalAgentStore:r}=await or(ud,"cursor"),s=fd.mkdtempSync(hm.join(gm.tmpdir(),"saffron-cursor-")),o=i=>n.create({model:{id:e.model??"auto"},...i?{systemPrompt:i}:{},tools:["mcp"],mcpServers:Object.fromEntries(Object.entries(e.mcpServers).map(([a,c])=>[a,{type:"http",url:c,headers:{Authorization:`Bearer ${e.mcpToken}`}}])),local:{cwd:s,settingSources:[],store:new r(s)}});try{let i=await pd(await o(e.systemPrompt),e.prompt,e);if(i.status==="error"&&/system.?prompt/i.test(i.error?.message??"")&&(i=await pd(await o(void 0),`${e.systemPrompt}
|
|
359
363
|
|
|
360
364
|
---
|
|
361
365
|
|
|
362
|
-
${e.prompt}`,e)),i.status==="error"&&!e.finished())throw new Error(`Cursor: ${i.error?.message??"the run failed"}${
|
|
363
|
-
`)),{calls:r,order:s,events:o}=
|
|
364
|
-
`)){if(!r.trim())continue;let s;try{s=JSON.parse(r)}catch{continue}if(s.type!=="resource-snapshot"||!s.snapshot)continue;let o=s.snapshot,i=o.request,a=o.response,c=o._monotonicTime;t.push({pageId:
|
|
366
|
+
${e.prompt}`,e)),i.status==="error"&&!e.finished())throw new Error(`Cursor: ${i.error?.message??"the run failed"}${mm(i.error?.message)}`)}finally{fd.rmSync(s,{recursive:!0,force:!0})}};async function pd(e,t,n){try{let r=await e.send(t),s="",o=new Set,i=!1;for await(let c of r.stream())if(c.type==="usage")n.usage.aiCalls++;else if(c.type==="assistant"){for(let l of c.message.content)l.type==="text"&&(s+=l.text);n.lastOutput(s)}else c.type==="tool_call"&&(s="",c.status==="running"&&o.add(c.call_id??`#${o.size}`),o.size>n.maxTurns&&!i&&(i=!0,await r.cancel()));let a=await r.wait();if(a.usage&&(n.usage.inputTokens+=a.usage.inputTokens,n.usage.outputTokens+=a.usage.outputTokens,n.usage.cacheReadTokens+=a.usage.cacheReadTokens,n.usage.cacheCreationTokens+=a.usage.cacheWriteTokens),a.model&&(n.usage.models=[...new Set([...n.usage.models??[],`cursor/${a.model.id}`])]),a.result&&n.lastOutput(a.result),i&&!n.finished())throw new Error(`Cursor: ${En(n.maxTurns)}`);return a}finally{e.close()}}function mm(e=""){return/api key|unauthenticated|unauthori[sz]ed|logged.?out/i.test(e)?". Sign in once with: npx saffron login cursor":""}async function hd(){let e=ir();if(e)throw new Error(e);let{Cursor:t}=await or(ud,"cursor"),n=await t.auth.status();if(n.status==="logged-in"){console.log(`Cursor: already signed in${n.email?` as ${n.email}`:""}.`);return}await t.auth.login({onLoginUrl:r=>console.log(`Opening ${r}`)}),console.log("Cursor: signed in. Saffron runs will use your Cursor plan.")}var pi=["claude","codex","antigravity","cursor"];function wd(e){return pi.includes(e)}var ui={codex:od,antigravity:dd,cursor:gd};function bd(e,t){return e==="claude"?new ps(t):new us(ui[e],t,()=>{let n=vd(e);return n.length>0?`${Zt[e]} cannot start here: ${n.join("; ")}`:void 0})}var vs=(...e)=>yd.join(ym.homedir(),...e);function md(e){try{return import.meta.resolve(e),!0}catch{return!1}}function vd(e){switch(e){case"claude":return[];case"codex":{let t=gs();return t?[t]:md("@openai/codex-sdk")?[]:["npm install --save-dev @openai/codex-sdk"]}case"antigravity":return ys()?ws().length>0?["Saffron's tools allowed in agy, once: npx saffron login antigravity"]:[]:["the Antigravity CLI: curl -fsSL https://antigravity.google/cli/install.sh | bash","then run `agy` once to sign in with your Google AI Pro or Ultra account"];case"cursor":{let t=ir();return t?[t]:md("@cursor/sdk")?[]:["npm install --save-dev @cursor/sdk"]}}}function gi(e){let t=process.env,n=vd(e);if(e==="claude")t.ANTHROPIC_API_KEY||t.CLAUDE_CODE_OAUTH_TOKEN||t.CLAUDE_CODE_USE_BEDROCK||t.CLAUDE_CODE_USE_VERTEX||bs.existsSync(vs(".claude",".credentials.json"))||bs.existsSync(vs(".claude.json"))||n.push("ANTHROPIC_API_KEY=sk-ant-... (console.anthropic.com \u2192 API keys)","or a Claude Code login on this machine");else if(e==="codex"&&!gs()){let r=yd.join(t.CODEX_HOME??vs(".codex"),"auth.json");!["keyring","auto"].includes(di().cli_auth_credentials_store??"")&&!bs.existsSync(r)&&n.push("a Codex login with your ChatGPT plan: npx @openai/codex login")}else e==="cursor"&&!ir()&&!t.CURSOR_API_KEY&&!bs.existsSync(vs(".cursor","sdk","auth.json"))&&n.push("a Cursor sign-in for Saffron (once per machine): npx saffron login cursor");return n}var Zt={claude:"Claude",codex:"Codex",antigravity:"Antigravity",cursor:"Cursor"};var Ft=(e,t=0)=>typeof e=="number"?e:t,te=e=>typeof e=="string"?e:void 0;function wm(e,t){if(!t)return;let n=te(t.selector);if(n)return bm(n);let r=te(t.url);if(r)return r;if(e==="press"||e==="keyboardPress")return te(t.key)}function bm(e){return e.replace(/internal:role=([a-z]+)\[name="((?:[^"\\]|\\.)*)"[is]?\]/g,(t,n,r)=>`${n} "${r}"`).replace(/internal:role=([a-z]+)/g,"$1").replace(/internal:label="((?:[^"\\]|\\.)*)"[is]?/g,'label "$1"').replace(/internal:text="((?:[^"\\]|\\.)*)"[is]?/g,'text "$1"').replace(/internal:attr=\[placeholder="((?:[^"\\]|\\.)*)"[is]?\]/g,'placeholder "$1"').replace(/internal:testid=\[data-testid="((?:[^"\\]|\\.)*)"s?\]/g,'test id "$1"').replace(/internal:has-text="((?:[^"\\]|\\.)*)"[is]?/g,'with text "$1"').replace(/ >> nth=0$/,"").replace(/ >> /g," \u203A ").replace(/nth=(\d+)/g,"#$1")}function vm(e){let t=new Map,n=[],r=[];for(let s of e){if(!s.trim())continue;let o;try{o=JSON.parse(s)}catch{continue}r.push(o);let i=te(o.callId);switch(o.type){case"before":{if(!i)break;let a=te(o.method)??"",c=o.class==="Tracing"&&a==="tracingGroup",l=a==="__waitInfo__";t.set(i,{callId:i,method:l?te(o.title)??"wait":a,subject:wm(a,o.params),selector:te(o.params?.selector),startTime:Ft(o.startTime),log:[],pageId:te(o.pageId),before:hi(o,"beforeSnapshot"),calls:[],parentId:te(o.parentId),isGroup:c,title:te(o.title),isWait:l}),n.push(i);break}case"input":{let a=i?t.get(i):void 0;if(a){a.input=hi({...o,pageId:a.pageId},"inputSnapshot");let c=o.point,l=o.box,d=c??(l?{x:l.x+l.width/2,y:l.y+l.height/2}:void 0);a.input&&d?a.input.point=d:d&&(a.inputPoint=d)}break}case"frame-snapshot":{let a=o.snapshot,c=a?.callId?t.get(a.callId):void 0;if(c&&a?.phase&&a.pageId&&a.isMainFrame!==!1){let l=a.phase,d={pageId:a.pageId,name:`${l}@${a.callId}`,callId:a.callId,phase:l};if(c.pageId||(c.pageId=a.pageId),l==="before"&&!c.before)c.before=d;else if(l==="after")c.after=d;else if(l==="action"&&!c.input){let p=c.inputPoint;c.input=p?{...d,point:p}:d}}break}case"log":{let a=i?t.get(i):void 0,c=te(o.message);a&&c&&a.log.push(c);break}case"after":{let a=i?t.get(i):void 0;if(!a)break;a.endTime=Ft(o.endTime,a.startTime);let c=o.error;c?.message&&(a.error=c.message);let l=hi({...o,pageId:a.pageId},"afterSnapshot");l&&(a.after=l);break}default:break}}return{calls:t,order:n,events:r}}function hi(e,t){let n=te(e[t]),r=te(e.pageId);return n&&r?{pageId:r,name:n}:void 0}function Sd(e){return mi(Ua(e))}function mi(e){let n=e.filter(v=>v.name.endsWith(".trace")).flatMap(v=>v.data.toString("utf8").split(`
|
|
367
|
+
`)),{calls:r,order:s,events:o}=vm(n),i=new Map;for(let v of o){let S=v.snapshot;if(v.type!=="frame-snapshot"||!S?.isMainFrame||!S.pageId||!S.frameUrl)continue;let x=S.snapshotName??(S.callId&&S.phase?`${S.phase}@${S.callId}`:void 0);x&&i.set(`${S.pageId}/${x}`,S.frameUrl)}for(let v of r.values())for(let S of[v.before,v.input,v.after])S&&(S.url=i.get(`${S.pageId}/${S.name}`));let a=[];for(let v of s){let S=r.get(v),x=S.parentId?r.get(S.parentId):void 0;x?x.calls.push(S):a.push(v)}let c=v=>{let{parentId:S,isGroup:x,title:b,isWait:R,...m}=v;return{...m,calls:m.calls.map(g=>c(g))}},l=v=>v.find(S=>S.error&&!S.isWait)?.error,d=[],p=[];for(let v of a){let S=r.get(v);if(!S.isGroup){p.push(c(S));continue}let x={title:S.title??"",startTime:S.startTime,endTime:S.endTime,error:S.error,actions:[],calls:[]},b=/^\[saffron:(agent|replay|pending):(-?\d+)\] (.*)$/.exec(x.title);b&&(x.phase=b[1],x.stepIndex=Number(b[2]),x.title=b[3]);let R=[];for(let m of S.calls)if(m.isGroup){let g={title:m.title??"",startTime:m.startTime,endTime:m.endTime,error:m.error??l(m.calls),calls:m.calls.map(E=>c(E))},T=/^\[saffron:action:(\d+)\] ([\s\S]*)$/.exec(g.title);T&&(g.actionIndex=Number(T[1]),g.title=T[2]),x.actions.push(g)}else R.push(m),x.calls.push(c(m));x.error||(x.error=x.actions.find(m=>m.error)?.error??l(R)),d.push(x)}let u=[],f=new Map,h,w,$,k=Number.POSITIVE_INFINITY,y=0;for(let v of o)if(v.type==="context-options")h=te(v.title),w=te(v.browserName),$=Number(v.version)||void 0,k=Math.min(k,Ft(v.monotonicTime,k));else if(v.type==="screencast-frame"){let S=te(v.file)??(te(v.sha1)?`resources/${te(v.sha1)}`:""),x={pageId:te(v.pageId)??"",file:S,sha1:S.slice(S.lastIndexOf("/")+1),timestamp:Ft(v.timestamp),width:Ft(v.width),height:Ft(v.height)};u.push(x),f.has(x.pageId)||f.set(x.pageId,{pageId:x.pageId})}else if(v.type==="event"&&v.class==="BrowserContext"&&v.method==="page"){let S=te(v.params?.pageId);S&&f.set(S,{...f.get(S),pageId:S,openedAt:Ft(v.time)})}else if(v.type==="event"&&v.class==="BrowserContext"&&v.method==="pageClosed"){let S=te(v.params?.pageId);S&&f.set(S,{...f.get(S),pageId:S,closedAt:Ft(v.time)})}else if(v.type==="frame-snapshot"){let S=v.snapshot;if(S?.pageId){let x=f.get(S.pageId)??{pageId:S.pageId};S.isMainFrame&&S.frameUrl&&(x.url=S.frameUrl),f.set(S.pageId,x)}}for(let v of r.values())k=Math.min(k,v.startTime),y=Math.max(y,v.endTime??v.startTime);for(let v of u)y=Math.max(y,v.timestamp);return Number.isFinite(k)||(k=0),{format:$,title:h,browserName:w,startTime:k,endTime:y,steps:d,calls:p,frames:u,requests:Sm(e),pages:[...f.values()],resources:e.filter(v=>v.name.startsWith("resources/")).map(v=>v.name.slice(10))}}function Sm(e){let t=[];for(let n of e.filter(r=>r.name.endsWith(".network")))for(let r of n.data.toString("utf8").split(`
|
|
368
|
+
`)){if(!r.trim())continue;let s;try{s=JSON.parse(r)}catch{continue}if(s.type!=="resource-snapshot"||!s.snapshot)continue;let o=s.snapshot,i=o.request,a=o.response,c=o._monotonicTime;t.push({pageId:te(o.pageref),method:te(i?.method)??"GET",url:te(i?.url)??"",status:Number.isFinite(a?.status)?a?.status:void 0,mimeType:te(a?.content?.mimeType),startedAt:Date.parse(te(o.startedDateTime)??"")||0,time:typeof o.time=="number"?o.time:void 0,timestamp:typeof c=="number"?c:void 0})}return t}import In from"node:fs";import{createHash as xm,randomBytes as Cd}from"node:crypto";import xd from"node:fs";import mt from"node:path";var $d="This run has no reviewable proposal identity. Run the scenario again to review from replay.",yi="The proposal does not belong to this replay.",kd=e=>e instanceof Error?e.message:String(e),Rd=(e,t)=>`No pending proposal at ${mt.relative(e,t)}: it has been accepted, rejected or removed since this run.`;function Td(e,t){let n=/ \(example \d+\)$/.exec(t.scenario),r=n?[t.scenario,t.scenario.slice(0,n.index)]:[t.scenario],s=t.proposalFile,o=a=>a.split(/[\\/]/).slice(-2).join("/"),i=mt.win32.isAbsolute(s)?a=>o(a)===o(s):a=>mt.resolve(a)===mt.resolve(e,s);return r.map(a=>Fe(e,t.feature,a)).find(i)}function Ed(e,t,n){if(Be(n)!==t.proposalRevision)return{available:!1,reason:"The proposal changed since this run. Open the latest run before reviewing it."};let r=a=>({available:!1,reason:a,rejectable:!0}),s;try{s=yn(n)}catch(a){if(a instanceof oe)return r(`The proposal cannot be read: ${mt.relative(e,n)}: ${a.problem}`);throw a}let{feature:o,scenario:i}=s.cache;if(mt.resolve(Fe(e,o,i))!==mt.resolve(n)||o!==t.feature||!(t.scenario===i||t.scenario===s.meta.recordedFor||t.scenario.startsWith(i+" (example ")))return{available:!1,reason:yi};try{if(!xd.existsSync(mt.resolve(e,o)))return r(`STALE: ${o} no longer exists`);let a=Ie(e,le(e),[mt.resolve(e,o)]),c=Le(e,s,a);if(c)return r(`STALE: ${c}`);let l=t.status==="red",d=s.meta.verified===!0&&!l,p=l?t.error??"This run replayed the proposal and it failed.":s.meta.proofError;return{available:!0,verified:d,...!d&&p?{proofError:p}:{},unbound:!s.meta.bound,diff:Et(Re(re(e,o,i)),s.cache),featureEdits:s.meta.featureEdits??[]}}catch(a){return r(kd(a))}}function Ad(e,t){if(!t.proposalFile||!t.proposalRevision)return{available:!1,reason:$d};try{let n=Td(e,{...t,proposalFile:t.proposalFile});return n?xd.existsSync(n)?Ed(e,t,n):{available:!1,reason:Rd(e,n)}:{available:!1,reason:yi}}catch(n){return{available:!1,reason:kd(n)}}}function _d(e,t,n,r=!1){if(!t.proposalFile||!t.proposalRevision)throw new Error($d);let s=Td(e,{...t,proposalFile:t.proposalFile});if(!s)throw new Error(yi);Pr(s,()=>{let o=Ed(e,t,s);if(n==="reject"){if(!o.available&&!o.rejectable)throw new Error(o.reason);Nr(s)}else{if(!o.available)throw new Error(o.reason);if(!o.verified&&!r)throw new Error("Confirm that you want to accept a proposal without successful proof replay.");jr(e,s)}},()=>{throw new Error(Rd(e,s))})}import $m from"node:http";import Xt from"node:path";function Id(){return`<!DOCTYPE html>
|
|
365
369
|
<html lang="en">
|
|
366
370
|
<head>
|
|
367
371
|
<meta charset="utf-8">
|
|
@@ -448,7 +452,7 @@ ${e.prompt}`,e)),i.status==="error"&&!e.finished())throw new Error(`Cursor: ${i.
|
|
|
448
452
|
</head>
|
|
449
453
|
<body>
|
|
450
454
|
<header>
|
|
451
|
-
${
|
|
455
|
+
${Gn(26)}
|
|
452
456
|
<div><div class="name" id="title">Saffron replay</div><div class="sub" id="subtitle"></div></div>
|
|
453
457
|
<span class="status" id="status"></span>
|
|
454
458
|
<label id="scenarioPicker" hidden>Scenario <select id="scenarioSelect" aria-label="Scenario"></select></label>
|
|
@@ -1061,9 +1065,9 @@ ${e.prompt}`,e)),i.status==="error"&&!e.finished())throw new Error(`Cursor: ${i.
|
|
|
1061
1065
|
})();
|
|
1062
1066
|
</script>
|
|
1063
1067
|
</body>
|
|
1064
|
-
</html>`}var Jt=class extends Error{},ld="This trace is gone, or a later run replaced it (one that stopped before writing its report). Run the scenario again to replay it.",Wh=4;function ci(e,t){let n=Vt.join(e,t.file);try{xn.accessSync(n,xn.constants.R_OK)}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return;throw s}if(!vt(Vt.join(e,".saffron","artifacts"),n))throw new Error(`${t.file} is not a file under .saffron/artifacts`);let r=xn.readFileSync(n);return t.sha256&&Ue(r)!==t.sha256?void 0:r}function Gh(){let e=es.resolve("playwright-core/package.json");return Vt.join(Vt.dirname(e),"lib","vite","traceViewer")}var ut={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpeg":"image/jpeg",".jpg":"image/jpeg",".ttf":"font/ttf",".webmanifest":"application/manifest+json",".zip":"application/zip"},Kh=new Set([".png",".jpeg",".jpg"]),ai={"Content-Security-Policy":"sandbox","X-Content-Type-Options":"nosniff"};function Yh(e){let t=/<script>([\s\S]*?)<\/script>/.exec(e)[1];return["default-src 'self'",`script-src 'sha256-${Jh("sha256").update(t).digest("base64")}'`,"style-src 'self' 'unsafe-inline'","worker-src 'self'","connect-src 'self'","frame-src 'self'","object-src 'none'","base-uri 'none'","form-action 'none'","frame-ancestors 'none'"].join("; ")}async function dd(e){let t=e.entries?[...e.entries]:[{scenario:e.scenario,traces:[{file:e.traceFile,data:e.traceData,label:e.label??"Execution",proof:e.proof,steps:e.scenario.steps,uniques:e.scenario.uniques},...(e.additionalTraces??[]).map(v=>({...v,proof:v.proof??!0}))]}],n=e.start??0;if(!t[n])throw new Error("No scenario to replay");let r=v=>{let S=_n(v),x=oi(S.map($=>({name:$.name,get data(){return $.read()}})));return{zip:v,model:x,resources:new Map(S.filter($=>$.name.includes("/")).map($=>[$.name,$.read]))}},s=v=>{try{return v.data?v.data:!v.read&&!xn.existsSync(v.file)?new Jt(ld):(v.read?v.read():xn.readFileSync(v.file))??new Jt(ld)}catch(S){return S instanceof Jt?S:new Jt(`This trace cannot be read: ${S instanceof Error?S.message:String(S)}`)}},o=[];{let v=t[n],S=v.traces.map(s),x=v.traces.map(($,h)=>({t:$,data:S[h]})).filter(({data:$},h)=>h===0||Buffer.isBuffer($));for(let[$,h]of v.traces.entries()){let m=S[$];$>0&&!Buffer.isBuffer(m)&&o.push({file:h.file,reason:m.message})}t[n]={...v,traces:x.map(({t:$,data:h})=>({...$,data:Buffer.isBuffer(h)?h:void 0,read:Buffer.isBuffer(h)?void 0:()=>{throw h}}))}}let i=new Map,a=(v,S)=>{let x=`${v}:${S}`,$=i.get(x);if($)i.delete(x);else{let h=s(t[v].traces[S]);if(!Buffer.isBuffer(h))throw h;$=r(h);let m=[...i.keys()].filter(w=>{let[g,R]=w.split(":").map(Number),C=t[g].traces[R];return g!==n&&(C.data!==void 0||C.checked===!0)});v!==n&&m.length>=Wh&&i.delete(m[0])}return i.set(x,$),$},c=new Map,l=(v,S)=>{let x=t[v].scenario.screenshots?.find(m=>m.file===S);if(!x)return;let $=`${v}:${S}`;if(c.has($))return c.get($);let h=an(e.projectRoot,x);return(v===n||!x.sha256)&&c.set($,h),h};try{a(n,0)}catch(v){if(t.length===1)throw v}for(let v of t[n].scenario.screenshots??[])l(n,v.file);let d=Gh(),p=ad(),u={"Content-Security-Policy":Yh(p)},f=cd(32).toString("hex"),y=cd(8).toString("hex"),b=t.map(v=>({feature:v.scenario.feature,scenario:v.scenario.scenario,status:v.scenario.status})),k=Vh.createServer((v,S)=>{let x=($,h,m,w={})=>{S.writeHead($,{"Content-Type":m,"Cache-Control":"no-store",...w}),S.end(h)};try{let $=v.headers.host??"";if(!/^(?:127\.0\.0\.1|localhost)(?::\d+)?$/i.test($))return x(403,"Invalid host","text/plain");let h=new URL(v.url??"/",`http://${$}`),m=Number(h.searchParams.get("scenario")??n),w=Number.isInteger(m)?t[m]:void 0,g=Number(h.searchParams.get("session")??"0"),R=w&&Number.isInteger(g)?w.traces[g]:void 0,C=()=>x(404,w?"No such trace session":"No such scenario","text/plain");if(h.pathname.startsWith("/api/review/")&&!e.viewOnly){if(v.method!=="POST")return x(405,"Use POST","text/plain");if(v.headers.origin!==`http://${$}`||v.headers["x-saffron-review"]!==f)return x(403,"Review must come from this replay page","text/plain");if(!w||!R)return C();let _=h.pathname.slice(12);if(_!=="accept"&&_!=="reject")return x(404,"Unknown decision","text/plain");try{return id(e.projectRoot,w.scenario,_,v.headers["x-saffron-unverified"]==="yes"),x(200,JSON.stringify({decision:_}),ut[".json"])}catch(I){return x(409,JSON.stringify({error:I instanceof Error?I.message:String(I)}),ut[".json"])}}if(v.method!=="GET"&&v.method!=="HEAD")return x(405,"Use GET","text/plain");if(h.pathname==="/"||h.pathname==="/index.html")return x(200,p,ut[".html"],u);if(h.pathname==="/api/replay"){let _=w?m:n,I=R?g:0,j=t[_],A=j.traces[I],H={scenarios:b,scenarioIndex:_,sessions:j.traces.map(P=>P.label),session:I,proof:A.proof===!0,instance:y},B;try{B=a(_,I).model}catch(P){let E=P instanceof Jt?P.message:`This trace cannot be read: ${P instanceof Error?P.message:String(P)}`;return x(200,JSON.stringify({...H,scenario:j.scenario,unavailable:E}),ut[".json"])}let N=e.viewOnly?{review:{available:!1,reason:e.viewOnly}}:{review:od(e.projectRoot,j.scenario),reviewToken:f};return x(200,JSON.stringify({...H,scenario:{...j.scenario,steps:A.steps,uniques:A.uniques},trace:B,...N}),ut[".json"])}if(h.pathname.startsWith("/artifact/")){let _=h.searchParams.get("v");if(_!==null&&_!==y)return x(410,"This replay was restarted. Reload the page.","text/plain");if(!w||!R)return C();if(h.pathname==="/artifact/trace.zip")return x(200,a(m,g).zip,ut[".zip"],ai);if(h.pathname.startsWith("/artifact/resource/")){let I=decodeURIComponent(h.pathname.slice(19)),j=a(m,g).resources,A=(j.get(I)??(I.includes("/")?void 0:j.get(`resources/${I}`)))?.();if(!A)return x(404,"no such resource","text/plain");let H=Vt.extname(h.pathname).toLowerCase();return x(200,A,Kh.has(H)?ut[H]:"application/octet-stream",ai)}if(h.pathname.startsWith("/artifact/screenshot/")){let I=l(m,decodeURIComponent(h.pathname.slice(21)));return I?x(200,I,ut[".jpg"],ai):x(404,"no such file","text/plain")}}if(h.pathname==="/trace/ping")return x(200,"ok","text/plain");if(h.pathname.startsWith("/trace/")){let _=h.pathname.slice(7)||"index.html",I=Vt.join(d,_);if(!vt(d,I))return x(404,"not found","text/plain");let j=Vt.extname(I).toLowerCase(),A=xn.readFileSync(I);return S.writeHead(200,{"Content-Type":ut[j]??"application/octet-stream","Service-Worker-Allowed":"/trace/"}),S.end(A)}x(404,"not found","text/plain")}catch{S.headersSent?S.destroy():x(400,"Invalid request","text/plain")}});return await new Promise((v,S)=>{k.once("error",S),k.listen(e.port??0,"127.0.0.1",()=>v())}),{url:`http://127.0.0.1:${k.address().port}/`,skipped:o,close:()=>new Promise(v=>k.close(()=>v()))}}import fd from"node:fs";import fs from"node:path";function ps(e){return JSON.stringify([e.role??null,e.name??null,e.nameRegex??null,e.label??null,e.text??null,e.testId??null,e.placeholder??null,e.frame??null])}function pd(e,t){let n=new Map,r=new Set,s=new Map,o=Math.min(e.steps.length,t.steps.length);for(let a=0;a<o;a++){if(e.steps[a].kind==="assertion"||t.steps[a].kind==="assertion"||e.steps[a].gherkin!==t.steps[a].gherkin)continue;let c=e.steps[a].actions,l=t.steps[a].actions;if(c.length===l.length)for(let d=0;d<c.length;d++){let p=c[d],u=l[d];if(p.action!==u.action||Ie.has(p.action)||!p.target||!u.target)continue;let f=ps(p.target),y=JSON.stringify(u.target);s.has(f)&&s.get(f)!==y&&r.add(f),s.set(f,y),f!==ps(u.target)&&n.set(f,{from:p.target,to:u.target})}}let i=[...n.entries()];return{changes:i.filter(([a])=>!r.has(a)).map(([,a])=>a),ambiguous:i.filter(([a])=>r.has(a)).map(([,a])=>a.from)}}function Zh(e){let t=fs.join(e,".saffron","cache");if(!fd.existsSync(t))return[];let n=[];for(let r of fd.readdirSync(t,{recursive:!0})){let s=String(r);s.endsWith(".json")&&n.push(fs.join(t,s))}return n}function ud(e,t,n,r){if(t.length===0)return[];let s=new Map,o=new Set;for(let a of t){let c=ps(a.from),l=s.get(c);l&&JSON.stringify(l.to)!==JSON.stringify(a.to)&&o.add(c),s.set(c,a)}for(let a of o)s.delete(a);let i=[];for(let a of Zh(e)){if(fs.resolve(a)===fs.resolve(n))continue;let c=wt(a);if(!c)continue;let l=[],d=!1;for(let p of c.steps){if(p.kind==="assertion")continue;let u=0;for(let f of p.actions){if(!f.target||Ie.has(f.action))continue;let y=s.get(ps(f.target));y&&(u++,r||(f.target=structuredClone(y.to),d=!0))}u>0&&l.push({gherkin:p.gherkin,count:u})}l.length>0&&(d&&sn(a,c),i.push({file:a,scenario:c.scenario,feature:c.feature,steps:l}))}return i}function us(e){return e.role?`${e.role} "${e.name??e.nameRegex??""}"`:e.label?`label "${e.label}"`:e.text?`text "${e.text}"`:e.testId?`testId "${e.testId}"`:(e.fallbackSelectors??[]).join(",")||"(empty target)"}import gd from"node:fs";import gs from"node:path";function hd(e,t,n,r,s){let o=Te(gs.join(e,t),e,s).find(c=>c.name===n);if(!o)return`scenario "${n}" is no longer in ${t}`;let i=o.steps.map(c=>c.text);if(i.length!==r.length)return`the scenario has ${i.length} steps now and had ${r.length} when this was recorded`;let a=i.findIndex((c,l)=>c!==r[l]);return a<0?void 0:`step ${a+1} now reads "${i[a]}" and was recorded as "${r[a]}"`}function md(e,t,n,r,s,o){let i={applied:[],skipped:[],appliedIndices:[]},a=Te(gs.join(e,t),e,s).find(u=>u.name===n);if(!a){for(let u of r)i.skipped.push({index:u.index,reason:`scenario "${n}" not found in ${t}`});return i}let c=new Map;for(let u of r){let f=a.steps[u.index]?.source;if(!f||f.fromBackground)continue;let y=`${f.file}:${f.line}`;c.set(y,(c.get(y)??new Set).add(u.text))}let l=$e(a),d=new Map,p=new Set;for(let u of r){let f=a.steps[u.index];if(!f?.source){i.skipped.push({index:u.index,reason:`no step at index ${u.index}`});continue}let y=[...$s([u.text,...ks([u.text])])].filter(g=>!l.has(g));if(y.length>0){i.skipped.push({index:u.index,reason:`it would make the scenario name ${y.map(g=>`{env:${g}}`).join(", ")}, which it does not reference now; a recording can only use the environment variables its scenario names, so edit the feature file by hand if you mean it`});continue}if(o&&o[u.index]!==f.text){i.skipped.push({index:u.index,reason:`step ${u.index+1} now reads "${f.text}", not the "${o[u.index]??"(nothing)"}" this edit was written for`});continue}let{file:b,line:k,fromStepSet:T,fromBackground:v}=f.source;if(v){i.skipped.push({index:u.index,reason:`"${f.text}" is a Background step shared across scenarios; edit it manually`});continue}let S=`${b}:${k}`,x=c.get(S);if(x.size>1){i.skipped.push({index:u.index,reason:`${S}${T?` (StepSet "${T}")`:""} is reached by several steps and the edits disagree: ${[...x].map(g=>`"${g}"`).join(" vs ")}. Decide the wording in the definition by hand`});continue}if(p.has(S)){i.appliedIndices.push(u.index);continue}let $=d.get(b);$||($=gd.readFileSync(gs.join(e,b),"utf8").split(`
|
|
1065
|
-
`),d.set(
|
|
1066
|
-
`));return i}
|
|
1068
|
+
</html>`}var Qt=class extends Error{},Pd="This trace is gone, or a later run replaced it (one that stopped before writing its report). Run the scenario again to replay it.",km=4;function bi(e,t){let n=Xt.join(e,t.file);try{In.accessSync(n,In.constants.R_OK)}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return;throw s}if(!kt(Xt.join(e,".saffron","artifacts"),n))throw new Error(`${t.file} is not a file under .saffron/artifacts`);let r=In.readFileSync(n);return t.sha256&&Ve(r)!==t.sha256?void 0:r}function Rm(){let e=ds.resolve("playwright-core/package.json");return Xt.join(Xt.dirname(e),"lib","vite","traceViewer")}var yt={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpeg":"image/jpeg",".jpg":"image/jpeg",".ttf":"font/ttf",".webmanifest":"application/manifest+json",".zip":"application/zip"},Tm=new Set([".png",".jpeg",".jpg"]),wi={"Content-Security-Policy":"sandbox","X-Content-Type-Options":"nosniff"};function Em(e){let t=/<script>([\s\S]*?)<\/script>/.exec(e)[1];return["default-src 'self'",`script-src 'sha256-${xm("sha256").update(t).digest("base64")}'`,"style-src 'self' 'unsafe-inline'","worker-src 'self'","connect-src 'self'","frame-src 'self'","object-src 'none'","base-uri 'none'","form-action 'none'","frame-ancestors 'none'"].join("; ")}async function Od(e){let t=e.entries?[...e.entries]:[{scenario:e.scenario,traces:[{file:e.traceFile,data:e.traceData,label:e.label??"Execution",proof:e.proof,steps:e.scenario.steps,uniques:e.scenario.uniques},...(e.additionalTraces??[]).map(y=>({...y,proof:y.proof??!0}))]}],n=e.start??0;if(!t[n])throw new Error("No scenario to replay");let r=y=>{let v=Mn(y),S=mi(v.map(x=>({name:x.name,get data(){return x.read()}})));return{zip:y,model:S,resources:new Map(v.filter(x=>x.name.includes("/")).map(x=>[x.name,x.read]))}},s=y=>{try{return y.data?y.data:!y.read&&!In.existsSync(y.file)?new Qt(Pd):(y.read?y.read():In.readFileSync(y.file))??new Qt(Pd)}catch(v){return v instanceof Qt?v:new Qt(`This trace cannot be read: ${v instanceof Error?v.message:String(v)}`)}},o=[];{let y=t[n],v=y.traces.map(s),S=y.traces.map((x,b)=>({t:x,data:v[b]})).filter(({data:x},b)=>b===0||Buffer.isBuffer(x));for(let[x,b]of y.traces.entries()){let R=v[x];x>0&&!Buffer.isBuffer(R)&&o.push({file:b.file,reason:R.message})}t[n]={...y,traces:S.map(({t:x,data:b})=>({...x,data:Buffer.isBuffer(b)?b:void 0,read:Buffer.isBuffer(b)?void 0:()=>{throw b}}))}}let i=new Map,a=(y,v)=>{let S=`${y}:${v}`,x=i.get(S);if(x)i.delete(S);else{let b=s(t[y].traces[v]);if(!Buffer.isBuffer(b))throw b;x=r(b);let R=[...i.keys()].filter(m=>{let[g,T]=m.split(":").map(Number),E=t[g].traces[T];return g!==n&&(E.data!==void 0||E.checked===!0)});y!==n&&R.length>=km&&i.delete(R[0])}return i.set(S,x),x},c=new Map,l=(y,v)=>{let S=t[y].scenario.screenshots?.find(R=>R.file===v);if(!S)return;let x=`${y}:${v}`;if(c.has(x))return c.get(x);let b=gn(e.projectRoot,S);return(y===n||!S.sha256)&&c.set(x,b),b};try{a(n,0)}catch(y){if(t.length===1)throw y}for(let y of t[n].scenario.screenshots??[])l(n,y.file);let d=Rm(),p=Id(),u={"Content-Security-Policy":Em(p)},f=Cd(32).toString("hex"),h=Cd(8).toString("hex"),w=t.map(y=>({feature:y.scenario.feature,scenario:y.scenario.scenario,status:y.scenario.status})),$=$m.createServer((y,v)=>{let S=(x,b,R,m={})=>{v.writeHead(x,{"Content-Type":R,"Cache-Control":"no-store",...m}),v.end(b)};try{let x=y.headers.host??"";if(!/^(?:127\.0\.0\.1|localhost)(?::\d+)?$/i.test(x))return S(403,"Invalid host","text/plain");let b=new URL(y.url??"/",`http://${x}`),R=Number(b.searchParams.get("scenario")??n),m=Number.isInteger(R)?t[R]:void 0,g=Number(b.searchParams.get("session")??"0"),T=m&&Number.isInteger(g)?m.traces[g]:void 0,E=()=>S(404,m?"No such trace session":"No such scenario","text/plain");if(b.pathname.startsWith("/api/review/")&&!e.viewOnly){if(y.method!=="POST")return S(405,"Use POST","text/plain");if(y.headers.origin!==`http://${x}`||y.headers["x-saffron-review"]!==f)return S(403,"Review must come from this replay page","text/plain");if(!m||!T)return E();let A=b.pathname.slice(12);if(A!=="accept"&&A!=="reject")return S(404,"Unknown decision","text/plain");try{return _d(e.projectRoot,m.scenario,A,y.headers["x-saffron-unverified"]==="yes"),S(200,JSON.stringify({decision:A}),yt[".json"])}catch(P){return S(409,JSON.stringify({error:P instanceof Error?P.message:String(P)}),yt[".json"])}}if(y.method!=="GET"&&y.method!=="HEAD")return S(405,"Use GET","text/plain");if(b.pathname==="/"||b.pathname==="/index.html")return S(200,p,yt[".html"],u);if(b.pathname==="/api/replay"){let A=m?R:n,P=T?g:0,O=t[A],I=O.traces[P],N={scenarios:w,scenarioIndex:A,sessions:O.traces.map(_=>_.label),session:P,proof:I.proof===!0,instance:h},M;try{M=a(A,P).model}catch(_){let j=_ instanceof Qt?_.message:`This trace cannot be read: ${_ instanceof Error?_.message:String(_)}`;return S(200,JSON.stringify({...N,scenario:O.scenario,unavailable:j}),yt[".json"])}let B=e.viewOnly?{review:{available:!1,reason:e.viewOnly}}:{review:Ad(e.projectRoot,O.scenario),reviewToken:f};return S(200,JSON.stringify({...N,scenario:{...O.scenario,steps:I.steps,uniques:I.uniques},trace:M,...B}),yt[".json"])}if(b.pathname.startsWith("/artifact/")){let A=b.searchParams.get("v");if(A!==null&&A!==h)return S(410,"This replay was restarted. Reload the page.","text/plain");if(!m||!T)return E();if(b.pathname==="/artifact/trace.zip")return S(200,a(R,g).zip,yt[".zip"],wi);if(b.pathname.startsWith("/artifact/resource/")){let P=decodeURIComponent(b.pathname.slice(19)),O=a(R,g).resources,I=(O.get(P)??(P.includes("/")?void 0:O.get(`resources/${P}`)))?.();if(!I)return S(404,"no such resource","text/plain");let N=Xt.extname(b.pathname).toLowerCase();return S(200,I,Tm.has(N)?yt[N]:"application/octet-stream",wi)}if(b.pathname.startsWith("/artifact/screenshot/")){let P=l(R,decodeURIComponent(b.pathname.slice(21)));return P?S(200,P,yt[".jpg"],wi):S(404,"no such file","text/plain")}}if(b.pathname==="/trace/ping")return S(200,"ok","text/plain");if(b.pathname.startsWith("/trace/")){let A=b.pathname.slice(7)||"index.html",P=Xt.join(d,A);if(!kt(d,P))return S(404,"not found","text/plain");let O=Xt.extname(P).toLowerCase(),I=In.readFileSync(P);return v.writeHead(200,{"Content-Type":yt[O]??"application/octet-stream","Service-Worker-Allowed":"/trace/"}),v.end(I)}S(404,"not found","text/plain")}catch{v.headersSent?v.destroy():S(400,"Invalid request","text/plain")}});return await new Promise((y,v)=>{$.once("error",v),$.listen(e.port??0,"127.0.0.1",()=>y())}),{url:`http://127.0.0.1:${$.address().port}/`,skipped:o,close:()=>new Promise(y=>$.close(()=>y()))}}import jd from"node:fs";import Ss from"node:path";function xs(e){return JSON.stringify([e.role??null,e.name??null,e.nameRegex??null,e.label??null,e.text??null,e.testId??null,e.placeholder??null,e.frame??null])}function Nd(e,t){let n=new Map,r=new Set,s=new Map,o=Math.min(e.steps.length,t.steps.length);for(let a=0;a<o;a++){if(e.steps[a].kind==="assertion"||t.steps[a].kind==="assertion"||e.steps[a].gherkin!==t.steps[a].gherkin)continue;let c=e.steps[a].actions,l=t.steps[a].actions;if(c.length===l.length)for(let d=0;d<c.length;d++){let p=c[d],u=l[d];if(p.action!==u.action||Ne.has(p.action)||!p.target||!u.target)continue;let f=xs(p.target),h=JSON.stringify(u.target);s.has(f)&&s.get(f)!==h&&r.add(f),s.set(f,h),f!==xs(u.target)&&n.set(f,{from:p.target,to:u.target})}}let i=[...n.entries()];return{changes:i.filter(([a])=>!r.has(a)).map(([,a])=>a),ambiguous:i.filter(([a])=>r.has(a)).map(([,a])=>a.from)}}function Am(e){let t=Ss.join(e,".saffron","cache");if(!jd.existsSync(t))return[];let n=[];for(let r of jd.readdirSync(t,{recursive:!0})){let s=String(r);s.endsWith(".json")&&n.push(Ss.join(t,s))}return n}function Fd(e,t,n,r){if(t.length===0)return[];let s=new Map,o=new Set;for(let a of t){let c=xs(a.from),l=s.get(c);l&&JSON.stringify(l.to)!==JSON.stringify(a.to)&&o.add(c),s.set(c,a)}for(let a of o)s.delete(a);let i=[];for(let a of Am(e)){if(Ss.resolve(a)===Ss.resolve(n))continue;let c=xt(a);if(!c)continue;let l=[],d=!1;for(let p of c.steps){if(p.kind==="assertion")continue;let u=0;for(let f of p.actions){if(!f.target||Ne.has(f.action))continue;let h=s.get(xs(f.target));h&&(u++,r||(f.target=structuredClone(h.to),d=!0))}u>0&&l.push({gherkin:p.gherkin,count:u})}l.length>0&&(d&&pn(a,c),i.push({file:a,scenario:c.scenario,feature:c.feature,steps:l}))}return i}function $s(e){return e.role?`${e.role} "${e.name??e.nameRegex??""}"`:e.label?`label "${e.label}"`:e.text?`text "${e.text}"`:e.testId?`testId "${e.testId}"`:(e.fallbackSelectors??[]).join(",")||"(empty target)"}import Md from"node:fs";import ks from"node:path";function Ld(e,t,n,r,s){let o=Ce(ks.join(e,t),e,s).find(c=>c.name===n);if(!o)return`scenario "${n}" is no longer in ${t}`;let i=o.steps.map(c=>c.text);if(i.length!==r.length)return`the scenario has ${i.length} steps now and had ${r.length} when this was recorded`;let a=i.findIndex((c,l)=>c!==r[l]);return a<0?void 0:`step ${a+1} now reads "${i[a]}" and was recorded as "${r[a]}"`}function Dd(e,t,n,r,s,o){let i={applied:[],skipped:[],appliedIndices:[]},a=Ce(ks.join(e,t),e,s).find(u=>u.name===n);if(!a){for(let u of r)i.skipped.push({index:u.index,reason:`scenario "${n}" not found in ${t}`});return i}let c=new Map;for(let u of r){let f=a.steps[u.index]?.source;if(!f||f.fromBackground)continue;let h=`${f.file}:${f.line}`;c.set(h,(c.get(h)??new Set).add(u.text))}let l=_e(a),d=new Map,p=new Set;for(let u of r){let f=a.steps[u.index];if(!f?.source){i.skipped.push({index:u.index,reason:`no step at index ${u.index}`});continue}let h=[...Os([u.text,...js([u.text])])].filter(g=>!l.has(g));if(h.length>0){i.skipped.push({index:u.index,reason:`it would make the scenario name ${h.map(g=>`{env:${g}}`).join(", ")}, which it does not reference now; a recording can only use the environment variables its scenario names, so edit the feature file by hand if you mean it`});continue}if(o&&o[u.index]!==f.text){i.skipped.push({index:u.index,reason:`step ${u.index+1} now reads "${f.text}", not the "${o[u.index]??"(nothing)"}" this edit was written for`});continue}let{file:w,line:$,fromStepSet:k,fromBackground:y}=f.source;if(y){i.skipped.push({index:u.index,reason:`"${f.text}" is a Background step shared across scenarios; edit it manually`});continue}let v=`${w}:${$}`,S=c.get(v);if(S.size>1){i.skipped.push({index:u.index,reason:`${v}${k?` (StepSet "${k}")`:""} is reached by several steps and the edits disagree: ${[...S].map(g=>`"${g}"`).join(" vs ")}. Decide the wording in the definition by hand`});continue}if(p.has(v)){i.appliedIndices.push(u.index);continue}let x=d.get(w);x||(x=Md.readFileSync(ks.join(e,w),"utf8").split(`
|
|
1069
|
+
`),d.set(w,x));let b=x[$-1],R=b?.match(/^(\s*)(\S+)\s+(.*)$/);if(!R||R[3]!==f.text){i.skipped.push({index:u.index,reason:`${w}:${$} no longer matches the recorded step text`});continue}let m=`${R[1]}${R[2]} ${u.text}`;x[$-1]=m,p.add(v),i.appliedIndices.push(u.index),i.applied.push({file:w,line:$,from:b.trim(),to:m.trim(),fromStepSet:k})}for(let[u,f]of d)i.applied.some(h=>h.file===u)&&Md.writeFileSync(ks.join(e,u),f.join(`
|
|
1070
|
+
`));return i}import{spawn as _m}from"node:child_process";function vi(e,t){if(e==null)return[];let n=Array.isArray(e)?e:[e];for(let r of n)if(typeof r!="string"||r.trim()==="")throw new Error(`"${t}" in saffron.config.json must be a command, or a list of commands, e.g. "${t}": "npm run seed"`);return n}function Im(e,t,n){let r=Date.now();return new Promise(s=>{let o=process.platform!=="win32",i=_m(t,{cwd:n.cwd,shell:!0,detached:o,env:{...process.env,...n.env},stdio:["ignore",process.stderr,process.stderr]}),a=!1,c=!1,l=()=>{try{o&&i.pid?process.kill(-i.pid,"SIGKILL"):i.kill("SIGKILL")}catch{}},d=setTimeout(()=>{a=!0,l()},n.timeoutMs),p=()=>{c=!0,l()};n.signal?.addEventListener("abort",p,{once:!0});let u=f=>{clearTimeout(d),n.signal?.removeEventListener("abort",p),s({phase:e,command:t,exitCode:f,durationMs:Date.now()-r,...a?{timedOut:a}:{},...c?{cancelled:c}:{}})};i.on("error",()=>u(null)),i.on("exit",f=>u(a||c?null:f))})}var Rs=e=>e.exitCode!==0;async function Si(e,t,n){let r=[];for(let s of t){if(n.signal?.aborted)break;console.error(`saffron ${e}: ${s}`);let o=await Im(e,s,n);if(r.push(o),o.cancelled||Rs(o)&&(console.error(`saffron ${e} failed: ${xi(o,n.timeoutMs)}`),e==="setup"))break}return r}function xi(e,t){return e.cancelled?`"${e.command}" was interrupted`:e.timedOut?`"${e.command}" was stopped after ${Math.round(t/1e3)}s (hookTimeoutMs)`:e.exitCode===null?`"${e.command}" could not be started`:`"${e.command}" exited with code ${e.exitCode}`}var Cm=`
|
|
1067
1071
|
.wrap { max-width: 1180px; }
|
|
1068
1072
|
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); gap: 0 14px; align-items: start; }
|
|
1069
1073
|
.panel { min-width: 0; }
|
|
@@ -1105,42 +1109,42 @@ ${e.prompt}`,e)),i.status==="error"&&!e.finished())throw new Error(`Cursor: ${i.
|
|
|
1105
1109
|
details.more summary { padding: 6px 0 0; font-family: var(--mono); font-size: 10.5px; color: var(--muted); }
|
|
1106
1110
|
details.more summary:hover { background: none; color: var(--text); }
|
|
1107
1111
|
@media (max-width: 560px) { .wrap { padding: 14px 12px 40px; } .grid { grid-template-columns: 1fr; } .kpis { grid-template-columns: repeat(2, 1fr); } }
|
|
1108
|
-
`,
|
|
1109
|
-
${
|
|
1110
|
-
${
|
|
1111
|
-
${
|
|
1112
|
-
${
|
|
1113
|
-
${
|
|
1114
|
-
${
|
|
1115
|
-
${
|
|
1116
|
-
${
|
|
1117
|
-
</section>`,d=`<div class="panel"><div class="panel-title">suite health \xB7 each scenario's latest result</div>${
|
|
1118
|
-
${
|
|
1119
|
-
${
|
|
1120
|
-
</div>`,u=
|
|
1112
|
+
`,en=(e,t)=>`${e} ${t}${e===1?"":"s"}`,$i=e=>new Date(e).toLocaleString("en-GB",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}),ki=e=>new Date(e).toLocaleString("en-GB",{day:"2-digit",month:"short",hour:"2-digit",minute:"2-digit"});function ar(e,t=""){let n=e.name??e.scenario;return`<div class="row-main"><div class="scn" data-f="${F(e.feature)}" data-s="${F(n)}" title="${F(`${e.feature} \u203A ${e.scenario}`)}">${F(e.scenario)}</div><div class="feat">${F(e.feature)}</div>${t}</div>`}function wt(e,t,n,r,s,o=""){return`<div class="panel${o?` accent-${o}`:""}"><div class="panel-head"><div class="panel-title${n?` ${n}`:""}">${F(e)}</div>${t===void 0?"":`<span class="count${t>0&&n?` ${n}`:""}">${t}</span>`}</div>${r||`<div class="empty">${F(s)}</div>`}</div>`}function Bd(e){let t=e.reduce((n,[r])=>n+r,0)||1;return`<div class="stack">${e.filter(([n])=>n>0).map(([n,r,s])=>`<span style="width:${(n/t*100).toFixed(2)}%;background:${s??`var(${r})`}"></span>`).join("")}</div>`}function Ud(e,t,n,r){if(e.length===0)return'<div class="empty">No runs yet.</div>';let s=Math.max(1,...e.map(t)),o=10,i=e.map((a,c)=>{let l=Math.max(2,t(a)/s*62);return`<rect x="${c*o+1.5}" y="${(64-l).toFixed(1)}" width="${o-3}" height="${l.toFixed(1)}" rx="1.5" fill="var(${r(a)})"><title>${F(n(a))}</title></rect>`}).join("");return`<svg class="bars" viewBox="0 0 ${e.length*o} 64" preserveAspectRatio="none" aria-hidden="true">${i}</svg><div class="axis"><span>${F(ki(e[0].startedAt))}</span><span>${F(ki(e.at(-1).startedAt))}</span></div>`}var cr=e=>e.length?`<ul class="rows">${e.join("")}</ul>`:"";function zd(e,t){let n=e.suite,r=n.green+n.yellow+n.unverified+n.red,s=r===0?void 0:Math.round((n.green+n.yellow)/r*100),o=x=>x>0?` \xB7 ${x} unverified`:"",i=n.red,a=e.lastRun,c=s===void 0?"":s>=95?"green":s>=80?"gold":"red",l=`<section class="kpis">
|
|
1113
|
+
${he("tests",String(n.tests),`${en(n.scenarios,"scenario")} \xB7 ${en(n.features,"feature")}`)}
|
|
1114
|
+
${he("passing",s===void 0?"\u2013":`${s}<span class="unit">%</span>`,`${n.green+n.yellow} of ${r} \xB7 latest results${o(n.unverified)}`,c,"",Sn(e.trend.map(x=>x.passRate),"var(--green)"))}
|
|
1115
|
+
${he("failing",String(i),i>0?"\u25BC red the last time they ran":"all clear",i>0?"red":"",i>0?"red":"green")}
|
|
1116
|
+
${he("flaky",String(e.flaky.length),e.flaky.length>0?"pass and fail by turns on one base URL":"none in 20 runs",e.flaky.length>0?"gold":"",e.flaky.length>0?"gold":"green")}
|
|
1117
|
+
${he("never run",String(e.neverRun.length),e.neverRun.length>0?"in no recorded run":"every scenario has run",e.neverRun.length>0?"gold":"",e.neverRun.length>0?"gold":"green")}
|
|
1118
|
+
${he("last run",a?rt(a.durationMs):"\u2013",a?`${en(a.ran,"test")} \xB7 ${a.passRate}% passed${o(a.unverified)}`:"no run yet","","",Sn(e.trend.map(x=>x.durationMs),"var(--muted)"))}
|
|
1119
|
+
${he("zero-ai replay",a?`${a.replayRate}<span class="unit">%</span>`:"\u2013","replayed from recordings, last run",a&&a.replayRate>=90?"green":"")}
|
|
1120
|
+
${he("recorded",n.scenarios?`${Math.round(n.recorded/n.scenarios*100)}<span class="unit">%</span>`:"\u2013",n.scenarios-n.recorded>0?`${n.scenarios-n.recorded} still need the agent`:"every scenario has a current recording",n.recorded===n.scenarios?"green":"")}
|
|
1121
|
+
</section>`,d=`<div class="panel"><div class="panel-title">suite health \xB7 each scenario's latest result</div>${Bd([[n.green,"--green"],[n.yellow,"--gold"],[n.unverified,"--gold","repeating-linear-gradient(135deg, var(--gold) 0 4px, var(--gold-soft) 4px 8px)"],[n.red,"--red"],[n.neverRun,"--faint"]])}<div class="legend"><span><i class="dot green"></i>${n.green} passed</span><span><i class="dot gold"></i>${n.yellow} healed</span>${n.unverified>0?`<span><i class="dot unverified"></i>${n.unverified} healed, unverified</span>`:""}<span><i class="dot red"></i>${n.red} failed</span><span><i class="dot faint"></i>${n.neverRun} never run</span></div></div>`,p=`<div class="grid">
|
|
1122
|
+
${wt(`pass rate \xB7 last ${en(e.trend.length,"run")}`,void 0,"",Ud(e.trend,x=>x.passRate,x=>`${$i(x.startedAt)}: ${x.passRate}% of ${x.tests} passed, ${x.red} failed`,x=>x.red>0?"--red":"--green"),"")}
|
|
1123
|
+
${wt(`execution time \xB7 last ${en(e.trend.length,"run")}`,void 0,"",Ud(e.trend,x=>x.durationMs,x=>`${$i(x.startedAt)}: ${rt(x.durationMs)} for ${en(x.tests,"test")}`,()=>"--muted"),"")}
|
|
1124
|
+
</div>`,u=cr(e.recentFailures.map(x=>`<li><i class="dot ${x.stillFailing?"red":"green"}"></i>${ar(x,x.error?`<div class="err" title="${F(x.error)}">${F(x.error)}</div>`:"")}<div class="row-side">${x.stillFailing?`<span class="red">${x.streak} run${x.streak===1?"":"s"} in a row</span>`:'<span class="green">passed since</span>'}<br>${F(ki(x.at))}</div></li>`)),f=cr(e.flaky.map(x=>`<li><i class="dot gold"></i>${ar(x)}<div class="row-side">flipped ${x.flips}\xD7 in ${x.runs} runs<br>${x.reds} red \xB7 last <span class="${x.last==="red"?"red":"green"}">${x.last==="red"?"failed":"passed"}</span></div></li>`)),h=cr(e.healing.map(x=>`<li><i class="dot gold"></i>${ar(x)}<div class="row-side">healed ${x.heals}\xD7${x.unverified>0?` <span class="gold">(${x.unverified} unverified)</span>`:""}<br>in ${x.runs} runs</div></li>`)),w=Math.max(1,...e.slowest.map(x=>x.avgMs)),$=cr(e.slowest.map(x=>`<li>${ar(x,`<div class="meter" style="width:${(x.avgMs/w*100).toFixed(1)}%"></div>`)}<div class="row-side">avg ${rt(x.avgMs)}<br>last ${rt(x.lastMs)}</div></li>`)),k=e.tags.length?`<table class="tags">${e.tags.map(x=>{let b=x.scenarios-x.neverRun,R=x.red>0?`<span style="color:var(--red)">${x.red} red</span>`:b===0?"never run":`${Math.round((x.green+x.yellow)/b*100)}%`;return`<tr><td class="tagname">${F(x.tag)}</td><td class="num">${x.scenarios}</td><td class="stackcell">${Bd([[x.green,"--green"],[x.yellow,"--gold"],[x.unverified,"--gold","repeating-linear-gradient(135deg, var(--gold) 0 4px, var(--gold-soft) 4px 8px)"],[x.red,"--red"],[x.neverRun,"--faint"]])}</td><td class="num">${R}</td></tr>`}).join("")}</table>`:"",y=(x,b)=>cr(x.map(R=>`<li><i class="dot ${b}"></i>${ar(R)}</li>`)),v=e.notInLastRun.length?`<details class="more"><summary>left out by tags or paths \xB7 show ${e.notInLastRun.length}</summary>${y(e.notInLastRun,"idle")}</details>`:"",S=e.historyRuns===0?"no runs recorded yet":`${en(e.historyRuns,"run")} in .saffron/history.jsonl`;return`<!doctype html>
|
|
1121
1125
|
<html lang="en">
|
|
1122
1126
|
<head>
|
|
1123
1127
|
<meta charset="utf-8"/>
|
|
1124
1128
|
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
|
1125
1129
|
<title>Saffron dashboard</title>
|
|
1126
|
-
${
|
|
1130
|
+
${Oo}
|
|
1127
1131
|
<style>
|
|
1128
|
-
${
|
|
1132
|
+
${jo}${Cm}</style>
|
|
1129
1133
|
</head>
|
|
1130
1134
|
<body>
|
|
1131
1135
|
<div class="topline"></div>
|
|
1132
1136
|
<div class="wrap">
|
|
1133
1137
|
<header class="top">
|
|
1134
1138
|
<div class="brand">
|
|
1135
|
-
${
|
|
1139
|
+
${Gn(38)}
|
|
1136
1140
|
<div>
|
|
1137
1141
|
<div class="brand-name">saffron</div>
|
|
1138
1142
|
<div class="brand-sub">suite quality</div>
|
|
1139
1143
|
</div>
|
|
1140
1144
|
</div>
|
|
1141
1145
|
<div class="run-meta">
|
|
1142
|
-
<span>${F(
|
|
1143
|
-
${a?`<span>\xB7</span><span>last run ${F(
|
|
1146
|
+
<span>${F(S)}</span>
|
|
1147
|
+
${a?`<span>\xB7</span><span>last run ${F($i(a.startedAt))}</span>`:""}
|
|
1144
1148
|
</div>
|
|
1145
1149
|
</header>
|
|
1146
1150
|
|
|
@@ -1152,20 +1156,20 @@ ${Ro}${nm}</style>
|
|
|
1152
1156
|
|
|
1153
1157
|
<div class="section-head"><span class="section-title">stability</span></div>
|
|
1154
1158
|
<div class="grid">
|
|
1155
|
-
${
|
|
1156
|
-
${
|
|
1157
|
-
${
|
|
1158
|
-
${
|
|
1159
|
+
${wt("recent failures \xB7 last 10 runs",e.recentFailures.length,"red",u,"Nothing failed in the last 10 runs.",i>0?"red":"")}
|
|
1160
|
+
${wt("flaky \xB7 last 20 runs",e.flaky.length,"gold",f,"No scenario passed and failed by turns.",e.flaky.length>0?"gold":"")}
|
|
1161
|
+
${wt("healed again and again",e.healing.length,"gold",h?`<div class="note">The page keeps changing under these: review the heals, or fix the step.</div>${h}`:"","No scenario needed the agent twice in the last 20 runs.")}
|
|
1162
|
+
${wt("slowest \xB7 average over 20 runs",void 0,"",$,"No timings yet.")}
|
|
1159
1163
|
</div>
|
|
1160
1164
|
|
|
1161
1165
|
<div class="section-head"><span class="section-title">coverage</span></div>
|
|
1162
1166
|
<div class="grid">
|
|
1163
|
-
${
|
|
1164
|
-
${
|
|
1165
|
-
${
|
|
1167
|
+
${wt("tags \xB7 latest results",e.tags.length,"",k,"No tags in the feature files.")}
|
|
1168
|
+
${wt("never run",e.neverRun.length,"gold",y(e.neverRun,"faint"),"Every scenario has run at least once.")}
|
|
1169
|
+
${wt("not in the last run",e.notInLastRun.length,"",v,"The last run ran every scenario that has run before.")}
|
|
1166
1170
|
</div>
|
|
1167
1171
|
|
|
1168
|
-
<footer>${
|
|
1172
|
+
<footer>${Po(11)} generated by saffron v${F(t)}</footer>
|
|
1169
1173
|
</div>
|
|
1170
1174
|
<script>
|
|
1171
1175
|
if (typeof window.saffronOpen === "function") document.body.classList.add("linked");
|
|
@@ -1176,60 +1180,60 @@ ${Ro}${nm}</style>
|
|
|
1176
1180
|
</script>
|
|
1177
1181
|
</body>
|
|
1178
1182
|
</html>
|
|
1179
|
-
`}import{spawnSync as
|
|
1180
|
-
${e.stdout}`,
|
|
1181
|
-
`).map(n=>n.trim()).find(n=>n&&!/^WARNING:/.test(n))??t;function kn(e){return e.missing?{kind:"missing-tool",message:"the GitHub CLI (gh) is not installed here: install it from cli.github.com and sign in with gh auth login"}:e.timedOut?{kind:"failed",message:"gh did not finish within 10 minutes"}:/gh auth login|not logged in|authentication required/i.test(tr(e))?{kind:"signed-out",message:"gh is not signed in: run gh auth login"}:/none of the git remotes|no git remotes|not a git repository/i.test(tr(e))?{kind:"not-a-repository",message:hi(e,"not a GitHub repository")}:{kind:"failed",message:hi(e,`gh exited with ${e.status}`)}}function Pt(e){if(e.missing)return{kind:"missing-tool",message:"the Azure CLI (az) is not installed here: install it, add its azure-devops extension (az extension add --name azure-devops) and sign in (az login, or AZURE_DEVOPS_EXT_PAT)"};if(e.timedOut)return{kind:"failed",message:"az did not finish within 10 minutes"};let t=tr(e);return/azure-devops|'pipelines' is (misspelled|not in)|not in the 'az' command group/i.test(t)&&!/login/i.test(t)?{kind:"missing-tool",message:"the Azure CLI has no azure-devops extension: az extension add --name azure-devops"}:/az login|az devops login|TF400813|not authorized|authentication failed|\b401\b/i.test(t)?{kind:"signed-out",message:"az is not signed in to Azure DevOps: run az login, or set AZURE_DEVOPS_EXT_PAT"}:/--organization|--org\b|--project|must be specified|could not detect/i.test(t)?{kind:"not-a-repository",message:"cannot tell which Azure DevOps organization and project: run this in a clone of an Azure Repos repository, or set ci.organization and ci.project in saffron.config.json"}:{kind:"failed",message:hi(e,`az exited with ${e.status}`)}}function yi(e,t,n){let r=n??t.ci?.provider;if(r!==void 0){if(!rm.includes(r))throw new D(`unknown CI provider "${r}": use "github" or "azure"`);return r}return Vr(e).some(s=>s.startsWith("dev.azure.com/"))?"azure":"github"}var rr=e=>[...e.ci?.organization?["--organization",e.ci.organization]:[],...e.ci?.project?["--project",e.ci.project]:[]];function om(e,t){let n=pe("git",["rev-parse","--abbrev-ref","HEAD"],e,t),r=n.status===0?n.stdout.trim():"";return r&&r!=="HEAD"?r:void 0}function im(e){let t=new Map;for(let[n,r]of Object.entries(ft(e))){try{if(Ne(Q.join(e,n))!==r.revision)continue}catch{continue}r.from.run&&t.set(r.from.run,(t.get(r.from.run)??0)+1)}return t}function Rd(e,t=Date.now()){let n=e?t-Date.parse(e):NaN;if(!(n>=0))return;let r=Math.round(n/6e4);if(r<60)return`${r} min ago`;let s=Math.round(r/60);return s<48?`${s} h ago`:`${Math.round(s/24)} days ago`}var G=e=>typeof e=="string"&&e?e:void 0,kd=e=>G(e)?.replace(/^refs\/(heads|tags)\//,""),am="databaseId,number,attempt,displayTitle,workflowName,status,conclusion,event,headBranch,headSha,createdAt,url";function cm(e){let t=e.status==="completed"?"completed":e.status==="in_progress"?"in_progress":"queued";return{id:String(e.databaseId),name:G(e.workflowName)??"workflow",number:String(e.number??""),title:G(e.displayTitle),status:t,conclusion:t==="completed"?G(e.conclusion):void 0,event:G(e.event),branch:G(e.headBranch),commit:G(e.headSha),createdAt:G(e.createdAt),url:G(e.url),attempt:typeof e.attempt=="number"?e.attempt:void 0}}var lm={completed:"completed",inProgress:"in_progress",cancelling:"in_progress"},dm={succeeded:"success",partiallySucceeded:"partial",failed:"failure",canceled:"cancelled"},fm={individualCI:"push",batchedCI:"push",pullRequest:"pull_request",schedule:"schedule",manual:"manual"};function Ed(e){let t=e.triggerInfo??{};return kd(t["pr.sourceBranch"])??kd(e.sourceBranch)}function Ad(e){let t=e.triggerInfo??{},n=lm[String(e.status)]??"queued",r=G(e.result);return{id:String(e.id),name:G(e.definition?.name)??"pipeline",number:String(e.buildNumber??e.id),status:n,conclusion:n==="completed"&&r?dm[r]??r:void 0,event:G(e.reason)?fm[String(e.reason)]??String(e.reason):void 0,branch:Ed(e),commit:G(t["pr.sourceSha"])??G(e.sourceVersion),createdAt:G(e.queueTime),url:G((e._links??{}).web?.href)}}function mi(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function ys(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>!!n&&typeof n=="object"):void 0}catch{return}}function pm(e){return new Set(e.map(t=>t.startsWith("dev.azure.com/")?t.slice(t.lastIndexOf("/_git/")+6):t.slice(t.indexOf("/")+1)))}function um(e,t,n,r,s,o,i=Math.min(Math.max(o,50),500)){for(let a=i;;a=Math.min(a*2,500)){let c=pe("az",["pipelines","runs","list","--top",String(a),...r,"--output","json",...rr(t)],e,n);if(c.missing||c.status!==0)return Pt(c);let l=ys(c.stdout);if(!l)return{kind:"failed",message:"az answered with something other than a list of runs"};let d=l.filter(s);if(d.length>=o||l.length<a||a>=500)return d}}function _d(e,t,n={}){let r=n.env??process.env,s=yi(e,t,n.provider),o=n.branch??om(e,r),i=o===void 0?void 0:$n(o),a=n.limit??20,c;if(s==="github"){let d=pe("gh",["run","list","--limit",String(a),"--json",am,...i?["--branch",i]:[]],e,r);if(d.missing||d.status!==0)return{provider:s,branch:i,runs:[],problem:kn(d)};let p=ys(d.stdout);if(!p)return{provider:s,branch:i,runs:[],problem:{kind:"failed",message:"gh answered with something other than a list of runs"}};c=p.map(cm)}else{let d=pm(Vr(e)),p=b=>{let k=G(b.repository?.name)?.toLowerCase();return d.size===0||!k||d.has(k)},u=b=>p(b)&&(!i||Ed(b)===i),f=i?[["--branch",`refs/heads/${i}`],["--branch",`refs/tags/${i}`],["--reason","pullRequest"]]:[[]],y=new Map;for(let b of f){let k=um(e,t,r,b,u,a);if(!Array.isArray(k))return{provider:s,branch:i,runs:[],problem:k};for(let T of k)y.set(String(T.id),T)}c=[...y.values()].sort((b,k)=>(Date.parse(G(k.queueTime)??"")||0)-(Date.parse(G(b.queueTime)??"")||0)).slice(0,a).map(Ad)}let l=im(e);return{provider:s,branch:i,runs:c.map(d=>({...d,pending:l.get(`${s}:${d.id}`)??0}))}}var Td=e=>`run ${e} has no Saffron bundle: none was uploaded, or it expired. Its workflow needs saffron export and an upload of saffron-bundle* (see the guide, section 19)`;function Id(e,t,n,r,s,o){let i,a;if(n==="github"){let c=pe("gh",["api",`repos/{owner}/{repo}/actions/runs/${r}`],e,s);if(c.missing||c.status!==0)throw new D(kn(c).message,kn(c).kind);let l=mi(c.stdout),d=G(l?.repository?.full_name);if(!l||String(l.id)!==r||!d)throw new D(`gh answered with something other than run ${r}`);let p=G(l.head_repository?.full_name);p?.toLowerCase()!==d.toLowerCase()&&(i={event:G(l.event),from:p});let u=l.status==="completed"?"completed":l.status==="in_progress"?"in_progress":"queued";a={provider:n,id:r,attempt:typeof l.run_attempt=="number"?l.run_attempt:1,name:G(l.name),branch:G(l.head_branch),commit:G(l.head_sha),url:G(l.html_url),status:u,conclusion:u==="completed"?G(l.conclusion):void 0,createdAt:G(l.created_at)}}else{let c=pe("az",["pipelines","runs","show","--id",r,"--output","json",...rr(t)],e,s);if(c.missing||c.status!==0)throw new D(Pt(c).message,Pt(c).kind);let l=mi(c.stdout);if(!l||String(l.id)!==r)throw new D(`az answered with something other than run ${r}`);let d=Ad(l);/^true$/i.test(String((l.triggerInfo??{})["pr.isFork"]))&&(i={event:d.event}),a={provider:n,id:r,attempt:1,name:d.name,branch:d.branch,commit:d.commit,url:d.url,status:d.status,conclusion:d.conclusion,createdAt:d.createdAt}}if(i&&!o)throw new D(`run ${r}${i.event?` (${i.event})`:""} comes from ${i.from?`the fork ${i.from}`:"a fork"}: code from outside this repository made its bundle, and could have put anything in it. Read that pull request, then import with --allow-fork if you trust it`,"fork");return a}var Cd=/^saffron-bundle[\w.-]*$/;function gm(e,t,n,r,s){let o;if(n==="github"){let i=pe("gh",["api",`repos/{owner}/{repo}/actions/runs/${r}/artifacts?per_page=100`],e,s);if(i.missing||i.status!==0)throw new D(kn(i).message,kn(i).kind);let a=mi(i.stdout)?.artifacts;o=Array.isArray(a)?a.filter(c=>!!c&&typeof c=="object"):void 0}else{let i=pe("az",["pipelines","runs","artifact","list","--run-id",r,"--output","json",...rr(t)],e,s);if(i.missing||i.status!==0)throw new D(Pt(i).message,Pt(i).kind);o=ys(i.stdout)}if(!o)throw new D(`${n==="github"?"gh":"az"} answered with something other than a list of artifacts`);return o.filter(i=>typeof i.name=="string"&&Cd.test(i.name)).map(i=>({name:i.name,sizeBytes:Number(i.size_in_bytes??((i.resource??{}).properties??{}).artifactsize)||0,expired:i.expired===!0}))}function Pd(e,t,n,r,s,o,i){if(n==="github"){let c=pe("gh",["run","download",r,"--pattern","saffron-bundle*","--dir",s],e,o);if(c.missing||c.status!==0)throw new D(/no (valid )?artifact/i.test(tr(c))?Td(r):kn(c).message);return}let a=rr(t);if(!i){let c=pe("az",["pipelines","runs","artifact","list","--run-id",r,"--output","json",...a],e,o);if(c.missing||c.status!==0)throw new D(Pt(c).message);i=(ys(c.stdout)??[]).map(l=>l.name).filter(l=>typeof l=="string"&&Cd.test(l))}if(i.length===0)throw new D(Td(r));for(let c of i){let l=pe("az",["pipelines","runs","artifact","download","--run-id",r,"--artifact-name",c,"--path",Q.join(s,c),...a],e,o);if(l.missing||l.status!==0)throw new D(`cannot download ${c}: ${Pt(l).message}`)}}function Od(e,t,n,r={}){jd(n);let s=r.env??process.env,o=yi(e,t,r.provider),i=Id(e,t,o,n,s,r.allowFork===!0),a=Nd(e,o,n,i.attempt);if(i.status==="completed"&&oe.existsSync(a))return{provider:o,dir:Q.join(a,"bundles"),remove:()=>{}};let{dir:c,remove:l}=Bo(e);try{return Pd(e,t,o,n,c,s),{provider:o,dir:c,remove:l}}catch(d){throw l(),d}}function jd(e){if(!/^\d+$/.test(e))throw new D(`--run takes the run's id, a number as saffron runs lists it, not "${e}"`)}var wi=e=>Q.join(e,".saffron","ci"),Nd=(e,t,n,r)=>Q.join(wi(e),`${t}-${n}`,`attempt-${r}`),hm=10,mm=1024**3;function ym(e){let t=0;for(let n of oe.readdirSync(e,{recursive:!0})){let r=oe.lstatSync(Q.join(e,String(n)),{throwIfNoEntry:!1});r?.isFile()&&(t+=r.size)}return t}function wm(e,t){let n=wi(e),r=oe.readdirSync(n,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>Q.join(n,i.name)).map(i=>({run:i,mtime:oe.statSync(i).mtimeMs,bytes:ym(i)})).sort((i,a)=>+(a.run===t)-+(i.run===t)||a.mtime-i.mtime),s=0,o=0;for(let i of r){if(i.run!==t&&(s+1>hm||o+i.bytes>mm)){oe.rmSync(i.run,{recursive:!0,force:!0});continue}s++,o+=i.bytes}}var nr=class extends D{constructor(n,r){super(`this run's results are ${Math.ceil(n/1024**2)} MB, over --max-download ${Math.round(r/1024**2)} MB. Run again with a higher --max-download to download them`,"too-large");this.sizeBytes=n}sizeBytes};function bi(e,t,n,r={}){jd(n);let s=r.env??process.env,o=yi(e,t,r.provider),i=Id(e,t,o,n,s,r.allowFork===!0);if(i.status!=="completed")return{run:i,artifacts:[],reasonKind:"running",reason:`run ${n} has not finished: its results are uploaded when it does`};let a=gm(e,t,o,n,s),c=a.filter(k=>!k.expired),l=c.map(({name:k,sizeBytes:T})=>({name:k,sizeBytes:T})),d=Nd(e,o,n,i.attempt),p=new Date;if(oe.existsSync(d))return oe.utimesSync(Q.dirname(d),p,p),{run:i,folder:d,cached:!0,artifacts:l};if(c.length===0)return a.length>0?{run:i,artifacts:l,reasonKind:"expired",reason:`run ${n}'s Saffron bundle expired: the service keeps artifacts for a limited time`}:{run:i,artifacts:l,reasonKind:"none",reason:`run ${n} uploaded no Saffron bundle. The guide's workflow exports only when a run fails; set if: always() on the export and upload steps to keep every run's results`};let u=c.reduce((k,T)=>k+T.sizeBytes,0);if(r.maxDownloadBytes!==void 0&&u>r.maxDownloadBytes)throw new nr(u,r.maxDownloadBytes);let f=wi(e);oe.mkdirSync(f,{recursive:!0});let y=Q.join(f,".gitignore");oe.existsSync(y)||oe.writeFileSync(y,`*
|
|
1182
|
-
`)
|
|
1183
|
-
`).map(t=>t.trim()).find(Boolean);async function
|
|
1184
|
-
`),
|
|
1185
|
-
`).slice(-3).join(" ")}`);return e.stdout}function
|
|
1183
|
+
`}import{spawnSync as rf}from"node:child_process";import qe from"node:fs";import of from"node:os";import ce from"node:path";import{spawnSync as Hd}from"node:child_process";import se from"node:fs";import ne from"node:path";var Pm=["github","azure"],Ts={github:"GitHub Actions",azure:"Azure Pipelines"};function Cn(e){if(e.startsWith("@")||/[\x00-\x1f\x7f]/.test(e))throw new D(`${JSON.stringify(e)} is not a branch name Saffron passes on`);return e}function Om(e){let t=e.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\*)$/,"$1$1");return t=`"${t}"`,t=t.replace(/[()%!^"<>&|;, ]/g,"^$&"),t.replace(/[()%!^"<>&|;, ]/g,"^$&")}function Se(e,t,n,r,s){let o=process.platform==="win32"&&e==="az",i=o?Hd("az.cmd",t.map(Om),{cwd:n,env:r,input:s,encoding:"utf8",shell:!0,windowsVerbatimArguments:!0,timeout:6e5,maxBuffer:64*1024*1024}):Hd(e,t,{cwd:n,env:r,input:s,encoding:"utf8",timeout:6e5,maxBuffer:64*1024*1024}),a=i.error?.code,c=a==="ENOENT"||o&&i.status===9009;return{status:i.status,stdout:(i.stdout??"").trim(),stderr:(i.stderr??"").trim(),missing:c,timedOut:a==="ETIMEDOUT"}}var lr=e=>`${e.stderr}
|
|
1184
|
+
${e.stdout}`,Ri=(e,t)=>lr(e).split(`
|
|
1185
|
+
`).map(n=>n.trim()).find(n=>n&&!/^WARNING:/.test(n))??t;function Pn(e){return e.missing?{kind:"missing-tool",message:"the GitHub CLI (gh) is not installed here: install it from cli.github.com and sign in with gh auth login"}:e.timedOut?{kind:"failed",message:"gh did not finish within 10 minutes"}:/gh auth login|not logged in|authentication required/i.test(lr(e))?{kind:"signed-out",message:"gh is not signed in: run gh auth login"}:/none of the git remotes|no git remotes|not a git repository/i.test(lr(e))?{kind:"not-a-repository",message:Ri(e,"not a GitHub repository")}:{kind:"failed",message:Ri(e,`gh exited with ${e.status}`)}}function tn(e){if(e.missing)return{kind:"missing-tool",message:"the Azure CLI (az) is not installed here: install it, add its azure-devops extension (az extension add --name azure-devops) and sign in (az login, or AZURE_DEVOPS_EXT_PAT)"};if(e.timedOut)return{kind:"failed",message:"az did not finish within 10 minutes"};let t=lr(e);return/azure-devops|'pipelines' is (misspelled|not in)|not in the 'az' command group/i.test(t)&&!/login/i.test(t)?{kind:"missing-tool",message:"the Azure CLI has no azure-devops extension: az extension add --name azure-devops"}:/az login|az devops login|TF400813|not authorized|authentication failed|\b401\b/i.test(t)?{kind:"signed-out",message:"az is not signed in to Azure DevOps: run az login, or set AZURE_DEVOPS_EXT_PAT"}:/--organization|--org\b|--project|must be specified|could not detect/i.test(t)?{kind:"not-a-repository",message:"cannot tell which Azure DevOps organization and project: run this in a clone of an Azure Repos repository, or set ci.organization and ci.project in saffron.config.json"}:{kind:"failed",message:Ri(e,`az exited with ${e.status}`)}}function Ai(e,t,n){let r=n??t.ci?.provider;if(r!==void 0){if(!Pm.includes(r))throw new D(`unknown CI provider "${r}": use "github" or "azure"`);return r}return ns(e).some(s=>s.startsWith("dev.azure.com/"))?"azure":"github"}var fr=e=>[...e.ci?.organization?["--organization",e.ci.organization]:[],...e.ci?.project?["--project",e.ci.project]:[]];function jm(e,t){let n=Se("git",["rev-parse","--abbrev-ref","HEAD"],e,t),r=n.status===0?n.stdout.trim():"";return r&&r!=="HEAD"?r:void 0}function Nm(e){let t=new Map;for(let[n,r]of Object.entries(ht(e))){try{if(Be(ne.join(e,n))!==r.revision)continue}catch{continue}r.from.run&&t.set(r.from.run,(t.get(r.from.run)??0)+1)}return t}function Jd(e,t=Date.now()){let n=e?t-Date.parse(e):NaN;if(!(n>=0))return;let r=Math.round(n/6e4);if(r<60)return`${r} min ago`;let s=Math.round(r/60);return s<48?`${s} h ago`:`${Math.round(s/24)} days ago`}var Q=e=>typeof e=="string"&&e?e:void 0,qd=e=>Q(e)?.replace(/^refs\/(heads|tags)\//,""),Fm="databaseId,number,attempt,displayTitle,workflowName,status,conclusion,event,headBranch,headSha,createdAt,url";function Mm(e){let t=e.status==="completed"?"completed":e.status==="in_progress"?"in_progress":"queued";return{id:String(e.databaseId),name:Q(e.workflowName)??"workflow",number:String(e.number??""),title:Q(e.displayTitle),status:t,conclusion:t==="completed"?Q(e.conclusion):void 0,event:Q(e.event),branch:Q(e.headBranch),commit:Q(e.headSha),createdAt:Q(e.createdAt),url:Q(e.url),attempt:typeof e.attempt=="number"?e.attempt:void 0}}var Lm={completed:"completed",inProgress:"in_progress",cancelling:"in_progress"},Dm={succeeded:"success",partiallySucceeded:"partial",failed:"failure",canceled:"cancelled"},Bm={individualCI:"push",batchedCI:"push",pullRequest:"pull_request",schedule:"schedule",manual:"manual"};function Wd(e){let t=e.triggerInfo??{};return qd(t["pr.sourceBranch"])??qd(e.sourceBranch)}function Vd(e){let t=e.triggerInfo??{},n=Lm[String(e.status)]??"queued",r=Q(e.result);return{id:String(e.id),name:Q(e.definition?.name)??"pipeline",number:String(e.buildNumber??e.id),status:n,conclusion:n==="completed"&&r?Dm[r]??r:void 0,event:Q(e.reason)?Bm[String(e.reason)]??String(e.reason):void 0,branch:Wd(e),commit:Q(t["pr.sourceSha"])??Q(e.sourceVersion),createdAt:Q(e.queueTime),url:Q((e._links??{}).web?.href)}}function Ti(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function _i(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>!!n&&typeof n=="object"):void 0}catch{return}}function Um(e){return new Set(e.map(t=>t.startsWith("dev.azure.com/")?t.slice(t.lastIndexOf("/_git/")+6):t.slice(t.indexOf("/")+1)))}function zm(e,t,n,r,s,o,i=Math.min(Math.max(o,50),500)){for(let a=i;;a=Math.min(a*2,500)){let c=Se("az",["pipelines","runs","list","--top",String(a),...r,"--output","json",...fr(t)],e,n);if(c.missing||c.status!==0)return tn(c);let l=_i(c.stdout);if(!l)return{kind:"failed",message:"az answered with something other than a list of runs"};let d=l.filter(s);if(d.length>=o||l.length<a||a>=500)return d}}function Gd(e,t,n={}){let r=n.env??process.env,s=Ai(e,t,n.provider),o=n.branch??jm(e,r),i=o===void 0?void 0:Cn(o),a=n.limit??20,c;if(s==="github"){let d=Se("gh",["run","list","--limit",String(a),"--json",Fm,...i?["--branch",i]:[]],e,r);if(d.missing||d.status!==0)return{provider:s,branch:i,runs:[],problem:Pn(d)};let p=_i(d.stdout);if(!p)return{provider:s,branch:i,runs:[],problem:{kind:"failed",message:"gh answered with something other than a list of runs"}};c=p.map(Mm)}else{let d=Um(ns(e)),p=w=>{let $=Q(w.repository?.name)?.toLowerCase();return d.size===0||!$||d.has($)},u=w=>p(w)&&(!i||Wd(w)===i),f=i?[["--branch",`refs/heads/${i}`],["--branch",`refs/tags/${i}`],["--reason","pullRequest"]]:[[]],h=new Map;for(let w of f){let $=zm(e,t,r,w,u,a);if(!Array.isArray($))return{provider:s,branch:i,runs:[],problem:$};for(let k of $)h.set(String(k.id),k)}c=[...h.values()].sort((w,$)=>(Date.parse(Q($.queueTime)??"")||0)-(Date.parse(Q(w.queueTime)??"")||0)).slice(0,a).map(Vd)}let l=Nm(e);return{provider:s,branch:i,runs:c.map(d=>({...d,pending:l.get(`${s}:${d.id}`)??0}))}}var Ei=e=>`run ${e} has no Saffron bundle: none was uploaded, or it expired. Its workflow needs saffron export and an upload of saffron-bundle* (see the guide, section 19)`;function Kd(e,t,n,r,s,o){let i,a;if(n==="github"){let c=Se("gh",["api",`repos/{owner}/{repo}/actions/runs/${r}`],e,s);if(c.missing||c.status!==0)throw new D(Pn(c).message,Pn(c).kind);let l=Ti(c.stdout),d=Q(l?.repository?.full_name);if(!l||String(l.id)!==r||!d)throw new D(`gh answered with something other than run ${r}`);let p=Q(l.head_repository?.full_name);p?.toLowerCase()!==d.toLowerCase()&&(i={event:Q(l.event),from:p});let u=l.status==="completed"?"completed":l.status==="in_progress"?"in_progress":"queued";a={provider:n,id:r,attempt:typeof l.run_attempt=="number"?l.run_attempt:1,name:Q(l.name),branch:Q(l.head_branch),commit:Q(l.head_sha),url:Q(l.html_url),status:u,conclusion:u==="completed"?Q(l.conclusion):void 0,createdAt:Q(l.created_at)}}else{let c=Se("az",["pipelines","runs","show","--id",r,"--output","json",...fr(t)],e,s);if(c.missing||c.status!==0)throw new D(tn(c).message,tn(c).kind);let l=Ti(c.stdout);if(!l||String(l.id)!==r)throw new D(`az answered with something other than run ${r}`);let d=Vd(l);/^true$/i.test(String((l.triggerInfo??{})["pr.isFork"]))&&(i={event:d.event}),a={provider:n,id:r,attempt:1,name:d.name,branch:d.branch,commit:d.commit,url:d.url,status:d.status,conclusion:d.conclusion,createdAt:d.createdAt}}if(i&&!o)throw new D(`run ${r}${i.event?` (${i.event})`:""} comes from ${i.from?`the fork ${i.from}`:"a fork"}: code from outside this repository made its bundle, and could have put anything in it. Read that pull request, then import with --allow-fork if you trust it`,"fork");return a}var Hm=/^saffron-bundle[\w.-]*$/;function Yd(e,t,n,r,s){let o;if(n==="github"){o=[];for(let i=1;o;i++){let a=Se("gh",["api",`repos/{owner}/{repo}/actions/runs/${r}/artifacts?per_page=100&page=${i}`],e,s);if(a.missing||a.status!==0)throw new D(Pn(a).message,Pn(a).kind);let c=Ti(a.stdout)?.artifacts;if(!Array.isArray(c))o=void 0;else if(o.push(...c.filter(l=>!!l&&typeof l=="object")),c.length<100)break}}else{let i=Se("az",["pipelines","runs","artifact","list","--run-id",r,"--output","json",...fr(t)],e,s);if(i.missing||i.status!==0)throw new D(tn(i).message,tn(i).kind);o=_i(i.stdout)}if(!o)throw new D(`${n==="github"?"gh":"az"} answered with something other than a list of artifacts`);return o.filter(i=>typeof i.name=="string"&&Hm.test(i.name)).map(i=>({name:i.name,sizeBytes:Number(i.size_in_bytes??((i.resource??{}).properties??{}).artifactsize)||0,expired:i.expired===!0}))}function Zd(e,t,n,r,s,o,i){if(i.length===0)throw new D(Ei(r));for(let a of i){let c=n==="github"?Se("gh",["run","download",r,"-n",a,"--dir",ne.join(s,a)],e,o):Se("az",["pipelines","runs","artifact","download","--run-id",r,"--artifact-name",a,"--path",ne.join(s,a),...fr(t)],e,o);if(c.missing||c.status!==0)throw n==="github"&&/no (valid )?artifact/i.test(lr(c))?new D(Ei(r)):new D(`cannot download ${a}: ${(n==="github"?Pn(c):tn(c)).message}`)}}function Qd(e,t,n,r={}){Xd(n);let s=r.env??process.env,o=Ai(e,t,r.provider),i=Kd(e,t,o,n,s,r.allowFork===!0),a=ef(e,o,n,i.attempt);if(i.status==="completed"&&se.existsSync(a))return{provider:o,dir:ne.join(a,"bundles"),remove:()=>{}};let c=Yd(e,t,o,n,s).filter(p=>!p.expired).map(p=>p.name);if(c.length===0)throw new D(Ei(n));let{dir:l,remove:d}=Ko(e);try{return Zd(e,t,o,n,l,s,c),{provider:o,dir:l,remove:d}}catch(p){throw d(),p}}function Xd(e){if(!/^\d+$/.test(e))throw new D(`--run takes the run's id, a number as saffron runs lists it, not "${e}"`)}var Ii=e=>ne.join(e,".saffron","ci"),ef=(e,t,n,r)=>ne.join(Ii(e),`${t}-${n}`,`attempt-${r}`),qm=10,Jm=1024**3;function Wm(e){let t=0;for(let n of se.readdirSync(e,{recursive:!0})){let r=se.lstatSync(ne.join(e,String(n)),{throwIfNoEntry:!1});r?.isFile()&&(t+=r.size)}return t}function Vm(e,t){let n=Ii(e),r=se.readdirSync(n,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>ne.join(n,i.name)).map(i=>({run:i,mtime:se.statSync(i).mtimeMs,bytes:Wm(i)})).sort((i,a)=>+(a.run===t)-+(i.run===t)||a.mtime-i.mtime),s=0,o=0;for(let i of r){if(i.run!==t&&(s+1>qm||o+i.bytes>Jm)){se.rmSync(i.run,{recursive:!0,force:!0});continue}s++,o+=i.bytes}}var dr=class extends D{constructor(n,r){super(`this run's results are ${Math.ceil(n/1024**2)} MB, over --max-download ${Math.round(r/1024**2)} MB. Run again with a higher --max-download to download them`,"too-large");this.sizeBytes=n}sizeBytes};function Ci(e,t,n,r={}){Xd(n);let s=r.env??process.env,o=Ai(e,t,r.provider),i=Kd(e,t,o,n,s,r.allowFork===!0);if(i.status!=="completed")return{run:i,artifacts:[],reasonKind:"running",reason:`run ${n} has not finished: its results are uploaded when it does`};let a=Yd(e,t,o,n,s),c=a.filter(k=>!k.expired),l=c.map(({name:k,sizeBytes:y})=>({name:k,sizeBytes:y})),d=ef(e,o,n,i.attempt),p=new Date;if(se.existsSync(d))return se.utimesSync(ne.dirname(d),p,p),{run:i,folder:d,cached:!0,artifacts:l};if(c.length===0)return a.length>0?{run:i,artifacts:l,reasonKind:"expired",reason:`run ${n}'s Saffron bundle expired: the service keeps artifacts for a limited time`}:{run:i,artifacts:l,reasonKind:"none",reason:`run ${n} uploaded no Saffron bundle. The guide's workflow exports only when a run fails; set if: always() on the export and upload steps to keep every run's results`};let u=c.reduce((k,y)=>k+y.sizeBytes,0);if(r.maxDownloadBytes!==void 0&&u>r.maxDownloadBytes)throw new dr(u,r.maxDownloadBytes);let f=Ii(e);se.mkdirSync(f,{recursive:!0});let h=ne.join(f,".gitignore");se.existsSync(h)||se.writeFileSync(h,`*
|
|
1186
|
+
`),se.mkdirSync(ne.dirname(d),{recursive:!0});let w=se.mkdtempSync(`${d}.partial-`);try{Zd(e,t,o,n,ne.join(w,"bundles"),s,c.map(k=>k.name));try{se.renameSync(w,d)}catch(k){if(!se.existsSync(d))throw k;return se.utimesSync(ne.dirname(d),p,p),{run:i,folder:d,cached:!0,artifacts:l}}}finally{se.rmSync(w,{recursive:!0,force:!0})}let $=Date.now()-1440*60*1e3;for(let k of se.readdirSync(ne.dirname(d))){let y=ne.join(ne.dirname(d),k),v=/^attempt-(\d+)$/.exec(k),S=/^attempt-\d+\.partial$/.test(k)||/^attempt-\d+\.partial-/.test(k)&&(se.statSync(y,{throwIfNoEntry:!1})?.mtimeMs??1/0)<$;(v&&Number(v[1])<i.attempt||S)&&se.rmSync(y,{recursive:!0,force:!0})}return se.utimesSync(ne.dirname(d),p,p),Vm(e,ne.dirname(d)),{run:i,folder:d,cached:!1,artifacts:l}}async function Pi(e,t,n){let{run:r,folder:s}=t;return Xc(e,s,[ne.join(s,"bundles")],n,{run:`${r.provider}:${r.id}`,describe:o=>`${Ts[r.provider]} run ${r.id} (${ne.basename(ne.dirname(o))})`})}var Gm=e=>e?.split(`
|
|
1187
|
+
`).map(t=>t.trim()).find(Boolean);async function tf(e,t,n,r,s={}){let o=Ci(e,t,r,s);if(!o.folder)return{results:{run:o.run,bundle:null,reasonKind:o.reasonKind,reason:o.reason,warnings:[]}};let i=o.folder,a=await Pi(e,{...o,folder:i},n),c=h=>xe(e,ne.join(i,h)),l=h=>se.existsSync(ne.join(i,h)),d={run:o.run,bundle:{folder:xe(e,i),cached:o.cached===!0,artifacts:o.artifacts},warnings:a.warnings},{report:p}=a;if(p){let{green:h,yellow:w,red:$,aiCalls:k,costUsd:y}=p.totals;d.totals={green:h,yellow:w,red:$,aiCalls:k,costUsd:y},d.scenarios=p.scenarios.map(v=>{let S=(v.evidence??[]).filter(g=>l(g.file)),x=S.filter(g=>g.kind!=="trace"),b=x.find(g=>g.kind==="failure")??x.find(g=>g.kind==="before-heal")??x[0],R=S.filter(g=>g.kind==="trace"),m=R.find(g=>!g.proof)??R[0];return{feature:v.feature,scenario:Jt(v),displayName:v.scenario,tags:v.tags,status:v.status,durationMs:v.durationMs,verified:v.verified,failingStep:v.steps.find(g=>g.status==="failed")?.gherkin,error:Gm(v.error),narrative:v.narrative,screenshot:b&&c(b.file),trace:m&&c(m.file)}}),se.writeFileSync(ne.join(i,"report.json"),`${JSON.stringify(p,null,2)}
|
|
1188
|
+
`),Te(ne.join(i,"report.html"),At(p,i)),d.reportHtml=c("report.html")}else d.scenarios=[];d.proposals=a.proposals;let{warnings:u,...f}=d;return{results:{...f,warnings:u},report:p}}function nf(e,t,n,r){let s=Se("az",["repos","pr","create","--draft","true","--source-branch",`refs/heads/${Cn(n.branch)}`,"--target-branch",`refs/heads/${Cn(n.base)}`,"--title",n.title,"--description",`@${n.bodyFile}`,"--output","json",...fr(t)],e,r);if(s.missing||s.status!==0)return{problem:`az repos pr create failed: ${tn(s).message}`};try{let o=JSON.parse(s.stdout),i=o.repository?.webUrl;return{url:i&&o.pullRequestId!==void 0?`${i}/pullrequest/${o.pullRequestId}`:void 0}}catch{return{}}}function sf(e,t,n){if(e.missing)throw new D(`${n}: ${t} is not installed here`);if(e.timedOut)throw new D(`${n}: ${t} did not finish within 10 minutes`);if(e.status!==0)throw new D(`${n}: ${(e.stderr||e.stdout||`exit ${e.status}`).split(`
|
|
1189
|
+
`).slice(-3).join(" ")}`);return e.stdout}function Km(e,t){let n=i=>Se("git",["config",i],e,t).stdout,r=t.GIT_AUTHOR_NAME||n("user.name"),s=t.GIT_AUTHOR_EMAIL||n("user.email"),o=t.GITHUB_ACTIONS==="true"?{name:"github-actions[bot]",email:"41898282+github-actions[bot]@users.noreply.github.com"}:{name:"Saffron",email:"saffron@localhost"};return{...t,GIT_AUTHOR_NAME:r||o.name,GIT_AUTHOR_EMAIL:s||o.email,GIT_COMMITTER_NAME:t.GIT_COMMITTER_NAME||r||o.name,GIT_COMMITTER_EMAIL:t.GIT_COMMITTER_EMAIL||s||o.email}}var Es=(e,t)=>`${e} ${t}${e===1?"":"s"}`,pr=e=>`\`${e.replaceAll("`","'")}\``,Oi=e=>{let t=e.startsWith("-")?`./${e}`:e;return/^[\w./-]+$/.test(t)?t:`'${t.replaceAll("'","'\\''")}'`};function ji(e,t=""){let n=Math.max(0,...[...e.matchAll(/`+/g)].map(s=>s[0].length)),r="`".repeat(Math.max(3,n+1));return`${r}${t}
|
|
1186
1190
|
${e}
|
|
1187
|
-
${r}`}var
|
|
1191
|
+
${r}`}var af={github:6e4,azure:3800};function Ym(e,t,n,r="",s=af.github){let{manifest:o,proposals:i}=t,a=o.run?o.url&&/^https?:\/\//i.test(o.url)?`[run ${o.run}](${o.url})`:`run ${pr(o.run)}`:"a run",c=o.headCommit??o.commit,l=[o.branch&&`on ${pr(o.branch)}`,c&&`at ${pr(c.slice(0,7))}`].filter(Boolean).join(" "),d=[`Saffron filed ${Es(i.length,"proposal")} in ${a}${l?` ${l}`:""}. This pull request carries ${i.length===1?"the proposal, not the recording":"the proposals, not the recordings"}: nothing is accepted until you accept it.`,"","**To review and accept** (no agent runs on your machine):","",ji([`git fetch origin ${Oi(n)} && git switch ${Oi(n)}`,...r?[`cd ${Oi(r.replace(/\/$/,""))}`]:[],"npx -y -p saffron-ai saffron diff","npx -y -p saffron-ai saffron accept --all",'git add -A .saffron/cache && git add -u .saffron/proposals && git commit -m "Accept Saffron proposals" && git push'].join(`
|
|
1188
1192
|
`),"bash"),"","Then mark this pull request ready for review. `accept --all` leaves UNVERIFIED proposals out: read one, and accept it by file if it is right. `saffron accept` refuses a proposal whose scenario or recording changed since it was filed."],p=d.join(`
|
|
1189
|
-
`).length;for(let[u,{proposal:f}]of i.entries()){let{feature:
|
|
1190
|
-
`),
|
|
1191
|
-
`);if(p+
|
|
1193
|
+
`).length;for(let[u,{proposal:f}]of i.entries()){let{feature:h,scenario:w}=f.cache,{mode:$,verified:k,proofError:y,narrative:v,adaptations:S}=f.meta,x=k===!0?"**verified \u2713**: a zero-AI proof replay passed":k===!1?"**UNVERIFIED \u2717**: its proof replay failed":"not verified: proof replays were off",b=[v,...S.map(g=>`\u26A0 ${g}`),...k===!1&&y?[`Proof replay: ${y}`]:[]].filter(Boolean).join(`
|
|
1194
|
+
`),R=Ur(Et(xt(re(e,h,w)),f.cache,f.meta.featureEdits)),m=["",`### ${pr(h)} \u203A ${pr(w)}`,"",`${$==="heal"?"Heal":"First recording"}, ${x}`,"",...b?[ji(b,"text"),""]:[],ji(R,"diff")].join(`
|
|
1195
|
+
`);if(p+m.length>s){d.push("",`\u2026and ${Es(i.length-u,"more proposal")}: run \`saffron diff\` on the branch to see ${i.length-u===1?"it":"them"}.`);break}d.push(m),p+=m.length+1}return`${d.join(`
|
|
1192
1196
|
`)}
|
|
1193
|
-
`}var
|
|
1194
|
-
`)[0]:String(
|
|
1195
|
-
`)}function
|
|
1196
|
-
`).slice(-2).join(" ")}`,failed:!0}:{...
|
|
1197
|
-
`).pop()}}import
|
|
1198
|
-
`)}function
|
|
1197
|
+
`}var Ni=e=>e.split(/[\\/]/).join("/");function Zm(e,t,n,r,s,o){let i=qe.mkdtempSync(ce.join(of.tmpdir(),"saffron-head-")),a=h=>{let w=rf("git",["show",`${n}:${r}${Ni(h)}`],{cwd:e,env:s,timeout:6e5,maxBuffer:67108864});return w.status===0?w.stdout:void 0},c=h=>{let w=ce.relative(e,ce.resolve(e,h));return!w.startsWith("..")&&!ce.isAbsolute(w)?Ni(w):void 0},l=c(o.features??"features"),d=c(o.dataDir??"data"),p=rf("git",["ls-tree","-r","-z","--full-tree","--name-only",n,"--",...[l,d].flatMap(h=>h===void 0?[]:[`${r}${h}`||"."])],{cwd:e,env:s,encoding:"utf8",timeout:6e5,maxBuffer:64*1024*1024}),u=Ae(),f=[];try{for(let w of(l!==void 0||d!==void 0)&&p.status===0?p.stdout.split("\0").filter(Boolean):[]){let $=w.slice(r.length);if(!(d!==void 0&&(d===""||$.startsWith(`${d}/`)))&&!$.endsWith(".saffron"))continue;let y=a($);y!==void 0&&(qe.mkdirSync(ce.dirname(ce.join(i,$)),{recursive:!0}),qe.writeFileSync(ce.join(i,$),y))}d!==void 0&&Ye(i,d,u.env);let h;try{h=Ie(i,o,[])}catch(w){let $=`cannot be checked: the StepSets at ${n.slice(0,7)} do not parse: ${w instanceof Error?w.message.split(`
|
|
1198
|
+
`)[0]:String(w)}`;return t.proposals.map(({file:k})=>({file:k,reason:$}))}for(let{file:w,proposal:$}of t.proposals){let{feature:k,scenario:y}=$.cache,v=a(k);if(!v){f.push({file:w,reason:`is for ${k}, which is not in ${n.slice(0,7)}`});continue}qe.mkdirSync(ce.dirname(ce.join(i,k)),{recursive:!0}),qe.writeFileSync(ce.join(i,k),v);let S=Ni(ce.relative(e,re(e,k,y))),x=a(S);qe.rmSync(ce.join(i,S),{force:!0}),x&&(qe.mkdirSync(ce.dirname(ce.join(i,S)),{recursive:!0}),qe.writeFileSync(ce.join(i,S),x));let b;try{b=Le(i,$,h)}catch(R){b=`cannot be checked: ${R instanceof Error?R.message:String(R)}`}b&&f.push({file:w,reason:`does not fit ${n.slice(0,7)}: ${b}`})}}finally{d!==void 0&&Ye(e,u.dir,u.env),qe.rmSync(i,{recursive:!0,force:!0})}return f}function Qm(e){let{manifest:t,proposals:n}=e;return[`Saffron: ${Es(n.length,"proposal")} to review${t.run?` from run ${t.run}`:""}`,"",...n.map(({proposal:r})=>`${r.cache.feature} \u203A ${r.cache.scenario} (${r.meta.mode}${r.meta.verified===!0?", verified":r.meta.verified===!1?", UNVERIFIED":""})`),"","Proposals only: nothing is accepted until someone runs saffron accept."].join(`
|
|
1199
|
+
`)}function ur(e,t){if(t!==void 0&&/[$`;|&<>()\s'"\\]/.test(t))throw new D(`${e} ${JSON.stringify(t)}: a branch name with a space, a quote or any of $ \` ; | & < > ( ) \\ is not accepted, as the pull request gives it to a shell`)}function cf(e,t,n,r={}){let s=r.env??process.env,o=(b,R,m={})=>sf(Se("git",R,e,m.env??s,m.input),"git",b),{manifest:i}=t;if(t.proposals.length===0)throw new D("there are no pending proposals to push");let a=r.base??i.branch;if(!a)throw new D("cannot tell which branch the pull request is for: pass --base <branch>");if(Cn(a),Cn(n),ur("--branch",n),ur("--base",r.base),n===a)throw new D(`--branch ${n} is the branch the proposals are for: name a new one, e.g. saffron/heal-<run id>`);if(n.startsWith("-"))throw new D(`${n} is not a branch name git accepts`);o(`${n} is not a branch name git accepts`,["check-ref-format","--branch",n]);let c=i.headCommit??i.commit;if(!c||!/^[0-9a-f]{40}([0-9a-f]{24})?$/i.test(c))throw new D("cannot tell which commit the run tested: run it in a git checkout");let l=o("not a git checkout",["rev-parse","HEAD"]);if(c!==l&&!Vo(e,l).includes(c)&&Se("git",["merge-base","--is-ancestor",c,l],e,s).status!==0)throw new D(`${c.slice(0,7)}, the commit the branch would start on, is not this checkout's HEAD, a commit it merged or one it descends from: run export --branch in the checkout the run tested`);Se("git",["cat-file","-e",`${c}^{commit}`],e,s).status!==0&&o(`the commit to build on, ${c.slice(0,7)}, is not in this clone and could not be fetched`,["fetch","--quiet","--no-tags","--depth=1","origin",c]);let d=Se("git",["ls-remote","--exit-code","--heads","origin",`refs/heads/${n}`],e,s);if(d.status===0)throw new D(`branch ${n} already exists on origin: give each run its own, e.g. saffron/heal-<run id>-<attempt>`);d.status!==2&&sf(d,"git","cannot reach origin");let p=o("not a git checkout",["rev-parse","--show-prefix"]),u=Zm(e,t,c,p,s,r.config??{}),f={...t,proposals:t.proposals.filter(b=>!u.some(R=>R.file===b.file))};if(f.proposals.length===0)throw new D(`no proposal fits ${c.slice(0,7)}, the commit the branch would start on: ${u.map(b=>`${ce.relative(e,b.file)} ${b.reason}`).join("; ")}`);let h=qe.mkdtempSync(ce.join(of.tmpdir(),"saffron-index-")),w={...s,GIT_INDEX_FILE:ce.join(h,"index")},$;try{o("cannot read the tested commit",["read-tree",c],{env:w});for(let{file:R,bytes:m}of f.proposals){let g=o("cannot store a proposal",["hash-object","-w","--stdin"],{input:m}),T=`${p}${ce.relative(e,R).split(ce.sep).join("/")}`;o("cannot stage a proposal",["update-index","--add","--cacheinfo",`100644,${g},${T}`],{env:w})}let b=o("cannot write the tree",["write-tree"],{env:w});$=o("cannot commit the proposals",["commit-tree",b,"-p",c,"-m",Qm(f)],{env:Km(e,s)})}finally{qe.rmSync(h,{recursive:!0,force:!0})}o(`cannot push ${n} to origin`,["push","--quiet","origin",`${$}:refs/heads/${n}`]);let k=i.repository?.startsWith("github.com/")?"github":i.repository?.startsWith("dev.azure.com/")?"azure":s.GITHUB_ACTIONS==="true"?"github":s.TF_BUILD==="True"?"azure":void 0,y=ce.join(ce.dirname(f.file),"saffron-pull-request.md");qe.writeFileSync(y,Ym(e,f,n,p,af[k??"github"]));let v={branch:n,base:a,commit:$,parent:c,bodyFile:y,leftOut:u};if(!k)return{...v,noPullRequest:`${i.repository??"this repository"} is not on GitHub or Azure DevOps`};let S=`Saffron: ${Es(f.proposals.length,"proposal")} to review for ${a}`;if(k==="azure"){let b=nf(e,r.config??{},{branch:n,base:a,title:S,bodyFile:y},s);return b.problem?{...v,noPullRequest:b.problem,failed:!0}:b.url?{...v,pullRequest:b.url}:{...v,noPullRequest:"az created it but did not say where",failed:!0}}let x=Se("gh",["pr","create","--draft","--base",a,"--head",n,"--title",S,"--body-file",y],e,s);return x.missing?{...v,noPullRequest:"the gh CLI is not installed here",failed:!0}:x.status!==0?{...v,noPullRequest:`gh pr create failed: ${(x.stderr||x.stdout).split(`
|
|
1200
|
+
`).slice(-2).join(" ")}`,failed:!0}:{...v,pullRequest:x.stdout.split(`
|
|
1201
|
+
`).pop()}}import W from"node:fs";import ee from"node:path";var gr={claude:".claude/skills",agents:".agents/skills",copilot:".github/skills",cursor:".cursor/skills"},Xm=["claude","agents"],ff="<!-- saffron:start -->",Mi="<!-- saffron:end -->";function ey(){return[ff,"## Saffron end-to-end tests","","UI tests are plain-Gherkin `.feature` / `.saffron` files under `features/`,","run by Saffron (`npx saffron run`). No step definitions exist: an AI agent","records each scenario once; later runs replay at zero tokens.","","- Load the `saffron` skill before writing or editing scenarios.","- Exact step text is the cache identity: run `npx saffron steps` and reuse"," recorded wordings instead of inventing synonyms.","- `Then` steps are never healed: write them as the verdict, last.","- `npx saffron status` shows what is cached, what awaits review, the tags"," and vocabulary health; editing a cached scenario's text re-records it.","- Never edit `.saffron/cache/` or `.saffron/proposals/` by hand; change the"," scenario text and re-run. Review proposals with `npx saffron accept`"," (`--all`, or chosen files) and `npx saffron reject`.","- A heal made in CI arrives as a bundle: `npx saffron runs` lists the"," branch's CI runs, `npx saffron import --run <id>` files its proposals"," here; then review and accept as above. `npx saffron trace <scenario>`"," replays a red or healed scenario step by step.","- Secrets go in `{env:VAR}` tokens, never in files.","- Shared test data (accounts, names, enum values) goes in `data/*.json`,",' referenced as `{data:file.path.key}`; check a whole list with "every',' {data:file.list}"; read Examples rows from a file with'," `Examples: {data:file}` (.saffron only). Use `{unique:name}` for a value"," that must be new on every run. Never put secrets in `data/`.",Mi,""].join(`
|
|
1202
|
+
`)}function lf(e,t){if(!W.existsSync(e))return W.writeFileSync(e,t),"created";let n=W.readFileSync(e,"utf8"),r=n.indexOf(ff),s=n.indexOf(Mi);if(r!==-1&&s!==-1&&s>r){let i=n.slice(0,r)+t.trimEnd()+n.slice(s+Mi.length);return i===n?"unchanged":(W.writeFileSync(e,i),"updated")}let o=n.endsWith(`
|
|
1199
1203
|
`)?`
|
|
1200
1204
|
`:`
|
|
1201
1205
|
|
|
1202
|
-
`;return
|
|
1203
|
-
`),s?"updated":"created")}function
|
|
1204
|
-
`),n.scaffolded.push("saffron.config.json"));let o=
|
|
1206
|
+
`;return W.writeFileSync(e,n+o+t),"updated"}var Fi={command:"npx",args:["saffron","mcp"]},ty={claude:{file:".mcp.json",key:"mcpServers",entry:Fi},cursor:{file:".cursor/mcp.json",key:"mcpServers",entry:Fi},copilot:{file:".vscode/mcp.json",key:"servers",entry:{type:"stdio",...Fi}}},df={agents:"codex mcp add saffron -- npx saffron mcp (Codex; other hosts: see their MCP settings)"};function ny(e,t){let n=ee.join(e,t.file),r={},s=W.existsSync(n);if(s)try{r=JSON.parse(W.readFileSync(n,"utf8"))}catch{throw new Error(`${t.file} is not valid JSON: fix it or remove it, then re-run`)}let o=r[t.key]??{};return JSON.stringify(o.saffron)===JSON.stringify(t.entry)?"unchanged":(o.saffron=t.entry,r[t.key]=o,W.mkdirSync(ee.dirname(n),{recursive:!0}),W.writeFileSync(n,JSON.stringify(r,null,2)+`
|
|
1207
|
+
`),s?"updated":"created")}function pf(e,t){W.mkdirSync(t,{recursive:!0});for(let n of W.readdirSync(e,{withFileTypes:!0})){let r=ee.join(e,n.name),s=ee.join(t,n.name);n.isDirectory()?pf(r,s):W.copyFileSync(r,s)}}function uf(e){let t=ee.join(e.packageRoot,"skills","saffron");if(!W.existsSync(ee.join(t,"SKILL.md")))throw new Error(`bundled skill not found at ${t}`);let n={skillDirs:[],instructionFiles:[],scaffolded:[],mcpFiles:[],mcpHints:[]},r=e.targets??Xm;for(let s of r){let o=ee.join(e.projectRoot,gr[s],"saffron");W.existsSync(o)&&W.rmSync(o,{recursive:!0,force:!0}),pf(t,o),n.skillDirs.push(ee.relative(e.projectRoot,o))}if(e.mcp!==!1)for(let s of r){let o=ty[s];o?n.mcpFiles.push({file:o.file,outcome:ny(e.projectRoot,o)}):df[s]&&n.mcpHints.push(df[s])}if(e.instructions!==!1){let s=ey(),o=ee.join(e.projectRoot,"AGENTS.md");n.instructionFiles.push({file:"AGENTS.md",outcome:lf(o,s)});let i=ee.join(e.projectRoot,"CLAUDE.md");W.existsSync(i)&&n.instructionFiles.push({file:"CLAUDE.md",outcome:lf(i,s)})}if(e.examples){n.examples=ry(e.projectRoot,e.packageRoot);for(let s of n.examples.files)n.scaffolded.push(s)}if(e.scaffold!==!1){let s=ee.join(e.projectRoot,"saffron.config.json");W.existsSync(s)||(W.writeFileSync(s,JSON.stringify({baseURL:"http://localhost:3000",features:"features"},null,2)+`
|
|
1208
|
+
`),n.scaffolded.push("saffron.config.json"));let o=ee.join(e.projectRoot,"features");W.existsSync(o)||(W.mkdirSync(o,{recursive:!0}),n.scaffolded.push("features/"));let i=ee.join(e.projectRoot,".gitignore"),a=[".saffron/reports/",".saffron/artifacts/",".saffron/ci/",...e.examples?[".env"]:[]],c=W.existsSync(i)?W.readFileSync(i,"utf8"):"",l=[];for(let d of a)c.split(`
|
|
1205
1209
|
`).some(p=>p.trim()===d)||(c+=(c&&!c.endsWith(`
|
|
1206
1210
|
`)?`
|
|
1207
1211
|
`:"")+d+`
|
|
1208
|
-
`,l.push(d));l.length>0&&(
|
|
1209
|
-
`)}import{spawn as
|
|
1210
|
-
`))}function
|
|
1211
|
-
`)[0]}`),
|
|
1212
|
-
interrupted: stopping, then running teardown`),
|
|
1213
|
-
${
|
|
1214
|
-
${
|
|
1215
|
-
${
|
|
1216
|
-
`)[0]:"not checked: no proof replay ran";console.log(`skipped UNVERIFIED ${L.basename(a)} (${
|
|
1217
|
-
`)[0])}): expect a heal or red on the next run.`);let
|
|
1218
|
-
${s.steps.length} step(s) across ${s.scannedFiles} file(s) \xB7 ${s.scannedCaches} cache(s) \xB7 \x1B[32m\u25CF\x1B[0m recorded (replays free) \xB7 \x1B[33m\u25CF\x1B[0m divergent \xB7 \u25CB unrecorded`)});
|
|
1219
|
-
`).map(d=>d.trim().replace(/^(Given|When|Then|And|But|\*)\s+/,"")).filter(d=>i.steps.some(p=>p.text===d)).length;console.log(`wrote ${c}`),console.log(`${l} step line(s) reuse the existing vocabulary (seedable)${a.usage.costUsd?` \xB7 $${a.usage.costUsd.toFixed(4)}`:""}`),console.log("review the draft, then record it: saffron run "+L.relative(process.cwd(),c))});
|
|
1220
|
-
`)),process.exit(1)});
|
|
1221
|
-
`))});
|
|
1212
|
+
`,l.push(d));l.length>0&&(W.writeFileSync(i,c),n.scaffolded.push(`.gitignore (+ ${l.join(", ")})`))}return n}function ry(e,t){let n=ee.join(t,"templates","saucedemo");if(!W.existsSync(ee.join(n,"features")))return{installed:!1,files:[],reason:`bundled examples not found at ${n}`};let r=ee.join(e,"features");if(W.existsSync(r)&&W.readdirSync(r).length>0)return{installed:!1,files:[],reason:"features/ is not empty; examples are only installed into an empty features directory"};let s=[];W.mkdirSync(r,{recursive:!0});for(let c of W.readdirSync(ee.join(n,"features")))W.copyFileSync(ee.join(n,"features",c),ee.join(r,c)),s.push(`features/${c}`);let o=ee.join(n,"data");if(W.existsSync(o)){W.mkdirSync(ee.join(e,"data"),{recursive:!0});for(let c of W.readdirSync(o)){let l=ee.join(e,"data",c);W.existsSync(l)||(W.copyFileSync(ee.join(o,c),l),s.push(`data/${c}`))}}let i=ee.join(e,"saffron.config.json");W.existsSync(i)||(W.copyFileSync(ee.join(n,"saffron.config.json"),i),s.push("saffron.config.json (baseURL https://www.saucedemo.com, retries 1)"));let a=ee.join(e,".env.example");return W.existsSync(a)||(W.copyFileSync(ee.join(n,".env.example"),a),s.push(".env.example")),{installed:!0,files:s}}import sy from"node:path";function gf(e){return["saffron lsp is a language server: it speaks LSP over stdio and is meant","to be launched by your editor, not run by hand (nothing happens here).","","JetBrains (IntelliJ, WebStorm, PyCharm, Rider, incl. Community):"," Easiest: install the Saffron plugin from the JetBrains Marketplace"," (https://plugins.jetbrains.com/plugin/34240-saffron): highlighting,"," this language server, run configurations and the Saffron tool window,"," in one click. Manual setup instead:"," 1. Completion, diagnostics, hover, go-to-definition: install the free"," LSP4IJ plugin, then Settings \u2192 Languages & Frameworks \u2192 Language"," Servers \u2192 +: command `npx saffron lsp`, working dir = project root,"," file patterns *.saffron and *.feature."," 2. Syntax highlighting comes from a TextMate bundle, not the LSP:"," Settings \u2192 Editor \u2192 TextMate Bundles \u2192 + and pick this folder:",` ${e?sy.join(e,"textmate","saffron"):"node_modules/saffron-ai/textmate/saffron"}`,"","Neovim / other LSP editors: cmd = { 'npx', 'saffron', 'lsp' },","filetypes = { 'saffron', 'feature' }.","","VS Code: install the extension instead:"," code --install-extension ChathurangaJayasinghe.saffron-vscode"].join(`
|
|
1213
|
+
`)}import{spawn as oy}from"node:child_process";function iy(e,t=process.platform){return t==="win32"?{command:'start "" "%SAFFRON_BROWSER_TARGET%"',args:[],options:{detached:!0,stdio:"ignore",shell:!0,windowsHide:!0,env:{...process.env,SAFFRON_BROWSER_TARGET:e}}}:{command:t==="darwin"?"open":"xdg-open",args:[e],options:{detached:!0,stdio:"ignore"}}}function hr(e){let{command:t,args:n,options:r}=iy(e),s=t.split(" ")[0],o=oy(t,n,r);o.on("error",()=>console.error(`Could not open a browser (${s} is not available here). Open the address above yourself.`)),o.unref()}function Li(e,t){let n=t.length>0?t:["features"],r=[];for(let s of n){let o=L.isAbsolute(s)?s:L.join(e,s);if(fe.existsSync(o))if(fe.statSync(o).isDirectory())for(let i of fe.readdirSync(o,{recursive:!0})){let a=String(i);pt(a)&&r.push(L.join(o,a))}else pt(o)&&r.push(o)}return r.sort()}function ly(e){let t=gi(e);t.length!==0&&console.error([`note: the ${Zt[e]} agent is not set up here. Cached scenarios replay fine`,"without AI, but recording and healing need:",...t.map(n=>` \xB7 ${n}`),"Replay-only runs: add --no-agent to silence this note.",""].join(`
|
|
1214
|
+
`))}function hf(e,t){let n=e.provider??"claude";return t===n?{model:e.model,healModel:e.healModel}:((e.model||e.healModel)&&console.error(`note: model and healModel in saffron.config.json name ${Zt[n]??n} models; this ${Zt[t]} run uses its default models (--model and --heal-model pick others).`),{})}function Bi(e,t){let n=e??t??"claude";return wd(n)||(console.error(`invalid provider "${n}": use ${pi.map(r=>`"${r}"`).join(", ")}`),process.exit(2)),n}async function dy(e){let t=ay.createInterface({input:process.stdin,output:process.stdout});try{let n=await new Promise(r=>t.question(e,r));return/^y(es)?$/i.test(n.trim())}finally{t.close()}}function As(e){console.error(`saffron: ${e.message}`),process.exit(2)}function Di(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e4?`${(e/1e3).toFixed(1)}k`:e.toLocaleString()}var fy={green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m"},py="\x1B[0m",V=new cy().name("saffron").description("AI-fallback test runner for end-to-end tests written in plain language: zero-token cached replay, runtime AI healing.").version(We()).option("-p, --project-root <dir>","project root",process.cwd());V.command("run").description("Run feature files (cached replay; AI records/heals on demand)").argument("[paths...]",'feature files or directories (default: features/); file:line runs the scenario at that line, Cucumber-style (login.saffron:12, or :12:30 for two); file:name the scenario of that name ("login.saffron:Successful login")').option("--base-url <url>","base URL of the app under test").option("--env <name>","data environment: data/<file>.<name>.json is laid over data/<file>.json (also SAFFRON_ENV, or env in the config)").option("--headed","run the browser headed").option("--filter <tags>",'only run scenarios whose @tags match: a list ("@smoke,@WA-TC1" runs either) or an expression ("@e2e and not @wip", parentheses allowed); repeat the flag for "or"',dl).option("--no-agent","disable AI fallback (cache misses/failures go red)").option("--rerecord","discard the committed caches of the selected scenarios and let the agent record them fresh, over a pending proposal this machine did not file too (the honest fix for a wrong recording)").option("--provider <name>",'whose agent records and heals: "claude" (default), "codex", "antigravity" or "cursor", on its login on this machine').option("--model <model>","model for the agent").option("--storage-state <file>","Playwright storageState JSON for authenticated sessions").option("--strict","treat passed-with-adaptation (yellow) as failure until its proposal is reviewed").option("--no-verify","skip the zero-AI proof replay of agent recordings before filing proposals").option("--no-reuse","disable Level-1 step reuse (seeding new recordings from existing step recordings)").option("--browser <name>",'browser: "chromium" (default), "chrome", "msedge", "firefox" or "webkit". Recording and healing need one of the first three').option("--heal-model <model>","cheaper model for heal sessions").option("--workers <n>","parallel replay workers (agent recording/healing stays sequential)").option("--shard <index/total>","run one part of the suite, e.g. 2/4 on the second of four CI machines; combine the parts with `saffron report --merge`").option("--shard-by <mode>",'how --shard splits the suite: "scenario" (default, spreads every file) or "file" (each feature file stays on one machine)').option("--no-hooks","skip the setup and teardown commands from the config").option("--trace <mode>",'execution trace per scenario: "off" (default), "on" or "retain-on-failure"; open one with saffron trace').option("--assertion-policy <policy>",'assertion adaptability: "strict" (default) or "adaptable-mid" (mid-scenario assertions may be adapted; the final assertion block never is)').action(async(e,t)=>{let n=L.resolve(V.opts().projectRoot),r=le(n);t.env&&Ye(n,r.dataDir,t.env);let s=t.baseUrl??r.baseURL,o=fl(e),i=e.length===0?Li(n,r.features?[r.features]:[]):o.plain.length>0?Li(n,o.plain):[],a=[...o.picks.keys()].map(C=>L.resolve(n,C)),c=[...o.plain,...o.picks.keys()].find(C=>!fe.existsSync(L.resolve(n,C)));c!==void 0&&(console.error(`${c} does not exist (in ${n}).`),process.exit(2));let l=[...new Set([...i,...a])].sort();l.length===0&&(console.error("No .feature/.saffron files found."),process.exit(2));let d=l.find(C=>{let H=L.relative(n,C);return H.split(/[\\/]/)[0]===".."||L.isAbsolute(H)});d&&(console.error(`${d} is outside the project (${n}). Run saffron from the project that holds it, or point --project-root at it.`),process.exit(2));let p=Bi(t.provider,r.provider),u=hf(r,p);t.agent!==!1&&ly(p);let f;try{let C=Ie(n,r,l);f=l.flatMap(H=>Ce(H,n,C))}catch(C){throw C instanceof be&&As(C),C}let h=f;if(o.picks.size>0)try{f=gl(f,n,o.picks,new Set(i))}catch(C){if(!(C instanceof Yt))throw C;console.error(C.message),process.exit(2)}let w;try{w=cl(t.filter)}catch(C){if(!(C instanceof Xn))throw C;console.error(`${C.message}. Write tags joined with and, or, not and parentheses: "@smoke and not @wip".`),process.exit(2)}if(w&&(f=ll(f,w),f.length===0&&(console.error(`No scenarios match --filter "${w.text}" in ${l.length} feature file(s).`),process.exit(2))),t.agent!==!1){let C=J=>{try{let ye=Re(re(n,J.featurePath,J.name));return!!ye&&zn(J,ye)}catch{return!1}},H=f.filter(J=>t.rerecord||!C(J)),q=pl(H,h).filter(J=>!f.includes(J));q.length>0&&(console.log(`${q.length} more Examples row(s) share a recording this run ${t.rerecord?"replaces":"records"}, and run to replay it`),f=[...f,...q])}let $;if(t.shardBy!==void 0&&t.shard===void 0&&(console.error("saffron: --shard-by needs --shard, e.g. --shard 2/4 --shard-by file"),process.exit(2)),t.shard!==void 0){try{let C=Pc(String(t.shardBy??r.shardBy??"scenario")),H=Oc(f,{...Cc(String(t.shard)),by:C});f=H.scenarios,$={...H.info,ciRun:Yr(),attempt:Zr()}}catch(C){console.error(C instanceof Error?C.message:String(C)),process.exit(2)}if(console.log(`shard ${$.index}/${$.total}${$.by==="file"?" (by file)":""}: ${f.length} of ${$.suiteSize} scenario(s)`),f.length===0){let C=new Date,H=Mo([],C,s),q=_o([],C,Xe(n).divergent.length,s);console.log(`report: ${Ho(n,{...H,shard:$,history:q})}`),process.exit(0)}}t.rerecord&&t.agent===!1&&(console.error("saffron: --rerecord needs the agent; drop --no-agent"),process.exit(2));{let C=f;try{let q=[...new Set([...Li(n,r.features?[r.features]:[]),...l])],J=Ie(n,r,q);C=q.flatMap(ye=>{try{return Ce(ye,n,J)}catch{return[]}})}catch{}let H=aa(n,C);if(H.length>0){console.error("cache path collision:");for(let q of H)console.error(` ${q}`);process.exit(2)}}{let C=new Map;for(let q of f)for(let J of _e(q))process.env[J]===void 0&&!C.has(J)&&C.set(J,q.displayName);let H=new Map;for(let q of f)for(let J of ct(je(q)))if(!H.has(J))try{wr(J)}catch(ye){H.set(J,`${ye instanceof Error?ye.message:String(ye)} (used by "${q.displayName}")`)}if(H.size>0){for(let q of H.values())console.error(q);process.exit(2)}if(C.size>0){for(let[q,J]of C)console.error(`missing environment variable ${q} (referenced as {env:${q}} by "${J}")`);console.error("set the variable(s), or add them to a git-ignored .env in the project root"),process.exit(2)}}let k=[],y=[];if(t.hooks!==!1)try{k=vi(r.setup,"setup"),y=vi(r.teardown,"teardown")}catch(C){console.error(C instanceof Error?C.message:String(C)),process.exit(2)}let v=new os({projectRoot:n,baseURL:s,headed:t.headed,actionTimeoutMs:r.actionTimeoutMs,pollIntervalMs:r.pollIntervalMs,screenshot:r.screenshot,trace:(()=>{let C=t.trace??r.trace??"off";return ao.includes(C)||(console.error(`invalid --trace "${C}": use ${ao.map(H=>`"${H}"`).join(", ")}`),process.exit(2)),C})(),retries:r.retries,storageState:t.storageState??r.storageState,browser:(()=>{let C=t.browser??r.browser??"chromium";return Ul(C)||(console.error(`invalid --browser "${C}": use ${si.map(H=>`"${H}"`).join(", ")}`),process.exit(2)),C})(),healModel:t.healModel??u.healModel,rerecord:t.rerecord===!0,verifyProposals:t.verify===!1?!1:r.verifyProposals,reuseSteps:t.reuse===!1?!1:r.reuseSteps,assertionPolicy:(()=>{let C=t.assertionPolicy??r.assertionPolicy??"strict";return C!=="strict"&&C!=="adaptable-mid"&&(console.error(`invalid --assertion-policy "${C}": use "strict" or "adaptable-mid"`),process.exit(2)),C})(),agent:t.agent?bd(p,{model:t.model??u.model,maxTurns:r.maxTurns,snapshotMode:r.snapshotMode}):void 0}),S=new Date,x=Math.max(1,Number.parseInt(String(t.workers??r.workers??1),10)||1),b=new Array(f.length),R=C=>{let H=C.scenario,q=fy[C.status],J=C.usage.inputTokens+C.usage.outputTokens,ye=C.usage.cacheReadTokens+C.usage.cacheCreationTokens,$f=ye>0?`, ${Di(ye)} cache traffic`:"";console.log(`${q}${C.status.toUpperCase().padEnd(7)}${py}${H.displayName} (${C.source}, ${C.durationMs}ms, ${C.usage.aiCalls} AI calls, ${J} tokens${$f})`);for(let Is of C.adaptations)console.log(` \u26A0 ${Is}`);C.status==="yellow"&&C.usage.aiCalls===0&&C.narrative&&console.log(` ${C.narrative}`),C.seededSteps&&console.log(` \u26A1 ${C.seededSteps}/${C.stepResults.length} steps seeded from existing recordings (zero AI)`);let _s=C.stepResults.reduce((Is,kf)=>Is+(kf.retries??0),0);_s&&console.log(` \u21BB ${_s} action ${_s===1?"retry":"retries"} absorbed before settling (retries: ${r.retries??1} per action)`),C.verified===!0?console.log(" \u2713 proposal verified by zero-AI proof replay"):C.verified===!1&&console.log(` \u2717 proposal UNVERIFIED, proof replay failed: ${C.proofError?.split(`
|
|
1215
|
+
`)[0]}`),C.error&&console.log(` ${C.error}`)},m=new AbortController,g={cwd:n,timeoutMs:r.hookTimeoutMs??Vs.hookTimeoutMs,env:{SAFFRON_BASE_URL:s,SAFFRON_ENV:Ae().env,SAFFRON_SHARD:$?`${$.index}/${$.total}`:void 0}},T=[],E,A=()=>E??=Si("teardown",y,g).then(C=>{T.push(...C)}),P=Promise.resolve([]);k.length+y.length>0&&process.on("SIGINT",()=>{if(m.signal.aborted){console.error("still cleaning up: teardown finishes, then Saffron exits");return}console.error(`
|
|
1216
|
+
interrupted: stopping, then running teardown`),m.abort(),P.then(()=>v.stop()).catch(()=>{}).then(A).finally(()=>process.exit(130))}),k.length>0&&(P=Si("setup",k,{...g,signal:m.signal}),T.push(...await P),m.signal.aborted&&await new Promise(()=>{}),T.some(Rs)&&(console.error("No scenario was run: the application is not in the state the suite expects."),await A(),process.exit(2)));try{await v.start()}catch(C){throw await A(),C instanceof rr&&(console.error(C.message),process.exit(2)),C}try{if(t.rerecord){let C=0;for(let H of f){let q=re(n,H.featurePath,H.name);fe.existsSync(q)&&(fe.rmSync(q),C++)}console.log(`rerecord: removed ${C} cache file(s) for ${f.length} scenario(s); the agent records them fresh (seeded from the other recordings). Restore with git if needed.`)}if(x>1&&f.length>1){let C=f.map((q,J)=>({s:q,i:J})),H=[];await Promise.all(Array.from({length:Math.min(x,C.length)},async()=>{for(;;){let q=C.shift();if(!q)return;let J=await v.runScenario(q.s,{agentDisabled:!0});J.status==="red"?H.push(q):(b[q.i]=J,R(J))}}));for(let q of H.sort((J,ye)=>J.i-ye.i)){let J=await v.runScenario(q.s);b[q.i]=J,R(J)}}else for(let C=0;C<f.length;C++){let H=await v.runScenario(f[C]);b[C]=H,R(H)}}finally{await v.stop(),await A()}let O=Mo(b,S,s);T.length>0&&(O.hooks=T);let I=Xe(n).divergent.length,N=o.picks.size>0,M={..._o(b,S,I,s),...N?{partial:!0}:{}};$||(N||(O.trends=Co(Wn(n),M)),Io(n,M)),O.totals.aiCalls>0&&(O.totals.plan=await v.agent?.planUsage?.());let B,_=!1;if($){let C=Ho(n,{...O,shard:$,history:M}),H=C.replace(/\.json$/,".html");fe.writeFileSync(H,At(O,n)),B=`${H}
|
|
1217
|
+
${C}`}else{let C=N?Uo(Bo(n),O):O;_=C!==O;let{html:H,json:q}=Kn(n,C);B=`${H}
|
|
1218
|
+
${q}`}let j=O.totals,U=j.cacheReadTokens+j.cacheCreationTokens;console.log(`
|
|
1219
|
+
${j.green} passed, ${j.yellow} pending review, ${j.red} failed \xB7 ${j.aiCalls} AI calls \xB7 ${(j.inputTokens+j.outputTokens).toLocaleString()} tokens in+out${U>0?` \xB7 ${Di(j.cacheReadTokens)} cache read \xB7 ${Di(j.cacheCreationTokens)} cache written`:""}${ko(j)}${j.models?.length?` \xB7 ${j.models.join(", ")}`:""}`);let K=O.trends;K?.prev&&console.log(Ro(K.prev));for(let C of K?.chronic??[])console.log(`\u26A0 chronic: ${C.feature} \u203A ${C.scenario}: ${C.heals} heal(s), ${C.reds} red(s) in last ${C.runs} run(s); re-record or fix the feature text instead of paying for more heals`);console.log(`report: ${B}`),N&&!$&&console.log(wf(_)),$&&console.log(`shard report, not a whole run: history and trends wait for \`saffron report --merge\` over all ${$.total} shard-*-of-${$.total}.json files`);let de=tt(L.resolve(V.opts().projectRoot),mr);de.length>0&&console.log(`${de.length} cache proposal(s) pending. Review with: saffron accept | saffron reject`);let Z=t.strict??r.strict??!1;Z&&j.yellow>0&&console.log(`strict mode: ${j.yellow} scenario(s) pending review treated as failure. Review proposals to go green.`);let Ge=j.red>0||Z&&j.yellow>0,bt=T.filter(C=>C.phase==="teardown"&&Rs(C));bt.length>0&&console.log(`teardown failed: ${bt.map(C=>xi(C,g.timeoutMs)).join("; ")}. The environment may hold data from this run.`),process.exit(Ge?1:bt.length>0?2:0)});V.command("accept").description("Promote pending cache proposals to committed caches").argument("[files...]","proposal file(s) (default with --all: every pending proposal, less those --all leaves out)").option("--all","accept every pending proposal that is verified and was not imported from a CI run (see --include-unverified, --include-imported)").option("--with-feature-edit","also apply the proposal's suggested .feature step rewrites").option("--propagate","apply the same locator fixes to every other cache using the same locator").option("--include-unverified","with --all: also accept proposals that are unverified or not checked (their proof replay failed, or did not run)").option("--include-imported","with --all: also accept proposals imported from a CI run (saffron import), which --all leaves for review by file").action((e,t)=>{let n=L.resolve(V.opts().projectRoot),r=le(n),s=t.all&&!t.includeImported?ht(n):{},o=0,i=e.length>0?e.map(Ys).map(a=>({...a,file:L.resolve(a.file)})):t.all?tt(n,mr).map(a=>({file:a.file,revision:void 0})):[];if(i.length===0){xf(n);return}try{for(let{file:a,revision:c}of i){let l=v=>{console.log(`not accepted: ${L.basename(a)} ${ue(v)}`),process.exitCode=1},d=Sf(n,a,c!==void 0,()=>{if(c&&Be(a)!==c)return l(vf);let v=s[L.relative(n,a).split(L.sep).join("/")];if(v&&Be(a)===v.revision){o++;return}let S;try{S=yn(a)}catch(R){if(!(R instanceof oe))throw R;return l(`cannot be read: ${R.problem}`)}if(S.meta.bound){let R=Le(n,S,Ie(n,r,[]));if(R)return l(`is stale: ${R}. Run the scenario again for a proposal made against what is there now, or reject this one.`)}else console.log(`\u26A0 ${L.basename(a)} is ${qr}; accepting as it is.`);if(S.meta.verified!==!0&&t.all&&!t.includeUnverified){let R=S.meta.verified===!1?S.meta.proofError?.split(`
|
|
1220
|
+
`)[0]:"not checked: no proof replay ran";console.log(`skipped UNVERIFIED ${L.basename(a)} (${ue(R)}). Re-record it (saffron run --rerecord), or accept it explicitly by file, or pass --include-unverified.`);return}S.meta.verified===!1&&console.log(`\u26A0 accepting UNVERIFIED proposal (proof replay failed: ${ue(S.meta.proofError?.split(`
|
|
1221
|
+
`)[0])}): expect a heal or red on the next run.`);let x=S.cache.steps.map(R=>R.gherkin);if(t.withFeatureEdit&&(S.meta.featureEdits??[]).length>0){let R=Ld(n,S.cache.feature,S.cache.scenario,x,Ie(n,r,[]));if(R)return l(`carries feature edits, and ${R}. Run the scenario again for a fresh proposal, or accept this one without --with-feature-edit.`)}let b=Re(re(n,S.cache.feature,S.cache.scenario));return{proposal:S,recordedSteps:x,oldCache:b,cacheFile:jr(n,a)}},l);if(!d)continue;let{proposal:p,recordedSteps:u,oldCache:f,cacheFile:h}=d;console.log(`accepted \u2192 ${h}`);let w=f?Nd(f,p.cache):{changes:[],ambiguous:[]},$=w.changes;for(let v of w.ambiguous)console.log(` locator fix for ${ue($s(v))} not propagated: this heal sent it to more than one place, so other caches are left alone.`);if($.length>0){let v=Fd(n,$,h,!t.propagate);for(let S of $)console.log(` locator fix: ${ue($s(S.from))} \u2192 ${ue($s(S.to))}`);if(v.length===0)console.log(" no other caches use this locator.");else if(t.propagate)for(let S of v)console.log(` propagated \u2192 ${S.feature} \u203A ${S.scenario} (${S.steps.map(x=>`"${x.gherkin}"`).join(", ")})`);else{console.log(` ${v.length} other cache(s) use the same locator: re-run with --propagate to fix them too:`);for(let S of v)console.log(` \xB7 ${S.feature} \u203A ${S.scenario}`)}}let k=p.meta.featureEdits??[];if(!t.withFeatureEdit||k.length===0)continue;let y=Dd(n,p.cache.feature,p.cache.scenario,k,Ie(n,r,[]),u);for(let v of y.applied){let S=v.fromStepSet?`${v.file}:${v.line} (StepSet "${v.fromStepSet}", fixes every invoking scenario)`:`${v.file}:${v.line}`;console.log(` feature edit ${S}:`),console.log(` - ${v.from}`),console.log(` + ${ue(v.to)}`)}for(let v of y.skipped)console.log(` skipped edit [${v.index}]: ${ue(v.reason)}`);if(y.appliedIndices.length>0){let v=new Set(y.appliedIndices),S=Re(h);for(let x of k)v.has(x.index)&&S.steps[x.index]&&(S.steps[x.index].gherkin=x.text);pn(h,S)}}}catch(a){throw a instanceof be&&As(a),a}o>0&&console.log(`skipped ${o} proposal${o===1?"":"s"} imported from a CI run: review ${o===1?"it":"them"} (saffron diff) and accept by file, or pass --include-imported.`)});V.command("steps").description("List/search the project's step vocabulary (files + caches): what exists, what's recorded, what to reuse").argument("[search]","case-insensitive substring filter").option("--json","machine-readable vocabulary").option("--snippets","write .vscode/saffron.code-snippets for native VS Code completion").action((e,t)=>{let n=L.resolve(V.opts().projectRoot),r=le(n),s;try{s=et(n,r.features??"features")}catch(i){throw i instanceof be&&As(i),i}if(e&&(s=_r(s,e)),t.json){console.log(JSON.stringify(s,null,2));return}if(t.snippets){let i=L.join(n,".vscode","saffron.code-snippets");fe.mkdirSync(L.dirname(i),{recursive:!0}),fe.writeFileSync(i,ga(s)),console.log(`wrote ${s.steps.length} step + ${s.stepSets.length} StepSet snippet(s) \u2192 ${i}`),console.log("re-run after recording sessions to keep completions current");return}let o={recorded:"\x1B[32m\u25CF\x1B[0m",divergent:"\x1B[33m\u25CF\x1B[0m",unrecorded:"\u25CB"};if(s.stepSets.length>0){console.log("step sets:");for(let i of s.stepSets)console.log(` ${i.name} (${i.steps.length} steps, ${i.usage} scenario(s)), ${i.file}:${i.line}`);console.log("")}for(let i of s.steps){let a=i.fromStepSet?` [${i.fromStepSet}]`:"";console.log(`${o[i.status]} ${i.keyword} ${i.text} \xD7${i.usage}${a}`)}console.log(`
|
|
1222
|
+
${s.steps.length} step(s) across ${s.scannedFiles} file(s) \xB7 ${s.scannedCaches} cache(s) \xB7 \x1B[32m\u25CF\x1B[0m recorded (replays free) \xB7 \x1B[33m\u25CF\x1B[0m divergent \xB7 \u25CB unrecorded`)});V.command("author").description("Draft a feature file from plain-paragraph requirements, reusing the project's step vocabulary (AI)").argument("<prose-file>","text/markdown file with the requirements").option("-o, --out <file>","output path (default: features/<name>.saffron)").option("--provider <name>",'whose agent writes the draft: "claude" (default), "codex", "antigravity" or "cursor"').option("--model <model>","model for authoring").action(async(e,t)=>{let n=L.resolve(V.opts().projectRoot),r=le(n),s=Bi(t.provider,r.provider),o=fe.readFileSync(L.resolve(e),"utf8"),i;try{i=et(n,r.features??"features")}catch(d){throw d instanceof be&&As(d),d}console.log(`authoring with ${i.steps.length} known step(s) and ${i.stepSets.length} step set(s) as vocabulary\u2026`);let a=await il(o,i,t.model??hf(r,s).model,s==="claude"?void 0:ui[s]),c=t.out?L.resolve(t.out):L.join(n,r.features??"features",`${L.basename(e).replace(/\.[^.]+$/,"")}.saffron`);fe.existsSync(c)&&(console.error(`refusing to overwrite ${c}: pass --out for a new path`),process.exit(1)),fe.mkdirSync(L.dirname(c),{recursive:!0}),fe.writeFileSync(c,a.content);let l=a.content.split(`
|
|
1223
|
+
`).map(d=>d.trim().replace(/^(Given|When|Then|And|But|\*)\s+/,"")).filter(d=>i.steps.some(p=>p.text===d)).length;console.log(`wrote ${c}`),console.log(`${l} step line(s) reuse the existing vocabulary (seedable)${a.usage.costUsd?` \xB7 $${a.usage.costUsd.toFixed(4)}`:""}`),console.log("review the draft, then record it: saffron run "+L.relative(process.cwd(),c))});V.command("login").description("Check or set up an AI provider's login on this machine (Cursor: a one-time sign-in for Saffron; Antigravity: allows Saffron's tools in agy)").argument("[provider]",'"claude", "codex", "antigravity" or "cursor" (default: the configured provider)').action(async e=>{let t=L.resolve(V.opts().projectRoot),n=Bi(e,le(t).provider),r=n==="cursor"?hd:n==="antigravity"?cd:void 0;if(r)try{await r()}catch(o){console.error(o instanceof Error?o.message:String(o)),process.exit(1)}let s=gi(n);if(s.length===0){console.log(`${Zt[n]}: ready to record and heal.`);return}console.log([`${Zt[n]} still needs:`,...s.map(o=>` \xB7 ${o}`)].join(`
|
|
1224
|
+
`)),process.exit(1)});V.command("mcp").description("Serve the step vocabulary to AI assistants over stdio MCP (search_steps, list_step_sets)").action(async()=>{let e=L.resolve(V.opts().projectRoot),t=le(e);await nl(e,t.features??"features")});V.command("lsp").description("Run the Saffron language server over stdio (completion, go-to-definition, hover, diagnostics). For JetBrains (LSP4IJ / Ultimate LSP API), Neovim, and any LSP-capable editor").action(()=>{process.stdin.isTTY&&(console.error(gf(Cr())),process.exit(2));let e=L.resolve(V.opts().projectRoot),t=le(e),n=process.argv.includes("-p")||process.argv.some(r=>r.startsWith("--project-root"));$l(e,t.features??"features",{rootFromClient:!n})});V.command("reject").description("Discard pending cache proposals (AI will retry next run)").argument("[files...]","proposal file(s)").option("--all","reject all pending proposals").action((e,t)=>{let n=L.resolve(V.opts().projectRoot),r=e.length>0?e.map(Ys).map(s=>({...s,file:L.resolve(s.file)})):t.all?tt(n,mr).map(s=>({file:s.file,revision:void 0})):[];if(r.length===0){xf(n);return}for(let{file:s,revision:o}of r){let i=Sf(n,s,o!==void 0,()=>{if(o&&Be(s)!==o)return vf;Nr(s)},a=>a);if(i){console.log(`not rejected: ${L.basename(s)} ${i}`),process.exitCode=1;continue}console.log(`rejected ${s}`)}});V.command("init").description("Make the project agent-ready: install the bundled Saffron skill into agent directories, add instructions to AGENTS.md, scaffold config").option("--agents <list>",`comma-separated targets: ${Object.keys(gr).join(", ")} (default: claude,agents)`).option("--no-instructions","do not touch AGENTS.md / CLAUDE.md").option("--no-scaffold","do not create saffron.config.json, features/, .gitignore entry").option("--no-mcp","do not register `saffron mcp` in project MCP configs (.mcp.json, .cursor/mcp.json, .vscode/mcp.json)").option("--examples","install the Saucedemo example suite (features, config, .env.example) for a guided first run").option("--no-examples","never install the example suite (skips the prompt)").action(async e=>{let t=L.resolve(V.opts().projectRoot),n=Cr();n||(console.error("saffron: cannot locate the installed package root"),process.exit(2));let r=e.agents?String(e.agents).split(",").map(i=>i.trim()).filter(Boolean):void 0;for(let i of r??[])i in gr||(console.error(`saffron: unknown agent target "${i}" (expected one of ${Object.keys(gr).join(", ")})`),process.exit(2));let s=e.examples===!0;e.examples===void 0&&process.stdin.isTTY&&process.stdout.isTTY&&(s=await dy("Install the Saucedemo example tests (login, cart, checkout) into features/ for a guided first run? [y/N] "));let o=uf({projectRoot:t,packageRoot:n,targets:r,instructions:e.instructions,scaffold:e.scaffold,mcp:e.mcp,examples:s});for(let i of o.skillDirs)console.log(`skill \u2192 ${i}/`);for(let i of o.mcpFiles)console.log(`${i.outcome.padEnd(9)} \u2192 ${i.file} (saffron mcp server)`);for(let i of o.mcpHints)console.log(`mcp hint \u2192 ${i}`);for(let i of o.instructionFiles)console.log(`${i.outcome.padEnd(9)} \u2192 ${i.file} (managed Saffron block)`);for(let i of o.scaffolded)console.log(`created \u2192 ${i}`);o.examples&&!o.examples.installed&&console.log(`examples \u2192 not installed: ${o.examples.reason}`),console.log("\nAgents now load the saffron skill when writing tests. Re-run after `npm update saffron-ai` to refresh it."),o.examples?.installed&&console.log(["","Your guided first run (recording needs Claude credentials; replays never do):"," cp .env.example .env # public demo credentials, resolved at replay"," npx playwright install chromium"," npx saffron run --filter @smoke # the agent records two scenarios (about $3 of AI usage), files proposals"," npx saffron accept --all # review, then promote them to caches"," npx saffron run --filter @smoke # replays at zero tokens","Then try the rest: npx saffron run (login errors outline, checkout with a data table)"].join(`
|
|
1225
|
+
`))});V.command("export").description("Pack the pending proposals, the last run's report and its screenshots and traces into one bundle, for review on another checkout (CI uploads it as an artifact)").option("-o, --out <file>","where to write the bundle (default: .saffron/reports/saffron-bundle.zip)").option("--branch <name>","also commit the pending proposals (not the caches) onto the commit the run tested as a new branch, push it to origin, and open a draft pull request (GitHub through gh, Azure DevOps through az)").option("--base <branch>","with --branch: the branch the pull request is for (default: the branch the run tested)").action(e=>{let t=L.resolve(V.opts().projectRoot);e.base!==void 0&&e.branch===void 0&&(console.error("saffron export: --base needs --branch"),process.exit(2));try{ur("--branch",e.branch),ur("--base",e.base)}catch(a){console.error(`saffron export: ${a.message}`),process.exit(2)}let n;try{n=Hc(t,{out:e.out?L.resolve(e.out):void 0})}catch(a){console.error(`saffron export: ${a instanceof Error?a.message:String(a)}`),process.exit(2)}for(let a of n.unreadable)console.error(`\u26A0 proposal ${a.file} cannot be read: ${ue(a.problem)}. Left out of the bundle.`);let r=n.manifest;if(console.log(`bundle: ${n.file}`),console.log(` ${r.proposals.length} proposal(s) \xB7 ${r.evidence.length} screenshot and trace file(s) \xB7 ${r.report?"the run's report":"no run report"}${r.shard?` \xB7 shard ${r.shard.index}/${r.shard.total}`:""}`),console.log(` from ${Zn(r)}`),n.missing.length>0&&console.log(` ${n.missing.length} file(s) the report names are gone, or were replaced by a later run: left out`),n.dropped.length>0&&console.log(` ${n.dropped.length} trace(s) of green scenarios left out: with them the bundle would be over the 4 GB one bundle holds`),console.log("Review it in a checkout of this repository with: saffron import <bundle>"),e.branch===void 0)return;if(n.proposals.length===0){console.log("No pending proposals: no branch to push.");return}let s;try{let a=le(t);s=cf(t,n,String(e.branch),{base:e.base,config:a})}catch(a){console.error(`saffron export: the bundle is written, but no branch was pushed: ${a instanceof Error?a.message:String(a)}`),process.exit(2)}for(let a of s.leftOut)console.error(`\u26A0 left out of the branch: ${L.relative(t,a.file)} ${a.reason}`);let o=n.proposals.length-s.leftOut.length,i=o===1?"the proposal":`${o} proposals`;console.log(`branch: ${s.branch} pushed to origin (${s.commit.slice(0,7)}: ${i} on top of ${s.parent.slice(0,7)})`),s.pullRequest?console.log(`draft pull request: ${s.pullRequest}`):(console.log(`no pull request: ${s.noPullRequest}. Open one from ${s.branch} to ${s.base}; its description is in ${s.bodyFile}`),s.failed&&(process.exitCode=1))});V.command("runs").description("List the CI runs of the checkout's branch (GitHub Actions through gh, Azure Pipelines through az), with how many of each run's proposals are pending here; import one with saffron import --run <id>").option("--branch <name>","another branch (default: the checkout's; every branch on a detached HEAD)").option("--limit <n>","how many runs (default 20)").option("--provider <name>",`"github" or "azure" (default: ci.provider in the config, else the repository's host)`).option("--json","machine-readable output").action(e=>{let t=L.resolve(V.opts().projectRoot),n=e.limit===void 0?void 0:Number(e.limit);n!==void 0&&!(Number.isInteger(n)&&n>0)&&(console.error(`invalid --limit "${e.limit}": use a whole number above 0`),process.exit(2));let r;try{r=Gd(t,le(t),{provider:e.provider,branch:e.branch,limit:n})}catch(i){let a=i instanceof Error?i.message:String(i);e.json?console.log(JSON.stringify({error:a},null,2)):console.error(`saffron runs: ${a}`),process.exit(2)}if(r.problem&&(process.exitCode=2),e.json){console.log(JSON.stringify(r.problem?{...r,error:r.problem.message}:r,null,2));return}if(r.problem){console.error(`saffron runs: ${r.problem.message}`);return}let s=`${Ts[r.provider]} runs ${r.branch?`on ${r.branch}`:"on every branch"}`;if(r.runs.length===0){console.log(`No ${s}.`);return}let o=i=>i.status!=="completed"?"\u25CF":i.conclusion==="success"?"\u2713":i.conclusion==="failure"?"\u2717":"\u25CB";console.log(`${s}:`);for(let i of r.runs){let a=[`${i.name} #${i.number}`,i.status==="completed"?i.conclusion:i.status.replace("_"," "),Jd(i.createdAt),i.commit?.slice(0,7),i.pending?`${i.pending} proposal${i.pending===1?"":"s"} pending here`:void 0].filter(Boolean);console.log(` ${i.id.padStart(12)} ${o(i)} ${a.join(" \xB7 ")}`)}console.log("Import one with: saffron import --run <id>")});V.command("import").description("Bring a bundle from `saffron export` (a CI run) into this checkout: its proposals, each checked against the files here, and the run's report, screenshots and traces. Then review and accept as usual").argument("[bundles...]","bundle files, folders holding saffron-bundle*.zip (a CI artifact download), or http(s) URLs").option("--run <id>","instead: download the bundles of this CI run (an id from saffron runs) through gh or az, and import them").option("--provider <name>",`with --run: "github" or "azure" (default: ci.provider in the config, else the repository's host)`).option("--allow-fork","with --run: import a run a fork's pull request started (code from outside this repository made its bundle); read that pull request first").option("--overwrite","replace a different proposal already pending here for the same scenario").option("--allow-unknown-repository","import a bundle that does not say which repository it comes from (made outside a git checkout); its proposals are still checked by their bindings").option("--json","machine-readable output").action(async(e,t)=>{let n=L.resolve(V.opts().projectRoot);function r(d,p=!1){t.json?console.log(JSON.stringify({error:d},null,2)):console.error(`saffron import: ${d}${p?"":". Nothing was imported."}`),process.exit(2)}t.run===void 0==(e.length===0)&&r("give bundle files, folders or URLs, or --run <id>, and not both"),t.provider!==void 0&&t.run===void 0&&r("--provider goes with --run"),t.allowFork&&t.run===void 0&&r("--allow-fork goes with --run");let s,o,i;try{let d=le(n),p=Ie(n,d,[]);t.run!==void 0&&(i=Qd(n,d,String(t.run),{provider:t.provider,allowFork:t.allowFork===!0}));let u=i?[i.dir]:e.map(h=>/^https?:\/\//i.test(h)?h:L.resolve(h)),f=i;s=await Gc(n,u,p,{overwrite:t.overwrite===!0,allowUnknownRepository:t.allowUnknownRepository===!0,describe:f?h=>`${Ts[f.provider]} run ${t.run} (${L.basename(L.dirname(h))})`:void 0,run:f?`${f.provider}:${t.run}`:void 0})}catch(d){o=d}finally{i?.remove()}if((o instanceof D||o instanceof be)&&r(o.message),(o!==void 0||!s)&&r(o instanceof Error?o.message:String(o),!0),s.proposals.some(d=>d.outcome==="refused")&&(process.exitCode=1),t.json){console.log(JSON.stringify(i?{run:{provider:i.provider,id:String(t.run)},...s}:s,null,2));return}for(let d of s.bundles)console.log(`bundle: ${d.source}`),console.log(` from ${Zn(d.origin)}${d.shard?` \xB7 shard ${d.shard.index}/${d.shard.total}`:""} \xB7 saffron-ai ${d.runner}`);for(let d of s.warnings)console.log(`\u26A0 ${d}`);for(let d of s.proposals){let p=d.feature?`${d.feature} \u203A ${d.scenario}`:d.file;d.outcome==="imported"?console.log(`imported \u2192 ${d.file} (${p})`):d.outcome==="unchanged"?console.log(`unchanged: ${p}: ${d.reason??"already pending here"}`):console.log(`not imported: ${p} ${d.reason}`)}let{written:a,unchanged:c}=s.evidence;a>0&&console.log(`evidence: ${a} screenshot and trace file(s) written${c?`, ${c} already here`:""}`),s.report==="written"&&console.log("report: .saffron/reports/latest.html now shows the imported run (saffron report, saffron trace)");let l=s.proposals.filter(d=>d.outcome==="imported").length;l===0&&a===0&&s.report!=="written"&&!s.proposals.some(d=>d.outcome==="refused")?console.log("Nothing changed: this was already imported."):l>0&&console.log("Review with: saffron diff \xB7 accept with: saffron accept <file> | --all --include-imported \xB7 then commit the caches with your git tools")});V.command("diff").description("Show what a pending proposal changes in the committed recording: the action list a reviewer is approving, not just the narrative, and the feature file edits it would apply").argument("[files...]","proposal file(s); default: every pending proposal").option("--json","machine-readable output").action((e,t)=>{let n=L.resolve(V.opts().projectRoot),r=e.length>0?e.map(o=>L.resolve(o)):tt(n,mr).map(o=>o.file);if(r.length===0){console.log("No pending proposals.");return}let s=r.map(o=>{let i=yn(o),a=Re(re(n,i.cache.feature,i.cache.scenario));return{file:L.relative(n,o),verified:i.meta.verified,stale:i.meta.bound?bf(n,i):qr,...Et(a,i.cache,i.meta.featureEdits)}});if(t.json){console.log(JSON.stringify(s.length===1?s[0]:s,null,2));return}console.log(s.map(o=>`${Ur(o)}${o.stale?`
|
|
1222
1226
|
|
|
1223
|
-
STALE: ${
|
|
1227
|
+
STALE: ${ue(o.stale)}`:""}`).join(`
|
|
1224
1228
|
|
|
1225
|
-
`))});
|
|
1226
|
-
${
|
|
1227
|
-
Press Ctrl-C to stop.`),t.open!==!1&&
|
|
1228
|
-
`)),process.exit(2));let s=e.yes&&!e.check?
|
|
1229
|
-
`))}e.check&&r.orphans.length>0&&process.exit(1)});
|
|
1230
|
-
${
|
|
1231
|
-
`)[0]:String(n)}`}}var
|
|
1232
|
-
`);for(let{file:n,proposal:r}of t){console.log(` ${n}`);let s=r.meta.verified===!0?" \xB7 verified \u2713":r.meta.verified===!1?" \xB7 UNVERIFIED \u2717":"";console.log(` ${
|
|
1229
|
+
`))});V.command("trace").description("Open the execution replay of a scenario from the last run: its Given / When / Then, the page at every action, the network alongside, and what the agent changed").argument("[scenario]","scenario name, feature path, or feature:scenario; default: every traced scenario, opening on a red one, else a yellow one").option("--port <n>","listen on a fixed port (default: a free one)").option("--no-open","print the URL without opening a browser").option("--json","print the parsed trace as JSON instead of serving it").option("--run <startedAt|id>","only if the last run is this one (its startedAt): an editor's row names the run it lists. Or a CI run's id (from saffron runs): replay that run's traces without importing it, view only").option("--provider <name>",`with a CI run's id: "github" or "azure" (default: ci.provider in the config, else the repository's host)`).option("--allow-fork","with a CI run's id: view a run a fork's pull request started").option("--max-download <MB>","with a CI run's id: refuse to download more than this many megabytes (default: no limit)").action(async(e,t)=>{let n=t.port===void 0?void 0:Number(t.port);n!==void 0&&(!Number.isInteger(n)||n<0||n>65535)&&(console.error(`invalid --port "${t.port}": use a whole number from 0 to 65535`),process.exit(2));let r=L.resolve(V.opts().projectRoot),s=typeof t.run=="string"&&/^\d+$/.test(t.run)?t.run:void 0,o=s?`CI run ${s}`:"the last run",i=r,a,c;if(s){let b=mf("trace",t.json===!0),R=yf(t.maxDownload,b);try{let m=le(r),g=Ci(r,m,s,{provider:t.provider,allowFork:t.allowFork===!0,maxDownloadBytes:R});if(!g.folder)throw new D(g.reason??`run ${s} has no Saffron bundle`);let T=await Pi(r,{...g,folder:g.folder},Ie(r,m,[]));if(!T.report)throw new D(`run ${s}'s bundle holds no run report`);i=g.folder,a=T.report}catch(m){return b(m)}c=`Viewed from CI run ${s}: nothing is filed here, so there is nothing to accept or reject. To review its proposals, import the run (saffron import --run ${s}).`}else{(t.provider!==void 0||t.allowFork||t.maxDownload!==void 0)&&(console.error("saffron trace: --provider, --allow-fork and --max-download go with --run <CI run id>"),process.exit(2));let b=L.join(r,".saffron","reports","latest.json");fe.existsSync(b)||(console.error("No report found. Run `saffron run` first."),process.exit(2)),a=JSON.parse(fe.readFileSync(b,"utf8")),t.run!==void 0&&a.startedAt!==t.run&&(console.error(`The last run changed since this was listed: it is now the run of ${a.startedAt}. Refresh the panel to replay it.`),process.exit(2))}let l=a.scenarios.filter(b=>b.evidence?.some(R=>R.kind==="trace"));l.length===0&&(console.error(`${s?o:"The last run"} kept no execution trace. Set "trace": "retain-on-failure" (or "on") in saffron.config.json, or run with --trace retain-on-failure, then run again.`),process.exit(2));let d=e?.trim(),p=l;if(d){let b=l.filter(R=>R.scenario===d||R.feature===d||`${R.feature}:${R.scenario}`===d);p=b.length>0?b:l.filter(R=>R.scenario.toLowerCase().includes(d.toLowerCase()))}if(p.length===0||t.json&&d&&p.length>1){console.error(p.length===0?`No traced scenario matches "${d}". Traced in ${o}:`:`--json prints one trace. Traced in ${o}:`);for(let b of l)console.error(` ${b.status.padEnd(6)} ${b.feature}:${b.scenario}`);console.error('Name one: saffron trace "<scenario name>", or "<feature>:<scenario name>" as listed'),process.exit(2)}let u=p.findIndex(b=>b.status==="red"),f=p.findIndex(b=>b.status==="yellow"),h=u>=0?u:f>=0?f:0,w=p[h],$=b=>L.basename(b,".zip").replace("proof-","Proof replay "),k=b=>{let R=b.evidence.filter(g=>g.kind==="trace"),m=R.find(g=>!g.proof)??R[0];return[m,...R.filter(g=>g!==m)]},[y]=k(w),v;if(p.length===1||t.json){let b=L.join(i,y.file);try{v=bi(i,y)}catch(R){console.error(`The trace cannot be read: ${R instanceof Error?R.message:String(R)}`),process.exit(2)}if(v||(console.error(fe.existsSync(b)?"The trace on disk is from a later run than the last report (a run that stopped before writing its report). Run the scenario again to replay it.":`The trace file is gone: ${b}. Run the scenario again.`),process.exit(2)),t.json){console.log(JSON.stringify(Sd(v),null,2));return}}let S=p.map((b,R)=>{let[m,...g]=k(b);return{scenario:{feature:b.feature,scenario:b.scenario,status:b.status,error:b.error,adaptations:b.adaptations,narrative:b.narrative,proposalDiff:b.proposalDiff,proposalFile:b.proposalFile,proposalRevision:b.proposalRevision,screenshots:b.evidence?.filter(T=>T.kind!=="trace"),ranAt:a.startedAt,source:["cache","agent-record","agent-heal"].find(T=>T===b.source),proposalReplay:b.proposalReplay===!0?!0:void 0},traces:[m,...g].map((T,E)=>({file:L.join(i,T.file),data:R===h&&E===0?v:void 0,read:()=>bi(i,T),checked:T.sha256!==void 0,label:T.proof?$(T.file):"Execution",proof:T.proof===!0,steps:T.proof?T.traceSteps:T.traceSteps??b.steps,uniques:T.proof?T.traceUniques:b.uniques}))}}),x;try{x=await Od({entries:S,start:h,projectRoot:i,port:n,viewOnly:c})}catch(b){console.error(`Could not start the replay: ${b instanceof Error?b.message:String(b)}`),process.exit(2)}for(let{file:b,reason:R}of x.skipped)console.error(`Skipping ${L.relative(i,b)}. ${R}`);console.log(`Saffron replay: ${p.length===1?`${w.feature} \u203A ${w.scenario}`:`${p.length} scenarios, opening on ${w.scenario}`}
|
|
1230
|
+
${x.url}
|
|
1231
|
+
Press Ctrl-C to stop.`),t.open!==!1&&hr(x.url),await new Promise(b=>{process.once("SIGINT",()=>{x.close().finally(b)})}),process.exit(0)});V.command("prune").description("List (and with --yes remove) recordings whose scenario no longer exists: caches and pending proposals left behind by a deleted scenario or feature file").option("--json","machine-readable output").option("--yes","actually delete the files listed").option("--check","exit 1 when anything is orphaned, delete nothing (for CI)").action(e=>{let t=L.resolve(V.opts().projectRoot),n=le(t),r=Mr(t,n.features??"features");r.unreadable.length>0&&(e.json?console.log(JSON.stringify({...r,removed:[]},null,2)):console.error(["saffron: cannot tell what is orphaned while a feature file fails to parse.",...r.unreadable.map(o=>` ${o}`),"Fix these first: a syntax error hides every scenario in the file."].join(`
|
|
1232
|
+
`)),process.exit(2));let s=e.yes&&!e.check?Ta(t,r.orphans):[];if(e.json)console.log(JSON.stringify({...r,removed:s},null,2));else if(r.orphans.length===0)console.log(`Nothing to prune. All ${r.kept} recordings belong to a scenario.`);else{let o=r.orphans.filter(c=>c.kind==="cache").length,i=r.orphans.filter(c=>c.kind==="proposal").length,a=r.orphans.length-o-i;console.log([`${r.orphans.length} orphaned ${r.orphans.length===1?"file":"files"} (${o} cache, ${i} proposal, ${a} screenshot ${a===1?"folder":"folders"}), ${r.kept} still owned:`,"",...r.orphans.map(c=>` ${s.length>0?"removed ":""}${Ea(c)}`),"",s.length>0?"Deleted. Re-record by running the scenarios again if you deleted something by mistake.":"Nothing was deleted. Run `saffron prune --yes` to remove them."].join(`
|
|
1233
|
+
`))}e.check&&r.orphans.length>0&&process.exit(1)});V.command("status").description("Project overview for dashboards and IDE panels: feature files and scenarios with cache state, tags, pending proposals, last run, history, vocabulary health, effective config").option("--json","machine-readable output").action(e=>{let t=L.resolve(V.opts().projectRoot),n=le(t),r=Qn(t,n);if(e.json){console.log(JSON.stringify(r,null,2));return}tl(r)});V.command("report").description("Open the latest HTML report, or merge shard reports into it, or view a CI run's results without importing them (--run)").argument("[paths...]","with --merge: shard report files or folders to search (default: .saffron)").option("--open","open in the default browser",!0).option("--merge","combine the shard-<i>-of-<n>.json reports of one sharded run into latest.json, latest.html and one history line").option("--run <id>","view a CI run's results (an id from saffron runs): downloaded once into .saffron/ci/, checked like an import, nothing filed. Import it with saffron import --run").option("--provider <name>",`with --run: "github" or "azure" (default: ci.provider in the config, else the repository's host)`).option("--allow-fork","with --run: view a run a fork's pull request started").option("--max-download <MB>","with --run: refuse to download more than this many megabytes (default: no limit)").option("--json","with --run: machine-readable output").action(async(e,t)=>{let n=L.resolve(V.opts().projectRoot);if(t.run!==void 0){await uy(n,String(t.run),t);return}for(let s of["provider","allowFork","maxDownload","json"])t[s]!==void 0&&(console.error(`saffron report: --${s.replace(/[A-Z]/g,o=>`-${o.toLowerCase()}`)} goes with --run`),process.exit(2));if(t.merge){gy(n,e);return}e.length>0&&(console.error("saffron report: paths are only read with --merge"),process.exit(2));let r=L.join(n,".saffron","reports","latest.html");fe.existsSync(r)||(console.error("No report found. Run `saffron run` first."),process.exit(2)),console.log(r),hr(r)});function mf(e,t){return n=>{let r=n instanceof Error?n.message:String(n);if(t){let s=n instanceof D?n.kind:void 0;console.log(JSON.stringify({error:r,...s?{kind:s}:{},...n instanceof dr?{sizeBytes:n.sizeBytes}:{}},null,2))}else console.error(`saffron ${e}: ${r}`);process.exit(2)}}function yf(e,t){let n=e===void 0?void 0:Number(e);return n!==void 0&&!(n>0)&&t(`invalid --max-download "${e}": use a number of megabytes above 0`),n===void 0?void 0:n*1024**2}async function uy(e,t,n){let r=mf("report",n.json===!0),s=yf(n.maxDownload,r),o;try{let l=le(e);o=await tf(e,l,Ie(e,l,[]),t,{provider:n.provider,allowFork:n.allowFork===!0,maxDownloadBytes:s})}catch(l){return r(l)}let{results:i}=o;if(n.json){console.log(JSON.stringify(i,null,2));return}if(!i.bundle){console.log(i.reason);return}for(let l of i.warnings)console.log(`\u26A0 ${l}`);let a=i.proposals??[];if(a.length>0&&console.log(`${a.length} proposal${a.length===1?"":"s"}, ${a.filter(l=>l.importable).length} importable: saffron import --run ${t}`),!i.reportHtml){console.log(`run ${t}'s bundle holds no run report`);return}let c=L.join(e,i.reportHtml);console.log(c),hr(c)}V.command("dashboard").description("Open the suite's quality dashboard: tests, failing, flaky and never-run scenarios, healing, timing and tags, from the run history").option("--stdout","print the page instead of writing and opening it (what the IDE panels read)").option("--no-open","write the page without opening a browser").action(e=>{let t=L.resolve(V.opts().projectRoot),n=Qn(t,le(t)),r=zd(n.quality,n.version);if(e.stdout){process.stdout.write(r);return}let s=L.join(t,".saffron","reports","dashboard.html");fe.mkdirSync(L.dirname(s),{recursive:!0}),fe.writeFileSync(s,r),console.log(s),e.open!==!1&&hr(s)});function wf(e){return`named scenarios only: ${e?"the report shows them in place of their last results, beside the rest of the last run":"the report holds just them: the last report was missing, imported from CI, for another base URL or billed another way"}; their history line counts for them, not as a run of the suite`}function gy(e,t){let n=t.length>0?t.map(w=>L.resolve(w)):[L.join(e,".saffron")],r;try{r=Xr(jc(n))}catch(w){console.error(`saffron report --merge: ${w instanceof Error?w.message:String(w)}`),process.exit(2)}let{report:s,history:o,replaced:i}=r;for(let w of i)console.log(`\u26A0 ${w} is a shard a later attempt of the run ran again: left out`);let a=Wn(e),c=a.find(w=>w.runId===o.runId),l=c?a.filter(w=>w.runId!==o.runId):a;o.partial||(s.trends=Co(l,o));let d=c!==void 0&&JSON.stringify(c)===JSON.stringify(o);d||xc(e,o);let p=o.partial?Uo(Bo(e),s):s,{html:u,json:f}=Kn(e,p),h=s.totals;console.log(`merged ${s.shards} shard(s): ${h.scenarios} scenario(s) \xB7 ${h.green} passed, ${h.yellow} pending review, ${h.red} failed \xB7 ${h.aiCalls} AI calls${ko(h)}`),d?console.log("history already holds this run: not appended again"):c&&console.log("history already held this run: its line is replaced with these results"),s.trends?.prev&&console.log(Ro(s.trends.prev));for(let w of s.trends?.chronic??[])console.log(`\u26A0 chronic: ${w.feature} \u203A ${w.scenario}: ${w.heals} heal(s), ${w.reds} red(s) in last ${w.runs} run(s)`);o.partial&&console.log(wf(p!==s)),console.log(`report: ${u}
|
|
1234
|
+
${f}`)}function bf(e,t){try{return Le(e,t,Ie(e,le(e),[]))}catch(n){return`cannot check: ${n instanceof Error?n.message.split(`
|
|
1235
|
+
`)[0]:String(n)}`}}var ue=e=>ie(String(e??""),1/0),mr=(e,t)=>console.error(`\u26A0 proposal ${e} cannot be read: ${ue(t)}`),hy="is no longer pending: it was accepted, rejected or removed since it was listed.",my="is not a pending proposal.",yy="is not a proposal file under .saffron/proposals.",vf="changed since it was listed. Refresh and review it again.",wy="is being decided by another process. Try again.";function Sf(e,t,n,r,s){if(!t.endsWith(".json")||fe.existsSync(t)&&!kt(L.join(e,".saffron","proposals"),t))return s(yy);try{return Pr(t,r,()=>s(n?hy:my))}catch(o){if(!(o instanceof zt))throw o;return s(wy)}}function xf(e){let t=tt(e,mr);if(t.length===0){console.log("No pending proposals.");return}console.log(`Pending proposals:
|
|
1236
|
+
`);for(let{file:n,proposal:r}of t){console.log(` ${n}`);let s=r.meta.verified===!0?" \xB7 verified \u2713":r.meta.verified===!1?" \xB7 UNVERIFIED \u2717":"";console.log(` ${ue(r.cache.feature)} \u203A ${ue(r.cache.scenario)} (${ue(r.meta.mode)}, ${ue(r.meta.createdAt)}${s})`);let o=r.meta.bound?bf(e,r):qr;o&&console.log(` \u2717 STALE: ${ue(o)}`),console.log(` ${ue(r.meta.narrative)}`);for(let i of r.meta.adaptations)console.log(` \u26A0 ${ue(i)}`);r.meta.suggestedFeatureEdit&&console.log(` suggested .feature edit:
|
|
1233
1237
|
${r.meta.suggestedFeatureEdit.split(`
|
|
1234
|
-
`).map(i=>` ${
|
|
1235
|
-
`)}`),console.log()}console.log("Accept with: saffron accept <file> | --all")}
|
|
1238
|
+
`).map(i=>` ${ue(i)}`).join(`
|
|
1239
|
+
`)}`),console.log()}console.log("Accept with: saffron accept <file> | --all")}V.parseAsync().catch(e=>{process.env.SAFFRON_DEBUG?console.error(e):console.error(`saffron: ${e instanceof Error?e.message:String(e)}`),process.exit(2)});
|