saffron-ai 0.5.3 → 0.5.5
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 +38 -0
- package/dist-pkg/cli.js +117 -115
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,38 @@ All notable changes to Saffron, in one place: the `saffron-ai` runner (npm),
|
|
|
4
4
|
the VS Code extension (`ChathurangaJayasinghe.saffron-vscode`) and the
|
|
5
5
|
JetBrains plugin (`ai.saffron.jetbrains`). Dates are publish dates.
|
|
6
6
|
|
|
7
|
+
## 0.5.5
|
|
8
|
+
|
|
9
|
+
Released 2026-09-17.
|
|
10
|
+
|
|
11
|
+
Runner
|
|
12
|
+
|
|
13
|
+
- `saffron status` reports duplicate wordings by behaviour: different
|
|
14
|
+
step texts whose recorded actions are identical once the step's own
|
|
15
|
+
arguments are masked. The previous wording-similarity list flagged
|
|
16
|
+
"enter X in the username field" against "enter Y in the password
|
|
17
|
+
field", which are different steps.
|
|
18
|
+
|
|
19
|
+
## 0.5.4
|
|
20
|
+
|
|
21
|
+
Released 2026-09-17.
|
|
22
|
+
|
|
23
|
+
Runner
|
|
24
|
+
|
|
25
|
+
- `saffron status [--json]`: the project overview that IDE panels and
|
|
26
|
+
dashboards read: feature files and scenarios with cache state, tags,
|
|
27
|
+
pending proposals with narratives, last run, history, vocabulary health
|
|
28
|
+
(divergent and near-duplicate steps) and the effective config.
|
|
29
|
+
- `saffron accept` and `saffron reject` take several proposal files at
|
|
30
|
+
once.
|
|
31
|
+
|
|
32
|
+
Editors
|
|
33
|
+
|
|
34
|
+
- JetBrains plugin 0.2.1 tool window gains Proposals, Tags, Health and
|
|
35
|
+
Dashboard tabs; VS Code extension 0.2.2 gains Tags, Proposals and
|
|
36
|
+
Health sections and an in-editor dashboard. All read
|
|
37
|
+
`saffron status --json`.
|
|
38
|
+
|
|
7
39
|
## 0.5.3
|
|
8
40
|
|
|
9
41
|
Released 2026-09-17.
|
|
@@ -38,6 +70,12 @@ Editors
|
|
|
38
70
|
in the editor title, and Command Palette entries for run all, open the
|
|
39
71
|
latest report and accept all proposals. Commands run in a "Saffron"
|
|
40
72
|
terminal from the workspace folder.
|
|
73
|
+
- VS Code extension 0.2.1: a **Saffron side panel**: an activity
|
|
74
|
+
bar view listing feature files with their scenarios (click to jump),
|
|
75
|
+
inline Run and Replay-only buttons, checkboxes with Run selected and Run
|
|
76
|
+
all, replay-only and headed toggles that apply to every run from the
|
|
77
|
+
extension, the last run's totals with the report one click away, and
|
|
78
|
+
the proposals pending review with Accept all.
|
|
41
79
|
|
|
42
80
|
## 0.5.2
|
|
43
81
|
|
package/dist-pkg/cli.js
CHANGED
|
@@ -1,46 +1,46 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`),n=new Map,r=new Map;return{source:
|
|
4
|
-
`),definitions:n,invocations:r}}function
|
|
5
|
-
`)}function
|
|
6
|
-
`}import{Server as
|
|
7
|
-
`),r=
|
|
8
|
-
${
|
|
2
|
+
import D from"node:fs";import A from"node:path";import{spawn as js}from"node:child_process";import _s from"node:readline";import{Command as Os}from"commander";import cr from"node:fs";import lr from"node:path";import{AstBuilder as dr,GherkinClassicTokenMatcher as pr,Parser as ur}from"@cucumber/gherkin";import{IdGenerator as fr,StepKeywordType as qe}from"@cucumber/messages";function te(e,t){return e.replace(/<([^<>]+)>/g,(n,r)=>r in t?t[r]:n)}function U(e){if(!e||e.length===0)return{};let t={};if(e.every(n=>n.length===2)){for(let[n,r]of e)t[`table:${n}`]=r;return t}if(e.length>=2){let[n,...r]=e;if(n.some(s=>!s))return{};r.forEach((s,o)=>{n.forEach((i,a)=>{s[a]!==void 0&&(t[`table:${o+1}:${i}`]=s[a])})})}return t}function ne(e){return e!==void 0?{docstring:e}:{}}function ae(e){let t=new Map;for(let r of e){let s={...U(r.resolvedTable??r.table),...ne(r.resolvedDocString??r.docString)};for(let[o,i]of Object.entries(s)){let a=t.get(o);a||t.set(o,a=new Set),a.add(i)}}let n={};for(let[r,s]of t)s.size===1&&(n[r]=[...s][0]);return n}import Be from"node:fs";import St from"node:path";import{AstBuilder as er,GherkinClassicTokenMatcher as tr,Parser as nr}from"@cucumber/gherkin";import{IdGenerator as rr}from"@cucumber/messages";var N=class extends Error{},sr=/^(\s*)StepSet:\s*(.+?)\s*$/,or=/^(\s*)StepSet\s+([^\s:].*?)\s*$/;function ze(e){let t=e.split(`
|
|
3
|
+
`),n=new Map,r=new Map;return{source:t.map((o,i)=>{let a=o.match(sr);if(a)return n.set(i+1,a[2]),`${a[1]}Scenario: ${a[2]}`;let d=o.match(or);return d?(r.set(i+1,d[2]),`${d[1]}* StepSet ${d[2]}`):o}).join(`
|
|
4
|
+
`),definitions:n,invocations:r}}function ir(e){return new nr(new er(rr.uuid()),new tr).parse(e)}function yt(e,t){for(let n of e)n.scenario?t(n.scenario):"rule"in n&&n.rule&&yt(n.rule.children,t)}function X(e,t){let n=new Map;for(let r of e){let s=St.relative(t,r),o=ze(Be.readFileSync(r,"utf8"));if(o.definitions.size===0)continue;let i=ir(o.source);i.feature&&yt(i.feature.children,a=>{let d=o.definitions.get(a.location.line);if(d===void 0)return;let p=n.get(d);if(p)throw new N(`StepSet "${d}" is defined twice: ${p.file}:${p.line} and ${s}:${a.location.line}. Set names are unique across the project. If line ${a.location.line} was meant to INVOKE the set inside a scenario, remove the colon: "StepSet ${d}".`);if(a.examples.length>0)throw new N(`StepSet "${d}" (${s}:${a.location.line}) has an Examples table \u2014 step sets take their values from the invoking scenario.`);for(let f of a.steps)if(o.invocations.has(f.location.line))throw new N(`StepSet "${d}" (${s}:${a.location.line}) invokes another step set at line ${f.location.line} \u2014 step sets cannot be nested.`);n.set(d,{name:d,file:s,line:a.location.line,steps:[...a.steps]})})}return n}var ar=[".feature",".saffron"];function re(e){return ar.some(t=>e.endsWith(t))}function ce(e){if(!Be.existsSync(e))return[];let t=[];for(let n of Be.readdirSync(e,{recursive:!0})){let r=String(n);r.endsWith(".saffron")&&t.push(St.join(e,r))}return t.sort()}function xt(e,t,n){return e.map(({step:r,source:s})=>{let o;switch(r.keywordType){case qe.OUTCOME:o="assertion";break;case qe.CONTEXT:case qe.ACTION:o="action";break;default:o=n.value}n.value=o;let i=r.dataTable?r.dataTable.rows.map(d=>d.cells.map(p=>p.value)):void 0,a=r.docString?.content;return{keyword:r.keyword.trim(),kind:o,text:r.text,resolvedText:te(r.text,t),table:i,resolvedTable:i?.map(d=>d.map(p=>te(p,t))),docString:a,resolvedDocString:a!==void 0?te(a,t):void 0,source:s}})}function bt(e,t,n,r,s){let o=[];for(let i of e){let a=r.get(i.location.line);if(a===void 0){o.push({step:i,source:{file:t,line:i.location.line,fromBackground:n}});continue}let d=s?.get(a);if(!d)throw new N(`${t}:${i.location.line} invokes StepSet "${a}", which is not defined anywhere in the project.`);for(let p of d.steps)o.push({step:p,source:{file:d.file,line:p.location.line,fromStepSet:d.name,fromBackground:n}})}return o}function gr(e,t,n,r,s){let o=e.tags.map(a=>a.name),i=[];if(e.examples.length===0)i.push({params:{},label:""});else{let a=0;for(let d of e.examples){let p=d.tableHeader?.cells.map(f=>f.value)??[];for(let f of d.tableBody){a+=1;let l={};f.cells.forEach((c,u)=>{l[p[u]]=c.value}),i.push({params:l,label:` (example ${a})`})}}}return i.map(({params:a,label:d})=>{let p={value:"action"};return{featurePath:t,featureName:n,name:e.name,displayName:`${e.name}${d}`,tags:o,steps:[...xt(r,a,p),...xt(s,a,p)],params:a}})}function Z(e,t,n){let r=cr.readFileSync(e,"utf8"),o=e.endsWith(".saffron")?ze(r):{source:r,definitions:new Map,invocations:new Map},a=new ur(new dr(fr.uuid()),new pr).parse(o.source);if(!a.feature)return[];let d=lr.relative(t,e),p=a.feature.name,f=[],l=(c,u)=>{let S=u;for(let g of c)if(g.background)S=[...u,...bt(g.background.steps,d,!0,o.invocations,n)];else if(g.scenario){if(o.definitions.has(g.scenario.location.line))continue;f.push(...gr(g.scenario,d,p,S,bt(g.scenario.steps,d,!1,o.invocations,n)))}else"rule"in g&&g.rule&&l(g.rule.children,S)};return l(a.feature.children,[]),f}import Et from"node:fs";import He from"node:path";import wt from"node:fs";import kt from"node:path";import Re from"node:fs";import he from"node:path";var vt=".saffron";function Te(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function B(e,t,n){let r=Te(he.basename(t,".feature"));return he.join(e,vt,"cache",r,`${Te(n)}.json`)}function Se(e,t,n){let r=Te(he.basename(t,".feature"));return he.join(e,vt,"proposals",r,`${Te(n)}.json`)}function z(e){if(!Re.existsSync(e))return;let t=JSON.parse(Re.readFileSync(e,"utf8"));if(t.version!==1)throw new Error(`Unsupported cache version ${t.version} in ${e}`);return t}function le(e,t){Re.mkdirSync(he.dirname(e),{recursive:!0}),Re.writeFileSync(e,`${JSON.stringify(t,null,2)}
|
|
5
|
+
`)}function Rt(e){let t=[];return{pattern:e.replace(/"((?:[^"\\]|\\.)*)"/g,(r,s)=>(t.push(s),`"\xAB${t.length-1}\xBB"`)),args:t}}function mr(e,t){let n=r=>JSON.stringify(r.map(({pageFingerprint:s,...o})=>o));return n(e)===n(t)}function hr(e){let t=new Set,n=r=>{if(r)for(let s of r.matchAll(/<([^<>]+)>/g))t.add(s[1])};for(let r of e.actions)n(r.value),n(r.url),n(r.pattern),n(r.target?.name),n(r.target?.nameRegex),n(r.target?.label),n(r.target?.text),n(r.target?.placeholder);return n(e.gherkin),t}function q(e){let t=kt.join(e,".saffron","cache"),n=new Map,r=new Map,s=0;if(wt.existsSync(t))for(let a of wt.readdirSync(t,{recursive:!0})){let d=String(a);if(!d.endsWith(".json"))continue;let p=z(kt.join(t,d));if(p){s++;for(let f of p.steps){let l=f.gherkin,c=JSON.stringify(f.actions.map(({pageFingerprint:g,...h})=>h)),u=r.get(l)??[];u.includes(c)||(u.push(c),r.set(l,u));let S=n.get(l);!S||p.recordedAt>S.recordedAt?n.set(l,{gherkin:f.gherkin,table:f.table,docString:f.docString,actions:f.actions,feature:p.feature,scenario:p.scenario,recordedAt:p.recordedAt,variants:u.length}):S.variants=u.length}}}let o=[...r.entries()].filter(([,a])=>a.length>1).map(([a])=>a),i=new Map;for(let a of n.values()){let{pattern:d,args:p}=Rt(a.gherkin);if(p.length===0)continue;let f=i.get(d);(!f||a.recordedAt>f.recordedAt)&&i.set(d,{...a,args:p})}return{steps:n,patterns:i,divergent:o,scannedCaches:s}}function $t(e,t,n){if(!!e.table!=!!t.table)return!1;if(e.table&&t.table){let o=Object.keys(U(e.table)),i=Object.keys(U(t.table));if(o.length>0&&i.length>0){if(JSON.stringify(o)!==JSON.stringify(i))return!1}else if(JSON.stringify(e.table)!==JSON.stringify(t.table))return!1}if(e.docString!==void 0!=(t.docString!==void 0)||e.docString!==void 0&&t.docString!==void 0&&e.docString!==t.docString&&!e.actions.some(o=>[o.value,o.url,o.pattern].some(i=>i?.includes("<docstring>"))))return!1;let r={...n,...U(t.resolvedTable??t.table),...ne(t.resolvedDocString??t.docString)},s=hr({gherkin:e.gherkin,keyword:"",kind:"action",actions:e.actions});for(let o of s)if(!(o in r))return!1;return!0}function Tt(e,t,n){let r=e.steps.get(t.text);if(r)return $t(r,t,n)?r:void 0;let{pattern:s,args:o}=Rt(t.text);if(o.length===0)return;let i=e.patterns.get(s);if(!i)return;let a=new Map;for(let l=0;l<o.length;l++){let c=i.args[l],u=o[l];if(c===u)continue;let S=a.get(c);if(S!==void 0&&S!==u)return;a.set(c,u)}let d=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,...d(u.target)].includes(l)))return;let p=l=>l!==void 0&&a.has(l)?a.get(l):l,f={...i,gherkin:t.text,actions:i.actions.map(({pageFingerprint:l,...c})=>({...c,value:p(c.value),url:p(c.url),pattern:p(c.pattern),target:c.target?{...c.target,name:p(c.target.name),nameRegex:p(c.target.nameRegex),label:p(c.target.label),text:p(c.target.text),placeholder:p(c.target.placeholder)}:void 0}))};return $t(f,t,n)?f:void 0}function At(e,t){let n=[];return e.forEach((r,s)=>{if(r.actions.length!==0&&!t.steps.has(r.gherkin)){for(let o of t.steps.values())if(!(o.variants>1)&&o.actions.length!==0&&mr(r.actions,o.actions)){n.push({index:s,from:r.gherkin,to:o.gherkin,feature:o.feature,scenario:o.scenario});break}}}),n}function Sr(e){if(!Et.existsSync(e))return[];let t=[];for(let n of Et.readdirSync(e,{recursive:!0})){let r=String(n);re(r)&&t.push(He.join(e,r))}return t.sort()}function H(e,t,n){let r=He.isAbsolute(t)?t:He.join(e,t),s=Sr(r),o=n??X(s.filter(c=>c.endsWith(".saffron")),e),i=new Map,a=new Map;for(let c of s)for(let u of Z(c,e,o)){let S=`${u.featurePath}::${u.name}`;for(let g of u.steps){let h=i.get(g.text);if(h||(h={text:g.text,keywords:new Map,kind:g.kind,scenarios:new Set,files:new Set,fromStepSet:g.source?.fromStepSet},i.set(g.text,h)),h.keywords.set(g.keyword,(h.keywords.get(g.keyword)??0)+1),h.scenarios.add(S),g.source&&h.files.add(g.source.file),g.source?.fromStepSet){let w=a.get(g.source.fromStepSet);w||a.set(g.source.fromStepSet,w=new Set),w.add(S)}}}let d=q(e),p=new Set(d.divergent),f=[...i.values()].map(c=>({text:c.text,keyword:[...c.keywords.entries()].sort((u,S)=>S[1]-u[1])[0][0],kind:c.kind,status:p.has(c.text)?"divergent":d.steps.has(c.text)?"recorded":"unrecorded",usage:c.scenarios.size,files:[...c.files].sort(),fromStepSet:c.fromStepSet})).sort((c,u)=>u.usage-c.usage||c.text.localeCompare(u.text)),l=[...o.values()].map(c=>({name:c.name,file:c.file,line:c.line,steps:c.steps.map(u=>u.text),usage:a.get(c.name)?.size??0})).sort((c,u)=>u.usage-c.usage||c.name.localeCompare(u.name));return{steps:f,stepSets:l,scannedFiles:s.length,scannedCaches:d.scannedCaches}}function Ae(e,t){let n=t.toLowerCase();return{...e,steps:e.steps.filter(r=>r.text.toLowerCase().includes(n)),stepSets:e.stepSets.filter(r=>r.name.toLowerCase().includes(n)||r.steps.some(s=>s.toLowerCase().includes(n)))}}function Pt(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)+`
|
|
6
|
+
`}import{Server as yr}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as xr}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as br,ListToolsRequestSchema as vr}from"@modelcontextprotocol/sdk/types.js";async function Ct(e,t){let n=new yr({name:"saffron",version:"0.1.0"},{capabilities:{tools:{}}});n.setRequestHandler(vr,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 \u2014 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:{}}}]})),n.setRequestHandler(br,async r=>{let s=H(e,t);if(r.params.name==="search_steps"){let o=r.params.arguments?.query,i=o?Ae(s,o):s;return{content:[{type:"text",text:JSON.stringify({steps:i.steps,scannedFiles:i.scannedFiles,scannedCaches:i.scannedCaches},null,2)}]}}return r.params.name==="list_step_sets"?{content:[{type:"text",text:JSON.stringify({stepSets:s.stepSets},null,2)}]}:{content:[{type:"text",text:`Unknown tool: ${r.params.name}`}],isError:!0}}),await n.connect(new xr)}import{query as wr}from"@anthropic-ai/claude-agent-sdk";function kr(e,t){let n=t.steps.map(s=>`- [${s.status}] ${s.keyword} ${s.text}`).join(`
|
|
7
|
+
`),r=t.stepSets.map(s=>`- StepSet ${s.name}
|
|
8
|
+
${s.steps.map(o=>` ${o}`).join(`
|
|
9
9
|
`)}`).join(`
|
|
10
|
-
`);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)","",
|
|
11
|
-
${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:",
|
|
12
|
-
`)}async function
|
|
13
|
-
`,usage:r}}import
|
|
14
|
-
`),
|
|
15
|
-
`);return{contents:{kind:
|
|
10
|
+
`);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:
|
|
11
|
+
${r}`:void 0,"","RULES:","1. Output ONLY the feature file content \u2014 no prose, no code fences, no explanations.","2. Gherkin/.saffron syntax: Feature:, Scenario:, Scenario Outline: + Examples, Given/When/Then/And/But. Prefer concrete scenarios; use an Outline only when the requirements list variations of the same flow.","3. Then steps are assertions \u2014 state exactly what must be true, one condition per step. End every scenario with at least one Then.","4. If the same 3+ step sequence would appear in two or more scenarios, define it once as a StepSet (first step a guard, last step an exit assertion) and invoke it. Definition uses a colon (StepSet: Name), invocation does not (StepSet Name).",'5. Use 2-column data tables for key/value input, header tables for lists of records, and """ doc strings for free text.',"6. Steps are natural language for an AI browser agent \u2014 never CSS selectors or code.","","REQUIREMENTS:",e.trim()].filter(s=>s!==void 0).join(`
|
|
12
|
+
`)}async function Ft(e,t,n){let r={aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0},s="",o=wr({prompt:kr(e,t),options:{model:n,maxTurns:1,permissionMode:"bypassPermissions",persistSession:!1,settingSources:[],allowedTools:[],systemPrompt:"You are Saffron's feature-file author. You write clean, assertive Gherkin that reuses the project's exact step vocabulary. You output only file content."}});for await(let i of o)if(i.type==="assistant")for(let a of i.message.content)a.type==="text"&&(s+=a.text);else i.type==="result"&&(r.aiCalls=i.num_turns,r.costUsd=i.total_cost_usd,"usage"in i&&i.usage&&(r.inputTokens=i.usage.input_tokens??0,r.outputTokens=i.usage.output_tokens??0,r.cacheReadTokens=i.usage.cache_read_input_tokens??0,r.cacheCreationTokens=i.usage.cache_creation_input_tokens??0));return s=s.replace(/^\s*```(?:gherkin|saffron)?\s*\n/,"").replace(/\n```\s*$/,"").trim(),{content:s+`
|
|
13
|
+
`,usage:r}}import It from"node:fs";import de from"node:path";import{createConnection as $r,ProposedFeatures as Rr,TextDocuments as Tr,TextDocumentSyncKind as Ar,CompletionItemKind as ye,InsertTextFormat as jt,DiagnosticSeverity as Ee,MarkupKind as _t}from"vscode-languageserver/node";import{TextDocument as Er}from"vscode-languageserver-textdocument";var Ot=/^(\s*)(Given|When|Then|And|But|\*)\s+(.+?)\s*$/,Pr=/^\s*StepSet:\s*(.+?)\s*$/,We=/^(\s*)(StepSet)\s+([^\s:].*?)\s*$/,Ge={recorded:"\u25CF recorded \u2014 replays at zero tokens",divergent:"\u25CF divergent \u2014 same text, different recordings",unrecorded:"\u25CB written, not recorded yet"};function Cr(e,t){let n=i=>new Set(i.toLowerCase().replace(/"[^"]*"/g,'"x"').split(/[^a-z0-9"<>]+/).filter(Boolean)),r=n(e),s=n(t);if(r.size===0||s.size===0)return 0;let o=0;for(let i of r)s.has(i)&&o++;return o/(r.size+s.size-o)}function Nt(e,t){let n=$r(Rr.all,process.stdin,process.stdout),r=new Tr(Er),s={steps:[],stepSets:[],scannedFiles:0,scannedCaches:0},o=new Map,i,a=()=>{try{let l=de.isAbsolute(t)?t:de.join(e,t);o=X(ce(l),e),s=H(e,t,o)}catch(l){n.console.warn(`saffron vocabulary rebuild: ${String(l)}`)}for(let l of r.all())f(l)},d=()=>{clearTimeout(i),i=setTimeout(a,300)};function p(l){return s.steps.find(c=>c.text===l)?.status}function f(l){if(!l.uri.endsWith(".saffron"))return;let c=[],u=l.getText().split(`
|
|
14
|
+
`),S=new Map;for(let g=0;g<u.length;g++){let h=u[g],w={start:{line:g,character:0},end:{line:g,character:h.length}},y=h.match(We);y&&!o.has(y[3])&&c.push({range:w,severity:Ee.Error,source:"saffron",message:`StepSet "${y[3]}" is not defined anywhere in the project.`});let m=h.match(Pr);if(m){let b=o.get(m[1]),C=de.relative(e,new URL(l.uri).pathname).replace(/\\/g,"/");(S.has(m[1])||b&&b.file!==C)&&c.push({range:w,severity:Ee.Error,source:"saffron",message:`StepSet "${m[1]}" is defined twice \u2014 set names are project-wide. If this line was meant to INVOKE the set, remove the colon: "StepSet ${m[1]}".`}),S.set(m[1],g)}let k=h.trim();if(k&&!y&&!m){for(let[b]of o)if(k.toLowerCase()===b.toLowerCase()){c.push({range:w,severity:Ee.Warning,source:"saffron",message:`Did you mean "StepSet ${b}"? Invoking a step set needs the StepSet keyword, like a step needs Given/When/Then.`});break}}let v=h.match(Ot);if(v&&p(v[3])!=="recorded"){for(let b of s.steps)if(!(b.text===v[3]||b.status==="unrecorded")&&Cr(b.text,v[3])>=.7){c.push({range:{start:{line:g,character:h.indexOf(v[3])},end:{line:g,character:h.length}},severity:Ee.Information,source:"saffron",message:`Similar to the ${b.status} step "${b.text}" (\xD7${b.usage}). Reusing the exact wording replays at zero tokens; a new wording costs a fresh AI recording.`});break}}}n.sendDiagnostics({uri:l.uri,diagnostics:c})}n.onInitialize(()=>(a(),{capabilities:{textDocumentSync:Ar.Incremental,completionProvider:{triggerCharacters:[" "]},definitionProvider:!0,hoverProvider:!0}})),n.onCompletion(l=>{let c=r.get(l.textDocument.uri);if(!c)return[];let u=c.getText({start:{line:l.position.line,character:0},end:l.position});return Fr(c.uri,u,l.position.line,s)}),n.onDefinition(l=>{let c=r.get(l.textDocument.uri);if(!c)return;let u=c.getText({start:{line:l.position.line,character:0},end:{line:l.position.line+1,character:0}}).replace(/\n$/,""),S=Dt(u,l.position.character);if(S){let y=Mt(e,S.name);return y?{uri:`file://${y.file}`,range:{start:{line:y.line,character:0},end:{line:y.line,character:0}}}:void 0}let g=u.match(We);if(!g)return;let h=o.get(g[3]);return h?{uri:`file://${de.join(e,h.file)}`,range:{start:{line:h.line-1,character:0},end:{line:h.line-1,character:0}}}:void 0}),n.onHover(l=>{let c=r.get(l.textDocument.uri);if(!c)return;{let h=c.getText({start:{line:l.position.line,character:0},end:{line:l.position.line+1,character:0}}).replace(/\n$/,""),w=Dt(h,l.position.character);if(w){let y=Mt(e,w.name),m=y?`defined in ${de.relative(e,y.file)} (line ${y.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:${w.name}}** ${m}.`}}}}let u=c.getText({start:{line:l.position.line,character:0},end:{line:l.position.line+1,character:0}}).replace(/\n$/,""),S=u.match(We);if(S){let h=s.stepSets.find(y=>y.name===S[3]);if(!h)return;let w=h.steps.map(y=>`- ${Ge[p(y)??"unrecorded"][0]} ${y}`).join(`
|
|
15
|
+
`);return{contents:{kind:_t.Markdown,value:`**StepSet ${h.name}** \u2014 expands to:
|
|
16
16
|
|
|
17
|
-
${
|
|
17
|
+
${w}`}}}let g=u.match(Ot);if(g){let h=s.steps.find(w=>w.text===g[3]);return h?{contents:{kind:_t.Markdown,value:`${Ge[h.status]}
|
|
18
18
|
|
|
19
|
-
Used in ${
|
|
19
|
+
Used in ${h.usage} place(s): ${h.files.join(", ")}${h.fromStepSet?`
|
|
20
20
|
|
|
21
|
-
Defined in StepSet **${
|
|
22
|
-
`).findIndex(i=>new RegExp(`^\\s*(?:export\\s+)?${
|
|
23
|
-
`)}));if(/^\s*(Given|When|Then|And|But|\*)\s+/.test(
|
|
21
|
+
Defined in StepSet **${h.fromStepSet}**`:""}`}}:void 0}}),r.onDidOpen(l=>f(l.document)),r.onDidChangeContent(l=>f(l.document)),r.onDidSave(()=>d()),n.onDidChangeWatchedFiles(()=>d()),r.listen(n),n.listen()}function Dt(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 Mt(e,t){for(let n of[".env",".env.example"]){let r=de.join(e,n);if(!It.existsSync(r))continue;let o=It.readFileSync(r,"utf8").split(`
|
|
22
|
+
`).findIndex(i=>new RegExp(`^\\s*(?:export\\s+)?${t}\\s*=`).test(i));if(o!==-1)return{file:r,line:o}}}function Fr(e,t,n,r){let s=e.endsWith(".saffron");if(/^\s*StepSet\s+/.test(t)&&s)return r.stepSets.map(a=>({label:a.name,kind:ye.Function,detail:`step set \xB7 ${a.steps.length} step(s) \xB7 \xD7${a.usage}`,documentation:a.steps.join(`
|
|
23
|
+
`)}));if(/^\s*(Given|When|Then|And|But|\*)\s+/.test(t))return r.steps.map((a,d)=>({label:a.text,kind:ye.Text,detail:`${Ge[a.status]} \xB7 \xD7${a.usage}`,sortText:String(d).padStart(5,"0"),filterText:a.text}));let i=t.replace(/^\s*/,"").trimEnd().toLowerCase().replace(/\s+/g,"");if(i.length>0&&("stepset:".startsWith(i)||i.startsWith("stepset"))&&s){let a={start:{line:n,character:t.length-t.replace(/^\s*/,"").length},end:{line:n,character:t.length}},d=[{label:"StepSet: \u2026",kind:ye.Keyword,detail:"define a reusable step set",documentation:`StepSet: Name
|
|
24
24
|
Given \u2026
|
|
25
25
|
When \u2026
|
|
26
26
|
|
|
27
|
-
Invoke it anywhere with: StepSet Name`,filterText:"step set stepset:",sortText:"0",insertTextFormat:
|
|
28
|
-
`),filterText:`step set ${p.name}`,sortText:`1${p.name}`,textEdit:{range:a,newText:`StepSet ${p.name}`}});return d}return[]}import
|
|
29
|
-
`)){let r=n.trim();if(!r||r.startsWith("#"))continue;let
|
|
30
|
-
`)}function
|
|
31
|
-
`).filter(Boolean).map(
|
|
32
|
-
`)){let a=
|
|
33
|
-
`)}}}var
|
|
34
|
-
`):void 0,featureEdits:
|
|
35
|
-
`)[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."}}await u.goto("about:blank")}if(p&&(
|
|
36
|
-
`)[0]}`}}if(
|
|
37
|
-
`)[0]}`}}}return await this.finalizeAgentRun(e,S,g,p,r,v,g?h?.failure:void 0)}finally{await l.close()}}async finalizeAgentRun(e,n,r,o,s,i=0,a){let d=r?"agent-heal":"agent-record",p=n.recordedSteps.map(w=>({gherkin:w.gherkin,kind:w.kind,status:n.success?"passed":"failed"}));if(!n.success)return{scenario:e,status:"red",source:d,stepResults:p,narrative:n.narrative,adaptations:n.adaptations,usage:n.usage,durationMs:Date.now()-s,error:n.narrative};let m=r?nn(o.steps,n.recordedSteps,this.options.assertionPolicy==="adaptable-mid",a?{stepIndex:a.stepIndex,actionIndex:a.actionIndex}:void 0):n.recordedSteps,c=[...n.adaptations],l={...n.usage},u,h;if(this.options.verifyProposals!==!1){let w=await this.proofReplay(e,this.buildCandidateCache(e,m));try{if(w.result.status!=="passed"&&w.result.failure){let b=w.result.failure;if(this.options.agent&&!(r&&b.kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||tn(o.steps,b.stepIndex))))try{let x=await this.withDialogsVisible(()=>this.options.agent.run({scenario:e,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:b.stepText,kind:b.kind,error:b.error},takeFingerprint:async()=>J(ge(this.browser)??w.page)}));l=rn(l,x.usage),x.success&&(c.push(...x.adaptations),m=r?nn(m,x.recordedSteps,this.options.assertionPolicy==="adaptable-mid"):zr(m,x.recordedSteps),await w.context.close(),w=await this.proofReplay(e,this.buildCandidateCache(e,m)))}catch{}}u=w.result.status==="passed",u||(h=w.result.failure?.error??`proof replay ${w.result.status}`)}finally{await w.context.close().catch(()=>{})}}let f=[...n.featureEdits];for(let w of wt(m,G(this.options.projectRoot)))c.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.`),f.some(b=>b.index===w.index)||f.push({index:w.index,text:w.to});let g=pe(e),v=w=>g.size>0?ne(w,g):w;c=c.map(v);let S={meta:{createdAt:new Date().toISOString(),mode:r?"heal":"record",narrative:v(n.narrative),adaptations:c,suggestedFeatureEdit:n.suggestedFeatureEdit?v(n.suggestedFeatureEdit):void 0,featureEdits:f.length>0?f:void 0,verified:u,proofError:h?v(h):void 0,seededSteps:i>0?i:void 0,recordedFor:e.displayName,usage:l},cache:{version:1,feature:e.featurePath,scenario:e.name,recordedAt:new Date().toISOString(),recordedBy:"agent",steps:m}},y=Gt(m);y.length>0&&(u=!1,h=[h,...y].filter(Boolean).join(" "));let A=Le(this.options.projectRoot,e.featurePath,e.name);return Mt(A,S),{scenario:e,status:"yellow",source:d,stepResults:p,narrative:n.narrative,adaptations:c,suggestedFeatureEdit:n.suggestedFeatureEdit,featureEdits:f.length>0?f:void 0,verified:u,proofError:h,seededSteps:i>0?i:void 0,proposalFile:A,usage:l,durationMs:Date.now()-s}}};import un from"node:path";import{createRequire as Yr}from"node:module";import{query as Jr}from"@anthropic-ai/claude-agent-sdk";import{createSdkMcpServer as Vr,tool as oe}from"@anthropic-ai/claude-agent-sdk";import{z as k}from"zod";var D=t=>({content:[{type:"text",text:t}]});function on(t){let e={};return t.role&&(e.role=t.role),t.name&&(e.name=t.name),t.nameRegex&&(e.nameRegex=t.nameRegex),t.label&&(e.label=t.label),t.text&&(e.text=t.text),t.selector&&(e.fallbackSelectors=[t.selector]),t.frame&&(e.frame=t.frame),Object.keys(e).length>0?e:void 0}var an={role:k.string().optional().describe("ARIA role of the element"),name:k.string().optional().describe("Accessible name \u2014 use the SHORTEST stable substring; never include volatile content like prices or dates"),nameRegex:k.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:k.string().optional().describe("Form-label text for getByLabel \u2014 the literal <label> text only, never a free-text description"),text:k.string().optional().describe("getByText locator text"),selector:k.string().optional().describe("CSS fallback selector"),frame:k.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 cn(t){return Vr({name:"saffron",version:"0.1.0",tools:[oe("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:k.number().int().min(0),text:k.string(),adaptation:k.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 e=>(t.currentStepIndex=e.index,t.announced.add(e.index),e.adaptation&&t.adaptations.push(`Step ${e.index+1} ("${e.text}"): ${e.adaptation}`),D(`Recording step ${e.index}: ${e.text}`))),oe("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:k.string().describe("Name to store the captured text under"),...an},async e=>{let n=on(e);return n?(t.addActions([{action:"captureText",target:n,saveAs:e.saveAs}]),D(`Capture recorded as "${e.saveAs}".`)):D("ERROR: capture needs a target (role/name, nameRegex, label, text, or selector).")}),oe("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:k.boolean().describe("true = accept/OK the dialog, false = dismiss/cancel"),promptText:k.string().optional().describe("Text typed into a prompt() before accepting")},async e=>(t.addArmedAction({action:"handleDialog",value:e.accept?"accept":"dismiss",...e.promptText?{promptText:e.promptText}:{}}),D(`Dialog handling recorded (${e.accept?"accept":"dismiss"}).`))),oe("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:k.string().describe("Regex matched against the response URL \u2014 path-only for portability"),method:k.string().optional().describe("HTTP method to match (any if omitted)"),status:k.string().optional().describe("Expected status \u2014 exact ('201') or class ('2xx'); default any 2xx"),bodyPattern:k.string().optional().describe(`Regex the response body must match, e.g. '"status"\\s*:\\s*"READY"' for polling waits`)},async e=>(t.addActions([{action:"waitForResponse",urlPattern:e.urlPattern,...e.method?{method:e.method}:{},...e.status?{status:e.status}:{},...e.bodyPattern?{pattern:e.bodyPattern}:{}}]),D("Network wait recorded."))),oe("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:k.enum(["visible","notVisible","text","url","value","differs","matches","attribute","response"]),...an,expected:k.string().optional().describe("Expected text/value for kind=text|value \u2014 stable text only, never volatile values"),url:k.string().optional().describe("URL substring for kind=url (path only, no host)"),pattern:k.string().optional().describe("kind=matches|attribute: regex the target's text (or attribute) must match, e.g. 'NOK [\\\\d,]+' for a price"),attribute:k.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:k.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:k.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:k.string().optional().describe("kind=response: HTTP method to match (any if omitted)"),status:k.string().optional().describe("kind=response: expected status \u2014 exact ('201') or class ('2xx'); default any 2xx"),bodyPattern:k.string().optional().describe("kind=response: regex the response body must match (verify via browser_network_requests first)"),compareTo:k.string().optional().describe("kind=differs: name of the captured value to compare against")},async e=>{let n=on(e),r;switch(e.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:e.expected??""};break;case"value":r={action:"expectValue",target:n,value:e.expected??""};break;case"url":r={action:"expectUrl",url:e.url??""};break;case"differs":if(!e.compareTo)return D("ERROR: kind=differs requires compareTo.");if(!e.capture&&!n)return D("ERROR: kind=differs needs either capture (a stored name) or a target element.");r={action:"expectDiffers",target:n,value:e.capture,compareTo:e.compareTo};break;case"matches":if(!e.pattern)return D("ERROR: kind=matches requires pattern.");r={action:"expectMatches",target:n,pattern:e.pattern};break;case"attribute":if(!e.attribute||!e.pattern)return D("ERROR: kind=attribute requires attribute and pattern.");r={action:"expectAttribute",target:n,attribute:e.attribute,pattern:e.pattern};break;case"response":if(!e.urlPattern)return D("ERROR: kind=response requires urlPattern.");r={action:"expectResponse",urlPattern:e.urlPattern,...e.method?{method:e.method}:{},...e.status?{status:e.status}:{},...e.bodyPattern?{pattern:e.bodyPattern}:{}};break}return!["url","differs","response"].includes(e.kind)&&!n?D("ERROR: assertion needs a target (role/name, nameRegex, label, text, or selector)."):(t.addActions([r]),D("Assertion recorded."))}),oe("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:k.boolean(),narrative:k.string().describe("2-4 sentence summary of the run: what happened, and why it failed if it did."),suggestedFeatureEdit:k.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:k.array(k.object({index:k.number().int().min(0).describe("zero-based step index"),text:k.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 e=>(t.done=!0,t.success=e.success,t.narrative=e.narrative,t.suggestedFeatureEdit=e.suggestedFeatureEdit,t.featureEdits=e.featureEdits??[],D("Run finalized.")))]})}function ln(t={}){let e=t.deliberateSnapshots?`
|
|
27
|
+
Invoke it anywhere with: StepSet Name`,filterText:"step set stepset:",sortText:"0",insertTextFormat:jt.Snippet,textEdit:{range:a,newText:"StepSet: ${1:Name}\n "}}];r.stepSets.length===0&&d.push({label:"StepSet \u2026",kind:ye.Keyword,detail:"invoke a step set (none defined yet)",filterText:"step set stepset",sortText:"1",insertTextFormat:jt.Snippet,textEdit:{range:a,newText:"StepSet ${1:Name}"}});for(let p of r.stepSets)d.push({label:`StepSet ${p.name}`,kind:ye.Function,detail:`invoke step set \xB7 ${p.steps.length} step(s)`,documentation:p.steps.join(`
|
|
28
|
+
`),filterText:`step set ${p.name}`,sortText:`1${p.name}`,textEdit:{range:a,newText:`StepSet ${p.name}`}});return d}return[]}import Ut from"node:fs";import Ir from"node:path";var Lt=/\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g;function xe(e){return e.replace(Lt,(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 Ye(e){let t=new Set;for(let n of e)if(n)for(let r of n.matchAll(Lt))t.add(r[1]);return t}function Je(e){let t=[];for(let n of e.steps){t.push(n.text,n.resolvedText),n.docString&&t.push(n.docString);for(let r of n.table??[])t.push(...r)}return t}function be(e){let t=new Map;for(let n of Ye(Je(e))){let r=process.env[n];r!==void 0&&t.set(n,r)}return t}function pe(e,t){let n=e;for(let[r,s]of[...t.entries()].sort((o,i)=>i[1].length-o[1].length))s.length<4||(n=n.split(s).join(`{env:${r}}`));return n}function Vt(e){let t=Ir.join(e,".env");if(Ut.existsSync(t))for(let n of Ut.readFileSync(t,"utf8").split(`
|
|
29
|
+
`)){let r=n.trim();if(!r||r.startsWith("#"))continue;let s=r.indexOf("=");if(s<=0)continue;let o=r.slice(0,s).trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(o))continue;let i=r.slice(s+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),process.env[o]===void 0&&(process.env[o]=i)}}import sn from"node:fs";import Wr from"node:net";import on from"node:path";import{chromium as Gr,firefox as Yr,webkit as Jr}from"playwright";import W from"node:fs";import Pe from"node:path";function Bt(e,t){W.mkdirSync(Pe.dirname(e),{recursive:!0}),W.writeFileSync(e,`${JSON.stringify(t,null,2)}
|
|
30
|
+
`)}function ue(e){return JSON.parse(W.readFileSync(e,"utf8"))}function se(e){let t=Pe.join(e,".saffron","proposals");if(!W.existsSync(t))return[];let n=[];for(let r of W.readdirSync(t)){let s=Pe.join(t,r);if(W.statSync(s).isDirectory())for(let o of W.readdirSync(s)){if(!o.endsWith(".json"))continue;let i=Pe.join(s,o);n.push({file:i,proposal:ue(i)})}}return n}function zt(e,t){let n=ue(t),r=B(e,n.cache.feature,n.cache.scenario);return le(r,n.cache),W.rmSync(t),r}function qt(e){W.rmSync(e)}import Wt from"node:path";var jr=/\{date([+-]\d+)?(?::([^}]+))?\}/g;function _r(e,t){let n=String(e.getFullYear()),r=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0");return t.replaceAll("YYYY",n).replaceAll("MM",r).replaceAll("DD",s).replaceAll("M",String(e.getMonth()+1)).replaceAll("D",String(e.getDate()))}function Ke(e,t=new Date){return e.replace(jr,(n,r,s)=>{let o=new Date(t);return o.setDate(o.getDate()+(r?parseInt(r,10):0)),_r(o,s??"YYYY-MM-DD")})}var Or=/\b(\d{4})-(\d{2})-(\d{2})\b/g,Dr=400;function Ht(e,t=new Date){let n=new Date(t.getFullYear(),t.getMonth(),t.getDate());return e.replace(Or,(r,s,o,i)=>{let a=new Date(Number(s),Number(o)-1,Number(i));if(Number.isNaN(a.getTime()))return r;let d=Math.round((a.getTime()-n.getTime())/864e5);return Math.abs(d)>Dr?r:d===0?"{date}":`{date${d>0?"+":""}${d}}`})}import{createHash as Mr}from"node:crypto";async function oe(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:${Mr("sha256").update(n).digest("hex")}`}var Ze=e=>new Promise(t=>setTimeout(t,e)),Xe=class{entries=[];seq=0;prevStepSeq=0;curStepSeq=0;listener;context;attach(t,n){this.context=t,this.listener=r=>{let s={seq:++this.seq,url:r.url(),method:r.request().method(),status:r.status()};if(this.entries.push(s),n){let o=r.headers()["content-type"]??"";/json|text|xml/i.test(o)&&r.text().then(i=>{s.body=i.length>262144?i.slice(0,262144):i}).catch(()=>{})}},t.on("response",this.listener)}detach(){this.context&&this.listener&&this.context.off("response",this.listener)}markStep(){this.prevStepSeq=this.curStepSeq,this.curStepSeq=this.seq}sincePreviousStep(){return this.entries.filter(t=>t.seq>this.prevStepSeq)}all(){return this.entries}};function Nr(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 Gt(e,t,n,r,s){return!(!t.test(e.url)||n&&e.method.toUpperCase()!==n.toUpperCase()||!Nr(e.status,r)||s&&!s.test(e.body??""))}var Ur=(e,t)=>`response matching ${e.method??"any-method"} /${t}/ status ${e.status??"2xx"}${e.pattern?` body /${e.pattern}/`:""}`;function Yt(e,t,n,r=!1){let s=a=>xe(Ke(te(a,n))),o=[],i=a=>{if(t.role){let d=t.nameRegex?new RegExp(s(t.nameRegex),"i"):t.name?s(t.name):void 0;o.push(a.getByRole(t.role,{name:d,exact:!1}))}t.label&&o.push(a.getByLabel(s(t.label))),t.placeholder&&o.push(a.getByPlaceholder(s(t.placeholder))),t.text&&o.push(a.getByText(s(t.text))),t.testId&&o.push(a.getByTestId(s(t.testId)));for(let d of t.fallbackSelectors??[])o.push(a.locator(d))};if(t.frame)i(e.frameLocator(s(t.frame)));else if(i(e),r)for(let a of e.frames())a!==e.mainFrame()&&i(a);if(o.length===0)throw new Error("Action target has neither role nor fallback selectors");return o}async function G(e,t,n){let r=Date.now()+t,s;for(;Date.now()<r;){try{if(await e())return}catch(o){s=o}await Ze(100)}throw new Error(`Timed out waiting for ${n}${s?` (${String(s)})`:""}`)}async function L(e,t){let n;for(let r of e)try{await t(r.first());return}catch(s){n=s}throw n}var Qe=e=>e.replace(/\s+/g," ").trim();async function et(e,t,n,r,s,o=new Map,i){let a=g=>xe(Ke(te(g,n))),d=t.value!==void 0?a(t.value):void 0,p=t.url!==void 0?a(t.url):void 0,f=t.action==="expectVisible"||t.action==="expectText"||t.action==="expectValue"||t.action==="expectMatches"||t.action==="expectAttribute"||t.action==="captureText",l=t.target?Yt(e,t.target,n,f):[],c={timeout:r},u={timeout:Math.min(1e3,r)},S=g=>async()=>{for(let h of l)try{if(await g(h.first()))return!0}catch{}return!1};switch(t.action){case"goto":{if(!p)throw new Error("goto requires url");let g=/^https?:\/\//.test(p)?p:new URL(p,s).toString();await e.goto(g,c);return}case"click":return L(l,g=>g.click(c));case"fill":return L(l,g=>g.fill(d??"",c));case"press":return l.length>0?L(l,g=>g.press(d??"",c)):e.keyboard.press(d??"");case"selectOption":return L(l,async g=>{await g.selectOption(d??"",c)});case"check":return L(l,g=>g.check(c));case"uncheck":return L(l,g=>g.uncheck(c));case"hover":return L(l,g=>g.hover(c));case"waitFor":return l.length>0?L(l,g=>g.waitFor({state:"visible",timeout:r})):Ze(Math.min(Number(d??"0"),r));case"expectVisible":return G(S(g=>g.isVisible()),r,"target to be visible");case"expectNotVisible":return L(l,g=>g.waitFor({state:"hidden",timeout:r}));case"expectText":return G(S(async g=>(await g.textContent(u)??"").includes(d??"")),r,`text "${d}"`);case"expectValue":return G(S(async g=>await g.inputValue(u)===(d??"")),r,`input value "${d}"`);case"expectUrl":{let g=p??d??"";return G(async()=>e.context().pages().some(h=>h.url().includes(g)),r,`URL containing "${g}" in any tab (current: ${e.context().pages().map(h=>h.url()).join(", ")})`)}case"handleDialog":{let g=(d??"accept")!=="dismiss",h=t.promptText?a(t.promptText):void 0;e.once("dialog",w=>{g?w.accept(h):w.dismiss()});return}case"uploadFile":{let g=(d??"").split(`
|
|
31
|
+
`).filter(Boolean).map(h=>Wt.isAbsolute(h)?h:Wt.resolve(h));if(g.length===0)throw new Error("uploadFile requires a path");if(l.length>0)return L(l,h=>h.setInputFiles(g,c));e.once("filechooser",h=>{h.setFiles(g)});return}case"dragTo":{if(!t.toTarget)throw new Error("dragTo requires toTarget");let g=Yt(e,t.toTarget,n);return L(l,h=>h.dragTo(g[0].first(),c))}case"captureText":{if(!t.saveAs)throw new Error("captureText requires saveAs");return G(S(async g=>{let h=Qe(await g.textContent(u)??"");return h===""?!1:(o.set(t.saveAs,h),!0)}),r,`non-empty text to capture as "${t.saveAs}"`)}case"expectDiffers":{if(!t.compareTo)throw new Error("expectDiffers requires compareTo");let g=o.get(t.compareTo);if(g===void 0)throw new Error(`expectDiffers: no captured value named "${t.compareTo}"`);if(l.length>0)return G(S(async y=>Qe(await y.textContent(u)??"")!==g),r,`target text to differ from "${t.compareTo}" (${g})`);let h=d??"",w=o.get(h);if(w===void 0)throw new Error(`expectDiffers: no captured value named "${h}"`);if(w===g)throw new Error(`expectDiffers: "${h}" (${w}) equals "${t.compareTo}" (${g})`);return}case"expectAttribute":{if(!t.attribute)throw new Error("expectAttribute requires attribute");if(!t.pattern)throw new Error("expectAttribute requires pattern");let g=new RegExp(t.pattern,"i");return G(S(async h=>g.test(await h.getAttribute(t.attribute,u)??"")),r,`attribute ${t.attribute} to match /${t.pattern}/i`)}case"expectMatches":{if(!t.pattern)throw new Error("expectMatches requires pattern");let g=new RegExp(t.pattern,"i");return G(S(async h=>g.test(Qe(await h.textContent(u)??""))),r,`target text to match /${t.pattern}/i`)}case"waitForResponse":case"expectResponse":{if(!t.urlPattern)throw new Error(`${t.action} requires urlPattern`);let g=new RegExp(a(t.urlPattern)),h=t.pattern?new RegExp(a(t.pattern)):void 0;if(!i){await e.waitForResponse(y=>Gt({seq:0,url:y.url(),method:y.request().method(),status:y.status()},g,t.method,t.status,void 0),c);return}let w=()=>t.action==="expectResponse"?i.all():i.sincePreviousStep();return G(async()=>w().some(y=>Gt(y,g,t.method,t.status,h)),r,Ur(t,t.urlPattern))}default:throw new Error(`Unknown action type: ${t.action}`)}}function Jt(e,t){return e.actions.some(n=>[n.value,n.url,n.pattern,n.target?.name,n.target?.nameRegex,n.target?.label,n.target?.text,n.target?.placeholder].some(r=>r?.includes(t)))}function Lr(e,t){return t.steps.length!==e.steps.length?!1:t.steps.every((n,r)=>{let s=e.steps[r];if(n.gherkin!==s.text)return!1;let o=n.table,i=s.table;if(!!o!=!!i)return!1;if(o&&i){let a=Object.keys(U(o)),d=Object.keys(U(i));if(a.length>0&&d.length>0){if(JSON.stringify(a)!==JSON.stringify(d))return!1}else if(JSON.stringify(o)!==JSON.stringify(i))return!1}if(n.docString!==void 0!=(s.docString!==void 0))return!1;if(n.docString!==void 0&&s.docString!==void 0&&n.docString!==s.docString){let a=t.steps.some(p=>Jt(p,"<docstring>")),d=t.steps.some(p=>Jt(p,n.docString));if(!a||d)return!1}return!0})}function tt(e,t){let n=e.steps[t],r=n?.resolvedTable??n?.table;return{...e.params,...ae(e.steps),...U(r),...ne(n?.resolvedDocString??n?.docString)}}async function ve(e,t,n,r={}){let s=r.actionTimeoutMs??5e3,o=r.retries??1,i=[],a=r.vars??new Map,d=()=>Object.fromEntries(a),p=n.steps.some(u=>u.actions.some(S=>(S.action==="waitForResponse"||S.action==="expectResponse")&&S.pattern!==void 0)),f=new Xe;f.attach(e.context(),p);let l=e,c=()=>{let u=e.context().pages(),S=u[u.length-1];S&&S!==l&&!S.isClosed()&&(l=S)};if(!Lr(t,n))return f.detach(),{status:"stale",stepResults:i,captured:d()};try{for(let u=0;u<n.steps.length;u++){let S=n.steps[u],g=tt(t,u);f.markStep();let h=!1,w=0;for(let y=0;y<S.actions.length;y++){let m=S.actions[y];c(),m.pageFingerprint&&await oe(l)!==m.pageFingerprint&&(h=!0);let k,v=!1;for(let b=0;b<=o&&!v;b++){b>0&&(w++,await Ze(250*b),c());try{await et(l,m,g,s,r.baseURL,a,f),v=!0}catch(C){k=C}}if(!v){let b=k instanceof Error?k.message:String(k);i.push({gherkin:S.gherkin,fromStepSet:S.fromStepSet,kind:S.kind,status:"failed",drift:h,...w?{retries:w}:{},error:b});for(let C=u+1;C<n.steps.length;C++)i.push({gherkin:n.steps[C].gherkin,kind:n.steps[C].kind,status:"skipped"});return{status:"failed",failure:{stepIndex:u,actionIndex:y,stepText:S.gherkin,kind:S.kind,error:b},stepResults:i,captured:d()}}}i.push({gherkin:S.gherkin,fromStepSet:S.fromStepSet,kind:S.kind,status:"passed",drift:h,...w?{retries:w}:{}})}return{status:"passed",stepResults:i,captured:d()}}finally{f.detach()}}var Kt=new Set(["expectVisible","expectNotVisible","expectText","expectUrl","expectValue","expectDiffers","expectMatches","expectAttribute","expectResponse"]);var Ce=class{steps;currentStepIndex=-1;done=!1;success=!1;narrative="";adaptations=[];suggestedFeatureEdit;featureEdits=[];announced=new Set;pendingFingerprint;constructor(t){this.steps=t.steps.map(n=>({gherkin:n.text,keyword:n.keyword,kind:n.kind,table:n.table,docString:n.docString,fromStepSet:n.source?.fromStepSet,actions:[]}))}addArmedAction(t){if(this.done)return;let n=Math.max(this.currentStepIndex,0),r=this.steps[n];if(!r||r.actions.some(i=>i.action===t.action&&i.value===t.value&&i.promptText===t.promptText))return;let o=Math.max(r.actions.length-1,0);r.actions.splice(o,0,t)}addActions(t){if(this.done||t.length===0)return;let n=Math.max(this.currentStepIndex,0),r=this.steps[n];r&&(this.pendingFingerprint&&t[0]&&(t[0].pageFingerprint=this.pendingFingerprint,this.pendingFingerprint=void 0),r.actions.push(...t))}},ie=e=>e.replace(/\\(['"\\])/g,"$1");function Vr(e){let t=e.match(/'((?:[^'\\]|\\.)*)'/);return t?ie(t[1]):void 0}function nt(e){let t={},n=e.match(/(?:frameLocator\('((?:[^'\\]|\\.)*)'\)|locator\('((?:[^'\\]|\\.)*)'\)\.contentFrame\(\))/);n&&(t.frame=ie(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=ie(i[1]))}let s=[[/getByLabel\('((?:[^'\\]|\\.)*)'\)/,"label"],[/getByText\('((?:[^'\\]|\\.)*)'\)/,"text"],[/getByTestId\('((?:[^'\\]|\\.)*)'\)/,"testId"],[/getByPlaceholder\('((?:[^'\\]|\\.)*)'\)/,"placeholder"]];for(let[i,a]of s){let d=e.match(i);d&&(t[a]=ie(d[1]))}let o=e.match(/(?:^|\.)locator\('((?:[^'\\]|\\.)*)'\)/);return o&&(t.fallbackSelectors=[ie(o[1])]),Object.keys(t).length>0?t:void 0}function Br(e,t){if(t&&e.startsWith(t)){let n=e.slice(t.length);return n.startsWith("/")?n:`/${n}`}return e}var zr={click:"click",dblclick:"click",fill:"fill",pressSequentially:"fill",type:"fill",press:"press",check:"check",uncheck:"uncheck",hover:"hover",selectOption:"selectOption"};function qr(e,t){let n=e.match(/page\.goto\('((?:[^'\\]|\\.)*)'\)/);if(n)return{action:"goto",url:Br(ie(n[1]),t)};let r=e.match(/page\.keyboard\.press\('((?:[^'\\]|\\.)*)'\)/);if(r)return{action:"press",value:ie(r[1])};let s=e.match(/await\s+page\.(.+)\.dragTo\(page\.(.+?)\);?\s*$/);if(s){let c=nt(s[1]),u=nt(s[2]);if(c&&u)return{action:"dragTo",target:c,toTarget:u}}let o=e.match(/await\s+page\.(.+)\.(click|dblclick|fill|pressSequentially|type|press|check|uncheck|hover|selectOption)\((.*)\);?\s*$/);if(!o)return;let[,i,a,d]=o,p=nt(i);if(!p)return;let f={action:zr[a],target:p},l=Vr(d);return l!==void 0&&a!=="click"&&a!=="dblclick"&&(f.value=l),f}function Qt(e,t){let n=[],r=Array.isArray(e)?e:e?.content;if(Array.isArray(r))for(let o of r){let i=o?.text;typeof i=="string"&&n.push(i)}else typeof e=="string"&&n.push(e);let s=[];for(let o of n)for(let i of o.split(`
|
|
32
|
+
`)){let a=qr(i.trim(),t);a&&s.push(a)}return Hr(s)}function Hr(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 Xt(e){let t=[];for(let n of e)if(/"[^"]+"|<[^<>]+>/.test(n.gherkin)){for(let s of n.actions)if(s.action==="fill"&&(s.value??"")===""){t.push(`Step "${n.gherkin}" recorded a fill with an empty value although the step passes one; the typed value was lost. Re-record with: saffron run --rerecord`);break}}return t}function rt(e,t){let n=e;for(let[r,s]of Object.entries(t).filter(([,o])=>o.length>=3).sort((o,i)=>i[1].length-o[1].length))n=n.split(s).join(`<${r}>`);return n}function Zt(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:rt(i,t),s=[...n].sort((i,a)=>a[1].length-i[1].length),o=i=>{if(i!==void 0){for(let[a,d]of s)if(i.includes(d))return`<${a}>`;return i}};return e.map(i=>({...i,actions:i.actions.map(a=>{let d=Kt.has(a.action)&&a.action!=="expectValue";return{...a,value:d?o(a.value):r(a.value),url:r(a.url),target:a.target?{...a.target,name:d?o(a.target.name):r(a.target.name),label:r(a.target.label),text:d?o(a.target.text):r(a.target.text),placeholder:r(a.target.placeholder)}:void 0}})}))}function en(e,t){let n=ae(t.steps);return e.map((r,s)=>{let o=t.steps[s],i=o?.resolvedTable??o?.table,a=o?.resolvedDocString??o?.docString,d=Object.entries({...n,...U(i),...ne(a)}).filter(([,f])=>f.length>=3).sort((f,l)=>l[1].length-f[1].length);if(d.length===0)return r;let p=f=>{if(f===void 0)return;let l=f;for(let[c,u]of d)l=l.split(u).join(`<${c}>`);return l};return{...r,actions:r.actions.map(f=>({...f,value:p(f.value),url:p(f.url),target:f.target?{...f.target,name:p(f.target.name),label:p(f.target.label),text:p(f.target.text),placeholder:p(f.target.placeholder)}:void 0}))}})}function tn(e,t=new Date){let n=r=>r===void 0?void 0:Ht(r,t);return e.map(r=>({...r,actions:r.actions.map(s=>({...s,value:n(s.value),url:n(s.url),target:s.target?{...s.target,name:n(s.target.name),nameRegex:n(s.target.nameRegex),label:n(s.target.label),text:n(s.target.text)}:void 0}))}))}function nn(e,t){if(t.size===0)return e;let n=r=>r===void 0?void 0:pe(r,t);return e.map(r=>({...r,actions:r.actions.map(s=>({...s,value:n(s.value),url:n(s.url),pattern:n(s.pattern),target:s.target?{...s.target,name:n(s.target.name),nameRegex:n(s.target.nameRegex),label:n(s.target.label),text:n(s.target.text),placeholder:n(s.target.placeholder)}:void 0}))}))}function rn(e,t){let n=t??{};if(e==="mcp__playwright__browser_handle_dialog"){let r={action:"handleDialog",value:n.accept?"accept":"dismiss"};return typeof n.promptText=="string"&&n.promptText&&(r.promptText=n.promptText),r}if(e==="mcp__playwright__browser_file_upload"){let r=Array.isArray(n.paths)?n.paths:[];if(r.length===0)return;let s=process.cwd()+"/";return{action:"uploadFile",value:r.map(i=>typeof i=="string"&&i.startsWith(s)?i.slice(s.length):i).join(`
|
|
33
|
+
`)}}}var fe={aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0};async function Kr(){return new Promise((e,t)=>{let n=Wr.createServer();n.listen(0,"127.0.0.1",()=>{let{port:r}=n.address();n.close(()=>e(r))}),n.on("error",t)})}function we(e){let t=e.contexts().flatMap(n=>n.pages());return[...t].reverse().find(n=>n.url()!=="about:blank")??t.at(-1)}function dn(e){let t=e.length;for(let n=e.length-1;n>=0&&e[n].kind==="assertion";n--)t=n;return t}function an(e,t){return e[t]?.kind==="assertion"&&t>=dn(e)}function cn(e,t,n=!1,r){let s=dn(e);return e.map((o,i)=>{let a=t[i],d=a&&a.actions.length>0;return o.kind==="assertion"?n&&i<s&&d?a:o:d?r&&i===r.stepIndex&&r.actionIndex>0?{...a,actions:[...o.actions.slice(0,r.actionIndex),...a.actions]}:a:o})}function Qr(e,t){return e.map((n,r)=>{let s=t[r];return s&&s.actions.length>0?s:n})}function ln(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 Fe=class{constructor(t){this.options=t}options;browser;cdpEndpoint;stepIndex;get agent(){return this.options.agent}getStepIndex(){if(!this.stepIndex&&(this.stepIndex=q(this.options.projectRoot),this.stepIndex.steps.size>0)){let t=this.stepIndex.divergent.length>0?` \xB7 ${this.stepIndex.divergent.length} step(s) have divergent recordings (Level-2 signal)`:"";console.log(`step index: ${this.stepIndex.steps.size} reusable steps from ${this.stepIndex.scannedCaches} cache(s)${t}`)}return this.stepIndex}async recordWithSeeding(t,n){let r=this.getStepIndex(),s=t.steps.length,o={...t.params,...ae(t.steps)},i=t.steps.map(y=>{let m=r.steps.size>0?Tt(r,y,o):void 0;return m?{gherkin:y.text,keyword:y.keyword,kind:y.kind,table:y.table,docString:y.docString,fromStepSet:y.source?.fromStepSet,actions:m.actions}:void 0}),a=t.steps.map(y=>({gherkin:y.text,keyword:y.keyword,kind:y.kind,table:y.table,docString:y.docString,fromStepSet:y.source?.fromStepSet,actions:[]})),d=new Map,p=[],f=[],l=[],c=[],u={...fe},S=0,g=0,h=0,w=y=>({success:y,narrative:f.join(" ")||"Composed entirely from seeded recordings.",adaptations:p,suggestedFeatureEdit:c.length>0?c.join(`
|
|
34
|
+
`):void 0,featureEdits:l,recordedSteps:a,announcedSteps:[],usage:u,seededCount:S});for(;h<s;){if(i[h]){let b=h;for(;b<s&&i[b];)b++;let C=i.slice(h,b),x={...t,steps:t.steps.slice(h,b)},R=await ve(n,x,this.buildCandidateCache(t,C),{baseURL:this.options.baseURL,actionTimeoutMs:this.options.actionTimeoutMs,retries:this.options.retries,vars:d}),E=R.status==="passed"?b-h:R.failure?.stepIndex??0;for(let O=0;O<E;O++)a[h+O]=C[O];if(S+=E,R.status==="passed"){h=b;continue}let I=h+E;p.push(`Seeded recording for "${t.steps[I].text}" did not replay in this scenario's context; the agent re-recorded it fresh. Divergence signal.`),i[I]=void 0,h=I;continue}if(!this.options.agent)return w(!1);g++;let y=h;for(;y<s&&!i[y];)y++;g>=3&&(y=s);let m=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:this.options.baseURL,mode:"record",cdpEndpoint:this.cdpEndpoint,assertionPolicy:this.options.assertionPolicy,completedSteps:h>0?t.steps.slice(0,h).map(b=>b.resolvedText):void 0,recordOnly:y<s?{from:h,to:y-1}:void 0,takeFingerprint:async()=>oe(we(this.browser)??n)}));if(u=ln(u,m.usage),f.push(m.narrative),p.push(...m.adaptations),l.push(...m.featureEdits),m.suggestedFeatureEdit&&c.push(m.suggestedFeatureEdit),!m.success)return w(!1);let k=m.announcedSteps.filter(b=>b>=h&&b<s),v=Math.min(s-1,Math.max(k.length>0?Math.max(...k):y-1,h));for(let b=h;b<=v;b++)a[b]=m.recordedSteps[b];h=v+1}return w(!0)}async withDialogsVisible(t){let n=()=>{},r=[],s=[],o=i=>{i.on("dialog",n),r.push(i)};for(let i of this.browser?.contexts()??[]){i.on("page",o),s.push(i);for(let a of i.pages())o(a)}try{return await t()}finally{for(let i of s)i.off("page",o);for(let i of r)try{i.off("dialog",n)}catch{}}}async start(){let t=this.options.browser??"chromium";if(t==="chromium"){let n=await Kr();this.browser=await Gr.launch({headless:!this.options.headed,args:[`--remote-debugging-port=${n}`]}),this.cdpEndpoint=`http://127.0.0.1:${n}`}else this.browser=await(t==="firefox"?Yr:Jr).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=on.isAbsolute(this.options.storageState)?this.options.storageState:on.join(this.options.projectRoot,this.options.storageState);if(!sn.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}}async proofReplay(t,n){let r=await this.browser.newContext({storageState:this.resolveStorageState()}),s=await r.newPage();return{result:await ve(s,t,n,{baseURL:this.options.baseURL,actionTimeoutMs:this.options.actionTimeoutMs,retries:this.options.retries}),context:r,page:s}}async runScenario(t,n={}){let r=await this.runScenarioInner(t,n),s=be(t);if(s.size>0){let o=i=>i===void 0?i:pe(i,s);r.error=o(r.error),r.narrative=o(r.narrative),r.proofError=o(r.proofError),r.suggestedFeatureEdit=o(r.suggestedFeatureEdit),r.adaptations=r.adaptations.map(i=>pe(i,s));for(let i of r.stepResults)i.error=o(i.error)}return r}async runScenarioInner(t,n={}){if(!this.browser)throw new Error("Orchestrator not started");let r=Date.now(),{projectRoot:s,baseURL:o,actionTimeoutMs:i,retries:a}=this.options,d=B(s,t.featurePath,t.name),p=z(d),f=Se(s,t.featurePath,t.name),l=!p&&sn.existsSync(f)?ue(f):void 0,c=await this.browser.newContext({storageState:this.resolveStorageState()}),u=await c.newPage();try{let S;if(l){let m=await ve(u,t,l.cache,{baseURL:o,actionTimeoutMs:i,retries:a}),k=l.meta.recordedFor??t.name;if(m.status==="passed")return{scenario:t,status:"yellow",source:"agent-record",stepResults:m.stepResults,narrative:`Replayed the pending proposal recorded for "${k}" at zero AI; accept it to go green.`,adaptations:[],verified:!0,proposalFile:f,usage:fe,durationMs:Date.now()-r};if(Object.keys(t.params).length>0&&k!==t.displayName){let b=m.failure;return{scenario:t,status:"red",source:"agent-record",stepResults:m.stepResults,adaptations:[],proposalFile:f,usage:fe,durationMs:Date.now()-r,error:`The pending proposal recorded for "${k}" does not replay for this Examples row`+(b?` (step "${b.stepText}": ${b.error.split(`
|
|
35
|
+
`)[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."}}await u.goto("about:blank")}if(p&&(S=await ve(u,t,p,{baseURL:o,actionTimeoutMs:i,retries:a}),S.status==="passed"))return{scenario:t,status:"green",source:"cache",stepResults:S.stepResults,adaptations:[],usage:fe,durationMs:Date.now()-r};if(!(this.options.agent!==void 0&&this.cdpEndpoint!==void 0&&!n.agentDisabled)){let m=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:S?.stepResults??[],adaptations:[],usage:fe,durationMs:Date.now()-r,error:p?S?.status==="stale"?`Cache is stale (feature file changed) and ${m}`:`Replay failed and ${m} ${S?.failure?.error??""}`.trimEnd():`No cache exists and ${m}`}}let h=p!==void 0&&S!==void 0&&S.status==="failed",w=0,y;try{if(h)y=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:o,mode:"heal",model:this.options.healModel,cdpEndpoint:this.cdpEndpoint,assertionPolicy:this.options.assertionPolicy,completedSteps:S.stepResults.filter(m=>m.status==="passed").map(m=>m.gherkin),failedStep:{text:S.failure.stepText,kind:S.failure.kind,error:S.failure.error},takeFingerprint:async()=>{let m=we(this.browser)??u;return oe(m)}}));else if(await u.goto("about:blank"),this.options.reuseSteps!==!1){let m=await this.recordWithSeeding(t,u);w=m.seededCount,y=m}else y=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:o,mode:"record",cdpEndpoint:this.cdpEndpoint,assertionPolicy:this.options.assertionPolicy,takeFingerprint:async()=>{let m=we(this.browser)??u;return oe(m)}}))}catch(m){let k=m instanceof Error?m.message:String(m);return{scenario:t,status:"red",source:h?"agent-heal":"agent-record",stepResults:S?.stepResults??[],adaptations:[],usage:fe,durationMs:Date.now()-r,error:`Agent invocation failed: ${k.split(`
|
|
36
|
+
`)[0]}`}}if(y.success&&h&&S.failure.kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||an(p.steps,S.failure.stepIndex))){let m=p.steps[S.failure.stepIndex],k=we(this.browser)??u,v=new Map(Object.entries(S.captured)),b=tt(t,S.failure.stepIndex);try{for(let C of m.actions)await et(k,C,b,this.options.actionTimeoutMs??5e3,o,v)}catch(C){let x=C instanceof Error?C.message:String(C);return{scenario:t,status:"red",source:"agent-heal",stepResults:S.stepResults,narrative:y.narrative,adaptations:y.adaptations,suggestedFeatureEdit:y.suggestedFeatureEdit,usage:y.usage,durationMs:Date.now()-r,error:`Assertion failed as written: "${m.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: ${x.split(`
|
|
37
|
+
`)[0]}`}}}return await this.finalizeAgentRun(t,y,h,p,r,w,h?S?.failure:void 0)}finally{await c.close()}}async finalizeAgentRun(t,n,r,s,o,i=0,a){let d=r?"agent-heal":"agent-record",p=n.recordedSteps.map(v=>({gherkin:v.gherkin,kind:v.kind,status:n.success?"passed":"failed"}));if(!n.success)return{scenario:t,status:"red",source:d,stepResults:p,narrative:n.narrative,adaptations:n.adaptations,usage:n.usage,durationMs:Date.now()-o,error:n.narrative};let f=r?cn(s.steps,n.recordedSteps,this.options.assertionPolicy==="adaptable-mid",a?{stepIndex:a.stepIndex,actionIndex:a.actionIndex}:void 0):n.recordedSteps,l=[...n.adaptations],c={...n.usage},u,S;if(this.options.verifyProposals!==!1){let v=await this.proofReplay(t,this.buildCandidateCache(t,f));try{if(v.result.status!=="passed"&&v.result.failure){let b=v.result.failure;if(this.options.agent&&!(r&&b.kind==="assertion"&&(this.options.assertionPolicy!=="adaptable-mid"||an(s.steps,b.stepIndex))))try{let x=await this.withDialogsVisible(()=>this.options.agent.run({scenario:t,baseURL:this.options.baseURL,mode:"refine",model:r?this.options.healModel:void 0,cdpEndpoint:this.cdpEndpoint,assertionPolicy:this.options.assertionPolicy,completedSteps:v.result.stepResults.filter(R=>R.status==="passed").map(R=>R.gherkin),failedStep:{text:b.stepText,kind:b.kind,error:b.error},takeFingerprint:async()=>oe(we(this.browser)??v.page)}));c=ln(c,x.usage),x.success&&(l.push(...x.adaptations),f=r?cn(f,x.recordedSteps,this.options.assertionPolicy==="adaptable-mid"):Qr(f,x.recordedSteps),await v.context.close(),v=await this.proofReplay(t,this.buildCandidateCache(t,f)))}catch{}}u=v.result.status==="passed",u||(S=v.result.failure?.error??`proof replay ${v.result.status}`)}finally{await v.context.close().catch(()=>{})}}let g=[...n.featureEdits];for(let v of At(f,q(this.options.projectRoot)))l.push(`duplicate wording: "${v.from}" recorded exactly the same actions as the existing step "${v.to}" (${v.feature} \u203A ${v.scenario}). Accept with --with-feature-edit to converge on the canonical wording.`),g.some(b=>b.index===v.index)||g.push({index:v.index,text:v.to});let h=be(t),w=v=>h.size>0?pe(v,h):v;l=l.map(w);let y={meta:{createdAt:new Date().toISOString(),mode:r?"heal":"record",narrative:w(n.narrative),adaptations:l,suggestedFeatureEdit:n.suggestedFeatureEdit?w(n.suggestedFeatureEdit):void 0,featureEdits:g.length>0?g:void 0,verified:u,proofError:S?w(S):void 0,seededSteps:i>0?i:void 0,recordedFor:t.displayName,usage:c},cache:{version:1,feature:t.featurePath,scenario:t.name,recordedAt:new Date().toISOString(),recordedBy:"agent",steps:f}},m=Xt(f);m.length>0&&(u=!1,S=[S,...m].filter(Boolean).join(" "));let k=Se(this.options.projectRoot,t.featurePath,t.name);return Bt(k,y),{scenario:t,status:"yellow",source:d,stepResults:p,narrative:n.narrative,adaptations:l,suggestedFeatureEdit:n.suggestedFeatureEdit,featureEdits:g.length>0?g:void 0,verified:u,proofError:S,seededSteps:i>0?i:void 0,proposalFile:k,usage:c,durationMs:Date.now()-o}}};import Sn from"node:path";import{createRequire as rs}from"node:module";import{query as ss}from"@anthropic-ai/claude-agent-sdk";import{createSdkMcpServer as Xr,tool as ge}from"@anthropic-ai/claude-agent-sdk";import{z as $}from"zod";var M=e=>({content:[{type:"text",text:e}]});function pn(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 un={role:$.string().optional().describe("ARIA role of the element"),name:$.string().optional().describe("Accessible name \u2014 use the SHORTEST stable substring; never include volatile content like prices or dates"),nameRegex:$.string().optional().describe("Regex for the accessible name when it embeds volatile content, e.g. 'Select \\\\{date\\\\+1\\\\} as checkin' cannot work \u2014 instead use nameRegex 'Select .* as checkin'"),label:$.string().optional().describe("Form-label text for getByLabel \u2014 the literal <label> text only, never a free-text description"),text:$.string().optional().describe("getByText locator text"),selector:$.string().optional().describe("CSS fallback selector"),frame:$.string().optional().describe(`CSS selector of the iframe hosting the element, e.g. 'iframe[title="Feedback widget"]' \u2014 REQUIRED whenever the element lives inside an iframe; without it replay looks only at the top-level page`)};function fn(e){return Xr({name:"saffron",version:"0.1.0",tools:[ge("saffron_step","Announce the Gherkin step you are about to perform. MUST be called before executing browser actions for each step, with the step's zero-based index and exact text.",{index:$.number().int().min(0),text:$.string(),adaptation:$.string().optional().describe("If the written step does not match the real UI and you are deviating from it, describe the deviation in one sentence.")},async t=>(e.currentStepIndex=t.index,e.announced.add(t.index),t.adaptation&&e.adaptations.push(`Step ${t.index+1} ("${t.text}"): ${t.adaptation}`),M(`Recording step ${t.index}: ${t.text}`))),ge("saffron_capture",`Record a captureText action for the current step: at replay time, the target element's text is read and stored under saveAs for later expectDiffers comparisons. Use for steps like 'I record the displayed price as "X"'. The target must select exactly the element whose text is the value.`,{saveAs:$.string().describe("Name to store the captured text under"),...un},async t=>{let n=pn(t);return n?(e.addActions([{action:"captureText",target:n,saveAs:t.saveAs}]),M(`Capture recorded as "${t.saveAs}".`)):M("ERROR: capture needs a target (role/name, nameRegex, label, text, or selector).")}),ge("saffron_dialog","Record how a native dialog (alert/confirm/prompt) must be handled at replay. Call this IMMEDIATELY whenever an action triggers a native dialog \u2014 whether you handled it via browser_handle_dialog or the browser reported it as already handled. At replay Saffron arms this handler BEFORE the triggering action, so without this call the replay will auto-dismiss the dialog and diverge from what you saw.",{accept:$.boolean().describe("true = accept/OK the dialog, false = dismiss/cancel"),promptText:$.string().optional().describe("Text typed into a prompt() before accepting")},async t=>(e.addArmedAction({action:"handleDialog",value:t.accept?"accept":"dismiss",...t.promptText?{promptText:t.promptText}:{}}),M(`Dialog handling recorded (${t.accept?"accept":"dismiss"}).`))),ge("saffron_wait_api","Record a network wait for the current step: replay will block until a matching API response is observed (responses from the triggering step count). Call AFTER you verified via browser_network_requests that the response actually occurred with the expected status/body. Use a path-only urlPattern regex and never literal volatile IDs (/api/orders/\\d+, not /api/orders/8842).",{urlPattern:$.string().describe("Regex matched against the response URL \u2014 path-only for portability"),method:$.string().optional().describe("HTTP method to match (any if omitted)"),status:$.string().optional().describe("Expected status \u2014 exact ('201') or class ('2xx'); default any 2xx"),bodyPattern:$.string().optional().describe(`Regex the response body must match, e.g. '"status"\\s*:\\s*"READY"' for polling waits`)},async t=>(e.addActions([{action:"waitForResponse",urlPattern:t.urlPattern,...t.method?{method:t.method}:{},...t.status?{status:t.status}:{},...t.bodyPattern?{pattern:t.bodyPattern}:{}}]),M("Network wait recorded."))),ge("saffron_assert","Record a verified assertion for the current Then step. Call ONLY after you have confirmed the condition holds via a page snapshot. If the condition does NOT hold, do not call this \u2014 call saffron_done with success=false instead. NEVER record volatile content (prices, dates, counters) as literal expected text \u2014 use kind=matches with a pattern, or kind=differs against captured values.",{kind:$.enum(["visible","notVisible","text","url","value","differs","matches","attribute","response"]),...un,expected:$.string().optional().describe("Expected text/value for kind=text|value \u2014 stable text only, never volatile values"),url:$.string().optional().describe("URL substring for kind=url (path only, no host)"),pattern:$.string().optional().describe("kind=matches|attribute: regex the target's text (or attribute) must match, e.g. 'NOK [\\\\d,]+' for a price"),attribute:$.string().optional().describe("kind=attribute: attribute name to check, e.g. 'href' for link-target assertions \u2014 use this for 'X should link to Y' instead of clicking through"),capture:$.string().optional().describe("kind=differs: name of the captured value on the LEFT of the comparison (omit when comparing the target element's live text)"),urlPattern:$.string().optional().describe("kind=response: regex matched against the response URL \u2014 path-only for portability, never literal volatile IDs (use /api/orders/\\d+)"),method:$.string().optional().describe("kind=response: HTTP method to match (any if omitted)"),status:$.string().optional().describe("kind=response: expected status \u2014 exact ('201') or class ('2xx'); default any 2xx"),bodyPattern:$.string().optional().describe("kind=response: regex the response body must match (verify via browser_network_requests first)"),compareTo:$.string().optional().describe("kind=differs: name of the captured value to compare against")},async t=>{let n=pn(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 M("ERROR: kind=differs requires compareTo.");if(!t.capture&&!n)return M("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 M("ERROR: kind=matches requires pattern.");r={action:"expectMatches",target:n,pattern:t.pattern};break;case"attribute":if(!t.attribute||!t.pattern)return M("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 M("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?M("ERROR: assertion needs a target (role/name, nameRegex, label, text, or selector)."):(e.addActions([r]),M("Assertion recorded."))}),ge("saffron_done","Finalize the run. Call exactly once, after the final step: success=true only if every step's intent was achieved and every assertion verified.",{success:$.boolean(),narrative:$.string().describe("2-4 sentence summary of the run: what happened, and why it failed if it did."),suggestedFeatureEdit:$.string().optional().describe("If you adapted any steps: the corrected Gherkin for those steps, as you would rewrite them in the .feature file (free text, for the human report)."),featureEdits:$.array($.object({index:$.number().int().min(0).describe("zero-based step index"),text:$.string().describe("replacement step text WITHOUT the Given/When/Then keyword")})).optional().describe("Machine-applicable version of the suggested edits: one entry per adapted step. Provide this whenever you adapted a step.")},async t=>(e.done=!0,e.success=t.success,e.narrative=t.narrative,e.suggestedFeatureEdit=t.suggestedFeatureEdit,e.featureEdits=t.featureEdits??[],M("Run finalized.")))]})}function gn(e={}){let t=e.deliberateSnapshots?`
|
|
38
38
|
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.
|
|
39
39
|
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.
|
|
40
40
|
|
|
41
41
|
Non-negotiable rules:
|
|
42
42
|
1. Before performing each step, call saffron_step with the step's index and exact text. Only then perform the browser actions for that step.
|
|
43
|
-
2. ${
|
|
43
|
+
2. ${e.adaptableMidAssertions?"Steps marked [assertion:final] are sacred \u2014 they are the scenario's verdict. Verify them against a page snapshot; if the condition does not hold, the scenario FAILS: call saffron_done with success=false. Never manipulate the page to force them, never weaken or substitute them. Steps marked [assertion] (mid-scenario checkpoints) MAY be adapted under this project's policy when the written condition no longer matches a legitimately changed UI \u2014 record the equivalent verified condition via saffron_assert AND report the deviation via saffron_step's adaptation field plus featureEdits. An application defect is still a failure, not an adaptation.":'Steps marked [assertion] or [assertion:final] are sacred. Verify them against a page snapshot. If the condition holds, record it with saffron_assert. If it does not hold, the scenario FAILS: call saffron_done with success=false. Never click, navigate, or otherwise manipulate the page to force an assertion to become true, and never weaken or substitute the asserted condition for a "close enough" one.'}
|
|
44
44
|
3. A Given step (or a StepSet guard) that describes a state the page is ALREADY in needs no action and is NOT an adaptation: confirm it from the current snapshot and continue. Only report an adaptation when you had to do something different from what the step says.
|
|
45
45
|
3a. Steps marked [action] may be adapted if the written step does not match the real UI (e.g. a step refers to a control that does not exist, or a required intermediate step is missing). Adapt minimally to achieve the step's evident intent, and report the deviation via saffron_step's "adaptation" field. Before adapting, take a snapshot and decide: is this UI drift (adapt) or an application defect (fail with saffron_done success=false and explain)?
|
|
46
46
|
4. Do not pursue goals beyond the scenario. Do not retry an assertion more than twice.
|
|
@@ -52,78 +52,78 @@ Non-negotiable rules:
|
|
|
52
52
|
5c. Real-world page furniture is supported: elements inside IFRAMES record and replay fine (interact normally) \u2014 but when a saffron_assert targets an element INSIDE an iframe, you MUST pass the iframe's CSS selector as the 'frame' argument (e.g. frame='iframe[title="Feedback widget"]'); replay cannot see into frames otherwise. File uploads: use browser_file_upload with the file path. Drag-and-drop: use browser_drag. All of these are recorded and replay deterministically.
|
|
53
53
|
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.
|
|
54
54
|
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.
|
|
55
|
-
7. Never ask the user questions; you are unattended.${
|
|
56
|
-
${d.map(
|
|
57
|
-
`)}`),p!==void 0&&(
|
|
55
|
+
7. Never ask the user questions; you are unattended.${t}`}function Zr(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 mn(e){let{scenario:t}=e,n=t.steps.map((s,o)=>{let i=l=>xe(l),a=`${o}. [${Zr(t.steps,o)}] ${s.keyword} ${i(s.resolvedText)}`,d=s.resolvedTable??s.table,p=s.resolvedDocString??s.docString,f=a;return d&&(f+=`
|
|
56
|
+
${d.map(l=>` | ${l.map(i).join(" | ")} |`).join(`
|
|
57
|
+
`)}`),p!==void 0&&(f+=`
|
|
58
58
|
"""
|
|
59
59
|
${i(p).split(`
|
|
60
|
-
`).map(
|
|
60
|
+
`).map(l=>` ${l}`).join(`
|
|
61
61
|
`)}
|
|
62
|
-
"""`),
|
|
63
|
-
`),r=[`Feature: ${
|
|
64
|
-
${(
|
|
65
|
-
`)||" (none)"}`,"",`Failed step: [${
|
|
66
|
-
${(
|
|
67
|
-
`)||" (none)"}`,"",`Failed step: [${
|
|
68
|
-
${
|
|
69
|
-
`)}`:"You are starting from a blank page.","",`Record ONLY steps ${
|
|
70
|
-
`),"",`The browser currently shows the state after those ${
|
|
71
|
-
`)}import{query as
|
|
72
|
-
`),a.set(
|
|
73
|
-
`));return
|
|
74
|
-
<path d="${
|
|
75
|
-
<path d="${
|
|
76
|
-
</svg>`}function
|
|
77
|
-
<div class="kpi-label">${
|
|
78
|
-
<div class="kpi-value ${r}">${
|
|
79
|
-
<div class="kpi-sub ${
|
|
80
|
-
</div>`}function
|
|
81
|
-
${
|
|
82
|
-
${
|
|
83
|
-
${
|
|
84
|
-
${
|
|
85
|
-
${
|
|
86
|
-
${
|
|
87
|
-
${n.plan?
|
|
88
|
-
</section>`}function
|
|
89
|
-
`)}</section>`:""}function
|
|
62
|
+
"""`),f}).join(`
|
|
63
|
+
`),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:
|
|
64
|
+
${(e.completedSteps??[]).map(s=>` \u2713 ${s}`).join(`
|
|
65
|
+
`)||" (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:
|
|
66
|
+
${(e.completedSteps??[]).map(s=>` \u2713 ${s}`).join(`
|
|
67
|
+
`)||" (none)"}`,"",`Failed step: [${e.failedStep?.kind}] ${e.failedStep?.text}`,`Failure: ${e.failedStep?.error}`,"","First diagnose: did the UI legitimately change (heal: adapt the actions, record via saffron_step + browser tools), or is the application broken (fail: saffron_done success=false with your diagnosis)?",e.assertionPolicy==="adaptable-mid"?"If the failed step is an [assertion:final]: you may re-verify the SAME condition once against the live page (timing), but if it does not hold AS WRITTEN, the run FAILS \u2014 call saffron_done success=false; never substitute it. If the failed step is a mid-scenario [assertion]: this project's policy allows adapting it \u2014 verify the equivalent condition on the legitimately-changed UI, record it via saffron_assert, and report the deviation via saffron_step's adaptation field plus featureEdits. An application defect still fails.":"If the failed step is an [assertion] or [assertion:final]: you may re-verify the SAME condition once against the live page (it may have been a timing issue). If the condition AS WRITTEN does not hold, the run FAILS \u2014 call saffron_done success=false. Do NOT substitute a different element, text, or URL that 'means the same thing'; suggesting a corrected assertion belongs in suggestedFeatureEdit of your failure report, never in saffron_assert.","Announce (saffron_step) and perform only the failed step and the steps after it.");else if(e.mode==="record"&&e.recordOnly){let{from:s,to:o}=e.recordOnly;r.push("MODE: RECORD (segment). This scenario is being composed from existing recordings plus your work.",e.completedSteps&&e.completedSteps.length>0?`Already executed against the live browser (do NOT redo):
|
|
68
|
+
${e.completedSteps.map(i=>` \u2713 ${i}`).join(`
|
|
69
|
+
`)}`:"You are starting from a blank page.","",`Record ONLY steps ${s} through ${o} (inclusive).`,`CRITICAL STOP RULE: the steps AFTER step ${o} already have recordings and will be replayed automatically the moment you stop. After completing step ${o}, immediately call saffron_done \u2014 do NOT perform, verify, or navigate into any later step. Executing a later step yourself would make the automatic replay run it TWICE.`)}else if(e.completedSteps&&e.completedSteps.length>0){let s=e.completedSteps.length;r.push("MODE: RECORD (seeded). No cache exists for this scenario yet, but its first steps matched existing recordings and were ALREADY EXECUTED against the live browser by zero-AI replay:",e.completedSteps.map(o=>` \u2713 ${o}`).join(`
|
|
70
|
+
`),"",`The browser currently shows the state after those ${s} step(s) (verify with a snapshot if unsure). Do NOT redo them and do NOT navigate away from the current state.`,`Start with saffron_step for step index ${s} and record from there to the end.`)}else r.push("MODE: RECORD. No cache exists for this scenario yet.","Execute every step in order, starting at step 0. Navigate to the base URL first if the scenario implies a starting page.");return r.filter(s=>s!==void 0).join(`
|
|
71
|
+
`)}import{query as es}from"@anthropic-ai/claude-agent-sdk";var ts="usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET";async function st(e,t=8e3){let n=e?.[ts];if(typeof n!="function")return;let r;try{let s=await Promise.race([n.call(e),new Promise(o=>{r=setTimeout(()=>o(void 0),t),r.unref?.()})]);return ns(s)}catch{return}finally{r&&clearTimeout(r)}}function ns(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 hn(){let e=()=>{},t=new Promise(s=>e=s);async function*n(){await t}let r;try{let s=es({prompt:n(),options:{maxTurns:1,tools:[],settingSources:[],persistSession:!1}});r=s;let o=(async()=>{try{for await(let a of s);}catch{}})(),i=await st(s);return e(),r.close?.(),await o,i}catch{e(),r?.close?.();return}}var os=rs(import.meta.url);function is(){let e=os.resolve("@playwright/mcp/package.json");return Sn.join(Sn.dirname(e),"cli.js")}var as=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"]),Ie=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 hn();return{subscriptionType:t.subscriptionType,fiveHourBefore:t.utilization,fiveHourAfter:n?.utilization,resetsAt:n?.resetsAt??t.resetsAt}}async run(t){let n=new Ce(t.scenario),r={aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0},s="",o=ss({prompt:mn(t),options:{systemPrompt:gn({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:[is(),"--cdp-endpoint",t.cdpEndpoint,"--snapshot-mode",this.opts.snapshotMode??"none","--image-responses","omit"]},saffron:fn(n)},hooks:{PreToolUse:[{hooks:[async i=>{let a=i;if(as.has(a.tool_name)&&t.takeFingerprint&&!n.pendingFingerprint)try{n.pendingFingerprint=await t.takeFingerprint()}catch{}return{continue:!0}}]}],PostToolUse:[{hooks:[async i=>{let a=i,d=rn(a.tool_name,a.tool_input);return d&&n.addArmedAction(d),a.tool_name.startsWith("mcp__playwright__")&&(n.addActions(Qt(a.tool_response,t.baseURL)),n.pendingFingerprint=void 0),{continue:!0}}]}]}}});this.planBefore||(this.planBefore=st(o));try{for await(let i of o)i.type==="result"&&(r.aiCalls=i.num_turns,r.costUsd=i.total_cost_usd,"modelUsage"in i&&i.modelUsage&&(r.models=Object.keys(i.modelUsage)),"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),i.subtype==="success"&&(s=i.result))}catch(i){let a=i instanceof Error?i.message:String(i);n.done=!0,n.success=!1,n.narrative=`Agent session error: ${a}`}return n.done||(n.success=!1,n.narrative=n.narrative||`Agent session ended without finalizing the run. Last output: ${s.slice(0,500)}`),{success:n.success,narrative:n.narrative,adaptations:n.adaptations,suggestedFeatureEdit:n.suggestedFeatureEdit,featureEdits:n.featureEdits.map(i=>({index:i.index,text:rt(i.text,t.scenario.params)})),recordedSteps:nn(tn(Zt(en(n.steps,t.scenario),t.scenario.params)),be(t.scenario)),announcedSteps:[...n.announced].sort((i,a)=>i-a),usage:r}}};function je(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 yn(e){return e.plan?` \xB7 5-hour window ${ot(e.plan.fiveHourBefore,e.plan.fiveHourAfter)} (${e.plan.subscriptionType} plan) \xB7 \u2248 ${je(e.costUsd)} at API rates`:` \xB7 ${je(e.costUsd)}`}function xn(e,t){return e?t?`\u2248 ${je(e)}`:je(e):""}function bn(e){if(!e)return"";let t=new Date(e);return Number.isNaN(t.getTime())?"":`resets ${t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`}import vn from"node:fs";import _e from"node:path";function Oe(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])}function wn(e,t){let n=new Map,r=Math.min(e.steps.length,t.steps.length);for(let s=0;s<r;s++){let o=e.steps[s].actions,i=t.steps[s].actions;if(o.length===i.length)for(let a=0;a<o.length;a++){let d=o[a],p=i[a];if(d.action!==p.action||!d.target||!p.target)continue;let f=Oe(d.target);f!==Oe(p.target)&&n.set(f,{from:d.target,to:p.target})}}return[...n.values()]}function cs(e){let t=_e.join(e,".saffron","cache");if(!vn.existsSync(t))return[];let n=[];for(let r of vn.readdirSync(t,{recursive:!0})){let s=String(r);s.endsWith(".json")&&n.push(_e.join(t,s))}return n}function kn(e,t,n,r){if(t.length===0)return[];let s=new Map(t.map(i=>[Oe(i.from),i])),o=[];for(let i of cs(e)){if(_e.resolve(i)===_e.resolve(n))continue;let a=z(i);if(!a)continue;let d=[],p=!1;for(let f of a.steps){let l=0;for(let c of f.actions){if(!c.target)continue;let u=s.get(Oe(c.target));u&&(l++,r||(c.target=structuredClone(u.to),p=!0))}l>0&&d.push({gherkin:f.gherkin,count:l})}d.length>0&&(p&&le(i,a),o.push({file:i,scenario:a.scenario,feature:a.feature,steps:d}))}return o}function it(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 $n from"node:fs";import at from"node:path";function Rn(e,t,n,r,s){let o={applied:[],skipped:[]},i=Z(at.join(e,t),e,s).find(p=>p.name===n);if(!i){for(let p of r)o.skipped.push({index:p.index,reason:`scenario "${n}" not found in ${t}`});return o}let a=new Map,d=new Set;for(let p of r){let f=i.steps[p.index];if(!f?.source){o.skipped.push({index:p.index,reason:`no step at index ${p.index}`});continue}let{file:l,line:c,fromStepSet:u,fromBackground:S}=f.source;if(S){o.skipped.push({index:p.index,reason:`"${f.text}" is a Background step shared across scenarios; edit it manually`});continue}let g=`${l}:${c}`;if(d.has(g))continue;let h=a.get(l);h||(h=$n.readFileSync(at.join(e,l),"utf8").split(`
|
|
72
|
+
`),a.set(l,h));let w=h[c-1],y=w?.match(/^(\s*)(\S+)\s+(.*)$/);if(!y||y[3]!==f.text){o.skipped.push({index:p.index,reason:`${l}:${c} no longer matches the recorded step text`});continue}let m=`${y[1]}${y[2]} ${p.text}`;h[c-1]=m,d.add(g),o.applied.push({file:l,line:c,from:w.trim(),to:m.trim(),fromStepSet:u})}for(let[p,f]of a)o.applied.some(l=>l.file===p)&&$n.writeFileSync(at.join(e,p),f.join(`
|
|
73
|
+
`));return o}import dt from"node:fs";import ct from"node:fs";import De from"node:path";import{fileURLToPath as ls}from"node:url";function Me(){let e=De.dirname(ls(import.meta.url));for(let t=0;t<6;t++){let n=De.join(e,"package.json");if(ct.existsSync(n))try{if(JSON.parse(ct.readFileSync(n,"utf8")).name==="saffron-ai")return e}catch{}e=De.dirname(e)}}function me(){let e=Me();if(!e)return"unknown";try{return JSON.parse(ct.readFileSync(De.join(e,"package.json"),"utf8")).version??"unknown"}catch{return"unknown"}}import pt from"node:path";var j=e=>e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',"""),An="M11 14 L10 4.5 L17.5 9.5 L24 2.5 L30.5 9.5 L38 4.5 L37 14 Z",ds="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 ps(e){return`<svg viewBox="0 0 48 48" width="${e}" height="${e}" aria-hidden="true">
|
|
74
|
+
<path d="${An}" fill="#F4A300"/>
|
|
75
|
+
<path d="${ds}" fill="#E7E9EC"/>
|
|
76
|
+
</svg>`}function us(e){return`<svg viewBox="8 1 32 15" height="${e}" aria-hidden="true"><path d="${An}" fill="#F4A300"/></svg>`}var fs={green:"passed",yellow:"pending review",red:"failed"};function Ne(e){return e>=1e3?`${(e/1e3).toFixed(1)}s`:`${e}ms`}function ke(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e4?`${(e/1e3).toFixed(1)}k`:e.toLocaleString()}function Y(e,t,n,r="",s="",o=""){return`<div class="kpi">
|
|
77
|
+
<div class="kpi-label">${e}</div>
|
|
78
|
+
<div class="kpi-value ${r}">${t}</div>
|
|
79
|
+
<div class="kpi-sub ${s}">${n}</div>${o}
|
|
80
|
+
</div>`}function lt(e,t){if(e.length<2)return"";let n=108,r=22,s=Math.min(...e),i=Math.max(...e)-s||1,a=e.map((d,p)=>`${(p/(e.length-1)*n).toFixed(1)},${(r-2-(d-s)/i*(r-4)).toFixed(1)}`).join(" ");return`<svg class="spark" viewBox="0 0 ${n} ${r}" width="${n}" height="${r}" aria-hidden="true"><polyline points="${a}" fill="none" stroke="${t}" stroke-width="1.8" stroke-linejoin="round" stroke-linecap="round"/></svg>`}var Tn=(e,t="",n=0)=>`${e>=0?"+":"\u2212"}${Math.abs(e).toFixed(n)}${t} vs prev`;function gs(e,t){let n=e.totals,r=e.trends,s=n.scenarios===0?0:Math.round((n.green+n.yellow)/n.scenarios*100),o=n.red>0?"red":n.yellow>0?"gold":"green",i=n.inputTokens+n.outputTokens,a=r?.prev?`${Tn(r.prev.passRatePp,"pp")} \xB7 ${n.green+n.yellow} of ${n.scenarios}`:`${n.green+n.yellow} of ${n.scenarios} scenarios`,d=r?.prev?`${Tn(r.prev.costUsd,"",4).replace("+","+$").replace("\u2212","\u2212$")} \xB7 ${Ne(t)}`:`${Ne(t)} total runtime`;return`<section class="kpis">
|
|
81
|
+
${Y("pass rate",`${s}<span class="unit">%</span>`,a,o,r?.prev?r.prev.passRatePp>=0?"green":"red":"",lt(r?.series.passRate??[],"var(--green)"))}
|
|
82
|
+
${Y("passed",String(n.green),"deterministic replay","green",n.green>0?"green":"")}
|
|
83
|
+
${Y("pending",String(n.yellow),n.yellow>0?"\u25B2 proposals to review":"nothing to review",n.yellow>0?"gold":"",n.yellow>0?"gold":"")}
|
|
84
|
+
${Y("failed",String(n.red),n.red>0?"\u25BC needs attention":"all clear",n.red>0?"red":"",n.red>0?"red":"green")}
|
|
85
|
+
${Y("ai calls",String(n.aiCalls),`${ke(i)} in+out tokens`,n.aiCalls>0?"":"green")}
|
|
86
|
+
${Y("cache traffic",ke(n.cacheReadTokens+n.cacheCreationTokens),n.cacheReadTokens+n.cacheCreationTokens>0?`${ke(n.cacheReadTokens)} read \xB7 ${ke(n.cacheCreationTokens)} written`:"zero (fully cached run)","",n.cacheReadTokens+n.cacheCreationTokens>0?"":"green")}
|
|
87
|
+
${n.plan?Y("plan usage",`${ot(n.plan.fiveHourBefore,n.plan.fiveHourAfter)}`,[`5-hour window \xB7 ${n.plan.subscriptionType} plan`,bn(n.plan.resetsAt)].filter(Boolean).join(" \xB7 "),"gold","")+Y("api-equivalent",`<span class="unit">\u2248 $</span>${n.costUsd.toFixed(n.costUsd>=1?2:4)}`,`what this run costs on an API key \xB7 ${d}`,"","",lt(r?.series.costUsd??[],"var(--gold)")):Y("ai cost",`<span class="unit">$</span>${n.costUsd.toFixed(n.costUsd>=1?2:4)}`,d,"","",lt(r?.series.costUsd??[],"var(--gold)"))}
|
|
88
|
+
</section>`}function ms(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>${j(r.feature)} \u203A ${j(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: ${j(r.message)}</li>`).join("")}</ul></div>`),n.length>0?`<section class="trends">${n.join(`
|
|
89
|
+
`)}</section>`:""}function hs(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}">
|
|
90
90
|
${r}
|
|
91
91
|
<div class="step-body">
|
|
92
|
-
<span class="step-text">${
|
|
92
|
+
<span class="step-text">${j(n.gherkin)}</span>
|
|
93
93
|
${n.kind==="assertion"?'<span class="tag">assert</span>':""}
|
|
94
|
-
${n.fromStepSet?`<span class="tag indigo" title="inlined from a StepSet definition: edit once, every invoking scenario follows">from StepSet: ${
|
|
94
|
+
${n.fromStepSet?`<span class="tag indigo" title="inlined from a StepSet definition: edit once, every invoking scenario follows">from StepSet: ${j(n.fromStepSet)}</span>`:""}
|
|
95
95
|
${n.drift?'<span class="tag gold" title="page fingerprint no longer matches the recording">drift</span>':""}
|
|
96
96
|
${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>`:""}
|
|
97
|
-
${n.error?`<div class="step-error">${
|
|
97
|
+
${n.error?`<div class="step-error">${j(n.error)}</div>`:""}
|
|
98
98
|
</div>
|
|
99
99
|
</li>`}).join(`
|
|
100
|
-
`)}</ol>`}function
|
|
100
|
+
`)}</ol>`}function Ss(e){return e.featureEdits&&e.featureEdits.length>0?`<div class="panel">
|
|
101
101
|
<div class="panel-title gold">suggested .feature edit</div>
|
|
102
|
-
<div class="diff">${
|
|
102
|
+
<div class="diff">${e.featureEdits.map(n=>{let r=e.steps[n.index]?.gherkin??`step ${n.index}`;return`<div class="diff-line del">\u2212 ${j(r)}</div><div class="diff-line add">+ ${j(n.text)}</div>`}).join("")}</div>
|
|
103
103
|
<div class="panel-hint">apply with <code>saffron accept --with-feature-edit</code></div>
|
|
104
|
-
</div>`:
|
|
104
|
+
</div>`:e.suggestedFeatureEdit?`<div class="panel"><div class="panel-title gold">suggested .feature edit</div><pre>${j(e.suggestedFeatureEdit)}</pre></div>`:""}function ys(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=xn(e.usage.costUsd,t),s=r?` \xB7 ${r}`:"";return`<span class="pill gold">${e.usage.aiCalls} ai \xB7 ${ke(n)} tok${s}</span>`}function xs(e,t){return`<details class="card" ${e.status!=="green"?"open":""}>
|
|
105
105
|
<summary>
|
|
106
|
-
<span class="pill ${
|
|
107
|
-
<span class="card-title">${
|
|
106
|
+
<span class="pill ${e.status==="green"?"green":e.status==="yellow"?"gold":"red"}">${fs[e.status]}</span>
|
|
107
|
+
<span class="card-title">${j(e.scenario)}</span>
|
|
108
108
|
<span class="card-meta">
|
|
109
|
-
<span class="m">${
|
|
109
|
+
<span class="m">${j(e.feature)}</span>
|
|
110
110
|
<span class="m-sep">\xB7</span>
|
|
111
|
-
<span class="m">${
|
|
111
|
+
<span class="m">${j(e.source)}</span>
|
|
112
112
|
<span class="m-sep">\xB7</span>
|
|
113
|
-
<span class="m">${
|
|
114
|
-
${
|
|
113
|
+
<span class="m">${Ne(e.durationMs)}</span>
|
|
114
|
+
${ys(e,t)}
|
|
115
115
|
</span>
|
|
116
116
|
</summary>
|
|
117
117
|
<div class="card-body">
|
|
118
|
-
${
|
|
119
|
-
${
|
|
120
|
-
${
|
|
121
|
-
${
|
|
122
|
-
${
|
|
118
|
+
${hs(e)}
|
|
119
|
+
${e.narrative?`<div class="panel"><div class="panel-title">agent narrative</div><p>${j(e.narrative)}</p></div>`:""}
|
|
120
|
+
${e.adaptations.length>0?`<div class="panel accent-gold"><div class="panel-title gold">adaptations</div><ul>${e.adaptations.map(n=>`<li>${j(n)}</li>`).join("")}</ul></div>`:""}
|
|
121
|
+
${Ss(e)}
|
|
122
|
+
${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">${j(e.proposalFile)}</p>${e.verified===!1&&e.proofError?`<p class="mono" style="color:var(--red)">proof replay failed: ${j(e.proofError.split(`
|
|
123
123
|
`)[0])}</p>`:""}<div class="panel-hint">review with <code>saffron accept</code> / <code>saffron reject</code></div></div>`:""}
|
|
124
|
-
${
|
|
124
|
+
${e.error&&e.status==="red"?`<div class="panel accent-red"><div class="panel-title red">failure</div><p>${j(e.error)}</p></div>`:""}
|
|
125
125
|
</div>
|
|
126
|
-
</details>`}function
|
|
126
|
+
</details>`}function En(e){let t=e.totals,n=new Date(e.startedAt),r=new Date(e.finishedAt).getTime()-n.getTime(),s=n.toLocaleString("en-GB",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"});return`<!doctype html>
|
|
127
127
|
<html lang="en">
|
|
128
128
|
<head>
|
|
129
129
|
<meta charset="utf-8"/>
|
|
@@ -243,61 +243,63 @@ ${t.completedSteps.map(i=>` \u2713 ${i}`).join(`
|
|
|
243
243
|
<div class="wrap">
|
|
244
244
|
<header class="top">
|
|
245
245
|
<div class="brand">
|
|
246
|
-
${
|
|
246
|
+
${ps(38)}
|
|
247
247
|
<div>
|
|
248
248
|
<div class="brand-name">saffron</div>
|
|
249
249
|
<div class="brand-sub">test run report</div>
|
|
250
250
|
</div>
|
|
251
251
|
</div>
|
|
252
252
|
<div class="run-meta">
|
|
253
|
-
<span>${
|
|
253
|
+
<span>${j(s)}</span>
|
|
254
254
|
<span>\xB7</span>
|
|
255
|
-
<span>${
|
|
256
|
-
${
|
|
255
|
+
<span>${Ne(r)}</span>
|
|
256
|
+
${e.baseURL?`<span class="chip base">${j(e.baseURL)}</span>`:""}
|
|
257
257
|
</div>
|
|
258
258
|
</header>
|
|
259
259
|
|
|
260
|
-
${
|
|
261
|
-
${
|
|
260
|
+
${gs(e,r)}
|
|
261
|
+
${ms(e)}
|
|
262
262
|
|
|
263
263
|
<div class="section-head">
|
|
264
|
-
<span class="section-title">scenarios \xB7 ${
|
|
265
|
-
<span class="section-title">saffron v${
|
|
264
|
+
<span class="section-title">scenarios \xB7 ${t.scenarios}</span>
|
|
265
|
+
<span class="section-title">saffron v${j(e.version)}</span>
|
|
266
266
|
</div>
|
|
267
|
-
${
|
|
267
|
+
${e.scenarios.map(o=>xs(o,!!e.totals.plan)).join(`
|
|
268
268
|
`)}
|
|
269
269
|
|
|
270
|
-
<footer>${
|
|
270
|
+
<footer>${us(11)} generated by saffron v${j(e.version)} \xB7 ${j(new Date(e.finishedAt).toLocaleString("en-GB",{dateStyle:"medium",timeStyle:"medium"}))}</footer>
|
|
271
271
|
</div>
|
|
272
272
|
</body>
|
|
273
273
|
</html>
|
|
274
|
-
`}function
|
|
275
|
-
`),
|
|
276
|
-
`)[0]}));return{runId:
|
|
277
|
-
`)}function
|
|
278
|
-
`).filter(Boolean),
|
|
279
|
-
`)}
|
|
274
|
+
`}function Pn(e,t,n){let r={scenarios:e.length,green:0,yellow:0,red:0,aiCalls:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0},s=new Set;for(let o of e){for(let i of o.usage.models??[])s.add(i);r[o.status]+=1,r.aiCalls+=o.usage.aiCalls,r.inputTokens+=o.usage.inputTokens,r.outputTokens+=o.usage.outputTokens,r.cacheReadTokens+=o.usage.cacheReadTokens,r.cacheCreationTokens+=o.usage.cacheCreationTokens??0,r.costUsd+=o.usage.costUsd??0}return s.size>0&&(r.models=[...s].sort()),{tool:"saffron",version:me(),startedAt:t.toISOString(),finishedAt:new Date().toISOString(),baseURL:n,totals:r,scenarios:e.map(o=>({feature:o.scenario.featurePath,scenario:o.scenario.displayName,tags:[...o.scenario.tags],status:o.status,source:o.source,durationMs:o.durationMs,usage:o.usage,steps:o.stepResults,narrative:o.narrative,adaptations:o.adaptations,suggestedFeatureEdit:o.suggestedFeatureEdit,featureEdits:o.featureEdits,verified:o.verified,proofError:o.proofError,proposalFile:o.proposalFile,error:o.error}))}}function Cn(e,t){let n=pt.join(e,".saffron","reports");dt.mkdirSync(n,{recursive:!0});let r=pt.join(n,"latest.json"),s=pt.join(n,"latest.html");return dt.writeFileSync(r,`${JSON.stringify(t,null,2)}
|
|
275
|
+
`),dt.writeFileSync(s,En(t)),{json:r,html:s}}function Fn(e){let t=e===void 0?[]:Array.isArray(e)?e:[e],n=new Set;for(let r of t)for(let s of r.split(/[\s,|]+/)){let o=s.trim();o&&n.add(o.startsWith("@")?o:`@${o}`)}return[...n]}function In(e,t){return t.length===0?e:e.filter(n=>n.tags.some(r=>t.includes(r)))}function jn(e,t){return[...t??[],e]}import _n from"node:fs";import bs from"node:path";function ee(e){Vt(e);let t=bs.join(e,"saffron.config.json");return _n.existsSync(t)?JSON.parse(_n.readFileSync(t,"utf8")):{}}var vs={features:"features",actionTimeoutMs:5e3,retries:1,maxTurns:100,strict:!1,verifyProposals:!0,snapshotMode:"none",reuseSteps:!0,browser:"chromium",workers:1,assertionPolicy:"strict"};function On(e){return{...vs,...Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}}import J from"node:fs";import K from"node:path";import Ue from"node:fs";import Dn from"node:path";function Mn(e){return Dn.join(e,".saffron","history.jsonl")}function Nn(e,t,n,r){let s=e.map(o=>({feature:o.scenario.featurePath,scenario:o.scenario.displayName,tags:[...o.scenario.tags],status:o.status,source:o.source,durationMs:o.durationMs,verified:o.verified,seededSteps:o.seededSteps,adaptations:o.adaptations.length,driftSteps:o.stepResults.filter(i=>i.drift).length,aiCalls:o.usage.aiCalls,tokensInOut:o.usage.inputTokens+o.usage.outputTokens,cacheRead:o.usage.cacheReadTokens,cacheWrite:o.usage.cacheCreationTokens,costUsd:o.usage.costUsd??0,error:o.error?.split(`
|
|
276
|
+
`)[0]}));return{runId:t.toISOString(),startedAt:t.toISOString(),finishedAt:new Date().toISOString(),baseURL:r,green:s.filter(o=>o.status==="green").length,yellow:s.filter(o=>o.status==="yellow").length,red:s.filter(o=>o.status==="red").length,aiCalls:s.reduce((o,i)=>o+i.aiCalls,0),costUsd:s.reduce((o,i)=>o+i.costUsd,0),divergentSteps:n,scenarios:s}}function Un(e,t){let n=Mn(e);Ue.mkdirSync(Dn.dirname(n),{recursive:!0}),Ue.appendFileSync(n,`${JSON.stringify(t)}
|
|
277
|
+
`)}function Le(e,t=50){let n=Mn(e);if(!Ue.existsSync(n))return[];let r=Ue.readFileSync(n,"utf8").trim().split(`
|
|
278
|
+
`).filter(Boolean),s=[];for(let o of r.slice(-t))try{s.push(JSON.parse(o))}catch{}return s}var ut=e=>{let t=e.green+e.yellow+e.red;return t===0?0:Math.round((e.green+e.yellow)/t*100)};function Ln(e,t){let n=[...e,t],r=n.slice(-20),s=n.slice(-10),o=e.at(-1),i=o?{passRatePp:ut(t)-ut(o),costUsd:t.costUsd-o.costUsd,aiCalls:t.aiCalls-o.aiCalls,red:t.red-o.red}:void 0,a=new Map;for(let l of s)for(let c of l.scenarios){let u=`${c.feature}::${c.scenario}`,S=a.get(u)??{feature:c.feature,scenario:c.scenario,heals:0,reds:0,runs:0};S.runs++,c.source==="agent-heal"&&c.status==="yellow"&&S.heals++,c.status==="red"&&S.reds++,a.set(u,S)}let d=[...a.values()].filter(l=>l.heals>=2||l.reds>=3).sort((l,c)=>c.heals+c.reds-(l.heals+l.reds)),p=new Map;for(let l of r)for(let c of l.scenarios)c.status==="red"&&c.error&&p.set(c.error,(p.get(c.error)??0)+1);let f=[...p.entries()].sort((l,c)=>c[1]-l[1]).slice(0,3).map(([l,c])=>({message:l,count:c}));return{prev:i,series:{passRate:r.map(ut),costUsd:r.map(l=>Number(l.costUsd.toFixed(4))),aiCalls:r.map(l=>l.aiCalls)},chronic:d,divergentSteps:t.divergentSteps,topIssues:f}}var ws=/^\s*(?:Scenario(?: Outline| Template)?|Example):\s*(.+?)\s*$/,ks=/^\s*StepSet:/;function ft(e,t){return K.relative(e,t).split(K.sep).join("/")}function $s(e,t){let n={green:0,yellow:1,red:2};return!e||n[t]>n[e]?t:e}function Vn(e,t){return`${e} :: ${t}`}function zn(e,t,n={}){let r=t.features??"features",s=K.isAbsolute(r)?r:K.join(e,r),o=K.join(e,".saffron","reports","latest.json"),i=K.join(e,".saffron","reports","latest.html"),a;try{a=JSON.parse(J.readFileSync(o,"utf8"))}catch{a=void 0}let d=new Map;for(let m of a?.scenarios??[]){let k=m.scenario.replace(/ \(example \d+\)$/,""),v=Vn(m.feature,k);d.set(v,$s(d.get(v),m.status))}let p=new Map,f;try{p=X(ce(s),e)}catch(m){f=m instanceof Error?m.message:String(m)}let l=J.existsSync(s)?[...J.readdirSync(s,{recursive:!0})].map(String).filter(re).map(m=>K.join(s,m)).sort():[],c=[],u=new Map;for(let m of l){let k=ft(e,m),v="";try{v=J.readFileSync(m,"utf8")}catch(P){c.push({path:k,name:k,scenarios:[],stepSets:0,error:String(P)});continue}let b=v.split(`
|
|
279
|
+
`),C=new Map,x=0;b.forEach((P,Q)=>{let V=P.match(ws);V&&!C.has(V[1])?C.set(V[1],Q+1):ks.test(P)&&x++});let R=b.find(P=>/^\s*Feature:/.test(P)),E=R?R.replace(/^\s*Feature:\s*/,"").trim():k,I;try{I=Z(m,e,p)}catch(P){c.push({path:k,name:E,scenarios:[],stepSets:x,error:f??(P instanceof Error?P.message:String(P))});continue}let O=new Map;for(let P of I){let Q=O.get(P.name);if(Q){Q.rows+=1;continue}O.set(P.name,{name:P.name,line:C.get(P.name),tags:[...P.tags],outline:Object.keys(P.params).length>0,rows:1,cached:J.existsSync(B(e,P.featurePath,P.name)),proposal:J.existsSync(Se(e,P.featurePath,P.name)),lastStatus:d.get(Vn(P.featurePath,P.name))});for(let V of P.tags)u.set(V,(u.get(V)??0)+1)}c.push({path:k,name:E,scenarios:[...O.values()],stepSets:x})}let S=se(e).map(({file:m,proposal:k})=>({file:ft(e,m),feature:k.cache.feature,scenario:k.cache.scenario,mode:k.meta.mode,createdAt:k.meta.createdAt,verified:k.meta.verified,proofError:k.meta.proofError,adaptations:k.meta.adaptations??[],narrative:k.meta.narrative,suggestedFeatureEdit:k.meta.suggestedFeatureEdit,recordedFor:k.meta.recordedFor,aiCalls:k.meta.usage?.aiCalls??0,costUsd:k.meta.usage?.costUsd})).sort((m,k)=>m.file.localeCompare(k.file)),g;try{g=H(e,r,p)}catch{g={steps:[],stepSets:[],scannedFiles:0,scannedCaches:0}}let h=Ts(e),w=Le(e,n.historyLimit??30).map(m=>({startedAt:m.startedAt,green:m.green,yellow:m.yellow,red:m.red,aiCalls:m.aiCalls,costUsd:m.costUsd})),y=K.join(e,"saffron.config.json");return{tool:"saffron",version:me(),projectRoot:e,packageInstalled:J.existsSync(K.join(e,"node_modules","saffron-ai")),config:{file:J.existsSync(y)?"saffron.config.json":void 0,effective:On(t)},features:c,tags:[...u.entries()].map(([m,k])=>({tag:m,scenarios:k})).sort((m,k)=>m.tag.localeCompare(k.tag)),proposals:S,lastRun:a?{startedAt:a.startedAt,finishedAt:a.finishedAt,totals:a.totals,reportHtml:J.existsSync(i)?ft(e,i):void 0}:void 0,history:w,vocabulary:{steps:g.steps.length,recorded:g.steps.filter(m=>m.status==="recorded").length,unrecorded:g.steps.filter(m=>m.status==="unrecorded").length,stepSets:g.stepSets.length,divergent:g.steps.filter(m=>m.status==="divergent").map(m=>m.text),duplicateWordings:h.slice(0,50)}}}function qn(e){let t=e.features.reduce((s,o)=>s+o.scenarios.length,0),n=e.features.reduce((s,o)=>s+o.scenarios.filter(i=>i.cached).length,0);console.log(`saffron ${e.version} \xB7 ${e.features.length} feature file(s) \xB7 ${t} scenario(s), ${n} cached`);for(let s of e.features){let o=s.scenarios.map(i=>i.proposal?"\u25D0":i.cached?"\u25CF":"\u25CB").join("");console.log(` ${s.path} ${o}${s.error?` \u2717 ${s.error.split(`
|
|
280
|
+
`)[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 r=e.vocabulary;console.log(`vocabulary: ${r.steps} steps (${r.recorded} recorded, ${r.unrecorded} unrecorded), ${r.stepSets} step sets, ${r.divergent.length} divergent, ${r.duplicateWordings.length} duplicate wording group(s)`),console.log(`config: ${e.config.file??"(defaults, no saffron.config.json)"}`)}var Rs=/^(<[^>]+>|\{env:[^}]+\}|\{date[^}]*\})$/;function Bn(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 Ts(e){let t;try{t=q(e)}catch{return[]}let n=new Map;for(let r of t.steps.values()){if(r.actions.length===0)continue;let s=[...r.gherkin.matchAll(/"([^"]*)"/g)].map(f=>f[1]),o=f=>f!==void 0&&(s.includes(f)||Rs.test(f))?"\xABarg\xBB":f,i=r.actions.map(f=>{let{pageFingerprint:l,value:c,promptText:u,...S}=f;return{...S,value:o(c),promptText:o(u)}}),a=JSON.stringify(i),d=r.actions.map(f=>`${f.action}${Bn(f.target)?` ${Bn(f.target)}`:f.url?` ${f.url}`:""}`).join(" \xB7 "),p=n.get(a)??{steps:new Set,actions:d};p.steps.add(r.gherkin),n.set(a,p)}return[...n.values()].filter(r=>r.steps.size>1).map(r=>({steps:[...r.steps].sort(),actions:r.actions})).sort((r,s)=>s.steps.length-r.steps.length||r.steps[0].localeCompare(s.steps[0]))}import T from"node:fs";import F from"node:path";var $e={claude:".claude/skills",agents:".agents/skills",copilot:".github/skills",cursor:".cursor/skills"},As=["claude","agents"],Gn="<!-- saffron:start -->",mt="<!-- saffron:end -->";function Es(){return[Gn,"## 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.","- Never edit `.saffron/cache/` or `.saffron/proposals/` by hand; change the"," scenario text and re-run. Review proposals with `npx saffron accept`.","- Secrets go in `{env:VAR}` tokens, never in files.",mt,""].join(`
|
|
281
|
+
`)}function Hn(e,t){if(!T.existsSync(e))return T.writeFileSync(e,t),"created";let n=T.readFileSync(e,"utf8"),r=n.indexOf(Gn),s=n.indexOf(mt);if(r!==-1&&s!==-1&&s>r){let i=n.slice(0,r)+t.trimEnd()+n.slice(s+mt.length);return i===n?"unchanged":(T.writeFileSync(e,i),"updated")}let o=n.endsWith(`
|
|
280
282
|
`)?`
|
|
281
283
|
`:`
|
|
282
284
|
|
|
283
|
-
`;return
|
|
284
|
-
`),
|
|
285
|
-
`),n.scaffolded.push("saffron.config.json"));let
|
|
286
|
-
`).some(
|
|
285
|
+
`;return T.writeFileSync(e,n+o+t),"updated"}var gt={command:"npx",args:["saffron","mcp"]},Ps={claude:{file:".mcp.json",key:"mcpServers",entry:gt},cursor:{file:".cursor/mcp.json",key:"mcpServers",entry:gt},copilot:{file:".vscode/mcp.json",key:"servers",entry:{type:"stdio",...gt}}},Wn={agents:"codex mcp add saffron -- npx saffron mcp (Codex; other hosts: see their MCP settings)"};function Cs(e,t){let n=F.join(e,t.file),r={},s=T.existsSync(n);if(s)try{r=JSON.parse(T.readFileSync(n,"utf8"))}catch{throw new Error(`${t.file} is not valid JSON: fix it or remove it, then re-run`)}let o=r[t.key]??{};return JSON.stringify(o.saffron)===JSON.stringify(t.entry)?"unchanged":(o.saffron=t.entry,r[t.key]=o,T.mkdirSync(F.dirname(n),{recursive:!0}),T.writeFileSync(n,JSON.stringify(r,null,2)+`
|
|
286
|
+
`),s?"updated":"created")}function Yn(e,t){T.mkdirSync(t,{recursive:!0});for(let n of T.readdirSync(e,{withFileTypes:!0})){let r=F.join(e,n.name),s=F.join(t,n.name);n.isDirectory()?Yn(r,s):T.copyFileSync(r,s)}}function Jn(e){let t=F.join(e.packageRoot,"skills","saffron");if(!T.existsSync(F.join(t,"SKILL.md")))throw new Error(`bundled skill not found at ${t}`);let n={skillDirs:[],instructionFiles:[],scaffolded:[],mcpFiles:[],mcpHints:[]},r=e.targets??As;for(let s of r){let o=F.join(e.projectRoot,$e[s],"saffron");T.existsSync(o)&&T.rmSync(o,{recursive:!0,force:!0}),Yn(t,o),n.skillDirs.push(F.relative(e.projectRoot,o))}if(e.mcp!==!1)for(let s of r){let o=Ps[s];o?n.mcpFiles.push({file:o.file,outcome:Cs(e.projectRoot,o)}):Wn[s]&&n.mcpHints.push(Wn[s])}if(e.instructions!==!1){let s=Es(),o=F.join(e.projectRoot,"AGENTS.md");n.instructionFiles.push({file:"AGENTS.md",outcome:Hn(o,s)});let i=F.join(e.projectRoot,"CLAUDE.md");T.existsSync(i)&&n.instructionFiles.push({file:"CLAUDE.md",outcome:Hn(i,s)})}if(e.examples){n.examples=Fs(e.projectRoot,e.packageRoot);for(let s of n.examples.files)n.scaffolded.push(s)}if(e.scaffold!==!1){let s=F.join(e.projectRoot,"saffron.config.json");T.existsSync(s)||(T.writeFileSync(s,JSON.stringify({baseURL:"http://localhost:3000",features:"features"},null,2)+`
|
|
287
|
+
`),n.scaffolded.push("saffron.config.json"));let o=F.join(e.projectRoot,"features");T.existsSync(o)||(T.mkdirSync(o,{recursive:!0}),n.scaffolded.push("features/"));let i=F.join(e.projectRoot,".gitignore"),a=e.examples?[".saffron/reports/",".env"]:[".saffron/reports/"],d=T.existsSync(i)?T.readFileSync(i,"utf8"):"",p=[];for(let f of a)d.split(`
|
|
288
|
+
`).some(l=>l.trim()===f)||(d+=(d&&!d.endsWith(`
|
|
287
289
|
`)?`
|
|
288
|
-
`:"")+
|
|
289
|
-
`,p.push(
|
|
290
|
-
`)}function
|
|
291
|
-
`))}async function
|
|
292
|
-
`)[0]}`),x.error&&console.log(` ${x.error}`)};await d.start();try{if(
|
|
293
|
-
${
|
|
294
|
-
${
|
|
290
|
+
`:"")+f+`
|
|
291
|
+
`,p.push(f));p.length>0&&(T.writeFileSync(i,d),n.scaffolded.push(`.gitignore (+ ${p.join(", ")})`))}return n}function Fs(e,t){let n=F.join(t,"templates","saucedemo");if(!T.existsSync(F.join(n,"features")))return{installed:!1,files:[],reason:`bundled examples not found at ${n}`};let r=F.join(e,"features");if(T.existsSync(r)&&T.readdirSync(r).length>0)return{installed:!1,files:[],reason:"features/ is not empty; examples are only installed into an empty features directory"};let s=[];T.mkdirSync(r,{recursive:!0});for(let a of T.readdirSync(F.join(n,"features")))T.copyFileSync(F.join(n,"features",a),F.join(r,a)),s.push(`features/${a}`);let o=F.join(e,"saffron.config.json");T.existsSync(o)||(T.copyFileSync(F.join(n,"saffron.config.json"),o),s.push("saffron.config.json (baseURL https://www.saucedemo.com, retries 1)"));let i=F.join(e,".env.example");return T.existsSync(i)||(T.copyFileSync(F.join(n,".env.example"),i),s.push(".env.example")),{installed:!0,files:s}}import Is from"node:path";function Kn(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):"," 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?Is.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(`
|
|
292
|
+
`)}function Ds(e,t){let n=t.length>0?t:["features"],r=[];for(let s of n){let o=A.isAbsolute(s)?s:A.join(e,s);if(D.existsSync(o))if(D.statSync(o).isDirectory())for(let i of D.readdirSync(o,{recursive:!0})){let a=String(i);re(a)&&r.push(A.join(o,a))}else re(o)&&r.push(o)}return r.sort()}function Qn(e,t,n){let r=A.isAbsolute(t.features??"features")?t.features:A.join(e,t.features??"features"),s=new Set(ce(r));for(let o of n)o.endsWith(".saffron")&&s.add(o);return X([...s].sort(),e)}function Ms(){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&&(D.existsSync(A.join(t,".claude",".credentials.json"))||D.existsSync(A.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(`
|
|
293
|
+
`))}async function Ns(e){let t=_s.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 Ve(e){console.error(`saffron: ${e.message}`),process.exit(2)}function ht(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e4?`${(e/1e3).toFixed(1)}k`:e.toLocaleString()}var Us={green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m"},Ls="\x1B[0m",_=new Os().name("saffron").description("Gherkin-native AI-fallback test runner: zero-token cached replay, runtime AI healing.").version(me()).option("-p, --project-root <dir>","project root",process.cwd());_.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',jn).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=A.resolve(_.opts().projectRoot),r=ee(n),s=t.baseUrl??r.baseURL,o=Ds(n,e.length>0?e:r.features?[r.features]:[]);o.length===0&&(console.error("No .feature/.saffron files found."),process.exit(2)),t.agent!==!1&&Ms();let i;try{let x=Qn(n,r,o);i=o.flatMap(R=>Z(R,n,x))}catch(x){throw x instanceof N&&Ve(x),x}let a=Fn(t.filter);if(a.length>0&&(i=In(i,a),i.length===0&&(console.error(`No scenarios match --filter ${a.join(",")} in ${o.length} feature file(s).`),process.exit(2))),t.rerecord){t.agent===!1&&(console.error("saffron: --rerecord needs the agent; drop --no-agent"),process.exit(2));let x=0;for(let R of i){let E=B(n,R.featurePath,R.name);D.existsSync(E)&&(D.rmSync(E),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=new Map;for(let R of i){let E=Je(R),I=z(B(n,R.featurePath,R.name));I&&E.push(JSON.stringify(I.steps));for(let O of Ye(E))process.env[O]===void 0&&!x.has(O)&&x.set(O,R.displayName)}if(x.size>0){for(let[R,E]of x)console.error(`missing environment variable ${R} (referenced as {env:${R}} by "${E}")`);console.error("set the variable(s), or add them to a git-ignored .env in the project root"),process.exit(2)}}let d=new Fe({projectRoot:n,baseURL:s,headed:t.headed,actionTimeoutMs:r.actionTimeoutMs,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 Ie({model:t.model??r.model,maxTurns:r.maxTurns,snapshotMode:r.snapshotMode}):void 0}),p=new Date,f=Math.max(1,Number.parseInt(String(t.workers??r.workers??1),10)||1),l=new Array(i.length),c=x=>{let R=x.scenario,E=Us[x.status],I=x.usage.inputTokens+x.usage.outputTokens,O=x.usage.cacheReadTokens+x.usage.cacheCreationTokens,P=O>0?`, ${ht(O)} cache traffic`:"";console.log(`${E}${x.status.toUpperCase().padEnd(7)}${Ls}${R.displayName} (${x.source}, ${x.durationMs}ms, ${x.usage.aiCalls} AI calls, ${I} tokens${P})`);for(let V of x.adaptations)console.log(` \u26A0 ${V}`);x.seededSteps&&console.log(` \u26A1 ${x.seededSteps}/${x.stepResults.length} steps seeded from existing recordings (zero AI)`);let Q=x.stepResults.reduce((V,Zn)=>V+(Zn.retries??0),0);Q&&console.log(` \u21BB ${Q} action ${Q===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(`
|
|
294
|
+
`)[0]}`),x.error&&console.log(` ${x.error}`)};await d.start();try{if(f>1&&i.length>1){let x=i.map((E,I)=>({s:E,i:I})),R=[];await Promise.all(Array.from({length:Math.min(f,x.length)},async()=>{for(;;){let E=x.shift();if(!E)return;let I=await d.runScenario(E.s,{agentDisabled:!0});I.status==="red"?R.push(E):(l[E.i]=I,c(I))}}));for(let E of R.sort((I,O)=>I.i-O.i)){let I=await d.runScenario(E.s);l[E.i]=I,c(I)}}else for(let x=0;x<i.length;x++){let R=await d.runScenario(i[x]);l[x]=R,c(R)}}finally{await d.stop()}let u=Pn(l,p,s),S=q(n).divergent.length,g=Nn(l,p,S,s),h=Le(n);u.trends=Ln(h,g),Un(n,g),u.totals.aiCalls>0&&(u.totals.plan=await d.agent?.planUsage?.());let{html:w,json:y}=Cn(n,u),m=u.totals,k=m.cacheReadTokens+m.cacheCreationTokens;console.log(`
|
|
295
|
+
${m.green} passed, ${m.yellow} pending review, ${m.red} failed \xB7 ${m.aiCalls} AI calls \xB7 ${(m.inputTokens+m.outputTokens).toLocaleString()} tokens in+out${k>0?` \xB7 ${ht(m.cacheReadTokens)} cache read \xB7 ${ht(m.cacheCreationTokens)} cache written`:""}${yn(m)}${m.models?.length?` \xB7 ${m.models.join(", ")}`:""}`);let v=u.trends;if(v?.prev){let x=v.prev.passRatePp,R=v.prev.costUsd;console.log(`vs previous run: pass rate ${x>=0?"+":""}${x}pp \xB7 cost ${R>=0?"+":"-"}$${Math.abs(R).toFixed(4)} \xB7 AI calls ${v.prev.aiCalls>=0?"+":""}${v.prev.aiCalls}`)}for(let x of v?.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: ${w}
|
|
296
|
+
${y}`);let b=se(A.resolve(_.opts().projectRoot));b.length>0&&console.log(`${b.length} cache proposal(s) pending. Review with: saffron accept | saffron reject`);let C=t.strict??r.strict??!1;C&&m.yellow>0&&console.log(`strict mode: ${m.yellow} scenario(s) pending review treated as failure. Review proposals to go green.`),process.exit(m.red>0||C&&m.yellow>0?1:0)});_.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=A.resolve(_.opts().projectRoot),r=ee(n),s=e.length>0?e.map(o=>A.resolve(o)):t.all?se(n).map(o=>o.file):[];if(s.length===0){Xn(n);return}for(let o of s){let i=ue(o);if(i.meta.verified===!1){if(t.all&&!t.includeUnverified){console.log(`skipped UNVERIFIED ${A.basename(o)} (${i.meta.proofError?.split(`
|
|
295
297
|
`)[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(`
|
|
296
|
-
`)[0]}): expect a heal or red on the next run.`)}let a=
|
|
297
|
-
${
|
|
298
|
-
`).map(p=>p.trim().replace(/^(Given|When|Then|And|But|\*)\s+/,"")).filter(p=>
|
|
299
|
-
`))});
|
|
300
|
-
`);for(let{file:n,proposal:r}of
|
|
298
|
+
`)[0]}): expect a heal or red on the next run.`)}let a=z(B(n,i.cache.feature,i.cache.scenario)),d=zt(n,o);console.log(`accepted \u2192 ${d}`);let p=a?wn(a,i.cache):[];if(p.length>0){let c=kn(n,p,d,!t.propagate);for(let u of p)console.log(` locator fix: ${it(u.from)} \u2192 ${it(u.to)}`);if(c.length===0)console.log(" no other caches use this locator.");else if(t.propagate)for(let u of c)console.log(` propagated \u2192 ${u.feature} \u203A ${u.scenario} (${u.steps.map(S=>`"${S.gherkin}"`).join(", ")})`);else{console.log(` ${c.length} other cache(s) use the same locator: re-run with --propagate to fix them too:`);for(let u of c)console.log(` \xB7 ${u.feature} \u203A ${u.scenario}`)}}let f=i.meta.featureEdits??[];if(!t.withFeatureEdit||f.length===0)continue;let l;try{l=Rn(n,i.cache.feature,i.cache.scenario,f,Qn(n,r,[]))}catch(c){throw c instanceof N&&Ve(c),c}for(let c of l.applied){let u=c.fromStepSet?`${c.file}:${c.line} (StepSet "${c.fromStepSet}", fixes every invoking scenario)`:`${c.file}:${c.line}`;console.log(` feature edit ${u}:`),console.log(` - ${c.from}`),console.log(` + ${c.to}`)}for(let c of l.skipped)console.log(` skipped edit [${c.index}]: ${c.reason}`);if(l.applied.length>0){let c=z(d);for(let u of f)c.steps[u.index]&&(c.steps[u.index].gherkin=u.text);le(d,c)}}});_.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=A.resolve(_.opts().projectRoot),r=ee(n),s;try{s=H(n,r.features??"features")}catch(i){throw i instanceof N&&Ve(i),i}if(e&&(s=Ae(s,e)),t.json){console.log(JSON.stringify(s,null,2));return}if(t.snippets){let i=A.join(n,".vscode","saffron.code-snippets");D.mkdirSync(A.dirname(i),{recursive:!0}),D.writeFileSync(i,Pt(s)),console.log(`wrote ${s.steps.length} step + ${s.stepSets.length} StepSet snippet(s) \u2192 ${i}`),console.log("re-run after recording sessions to keep completions current");return}let o={recorded:"\x1B[32m\u25CF\x1B[0m",divergent:"\x1B[33m\u25CF\x1B[0m",unrecorded:"\u25CB"};if(s.stepSets.length>0){console.log("step sets:");for(let i of s.stepSets)console.log(` ${i.name} (${i.steps.length} steps, ${i.usage} scenario(s)), ${i.file}:${i.line}`);console.log("")}for(let i of s.steps){let a=i.fromStepSet?` [${i.fromStepSet}]`:"";console.log(`${o[i.status]} ${i.keyword} ${i.text} \xD7${i.usage}${a}`)}console.log(`
|
|
299
|
+
${s.steps.length} step(s) across ${s.scannedFiles} file(s) \xB7 ${s.scannedCaches} cache(s) \xB7 \x1B[32m\u25CF\x1B[0m recorded (replays free) \xB7 \x1B[33m\u25CF\x1B[0m divergent \xB7 \u25CB unrecorded`)});_.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=A.resolve(_.opts().projectRoot),r=ee(n),s=D.readFileSync(A.resolve(e),"utf8"),o;try{o=H(n,r.features??"features")}catch(p){throw p instanceof N&&Ve(p),p}console.log(`authoring with ${o.steps.length} known step(s) and ${o.stepSets.length} step set(s) as vocabulary\u2026`);let i=await Ft(s,o,t.model??r.model),a=t.out?A.resolve(t.out):A.join(n,r.features??"features",`${A.basename(e).replace(/\.[^.]+$/,"")}.saffron`);D.existsSync(a)&&(console.error(`refusing to overwrite ${a}: pass --out for a new path`),process.exit(1)),D.mkdirSync(A.dirname(a),{recursive:!0}),D.writeFileSync(a,i.content);let d=i.content.split(`
|
|
300
|
+
`).map(p=>p.trim().replace(/^(Given|When|Then|And|But|\*)\s+/,"")).filter(p=>o.steps.some(f=>f.text===p)).length;console.log(`wrote ${a}`),console.log(`${d} 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 "+A.relative(process.cwd(),a))});_.command("mcp").description("Serve the step vocabulary to AI assistants over stdio MCP (search_steps, list_step_sets)").action(async()=>{let e=A.resolve(_.opts().projectRoot),t=ee(e);await Ct(e,t.features??"features")});_.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(Kn(Me())),process.exit(2));let e=A.resolve(_.opts().projectRoot),t=ee(e);Nt(e,t.features??"features")});_.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=A.resolve(_.opts().projectRoot),r=e.length>0?e.map(s=>A.resolve(s)):t.all?se(n).map(s=>s.file):[];if(r.length===0){Xn(n);return}for(let s of r)qt(s),console.log(`rejected ${s}`)});_.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($e).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=A.resolve(_.opts().projectRoot),n=Me();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 $e||(console.error(`saffron: unknown agent target "${i}" (expected one of ${Object.keys($e).join(", ")})`),process.exit(2));let s=e.examples===!0;e.examples===void 0&&process.stdin.isTTY&&process.stdout.isTTY&&(s=await Ns("Install the Saucedemo example tests (login, cart, checkout) into features/ for a guided first run? [y/N] "));let o=Jn({projectRoot:t,packageRoot:n,targets:r,instructions:e.instructions,scaffold:e.scaffold,mcp:e.mcp,examples:s});for(let i of o.skillDirs)console.log(`skill \u2192 ${i}/`);for(let i of o.mcpFiles)console.log(`${i.outcome.padEnd(9)} \u2192 ${i.file} (saffron mcp server)`);for(let i of o.mcpHints)console.log(`mcp hint \u2192 ${i}`);for(let i of o.instructionFiles)console.log(`${i.outcome.padEnd(9)} \u2192 ${i.file} (managed Saffron block)`);for(let i of o.scaffolded)console.log(`created \u2192 ${i}`);o.examples&&!o.examples.installed&&console.log(`examples \u2192 not installed: ${o.examples.reason}`),console.log("\nAgents now load the saffron skill when writing tests. Re-run after `npm update saffron-ai` to refresh it."),o.examples?.installed&&console.log(["","Your guided first run (recording needs Claude credentials; replays never do):"," cp .env.example .env # public demo credentials, resolved at replay"," npx playwright install chromium"," npx saffron run --filter @smoke # the agent records two scenarios (about $3 of AI usage), files proposals"," npx saffron accept --all # review, then promote them to caches"," npx saffron run --filter @smoke # replays at zero tokens","Then try the rest: npx saffron run (login errors outline, checkout with a data table)"].join(`
|
|
301
|
+
`))});_.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=A.resolve(_.opts().projectRoot),n=ee(t),r=zn(t,n);if(e.json){console.log(JSON.stringify(r,null,2));return}qn(r)});_.command("report").description("Open the latest HTML report").option("--open","open in the default browser",!0).action(()=>{let e=A.resolve(_.opts().projectRoot),t=A.join(e,".saffron","reports","latest.html");D.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";js(n,[t],{detached:!0,stdio:"ignore"}).unref()});function Xn(e){let t=se(e);if(t.length===0){console.log("No pending proposals.");return}console.log(`Pending proposals:
|
|
302
|
+
`);for(let{file:n,proposal:r}of t){console.log(` ${n}`);let s=r.meta.verified===!0?" \xB7 verified \u2713":r.meta.verified===!1?" \xB7 UNVERIFIED \u2717":"";console.log(` ${r.cache.feature} \u203A ${r.cache.scenario} (${r.meta.mode}, ${r.meta.createdAt}${s})`),console.log(` ${r.meta.narrative}`);for(let o of r.meta.adaptations)console.log(` \u26A0 ${o}`);r.meta.suggestedFeatureEdit&&console.log(` suggested .feature edit:
|
|
301
303
|
${r.meta.suggestedFeatureEdit.split(`
|
|
302
|
-
`).map(
|
|
303
|
-
`)}`),console.log()}console.log("Accept with: saffron accept <file> | --all")}
|
|
304
|
+
`).map(o=>` ${o}`).join(`
|
|
305
|
+
`)}`),console.log()}console.log("Accept with: saffron accept <file> | --all")}_.parseAsync();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "saffron-ai",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.5",
|
|
4
4
|
"description": "Gherkin-native AI-fallback test runner: zero-token cached replay, runtime AI healing, honest reports",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"test": "vitest run",
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"license": "SEE LICENSE IN LICENSE",
|
|
25
25
|
"type": "module",
|
|
26
26
|
"bin": {
|
|
27
|
-
"saffron": "
|
|
27
|
+
"saffron": "dist-pkg/cli.js"
|
|
28
28
|
},
|
|
29
29
|
"devDependencies": {
|
|
30
30
|
"@types/node": "^26.1.0",
|