saffron-ai 0.9.9 → 1.0.0
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 +423 -0
- package/README.md +2 -2
- package/dist-pkg/cli.js +355 -244
- package/package.json +4 -3
- package/skills/saffron/SKILL.md +181 -95
- package/skills/saffron/references/config.md +4 -3
- package/skills/saffron/references/syntax.md +102 -1
package/dist-pkg/cli.js
CHANGED
|
@@ -1,44 +1,59 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`||
|
|
4
|
-
`&&
|
|
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,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(
|
|
7
|
-
`),definitions:n,invocations:r}}function
|
|
8
|
-
`).filter(
|
|
2
|
+
import ke from"node:fs";import q from"node:path";import Bb from"node:readline";import{Command as Lb}from"commander";import og from"node:fs";import ig from"node:path";import{AstBuilder as ag,dialects as jc,GherkinClassicTokenMatcher as cg,Parser as lg}from"@cucumber/gherkin";import{IdGenerator as dg,StepKeywordType as ii}from"@cucumber/messages";import $c from"node:fs";import Vp from"node:path";import Kn from"node:fs";import Wt from"node:path";var Ie=/\{data:([A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+)\}/g,Yn=Wt.resolve("data"),Pt,vc=process.cwd(),$s=new Map;function Ot(e,t="data",n){vc=Wt.resolve(e),Yn=Wt.isAbsolute(t)?t:Wt.join(e,t),Pt=n?.trim()||void 0,$s.clear()}var Ve=()=>({dir:Yn,env:Pt,root:vc});function xc(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?xc(e[s],o):o;return r}function bc(e,t){try{return JSON.parse(Kn.readFileSync(e,"utf8"))}catch(n){throw new Error(`data file ${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}}function Hp(e){if($s.has(e))return $s.get(e);let t=Wt.join(Yn,`${e}.json`),n=Pt?Wt.join(Yn,`${e}.${Pt}.json`):void 0,r=Kn.existsSync(t),s=n!==void 0&&Kn.existsSync(n);if(!r&&!s)throw new Error(`data file ${Wt.relative(process.cwd(),t)||t} does not exist${Pt?` (nor ${e}.${Pt}.json for the "${Pt}" environment)`:""}`);let o=r?bc(t,`${e}.json`):void 0;if(s){let i=bc(n,`${e}.${Pt}.json`);o=r?xc(o,i):i}return $s.set(e,o),o}function Rn(e){let[t,...n]=e.split("."),r=Hp(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 Je(e){let t;try{t=Rn(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 fn(e){let t;try{t=Rn(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 ks(e){fn(e)}function Sc(e){return e.replace(Ie,(t,n)=>{let r=fn(n);return Array.isArray(Rn(n))?`${t} (a data list, currently: ${r.map(o=>`"${o}"`).join(", ")})`:r[0]})}function qp(e){let t=[],n=[],r="",s=!1,o=!1,i=()=>{n.push(r),(o||n.some(a=>a.trim()!==""))&&t.push(n),n=[],r="",o=!1};for(let a=0;a<e.length;a++){let c=e[a];s?c==='"'&&e[a+1]==='"'?(r+='"',a++):c==='"'?s=!1:r+=c:c==='"'&&r===""?s=o=!0:c===","?(n.push(r),r=""):c===`
|
|
3
|
+
`||c==="\r"?(c==="\r"&&e[a+1]===`
|
|
4
|
+
`&&a++,i()):r+=c}return i(),t.map(a=>a.map(c=>c.trim()))}function Rs(e){let t=a=>{throw new Error(`Examples: {data:${e}}: ${a}`)},n=Pt?Wt.join(Yn,`${e}.${Pt}.csv`):void 0,r=n&&Kn.existsSync(n)?n:Wt.join(Yn,`${e}.csv`);if(!e.includes(".")&&Kn.existsSync(r)){let[a,...c]=qp(Kn.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,u)=>[d,l[u]??""])))}}let s;try{s=Rn(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 Ar(e){return e.replace(Ie,(t,n)=>Je(n))}function Gt(e){let t=new Set;for(let n of e)if(n)for(let r of n.matchAll(Ie))t.add(r[1]);return t}function Zn(e){let t=new Map;for(let n of Gt(e))try{t.set(n,Je(n))}catch{}return t}function Zo(e,t,n=new Set){let r=new Map;for(let[c,l]of t)r.set(l,[...r.get(l)??[],c]);let s=[];for(let[c,l]of r){let d=l.length===1?l:l.filter(u=>n.has(u));d.length===1&&s.push([d[0],c])}s.sort((c,l)=>l[1].length-c[1].length);for(let[c,l]of s)if(l!==""&&e===l)return`{data:${c}}`;let o=new Map(s.filter(([,c])=>c.length>=4).map(([c,l])=>[l,`{data:${c}}`]));if(o.size===0)return e;let i=[...o.keys()].map(c=>c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),a=new RegExp(i,"g");return e.split(/(\{(?:env|data|unique|date)[^{}]*\})/).map((c,l)=>l%2?c:c.replace(a,d=>o.get(d))).join("")}var Ue=/\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g;function Es(e,t){return e.replace(Ue,(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 ei(e){let t=new Set;for(let n of e)if(n)for(let r of n.matchAll(Ue))t.add(r[1]);return t}function st(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 Cr(e){let t=[];for(let n of Gt(e))try{t.push(...fn(n))}catch{}return t}function We(e){let t=st(e);return ei([...t,...Cr(t)])}function ot(e){let t=new Map;for(let n of We(e)){let r=process.env[n];r!==void 0&&t.set(n,r)}return t}var Tn=3,Xo=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)?)\\?\}`,Jp=/\{(env:[A-Za-z_][A-Za-z0-9_]*|data:[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+)\\\}/g,Tc=e=>`${e.slice(0,-1)}\\}`,Ec=e=>e.replace(Jp,"{$1}"),Ts={'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"};function Qo(e,t,n,r){let s="";for(let o of e.split("")){let i=o.charCodeAt(0);if(t?.test(o)||i<32&&!Ts[o]){let a=i.toString(16).padStart(4,"0");s+="\\u"+(n?a.toUpperCase():a)}else Ts[o]?s+=Ts[o]:o==="/"&&r?s+="\\/":s+=o}return s}function Wp(e){return[e,e.replace(/%[0-9A-F]{2}/g,t=>t.toLowerCase())]}function kc(e,t,n){return e.replace(/[&<>"'+]|[^\x00-\x7f]/gu,r=>t[r]??(n&&r>"\x7F"?n(r.codePointAt(0)):r))}function Gp(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 Kp=[/["#<>']/,/["#<>?^`{}]/,/["#<>?^`{|}]/,/["#<>?^`{}/:;=@[\\\]|]/,/["#<>?^`{}/:;=@[\\\]|']/];function Yp(e){let t=/[^\x00-\x7f]/,n=new Set([e]);for(let[o,i,a]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(Qo(e,o,i,a));let r=o=>Qo(o,void 0,!1,!1).replaceAll('\\"','"').replaceAll("'","\\'");for(let o of[e,je(e),je(e).replaceAll("/","\\/")])for(let i of[o,r(o),o.replaceAll("'","\\'")])n.add(i),n.add(Qo(i,void 0,!1,!1));let s=o=>{try{for(let i of Wp(o()))n.add(i)}catch{}};s(()=>encodeURIComponent(e)),s(()=>encodeURIComponent(e).replaceAll("'","%27")),s(()=>encodeURI(e)),s(()=>new URLSearchParams([["",e]]).toString().slice(1));for(let o of Kp)s(()=>Gp(e,o));for(let o of[{"&":"&","<":"<",">":">"},{"&":"&","<":"<",">":">",'"':""","'":"'"},{"&":"&","<":"<",">":">",'"':""","'":"'"},{"&":"&","<":"<",">":">",'"':""","'":"'"},{"&":"&","<":"<",">":">",'"':""","'":"'"},{"&":"&","<":"<",">":">",'"':""","'":"'","+":"+"}])n.add(kc(e,o));return n.add(kc(e,{"&":"&","<":"<",">":">",'"':""","'":"'","+":"+"},o=>`&#x${o.toString(16).toUpperCase()};`)),[...n]}var _r=e=>e.map(t=>`{env:${t}}`).join(""),je=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Zp=e=>Buffer.from(e,"utf8").toString("latin1");function un(e,t={}){let n=[...e.entries()].filter(([,f])=>f.length>=Tn).sort((f,p)=>p[1].length-f[1].length),r=new Map,s=new Set;for(let[f,p]of n){t.standaloneBelow!==void 0&&p.length<t.standaloneBelow&&s.add(p);let m=t.encodings?Yp(p):[p];for(let h of m){let w=t.bytes?[Zp(h),.../^[\x00-\xff]*$/.test(h)?[h]:[]]:[h];for(let b of w)r.has(b)||r.set(b,f)}}let o=new Set(n.map(([,f])=>f)),i=new Set(["u"]);for(let[,f]of n)for(let p of f){let m=Ts[p]??(p==="/"?"\\/":void 0);m&&i.add(m.slice(1))}let a=new RegExp(`\\\\[${[...i].map(je).join("")}]`);if(r.size===0)return{empty:!0,mask:f=>f,matches:()=>[],occursIn:()=>!1,isValue:()=>!1,hiddenByEscape:a};let c=[...r.keys()].sort((f,p)=>p.length-f.length).map(f=>s.has(f)?`(?<![A-Za-z0-9])${je(f)}(?![A-Za-z0-9])`:je(f)).join("|"),l=new RegExp(`(${Xo})|${c}`,"g"),d=new RegExp(`(${Xo})|${c}`,"y"),u=new RegExp(c),g=f=>{let p=[];l.lastIndex=0;for(let m=l.exec(f);m!==null;m=l.exec(f)){if(m[1]!==void 0)continue;let h=m.index,w=h+m[0].length,b=[r.get(m[0])];for(let y=h+1;y<w;y++){d.lastIndex=y;let S=d.exec(f);S&&S[1]===void 0&&y+S[0].length>w&&(w=y+S[0].length,b.push(r.get(S[0])))}p.push({start:h,end:w,names:[...new Set(b)]}),l.lastIndex=w}return p};return{empty:!1,hiddenByEscape:a,occursIn:f=>u.test(f),isValue:f=>o.has(f),matches:g,mask(f){let p="",m=0;for(let h of g(f))p+=f.slice(m,h.start)+_r(h.names),m=h.end;return m===0?f:p+f.slice(m)}}}function ti(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(Ue)].map(g=>g[1]);if(l.length===0||l.some(g=>!t.has(g)))continue;let d=c.replace(Ue,(g,f)=>t.get(f));if(d===c||d.length<Tn||c===`{env:${l[0]}}`)continue;let u=n(d);r.has(u)||r.set(u,c.split(/(\{env:[A-Za-z_][A-Za-z0-9_]*\})/).map((g,f)=>f%2?g:n(g)).join(""))}if(r.size===0)return i=>i;let s=[...r.keys()].sort((i,a)=>a.length-i.length).map(je).join("|"),o=new RegExp(`(${Xo})|${s}`,"g");return i=>i.replace(o,(a,c)=>c!==void 0?a:r.get(a))}var Rc=new WeakMap;function it(e,t){let n=Rc.get(t);return n||(n=un(t,{encodings:!0}),Rc.set(t,n)),n.mask(e)}function Ac(e){let t=Vp.join(e,".env");if($c.existsSync(t))for(let n of $c.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 En(e,t){return e.replace(/<([^<>]+)>/g,(n,r)=>r in t?t[r]:n)}function ze(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 An(e){return e!==void 0?{docstring:e}:{}}function pn(e){let t=new Map;for(let r of e){let s={...ze(r.resolvedTable??r.table),...An(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 ni(e){return e.replace(/\\.|["'`]|>>/g,t=>t[0]==="\\"?t:t===">>"?"\\>\\>":`\\${t}`)}var we={quoted:e=>JSON.stringify(e).slice(1,-1),regex:e=>ni(je(e).replaceAll("/","\\/")),pattern:e=>je(e)};function Cn(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))}var ri=/^As "([^"]+)"\s+(?=\S)/,$t="default",Ge=e=>e||$t;function kt(e){return ri.exec(e)?.[1].trim()||void 0}function Cc(e,t){let n=ri.exec(e)?.[0],r=Te(t);return n?`${n}${r}`:r}var Te=e=>e.replace(ri,"");function Ke(e,t){let n=t;return e.map(r=>{let s=kt(r);return s!==void 0&&(n=s===$t?void 0:s),n})}function _c(e){if(!(!/^As\s+"[^"]*"\s+\S/.test(e)||kt(e)!==void 0))return`"${e}" starts like a browser session but names none. Write As "name" and the step after one space, as in As "buyer" I open the cart; the name cannot be empty.`}var de=e=>e??"";function gn(e){return new Set(e.map(t=>de(t.session))).size>1}function Pr(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"session"}function As(e,t=[],n){let r,s,o,i=!1,a=!1,c;return e.map((l,d)=>{let u=r,g=/^\s*("""|```)/.exec(l)?.[1];if(g)return c?c===g&&(c=void 0):c=g,u;if(c)return u;if(/^\s*Feature:/.test(l))r=s=o=void 0,i=a=!1;else if(/^\s*Rule:/.test(l))i=!0,a=!1,r=o=s;else if(/^\s*Background:/.test(l))a=!0,r=i?s:void 0;else if(n?.has(d)||/^\s*(?:Scenario(?: Outline| Template)?|Example):/.test(l))a=!1,r=i?o:s;else if(/^\s*StepSet:/.test(l))a=!1,r=void 0;else{let f=/^\s*(?:Given|When|Then|And|But|\*)\s+(.+?)\s*$/.exec(l)?.[1],p=/^\s*StepSet\s+([^\s:].*?)\s*$/.exec(l)?.[1],m=f?[f]:t.find(h=>h.name===p)?.steps;m?.length&&(r=Ke(m,r).at(-1),a&&(i?o=r:s=r))}return u})}function Pc(e,t,n){if(!n)return;let r=[...new Set(e)].filter(o=>o!==$t&&!t.includes(o)).sort();return r.length<2?void 0:`${`${r.slice(0,-1).join(", ")} and ${r.at(-1)}`} ${r.length===2?"both":"all"} start signed in from storageState (${n}), as the same person; give each its own sessions entry in saffron.config.json.`}import Or from"node:fs";import Cs from"node:path";import{AstBuilder as Qp,GherkinClassicTokenMatcher as Xp,Parser as eg}from"@cucumber/gherkin";import{IdGenerator as tg}from"@cucumber/messages";var Ee=class extends Error{},ng=/^(\s*)StepSet:\s*(.+?)\s*$/,rg=/^(\s*)StepSet\s+([^\s:].*?)\s*$/;function si(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(ng);if(l)return n.set(a+1,l[2]),`${l[1]}Scenario: ${l[2]}`;let d=i.match(rg);return d?(r.set(a+1,d[2]),`${d[1]}* StepSet ${d[2]}`):i}).join(`
|
|
7
|
+
`),definitions:n,invocations:r}}function sg(e){return new eg(new Qp(tg.uuid()),new Xp).parse(e)}function Ic(e,t){for(let n of e)n.scenario?t(n.scenario):"rule"in n&&n.rule&&Ic(n.rule.children,t)}function Kt(e,t){let n=new Map;for(let r of e){let s=Cs.relative(t,r),o=si(Or.readFileSync(r,"utf8"));if(o.definitions.size===0)continue;let i=sg(o.source);i.feature&&Ic(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 Ee(`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 Ee(`StepSet "${c}" (${s}:${a.location.line}) has an Examples table: step sets take their values from the invoking scenario.`);for(let d of a.steps)if(o.invocations.has(d.location.line))throw new Ee(`StepSet "${c}" (${s}:${a.location.line}) invokes another step set at line ${d.location.line}, and step sets cannot be nested.`);n.set(c,{name:c,file:s,line:a.location.line,steps:[...a.steps]})})}return n}var oi=[".feature",".saffron"];function Yt(e){return oi.some(t=>e.endsWith(t))}function Ye(e,t,n){let r=Cs.isAbsolute(t.features??"features")?t.features:Cs.join(e,t.features??"features"),s=new Set(_n(r));for(let o of n)o.endsWith(".saffron")&&s.add(o);return Kt([...s].sort(),e)}var Oc=new Set([".saffron","node_modules",".git"]);function Zt(e,t){if(!Or.existsSync(e))return[];let n=[],r=new Set,s=[],o=c=>["ENOENT","ELOOP"].includes(c.code??""),i=c=>{try{return Or.statSync(c)}catch(l){if(o(l))return;throw l}},a=(c,l=!1)=>{let d,u;try{if(d=Or.realpathSync(c),r.has(d))return;u=Or.readdirSync(c,{withFileTypes:!0})}catch(g){if(l&&o(g))return;throw g}r.add(d);for(let g of u){let f=Cs.join(c,g.name);if(g.isSymbolicLink()){let p=i(f);p?.isDirectory()?Oc.has(g.name)||s.push(f):p?.isFile()&&t(g.name)&&n.push(f)}else g.isDirectory()?Oc.has(g.name)||a(f):g.isFile()&&t(g.name)&&n.push(f)}};a(e);for(let c=0;c<s.length;c++)a(s[c],!0);return n.sort()}function _n(e){return Zt(e,t=>t.endsWith(".saffron"))}function Nc(e,t,n){return e.map(({step:r,source:s})=>{let o;switch(r.keywordType){case ii.OUTCOME:o="assertion";break;case ii.CONTEXT:case ii.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:En(r.text,t),table:i,resolvedTable:i?.map(c=>c.map(l=>En(l,t))),docString:a,resolvedDocString:a!==void 0?En(a,t):void 0,source:s}})}function Mc(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 Ee(`${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 fg(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 u=[...new Set([...a,...d.tags.map(p=>p.name)])],g=d.name.trim().match(/^\{data:([A-Za-z0-9_.-]+)\}$/);if(g&&!d.tableHeader){let p=`${t}:${d.location.line}`;if(!o)throw new Ee(`${p} 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 m;try{m=Rs(g[1])}catch(b){throw new Ee(`${p} ${b instanceof Error?b.message:String(b)}`)}let w=[...new Set([...r,...s].flatMap(b=>[b.step.text,b.step.docString?.content??"",...b.step.dataTable?.rows.flatMap(y=>y.cells.map(S=>S.value))??[]].flatMap(y=>[...y.matchAll(/<([^<>]+)>/g)].map(S=>S[1]))))].filter(b=>!m.headers.includes(b)&&!b.startsWith("table:")&&b!=="docstring");if(w.length>0)throw new Ee(`${p} the scenario uses <${w.join(">, <")}>, but {data:${g[1]}} has the columns ${m.headers.map(b=>`"${b}"`).join(", ")}.`);for(let b of m.rows)l+=1,c.push({params:b,label:` (example ${l})`,tags:u});continue}let f=d.tableHeader?.cells.map(p=>p.value)??[];for(let p of d.tableBody){l+=1;let m={};p.cells.forEach((h,w)=>{m[f[w]]=h.value}),c.push({params:m,label:` (example ${l})`,line:p.location.line,tags:u})}}}return c.map(({params:l,label:d,line:u,tags:g})=>{let f={value:"action"},p=[...Nc(r,l,f),...Nc(s,l,f)];for(let h of p){let w=_c(h.resolvedText);if(w){let b=h.source?`${h.source.file}:${h.source.line}`:t;throw new Ee(`${b} ${w}${h.text!==h.resolvedText?` (with the Examples values of "${e.name}${d}")`:""}`)}}let m=Ke(p.map(h=>h.resolvedText));return{featurePath:t,featureName:n,name:e.name,displayName:`${e.name}${d}`,tags:g,steps:p.map((h,w)=>m[w]===void 0?h:{...h,session:m[w]}),params:l,...e.examples.length>0?{exampleRows:c.map(h=>h.params)}:{},line:e.location.line,...u!==void 0?{exampleLine:u}:{}}})}function Fc(e,t){let n=og.readFileSync(e,"utf8"),r=e.endsWith(".saffron"),s=r?si(n):{source:n,definitions:new Map,invocations:new Map},o=new lg(new ag(dg.uuid()),new cg),i=ig.relative(t,e),a;try{a=o.parse(s.source)}catch(c){let l=(c instanceof Error?c.message:String(c)).split(`
|
|
8
|
+
`).filter(u=>/^\(\d+:\d+\)/.test(u)).map(u=>`${i}${u.replace(/^\((\d+):(\d+)\)/,":$1:$2")}`),d=!r&&/^\s*StepSet\b/m.test(n);throw new Ee(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
9
|
${l.join(`
|
|
10
10
|
`)||(c instanceof Error?c.message:String(c))}`)}return{doc:a,pre:s,relPath:i,isSaffron:r,lineCount:n.split(`
|
|
11
11
|
`).length-(n.endsWith(`
|
|
12
|
-
`)?1:0)}}function
|
|
13
|
-
`)}function Yn(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 En(e,t){if(t.trim()==="")return!1;let n=s=>(s??"").replace(/<[^<>]+>/g,""),r=new Set([t,...Object.values(xe).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 qr(e){let t=[];return{pattern:e.replace(/"((?:[^"\\]|\\.)*)"/g,(r,s)=>(t.push(s),`"\xAB${t.length-1}\xBB"`)),args:t}}function Fp(e,t){let n=r=>JSON.stringify(r.map(({pageFingerprint:s,...o})=>o));return n(e)===n(t)}function Lp(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 lt(e){let t=Fa.join(e,".saffron","cache"),n=new Map,r=new Map,s=0;if(Ma.existsSync(t))for(let a of Ma.readdirSync(t,{recursive:!0})){let c=String(a);if(!c.endsWith(".json"))continue;let l=Lt(Fa.join(t,c));if(l){s++;for(let d of l.steps){let p=d.gherkin,u=JSON.stringify(d.actions.map(({pageFingerprint:w,...R})=>R)),f=r.get(p)??[];f.includes(u)||(f.push(u),r.set(p,f));let g=n.get(p);!g||l.recordedAt>g.recordedAt?n.set(p,{gherkin:d.gherkin,table:d.table,docString:d.docString,actions:d.actions,sourceParams:Mt(l.steps),sourceData:l.data,feature:l.feature,scenario:l.scenario,recordedAt:l.recordedAt,variants:f.length}):g.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}=qr(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 La(e,t,n){if(!!e.table!=!!t.table)return!1;if(e.table&&t.table){let o=Object.keys(Ce(e.table)),i=Object.keys(Ce(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=Ce(e.table),i=Ce(t.table);for(let a of Object.keys(o))if(o[a]!==i[a]&&(!Yn(e.actions,`<${a}>`)||En(e.actions,o[a])))return!1}for(let[o,i]of Object.entries(e.sourceParams??{}))if(o in n&&n[o]!==i&&En(e.actions,i))return!1;for(let[o,i]of Object.entries(e.sourceData??{})){let a;try{a=Sn(o)}catch{continue}if(a!==i&&(En(e.actions,i)||e.gherkin.includes(`{data:${o}}`)&&!Yn(e.actions,`{data:${o}}`)))return!1}let r={...n,...Ce(t.resolvedTable??t.table),...en(t.resolvedDocString??t.docString)},s=Lp({gherkin:e.gherkin,keyword:"",kind:"action",actions:e.actions});for(let o of s)if(!(o in r))return!1;return!0}function Ba(e,t,n){let r=e.steps.get(t.text);if(r)return La(r,t,n)?r:void 0;let{pattern:s,args:o}=qr(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 g=a.get(u);if(g!==void 0&&g!==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 La(d,t,n)?d:void 0}function Da(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&&Fp(r.actions,o.actions)){n.push({index:s,from:r.gherkin,to:o.gherkin,feature:o.feature,scenario:o.scenario});break}}}),n}function uo(e){if(!Ua.existsSync(e))return[];let t=[];for(let n of Ua.readdirSync(e,{recursive:!0})){let r=String(n);Tt(r)&&t.push(po.join(e,r))}return t.sort()}function dt(e,t,n,r){let s=po.isAbsolute(t)?t:po.join(e,t),o=uo(s),i=n??Rt(o.filter(f=>f.endsWith(".saffron")),e),a=new Map,c=new Map;for(let f of o)for(let g of r?.get(f)??Be(f,e,i)){let w=`${g.featurePath}::${g.name}`;for(let R of g.steps){let $=a.get(R.text);if($||($={text:R.text,keywords:new Map,kind:R.kind,scenarios:new Set,files:new Set,fromStepSet:R.source?.fromStepSet},a.set(R.text,$)),$.keywords.set(R.keyword,($.keywords.get(R.keyword)??0)+1),$.scenarios.add(w),R.source&&$.files.add(R.source.file),R.source?.fromStepSet){let m=c.get(R.source.fromStepSet);m||c.set(R.source.fromStepSet,m=new Set),m.add(w)}}}let l=lt(e),d=new Set(l.divergent),p=[...a.values()].map(f=>({text:f.text,keyword:[...f.keywords.entries()].sort((g,w)=>w[1]-g[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,g)=>g.usage-f.usage||f.text.localeCompare(g.text)),u=[...i.values()].map(f=>({name:f.name,file:f.file,line:f.line,steps:f.steps.map(g=>g.text),usage:c.get(f.name)?.size??0})).sort((f,g)=>g.usage-f.usage||f.name.localeCompare(g.name));return{steps:p,stepSets:u,scannedFiles:o.length,scannedCaches:l.scannedCaches}}function Jr(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 za(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
|
-
`}
|
|
15
|
-
|
|
16
|
-
`)
|
|
12
|
+
`)?1:0)}}function Bc(e,t){let{doc:n,pre:r,lineCount:s}=Fc(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:u}=l.background;o.push({kind:"background",name:d,line:u.line,start:u.line,rows:[]})}else if(l.scenario){let{name:d,location:u,tags:g,examples:f}=l.scenario,p=r.definitions.has(u.line)?"stepSet":"scenario",m=f.flatMap(h=>h.tableBody.map(w=>w.location.line));o.push({kind:p,name:d,line:u.line,start:i(g,u.line),rows:m})}else if("rule"in l&&l.rule){let{name:d,location:u,tags:g}=l.rule;o.push({kind:"rule",name:d,line:u.line,start:i(g,u.line),rows:[]}),a(l.rule.children)}};return n.feature&&a(n.feature.children),{blocks:o,lineCount:s}}function Ir(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&&jc[r]||jc.en,o=[...s.scenario,...s.scenarioOutline].map(c=>`${c.trim()}:`),i=[],a;return t.forEach((c,l)=>{let d=c.trim(),u=['"""',"```"].find(f=>d.startsWith(f));if(u){a?a===u&&(a=void 0):a=u;return}if(a)return;let g=o.find(f=>d.startsWith(f));g&&i.push({line:l+1,name:d.slice(g.length).trim()})}),i}function Ze(e,t,n){let{doc:r,pre:s,relPath:o,isSaffron:i}=Fc(e,t);if(!r.feature)return[];let a=r.feature.name,c=[],l=(d,u,g)=>{let f=u;for(let p of d)if(p.background)f=[...u,...Mc(p.background.steps,o,!0,s.invocations,n)];else if(p.scenario){if(s.definitions.has(p.scenario.location.line))continue;c.push(...fg(p.scenario,o,a,f,Mc(p.scenario.steps,o,!1,s.invocations,n),i,g))}else"rule"in p&&p.rule&&l(p.rule.children,f,[...g,...p.rule.tags.map(m=>m.name)])};return l(r.feature.children,[],r.feature.tags.map(d=>d.name)),c}import ul from"node:fs";import js from"node:path";import il from"node:fs";import al from"node:path";import{createHash as Yc}from"node:crypto";import Et from"node:fs";import Tt from"node:path";import{createHash as mg}from"node:crypto";var ug=/\{date([+-]\d+)?(?::([^}]+))?\}/g;function pg(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 It(e,t=new Date){return e.replace(ug,(n,r,s)=>{let o=new Date(t);return o.setDate(o.getDate()+(r?parseInt(r,10):0)),pg(o,s??"YYYY-MM-DD")})}var gg=/\b(\d{4})-(\d{2})-(\d{2})\b/g,hg=400;function Lc(e,t=new Date,n=[]){let r=new Date(t.getFullYear(),t.getMonth(),t.getDate());return e.replace(gg,(s,o,i,a)=>{if(n.some(d=>d.includes(s)))return s;let c=new Date(Number(o),Number(i)-1,Number(a));if(Number.isNaN(c.getTime()))return s;let l=Math.round((c.getTime()-r.getTime())/864e5);return Math.abs(l)>hg?s:l===0?"{date}":`{date${l>0?"+":""}${l}}`})}function Rt(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 jr(e){return[e.action==="expectDiffers"?void 0:e.value,e.url,e.urlPattern,e.pattern,e.promptText,e.each,...[e.target,e.toTarget].flatMap(t=>[t?.name,t?.nameRegex,t?.label,t?.text,t?.placeholder,t?.testId,t?.frame,...t?.fallbackSelectors??[]])]}function Qt(e){return[...jr(e),e.status,e.method,e.attribute]}function Xt(e,t){if(t.trim()==="")return!1;let{exact:n,loose:r}=qc(t),s=r.map(i=>en(i,"iu")),o=i=>{let a=i.replace(Ue," ").replace(Ie," "),c=a.replace(/<[^<>]+>/g," ").normalize("NFC");return/[<>]/.test(t)?[c,a.normalize("NFC")]:[c]};return e.some(i=>Qt(i).some(a=>a!==void 0&&o(a).some(c=>{let l=t.length<3?c.replace(ci," "):c;return n.some(d=>l.includes(d))||s.some(d=>d.test(l))})))}function Pn(e,t,n,r,s,o){let i=s?Date.parse(s):NaN,a=Object.keys(n),c=_s(t,o,a),l=(d,u)=>ai(d,o,u);for(let[d,u]of a.entries())for(let g of a.slice(d+1))if(!(r[u]===void 0||r[g]===void 0||l(n[u],i)==="")&&!(l(n[u],i)!==l(n[g],i)||l(r[u])===l(r[g]))&&(Rt(e,`<${u}>`)||Rt(e,`<${g}>`)))return!0;for(let d of a.filter(u=>/\{env:/.test(n[u])&&r[u]!==void 0))if([...n[d].matchAll(Ue)].map(([g])=>g).some(g=>!t.includes(g)&&Rt(e,g))){for(let g of a)if(!(g===d||/\{env:/.test(n[g])||r[g]===void 0||!t.includes(`<${g}>`)||Rt(e,`<${g}>`))&&l(r[g])!==l(r[d]))return!0}return Object.entries(n).some(([d,u])=>{let g=r[d];if(g===void 0)return!1;let f=u.includes("{date")&&!Number.isNaN(i);if(g===u&&(!f||It(u,new Date(i))===It(g)))return!1;let p=t.includes(`<${d}>`);if(u.trim()==="")return p&&g.trim()!==""&&!Rt(e,`<${d}>`);let m=new Set(g===u?[]:_s(u,o,a));if(f){let h=u.replace(/\{date([+-]\d+)?:[^}]*\}/g,"{date$1}");h!==u&&p&&g!==u&&m.add(h);for(let w of[0,1])for(let b of new Set([u,h])){let y=It(b,new Date(i-w*864e5));(p||/(?<!\d)\d{4}(?!\d)/.test(y))&&m.add(y)}}return[...m].some(h=>h.trim()!==""&&(p||!c.some(w=>en(h).test(w)))&&Hc(e,h,p,w=>_s(w,o,a)))})}function zc(e,t,n={}){let r=/\{env:|\{date/;if(e.some(i=>Qt(i).some(a=>a!==void 0&&(r.test(a)||/\{data:/.test(a))))||Object.values(t).some(i=>i.trim()==="")&&e.some(i=>i.value===""))return!0;let s=Object.values(t).filter(i=>i.trim()!=="");if(new Set(s).size<s.length)return!0;let o=i=>[i.replace(Xn(Object.keys(t))," ").normalize("NFC")];return Object.values(t).some(i=>{if(r.test(i)||[...i.matchAll(Ie)].some(([,c])=>!(c in n)))return!0;let a=i.replace(Ie,(c,l)=>n[l]);return[i,a].some(c=>c.trim()!==""&&Hc(e,c,!0,o))})}function Hc(e,t,n,r){if(t.length<3&&!n)return!1;let{exact:s,loose:o}=qc(t),i=n&&t.length>=3,a=s.map(u=>Ps(t,u,"u",n)),c=o.map(u=>en(u,"iu")),l=u=>{let g=t.length<3?u.replace(ci," "):u;return a.some(f=>f.test(g))||(i?o.some(f=>g.toLowerCase().includes(f)):c.some(f=>f.test(g)))},d=u=>n?Qt(u):jr(u);return e.some(u=>d(u).some(g=>g!==void 0&&r(g).some(l)))}function Ps(e,t=e,n="gu",r=!0){let s=t.normalize("NFC");return r&&e.length>=3?new RegExp(je(s),n):en(s,n)}function Qn(e,t,n,r=t){let s=e.normalize("NFC");return s.includes(r.normalize("NFC"))?Ps(t,r,"u",n).test(t.length<3?s.replace(ci," "):s):!1}function ai(e,t,n){return It(_s(e,t,[]).at(-1),n===void 0||Number.isNaN(n)?new Date:new Date(n))}function Nr(e,t,n,r,s){let o=r?Date.parse(r):NaN;return e.find(i=>{let a=t[i],c=n[i];return a===void 0||c===void 0?!0:a!==c&&ai(a,s,o)!==ai(c,s)})}function Xn(e){return new RegExp(`<(?:table:[^<>]+|docstring${[...e].map(t=>`|${je(t)}`).join("")})>`,"g")}var Dc=String.raw`[\p{L}\p{N}\p{M}]`,Uc=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u,ci=/:nth-[a-z-]+\([^)]*\)|\bnth=-?\d+|\bh[1-6]\b/gi;function en(e,t="u"){let n=[...e],r=n.length>=2&&Uc.test(n[0])?"":`(?<!${Dc})`,s=n.length>=2&&Uc.test(n[n.length-1])?"":`(?!${Dc})`;return new RegExp(`${r}${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}${s}`,t)}function qc(e){let t=e.normalize("NFC"),n=[...new Set([t,...Object.values(we).map(i=>i(t))])],r=t.toLowerCase(),s=new Set([r]);try{s.add(encodeURIComponent(t).toLowerCase()),s.add(encodeURIComponent(t).replaceAll("%20","+").toLowerCase())}catch{}let o=r.split(/[^\p{L}\p{N}\p{M}]+/u).filter(Boolean);if(o.length>1)for(let i of["-","_",""])s.add(o.join(i));return{exact:n,loose:[...s]}}function li(e){return e.length>=5||e.length>=3&&/\p{N}/u.test(e)}function _s(e,t,n){let r=(e??"").replace(n?Xn(n):/<[^<>]+>/g," ").normalize("NFC"),s=r.replace(Ie,(o,i)=>t?.[i]??wg(i)??o).replace(Ue,(o,i)=>process.env[i]??o);return s===r?[r]:[r,s]}function wg(e){try{return Je(e)}catch{return}}function Vc(e,t){return e===t?"bare":e===`^${t}$`?"anchored":void 0}function er(e){if(!/\{(?:env|data):/.test(e))return;let t=!1,n=e.replace(Ie,(s,o)=>{try{return Je(o)}catch{return t=!0,s}});if(!new RegExp(Ue.source).test(n))return;let r=n.replace(Ue,(s,o)=>{let i=process.env[o];return i===void 0&&(t=!0),i??s});return t?void 0:mg("sha256").update(r).digest("hex")}var at=new Set(["expectVisible","expectNotVisible","expectText","expectUrl","expectValue","expectDiffers","expectMatches","expectAttribute","expectResponse","expectEach"]);function Mr(e){if((e.rowBound?.length??0)>0||Ke(e.steps.map(n=>n.gherkin)).some(n=>n!==void 0)||e.examples&&e.steps.some(n=>zc(n.actions,e.examples,e.data)))return 2;let t=n=>n.clickCount!==void 0&&n.clickCount!==1||n.button!==void 0&&n.button!=="left"||(n.modifiers?.length??0)>0||n.clearSelection===!0||n.action==="selectOption"&&(n.value??"").includes(`
|
|
13
|
+
`)||[n.status,n.method,n.attribute].some(r=>r!==void 0&&/<[^<>]+>|\{(?:data|env|date|unique)[^{}]*\}/.test(r));return e.steps.some(n=>n.actions.some(t))?2:1}import Jc from"node:path";var Os=2,yg=new Set(["goto","click","fill","press","selectOption","check","uncheck","hover","waitFor","captureText","handleDialog","uploadFile","dragTo","waitForResponse","switchTab","closeTab","newTab",...at]),bg=["role","name","nameRegex","label","text","testId","placeholder","frame"],vg=["value","url","saveAs","compareTo","each","pattern","attribute","promptText","urlPattern","method","status","pageFingerprint"],di=/[\u0000-\u001f\u007f-\u009f]/,ge=class extends Error{constructor(n,r){super(`${n}: ${r}`);this.file=n;this.problem=r}file;problem},Qe=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function J(e,t,n){if(!e)throw new ge(t,n)}function Wc(e,t,n){J(Qe(e),t,`${n} must be an object`);for(let r of bg)J(e[r]===void 0||typeof e[r]=="string",t,`${n}.${r} must be a string`);e.fallbackSelectors!==void 0&&J(Array.isArray(e.fallbackSelectors)&&e.fallbackSelectors.every(r=>typeof r=="string"),t,`${n}.fallbackSelectors must be a list of selectors`)}var xg=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),Sg={goto:["url"],click:["target"],fill:["target","value"],press:["value"],selectOption:["target","valueOrClear"],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 $g(e,t,n){let r=o=>typeof e[o]=="string",s=o=>Qe(e[o])&&xg(e[o]);for(let o of Sg[e.action])switch(o){case"target":case"toTarget":J(s(o),t,`${n} (${e.action}) needs a ${o} with a role, name, label, text, test id, placeholder or selector`);break;case"urlOrValue":J(r("url")||r("value"),t,`${n} (${e.action}) needs a url`);break;case"targetOrValue":J(s("target")||r("value"),t,`${n} (${e.action}) needs a target or a value`);break;case"valueOrClear":J(r("value")||e.clearSelection===!0,t,`${n} (${e.action}) needs value`);break;default:J(r(o),t,`${n} (${e.action}) needs ${o}`)}for(let o of["target","toTarget"])e[o]!==void 0&&J(s(o),t,`${n}.${o} has no usable locator`);if(e.action==="expectUrl"){let o=e.url??e.value;J(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&&J(e[o].length>0,t,`${n}.${o} must not be empty`);["press","uploadFile","switchTab","expectText"].includes(e.action)&&J(typeof e.value=="string"&&e.value.length>0,t,`${n} (${e.action}) needs a non-empty value`)}function kg(e,t,n){J(Qe(e),t,`${n} must be an object`),J(typeof e.action=="string",t,`${n}.action is missing`),J(yg.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 vg)J(e[r]===void 0||typeof e[r]=="string",t,`${n}.${r} must be a string`);J(e.opensTab===void 0||typeof e.opensTab=="boolean",t,`${n}.opensTab must be true or false`),J(e.clearSelection===void 0||typeof e.clearSelection=="boolean",t,`${n}.clearSelection must be true or false`),J(e.clickCount===void 0||Number.isInteger(e.clickCount)&&e.clickCount>=1,t,`${n}.clickCount must be a whole number from 1`),J(e.button===void 0||["left","right","middle"].includes(e.button),t,`${n}.button must be "left", "right" or "middle"`),J(e.modifiers===void 0||Array.isArray(e.modifiers)&&e.modifiers.every(r=>["Alt","Control","ControlOrMeta","Meta","Shift"].includes(r)),t,`${n}.modifiers must be a list of Alt, Control, ControlOrMeta, Meta or Shift`),e.target!==void 0&&Wc(e.target,t,`${n}.target`),e.toTarget!==void 0&&Wc(e.toTarget,t,`${n}.toTarget`),$g(e,t,n)}function Rg(e,t,n){J(Qe(e),t,`${n} must be an object`),J(typeof e.gherkin=="string"&&e.gherkin.length>0,t,`${n}.gherkin (the step text) is missing`),J(typeof e.keyword=="string",t,`${n}.keyword is missing`),J(e.kind==="action"||e.kind==="assertion",t,`${n}.kind must be "action" or "assertion"`),J(Array.isArray(e.actions),t,`${n}.actions must be a list (empty for a recorded no-op)`),e.actions.forEach((r,s)=>kg(r,t,`${n}.actions[${s}]`)),e.table!==void 0&&J(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`),J(e.docString===void 0||typeof e.docString=="string",t,`${n}.docString must be a string`),J(e.fromStepSet===void 0||typeof e.fromStepSet=="string",t,`${n}.fromStepSet must be a string`)}function fi(e,t){if(J(Qe(e),t,"is not a JSON object"),J(e.version!==void 0,t,"has no version: not a Saffron recording"),J(e.version===1||e.version===Os,t,typeof e.version=="number"&&e.version>Os?`is schema version ${e.version}; this saffron-ai reads versions 1 to ${Os}. Update saffron-ai to the release that wrote it`:`has schema version ${JSON.stringify(e.version)}; this saffron-ai reads versions 1 to ${Os}`),J(typeof e.feature=="string"&&e.feature.length>0,t,"feature (the feature file path) is missing"),J(!Jc.isAbsolute(e.feature)&&!Jc.win32.isAbsolute(e.feature)&&!e.feature.split(/[\\/]/).includes(".."),t,`names a feature file outside the project: ${JSON.stringify(e.feature)}`),J(typeof e.scenario=="string"&&e.scenario.length>0,t,"scenario (the scenario name) is missing"),J(e.recordedAt===void 0||typeof e.recordedAt=="string",t,"recordedAt must be a string"),J(e.recordedBy===void 0||e.recordedBy==="agent"||e.recordedBy==="manual",t,'recordedBy must be "agent" or "manual"'),J(Array.isArray(e.steps),t,"steps must be a list"),e.steps.forEach((n,r)=>Rg(n,t,`steps[${r}]`)),e.data!==void 0&&J(Qe(e.data)&&Object.values(e.data).every(n=>typeof n=="string"),t,"data must map references to strings"),e.examples!==void 0&&J(Qe(e.examples)&&Object.values(e.examples).every(n=>typeof n=="string"),t,"examples must map columns to strings"),e.rowBound!==void 0){let n=e.steps.length;J(Array.isArray(e.rowBound)&&e.rowBound.every(r=>Qe(r)&&typeof r.column=="string"&&Number.isInteger(r.step)&&r.step>=0&&r.step<n&&(r.reason==="list"||r.reason==="glued"||r.reason==="data"||r.reason==="value"||r.reason==="reads")&&(r.valueSha===void 0||typeof r.valueSha=="string"&&/^[0-9a-f]{64}$/.test(r.valueSha))),t,'rowBound must be a list of { column, step, reason: "list" | "glued" | "data" | "value" | "reads", valueSha? } naming steps of this recording'),J(Qe(e.examples),t,"rowBound needs examples, the row it was recorded on")}return e}function Gc(e,t){J(Qe(e),t,"is not a JSON object"),J(Qe(e.meta),t,"meta is missing: not a Saffron proposal");let n=e.meta;J(n.mode==="record"||n.mode==="heal",t,'meta.mode must be "record" or "heal"'),J(typeof n.narrative=="string",t,"meta.narrative must be a string"),J(Array.isArray(n.adaptations)&&n.adaptations.every(r=>typeof r=="string"),t,"meta.adaptations must be a list of strings"),J(n.verified===void 0||typeof n.verified=="boolean",t,"meta.verified must be true or false"),J(Qe(n.usage),t,"meta.usage is missing"),n.featureEdits!==void 0&&(J(Array.isArray(n.featureEdits)&&n.featureEdits.every(r=>Qe(r)&&typeof r.index=="number"&&typeof r.text=="string"),t,"meta.featureEdits must be a list of { index, text }"),n.featureEdits.forEach((r,s)=>J(r.text.trim().length>0,t,`meta.featureEdits[${s}].text is empty: a feature edit must give the step's new text`)),n.featureEdits.forEach((r,s)=>J(!di.test(r.text),t,`meta.featureEdits[${s}].text holds a line break or another control character`))),n.bound!==void 0&&J(Qe(n.bound)&&["scenario","committed","recording"].every(r=>typeof n.bound[r]=="string"),t,"meta.bound must hold the scenario, committed and recording digests"),fi(e.cache,`${t} (cache)`)}var Zc=".saffron",Qc=e=>Yc("sha1").update(e).digest("hex").slice(0,8),pi=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");function Xc(e){return pi(e)||`unnamed-${Qc(e)}`}var el=e=>pi(e)||"unnamed";function tl(e){let t=pi(e);return t&&/[^\x00-\x7f]/.test(e)?`${t}-${Qc(e)}`:Xc(e)}function nl(e,t,n,r){let s;try{s=Et.readFileSync(e,"utf8")}catch{return!0}try{return t(JSON.parse(s))}catch{return r.some(o=>new RegExp(`"${n}"\\s*:\\s*${je(JSON.stringify(o))}`).test(s))}}function Tg(e,t,n){let r=Tt.join(e,`${tl(t)}.json`),s=Tt.join(e,`${el(t)}.json`);return s===r||Et.existsSync(r)||!Et.existsSync(s)?r:nl(s,o=>n(o)===t,"scenario",[t])?s:r}var Kc=new Map;function rl(e){let t=Tt.join(e,"saffron.config.json"),n=Et.statSync(t,{throwIfNoEntry:!1}),r=n?`${n.mtimeMs}:${n.ctimeMs}:${n.size}:${n.ino}`:"none",s=Kc.get(e);if(s?.stamp===r)return s.top;let o="features";try{let c=JSON.parse(Et.readFileSync(t,"utf8"));typeof c?.features=="string"&&c.features.trim()&&(o=c.features)}catch{}let i=Tt.relative(e,Tt.resolve(e,o)),a=i.startsWith("..")||Tt.isAbsolute(i)?void 0:i.split(/[\\/]/)[0];return Kc.set(e,{stamp:r,top:a}),a}function ui(e,t,n=Xc){let r=e.split(/[\\/]/).filter(Boolean),s=r.pop()??"unnamed",o=t===void 0||r[0]===t?r.slice(1):r,i=n([...o,Tt.basename(s,".feature")].join("-"));if(o.length===0)return i;let a=Yc("sha1").update(e.replace(/\\/g,"/")).digest("hex").slice(0,6);return`${i}-${a}`}function sl(e,t,n,r,s){let o=d=>Tg(Tt.join(e,Zc,t,d),r,u=>s(u)?.scenario),i=o(ui(n,rl(e))),a=o(ui(n,void 0,el));if(a===i||Et.existsSync(i)||!Et.existsSync(a))return i;let c=d=>typeof d=="string"?d.replace(/\\/g,"/"):d;return nl(a,d=>c(s(d)?.feature)===c(n),"feature",[n,c(n)])?a:i}function fe(e,t,n){return sl(e,"cache",t,n,r=>r)}function ol(e,t){let n=new Map;for(let r of t){let s=fe(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 ${Tt.relative(e,r)}. Rename one scenario or one file.`)}var On="owner.json";function tn(e,t,n){return Tt.join(e,Zc,"artifacts",ui(t,rl(e)),tl(n))}function ct(e,t,n){return sl(e,"proposals",t,n,r=>r?.cache)}function jt(e,t){try{return He(e)}catch(n){if(!(n instanceof ge))throw n;t?.(e,n.problem);return}}function He(e){if(!Et.existsSync(e))return;let t;try{t=JSON.parse(Et.readFileSync(e,"utf8"))}catch(n){throw new ge(e,`is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}return fi(t,e)}function tr(e,t){Et.mkdirSync(Tt.dirname(e),{recursive:!0}),Et.writeFileSync(e,`${JSON.stringify({...t,version:Mr(t)},null,2)}
|
|
14
|
+
`)}function Is(e){let t=[];return{pattern:e.replace(/"((?:[^"\\]|\\.)*)"/g,(r,s)=>(t.push(s),`"\xAB${t.length-1}\xBB"`)),args:t}}function gi(e,t){let n=r=>JSON.stringify(r.map(({pageFingerprint:s,...o})=>o));return n(e)===n(t)}function Eg(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)Qt(r).forEach(n);return n(e.gherkin),t}var ll=/<[^<>]+>/,nn=(e,t)=>`${de(e)}
|
|
15
|
+
${t}`;function Nt(e){let t=al.join(e,".saffron","cache"),n=new Map,r=new Map,s=new Map,o=new Map,i=new Set,a=0;if(il.existsSync(t))for(let d of il.readdirSync(t,{recursive:!0})){let u=String(d);if(!u.endsWith(".json"))continue;let g=jt(al.join(t,u));if(!g)continue;a++;let f=Ke(g.steps.map(m=>m.gherkin)),p=pn(g.steps);for(let[m,h]of g.steps.entries()){let w=h.gherkin,b=JSON.stringify(h.actions.map(({pageFingerprint:A,...O})=>O)),y=nn(f[m],w),S=o.get(y)??new Set;S.add(b),o.set(y,S),S.size>1&&i.add(w);let x=n.get(w),C=Math.max(S.size,x?.variants??0),$={gherkin:h.gherkin,table:h.table,docString:h.docString,actions:h.actions,sourceParams:p,sourceData:g.data,...g.examples?{examples:g.examples}:{},...g.rowBound?.some(A=>A.step===m)?{rowBound:g.rowBound.filter(A=>A.step===m).map(A=>A.column)}:{},...g.rowBound?.some(A=>A.step===m&&A.valueSha)?{rowBoundValues:Object.fromEntries(g.rowBound.filter(A=>A.step===m&&A.valueSha).map(A=>[A.column,A.valueSha]))}:{},feature:g.feature,scenario:g.scenario,recordedAt:g.recordedAt??"",variants:C,...f[m]?{session:f[m]}:{}};!x||$.recordedAt>x.recordedAt?n.set(w,$):x.variants=C;let k=n.get(w),R=Te(w),_=s.get(R);if((!_||_.recordedAt<=k.recordedAt)&&s.set(R,k),f[m]?.match(ll))continue;let v=r.get(y);!v||v.recordedAt<=$.recordedAt?r.set(y,{...$,variants:S.size}):v.variants=S.size}}let c=[...i],l=new Map;for(let d of r.values()){let{pattern:u,args:g}=Is(d.gherkin);if(g.length===0)continue;let f=nn(d.session,u),p=l.get(f);(!p||d.recordedAt>p.recordedAt)&&l.set(f,{...d,args:g})}return{steps:n,seeds:r,bare:s,patterns:l,divergent:c,scannedCaches:a}}function cl(e,t,n){if(!!e.table!=!!t.table)return!1;if(e.table&&t.table){let o=Object.keys(ze(e.table)),i=Object.keys(ze(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>")))||Xt(e.actions,e.docString)))return!1;if(e.table&&t.table){let o=ze(e.table),i=ze(t.table);for(let a of Object.keys(o))if(o[a]!==i[a]&&(!Rt(e.actions,`<${a}>`)||Xt(e.actions,o[a])))return!1}for(let[o,i]of Object.entries(e.sourceParams??{}))if(o in n&&n[o]!==i&&Xt(e.actions,i))return!1;if(e.rowBound&&(!e.examples||Nr(e.rowBound,e.examples,n,e.recordedAt,e.sourceData)!==void 0)||e.rowBoundValues&&Object.entries(e.rowBoundValues).some(([o,i])=>er(n[o]??"")!==i))return!1;if(e.examples){let o=[t.text,...t.table?.flat()??[],t.docString??""].join(`
|
|
16
|
+
`);if(Pn(e.actions,o,e.examples,n,e.recordedAt,e.sourceData))return!1}for(let[o,i]of Object.entries(e.sourceData??{})){let a;try{a=Je(o)}catch{continue}if(a!==i&&(Xt(e.actions,i)||e.gherkin.includes(`{data:${o}}`)&&!Rt(e.actions,`{data:${o}}`)))return!1}let r={...n,...ze(t.resolvedTable??t.table),...An(t.resolvedDocString??t.docString)},s=Eg({gherkin:e.gherkin,keyword:"",kind:"action",actions:e.actions});for(let o of s)if(!(o in r))return!1;return!0}function dl(e,t,n){let r=t.text,[s]=Ke([r],t.session),o=s?.match(ll)?t.session:s,i=e.seeds.get(nn(o,r));if(i)return cl(i,t,n)?i:void 0;let{pattern:a,args:c}=Is(r);if(c.length===0)return;let l=e.patterns.get(nn(o,a));if(!l)return;let d=new Map;for(let w=0;w<c.length;w++){let b=l.args[w],y=c[w],S=d.get(b);if(S!==void 0&&S!==y)return;d.set(b,y)}let u=new Map([...d].filter(([w,b])=>w!==b)),g=w=>[w?.name,w?.nameRegex,w?.label,w?.text,w?.placeholder];for(let w of u.keys())if(!l.actions.some(y=>[y.value,y.url,y.pattern,y.urlPattern,y.promptText,y.status,y.method,y.attribute,...g(y.target),...g(y.toTarget)].includes(w)))return;let f=w=>{let b=y=>y?{...y,name:w(y.name),nameRegex:w(y.nameRegex),label:w(y.label),text:w(y.text),placeholder:w(y.placeholder)}:void 0;return l.actions.map(({pageFingerprint:y,...S})=>({...S,value:w(S.value),url:w(S.url),pattern:w(S.pattern),urlPattern:w(S.urlPattern),promptText:w(S.promptText),status:w(S.status),method:w(S.method),attribute:w(S.attribute),target:b(S.target),toTarget:b(S.toTarget)}))},p=f(w=>w!==void 0&&u.has(w)?"":w),m=w=>{if(l.sourceData?.[w]!==void 0)return l.sourceData[w];try{return Je(w)}catch{return}};for(let w of u.keys()){if(Xt(p,w))return;let b=w.replace(Ie,(y,S)=>m(S)??y);if(b!==w&&Xt(p,b))return}for(let w of u.keys())for(let[b]of w.matchAll(/<[^<>]+>|\{(?:data|env):[^{}]+\}/g))if(Rt(p,b))return;if(l.examples){let w={...l.examples};for(let[b,y]of u){let S=b.match(/^<([^<>]+)>$/)?.[1];S!==void 0&&S in w&&(w[S]=y)}if(Pn(l.actions,l.gherkin,l.examples,w,l.recordedAt,l.sourceData))return}let h={...l,gherkin:t.text,actions:f(w=>w!==void 0&&u.has(w)?u.get(w):w)};return cl(h,t,n)?h:void 0}function fl(e,t){let n=[];return e.forEach((r,s)=>{if(r.actions.length!==0&&!(t.steps.has(r.gherkin)||t.bare.has(Te(r.gherkin)))){for(let o of t.steps.values())if(!(o.variants>1)&&o.actions.length!==0&&kt(o.gherkin)===kt(r.gherkin)&&gi(r.actions,o.actions)){n.push({index:s,from:r.gherkin,to:o.gherkin,feature:o.feature,scenario:o.scenario});break}}}),n}function hi(e){return Zt(e,Yt)}function Mt(e,t,n,r){let s=js.isAbsolute(t)?t:js.join(e,t),o=hi(s),i=n??Kt(o.filter(m=>m.endsWith(".saffron")),e),a=new Map,c=new Map;for(let m of o)for(let h of r?.get(m)??Ze(m,e,i)){let w=`${h.featurePath}::${h.name}`;for(let b of h.steps){let y=Te(b.text),S=a.get(y);if(S||(S={text:y,prefixed:new Set,keywords:new Map,kind:b.kind,scenarios:new Set,files:new Set,fromStepSet:b.source?.fromStepSet},a.set(y,S)),b.text!==y&&S.prefixed.add(b.text),S.keywords.set(b.keyword,(S.keywords.get(b.keyword)??0)+1),S.scenarios.add(w),b.source&&S.files.add(b.source.file),b.source?.fromStepSet){let x=c.get(b.source.fromStepSet);x||c.set(b.source.fromStepSet,x=new Set),x.add(w)}}}let l=Nt(e),d=new Map;for(let[m,h]of l.seeds){let w=Te(h.gherkin),b=d.get(w)??{};b[m]=h.variants>1?"divergent":"recorded",d.set(w,b)}for(let[m,h]of Ag(e)){let w=Te(m.slice(m.indexOf(`
|
|
17
|
+
`)+1));d.set(w,{...d.get(w),[m]:h})}let u=m=>d.get(Te(m))?.[nn(Ke([m])[0],m)]??"unrecorded",g=m=>{let h=Object.values(d.get(m)??{});return h.includes("divergent")?"divergent":h.length?"recorded":"unrecorded"},f=[...a.values()].map(m=>({text:m.text,keyword:[...m.keywords.entries()].sort((h,w)=>w[1]-h[1])[0][0],kind:m.kind,status:g(m.text),recordings:d.get(m.text)??{},...m.prefixed.size?{sessions:Object.fromEntries([...m.prefixed].sort().map(h=>[h,u(h)]))}:{},usage:m.scenarios.size,files:[...m.files].sort(),fromStepSet:m.fromStepSet})).sort((m,h)=>h.usage-m.usage||m.text.localeCompare(h.text)),p=[...i.values()].map(m=>({name:m.name,file:m.file,line:m.line,steps:m.steps.map(h=>h.text),usage:c.get(m.name)?.size??0})).sort((m,h)=>h.usage-m.usage||m.name.localeCompare(h.name));return{steps:f,stepSets:p,scannedFiles:o.length,scannedCaches:l.scannedCaches}}function Ag(e){let t=js.join(e,".saffron","cache"),n=new Map;if(!ul.existsSync(t))return new Map;for(let r of ul.readdirSync(t,{recursive:!0})){if(!String(r).endsWith(".json"))continue;let s=jt(js.join(t,String(r)));if(!s)continue;let o=Ke(s.steps.map(i=>i.gherkin));s.steps.forEach((i,a)=>{if(!o[a]?.match(/<[^<>]+>/))return;let c=nn(o[a],i.gherkin),l=n.get(c)??new Set;l.add(JSON.stringify(i.actions.map(({pageFingerprint:d,...u})=>u))),n.set(c,l)})}return new Map([...n].map(([r,s])=>[r,s.size>1?"divergent":"recorded"]))}function Ns(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 pl(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) in ${r.file}`};return JSON.stringify(t,null,2)+`
|
|
18
|
+
`}import{Server as zm}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as Hm}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as qm,ListToolsRequestSchema as Vm}from"@modelcontextprotocol/sdk/types.js";import Ut from"node:fs";import _t from"node:path";import gl from"node:fs";import Cg from"node:path";function ye(e){Ac(e);let t=Cg.join(e,"saffron.config.json"),n=gl.existsSync(t)?JSON.parse(gl.readFileSync(t,"utf8")):{};return typeof n.features=="string"&&!n.features.trim()&&(n.features=nr.features),Ot(e,n.dataDir,process.env.SAFFRON_ENV??n.env),n}var nr={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,agentWorkers:1,assertionPolicy:"strict",hookTimeoutMs:3e5,trace:"off"};function hl(e){return{...nr,...Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}}import mi from"node:fs";import Ms from"node:path";import{fileURLToPath as _g}from"node:url";function Fs(){let e=Ms.dirname(_g(import.meta.url));for(let t=0;t<6;t++){let n=Ms.join(e,"package.json");if(mi.existsSync(n))try{if(JSON.parse(mi.readFileSync(n,"utf8")).name==="saffron-ai")return e}catch{}e=Ms.dirname(e)}}function Xe(){let e=Fs();if(!e)return"unknown";try{return JSON.parse(mi.readFileSync(Ms.join(e,"package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}import et from"node:fs";import Fe from"node:path";import Me from"node:fs";import{createHash as Ig}from"node:crypto";import ml from"node:os";import rr from"node:path";import rn from"node:fs";import hn from"node:path";import{createHash as Pg,randomBytes as Og}from"node:crypto";function ht(e,t){try{if(!rn.statSync(t).isFile())return!1;let n=hn.relative(rn.realpathSync(e),rn.realpathSync(t));return n!==""&&n!==".."&&!n.startsWith(".."+hn.sep)&&!hn.isAbsolute(n)}catch{return!1}}var Ae=(e,t)=>hn.relative(e,t).split(hn.sep).join("/");function At(e){return Pg("sha256").update(e).digest("hex")}function Ne(e,t,n){rn.mkdirSync(hn.dirname(e),{recursive:!0});let r=`${e}.${process.pid}-${Og(4).toString("hex")}.partial`;try{rn.writeFileSync(r,t),n!==void 0&&rn.chmodSync(r,n),rn.renameSync(r,e)}catch(s){throw rn.rmSync(r,{force:!0}),s}}function mn(e,t){let n=hn.join(e,t.file);if(ht(hn.join(e,".saffron","artifacts"),n))try{let r=rn.readFileSync(n);return t.sha256&&At(r)!==t.sha256?void 0:r}catch{return}}function wl(e,t){Me.mkdirSync(rr.dirname(e),{recursive:!0});let n=Buffer.from(`${JSON.stringify(t,null,2)}
|
|
19
|
+
`);return sr(e,()=>Ne(e,n)),bi(n)}var jg=6e4,Ng=5e3,Mg=60*6e4,Fg=new Int32Array(new SharedArrayBuffer(4)),In=class extends Error{};function sr(e,t,n=1e4){let r=`${e}.lock`,s=Date.now()+n,o;for(;;){o=JSON.stringify({pid:process.pid,host:ml.hostname(),at:new Date().toISOString()});try{Me.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 In(`${e} is being decided by another process. Try again.`);Bg(r)||Atomics.wait(Fg,0,0,25)}}try{return t()}finally{wi(r)===o&&Me.rmSync(r,{force:!0})}}function wi(e){try{return Me.readFileSync(e,"utf8")}catch{return}}function Bg(e){let t=wi(e);if(t===void 0)return!1;let n={};try{n=JSON.parse(t)||{}}catch{}let r=Date.parse(n.at??""),s=jg;if(Number.isNaN(r)){try{r=Me.statSync(e).mtimeMs}catch{return!1}s=Ng}let o=n.host===ml.hostname()&&typeof n.pid=="number";return o&&Lg(n.pid)&&Date.now()-r<Mg||!o&&Date.now()-r<s||wi(e)!==t?!1:(Me.rmSync(e,{force:!0}),!0)}function Lg(e){try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}function Bs(e,t,n){return Me.existsSync(e)?sr(e,()=>Me.existsSync(e)?t():n()):n()}function yi(e){let t=/^(.+)#([0-9a-f]{64})$/i.exec(e);return t?{file:t[1],revision:t[2].toLowerCase()}:{file:e}}function mt(e){return bi(Me.readFileSync(e))}var bi=e=>Ig("sha256").update(e).digest("hex"),yl=e=>rr.join(e,".saffron","reports","filed.json");function bl(e){let t;try{t=JSON.parse(Me.readFileSync(yl(e),"utf8"))}catch{return{}}return!t||typeof t!="object"||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([,n])=>typeof n=="string"))}function vl(e,t,n){return bl(e)[Ae(e,t)]===n}function xl(e,t,n){let r=bl(e);r[Ae(e,t)]=n;for(let[s,o]of Object.entries(r)){try{if(mt(rr.join(e,s))===o)continue}catch{}delete r[s]}Ne(yl(e),`${JSON.stringify(r,null,2)}
|
|
20
|
+
`)}function or(e){return Ls(e).proposal}function Ls(e){return vi(Me.readFileSync(e),e)}function vi(e,t){let n;try{n=JSON.parse(e.toString("utf8"))}catch(r){throw new ge(t,`is not valid JSON: ${r instanceof Error?r.message:String(r)}`)}return Gc(n,t),{proposal:n,revision:bi(e),bytes:e}}function Ft(e,t){let n=rr.join(e,".saffron","proposals");if(!Me.existsSync(n))return[];let r=[];for(let s of Me.readdirSync(n)){let o=rr.join(n,s);if(Me.statSync(o).isDirectory())for(let i of Me.readdirSync(o)){if(!i.endsWith(".json"))continue;let a=rr.join(o,i);try{r.push({file:a,...Ls(a)})}catch(c){if(!t||!(c instanceof ge))throw c;t(a,c.problem)}}}return r}function Ds(e,t){let n=or(t),r=fe(e,n.cache.feature,n.cache.scenario);return tr(r,n.cache),Me.rmSync(t),r}function Us(e){Me.rmSync(e)}var xi=(e,t)=>Fe.relative(e,t).split(Fe.sep).join("/");function Sl(e){return et.existsSync(e)?[...et.readdirSync(e,{recursive:!0})].map(String).filter(t=>t.endsWith(".json")).map(t=>Fe.join(e,t)).sort():[]}function $l(e){try{let t=JSON.parse(et.readFileSync(e,"utf8")),n="cache"in t&&t.cache?t.cache:t;return{feature:n.feature,scenario:n.scenario}}catch{return{}}}function kl(e){try{let t=JSON.parse(et.readFileSync(Fe.join(e,On),"utf8"));return{feature:typeof t.feature=="string"?t.feature:void 0,scenario:typeof t.scenario=="string"?t.scenario:void 0}}catch{return{}}}function Hs(e,t,n){let r=Fe.isAbsolute(t)?t:Fe.join(e,t),s=new Set(Zt(r,Yt));for(let l of["cache","proposals"])for(let d of Sl(Fe.join(e,".saffron",l))){let{feature:u}=$l(d);if(typeof u=="string"){let g=Fe.resolve(e,u);et.existsSync(g)&&s.add(g)}}for(let l of zs(Fe.join(e,".saffron","artifacts")))for(let d of zs(l)){let u=kl(d).feature;if(u){let g=Fe.resolve(e,u);et.existsSync(g)&&s.add(g)}}let o=[...n?.unreadable??[]],i=[...s].filter(l=>!n?.parsedFiles.has(l)),a=new Map;if(i.length>0)try{a=Kt([...new Set([..._n(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=Ze(l,e,a)}catch(u){o.push(`${xi(e,l)}: ${u instanceof Error?u.message:String(u)}`);continue}for(let u of d)c.add(fe(e,u.featurePath,u.name)),c.add(ct(e,u.featurePath,u.name)),c.add(tn(e,u.featurePath,u.displayName))}return{...Dg(e,c),unreadable:o}}function Dg(e,t){let n=[],r=0;for(let o of["cache","proposal"]){let i=Fe.join(e,".saffron",o==="cache"?"cache":"proposals");for(let a of Sl(i)){if(t.has(a)){r++;continue}let{feature:c,scenario:l}=$l(a),d=c?Fe.join(e,c):void 0;n.push({file:xi(e,a),kind:o,feature:c,scenario:l,reason:c?et.existsSync(d)?"scenario-gone":"feature-gone":"unknown"})}}let s=Fe.join(e,".saffron","artifacts");for(let o of zs(s))for(let i of zs(o)){let{feature:a,scenario:c}=kl(i),l=a&&c?tn(e,a,c):void 0;if(t.has(i)||l&&t.has(l)&&l!==i&&!et.existsSync(l)){r++;continue}n.push({file:xi(e,i),kind:"artifact",feature:a,scenario:c,reason:a?et.existsSync(Fe.join(e,a))?"scenario-gone":"feature-gone":"unknown"})}return{orphans:n,kept:r}}function zs(e){try{return et.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>Fe.join(e,t.name)).sort()}catch{return[]}}function Rl(e,t){let n=[],r=new Set;for(let s of t){let o=Fe.join(e,s.file);try{s.kind==="proposal"?sr(o,()=>et.rmSync(o)):et.rmSync(o,{recursive:s.kind==="artifact"}),n.push(s.file),r.add(Fe.dirname(o))}catch{}}for(let s of r)try{et.readdirSync(s).length===0&&et.rmdirSync(s)}catch{}return n}function Tl(e){if(e.kind==="artifact")return`${e.file}/
|
|
17
21
|
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}
|
|
18
|
-
${e.kind==="proposal"?"pending proposal for ":""}${t}: ${n}`}import
|
|
22
|
+
${e.kind==="proposal"?"pending proposal for ":""}${t}: ${n}`}import jh from"node:path";import{createHash as Ug,randomBytes as zg}from"node:crypto";var El=/\{unique:([A-Za-z0-9_-]+)(?::(digits))?\}/g,wt="__saffron_unique_seed",wn=()=>`${Date.now().toString(36)}${zg(4).toString("hex")}`;function Al(e,t,n=!1){let r=Ug("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 jn(e,t){return e.replace(El,(n,r,s)=>Al(t,r,s==="digits"))}function ir(e,t){let n=new Map;for(let r of e)if(r)for(let s of r.matchAll(El))n.set(s[0],Al(t,s[1],s[2]==="digits"));return n}function Cl(e,t){let n=e;for(let[r,s]of t)n=n.split(s).join(r);return n}import{createHash as Hg}from"node:crypto";async function qs(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:${Hg("sha256").update(n).digest("hex")}`}var qg=/^[a-z][a-z\d+.-]*:|^\/\//i,_l=e=>e.pathname.replace(/\/+$/,"");function Fr(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=_l(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 Si(e,t){if(qg.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:`${_l(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 $i from"node:fs";import Vg from"node:os";import tt from"node:path";import{Client as Jg}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as Wg}from"@modelcontextprotocol/sdk/client/stdio.js";import{McpServer as Gg}from"@modelcontextprotocol/sdk/server/mcp.js";import{CallToolRequestSchema as Kg,ListToolsRequestSchema as Yg}from"@modelcontextprotocol/sdk/types.js";var ki=6e4;function Ol(){return $i.mkdtempSync(tt.join(Vg.tmpdir(),"saffron-mcp-"))}var Ri=1e8,Il=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 Zg(e){return{...e,tools:e.tools.filter(t=>Il.has(t.name))}}function Qg(e){return Il.has(e)?void 0:{isError:!0,content:[{type:"text",text:`${e} is not available in a Saffron session.`}]}}var Pl=e=>({isError:!0,content:[{type:"text",text:e}]}),Xg=new Set(["http:","https:"]);function Br(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 Xg.has(n.protocol)||n.href==="about:blank"?void 0:t}function Ti(e,t){if(!Array.isArray(e))return;let n=i=>{try{return $i.realpathSync(i)}catch{return}},r=n(t)??tt.resolve(t),s=i=>{let a=tt.relative(r,i);return a.startsWith("..")||tt.isAbsolute(a)?void 0:a},o=i=>i.split(tt.sep).some(a=>a.startsWith(".")&&a!=="..");for(let i of e){if(typeof i!="string")continue;let a=tt.resolve(i),c=n(a),l=n(tt.dirname(a)),d=s(c??(l?tt.join(l,tt.basename(a)):a));if(d===void 0&&!c&&!l){let u=tt.relative(tt.resolve(t),a);!u.startsWith("..")&&!tt.isAbsolute(u)&&(d=u)}if(d===void 0)return`${i} is outside the project; uploads come from files inside it.`;if(o(d)||o(tt.relative(tt.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($i.statSync(c).isDirectory())return`${i} is a folder; a Saffron session uploads single files only.`}}function eh(e,t,n=process.cwd()){if(!t)return{args:t};let r=e==="browser_navigate"||e==="browser_tabs"?Br(t.url):e==="browser_file_upload"?Ti(t.paths,n):void 0;if(r)return{args:t,refused:Pl(r)};if(e==="browser_tabs"&&t.isolatedContext!==void 0)return{args:t,refused:Pl(`isolatedContext is not available in a Saffron session: open the tab in the scenario's own context. Another person's browser is an As "name" step.`)};if("filename"in t){let{filename:s,...o}=t;return{args:o}}return{args:t}}function th(e,t=ki){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=`
|
|
19
23
|
|
|
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
|
|
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=
|
|
22
|
-
`),"utf8"):void 0}function
|
|
23
|
-
`)
|
|
24
|
-
`),r=[];for(let s of n){if(!s.trim()){r.push(s);continue}let i=
|
|
25
|
-
`)}var
|
|
26
|
-
`||e==="\r";function
|
|
27
|
-
`)
|
|
28
|
-
`)
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
`)
|
|
33
|
-
`)
|
|
24
|
+
[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 jl(e,t){let n=new Jg({name:"saffron-cap",version:"1"}),r=Object.fromEntries(Object.entries(process.env).filter(o=>o[1]!==void 0));await n.connect(new Wg({...e,env:r,stderr:"ignore"}));let s=Ei(n,void 0,t);return{config:{type:"sdk",name:"playwright",instance:s},close:async()=>{await Promise.allSettled([n.close(),s.close()])}}}function Ei(e,t=(r,s,o)=>o(),n){let r=new Gg({name:"playwright",version:"1"},{capabilities:{tools:{}}});return r.server.setRequestHandler(Yg,async()=>Zg(await e.listTools())),r.server.setRequestHandler(Kg,async(s,o)=>{let i=Qg(s.params.name);if(i)return i;let a=eh(s.params.name,s.params.arguments,n);if(a.refused)return a.refused;let c={...s.params,arguments:a.args};return th(await t(c.name,c.arguments,()=>e.callTool(c,void 0,{timeout:Ri,signal:o.signal})))}),r}import Dr from"node:fs";import ah from"node:os";import Ai from"node:path";import nt from"node:fs";import nh from"node:path";import{createHash as rh,randomBytes as sh}from"node:crypto";import Js from"node:zlib";var yn=4294967295,Ml=67324752,Fl=33639248,Bl=101010256;function Ll(e){return Lr(e).map(t=>({name:t.name,data:t.read()}))}function Dl(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)===Bl){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)!==Fl)throw new Error("not a zip file: bad central directory entry");let d=i.readUInt16LE(a+10),u=i.readUInt32LE(a+16),g=i.readUInt32LE(a+20),f=i.readUInt32LE(a+24),p=i.readUInt16LE(a+28),m=i.readUInt16LE(a+30),h=i.readUInt16LE(a+32),w=i.readUInt32LE(a+42),b=i.subarray(a+46,a+46+p).toString("utf8");a+=46+p+m+h;let y=e(w,30);if(y.length<30||y.readUInt32LE(0)!==Ml)throw new Error(`not a zip file: bad local header for ${b}`);let S=w+30+y.readUInt16LE(26)+y.readUInt16LE(28);if(!b.endsWith("/")){if(d!==0&&d!==8)throw new Error(`zip entry ${b} uses compression method ${d}, which is not supported`);c.push({name:b,method:d,crc:u,size:f,compressedSize:g,start:S})}}return c}function Lr(e){return Dl((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):Js.inflateRawSync(a)}})}function oh(e,t,n){let r=nt.openSync(e,"r");try{let s=Buffer.alloc(n),o=0;for(;o<n;){let i=nt.readSync(r,s,o,n-o,t+o);if(i===0)break;o+=i}return s.subarray(0,o)}finally{nt.closeSync(r)}}function Ul(e){let t=nt.statSync(e).size,n=(r,s)=>oh(e,r,Math.max(0,Math.min(s,t-r)));return Dl(n,t).map(r=>({...r,raw:()=>n(r.start,r.compressedSize)}))}var ih=(()=>{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 Vs(e,t=0){let n=Js.crc32;if(n)return n(e,t)>>>0;let r=(t^4294967295)>>>0;for(let s of e)r=ih[(r^s)&255]^r>>>8;return(r^4294967295)>>>0}var Nl=1024*1024;function zl(e,t){let n=nt.openSync(e,"r");try{let r=Buffer.alloc(Nl);for(let s;(s=nt.readSync(n,r,0,Nl,null))>0;)t(r.subarray(0,s))}finally{nt.closeSync(n)}}function Ws(e){let t=rh("sha256"),n=0,r=0;return zl(e,s=>{n=Vs(s,n),r+=s.length,t.update(s)}),{crc:n,size:r,sha256:t.digest("hex")}}function Hl(e,t,n,r,s,o){let i=Buffer.alloc(30);i.writeUInt32LE(Ml,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(Fl,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 ql(e,t,n){let r=Buffer.alloc(22);return r.writeUInt32LE(Bl,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 Vl=e=>new Error(`cannot write a zip of ${e} files: one holds at most 65,535`),Jl=e=>new Error(`cannot write ${e} into a zip: a zip holds at most 4 GB, and this one would be larger`),Wl=()=>new Error("cannot write the zip: a zip holds at most 4 GB, and this one would be larger");function Gl(e){if(e.length>65535)throw Vl(e.length);let t=[],n=[],r=0;for(let o of e){let i="raw"in o,a=i?o.raw:Js.deflateRawSync(o.data),c=i?o.size:o.data.length,l=Buffer.from(o.name,"utf8");if(c>yn||r+30+l.length+a.length>yn)throw Jl(o.name);let{local:d,central:u}=Hl(l,i?o.method:8,i?o.crc:Vs(o.data),a.length,c,r);t.push(d,l,a),n.push(u,l),r+=d.length+l.length+a.length}let s=n.reduce((o,i)=>o+i.length,0);if(r+s>yn)throw Wl();return Buffer.concat([...t,...n,ql(e.length,s,r)])}function ar(e,t){for(let n=0;n<t.length;)n+=nt.writeSync(e,t,n,t.length-n)}function Kl(e,t){if(t.length>65535)throw Vl(t.length);nt.mkdirSync(nh.dirname(e),{recursive:!0});let n=`${e}.${process.pid}-${sh(4).toString("hex")}.partial`,r=nt.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)?Ws(a.file):void 0,u=l?void 0:Js.deflateRawSync(a.data),g=l?d?.crc??a.crc:Vs(a.data),f=l?d?.size??a.size:a.data.length,p=u?.length??f;if(f>yn||o+30+c.length+p>yn)throw Jl(a.name);let{local:m,central:h}=Hl(c,l?0:8,g,p,f,o);if(ar(r,m),ar(r,c),u)ar(r,u);else{let w=0,b=0;if(zl(a.file,y=>{w+y.length>f||(ar(r,y),w+=y.length,b=Vs(y,b))}),w!==f||b!==g)throw new Error(`${a.name} changed while it was being packed`)}s.push(h,c),o+=m.length+c.length+p}let i=s.reduce((a,c)=>a+c.length,0);if(o+i>yn)throw Wl();for(let a of s)ar(r,a);ar(r,ql(t.length,i,o)),nt.closeSync(r),nt.renameSync(n,e)}catch(s){try{nt.closeSync(r)}catch{}throw nt.rmSync(n,{force:!0}),s}}var Ci=["off","on","retain-on-failure"],_i="trace.zip";async function Zl(e,t){await e.tracing.start({screenshots:!0,snapshots:!0,sources:!1,title:t})}async function Gs(e,t){t&&Dr.mkdirSync(Ai.dirname(t),{recursive:!0}),await e.tracing.stop(t?{path:t}:void 0)}async function Ks(e,t,n){let r;try{r=Dr.mkdtempSync(Ai.join(ah.tmpdir(),"saffron-trace-"));let s=Ai.join(r,_i);await e.tracing.stop({path:s});let o=bh(Dr.readFileSync(s),n);return Ne(t,o),At(o)}catch{try{Dr.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{Dr.rmSync(r,{recursive:!0,force:!0})}catch{console.warn("Could not remove the private temporary trace directory.")}}}async function Ql(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 ch=new Set(["callId","parentId","pageId","frameId","contextId","pageref","_frameref","snapshotName","beforeSnapshot","afterSnapshot","inputSnapshot","sha1","_sha1"]),lh=new Set(["before","action","after"]),dh=/^\[saffron:(?:agent|replay|pending|action):-?\d+\] /,fh=new Set(["type","class","method"]),uh=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__"]),ph=new Set(["style","__playwright_style_sheet_"]),gh=new Set(["srcset","imagesrcset"]),hh=/^(?:image\/(?!svg)|font\/|audio\/|video\/)/i,mh=/\.(?:jpe?g|png|gif|webp|avif|bmp|ico|woff2?|ttf|otf|eot|mp3|mp4|m4a|wav|ogg|webm)$/i,wh=/^text\/css\b/i,yh=/\.css$/i;function bh(e,t){let n=un(t,{encodings:!0});if(n.empty)return e;let r=un(t,{encodings:!0,bytes:!0}),s=Lr(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:_h(t)},a=new Set,c=new Set,l=f=>{for(let p of[f.snapshot?.response?.content,f.snapshot?.request?.postData]){if(!p)continue;let m=p._file??(p._sha1&&`resources/${p._sha1}`);if(!m)continue;let h=String(p.mimeType??"");hh.test(h)?a.add(m):wh.test(h)&&c.add(m)}},d=[...s],u=!1,g=(f,p)=>{p&&(d[f]={name:s[f].name,data:p},u=!0)};return s.forEach((f,p)=>{/\.(?:trace|network)$/.test(f.name)?g(p,vh(f.read(),n,i,f.name.endsWith(".network")?l:void 0)):f.name.endsWith(".stacks")&&g(p,xh(f.read(),n,i))}),s.forEach((f,p)=>{/\.(?:trace|network|stacks)$/.test(f.name)||a.has(f.name)||mh.test(f.name)||g(p,Sh(f.read(),n,r,c.has(f.name)||yh.test(f.name)))}),u?Gl(d):e}function vh(e,t,n,r){let s=e.toString("utf8").split(`
|
|
25
|
+
`),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=Oi(a,t,{keys:!1,numbers:!1,playwright:n});l!==a&&(s[i]=l,o=!0)}return o?Buffer.from(s.join(`
|
|
26
|
+
`),"utf8"):void 0}function xh(e,t,n){let r=e.toString("utf8");if(JSON.parse(r),!t.occursIn(r)&&!t.hiddenByEscape.test(r))return;let s=Oi(r,t,{keys:!1,numbers:!1,playwright:n});return s===r?void 0:Buffer.from(s,"utf8")}function Sh(e,t,n,r=!1){if(r){let d=e.toString("latin1"),u=nd(d,n);return u===d?void 0:Buffer.from(u,"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)?Xl(i,t):void 0,u=d===void 0&&/^\s*(?:[[{"\d-]|true|false|null)/.test(i)&&i.trim().includes(`
|
|
27
|
+
`)?$h(i,t):void 0,g=d??u;if(g!==void 0)return g===i?void 0:Buffer.from(o+g,"utf8")}let c=e.toString("latin1"),l=n.mask(c);return l===c?void 0:Buffer.from(l,"latin1")}function Xl(e,t){try{JSON.parse(e)}catch(n){if(n instanceof SyntaxError)return;throw n}return!t.occursIn(e)&&!t.hiddenByEscape.test(e)?e:Oi(e,t,{keys:!0,numbers:!0})}function $h(e,t){let n=e.split(`
|
|
28
|
+
`),r=[];for(let s of n){if(!s.trim()){r.push(s);continue}let i=Xl(s,t);if(i===void 0)return;r.push(i)}return r.join(`
|
|
29
|
+
`)}var ed=/^([a-z][a-z0-9+.-]*:\/\/)([^/?#]*@)?([^/?#]*)/i;function td(e,t=0,n=e.length){let r=ed.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 kh(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 Rh=e=>e.map(t=>`%7Benv:${t}%7D`).join(""),Th=e=>e.map(t=>`\\{env\\:${t}\\}`).join("");function Pi(e,t,n,r){let s=n.map(([i,a])=>({start:i,end:a,kept:td(e,i,a)})),o=0;return kh(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:Rh,kept:a.kept}:{token:r}})}function Eh(e,t){return td(e)?Pi(e,t,[[0,e.length]],_r):t.mask(e)}var Ah=/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)\s'"]*))|@import\s+(?:"([^"]*)"|'([^']*)')/dgi;function nd(e,t){if(!t.occursIn(e))return e;let n=[...e.matchAll(Ah)].map(r=>r.indices.slice(1).find(s=>s!==void 0));return Pi(e,t,n,Th)}function Ch(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 Pi(e,t,n,_r)}function _h(e){let t=new Map;for(let[n,r]of e)if(!(r.length<Tn||!ed.test(r)||!URL.canParse(r)))for(let s of new URL(r).searchParams.values())s.length>=Tn&&!t.has(s)&&t.set(s,n);return t}var Yl=e=>e===" "||e===" "||e===`
|
|
30
|
+
`||e==="\r";function Oi(e,t,n){let r=[],s=0,o,i=[],a=c=>{let l=c-1;for(;l>=0&&Yl(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),u=a(c)===":"?o:void 0;i.push({dom:(d?.dom??!1)||u==="html",logged:(d?.logged??!1)||u==="value"});continue}if(l==="}"||l==="]"){i.pop();continue}if(l==='"'){let d=c++,u=!1;for(;c<e.length&&e[c]!=='"';c++)e[c]==="\\"&&(u=!0,c++);let g=c+1,f=g;for(;f<e.length&&Yl(e[f]);)f++;let p=e[f]===":",m=u?JSON.parse(e.slice(d,g)):e.slice(d+1,c),h=i.at(-1),w=!p&&a(d)===":"?o:void 0,b=x=>t.mask(x);if(p){if(o=m,!n.keys)continue}else if(n.playwright){if(i.length===1&&w!==void 0&&fh.has(w)||n.playwright.names.has(m))continue;let{pieces:x}=n.playwright;if(b=C=>x.has(C)?_r([x.get(C)]):Eh(C,t),h?.dom){if(a(d)==="["){h.tag=m.toUpperCase();continue}let C=w===void 0?h.tag:i.at(-2)?.tag;if(w!==void 0&&uh.has(w)||w==="src"&&(C==="IFRAME"||C==="FRAME"))continue;w===void 0&&C==="STYLE"||w!==void 0&&ph.has(w)?b=$=>nd($,t):w!==void 0&&gh.has(w)&&(b=$=>Ch($,t))}else if(w!==void 0&&ch.has(w)||w==="phase"&&lh.has(m))continue}let y=n.playwright&&i.length===1&&w==="title"?dh.exec(m)?.[0]??"":"",S=y+b(m.slice(y.length));S!==m&&(r.push(e.slice(s,d),JSON.stringify(S)),s=g)}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 ue(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 zr(e){return Array.isArray(e)?e.map(zr):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,zr(n)])):e}var Ii=e=>JSON.stringify(zr(e));function ji(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))ji(s,t?`${t}.${r}`:r,n);else t&&(n[t]=String(e));return n}function Ph(e,t){let n=ji(zr(e)),r=ji(zr(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 id(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 rd(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 sd=e=>`${e.method??"any"} /${e.urlPattern}/ ${e.status??"2xx"}`+(e.pattern?` with a body matching /${e.pattern}/`:"");function lt(e){let t=rd(e.target),n=e.value??"",r=(()=>{switch(e.action){case"goto":return`go to ${e.url}`;case"click":{let s=[e.clickCount===2?"double ":e.clickCount&&e.clickCount>2?`${e.clickCount}x `:"",e.button&&e.button!=="left"?`${e.button}-`:""].join("");return`${e.modifiers?.length?`${e.modifiers.join("+")}+`:""}${s}click ${t}`}case"fill":return`fill ${t} with "${n}"`;case"press":return t?`press ${n} on ${t}`:`press ${n}`;case"selectOption":return e.clearSelection?`clear the selection in ${t}`:`select ${n.split(`
|
|
31
|
+
`).map(s=>`"${s}"`).join(", ")} 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 ${rd(e.toTarget)}`;case"waitForResponse":return`wait for ${sd(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 ${sd(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 Ur=e=>at.has(e.action);function Oh(e,t){let n=id(e,t,Ii),r=[];for(let s=0;s<n.length;s++){let o=n[s];if(o.before&&o.after){r.push({change:"same",before:lt(o.before),after:lt(o.after),assertion:Ur(o.after)});continue}let i=n[s+1];if(o.before&&i?.after&&!i.before){r.push({change:"changed",before:lt(o.before),after:lt(i.after),details:Ph(o.before,i.after),assertion:Ur(o.before)||Ur(i.after)}),s++;continue}o.before&&r.push({change:"removed",before:lt(o.before),assertion:Ur(o.before)}),o.after&&r.push({change:"added",after:lt(o.after),assertion:Ur(o.after)})}return r}var Ih=e=>`${e.kind}\0${e.gherkin}`;function bn(e,t,n=[]){let r=id(e?.steps??[],t.steps,Ih),s=[],o={added:0,removed:0,changed:0,assertions:0};for(let i of r){let a=i.after??i.before,c=Oh(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=>{let a=t.steps[i.index]?.gherkin??`step ${i.index+1}`;return{index:i.index,from:a,to:i.text,fromStepSet:t.steps[i.index]?.fromStepSet,...kt(a)!==kt(i.text)?{skipped:'it changes which browser session the step runs in (its As "...")'}:{}}})}:{}}}var od=new Set(["goto","click","press","newTab","switchTab","closeTab"]);function ad(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(u=>od.has(u.action)),a=[...t[s].actions.filter(u=>od.has(u.action))],c=[];for(let u of o){let g=a.findIndex(f=>Ii(f)===Ii(u));g>=0?a.splice(g,1):c.push(u)}let l=a;for(let u=c.length-1;u>=0;u--){let g=l.findIndex(f=>f.action===c[u].action);g>=0&&(l.splice(g,1),c.splice(u,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(lt).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(lt).join("; ")}. A page or navigation step may have been added or reordered.`)}return n}function Ys(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}`),i.skipped&&t.push(` (accept skips this edit: ${i.skipped})`)}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=>ue(i,1/0)).join(`
|
|
32
|
+
`)}var Bi=e=>new Promise(t=>setTimeout(t,e)),Fi=class{entries=[];lastMatch;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}).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 Nh(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 cd(e,t,n,r,s){return!(!t.test(e.url)||n&&e.method.toUpperCase()!==n.toUpperCase()||!Nh(e.status,r)||s&&(e.body===void 0||!s.test(e.body)))}var Mh=(e,t)=>`response matching ${e.method??"any-method"} /${t}/ status ${e.status??"2xx"}${e.pattern?` body /${e.pattern}/`:""}`,ld=new Set(["click","fill","press","selectOption","check","uncheck","hover","dragTo","uploadFile"]),fd=/(?<=(?:^|[^\\])(?:\\\\)*)(\\?)(<[^<>]+>|\{(?:env|data|date)[^{}]*\})/g;function Ct(e,t,n,r){return e===void 0||e.trim()===""?!1:t.trim()===""?!0:r!==void 0&&r.test("")&&r.test("\u2063zq9")&&[...e.matchAll(fd)].some(({2:s,index:o})=>{let i=e.slice(Math.max(0,o-2),o);return!(s.startsWith("<")&&(i==="(?"||i==="\\k"))&&n(s).trim()===""})}var Lt=(e,t)=>new Error(`${e} "${t}" is empty for this row, so it would hold for anything. Give that cell or data value a value, or give the check its own Scenario.`);function ud(e,t,n){return Ec(Es(Ar(It(En(e,t))),n))}function Hr(e,t,n,r=!1){return e.replace(fd,(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 dd(e,t,n,r=!1,s=!0,o=new Set){let i=u=>ud(u,n,o);for(let u of["name","text","label","placeholder","testId"])if(Ct(t[u],i(t[u]??""),i))throw Lt(`The target's ${u}`,t[u]);if(t.role&&t.nameRegex!==void 0){let u=Hr(t.nameRegex,i,we.pattern,!0);if(Ct(t.nameRegex,u,i,new RegExp(u,"i")))throw Lt("The target's name",t.nameRegex)}let a=u=>u.split(">>").map(g=>g.trim().startsWith("internal:")?g:g.replace(/(\[\s*[\w-]+\s*=\s*)(["'])((?:(?!\2)[^\\]|\\.)*)\2(\s*[is]?\s*\])/g,"$1$2$2$4")).join(">>");for(let u of[...t.fallbackSelectors??[],...t.frame?[t.frame]:[]]){let g=a(u);Cn(g,(m,h)=>{let w=Hr(m,i,we[h],h==="regex"),b;try{b=h==="regex"?new RegExp(w):void 0}catch{}if(Ct(m,w,i,b))throw Lt("The text in selector",u);return m},m=>m);let f=[...g.matchAll(/'((?:[^'\\]|\\.)*)'/g)].map(m=>m[1]),p=g.split(">>").flatMap(m=>m.trim().match(/^(?:internal:)?text=(?!["/])(.*)$/s)?.[1]??[]);for(let m of[...f,...p])if(Ct(m,i(m),i))throw Lt("The text in selector",u)}let c=[],l=u=>Cn(u,(g,f)=>Hr(g,i,we[f],f==="regex"),i),d=u=>{if(t.role){let g=t.nameRegex?new RegExp(Hr(t.nameRegex,i,we.pattern,!0),"i"):t.name?i(t.name):void 0,f=t.role;g===void 0&&!!(t.label||t.placeholder||t.text||t.testId||t.fallbackSelectors?.length)?t.text&&c.push(u.getByRole(f).filter({hasText:i(t.text)})):typeof g=="string"?(c.push(u.getByRole(f,{name:g,exact:!0})),s&&c.push(u.getByRole(f,{name:g,exact:!1}))):c.push(u.getByRole(f,{name:g,exact:!1}))}t.label&&c.push(u.getByLabel(i(t.label))),t.placeholder&&c.push(u.getByPlaceholder(i(t.placeholder))),t.text&&!t.role&&c.push(u.getByText(i(t.text))),t.testId&&c.push(u.getByTestId(i(t.testId)));for(let g of t.fallbackSelectors??[])c.push(u.locator(l(g)))};if(t.frame)d(e.frameLocator(l(t.frame)));else if(d(e),r)for(let u of e.frames())u!==e.mainFrame()&&d(u);if(c.length===0)throw new Error("Action target has neither role nor fallback selectors");return c}var pd=100;async function Fh(e,t,n,r){let s=Date.now()+t,o;for(;Date.now()<s;){try{if(await e())return}catch(i){o=i}await Bi(r)}throw new Error(`Timed out waiting for ${n}${o?` (${String(o)})`:""}`)}async function Bt(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 Bh=20,yt=e=>e.replace(/\s+/g," ").trim(),qr=new WeakMap;function Qs(e,t=!1){if(!e.isConnected)return{text:"",pieces:[],kept:!1};let n=e.ownerDocument,r=n.defaultView,s=w=>r.getComputedStyle(w),o=w=>w.checkVisibility?.({contentVisibilityAuto:!1,visibilityProperty:!1,opacityProperty:!1})??w.getClientRects().length>0,i=w=>w.replace(/\s+/g," ").trim(),a=new Set,c=w=>{w&&a.add(w)},l=n.createRange(),d=!1,u=!1;for(let w=e.parentElement;w&&!u;w=w.parentElement)u=s(w).contentVisibility==="auto";let g=(w,b,y,S)=>{if(w.tagName==="BR")return["",`
|
|
33
|
+
`,""];if(w.tagName==="TEXTAREA"){let O=b.visibility==="visible"?String(w.value??""):"";return[O,O,t?i(O):""]}let x=b.visibility!=="visible"||b.contentVisibility==="hidden"||w.tagName==="DETAILS"&&!w.open,C=/^(pre|pre-wrap|pre-line|break-spaces)$/.test(b.whiteSpace),$=S||b.contentVisibility==="auto",k="",R="",_="",v=0;for(let O of Array.from(w.childNodes)){if(O.nodeType===3){if(x)continue;let F=O.nodeValue??"",z=/\S/.test(F);if(z&&!y){l.selectNodeContents(O);let L=!!w.shadowRoot||/^(CANVAS|VIDEO|AUDIO|OBJECT|IFRAME)$/.test(w.tagName);if(l.getClientRects().length===0&&(!$||L))continue}let N=F.replace(/[ \t\n\r\f]+/g," ");C?z&&F!==N&&(d=!0):F=N,k+=F,R+=F,z&&(v+=2);continue}if(O.nodeType!==1)continue;let P=s(O);if(P.display==="none"||y&&O.hidden||!y&&P.display!=="contents"&&!o(O))continue;let[E,T,M]=g(O,P,y||O.tagName==="SELECT",$);k+=E;let I=O.tagName!=="OPTION"&&/^(inline|contents)/.test(P.display);R+=I?T:`
|
|
34
|
+
${T}
|
|
35
|
+
`,!(!t||!M)&&(v++,_=M,I&&T.includes(`
|
|
36
|
+
`)&&(c(i(T.slice(0,T.indexOf(`
|
|
37
|
+
`)))),c(i(T.slice(T.lastIndexOf(`
|
|
38
|
+
`)+1)))))}if(!t)return[k,R,""];let A=v===1?_:i(R);return c(A),[k,R,A]},f=e.closest("select"),p;if(f){p=f.getClientRects().length>0&&o(f);for(let w=e;p&&w!==f;w=w.parentElement)(w.hidden||s(w).display==="none")&&(p=!1)}else{let w=e;for(;w&&s(w).display==="contents";)w=w.parentElement;p=!w||o(w)}if(!p)return{text:"",pieces:[],kept:!1};let[m,h]=g(e,s(e),!!f,u);if(t)for(let w of h.split(`
|
|
39
|
+
`))c(i(w));return{text:m,pieces:[...a],kept:d}}function Lh(e,[t,n]){let r=(0,eval)("("+n+")"),s=a=>{for(let c=a;c;c=c.parentElement??c.getRootNode().host)if(c.hidden||c.ownerDocument.defaultView.getComputedStyle(c).display==="none")return!0;return!1},o=a=>String(a.textContent??"").replace(/\s+/g," ").trim(),i=a=>s(a)||o(a)!==""&&!/\S/.test(r(a).text);if(e.length===0||!i(e[0]))return 0;for(let a=1;a<Math.min(e.length,t);a++)if(!i(e[a]))return o(e[a])===o(e[0])?a:0;return 0}async function Ni(e,t){let{text:n,kept:r}=await e.evaluate(Qs,!1,t);if(/\S/.test(n)||await e.isVisible())return{text:n,kept:r}}async function Xs(e,t,n,r,s,o=new Map,i,a=pd,c=new Set){let l=($,k,R)=>Fh($,k,R,a),d=qr.get(e);if(d&&ld.has(t.action)&&t.action!=="uploadFile"){qr.delete(e);let $,k=_=>{$??=_};e.on("filechooser",k);let R;try{if(R=await Xs(e,t,n,r,s,o,i,a,c),$||await e.waitForEvent("filechooser",{timeout:r}).then(k,()=>{}),!$)throw new Error(`uploadFile failed: the ${t.action} after it opened no file chooser within ${r} ms`);try{await $.setFiles(d,{timeout:r})}catch(_){throw new Error(`uploadFile failed: ${_ instanceof Error?_.message:String(_)}`)}}catch(_){throw qr.set(e,d),_}finally{e.off("filechooser",k)}return R}o.has(wt)||o.set(wt,wn());let u=o.get(wt),g=$=>typeof $=="string"?jn($,u):Array.isArray($)?$.map(g):$&&typeof $=="object"?Object.fromEntries(Object.entries($).map(([k,R])=>[k,g(R)])):$;t=g(t),n=g(n);let f=$=>ud($,n,c),p=$=>Hr($,f,we.pattern,!0),m=t.value!==void 0?f(t.value):void 0,h=t.url!==void 0?f(t.url):void 0,w=t.action==="expectVisible"||t.action==="expectText"||t.action==="expectValue"||t.action==="expectMatches"||t.action==="expectAttribute"||t.action==="expectEach"||t.action==="expectDiffers"||t.action==="captureText",b=t.target?dd(e,t.target,n,w,!ld.has(t.action),c):[],y={timeout:r},S={timeout:Math.min(1e3,r)},x=async $=>{let k=await $.evaluateAll(Lh,[Bh,Qs.toString()]);return k>0?$.nth(k):$.first()},C=$=>async()=>{for(let k of b)try{if(await $(await x(k)))return!0}catch{}return!1};switch(t.action){case"goto":{if(!h)throw new Error("goto requires url");let $=Br(h);if($)throw new Error($);await e.goto(Si(h,s),y);return}case"click":{let{clickCount:$,button:k,modifiers:R}=t,_={...y,clickCount:$,button:k,modifiers:R};return Bt(b,v=>v.click(_),!0)}case"fill":return Bt(b,$=>$.fill(m??"",y),!0);case"press":return b.length>0?Bt(b,$=>$.press(m??"",y),!0):e.keyboard.press(m??"");case"selectOption":return Bt(b,async $=>{if(t.clearSelection){await $.selectOption([],y);return}let k=(m??"").split(`
|
|
40
|
+
`);await $.selectOption(k.length>1?k:k[0],y)},!0);case"check":return Bt(b,$=>$.check(y),!0);case"uncheck":return Bt(b,$=>$.uncheck(y),!0);case"hover":return Bt(b,$=>$.hover(y),!0);case"waitFor":return b.length>0?Bt(b,$=>$.waitFor({state:"visible",timeout:r})):Bi(Math.min(Number(m??"0"),r));case"expectVisible":return l(C($=>$.isVisible()),r,"target to be visible");case"expectNotVisible":return l(async()=>{for(let $ of b){let k=await $.count();for(let R=0;R<k;R++)if(await $.nth(R).isVisible())return!1}return!0},r,`every match of every recorded locator to be hidden (${b.length} locator(s))`);case"expectText":return l(C(async $=>{let k=await Ni($,S);return k===void 0?yt(m??"")==="":yt(m??"")===""?yt(k.text)==="":yt(k.text).includes(yt(m??""))||k.kept&&k.text.includes(m??"")}),r,`text "${m}"`);case"expectEach":{let $=(t.each!==void 0?En(t.each,n):void 0)?.match(/^\{data:([^}]+)\}$/)?.[1];if(!$)throw new Error(`expectEach needs a {data:...} list reference, got ${JSON.stringify(t.each)}`);let k=fn($),R=async v=>{let{pieces:A}=await v.evaluate(Qs,!0,S),O=new Set(A.map(P=>P.toLowerCase()));if(await v.isVisible())for(let P of(await v.innerText(S)).split(`
|
|
41
|
+
`))O.has(yt(P).toLowerCase())&&A.push(yt(P));return new Set(A)},_=k;return l(async()=>{for(let v of b)try{let A=await R(await x(v)),O=k.filter(P=>!A.has(P.replace(/\s+/g," ").trim()));if(O.length<_.length&&(_=O),O.length===0)return!0}catch{}return!1},r,`every value of ${t.each} to be shown`).catch(()=>{throw new Error(`${_.map(v=>`"${v}"`).join(", ")} from ${t.each} ${_.length===1?"is":"are"} not shown in the target (${k.length-_.length} of ${k.length} found)`)})}case"expectValue":return l(C(async $=>await $.inputValue(S)===(m??"")),r,`input value "${m}"`);case"expectUrl":{let $=h??m??"";if($.trim()==="")throw Lt("The expected URL",t.url??t.value??"");return l(async()=>e.url().includes($),r,`URL containing "${$}" on the active page (${e.url()})`)}case"handleDialog":{let $=(m??"accept")!=="dismiss",k=t.promptText?f(t.promptText):void 0;e.once("dialog",R=>{$?R.accept(k):R.dismiss()});return}case"uploadFile":{let $=Ve().root,k=(m??"").split(`
|
|
42
|
+
`).filter(Boolean).map(_=>jh.resolve($,_));if(k.length===0)throw new Error("uploadFile requires a path");let R=Ti(k,$);if(R)throw new Error(R);if(b.length>0)return Bt(b,_=>_.setInputFiles(k,y),!0);qr.set(e,k);return}case"dragTo":{if(!t.toTarget)throw new Error("dragTo requires toTarget");let $=dd(e,t.toTarget,n,!1,!1,c);return Bt(b,k=>k.dragTo($[0].first(),y),!0)}case"captureText":{if(!t.saveAs)throw new Error("captureText requires saveAs");return l(C(async $=>{let k=yt((await Ni($,S))?.text??"");return k===""?!1:(o.set(t.saveAs,k),!0)}),r,`non-empty text to capture as "${t.saveAs}"`)}case"expectDiffers":{if(!t.compareTo)throw new Error("expectDiffers requires compareTo");let $=o.get(t.compareTo);if($===void 0)throw new Error(`expectDiffers: no captured value named "${t.compareTo}"`);if(b.length>0){let _;try{return await l(async()=>{for(let v of b){let A=_;try{if(A??=await(await x(v)).elementHandle(S)??void 0,!A)continue;let O=yt((await A.evaluate(Qs,!1)).text);if(O===""){if(_)return!1;continue}return _=A,O!==$}catch{if(_)return!1}finally{A&&A!==_&&await A.dispose().catch(()=>{})}}return!1},r,`target text to differ from "${t.compareTo}" (${$})`)}finally{await _?.dispose().catch(()=>{})}}let k=m??"",R=o.get(k);if(R===void 0)throw new Error(`expectDiffers: no captured value named "${k}"`);if(R===$)throw new Error(`expectDiffers: "${k}" (${R}) equals "${t.compareTo}" (${$})`);return}case"expectAttribute":{if(!t.attribute)throw new Error("expectAttribute requires attribute");if(!t.pattern)throw new Error("expectAttribute requires pattern");let $=p(t.pattern),k=new RegExp($,"i"),R=f(t.attribute);if(Ct(t.attribute,R,f))throw Lt("The attribute name",t.attribute);let _=Ct(t.pattern,$,f,k),v=k.test("")&&k.test("false")&&!k.test("true");return l(C(async A=>{let O=await A.getAttribute(R,S);return _?(O??"").trim()==="":O===null?v:k.test(O)}),r,`attribute ${R} to match /${t.pattern}/i`)}case"expectMatches":{if(!t.pattern)throw new Error("expectMatches requires pattern");let $=p(t.pattern),k=new RegExp($,"i"),R=yt($)===""||Ct(t.pattern,$,f,k);return l(C(async _=>{let v=await Ni(_,S);return v===void 0?R:R?yt(v.text)==="":k.test(yt(v.text))||v.kept&&k.test(v.text)}),r,`target text to match /${t.pattern}/i`)}case"switchTab":{let $=Number.parseInt(m??"",10),k=()=>e.context().pages().filter(_=>!_.isClosed());await l(async()=>k().length>$,r,`tab ${m} to exist (${k().length} open: ${k().map(_=>_.url()).join(", ")})`);let R=k()[$];return await R.bringToFront(),R}case"closeTab":{let $=e.context().pages().filter(_=>!_.isClosed()),k=m===void 0?e:$[Number.parseInt(m,10)];if(!k)throw new Error(`tab ${m} does not exist (${$.length} open)`);await k.close();let R=e.context().pages().filter(_=>!_.isClosed());if(R.length===0)throw new Error("closed the last tab; nothing left to drive");return R[R.length-1]}case"newTab":{let $=h?Br(h):void 0;if($)throw new Error($);let k=await e.context().newPage();return h&&await k.goto(Si(h,s),y),k}case"waitForResponse":case"expectResponse":{if(!t.urlPattern)throw new Error(`${t.action} requires urlPattern`);let $=p(t.urlPattern),k=new RegExp($),R=t.status!==void 0?f(t.status):void 0,_=t.method!==void 0?f(t.method):void 0,v=t.pattern?p(t.pattern):void 0,A=v!==void 0?new RegExp(v):void 0;if(Ct(t.urlPattern,$,f,k))throw Lt("The response URL pattern",t.urlPattern);if(Ct(t.status,R??"",f))throw Lt("The response status",t.status);if(Ct(t.method,_??"",f))throw Lt("The response method",t.method);if(A&&Ct(t.pattern,v,f,A))throw Lt("The response body pattern",t.pattern);if(!i){await e.waitForResponse(async P=>{let E={seq:0,url:P.url(),method:P.request().method(),status:P.status()};if(!cd(E,k,_,R,void 0))return!1;if(!A)return!0;let T=await P.text().catch(()=>{});return T!==void 0&&A.test(T)},y);return}let O=()=>t.action==="expectResponse"?i.all():i.sincePreviousStep();return l(async()=>{let P=O().find(E=>cd(E,k,_,R,A));return P&&(i.lastMatch=P),P!==void 0},r,Mh({...t,status:R,method:_},t.urlPattern))}default:throw new Error(`Unknown action type: ${t.action}`)}}var Zs=(e,t)=>Rt(e.actions,t);function Dh(e,t){let n=e.examples;return n?e.steps.some(r=>r.actions.some(s=>Qt(s).some(o=>o!==void 0&&[...o.matchAll(/\{data:([^{}]*<[^<>{}]+>[^{}]*)\}/g)].some(([,i])=>i.replace(/<([^<>]+)>/g,(a,c)=>n[c]??"\0")===t)))):!1}var Mi=(e,t)=>Xt(e.actions,t);function cr(e,t){if(!t.rowBound?.length||!t.examples||t.steps.length!==e.steps.length||t.steps.some((h,w)=>h.gherkin!==e.steps[w].text||h.kind!==e.steps[w].kind)||t.steps.some((h,w)=>JSON.stringify(h.table??null)!==JSON.stringify(e.steps[w].table??null)||(h.docString??null)!==(e.steps[w].docString??null))&&!lr(e,t))return;let r=t.rowBound.filter(h=>h.column in e.params),s=Nr([...new Set(r.map(h=>h.column))],t.examples,e.params,t.recordedAt,t.data);if(s===void 0){let h=r.find(y=>y.valueSha!==void 0&&er(e.params[y.column])!==y.valueSha);if(!h)return;let{keyword:w,gherkin:b}=t.steps[h.step];return`This Outline was recorded with ${h.column} as ${t.examples[h.column]}, which resolves to another value now (or is not set), and step ${h.step+1} ("${w?`${w.trim()} `:""}${b}") still holds the value it had, so the recording cannot check this row. Record the Outline again with saffron run --rerecord.`}let{step:o,reason:i}=r.find(h=>h.column===s),a=t.examples[s],c=`this row, where ${s} is "${e.params[s]}"`,{keyword:l,gherkin:d}=t.steps[o],u=`step ${o+1} ("${l?`${l.trim()} `:""}${d}")`,g=d.includes(`<${s}>`),f=[...new Set(r.map(h=>h.column))],m=(e.exampleRows??[]).every(h=>Nr(f,t.examples,h,t.recordedAt,t.data)!==void 0)?` No Examples row has ${s} "${a}" any more: record the Outline again with saffron run --rerecord.`:" Or record the Outline again on another row with saffron run --rerecord.";return(i==="list"?`This Outline was recorded on the row where ${s} is "${a}", and ${u} holds other rows' ${s} values too, so one recording cannot check ${c}. Give that check its own Scenario, or give the text it holds an Examples column of its own and write that column in the step.`:i==="reads"?`This Outline was recorded on the row where ${s} is "${a}", and ${u} checks a response status, method or attribute against what a {data:...} reference keyed by <${s}> reads on that row, so one recording cannot check ${c}. Give the expected value an Examples column of its own and name it in that step, or give that check its own Scenario.`:i==="value"?`This Outline was recorded on the row where ${s} is "${a}", and ${u} checks "${a}" as a response status, method or attribute without naming <${s}>, so one recording cannot check ${c}. If that check follows the row, name <${s}> in that step; if the value only coincides, give the check its own Scenario.`:i==="data"?`This Outline was recorded on the row where ${s} is "${a}", and ${u} reads a {data:...} entry that more than one of the Outline's {data:...} references chose on that row, so one recording cannot check ${c}. Write the {data:...} reference that step needs in its own text, or give that check its own Scenario.`:g?`This Outline was recorded on the row where ${s} is "${a}", and ${u} holds "${a}" spelled otherwise or inside other text (an attribute's name, a {data:...} path), where <${s}> cannot follow the row, so one recording cannot check ${c}. Spell the value as the cell does, give it an Examples column of its own, or give that check its own Scenario.`:`This Outline was recorded on the row where ${s} is "${a}", and ${u} writes "${a}" inside other text without naming <${s}>, so one recording cannot check ${c}. Put <${s}> in that step, or give that check its own Scenario.`)+m}function lr(e,t){if(t.steps.length!==e.steps.length)return!1;let n=t.examples?[t.examples]:Object.keys(e.params).length>0?e.exampleRows??[]:[];for(let[r,s]of Object.entries(t.data??{})){let o;try{o=Je(r)}catch{continue}if(o===s)continue;let i=t.steps.some(c=>Zs(c,`{data:${r}}`))||Dh(t,r),a=t.steps.some(c=>Mi(c,s));if(!i||a)return!1}return t.steps.every((r,s)=>{let o=e.steps[s];if(r.gherkin!==o.text||r.kind!==o.kind)return!1;if(n.length>0){let c=[o.text,...o.table?.flat()??[],o.docString??""].join(`
|
|
43
|
+
`);if(n.some(l=>Pn(r.actions,c,l,e.params,t.recordedAt)))return!1}let i=r.table,a=o.table;if(!!i!=!!a)return!1;if(i&&a){let c=Object.keys(ze(i)),l=Object.keys(ze(a));if(c.length>0&&l.length>0){if(JSON.stringify(c)!==JSON.stringify(l))return!1;let d=ze(i),u=ze(a);for(let g of c){if(d[g]===u[g])continue;let f=`<${g}>`,p=t.steps.some(h=>Zs(h,f)),m=t.steps.some(h=>Mi(h,d[g]));if(!p||m)return!1}}else if(JSON.stringify(i)!==JSON.stringify(a))return!1}if(r.docString!==void 0!=(o.docString!==void 0))return!1;if(r.docString!==void 0&&o.docString!==void 0&&r.docString!==o.docString){let c=t.steps.some(d=>Zs(d,"<docstring>")),l=t.steps.some(d=>Zs(d,r.docString)||Mi(d,r.docString));if(!c||l)return!1}return!0})}function Li(e,t){let n=e.steps[t],r=n?.resolvedTable??n?.table;return{...e.params,...pn(e.steps),...ze(r),...An(n?.resolvedDocString??n?.docString)}}async function Vr(e,t,n,r={}){let s=r.actionTimeoutMs??5e3,o=r.retries??1,i=Math.max(10,r.pollIntervalMs??pd),a=[],c=r.envNames??We(t),l=r.vars??new Map;r.uniqueSeed&&l.set(wt,r.uniqueSeed);let d=()=>Object.fromEntries(l),u=n.steps.some(v=>v.actions.some(A=>(A.action==="waitForResponse"||A.action==="expectResponse")&&A.pattern!==void 0)),g=r.sessions??new Map;g.set(de(t.steps[0]?.session),e);let f=new Map,p=v=>{let A=v.context();for(let T of A.pages())qr.delete(T);let O=new Fi;O.attach(A,u);let P=[],E=T=>P.push(T);return A.on("page",E),{context:A,active:v,seen:new Set(A.pages()),opened:P,onPage:E,netLog:O}},m=async v=>{let A=f.get(v);if(A)return A;let O=g.get(v);if(!O||O.isClosed()){if(!r.openSession)throw new Error(`browser session "${v}" cannot be opened in this replay`);O=await r.openSession(v),g.set(v,O)}let P=p(O);return f.set(v,P),P},h=await m(de(t.steps[0]?.session)),w=!1,b=()=>(w=r.keepResponseLog===!0,w?{responses:h.netLog}:{}),y=()=>{for(let[v,A]of f)A.active.isClosed()||g.set(v,A.active);return{activePage:h.active.isClosed()?void 0:h.active,sessions:g}},S=v=>new Promise(A=>{let O=h.context,P=()=>{clearTimeout(E),O.off("page",P),A()},E=setTimeout(P,v);O.on("page",P)}),x=[],$=!n.steps.some(v=>v.actions.some(A=>A.opensTab))&&n.steps.some(v=>v.actions.some(A=>A.action==="switchTab"||A.action==="closeTab"||A.action==="newTab")),k=()=>{let v=h.context.pages();for(let A of v)h.seen.has(A)||(h.seen.add(A),A.isClosed()||(h.active=A));if(h.active.isClosed()){let A=v.filter(O=>!O.isClosed());A.length>0&&(h.active=A[A.length-1])}},R=()=>{for(let v of f.values())v.context.off("page",v.onPage),w&&v===h||v.netLog.detach()};if(!lr(t,n))return R(),{status:"stale",stepResults:a,captured:d()};let _=v=>{for(let A=v+1;A<n.steps.length;A++)a.push({gherkin:n.steps[A].gherkin,kind:n.steps[A].kind,status:"skipped"})};try{for(let v=0;v<n.steps.length;v++){let A=n.steps[v],O=Li(t,v),P=!1,E=0,T=[],M=[];try{h=await m(de(t.steps[v]?.session))}catch(N){let L=`Could not open browser session "${Ge(de(t.steps[v]?.session))}": ${N instanceof Error?N.message.split(`
|
|
44
|
+
`)[0]:String(N)}`;return a.push({gherkin:A.gherkin,fromStepSet:A.fromStepSet,kind:A.kind,status:"failed",error:L}),_(v),{status:"failed",failure:{stepIndex:v,actionIndex:0,stepText:A.gherkin,kind:A.kind,error:L},stepResults:a,captured:d(),tabOpeners:x,...y(),activePage:void 0}}for(let N of f.values())N.netLog.markStep();let I=(N,L)=>{let G=h.context.pages().filter(Z=>!Z.isClosed()),U=G.filter(Z=>!L.has(Z)).at(-1),Y=U??h.active;if(Y===N||Y.isClosed())return;let V=U?"opened":N.isClosed()?"closed":"switched";T.push({how:V,tab:G.indexOf(Y)+1,url:Y.url()})},F=h.context;r.trace&&await F.tracing.group(`[saffron:${r.tracePhase??"replay"}:${v+(r.traceStepOffset??0)}] ${A.keyword} ${A.gherkin}`).catch(()=>{});let z=async()=>{r.trace&&await F.tracing.groupEnd().catch(()=>{})};try{if(A.kind==="assertion"&&!A.actions.some(N=>at.has(N.action))){let N=`Assertion step "${A.gherkin}" recorded ${A.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.`;return a.push({gherkin:A.gherkin,fromStepSet:A.fromStepSet,kind:A.kind,status:"failed",drift:P,error:N}),_(v),{status:"failed",failure:{stepIndex:v,actionIndex:0,stepText:A.gherkin,kind:A.kind,error:N},stepResults:a,captured:d(),tabOpeners:x,...y(),...b()}}for(let N=0;N<A.actions.length;N++){let L=A.actions[N];k();let G=h.active,U=new Set(h.context.pages());h.netLog.lastMatch=void 0,L.pageFingerprint&&await qs(h.active)!==L.pageFingerprint&&(P=!0);let Y,V=!1;for(let Z=0;Z<=o&&!V;Z++){Z>0&&(E++,await Bi(250*Z),k());try{let oe=Z>0?`${lt(L)} (attempt ${Z+1})`:lt(L),ve=await Ql(h.active,r.trace,`[saffron:action:${N}] ${oe}`,()=>Xs(h.active,L,O,s,r.baseURL,l,h.netLog,i,c));ve&&(h.active=ve,h.seen.add(ve));let qt=L.action==="click"||L.action==="press";if(h.opened.length===0&&L.opensTab?await h.context.waitForEvent("page",{timeout:s}).catch(()=>{}):h.opened.length===0&&qt&&$&&await S(150),L.opensTab&&h.opened.length===0)throw new Error("this action opened a new tab when it was recorded, and none opened now; the flow has changed");h.opened.length>0&&x.push({stepIndex:v,actionIndex:N});let gt=L.action==="click"&&((L.modifiers?.length??0)>0||L.button==="middle");for(;h.opened.length>0;){let Re=h.opened.shift();gt&&h.seen.add(Re),await Re.waitForLoadState("domcontentloaded",{timeout:s}).catch(()=>{})}V=!0,I(G,U);let rt=h.netLog.lastMatch;rt&&(L.action==="waitForResponse"||L.action==="expectResponse")&&M.push({action:L.action,method:rt.method,url:rt.url,status:rt.status})}catch(oe){Y=oe}}if(!V){let Z=Y instanceof Error?Y.message:String(Y);a.push({gherkin:A.gherkin,fromStepSet:A.fromStepSet,kind:A.kind,status:"failed",drift:P,...E?{retries:E}:{},...T.length?{tabs:T}:{},...M.length?{responses:M}:{},failedActionIndex:N,error:Z}),_(v);let oe={stepIndex:v,actionIndex:N,stepText:A.gherkin,kind:A.kind,error:Z,pageUrl:h.active.isClosed()?void 0:h.active.url()};return await r.onFailure?.(h.active,oe).catch(()=>{}),{status:"failed",failure:oe,stepResults:a,captured:d(),tabOpeners:x,...y(),...b()}}}a.push({gherkin:A.gherkin,fromStepSet:A.fromStepSet,kind:A.kind,status:"passed",drift:P,...E?{retries:E}:{},...T.length?{tabs:T}:{},...M.length?{responses:M}:{}})}finally{await z()}}return{status:"passed",stepResults:a,captured:d(),tabOpeners:x,...y()}}finally{R()}}import{createHash as Uh}from"node:crypto";import zh from"node:path";var Di=e=>Uh("sha1").update(JSON.stringify(e)).digest("hex").slice(0,16);function gd(e){return{steps:e.steps.map(t=>({...t,actions:t.actions.map(({pageFingerprint:n,...r})=>r)})),data:e.data??null,...e.examples?{examples:e.examples}:{},...e.rowBound?{rowBound:e.rowBound}:{}}}var hd=e=>Di(e.map(t=>[t.kind,t.text,t.table??null,t.docString??null])),Jr=e=>e?Di(gd(e)):"none",md=(e,t)=>Di({contract:gd(e),featureEdits:t??null});function wd(e,t,n,r){return{scenario:hd(e.steps),committed:Jr(t),recording:md(n,r)}}function dt(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=Ze(zh.join(e,o),e,n).find(l=>l.name===i)}catch(l){s.push(`${o} no longer parses: ${l instanceof Error?l.message.split(`
|
|
45
|
+
`)[0]:String(l)}`)}s.length||(a?hd(a.steps)!==r.scenario&&s.push(Hh(a,t.cache)):s.push(`scenario "${i}" is no longer in ${o}`));let c;try{c=He(fe(e,o,i))}catch(l){if(!(l instanceof ge))throw l;return s.push(`the committed recording cannot be read (${l.problem})`),s.join("; ")}return Jr(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"),md(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 Hh(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 eo="not bound: filed by a runner older than 0.8.5, so changes since cannot be detected";import Fn from"node:fs";import vd from"node:path";function to(e){return`$${e.toFixed(e>=1?2:4)}`}function Ui(e,t){let n=e===void 0?"?":`${Math.round(e)}%`,r=t===void 0?"?":`${Math.round(t)}%`;return`${n} \u2192 ${r}`}function ft(e){return e.costUsd>0||e.aiCalls===0}function zi(e){return ft(e)?e.plan?` \xB7 5-hour window ${Ui(e.plan.fiveHourBefore,e.plan.fiveHourAfter)} (${e.plan.subscriptionType} plan) \xB7 \u2248 ${to(e.costUsd)} at API rates`:` \xB7 ${to(e.costUsd)}`:" \xB7 cost not reported by the provider"}function yd(e,t){return e?t?`\u2248 ${to(e)}`:to(e):""}function bd(e){if(!e)return"";let t=new Date(e);return Number.isNaN(t.getTime())?"":`resets ${t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`}function Hi(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 Wr=e=>e.status==="yellow"&&e.verified===!1,qi=(e,t)=>e.green+e.yellow-t.filter(Wr).length;function Nn(e,t){let n=e.green+e.yellow+e.red;return n===0?0:Math.round(qi(e,t)/n*100)}function Mn(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 xd(e,t){return e.feature===t.feature&&e.scenario===t.scenario&&(e.browser===void 0||t.browser===void 0||e.browser===t.browser)}function Ji(e){let t=r=>`${r.feature}\0${r.scenario}`,n=new Map;for(let r of e)r.browser&&n.set(t(r),(n.get(t(r))??new Set).add(r.browser));return r=>{let s=[...n.get(t(r))??[]];return s.length<2?[{key:t(r)}]:(r.browser?[r.browser]:s).map(o=>({key:`${t(r)}\0${o}`,browser:o}))}}function Wi(e){return vd.join(e,".saffron","history.jsonl")}function Gi(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(`
|
|
46
|
+
`)[0],browser:o.browser}));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 Ki(e,t){let n=Wi(e);Fn.mkdirSync(vd.dirname(n),{recursive:!0}),Fn.appendFileSync(n,`${JSON.stringify(t)}
|
|
47
|
+
`)}function Sd(e,t){let n=Wi(e);if(!Fn.existsSync(n))return Ki(e,t);let r=Fn.readFileSync(n,"utf8").split(`
|
|
48
|
+
`).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)),Fn.writeFileSync(n,`${o.join(`
|
|
34
49
|
`)}
|
|
35
|
-
`)}function
|
|
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
|
|
37
|
-
<path d="${
|
|
38
|
-
<path d="${
|
|
39
|
-
</svg>`}function
|
|
50
|
+
`)}function Gr(e,t=50){let n=Wi(e);if(!Fn.existsSync(n))return[];let r=Fn.readFileSync(n,"utf8").trim().split(`
|
|
51
|
+
`).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 Vi=e=>Nn(e,e.scenarios);function Yi(e,t){let n=e.filter(f=>!f.partial),r=[...n,t],s=r.slice(-20),o=r.slice(-10),i=n.at(-1),a=i?{passRatePp:Vi(t)-Vi(i),costUsd:ft(t)&&ft(i)?t.costUsd-i.costUsd:void 0,aiCalls:t.aiCalls-i.aiCalls,red:t.red-i.red}:void 0,c=new Map,l=Ji(o.flatMap(f=>f.scenarios));for(let f of o)for(let p of f.scenarios)for(let{key:m,browser:h}of l(p)){let w=c.get(m)??{feature:p.feature,scenario:h?`${p.scenario} [${h}]`:p.scenario,heals:0,reds:0,runs:0};w.runs++,p.source==="agent-heal"&&p.status==="yellow"&&w.heals++,p.status==="red"&&w.reds++,c.set(m,w)}let d=[...c.values()].filter(f=>f.heals>=2||f.reds>=3).sort((f,p)=>p.heals+p.reds-(f.heals+f.reds)),u=new Map;for(let f of s)for(let p of f.scenarios)p.status==="red"&&p.error&&u.set(p.error,(u.get(p.error)??0)+1);let g=[...u.entries()].sort((f,p)=>p[1]-f[1]).slice(0,3).map(([f,p])=>({message:f,count:p}));return{prev:a,series:{passRate:s.map(Vi),costUsd:s.map(f=>ft(f)?Number(f.costUsd.toFixed(4)):null),aiCalls:s.map(f=>f.aiCalls)},chronic:d,divergentSteps:t.divergentSteps,topIssues:g}}var $d=20,qh=10,Vh=e=>e.scenarios.filter(Wr).length,Rd=e=>e.replace(/\\/g,"/"),dr=(e,t)=>`${Rd(e)}\0${t}`,Jh=(e,t)=>t===0?0:Math.round(e/t*100),kd=e=>Math.max(0,Date.parse(e.finishedAt)-Date.parse(e.startedAt))||0;function Td(e,t){let n=new Map;for(let E of e)for(let T of E.scenarios)n.set(dr(E.path,T.name),{feature:E.path,scenario:T.name,tags:T.tags});let r=E=>Mn(E,T=>n.has(dr(E.feature,T))),s=E=>n.has(dr(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(-$d),l=i.at(-1),d=new Set((l?.scenarios??[]).flatMap(E=>E.browser?[E.browser]:[])),u=E=>E===""||d.size===0||d.has(E),g=new Map,f=t.filter(E=>E.startedAt>=a($d)),p=Ji(f.flatMap(E=>E.scenarios));for(let E of f)for(let T of E.scenarios){if(!s(T))continue;let M=r(T);for(let{key:I,browser:F}of p(T)){let z=g.get(I)??{ref:{feature:Rd(T.feature),scenario:T.scenario,...M!==T.scenario?{name:M}:{},...F?{browser:F}:{}},results:[]};z.results.push({at:E.startedAt,s:T,target:E.baseURL??""}),g.set(I,z)}}let m=[],h=[],w=[];for(let{ref:E,results:T}of g.values()){if(E.browser&&!u(E.browser))continue;let M=new Map,I=0,F=0,z=0;for(let L of T){if(L.s.source==="agent-record")continue;let G=L.s.status==="red";z++,G&&F++;let U=M.get(L.target);U!==void 0&&U!==G&&I++,M.set(L.target,G)}I>=2&&m.push({...E,runs:z,reds:F,flips:I,last:T.at(-1).s.status});let N=T.filter(L=>L.s.source==="agent-heal"&&L.s.status==="yellow");N.length>=2&&h.push({...E,runs:T.length,heals:N.length,unverified:N.filter(L=>Wr(L.s)).length}),w.push({...E,avgMs:Math.round(T.reduce((L,G)=>L+G.s.durationMs,0)/T.length),lastMs:T.at(-1).s.durationMs,runs:T.length})}m.sort((E,T)=>T.flips-E.flips||T.reds-E.reds),h.sort((E,T)=>T.heals-E.heals),w.sort((E,T)=>T.avgMs-E.avgMs);let b=[],y=new Set(t.filter(E=>E.startedAt>=a(qh)).map(E=>E.startedAt));for(let{ref:E,results:T}of g.values()){if(E.browser&&!u(E.browser))continue;let M=T.findLast(z=>z.s.status==="red");if(!M||!y.has(M.at))continue;let I=T.at(-1).s.status==="red",F=0;for(let z=T.length-1;z>=0&&T[z].s.status==="red";z--)F++;b.push({...E,at:M.at,error:M.s.error,stillFailing:I,streak:F})}b.sort((E,T)=>Number(T.stillFailing)-Number(E.stillFailing)||T.at.localeCompare(E.at));let S={green:0,yellow:1,unverified:2,red:3},x=new Map;for(let E of t)for(let T of E.scenarios){let M=dr(T.feature,r(T)),I=x.get(M)??new Map,F=I.get(T.scenario)??new Map;T.browser?F.delete(""):F.clear(),F.set(T.browser??"",Wr(T)?"unverified":T.status),I.set(T.scenario,F),x.set(M,I)}let C=new Map;for(let E of e)for(let T of E.scenarios){let M=Array.from({length:T.rows},(I,F)=>`${T.name} (example ${F+1})`);C.set(dr(E.path,T.name),new Set(T.outline===!0?M:T.outline===!1?[T.name]:[T.name,...M]))}let $=new Map;for(let[E,T]of x){let M=C.get(E),I=[...T].filter(([F])=>!M||M.has(F)).flatMap(([,F])=>{let z=[...F],N=z.filter(([L])=>u(L));return(N.length>0?N:z).map(([,L])=>L)});I.length>0&&$.set(E,I.reduce((F,z)=>S[z]>S[F]?z:F))}let k=new Set($.keys()),R=new Set((l?.scenarios??[]).map(E=>dr(E.feature,r(E)))),_=[],v=[];for(let[E,T]of n){let M={feature:T.feature,scenario:T.scenario};k.has(E)?l&&!R.has(E)&&v.push(M):_.push(M)}let A=l?(()=>{let E=l.scenarios.length,T=Vh(l);return{startedAt:l.startedAt,durationMs:kd(l),ran:E,green:l.green,yellow:l.yellow,red:l.red,unverified:T,passRate:Nn(l,l.scenarios),replayRate:Jh(l.scenarios.filter(M=>M.source==="cache"&&M.status==="green").length,E)}})():void 0,O={green:0,yellow:0,unverified:0,red:0,neverRun:0},P=new Map;for(let[E,T]of n){let M=$.get(E)??"neverRun";O[M]++;for(let I of T.tags){let F=P.get(I)??{tag:I,scenarios:0,green:0,yellow:0,unverified:0,red:0,neverRun:0};F.scenarios++,F[M]++,P.set(I,F)}}return{historyRuns:t.length,suite:{features:e.length,scenarios:o.length,tests:o.reduce((E,T)=>E+T.rows,0),recorded:o.filter(E=>E.cacheState===void 0?E.cached:E.cacheState==="valid").length,...O},lastRun:A,trend:c.map(E=>({startedAt:E.startedAt,passRate:Nn(E,E.scenarios),durationMs:kd(E),red:E.red,tests:E.green+E.yellow+E.red})),flaky:m,healing:h,recentFailures:b,notInLastRun:v,neverRun:_,slowest:w.slice(0,10),tags:[...P.values()].sort((E,T)=>T.red-E.red||T.scenarios-E.scenarios||E.tag.localeCompare(T.tag))}}import{execFileSync as pm}from"node:child_process";import{createHash as gm,randomBytes as ca}from"node:crypto";import ne from"node:fs";import ce from"node:path";import hm from"node:zlib";var B=e=>String(e).replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',"""),Ad="M11 14 L10 4.5 L17.5 9.5 L24 2.5 L30.5 9.5 L38 4.5 L37 14 Z",Wh="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 Bn(e){return`<svg viewBox="0 0 48 48" width="${e}" height="${e}" aria-hidden="true">
|
|
52
|
+
<path d="${Ad}" fill="#F4A300"/>
|
|
53
|
+
<path d="${Wh}" fill="#E7E9EC"/>
|
|
54
|
+
</svg>`}function Yr(e){return`<svg viewBox="8 1 32 15" height="${e}" aria-hidden="true"><path d="${Ad}" fill="#F4A300"/></svg>`}function Gh(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="${B(t.url)}" target="_blank" rel="noopener noreferrer">${B(s)}</a>`:`<span class="chip">${B(s)}</span>`}var Zr=`<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
40
55
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
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">`,
|
|
56
|
+
<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">`,Qr=` :root {
|
|
42
57
|
--bg: #131416;
|
|
43
58
|
--card: #1A1B1E;
|
|
44
59
|
--card-2: #16171A;
|
|
@@ -148,161 +163,173 @@ import ue from"node:fs";import U from"node:path";import Uw from"node:readline";i
|
|
|
148
163
|
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); }
|
|
149
164
|
|
|
150
165
|
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; }
|
|
151
|
-
`,
|
|
166
|
+
`,Kh={green:"passed",yellow:"pending review",red:"failed"};function Yh(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"} ${B(String(n.phase))} \xB7 ${B(n.command)} \xB7 ${B(s)} \xB7 ${B(Le(n.durationMs))}</div>`}).join("")}</div>`:""}function Zi(e,t=5){return[...e.scenarios].sort((n,r)=>Number(r.durationMs)-Number(n.durationMs)).slice(0,t)}function Qi(e,t=0){let n=Number(e.spanMs??t);return n>0?`${Math.min(100,Math.round(Number(e.busyMs)/n*100))}%`:"\u2013"}function Zh(e){let t=e.timing?.workers??[],n=Number(e.timing?.wallMs??0),r=t.length>1&&n>0?t.map(o=>`<div class="mono">worker ${B(o.worker)} \xB7 ${Number(o.runs)} run${Number(o.runs)===1?"":"s"} \xB7 ${B(Le(Number(o.busyMs)))} busy \xB7 ${B(Qi(o,n))}</div>`).join(""):"",s=e.scenarios.length>1?Zi(e).map(o=>`<div class="mono">${B(Le(Number(o.durationMs)))} \xB7 ${B(o.feature)} \u203A ${B(o.scenario)}${e.browsers&&o.browser?` \xB7 ${B(o.browser)}`:""}${o.worker&&t.length>1?` \xB7 worker ${B(o.worker)}`:""}</div>`).join(""):"";return!r&&!s?"":`<div class="panel"><div class="panel-title">timing${n>0?` \xB7 ${B(Le(n))} from the first scenario to the last`:""}</div>${r}${r&&s?'<div class="panel-hint">slowest scenarios</div>':""}${s}</div>`}function Le(e){return e>=1e3?`${(e/1e3).toFixed(1)}s`:`${e}ms`}function Kr(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e4?`${(e/1e3).toFixed(1)}k`:Number(e).toLocaleString()}function pe(e,t,n,r="",s="",o=""){return`<div class="kpi">
|
|
152
167
|
<div class="kpi-label">${e}</div>
|
|
153
168
|
<div class="kpi-value ${r}">${t}</div>
|
|
154
169
|
<div class="kpi-sub ${s}">${n}</div>${o}
|
|
155
|
-
</div>`}function
|
|
156
|
-
${
|
|
157
|
-
${
|
|
158
|
-
${
|
|
159
|
-
${
|
|
160
|
-
${
|
|
161
|
-
${
|
|
162
|
-
${n.plan?
|
|
163
|
-
</section>`}function
|
|
164
|
-
`)}</section>`:""}function
|
|
165
|
-
${
|
|
170
|
+
</div>`}function fr(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 u=`${(d/(e.length-1)*r).toFixed(1)},${(s-2-(l-o)/a*(s-4)).toFixed(1)}`;return d===0||e[d-1]===null?`M${u}h0`:`L${u}`}).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 Ed=(e,t="",n=0)=>`${e>=0?"+":"\u2212"}${Math.abs(e).toFixed(n)}${t} vs prev`;function Qh(e,t){let n=e.totals,r=e.trends,[s,o,i,a]=[n.scenarios,n.green,n.yellow,n.red].map(Number),c=qi({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",u=n.inputTokens+n.outputTokens,g=r?.prev?`${Ed(r.prev.passRatePp,"pp")} \xB7 ${c} of ${s}`:`${c} of ${s} scenarios`,f=r?.prev?.costUsd!==void 0?`${Ed(r.prev.costUsd,"",4).replace("+","+$").replace("\u2212","\u2212$")} \xB7 ${Le(t)}`:`${Le(t)} total runtime`;return`<section class="kpis">
|
|
171
|
+
${pe("pass rate",`${l}<span class="unit">%</span>`,g,d,r?.prev?r.prev.passRatePp>=0?"green":"red":"",fr(r?.series.passRate??[],"var(--green)"))}
|
|
172
|
+
${pe("passed",String(o),"deterministic replay","green",o>0?"green":"")}
|
|
173
|
+
${pe("pending",String(i),i>0?"\u25B2 proposals to review":"nothing to review",i>0?"gold":"",i>0?"gold":"")}
|
|
174
|
+
${pe("failed",String(a),a>0?"\u25BC needs attention":"all clear",a>0?"red":"",a>0?"red":"green")}
|
|
175
|
+
${pe("ai calls",String(Number(n.aiCalls)),`${Kr(u)} in+out tokens`,n.aiCalls>0?"":"green")}
|
|
176
|
+
${pe("cache traffic",Kr(n.cacheReadTokens+n.cacheCreationTokens),n.cacheReadTokens+n.cacheCreationTokens>0?`${Kr(n.cacheReadTokens)} read \xB7 ${Kr(n.cacheCreationTokens)} written`:"zero (fully cached run)","",n.cacheReadTokens+n.cacheCreationTokens>0?"":"green")}
|
|
177
|
+
${n.plan?pe("plan usage",`${Ui(n.plan.fiveHourBefore,n.plan.fiveHourAfter)}`,[`5-hour window \xB7 ${B(n.plan.subscriptionType)} plan`,bd(n.plan.resetsAt)].filter(Boolean).join(" \xB7 "),"gold","")+pe("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}`,"","",fr(r?.series.costUsd??[],"var(--gold)")):pe("ai cost",ft(n)?`<span class="unit">$</span>${n.costUsd.toFixed(n.costUsd>=1?2:4)}`:"n/a",ft(n)?f:"not reported by the provider","","",ft(n)?fr(r?.series.costUsd??[],"var(--gold)"):"")}
|
|
178
|
+
</section>`}function Xh(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>${B(r.feature)} \u203A ${B(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: ${B(r.message)}</li>`).join("")}</ul></div>`),n.length>0?`<section class="trends">${n.join(`
|
|
179
|
+
`)}</section>`:""}function em(e){let t=Array.isArray(e.sessions)?e.sessions:[];return`<ol class="steps">${e.steps.map((r,s)=>{let o=typeof t[s]=="string"&&(s===0||t[s]!==t[s-1])?t[s]:void 0,i=r.status==="passed"?'<span class="dot green"></span>':r.status==="failed"?'<span class="dot red"></span>':'<span class="dot idle"></span>';return`<li class="step ${B(r.status)}">
|
|
180
|
+
${i}
|
|
166
181
|
<div class="step-body">
|
|
167
|
-
<span class="step-text">${
|
|
168
|
-
${
|
|
169
|
-
${
|
|
170
|
-
${
|
|
171
|
-
${
|
|
172
|
-
${
|
|
182
|
+
<span class="step-text">${B(r.gherkin)}</span>
|
|
183
|
+
${o?`<span class="tag indigo" title="the browser session this step and the ones after it run in, each a browser of its own">session: ${B(o)}</span>`:""}
|
|
184
|
+
${r.kind==="assertion"?'<span class="tag">assert</span>':""}
|
|
185
|
+
${r.fromStepSet?`<span class="tag indigo" title="inlined from a StepSet definition: edit once, every invoking scenario follows">from StepSet: ${B(r.fromStepSet)}</span>`:""}
|
|
186
|
+
${r.drift?'<span class="tag gold" title="page fingerprint no longer matches the recording">drift</span>':""}
|
|
187
|
+
${r.retries?`<span class="tag gold" title="an action failed and was re-attempted with backoff before the step settled">retried \xD7${Number(r.retries)}</span>`:""}
|
|
188
|
+
${r.error?`<div class="step-error">${B(r.error)}</div>`:""}
|
|
173
189
|
</div>
|
|
174
190
|
</li>`}).join(`
|
|
175
|
-
`)}</ol>`}function
|
|
191
|
+
`)}</ol>`}function tm(e){return e.featureEdits&&e.featureEdits.length>0?`<div class="panel">
|
|
176
192
|
<div class="panel-title gold">suggested .feature edit</div>
|
|
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 ${
|
|
193
|
+
<div class="diff">${e.featureEdits.map(n=>{let r=e.steps[n.index]?.gherkin??`step ${n.index}`;return`<div class="diff-line del">\u2212 ${B(r)}</div><div class="diff-line add">+ ${B(n.text)}</div>`}).join("")}</div>
|
|
178
194
|
<div class="panel-hint">apply with <code>saffron accept --with-feature-edit</code></div>
|
|
179
|
-
</div>`:e.suggestedFeatureEdit?`<div class="panel"><div class="panel-title gold">suggested .feature edit</div><pre>${
|
|
195
|
+
</div>`:e.suggestedFeatureEdit?`<div class="panel"><div class="panel-title gold">suggested .feature edit</div><pre>${B(e.suggestedFeatureEdit)}</pre></div>`:""}function nm(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> ':""}${B(c.gherkin)}${c.fromStepSet?` <span class="mono">(step set "${B(c.fromStepSet)}")</span>`:""}</div>`,d=c.actions.flatMap(u=>u.change==="same"?[`<div class="diff-line"> ${B(u.before??"")}</div>`]:u.change==="added"?[`<div class="diff-line add">+ ${B(u.after??"")}</div>`]:u.change==="removed"?[`<div class="diff-line del">\u2212 ${B(u.before??"")}</div>`]:[`<div class="diff-line del">\u2212 ${B(u.before??"")}</div>`,`<div class="diff-line add">+ ${B(u.after??"")}</div>`,...(u.details??[]).map(g=>`<div class="diff-line detail">${B(g)}</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">${B(a)}</div></div>`}function rm(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=yd(e.usage.costUsd,t),s=r?` \xB7 ${r}`:"";return`<span class="pill gold">${Number(e.usage.aiCalls)} ai \xB7 ${Kr(n)} tok${s}</span>`}function sm(e,t,n,r=!1){return`<details class="card" ${e.status!=="green"?"open":""}>
|
|
180
196
|
<summary>
|
|
181
|
-
<span class="pill ${e.status==="green"?"green":e.status==="yellow"?"gold":"red"}">${
|
|
182
|
-
<span class="card-title">${
|
|
197
|
+
<span class="pill ${e.status==="green"?"green":e.status==="yellow"?"gold":"red"}">${Kh[e.status]}</span>
|
|
198
|
+
<span class="card-title">${B(e.scenario)}</span>
|
|
183
199
|
<span class="card-meta">
|
|
184
|
-
<span class="m">${
|
|
200
|
+
<span class="m">${B(e.feature)}</span>
|
|
185
201
|
<span class="m-sep">\xB7</span>
|
|
186
|
-
<span class="m">${
|
|
202
|
+
<span class="m">${B(e.source)}</span>
|
|
187
203
|
<span class="m-sep">\xB7</span>
|
|
188
|
-
<span class="m">${
|
|
189
|
-
${r&&e.browser?`<span class="m-sep">\xB7</span><span class="chip">${
|
|
190
|
-
${
|
|
204
|
+
<span class="m">${Le(Number(e.durationMs))}</span>
|
|
205
|
+
${r&&e.browser?`<span class="m-sep">\xB7</span><span class="chip">${B(e.browser)}</span>`:""}
|
|
206
|
+
${rm(e,t)}
|
|
191
207
|
</span>
|
|
192
208
|
</summary>
|
|
193
209
|
<div class="card-body">
|
|
194
|
-
${
|
|
195
|
-
${e.narrative?`<div class="panel"><div class="panel-title">agent narrative</div><p>${
|
|
196
|
-
${e.adaptations.length>0?`<div class="panel accent-gold"><div class="panel-title gold">adaptations</div><ul>${e.adaptations.map(s=>`<li>${
|
|
197
|
-
${
|
|
198
|
-
${
|
|
199
|
-
${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">${
|
|
210
|
+
${em(e)}
|
|
211
|
+
${e.narrative?`<div class="panel"><div class="panel-title">agent narrative</div><p>${B(e.narrative)}</p></div>`:""}
|
|
212
|
+
${e.adaptations.length>0?`<div class="panel accent-gold"><div class="panel-title gold">adaptations</div><ul>${e.adaptations.map(s=>`<li>${B(s)}</li>`).join("")}</ul></div>`:""}
|
|
213
|
+
${tm(e)}
|
|
214
|
+
${nm(e)}
|
|
215
|
+
${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">${B(e.proposalFile)}</p>${e.verified===!1&&e.proofError?`<p class="mono" style="color:var(--red)">proof replay failed: ${B(e.proofError.split(`
|
|
200
216
|
`)[0])}</p>`:""}<div class="panel-hint">review with <code>saffron accept</code> / <code>saffron reject</code></div></div>`:""}
|
|
201
|
-
${e.error&&e.status==="red"?`<div class="panel accent-red"><div class="panel-title red">failure</div><p>${
|
|
202
|
-
${e.uniques&&e.status!=="green"?`<div class="panel"><div class="panel-title">unique values in this run</div>${Object.entries(e.uniques).map(([s,o])=>`<div class="mono">${
|
|
203
|
-
${e.proofUniques&&e.status!=="green"?`<div class="panel"><div class="panel-title">unique values in the proof replay</div>${Object.entries(e.proofUniques).map(([s,o])=>`<div class="mono">${
|
|
204
|
-
${
|
|
217
|
+
${e.error&&e.status==="red"?`<div class="panel accent-red"><div class="panel-title red">failure</div><p>${B(e.error)}</p></div>`:""}
|
|
218
|
+
${e.uniques&&e.status!=="green"?`<div class="panel"><div class="panel-title">unique values in this run</div>${Object.entries(e.uniques).map(([s,o])=>`<div class="mono">${B(s)} = ${B(o)}</div>`).join("")}</div>`:""}
|
|
219
|
+
${e.proofUniques&&e.status!=="green"?`<div class="panel"><div class="panel-title">unique values in the proof replay</div>${Object.entries(e.proofUniques).map(([s,o])=>`<div class="mono">${B(s)} = ${B(o)}</div>`).join("")}</div>`:""}
|
|
220
|
+
${om(e,n,r)}
|
|
205
221
|
</div>
|
|
206
|
-
</details>`}function
|
|
222
|
+
</details>`}function om(e,t,n=!1){let r=(e.evidence??[]).filter(a=>a.kind==="trace"),o=r[0]?`<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 ${B(im(`${e.feature}:${e.scenario}${n&&e.browser?`@${e.browser}`:""}`))}</div><div class="panel-hint">${r.map(a=>B(a.file)).join(" \xB7 ")}</div></div>`:"",i=(e.evidence??[]).flatMap(a=>{if(!t||a.kind!=="failure"&&a.kind!=="before-heal")return[];let c=mn(t,a);if(!c)return[];try{let l=c.toString("base64"),d=a.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>${B(d)}${a.step?`: <span class="mono">${B(a.step)}</span>`:""}</figcaption><a href="data:image/jpeg;base64,${l}" target="_blank" rel="noopener"><img alt="${B(d)}" src="data:image/jpeg;base64,${l}"/></a><div class="panel-hint">${B(a.file)}</div></figure>`]}catch{return[]}});return i.length===0?o:`<div class="panel ${e.status==="red"?"accent-red":"accent-gold"}"><div class="panel-title ${e.status==="red"?"red":"gold"}">screenshot</div>${i.join("")}</div>${o}`}var im=e=>/[^A-Za-z0-9_./:-]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e;function vn(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>
|
|
207
223
|
<html lang="en">
|
|
208
224
|
<head>
|
|
209
225
|
<meta charset="utf-8"/>
|
|
210
226
|
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
|
211
227
|
<title>Saffron run report</title>
|
|
212
|
-
${
|
|
228
|
+
${Zr}
|
|
213
229
|
<style>
|
|
214
|
-
${
|
|
230
|
+
${Qr}</style>
|
|
215
231
|
</head>
|
|
216
232
|
<body>
|
|
217
233
|
<div class="topline"></div>
|
|
218
234
|
<div class="wrap">
|
|
219
235
|
<header class="top">
|
|
220
236
|
<div class="brand">
|
|
221
|
-
${
|
|
237
|
+
${Bn(38)}
|
|
222
238
|
<div>
|
|
223
239
|
<div class="brand-name">saffron</div>
|
|
224
240
|
<div class="brand-sub">test run report</div>
|
|
225
241
|
</div>
|
|
226
242
|
</div>
|
|
227
243
|
<div class="run-meta">
|
|
228
|
-
<span>${
|
|
244
|
+
<span>${B(o)}</span>
|
|
229
245
|
<span>\xB7</span>
|
|
230
|
-
<span>${
|
|
231
|
-
${e.baseURL?`<span class="chip base">${
|
|
246
|
+
<span>${Le(s)}</span>
|
|
247
|
+
${e.baseURL?`<span class="chip base">${B(e.baseURL)}</span>`:""}
|
|
232
248
|
${e.shards?`<span class="chip">merged from ${Number(e.shards)} shards</span>`:""}
|
|
233
|
-
${e.browsers?.length?`<span class="chip">${e.browsers.map(i=>
|
|
234
|
-
${
|
|
249
|
+
${e.browsers?.length?`<span class="chip">${e.browsers.map(i=>B(i)).join(" \xB7 ")}</span>`:""}
|
|
250
|
+
${Gh(e)}
|
|
235
251
|
</div>
|
|
236
252
|
</header>
|
|
237
253
|
|
|
238
|
-
${
|
|
239
|
-
${
|
|
240
|
-
${
|
|
241
|
-
${
|
|
254
|
+
${Qh(e,s)}
|
|
255
|
+
${Xh(e)}
|
|
256
|
+
${Yh(e)}
|
|
257
|
+
${Zh(e)}
|
|
242
258
|
|
|
243
259
|
<div class="section-head">
|
|
244
260
|
<span class="section-title">scenarios \xB7 ${Number(n.scenarios)}</span>
|
|
245
|
-
<span class="section-title">saffron v${
|
|
261
|
+
<span class="section-title">saffron v${B(e.version)}</span>
|
|
246
262
|
</div>
|
|
247
|
-
${e.scenarios.map(i=>
|
|
263
|
+
${e.scenarios.map(i=>sm(i,!!e.totals.plan,t,!!e.browsers)).join(`
|
|
248
264
|
`)}
|
|
249
265
|
|
|
250
|
-
<footer>${
|
|
266
|
+
<footer>${Yr(11)} generated by saffron v${B(e.version)} \xB7 ${B(new Date(e.finishedAt).toLocaleString("en-GB",{dateStyle:"medium",timeStyle:"medium"}))}</footer>
|
|
251
267
|
</div>
|
|
252
268
|
</body>
|
|
253
269
|
</html>
|
|
254
|
-
`}import
|
|
255
|
-
`),
|
|
256
|
-
${d.name}`;o.set(
|
|
257
|
-
`)).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
|
|
258
|
-
`),r}var
|
|
259
|
-
`));let
|
|
260
|
-
`)??[]).map(r=>r.split(/\s+/)[1]).filter(Boolean);return[...new Set(n.map(
|
|
270
|
+
`}import so from"node:fs";import oo from"node:path";function io(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 Xi(e,t,n){return{tool:"saffron",version:Xe(),startedAt:t.toISOString(),finishedAt:new Date().toISOString(),baseURL:n,totals:io(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,sessions:gn(r.scenario.steps)?r.scenario.steps.map(s=>Ge(de(s.session))):void 0,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,worker:r.worker,browser:r.browser}))}}var Dt=e=>!!e&&typeof e=="object"&&!Array.isArray(e),no=(e,t)=>t.find(n=>typeof e[n]!="number"),ro=e=>e===void 0||typeof e=="number",am=["scenarios","green","yellow","red","aiCalls","inputTokens","outputTokens","cacheReadTokens","costUsd"],cm=["aiCalls","inputTokens","outputTokens","cacheReadTokens"],Cd=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 ea(e){if(!Dt(e)||e.tool!=="saffron")return"is not a Saffron run report";if(!Cd(e.startedAt)||!Cd(e.finishedAt))return"has no start or finish time";if(!Dt(e.totals))return"has no totals";let t=no(e.totals,am);if(t)return`has totals.${t} that is not a number`;if(!Array.isArray(e.scenarios))return"has no list of scenarios";for(let[o,i]of e.scenarios.entries()){let a=`scenarios[${o}]`;if(!Dt(i)||typeof i.feature!="string"||typeof i.scenario!="string")return`has ${a} without a feature and scenario name`;if(!["green","yellow","red"].includes(i.status))return`has ${a}.status ${JSON.stringify(i.status)}, which this saffron-ai does not know`;if(!Dt(i.usage)||no(i.usage,cm))return`has ${a}.usage without its token counts`;if(!Array.isArray(i.steps))return`has ${a}.steps that is not a list`;let c=i.steps.findIndex(d=>!Dt(d)||typeof d.gherkin!="string"||typeof d.kind!="string"||typeof d.status!="string");if(c>=0)return`has ${a}.steps[${c}] without its gherkin, kind and status`;for(let[d,u]of i.steps.entries()){if(!["passed","failed","skipped"].includes(u.status))return`has ${a}.steps[${d}].status ${JSON.stringify(u.status)}, which this saffron-ai does not know`;let g=["retries","failedActionIndex"].find(f=>!ro(u[f]));if(g)return`has ${a}.steps[${d}].${g} that is not a number`}let l=["browser","worker"].find(d=>i[d]!==void 0&&typeof i[d]!="string");if(l)return`has ${a}.${l} that is not text`;if(i.evidence!==void 0&&!(Array.isArray(i.evidence)&&i.evidence.every(d=>Dt(d)&&typeof d.file=="string"&&typeof d.kind=="string")))return`has ${a}.evidence that is not a list of files`}if(e.browsers!==void 0&&!(Array.isArray(e.browsers)&&e.browsers.every(o=>typeof o=="string")))return"has browsers that is not a list of names";let n=e.timing;if(n!==void 0&&!(Dt(n)&&typeof n.wallMs=="number"&&Array.isArray(n.workers)&&n.workers.every(o=>Dt(o)&&typeof o.worker=="string"&&!no(o,["runs","busyMs"])&&ro(o.spanMs))))return"has timing whose workers are not a list of named counts";let r=e.trends,s=(o,i)=>Array.isArray(o)&&o.every(a=>Dt(a)&&!no(a,i));if(r!==void 0&&!(Dt(r)&&ro(r.divergentSteps)&&s(r.chronic,["heals","reds","runs"])&&s(r.topIssues,["count"])&&(r.prev===void 0||s([r.prev],["passRatePp","aiCalls","red"])&&ro(r.prev.costUsd))))return"has trends whose counts are not numbers"}var ta=e=>ea(e)===void 0;function na(e){try{let t=JSON.parse(so.readFileSync(oo.join(e,".saffron","reports","latest.json"),"utf8"));return ta(t)?t:void 0}catch{return}}function ra(e,t){if(!e||e.imported||e.baseURL!==t.baseURL)return t;let n=new Set,r=e.scenarios.flatMap(p=>{let m=t.scenarios.find(h=>xd(p,h));return m?n.has(m)?[]:(n.add(m),[m]):[p]}),s=r.filter(p=>!t.scenarios.includes(p)),o=t.totals.aiCalls>0;if(o&&s.some(p=>p.usage.aiCalls>0)&&!t.totals.plan!=!e.totals.plan)return t;r.push(...t.scenarios.filter(p=>!n.has(p)));let i=[...new Set(r.flatMap(p=>p.browser?[p.browser]:[]))],{trends:a,shards:c,hooks:l,timing:d,browsers:u,...g}=e,f=o?t.totals.plan:e.totals.plan;return{...g,version:t.version,startedAt:t.startedAt,finishedAt:t.finishedAt,totals:{...io(r),...f?{plan:f}:{}},scenarios:r,...t.shards?{shards:t.shards}:{},...t.hooks?{hooks:t.hooks}:{},...t.timing?{timing:t.timing}:{},...i.length>1?{browsers:i}:{}}}function Xr(e,t){let n=oo.join(e,".saffron","reports");so.mkdirSync(n,{recursive:!0});let r=oo.join(n,"latest.json"),s=oo.join(n,"latest.html");return so.writeFileSync(r,`${JSON.stringify(t,null,2)}
|
|
271
|
+
`),so.writeFileSync(s,vn(t,e)),{json:r,html:s}}import lm from"node:crypto";import es from"node:fs";import ao from"node:path";var _d=["scenario","file"];function Od(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 Id(e){if(!_d.includes(e))throw new Error(`invalid --shard-by "${e}": use ${_d.map(t=>`"${t}"`).join(" or ")}`);return e}function sa(e){return`shard-${e.index}-of-${e.total}`}var dm=e=>`${e.featurePath}${e.displayName}`;function jd(e,t){let n=t.by??"scenario",r=e.map(dm),s=new Set,o=new Map;e.forEach((d,u)=>{let g=n==="file"?d.featurePath:`${d.featurePath}
|
|
272
|
+
${d.name}`;o.set(g,[...o.get(g)??[],u])});let i=new Array(t.total).fill(0),a=[...o].sort((d,u)=>u[1].length-d[1].length||(d[0]<u[0]?-1:d[0]>u[0]?1:0));for(let[,d]of a){let u=i.indexOf(Math.min(...i));if(i[u]+=d.length,u===t.index-1)for(let g of d)s.add(g)}let c=e.map((d,u)=>u).filter(d=>s.has(d)),l=lm.createHash("sha256").update([...r].sort().join(`
|
|
273
|
+
`)).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 co(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 lo=(e=process.env)=>e.GITHUB_RUN_ATTEMPT||e.SYSTEM_JOBATTEMPT||void 0;function oa(e,t){let n=ao.join(e,".saffron","reports");es.mkdirSync(n,{recursive:!0});let r=ao.join(n,`${sa(t.shard)}.json`);return es.writeFileSync(r,`${JSON.stringify(t,null,2)}
|
|
274
|
+
`),r}var Pd=e=>typeof e=="number"&&Number.isFinite(e),ur=(e,t)=>e===void 0||t(e),Ln=e=>typeof e=="string",fm=e=>{let t=e;return!!t&&typeof t=="object"&&Ln(t.feature)&&Ln(t.scenario)&&ur(t.name,Ln)&&ur(t.tags,n=>Array.isArray(n)&&n.every(Ln))&&["green","yellow","red"].includes(t.status)&&Ln(t.source)&&[t.durationMs,t.adaptations,t.driftSteps,t.aiCalls,t.tokensInOut,t.cacheRead,t.cacheWrite,t.costUsd].every(Pd)&&ur(t.verified,n=>typeof n=="boolean")&&ur(t.seededSteps,Pd)&&ur(t.error,Ln)&&ur(t.browser,Ln)},ts=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)&&(t.shard.browser===void 0||typeof t.shard.browser=="string")&&Array.isArray(t.scenarios)&&!!t.history&&Array.isArray(t.history.scenarios)&&t.history.scenarios.every(fm)},um=/^shard-\d+-of-\d+\.json$/;function Nd(e){let t=[],n=(r,s)=>{let o=es.statSync(r,{throwIfNoEntry:!1});if(!o)throw new Error(`not found: ${r}`);if(o.isDirectory())for(let i of es.readdirSync(r).sort())n(ao.join(r,i),!1);else(s||um.test(ao.basename(r)))&&t.push(r)};for(let r of e)n(r,!0);return t.map(r=>{let s;try{s=JSON.parse(es.readFileSync(r,"utf8"))}catch(o){throw new Error(`cannot read shard report ${r}: ${o instanceof Error?o.message:String(o)}`)}if(!ts(s))throw new Error(`${r} is not a shard report (written by saffron run --shard)`);return{file:r,report:s}})}var Dn=class extends Error{};function fo(e,t={}){if(e.length===0)throw new Dn("no shard reports found. Shards write .saffron/reports/shard-<i>-of-<n>.json");let n=v=>Number(v.report.shard.attempt)||0,r=v=>{let{ciRun:A,index:O,total:P,suite:E,suiteSize:T,by:M,browser:I}=v.report.shard;return JSON.stringify([A??"",O,P,E,T,M??"scenario",v.report.baseURL??"",I??""])},s=new Map;for(let v of e)s.set(r(v),Math.max(s.get(r(v))??0,n(v)));let o=e.filter(v=>n(v)<s.get(r(v)));e=e.filter(v=>!o.includes(v));let i=e[0].report.shard,a=[],c=v=>v.map(A=>A.file).join(", "),l=new Set(e.map(v=>v.report.shard.total));l.size>1&&a.push(`shards disagree on the shard count (${[...l].sort().join(", ")}): ${c(e)}`),new Set(e.map(v=>`${v.report.shard.suite}/${v.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 u=new Set(e.map(v=>v.report.shard.by??"scenario"));u.size>1&&a.push(`shards split the suite in different ways (--shard-by ${[...u].sort().join(" and ")}): every shard must use the same`);let g=new Set(e.map(v=>v.report.shard.ciRun??""));g.size>1&&a.push(`shards come from different CI runs (${[...g].map(v=>v||"none recorded").join(", ")})`);let f=[...new Set(e.map(v=>v.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 p=[...new Set(e.map(v=>v.report.shard.browser??"(no browser recorded)"))];p.length>1&&a.push(`the shards ran in different browsers: ${p.join(", ")}. Merge the shards of one browser at a time`);let m=new Map;for(let v of e)m.set(v.report.shard.index,[...m.get(v.report.shard.index)??[],v]);for(let[v,A]of[...m].sort((O,P)=>O[0]-P[0]))A.length>1&&a.push(`shard ${v}/${i.total} appears ${A.length} times: ${c(A)}`);if(l.size===1&&!t.partial){let v=Array.from({length:i.total},(A,O)=>O+1).filter(A=>!m.has(A));v.length>0&&a.push(`missing ${v.length===1?"shard":"shards"} ${v.map(A=>`${A}/${i.total}`).join(", ")}. A merge without ${v.length===1?"it":"them"} would under-count the run`)}if(a.length===0){let v=new Set,A=0;for(let O of e){let{positions:P}=O.report.shard;(P.length!==O.report.scenarios.length||P.length!==O.report.history.scenarios.length)&&a.push(`${O.file} is inconsistent: ${P.length} positions for ${O.report.scenarios.length} scenarios`);for(let E of P)v.has(E)&&a.push(`two shards both ran scenario ${E+1} of the suite`),v.add(E);A+=P.length}a.length===0&&!t.partial&&A!==i.suiteSize&&a.push(`the shards hold ${A} scenarios but the suite has ${i.suiteSize}`)}if(a.length>0)throw new Dn(a.join(`
|
|
275
|
+
`));let h=e.sort((v,A)=>v.report.shard.index-A.report.shard.index).flatMap(({report:v})=>v.shard.positions.map((A,O)=>({position:A,scenario:v.scenarios[O].worker?{...v.scenarios[O],worker:`${v.shard.index}/${v.shard.total} \xB7 ${v.scenarios[O].worker}`}:v.scenarios[O],history:v.history.scenarios[O]}))).sort((v,A)=>v.position-A.position),w=e.map(v=>v.report),b=w.map(v=>v.startedAt).sort()[0],y=w.map(v=>v.finishedAt).sort().at(-1),S=h.map(v=>v.scenario),x=w.flatMap(v=>v.hooks??[]),C={tool:"saffron",version:w[0].version,startedAt:b,finishedAt:y,baseURL:w.find(v=>v.baseURL)?.baseURL,totals:io(S),scenarios:S,shards:e.length};x.length>0&&(C.hooks=x);let $=e.filter(v=>v.report.timing).sort((v,A)=>v.report.shard.index-A.report.shard.index);$.length>0&&(C.timing={wallMs:Math.max(...$.map(v=>v.report.timing.wallMs)),workers:$.flatMap(v=>v.report.timing.workers.map(A=>({...A,worker:`${v.report.shard.index}/${v.report.shard.total} \xB7 ${A.worker}`})))});let k=h.map(v=>v.history),_={runId:i.ciRun?`${i.ciRun}:${i.suite}:${C.baseURL??""}${i.browser?`:${i.browser}`:""}`:b,startedAt:b,finishedAt:y,baseURL:C.baseURL,green:k.filter(v=>v.status==="green").length,yellow:k.filter(v=>v.status==="yellow").length,red:k.filter(v=>v.status==="red").length,aiCalls:k.reduce((v,A)=>v+A.aiCalls,0),costUsd:k.reduce((v,A)=>v+A.costUsd,0),divergentSteps:Math.max(...w.map(v=>v.history.divergentSteps)),...w.some(v=>v.history.partial)?{partial:!0}:{},scenarios:k};return{report:C,history:_,replaced:o.map(v=>v.file)}}var uo=1,H=class extends Error{constructor(n,r){super(ue(n,1/0));this.kind=r}kind},Un=e=>e instanceof Error?e.message:String(e);function sn(e,t){try{return pm("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4}).trim()||void 0}catch{return}}function zd(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 go(e){let n=(sn(e,["remote","-v"])?.split(`
|
|
276
|
+
`)??[]).map(r=>r.split(/\s+/)[1]).filter(Boolean);return[...new Set(n.map(zd).filter(r=>r!==void 0))]}var Md=e=>e?.replace(/^refs\/heads\//,"")||void 0,Hd=e=>e.GITHUB_EVENT_NAME==="pull_request"||!!e.GITHUB_EVENT_NAME?.startsWith("pull_request_review");function mm(e){if(!e.GITHUB_EVENT_PATH||!Hd(e))return{};let t=n=>typeof n=="string"&&n?n:void 0;try{let n=JSON.parse(ne.readFileSync(e.GITHUB_EVENT_PATH,"utf8"))?.pull_request?.head;return{sha:t(n?.sha),ref:t(n?.ref)}}catch{return{}}}function la(e,t){return[...(sn(e,["cat-file","-p",t])??"").split(`
|
|
261
277
|
|
|
262
|
-
`)[0].matchAll(/^parent ([0-9a-f]+)$/gm)].map(r=>r[1])}function
|
|
263
|
-
`)??[],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&&
|
|
264
|
-
`)},...r]),{file:f,manifest:u,proposals:o,missing:l,dropped:d,unreadable:n}}var bs="[a-z0-9-]+",bl=new RegExp(`^proposals/${bs}/${bs}\\.json$`),Og=new RegExp(`^artifacts/${bs}/${bs}/[A-Za-z0-9][A-Za-z0-9._-]*$`),fi=1024**3,hi=8*1024**3,jg="the bundles to import add up to more than 8 GB unzipped",ul=Math.min(hi,zt),gl=100,Ng=1024**2,Mg=6e5;function Fg(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function mi(e){let t=te.join(e,".saffron","reports");for(let o of Q.existsSync(t)?Q.readdirSync(t):[]){let i=Number(/^run-download-(\d+)-/.exec(o)?.[1]),a=te.join(t,o),c=i?Q.statSync(a,{throwIfNoEntry:!1}):void 0;c&&Date.now()-c.mtimeMs>36e5&&!Fg(i)&&Q.rmSync(a,{recursive:!0,force:!0})}let n=te.join(t,`run-download-${process.pid}-${ui(4).toString("hex")}`),r=Q.mkdirSync(n,{recursive:!0});return{dir:n,remove:()=>{Q.rmSync(n,{recursive:!0,force:!0});for(let o=t;r&&o.startsWith(r);o=te.dirname(o))try{Q.rmdirSync(o)}catch{break}}}}async function Lg(e,t){let n=r=>new z(r?.name==="TimeoutError"?`cannot download ${e}: it did not finish within 10 minutes`:`cannot download ${e}: ${dn(r)}`);try{let r=await fetch(e,{redirect:"follow",signal:AbortSignal.timeout(Mg)});if(!r.ok||!r.body)throw new z(`cannot download ${e}: HTTP ${r.status}`);let s=Q.openSync(t,"w");try{let o=0;for await(let i of r.body){if(o+=i.length,o>hi)throw new z(`cannot download ${e}: it is over 8 GB`);Q.writeSync(s,i)}}finally{Q.closeSync(s)}}catch(r){throw r instanceof z?r:n(r)}}async function Bg(e,t){if(/^https?:\/\//i.test(e)){let s=te.join(t(),`url-${ui(4).toString("hex")}.zip`);return await Lg(e,s),[{source:e,file:s}]}let n=Q.statSync(e,{throwIfNoEntry:!1});if(!n)throw new z(`not found: ${e}`);let r=n.isDirectory()?Q.readdirSync(e,{recursive:!0}).map(String).filter(s=>/^saffron-bundle.*\.zip$/.test(te.basename(s))).sort().map(s=>te.join(e,s)):[e];if(r.length===0)throw new z(`no saffron-bundle*.zip under ${e}`);return r.map(s=>({source:s,file:s}))}function Dg(e,t){let n;try{n=wc(t)}catch(s){throw new z(`${e} is not a Saffron bundle: ${dn(s)}`)}let r=new Map;for(let s of n){if(r.has(s.name))throw new z(`${e} is damaged: it holds ${ie(s.name)} twice`);r.set(s.name,s)}return{source:e,file:t,entries:r}}var Ug=1024*1024;function hl(e,t,n){let r=Tg("sha256"),s=Q.openSync(e,"r");try{let o=Buffer.alloc(Math.max(1,Math.min(Ug,t.size)));for(let i=0;i<t.size;){let a=Q.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{Q.closeSync(s)}return r.digest("hex")}function zg(e){try{return ns(e).sha256}catch{return}}function Hg({source:e,file:t,entries:n}){let r=f=>new z(`${e} ${f}`);for(let f of n.values()){if(f.size>fi||f.compressedSize>fi)throw r(`is damaged: ${ie(f.name)} is too large`);if(f.method!==0&&f.size>Ng&&f.size>gl*f.compressedSize)throw r(`is damaged: ${ie(f.name)} claims to unzip to over ${gl} times its size`)}let s=f=>{let g=n.get(f);if(!g)throw r(`is damaged: ${f} is missing`);let w;try{let R=g.raw();if(R.length!==g.compressedSize)throw new Error("the file ends early");w=g.method===0?R:Eg.inflateRawSync(R,{maxOutputLength:Math.max(g.size,1)})}catch(R){throw r(`is damaged: ${f} cannot be read (${dn(R)})`)}if(w.length!==g.size)throw r(`is damaged: ${f} is truncated`);return w},o=f=>{let g=n.get(f);if(!(!g||g.method!==0)){if(g.compressedSize!==g.size)throw r(`is damaged: ${f} is truncated`);return g}},i=f=>{let g=o(f);if(!g)return rt(s(f));try{return hl(t,g)}catch(w){throw r(`is damaged: ${f} cannot be read (${dn(w)})`)}},a=(f,g,w)=>{let R=o(f),$=()=>new Error(ie(`${e} is damaged: ${f} changed while it was imported`,1/0));if(!R){let S=s(f);if(rt(S)!==w)throw $();Oe(g,S);return}Q.mkdirSync(te.dirname(g),{recursive:!0});let m=`${g}.${process.pid}-${ui(4).toString("hex")}.partial`,v=Q.openSync(m,"w");try{let S;try{S=hl(t,R,x=>{for(let b=0;b<x.length;)b+=Q.writeSync(v,x,b,x.length-b)})}finally{Q.closeSync(v)}if(S!==w)throw $();Q.renameSync(m,g)}catch(S){throw Q.rmSync(m,{force:!0}),S}},c=f=>{try{return JSON.parse(s(f).toString("utf8"))}catch(g){throw g instanceof z?g: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>ys)throw r(`is bundle format ${l.format}, made by saffron-ai ${l.runner}; this saffron-ai (${nt()}) reads format ${ys}. Update saffron-ai to import it`);if(l.format!==ys)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"||!bl.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 g=s(f.entry);if(rt(g)!==f.revision)throw r(`is damaged: ${f.entry} is not the proposal its manifest names`);p.set(f.entry,g)}for(let f of l.evidence){if(!f||typeof f.entry!="string"||!Og.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"),g=oi(f);if(g)throw r(`is damaged: report.json ${g}`);try{qt(f)}catch(w){throw r(`is damaged: report.json cannot be shown (${dn(w)})`)}u=f}if(d&&!(u&&ms(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 qg(e,t){let n=t.headCommit??t.commit,r=At(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)||!At(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]=(At(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 pi(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 vl=e=>te.join(e,".saffron","reports","imported.json");function _t(e){let t;try{t=JSON.parse(Q.readFileSync(vl(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 Jg(e,t){try{return Q.readFileSync(e).equals(t)}catch{return!1}}function Sl(e,t,n,r,s){let o;try{o=bo(t,n)}catch($){let m={file:`.saffron/${n}`,feature:"",scenario:""},v=`cannot be read: ${$ instanceof le?$.problem:dn($)}`;return{verdict:{...m,outcome:"refused",reason:v},shown:m,file:te.join(e,".saffron",n),revision:"",verified:!1}}let{proposal:i,revision:a}=o,{feature:c,scenario:l}=i.cache,d=qe(e,c,l),p={file:Ae(e,d),feature:ie(c),scenario:ie(l)},u=$=>({verdict:$,shown:p,file:d,revision:a,verified:i.meta.verified===!0}),f=$=>u({...p,outcome:"refused",reason:$});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 g=s?`. ${s}`:"";if(!Q.existsSync(te.join(e,c)))return f(`is for ${p.feature}, which is not in this checkout${g}`);let w=Lt(se(e,c,l));if(w&&ir(w)===ir(i.cache))return u({...p,outcome:"unchanged",reason:"already accepted here: the committed recording is this proposal's"});let R;try{R=We(e,i,r)}catch($){R=`cannot be checked: ${dn($)}`}return R?f(`does not fit this checkout: ${ie(R,1e3)}${g}`):u()}function xl(e,t){if(Q.existsSync(e.file)){if(Ge(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 Wg(e,t,n,r,s,o){let i=Sl(e,t,n,r,o);if(i.verdict)return i.verdict;Q.mkdirSync(te.dirname(i.file),{recursive:!0});try{return In(i.file,()=>{let a=xl(i,s);return a||(Oe(i.file,t),{...i.shown,outcome:"imported"})})}catch(a){if(a instanceof rn)return{...i.shown,outcome:"refused",reason:"is being decided by another process. Try again."};throw a}}async function $l(e,t,n,r={}){let s;try{let o=await kl(t,()=>(s??=mi(e)).dir,r.describe);return Gg(e,o,n,r)}finally{s?.remove()}}async function kl(e,t,n){let r=[];for(let s of e)for(let o of await Bg(s,t))r.push(Dg(n?.(o.source)??o.source,o.file));if(r.reduce((s,o)=>s+[...o.entries.values()].reduce((i,a)=>i+a.size,0),0)>hi)throw new z(jg);return r.map(Hg)}function Vg(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 Rl(e,t,n){let r=t;if(r.length===0)throw new z("no bundle to import");let s=new Set,o=vs(e);for(let u of r){if(n.run!==void 0&&u.manifest.run!==n.run)throw new z(`${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 z(`${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 g=R=>R.slice(R.indexOf("/")),w=o.find(R=>g(R)===g(f));if(!w)throw new z(`${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(m=>m.manifest.run??""));if(u.size>1)throw new z(`these bundles come from different runs (${[...u].map(m=>m||"none recorded").join(", ")}). Import one run at a time`);let f=m=>Number(m.manifest.attempt)||0,g=m=>m.manifest.shard?.index??0,w=new Map;for(let m of r){let v=w.get(g(m));(!v||f(m)>f(v))&&w.set(g(m),m)}let R=r.filter(m=>f(m)<f(w.get(g(m))));for(let m of R){let v=m.manifest.shard?`shard ${m.manifest.shard.index}`:"the whole run";s.add(`${m.source} is ${v} of attempt ${f(m)}, which attempt ${f(w.get(g(m)))} ran again: left out`)}r=r.filter(m=>!R.includes(m));let $=r.filter(m=>!m.manifest.shard);if($.length>0&&r.length>1)throw new z(`${$.map(m=>m.source).join(", ")} ${$.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,...g}=a[0].report;i=g}else if(a.length>0)try{let u=ws(a.map(f=>({file:f.source,report:f.report})),{partial:!0});if(u.replaced.length>0)throw new ln(`${u.replaced.join(", ")} holds a shard that another bundle of the same attempt holds too`);i=u.report}catch(u){throw u instanceof ln?new z(`these shard bundles do not belong together: ${u.message}`):u}let c=r[0].manifest,l=qg(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={...pi(c),...u.length>0?{shards:{imported:u.map(f=>f.index).sort((f,g)=>f-g),total:u[0].total}}:{}}}return{bundles:r,report:i,warnings:s,hint:p}}function Tl(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(te.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=te.join(e,".saffron",...i.split("/"));if(zg(c)===a){r.unchanged++;continue}o.write(i,c,a),r.written++;let l=s.get(`.saffron/${te.posix.dirname(i)}`);l&&Q.writeFileSync(te.join(te.dirname(c),nn),JSON.stringify(l,null,2))}return r}function El(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 ${Vg(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}=Rl(e,t,r),c=Tl(e,s,o),l;if(o){for(let g of o.scenarios){let w=typeof g.proposalFile=="string"?g.proposalFile.split(/[\\/]/).slice(-2):[];bl.test(`proposals/${w.join("/")}`)&&(g.proposalFile=`.saffron/proposals/${w.join("/")}`)}let f=te.join(e,".saffron","reports","latest.json");Jg(f,Buffer.from(`${JSON.stringify(o,null,2)}
|
|
265
|
-
`))?l="unchanged":(fr(e,o),l="written")}let d=[],p=_t(e),u=JSON.stringify(p);for(let{b:f,p:g,conflict:w}of El(s)){if(w){d.push(w);continue}let R=Wg(e,f.files.get(g.entry),g.entry,n,r.overwrite===!0,a),$=R.reason===void 0?R:{...R,reason:ie(R.reason,1/0)};d.push($),($.outcome==="imported"||$.outcome==="unchanged"&&!$.reason)&&(p[$.file]={revision:g.revision,from:{...pi(f.manifest),...f.manifest.shard?{shard:f.manifest.shard}:{}}})}for(let[f,g]of Object.entries(p)){let w;try{w=Ge(te.join(e,f))}catch{w=void 0}w!==g.revision&&delete p[f]}return JSON.stringify(p)!==u&&Oe(vl(e),`${JSON.stringify(p,null,2)}
|
|
266
|
-
`)
|
|
267
|
-
`)
|
|
268
|
-
`)
|
|
269
|
-
`)
|
|
278
|
+
`)[0].matchAll(/^parent ([0-9a-f]+)$/gm)].map(r=>r[1])}function wm(e,t=process.env){let n=sn(e,["remote"])?.split(`
|
|
279
|
+
`)??[],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&&sn(e,["remote","get-url",r]),s,t.BUILD_REPOSITORY_URI].map(p=>p?zd(p):void 0).find(Boolean),i=sn(e,["rev-parse","--abbrev-ref","HEAD"]),a=mm(t),c=(Hd(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)||Md(t.SYSTEM_PULLREQUEST_SOURCEBRANCH)||(t.BUILD_SOURCEBRANCH?.startsWith("refs/heads/")?Md(t.BUILD_SOURCEBRANCH):void 0)||(i!=="HEAD"?i:void 0),l=sn(e,["rev-parse","HEAD"])||t.GITHUB_SHA||t.BUILD_SOURCEVERSION,d=a.sha||t.SYSTEM_PULLREQUEST_SOURCECOMMITID,u=d&&l&&la(e,l)[1]===d?d:void 0,g=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:u&&u!==l?u:void 0,run:t.GITHUB_RUN_ID&&`github:${t.GITHUB_RUN_ID}`||t.BUILD_BUILDID&&`azure:${t.BUILD_BUILDID}`||co(t),attempt:lo(t),url:g};return Object.fromEntries(Object.entries(f).filter(([,p])=>p!==void 0))}function ns(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 ym=/^(latest|shard-\d+-of-\d+)\.json$/;function bm(e){let t=ce.join(e,".saffron","reports"),n;try{n=ne.readdirSync(t).filter(s=>ym.test(s)).sort()}catch{return}let r;for(let s of n)try{let o=ne.readFileSync(ce.join(t,s)),i=JSON.parse(o.toString("utf8"));ta(i)&&(!r||i.finishedAt>r.report.finishedAt)&&(r={bytes:o,report:i})}catch{}return r}function vm(e,t,n=!1){let r=n?"saffron-summary":"saffron-bundle";return ce.join(e,".saffron","reports",t?`${r}-${sa(t)}.zip`:`${r}.zip`)}var Fd=e=>`${(e/1024**3).toFixed(1)} GB`,Bd='Keep fewer traces ("trace": "retain-on-failure" in saffron.config.json, or --trace retain-on-failure) and run again';function qd(e,t={}){let n=[],r=[],s=[],o=[],i=ce.join(e,".saffron","proposals"),a=t.summary===!0;for(let{file:m,proposal:h,revision:w,bytes:b}of a?[]:Ft(e,(y,S)=>n.push({file:Ae(e,y),problem:S}))){let y=`proposals/${Ae(i,m)}`;r.push({name:y,data:b}),s.push({entry:y,feature:h.cache.feature,scenario:h.cache.scenario,revision:w,bound:h.meta.bound}),o.push({file:m,proposal:h,bytes:b})}let c=bm(e),l=[],d=[],u=[];if(c){let m=a?Buffer.from(`${JSON.stringify({...c.report,scenarios:c.report.scenarios.map(y=>({...y,evidence:y.evidence?.filter(S=>S.kind!=="trace")}))},null,2)}
|
|
280
|
+
`):c.bytes;r.push({name:"report.json",data:m});let h=[],w=new Set;for(let y of c.report.scenarios)for(let S of y.evidence??[]){if(w.has(S.file)||a&&S.kind==="trace")continue;w.add(S.file);let x=S.file.startsWith(".saffron/artifacts/")?ne.statSync(ce.join(e,S.file),{throwIfNoEntry:!1}):void 0;if(!x?.isFile()){d.push(S.file);continue}let C=y.status==="green"&&S.kind==="trace";if(x.size>ia){if(C){u.push(S.file);continue}throw new H(`${S.file} is ${Fd(x.size)}, over the 1 GB a bundle holds per file. ${Bd}`)}h.push({e:S,size:x.size,greenTrace:C})}let b=()=>r.reduce((y,S)=>y+("data"in S?S.data.length:S.size??0)+1024,0)+h.reduce((y,S)=>y+S.size+1024,0);if(b()>Ld)for(let y of h.filter(S=>S.greenTrace))h.splice(h.indexOf(y),1),u.push(y.e.file);if(b()>Ld)throw new H(`the bundle would hold ${Fd(b())}${u.length?" even without the traces of green scenarios":""}, over the 4 GB one bundle holds. ${Bd}, or split the run into shards (--shard)`);for(let{e:y}of h){let S=ce.join(e,y.file),x;try{x=ht(ce.join(e,".saffron","artifacts"),S)?Ws(S):void 0}catch{x=void 0}if(!x||y.sha256&&x.sha256!==y.sha256){d.push(y.file);continue}let C=y.file.slice(9);r.push({name:C,file:S,crc:x.crc,size:x.size}),l.push({entry:C,sha256:x.sha256})}}if(!c&&(a||s.length===0))throw new H(`nothing to export: no run report${a?"":" and no pending proposals"} under .saffron. Run \`saffron run\` first.`);let g=c&&ts(c.report)?{index:c.report.shard.index,total:c.report.shard.total}:void 0,f={tool:"saffron",format:uo,runner:Xe(),createdAt:new Date().toISOString(),...wm(e,t.env),...g?{shard:g}:{},...c?{report:"report.json"}:{},...a?{summary:!0}:{},proposals:s,evidence:l},p=t.out??vm(e,g,a);if(ne.existsSync(p)&&ne.statSync(p).isDirectory())throw new H(`${p} is a folder: give --out a file name, such as ${ce.join(p,"saffron-bundle.zip")}`);return Kl(p,[{name:"manifest.json",data:Buffer.from(`${JSON.stringify(f,null,2)}
|
|
281
|
+
`)},...r]),{file:p,manifest:f,proposals:o,missing:d,dropped:u,unreadable:n}}var po="[a-z0-9-]+",Vd=new RegExp(`^proposals/${po}/${po}\\.json$`),xm="(?:chromium|chrome|msedge|firefox|webkit)/",Sm=new RegExp(`^artifacts/${po}/${po}/(?:${xm})?[A-Za-z0-9][A-Za-z0-9._-]*$`),ia=1024**3,da=8*1024**3,$m="the bundles to import add up to more than 8 GB unzipped",Ld=Math.min(da,yn),Dd=100,km=1024**2,Rm=6e5;function Tm(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function fa(e){let t=ce.join(e,".saffron","reports");for(let o of ne.existsSync(t)?ne.readdirSync(t):[]){let i=Number(/^run-download-(\d+)-/.exec(o)?.[1]),a=ce.join(t,o),c=i?ne.statSync(a,{throwIfNoEntry:!1}):void 0;c&&Date.now()-c.mtimeMs>36e5&&!Tm(i)&&ne.rmSync(a,{recursive:!0,force:!0})}let n=ce.join(t,`run-download-${process.pid}-${ca(4).toString("hex")}`),r=ne.mkdirSync(n,{recursive:!0});return{dir:n,remove:()=>{ne.rmSync(n,{recursive:!0,force:!0});for(let o=t;r&&o.startsWith(r);o=ce.dirname(o))try{ne.rmdirSync(o)}catch{break}}}}async function Em(e,t){let n=r=>new H(r?.name==="TimeoutError"?`cannot download ${e}: it did not finish within 10 minutes`:`cannot download ${e}: ${Un(r)}`);try{let r=await fetch(e,{redirect:"follow",signal:AbortSignal.timeout(Rm)});if(!r.ok||!r.body)throw new H(`cannot download ${e}: HTTP ${r.status}`);let s=ne.openSync(t,"w");try{let o=0;for await(let i of r.body){if(o+=i.length,o>da)throw new H(`cannot download ${e}: it is over 8 GB`);ne.writeSync(s,i)}}finally{ne.closeSync(s)}}catch(r){throw r instanceof H?r:n(r)}}async function Am(e,t){if(/^https?:\/\//i.test(e)){let s=ce.join(t(),`url-${ca(4).toString("hex")}.zip`);return await Em(e,s),[{source:e,file:s}]}let n=ne.statSync(e,{throwIfNoEntry:!1});if(!n)throw new H(`not found: ${e}`);let r=n.isDirectory()?ne.readdirSync(e,{recursive:!0}).map(String).filter(s=>/^saffron-(bundle|summary).*\.zip$/.test(ce.basename(s))).sort().map(s=>ce.join(e,s)):[e];if(r.length===0)throw new H(`no saffron-bundle*.zip or saffron-summary*.zip under ${e}`);return r.map(s=>({source:s,file:s}))}function Cm(e,t){let n;try{n=Ul(t)}catch(s){throw new H(`${e} is not a Saffron bundle: ${Un(s)}`)}let r=new Map;for(let s of n){if(r.has(s.name))throw new H(`${e} is damaged: it holds ${ue(s.name)} twice`);r.set(s.name,s)}return{source:e,file:t,entries:r}}var _m=1024*1024;function Ud(e,t,n){let r=gm("sha256"),s=ne.openSync(e,"r");try{let o=Buffer.alloc(Math.max(1,Math.min(_m,t.size)));for(let i=0;i<t.size;){let a=ne.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{ne.closeSync(s)}return r.digest("hex")}function Pm(e){try{return Ws(e).sha256}catch{return}}function Om({source:e,file:t,entries:n}){let r=f=>new H(`${e} ${f}`);for(let f of n.values()){if(f.size>ia||f.compressedSize>ia)throw r(`is damaged: ${ue(f.name)} is too large`);if(f.method!==0&&f.size>km&&f.size>Dd*f.compressedSize)throw r(`is damaged: ${ue(f.name)} claims to unzip to over ${Dd} times its size`)}let s=f=>{let p=n.get(f);if(!p)throw r(`is damaged: ${f} is missing`);let m;try{let h=p.raw();if(h.length!==p.compressedSize)throw new Error("the file ends early");m=p.method===0?h:hm.inflateRawSync(h,{maxOutputLength:Math.max(p.size,1)})}catch(h){throw r(`is damaged: ${f} cannot be read (${Un(h)})`)}if(m.length!==p.size)throw r(`is damaged: ${f} is truncated`);return m},o=f=>{let p=n.get(f);if(!(!p||p.method!==0)){if(p.compressedSize!==p.size)throw r(`is damaged: ${f} is truncated`);return p}},i=f=>{let p=o(f);if(!p)return At(s(f));try{return Ud(t,p)}catch(m){throw r(`is damaged: ${f} cannot be read (${Un(m)})`)}},a=(f,p,m)=>{let h=o(f),w=()=>new Error(ue(`${e} is damaged: ${f} changed while it was imported`,1/0));if(!h){let S=s(f);if(At(S)!==m)throw w();Ne(p,S);return}ne.mkdirSync(ce.dirname(p),{recursive:!0});let b=`${p}.${process.pid}-${ca(4).toString("hex")}.partial`,y=ne.openSync(b,"w");try{let S;try{S=Ud(t,h,x=>{for(let C=0;C<x.length;)C+=ne.writeSync(y,x,C,x.length-C)})}finally{ne.closeSync(y)}if(S!==m)throw w();ne.renameSync(b,p)}catch(S){throw ne.rmSync(b,{force:!0}),S}},c=f=>{try{return JSON.parse(s(f).toString("utf8"))}catch(p){throw p instanceof H?p: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]=ue(l[f],2048)}if(l.format>uo)throw r(`is bundle format ${l.format}, made by saffron-ai ${l.runner}; this saffron-ai (${Xe()}) reads format ${uo}. Update saffron-ai to import it`);if(l.format!==uo)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");if(l.summary!==void 0&&l.summary!==!0)throw r("is damaged: its manifest's summary is not true");if(l.summary&&l.proposals.length>0)throw r("is damaged: it is a summary and lists proposals");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 u=new Map;for(let f of l.proposals){if(!f||typeof f.entry!="string"||!Vd.test(f.entry)||typeof f.revision!="string")throw r(`is damaged: its manifest lists a proposal at ${ue(JSON.stringify(f?.entry)??"nothing")}`);typeof f.feature=="string"&&(f.feature=ue(f.feature)),typeof f.scenario=="string"&&(f.scenario=ue(f.scenario));let p=s(f.entry);if(At(p)!==f.revision)throw r(`is damaged: ${f.entry} is not the proposal its manifest names`);u.set(f.entry,p)}for(let f of l.evidence){if(!f||typeof f.entry!="string"||!Sm.test(f.entry)||typeof f.sha256!="string")throw r(`is damaged: its manifest lists evidence at ${ue(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 g;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"),p=ea(f);if(p)throw r(`is damaged: report.json ${p}`);try{vn(f)}catch(m){throw r(`is damaged: report.json cannot be shown (${Un(m)})`)}g=f}if(d&&!(g&&ts(g)))throw r("is damaged: it is a shard's bundle without the shard's report");return{source:e,manifest:l,report:g,files:u,read:s,write:a}}function Im(e,t){let n=t.headCommit??t.commit,r=sn(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)||!sn(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]=(sn(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 aa(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 Jd=e=>ce.join(e,".saffron","reports","imported.json");function on(e){let t;try{t=JSON.parse(ne.readFileSync(Jd(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 jm(e,t){try{return ne.readFileSync(e).equals(t)}catch{return!1}}function Wd(e,t,n,r,s){let o;try{o=vi(t,n)}catch(w){let b={file:`.saffron/${n}`,feature:"",scenario:""},y=`cannot be read: ${w instanceof ge?w.problem:Un(w)}`;return{verdict:{...b,outcome:"refused",reason:y},shown:b,file:ce.join(e,".saffron",n),revision:"",verified:!1}}let{proposal:i,revision:a}=o,{feature:c,scenario:l}=i.cache,d=ct(e,c,l),u={file:Ae(e,d),feature:ue(c),scenario:ue(l)},g=w=>({verdict:w,shown:u,file:d,revision:a,verified:i.meta.verified===!0}),f=w=>g({...u,outcome:"refused",reason:w});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 p=s?`. ${s}`:"";if(!ne.existsSync(ce.join(e,c)))return f(`is for ${u.feature}, which is not in this checkout${p}`);let m=jt(fe(e,c,l));if(m&&Jr(m)===Jr(i.cache))return g({...u,outcome:"unchanged",reason:"already accepted here: the committed recording is this proposal's"});let h;try{h=dt(e,i,r)}catch(w){h=`cannot be checked: ${Un(w)}`}return h?f(`does not fit this checkout: ${ue(h,1e3)}${p}`):g()}function Gd(e,t){if(ne.existsSync(e.file)){if(mt(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 Nm(e,t,n,r,s,o){let i=Wd(e,t,n,r,o);if(i.verdict)return i.verdict;ne.mkdirSync(ce.dirname(i.file),{recursive:!0});try{return sr(i.file,()=>{let a=Gd(i,s);return a||(Ne(i.file,t),{...i.shown,outcome:"imported"})})}catch(a){if(a instanceof In)return{...i.shown,outcome:"refused",reason:"is being decided by another process. Try again."};throw a}}async function Kd(e,t,n,r={}){let s;try{let o=Zd(await Qd(t,()=>(s??=fa(e)).dir,r.describe));return Fm(e,o,n,r)}finally{s?.remove()}}function Yd(e){let t=e.report&&ts(e.report)?e.report.shard:void 0,n=[...new Set([t?.browser,...(e.report?.scenarios??[]).map(r=>r.browser)].filter(Boolean))].sort();return JSON.stringify([e.manifest.repository??"",e.manifest.run??"",e.manifest.shard?.index??0,t?.suite??"",t?.total??0,t?t.by??"scenario":"",n,e.report?.baseURL??""])}function Zd(e){let t=r=>`${Yd(r)}|${Number(r.manifest.attempt)||0}`,n=new Set(e.filter(r=>!r.manifest.summary&&r.report).map(t));return e.filter(r=>!r.manifest.summary||!n.has(t(r)))}async function Qd(e,t,n){let r=[];for(let s of e)for(let o of await Am(s,t))r.push(Cm(n?.(o.source)??o.source,o.file));if(r.reduce((s,o)=>s+[...o.entries.values()].reduce((i,a)=>i+a.size,0),0)>da)throw new H($m);return r.map(Om)}function Mm(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 Xd(e,t,n){let r=t;if(r.length===0)throw new H("no bundle to import");let s=new Set,o=go(e);for(let g of r){if(n.run!==void 0&&g.manifest.run!==n.run)throw new H(`${g.source} was made by ${g.manifest.run?`run ${g.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=g.manifest.repository;if(!f&&!n.allowUnknownRepository)throw new H(`${g.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(`${g.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 p=h=>h.slice(h.indexOf("/")),m=o.find(h=>p(h)===p(f));if(!m)throw new H(`${g.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 ${m}: 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 g=new Set(r.map(y=>y.manifest.run??""));if(g.size>1)throw new H(`these bundles come from different runs (${[...g].map(y=>y||"none recorded").join(", ")}). Import one run at a time`);let f=y=>Number(y.manifest.attempt)||0,p=Yd,m=y=>y.manifest.shard?.index??0,h=y=>r.filter(S=>m(S)===m(y)&&(!y.report||p(S)===p(y))).reduce((S,x)=>f(x)>f(S)?x:S),w=r.filter(y=>f(y)<f(h(y)));for(let y of w){let S=y.manifest.shard?`shard ${y.manifest.shard.index}`:"the whole run";s.add(`${y.source} is ${S} of attempt ${f(y)}, which attempt ${f(h(y))} ran again: left out`)}r=r.filter(y=>!w.includes(y));let b=r.filter(y=>!y.manifest.shard);if(b.length>0&&r.length>1)throw new H(`${b.map(y=>y.source).join(", ")} ${b.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(g=>g.report);if(r.length===1&&a.length===1){let{shard:g,history:f,...p}=a[0].report;i=p}else if(a.length>0)try{let g=fo(a.map(f=>({file:f.source,report:f.report})),{partial:!0});if(g.replaced.length>0)throw new Dn(`${g.replaced.join(", ")} holds a shard that another bundle of the same attempt holds too`);i=g.report}catch(g){throw g instanceof Dn?new H(`these shard bundles do not belong together: ${g.message.split(`
|
|
282
|
+
`).join("; ")}`):g}let c=r[0].manifest,l=Im(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,u=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 g=r.flatMap(f=>f.manifest.shard?[f.manifest.shard]:[]);i.imported={...aa(c),...g.length>0?{shards:{imported:g.map(f=>f.index).sort((f,p)=>f-p),total:g[0].total}}:{}}}return{bundles:r,report:i,warnings:s,hint:u}}function ef(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(ce.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=ce.join(e,".saffron",...i.split("/"));if(Pm(c)===a){r.unchanged++;continue}o.write(i,c,a),r.written++;let l=s.get(`.saffron/${ce.posix.dirname(i)}`);l&&ne.writeFileSync(ce.join(e,".saffron",...i.split("/").slice(0,3),On),JSON.stringify(l,null,2))}return r}function tf(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 ${Mm(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 Fm(e,t,n,r){let{bundles:s,report:o,warnings:i,hint:a}=Xd(e,t,r);if(s.every(f=>f.manifest.summary))throw new H(`${s[0].source} is a summary (saffron export --report-only): the run's results, which saffron report --run shows, and no proposals. Import the run's full bundle (saffron-bundle*)`);let c=ef(e,s,o),l;if(o){for(let p of o.scenarios){let m=typeof p.proposalFile=="string"?p.proposalFile.split(/[\\/]/).slice(-2):[];Vd.test(`proposals/${m.join("/")}`)&&(p.proposalFile=`.saffron/proposals/${m.join("/")}`)}let f=ce.join(e,".saffron","reports","latest.json");jm(f,Buffer.from(`${JSON.stringify(o,null,2)}
|
|
283
|
+
`))?l="unchanged":(Xr(e,o),l="written")}let d=[],u=on(e),g=JSON.stringify(u);for(let{b:f,p,conflict:m}of tf(s)){if(m){d.push(m);continue}let h=Nm(e,f.files.get(p.entry),p.entry,n,r.overwrite===!0,a),w=h.reason===void 0?h:{...h,reason:ue(h.reason,1/0)};d.push(w),(w.outcome==="imported"||w.outcome==="unchanged"&&!w.reason)&&(u[w.file]={revision:p.revision,from:{...aa(f.manifest),...f.manifest.shard?{shard:f.manifest.shard}:{}}})}for(let[f,p]of Object.entries(u)){let m;try{m=mt(ce.join(e,f))}catch{m=void 0}m!==p.revision&&delete u[f]}return JSON.stringify(u)!==g&&Ne(Jd(e),`${JSON.stringify(u,null,2)}
|
|
284
|
+
`),{bundles:s.map(f=>{let{runner:p,createdAt:m,shard:h}=f.manifest;return{source:f.source,runner:p,createdAt:m,origin:aa(f.manifest),...h?{shard:{index:h.index,total:h.total}}:{}}}),warnings:[...i],proposals:d,evidence:c,...l?{report:l}:{}}}async function nf(e,t,n,r,s={}){let o=Zd(await Qd(n,()=>{throw new H("a viewed run is read from its downloaded folder")},s.describe)),{bundles:i,report:a,warnings:c,hint:l}=Xd(e,o,{run:s.run});ef(t,i,a);let d=tf(i).map(({b:u,p:g,conflict:f})=>{if(f)return{feature:f.feature,scenario:f.scenario,verified:!1,importable:!1,reason:f.reason};let p=Wd(e,u.files.get(g.entry),g.entry,r,l),m=p.verdict??Gd(p,!1),{feature:h,scenario:w}=p.shown,b={feature:h||(typeof g.feature=="string"?g.feature:""),scenario:w||(typeof g.scenario=="string"?g.scenario:""),verified:p.verified};return m?{...b,importable:!1,reason:ue(m.reason??"already pending here",1/0)}:{...b,importable:!0}});return{report:a,warnings:[...c],proposals:d,summaryOnly:i.every(u=>u.manifest.summary===!0)}}var Bm=/^\s*StepSet:/;function xn(e,t){return _t.relative(e,t).split(_t.sep).join("/")}function Lm(e,t){let n={green:0,yellow:1,red:2};return!e||n[t]>n[e]?t:e}function rs(e,t,n={}){let r=t.features??"features",s=_t.isAbsolute(r)?r:_t.join(e,r),o=_t.join(e,".saffron","reports","latest.json"),i=_t.join(e,".saffron","reports","latest.html"),a;try{a=JSON.parse(Ut.readFileSync(o,"utf8"))}catch{a=void 0}let c=new Map;for(let k of a?.scenarios??[])c.set(k.feature,[...c.get(k.feature)??[],k]);let l=new Map,d;try{l=Kt(_n(s),e)}catch(k){d=k instanceof Error?k.message:String(k)}let u=Zt(s,Yt),g=[],f=new Map,p=new Map,m={parsedFiles:new Set,owned:new Set,unreadable:d?[d]:[]};for(let k of u){let R=xn(e,k),_="";try{_=Ut.readFileSync(k,"utf8")}catch(F){g.push({path:R,name:R,scenarios:[],stepSets:0,error:String(F)}),m.unreadable.push(`${R}: ${String(F)}`);continue}let v=_.split(`
|
|
285
|
+
`),A=v.filter(F=>Bm.test(F)).length,O=v.find(F=>/^\s*Feature:/.test(F)),P=O?O.replace(/^\s*Feature:\s*/,"").trim():R,E;try{E=Ze(k,e,l)}catch(F){g.push({path:R,name:P,scenarios:[],stepSets:A,error:d??(F instanceof Error?F.message:String(F))}),m.unreadable.push(`${R}: ${F instanceof Error?F.message:String(F)}`);continue}m.parsedFiles.add(k),p.set(k,E);let T=new Set(E.map(F=>F.name)),M=new Map;for(let F of(E[0]&&c.get(E[0].featurePath))??[]){let z=Mn(F,N=>T.has(N));M.set(z,Lm(M.get(z),F.status))}let I=new Map;for(let F of E){m.owned.add(tn(e,F.featurePath,F.displayName));let z=I.get(F.name);if(z){z.rows+=1;for(let U of F.tags)z.tags.includes(U)||(z.tags.push(U),f.set(U,(f.get(U)??0)+1));continue}let N=fe(e,F.featurePath,F.name);m.owned.add(N),m.owned.add(ct(e,F.featurePath,F.name));let L="missing",G;if(Ut.existsSync(N))try{let U=He(N);L=U&&lr(F,U)?"valid":"stale"}catch(U){L="invalid",G=U instanceof ge?U.problem:U instanceof Error?U.message:String(U)}I.set(F.name,{name:F.name,line:F.line,tags:[...F.tags],outline:Object.keys(F.params).length>0,rows:1,cached:L!=="missing",cacheState:L,...G?{cacheProblem:G}:{},proposal:Ut.existsSync(ct(e,F.featurePath,F.name)),lastStatus:M.get(F.name)});for(let U of F.tags)f.set(U,(f.get(U)??0)+1)}g.push({path:R,name:P,scenarios:[...I.values()],stepSets:A})}let h=[],w=on(e),b=Ft(e,(k,R)=>h.push({file:xn(e,k),problem:R})).map(({file:k,proposal:R,revision:_})=>({file:xn(e,k),feature:R.cache.feature,scenario:R.cache.scenario,mode:R.meta.mode,createdAt:R.meta.createdAt,verified:R.meta.verified,proofError:R.meta.proofError,stale:R.meta.bound?dt(e,R,l):void 0,unbound:R.meta.bound?void 0:!0,revision:_,adaptations:R.meta.adaptations??[],narrative:R.meta.narrative,suggestedFeatureEdit:R.meta.suggestedFeatureEdit,recordedFor:R.meta.recordedFor,aiCalls:R.meta.usage?.aiCalls??0,costUsd:R.meta.usage&&ft({costUsd:R.meta.usage.costUsd??0,aiCalls:R.meta.usage.aiCalls})?R.meta.usage.costUsd:void 0,importedFrom:w[xn(e,k)]?.revision===_?w[xn(e,k)].from:void 0})).sort((k,R)=>k.file.localeCompare(R.file)),y;try{y=Mt(e,r,l,p)}catch{y={steps:[],stepSets:[],scannedFiles:0,scannedCaches:0}}let S=Um(e),x=Gr(e,Math.max(100,n.historyLimit??30)),C=x.filter(k=>!k.partial).slice(-(n.historyLimit??30)).map(k=>({startedAt:k.startedAt,green:k.green,yellow:k.yellow,red:k.red,passRate:Nn(k,k.scenarios),aiCalls:k.aiCalls,costUsd:ft(k)?k.costUsd:void 0})),$=_t.join(e,"saffron.config.json");return{tool:"saffron",version:Xe(),projectRoot:e,packageInstalled:Ut.existsSync(_t.join(e,"node_modules","saffron-ai")),config:{file:Ut.existsSync($)?"saffron.config.json":void 0,effective:hl(t)},featuresDir:(_t.relative(e,s)||".").split(_t.sep).join("/"),features:g,tags:[...f.entries()].map(([k,R])=>({tag:k,scenarios:R})).sort((k,R)=>k.tag.localeCompare(R.tag)),proposals:b,unreadableProposals:h,lastRun:a?{startedAt:a.startedAt,finishedAt:a.finishedAt,totals:{...a.totals,costUsd:ft(a.totals)?a.totals.costUsd:void 0},reportHtml:Ut.existsSync(i)?xn(e,i):void 0,...a.browsers?.length?{browsers:a.browsers}:{},attention:a.scenarios.filter(k=>k.status!=="green").map(k=>({feature:k.feature,scenario:k.scenario,baseScenario:Mn(k,R=>g.some(_=>_.path===k.feature&&_.scenarios.some(v=>v.name===R))),status:k.status,...k.browser?{browser:k.browser}:{},error:k.status==="red"?k.error?.split(`
|
|
286
|
+
`)[0]:void 0,failedStep:(k.steps??[]).find(R=>R.status==="failed")?.gherkin??k.evidence?.find(R=>R.step)?.step,evidence:(k.evidence??[]).filter(R=>R.kind==="trace"?Ut.existsSync(_t.join(e,R.file)):mn(e,R)!==void 0).map(R=>({kind:R.kind,file:R.file,...R.step?{step:R.step}:{},...R.sha256?{sha256:R.sha256}:{},...R.proof===!0?{proof:!0}:{},...typeof R.session=="string"?{session:R.session}:{}}))})).sort((k,R)=>k.status===R.status?0:k.status==="red"?-1:1)}:void 0,history:C,quality:Td(g,x),vocabulary:{steps:y.steps.length,recorded:y.steps.filter(k=>k.status==="recorded").length,unrecorded:y.steps.filter(k=>k.status==="unrecorded").length,stepSets:y.stepSets.length,divergent:y.steps.filter(k=>k.status==="divergent").map(k=>k.text),duplicateWordings:S.slice(0,50)},data:(()=>{let k=Ve(),R=[],_=new Set;for(let[v,A]of p)for(let O of A)for(let P of Gt(st(O)))if(!_.has(P)){_.add(P);try{ks(P)}catch(E){R.push({ref:P,reason:E instanceof Error?E.message:String(E),feature:xn(e,v),scenario:O.name})}}return{dir:xn(e,k.dir),env:k.env,files:Ut.existsSync(k.dir)?Ut.readdirSync(k.dir).filter(v=>/\.(json|csv)$/.test(v)).sort():[],unresolved:R}})(),...(()=>{let k=Hs(e,r,m),R=k.unreadable.length===0;return{orphans:R?k.orphans:[],orphanScan:{complete:R,errors:k.unreadable}}})()}}function sf(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(`
|
|
287
|
+
`)[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.orphanScan.complete?e.orphans.length&&console.log(`${e.orphans.length} recording(s) belong to no scenario: run \`saffron prune\` to see them`):console.log(`orphaned recordings not checked: ${e.orphanScan.errors[0]}`),(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 Dm=/^(<[^>]+>|\{env:[^}]+\}|\{date[^}]*\})$/;function rf(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 Um(e){let t;try{t=Nt(e)}catch{return[]}let n=new Map;for(let r of t.steps.values()){if(r.actions.length===0)continue;let s=Te(r.gherkin),o=Is(s).pattern,i=[...s.matchAll(/"([^"]*)"/g)].map(g=>g[1]),a=g=>g!==void 0&&(i.includes(g)||Dm.test(g))?"\xABarg\xBB":g,c=r.actions.map(g=>{let{pageFingerprint:f,value:p,promptText:m,...h}=g;return{...h,value:a(p),promptText:a(m)}}),l=JSON.stringify(c),d=r.actions.map(g=>`${g.action}${rf(g.target)?` ${rf(g.target)}`:g.url?` ${g.url}`:""}`).join(" \xB7 "),u=n.get(l)??{steps:new Map,actions:d};u.steps.has(o)||u.steps.set(o,r.gherkin),n.set(l,u)}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 of(e,t){let n=new zm({name:"saffron",version:Xe()},{capabilities:{tools:{}}});n.setRequestHandler(Vm,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(qm,async r=>Jm(r.params.name,r.params.arguments,e)),await n.connect(new Hm)}function Jm(e,t,n){let r=i=>({content:[{type:"text",text:JSON.stringify(i,null,2)}]}),s=ye(n),o=s.features??nr.features;if(e==="search_steps"){let i=Mt(n,o),a=typeof t?.query=="string"?t.query:void 0,c=a?Ns(i,a):i;return r({steps:c.steps.map(({sessions:l,recordings:d,...u})=>u),scannedFiles:c.scannedFiles,scannedCaches:c.scannedCaches})}if(e==="list_step_sets"){let i=Mt(n,o);return r({stepSets:i.stepSets})}return e==="project_status"?r(rs(n,s)):{content:[{type:"text",text:`Unknown tool: ${e}`}],isError:!0}}import{query as Wm}from"@anthropic-ai/claude-agent-sdk";function af(e,t){let n=t.steps.map(s=>`- [${s.status}] ${s.keyword} ${s.text}`).join(`
|
|
270
288
|
`),r=t.stepSets.map(s=>`- StepSet ${s.name}
|
|
271
289
|
${s.steps.map(o=>` ${o}`).join(`
|
|
272
290
|
`)}`).join(`
|
|
273
|
-
`);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:
|
|
274
|
-
${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.
|
|
275
|
-
`)}var
|
|
276
|
-
`}import
|
|
277
|
-
${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
|
|
278
|
-
`),A=kh(y);if(!h.uri.endsWith(".saffron")){p.sendDiagnostics({uri:h.uri,diagnostics:A});return}let E=new Map;for(let P=0;P<y.length;P++){let O=y[P],M={start:{line:P,character:0},end:{line:P,character:O.length}},T=O.match(vi);T&&!g.has(T[3])&&A.push({range:M,severity:mr.Error,source:"saffron",message:`StepSet "${T[3]}" is not defined anywhere in the project.`});let C=O.match(wh);if(C){let _=g.get(C[1]),F=de.relative(r,Wt(h.uri)).replace(/\\/g,"/");(E.has(C[1])||_&&_.file.replace(/\\/g,"/")!==F)&&A.push({range:M,severity:mr.Error,source:"saffron",message:`StepSet "${C[1]}" is defined twice. Set names are project-wide. If this line was meant to INVOKE the set, remove the colon: "StepSet ${C[1]}".`}),E.set(C[1],P)}let j=O.trim();if(j&&!T&&!C){for(let[_]of g)if(j.toLowerCase()===_.toLowerCase()){A.push({range:M,severity:mr.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 L=O.match(Wl);if(L&&b(L[3])!=="recorded"){for(let _ of f.steps)if(!(_.text===L[3]||_.status==="unrecorded")&&yh(_.text,L[3])>=.7){A.push({range:{start:{line:P,character:O.indexOf(L[3])},end:{line:P,character:O.length}},severity:mr.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:h.uri,diagnostics:A})}p.onInitialize(h=>{if(n.rootFromClient){let y=h.workspaceFolders?.[0]?.uri??h.rootUri??void 0;if(y&&y.startsWith("file:")){let A=Wt(y);Ze.existsSync(A)&&(o=r=A,s=Gl(A)??t)}}return i=h.capabilities.workspace?.didChangeWatchedFiles?.dynamicRegistration===!0,a=h.initializationOptions?.runLenses===!0,S(),{capabilities:{textDocumentSync:uh.Incremental,completionProvider:{triggerCharacters:[" ",":","."]},definitionProvider:!0,hoverProvider:!0,...a?{codeLensProvider:{resolveProvider:!1}}:{}}}}),p.onCodeLens(h=>{let y=u.get(h.textDocument.uri);if(!a||!y||!y.uri.startsWith("file:"))return[];let A=Wt(y.uri),E=vh(A,o);return E?!A.endsWith(".saffron")&&!Ze.existsSync(de.join(E,"saffron.config.json"))?[]:Sh(A,y.getText(),E):[]}),p.onInitialized(()=>{if(!i)return;let h=[...["**/*.saffron","**/*.feature","**/saffron.config.json","**/.saffron/cache/**","**/data/**"].map(y=>({globPattern:y})),{globPattern:"**",kind:hh.Delete}];p.client.register(gh.type,{watchers:h}).catch(()=>{i=!1})}),p.onCompletion(h=>{let y=u.get(h.textDocument.uri);if(!y)return[];c(y.uri);let A=y.getText({start:{line:h.position.line,character:0},end:h.position}),E=Rh(A);return E||Th(y.uri,A,h.position.line,f)}),p.onDefinition(h=>{let y=u.get(h.textDocument.uri);if(!y)return;c(y.uri);let A=y.getText({start:{line:h.position.line,character:0},end:{line:h.position.line+1,character:0}}).replace(/\n$/,""),E=Kl(A,h.position.character);if(E){let C=$h(E.ref);return C?{uri:bi(C.file).href,range:{start:{line:C.line,character:0},end:{line:C.line,character:0}}}:void 0}let P=Yl(A,h.position.character);if(P){let C=Zl(r,P.name);return C?{uri:bi(C.file).href,range:{start:{line:C.line,character:0},end:{line:C.line,character:0}}}:void 0}let O=A.match(vi);if(!O)return;let M=g.get(O[3]);return M?{uri:bi(de.join(r,M.file)).href,range:{start:{line:M.line-1,character:0},end:{line:M.line-1,character:0}}}:void 0}),p.onHover(h=>{let y=u.get(h.textDocument.uri);if(!y)return;c(y.uri);{let O=y.getText({start:{line:h.position.line,character:0},end:{line:h.position.line+1,character:0}}).replace(/\n$/,""),M=Kl(O,h.position.character);if(M)return{contents:{kind:"markdown",value:Xl(M.ref)}};let T=Yl(O,h.position.character);if(T){let C=Zl(r,T.name),j=C?`defined in ${de.relative(r,C.file)} (line ${C.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:${T.name}}** ${j}.`}}}}let A=y.getText({start:{line:h.position.line,character:0},end:{line:h.position.line+1,character:0}}).replace(/\n$/,""),E=A.match(vi);if(E){let O=f.stepSets.find(T=>T.name===E[3]);if(!O)return;let M=O.steps.map(T=>`- ${Si[b(T)??"unrecorded"][0]} ${T}`).join(`
|
|
279
|
-
`);return{contents:{kind:Jl.Markdown,value:`**StepSet ${O.name}** expands to:
|
|
291
|
+
`);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 for .saffron output, invoke with a line reading exactly \`StepSet <name>\` instead of repeating their steps:
|
|
292
|
+
${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. In .saffron, reuse a StepSet for a repeated flow (first step a guard, last step an exit assertion). Definition uses a colon (StepSet: Name), invocation does not (StepSet Name). If the requirements request .feature, use standard Gherkin without StepSets or file-backed Examples.",'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.","7. One independently testable behavior per scenario and one clear intent per step; keep necessary setup and waits without a fixed step-count limit. When translating existing tests, preserve intended coverage but split independent changes. Do not assume every intermediate value must differ from every earlier value.",'8. Name every captured value explicitly, e.g. I record the displayed price for the selected date as "beforePrice", then the displayed price for the selected date should differ from "beforePrice". Reuse that exact name; never say only "the price I noted". Capture before the change, compare the same target afterwards, and never recreate the baseline or change application state inside a final assertion.','9. Captures store text, not parsed numbers. For an amount change, capture amount-only text rather than a whole label containing currency, date or guest count. Calling a capture "numeric" does not enable arithmetic.',"10. Use observable waits from the supplied evidence: the relevant UI state or API response, not a fixed sleep or an unspecified 'finished loading'. Distinguish a selector's option code (GBP) from the price's display symbol (\xA3); selecting a currency alone does not prove prices refreshed.","11. Use {env:VAR} for secrets, existing {data:file.key} references for shared data, and named captures for changing display values. Establish the relevant starting state and document required fixtures. Do not invent data-file keys or application behavior.","12. This is a draft-only call with no browser inspection or execution. Use supplied observations and vocabulary; flag missing UI evidence, prerequisites, or uncertain expectations in Gherkin comments for inspection before recording. Never claim the draft was inspected, recorded, verified, or passed. Completion requires targeted recording, review of verified proposals for faithful assertions, acceptance, and replay with --no-agent; those happen after this call.","","REQUIREMENTS:",e.trim()].filter(s=>s!==void 0).join(`
|
|
293
|
+
`)}var cf="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 df(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:cf,prompt:af(e,t),model:n,maxTurns:1,mcpServers:{},mcpToken:"",usage:s,lastOutput:a=>{o=a},finished:()=>!1}),{content:lf(o),usage:s};let i=Wm({prompt:af(e,t),options:{model:n,maxTurns:1,tools:[],persistSession:!1,settingSources:[],strictMcpConfig:!0,settings:{disableClaudeAiConnectors:!0},allowedTools:[],systemPrompt:cf}});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:lf(o),usage:s}}function lf(e){return e.replace(/^\s*```(?:gherkin|saffron)?\s*\n/,"").replace(/\n```\s*$/,"").trim()+`
|
|
294
|
+
`}import bt from"node:fs";import{fileURLToPath as Sn,pathToFileURL as ga}from"node:url";import he from"node:path";import{createConnection as Xm,ProposedFeatures as ew,TextDocuments as tw,TextDocumentSyncKind as nw,DidChangeWatchedFilesNotification as rw,WatchKind as sw,CompletionItemKind as $n,InsertTextFormat as bf,DiagnosticSeverity as os,MarkupKind as vf}from"vscode-languageserver/node";import{TextDocument as ow}from"vscode-languageserver-textdocument";import ff from"node:path";var ss=class extends Error{},ua=new Set(["and","or","not","(",")"]);function Gm(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":ua.has(s.toLowerCase())?s.toLowerCase():s.startsWith("@")?s:`@${s}`)}function Km(e){let t=Gm(e),n=0,r=()=>t[n],s=d=>{throw new ss(`--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 u=a(),g=d;d=f=>g(f)||u(f)}return d},a=()=>{let d=c();for(;r()==="and";){n++;let u=c(),g=d;d=f=>g(f)&&u(f)}return d},c=()=>{let d=r();if(d===void 0)return s("expected a tag at the end");if(d==="not"){n++;let u=c();return g=>!u(g)}if(d==="("){n++;let u=i();return r()!==")"?s("missing a closing parenthesis"):(n++,u)}return ua.has(d)?s(`expected a tag, found "${d}"`):(n++,u=>u.has(d))},l=i();return n<t.length?s(ua.has(t[n])?`unexpected "${t[n]}"`:`unexpected "${t[n]}": with and, not or parentheses, join every tag with and/or`):l}function uf(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(Km);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 pf(e,t){return t?e.filter(n=>t.matches(n.tags)):e}function gf(e,t){return[...t??[],e]}var Ym=new RegExp(`^(.+?(?:${oi.map(e=>e.replace(".","\\.")).join("|")})):(.+)$`),pa=/^\d+(?::\d+)*$/;function hf(e){let t=[],n=new Map;for(let r of e){let s=Ym.exec(r);if(!s){t.push(r);continue}let o=pa.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 zn=class extends Error{};function mf(e,t){let n=o=>`${o.featurePath}
|
|
295
|
+
${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 wf(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 Zm(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"} ${wf(s)}.`,i=c=>{throw new zn(`${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 Qm(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 zn(`${e}:${t} names no scenario.${o.length===0?" It has no scenarios.":` Its scenario${o.length===1?" is":"s are"} ${wf(o)}.`}`)}function yf(e,t,n,r){let s=new Map,o=new Map;for(let[a,c]of n){let l=ff.resolve(t,a);if(r.has(l))continue;let{blocks:d,lineCount:u}=Bc(l,t),g=ff.relative(t,l),f=s.get(g)??new Map;for(let p of c){if(typeof p=="string"&&!d.some(b=>b.kind==="scenario"&&b.name===p)&&e.some(b=>b.featurePath===g&&b.displayName===p)){o.set(g,(o.get(g)??new Set).add(p));continue}let{line:h,block:w}=typeof p=="number"?Zm(a,p,d,u):Qm(a,p,d);f.set(h,`${a}:${p} is in Scenario Outline "${w.name}", whose Examples have no rows yet: nothing to run`)}s.set(g,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(u=>u.featurePath===a&&(u.line===l||u.exampleLine===l)))throw new zn(`${d}.`);return i}var xf=/^(\s*)(Given|When|Then|And|But|\*)\s+(.+?)\s*$/,iw=/^\s*StepSet:\s*(.+?)\s*$/,ha=/^(\s*)(StepSet)\s+([^\s:].*?)\s*$/,ma={recorded:"\u25CF recorded: replays at zero tokens",divergent:"\u25CF divergent: same text, different recordings",unrecorded:"\u25CB written, not recorded yet"};function aw(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 Sf(e){try{return JSON.parse(bt.readFileSync(he.join(e,"saffron.config.json"),"utf8"))}catch{return{}}}function $f(e){try{let t=JSON.parse(bt.readFileSync(he.join(e,"saffron.config.json"),"utf8"));return typeof t.features=="string"&&t.features.trim()!==""?t.features:void 0}catch{return}}function pr(e,t){let n=he.dirname(e),r=he.resolve(t);for(;;){if(bt.existsSync(he.join(n,"saffron.config.json")))return n;if(n===r||he.dirname(n)===n)return t;n=he.dirname(n)}}function is(e,t,n){return e.recordings?e.recordings[nn(Ke([t],n)[0],t)]??"unrecorded":t===e.text?e.status:e.sessions?.[t]??"unrecorded"}function cw(e,t,n){return`${ma[is(e,t,n)]}
|
|
280
296
|
|
|
281
|
-
${
|
|
297
|
+
Used in ${e.usage} place(s): ${e.files.join(", ")}${e.fromStepSet?`
|
|
282
298
|
|
|
283
|
-
|
|
299
|
+
Defined in StepSet **${e.fromStepSet}**`:""}`}function Ef(e,t,n={}){let r=e,s=t,o=e,i=!1,a=!1,c=R=>{if(!R.startsWith("file:"))return;let _=pr(Sn(R),o);if(_===r)return;b(_);let v=h.get(_);if(!v||!i||w.has(_))return S();({vocab:f,registry:p,files:m}=v);for(let A of g.all())d(A)&&k(A)},l=R=>{if(!R.startsWith("file:"))return;let _=Sn(R),v=pr(_,o);h.get(v)?.files.has(_)||w.add(v)},d=R=>!R.uri.startsWith("file:")||pr(Sn(R.uri),o)===r,u=Xm(ew.all,process.stdin,process.stdout),g=new tw(ow),f={steps:[],stepSets:[],scannedFiles:0,scannedCaches:0},p=new Map,m=new Set,h=new Map,w=new Set,b=R=>{r=R,s=$f(R)??(bt.existsSync(he.join(R,"saffron.config.json"))?"features":t);try{let _=Sf(R);Ot(R,_.dataDir,process.env.SAFFRON_ENV??_.env)}catch(_){u.console.warn(`saffron vocabulary rebuild: ${String(_)}`)}},y,S=()=>{try{let R=he.isAbsolute(s)?s:he.join(r,s),_=Sf(r);Ot(r,_.dataDir,process.env.SAFFRON_ENV??_.env),p=Kt(_n(R),r),f=Mt(r,s,p),m=new Set(hi(R)),h.set(r,{vocab:f,registry:p,files:m}),w.delete(r)}catch(R){u.console.warn(`saffron vocabulary rebuild: ${String(R)}`),{vocab:f,registry:p,files:m}=h.get(r)??{vocab:{steps:[],stepSets:[],scannedFiles:0,scannedCaches:0},registry:new Map,files:new Set}}for(let R of g.all())d(R)&&k(R)},x=()=>{clearTimeout(y),y=setTimeout(()=>{let R=r,_=new Set(g.all().filter(v=>v.uri.startsWith("file:")).map(v=>pr(Sn(v.uri),o)));for(let v of h.keys())!_.has(v)&&v!==R&&h.delete(v);_.delete(R);for(let v of[..._,R])b(v),S()},300)};function C(R){let _=Te(R);return f.steps.find(v=>v.text===_)}function $(R,_){let v=C(R);return v&&is(v,R,_)}function k(R){let _=R.getText().split(`
|
|
300
|
+
`),v=gw(_);if(!R.uri.endsWith(".saffron")){u.sendDiagnostics({uri:R.uri,diagnostics:v});return}let A=As(_,f.stepSets,new Set(Ir(R.getText()).map(P=>P.line-1))),O=new Map;for(let P=0;P<_.length;P++){let E=_[P],T={start:{line:P,character:0},end:{line:P,character:E.length}},M=E.match(ha);M&&!p.has(M[3])&&v.push({range:T,severity:os.Error,source:"saffron",message:`StepSet "${M[3]}" is not defined anywhere in the project.`});let I=E.match(iw);if(I){let N=p.get(I[1]),L=he.relative(r,Sn(R.uri)).replace(/\\/g,"/");(O.has(I[1])||N&&N.file.replace(/\\/g,"/")!==L)&&v.push({range:T,severity:os.Error,source:"saffron",message:`StepSet "${I[1]}" is defined twice. Set names are project-wide. If this line was meant to INVOKE the set, remove the colon: "StepSet ${I[1]}".`}),O.set(I[1],P)}let F=E.trim();if(F&&!M&&!I){for(let[N]of p)if(F.toLowerCase()===N.toLowerCase()){v.push({range:T,severity:os.Warning,source:"saffron",message:`Did you mean "StepSet ${N}"? Invoking a step set needs the StepSet keyword, like a step needs Given/When/Then.`});break}}let z=E.match(xf);if(z&&$(z[3],A[P])!=="recorded"){let N=Te(z[3]);for(let L of f.steps)if(!(L.text===N||is(L,L.text,A[P])==="unrecorded")&&aw(L.text,N)>=.7){v.push({range:{start:{line:P,character:E.indexOf(z[3])},end:{line:P,character:E.length}},severity:os.Information,source:"saffron",message:`Similar to the ${is(L,L.text,A[P])} step "${L.text}" (\xD7${L.usage}). Reusing the exact wording replays at zero tokens; a new wording costs a fresh AI recording.`});break}}}u.sendDiagnostics({uri:R.uri,diagnostics:v})}u.onInitialize(R=>{if(n.rootFromClient){let _=R.workspaceFolders?.[0]?.uri??R.rootUri??void 0;if(_&&_.startsWith("file:")){let v=Sn(_);bt.existsSync(v)&&(o=r=v,s=$f(v)??t)}}return i=R.capabilities.workspace?.didChangeWatchedFiles?.dynamicRegistration===!0,a=R.initializationOptions?.runLenses===!0,S(),{capabilities:{textDocumentSync:nw.Incremental,completionProvider:{triggerCharacters:[" ",":","."]},definitionProvider:!0,hoverProvider:!0,...a?{codeLensProvider:{resolveProvider:!1}}:{}}}}),u.onCodeLens(R=>{let _=g.get(R.textDocument.uri);if(!a||!_||!_.uri.startsWith("file:"))return[];let v=Sn(_.uri),A=dw(v,o);return A?!v.endsWith(".saffron")&&!bt.existsSync(he.join(A,"saffron.config.json"))?[]:fw(v,_.getText(),A):[]}),u.onInitialized(()=>{if(!i)return;let R=[...["**/*.saffron","**/*.feature","**/saffron.config.json","**/.saffron/cache/**","**/data/**"].map(_=>({globPattern:_})),{globPattern:"**",kind:sw.Delete}];u.client.register(rw.type,{watchers:R}).catch(()=>{i=!1})}),u.onCompletion(R=>{let _=g.get(R.textDocument.uri);if(!_)return[];c(_.uri);let v=_.getText({start:{line:R.position.line,character:0},end:R.position}),A=hw(v);if(A)return A;let O=_.getText({start:R.position,end:{line:R.position.line+1,character:0}}).replace(/\r?\n$/,"");return mw(_.uri,v,R.position.line,f,O,As(_.getText().split(`
|
|
301
|
+
`),f.stepSets,new Set(Ir(_.getText()).map(P=>P.line-1)))[R.position.line])}),u.onDefinition(R=>{let _=g.get(R.textDocument.uri);if(!_)return;c(_.uri);let v=_.getText({start:{line:R.position.line,character:0},end:{line:R.position.line+1,character:0}}).replace(/\n$/,""),A=kf(v,R.position.character);if(A){let M=pw(A.ref);return M?{uri:ga(M.file).href,range:{start:{line:M.line,character:0},end:{line:M.line,character:0}}}:void 0}let O=Rf(v,R.position.character);if(O){let M=Tf(r,O.name);return M?{uri:ga(M.file).href,range:{start:{line:M.line,character:0},end:{line:M.line,character:0}}}:void 0}let P=v.match(ha);if(!P)return;let E=p.get(P[3]);return E?{uri:ga(he.join(r,E.file)).href,range:{start:{line:E.line-1,character:0},end:{line:E.line-1,character:0}}}:void 0}),u.onHover(R=>{let _=g.get(R.textDocument.uri);if(!_)return;c(_.uri);{let E=_.getText({start:{line:R.position.line,character:0},end:{line:R.position.line+1,character:0}}).replace(/\n$/,""),T=kf(E,R.position.character);if(T)return{contents:{kind:"markdown",value:Af(T.ref)}};let M=Rf(E,R.position.character);if(M){let I=Tf(r,M.name),F=I?`defined in ${he.relative(r,I.file)} (line ${I.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:${M.name}}** ${F}.`}}}}let v=_.getText({start:{line:R.position.line,character:0},end:{line:R.position.line+1,character:0}}).replace(/\n$/,""),A=As(_.getText().split(`
|
|
302
|
+
`),f.stepSets,new Set(Ir(_.getText()).map(E=>E.line-1)))[R.position.line],O=v.match(ha);if(O){let E=f.stepSets.find(I=>I.name===O[3]);if(!E)return;let T=Ke(E.steps,A),M=E.steps.map((I,F)=>`- ${ma[$(I,T[F])??"unrecorded"][0]} ${I}`).join(`
|
|
303
|
+
`);return{contents:{kind:vf.Markdown,value:`**StepSet ${E.name}** expands to:
|
|
284
304
|
|
|
285
|
-
|
|
286
|
-
`),
|
|
287
|
-
`).findIndex(i=>new RegExp(`^\\s*(?:export\\s+)?${t}\\s*=`).test(i));if(o!==-1)return{file:r,line:o}}}function
|
|
288
|
-
`)}));
|
|
305
|
+
${M}`}}}let P=v.match(xf);if(P){let E=C(P[3]);return E?{contents:{kind:vf.Markdown,value:cw(E,P[3],A)}}:void 0}}),g.onDidOpen(R=>{if(l(R.document.uri),R.document.uri.startsWith("file:")){let _=Sn(R.document.uri);pr(_,o)===r&&!m.has(_)&&x()}c(R.document.uri),k(R.document)}),g.onDidClose(R=>l(R.document.uri)),g.onDidChangeContent(R=>{c(R.document.uri),k(R.document)}),g.onDidSave(()=>x()),u.onDidChangeWatchedFiles(()=>x()),g.listen(u),u.listen()}var lw="saffron.runScenario";function dw(e,t){let n=pr(e,t),r=he.relative(he.resolve(t),n);return r.split(/[\\/]/)[0]===".."||he.isAbsolute(r)?void 0:n}function fw(e,t,n){let r=he.relative(n,e).split(he.sep).join("/");return r.startsWith("../")||he.isAbsolute(r)?[]:Ir(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&&!pa.test(o)?`${r}:${o}`:`${r}:${s}`;return{range:i,command:{title:c,command:lw,arguments:[{root:n,target:d,scenario:o,mode:l}]}}};return[a("\u25B6 Run scenario","run"),a("Replay only","replay"),a("Headed","headed")]})}function kf(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 uw=e=>/^\s*Examples:/.test(e);function Af(e,t=!1){let{env:n}=Ve(),r=n?` (environment "${n}")`:"";try{if(t||!e.includes(".")){let{headers:i,rows:a}=Rs(e);return`**{data:${e}}** ${a.length} Examples row(s), columns ${i.map(c=>`\`${c}\``).join(", ")}${r}.`}let s=fn(e);return Array.isArray(Rn(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 pw(e){let{dir:t,env:n}=Ve(),[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=he.join(t,c);if(!bt.existsSync(l))continue;let d=bt.readFileSync(l,"utf8").split(`
|
|
306
|
+
`),u=i?d.findIndex(g=>g.includes(`"${i}"`)):0;if(u>=0)return{file:l,line:u};a??={file:l,line:0}}return a}function gw(e){let t=[];return e.forEach((n,r)=>{for(let s of n.matchAll(/\{data:([A-Za-z0-9_.-]+)\}/g)){let o=Af(s[1],uw(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:os.Error,source:"saffron",message:o.replace(/\*\*/g,"")})}}),t}function hw(e){let t=e.match(/\{data:([A-Za-z0-9_.-]*)$/);if(!t)return;let n=t[1],{dir:r}=Ve(),s=n.split(".");if(s.length===1)return(bt.existsSync(r)?[...new Set(bt.readdirSync(r).filter(i=>/\.(json|csv)$/.test(i)).map(i=>i.split(".")[0]))].sort():[]).map(i=>({label:i,kind:$n.File,detail:"data file",insertText:i}));try{let o=Rn(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"?$n.Module:$n.Value,detail:Array.isArray(a)?`list of ${a.length}`:a!==null&&typeof a=="object"?"object":JSON.stringify(a),insertText:i}))}catch{return[]}}function Rf(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 Tf(e,t){for(let n of[".env",".env.example"]){let r=he.join(e,n);if(!bt.existsSync(r))continue;let o=bt.readFileSync(r,"utf8").split(`
|
|
307
|
+
`).findIndex(i=>new RegExp(`^\\s*(?:export\\s+)?${t}\\s*=`).test(i));if(o!==-1)return{file:r,line:o}}}function mw(e,t,n,r,s="",o){let i=e.endsWith(".saffron"),a=t.length+s.trimEnd().length,c=p=>({start:{line:n,character:p},end:{line:n,character:a}}),l=/^\s*StepSet\s+/.exec(t);if(l&&i)return r.stepSets.map(p=>({textEdit:{range:c(l[0].length),newText:p.name},label:p.name,kind:$n.Function,detail:`step set \xB7 ${p.steps.length} step(s) \xB7 \xD7${p.usage}`,documentation:p.steps.join(`
|
|
308
|
+
`)}));let d=/^\s*(?:Given|When|Then|And|But|\*)\s+(As "[^"]+"\s+)?/,u=d.test(t)?d.exec(t+s):null;if(u&&u[0].length>t.length)return[];if(u)return r.steps.map((p,m)=>({textEdit:{range:c(u[0].length),newText:p.text},label:p.text,kind:$n.Text,detail:`${ma[is(p,`${u[1]??""}${p.text}`,o)]} \xB7 \xD7${p.usage}`,sortText:String(m).padStart(5,"0"),filterText:p.text}));let f=t.replace(/^\s*/,"").trimEnd().toLowerCase().replace(/\s+/g,"");if(f.length>0&&("stepset:".startsWith(f)||f.startsWith("stepset"))&&i){let p={start:{line:n,character:t.length-t.replace(/^\s*/,"").length},end:{line:n,character:t.length}},m=[{label:"StepSet: \u2026",kind:$n.Keyword,detail:"define a reusable step set",documentation:`StepSet: Name
|
|
289
309
|
Given \u2026
|
|
290
310
|
When \u2026
|
|
291
311
|
|
|
292
|
-
Invoke it anywhere with: StepSet Name`,filterText:"step set stepset:",sortText:"0",insertTextFormat:
|
|
293
|
-
`),filterText:`step set ${l.name}`,sortText:`1${l.name}`,textEdit:{range:a,newText:`StepSet ${l.name}`}});return c}return[]}async function xi(e,t,n){let r=[...e],s;if(await Promise.all(Array.from({length:Math.min(t,r.length)},async(o,i)=>{for(let a=r.shift();a&&!s;a=r.shift())for(let c of a){if(s)return;try{await n(c,i)}catch(l){s??={error:l};return}}})),s)throw s.error}function ed(e,t){let n=new Map;for(let r of e)n.set(t(r),[...n.get(t(r))??[],r]);return[...n.values()]}import mt from"node:fs";import Jh from"node:net";import wt from"node:path";import{chromium as Wh,devices as Ri,firefox as Vh,webkit as Gh}from"playwright";import Eh from"node:path";var Ah=5e3,_h=new Set(["click","press","selectOption","check","uncheck","hover","dragTo"]);function sd(e){return e.mode==="heal"||e.mode==="refine"}function od(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 td=e=>`${e} action${e===1?"":"s"}`,nd=e=>e.map(Je).join("; "),Ss=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: ${td(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: ${nd(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 ${td(r.length)} the agent performed ${s}: ${nd(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<=Ah;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=>_h.has(s.action));r&&(this.lastOpener=r,this.lastOpenerAt=Date.now(),this.pendingTabOpen&&(r.opensTab=!0,this.pendingTabOpen=!1,this.pendingTabFallback=void 0))}},ht=e=>e.replace(/\\(['"\\])/g,"$1");function Ih(e){let t=e.match(/'((?:[^'\\]|\\.)*)'/);return t?ht(t[1]):void 0}function Ch(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 $i(e,t){let n=/^'((?:[^'\\]|\\.)*)'$/.exec(e.trim());if(n)return`${JSON.stringify(ht(n[1]))}${t?"s":"i"}`;let r=/^\/((?:[^/\\]|\\.)*)\/([a-z]*)$/.exec(e.trim());if(!r)return;let s=no(r[1]);return s!==r[1]&&/[uv]/.test(r[2])?void 0:`/${s}/${r[2]}`}var Ph=new Set(["checked","disabled","selected","expanded","includeHidden","level","pressed","busy"]);function rd(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?ht(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=$i(a,n);if(c===void 0)return;o+=`[${i}=${c}]`}else if(Ph.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:$i(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)?ht(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=$i(s[1],!1);return o===void 0?void 0:`internal:has-text=${o}`}default:return}}function Oh({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 ki(e){let t={},n=e.match(/(?:frameLocator\('((?:[^'\\]|\\.)*)'\)|locator\('((?:[^'\\]|\\.)*)'\)\.contentFrame\(\))/);n&&(t.frame=ht(n[1]??n[2]),e=e.slice((n.index??0)+n[0].length));let r=Ch(e.replace(/^\./,"")),s=r?.filter((c,l)=>!(c.method==="first"&&l===r.length-1));if(s&&s.length>1){let c=s.map(l=>rd(l.method,l.args));return c.some(l=>l===void 0)?void 0:{...t,fallbackSelectors:[c.join(" >> ")]}}if(s?.length===1&&!Oh(s[0])){let c=rd(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=ht(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]=ht(d[1]))}let a=e.match(/(?:^|\.)locator\('((?:[^'\\]|\\.)*)'\)/);return a&&(t.fallbackSelectors=[ht(a[1])]),Object.keys(t).length>0?t:void 0}var jh={click:"click",dblclick:"click",fill:"fill",pressSequentially:"fill",type:"fill",press:"press",check:"check",uncheck:"uncheck",hover:"hover",selectOption:"selectOption"};function Nh(e,t){let n=e.match(/page\.goto\('((?:[^'\\]|\\.)*)'\)/);if(n)return{action:"goto",url:Zn(ht(n[1]),t)};let r=e.match(/page\.keyboard\.press\('((?:[^'\\]|\\.)*)'\)/);if(r)return{action:"press",value:ht(r[1])};let s=e.match(/await\s+page\.(.+)\.dragTo\(page\.(.+?)\);?\s*$/);if(s){let u=ki(s[1]),f=ki(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=ki(i);if(!l)return;let d={action:jh[a],target:l},p=Ih(c);return p!==void 0&&a!=="click"&&a!=="dblclick"&&(d.value=p),d}function id(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 ad(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(`
|
|
312
|
+
Invoke it anywhere with: StepSet Name`,filterText:"step set stepset:",sortText:"0",insertTextFormat:bf.Snippet,textEdit:{range:p,newText:"StepSet: ${1:Name}\n "}}];r.stepSets.length===0&&m.push({label:"StepSet \u2026",kind:$n.Keyword,detail:"invoke a step set (none defined yet)",filterText:"step set stepset",sortText:"1",insertTextFormat:bf.Snippet,textEdit:{range:p,newText:"StepSet ${1:Name}"}});for(let h of r.stepSets)m.push({label:`StepSet ${h.name}`,kind:$n.Function,detail:`invoke step set \xB7 ${h.steps.length} step(s)`,documentation:h.steps.join(`
|
|
313
|
+
`),filterText:`step set ${h.name}`,sortText:`1${h.name}`,textEdit:{range:p,newText:`StepSet ${h.name}`}});return m}return[]}async function wa(e,t,n){let r=[...e],s;if(await Promise.all(Array.from({length:Math.min(t,r.length)},async(o,i)=>{for(let a=r.shift();a&&!s;a=r.shift())for(let c of a){if(s)return;try{await n(c,i)}catch(l){s??={error:l};return}}})),s)throw s.error}function Cf(e,t){let n=new Map;for(let r of e)n.set(t(r),[...n.get(t(r))??[],r]);return[...n.values()]}import zt from"node:fs";import Fw from"node:net";import ut from"node:path";import{chromium as Bw,devices as Ea,firefox as Lw,webkit as Dw}from"playwright";import ww from"node:path";import{createHash as yw}from"node:crypto";var bw=5e3,vw=new Set(["click","press","selectOption","check","uncheck","hover","dragTo"]);function jf(e){return e.mode==="heal"||e.mode==="refine"}function Sa(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 _f=e=>`${e} action${e===1?"":"s"}`,Pf=e=>e.map(lt).join("; "),ho=class{firstStep;discardBeforeAnnounce;preAnnounce=[];discarded=[];carried;pendingTabOpen=!1;pendingTabFallback;lastOpener;lastOpenerAt=0;lastOpenerSession="";sessionKeys;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.sessionKeys=t.steps.map(r=>de(r.session)),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}let r=Math.max(n.length-1,0),s=n[r-1];s!==void 0&&s.action===t.action&&s.value===t.value&&s.promptText===t.promptText||n.splice(r,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: ${_f(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: ${Pf(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 ${_f(r.length)} the agent performed ${s}: ${Pf(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(t){let r=Date.now()-this.lastOpenerAt<=bw&&(t===void 0||t===this.lastOpenerSession)?this.lastOpener:void 0,s=t!==void 0&&t!==this.sessionOf(this.currentStepIndex);if(this.inFlight.size===0||s){r&&(r.opensTab=!0);return}this.pendingTabOpen=!0,this.pendingTabFallback=r}sessionOf(t){return this.sessionKeys[t>=0?t:this.firstStep]??""}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=>vw.has(s.action));r&&(this.lastOpener=r,this.lastOpenerAt=Date.now(),this.lastOpenerSession=this.sessionOf(this.currentStepIndex),this.pendingTabOpen&&(r.opensTab=!0,this.pendingTabOpen=!1,this.pendingTabFallback=void 0))}},xw={n:`
|
|
314
|
+
`,r:"\r",t:" ",b:"\b",f:"\f",v:"\v",0:"\0"},vt=e=>e.replace(/\\(?:x([0-9a-fA-F]{2})|u\{([0-9a-fA-F]+)\}|u([0-9a-fA-F]{4})|([\s\S]))/g,(t,n,r,s,o)=>r!==void 0?String.fromCodePoint(parseInt(r,16)):n!==void 0||s!==void 0?String.fromCharCode(parseInt(n??s,16)):xw[o]??o);function Sw(e){let t=e.match(/'((?:[^'\\]|\\.)*)'/);return t?vt(t[1]):void 0}function Nf(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 ya(e,t){let n=/^'((?:[^'\\]|\\.)*)'$/.exec(e.trim());if(n)return`${JSON.stringify(vt(n[1]))}${t?"s":"i"}`;let r=/^\/((?:[^/\\]|\\.)*)\/([a-z]*)$/.exec(e.trim());if(!r)return;let s=ni(r[1]);return s!==r[1]&&/[uv]/.test(r[2])?void 0:`/${s}/${r[2]}`}var $w=new Set(["checked","disabled","selected","expanded","includeHidden","level","pressed","busy"]);function Of(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?vt(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=ya(a,n);if(c===void 0)return;o+=`[${i}=${c}]`}else if($w.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:ya(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)?vt(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=ya(s[1],!1);return o===void 0?void 0:`internal:has-text=${o}`}default:return}}function kw({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 ba(e){let t={},n=e.match(/(?:frameLocator\('((?:[^'\\]|\\.)*)'\)|locator\('((?:[^'\\]|\\.)*)'\)\.contentFrame\(\))/);n&&(t.frame=vt(n[1]??n[2]),e=e.slice((n.index??0)+n[0].length));let r=Nf(e.replace(/^\./,"")),s=r?.filter((c,l)=>!(c.method==="first"&&l===r.length-1));if(s&&s.length>1){let c=s.map(l=>Of(l.method,l.args));return c.some(l=>l===void 0)?void 0:{...t,fallbackSelectors:[c.join(" >> ")]}}if(s?.length===1&&!kw(s[0])){let c=Of(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=vt(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]=vt(d[1]))}let a=e.match(/(?:^|\.)locator\('((?:[^'\\]|\\.)*)'\)/);return a&&(t.fallbackSelectors=[vt(a[1])]),Object.keys(t).length>0?t:void 0}var If={click:"click",dblclick:"click",fill:"fill",pressSequentially:"fill",type:"fill",press:"press",check:"check",uncheck:"uncheck",hover:"hover",selectOption:"selectOption"};function Rw(e,t){let n=e.match(/page\.goto\('((?:[^'\\]|\\.)*)'\)/);if(n)return{action:"goto",url:Fr(vt(n[1]),t)};let r=e.match(/page\.keyboard\.press\('((?:[^'\\]|\\.)*)'\)/);if(r)return{action:"press",value:vt(r[1])};let s=e.match(/await\s+page\.(.+)\.dragTo\(page\.(.+?)\);?\s*$/);if(s){let m=ba(s[1]),h=ba(s[2]);if(m&&h)return{action:"dragTo",target:m,toTarget:h}}let o=/await\s+page\.(.*\))\s*;?\s*$/.exec(e)?.[1],i=o===void 0?void 0:Nf(o),a=i?.[i.length-1];if(!i||!a||i.length<2||!Object.hasOwn(If,a.method))return;let{method:c,args:l}=a,d=i.slice(0,-1).map(m=>`${m.method}(${m.args})`).join("."),u=ba(d);if(!u)return;let g={action:If[c],target:u};if(c==="click"||c==="dblclick"){let m=/clickCount:\s*(\d+)/.exec(l)?.[1];c==="dblclick"?g.clickCount=2:m&&m!=="1"&&(g.clickCount=Number(m));let h=/button:\s*'(left|right|middle)'/.exec(l)?.[1];h&&h!=="left"&&(g.button=h);let w=/modifiers:\s*\[([^\]]*)\]/.exec(l)?.[1],b=w?[...w.matchAll(/'((?:[^'\\]|\\.)*)'/g)].map(y=>vt(y[1])):[];return b.length>0&&(g.modifiers=b),g}let f=c==="selectOption"?/^\s*\[((?:'(?:[^'\\]|\\.)*'|[^\]'])*)\]/.exec(l)?.[1]:void 0;if(f!==void 0&&!f.trim())return{...g,clearSelection:!0};let p=f?.trim()?[...f.matchAll(/'((?:[^'\\]|\\.)*)'/g)].map(m=>vt(m[1])).join(`
|
|
315
|
+
`):Sw(l);return p!==void 0&&(g.value=p),g}function Mf(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 Ff(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(`
|
|
294
316
|
`);for(let a of i.split(`
|
|
295
|
-
`)){let c=
|
|
296
|
-
`)
|
|
297
|
-
`)
|
|
298
|
-
|
|
299
|
-
`)
|
|
300
|
-
`)[0]}. Generate it again with: npx playwright open --save-storage=${this.options.storageState} <url>`)}return t}contextOptions(){let{defaultBrowserType:t,...n}=this.options.device?Ri[this.options.device]??{}:{};return{storageState:this.resolveStorageState(),...n,...this.options.viewport?{viewport:this.options.viewport}:{}}}artifacts(t){let n=Ft(this.options.projectRoot,t.featurePath,t.displayName);return this.options.artifactsPerBrowser?wt.join(n,this.options.browser??"chromium"):n}buildCandidateCache(t,n){return{version:1,feature:t.featurePath,scenario:t.name,recordedAt:new Date().toISOString(),recordedBy:"agent",steps:n,...pd(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(this.contextOptions()),i=this.options.trace!==void 0&&this.options.trace!=="off";i&&await Io(o,s?t.displayName:`${t.displayName} (proof replay)`);let a=await o.newPage();return{result:await or(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=ct(t);if(s.size>0){let o=i=>i===void 0?i:et(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=>et(i,s));for(let i of r.stepResults){i.error=o(i.error);for(let a of i.tabs??[])a.url=et(a.url,s);for(let a of i.responses??[])a.url=et(a.url,s)}}return r}async screenshot(t,n,r,s){let o=this.options.screenshot??"viewport";if(o!=="off")try{let i=this.artifacts(n);this.claimArtifactDir(n);let a=wt.join(i,`${r}.jpg`),c=await t.screenshot({path:a,type:"jpeg",quality:80,fullPage:o==="full-page",timeout:5e3});return{kind:r,file:Ae(this.options.projectRoot,a),step:s,sha256:rt(c)}}catch{return}}claimArtifactDir(t){let n=Ft(this.options.projectRoot,t.featurePath,t.displayName);mt.mkdirSync(this.artifacts(t),{recursive:!0}),mt.writeFileSync(wt.join(n,nn),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=se(s,t.featurePath,t.name),d;try{d=Pe(l)}catch(P){if(!(P instanceof le))throw P;return{scenario:t,status:"red",source:"cache",stepResults:[],adaptations:[],usage:Kt,durationMs:Date.now()-r,error:`The recording cannot be read: ${P.problem}. Fix the file, or re-record it with saffron run --rerecord.`}}let p=qe(s,t.featurePath,t.name),u=Ae(s,p),f,g;if(mt.existsSync(p))try{({proposal:f,revision:g}=Kr(p))}catch(P){if(!(P instanceof le)&&P.code!=="ENOENT")throw P;f=void 0}let w=!1;f&&!Ka(s,p,g)&&(w=!this.options.rerecord,f=void 0),f&&We(s,f,t)&&(f=void 0);let R=P=>P.status==="stale"?"the committed recording no longer matches the scenario":`the committed recording failed${P.failure?` at "${P.failure.stepText}"`:""}`,$=P=>{let O=_t(s)[u],M=O?.revision===g?` from ${ie(ur(O.from))}`:"",T=P?R(P):"";return{scenario:t,status:"yellow",source:d?"cache":"agent-record",stepResults:P?.stepResults??[],narrative:(T?`${T[0].toUpperCase()}${T.slice(1)}. `:"")+`A proposal${M} 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:g,usage:Kt,durationMs:Date.now()-r}};if(mt.rmSync(this.artifacts(t),{recursive:!0,force:!0}),this.options.artifactsPerBrowser){let P=Ft(s,t.featurePath,t.displayName);for(let O of mt.existsSync(P)?mt.readdirSync(P,{withFileTypes:!0}):[])O.isFile()&&O.name!==nn&&mt.rmSync(wt.join(P,O.name),{force:!0})}if(w&&!d)return $();let m=(P,O)=>({scenario:t,status:"yellow",source:"agent-record",proposalReplay:!0,stepResults:P.stepResults,narrative:`Replayed the pending proposal recorded for "${f.meta.recordedFor??t.name}" at zero AI${O?` instead of ${O.status==="stale"?"recording":"healing"} again: ${R(O)}`:""}; accept it to go green.`,adaptations:[],verified:!0,proposalFile:u,proposalRevision:g,usage:Kt,durationMs:Date.now()-r}),v=await this.browser.newContext(this.contextOptions()),S=this.options.trace??"off",x=S!=="off";x&&await Io(v,t.displayName);let b=!x,k,h=await v.newPage(),y=Ut(),A=[],E=(P,O)=>this.screenshot(P,t,"before-heal",O.stepText).then(M=>{M&&A.push(M)});try{let P=await(async()=>{let T;if(f&&!d){let D=await or(h,t,f.cache,{baseURL:o,actionTimeoutMs:i,retries:a,pollIntervalMs:c,uniqueSeed:y,trace:x,tracePhase:"pending"}),H=f.meta.recordedFor??t.name;if(D.status==="passed")return m(D);if(Object.keys(t.params).length>0&&H!==t.displayName){let W=D.failure;return{scenario:t,status:"red",source:"agent-record",proposalReplay:!0,stepResults:D.stepResults,adaptations:[],proposalFile:u,proposalRevision:g,usage:Kt,durationMs:Date.now()-r,error:`The pending proposal recorded for "${H}" does not replay for this Examples row`+(W?` (step "${W.stepText}": ${W.error.split(`
|
|
301
|
-
`)[0]})
|
|
302
|
-
`)[
|
|
303
|
-
|
|
304
|
-
`)[0]}
|
|
305
|
-
`)[0]}`,wn=T.failure.stepIndex,bt=T.stepResults.map((ot,jt)=>jt===wn?{...ot,status:"failed",error:Te}:ot);return{scenario:t,status:"red",source:"agent-heal",stepResults:bt,executionStepResults:bt.map((ot,jt)=>jt>wn&&ot.status==="skipped"?{...ot,status:"passed"}:ot),narrative:_.narrative,adaptations:_.adaptations,suggestedFeatureEdit:_.suggestedFeatureEdit,usage:_.usage,durationMs:Date.now()-r,error:Te}}finally{F?.detach()}}return F?.detach(),await this.finalizeAgentRun(t,_,j,d,r,L,j?T?.failure:void 0,y)})(),O=A.find(T=>T.kind==="before-heal");if(P.source==="cache"&&O){let T=O.file.replace(/before-heal\.jpg$/,"failure.jpg");try{mt.renameSync(wt.join(s,O.file),wt.join(s,T)),O.file=T}catch{}O.kind="failure"}else if(P.status==="red"){let T=P.stepResults.find(j=>j.status==="failed")?.gherkin,C=await this.screenshot(Ln(this.browser)??h,t,"failure",T);C&&A.push(C)}let M=On(ze(t),y);if(M.size>0&&(P.uniques=Object.fromEntries(M)),A.push(...P.evidence??[]),x){let C=S==="on"||P.status!=="green"?wt.join(this.artifacts(t),_o):void 0;b=!0;let j=k??v;C||await Co(j).catch(()=>{});let L=C?await Po(j,C,ct(t)):void 0;if(C&&L){this.claimArtifactDir(t);let _=ct(t);A.unshift({kind:"trace",file:Ae(s,C),sha256:L,traceSteps:(P.executionStepResults??P.stepResults).map(F=>({...F,error:F.error&&et(F.error,_)}))})}}return A.length>0&&(P.status!=="green"||A.some(T=>T.kind==="trace"))&&(P.evidence=A),P}finally{b||await Co(v).catch(()=>{}),await k?.close(),await v.close()}}async finalizeAgentRun(t,n,r,s,o,i=0,a,c=Ut()){let l=r?"agent-heal":"agent-record",d=n.success?n.recordedSteps.map(_=>({gherkin:_.gherkin,kind:_.kind,status:"passed"})):vd(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?gd(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?hd(n.recordedSteps,a.stepIndex):[]],f={...n.usage},g,w,R,$,m=[],v=0,S=new Set,x,b=async(_,F,D=F.stepResults)=>{if(!S.has(_)){S.add(_);try{if(this.options.trace&&this.options.trace!=="off"){let H=wt.join(this.artifacts(t),`proof-${++v}.zip`),V=ct(t),W=await Po(_,H,V);if(W){this.claimArtifactDir(t);let ce=F.captured[Ke],st=ce?On(ze(t),ce):new Map;m.push({kind:"trace",proof:!0,file:Ae(this.options.projectRoot,H),sha256:W,traceSteps:D.map(Te=>({...Te,error:Te.error&&et(Te.error,V)})),traceUniques:st.size?Object.fromEntries(st):void 0})}}}finally{await _.close()}}};if(this.options.verifyProposals!==!1){let _=await this.proofReplay(t,this.buildCandidateCache(t,p),Ut());$=_.result.captured[Ke];try{if(_.result.status!=="passed"&&_.result.failure){let F=_.result.failure;if(this.options.agent&&!(r&&F.kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||ud(s.steps,F.stepIndex))))try{let H=await xs(this.browser,_.result.activePage??yr(_.page.context(),F.pageUrl)??_.page),V=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(W=>W.status==="passed").map(W=>W.gherkin),failedStep:{text:F.stepText,kind:F.kind,error:F.error,pageUrl:F.pageUrl,stepIndex:F.stepIndex},liveTab:H,uniqueSeed:_.result.captured[Ke],onTabOpened:this.tabWatcher(),takeFingerprint:async()=>sn(Ln(this.browser)??_.page)}));f=md(f,V.usage),x=Qh(_.result.stepResults,F,V),V.success&&(u.push(...V.adaptations),u.push(...hd(V.recordedSteps,F.stepIndex)),p=r?gd(p,V.recordedSteps,this.options.assertionPolicy==="adaptable-mid",{stepIndex:F.stepIndex,actionIndex:0}):Zh(p,V.recordedSteps,F.stepIndex),await b(_.context,_.result,x),x=void 0,_=await this.proofReplay(t,this.buildCandidateCache(t,p),Ut()),$=_.result.captured[Ke])}catch{}}for(let F of _.result.tabOpeners??[]){let D=p[F.stepIndex]?.actions[F.actionIndex];D&&(D.opensTab=!0)}g=_.result.status==="passed",g||(w=_.result.failure?.error??`proof replay ${_.result.status}`,R=_.result.stepResults)}finally{await b(_.context,_.result,x).catch(()=>{})}}r&&s&&u.push(...Yh(s.steps,p,a,this.options.baseURL));let k=[...n.featureEdits];for(let _ of Da(p,lt(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.`),k.some(F=>F.index===_.index)||k.push({index:_.index,text:_.to});let h=cd(p);h.length>0&&(g=!1,w=[w,...h].filter(Boolean).join(" "));let y=ct(t),A=_=>y.size>0?et(_,y):_;u=u.map(A);let E=k.map(_=>({index:_.index,text:A(_.text)})),P=A(n.narrative),O=n.suggestedFeatureEdit?A(n.suggestedFeatureEdit):void 0,M={version:1,feature:t.featurePath,scenario:t.name,recordedAt:new Date().toISOString(),recordedBy:"agent",steps:p,...pd(t)},T={meta:{createdAt:M.recordedAt,mode:r?"heal":"record",narrative:P,adaptations:u,suggestedFeatureEdit:O,featureEdits:E.length>0?E:void 0,verified:g,proofError:w?A(w):void 0,seededSteps:i>0?i:void 0,recordedFor:t.displayName,usage:f,bound:Wc(t,s,M,E.length>0?E:void 0)},cache:M},C=qe(this.options.projectRoot,t.featurePath,t.name),j=Wa(C,T);Ya(this.options.projectRoot,C,j);let L=Pe(se(this.options.projectRoot,t.featurePath,t.name));return{proposalDiff:Ht(L,T.cache),scenario:t,status:"yellow",source:l,stepResults:R??d,executionStepResults:d,evidence:m,proofUniques:(()=>{let _=$?On(ze(t),$):void 0;return _&&_.size>0?Object.fromEntries(_):void 0})(),narrative:P,adaptations:u,suggestedFeatureEdit:O,featureEdits:E.length>0?E:void 0,verified:g,proofError:w,seededSteps:i>0?i:void 0,proposalFile:Ae(this.options.projectRoot,C),proposalRevision:j,usage:f,durationMs:Date.now()-o}}};import Fs from"node:fs";import Zm from"node:os";import Gd from"node:path";import{query as xm}from"@anthropic-ai/claude-agent-sdk";import{McpServer as Xh}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as Y}from"zod";var Ie=e=>({content:[{type:"text",text:e}]});function Dn(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 em(e){let t=new Xh({name:e.name,version:e.version});for(let n of e.tools)n(t);return{type:"sdk",name:e.name,instance:t}}function Sd(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 tm=new Set(["main","banner","contentinfo","status","alert","alertdialog","dialog","search"]);function xd(e){if(!e?.role)return;let{role:t,frame:n,...r}=e;if(!(Object.keys(r).length>0||tm.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 nm(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 $d=new WeakSet;function rm(e,t){if(t.success&&!$d.has(e)){let n=[...e.announced].filter(r=>r>=e.firstStep&&e.steps[r]?.kind==="assertion"&&!e.steps[r].actions.some(s=>He.has(s.action))).sort((r,s)=>r-s);if(n.length>0)return $d.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=>!ao.test(n.text)),"Run finalized."}var kd={role:Y.string().optional().describe("ARIA role of the element"),name:Y.string().optional().describe("Accessible name \u2014 use the SHORTEST stable substring; never include volatile content like prices or dates"),nameRegex:Y.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:Y.string().optional().describe("Form-label text for getByLabel \u2014 the literal <label> text only, never a free-text description"),text:Y.string().optional().describe("getByText locator text"),selector:Y.string().optional().describe("CSS fallback selector"),frame:Y.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 ks(e){return em({name:"saffron",version:"0.1.0",tools:[Dn("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:Y.number().int().min(0),text:Y.string(),adaptation:Y.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=>Ie(nm(e,t))),Dn("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:Y.string().describe("Name to store the captured text under"),...kd},async t=>{let n=Sd(t);if(!n)return Ie("ERROR: capture needs a target (role/name, nameRegex, label, text, or selector).");let r=xd(n);return r?Ie(r):(e.addActions([{action:"captureText",target:n,saveAs:t.saveAs}]),Ie(`Capture recorded as "${t.saveAs}".`))}),Dn("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:Y.boolean().describe("true = accept/OK the dialog, false = dismiss/cancel"),promptText:Y.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}:{}}),Ie(`Dialog handling recorded (${t.accept?"accept":"dismiss"}).`))),Dn("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:Y.string().describe("Regex matched against the response URL \u2014 path-only for portability"),method:Y.string().optional().describe("HTTP method to match (any if omitted)"),status:Y.string().optional().describe("Expected status \u2014 exact ('201') or class ('2xx'); default any 2xx"),bodyPattern:Y.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}:{}}]),Ie("Network wait recorded."))),Dn("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:Y.enum(["visible","notVisible","text","url","value","differs","matches","attribute","response","each"]),...kd,expected:Y.string().optional().describe("Expected text/value for kind=text|value \u2014 stable text only, never volatile values"),url:Y.string().optional().describe("URL substring for kind=url (path only, no host)"),pattern:Y.string().optional().describe("kind=matches|attribute: regex the target's text (or attribute) must match, e.g. 'NOK [\\\\d,]+' for a price"),attribute:Y.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:Y.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:Y.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:Y.string().optional().describe("kind=response: HTTP method to match (any if omitted)"),status:Y.string().optional().describe("kind=response: expected status \u2014 exact ('201') or class ('2xx'); default any 2xx"),bodyPattern:Y.string().optional().describe("kind=response: regex the response body must match (verify via browser_network_requests first)"),each:Y.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:Y.string().optional().describe("kind=differs: name of the captured value to compare against")},async t=>{let n=Sd(t),r=xd(n);if(r)return Ie(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 Ie("ERROR: kind=differs requires compareTo.");if(!t.capture&&!n)return Ie("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 Ie("ERROR: kind=matches requires pattern.");s={action:"expectMatches",target:n,pattern:t.pattern};break;case"attribute":if(!t.attribute||!t.pattern)return Ie("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 Ie("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 Ie("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?Ie("ERROR: assertion needs a target (role/name, nameRegex, label, text, or selector)."):(e.addActions([s]),Ie("Assertion recorded."))}),Dn("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:Y.boolean(),narrative:Y.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:Y.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:Y.array(Y.object({index:Y.number().int().min(0).describe("zero-based step index"),text:Y.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=>Ie(rm(e,t)))]})}function Ts(e={}){let t=e.deliberateSnapshots?`
|
|
317
|
+
`)){let c=Rw(a.trim(),t);c&&s.push(c)}}return Tw(s)}function Tw(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 Bf(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(Te(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 Lf(e,t,n=we.pattern){for(let[r,s]of t){let o=Vc(e,n(s));if(o)return o==="bare"?`<${r}>`:`^<${r}>$`}}function gr(e,t,n=o=>o,r=!1,s=Object.keys(t)){let o=Object.entries(t).filter(([,a])=>a.length>=3);if(!r)return mo(e,o,a=>new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),n,s);let i=o.find(([,a])=>!li(a)&&e===n(a));return i?`<${i[0]}>`:mo(e,o.filter(([,a])=>li(a)),a=>en(a,"gu"),n,s)}function mo(e,t,n,r=o=>o,s=t.map(([o])=>o)){let o=new RegExp(`(${Xn(s).source})`);return[...t].sort((i,a)=>a[1].length-i[1].length).reduce((i,[a,c])=>i.split(o).map((l,d)=>{if(d%2)return l;let u=l.normalize("NFC"),g=u.replace(n(r(c).normalize("NFC"),c),()=>`<${a}>`);return g===u?l:g}).join(""),e)}function Ew(e,t,n){if(/^\s*(?:xpath=|\/\/)/.test(e))return e.replace(/'([^']*)'|"([^"]*)"/g,(o,i,a)=>i!==void 0?`'${n(i)}'`:`"${n(a)}"`);let r,s=!0;return Cn(e,t,o=>o.split(/(>>)/).map((i,a)=>a%2?i:((s||a>0)&&(r=i.match(/^\s*([a-z_-]+(?::[a-z_-]+)?)=/i)?.[1]?.toLowerCase()),s=!1,r===void 0?i.replace(/([#.])((?:[\p{L}\p{N}\p{M}_-]|\\.)+)/gu,(c,l,d)=>l+n(d)):/^(?:id|data-testid|data-test-id|data-test)$/.test(r)?i.replace(/=(.*)$/s,(c,l)=>`=${n(l)}`):i)).join(""))}function $a(e,t){let n=[e??"",t?.text??"",...t?.table?.flat()??[],t?.docString??""].join(`
|
|
318
|
+
`);return new Set([...n.matchAll(/<([^<>]+)>/g)].map(r=>r[1]))}function ka(e,t){let n=[e?.text??"",...e?.table?.flat()??[],e?.docString??""].join(`
|
|
319
|
+
`).replace(/<[^<>]+>/g," ");try{return t(n)}catch{return n}}function Ra(e,t,n=e,r="",s=o=>[n[o]??e[o]]){let o=new Map;for(let i of Object.keys(e))o.set(n[i]??e[i],[...o.get(n[i]??e[i])??[],i]);return Object.fromEntries(Object.entries(e).filter(([i,a])=>{let c=n[i]??a;if(c!==""&&en(c).test(r)&&(!t.has(i)||!s(i).every(d=>en(d).test(r))))return!1;let l=o.get(c);return l.length>1&&l.some(d=>/\{env:/.test(e[d]))?!1:(l.find(d=>t.has(d))??l[0])===i}))}function wo(e,t,n){let r=e.flatMap(s=>{let o=s[t];if(o===void 0)return[];try{return[n(o)]}catch{return[o]}});return[...new Set(r)].filter(s=>s.trim()!=="")}function Df(e,t,n,r){return e(t).filter(s=>s!==n&&!/\{(?:env|data|unique|date)/.test(s)&&(s.length>=3||r.has(t)))}function va(e,t){return new RegExp(`(^|[-_:.])${je(e)}(?=$|[-_:.])`,t)}function Uf(e,t){let n=Object.keys(t.params);if(n.length===0)return[];let r=t.exampleRows??[t.params],s=Zn(r.flatMap(p=>Object.values(p))),o=p=>p.replace(Ie,(m,h)=>s.get(h)??m).replace(Ue,(m,h)=>process.env[h]??m),i=Object.fromEntries(Object.entries(t.params).map(([p,m])=>[p,o(m)])),a=p=>!/\{(?:env|data|unique|date)/.test(p),c=p=>wo(r,p,o),l=(p,m,h)=>{let w=p.trim(),b=`${m}
|
|
320
|
+
${m.replace(Ie,(S,x)=>h.get(x)??S)}`.toLowerCase(),y=S=>m.includes(S)&&(w===S||w.startsWith(S)&&/^[/?#]/.test(w.slice(S.length))||b.includes(w.toLowerCase()));return p.replace(Xn(n)," ").replace(Ie,(S,x)=>y(S)?S:s.get(x)??h.get(x)??S).replace(Ue,(S,x)=>y(S)?S:process.env[x]??S).replace(/\{(?:env|data|unique|date)[^{}]*\}/g," ")},d=[],u=[...new Set(t.steps.flatMap(p=>[p.text,...p.table?.flat()??[],p.docString??""]).flatMap(p=>[...p.matchAll(/\{data:([^{}]*<[^<>{}]+>[^{}]*)\}/g)].map(m=>m[1])))].flatMap(p=>{let m=[...p.matchAll(/<([^<>]+)>/g)].map(b=>b[1]).filter(b=>b in t.params),w=(b=>{if(!m.some(y=>/[{}<>]/.test(b[y]??"{")))try{return Je(p.replace(/<([^<>]+)>/g,(y,S)=>b[S]??y))}catch{return}})(t.params);return m.length===0||w===void 0||w.trim()===""?[]:[{used:m,value:w.trim().toLowerCase()}]}),g=[...Hf(t).all].filter(([,p])=>p.size>1);g.length>0&&e.forEach((p,m)=>{let h=p.actions.flatMap(w=>Qt(w)).filter(w=>w!==void 0);for(let[w,b]of g){if(!h.some(S=>S.includes(w)))continue;let y=new Set([...b].flatMap(S=>[...S.matchAll(/<([^<>]+)>/g)].map(x=>x[1])));for(let S of y)S in t.params&&d.push({column:S,step:m,reason:"data"})}});let f=p=>{let m=er(t.params[p]);return m?{valueSha:m}:{}};return e.forEach((p,m)=>{let h=$a(p.gherkin,t.steps[m]),w=Ra(i,h,i,ka(t.steps[m],T=>T),c),b=Object.entries(w).filter(([T,M])=>a(M)&&M.trim()!==""&&(M.length>=3||h.has(T))),y=new Set(b.filter(([T])=>h.has(T)).map(([,T])=>T)),S=t.steps[m],x=[S?.text??p.gherkin,...S?.table?.flat()??[],S?.docString??""].join(`
|
|
321
|
+
`),C=Zn([x]),$=[x,...C.values()].join(`
|
|
322
|
+
`),k=p.actions.flatMap(T=>jr(T)).flatMap(T=>T===void 0?[]:[l(T,$,C).normalize("NFC")]),_=p.actions.flatMap(T=>T.each!==void 0&&!x.includes(T.each)?T.each.match(/^\{data:([^{}]+)\}$/)?.slice(1)??[]:[]).map(T=>T.toLowerCase()),v=p.actions.flatMap(T=>T.attribute!==void 0?[T.attribute]:[]),A=T=>[T,T.replace(/\s+/g,"-"),T.replace(/\s+/g,"_")].some(M=>_.some(I=>I.includes(M))||v.some(I=>va(M,"i").test(I))),O=p.actions.flatMap(T=>[T.status,T.method,T.attribute]).flatMap(T=>T===void 0?[]:[l(T,$,C).trim().toLowerCase()]),P=new Set;for(let[T,M]of Object.entries(i)){let I=M.trim().toLowerCase();h.has(T)||/\{(?:date|unique)/.test(t.params[T]??"")||I===""||!O.includes(I)||(d.push({column:T,step:m,reason:"value",...f(T)}),P.add(T))}for(let[T,M]of Object.entries(i)){if(P.has(T)||/\{(?:date|unique)/.test(t.params[T]??""))continue;let I=M.trim().toLowerCase();I.length<3||!A(I)||(d.push({column:T,step:m,reason:"glued",...f(T)}),P.add(T))}for(let{used:T,value:M}of u)if(O.includes(M))for(let I of T)P.has(I)||(d.push({column:I,step:m,reason:"reads",...f(I)}),P.add(I));for(let[T,M]of b){if(P.has(T))continue;let I=Df(c,T,M,h);I.length>0&&k.some(F=>Qn(F,M,y.has(M))&&I.some(z=>Qn(F,z,y.has(M))))?d.push({column:T,step:m,reason:"list",...f(T)}):!h.has(T)&&M.length>=3&&k.some(F=>F.includes(M.normalize("NFC")))&&d.push({column:T,step:m,reason:"glued",...f(T)})}let E=T=>d.some(M=>M.column===T&&M.step===m);for(let[T,M]of Object.entries(t.params)){let I=i[T]??"";if(E(T)||I.trim()===""||/\{(?:date|unique)/.test(M))continue;let F=Object.keys(i).filter(N=>i[N]===I&&!/\{(?:date|unique)/.test(t.params[N]??""));if(F.length>1&&r.some(N=>new Set(F.map(L=>o(N[L]??""))).size>1))continue;let z={...t.params,...Object.fromEntries(F.map(N=>[N,"\u2063another row\u2063"]))};Pn(p.actions,x,t.params,z)&&d.push({column:T,step:m,reason:"glued",...f(T)})}if(p.kind==="assertion")for(let[T,M]of Object.entries(t.params)){let I=(i[T]??"").trim();E(T)||h.has(T)||I===""||I.length>2||/\{(?:date|unique)/.test(M)||en(I,"u").test(x)||p.actions.some(F=>jr(F).some(z=>z!==void 0&&Qn(l(z,$,C),I,!1)))&&d.push({column:T,step:m,reason:"glued",...f(T)})}}),d}function Aw(e,t,n=[],r=t,s=i=>i,o=[]){let i=d=>wo(o.length>0?o:[t],d,s),a=new Map,c=d=>a.get(d)??a.set(d,wo(o.length>0?o:[t],d,u=>u)).get(d),l=Object.keys(t);return e.map((d,u)=>{let g=$a(d.gherkin,n[u]),f=[...g].filter(v=>v in t&&(r[v]??t[v])===""),p=f.length===1?`<${f[0]}>`:void 0,m=Ra(t,g,r,ka(n[u],s),i),h=Object.entries(m).map(([v,A])=>[v,A.includes("{date")?A:r[v]??A]).filter(([v,A])=>A.length>=3||A!==""&&g.has(v));if(h.length===0&&!p)return d;let w=new Set(h.filter(([v])=>g.has(v)).map(([,v])=>v)),b=(v,A)=>Ps(A,v,"gu",w.has(A)),y=(v,A,O)=>Lf(v,A,O)??mo(v,A,b,O,l),x=[...h.filter(([v])=>g.has(v))].sort((v,A)=>A[1].length-v[1].length),C=v=>v===void 0?v:x.reduce((A,[O,P])=>A.replace(va(P,"gi"),(E,T)=>`${T}<${O}>`),v),$=(v,A=O=>O)=>{if(v===void 0)return;let O=y(v,h,A),P=O.replace(Xn(l)," "),E=h.filter(([T,M])=>!/\{(?:env|data|unique|date)/.test(t[T])&&Qn(v,M,w.has(M),A(M))&&Df(c,T,M,g).some(I=>Qn(P,I,w.has(M),A(I))));return E.length===0?O:y(v,h.filter(T=>!E.includes(T)),A)},k=v=>$(v,we.pattern),R=v=>v===void 0?void 0:Ew(v,(A,O)=>$(A,we[O]),A=>mo(A,h,b,void 0,l)),_=v=>v?{...v,name:$(v.name),nameRegex:k(v.nameRegex),label:$(v.label),text:$(v.text),placeholder:$(v.placeholder),testId:$(v.testId),frame:R(v.frame),fallbackSelectors:v.fallbackSelectors?.map(A=>R(A))}:void 0;return{...d,actions:d.actions.map(v=>({...v,value:v.action==="expectDiffers"?v.value:(v.action==="fill"||at.has(v.action))&&v.value===""&&p?p:$(v.value),url:$(v.url),pattern:k(v.pattern),urlPattern:k(v.urlPattern),promptText:$(v.promptText),each:v.each!==void 0&&!d.gherkin.includes(v.each)?v.each.replace(/^\{data:([^{}]+)\}$/,(A,O)=>`{data:${x.reduce((P,[E,T])=>P.replace(va(T,"g"),(M,I)=>`${I}<${E}>`),O)}}`):v.each,status:C(v.status),method:C(v.method),attribute:C(v.attribute),target:_(v.target),toTarget:_(v.toTarget)}))}})}function Cw(e,t,n=r=>r){let r=pn(t.steps);return e.map((s,o)=>{let i=t.steps[o],a=i?.resolvedTable??i?.table,c=i?.resolvedDocString??i?.docString,l={...ze(a),...An(c)},d=new Set,u=Object.entries({...r,...l}).map(([h,w])=>{let b=n(w);return w.includes("{date")&&d.add(h),[h,b]}).filter(([h,w])=>w.length>=3&&(!d.has(h)||h in l||xa(w))),g=new Set(u.map(([,h])=>h).filter((h,w,b)=>b.indexOf(h)!==w)),f=u.filter(([,h])=>!g.has(h)).sort((h,w)=>w[1].length-h[1].length);if(f.length===0)return s;let p=(h,w=y=>y,b=!1)=>h===void 0?void 0:f.reduce((y,[S,x])=>gr(y,{[S]:x},w,b||d.has(S)),h),m=h=>h?{...h,name:p(h.name),nameRegex:p(h.nameRegex,we.pattern),label:p(h.label),text:p(h.text),placeholder:p(h.placeholder),testId:p(h.testId,void 0,!0),frame:p(h.frame,void 0,!0),fallbackSelectors:h.fallbackSelectors?.map(w=>Cn(w,(b,y)=>p(b,we[y])??b))}:void 0;return{...s,actions:s.actions.map(h=>({...h,value:h.action==="expectDiffers"?h.value:p(h.value),url:p(h.url),pattern:p(h.pattern,we.pattern),urlPattern:p(h.urlPattern,we.pattern),promptText:p(h.promptText),target:m(h.target),toTarget:m(h.toTarget)}))}})}var xa=e=>/(?<!\d)\d{4}(?!\d)/.test(e);function _w(e,t=new Date,n=[]){return e.map(r=>({...r,actions:r.actions.map(s=>hr(s,o=>Lc(o,t,n)))}))}function hr(e,t,n,r=t){let s=(l,d,u=t)=>{let g={...l};for(let f of d)typeof l[f]=="string"&&(g[f]=u(l[f]));return g},o=l=>n?n(l,"pattern"):t(l),i=l=>{let d=s(s(l,["name","label","text","placeholder","testId","frame"]),["nameRegex"],o);return l.fallbackSelectors&&(d.fallbackSelectors=l.fallbackSelectors.map(u=>n?Cn(u,n,t):t(u))),d},a=e.action==="expectDiffers"?["url","promptText"]:["value","url","promptText"],c=s(s(s(e,a),["status","method","attribute","each"],r),["pattern","urlPattern"],o);return e.target&&(c.target=i(e.target)),e.toTarget&&(c.toTarget=i(e.toTarget)),c}function Pw(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(je).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 Ow(e,t){let n=We(t),r=Gt(st(t)),s=new RegExp(`${Ue.source}|${Ie.source}`,"g"),o=i=>i.replace(s,(a,c,l)=>(c!==void 0?n.has(c):r.has(l))?a:Tc(a));return e.map(i=>({...i,actions:i.actions.map(a=>({...hr(a,o),...a.each!==void 0?{each:a.each}:{}}))}))}function Iw(e,t,n=[]){if(t.size===0)return e;let r=ti(n,t),s=un(t,{standaloneBelow:6}),o=p=>s.mask(r(p)),i=[...t].filter(([,p])=>p.length>=Tn),a=p=>{let m=ti(n,t,we[p]),h=un(new Map(i.filter(([,b])=>b.length>=6).map(([b,y])=>[b,we[p](y)]))),w=i.filter(([,b])=>b.length<6).map(([b,y])=>[b,we[p](y)]);return b=>o(Pw(h.mask(m(b)),w))},c={quoted:a("quoted"),regex:a("regex"),pattern:a("pattern")},l=new Set(e.flatMap(p=>p.actions.flatMap(m=>[m.saveAs,m.compareTo,m.action==="expectDiffers"?m.value:void 0].filter(h=>h!==void 0)))),d=un(t,{encodings:!0}),u=new Map,g=new Set(l);for(let p of l){let m=d.mask(p);if(m===p)continue;let h=`capture-${yw("sha256").update(m).digest("hex")}`;if(g.has(h)||d.mask(h)!==h)throw new Error("Secret-bearing capture names cannot be safely distinguished. Record again with distinct capture names that contain no secrets.");g.add(h),u.set(p,h)}let f=p=>p===void 0?void 0:u.get(p)??p;return e.map(p=>({...p,actions:p.actions.map(m=>({...hr(m,o,(h,w)=>c[w](h)),...m.saveAs!==void 0?{saveAs:f(m.saveAs)}:{},...m.compareTo!==void 0?{compareTo:f(m.compareTo)}:{},...m.action==="expectDiffers"&&m.value!==void 0?{value:f(m.value)}:{}}))}))}function zf(e,t,n="",r=new Date){let s=st(t),o=ot(t),i=r,a=S=>It(Ar(jn(S,n)),i).replace(Ue,(x,C)=>o.get(C)??x),c=Object.fromEntries(Object.entries(t.params).map(([S,x])=>{try{return[S,a(x)]}catch{return[S,x]}})),l=e.map((S,x)=>$a(S.gherkin,t.steps[x])),d=l.map((S,x)=>Ra(t.params,S,c,ka(t.steps[x],a),C=>wo(t.exampleRows??[t.params],C,a))),u=Object.entries(t.params).filter(([,S])=>S.includes("{date")).map(([S,x])=>[S,x,c[S]]),g=S=>u.filter(([x,,C])=>x in(d[S]??{})&&(l[S]?.has(x)||xa(C))),f=Aw(Cw(Ow(e,t),t,S=>It(Ar(jn(S,n)),i)),t.params,t.steps,c,a,t.exampleRows),p=[...s,...Cr(s),...o.values()],m=f.map((S,x)=>{let C=u.filter(([$,,k])=>l[x]?.has($)||xa(k)).map(([,,$])=>$);return _w([S],i,[...p,...C])[0]}),h=Iw(Nw(Mw(m,Zn(s)),ir(s,n)),o,s),w=Object.fromEntries(Object.entries(t.params).filter(([,S])=>!S.includes("{date")&&/\{(?:env|data|unique):/.test(S))),b=Object.keys(t.params),y=jw(h,t);return Object.keys(w).length===0&&u.length===0?y:y.map((S,x)=>{let C=g(x),$={...Object.fromEntries(Object.entries(w).filter(([O])=>O in(d[x]??{}))),...Object.fromEntries(C.map(([O,P])=>[O,P]))},k=Object.fromEntries(C.filter(([,,O])=>!O.includes("{date")).map(([O,,P])=>[O,P])),R=Object.entries(k).filter(([,O])=>O.length<3),_=(O,P)=>{let E=R.find(([,T])=>O===(P?P(T):T));return E?`<${E[0]}>`:gr(O,k,P,!0,b)},v=O=>_(gr(O,$,void 0,!1,b)),A=(O,P)=>{let E=gr(O,$,void 0,!1,b);return(P==="pattern"?Lf(E,R):void 0)??_(E,we[P])};return{...S,actions:S.actions.map(O=>hr(O,v,A))}})}function Hf(e){let t=e.steps.map(o=>[o.text,...o.table?.flat()??[],o.docString??""]),n=t.flat(),r=t.map(()=>new Map),s=new Map;return t.forEach((o,i)=>{for(let a of o)for(let[c,l]of a.matchAll(/\{data:([^{}]*<[^<>{}]+>[^{}]*)\}/g)){let d=!0,u=`{data:${l.replace(/<([^<>]+)>/g,(g,f)=>{let p=e.params[f];return(p===void 0||/[{}<>]/.test(p))&&(d=!1),p??""})}}`;if(!(!d||n.some(g=>g.includes(u))))for(let g of[r[i],s])(g.get(u)??g.set(u,new Set).get(u)).add(c)}}),{own:r,all:s}}function jw(e,t){let{own:n,all:r}=Hf(t),s=i=>[...i].filter(([,a])=>a.size===1).map(([a,c])=>[a,[...c][0]]),o=s(r);return o.length===0&&n.every(i=>i.size===0)?e:e.map((i,a)=>{let c=new Map([...o,...s(n[a]??new Map)]);if(c.size===0)return i;let l=d=>{let u=d;for(let[g,f]of c)u=u.split(g).join(f);return u};return{...i,actions:i.actions.map(d=>hr(d,l,u=>l(u)))}})}function Nw(e,t){if(t.size===0)return e;let n=r=>typeof r=="string"?Cl(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 Mw(e,t){return t.size===0?e:e.map(n=>{let r=new Set([...n.gherkin.matchAll(Ie)].map(d=>d[1])),s=d=>Zo(d,t,r),o=d=>new Map([...t].filter(([,u])=>u.length>=4).map(([u,g])=>[u,we[d](g)])),i={quoted:o("quoted"),regex:o("regex"),pattern:o("pattern")},a=d=>d.split(/(\{(?:env|data|unique|date)[^{}]*\})/).map((u,g)=>g%2?u:s(u)).join(""),c=(d,u)=>a(Zo(d,i[u],r)),l=d=>{let u=[...t].filter(([g,f])=>r.has(g)&&f===d);return u.length===1?`{data:${u[0][0]}}`:d};return{...n,actions:n.actions.map(d=>hr(d,s,c,l))}})}function qf(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:Fr(r.url,n)}:{action:"newTab"};default:return}}function Vf(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=Ve().root+ww.sep;return{action:"uploadFile",value:r.map(i=>typeof i=="string"&&i.startsWith(s)?i.slice(s.length):i).join(`
|
|
323
|
+
`)}}}function mr(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 yo(e,t,n=[]){let r=t.context();for(let o of e.contexts())if(!(o===r||n.includes(o)))for(let i of o.pages())await i.close().catch(()=>{});await t.bringToFront().catch(()=>{});let s=r.pages().filter(o=>!o.isClosed());return{index:Math.max(s.indexOf(t),0),count:s.length,url:t.url()}}var bo=class{constructor(t,n,r,s=o=>o.newPage()){this.main=t;this.mainKey=n;this.create=r;this.newPage=s;this.follow(t,n)}main;mainKey;create;newPage;pages=new Map;others=new Map;follow(t,n){t.on("page",r=>this.pages.set(n,r))}contextOf(t){return t===this.mainKey?this.main:this.others.get(t)}contexts(){return[this.main,...this.others.values()]}opened(){return[...this.others]}async open(t){let n=await this.create(t);this.others.set(t,n),this.follow(n,t);let r=await this.newPage(n);return this.pages.set(t,r),r}livePage(t){let n=this.pages.get(t);if(n&&!n.isClosed())return n;let r=this.contextOf(t);return r&&mr(r)}pageOf=async t=>{let n=this.livePage(t);if(n)return this.pages.set(t,n),n;let r=this.contextOf(t);if(!r)return this.open(t);let s=await this.newPage(r);return this.pages.set(t,s),s};selectTab(t,n){t??=this.mainKey;let r=this.contextOf(t)?.pages().filter(s=>!s.isClosed())[n];r&&this.pages.set(t,r)}async blank(){for(let[t,n]of this.others){let r=mr(n)??await this.newPage(n);await r.goto("about:blank").catch(()=>{}),this.pages.set(t,r)}}async close(){for(let t of this.others.values())await t.close().catch(()=>{});this.others.clear()}};var _a=["chromium","chrome","msedge","firefox","webkit"],Aa={chrome:{label:"Google Chrome"},msedge:{label:"Microsoft Edge"}};function Yf(e){return _a.includes(e)}function wr(e){return e==="chromium"||Aa[e]!==void 0}var pt=class extends Error{},Ca=class extends pt{},Pa=Object.keys(Ea);function Zf(e){let t=/^(\d{2,5})x(\d{2,5})$/.exec(e.trim());return t?{width:Number(t[1]),height:Number(t[2])}:void 0}var an={aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0};async function Uw(){return new Promise((e,t)=>{let n=Fw.createServer();n.listen(0,"127.0.0.1",()=>{let{port:r}=n.address();n.close(()=>e(r))}),n.on("error",t)})}function Jf(e,t){let n=Zn(st(e)),r=Uf(t,e);return{...n.size>0?{data:Object.fromEntries([...n].sort(([s],[o])=>s.localeCompare(o)))}:{},...Object.keys(e.params).length>0?{examples:e.params}:{},...r.length>0?{rowBound:r}:{}}}function Ta(e,t){return e.livePage(t??e.mainKey)}function Qf(e){let t=e.length;for(let n=e.length-1;n>=0&&e[n].kind==="assertion";n--)t=n;return t}function vo(e,t){return e[t]?.kind==="assertion"&&t>=Qf(e)}function Wf(e,t,n=!1,r){let s=Qf(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?o:r&&i===r.stepIndex&&r.actionIndex>0?{...a,actions:[...o.actions.slice(0,r.actionIndex),...a.actions]}:a})}function zw(e,t,n,r){let s=ad(e,t);return s.length===0||!n?.pageUrl?s:[`page at failure: replay stopped at step ${n.stepIndex+1} ("${n.stepText}") on ${Fr(n.pageUrl,r)}, where the heal started.`,...s]}function Hw(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 Gf(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 Xf(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 qw(e,t,n){let r=n.success?e.map(s=>({gherkin:s.gherkin,kind:s.kind,status:"passed"})):Xf(e,n.announcedSteps??[],t,n.narrative);return e.map((s,o)=>o<t.stepIndex?s:r[o])}function Kf(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 xo=class{constructor(t){this.options=t;this.filedThisRun=t.filedThisRun??new Map}options;browser;cdpEndpoint;stepIndex;tabListeners=new Set;armDialogs;openingOwnPages=new Set;filedThisRun;get agent(){return this.options.agent}getStepIndex(){if(!this.stepIndex&&(this.stepIndex=Nt(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,s){let o=this.getStepIndex(),i=t.steps.length,a={...t.params,...pn(t.steps)},c=t.steps.map(x=>{let C=o.steps.size>0?dl(o,x,a):void 0;return C?{gherkin:x.text,keyword:x.keyword,kind:x.kind,table:x.table,docString:x.docString,fromStepSet:x.source?.fromStepSet,actions:C.actions}:void 0}),l=t.steps.map(x=>({gherkin:x.text,keyword:x.keyword,kind:x.kind,table:x.table,docString:x.docString,fromStepSet:x.source?.fromStepSet,actions:[]})),d=new Map;d.set(wt,r);let u=[],g=[],f=[],p=[],m={...an},h=x=>s.pageOf(de(t.steps[x]?.session)),w=0,b=0,y=0,S=(x,C)=>({success:x,narrative:g.join(" ")||"Composed entirely from seeded recordings.",adaptations:u,suggestedFeatureEdit:p.length>0?p.join(`
|
|
324
|
+
`):void 0,featureEdits:f,recordedSteps:l,announcedSteps:C===void 0?[]:Array.from({length:C+1},($,k)=>k),usage:m,seededCount:w});for(;y<i;){if(c[y]){let _=y;for(;_<i&&c[_];)_++;let v=c.slice(y,_),A={...t,steps:t.steps.slice(y,_)},O=await Vr(await h(y),A,this.buildCandidateCache(t,v),{sessions:s.pages,openSession:s.pageOf,baseURL:this.options.baseURL,actionTimeoutMs:this.options.actionTimeoutMs,retries:this.options.retries,pollIntervalMs:this.options.pollIntervalMs,vars:d,trace:this.options.trace!==void 0&&this.options.trace!=="off",traceStepOffset:y,envNames:We(t)}),P=O.status==="passed"?_-y:O.failure?.stepIndex??0;for(let T=0;T<P;T++)l[y+T]=v[T];if(w+=P,O.status==="passed"){y=_;continue}let E=y+P;u.push(`Seeded recording for "${t.steps[E].text}" did not replay in this scenario's context; the agent re-recorded it fresh. Divergence signal.`),c[E]=void 0,y=E;continue}if(!this.options.agent)return S(!1,y);b++;let x=y;for(;x<i&&!c[x];)x++;b>=3&&(x=i);let C=await yo(this.browser,await h(y),s.contexts()),$=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(_=>_.resolvedText):void 0,recordOnly:x<i?{from:y,to:x-1}:void 0,liveTab:C,uniqueSeed:d.get(wt),onTabOpened:this.tabWatcher(),...this.sessionHooks(t,s,n)}));if(m=Kf(m,$.usage),g.push($.narrative),u.push(...$.adaptations),f.push(...$.featureEdits),$.suggestedFeatureEdit&&p.push($.suggestedFeatureEdit),!$.success){let _=$.announcedSteps.filter(v=>v>=y&&v<i);return S(!1,_.length>0?Math.max(..._):y)}let k=$.announcedSteps.filter(_=>_>=y&&_<i),R=Math.min(i-1,Math.max(k.length>0?Math.max(...k):x-1,y));for(let _=y;_<=R;_++)l[_]=$.recordedSteps[_];y=R+1}return S(!0)}async withDialogsVisible(t){let n=()=>{},r=[],s=[],o=a=>{a.on("dialog",n),r.push(a)},i=a=>{a.on("page",o),s.push(a);for(let c of a.pages())o(c)};for(let a of this.browser?.contexts()??[])i(a);this.armDialogs=i;try{return await t()}finally{this.armDialogs=void 0;for(let a of s)a.off("page",o);for(let a of r)try{a.off("dialog",n)}catch{}}}async start(){let t=this.options.browser??"chromium";if(wr(t)){let r=await Uw();try{this.browser=await Bw.launch({headless:!this.options.headed,channel:Aa[t]?t:void 0,args:[`--remote-debugging-port=${r}`]})}catch(s){let o=s instanceof Error?s.message:String(s),i=Aa[t];throw i&&/is not found at|distribution .* is not found/i.test(o)?new Ca(`${i.label} is not installed on this machine, so --browser ${t} cannot run.
|
|
325
|
+
Install it (npx playwright install ${t} does that), or use --browser chromium, which Saffron ships with.`):s}this.cdpEndpoint=`http://127.0.0.1:${r}`}else this.browser=await(t==="firefox"?Lw:Dw).launch({headless:!this.options.headed}),this.cdpEndpoint=void 0;let n;try{n=this.contextOptions();let r=this.options.sessions??{},s=a=>typeof a=="object"&&a!==null&&!Array.isArray(a);if(!s(r))throw new pt('"sessions" in saffron.config.json must map session names to their settings, such as { "buyer": { "storageState": ".auth/buyer.json" } }.');for(let[a,c]of Object.entries(r)){let l=`{ "storageState": ".auth/${Pr(a)}.json" }`;if(!s(c)||Object.keys(c).some(d=>d!=="storageState"))throw new pt(`sessions."${a}" in saffron.config.json takes only a storageState, such as ${l}.`);if(c.storageState!==void 0&&(typeof c.storageState!="string"||c.storageState.trim()===""))throw new pt(`sessions."${a}".storageState in saffron.config.json must be a file path, such as ".auth/${Pr(a)}.json".`);if(a===$t&&c.storageState!==void 0&&ut.resolve(this.options.projectRoot,c.storageState)!==n.storageState)throw new pt(`sessions."${$t}".storageState in saffron.config.json is never read: the default session signs in with the top-level storageState. Set that instead, or make the two the same.`);a!==$t&&this.contextOptions(a)}let o=new Set([n.storageState,...Object.keys(r).filter(a=>a!==$t).map(a=>this.contextOptions(a).storageState)]),i=this.browser;await Promise.all([...o].filter(a=>typeof a=="string").map(async a=>{try{let c=JSON.parse(zt.readFileSync(a,"utf8"));if(!c||typeof c!="object"||Array.isArray(c))throw new Error("it is not a JSON object");await(await i.newContext({storageState:a})).close()}catch(c){throw new pt(`storageState file ${a} cannot be used: ${(c instanceof Error?c.message:String(c)).split(`
|
|
326
|
+
`)[0]}. Generate it again with: npx playwright open --save-storage=${Ae(this.options.projectRoot,a)} <url>`)}}))}catch(r){throw await this.stop(),r}if(this.options.device||this.options.viewport){if(t==="firefox"&&this.options.device&&Ea[this.options.device]?.isMobile)throw await this.stop(),new pt(`--device "${this.options.device}" is a mobile profile, and Playwright does not emulate mobile devices in Firefox. Run it in chromium or webkit, or give Firefox a --viewport instead.`);try{await(await this.browser.newContext(n)).close()}catch(r){await this.stop();let s=(r instanceof Error?r.message:String(r)).split(`
|
|
327
|
+
`)[0];throw new pt(`${this.options.device?`--device "${this.options.device}"`:"--viewport"} cannot run in ${t}: ${s}`)}}}async stop(){await this.browser?.close(),this.browser=void 0}resolveStorageState(t=this.options.storageState){if(!t)return;let n=ut.isAbsolute(t)?t:ut.join(this.options.projectRoot,t);if(!zt.existsSync(n))throw new pt(`storageState file not found: ${n}. Generate one with: npx playwright open --save-storage=${t} <url>`);return n}contextOptions(t){let{defaultBrowserType:n,...r}=this.options.device?Ea[this.options.device]??{}:{},s=t===void 0?void 0:this.options.sessions?.[t]?.storageState;return{storageState:this.resolveStorageState(s??this.options.storageState),...r,...this.options.viewport?{viewport:this.options.viewport}:{}}}artifacts(t){let n=tn(this.options.projectRoot,t.featurePath,t.displayName);return this.options.artifactsPerBrowser?ut.join(n,this.options.browser??"chromium"):n}buildCandidateCache(t,n){let r={version:1,feature:t.featurePath,scenario:t.name,recordedAt:new Date().toISOString(),recordedBy:"agent",steps:n,...Jf(t,n)};return{...r,version:Mr(r)}}tabWatcher(){return t=>{let n=r=>t(r);return this.tabListeners.add(n),()=>{this.tabListeners.delete(n)}}}async newContext(t,n){let r=await this.browser.newContext(this.contextOptions(t||void 0));return r.on("page",()=>{if(!this.openingOwnPages.has(r))for(let s of this.tabListeners)s(t)}),this.armDialogs?.(r),n&&this.options.trace!==void 0&&this.options.trace!=="off"&&await Zl(r,n),r}sessionsFor(t,n,r){return new bo(n,de(t.steps[0]?.session),s=>this.newContext(s,`${r} \xB7 session "${Ge(s)}"`),async s=>{this.openingOwnPages.add(s);try{return await s.newPage()}finally{this.openingOwnPages.delete(s)}})}sessionHooks(t,n,r){return{sessionPage:n.pageOf,onActiveTab:(s,o)=>n.selectTab(o,s),takeFingerprint:async s=>qs(Ta(n,s)??r)}}namedSession(t,n){return gn(n)?{session:Ge(t.mainKey)}:{}}async saveSessionTraces(t,n,r,s){let o=[],i=ot(t),a=new Set;for(let[c,l]of n.opened()){if(!r){await Gs(l).catch(()=>{});continue}let d=Pr(Ge(c));for(let f=2;a.has(d);f++)d=`${Pr(Ge(c))}-${f}`;a.add(d);let u=ut.join(this.artifacts(t),`${r}.${d}.zip`),g=await Ks(l,u,i);g&&(this.claimArtifactDir(t),o.push({...s,kind:"trace",file:Ae(this.options.projectRoot,u),sha256:g,session:Ge(c)}))}return o}async proofReplay(t,n,r,s){let o=this.options.trace!==void 0&&this.options.trace!=="off",i=s?t.displayName:`${t.displayName} (proof replay)`,a=await this.newContext(de(t.steps[0]?.session),i),c=this.sessionsFor(t,a,i),l=await a.newPage();return{result:await Vr(l,t,n,{sessions:c.pages,openSession:c.pageOf,baseURL:this.options.baseURL,actionTimeoutMs:this.options.actionTimeoutMs,retries:this.options.retries,pollIntervalMs:this.options.pollIntervalMs,uniqueSeed:r,trace:o,tracePhase:s}),context:a,page:l,sessions:c}}async runScenario(t,n={}){let r=await this.runScenarioInner(t,n),s=ot(t);if(s.size>0){let o=a=>a===void 0?a:it(a,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(a=>it(a,s));let i=[r.stepResults,r.executionStepResults,...(r.evidence??[]).map(a=>a.traceSteps)];for(let a of i.flatMap(c=>c??[])){a.error=o(a.error);for(let c of a.tabs??[])c.url=it(c.url,s);for(let c of a.responses??[])c.url=it(c.url,s)}}return r}async screenshot(t,n,r,s){let o=this.options.screenshot??"viewport";if(o!=="off")try{let i=this.artifacts(n);this.claimArtifactDir(n);let a=ut.join(i,`${r}.jpg`),c=await t.screenshot({path:a,type:"jpeg",quality:80,fullPage:o==="full-page",timeout:5e3});return{kind:r,file:Ae(this.options.projectRoot,a),step:s,sha256:At(c)}}catch{return}}claimArtifactDir(t){let n=tn(this.options.projectRoot,t.featurePath,t.displayName);zt.mkdirSync(this.artifacts(t),{recursive:!0}),zt.writeFileSync(ut.join(n,On),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=fe(s,t.featurePath,t.name),d;try{d=He(l)}catch(E){if(!(E instanceof ge))throw E;return{scenario:t,status:"red",source:"cache",stepResults:[],adaptations:[],usage:an,durationMs:Date.now()-r,error:`The recording cannot be read: ${E.problem}. Fix the file, or re-record it with saffron run --rerecord.`}}let u=ct(s,t.featurePath,t.name),g=Ae(s,u),f,p;if(zt.existsSync(u))try{({proposal:f,revision:p}=Ls(u))}catch(E){if(!(E instanceof ge)&&E.code!=="ENOENT")throw E;f=void 0}let m=!1;f&&!vl(s,u,p)&&(m=!this.options.rerecord,f=void 0),f&&dt(s,f,t)&&(f=void 0),f&&this.options.rerecord&&this.filedThisRun.get(u)!==p&&cr(t,f.cache)&&(f=void 0);let h=d&&cr(t,d)||f&&cr(t,f.cache);if(h)return{scenario:t,status:"red",source:"cache",stepResults:[],adaptations:[],usage:an,durationMs:Date.now()-r,error:h};let w=E=>E.status==="stale"?"the committed recording no longer matches the scenario":`the committed recording failed${E.failure?` at "${E.failure.stepText}"`:""}`,b=E=>{let T=on(s)[g],M=T?.revision===p?` from ${ue(ns(T.from))}`:"",I=E?w(E):"";return{scenario:t,status:"yellow",source:d?"cache":"agent-record",stepResults:E?.stepResults??[],narrative:(I?`${I[0].toUpperCase()}${I.slice(1)}. `:"")+`A proposal${M} is pending review at ${g}. It was not filed on this machine, so this run does not replay it, heal or record over it. Review it with saffron diff ${g}, then saffron accept or saffron reject it.`,adaptations:[],proposalFile:g,proposalRevision:p,usage:an,durationMs:Date.now()-r}};if(zt.rmSync(this.artifacts(t),{recursive:!0,force:!0}),this.options.artifactsPerBrowser){let E=tn(s,t.featurePath,t.displayName);for(let T of zt.existsSync(E)?zt.readdirSync(E,{withFileTypes:!0}):[])T.isFile()&&T.name!==On&&zt.rmSync(ut.join(E,T.name),{force:!0})}if(m&&!d)return b();let y=(E,T)=>({scenario:t,status:"yellow",source:"agent-record",proposalReplay:!0,stepResults:E.stepResults,narrative:`Replayed the pending proposal recorded for "${f.meta.recordedFor??t.name}" at zero AI${T?` instead of ${T.status==="stale"?"recording":"healing"} again: ${w(T)}`:""}; accept it to go green.`,adaptations:[],verified:!0,proposalFile:g,proposalRevision:p,usage:an,durationMs:Date.now()-r}),S=this.options.trace??"off",x=S!=="off",C=await this.newContext(de(t.steps[0]?.session),t.displayName),$=this.sessionsFor(t,C,t.displayName),k=!x,R,_,v=await C.newPage(),A=wn(),O=[],P=(E,T)=>this.screenshot(E,t,"before-heal",T.stepText).then(M=>{M&&O.push(M)});try{let E=await(async()=>{let I;if(f&&!d){let U=await Vr(v,t,f.cache,{sessions:$.pages,openSession:$.pageOf,baseURL:o,actionTimeoutMs:i,retries:a,pollIntervalMs:c,uniqueSeed:A,trace:x,tracePhase:"pending"}),Y=f.meta.recordedFor??t.name;if(U.status==="passed")return y(U);if(Object.keys(t.params).length>0&&Y!==t.displayName){let Z=U.failure;return{scenario:t,status:"red",source:"agent-record",proposalReplay:!0,stepResults:U.stepResults,adaptations:[],proposalFile:g,proposalRevision:p,usage:an,durationMs:Date.now()-r,error:`The pending proposal recorded for "${Y}" does not replay for this Examples row`+(Z?` (step "${Z.stepText}": ${Z.error.split(`
|
|
328
|
+
`)[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(it(` \u21BA pending proposal for "${t.displayName}" did not replay`+(U.failure?` (step "${U.failure.stepText}": ${U.failure.error.split(`
|
|
329
|
+
`)[0]})`:"")+"; recording again",ot(t))),await v.goto("about:blank")}if(d){if(I=await Vr(v,t,d,{sessions:$.pages,openSession:$.pageOf,baseURL:o,actionTimeoutMs:i,retries:a,pollIntervalMs:c,uniqueSeed:A,trace:x,onFailure:P,keepResponseLog:!0}),I.status==="passed")return{scenario:t,status:"green",source:"cache",stepResults:I.stepResults,adaptations:[],usage:an,durationMs:Date.now()-r};if(m)return I.responses?.detach(),b(I);let U=Y=>d.steps[Y].kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||vo(d.steps,Y));if(f&&I.status==="failed"&&d.steps.some((Y,V)=>U(V)&&!gi(f.cache.steps[V]?.actions??[],Y.actions))&&(f=void 0),f){let Y=wn(),V=await this.proofReplay(t,f.cache,Y,"pending");if(V.result.status==="passed")return I.responses?.detach(),R=V.context,_=V.sessions,A=Y,y(V.result,I);await V.sessions.close(),await V.context.close(),console.log(it(` \u21BA pending proposal for "${t.displayName}" did not replay`+(V.result.failure?` (step "${V.result.failure.stepText}": ${V.result.failure.error.split(`
|
|
330
|
+
`)[0]})`:"")+(I.status==="failed"?"; healing":"; recording again"),ot(t)))}}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.";I?.responses?.detach();let Y=d!==void 0&&d.examples===void 0&&Object.keys(t.params).length>0&&d.steps.length===t.steps.length&&d.steps.every((V,Z)=>{let oe=t.steps[Z];return V.gherkin===oe.text&&V.kind===oe.kind&&V.docString===oe.docString&&JSON.stringify(V.table)===JSON.stringify(oe.table)})&&Object.entries(d.data??{}).every(([V,Z])=>{try{return Je(V)===Z}catch{return!0}});return{scenario:t,status:"red",source:"cache",stepResults:I?.stepResults??[],adaptations:[],usage:an,durationMs:Date.now()-r,error:d?I?.status==="stale"?Y?`The recording was made by an older saffron-ai and still holds another Examples row's value, so this row needs it recorded again once, and ${U}`:`Cache is stale (feature file changed) and ${U}`:`Replay failed and ${U} ${I?.failure?.error??""}`.trimEnd():`No cache exists and ${U}`}}let z=d!==void 0&&I!==void 0&&I.status==="failed",N=0,L,G;try{if(z){G=I.responses;let U=$.contextOf(de(t.steps[I.failure.stepIndex]?.session))??v.context(),Y=await yo(this.browser,I.activePage??mr(U,I.failure.pageUrl)??v,$.contexts());L=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:o,traceContext:x?v.context():void 0,mode:"heal",liveTab:Y,model:this.options.healModel,cdpEndpoint:this.cdpEndpoint,projectRoot:this.options.projectRoot,assertionPolicy:this.options.assertionPolicy,completedSteps:I.stepResults.filter(V=>V.status==="passed").map(V=>V.gherkin),failedStep:{text:I.failure.stepText,kind:I.failure.kind,error:I.failure.error,pageUrl:I.failure.pageUrl,stepIndex:I.failure.stepIndex},uniqueSeed:A,onTabOpened:this.tabWatcher(),...this.sessionHooks(t,$,v)}))}else if(await v.goto("about:blank"),await $.blank(),$.pages.set($.mainKey,v),this.options.reuseSteps!==!1){let U=await this.recordWithSeeding(t,v,A,$);N=U.seededCount,L=U}else L=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:o,traceContext:x?v.context():void 0,mode:"record",cdpEndpoint:this.cdpEndpoint,projectRoot:this.options.projectRoot,assertionPolicy:this.options.assertionPolicy,uniqueSeed:A,onTabOpened:this.tabWatcher(),...this.sessionHooks(t,$,v)}))}catch(U){G?.detach();let Y=U instanceof Error?U.message:String(U);return{scenario:t,status:"red",source:z?"agent-heal":"agent-record",stepResults:I?.stepResults??[],adaptations:[],usage:an,durationMs:Date.now()-r,error:`Agent invocation failed: ${Y.split(`
|
|
331
|
+
`)[0]}`}}if(L.success&&z&&I.failure.kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||vo(d.steps,I.failure.stepIndex))){let U=d.steps[I.failure.stepIndex],Y=Ta($,de(t.steps[I.failure.stepIndex]?.session))??v,V=new Map(Object.entries(I.captured)),Z=Li(t,I.failure.stepIndex);try{for(let oe of U.actions)await Xs(Y,oe,Z,this.options.actionTimeoutMs??5e3,o,V,G,void 0,We(t))}catch(oe){let ve=oe instanceof Error?oe.message:String(oe),qt=`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: ${ve.split(`
|
|
332
|
+
`)[0]}`,gt=I.failure.stepIndex,rt=I.stepResults.map((Re,Tr)=>Tr===gt?{...Re,status:"failed",error:qt}:Re);return{scenario:t,status:"red",source:"agent-heal",stepResults:rt,executionStepResults:rt.map((Re,Tr)=>Tr>gt&&Re.status==="skipped"?{...Re,status:"passed"}:Re),narrative:L.narrative,adaptations:L.adaptations,suggestedFeatureEdit:L.suggestedFeatureEdit,usage:L.usage,durationMs:Date.now()-r,error:qt}}finally{G?.detach()}}return G?.detach(),await this.finalizeAgentRun(t,L,z,d,r,N,z?I?.failure:void 0,A)})(),T=O.find(I=>I.kind==="before-heal");if(E.source==="cache"&&T){let I=T.file.replace(/before-heal\.jpg$/,"failure.jpg");try{zt.renameSync(ut.join(s,T.file),ut.join(s,I)),T.file=I}catch{}T.kind="failure"}else if(E.status==="red"){let I=E.stepResults.findIndex(L=>L.status==="failed"),F=E.stepResults[I]?.gherkin,z=de(t.steps[Math.max(I,0)]?.session),N=await this.screenshot(Ta(_??$,z)??v,t,"failure",F);N&&O.push(N)}let M=ir(st(t),A);if(M.size>0&&(E.uniques=Object.fromEntries(M)),O.push(...E.evidence??[]),x){let F=S==="on"||E.status!=="green"?ut.join(this.artifacts(t),_i):void 0;k=!0;let z=R??C;F||await Gs(z).catch(()=>{});let N=F?await Ks(z,F,ot(t)):void 0,L=ot(t),G=(E.executionStepResults??E.stepResults).map(V=>({...V,error:V.error&&it(V.error,L)})),U=_??$,Y=await this.saveSessionTraces(t,U,F&&N?ut.basename(F,".zip"):void 0,{traceSteps:G});F&&N&&(this.claimArtifactDir(t),O.unshift({kind:"trace",file:Ae(s,F),sha256:N,traceSteps:G,...this.namedSession(U,t.steps)},...Y))}return O.length>0&&(E.status!=="green"||O.some(I=>I.kind==="trace"))&&(E.evidence=O),E}finally{k||await Gs(C).catch(()=>{}),await _?.close(),await R?.close(),await $.close(),await C.close()}}async finalizeAgentRun(t,n,r,s,o,i=0,a,c=wn()){let l=r?"agent-heal":"agent-record",d=n.success?n.recordedSteps.map(N=>({gherkin:N.gherkin,kind:N.kind,status:"passed"})):Xf(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 u=r?Wf(s.steps,n.recordedSteps,this.options.assertionPolicy==="adaptable-mid",a?{stepIndex:a.stepIndex,actionIndex:a.actionIndex}:void 0):n.recordedSteps,g=[...n.adaptations,...r&&a?Gf(n.recordedSteps,a.stepIndex):[]],f={...n.usage},p,m,h,w,b=[],y=0,S=new Set,x,C=async({context:N,sessions:L},G,U=G.stepResults)=>{if(!S.has(N)){S.add(N);try{if(this.options.trace&&this.options.trace!=="off"){let Y=`proof-${++y}`,V=ut.join(this.artifacts(t),`${Y}.zip`),Z=ot(t),oe=await Ks(N,V,Z),ve=G.captured[wt],qt=ve?ir(st(t),ve):new Map,gt={proof:!0,traceSteps:U.map(Re=>({...Re,error:Re.error&&it(Re.error,Z)})),traceUniques:qt.size?Object.fromEntries(qt):void 0},rt=await this.saveSessionTraces(t,L,oe?Y:void 0,gt);oe&&(this.claimArtifactDir(t),b.push({kind:"trace",file:Ae(this.options.projectRoot,V),sha256:oe,...gt,...this.namedSession(L,t.steps)},...rt))}}finally{await L.close(),await N.close()}}};if(this.options.verifyProposals!==!1){let N=await this.proofReplay(t,this.buildCandidateCache(t,u),wn());w=N.result.captured[wt];try{if(N.result.status!=="passed"&&N.result.failure){let L=N.result.failure;if(this.options.agent&&!(r&&L.kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||vo(s.steps,L.stepIndex))))try{let U=N.sessions.contextOf(de(t.steps[L.stepIndex]?.session))??N.context,Y=await yo(this.browser,N.result.activePage??mr(U,L.pageUrl)??N.page,N.sessions.contexts()),V=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:"refine",model:r?this.options.healModel:void 0,cdpEndpoint:this.cdpEndpoint,projectRoot:this.options.projectRoot,assertionPolicy:this.options.assertionPolicy,completedSteps:N.result.stepResults.filter(Z=>Z.status==="passed").map(Z=>Z.gherkin),failedStep:{text:L.stepText,kind:L.kind,error:L.error,pageUrl:L.pageUrl,stepIndex:L.stepIndex},liveTab:Y,uniqueSeed:N.result.captured[wt],onTabOpened:this.tabWatcher(),...this.sessionHooks(t,N.sessions,N.page)}));f=Kf(f,V.usage),x=qw(N.result.stepResults,L,V),V.success&&(g.push(...V.adaptations),g.push(...Gf(V.recordedSteps,L.stepIndex)),u=r?Wf(u,V.recordedSteps,this.options.assertionPolicy==="adaptable-mid",{stepIndex:L.stepIndex,actionIndex:0}):Hw(u,V.recordedSteps,L.stepIndex),await C(N,N.result,x),x=void 0,N=await this.proofReplay(t,this.buildCandidateCache(t,u),wn()),w=N.result.captured[wt])}catch{}}for(let L of N.result.tabOpeners??[]){let G=u[L.stepIndex]?.actions[L.actionIndex];G&&(G.opensTab=!0)}p=N.result.status==="passed",p||(m=N.result.failure?.error??`proof replay ${N.result.status}`,h=N.result.stepResults)}finally{await C(N,N.result,x).catch(()=>{})}}r&&s&&g.push(...zw(s.steps,u,a,this.options.baseURL));let $=N=>r&&t.steps[N]?.kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||vo(s.steps,N)),k=n.featureEdits.filter(N=>!$(N.index));for(let N of fl(u,Nt(this.options.projectRoot)))g.push(`duplicate wording: "${N.from}" recorded exactly the same actions as the existing step "${N.to}" (${N.feature} \u203A ${N.scenario}). Accept with --with-feature-edit to converge on the canonical wording.`),k.some(L=>L.index===N.index)||k.push({index:N.index,text:N.to});let R=Bf(u);R.length>0&&(p=!1,m=[m,...R].filter(Boolean).join(" "));let _=ot(t),v=N=>_.size>0?it(N,_):N;g=g.map(v);let A=k.map(N=>({index:N.index,text:v(N.text)})),O=v(n.narrative),P=n.suggestedFeatureEdit?v(n.suggestedFeatureEdit):void 0,E={version:1,feature:t.featurePath,scenario:t.name,recordedAt:new Date().toISOString(),recordedBy:"agent",steps:u,...Jf(t,u)},T={...E,version:Mr(E)},M={meta:{createdAt:T.recordedAt,mode:r?"heal":"record",narrative:O,adaptations:g,suggestedFeatureEdit:P,featureEdits:A.length>0?A:void 0,verified:p,proofError:m?v(m):void 0,seededSteps:i>0?i:void 0,recordedFor:t.displayName,usage:f,bound:wd(t,s,T,A.length>0?A:void 0)},cache:T},I=ct(this.options.projectRoot,t.featurePath,t.name),F=wl(I,M);xl(this.options.projectRoot,I,F),this.filedThisRun.set(I,F);let z=He(fe(this.options.projectRoot,t.featurePath,t.name));return{proposalDiff:bn(z,M.cache),scenario:t,status:"yellow",source:l,stepResults:h??d,executionStepResults:d,evidence:b,proofUniques:(()=>{let N=w?ir(st(t),w):void 0;return N&&N.size>0?Object.fromEntries(N):void 0})(),narrative:O,adaptations:g,suggestedFeatureEdit:P,featureEdits:A.length>0?A:void 0,verified:p,proofError:m,seededSteps:i>0?i:void 0,proposalFile:Ae(this.options.projectRoot,I),proposalRevision:F,usage:f,durationMs:Date.now()-o}}};import jo from"node:fs";import qy from"node:os";import _u from"node:path";import{query as hy}from"@anthropic-ai/claude-agent-sdk";import{McpServer as Vw}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as X}from"zod";var De=e=>({content:[{type:"text",text:e}]});function yr(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 Jw(e){let t=new Vw({name:e.name,version:e.version});for(let n of e.tools)n(t);return{type:"sdk",name:e.name,instance:t}}function eu(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 Ww=new Set(["main","banner","contentinfo","status","alert","alertdialog","dialog","search"]);function tu(e){if(!e?.role)return;let{role:t,frame:n,...r}=e;if(!(Object.keys(r).length>0||Ww.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 Gw(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 nu=new WeakSet;function Kw(e,t){if(t.success&&!nu.has(e)){let n=[...e.announced].filter(r=>r>=e.firstStep&&e.steps[r]?.kind==="assertion"&&!e.steps[r].actions.some(s=>at.has(s.action))).sort((r,s)=>r-s);if(n.length>0)return nu.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=>!di.test(n.text)&&n.text.trim()!==""),"Run finalized."}var ru={role:X.string().optional().describe("ARIA role of the element"),name:X.string().optional().describe("Accessible name \u2014 use the SHORTEST stable substring; never include volatile content like prices or dates"),nameRegex:X.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:X.string().optional().describe("Form-label text for getByLabel \u2014 the literal <label> text only, never a free-text description"),text:X.string().optional().describe("getByText locator text"),selector:X.string().optional().describe("CSS fallback selector"),frame:X.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 So(e){return Jw({name:"saffron",version:"0.1.0",tools:[yr("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:X.number().int().min(0),text:X.string(),adaptation:X.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=>De(Gw(e,t))),yr("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:X.string().describe("Name to store the captured text under"),...ru},async t=>{let n=eu(t);if(!n)return De("ERROR: capture needs a target (role/name, nameRegex, label, text, or selector).");let r=tu(n);return r?De(r):(e.addActions([{action:"captureText",target:n,saveAs:t.saveAs}]),De(`Capture recorded as "${t.saveAs}".`))}),yr("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:X.boolean().describe("true = accept/OK the dialog, false = dismiss/cancel"),promptText:X.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}:{}}),De(`Dialog handling recorded (${t.accept?"accept":"dismiss"}).`))),yr("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:X.string().describe("Regex matched against the response URL \u2014 path-only for portability"),method:X.string().optional().describe("HTTP method to match (any if omitted)"),status:X.string().optional().describe("Expected status \u2014 exact ('201') or class ('2xx'); default any 2xx"),bodyPattern:X.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}:{}}]),De("Network wait recorded."))),yr("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:X.enum(["visible","notVisible","text","url","value","differs","matches","attribute","response","each"]),...ru,expected:X.string().optional().describe("Expected text/value for kind=text|value \u2014 stable text only, never volatile values"),url:X.string().optional().describe("URL substring for kind=url (path only, no host)"),pattern:X.string().optional().describe("kind=matches|attribute: regex the target's text (or attribute) must match, e.g. 'NOK [\\\\d,]+' for a price"),attribute:X.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:X.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:X.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:X.string().optional().describe("kind=response: HTTP method to match (any if omitted)"),status:X.string().optional().describe("kind=response: expected status \u2014 exact ('201') or class ('2xx'); default any 2xx"),bodyPattern:X.string().optional().describe("kind=response: regex the response body must match (verify via browser_network_requests first)"),each:X.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:X.string().optional().describe("kind=differs: name of the captured value to compare against")},async t=>{let n=eu(t),r=tu(n);if(r)return De(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 De("ERROR: kind=differs requires compareTo.");if(!t.capture&&!n)return De("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 De("ERROR: kind=matches requires pattern.");s={action:"expectMatches",target:n,pattern:t.pattern};break;case"attribute":if(!t.attribute||!t.pattern)return De("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 De("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 De("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?De("ERROR: assertion needs a target (role/name, nameRegex, label, text, or selector)."):(e.addActions([s]),De("Assertion recorded."))}),yr("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:X.boolean(),narrative:X.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:X.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:X.array(X.object({index:X.number().int().min(0).describe("zero-based step index"),text:X.string().min(1).regex(/\S/,"a step text cannot be blank").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=>De(Kw(e,t)))]})}function ko(e={}){let t=e.deliberateSnapshots?`
|
|
306
333
|
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.
|
|
307
334
|
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.
|
|
308
335
|
|
|
@@ -320,38 +347,39 @@ Non-negotiable rules:
|
|
|
320
347
|
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.
|
|
321
348
|
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.
|
|
322
349
|
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.
|
|
323
|
-
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 ${
|
|
350
|
+
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 ${ki.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.
|
|
324
351
|
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.
|
|
325
|
-
7. Never ask the user questions; you are unattended.${t}`}function
|
|
326
|
-
${
|
|
327
|
-
`)}`),
|
|
352
|
+
7. Never ask the user questions; you are unattended.${t}`}function Yw(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 Zw=`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.`,Qw=`BROWSER SESSIONS: this scenario runs in several browser sessions, one per person, each a separate browser with its own cookies, login and tabs. [session: ...] on each step names its session ("default" for the steps before the first As "..."). Your browser tools act in the session of the step you announced last with saffron_step, so always announce a step before acting for it, and when the next step is in another session, call saffron_step for it on its own and wait for its reply before any browser call; browser_tabs lists that session's tabs only. A session keeps its page while you work in another one: when you come back to it, take a snapshot before acting. Never sign one session in as another session's person.`;function $o(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 su(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 Ro(e){let{scenario:t}=e,n=We(t),r=gn(t.steps),s=t.steps.map((i,a)=>{let c=p=>Es(Sc(jn(p,e.uniqueSeed??"")),n),l=r?` [session: ${Ge(de(i.session))}]`:"",d=`${a}. [${Yw(t.steps,a)}]${l} ${i.keyword} ${c(i.resolvedText)}`,u=i.resolvedTable??i.table,g=i.resolvedDocString??i.docString,f=d;return u&&(f+=`
|
|
353
|
+
${u.map(p=>` | ${p.map(c).join(" | ")} |`).join(`
|
|
354
|
+
`)}`),g!==void 0&&(f+=`
|
|
328
355
|
"""
|
|
329
|
-
${
|
|
330
|
-
`).map(
|
|
356
|
+
${c(g).split(`
|
|
357
|
+
`).map(p=>` ${p}`).join(`
|
|
331
358
|
`)}
|
|
332
|
-
"""`),
|
|
333
|
-
`),
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
${
|
|
337
|
-
|
|
338
|
-
${e.
|
|
339
|
-
|
|
340
|
-
`),"",`
|
|
341
|
-
`)
|
|
342
|
-
`);if(!A.includes(Ad))throw new Error(A.replace(/^### Error\s*/,"").trim()||"the browser backend did not start")}catch(k){throw await Promise.allSettled([$.close(),R?.close()]),w(!1),k}let m=Promise.resolve(),v=(k,h,y=t())=>{let A=m.then(()=>Pi(e,y,k,h));return m=A.catch(()=>{}),A},S=To($,(k,h,y)=>v(hm(k,h),y),s.projectRoot),x=async()=>{let k=[...p];if(k.length===0)return;let h=Promise.all(k.map(A=>A.path().then(()=>!0,()=>!0))),y=!await Promise.race([h,_s(um).then(()=>!1)]);y&&Ci++;try{y&&(await Promise.allSettled(k.map(A=>A.cancel())),await Promise.allSettled(k.map(A=>A.failure()))),await _s(0),await _s(0)}finally{y&&Ci--}};return{config:{type:"sdk",name:"playwright",instance:S},close:async()=>{await Promise.race([m,_s(pm)]),await x().catch(()=>{}),await Promise.allSettled([$.close()]),await Promise.allSettled([R.close()]),await Promise.allSettled([S.close()]),w(!0)},grouped:(k,h)=>v(k,h)}}var ym=wm(import.meta.url);function bm(){let e=ym.resolve("@playwright/mcp/package.json");return Cd.join(Cd.dirname(e),"cli.js")}var vm=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"]),Sm=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 Oi(e,t){if(Sm.has(e))return!1;if(e==="mcp__playwright__browser_tabs"){let n=t?.action;return!(n==="list"||n==="select"||n==="close")}return!0}var Un=class e{constructor(t,n){this.ctx=t;this.snapshotMode=n;this.state=new Ss(t.scenario,{firstStep:od(t),discardBeforeAnnounce:sd(t)})}ctx;snapshotMode;state;usage={aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0};resultText="";traced;capped;outputDir=cc();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=ct(t.scenario);try{s.traced=await Id(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: ${et(a,o)}`)},{outputDir:s.outputDir,projectRoot:s.projectRoot})}catch(i){r.traceBridgeUnavailable=!0;let a=et(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 dc(this.playwrightStdio(),this.projectRoot),this.capped.config)}playwrightStdio(){return{command:process.execPath,args:[bm(),"--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?Pi(this.ctx.traceContext,this.currentStep(),n,t):t()}async beforeTool(t,n){if(this.state.beginToolCall(t),vm.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=fd(n,r);o&&this.state.addArmedAction(o);let i=dd(n,r,this.ctx.baseURL);if(i&&this.state.addActions([i]),n.startsWith("mcp__playwright__")){let a=id(s);a!==void 0&&this.ctx.onActiveTab?.(a),this.state.addActions(ad(s,this.ctx.baseURL)),this.state.pendingFingerprint=void 0}this.state.endToolCall(t,Oi(n,r))}failedTool(t,n,r){n.startsWith("mcp__playwright__")&&(this.state.pendingFingerprint=void 0),this.state.endToolCall(t,Oi(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(),mm.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:Gt(r.text,t.scenario.params)})),recordedSteps:ld(n.steps,t.scenario,t.uniqueSeed),announcedSteps:[...n.announced].sort((r,s)=>r-s),usage:this.usage}}};var Is=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 Td();return{subscriptionType:t.subscriptionType,fiveHourBefore:t.utilization,fiveHourAfter:n?.utilization,resetsAt:n?.resetsAt??t.resetsAt}}async run(t){let n=await Un.open(t,this.opts.snapshotMode??"none",this),r;try{r=xm({prompt:Es(t),options:{systemPrompt:Ts({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:ks(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=Ii(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 $m from"node:http";import{randomBytes as km,randomUUID as Rm,timingSafeEqual as Tm}from"node:crypto";import{Client as Em}from"@modelcontextprotocol/sdk/client/index.js";import{InMemoryTransport as Am}from"@modelcontextprotocol/sdk/inMemory.js";import{Server as _m}from"@modelcontextprotocol/sdk/server/index.js";import{StreamableHTTPServerTransport as Im}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as Cm,ListToolsRequestSchema as Pm}from"@modelcontextprotocol/sdk/types.js";async function Om(e,t){let n=km(16).toString("hex"),r=Buffer.from(`Bearer ${n}`),s=c=>{let l=Buffer.from(c??"");return l.length===r.length&&Tm(l,r)},o=(c,l)=>{let d=new _m({name:c,version:"1"},{capabilities:{tools:{}}});return d.setRequestHandler(Pm,p=>l.listTools(p.params)),d.setRequestHandler(Cm,async p=>{let u=Rm(),f=`mcp__${c}__${p.params.name}`,g=p.params.arguments??{};await t.beforeTool(u,f);try{let w=await l.callTool(p.params,void 0,{timeout:ko});return w.isError?t.failedTool(u,f,g):t.afterTool(u,f,g,w),w}catch(w){throw t.failedTool(u,f,g),w}}),d},i=$m.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 Im({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 Pd(e){let[t,n]=Am.createLinkedPair();await e.connect(n);let r=new Em({name:"saffron-gateway",version:"1"});return await r.connect(t),r}async function Od(e){let t=[];try{let n=await Pd((await e.playwrightServer()).instance);t.push(n);let r=await Pd(ks(e.state).instance);t.push(r);let s=await Om({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 Cs=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 Un.open(t,this.opts.snapshotMode??"none",this),s;try{s=await Od(r)}catch(o){throw await r.close(),o}r.watchTabs();try{await this.drive({systemPrompt:Ts({deliberateSnapshots:r.snapshotMode==="none",adaptableMidAssertions:t.assertionPolicy==="adaptable-mid"}),prompt:Es(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 vr(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 zn(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 Hn from"node:fs";import ji from"node:os";import yt from"node:path";import{createHash as jm}from"node:crypto";import{createRequire as jd}from"node:module";function Nm(){try{let e=jd(import.meta.resolve("@openai/codex-sdk")).resolve("@openai/codex/package.json"),t=jd(e).resolve(`@openai/codex-${process.platform}-${process.arch}/package.json`),n=yt.join(yt.dirname(t),"vendor");for(let r of Hn.readdirSync(n))for(let s of[yt.join(n,r,"bin","codex"),yt.join(n,r,"codex","codex")])if(Hn.existsSync(s))return s}catch{}}function Ps(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 Mm(e){return`'${e.replaceAll("'","'\\''")}'`}function Fm(){let e=Ps();if(e)throw new Error(e);let t=Nm();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=yt.join(process.env.XDG_CACHE_HOME||yt.join(ji.homedir(),".cache"),"saffron");Hn.mkdirSync(n,{recursive:!0});let r=yt.join(n,`codex-${jm("sha256").update(t).digest("hex").slice(0,12)}`);return Oe(r,`#!/bin/sh
|
|
359
|
+
"""`),f}).join(`
|
|
360
|
+
`),o=[`Feature: ${t.featureName} (${t.featurePath})`,`Scenario: ${t.displayName}`,e.baseURL?`Base URL: ${e.baseURL}`:void 0,"",r?"Steps (index. [kind] [session] keyword text):":"Steps (index. [kind] keyword text):",s,"",r?`${Qw}
|
|
361
|
+
`:void 0];if(e.mode==="refine")o.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.",$o(e),"",`Steps that replayed fine:
|
|
362
|
+
${(e.completedSteps??[]).map(i=>` \u2713 ${i}`).join(`
|
|
363
|
+
`)||" (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.",su(e));else if(e.mode==="heal")o.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.",$o(e),"",`Steps already completed by replay:
|
|
364
|
+
${(e.completedSteps??[]).map(i=>` \u2713 ${i}`).join(`
|
|
365
|
+
`)||" (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)?",Zw,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.",su(e));else if(e.mode==="record"&&e.recordOnly){let{from:i,to:a}=e.recordOnly;o.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):
|
|
366
|
+
${e.completedSteps.map(c=>` \u2713 ${c}`).join(`
|
|
367
|
+
`)}`:"You are starting from a blank page.",$o(e),"",`Record ONLY steps ${i} through ${a} (inclusive).`,`CRITICAL STOP RULE: the steps AFTER step ${a} already have recordings and will be replayed automatically the moment you stop. After completing step ${a}, 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 i=e.completedSteps.length;o.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(a=>` \u2713 ${a}`).join(`
|
|
368
|
+
`),"",`The browser currently shows the state after those ${i} step(s) (verify with a snapshot if unsure). Do NOT redo them and do NOT navigate away from the current state.`,$o(e),`Start with saffron_step for step index ${i} and record from there to the end.`)}else o.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 o.filter(i=>i!==void 0).join(`
|
|
369
|
+
`)}import{query as Xw}from"@anthropic-ai/claude-agent-sdk";var ey="usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET";async function Oa(e,t=8e3){let n=e?.[ey];if(typeof n!="function")return;let r;try{let s=await Promise.race([n.call(e,{skipBehaviors:!0}),new Promise(o=>{r=setTimeout(()=>o(void 0),t),r.unref?.()})]);return ty(s)}catch{return}finally{r&&clearTimeout(r)}}function ty(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 ou(){let e=()=>{},t=new Promise(s=>e=s);async function*n(){await t}let r;try{let s=Xw({prompt:n(),options:{maxTurns:1,tools:[],settingSources:[],persistSession:!1}});r=s;let o=(async()=>{try{for await(let a of s);}catch{}})(),i=await Oa(s);return e(),r.close?.(),await o,i}catch{e(),r?.close?.();return}}import fu from"node:fs";import uu from"node:path";import{createRequire as dy}from"node:module";import{createRequire as iu}from"node:module";var ny=iu(import.meta.url),To=iu(ny.resolve("playwright/package.json"));import{Client as ry}from"@modelcontextprotocol/sdk/client/index.js";import{InMemoryTransport as sy}from"@modelcontextprotocol/sdk/inMemory.js";var au=1e4,oy=5e3,cu="saffron_connection_check",iy=()=>!0,ay=()=>!1,as=e=>new Promise(t=>{setTimeout(t,e).unref()}),cs=new Set,Ia=0,lu=e=>{Ia===0&&[...cs].at(-1)?.(e)};function cy(e){let t=n=>e(n);return cs.size===0&&process.on("unhandledRejection",lu),cs.add(t),()=>{cs.delete(t)&&cs.size===0&&process.off("unhandledRejection",lu)}}async function ja(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 ly(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}var Hn=class extends Error{};async function du(e,t,n="none",r=()=>{},s={},o){let{createConnection:i,resolveCLIConfigForMCP:a}=To("playwright-core/lib/coreBundle").tools,c=await a?.({},process.env)??{},l={...c,browser:{...c.browser,isolated:!1},sharedBrowserContext:!0,imageResponses:"omit",...s.outputDir?{outputDir:s.outputDir}:{},snapshot:{...c.snapshot,mode:n}},d=cy(r),u=new Set,g=P=>{u.add(P)},f=async(P,E)=>{let T=P.browser(),M=new Set(T?.listeners("disconnected")??[]),I=G=>{G.on("download",g)};for(let G of P.pages())I(G);P.on("page",I);let F=G=>{P.off("page",I);for(let U of P.pages())U.off("download",g);for(let U of T?.listeners("disconnected")??[])M.has(U)||T.off("disconnected",U);return G?m(P):void 0},z,N=new ry({name:"saffron-trace",version:"1"});try{z=await i(l,async()=>P);let[G,U]=sy.createLinkedPair();await z.connect(U),await N.connect(G);let V=((await N.callTool({name:cu,arguments:{}})).content??[]).map(ve=>ve.text??"").join(`
|
|
370
|
+
`);if(!V.includes(cu))throw new Error(V.replace(/^### Error\s*/,"").trim()||"the browser backend did not start");let Z=P.pages().filter(ve=>!ve.isClosed()),oe=E?Z.indexOf(E):-1;if(oe>0&&(await N.callTool({name:"browser_tabs",arguments:{action:"list"}}),(await N.callTool({name:"browser_tabs",arguments:{action:"select",index:oe}})).isError))throw new Hn(`could not start on the session's tab ${oe}`)}catch(G){throw await Promise.allSettled([N.close(),z?.close()]),F(!1),G}let L=z;return{context:P,client:N,close:async()=>{await Promise.allSettled([N.close()]),await Promise.allSettled([L.close()])},release:F}},p=0,m=P=>{p++;let E=!1,T=()=>{E||(E=!0,clearTimeout(I),P.off("close",M),--p===0&&d())},M=()=>{setTimeout(T,1e3).unref()},I=setTimeout(T,3e5);return I.unref(),P.on("close",M),T},h=new Map,w=new Set,b=!1,y=!1,S=P=>{let E=h.get(P);if(!E){if(b)return Promise.reject(new Hn("the agent session is over"));E=o?o.pageOf(P).then(T=>f(T.context(),T),T=>{throw new Hn(`browser session "${Ge(P)}" could not open: ${T instanceof Error?T.message:String(T)}`)}):f(e),h.set(P,E),E.then(T=>{y?T.close().finally(()=>T.release(!1)):w.add(T)},()=>{}),E.catch(()=>{h.get(P)===E&&h.delete(P)})}return E},x=()=>o?.keyOf()??"",C;try{C=await S(x())}catch(P){throw d(),P}let $=Promise.resolve(),k,R=(P,E)=>{let T=$.then(async()=>{let M=x(),I=await S(M);k=M;try{return await ja(I.context,t(),P,E)}finally{k=void 0}});return $=T.then(()=>{},()=>{}),T},v=Ei({listTools:(...P)=>C.client.listTools(...P),callTool:async(...P)=>(await S(k??x())).client.callTool(...P)},(P,E,T)=>R(ly(P,E),T),s.projectRoot),A=async()=>{let P=[...u];if(P.length===0)return;let E=Promise.all(P.map(M=>M.path().then(()=>!0,()=>!0))),T=!await Promise.race([E,as(oy).then(()=>!1)]);T&&Ia++;try{T&&(await Promise.allSettled(P.map(M=>M.cancel())),await Promise.allSettled(P.map(M=>M.failure()))),await as(0),await as(0)}finally{T&&Ia--}};return{config:{type:"sdk",name:"playwright",instance:v},close:async()=>{b=!0,await Promise.race([$,as(au)]),await A().catch(()=>{});let P=Promise.allSettled([...h.values()]);await Promise.race([P.then(iy),as(au).then(ay)]);let E=[...w];y=!0;for(let T of E)await T.close();await Promise.allSettled([v.close()]);for(let T of E)T.release(!0)},grouped:(P,E)=>R(P,E)}}var fy=dy(import.meta.url),pu="This scenario runs in several browser sessions, and the agent needs Playwright's in-process browser tools to act in each of them; they could not start";function uy(){let e=fy.resolve("@playwright/mcp/package.json");return uu.join(uu.dirname(e),"cli.js")}var py=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"]),gy=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 Na(e,t){if(gy.has(e))return!1;if(e==="mcp__playwright__browser_tabs"){let n=t?.action;return!(n==="list"||n==="select"||n==="close")}return!0}var br=class e{constructor(t,n){this.ctx=t;this.snapshotMode=n;this.state=new ho(t.scenario,{firstStep:Sa(t),discardBeforeAnnounce:jf(t)})}ctx;snapshotMode;state;usage={aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0};resultText="";traced;capped;outputDir=Ol();get projectRoot(){return this.ctx.projectRoot??process.cwd()}stopTabWatch;startedAt=new Date;static async open(t,n,r){let s=new e(t,n);try{return await e.attach(s,t,n,r)}catch(o){throw fu.rmSync(s.outputDir,{recursive:!0,force:!0}),o}}static async attach(t,n,r,s){let o=gn(n.scenario.steps)?n.sessionPage:void 0;if(o&&s.traceBridgeUnavailable)throw new Error(pu);if((n.traceContext||o)&&!s.traceBridgeUnavailable){let i=ot(n.scenario),a=n.traceContext??(await o(t.sessionKey())).context();try{let c=o&&{keyOf:()=>t.sessionKey(),pageOf:o};t.traced=await du(a,()=>t.currentStep(),r,l=>{let d=l instanceof Error?l.message:String(l);console.warn(`A promise rejected during the agent session and nothing handled it: ${it(d,i)}`)},{outputDir:t.outputDir,projectRoot:t.projectRoot},c)}catch(c){if(c instanceof Hn)throw c;let l=it(c instanceof Error?c.message:String(c),i);if(o)throw new Error(`${pu} (${l})`);s.traceBridgeUnavailable=!0,console.warn(`Agent tracing could not start (${l}). Continuing through the standard browser connection; agent calls will be absent from these traces.`)}}return t}sessionKey(){let t=this.state.currentStepIndex>=0?this.state.currentStepIndex:Sa(this.ctx);return de(this.ctx.scenario.steps[t]?.session)}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 jl(this.playwrightStdio(),this.projectRoot),this.capped.config)}playwrightStdio(){return{command:process.execPath,args:[uy(),"--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?ja(this.ctx.traceContext,this.currentStep(),n,t):t()}async beforeTool(t,n){if(this.state.beginToolCall(t),py.has(n)&&this.ctx.takeFingerprint&&!this.state.pendingFingerprint)try{let r=this.ctx.takeFingerprint;this.state.pendingFingerprint=await this.noteThePage(()=>r(this.sessionKey()))}catch{}}afterTool(t,n,r,s){let o=Vf(n,r);o&&this.state.addArmedAction(o);let i=qf(n,r,this.ctx.baseURL);if(i&&this.state.addActions([i]),n.startsWith("mcp__playwright__")){let a=Mf(s);a!==void 0&&this.ctx.onActiveTab?.(a,this.sessionKey()),this.state.addActions(Ff(s,this.ctx.baseURL)),this.state.pendingFingerprint=void 0}this.state.endToolCall(t,Na(n,r))}failedTool(t,n,r){n.startsWith("mcp__playwright__")&&(this.state.pendingFingerprint=void 0),this.state.endToolCall(t,Na(n,r))}watchTabs(){this.stopTabWatch=this.ctx.onTabOpened?.(t=>this.state.markTabOpened(t))}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(),fu.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=>{let s=gr(r.text,t.scenario.params),o=t.scenario.steps[r.index];return{index:r.index,text:o?Cc(o.text,s):s}}),recordedSteps:zf(n.steps,t.scenario,t.uniqueSeed,this.startedAt),announcedSteps:[...n.announced].sort((r,s)=>r-s),usage:this.usage}}};var Eo=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 ou();return{subscriptionType:t.subscriptionType,fiveHourBefore:t.utilization,fiveHourAfter:n?.utilization,resetsAt:n?.resetsAt??t.resetsAt}}async run(t){let n=await br.open(t,this.opts.snapshotMode??"none",this),r;try{r=hy({prompt:Ro(t),options:{systemPrompt:ko({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:So(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=Oa(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 my from"node:http";import{randomBytes as wy,randomUUID as yy,timingSafeEqual as by}from"node:crypto";import{Client as vy}from"@modelcontextprotocol/sdk/client/index.js";import{InMemoryTransport as xy}from"@modelcontextprotocol/sdk/inMemory.js";import{Server as Sy}from"@modelcontextprotocol/sdk/server/index.js";import{StreamableHTTPServerTransport as $y}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as ky,ListToolsRequestSchema as Ry}from"@modelcontextprotocol/sdk/types.js";async function Ty(e,t){let n=wy(16).toString("hex"),r=Buffer.from(`Bearer ${n}`),s=u=>{let g=Buffer.from(u??"");return g.length===r.length&&by(g,r)},o=Promise.resolve(),i=!1,a=u=>{let g=o.then(u);return o=g.catch(()=>{}),g},c=(u,g)=>{let f=new Sy({name:u,version:"1"},{capabilities:{tools:{}}});return f.setRequestHandler(Ry,p=>g.listTools(p.params)),f.setRequestHandler(ky,(p,m)=>a(async()=>{if(i||m.signal.aborted)throw new Error(i?"the agent session is over":"the call was cancelled before its turn came");let h=yy(),w=`mcp__${u}__${p.params.name}`,b=p.params.arguments??{};await t.beforeTool(h,w);try{let y=await g.callTool(p.params,void 0,{timeout:Ri});return y.isError?t.failedTool(h,w,b):t.afterTool(h,w,b,y),y}catch(y){throw t.failedTool(h,w,b),y}})),f},l=my.createServer(async(u,g)=>{let f=(u.url??"").split("?")[0].slice(1),p=s(u.headers.authorization)?e[f]:void 0;if(!p)return void g.writeHead(404).end();if(u.method!=="POST")return void g.writeHead(405,{Allow:"POST"}).end();let m=c(f,p),h=new $y({sessionIdGenerator:void 0,enableJsonResponse:!0});g.on("close",()=>{Promise.allSettled([h.close(),m.close()])});try{await m.connect(h),await h.handleRequest(u,g)}catch{g.headersSent||g.writeHead(500).end()}});l.requestTimeout=0,await new Promise((u,g)=>{l.once("error",g),l.listen(0,"127.0.0.1",()=>u())});let{port:d}=l.address();return{urls:Object.fromEntries(Object.keys(e).map(u=>[u,`http://127.0.0.1:${d}/${u}`])),token:n,close:async()=>{i=!0,l.closeAllConnections(),await new Promise(u=>l.close(()=>u()))}}}async function gu(e){let[t,n]=xy.createLinkedPair();await e.connect(n);let r=new vy({name:"saffron-gateway",version:"1"});return await r.connect(t),r}async function hu(e){let t=[];try{let n=await gu((await e.playwrightServer()).instance);t.push(n);let r=await gu(So(e.state).instance);t.push(r);let s=await Ty({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 Ao=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 br.open(t,this.opts.snapshotMode??"none",this),s;try{s=await hu(r)}catch(o){throw await r.close(),o}r.watchTabs();try{await this.drive({systemPrompt:ko({deliberateSnapshots:r.snapshotMode==="none",adaptableMidAssertions:t.assertionPolicy==="adaptable-mid"}),prompt:Ro(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 ls(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 vr(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 xr from"node:fs";import Ma from"node:os";import Ht from"node:path";import{createHash as Ey}from"node:crypto";import{createRequire as mu}from"node:module";function Ay(){try{let e=mu(import.meta.resolve("@openai/codex-sdk")).resolve("@openai/codex/package.json"),t=mu(e).resolve(`@openai/codex-${process.platform}-${process.arch}/package.json`),n=Ht.join(Ht.dirname(t),"vendor");for(let r of xr.readdirSync(n))for(let s of[Ht.join(n,r,"bin","codex"),Ht.join(n,r,"codex","codex")])if(xr.existsSync(s))return s}catch{}}function Co(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 Cy(e){return`'${e.replaceAll("'","'\\''")}'`}function _y(){let e=Co();if(e)throw new Error(e);let t=Ay();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=Ht.join(process.env.XDG_CACHE_HOME||Ht.join(Ma.homedir(),".cache"),"saffron");xr.mkdirSync(n,{recursive:!0});let r=Ht.join(n,`codex-${Ey("sha256").update(t).digest("hex").slice(0,12)}`);return Ne(r,`#!/bin/sh
|
|
343
371
|
sub="$1"; shift
|
|
344
|
-
exec ${
|
|
345
|
-
`,493),r}var
|
|
346
|
-
`,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
|
|
347
|
-
`).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=
|
|
372
|
+
exec ${Cy(t)} "$sub" --ignore-user-config --ephemeral "$@"
|
|
373
|
+
`,493),r}var wu="SAFFRON_MCP_TOKEN",Py=["cli_auth_credentials_store","forced_login_method","forced_chatgpt_workspace_id"];function Oy(e){let t=e.split(/^\s*\[/m)[0],n={};for(let r of Py){let s=new RegExp(`^\\s*${r}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`,"m").exec(t);s&&(n[r]=s[1]??s[2])}return n}function Fa(){try{return Oy(xr.readFileSync(Ht.join(process.env.CODEX_HOME??Ht.join(Ma.homedir(),".codex"),"config.toml"),"utf8"))}catch{return{}}}var yu=async e=>{let{Codex:t}=await ls("@openai/codex-sdk","codex"),n=xr.mkdtempSync(Ht.join(Ma.tmpdir(),"saffron-codex-"));try{let r=Object.fromEntries(Object.entries(process.env).filter(l=>l[1]!==void 0)),o=new t({codexPathOverride:_y(),env:{...r,[wu]:e.mcpToken},config:{...Fa(),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:wu,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=vr(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 u=d.usage;e.usage.inputTokens=u.input_tokens-u.cached_input_tokens,e.usage.cacheReadTokens=u.cached_input_tokens,e.usage.cacheCreationTokens=u.cache_write_input_tokens??0,e.usage.outputTokens=u.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{xr.rmSync(n,{recursive:!0,force:!0})}};import{spawn as Iy,spawnSync as jy}from"node:child_process";import Se from"node:fs";import Po from"node:os";import Ce from"node:path";import Ny from"node:readline";var _o="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 Oo(){for(let e of[...(process.env.PATH??"").split(Ce.delimiter),Ce.join(Po.homedir(),".local","bin")]){let t=Ce.join(e,process.platform==="win32"?"agy.exe":"agy");if(e&&Se.existsSync(t))return t}}var Sr={playwright:"saffron_browser",saffron:"saffron_tools"},bu=Object.values(Sr).map(e=>`mcp(${e}/*)`),Ba=()=>Ce.join(Po.homedir(),".gemini","antigravity-cli","settings.json");function vu(e){if(!Se.existsSync(e))return{};try{let t=JSON.parse(Se.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 Io(e=Ba()){let t;try{t=vu(e).permissions?.allow}catch{return bu}return bu.filter(n=>!(Array.isArray(t)&&t.includes(n)))}function My(e=Ba()){let t=vu(e),n=Io(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=Se.lstatSync(e,{throwIfNoEntry:!1})?.isSymbolicLink()??!1,a=Fy(e),c=Se.existsSync(a)?Se.statSync(a).mode&4095:void 0;try{Ne(a,JSON.stringify(o,null,2)+`
|
|
374
|
+
`,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 Fy(e){let t=e;for(let n=0;n<40&&Se.lstatSync(t,{throwIfNoEntry:!1})?.isSymbolicLink();n++)t=Ce.resolve(Se.realpathSync(Ce.dirname(t)),Se.readlinkSync(t));return Se.existsSync(t)?Se.realpathSync(t):t}async function xu(){let e=Oo();if(!e)throw new Error(`the antigravity provider needs the agy command: ${_o}`);let t=jy(e,["models"],{encoding:"utf8",timeout:6e4});if(t.status!==0){let r=`${t.stderr??""}${t.stdout??""}`.trim().split(`
|
|
375
|
+
`).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=My();console.log(n.length>0?`Antigravity: allowed Saffron's tools in ${Ba()}: ${n.join(", ")}. Remove those lines to take it back.`:"Antigravity: Saffron's tools are already allowed.")}var Su=Ce.join(Po.homedir(),".gemini","antigravity-cli","mcp"),By=Object.values(Sr).map(e=>Ce.join(Su,e)),Ly=`const path=require("path");const DIRS=${JSON.stringify(By)};const SERVERS=${JSON.stringify(Object.values(Sr))};
|
|
348
376
|
let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{let t={};try{t=JSON.parse(s).toolCall||{}}catch{}const a=t.args||{};
|
|
349
377
|
const file=typeof a.AbsolutePath==="string"?path.resolve(a.AbsolutePath):"";
|
|
350
378
|
const dir=typeof a.DirectoryPath==="string"?path.resolve(a.DirectoryPath):"";
|
|
351
379
|
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));
|
|
352
|
-
process.stdout.write(JSON.stringify(ok?{decision:"allow"}:{decision:"deny",reason:"Only Saffron's browser and saffron tools are available in a Saffron session."}))})`,
|
|
380
|
+
process.stdout.write(JSON.stringify(ok?{decision:"allow"}:{decision:"deny",reason:"Only Saffron's browser and saffron tools are available in a Saffron session."}))})`,Dy=(e,t)=>`let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{let i=0;try{i=JSON.parse(s).invocationNum}catch{}
|
|
353
381
|
const stop=i+1>=${e};if(stop)require("fs").writeFileSync(${JSON.stringify(t)},"");
|
|
354
|
-
process.stdout.write(JSON.stringify(stop?{terminationBehavior:"terminate"}:{}))})
|
|
382
|
+
process.stdout.write(JSON.stringify(stop?{terminationBehavior:"terminate"}:{}))})`,$u=async e=>{let t=Oo();if(!t)throw new Error(`the antigravity provider needs the agy command: ${_o}`);if(Object.keys(e.mcpServers).length>0&&Io().length>0)throw new Error("agy does not allow Saffron's tools yet: run npx saffron login antigravity once");let n=Se.mkdtempSync(Ce.join(Po.tmpdir(),"saffron-agy-"));try{let r=Ce.join(n,".agents");Se.mkdirSync(Ce.join(r,"agents"),{recursive:!0}),Se.writeFileSync(Ce.join(r,"agents","saffron.md"),`---
|
|
355
383
|
name: saffron
|
|
356
384
|
description: Saffron's browser test agent.
|
|
357
385
|
mainAgent: true
|
|
@@ -361,15 +389,15 @@ commandExecutionPolicy: off
|
|
|
361
389
|
|
|
362
390
|
${e.systemPrompt}
|
|
363
391
|
|
|
364
|
-
Your tools are MCP tools, called with call_mcp_tool: the browser_* tools are on the ${
|
|
365
|
-
`),
|
|
366
|
-
`).at(-1)||`agy exited with ${
|
|
392
|
+
Your tools are MCP tools, called with call_mcp_tool: the browser_* tools are on the ${Sr.playwright} server and the saffron_* tools on the ${Sr.saffron} server. Before a tool's first call, read its parameters with view_file from ${Ce.join(Su,"<server>","<tool>.json")}. No other tool is available.
|
|
393
|
+
`),Se.writeFileSync(Ce.join(r,"mcp_config.json"),JSON.stringify({mcpServers:Object.fromEntries(Object.entries(e.mcpServers).map(([h,w])=>[Sr[h]??h,{serverUrl:w,headers:{Authorization:`Bearer ${e.mcpToken}`}}]))}));let s=(h,w)=>{let b=Ce.join(n,h);return Se.writeFileSync(b,w),`${JSON.stringify(process.execPath)} ${JSON.stringify(b)}`};Se.writeFileSync(Ce.join(r,"hooks.json"),JSON.stringify({"saffron-gate":{PreToolUse:[{matcher:"",hooks:[{type:"command",command:s("gate.cjs",Ly)}]}]},"saffron-turns":{PostInvocation:[{type:"command",command:s("turns.cjs",Dy(e.maxTurns,Ce.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=Iy(t,i,{cwd:n,stdio:["pipe","pipe","pipe"]});a.stdin.on("error",()=>{}),a.stdin.end(e.prompt);let c="";a.stderr.on("data",h=>{c=(c+h).slice(-4e3)});let l=new Promise((h,w)=>a.once("error",b=>w(new Error(`Antigravity: could not start ${t}: ${b.message}. ${_o}`)))),d=new Promise(h=>a.once("close",h)),u="",g,f,p=(async()=>{for await(let h of Ny.createInterface({input:a.stdout})){let w;try{w=JSON.parse(h)}catch{continue}let b=w.step_update;b?(b.state==="DONE"&&b.usage&&e.usage.aiCalls++,b.step_type==="agent_response"&&typeof b.text_delta=="string"&&(b.step_index!==g&&([u,g]=["",b.step_index]),u+=b.text_delta,e.lastOutput(u))):w.event==="result"&&(f=w.result)}})();await Promise.race([p,l]);let m=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()&&Se.existsSync(Ce.join(n,"turn-limit")))throw new Error(`Antigravity: ${vr(e.maxTurns)}`);if((f?.status!=="SUCCESS"||m!==0)&&!e.finished()){let h=typeof f?.error=="string"?f.error:c.trim().split(`
|
|
394
|
+
`).at(-1)||`agy exited with ${m}`;throw new Error(`Antigravity: ${h}${/auth/i.test(h)?`. ${_o}`:""}`)}}finally{Se.rmSync(n,{recursive:!0,force:!0})}};import ku from"node:fs";import Uy from"node:os";import zy from"node:path";var Tu="@cursor/sdk";function ds(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 Eu=async e=>{let t=ds();if(t)throw new Error(t);let{Agent:n,JsonlLocalAgentStore:r}=await ls(Tu,"cursor"),s=ku.mkdtempSync(zy.join(Uy.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 Ru(await o(e.systemPrompt),e.prompt,e);if(i.status==="error"&&/system.?prompt/i.test(i.error?.message??"")&&(i=await Ru(await o(void 0),`${e.systemPrompt}
|
|
367
395
|
|
|
368
396
|
---
|
|
369
397
|
|
|
370
|
-
${e.prompt}`,e)),i.status==="error"&&!e.finished())throw new Error(`Cursor: ${i.error?.message??"the run failed"}${
|
|
371
|
-
`)),{calls:r,order:s,events:o}=
|
|
372
|
-
`)){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:
|
|
398
|
+
${e.prompt}`,e)),i.status==="error"&&!e.finished())throw new Error(`Cursor: ${i.error?.message??"the run failed"}${Hy(i.error?.message)}`)}finally{ku.rmSync(s,{recursive:!0,force:!0})}};async function Ru(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: ${vr(n.maxTurns)}`);return a}finally{e.close()}}function Hy(e=""){return/api key|unauthenticated|unauthori[sz]ed|logged.?out/i.test(e)?". Sign in once with: npx saffron login cursor":""}async function Au(){let e=ds();if(e)throw new Error(e);let{Cursor:t}=await ls(Tu,"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 La=["claude","codex","antigravity","cursor"];function Pu(e){return La.includes(e)}var Da={codex:yu,antigravity:$u,cursor:Eu};function Ou(e,t){return e==="claude"?new Eo(t):new Ao(Da[e],t,()=>{let n=Iu(e);return n.length>0?`${qn[e]} cannot start here: ${n.join("; ")}`:void 0})}var No=(...e)=>_u.join(qy.homedir(),...e);function Cu(e){try{return import.meta.resolve(e),!0}catch{return!1}}function Iu(e){switch(e){case"claude":return[];case"codex":{let t=Co();return t?[t]:Cu("@openai/codex-sdk")?[]:["npm install --save-dev @openai/codex-sdk"]}case"antigravity":return Oo()?Io().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=ds();return t?[t]:Cu("@cursor/sdk")?[]:["npm install --save-dev @cursor/sdk"]}}}function Ua(e){let t=process.env,n=Iu(e);if(e==="claude")t.ANTHROPIC_API_KEY||t.CLAUDE_CODE_OAUTH_TOKEN||t.CLAUDE_CODE_USE_BEDROCK||t.CLAUDE_CODE_USE_VERTEX||jo.existsSync(No(".claude",".credentials.json"))||jo.existsSync(No(".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"&&!Co()){let r=_u.join(t.CODEX_HOME??No(".codex"),"auth.json");!["keyring","auto"].includes(Fa().cli_auth_credentials_store??"")&&!jo.existsSync(r)&&n.push("a Codex login with your ChatGPT plan: npx @openai/codex login")}else e==="cursor"&&!ds()&&!t.CURSOR_API_KEY&&!jo.existsSync(No(".cursor","sdk","auth.json"))&&n.push("a Cursor sign-in for Saffron (once per machine): npx saffron login cursor");return n}var qn={claude:"Claude",codex:"Codex",antigravity:"Antigravity",cursor:"Cursor"};var kn=(e,t=0)=>typeof e=="number"?e:t,le=e=>typeof e=="string"?e:void 0;function Vy(e,t){if(!t)return;let n=le(t.selector);if(n)return Jy(n);let r=le(t.url);if(r)return r;if(e==="press"||e==="keyboardPress")return le(t.key)}function Jy(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 Wy(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=le(o.callId);switch(o.type){case"before":{if(!i)break;let a=le(o.method)??"",c=o.class==="Tracing"&&a==="tracingGroup",l=a==="__waitInfo__";t.set(i,{callId:i,method:l?le(o.title)??"wait":a,subject:Vy(a,o.params),selector:le(o.params?.selector),startTime:kn(o.startTime),log:[],pageId:le(o.pageId),before:za(o,"beforeSnapshot"),calls:[],parentId:le(o.parentId),isGroup:c,title:le(o.title),isWait:l}),n.push(i);break}case"input":{let a=i?t.get(i):void 0;if(a){a.input=za({...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 u=c.inputPoint;c.input=u?{...d,point:u}:d}}break}case"log":{let a=i?t.get(i):void 0,c=le(o.message);a&&c&&a.log.push(c);break}case"after":{let a=i?t.get(i):void 0;if(!a)break;a.endTime=kn(o.endTime,a.startTime);let c=o.error;c?.message&&(a.error=c.message);let l=za({...o,pageId:a.pageId},"afterSnapshot");l&&(a.after=l);break}default:break}}return{calls:t,order:n,events:r}}function za(e,t){let n=le(e[t]),r=le(e.pageId);return n&&r?{pageId:r,name:n}:void 0}function ju(e){return Ha(Ll(e))}function Ha(e){let n=e.filter(y=>y.name.endsWith(".trace")).flatMap(y=>y.data.toString("utf8").split(`
|
|
399
|
+
`)),{calls:r,order:s,events:o}=Wy(n),i=new Map;for(let y of o){let S=y.snapshot;if(y.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 y of r.values())for(let S of[y.before,y.input,y.after])S&&(S.url=i.get(`${S.pageId}/${S.name}`));let a=[];for(let y of s){let S=r.get(y),x=S.parentId?r.get(S.parentId):void 0;x?x.calls.push(S):a.push(y)}let c=y=>{let{parentId:S,isGroup:x,title:C,isWait:$,...k}=y;return{...k,calls:k.calls.map(R=>c(R))}},l=y=>y.find(S=>S.error&&!S.isWait)?.error,d=[],u=[];for(let y of a){let S=r.get(y);if(!S.isGroup){u.push(c(S));continue}let x={title:S.title??"",startTime:S.startTime,endTime:S.endTime,error:S.error,actions:[],calls:[]},C=/^\[saffron:(agent|replay|pending):(-?\d+)\] (.*)$/.exec(x.title);C&&(x.phase=C[1],x.stepIndex=Number(C[2]),x.title=C[3]);let $=[];for(let k of S.calls)if(k.isGroup){let R={title:k.title??"",startTime:k.startTime,endTime:k.endTime,error:k.error??l(k.calls),calls:k.calls.map(v=>c(v))},_=/^\[saffron:action:(\d+)\] ([\s\S]*)$/.exec(R.title);_&&(R.actionIndex=Number(_[1]),R.title=_[2]),x.actions.push(R)}else $.push(k),x.calls.push(c(k));x.error||(x.error=x.actions.find(k=>k.error)?.error??l($)),d.push(x)}let g=[],f=new Map,p,m,h,w=Number.POSITIVE_INFINITY,b=0;for(let y of o)if(y.type==="context-options")p=le(y.title),m=le(y.browserName),h=Number(y.version)||void 0,w=Math.min(w,kn(y.monotonicTime,w));else if(y.type==="screencast-frame"){let S=le(y.file)??(le(y.sha1)?`resources/${le(y.sha1)}`:""),x={pageId:le(y.pageId)??"",file:S,sha1:S.slice(S.lastIndexOf("/")+1),timestamp:kn(y.timestamp),width:kn(y.width),height:kn(y.height)};g.push(x),f.has(x.pageId)||f.set(x.pageId,{pageId:x.pageId})}else if(y.type==="event"&&y.class==="BrowserContext"&&y.method==="page"){let S=le(y.params?.pageId);S&&f.set(S,{...f.get(S),pageId:S,openedAt:kn(y.time)})}else if(y.type==="event"&&y.class==="BrowserContext"&&y.method==="pageClosed"){let S=le(y.params?.pageId);S&&f.set(S,{...f.get(S),pageId:S,closedAt:kn(y.time)})}else if(y.type==="frame-snapshot"){let S=y.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 y of r.values())w=Math.min(w,y.startTime),b=Math.max(b,y.endTime??y.startTime);for(let y of g)b=Math.max(b,y.timestamp);return Number.isFinite(w)||(w=0),{format:h,title:p,browserName:m,startTime:w,endTime:b,steps:d,calls:u,frames:g,requests:Gy(e),pages:[...f.values()],resources:e.filter(y=>y.name.startsWith("resources/")).map(y=>y.name.slice(10))}}function Gy(e){let t=[];for(let n of e.filter(r=>r.name.endsWith(".network")))for(let r of n.data.toString("utf8").split(`
|
|
400
|
+
`)){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:le(o.pageref),method:le(i?.method)??"GET",url:le(i?.url)??"",status:Number.isFinite(a?.status)?a?.status:void 0,mimeType:le(a?.content?.mimeType),startedAt:Date.parse(le(o.startedDateTime)??"")||0,time:typeof o.time=="number"?o.time:void 0,timestamp:typeof c=="number"?c:void 0})}return t}import $r from"node:fs";import{createHash as Ky,randomBytes as qu}from"node:crypto";import Nu from"node:fs";import cn from"node:path";var Mu="This run has no reviewable proposal identity. Run the scenario again to review from replay.",qa="The proposal does not belong to this replay.",Fu=e=>e instanceof Error?e.message:String(e),Bu=(e,t)=>`No pending proposal at ${cn.relative(e,t)}: it has been accepted, rejected or removed since this run.`;function Lu(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=cn.win32.isAbsolute(s)?a=>o(a)===o(s):a=>cn.resolve(a)===cn.resolve(e,s);return r.map(a=>ct(e,t.feature,a)).find(i)}function Du(e,t,n){if(mt(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=or(n)}catch(a){if(a instanceof ge)return r(`The proposal cannot be read: ${cn.relative(e,n)}: ${a.problem}`);throw a}let{feature:o,scenario:i}=s.cache;if(cn.resolve(ct(e,o,i))!==cn.resolve(n)||o!==t.feature||!(t.scenario===i||t.scenario===s.meta.recordedFor||t.scenario.startsWith(i+" (example ")))return{available:!1,reason:qa};try{if(!Nu.existsSync(cn.resolve(e,o)))return r(`STALE: ${o} no longer exists`);let a=Ye(e,ye(e),[cn.resolve(e,o)]),c=dt(e,s,a);if(c)return r(`STALE: ${c}`);let l=t.status==="red",d=s.meta.verified===!0&&!l,u=l?t.error??"This run replayed the proposal and it failed.":s.meta.proofError;return{available:!0,verified:d,...!d&&u?{proofError:u}:{},unbound:!s.meta.bound,diff:bn(He(fe(e,o,i)),s.cache),featureEdits:s.meta.featureEdits??[]}}catch(a){return r(Fu(a))}}function Uu(e,t){if(!t.proposalFile||!t.proposalRevision)return{available:!1,reason:Mu};try{let n=Lu(e,{...t,proposalFile:t.proposalFile});return n?Nu.existsSync(n)?Du(e,t,n):{available:!1,reason:Bu(e,n)}:{available:!1,reason:qa}}catch(n){return{available:!1,reason:Fu(n)}}}function zu(e,t,n,r=!1){if(!t.proposalFile||!t.proposalRevision)throw new Error(Mu);let s=Lu(e,{...t,proposalFile:t.proposalFile});if(!s)throw new Error(qa);Bs(s,()=>{let o=Du(e,t,s);if(n==="reject"){if(!o.available&&!o.rejectable)throw new Error(o.reason);Us(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.");Ds(e,s)}},()=>{throw new Error(Bu(e,s))})}import Yy from"node:http";import Jn from"node:path";function Hu(){return`<!DOCTYPE html>
|
|
373
401
|
<html lang="en">
|
|
374
402
|
<head>
|
|
375
403
|
<meta charset="utf-8">
|
|
@@ -406,7 +434,7 @@ ${e.prompt}`,e)),i.status==="error"&&!e.finished())throw new Error(`Cursor: ${i.
|
|
|
406
434
|
.step.selected { border-left-color: var(--brand); background: rgba(244,163,0,.05); }
|
|
407
435
|
.step .kw { font-family: var(--mono); font-size: 11px; color: var(--muted); margin-right: 6px; }
|
|
408
436
|
.step .text { color: var(--text); }
|
|
409
|
-
.step.passed .mark { color: var(--green); } .step.healed .mark { color: var(--gold); } .step.failed .mark { color: var(--red); } .step.skipped .mark, .step.skipped .text { color: var(--faint); }
|
|
437
|
+
.step.passed .mark { color: var(--green); } .step.healed .mark { color: var(--gold); } .step.failed .mark { color: var(--red); } .step.skipped .mark, .step.skipped .text { color: var(--faint); } .step.elsewhere .mark, .step.elsewhere .text { color: var(--faint); }
|
|
410
438
|
.step .mark { display: inline-block; width: 14px; font-family: var(--mono); }
|
|
411
439
|
.step .meta { font-family: var(--mono); font-size: 10.5px; color: var(--muted); margin-left: 20px; margin-top: 2px; }
|
|
412
440
|
.actions { margin: 4px 0 0 20px; display: none; }
|
|
@@ -456,7 +484,7 @@ ${e.prompt}`,e)),i.status==="error"&&!e.finished())throw new Error(`Cursor: ${i.
|
|
|
456
484
|
</head>
|
|
457
485
|
<body>
|
|
458
486
|
<header>
|
|
459
|
-
${
|
|
487
|
+
${Bn(26)}
|
|
460
488
|
<div><div class="name" id="title">Saffron replay</div><div class="sub" id="subtitle"></div></div>
|
|
461
489
|
<span class="status" id="status"></span>
|
|
462
490
|
<label id="scenarioPicker" hidden>Scenario <select id="scenarioSelect" aria-label="Scenario"></select></label>
|
|
@@ -609,6 +637,10 @@ ${e.prompt}`,e)),i.status==="error"&&!e.finished())throw new Error(`Cursor: ${i.
|
|
|
609
637
|
&& (source === "agent-heal" ? (replayMissed && agentActed) || change === "changed" : source === undefined && change === "changed");
|
|
610
638
|
const proposed = proposalRun && change !== undefined && change !== "same";
|
|
611
639
|
const recorded = status === "passed" && !proposalRun && source === "agent-record" && agentActed;
|
|
640
|
+
// In a scenario with several browser sessions, a step of another session
|
|
641
|
+
// ran in that session's own trace, not in this one.
|
|
642
|
+
const elsewhere = scenario.traceSession !== undefined && scenario.stepSessions?.[i] !== undefined && scenario.stepSessions[i] !== scenario.traceSession
|
|
643
|
+
? scenario.stepSessions[i] : undefined;
|
|
612
644
|
const title = ts?.title ?? ((rs?.gherkin ? (rs.kind === "assertion" ? "Then " : "When ") + rs.gherkin : "step " + (i + 1)));
|
|
613
645
|
// Saffron assertions can fail without any Playwright call throwing.
|
|
614
646
|
// Conversely a failed call can be absorbed by a successful fallback.
|
|
@@ -623,6 +655,7 @@ ${e.prompt}`,e)),i.status==="error"&&!e.finished())throw new Error(`Cursor: ${i.
|
|
|
623
655
|
healed,
|
|
624
656
|
proposed,
|
|
625
657
|
recorded,
|
|
658
|
+
elsewhere,
|
|
626
659
|
error: rs ? rs.error : ts?.error,
|
|
627
660
|
retries: rs?.retries,
|
|
628
661
|
tabs: rs?.tabs,
|
|
@@ -684,12 +717,12 @@ ${e.prompt}`,e)),i.status==="error"&&!e.finished())throw new Error(`Cursor: ${i.
|
|
|
684
717
|
.sort((a, b) => (a.t ?? 0) - (b.t ?? 0));
|
|
685
718
|
const tabWords = (t) => (t.how === "opened" ? "opened tab " : t.how === "closed" ? "closed a tab, on tab " : "switched to tab ") + Number(t.tab);
|
|
686
719
|
const urlPath = (url) => String(url ?? "").replace(/^https?:\\/\\/[^/]+/, "");
|
|
687
|
-
const mark = (step) => (step.healed ? "\u2726" : step.status === "passed" ? "\u2713" : step.status === "failed" ? "\u2717" : "\xB7");
|
|
720
|
+
const mark = (step) => (step.elsewhere ? "\xB7" : step.healed ? "\u2726" : step.status === "passed" ? "\u2713" : step.status === "failed" ? "\u2717" : "\xB7");
|
|
688
721
|
|
|
689
722
|
$("steps").innerHTML = steps.map((s) => \`
|
|
690
|
-
<div class="step \${esc(s.status)}\${s.healed ? " healed" : ""}" data-step="\${s.index}">
|
|
723
|
+
<div class="step \${esc(s.status)}\${s.healed ? " healed" : ""}\${s.elsewhere ? " elsewhere" : ""}" data-step="\${s.index}">
|
|
691
724
|
<span class="mark" title="\${s.healed ? "healed by the agent" : ""}">\${mark(s)}</span><span class="kw">\${esc(keywordOf(s.title))}</span><span class="text">\${esc(textOf(s.title))}</span>
|
|
692
|
-
\${s.healed ? \`<div class="meta">healed by the agent</div>\` : s.proposed ? \`<div class="meta">ran the proposed recording</div>\` : s.recorded ? \`<div class="meta">recorded by the agent</div>\` : ""}\${s.retries ? \`<div class="meta">retried \xD7\${Number(s.retries)}</div>\` : ""}\${(s.tabs ?? []).map((t) => \`<div class="meta">\${esc(tabWords(t))}</div>\`).join("")}\${s.startTime !== undefined ? \`<div class="meta">\${ms(s.startTime)} \u2192 \${ms(s.endTime)}</div>\` : ""}
|
|
725
|
+
\${s.elsewhere ? \`<div class="meta">in session "\${esc(s.elsewhere)}": its own trace</div>\` : s.healed ? \`<div class="meta">healed by the agent</div>\` : s.proposed ? \`<div class="meta">ran the proposed recording</div>\` : s.recorded ? \`<div class="meta">recorded by the agent</div>\` : ""}\${s.retries ? \`<div class="meta">retried \xD7\${Number(s.retries)}</div>\` : ""}\${(s.tabs ?? []).map((t) => \`<div class="meta">\${esc(tabWords(t))}</div>\`).join("")}\${s.startTime !== undefined ? \`<div class="meta">\${ms(s.startTime)} \u2192 \${ms(s.endTime)}</div>\` : ""}
|
|
693
726
|
<div class="actions">\${inOrder(s).map((x) => x.action ? \`<div class="action \${x.action.error ? "failed" : ""}" data-step="\${s.index}" data-action="\${x.j}"><span>\${esc(x.action.title)}</span><span class="t">\${ms(x.action.startTime)}</span></div>\`
|
|
694
727
|
: \`<div class="action \${x.call.error ? "failed" : ""}" data-step="\${s.index}" data-call="\${x.j}"><span>\${esc(callLabel(x.call))}\${callSubject(x.call) ? " " + esc(callSubject(x.call)) : ""}</span><span class="t">\${ms(x.call.startTime)}</span></div>\`).join("")}</div>
|
|
695
728
|
</div>\`).join("");
|
|
@@ -757,7 +790,7 @@ ${e.prompt}`,e)),i.status==="error"&&!e.finished())throw new Error(`Cursor: ${i.
|
|
|
757
790
|
const nextSectionAfter = (s, t) => Math.min(...steps.filter((x) => x !== s && x.startTime !== undefined && x.startTime > t).map((x) => x.startTime));
|
|
758
791
|
const snapshotFor = () => {
|
|
759
792
|
// A step that never ran has no page to borrow: any would be an earlier step's.
|
|
760
|
-
if (steps[sel.step]?.status === "skipped") return {};
|
|
793
|
+
if (steps[sel.step]?.status === "skipped" || steps[sel.step]?.elsewhere) return {};
|
|
761
794
|
const own = ownSnapshot();
|
|
762
795
|
if (own) return { snap: own };
|
|
763
796
|
const step = steps[sel.step];
|
|
@@ -847,6 +880,7 @@ ${e.prompt}`,e)),i.status==="error"&&!e.finished())throw new Error(`Cursor: ${i.
|
|
|
847
880
|
$("snap").removeAttribute("src");
|
|
848
881
|
$("empty").style.display = "grid";
|
|
849
882
|
$("empty").textContent = !step ? "Select a step."
|
|
883
|
+
: step.elsewhere ? 'This step ran in session "' + step.elsewhere + '": pick its trace above to see it.'
|
|
850
884
|
: step.status === "skipped" ? "This step was never reached."
|
|
851
885
|
: unknownTab ? "No snapshot for this selection: it took none of its own, and with several tabs open the trace does not say which tab it ran in."
|
|
852
886
|
: "No snapshot for this selection.";
|
|
@@ -892,7 +926,9 @@ ${e.prompt}`,e)),i.status==="error"&&!e.finished())throw new Error(`Cursor: ${i.
|
|
|
892
926
|
\`<div class="log">\${c.log.map((l) => esc(l)).join("\\n")}\${r.count > 1 ? \`\\n\u2026 polled \${r.count} times\` : ""}\${r.error ? \`\\n<span class="err">\${esc(r.error)}</span>\` : ""}</div></div>\`);
|
|
893
927
|
}
|
|
894
928
|
if (bookkeeping) parts.push(\`<div class="panel"><div class="panel-hint">and \${bookkeeping} bookkeeping call\${bookkeeping === 1 ? "" : "s"} the agent's browser tools make after each action (console, page errors, requests)</div></div>\`);
|
|
895
|
-
if (calls.length === 0) parts.push(
|
|
929
|
+
if (calls.length === 0) parts.push(step.elsewhere
|
|
930
|
+
? \`<div class="panel"><div class="panel-title">another session</div><div>This step ran in session "\${esc(step.elsewhere)}", whose trace is its own: pick it above.</div></div>\`
|
|
931
|
+
: \`<div class="panel"><div class="panel-title">no calls</div><div>Nothing was executed for this step in this run.</div></div>\`);
|
|
896
932
|
$("details").innerHTML = parts.join("");
|
|
897
933
|
}
|
|
898
934
|
|
|
@@ -1072,7 +1108,7 @@ ${e.prompt}`,e)),i.status==="error"&&!e.finished())throw new Error(`Cursor: ${i.
|
|
|
1072
1108
|
renderSaffron();
|
|
1073
1109
|
// Open on the failure when there is one, else on what the agent healed
|
|
1074
1110
|
// (in a proof replay, what the proposal changed), else on the first step.
|
|
1075
|
-
const failed = steps.findIndex((s) => s.status === "failed");
|
|
1111
|
+
const failed = steps.findIndex((s) => s.status === "failed" && !s.elsewhere);
|
|
1076
1112
|
const healedAt = steps.findIndex((s) => s.healed || s.proposed);
|
|
1077
1113
|
const start = failed >= 0 ? failed : healedAt >= 0 ? healedAt : 0;
|
|
1078
1114
|
// The last failed action: after retries, the attempt that actually failed the step.
|
|
@@ -1083,9 +1119,9 @@ ${e.prompt}`,e)),i.status==="error"&&!e.finished())throw new Error(`Cursor: ${i.
|
|
|
1083
1119
|
})();
|
|
1084
1120
|
</script>
|
|
1085
1121
|
</body>
|
|
1086
|
-
</html>`}var un=class extends Error{},df="This trace is gone, or a later run replaced it (one that stopped before writing its report). Run the scenario again to replay it.",sw=4;function qi(e,t){let n=gn.join(e,t.file);try{Jn.accessSync(n,Jn.constants.R_OK)}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return;throw s}if(!Dt(gn.join(e,".saffron","artifacts"),n))throw new Error(`${t.file} is not a file under .saffron/artifacts`);let r=Jn.readFileSync(n);return t.sha256&&rt(r)!==t.sha256?void 0:r}function ow(){let e=As.resolve("playwright-core/package.json");return gn.join(gn.dirname(e),"lib","vite","traceViewer")}var Pt={".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"},iw=new Set([".png",".jpeg",".jpg"]),Hi={"Content-Security-Policy":"sandbox","X-Content-Type-Options":"nosniff"};function aw(e){let t=/<script>([\s\S]*?)<\/script>/.exec(e)[1];return["default-src 'self'",`script-src 'sha256-${nw("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 ff(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(m=>({...m,proof:m.proof??!0}))]}],n=e.start??0;if(!t[n])throw new Error("No scenario to replay");let r=m=>{let v=Xn(m),S=Ui(v.map(x=>({name:x.name,get data(){return x.read()}})));return{zip:m,model:S,resources:new Map(v.filter(x=>x.name.includes("/")).map(x=>[x.name,x.read]))}},s=m=>{try{return m.data?m.data:!m.read&&!Jn.existsSync(m.file)?new un(df):(m.read?m.read():Jn.readFileSync(m.file))??new un(df)}catch(v){return v instanceof un?v:new un(`This trace cannot be read: ${v instanceof Error?v.message:String(v)}`)}},o=[];{let m=t[n],v=m.traces.map(s),S=m.traces.map((x,b)=>({t:x,data:v[b]})).filter(({data:x},b)=>b===0||Buffer.isBuffer(x));for(let[x,b]of m.traces.entries()){let k=v[x];x>0&&!Buffer.isBuffer(k)&&o.push({file:b.file,reason:k.message})}t[n]={...m,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=(m,v)=>{let S=`${m}:${v}`,x=i.get(S);if(x)i.delete(S);else{let b=s(t[m].traces[v]);if(!Buffer.isBuffer(b))throw b;x=r(b);let k=[...i.keys()].filter(h=>{let[y,A]=h.split(":").map(Number),E=t[y].traces[A];return y!==n&&(E.data!==void 0||E.checked===!0)});m!==n&&k.length>=sw&&i.delete(k[0])}return i.set(S,x),x},c=new Map,l=(m,v)=>{let S=t[m].scenario.screenshots?.find(k=>k.file===v);if(!S)return;let x=`${m}:${v}`;if(c.has(x))return c.get(x);let b=An(e.projectRoot,S);return(m===n||!S.sha256)&&c.set(x,b),b};try{a(n,0)}catch(m){if(t.length===1)throw m}for(let m of t[n].scenario.screenshots??[])l(n,m.file);let d=ow(),p=cf(),u={"Content-Security-Policy":aw(p)},f=lf(32).toString("hex"),g=lf(8).toString("hex"),w=t.map(m=>({feature:m.scenario.feature,scenario:m.scenario.scenario,status:m.scenario.status,browser:m.scenario.browser})),R=rw.createServer((m,v)=>{let S=(x,b,k,h={})=>{v.writeHead(x,{"Content-Type":k,"Cache-Control":"no-store",...h}),v.end(b)};try{let x=m.headers.host??"";if(!/^(?:127\.0\.0\.1|localhost)(?::\d+)?$/i.test(x))return S(403,"Invalid host","text/plain");let b=new URL(m.url??"/",`http://${x}`),k=Number(b.searchParams.get("scenario")??n),h=Number.isInteger(k)?t[k]:void 0,y=Number(b.searchParams.get("session")??"0"),A=h&&Number.isInteger(y)?h.traces[y]:void 0,E=()=>S(404,h?"No such trace session":"No such scenario","text/plain");if(b.pathname.startsWith("/api/review/")&&!e.viewOnly){if(m.method!=="POST")return S(405,"Use POST","text/plain");if(m.headers.origin!==`http://${x}`||m.headers["x-saffron-review"]!==f)return S(403,"Review must come from this replay page","text/plain");if(!h||!A)return E();let P=b.pathname.slice(12);if(P!=="accept"&&P!=="reject")return S(404,"Unknown decision","text/plain");try{return af(e.projectRoot,h.scenario,P,m.headers["x-saffron-unverified"]==="yes"),S(200,JSON.stringify({decision:P}),Pt[".json"])}catch(O){return S(409,JSON.stringify({error:O instanceof Error?O.message:String(O)}),Pt[".json"])}}if(m.method!=="GET"&&m.method!=="HEAD")return S(405,"Use GET","text/plain");if(b.pathname==="/"||b.pathname==="/index.html")return S(200,p,Pt[".html"],u);if(b.pathname==="/api/replay"){let P=h?k:n,O=A?y:0,M=t[P],T=M.traces[O],C={scenarios:w,scenarioIndex:P,sessions:M.traces.map(_=>_.label),session:O,proof:T.proof===!0,instance:g},j;try{j=a(P,O).model}catch(_){let F=_ instanceof un?_.message:`This trace cannot be read: ${_ instanceof Error?_.message:String(_)}`;return S(200,JSON.stringify({...C,scenario:M.scenario,unavailable:F}),Pt[".json"])}let L=e.viewOnly?{review:{available:!1,reason:e.viewOnly}}:{review:of(e.projectRoot,M.scenario),reviewToken:f};return S(200,JSON.stringify({...C,scenario:{...M.scenario,steps:T.steps,uniques:T.uniques},trace:j,...L}),Pt[".json"])}if(b.pathname.startsWith("/artifact/")){let P=b.searchParams.get("v");if(P!==null&&P!==g)return S(410,"This replay was restarted. Reload the page.","text/plain");if(!h||!A)return E();if(b.pathname==="/artifact/trace.zip")return S(200,a(k,y).zip,Pt[".zip"],Hi);if(b.pathname.startsWith("/artifact/resource/")){let O=decodeURIComponent(b.pathname.slice(19)),M=a(k,y).resources,T=(M.get(O)??(O.includes("/")?void 0:M.get(`resources/${O}`)))?.();if(!T)return S(404,"no such resource","text/plain");let C=gn.extname(b.pathname).toLowerCase();return S(200,T,iw.has(C)?Pt[C]:"application/octet-stream",Hi)}if(b.pathname.startsWith("/artifact/screenshot/")){let O=l(k,decodeURIComponent(b.pathname.slice(21)));return O?S(200,O,Pt[".jpg"],Hi):S(404,"no such file","text/plain")}}if(b.pathname==="/trace/ping")return S(200,"ok","text/plain");if(b.pathname.startsWith("/trace/")){let P=b.pathname.slice(7)||"index.html",O=gn.join(d,P);if(!Dt(d,O))return S(404,"not found","text/plain");let M=gn.extname(O).toLowerCase(),T=Jn.readFileSync(O);return v.writeHead(200,{"Content-Type":Pt[M]??"application/octet-stream","Service-Worker-Allowed":"/trace/"}),v.end(T)}S(404,"not found","text/plain")}catch{v.headersSent?v.destroy():S(400,"Invalid request","text/plain")}});return await new Promise((m,v)=>{R.once("error",v),R.listen(e.port??0,"127.0.0.1",()=>m())}),{url:`http://127.0.0.1:${R.address().port}/`,skipped:o,close:()=>new Promise(m=>R.close(()=>m()))}}import pf from"node:fs";import Bs from"node:path";function Ds(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 uf(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||He.has(p.action)||!p.target||!u.target)continue;let f=Ds(p.target),g=JSON.stringify(u.target);s.has(f)&&s.get(f)!==g&&r.add(f),s.set(f,g),f!==Ds(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 cw(e){let t=Bs.join(e,".saffron","cache");if(!pf.existsSync(t))return[];let n=[];for(let r of pf.readdirSync(t,{recursive:!0})){let s=String(r);s.endsWith(".json")&&n.push(Bs.join(t,s))}return n}function gf(e,t,n,r){if(t.length===0)return[];let s=new Map,o=new Set;for(let a of t){let c=Ds(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 cw(e)){if(Bs.resolve(a)===Bs.resolve(n))continue;let c=Lt(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||He.has(f.action))continue;let g=s.get(Ds(f.target));g&&(u++,r||(f.target=structuredClone(g.to),d=!0))}u>0&&l.push({gherkin:p.gherkin,count:u})}l.length>0&&(d&&Tn(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 hf from"node:fs";import zs from"node:path";function mf(e,t,n,r,s){let o=Be(zs.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 wf(e,t,n,r,s,o){let i={applied:[],skipped:[],appliedIndices:[]},a=Be(zs.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 g=`${f.file}:${f.line}`;c.set(g,(c.get(g)??new Set).add(u.text))}let l=Fe(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 g=[...Xs([u.text,...eo([u.text])])].filter(y=>!l.has(y));if(g.length>0){i.skipped.push({index:u.index,reason:`it would make the scenario name ${g.map(y=>`{env:${y}}`).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:R,fromStepSet:$,fromBackground:m}=f.source;if(m){i.skipped.push({index:u.index,reason:`"${f.text}" is a Background step shared across scenarios; edit it manually`});continue}let v=`${w}:${R}`,S=c.get(v);if(S.size>1){i.skipped.push({index:u.index,reason:`${v}${$?` (StepSet "${$}")`:""} is reached by several steps and the edits disagree: ${[...S].map(y=>`"${y}"`).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=hf.readFileSync(zs.join(e,w),"utf8").split(`
|
|
1087
|
-
`),
|
|
1088
|
-
`));return i}import{spawn as
|
|
1122
|
+
</html>`}var Vn=class extends Error{},Vu="This trace is gone, or a later run replaced it (one that stopped before writing its report). Run the scenario again to replay it.",Zy=4;function Ja(e,t){let n=Jn.join(e,t.file);try{$r.accessSync(n,$r.constants.R_OK)}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return;throw s}if(!ht(Jn.join(e,".saffron","artifacts"),n))throw new Error(`${t.file} is not a file under .saffron/artifacts`);let r=$r.readFileSync(n);return t.sha256&&At(r)!==t.sha256?void 0:r}function Qy(){let e=To.resolve("playwright-core/package.json");return Jn.join(Jn.dirname(e),"lib","vite","traceViewer")}var ln={".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"},Xy=new Set([".png",".jpeg",".jpg"]),Va={"Content-Security-Policy":"sandbox","X-Content-Type-Options":"nosniff"};function eb(e){let t=/<script>([\s\S]*?)<\/script>/.exec(e)[1];return["default-src 'self'",`script-src 'sha256-${Ky("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 Ju(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(b=>({...b,proof:b.proof??!0}))]}],n=e.start??0;if(!t[n])throw new Error("No scenario to replay");let r=b=>{let y=Lr(b),S=Ha(y.map(x=>({name:x.name,get data(){return x.read()}})));return{zip:b,model:S,resources:new Map(y.filter(x=>x.name.includes("/")).map(x=>[x.name,x.read]))}},s=b=>{try{return b.data?b.data:!b.read&&!$r.existsSync(b.file)?new Vn(Vu):(b.read?b.read():$r.readFileSync(b.file))??new Vn(Vu)}catch(y){return y instanceof Vn?y:new Vn(`This trace cannot be read: ${y instanceof Error?y.message:String(y)}`)}},o=[];{let b=t[n],y=b.traces.map(s),S=b.traces.map((x,C)=>({t:x,data:y[C]})).filter(({data:x},C)=>C===0||Buffer.isBuffer(x));for(let[x,C]of b.traces.entries()){let $=y[x];x>0&&!Buffer.isBuffer($)&&o.push({file:C.file,reason:$.message})}t[n]={...b,traces:S.map(({t:x,data:C})=>({...x,data:Buffer.isBuffer(C)?C:void 0,read:Buffer.isBuffer(C)?void 0:()=>{throw C}}))}}let i=new Map,a=(b,y)=>{let S=`${b}:${y}`,x=i.get(S);if(x)i.delete(S);else{let C=s(t[b].traces[y]);if(!Buffer.isBuffer(C))throw C;x=r(C);let $=[...i.keys()].filter(k=>{let[R,_]=k.split(":").map(Number),v=t[R].traces[_];return R!==n&&(v.data!==void 0||v.checked===!0)});b!==n&&$.length>=Zy&&i.delete($[0])}return i.set(S,x),x},c=new Map,l=(b,y)=>{let S=t[b].scenario.screenshots?.find($=>$.file===y);if(!S)return;let x=`${b}:${y}`;if(c.has(x))return c.get(x);let C=mn(e.projectRoot,S);return(b===n||!S.sha256)&&c.set(x,C),C};try{a(n,0)}catch(b){if(t.length===1)throw b}for(let b of t[n].scenario.screenshots??[])l(n,b.file);let d=Qy(),u=Hu(),g={"Content-Security-Policy":eb(u)},f=qu(32).toString("hex"),p=qu(8).toString("hex"),m=t.map(b=>({feature:b.scenario.feature,scenario:b.scenario.scenario,status:b.scenario.status,browser:b.scenario.browser})),h=Yy.createServer((b,y)=>{let S=(x,C,$,k={})=>{y.writeHead(x,{"Content-Type":$,"Cache-Control":"no-store",...k}),y.end(C)};try{let x=b.headers.host??"";if(!/^(?:127\.0\.0\.1|localhost)(?::\d+)?$/i.test(x))return S(403,"Invalid host","text/plain");let C=new URL(b.url??"/",`http://${x}`),$=Number(C.searchParams.get("scenario")??n),k=Number.isInteger($)?t[$]:void 0,R=Number(C.searchParams.get("session")??"0"),_=k&&Number.isInteger(R)?k.traces[R]:void 0,v=()=>S(404,k?"No such trace session":"No such scenario","text/plain");if(C.pathname.startsWith("/api/review/")&&!e.viewOnly){if(b.method!=="POST")return S(405,"Use POST","text/plain");if(b.headers.origin!==`http://${x}`||b.headers["x-saffron-review"]!==f)return S(403,"Review must come from this replay page","text/plain");if(!k||!_)return v();let A=C.pathname.slice(12);if(A!=="accept"&&A!=="reject")return S(404,"Unknown decision","text/plain");try{return zu(e.projectRoot,k.scenario,A,b.headers["x-saffron-unverified"]==="yes"),S(200,JSON.stringify({decision:A}),ln[".json"])}catch(O){return S(409,JSON.stringify({error:O instanceof Error?O.message:String(O)}),ln[".json"])}}if(b.method!=="GET"&&b.method!=="HEAD")return S(405,"Use GET","text/plain");if(C.pathname==="/"||C.pathname==="/index.html")return S(200,u,ln[".html"],g);if(C.pathname==="/api/replay"){let A=k?$:n,O=_?R:0,P=t[A],E=P.traces[O],T={scenarios:m,scenarioIndex:A,sessions:P.traces.map(F=>F.label),session:O,proof:E.proof===!0,instance:p},M;try{M=a(A,O).model}catch(F){let z=F instanceof Vn?F.message:`This trace cannot be read: ${F instanceof Error?F.message:String(F)}`;return S(200,JSON.stringify({...T,scenario:P.scenario,unavailable:z}),ln[".json"])}let I=e.viewOnly?{review:{available:!1,reason:e.viewOnly}}:{review:Uu(e.projectRoot,P.scenario),reviewToken:f};return S(200,JSON.stringify({...T,scenario:{...P.scenario,steps:E.steps,uniques:E.uniques,traceSession:E.browserSession},trace:M,...I}),ln[".json"])}if(C.pathname.startsWith("/artifact/")){let A=C.searchParams.get("v");if(A!==null&&A!==p)return S(410,"This replay was restarted. Reload the page.","text/plain");if(!k||!_)return v();if(C.pathname==="/artifact/trace.zip")return S(200,a($,R).zip,ln[".zip"],Va);if(C.pathname.startsWith("/artifact/resource/")){let O=decodeURIComponent(C.pathname.slice(19)),P=a($,R).resources,E=(P.get(O)??(O.includes("/")?void 0:P.get(`resources/${O}`)))?.();if(!E)return S(404,"no such resource","text/plain");let T=Jn.extname(C.pathname).toLowerCase();return S(200,E,Xy.has(T)?ln[T]:"application/octet-stream",Va)}if(C.pathname.startsWith("/artifact/screenshot/")){let O=l($,decodeURIComponent(C.pathname.slice(21)));return O?S(200,O,ln[".jpg"],Va):S(404,"no such file","text/plain")}}if(C.pathname==="/trace/ping")return S(200,"ok","text/plain");if(C.pathname.startsWith("/trace/")){let A=C.pathname.slice(7)||"index.html",O=Jn.join(d,A);if(!ht(d,O))return S(404,"not found","text/plain");let P=Jn.extname(O).toLowerCase(),E=$r.readFileSync(O);return y.writeHead(200,{"Content-Type":ln[P]??"application/octet-stream","Service-Worker-Allowed":"/trace/"}),y.end(E)}S(404,"not found","text/plain")}catch{y.headersSent?y.destroy():S(400,"Invalid request","text/plain")}});return await new Promise((b,y)=>{h.once("error",y),h.listen(e.port??0,"127.0.0.1",()=>b())}),{url:`http://127.0.0.1:${h.address().port}/`,skipped:o,close:()=>new Promise(b=>h.close(()=>b()))}}import Wu from"node:fs";import Mo from"node:path";function Fo(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,e.role||e.name||e.nameRegex||e.label||e.text||e.testId||e.placeholder?null:e.fallbackSelectors??[]])}function Gu(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 u=c[d],g=l[d];if(u.action!==g.action||at.has(u.action)||!u.target||!g.target)continue;let f=Fo(u.target),p=JSON.stringify(g.target);s.has(f)&&s.get(f)!==p&&r.add(f),s.set(f,p),f!==Fo(g.target)&&n.set(f,{from:u.target,to:g.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 tb(e){let t=Mo.join(e,".saffron","cache");if(!Wu.existsSync(t))return[];let n=[];for(let r of Wu.readdirSync(t,{recursive:!0})){let s=String(r);s.endsWith(".json")&&n.push(Mo.join(t,s))}return n}function Ku(e,t,n,r){if(t.length===0)return[];let s=new Map,o=new Set;for(let a of t){let c=Fo(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 tb(e)){if(Mo.resolve(a)===Mo.resolve(n))continue;let c=jt(a);if(!c)continue;let l=[],d=!1;for(let u of c.steps){if(u.kind==="assertion")continue;let g=0;for(let f of u.actions){if(!f.target||at.has(f.action))continue;let p=s.get(Fo(f.target));p&&(g++,r||(f.target=structuredClone(p.to),d=!0))}g>0&&l.push({gherkin:u.gherkin,count:g})}l.length>0&&(d&&tr(a,c),i.push({file:a,scenario:c.scenario,feature:c.feature,steps:l}))}return i}function Bo(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 Yu from"node:fs";import Lo from"node:path";function Zu(e,t,n,r,s){let o=Ze(Lo.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 Qu(e,t,n,r,s,o){let i={applied:[],skipped:[],appliedIndices:[]},a=r.filter(f=>f.text.trim()!==""?!0:(i.skipped.push({index:f.index,reason:"the edit has no step text"}),!1)),c=Ze(Lo.join(e,t),e,s).find(f=>f.name===n);if(!c){for(let f of a)i.skipped.push({index:f.index,reason:`scenario "${n}" not found in ${t}`});return i}let l=new Map;for(let f of a){let p=c.steps[f.index]?.source;if(!p||p.fromBackground)continue;let m=`${p.file}:${p.line}`;l.set(m,(l.get(m)??new Set).add(f.text))}let d=We(c),u=new Map,g=new Set;for(let f of a){let p=c.steps[f.index];if(!p?.source){i.skipped.push({index:f.index,reason:`no step at index ${f.index}`});continue}let m=[...ei([f.text,...Cr([f.text])])].filter(v=>!d.has(v));if(m.length>0){i.skipped.push({index:f.index,reason:`it would make the scenario name ${m.map(v=>`{env:${v}}`).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(kt(f.text)!==kt(p.text)){i.skipped.push({index:f.index,reason:'it would change which browser session the step runs in (its As "..."); edit the feature file by hand if you mean it'});continue}if(o&&o[f.index]!==p.text){i.skipped.push({index:f.index,reason:`step ${f.index+1} now reads "${p.text}", not the "${o[f.index]??"(nothing)"}" this edit was written for`});continue}let{file:h,line:w,fromStepSet:b,fromBackground:y}=p.source;if(y){i.skipped.push({index:f.index,reason:`"${p.text}" is a Background step shared across scenarios; edit it manually`});continue}let S=`${h}:${w}`,x=l.get(S);if(x.size>1){i.skipped.push({index:f.index,reason:`${S}${b?` (StepSet "${b}")`:""} is reached by several steps and the edits disagree: ${[...x].map(v=>`"${v}"`).join(" vs ")}. Decide the wording in the definition by hand`});continue}let C=c.steps.findIndex((v,A)=>v.source?.file===h&&v.source.line===w&&v.text!==f.text&&!a.some(O=>O.index===A&&O.text===f.text));if(C>=0){i.skipped.push({index:f.index,reason:`${S} is also used at step ${C+1}, which has no agreeing edit; edit the shared definition by hand`});continue}if(g.has(S)){i.appliedIndices.push(f.index);continue}let $=u.get(h);$||($=Yu.readFileSync(Lo.join(e,h),"utf8").split(`
|
|
1123
|
+
`),u.set(h,$));let k=$[w-1],R=k?.match(/^(\s*)(\S+)\s+(.*)$/);if(!R||R[3]!==p.text){i.skipped.push({index:f.index,reason:`${h}:${w} no longer matches the recorded step text`});continue}let _=`${R[1]}${R[2]} ${f.text}`;$[w-1]=_,g.add(S),i.appliedIndices.push(f.index),i.applied.push({file:h,line:w,from:k.trim(),to:_.trim(),fromStepSet:b})}for(let[f,p]of u)i.applied.some(m=>m.file===f)&&Yu.writeFileSync(Lo.join(e,f),p.join(`
|
|
1124
|
+
`));return i}import{spawn as nb}from"node:child_process";function Wa(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 rb(e,t,n){let r=Date.now();return new Promise(s=>{let o=process.platform!=="win32",i=nb(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),u=()=>{c=!0,l()};n.signal?.addEventListener("abort",u,{once:!0});let g=f=>{clearTimeout(d),n.signal?.removeEventListener("abort",u),s({phase:e,command:t,exitCode:f,durationMs:Date.now()-r,...a?{timedOut:a}:{},...c?{cancelled:c}:{}})};i.on("error",()=>g(null)),i.on("exit",f=>g(a||c?null:f))})}var Do=e=>e.exitCode!==0;async function Ga(e,t,n){let r=[];for(let s of t){if(n.signal?.aborted)break;console.error(`saffron ${e}: ${s}`);let o=await rb(e,s,n);if(r.push(o),o.cancelled||Do(o)&&(console.error(`saffron ${e} failed: ${Ka(o,n.timeoutMs)}`),e==="setup"))break}return r}function Ka(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 sb=`
|
|
1089
1125
|
.wrap { max-width: 1180px; }
|
|
1090
1126
|
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); gap: 0 14px; align-items: start; }
|
|
1091
1127
|
.panel { min-width: 0; }
|
|
@@ -1127,42 +1163,42 @@ ${e.prompt}`,e)),i.status==="error"&&!e.finished())throw new Error(`Cursor: ${i.
|
|
|
1127
1163
|
details.more summary { padding: 6px 0 0; font-family: var(--mono); font-size: 10.5px; color: var(--muted); }
|
|
1128
1164
|
details.more summary:hover { background: none; color: var(--text); }
|
|
1129
1165
|
@media (max-width: 560px) { .wrap { padding: 14px 12px 40px; } .grid { grid-template-columns: 1fr; } .kpis { grid-template-columns: repeat(2, 1fr); } }
|
|
1130
|
-
`,
|
|
1131
|
-
${
|
|
1132
|
-
${
|
|
1133
|
-
${
|
|
1134
|
-
${
|
|
1135
|
-
${
|
|
1136
|
-
${
|
|
1137
|
-
${
|
|
1138
|
-
${
|
|
1139
|
-
</section>`,d=`<div class="panel"><div class="panel-title">suite health \xB7 each scenario's latest result</div>${
|
|
1140
|
-
${
|
|
1141
|
-
${
|
|
1142
|
-
</div>`,
|
|
1166
|
+
`,se=e=>String(Number(e)),Ya=e=>B(Le(Number(e))),Wn=(e,t)=>`${se(e)} ${t}${Number(e)===1?"":"s"}`,Za=e=>new Date(e).toLocaleString("en-GB",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}),Qa=e=>new Date(e).toLocaleString("en-GB",{day:"2-digit",month:"short",hour:"2-digit",minute:"2-digit"});function fs(e,t=""){let n=e.name??e.scenario;return`<div class="row-main"><div class="scn" data-f="${B(e.feature)}" data-s="${B(n)}" title="${B(`${e.feature} \u203A ${e.scenario}`)}">${B(e.scenario)}</div><div class="feat">${B(e.feature)}${e.browser?` \xB7 ${B(e.browser)}`:""}</div>${t}</div>`}function dn(e,t,n,r,s,o=""){return`<div class="panel${o?` accent-${o}`:""}"><div class="panel-head"><div class="panel-title${n?` ${n}`:""}">${B(e)}</div>${t===void 0?"":`<span class="count${t>0&&n?` ${n}`:""}">${se(t)}</span>`}</div>${r||`<div class="empty">${B(s)}</div>`}</div>`}function Xu(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 ep(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>${B(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>${B(Qa(e[0].startedAt))}</span><span>${B(Qa(e.at(-1).startedAt))}</span></div>`}var us=e=>e.length?`<ul class="rows">${e.join("")}</ul>`:"";function tp(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 ${se(x)} unverified`:"",i=n.red,a=e.lastRun,c=s===void 0?"":s>=95?"green":s>=80?"gold":"red",l=`<section class="kpis">
|
|
1167
|
+
${pe("tests",se(n.tests),`${Wn(n.scenarios,"scenario")} \xB7 ${Wn(n.features,"feature")}`)}
|
|
1168
|
+
${pe("passing",s===void 0?"\u2013":`${s}<span class="unit">%</span>`,`${se(n.green+n.yellow)} of ${se(r)} \xB7 latest results${o(n.unverified)}`,c,"",fr(e.trend.map(x=>x.passRate),"var(--green)"))}
|
|
1169
|
+
${pe("failing",se(i),i>0?"\u25BC red the last time they ran":"all clear",i>0?"red":"",i>0?"red":"green")}
|
|
1170
|
+
${pe("flaky",se(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")}
|
|
1171
|
+
${pe("never run",se(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")}
|
|
1172
|
+
${pe("last run",a?Ya(a.durationMs):"\u2013",a?`${Wn(a.ran,"test")} \xB7 ${se(a.passRate)}% passed${o(a.unverified)}`:"no run yet","","",fr(e.trend.map(x=>x.durationMs),"var(--muted)"))}
|
|
1173
|
+
${pe("zero-ai replay",a?`${se(a.replayRate)}<span class="unit">%</span>`:"\u2013","replayed from recordings, last run",a&&a.replayRate>=90?"green":"")}
|
|
1174
|
+
${pe("recorded",n.scenarios?`${Math.round(n.recorded/n.scenarios*100)}<span class="unit">%</span>`:"\u2013",n.scenarios-n.recorded>0?`${se(n.scenarios-n.recorded)} still need the agent`:"every scenario has a current recording",n.recorded===n.scenarios?"green":"")}
|
|
1175
|
+
</section>`,d=`<div class="panel"><div class="panel-title">suite health \xB7 each scenario's latest result</div>${Xu([[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>${se(n.green)} passed</span><span><i class="dot gold"></i>${se(n.yellow)} healed</span>${n.unverified>0?`<span><i class="dot unverified"></i>${se(n.unverified)} healed, unverified</span>`:""}<span><i class="dot red"></i>${se(n.red)} failed</span><span><i class="dot faint"></i>${se(n.neverRun)} never run</span></div></div>`,u=`<div class="grid">
|
|
1176
|
+
${dn(`pass rate \xB7 last ${Wn(e.trend.length,"run")}`,void 0,"",ep(e.trend,x=>x.passRate,x=>`${Za(x.startedAt)}: ${se(x.passRate)}% of ${se(x.tests)} passed, ${se(x.red)} failed`,x=>x.red>0?"--red":"--green"),"")}
|
|
1177
|
+
${dn(`execution time \xB7 last ${Wn(e.trend.length,"run")}`,void 0,"",ep(e.trend,x=>x.durationMs,x=>`${Za(x.startedAt)}: ${Le(Number(x.durationMs))} for ${Wn(x.tests,"test")}`,()=>"--muted"),"")}
|
|
1178
|
+
</div>`,g=us(e.recentFailures.map(x=>`<li><i class="dot ${x.stillFailing?"red":"green"}"></i>${fs(x,x.error?`<div class="err" title="${B(x.error)}">${B(x.error)}</div>`:"")}<div class="row-side">${x.stillFailing?`<span class="red">${se(x.streak)} run${Number(x.streak)===1?"":"s"} in a row</span>`:'<span class="green">passed since</span>'}<br>${B(Qa(x.at))}</div></li>`)),f=us(e.flaky.map(x=>`<li><i class="dot gold"></i>${fs(x)}<div class="row-side">flipped ${se(x.flips)}\xD7 in ${se(x.runs)} runs<br>${se(x.reds)} red \xB7 last <span class="${x.last==="red"?"red":"green"}">${x.last==="red"?"failed":"passed"}</span></div></li>`)),p=us(e.healing.map(x=>`<li><i class="dot gold"></i>${fs(x)}<div class="row-side">healed ${se(x.heals)}\xD7${x.unverified>0?` <span class="gold">(${se(x.unverified)} unverified)</span>`:""}<br>in ${se(x.runs)} runs</div></li>`)),m=Math.max(1,...e.slowest.map(x=>x.avgMs)),h=us(e.slowest.map(x=>`<li>${fs(x,`<div class="meter" style="width:${(x.avgMs/m*100).toFixed(1)}%"></div>`)}<div class="row-side">avg ${Ya(x.avgMs)}<br>last ${Ya(x.lastMs)}</div></li>`)),w=e.tags.length?`<table class="tags">${e.tags.map(x=>{let C=x.scenarios-x.neverRun,$=x.red>0?`<span style="color:var(--red)">${se(x.red)} red</span>`:C===0?"never run":`${Math.round((x.green+x.yellow)/C*100)}%`;return`<tr><td class="tagname">${B(x.tag)}</td><td class="num">${se(x.scenarios)}</td><td class="stackcell">${Xu([[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">${$}</td></tr>`}).join("")}</table>`:"",b=(x,C)=>us(x.map($=>`<li><i class="dot ${C}"></i>${fs($)}</li>`)),y=e.notInLastRun.length?`<details class="more"><summary>left out by tags or paths \xB7 show ${se(e.notInLastRun.length)}</summary>${b(e.notInLastRun,"idle")}</details>`:"",S=e.historyRuns===0?"no runs recorded yet":`${Wn(e.historyRuns,"run")} in .saffron/history.jsonl`;return`<!doctype html>
|
|
1143
1179
|
<html lang="en">
|
|
1144
1180
|
<head>
|
|
1145
1181
|
<meta charset="utf-8"/>
|
|
1146
1182
|
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
|
1147
1183
|
<title>Saffron dashboard</title>
|
|
1148
|
-
${
|
|
1184
|
+
${Zr}
|
|
1149
1185
|
<style>
|
|
1150
|
-
${
|
|
1186
|
+
${Qr}${sb}</style>
|
|
1151
1187
|
</head>
|
|
1152
1188
|
<body>
|
|
1153
1189
|
<div class="topline"></div>
|
|
1154
1190
|
<div class="wrap">
|
|
1155
1191
|
<header class="top">
|
|
1156
1192
|
<div class="brand">
|
|
1157
|
-
${
|
|
1193
|
+
${Bn(38)}
|
|
1158
1194
|
<div>
|
|
1159
1195
|
<div class="brand-name">saffron</div>
|
|
1160
1196
|
<div class="brand-sub">suite quality</div>
|
|
1161
1197
|
</div>
|
|
1162
1198
|
</div>
|
|
1163
1199
|
<div class="run-meta">
|
|
1164
|
-
<span>${
|
|
1165
|
-
${a?`<span>\xB7</span><span>last run ${
|
|
1200
|
+
<span>${B(S)}</span>
|
|
1201
|
+
${a?`<span>\xB7</span><span>last run ${B(Za(a.startedAt))}</span>`:""}
|
|
1166
1202
|
</div>
|
|
1167
1203
|
</header>
|
|
1168
1204
|
|
|
@@ -1170,24 +1206,24 @@ ${ti}${fw}</style>
|
|
|
1170
1206
|
${d}
|
|
1171
1207
|
|
|
1172
1208
|
<div class="section-head"><span class="section-title">trends</span></div>
|
|
1173
|
-
${
|
|
1209
|
+
${u}
|
|
1174
1210
|
|
|
1175
1211
|
<div class="section-head"><span class="section-title">stability</span></div>
|
|
1176
1212
|
<div class="grid">
|
|
1177
|
-
${
|
|
1178
|
-
${
|
|
1179
|
-
${
|
|
1180
|
-
${
|
|
1213
|
+
${dn("recent failures \xB7 last 10 runs",e.recentFailures.length,"red",g,"Nothing failed in the last 10 runs.",i>0?"red":"")}
|
|
1214
|
+
${dn("flaky \xB7 last 20 runs",e.flaky.length,"gold",f,"No scenario passed and failed by turns.",e.flaky.length>0?"gold":"")}
|
|
1215
|
+
${dn("healed again and again",e.healing.length,"gold",p?`<div class="note">The page keeps changing under these: review the heals, or fix the step.</div>${p}`:"","No scenario needed the agent twice in the last 20 runs.")}
|
|
1216
|
+
${dn("slowest \xB7 average over 20 runs",void 0,"",h,"No timings yet.")}
|
|
1181
1217
|
</div>
|
|
1182
1218
|
|
|
1183
1219
|
<div class="section-head"><span class="section-title">coverage</span></div>
|
|
1184
1220
|
<div class="grid">
|
|
1185
|
-
${
|
|
1186
|
-
${
|
|
1187
|
-
${
|
|
1221
|
+
${dn("tags \xB7 latest results",e.tags.length,"",w,"No tags in the feature files.")}
|
|
1222
|
+
${dn("never run",e.neverRun.length,"gold",b(e.neverRun,"faint"),"Every scenario has run at least once.")}
|
|
1223
|
+
${dn("not in the last run",e.notInLastRun.length,"",y,"The last run ran every scenario that has run before.")}
|
|
1188
1224
|
</div>
|
|
1189
1225
|
|
|
1190
|
-
<footer>${
|
|
1226
|
+
<footer>${Yr(11)} generated by saffron v${B(t)}</footer>
|
|
1191
1227
|
</div>
|
|
1192
1228
|
<script>
|
|
1193
1229
|
if (typeof window.saffronOpen === "function") document.body.classList.add("linked");
|
|
@@ -1198,62 +1234,137 @@ ${ti}${fw}</style>
|
|
|
1198
1234
|
</script>
|
|
1199
1235
|
</body>
|
|
1200
1236
|
</html>
|
|
1201
|
-
`}import{spawnSync as
|
|
1202
|
-
|
|
1203
|
-
`).map(n=>n.trim()).find(n=>n&&!/^WARNING:/.test(n))??t;function Vn(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(kr(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(kr(e))?{kind:"not-a-repository",message:Yi(e,"not a GitHub repository")}:{kind:"failed",message:Yi(e,`gh exited with ${e.status}`)}}function mn(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=kr(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:Yi(e,`az exited with ${e.status}`)}}function Xi(e,t,n){let r=n??t.ci?.provider;if(r!==void 0){if(!pw.includes(r))throw new z(`unknown CI provider "${r}": use "github" or "azure"`);return r}return vs(e).some(s=>s.startsWith("dev.azure.com/"))?"azure":"github"}var Tr=e=>[...e.ci?.organization?["--organization",e.ci.organization]:[],...e.ci?.project?["--project",e.ci.project]:[]];function gw(e,t){let n=Re("git",["rev-parse","--abbrev-ref","HEAD"],e,t),r=n.status===0?n.stdout.trim():"";return r&&r!=="HEAD"?r:void 0}function hw(e){let t=new Map;for(let[n,r]of Object.entries(_t(e))){try{if(Ge(oe.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 $f(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 X=e=>typeof e=="string"&&e?e:void 0,xf=e=>X(e)?.replace(/^refs\/(heads|tags)\//,""),mw="databaseId,number,attempt,displayTitle,workflowName,status,conclusion,event,headBranch,headSha,createdAt,url";function ww(e){let t=e.status==="completed"?"completed":e.status==="in_progress"?"in_progress":"queued";return{id:String(e.databaseId),name:X(e.workflowName)??"workflow",number:String(e.number??""),title:X(e.displayTitle),status:t,conclusion:t==="completed"?X(e.conclusion):void 0,event:X(e.event),branch:X(e.headBranch),commit:X(e.headSha),createdAt:X(e.createdAt),url:X(e.url),attempt:typeof e.attempt=="number"?e.attempt:void 0}}var yw={completed:"completed",inProgress:"in_progress",cancelling:"in_progress"},bw={succeeded:"success",partiallySucceeded:"partial",failed:"failure",canceled:"cancelled"},vw={individualCI:"push",batchedCI:"push",pullRequest:"pull_request",schedule:"schedule",manual:"manual"};function kf(e){let t=e.triggerInfo??{};return xf(t["pr.sourceBranch"])??xf(e.sourceBranch)}function Rf(e){let t=e.triggerInfo??{},n=yw[String(e.status)]??"queued",r=X(e.result);return{id:String(e.id),name:X(e.definition?.name)??"pipeline",number:String(e.buildNumber??e.id),status:n,conclusion:n==="completed"&&r?bw[r]??r:void 0,event:X(e.reason)?vw[String(e.reason)]??String(e.reason):void 0,branch:kf(e),commit:X(t["pr.sourceSha"])??X(e.sourceVersion),createdAt:X(e.queueTime),url:X((e._links??{}).web?.href)}}function Zi(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function ea(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>!!n&&typeof n=="object"):void 0}catch{return}}function Sw(e){return new Set(e.map(t=>t.startsWith("dev.azure.com/")?t.slice(t.lastIndexOf("/_git/")+6):t.slice(t.indexOf("/")+1)))}function xw(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=Re("az",["pipelines","runs","list","--top",String(a),...r,"--output","json",...Tr(t)],e,n);if(c.missing||c.status!==0)return mn(c);let l=ea(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 Tf(e,t,n={}){let r=n.env??process.env,s=Xi(e,t,n.provider),o=n.branch??gw(e,r),i=o===void 0?void 0:Wn(o),a=n.limit??20,c;if(s==="github"){let d=Re("gh",["run","list","--limit",String(a),"--json",mw,...i?["--branch",i]:[]],e,r);if(d.missing||d.status!==0)return{provider:s,branch:i,runs:[],problem:Vn(d)};let p=ea(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(ww)}else{let d=Sw(vs(e)),p=w=>{let R=X(w.repository?.name)?.toLowerCase();return d.size===0||!R||d.has(R)},u=w=>p(w)&&(!i||kf(w)===i),f=i?[["--branch",`refs/heads/${i}`],["--branch",`refs/tags/${i}`],["--reason","pullRequest"]]:[[]],g=new Map;for(let w of f){let R=xw(e,t,r,w,u,a);if(!Array.isArray(R))return{provider:s,branch:i,runs:[],problem:R};for(let $ of R)g.set(String($.id),$)}c=[...g.values()].sort((w,R)=>(Date.parse(X(R.queueTime)??"")||0)-(Date.parse(X(w.queueTime)??"")||0)).slice(0,a).map(Rf)}let l=hw(e);return{provider:s,branch:i,runs:c.map(d=>({...d,pending:l.get(`${s}:${d.id}`)??0}))}}var Qi=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 Ef(e,t,n,r,s,o){let i,a;if(n==="github"){let c=Re("gh",["api",`repos/{owner}/{repo}/actions/runs/${r}`],e,s);if(c.missing||c.status!==0)throw new z(Vn(c).message,Vn(c).kind);let l=Zi(c.stdout),d=X(l?.repository?.full_name);if(!l||String(l.id)!==r||!d)throw new z(`gh answered with something other than run ${r}`);let p=X(l.head_repository?.full_name);p?.toLowerCase()!==d.toLowerCase()&&(i={event:X(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:X(l.name),branch:X(l.head_branch),commit:X(l.head_sha),url:X(l.html_url),status:u,conclusion:u==="completed"?X(l.conclusion):void 0,createdAt:X(l.created_at)}}else{let c=Re("az",["pipelines","runs","show","--id",r,"--output","json",...Tr(t)],e,s);if(c.missing||c.status!==0)throw new z(mn(c).message,mn(c).kind);let l=Zi(c.stdout);if(!l||String(l.id)!==r)throw new z(`az answered with something other than run ${r}`);let d=Rf(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 z(`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 $w=/^saffron-bundle[\w.-]*$/;function Af(e,t,n,r,s){let o;if(n==="github"){o=[];for(let i=1;o;i++){let a=Re("gh",["api",`repos/{owner}/{repo}/actions/runs/${r}/artifacts?per_page=100&page=${i}`],e,s);if(a.missing||a.status!==0)throw new z(Vn(a).message,Vn(a).kind);let c=Zi(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=Re("az",["pipelines","runs","artifact","list","--run-id",r,"--output","json",...Tr(t)],e,s);if(i.missing||i.status!==0)throw new z(mn(i).message,mn(i).kind);o=ea(i.stdout)}if(!o)throw new z(`${n==="github"?"gh":"az"} answered with something other than a list of artifacts`);return o.filter(i=>typeof i.name=="string"&&$w.test(i.name)).map(i=>({name:i.name,sizeBytes:Number(i.size_in_bytes??((i.resource??{}).properties??{}).artifactsize)||0,expired:i.expired===!0}))}function _f(e,t,n,r,s,o,i){if(i.length===0)throw new z(Qi(r));for(let a of i){let c=n==="github"?Re("gh",["run","download",r,"-n",a,"--dir",oe.join(s,a)],e,o):Re("az",["pipelines","runs","artifact","download","--run-id",r,"--artifact-name",a,"--path",oe.join(s,a),...Tr(t)],e,o);if(c.missing||c.status!==0)throw n==="github"&&/no (valid )?artifact/i.test(kr(c))?new z(Qi(r)):new z(`cannot download ${a}: ${(n==="github"?Vn(c):mn(c)).message}`)}}function If(e,t,n,r={}){Cf(n);let s=r.env??process.env,o=Xi(e,t,r.provider),i=Ef(e,t,o,n,s,r.allowFork===!0),a=Pf(e,o,n,i.attempt);if(i.status==="completed"&&ae.existsSync(a))return{provider:o,dir:oe.join(a,"bundles"),remove:()=>{}};let c=Af(e,t,o,n,s).filter(p=>!p.expired).map(p=>p.name);if(c.length===0)throw new z(Qi(n));let{dir:l,remove:d}=mi(e);try{return _f(e,t,o,n,l,s,c),{provider:o,dir:l,remove:d}}catch(p){throw d(),p}}function Cf(e){if(!/^\d+$/.test(e))throw new z(`--run takes the run's id, a number as saffron runs lists it, not "${e}"`)}var ta=e=>oe.join(e,".saffron","ci"),Pf=(e,t,n,r)=>oe.join(ta(e),`${t}-${n}`,`attempt-${r}`),kw=10,Rw=1024**3;function Tw(e){let t=0;for(let n of ae.readdirSync(e,{recursive:!0})){let r=ae.lstatSync(oe.join(e,String(n)),{throwIfNoEntry:!1});r?.isFile()&&(t+=r.size)}return t}function Ew(e,t){let n=ta(e),r=ae.readdirSync(n,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>oe.join(n,i.name)).map(i=>({run:i,mtime:ae.statSync(i).mtimeMs,bytes:Tw(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>kw||o+i.bytes>Rw)){ae.rmSync(i.run,{recursive:!0,force:!0});continue}s++,o+=i.bytes}}var Rr=class extends z{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 na(e,t,n,r={}){Cf(n);let s=r.env??process.env,o=Xi(e,t,r.provider),i=Ef(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=Af(e,t,o,n,s),c=a.filter($=>!$.expired),l=c.map(({name:$,sizeBytes:m})=>({name:$,sizeBytes:m})),d=Pf(e,o,n,i.attempt),p=new Date;if(ae.existsSync(d))return ae.utimesSync(oe.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(($,m)=>$+m.sizeBytes,0);if(r.maxDownloadBytes!==void 0&&u>r.maxDownloadBytes)throw new Rr(u,r.maxDownloadBytes);let f=ta(e);ae.mkdirSync(f,{recursive:!0});let g=oe.join(f,".gitignore");ae.existsSync(g)||ae.writeFileSync(g,`*
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1237
|
+
`}import{spawnSync as vp}from"node:child_process";import xt from"node:fs";import Sp from"node:os";import me from"node:path";import{spawnSync as rp}from"node:child_process";import be from"node:fs";import ae from"node:path";import ob from"node:fs";import Xa from"node:path";var ib=`
|
|
1238
|
+
.wrap { max-width: 1060px; }
|
|
1239
|
+
.acts { display: none; gap: 8px; flex-wrap: wrap; margin-top: 10px; }
|
|
1240
|
+
.linked .acts { display: flex; }
|
|
1241
|
+
.act { font: 600 11px var(--mono); color: var(--text-dim); background: var(--card); border: 1px solid var(--border-2); border-radius: 6px; padding: 4px 10px; cursor: pointer; }
|
|
1242
|
+
.act:hover { color: var(--text); border-color: var(--brand); }
|
|
1243
|
+
.act.primary { color: var(--brand); }
|
|
1244
|
+
.cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 14px; align-items: start; }
|
|
1245
|
+
.card { background: var(--card); border: 1px solid var(--border); border-radius: 10px; padding: 14px; min-width: 0; }
|
|
1246
|
+
.card.red { border-left: 3px solid var(--red); }
|
|
1247
|
+
.card.yellow { border-left: 3px solid var(--gold); }
|
|
1248
|
+
.card .scn { color: #E7E9EC; font-weight: 500; font-size: 14px; overflow-wrap: anywhere; }
|
|
1249
|
+
.card .feat { font-family: var(--mono); font-size: 10.5px; color: var(--faint); margin-top: 2px; overflow-wrap: anywhere; }
|
|
1250
|
+
.card .step { font-size: 12.5px; color: var(--text-dim); margin-top: 8px; overflow-wrap: anywhere; }
|
|
1251
|
+
.card .err { font-family: var(--mono); font-size: 11px; color: var(--red); margin-top: 4px; overflow-wrap: anywhere; }
|
|
1252
|
+
.card .story { font-size: 12px; color: var(--muted); margin-top: 6px; overflow-wrap: anywhere; }
|
|
1253
|
+
.shot { display: block; width: 100%; max-height: 220px; object-fit: cover; object-position: top; border-radius: 6px; border: 1px solid var(--border); margin-top: 10px; background: #0d0e10; }
|
|
1254
|
+
details.shot-full summary { list-style: none; cursor: zoom-in; padding: 0; background: none; }
|
|
1255
|
+
details.shot-full summary::-webkit-details-marker { display: none; }
|
|
1256
|
+
details.shot-full[open] .shot { max-height: none; cursor: zoom-out; }
|
|
1257
|
+
.note { font-size: 12.5px; color: var(--muted); }
|
|
1258
|
+
.rows { list-style: none; padding: 0; margin: 8px 0 0; }
|
|
1259
|
+
.rows li { display: flex; gap: 10px; align-items: baseline; padding: 6px 0; border-top: 1px solid var(--border); font-size: 12.5px; min-width: 0; }
|
|
1260
|
+
.rows li:first-child { border-top: none; }
|
|
1261
|
+
.rows .grow { flex: 1; min-width: 0; overflow-wrap: anywhere; }
|
|
1262
|
+
.rows .why { font-family: var(--mono); font-size: 10.5px; color: var(--muted); }
|
|
1263
|
+
.ok { color: var(--green); } .no { color: var(--muted); }
|
|
1264
|
+
details.more summary { padding: 2px 0; font-family: var(--mono); font-size: 10.5px; color: var(--muted); cursor: pointer; }
|
|
1265
|
+
details.more summary:hover { color: var(--text); }
|
|
1266
|
+
`;function ab(e,t){if(!(!t||!ht(Xa.join(e,".saffron","ci"),Xa.join(e,t))))try{let n=ob.readFileSync(Xa.join(e,t));return n.length<=4*1024**2?`data:image/${/\.png$/i.test(t)?"png":"jpeg"};base64,${n.toString("base64")}`:void 0}catch{return}}var ps=(e,t,n,r=!1)=>`<button class="act${r?" primary":""}" data-act="${B(e)}"${n?` data-f="${B(n.feature)}" data-s="${B(n.scenario)}"${n.browser?` data-b="${B(n.browser)}"`:""}`:""}>${B(t)}</button>`,np=e=>e?.split(`
|
|
1267
|
+
`).map(t=>t.trim()).find(Boolean);function Uo(e,t,n){let{run:r}=e,s=`${r.name??"CI run"} \xB7 run ${r.id}${r.attempt>1?`, attempt ${r.attempt}`:""}`,o=[r.status==="completed"?r.conclusion??"completed":r.status.replace("_"," "),r.branch&&`${r.branch}${r.commit?` @ ${r.commit.slice(0,7)}`:""}`,r.createdAt&&new Date(r.createdAt).toLocaleString("en-GB",{day:"2-digit",month:"short",hour:"2-digit",minute:"2-digit"})].filter(Boolean),i;if(!e.bundle)i=`<div class="panel"><div class="panel-title">no results</div><div class="note">${B(e.reason??"This run has no Saffron results.")}</div></div>`;else{let a=e.scenarios??[],c=e.totals??{green:0,yellow:0,red:0,aiCalls:0,costUsd:0},l=`<div class="kpis">${pe("passed",String(c.green),"green","green")}${pe("pending review",String(c.yellow),"healed or recorded",c.yellow?"gold":"")}${pe("failed",String(c.red),"red",c.red?"red":"")}${pe("agent",c.costUsd>0?`$${c.costUsd.toFixed(2)}`:String(c.aiCalls),c.costUsd>0?`${c.aiCalls} AI calls`:"AI calls")}</div>`,d=e.warnings.length?`<div class="panel accent-gold"><div class="panel-title gold">warnings</div>${e.warnings.map(x=>`<div class="note">${B(x)}</div>`).join("")}</div>`:"",u=e.bundle.summaryOnly?'<div class="panel"><div class="note">This run uploaded only a summary (saffron export --report-only): its results and screenshots, no traces to replay and nothing to import.</div></div>':"",g=x=>{let C=ab(t,x.screenshot),$={feature:x.feature,scenario:x.displayName,browser:x.browser},k={feature:x.feature,scenario:x.scenario,browser:x.browser};return`<div class="card ${x.status==="red"?"red":"yellow"}">
|
|
1268
|
+
<div class="scn">${B(x.displayName)}</div>
|
|
1269
|
+
<div class="feat">${B(x.feature)}${x.browser?` \xB7 ${B(x.browser)}`:""} \xB7 ${B(Le(x.durationMs))}${x.verified===!1?" \xB7 unverified":x.verified?" \xB7 verified":""}</div>
|
|
1270
|
+
${x.failingStep?`<div class="step">${x.status==="red"?"failed at":"changed at"}: ${B(np(x.failingStep)??"")}</div>`:""}
|
|
1271
|
+
${x.error?`<div class="err">${B(x.error)}</div>`:""}
|
|
1272
|
+
${x.narrative?`<div class="story">${B(x.narrative)}</div>`:""}
|
|
1273
|
+
${C?`<details class="shot-full"><summary><img class="shot" src="${C}" alt="screenshot of ${B(x.displayName)}"></summary></details>`:""}
|
|
1274
|
+
<div class="acts">${x.trace?ps("trace","Open trace",$,!0):""}${ps("open","Open scenario",k)}</div>
|
|
1275
|
+
</div>`},f=a.filter(x=>x.status==="red"),p=a.filter(x=>x.status==="yellow"),m=a.filter(x=>x.status==="green"),h=(x,C)=>C.length?`<div class="section-head"><span class="section-title">${B(x)}</span></div><div class="cards">${C.map(g).join("")}</div>`:"",w=m.length?`<div class="section-head"><span class="section-title">passed</span></div><div class="panel"><details class="more"><summary>${m.length} scenario${m.length===1?"":"s"} passed</summary><ul class="rows">${m.map(x=>`<li><span class="grow">${B(x.displayName)}</span><span class="why">${B(x.feature)}${x.browser?` \xB7 ${B(x.browser)}`:""}</span></li>`).join("")}</ul></details></div>`:"",b=e.proposals??[],y=b.filter(x=>x.importable).length,S=b.length?`<div class="section-head"><span class="section-title">proposals</span></div><div class="panel"><div class="note">${b.length} proposal${b.length===1?"":"s"}, ${y} importable here. Import files them for review in this checkout.</div><ul class="rows">${b.map(x=>`<li><span class="${x.importable?"ok":"no"}">${x.importable?"\u2713":"\xB7"}</span><span class="grow">${B(x.feature)} \u203A ${B(x.scenario)}</span><span class="why">${B(x.importable?x.verified?"verified":"unverified":np(x.reason)??"not importable")}</span></li>`).join("")}</ul>${y?`<div class="acts">${ps("import","Import",void 0,!0)}</div>`:""}</div>`:"";i=`${l}${d}${u}${h("failed",f)}${h("pending review",p)}${w}${S}`}return`<!doctype html>
|
|
1276
|
+
<html lang="en">
|
|
1277
|
+
<head>
|
|
1278
|
+
<meta charset="utf-8"/>
|
|
1279
|
+
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
|
1280
|
+
<title>${B(s)}</title>
|
|
1281
|
+
${Zr}
|
|
1282
|
+
<style>
|
|
1283
|
+
${Qr}${ib}</style>
|
|
1284
|
+
</head>
|
|
1285
|
+
<body>
|
|
1286
|
+
<div class="topline"></div>
|
|
1287
|
+
<div class="wrap">
|
|
1288
|
+
<header class="top">
|
|
1289
|
+
<div class="brand">
|
|
1290
|
+
${Bn(38)}
|
|
1291
|
+
<div>
|
|
1292
|
+
<div class="brand-name">saffron</div>
|
|
1293
|
+
<div class="brand-sub">${B(s)}</div>
|
|
1294
|
+
</div>
|
|
1295
|
+
</div>
|
|
1296
|
+
<div class="run-meta">${o.map(a=>`<span>${B(a)}</span>`).join("<span>\xB7</span>")}</div>
|
|
1297
|
+
</header>
|
|
1298
|
+
<div class="acts">${e.reportHtml?ps("report","Open report"):""}${r.url?ps("run","Open run page"):""}</div>
|
|
1299
|
+
${i}
|
|
1300
|
+
<footer>${Yr(11)} generated by saffron v${B(n)}</footer>
|
|
1301
|
+
</div>
|
|
1302
|
+
<script>
|
|
1303
|
+
if (typeof window.saffronAct === "function") document.body.classList.add("linked");
|
|
1304
|
+
document.addEventListener("click", function (e) {
|
|
1305
|
+
var el = e.target.closest && e.target.closest("[data-act]");
|
|
1306
|
+
if (el && typeof window.saffronAct === "function") window.saffronAct(el.getAttribute("data-act"), el.getAttribute("data-f") || undefined, el.getAttribute("data-s") || undefined, el.getAttribute("data-b") || undefined);
|
|
1307
|
+
});
|
|
1308
|
+
</script>
|
|
1309
|
+
</body>
|
|
1310
|
+
</html>
|
|
1311
|
+
`}var cb=["github","azure"],Ho={github:"GitHub Actions",azure:"Azure Pipelines"};function sp(e,t){let n={full:"results",summary:"summary only",expired:"results expired",none:"no results uploaded",running:"still running"}[e];if(!t)return n;let r=t/1024**2;return`${n}, ${r<1?"under 1":Math.round(r)} MB`}function kr(e){if(e.startsWith("@")||/[\x00-\x1f\x7f]/.test(e))throw new H(`${JSON.stringify(e)} is not a branch name Saffron passes on`);return e}function lb(e){let t=e.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\*)$/,"$1$1");return t=`"${t}"`,t=t.replace(/[()%!^"<>&|;, ]/g,"^$&"),t.replace(/[()%!^"<>&|;, ]/g,"^$&")}function _e(e,t,n,r,s){let o=process.platform==="win32"&&e==="az",i=o?rp("az.cmd",t.map(lb),{cwd:n,env:r,input:s,encoding:"utf8",shell:!0,windowsVerbatimArguments:!0,timeout:6e5,maxBuffer:64*1024*1024}):rp(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 gs=e=>`${e.stderr}
|
|
1312
|
+
${e.stdout}`,ec=(e,t)=>gs(e).split(`
|
|
1313
|
+
`).map(n=>n.trim()).find(n=>n&&!/^WARNING:/.test(n))??t;function Rr(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(gs(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(gs(e))?{kind:"not-a-repository",message:ec(e,"not a GitHub repository")}:{kind:"failed",message:ec(e,`gh exited with ${e.status}`)}}function Gn(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=gs(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:ec(e,`az exited with ${e.status}`)}}function rc(e,t,n){let r=n??t.ci?.provider;if(r!==void 0){if(!cb.includes(r))throw new H(`unknown CI provider "${r}": use "github" or "azure"`);return r}return go(e).some(s=>s.startsWith("dev.azure.com/"))?"azure":"github"}var ms=e=>[...e.ci?.organization?["--organization",e.ci.organization]:[],...e.ci?.project?["--project",e.ci.project]:[]];function db(e,t){let n=_e("git",["rev-parse","--abbrev-ref","HEAD"],e,t),r=n.status===0?n.stdout.trim():"";return r&&r!=="HEAD"?r:void 0}function fb(e){let t=new Map;for(let[n,r]of Object.entries(on(e))){try{if(mt(ae.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 ap(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 re=e=>typeof e=="string"&&e?e:void 0,op=e=>re(e)?.replace(/^refs\/(heads|tags)\//,""),ip="databaseId,number,attempt,displayTitle,workflowName,status,conclusion,event,headBranch,headSha,createdAt,startedAt,url";function ub(e){let t=e.status==="completed"?"completed":e.status==="in_progress"?"in_progress":"queued";return{id:String(e.databaseId),name:re(e.workflowName)??"workflow",number:String(e.number??""),title:re(e.displayTitle),status:t,conclusion:t==="completed"?re(e.conclusion):void 0,event:re(e.event),branch:re(e.headBranch),commit:re(e.headSha),createdAt:re(e.createdAt),url:re(e.url),attempt:typeof e.attempt=="number"?e.attempt:void 0}}var pb={completed:"completed",inProgress:"in_progress",cancelling:"in_progress"},gb={succeeded:"success",partiallySucceeded:"partial",failed:"failure",canceled:"cancelled"},hb={individualCI:"push",batchedCI:"push",pullRequest:"pull_request",schedule:"schedule",manual:"manual"};function cp(e){let t=e.triggerInfo??{};return op(t["pr.sourceBranch"])??op(e.sourceBranch)}function lp(e){let t=e.triggerInfo??{},n=pb[String(e.status)]??"queued",r=re(e.result);return{id:String(e.id),name:re(e.definition?.name)??"pipeline",number:String(e.buildNumber??e.id),status:n,conclusion:n==="completed"&&r?gb[r]??r:void 0,event:re(e.reason)?hb[String(e.reason)]??String(e.reason):void 0,branch:cp(e),commit:re(t["pr.sourceSha"])??re(e.sourceVersion),createdAt:re(e.queueTime),url:re((e._links??{}).web?.href)}}function zo(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function sc(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>!!n&&typeof n=="object"):void 0}catch{return}}function mb(e){return new Set(e.map(t=>t.startsWith("dev.azure.com/")?t.slice(t.lastIndexOf("/_git/")+6):t.slice(t.indexOf("/")+1)))}function wb(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=_e("az",["pipelines","runs","list","--top",String(a),...r,"--output","json",...ms(t)],e,n);if(c.missing||c.status!==0)return Gn(c);let l=sc(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 dp(e,t,n={}){let r=n.env??process.env,s=rc(e,t,n.provider),o=n.branch??db(e,r),i=o===void 0?void 0:kr(o),a=n.limit??20,c,l=new Map;if(s==="github"){let g=m=>_e("gh",["run","list","--limit",String(a),"--json",m,...i?["--branch",i]:[]],e,r),f=g(ip);if(!f.missing&&f.status!==0&&/startedAt/.test(`${f.stderr??""}${f.stdout??""}`)&&(f=g(ip.replace(",startedAt",""))),f.missing||f.status!==0)return{provider:s,branch:i,runs:[],problem:Rr(f)};let p=sc(f.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(ub);for(let m of p)l.set(String(m.databaseId),Date.parse(re(m.startedAt)??""))}else{let g=mb(go(e)),f=w=>{let b=re(w.repository?.name)?.toLowerCase();return g.size===0||!b||g.has(b)},p=w=>f(w)&&(!i||cp(w)===i),m=i?[["--branch",`refs/heads/${i}`],["--branch",`refs/tags/${i}`],["--reason","pullRequest"]]:[[]],h=new Map;for(let w of m){let b=wb(e,t,r,w,p,a);if(!Array.isArray(b))return{provider:s,branch:i,runs:[],problem:b};for(let y of b)h.set(String(y.id),y)}c=[...h.values()].sort((w,b)=>(Date.parse(re(b.queueTime)??"")||0)-(Date.parse(re(w.queueTime)??"")||0)).slice(0,a).map(lp)}let d=fb(e),u=s==="github"?yb(e,r,c,l):new Map;return{provider:s,branch:i,runs:c.map(g=>{let f=u.get(g.id);return{...g,pending:d.get(`${s}:${g.id}`)??0,...f?{results:f}:{}}})}}function yb(e,t,n,r){let s=new Map;for(let d of n)d.status!=="completed"&&s.set(d.id,{kind:"running",label:sp("running")});let o=n.filter(d=>d.status==="completed");if(o.length===0)return s;let i=Math.min(...o.map(d=>Date.parse(d.createdAt??"")||0)),a=new Map,c=!1;for(let d=1;d<=5&&!c;d++){let u=_e("gh",["api",`repos/{owner}/{repo}/actions/artifacts?per_page=100&page=${d}`],e,t),g=u.missing||u.status!==0?void 0:zo(u.stdout)?.artifacts;if(!Array.isArray(g))break;for(let f of g.filter(p=>!!p&&typeof p=="object")){let p=String((f.workflow_run??{}).id??"");p&&a.set(p,[...a.get(p)??[],f]);let m=Date.parse(re(f.created_at)??"");!Number.isNaN(m)&&m<i&&(c=!0)}g.length<100&&(c=!0)}let l=d=>d.reduce((u,g)=>u+(Number(g.size_in_bytes)||0),0);for(let d of o){let u=bb(a.get(d.id)??[],(d.attempt??1)>1?r.get(d.id):void 0),g=w=>u.filter(b=>typeof b.name=="string"&&w.test(b.name)),f=g(up),p=g(nc),m=w=>w.filter(b=>b.expired!==!0),h=(w,b)=>s.set(d.id,{kind:w,...b!==void 0?{sizeBytes:b}:{},label:sp(w,b)});m(f).length>0?h("full",l(m(f))):m(p).length>0?h("summary",l(m(p))):f.length+p.length>0?h("expired"):c&&h("none")}return s}function bb(e,t){if(t===void 0||Number.isNaN(t))return e;let n=o=>String(o.name).replace(/^saffron-(bundle|summary)/,""),r=o=>Date.parse(re(o.created_at)??"")>=t,s=new Set(e.filter(r).map(n));return e.filter(o=>r(o)||!s.has(n(o)))}var tc=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 fp(e,t,n,r,s,o){let i,a;if(n==="github"){let c=_e("gh",["api",`repos/{owner}/{repo}/actions/runs/${r}`],e,s);if(c.missing||c.status!==0)throw new H(Rr(c).message,Rr(c).kind);let l=zo(c.stdout),d=re(l?.repository?.full_name);if(!l||String(l.id)!==r||!d)throw new H(`gh answered with something other than run ${r}`);let u=re(l.head_repository?.full_name);u?.toLowerCase()!==d.toLowerCase()&&(i={event:re(l.event),from:u});let g=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:re(l.name),branch:re(l.head_branch),commit:re(l.head_sha),url:re(l.html_url),status:g,conclusion:g==="completed"?re(l.conclusion):void 0,createdAt:re(l.created_at)}}else{let c=_e("az",["pipelines","runs","show","--id",r,"--output","json",...ms(t)],e,s);if(c.missing||c.status!==0)throw new H(Gn(c).message,Gn(c).kind);let l=zo(c.stdout);if(!l||String(l.id)!==r)throw new H(`az answered with something other than run ${r}`);let d=lp(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 H(`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 up=/^saffron-bundle[\w.-]*$/,nc=/^saffron-summary[\w.-]*$/;function pp(e,t,n,r,s){let o;if(n==="github"){o=[];for(let i=1;o;i++){let a=_e("gh",["api",`repos/{owner}/{repo}/actions/runs/${r}/artifacts?per_page=100&page=${i}`],e,s);if(a.missing||a.status!==0)throw new H(Rr(a).message,Rr(a).kind);let c=zo(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=_e("az",["pipelines","runs","artifact","list","--run-id",r,"--output","json",...ms(t)],e,s);if(i.missing||i.status!==0)throw new H(Gn(i).message,Gn(i).kind);o=sc(i.stdout)}if(!o)throw new H(`${n==="github"?"gh":"az"} answered with something other than a list of artifacts`);return o.filter(i=>typeof i.name=="string"&&(up.test(i.name)||nc.test(i.name))).map(i=>({name:i.name,sizeBytes:Number(i.size_in_bytes??((i.resource??{}).properties??{}).artifactsize)||0,expired:i.expired===!0,summary:nc.test(i.name)}))}function gp(e,t,n,r,s,o,i){if(i.length===0)throw new H(tc(r));for(let a of i){let c=n==="github"?_e("gh",["run","download",r,"-n",a,"--dir",ae.join(s,a)],e,o):_e("az",["pipelines","runs","artifact","download","--run-id",r,"--artifact-name",a,"--path",ae.join(s,a),...ms(t)],e,o);if(c.missing||c.status!==0)throw n==="github"&&/no (valid )?artifact/i.test(gs(c))?new H(tc(r)):new H(`cannot download ${a}: ${(n==="github"?Rr(c):Gn(c)).message}`)}}function hp(e,t,n,r={}){mp(n);let s=r.env??process.env,o=rc(e,t,r.provider),i=fp(e,t,o,n,s,r.allowFork===!0),a=wp(e,o,n,i.attempt);if(i.status==="completed"&&be.existsSync(a))return{provider:o,dir:ae.join(a,"bundles"),remove:()=>{}};let c=pp(e,t,o,n,s).filter(u=>!u.expired).map(u=>u.name);if(c.length===0)throw new H(tc(n));let{dir:l,remove:d}=fa(e);try{return gp(e,t,o,n,l,s,c),{provider:o,dir:l,remove:d}}catch(u){throw d(),u}}function mp(e){if(!/^\d+$/.test(e))throw new H(`--run takes the run's id, a number as saffron runs lists it, not "${e}"`)}var oc=e=>ae.join(e,".saffron","ci"),wp=(e,t,n,r)=>ae.join(oc(e),`${t}-${n}`,`attempt-${r}`),vb=10,xb=1024**3;function Sb(e){let t=0;for(let n of be.readdirSync(e,{recursive:!0})){let r=be.lstatSync(ae.join(e,String(n)),{throwIfNoEntry:!1});r?.isFile()&&(t+=r.size)}return t}function $b(e,t){let n=oc(e),r=be.readdirSync(n,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>ae.join(n,i.name)).map(i=>({run:i,mtime:be.statSync(i).mtimeMs,bytes:Sb(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>vb||o+i.bytes>xb)){be.rmSync(i.run,{recursive:!0,force:!0});continue}s++,o+=i.bytes}}var hs=class extends H{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 ic(e,t,n,r={}){mp(n);let s=r.env??process.env,o=rc(e,t,r.provider),i=fp(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=pp(e,t,o,n,s),c=a.filter(w=>!w.expired),l=c.map(({name:w,sizeBytes:b})=>({name:w,sizeBytes:b})),d=wp(e,o,n,i.attempt),u=new Date;if(be.existsSync(d))return be.utimesSync(ae.dirname(d),u,u),{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 g=c.reduce((w,b)=>w+b.sizeBytes,0);if(r.maxDownloadBytes!==void 0&&g>r.maxDownloadBytes)throw new hs(g,r.maxDownloadBytes);let f=oc(e);be.mkdirSync(f,{recursive:!0});let p=ae.join(f,".gitignore");be.existsSync(p)||be.writeFileSync(p,`*
|
|
1314
|
+
`),be.mkdirSync(ae.dirname(d),{recursive:!0});let m=be.mkdtempSync(`${d}.partial-`);try{gp(e,t,o,n,ae.join(m,"bundles"),s,c.map(w=>w.name));try{be.renameSync(m,d)}catch(w){if(!be.existsSync(d))throw w;return be.utimesSync(ae.dirname(d),u,u),{run:i,folder:d,cached:!0,artifacts:l}}}finally{be.rmSync(m,{recursive:!0,force:!0})}let h=Date.now()-1440*60*1e3;for(let w of be.readdirSync(ae.dirname(d))){let b=ae.join(ae.dirname(d),w),y=/^attempt-(\d+)$/.exec(w),S=/^attempt-\d+\.partial$/.test(w)||/^attempt-\d+\.partial-/.test(w)&&(be.statSync(b,{throwIfNoEntry:!1})?.mtimeMs??1/0)<h;(y&&Number(y[1])<i.attempt||S)&&be.rmSync(b,{recursive:!0,force:!0})}return be.utimesSync(ae.dirname(d),u,u),$b(e,ae.dirname(d)),{run:i,folder:d,cached:!1,artifacts:l}}async function ac(e,t,n){let{run:r,folder:s}=t;return nf(e,s,[ae.join(s,"bundles")],n,{run:`${r.provider}:${r.id}`,describe:o=>`${Ho[r.provider]} run ${r.id} (${ae.basename(ae.dirname(o))})`})}var kb=e=>e?.split(`
|
|
1315
|
+
`).map(t=>t.trim()).find(Boolean);async function yp(e,t,n,r,s={}){let o=ic(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 ac(e,{...o,folder:i},n),c=f=>Ae(e,ae.join(i,f)),l={run:o.run,bundle:{folder:Ae(e,i),cached:o.cached===!0,artifacts:o.artifacts,...a.summaryOnly?{summaryOnly:!0}:{}},warnings:a.warnings},{report:d}=a;if(d){let{green:f,yellow:p,red:m,aiCalls:h,costUsd:w}=d.totals;l.totals={green:f,yellow:p,red:m,aiCalls:h,costUsd:w},d.browsers?.length&&(l.browsers=d.browsers),l.scenarios=d.scenarios.map(b=>{let y=(b.evidence??[]).filter(k=>k.kind==="trace"?ht(ae.join(i,".saffron","artifacts"),ae.join(i,k.file)):mn(i,k)!==void 0),S=y.filter(k=>k.kind!=="trace"),x=S.find(k=>k.kind==="failure")??S.find(k=>k.kind==="before-heal")??S[0],C=y.filter(k=>k.kind==="trace"),$=C.find(k=>!k.proof)??C[0];return{feature:b.feature,scenario:Mn(b),displayName:b.scenario,tags:b.tags,status:b.status,durationMs:b.durationMs,verified:b.verified,failingStep:b.steps.find(k=>k.status==="failed")?.gherkin,error:kb(b.error),narrative:b.narrative,screenshot:x&&c(x.file),trace:$&&c($.file),...b.browser?{browser:b.browser}:{}}}),Ne(ae.join(i,"report.json"),`${JSON.stringify(d,null,2)}
|
|
1316
|
+
`),Ne(ae.join(i,"report.html"),vn(d,i)),l.reportHtml=c("report.html")}else l.scenarios=[];l.proposals=a.proposals,Ne(ae.join(i,"panel.html"),Uo(l,e,Xe())),l.panelHtml=c("panel.html");let{warnings:u,...g}=l;return{results:{...g,warnings:u},report:d}}function bp(e,t,n,r){let s=_e("az",["repos","pr","create","--draft","true","--source-branch",`refs/heads/${kr(n.branch)}`,"--target-branch",`refs/heads/${kr(n.base)}`,"--title",n.title,"--description",`@${n.bodyFile}`,"--output","json",...ms(t)],e,r);if(s.missing||s.status!==0)return{problem:`az repos pr create failed: ${Gn(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 xp(e,t,n){if(e.missing)throw new H(`${n}: ${t} is not installed here`);if(e.timedOut)throw new H(`${n}: ${t} did not finish within 10 minutes`);if(e.status!==0)throw new H(`${n}: ${(e.stderr||e.stdout||`exit ${e.status}`).split(`
|
|
1317
|
+
`).slice(-3).join(" ")}`);return e.stdout}function Rb(e,t){let n=i=>_e("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 qo=(e,t)=>`${e} ${t}${e===1?"":"s"}`,ws=e=>`\`${e.replaceAll("`","'")}\``,cc=e=>{let t=e.startsWith("-")?`./${e}`:e;return/^[\w./-]+$/.test(t)?t:`'${t.replaceAll("'","'\\''")}'`};function lc(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}
|
|
1208
1318
|
${e}
|
|
1209
|
-
${r}`}var
|
|
1210
|
-
`),"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."],
|
|
1211
|
-
`).length;for(let[
|
|
1212
|
-
`)
|
|
1213
|
-
`);if(
|
|
1319
|
+
${r}`}var $p={github:6e4,azure:3800};function Tb(e,t,n,r="",s=$p.github){let{manifest:o,proposals:i}=t,a=o.run?o.url&&/^https?:\/\//i.test(o.url)?`[run ${o.run}](${o.url})`:`run ${ws(o.run)}`:"a run",c=o.headCommit??o.commit,l=[o.branch&&`on ${ws(o.branch)}`,c&&`at ${ws(c.slice(0,7))}`].filter(Boolean).join(" "),d=[`Saffron filed ${qo(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):","",lc([`git fetch origin ${cc(n)} && git switch ${cc(n)}`,...r?[`cd ${cc(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(`
|
|
1320
|
+
`),"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."],u=d.join(`
|
|
1321
|
+
`).length;for(let[g,{proposal:f}]of i.entries()){let{feature:p,scenario:m}=f.cache,{mode:h,verified:w,proofError:b,narrative:y,adaptations:S}=f.meta,x=w===!0?"**verified \u2713**: a zero-AI proof replay passed":w===!1?"**UNVERIFIED \u2717**: its proof replay failed":"not verified: proof replays were off",C=[y,...S.map(R=>`\u26A0 ${R}`),...w===!1&&b?[`Proof replay: ${b}`]:[]].filter(Boolean).join(`
|
|
1322
|
+
`),$=Ys(bn(jt(fe(e,p,m)),f.cache,f.meta.featureEdits)),k=["",`### ${ws(p)} \u203A ${ws(m)}`,"",`${h==="heal"?"Heal":"First recording"}, ${x}`,"",...C?[lc(C,"text"),""]:[],lc($,"diff")].join(`
|
|
1323
|
+
`);if(u+k.length>s){d.push("",`\u2026and ${qo(i.length-g,"more proposal")}: run \`saffron diff\` on the branch to see ${i.length-g===1?"it":"them"}.`);break}d.push(k),u+=k.length+1}return`${d.join(`
|
|
1214
1324
|
`)}
|
|
1215
|
-
`}var
|
|
1216
|
-
`)[0]:String(
|
|
1217
|
-
`)}function
|
|
1218
|
-
`).slice(-2).join(" ")}`,failed:!0}:{...
|
|
1219
|
-
`).pop()}}import
|
|
1220
|
-
`)}function
|
|
1325
|
+
`}var dc=e=>e.split(/[\\/]/).join("/");function Eb(e,t,n,r,s,o){let i=xt.mkdtempSync(me.join(Sp.tmpdir(),"saffron-head-")),a=p=>{let m=vp("git",["show",`${n}:${r}${dc(p)}`],{cwd:e,env:s,timeout:6e5,maxBuffer:67108864});return m.status===0?m.stdout:void 0},c=p=>{let m=me.relative(e,me.resolve(e,p));return!m.startsWith("..")&&!me.isAbsolute(m)?dc(m):void 0},l=c(o.features??"features"),d=c(o.dataDir??"data"),u=vp("git",["ls-tree","-r","-z","--full-tree","--name-only",n,"--",...[l,d].flatMap(p=>p===void 0?[]:[`${r}${p}`||"."])],{cwd:e,env:s,encoding:"utf8",timeout:6e5,maxBuffer:64*1024*1024}),g=Ve(),f=[];try{for(let m of(l!==void 0||d!==void 0)&&u.status===0?u.stdout.split("\0").filter(Boolean):[]){let h=m.slice(r.length);if(!(d!==void 0&&(d===""||h.startsWith(`${d}/`)))&&!h.endsWith(".saffron"))continue;let b=a(h);b!==void 0&&(xt.mkdirSync(me.dirname(me.join(i,h)),{recursive:!0}),xt.writeFileSync(me.join(i,h),b))}d!==void 0&&Ot(i,d,g.env);let p;try{p=Ye(i,o,[])}catch(m){let h=`cannot be checked: the StepSets at ${n.slice(0,7)} do not parse: ${m instanceof Error?m.message.split(`
|
|
1326
|
+
`)[0]:String(m)}`;return t.proposals.map(({file:w})=>({file:w,reason:h}))}for(let{file:m,proposal:h}of t.proposals){let{feature:w,scenario:b}=h.cache,y=a(w);if(!y){f.push({file:m,reason:`is for ${w}, which is not in ${n.slice(0,7)}`});continue}xt.mkdirSync(me.dirname(me.join(i,w)),{recursive:!0}),xt.writeFileSync(me.join(i,w),y);let S=dc(me.relative(e,fe(e,w,b))),x=a(S);xt.rmSync(me.join(i,S),{force:!0}),x&&(xt.mkdirSync(me.dirname(me.join(i,S)),{recursive:!0}),xt.writeFileSync(me.join(i,S),x));let C;try{C=dt(i,h,p)}catch($){C=`cannot be checked: ${$ instanceof Error?$.message:String($)}`}C&&f.push({file:m,reason:`does not fit ${n.slice(0,7)}: ${C}`})}}finally{d!==void 0&&Ot(e,g.dir,g.env),xt.rmSync(i,{recursive:!0,force:!0})}return f}function Ab(e){let{manifest:t,proposals:n}=e;return[`Saffron: ${qo(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(`
|
|
1327
|
+
`)}function ys(e,t){if(t!==void 0&&/[$`;|&<>()\s'"\\]/.test(t))throw new H(`${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 kp(e,t,n,r={}){let s=r.env??process.env,o=(C,$,k={})=>xp(_e("git",$,e,k.env??s,k.input),"git",C),{manifest:i}=t;if(t.proposals.length===0)throw new H("there are no pending proposals to push");let a=r.base??i.branch;if(!a)throw new H("cannot tell which branch the pull request is for: pass --base <branch>");if(kr(a),kr(n),ys("--branch",n),ys("--base",r.base),n===a)throw new H(`--branch ${n} is the branch the proposals are for: name a new one, e.g. saffron/heal-<run id>`);if(n.startsWith("-"))throw new H(`${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 H("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&&!la(e,l).includes(c)&&_e("git",["merge-base","--is-ancestor",c,l],e,s).status!==0)throw new H(`${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`);_e("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=_e("git",["ls-remote","--exit-code","--heads","origin",`refs/heads/${n}`],e,s);if(d.status===0)throw new H(`branch ${n} already exists on origin: give each run its own, e.g. saffron/heal-<run id>-<attempt>`);d.status!==2&&xp(d,"git","cannot reach origin");let u=o("not a git checkout",["rev-parse","--show-prefix"]),g=Eb(e,t,c,u,s,r.config??{}),f={...t,proposals:t.proposals.filter(C=>!g.some($=>$.file===C.file))};if(f.proposals.length===0)throw new H(`no proposal fits ${c.slice(0,7)}, the commit the branch would start on: ${g.map(C=>`${me.relative(e,C.file)} ${C.reason}`).join("; ")}`);let p=xt.mkdtempSync(me.join(Sp.tmpdir(),"saffron-index-")),m={...s,GIT_INDEX_FILE:me.join(p,"index")},h;try{o("cannot read the tested commit",["read-tree",c],{env:m});for(let{file:$,bytes:k}of f.proposals){let R=o("cannot store a proposal",["hash-object","-w","--stdin"],{input:k}),_=`${u}${me.relative(e,$).split(me.sep).join("/")}`;o("cannot stage a proposal",["update-index","--add","--cacheinfo",`100644,${R},${_}`],{env:m})}let C=o("cannot write the tree",["write-tree"],{env:m});h=o("cannot commit the proposals",["commit-tree",C,"-p",c,"-m",Ab(f)],{env:Rb(e,s)})}finally{xt.rmSync(p,{recursive:!0,force:!0})}o(`cannot push ${n} to origin`,["push","--quiet","origin",`${h}:refs/heads/${n}`]);let w=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,b=me.join(me.dirname(f.file),"saffron-pull-request.md");xt.writeFileSync(b,Tb(e,f,n,u,$p[w??"github"]));let y={branch:n,base:a,commit:h,parent:c,bodyFile:b,leftOut:g};if(!w)return{...y,noPullRequest:`${i.repository??"this repository"} is not on GitHub or Azure DevOps`};let S=`Saffron: ${qo(f.proposals.length,"proposal")} to review for ${a}`;if(w==="azure"){let C=bp(e,r.config??{},{branch:n,base:a,title:S,bodyFile:b},s);return C.problem?{...y,noPullRequest:C.problem,failed:!0}:C.url?{...y,pullRequest:C.url}:{...y,noPullRequest:"az created it but did not say where",failed:!0}}let x=_e("gh",["pr","create","--draft","--base",a,"--head",n,"--title",S,"--body-file",b],e,s);return x.missing?{...y,noPullRequest:"the gh CLI is not installed here",failed:!0}:x.status!==0?{...y,noPullRequest:`gh pr create failed: ${(x.stderr||x.stdout).split(`
|
|
1328
|
+
`).slice(-2).join(" ")}`,failed:!0}:{...y,pullRequest:x.stdout.split(`
|
|
1329
|
+
`).pop()}}import K from"node:fs";import te from"node:path";var bs={claude:".claude/skills",agents:".agents/skills",copilot:".github/skills",cursor:".cursor/skills"},Cb=["claude","agents"],Ep="<!-- saffron:start -->",uc="<!-- saffron:end -->";function _b(){return[Ep,"## Saffron end-to-end tests","","UI tests are plain-language `.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.","","- Exact step text is the recording's identity: run `npx saffron steps` and"," reuse recorded wordings instead of inventing synonyms.","- `Then` steps are never healed: write them as the verdict, last.","- Never hand-edit `.saffron/cache/` or `.saffron/proposals/`; change the"," scenario text and re-run. Review with `npx saffron accept` / `reject`.","- Secrets only as `{env:VAR}` tokens, never in files or `data/`.","","When asked to create, translate, or edit Saffron scenarios in `.saffron`","or `.feature` files, load the `saffron` skill and follow its authoring","workflow: inspect the relevant UI, reuse recorded vocabulary, name","captures explicitly, and use observable waits and final assertions.","A working test requires reviewing its verified proposal and passing","the affected scenarios with `--no-agent`. For draft-only requests or","unavailable execution, report the validation still needed.","","This authoring workflow does not apply to ordinary application changes","or requests only to run tests, inspect reports, review proposals, or","configure Saffron. Never hand-edit generated caches or proposals to","make a test pass.",uc,""].join(`
|
|
1330
|
+
`)}function Rp(e,t){if(!K.existsSync(e))return K.writeFileSync(e,t),"created";let n=K.readFileSync(e,"utf8"),r=n.indexOf(Ep),s=n.indexOf(uc);if(r!==-1&&s!==-1&&s>r){let i=n.slice(0,r)+t.trimEnd()+n.slice(s+uc.length);return i===n?"unchanged":(K.writeFileSync(e,i),"updated")}let o=n.endsWith(`
|
|
1221
1331
|
`)?`
|
|
1222
1332
|
`:`
|
|
1223
1333
|
|
|
1224
|
-
`;return
|
|
1225
|
-
`),s?"updated":"created")}function
|
|
1226
|
-
`),n.scaffolded.push("saffron.config.json"));let
|
|
1227
|
-
`).some(
|
|
1334
|
+
`;return K.writeFileSync(e,n+o+t),"updated"}var fc={command:"npx",args:["saffron","mcp"]},Pb={claude:{file:".mcp.json",key:"mcpServers",entry:fc},cursor:{file:".cursor/mcp.json",key:"mcpServers",entry:fc},copilot:{file:".vscode/mcp.json",key:"servers",entry:{type:"stdio",...fc}}},Tp={agents:"codex mcp add saffron -- npx saffron mcp (Codex; other hosts: see their MCP settings)"};function Ob(e,t){let n=te.join(e,t.file),r={},s=K.existsSync(n);if(s)try{r=JSON.parse(K.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,K.mkdirSync(te.dirname(n),{recursive:!0}),K.writeFileSync(n,JSON.stringify(r,null,2)+`
|
|
1335
|
+
`),s?"updated":"created")}function Ap(e,t){K.mkdirSync(t,{recursive:!0});for(let n of K.readdirSync(e,{withFileTypes:!0})){let r=te.join(e,n.name),s=te.join(t,n.name);n.isDirectory()?Ap(r,s):K.copyFileSync(r,s)}}function Cp(e){let t=te.join(e.packageRoot,"skills","saffron");if(!K.existsSync(te.join(t,"SKILL.md")))throw new Error(`bundled skill not found at ${t}`);let n={skillDirs:[],instructionFiles:[],scaffolded:[],mcpFiles:[],mcpHints:[]},r=e.targets??Cb;for(let s of r){let o=te.join(e.projectRoot,bs[s],"saffron");K.existsSync(o)&&K.rmSync(o,{recursive:!0,force:!0}),Ap(t,o),n.skillDirs.push(te.relative(e.projectRoot,o))}if(e.mcp!==!1)for(let s of r){let o=Pb[s];o?n.mcpFiles.push({file:o.file,outcome:Ob(e.projectRoot,o)}):Tp[s]&&n.mcpHints.push(Tp[s])}if(e.instructions!==!1){let s=_b(),o=te.join(e.projectRoot,"AGENTS.md");n.instructionFiles.push({file:"AGENTS.md",outcome:Rp(o,s)});let i=te.join(e.projectRoot,"CLAUDE.md");K.existsSync(i)&&n.instructionFiles.push({file:"CLAUDE.md",outcome:Rp(i,s)})}if(e.examples){n.examples=Ib(e.projectRoot,e.packageRoot,Vo(e.projectRoot));for(let s of n.examples.files)n.scaffolded.push(s)}if(e.scaffold!==!1){let s=te.join(e.projectRoot,"saffron.config.json");K.existsSync(s)||(K.writeFileSync(s,JSON.stringify({baseURL:"http://localhost:3000",features:"features"},null,2)+`
|
|
1336
|
+
`),n.scaffolded.push("saffron.config.json"));let{features:o}=Vo(e.projectRoot),i=te.resolve(e.projectRoot,o);!K.existsSync(i)&&_p(e.projectRoot,i)&&(K.mkdirSync(i,{recursive:!0}),n.scaffolded.push(`${o}/`));let a=te.join(e.projectRoot,".gitignore"),c=[".saffron/reports/",".saffron/artifacts/",".saffron/ci/",...e.examples?[".env"]:[]],l=K.existsSync(a)?K.readFileSync(a,"utf8"):"",d=[];for(let u of c)l.split(`
|
|
1337
|
+
`).some(g=>g.trim()===u)||(l+=(l&&!l.endsWith(`
|
|
1228
1338
|
`)?`
|
|
1229
|
-
`:"")+
|
|
1230
|
-
`,
|
|
1231
|
-
`)}
|
|
1232
|
-
`))}function Wf(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 ${pn[n]??n} models; this ${pn[t]} run uses its default models (--model and --heal-model pick others).`),{})}function fa(e,t){let n=e??t??"claude";return Kd(n)||(console.error(`invalid provider "${n}": use ${Fi.map(r=>`"${r}"`).join(", ")}`),process.exit(2)),n}async function qw(e){let t=Uw.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 Ws(e){console.error(`saffron: ${e.message}`),process.exit(2)}function da(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e4?`${(e/1e3).toFixed(1)}k`:e.toLocaleString()}var Jw={green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m"},Ww="\x1B[0m",K=new zw().name("saffron").description("AI-fallback test runner for end-to-end tests written in plain language: zero-token cached replay, runtime AI healing.").version(nt()).option("-p, --project-root <dir>","project root",process.cwd());K.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"',Bl).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. A list ("chromium,firefox,webkit") runs the suite in each, into one report').option("--device <name>",'run under a Playwright device profile, e.g. "iPhone 15" or "Pixel 7"').option("--viewport <size>","viewport as WIDTHxHEIGHT, e.g. 1280x720 (over the device's)").option("--heal-model <model>","cheaper model for heal sessions").option("--workers <n>","parallel replay workers").option("--agent-workers <n>","agent sessions (recording, healing) that may run at once, each in a browser of its own (default 1)").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=U.resolve(K.opts().projectRoot),r=pe(n);t.env&&at(n,r.dataDir,t.env);let s=t.baseUrl??r.baseURL,o=Dl(e),i=e.length===0?la(n,r.features?[r.features]:[]):o.plain.length>0?la(n,o.plain):[],a=[...o.picks.keys()].map(I=>U.resolve(n,I)),c=[...o.plain,...o.picks.keys()].find(I=>!ue.existsSync(U.resolve(n,I)));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(I=>{let B=U.relative(n,I);return B.split(/[\\/]/)[0]===".."||U.isAbsolute(B)});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=fa(t.provider,r.provider),u=Wf(r,p);t.agent!==!1&&Hw(p);let f;try{let I=Le(n,r,l);f=l.flatMap(B=>Be(B,n,I))}catch(I){throw I instanceof $e&&Ws(I),I}let g=f;if(o.picks.size>0)try{f=Hl(f,n,o.picks,new Set(i))}catch(I){if(!(I instanceof fn))throw I;console.error(I.message),process.exit(2)}let w;try{w=Fl(t.filter)}catch(I){if(!(I instanceof hr))throw I;console.error(`${I.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 I=Z=>{try{let me=Pe(se(n,Z.featurePath,Z.name));return!!me&&sr(Z,me)}catch{return!1}},B=f.filter(Z=>t.rerecord||!I(Z)),q=Ul(B,g).filter(Z=>!f.includes(Z));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 R=(()=>{let I=t.browser??r.browser??"chromium",B=(Array.isArray(I)?I:String(I).split(",")).map(Z=>String(Z).trim()).filter(Boolean),q=B.find(Z=>!wd(Z));return(q!==void 0||B.length===0)&&(console.error(`invalid --browser "${q??""}": use ${Ai.map(Z=>`"${Z}"`).join(", ")}, or a list of them`),process.exit(2)),[...new Set(B)].sort((Z,me)=>+!Bn(Z)-+!Bn(me))})(),$=R.length>1,m;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 I=al(String(t.shardBy??r.shardBy??"scenario")),B=cl(f,{...il(String(t.shard)),by:I});if(f=B.scenarios,$)throw new Error("saffron: a browser matrix and --shard do not mix: give each shard job one --browser (a CI matrix runs them side by side)");m={...B.info,ciRun:gs(),attempt:hs(),browser:R[0]}}catch(I){console.error(I instanceof Error?I.message:String(I)),process.exit(2)}if(console.log(`shard ${m.index}/${m.total}${m.by==="file"?" (by file)":""}: ${f.length} of ${m.suiteSize} scenario(s)`),f.length===0){let I=new Date,B=si([],I,s),q=Yo([],I,lt(n).divergent.length,s);console.log(`report: ${di(n,{...B,shard:m,history:q})}`),process.exit(0)}}t.rerecord&&t.agent===!1&&(console.error("saffron: --rerecord needs the agent; drop --no-agent"),process.exit(2));{let I=f;try{let q=[...new Set([...la(n,r.features?[r.features]:[]),...l])],Z=Le(n,r,q);I=q.flatMap(me=>{try{return Be(me,n,Z)}catch{return[]}})}catch{}let B=Na(n,I);if(B.length>0){console.error("cache path collision:");for(let q of B)console.error(` ${q}`);process.exit(2)}}{let I=new Map;for(let q of f)for(let Z of Fe(q))process.env[Z]===void 0&&!I.has(Z)&&I.set(Z,q.displayName);let B=new Map;for(let q of f)for(let Z of $t(ze(q)))if(!B.has(Z))try{jr(Z)}catch(me){B.set(Z,`${me instanceof Error?me.message:String(me)} (used by "${q.displayName}")`)}if(B.size>0){for(let q of B.values())console.error(q);process.exit(2)}if(I.size>0){for(let[q,Z]of I)console.error(`missing environment variable ${q} (referenced as {env:${q}} by "${Z}")`);console.error("set the variable(s), or add them to a git-ignored .env in the project root"),process.exit(2)}}let v=[],S=[];if(t.hooks!==!1)try{v=Ji(r.setup,"setup"),S=Ji(r.teardown,"teardown")}catch(I){console.error(I instanceof Error?I.message:String(I)),process.exit(2)}let x=t.device??r.device,b=x===void 0?void 0:String(x);if(b!==void 0&&(typeof x!="string"||!_i.includes(b))){let I=_i.filter(B=>B.toLowerCase().includes(b.toLowerCase().split(" ")[0])).slice(0,8);console.error(`unknown --device "${b}". ${I.length>0?`Close: ${I.map(B=>`"${B}"`).join(", ")}`:'Use a Playwright device name, e.g. "iPhone 15", "Pixel 7" or "Desktop Chrome"'}`),process.exit(2)}let k=t.viewport??r.viewport,h=k===void 0?void 0:yd(String(k));k!==void 0&&!h&&(console.error(`invalid --viewport "${k}": use WIDTHxHEIGHT, e.g. 1280x720`),process.exit(2));let y=I=>Math.max(1,Number.parseInt(String(I??1),10)||1),A=y(t.workers??r.workers),E=y(t.agentWorkers??r.agentWorkers),P=t.agent?Yd(p,{model:t.model??u.model,maxTurns:r.maxTurns,snapshotMode:r.snapshotMode}):void 0,O=(()=>{let I=t.trace??r.trace??"off";return Ao.includes(I)||(console.error(`invalid --trace "${I}": use ${Ao.map(B=>`"${B}"`).join(", ")}`),process.exit(2)),I})(),M=(()=>{let I=t.assertionPolicy??r.assertionPolicy??"strict";return I!=="strict"&&I!=="adaptable-mid"&&(console.error(`invalid --assertion-policy "${I}": use "strict" or "adaptable-mid"`),process.exit(2)),I})(),T=I=>new $s({projectRoot:n,baseURL:s,headed:t.headed,actionTimeoutMs:r.actionTimeoutMs,pollIntervalMs:r.pollIntervalMs,screenshot:r.screenshot,trace:O,retries:r.retries,storageState:t.storageState??r.storageState,browser:I,device:b,viewport:h,artifactsPerBrowser:$,healModel:t.healModel??u.healModel,rerecord:t.rerecord===!0,verifyProposals:t.verify===!1?!1:r.verifyProposals,reuseSteps:t.reuse===!1?!1:r.reuseSteps,assertionPolicy:M,agent:P}),C=new Set,j=async I=>{let B=T(I);return C.add(B),await B.start(),B},L=async I=>{for(let B of[...I])C.delete(B),await B.stop()},_=new Date,F=[],D=new Map,H=new Map,V=async(I,B,q,Z,me)=>{let vt=$?`${B} \xB7 ${q}`:q,Xe=Date.now(),ee=await I.runScenario(Z,me),Ne=Date.now(),Ee=D.get(vt)??{worker:vt,runs:0,busyMs:0,spanMs:0,browser:B};D.set(vt,Ee),Ee.runs++,Ee.busyMs+=Ne-Xe;let St=H.get(B)??{first:Xe,last:Ne};return H.set(B,{first:Math.min(St.first,Xe),last:Math.max(St.last,Ne)}),ee.worker=vt,ee.browser=B,ee},W=I=>{let B=I.scenario,q=Jw[I.status],Z=I.usage.inputTokens+I.usage.outputTokens,me=I.usage.cacheReadTokens+I.usage.cacheCreationTokens,vt=me>0?`, ${da(me)} cache traffic`:"";console.log(`${q}${I.status.toUpperCase().padEnd(7)}${Ww}${B.displayName}${$?` [${I.browser}]`:""} (${I.source}, ${I.durationMs}ms, ${I.usage.aiCalls} AI calls, ${Z} tokens${vt})`);for(let ee of I.adaptations)console.log(` \u26A0 ${ee}`);I.status==="yellow"&&I.usage.aiCalls===0&&I.narrative&&console.log(` ${I.narrative}`),I.seededSteps&&console.log(` \u26A1 ${I.seededSteps}/${I.stepResults.length} steps seeded from existing recordings (zero AI)`);let Xe=I.stepResults.reduce((ee,Ne)=>ee+(Ne.retries??0),0);Xe&&console.log(` \u21BB ${Xe} action ${Xe===1?"retry":"retries"} absorbed before settling (retries: ${r.retries??1} per action)`),I.verified===!0?console.log(" \u2713 proposal verified by zero-AI proof replay"):I.verified===!1&&console.log(` \u2717 proposal UNVERIFIED, proof replay failed: ${I.proofError?.split(`
|
|
1233
|
-
`)[0]}`),I.error&&console.log(` ${I.error}`)},ce=new AbortController,st={cwd:n,timeoutMs:r.hookTimeoutMs??go.hookTimeoutMs,env:{SAFFRON_BASE_URL:s,SAFFRON_ENV:Me().env,SAFFRON_SHARD:m?`${m.index}/${m.total}`:void 0}},Te=[],wn,bt=()=>wn??=Wi("teardown",S,st).then(I=>{Te.push(...I)}),ot=Promise.resolve([]);v.length+S.length>0&&process.on("SIGINT",()=>{if(ce.signal.aborted){console.error("still cleaning up: teardown finishes, then Saffron exits");return}console.error(`
|
|
1234
|
-
|
|
1235
|
-
`)
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
${
|
|
1239
|
-
${
|
|
1240
|
-
|
|
1241
|
-
`)[0]
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
`)
|
|
1245
|
-
`))});
|
|
1339
|
+
`:"")+u+`
|
|
1340
|
+
`,d.push(u));d.length>0&&(K.writeFileSync(a,l),n.scaffolded.push(`.gitignore (+ ${d.join(", ")})`))}return n}function Vo(e){let t={};try{t=JSON.parse(K.readFileSync(te.join(e,"saffron.config.json"),"utf8"))}catch{}let n=(r,s)=>typeof r=="string"&&r.trim()?r.trim().replace(/(.)[\\/]+$/,"$1"):s;return{features:n(t?.features,"features"),data:n(t?.dataDir,"data")}}function _p(e,t){let n=te.relative(te.resolve(e),te.resolve(t));return n===""||n!==".."&&!n.startsWith(".."+te.sep)&&!te.isAbsolute(n)}function Ib(e,t,n={features:"features",data:"data"}){let r=te.join(t,"templates","saucedemo");if(!K.existsSync(te.join(r,"features")))return{installed:!1,files:[],reason:`bundled examples not found at ${r}`};let s=te.resolve(e,n.features),o=te.resolve(e,n.data);for(let[u,g]of[[s,n.features],[o,n.data]]){if(!_p(e,u))return{installed:!1,files:[],reason:`${g} is outside the project; examples are only installed inside it`};if(K.existsSync(u)&&!K.statSync(u).isDirectory())return{installed:!1,files:[],reason:`${g} is a file, not a folder; examples are installed into a folder`}}if(K.existsSync(s)&&K.readdirSync(s).length>0)return{installed:!1,files:[],reason:`${n.features}/ is not empty; examples are only installed into an empty features directory`};let i=[];K.mkdirSync(s,{recursive:!0});for(let u of K.readdirSync(te.join(r,"features")))K.copyFileSync(te.join(r,"features",u),te.join(s,u)),i.push(`${n.features}/${u}`);let a=te.join(r,"data");if(K.existsSync(a)){K.mkdirSync(o,{recursive:!0});for(let u of K.readdirSync(a)){let g=te.join(o,u);K.existsSync(g)||(K.copyFileSync(te.join(a,u),g),i.push(`${n.data}/${u}`))}}let c=te.join(e,"saffron.config.json"),l;K.existsSync(c)?l=jb(c,te.join(r,"saffron.config.json"),i):(K.copyFileSync(te.join(r,"saffron.config.json"),c),i.push("saffron.config.json (baseURL https://www.saucedemo.com, retries 1)"));let d=te.join(e,".env.example");return K.existsSync(d)||(K.copyFileSync(te.join(r,".env.example"),d),i.push(".env.example")),{installed:!0,files:i,...l?{note:l}:{}}}function jb(e,t,n){let r;try{r=JSON.parse(K.readFileSync(e,"utf8"))}catch{return}if(!r||typeof r!="object"||Array.isArray(r))return;let s=JSON.parse(K.readFileSync(t,"utf8")),o=s.baseURL;if(r.baseURL!==void 0)return r.baseURL===o?void 0:`the examples target ${o}, but saffron.config.json keeps your baseURL ${String(r.baseURL)}; set "baseURL": "${o}" to run them`;let i=Object.keys(s).filter(a=>a!=="features"&&!(a in r));for(let a of i)r[a]=s[a];K.writeFileSync(e,JSON.stringify(r,null,2)+`
|
|
1341
|
+
`),n.push(`saffron.config.json (+ ${i.map(a=>`${a} ${String(s[a])}`).join(", ")})`)}import Nb from"node:path";function Pp(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?Nb.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(`
|
|
1342
|
+
`)}import{spawn as Mb}from"node:child_process";function Fb(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 vs(e){let{command:t,args:n,options:r}=Fb(e),s=t.split(" ")[0],o=Mb(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 pc(e,t){let n=t.length>0?t:["features"],r=[];for(let s of n){let o=q.isAbsolute(s)?s:q.join(e,s);ke.existsSync(o)&&(ke.statSync(o).isDirectory()?r.push(...Zt(o,Yt)):Yt(o)&&r.push(o))}return r.sort()}function Db(e){let t=Ua(e);t.length!==0&&console.error([`note: the ${qn[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(`
|
|
1343
|
+
`))}function Op(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 ${qn[n]??n} models; this ${qn[t]} run uses its default models (--model and --heal-model pick others).`),{})}function hc(e,t){let n=e??t??"claude";return Pu(n)||(console.error(`invalid provider "${n}": use ${La.map(r=>`"${r}"`).join(", ")}`),process.exit(2)),n}async function Ub(e){let t=Bb.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 Jo(e){console.error(`saffron: ${e.message}`),process.exit(2)}function gc(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e4?`${(e/1e3).toFixed(1)}k`:e.toLocaleString()}var zb={green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m"},Hb="\x1B[0m",Q=new Lb().name("saffron").description("AI-fallback test runner for end-to-end tests written in plain language: zero-token cached replay, runtime AI healing.").version(Xe()).option("-p, --project-root <dir>","project root",process.cwd());Q.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"',gf).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. A list ("chromium,firefox,webkit") runs the suite in each, into one report').option("--device <name>",'run under a Playwright device profile, e.g. "iPhone 15" or "Pixel 7"').option("--viewport <size>","viewport as WIDTHxHEIGHT, e.g. 1280x720 (over the device's)").option("--heal-model <model>","cheaper model for heal sessions").option("--workers <n>","parallel replay workers").option("--agent-workers <n>","agent sessions (recording, healing) that may run at once, each in a browser of its own (default 1)").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=q.resolve(Q.opts().projectRoot),r=ye(n);t.env&&Ot(n,r.dataDir,t.env);let s=t.baseUrl??r.baseURL,o=hf(e),i=e.length===0?pc(n,r.features?[r.features]:[]):o.plain.length>0?pc(n,o.plain):[],a=[...o.picks.keys()].map(j=>q.resolve(n,j)),c=[...o.plain,...o.picks.keys()].find(j=>!ke.existsSync(q.resolve(n,j)));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(j=>{let D=q.relative(n,j);return D.split(/[\\/]/)[0]===".."||q.isAbsolute(D)});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 u=hc(t.provider,r.provider),g=Op(r,u);t.agent!==!1&&Db(u);let f;try{let j=Ye(n,r,l);f=l.flatMap(D=>Ze(D,n,j))}catch(j){throw j instanceof Ee&&Jo(j),j}let p=f;if(e.length===0){let j=new Set(p.flatMap(D=>D.steps.flatMap(W=>W.session===void 0?[]:[W.session])));for(let D of Object.keys(r.sessions??{}))D===$t?console.warn(`saffron.config.json sets up the browser session "${$t}", which takes storageState (or --storage-state) like every scenario: "sessions" is for named sessions.`):j.has(D)||console.warn(`saffron.config.json sets up the browser session "${D}", and no step names it with As "${D}". Check the spelling.`)}let m=Pc(p.flatMap(j=>j.steps.flatMap(D=>D.session===void 0?[]:[D.session])),Object.keys(r.sessions??{}),t.storageState??r.storageState);if(m&&console.warn(m),o.picks.size>0)try{f=yf(f,n,o.picks,new Set(i))}catch(j){if(!(j instanceof zn))throw j;console.error(j.message),process.exit(2)}let h;try{h=uf(t.filter)}catch(j){if(!(j instanceof ss))throw j;console.error(`${j.message}. Write tags joined with and, or, not and parentheses: "@smoke and not @wip".`),process.exit(2)}if(h&&(f=pf(f,h),f.length===0&&(console.error(`No scenarios match --filter "${h.text}" in ${l.length} feature file(s).`),process.exit(2))),t.agent!==!1){let j=ee=>{try{let xe=He(fe(n,ee.featurePath,ee.name));return!!xe&&(lr(ee,xe)||cr(ee,xe)!==void 0)}catch{return!1}},D=f.filter(ee=>t.rerecord||!j(ee)),W=mf(D,p).filter(ee=>!f.includes(ee));W.length>0&&(console.log(`${W.length} more Examples row(s) share a recording this run ${t.rerecord?"replaces":"records"}, and run to replay it`),f=[...f,...W])}let w=(()=>{let j=t.browser??r.browser??"chromium",D=(Array.isArray(j)?j:String(j).split(",")).map(ee=>String(ee).trim()).filter(Boolean),W=D.find(ee=>!Yf(ee));return(W!==void 0||D.length===0)&&(console.error(`invalid --browser "${W??""}": use ${_a.map(ee=>`"${ee}"`).join(", ")}, or a list of them`),process.exit(2)),[...new Set(D)].sort((ee,xe)=>+!wr(ee)-+!wr(xe))})(),b=w.length>1,y;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 j=Id(String(t.shardBy??r.shardBy??"scenario")),D=jd(f,{...Od(String(t.shard)),by:j});if(f=D.scenarios,b)throw new Error("saffron: a browser matrix and --shard do not mix: give each shard job one --browser (a CI matrix runs them side by side)");y={...D.info,ciRun:co(),attempt:lo(),browser:w[0]}}catch(j){console.error(j instanceof Error?j.message:String(j)),process.exit(2)}if(console.log(`shard ${y.index}/${y.total}${y.by==="file"?" (by file)":""}: ${f.length} of ${y.suiteSize} scenario(s)`),f.length===0){let j=new Date,D=Xi([],j,s),W=Gi([],j,Nt(n).divergent.length,s);console.log(`report: ${oa(n,{...D,shard:y,history:W})}`),process.exit(0)}}t.rerecord&&t.agent===!1&&(console.error("saffron: --rerecord needs the agent; drop --no-agent"),process.exit(2));{let j=f;try{let W=[...new Set([...pc(n,r.features?[r.features]:[]),...l])],ee=Ye(n,r,W);j=W.flatMap(xe=>{try{return Ze(xe,n,ee)}catch{return[]}})}catch{}let D=ol(n,j);if(D.length>0){console.error("cache path collision:");for(let W of D)console.error(` ${W}`);process.exit(2)}}{let j=new Map;for(let W of f)for(let ee of We(W))process.env[ee]===void 0&&!j.has(ee)&&j.set(ee,W.displayName);let D=new Map;for(let W of f)for(let ee of Gt(st(W)))if(!D.has(ee))try{ks(ee)}catch(xe){D.set(ee,`${xe instanceof Error?xe.message:String(xe)} (used by "${W.displayName}")`)}if(D.size>0){for(let W of D.values())console.error(W);process.exit(2)}if(j.size>0){for(let[W,ee]of j)console.error(`missing environment variable ${W} (referenced as {env:${W}} by "${ee}")`);console.error("set the variable(s), or add them to a git-ignored .env in the project root"),process.exit(2)}}let S=[],x=[];if(t.hooks!==!1)try{S=Wa(r.setup,"setup"),x=Wa(r.teardown,"teardown")}catch(j){console.error(j instanceof Error?j.message:String(j)),process.exit(2)}let C=t.device??r.device,$=C===void 0?void 0:String(C);if($!==void 0&&(typeof C!="string"||!Pa.includes($))){let j=Pa.filter(D=>D.toLowerCase().includes($.toLowerCase().split(" ")[0])).slice(0,8);console.error(`unknown --device "${$}". ${j.length>0?`Close: ${j.map(D=>`"${D}"`).join(", ")}`:'Use a Playwright device name, e.g. "iPhone 15", "Pixel 7" or "Desktop Chrome"'}`),process.exit(2)}let k=t.viewport??r.viewport,R=k===void 0?void 0:Zf(String(k));k!==void 0&&!R&&(console.error(`invalid --viewport "${k}": use WIDTHxHEIGHT, e.g. 1280x720`),process.exit(2));let _=j=>Math.max(1,Number.parseInt(String(j??1),10)||1),v=_(t.workers??r.workers),A=_(t.agentWorkers??r.agentWorkers),O=t.agent?Ou(u,{model:t.model??g.model,maxTurns:r.maxTurns,snapshotMode:r.snapshotMode}):void 0,P=(()=>{let j=t.trace??r.trace??"off";return Ci.includes(j)||(console.error(`invalid --trace "${j}": use ${Ci.map(D=>`"${D}"`).join(", ")}`),process.exit(2)),j})(),E=(()=>{let j=t.assertionPolicy??r.assertionPolicy??"strict";return j!=="strict"&&j!=="adaptable-mid"&&(console.error(`invalid --assertion-policy "${j}": use "strict" or "adaptable-mid"`),process.exit(2)),j})(),T=new Map,M=j=>new xo({filedThisRun:T,projectRoot:n,baseURL:s,headed:t.headed,actionTimeoutMs:r.actionTimeoutMs,pollIntervalMs:r.pollIntervalMs,screenshot:r.screenshot,trace:P,retries:r.retries,storageState:t.storageState??r.storageState,sessions:r.sessions,browser:j,device:$,viewport:R,artifactsPerBrowser:b,healModel:t.healModel??g.healModel,rerecord:t.rerecord===!0,verifyProposals:t.verify===!1?!1:r.verifyProposals,reuseSteps:t.reuse===!1?!1:r.reuseSteps,assertionPolicy:E,agent:O}),I=new Set,F=async j=>{let D=M(j);return I.add(D),await D.start(),D},z=async j=>{for(let D of[...j])I.delete(D),await D.stop()},N=new Date,L=[],G=new Map,U=new Map,Y=async(j,D,W,ee,xe)=>{let Vt=b?`${D} \xB7 ${W}`:W,St=Date.now(),ie=await j.runScenario(ee,xe),qe=Date.now(),Be=G.get(Vt)??{worker:Vt,runs:0,busyMs:0,spanMs:0,browser:D};G.set(Vt,Be),Be.runs++,Be.busyMs+=qe-St;let Jt=U.get(D)??{first:St,last:qe};return U.set(D,{first:Math.min(Jt.first,St),last:Math.max(Jt.last,qe)}),ie.worker=Vt,ie.browser=D,ie},V=j=>{let D=j.scenario,W=zb[j.status],ee=j.usage.inputTokens+j.usage.outputTokens,xe=j.usage.cacheReadTokens+j.usage.cacheCreationTokens,Vt=xe>0?`, ${gc(xe)} cache traffic`:"";console.log(`${W}${j.status.toUpperCase().padEnd(7)}${Hb}${D.displayName}${b?` [${j.browser}]`:""} (${j.source}, ${j.durationMs}ms, ${j.usage.aiCalls} AI calls, ${ee} tokens${Vt})`);for(let ie of j.adaptations)console.log(` \u26A0 ${ie}`);j.status==="yellow"&&j.usage.aiCalls===0&&j.narrative&&console.log(` ${j.narrative}`),j.seededSteps&&console.log(` \u26A1 ${j.seededSteps}/${j.stepResults.length} steps seeded from existing recordings (zero AI)`);let St=j.stepResults.reduce((ie,qe)=>ie+(qe.retries??0),0);St&&console.log(` \u21BB ${St} action ${St===1?"retry":"retries"} absorbed before settling (retries: ${r.retries??1} per action)`),j.verified===!0?console.log(" \u2713 proposal verified by zero-AI proof replay"):j.verified===!1&&console.log(` \u2717 proposal UNVERIFIED, proof replay failed: ${j.proofError?.split(`
|
|
1344
|
+
`)[0]}`),j.error&&console.log(` ${j.error}`)},Z=new AbortController,oe={cwd:n,timeoutMs:r.hookTimeoutMs??nr.hookTimeoutMs,env:{SAFFRON_BASE_URL:s,SAFFRON_ENV:Ve().env,SAFFRON_SHARD:y?`${y.index}/${y.total}`:void 0}},ve=[],qt,gt=()=>qt??=Ga("teardown",x,oe).then(j=>{ve.push(...j)}),rt=Promise.resolve([]);S.length+x.length>0&&process.on("SIGINT",()=>{if(Z.signal.aborted){console.error("still cleaning up: teardown finishes, then Saffron exits");return}console.error(`
|
|
1345
|
+
interrupted: stopping, then running teardown`),Z.abort(),rt.then(()=>z(I)).catch(()=>{}).then(gt).finally(()=>process.exit(130))}),S.length>0&&(rt=Ga("setup",S,{...oe,signal:Z.signal}),ve.push(...await rt),Z.signal.aborted&&await new Promise(()=>{}),ve.some(Do)&&(console.error("No scenario was run: the application is not in the state the suite expects."),await gt(),process.exit(2)));let Re=new Map;try{for(let j of w)Re.set(j,await F(j))}catch(j){throw await z(I).catch(()=>{}),await gt(),j instanceof pt&&(console.error(j.message),process.exit(2)),j}let Tr=async j=>{let D=Re.get(j),W=new Array(f.length);if(v===1&&A===1||f.length===1){for(let ie=0;ie<f.length;ie++)W[ie]=await Y(D,j,"1",f[ie]),V(W[ie]);return W}let ee=O!==void 0&&wr(j),xe=[];await wa(f.map((ie,qe)=>[{s:ie,i:qe}]),v,async(ie,qe)=>{let Be=await Y(D,j,String(qe+1),ie.s,{agentDisabled:!0});Be.status==="red"&&ee?xe.push(ie):(W[ie.i]=Be,V(Be))});let Vt=Cf(xe.sort((ie,qe)=>ie.i-qe.i),ie=>fe(n,ie.s.featurePath,ie.s.name)),St=[];try{for(let Be=1;Be<Math.min(A,Vt.length);Be++)try{St.push(await F(j))}catch(Jt){console.log(` \u26A0 agent worker ${Be+1} could not start a browser (${(Jt instanceof Error?Jt.message:String(Jt)).split(`
|
|
1346
|
+
`)[0]}); going on with ${Be}`);break}let ie=[D,...St],qe=ie.length;await wa(Vt,qe,async(Be,Jt)=>{W[Be.i]=await Y(ie[Jt],j,qe>1?`agent ${Jt+1}`:"agent",Be.s),V(W[Be.i])})}finally{await z(St)}return W};try{if(t.rerecord){let j=0;for(let D of f){let W=fe(n,D.featurePath,D.name);ke.existsSync(W)&&(ke.rmSync(W),j++)}console.log(`rerecord: removed ${j} cache file(s) for ${f.length} scenario(s); the agent records them fresh (seeded from the other recordings). Restore with git if needed.`)}for(let j of w)b&&console.log(`
|
|
1347
|
+
${j}${wr(j)?"":" (replay only: recording and healing need a Chromium-family browser)"}`),L.push(...await Tr(j)),await z([Re.get(j)]),Re.delete(j)}finally{await z(I),await gt()}let Pe=Xi(L,N,s);if(ve.length>0&&(Pe.hooks=ve),G.size>0){let j=[...U.values()];Pe.timing={wallMs:Math.max(...j.map(D=>D.last))-Math.min(...j.map(D=>D.first)),workers:[...G.values()].sort((D,W)=>w.indexOf(D.browser)-w.indexOf(W.browser)||D.worker.localeCompare(W.worker,void 0,{numeric:!0})).map(({browser:D,...W})=>({...W,spanMs:U.get(D).last-U.get(D).first}))}}b&&(Pe.browsers=w);let Dp=Nt(n).divergent.length,Ss=o.picks.size>0,Wo={...Gi(L,N,Dp,s),...Ss?{partial:!0}:{}};y||(Ss||(Pe.trends=Yi(Gr(n),Wo)),Ki(n,Wo)),Pe.totals.aiCalls>0&&(Pe.totals.plan=await O?.planUsage?.());let Go,mc=!1;if(y){let j=oa(n,{...Pe,shard:y,history:Wo}),D=j.replace(/\.json$/,".html");ke.writeFileSync(D,vn(Pe,n)),Go=`${D}
|
|
1348
|
+
${j}`}else{let j=Ss?ra(na(n),Pe):Pe;mc=j!==Pe;let{html:D,json:W}=Xr(n,j);Go=`${D}
|
|
1349
|
+
${W}`}let Oe=Pe.totals,Up=Oe.cacheReadTokens+Oe.cacheCreationTokens;console.log(`
|
|
1350
|
+
${Oe.green} passed, ${Oe.yellow} pending review, ${Oe.red} failed \xB7 ${Oe.aiCalls} AI calls \xB7 ${(Oe.inputTokens+Oe.outputTokens).toLocaleString()} tokens in+out${Up>0?` \xB7 ${gc(Oe.cacheReadTokens)} cache read \xB7 ${gc(Oe.cacheCreationTokens)} cache written`:""}${zi(Oe)}${Oe.models?.length?` \xB7 ${Oe.models.join(", ")}`:""}`);let Er=Pe.timing;Er&&Er.workers.length>1&&Er.wallMs>0&&console.log(`workers over ${Le(Er.wallMs)}: ${Er.workers.map(j=>`${j.worker} ${Qi(j)} busy`).join(" \xB7 ")}`),Pe.scenarios.length>3&&console.log(`slowest: ${Zi(Pe,3).map(j=>`${j.scenario}${Pe.browsers&&j.browser?` [${j.browser}]`:""} ${Le(j.durationMs)}`).join(" \xB7 ")}`);let Ko=Pe.trends;Ko?.prev&&console.log(Hi(Ko.prev));for(let j of Ko?.chronic??[])console.log(`\u26A0 chronic: ${j.feature} \u203A ${j.scenario}: ${j.heals} heal(s), ${j.reds} red(s) in last ${j.runs} run(s); re-record or fix the feature text instead of paying for more heals`);console.log(`report: ${Go}`),Ss&&!y&&console.log(Np(mc)),y&&console.log(`shard report, not a whole run: history and trends wait for \`saffron report --merge\` over all ${y.total} shard-*-of-${y.total}.json files`);let wc=Ft(q.resolve(Q.opts().projectRoot),xs);wc.length>0&&console.log(`${wc.length} cache proposal(s) pending. Review with: saffron accept | saffron reject`);let yc=t.strict??r.strict??!1;yc&&Oe.yellow>0&&console.log(`strict mode: ${Oe.yellow} scenario(s) pending review treated as failure. Review proposals to go green.`);let zp=Oe.red>0||yc&&Oe.yellow>0,Yo=ve.filter(j=>j.phase==="teardown"&&Do(j));Yo.length>0&&console.log(`teardown failed: ${Yo.map(j=>Ka(j,oe.timeoutMs)).join("; ")}. The environment may hold data from this run.`),process.exit(zp?1:Yo.length>0?2:0)});Q.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=q.resolve(Q.opts().projectRoot),r=ye(n),s=t.all&&!t.includeImported?on(n):{},o=0,i=e.length>0?e.map(yi).map(a=>({...a,file:q.resolve(a.file)})):t.all?Ft(n,xs).map(a=>({file:a.file,revision:void 0})):[];if(i.length===0){Lp(n);return}try{for(let{file:a,revision:c}of i){let l=y=>{console.log(`not accepted: ${q.basename(a)} ${$e(y)}`),process.exitCode=1},d=Bp(n,a,c!==void 0,()=>{if(c&&mt(a)!==c)return l(Fp);let y=s[q.relative(n,a).split(q.sep).join("/")];if(y&&mt(a)===y.revision){o++;return}let S;try{S=or(a)}catch($){if(!($ instanceof ge))throw $;return l(`cannot be read: ${$.problem}`)}if(S.meta.bound){let $=dt(n,S,Ye(n,r,[]));if($)return l(`is stale: ${$}. Run the scenario again for a proposal made against what is there now, or reject this one.`)}else console.log(`\u26A0 ${q.basename(a)} is ${eo}; accepting as it is.`);if(S.meta.verified!==!0&&t.all&&!t.includeUnverified){let $=S.meta.verified===!1?S.meta.proofError?.split(`
|
|
1351
|
+
`)[0]:"not checked: no proof replay ran";console.log(`skipped UNVERIFIED ${q.basename(a)} (${$e($)}). 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: ${$e(S.meta.proofError?.split(`
|
|
1352
|
+
`)[0])}): expect a heal or red on the next run.`);let x=S.cache.steps.map($=>$.gherkin);if(t.withFeatureEdit&&(S.meta.featureEdits??[]).length>0){let $=Zu(n,S.cache.feature,S.cache.scenario,x,Ye(n,r,[]));if($)return l(`carries feature edits, and ${$}. Run the scenario again for a fresh proposal, or accept this one without --with-feature-edit.`)}let C=He(fe(n,S.cache.feature,S.cache.scenario));return{proposal:S,recordedSteps:x,oldCache:C,cacheFile:Ds(n,a)}},l);if(!d)continue;let{proposal:u,recordedSteps:g,oldCache:f,cacheFile:p}=d;console.log(`accepted \u2192 ${p}`);let m=f?Gu(f,u.cache):{changes:[],ambiguous:[]},h=m.changes;for(let y of m.ambiguous)console.log(` locator fix for ${$e(Bo(y))} not propagated: this heal sent it to more than one place, so other caches are left alone.`);if(h.length>0){let y=Ku(n,h,p,!t.propagate);for(let S of h)console.log(` locator fix: ${$e(Bo(S.from))} \u2192 ${$e(Bo(S.to))}`);if(y.length===0)console.log(" no other caches use this locator.");else if(t.propagate)for(let S of y)console.log(` propagated \u2192 ${S.feature} \u203A ${S.scenario} (${S.steps.map(x=>`"${x.gherkin}"`).join(", ")})`);else{console.log(` ${y.length} other cache(s) use the same locator: re-run with --propagate to fix them too:`);for(let S of y)console.log(` \xB7 ${S.feature} \u203A ${S.scenario}`)}}let w=u.meta.featureEdits??[];if(!t.withFeatureEdit||w.length===0)continue;let b=Qu(n,u.cache.feature,u.cache.scenario,w,Ye(n,r,[]),g);for(let y of b.applied){let S=y.fromStepSet?`${y.file}:${y.line} (StepSet "${y.fromStepSet}", fixes every invoking scenario)`:`${y.file}:${y.line}`;console.log(` feature edit ${S}:`),console.log(` - ${y.from}`),console.log(` + ${$e(y.to)}`)}for(let y of b.skipped)console.log(` skipped edit [${y.index}]: ${$e(y.reason)}`);if(b.appliedIndices.length>0){let y=new Set(b.appliedIndices),S=He(p);for(let x of w)y.has(x.index)&&x.text.trim()!==""&&S.steps[x.index]&&(S.steps[x.index].gherkin=x.text);tr(p,S)}}}catch(a){throw a instanceof Ee&&Jo(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.`)});Q.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=q.resolve(Q.opts().projectRoot),r=ye(n),s;try{s=Mt(n,r.features??"features")}catch(i){throw i instanceof Ee&&Jo(i),i}if(e&&(s=Ns(s,e)),t.json){console.log(JSON.stringify(s,null,2));return}if(t.snippets){let i=q.join(n,".vscode","saffron.code-snippets");ke.mkdirSync(q.dirname(i),{recursive:!0}),ke.writeFileSync(i,pl(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(`
|
|
1353
|
+
${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`)});Q.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=q.resolve(Q.opts().projectRoot),r=ye(n),s=hc(t.provider,r.provider),o=ke.readFileSync(q.resolve(e),"utf8"),i;try{i=Mt(n,r.features??"features")}catch(d){throw d instanceof Ee&&Jo(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 df(o,i,t.model??Op(r,s).model,s==="claude"?void 0:Da[s]),c=t.out?q.resolve(t.out):q.join(n,r.features??"features",`${q.basename(e).replace(/\.[^.]+$/,"")}.saffron`);ke.existsSync(c)&&(console.error(`refusing to overwrite ${c}: pass --out for a new path`),process.exit(1)),ke.mkdirSync(q.dirname(c),{recursive:!0}),ke.writeFileSync(c,a.content);let l=a.content.split(`
|
|
1354
|
+
`).map(d=>d.trim().replace(/^(Given|When|Then|And|But|\*)\s+/,"")).filter(d=>i.steps.some(u=>u.text===Te(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("draft only: browser behavior and replay have not been validated."),console.log("inspect the relevant UI, resolve assumptions, then record affected scenarios: saffron run "+q.relative(process.cwd(),c)+":<line>"),console.log("review with saffron diff; accept only faithful, verified proposals, then replay the affected scenarios with --no-agent.")});Q.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=q.resolve(Q.opts().projectRoot),n=hc(e,ye(t).provider),r=n==="cursor"?Au:n==="antigravity"?xu:void 0;if(r)try{await r()}catch(o){console.error(o instanceof Error?o.message:String(o)),process.exit(1)}let s=Ua(n);if(s.length===0){console.log(`${qn[n]}: ready to record and heal.`);return}console.log([`${qn[n]} still needs:`,...s.map(o=>` \xB7 ${o}`)].join(`
|
|
1355
|
+
`)),process.exit(1)});Q.command("mcp").description("Serve the step vocabulary to AI assistants over stdio MCP (search_steps, list_step_sets)").action(async()=>{let e=q.resolve(Q.opts().projectRoot),t=ye(e);await of(e,t.features??"features")});Q.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(Pp(Fs())),process.exit(2));let e=q.resolve(Q.opts().projectRoot),t=ye(e),n=process.argv.includes("-p")||process.argv.some(r=>r.startsWith("--project-root"));Ef(e,t.features??"features",{rootFromClient:!n})});Q.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=q.resolve(Q.opts().projectRoot),r=e.length>0?e.map(yi).map(s=>({...s,file:q.resolve(s.file)})):t.all?Ft(n,xs).map(s=>({file:s.file,revision:void 0})):[];if(r.length===0){Lp(n);return}for(let{file:s,revision:o}of r){let i=Bp(n,s,o!==void 0,()=>{if(o&&mt(s)!==o)return Fp;Us(s)},a=>a);if(i){console.log(`not rejected: ${q.basename(s)} ${i}`),process.exitCode=1;continue}console.log(`rejected ${s}`)}});Q.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(bs).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=q.resolve(Q.opts().projectRoot),n=Fs();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 bs||(console.error(`saffron: unknown agent target "${i}" (expected one of ${Object.keys(bs).join(", ")})`),process.exit(2));let s=e.examples===!0;e.examples===void 0&&process.stdin.isTTY&&process.stdout.isTTY&&(s=await Ub(`Install the Saucedemo example tests (login, cart, checkout) into ${Vo(t).features}/ for a guided first run? [y/N] `));let o=Cp({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}`),o.examples?.note&&console.log(`examples \u2192 note: ${o.examples.note}`),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(`
|
|
1356
|
+
`))});Q.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)").option("--report-only","a summary instead: the last run's report and screenshots, no proposals and no traces (default: .saffron/reports/saffron-summary.zip). Small enough to upload on every run, so editors can show any run's results; a run that left only summaries has nothing to import").action(e=>{let t=q.resolve(Q.opts().projectRoot);e.base!==void 0&&e.branch===void 0&&(console.error("saffron export: --base needs --branch"),process.exit(2)),e.reportOnly&&e.branch!==void 0&&(console.error("saffron export: --report-only holds no proposals, so there is nothing for --branch to push"),process.exit(2));try{ys("--branch",e.branch),ys("--base",e.base)}catch(a){console.error(`saffron export: ${a.message}`),process.exit(2)}let n;try{n=qd(t,{out:e.out?q.resolve(e.out):void 0,summary:e.reportOnly===!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: ${$e(a.problem)}. Left out of the bundle.`);let r=n.manifest;if(console.log(`${r.summary?"summary":"bundle"}: ${n.file}`),console.log(r.summary?` the run's report \xB7 ${r.evidence.length} screenshot(s)${r.shard?` \xB7 shard ${r.shard.index}/${r.shard.total}`:""}`:` ${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 ${ns(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`),r.summary){console.log("Upload it as a saffron-summary* artifact: saffron runs marks the run, and saffron report --run <id> shows its results.");return}if(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=ye(t);s=kp(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: ${q.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))});Q.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=q.resolve(Q.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=dp(t,ye(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=`${Ho[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("_"," "),ap(i.createdAt),i.commit?.slice(0,7),i.pending?`${i.pending} proposal${i.pending===1?"":"s"} pending here`:void 0,i.results?.kind==="running"?void 0:i.results?.label].filter(Boolean);console.log(` ${i.id.padStart(12)} ${o(i)} ${a.join(" \xB7 ")}`)}console.log("Import one with: saffron import --run <id>")});Q.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=q.resolve(Q.opts().projectRoot);function r(d,u=!1){t.json?console.log(JSON.stringify({error:d},null,2)):console.error(`saffron import: ${d}${u?"":". 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=ye(n),u=Ye(n,d,[]);t.run!==void 0&&(i=hp(n,d,String(t.run),{provider:t.provider,allowFork:t.allowFork===!0}));let g=i?[i.dir]:e.map(p=>/^https?:\/\//i.test(p)?p:q.resolve(p)),f=i;s=await Kd(n,g,u,{overwrite:t.overwrite===!0,allowUnknownRepository:t.allowUnknownRepository===!0,describe:f?p=>`${Ho[f.provider]} run ${t.run} (${q.basename(q.dirname(p))})`:void 0,run:f?`${f.provider}:${t.run}`:void 0})}catch(d){o=d}finally{i?.remove()}if((o instanceof H||o instanceof Ee)&&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 ${ns(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 u=d.feature?`${d.feature} \u203A ${d.scenario}`:d.file;d.outcome==="imported"?console.log(`imported \u2192 ${d.file} (${u})`):d.outcome==="unchanged"?console.log(`unchanged: ${u}: ${d.reason??"already pending here"}`):console.log(`not imported: ${u} ${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")});Q.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=q.resolve(Q.opts().projectRoot),r=e.length>0?e.map(o=>q.resolve(o)):Ft(n,xs).map(o=>o.file);if(r.length===0){console.log("No pending proposals.");return}let s=r.map(o=>{let i=or(o),a=He(fe(n,i.cache.feature,i.cache.scenario));return{file:q.relative(n,o),verified:i.meta.verified,stale:i.meta.bound?Mp(n,i):eo,...bn(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=>`${Ys(o)}${o.stale?`
|
|
1246
1357
|
|
|
1247
|
-
STALE: ${
|
|
1358
|
+
STALE: ${$e(o.stale)}`:""}`).join(`
|
|
1248
1359
|
|
|
1249
|
-
`))});
|
|
1360
|
+
`))});Q.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=q.resolve(Q.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 C=Ip("trace",t.json===!0),$=jp(t.maxDownload,C);try{let k=ye(r),R=ic(r,k,s,{provider:t.provider,allowFork:t.allowFork===!0,maxDownloadBytes:$});if(!R.folder)throw new H(R.reason??`run ${s} has no Saffron bundle`);let _=await ac(r,{...R,folder:R.folder},Ye(r,k,[]));if(!_.report)throw new H(`run ${s}'s bundle holds no run report`);i=R.folder,a=_.report}catch(k){return C(k)}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 C=q.join(r,".saffron","reports","latest.json");ke.existsSync(C)||(console.error("No report found. Run `saffron run` first."),process.exit(2)),a=JSON.parse(ke.readFileSync(C,"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(C=>C.evidence?.some($=>$.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(),u=l;if(d){let C=l.filter($=>$.scenario===d||$.feature===d||`${$.feature}:${$.scenario}`===d||`${$.feature}:${$.scenario}@${$.browser}`===d||`${$.scenario}@${$.browser}`===d);u=C.length>0?C:l.filter($=>$.scenario.toLowerCase().includes(d.toLowerCase()))}if(u.length===0||t.json&&d&&u.length>1){console.error(u.length===0?`No traced scenario matches "${d}". Traced in ${o}:`:`--json prints one trace. Traced in ${o}:`);for(let C of l)console.error(` ${C.status.padEnd(6)} ${C.feature}:${C.scenario}${a.browsers&&C.browser?`@${ue(C.browser)}`:""}`);console.error('Name one: saffron trace "<scenario name>", or "<feature>:<scenario name>" as listed'),process.exit(2)}let g=u.findIndex(C=>C.status==="red"),f=u.findIndex(C=>C.status==="yellow"),p=g>=0?g:f>=0?f:0,m=u[p],h=C=>q.basename(C,".zip").split(".")[0].replace("proof-","Proof replay "),w=C=>{let $=C.evidence.filter(_=>_.kind==="trace"),k=C.sessions?.[C.steps.findIndex(_=>_.status==="failed")],R=$.find(_=>!_.proof&&k!==void 0&&_.session===k)??$.find(_=>!_.proof)??$[0];return[R,...$.filter(_=>_!==R)]},[b]=w(m),y;if(u.length===1||t.json){let C=q.join(i,b.file);try{y=Ja(i,b)}catch($){console.error(`The trace cannot be read: ${$ instanceof Error?$.message:String($)}`),process.exit(2)}if(y||(console.error(ke.existsSync(C)?"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: ${C}. Run the scenario again.`),process.exit(2)),t.json){console.log(JSON.stringify({...ju(y),...b.session?{session:b.session}:{}},null,2));return}}let S=u.map((C,$)=>{let[k,...R]=w(C);return{scenario:{feature:C.feature,scenario:C.scenario,status:C.status,error:C.error,adaptations:C.adaptations,narrative:C.narrative,proposalDiff:C.proposalDiff,proposalFile:C.proposalFile,proposalRevision:C.proposalRevision,screenshots:C.evidence?.filter(_=>_.kind!=="trace"),ranAt:a.startedAt,source:["cache","agent-record","agent-heal"].find(_=>_===C.source),proposalReplay:C.proposalReplay===!0?!0:void 0,usage:C.usage,browser:a.browsers?C.browser:void 0,stepSessions:C.sessions},traces:[k,...R].map((_,v)=>({file:q.join(i,_.file),data:$===p&&v===0?y:void 0,read:()=>Ja(i,_),checked:_.sha256!==void 0,label:`${_.proof?h(_.file):"Execution"}${_.session?` \xB7 session "${_.session}"`:""}`,proof:_.proof===!0,steps:_.proof?_.traceSteps:_.traceSteps??C.steps,uniques:_.proof?_.traceUniques:C.uniques,browserSession:_.session}))}}),x;try{x=await Ju({entries:S,start:p,projectRoot:i,port:n,viewOnly:c})}catch(C){console.error(`Could not start the replay: ${C instanceof Error?C.message:String(C)}`),process.exit(2)}for(let{file:C,reason:$}of x.skipped)console.error(`Skipping ${q.relative(i,C)}. ${$}`);console.log(`Saffron replay: ${u.length===1?`${m.feature} \u203A ${m.scenario}`:`${u.length} scenarios, opening on ${m.scenario}`}
|
|
1250
1361
|
${x.url}
|
|
1251
|
-
Press Ctrl-C to stop.`),t.open!==!1&&
|
|
1252
|
-
`)),process.exit(2));let s=e.yes&&!e.check?
|
|
1253
|
-
`))}e.check&&r.orphans.length>0&&process.exit(1)});
|
|
1254
|
-
${f}`)}function
|
|
1255
|
-
`)[0]:String(n)}`}}var
|
|
1256
|
-
`);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(` ${
|
|
1362
|
+
Press Ctrl-C to stop.`),t.open!==!1&&vs(x.url),await new Promise(C=>{process.once("SIGINT",()=>{x.close().finally(C)})}),process.exit(0)});Q.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=q.resolve(Q.opts().projectRoot),n=ye(t),r=Hs(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(`
|
|
1363
|
+
`)),process.exit(2));let s=e.yes&&!e.check?Rl(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 ":""}${Tl(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(`
|
|
1364
|
+
`))}e.check&&r.orphans.length>0&&process.exit(1)});Q.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=q.resolve(Q.opts().projectRoot),n=ye(t),r=rs(t,n);if(e.json){console.log(JSON.stringify(r,null,2));return}sf(r)});Q.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").option("--panel","with --run: print the run's results as one page (what the editors' CI results panel shows); a failure is {error} as with --json").action(async(e,t)=>{let n=q.resolve(Q.opts().projectRoot);if(t.run!==void 0){t.json&&t.panel&&(console.error("saffron report: --json and --panel print different things: pick one"),process.exit(2)),await qb(n,String(t.run),t);return}for(let s of["provider","allowFork","maxDownload","json","panel"])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){Vb(n,e);return}e.length>0&&(console.error("saffron report: paths are only read with --merge"),process.exit(2));let r=q.join(n,".saffron","reports","latest.html");ke.existsSync(r)||(console.error("No report found. Run `saffron run` first."),process.exit(2)),console.log(r),vs(r)});function Ip(e,t){return n=>{let r=n instanceof Error?n.message:String(n);if(t){let s=n instanceof H?n.kind:void 0;console.log(JSON.stringify({error:r,...s?{kind:s}:{},...n instanceof hs?{sizeBytes:n.sizeBytes}:{}},null,2))}else console.error(`saffron ${e}: ${r}`);process.exit(2)}}function jp(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 qb(e,t,n){let r=Ip("report",n.json===!0||n.panel===!0),s=jp(n.maxDownload,r),o;try{let l=ye(e);o=await yp(e,l,Ye(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(n.panel){process.stdout.write(Uo(i,e,Xe()));return}if(!i.bundle){console.log(i.reason);return}for(let l of i.warnings)console.log(`\u26A0 ${l}`);i.bundle.summaryOnly&&console.log(`run ${t} uploaded only a summary: its results and screenshots, no traces to replay and nothing to import`);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=q.join(e,i.reportHtml);console.log(c),vs(c)}Q.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=q.resolve(Q.opts().projectRoot),n=rs(t,ye(t)),r=tp(n.quality,n.version);if(e.stdout){process.stdout.write(r);return}let s=q.join(t,".saffron","reports","dashboard.html");ke.mkdirSync(q.dirname(s),{recursive:!0}),ke.writeFileSync(s,r),console.log(s),e.open!==!1&&vs(s)});function Np(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 Vb(e,t){let n=t.length>0?t.map(m=>q.resolve(m)):[q.join(e,".saffron")],r;try{r=fo(Nd(n))}catch(m){console.error(`saffron report --merge: ${m instanceof Error?m.message:String(m)}`),process.exit(2)}let{report:s,history:o,replaced:i}=r;for(let m of i)console.log(`\u26A0 ${m} is a shard a later attempt of the run ran again: left out`);let a=Gr(e),c=a.find(m=>m.runId===o.runId),l=c?a.filter(m=>m.runId!==o.runId):a;o.partial||(s.trends=Yi(l,o));let d=c!==void 0&&JSON.stringify(c)===JSON.stringify(o);d||Sd(e,o);let u=o.partial?ra(na(e),s):s,{html:g,json:f}=Xr(e,u),p=s.totals;console.log(`merged ${s.shards} shard(s): ${p.scenarios} scenario(s) \xB7 ${p.green} passed, ${p.yellow} pending review, ${p.red} failed \xB7 ${p.aiCalls} AI calls${zi(p)}`),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(Hi(s.trends.prev));for(let m of s.trends?.chronic??[])console.log(`\u26A0 chronic: ${m.feature} \u203A ${m.scenario}: ${m.heals} heal(s), ${m.reds} red(s) in last ${m.runs} run(s)`);o.partial&&console.log(Np(u!==s)),console.log(`report: ${g}
|
|
1365
|
+
${f}`)}function Mp(e,t){try{return dt(e,t,Ye(e,ye(e),[]))}catch(n){return`cannot check: ${n instanceof Error?n.message.split(`
|
|
1366
|
+
`)[0]:String(n)}`}}var $e=e=>ue(String(e??""),1/0),xs=(e,t)=>console.error(`\u26A0 proposal ${e} cannot be read: ${$e(t)}`),Jb="is no longer pending: it was accepted, rejected or removed since it was listed.",Wb="is not a pending proposal.",Gb="is not a proposal file under .saffron/proposals.",Fp="changed since it was listed. Refresh and review it again.",Kb="is being decided by another process. Try again.";function Bp(e,t,n,r,s){if(!t.endsWith(".json")||ke.existsSync(t)&&!ht(q.join(e,".saffron","proposals"),t))return s(Gb);try{return Bs(t,r,()=>s(n?Jb:Wb))}catch(o){if(!(o instanceof In))throw o;return s(Kb)}}function Lp(e){let t=Ft(e,xs);if(t.length===0){console.log("No pending proposals.");return}console.log(`Pending proposals:
|
|
1367
|
+
`);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(` ${$e(r.cache.feature)} \u203A ${$e(r.cache.scenario)} (${$e(r.meta.mode)}, ${$e(r.meta.createdAt)}${s})`);let o=r.meta.bound?Mp(e,r):eo;o&&console.log(` \u2717 STALE: ${$e(o)}`),console.log(` ${$e(r.meta.narrative)}`);for(let i of r.meta.adaptations)console.log(` \u26A0 ${$e(i)}`);r.meta.suggestedFeatureEdit&&console.log(` suggested .feature edit:
|
|
1257
1368
|
${r.meta.suggestedFeatureEdit.split(`
|
|
1258
|
-
`).map(i=>` ${
|
|
1259
|
-
`)}`),console.log()}console.log("Accept with: saffron accept <file> | --all")}
|
|
1369
|
+
`).map(i=>` ${$e(i)}`).join(`
|
|
1370
|
+
`)}`),console.log()}console.log("Accept with: saffron accept <file> | --all")}Q.parseAsync().catch(e=>{process.env.SAFFRON_DEBUG?console.error(e):console.error(`saffron: ${e instanceof Error?e.message:String(e)}`),process.exit(2)});
|