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