saffron-ai 0.7.2 → 0.8.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 +61 -0
- package/README.md +1 -0
- package/dist-pkg/cli.js +116 -109
- package/package.json +1 -1
- package/skills/saffron/SKILL.md +1 -0
- package/skills/saffron/references/config.md +2 -0
- package/skills/saffron/references/syntax.md +54 -0
- package/templates/saucedemo/data/catalog.json +11 -0
- package/templates/saucedemo/features/shopping.saffron +9 -0
- package/textmate/saffron/syntaxes/saffron.tmLanguage.json +7 -2
package/dist-pkg/cli.js
CHANGED
|
@@ -1,52 +1,57 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
`).
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
`
|
|
10
|
-
`)){let r
|
|
11
|
-
|
|
12
|
-
`)
|
|
13
|
-
|
|
14
|
-
`)[
|
|
15
|
-
`)}
|
|
16
|
-
`).filter(Boolean)
|
|
17
|
-
`)
|
|
18
|
-
`)[0]:
|
|
19
|
-
`)
|
|
20
|
-
`),r=t.
|
|
21
|
-
|
|
2
|
+
import B from"node:fs";import F from"node:path";import{spawn as mi}from"node:child_process";import yi from"node:readline";import{Command as Si}from"commander";import vs from"node:fs";import ws from"node:path";import{AstBuilder as ks,GherkinClassicTokenMatcher as $s,Parser as Ts}from"@cucumber/gherkin";import{IdGenerator as Rs,StepKeywordType as Ot}from"@cucumber/messages";function Se(e,t){return e.replace(/<([^<>]+)>/g,(n,r)=>r in t?t[r]:n)}function U(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 be(e){return e!==void 0?{docstring:e}:{}}function le(e){let t=new Map;for(let r of e){let s={...U(r.resolvedTable??r.table),...be(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}import Re from"node:fs";import de from"node:path";var Ct=/\{data:([A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+)\}/g,Ae=de.resolve("data"),Y,et=new Map;function Ee(e,t="data",n){Ae=de.isAbsolute(t)?t:de.join(e,t),Y=n?.trim()||void 0,et.clear()}var Pe=()=>({dir:Ae,env:Y});function pn(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?pn(e[s],o):o;return r}function dn(e,t){try{return JSON.parse(Re.readFileSync(e,"utf8"))}catch(n){throw new Error(`data file ${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}}function ps(e){if(et.has(e))return et.get(e);let t=de.join(Ae,`${e}.json`),n=Y?de.join(Ae,`${e}.${Y}.json`):void 0,r=Re.existsSync(t),s=n!==void 0&&Re.existsSync(n);if(!r&&!s)throw new Error(`data file ${de.relative(process.cwd(),t)||t} does not exist${Y?` (nor ${e}.${Y}.json for the "${Y}" environment)`:""}`);let o=r?dn(t,`${e}.json`):void 0;if(s){let i=dn(n,`${e}.${Y}.json`);o=r?pn(o,i):i}return et.set(e,o),o}function xe(e){let[t,...n]=e.split("."),r=ps(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 tt(e){let t;try{t=xe(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 je(e){let t;try{t=xe(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 nt(e){je(e)}function fn(e){return e.replace(Ct,(t,n)=>{let r=je(n);return Array.isArray(xe(n))?`${t} (a data list, currently: ${r.map(o=>`"${o}"`).join(", ")})`:r[0]})}function fs(e){let t=[],n=[],r="",s=!1;for(let o=0;o<e.length;o++){let i=e[o];s?i==='"'&&e[o+1]==='"'?(r+='"',o++):i==='"'?s=!1:r+=i:i==='"'&&r===""?s=!0:i===","?(n.push(r),r=""):i===`
|
|
3
|
+
`||i==="\r"?(i==="\r"&&e[o+1]===`
|
|
4
|
+
`&&o++,n.push(r),r="",n.some(a=>a!=="")&&t.push(n),n=[]):r+=i}return n.push(r),n.some(o=>o!=="")&&t.push(n),t.map(o=>o.map(i=>i.trim()))}function rt(e){let t=a=>{throw new Error(`Examples: {data:${e}}: ${a}`)},n=Y?de.join(Ae,`${e}.${Y}.csv`):void 0,r=n&&Re.existsSync(n)?n:de.join(Ae,`${e}.csv`);if(!e.includes(".")&&Re.existsSync(r)){let[a,...c]=fs(Re.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((h,d)=>[h,l[d]??""])))}}let s;try{s=xe(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 _t(e){return e.replace(Ct,(t,n)=>tt(n))}function Ue(e){let t=new Set;for(let n of e)if(n)for(let r of n.matchAll(Ct))t.add(r[1]);return t}function st(e){let t=new Map;for(let n of Ue(e))try{t.set(n,tt(n))}catch{}return t}function un(e,t){let n=[...t.entries()].sort((s,o)=>o[1].length-s[1].length);for(let[s,o]of n)if(o!==""&&e===o)return`{data:${s}}`;let r=e;for(let[s,o]of n)o.length<4||(r=r.split(o).join(`{data:${s}}`));return r}import Ft from"node:fs";import gn from"node:path";import{AstBuilder as us,GherkinClassicTokenMatcher as gs,Parser as hs}from"@cucumber/gherkin";import{IdGenerator as ms}from"@cucumber/messages";var N=class extends Error{},ys=/^(\s*)StepSet:\s*(.+?)\s*$/,Ss=/^(\s*)StepSet\s+([^\s:].*?)\s*$/;function It(e){let t=e.split(`
|
|
5
|
+
`),n=new Map,r=new Map;return{source:t.map((o,i)=>{let a=o.match(ys);if(a)return n.set(i+1,a[2]),`${a[1]}Scenario: ${a[2]}`;let c=o.match(Ss);return c?(r.set(i+1,c[2]),`${c[1]}* StepSet ${c[2]}`):o}).join(`
|
|
6
|
+
`),definitions:n,invocations:r}}function bs(e){return new hs(new us(ms.uuid()),new gs).parse(e)}function hn(e,t){for(let n of e)n.scenario?t(n.scenario):"rule"in n&&n.rule&&hn(n.rule.children,t)}function Q(e,t){let n=new Map;for(let r of e){let s=gn.relative(t,r),o=It(Ft.readFileSync(r,"utf8"));if(o.definitions.size===0)continue;let i=bs(o.source);i.feature&&hn(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 N(`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 N(`StepSet "${c}" (${s}:${a.location.line}) has an Examples table \u2014 step sets take their values from the invoking scenario.`);for(let h of a.steps)if(o.invocations.has(h.location.line))throw new N(`StepSet "${c}" (${s}:${a.location.line}) invokes another step set at line ${h.location.line} \u2014 step sets cannot be nested.`);n.set(c,{name:c,file:s,line:a.location.line,steps:[...a.steps]})})}return n}var xs=[".feature",".saffron"];function te(e){return xs.some(t=>e.endsWith(t))}function pe(e){if(!Ft.existsSync(e))return[];let t=[];for(let n of Ft.readdirSync(e,{recursive:!0})){let r=String(n);r.endsWith(".saffron")&&t.push(gn.join(e,r))}return t.sort()}function mn(e,t,n){return e.map(({step:r,source:s})=>{let o;switch(r.keywordType){case Ot.OUTCOME:o="assertion";break;case Ot.CONTEXT:case Ot.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:Se(r.text,t),table:i,resolvedTable:i?.map(c=>c.map(l=>Se(l,t))),docString:a,resolvedDocString:a!==void 0?Se(a,t):void 0,source:s}})}function yn(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 N(`${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 As(e,t,n,r,s,o=!1){let i=e.tags.map(c=>c.name),a=[];if(e.examples.length===0)a.push({params:{},label:""});else{let c=0;for(let l of e.examples){let h=l.name.trim().match(/^\{data:([A-Za-z0-9_.-]+)\}$/);if(h&&!l.tableHeader){let g=`${t}:${l.location.line}`;if(!o)throw new N(`${g} 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=rt(h[1])}catch(x){throw new N(`${g} ${x instanceof Error?x.message:String(x)}`)}let S=[...new Set([...r,...s].flatMap(x=>[x.step.text,x.step.docString?.content??"",...x.step.dataTable?.rows.flatMap(R=>R.cells.map($=>$.value))??[]].flatMap(R=>[...R.matchAll(/<([^<>]+)>/g)].map($=>$[1]))))].filter(x=>!m.headers.includes(x)&&!x.startsWith("table:")&&x!=="docstring");if(S.length>0)throw new N(`${g} the scenario uses <${S.join(">, <")}>, but {data:${h[1]}} has the columns ${m.headers.map(x=>`"${x}"`).join(", ")}.`);for(let x of m.rows)c+=1,a.push({params:x,label:` (example ${c})`});continue}let d=l.tableHeader?.cells.map(g=>g.value)??[];for(let g of l.tableBody){c+=1;let m={};g.cells.forEach((u,S)=>{m[d[S]]=u.value}),a.push({params:m,label:` (example ${c})`})}}}return a.map(({params:c,label:l})=>{let h={value:"action"};return{featurePath:t,featureName:n,name:e.name,displayName:`${e.name}${l}`,tags:i,steps:[...mn(r,c,h),...mn(s,c,h)],params:c}})}function W(e,t,n){let r=vs.readFileSync(e,"utf8"),s=e.endsWith(".saffron"),o=s?It(r):{source:r,definitions:new Map,invocations:new Map},i=new Ts(new ks(Rs.uuid()),new $s),a=ws.relative(t,e),c;try{c=i.parse(o.source)}catch(g){let m=(g instanceof Error?g.message:String(g)).split(`
|
|
7
|
+
`).filter(S=>/^\(\d+:\d+\)/.test(S)).map(S=>`${a}${S.replace(/^\((\d+):(\d+)\)/,":$1:$2")}`),u=!s&&/^\s*StepSet\b/m.test(r);throw new N(u?`${a} uses StepSet, which only .saffron files understand. Rename it to ${a.replace(/\.feature$/,".saffron")}: nothing else needs to change (a .saffron file accepts everything a .feature file does).`:`${a} is not valid Gherkin:
|
|
8
|
+
${m.join(`
|
|
9
|
+
`)||(g instanceof Error?g.message:String(g))}`)}if(!c.feature)return[];let l=c.feature.name,h=[],d=(g,m)=>{let u=m;for(let S of g)if(S.background)u=[...m,...yn(S.background.steps,a,!0,o.invocations,n)];else if(S.scenario){if(o.definitions.has(S.scenario.location.line))continue;h.push(...As(S.scenario,a,l,u,yn(S.scenario.steps,a,!1,o.invocations,n),s))}else"rule"in S&&S.rule&&d(S.rule.children,u)};return d(c.feature.children,[]),h}import $n from"node:fs";import Nt from"node:path";import bn from"node:fs";import xn from"node:path";import{createHash as Es}from"node:crypto";import ot from"node:fs";import Ce from"node:path";var Dt=".saffron";function it(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function Mt(e){let t=e.split(/[\\/]/).filter(Boolean),n=t.pop()??"unnamed",r=t.slice(1),s=it([...r,Ce.basename(n,".feature")].join("-"));if(r.length===0)return s;let o=Es("sha1").update(e.replace(/\\/g,"/")).digest("hex").slice(0,6);return`${s}-${o}`}function L(e,t,n){return Ce.join(e,Dt,"cache",Mt(t),`${it(n)}.json`)}function Sn(e,t){let n=new Map;for(let r of t){let s=L(e,r.featurePath,r.name),o=n.get(s)??new Set;o.add(`${r.featurePath} \u203A ${r.name}`),n.set(s,o)}return[...n.entries()].filter(([,r])=>r.size>1).map(([r,s])=>`${[...s].join(" and ")} both map to ${Ce.relative(e,r)}. Rename one scenario or one file.`)}function ve(e,t,n){return Ce.join(e,Dt,"artifacts",Mt(t),it(n))}function fe(e,t,n){return Ce.join(e,Dt,"proposals",Mt(t),`${it(n)}.json`)}function z(e){if(!ot.existsSync(e))return;let t=JSON.parse(ot.readFileSync(e,"utf8"));if(t.version!==1)throw new Error(`Unsupported cache version ${t.version} in ${e}`);return t}function _e(e,t){ot.mkdirSync(Ce.dirname(e),{recursive:!0}),ot.writeFileSync(e,`${JSON.stringify(t,null,2)}
|
|
10
|
+
`)}function at(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 Le(e,t){if(t.trim()==="")return!1;let n=r=>(r??"").replace(/<[^<>]+>/g,"");return e.some(r=>[r.value,r.url,r.urlPattern,r.pattern,r.promptText,r.compareTo,...[r.target,r.toTarget].flatMap(s=>[s?.name,s?.nameRegex,s?.label,s?.text,s?.placeholder,s?.testId,s?.frame,...s?.fallbackSelectors??[]])].some(s=>n(s).includes(t)))}function ct(e){let t=[];return{pattern:e.replace(/"((?:[^"\\]|\\.)*)"/g,(r,s)=>(t.push(s),`"\xAB${t.length-1}\xBB"`)),args:t}}function Ps(e,t){let n=r=>JSON.stringify(r.map(({pageFingerprint:s,...o})=>o));return n(e)===n(t)}function js(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 ne(e){let t=xn.join(e,".saffron","cache"),n=new Map,r=new Map,s=0;if(bn.existsSync(t))for(let a of bn.readdirSync(t,{recursive:!0})){let c=String(a);if(!c.endsWith(".json"))continue;let l=z(xn.join(t,c));if(l){s++;for(let h of l.steps){let d=h.gherkin,g=JSON.stringify(h.actions.map(({pageFingerprint:S,...x})=>x)),m=r.get(d)??[];m.includes(g)||(m.push(g),r.set(d,m));let u=n.get(d);!u||l.recordedAt>u.recordedAt?n.set(d,{gherkin:h.gherkin,table:h.table,docString:h.docString,actions:h.actions,sourceParams:le(l.steps),feature:l.feature,scenario:l.scenario,recordedAt:l.recordedAt,variants:m.length}):u.variants=m.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}=ct(a.gherkin);if(l.length===0)continue;let h=i.get(c);(!h||a.recordedAt>h.recordedAt)&&i.set(c,{...a,args:l})}return{steps:n,patterns:i,divergent:o,scannedCaches:s}}function vn(e,t,n){if(!!e.table!=!!t.table)return!1;if(e.table&&t.table){let o=Object.keys(U(e.table)),i=Object.keys(U(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=U(e.table),i=U(t.table);for(let a of Object.keys(o))if(o[a]!==i[a]&&(!at(e.actions,`<${a}>`)||Le(e.actions,o[a])))return!1}for(let[o,i]of Object.entries(e.sourceParams??{}))if(o in n&&n[o]!==i&&Le(e.actions,i))return!1;let r={...n,...U(t.resolvedTable??t.table),...be(t.resolvedDocString??t.docString)},s=js({gherkin:e.gherkin,keyword:"",kind:"action",actions:e.actions});for(let o of s)if(!(o in r))return!1;return!0}function wn(e,t,n){let r=e.steps.get(t.text);if(r)return vn(r,t,n)?r:void 0;let{pattern:s,args:o}=ct(t.text);if(o.length===0)return;let i=e.patterns.get(s);if(!i)return;let a=new Map;for(let d=0;d<o.length;d++){let g=i.args[d],m=o[d];if(g===m)continue;let u=a.get(g);if(u!==void 0&&u!==m)return;a.set(g,m)}let c=d=>[d?.name,d?.nameRegex,d?.label,d?.text,d?.placeholder];for(let d of a.keys())if(!i.actions.some(m=>[m.value,m.url,m.pattern,...c(m.target)].includes(d)))return;let l=d=>d!==void 0&&a.has(d)?a.get(d):d,h={...i,gherkin:t.text,actions:i.actions.map(({pageFingerprint:d,...g})=>({...g,value:l(g.value),url:l(g.url),pattern:l(g.pattern),target:g.target?{...g.target,name:l(g.target.name),nameRegex:l(g.target.nameRegex),label:l(g.target.label),text:l(g.target.text),placeholder:l(g.target.placeholder)}:void 0}))};return vn(h,t,n)?h:void 0}function kn(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&&Ps(r.actions,o.actions)){n.push({index:s,from:r.gherkin,to:o.gherkin,feature:o.feature,scenario:o.scenario});break}}}),n}function Cs(e){if(!$n.existsSync(e))return[];let t=[];for(let n of $n.readdirSync(e,{recursive:!0})){let r=String(n);te(r)&&t.push(Nt.join(e,r))}return t.sort()}function Z(e,t,n,r){let s=Nt.isAbsolute(t)?t:Nt.join(e,t),o=Cs(s),i=n??Q(o.filter(m=>m.endsWith(".saffron")),e),a=new Map,c=new Map;for(let m of o)for(let u of r?.get(m)??W(m,e,i)){let S=`${u.featurePath}::${u.name}`;for(let x of u.steps){let R=a.get(x.text);if(R||(R={text:x.text,keywords:new Map,kind:x.kind,scenarios:new Set,files:new Set,fromStepSet:x.source?.fromStepSet},a.set(x.text,R)),R.keywords.set(x.keyword,(R.keywords.get(x.keyword)??0)+1),R.scenarios.add(S),x.source&&R.files.add(x.source.file),x.source?.fromStepSet){let $=c.get(x.source.fromStepSet);$||c.set(x.source.fromStepSet,$=new Set),$.add(S)}}}let l=ne(e),h=new Set(l.divergent),d=[...a.values()].map(m=>({text:m.text,keyword:[...m.keywords.entries()].sort((u,S)=>S[1]-u[1])[0][0],kind:m.kind,status:h.has(m.text)?"divergent":l.steps.has(m.text)?"recorded":"unrecorded",usage:m.scenarios.size,files:[...m.files].sort(),fromStepSet:m.fromStepSet})).sort((m,u)=>u.usage-m.usage||m.text.localeCompare(u.text)),g=[...i.values()].map(m=>({name:m.name,file:m.file,line:m.line,steps:m.steps.map(u=>u.text),usage:c.get(m.name)?.size??0})).sort((m,u)=>u.usage-m.usage||m.name.localeCompare(u.name));return{steps:d,stepSets:g,scannedFiles:o.length,scannedCaches:l.scannedCaches}}function lt(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 Tn(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)+`
|
|
11
|
+
`}import{Server as Xs}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as eo}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as to,ListToolsRequestSchema as no}from"@modelcontextprotocol/sdk/types.js";import J from"node:fs";import ee from"node:path";import Pn from"node:fs";import Fs from"node:path";import Rn from"node:fs";import _s from"node:path";var An=/\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g;function ze(e){return e.replace(An,(t,n)=>{let r=process.env[n];if(r===void 0)throw new Error(`environment variable ${n} is not set (referenced as {env:${n}}) \u2014 export it or add it to .env`);return r})}function Ut(e){let t=new Set;for(let n of e)if(n)for(let r of n.matchAll(An))t.add(r[1]);return t}function H(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 Ve(e){let t=new Map;for(let n of Ut(H(e))){let r=process.env[n];r!==void 0&&t.set(n,r)}return t}function Fe(e,t){let n=e;for(let[r,s]of[...t.entries()].sort((o,i)=>i[1].length-o[1].length))s.length<4||(n=n.split(s).join(`{env:${r}}`));return n}function En(e){let t=_s.join(e,".env");if(Rn.existsSync(t))for(let n of Rn.readFileSync(t,"utf8").split(`
|
|
12
|
+
`)){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 K(e){En(e);let t=Fs.join(e,"saffron.config.json"),n=Pn.existsSync(t)?JSON.parse(Pn.readFileSync(t,"utf8")):{};return Ee(e,n.dataDir,process.env.SAFFRON_ENV??n.env),n}var Is={features:"features",dataDir:"data",actionTimeoutMs:5e3,pollIntervalMs:100,retries:1,screenshot:"viewport",maxTurns:100,strict:!1,verifyProposals:!0,snapshotMode:"none",reuseSteps:!0,browser:"chromium",workers:1,assertionPolicy:"strict"};function jn(e){return{...Is,...Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}}import Lt from"node:fs";import dt from"node:path";import{fileURLToPath as Os}from"node:url";function pt(){let e=dt.dirname(Os(import.meta.url));for(let t=0;t<6;t++){let n=dt.join(e,"package.json");if(Lt.existsSync(n))try{if(JSON.parse(Lt.readFileSync(n,"utf8")).name==="saffron-ai")return e}catch{}e=dt.dirname(e)}}function ue(){let e=pt();if(!e)return"unknown";try{return JSON.parse(Lt.readFileSync(dt.join(e,"package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}import G from"node:fs";import V from"node:path";var zt=(e,t)=>V.relative(e,t).split(V.sep).join("/");function _n(e){return G.existsSync(e)?[...G.readdirSync(e,{recursive:!0})].map(String).filter(t=>t.endsWith(".json")).map(t=>V.join(e,t)).sort():[]}function Fn(e){try{let t=JSON.parse(G.readFileSync(e,"utf8")),n="cache"in t&&t.cache?t.cache:t;return{feature:n.feature,scenario:n.scenario}}catch{return{}}}function ft(e,t,n){let r=V.isAbsolute(t)?t:V.join(e,t),s=new Set(G.existsSync(r)?[...G.readdirSync(r,{recursive:!0})].map(String).filter(te).map(l=>V.join(r,l)):[]);for(let l of["cache","proposals"])for(let h of _n(V.join(e,".saffron",l))){let{feature:d}=Fn(h);if(typeof d=="string"){let g=V.resolve(e,d);G.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=Q([...new Set([...pe(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 h;try{h=W(l,e,a)}catch(d){o.push(`${zt(e,l)}: ${d instanceof Error?d.message:String(d)}`);continue}for(let d of h)c.add(L(e,d.featurePath,d.name)),c.add(fe(e,d.featurePath,d.name)),c.add(ve(e,d.featurePath,d.displayName))}return{...Ds(e,c),unreadable:o}}function Ds(e,t){let n=[],r=0;for(let o of["cache","proposal"]){let i=V.join(e,".saffron",o==="cache"?"cache":"proposals");for(let a of _n(i)){if(t.has(a)){r++;continue}let{feature:c,scenario:l}=Fn(a),h=c?V.join(e,c):void 0;n.push({file:zt(e,a),kind:o,feature:c,scenario:l,reason:c?G.existsSync(h)?"scenario-gone":"feature-gone":"unknown"})}}let s=V.join(e,".saffron","artifacts");for(let o of Cn(s))for(let i of Cn(o)){if(t.has(i)){r++;continue}n.push({file:zt(e,i),kind:"artifact",reason:"unknown"})}return{orphans:n,kept:r}}function Cn(e){try{return G.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>V.join(e,t.name)).sort()}catch{return[]}}function In(e,t){let n=[],r=new Set;for(let s of t){let o=V.join(e,s.file);try{G.rmSync(o,{recursive:s.kind==="artifact"}),n.push(s.file),r.add(V.dirname(o))}catch{}}for(let s of r)try{G.readdirSync(s).length===0&&G.rmdirSync(s)}catch{}return n}function On(e){if(e.kind==="artifact")return`${e.file}/
|
|
13
|
+
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}
|
|
14
|
+
${e.kind==="proposal"?"pending proposal for ":""}${t}: ${n}`}import Ln from"node:path";var re=new Set(["expectVisible","expectNotVisible","expectText","expectUrl","expectValue","expectDiffers","expectMatches","expectAttribute","expectResponse","expectEach"]);var Ms=/\{date([+-]\d+)?(?::([^}]+))?\}/g;function Ns(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 Vt(e,t=new Date){return e.replace(Ms,(n,r,s)=>{let o=new Date(t);return o.setDate(o.getDate()+(r?parseInt(r,10):0)),Ns(o,s??"YYYY-MM-DD")})}var Us=/\b(\d{4})-(\d{2})-(\d{2})\b/g,Ls=400;function Dn(e,t=new Date){let n=new Date(t.getFullYear(),t.getMonth(),t.getDate());return e.replace(Us,(r,s,o,i)=>{let a=new Date(Number(s),Number(o)-1,Number(i));if(Number.isNaN(a.getTime()))return r;let c=Math.round((a.getTime()-n.getTime())/864e5);return Math.abs(c)>Ls?r:c===0?"{date}":`{date${c>0?"+":""}${c}}`})}import{createHash as zs,randomBytes as Vs}from"node:crypto";var Mn=/\{unique:([A-Za-z0-9_-]+)(?::(digits))?\}/g,se="__saffron_unique_seed",qe=()=>`${Date.now().toString(36)}${Vs(4).toString("hex")}`;function Nn(e,t,n=!1){let r=zs("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 ut(e,t){return e.replace(Mn,(n,r,s)=>Nn(t,r,s==="digits"))}function gt(e,t){let n=new Map;for(let r of e)if(r)for(let s of r.matchAll(Mn))n.set(s[0],Nn(t,s[1],s[2]==="digits"));return n}function Un(e,t){let n=e;for(let[r,s]of t)n=n.split(s).join(r);return n}import{createHash as qs}from"node:crypto";async function we(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:${qs("sha256").update(n).digest("hex")}`}var Wt=e=>new Promise(t=>setTimeout(t,e)),Bt=class{entries=[];seq=0;prevStepSeq=0;curStepSeq=0;listener;context;attach(t,n){this.context=t,this.listener=r=>{let s={seq:++this.seq,url:r.url(),method:r.request().method(),status:r.status()};if(this.entries.push(s),n){let o=r.headers()["content-type"]??"";/json|text|xml/i.test(o)&&r.text().then(i=>{s.body=i.length>262144?i.slice(0,262144):i}).catch(()=>{})}},t.on("response",this.listener)}detach(){this.context&&this.listener&&this.context.off("response",this.listener)}markStep(){this.prevStepSeq=this.curStepSeq,this.curStepSeq=this.seq}sincePreviousStep(){return this.entries.filter(t=>t.seq>this.prevStepSeq)}all(){return this.entries}};function Bs(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 zn(e,t,n,r,s){return!(!t.test(e.url)||n&&e.method.toUpperCase()!==n.toUpperCase()||!Bs(e.status,r)||s&&!s.test(e.body??""))}var Ws=(e,t)=>`response matching ${e.method??"any-method"} /${t}/ status ${e.status??"2xx"}${e.pattern?` body /${e.pattern}/`:""}`,Hs=new Set(["click","fill","press","selectOption","check","uncheck","hover","dragTo","uploadFile"]);function Vn(e,t,n,r=!1,s=!0){let o=c=>ze(_t(Vt(Se(c,n)))),i=[],a=c=>{if(t.role){let l=t.nameRegex?new RegExp(o(t.nameRegex),"i"):t.name?o(t.name):void 0,h=t.role;typeof l=="string"?(i.push(c.getByRole(h,{name:l,exact:!0})),s&&i.push(c.getByRole(h,{name:l,exact:!1}))):i.push(c.getByRole(h,{name:l,exact:!1}))}t.label&&i.push(c.getByLabel(o(t.label))),t.placeholder&&i.push(c.getByPlaceholder(o(t.placeholder))),t.text&&i.push(c.getByText(o(t.text))),t.testId&&i.push(c.getByTestId(o(t.testId)));for(let l of t.fallbackSelectors??[])i.push(c.locator(l))};if(t.frame)a(e.frameLocator(o(t.frame)));else if(a(e),r)for(let c of e.frames())c!==e.mainFrame()&&a(c);if(i.length===0)throw new Error("Action target has neither role nor fallback selectors");return i}var Bn=100;async function Js(e,t,n,r){let s=Date.now()+t,o;for(;Date.now()<s;){try{if(await e())return}catch(i){o=i}await Wt(r)}throw new Error(`Timed out waiting for ${n}${o?` (${String(o)})`:""}`)}async function X(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 qt=e=>e.replace(/\s+/g," ").trim();async function Ht(e,t,n,r,s,o=new Map,i,a=Bn){let c=(f,y,p)=>Js(f,y,p,a);o.has(se)||o.set(se,qe());let l=o.get(se),h=f=>typeof f=="string"?ut(f,l):Array.isArray(f)?f.map(h):f&&typeof f=="object"?Object.fromEntries(Object.entries(f).map(([y,p])=>[y,h(p)])):f;t=h(t);let d=f=>ze(_t(Vt(Se(f,n)))),g=t.value!==void 0?d(t.value):void 0,m=t.url!==void 0?d(t.url):void 0,u=t.action==="expectVisible"||t.action==="expectText"||t.action==="expectValue"||t.action==="expectMatches"||t.action==="expectAttribute"||t.action==="expectEach"||t.action==="captureText",S=t.target?Vn(e,t.target,n,u,!Hs.has(t.action)):[],x={timeout:r},R={timeout:Math.min(1e3,r)},$=f=>async()=>{for(let y of S)try{if(await f(y.first()))return!0}catch{}return!1};switch(t.action){case"goto":{if(!m)throw new Error("goto requires url");let f=/^https?:\/\//.test(m)?m:new URL(m,s).toString();await e.goto(f,x);return}case"click":return X(S,f=>f.click(x),!0);case"fill":return X(S,f=>f.fill(g??"",x),!0);case"press":return S.length>0?X(S,f=>f.press(g??"",x),!0):e.keyboard.press(g??"");case"selectOption":return X(S,async f=>{await f.selectOption(g??"",x)},!0);case"check":return X(S,f=>f.check(x),!0);case"uncheck":return X(S,f=>f.uncheck(x),!0);case"hover":return X(S,f=>f.hover(x),!0);case"waitFor":return S.length>0?X(S,f=>f.waitFor({state:"visible",timeout:r})):Wt(Math.min(Number(g??"0"),r));case"expectVisible":return c($(f=>f.isVisible()),r,"target to be visible");case"expectNotVisible":return c(async()=>{for(let f of S){let y=await f.count();for(let p=0;p<y;p++)if(await f.nth(p).isVisible())return!1}return!0},r,`every match of every recorded locator to be hidden (${S.length} locator(s))`);case"expectText":return c($(async f=>(await f.textContent(R)??"").includes(g??"")),r,`text "${g}"`);case"expectEach":{let f=t.each?.match(/^\{data:([^}]+)\}$/)?.[1];if(!f)throw new Error(`expectEach needs a {data:...} list reference, got ${JSON.stringify(t.each)}`);let y=je(f),p=async E=>new Set(await E.evaluate(w=>{let k=T=>(T??"").replace(/\s+/g," ").trim(),v=new Set;for(let T of Array.from(w.options??[]))v.add(k(T.textContent));for(let T of Array.from(w.querySelectorAll("*")))v.add(k(T.textContent));v.add(k(w.textContent));for(let T of String(w.innerText??"").split(`
|
|
15
|
+
`))v.add(k(T));return[...v]},void 0,R)),b=y;return c(async()=>{for(let E of S)try{let w=await p(E.first()),k=y.filter(v=>!w.has(v.replace(/\s+/g," ").trim()));if(k.length<b.length&&(b=k),k.length===0)return!0}catch{}return!1},r,`every value of ${t.each} to be shown`).catch(()=>{throw new Error(`${b.map(E=>`"${E}"`).join(", ")} from ${t.each} ${b.length===1?"is":"are"} not shown in the target (${y.length-b.length} of ${y.length} found)`)})}case"expectValue":return c($(async f=>await f.inputValue(R)===(g??"")),r,`input value "${g}"`);case"expectUrl":{let f=m??g??"";return c(async()=>e.url().includes(f),r,`URL containing "${f}" on the active page (${e.url()})`)}case"handleDialog":{let f=(g??"accept")!=="dismiss",y=t.promptText?d(t.promptText):void 0;e.once("dialog",p=>{f?p.accept(y):p.dismiss()});return}case"uploadFile":{let f=(g??"").split(`
|
|
16
|
+
`).filter(Boolean).map(y=>Ln.isAbsolute(y)?y:Ln.resolve(y));if(f.length===0)throw new Error("uploadFile requires a path");if(S.length>0)return X(S,y=>y.setInputFiles(f,x),!0);e.once("filechooser",y=>{y.setFiles(f)});return}case"dragTo":{if(!t.toTarget)throw new Error("dragTo requires toTarget");let f=Vn(e,t.toTarget,n,!1,!1);return X(S,y=>y.dragTo(f[0].first(),x),!0)}case"captureText":{if(!t.saveAs)throw new Error("captureText requires saveAs");return c($(async f=>{let y=qt(await f.textContent(R)??"");return y===""?!1:(o.set(t.saveAs,y),!0)}),r,`non-empty text to capture as "${t.saveAs}"`)}case"expectDiffers":{if(!t.compareTo)throw new Error("expectDiffers requires compareTo");let f=o.get(t.compareTo);if(f===void 0)throw new Error(`expectDiffers: no captured value named "${t.compareTo}"`);if(S.length>0)return c($(async b=>qt(await b.textContent(R)??"")!==f),r,`target text to differ from "${t.compareTo}" (${f})`);let y=g??"",p=o.get(y);if(p===void 0)throw new Error(`expectDiffers: no captured value named "${y}"`);if(p===f)throw new Error(`expectDiffers: "${y}" (${p}) equals "${t.compareTo}" (${f})`);return}case"expectAttribute":{if(!t.attribute)throw new Error("expectAttribute requires attribute");if(!t.pattern)throw new Error("expectAttribute requires pattern");let f=new RegExp(t.pattern,"i");return c($(async y=>f.test(await y.getAttribute(t.attribute,R)??"")),r,`attribute ${t.attribute} to match /${t.pattern}/i`)}case"expectMatches":{if(!t.pattern)throw new Error("expectMatches requires pattern");let f=new RegExp(t.pattern,"i");return c($(async y=>f.test(qt(await y.textContent(R)??""))),r,`target text to match /${t.pattern}/i`)}case"switchTab":{let f=Number.parseInt(g??"",10),y=()=>e.context().pages().filter(b=>!b.isClosed());await c(async()=>y().length>f,r,`tab ${g} to exist (${y().length} open: ${y().map(b=>b.url()).join(", ")})`);let p=y()[f];return await p.bringToFront(),p}case"closeTab":{let f=e.context().pages().filter(b=>!b.isClosed()),y=g===void 0?e:f[Number.parseInt(g,10)];if(!y)throw new Error(`tab ${g} does not exist (${f.length} open)`);await y.close();let p=e.context().pages().filter(b=>!b.isClosed());if(p.length===0)throw new Error("closed the last tab; nothing left to drive");return p[p.length-1]}case"newTab":{let f=await e.context().newPage();if(m){let y=/^https?:\/\//.test(m)?m:new URL(m,s).toString();await f.goto(y,x)}return f}case"waitForResponse":case"expectResponse":{if(!t.urlPattern)throw new Error(`${t.action} requires urlPattern`);let f=new RegExp(d(t.urlPattern)),y=t.pattern?new RegExp(d(t.pattern)):void 0;if(!i){await e.waitForResponse(b=>zn({seq:0,url:b.url(),method:b.request().method(),status:b.status()},f,t.method,t.status,void 0),x);return}let p=()=>t.action==="expectResponse"?i.all():i.sincePreviousStep();return c(async()=>p().some(b=>zn(b,f,t.method,t.status,y)),r,Ws(t,t.urlPattern))}default:throw new Error(`Unknown action type: ${t.action}`)}}var ht=(e,t)=>at(e.actions,t),qn=(e,t)=>Le(e.actions,t);function Jt(e,t){if(t.steps.length!==e.steps.length)return!1;for(let[n,r]of Object.entries(t.data??{})){let s;try{s=tt(n)}catch{continue}if(s===r)continue;let o=t.steps.some(a=>ht(a,`{data:${n}}`)),i=t.steps.some(a=>qn(a,r));if(!o||i)return!1}return t.steps.every((n,r)=>{let s=e.steps[r];if(n.gherkin!==s.text||n.kind!==s.kind)return!1;let o=n.table,i=s.table;if(!!o!=!!i)return!1;if(o&&i){let a=Object.keys(U(o)),c=Object.keys(U(i));if(a.length>0&&c.length>0){if(JSON.stringify(a)!==JSON.stringify(c))return!1;let l=U(o),h=U(i);for(let d of a){if(l[d]===h[d])continue;let g=`<${d}>`,m=t.steps.some(S=>ht(S,g)),u=t.steps.some(S=>qn(S,l[d]));if(!m||u)return!1}}else if(JSON.stringify(o)!==JSON.stringify(i))return!1}if(n.docString!==void 0!=(s.docString!==void 0))return!1;if(n.docString!==void 0&&s.docString!==void 0&&n.docString!==s.docString){let a=t.steps.some(l=>ht(l,"<docstring>")),c=t.steps.some(l=>ht(l,n.docString));if(!a||c)return!1}return!0})}function Kt(e,t){let n=e.steps[t],r=n?.resolvedTable??n?.table;return{...e.params,...le(e.steps),...U(r),...be(n?.resolvedDocString??n?.docString)}}async function Be(e,t,n,r={}){let s=r.actionTimeoutMs??5e3,o=r.retries??1,i=Math.max(10,r.pollIntervalMs??Bn),a=[],c=r.vars??new Map;r.uniqueSeed&&c.set(se,r.uniqueSeed);let l=()=>Object.fromEntries(c),h=n.steps.some(y=>y.actions.some(p=>(p.action==="waitForResponse"||p.action==="expectResponse")&&p.pattern!==void 0)),d=new Bt;d.attach(e.context(),h);let g=e,m=new Set(e.context().pages()),u=[],S=y=>u.push(y);e.context().on("page",S);let x=[],$=!n.steps.some(y=>y.actions.some(p=>p.opensTab))&&n.steps.some(y=>y.actions.some(p=>p.action==="switchTab"||p.action==="closeTab"||p.action==="newTab")),f=()=>{let y=e.context().pages();for(let p of y)m.has(p)||(m.add(p),p.isClosed()||(g=p));if(g.isClosed()){let p=y.filter(b=>!b.isClosed());p.length>0&&(g=p[p.length-1])}};if(!Jt(t,n))return d.detach(),{status:"stale",stepResults:a,captured:l()};try{for(let y=0;y<n.steps.length;y++){let p=n.steps[y],b=Kt(t,y);d.markStep();let E=!1,w=0;if(p.kind==="assertion"&&!p.actions.some(k=>re.has(k.action))){let k=`Assertion step "${p.gherkin}" recorded ${p.actions.length===0?"nothing":"only setup actions"}, so nothing was checked. Re-record the scenario (saffron run --rerecord) so the agent records what must be true.`;a.push({gherkin:p.gherkin,fromStepSet:p.fromStepSet,kind:p.kind,status:"failed",drift:E,error:k});for(let v=y+1;v<n.steps.length;v++)a.push({gherkin:n.steps[v].gherkin,kind:n.steps[v].kind,status:"skipped"});return{status:"failed",failure:{stepIndex:y,actionIndex:0,stepText:p.gherkin,kind:p.kind,error:k},stepResults:a,captured:l()}}for(let k=0;k<p.actions.length;k++){let v=p.actions[k];f(),v.pageFingerprint&&await we(g)!==v.pageFingerprint&&(E=!0);let T,P=!1;for(let I=0;I<=o&&!P;I++){I>0&&(w++,await Wt(250*I),f());try{let M=await Ht(g,v,b,s,r.baseURL,c,d,i);M&&(g=M,m.add(M));let A=v.action==="click"||v.action==="press";if(u.length===0&&(v.opensTab||A&&$)&&await e.context().waitForEvent("page",{timeout:v.opensTab?s:150}).catch(()=>{}),v.opensTab&&u.length===0)throw new Error("this action opened a new tab when it was recorded, and none opened now; the flow has changed");for(u.length>0&&x.push({stepIndex:y,actionIndex:k});u.length>0;)await u.shift().waitForLoadState("domcontentloaded",{timeout:s}).catch(()=>{});P=!0}catch(M){T=M}}if(!P){let I=T instanceof Error?T.message:String(T);a.push({gherkin:p.gherkin,fromStepSet:p.fromStepSet,kind:p.kind,status:"failed",drift:E,...w?{retries:w}:{},error:I});for(let A=y+1;A<n.steps.length;A++)a.push({gherkin:n.steps[A].gherkin,kind:n.steps[A].kind,status:"skipped"});let M={stepIndex:y,actionIndex:k,stepText:p.gherkin,kind:p.kind,error:I};return await r.onFailure?.(g,M).catch(()=>{}),{status:"failed",failure:M,stepResults:a,captured:l(),tabOpeners:x}}}a.push({gherkin:p.gherkin,fromStepSet:p.fromStepSet,kind:p.kind,status:"passed",drift:E,...w?{retries:w}:{}})}return{status:"passed",stepResults:a,captured:l(),tabOpeners:x}}finally{e.context().off("page",S),d.detach()}}import oe from"node:fs";import mt from"node:path";function Wn(e,t){oe.mkdirSync(mt.dirname(e),{recursive:!0}),oe.writeFileSync(e,`${JSON.stringify(t,null,2)}
|
|
17
|
+
`)}function ke(e){return JSON.parse(oe.readFileSync(e,"utf8"))}function ge(e){let t=mt.join(e,".saffron","proposals");if(!oe.existsSync(t))return[];let n=[];for(let r of oe.readdirSync(t)){let s=mt.join(t,r);if(oe.statSync(s).isDirectory())for(let o of oe.readdirSync(s)){if(!o.endsWith(".json"))continue;let i=mt.join(s,o);n.push({file:i,proposal:ke(i)})}}return n}function Hn(e,t){let n=ke(t),r=L(e,n.cache.feature,n.cache.scenario);return _e(r,n.cache),oe.rmSync(t),r}function Jn(e){oe.rmSync(e)}import yt from"node:fs";import Kn from"node:path";function Gn(e){return Kn.join(e,".saffron","history.jsonl")}function Yn(e,t,n,r){let s=e.map(o=>({feature:o.scenario.featurePath,scenario:o.scenario.displayName,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(`
|
|
18
|
+
`)[0]}));return{runId:t.toISOString(),startedAt:t.toISOString(),finishedAt:new Date().toISOString(),baseURL:r,green:s.filter(o=>o.status==="green").length,yellow:s.filter(o=>o.status==="yellow").length,red:s.filter(o=>o.status==="red").length,aiCalls:s.reduce((o,i)=>o+i.aiCalls,0),costUsd:s.reduce((o,i)=>o+i.costUsd,0),divergentSteps:n,scenarios:s}}function Qn(e,t){let n=Gn(e);yt.mkdirSync(Kn.dirname(n),{recursive:!0}),yt.appendFileSync(n,`${JSON.stringify(t)}
|
|
19
|
+
`)}function St(e,t=50){let n=Gn(e);if(!yt.existsSync(n))return[];let r=yt.readFileSync(n,"utf8").trim().split(`
|
|
20
|
+
`).filter(Boolean),s=[];for(let o of r.slice(-t))try{s.push(JSON.parse(o))}catch{}return s}var Gt=e=>{let t=e.green+e.yellow+e.red;return t===0?0:Math.round((e.green+e.yellow)/t*100)};function Zn(e,t){let n=[...e,t],r=n.slice(-20),s=n.slice(-10),o=e.at(-1),i=o?{passRatePp:Gt(t)-Gt(o),costUsd:t.costUsd-o.costUsd,aiCalls:t.aiCalls-o.aiCalls,red:t.red-o.red}:void 0,a=new Map;for(let d of s)for(let g of d.scenarios){let m=`${g.feature}::${g.scenario}`,u=a.get(m)??{feature:g.feature,scenario:g.scenario,heals:0,reds:0,runs:0};u.runs++,g.source==="agent-heal"&&g.status==="yellow"&&u.heals++,g.status==="red"&&u.reds++,a.set(m,u)}let c=[...a.values()].filter(d=>d.heals>=2||d.reds>=3).sort((d,g)=>g.heals+g.reds-(d.heals+d.reds)),l=new Map;for(let d of r)for(let g of d.scenarios)g.status==="red"&&g.error&&l.set(g.error,(l.get(g.error)??0)+1);let h=[...l.entries()].sort((d,g)=>g[1]-d[1]).slice(0,3).map(([d,g])=>({message:d,count:g}));return{prev:i,series:{passRate:r.map(Gt),costUsd:r.map(d=>Number(d.costUsd.toFixed(4))),aiCalls:r.map(d=>d.aiCalls)},chronic:c,divergentSteps:t.divergentSteps,topIssues:h}}var Ks=/^\s*(?:Scenario(?: Outline| Template)?|Example):\s*(.+?)\s*$/,Gs=/^\s*StepSet:/;function We(e,t){return ee.relative(e,t).split(ee.sep).join("/")}function Ys(e,t){let n={green:0,yellow:1,red:2};return!e||n[t]>n[e]?t:e}function Xn(e,t){return`${e} :: ${t}`}function bt(e,t,n={}){let r=t.features??"features",s=ee.isAbsolute(r)?r:ee.join(e,r),o=ee.join(e,".saffron","reports","latest.json"),i=ee.join(e,".saffron","reports","latest.html"),a;try{a=JSON.parse(J.readFileSync(o,"utf8"))}catch{a=void 0}let c=new Map;for(let p of a?.scenarios??[]){let b=p.scenario.replace(/ \(example \d+\)$/,""),E=Xn(p.feature,b);c.set(E,Ys(c.get(E),p.status))}let l=new Map,h;try{l=Q(pe(s),e)}catch(p){h=p instanceof Error?p.message:String(p)}let d=J.existsSync(s)?[...J.readdirSync(s,{recursive:!0})].map(String).filter(te).map(p=>ee.join(s,p)).sort():[],g=[],m=new Map,u=new Map,S={parsedFiles:new Set,owned:new Set,unreadable:h?[h]:[]};for(let p of d){let b=We(e,p),E="";try{E=J.readFileSync(p,"utf8")}catch(A){g.push({path:b,name:b,scenarios:[],stepSets:0,error:String(A)}),S.unreadable.push(`${b}: ${String(A)}`);continue}let w=E.split(`
|
|
21
|
+
`),k=new Map,v=0;w.forEach((A,me)=>{let ye=A.match(Ks);ye&&!k.has(ye[1])?k.set(ye[1],me+1):Gs.test(A)&&v++});let T=w.find(A=>/^\s*Feature:/.test(A)),P=T?T.replace(/^\s*Feature:\s*/,"").trim():b,I;try{I=W(p,e,l)}catch(A){g.push({path:b,name:P,scenarios:[],stepSets:v,error:h??(A instanceof Error?A.message:String(A))}),S.unreadable.push(`${b}: ${A instanceof Error?A.message:String(A)}`);continue}S.parsedFiles.add(p),u.set(p,I);let M=new Map;for(let A of I){S.owned.add(ve(e,A.featurePath,A.displayName));let me=M.get(A.name);if(me){me.rows+=1;continue}let ye=L(e,A.featurePath,A.name);S.owned.add(ye),S.owned.add(fe(e,A.featurePath,A.name));let Xe="missing";if(J.existsSync(ye))try{let Ne=z(ye);Xe=Ne&&Jt(A,Ne)?"valid":"stale"}catch{Xe="invalid"}M.set(A.name,{name:A.name,line:k.get(A.name),tags:[...A.tags],outline:Object.keys(A.params).length>0,rows:1,cached:Xe!=="missing",cacheState:Xe,proposal:J.existsSync(fe(e,A.featurePath,A.name)),lastStatus:c.get(Xn(A.featurePath,A.name))});for(let Ne of A.tags)m.set(Ne,(m.get(Ne)??0)+1)}g.push({path:b,name:P,scenarios:[...M.values()],stepSets:v})}let x=ge(e).map(({file:p,proposal:b})=>({file:We(e,p),feature:b.cache.feature,scenario:b.cache.scenario,mode:b.meta.mode,createdAt:b.meta.createdAt,verified:b.meta.verified,proofError:b.meta.proofError,adaptations:b.meta.adaptations??[],narrative:b.meta.narrative,suggestedFeatureEdit:b.meta.suggestedFeatureEdit,recordedFor:b.meta.recordedFor,aiCalls:b.meta.usage?.aiCalls??0,costUsd:b.meta.usage?.costUsd})).sort((p,b)=>p.file.localeCompare(b.file)),R;try{R=Z(e,r,l,u)}catch{R={steps:[],stepSets:[],scannedFiles:0,scannedCaches:0}}let $=Zs(e),f=St(e,n.historyLimit??30).map(p=>({startedAt:p.startedAt,green:p.green,yellow:p.yellow,red:p.red,aiCalls:p.aiCalls,costUsd:p.costUsd})),y=ee.join(e,"saffron.config.json");return{tool:"saffron",version:ue(),projectRoot:e,packageInstalled:J.existsSync(ee.join(e,"node_modules","saffron-ai")),config:{file:J.existsSync(y)?"saffron.config.json":void 0,effective:jn(t)},features:g,tags:[...m.entries()].map(([p,b])=>({tag:p,scenarios:b})).sort((p,b)=>p.tag.localeCompare(b.tag)),proposals:x,lastRun:a?{startedAt:a.startedAt,finishedAt:a.finishedAt,totals:a.totals,reportHtml:J.existsSync(i)?We(e,i):void 0,attention:a.scenarios.filter(p=>p.status!=="green").map(p=>({feature:p.feature,scenario:p.scenario,baseScenario:p.scenario.replace(/ \(example \d+\)$/,""),status:p.status,error:p.status==="red"?p.error?.split(`
|
|
22
|
+
`)[0]:void 0,failedStep:(p.steps??[]).find(b=>b.status==="failed")?.gherkin??p.evidence?.[0]?.step,evidence:(p.evidence??[]).filter(b=>J.existsSync(ee.join(e,b.file)))})).sort((p,b)=>p.status===b.status?0:p.status==="red"?-1:1)}:void 0,history:f,vocabulary:{steps:R.steps.length,recorded:R.steps.filter(p=>p.status==="recorded").length,unrecorded:R.steps.filter(p=>p.status==="unrecorded").length,stepSets:R.stepSets.length,divergent:R.steps.filter(p=>p.status==="divergent").map(p=>p.text),duplicateWordings:$.slice(0,50)},data:(()=>{let p=Pe(),b=[],E=new Set;for(let[w,k]of u)for(let v of k)for(let T of Ue(H(v)))if(!E.has(T)){E.add(T);try{nt(T)}catch(P){b.push({ref:T,reason:P instanceof Error?P.message:String(P),feature:We(e,w),scenario:v.name})}}return{dir:We(e,p.dir),env:p.env,files:J.existsSync(p.dir)?J.readdirSync(p.dir).filter(w=>/\.(json|csv)$/.test(w)).sort():[],unresolved:b}})(),orphans:(()=>{let p=ft(e,r,S);return p.unreadable.length?[]:p.orphans})()}}function tr(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(`
|
|
23
|
+
`)[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.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.toFixed(2)}`)}let s=e.vocabulary;console.log(`vocabulary: ${s.steps} steps (${s.recorded} recorded, ${s.unrecorded} unrecorded), ${s.stepSets} step sets, ${s.divergent.length} divergent, ${s.duplicateWordings.length} duplicate wording group(s)`),e.orphans.length&&console.log(`${e.orphans.length} recording(s) belong to no scenario: run \`saffron prune\` to see them`),(e.data.files.length||e.data.unresolved.length)&&console.log(`test data: ${e.data.files.length} file(s) in ${e.data.dir}/${e.data.env?` \xB7 environment "${e.data.env}"`:""}`+(e.data.unresolved.length?` \xB7 ${e.data.unresolved.length} reference(s) do not resolve: ${e.data.unresolved.map(o=>`{data:${o.ref}}`).join(", ")}`:"")),console.log(`config: ${e.config.file??"(defaults, no saffron.config.json)"}`)}var Qs=/^(<[^>]+>|\{env:[^}]+\}|\{date[^}]*\})$/;function er(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 Zs(e){let t;try{t=ne(e)}catch{return[]}let n=new Map;for(let r of t.steps.values()){if(r.actions.length===0)continue;let s=ct(r.gherkin).pattern,o=[...r.gherkin.matchAll(/"([^"]*)"/g)].map(d=>d[1]),i=d=>d!==void 0&&(o.includes(d)||Qs.test(d))?"\xABarg\xBB":d,a=r.actions.map(d=>{let{pageFingerprint:g,value:m,promptText:u,...S}=d;return{...S,value:i(m),promptText:i(u)}}),c=JSON.stringify(a),l=r.actions.map(d=>`${d.action}${er(d.target)?` ${er(d.target)}`:d.url?` ${d.url}`:""}`).join(" \xB7 "),h=n.get(c)??{steps:new Map,actions:l};h.steps.has(s)||h.steps.set(s,r.gherkin),n.set(c,h)}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 nr(e,t){let n=new Xs({name:"saffron",version:ue()},{capabilities:{tools:{}}});n.setRequestHandler(no,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, 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(to,async r=>ro(r.params.name,r.params.arguments,e,t)),await n.connect(new eo)}function ro(e,t,n,r){let s=o=>({content:[{type:"text",text:JSON.stringify(o,null,2)}]});if(e==="search_steps"){let o=Z(n,r),i=typeof t?.query=="string"?t.query:void 0,a=i?lt(o,i):o;return s({steps:a.steps,scannedFiles:a.scannedFiles,scannedCaches:a.scannedCaches})}if(e==="list_step_sets"){let o=Z(n,r);return s({stepSets:o.stepSets})}return e==="project_status"?s(bt(n,K(n))):{content:[{type:"text",text:`Unknown tool: ${e}`}],isError:!0}}import{query as so}from"@anthropic-ai/claude-agent-sdk";function oo(e,t){let n=t.steps.map(s=>`- [${s.status}] ${s.keyword} ${s.text}`).join(`
|
|
24
|
+
`),r=t.stepSets.map(s=>`- StepSet ${s.name}
|
|
25
|
+
${s.steps.map(o=>` ${o}`).join(`
|
|
22
26
|
`)}`).join(`
|
|
23
27
|
`);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:
|
|
24
|
-
${r}`:void 0,"","RULES:","1. Output ONLY the feature file content \u2014 no prose, no code fences, no explanations.","2. Gherkin/.saffron syntax: Feature:, Scenario:, Scenario Outline: + Examples, Given/When/Then/And/But. Prefer concrete scenarios; use an Outline only when the requirements list variations of the same flow.","3. Then steps are assertions \u2014 state exactly what must be true, one condition per step. End every scenario with at least one Then.","4. If the same 3+ step sequence would appear in two or more scenarios, define it once as a StepSet (first step a guard, last step an exit assertion) and invoke it. Definition uses a colon (StepSet: Name), invocation does not (StepSet Name).",'5. Use 2-column data tables for key/value input, header tables for lists of records, and """ doc strings for free text.',"6. Steps are natural language for an AI browser agent \u2014 never CSS selectors or code.","","REQUIREMENTS:",e.trim()].filter(
|
|
25
|
-
`)}async function
|
|
26
|
-
`,usage:r}}import
|
|
27
|
-
`),
|
|
28
|
-
`);return{contents:{kind:
|
|
28
|
+
${r}`:void 0,"","RULES:","1. Output ONLY the feature file content \u2014 no prose, no code fences, no explanations.","2. Gherkin/.saffron syntax: Feature:, Scenario:, Scenario Outline: + Examples, Given/When/Then/And/But. Prefer concrete scenarios; use an Outline only when the requirements list variations of the same flow.","3. Then steps are assertions \u2014 state exactly what must be true, one condition per step. End every scenario with at least one Then.","4. If the same 3+ step sequence would appear in two or more scenarios, define it once as a StepSet (first step a guard, last step an exit assertion) and invoke it. Definition uses a colon (StepSet: Name), invocation does not (StepSet Name).",'5. Use 2-column data tables for key/value input, header tables for lists of records, and """ doc strings for free text.',"6. Steps are natural language for an AI browser agent \u2014 never CSS selectors or code.","","REQUIREMENTS:",e.trim()].filter(s=>s!==void 0).join(`
|
|
29
|
+
`)}async function rr(e,t,n){let r={aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0},s="",o=so({prompt:oo(e,t),options:{model:n,maxTurns:1,permissionMode:"bypassPermissions",persistSession:!1,settingSources:[],allowedTools:[],systemPrompt:"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."}});for await(let i of o)if(i.type==="assistant")for(let a of i.message.content)a.type==="text"&&(s+=a.text);else i.type==="result"&&(r.aiCalls=i.num_turns,r.costUsd=i.total_cost_usd,"usage"in i&&i.usage&&(r.inputTokens=i.usage.input_tokens??0,r.outputTokens=i.usage.output_tokens??0,r.cacheReadTokens=i.usage.cache_read_input_tokens??0,r.cacheCreationTokens=i.usage.cache_creation_input_tokens??0));return s=s.replace(/^\s*```(?:gherkin|saffron)?\s*\n/,"").replace(/\n```\s*$/,"").trim(),{content:s+`
|
|
30
|
+
`,usage:r}}import ae from"node:fs";import{fileURLToPath as sr}from"node:url";import ie from"node:path";import{createConnection as io,ProposedFeatures as ao,TextDocuments as co,TextDocumentSyncKind as lo,CompletionItemKind as he,InsertTextFormat as or,DiagnosticSeverity as He,MarkupKind as ir}from"vscode-languageserver/node";import{TextDocument as po}from"vscode-languageserver-textdocument";var ar=/^(\s*)(Given|When|Then|And|But|\*)\s+(.+?)\s*$/,fo=/^\s*StepSet:\s*(.+?)\s*$/,Yt=/^(\s*)(StepSet)\s+([^\s:].*?)\s*$/,Qt={recorded:"\u25CF recorded \u2014 replays at zero tokens",divergent:"\u25CF divergent \u2014 same text, different recordings",unrecorded:"\u25CB written, not recorded yet"};function uo(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 go(e){try{return JSON.parse(ae.readFileSync(ie.join(e,"saffron.config.json"),"utf8"))}catch{return{}}}function ho(e){try{let t=JSON.parse(ae.readFileSync(ie.join(e,"saffron.config.json"),"utf8"));return typeof t.features=="string"?t.features:void 0}catch{return}}function pr(e,t,n={}){let r=e,s=t,o=io(ao.all,process.stdin,process.stdout),i=new co(po),a={steps:[],stepSets:[],scannedFiles:0,scannedCaches:0},c=new Map,l,h=()=>{try{let u=ie.isAbsolute(s)?s:ie.join(r,s),S=go(r);Ee(r,S.dataDir,process.env.SAFFRON_ENV??S.env),c=Q(pe(u),r),a=Z(r,s,c)}catch(u){o.console.warn(`saffron vocabulary rebuild: ${String(u)}`)}for(let u of i.all())m(u)},d=()=>{clearTimeout(l),l=setTimeout(h,300)};function g(u){return a.steps.find(S=>S.text===u)?.status}function m(u){let S=u.getText().split(`
|
|
31
|
+
`),x=So(S);if(!u.uri.endsWith(".saffron")){o.sendDiagnostics({uri:u.uri,diagnostics:x});return}let R=new Map;for(let $=0;$<S.length;$++){let f=S[$],y={start:{line:$,character:0},end:{line:$,character:f.length}},p=f.match(Yt);p&&!c.has(p[3])&&x.push({range:y,severity:He.Error,source:"saffron",message:`StepSet "${p[3]}" is not defined anywhere in the project.`});let b=f.match(fo);if(b){let k=c.get(b[1]),v=ie.relative(r,sr(u.uri)).replace(/\\/g,"/");(R.has(b[1])||k&&k.file!==v)&&x.push({range:y,severity:He.Error,source:"saffron",message:`StepSet "${b[1]}" is defined twice \u2014 set names are project-wide. If this line was meant to INVOKE the set, remove the colon: "StepSet ${b[1]}".`}),R.set(b[1],$)}let E=f.trim();if(E&&!p&&!b){for(let[k]of c)if(E.toLowerCase()===k.toLowerCase()){x.push({range:y,severity:He.Warning,source:"saffron",message:`Did you mean "StepSet ${k}"? Invoking a step set needs the StepSet keyword, like a step needs Given/When/Then.`});break}}let w=f.match(ar);if(w&&g(w[3])!=="recorded"){for(let k of a.steps)if(!(k.text===w[3]||k.status==="unrecorded")&&uo(k.text,w[3])>=.7){x.push({range:{start:{line:$,character:f.indexOf(w[3])},end:{line:$,character:f.length}},severity:He.Information,source:"saffron",message:`Similar to the ${k.status} step "${k.text}" (\xD7${k.usage}). Reusing the exact wording replays at zero tokens; a new wording costs a fresh AI recording.`});break}}}o.sendDiagnostics({uri:u.uri,diagnostics:x})}o.onInitialize(u=>{if(n.rootFromClient){let S=u.workspaceFolders?.[0]?.uri??u.rootUri??void 0;if(S&&S.startsWith("file:")){let x=sr(S);ae.existsSync(x)&&(r=x,s=ho(x)??t)}}return h(),{capabilities:{textDocumentSync:lo.Incremental,completionProvider:{triggerCharacters:[" ",":","."]},definitionProvider:!0,hoverProvider:!0}}}),o.onCompletion(u=>{let S=i.get(u.textDocument.uri);if(!S)return[];let x=S.getText({start:{line:u.position.line,character:0},end:u.position}),R=bo(x);return R||xo(S.uri,x,u.position.line,a)}),o.onDefinition(u=>{let S=i.get(u.textDocument.uri);if(!S)return;let x=S.getText({start:{line:u.position.line,character:0},end:{line:u.position.line+1,character:0}}).replace(/\n$/,""),R=cr(x,u.position.character);if(R){let b=yo(R.ref);return b?{uri:`file://${b.file}`,range:{start:{line:b.line,character:0},end:{line:b.line,character:0}}}:void 0}let $=lr(x,u.position.character);if($){let b=dr(r,$.name);return b?{uri:`file://${b.file}`,range:{start:{line:b.line,character:0},end:{line:b.line,character:0}}}:void 0}let f=x.match(Yt);if(!f)return;let y=c.get(f[3]);return y?{uri:`file://${ie.join(r,y.file)}`,range:{start:{line:y.line-1,character:0},end:{line:y.line-1,character:0}}}:void 0}),o.onHover(u=>{let S=i.get(u.textDocument.uri);if(!S)return;{let f=S.getText({start:{line:u.position.line,character:0},end:{line:u.position.line+1,character:0}}).replace(/\n$/,""),y=cr(f,u.position.character);if(y)return{contents:{kind:"markdown",value:fr(y.ref)}};let p=lr(f,u.position.character);if(p){let b=dr(r,p.name),E=b?`defined in ${ie.relative(r,b.file)} (line ${b.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:${p.name}}** ${E}.`}}}}let x=S.getText({start:{line:u.position.line,character:0},end:{line:u.position.line+1,character:0}}).replace(/\n$/,""),R=x.match(Yt);if(R){let f=a.stepSets.find(p=>p.name===R[3]);if(!f)return;let y=f.steps.map(p=>`- ${Qt[g(p)??"unrecorded"][0]} ${p}`).join(`
|
|
32
|
+
`);return{contents:{kind:ir.Markdown,value:`**StepSet ${f.name}** \u2014 expands to:
|
|
29
33
|
|
|
30
|
-
${
|
|
34
|
+
${y}`}}}let $=x.match(ar);if($){let f=a.steps.find(y=>y.text===$[3]);return f?{contents:{kind:ir.Markdown,value:`${Qt[f.status]}
|
|
31
35
|
|
|
32
|
-
Used in ${
|
|
36
|
+
Used in ${f.usage} place(s): ${f.files.join(", ")}${f.fromStepSet?`
|
|
33
37
|
|
|
34
|
-
Defined in StepSet **${
|
|
35
|
-
`).findIndex(
|
|
36
|
-
`)}));if(/^\s*
|
|
38
|
+
Defined in StepSet **${f.fromStepSet}**`:""}`}}:void 0}}),i.onDidOpen(u=>m(u.document)),i.onDidChangeContent(u=>m(u.document)),i.onDidSave(()=>d()),o.onDidChangeWatchedFiles(()=>d()),i.listen(o),o.listen()}function cr(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 mo=e=>/^\s*Examples:/.test(e);function fr(e,t=!1){let{env:n}=Pe(),r=n?` (environment "${n}")`:"";try{if(t||!e.includes(".")){let{headers:i,rows:a}=rt(e);return`**{data:${e}}** ${a.length} Examples row(s), columns ${i.map(c=>`\`${c}\``).join(", ")}${r}.`}let s=je(e);return Array.isArray(xe(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 yo(e){let{dir:t,env:n}=Pe(),[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=ie.join(t,c);if(!ae.existsSync(l))continue;let h=ae.readFileSync(l,"utf8").split(`
|
|
39
|
+
`),d=i?h.findIndex(g=>g.includes(`"${i}"`)):0;if(d>=0)return{file:l,line:d};a??={file:l,line:0}}return a}function So(e){let t=[];return e.forEach((n,r)=>{for(let s of n.matchAll(/\{data:([A-Za-z0-9_.-]+)\}/g)){let o=fr(s[1],mo(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:He.Error,source:"saffron",message:o.replace(/\*\*/g,"")})}}),t}function bo(e){let t=e.match(/\{data:([A-Za-z0-9_.-]*)$/);if(!t)return;let n=t[1],{dir:r}=Pe(),s=n.split(".");if(s.length===1)return(ae.existsSync(r)?[...new Set(ae.readdirSync(r).filter(i=>/\.(json|csv)$/.test(i)).map(i=>i.split(".")[0]))].sort():[]).map(i=>({label:i,kind:he.File,detail:"data file",insertText:i}));try{let o=xe(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"?he.Module:he.Value,detail:Array.isArray(a)?`list of ${a.length}`:a!==null&&typeof a=="object"?"object":JSON.stringify(a),insertText:i}))}catch{return[]}}function lr(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 dr(e,t){for(let n of[".env",".env.example"]){let r=ie.join(e,n);if(!ae.existsSync(r))continue;let o=ae.readFileSync(r,"utf8").split(`
|
|
40
|
+
`).findIndex(i=>new RegExp(`^\\s*(?:export\\s+)?${t}\\s*=`).test(i));if(o!==-1)return{file:r,line:o}}}function xo(e,t,n,r){let s=e.endsWith(".saffron");if(/^\s*StepSet\s+/.test(t)&&s)return r.stepSets.map(a=>({label:a.name,kind:he.Function,detail:`step set \xB7 ${a.steps.length} step(s) \xB7 \xD7${a.usage}`,documentation:a.steps.join(`
|
|
41
|
+
`)}));if(/^\s*(Given|When|Then|And|But|\*)\s+/.test(t))return r.steps.map((a,c)=>({label:a.text,kind:he.Text,detail:`${Qt[a.status]} \xB7 \xD7${a.usage}`,sortText:String(c).padStart(5,"0"),filterText:a.text}));let i=t.replace(/^\s*/,"").trimEnd().toLowerCase().replace(/\s+/g,"");if(i.length>0&&("stepset:".startsWith(i)||i.startsWith("stepset"))&&s){let a={start:{line:n,character:t.length-t.replace(/^\s*/,"").length},end:{line:n,character:t.length}},c=[{label:"StepSet: \u2026",kind:he.Keyword,detail:"define a reusable step set",documentation:`StepSet: Name
|
|
37
42
|
Given \u2026
|
|
38
43
|
When \u2026
|
|
39
44
|
|
|
40
|
-
Invoke it anywhere with: StepSet Name`,filterText:"step set stepset:",sortText:"0",insertTextFormat:
|
|
41
|
-
`),filterText:`step set ${
|
|
42
|
-
`)){let a=
|
|
43
|
-
`)}}}function
|
|
44
|
-
`)}var
|
|
45
|
-
`):void 0,featureEdits:
|
|
46
|
-
`)[0]})`:"")+". A row value is probably baked in as a literal instead of a <placeholder>; inspect the proposal, reject it, and re-record with saffron run --rerecord."}}console.log(` \u21BA pending proposal for "${t.displayName}" did not replay`+(
|
|
47
|
-
`)[0]})`:"")+"; recording again"),await
|
|
48
|
-
`)[0]}`}}if(
|
|
49
|
-
`)[0]}`}}}return await this.finalizeAgentRun(t,v,$,f,r,g,$?m?.failure:void 0)})();if(y.status==="red"){let m=b.find(S=>S.kind==="before-heal");if(y.source==="cache"&&m){let S=m.file.replace(/before-heal\.jpg$/,"failure.jpg");try{je.renameSync(ye.join(o,m.file),ye.join(o,S)),m.file=S}catch{}m.kind="failure"}else{let S=y.stepResults.find(g=>g.status==="failed")?.gherkin,$=await this.screenshot(ke(this.browser)??p,t,"failure",S);$&&b.push($)}}return b.length>0&&y.status!=="green"&&(y.evidence=b),y}finally{await u.close()}}async finalizeAgentRun(t,n,r,o,s,i=0,a){let c=r?"agent-heal":"agent-record",d=n.recordedSteps.map(w=>({gherkin:w.gherkin,kind:w.kind,status:n.success?"passed":"failed"}));if(!n.success)return{scenario:t,status:"red",source:c,stepResults:d,narrative:n.narrative,adaptations:n.adaptations,usage:n.usage,durationMs:Date.now()-s,error:n.narrative};let f=r?Kn(o.steps,n.recordedSteps,this.options.assertionPolicy==="adaptable-mid",a?{stepIndex:a.stepIndex,actionIndex:a.actionIndex}:void 0):n.recordedSteps,l=[...n.adaptations],h={...n.usage},u,p,b;if(this.options.verifyProposals!==!1){let w=await this.proofReplay(t,this.buildCandidateCache(t,f));try{if(w.result.status!=="passed"&&w.result.failure){let A=w.result.failure;if(this.options.agent&&!(r&&A.kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||Gn(o.steps,A.stepIndex))))try{let D=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:this.options.baseURL,mode:"refine",model:r?this.options.healModel:void 0,cdpEndpoint:this.cdpEndpoint,assertionPolicy:this.options.assertionPolicy,completedSteps:w.result.stepResults.filter(M=>M.status==="passed").map(M=>M.gherkin),failedStep:{text:A.stepText,kind:A.kind,error:A.error},onTabOpened:this.tabWatcher(),takeFingerprint:async()=>ue(ke(this.browser)??w.page)}));h=Yn(h,D.usage),D.success&&(l.push(...D.adaptations),f=r?Kn(f,D.recordedSteps,this.options.assertionPolicy==="adaptable-mid"):Gs(f,D.recordedSteps),await w.context.close(),w=await this.proofReplay(t,this.buildCandidateCache(t,f)))}catch{}}for(let A of w.result.tabOpeners??[]){let j=f[A.stepIndex]?.actions[A.actionIndex];j&&(j.opensTab=!0)}u=w.result.status==="passed",u||(p=w.result.failure?.error??`proof replay ${w.result.status}`,b=w.result.stepResults)}finally{await w.context.close().catch(()=>{})}}let k=[...n.featureEdits];for(let w of Qt(f,ee(this.options.projectRoot)))l.push(`duplicate wording: "${w.from}" recorded exactly the same actions as the existing step "${w.to}" (${w.feature} \u203A ${w.scenario}). Accept with --with-feature-edit to converge on the canonical wording.`),k.some(A=>A.index===w.index)||k.push({index:w.index,text:w.to});let y=Mn(f);y.length>0&&(u=!1,p=[p,...y].filter(Boolean).join(" "));let m=Ee(t),S=w=>m.size>0?xe(w,m):w;l=l.map(S);let $=k.map(w=>({index:w.index,text:S(w.text)})),g=S(n.narrative),v=n.suggestedFeatureEdit?S(n.suggestedFeatureEdit):void 0,R={meta:{createdAt:new Date().toISOString(),mode:r?"heal":"record",narrative:g,adaptations:l,suggestedFeatureEdit:v,featureEdits:$.length>0?$:void 0,verified:u,proofError:p?S(p):void 0,seededSteps:i>0?i:void 0,recordedFor:t.displayName,usage:h},cache:{version:1,feature:t.featurePath,scenario:t.name,recordedAt:new Date().toISOString(),recordedBy:"agent",steps:f}},x=ie(this.options.projectRoot,t.featurePath,t.name);mn(x,R);let T=B(L(this.options.projectRoot,t.featurePath,t.name));return{proposalDiff:Ze(T,R.cache),scenario:t,status:"yellow",source:c,stepResults:b??d,narrative:g,adaptations:l,suggestedFeatureEdit:v,featureEdits:$.length>0?$:void 0,verified:u,proofError:p,seededSteps:i>0?i:void 0,proposalFile:x,usage:h,durationMs:Date.now()-s}}};import sr from"node:path";import{createRequire as eo}from"node:module";import{query as to}from"@anthropic-ai/claude-agent-sdk";import{createSdkMcpServer as Ks,tool as $e}from"@anthropic-ai/claude-agent-sdk";import{z as P}from"zod";var V=e=>({content:[{type:"text",text:e}]});function Xn(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 Zn={role:P.string().optional().describe("ARIA role of the element"),name:P.string().optional().describe("Accessible name \u2014 use the SHORTEST stable substring; never include volatile content like prices or dates"),nameRegex:P.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:P.string().optional().describe("Form-label text for getByLabel \u2014 the literal <label> text only, never a free-text description"),text:P.string().optional().describe("getByText locator text"),selector:P.string().optional().describe("CSS fallback selector"),frame:P.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 er(e){return Ks({name:"saffron",version:"0.1.0",tools:[$e("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:P.number().int().min(0),text:P.string(),adaptation:P.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.")},async t=>(e.currentStepIndex=t.index,e.announced.add(t.index),t.adaptation&&e.adaptations.push(`Step ${t.index+1} ("${t.text}"): ${t.adaptation}`),V(`Recording step ${t.index}: ${t.text}`))),$e("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:P.string().describe("Name to store the captured text under"),...Zn},async t=>{let n=Xn(t);return n?(e.addActions([{action:"captureText",target:n,saveAs:t.saveAs}]),V(`Capture recorded as "${t.saveAs}".`)):V("ERROR: capture needs a target (role/name, nameRegex, label, text, or selector).")}),$e("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:P.boolean().describe("true = accept/OK the dialog, false = dismiss/cancel"),promptText:P.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}:{}}),V(`Dialog handling recorded (${t.accept?"accept":"dismiss"}).`))),$e("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:P.string().describe("Regex matched against the response URL \u2014 path-only for portability"),method:P.string().optional().describe("HTTP method to match (any if omitted)"),status:P.string().optional().describe("Expected status \u2014 exact ('201') or class ('2xx'); default any 2xx"),bodyPattern:P.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}:{}}]),V("Network wait recorded."))),$e("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:P.enum(["visible","notVisible","text","url","value","differs","matches","attribute","response"]),...Zn,expected:P.string().optional().describe("Expected text/value for kind=text|value \u2014 stable text only, never volatile values"),url:P.string().optional().describe("URL substring for kind=url (path only, no host)"),pattern:P.string().optional().describe("kind=matches|attribute: regex the target's text (or attribute) must match, e.g. 'NOK [\\\\d,]+' for a price"),attribute:P.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:P.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:P.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:P.string().optional().describe("kind=response: HTTP method to match (any if omitted)"),status:P.string().optional().describe("kind=response: expected status \u2014 exact ('201') or class ('2xx'); default any 2xx"),bodyPattern:P.string().optional().describe("kind=response: regex the response body must match (verify via browser_network_requests first)"),compareTo:P.string().optional().describe("kind=differs: name of the captured value to compare against")},async t=>{let n=Xn(t),r;switch(t.kind){case"visible":r={action:"expectVisible",target:n};break;case"notVisible":r={action:"expectNotVisible",target:n};break;case"text":r={action:"expectText",target:n,value:t.expected??""};break;case"value":r={action:"expectValue",target:n,value:t.expected??""};break;case"url":r={action:"expectUrl",url:t.url??""};break;case"differs":if(!t.compareTo)return V("ERROR: kind=differs requires compareTo.");if(!t.capture&&!n)return V("ERROR: kind=differs needs either capture (a stored name) or a target element.");r={action:"expectDiffers",target:n,value:t.capture,compareTo:t.compareTo};break;case"matches":if(!t.pattern)return V("ERROR: kind=matches requires pattern.");r={action:"expectMatches",target:n,pattern:t.pattern};break;case"attribute":if(!t.attribute||!t.pattern)return V("ERROR: kind=attribute requires attribute and pattern.");r={action:"expectAttribute",target:n,attribute:t.attribute,pattern:t.pattern};break;case"response":if(!t.urlPattern)return V("ERROR: kind=response requires urlPattern.");r={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?V("ERROR: assertion needs a target (role/name, nameRegex, label, text, or selector)."):(e.addActions([r]),V("Assertion recorded."))}),$e("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:P.boolean(),narrative:P.string().describe("2-4 sentence summary of the run: what happened, and why it failed if it did."),suggestedFeatureEdit:P.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:P.array(P.object({index:P.number().int().min(0).describe("zero-based step index"),text:P.string().describe("replacement step text WITHOUT the Given/When/Then keyword")})).optional().describe("Machine-applicable version of the suggested edits: one entry per adapted step. Provide this whenever you adapted a step.")},async t=>(e.done=!0,e.success=t.success,e.narrative=t.narrative,e.suggestedFeatureEdit=t.suggestedFeatureEdit,e.featureEdits=t.featureEdits??[],V("Run finalized.")))]})}function tr(e={}){let t=e.deliberateSnapshots?`
|
|
45
|
+
Invoke it anywhere with: StepSet Name`,filterText:"step set stepset:",sortText:"0",insertTextFormat:or.Snippet,textEdit:{range:a,newText:"StepSet: ${1:Name}\n "}}];r.stepSets.length===0&&c.push({label:"StepSet \u2026",kind:he.Keyword,detail:"invoke a step set (none defined yet)",filterText:"step set stepset",sortText:"1",insertTextFormat:or.Snippet,textEdit:{range:a,newText:"StepSet ${1:Name}"}});for(let l of r.stepSets)c.push({label:`StepSet ${l.name}`,kind:he.Function,detail:`invoke step set \xB7 ${l.steps.length} step(s)`,documentation:l.steps.join(`
|
|
46
|
+
`),filterText:`step set ${l.name}`,sortText:`1${l.name}`,textEdit:{range:a,newText:`StepSet ${l.name}`}});return c}return[]}import Ge from"node:fs";import _o from"node:net";import Te from"node:path";import{chromium as Fo,firefox as Io,webkit as Oo}from"playwright";var vo=5e3,wo=new Set(["click","press","selectOption","check","uncheck","hover","dragTo"]),xt=class{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){this.steps=t.steps.map(n=>({gherkin:n.text,keyword:n.keyword,kind:n.kind,table:n.table,docString:n.docString,fromStepSet:n.source?.fromStepSet,actions:[]}))}addArmedAction(t){if(this.done)return;let n=Math.max(this.currentStepIndex,0),r=this.steps[n];if(!r||r.actions.some(i=>i.action===t.action&&i.value===t.value&&i.promptText===t.promptText))return;let o=Math.max(r.actions.length-1,0);r.actions.splice(o,0,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<=vo;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;let n=Math.max(this.currentStepIndex,0),r=this.steps[n];if(!r)return;this.pendingFingerprint&&t[0]&&(t[0].pageFingerprint=this.pendingFingerprint,this.pendingFingerprint=void 0),r.actions.push(...t);let s=[...t].reverse().find(o=>wo.has(o.action));s&&(this.lastOpener=s,this.lastOpenerAt=Date.now(),this.pendingTabOpen&&(s.opensTab=!0,this.pendingTabOpen=!1,this.pendingTabFallback=void 0))}},$e=e=>e.replace(/\\(['"\\])/g,"$1");function ko(e){let t=e.match(/'((?:[^'\\]|\\.)*)'/);return t?$e(t[1]):void 0}function Zt(e){let t={},n=e.match(/(?:frameLocator\('((?:[^'\\]|\\.)*)'\)|locator\('((?:[^'\\]|\\.)*)'\)\.contentFrame\(\))/);n&&(t.frame=$e(n[1]??n[2]),e=e.slice((n.index??0)+n[0].length));let r=e.match(/getByRole\('([^']+)'(?:,\s*\{([^}]*)\})?\)/);if(r){t.role=r[1];let i=(r[2]??"").match(/name:\s*'((?:[^'\\]|\\.)*)'/);i&&(t.name=$e(i[1]))}let s=[[/getByLabel\('((?:[^'\\]|\\.)*)'\)/,"label"],[/getByText\('((?:[^'\\]|\\.)*)'\)/,"text"],[/getByTestId\('((?:[^'\\]|\\.)*)'\)/,"testId"],[/getByPlaceholder\('((?:[^'\\]|\\.)*)'\)/,"placeholder"]];for(let[i,a]of s){let c=e.match(i);c&&(t[a]=$e(c[1]))}let o=e.match(/(?:^|\.)locator\('((?:[^'\\]|\\.)*)'\)/);return o&&(t.fallbackSelectors=[$e(o[1])]),Object.keys(t).length>0?t:void 0}function $o(e,t){if(t&&e.startsWith(t)){let n=e.slice(t.length);return n.startsWith("/")?n:`/${n}`}return e}var To={click:"click",dblclick:"click",fill:"fill",pressSequentially:"fill",type:"fill",press:"press",check:"check",uncheck:"uncheck",hover:"hover",selectOption:"selectOption"};function Ro(e,t){let n=e.match(/page\.goto\('((?:[^'\\]|\\.)*)'\)/);if(n)return{action:"goto",url:$o($e(n[1]),t)};let r=e.match(/page\.keyboard\.press\('((?:[^'\\]|\\.)*)'\)/);if(r)return{action:"press",value:$e(r[1])};let s=e.match(/await\s+page\.(.+)\.dragTo\(page\.(.+?)\);?\s*$/);if(s){let g=Zt(s[1]),m=Zt(s[2]);if(g&&m)return{action:"dragTo",target:g,toTarget:m}}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=Zt(i);if(!l)return;let h={action:To[a],target:l},d=ko(c);return d!==void 0&&a!=="click"&&a!=="dblclick"&&(h.value=d),h}function ur(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)for(let i of o.split(`
|
|
47
|
+
`)){let a=Ro(i.trim(),t);a&&s.push(a)}return Ao(s)}function Ao(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 gr(e){let t=[];for(let n of e){if(n.kind==="assertion"&&n.actions.length===0){t.push(`Step "${n.gherkin}" is an assertion but recorded no check, so nothing would be verified. Re-record with: saffron run --rerecord`);continue}if(/"[^"]+"|<[^<>]+>/.test(n.gherkin)){for(let s of n.actions)if(s.action==="fill"&&(s.value??"")===""){t.push(`Step "${n.gherkin}" recorded a fill with an empty value although the step passes one; the typed value was lost. Re-record with: saffron run --rerecord`);break}}}return t}function Xt(e,t){let n=e;for(let[r,s]of Object.entries(t).filter(([,o])=>o.length>=3).sort((o,i)=>i[1].length-o[1].length))n=n.split(s).join(`<${r}>`);return n}function hr(e,t){let n=Object.entries(t).filter(([,i])=>i.length>=3);if(n.length===0)return e;let r=i=>i===void 0?void 0:Xt(i,t),s=[...n].sort((i,a)=>a[1].length-i[1].length),o=i=>{if(i!==void 0){for(let[a,c]of s)if(i.includes(c))return`<${a}>`;return i}};return e.map(i=>({...i,actions:i.actions.map(a=>{let c=re.has(a.action)&&a.action!=="expectValue";return{...a,value:c?o(a.value):r(a.value),url:r(a.url),target:a.target?{...a.target,name:c?o(a.target.name):r(a.target.name),label:r(a.target.label),text:c?o(a.target.text):r(a.target.text),placeholder:r(a.target.placeholder)}:void 0}})}))}function mr(e,t){let n=le(t.steps);return e.map((r,s)=>{let o=t.steps[s],i=o?.resolvedTable??o?.table,a=o?.resolvedDocString??o?.docString,c=Object.entries({...n,...U(i),...be(a)}).filter(([,h])=>h.length>=3).sort((h,d)=>d[1].length-h[1].length);if(c.length===0)return r;let l=h=>{if(h===void 0)return;let d=h;for(let[g,m]of c)d=d.split(m).join(`<${g}>`);return d};return{...r,actions:r.actions.map(h=>({...h,value:l(h.value),url:l(h.url),target:h.target?{...h.target,name:l(h.target.name),label:l(h.target.label),text:l(h.target.text),placeholder:l(h.target.placeholder)}:void 0}))}})}function yr(e,t=new Date){let n=r=>r===void 0?void 0:Dn(r,t);return e.map(r=>({...r,actions:r.actions.map(s=>({...s,value:n(s.value),url:n(s.url),target:s.target?{...s.target,name:n(s.target.name),nameRegex:n(s.target.nameRegex),label:n(s.target.label),text:n(s.target.text)}:void 0}))}))}function Sr(e,t){if(t.size===0)return e;let n=r=>r===void 0?void 0:Fe(r,t);return e.map(r=>({...r,actions:r.actions.map(s=>({...s,value:n(s.value),url:n(s.url),pattern:n(s.pattern),target:s.target?{...s.target,name:n(s.target.name),nameRegex:n(s.target.nameRegex),label:n(s.target.label),text:n(s.target.text),placeholder:n(s.target.placeholder)}:void 0}))}))}function br(e,t){if(t.size===0)return e;let n=r=>typeof r=="string"?Un(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 xr(e,t){if(t.size===0)return e;let n=r=>r===void 0?void 0:un(r,t);return e.map(r=>({...r,actions:r.actions.map(s=>({...s,value:n(s.value),url:n(s.url),pattern:n(s.pattern),target:s.target?{...s.target,name:n(s.target.name),nameRegex:n(s.target.nameRegex),label:n(s.target.label),text:n(s.target.text),placeholder:n(s.target.placeholder)}:void 0}))}))}function vr(e,t){if(e!=="mcp__playwright__browser_tabs")return;let n=t??{},r=typeof n.index=="number"?String(n.index):void 0;switch(n.action){case"select":return r===void 0?void 0:{action:"switchTab",value:r};case"close":return r===void 0?{action:"closeTab"}:{action:"closeTab",value:r};case"new":return typeof n.url=="string"&&n.url?{action:"newTab",url:n.url}:{action:"newTab"};default:return}}function wr(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=process.cwd()+"/";return{action:"uploadFile",value:r.map(i=>typeof i=="string"&&i.startsWith(s)?i.slice(s.length):i).join(`
|
|
48
|
+
`)}}}function Ke(e){return Array.isArray(e)?e.map(Ke):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,Ke(n)])):e}var Eo=e=>JSON.stringify(Ke(e));function en(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))en(s,t?`${t}.${r}`:r,n);else t&&(n[t]=String(e));return n}function Po(e,t){let n=en(Ke(e)),r=en(Ke(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 Tr(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 h=s.length-1;h>=0;h--)o[l][h]=r[l]===s[h]?o[l+1][h+1]+1:Math.max(o[l+1][h],o[l][h+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 kr(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 $r=e=>`${e.method??"any"} /${e.urlPattern}/ ${e.status??"2xx"}`+(e.pattern?` with a body matching /${e.pattern}/`:"");function Ie(e){let t=kr(e.target),n=e.value??"",r=(()=>{switch(e.action){case"goto":return`go to ${e.url}`;case"click":return`click ${t}`;case"fill":return`fill ${t} with "${n}"`;case"press":return t?`press ${n} on ${t}`:`press ${n}`;case"selectOption":return`select "${n}" in ${t}`;case"check":return`check ${t}`;case"uncheck":return`uncheck ${t}`;case"hover":return`hover ${t}`;case"waitFor":return t?`wait for ${t}`:`wait ${n}ms`;case"captureText":return`remember ${t} as "${e.saveAs}"`;case"handleDialog":return`${n} the dialog${e.promptText?` with "${e.promptText}"`:""}`;case"uploadFile":return`upload ${n}`;case"dragTo":return`drag ${t} onto ${kr(e.toTarget)}`;case"waitForResponse":return`wait for ${$r(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 ${$r(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 Je=e=>re.has(e.action);function jo(e,t){let n=Tr(e,t,Eo),r=[];for(let s=0;s<n.length;s++){let o=n[s];if(o.before&&o.after){r.push({change:"same",before:Ie(o.before),after:Ie(o.after),assertion:Je(o.after)});continue}let i=n[s+1];if(o.before&&i?.after&&!i.before){r.push({change:"changed",before:Ie(o.before),after:Ie(i.after),details:Po(o.before,i.after),assertion:Je(o.before)||Je(i.after)}),s++;continue}o.before&&r.push({change:"removed",before:Ie(o.before),assertion:Je(o.before)}),o.after&&r.push({change:"added",after:Ie(o.after),assertion:Je(o.after)})}return r}var Co=e=>`${e.kind}\0${e.gherkin}`;function vt(e,t){let n=Tr(e?.steps??[],t.steps,Co),r=[],s={added:0,removed:0,changed:0,assertions:0};for(let o of n){let i=o.after??o.before,a=jo(o.before?.actions??[],o.after?.actions??[]);for(let l of a)l.change==="added"?s.added++:l.change==="removed"?s.removed++:l.change==="changed"&&s.changed++,l.change!=="same"&&l.assertion&&s.assertions++;let c=e&&o.before?o.after?a.some(l=>l.change!=="same")?"changed":"same":"removed":"added";r.push({gherkin:i.gherkin,kind:i.kind,fromStepSet:i.fromStepSet,change:c,actions:a})}return{feature:t.feature,scenario:t.scenario,hasCommitted:e!==void 0,steps:r,summary:s}}function Rr(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("")}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.join(`
|
|
49
|
+
`)}var Oe={aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0};async function Do(){return new Promise((e,t)=>{let n=_o.createServer();n.listen(0,"127.0.0.1",()=>{let{port:r}=n.address();n.close(()=>e(r))}),n.on("error",t)})}function Ar(e){let t=st(H(e));return t.size>0?{data:Object.fromEntries([...t].sort(([n],[r])=>n.localeCompare(r)))}:{}}function De(e){let t=e.contexts().flatMap(n=>n.pages());return[...t].reverse().find(n=>n.url()!=="about:blank")??t.at(-1)}function Cr(e){let t=e.length;for(let n=e.length-1;n>=0&&e[n].kind==="assertion";n--)t=n;return t}function Er(e,t){return e[t]?.kind==="assertion"&&t>=Cr(e)}function Pr(e,t,n=!1,r){let s=Cr(e);return e.map((o,i)=>{let a=t[i],c=a&&a.actions.length>0;return o.kind==="assertion"?n&&i<s&&c?a:o:c?r&&i===r.stepIndex&&r.actionIndex>0?{...a,actions:[...o.actions.slice(0,r.actionIndex),...a.actions]}:a:o})}function Mo(e,t){return e.map((n,r)=>{let s=t[r];return s&&s.actions.length>0?s:n})}function jr(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 wt=class{constructor(t){this.options=t}options;browser;cdpEndpoint;stepIndex;get agent(){return this.options.agent}getStepIndex(){if(!this.stepIndex&&(this.stepIndex=ne(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){let r=this.getStepIndex(),s=t.steps.length,o={...t.params,...le(t.steps)},i=t.steps.map($=>{let f=r.steps.size>0?wn(r,$,o):void 0;return f?{gherkin:$.text,keyword:$.keyword,kind:$.kind,table:$.table,docString:$.docString,fromStepSet:$.source?.fromStepSet,actions:f.actions}:void 0}),a=t.steps.map($=>({gherkin:$.text,keyword:$.keyword,kind:$.kind,table:$.table,docString:$.docString,fromStepSet:$.source?.fromStepSet,actions:[]})),c=new Map;c.set(se,qe());let l=[],h=[],d=[],g=[],m={...Oe},u=0,S=0,x=0,R=$=>({success:$,narrative:h.join(" ")||"Composed entirely from seeded recordings.",adaptations:l,suggestedFeatureEdit:g.length>0?g.join(`
|
|
50
|
+
`):void 0,featureEdits:d,recordedSteps:a,announcedSteps:[],usage:m,seededCount:u});for(;x<s;){if(i[x]){let b=x;for(;b<s&&i[b];)b++;let E=i.slice(x,b),w={...t,steps:t.steps.slice(x,b)},k=await Be(n,w,this.buildCandidateCache(t,E),{baseURL:this.options.baseURL,actionTimeoutMs:this.options.actionTimeoutMs,retries:this.options.retries,pollIntervalMs:this.options.pollIntervalMs,vars:c}),v=k.status==="passed"?b-x:k.failure?.stepIndex??0;for(let P=0;P<v;P++)a[x+P]=E[P];if(u+=v,k.status==="passed"){x=b;continue}let T=x+v;l.push(`Seeded recording for "${t.steps[T].text}" did not replay in this scenario's context; the agent re-recorded it fresh. Divergence signal.`),i[T]=void 0,x=T;continue}if(!this.options.agent)return R(!1);S++;let $=x;for(;$<s&&!i[$];)$++;S>=3&&($=s);let f=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:this.options.baseURL,mode:"record",cdpEndpoint:this.cdpEndpoint,assertionPolicy:this.options.assertionPolicy,completedSteps:x>0?t.steps.slice(0,x).map(b=>b.resolvedText):void 0,recordOnly:$<s?{from:x,to:$-1}:void 0,uniqueSeed:c.get(se),onTabOpened:this.tabWatcher(),takeFingerprint:async()=>we(De(this.browser)??n)}));if(m=jr(m,f.usage),h.push(f.narrative),l.push(...f.adaptations),d.push(...f.featureEdits),f.suggestedFeatureEdit&&g.push(f.suggestedFeatureEdit),!f.success)return R(!1);let y=f.announcedSteps.filter(b=>b>=x&&b<s),p=Math.min(s-1,Math.max(y.length>0?Math.max(...y):$-1,x));for(let b=x;b<=p;b++)a[b]=f.recordedSteps[b];x=p+1}return R(!0)}async withDialogsVisible(t){let n=()=>{},r=[],s=[],o=i=>{i.on("dialog",n),r.push(i)};for(let i of this.browser?.contexts()??[]){i.on("page",o),s.push(i);for(let a of i.pages())o(a)}try{return await t()}finally{for(let i of s)i.off("page",o);for(let i of r)try{i.off("dialog",n)}catch{}}}async start(){let t=this.options.browser??"chromium";if(t==="chromium"){let n=await Do();this.browser=await Fo.launch({headless:!this.options.headed,args:[`--remote-debugging-port=${n}`]}),this.cdpEndpoint=`http://127.0.0.1:${n}`}else this.browser=await(t==="firefox"?Io:Oo).launch({headless:!this.options.headed}),this.cdpEndpoint=void 0}async stop(){await this.browser?.close(),this.browser=void 0}resolveStorageState(){if(!this.options.storageState)return;let t=Te.isAbsolute(this.options.storageState)?this.options.storageState:Te.join(this.options.projectRoot,this.options.storageState);if(!Ge.existsSync(t))throw new Error(`storageState file not found: ${t}. Generate one with: npx playwright open --save-storage=${this.options.storageState} <url>`);return t}buildCandidateCache(t,n){return{version:1,feature:t.featurePath,scenario:t.name,recordedAt:new Date().toISOString(),recordedBy:"agent",steps:n,...Ar(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){let r=await this.browser.newContext({storageState:this.resolveStorageState()}),s=await r.newPage();return{result:await Be(s,t,n,{baseURL:this.options.baseURL,actionTimeoutMs:this.options.actionTimeoutMs,retries:this.options.retries,pollIntervalMs:this.options.pollIntervalMs}),context:r,page:s}}async runScenario(t,n={}){let r=await this.runScenarioInner(t,n),s=Ve(t);if(s.size>0){let o=i=>i===void 0?i:Fe(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=>Fe(i,s));for(let i of r.stepResults)i.error=o(i.error)}return r}async screenshot(t,n,r,s){let o=this.options.screenshot??"viewport";if(o!=="off")try{let i=ve(this.options.projectRoot,n.featurePath,n.displayName);Ge.mkdirSync(i,{recursive:!0});let a=Te.join(i,`${r}.jpg`);return await t.screenshot({path:a,type:"jpeg",quality:80,fullPage:o==="full-page",timeout:5e3}),{kind:r,file:Te.relative(this.options.projectRoot,a).split(Te.sep).join("/"),step:s}}catch{return}}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=L(s,t.featurePath,t.name),h=z(l),d=fe(s,t.featurePath,t.name),g=!h&&Ge.existsSync(d)?ke(d):void 0,m=await this.browser.newContext({storageState:this.resolveStorageState()}),u=await m.newPage(),S=qe(),x=[];Ge.rmSync(ve(s,t.featurePath,t.displayName),{recursive:!0,force:!0});let R=($,f)=>this.screenshot($,t,"before-heal",f.stepText).then(y=>{y&&x.push(y)});try{let $=await(async()=>{let y;if(g){let k=await Be(u,t,g.cache,{baseURL:o,actionTimeoutMs:i,retries:a,pollIntervalMs:c}),v=g.meta.recordedFor??t.name;if(k.status==="passed")return{scenario:t,status:"yellow",source:"agent-record",stepResults:k.stepResults,narrative:`Replayed the pending proposal recorded for "${v}" at zero AI; accept it to go green.`,adaptations:[],verified:!0,proposalFile:d,usage:Oe,durationMs:Date.now()-r};if(Object.keys(t.params).length>0&&v!==t.displayName){let P=k.failure;return{scenario:t,status:"red",source:"agent-record",stepResults:k.stepResults,adaptations:[],proposalFile:d,usage:Oe,durationMs:Date.now()-r,error:`The pending proposal recorded for "${v}" does not replay for this Examples row`+(P?` (step "${P.stepText}": ${P.error.split(`
|
|
51
|
+
`)[0]})`:"")+". A row value is probably baked in as a literal instead of a <placeholder>; inspect the proposal, reject it, and re-record with saffron run --rerecord."}}console.log(` \u21BA pending proposal for "${t.displayName}" did not replay`+(k.failure?` (step "${k.failure.stepText}": ${k.failure.error.split(`
|
|
52
|
+
`)[0]})`:"")+"; recording again"),await u.goto("about:blank")}if(h&&(y=await Be(u,t,h,{baseURL:o,actionTimeoutMs:i,retries:a,pollIntervalMs:c,uniqueSeed:S,onFailure:R}),y.status==="passed"))return{scenario:t,status:"green",source:"cache",stepResults:y.stepResults,adaptations:[],usage:Oe,durationMs:Date.now()-r};if(!(this.options.agent!==void 0&&this.cdpEndpoint!==void 0&&!n.agentDisabled)){let k=this.options.agent!==void 0&&this.cdpEndpoint===void 0&&!n.agentDisabled?`recording/healing requires Chromium (the agent attaches over CDP). Record with --browser chromium (the default), then replay with --browser ${this.options.browser}.`:"no agent is configured.";return{scenario:t,status:"red",source:"cache",stepResults:y?.stepResults??[],adaptations:[],usage:Oe,durationMs:Date.now()-r,error:h?y?.status==="stale"?`Cache is stale (feature file changed) and ${k}`:`Replay failed and ${k} ${y?.failure?.error??""}`.trimEnd():`No cache exists and ${k}`}}let b=h!==void 0&&y!==void 0&&y.status==="failed",E=0,w;try{if(b)w=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:o,mode:"heal",model:this.options.healModel,cdpEndpoint:this.cdpEndpoint,assertionPolicy:this.options.assertionPolicy,completedSteps:y.stepResults.filter(k=>k.status==="passed").map(k=>k.gherkin),failedStep:{text:y.failure.stepText,kind:y.failure.kind,error:y.failure.error},uniqueSeed:S,onTabOpened:this.tabWatcher(),takeFingerprint:async()=>{let k=De(this.browser)??u;return we(k)}}));else if(await u.goto("about:blank"),this.options.reuseSteps!==!1){let k=await this.recordWithSeeding(t,u);E=k.seededCount,w=k}else w=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:o,mode:"record",cdpEndpoint:this.cdpEndpoint,assertionPolicy:this.options.assertionPolicy,uniqueSeed:S,onTabOpened:this.tabWatcher(),takeFingerprint:async()=>{let k=De(this.browser)??u;return we(k)}}))}catch(k){let v=k instanceof Error?k.message:String(k);return{scenario:t,status:"red",source:b?"agent-heal":"agent-record",stepResults:y?.stepResults??[],adaptations:[],usage:Oe,durationMs:Date.now()-r,error:`Agent invocation failed: ${v.split(`
|
|
53
|
+
`)[0]}`}}if(w.success&&b&&y.failure.kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||Er(h.steps,y.failure.stepIndex))){let k=h.steps[y.failure.stepIndex],v=De(this.browser)??u,T=new Map(Object.entries(y.captured)),P=Kt(t,y.failure.stepIndex);try{for(let I of k.actions)await Ht(v,I,P,this.options.actionTimeoutMs??5e3,o,T)}catch(I){let M=I instanceof Error?I.message:String(I);return{scenario:t,status:"red",source:"agent-heal",stepResults:y.stepResults,narrative:w.narrative,adaptations:w.adaptations,suggestedFeatureEdit:w.suggestedFeatureEdit,usage:w.usage,durationMs:Date.now()-r,error:`Assertion failed as written: "${k.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: ${M.split(`
|
|
54
|
+
`)[0]}`}}}return await this.finalizeAgentRun(t,w,b,h,r,E,b?y?.failure:void 0)})();if($.status==="red"){let y=x.find(p=>p.kind==="before-heal");if($.source==="cache"&&y){let p=y.file.replace(/before-heal\.jpg$/,"failure.jpg");try{Ge.renameSync(Te.join(s,y.file),Te.join(s,p)),y.file=p}catch{}y.kind="failure"}else{let p=$.stepResults.find(E=>E.status==="failed")?.gherkin,b=await this.screenshot(De(this.browser)??u,t,"failure",p);b&&x.push(b)}}let f=gt(H(t),S);return f.size>0&&($.uniques=Object.fromEntries(f)),x.length>0&&$.status!=="green"&&($.evidence=x),$}finally{await m.close()}}async finalizeAgentRun(t,n,r,s,o,i=0,a){let c=r?"agent-heal":"agent-record",l=n.recordedSteps.map(v=>({gherkin:v.gherkin,kind:v.kind,status:n.success?"passed":"failed"}));if(!n.success)return{scenario:t,status:"red",source:c,stepResults:l,narrative:n.narrative,adaptations:n.adaptations,usage:n.usage,durationMs:Date.now()-o,error:n.narrative};let h=r?Pr(s.steps,n.recordedSteps,this.options.assertionPolicy==="adaptable-mid",a?{stepIndex:a.stepIndex,actionIndex:a.actionIndex}:void 0):n.recordedSteps,d=[...n.adaptations],g={...n.usage},m,u,S;if(this.options.verifyProposals!==!1){let v=await this.proofReplay(t,this.buildCandidateCache(t,h));try{if(v.result.status!=="passed"&&v.result.failure){let T=v.result.failure;if(this.options.agent&&!(r&&T.kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||Er(s.steps,T.stepIndex))))try{let I=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:this.options.baseURL,mode:"refine",model:r?this.options.healModel:void 0,cdpEndpoint:this.cdpEndpoint,assertionPolicy:this.options.assertionPolicy,completedSteps:v.result.stepResults.filter(M=>M.status==="passed").map(M=>M.gherkin),failedStep:{text:T.stepText,kind:T.kind,error:T.error},uniqueSeed:v.result.captured[se],onTabOpened:this.tabWatcher(),takeFingerprint:async()=>we(De(this.browser)??v.page)}));g=jr(g,I.usage),I.success&&(d.push(...I.adaptations),h=r?Pr(h,I.recordedSteps,this.options.assertionPolicy==="adaptable-mid"):Mo(h,I.recordedSteps),await v.context.close(),v=await this.proofReplay(t,this.buildCandidateCache(t,h)))}catch{}}for(let T of v.result.tabOpeners??[]){let P=h[T.stepIndex]?.actions[T.actionIndex];P&&(P.opensTab=!0)}m=v.result.status==="passed",m||(u=v.result.failure?.error??`proof replay ${v.result.status}`,S=v.result.stepResults)}finally{await v.context.close().catch(()=>{})}}let x=[...n.featureEdits];for(let v of kn(h,ne(this.options.projectRoot)))d.push(`duplicate wording: "${v.from}" recorded exactly the same actions as the existing step "${v.to}" (${v.feature} \u203A ${v.scenario}). Accept with --with-feature-edit to converge on the canonical wording.`),x.some(T=>T.index===v.index)||x.push({index:v.index,text:v.to});let R=gr(h);R.length>0&&(m=!1,u=[u,...R].filter(Boolean).join(" "));let $=Ve(t),f=v=>$.size>0?Fe(v,$):v;d=d.map(f);let y=x.map(v=>({index:v.index,text:f(v.text)})),p=f(n.narrative),b=n.suggestedFeatureEdit?f(n.suggestedFeatureEdit):void 0,E={meta:{createdAt:new Date().toISOString(),mode:r?"heal":"record",narrative:p,adaptations:d,suggestedFeatureEdit:b,featureEdits:y.length>0?y:void 0,verified:m,proofError:u?f(u):void 0,seededSteps:i>0?i:void 0,recordedFor:t.displayName,usage:g},cache:{version:1,feature:t.featurePath,scenario:t.name,recordedAt:new Date().toISOString(),recordedBy:"agent",steps:h,...Ar(t)}},w=fe(this.options.projectRoot,t.featurePath,t.name);Wn(w,E);let k=z(L(this.options.projectRoot,t.featurePath,t.name));return{proposalDiff:vt(k,E.cache),scenario:t,status:"yellow",source:c,stepResults:S??l,narrative:p,adaptations:d,suggestedFeatureEdit:b,featureEdits:y.length>0?y:void 0,verified:m,proofError:u,seededSteps:i>0?i:void 0,proposalFile:w,usage:g,durationMs:Date.now()-o}}};import Nr from"node:path";import{createRequire as qo}from"node:module";import{query as Bo}from"@anthropic-ai/claude-agent-sdk";import{createSdkMcpServer as No,tool as Me}from"@anthropic-ai/claude-agent-sdk";import{z as _}from"zod";var q=e=>({content:[{type:"text",text:e}]});function _r(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 Fr={role:_.string().optional().describe("ARIA role of the element"),name:_.string().optional().describe("Accessible name \u2014 use the SHORTEST stable substring; never include volatile content like prices or dates"),nameRegex:_.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:_.string().optional().describe("Form-label text for getByLabel \u2014 the literal <label> text only, never a free-text description"),text:_.string().optional().describe("getByText locator text"),selector:_.string().optional().describe("CSS fallback selector"),frame:_.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 Ir(e){return No({name:"saffron",version:"0.1.0",tools:[Me("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:_.number().int().min(0),text:_.string(),adaptation:_.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.")},async t=>(e.currentStepIndex=t.index,e.announced.add(t.index),t.adaptation&&e.adaptations.push(`Step ${t.index+1} ("${t.text}"): ${t.adaptation}`),q(`Recording step ${t.index}: ${t.text}`))),Me("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:_.string().describe("Name to store the captured text under"),...Fr},async t=>{let n=_r(t);return n?(e.addActions([{action:"captureText",target:n,saveAs:t.saveAs}]),q(`Capture recorded as "${t.saveAs}".`)):q("ERROR: capture needs a target (role/name, nameRegex, label, text, or selector).")}),Me("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:_.boolean().describe("true = accept/OK the dialog, false = dismiss/cancel"),promptText:_.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}:{}}),q(`Dialog handling recorded (${t.accept?"accept":"dismiss"}).`))),Me("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:_.string().describe("Regex matched against the response URL \u2014 path-only for portability"),method:_.string().optional().describe("HTTP method to match (any if omitted)"),status:_.string().optional().describe("Expected status \u2014 exact ('201') or class ('2xx'); default any 2xx"),bodyPattern:_.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}:{}}]),q("Network wait recorded."))),Me("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:_.enum(["visible","notVisible","text","url","value","differs","matches","attribute","response","each"]),...Fr,expected:_.string().optional().describe("Expected text/value for kind=text|value \u2014 stable text only, never volatile values"),url:_.string().optional().describe("URL substring for kind=url (path only, no host)"),pattern:_.string().optional().describe("kind=matches|attribute: regex the target's text (or attribute) must match, e.g. 'NOK [\\\\d,]+' for a price"),attribute:_.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:_.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:_.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:_.string().optional().describe("kind=response: HTTP method to match (any if omitted)"),status:_.string().optional().describe("kind=response: expected status \u2014 exact ('201') or class ('2xx'); default any 2xx"),bodyPattern:_.string().optional().describe("kind=response: regex the response body must match (verify via browser_network_requests first)"),each:_.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:_.string().optional().describe("kind=differs: name of the captured value to compare against")},async t=>{let n=_r(t),r;switch(t.kind){case"visible":r={action:"expectVisible",target:n};break;case"notVisible":r={action:"expectNotVisible",target:n};break;case"text":r={action:"expectText",target:n,value:t.expected??""};break;case"value":r={action:"expectValue",target:n,value:t.expected??""};break;case"url":r={action:"expectUrl",url:t.url??""};break;case"differs":if(!t.compareTo)return q("ERROR: kind=differs requires compareTo.");if(!t.capture&&!n)return q("ERROR: kind=differs needs either capture (a stored name) or a target element.");r={action:"expectDiffers",target:n,value:t.capture,compareTo:t.compareTo};break;case"matches":if(!t.pattern)return q("ERROR: kind=matches requires pattern.");r={action:"expectMatches",target:n,pattern:t.pattern};break;case"attribute":if(!t.attribute||!t.pattern)return q("ERROR: kind=attribute requires attribute and pattern.");r={action:"expectAttribute",target:n,attribute:t.attribute,pattern:t.pattern};break;case"each":if(!t.each||!/^\{data:[^}]+\}$/.test(t.each))return q("ERROR: kind=each requires each='{data:file.list}', the token exactly as the step writes it (not the values).");r={action:"expectEach",target:n,each:t.each};break;case"response":if(!t.urlPattern)return q("ERROR: kind=response requires urlPattern.");r={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?q("ERROR: assertion needs a target (role/name, nameRegex, label, text, or selector)."):(e.addActions([r]),q("Assertion recorded."))}),Me("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:_.boolean(),narrative:_.string().describe("2-4 sentence summary of the run: what happened, and why it failed if it did."),suggestedFeatureEdit:_.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:_.array(_.object({index:_.number().int().min(0).describe("zero-based step index"),text:_.string().describe("replacement step text WITHOUT the Given/When/Then keyword")})).optional().describe("Machine-applicable version of the suggested edits: one entry per adapted step. Provide this whenever you adapted a step.")},async t=>(e.done=!0,e.success=t.success,e.narrative=t.narrative,e.suggestedFeatureEdit=t.suggestedFeatureEdit,e.featureEdits=t.featureEdits??[],q("Run finalized.")))]})}function Or(e={}){let t=e.deliberateSnapshots?`
|
|
50
55
|
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.
|
|
51
56
|
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.
|
|
52
57
|
|
|
@@ -61,45 +66,46 @@ Non-negotiable rules:
|
|
|
61
66
|
5a2. When a Then step quotes the expected text (or carries a <param> that resolves to it), pass EXACTLY that quoted text as the expected argument of saffron_assert. Replay checks containment, so the step's own wording is enough; never substitute the page's longer sentence, and never a value from a different Examples row.
|
|
62
67
|
5b. Literal ISO dates (YYYY-MM-DD) in recorded locators are auto-templated to {date\xB1N} relative to today, so date-picker recordings stay valid tomorrow. For non-ISO date formats in names, use nameRegex.
|
|
63
68
|
6. When all steps are done, call saffron_done exactly once. If you adapted steps, include BOTH suggestedFeatureEdit (human-readable corrected Gherkin) AND featureEdits (one {index, text} entry per adapted step, text without the keyword) so the correction can be applied automatically.
|
|
69
|
+
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.
|
|
64
70
|
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.
|
|
65
71
|
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.
|
|
66
72
|
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.
|
|
67
73
|
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.
|
|
68
|
-
7. Never ask the user questions; you are unattended.${t}`}function
|
|
69
|
-
${c.map(
|
|
70
|
-
`)}`),
|
|
74
|
+
7. Never ask the user questions; you are unattended.${t}`}function Uo(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"}function Dr(e){let{scenario:t}=e,n=t.steps.map((s,o)=>{let i=d=>ze(fn(ut(d,e.uniqueSeed??""))),a=`${o}. [${Uo(t.steps,o)}] ${s.keyword} ${i(s.resolvedText)}`,c=s.resolvedTable??s.table,l=s.resolvedDocString??s.docString,h=a;return c&&(h+=`
|
|
75
|
+
${c.map(d=>` | ${d.map(i).join(" | ")} |`).join(`
|
|
76
|
+
`)}`),l!==void 0&&(h+=`
|
|
71
77
|
"""
|
|
72
|
-
${i(
|
|
73
|
-
`).map(
|
|
78
|
+
${i(l).split(`
|
|
79
|
+
`).map(d=>` ${d}`).join(`
|
|
74
80
|
`)}
|
|
75
|
-
"""`),
|
|
81
|
+
"""`),h}).join(`
|
|
76
82
|
`),r=[`Feature: ${t.featureName} (${t.featurePath})`,`Scenario: ${t.displayName}`,e.baseURL?`Base URL: ${e.baseURL}`:void 0,"","Steps (index. [kind] keyword text):",n,""];if(e.mode==="refine")r.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.","",`Steps that replayed fine:
|
|
77
|
-
${(e.completedSteps??[]).map(
|
|
83
|
+
${(e.completedSteps??[]).map(s=>` \u2713 ${s}`).join(`
|
|
78
84
|
`)||" (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.");else if(e.mode==="heal")r.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.","",`Steps already completed by replay:
|
|
79
|
-
${(e.completedSteps??[]).map(
|
|
80
|
-
`)||" (none)"}`,"",`Failed step: [${e.failedStep?.kind}] ${e.failedStep?.text}`,`Failure: ${e.failedStep?.error}`,"","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)?",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.");else if(e.mode==="record"&&e.recordOnly){let{from:
|
|
85
|
+
${(e.completedSteps??[]).map(s=>` \u2713 ${s}`).join(`
|
|
86
|
+
`)||" (none)"}`,"",`Failed step: [${e.failedStep?.kind}] ${e.failedStep?.text}`,`Failure: ${e.failedStep?.error}`,"","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)?",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.");else if(e.mode==="record"&&e.recordOnly){let{from:s,to:o}=e.recordOnly;r.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):
|
|
81
87
|
${e.completedSteps.map(i=>` \u2713 ${i}`).join(`
|
|
82
|
-
`)}`:"You are starting from a blank page.","",`Record ONLY steps ${
|
|
83
|
-
`),"",`The browser currently shows the state after those ${
|
|
84
|
-
`)}import{query as
|
|
85
|
-
`),
|
|
86
|
-
`));return i}import
|
|
87
|
-
<path d="${
|
|
88
|
-
<path d="${
|
|
89
|
-
</svg>`}function
|
|
88
|
+
`)}`:"You are starting from a blank page.","",`Record ONLY steps ${s} through ${o} (inclusive).`,`CRITICAL STOP RULE: the steps AFTER step ${o} already have recordings and will be replayed automatically the moment you stop. After completing step ${o}, 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 s=e.completedSteps.length;r.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(o=>` \u2713 ${o}`).join(`
|
|
89
|
+
`),"",`The browser currently shows the state after those ${s} step(s) (verify with a snapshot if unsure). Do NOT redo them and do NOT navigate away from the current state.`,`Start with saffron_step for step index ${s} and record from there to the end.`)}else r.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 r.filter(s=>s!==void 0).join(`
|
|
90
|
+
`)}import{query as Lo}from"@anthropic-ai/claude-agent-sdk";var zo="usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET";async function tn(e,t=8e3){let n=e?.[zo];if(typeof n!="function")return;let r;try{let s=await Promise.race([n.call(e),new Promise(o=>{r=setTimeout(()=>o(void 0),t),r.unref?.()})]);return Vo(s)}catch{return}finally{r&&clearTimeout(r)}}function Vo(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 Mr(){let e=()=>{},t=new Promise(s=>e=s);async function*n(){await t}let r;try{let s=Lo({prompt:n(),options:{maxTurns:1,tools:[],settingSources:[],persistSession:!1}});r=s;let o=(async()=>{try{for await(let a of s);}catch{}})(),i=await tn(s);return e(),r.close?.(),await o,i}catch{e(),r?.close?.();return}}var Wo=qo(import.meta.url);function Ho(){let e=Wo.resolve("@playwright/mcp/package.json");return Nr.join(Nr.dirname(e),"cli.js")}var Jo=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"]),Ko=new Set(["mcp__playwright__browser_snapshot","mcp__playwright__browser_wait_for","mcp__playwright__browser_take_screenshot","mcp__playwright__browser_console_messages","mcp__playwright__browser_network_requests","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 Ur(e,t){if(Ko.has(e))return!1;if(e==="mcp__playwright__browser_tabs"){let n=t?.action;return!(n==="list"||n==="select"||n==="close")}return!0}var kt=class{constructor(t={}){this.opts=t}opts;planBefore;async planUsage(){if(!this.planBefore)return;let t=await this.planBefore;if(!t)return;let n=await Mr();return{subscriptionType:t.subscriptionType,fiveHourBefore:t.utilization,fiveHourAfter:n?.utilization,resetsAt:n?.resetsAt??t.resetsAt}}async run(t){let n=new xt(t.scenario),r={aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0},s="",o=Bo({prompt:Dr(t),options:{systemPrompt:Or({deliberateSnapshots:(this.opts.snapshotMode??"none")==="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:[],mcpServers:{playwright:{type:"stdio",command:process.execPath,args:[Ho(),"--cdp-endpoint",t.cdpEndpoint,"--snapshot-mode",this.opts.snapshotMode??"none","--image-responses","omit"]},saffron:Ir(n)},hooks:{PreToolUse:[{hooks:[async a=>{let c=a;if(n.beginToolCall(c.tool_use_id),Jo.has(c.tool_name)&&t.takeFingerprint&&!n.pendingFingerprint)try{n.pendingFingerprint=await t.takeFingerprint()}catch{}return{continue:!0}}]}],PostToolUse:[{hooks:[async a=>{let c=a,l=wr(c.tool_name,c.tool_input);l&&n.addArmedAction(l);let h=vr(c.tool_name,c.tool_input);return h&&n.addActions([h]),c.tool_name.startsWith("mcp__playwright__")&&(n.addActions(ur(c.tool_response,t.baseURL)),n.pendingFingerprint=void 0),n.endToolCall(c.tool_use_id,Ur(c.tool_name,c.tool_input)),{continue:!0}}]}],PostToolUseFailure:[{hooks:[async a=>{let c=a;return c.tool_name.startsWith("mcp__playwright__")&&(n.pendingFingerprint=void 0),n.endToolCall(c.tool_use_id,Ur(c.tool_name,c.tool_input)),{continue:!0}}]}]}}});this.planBefore||(this.planBefore=tn(o));let i=t.onTabOpened?.(()=>n.markTabOpened());try{for await(let a of o)a.type==="result"&&(r.aiCalls=a.num_turns,r.costUsd=a.total_cost_usd,"modelUsage"in a&&a.modelUsage&&(r.models=Object.keys(a.modelUsage)),"usage"in a&&a.usage&&(r.inputTokens=a.usage.input_tokens??0,r.outputTokens=a.usage.output_tokens??0,r.cacheReadTokens=a.usage.cache_read_input_tokens??0,r.cacheCreationTokens=a.usage.cache_creation_input_tokens??0),a.subtype==="success"&&(s=a.result))}catch(a){let c=a instanceof Error?a.message:String(a);n.done=!0,n.success=!1,n.narrative=`Agent session error: ${c}`}finally{i?.()}return n.done||(n.success=!1,n.narrative=n.narrative||`Agent session ended without finalizing the run. Last output: ${s.slice(0,500)}`),{success:n.success,narrative:n.narrative,adaptations:n.adaptations,suggestedFeatureEdit:n.suggestedFeatureEdit,featureEdits:n.featureEdits.map(a=>({index:a.index,text:Xt(a.text,t.scenario.params)})),recordedSteps:Sr(br(xr(yr(hr(mr(n.steps,t.scenario),t.scenario.params)),st(H(t.scenario))),gt(H(t.scenario),t.uniqueSeed??"")),Ve(t.scenario)),announcedSteps:[...n.announced].sort((a,c)=>a-c),usage:r}}};function $t(e){return`$${e.toFixed(e>=1?2:4)}`}function nn(e,t){let n=e===void 0?"?":`${Math.round(e)}%`,r=t===void 0?"?":`${Math.round(t)}%`;return`${n} \u2192 ${r}`}function Lr(e){return e.plan?` \xB7 5-hour window ${nn(e.plan.fiveHourBefore,e.plan.fiveHourAfter)} (${e.plan.subscriptionType} plan) \xB7 \u2248 ${$t(e.costUsd)} at API rates`:` \xB7 ${$t(e.costUsd)}`}function zr(e,t){return e?t?`\u2248 ${$t(e)}`:$t(e):""}function Vr(e){if(!e)return"";let t=new Date(e);return Number.isNaN(t.getTime())?"":`resets ${t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`}import qr from"node:fs";import Tt from"node:path";function Rt(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 Br(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 h=0;h<c.length;h++){let d=c[h],g=l[h];if(d.action!==g.action||re.has(d.action)||!d.target||!g.target)continue;let m=Rt(d.target),u=JSON.stringify(g.target);s.has(m)&&s.get(m)!==u&&r.add(m),s.set(m,u),m!==Rt(g.target)&&n.set(m,{from:d.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 Go(e){let t=Tt.join(e,".saffron","cache");if(!qr.existsSync(t))return[];let n=[];for(let r of qr.readdirSync(t,{recursive:!0})){let s=String(r);s.endsWith(".json")&&n.push(Tt.join(t,s))}return n}function Wr(e,t,n,r){if(t.length===0)return[];let s=new Map,o=new Set;for(let a of t){let c=Rt(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 Go(e)){if(Tt.resolve(a)===Tt.resolve(n))continue;let c=z(a);if(!c)continue;let l=[],h=!1;for(let d of c.steps){if(d.kind==="assertion")continue;let g=0;for(let m of d.actions){if(!m.target||re.has(m.action))continue;let u=s.get(Rt(m.target));u&&(g++,r||(m.target=structuredClone(u.to),h=!0))}g>0&&l.push({gherkin:d.gherkin,count:g})}l.length>0&&(h&&_e(a,c),i.push({file:a,scenario:c.scenario,feature:c.feature,steps:l}))}return i}function At(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 Hr from"node:fs";import Et from"node:path";function Jr(e,t,n,r,s){let o=W(Et.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 Kr(e,t,n,r,s,o){let i={applied:[],skipped:[],appliedIndices:[]},a=W(Et.join(e,t),e,s).find(d=>d.name===n);if(!a){for(let d of r)i.skipped.push({index:d.index,reason:`scenario "${n}" not found in ${t}`});return i}let c=new Map;for(let d of r){let g=a.steps[d.index]?.source;if(!g||g.fromBackground)continue;let m=`${g.file}:${g.line}`;c.set(m,(c.get(m)??new Set).add(d.text))}let l=new Map,h=new Set;for(let d of r){let g=a.steps[d.index];if(!g?.source){i.skipped.push({index:d.index,reason:`no step at index ${d.index}`});continue}if(o&&o[d.index]!==g.text){i.skipped.push({index:d.index,reason:`step ${d.index+1} now reads "${g.text}", not the "${o[d.index]??"(nothing)"}" this edit was written for`});continue}let{file:m,line:u,fromStepSet:S,fromBackground:x}=g.source;if(x){i.skipped.push({index:d.index,reason:`"${g.text}" is a Background step shared across scenarios; edit it manually`});continue}let R=`${m}:${u}`,$=c.get(R);if($.size>1){i.skipped.push({index:d.index,reason:`${R}${S?` (StepSet "${S}")`:""} is reached by several steps and the edits disagree: ${[...$].map(E=>`"${E}"`).join(" vs ")}. Decide the wording in the definition by hand`});continue}if(h.has(R)){i.appliedIndices.push(d.index);continue}let f=l.get(m);f||(f=Hr.readFileSync(Et.join(e,m),"utf8").split(`
|
|
91
|
+
`),l.set(m,f));let y=f[u-1],p=y?.match(/^(\s*)(\S+)\s+(.*)$/);if(!p||p[3]!==g.text){i.skipped.push({index:d.index,reason:`${m}:${u} no longer matches the recorded step text`});continue}let b=`${p[1]}${p[2]} ${d.text}`;f[u-1]=b,h.add(R),i.appliedIndices.push(d.index),i.applied.push({file:m,line:u,from:y.trim(),to:b.trim(),fromStepSet:S})}for(let[d,g]of l)i.applied.some(m=>m.file===d)&&Hr.writeFileSync(Et.join(e,d),g.join(`
|
|
92
|
+
`));return i}import sn from"node:fs";import on from"node:path";import Yo from"node:fs";import Qo from"node:path";var C=e=>e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',"""),Yr="M11 14 L10 4.5 L17.5 9.5 L24 2.5 L30.5 9.5 L38 4.5 L37 14 Z",Zo="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 Xo(e){return`<svg viewBox="0 0 48 48" width="${e}" height="${e}" aria-hidden="true">
|
|
93
|
+
<path d="${Yr}" fill="#F4A300"/>
|
|
94
|
+
<path d="${Zo}" fill="#E7E9EC"/>
|
|
95
|
+
</svg>`}function ei(e){return`<svg viewBox="8 1 32 15" height="${e}" aria-hidden="true"><path d="${Yr}" fill="#F4A300"/></svg>`}var ti={green:"passed",yellow:"pending review",red:"failed"};function Pt(e){return e>=1e3?`${(e/1e3).toFixed(1)}s`:`${e}ms`}function Ye(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e4?`${(e/1e3).toFixed(1)}k`:e.toLocaleString()}function ce(e,t,n,r="",s="",o=""){return`<div class="kpi">
|
|
90
96
|
<div class="kpi-label">${e}</div>
|
|
91
97
|
<div class="kpi-value ${r}">${t}</div>
|
|
92
|
-
<div class="kpi-sub ${
|
|
93
|
-
</div>`}function
|
|
94
|
-
${
|
|
95
|
-
${
|
|
96
|
-
${
|
|
97
|
-
${
|
|
98
|
-
${
|
|
99
|
-
${
|
|
100
|
-
${n.plan?
|
|
101
|
-
</section>`}function
|
|
102
|
-
`)}</section>`:""}function
|
|
98
|
+
<div class="kpi-sub ${s}">${n}</div>${o}
|
|
99
|
+
</div>`}function rn(e,t){if(e.length<2)return"";let n=108,r=22,s=Math.min(...e),i=Math.max(...e)-s||1,a=e.map((c,l)=>`${(l/(e.length-1)*n).toFixed(1)},${(r-2-(c-s)/i*(r-4)).toFixed(1)}`).join(" ");return`<svg class="spark" viewBox="0 0 ${n} ${r}" width="${n}" height="${r}" aria-hidden="true"><polyline points="${a}" fill="none" stroke="${t}" stroke-width="1.8" stroke-linejoin="round" stroke-linecap="round"/></svg>`}var Gr=(e,t="",n=0)=>`${e>=0?"+":"\u2212"}${Math.abs(e).toFixed(n)}${t} vs prev`;function ni(e,t){let n=e.totals,r=e.trends,s=n.scenarios===0?0:Math.round((n.green+n.yellow)/n.scenarios*100),o=n.red>0?"red":n.yellow>0?"gold":"green",i=n.inputTokens+n.outputTokens,a=r?.prev?`${Gr(r.prev.passRatePp,"pp")} \xB7 ${n.green+n.yellow} of ${n.scenarios}`:`${n.green+n.yellow} of ${n.scenarios} scenarios`,c=r?.prev?`${Gr(r.prev.costUsd,"",4).replace("+","+$").replace("\u2212","\u2212$")} \xB7 ${Pt(t)}`:`${Pt(t)} total runtime`;return`<section class="kpis">
|
|
100
|
+
${ce("pass rate",`${s}<span class="unit">%</span>`,a,o,r?.prev?r.prev.passRatePp>=0?"green":"red":"",rn(r?.series.passRate??[],"var(--green)"))}
|
|
101
|
+
${ce("passed",String(n.green),"deterministic replay","green",n.green>0?"green":"")}
|
|
102
|
+
${ce("pending",String(n.yellow),n.yellow>0?"\u25B2 proposals to review":"nothing to review",n.yellow>0?"gold":"",n.yellow>0?"gold":"")}
|
|
103
|
+
${ce("failed",String(n.red),n.red>0?"\u25BC needs attention":"all clear",n.red>0?"red":"",n.red>0?"red":"green")}
|
|
104
|
+
${ce("ai calls",String(n.aiCalls),`${Ye(i)} in+out tokens`,n.aiCalls>0?"":"green")}
|
|
105
|
+
${ce("cache traffic",Ye(n.cacheReadTokens+n.cacheCreationTokens),n.cacheReadTokens+n.cacheCreationTokens>0?`${Ye(n.cacheReadTokens)} read \xB7 ${Ye(n.cacheCreationTokens)} written`:"zero (fully cached run)","",n.cacheReadTokens+n.cacheCreationTokens>0?"":"green")}
|
|
106
|
+
${n.plan?ce("plan usage",`${nn(n.plan.fiveHourBefore,n.plan.fiveHourAfter)}`,[`5-hour window \xB7 ${n.plan.subscriptionType} plan`,Vr(n.plan.resetsAt)].filter(Boolean).join(" \xB7 "),"gold","")+ce("api-equivalent",`<span class="unit">\u2248 $</span>${n.costUsd.toFixed(n.costUsd>=1?2:4)}`,`what this run costs on an API key \xB7 ${c}`,"","",rn(r?.series.costUsd??[],"var(--gold)")):ce("ai cost",`<span class="unit">$</span>${n.costUsd.toFixed(n.costUsd>=1?2:4)}`,c,"","",rn(r?.series.costUsd??[],"var(--gold)"))}
|
|
107
|
+
</section>`}function ri(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>${C(r.feature)} \u203A ${C(r.scenario)}: ${r.heals} heal(s), ${r.reds} red(s) in the last ${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>${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>${r.count}\xD7: ${C(r.message)}</li>`).join("")}</ul></div>`),n.length>0?`<section class="trends">${n.join(`
|
|
108
|
+
`)}</section>`:""}function si(e){return`<ol class="steps">${e.steps.map(n=>{let r=n.status==="passed"?'<span class="dot green"></span>':n.status==="failed"?'<span class="dot red"></span>':'<span class="dot idle"></span>';return`<li class="step ${n.status}">
|
|
103
109
|
${r}
|
|
104
110
|
<div class="step-body">
|
|
105
111
|
<span class="step-text">${C(n.gherkin)}</span>
|
|
@@ -110,35 +116,36 @@ ${e.completedSteps.map(i=>` \u2713 ${i}`).join(`
|
|
|
110
116
|
${n.error?`<div class="step-error">${C(n.error)}</div>`:""}
|
|
111
117
|
</div>
|
|
112
118
|
</li>`}).join(`
|
|
113
|
-
`)}</ol>`}function
|
|
119
|
+
`)}</ol>`}function oi(e){return e.featureEdits&&e.featureEdits.length>0?`<div class="panel">
|
|
114
120
|
<div class="panel-title gold">suggested .feature edit</div>
|
|
115
121
|
<div class="diff">${e.featureEdits.map(n=>{let r=e.steps[n.index]?.gherkin??`step ${n.index}`;return`<div class="diff-line del">\u2212 ${C(r)}</div><div class="diff-line add">+ ${C(n.text)}</div>`}).join("")}</div>
|
|
116
122
|
<div class="panel-hint">apply with <code>saffron accept --with-feature-edit</code></div>
|
|
117
|
-
</div>`:e.suggestedFeatureEdit?`<div class="panel"><div class="panel-title gold">suggested .feature edit</div><pre>${C(e.suggestedFeatureEdit)}</pre></div>`:""}function
|
|
123
|
+
</div>`:e.suggestedFeatureEdit?`<div class="panel"><div class="panel-title gold">suggested .feature edit</div><pre>${C(e.suggestedFeatureEdit)}</pre></div>`:""}function ii(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> ':""}${C(c.gherkin)}${c.fromStepSet?` <span class="mono">(step set "${C(c.fromStepSet)}")</span>`:""}</div>`,h=c.actions.flatMap(d=>d.change==="same"?[`<div class="diff-line"> ${C(d.before??"")}</div>`]:d.change==="added"?[`<div class="diff-line add">+ ${C(d.after??"")}</div>`]:d.change==="removed"?[`<div class="diff-line del">\u2212 ${C(d.before??"")}</div>`]:[`<div class="diff-line del">\u2212 ${C(d.before??"")}</div>`,`<div class="diff-line add">+ ${C(d.after??"")}</div>`,...(d.details??[]).map(g=>`<div class="diff-line detail">${C(g)}</div>`)]).join("");return`${l}<div class="diff">${h}</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">${C(a)}</div></div>`}function ai(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=zr(e.usage.costUsd,t),s=r?` \xB7 ${r}`:"";return`<span class="pill gold">${e.usage.aiCalls} ai \xB7 ${Ye(n)} tok${s}</span>`}function ci(e,t,n){return`<details class="card" ${e.status!=="green"?"open":""}>
|
|
118
124
|
<summary>
|
|
119
|
-
<span class="pill ${e.status==="green"?"green":e.status==="yellow"?"gold":"red"}">${
|
|
125
|
+
<span class="pill ${e.status==="green"?"green":e.status==="yellow"?"gold":"red"}">${ti[e.status]}</span>
|
|
120
126
|
<span class="card-title">${C(e.scenario)}</span>
|
|
121
127
|
<span class="card-meta">
|
|
122
128
|
<span class="m">${C(e.feature)}</span>
|
|
123
129
|
<span class="m-sep">\xB7</span>
|
|
124
130
|
<span class="m">${C(e.source)}</span>
|
|
125
131
|
<span class="m-sep">\xB7</span>
|
|
126
|
-
<span class="m">${
|
|
127
|
-
${
|
|
132
|
+
<span class="m">${Pt(e.durationMs)}</span>
|
|
133
|
+
${ai(e,t)}
|
|
128
134
|
</span>
|
|
129
135
|
</summary>
|
|
130
136
|
<div class="card-body">
|
|
131
|
-
${
|
|
137
|
+
${si(e)}
|
|
132
138
|
${e.narrative?`<div class="panel"><div class="panel-title">agent narrative</div><p>${C(e.narrative)}</p></div>`:""}
|
|
133
139
|
${e.adaptations.length>0?`<div class="panel accent-gold"><div class="panel-title gold">adaptations</div><ul>${e.adaptations.map(r=>`<li>${C(r)}</li>`).join("")}</ul></div>`:""}
|
|
134
|
-
${
|
|
135
|
-
${
|
|
140
|
+
${oi(e)}
|
|
141
|
+
${ii(e)}
|
|
136
142
|
${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">${C(e.proposalFile)}</p>${e.verified===!1&&e.proofError?`<p class="mono" style="color:var(--red)">proof replay failed: ${C(e.proofError.split(`
|
|
137
143
|
`)[0])}</p>`:""}<div class="panel-hint">review with <code>saffron accept</code> / <code>saffron reject</code></div></div>`:""}
|
|
138
144
|
${e.error&&e.status==="red"?`<div class="panel accent-red"><div class="panel-title red">failure</div><p>${C(e.error)}</p></div>`:""}
|
|
139
|
-
${
|
|
145
|
+
${e.uniques&&e.status!=="green"?`<div class="panel"><div class="panel-title">unique values in this run</div>${Object.entries(e.uniques).map(([r,s])=>`<div class="mono">${C(r)} = ${C(s)}</div>`).join("")}</div>`:""}
|
|
146
|
+
${li(e,n)}
|
|
140
147
|
</div>
|
|
141
|
-
</details>`}function
|
|
148
|
+
</details>`}function li(e,t){let n=(e.evidence??[]).flatMap(r=>{if(!t)return[];try{let s=Yo.readFileSync(Qo.join(t,r.file)).toString("base64"),o=r.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>${C(o)}${r.step?`: <span class="mono">${C(r.step)}</span>`:""}</figcaption><a href="data:image/jpeg;base64,${s}" target="_blank" rel="noopener"><img alt="${C(o)}" src="data:image/jpeg;base64,${s}"/></a><div class="panel-hint">${C(r.file)}</div></figure>`]}catch{return[]}});return n.length===0?"":`<div class="panel ${e.status==="red"?"accent-red":"accent-gold"}"><div class="panel-title ${e.status==="red"?"red":"gold"}">screenshot</div>${n.join("")}</div>`}function Qr(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>
|
|
142
149
|
<html lang="en">
|
|
143
150
|
<head>
|
|
144
151
|
<meta charset="utf-8"/>
|
|
@@ -263,62 +270,62 @@ ${e.completedSteps.map(i=>` \u2713 ${i}`).join(`
|
|
|
263
270
|
<div class="wrap">
|
|
264
271
|
<header class="top">
|
|
265
272
|
<div class="brand">
|
|
266
|
-
${
|
|
273
|
+
${Xo(38)}
|
|
267
274
|
<div>
|
|
268
275
|
<div class="brand-name">saffron</div>
|
|
269
276
|
<div class="brand-sub">test run report</div>
|
|
270
277
|
</div>
|
|
271
278
|
</div>
|
|
272
279
|
<div class="run-meta">
|
|
273
|
-
<span>${C(
|
|
280
|
+
<span>${C(o)}</span>
|
|
274
281
|
<span>\xB7</span>
|
|
275
|
-
<span>${
|
|
282
|
+
<span>${Pt(s)}</span>
|
|
276
283
|
${e.baseURL?`<span class="chip base">${C(e.baseURL)}</span>`:""}
|
|
277
284
|
</div>
|
|
278
285
|
</header>
|
|
279
286
|
|
|
280
|
-
${
|
|
281
|
-
${
|
|
287
|
+
${ni(e,s)}
|
|
288
|
+
${ri(e)}
|
|
282
289
|
|
|
283
290
|
<div class="section-head">
|
|
284
291
|
<span class="section-title">scenarios \xB7 ${n.scenarios}</span>
|
|
285
292
|
<span class="section-title">saffron v${C(e.version)}</span>
|
|
286
293
|
</div>
|
|
287
|
-
${e.scenarios.map(i=>
|
|
294
|
+
${e.scenarios.map(i=>ci(i,!!e.totals.plan,t)).join(`
|
|
288
295
|
`)}
|
|
289
296
|
|
|
290
|
-
<footer>${
|
|
297
|
+
<footer>${ei(11)} generated by saffron v${C(e.version)} \xB7 ${C(new Date(e.finishedAt).toLocaleString("en-GB",{dateStyle:"medium",timeStyle:"medium"}))}</footer>
|
|
291
298
|
</div>
|
|
292
299
|
</body>
|
|
293
300
|
</html>
|
|
294
|
-
`}function
|
|
295
|
-
`),
|
|
296
|
-
`)}function
|
|
301
|
+
`}function Zr(e,t,n){let r={scenarios:e.length,green:0,yellow:0,red:0,aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0},s=new Set;for(let o of e){for(let i of o.usage.models??[])s.add(i);r[o.status]+=1,r.aiCalls+=o.usage.aiCalls,r.inputTokens+=o.usage.inputTokens,r.outputTokens+=o.usage.outputTokens,r.cacheReadTokens+=o.usage.cacheReadTokens,r.cacheCreationTokens+=o.usage.cacheCreationTokens??0,r.costUsd+=o.usage.costUsd??0}return s.size>0&&(r.models=[...s].sort()),{tool:"saffron",version:ue(),startedAt:t.toISOString(),finishedAt:new Date().toISOString(),baseURL:n,totals:r,scenarios:e.map(o=>({feature:o.scenario.featurePath,scenario:o.scenario.displayName,tags:[...o.scenario.tags],status:o.status,source:o.source,durationMs:o.durationMs,usage:o.usage,steps:o.stepResults,narrative:o.narrative,adaptations:o.adaptations,suggestedFeatureEdit:o.suggestedFeatureEdit,featureEdits:o.featureEdits,verified:o.verified,proofError:o.proofError,proposalFile:o.proposalFile,proposalDiff:o.proposalDiff,error:o.error,evidence:o.evidence,uniques:o.uniques}))}}function Xr(e,t){let n=on.join(e,".saffron","reports");sn.mkdirSync(n,{recursive:!0});let r=on.join(n,"latest.json"),s=on.join(n,"latest.html");return sn.writeFileSync(r,`${JSON.stringify(t,null,2)}
|
|
302
|
+
`),sn.writeFileSync(s,Qr(t,e)),{json:r,html:s}}function es(e){let t=e===void 0?[]:Array.isArray(e)?e:[e],n=new Set;for(let r of t)for(let s of r.split(/[\s,|]+/)){let o=s.trim();o&&n.add(o.startsWith("@")?o:`@${o}`)}return[...n]}function ts(e,t){return t.length===0?e:e.filter(n=>n.tags.some(r=>t.includes(r)))}function ns(e,t){return[...t??[],e]}import j from"node:fs";import O from"node:path";var Qe={claude:".claude/skills",agents:".agents/skills",copilot:".github/skills",cursor:".cursor/skills"},di=["claude","agents"],os="<!-- saffron:start -->",cn="<!-- saffron:end -->";function pi(){return[os,"## Saffron end-to-end tests","","UI tests are plain-Gherkin `.feature` / `.saffron` files under `features/`,","run by Saffron (`npx saffron run`). No step definitions exist: an AI agent","records each scenario once; later runs replay at zero tokens.","","- Load the `saffron` skill before writing or editing scenarios.","- Exact step text is the cache identity: run `npx saffron steps` and reuse"," recorded wordings instead of inventing synonyms.","- `Then` steps are never healed: write them as the verdict, last.","- `npx saffron status` shows what is cached, what awaits review, the tags"," and vocabulary health; editing a cached scenario's text re-records it.","- Never edit `.saffron/cache/` or `.saffron/proposals/` by hand; change the"," scenario text and re-run. Review proposals with `npx saffron accept`"," (`--all`, or chosen files) and `npx saffron reject`.","- Secrets go in `{env:VAR}` tokens, never in files.","- Shared test data (accounts, names, enum values) goes in `data/*.json`,",' referenced as `{data:file.path.key}`; check a whole list with "every',' {data:file.list}"; read Examples rows from a file with'," `Examples: {data:file}` (.saffron only). Use `{unique:name}` for a value"," that must be new on every run. Never put secrets in `data/`.",cn,""].join(`
|
|
303
|
+
`)}function rs(e,t){if(!j.existsSync(e))return j.writeFileSync(e,t),"created";let n=j.readFileSync(e,"utf8"),r=n.indexOf(os),s=n.indexOf(cn);if(r!==-1&&s!==-1&&s>r){let i=n.slice(0,r)+t.trimEnd()+n.slice(s+cn.length);return i===n?"unchanged":(j.writeFileSync(e,i),"updated")}let o=n.endsWith(`
|
|
297
304
|
`)?`
|
|
298
305
|
`:`
|
|
299
306
|
|
|
300
|
-
`;return
|
|
301
|
-
`),
|
|
302
|
-
`),n.scaffolded.push("saffron.config.json"));let
|
|
303
|
-
`).some(
|
|
307
|
+
`;return j.writeFileSync(e,n+o+t),"updated"}var an={command:"npx",args:["saffron","mcp"]},fi={claude:{file:".mcp.json",key:"mcpServers",entry:an},cursor:{file:".cursor/mcp.json",key:"mcpServers",entry:an},copilot:{file:".vscode/mcp.json",key:"servers",entry:{type:"stdio",...an}}},ss={agents:"codex mcp add saffron -- npx saffron mcp (Codex; other hosts: see their MCP settings)"};function ui(e,t){let n=O.join(e,t.file),r={},s=j.existsSync(n);if(s)try{r=JSON.parse(j.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,j.mkdirSync(O.dirname(n),{recursive:!0}),j.writeFileSync(n,JSON.stringify(r,null,2)+`
|
|
308
|
+
`),s?"updated":"created")}function is(e,t){j.mkdirSync(t,{recursive:!0});for(let n of j.readdirSync(e,{withFileTypes:!0})){let r=O.join(e,n.name),s=O.join(t,n.name);n.isDirectory()?is(r,s):j.copyFileSync(r,s)}}function as(e){let t=O.join(e.packageRoot,"skills","saffron");if(!j.existsSync(O.join(t,"SKILL.md")))throw new Error(`bundled skill not found at ${t}`);let n={skillDirs:[],instructionFiles:[],scaffolded:[],mcpFiles:[],mcpHints:[]},r=e.targets??di;for(let s of r){let o=O.join(e.projectRoot,Qe[s],"saffron");j.existsSync(o)&&j.rmSync(o,{recursive:!0,force:!0}),is(t,o),n.skillDirs.push(O.relative(e.projectRoot,o))}if(e.mcp!==!1)for(let s of r){let o=fi[s];o?n.mcpFiles.push({file:o.file,outcome:ui(e.projectRoot,o)}):ss[s]&&n.mcpHints.push(ss[s])}if(e.instructions!==!1){let s=pi(),o=O.join(e.projectRoot,"AGENTS.md");n.instructionFiles.push({file:"AGENTS.md",outcome:rs(o,s)});let i=O.join(e.projectRoot,"CLAUDE.md");j.existsSync(i)&&n.instructionFiles.push({file:"CLAUDE.md",outcome:rs(i,s)})}if(e.examples){n.examples=gi(e.projectRoot,e.packageRoot);for(let s of n.examples.files)n.scaffolded.push(s)}if(e.scaffold!==!1){let s=O.join(e.projectRoot,"saffron.config.json");j.existsSync(s)||(j.writeFileSync(s,JSON.stringify({baseURL:"http://localhost:3000",features:"features"},null,2)+`
|
|
309
|
+
`),n.scaffolded.push("saffron.config.json"));let o=O.join(e.projectRoot,"features");j.existsSync(o)||(j.mkdirSync(o,{recursive:!0}),n.scaffolded.push("features/"));let i=O.join(e.projectRoot,".gitignore"),a=e.examples?[".saffron/reports/",".saffron/artifacts/",".env"]:[".saffron/reports/",".saffron/artifacts/"],c=j.existsSync(i)?j.readFileSync(i,"utf8"):"",l=[];for(let h of a)c.split(`
|
|
310
|
+
`).some(d=>d.trim()===h)||(c+=(c&&!c.endsWith(`
|
|
304
311
|
`)?`
|
|
305
|
-
`:"")+
|
|
306
|
-
`,
|
|
307
|
-
`)}function
|
|
308
|
-
`))}async function
|
|
309
|
-
`)[0]}`),
|
|
310
|
-
${
|
|
311
|
-
${
|
|
312
|
+
`:"")+h+`
|
|
313
|
+
`,l.push(h));l.length>0&&(j.writeFileSync(i,c),n.scaffolded.push(`.gitignore (+ ${l.join(", ")})`))}return n}function gi(e,t){let n=O.join(t,"templates","saucedemo");if(!j.existsSync(O.join(n,"features")))return{installed:!1,files:[],reason:`bundled examples not found at ${n}`};let r=O.join(e,"features");if(j.existsSync(r)&&j.readdirSync(r).length>0)return{installed:!1,files:[],reason:"features/ is not empty; examples are only installed into an empty features directory"};let s=[];j.mkdirSync(r,{recursive:!0});for(let c of j.readdirSync(O.join(n,"features")))j.copyFileSync(O.join(n,"features",c),O.join(r,c)),s.push(`features/${c}`);let o=O.join(n,"data");if(j.existsSync(o)){j.mkdirSync(O.join(e,"data"),{recursive:!0});for(let c of j.readdirSync(o)){let l=O.join(e,"data",c);j.existsSync(l)||(j.copyFileSync(O.join(o,c),l),s.push(`data/${c}`))}}let i=O.join(e,"saffron.config.json");j.existsSync(i)||(j.copyFileSync(O.join(n,"saffron.config.json"),i),s.push("saffron.config.json (baseURL https://www.saucedemo.com, retries 1)"));let a=O.join(e,".env.example");return j.existsSync(a)||(j.copyFileSync(O.join(n,".env.example"),a),s.push(".env.example")),{installed:!0,files:s}}import hi from"node:path";function cs(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?hi.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(`
|
|
314
|
+
`)}function ls(e,t){let n=t.length>0?t:["features"],r=[];for(let s of n){let o=F.isAbsolute(s)?s:F.join(e,s);if(B.existsSync(o))if(B.statSync(o).isDirectory())for(let i of B.readdirSync(o,{recursive:!0})){let a=String(i);te(a)&&r.push(F.join(o,a))}else te(o)&&r.push(o)}return r.sort()}function jt(e,t,n){let r=F.isAbsolute(t.features??"features")?t.features:F.join(e,t.features??"features"),s=new Set(pe(r));for(let o of n)o.endsWith(".saffron")&&s.add(o);return Q([...s].sort(),e)}function bi(){let e=process.env.ANTHROPIC_API_KEY||process.env.CLAUDE_CODE_OAUTH_TOKEN||process.env.CLAUDE_CODE_USE_BEDROCK||process.env.CLAUDE_CODE_USE_VERTEX,t=process.env.HOME??"",n=t&&(B.existsSync(F.join(t,".claude",".credentials.json"))||B.existsSync(F.join(t,".claude.json")));e||n||console.error(["note: no Claude credentials detected. Cached scenarios replay fine","without AI, but recording and healing need one of:"," \xB7 ANTHROPIC_API_KEY=sk-ant-... (console.anthropic.com \u2192 API keys)"," \xB7 a Claude Code login on this machine","Replay-only runs: add --no-agent to silence this note.",""].join(`
|
|
315
|
+
`))}async function xi(e){let t=yi.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 Ze(e){console.error(`saffron: ${e.message}`),process.exit(2)}function ln(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e4?`${(e/1e3).toFixed(1)}k`:e.toLocaleString()}var vi={green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m"},wi="\x1B[0m",D=new Si().name("saffron").description("Gherkin-native AI-fallback test runner: zero-token cached replay, runtime AI healing.").version(ue()).option("-p, --project-root <dir>","project root",process.cwd());D.command("run").description("Run feature files (cached replay; AI records/heals on demand)").argument("[paths...]","feature files or directories (default: features/)").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 carrying any of these @tags: comma-separated ("@smoke,@WA-TC1") or repeat the flag',ns).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 (the honest fix for a wrong recording)").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>",'replay browser: "chromium" (default), "firefox", or "webkit", recording/healing always use Chromium').option("--heal-model <model>","cheaper model for heal sessions").option("--workers <n>","parallel replay workers (agent recording/healing stays sequential)").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=F.resolve(D.opts().projectRoot),r=K(n);t.env&&Ee(n,r.dataDir,t.env);let s=t.baseUrl??r.baseURL,o=ls(n,e.length>0?e:r.features?[r.features]:[]);o.length===0&&(console.error("No .feature/.saffron files found."),process.exit(2)),t.agent!==!1&&bi();let i;try{let w=jt(n,r,o);i=o.flatMap(k=>W(k,n,w))}catch(w){throw w instanceof N&&Ze(w),w}let a=es(t.filter);if(a.length>0&&(i=ts(i,a),i.length===0&&(console.error(`No scenarios match --filter ${a.join(",")} in ${o.length} feature file(s).`),process.exit(2))),t.rerecord){t.agent===!1&&(console.error("saffron: --rerecord needs the agent; drop --no-agent"),process.exit(2));let w=0;for(let k of i){let v=L(n,k.featurePath,k.name);B.existsSync(v)&&(B.rmSync(v),w++)}console.log(`rerecord: removed ${w} cache file(s) for ${i.length} scenario(s); the agent records them fresh (seeded from the other recordings). Restore with git if needed.`)}{let w=i;try{let v=ls(n,[]),T=jt(n,r,v);w=v.flatMap(P=>{try{return W(P,n,T)}catch{return[]}})}catch{}let k=Sn(n,w);if(k.length>0){console.error("cache path collision:");for(let v of k)console.error(` ${v}`);process.exit(2)}}{let w=new Map;for(let v of i){let T=H(v),P=z(L(n,v.featurePath,v.name));P&&T.push(JSON.stringify(P.steps));for(let I of Ut(T))process.env[I]===void 0&&!w.has(I)&&w.set(I,v.displayName)}let k=new Map;for(let v of i)for(let T of Ue(H(v)))if(!k.has(T))try{nt(T)}catch(P){k.set(T,`${P instanceof Error?P.message:String(P)} (used by "${v.displayName}")`)}if(k.size>0){for(let v of k.values())console.error(v);process.exit(2)}if(w.size>0){for(let[v,T]of w)console.error(`missing environment variable ${v} (referenced as {env:${v}} by "${T}")`);console.error("set the variable(s), or add them to a git-ignored .env in the project root"),process.exit(2)}}let c=new wt({projectRoot:n,baseURL:s,headed:t.headed,actionTimeoutMs:r.actionTimeoutMs,pollIntervalMs:r.pollIntervalMs,screenshot:r.screenshot,retries:r.retries,storageState:t.storageState??r.storageState,browser:(()=>{let w=t.browser??r.browser??"chromium";return w!=="chromium"&&w!=="firefox"&&w!=="webkit"&&(console.error(`invalid --browser "${w}": use "chromium", "firefox", or "webkit"`),process.exit(2)),w})(),healModel:t.healModel??r.healModel,verifyProposals:t.verify===!1?!1:r.verifyProposals,reuseSteps:t.reuse===!1?!1:r.reuseSteps,assertionPolicy:(()=>{let w=t.assertionPolicy??r.assertionPolicy??"strict";return w!=="strict"&&w!=="adaptable-mid"&&(console.error(`invalid --assertion-policy "${w}": use "strict" or "adaptable-mid"`),process.exit(2)),w})(),agent:t.agent?new kt({model:t.model??r.model,maxTurns:r.maxTurns,snapshotMode:r.snapshotMode}):void 0}),l=new Date,h=Math.max(1,Number.parseInt(String(t.workers??r.workers??1),10)||1),d=new Array(i.length),g=w=>{let k=w.scenario,v=vi[w.status],T=w.usage.inputTokens+w.usage.outputTokens,P=w.usage.cacheReadTokens+w.usage.cacheCreationTokens,I=P>0?`, ${ln(P)} cache traffic`:"";console.log(`${v}${w.status.toUpperCase().padEnd(7)}${wi}${k.displayName} (${w.source}, ${w.durationMs}ms, ${w.usage.aiCalls} AI calls, ${T} tokens${I})`);for(let A of w.adaptations)console.log(` \u26A0 ${A}`);w.seededSteps&&console.log(` \u26A1 ${w.seededSteps}/${w.stepResults.length} steps seeded from existing recordings (zero AI)`);let M=w.stepResults.reduce((A,me)=>A+(me.retries??0),0);M&&console.log(` \u21BB ${M} action ${M===1?"retry":"retries"} absorbed before settling (retries: ${r.retries??1} per action)`),w.verified===!0?console.log(" \u2713 proposal verified by zero-AI proof replay"):w.verified===!1&&console.log(` \u2717 proposal UNVERIFIED, proof replay failed: ${w.proofError?.split(`
|
|
316
|
+
`)[0]}`),w.error&&console.log(` ${w.error}`)};await c.start();try{if(h>1&&i.length>1){let w=i.map((v,T)=>({s:v,i:T})),k=[];await Promise.all(Array.from({length:Math.min(h,w.length)},async()=>{for(;;){let v=w.shift();if(!v)return;let T=await c.runScenario(v.s,{agentDisabled:!0});T.status==="red"?k.push(v):(d[v.i]=T,g(T))}}));for(let v of k.sort((T,P)=>T.i-P.i)){let T=await c.runScenario(v.s);d[v.i]=T,g(T)}}else for(let w=0;w<i.length;w++){let k=await c.runScenario(i[w]);d[w]=k,g(k)}}finally{await c.stop()}let m=Zr(d,l,s),u=ne(n).divergent.length,S=Yn(d,l,u,s),x=St(n);m.trends=Zn(x,S),Qn(n,S),m.totals.aiCalls>0&&(m.totals.plan=await c.agent?.planUsage?.());let{html:R,json:$}=Xr(n,m),f=m.totals,y=f.cacheReadTokens+f.cacheCreationTokens;console.log(`
|
|
317
|
+
${f.green} passed, ${f.yellow} pending review, ${f.red} failed \xB7 ${f.aiCalls} AI calls \xB7 ${(f.inputTokens+f.outputTokens).toLocaleString()} tokens in+out${y>0?` \xB7 ${ln(f.cacheReadTokens)} cache read \xB7 ${ln(f.cacheCreationTokens)} cache written`:""}${Lr(f)}${f.models?.length?` \xB7 ${f.models.join(", ")}`:""}`);let p=m.trends;if(p?.prev){let w=p.prev.passRatePp,k=p.prev.costUsd;console.log(`vs previous run: pass rate ${w>=0?"+":""}${w}pp \xB7 cost ${k>=0?"+":"-"}$${Math.abs(k).toFixed(4)} \xB7 AI calls ${p.prev.aiCalls>=0?"+":""}${p.prev.aiCalls}`)}for(let w of p?.chronic??[])console.log(`\u26A0 chronic: ${w.feature} \u203A ${w.scenario}: ${w.heals} heal(s), ${w.reds} red(s) in last ${w.runs} run(s); re-record or fix the feature text instead of paying for more heals`);console.log(`report: ${R}
|
|
318
|
+
${$}`);let b=ge(F.resolve(D.opts().projectRoot));b.length>0&&console.log(`${b.length} cache proposal(s) pending. Review with: saffron accept | saffron reject`);let E=t.strict??r.strict??!1;E&&f.yellow>0&&console.log(`strict mode: ${f.yellow} scenario(s) pending review treated as failure. Review proposals to go green.`),process.exit(f.red>0||E&&f.yellow>0?1:0)});D.command("accept").description("Promote pending cache proposals to committed caches").argument("[files...]","proposal file(s) (default with --all: every proposal)").option("--all","accept all pending proposals").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 whose proof replay failed").action((e,t)=>{let n=F.resolve(D.opts().projectRoot),r=K(n),s=e.length>0?e.map(o=>F.resolve(o)):t.all?ge(n).map(o=>o.file):[];if(s.length===0){ds(n);return}for(let o of s){let i=ke(o);if(i.meta.verified===!1){if(t.all&&!t.includeUnverified){console.log(`skipped UNVERIFIED ${F.basename(o)} (${i.meta.proofError?.split(`
|
|
312
319
|
`)[0]}). Re-record it (saffron run --rerecord), or accept it explicitly by file, or pass --include-unverified.`);continue}console.log(`\u26A0 accepting UNVERIFIED proposal (proof replay failed: ${i.meta.proofError?.split(`
|
|
313
|
-
`)[0]}): expect a heal or red on the next run.`)}let a=i.cache.steps.map(
|
|
314
|
-
${
|
|
315
|
-
`).map(
|
|
316
|
-
`))});
|
|
320
|
+
`)[0]}): expect a heal or red on the next run.`)}let a=i.cache.steps.map(u=>u.gherkin);if(t.withFeatureEdit&&(i.meta.featureEdits??[]).length>0){let u;try{u=Jr(n,i.cache.feature,i.cache.scenario,a,jt(n,r,[]))}catch(S){throw S instanceof N&&Ze(S),S}if(u){console.log(`not accepted: ${F.basename(o)} carries feature edits, and ${u}. Run the scenario again for a fresh proposal, or accept this one without --with-feature-edit.`),process.exitCode=1;continue}}let c=z(L(n,i.cache.feature,i.cache.scenario)),l=Hn(n,o);console.log(`accepted \u2192 ${l}`);let h=c?Br(c,i.cache):{changes:[],ambiguous:[]},d=h.changes;for(let u of h.ambiguous)console.log(` locator fix for ${At(u)} not propagated: this heal sent it to more than one place, so other caches are left alone.`);if(d.length>0){let u=Wr(n,d,l,!t.propagate);for(let S of d)console.log(` locator fix: ${At(S.from)} \u2192 ${At(S.to)}`);if(u.length===0)console.log(" no other caches use this locator.");else if(t.propagate)for(let S of u)console.log(` propagated \u2192 ${S.feature} \u203A ${S.scenario} (${S.steps.map(x=>`"${x.gherkin}"`).join(", ")})`);else{console.log(` ${u.length} other cache(s) use the same locator: re-run with --propagate to fix them too:`);for(let S of u)console.log(` \xB7 ${S.feature} \u203A ${S.scenario}`)}}let g=i.meta.featureEdits??[];if(!t.withFeatureEdit||g.length===0)continue;let m;try{m=Kr(n,i.cache.feature,i.cache.scenario,g,jt(n,r,[]),a)}catch(u){throw u instanceof N&&Ze(u),u}for(let u of m.applied){let S=u.fromStepSet?`${u.file}:${u.line} (StepSet "${u.fromStepSet}", fixes every invoking scenario)`:`${u.file}:${u.line}`;console.log(` feature edit ${S}:`),console.log(` - ${u.from}`),console.log(` + ${u.to}`)}for(let u of m.skipped)console.log(` skipped edit [${u.index}]: ${u.reason}`);if(m.appliedIndices.length>0){let u=new Set(m.appliedIndices),S=z(l);for(let x of g)u.has(x.index)&&S.steps[x.index]&&(S.steps[x.index].gherkin=x.text);_e(l,S)}}});D.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=F.resolve(D.opts().projectRoot),r=K(n),s;try{s=Z(n,r.features??"features")}catch(i){throw i instanceof N&&Ze(i),i}if(e&&(s=lt(s,e)),t.json){console.log(JSON.stringify(s,null,2));return}if(t.snippets){let i=F.join(n,".vscode","saffron.code-snippets");B.mkdirSync(F.dirname(i),{recursive:!0}),B.writeFileSync(i,Tn(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(`
|
|
321
|
+
${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`)});D.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("--model <model>","model for authoring").action(async(e,t)=>{let n=F.resolve(D.opts().projectRoot),r=K(n),s=B.readFileSync(F.resolve(e),"utf8"),o;try{o=Z(n,r.features??"features")}catch(l){throw l instanceof N&&Ze(l),l}console.log(`authoring with ${o.steps.length} known step(s) and ${o.stepSets.length} step set(s) as vocabulary\u2026`);let i=await rr(s,o,t.model??r.model),a=t.out?F.resolve(t.out):F.join(n,r.features??"features",`${F.basename(e).replace(/\.[^.]+$/,"")}.saffron`);B.existsSync(a)&&(console.error(`refusing to overwrite ${a}: pass --out for a new path`),process.exit(1)),B.mkdirSync(F.dirname(a),{recursive:!0}),B.writeFileSync(a,i.content);let c=i.content.split(`
|
|
322
|
+
`).map(l=>l.trim().replace(/^(Given|When|Then|And|But|\*)\s+/,"")).filter(l=>o.steps.some(h=>h.text===l)).length;console.log(`wrote ${a}`),console.log(`${c} step line(s) reuse the existing vocabulary (seedable) \xB7 $${(i.usage.costUsd??0).toFixed(4)}`),console.log("review the draft, then record it: saffron run "+F.relative(process.cwd(),a))});D.command("mcp").description("Serve the step vocabulary to AI assistants over stdio MCP (search_steps, list_step_sets)").action(async()=>{let e=F.resolve(D.opts().projectRoot),t=K(e);await nr(e,t.features??"features")});D.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(cs(pt())),process.exit(2));let e=F.resolve(D.opts().projectRoot),t=K(e),n=process.argv.includes("-p")||process.argv.some(r=>r.startsWith("--project-root"));pr(e,t.features??"features",{rootFromClient:!n})});D.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=F.resolve(D.opts().projectRoot),r=e.length>0?e.map(s=>F.resolve(s)):t.all?ge(n).map(s=>s.file):[];if(r.length===0){ds(n);return}for(let s of r)Jn(s),console.log(`rejected ${s}`)});D.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(Qe).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=F.resolve(D.opts().projectRoot),n=pt();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 Qe||(console.error(`saffron: unknown agent target "${i}" (expected one of ${Object.keys(Qe).join(", ")})`),process.exit(2));let s=e.examples===!0;e.examples===void 0&&process.stdin.isTTY&&process.stdout.isTTY&&(s=await xi("Install the Saucedemo example tests (login, cart, checkout) into features/ for a guided first run? [y/N] "));let o=as({projectRoot:t,packageRoot:n,targets:r,instructions:e.instructions,scaffold:e.scaffold,mcp:e.mcp,examples:s});for(let i of o.skillDirs)console.log(`skill \u2192 ${i}/`);for(let i of o.mcpFiles)console.log(`${i.outcome.padEnd(9)} \u2192 ${i.file} (saffron mcp server)`);for(let i of o.mcpHints)console.log(`mcp hint \u2192 ${i}`);for(let i of o.instructionFiles)console.log(`${i.outcome.padEnd(9)} \u2192 ${i.file} (managed Saffron block)`);for(let i of o.scaffolded)console.log(`created \u2192 ${i}`);o.examples&&!o.examples.installed&&console.log(`examples \u2192 not installed: ${o.examples.reason}`),console.log("\nAgents now load the saffron skill when writing tests. Re-run after `npm update saffron-ai` to refresh it."),o.examples?.installed&&console.log(["","Your guided first run (recording needs Claude credentials; replays never do):"," cp .env.example .env # public demo credentials, resolved at replay"," npx playwright install chromium"," npx saffron run --filter @smoke # the agent records two scenarios (about $3 of AI usage), files proposals"," npx saffron accept --all # review, then promote them to caches"," npx saffron run --filter @smoke # replays at zero tokens","Then try the rest: npx saffron run (login errors outline, checkout with a data table)"].join(`
|
|
323
|
+
`))});D.command("diff").description("Show what a pending proposal changes in the committed recording: the action list a reviewer is approving, not just the narrative").argument("[files...]","proposal file(s); default: every pending proposal").option("--json","machine-readable output").action((e,t)=>{let n=F.resolve(D.opts().projectRoot),r=e.length>0?e.map(o=>F.resolve(o)):ge(n).map(o=>o.file);if(r.length===0){console.log("No pending proposals.");return}let s=r.map(o=>{let i=ke(o),a=z(L(n,i.cache.feature,i.cache.scenario));return{file:F.relative(n,o),verified:i.meta.verified,...vt(a,i.cache)}});if(t.json){console.log(JSON.stringify(s.length===1?s[0]:s,null,2));return}console.log(s.map(o=>Rr(o)).join(`
|
|
317
324
|
|
|
318
|
-
`))});
|
|
319
|
-
`)),process.exit(2));let
|
|
320
|
-
`))}e.check&&r.orphans.length>0&&process.exit(1)});
|
|
321
|
-
`);for(let{file:n,proposal:r}of t){console.log(` ${n}`);let
|
|
325
|
+
`))});D.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=F.resolve(D.opts().projectRoot),n=K(t),r=ft(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(`
|
|
326
|
+
`)),process.exit(2));let s=e.yes&&!e.check?In(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 ":""}${On(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(`
|
|
327
|
+
`))}e.check&&r.orphans.length>0&&process.exit(1)});D.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=F.resolve(D.opts().projectRoot),n=K(t),r=bt(t,n);if(e.json){console.log(JSON.stringify(r,null,2));return}tr(r)});D.command("report").description("Open the latest HTML report").option("--open","open in the default browser",!0).action(()=>{let e=F.resolve(D.opts().projectRoot),t=F.join(e,".saffron","reports","latest.html");B.existsSync(t)||(console.error("No report found. Run `saffron run` first."),process.exit(2)),console.log(t);let n=process.platform==="darwin"?"open":"xdg-open";mi(n,[t],{detached:!0,stdio:"ignore"}).unref()});function ds(e){let t=ge(e);if(t.length===0){console.log("No pending proposals.");return}console.log(`Pending proposals:
|
|
328
|
+
`);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(` ${r.cache.feature} \u203A ${r.cache.scenario} (${r.meta.mode}, ${r.meta.createdAt}${s})`),console.log(` ${r.meta.narrative}`);for(let o of r.meta.adaptations)console.log(` \u26A0 ${o}`);r.meta.suggestedFeatureEdit&&console.log(` suggested .feature edit:
|
|
322
329
|
${r.meta.suggestedFeatureEdit.split(`
|
|
323
|
-
`).map(
|
|
324
|
-
`)}`),console.log()}console.log("Accept with: saffron accept <file> | --all")}
|
|
330
|
+
`).map(o=>` ${o}`).join(`
|
|
331
|
+
`)}`),console.log()}console.log("Accept with: saffron accept <file> | --all")}D.parseAsync();
|