ripplo 0.4.10 → 0.4.11

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.
Files changed (2) hide show
  1. package/dist/index.js +179 -179
  2. package/package.json +5 -5
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import{execFileSync as Ca}from"child_process";import Ea from"fs";import pt from"path";function tr(e){let t=$a(e);return t??Cn(e)}function Cn(e){let t=pt.dirname(e);return Ta(pt.join(e,".ripplo"))?e:t===e?null:Cn(t)}function Ta(e){try{return Ea.statSync(e).isDirectory()}catch{return!1}}function $a(e){let t=Aa(["rev-parse","--show-toplevel"],e);if(t==null)return null;let r=t.trim();return r.length===0?null:pt.isAbsolute(r)?r:pt.resolve(e,r)}function Aa(e,t){try{return Ca("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return null}}import $n from"fs";import gt from"path";import{config as Na}from"dotenv";import{z as ft}from"zod";import Ke from"fs";import nr from"path";import{z as mt}from"zod";var En=nr.join(".ripplo","project.json"),rr=[".env",".env.local"],Ia=mt.object({envFiles:mt.array(mt.string().min(1)).optional(),projectId:mt.string().min(1)});function or(e){return nr.join(e,En)}function ir(e){let t=or(e);if(!Ke.existsSync(t))throw new Error(`ripplo: missing ${En}. Run \`ripplo init\` to create it.`);let r=JSON.parse(Ke.readFileSync(t,"utf8")),n=Ia.parse(r);return{envFiles:n.envFiles??rr,projectId:n.projectId}}function sr(e){let t=or(e);if(Ke.existsSync(t))try{return ir(e)}catch{return}}function Tn({cwd:e,envFiles:t,projectId:r}){let n=or(e);Ke.mkdirSync(nr.dirname(n),{recursive:!0});let o={projectId:r};t!=null&&!ja(t)&&(o.envFiles=[...t]),Ke.writeFileSync(n,JSON.stringify(o,null,2)+`
3
- `)}function ja(e){return e.length!==rr.length?!1:e.every((t,r)=>t===rr[r])}function An(e){let r=sr(e)?.envFiles??[".env",".env.local"],n=gt.join(e,".ripplo");r.forEach(o=>{let i=gt.resolve(n,o);$n.existsSync(i)&&Na({override:!0,path:i,quiet:!0})}),ar=void 0}var Oa=ft.object({RIPPLO_APP_URL:ft.url(),RIPPLO_ENGINE_URL:ft.url(),RIPPLO_WEBHOOK_SECRET:ft.string().min(1)}),ar;function Ie(){return ar??=Da(),ar}function Da(){let e=Oa.safeParse(process.env);if(!e.success){let r=e.error.issues.map(s=>` ${s.path.join(".")}: ${s.message}`).join(`
4
- `),n=lr(process.cwd()),o=n.map(s=>` ${s}`).join(`
2
+ var Nn=Object.defineProperty;var _a=Object.getOwnPropertyDescriptor;var La=Object.getOwnPropertyNames;var Ua=Object.prototype.hasOwnProperty;var Va=(e,t)=>{for(var r in t)Nn(e,r,{get:t[r],enumerable:!0})},jn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of La(t))!Ua.call(e,o)&&o!==r&&Nn(e,o,{get:()=>t[o],enumerable:!(n=_a(t,o))||n.enumerable});return e},sr=(e,t,r)=>(jn(e,t,"default"),r&&jn(r,t,"default"));import{execFileSync as Fa}from"child_process";import Ma from"fs";import yt from"path";function ar(e){let t=Ha(e);return t??On(e)}function On(e){let t=yt.dirname(e);return Ba(yt.join(e,".ripplo"))?e:t===e?null:On(t)}function Ba(e){try{return Ma.statSync(e).isDirectory()}catch{return!1}}function Ha(e){let t=qa(["rev-parse","--show-toplevel"],e);if(t==null)return null;let r=t.trim();return r.length===0?null:yt.isAbsolute(r)?r:yt.resolve(e,r)}function qa(e,t){try{return Fa("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return null}}import Ln from"fs";import bt from"path";import{config as Ga}from"dotenv";import{z as wt}from"zod";import Xe from"fs";import cr from"path";import{z as ht}from"zod";var Dn=cr.join(".ripplo","project.json"),lr=[".env",".env.local"],Wa=ht.object({envFiles:ht.array(ht.string().min(1)).optional(),projectId:ht.string().min(1)});function dr(e){return cr.join(e,Dn)}function ur(e){let t=dr(e);if(!Xe.existsSync(t))throw new Error(`ripplo: missing ${Dn}. Run \`ripplo init\` to create it.`);let r=JSON.parse(Xe.readFileSync(t,"utf8")),n=Wa.parse(r);return{envFiles:n.envFiles??lr,projectId:n.projectId}}function pr(e){let t=dr(e);if(Xe.existsSync(t))try{return ur(e)}catch{return}}function _n({cwd:e,envFiles:t,projectId:r}){let n=dr(e);Xe.mkdirSync(cr.dirname(n),{recursive:!0});let o={projectId:r};t!=null&&!za(t)&&(o.envFiles=[...t]),Xe.writeFileSync(n,JSON.stringify(o,null,2)+`
3
+ `)}function za(e){return e.length!==lr.length?!1:e.every((t,r)=>t===lr[r])}function Un(e){let r=pr(e)?.envFiles??[".env",".env.local"],n=bt.join(e,".ripplo");r.forEach(o=>{let i=bt.resolve(n,o);Ln.existsSync(i)&&Ga({override:!0,path:i,quiet:!0})}),mr=void 0}var Ja=wt.object({RIPPLO_APP_URL:wt.url(),RIPPLO_ENGINE_URL:wt.url(),RIPPLO_WEBHOOK_SECRET:wt.string().min(1)}),mr;function je(){return mr??=Ka(),mr}function Ka(){let e=Ja.safeParse(process.env);if(!e.success){let r=e.error.issues.map(s=>` ${s.path.join(".")}: ${s.message}`).join(`
4
+ `),n=fr(process.cwd()),o=n.map(s=>` ${s}`).join(`
5
5
  `),i=n.length>0?`
6
6
 
7
7
  Declared env file(s) not found at this path:
@@ -9,48 +9,48 @@ ${o}
9
9
  If you're in a git worktree, the env file may not have been copied from the main checkout \u2014 recreate it (or symlink to a shared file outside the working tree).`:"";throw new Error(`ripplo: env config invalid:
10
10
  ${r}
11
11
 
12
- Add missing values to the env file(s) declared in .ripplo/project.json.${i}`)}let t=e.data;return{appUrl:t.RIPPLO_APP_URL,engineUrl:t.RIPPLO_ENGINE_URL,webhookSecret:t.RIPPLO_WEBHOOK_SECRET}}function lr(e){let r=sr(e)?.envFiles??[],n=gt.join(e,".ripplo");return r.map(o=>gt.resolve(n,o)).filter(o=>!$n.existsSync(o))}import pw from"yargs";import{hideBin as mw}from"yargs/helpers";import{graphql as rp}from"gql.tada";async function yt(e,t,r){let n;try{return n=await e.context().newCDPSession(e),await r(n)}catch{return t}finally{await n?.detach().catch(()=>{})}}async function M({awaitPromise:e,expression:t,page:r}){return yt(r,void 0,async n=>{let o=await n.send("Runtime.evaluate",{awaitPromise:e,expression:t,returnByValue:!0});if(o.exceptionDetails==null)return o.result.value})}var La=Object.prototype.toString,Ne=Array.isArray||function(t){return La.call(t)==="[object Array]"};function dr(e){return typeof e=="function"}function _a(e){return Ne(e)?"array":typeof e}function cr(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function In(e,t){return e!=null&&typeof e=="object"&&t in e}function Ua(e,t){return e!=null&&typeof e!="object"&&e.hasOwnProperty&&e.hasOwnProperty(t)}var Va=RegExp.prototype.test;function Fa(e,t){return Va.call(e,t)}var Ma=/\S/;function Ha(e){return!Fa(Ma,e)}var qa={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function Ba(e){return String(e).replace(/[&<>"'`=\/]/g,function(r){return qa[r]})}var Wa=/\s*/,za=/\s+/,jn=/\s*=/,Ga=/\s*\}/,Ja=/#|\^|\/|>|\{|&|=|!/;function Ka(e,t){if(!e)return[];var r=!1,n=[],o=[],i=[],s=!1,a=!1,l="",c=0;function d(){if(s&&!a)for(;i.length;)delete o[i.pop()];else i=[];s=!1,a=!1}var u,f,w;function v(U){if(typeof U=="string"&&(U=U.split(za,2)),!Ne(U)||U.length!==2)throw new Error("Invalid tags: "+U);u=new RegExp(cr(U[0])+"\\s*"),f=new RegExp("\\s*"+cr(U[1])),w=new RegExp("\\s*"+cr("}"+U[1]))}v(t||re.tags);for(var g=new Xe(e),E,P,L,z,_,F;!g.eos();){if(E=g.pos,L=g.scanUntil(u),L)for(var ie=0,Ae=L.length;ie<Ae;++ie)z=L.charAt(ie),Ha(z)?(i.push(o.length),l+=z):(a=!0,r=!0,l+=" "),o.push(["text",z,E,E+1]),E+=1,z===`
13
- `&&(d(),l="",c=0,r=!1);if(!g.scan(u))break;if(s=!0,P=g.scan(Ja)||"name",g.scan(Wa),P==="="?(L=g.scanUntil(jn),g.scan(jn),g.scanUntil(f)):P==="{"?(L=g.scanUntil(w),g.scan(Ga),g.scanUntil(f),P="&"):L=g.scanUntil(f),!g.scan(f))throw new Error("Unclosed tag at "+g.pos);if(P==">"?_=[P,L,E,g.pos,l,c,r]:_=[P,L,E,g.pos],c++,o.push(_),P==="#"||P==="^")n.push(_);else if(P==="/"){if(F=n.pop(),!F)throw new Error('Unopened section "'+L+'" at '+E);if(F[1]!==L)throw new Error('Unclosed section "'+F[1]+'" at '+E)}else P==="name"||P==="{"||P==="&"?a=!0:P==="="&&v(L)}if(d(),F=n.pop(),F)throw new Error('Unclosed section "'+F[1]+'" at '+g.pos);return Xa(Ya(o))}function Ya(e){for(var t=[],r,n,o=0,i=e.length;o<i;++o)r=e[o],r&&(r[0]==="text"&&n&&n[0]==="text"?(n[1]+=r[1],n[3]=r[3]):(t.push(r),n=r));return t}function Xa(e){for(var t=[],r=t,n=[],o,i,s=0,a=e.length;s<a;++s)switch(o=e[s],o[0]){case"#":case"^":r.push(o),n.push(o),r=o[4]=[];break;case"/":i=n.pop(),i[5]=o[2],r=n.length>0?n[n.length-1][4]:t;break;default:r.push(o)}return t}function Xe(e){this.string=e,this.tail=e,this.pos=0}Xe.prototype.eos=function(){return this.tail===""};Xe.prototype.scan=function(t){var r=this.tail.match(t);if(!r||r.index!==0)return"";var n=r[0];return this.tail=this.tail.substring(n.length),this.pos+=n.length,n};Xe.prototype.scanUntil=function(t){var r=this.tail.search(t),n;switch(r){case-1:n=this.tail,this.tail="";break;case 0:n="";break;default:n=this.tail.substring(0,r),this.tail=this.tail.substring(r)}return this.pos+=n.length,n};function je(e,t){this.view=e,this.cache={".":this.view},this.parent=t}je.prototype.push=function(t){return new je(t,this)};je.prototype.lookup=function(t){var r=this.cache,n;if(r.hasOwnProperty(t))n=r[t];else{for(var o=this,i,s,a,l=!1;o;){if(t.indexOf(".")>0)for(i=o.view,s=t.split("."),a=0;i!=null&&a<s.length;)a===s.length-1&&(l=In(i,s[a])||Ua(i,s[a])),i=i[s[a++]];else i=o.view[t],l=In(o.view,t);if(l){n=i;break}o=o.parent}r[t]=n}return dr(n)&&(n=n.call(this.view)),n};function J(){this.templateCache={_cache:{},set:function(t,r){this._cache[t]=r},get:function(t){return this._cache[t]},clear:function(){this._cache={}}}}J.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};J.prototype.parse=function(t,r){var n=this.templateCache,o=t+":"+(r||re.tags).join(":"),i=typeof n<"u",s=i?n.get(o):void 0;return s==null&&(s=Ka(t,r),i&&n.set(o,s)),s};J.prototype.render=function(t,r,n,o){var i=this.getConfigTags(o),s=this.parse(t,i),a=r instanceof je?r:new je(r,void 0);return this.renderTokens(s,a,n,t,o)};J.prototype.renderTokens=function(t,r,n,o,i){for(var s="",a,l,c,d=0,u=t.length;d<u;++d)c=void 0,a=t[d],l=a[0],l==="#"?c=this.renderSection(a,r,n,o,i):l==="^"?c=this.renderInverted(a,r,n,o,i):l===">"?c=this.renderPartial(a,r,n,i):l==="&"?c=this.unescapedValue(a,r):l==="name"?c=this.escapedValue(a,r,i):l==="text"&&(c=this.rawValue(a)),c!==void 0&&(s+=c);return s};J.prototype.renderSection=function(t,r,n,o,i){var s=this,a="",l=r.lookup(t[1]);function c(f){return s.render(f,r,n,i)}if(l){if(Ne(l))for(var d=0,u=l.length;d<u;++d)a+=this.renderTokens(t[4],r.push(l[d]),n,o,i);else if(typeof l=="object"||typeof l=="string"||typeof l=="number")a+=this.renderTokens(t[4],r.push(l),n,o,i);else if(dr(l)){if(typeof o!="string")throw new Error("Cannot use higher-order sections without the original template");l=l.call(r.view,o.slice(t[3],t[5]),c),l!=null&&(a+=l)}else a+=this.renderTokens(t[4],r,n,o,i);return a}};J.prototype.renderInverted=function(t,r,n,o,i){var s=r.lookup(t[1]);if(!s||Ne(s)&&s.length===0)return this.renderTokens(t[4],r,n,o,i)};J.prototype.indentPartial=function(t,r,n){for(var o=r.replace(/[^ \t]/g,""),i=t.split(`
12
+ Add missing values to the env file(s) declared in .ripplo/project.json.${i}`)}let t=e.data;return{appUrl:t.RIPPLO_APP_URL,engineUrl:t.RIPPLO_ENGINE_URL,webhookSecret:t.RIPPLO_WEBHOOK_SECRET}}function fr(e){let r=pr(e)?.envFiles??[],n=bt.join(e,".ripplo");return r.map(o=>bt.resolve(n,o)).filter(o=>!Ln.existsSync(o))}import xw from"yargs";import{hideBin as Cw}from"yargs/helpers";import{graphql as gp}from"gql.tada";async function St(e,t,r){let n;try{return n=await e.context().newCDPSession(e),await r(n)}catch{return t}finally{await n?.detach().catch(()=>{})}}async function M({awaitPromise:e,expression:t,page:r}){return St(r,void 0,async n=>{let o=await n.send("Runtime.evaluate",{awaitPromise:e,expression:t,returnByValue:!0});if(o.exceptionDetails==null)return o.result.value})}var Ya=Object.prototype.toString,Oe=Array.isArray||function(t){return Ya.call(t)==="[object Array]"};function yr(e){return typeof e=="function"}function Xa(e){return Oe(e)?"array":typeof e}function gr(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Vn(e,t){return e!=null&&typeof e=="object"&&t in e}function Qa(e,t){return e!=null&&typeof e!="object"&&e.hasOwnProperty&&e.hasOwnProperty(t)}var Za=RegExp.prototype.test;function el(e,t){return Za.call(e,t)}var tl=/\S/;function rl(e){return!el(tl,e)}var nl={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function ol(e){return String(e).replace(/[&<>"'`=\/]/g,function(r){return nl[r]})}var il=/\s*/,sl=/\s+/,Fn=/\s*=/,al=/\s*\}/,ll=/#|\^|\/|>|\{|&|=|!/;function cl(e,t){if(!e)return[];var r=!1,n=[],o=[],i=[],s=!1,a=!1,l="",c=0;function d(){if(s&&!a)for(;i.length;)delete o[i.pop()];else i=[];s=!1,a=!1}var u,f,w;function v(U){if(typeof U=="string"&&(U=U.split(sl,2)),!Oe(U)||U.length!==2)throw new Error("Invalid tags: "+U);u=new RegExp(gr(U[0])+"\\s*"),f=new RegExp("\\s*"+gr(U[1])),w=new RegExp("\\s*"+gr("}"+U[1]))}v(t||ne.tags);for(var g=new Ze(e),E,P,_,z,L,F;!g.eos();){if(E=g.pos,_=g.scanUntil(u),_)for(var se=0,Ie=_.length;se<Ie;++se)z=_.charAt(se),rl(z)?(i.push(o.length),l+=z):(a=!0,r=!0,l+=" "),o.push(["text",z,E,E+1]),E+=1,z===`
13
+ `&&(d(),l="",c=0,r=!1);if(!g.scan(u))break;if(s=!0,P=g.scan(ll)||"name",g.scan(il),P==="="?(_=g.scanUntil(Fn),g.scan(Fn),g.scanUntil(f)):P==="{"?(_=g.scanUntil(w),g.scan(al),g.scanUntil(f),P="&"):_=g.scanUntil(f),!g.scan(f))throw new Error("Unclosed tag at "+g.pos);if(P==">"?L=[P,_,E,g.pos,l,c,r]:L=[P,_,E,g.pos],c++,o.push(L),P==="#"||P==="^")n.push(L);else if(P==="/"){if(F=n.pop(),!F)throw new Error('Unopened section "'+_+'" at '+E);if(F[1]!==_)throw new Error('Unclosed section "'+F[1]+'" at '+E)}else P==="name"||P==="{"||P==="&"?a=!0:P==="="&&v(_)}if(d(),F=n.pop(),F)throw new Error('Unclosed section "'+F[1]+'" at '+g.pos);return ul(dl(o))}function dl(e){for(var t=[],r,n,o=0,i=e.length;o<i;++o)r=e[o],r&&(r[0]==="text"&&n&&n[0]==="text"?(n[1]+=r[1],n[3]=r[3]):(t.push(r),n=r));return t}function ul(e){for(var t=[],r=t,n=[],o,i,s=0,a=e.length;s<a;++s)switch(o=e[s],o[0]){case"#":case"^":r.push(o),n.push(o),r=o[4]=[];break;case"/":i=n.pop(),i[5]=o[2],r=n.length>0?n[n.length-1][4]:t;break;default:r.push(o)}return t}function Ze(e){this.string=e,this.tail=e,this.pos=0}Ze.prototype.eos=function(){return this.tail===""};Ze.prototype.scan=function(t){var r=this.tail.match(t);if(!r||r.index!==0)return"";var n=r[0];return this.tail=this.tail.substring(n.length),this.pos+=n.length,n};Ze.prototype.scanUntil=function(t){var r=this.tail.search(t),n;switch(r){case-1:n=this.tail,this.tail="";break;case 0:n="";break;default:n=this.tail.substring(0,r),this.tail=this.tail.substring(r)}return this.pos+=n.length,n};function Ne(e,t){this.view=e,this.cache={".":this.view},this.parent=t}Ne.prototype.push=function(t){return new Ne(t,this)};Ne.prototype.lookup=function(t){var r=this.cache,n;if(r.hasOwnProperty(t))n=r[t];else{for(var o=this,i,s,a,l=!1;o;){if(t.indexOf(".")>0)for(i=o.view,s=t.split("."),a=0;i!=null&&a<s.length;)a===s.length-1&&(l=Vn(i,s[a])||Qa(i,s[a])),i=i[s[a++]];else i=o.view[t],l=Vn(o.view,t);if(l){n=i;break}o=o.parent}r[t]=n}return yr(n)&&(n=n.call(this.view)),n};function K(){this.templateCache={_cache:{},set:function(t,r){this._cache[t]=r},get:function(t){return this._cache[t]},clear:function(){this._cache={}}}}K.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};K.prototype.parse=function(t,r){var n=this.templateCache,o=t+":"+(r||ne.tags).join(":"),i=typeof n<"u",s=i?n.get(o):void 0;return s==null&&(s=cl(t,r),i&&n.set(o,s)),s};K.prototype.render=function(t,r,n,o){var i=this.getConfigTags(o),s=this.parse(t,i),a=r instanceof Ne?r:new Ne(r,void 0);return this.renderTokens(s,a,n,t,o)};K.prototype.renderTokens=function(t,r,n,o,i){for(var s="",a,l,c,d=0,u=t.length;d<u;++d)c=void 0,a=t[d],l=a[0],l==="#"?c=this.renderSection(a,r,n,o,i):l==="^"?c=this.renderInverted(a,r,n,o,i):l===">"?c=this.renderPartial(a,r,n,i):l==="&"?c=this.unescapedValue(a,r):l==="name"?c=this.escapedValue(a,r,i):l==="text"&&(c=this.rawValue(a)),c!==void 0&&(s+=c);return s};K.prototype.renderSection=function(t,r,n,o,i){var s=this,a="",l=r.lookup(t[1]);function c(f){return s.render(f,r,n,i)}if(l){if(Oe(l))for(var d=0,u=l.length;d<u;++d)a+=this.renderTokens(t[4],r.push(l[d]),n,o,i);else if(typeof l=="object"||typeof l=="string"||typeof l=="number")a+=this.renderTokens(t[4],r.push(l),n,o,i);else if(yr(l)){if(typeof o!="string")throw new Error("Cannot use higher-order sections without the original template");l=l.call(r.view,o.slice(t[3],t[5]),c),l!=null&&(a+=l)}else a+=this.renderTokens(t[4],r,n,o,i);return a}};K.prototype.renderInverted=function(t,r,n,o,i){var s=r.lookup(t[1]);if(!s||Oe(s)&&s.length===0)return this.renderTokens(t[4],r,n,o,i)};K.prototype.indentPartial=function(t,r,n){for(var o=r.replace(/[^ \t]/g,""),i=t.split(`
14
14
  `),s=0;s<i.length;s++)i[s].length&&(s>0||!n)&&(i[s]=o+i[s]);return i.join(`
15
- `)};J.prototype.renderPartial=function(t,r,n,o){if(n){var i=this.getConfigTags(o),s=dr(n)?n(t[1]):n[t[1]];if(s!=null){var a=t[6],l=t[5],c=t[4],d=s;l==0&&c&&(d=this.indentPartial(s,c,a));var u=this.parse(d,i);return this.renderTokens(u,r,n,d,o)}}};J.prototype.unescapedValue=function(t,r){var n=r.lookup(t[1]);if(n!=null)return n};J.prototype.escapedValue=function(t,r,n){var o=this.getConfigEscape(n)||re.escape,i=r.lookup(t[1]);if(i!=null)return typeof i=="number"&&o===re.escape?String(i):o(i)};J.prototype.rawValue=function(t){return t[1]};J.prototype.getConfigTags=function(t){return Ne(t)?t:t&&typeof t=="object"?t.tags:void 0};J.prototype.getConfigEscape=function(t){if(t&&typeof t=="object"&&!Ne(t))return t.escape};var re={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(e){Ye.templateCache=e},get templateCache(){return Ye.templateCache}},Ye=new J;re.clearCache=function(){return Ye.clearCache()};re.parse=function(t,r){return Ye.parse(t,r)};re.render=function(t,r,n,o){if(typeof t!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+_a(t)+'" was given as the first argument for mustache#render(template, view, partials)');return Ye.render(t,r,n,o)};re.escape=Ba;re.Scanner=Xe;re.Context=je;re.Writer=J;var Nn=re;function Qe({defs:e}){return e==null?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Za({def:r,name:t})]))}var Qa={boolean:!1,number:0,string:""};function Za({def:e,name:t}){if(e.type==="env"){let r=process.env[e.key];if(r==null)throw new Error(`Environment variable "${e.key}" not set for variable "${t}"`);return r}return e.default??Qa[e.type]??""}function ht({ref:e,variables:t}){if(e.type==="static")return e.value;let r=t[e.name];if(r==null||typeof r=="object")throw new Error(`Variable "${e.name}" is not defined`);return r}function K({ref:e,variables:t}){let r=String(ht({ref:e,variables:t}));return bt({raw:r,variables:t})}function wt({ref:e,variables:t}){let r=ht({ref:e,variables:t});return typeof r=="string"?bt({raw:r,variables:t}):r}function bt({raw:e,variables:t}){return Nn.render(e,t,{},{escape:r=>r})}function ur({ref:e,variables:t}){let r=ht({ref:e,variables:t});if(typeof r=="number")return r;let n=Number(r);if(Number.isNaN(n))throw new TypeError(`Cannot convert "${String(r)}" to number`);return n}function Oe({name:e,store:t,value:r}){return{...t,[e]:r}}function H({locator:e,page:t,variables:r}){switch(e.by){case"testId":return t.getByTestId(On(e.value,r));case"role":return t.getByRole(e.role,{exact:!0,name:e.name==null?void 0:On(e.name,r)})}}function On(e,t){return t==null?e:bt({raw:e,variables:t})}async function Dn({node:e,page:t,timeout:r}){await H({locator:e.source,page:t,variables:void 0}).dragTo(H({locator:e.target,page:t,variables:void 0}),{timeout:r})}async function Ln({node:e,page:t,timeout:r}){await H({locator:e.locator,page:t,variables:void 0}).click({button:"right",timeout:r})}function _n({node:e,page:t,variables:r}){return t.once("dialog",async n=>{e.action==="accept"?await n.accept(e.promptText??void 0):await n.dismiss()}),{variables:r}}async function Un({node:e,page:t,variables:r}){if(e.action==="write"){if(e.value==null)throw new Error("clipboard write requires a value");let o=K({ref:e.value,variables:r}),i=JSON.stringify(o);return await M({awaitPromise:!0,expression:`navigator.clipboard.writeText(${i})`,page:t}),{variables:r}}if(e.variable==null)throw new Error("clipboard read requires a variable name to store the result");let n=await M({awaitPromise:!0,expression:"navigator.clipboard.readText()",page:t})??"";return{variables:Oe({name:e.variable,store:r,value:n})}}async function Vn({node:e,page:t}){let r=t.context();e.state==="granted"?await r.grantPermissions([e.permission]):await r.clearPermissions()}async function pr({node:e,page:t,timeout:r,variables:n}){switch(e.type){case"click":case"check":case"uncheck":case"clear":case"dblclick":case"focus":case"hover":case"scrollIntoView":return tl({node:e,page:t,timeout:r,variables:n});case"rightClick":return await Ln({node:e,page:t,timeout:r}),{variables:n};case"goto":{let o=K({ref:e.url,variables:n});return await t.goto(o,{timeout:r,waitUntil:"domcontentloaded"}),await t.waitForLoadState("load",{timeout:r}),await t.waitForFunction("document.body != null && document.body.childElementCount > 0 && (document.body.textContent?.trim().length ?? 0) > 0",void 0,{timeout:r}),await M({awaitPromise:!0,expression:"new Promise((resolve) => { requestAnimationFrame(() => requestAnimationFrame(() => resolve(undefined))); })",page:t}),{variables:n}}case"fill":return nl({node:e,page:t,timeout:r,variables:n});case"select":return ol({node:e,page:t,timeout:r,variables:n});case"type":return il({node:e,page:t,timeout:r,variables:n});case"press":return await rl({node:e,page:t,timeout:r}),{variables:n};case"drag":return await Dn({node:e,page:t,timeout:r}),{variables:n};case"upload":return sl({node:e,page:t,timeout:r,variables:n});case"extractText":return al({node:e,page:t,timeout:r,variables:n});case"setVariable":{let o=wt({ref:e.value,variables:n});return{variables:Oe({name:e.variable,store:n,value:o})}}case"fail":throw new Error(e.message);case"setViewport":return await t.setViewportSize({height:e.height,width:e.width}),{variables:n};case"handleDialog":return _n({node:e,page:t,variables:n});case"clipboard":return Un({node:e,page:t,variables:n});case"setPermission":return await Vn({node:e,page:t}),{variables:n}}}var el={check:"check",clear:"clear",click:"click",dblclick:"dblclick",focus:"focus",hover:"hover",scrollIntoView:"scrollIntoViewIfNeeded",uncheck:"uncheck"};async function tl({node:e,page:t,timeout:r,variables:n}){return await H({locator:e.locator,page:t,variables:n})[el[e.type]]({timeout:r}),{variables:n}}async function rl({node:e,page:t,timeout:r}){e.locator==null?await t.keyboard.press(e.key):await H({locator:e.locator,page:t,variables:void 0}).press(e.key,{timeout:r})}async function nl({node:e,page:t,timeout:r,variables:n}){let o=K({ref:e.value,variables:n});return await H({locator:e.locator,page:t,variables:n}).fill(o,{timeout:r}),{variables:n}}async function ol({node:e,page:t,timeout:r,variables:n}){let o=K({ref:e.value,variables:n});return await H({locator:e.locator,page:t,variables:n}).selectOption(o,{timeout:r}),{variables:n}}async function il({node:e,page:t,timeout:r,variables:n}){let o=K({ref:e.value,variables:n});return await H({locator:e.locator,page:t,variables:n}).pressSequentially(o,{timeout:r}),{variables:n}}async function sl({node:e,page:t,timeout:r,variables:n}){return await H({locator:e.locator,page:t,variables:n}).setInputFiles(e.files,{timeout:r}),{variables:n}}async function al({node:e,page:t,timeout:r,variables:n}){let o=await H({locator:e.locator,page:t,variables:n}).textContent({timeout:r});if(o==null)throw new Error("extractText: element had no text content");return{variables:Oe({name:e.variable,store:n,value:o})}}import Xl from"@anthropic-ai/sdk";import{z as Fn}from"zod";import{z as ll}from"zod";function y({description:e,execute:t,name:r,schema:n}){let o=ll.toJSONSchema(n,{target:"draft-2020-12"});return{anthropicTool:{description:e,input_schema:{...o,type:"object"},name:r},name:r,async execute(i,s){let a=n.parse(s);return{...await Promise.resolve(t(i,a)),kind:"action"}}}}function S(e){let t=[...e.assertions],r={assertions:t,detail:e.detail,duration:Math.round(e.duration),nodeId:`agent-step-${String(e.stepIndex)}`,nodeType:e.nodeType,recordingEndMs:void 0,recordingStartMs:void 0,snapshotTimestamp:Math.round(performance.now()-e.runStartTime),status:e.status,stepIndex:e.stepIndex,title:e.title,url:e.page.url()},n=t.length>0?t.map(o=>`${o.status}: ${o.description} \u2014 ${o.detail??""}`).join(`
16
- `):`${e.status}: ${e.title}`;return{specNode:e.specNode,stepResult:r,toolOutput:n}}var cl=Fn.object({selector:Fn.string().describe("CSS selector for the checkbox or radio button")}),Mn=y({description:"Assert that a checkbox or radio button is checked",name:"assert_checked",schema:cl,execute:async(e,t)=>{let r=performance.now(),n=await e.page.locator(t.selector).isChecked().catch(()=>!1),o=n?"passed":"failed",i=[{description:`Element ${t.selector} is checked`,detail:n?void 0:"Element is not checked",status:o}];return S({assertions:i,detail:n?"Element is checked":"Element is not checked",duration:performance.now()-r,nodeType:"assertChecked",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:o,stepIndex:e.stepIndex,title:`Assert checked: ${t.selector}`})}});import{z as Hn}from"zod";var dl=Hn.object({selector:Hn.string().describe("CSS selector for the element to check focus on")}),qn=y({description:"Assert that an element has keyboard focus. Use for accessibility tab-order testing.",name:"assert_focused",schema:dl,execute:async(e,t)=>{let r=performance.now(),o=!!await e.page.locator(t.selector).evaluate("(el) => document.activeElement === el",void 0,{timeout:5e3}).catch(()=>!1),i=o?"passed":"failed",s=[{description:`Element ${t.selector} is focused`,detail:o?void 0:"Element does not have focus",status:i}];return S({assertions:s,detail:o?"Element is focused":"Element does not have focus",duration:performance.now()-r,nodeType:"assertFocused",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:i,stepIndex:e.stepIndex,title:`Assert focused: ${t.selector}`})}});import{z as mr}from"zod";var ul=mr.object({expected:mr.string().describe("The expected text content"),selector:mr.string().describe("CSS selector for the element to check")}),Bn=y({description:"Assert that an element's text content matches the expected value",name:"assert_text",schema:ul,execute:async(e,t)=>{let r=performance.now(),n=await e.page.locator(t.selector).textContent({timeout:5e3}).catch(()=>null),o=n!=null&&n.includes(t.expected),i=o?"passed":"failed",s=[{description:`Text contains "${t.expected}"`,detail:`Actual: "${n??"(not found)"}"`,status:i}];return S({assertions:s,detail:o?`Text matches: "${t.expected}"`:`Expected "${t.expected}", got "${n??"(not found)"}"`,duration:performance.now()-r,nodeType:"assertText",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:i,stepIndex:e.stepIndex,title:`Assert text: ${t.selector}`})}});import{z as fr}from"zod";var pl=fr.object({expected:fr.string().describe("Expected page title or substring"),operator:fr.enum(["equals","contains","startsWith","endsWith"]).describe("Comparison operator").default("contains")}),Wn=y({description:"Assert that the page title matches an expected value",name:"assert_title",schema:pl,execute:async(e,t)=>{let r=performance.now(),n=await e.page.title(),o=ml({actual:n,expected:t.expected,operator:t.operator}),i=o?"passed":"failed",s=[{description:`Title ${t.operator} "${t.expected}"`,detail:o?void 0:`Got: "${n}"`,status:i}],a=`agent-step-${String(e.stepIndex)}`,l={expected:{type:"static",value:t.expected},id:a,operator:t.operator,type:"assertTitle"};return S({assertions:s,detail:o?"Title matches":`Expected title ${t.operator} "${t.expected}", got "${n}"`,duration:performance.now()-r,nodeType:"assertTitle",page:e.page,runStartTime:e.runStartTime,specNode:l,status:i,stepIndex:e.stepIndex,title:`Assert title ${t.operator} "${t.expected}"`})}});function ml({actual:e,expected:t,operator:r}){return r==="equals"?e===t:r==="contains"?e.includes(t):r==="startsWith"?e.startsWith(t):r==="endsWith"?e.endsWith(t):!1}import{z as zn}from"zod";var fl=zn.object({selector:zn.string().describe("CSS selector for the element to check")}),Gn=y({description:"Assert that an element matching the selector is visible on the page",name:"assert_visible",schema:fl,execute:async(e,t)=>{let r=performance.now(),n=await e.page.locator(t.selector).isVisible().catch(()=>!1),o=n?"passed":"failed",i=[{description:`Element ${t.selector} is visible`,detail:n?"Element is visible":"Element is not visible",status:o}];return S({assertions:i,detail:n?"Element is visible":"Element is not visible",duration:performance.now()-r,nodeType:"assertVisible",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:o,stepIndex:e.stepIndex,title:`Assert visible: ${t.selector}`})}});import{z as Jn}from"zod";var gl=Jn.object({selector:Jn.string().describe("CSS selector for the checkbox to check")}),Kn=y({description:"Check a checkbox matching the CSS selector",name:"check",schema:gl,execute:async(e,t)=>{let r=performance.now();return await e.page.locator(t.selector).check({timeout:5e3}),S({assertions:[],detail:`Checked ${t.selector}`,duration:performance.now()-r,nodeType:"check",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Check ${t.selector}`})}});import{z as Yn}from"zod";var yl=Yn.object({selector:Yn.string().describe("CSS selector for the input to clear")}),Xn=y({description:"Clear the contents of an input field",name:"clear",schema:yl,execute:async(e,t)=>{let r=performance.now();return await e.page.locator(t.selector).clear({timeout:5e3}),S({assertions:[],detail:`Cleared ${t.selector}`,duration:performance.now()-r,nodeType:"clear",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Clear ${t.selector}`})}});import{z as Qn}from"zod";var hl=Qn.object({selector:Qn.string().describe("CSS selector for the element to click")}),Zn=y({description:"Click an element matching the CSS selector",name:"click",schema:hl,execute:async(e,t)=>{let r=performance.now();return await e.page.locator(t.selector).click({timeout:5e3}),S({assertions:[],detail:`Clicked ${t.selector}`,duration:performance.now()-r,nodeType:"click",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Click ${t.selector}`})}});import{z as gr}from"zod";var wl=gr.object({action:gr.enum(["read","write"]).describe("Whether to read from or write to the clipboard"),value:gr.string().optional().describe("Text to write (required for write action)")}),eo=y({description:"Read from or write to the browser clipboard. For write, provide the text value. For read, the clipboard contents are returned.",name:"clipboard",schema:wl,execute:async(e,t)=>{let r=performance.now(),n=`agent-step-${String(e.stepIndex)}`;if(t.action==="write"){if(t.value==null)throw new Error("clipboard write requires a value");let s=JSON.stringify(t.value);await M({awaitPromise:!0,expression:`navigator.clipboard.writeText(${s})`,page:e.page});let a={action:"write",id:n,type:"clipboard",value:{type:"static",value:t.value}};return S({assertions:[],detail:`Wrote to clipboard: "${t.value}"`,duration:performance.now()-r,nodeType:"clipboard",page:e.page,runStartTime:e.runStartTime,specNode:a,status:"passed",stepIndex:e.stepIndex,title:"Clipboard write"})}let o=await M({awaitPromise:!0,expression:"navigator.clipboard.readText()",page:e.page})??"",i={action:"read",id:n,type:"clipboard"};return S({assertions:[],detail:`Clipboard contents: "${o}"`,duration:performance.now()-r,nodeType:"clipboard",page:e.page,runStartTime:e.runStartTime,specNode:i,status:"passed",stepIndex:e.stepIndex,title:"Clipboard read"})}});import{z as St}from"zod";var to=St.object({summary:St.string().describe("This is the ONLY output the user sees. If the agent profile specifies an Output format, follow those instructions exactly. Otherwise, provide a summary of your findings."),verdict:St.enum(["pass","fail"]).describe("Whether the test passed or failed. If the agent profile defines Success Criteria, base this verdict on whether those criteria were met.")}),ro={anthropicTool:{description:"Call this tool when you have finished your evaluation. If the agent profile defines an Output section, the summary MUST follow those output instructions exactly. Otherwise, summarize your findings.",input_schema:{...St.toJSONSchema(to,{target:"draft-2020-12"}),type:"object"},name:"complete_test"},name:"complete_test",execute(e,t){let r=to.parse(t),n={kind:"verdict",summary:r.summary,toolOutput:`Verdict: ${r.verdict}
17
- ${r.summary}`,verdict:r.verdict};return Promise.resolve(n)}};import{z as no}from"zod";var bl=no.object({selector:no.string().describe("CSS selector for the element to extract text from")}),oo=y({description:"Extract the text content of an element matching the CSS selector. Returns the text so you can use it in assertions or decisions.",name:"extract_text",schema:bl,execute:async(e,t)=>{let r=performance.now(),o=await e.page.locator(t.selector).textContent({timeout:5e3})??"";return S({assertions:[],detail:`Extracted text: "${o}"`,duration:performance.now()-r,nodeType:"extractText",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Extract text from ${t.selector}`})}});import{z as yr}from"zod";var Sl=yr.object({selector:yr.string().describe("CSS selector for the input element"),value:yr.string().describe("The text to type into the element")}),io=y({description:"Clear and type text into an input element matching the CSS selector",name:"fill",schema:Sl,execute:async(e,t)=>{let r=performance.now();return await e.page.locator(t.selector).fill(t.value,{timeout:5e3}),S({assertions:[],detail:`Filled ${t.selector} with "${t.value}"`,duration:performance.now()-r,nodeType:"fill",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Fill ${t.selector}`})}});import{z as so}from"zod";var vl=so.object({level:so.string().describe("Filter by log level: 'error', 'warning', 'log', 'info', 'debug', or 'all'").default("all")}),ao=y({description:"Get console log messages from the browser. Optionally filter by level (error, warning, log, info, debug, all).",name:"get_console_logs",schema:vl,execute:(e,t)=>{let r=t.level==="all"?e.monitor.consoleEntries:e.monitor.consoleEntries.filter(o=>o.level===t.level);if(r.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:`No console ${t.level==="all"?"messages":t.level+" messages"} recorded.`};let n=r.map(o=>kl(o)).join(`
15
+ `)};K.prototype.renderPartial=function(t,r,n,o){if(n){var i=this.getConfigTags(o),s=yr(n)?n(t[1]):n[t[1]];if(s!=null){var a=t[6],l=t[5],c=t[4],d=s;l==0&&c&&(d=this.indentPartial(s,c,a));var u=this.parse(d,i);return this.renderTokens(u,r,n,d,o)}}};K.prototype.unescapedValue=function(t,r){var n=r.lookup(t[1]);if(n!=null)return n};K.prototype.escapedValue=function(t,r,n){var o=this.getConfigEscape(n)||ne.escape,i=r.lookup(t[1]);if(i!=null)return typeof i=="number"&&o===ne.escape?String(i):o(i)};K.prototype.rawValue=function(t){return t[1]};K.prototype.getConfigTags=function(t){return Oe(t)?t:t&&typeof t=="object"?t.tags:void 0};K.prototype.getConfigEscape=function(t){if(t&&typeof t=="object"&&!Oe(t))return t.escape};var ne={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(e){Qe.templateCache=e},get templateCache(){return Qe.templateCache}},Qe=new K;ne.clearCache=function(){return Qe.clearCache()};ne.parse=function(t,r){return Qe.parse(t,r)};ne.render=function(t,r,n,o){if(typeof t!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+Xa(t)+'" was given as the first argument for mustache#render(template, view, partials)');return Qe.render(t,r,n,o)};ne.escape=ol;ne.Scanner=Ze;ne.Context=Ne;ne.Writer=K;var Mn=ne;function et({defs:e}){return e==null?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,ml({def:r,name:t})]))}var pl={boolean:!1,number:0,string:""};function ml({def:e,name:t}){if(e.type==="env"){let r=process.env[e.key];if(r==null)throw new Error(`Environment variable "${e.key}" not set for variable "${t}"`);return r}return e.default??pl[e.type]??""}function vt({ref:e,variables:t}){if(e.type==="static")return e.value;let r=t[e.name];if(r==null||typeof r=="object")throw new Error(`Variable "${e.name}" is not defined`);return r}function Y({ref:e,variables:t}){let r=String(vt({ref:e,variables:t}));return Rt({raw:r,variables:t})}function kt({ref:e,variables:t}){let r=vt({ref:e,variables:t});return typeof r=="string"?Rt({raw:r,variables:t}):r}function Rt({raw:e,variables:t}){return Mn.render(e,t,{},{escape:r=>r})}function hr({ref:e,variables:t}){let r=vt({ref:e,variables:t});if(typeof r=="number")return r;let n=Number(r);if(Number.isNaN(n))throw new TypeError(`Cannot convert "${String(r)}" to number`);return n}function De({name:e,store:t,value:r}){return{...t,[e]:r}}function B({locator:e,page:t,variables:r}){switch(e.by){case"testId":return t.getByTestId(Bn(e.value,r));case"role":return t.getByRole(e.role,{exact:!0,name:e.name==null?void 0:Bn(e.name,r)})}}function Bn(e,t){return t==null?e:Rt({raw:e,variables:t})}async function Hn({node:e,page:t,timeout:r}){await B({locator:e.source,page:t,variables:void 0}).dragTo(B({locator:e.target,page:t,variables:void 0}),{timeout:r})}async function qn({node:e,page:t,timeout:r}){await B({locator:e.locator,page:t,variables:void 0}).click({button:"right",timeout:r})}function Wn({node:e,page:t,variables:r}){return t.once("dialog",async n=>{e.action==="accept"?await n.accept(e.promptText??void 0):await n.dismiss()}),{variables:r}}async function zn({node:e,page:t,variables:r}){if(e.action==="write"){if(e.value==null)throw new Error("clipboard write requires a value");let o=Y({ref:e.value,variables:r}),i=JSON.stringify(o);return await M({awaitPromise:!0,expression:`navigator.clipboard.writeText(${i})`,page:t}),{variables:r}}if(e.variable==null)throw new Error("clipboard read requires a variable name to store the result");let n=await M({awaitPromise:!0,expression:"navigator.clipboard.readText()",page:t})??"";return{variables:De({name:e.variable,store:r,value:n})}}async function Gn({node:e,page:t}){let r=t.context();e.state==="granted"?await r.grantPermissions([e.permission]):await r.clearPermissions()}async function wr({node:e,page:t,timeout:r,variables:n}){switch(e.type){case"click":case"check":case"uncheck":case"clear":case"dblclick":case"focus":case"hover":case"scrollIntoView":return gl({node:e,page:t,timeout:r,variables:n});case"rightClick":return await qn({node:e,page:t,timeout:r}),{variables:n};case"goto":{let o=Y({ref:e.url,variables:n});return await t.goto(o,{timeout:r,waitUntil:"domcontentloaded"}),await t.waitForLoadState("load",{timeout:r}),await t.waitForFunction("document.body != null && document.body.childElementCount > 0 && (document.body.textContent?.trim().length ?? 0) > 0",void 0,{timeout:r}),await M({awaitPromise:!0,expression:"new Promise((resolve) => { requestAnimationFrame(() => requestAnimationFrame(() => resolve(undefined))); })",page:t}),{variables:n}}case"fill":return hl({node:e,page:t,timeout:r,variables:n});case"select":return wl({node:e,page:t,timeout:r,variables:n});case"type":return bl({node:e,page:t,timeout:r,variables:n});case"press":return await yl({node:e,page:t,timeout:r}),{variables:n};case"drag":return await Hn({node:e,page:t,timeout:r}),{variables:n};case"upload":return Sl({node:e,page:t,timeout:r,variables:n});case"extractText":return vl({node:e,page:t,timeout:r,variables:n});case"setVariable":{let o=kt({ref:e.value,variables:n});return{variables:De({name:e.variable,store:n,value:o})}}case"fail":throw new Error(e.message);case"setViewport":return await t.setViewportSize({height:e.height,width:e.width}),{variables:n};case"handleDialog":return Wn({node:e,page:t,variables:n});case"clipboard":return zn({node:e,page:t,variables:n});case"setPermission":return await Gn({node:e,page:t}),{variables:n}}}var fl={check:"check",clear:"clear",click:"click",dblclick:"dblclick",focus:"focus",hover:"hover",scrollIntoView:"scrollIntoViewIfNeeded",uncheck:"uncheck"};async function gl({node:e,page:t,timeout:r,variables:n}){return await B({locator:e.locator,page:t,variables:n})[fl[e.type]]({timeout:r}),{variables:n}}async function yl({node:e,page:t,timeout:r}){e.locator==null?await t.keyboard.press(e.key):await B({locator:e.locator,page:t,variables:void 0}).press(e.key,{timeout:r})}async function hl({node:e,page:t,timeout:r,variables:n}){let o=Y({ref:e.value,variables:n});return await B({locator:e.locator,page:t,variables:n}).fill(o,{timeout:r}),{variables:n}}async function wl({node:e,page:t,timeout:r,variables:n}){let o=Y({ref:e.value,variables:n});return await B({locator:e.locator,page:t,variables:n}).selectOption(o,{timeout:r}),{variables:n}}async function bl({node:e,page:t,timeout:r,variables:n}){let o=Y({ref:e.value,variables:n});return await B({locator:e.locator,page:t,variables:n}).pressSequentially(o,{timeout:r}),{variables:n}}async function Sl({node:e,page:t,timeout:r,variables:n}){return await B({locator:e.locator,page:t,variables:n}).setInputFiles(e.files,{timeout:r}),{variables:n}}async function vl({node:e,page:t,timeout:r,variables:n}){let o=await B({locator:e.locator,page:t,variables:n}).textContent({timeout:r});if(o==null)throw new Error("extractText: element had no text content");return{variables:De({name:e.variable,store:n,value:o})}}import uc from"@anthropic-ai/sdk";import{z as Jn}from"zod";import{z as kl}from"zod";function y({description:e,execute:t,name:r,schema:n}){let o=kl.toJSONSchema(n,{target:"draft-2020-12"});return{anthropicTool:{description:e,input_schema:{...o,type:"object"},name:r},name:r,async execute(i,s){let a=n.parse(s);return{...await Promise.resolve(t(i,a)),kind:"action"}}}}function S(e){let t=[...e.assertions],r={assertions:t,detail:e.detail,duration:Math.round(e.duration),nodeId:`agent-step-${String(e.stepIndex)}`,nodeType:e.nodeType,recordingEndMs:void 0,recordingStartMs:void 0,snapshotTimestamp:Math.round(performance.now()-e.runStartTime),status:e.status,stepIndex:e.stepIndex,title:e.title,url:e.page.url()},n=t.length>0?t.map(o=>`${o.status}: ${o.description} \u2014 ${o.detail??""}`).join(`
16
+ `):`${e.status}: ${e.title}`;return{specNode:e.specNode,stepResult:r,toolOutput:n}}var Rl=Jn.object({selector:Jn.string().describe("CSS selector for the checkbox or radio button")}),Kn=y({description:"Assert that a checkbox or radio button is checked",name:"assert_checked",schema:Rl,execute:async(e,t)=>{let r=performance.now(),n=await e.page.locator(t.selector).isChecked().catch(()=>!1),o=n?"passed":"failed",i=[{description:`Element ${t.selector} is checked`,detail:n?void 0:"Element is not checked",status:o}];return S({assertions:i,detail:n?"Element is checked":"Element is not checked",duration:performance.now()-r,nodeType:"assertChecked",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:o,stepIndex:e.stepIndex,title:`Assert checked: ${t.selector}`})}});import{z as Yn}from"zod";var Pl=Yn.object({selector:Yn.string().describe("CSS selector for the element to check focus on")}),Xn=y({description:"Assert that an element has keyboard focus. Use for accessibility tab-order testing.",name:"assert_focused",schema:Pl,execute:async(e,t)=>{let r=performance.now(),o=!!await e.page.locator(t.selector).evaluate("(el) => document.activeElement === el",void 0,{timeout:5e3}).catch(()=>!1),i=o?"passed":"failed",s=[{description:`Element ${t.selector} is focused`,detail:o?void 0:"Element does not have focus",status:i}];return S({assertions:s,detail:o?"Element is focused":"Element does not have focus",duration:performance.now()-r,nodeType:"assertFocused",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:i,stepIndex:e.stepIndex,title:`Assert focused: ${t.selector}`})}});import{z as br}from"zod";var xl=br.object({expected:br.string().describe("The expected text content"),selector:br.string().describe("CSS selector for the element to check")}),Qn=y({description:"Assert that an element's text content matches the expected value",name:"assert_text",schema:xl,execute:async(e,t)=>{let r=performance.now(),n=await e.page.locator(t.selector).textContent({timeout:5e3}).catch(()=>null),o=n!=null&&n.includes(t.expected),i=o?"passed":"failed",s=[{description:`Text contains "${t.expected}"`,detail:`Actual: "${n??"(not found)"}"`,status:i}];return S({assertions:s,detail:o?`Text matches: "${t.expected}"`:`Expected "${t.expected}", got "${n??"(not found)"}"`,duration:performance.now()-r,nodeType:"assertText",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:i,stepIndex:e.stepIndex,title:`Assert text: ${t.selector}`})}});import{z as Sr}from"zod";var Cl=Sr.object({expected:Sr.string().describe("Expected page title or substring"),operator:Sr.enum(["equals","contains","startsWith","endsWith"]).describe("Comparison operator").default("contains")}),Zn=y({description:"Assert that the page title matches an expected value",name:"assert_title",schema:Cl,execute:async(e,t)=>{let r=performance.now(),n=await e.page.title(),o=El({actual:n,expected:t.expected,operator:t.operator}),i=o?"passed":"failed",s=[{description:`Title ${t.operator} "${t.expected}"`,detail:o?void 0:`Got: "${n}"`,status:i}],a=`agent-step-${String(e.stepIndex)}`,l={expected:{type:"static",value:t.expected},id:a,operator:t.operator,type:"assertTitle"};return S({assertions:s,detail:o?"Title matches":`Expected title ${t.operator} "${t.expected}", got "${n}"`,duration:performance.now()-r,nodeType:"assertTitle",page:e.page,runStartTime:e.runStartTime,specNode:l,status:i,stepIndex:e.stepIndex,title:`Assert title ${t.operator} "${t.expected}"`})}});function El({actual:e,expected:t,operator:r}){return r==="equals"?e===t:r==="contains"?e.includes(t):r==="startsWith"?e.startsWith(t):r==="endsWith"?e.endsWith(t):!1}import{z as eo}from"zod";var Tl=eo.object({selector:eo.string().describe("CSS selector for the element to check")}),to=y({description:"Assert that an element matching the selector is visible on the page",name:"assert_visible",schema:Tl,execute:async(e,t)=>{let r=performance.now(),n=await e.page.locator(t.selector).isVisible().catch(()=>!1),o=n?"passed":"failed",i=[{description:`Element ${t.selector} is visible`,detail:n?"Element is visible":"Element is not visible",status:o}];return S({assertions:i,detail:n?"Element is visible":"Element is not visible",duration:performance.now()-r,nodeType:"assertVisible",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:o,stepIndex:e.stepIndex,title:`Assert visible: ${t.selector}`})}});import{z as ro}from"zod";var $l=ro.object({selector:ro.string().describe("CSS selector for the checkbox to check")}),no=y({description:"Check a checkbox matching the CSS selector",name:"check",schema:$l,execute:async(e,t)=>{let r=performance.now();return await e.page.locator(t.selector).check({timeout:5e3}),S({assertions:[],detail:`Checked ${t.selector}`,duration:performance.now()-r,nodeType:"check",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Check ${t.selector}`})}});import{z as oo}from"zod";var Al=oo.object({selector:oo.string().describe("CSS selector for the input to clear")}),io=y({description:"Clear the contents of an input field",name:"clear",schema:Al,execute:async(e,t)=>{let r=performance.now();return await e.page.locator(t.selector).clear({timeout:5e3}),S({assertions:[],detail:`Cleared ${t.selector}`,duration:performance.now()-r,nodeType:"clear",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Clear ${t.selector}`})}});import{z as so}from"zod";var Il=so.object({selector:so.string().describe("CSS selector for the element to click")}),ao=y({description:"Click an element matching the CSS selector",name:"click",schema:Il,execute:async(e,t)=>{let r=performance.now();return await e.page.locator(t.selector).click({timeout:5e3}),S({assertions:[],detail:`Clicked ${t.selector}`,duration:performance.now()-r,nodeType:"click",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Click ${t.selector}`})}});import{z as vr}from"zod";var jl=vr.object({action:vr.enum(["read","write"]).describe("Whether to read from or write to the clipboard"),value:vr.string().optional().describe("Text to write (required for write action)")}),lo=y({description:"Read from or write to the browser clipboard. For write, provide the text value. For read, the clipboard contents are returned.",name:"clipboard",schema:jl,execute:async(e,t)=>{let r=performance.now(),n=`agent-step-${String(e.stepIndex)}`;if(t.action==="write"){if(t.value==null)throw new Error("clipboard write requires a value");let s=JSON.stringify(t.value);await M({awaitPromise:!0,expression:`navigator.clipboard.writeText(${s})`,page:e.page});let a={action:"write",id:n,type:"clipboard",value:{type:"static",value:t.value}};return S({assertions:[],detail:`Wrote to clipboard: "${t.value}"`,duration:performance.now()-r,nodeType:"clipboard",page:e.page,runStartTime:e.runStartTime,specNode:a,status:"passed",stepIndex:e.stepIndex,title:"Clipboard write"})}let o=await M({awaitPromise:!0,expression:"navigator.clipboard.readText()",page:e.page})??"",i={action:"read",id:n,type:"clipboard"};return S({assertions:[],detail:`Clipboard contents: "${o}"`,duration:performance.now()-r,nodeType:"clipboard",page:e.page,runStartTime:e.runStartTime,specNode:i,status:"passed",stepIndex:e.stepIndex,title:"Clipboard read"})}});import{z as Pt}from"zod";var co=Pt.object({summary:Pt.string().describe("This is the ONLY output the user sees. If the agent profile specifies an Output format, follow those instructions exactly. Otherwise, provide a summary of your findings."),verdict:Pt.enum(["pass","fail"]).describe("Whether the test passed or failed. If the agent profile defines Success Criteria, base this verdict on whether those criteria were met.")}),uo={anthropicTool:{description:"Call this tool when you have finished your evaluation. If the agent profile defines an Output section, the summary MUST follow those output instructions exactly. Otherwise, summarize your findings.",input_schema:{...Pt.toJSONSchema(co,{target:"draft-2020-12"}),type:"object"},name:"complete_test"},name:"complete_test",execute(e,t){let r=co.parse(t),n={kind:"verdict",summary:r.summary,toolOutput:`Verdict: ${r.verdict}
17
+ ${r.summary}`,verdict:r.verdict};return Promise.resolve(n)}};import{z as po}from"zod";var Nl=po.object({selector:po.string().describe("CSS selector for the element to extract text from")}),mo=y({description:"Extract the text content of an element matching the CSS selector. Returns the text so you can use it in assertions or decisions.",name:"extract_text",schema:Nl,execute:async(e,t)=>{let r=performance.now(),o=await e.page.locator(t.selector).textContent({timeout:5e3})??"";return S({assertions:[],detail:`Extracted text: "${o}"`,duration:performance.now()-r,nodeType:"extractText",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Extract text from ${t.selector}`})}});import{z as kr}from"zod";var Ol=kr.object({selector:kr.string().describe("CSS selector for the input element"),value:kr.string().describe("The text to type into the element")}),fo=y({description:"Clear and type text into an input element matching the CSS selector",name:"fill",schema:Ol,execute:async(e,t)=>{let r=performance.now();return await e.page.locator(t.selector).fill(t.value,{timeout:5e3}),S({assertions:[],detail:`Filled ${t.selector} with "${t.value}"`,duration:performance.now()-r,nodeType:"fill",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Fill ${t.selector}`})}});import{z as go}from"zod";var Dl=go.object({level:go.string().describe("Filter by log level: 'error', 'warning', 'log', 'info', 'debug', or 'all'").default("all")}),yo=y({description:"Get console log messages from the browser. Optionally filter by level (error, warning, log, info, debug, all).",name:"get_console_logs",schema:Dl,execute:(e,t)=>{let r=t.level==="all"?e.monitor.consoleEntries:e.monitor.consoleEntries.filter(o=>o.level===t.level);if(r.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:`No console ${t.level==="all"?"messages":t.level+" messages"} recorded.`};let n=r.map(o=>_l(o)).join(`
18
18
  `);return{specNode:void 0,stepResult:void 0,toolOutput:`${String(r.length)} console messages:
19
- ${n}`}}});function kl(e){let t=e.url.length>0?` (${e.url})`:"";return`[${e.level.toUpperCase()}] ${e.text}${t}`}import{z as lo}from"zod";var hr=50,Rl=lo.object({urlFilter:lo.string().describe("Optional regex to filter network entries by URL. Omit to see all.").default("")}),co=y({description:"Get a summary of network requests/responses. Shows method, URL, status code, and content type. Optionally filter by URL regex.",name:"get_network_log",schema:Rl,execute:(e,t)=>{let r=t.urlFilter.length>0?new RegExp(t.urlFilter,"i"):void 0,n=r==null?e.monitor.networkEntries:e.monitor.networkEntries.filter(a=>r.test(a.url));if(n.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:"No network requests recorded."};let o=n.slice(-hr),i=o.map(a=>{let l=a.statusCode==null?"pending":String(a.statusCode),c=a.responseHeaders["content-type"]??"";return`${a.method} ${l} ${a.url} [${c}]`}).join(`
20
- `),s=n.length>hr?`
21
- (showing last ${String(hr)} of ${String(n.length)})`:"";return{specNode:void 0,stepResult:void 0,toolOutput:`${String(o.length)} network requests:${s}
22
- ${i}`}}});import{z as uo}from"zod";var Pl=uo.object({urlPattern:uo.string().describe("Regex pattern to match the request URL")}),po=y({description:"Get the full response body for a specific network request matching the URL pattern. Returns the most recent match.",name:"get_network_response",schema:Pl,execute:(e,t)=>{let r=new RegExp(t.urlPattern,"i"),n=e.monitor.networkEntries.filter(l=>r.test(l.url));if(n.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:`No network requests matching: ${t.urlPattern}`};let o=n.at(-1);if(o==null)return{specNode:void 0,stepResult:void 0,toolOutput:`No network requests matching: ${t.urlPattern}`};let i=o.statusCode==null?"pending":String(o.statusCode),s=Object.entries(o.responseHeaders).map(([l,c])=>` ${l}: ${c}`).join(`
19
+ ${n}`}}});function _l(e){let t=e.url.length>0?` (${e.url})`:"";return`[${e.level.toUpperCase()}] ${e.text}${t}`}import{z as ho}from"zod";var Rr=50,Ll=ho.object({urlFilter:ho.string().describe("Optional regex to filter network entries by URL. Omit to see all.").default("")}),wo=y({description:"Get a summary of network requests/responses. Shows method, URL, status code, and content type. Optionally filter by URL regex.",name:"get_network_log",schema:Ll,execute:(e,t)=>{let r=t.urlFilter.length>0?new RegExp(t.urlFilter,"i"):void 0,n=r==null?e.monitor.networkEntries:e.monitor.networkEntries.filter(a=>r.test(a.url));if(n.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:"No network requests recorded."};let o=n.slice(-Rr),i=o.map(a=>{let l=a.statusCode==null?"pending":String(a.statusCode),c=a.responseHeaders["content-type"]??"";return`${a.method} ${l} ${a.url} [${c}]`}).join(`
20
+ `),s=n.length>Rr?`
21
+ (showing last ${String(Rr)} of ${String(n.length)})`:"";return{specNode:void 0,stepResult:void 0,toolOutput:`${String(o.length)} network requests:${s}
22
+ ${i}`}}});import{z as bo}from"zod";var Ul=bo.object({urlPattern:bo.string().describe("Regex pattern to match the request URL")}),So=y({description:"Get the full response body for a specific network request matching the URL pattern. Returns the most recent match.",name:"get_network_response",schema:Ul,execute:(e,t)=>{let r=new RegExp(t.urlPattern,"i"),n=e.monitor.networkEntries.filter(l=>r.test(l.url));if(n.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:`No network requests matching: ${t.urlPattern}`};let o=n.at(-1);if(o==null)return{specNode:void 0,stepResult:void 0,toolOutput:`No network requests matching: ${t.urlPattern}`};let i=o.statusCode==null?"pending":String(o.statusCode),s=Object.entries(o.responseHeaders).map(([l,c])=>` ${l}: ${c}`).join(`
23
23
  `),a=o.responseBody??"(no body captured)";return{specNode:void 0,stepResult:void 0,toolOutput:`${o.method} ${i} ${o.url}
24
24
 
25
25
  Response Headers:
26
26
  ${s}
27
27
 
28
28
  Body:
29
- ${a}`}}});import{z as xl}from"zod";var Cl=xl.object({}),mo=y({description:"Get the accessibility tree of the current page. Use this to verify ARIA roles, labels, states, and the semantic structure of the page.",name:"get_accessibility_tree",schema:Cl,execute:async(e,t)=>{try{let r=await e.page.context().newCDPSession(e.page);try{let n=await r.send("Accessibility.getFullAXTree");return{specNode:void 0,stepResult:void 0,toolOutput:JSON.stringify(n,null,2)}}finally{await r.detach().catch(()=>{})}}catch{return{specNode:void 0,stepResult:void 0,toolOutput:"(unable to capture accessibility tree)"}}}});import{z as El}from"zod";var Tl=El.object({}),fo=y({description:"Get a text representation of the current page content for inspection",name:"get_page_content",schema:Tl,execute:async(e,t)=>{let r=await e.page.locator("body").textContent({timeout:5e3}),n=e.page.url(),o=await e.page.title();return{specNode:void 0,stepResult:void 0,toolOutput:`URL: ${n}
29
+ ${a}`}}});import{z as Vl}from"zod";var Fl=Vl.object({}),vo=y({description:"Get the accessibility tree of the current page. Use this to verify ARIA roles, labels, states, and the semantic structure of the page.",name:"get_accessibility_tree",schema:Fl,execute:async(e,t)=>{try{let r=await e.page.context().newCDPSession(e.page);try{let n=await r.send("Accessibility.getFullAXTree");return{specNode:void 0,stepResult:void 0,toolOutput:JSON.stringify(n,null,2)}}finally{await r.detach().catch(()=>{})}}catch{return{specNode:void 0,stepResult:void 0,toolOutput:"(unable to capture accessibility tree)"}}}});import{z as Ml}from"zod";var Bl=Ml.object({}),ko=y({description:"Get a text representation of the current page content for inspection",name:"get_page_content",schema:Bl,execute:async(e,t)=>{let r=await e.page.locator("body").textContent({timeout:5e3}),n=e.page.url(),o=await e.page.title();return{specNode:void 0,stepResult:void 0,toolOutput:`URL: ${n}
30
30
  Title: ${o}
31
31
 
32
- ${r??""}`}}});import{z as $l}from"zod";var Al=$l.object({}),go=y({description:"Get uncaught JavaScript exceptions (page errors) that have occurred. These are runtime errors thrown in the browser that were not caught by error handlers.",name:"get_page_errors",schema:Al,execute:(e,t)=>{if(e.monitor.pageErrors.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:"No page errors recorded."};let r=e.monitor.pageErrors.map((n,o)=>`--- Error ${String(o+1)} ---
32
+ ${r??""}`}}});import{z as Hl}from"zod";var ql=Hl.object({}),Ro=y({description:"Get uncaught JavaScript exceptions (page errors) that have occurred. These are runtime errors thrown in the browser that were not caught by error handlers.",name:"get_page_errors",schema:ql,execute:(e,t)=>{if(e.monitor.pageErrors.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:"No page errors recorded."};let r=e.monitor.pageErrors.map((n,o)=>`--- Error ${String(o+1)} ---
33
33
  ${n}`).join(`
34
34
 
35
35
  `);return{specNode:void 0,stepResult:void 0,toolOutput:`${String(e.monitor.pageErrors.length)} page errors:
36
36
 
37
- ${r}`}}});import{z as yo}from"zod";var Il=yo.object({type:yo.enum(["all","cookies","localStorage","sessionStorage"]).describe("Which storage to retrieve").default("all")}),wo=y({description:"Get browser storage state: cookies (with httpOnly, secure, sameSite flags), localStorage, and/or sessionStorage. Useful for verifying authentication state, security cookie flags, and stored data.",name:"get_storage",schema:Il,execute:async(e,t)=>({specNode:void 0,stepResult:void 0,toolOutput:[...t.type==="all"||t.type==="cookies"?[await jl(e.page)]:[],...t.type==="all"||t.type==="localStorage"?[await ho(e.page,"localStorage")]:[],...t.type==="all"||t.type==="sessionStorage"?[await ho(e.page,"sessionStorage")]:[]].join(`
37
+ ${r}`}}});import{z as Po}from"zod";var Wl=Po.object({type:Po.enum(["all","cookies","localStorage","sessionStorage"]).describe("Which storage to retrieve").default("all")}),Co=y({description:"Get browser storage state: cookies (with httpOnly, secure, sameSite flags), localStorage, and/or sessionStorage. Useful for verifying authentication state, security cookie flags, and stored data.",name:"get_storage",schema:Wl,execute:async(e,t)=>({specNode:void 0,stepResult:void 0,toolOutput:[...t.type==="all"||t.type==="cookies"?[await zl(e.page)]:[],...t.type==="all"||t.type==="localStorage"?[await xo(e.page,"localStorage")]:[],...t.type==="all"||t.type==="sessionStorage"?[await xo(e.page,"sessionStorage")]:[]].join(`
38
38
 
39
- `)})});async function jl(e){let t=await e.context().cookies();if(t.length===0)return`## Cookies
39
+ `)})});async function zl(e){let t=await e.context().cookies();if(t.length===0)return`## Cookies
40
40
  (none)`;let r=t.map(n=>` ${n.name}=${n.value} (domain=${n.domain}, httpOnly=${String(n.httpOnly)}, secure=${String(n.secure)}, sameSite=${n.sameSite})`);return`## Cookies (${String(t.length)})
41
41
  ${r.join(`
42
- `)}`}async function ho(e,t){let r=await M({awaitPromise:!1,expression:`JSON.stringify(Object.fromEntries(Object.entries(${t})))`,page:e});return`## ${t}
43
- ${r??"{}"}`}import{z as wr}from"zod";var Nl=wr.object({action:wr.enum(["accept","dismiss"]).describe("Whether to accept or dismiss the dialog"),promptText:wr.string().optional().describe("Text to enter for prompt dialogs")}),bo=y({description:"Set up a handler for the next browser dialog (alert, confirm, prompt). Call this BEFORE the action that triggers the dialog.",name:"handle_dialog",schema:Nl,execute:(e,t)=>{let r=performance.now();e.page.once("dialog",async i=>{t.action==="accept"?await i.accept(t.promptText??void 0):await i.dismiss()});let n=`agent-step-${String(e.stepIndex)}`,o={action:t.action,id:n,type:"handleDialog"};return S({assertions:[],detail:`Dialog handler set: ${t.action}`,duration:performance.now()-r,nodeType:"handleDialog",page:e.page,runStartTime:e.runStartTime,specNode:o,status:"passed",stepIndex:e.stepIndex,title:`Handle dialog: ${t.action}`})}});import{z as So}from"zod";var Ol=So.object({selector:So.string().describe("CSS selector for the element to hover over")}),vo=y({description:"Hover over an element matching the CSS selector",name:"hover",schema:Ol,execute:async(e,t)=>{let r=performance.now();return await e.page.locator(t.selector).hover({timeout:5e3}),S({assertions:[],detail:`Hovered over ${t.selector}`,duration:performance.now()-r,nodeType:"hover",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Hover ${t.selector}`})}});import{z as br}from"zod";var Dl=br.object({permission:br.string().describe("Permission name (e.g. geolocation, notifications, camera, clipboard-read)"),state:br.enum(["granted","prompt"]).describe("Permission state to set")}),ko=y({description:"Set a browser permission state (geolocation, notifications, camera, etc.)",name:"set_permission",schema:Dl,execute:async(e,t)=>{let r=performance.now(),n=e.page.context();t.state==="granted"?await n.grantPermissions([t.permission]):await n.clearPermissions();let i={id:`agent-step-${String(e.stepIndex)}`,permission:t.permission,state:t.state,type:"setPermission"};return S({assertions:[],detail:`Set ${t.permission} to ${t.state}`,duration:performance.now()-r,nodeType:"setPermission",page:e.page,runStartTime:e.runStartTime,specNode:i,status:"passed",stepIndex:e.stepIndex,title:`Set permission: ${t.permission} \u2192 ${t.state}`})}});import{z as Ro}from"zod";var Ll=Ro.object({url:Ro.string().describe("The URL to navigate to")}),Po=y({description:"Navigate the browser to a URL",name:"navigate",schema:Ll,execute:async(e,t)=>{let r=performance.now();await e.page.goto(t.url,{waitUntil:"domcontentloaded"});let o={id:`agent-step-${String(e.stepIndex)}`,type:"goto",url:{type:"static",value:t.url}};return S({assertions:[],detail:`Navigated to ${t.url}`,duration:performance.now()-r,nodeType:"goto",page:e.page,runStartTime:e.runStartTime,specNode:o,status:"passed",stepIndex:e.stepIndex,title:`Navigate to ${t.url}`})}});import{z as xo}from"zod";var _l=xo.object({key:xo.string().describe("Key to press, e.g. 'Enter', 'Tab', 'Escape'")}),Co=y({description:"Press a keyboard key",name:"press",schema:_l,execute:async(e,t)=>{let r=performance.now();await e.page.keyboard.press(t.key);let o={id:`agent-step-${String(e.stepIndex)}`,key:t.key,type:"press"};return S({assertions:[],detail:`Pressed ${t.key}`,duration:performance.now()-r,nodeType:"press",page:e.page,runStartTime:e.runStartTime,specNode:o,status:"passed",stepIndex:e.stepIndex,title:`Press ${t.key}`})}});import{z as Sr}from"zod";var Ul=Sr.object({height:Sr.number().int().positive().describe("Viewport height in pixels"),width:Sr.number().int().positive().describe("Viewport width in pixels")}),Eo=y({description:"Resize the browser viewport to the specified dimensions. Use this to test responsive layouts at different screen sizes (e.g. mobile: 375x812, tablet: 768x1024, desktop: 1440x900).",name:"resize_viewport",schema:Ul,execute:async(e,t)=>{let r=performance.now();await e.page.setViewportSize({height:t.height,width:t.width});let n=`agent-step-${String(e.stepIndex)}`,o={height:t.height,id:n,type:"setViewport",width:t.width};return S({assertions:[],detail:`Resized viewport to ${String(t.width)}x${String(t.height)}`,duration:performance.now()-r,nodeType:"setViewport",page:e.page,runStartTime:e.runStartTime,specNode:o,status:"passed",stepIndex:e.stepIndex,title:`Resize viewport to ${String(t.width)}x${String(t.height)}`})}});import{z as To}from"zod";var Vl=To.object({selector:To.string().describe("CSS selector for the element to right-click")}),$o=y({description:"Right-click an element to open the context menu",name:"right_click",schema:Vl,execute:async(e,t)=>{let r=performance.now();return await e.page.locator(t.selector).click({button:"right",timeout:5e3}),S({assertions:[],detail:`Right-clicked ${t.selector}`,duration:performance.now()-r,nodeType:"rightClick",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Right-click ${t.selector}`})}});import{z as Ao}from"zod";var Fl=Ao.object({pattern:Ao.string().describe("Regex pattern to search console log messages")}),Io=y({description:"Search console log messages for a regex pattern. Returns matching entries.",name:"search_console",schema:Fl,execute:(e,t)=>{let r=new RegExp(t.pattern,"i"),n=e.monitor.consoleEntries.filter(i=>r.test(i.text));if(n.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:`No console messages matching: ${t.pattern}`};let o=n.map(i=>Ml(i)).join(`
42
+ `)}`}async function xo(e,t){let r=await M({awaitPromise:!1,expression:`JSON.stringify(Object.fromEntries(Object.entries(${t})))`,page:e});return`## ${t}
43
+ ${r??"{}"}`}import{z as Pr}from"zod";var Gl=Pr.object({action:Pr.enum(["accept","dismiss"]).describe("Whether to accept or dismiss the dialog"),promptText:Pr.string().optional().describe("Text to enter for prompt dialogs")}),Eo=y({description:"Set up a handler for the next browser dialog (alert, confirm, prompt). Call this BEFORE the action that triggers the dialog.",name:"handle_dialog",schema:Gl,execute:(e,t)=>{let r=performance.now();e.page.once("dialog",async i=>{t.action==="accept"?await i.accept(t.promptText??void 0):await i.dismiss()});let n=`agent-step-${String(e.stepIndex)}`,o={action:t.action,id:n,type:"handleDialog"};return S({assertions:[],detail:`Dialog handler set: ${t.action}`,duration:performance.now()-r,nodeType:"handleDialog",page:e.page,runStartTime:e.runStartTime,specNode:o,status:"passed",stepIndex:e.stepIndex,title:`Handle dialog: ${t.action}`})}});import{z as To}from"zod";var Jl=To.object({selector:To.string().describe("CSS selector for the element to hover over")}),$o=y({description:"Hover over an element matching the CSS selector",name:"hover",schema:Jl,execute:async(e,t)=>{let r=performance.now();return await e.page.locator(t.selector).hover({timeout:5e3}),S({assertions:[],detail:`Hovered over ${t.selector}`,duration:performance.now()-r,nodeType:"hover",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Hover ${t.selector}`})}});import{z as xr}from"zod";var Kl=xr.object({permission:xr.string().describe("Permission name (e.g. geolocation, notifications, camera, clipboard-read)"),state:xr.enum(["granted","prompt"]).describe("Permission state to set")}),Ao=y({description:"Set a browser permission state (geolocation, notifications, camera, etc.)",name:"set_permission",schema:Kl,execute:async(e,t)=>{let r=performance.now(),n=e.page.context();t.state==="granted"?await n.grantPermissions([t.permission]):await n.clearPermissions();let i={id:`agent-step-${String(e.stepIndex)}`,permission:t.permission,state:t.state,type:"setPermission"};return S({assertions:[],detail:`Set ${t.permission} to ${t.state}`,duration:performance.now()-r,nodeType:"setPermission",page:e.page,runStartTime:e.runStartTime,specNode:i,status:"passed",stepIndex:e.stepIndex,title:`Set permission: ${t.permission} \u2192 ${t.state}`})}});import{z as Io}from"zod";var Yl=Io.object({url:Io.string().describe("The URL to navigate to")}),jo=y({description:"Navigate the browser to a URL",name:"navigate",schema:Yl,execute:async(e,t)=>{let r=performance.now();await e.page.goto(t.url,{waitUntil:"domcontentloaded"});let o={id:`agent-step-${String(e.stepIndex)}`,type:"goto",url:{type:"static",value:t.url}};return S({assertions:[],detail:`Navigated to ${t.url}`,duration:performance.now()-r,nodeType:"goto",page:e.page,runStartTime:e.runStartTime,specNode:o,status:"passed",stepIndex:e.stepIndex,title:`Navigate to ${t.url}`})}});import{z as No}from"zod";var Xl=No.object({key:No.string().describe("Key to press, e.g. 'Enter', 'Tab', 'Escape'")}),Oo=y({description:"Press a keyboard key",name:"press",schema:Xl,execute:async(e,t)=>{let r=performance.now();await e.page.keyboard.press(t.key);let o={id:`agent-step-${String(e.stepIndex)}`,key:t.key,type:"press"};return S({assertions:[],detail:`Pressed ${t.key}`,duration:performance.now()-r,nodeType:"press",page:e.page,runStartTime:e.runStartTime,specNode:o,status:"passed",stepIndex:e.stepIndex,title:`Press ${t.key}`})}});import{z as Cr}from"zod";var Ql=Cr.object({height:Cr.number().int().positive().describe("Viewport height in pixels"),width:Cr.number().int().positive().describe("Viewport width in pixels")}),Do=y({description:"Resize the browser viewport to the specified dimensions. Use this to test responsive layouts at different screen sizes (e.g. mobile: 375x812, tablet: 768x1024, desktop: 1440x900).",name:"resize_viewport",schema:Ql,execute:async(e,t)=>{let r=performance.now();await e.page.setViewportSize({height:t.height,width:t.width});let n=`agent-step-${String(e.stepIndex)}`,o={height:t.height,id:n,type:"setViewport",width:t.width};return S({assertions:[],detail:`Resized viewport to ${String(t.width)}x${String(t.height)}`,duration:performance.now()-r,nodeType:"setViewport",page:e.page,runStartTime:e.runStartTime,specNode:o,status:"passed",stepIndex:e.stepIndex,title:`Resize viewport to ${String(t.width)}x${String(t.height)}`})}});import{z as _o}from"zod";var Zl=_o.object({selector:_o.string().describe("CSS selector for the element to right-click")}),Lo=y({description:"Right-click an element to open the context menu",name:"right_click",schema:Zl,execute:async(e,t)=>{let r=performance.now();return await e.page.locator(t.selector).click({button:"right",timeout:5e3}),S({assertions:[],detail:`Right-clicked ${t.selector}`,duration:performance.now()-r,nodeType:"rightClick",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Right-click ${t.selector}`})}});import{z as Uo}from"zod";var ec=Uo.object({pattern:Uo.string().describe("Regex pattern to search console log messages")}),Vo=y({description:"Search console log messages for a regex pattern. Returns matching entries.",name:"search_console",schema:ec,execute:(e,t)=>{let r=new RegExp(t.pattern,"i"),n=e.monitor.consoleEntries.filter(i=>r.test(i.text));if(n.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:`No console messages matching: ${t.pattern}`};let o=n.map(i=>tc(i)).join(`
44
44
  `);return{specNode:void 0,stepResult:void 0,toolOutput:`${String(n.length)} matching console messages:
45
- ${o}`}}});function Ml(e){let t=e.url.length>0?` (${e.url})`:"";return`[${e.level.toUpperCase()}] ${e.text}${t}`}import{z as jo}from"zod";var Hl=jo.object({pattern:jo.string().describe("Regex pattern to search across network request URLs and response bodies")}),No=y({description:"Search network requests and response bodies for a regex pattern. Useful for finding API calls, tokens, or specific data in responses.",name:"search_network",schema:Hl,execute:(e,t)=>{let r=new RegExp(t.pattern,"i"),n=e.monitor.networkEntries.filter(i=>r.test(i.url)||i.responseBody!=null&&r.test(i.responseBody));if(n.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:`No network entries matching: ${t.pattern}`};let o=n.map(i=>{let s=i.statusCode==null?"pending":String(i.statusCode),a=r.test(i.url)?" [URL match]":"",l=i.responseBody!=null&&r.test(i.responseBody)?" [body match]":"";return`${i.method} ${s} ${i.url}${a}${l}`}).join(`
45
+ ${o}`}}});function tc(e){let t=e.url.length>0?` (${e.url})`:"";return`[${e.level.toUpperCase()}] ${e.text}${t}`}import{z as Fo}from"zod";var rc=Fo.object({pattern:Fo.string().describe("Regex pattern to search across network request URLs and response bodies")}),Mo=y({description:"Search network requests and response bodies for a regex pattern. Useful for finding API calls, tokens, or specific data in responses.",name:"search_network",schema:rc,execute:(e,t)=>{let r=new RegExp(t.pattern,"i"),n=e.monitor.networkEntries.filter(i=>r.test(i.url)||i.responseBody!=null&&r.test(i.responseBody));if(n.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:`No network entries matching: ${t.pattern}`};let o=n.map(i=>{let s=i.statusCode==null?"pending":String(i.statusCode),a=r.test(i.url)?" [URL match]":"",l=i.responseBody!=null&&r.test(i.responseBody)?" [body match]":"";return`${i.method} ${s} ${i.url}${a}${l}`}).join(`
46
46
  `);return{specNode:void 0,stepResult:void 0,toolOutput:`${String(n.length)} matching network entries:
47
- ${o}`}}});import{z as Oo}from"zod";var ql=20,Bl=2,Wl=Oo.object({pattern:Oo.string().describe("Regex pattern to search for in the page HTML")}),Do=y({description:"Search the current page's full HTML/DOM for a regex pattern. Returns matching lines with context. Useful for finding elements, attributes, text content, or hidden data without reading the entire page.",name:"search_page",schema:Wl,execute:async(e,t)=>{let n=(await M({awaitPromise:!1,expression:"document.documentElement.outerHTML",page:e.page})??"").split(`
48
- `),o=zl({contextLines:Bl,lines:n,maxResults:ql,pattern:t.pattern});return o.length===0?{specNode:void 0,stepResult:void 0,toolOutput:`No matches found for pattern: ${t.pattern}`}:{specNode:void 0,stepResult:void 0,toolOutput:o.join(`
47
+ ${o}`}}});import{z as Bo}from"zod";var nc=20,oc=2,ic=Bo.object({pattern:Bo.string().describe("Regex pattern to search for in the page HTML")}),Ho=y({description:"Search the current page's full HTML/DOM for a regex pattern. Returns matching lines with context. Useful for finding elements, attributes, text content, or hidden data without reading the entire page.",name:"search_page",schema:ic,execute:async(e,t)=>{let n=(await M({awaitPromise:!1,expression:"document.documentElement.outerHTML",page:e.page})??"").split(`
48
+ `),o=sc({contextLines:oc,lines:n,maxResults:nc,pattern:t.pattern});return o.length===0?{specNode:void 0,stepResult:void 0,toolOutput:`No matches found for pattern: ${t.pattern}`}:{specNode:void 0,stepResult:void 0,toolOutput:o.join(`
49
49
  ---
50
- `)}}});function zl({contextLines:e,lines:t,maxResults:r,pattern:n}){let o=new RegExp(n,"i"),i=[];return t.forEach((s,a)=>{if(i.length>=r||!o.test(s))return;let l=Math.max(0,a-e),c=Math.min(t.length-1,a+e),d=t.slice(l,c+1).map((u,f)=>{let w=l+f+1;return`${l+f===a?">":" "} ${String(w)}: ${u}`}).join(`
51
- `);i.push(d)}),i}import{z as vr}from"zod";var Gl=vr.object({selector:vr.string().describe("CSS selector for the select element"),value:vr.string().describe("The option value to select")}),Lo=y({description:"Select an option from a dropdown/select element",name:"select",schema:Gl,execute:async(e,t)=>{let r=performance.now();return await e.page.locator(t.selector).selectOption(t.value,{timeout:5e3}),S({assertions:[],detail:`Selected "${t.value}" in ${t.selector}`,duration:performance.now()-r,nodeType:"select",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Select ${t.value}`})}});import{z as _o}from"zod";var Jl=_o.object({selector:_o.string().describe("CSS selector for the checkbox to uncheck")}),Uo=y({description:"Uncheck a checkbox matching the CSS selector",name:"uncheck",schema:Jl,execute:async(e,t)=>{let r=performance.now();return await e.page.locator(t.selector).uncheck({timeout:5e3}),S({assertions:[],detail:`Unchecked ${t.selector}`,duration:performance.now()-r,nodeType:"uncheck",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Uncheck ${t.selector}`})}});var vt=class{method;requestHeaders;requestPostData;timestamp;url;responseBody=void 0;responseHeaders={};statusCode=void 0;constructor(t){this.method=t.method(),this.requestHeaders=t.headers(),this.requestPostData=t.postData()??void 0,this.timestamp=Date.now(),this.url=t.url()}applyResponse(t){this.statusCode=t.status(),this.responseHeaders=t.headers(),t.text().then(r=>{this.responseBody=r.length>1e5?`${r.slice(0,1e5)}... (truncated)`:r}).catch(()=>{this.responseBody="(unable to read body)"})}};function Ze(e){let t=[],r=[],n=[],o=new Map;function i(u){t.push({level:u.type(),text:u.text(),timestamp:Date.now(),url:u.location().url})}function s(u){let f=new vt(u);o.set(u,f),r.push(f)}function a(u){let f=o.get(u.request());f!=null&&(o.delete(u.request()),f.applyResponse(u))}function l(u){n.push(`${u.message}
52
- ${u.stack??""}`)}function c(u){let f=u.failure(),w=new vt(u);w.responseBody=`(request failed: ${f?.errorText??"unknown"})`,r.push(w)}e.on("console",i),e.on("request",s),e.on("response",a),e.on("pageerror",l),e.on("requestfailed",c);function d(){e.off("console",i),e.off("request",s),e.off("response",a),e.off("pageerror",l),e.off("requestfailed",c)}return{consoleEntries:t,detach:d,networkEntries:r,pageErrors:n}}var kr=[Po,Zn,io,Co,Kn,Uo,Lo,vo,fo,Do,Xn,$o,bo,eo,ko,Gn,Bn,Wn,Mn,qn,ao,co,po,go,mo,wo,Io,No,Eo,oo,ro],Kl=new Map(kr.map(e=>[e.name,e])),Rr=kr.map(e=>e.anthropicTool),Vo=kr.map(e=>`- **${e.name}**: ${e.anthropicTool.description??""}`).join(`
53
- `);async function Fo({input:e,monitor:t,name:r,page:n,runStartTime:o,stepIndex:i}){let s=Kl.get(r);if(s==null)throw new Error(`Unknown agent tool: ${r}`);return s.execute({monitor:t,page:n,runStartTime:o,stepIndex:i},e)}import vv from"fs";import Rv from"path";import Yl from"pino";var h=Yl({transport:{options:{ignore:"pid,hostname"},target:"pino-pretty"}});var Ql=50,Mo=16384;async function Pr({baseUrl:e,executedPreconditions:t,extraVariables:r,onStep:n,page:o,runId:i,serverUrl:s,spec:a,systemPrompt:l,token:c,workflowContext:d}){let u=new Xl({apiKey:"ripplo",baseURL:`${s}/api/proxy/anthropic`,defaultHeaders:{Authorization:`Bearer ${c}`,"x-run-id":i}}),f=performance.now(),w=Ze(o);await sc({baseUrl:e,page:o});let v=tc({extraVariables:r,spec:a}),g=nc({baseUrl:e,executedPreconditions:t,spec:a,systemPrompt:l,variables:v,workflowContext:d}),E=oc({baseUrl:e,spec:a,variables:v}),L=[{content:ic({page:o,startUrl:E}),role:"user"}],z=[],_=[],F={findings:"",stepIndex:0,verdict:void 0};F=await Zl({client:u,messages:L,monitor:w,onStep:n,page:o,runStartTime:f,specNodes:_,state:F,steps:z,system:g}),F.verdict==null&&(F=await ec({client:u,messages:L,monitor:w,onStep:n,page:o,runStartTime:f,specNodes:_,state:F,steps:z,system:g}));let ie=lc(_);return{findings:F.findings,generatedSpec:ie,monitor:w,steps:z,verdict:F.verdict??"fail"}}function Ho({result:e,state:t}){return{findings:e.newFindings.length>0?e.newFindings:t.findings,stepIndex:e.nextStepIndex,verdict:e.verdict??t.verdict}}async function Zl({client:e,messages:t,monitor:r,onStep:n,page:o,runStartTime:i,specNodes:s,state:a,steps:l,system:c}){let d=a;for(let u=0;u<Ql;u++){h.info("Agent iteration %d",u+1);let f=await e.messages.create({max_tokens:Mo,messages:t,model:"server-controlled",system:c,tools:Rr}),w=await qo({messages:t,monitor:r,onStep:n,page:o,response:f,runStartTime:i,specNodes:s,stepIndex:d.stepIndex,steps:l});if(d=Ho({result:w,state:d}),!w.continueLoop)break}return d}async function ec({client:e,messages:t,monitor:r,onStep:n,page:o,runStartTime:i,specNodes:s,state:a,steps:l,system:c}){h.warn("Agent exited without calling complete_test \u2014 forcing completion"),t.push({content:"You must call the complete_test tool now with your verdict and summary. Do not perform any more actions \u2014 just call complete_test.",role:"user"});let d=await e.messages.create({max_tokens:Mo,messages:t,model:"server-controlled",system:c,tool_choice:{name:"complete_test",type:"tool"},tools:Rr}),u=await qo({messages:t,monitor:r,onStep:n,page:o,response:d,runStartTime:i,specNodes:s,stepIndex:a.stepIndex,steps:l});return Ho({result:u,state:a})}function tc({extraVariables:e,spec:t}){let r=rc(e,t?.variableNamespaces);return{...Qe({defs:t?.variables}),...r}}function rc(e,t){if(e==null||t==null)return{};let r=new Map;Object.entries(t).forEach(([o,i])=>{r.set(i,o)});let n={};return Object.entries(e).forEach(([o,i])=>{let s=r.get(o);Object.entries(i).forEach(([a,l])=>{n[s==null?a:`${s}.${a}`]=l})}),n}function nc({baseUrl:e,executedPreconditions:t,spec:r,systemPrompt:n,variables:o,workflowContext:i}){let s=i==null?"":[`
50
+ `)}}});function sc({contextLines:e,lines:t,maxResults:r,pattern:n}){let o=new RegExp(n,"i"),i=[];return t.forEach((s,a)=>{if(i.length>=r||!o.test(s))return;let l=Math.max(0,a-e),c=Math.min(t.length-1,a+e),d=t.slice(l,c+1).map((u,f)=>{let w=l+f+1;return`${l+f===a?">":" "} ${String(w)}: ${u}`}).join(`
51
+ `);i.push(d)}),i}import{z as Er}from"zod";var ac=Er.object({selector:Er.string().describe("CSS selector for the select element"),value:Er.string().describe("The option value to select")}),qo=y({description:"Select an option from a dropdown/select element",name:"select",schema:ac,execute:async(e,t)=>{let r=performance.now();return await e.page.locator(t.selector).selectOption(t.value,{timeout:5e3}),S({assertions:[],detail:`Selected "${t.value}" in ${t.selector}`,duration:performance.now()-r,nodeType:"select",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Select ${t.value}`})}});import{z as Wo}from"zod";var lc=Wo.object({selector:Wo.string().describe("CSS selector for the checkbox to uncheck")}),zo=y({description:"Uncheck a checkbox matching the CSS selector",name:"uncheck",schema:lc,execute:async(e,t)=>{let r=performance.now();return await e.page.locator(t.selector).uncheck({timeout:5e3}),S({assertions:[],detail:`Unchecked ${t.selector}`,duration:performance.now()-r,nodeType:"uncheck",page:e.page,runStartTime:e.runStartTime,specNode:void 0,status:"passed",stepIndex:e.stepIndex,title:`Uncheck ${t.selector}`})}});var xt=class{method;requestHeaders;requestPostData;timestamp;url;responseBody=void 0;responseHeaders={};statusCode=void 0;constructor(t){this.method=t.method(),this.requestHeaders=t.headers(),this.requestPostData=t.postData()??void 0,this.timestamp=Date.now(),this.url=t.url()}applyResponse(t){this.statusCode=t.status(),this.responseHeaders=t.headers(),t.text().then(r=>{this.responseBody=r.length>1e5?`${r.slice(0,1e5)}... (truncated)`:r}).catch(()=>{this.responseBody="(unable to read body)"})}};function tt(e){let t=[],r=[],n=[],o=new Map;function i(u){t.push({level:u.type(),text:u.text(),timestamp:Date.now(),url:u.location().url})}function s(u){let f=new xt(u);o.set(u,f),r.push(f)}function a(u){let f=o.get(u.request());f!=null&&(o.delete(u.request()),f.applyResponse(u))}function l(u){n.push(`${u.message}
52
+ ${u.stack??""}`)}function c(u){let f=u.failure(),w=new xt(u);w.responseBody=`(request failed: ${f?.errorText??"unknown"})`,r.push(w)}e.on("console",i),e.on("request",s),e.on("response",a),e.on("pageerror",l),e.on("requestfailed",c);function d(){e.off("console",i),e.off("request",s),e.off("response",a),e.off("pageerror",l),e.off("requestfailed",c)}return{consoleEntries:t,detach:d,networkEntries:r,pageErrors:n}}var Tr=[jo,ao,fo,Oo,no,zo,qo,$o,ko,Ho,io,Lo,Eo,lo,Ao,to,Qn,Zn,Kn,Xn,yo,wo,So,Ro,vo,Co,Vo,Mo,Do,mo,uo],cc=new Map(Tr.map(e=>[e.name,e])),$r=Tr.map(e=>e.anthropicTool),Go=Tr.map(e=>`- **${e.name}**: ${e.anthropicTool.description??""}`).join(`
53
+ `);async function Jo({input:e,monitor:t,name:r,page:n,runStartTime:o,stepIndex:i}){let s=cc.get(r);if(s==null)throw new Error(`Unknown agent tool: ${r}`);return s.execute({monitor:t,page:n,runStartTime:o,stepIndex:i},e)}import Dv from"fs";import Lv from"path";import dc from"pino";var h=dc({transport:{options:{ignore:"pid,hostname"},target:"pino-pretty"}});var pc=50,Ko=16384;async function Ar({baseUrl:e,executedPreconditions:t,extraVariables:r,onStep:n,page:o,runId:i,serverUrl:s,spec:a,systemPrompt:l,token:c,workflowContext:d}){let u=new uc({apiKey:"ripplo",baseURL:`${s}/api/proxy/anthropic`,defaultHeaders:{Authorization:`Bearer ${c}`,"x-run-id":i}}),f=performance.now(),w=tt(o);await Sc({baseUrl:e,page:o});let v=gc({extraVariables:r,spec:a}),g=hc({baseUrl:e,executedPreconditions:t,spec:a,systemPrompt:l,variables:v,workflowContext:d}),E=wc({baseUrl:e,spec:a,variables:v}),_=[{content:bc({page:o,startUrl:E}),role:"user"}],z=[],L=[],F={findings:"",stepIndex:0,verdict:void 0};F=await mc({client:u,messages:_,monitor:w,onStep:n,page:o,runStartTime:f,specNodes:L,state:F,steps:z,system:g}),F.verdict==null&&(F=await fc({client:u,messages:_,monitor:w,onStep:n,page:o,runStartTime:f,specNodes:L,state:F,steps:z,system:g}));let se=kc(L);return{findings:F.findings,generatedSpec:se,monitor:w,steps:z,verdict:F.verdict??"fail"}}function Yo({result:e,state:t}){return{findings:e.newFindings.length>0?e.newFindings:t.findings,stepIndex:e.nextStepIndex,verdict:e.verdict??t.verdict}}async function mc({client:e,messages:t,monitor:r,onStep:n,page:o,runStartTime:i,specNodes:s,state:a,steps:l,system:c}){let d=a;for(let u=0;u<pc;u++){h.info("Agent iteration %d",u+1);let f=await e.messages.create({max_tokens:Ko,messages:t,model:"server-controlled",system:c,tools:$r}),w=await Xo({messages:t,monitor:r,onStep:n,page:o,response:f,runStartTime:i,specNodes:s,stepIndex:d.stepIndex,steps:l});if(d=Yo({result:w,state:d}),!w.continueLoop)break}return d}async function fc({client:e,messages:t,monitor:r,onStep:n,page:o,runStartTime:i,specNodes:s,state:a,steps:l,system:c}){h.warn("Agent exited without calling complete_test \u2014 forcing completion"),t.push({content:"You must call the complete_test tool now with your verdict and summary. Do not perform any more actions \u2014 just call complete_test.",role:"user"});let d=await e.messages.create({max_tokens:Ko,messages:t,model:"server-controlled",system:c,tool_choice:{name:"complete_test",type:"tool"},tools:$r}),u=await Xo({messages:t,monitor:r,onStep:n,page:o,response:d,runStartTime:i,specNodes:s,stepIndex:a.stepIndex,steps:l});return Yo({result:u,state:a})}function gc({extraVariables:e,spec:t}){let r=yc(e,t?.variableNamespaces);return{...et({defs:t?.variables}),...r}}function yc(e,t){if(e==null||t==null)return{};let r=new Map;Object.entries(t).forEach(([o,i])=>{r.set(i,o)});let n={};return Object.entries(e).forEach(([o,i])=>{let s=r.get(o);Object.entries(i).forEach(([a,l])=>{n[s==null?a:`${s}.${a}`]=l})}),n}function hc({baseUrl:e,executedPreconditions:t,spec:r,systemPrompt:n,variables:o,workflowContext:i}){let s=i==null?"":[`
54
54
 
55
55
  ## Workflow Under Test`,`**Name:** ${i.name}`,`**Description:** ${i.description}`,`**Expected Outcome:** ${i.expectedOutcome}`,`
56
56
  Focus your testing ONLY on this specific workflow. Do not test unrelated parts of the application.`].join(`
@@ -71,23 +71,23 @@ Do not repeat any of these steps.`,d=Object.entries(o),u=d.map(([w,v])=>`- **${w
71
71
 
72
72
  ## Resolved Variables
73
73
  ${u}`;return[`You are testing the application at: ${e}`,"Use the provided tools to navigate, interact with, and assert things about the page.","Use get_page_content to inspect the page when you need to understand what's on screen.","Follow the workflow steps to complete the task.",`
74
- ## Available Tools`,Vo,s,c,a,f,`
74
+ ## Available Tools`,Go,s,c,a,f,`
75
75
  ## Agent Profile (HIGHEST PRIORITY \u2014 these instructions override any defaults above)`,n].join(`
76
- `)}function oc({baseUrl:e,spec:t,variables:r}){if(t==null)return e;let n=t.nodes[t.entryNode];if(n==null||n.type!=="goto"||n.url.type!=="static")return e;let i=n.url.value.replaceAll(/\{\{(\w+)\}\}/g,(s,a)=>{let l=r[a];return l==null?`{{${a}}}`:typeof l=="object"?JSON.stringify(l):String(l)});return i.startsWith("http")?i:`${e}${i.startsWith("/")?"":"/"}${i}`}function ic({page:e,startUrl:t}){let r=e.url();return r!=="about:blank"&&r.length>0?`You are already on the page at ${r}. Begin testing from this page \u2014 do not navigate away unless the workflow requires it.`:`Navigate to ${t} and begin testing.`}async function sc({baseUrl:e,page:t}){let r=new URL(e).origin;await t.route("**/*",n=>{let o=n.request();return o.isNavigationRequest()&&new URL(o.url()).origin!==r?(h.warn("Blocked navigation to off-origin URL: %s",o.url()),n.abort("blockedbyclient")):n.continue()})}async function qo({messages:e,monitor:t,onStep:r,page:n,response:o,runStartTime:i,specNodes:s,stepIndex:a,steps:l}){let c=o.content.filter(E=>E.type==="text").map(E=>E.text),d=o.content.filter(E=>E.type==="tool_use");if(d.length===0)return{continueLoop:!1,newFindings:c.join(`
77
- `),nextStepIndex:a,verdict:void 0};let u=[],f=a,w,v;for(let E of d){let P=await ac({block:E,monitor:t,onStep:r,page:n,runStartTime:i,specNodes:s,stepIndex:f,steps:l});u.push(P.toolResult),f=P.nextStepIndex,P.verdict!=null&&(w=P.verdict,v=P.summary)}e.push({content:o.content,role:"assistant"},{content:u,role:"user"});let g=v??c.join(`
78
- `);return{continueLoop:w==null&&o.stop_reason==="tool_use",newFindings:g,nextStepIndex:f,verdict:w}}async function ac({block:e,monitor:t,onStep:r,page:n,runStartTime:o,specNodes:i,stepIndex:s,steps:a}){try{let l=await Fo({input:e.input,monitor:t,name:e.name,page:n,runStartTime:o,stepIndex:s}),c={content:l.toolOutput,tool_use_id:e.id,type:"tool_result"};return l.kind==="verdict"?(h.info(" [%d] %s \u2014 verdict: %s",s,e.name,l.verdict),{nextStepIndex:s,summary:l.summary,toolResult:c,verdict:l.verdict}):(l.specNode!=null&&i.push(l.specNode),l.stepResult!=null?(a.push(l.stepResult),r?.(l.stepResult),h.info(" [%d] %s \u2014 %s",s,e.name,l.stepResult.status),{nextStepIndex:s+1,summary:void 0,toolResult:c,verdict:void 0}):(h.info(" [%d] %s \u2014 info",s,e.name),{nextStepIndex:s,summary:void 0,toolResult:c,verdict:void 0}))}catch(l){let c=l instanceof Error?l.message:"Unknown error";h.error(" [%d] %s \u2014 error: %s",s,e.name,c);let d={assertions:[],detail:`Error: ${c}`,duration:0,nodeId:`agent-step-${String(s)}`,nodeType:"click",recordingEndMs:void 0,recordingStartMs:void 0,snapshotTimestamp:Math.round(performance.now()-o),status:"failed",stepIndex:s,title:`${e.name} (error)`,url:n.url()};return a.push(d),r?.(d),{nextStepIndex:s+1,summary:void 0,toolResult:{content:`Error: ${c}`,is_error:!0,tool_use_id:e.id,type:"tool_result"},verdict:void 0}}}function lc(e){if(e.length===0)return{entryNode:"",nodes:{}};let t={};e.forEach((n,o)=>{let i=e[o+1],s=i==null?n:{...n,next:i.id};t[n.id]=s});let r=e[0];if(r==null)throw new Error("Expected at least one spec node after length check");return{entryNode:r.id,nodes:t}}function xr({description:e,output:t,successCriteria:r}){let n=[`## Agent Identity
76
+ `)}function wc({baseUrl:e,spec:t,variables:r}){if(t==null)return e;let n=t.nodes[t.entryNode];if(n==null||n.type!=="goto"||n.url.type!=="static")return e;let i=n.url.value.replaceAll(/\{\{(\w+)\}\}/g,(s,a)=>{let l=r[a];return l==null?`{{${a}}}`:typeof l=="object"?JSON.stringify(l):String(l)});return i.startsWith("http")?i:`${e}${i.startsWith("/")?"":"/"}${i}`}function bc({page:e,startUrl:t}){let r=e.url();return r!=="about:blank"&&r.length>0?`You are already on the page at ${r}. Begin testing from this page \u2014 do not navigate away unless the workflow requires it.`:`Navigate to ${t} and begin testing.`}async function Sc({baseUrl:e,page:t}){let r=new URL(e).origin;await t.route("**/*",n=>{let o=n.request();return o.isNavigationRequest()&&new URL(o.url()).origin!==r?(h.warn("Blocked navigation to off-origin URL: %s",o.url()),n.abort("blockedbyclient")):n.continue()})}async function Xo({messages:e,monitor:t,onStep:r,page:n,response:o,runStartTime:i,specNodes:s,stepIndex:a,steps:l}){let c=o.content.filter(E=>E.type==="text").map(E=>E.text),d=o.content.filter(E=>E.type==="tool_use");if(d.length===0)return{continueLoop:!1,newFindings:c.join(`
77
+ `),nextStepIndex:a,verdict:void 0};let u=[],f=a,w,v;for(let E of d){let P=await vc({block:E,monitor:t,onStep:r,page:n,runStartTime:i,specNodes:s,stepIndex:f,steps:l});u.push(P.toolResult),f=P.nextStepIndex,P.verdict!=null&&(w=P.verdict,v=P.summary)}e.push({content:o.content,role:"assistant"},{content:u,role:"user"});let g=v??c.join(`
78
+ `);return{continueLoop:w==null&&o.stop_reason==="tool_use",newFindings:g,nextStepIndex:f,verdict:w}}async function vc({block:e,monitor:t,onStep:r,page:n,runStartTime:o,specNodes:i,stepIndex:s,steps:a}){try{let l=await Jo({input:e.input,monitor:t,name:e.name,page:n,runStartTime:o,stepIndex:s}),c={content:l.toolOutput,tool_use_id:e.id,type:"tool_result"};return l.kind==="verdict"?(h.info(" [%d] %s \u2014 verdict: %s",s,e.name,l.verdict),{nextStepIndex:s,summary:l.summary,toolResult:c,verdict:l.verdict}):(l.specNode!=null&&i.push(l.specNode),l.stepResult!=null?(a.push(l.stepResult),r?.(l.stepResult),h.info(" [%d] %s \u2014 %s",s,e.name,l.stepResult.status),{nextStepIndex:s+1,summary:void 0,toolResult:c,verdict:void 0}):(h.info(" [%d] %s \u2014 info",s,e.name),{nextStepIndex:s,summary:void 0,toolResult:c,verdict:void 0}))}catch(l){let c=l instanceof Error?l.message:"Unknown error";h.error(" [%d] %s \u2014 error: %s",s,e.name,c);let d={assertions:[],detail:`Error: ${c}`,duration:0,nodeId:`agent-step-${String(s)}`,nodeType:"click",recordingEndMs:void 0,recordingStartMs:void 0,snapshotTimestamp:Math.round(performance.now()-o),status:"failed",stepIndex:s,title:`${e.name} (error)`,url:n.url()};return a.push(d),r?.(d),{nextStepIndex:s+1,summary:void 0,toolResult:{content:`Error: ${c}`,is_error:!0,tool_use_id:e.id,type:"tool_result"},verdict:void 0}}}function kc(e){if(e.length===0)return{entryNode:"",nodes:{}};let t={};e.forEach((n,o)=>{let i=e[o+1],s=i==null?n:{...n,next:i.id};t[n.id]=s});let r=e[0];if(r==null)throw new Error("Expected at least one spec node after length check");return{entryNode:r.id,nodes:t}}function Ir({description:e,output:t,successCriteria:r}){let n=[`## Agent Identity
79
79
  ${e}`];t!=null&&t.length>0&&n.push(`## Output
80
80
  ${t}`),r!=null&&r.length>0&&n.push(`## Success Criteria
81
- ${r}`);let o=["## Completing Your Evaluation",'When you finish your evaluation, you MUST call the `complete_test` tool with your verdict ("pass" or "fail") and a `summary` string.',cc({hasSuccessCriteria:r!=null&&r.length>0}),dc({hasOutput:t!=null&&t.length>0})];return n.push(o.join(`
81
+ ${r}`);let o=["## Completing Your Evaluation",'When you finish your evaluation, you MUST call the `complete_test` tool with your verdict ("pass" or "fail") and a `summary` string.',Rc({hasSuccessCriteria:r!=null&&r.length>0}),Pc({hasOutput:t!=null&&t.length>0})];return n.push(o.join(`
82
82
  `)),n.join(`
83
83
 
84
- `)}function cc({hasSuccessCriteria:e}){return e?"Base your verdict strictly on the Success Criteria defined above. A test passes ONLY if all success criteria are met, and fails if any criterion is not met. Individual step failures during exploration do not necessarily mean the test failed, but the success criteria are the ultimate authority for your verdict.":"Base your verdict on whether the workflow worked correctly. Individual step failures during exploration do not necessarily mean the test failed."}function dc({hasOutput:e}){return e?'The `summary` parameter is the ONLY output the user will see. You MUST use the `summary` field for EXACTLY the output described in the "Output" section above \u2014 nothing else. Do not describe what you did, do not list steps, do not add a test summary. The `summary` must contain ONLY what the Output section asks for, word for word if it specifies exact text.':"Include a brief summary of what you found in the `summary` parameter."}import{execFile as uc}from"child_process";import{createRequire as pc}from"module";import Bo from"fs";import Wo from"path";import{chromium as zo}from"playwright";async function Ce({headed:e}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";try{return await zo.launch({headless:!e})}catch(t){throw mc(t)?new Error(`Playwright browsers are not installed. Run:
84
+ `)}function Rc({hasSuccessCriteria:e}){return e?"Base your verdict strictly on the Success Criteria defined above. A test passes ONLY if all success criteria are met, and fails if any criterion is not met. Individual step failures during exploration do not necessarily mean the test failed, but the success criteria are the ultimate authority for your verdict.":"Base your verdict on whether the workflow worked correctly. Individual step failures during exploration do not necessarily mean the test failed."}function Pc({hasOutput:e}){return e?'The `summary` parameter is the ONLY output the user will see. You MUST use the `summary` field for EXACTLY the output described in the "Output" section above \u2014 nothing else. Do not describe what you did, do not list steps, do not add a test summary. The `summary` must contain ONLY what the Output section asks for, word for word if it specifies exact text.':"Include a brief summary of what you found in the `summary` parameter."}import{execFile as xc}from"child_process";import{createRequire as Cc}from"module";import Qo from"fs";import Zo from"path";import{chromium as ei}from"playwright";async function Te({headed:e}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";try{return await ei.launch({headless:!e})}catch(t){throw Ec(t)?new Error(`Playwright browsers are not installed. Run:
85
85
 
86
86
  npx playwright install chromium
87
- `):t}}async function Cr(){let e=zo.executablePath();if(Bo.existsSync(e))return;h.info("Chromium not found. Installing via Playwright...");let t=pc(import.meta.url),r=Wo.dirname(t.resolve("playwright/package.json")),n=Wo.join(r,"cli.js");if(await new Promise((o,i)=>{uc(process.execPath,[n,"install","chromium"],s=>{if(s!=null){i(new Error(`Playwright install failed: ${s.message}`));return}o()})}),!Bo.existsSync(e))throw new Error(`Playwright browser installation failed. Try running manually:
87
+ `):t}}async function jr(){let e=ei.executablePath();if(Qo.existsSync(e))return;h.info("Chromium not found. Installing via Playwright...");let t=Cc(import.meta.url),r=Zo.dirname(t.resolve("playwright/package.json")),n=Zo.join(r,"cli.js");if(await new Promise((o,i)=>{xc(process.execPath,[n,"install","chromium"],s=>{if(s!=null){i(new Error(`Playwright install failed: ${s.message}`));return}o()})}),!Qo.existsSync(e))throw new Error(`Playwright browser installation failed. Try running manually:
88
88
 
89
89
  npx playwright install chromium
90
- `);h.info("\u2713 Chromium installed")}function mc(e){return e instanceof Error?e.message.includes("Executable doesn't exist"):!1}import{mkdir as Er,writeFile as se}from"fs/promises";import Y from"path";async function kt({context:e,page:t,runId:r,stepIndex:n,stepResult:o}){try{let i=Y.join(process.cwd(),".ripplo","debug",r,"steps",String(n));await Er(i,{recursive:!0});let s={assertions:o.assertions,detail:o.detail,duration:o.duration,nodeId:o.nodeId,nodeType:o.nodeType,snapshotTimestamp:o.snapshotTimestamp,status:o.status,stepIndex:o.stepIndex,title:o.title,url:o.url};await Promise.all([se(Y.join(i,"info.json"),JSON.stringify(s,null,2)),fc({context:e,page:t,stepDir:i})])}catch(i){let s=i instanceof Error?i.message:String(i);h.warn("Failed to write step debug data for step %d: %s",n,s)}}async function fc({context:e,page:t,stepDir:r}){let[n,o,i,s]=await Promise.all([gc(t),yc(t),bc({context:e,page:t}),hc(t)]);await Promise.all([se(Y.join(r,"dom.html"),n),se(Y.join(r,"accessibility-tree.txt"),o),se(Y.join(r,"storage.json"),JSON.stringify(i,null,2)),s==null?Promise.resolve():se(Y.join(r,"screenshot.png"),s)])}async function gc(e){return await M({awaitPromise:!1,expression:"document.documentElement.outerHTML",page:e})??"(unable to capture DOM)"}async function yc(e){return yt(e,"(unable to capture accessibility tree)",async t=>{let r=await t.send("Accessibility.getFullAXTree");return JSON.stringify(r,null,2)})}async function hc(e){return yt(e,void 0,async t=>{let r=await t.send("Page.captureScreenshot",{format:"png"});return Buffer.from(r.data,"base64")})}var wc=`(() => {
90
+ `);h.info("\u2713 Chromium installed")}function Ec(e){return e instanceof Error?e.message.includes("Executable doesn't exist"):!1}import{mkdir as Nr,writeFile as ae}from"fs/promises";import X from"path";async function Ct({context:e,page:t,runId:r,stepIndex:n,stepResult:o}){try{let i=X.join(process.cwd(),".ripplo","debug",r,"steps",String(n));await Nr(i,{recursive:!0});let s={assertions:o.assertions,detail:o.detail,duration:o.duration,nodeId:o.nodeId,nodeType:o.nodeType,snapshotTimestamp:o.snapshotTimestamp,status:o.status,stepIndex:o.stepIndex,title:o.title,url:o.url};await Promise.all([ae(X.join(i,"info.json"),JSON.stringify(s,null,2)),Tc({context:e,page:t,stepDir:i})])}catch(i){let s=i instanceof Error?i.message:String(i);h.warn("Failed to write step debug data for step %d: %s",n,s)}}async function Tc({context:e,page:t,stepDir:r}){let[n,o,i,s]=await Promise.all([$c(t),Ac(t),Nc({context:e,page:t}),Ic(t)]);await Promise.all([ae(X.join(r,"dom.html"),n),ae(X.join(r,"accessibility-tree.txt"),o),ae(X.join(r,"storage.json"),JSON.stringify(i,null,2)),s==null?Promise.resolve():ae(X.join(r,"screenshot.png"),s)])}async function $c(e){return await M({awaitPromise:!1,expression:"document.documentElement.outerHTML",page:e})??"(unable to capture DOM)"}async function Ac(e){return St(e,"(unable to capture accessibility tree)",async t=>{let r=await t.send("Accessibility.getFullAXTree");return JSON.stringify(r,null,2)})}async function Ic(e){return St(e,void 0,async t=>{let r=await t.send("Page.captureScreenshot",{format:"png"});return Buffer.from(r.data,"base64")})}var jc=`(() => {
91
91
  function dump(s) {
92
92
  var out = {};
93
93
  for (var i = 0; i < s.length; i++) {
@@ -97,49 +97,49 @@ ${r}`);let o=["## Completing Your Evaluation",'When you finish your evaluation,
97
97
  return out;
98
98
  }
99
99
  return { localStorage: dump(localStorage), sessionStorage: dump(sessionStorage) };
100
- })()`;async function bc({context:e,page:t}){let[r,n]=await Promise.all([M({awaitPromise:!1,expression:wc,page:t}),e.cookies().catch(()=>[])]);return{cookies:n,localStorage:r?.localStorage??{},sessionStorage:r?.sessionStorage??{}}}async function Rt({monitor:e,runId:t,steps:r,summary:n}){try{let o=Y.join(process.cwd(),".ripplo","debug",t);await Er(o,{recursive:!0}),await Promise.all([se(Y.join(o,"summary.txt"),Sc({steps:r,summary:n})),se(Y.join(o,"console.log"),vc(e.consoleEntries)),se(Y.join(o,"network.jsonl"),kc(e.networkEntries)),se(Y.join(o,"page-errors.log"),e.pageErrors.join(`
100
+ })()`;async function Nc({context:e,page:t}){let[r,n]=await Promise.all([M({awaitPromise:!1,expression:jc,page:t}),e.cookies().catch(()=>[])]);return{cookies:n,localStorage:r?.localStorage??{},sessionStorage:r?.sessionStorage??{}}}async function Et({monitor:e,runId:t,steps:r,summary:n}){try{let o=X.join(process.cwd(),".ripplo","debug",t);await Nr(o,{recursive:!0}),await Promise.all([ae(X.join(o,"summary.txt"),Oc({steps:r,summary:n})),ae(X.join(o,"console.log"),Dc(e.consoleEntries)),ae(X.join(o,"network.jsonl"),_c(e.networkEntries)),ae(X.join(o,"page-errors.log"),e.pageErrors.join(`
101
101
  ---
102
- `))]),h.info("Debug artifacts written to .ripplo/debug/%s/",t)}catch(o){let i=o instanceof Error?o.message:String(o);h.warn("Failed to write run debug summary: %s",i)}}function Sc({steps:e,summary:t}){return[`Run ID: ${t.runId}`,`Workflow: ${t.workflowName}`,`Status: ${t.status}`,`Duration: ${String(t.duration)}ms`,`Passed: ${String(t.passCount)}`,`Failed: ${String(t.failCount)}`,"","Steps:",...e.map(n=>` [${String(n.stepIndex)}] ${n.status==="passed"?"\u2713":"\u2717"} ${n.title} (${String(n.duration)}ms) \u2014 ${n.detail??"ok"}`)].join(`
103
- `)}function vc(e){return e.map(t=>`[${new Date(t.timestamp).toISOString()}] [${t.level.toUpperCase()}] (${t.url}) ${t.text}`).join(`
104
- `)}function kc(e){return e.map(t=>JSON.stringify(t)).join(`
105
- `)}async function Go({error:e,runId:t,stack:r,workflowName:n}){try{let o=Y.join(process.cwd(),".ripplo","debug",t);await Er(o,{recursive:!0});let i=r==null?e:`${e}
102
+ `))]),h.info("Debug artifacts written to .ripplo/debug/%s/",t)}catch(o){let i=o instanceof Error?o.message:String(o);h.warn("Failed to write run debug summary: %s",i)}}function Oc({steps:e,summary:t}){return[`Run ID: ${t.runId}`,`Workflow: ${t.workflowName}`,`Status: ${t.status}`,`Duration: ${String(t.duration)}ms`,`Passed: ${String(t.passCount)}`,`Failed: ${String(t.failCount)}`,"","Steps:",...e.map(n=>` [${String(n.stepIndex)}] ${n.status==="passed"?"\u2713":"\u2717"} ${n.title} (${String(n.duration)}ms) \u2014 ${n.detail??"ok"}`)].join(`
103
+ `)}function Dc(e){return e.map(t=>`[${new Date(t.timestamp).toISOString()}] [${t.level.toUpperCase()}] (${t.url}) ${t.text}`).join(`
104
+ `)}function _c(e){return e.map(t=>JSON.stringify(t)).join(`
105
+ `)}async function ti({error:e,runId:t,stack:r,workflowName:n}){try{let o=X.join(process.cwd(),".ripplo","debug",t);await Nr(o,{recursive:!0});let i=r==null?e:`${e}
106
106
 
107
107
  ${r}`,s=[`Run ID: ${t}`,`Workflow: ${n}`,"Status: failed","",`Error: ${e}`,"",r==null?"":`Stack trace:
108
108
  ${r}`].join(`
109
- `);await Promise.all([se(Y.join(o,"error.txt"),i),se(Y.join(o,"summary.txt"),s)]),h.info("Debug error artifacts written to .ripplo/debug/%s/",t)}catch(o){let i=o instanceof Error?o.message:String(o);h.warn("Failed to write error debug artifacts: %s",i)}}import{readFileSync as Rc}from"fs";import{createRequire as Pc}from"module";import Jo from"path";import{gzipSync as xc}from"zlib";var Cc=Pc(import.meta.url),Ec=Cc.resolve("rrweb"),Tc=Jo.join(Jo.dirname(Ec),"rrweb.umd.min.cjs"),$c=Rc(Tc,"utf8"),Ac=[";(function() {"," try {"," if (window.__ripploRrwebLoaded) return;"," window.__ripploRrwebLoaded = true;"," window.__ripploRrwebBuffer = [];"," window.__ripploRrwebDrain = function() {"," var out = window.__ripploRrwebBuffer;"," window.__ripploRrwebBuffer = [];"," return out;"," };"," var r = window.rrweb;"," if (r == null || r.record == null) {"," console.warn('[ripplo] rrweb global not found');"," return;"," }"," function startRecording() {"," if (window.__ripploRrwebStartedAt != null) return;"," window.__ripploRrwebStartedAt = Date.now();"," var stop = r.record({"," emit: function(event) { window.__ripploRrwebBuffer.push(event); },"," recordCanvas: false,"," recordCrossOriginIframes: false,"," });"," window.__ripploRrwebStop = stop;"," }"," window.__ripploRrwebStart = startRecording;"," // Auto-start on every bootstrap run so agent-driven tests (which don't"," // emit a 'first step' signal before navigating) capture from the start."," startRecording();"," } catch (err) {"," console.error('[ripplo] rrweb bootstrap failed', err && err.message ? err.message : err);"," }","})();"].join(`
110
- `),Ic=$c+`
111
- `+Ac;async function Pt(e){let t,r=0;async function n(){await e.addScriptTag({content:Ic}).catch(()=>{})}await n(),e.on("load",()=>{n()});async function o(){await M({awaitPromise:!1,expression:"globalThis.__ripploRrwebStart && globalThis.__ripploRrwebStart()",page:e});let l=await M({awaitPromise:!1,expression:"globalThis.__ripploRrwebStartedAt",page:e});typeof l=="number"&&(t??=l)}function i(){if(t!=null)return Date.now()-t}async function s(){let l=await M({awaitPromise:!1,expression:"globalThis.__ripploRrwebDrain ? globalThis.__ripploRrwebDrain() : []",page:e})??[],c=l[0],d=l.at(-1);if(c==null||d==null)return;t??=c.timestamp;let u=t,f=l.map(g=>JSON.stringify(g)).join(`
112
- `),v={body:xc(Buffer.from(f,"utf8")),chunkIndex:r,endTimestamp:d.timestamp-u,eventCount:l.length,startTimestamp:c.timestamp-u};return r+=1,v}async function a(){await M({awaitPromise:!1,expression:"globalThis.__ripploRrwebStop && globalThis.__ripploRrwebStop()",page:e})}return{currentOffsetMs:i,detach:a,start:o,takeChunk:s}}async function Tr({baseUrl:e,cookies:t,executedPreconditions:r,extraVariables:n,headed:o,runId:i,serverUrl:s,spec:a,streaming:l,systemPrompt:c,token:d,workflowContext:u}){let f=await Ce({headed:o}),w=await f.newContext({baseURL:e});t.length>0&&(await w.addCookies([...t]),h.info("Injected %d cookies from preconditions",t.length));let v=await w.newPage(),g=await Pt(v);async function E(){let z=await g.takeChunk();z!=null&&l.enqueueRecordingChunk(z)}let P=setInterval(()=>{E()},2e3);await g.start();try{let z=function(ae){let Je={...ae,recordingEndMs:g.currentOffsetMs(),recordingStartMs:ae.recordingStartMs??g.currentOffsetMs()};l.enqueueStep(Je),l.flushSteps(),kt({context:w,page:v,runId:i,stepIndex:Je.stepIndex,stepResult:Je})};var L=z;let _=await Pr({baseUrl:e,executedPreconditions:r,extraVariables:n,onStep:z,page:v,runId:i,serverUrl:s,spec:a,systemPrompt:c,token:d,workflowContext:u}),F=_.verdict==="pass"?"passed":"failed";await l.complete({statusOverride:F,steps:_.steps,summary:_.findings});let ie=_.steps.filter(ae=>ae.status==="passed").length,Ae=_.steps.filter(ae=>ae.status==="failed").length,U={duration:_.steps.reduce((ae,Je)=>ae+Je.duration,0),failCount:Ae,passCount:ie,runId:i,status:F,workflowName:u.name};await Rt({monitor:_.monitor,runId:i,steps:_.steps,summary:U}),h.info("Agent test complete: %d passed, %d failed",ie,Ae),h.info(`
109
+ `);await Promise.all([ae(X.join(o,"error.txt"),i),ae(X.join(o,"summary.txt"),s)]),h.info("Debug error artifacts written to .ripplo/debug/%s/",t)}catch(o){let i=o instanceof Error?o.message:String(o);h.warn("Failed to write error debug artifacts: %s",i)}}import{readFileSync as Lc}from"fs";import{createRequire as Uc}from"module";import ri from"path";import{gzipSync as Vc}from"zlib";var Fc=Uc(import.meta.url),Mc=Fc.resolve("rrweb"),Bc=ri.join(ri.dirname(Mc),"rrweb.umd.min.cjs"),Hc=Lc(Bc,"utf8"),qc=[";(function() {"," try {"," if (window.__ripploRrwebLoaded) return;"," window.__ripploRrwebLoaded = true;"," window.__ripploRrwebBuffer = [];"," window.__ripploRrwebDrain = function() {"," var out = window.__ripploRrwebBuffer;"," window.__ripploRrwebBuffer = [];"," return out;"," };"," var r = window.rrweb;"," if (r == null || r.record == null) {"," console.warn('[ripplo] rrweb global not found');"," return;"," }"," function startRecording() {"," if (window.__ripploRrwebStartedAt != null) return;"," window.__ripploRrwebStartedAt = Date.now();"," var stop = r.record({"," emit: function(event) { window.__ripploRrwebBuffer.push(event); },"," recordCanvas: false,"," recordCrossOriginIframes: false,"," });"," window.__ripploRrwebStop = stop;"," }"," window.__ripploRrwebStart = startRecording;"," // Auto-start on every bootstrap run so agent-driven tests (which don't"," // emit a 'first step' signal before navigating) capture from the start."," startRecording();"," } catch (err) {"," console.error('[ripplo] rrweb bootstrap failed', err && err.message ? err.message : err);"," }","})();"].join(`
110
+ `),Wc=Hc+`
111
+ `+qc;async function Tt(e){let t,r=0;async function n(){await e.addScriptTag({content:Wc}).catch(()=>{})}await n(),e.on("load",()=>{n()});async function o(){await M({awaitPromise:!1,expression:"globalThis.__ripploRrwebStart && globalThis.__ripploRrwebStart()",page:e});let l=await M({awaitPromise:!1,expression:"globalThis.__ripploRrwebStartedAt",page:e});typeof l=="number"&&(t??=l)}function i(){if(t!=null)return Date.now()-t}async function s(){let l=await M({awaitPromise:!1,expression:"globalThis.__ripploRrwebDrain ? globalThis.__ripploRrwebDrain() : []",page:e})??[],c=l[0],d=l.at(-1);if(c==null||d==null)return;t??=c.timestamp;let u=t,f=l.map(g=>JSON.stringify(g)).join(`
112
+ `),v={body:Vc(Buffer.from(f,"utf8")),chunkIndex:r,endTimestamp:d.timestamp-u,eventCount:l.length,startTimestamp:c.timestamp-u};return r+=1,v}async function a(){await M({awaitPromise:!1,expression:"globalThis.__ripploRrwebStop && globalThis.__ripploRrwebStop()",page:e})}return{currentOffsetMs:i,detach:a,start:o,takeChunk:s}}async function Or({baseUrl:e,cookies:t,executedPreconditions:r,extraVariables:n,headed:o,runId:i,serverUrl:s,spec:a,streaming:l,systemPrompt:c,token:d,workflowContext:u}){let f=await Te({headed:o}),w=await f.newContext({baseURL:e});t.length>0&&(await w.addCookies([...t]),h.info("Injected %d cookies from preconditions",t.length));let v=await w.newPage(),g=await Tt(v);async function E(){let z=await g.takeChunk();z!=null&&l.enqueueRecordingChunk(z)}let P=setInterval(()=>{E()},2e3);await g.start();try{let z=function(le){let Ye={...le,recordingEndMs:g.currentOffsetMs(),recordingStartMs:le.recordingStartMs??g.currentOffsetMs()};l.enqueueStep(Ye),l.flushSteps(),Ct({context:w,page:v,runId:i,stepIndex:Ye.stepIndex,stepResult:Ye})};var _=z;let L=await Ar({baseUrl:e,executedPreconditions:r,extraVariables:n,onStep:z,page:v,runId:i,serverUrl:s,spec:a,systemPrompt:c,token:d,workflowContext:u}),F=L.verdict==="pass"?"passed":"failed";await l.complete({statusOverride:F,steps:L.steps,summary:L.findings});let se=L.steps.filter(le=>le.status==="passed").length,Ie=L.steps.filter(le=>le.status==="failed").length,U={duration:L.steps.reduce((le,Ye)=>le+Ye.duration,0),failCount:Ie,passCount:se,runId:i,status:F,workflowName:u.name};await Et({monitor:L.monitor,runId:i,steps:L.steps,summary:U}),h.info("Agent test complete: %d passed, %d failed",se,Ie),h.info(`
113
113
  === Agent Summary ===
114
- %s`,_.findings)}finally{clearInterval(P),await g.detach(),await E(),await f.close()}}async function $r({expected:e,locator:t,operator:r,timeout:n}){let o=await t.textContent({timeout:n});return Ee({actual:o??"",expected:e,label:"Text",operator:r})}async function Ar({expected:e,operator:t,page:r,timeout:n}){let o=i=>Ee({actual:i,expected:e,label:"URL",operator:t}).status==="passed";return await r.waitForURL(i=>o(i.toString()),{timeout:n}).catch(()=>{}),Ee({actual:r.url(),expected:e,label:"URL",operator:t})}async function Ko({expected:e,operator:t,page:r,timeout:n}){let o=Date.now()+n,i=async()=>Ee({actual:await r.title(),expected:e,label:"Title",operator:t}),s=await i();for(;s.status==="failed"&&Date.now()<o;)await new Promise(a=>{setTimeout(a,50)}),s=await i();return s}async function Ir({expected:e,locator:t,operator:r}){let n=await t.count();return ni({actual:n,expected:e,label:"Count",operator:r})}async function jr({expected:e,locator:t,operator:r,timeout:n}){let o=await t.inputValue({timeout:n});return Ee({actual:o,expected:e,label:"Value",operator:r})}async function Nr({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),{description:"Element is visible",detail:void 0,status:"passed"}}catch{return{description:"Element is visible",detail:"Element not visible",status:"failed"}}}async function Or({locator:e,timeout:t}){try{return await e.waitFor({state:"hidden",timeout:t}),{description:"Element is not visible",detail:void 0,status:"passed"}}catch{return{description:"Element is not visible",detail:"Element still visible",status:"failed"}}}async function Yo({attribute:e,expected:t,locator:r,operator:n,timeout:o}){let i=await r.getAttribute(e,{timeout:o});return Ee({actual:i??"",expected:t,label:`Attribute "${e}"`,operator:n})}async function Xo({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),await e.isEnabled()?{description:"Element is enabled",detail:void 0,status:"passed"}:{description:"Element is enabled",detail:"Element is disabled",status:"failed"}}catch{return{description:"Element is enabled",detail:"Element not found",status:"failed"}}}async function Qo({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),await e.isDisabled()?{description:"Element is disabled",detail:void 0,status:"passed"}:{description:"Element is disabled",detail:"Element is enabled",status:"failed"}}catch{return{description:"Element is disabled",detail:"Element not found",status:"failed"}}}async function Zo({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),await e.isChecked()?{description:"Element is checked",detail:void 0,status:"passed"}:{description:"Element is checked",detail:"Element is not checked",status:"failed"}}catch{return{description:"Element is checked",detail:"Element not found",status:"failed"}}}async function ei({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),await e.isChecked()?{description:"Element is not checked",detail:"Element is checked",status:"failed"}:{description:"Element is not checked",detail:void 0,status:"passed"}}catch{return{description:"Element is not checked",detail:"Element not found",status:"failed"}}}async function ti({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),!await e.evaluate("(el) => document.activeElement === el",void 0,{timeout:t})?{description:"Element is focused",detail:"Element is not focused",status:"failed"}:{description:"Element is focused",detail:void 0,status:"passed"}}catch{return{description:"Element is focused",detail:"Element not found",status:"failed"}}}async function ri({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),!!await e.evaluate("(el) => document.activeElement === el",void 0,{timeout:t})?{description:"Element is not focused",detail:"Element is focused",status:"failed"}:{description:"Element is not focused",detail:void 0,status:"passed"}}catch{return{description:"Element is not focused",detail:"Element not found",status:"failed"}}}function Ee(e){let t=`${e.label} ${e.operator} "${e.expected}"`,r=jc(e),n=r?void 0:`Got: "${e.actual}"`;return{description:t,detail:n,status:r?"passed":"failed"}}function jc({actual:e,expected:t,operator:r}){return r==="equals"?e===t:r==="notEquals"?e!==t:r==="contains"?e.includes(t):r==="startsWith"?e.startsWith(t):r==="endsWith"?e.endsWith(t):new RegExp(t).test(e)}function ni(e){let t=`${e.label} ${e.operator} ${String(e.expected)}`,r=Nc(e),n=r?void 0:`Got: ${String(e.actual)}`;return{description:t,detail:n,status:r?"passed":"failed"}}function Nc({actual:e,expected:t,operator:r}){return r==="equals"?e===t:r==="notEquals"?e!==t:r==="greaterThan"?e>t:r==="greaterThanOrEqual"?e>=t:r==="lessThan"?e<t:e<=t}import{readdir as Vc,rm as Fc,stat as Mc}from"fs/promises";import ak from"os";import si from"path";import{graphql as Hc}from"gql.tada";import{print as Oc}from"graphql";var Dc=15e3;async function b(e){let t=Oc(e.document),r=JSON.stringify({query:t,variables:e.variables}),n=`${e.config.ripploServerUrl}/graphql`,o;try{o=await fetch(n,{body:r,headers:{Authorization:`Bearer ${e.config.token}`,"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(Dc)})}catch(s){let a=s instanceof Error?s.message:String(s);throw new Error(`Failed to connect to Ripplo server at ${e.config.ripploServerUrl}. Make sure \`npx ripplo\` is running and your internet connection is active. Details: ${a}`)}let i=await Lc({res:o,url:n});if(!_c(i))throw new Error("Invalid GraphQL response");if(Uc(i))throw new Error(i.errors.map(s=>s.message).join(", "));if(i.data==null)throw new Error("No data returned from server");return i.data}async function Lc({res:e,url:t}){let r=await e.text();if(r.length===0)throw new Error(`Empty response from Ripplo server at ${t} (status ${String(e.status)}). The server may have restarted or the request was rejected before a body was sent.`);try{return JSON.parse(r)}catch{throw new Error(`Non-JSON response from Ripplo server at ${t} (status ${String(e.status)}): ${r.slice(0,200)}`)}}function _c(e){return typeof e=="object"&&e!=null&&("data"in e||"errors"in e)}function Uc(e){return Array.isArray(e.errors)&&e.errors.length>0}var oi=si.join(process.cwd(),".ripplo","debug"),ii=360*60*1e3,pk=Hc(`
114
+ %s`,L.findings)}finally{clearInterval(P),await g.detach(),await E(),await f.close()}}var J={};Va(J,{default:()=>zc});sr(J,yk);import*as yk from"playwright/test";import{default as zc}from"playwright/test";async function Dr({expected:e,locator:t,operator:r,timeout:n}){await rt({expected:e,operator:r,timeout:n,read:async()=>await t.textContent()??""});let o=await nt(async()=>await t.textContent()??"");return _e({actual:o,expected:e,label:"Text",operator:r})}async function _r({expected:e,operator:t,page:r,timeout:n}){return await rt({expected:e,operator:t,timeout:n,read:()=>Promise.resolve(r.url())}),_e({actual:r.url(),expected:e,label:"URL",operator:t})}async function ni({expected:e,operator:t,page:r,timeout:n}){await rt({expected:e,operator:t,timeout:n,read:()=>r.title()});let o=await nt(()=>r.title());return _e({actual:o,expected:e,label:"Title",operator:t})}async function Lr({expected:e,locator:t,operator:r,timeout:n}){await J.expect.poll(async()=>mi({actual:await t.count(),expected:e,operator:r}),{timeout:n}).toBe(!0).catch(()=>{});let o=await t.count();return pi({actual:o,expected:e,label:"Count",operator:r})}async function Ur({expected:e,locator:t,operator:r,timeout:n}){await rt({expected:e,operator:r,timeout:n,read:()=>t.inputValue()});let o=await nt(()=>t.inputValue());return _e({actual:o,expected:e,label:"Value",operator:r})}async function Vr({locator:e,timeout:t}){return Se({description:"Element is visible",failureDetail:"Element not visible",run:()=>(0,J.expect)(e).toBeVisible({timeout:t})})}async function Fr({locator:e,timeout:t}){return Se({description:"Element is not visible",failureDetail:"Element still visible",run:()=>(0,J.expect)(e).toBeHidden({timeout:t})})}async function oi({attribute:e,expected:t,locator:r,operator:n,timeout:o}){await rt({expected:t,operator:n,timeout:o,read:async()=>await r.getAttribute(e)??""});let i=await nt(async()=>await r.getAttribute(e)??"");return _e({actual:i,expected:t,label:`Attribute "${e}"`,operator:n})}async function ii({locator:e,timeout:t}){return Se({description:"Element is enabled",failureDetail:"Element is disabled or not found",run:()=>(0,J.expect)(e).toBeEnabled({timeout:t})})}async function si({locator:e,timeout:t}){return Se({description:"Element is disabled",failureDetail:"Element is enabled or not found",run:()=>(0,J.expect)(e).toBeDisabled({timeout:t})})}async function ai({locator:e,timeout:t}){return Se({description:"Element is checked",failureDetail:"Element is not checked",run:()=>(0,J.expect)(e).toBeChecked({timeout:t})})}async function li({locator:e,timeout:t}){return Se({description:"Element is not checked",failureDetail:"Element is checked",run:()=>(0,J.expect)(e).not.toBeChecked({timeout:t})})}async function ci({locator:e,timeout:t}){return Se({description:"Element is focused",failureDetail:"Element is not focused",run:()=>(0,J.expect)(e).toBeFocused({timeout:t})})}async function di({locator:e,timeout:t}){return Se({description:"Element is not focused",failureDetail:"Element is focused",run:()=>(0,J.expect)(e).not.toBeFocused({timeout:t})})}async function Se({description:e,failureDetail:t,run:r}){try{return await r(),{description:e,detail:void 0,status:"passed"}}catch{return{description:e,detail:t,status:"failed"}}}async function rt({expected:e,operator:t,read:r,timeout:n}){await J.expect.poll(async()=>{let o=await nt(r);return ui({actual:o,expected:e,operator:t})},{timeout:n}).toBe(!0).catch(()=>{})}async function nt(e){return e().catch(()=>"")}function _e(e){let t=`${e.label} ${e.operator} "${e.expected}"`,r=ui(e),n=r?void 0:`Got: "${e.actual}"`;return{description:t,detail:n,status:r?"passed":"failed"}}function ui({actual:e,expected:t,operator:r}){return r==="equals"?e===t:r==="notEquals"?e!==t:r==="contains"?e.includes(t):r==="startsWith"?e.startsWith(t):r==="endsWith"?e.endsWith(t):new RegExp(t).test(e)}function pi(e){let t=`${e.label} ${e.operator} ${String(e.expected)}`,r=mi(e),n=r?void 0:`Got: ${String(e.actual)}`;return{description:t,detail:n,status:r?"passed":"failed"}}function mi({actual:e,expected:t,operator:r}){return r==="equals"?e===t:r==="notEquals"?e!==t:r==="greaterThan"?e>t:r==="greaterThanOrEqual"?e>=t:r==="lessThan"?e<t:e<=t}import{readdir as Qc,rm as Zc,stat as ed}from"fs/promises";import Pk from"os";import yi from"path";import{graphql as td}from"gql.tada";import{print as Gc}from"graphql";var Jc=15e3;async function b(e){let t=Gc(e.document),r=JSON.stringify({query:t,variables:e.variables}),n=`${e.config.ripploServerUrl}/graphql`,o;try{o=await fetch(n,{body:r,headers:{Authorization:`Bearer ${e.config.token}`,"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(Jc)})}catch(s){let a=s instanceof Error?s.message:String(s);throw new Error(`Failed to connect to Ripplo server at ${e.config.ripploServerUrl}. Make sure \`npx ripplo\` is running and your internet connection is active. Details: ${a}`)}let i=await Kc({res:o,url:n});if(!Yc(i))throw new Error("Invalid GraphQL response");if(Xc(i))throw new Error(i.errors.map(s=>s.message).join(", "));if(i.data==null)throw new Error("No data returned from server");return i.data}async function Kc({res:e,url:t}){let r=await e.text();if(r.length===0)throw new Error(`Empty response from Ripplo server at ${t} (status ${String(e.status)}). The server may have restarted or the request was rejected before a body was sent.`);try{return JSON.parse(r)}catch{throw new Error(`Non-JSON response from Ripplo server at ${t} (status ${String(e.status)}): ${r.slice(0,200)}`)}}function Yc(e){return typeof e=="object"&&e!=null&&("data"in e||"errors"in e)}function Xc(e){return Array.isArray(e.errors)&&e.errors.length>0}var fi=yi.join(process.cwd(),".ripplo","debug"),gi=360*60*1e3,$k=td(`
115
115
  mutation RevokeCurrentCliToken {
116
116
  revokeCurrentCliToken
117
117
  }
118
- `);async function Dr({maxRuns:e}){try{let r=(await Vc(oi,{withFileTypes:!0})).filter(c=>c.isDirectory()),n=Date.now(),o=await Promise.all(r.map(async c=>{let d=si.join(oi,c.name),u=await Mc(d);return{dirPath:d,mtime:u.mtimeMs}})),i=o.filter(c=>n-c.mtime>ii),a=o.filter(c=>n-c.mtime<=ii).toSorted((c,d)=>d.mtime-c.mtime).slice(e),l=[...i,...a];if(l.length===0)return;await Promise.allSettled(l.map(c=>Fc(c.dirPath,{force:!0,recursive:!0}))),h.info("Pruned %d old debug run(s)",l.length)}catch{h.warn("Debug run pruning failed, ignoring")}}var qc=5e3;async function Lr({appUrl:e}){try{await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(qc)})}catch(t){let r=t instanceof Error?t.message:String(t);throw h.debug("App URL reachability check failed: %s",r),new Error([`Could not reach your dev server at ${e}.`,"","Troubleshooting:",` 1. Make sure your app is running at ${e}`," 2. Check RIPPLO_APP_URL in the env file declared in .ripplo/project.json"," 3. If you're in a git worktree, RIPPLO_APP_URL and RIPPLO_ENGINE_URL must point at this worktree's dev server port (not main's)"].join(`
119
- `))}}import nt from"fs";import Te from"fs";import Bc from"os";import et from"path";var Wc=".local",zc=".ripplo";function _r(e){return et.join(e,".ripplo",Wc)}function tt(e){let t=_r(e);Te.existsSync(t)||Te.mkdirSync(t,{recursive:!0});let r=et.join(t,".gitignore");return Te.existsSync(r)||Te.writeFileSync(r,`*
120
- `),t}function rt(e,t){return et.join(_r(e),t)}function Ur(){return et.join(Bc.homedir(),zc)}function Vr(){let e=Ur();return Te.existsSync(e)?Te.chmodSync(e,448):Te.mkdirSync(e,{mode:448,recursive:!0}),e}function be(e){return et.join(Ur(),e)}function ne(){let e=process.env.RIPPLO_TOKEN;if(e!=null&&e.trim().length>0)return e.trim();let t=be("token");if(!nt.existsSync(t))return null;let r=nt.readFileSync(t,"utf8").trim();return r.length===0?null:r}function Fr(e){Vr(),nt.writeFileSync(be("token"),e+`
121
- `,{mode:384})}function Mr(){let e=be("token");return nt.existsSync(e)?(nt.unlinkSync(e),!0):!1}import{z as fe}from"zod";import{z as xt}from"zod";var Gc=xt.object({__codec:xt.string().min(1),data:xt.unknown(),version:xt.number().int().positive()}),Ct=class extends Error{codec;currentVersion;gotVersion;constructor(t){super(`Unsupported ${t.codec} version ${String(t.gotVersion)} (current ${String(t.currentVersion)}). Upgrade Ripplo or rebuild with a compatible CLI.`),this.name="CodecVersionError",this.codec=t.codec,this.currentVersion=t.currentVersion,this.gotVersion=t.gotVersion}},Et=class extends Error{constructor(t){super(`Codec mismatch: expected "${t.expected}", got "${t.got}"`),this.name="CodecMismatchError"}};function Tt(e){return ai({legacy:void 0,migrators:[],name:e,schemas:[]})}function ai(e){return{initial:t=>Hr(t,{...e,schemas:[t]}),legacy:t=>ai({...e,legacy:t})}}function Hr(e,t){return{build:()=>Jc(e,t),legacy:r=>Hr(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return Hr(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function Jc(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>Kc(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function Kc(e,t,r){let{data:n,version:o}=Yc(t,r),i=li(t,n,o);return e.parse(i)}function Yc(e,t){let r=Gc.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new Et({expected:e.name,got:r.data.__codec});return{data:r.data.data,version:r.data.version}}if(e.legacy!=null&&e.legacy.detect(t))return{data:t,version:e.legacy.assumedVersion};throw new Error(`Cannot decode "${e.name}": value is not a codec envelope and no legacy detector matched.`)}function li(e,t,r){let n=e.schemas.length;if(r>n)throw new Ct({codec:e.name,currentVersion:n,gotVersion:r});if(r===n)return t;let o=e.schemas[r-1];if(o==null)throw new Error(`Codec "${e.name}" missing schema for v${String(r)}; cannot migrate.`);let i=o.parse(t),s=e.migrators[r-1];if(s==null)throw new Error(`Codec "${e.name}" missing migrator v${String(r)} \u2192 v${String(r+1)}.`);return li(e,s(i),r+1)}import{z as pi}from"zod";import{z as De}from"zod";var qr=De.object({depends:De.array(De.string().min(1)).optional().describe("Names of other preconditions that must be satisfied first. Resolved via topological sort; cycles are rejected at validation time."),description:De.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:De.array(De.string().min(1)).optional().describe("Keys that the execute response's data field will contain. e.g. ['projectId', 'workflowId']. These are used for route param interpolation ({{projectId}}) and workflow variables. Declared here so generated types are strongly typed per precondition.")}).describe("A named precondition declared at the graph level. States reference these by name.");import{z as p}from"zod";import{z as Se}from"zod";var Xc=Se.object({by:Se.literal("testId"),value:Se.string().min(1)}),Qc=Se.object({by:Se.literal("role"),name:Se.string().optional(),role:Se.string().min(1)}),T=Se.discriminatedUnion("by",[Xc,Qc]);import{z as ci}from"zod";var ve=ci.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),$t=ci.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]);import{z as O}from"zod";var Zc=O.object({type:O.literal("static"),value:O.union([O.string(),O.number(),O.boolean()])}),At=O.object({name:O.string().min(1),type:O.literal("variable")}),It=O.discriminatedUnion("type",[Zc,At]),Q=O.discriminatedUnion("type",[O.object({type:O.literal("static"),value:O.string()}),At]),jt=O.discriminatedUnion("type",[O.object({type:O.literal("static"),value:O.number().int().nonnegative()}),At]),Br=O.discriminatedUnion("type",[O.object({type:O.literal("static"),value:O.union([O.string(),O.number(),O.boolean()])}),At]);import{z as Z}from"zod";var Nt=Z.discriminatedUnion("type",[Z.object({default:Z.string().optional(),type:Z.literal("string")}),Z.object({default:Z.number().optional(),type:Z.literal("number")}),Z.object({default:Z.boolean().optional(),type:Z.literal("boolean")}),Z.object({key:Z.string().min(1),type:Z.literal("env")})]);var x={id:p.string().min(1).max(200),label:p.string().max(500).optional(),next:p.string().max(200).optional(),uiOnly:p.boolean().optional()},di=500,ed=p.object({...x,type:p.literal("goto"),url:Q}),td=p.object({...x,locator:T,type:p.literal("click")}),rd=p.object({...x,locator:T,type:p.literal("fill"),value:Q}),nd=p.object({...x,locator:T,type:p.literal("select"),value:Q}),od=p.object({...x,locator:T,type:p.literal("hover")}),id=p.object({...x,key:p.string().min(1),locator:T.optional(),type:p.literal("press")}),sd=p.object({...x,locator:T,type:p.literal("check")}),ad=p.object({...x,locator:T,type:p.literal("uncheck")}),ld=p.object({...x,height:p.number().int().positive(),type:p.literal("setViewport"),width:p.number().int().positive()}),cd=p.object({...x,message:p.string().min(1),type:p.literal("fail")}),dd=p.object({...x,type:p.literal("setVariable"),value:It,variable:p.string().min(1)}),ud=p.object({...x,locator:T,type:p.literal("extractText"),variable:p.string().min(1)}),pd=p.object({...x,files:p.array(p.string()).min(1),locator:T,type:p.literal("upload")}),md=p.object({...x,locator:T,type:p.literal("dblclick")}),fd=p.object({...x,source:T,target:T,type:p.literal("drag")}),gd=p.object({...x,locator:T,type:p.literal("scrollIntoView")}),yd=p.object({...x,locator:T,type:p.literal("type"),value:Q}),hd=p.object({...x,locator:T,type:p.literal("focus")}),wd=p.object({...x,locator:T,type:p.literal("clear")}),bd=p.object({...x,locator:T,type:p.literal("rightClick")}),Sd=p.object({...x,action:p.enum(["accept","dismiss"]),promptText:p.string().optional(),type:p.literal("handleDialog")}),vd=p.object({...x,action:p.enum(["read","write"]),type:p.literal("clipboard"),value:Q.optional(),variable:p.string().min(1).optional()}),kd=p.object({...x,permission:p.string().min(1),state:p.enum(["granted","prompt"]),type:p.literal("setPermission")}),Rd=p.object({...x,locator:T,type:p.literal("assertVisible")}),Pd=p.object({...x,locator:T,type:p.literal("assertNotVisible")}),xd=p.object({...x,expected:Q,locator:T,operator:ve,type:p.literal("assertText")}),Cd=p.object({...x,expected:Q,operator:ve,type:p.literal("assertUrl")}),Ed=p.object({...x,expected:jt,locator:T,operator:$t,type:p.literal("assertCount")}),Td=p.object({...x,expected:Q,locator:T,operator:ve,type:p.literal("assertValue")}),$d=p.object({...x,attribute:p.string().min(1),expected:Q,locator:T,operator:ve,type:p.literal("assertAttribute")}),Ad=p.object({...x,locator:T,type:p.literal("assertEnabled")}),Id=p.object({...x,locator:T,type:p.literal("assertDisabled")}),jd=p.object({...x,expected:Q,operator:ve,type:p.literal("assertTitle")}),Nd=p.object({...x,locator:T,type:p.literal("assertChecked")}),Od=p.object({...x,locator:T,type:p.literal("assertNotChecked")}),Dd=p.object({...x,locator:T,type:p.literal("assertFocused")}),Ld=p.object({...x,locator:T,type:p.literal("assertNotFocused")}),_d=p.object({...x,budget:p.enum(["fast","slow","async"]),observer:p.string().min(1).max(200),params:p.record(p.string().max(200),Br),type:p.literal("assertObserver")}),ui=p.discriminatedUnion("type",[ed,td,rd,nd,od,id,sd,ad,Rd,Pd,xd,Cd,Ed,Td,$d,Ad,Id,ld,cd,dd,ud,pd,md,fd,gd,yd,hd,wd,bd,Sd,vd,kd,jd,Nd,Od,Dd,Ld,_d]),Ot=p.object({entryNode:p.string().min(1).max(200),nodes:p.record(p.string().max(200),ui).refine(e=>Object.keys(e).length<=di,`Workflow has more than ${String(di)} nodes`),uiOnly:p.boolean().optional(),variableNamespaces:p.record(p.string().max(200),p.string().max(500)).optional(),variables:p.record(p.string().max(200),Nt).optional()});var Ud=pi.record(pi.string().max(200),qr),Vd={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},Fd={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},Wr=Tt("workflow-spec").legacy(Vd).initial(Ot).build(),Md=Tt("precondition-map").legacy(Fd).initial(Ud).build();import{z as zr}from"zod";var mi=["fast","slow","async"],Hd=zr.object({budget:zr.enum(mi).describe("Polling budget tier: fast | slow | async"),description:zr.string().min(1).describe("Human-readable description of what this observer checks")}).describe("A named backend state observer. Tests assert against it with assert.backend(observer, params). Implementation lives on the user's server.");import{graphql as _t,readFragment as Dt}from"gql.tada";import{z as oe}from"zod";import fi from"crypto";import{Webhook as qd}from"standardwebhooks";function ke({body:e,secret:t}){let r=new qd(t),n=`msg_${fi.randomUUID()}`,o=new Date,i=r.sign(n,o,e),s=Math.floor(o.getTime()/1e3);return{"webhook-id":n,"webhook-signature":i,"webhook-timestamp":String(s)}}function Gr(){return`whsec_${fi.randomBytes(24).toString("base64")}`}var Bd=15e4,Wd={async:{backoffMs:[500,1e3,2e3,5e3],timeoutMs:12e4},fast:{backoffMs:[100,250,500,1e3],timeoutMs:5e3},slow:{backoffMs:[250,500,1e3,2e3],timeoutMs:3e4}},zd=oe.discriminatedUnion("kind",[oe.object({kind:oe.literal("pass")}),oe.object({kind:oe.literal("retry"),reason:oe.string()}),oe.object({kind:oe.literal("fail"),reason:oe.string()})]),Gd=oe.object({error:oe.string().optional(),outcome:zd.optional(),success:oe.boolean()});async function gi({apiUrl:e,budget:t,observer:r,params:n,webhookSecret:o}){let i=Wd[t],s=performance.now(),a={lastReason:void 0,pollCount:0};for(;performance.now()-s<i.timeoutMs;){a.pollCount+=1;let l=await Kd({apiUrl:e,observer:r,params:n,webhookSecret:o}),c=Jd({observer:r,outcome:l,start:s,state:a});if(c!=null)return c;let d=i.timeoutMs-(performance.now()-s);if(d<=0)break;let u=Math.min(Yd({backoff:i.backoffMs,pollCount:a.pollCount}),d);await Xd(u)}return{description:`observer "${r}"`,detail:`budget "${t}" exhausted after ${String(a.pollCount)} poll(s) (${yi(s)}); last: ${a.lastReason??"no retry reason"}
122
- \u2192 /ripplo:debug \u2014 check .ripplo/debug/<runId>/ artifacts`,status:"failed"}}function Jd({observer:e,outcome:t,start:r,state:n}){return t.kind==="transport-error"?{description:`observer "${e}"`,detail:`transport error after ${String(n.pollCount)} poll(s): ${t.reason}
123
- Load \`/ripplo:setup\` skill for instructions on engine endpoint + webhook secret wiring.`,status:"failed"}:t.kind==="pass"?{description:`observer "${e}"`,detail:n.pollCount>1?`passed after ${String(n.pollCount)} polls (${yi(r)})`:void 0,status:"passed"}:t.kind==="fail"?{description:`observer "${e}"`,detail:`failed (invariant): ${t.reason} (after ${String(n.pollCount)} poll(s)) \u2014 ctx.fail stops polling immediately and is reserved for invariant violations (wrong shape, contradictory/forbidden state). For transient conditions like "not yet committed", "status not yet X", or "row not found", use ctx.retry(reason) so the runtime keeps polling until the budget expires.
124
- Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=t.reason,null)}async function Kd({apiUrl:e,observer:t,params:r,webhookSecret:n}){let o=JSON.stringify({observer:t,params:r});try{let i=await fetch(`${e}/execute-observer`,{body:o,headers:{"Content-Type":"application/json",...ke({body:o,secret:n})},method:"PUT",signal:AbortSignal.timeout(Bd)});if(!i.ok){let l=await i.text().catch(()=>"");return{kind:"transport-error",reason:`status ${String(i.status)}: ${l.slice(0,200)}`}}let s=await i.json(),a=Gd.safeParse(s);return a.success?!a.data.success||a.data.outcome==null?{kind:"transport-error",reason:a.data.error??"engine reported failure without outcome"}:a.data.outcome:{kind:"transport-error",reason:`invalid response shape: ${a.error.message}`}}catch(i){let s=i instanceof Error?i.message:String(i);return h.error("observer request failed: %s",s),{kind:"transport-error",reason:s}}}function Yd({backoff:e,pollCount:t}){let r=Math.min(t-1,e.length-1);return e[r]??1e3}function yi(e){return`${String(Math.round(performance.now()-e))}ms`}async function Xd(e){return new Promise(t=>setTimeout(t,e))}var Qd=1e4;async function Jr({failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,spec:i,variables:s}){let a=performance.now();return eu({currentId:i.entryNode,failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,runStartTime:a,spec:i,variables:s})}function Zd({onStep:e,steps:t,target:r}){t.forEach(n=>{let o={...n,stepIndex:r.length};r.push(o),e?.(o)})}async function eu({currentId:e,failFast:t,getRecordingOffsetMs:r,observerTransport:n,onStep:o,page:i,runStartTime:s,spec:a,variables:l}){let c=[],d=l,u=e;for(;u!=null;){let f=a.nodes[u];if(f==null)throw new Error(`Node "${u}" not found in spec`);let w=u,v=f.label??`${f.type} (${u})`;h.info("Executing node: %s [%s]",v,f.type);let g=await tu({getRecordingOffsetMs:r,node:f,nodeId:w,observerTransport:n,page:i,runStartTime:s,variables:d});if(Zd({onStep:o,steps:[g],target:c}),d=g.variables,t&&g.status==="failed")break;u=f.next}return{steps:c,variables:d}}async function tu({getRecordingOffsetMs:e,node:t,nodeId:r,observerTransport:n,page:o,runStartTime:i,variables:s}){let a=performance.now(),l=e?.(),c=t.label??`${t.type} (${t.id})`,d=Qd;try{let u=await ru({node:t,observerTransport:n,page:o,timeout:d,variables:s}),f=Math.round(performance.now()-a),w=u.assertions.some(g=>g.status==="failed"),v=e?.();return{assertions:u.assertions,detail:void 0,duration:f,nodeId:r,nodeType:t.type,recordingEndMs:v,recordingStartMs:l,snapshotTimestamp:Math.round(performance.now()-i),status:w?"failed":"passed",stepIndex:0,title:c,url:o.url(),variables:u.variables}}catch(u){let f=Math.round(performance.now()-a),w=u instanceof Error?u.message:String(u),v=e?.();return{assertions:[],detail:w,duration:f,nodeId:r,nodeType:t.type,recordingEndMs:v,recordingStartMs:l,snapshotTimestamp:Math.round(performance.now()-i),status:"failed",stepIndex:0,title:c,url:o.url(),variables:s}}}async function ru({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(nu(e)){let s=await pr({node:e,page:r,timeout:n,variables:o});return{assertions:[],variables:s.variables}}return{assertions:await iu({node:e,observerTransport:t,page:r,timeout:n,variables:o}),variables:o}}function nu(e){return["goto","click","dblclick","fill","select","hover","press","check","uncheck","clear","rightClick","handleDialog","clipboard","setPermission","setViewport","fail","setVariable","extractText","upload","drag","scrollIntoView","type","focus"].includes(e.type)}function ou(e){return e.type.startsWith("assert")}async function iu({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(!ou(e))throw new Error(`Unknown node type: ${e.type}`);let i=e;switch(i.type){case"assertVisible":case"assertNotVisible":case"assertEnabled":case"assertDisabled":case"assertChecked":case"assertNotChecked":case"assertFocused":case"assertNotFocused":return au({assertNode:i,page:r,timeout:n,variables:o});case"assertText":{let s=K({ref:i.expected,variables:o});return[await $r({expected:s,locator:H({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertUrl":{let s=K({ref:i.expected,variables:o});return[await Ar({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertTitle":{let s=K({ref:i.expected,variables:o});return[await Ko({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertCount":{let s=ur({ref:i.expected,variables:o});return[await Ir({expected:s,locator:H({locator:i.locator,page:r,variables:o}),operator:i.operator})]}case"assertValue":{let s=K({ref:i.expected,variables:o});return[await jr({expected:s,locator:H({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertAttribute":{let s=K({ref:i.expected,variables:o});return[await Yo({attribute:i.attribute,expected:s,locator:H({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertObserver":{if(t==null)return[{description:`observer "${i.observer}"`,detail:"observer transport not configured \u2014 set engineUrl + webhookSecret in ripplo.config",status:"failed"}];let s={};return Object.entries(i.params).forEach(([a,l])=>{s[a]=wt({ref:l,variables:o})}),[await gi({apiUrl:t.apiUrl,budget:i.budget,observer:i.observer,params:s,webhookSecret:t.webhookSecret})]}}}var su={assertChecked:Zo,assertDisabled:Qo,assertEnabled:Xo,assertFocused:ti,assertNotChecked:ei,assertNotFocused:ri,assertNotVisible:Or,assertVisible:Nr};async function au({assertNode:e,page:t,timeout:r,variables:n}){let o=su[e.type];return[await o({locator:H({locator:e.locator,page:t,variables:n}),timeout:r})]}var hi=1e4;async function Kr({baseUrl:e,browser:t,cookies:r,extraVariables:n,observerTransport:o,onRecordingChunk:i,onStep:s,runId:a,spec:l}){let c=await t.newContext({baseURL:e});c.setDefaultTimeout(hi),c.setDefaultNavigationTimeout(hi),r.length>0&&await c.addCookies(r);let d=await c.newPage(),u=Ze(d),f=await Pt(d);async function w(){let U=await f.takeChunk();U!=null&&i?.(U)}let v=setInterval(()=>{w()},2e3),g=[],E=!1;function P(U){s?.(U),E||(E=!0,f.start()),g.push(kt({context:c,page:d,runId:a,stepIndex:U.stepIndex,stepResult:U}))}let L=lu(n,l.variableNamespaces),z={...Qe({defs:l.variables}),...L},_=await Jr({failFast:!0,getRecordingOffsetMs:f.currentOffsetMs,observerTransport:o,onStep:P,page:d,spec:l,variables:z});clearInterval(v);let F=_.steps.filter(U=>U.status==="passed").length,ie=_.steps.filter(U=>U.status==="failed").length,Ae={duration:_.steps.reduce((U,ae)=>U+ae.duration,0),failCount:ie,passCount:F,runId:a,status:ie>0?"failed":"passed",workflowName:""};return await Promise.all([Promise.allSettled(g).then(()=>Rt({monitor:u,runId:a,steps:_.steps,summary:Ae})),f.detach().then(w)]),await c.close(),_.steps}function lu(e,t){if(e==null||t==null)return{};let r=new Map;Object.entries(t).forEach(([o,i])=>{r.set(i,o)});let n={};return Object.entries(e).forEach(([o,i])=>{let s=r.get(o);s!=null&&(n[s]={...n[s],...i})}),n}async function me({fn:e,label:t}){let r=performance.now(),n=await e();return h.info("%s: %dms",t,Math.round(performance.now()-r)),n}import{parseSetCookie as cu}from"set-cookie-parser";import{z as ee}from"zod";var wi=3e4,du=ee.object({data:ee.record(ee.string(),ee.record(ee.string(),ee.string())),error:ee.string().optional(),executed:ee.array(ee.string()),runId:ee.string(),success:ee.boolean()});async function Yr({project:e,webhookSecret:t,workflowSlug:r}){let n={apiUrl:void 0,cookies:[],data:{},executed:[]},o=e.workflows.find(a=>a.slug===r);if(o==null)return n;let i=e.engineBaseUrl.length===0?void 0:e.engineBaseUrl,s=o.preconditions;return s.length===0?{...n,apiUrl:i}:i==null?n:bi({apiUrl:i,preconditionNames:s,webhookSecret:t})}async function Xr({apiUrl:e,cookies:t,data:r,executed:n,webhookSecret:o}){if(n.length!==0)try{let i=JSON.stringify({data:r,preconditions:n}),s=await fetch(`${e}/teardown-preconditions`,{body:i,headers:{"Content-Type":"application/json",...fu({cookies:t}),...ke({body:i,secret:o})},method:"PUT",signal:AbortSignal.timeout(wi)});s.ok||h.error("Teardown returned %s",String(s.status))}catch{h.error("Teardown request failed")}}async function bi({apiUrl:e,preconditionNames:t,webhookSecret:r}){let n=performance.now(),o=JSON.stringify({preconditions:t}),i=await fetch(`${e}/execute-preconditions`,{body:o,headers:{"Content-Type":"application/json",...ke({body:o,secret:r})},method:"PUT",signal:AbortSignal.timeout(wi)});if(!i.ok){let c=await pu(i);throw new Error(`execute-preconditions returned ${String(i.status)}: ${c}`)}let s=await i.json(),a=du.safeParse(s);if(!a.success)throw new Error(`execute-preconditions response has invalid shape: ${a.error.message}`);if(!a.data.success){let c=a.data.error??"no error detail";throw new Error(`Precondition batch failed: ${c}`)}let l=gu({domain:new URL(e).hostname,res:i});return h.info("Preconditions resolved: %s (%dms)",a.data.executed.join(", "),Math.round(performance.now()-n)),{apiUrl:e,cookies:l,data:a.data.data,executed:a.data.executed}}var uu=ee.object({error:ee.string()});async function pu(e){let t=await e.text().catch(()=>"");if(t.length===0)return"no body";let r=mu(t),n=r==null?null:uu.safeParse(r);return n!=null&&n.success?n.data.error:t.slice(0,500)}function mu(e){try{return JSON.parse(e)}catch{return null}}function fu({cookies:e}){return e.length===0?{}:{Cookie:e.map(r=>`${r.name}=${r.value}`).join("; ")}}function gu({domain:e,res:t}){let r=t.headers.getSetCookie();return cu(r,{decodeValues:!1}).map(o=>yu({cookie:o,domain:e}))}function yu({cookie:e,domain:t}){let r={domain:e.domain??t,httpOnly:e.httpOnly??!1,name:e.name,path:e.path??"/",secure:e.secure??!1,value:e.value};return e.sameSite!=null&&(r.sameSite=wu({raw:e.sameSite})),e.expires!=null?r.expires=Math.floor(e.expires.getTime()/1e3):e.maxAge!=null&&(r.expires=Math.floor(Date.now()/1e3)+e.maxAge),r}var hu={lax:"Lax",none:"None",strict:"Strict"};function wu({raw:e}){return hu[e.toLowerCase()]??"Lax"}async function Qr({engineBaseUrl:e,preconditionNames:t,webhookSecret:r}){let n=e.length===0?void 0:e;return n==null||t.length===0?{apiUrl:n,cookies:[],data:{},executed:[]}:bi({apiUrl:n,preconditionNames:t,webhookSecret:r})}import{graphql as ot}from"gql.tada";async function Zr({agentProfileId:e,config:t,runId:r}){let n=await b({config:t,document:ku,variables:{agentProfileId:e??null,platform:"chromium",runId:r}});if(n.startRun==null)throw new Error("Failed to start run");let o=n.startRun.id,i=[];function s(d){let u=Su({config:t,runResultId:o,steps:[d]}).catch(f=>{h.error(f,"Failed to submit step %d",d.stepIndex)});i.push(u)}function a(d){let u=bu({chunk:d,config:t,runResultId:o}).catch(f=>{h.error(f,"Failed to submit recording chunk %d",d.chunkIndex)});i.push(u)}async function l(){await Promise.all(i)}async function c({statusOverride:d,steps:u,summary:f}){await me({label:`flushSteps (${String(i.length)} steps)`,fn:()=>Promise.all(i)});let w=u.filter(P=>P.status==="passed").length,v=u.filter(P=>P.status==="failed").length,g=u.reduce((P,L)=>P+L.duration,0),E=d??(v>0?"failed":"passed");await me({label:"completeRun",fn:()=>b({config:t,document:xu,variables:{duration:g,failCount:v,passCount:w,runResultId:o,status:E,summary:f??null,warnCount:0}})})}return{complete:c,enqueueRecordingChunk:a,enqueueStep:s,flushSteps:l,runResultId:o}}async function bu({chunk:e,config:t,runResultId:r}){await b({config:t,document:Pu,variables:{input:{bodyBase64:e.body.toString("base64"),chunkIndex:e.chunkIndex,endTimestamp:e.endTimestamp,eventCount:e.eventCount,runResultId:r,startTimestamp:e.startTimestamp}}})}async function Su({config:e,runResultId:t,steps:r}){let n=r.map(o=>({assertions:o.assertions.map(i=>({description:i.description,detail:i.detail,status:i.status})),detail:o.detail,duration:o.duration,nodeType:o.nodeType,recordingEndMs:o.recordingEndMs??null,recordingStartMs:o.recordingStartMs??null,snapshotTimestamp:o.snapshotTimestamp,status:o.status,stepIndex:o.stepIndex,title:o.title,url:o.url}));await b({config:e,document:Ru,variables:{runResultId:t,steps:n}})}async function en({config:e,reason:t,runId:r}){await b({config:e,document:vu,variables:{reason:t,runId:r}})}var vu=ot(`
118
+ `);async function Mr({maxRuns:e}){try{let r=(await Qc(fi,{withFileTypes:!0})).filter(c=>c.isDirectory()),n=Date.now(),o=await Promise.all(r.map(async c=>{let d=yi.join(fi,c.name),u=await ed(d);return{dirPath:d,mtime:u.mtimeMs}})),i=o.filter(c=>n-c.mtime>gi),a=o.filter(c=>n-c.mtime<=gi).toSorted((c,d)=>d.mtime-c.mtime).slice(e),l=[...i,...a];if(l.length===0)return;await Promise.allSettled(l.map(c=>Zc(c.dirPath,{force:!0,recursive:!0}))),h.info("Pruned %d old debug run(s)",l.length)}catch{h.warn("Debug run pruning failed, ignoring")}}var rd=5e3;async function Br({appUrl:e}){try{await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(rd)})}catch(t){let r=t instanceof Error?t.message:String(t);throw h.debug("App URL reachability check failed: %s",r),new Error([`Could not reach your dev server at ${e}.`,"","Troubleshooting:",` 1. Make sure your app is running at ${e}`," 2. Check RIPPLO_APP_URL in the env file declared in .ripplo/project.json"," 3. If you're in a git worktree, RIPPLO_APP_URL and RIPPLO_ENGINE_URL must point at this worktree's dev server port (not main's)"].join(`
119
+ `))}}import at from"fs";import $e from"fs";import nd from"os";import ot from"path";var od=".local",id=".ripplo";function Hr(e){return ot.join(e,".ripplo",od)}function it(e){let t=Hr(e);$e.existsSync(t)||$e.mkdirSync(t,{recursive:!0});let r=ot.join(t,".gitignore");return $e.existsSync(r)||$e.writeFileSync(r,`*
120
+ `),t}function st(e,t){return ot.join(Hr(e),t)}function qr(){return ot.join(nd.homedir(),id)}function Wr(){let e=qr();return $e.existsSync(e)?$e.chmodSync(e,448):$e.mkdirSync(e,{mode:448,recursive:!0}),e}function ve(e){return ot.join(qr(),e)}function oe(){let e=process.env.RIPPLO_TOKEN;if(e!=null&&e.trim().length>0)return e.trim();let t=ve("token");if(!at.existsSync(t))return null;let r=at.readFileSync(t,"utf8").trim();return r.length===0?null:r}function zr(e){Wr(),at.writeFileSync(ve("token"),e+`
121
+ `,{mode:384})}function Gr(){let e=ve("token");return at.existsSync(e)?(at.unlinkSync(e),!0):!1}import{z as ge}from"zod";import{z as $t}from"zod";var sd=$t.object({__codec:$t.string().min(1),data:$t.unknown(),version:$t.number().int().positive()}),At=class extends Error{codec;currentVersion;gotVersion;constructor(t){super(`Unsupported ${t.codec} version ${String(t.gotVersion)} (current ${String(t.currentVersion)}). Upgrade Ripplo or rebuild with a compatible CLI.`),this.name="CodecVersionError",this.codec=t.codec,this.currentVersion=t.currentVersion,this.gotVersion=t.gotVersion}},It=class extends Error{constructor(t){super(`Codec mismatch: expected "${t.expected}", got "${t.got}"`),this.name="CodecMismatchError"}};function jt(e){return hi({legacy:void 0,migrators:[],name:e,schemas:[]})}function hi(e){return{initial:t=>Jr(t,{...e,schemas:[t]}),legacy:t=>hi({...e,legacy:t})}}function Jr(e,t){return{build:()=>ad(e,t),legacy:r=>Jr(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return Jr(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function ad(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>ld(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function ld(e,t,r){let{data:n,version:o}=cd(t,r),i=wi(t,n,o);return e.parse(i)}function cd(e,t){let r=sd.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new It({expected:e.name,got:r.data.__codec});return{data:r.data.data,version:r.data.version}}if(e.legacy!=null&&e.legacy.detect(t))return{data:t,version:e.legacy.assumedVersion};throw new Error(`Cannot decode "${e.name}": value is not a codec envelope and no legacy detector matched.`)}function wi(e,t,r){let n=e.schemas.length;if(r>n)throw new At({codec:e.name,currentVersion:n,gotVersion:r});if(r===n)return t;let o=e.schemas[r-1];if(o==null)throw new Error(`Codec "${e.name}" missing schema for v${String(r)}; cannot migrate.`);let i=o.parse(t),s=e.migrators[r-1];if(s==null)throw new Error(`Codec "${e.name}" missing migrator v${String(r)} \u2192 v${String(r+1)}.`);return wi(e,s(i),r+1)}import{z as ki}from"zod";import{z as Le}from"zod";var Kr=Le.object({depends:Le.array(Le.string().min(1)).optional().describe("Names of other preconditions that must be satisfied first. Resolved via topological sort; cycles are rejected at validation time."),description:Le.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:Le.array(Le.string().min(1)).optional().describe("Keys that the execute response's data field will contain. e.g. ['projectId', 'workflowId']. These are used for route param interpolation ({{projectId}}) and workflow variables. Declared here so generated types are strongly typed per precondition.")}).describe("A named precondition declared at the graph level. States reference these by name.");import{z as p}from"zod";import{z as ke}from"zod";var dd=ke.object({by:ke.literal("testId"),value:ke.string().min(1)}),ud=ke.object({by:ke.literal("role"),name:ke.string().optional(),role:ke.string().min(1)}),T=ke.discriminatedUnion("by",[dd,ud]);import{z as bi}from"zod";var Re=bi.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),Nt=bi.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]);import{z as O}from"zod";var pd=O.object({type:O.literal("static"),value:O.union([O.string(),O.number(),O.boolean()])}),Ot=O.object({name:O.string().min(1),type:O.literal("variable")}),Dt=O.discriminatedUnion("type",[pd,Ot]),Z=O.discriminatedUnion("type",[O.object({type:O.literal("static"),value:O.string()}),Ot]),_t=O.discriminatedUnion("type",[O.object({type:O.literal("static"),value:O.number().int().nonnegative()}),Ot]),Yr=O.discriminatedUnion("type",[O.object({type:O.literal("static"),value:O.union([O.string(),O.number(),O.boolean()])}),Ot]);import{z as ee}from"zod";var Lt=ee.discriminatedUnion("type",[ee.object({default:ee.string().optional(),type:ee.literal("string")}),ee.object({default:ee.number().optional(),type:ee.literal("number")}),ee.object({default:ee.boolean().optional(),type:ee.literal("boolean")}),ee.object({key:ee.string().min(1),type:ee.literal("env")})]);var x={id:p.string().min(1).max(200),label:p.string().max(500).optional(),next:p.string().max(200).optional(),uiOnly:p.boolean().optional()},Si=500,md=p.object({...x,type:p.literal("goto"),url:Z}),fd=p.object({...x,locator:T,type:p.literal("click")}),gd=p.object({...x,locator:T,type:p.literal("fill"),value:Z}),yd=p.object({...x,locator:T,type:p.literal("select"),value:Z}),hd=p.object({...x,locator:T,type:p.literal("hover")}),wd=p.object({...x,key:p.string().min(1),locator:T.optional(),type:p.literal("press")}),bd=p.object({...x,locator:T,type:p.literal("check")}),Sd=p.object({...x,locator:T,type:p.literal("uncheck")}),vd=p.object({...x,height:p.number().int().positive(),type:p.literal("setViewport"),width:p.number().int().positive()}),kd=p.object({...x,message:p.string().min(1),type:p.literal("fail")}),Rd=p.object({...x,type:p.literal("setVariable"),value:Dt,variable:p.string().min(1)}),Pd=p.object({...x,locator:T,type:p.literal("extractText"),variable:p.string().min(1)}),xd=p.object({...x,files:p.array(p.string()).min(1),locator:T,type:p.literal("upload")}),Cd=p.object({...x,locator:T,type:p.literal("dblclick")}),Ed=p.object({...x,source:T,target:T,type:p.literal("drag")}),Td=p.object({...x,locator:T,type:p.literal("scrollIntoView")}),$d=p.object({...x,locator:T,type:p.literal("type"),value:Z}),Ad=p.object({...x,locator:T,type:p.literal("focus")}),Id=p.object({...x,locator:T,type:p.literal("clear")}),jd=p.object({...x,locator:T,type:p.literal("rightClick")}),Nd=p.object({...x,action:p.enum(["accept","dismiss"]),promptText:p.string().optional(),type:p.literal("handleDialog")}),Od=p.object({...x,action:p.enum(["read","write"]),type:p.literal("clipboard"),value:Z.optional(),variable:p.string().min(1).optional()}),Dd=p.object({...x,permission:p.string().min(1),state:p.enum(["granted","prompt"]),type:p.literal("setPermission")}),_d=p.object({...x,locator:T,type:p.literal("assertVisible")}),Ld=p.object({...x,locator:T,type:p.literal("assertNotVisible")}),Ud=p.object({...x,expected:Z,locator:T,operator:Re,type:p.literal("assertText")}),Vd=p.object({...x,expected:Z,operator:Re,type:p.literal("assertUrl")}),Fd=p.object({...x,expected:_t,locator:T,operator:Nt,type:p.literal("assertCount")}),Md=p.object({...x,expected:Z,locator:T,operator:Re,type:p.literal("assertValue")}),Bd=p.object({...x,attribute:p.string().min(1),expected:Z,locator:T,operator:Re,type:p.literal("assertAttribute")}),Hd=p.object({...x,locator:T,type:p.literal("assertEnabled")}),qd=p.object({...x,locator:T,type:p.literal("assertDisabled")}),Wd=p.object({...x,expected:Z,operator:Re,type:p.literal("assertTitle")}),zd=p.object({...x,locator:T,type:p.literal("assertChecked")}),Gd=p.object({...x,locator:T,type:p.literal("assertNotChecked")}),Jd=p.object({...x,locator:T,type:p.literal("assertFocused")}),Kd=p.object({...x,locator:T,type:p.literal("assertNotFocused")}),Yd=p.object({...x,budget:p.enum(["fast","slow","async"]),observer:p.string().min(1).max(200),params:p.record(p.string().max(200),Yr),type:p.literal("assertObserver")}),vi=p.discriminatedUnion("type",[md,fd,gd,yd,hd,wd,bd,Sd,_d,Ld,Ud,Vd,Fd,Md,Bd,Hd,qd,vd,kd,Rd,Pd,xd,Cd,Ed,Td,$d,Ad,Id,jd,Nd,Od,Dd,Wd,zd,Gd,Jd,Kd,Yd]),Ut=p.object({entryNode:p.string().min(1).max(200),nodes:p.record(p.string().max(200),vi).refine(e=>Object.keys(e).length<=Si,`Workflow has more than ${String(Si)} nodes`),uiOnly:p.boolean().optional(),variableNamespaces:p.record(p.string().max(200),p.string().max(500)).optional(),variables:p.record(p.string().max(200),Lt).optional()});var Xd=ki.record(ki.string().max(200),Kr),Qd={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},Zd={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},Xr=jt("workflow-spec").legacy(Qd).initial(Ut).build(),eu=jt("precondition-map").legacy(Zd).initial(Xd).build();import{z as Qr}from"zod";var Ri=["fast","slow","async"],tu=Qr.object({budget:Qr.enum(Ri).describe("Polling budget tier: fast | slow | async"),description:Qr.string().min(1).describe("Human-readable description of what this observer checks")}).describe("A named backend state observer. Tests assert against it with assert.backend(observer, params). Implementation lives on the user's server.");import{graphql as Mt,readFragment as Vt}from"gql.tada";import{z as ie}from"zod";import Pi from"crypto";import{Webhook as ru}from"standardwebhooks";function Pe({body:e,secret:t}){let r=new ru(t),n=`msg_${Pi.randomUUID()}`,o=new Date,i=r.sign(n,o,e),s=Math.floor(o.getTime()/1e3);return{"webhook-id":n,"webhook-signature":i,"webhook-timestamp":String(s)}}function Zr(){return`whsec_${Pi.randomBytes(24).toString("base64")}`}var nu=15e4,ou={async:{backoffMs:[500,1e3,2e3,5e3],timeoutMs:12e4},fast:{backoffMs:[100,250,500,1e3],timeoutMs:5e3},slow:{backoffMs:[250,500,1e3,2e3],timeoutMs:3e4}},iu=ie.discriminatedUnion("kind",[ie.object({kind:ie.literal("pass")}),ie.object({kind:ie.literal("retry"),reason:ie.string()}),ie.object({kind:ie.literal("fail"),reason:ie.string()})]),su=ie.object({error:ie.string().optional(),outcome:iu.optional(),success:ie.boolean()});async function xi({apiUrl:e,budget:t,observer:r,params:n,webhookSecret:o}){let i=ou[t],s=performance.now(),a={lastReason:void 0,pollCount:0};for(;performance.now()-s<i.timeoutMs;){a.pollCount+=1;let l=await lu({apiUrl:e,observer:r,params:n,webhookSecret:o}),c=au({observer:r,outcome:l,start:s,state:a});if(c!=null)return c;let d=i.timeoutMs-(performance.now()-s);if(d<=0)break;let u=Math.min(cu({backoff:i.backoffMs,pollCount:a.pollCount}),d);await du(u)}return{description:`observer "${r}"`,detail:`budget "${t}" exhausted after ${String(a.pollCount)} poll(s) (${Ci(s)}); last: ${a.lastReason??"no retry reason"}
122
+ \u2192 /ripplo:debug \u2014 check .ripplo/debug/<runId>/ artifacts`,status:"failed"}}function au({observer:e,outcome:t,start:r,state:n}){return t.kind==="transport-error"?{description:`observer "${e}"`,detail:`transport error after ${String(n.pollCount)} poll(s): ${t.reason}
123
+ Load \`/ripplo:setup\` skill for instructions on engine endpoint + webhook secret wiring.`,status:"failed"}:t.kind==="pass"?{description:`observer "${e}"`,detail:n.pollCount>1?`passed after ${String(n.pollCount)} polls (${Ci(r)})`:void 0,status:"passed"}:t.kind==="fail"?{description:`observer "${e}"`,detail:`failed (invariant): ${t.reason} (after ${String(n.pollCount)} poll(s)) \u2014 ctx.fail stops polling immediately and is reserved for invariant violations (wrong shape, contradictory/forbidden state). For transient conditions like "not yet committed", "status not yet X", or "row not found", use ctx.retry(reason) so the runtime keeps polling until the budget expires.
124
+ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=t.reason,null)}async function lu({apiUrl:e,observer:t,params:r,webhookSecret:n}){let o=JSON.stringify({observer:t,params:r});try{let i=await fetch(`${e}/execute-observer`,{body:o,headers:{"Content-Type":"application/json",...Pe({body:o,secret:n})},method:"PUT",signal:AbortSignal.timeout(nu)});if(!i.ok){let l=await i.text().catch(()=>"");return{kind:"transport-error",reason:`status ${String(i.status)}: ${l.slice(0,200)}`}}let s=await i.json(),a=su.safeParse(s);return a.success?!a.data.success||a.data.outcome==null?{kind:"transport-error",reason:a.data.error??"engine reported failure without outcome"}:a.data.outcome:{kind:"transport-error",reason:`invalid response shape: ${a.error.message}`}}catch(i){let s=i instanceof Error?i.message:String(i);return h.error("observer request failed: %s",s),{kind:"transport-error",reason:s}}}function cu({backoff:e,pollCount:t}){let r=Math.min(t-1,e.length-1);return e[r]??1e3}function Ci(e){return`${String(Math.round(performance.now()-e))}ms`}async function du(e){return new Promise(t=>setTimeout(t,e))}var uu=1e4;async function en({failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,spec:i,variables:s}){let a=performance.now();return mu({currentId:i.entryNode,failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,runStartTime:a,spec:i,variables:s})}function pu({onStep:e,steps:t,target:r}){t.forEach(n=>{let o={...n,stepIndex:r.length};r.push(o),e?.(o)})}async function mu({currentId:e,failFast:t,getRecordingOffsetMs:r,observerTransport:n,onStep:o,page:i,runStartTime:s,spec:a,variables:l}){let c=[],d=l,u=e;for(;u!=null;){let f=a.nodes[u];if(f==null)throw new Error(`Node "${u}" not found in spec`);let w=u,v=f.label??`${f.type} (${u})`;h.info("Executing node: %s [%s]",v,f.type);let g=await fu({getRecordingOffsetMs:r,node:f,nodeId:w,observerTransport:n,page:i,runStartTime:s,variables:d});if(pu({onStep:o,steps:[g],target:c}),d=g.variables,t&&g.status==="failed")break;u=f.next}return{steps:c,variables:d}}async function fu({getRecordingOffsetMs:e,node:t,nodeId:r,observerTransport:n,page:o,runStartTime:i,variables:s}){let a=performance.now(),l=e?.(),c=t.label??`${t.type} (${t.id})`,d=uu;try{let u=await gu({node:t,observerTransport:n,page:o,timeout:d,variables:s}),f=Math.round(performance.now()-a),w=u.assertions.some(g=>g.status==="failed"),v=e?.();return{assertions:u.assertions,detail:void 0,duration:f,nodeId:r,nodeType:t.type,recordingEndMs:v,recordingStartMs:l,snapshotTimestamp:Math.round(performance.now()-i),status:w?"failed":"passed",stepIndex:0,title:c,url:o.url(),variables:u.variables}}catch(u){let f=Math.round(performance.now()-a),w=u instanceof Error?u.message:String(u),v=e?.();return{assertions:[],detail:w,duration:f,nodeId:r,nodeType:t.type,recordingEndMs:v,recordingStartMs:l,snapshotTimestamp:Math.round(performance.now()-i),status:"failed",stepIndex:0,title:c,url:o.url(),variables:s}}}async function gu({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(yu(e)){let s=await wr({node:e,page:r,timeout:n,variables:o});return{assertions:[],variables:s.variables}}return{assertions:await wu({node:e,observerTransport:t,page:r,timeout:n,variables:o}),variables:o}}function yu(e){return["goto","click","dblclick","fill","select","hover","press","check","uncheck","clear","rightClick","handleDialog","clipboard","setPermission","setViewport","fail","setVariable","extractText","upload","drag","scrollIntoView","type","focus"].includes(e.type)}function hu(e){return e.type.startsWith("assert")}async function wu({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(!hu(e))throw new Error(`Unknown node type: ${e.type}`);let i=e;switch(i.type){case"assertVisible":case"assertNotVisible":case"assertEnabled":case"assertDisabled":case"assertChecked":case"assertNotChecked":case"assertFocused":case"assertNotFocused":return Su({assertNode:i,page:r,timeout:n,variables:o});case"assertText":{let s=Y({ref:i.expected,variables:o});return[await Dr({expected:s,locator:B({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertUrl":{let s=Y({ref:i.expected,variables:o});return[await _r({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertTitle":{let s=Y({ref:i.expected,variables:o});return[await ni({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertCount":{let s=hr({ref:i.expected,variables:o});return[await Lr({expected:s,locator:B({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertValue":{let s=Y({ref:i.expected,variables:o});return[await Ur({expected:s,locator:B({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertAttribute":{let s=Y({ref:i.expected,variables:o});return[await oi({attribute:i.attribute,expected:s,locator:B({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertObserver":{if(t==null)return[{description:`observer "${i.observer}"`,detail:"observer transport not configured \u2014 set engineUrl + webhookSecret in ripplo.config",status:"failed"}];let s={};return Object.entries(i.params).forEach(([a,l])=>{s[a]=kt({ref:l,variables:o})}),[await xi({apiUrl:t.apiUrl,budget:i.budget,observer:i.observer,params:s,webhookSecret:t.webhookSecret})]}}}var bu={assertChecked:ai,assertDisabled:si,assertEnabled:ii,assertFocused:ci,assertNotChecked:li,assertNotFocused:di,assertNotVisible:Fr,assertVisible:Vr};async function Su({assertNode:e,page:t,timeout:r,variables:n}){let o=bu[e.type];return[await o({locator:B({locator:e.locator,page:t,variables:n}),timeout:r})]}var Ei=1e4;async function tn({baseUrl:e,browser:t,cookies:r,extraVariables:n,observerTransport:o,onRecordingChunk:i,onStep:s,runId:a,spec:l}){let c=await t.newContext({baseURL:e});c.setDefaultTimeout(Ei),c.setDefaultNavigationTimeout(Ei),r.length>0&&await c.addCookies(r);let d=await c.newPage(),u=tt(d),f=await Tt(d);async function w(){let U=await f.takeChunk();U!=null&&i?.(U)}let v=setInterval(()=>{w()},2e3),g=[],E=!1;function P(U){s?.(U),E||(E=!0,f.start()),g.push(Ct({context:c,page:d,runId:a,stepIndex:U.stepIndex,stepResult:U}))}let _=vu(n,l.variableNamespaces),z={...et({defs:l.variables}),..._},L=await en({failFast:!0,getRecordingOffsetMs:f.currentOffsetMs,observerTransport:o,onStep:P,page:d,spec:l,variables:z});clearInterval(v);let F=L.steps.filter(U=>U.status==="passed").length,se=L.steps.filter(U=>U.status==="failed").length,Ie={duration:L.steps.reduce((U,le)=>U+le.duration,0),failCount:se,passCount:F,runId:a,status:se>0?"failed":"passed",workflowName:""};return await Promise.all([Promise.allSettled(g).then(()=>Et({monitor:u,runId:a,steps:L.steps,summary:Ie})),f.detach().then(w)]),await c.close(),L.steps}function vu(e,t){if(e==null||t==null)return{};let r=new Map;Object.entries(t).forEach(([o,i])=>{r.set(i,o)});let n={};return Object.entries(e).forEach(([o,i])=>{let s=r.get(o);s!=null&&(n[s]={...n[s],...i})}),n}async function fe({fn:e,label:t}){let r=performance.now(),n=await e();return h.info("%s: %dms",t,Math.round(performance.now()-r)),n}import{parseSetCookie as ku}from"set-cookie-parser";import{z as te}from"zod";var Ti=3e4,Ru=te.object({data:te.record(te.string(),te.record(te.string(),te.string())),error:te.string().optional(),executed:te.array(te.string()),runId:te.string(),success:te.boolean()});async function rn({project:e,webhookSecret:t,workflowSlug:r}){let n={apiUrl:void 0,cookies:[],data:{},executed:[]},o=e.workflows.find(a=>a.slug===r);if(o==null)return n;let i=e.engineBaseUrl.length===0?void 0:e.engineBaseUrl,s=o.preconditions;return s.length===0?{...n,apiUrl:i}:i==null?n:$i({apiUrl:i,preconditionNames:s,webhookSecret:t})}async function nn({apiUrl:e,cookies:t,data:r,executed:n,webhookSecret:o}){if(n.length!==0)try{let i=JSON.stringify({data:r,preconditions:n}),s=await fetch(`${e}/teardown-preconditions`,{body:i,headers:{"Content-Type":"application/json",...Eu({cookies:t}),...Pe({body:i,secret:o})},method:"PUT",signal:AbortSignal.timeout(Ti)});s.ok||h.error("Teardown returned %s",String(s.status))}catch{h.error("Teardown request failed")}}async function $i({apiUrl:e,preconditionNames:t,webhookSecret:r}){let n=performance.now(),o=JSON.stringify({preconditions:t}),i=await fetch(`${e}/execute-preconditions`,{body:o,headers:{"Content-Type":"application/json",...Pe({body:o,secret:r})},method:"PUT",signal:AbortSignal.timeout(Ti)});if(!i.ok){let c=await xu(i);throw new Error(`execute-preconditions returned ${String(i.status)}: ${c}`)}let s=await i.json(),a=Ru.safeParse(s);if(!a.success)throw new Error(`execute-preconditions response has invalid shape: ${a.error.message}`);if(!a.data.success){let c=a.data.error??"no error detail";throw new Error(`Precondition batch failed: ${c}`)}let l=Tu({domain:new URL(e).hostname,res:i});return h.info("Preconditions resolved: %s (%dms)",a.data.executed.join(", "),Math.round(performance.now()-n)),{apiUrl:e,cookies:l,data:a.data.data,executed:a.data.executed}}var Pu=te.object({error:te.string()});async function xu(e){let t=await e.text().catch(()=>"");if(t.length===0)return"no body";let r=Cu(t),n=r==null?null:Pu.safeParse(r);return n!=null&&n.success?n.data.error:t.slice(0,500)}function Cu(e){try{return JSON.parse(e)}catch{return null}}function Eu({cookies:e}){return e.length===0?{}:{Cookie:e.map(r=>`${r.name}=${r.value}`).join("; ")}}function Tu({domain:e,res:t}){let r=t.headers.getSetCookie();return ku(r,{decodeValues:!1}).map(o=>$u({cookie:o,domain:e}))}function $u({cookie:e,domain:t}){let r={domain:e.domain??t,httpOnly:e.httpOnly??!1,name:e.name,path:e.path??"/",secure:e.secure??!1,value:e.value};return e.sameSite!=null&&(r.sameSite=Iu({raw:e.sameSite})),e.expires!=null?r.expires=Math.floor(e.expires.getTime()/1e3):e.maxAge!=null&&(r.expires=Math.floor(Date.now()/1e3)+e.maxAge),r}var Au={lax:"Lax",none:"None",strict:"Strict"};function Iu({raw:e}){return Au[e.toLowerCase()]??"Lax"}async function on({engineBaseUrl:e,preconditionNames:t,webhookSecret:r}){let n=e.length===0?void 0:e;return n==null||t.length===0?{apiUrl:n,cookies:[],data:{},executed:[]}:$i({apiUrl:n,preconditionNames:t,webhookSecret:r})}import{graphql as lt}from"gql.tada";async function sn({agentProfileId:e,config:t,runId:r}){let n=await b({config:t,document:Du,variables:{agentProfileId:e??null,platform:"chromium",runId:r}});if(n.startRun==null)throw new Error("Failed to start run");let o=n.startRun.id,i=[];function s(d){let u=Nu({config:t,runResultId:o,steps:[d]}).catch(f=>{h.error(f,"Failed to submit step %d",d.stepIndex)});i.push(u)}function a(d){let u=ju({chunk:d,config:t,runResultId:o}).catch(f=>{h.error(f,"Failed to submit recording chunk %d",d.chunkIndex)});i.push(u)}async function l(){await Promise.all(i)}async function c({statusOverride:d,steps:u,summary:f}){await fe({label:`flushSteps (${String(i.length)} steps)`,fn:()=>Promise.all(i)});let w=u.filter(P=>P.status==="passed").length,v=u.filter(P=>P.status==="failed").length,g=u.reduce((P,_)=>P+_.duration,0),E=d??(v>0?"failed":"passed");await fe({label:"completeRun",fn:()=>b({config:t,document:Uu,variables:{duration:g,failCount:v,passCount:w,runResultId:o,status:E,summary:f??null,warnCount:0}})})}return{complete:c,enqueueRecordingChunk:a,enqueueStep:s,flushSteps:l,runResultId:o}}async function ju({chunk:e,config:t,runResultId:r}){await b({config:t,document:Lu,variables:{input:{bodyBase64:e.body.toString("base64"),chunkIndex:e.chunkIndex,endTimestamp:e.endTimestamp,eventCount:e.eventCount,runResultId:r,startTimestamp:e.startTimestamp}}})}async function Nu({config:e,runResultId:t,steps:r}){let n=r.map(o=>({assertions:o.assertions.map(i=>({description:i.description,detail:i.detail,status:i.status})),detail:o.detail,duration:o.duration,nodeType:o.nodeType,recordingEndMs:o.recordingEndMs??null,recordingStartMs:o.recordingStartMs??null,snapshotTimestamp:o.snapshotTimestamp,status:o.status,stepIndex:o.stepIndex,title:o.title,url:o.url}));await b({config:e,document:_u,variables:{runResultId:t,steps:n}})}async function an({config:e,reason:t,runId:r}){await b({config:e,document:Ou,variables:{reason:t,runId:r}})}var Ou=lt(`
125
125
  mutation FailRunCLI($runId: String!, $reason: String!) {
126
126
  failRun(runId: $runId, reason: $reason)
127
127
  }
128
- `),ku=ot(`
128
+ `),Du=lt(`
129
129
  mutation StartRunCLI($runId: String!, $platform: String!, $agentProfileId: String) {
130
130
  startRun(runId: $runId, platform: $platform, agentProfileId: $agentProfileId) {
131
131
  id
132
132
  }
133
133
  }
134
- `),Ru=ot(`
134
+ `),_u=lt(`
135
135
  mutation SubmitRunStepsCLI($runResultId: String!, $steps: [StepInput!]!) {
136
136
  submitRunSteps(runResultId: $runResultId, steps: $steps)
137
137
  }
138
- `),Pu=ot(`
138
+ `),Lu=lt(`
139
139
  mutation SubmitRunRecordingChunkCLI($input: SubmitRunRecordingChunkInput!) {
140
140
  submitRunRecordingChunk(input: $input)
141
141
  }
142
- `),xu=ot(`
142
+ `),Uu=lt(`
143
143
  mutation CompleteRunCLI(
144
144
  $runResultId: String!
145
145
  $status: String!
@@ -162,7 +162,7 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
162
162
  status
163
163
  }
164
164
  }
165
- `);var Cu=12e4,Lt=_t(`
165
+ `);var Vu=12e4,Ft=Mt(`
166
166
  fragment WorkflowRun on Workflow {
167
167
  id
168
168
  slug
@@ -174,7 +174,7 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
174
174
  preconditionName
175
175
  }
176
176
  }
177
- `),Si=_t(`
177
+ `),Ai=Mt(`
178
178
  fragment ProjectRun on Project {
179
179
  id
180
180
  cloudBaseUrl
@@ -183,13 +183,13 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
183
183
  ...WorkflowRun
184
184
  }
185
185
  }
186
- `,[Lt]),Eu=_t(`
186
+ `,[Ft]),Fu=Mt(`
187
187
  query ProjectRun($projectId: String!) {
188
188
  project(id: $projectId) {
189
189
  ...ProjectRun
190
190
  }
191
191
  }
192
- `,[Si]),Tu=_t(`
192
+ `,[Ai]),Mu=Mt(`
193
193
  query AgentProfileRun($id: String!) {
194
194
  agentProfile(id: $id) {
195
195
  id
@@ -199,30 +199,30 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
199
199
  successCriteria
200
200
  }
201
201
  }
202
- `);async function tn({agentProfileDescription:e,agentProfileId:t,baseUrl:r,browser:n,config:o,headed:i,preconditionNames:s,runId:a,webhookSecret:l,workflowId:c}){let d="unknown",u,f,w=!1;try{w=n==null,f=$u({externalBrowser:n,headed:i});let v=s==null?void 0:Qr({engineBaseUrl:o.engineUrl,preconditionNames:s,webhookSecret:l}),[{project:g,workflow:E},P]=await Promise.all([me({label:"Run context resolved",fn:()=>Lu({config:o,workflowId:c})}),me({label:"Streaming run started",fn:()=>Zr({agentProfileId:t,config:o,runId:a})}),Lr({appUrl:r})]);d=E.name,u=P;let L=Uu(E.spec);h.info("Executing workflow: %s",E.name),await Mu(Iu({agentProfileDescription:e,agentProfileId:t,baseUrl:r,browserPromise:f,config:o,headed:i,ownsBrowser:w,preconditionPromise:v,project:g,runId:a,specData:L,streaming:u,webhookSecret:l,workflow:E}),Fu())}catch(v){throw await Au({browserPromise:f,config:o,error:v,ownsBrowser:w,runId:a,streaming:u,workflowName:d}),v}}function $u({externalBrowser:e,headed:t}){return e!=null?Promise.resolve(e):me({label:"Browser launched",fn:()=>Ce({headed:t})})}async function Au({browserPromise:e,config:t,error:r,ownsBrowser:n,runId:o,streaming:i,workflowName:s}){let a=r instanceof Error?r.message:String(r),l=r instanceof Error?r.stack:void 0;await Go({error:a,runId:o,stack:l,workflowName:s}),i==null?await en({config:t,reason:a,runId:o}).catch(()=>{}):await i.complete({statusOverride:"failed",steps:[],summary:a}).catch(()=>{}),n&&e!=null&&await(await e.catch(()=>{}))?.close()}async function Iu({agentProfileDescription:e,agentProfileId:t,baseUrl:r,browserPromise:n,config:o,headed:i,ownsBrowser:s,preconditionPromise:a,project:l,runId:c,specData:d,streaming:u,webhookSecret:f,workflow:w}){let v=a??Yr({project:Ou(l),webhookSecret:f,workflowSlug:w.slug}),[g,E]=await Promise.all([v,n]);if(t!=null){s&&await E.close(),await ju({agentProfileDescription:e,agentProfileId:t,baseUrl:r,config:o,headed:i,preconditionResult:g,runId:c,specData:d,streaming:u,webhookSecret:f,workflow:w});return}await Du({baseUrl:r,browser:E,preconditionResult:g,runId:c,specData:d,streaming:u,webhookSecret:f})}async function ju({agentProfileDescription:e,agentProfileId:t,baseUrl:r,config:n,headed:o,preconditionResult:i,runId:s,specData:a,streaming:l,webhookSecret:c,workflow:d}){let u=e!=null&&e.length>0?e:await _u({config:n,profileId:t});await Tr({baseUrl:r,cookies:i.cookies,executedPreconditions:i.executed,extraVariables:i.data,headed:o,runId:s,serverUrl:n.ripploServerUrl,spec:a,streaming:l,systemPrompt:u,token:n.token,workflowContext:{description:d.name,expectedOutcome:d.name,name:d.name}}),await vi({preconditionResult:i,webhookSecret:c})}var Nu=fe.object({preconditions:fe.array(fe.string()),requiresKeys:fe.array(fe.object({namespace:fe.string(),preconditionName:fe.string()})),slug:fe.string()});function Ou(e){let t=(e.workflows??[]).map(r=>{let n=Dt(Lt,r);return Nu.parse(n)});return{engineBaseUrl:e.engineBaseUrl,workflows:t}}async function Du({baseUrl:e,browser:t,preconditionResult:r,runId:n,specData:o,streaming:i,webhookSecret:s}){let a=await me({label:"Spec executed",fn:()=>Kr({baseUrl:e,browser:t,cookies:r.cookies,extraVariables:r.data,observerTransport:r.apiUrl==null?void 0:{apiUrl:r.apiUrl,webhookSecret:s},onRecordingChunk:i.enqueueRecordingChunk,onStep:i.enqueueStep,runId:n,spec:o})});await vi({preconditionResult:r,webhookSecret:s}),await i.complete({statusOverride:void 0,steps:a,summary:void 0});let l=a.filter(d=>d.status==="passed").length,c=a.filter(d=>d.status==="failed").length;h.info("Run complete: %d passed, %d failed",l,c)}async function vi({preconditionResult:e,webhookSecret:t}){e.apiUrl!=null&&await Xr({apiUrl:e.apiUrl,cookies:e.cookies,data:e.data,executed:e.executed,webhookSecret:t})}async function Lu({config:e,workflowId:t}){let r=await b({config:e,document:Eu,variables:{projectId:e.projectId}});if(r.project==null)throw new Error("Project not found");let o={...Dt(Si,r.project),...e.engineUrl.length>0?{engineBaseUrl:e.engineUrl}:{}},s=(o.workflows??[]).find(l=>Dt(Lt,l).id===t);if(s==null)throw new Error(`Workflow ${t} not found`);let a=Dt(Lt,s);return{project:o,workflow:a}}async function _u({config:e,profileId:t}){let r=await b({config:e,document:Tu,variables:{id:t}});if(r.agentProfile==null)throw new Error(`Agent profile not found: ${t}`);let n=r.agentProfile,o=n.description;if(o==null||o.length===0)throw new Error(`Agent profile "${n.name}" has no description`);return h.info("Using agent profile: %s",n.name),xr({description:o,output:n.output??void 0,successCriteria:n.successCriteria??void 0})}function Uu(e){if(e==null)throw new Error("Workflow has no spec");return Wr.decode(e)}var Vu=fe.coerce.number().int().positive().catch(Cu);function Fu(){return Vu.parse(process.env.RIPPLO_RUN_TIMEOUT_MS)}async function Mu(e,t){let r,n=new Promise((o,i)=>{r=setTimeout(()=>{i(new Error(`Run timed out after ${String(t)}ms`))},t)});try{await Promise.race([e,n])}finally{r!=null&&clearTimeout(r)}}import{exec as zu}from"child_process";import{createAuthClient as Hu}from"better-auth/client";import{deviceAuthorizationClient as qu}from"better-auth/client/plugins";function ki({baseURL:e}){return Hu({baseURL:e,fetchOptions:{headers:{"User-Agent":"Ripplo CLI"}},plugins:[qu()]})}import{z as Ri}from"zod";var Bu="https://ripplo.ai";function ge(){return rn().RIPPLO_SERVER_URL}var Wu=Ri.object({RIPPLO_SERVER_URL:Ri.string().min(1).default(Bu)}),Pi;function rn(){return Pi??=Wu.parse(process.env),Pi}var Gu=5e3,xi="ripplo-cli";async function Ci({onDeviceCode:e,url:t}){let r=t??rn().RIPPLO_SERVER_URL,n=ki({baseURL:r}),o=await n.device.code({client_id:xi});if(o.error!=null)throw new Error(`Failed to request device code: ${o.error.error_description}`);let{device_code:i,user_code:s,verification_uri_complete:a}=o.data;e({userCode:s,verificationUrl:a}),Zu(a);let l=await Ju({authClient:n,deviceCode:i});return Fr(l),l}async function Ju({authClient:e,deviceCode:t}){for(;;){await Xu(Gu);let r=await e.device.token({client_id:xi,device_code:t,grant_type:"urn:ietf:params:oauth:grant-type:device_code"});if(r.data?.access_token!=null)return r.data.access_token;if(r.error==null)continue;if(!Yu(r.error.error))throw new Error(`Authorization failed: ${r.error.error_description}`)}}var Ku=new Set(["authorization_pending","slow_down"]);function Yu(e){return Ku.has(e)}function Xu(e){return new Promise(t=>{setTimeout(t,e)})}function Qu(){return process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open"}function Zu(e){let t=Qu();zu(`${t} "${e}"`,()=>{})}function Le({serverUrl:e,token:t}){return{appUrl:"",cwd:process.cwd(),engineUrl:"",projectId:"",ripploServerUrl:e,token:t,webhookSecret:""}}import ep from"fs";import tp from"path";function I(e){return ep.existsSync(tp.join(e,".ripplo"))}var np=rp(`
202
+ `);async function ln({agentProfileDescription:e,agentProfileId:t,baseUrl:r,browser:n,config:o,headed:i,preconditionNames:s,runId:a,webhookSecret:l,workflowId:c}){let d="unknown",u,f,w=!1;try{w=n==null,f=Bu({externalBrowser:n,headed:i});let v=s==null?void 0:on({engineBaseUrl:o.engineUrl,preconditionNames:s,webhookSecret:l}),[{project:g,workflow:E},P]=await Promise.all([fe({label:"Run context resolved",fn:()=>Ku({config:o,workflowId:c})}),fe({label:"Streaming run started",fn:()=>sn({agentProfileId:t,config:o,runId:a})}),Br({appUrl:r})]);d=E.name,u=P;let _=Xu(E.spec);h.info("Executing workflow: %s",E.name),await ep(qu({agentProfileDescription:e,agentProfileId:t,baseUrl:r,browserPromise:f,config:o,headed:i,ownsBrowser:w,preconditionPromise:v,project:g,runId:a,specData:_,streaming:u,webhookSecret:l,workflow:E}),Zu())}catch(v){throw await Hu({browserPromise:f,config:o,error:v,ownsBrowser:w,runId:a,streaming:u,workflowName:d}),v}}function Bu({externalBrowser:e,headed:t}){return e!=null?Promise.resolve(e):fe({label:"Browser launched",fn:()=>Te({headed:t})})}async function Hu({browserPromise:e,config:t,error:r,ownsBrowser:n,runId:o,streaming:i,workflowName:s}){let a=r instanceof Error?r.message:String(r),l=r instanceof Error?r.stack:void 0;await ti({error:a,runId:o,stack:l,workflowName:s}),i==null?await an({config:t,reason:a,runId:o}).catch(()=>{}):await i.complete({statusOverride:"failed",steps:[],summary:a}).catch(()=>{}),n&&e!=null&&await(await e.catch(()=>{}))?.close()}async function qu({agentProfileDescription:e,agentProfileId:t,baseUrl:r,browserPromise:n,config:o,headed:i,ownsBrowser:s,preconditionPromise:a,project:l,runId:c,specData:d,streaming:u,webhookSecret:f,workflow:w}){let v=a??rn({project:Gu(l),webhookSecret:f,workflowSlug:w.slug}),[g,E]=await Promise.all([v,n]);if(t!=null){s&&await E.close(),await Wu({agentProfileDescription:e,agentProfileId:t,baseUrl:r,config:o,headed:i,preconditionResult:g,runId:c,specData:d,streaming:u,webhookSecret:f,workflow:w});return}await Ju({baseUrl:r,browser:E,preconditionResult:g,runId:c,specData:d,streaming:u,webhookSecret:f})}async function Wu({agentProfileDescription:e,agentProfileId:t,baseUrl:r,config:n,headed:o,preconditionResult:i,runId:s,specData:a,streaming:l,webhookSecret:c,workflow:d}){let u=e!=null&&e.length>0?e:await Yu({config:n,profileId:t});await Or({baseUrl:r,cookies:i.cookies,executedPreconditions:i.executed,extraVariables:i.data,headed:o,runId:s,serverUrl:n.ripploServerUrl,spec:a,streaming:l,systemPrompt:u,token:n.token,workflowContext:{description:d.name,expectedOutcome:d.name,name:d.name}}),await Ii({preconditionResult:i,webhookSecret:c})}var zu=ge.object({preconditions:ge.array(ge.string()),requiresKeys:ge.array(ge.object({namespace:ge.string(),preconditionName:ge.string()})),slug:ge.string()});function Gu(e){let t=(e.workflows??[]).map(r=>{let n=Vt(Ft,r);return zu.parse(n)});return{engineBaseUrl:e.engineBaseUrl,workflows:t}}async function Ju({baseUrl:e,browser:t,preconditionResult:r,runId:n,specData:o,streaming:i,webhookSecret:s}){let a=await fe({label:"Spec executed",fn:()=>tn({baseUrl:e,browser:t,cookies:r.cookies,extraVariables:r.data,observerTransport:r.apiUrl==null?void 0:{apiUrl:r.apiUrl,webhookSecret:s},onRecordingChunk:i.enqueueRecordingChunk,onStep:i.enqueueStep,runId:n,spec:o})});await Ii({preconditionResult:r,webhookSecret:s}),await i.complete({statusOverride:void 0,steps:a,summary:void 0});let l=a.filter(d=>d.status==="passed").length,c=a.filter(d=>d.status==="failed").length;h.info("Run complete: %d passed, %d failed",l,c)}async function Ii({preconditionResult:e,webhookSecret:t}){e.apiUrl!=null&&await nn({apiUrl:e.apiUrl,cookies:e.cookies,data:e.data,executed:e.executed,webhookSecret:t})}async function Ku({config:e,workflowId:t}){let r=await b({config:e,document:Fu,variables:{projectId:e.projectId}});if(r.project==null)throw new Error("Project not found");let o={...Vt(Ai,r.project),...e.engineUrl.length>0?{engineBaseUrl:e.engineUrl}:{}},s=(o.workflows??[]).find(l=>Vt(Ft,l).id===t);if(s==null)throw new Error(`Workflow ${t} not found`);let a=Vt(Ft,s);return{project:o,workflow:a}}async function Yu({config:e,profileId:t}){let r=await b({config:e,document:Mu,variables:{id:t}});if(r.agentProfile==null)throw new Error(`Agent profile not found: ${t}`);let n=r.agentProfile,o=n.description;if(o==null||o.length===0)throw new Error(`Agent profile "${n.name}" has no description`);return h.info("Using agent profile: %s",n.name),Ir({description:o,output:n.output??void 0,successCriteria:n.successCriteria??void 0})}function Xu(e){if(e==null)throw new Error("Workflow has no spec");return Xr.decode(e)}var Qu=ge.coerce.number().int().positive().catch(Vu);function Zu(){return Qu.parse(process.env.RIPPLO_RUN_TIMEOUT_MS)}async function ep(e,t){let r,n=new Promise((o,i)=>{r=setTimeout(()=>{i(new Error(`Run timed out after ${String(t)}ms`))},t)});try{await Promise.race([e,n])}finally{r!=null&&clearTimeout(r)}}import{exec as ip}from"child_process";import{createAuthClient as tp}from"better-auth/client";import{deviceAuthorizationClient as rp}from"better-auth/client/plugins";function ji({baseURL:e}){return tp({baseURL:e,fetchOptions:{headers:{"User-Agent":"Ripplo CLI"}},plugins:[rp()]})}import{z as cn}from"zod";var np="https://ripplo.ai";function ye(){return Bt().RIPPLO_SERVER_URL}function Oi(){return Bt().RIPPLO_PROJECT_ID}var op=cn.object({RIPPLO_PROJECT_ID:cn.string().min(1).optional(),RIPPLO_SERVER_URL:cn.string().min(1).default(np)}),Ni;function Bt(){return Ni??=op.parse(process.env),Ni}var sp=5e3,Di="ripplo-cli";async function _i({onDeviceCode:e,url:t}){let r=t??Bt().RIPPLO_SERVER_URL,n=ji({baseURL:r}),o=await n.device.code({client_id:Di});if(o.error!=null)throw new Error(`Failed to request device code: ${o.error.error_description}`);let{device_code:i,user_code:s,verification_uri_complete:a}=o.data;e({userCode:s,verificationUrl:a}),pp(a);let l=await ap({authClient:n,deviceCode:i});return zr(l),l}async function ap({authClient:e,deviceCode:t}){for(;;){await dp(sp);let r=await e.device.token({client_id:Di,device_code:t,grant_type:"urn:ietf:params:oauth:grant-type:device_code"});if(r.data?.access_token!=null)return r.data.access_token;if(r.error==null)continue;if(!cp(r.error.error))throw new Error(`Authorization failed: ${r.error.error_description}`)}}var lp=new Set(["authorization_pending","slow_down"]);function cp(e){return lp.has(e)}function dp(e){return new Promise(t=>{setTimeout(t,e)})}function up(){return process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open"}function pp(e){let t=up();ip(`${t} "${e}"`,()=>{})}function Ue({serverUrl:e,token:t}){return{appUrl:"",cwd:process.cwd(),engineUrl:"",projectId:"",ripploServerUrl:e,token:t,webhookSecret:""}}import mp from"fs";import fp from"path";function I(e){return mp.existsSync(fp.join(e,".ripplo"))}var yp=gp(`
203
203
  query AuthViewer {
204
204
  currentUser {
205
205
  name
206
206
  email
207
207
  }
208
208
  }
209
- `);async function Ei(){let e=ge(),t=ne();if(t!=null){let s=await nn({serverUrl:e,token:t});if(s!=null){process.stdout.write(`Already signed in as ${s.email}. Run \`ripplo auth logout\` to switch.
209
+ `);async function Li(){let e=ye(),t=oe();if(t!=null){let s=await dn({serverUrl:e,token:t});if(s!=null){process.stdout.write(`Already signed in as ${s.email}. Run \`ripplo auth logout\` to switch.
210
210
  `);return}process.stdout.write(`Your saved session expired \u2014 let's sign you back in.
211
211
 
212
- `)}let r=await Ci({url:e,onDeviceCode:s=>{process.stdout.write(`Opening your browser to finish sign-in.
212
+ `)}let r=await _i({url:e,onDeviceCode:s=>{process.stdout.write(`Opening your browser to finish sign-in.
213
213
  `),process.stdout.write(`If it didn't open, visit: ${s.verificationUrl}
214
214
  `),process.stdout.write(`Verification code: ${s.userCode}
215
215
 
216
216
  `),process.stdout.write(`Waiting for you to approve...
217
- `)}}),n=await nn({serverUrl:e,token:r}),o=I(process.cwd()),i=o?"Welcome back":"Welcome to Ripplo";process.stdout.write(`
217
+ `)}}),n=await dn({serverUrl:e,token:r}),o=I(process.cwd()),i=o?"Welcome back":"Welcome to Ripplo";process.stdout.write(`
218
218
  `),process.stdout.write(n==null?`${i}.
219
- `:`${i}, ${op(n)}.
220
- `),process.stdout.write(`Session saved to ${be("token")}.
221
- `),o||(process.stdout.write("\nNext: run `/ripplo:setup` in Claude Code to wire Ripplo into this project,\n"),process.stdout.write("or `npx ripplo init` to set it up by hand.\n"))}function op(e){let t=e.name.trim().split(/\s+/)[0];return t!=null&&t.length>0?t:e.email}async function nn({serverUrl:e,token:t}){try{let n=(await b({config:Le({serverUrl:e,token:t}),document:np,variables:void 0})).currentUser;return n==null?null:{email:n.email,name:n.name}}catch{return null}}async function Ti(){let e=ne();e==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login`.\n"),process.exit(1));let t=ge(),r=await nn({serverUrl:t,token:e});r==null&&(process.stdout.write("Token rejected. Run `ripplo auth login` to re-authenticate.\n"),process.exit(1)),process.stdout.write(`Authenticated as ${r.name} <${r.email}> (${t})
222
- `)}function $i(){if(!Mr()){process.stdout.write(`No token to remove.
223
- `);return}process.stdout.write(`Removed ${be("token")}
224
- `)}import sn from"fs/promises";import an from"path";import{z as Ut}from"zod";import{z as Ai}from"zod";import{z as _e}from"zod";import{z as m}from"zod";import{z as Re}from"zod";import{z as Di}from"zod";import{z as D}from"zod";import{z as te}from"zod";import{z as on}from"zod";import{z as G}from"zod";var ip=Ut.object({__codec:Ut.string().min(1),data:Ut.unknown(),version:Ut.number().int().positive()}),sp=class extends Error{codec;currentVersion;gotVersion;constructor(e){super(`Unsupported ${e.codec} version ${String(e.gotVersion)} (current ${String(e.currentVersion)}). Upgrade Ripplo or rebuild with a compatible CLI.`),this.name="CodecVersionError",this.codec=e.codec,this.currentVersion=e.currentVersion,this.gotVersion=e.gotVersion}},ap=class extends Error{constructor(e){super(`Codec mismatch: expected "${e.expected}", got "${e.got}"`),this.name="CodecMismatchError"}};function dn(e){return ji({legacy:void 0,migrators:[],name:e,schemas:[]})}function lp(e,t){let r=JSON.parse(t);return e.decode(r)}function ji(e){return{initial:t=>ln(t,{...e,schemas:[t]}),legacy:t=>ji({...e,legacy:t})}}function ln(e,t){return{build:()=>cp(e,t),legacy:r=>ln(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return ln(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function cp(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>dp(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function dp(e,t,r){let{data:n,version:o}=up(t,r),i=Ni(t,n,o);return e.parse(i)}function up(e,t){let r=ip.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new ap({expected:e.name,got:r.data.__codec});return{data:r.data.data,version:r.data.version}}if(e.legacy!=null&&e.legacy.detect(t))return{data:t,version:e.legacy.assumedVersion};throw new Error(`Cannot decode "${e.name}": value is not a codec envelope and no legacy detector matched.`)}function Ni(e,t,r){let n=e.schemas.length;if(r>n)throw new sp({codec:e.name,currentVersion:n,gotVersion:r});if(r===n)return t;let o=e.schemas[r-1];if(o==null)throw new Error(`Codec "${e.name}" missing schema for v${String(r)}; cannot migrate.`);let i=o.parse(t),s=e.migrators[r-1];if(s==null)throw new Error(`Codec "${e.name}" missing migrator v${String(r)} \u2192 v${String(r+1)}.`);return Ni(e,s(i),r+1)}var Oi=_e.object({depends:_e.array(_e.string().min(1)).optional().describe("Names of other preconditions that must be satisfied first. Resolved via topological sort; cycles are rejected at validation time."),description:_e.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:_e.array(_e.string().min(1)).optional().describe("Keys that the execute response's data field will contain. e.g. ['projectId', 'workflowId']. These are used for route param interpolation ({{projectId}}) and workflow variables. Declared here so generated types are strongly typed per precondition.")}).describe("A named precondition declared at the graph level. States reference these by name."),pp=Re.object({by:Re.literal("testId"),value:Re.string().min(1)}),mp=Re.object({by:Re.literal("role"),name:Re.string().optional(),role:Re.string().min(1)}),A=Re.discriminatedUnion("by",[pp,mp]),it=Di.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),fp=Di.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]),gp=D.object({type:D.literal("static"),value:D.union([D.string(),D.number(),D.boolean()])}),Vt=D.object({name:D.string().min(1),type:D.literal("variable")}),yp=D.discriminatedUnion("type",[gp,Vt]),le=D.discriminatedUnion("type",[D.object({type:D.literal("static"),value:D.string()}),Vt]),hp=D.discriminatedUnion("type",[D.object({type:D.literal("static"),value:D.number().int().nonnegative()}),Vt]),wp=D.discriminatedUnion("type",[D.object({type:D.literal("static"),value:D.union([D.string(),D.number(),D.boolean()])}),Vt]),bp=te.discriminatedUnion("type",[te.object({default:te.string().optional(),type:te.literal("string")}),te.object({default:te.number().optional(),type:te.literal("number")}),te.object({default:te.boolean().optional(),type:te.literal("boolean")}),te.object({key:te.string().min(1),type:te.literal("env")})]),C={id:m.string().min(1).max(200),label:m.string().max(500).optional(),next:m.string().max(200).optional(),uiOnly:m.boolean().optional()},Ii=500,Sp=m.object({...C,type:m.literal("goto"),url:le}),vp=m.object({...C,locator:A,type:m.literal("click")}),kp=m.object({...C,locator:A,type:m.literal("fill"),value:le}),Rp=m.object({...C,locator:A,type:m.literal("select"),value:le}),Pp=m.object({...C,locator:A,type:m.literal("hover")}),xp=m.object({...C,key:m.string().min(1),locator:A.optional(),type:m.literal("press")}),Cp=m.object({...C,locator:A,type:m.literal("check")}),Ep=m.object({...C,locator:A,type:m.literal("uncheck")}),Tp=m.object({...C,height:m.number().int().positive(),type:m.literal("setViewport"),width:m.number().int().positive()}),$p=m.object({...C,message:m.string().min(1),type:m.literal("fail")}),Ap=m.object({...C,type:m.literal("setVariable"),value:yp,variable:m.string().min(1)}),Ip=m.object({...C,locator:A,type:m.literal("extractText"),variable:m.string().min(1)}),jp=m.object({...C,files:m.array(m.string()).min(1),locator:A,type:m.literal("upload")}),Np=m.object({...C,locator:A,type:m.literal("dblclick")}),Op=m.object({...C,source:A,target:A,type:m.literal("drag")}),Dp=m.object({...C,locator:A,type:m.literal("scrollIntoView")}),Lp=m.object({...C,locator:A,type:m.literal("type"),value:le}),_p=m.object({...C,locator:A,type:m.literal("focus")}),Up=m.object({...C,locator:A,type:m.literal("clear")}),Vp=m.object({...C,locator:A,type:m.literal("rightClick")}),Fp=m.object({...C,action:m.enum(["accept","dismiss"]),promptText:m.string().optional(),type:m.literal("handleDialog")}),Mp=m.object({...C,action:m.enum(["read","write"]),type:m.literal("clipboard"),value:le.optional(),variable:m.string().min(1).optional()}),Hp=m.object({...C,permission:m.string().min(1),state:m.enum(["granted","prompt"]),type:m.literal("setPermission")}),qp=m.object({...C,locator:A,type:m.literal("assertVisible")}),Bp=m.object({...C,locator:A,type:m.literal("assertNotVisible")}),Wp=m.object({...C,expected:le,locator:A,operator:it,type:m.literal("assertText")}),zp=m.object({...C,expected:le,operator:it,type:m.literal("assertUrl")}),Gp=m.object({...C,expected:hp,locator:A,operator:fp,type:m.literal("assertCount")}),Jp=m.object({...C,expected:le,locator:A,operator:it,type:m.literal("assertValue")}),Kp=m.object({...C,attribute:m.string().min(1),expected:le,locator:A,operator:it,type:m.literal("assertAttribute")}),Yp=m.object({...C,locator:A,type:m.literal("assertEnabled")}),Xp=m.object({...C,locator:A,type:m.literal("assertDisabled")}),Qp=m.object({...C,expected:le,operator:it,type:m.literal("assertTitle")}),Zp=m.object({...C,locator:A,type:m.literal("assertChecked")}),em=m.object({...C,locator:A,type:m.literal("assertNotChecked")}),tm=m.object({...C,locator:A,type:m.literal("assertFocused")}),rm=m.object({...C,locator:A,type:m.literal("assertNotFocused")}),nm=m.object({...C,budget:m.enum(["fast","slow","async"]),observer:m.string().min(1).max(200),params:m.record(m.string().max(200),wp),type:m.literal("assertObserver")}),om=m.discriminatedUnion("type",[Sp,vp,kp,Rp,Pp,xp,Cp,Ep,qp,Bp,Wp,zp,Gp,Jp,Kp,Yp,Xp,Tp,$p,Ap,Ip,jp,Np,Op,Dp,Lp,_p,Up,Vp,Fp,Mp,Hp,Qp,Zp,em,tm,rm,nm]),Li=m.object({entryNode:m.string().min(1).max(200),nodes:m.record(m.string().max(200),om).refine(e=>Object.keys(e).length<=Ii,`Workflow has more than ${String(Ii)} nodes`),uiOnly:m.boolean().optional(),variableNamespaces:m.record(m.string().max(200),m.string().max(500)).optional(),variables:m.record(m.string().max(200),bp).optional()}),im=Ai.record(Ai.string().max(200),Oi),sm={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},am={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},dx=dn("workflow-spec").legacy(sm).initial(Li).build(),ux=dn("precondition-map").legacy(am).initial(im).build(),lm=["fast","slow","async"],cm=on.object({budget:on.enum(lm).describe("Polling budget tier: fast | slow | async"),description:on.string().min(1).describe("Human-readable description of what this observer checks")}).describe("A named backend state observer. Tests assert against it with assert.backend(observer, params). Implementation lives on the user's server."),ce=".ripplo/ripplo.lock",dm=5e3,um=G.record(G.string().max(200),G.string().max(200)),pm=G.object({coverage:G.array(G.string().max(500)).max(2e3).default([]),expectedOutcome:G.string().max(2e3),name:G.string().max(200),preconditions:G.array(G.string().max(200)).max(1e3),requiresKeys:um,slug:G.string().max(200),spec:Li}),mm=G.object({observers:G.record(G.string().max(200),cm),preconditions:G.record(G.string().max(200),Oi),tests:G.array(pm).max(dm)}),_i=dn("ripplo-lockfile").initial(mm).build();function Ui(e){return{observers:e.observers,preconditions:e.preconditions,tests:e.tests.filter(t=>t.implemented).map(t=>({coverage:[...t.coverage],expectedOutcome:t.expectedOutcome,name:t.name,preconditions:[...t.preconditions],requiresKeys:{...t.requiresKeys},slug:t.slug,spec:t.spec}))}}function cn(e){let t=_i.encode(e);return`${JSON.stringify(t,ym(t),2)}
225
- `}async function Ft({cwd:e}){let t=an.join(e,ce),r=await fm(t);return r==null?null:lp(_i,r)}async function de({cwd:e,result:t}){let r=Ui(t),n=an.join(e,ce);await sn.mkdir(an.dirname(n),{recursive:!0}),await sn.writeFile(n,cn(r),"utf8")}function Mt({compiled:e,existing:t}){if(t==null)return"missing";let r=cn(Ui(e)),n=cn(t);return r===n?"match":"stale"}async function fm(e){try{return await sn.readFile(e,"utf8")}catch(t){if(gm(t)&&t.code==="ENOENT")return null;throw t}}function gm(e){return e instanceof Error&&"code"in e}function ym(e){return function(r,n){return n===e||!hm(n)?n:Object.fromEntries(Object.entries(n).toSorted(([o],[i])=>o.localeCompare(i)))}}function hm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import st from"fs";import Bt from"path";var un=["**/src/**","**/app/**","**/apps/**","**/pages/**","**/routes/**","**/components/**","**/server/**","**/api/**","**/backend/**","**/features/**","**/modules/**","**/views/**","**/ui/**","**/hooks/**","**/contexts/**","**/providers/**","**/controllers/**","**/handlers/**","**/resolvers/**","**/services/**","**/middleware/**","**/lib/**"],Pe=["**/*.gen.*","**/generated/**","**/*.d.ts","**/*.test.*","**/*.spec.*","**/node_modules/**","**/dist/**","**/build/**",".ripplo/**","**/*.md","**/.next/**","**/.turbo/**","**/.vercel/**","**/.svelte-kit/**","**/.nuxt/**","**/.astro/**","**/coverage/**","**/storybook-static/**","**/*.stories.*","**/*.story.*","**/cli/**","**/scripts/**","**/tools/**","**/__tests__/**","**/__mocks__/**","**/__fixtures__/**","**/*.config.*","**/*.setup.*","**/public/**","**/static/**","**/assets/**","**/migrations/**","**/prisma/migrations/**","**/scripts/**"];function Vi(e){return e.data}function Fi(e){return{as(t){return{data:{label:t,node:e}}}}}function Ht(e){let t=e.getPreconditions(),r=e.getObservers(),n=e.getTests();wm(n);let o={};t.forEach(a=>{o[a.name]={depends:[...a.dependsOn],description:a.description,returns:[...a.returns]}});let i={};r.forEach(a=>{i[a.name]={budget:a.budget,description:a.description}});let s=n.map(a=>bm(a,t));return{observers:i,preconditions:o,tests:s}}function wm(e){let t=new Map;e.forEach(r=>{let n=t.get(r.id);if(n!=null)throw new Error(`Duplicate test id "${r.id}" used by "${n}" and "${r.name}"`);t.set(r.id,r.name)})}function bm(e,t){let r=e.id,{accessedKeys:n,vars:o}=vm(e.requiresKeys),i=e.startsAtFn==null?void 0:e.startsAtFn(o),s=e.stepsFn==null?[]:e.stepsFn(o),a=i==null?s:[Sm(i),...s],l=km(a,n,e.requiresKeys,e.uiOnly),c=[];Object.keys(e.requiresKeys).length>0&&n.size===0&&e.implemented&&c.push("Test requires preconditions but never references their data \u2014 destructure and use precondition data in steps()");let u=Pm(e.requires,t);return{additionalChecks:[],coverage:e.coverage,description:e.description,expectedOutcome:e.expectedOutcome,implemented:e.implemented,name:e.name,preconditions:u,requiresKeys:{...e.requiresKeys},slug:r,spec:l,warnings:c}}function Sm(e){return Fi({type:"goto",url:{type:"static",value:e}}).as(`navigate to ${e}`)}function vm(e){let t=new Set,r={};return Object.keys(e).forEach(n=>{r[n]=new Proxy({},{get(o,i){if(typeof i=="string"){let s=`${n}.${i}`;return t.add(s),`{{${s}}}`}}})}),{accessedKeys:t,vars:r}}function km(e,t,r,n){let o={};e.forEach((a,l)=>{let c=`step-${String(l)}`,d=l<e.length-1?`step-${String(l+1)}`:void 0;o[c]=Rm(a,c,d)});let i={};t.forEach(a=>{i[a]={default:`test-${a}`,type:"string"}});let s={...r};return{entryNode:"step-0",nodes:o,uiOnly:n,variableNamespaces:s,variables:i}}function Rm(e,t,r){let{label:n,node:o}=Vi(e);return{...o,id:t,label:n,next:r}}function Pm(e,t){let r=new Map(t.map(s=>[s.name,s])),n=[],o=new Set;function i(s){o.has(s)||(o.add(s),r.get(s)?.dependsOn.forEach(a=>{i(a)}),n.push(s))}return e.forEach(s=>{i(s)}),n}import{Webhook as kx,WebhookVerificationError as Rx}from"standardwebhooks";import{z as $}from"zod";var xx=$.object({preconditions:$.array($.string().min(1))}),Cx=$.object({data:$.record($.string(),$.record($.string(),$.string())),preconditions:$.array($.string().min(1))}),Ex=$.object({observer:$.string().min(1).max(200),params:$.record($.string().max(200),$.union([$.string(),$.number(),$.boolean()]))}),xm=$.discriminatedUnion("kind",[$.object({kind:$.literal("pass")}),$.object({kind:$.literal("retry"),reason:$.string()}),$.object({kind:$.literal("fail"),reason:$.string()})]),Tx=$.object({error:$.string().optional(),outcome:xm.optional(),success:$.boolean()});function Ue(e){let t=[];return e.tests.forEach(r=>{let n=Cm(r),o=i=>{t.push({...i,test:r.slug})};Jm.forEach(i=>{i(n,r,o)})}),{diagnostics:t}}function Cm(e){let t=[],r=e.spec.entryNode,n=new Set;for(;r!=null&&!n.has(r);){n.add(r);let o=e.spec.nodes[r];if(o==null)break;t.push(o),r=o.next}return t}function Em(e,t,r){e.forEach(n=>{n.type==="assertText"&&"operator"in n&&n.operator!=="equals"&&r({message:`${n.type} uses operator "${n.operator}" \u2014 only "equals" is allowed for determinism`,rule:"exact-text-match",step:n.label??n.id})})}function Tm(e,t,r){Object.keys(t.spec.variables??{}).length>0&&e.forEach(o=>{if(o.type==="fill"&&Hi(o.value)){let i=o.value.value;!qi(i)&&Dm(i)&&r({message:`fill() uses hardcoded value "${i}" \u2014 consider using precondition data via {{namespace.key}}`,rule:"no-hardcoded-data",step:o.label??o.id})}})}function $m(e,t,r){if(Object.keys(t.spec.variables??{}).length===0)return;e.some(i=>JSON.stringify(i).includes("{{"))||r({message:"Test requires preconditions but steps() never references precondition data \u2014 destructure and use it",rule:"prefer-precondition-data",step:void 0})}function Am(e,t,r){e.forEach(n=>{(n.label==null||n.label.length===0)&&r({message:`Step "${n.id}" lacks .as("...") label \u2014 every step must be labeled`,rule:"missing-label",step:n.id})})}function Im(e,t,r){let n=new Map;e.forEach(o=>{if(o.label==null)return;let i=n.get(o.label);i==null?n.set(o.label,o.id):r({message:`Duplicate label "${o.label}" \u2014 also used by ${i}`,rule:"no-duplicate-labels",step:o.label})})}function jm(e,t,r){let n=0;e.forEach(o=>{Ve(o)?n=0:(n++,n===3&&r({message:"3+ consecutive actions without an assertion \u2014 add verification between actions",rule:"assert-after-action",step:o.label??o.id}))})}function Nm(e,t,r){if(e.length===0)return;let n=e.at(-1);n!=null&&!Ve(n)&&r({message:"Last step is an action, not an assertion \u2014 expectedOutcome should be verified by assertions at the end",rule:"assert-matches-outcome",step:n.label??n.id})}function Om(e,t,r){t.implemented&&e.length===0&&r({message:"Test has zero steps",rule:"no-empty-steps",step:void 0})}function Hi(e){return!(typeof e!="object"||e==null||!("type"in e)||e.type!=="static"||!("value"in e)||typeof e.value!="string")}function qi(e){return e.includes("{{")}function Dm(e){return e.includes("@")||/\b[a-f0-9]{8,}\b/.test(e)||/^(test|ripplo|example|sample|demo)/i.test(e)}function Ve(e){return e.type.startsWith("assert")}var Lm=new Set(["assertText","assertValue","assertCount","assertUrl","assertNotVisible","assertChecked","assertNotChecked","assertAttribute","assertDisabled","assertEnabled"]);function _m(e){return Lm.has(e.type)}function Um(e,t,r){!t.implemented||e.length===0||e.some(n=>Ve(n))||r({message:"Test has zero assertion steps \u2014 cannot verify expectedOutcome. Add assert.* steps.",rule:"no-assertions",step:void 0})}function Vm(e,t,r){if(!t.implemented||e.length<=3)return;let n=e.filter(i=>Ve(i)).length;if(n===0)return;let o=n/e.length;if(o<.15){let i=Math.round(o*100);r({message:`Only ${String(n)}/${String(e.length)} steps are assertions (${String(i)}%) \u2014 add more verification between actions`,rule:"low-assertion-ratio",step:void 0})}}function pn(e){if(!("locator"in e)||e.locator==null)return;let t=e.locator;return t.by==="role"?`role:${t.role}:${t.name??""}`:`testId:${t.value}`}function Fm(e,t,r){e.forEach((n,o)=>{if(n.type!=="click")return;let i=pn(n);if(i==null)return;let s=e.slice(o+1,o+4);s.find(c=>c.type==="assertVisible"&&pn(c)===i)==null||s.some(c=>_m(c)||Ve(c)&&pn(c)!==i)||r({message:`click "${n.label??n.id}" is followed only by assert.visible on the same locator \u2014 verifies nothing about the click's effect`,rule:"tautological-post-click-assert",step:n.label??n.id})})}var Mm=new Set(["the","is","a","an","and","or","of","to","in","on","at","for","that","this","with","be","are","was","were","it","its","as","by","from","after","before","should","will","can","still","but","not","no","so","if","then","than","user","users","page","view","shows","show","see","click","clicks","clicked","clickable","visible","appears","appear","displayed","stays","remains"]);function mn(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=3&&!Mm.has(t))}function Hm(e){let t=e.label==null?[]:mn(e.label);if(!("locator"in e)||e.locator==null)return t;let r=e.locator,n=r.by==="role"?r.name??"":r.value;return[...t,...mn(n)]}function qm(e,t,r){if(!t.implemented||e.length===0)return;let n=new Set(mn(t.expectedOutcome));if(n.size===0)return;let o=e.filter(s=>Ve(s));if(o.length===0)return;o.some(s=>Hm(s).some(a=>n.has(a)))||r({message:`No assertion references any keyword from expectedOutcome (${[...n].join(", ")}) \u2014 the outcome may not actually be verified`,rule:"expected-outcome-keyword-coverage",step:void 0})}var Bm=/save|submit|create|delete|remove|send|invite|update|confirm|publish|apply|pay|subscribe|upgrade|cancel|archive|rename/i;function Mi(e){if(e.type==="upload"||e.type==="handleDialog"&&e.action==="accept")return!0;if(e.type!=="click")return!1;let t=e.locator,r=t.by==="role"?t.name??"":t.value;return Bm.test(r)}function Wm(e,t,r){!t.implemented||t.spec.uiOnly===!0||e.forEach((n,o)=>{if(!Mi(n)||"uiOnly"in n&&n.uiOnly===!0)return;let i=e.slice(o+1),s=i.findIndex(d=>Mi(d)),a=s===-1?i.length:s;i.slice(0,a).some(d=>d.type==="assertObserver")||r({message:`"${n.label??n.id}" looks like it mutates backend state but no assert.backend(...) observer verifies it \u2014 the test can pass while the server is broken. You need to add an observer that checks the persisted result (see .ripplo/observers/ for examples). Only if this action truly does NOT change any server state (pure client-side interaction, presentation toggle, etc.) should you fall back to marking the step { uiOnly: true } to silence this rule.`,rule:"mutation-without-observer-coverage",step:n.label??n.id})})}function zm(e,t,r){Object.keys(t.spec.variables??{}).length!==0&&e.forEach(o=>{if(o.type!=="assertObserver")return;let i=Object.entries(o.params);i.length===0||i.some(([,a])=>Hi(a)&&qi(a.value))||r({message:`assert.backend "${o.label??o.id}" passes only hardcoded params while the test defines precondition variables \u2014 observer assertions should reference {{namespace.key}} so they match the actual precondition data`,rule:"observer-params-reference-variables",step:o.label??o.id})})}function Gm(e,t,r){let n=new Set(Object.keys(t.spec.variables??{})),o=/\{\{([^{}]+?)\}\}/g;e.forEach(i=>{let a=[...JSON.stringify(i).matchAll(o)],l=[...new Set(a.map(u=>u[1]).filter(u=>u!=null&&!n.has(u)))];if(l.length===0)return;let c=l.map(u=>`{{${u}}}`).join(", "),d=[...new Set(l.map(u=>u.split(".")[0]??u))].join(", ");r({message:`"${i.label??i.id}" contains literal template string(s) ${c} \u2014 destructure the proxy in .steps(({ ${d} }) => \u2026) and pass the proxy value (e.g. \`${l[0]??""}\`) directly. Writing the template as a string bypasses type-checking and silently accepts typos.`,rule:"no-literal-template-strings",step:i.label??i.id})})}var Jm=[Em,Tm,Gm,$m,Am,Im,jm,Nm,Om,Um,Vm,Fm,qm,Wm,zm];import Sf from"picomatch";import{execFileSync as Km,spawnSync as Ym}from"child_process";function X(e,t){return Km("git",[...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}function Bi(e,t){let r=Ym("git",["show",e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(r.status===0)return r.stdout;if(r.status===128)return null;throw new Error(`git show ${e} failed (${String(r.status)}): ${r.stderr}`)}import k from"typescript";import*as Wi from"remeda";var zi=[["onClick","click"],["onContextMenu","click"],["onKeyDown","click"],["onKeyPress","click"],["onKeyUp","click"],["onSelect","click"],["onOpenChange","click"],["onPress","click"],["onActivate","click"],["onToggle","click"],["onOpen","click"],["onClose","click"],["onDismiss","click"],["onConfirm","click"],["onCancel","click"],["onApply","click"],["onClear","click"],["onSubmit","submit"],["onReset","submit"],["onDrop","drag"],["onDragEnd","drag"],["onDragEnter","drag"],["onDragLeave","drag"],["onDragOver","drag"],["onDragStart","drag"],["onValueChange","select"],["onSelectionChange","select"],["onChange","input"],["onCheckedChange","input"],["onInput","input"]],Xm=new Map([["button","click"],["link","navigate"],["textbox","input"],["searchbox","input"],["combobox","select"],["listbox","select"]]),Qm=[[/(?:^|[a-z])Button$/,"click"],[/(?:^|[a-z])(?:Link|NavLink|Anchor)$/,"navigate"],[/(?:^|[a-z])(?:Textarea|TextArea|Input|Field|SearchBox)$/,"input"],[/(?:^|[a-z])(?:Select|Combobox|ComboBox|Dropdown)$/,"select"],[/(?:^|[a-z])Form$/,"submit"]];function qt({filePath:e,source:t}){let r=k.createSourceFile(e,t,k.ScriptTarget.Latest,!0,k.ScriptKind.TSX);return r.statements.flatMap(n=>Zm({filePath:e,sf:r,stmt:n}))}function Zm({filePath:e,sf:t,stmt:r}){let n=tf(r);if(n==null||ef(n))return[];let o=Gi(r,t).map(i=>({id:`${e}#${n}.${i.kind}[${i.label}]`,line:i.line}));return Wi.uniqueBy(o,i=>i.id)}function ef(e){return e.endsWith("Fragment")||e.endsWith("Skeleton")||/^use[A-Z]/.test(e)||/^[A-Z][A-Z0-9_]*$/.test(e)}function tf(e){if(k.isExportAssignment(e))return rf(e.expression);if(!nf(e))return null;if(k.isFunctionDeclaration(e)||k.isClassDeclaration(e))return e.name?.text??null;if(k.isVariableStatement(e)){let t=e.declarationList.declarations[0];return t!=null&&k.isIdentifier(t.name)?t.name.text:null}return null}function rf(e){return k.isIdentifier(e)?e.text:(k.isFunctionExpression(e)||k.isClassExpression(e))&&e.name!=null?e.name.text:"default"}function nf(e){if(!k.canHaveModifiers(e))return!1;let t=k.getModifiers(e);return t!=null&&t.some(r=>r.kind===k.SyntaxKind.ExportKeyword)}function Gi(e,t){let r=of(e,t),n=e.getChildren(t).flatMap(o=>Gi(o,t));return r==null?n:[r,...n]}function of(e,t){let r=sf(e);if(r==null)return null;let n=af(r);if(n==null)return null;let o=pf(r,n);return o==null?null:{kind:n,label:o,line:bf(t,e.getStart(t))}}function sf(e){return k.isJsxSelfClosingElement(e)&&k.isIdentifier(e.tagName)?{attrs:e.attributes,children:[],tag:e.tagName.text}:k.isJsxElement(e)&&k.isIdentifier(e.openingElement.tagName)?{attrs:e.openingElement.attributes,children:e.children,tag:e.openingElement.tagName.text}:null}function af({attrs:e,tag:t}){let r=ue(e,"role");return r!=null?Xm.get(r)??null:cf(t,e)??df(t)??uf(e)}var lf=new Map([["button",()=>"click"],["a",e=>ue(e,"href")==null?null:"navigate"],["input",e=>ue(e,"type")==="file"?"upload":"input"],["textarea",()=>"input"],["select",()=>"select"],["form",()=>"submit"]]);function cf(e,t){return lf.get(e)?.(t)??null}function df(e){return/^[A-Z]/.test(e)?Qm.find(([t])=>t.test(e))?.[1]??null:null}function uf(e){return zi.find(([t])=>gf(e,t))?.[1]??null}function pf({attrs:e,children:t,tag:r},n){return n==="navigate"?ue(e,"href")??ue(e,"to"):ue(e,"aria-label")??ue(e,"label")??ue(e,"title")??ue(e,"name")??ue(e,"placeholder")??(mf(r)?void 0:wf(t))??ff(e,n)}function mf(e){return e==="input"||e==="textarea"||e==="select"}function ff(e,t){let r=zi.find(([,o])=>o===t)?.[0];if(r==null)return;let n=yf(e,r);if(n!=null){if(k.isIdentifier(n))return n.text;if(k.isArrowFunction(n)||k.isFunctionExpression(n))return Ji(n.body)}}function Ji(e){if(k.isCallExpression(e)){let t=e.expression;return k.isIdentifier(t)?t.text:k.isPropertyAccessExpression(t)?t.name.text:void 0}return k.forEachChild(e,Ji)}function gf(e,t){return e.properties.some(r=>k.isJsxAttribute(r)&&k.isIdentifier(r.name)&&r.name.text===t)}function Ki(e,t){return e.properties.find(r=>k.isJsxAttribute(r)&&k.isIdentifier(r.name)&&r.name.text===t)}function ue(e,t){let r=Ki(e,t);return r==null?void 0:hf(r.initializer)}function yf(e,t){let r=Ki(e,t);if(!(r?.initializer==null||!k.isJsxExpression(r.initializer)))return r.initializer.expression}function hf(e){if(e==null)return"";if(k.isStringLiteral(e))return e.text;if(k.isJsxExpression(e))return Xi(e.expression)}function wf(e){let t=e.flatMap(r=>Yi(r)).join(" ").trim();return t.length===0?void 0:t}function Yi(e){if(k.isJsxText(e)){let t=e.text.trim();return t.length===0?[]:[t]}if(k.isJsxExpression(e)){let t=Xi(e.expression);return t==null?[]:[t]}return k.isJsxElement(e)?e.children.flatMap(t=>Yi(t)):[]}function Xi(e){if(e!=null){if(k.isStringLiteral(e)||k.isNoSubstitutionTemplateLiteral(e))return e.text;if(k.isCallExpression(e)&&e.arguments.length===1){let t=e.arguments[0];if(t!=null&&(k.isStringLiteral(t)||k.isNoSubstitutionTemplateLiteral(t)))return t.text}}}function bf(e,t){return e.getLineAndCharacterOfPosition(t).line+1}var vf=Bt.join(".ripplo","coverage.d.ts");function Fe({cwd:e}){kf({cwd:e,ignorePaths:Pe})}function kf({cwd:e,ignorePaths:t}){let r=Me({cwd:e,ignorePaths:t});xf({content:Pf(r),cwd:e})}function Me({cwd:e,ignorePaths:t}){let n=Rf({cwd:e,ignorePaths:t}).flatMap(o=>fn({cwd:e,file:o}));return[...new Set(n)].sort((o,i)=>o.localeCompare(i))}function Rf({cwd:e,ignorePaths:t}){let r=X(["ls-files","--cached","--others","--exclude-standard","-z"],e),n=Sf([...t]);return r.split("\0").filter(o=>o.length>0&&/\.(tsx|jsx)$/.test(o)).filter(o=>!n(o)).filter(o=>st.existsSync(Bt.join(e,o)))}function fn({cwd:e,file:t}){let r=st.readFileSync(Bt.join(e,t),"utf8");return qt({filePath:t,source:r}).map(n=>n.id)}function Pf(e){let t=`// GENERATED \u2014 do not edit
219
+ `:`${i}, ${hp(n)}.
220
+ `),process.stdout.write(`Session saved to ${ve("token")}.
221
+ `),o||(process.stdout.write("\nNext: run `/ripplo:setup` in Claude Code to wire Ripplo into this project,\n"),process.stdout.write("or `npx ripplo init` to set it up by hand.\n"))}function hp(e){let t=e.name.trim().split(/\s+/)[0];return t!=null&&t.length>0?t:e.email}async function dn({serverUrl:e,token:t}){try{let n=(await b({config:Ue({serverUrl:e,token:t}),document:yp,variables:void 0})).currentUser;return n==null?null:{email:n.email,name:n.name}}catch{return null}}async function Ui(){let e=oe();e==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login`.\n"),process.exit(1));let t=ye(),r=await dn({serverUrl:t,token:e});r==null&&(process.stdout.write("Token rejected. Run `ripplo auth login` to re-authenticate.\n"),process.exit(1)),process.stdout.write(`Authenticated as ${r.name} <${r.email}> (${t})
222
+ `)}function Vi(){if(!Gr()){process.stdout.write(`No token to remove.
223
+ `);return}process.stdout.write(`Removed ${ve("token")}
224
+ `)}import pn from"fs/promises";import mn from"path";import{z as Ht}from"zod";import{z as Fi}from"zod";import{z as Ve}from"zod";import{z as m}from"zod";import{z as xe}from"zod";import{z as Wi}from"zod";import{z as D}from"zod";import{z as re}from"zod";import{z as un}from"zod";import{z as G}from"zod";var wp=Ht.object({__codec:Ht.string().min(1),data:Ht.unknown(),version:Ht.number().int().positive()}),bp=class extends Error{codec;currentVersion;gotVersion;constructor(e){super(`Unsupported ${e.codec} version ${String(e.gotVersion)} (current ${String(e.currentVersion)}). Upgrade Ripplo or rebuild with a compatible CLI.`),this.name="CodecVersionError",this.codec=e.codec,this.currentVersion=e.currentVersion,this.gotVersion=e.gotVersion}},Sp=class extends Error{constructor(e){super(`Codec mismatch: expected "${e.expected}", got "${e.got}"`),this.name="CodecMismatchError"}};function yn(e){return Bi({legacy:void 0,migrators:[],name:e,schemas:[]})}function vp(e,t){let r=JSON.parse(t);return e.decode(r)}function Bi(e){return{initial:t=>fn(t,{...e,schemas:[t]}),legacy:t=>Bi({...e,legacy:t})}}function fn(e,t){return{build:()=>kp(e,t),legacy:r=>fn(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return fn(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function kp(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>Rp(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function Rp(e,t,r){let{data:n,version:o}=Pp(t,r),i=Hi(t,n,o);return e.parse(i)}function Pp(e,t){let r=wp.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new Sp({expected:e.name,got:r.data.__codec});return{data:r.data.data,version:r.data.version}}if(e.legacy!=null&&e.legacy.detect(t))return{data:t,version:e.legacy.assumedVersion};throw new Error(`Cannot decode "${e.name}": value is not a codec envelope and no legacy detector matched.`)}function Hi(e,t,r){let n=e.schemas.length;if(r>n)throw new bp({codec:e.name,currentVersion:n,gotVersion:r});if(r===n)return t;let o=e.schemas[r-1];if(o==null)throw new Error(`Codec "${e.name}" missing schema for v${String(r)}; cannot migrate.`);let i=o.parse(t),s=e.migrators[r-1];if(s==null)throw new Error(`Codec "${e.name}" missing migrator v${String(r)} \u2192 v${String(r+1)}.`);return Hi(e,s(i),r+1)}var qi=Ve.object({depends:Ve.array(Ve.string().min(1)).optional().describe("Names of other preconditions that must be satisfied first. Resolved via topological sort; cycles are rejected at validation time."),description:Ve.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:Ve.array(Ve.string().min(1)).optional().describe("Keys that the execute response's data field will contain. e.g. ['projectId', 'workflowId']. These are used for route param interpolation ({{projectId}}) and workflow variables. Declared here so generated types are strongly typed per precondition.")}).describe("A named precondition declared at the graph level. States reference these by name."),xp=xe.object({by:xe.literal("testId"),value:xe.string().min(1)}),Cp=xe.object({by:xe.literal("role"),name:xe.string().optional(),role:xe.string().min(1)}),A=xe.discriminatedUnion("by",[xp,Cp]),ct=Wi.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),Ep=Wi.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]),Tp=D.object({type:D.literal("static"),value:D.union([D.string(),D.number(),D.boolean()])}),qt=D.object({name:D.string().min(1),type:D.literal("variable")}),$p=D.discriminatedUnion("type",[Tp,qt]),ce=D.discriminatedUnion("type",[D.object({type:D.literal("static"),value:D.string()}),qt]),Ap=D.discriminatedUnion("type",[D.object({type:D.literal("static"),value:D.number().int().nonnegative()}),qt]),Ip=D.discriminatedUnion("type",[D.object({type:D.literal("static"),value:D.union([D.string(),D.number(),D.boolean()])}),qt]),jp=re.discriminatedUnion("type",[re.object({default:re.string().optional(),type:re.literal("string")}),re.object({default:re.number().optional(),type:re.literal("number")}),re.object({default:re.boolean().optional(),type:re.literal("boolean")}),re.object({key:re.string().min(1),type:re.literal("env")})]),C={id:m.string().min(1).max(200),label:m.string().max(500).optional(),next:m.string().max(200).optional(),uiOnly:m.boolean().optional()},Mi=500,Np=m.object({...C,type:m.literal("goto"),url:ce}),Op=m.object({...C,locator:A,type:m.literal("click")}),Dp=m.object({...C,locator:A,type:m.literal("fill"),value:ce}),_p=m.object({...C,locator:A,type:m.literal("select"),value:ce}),Lp=m.object({...C,locator:A,type:m.literal("hover")}),Up=m.object({...C,key:m.string().min(1),locator:A.optional(),type:m.literal("press")}),Vp=m.object({...C,locator:A,type:m.literal("check")}),Fp=m.object({...C,locator:A,type:m.literal("uncheck")}),Mp=m.object({...C,height:m.number().int().positive(),type:m.literal("setViewport"),width:m.number().int().positive()}),Bp=m.object({...C,message:m.string().min(1),type:m.literal("fail")}),Hp=m.object({...C,type:m.literal("setVariable"),value:$p,variable:m.string().min(1)}),qp=m.object({...C,locator:A,type:m.literal("extractText"),variable:m.string().min(1)}),Wp=m.object({...C,files:m.array(m.string()).min(1),locator:A,type:m.literal("upload")}),zp=m.object({...C,locator:A,type:m.literal("dblclick")}),Gp=m.object({...C,source:A,target:A,type:m.literal("drag")}),Jp=m.object({...C,locator:A,type:m.literal("scrollIntoView")}),Kp=m.object({...C,locator:A,type:m.literal("type"),value:ce}),Yp=m.object({...C,locator:A,type:m.literal("focus")}),Xp=m.object({...C,locator:A,type:m.literal("clear")}),Qp=m.object({...C,locator:A,type:m.literal("rightClick")}),Zp=m.object({...C,action:m.enum(["accept","dismiss"]),promptText:m.string().optional(),type:m.literal("handleDialog")}),em=m.object({...C,action:m.enum(["read","write"]),type:m.literal("clipboard"),value:ce.optional(),variable:m.string().min(1).optional()}),tm=m.object({...C,permission:m.string().min(1),state:m.enum(["granted","prompt"]),type:m.literal("setPermission")}),rm=m.object({...C,locator:A,type:m.literal("assertVisible")}),nm=m.object({...C,locator:A,type:m.literal("assertNotVisible")}),om=m.object({...C,expected:ce,locator:A,operator:ct,type:m.literal("assertText")}),im=m.object({...C,expected:ce,operator:ct,type:m.literal("assertUrl")}),sm=m.object({...C,expected:Ap,locator:A,operator:Ep,type:m.literal("assertCount")}),am=m.object({...C,expected:ce,locator:A,operator:ct,type:m.literal("assertValue")}),lm=m.object({...C,attribute:m.string().min(1),expected:ce,locator:A,operator:ct,type:m.literal("assertAttribute")}),cm=m.object({...C,locator:A,type:m.literal("assertEnabled")}),dm=m.object({...C,locator:A,type:m.literal("assertDisabled")}),um=m.object({...C,expected:ce,operator:ct,type:m.literal("assertTitle")}),pm=m.object({...C,locator:A,type:m.literal("assertChecked")}),mm=m.object({...C,locator:A,type:m.literal("assertNotChecked")}),fm=m.object({...C,locator:A,type:m.literal("assertFocused")}),gm=m.object({...C,locator:A,type:m.literal("assertNotFocused")}),ym=m.object({...C,budget:m.enum(["fast","slow","async"]),observer:m.string().min(1).max(200),params:m.record(m.string().max(200),Ip),type:m.literal("assertObserver")}),hm=m.discriminatedUnion("type",[Np,Op,Dp,_p,Lp,Up,Vp,Fp,rm,nm,om,im,sm,am,lm,cm,dm,Mp,Bp,Hp,qp,Wp,zp,Gp,Jp,Kp,Yp,Xp,Qp,Zp,em,tm,um,pm,mm,fm,gm,ym]),zi=m.object({entryNode:m.string().min(1).max(200),nodes:m.record(m.string().max(200),hm).refine(e=>Object.keys(e).length<=Mi,`Workflow has more than ${String(Mi)} nodes`),uiOnly:m.boolean().optional(),variableNamespaces:m.record(m.string().max(200),m.string().max(500)).optional(),variables:m.record(m.string().max(200),jp).optional()}),wm=Fi.record(Fi.string().max(200),qi),bm={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},Sm={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},Ex=yn("workflow-spec").legacy(bm).initial(zi).build(),Tx=yn("precondition-map").legacy(Sm).initial(wm).build(),vm=["fast","slow","async"],km=un.object({budget:un.enum(vm).describe("Polling budget tier: fast | slow | async"),description:un.string().min(1).describe("Human-readable description of what this observer checks")}).describe("A named backend state observer. Tests assert against it with assert.backend(observer, params). Implementation lives on the user's server."),de=".ripplo/ripplo.lock",Rm=5e3,Pm=G.record(G.string().max(200),G.string().max(200)),xm=G.object({coverage:G.array(G.string().max(500)).max(2e3).default([]),expectedOutcome:G.string().max(2e3),name:G.string().max(200),preconditions:G.array(G.string().max(200)).max(1e3),requiresKeys:Pm,slug:G.string().max(200),spec:zi}),Cm=G.object({observers:G.record(G.string().max(200),km),preconditions:G.record(G.string().max(200),qi),tests:G.array(xm).max(Rm)}),Gi=yn("ripplo-lockfile").initial(Cm).build();function Ji(e){return{observers:e.observers,preconditions:e.preconditions,tests:e.tests.filter(t=>t.implemented).map(t=>({coverage:[...t.coverage],expectedOutcome:t.expectedOutcome,name:t.name,preconditions:[...t.preconditions],requiresKeys:{...t.requiresKeys},slug:t.slug,spec:t.spec}))}}function gn(e){let t=Gi.encode(e);return`${JSON.stringify(t,$m(t),2)}
225
+ `}async function Wt({cwd:e}){let t=mn.join(e,de),r=await Em(t);return r==null?null:vp(Gi,r)}async function ue({cwd:e,result:t}){let r=Ji(t),n=mn.join(e,de);await pn.mkdir(mn.dirname(n),{recursive:!0}),await pn.writeFile(n,gn(r),"utf8")}function zt({compiled:e,existing:t}){if(t==null)return"missing";let r=gn(Ji(e)),n=gn(t);return r===n?"match":"stale"}async function Em(e){try{return await pn.readFile(e,"utf8")}catch(t){if(Tm(t)&&t.code==="ENOENT")return null;throw t}}function Tm(e){return e instanceof Error&&"code"in e}function $m(e){return function(r,n){return n===e||!Am(n)?n:Object.fromEntries(Object.entries(n).toSorted(([o],[i])=>o.localeCompare(i)))}}function Am(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import dt from"fs";import Kt from"path";var hn=["**/src/**","**/app/**","**/apps/**","**/pages/**","**/routes/**","**/components/**","**/server/**","**/api/**","**/backend/**","**/features/**","**/modules/**","**/views/**","**/ui/**","**/hooks/**","**/contexts/**","**/providers/**","**/controllers/**","**/handlers/**","**/resolvers/**","**/services/**","**/middleware/**","**/lib/**"],Ce=["**/*.gen.*","**/generated/**","**/*.d.ts","**/*.test.*","**/*.spec.*","**/node_modules/**","**/dist/**","**/build/**",".ripplo/**","**/*.md","**/.next/**","**/.turbo/**","**/.vercel/**","**/.svelte-kit/**","**/.nuxt/**","**/.astro/**","**/coverage/**","**/storybook-static/**","**/*.stories.*","**/*.story.*","**/cli/**","**/scripts/**","**/tools/**","**/__tests__/**","**/__mocks__/**","**/__fixtures__/**","**/*.config.*","**/*.setup.*","**/public/**","**/static/**","**/assets/**","**/migrations/**","**/prisma/migrations/**","**/scripts/**"];function Ki(e){return e.data}function Yi(e){return{as(t){return{data:{label:t,node:e}}}}}function Gt(e){let t=e.getPreconditions(),r=e.getObservers(),n=e.getTests();Im(n);let o={};t.forEach(a=>{o[a.name]={depends:[...a.dependsOn],description:a.description,returns:[...a.returns]}});let i={};r.forEach(a=>{i[a.name]={budget:a.budget,description:a.description}});let s=n.map(a=>jm(a,t));return{observers:i,preconditions:o,tests:s}}function Im(e){let t=new Map;e.forEach(r=>{let n=t.get(r.id);if(n!=null)throw new Error(`Duplicate test id "${r.id}" used by "${n}" and "${r.name}"`);t.set(r.id,r.name)})}function jm(e,t){let r=e.id,{accessedKeys:n,vars:o}=Om(e.requiresKeys),i=e.startsAtFn==null?void 0:e.startsAtFn(o),s=e.stepsFn==null?[]:e.stepsFn(o),a=i==null?s:[Nm(i),...s],l=Dm(a,n,e.requiresKeys,e.uiOnly),c=[];Object.keys(e.requiresKeys).length>0&&n.size===0&&e.implemented&&c.push("Test requires preconditions but never references their data \u2014 destructure and use precondition data in steps()");let u=Lm(e.requires,t);return{additionalChecks:[],coverage:e.coverage,description:e.description,expectedOutcome:e.expectedOutcome,implemented:e.implemented,name:e.name,preconditions:u,requiresKeys:{...e.requiresKeys},slug:r,spec:l,warnings:c}}function Nm(e){return Yi({type:"goto",url:{type:"static",value:e}}).as(`navigate to ${e}`)}function Om(e){let t=new Set,r={};return Object.keys(e).forEach(n=>{r[n]=new Proxy({},{get(o,i){if(typeof i=="string"){let s=`${n}.${i}`;return t.add(s),`{{${s}}}`}}})}),{accessedKeys:t,vars:r}}function Dm(e,t,r,n){let o={};e.forEach((a,l)=>{let c=`step-${String(l)}`,d=l<e.length-1?`step-${String(l+1)}`:void 0;o[c]=_m(a,c,d)});let i={};t.forEach(a=>{i[a]={default:`test-${a}`,type:"string"}});let s={...r};return{entryNode:"step-0",nodes:o,uiOnly:n,variableNamespaces:s,variables:i}}function _m(e,t,r){let{label:n,node:o}=Ki(e);return{...o,id:t,label:n,next:r}}function Lm(e,t){let r=new Map(t.map(s=>[s.name,s])),n=[],o=new Set;function i(s){o.has(s)||(o.add(s),r.get(s)?.dependsOn.forEach(a=>{i(a)}),n.push(s))}return e.forEach(s=>{i(s)}),n}import{Webhook as Vx,WebhookVerificationError as Fx}from"standardwebhooks";import{z as $}from"zod";var Bx=$.object({preconditions:$.array($.string().min(1))}),Hx=$.object({data:$.record($.string(),$.record($.string(),$.string())),preconditions:$.array($.string().min(1))}),qx=$.object({observer:$.string().min(1).max(200),params:$.record($.string().max(200),$.union([$.string(),$.number(),$.boolean()]))}),Um=$.discriminatedUnion("kind",[$.object({kind:$.literal("pass")}),$.object({kind:$.literal("retry"),reason:$.string()}),$.object({kind:$.literal("fail"),reason:$.string()})]),Wx=$.object({error:$.string().optional(),outcome:Um.optional(),success:$.boolean()});function Fe(e){let t=[];return e.tests.forEach(r=>{let n=Vm(r),o=i=>{t.push({...i,test:r.slug})};lf.forEach(i=>{i(n,r,o)})}),{diagnostics:t}}function Vm(e){let t=[],r=e.spec.entryNode,n=new Set;for(;r!=null&&!n.has(r);){n.add(r);let o=e.spec.nodes[r];if(o==null)break;t.push(o),r=o.next}return t}function Fm(e,t,r){e.forEach(n=>{n.type==="assertText"&&"operator"in n&&n.operator!=="equals"&&r({message:`${n.type} uses operator "${n.operator}" \u2014 only "equals" is allowed for determinism`,rule:"exact-text-match",step:n.label??n.id})})}function Mm(e,t,r){Object.keys(t.spec.variables??{}).length>0&&e.forEach(o=>{if(o.type==="fill"&&Qi(o.value)){let i=o.value.value;!Zi(i)&&Jm(i)&&r({message:`fill() uses hardcoded value "${i}" \u2014 consider using precondition data via {{namespace.key}}`,rule:"no-hardcoded-data",step:o.label??o.id})}})}function Bm(e,t,r){if(Object.keys(t.spec.variables??{}).length===0)return;e.some(i=>JSON.stringify(i).includes("{{"))||r({message:"Test requires preconditions but steps() never references precondition data \u2014 destructure and use it",rule:"prefer-precondition-data",step:void 0})}function Hm(e,t,r){e.forEach(n=>{(n.label==null||n.label.length===0)&&r({message:`Step "${n.id}" lacks .as("...") label \u2014 every step must be labeled`,rule:"missing-label",step:n.id})})}function qm(e,t,r){let n=new Map;e.forEach(o=>{if(o.label==null)return;let i=n.get(o.label);i==null?n.set(o.label,o.id):r({message:`Duplicate label "${o.label}" \u2014 also used by ${i}`,rule:"no-duplicate-labels",step:o.label})})}function Wm(e,t,r){let n=0;e.forEach((o,i)=>{if(!(i===0&&o.type==="goto")){if(Me(o)){n=0;return}n++,n===3&&r({message:"3+ consecutive actions without an assertion \u2014 add verification between actions",rule:"assert-after-action",step:o.label??o.id})}})}function zm(e,t,r){if(e.length===0)return;let n=e.at(-1);n!=null&&!Me(n)&&r({message:"Last step is an action, not an assertion \u2014 expectedOutcome should be verified by assertions at the end",rule:"assert-matches-outcome",step:n.label??n.id})}function Gm(e,t,r){t.implemented&&e.length===0&&r({message:"Test has zero steps",rule:"no-empty-steps",step:void 0})}function Qi(e){return!(typeof e!="object"||e==null||!("type"in e)||e.type!=="static"||!("value"in e)||typeof e.value!="string")}function Zi(e){return e.includes("{{")}function Jm(e){return e.includes("@")||/\b[a-f0-9]{8,}\b/.test(e)||/^(test|ripplo|example|sample|demo)/i.test(e)}function Me(e){return e.type.startsWith("assert")}var Km=new Set(["assertText","assertValue","assertCount","assertUrl","assertNotVisible","assertChecked","assertNotChecked","assertAttribute","assertDisabled","assertEnabled"]);function Ym(e){return Km.has(e.type)}function Xm(e,t,r){!t.implemented||e.length===0||e.some(n=>Me(n))||r({message:"Test has zero assertion steps \u2014 cannot verify expectedOutcome. Add assert.* steps.",rule:"no-assertions",step:void 0})}function Qm(e,t,r){if(!t.implemented||e.length<=3)return;let n=e.filter(i=>Me(i)).length;if(n===0)return;let o=n/e.length;if(o<.15){let i=Math.round(o*100);r({message:`Only ${String(n)}/${String(e.length)} steps are assertions (${String(i)}%) \u2014 add more verification between actions`,rule:"low-assertion-ratio",step:void 0})}}function wn(e){if(!("locator"in e)||e.locator==null)return;let t=e.locator;return t.by==="role"?`role:${t.role}:${t.name??""}`:`testId:${t.value}`}function Zm(e,t,r){e.forEach((n,o)=>{if(n.type!=="click")return;let i=wn(n);if(i==null)return;let s=e.slice(o+1,o+4);s.find(c=>c.type==="assertVisible"&&wn(c)===i)==null||s.some(c=>Ym(c)||Me(c)&&wn(c)!==i)||r({message:`click "${n.label??n.id}" is followed only by assert.visible on the same locator \u2014 verifies nothing about the click's effect`,rule:"tautological-post-click-assert",step:n.label??n.id})})}var ef=new Set(["the","is","a","an","and","or","of","to","in","on","at","for","that","this","with","be","are","was","were","it","its","as","by","from","after","before","should","will","can","still","but","not","no","so","if","then","than","user","users","page","view","shows","show","see","click","clicks","clicked","clickable","visible","appears","appear","displayed","stays","remains"]);function bn(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=3&&!ef.has(t))}function tf(e){let t=e.label==null?[]:bn(e.label);if(!("locator"in e)||e.locator==null)return t;let r=e.locator,n=r.by==="role"?r.name??"":r.value;return[...t,...bn(n)]}function rf(e,t,r){if(!t.implemented||e.length===0)return;let n=new Set(bn(t.expectedOutcome));if(n.size===0)return;let o=e.filter(s=>Me(s));if(o.length===0)return;o.some(s=>tf(s).some(a=>n.has(a)))||r({message:`No assertion references any keyword from expectedOutcome (${[...n].join(", ")}) \u2014 the outcome may not actually be verified`,rule:"expected-outcome-keyword-coverage",step:void 0})}var nf=/save|submit|create|delete|remove|send|invite|update|confirm|publish|apply|pay|subscribe|upgrade|cancel|archive|rename/i;function Xi(e){if(e.type==="upload")return!0;if(e.type!=="click")return!1;let t=e.locator,r=t.by==="role"?t.name??"":t.value;return nf.test(r)}function of(e,t,r){!t.implemented||t.spec.uiOnly===!0||e.forEach((n,o)=>{if(!Xi(n)||"uiOnly"in n&&n.uiOnly===!0)return;let i=e.slice(o+1),s=i.findIndex(d=>Xi(d)),a=s===-1?i.length:s;i.slice(0,a).some(d=>d.type==="assertObserver")||r({message:`"${n.label??n.id}" looks like it mutates backend state but no assert.backend(...) observer verifies it \u2014 the test can pass while the server is broken. You need to add an observer that checks the persisted result (see .ripplo/observers/ for examples). Only if this action truly does NOT change any server state (pure client-side interaction, presentation toggle, etc.) should you fall back to marking the step { uiOnly: true } to silence this rule.`,rule:"mutation-without-observer-coverage",step:n.label??n.id})})}function sf(e,t,r){Object.keys(t.spec.variables??{}).length!==0&&e.forEach(o=>{if(o.type!=="assertObserver")return;let i=Object.entries(o.params);i.length===0||i.some(([,a])=>Qi(a)&&Zi(a.value))||r({message:`assert.backend "${o.label??o.id}" passes only hardcoded params while the test defines precondition variables \u2014 observer assertions should reference {{namespace.key}} so they match the actual precondition data`,rule:"observer-params-reference-variables",step:o.label??o.id})})}function af(e,t,r){let n=new Set(Object.keys(t.spec.variables??{})),o=/\{\{([^{}]+?)\}\}/g;e.forEach(i=>{let a=[...JSON.stringify(i).matchAll(o)],l=[...new Set(a.map(u=>u[1]).filter(u=>u!=null&&!n.has(u)))];if(l.length===0)return;let c=l.map(u=>`{{${u}}}`).join(", "),d=[...new Set(l.map(u=>u.split(".")[0]??u))].join(", ");r({message:`"${i.label??i.id}" contains literal template string(s) ${c} \u2014 destructure the proxy in .steps(({ ${d} }) => \u2026) and pass the proxy value (e.g. \`${l[0]??""}\`) directly. Writing the template as a string bypasses type-checking and silently accepts typos.`,rule:"no-literal-template-strings",step:i.label??i.id})})}var lf=[Fm,Mm,af,Bm,Hm,qm,Wm,zm,Gm,Xm,Qm,Zm,rf,of,sf];import Nf from"picomatch";import{execFileSync as cf,spawnSync as df}from"child_process";function Q(e,t){return cf("git",[...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}function es(e,t){let r=df("git",["show",e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(r.status===0)return r.stdout;if(r.status===128)return null;throw new Error(`git show ${e} failed (${String(r.status)}): ${r.stderr}`)}import k from"typescript";import*as ts from"remeda";var rs=[["onClick","click"],["onContextMenu","click"],["onKeyDown","click"],["onKeyPress","click"],["onKeyUp","click"],["onSelect","click"],["onOpenChange","click"],["onPress","click"],["onActivate","click"],["onToggle","click"],["onOpen","click"],["onClose","click"],["onDismiss","click"],["onConfirm","click"],["onCancel","click"],["onApply","click"],["onClear","click"],["onSubmit","submit"],["onReset","submit"],["onDrop","drag"],["onDragEnd","drag"],["onDragEnter","drag"],["onDragLeave","drag"],["onDragOver","drag"],["onDragStart","drag"],["onValueChange","select"],["onSelectionChange","select"],["onChange","input"],["onCheckedChange","input"],["onInput","input"]],uf=new Map([["button","click"],["link","navigate"],["textbox","input"],["searchbox","input"],["combobox","select"],["listbox","select"]]),pf=[[/(?:^|[a-z])Button$/,"click"],[/(?:^|[a-z])(?:Link|NavLink|Anchor)$/,"navigate"],[/(?:^|[a-z])(?:Textarea|TextArea|Input|Field|SearchBox)$/,"input"],[/(?:^|[a-z])(?:Select|Combobox|ComboBox|Dropdown)$/,"select"],[/(?:^|[a-z])Form$/,"submit"]];function Jt({filePath:e,source:t}){let r=k.createSourceFile(e,t,k.ScriptTarget.Latest,!0,k.ScriptKind.TSX);return r.statements.flatMap(n=>mf({filePath:e,sf:r,stmt:n}))}function mf({filePath:e,sf:t,stmt:r}){let n=gf(r);if(n==null||ff(n))return[];let o=ns(r,t).map(i=>({id:`${e}#${n}.${i.kind}[${i.label}]`,line:i.line}));return ts.uniqueBy(o,i=>i.id)}function ff(e){return e.endsWith("Fragment")||e.endsWith("Skeleton")||/^use[A-Z]/.test(e)||/^[A-Z][A-Z0-9_]*$/.test(e)}function gf(e){if(k.isExportAssignment(e))return yf(e.expression);if(!hf(e))return null;if(k.isFunctionDeclaration(e)||k.isClassDeclaration(e))return e.name?.text??null;if(k.isVariableStatement(e)){let t=e.declarationList.declarations[0];return t!=null&&k.isIdentifier(t.name)?t.name.text:null}return null}function yf(e){return k.isIdentifier(e)?e.text:(k.isFunctionExpression(e)||k.isClassExpression(e))&&e.name!=null?e.name.text:"default"}function hf(e){if(!k.canHaveModifiers(e))return!1;let t=k.getModifiers(e);return t!=null&&t.some(r=>r.kind===k.SyntaxKind.ExportKeyword)}function ns(e,t){let r=wf(e,t),n=e.getChildren(t).flatMap(o=>ns(o,t));return r==null?n:[r,...n]}function wf(e,t){let r=bf(e);if(r==null)return null;let n=Sf(r);if(n==null)return null;let o=xf(r,n);return o==null?null:{kind:n,label:o,line:jf(t,e.getStart(t))}}function bf(e){return k.isJsxSelfClosingElement(e)&&k.isIdentifier(e.tagName)?{attrs:e.attributes,children:[],tag:e.tagName.text}:k.isJsxElement(e)&&k.isIdentifier(e.openingElement.tagName)?{attrs:e.openingElement.attributes,children:e.children,tag:e.openingElement.tagName.text}:null}function Sf({attrs:e,tag:t}){let r=pe(e,"role");return r!=null?uf.get(r)??null:kf(t,e)??Rf(t)??Pf(e)}var vf=new Map([["button",()=>"click"],["a",e=>pe(e,"href")==null?null:"navigate"],["input",e=>pe(e,"type")==="file"?"upload":"input"],["textarea",()=>"input"],["select",()=>"select"],["form",()=>"submit"]]);function kf(e,t){return vf.get(e)?.(t)??null}function Rf(e){return/^[A-Z]/.test(e)?pf.find(([t])=>t.test(e))?.[1]??null:null}function Pf(e){return rs.find(([t])=>Tf(e,t))?.[1]??null}function xf({attrs:e,children:t,tag:r},n){return n==="navigate"?pe(e,"href")??pe(e,"to"):pe(e,"aria-label")??pe(e,"label")??pe(e,"title")??pe(e,"name")??pe(e,"placeholder")??(Cf(r)?void 0:If(t))??Ef(e,n)}function Cf(e){return e==="input"||e==="textarea"||e==="select"}function Ef(e,t){let r=rs.find(([,o])=>o===t)?.[0];if(r==null)return;let n=$f(e,r);if(n!=null){if(k.isIdentifier(n))return n.text;if(k.isArrowFunction(n)||k.isFunctionExpression(n))return os(n.body)}}function os(e){if(k.isCallExpression(e)){let t=e.expression;return k.isIdentifier(t)?t.text:k.isPropertyAccessExpression(t)?t.name.text:void 0}return k.forEachChild(e,os)}function Tf(e,t){return e.properties.some(r=>k.isJsxAttribute(r)&&k.isIdentifier(r.name)&&r.name.text===t)}function is(e,t){return e.properties.find(r=>k.isJsxAttribute(r)&&k.isIdentifier(r.name)&&r.name.text===t)}function pe(e,t){let r=is(e,t);return r==null?void 0:Af(r.initializer)}function $f(e,t){let r=is(e,t);if(!(r?.initializer==null||!k.isJsxExpression(r.initializer)))return r.initializer.expression}function Af(e){if(e==null)return"";if(k.isStringLiteral(e))return e.text;if(k.isJsxExpression(e))return as(e.expression)}function If(e){let t=e.flatMap(r=>ss(r)).join(" ").trim();return t.length===0?void 0:t}function ss(e){if(k.isJsxText(e)){let t=e.text.trim();return t.length===0?[]:[t]}if(k.isJsxExpression(e)){let t=as(e.expression);return t==null?[]:[t]}return k.isJsxElement(e)?e.children.flatMap(t=>ss(t)):[]}function as(e){if(e!=null){if(k.isStringLiteral(e)||k.isNoSubstitutionTemplateLiteral(e))return e.text;if(k.isCallExpression(e)&&e.arguments.length===1){let t=e.arguments[0];if(t!=null&&(k.isStringLiteral(t)||k.isNoSubstitutionTemplateLiteral(t)))return t.text}}}function jf(e,t){return e.getLineAndCharacterOfPosition(t).line+1}var Of=Kt.join(".ripplo","coverage.d.ts");function Be({cwd:e}){Df({cwd:e,ignorePaths:Ce})}function Df({cwd:e,ignorePaths:t}){let r=He({cwd:e,ignorePaths:t});Uf({content:Lf(r),cwd:e})}function He({cwd:e,ignorePaths:t}){let n=_f({cwd:e,ignorePaths:t}).flatMap(o=>Sn({cwd:e,file:o}));return[...new Set(n)].sort((o,i)=>o.localeCompare(i))}function _f({cwd:e,ignorePaths:t}){let r=Q(["ls-files","--cached","--others","--exclude-standard","-z"],e),n=Nf([...t]);return r.split("\0").filter(o=>o.length>0&&/\.(tsx|jsx)$/.test(o)).filter(o=>!n(o)).filter(o=>dt.existsSync(Kt.join(e,o)))}function Sn({cwd:e,file:t}){let r=dt.readFileSync(Kt.join(e,t),"utf8");return Jt({filePath:t,source:r}).map(n=>n.id)}function Lf(e){let t=`// GENERATED \u2014 do not edit
226
226
  import "@ripplo/testing";
227
227
 
228
228
  declare module "@ripplo/testing" {
@@ -233,22 +233,22 @@ declare module "@ripplo/testing" {
233
233
  `:`${t}${r}
234
234
  }
235
235
  }
236
- `}function xf({content:e,cwd:t}){let r=Bt.join(t,vf);st.existsSync(r)&&st.readFileSync(r,"utf8")===e||st.writeFileSync(r,e)}import Qi from"path";import{createJiti as Cf}from"jiti";var Ef=["getObservers","getPreconditions","getTests","getUnimplemented"];function Tf(e){return e==null||typeof e!="object"?!1:Ef.every(t=>typeof Reflect.get(e,t)=="function")}function $f(e){return e===null?"null":Array.isArray(e)?"array":typeof e}async function j(e){let t=Qi.join(e,".ripplo","index.ts"),r=Qi.join(e,".ripplo");try{let o=await Cf(import.meta.url,{moduleCache:!1,sourceMaps:!0}).import(t),i=o!=null&&typeof o=="object"&&"default"in o?Reflect.get(o,"default"):o;if(!Tf(i))return{error:`${t} must default-export a RipploBuilder (got ${$f(i)})`,ok:!1};let s=Ht(i);return{builder:i,ok:!0,result:s}}catch(n){return{error:If(n,r),ok:!1}}}var Af=/\(?([^\s()]{1,500}\.ts):(\d{1,10}):(\d{1,10})\)?$/;function If(e,t){if(!(e instanceof Error))return String(e);let r=jf(e.stack,t);return r==null?e.message:`${r} \u2014 ${e.message}`}function jf(e,t){if(e==null)return;let n=e.split(`
237
- `).map(a=>Af.exec(a)).find(a=>a!=null&&a[1]!=null&&a[2]!=null&&a[3]!=null&&a[1].startsWith(t));if(n==null)return;let[,o,i,s]=n;return`${o??""}:${i??""}:${s??""}`}function R(e,t){return t==null?`Load \`/ripplo:${e}\` skill for instructions.`:`Load \`/ripplo:${e}\` skill for instructions on ${t}.`}function Zi(e){return e.length===1?R(e[0]):`REQUIRED before proceeding: load ${e.map(r=>`\`/ripplo:${r}\``).join(" AND ")} skills (load every one \u2014 each carries rules the others don't).`}async function es(e){let t=process.cwd(),r=await j(t);if(r.ok||(process.stderr.write(`Compilation failed: ${r.error}
236
+ `}function Uf({content:e,cwd:t}){let r=Kt.join(t,Of);dt.existsSync(r)&&dt.readFileSync(r,"utf8")===e||dt.writeFileSync(r,e)}import ls from"path";import{createJiti as Vf}from"jiti";var Ff=["getObservers","getPreconditions","getTests","getUnimplemented"];function Mf(e){return e==null||typeof e!="object"?!1:Ff.every(t=>typeof Reflect.get(e,t)=="function")}function Bf(e){return e===null?"null":Array.isArray(e)?"array":typeof e}async function j(e){let t=ls.join(e,".ripplo","index.ts"),r=ls.join(e,".ripplo");try{let o=await Vf(import.meta.url,{moduleCache:!1,sourceMaps:!0}).import(t),i=o!=null&&typeof o=="object"&&"default"in o?Reflect.get(o,"default"):o;if(!Mf(i))return{error:`${t} must default-export a RipploBuilder (got ${Bf(i)})`,ok:!1};let s=Gt(i);return{builder:i,ok:!0,result:s}}catch(n){return{error:qf(n,r),ok:!1}}}var Hf=/\(?([^\s()]{1,500}\.ts):(\d{1,10}):(\d{1,10})\)?$/;function qf(e,t){if(!(e instanceof Error))return String(e);let r=Wf(e.stack,t);return r==null?e.message:`${r} \u2014 ${e.message}`}function Wf(e,t){if(e==null)return;let n=e.split(`
237
+ `).map(a=>Hf.exec(a)).find(a=>a!=null&&a[1]!=null&&a[2]!=null&&a[3]!=null&&a[1].startsWith(t));if(n==null)return;let[,o,i,s]=n;return`${o??""}:${i??""}:${s??""}`}function R(e,t){return t==null?`Load \`/ripplo:${e}\` skill for instructions.`:`Load \`/ripplo:${e}\` skill for instructions on ${t}.`}function cs(e){return e.length===1?R(e[0]):`REQUIRED before proceeding: load ${e.map(r=>`\`/ripplo:${r}\``).join(" AND ")} skills (load every one \u2014 each carries rules the others don't).`}async function ds(e){let t=process.cwd(),r=await j(t);if(r.ok||(process.stderr.write(`Compilation failed: ${r.error}
238
238
  `),process.stderr.write(`${R("create","DSL authoring + lint rules")}
239
- `),process.exit(1)),e.check){let n=await Ft({cwd:t}),o=Mt({compiled:r.result,existing:n});if(o==="match"){process.stdout.write(`${ce} is up to date
240
- `);return}let i=o==="missing"?"missing":"out of date";process.stderr.write(`${ce} is ${i} \u2014 run \`ripplo compile\` and commit the result
239
+ `),process.exit(1)),e.check){let n=await Wt({cwd:t}),o=zt({compiled:r.result,existing:n});if(o==="match"){process.stdout.write(`${de} is up to date
240
+ `);return}let i=o==="missing"?"missing":"out of date";process.stderr.write(`${de} is ${i} \u2014 run \`ripplo compile\` and commit the result
241
241
  `),process.stderr.write(`${R("setup")}
242
- `),process.exit(1)}await de({cwd:t,result:r.result}),Fe({cwd:t}),process.stdout.write(`wrote ${ce}
243
- `)}import ye from"process";import Nf from"fs";import Of from"path";import Df from"picomatch";function ts({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(Me({cwd:t,ignorePaths:r})),o=os(e),i=Lf({cwd:t,ignorePaths:r});return ns({acknowledged:o,allStatements:n,unacked:i})}function rs({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(Me({cwd:t,ignorePaths:r})),o=os(e);return ns({acknowledged:o,allStatements:n,unacked:n})}function ns({acknowledged:e,allStatements:t,unacked:r}){let n=[...r].filter(i=>!e.has(i)).map(i=>({id:i,kind:"unacknowledged"})),o=[...e].filter(i=>!t.has(i)).map(i=>({id:i,kind:"stale"}));return[...n,...o]}function os(e){return new Set(e.tests.flatMap(t=>t.coverage))}function Lf({cwd:e,ignorePaths:t}){let r=_f({cwd:e,ignorePaths:t}),n=new Set(r.flatMap(i=>Uf({cwd:e,file:i}))),o=new Set(r.flatMap(i=>Vf({cwd:e,file:i})?fn({cwd:e,file:i}):[]));return new Set([...o].filter(i=>!n.has(i)))}function _f({cwd:e,ignorePaths:t}){let r=X(["diff","--name-only","HEAD","-z"],e),n=X(["ls-files","--others","--exclude-standard","-z"],e),o=Df([...t]);return[...new Set([...r.split("\0"),...n.split("\0")])].filter(i=>i.length>0&&/\.(tsx|jsx)$/.test(i)).filter(i=>!o(i))}function Uf({cwd:e,file:t}){let r=Bi(`HEAD:${t}`,e);return r==null?[]:qt({filePath:t,source:r}).map(n=>n.id)}function Vf({cwd:e,file:t}){return Nf.existsSync(Of.join(e,t))}async function is(){let e=ye.cwd(),t=await j(e);t.ok||(ye.stderr.write(`Compilation failed: ${t.error}
244
- `),ye.exit(1));let r=Me({cwd:e,ignorePaths:Pe}),n=rs({compileResult:t.result,cwd:e,ignorePaths:Pe}),o=n.filter(a=>a.kind==="unacknowledged"),i=n.filter(a=>a.kind==="stale"),s=r.length-o.length;ye.stdout.write(`Coverage: ${String(s)}/${String(r.length)} statements acknowledged
245
- `),o.length>0&&(ye.stdout.write(`
242
+ `),process.exit(1)}await ue({cwd:t,result:r.result}),Be({cwd:t}),process.stdout.write(`wrote ${de}
243
+ `)}import he from"process";import zf from"fs";import Gf from"path";import Jf from"picomatch";function us({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(He({cwd:t,ignorePaths:r})),o=fs(e),i=Kf({cwd:t,ignorePaths:r});return ms({acknowledged:o,allStatements:n,unacked:i})}function ps({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(He({cwd:t,ignorePaths:r})),o=fs(e);return ms({acknowledged:o,allStatements:n,unacked:n})}function ms({acknowledged:e,allStatements:t,unacked:r}){let n=[...r].filter(i=>!e.has(i)).map(i=>({id:i,kind:"unacknowledged"})),o=[...e].filter(i=>!t.has(i)).map(i=>({id:i,kind:"stale"}));return[...n,...o]}function fs(e){return new Set(e.tests.flatMap(t=>t.coverage))}function Kf({cwd:e,ignorePaths:t}){let r=Yf({cwd:e,ignorePaths:t}),n=new Set(r.flatMap(i=>Xf({cwd:e,file:i}))),o=new Set(r.flatMap(i=>Qf({cwd:e,file:i})?Sn({cwd:e,file:i}):[]));return new Set([...o].filter(i=>!n.has(i)))}function Yf({cwd:e,ignorePaths:t}){let r=Q(["diff","--name-only","HEAD","-z"],e),n=Q(["ls-files","--others","--exclude-standard","-z"],e),o=Jf([...t]);return[...new Set([...r.split("\0"),...n.split("\0")])].filter(i=>i.length>0&&/\.(tsx|jsx)$/.test(i)).filter(i=>!o(i))}function Xf({cwd:e,file:t}){let r=es(`HEAD:${t}`,e);return r==null?[]:Jt({filePath:t,source:r}).map(n=>n.id)}function Qf({cwd:e,file:t}){return zf.existsSync(Gf.join(e,t))}async function gs(){let e=he.cwd(),t=await j(e);t.ok||(he.stderr.write(`Compilation failed: ${t.error}
244
+ `),he.exit(1));let r=He({cwd:e,ignorePaths:Ce}),n=ps({compileResult:t.result,cwd:e,ignorePaths:Ce}),o=n.filter(a=>a.kind==="unacknowledged"),i=n.filter(a=>a.kind==="stale"),s=r.length-o.length;he.stdout.write(`Coverage: ${String(s)}/${String(r.length)} statements acknowledged
245
+ `),o.length>0&&(he.stdout.write(`
246
246
  Unacknowledged (${String(o.length)}):
247
- `),o.forEach(a=>ye.stdout.write(` ${a.id}
248
- `))),i.length>0&&(ye.stdout.write(`
247
+ `),o.forEach(a=>he.stdout.write(` ${a.id}
248
+ `))),i.length>0&&(he.stdout.write(`
249
249
  Stale claims (${String(i.length)}):
250
- `),i.forEach(a=>ye.stdout.write(` ${a.id}
251
- `))),n.length>0&&ye.exit(1)}import hn from"fs";import Wf from"path";import{chromium as zf}from"playwright";import{graphql as Mf}from"gql.tada";import ss from"fs";import gn from"path";function as(e){let t=ss.realpathSync(e),r=t,n=gn.dirname(r);for(;n!==r;){if(ss.existsSync(gn.join(r,".git")))return r;r=n,n=gn.dirname(r)}return t}function B(e){let t=ir(e),r=Ie(),n=ne();if(n==null)throw new Error("ripplo: not authenticated. Run `ripplo auth login`.");return{appUrl:r.appUrl,cwd:as(e),engineUrl:r.engineUrl,projectId:t.projectId,ripploServerUrl:ge(),token:n,webhookSecret:r.webhookSecret}}import at from"fs";var Ff="dev.pid";function ls(e){return rt(e,Ff)}function He(e){let t=ls(e);if(!at.existsSync(t))return!1;let r=at.readFileSync(t,"utf8").trim(),n=Number.parseInt(r,10);if(!Number.isFinite(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch{return!1}}function cs(e){tt(e);let t=ls(e);at.writeFileSync(t,String(process.pid));let r=!1;return()=>{if(!r){r=!0;try{let n=at.readFileSync(t,"utf8").trim();Number.parseInt(n,10)===process.pid&&at.unlinkSync(t)}catch{}}}}var Hf=Mf(`
250
+ `),i.forEach(a=>he.stdout.write(` ${a.id}
251
+ `))),n.length>0&&he.exit(1)}import Rn from"fs";import og from"path";import{chromium as ig}from"playwright";import{graphql as eg}from"gql.tada";import ys from"fs";import vn from"path";function hs(e){let t=ys.realpathSync(e),r=t,n=vn.dirname(r);for(;n!==r;){if(ys.existsSync(vn.join(r,".git")))return r;r=n,n=vn.dirname(r)}return t}function q(e){let t=ur(e),r=je(),n=oe();if(n==null)throw new Error("ripplo: not authenticated. Run `ripplo auth login`.");return{appUrl:r.appUrl,cwd:hs(e),engineUrl:r.engineUrl,projectId:Oi()??t.projectId,ripploServerUrl:ye(),token:n,webhookSecret:r.webhookSecret}}import ut from"fs";var Zf="dev.pid";function ws(e){return st(e,Zf)}function qe(e){let t=ws(e);if(!ut.existsSync(t))return!1;let r=ut.readFileSync(t,"utf8").trim(),n=Number.parseInt(r,10);if(!Number.isFinite(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch{return!1}}function bs(e){it(e);let t=ws(e);ut.writeFileSync(t,String(process.pid));let r=!1;return()=>{if(!r){r=!0;try{let n=ut.readFileSync(t,"utf8").trim();Number.parseInt(n,10)===process.pid&&ut.unlinkSync(t)}catch{}}}}var tg=eg(`
252
252
  query DevSessionCheckHealth($projectId: String!, $cwd: String!) {
253
253
  project(id: $projectId) {
254
254
  id
@@ -257,18 +257,18 @@ Stale claims (${String(i.length)}):
257
257
  }
258
258
  }
259
259
  }
260
- `);function ds(e){switch(e.status){case"active":return"\u2713 Dev session: ripplo watch is live for this directory";case"starting":return"! Dev session: `ripplo watch` is running locally but hasn't registered with the server yet. Wait a few seconds and re-run `npx ripplo doctor`. If it persists, check the watch process output for auth/network errors.";case"missing":return"\u2717 Dev session: no active ripplo watch. Start `npx ripplo watch` as a background process (separate from your app's dev server). Without it, `ripplo run` will refuse to dispatch and scope/coverage hooks won't arm."}}async function us(e){let t=He(e),r;try{r=B(e)}catch{return{status:t?"starting":"missing",type:"dev-session"}}return(await b({config:r,document:Hf,variables:{cwd:r.cwd,projectId:r.projectId}}).catch(()=>null))?.project?.devSession!=null?{status:"active",type:"dev-session"}:{status:t?"starting":"missing",type:"dev-session"}}import qf from"fs";import Bf from"path";async function ps(e){let t=Bf.join(e,".ripplo","index.ts");if(!qf.existsSync(t))return{appUrl:void 0,engineUrl:void 0,errors:[{message:".ripplo/index.ts not found",path:""}],valid:!1,warnings:[]};let r=await j(e);if(!r.ok)return{appUrl:void 0,engineUrl:void 0,errors:[{message:r.error,path:".ripplo/"}],valid:!1,warnings:[]};try{let n=Ie();return{appUrl:n.appUrl,engineUrl:n.engineUrl,errors:[],valid:!0,warnings:[]}}catch(n){return{appUrl:void 0,engineUrl:void 0,errors:[{message:n instanceof Error?n.message:String(n),path:""}],valid:!1,warnings:[]}}}async function yn(e){try{await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(5e3)});return}catch{return`appUrl (${e}) is not responding. Make sure your dev server is running on that port.`}}async function ms({appUrl:e,engineUrl:t}){let r=t.startsWith("http://")||t.startsWith("https://")?t:`${e}${t}`;try{return(await fetch(`${r}/execute-preconditions`,{body:JSON.stringify({preconditions:[]}),headers:{"Content-Type":"application/json"},method:"PUT",signal:AbortSignal.timeout(5e3)})).ok?"Engine endpoint accepted an unsigned request \u2014 webhook signature verification may be missing.":void 0}catch{return}}function fs(e){switch(e.type){case"settings":return!e.valid;case"env-files":return e.missing.length>0;case"token":return!e.exists;case"dev-server":return!e.reachable;case"dev-session":return e.status!=="active";case"preconditions":return e.count>0&&!e.configured;case"engine-endpoint":return!e.reachable;case"adapter-enabled":return e.status!=="enabled";case"webhook-verification":return!e.rejectsUnsigned;case"preconditions-validation":return!e.valid;case"workflows":return e.invalidNames.length>0;case"browser":return!e.installed;case"lockfile":return e.status!=="match";case"pre-commit-hook":return!e.installed}}async function gs(e){let t=await Kf(e),r={missing:lr(e),type:"env-files"},n=Yf(),o=Xf(),i=await j(e),s=Qf(i),a=tg(i),l=await Gf(e,i),c=Jf(e),d=await rg(t,i);return[t,r,n,...d,s,a,l,c,o]}async function Gf(e,t){if(!t.ok)return{status:"missing",type:"lockfile"};let r=await Ft({cwd:e});return{status:Mt({compiled:t.result,existing:r}),type:"lockfile"}}function Jf(e){let t=Wf.join(e,".git","hooks","pre-commit");return hn.existsSync(t)?{installed:hn.readFileSync(t,"utf8").includes("ripplo compile --check"),type:"pre-commit-hook"}:{installed:!1,type:"pre-commit-hook"}}async function Kf(e){let t=await ps(e);return t.valid?{missingFields:[],type:"settings",valid:!0}:{missingFields:t.errors.map(n=>n.path).filter(n=>n.length>0),type:"settings",valid:!1}}function Yf(){let e=ne();return{exists:e!=null&&e.length>0,type:"token"}}function Xf(){let e=zf.executablePath();return{installed:hn.existsSync(e),type:"browser"}}function Qf(e){if(!e.ok)return{errorCount:1,errors:[{message:e.error,path:""}],found:!1,type:"preconditions-validation",valid:!1};let t=Zf(e.result.preconditions,e.result.tests);return{errorCount:t.length,errors:t,found:!0,type:"preconditions-validation",valid:t.length===0}}function Zf(e,t){let r=[],n=new Set(Object.keys(e));return Object.entries(e).forEach(([o,i])=>{(i.depends??[]).forEach(s=>{n.has(s)||r.push({message:`Depends on non-existent precondition "${s}"`,path:`preconditions.${o}.depends`})})}),t.forEach(o=>{Object.entries(o.requiresKeys).forEach(([i,s])=>{n.has(s)||r.push({message:`Test "${o.slug}" requires non-existent precondition "${s}" (as ${i})`,path:`tests.${o.slug}.requiresKeys.${i}`})})}),eg(e).forEach(o=>{r.push({message:o,path:"preconditions"})}),r}function eg(e){let t=new Set,r=new Set,n=[];function o(i){if(r.has(i)){n.push(`Precondition "${i}" has a circular dependency`);return}t.has(i)||(t.add(i),r.add(i),(e[i]?.depends??[]).forEach(s=>{o(s)}),r.delete(i))}return Object.keys(e).forEach(i=>{o(i)}),n}function tg(e){if(!e.ok)return{invalidNames:[],invalidWorkflows:[],total:0,type:"workflows",valid:0};let t=e.result.tests.length;return{invalidNames:[],invalidWorkflows:[],total:t,type:"workflows",valid:t}}async function rg(e,t){if(!e.valid||!t.ok)return[];let r;try{let a=Ie();r={appUrl:a.appUrl,engineUrl:a.engineUrl,webhookSecret:a.webhookSecret}}catch{return[]}let n=[],o=await yn(r.appUrl)==null;n.push({appUrl:r.appUrl,reachable:o,type:"dev-server"});let i=await us(process.cwd());n.push(i);let s=await ng(r,t);return n.push(...s),n}async function ng(e,t){let r=t.ok?Object.keys(t.result.preconditions).length:0,n=e.engineUrl.length>0,o={configured:n,count:r,endpointReachable:void 0,type:"preconditions"};if(r===0||!n)return[o];let i=sg(e.appUrl,e.engineUrl);if(i==null)return[o];let s=await yn(i)==null,a=[];if(a.push({configured:!0,count:r,endpointReachable:s,type:"preconditions"}),ys(e.engineUrl)&&a.push({reachable:s,type:"engine-endpoint",url:i}),!s)return a;let l=await ms({appUrl:e.appUrl,engineUrl:e.engineUrl});a.push({rejectsUnsigned:l==null,type:"webhook-verification"});let c=await og({engineUrl:i,webhookSecret:e.webhookSecret});return a.push({status:c,type:"adapter-enabled",url:i}),a}async function og({engineUrl:e,webhookSecret:t}){if(t.length===0)return"no-secret";let r=JSON.stringify({preconditions:[]});try{let n=await fetch(`${e}/execute-preconditions`,{body:r,headers:{"Content-Type":"application/json",...ke({body:r,secret:t})},method:"PUT",signal:AbortSignal.timeout(5e3)});return n.status===404?"disabled":n.status===401||n.status===403?"bad-secret":"enabled"}catch{return"unreachable"}}function ig(e){switch(e.status){case"enabled":return`\u2713 Adapter: enabled at ${e.url}`;case"disabled":return"\u2717 Adapter: disabled (handler returned 404). Set ENABLE_RIPPLO_TESTING=true in your app's env (e.g. apps/<app>/.env.local for Next.js) and restart the dev server.";case"bad-secret":return"\u2717 Adapter: webhook signature rejected. RIPPLO_WEBHOOK_SECRET seen by your dev server does not match the one in your env file.";case"unreachable":return`\u2717 Adapter: ${e.url} could not be reached for signed probe.`;case"no-secret":return"\u2717 Adapter: RIPPLO_WEBHOOK_SECRET is not set in your env file (declared in .ripplo/project.json)."}}function ys(e){return e.startsWith("http://")||e.startsWith("https://")}function sg(e,t){return ys(t)?t:`${e}${t}`}function hs(e){switch(e.type){case"settings":return cg(e);case"env-files":return dg(e);case"token":return ug(e);case"dev-server":return pg(e);case"dev-session":return ds(e);case"preconditions":return gg(e);case"webhook-verification":return mg(e);case"preconditions-validation":return yg(e);case"workflows":return hg(e);case"browser":return fg(e);case"engine-endpoint":return e.reachable?`\u2713 Engine endpoint: ${e.url} is reachable`:`\u2717 Engine endpoint: ${e.url} is not reachable`;case"adapter-enabled":return ig(e);case"lockfile":return ag(e);case"pre-commit-hook":return lg(e)}}function ag(e){switch(e.status){case"match":return`\u2713 Lockfile: ${ce} is up to date`;case"missing":return`\u2717 Lockfile: ${ce} is missing \u2014 run \`ripplo compile\` and commit it`;case"stale":return`\u2717 Lockfile: ${ce} is out of date \u2014 run \`ripplo compile\` and commit it`}}function lg(e){return e.installed?"\u2713 Pre-commit hook: .git/hooks/pre-commit runs `ripplo compile --check`":"! Pre-commit hook: .git/hooks/pre-commit does not run `ripplo compile --check` \u2014 see the setup skill for the snippet"}function cg(e){return e.valid?"\u2713 Settings: Project configured":`\u2717 Settings: Missing fields: ${e.missingFields.join(", ")}`}function dg(e){return e.missing.length===0?"\u2713 Env files: declared files present":`\u2717 Env files: declared in .ripplo/project.json but missing:
260
+ `);function Ss(e){switch(e.status){case"active":return"\u2713 Dev session: ripplo watch is live for this directory";case"starting":return"! Dev session: `ripplo watch` is running locally but hasn't registered with the server yet. Wait a few seconds and re-run `npx ripplo doctor`. If it persists, check the watch process output for auth/network errors.";case"missing":return"\u2717 Dev session: no active ripplo watch. Start `npx ripplo watch` as a background process (separate from your app's dev server). Without it, `ripplo run` will refuse to dispatch and scope/coverage hooks won't arm."}}async function vs(e){let t=qe(e),r;try{r=q(e)}catch{return{status:t?"starting":"missing",type:"dev-session"}}return(await b({config:r,document:tg,variables:{cwd:r.cwd,projectId:r.projectId}}).catch(()=>null))?.project?.devSession!=null?{status:"active",type:"dev-session"}:{status:t?"starting":"missing",type:"dev-session"}}import rg from"fs";import ng from"path";async function ks(e){let t=ng.join(e,".ripplo","index.ts");if(!rg.existsSync(t))return{appUrl:void 0,engineUrl:void 0,errors:[{message:".ripplo/index.ts not found",path:""}],valid:!1,warnings:[]};let r=await j(e);if(!r.ok)return{appUrl:void 0,engineUrl:void 0,errors:[{message:r.error,path:".ripplo/"}],valid:!1,warnings:[]};try{let n=je();return{appUrl:n.appUrl,engineUrl:n.engineUrl,errors:[],valid:!0,warnings:[]}}catch(n){return{appUrl:void 0,engineUrl:void 0,errors:[{message:n instanceof Error?n.message:String(n),path:""}],valid:!1,warnings:[]}}}async function kn(e){try{await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(5e3)});return}catch{return`appUrl (${e}) is not responding. Make sure your dev server is running on that port.`}}async function Rs({appUrl:e,engineUrl:t}){let r=t.startsWith("http://")||t.startsWith("https://")?t:`${e}${t}`;try{return(await fetch(`${r}/execute-preconditions`,{body:JSON.stringify({preconditions:[]}),headers:{"Content-Type":"application/json"},method:"PUT",signal:AbortSignal.timeout(5e3)})).ok?"Engine endpoint accepted an unsigned request \u2014 webhook signature verification may be missing.":void 0}catch{return}}function Ps(e){switch(e.type){case"settings":return!e.valid;case"env-files":return e.missing.length>0;case"token":return!e.exists;case"dev-server":return!e.reachable;case"dev-session":return e.status!=="active";case"preconditions":return e.count>0&&!e.configured;case"engine-endpoint":return!e.reachable;case"adapter-enabled":return e.status!=="enabled";case"webhook-verification":return!e.rejectsUnsigned;case"preconditions-validation":return!e.valid;case"workflows":return e.invalidNames.length>0;case"browser":return!e.installed;case"lockfile":return e.status!=="match";case"pre-commit-hook":return!e.installed}}async function xs(e){let t=await lg(e),r={missing:fr(e),type:"env-files"},n=cg(),o=dg(),i=await j(e),s=ug(i),a=fg(i),l=await sg(e,i),c=ag(e),d=await gg(t,i);return[t,r,n,...d,s,a,l,c,o]}async function sg(e,t){if(!t.ok)return{status:"missing",type:"lockfile"};let r=await Wt({cwd:e});return{status:zt({compiled:t.result,existing:r}),type:"lockfile"}}function ag(e){let t=og.join(e,".git","hooks","pre-commit");return Rn.existsSync(t)?{installed:Rn.readFileSync(t,"utf8").includes("ripplo compile --check"),type:"pre-commit-hook"}:{installed:!1,type:"pre-commit-hook"}}async function lg(e){let t=await ks(e);return t.valid?{missingFields:[],type:"settings",valid:!0}:{missingFields:t.errors.map(n=>n.path).filter(n=>n.length>0),type:"settings",valid:!1}}function cg(){let e=oe();return{exists:e!=null&&e.length>0,type:"token"}}function dg(){let e=ig.executablePath();return{installed:Rn.existsSync(e),type:"browser"}}function ug(e){if(!e.ok)return{errorCount:1,errors:[{message:e.error,path:""}],found:!1,type:"preconditions-validation",valid:!1};let t=pg(e.result.preconditions,e.result.tests);return{errorCount:t.length,errors:t,found:!0,type:"preconditions-validation",valid:t.length===0}}function pg(e,t){let r=[],n=new Set(Object.keys(e));return Object.entries(e).forEach(([o,i])=>{(i.depends??[]).forEach(s=>{n.has(s)||r.push({message:`Depends on non-existent precondition "${s}"`,path:`preconditions.${o}.depends`})})}),t.forEach(o=>{Object.entries(o.requiresKeys).forEach(([i,s])=>{n.has(s)||r.push({message:`Test "${o.slug}" requires non-existent precondition "${s}" (as ${i})`,path:`tests.${o.slug}.requiresKeys.${i}`})})}),mg(e).forEach(o=>{r.push({message:o,path:"preconditions"})}),r}function mg(e){let t=new Set,r=new Set,n=[];function o(i){if(r.has(i)){n.push(`Precondition "${i}" has a circular dependency`);return}t.has(i)||(t.add(i),r.add(i),(e[i]?.depends??[]).forEach(s=>{o(s)}),r.delete(i))}return Object.keys(e).forEach(i=>{o(i)}),n}function fg(e){if(!e.ok)return{invalidNames:[],invalidWorkflows:[],total:0,type:"workflows",valid:0};let t=e.result.tests.length;return{invalidNames:[],invalidWorkflows:[],total:t,type:"workflows",valid:t}}async function gg(e,t){if(!e.valid||!t.ok)return[];let r;try{let a=je();r={appUrl:a.appUrl,engineUrl:a.engineUrl,webhookSecret:a.webhookSecret}}catch{return[]}let n=[],o=await kn(r.appUrl)==null;n.push({appUrl:r.appUrl,reachable:o,type:"dev-server"});let i=await vs(process.cwd());n.push(i);let s=await yg(r,t);return n.push(...s),n}async function yg(e,t){let r=t.ok?Object.keys(t.result.preconditions).length:0,n=e.engineUrl.length>0,o={configured:n,count:r,endpointReachable:void 0,type:"preconditions"};if(r===0||!n)return[o];let i=bg(e.appUrl,e.engineUrl);if(i==null)return[o];let s=await kn(i)==null,a=[];if(a.push({configured:!0,count:r,endpointReachable:s,type:"preconditions"}),Cs(e.engineUrl)&&a.push({reachable:s,type:"engine-endpoint",url:i}),!s)return a;let l=await Rs({appUrl:e.appUrl,engineUrl:e.engineUrl});a.push({rejectsUnsigned:l==null,type:"webhook-verification"});let c=await hg({engineUrl:i,webhookSecret:e.webhookSecret});return a.push({status:c,type:"adapter-enabled",url:i}),a}async function hg({engineUrl:e,webhookSecret:t}){if(t.length===0)return"no-secret";let r=JSON.stringify({preconditions:[]});try{let n=await fetch(`${e}/execute-preconditions`,{body:r,headers:{"Content-Type":"application/json",...Pe({body:r,secret:t})},method:"PUT",signal:AbortSignal.timeout(5e3)});return n.status===404?"disabled":n.status===401||n.status===403?"bad-secret":"enabled"}catch{return"unreachable"}}function wg(e){switch(e.status){case"enabled":return`\u2713 Adapter: enabled at ${e.url}`;case"disabled":return"\u2717 Adapter: disabled (handler returned 404). Set ENABLE_RIPPLO_TESTING=true in your app's env (e.g. apps/<app>/.env.local for Next.js) and restart the dev server.";case"bad-secret":return"\u2717 Adapter: webhook signature rejected. RIPPLO_WEBHOOK_SECRET seen by your dev server does not match the one in your env file.";case"unreachable":return`\u2717 Adapter: ${e.url} could not be reached for signed probe.`;case"no-secret":return"\u2717 Adapter: RIPPLO_WEBHOOK_SECRET is not set in your env file (declared in .ripplo/project.json)."}}function Cs(e){return e.startsWith("http://")||e.startsWith("https://")}function bg(e,t){return Cs(t)?t:`${e}${t}`}function Es(e){switch(e.type){case"settings":return kg(e);case"env-files":return Rg(e);case"token":return Pg(e);case"dev-server":return xg(e);case"dev-session":return Ss(e);case"preconditions":return Tg(e);case"webhook-verification":return Cg(e);case"preconditions-validation":return $g(e);case"workflows":return Ag(e);case"browser":return Eg(e);case"engine-endpoint":return e.reachable?`\u2713 Engine endpoint: ${e.url} is reachable`:`\u2717 Engine endpoint: ${e.url} is not reachable`;case"adapter-enabled":return wg(e);case"lockfile":return Sg(e);case"pre-commit-hook":return vg(e)}}function Sg(e){switch(e.status){case"match":return`\u2713 Lockfile: ${de} is up to date`;case"missing":return`\u2717 Lockfile: ${de} is missing \u2014 run \`ripplo compile\` and commit it`;case"stale":return`\u2717 Lockfile: ${de} is out of date \u2014 run \`ripplo compile\` and commit it`}}function vg(e){return e.installed?"\u2713 Pre-commit hook: .git/hooks/pre-commit runs `ripplo compile --check`":"! Pre-commit hook: .git/hooks/pre-commit does not run `ripplo compile --check` \u2014 see the setup skill for the snippet"}function kg(e){return e.valid?"\u2713 Settings: Project configured":`\u2717 Settings: Missing fields: ${e.missingFields.join(", ")}`}function Rg(e){return e.missing.length===0?"\u2713 Env files: declared files present":`\u2717 Env files: declared in .ripplo/project.json but missing:
261
261
  ${e.missing.map(r=>` ${r}`).join(`
262
262
  `)}
263
- If you're in a git worktree, copy the env file from the main checkout (or symlink to a shared file outside the working tree).`}function ug(e){return e.exists?"\u2713 Auth: Token found":"\u2717 Auth: No token found. Run `ripplo` to authenticate."}function pg(e){return e.reachable?`\u2713 Dev server: ${e.appUrl} is reachable`:`\u2717 Dev server: ${e.appUrl} is not responding. Make sure your dev server is running.`}function mg(e){return e.rejectsUnsigned?"\u2713 Webhook verification: Unsigned requests are correctly rejected":"\u2717 Webhook verification: Endpoint accepted an unsigned request \u2014 webhook signature verification may be missing or misconfigured."}function fg(e){return e.installed?"\u2713 Browser: Chromium installed":"\u2717 Browser: Chromium not installed. Run: npx playwright install chromium"}function gg(e){return e.count===0?"! Preconditions: None defined":e.configured?e.endpointReachable===void 0?`! Preconditions: ${String(e.count)} defined (could not verify endpoint)`:`\u2713 Preconditions: ${String(e.count)} defined, endpoint configured`:`\u2717 Preconditions: ${String(e.count)} defined but RIPPLO_ENGINE_URL is not set in your env file`}function yg(e){if(!e.found)return"\u2717 State graph: DSL compilation failed";if(e.valid)return"\u2713 State graph: Valid";let t=e.errors.map(r=>` - ${r.path===""?"":r.path+": "}${r.message}`);return`\u2717 State graph: ${String(e.errorCount)} validation error${e.errorCount===1?"":"s"}
263
+ If you're in a git worktree, copy the env file from the main checkout (or symlink to a shared file outside the working tree).`}function Pg(e){return e.exists?"\u2713 Auth: Token found":"\u2717 Auth: No token found. Run `ripplo` to authenticate."}function xg(e){return e.reachable?`\u2713 Dev server: ${e.appUrl} is reachable`:`\u2717 Dev server: ${e.appUrl} is not responding. Make sure your dev server is running.`}function Cg(e){return e.rejectsUnsigned?"\u2713 Webhook verification: Unsigned requests are correctly rejected":"\u2717 Webhook verification: Endpoint accepted an unsigned request \u2014 webhook signature verification may be missing or misconfigured."}function Eg(e){return e.installed?"\u2713 Browser: Chromium installed":"\u2717 Browser: Chromium not installed. Run: npx playwright install chromium"}function Tg(e){return e.count===0?"! Preconditions: None defined":e.configured?e.endpointReachable===void 0?`! Preconditions: ${String(e.count)} defined (could not verify endpoint)`:`\u2713 Preconditions: ${String(e.count)} defined, endpoint configured`:`\u2717 Preconditions: ${String(e.count)} defined but RIPPLO_ENGINE_URL is not set in your env file`}function $g(e){if(!e.found)return"\u2717 State graph: DSL compilation failed";if(e.valid)return"\u2713 State graph: Valid";let t=e.errors.map(r=>` - ${r.path===""?"":r.path+": "}${r.message}`);return`\u2717 State graph: ${String(e.errorCount)} validation error${e.errorCount===1?"":"s"}
264
264
  ${t.join(`
265
- `)}`}function hg(e){if(e.total===0)return"! Tests: No tests defined";if(e.invalidNames.length===0)return`\u2713 Tests: ${String(e.total)} valid`;let t=e.invalidWorkflows.map(r=>wg(r));return`\u2717 Tests: ${String(e.invalidNames.length)} invalid
265
+ `)}`}function Ag(e){if(e.total===0)return"! Tests: No tests defined";if(e.invalidNames.length===0)return`\u2713 Tests: ${String(e.total)} valid`;let t=e.invalidWorkflows.map(r=>Ig(r));return`\u2717 Tests: ${String(e.invalidNames.length)} invalid
266
266
  ${t.join(`
267
- `)}`}function wg(e){let t=e.errors.map(r=>" - "+(r.path===""?"":r.path+": ")+r.message);return" "+e.name+`:
267
+ `)}`}function Ig(e){let t=e.errors.map(r=>" - "+(r.path===""?"":r.path+": ")+r.message);return" "+e.name+`:
268
268
  `+t.join(`
269
- `)}async function ws(){let e=process.cwd(),t=await gs(e),r=t.map(o=>hs(o));process.stdout.write(r.join(`
269
+ `)}async function Ts(){let e=process.cwd(),t=await xs(e),r=t.map(o=>Es(o));process.stdout.write(r.join(`
270
270
  `)+`
271
- `);let n=t.some(o=>fs(o));process.exit(n?1:0)}import{graphql as zt,readFragment as Cg}from"gql.tada";import Sg from"crypto";import{graphql as vg}from"gql.tada";import wn from"fs";import bn from"path";function Wt(e){try{let t=bn.join(bg(e),"HEAD"),r=wn.readFileSync(t,"utf8").trim(),n="ref: refs/heads/";return r.startsWith(n)?r.slice(n.length):r.length===0?void 0:r.slice(0,7)}catch{return}}function bg(e){let t=bn.join(e,".git");if(wn.statSync(t).isDirectory())return t;let n=wn.readFileSync(t,"utf8").trim(),o="gitdir:";if(!n.startsWith(o))throw new Error(`unrecognized .git file at ${t}`);let i=n.slice(o.length).trim();if(i.length===0)throw new Error(`empty gitdir pointer at ${t}`);return bn.resolve(e,i)}var kg=vg(`
271
+ `);let n=t.some(o=>Ps(o));process.exit(n?1:0)}import{graphql as Xt,readFragment as Vg}from"gql.tada";import Ng from"crypto";import{graphql as Og}from"gql.tada";import Pn from"fs";import xn from"path";function Yt(e){try{let t=xn.join(jg(e),"HEAD"),r=Pn.readFileSync(t,"utf8").trim(),n="ref: refs/heads/";return r.startsWith(n)?r.slice(n.length):r.length===0?void 0:r.slice(0,7)}catch{return}}function jg(e){let t=xn.join(e,".git");if(Pn.statSync(t).isDirectory())return t;let n=Pn.readFileSync(t,"utf8").trim(),o="gitdir:";if(!n.startsWith(o))throw new Error(`unrecognized .git file at ${t}`);let i=n.slice(o.length).trim();if(i.length===0)throw new Error(`empty gitdir pointer at ${t}`);return xn.resolve(e,i)}var Dg=Og(`
272
272
  mutation SyncDevSession(
273
273
  $projectId: String!
274
274
  $cwd: String!
@@ -286,12 +286,12 @@ ${t.join(`
286
286
  id
287
287
  }
288
288
  }
289
- `);async function lt(e){let t=Rg(e.compiled);return xg({config:e.config,cwd:e.cwd,payload:t})}async function $e(e,t){let r=await j(e);if(!r.ok)throw new Error(`DSL compilation failed: ${r.error}`);let n=await lt({compiled:r.result,config:t,cwd:e});return{compiled:r.result,devSessionId:n.devSessionId}}function Rg(e){return{preconditions:Object.entries(e.preconditions).map(([t,r])=>({depends:[...r.depends??[]],description:r.description,name:t,returns:[...r.returns??[]]})),workflows:e.tests.map(t=>({expectedOutcome:t.expectedOutcome,name:t.name,preconditions:[...t.preconditions],requiresKeys:Object.entries(t.requiresKeys).map(([r,n])=>({namespace:r,preconditionName:n})),slug:t.slug,spec:t.implemented?JSON.stringify(t.spec):null}))}}function Pg(e){return Sg.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function xg({config:e,cwd:t,payload:r}){let n=Pg(r),o=Wt(t),i=await b({config:e,document:kg,variables:{branch:o??null,cwd:t,preconditions:r.preconditions.map(s=>({depends:[...s.depends],description:s.description,name:s.name,returns:[...s.returns]})),projectId:e.projectId,workflows:r.workflows.map(s=>({expectedOutcome:s.expectedOutcome,name:s.name,preconditions:[...s.preconditions],requiresKeys:s.requiresKeys.map(a=>({namespace:a.namespace,preconditionName:a.preconditionName})),slug:s.slug,spec:s.spec??null}))}});if(i.syncDevSession==null)throw new Error("syncDevSession returned null");return{devSessionId:i.syncDevSession.id,hash:n}}import bs from"figures";var ct={cross:bs.cross,tick:bs.tick};var vs=zt(`
289
+ `);async function pt(e){let t=_g(e.compiled);return Ug({config:e.config,cwd:e.cwd,payload:t})}async function Ae(e,t){let r=await j(e);if(!r.ok)throw new Error(`DSL compilation failed: ${r.error}`);let n=await pt({compiled:r.result,config:t,cwd:e});return{compiled:r.result,devSessionId:n.devSessionId}}function _g(e){return{preconditions:Object.entries(e.preconditions).map(([t,r])=>({depends:[...r.depends??[]],description:r.description,name:t,returns:[...r.returns??[]]})),workflows:e.tests.map(t=>({expectedOutcome:t.expectedOutcome,name:t.name,preconditions:[...t.preconditions],requiresKeys:Object.entries(t.requiresKeys).map(([r,n])=>({namespace:r,preconditionName:n})),slug:t.slug,spec:t.implemented?JSON.stringify(t.spec):null}))}}function Lg(e){return Ng.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function Ug({config:e,cwd:t,payload:r}){let n=Lg(r),o=Yt(t),i=await b({config:e,document:Dg,variables:{branch:o??null,cwd:t,preconditions:r.preconditions.map(s=>({depends:[...s.depends],description:s.description,name:s.name,returns:[...s.returns]})),projectId:e.projectId,workflows:r.workflows.map(s=>({expectedOutcome:s.expectedOutcome,name:s.name,preconditions:[...s.preconditions],requiresKeys:s.requiresKeys.map(a=>({namespace:a.namespace,preconditionName:a.preconditionName})),slug:s.slug,spec:s.spec??null}))}});if(i.syncDevSession==null)throw new Error("syncDevSession returned null");return{devSessionId:i.syncDevSession.id,hash:n}}import $s from"figures";var mt={cross:$s.cross,tick:$s.tick};var Is=Xt(`
290
290
  fragment WorkflowIdMCP on Workflow {
291
291
  id
292
292
  slug
293
293
  }
294
- `),Eg=zt(`
294
+ `),Fg=Xt(`
295
295
  query ProjectWorkflowIdsMCP($projectId: String!, $cwd: String!) {
296
296
  project(id: $projectId) {
297
297
  id
@@ -303,14 +303,14 @@ ${t.join(`
303
303
  }
304
304
  }
305
305
  }
306
- `,[vs]),Tg=zt(`
306
+ `,[Is]),Mg=Xt(`
307
307
  mutation CreateRunMCP($workflowId: String!, $platforms: [String!]!, $concurrency: Int!) {
308
308
  createRun(workflowId: $workflowId, platforms: $platforms, concurrency: $concurrency) {
309
309
  id
310
310
  status
311
311
  }
312
312
  }
313
- `),$g=zt(`
313
+ `),Bg=Xt(`
314
314
  query RunStatusMCP($id: String!) {
315
315
  run(id: $id) {
316
316
  id
@@ -337,8 +337,8 @@ ${t.join(`
337
337
  }
338
338
  }
339
339
  }
340
- `);async function Gt({config:e,ids:t}){let r=await Ag({config:e,ids:t}),n=await Promise.all(r.map(async s=>{try{let a=await Dg({config:e,workflowId:s.workflowId});return{entry:s,ok:!0,runId:a}}catch(a){let l=a instanceof Error?a.message:String(a);return{entry:s,message:l,ok:!1}}})),o=await Promise.all(n.map(async s=>{if(!s.ok)return{id:s.entry.id,runId:"",summary:`ERROR creating run: ${s.message}
341
- ${R("setup","check auth + config")}`};let{entry:a,runId:l}=s;try{let c=await _g({config:e,runId:l}),d=Og({config:e,id:a.id,runId:l}),u=`.ripplo/debug/${l}/`;return{id:a.id,runId:l,summary:`View run: ${d}
340
+ `);async function Qt({config:e,ids:t}){let r=await Hg({config:e,ids:t}),n=await Promise.all(r.map(async s=>{try{let a=await Jg({config:e,workflowId:s.workflowId});return{entry:s,ok:!0,runId:a}}catch(a){let l=a instanceof Error?a.message:String(a);return{entry:s,message:l,ok:!1}}})),o=await Promise.all(n.map(async s=>{if(!s.ok)return{id:s.entry.id,runId:"",summary:`ERROR creating run: ${s.message}
341
+ ${R("setup","check auth + config")}`};let{entry:a,runId:l}=s;try{let c=await Yg({config:e,runId:l}),d=Gg({config:e,id:a.id,runId:l}),u=`.ripplo/debug/${l}/`;return{id:a.id,runId:l,summary:`View run: ${d}
342
342
  Debug artifacts: ${u}
343
343
  ${R("debug","read summary.txt, accessibility-tree, network.jsonl before guessing")}
344
344
 
@@ -348,10 +348,10 @@ ${s.summary}`).join(`
348
348
 
349
349
  ---
350
350
 
351
- `);return{results:o,summary:i}}async function Ag({config:e,ids:t}){let r=await $e(e.cwd,e),n=await b({config:e,document:Eg,variables:{cwd:e.cwd,projectId:e.projectId}});if(n.project==null)throw new Error("Project not found");if(n.project.devSession==null)throw new Error("No active dev session. Start one by running `ripplo` (or `npx ripplo`) in your terminal, then try again.");let o=(n.project.workflows??[]).map(s=>Cg(vs,s));if(t.length===0)return o.map(s=>({id:s.slug,workflowId:s.id}));let i=r.compiled.tests.map(s=>s.slug);return t.map(s=>{let a=o.find(l=>l.slug===s);if(a==null)throw new Error(Ig({compiledSlugs:i,slug:s}));return{id:s,workflowId:a.id}})}function Ig({compiledSlugs:e,slug:t}){if(e.includes(t))return`Test "${t}" was synced from .ripplo/ but the server didn't return it. This is likely a server-state bug \u2014 check the server logs for the SyncDevSession mutation.`;let r=jg({compiledSlugs:e,limit:3,slug:t}),n=r.length>0?`
351
+ `);return{results:o,summary:i}}async function Hg({config:e,ids:t}){let r=await Ae(e.cwd,e),n=await b({config:e,document:Fg,variables:{cwd:e.cwd,projectId:e.projectId}});if(n.project==null)throw new Error("Project not found");if(n.project.devSession==null)throw new Error("No active dev session. Start one by running `ripplo` (or `npx ripplo`) in your terminal, then try again.");let o=(n.project.workflows??[]).map(s=>Vg(Is,s));if(t.length===0)return o.map(s=>({id:s.slug,workflowId:s.id}));let i=r.compiled.tests.map(s=>s.slug);return t.map(s=>{let a=o.find(l=>l.slug===s);if(a==null)throw new Error(qg({compiledSlugs:i,slug:s}));return{id:s,workflowId:a.id}})}function qg({compiledSlugs:e,slug:t}){if(e.includes(t))return`Test "${t}" was synced from .ripplo/ but the server didn't return it. This is likely a server-state bug \u2014 check the server logs for the SyncDevSession mutation.`;let r=Wg({compiledSlugs:e,limit:3,slug:t}),n=r.length>0?`
352
352
  Did you mean: ${r.join(", ")}?`:"";return`Test "${t}" is not registered in this dev session.${n}
353
- Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on demand \u2014 restarting the dev server will not help.)`}function jg({compiledSlugs:e,limit:t,slug:r}){let n=new Set(r.split("-"));return e.map(i=>({candidate:i,score:Ng(n,i)})).filter(i=>i.score>0).toSorted((i,s)=>s.score-i.score).slice(0,t).map(i=>i.candidate)}function Ng(e,t){return t.split("-").filter(r=>e.has(r)).length}function Og({config:e,id:t,runId:r}){let n=e.ripploServerUrl.replace(/:3000\b/,":3001"),o=new URL(n.endsWith("/")?n:`${n}/`);return new URL(`projects/${e.projectId}/workflows/${t}/runs/${r}`,o).toString()}async function Dg({config:e,workflowId:t}){let r=await b({config:e,document:Tg,variables:{concurrency:1,platforms:["chromium"],workflowId:t}});if(r.createRun==null)throw new Error("Failed to create run");return r.createRun.id}var Lg=2e3,Ss=150;async function _g({config:e,runId:t}){let r=0;for(;r<Ss;){await Vg(Lg),r+=1;let o=(await b({config:e,document:$g,variables:{id:t}})).run;if(o==null)throw new Error(`Run ${t} not found`);if(!(o.status==="pending"||o.status==="running"))return Ug({results:o.results??[],runId:t,status:o.status})}return`Run ${t} timed out after polling ${String(Ss)} times.`}function Ug({results:e,runId:t,status:r}){let n=[`Run ${t}: ${r.toUpperCase()}`];return e.forEach(o=>{n.push(` ${o.status}: ${String(o.passCount)} passed, ${String(o.failCount)} failed (${String(o.duration??0)}ms)`),o.summary!=null&&n.push(` Summary: ${o.summary}`),o.traceEntries.forEach(i=>{let s=i.status==="passed"?ct.tick:ct.cross,a=i.detail==null?"":` \u2014 ${i.detail}`;n.push(` ${s} ${i.title} (${String(i.duration)}ms)${a}`),i.assertions.forEach(l=>{let c=l.status==="passed"?ct.tick:ct.cross,d=l.detail==null?"":` \u2014 ${l.detail}`;n.push(` ${c} ${l.description}${d}`)})})}),n.join(`
354
- `)}function Vg(e){return new Promise(t=>{setTimeout(t,e)})}import{graphql as Fg}from"gql.tada";var Mg=Fg(`
353
+ Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on demand \u2014 restarting the dev server will not help.)`}function Wg({compiledSlugs:e,limit:t,slug:r}){let n=new Set(r.split("-"));return e.map(i=>({candidate:i,score:zg(n,i)})).filter(i=>i.score>0).toSorted((i,s)=>s.score-i.score).slice(0,t).map(i=>i.candidate)}function zg(e,t){return t.split("-").filter(r=>e.has(r)).length}function Gg({config:e,id:t,runId:r}){let n=e.ripploServerUrl.replace(/:3000\b/,":3001"),o=new URL(n.endsWith("/")?n:`${n}/`);return new URL(`projects/${e.projectId}/workflows/${t}/runs/${r}`,o).toString()}async function Jg({config:e,workflowId:t}){let r=await b({config:e,document:Mg,variables:{concurrency:1,platforms:["chromium"],workflowId:t}});if(r.createRun==null)throw new Error("Failed to create run");return r.createRun.id}var Kg=2e3,As=150;async function Yg({config:e,runId:t}){let r=0;for(;r<As;){await Qg(Kg),r+=1;let o=(await b({config:e,document:Bg,variables:{id:t}})).run;if(o==null)throw new Error(`Run ${t} not found`);if(!(o.status==="pending"||o.status==="running"))return Xg({results:o.results??[],runId:t,status:o.status})}return`Run ${t} timed out after polling ${String(As)} times.`}function Xg({results:e,runId:t,status:r}){let n=[`Run ${t}: ${r.toUpperCase()}`];return e.forEach(o=>{n.push(` ${o.status}: ${String(o.passCount)} passed, ${String(o.failCount)} failed (${String(o.duration??0)}ms)`),o.summary!=null&&n.push(` Summary: ${o.summary}`),o.traceEntries.forEach(i=>{let s=i.status==="passed"?mt.tick:mt.cross,a=i.detail==null?"":` \u2014 ${i.detail}`;n.push(` ${s} ${i.title} (${String(i.duration)}ms)${a}`),i.assertions.forEach(l=>{let c=l.status==="passed"?mt.tick:mt.cross,d=l.detail==null?"":` \u2014 ${l.detail}`;n.push(` ${c} ${l.description}${d}`)})})}),n.join(`
354
+ `)}function Qg(e){return new Promise(t=>{setTimeout(t,e)})}import{graphql as Zg}from"gql.tada";var ey=Zg(`
355
355
  query DevSessionCheckPreflight($projectId: String!, $cwd: String!) {
356
356
  project(id: $projectId) {
357
357
  id
@@ -360,36 +360,36 @@ Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on
360
360
  }
361
361
  }
362
362
  }
363
- `);function he(){try{return B(process.cwd())}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}
363
+ `);function we(){try{return q(process.cwd())}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}
364
364
  `),process.stderr.write(`${R("setup")}
365
- `),process.exit(1)}}async function we(e){(await b({config:e,document:Mg,variables:{cwd:e.cwd,projectId:e.projectId}})).project?.devSession==null&&(process.stderr.write("No active dev session. Start `npx ripplo watch` as a background process (your app's dev server must also be running), then retry. Or run `/ripplo:start` in Claude Code.\n"),process.stderr.write(`${R("setup")}
366
- `),process.exit(1))}async function ks({id:e,runs:t}){let r=he();await we(r),process.stdout.write(`flake-detect "${e}" x${String(t)}...
367
- `);let n=await Promise.allSettled(Array.from({length:t},()=>Gt({config:r,ids:[e]}))),o=0,i=0,s=new Map;n.forEach(l=>{if(l.status==="rejected"){i++;let d=l.reason instanceof Error?l.reason.message:"unknown error";s.set(d,(s.get(d)??0)+1);return}let c=l.value.results[0];if(c==null){i++;return}if(c.summary.includes("FAILED")||c.summary.includes("ERROR")){i++;let d=c.summary.split(`
365
+ `),process.exit(1)}}async function be(e){(await b({config:e,document:ey,variables:{cwd:e.cwd,projectId:e.projectId}})).project?.devSession==null&&(process.stderr.write("No active dev session. Start `npx ripplo watch` as a background process (your app's dev server must also be running), then retry. Or run `/ripplo:start` in Claude Code.\n"),process.stderr.write(`${R("setup")}
366
+ `),process.exit(1))}async function js({id:e,runs:t}){let r=we();await be(r),process.stdout.write(`flake-detect "${e}" x${String(t)}...
367
+ `);let n=await Promise.allSettled(Array.from({length:t},()=>Qt({config:r,ids:[e]}))),o=0,i=0,s=new Map;n.forEach(l=>{if(l.status==="rejected"){i++;let d=l.reason instanceof Error?l.reason.message:"unknown error";s.set(d,(s.get(d)??0)+1);return}let c=l.value.results[0];if(c==null){i++;return}if(c.summary.includes("FAILED")||c.summary.includes("ERROR")){i++;let d=c.summary.split(`
368
368
  `).find(u=>u.includes("FAILED")||u.includes("ERROR"))??"unknown failure";s.set(d,(s.get(d)??0)+1)}else o++});let a=t>0?i/t*100:0;process.stdout.write(`${String(o)} passed / ${String(i)} failed (${a.toFixed(1)}% flake)
369
369
  `),s.size>0&&s.forEach((l,c)=>{process.stdout.write(` ${String(l)}x: ${c}
370
370
  `)}),i>0&&process.stderr.write(`${R("flake-detect","parallel safety + race conditions")}
371
- `),process.exit(i>0?1:0)}import Jt from"fs";import{graphql as qg}from"gql.tada";import Hg from"fs";function pe(e){return rt(e,"hooks-paused")}function V(e){return Hg.existsSync(pe(e))?!1:He(e)}var Bg=qg(`
371
+ `),process.exit(i>0?1:0)}import Zt from"fs";import{graphql as ry}from"gql.tada";import ty from"fs";function me(e){return st(e,"hooks-paused")}function V(e){return ty.existsSync(me(e))?!1:qe(e)}var ny=ry(`
372
372
  mutation CliSetHooksPaused($projectId: String!, $paused: Boolean!) {
373
373
  setHooksPaused(projectId: $projectId, paused: $paused)
374
374
  }
375
- `);async function Rs(){process.stdin.isTTY||(process.stderr.write("`ripplo hooks pause` must be invoked interactively from a terminal \u2014 refusing non-TTY invocation. Bypassing the gate is a human decision, not an agent decision.\n"),process.exit(1));let e=process.cwd();tt(e);let t=pe(e);if(Jt.existsSync(t)){process.stdout.write("Hooks already paused. Run `ripplo hooks resume` to re-enable.\n");return}Jt.writeFileSync(t,""),await xs(e,!0),process.stdout.write("Hooks paused. Pre-edit gates and stop enforcement are off until you run `ripplo hooks resume`.\n")}async function Ps(){let e=process.cwd(),t=pe(e);if(!Jt.existsSync(t)){process.stdout.write(`Hooks already active.
376
- `);return}Jt.unlinkSync(t),await xs(e,!1),process.stdout.write(`Hooks resumed.
377
- `)}async function xs(e,t){let r;try{r=B(e)}catch{return}await b({config:r,document:Bg,variables:{paused:t,projectId:r.projectId}}).catch(()=>null)}import qe from"fs";import Be from"path";import{input as Ts,select as $s}from"@inquirer/prompts";import{graphql as dy}from"gql.tada";import{exec as Wg}from"child_process";import q from"fs";import W from"path";import{promisify as zg}from"util";var Gg=["@ripplo/testing"],Cs=".ripplo/ripplo.lock linguist-generated=true",Jg=[".ripplo/debug/",".ripplo/.local/"],Kg=zg(Wg);async function Es({cwd:e,onStep:t}){t("Scaffolding project files..."),ny({cwd:e}),t("Updating .gitignore..."),oy(e),t("Marking ripplo.lock as generated..."),Qg(e),t("Installing dependencies...");let r=await Yg(e),n=[];if(r.ok||n.push({manualCommand:r.cmd,message:`Couldn't auto-install dev dependencies (${r.reason}). Run the command below, then run \`ripplo lint\` to compile the lockfile.`}),r.ok){t("Compiling initial lockfile...");let o=await Xg(e);o!=null&&n.push({manualCommand:void 0,message:o})}return t("Setting up browser..."),await Cr(),n}async function Yg(e){let t=Zg({cwd:e,pm:ry(e)});h.info("Installing dependencies: %s",t);try{return await Kg(t,{cwd:e}),{ok:!0}}catch(r){let n=r instanceof Error?r.message.split(`
378
- `)[0]??r.message:String(r);return h.warn("Install failed (%s): %s",t,n),{cmd:t,ok:!1,reason:n}}}async function Xg(e){try{let t=await j(e);if(!t.ok)return;await de({cwd:e,result:t.result});return}catch(t){return`Couldn't compile initial lockfile: ${t instanceof Error?t.message:String(t)}.`}}function Qg(e){let t=W.join(e,".gitattributes"),r=q.existsSync(t)?q.readFileSync(t,"utf8"):"";if(r.includes(Cs))return;let n=r.length===0||r.endsWith(`
375
+ `);async function Ns(){process.stdin.isTTY||(process.stderr.write("`ripplo hooks pause` must be invoked interactively from a terminal \u2014 refusing non-TTY invocation. Bypassing the gate is a human decision, not an agent decision.\n"),process.exit(1));let e=process.cwd();it(e);let t=me(e);if(Zt.existsSync(t)){process.stdout.write("Hooks already paused. Run `ripplo hooks resume` to re-enable.\n");return}Zt.writeFileSync(t,""),await Ds(e,!0),process.stdout.write("Hooks paused. Pre-edit gates and stop enforcement are off until you run `ripplo hooks resume`.\n")}async function Os(){let e=process.cwd(),t=me(e);if(!Zt.existsSync(t)){process.stdout.write(`Hooks already active.
376
+ `);return}Zt.unlinkSync(t),await Ds(e,!1),process.stdout.write(`Hooks resumed.
377
+ `)}async function Ds(e,t){let r;try{r=q(e)}catch{return}await b({config:r,document:ny,variables:{paused:t,projectId:r.projectId}}).catch(()=>null)}import We from"fs";import ze from"path";import{input as Us,select as Vs}from"@inquirer/prompts";import{graphql as Ry}from"gql.tada";import{exec as oy}from"child_process";import H from"fs";import W from"path";import{promisify as iy}from"util";var sy=["@ripplo/testing"],_s=".ripplo/ripplo.lock linguist-generated=true",ay=[".ripplo/debug/",".ripplo/.local/"],ly=iy(oy);async function Ls({cwd:e,onStep:t}){t("Scaffolding project files..."),yy({cwd:e}),t("Updating .gitignore..."),hy(e),t("Marking ripplo.lock as generated..."),uy(e),t("Installing dependencies...");let r=await cy(e),n=[];if(r.ok||n.push({manualCommand:r.cmd,message:`Couldn't auto-install dev dependencies (${r.reason}). Run the command below, then run \`ripplo lint\` to compile the lockfile.`}),r.ok){t("Compiling initial lockfile...");let o=await dy(e);o!=null&&n.push({manualCommand:void 0,message:o})}return t("Setting up browser..."),await jr(),n}async function cy(e){let t=py({cwd:e,pm:gy(e)});h.info("Installing dependencies: %s",t);try{return await ly(t,{cwd:e}),{ok:!0}}catch(r){let n=r instanceof Error?r.message.split(`
378
+ `)[0]??r.message:String(r);return h.warn("Install failed (%s): %s",t,n),{cmd:t,ok:!1,reason:n}}}async function dy(e){try{let t=await j(e);if(!t.ok)return;await ue({cwd:e,result:t.result});return}catch(t){return`Couldn't compile initial lockfile: ${t instanceof Error?t.message:String(t)}.`}}function uy(e){let t=W.join(e,".gitattributes"),r=H.existsSync(t)?H.readFileSync(t,"utf8"):"";if(r.includes(_s))return;let n=r.length===0||r.endsWith(`
379
379
  `)?"":`
380
- `;q.writeFileSync(t,`${r}${n}${Cs}
381
- `)}function Zg({cwd:e,pm:t}){let r=Gg.join(" ");return t==="pnpm"?ey(e)?`pnpm add -wD ${r}`:`pnpm add -D ${r}`:t==="yarn"?ty(e)?`yarn add -WD ${r}`:`yarn add -D ${r}`:t==="bun"?`bun add -d ${r}`:`npm install -D ${r}`}function ey(e){return q.existsSync(W.join(e,"pnpm-workspace.yaml"))||q.existsSync(W.join(e,"pnpm-workspace.yml"))}function ty(e){let t=W.join(e,"package.json");if(!q.existsSync(t))return!1;try{let r=JSON.parse(q.readFileSync(t,"utf8"));if(r==null||typeof r!="object"||!("workspaces"in r))return!1;let n=r.workspaces;return Array.isArray(n)||n!=null&&typeof n=="object"}catch{return!1}}function ry(e){return q.existsSync(W.join(e,"pnpm-lock.yaml"))?"pnpm":q.existsSync(W.join(e,"yarn.lock"))?"yarn":q.existsSync(W.join(e,"bun.lockb"))||q.existsSync(W.join(e,"bun.lock"))?"bun":"npm"}function ny({cwd:e}){let t=W.join(e,".ripplo"),r=W.join(t,"tests"),n=W.join(t,"preconditions"),o=W.join(t,"observers");q.mkdirSync(r,{recursive:!0}),q.mkdirSync(n,{recursive:!0}),q.mkdirSync(o,{recursive:!0}),dt(W.join(t,"index.ts"),iy),dt(W.join(n,"index.ts"),sy),dt(W.join(o,"index.ts"),ay),dt(W.join(r,"index.ts"),ly),dt(W.join(t,"tsconfig.json"),cy)}function dt(e,t){q.existsSync(e)||q.writeFileSync(e,t)}function oy(e){let t=W.join(e,".gitignore");if(!q.existsSync(t))return;let r=q.readFileSync(t,"utf8"),n=Jg.filter(i=>!r.includes(i));if(n.length===0)return;let o=r.endsWith(`
380
+ `;H.writeFileSync(t,`${r}${n}${_s}
381
+ `)}function py({cwd:e,pm:t}){let r=sy.join(" ");return t==="pnpm"?my(e)?`pnpm add -wD ${r}`:`pnpm add -D ${r}`:t==="yarn"?fy(e)?`yarn add -WD ${r}`:`yarn add -D ${r}`:t==="bun"?`bun add -d ${r}`:`npm install -D ${r}`}function my(e){return H.existsSync(W.join(e,"pnpm-workspace.yaml"))||H.existsSync(W.join(e,"pnpm-workspace.yml"))}function fy(e){let t=W.join(e,"package.json");if(!H.existsSync(t))return!1;try{let r=JSON.parse(H.readFileSync(t,"utf8"));if(r==null||typeof r!="object"||!("workspaces"in r))return!1;let n=r.workspaces;return Array.isArray(n)||n!=null&&typeof n=="object"}catch{return!1}}function gy(e){return H.existsSync(W.join(e,"pnpm-lock.yaml"))?"pnpm":H.existsSync(W.join(e,"yarn.lock"))?"yarn":H.existsSync(W.join(e,"bun.lockb"))||H.existsSync(W.join(e,"bun.lock"))?"bun":"npm"}function yy({cwd:e}){let t=W.join(e,".ripplo"),r=W.join(t,"tests"),n=W.join(t,"preconditions"),o=W.join(t,"observers");H.mkdirSync(r,{recursive:!0}),H.mkdirSync(n,{recursive:!0}),H.mkdirSync(o,{recursive:!0}),ft(W.join(t,"index.ts"),wy),ft(W.join(n,"index.ts"),by),ft(W.join(o,"index.ts"),Sy),ft(W.join(r,"index.ts"),vy),ft(W.join(t,"tsconfig.json"),ky)}function ft(e,t){H.existsSync(e)||H.writeFileSync(e,t)}function hy(e){let t=W.join(e,".gitignore");if(!H.existsSync(t))return;let r=H.readFileSync(t,"utf8"),n=ay.filter(i=>!r.includes(i));if(n.length===0)return;let o=r.endsWith(`
382
382
  `)?"":`
383
- `;q.writeFileSync(t,r+o+n.join(`
383
+ `;H.writeFileSync(t,r+o+n.join(`
384
384
  `)+`
385
- `)}var iy=`import { createRipplo } from "@ripplo/testing";
386
- import { preconditions } from "./preconditions/index.js";
387
- import { observers } from "./observers/index.js";
388
- import { tests } from "./tests/index.js";
385
+ `)}var wy=`import { createRipplo } from "@ripplo/testing";
386
+ import { preconditions } from "./preconditions/index";
387
+ import { observers } from "./observers/index";
388
+ import { tests } from "./tests/index";
389
389
 
390
390
  export { preconditions, observers, tests };
391
391
  export default createRipplo({ preconditions, observers, tests });
392
- `,sy=`// Declare preconditions with \`precondition(name)\` from @ripplo/testing and collect them
392
+ `,by=`// Declare preconditions with \`precondition(name)\` from @ripplo/testing and collect them
393
393
  // in the \`preconditions\` registry below. Every handle in this registry must be implemented
394
394
  // in your app server's \`createEngine(ripplo, { preconditions: {...}, observers: {...} })\` call.
395
395
  //
@@ -403,7 +403,7 @@ export default createRipplo({ preconditions, observers, tests });
403
403
  // export const preconditions = { authLoggedIn };
404
404
 
405
405
  export const preconditions = {};
406
- `,ay=`// Declare observers with \`observer(name)\` from @ripplo/testing and collect them in
406
+ `,Sy=`// Declare observers with \`observer(name)\` from @ripplo/testing and collect them in
407
407
  // the \`observers\` registry below. Use them in tests via \`assert.backend(handle, params)\`.
408
408
  //
409
409
  // Example:
@@ -416,15 +416,15 @@ export const preconditions = {};
416
416
  // export const observers = { orgNameIs };
417
417
 
418
418
  export const observers = {};
419
- `,ly=`// Each test file under ./tests exports a TestDefinition. Import them here and add them
419
+ `,vy=`// Each test file under ./tests exports a TestDefinition. Import them here and add them
420
420
  // to the \`tests\` array \u2014 that's what \`createRipplo({ ..., tests })\` receives.
421
421
  //
422
422
  // Example:
423
- // import { myTest } from "./my-test.js";
423
+ // import { myTest } from "./my-test";
424
424
  // export const tests = [myTest] as const;
425
425
 
426
426
  export const tests = [] as const;
427
- `,cy=`{
427
+ `,ky=`{
428
428
  "compilerOptions": {
429
429
  "strict": true,
430
430
  "noUncheckedIndexedAccess": true,
@@ -440,68 +440,68 @@ export const tests = [] as const;
440
440
  "include": ["*.ts", "coverage.d.ts", "observers/**/*.ts", "preconditions/**/*.ts", "tests/**/*.ts"],
441
441
  "exclude": ["node_modules"]
442
442
  }
443
- `;var uy=dy(`
443
+ `;var Py=Ry(`
444
444
  query InitProjects {
445
445
  projects {
446
446
  id
447
447
  name
448
448
  }
449
449
  }
450
- `),Sn=["../.env.local","../.env"];async function As(e=fy()){let t=process.cwd(),r=ne();r==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let n=ge();py(t)&&(process.stdout.write(`\`.ripplo/index.ts\` already exists at ${t}. Delete it first if you want to re-init.
451
- `),process.exit(1));let o=await my({serverUrl:n,token:r});o.length===0&&(process.stdout.write("No projects found. Create one in the dashboard first, then re-run `ripplo init`.\n"),process.exit(1));let i=await yy(o,e.projectId),s=await hy(t,e.envFile),a=await wy(e.appUrl),l=gy(a,e.engineUrl),c=Be.resolve(Be.join(t,".ripplo"),s);Tn({cwd:t,envFiles:[s],projectId:i}),vy({appUrl:a,engineUrl:l,filePath:c});let d=await Es({cwd:t,onStep:u=>{process.stdout.write(` ${u}
450
+ `),Cn=["../.env.local","../.env"];async function Fs(e=Ey()){let t=process.cwd(),r=oe();r==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let n=ye();xy(t)&&(process.stdout.write(`\`.ripplo/index.ts\` already exists at ${t}. Delete it first if you want to re-init.
451
+ `),process.exit(1));let o=await Cy({serverUrl:n,token:r});o.length===0&&(process.stdout.write("No projects found. Create one in the dashboard first, then re-run `ripplo init`.\n"),process.exit(1));let i=await $y(o,e.projectId),s=await Ay(t,e.envFile),a=await Iy(e.appUrl),l=Ty(a,e.engineUrl),c=ze.resolve(ze.join(t,".ripplo"),s);_n({cwd:t,envFiles:[s],projectId:i}),Oy({appUrl:a,engineUrl:l,filePath:c});let d=await Ls({cwd:t,onStep:u=>{process.stdout.write(` ${u}
452
452
  `)}});if(d.length>0){process.stdout.write(`Done with warnings:
453
453
  `),d.forEach(u=>{process.stdout.write(` - ${u.message}
454
454
  `),u.manualCommand!=null&&process.stdout.write(` run: ${u.manualCommand}
455
- `)});return}process.stdout.write("Ready. Start `npx ripplo watch` as a background process (or run `/ripplo:start` in Claude Code), then write tests in `.ripplo/tests/`.\n")}function py(e){return qe.existsSync(Be.join(e,".ripplo","index.ts"))}async function my({serverUrl:e,token:t}){return((await b({config:Le({serverUrl:e,token:t}),document:uy,variables:void 0})).projects??[]).map(n=>({id:n.id,name:n.name}))}function fy(){return{appUrl:void 0,engineUrl:void 0,envFile:void 0,projectId:void 0}}function gy(e,t){if(t!=null){try{new URL(t)}catch{process.stdout.write(`--engine-url is not a valid URL: ${t}
456
- `),process.exit(1)}return t}return`${e.replace(/\/$/,"")}/ripplo`}async function yy(e,t){if(t!=null){let r=e.find(n=>n.id===t);return r==null&&(process.stdout.write(`Unknown project id: ${t}
455
+ `)});return}process.stdout.write("Ready. Start `npx ripplo watch` as a background process (or run `/ripplo:start` in Claude Code), then write tests in `.ripplo/tests/`.\n")}function xy(e){return We.existsSync(ze.join(e,".ripplo","index.ts"))}async function Cy({serverUrl:e,token:t}){return((await b({config:Ue({serverUrl:e,token:t}),document:Py,variables:void 0})).projects??[]).map(n=>({id:n.id,name:n.name}))}function Ey(){return{appUrl:void 0,engineUrl:void 0,envFile:void 0,projectId:void 0}}function Ty(e,t){if(t!=null){try{new URL(t)}catch{process.stdout.write(`--engine-url is not a valid URL: ${t}
456
+ `),process.exit(1)}return t}return`${e.replace(/\/$/,"")}/ripplo`}async function $y(e,t){if(t!=null){let r=e.find(n=>n.id===t);return r==null&&(process.stdout.write(`Unknown project id: ${t}
457
457
  `),process.exit(1)),process.stdout.write(`Using project: ${r.name} (${r.id})
458
458
  `),r.id}if(e.length===1){let r=e[0];if(r==null)throw new Error("unreachable");return process.stdout.write(`Using project: ${r.name} (${r.id})
459
- `),r.id}return $s({choices:e.map(r=>({name:r.name,value:r.id})),message:"Select a project"})}async function hy(e,t){return t!=null?(t.trim().length===0&&(process.stdout.write(`--env must not be empty
460
- `),process.exit(1)),t):by(e)}async function wy(e){if(e!=null){try{new URL(e)}catch{process.stdout.write(`--app-url is not a valid URL: ${e}
461
- `),process.exit(1)}return e}return Sy()}async function by(e){let t=Be.join(e,".ripplo"),r=Sn.find(o=>qe.existsSync(Be.resolve(t,o))),n=await $s({choices:[...Sn.map(o=>({name:r===o?`${o} (detected)`:o,value:o})),{name:"custom path",value:"__custom__"}],default:r??Sn[0],message:"Which env file should ripplo write RIPPLO_APP_URL, RIPPLO_ENGINE_URL, RIPPLO_WEBHOOK_SECRET, and ENABLE_RIPPLO_TESTING to?"});return n!=="__custom__"?n:Ts({message:"Path to env file (relative to .ripplo/, e.g. ../apps/server/.env)",validate:o=>o.trim().length>0?!0:"required"})}async function Sy(){return Ts({default:"http://localhost:3000",message:"Where does your dev server run? (RIPPLO_APP_URL)",validate:e=>{try{return new URL(e),!0}catch{return"must be a valid URL"}}})}function vy({appUrl:e,engineUrl:t,filePath:r}){qe.mkdirSync(Be.dirname(r),{recursive:!0});let n=qe.existsSync(r)?qe.readFileSync(r,"utf8"):"",o=[];if(/^RIPPLO_APP_URL=/m.test(n)||o.push(`RIPPLO_APP_URL=${e}`),/^RIPPLO_ENGINE_URL=/m.test(n)||o.push(`RIPPLO_ENGINE_URL=${t}`),/^RIPPLO_WEBHOOK_SECRET=/m.test(n)||o.push(`RIPPLO_WEBHOOK_SECRET=${Gr()}`),/^ENABLE_RIPPLO_TESTING=/m.test(n)||o.push("ENABLE_RIPPLO_TESTING=true"),o.length===0)return;let i=n.length===0||n.endsWith(`
459
+ `),r.id}return Vs({choices:e.map(r=>({name:r.name,value:r.id})),message:"Select a project"})}async function Ay(e,t){return t!=null?(t.trim().length===0&&(process.stdout.write(`--env must not be empty
460
+ `),process.exit(1)),t):jy(e)}async function Iy(e){if(e!=null){try{new URL(e)}catch{process.stdout.write(`--app-url is not a valid URL: ${e}
461
+ `),process.exit(1)}return e}return Ny()}async function jy(e){let t=ze.join(e,".ripplo"),r=Cn.find(o=>We.existsSync(ze.resolve(t,o))),n=await Vs({choices:[...Cn.map(o=>({name:r===o?`${o} (detected)`:o,value:o})),{name:"custom path",value:"__custom__"}],default:r??Cn[0],message:"Which env file should ripplo write RIPPLO_APP_URL, RIPPLO_ENGINE_URL, RIPPLO_WEBHOOK_SECRET, and ENABLE_RIPPLO_TESTING to?"});return n!=="__custom__"?n:Us({message:"Path to env file (relative to .ripplo/, e.g. ../apps/server/.env)",validate:o=>o.trim().length>0?!0:"required"})}async function Ny(){return Us({default:"http://localhost:3000",message:"Where does your dev server run? (RIPPLO_APP_URL)",validate:e=>{try{return new URL(e),!0}catch{return"must be a valid URL"}}})}function Oy({appUrl:e,engineUrl:t,filePath:r}){We.mkdirSync(ze.dirname(r),{recursive:!0});let n=We.existsSync(r)?We.readFileSync(r,"utf8"):"",o=[];if(/^RIPPLO_APP_URL=/m.test(n)||o.push(`RIPPLO_APP_URL=${e}`),/^RIPPLO_ENGINE_URL=/m.test(n)||o.push(`RIPPLO_ENGINE_URL=${t}`),/^RIPPLO_WEBHOOK_SECRET=/m.test(n)||o.push(`RIPPLO_WEBHOOK_SECRET=${Zr()}`),/^ENABLE_RIPPLO_TESTING=/m.test(n)||o.push("ENABLE_RIPPLO_TESTING=true"),o.length===0)return;let i=n.length===0||n.endsWith(`
462
462
  `)?"":`
463
- `;qe.writeFileSync(r,`${n}${i}${o.join(`
463
+ `;We.writeFileSync(r,`${n}${i}${o.join(`
464
464
  `)}
465
- `)}import vn from"fs";import Is from"path";import*as js from"remeda";import ky from"path";import{graphql as Ry}from"gql.tada";var Py=Ry(`
465
+ `)}import En from"fs";import Ms from"path";import*as Bs from"remeda";import Dy from"path";import{graphql as _y}from"gql.tada";var Ly=_y(`
466
466
  mutation AutoScopeAddDirty($projectId: String!, $cwd: String!, $workflowSlugs: [String!]!) {
467
467
  addAgentScopeItems(projectId: $projectId, cwd: $cwd, workflowSlugs: $workflowSlugs) {
468
468
  id
469
469
  }
470
470
  }
471
- `);async function Kt({compileResult:e,cwd:t}){if(!V(t))return{addedSlugs:[]};let r=xy(t);if(r.length===0)return{addedSlugs:[]};let n=new Set(e.result.tests.map(c=>c.slug)),o=r.filter(c=>n.has(c));if(o.length===0)return{addedSlugs:[]};let i;try{i=B(t)}catch{return{addedSlugs:[]}}if(await lt({compiled:e.result,config:i,cwd:t}).catch(c=>(h.warn("auto-sync failed: %s",c instanceof Error?c.message:String(c)),null))==null)return{addedSlugs:[]};let a=await b({config:i,document:Py,variables:{cwd:i.cwd,projectId:i.projectId,workflowSlugs:o}}).catch(c=>(h.warn("auto-scope failed: %s",c instanceof Error?c.message:String(c)),null));return a==null?{addedSlugs:[]}:(a.addAgentScopeItems??[]).length===0?{addedSlugs:[]}:{addedSlugs:o}}function xy(e){let t;try{t=X(["status","--porcelain","--",".ripplo/tests"],e)}catch{return[]}return t.split(`
472
- `).map(r=>r.slice(3).trim()).filter(r=>/^\.ripplo\/tests\/[^/]+\.ts$/.test(r)).map(r=>ky.basename(r,".ts")).filter(r=>r!=="index")}async function Ns(e){let{ids:t,requireImplemented:r}=e,n=process.cwd(),o=await j(n);o.ok||(process.stderr.write(`Compilation failed: ${o.error}
471
+ `);async function er({compileResult:e,cwd:t}){if(!V(t))return{addedSlugs:[]};let r=Uy(t);if(r.length===0)return{addedSlugs:[]};let n=new Set(e.result.tests.map(c=>c.slug)),o=r.filter(c=>n.has(c));if(o.length===0)return{addedSlugs:[]};let i;try{i=q(t)}catch{return{addedSlugs:[]}}if(await pt({compiled:e.result,config:i,cwd:t}).catch(c=>(h.warn("auto-sync failed: %s",c instanceof Error?c.message:String(c)),null))==null)return{addedSlugs:[]};let a=await b({config:i,document:Ly,variables:{cwd:i.cwd,projectId:i.projectId,workflowSlugs:o}}).catch(c=>(h.warn("auto-scope failed: %s",c instanceof Error?c.message:String(c)),null));return a==null?{addedSlugs:[]}:(a.addAgentScopeItems??[]).length===0?{addedSlugs:[]}:{addedSlugs:o}}function Uy(e){let t;try{t=Q(["status","--porcelain","--",".ripplo/tests"],e)}catch{return[]}return t.split(`
472
+ `).map(r=>r.slice(3).trim()).filter(r=>/^\.ripplo\/tests\/[^/]+\.ts$/.test(r)).map(r=>Dy.basename(r,".ts")).filter(r=>r!=="index")}async function Hs(e){let{ids:t,requireImplemented:r}=e,n=process.cwd(),o=await j(n);o.ok||(process.stderr.write(`Compilation failed: ${o.error}
473
473
  `),process.stderr.write(`${R("create","DSL authoring + lint rules")}
474
- `),process.exit(1)),await de({cwd:n,result:o.result});let i=Ue(o.result),s=t.length===0?i.diagnostics:i.diagnostics.filter(g=>t.includes(g.test)),a=js.groupBy(s,g=>g.test);Object.entries(a).forEach(([g,E])=>{process.stderr.write(`
474
+ `),process.exit(1)),await ue({cwd:n,result:o.result});let i=Fe(o.result),s=t.length===0?i.diagnostics:i.diagnostics.filter(g=>t.includes(g.test)),a=Bs.groupBy(s,g=>g.test);Object.entries(a).forEach(([g,E])=>{process.stderr.write(`
475
475
  ${g}
476
- `),E.forEach(P=>{let L=P.step==null?"":` at "${P.step}"`;process.stderr.write(` [${P.rule}]${L}
476
+ `),E.forEach(P=>{let _=P.step==null?"":` at "${P.step}"`;process.stderr.write(` [${P.rule}]${_}
477
477
  `),process.stderr.write(` ${P.message}
478
478
  `)})});let l=new Set(o.builder.getUnimplemented().tests),c=r.filter(g=>l.has(g));c.length>0&&(process.stderr.write(`
479
479
  not-implemented
480
480
  `),c.forEach(g=>{process.stderr.write(` ${g} is still marked .notImplemented()
481
- `)}));let d=$y(n);d.length>0&&(process.stderr.write(`
481
+ `)}));let d=By(n);d.length>0&&(process.stderr.write(`
482
482
  preconditions
483
483
  `),d.forEach(g=>{process.stderr.write(` [hardcoded-identifier] ${g.file}
484
484
  `),process.stderr.write(` ${g.message}
485
485
  `)}));let u=s.length+c.length+d.length;u>0&&(process.stderr.write(`
486
486
  ${String(u)} error(s)
487
- `),Cy({diagnostics:s,hardcodeWarnings:d,stillStubbed:c}),process.exit(1));let f=o.result.tests.length,w=t.length===0?"all tests":`${String(t.length)} test(s)`;process.stdout.write(`\u2713 ripplo lint: ${w} passed (${String(f)} compiled, lockfile written)
488
- `);let{addedSlugs:v}=await Kt({compileResult:o,cwd:n});v.length>0&&process.stdout.write(`\u2713 Auto-scoped ${v.join(", ")} (dirty tests).
489
- `)}function Cy({diagnostics:e,hardcodeWarnings:t,stillStubbed:r}){let n=new Set;(e.length>0||r.length>0)&&n.add("create"),t.length>0&&n.add("explore"),n.forEach(o=>process.stderr.write(`${R(o)}
490
- `))}var Ey=/['"`][\w.+-]+@[\w.-]+\.[a-z]{2,}['"`]/i,Ty=/['"`][0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}['"`]/i;function $y(e){let t=Is.join(e,".ripplo","preconditions");return vn.existsSync(t)?vn.readdirSync(t).filter(n=>n.endsWith(".ts")).flatMap(n=>Ay(Is.join(t,n))):[]}function Ay(e){let t=vn.readFileSync(e,"utf8"),r=t.includes("ctx.uniqueEmail")||t.includes("ctx.uniqueId"),n=[],o=Ey.exec(t);o!=null&&!r&&n.push({file:e,message:`hardcoded email literal ${o[0]} \u2014 use ctx.uniqueEmail() so parallel runs don't collide`});let i=Ty.exec(t);return i!=null&&!r&&n.push({file:e,message:`hardcoded UUID-like literal ${i[0]} \u2014 use ctx.uniqueId() so parallel runs don't collide`}),n}import{graphql as Iy}from"gql.tada";var jy=Iy(`
487
+ `),Vy({diagnostics:s,hardcodeWarnings:d,stillStubbed:c}),process.exit(1));let f=o.result.tests.length,w=t.length===0?"all tests":`${String(t.length)} test(s)`;process.stdout.write(`\u2713 ripplo lint: ${w} passed (${String(f)} compiled, lockfile written)
488
+ `);let{addedSlugs:v}=await er({compileResult:o,cwd:n});v.length>0&&process.stdout.write(`\u2713 Auto-scoped ${v.join(", ")} (dirty tests).
489
+ `)}function Vy({diagnostics:e,hardcodeWarnings:t,stillStubbed:r}){let n=new Set;(e.length>0||r.length>0)&&n.add("create"),t.length>0&&n.add("explore"),n.forEach(o=>process.stderr.write(`${R(o)}
490
+ `))}var Fy=/['"`][\w.+-]+@[\w.-]+\.[a-z]{2,}['"`]/i,My=/['"`][0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}['"`]/i;function By(e){let t=Ms.join(e,".ripplo","preconditions");return En.existsSync(t)?En.readdirSync(t).filter(n=>n.endsWith(".ts")).flatMap(n=>Hy(Ms.join(t,n))):[]}function Hy(e){let t=En.readFileSync(e,"utf8"),r=t.includes("ctx.uniqueEmail")||t.includes("ctx.uniqueId"),n=[],o=Fy.exec(t);o!=null&&!r&&n.push({file:e,message:`hardcoded email literal ${o[0]} \u2014 use ctx.uniqueEmail() so parallel runs don't collide`});let i=My.exec(t);return i!=null&&!r&&n.push({file:e,message:`hardcoded UUID-like literal ${i[0]} \u2014 use ctx.uniqueId() so parallel runs don't collide`}),n}import{graphql as qy}from"gql.tada";var Wy=qy(`
491
491
  query ProjectsList {
492
492
  projects {
493
493
  id
494
494
  name
495
495
  }
496
496
  }
497
- `);async function Os(){let e=ne();e==null&&(process.stderr.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let t=ge(),n=((await b({config:Le({serverUrl:t,token:e}),document:jy,variables:void 0})).projects??[]).map(o=>({id:o.id,name:o.name}));process.stdout.write(`${JSON.stringify({projects:n},null,2)}
498
- `)}async function Ds(e){let t=he();await we(t);let{results:r,summary:n}=await Gt({config:t,ids:e});process.stdout.write(`${n}
497
+ `);async function qs(){let e=oe();e==null&&(process.stderr.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let t=ye(),n=((await b({config:Ue({serverUrl:t,token:e}),document:Wy,variables:void 0})).projects??[]).map(o=>({id:o.id,name:o.name}));process.stdout.write(`${JSON.stringify({projects:n},null,2)}
498
+ `)}async function Ws(e){let t=we();await be(t);let{results:r,summary:n}=await Qt({config:t,ids:e});process.stdout.write(`${n}
499
499
  `);let o=r.some(i=>i.summary.includes("FAILED")||i.summary.includes("ERROR"));o&&(process.stderr.write(`Artifacts in .ripplo/debug/<runId>/ \u2014 read before re-running.
500
500
  `),process.stderr.write(`${R("debug")}
501
- `)),process.exit(o?1:0)}async function Ls(){let e=process.cwd(),t=B(e);try{let r=await $e(t.cwd,t),n=r.compiled.tests.length,o=Object.keys(r.compiled.preconditions).length;process.stdout.write(`synced ${String(n)} tests, ${String(o)} preconditions to dev session ${r.devSessionId}
501
+ `)),process.exit(o?1:0)}async function zs(){let e=process.cwd(),t=q(e);try{let r=await Ae(t.cwd,t),n=r.compiled.tests.length,o=Object.keys(r.compiled.preconditions).length;process.stdout.write(`synced ${String(n)} tests, ${String(o)} preconditions to dev session ${r.devSessionId}
502
502
  `)}catch(r){let n=r instanceof Error?r.message:String(r);process.stderr.write(`ripplo sync failed: ${n}
503
503
  `),process.stderr.write(`${R("setup","verify auth + server reachability")}
504
- `),process.exit(1)}}import Rn from"fs";import{createClient as Vy}from"graphql-sse";import{graphql as Yt}from"gql.tada";import{print as Us}from"graphql";import{availableParallelism as Ny}from"os";import Oy from"p-limit";var Dy=Math.max(1,Math.min(10,Math.floor(Ny()/2))),Ly=Oy(Dy),kn=new Set;async function _s(e){if(!kn.has(e.runId)){kn.add(e.runId);try{await Ly(()=>_y(e))}finally{kn.delete(e.runId)}}}async function _y({agentProfileDescription:e,agentProfileId:t,config:r,cwd:n,runId:o,workflowId:i,workflowSlug:s}){let a=await Ce({headed:!1});try{await Dr({maxRuns:100});let l=n!=null&&s!=null?await Uy({cwd:n,workflowSlug:s}):void 0;await tn({agentProfileDescription:e,agentProfileId:t,baseUrl:r.appUrl,browser:a,config:r,headed:!1,preconditionNames:l,runId:o,webhookSecret:r.webhookSecret,workflowId:i})}catch(l){h.error(l,"Runner error")}finally{await a.close()}}async function Uy({cwd:e,workflowSlug:t}){let r=await j(e);if(!r.ok)return;let n=r.result.tests.find(o=>o.slug===t);if(n!=null)return n.preconditions}var Fy=15e3,My=Yt(`
504
+ `),process.exit(1)}}import $n from"fs";import{createClient as Qy}from"graphql-sse";import{graphql as tr}from"gql.tada";import{print as Js}from"graphql";import{availableParallelism as zy}from"os";import Gy from"p-limit";var Jy=Math.max(1,Math.min(10,Math.floor(zy()/2))),Ky=Gy(Jy),Tn=new Set;async function Gs(e){if(!Tn.has(e.runId)){Tn.add(e.runId);try{await Ky(()=>Yy(e))}finally{Tn.delete(e.runId)}}}async function Yy({agentProfileDescription:e,agentProfileId:t,config:r,cwd:n,runId:o,workflowId:i,workflowSlug:s}){let a=await Te({headed:!1});try{await Mr({maxRuns:100});let l=n!=null&&s!=null?await Xy({cwd:n,workflowSlug:s}):void 0;await ln({agentProfileDescription:e,agentProfileId:t,baseUrl:r.appUrl,browser:a,config:r,headed:!1,preconditionNames:l,runId:o,webhookSecret:r.webhookSecret,workflowId:i})}catch(l){h.error(l,"Runner error")}finally{await a.close()}}async function Xy({cwd:e,workflowSlug:t}){let r=await j(e);if(!r.ok)return;let n=r.result.tests.find(o=>o.slug===t);if(n!=null)return n.preconditions}var Zy=15e3,eh=tr(`
505
505
  subscription RunRequestedWatch($devSessionId: String!) {
506
506
  runRequested(devSessionId: $devSessionId) {
507
507
  agentProfileDescription
@@ -511,30 +511,30 @@ ${String(u)} error(s)
511
511
  workflowSlug
512
512
  }
513
513
  }
514
- `),Hy=Yt(`
514
+ `),th=tr(`
515
515
  subscription HooksPausedWatch($projectId: String!) {
516
516
  hooksPausedRequested(projectId: $projectId) {
517
517
  paused
518
518
  projectId
519
519
  }
520
520
  }
521
- `),qy=Yt(`
521
+ `),rh=tr(`
522
522
  mutation HeartbeatDevSessionWatch($id: String!) {
523
523
  heartbeatDevSession(id: $id) {
524
524
  id
525
525
  }
526
526
  }
527
- `),By=Yt(`
527
+ `),nh=tr(`
528
528
  mutation EndDevSessionWatch($projectId: String!, $cwd: String!) {
529
529
  endDevSession(projectId: $projectId, cwd: $cwd) {
530
530
  id
531
531
  }
532
532
  }
533
- `);async function Vs(){th();let e=Jy(process.cwd()),t=e.cwd,r=await j(t);r.ok||(process.stderr.write(`ripplo: DSL compilation failed: ${r.error}
534
- `),process.exit(1));let n=await Xy(()=>lt({compiled:r.result,config:e,cwd:t})),o=Wt(t);o!=null&&h.info("watching branch %s in %s",o,t);let i=cs(t),s=Vy({headers:{Authorization:`Bearer ${e.token}`},retryAttempts:1/0,url:`${e.ripploServerUrl}/graphql`}),a=Wy({config:e,cwd:t,devSessionId:n.devSessionId,sseClient:s}),l=zy({cwd:t,projectId:e.projectId,sseClient:s}),c=Gy({config:e,devSessionId:n.devSessionId});process.stdout.write(`ripplo watch: ready as local executor for session ${n.devSessionId} (sync happens on each \`ripplo run\`; Ctrl-C to stop)
535
- `);let d=async()=>{c(),a(),l(),await Promise.race([b({config:e,document:By,variables:{cwd:e.cwd,projectId:e.projectId}}).catch(()=>{}),new Promise(f=>setTimeout(f,3e3))]),i()},u=()=>{d().finally(()=>process.exit(0))};process.on("SIGINT",u),process.on("SIGTERM",u),process.on("SIGHUP",u),process.on("SIGBREAK",u),await new Promise(()=>{})}function Wy({config:e,cwd:t,devSessionId:r,sseClient:n}){return n.subscribe({query:Us(My),variables:{devSessionId:r}},{complete:()=>{},error:o=>{h.error(o,"runRequested subscription error")},next:o=>{let i=o.data?.runRequested;i!=null&&(process.stdout.write(`ripplo: run ${i.runId} (${i.workflowSlug})
536
- `),_s({agentProfileDescription:i.agentProfileDescription??void 0,agentProfileId:i.agentProfileId??void 0,config:e,cwd:t,runId:i.runId,workflowId:i.workflowId,workflowSlug:i.workflowSlug}).catch(s=>{h.error({err:s,runId:i.runId,workflowSlug:i.workflowSlug},"run execution failed; watch continuing")}))}})}function zy({cwd:e,projectId:t,sseClient:r}){return r.subscribe({query:Us(Hy),variables:{projectId:t}},{complete:()=>{},error:n=>{h.error(n,"hooksPaused subscription error")},next:n=>{let o=n.data?.hooksPausedRequested?.paused;if(o===!0){Rn.writeFileSync(pe(e),"");return}o===!1&&Rn.existsSync(pe(e))&&Rn.unlinkSync(pe(e))}})}function Gy({config:e,devSessionId:t}){let r=setInterval(()=>{b({config:e,document:qy,variables:{id:t}}).catch(n=>{h.warn("heartbeat failed: %s",n instanceof Error?n.message:String(n))})},Fy);return()=>{clearInterval(r)}}function Jy(e){try{return B(e)}catch(t){let r=t instanceof Error?t.message:String(t);process.stderr.write(`${r}
537
- `),process.exit(1)}}var Ky=1e3,Yy=6e4;async function Xy(e){let t=Date.now()+Yy,r;for(;Date.now()<t;){let n=await Qy(e);if(n.ok)return n.value;if(!Zy(n.message))throw n.error;r=n.error,await eh(Ky)}throw r instanceof Error?r:new Error("server never became ready")}async function Qy(e){try{return{ok:!0,value:await e()}}catch(t){let r=t instanceof Error?t.message:String(t);return{error:t,message:r,ok:!1}}}function Zy(e){return e.includes("status 502")||e.includes("ECONNREFUSED")||e.includes("Failed to connect")||e.includes("fetch failed")}function eh(e){return new Promise(t=>setTimeout(t,e))}function th(){process.on("unhandledRejection",e=>{h.error({err:e},"unhandledRejection in watch; continuing")}),process.on("uncaughtException",e=>{h.error({err:e},"uncaughtException in watch; continuing")})}import{graphql as ut}from"gql.tada";var rh=ut(`
533
+ `);async function Ks(){fh();let e=ah(process.cwd()),t=e.cwd,r=await j(t);r.ok||(process.stderr.write(`ripplo: DSL compilation failed: ${r.error}
534
+ `),process.exit(1));let n=await dh(()=>pt({compiled:r.result,config:e,cwd:t})),o=Yt(t);o!=null&&h.info("watching branch %s in %s",o,t);let i=bs(t),s=Qy({headers:{Authorization:`Bearer ${e.token}`},retryAttempts:1/0,url:`${e.ripploServerUrl}/graphql`}),a=oh({config:e,cwd:t,devSessionId:n.devSessionId,sseClient:s}),l=ih({cwd:t,projectId:e.projectId,sseClient:s}),c=sh({config:e,devSessionId:n.devSessionId});process.stdout.write(`ripplo watch: ready as local executor for session ${n.devSessionId} (sync happens on each \`ripplo run\`; Ctrl-C to stop)
535
+ `);let d=async()=>{c(),a(),l(),await Promise.race([b({config:e,document:nh,variables:{cwd:e.cwd,projectId:e.projectId}}).catch(()=>{}),new Promise(f=>setTimeout(f,3e3))]),i()},u=()=>{d().finally(()=>process.exit(0))};process.on("SIGINT",u),process.on("SIGTERM",u),process.on("SIGHUP",u),process.on("SIGBREAK",u),await new Promise(()=>{})}function oh({config:e,cwd:t,devSessionId:r,sseClient:n}){return n.subscribe({query:Js(eh),variables:{devSessionId:r}},{complete:()=>{},error:o=>{h.error(o,"runRequested subscription error")},next:o=>{let i=o.data?.runRequested;i!=null&&(process.stdout.write(`ripplo: run ${i.runId} (${i.workflowSlug})
536
+ `),Gs({agentProfileDescription:i.agentProfileDescription??void 0,agentProfileId:i.agentProfileId??void 0,config:e,cwd:t,runId:i.runId,workflowId:i.workflowId,workflowSlug:i.workflowSlug}).catch(s=>{h.error({err:s,runId:i.runId,workflowSlug:i.workflowSlug},"run execution failed; watch continuing")}))}})}function ih({cwd:e,projectId:t,sseClient:r}){return r.subscribe({query:Js(th),variables:{projectId:t}},{complete:()=>{},error:n=>{h.error(n,"hooksPaused subscription error")},next:n=>{let o=n.data?.hooksPausedRequested?.paused;if(o===!0){$n.writeFileSync(me(e),"");return}o===!1&&$n.existsSync(me(e))&&$n.unlinkSync(me(e))}})}function sh({config:e,devSessionId:t}){let r=setInterval(()=>{b({config:e,document:rh,variables:{id:t}}).catch(n=>{h.warn("heartbeat failed: %s",n instanceof Error?n.message:String(n))})},Zy);return()=>{clearInterval(r)}}function ah(e){try{return q(e)}catch(t){let r=t instanceof Error?t.message:String(t);process.stderr.write(`${r}
537
+ `),process.exit(1)}}var lh=1e3,ch=6e4;async function dh(e){let t=Date.now()+ch,r;for(;Date.now()<t;){let n=await uh(e);if(n.ok)return n.value;if(!ph(n.message))throw n.error;r=n.error,await mh(lh)}throw r instanceof Error?r:new Error("server never became ready")}async function uh(e){try{return{ok:!0,value:await e()}}catch(t){let r=t instanceof Error?t.message:String(t);return{error:t,message:r,ok:!1}}}function ph(e){return e.includes("status 502")||e.includes("ECONNREFUSED")||e.includes("Failed to connect")||e.includes("fetch failed")}function mh(e){return new Promise(t=>setTimeout(t,e))}function fh(){process.on("unhandledRejection",e=>{h.error({err:e},"unhandledRejection in watch; continuing")}),process.on("uncaughtException",e=>{h.error({err:e},"uncaughtException in watch; continuing")})}import{graphql as gt}from"gql.tada";var gh=gt(`
538
538
  query ScopeStatus($projectId: String!, $cwd: String!) {
539
539
  project(id: $projectId) {
540
540
  id
@@ -554,7 +554,7 @@ ${String(u)} error(s)
554
554
  }
555
555
  }
556
556
  }
557
- `),nh=ut(`
557
+ `),yh=gt(`
558
558
  query ScopeWorkflowBySlug($projectId: String!, $cwd: String!, $slug: String!) {
559
559
  project(id: $projectId) {
560
560
  id
@@ -567,7 +567,7 @@ ${String(u)} error(s)
567
567
  }
568
568
  }
569
569
  }
570
- `),oh=ut(`
570
+ `),hh=gt(`
571
571
  mutation ScopeAddAgent($projectId: String!, $cwd: String!, $workflowSlugs: [String!]!) {
572
572
  addAgentScopeItems(projectId: $projectId, cwd: $cwd, workflowSlugs: $workflowSlugs) {
573
573
  id
@@ -577,36 +577,36 @@ ${String(u)} error(s)
577
577
  }
578
578
  }
579
579
  }
580
- `),ih=ut(`
580
+ `),wh=gt(`
581
581
  mutation ScopeLink($id: ID!, $workflowId: String!) {
582
582
  linkScopeItem(id: $id, workflowId: $workflowId) {
583
583
  id
584
584
  }
585
585
  }
586
- `),sh=ut(`
586
+ `),bh=gt(`
587
587
  mutation ScopeRemoveMany($ids: [ID!]!) {
588
588
  removeScopeItems(ids: $ids)
589
589
  }
590
- `);async function Fs(e){let t=he();await we(t);let n=(await b({config:t,document:rh,variables:{cwd:t.cwd,projectId:t.projectId}})).project?.devSession?.scopeItems??[];if(e.format==="json"){process.stdout.write(`${JSON.stringify(n,null,2)}
590
+ `);async function Ys(e){let t=we();await be(t);let n=(await b({config:t,document:gh,variables:{cwd:t.cwd,projectId:t.projectId}})).project?.devSession?.scopeItems??[];if(e.format==="json"){process.stdout.write(`${JSON.stringify(n,null,2)}
591
591
  `);return}if(n.length===0){process.stdout.write("No scope items. Add via `ripplo scope add <test-ids..>` (variadic) or from the dashboard.\n");return}n.forEach(o=>{let i=o.workflow;if(i==null){process.stdout.write(` [intent] (${o.id}) ${o.label??""}
592
592
  `);return}let s=i.spec==null?"stub":"implemented";process.stdout.write(` [${s}] (${o.id}) ${i.slug} \u2014 ${i.name}
593
- `)})}async function Ms({testIds:e}){let t=he();await we(t),await $e(t.cwd,t);let n=(await b({config:t,document:oh,variables:{cwd:t.cwd,projectId:t.projectId,workflowSlugs:[...e]}})).addAgentScopeItems??[];if(n.length===0){process.stdout.write(`No scope items added.
593
+ `)})}async function Xs({testIds:e}){let t=we();await be(t),await Ae(t.cwd,t);let n=(await b({config:t,document:hh,variables:{cwd:t.cwd,projectId:t.projectId,workflowSlugs:[...e]}})).addAgentScopeItems??[];if(n.length===0){process.stdout.write(`No scope items added.
594
594
  `);return}let o=n.map(i=>i.workflow?.slug??"?").join(", ");process.stdout.write(`Added ${String(n.length)} scope item(s): ${o}
595
- `)}async function Hs({id:e,testId:t}){let r=he();await we(r),await $e(r.cwd,r);let n=await ah({cfg:r,slug:t});await b({config:r,document:ih,variables:{id:e,workflowId:n}}),process.stdout.write(`Linked scope item ${e} to ${t}
596
- `)}async function qs({ids:e}){let t=he();await we(t);let n=(await b({config:t,document:sh,variables:{ids:[...e]}})).removeScopeItems??0;process.stdout.write(`Removed ${String(n)} scope item(s)
597
- `)}async function ah({cfg:e,slug:t}){let n=(await b({config:e,document:nh,variables:{cwd:e.cwd,projectId:e.projectId,slug:t}})).project?.devSession?.workflows?.[0];return n==null&&(process.stderr.write(`No workflow found with id "${t}". Create a stub first via the testing DSL.
595
+ `)}async function Qs({id:e,testId:t}){let r=we();await be(r),await Ae(r.cwd,r);let n=await Sh({cfg:r,slug:t});await b({config:r,document:wh,variables:{id:e,workflowId:n}}),process.stdout.write(`Linked scope item ${e} to ${t}
596
+ `)}async function Zs({ids:e}){let t=we();await be(t);let n=(await b({config:t,document:bh,variables:{ids:[...e]}})).removeScopeItems??0;process.stdout.write(`Removed ${String(n)} scope item(s)
597
+ `)}async function Sh({cfg:e,slug:t}){let n=(await b({config:e,document:yh,variables:{cwd:e.cwd,projectId:e.projectId,slug:t}})).project?.devSession?.workflows?.[0];return n==null&&(process.stderr.write(`No workflow found with id "${t}". Create a stub first via the testing DSL.
598
598
  `),process.stderr.write(`${R("create")}
599
- `),process.exit(1)),n.id}async function Bs(e){let t=process.cwd(),r=await j(t);r.ok||(process.stderr.write(`Compilation failed: ${r.error}
599
+ `),process.exit(1)),n.id}async function ea(e){let t=process.cwd(),r=await j(t);r.ok||(process.stderr.write(`Compilation failed: ${r.error}
600
600
  `),process.exit(1));let{tests:n}=r.builder.getUnimplemented();if(e.format==="summary"){n.length>0&&process.stdout.write(`tests: ${n.join(", ")}
601
601
  `);return}let o={tests:n.map(i=>({id:i,implemented:!1}))};process.stdout.write(`${JSON.stringify(o,null,2)}
602
- `)}import{z as lh}from"zod";function N(e,t){let r=lh.custom(n=>typeof n=="object"&&n!==null&&"hook_event_name"in n&&n.hook_event_name===e);return{event:e,run:async n=>await t(r.parse(n))??void 0}}import{createHash as h$}from"crypto";import Ws from"picomatch";function ch(e){return X(["diff","--name-only","HEAD"],e).split(`
603
- `).filter(t=>t.length>0)}function zs({cwd:e,ignoreGlobs:t,watchGlobs:r}){let n=Ws([...r]),o=Ws([...t]);return ch(e).filter(i=>n(i)&&!o(i))}function Xt(e,...t){return X(["diff","--name-only","HEAD","--",...t],e).split(`
604
- `).filter(r=>r.length>0)}import{createHash as dh}from"crypto";import{mkdirSync as uh,readFileSync as Gs,writeFileSync as ph}from"fs";import Pn from"path";var mh=[".ts",".tsx",".js",".jsx"];function We(e){let t=dh("sha256");return t.update(X(["rev-parse","HEAD"],e)),t.update("\0"),t.update(X(["diff","HEAD"],e)),t.update("\0"),X(["ls-files","--others","--exclude-standard"],e).split(`
605
- `).filter(n=>n.length>0).filter(n=>mh.some(o=>n.endsWith(o))).toSorted((n,o)=>n.localeCompare(o)).forEach(n=>{t.update(n),t.update("\0"),t.update(fh(Pn.join(e,n))),t.update("\0")}),t.digest("hex")}function ze(e,t){try{return Gs(Js(e,t),"utf8").trim()}catch{return null}}function Ge(e,t,r){let n=Js(e,t);uh(Pn.dirname(n),{recursive:!0}),ph(n,r)}function Js(e,t){return Pn.join(e,".ripplo",".local",`${t}.hash`)}function fh(e){try{return Gs(e)}catch{return Buffer.alloc(0)}}function xe(){return{ignorePaths:Pe,watchPaths:un}}var Ks=N("UserPromptSubmit",e=>{let{cwd:t}=e;if(!I(t)||!V(t))return;let r=We(t);if(ze(t,"coverage-nudge")===r)return;let{ignorePaths:n,watchPaths:o}=xe(),i=zs({cwd:t,ignoreGlobs:n,watchGlobs:o});if(Ge(t,"coverage-nudge",r),!(i.length===0||Xt(t,".ripplo/tests",".ripplo/preconditions",".ripplo/observers").length>0))return{hookSpecificOutput:{additionalContext:`SCOPE DRIFT: ${String(i.length)} app file(s) changed without .ripplo/tests updates. ${R("scope")}`,hookEventName:"UserPromptSubmit"}}});import Qt from"fs";import gh from"os";import Ys from"path";var Xs=N("PreToolUse",e=>{if(e.tool_name!=="ExitPlanMode"||!V(e.cwd))return;let t=yh();if(t==null)return;let r=Qt.readFileSync(t,"utf8");if(!/\.ripplo\/tests|Tests to implement|No e2e coverage needed/.test(r))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Plan must cite ripplo test stubs. Add a "Tests to implement" section listing .ripplo/tests/<id>.ts per affected flow, OR add "No e2e coverage needed: <reason>" if this plan touches no user-facing behavior. ${R("explore")}`}}});function yh(){let e=Ys.join(gh.homedir(),".claude","plans");return Qt.existsSync(e)?Qt.readdirSync(e).filter(r=>r.endsWith(".md")).map(r=>Ys.join(e,r)).map(r=>({full:r,mtime:Qt.statSync(r).mtimeMs})).sort((r,n)=>n.mtime-r.mtime)[0]?.full??null:null}var Qs=N("UserPromptSubmit",async e=>{if(e.permission_mode!=="plan"||!I(e.cwd)||!V(e.cwd))return;let t=await j(e.cwd);if(!t.ok)return;let{tests:r}=t.builder.getUnimplemented(),n=['Plan must include "Tests to implement" with .ripplo/tests/<id>.ts per affected flow (ExitPlanMode blocks otherwise).'];return r.length>0&&n.push(`Existing stubs: ${r.join(", ")}`),{hookSpecificOutput:{additionalContext:n.join(`
606
- `),hookEventName:"UserPromptSubmit"}}});import hh from"path";import Zs from"picomatch";import{z as ea}from"zod";var wh=ea.looseObject({file_path:ea.string()}),ta=N("PostToolUse",async e=>{let t=wh.safeParse(e.tool_input);if(!t.success)return;let r=t.data.file_path,{cwd:n}=e;if(!I(n)||!V(n))return;let o=hh.relative(n,r);if(o.startsWith(".."))return;let{ignorePaths:i,watchPaths:s}=xe(),a=Zs([...s]),l=Zs([...i]);if(!a(o)||l(o))return;let c=await j(n);if(!c.ok)return;let{tests:d}=c.builder.getUnimplemented();if(d.length!==0)return{hookSpecificOutput:{additionalContext:`Reminder: .notImplemented() stubs still present \u2014 tests: ${d.join(", ")}`,hookEventName:"PostToolUse"}}});import{z as ra}from"zod";var bh=ra.looseObject({file_path:ra.string()}),na=N("PostToolUse",async e=>{let t=bh.safeParse(e.tool_input);if(!t.success)return;let r=t.data.file_path;if(!/\/\.ripplo\/.*\.ts$/.test(r))return;let{cwd:n}=e;if(!I(n)||!V(n))return;let o=await j(n);if(!o.ok)return{decision:"block",reason:`Compilation failed: ${o.error}
607
- ${R("create","DSL authoring + lint rules")}`};await de({cwd:n,result:o.result}),Fe({cwd:n});let{diagnostics:i}=Ue(o.result);if(i.length===0){let{addedSlugs:a}=await Kt({compileResult:o,cwd:n});return a.length===0?void 0:{hookSpecificOutput:{additionalContext:`Auto-scoped ${a.join(", ")} (dirty tests).`,hookEventName:"PostToolUse"}}}return{decision:"block",reason:`${i.map(a=>{let l=a.step==null?"":` at "${a.step}"`;return` [${a.rule}]${l} ${a.test}: ${a.message}`}).join(`
602
+ `)}import{z as vh}from"zod";function N(e,t){let r=vh.custom(n=>typeof n=="object"&&n!==null&&"hook_event_name"in n&&n.hook_event_name===e);return{event:e,run:async n=>await t(r.parse(n))??void 0}}import{createHash as O$}from"crypto";import ta from"picomatch";function kh(e){return Q(["diff","--name-only","HEAD"],e).split(`
603
+ `).filter(t=>t.length>0)}function ra({cwd:e,ignoreGlobs:t,watchGlobs:r}){let n=ta([...r]),o=ta([...t]);return kh(e).filter(i=>n(i)&&!o(i))}function rr(e,...t){return Q(["diff","--name-only","HEAD","--",...t],e).split(`
604
+ `).filter(r=>r.length>0)}import{createHash as Rh}from"crypto";import{mkdirSync as Ph,readFileSync as na,writeFileSync as xh}from"fs";import An from"path";var Ch=[".ts",".tsx",".js",".jsx"];function Ge(e){let t=Rh("sha256");return t.update(Q(["rev-parse","HEAD"],e)),t.update("\0"),t.update(Q(["diff","HEAD"],e)),t.update("\0"),Q(["ls-files","--others","--exclude-standard"],e).split(`
605
+ `).filter(n=>n.length>0).filter(n=>Ch.some(o=>n.endsWith(o))).toSorted((n,o)=>n.localeCompare(o)).forEach(n=>{t.update(n),t.update("\0"),t.update(Eh(An.join(e,n))),t.update("\0")}),t.digest("hex")}function Je(e,t){try{return na(oa(e,t),"utf8").trim()}catch{return null}}function Ke(e,t,r){let n=oa(e,t);Ph(An.dirname(n),{recursive:!0}),xh(n,r)}function oa(e,t){return An.join(e,".ripplo",".local",`${t}.hash`)}function Eh(e){try{return na(e)}catch{return Buffer.alloc(0)}}function Ee(){return{ignorePaths:Ce,watchPaths:hn}}var ia=N("UserPromptSubmit",e=>{let{cwd:t}=e;if(!I(t)||!V(t))return;let r=Ge(t);if(Je(t,"coverage-nudge")===r)return;let{ignorePaths:n,watchPaths:o}=Ee(),i=ra({cwd:t,ignoreGlobs:n,watchGlobs:o});if(Ke(t,"coverage-nudge",r),!(i.length===0||rr(t,".ripplo/tests",".ripplo/preconditions",".ripplo/observers").length>0))return{hookSpecificOutput:{additionalContext:`SCOPE DRIFT: ${String(i.length)} app file(s) changed without .ripplo/tests updates. ${R("scope")}`,hookEventName:"UserPromptSubmit"}}});import nr from"fs";import Th from"os";import sa from"path";var aa=N("PreToolUse",e=>{if(e.tool_name!=="ExitPlanMode"||!V(e.cwd))return;let t=$h();if(t==null)return;let r=nr.readFileSync(t,"utf8");if(!/\.ripplo\/tests|Tests to implement|No e2e coverage needed/.test(r))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Plan must cite ripplo test stubs. Add a "Tests to implement" section listing .ripplo/tests/<id>.ts per affected flow, OR add "No e2e coverage needed: <reason>" if this plan touches no user-facing behavior. ${R("explore")}`}}});function $h(){let e=sa.join(Th.homedir(),".claude","plans");return nr.existsSync(e)?nr.readdirSync(e).filter(r=>r.endsWith(".md")).map(r=>sa.join(e,r)).map(r=>({full:r,mtime:nr.statSync(r).mtimeMs})).sort((r,n)=>n.mtime-r.mtime)[0]?.full??null:null}var la=N("UserPromptSubmit",async e=>{if(e.permission_mode!=="plan"||!I(e.cwd)||!V(e.cwd))return;let t=await j(e.cwd);if(!t.ok)return;let{tests:r}=t.builder.getUnimplemented(),n=['Plan must include "Tests to implement" with .ripplo/tests/<id>.ts per affected flow (ExitPlanMode blocks otherwise).'];return r.length>0&&n.push(`Existing stubs: ${r.join(", ")}`),{hookSpecificOutput:{additionalContext:n.join(`
606
+ `),hookEventName:"UserPromptSubmit"}}});import Ah from"path";import ca from"picomatch";import{z as da}from"zod";var Ih=da.looseObject({file_path:da.string()}),ua=N("PostToolUse",async e=>{let t=Ih.safeParse(e.tool_input);if(!t.success)return;let r=t.data.file_path,{cwd:n}=e;if(!I(n)||!V(n))return;let o=Ah.relative(n,r);if(o.startsWith(".."))return;let{ignorePaths:i,watchPaths:s}=Ee(),a=ca([...s]),l=ca([...i]);if(!a(o)||l(o))return;let c=await j(n);if(!c.ok)return;let{tests:d}=c.builder.getUnimplemented();if(d.length!==0)return{hookSpecificOutput:{additionalContext:`Reminder: .notImplemented() stubs still present \u2014 tests: ${d.join(", ")}`,hookEventName:"PostToolUse"}}});import{z as pa}from"zod";var jh=pa.looseObject({file_path:pa.string()}),ma=N("PostToolUse",async e=>{let t=jh.safeParse(e.tool_input);if(!t.success)return;let r=t.data.file_path;if(!/\/\.ripplo\/.*\.ts$/.test(r))return;let{cwd:n}=e;if(!I(n)||!V(n))return;let o=await j(n);if(!o.ok)return{decision:"block",reason:`Compilation failed: ${o.error}
607
+ ${R("create","DSL authoring + lint rules")}`};await ue({cwd:n,result:o.result}),Be({cwd:n});let{diagnostics:i}=Fe(o.result);if(i.length===0){let{addedSlugs:a}=await er({compileResult:o,cwd:n});return a.length===0?void 0:{hookSpecificOutput:{additionalContext:`Auto-scoped ${a.join(", ")} (dirty tests).`,hookEventName:"PostToolUse"}}}return{decision:"block",reason:`${i.map(a=>{let l=a.step==null?"":` at "${a.step}"`;return` [${a.rule}]${l} ${a.test}: ${a.message}`}).join(`
608
608
  `)}
609
- ${R("create")}`}});import{z as oa}from"zod";var Sh=oa.looseObject({command:oa.string()}),vh=/\bripplo\s+hooks\s+pause\b/,ia=N("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=Sh.safeParse(e.tool_input);if(!t.success||!vh.test(t.data.command))return;let{cwd:r}=e;if(I(r))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"`ripplo hooks pause` is a human-only escape hatch \u2014 agents can't bypass Ripplo guardrails on their own. If watch genuinely can't start (auth, server down, intentional offline work), surface the blocker to the user and ask them to run `npx ripplo hooks pause` themselves from their terminal."}}});import{parse as Ch}from"shell-quote";import{z as la}from"zod";import{existsSync as kh,mkdirSync as Rh,rmSync as bA,writeFileSync as Ph}from"fs";import xn from"path";function sa(e,t,r){let n=aa(e,t,r);Rh(xn.dirname(n),{recursive:!0}),Ph(n,"")}function Zt(e,t,r){return kh(aa(e,t,r))}function xh(e,t){return xn.join(e,".ripplo",".local","skills-loaded",t)}function aa(e,t,r){return xn.join(xh(e,t),r)}var Eh=la.looseObject({command:la.string()}),Th="debug",$h=new Set(["tail","head","less","more","wc","sort","uniq","awk","sed","grep"]),da=N("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=Eh.safeParse(e.tool_input);if(!t.success)return;let r=Ah(t.data.command);if(!Ih(r))return;let{cwd:n}=e;if(!I(n)||!V(n))return;let o=Nh(r);if(o!=null)return ca(`Don't pipe \`ripplo run\` through \`${o}\` \u2014 buffering filters hold all stdout until EOF, hiding live progress; if you kill the pipeline mid-run the run is orphaned on the server. Redirect to a file instead: \`ripplo run <id> > /tmp/run.log 2>&1\` and Read the file, or use \`run_in_background: true\`.`);if(!Zt(n,e.session_id,Th))return ca("Running `ripplo run` requires the `/ripplo:debug` skill loaded first. Load `/ripplo:debug` then retry \u2014 it carries the artifact-read order, the 3-strike rule, and the no-grep-piping guidance for run failures.")});function Ah(e){try{return Ch(e)}catch{return[]}}function Ih(e){return e.some((t,r)=>t==="ripplo"&&e[r+1]==="run")}function jh(e){return typeof e=="object"&&"op"in e&&e.op==="|"}function Nh(e){let t=e.find((r,n)=>{let o=e[n-1];return o!=null&&jh(o)&&typeof r=="string"&&$h.has(r)});return typeof t=="string"?t:null}function ca(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}}}import Oh from"path";import{z as ua}from"zod";var Dh=new Set(["Edit","Write","NotebookEdit"]),Lh=ua.looseObject({file_path:ua.string()}),_h="create",pa=N("PreToolUse",e=>{if(!Dh.has(e.tool_name))return;let t=Lh.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!I(r)||!V(r))return;let n=Oh.relative(r,t.data.file_path);if(!(n.startsWith("..")||n!==".ripplo"&&!n.startsWith(".ripplo/"))&&!Zt(r,e.session_id,_h))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Editing \`.ripplo/\` files (${n}) requires the \`/ripplo:create\` skill loaded first. Load \`/ripplo:create\` then retry \u2014 it carries the DSL builder shape, lint rules, and the parallelization guidance you'll need.`}}});import Uh from"path";import ma from"picomatch";import{graphql as Vh}from"gql.tada";import{z as fa}from"zod";var Fh=new Set(["Edit","Write","NotebookEdit"]),Mh=fa.looseObject({file_path:fa.string()}),Hh=Vh(`
609
+ ${R("create")}`}});import{z as fa}from"zod";var Nh=fa.looseObject({command:fa.string()}),Oh=/\bripplo\s+hooks\s+pause\b/,ga=N("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=Nh.safeParse(e.tool_input);if(!t.success||!Oh.test(t.data.command))return;let{cwd:r}=e;if(I(r))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"`ripplo hooks pause` is a human-only escape hatch \u2014 agents can't bypass Ripplo guardrails on their own. If watch genuinely can't start (auth, server down, intentional offline work), surface the blocker to the user and ask them to run `npx ripplo hooks pause` themselves from their terminal."}}});import{parse as Vh}from"shell-quote";import{z as wa}from"zod";import{existsSync as Dh,mkdirSync as _h,rmSync as _A,writeFileSync as Lh}from"fs";import In from"path";function ya(e,t,r){let n=ha(e,t,r);_h(In.dirname(n),{recursive:!0}),Lh(n,"")}function or(e,t,r){return Dh(ha(e,t,r))}function Uh(e,t){return In.join(e,".ripplo",".local","skills-loaded",t)}function ha(e,t,r){return In.join(Uh(e,t),r)}var Fh=wa.looseObject({command:wa.string()}),Mh="debug",Bh=new Set(["tail","head","less","more","wc","sort","uniq","awk","sed","grep"]),Sa=N("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=Fh.safeParse(e.tool_input);if(!t.success)return;let r=Hh(t.data.command);if(!qh(r))return;let{cwd:n}=e;if(!I(n)||!V(n))return;let o=zh(r);if(o!=null)return ba(`Don't pipe \`ripplo run\` through \`${o}\` \u2014 buffering filters hold all stdout until EOF, hiding live progress; if you kill the pipeline mid-run the run is orphaned on the server. Redirect to a file instead: \`ripplo run <id> > /tmp/run.log 2>&1\` and Read the file, or use \`run_in_background: true\`.`);if(!or(n,e.session_id,Mh))return ba("Running `ripplo run` requires the `/ripplo:debug` skill loaded first. Load `/ripplo:debug` then retry \u2014 it carries the artifact-read order, the 3-strike rule, and the no-grep-piping guidance for run failures.")});function Hh(e){try{return Vh(e)}catch{return[]}}function qh(e){return e.some((t,r)=>t==="ripplo"&&e[r+1]==="run")}function Wh(e){return typeof e=="object"&&"op"in e&&e.op==="|"}function zh(e){let t=e.find((r,n)=>{let o=e[n-1];return o!=null&&Wh(o)&&typeof r=="string"&&Bh.has(r)});return typeof t=="string"?t:null}function ba(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}}}import Gh from"path";import{z as va}from"zod";var Jh=new Set(["Edit","Write","NotebookEdit"]),Kh=va.looseObject({file_path:va.string()}),Yh="create",ka=N("PreToolUse",e=>{if(!Jh.has(e.tool_name))return;let t=Kh.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!I(r)||!V(r))return;let n=Gh.relative(r,t.data.file_path);if(!(n.startsWith("..")||n!==".ripplo"&&!n.startsWith(".ripplo/"))&&!or(r,e.session_id,Yh))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Editing \`.ripplo/\` files (${n}) requires the \`/ripplo:create\` skill loaded first. Load \`/ripplo:create\` then retry \u2014 it carries the DSL builder shape, lint rules, and the parallelization guidance you'll need.`}}});import Xh from"path";import Ra from"picomatch";import{graphql as Qh}from"gql.tada";import{z as Pa}from"zod";var Zh=new Set(["Edit","Write","NotebookEdit"]),ew=Pa.looseObject({file_path:Pa.string()}),tw=Qh(`
610
610
  query PreEditScopeGate($projectId: String!, $cwd: String!) {
611
611
  project(id: $projectId) {
612
612
  id
@@ -618,7 +618,7 @@ ${R("create")}`}});import{z as oa}from"zod";var Sh=oa.looseObject({command:oa.st
618
618
  }
619
619
  }
620
620
  }
621
- `),ga=N("PreToolUse",async e=>{if(!Fh.has(e.tool_name))return;let t=Mh.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!I(r)||!V(r))return;let n=Uh.relative(r,t.data.file_path);if(!(n.startsWith("..")||n===".ripplo"||n.startsWith(".ripplo/")||!qh(n)||await Bh(r)))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Scope empty; edit touches app code (${n}). Stub a test or \`scope add\` an existing one before proceeding \u2014 or acknowledge "no user-facing behavior" if pure refactor. Hook re-fires until scope is populated (or hooks paused via the web UI). ${Zi(["scope","create"])}`}}});function qh(e){let{ignorePaths:t,watchPaths:r}=xe(),n=ma([...r]),o=ma([...t]);return n(e)&&!o(e)}async function Bh(e){let t;try{t=B(e)}catch{return!0}let r=await b({config:t,document:Hh,variables:{cwd:t.cwd,projectId:t.projectId}}).catch(()=>null);return r==null?!0:(r.project?.devSession?.scopeItems??[]).length>0}import Wh from"fs";import zh from"path";import{z as ya}from"zod";var Gh=new Set(["Edit","Write","NotebookEdit"]),Jh=ya.looseObject({file_path:ya.string()}),ha=N("PreToolUse",e=>{if(!Gh.has(e.tool_name))return;let t=Jh.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!I(r))return;let n=zh.relative(r,t.data.file_path);if(!(n.startsWith("..")||n!==".ripplo"&&!n.startsWith(".ripplo/"))&&!Wh.existsSync(pe(r))&&!He(r))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`\`ripplo watch\` is not running, so this edit to \`${n}\` won't sync to the server and dev-mode guardrails won't fire. Run \`/ripplo:start\` (or spawn \`npx ripplo watch\` directly via Bash with run_in_background), then retry. The app's dev server also needs to be running \u2014 \`npx ripplo doctor\` reports both. If watch can't start (auth, server down, intentional offline work), the user can run \`npx ripplo hooks pause\` to bypass this gate; \`npx ripplo hooks resume\` re-enables it. ${R("start")}`}}});import{graphql as Kh}from"gql.tada";var Yh=Kh(`
621
+ `),xa=N("PreToolUse",async e=>{if(!Zh.has(e.tool_name))return;let t=ew.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!I(r)||!V(r))return;let n=Xh.relative(r,t.data.file_path);if(!(n.startsWith("..")||n===".ripplo"||n.startsWith(".ripplo/")||!rw(n)||await nw(r)))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Scope empty; edit touches app code (${n}). Stub a test or \`scope add\` an existing one before proceeding \u2014 or acknowledge "no user-facing behavior" if pure refactor. Hook re-fires until scope is populated (or hooks paused via the web UI). ${cs(["scope","create"])}`}}});function rw(e){let{ignorePaths:t,watchPaths:r}=Ee(),n=Ra([...r]),o=Ra([...t]);return n(e)&&!o(e)}async function nw(e){let t;try{t=q(e)}catch{return!0}let r=await b({config:t,document:tw,variables:{cwd:t.cwd,projectId:t.projectId}}).catch(()=>null);return r==null?!0:(r.project?.devSession?.scopeItems??[]).length>0}import ow from"fs";import iw from"path";import{z as Ca}from"zod";var sw=new Set(["Edit","Write","NotebookEdit"]),aw=Ca.looseObject({file_path:Ca.string()}),Ea=N("PreToolUse",e=>{if(!sw.has(e.tool_name))return;let t=aw.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!I(r))return;let n=iw.relative(r,t.data.file_path);if(!(n.startsWith("..")||n!==".ripplo"&&!n.startsWith(".ripplo/"))&&!ow.existsSync(me(r))&&!qe(r))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`\`ripplo watch\` is not running, so this edit to \`${n}\` won't sync to the server and dev-mode guardrails won't fire. Run \`/ripplo:start\` (or spawn \`npx ripplo watch\` directly via Bash with run_in_background), then retry. The app's dev server also needs to be running \u2014 \`npx ripplo doctor\` reports both. If watch can't start (auth, server down, intentional offline work), the user can run \`npx ripplo hooks pause\` to bypass this gate; \`npx ripplo hooks resume\` re-enables it. ${R("start")}`}}});import{graphql as lw}from"gql.tada";var cw=lw(`
622
622
  query ScopeReminder($projectId: String!, $cwd: String!) {
623
623
  project(id: $projectId) {
624
624
  id
@@ -635,9 +635,9 @@ ${R("create")}`}});import{z as oa}from"zod";var Sh=oa.looseObject({command:oa.st
635
635
  }
636
636
  }
637
637
  }
638
- `),wa=N("UserPromptSubmit",async e=>{let{cwd:t}=e;if(!I(t)||!V(t))return;let r=We(t);if(ze(t,"scope-reminder")===r)return;let n;try{n=B(t)}catch{return}let o=await b({config:n,document:Yh,variables:{cwd:n.cwd,projectId:n.projectId}}).catch(()=>null);if(o==null)return;Ge(t,"scope-reminder",r);let i=o.project?.devSession?.scopeItems??[];return{hookSpecificOutput:{additionalContext:i.length===0?`RIPPLO SCOPE: empty. ${R("scope")}`:`RIPPLO SCOPE (${String(i.length)}):
638
+ `),Ta=N("UserPromptSubmit",async e=>{let{cwd:t}=e;if(!I(t)||!V(t))return;let r=Ge(t);if(Je(t,"scope-reminder")===r)return;let n;try{n=q(t)}catch{return}let o=await b({config:n,document:cw,variables:{cwd:n.cwd,projectId:n.projectId}}).catch(()=>null);if(o==null)return;Ke(t,"scope-reminder",r);let i=o.project?.devSession?.scopeItems??[];return{hookSpecificOutput:{additionalContext:i.length===0?`RIPPLO SCOPE: empty. ${R("scope")}`:`RIPPLO SCOPE (${String(i.length)}):
639
639
  ${i.map(a=>{let l=a.workflow;return l==null?` [intent] (${a.id}) ${a.label??""}`:` [${l.spec==null?"stub":"implemented"}] (${a.id}) ${l.slug}`}).join(`
640
- `)}`,hookEventName:"UserPromptSubmit"}}});var Xh="# Ripplo \u2014 always-on session context\n\nEvery user-facing change in this repo ships with a deterministic, backend-aware test that proves it works end-to-end.\n\n## Load the right skill before acting \u2014 this is critical\n\nThe skills below carry the procedural detail you need to do Ripplo work correctly: precondition isolation, observer budget tiers, coverage IDs, scope discipline, artifact-read order on failures, parallelization patterns. **None of that is reproduced in this preamble** \u2014 only the always-on guardrails are. If you act on a Ripplo task without loading the matching skill, you will skip rules that exist to prevent specific past failure modes (cross-run data leakage, \"passing\" tests that never asserted backend state, cleared coverage gates without proof, etc.).\n\nMatch the task to a skill from the triage table; if unsure between two, load both. If completely unsure, load `/ripplo:explore` or `/ripplo:create`. Loading is cheap; acting under-informed is not.\n\n## Skill triage\n\n- Load `/ripplo:setup` skill for instructions on initializing Ripplo in a project; `ripplo doctor` reports the engine endpoint missing.\n- Load `/ripplo:explore` skill for instructions on planning/stubbing test coverage for a new project or new feature area.\n- Load `/ripplo:scope` skill for instructions on managing the working set of tests this session is responsible for.\n- Load `/ripplo:create` skill for instructions on authoring a single test spec for a user flow.\n- Load `/ripplo:run` skill for instructions on executing existing tests.\n- Load `/ripplo:debug` skill for instructions on a failed run; read artifacts in `.ripplo/debug/<runId>/` before re-running.\n- Load `/ripplo:flake-detect` skill for instructions on intermittent failures; parallelizes N runs (only use with evidence of flake).\n\n## Universal rules\n\n- **Two background processes must be running before feature work.** (1) The app's dev server, so the app is reachable; (2) `npx ripplo watch` (run `/ripplo:start` to spawn it, or invoke it directly via Bash with `run_in_background`), so the dev session is live. Without watch, scope/coverage hooks don't arm and `ripplo run` refuses to dispatch. Without the dev server, runs fail when they try to hit the app. `npx ripplo doctor` reports both.\n- **Two funnels.** Definitions \u2192 `createRipplo({ preconditions, observers, tests })` in `.ripplo/index.ts`. Implementations \u2192 `createEngine(ripplo, { preconditions, observers })` in your app server's `test/engine.ts`. Never call either elsewhere. TS enforces exhaustiveness across both.\n- **\"Done\" = app code delivers the behavior AND a passing test proves it.** Both halves. Shipping without a test isn't done; writing a test against broken UI/API isn't done.\n- **Scope is your job.** For any non-trivial change, enumerate every flow it could affect and either `scope add` existing tests or stub `.notImplemented()` tests. Don't wait to be told.\n- **`scope remove` is never for size/effort.** Valid only when an item is genuinely out of scope (wrong flow, duplicate, user said \"not this session,\" feature cut). \"Too many stubs\" \u2192 parallelize with subagents. Don't present \"implement vs. remove\" as a neutral A/B.\n- **Stub gates are not a question.** When `stop-enforce` blocks on `.notImplemented()` stubs, implement them \u2014 don't ask the user \"implement or defer?\", don't propose pausing hooks as option B. The fix isn't done until the test is. New scaffolding (precondition, observer, engine impl) is in-scope work, not follow-up.\n- **`uiOnly: true` is not a stub.** Observer wiring is in-scope for mutation flows; don't use it to silence observer lint.\n- **Never weaken a test to make it pass.** No `contains`/regex for exact text, no removed assertions, no fabricated locators. App lacks an accessible name \u2192 add one to the app, don't fall back to `testId()`. App bug \u2192 report with evidence.\n- **Artifacts first, re-run last.** Failed runs produce DOM, a11y tree, console, network, screenshots under `.ripplo/debug/<runId>/`. Read them. Never pipe `ripplo run` through `grep`/`tail`/`head`. Form a hypothesis citing an artifact line, make ONE change, re-run once.\n- **3-strike rule.** Same failure after 3 targeted fixes \u2192 stop and report. Repeated failure on the same step almost always means the diagnosis is wrong.\n- **`.ripplo/ripplo.lock` is committed, never hand-edited.** `ripplo lint` / `ripplo compile` regenerates it. Pre-commit runs `ripplo compile --check`.\n- **Scratch files live in `.ripplo/.local/`.** Never loose in `.ripplo/`.\n- **Worktrees are self-contained.** Each worktree has its own `.ripplo/` checkout, DevSession, scope, and debug artifacts. Auth and projectId are shared globally. Env files (typically gitignored) won't carry over to a fresh worktree \u2014 copy from main or point at a shared file. **If sibling worktrees run dev servers on different ports, the worktree's env file MUST update both `RIPPLO_APP_URL` and `RIPPLO_ENGINE_URL` to match the port that worktree's dev server is bound to** (e.g. main on `:3000`, this worktree on `:3001` \u2192 set `RIPPLO_APP_URL=http://localhost:3001` and `RIPPLO_ENGINE_URL=http://localhost:3001/ripplo` in the worktree's env file). Mismatched ports = `npx ripplo watch` (whether started via `/ripplo:start` or manually) talks to the wrong server, runs silently fail or hit the sibling worktree's app.\n- **DSL locators are semantic.** No `css` / `placeholder` / `waitFor` / `group`.\n- **New backend assertion?** Declare in `.ripplo/observers/index.ts`, implement in your app server's `engine.ts` (TS flags the missing impl).\n\n## Key files\n\n- `.ripplo/index.ts` \u2014 `createRipplo` call.\n- `.ripplo/{preconditions,observers,tests}/index.ts` \u2014 registry aggregators.\n- `.ripplo/project.json` \u2014 project id + env-file pointers.\n- `<app>/src/test/engine.ts` \u2014 single impl funnel via `createEngine`.\n- `packages/testing/README.md` (or the npm page for `@ripplo/testing`) \u2014 DSL reference.\n",ba=N("SessionStart",e=>{if(I(e.cwd))return{hookSpecificOutput:{additionalContext:Xh,hookEventName:"SessionStart"}}});import{execFileSync as Qh}from"child_process";import Zh from"path";import Sa from"process";import{graphql as ew}from"gql.tada";import{z as er}from"zod";var tw=ew(`
640
+ `)}`,hookEventName:"UserPromptSubmit"}}});var dw="# Ripplo \u2014 always-on session context\n\nEvery user-facing change in this repo ships with a deterministic, backend-aware test that proves it works end-to-end.\n\n## Load the right skill before acting \u2014 this is critical\n\nThe skills below carry the procedural detail you need to do Ripplo work correctly: precondition isolation, observer budget tiers, coverage IDs, scope discipline, artifact-read order on failures, parallelization patterns. **None of that is reproduced in this preamble** \u2014 only the always-on guardrails are. If you act on a Ripplo task without loading the matching skill, you will skip rules that exist to prevent specific past failure modes (cross-run data leakage, \"passing\" tests that never asserted backend state, cleared coverage gates without proof, etc.).\n\nMatch the task to a skill from the triage table; if unsure between two, load both. If completely unsure, load `/ripplo:explore` or `/ripplo:create`. Loading is cheap; acting under-informed is not.\n\n## Skill triage\n\n- Load `/ripplo:setup` skill for instructions on initializing Ripplo in a project; `ripplo doctor` reports the engine endpoint missing.\n- Load `/ripplo:explore` skill for instructions on planning/stubbing test coverage for a new project or new feature area.\n- Load `/ripplo:scope` skill for instructions on managing the working set of tests this session is responsible for.\n- Load `/ripplo:create` skill for instructions on authoring a single test spec for a user flow.\n- Load `/ripplo:run` skill for instructions on executing existing tests.\n- Load `/ripplo:debug` skill for instructions on a failed run; read artifacts in `.ripplo/debug/<runId>/` before re-running.\n- Load `/ripplo:flake-detect` skill for instructions on intermittent failures; parallelizes N runs (only use with evidence of flake).\n\n## Universal rules\n\n- **Two background processes must be running before feature work.** (1) The app's dev server, so the app is reachable; (2) `npx ripplo watch` (run `/ripplo:start` to spawn it, or invoke it directly via Bash with `run_in_background`), so the dev session is live. Without watch, scope/coverage hooks don't arm and `ripplo run` refuses to dispatch. Without the dev server, runs fail when they try to hit the app. `npx ripplo doctor` reports both.\n- **Two funnels.** Definitions \u2192 `createRipplo({ preconditions, observers, tests })` in `.ripplo/index.ts`. Implementations \u2192 `createEngine(ripplo, { preconditions, observers })` in your app server's `test/engine.ts`. Never call either elsewhere. TS enforces exhaustiveness across both.\n- **\"Done\" = app code delivers the behavior AND a passing test proves it.** Both halves. Shipping without a test isn't done; writing a test against broken UI/API isn't done.\n- **Scope is your job.** For any non-trivial change, enumerate every flow it could affect and either `scope add` existing tests or stub `.notImplemented()` tests. Don't wait to be told.\n- **`scope remove` is never for size/effort.** Valid only when an item is genuinely out of scope (wrong flow, duplicate, user said \"not this session,\" feature cut). \"Too many stubs\" \u2192 parallelize with subagents. Don't present \"implement vs. remove\" as a neutral A/B.\n- **Stub gates are not a question.** When `stop-enforce` blocks on `.notImplemented()` stubs, implement them \u2014 don't ask the user \"implement or defer?\", don't propose pausing hooks as option B. The fix isn't done until the test is. New scaffolding (precondition, observer, engine impl) is in-scope work, not follow-up.\n- **`uiOnly: true` is not a stub.** Observer wiring is in-scope for mutation flows; don't use it to silence observer lint.\n- **Never weaken a test to make it pass.** No `contains`/regex for exact text, no removed assertions, no fabricated locators. App lacks an accessible name \u2192 add one to the app, don't fall back to `testId()`. App bug \u2192 report with evidence.\n- **Artifacts first, re-run last.** Failed runs produce DOM, a11y tree, console, network, screenshots under `.ripplo/debug/<runId>/`. Read them. Never pipe `ripplo run` through `grep`/`tail`/`head`. Form a hypothesis citing an artifact line, make ONE change, re-run once.\n- **3-strike rule.** Same failure after 3 targeted fixes \u2192 stop and report. Repeated failure on the same step almost always means the diagnosis is wrong.\n- **`.ripplo/ripplo.lock` is committed, never hand-edited.** `ripplo lint` / `ripplo compile` regenerates it. Pre-commit runs `ripplo compile --check`.\n- **Scratch files live in `.ripplo/.local/`.** Never loose in `.ripplo/`.\n- **Worktrees are self-contained.** Each worktree has its own `.ripplo/` checkout, DevSession, scope, and debug artifacts. Auth and projectId are shared globally. Env files (typically gitignored) won't carry over to a fresh worktree \u2014 copy from main or point at a shared file. **If sibling worktrees run dev servers on different ports, the worktree's env file MUST update both `RIPPLO_APP_URL` and `RIPPLO_ENGINE_URL` to match the port that worktree's dev server is bound to** (e.g. main on `:3000`, this worktree on `:3001` \u2192 set `RIPPLO_APP_URL=http://localhost:3001` and `RIPPLO_ENGINE_URL=http://localhost:3001/ripplo` in the worktree's env file). Mismatched ports = `npx ripplo watch` (whether started via `/ripplo:start` or manually) talks to the wrong server, runs silently fail or hit the sibling worktree's app.\n- **DSL locators are semantic.** No `css` / `placeholder` / `waitFor` / `group`.\n- **New backend assertion?** Declare in `.ripplo/observers/index.ts`, implement in your app server's `engine.ts` (TS flags the missing impl).\n\n## Key files\n\n- `.ripplo/index.ts` \u2014 `createRipplo` call.\n- `.ripplo/{preconditions,observers,tests}/index.ts` \u2014 registry aggregators.\n- `.ripplo/project.json` \u2014 project id + env-file pointers.\n- `<app>/src/test/engine.ts` \u2014 single impl funnel via `createEngine`.\n- `packages/testing/README.md` (or the npm page for `@ripplo/testing`) \u2014 DSL reference.\n",$a=N("SessionStart",e=>{if(I(e.cwd))return{hookSpecificOutput:{additionalContext:dw,hookEventName:"SessionStart"}}});import{execFileSync as uw}from"child_process";import pw from"path";import Aa from"process";import{graphql as mw}from"gql.tada";import{z as ir}from"zod";var fw=mw(`
641
641
  query ScopeEnforce($projectId: String!, $cwd: String!) {
642
642
  project(id: $projectId) {
643
643
  id
@@ -656,14 +656,14 @@ ${i.map(a=>{let l=a.workflow;return l==null?` [intent] (${a.id}) ${a.label??""}
656
656
  }
657
657
  }
658
658
  }
659
- `),ka=N("Stop",async e=>{let{cwd:t}=e;if(!I(t)||!V(t))return;let r=We(t),n=ze(t,"stop-enforce")===r;if(n&&!e.stop_hook_active)return;let o=rw(t),i=await nw(t,o);if(Ge(t,"stop-enforce",r),i.length!==0)return n&&e.stop_hook_active?{continue:!1,stopReason:`Stop-enforce: same repo state across consecutive stop attempts; agent appears stuck. Errors:
659
+ `),ja=N("Stop",async e=>{let{cwd:t}=e;if(!I(t)||!V(t))return;let r=Ge(t),n=Je(t,"stop-enforce")===r;if(n&&!e.stop_hook_active)return;let o=gw(t),i=await yw(t,o);if(Ke(t,"stop-enforce",r),i.length!==0)return n&&e.stop_hook_active?{continue:!1,stopReason:`Stop-enforce: same repo state across consecutive stop attempts; agent appears stuck. Errors:
660
660
  ${i.join(`
661
661
 
662
662
  `)}`}:{decision:"block",reason:i.join(`
663
663
 
664
- `)}});function rw(e){return Xt(e,".ripplo/tests").filter(t=>t.endsWith(".ts")).map(t=>Zh.basename(t,".ts")).filter(t=>t!=="index")}async function nw(e,t){let r=await j(e);if(!r.ok)return[`--- Compilation failed ---
664
+ `)}});function gw(e){return rr(e,".ripplo/tests").filter(t=>t.endsWith(".ts")).map(t=>pw.basename(t,".ts")).filter(t=>t!=="index")}async function yw(e,t){let r=await j(e);if(!r.ok)return[`--- Compilation failed ---
665
665
  ${r.error}
666
- ${R("create")}`];await de({cwd:e,result:r.result}),Fe({cwd:e});let n=await iw(e),o=[...new Set([...t,...n.scopedSlugsToRun])],i=sw(r,t),s=aw(r),a=ow(e,r),l=lw(e,o);return[i,s,a,l,n.error].filter(c=>c!=null)}function ow(e,t){let{ignorePaths:r}=xe(),n=ts({compileResult:t.result,cwd:e,ignorePaths:r});if(n.length===0)return null;let o=n.filter(a=>a.kind==="unacknowledged"),i=n.filter(a=>a.kind==="stale"),s=[];if(o.length>0){let a=o.map(l=>` ${l.id}`).join(`
666
+ ${R("create")}`];await ue({cwd:e,result:r.result}),Be({cwd:e});let n=await ww(e),o=[...new Set([...t,...n.scopedSlugsToRun])],i=bw(r,t),s=Sw(r),a=hw(e,r),l=vw(e,o);return[i,s,a,l,n.error].filter(c=>c!=null)}function hw(e,t){let{ignorePaths:r}=Ee(),n=us({compileResult:t.result,cwd:e,ignorePaths:r});if(n.length===0)return null;let o=n.filter(a=>a.kind==="unacknowledged"),i=n.filter(a=>a.kind==="stale"),s=[];if(o.length>0){let a=o.map(l=>` ${l.id}`).join(`
667
667
  `);s.push(`Unacknowledged interactions (add to a test's .coverage(...)):
668
668
  ${a}`)}if(i.length>0){let a=i.map(l=>` ${l.id}`).join(`
669
669
  `);s.push(`Stale .coverage(...) claims (id no longer exists in source):
@@ -671,23 +671,23 @@ ${a}`)}return`--- Exhaustiveness ---
671
671
  ${s.join(`
672
672
 
673
673
  `)}
674
- ${R("create")}`}async function iw(e){let t;try{t=B(e)}catch{return{error:null,scopedSlugsToRun:[]}}let n=(await b({config:t,document:tw,variables:{cwd:t.cwd,projectId:t.projectId}}).catch(()=>null))?.project?.devSession?.scopeItems??[],o=n.flatMap(a=>{let l=a.workflow;return l==null?[` [intent] ${a.label??"(no label)"} \u2014 stub a test for this flow`]:l.spec==null?[` [stub] ${l.slug} \u2014 implement \`${l.name}\``]:[]}),i=n.flatMap(a=>a.workflow?.spec==null?[]:[a.workflow.slug]);return{error:o.length===0?null:`--- Testing Scope ---
674
+ ${R("create")}`}async function ww(e){let t;try{t=q(e)}catch{return{error:null,scopedSlugsToRun:[]}}let n=(await b({config:t,document:fw,variables:{cwd:t.cwd,projectId:t.projectId}}).catch(()=>null))?.project?.devSession?.scopeItems??[],o=n.flatMap(a=>{let l=a.workflow;return l==null?[` [intent] ${a.label??"(no label)"} \u2014 stub a test for this flow`]:l.spec==null?[` [stub] ${l.slug} \u2014 implement \`${l.name}\``]:[]}),i=n.flatMap(a=>a.workflow?.spec==null?[]:[a.workflow.slug]);return{error:o.length===0?null:`--- Testing Scope ---
675
675
  ${o.join(`
676
676
  `)}
677
- ${R("create")}`,scopedSlugsToRun:i}}function sw(e,t){let{diagnostics:r}=Ue(e.result),n=new Set(e.builder.getUnimplemented().tests),o=t.filter(a=>n.has(a));if(r.length===0&&o.length===0)return null;let i=r.map(a=>{let l=a.step==null?"":` at "${a.step}"`;return` [${a.rule}]${l} ${a.test}: ${a.message}`}),s=o.map(a=>` [not-implemented] ${a} is still marked .notImplemented()`);return`--- Ripplo Lint ---
677
+ ${R("create")}`,scopedSlugsToRun:i}}function bw(e,t){let{diagnostics:r}=Fe(e.result),n=new Set(e.builder.getUnimplemented().tests),o=t.filter(a=>n.has(a));if(r.length===0&&o.length===0)return null;let i=r.map(a=>{let l=a.step==null?"":` at "${a.step}"`;return` [${a.rule}]${l} ${a.test}: ${a.message}`}),s=o.map(a=>` [not-implemented] ${a} is still marked .notImplemented()`);return`--- Ripplo Lint ---
678
678
  ${[...i,...s].join(`
679
679
  `)}
680
- ${R("create")}`}function aw(e){let{tests:t}=e.builder.getUnimplemented();return t.length===0?null:`--- Unimplemented stubs ---
680
+ ${R("create")}`}function Sw(e){let{tests:t}=e.builder.getUnimplemented();return t.length===0?null:`--- Unimplemented stubs ---
681
681
  ${t.join(", ")}
682
682
  Implement the stub now. Do not ask the user "implement or defer?" \u2014 that framing is forbidden by /ripplo:create. New scaffolding (precondition, observer, engine impl) is in-scope, not follow-up.
683
- ${R("create")}`}function lw(e,t){if(t.length===0)return null;let r=dw(["run",...t],e);if(r.code===0)return null;let n=r.output.split(`
683
+ ${R("create")}`}function vw(e,t){if(t.length===0)return null;let r=Rw(["run",...t],e);if(r.code===0)return null;let n=r.output.split(`
684
684
  `).filter(o=>/FAILED/.test(o)).join(`
685
685
  `);return n.length===0?null:`--- Ripplo Run Failures (${t.join(" ")}) ---
686
686
  ${n}
687
- Artifacts: .ripplo/debug/<runId>/. ${R("debug")}`}var cw=er.object({status:er.number().nullish(),stderr:er.unknown().optional(),stdout:er.unknown().optional()});function va(e){return e instanceof Buffer?e.toString("utf8"):typeof e=="string"?e:""}function dw(e,t){let r=Sa.argv[1];if(r==null)return{code:1,output:""};try{return{code:0,output:Qh(Sa.execPath,[r,...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}}catch(n){let o=cw.safeParse(n);if(!o.success)return{code:1,output:""};let i=`${va(o.data.stdout)}${va(o.data.stderr)}`;return{code:o.data.status??1,output:i}}}import{z as Ra}from"zod";var uw=Ra.looseObject({skill:Ra.string()}),Pa=N("PostToolUse",e=>{if(e.tool_name!=="Skill")return;let t=uw.safeParse(e.tool_input);if(!t.success)return;let r=/^ripplo:(.+)$/.exec(t.data.skill);if(r==null)return;let n=r[1];n!=null&&I(e.cwd)&&sa(e.cwd,e.session_id,n)});vw();An(process.cwd());var xa={"coverage-nudge":Ks,"exit-plan-gate":Xs,"plan-reminder":Qs,"post-edit-flag-stubs":ta,"post-edit-lint":na,"pre-bash-hooks-pause-gate":ia,"pre-bash-run-gate":da,"pre-edit-ripplo-skill-gate":pa,"pre-edit-scope-gate":ga,"pre-edit-watch-gate":ha,"scope-reminder":wa,"session-preamble":ba,"stop-enforce":ka,"track-skill-load":Pa};async function fw(){await pw(mw(process.argv)).scriptName("ripplo").version("0.4.10").command("watch","Watch for run requests and execute locally",()=>{},()=>Vs()).command("auth <subcommand>","Manage authentication",Sw).command("projects <subcommand>","Inspect Ripplo projects",bw).command("hooks <subcommand>","Pause or resume Ripplo hooks",ww).command("init","Scaffold .ripplo/ in this project",e=>e.option("project",{type:"string"}).option("env",{type:"string"}).option("app-url",{type:"string"}).option("engine-url",{type:"string"}),e=>As({appUrl:e["app-url"],engineUrl:e["engine-url"],envFile:e.env,projectId:e.project})).command("run [ids..]","Run tests in parallel",e=>{let t=[];return e.positional("ids",{array:!0,default:t,describe:"Test ids to run (all if omitted)",type:"string"})},e=>Ds(e.ids)).command("lint [ids..]","Compile and lint tests (all or specific ids)",e=>{let t=[];return e.positional("ids",{array:!0,default:t,describe:"Test ids to lint (all if omitted)",type:"string"}).option("require-implemented",{array:!0,default:t,describe:"Test ids that must not be .notImplemented() \u2014 fails if any still are",type:"string"})},e=>Ns({ids:e.ids,requireImplemented:e["require-implemented"]})).command("flake-detect <id>","Run N times to detect flakiness",e=>e.positional("id",{demandOption:!0,type:"string"}).option("runs",{default:10,type:"number"}),e=>ks({id:e.id,runs:e.runs})).command("sync","Push the compiled .ripplo/ resources to the server (no run)",()=>{},()=>Ls()).command("compile","Compile the DSL and write .ripplo/ripplo.lock",e=>e.option("check",{default:!1,describe:"Exit non-zero if the lockfile is missing or stale (does not write)",type:"boolean"}),e=>es({check:e.check})).command("cover","Audit all coverage statements",()=>{},()=>is()).command("doctor","Check project health",()=>{},()=>ws()).command("status","Report unimplemented tests and preconditions",e=>e.option("format",{choices:["json","summary"],default:"json",describe:"Output format"}),e=>Bs({format:e.format})).command("scope <subcommand>","Manage testing scope",hw).command("hook <name>","Internal: run a Claude Code plugin hook",e=>e.positional("name",{choices:Object.keys(xa),demandOption:!0,type:"string"}),e=>gw(e.name)).strict().help().parse()}async function gw(e){let t=xa[e];t==null&&(process.stderr.write(`Unknown hook: ${e}
688
- `),process.exit(1));let r=await yw(),n=r.trim()===""?{}:JSON.parse(r),o=await t.run(n);o!=null&&process.stdout.write(JSON.stringify(o))}function yw(){return new Promise((e,t)=>{if(process.stdin.isTTY){e("");return}let r=[];process.stdin.on("data",n=>r.push(n)),process.stdin.on("end",()=>{e(Buffer.concat(r).toString("utf8"))}),process.stdin.on("error",t)})}fw().catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
689
- `),process.exit(1)});function hw(e){return e.command("status","Print the current scope",t=>t.option("format",{choices:["json","text"],default:"text",describe:"Output format"}),t=>Fs({format:t.format})).command("add <test-ids..>","Bind one or more existing tests (stubs or implemented) to scope as agent intent",t=>{let r=[];return t.positional("test-ids",{array:!0,default:r,demandOption:!0,describe:"Slugs of existing workflows",type:"string"})},t=>Ms({testIds:t["test-ids"]})).command("link <id> <test-id>","Link an existing scope item to a test",t=>t.positional("id",{demandOption:!0,describe:"Scope item id",type:"string"}).positional("test-id",{demandOption:!0,describe:"Slug of the workflow to link",type:"string"}),t=>Hs({id:t.id,testId:t["test-id"]})).command("remove <ids..>","Remove one or more scope items by id",t=>{let r=[];return t.positional("ids",{array:!0,default:r,demandOption:!0,describe:"Scope item ids",type:"string"})},t=>qs({ids:t.ids})).demandCommand(1)}function ww(e){return e.command("pause","Disable all Ripplo pre-edit gates and stop enforcement until resumed",()=>{},()=>Rs()).command("resume","Re-enable Ripplo hooks paused via `ripplo hooks pause`",()=>{},()=>Ps()).demandCommand(1)}function bw(e){return e.command("list","List projects you have access to (JSON)",()=>{},()=>Os()).demandCommand(1)}function Sw(e){return e.command("login","Authenticate via device flow",()=>{},()=>Ei()).command("status","Show authentication status",()=>{},()=>Ti()).command("logout","Remove the saved token",()=>{},()=>{$i()}).demandCommand(1)}function vw(){let e=process.cwd(),t=tr(e);t!=null&&t!==e&&(process.chdir(t),process.stderr.write(`ripplo: resolved .ripplo/ at ${t}
690
- `))}export{fw as main};
687
+ Artifacts: .ripplo/debug/<runId>/. ${R("debug")}`}var kw=ir.object({status:ir.number().nullish(),stderr:ir.unknown().optional(),stdout:ir.unknown().optional()});function Ia(e){return e instanceof Buffer?e.toString("utf8"):typeof e=="string"?e:""}function Rw(e,t){let r=Aa.argv[1];if(r==null)return{code:1,output:""};try{return{code:0,output:uw(Aa.execPath,[r,...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}}catch(n){let o=kw.safeParse(n);if(!o.success)return{code:1,output:""};let i=`${Ia(o.data.stdout)}${Ia(o.data.stderr)}`;return{code:o.data.status??1,output:i}}}import{z as Na}from"zod";var Pw=Na.looseObject({skill:Na.string()}),Oa=N("PostToolUse",e=>{if(e.tool_name!=="Skill")return;let t=Pw.safeParse(e.tool_input);if(!t.success)return;let r=/^ripplo:(.+)$/.exec(t.data.skill);if(r==null)return;let n=r[1];n!=null&&I(e.cwd)&&ya(e.cwd,e.session_id,n)});Ow();Un(process.cwd());var Da={"coverage-nudge":ia,"exit-plan-gate":aa,"plan-reminder":la,"post-edit-flag-stubs":ua,"post-edit-lint":ma,"pre-bash-hooks-pause-gate":ga,"pre-bash-run-gate":Sa,"pre-edit-ripplo-skill-gate":ka,"pre-edit-scope-gate":xa,"pre-edit-watch-gate":Ea,"scope-reminder":Ta,"session-preamble":$a,"stop-enforce":ja,"track-skill-load":Oa};async function Ew(){await xw(Cw(process.argv)).scriptName("ripplo").version("0.4.11").command("watch","Watch for run requests and execute locally",()=>{},()=>Ks()).command("auth <subcommand>","Manage authentication",Nw).command("projects <subcommand>","Inspect Ripplo projects",jw).command("hooks <subcommand>","Pause or resume Ripplo hooks",Iw).command("init","Scaffold .ripplo/ in this project",e=>e.option("project",{type:"string"}).option("env",{type:"string"}).option("app-url",{type:"string"}).option("engine-url",{type:"string"}),e=>Fs({appUrl:e["app-url"],engineUrl:e["engine-url"],envFile:e.env,projectId:e.project})).command("run [ids..]","Run tests in parallel",e=>{let t=[];return e.positional("ids",{array:!0,default:t,describe:"Test ids to run (all if omitted)",type:"string"})},e=>Ws(e.ids)).command("lint [ids..]","Compile and lint tests (all or specific ids)",e=>{let t=[];return e.positional("ids",{array:!0,default:t,describe:"Test ids to lint (all if omitted)",type:"string"}).option("require-implemented",{array:!0,default:t,describe:"Test ids that must not be .notImplemented() \u2014 fails if any still are",type:"string"})},e=>Hs({ids:e.ids,requireImplemented:e["require-implemented"]})).command("flake-detect <id>","Run N times to detect flakiness",e=>e.positional("id",{demandOption:!0,type:"string"}).option("runs",{default:10,type:"number"}),e=>js({id:e.id,runs:e.runs})).command("sync","Push the compiled .ripplo/ resources to the server (no run)",()=>{},()=>zs()).command("compile","Compile the DSL and write .ripplo/ripplo.lock",e=>e.option("check",{default:!1,describe:"Exit non-zero if the lockfile is missing or stale (does not write)",type:"boolean"}),e=>ds({check:e.check})).command("cover","Audit all coverage statements",()=>{},()=>gs()).command("doctor","Check project health",()=>{},()=>Ts()).command("status","Report unimplemented tests and preconditions",e=>e.option("format",{choices:["json","summary"],default:"json",describe:"Output format"}),e=>ea({format:e.format})).command("scope <subcommand>","Manage testing scope",Aw).command("hook <name>","Internal: run a Claude Code plugin hook",e=>e.positional("name",{choices:Object.keys(Da),demandOption:!0,type:"string"}),e=>Tw(e.name)).strict().help().parse()}async function Tw(e){let t=Da[e];t==null&&(process.stderr.write(`Unknown hook: ${e}
688
+ `),process.exit(1));let r=await $w(),n=r.trim()===""?{}:JSON.parse(r),o=await t.run(n);o!=null&&process.stdout.write(JSON.stringify(o))}function $w(){return new Promise((e,t)=>{if(process.stdin.isTTY){e("");return}let r=[];process.stdin.on("data",n=>r.push(n)),process.stdin.on("end",()=>{e(Buffer.concat(r).toString("utf8"))}),process.stdin.on("error",t)})}Ew().catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
689
+ `),process.exit(1)});function Aw(e){return e.command("status","Print the current scope",t=>t.option("format",{choices:["json","text"],default:"text",describe:"Output format"}),t=>Ys({format:t.format})).command("add <test-ids..>","Bind one or more existing tests (stubs or implemented) to scope as agent intent",t=>{let r=[];return t.positional("test-ids",{array:!0,default:r,demandOption:!0,describe:"Slugs of existing workflows",type:"string"})},t=>Xs({testIds:t["test-ids"]})).command("link <id> <test-id>","Link an existing scope item to a test",t=>t.positional("id",{demandOption:!0,describe:"Scope item id",type:"string"}).positional("test-id",{demandOption:!0,describe:"Slug of the workflow to link",type:"string"}),t=>Qs({id:t.id,testId:t["test-id"]})).command("remove <ids..>","Remove one or more scope items by id",t=>{let r=[];return t.positional("ids",{array:!0,default:r,demandOption:!0,describe:"Scope item ids",type:"string"})},t=>Zs({ids:t.ids})).demandCommand(1)}function Iw(e){return e.command("pause","Disable all Ripplo pre-edit gates and stop enforcement until resumed",()=>{},()=>Ns()).command("resume","Re-enable Ripplo hooks paused via `ripplo hooks pause`",()=>{},()=>Os()).demandCommand(1)}function jw(e){return e.command("list","List projects you have access to (JSON)",()=>{},()=>qs()).demandCommand(1)}function Nw(e){return e.command("login","Authenticate via device flow",()=>{},()=>Li()).command("status","Show authentication status",()=>{},()=>Ui()).command("logout","Remove the saved token",()=>{},()=>{Vi()}).demandCommand(1)}function Ow(){let e=process.cwd(),t=ar(e);t!=null&&t!==e&&(process.chdir(t),process.stderr.write(`ripplo: resolved .ripplo/ at ${t}
690
+ `))}export{Ew as main};
691
691
  /*! Bundled license information:
692
692
 
693
693
  mustache/mustache.mjs: