ripplo 0.4.15 → 0.4.16

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 +150 -146
  2. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- var an=Object.defineProperty;var ps=Object.getOwnPropertyDescriptor;var ms=Object.getOwnPropertyNames;var fs=Object.prototype.hasOwnProperty;var gs=(e,t)=>{for(var r in t)an(e,r,{get:t[r],enumerable:!0})},sn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ms(t))!fs.call(e,o)&&o!==r&&an(e,o,{get:()=>t[o],enumerable:!(n=ps(t,o))||n.enumerable});return e},Xt=(e,t,r)=>(sn(e,t,"default"),r&&sn(r,t,"default"));import{execFileSync as ys}from"child_process";import hs from"fs";import ut from"path";function Qt(e){let t=bs(e);return t??ln(e)}function ln(e){let t=ut.dirname(e);return ws(ut.join(e,".ripplo"))?e:t===e?null:ln(t)}function ws(e){try{return hs.statSync(e).isDirectory()}catch{return!1}}function bs(e){let t=vs(["rev-parse","--show-toplevel"],e);if(t==null)return null;let r=t.trim();return r.length===0?null:ut.isAbsolute(r)?r:ut.resolve(e,r)}function vs(e,t){try{return ys("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return null}}import un from"fs";import ft from"path";import{config as Rs}from"dotenv";import{z as mt}from"zod";import Ge from"fs";import Zt from"path";import{z as pt}from"zod";var cn=Zt.join(".ripplo","project.json"),Yt=[".env",".env.local"],Ss=pt.object({envFiles:pt.array(pt.string().min(1)).optional(),projectId:pt.string().min(1)});function er(e){return Zt.join(e,cn)}function tr(e){let t=er(e);if(!Ge.existsSync(t))throw new Error(`ripplo: missing ${cn}. Run \`ripplo init\` to create it.`);let r=JSON.parse(Ge.readFileSync(t,"utf8")),n=Ss.parse(r);return{envFiles:n.envFiles??Yt,projectId:n.projectId}}function rr(e){let t=er(e);if(Ge.existsSync(t))try{return tr(e)}catch{return}}function dn({cwd:e,envFiles:t,projectId:r}){let n=er(e);Ge.mkdirSync(Zt.dirname(n),{recursive:!0});let o={projectId:r};t!=null&&!ks(t)&&(o.envFiles=[...t]),Ge.writeFileSync(n,JSON.stringify(o,null,2)+`
3
- `)}function ks(e){return e.length!==Yt.length?!1:e.every((t,r)=>t===Yt[r])}function pn(e){let r=rr(e)?.envFiles??[".env",".env.local"],n=ft.join(e,".ripplo");r.forEach(o=>{let i=ft.resolve(n,o);un.existsSync(i)&&Rs({override:!0,path:i,quiet:!0})}),nr=void 0}var Ps=mt.object({RIPPLO_APP_URL:mt.url(),RIPPLO_ENGINE_URL:mt.url(),RIPPLO_WEBHOOK_SECRET:mt.string().min(1)}),nr;function Ae(){return nr??=xs(),nr}function xs(){let e=Ps.safeParse(process.env);if(!e.success){let r=e.error.issues.map(s=>` ${s.path.join(".")}: ${s.message}`).join(`
4
- `),n=or(process.cwd()),o=n.map(s=>` ${s}`).join(`
2
+ var ln=Object.defineProperty;var fs=Object.getOwnPropertyDescriptor;var gs=Object.getOwnPropertyNames;var ys=Object.prototype.hasOwnProperty;var hs=(e,t)=>{for(var r in t)ln(e,r,{get:t[r],enumerable:!0})},an=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of gs(t))!ys.call(e,o)&&o!==r&&ln(e,o,{get:()=>t[o],enumerable:!(n=fs(t,o))||n.enumerable});return e},Qt=(e,t,r)=>(an(e,t,"default"),r&&an(r,t,"default"));import{execFileSync as ws}from"child_process";import bs from"fs";import ut from"path";function Yt(e){let t=ks(e);return t??cn(e)}function cn(e){let t=ut.dirname(e);return vs(ut.join(e,".ripplo"))?e:t===e?null:cn(t)}function vs(e){try{return bs.statSync(e).isDirectory()}catch{return!1}}function ks(e){let t=Ss(["rev-parse","--show-toplevel"],e);if(t==null)return null;let r=t.trim();return r.length===0?null:ut.isAbsolute(r)?r:ut.resolve(e,r)}function Ss(e,t){try{return ws("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return null}}import pn from"fs";import ft from"path";import{config as xs}from"dotenv";import{z as mt}from"zod";import Ke from"fs";import er from"path";import{z as pt}from"zod";var dn=er.join(".ripplo","project.json"),Zt=[".env",".env.local"],Rs=pt.object({envFiles:pt.array(pt.string().min(1)).optional(),projectId:pt.string().min(1)});function tr(e){return er.join(e,dn)}function rr(e){let t=tr(e);if(!Ke.existsSync(t))throw new Error(`ripplo: missing ${dn}. Run \`ripplo init\` to create it.`);let r=JSON.parse(Ke.readFileSync(t,"utf8")),n=Rs.parse(r);return{envFiles:n.envFiles??Zt,projectId:n.projectId}}function nr(e){let t=tr(e);if(Ke.existsSync(t))try{return rr(e)}catch{return}}function un({cwd:e,envFiles:t,projectId:r}){let n=tr(e);Ke.mkdirSync(er.dirname(n),{recursive:!0});let o={projectId:r};t!=null&&!Ps(t)&&(o.envFiles=[...t]),Ke.writeFileSync(n,JSON.stringify(o,null,2)+`
3
+ `)}function Ps(e){return e.length!==Zt.length?!1:e.every((t,r)=>t===Zt[r])}function mn(e){let r=nr(e)?.envFiles??[".env",".env.local"],n=ft.join(e,".ripplo");r.forEach(o=>{let i=ft.resolve(n,o);pn.existsSync(i)&&xs({override:!0,path:i,quiet:!0})}),or=void 0}var Cs=mt.object({RIPPLO_APP_URL:mt.url(),RIPPLO_ENGINE_URL:mt.url(),RIPPLO_WEBHOOK_SECRET:mt.string().min(1)}),or;function $e(){return or??=Es(),or}function Es(){let e=Cs.safeParse(process.env);if(!e.success){let r=e.error.issues.map(s=>` ${s.path.join(".")}: ${s.message}`).join(`
4
+ `),n=ir(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,24 +9,24 @@ ${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 or(e){let r=rr(e)?.envFiles??[],n=ft.join(e,".ripplo");return r.map(o=>ft.resolve(n,o)).filter(o=>!un.existsSync(o))}import sy from"yargs";import{hideBin as ay}from"yargs/helpers";import{graphql as zc}from"gql.tada";async function gt(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 z({awaitPromise:e,expression:t,page:r}){return gt(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 Cs=Object.prototype.toString,Te=Array.isArray||function(t){return Cs.call(t)==="[object Array]"};function sr(e){return typeof e=="function"}function Es(e){return Te(e)?"array":typeof e}function ir(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function mn(e,t){return e!=null&&typeof e=="object"&&t in e}function As(e,t){return e!=null&&typeof e!="object"&&e.hasOwnProperty&&e.hasOwnProperty(t)}var Is=RegExp.prototype.test;function Ts(e,t){return Is.call(e,t)}var $s=/\S/;function js(e){return!Ts($s,e)}var Ns={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function Os(e){return String(e).replace(/[&<>"'`=\/]/g,function(r){return Ns[r]})}var Ds=/\s*/,Ls=/\s+/,fn=/\s*=/,_s=/\s*\}/,Us=/#|\^|\/|>|\{|&|=|!/;function Vs(e,t){if(!e)return[];var r=!1,n=[],o=[],i=[],s=!1,a=!1,l="",c=0;function p(){if(s&&!a)for(;i.length;)delete o[i.pop()];else i=[];s=!1,a=!1}var m,S,j;function N(oe){if(typeof oe=="string"&&(oe=oe.split(Ls,2)),!Te(oe)||oe.length!==2)throw new Error("Invalid tags: "+oe);m=new RegExp(ir(oe[0])+"\\s*"),S=new RegExp("\\s*"+ir(oe[1])),j=new RegExp("\\s*"+ir("}"+oe[1]))}N(t||Z.tags);for(var f=new Je(e),M,$,V,ne,Ee,ie;!f.eos();){if(M=f.pos,V=f.scanUntil(m),V)for(var ze=0,W=V.length;ze<W;++ze)ne=V.charAt(ze),js(ne)?(i.push(o.length),l+=ne):(a=!0,r=!0,l+=" "),o.push(["text",ne,M,M+1]),M+=1,ne===`
13
- `&&(p(),l="",c=0,r=!1);if(!f.scan(m))break;if(s=!0,$=f.scan(Us)||"name",f.scan(Ds),$==="="?(V=f.scanUntil(fn),f.scan(fn),f.scanUntil(S)):$==="{"?(V=f.scanUntil(j),f.scan(_s),f.scanUntil(S),$="&"):V=f.scanUntil(S),!f.scan(S))throw new Error("Unclosed tag at "+f.pos);if($==">"?Ee=[$,V,M,f.pos,l,c,r]:Ee=[$,V,M,f.pos],c++,o.push(Ee),$==="#"||$==="^")n.push(Ee);else if($==="/"){if(ie=n.pop(),!ie)throw new Error('Unopened section "'+V+'" at '+M);if(ie[1]!==V)throw new Error('Unclosed section "'+ie[1]+'" at '+M)}else $==="name"||$==="{"||$==="&"?a=!0:$==="="&&N(V)}if(p(),ie=n.pop(),ie)throw new Error('Unclosed section "'+ie[1]+'" at '+f.pos);return Hs(Fs(o))}function Fs(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 Hs(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 Je(e){this.string=e,this.tail=e,this.pos=0}Je.prototype.eos=function(){return this.tail===""};Je.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};Je.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 Ie(e,t){this.view=e,this.cache={".":this.view},this.parent=t}Ie.prototype.push=function(t){return new Ie(t,this)};Ie.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=mn(i,s[a])||As(i,s[a])),i=i[s[a++]];else i=o.view[t],l=mn(o.view,t);if(l){n=i;break}o=o.parent}r[t]=n}return sr(n)&&(n=n.call(this.view)),n};function H(){this.templateCache={_cache:{},set:function(t,r){this._cache[t]=r},get:function(t){return this._cache[t]},clear:function(){this._cache={}}}}H.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};H.prototype.parse=function(t,r){var n=this.templateCache,o=t+":"+(r||Z.tags).join(":"),i=typeof n<"u",s=i?n.get(o):void 0;return s==null&&(s=Vs(t,r),i&&n.set(o,s)),s};H.prototype.render=function(t,r,n,o){var i=this.getConfigTags(o),s=this.parse(t,i),a=r instanceof Ie?r:new Ie(r,void 0);return this.renderTokens(s,a,n,t,o)};H.prototype.renderTokens=function(t,r,n,o,i){for(var s="",a,l,c,p=0,m=t.length;p<m;++p)c=void 0,a=t[p],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};H.prototype.renderSection=function(t,r,n,o,i){var s=this,a="",l=r.lookup(t[1]);function c(S){return s.render(S,r,n,i)}if(l){if(Te(l))for(var p=0,m=l.length;p<m;++p)a+=this.renderTokens(t[4],r.push(l[p]),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(sr(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}};H.prototype.renderInverted=function(t,r,n,o,i){var s=r.lookup(t[1]);if(!s||Te(s)&&s.length===0)return this.renderTokens(t[4],r,n,o,i)};H.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 ir(e){let r=nr(e)?.envFiles??[],n=ft.join(e,".ripplo");return r.map(o=>ft.resolve(n,o)).filter(o=>!pn.existsSync(o))}import cy from"yargs";import{hideBin as dy}from"yargs/helpers";import{graphql as Kc}from"gql.tada";async function gt(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 G({awaitPromise:e,expression:t,page:r}){return gt(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 As=Object.prototype.toString,je=Array.isArray||function(t){return As.call(t)==="[object Array]"};function ar(e){return typeof e=="function"}function Is(e){return je(e)?"array":typeof e}function sr(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function fn(e,t){return e!=null&&typeof e=="object"&&t in e}function $s(e,t){return e!=null&&typeof e!="object"&&e.hasOwnProperty&&e.hasOwnProperty(t)}var Ts=RegExp.prototype.test;function js(e,t){return Ts.call(e,t)}var Ns=/\S/;function Os(e){return!js(Ns,e)}var Ds={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function Ls(e){return String(e).replace(/[&<>"'`=\/]/g,function(r){return Ds[r]})}var _s=/\s*/,Us=/\s+/,gn=/\s*=/,Vs=/\s*\}/,Fs=/#|\^|\/|>|\{|&|=|!/;function Hs(e,t){if(!e)return[];var r=!1,n=[],o=[],i=[],s=!1,a=!1,l="",c=0;function p(){if(s&&!a)for(;i.length;)delete o[i.pop()];else i=[];s=!1,a=!1}var m,S,j;function N(oe){if(typeof oe=="string"&&(oe=oe.split(Us,2)),!je(oe)||oe.length!==2)throw new Error("Invalid tags: "+oe);m=new RegExp(sr(oe[0])+"\\s*"),S=new RegExp("\\s*"+sr(oe[1])),j=new RegExp("\\s*"+sr("}"+oe[1]))}N(t||Z.tags);for(var f=new Xe(e),W,T,V,ne,Ie,ie;!f.eos();){if(W=f.pos,V=f.scanUntil(m),V)for(var Ge=0,B=V.length;Ge<B;++Ge)ne=V.charAt(Ge),Os(ne)?(i.push(o.length),l+=ne):(a=!0,r=!0,l+=" "),o.push(["text",ne,W,W+1]),W+=1,ne===`
13
+ `&&(p(),l="",c=0,r=!1);if(!f.scan(m))break;if(s=!0,T=f.scan(Fs)||"name",f.scan(_s),T==="="?(V=f.scanUntil(gn),f.scan(gn),f.scanUntil(S)):T==="{"?(V=f.scanUntil(j),f.scan(Vs),f.scanUntil(S),T="&"):V=f.scanUntil(S),!f.scan(S))throw new Error("Unclosed tag at "+f.pos);if(T==">"?Ie=[T,V,W,f.pos,l,c,r]:Ie=[T,V,W,f.pos],c++,o.push(Ie),T==="#"||T==="^")n.push(Ie);else if(T==="/"){if(ie=n.pop(),!ie)throw new Error('Unopened section "'+V+'" at '+W);if(ie[1]!==V)throw new Error('Unclosed section "'+ie[1]+'" at '+W)}else T==="name"||T==="{"||T==="&"?a=!0:T==="="&&N(V)}if(p(),ie=n.pop(),ie)throw new Error('Unclosed section "'+ie[1]+'" at '+f.pos);return Ws(Ms(o))}function Ms(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 Ws(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 Te(e,t){this.view=e,this.cache={".":this.view},this.parent=t}Te.prototype.push=function(t){return new Te(t,this)};Te.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=fn(i,s[a])||$s(i,s[a])),i=i[s[a++]];else i=o.view[t],l=fn(o.view,t);if(l){n=i;break}o=o.parent}r[t]=n}return ar(n)&&(n=n.call(this.view)),n};function M(){this.templateCache={_cache:{},set:function(t,r){this._cache[t]=r},get:function(t){return this._cache[t]},clear:function(){this._cache={}}}}M.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};M.prototype.parse=function(t,r){var n=this.templateCache,o=t+":"+(r||Z.tags).join(":"),i=typeof n<"u",s=i?n.get(o):void 0;return s==null&&(s=Hs(t,r),i&&n.set(o,s)),s};M.prototype.render=function(t,r,n,o){var i=this.getConfigTags(o),s=this.parse(t,i),a=r instanceof Te?r:new Te(r,void 0);return this.renderTokens(s,a,n,t,o)};M.prototype.renderTokens=function(t,r,n,o,i){for(var s="",a,l,c,p=0,m=t.length;p<m;++p)c=void 0,a=t[p],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};M.prototype.renderSection=function(t,r,n,o,i){var s=this,a="",l=r.lookup(t[1]);function c(S){return s.render(S,r,n,i)}if(l){if(je(l))for(var p=0,m=l.length;p<m;++p)a+=this.renderTokens(t[4],r.push(l[p]),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(ar(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}};M.prototype.renderInverted=function(t,r,n,o,i){var s=r.lookup(t[1]);if(!s||je(s)&&s.length===0)return this.renderTokens(t[4],r,n,o,i)};M.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
- `)};H.prototype.renderPartial=function(t,r,n,o){if(n){var i=this.getConfigTags(o),s=sr(n)?n(t[1]):n[t[1]];if(s!=null){var a=t[6],l=t[5],c=t[4],p=s;l==0&&c&&(p=this.indentPartial(s,c,a));var m=this.parse(p,i);return this.renderTokens(m,r,n,p,o)}}};H.prototype.unescapedValue=function(t,r){var n=r.lookup(t[1]);if(n!=null)return n};H.prototype.escapedValue=function(t,r,n){var o=this.getConfigEscape(n)||Z.escape,i=r.lookup(t[1]);if(i!=null)return typeof i=="number"&&o===Z.escape?String(i):o(i)};H.prototype.rawValue=function(t){return t[1]};H.prototype.getConfigTags=function(t){return Te(t)?t:t&&typeof t=="object"?t.tags:void 0};H.prototype.getConfigEscape=function(t){if(t&&typeof t=="object"&&!Te(t))return t.escape};var Z={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){Ke.templateCache=e},get templateCache(){return Ke.templateCache}},Ke=new H;Z.clearCache=function(){return Ke.clearCache()};Z.parse=function(t,r){return Ke.parse(t,r)};Z.render=function(t,r,n,o){if(typeof t!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+Es(t)+'" was given as the first argument for mustache#render(template, view, partials)');return Ke.render(t,r,n,o)};Z.escape=Os;Z.Scanner=Je;Z.Context=Ie;Z.Writer=H;var gn=Z;function ar({defs:e}){return e==null?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Ws({def:r,name:t})]))}var Ms={boolean:!1,number:0,string:""};function Ws({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??Ms[e.type]??""}function yt({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 B({ref:e,variables:t}){let r=String(yt({ref:e,variables:t}));return wt({raw:r,variables:t})}function ht({ref:e,variables:t}){let r=yt({ref:e,variables:t});return typeof r=="string"?wt({raw:r,variables:t}):r}function wt({raw:e,variables:t}){return gn.render(e,t,{},{escape:r=>r})}function lr({ref:e,variables:t}){let r=yt({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 $e({name:e,store:t,value:r}){return{...t,[e]:r}}function O({locator:e,page:t,variables:r}){switch(e.by){case"testId":return t.getByTestId(yn(e.value,r));case"role":return t.getByRole(e.role,{exact:!0,name:e.name==null?void 0:yn(e.name,r)})}}function yn(e,t){return t==null?e:wt({raw:e,variables:t})}async function hn({node:e,page:t,timeout:r}){await O({locator:e.source,page:t,variables:void 0}).dragTo(O({locator:e.target,page:t,variables:void 0}),{timeout:r})}async function wn({node:e,page:t,timeout:r}){await O({locator:e.locator,page:t,variables:void 0}).click({button:"right",timeout:r})}function bn({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 vn({node:e,page:t,variables:r}){if(e.action==="write"){if(e.value==null)throw new Error("clipboard write requires a value");let o=B({ref:e.value,variables:r}),i=JSON.stringify(o);return await z({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 z({awaitPromise:!0,expression:"navigator.clipboard.readText()",page:t})??"";return{variables:$e({name:e.variable,store:r,value:n})}}async function Sn({node:e,page:t}){let r=t.context();e.state==="granted"?await r.grantPermissions([e.permission]):await r.clearPermissions()}async function cr({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 qs({node:e,page:t,timeout:r,variables:n});case"rightClick":return await wn({node:e,page:t,timeout:r}),{variables:n};case"goto":{let o=B({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 z({awaitPromise:!0,expression:"new Promise((resolve) => { requestAnimationFrame(() => requestAnimationFrame(() => resolve(undefined))); })",page:t}),{variables:n}}case"fill":return Gs({node:e,page:t,timeout:r,variables:n});case"select":return Ks({node:e,page:t,timeout:r,variables:n});case"type":return Js({node:e,page:t,timeout:r,variables:n});case"press":return await zs({node:e,page:t,timeout:r}),{variables:n};case"drag":return await hn({node:e,page:t,timeout:r}),{variables:n};case"upload":return Xs({node:e,page:t,timeout:r,variables:n});case"extractText":return Qs({node:e,page:t,timeout:r,variables:n});case"setVariable":{let o=ht({ref:e.value,variables:n});return{variables:$e({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 bn({node:e,page:t,variables:n});case"clipboard":return vn({node:e,page:t,variables:n});case"setPermission":return await Sn({node:e,page:t}),{variables:n}}}var Bs={check:"check",clear:"clear",click:"click",dblclick:"dblclick",focus:"focus",hover:"hover",scrollIntoView:"scrollIntoViewIfNeeded",uncheck:"uncheck"};async function qs({node:e,page:t,timeout:r,variables:n}){return await O({locator:e.locator,page:t,variables:n})[Bs[e.type]]({timeout:r}),{variables:n}}async function zs({node:e,page:t,timeout:r}){e.locator==null?await t.keyboard.press(e.key):await O({locator:e.locator,page:t,variables:void 0}).press(e.key,{timeout:r})}async function Gs({node:e,page:t,timeout:r,variables:n}){let o=B({ref:e.value,variables:n});return await O({locator:e.locator,page:t,variables:n}).fill(o,{timeout:r}),{variables:n}}async function Ks({node:e,page:t,timeout:r,variables:n}){let o=B({ref:e.value,variables:n});return await O({locator:e.locator,page:t,variables:n}).selectOption(o,{timeout:r}),{variables:n}}async function Js({node:e,page:t,timeout:r,variables:n}){let o=B({ref:e.value,variables:n});return await O({locator:e.locator,page:t,variables:n}).pressSequentially(o,{timeout:r}),{variables:n}}async function Xs({node:e,page:t,timeout:r,variables:n}){return await O({locator:e.locator,page:t,variables:n}).setInputFiles(e.files,{timeout:r}),{variables:n}}async function Qs({node:e,page:t,timeout:r,variables:n}){let o=await O({locator:e.locator,page:t,variables:n}).textContent({timeout:r});if(o==null)throw new Error("extractText: element had no text content");return{variables:$e({name:e.variable,store:n,value:o})}}var F={};gs(F,{default:()=>Ys});Xt(F,zy);import*as zy from"playwright/test";import{default as Ys}from"playwright/test";async function dr({expected:e,locator:t,operator:r,timeout:n}){await Xe({expected:e,operator:r,timeout:n,read:async()=>await t.textContent()??""});let o=await Qe(async()=>await t.textContent()??"");return je({actual:o,expected:e,label:"Text",operator:r})}async function ur({expected:e,operator:t,page:r,timeout:n}){return await Xe({expected:e,operator:t,timeout:n,read:()=>Promise.resolve(r.url())}),je({actual:r.url(),expected:e,label:"URL",operator:t})}async function kn({expected:e,operator:t,page:r,timeout:n}){await Xe({expected:e,operator:t,timeout:n,read:()=>r.title()});let o=await Qe(()=>r.title());return je({actual:o,expected:e,label:"Title",operator:t})}async function pr({expected:e,locator:t,operator:r,timeout:n}){await F.expect.poll(async()=>jn({actual:await t.count(),expected:e,operator:r}),{timeout:n}).toBe(!0).catch(()=>{});let o=await t.count();return $n({actual:o,expected:e,label:"Count",operator:r})}async function mr({expected:e,locator:t,operator:r,timeout:n}){await Xe({expected:e,operator:r,timeout:n,read:()=>t.inputValue()});let o=await Qe(()=>t.inputValue());return je({actual:o,expected:e,label:"Value",operator:r})}async function fr({locator:e,timeout:t}){return ge({description:"Element is visible",failureDetail:"Element not visible",run:()=>(0,F.expect)(e).toBeVisible({timeout:t})})}async function gr({locator:e,timeout:t}){return ge({description:"Element is not visible",failureDetail:"Element still visible",run:()=>(0,F.expect)(e).toBeHidden({timeout:t})})}async function Rn({attribute:e,expected:t,locator:r,operator:n,timeout:o}){await Xe({expected:t,operator:n,timeout:o,read:async()=>await r.getAttribute(e)??""});let i=await Qe(async()=>await r.getAttribute(e)??"");return je({actual:i,expected:t,label:`Attribute "${e}"`,operator:n})}async function Pn({locator:e,timeout:t}){return ge({description:"Element is enabled",failureDetail:"Element is disabled or not found",run:()=>(0,F.expect)(e).toBeEnabled({timeout:t})})}async function xn({locator:e,timeout:t}){return ge({description:"Element is disabled",failureDetail:"Element is enabled or not found",run:()=>(0,F.expect)(e).toBeDisabled({timeout:t})})}async function Cn({locator:e,timeout:t}){return ge({description:"Element is checked",failureDetail:"Element is not checked",run:()=>(0,F.expect)(e).toBeChecked({timeout:t})})}async function En({locator:e,timeout:t}){return ge({description:"Element is not checked",failureDetail:"Element is checked",run:()=>(0,F.expect)(e).not.toBeChecked({timeout:t})})}async function An({locator:e,timeout:t}){return ge({description:"Element is focused",failureDetail:"Element is not focused",run:()=>(0,F.expect)(e).toBeFocused({timeout:t})})}async function In({locator:e,timeout:t}){return ge({description:"Element is not focused",failureDetail:"Element is focused",run:()=>(0,F.expect)(e).not.toBeFocused({timeout:t})})}async function ge({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 Xe({expected:e,operator:t,read:r,timeout:n}){await F.expect.poll(async()=>{let o=await Qe(r);return Tn({actual:o,expected:e,operator:t})},{timeout:n}).toBe(!0).catch(()=>{})}async function Qe(e){return e().catch(()=>"")}function je(e){let t=`${e.label} ${e.operator} "${e.expected}"`,r=Tn(e),n=r?void 0:`Got: "${e.actual}"`;return{description:t,detail:n,status:r?"passed":"failed"}}function Tn({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 $n(e){let t=`${e.label} ${e.operator} ${String(e.expected)}`,r=jn(e),n=r?void 0:`Got: ${String(e.actual)}`;return{description:t,detail:n,status:r?"passed":"failed"}}function jn({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{execFile as ea}from"child_process";import{createRequire as ta}from"module";import Nn from"fs";import On from"path";import{chromium as Dn}from"playwright";import Qy from"fs";import Zy from"path";import Zs from"pino";var y=Zs({transport:{options:{ignore:"pid,hostname"},target:"pino-pretty"}});async function Ye({headed:e}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";try{return await Dn.launch({headless:!e})}catch(t){throw ra(t)?new Error(`Playwright browsers are not installed. Run:
15
+ `)};M.prototype.renderPartial=function(t,r,n,o){if(n){var i=this.getConfigTags(o),s=ar(n)?n(t[1]):n[t[1]];if(s!=null){var a=t[6],l=t[5],c=t[4],p=s;l==0&&c&&(p=this.indentPartial(s,c,a));var m=this.parse(p,i);return this.renderTokens(m,r,n,p,o)}}};M.prototype.unescapedValue=function(t,r){var n=r.lookup(t[1]);if(n!=null)return n};M.prototype.escapedValue=function(t,r,n){var o=this.getConfigEscape(n)||Z.escape,i=r.lookup(t[1]);if(i!=null)return typeof i=="number"&&o===Z.escape?String(i):o(i)};M.prototype.rawValue=function(t){return t[1]};M.prototype.getConfigTags=function(t){return je(t)?t:t&&typeof t=="object"?t.tags:void 0};M.prototype.getConfigEscape=function(t){if(t&&typeof t=="object"&&!je(t))return t.escape};var Z={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){Je.templateCache=e},get templateCache(){return Je.templateCache}},Je=new M;Z.clearCache=function(){return Je.clearCache()};Z.parse=function(t,r){return Je.parse(t,r)};Z.render=function(t,r,n,o){if(typeof t!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+Is(t)+'" was given as the first argument for mustache#render(template, view, partials)');return Je.render(t,r,n,o)};Z.escape=Ls;Z.Scanner=Xe;Z.Context=Te;Z.Writer=M;var yn=Z;function lr({defs:e}){return e==null?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,qs({def:r,name:t})]))}var Bs={boolean:!1,number:0,string:""};function qs({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??Bs[e.type]??""}function yt({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 q({ref:e,variables:t}){let r=String(yt({ref:e,variables:t}));return wt({raw:r,variables:t})}function ht({ref:e,variables:t}){let r=yt({ref:e,variables:t});return typeof r=="string"?wt({raw:r,variables:t}):r}function wt({raw:e,variables:t}){return yn.render(e,t,{},{escape:r=>r})}function cr({ref:e,variables:t}){let r=yt({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 Ne({name:e,store:t,value:r}){return{...t,[e]:r}}function O({locator:e,page:t,variables:r}){switch(e.by){case"testId":return t.getByTestId(hn(e.value,r));case"role":return t.getByRole(e.role,{exact:!0,name:e.name==null?void 0:hn(e.name,r)})}}function hn(e,t){return t==null?e:wt({raw:e,variables:t})}async function wn({node:e,page:t,timeout:r}){await O({locator:e.source,page:t,variables:void 0}).dragTo(O({locator:e.target,page:t,variables:void 0}),{timeout:r})}async function bn({node:e,page:t,timeout:r}){await O({locator:e.locator,page:t,variables:void 0}).click({button:"right",timeout:r})}function vn({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 kn({node:e,page:t,variables:r}){if(e.action==="write"){if(e.value==null)throw new Error("clipboard write requires a value");let o=q({ref:e.value,variables:r}),i=JSON.stringify(o);return await G({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 G({awaitPromise:!0,expression:"navigator.clipboard.readText()",page:t})??"";return{variables:Ne({name:e.variable,store:r,value:n})}}async function Sn({node:e,page:t}){let r=t.context();e.state==="granted"?await r.grantPermissions([e.permission]):await r.clearPermissions()}async function dr({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 Gs({node:e,page:t,timeout:r,variables:n});case"rightClick":return await bn({node:e,page:t,timeout:r}),{variables:n};case"goto":{let o=q({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 G({awaitPromise:!0,expression:"new Promise((resolve) => { requestAnimationFrame(() => requestAnimationFrame(() => resolve(undefined))); })",page:t}),{variables:n}}case"fill":return Js({node:e,page:t,timeout:r,variables:n});case"select":return Xs({node:e,page:t,timeout:r,variables:n});case"type":return Qs({node:e,page:t,timeout:r,variables:n});case"press":return await Ks({node:e,page:t,timeout:r}),{variables:n};case"drag":return await wn({node:e,page:t,timeout:r}),{variables:n};case"upload":return Ys({node:e,page:t,timeout:r,variables:n});case"extractText":return Zs({node:e,page:t,timeout:r,variables:n});case"setVariable":{let o=ht({ref:e.value,variables:n});return{variables:Ne({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 vn({node:e,page:t,variables:n});case"clipboard":return kn({node:e,page:t,variables:n});case"setPermission":return await Sn({node:e,page:t}),{variables:n}}}var zs={check:"check",clear:"clear",click:"click",dblclick:"dblclick",focus:"focus",hover:"hover",scrollIntoView:"scrollIntoViewIfNeeded",uncheck:"uncheck"};async function Gs({node:e,page:t,timeout:r,variables:n}){return await O({locator:e.locator,page:t,variables:n})[zs[e.type]]({timeout:r}),{variables:n}}async function Ks({node:e,page:t,timeout:r}){e.locator==null?await t.keyboard.press(e.key):await O({locator:e.locator,page:t,variables:void 0}).press(e.key,{timeout:r})}async function Js({node:e,page:t,timeout:r,variables:n}){let o=q({ref:e.value,variables:n});return await O({locator:e.locator,page:t,variables:n}).fill(o,{timeout:r}),{variables:n}}async function Xs({node:e,page:t,timeout:r,variables:n}){let o=q({ref:e.value,variables:n});return await O({locator:e.locator,page:t,variables:n}).selectOption(o,{timeout:r}),{variables:n}}async function Qs({node:e,page:t,timeout:r,variables:n}){let o=q({ref:e.value,variables:n});return await O({locator:e.locator,page:t,variables:n}).pressSequentially(o,{timeout:r}),{variables:n}}async function Ys({node:e,page:t,timeout:r,variables:n}){return await O({locator:e.locator,page:t,variables:n}).setInputFiles(e.files,{timeout:r}),{variables:n}}async function Zs({node:e,page:t,timeout:r,variables:n}){let o=await O({locator:e.locator,page:t,variables:n}).textContent({timeout:r});if(o==null)throw new Error("extractText: element had no text content");return{variables:Ne({name:e.variable,store:n,value:o})}}var F={};hs(F,{default:()=>ea});Qt(F,Jy);import*as Jy from"playwright/test";import{default as ea}from"playwright/test";async function ur({expected:e,locator:t,operator:r,timeout:n}){await Qe({expected:e,operator:r,timeout:n,read:async()=>await t.textContent()??""});let o=await Ye(async()=>await t.textContent()??"");return Oe({actual:o,expected:e,label:"Text",operator:r})}async function pr({expected:e,operator:t,page:r,timeout:n}){return await Qe({expected:e,operator:t,timeout:n,read:()=>Promise.resolve(r.url())}),Oe({actual:r.url(),expected:e,label:"URL",operator:t})}async function Rn({expected:e,operator:t,page:r,timeout:n}){await Qe({expected:e,operator:t,timeout:n,read:()=>r.title()});let o=await Ye(()=>r.title());return Oe({actual:o,expected:e,label:"Title",operator:t})}async function mr({expected:e,locator:t,operator:r,timeout:n}){await F.expect.poll(async()=>Nn({actual:await t.count(),expected:e,operator:r}),{timeout:n}).toBe(!0).catch(()=>{});let o=await t.count();return jn({actual:o,expected:e,label:"Count",operator:r})}async function fr({expected:e,locator:t,operator:r,timeout:n}){await Qe({expected:e,operator:r,timeout:n,read:()=>t.inputValue()});let o=await Ye(()=>t.inputValue());return Oe({actual:o,expected:e,label:"Value",operator:r})}async function gr({locator:e,timeout:t}){return ge({description:"Element is visible",failureDetail:"Element not visible",run:()=>(0,F.expect)(e).toBeVisible({timeout:t})})}async function yr({locator:e,timeout:t}){return ge({description:"Element is not visible",failureDetail:"Element still visible",run:()=>(0,F.expect)(e).toBeHidden({timeout:t})})}async function Pn({attribute:e,expected:t,locator:r,operator:n,timeout:o}){await Qe({expected:t,operator:n,timeout:o,read:async()=>await r.getAttribute(e)??""});let i=await Ye(async()=>await r.getAttribute(e)??"");return Oe({actual:i,expected:t,label:`Attribute "${e}"`,operator:n})}async function xn({locator:e,timeout:t}){return ge({description:"Element is enabled",failureDetail:"Element is disabled or not found",run:()=>(0,F.expect)(e).toBeEnabled({timeout:t})})}async function Cn({locator:e,timeout:t}){return ge({description:"Element is disabled",failureDetail:"Element is enabled or not found",run:()=>(0,F.expect)(e).toBeDisabled({timeout:t})})}async function En({locator:e,timeout:t}){return ge({description:"Element is checked",failureDetail:"Element is not checked",run:()=>(0,F.expect)(e).toBeChecked({timeout:t})})}async function An({locator:e,timeout:t}){return ge({description:"Element is not checked",failureDetail:"Element is checked",run:()=>(0,F.expect)(e).not.toBeChecked({timeout:t})})}async function In({locator:e,timeout:t}){return ge({description:"Element is focused",failureDetail:"Element is not focused",run:()=>(0,F.expect)(e).toBeFocused({timeout:t})})}async function $n({locator:e,timeout:t}){return ge({description:"Element is not focused",failureDetail:"Element is focused",run:()=>(0,F.expect)(e).not.toBeFocused({timeout:t})})}async function ge({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 Qe({expected:e,operator:t,read:r,timeout:n}){await F.expect.poll(async()=>{let o=await Ye(r);return Tn({actual:o,expected:e,operator:t})},{timeout:n}).toBe(!0).catch(()=>{})}async function Ye(e){return e().catch(()=>"")}function Oe(e){let t=`${e.label} ${e.operator} "${e.expected}"`,r=Tn(e),n=r?void 0:`Got: "${e.actual}"`;return{description:t,detail:n,status:r?"passed":"failed"}}function Tn({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 jn(e){let t=`${e.label} ${e.operator} ${String(e.expected)}`,r=Nn(e),n=r?void 0:`Got: ${String(e.actual)}`;return{description:t,detail:n,status:r?"passed":"failed"}}function Nn({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{execFile as ra}from"child_process";import{createRequire as na}from"module";import On from"fs";import Dn from"path";import{chromium as Ln}from"playwright";import eh from"fs";import rh from"path";import ta from"pino";var y=ta({transport:{options:{ignore:"pid,hostname"},target:"pino-pretty"}});async function Ze({headed:e}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";try{return await Ln.launch({headless:!e})}catch(t){throw oa(t)?new Error(`Playwright browsers are not installed. Run:
16
16
 
17
17
  npx playwright install chromium
18
- `):t}}async function yr(){let e=Dn.executablePath();if(Nn.existsSync(e))return;y.info("Chromium not found. Installing via Playwright...");let t=ta(import.meta.url),r=On.dirname(t.resolve("playwright/package.json")),n=On.join(r,"cli.js");if(await new Promise((o,i)=>{ea(process.execPath,[n,"install","chromium"],s=>{if(s!=null){i(new Error(`Playwright install failed: ${s.message}`));return}o()})}),!Nn.existsSync(e))throw new Error(`Playwright browser installation failed. Try running manually:
18
+ `):t}}async function hr(){let e=Ln.executablePath();if(On.existsSync(e))return;y.info("Chromium not found. Installing via Playwright...");let t=na(import.meta.url),r=Dn.dirname(t.resolve("playwright/package.json")),n=Dn.join(r,"cli.js");if(await new Promise((o,i)=>{ra(process.execPath,[n,"install","chromium"],s=>{if(s!=null){i(new Error(`Playwright install failed: ${s.message}`));return}o()})}),!On.existsSync(e))throw new Error(`Playwright browser installation failed. Try running manually:
19
19
 
20
20
  npx playwright install chromium
21
- `);y.info("\u2713 Chromium installed")}function ra(e){return e instanceof Error?e.message.includes("Executable doesn't exist"):!1}import{readdir as la,rm as ca,stat as da}from"fs/promises";import mh from"os";import Un from"path";import{graphql as ua}from"gql.tada";import{print as na}from"graphql";var oa=15e3;async function g(e){let t=na(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(oa)})}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 ia({res:o,url:n});if(!sa(i))throw new Error("Invalid GraphQL response");if(aa(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 ia({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 sa(e){return typeof e=="object"&&e!=null&&("data"in e||"errors"in e)}function aa(e){return Array.isArray(e.errors)&&e.errors.length>0}var Ln=Un.join(process.cwd(),".ripplo","debug"),_n=360*60*1e3,wh=ua(`
21
+ `);y.info("\u2713 Chromium installed")}function oa(e){return e instanceof Error?e.message.includes("Executable doesn't exist"):!1}import{readdir as da,rm as ua,stat as pa}from"fs/promises";import yh from"os";import Vn from"path";import{graphql as ma}from"gql.tada";import{print as ia}from"graphql";var sa=15e3;async function g(e){let t=ia(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(sa)})}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 aa({res:o,url:n});if(!la(i))throw new Error("Invalid GraphQL response");if(ca(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 aa({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 la(e){return typeof e=="object"&&e!=null&&("data"in e||"errors"in e)}function ca(e){return Array.isArray(e.errors)&&e.errors.length>0}var _n=Vn.join(process.cwd(),".ripplo","debug"),Un=360*60*1e3,kh=ma(`
22
22
  mutation RevokeCurrentCliToken {
23
23
  revokeCurrentCliToken
24
24
  }
25
- `);async function hr({maxRuns:e}){try{let r=(await la(Ln,{withFileTypes:!0})).filter(c=>c.isDirectory()),n=Date.now(),o=await Promise.all(r.map(async c=>{let p=Un.join(Ln,c.name),m=await da(p);return{dirPath:p,mtime:m.mtimeMs}})),i=o.filter(c=>n-c.mtime>_n),a=o.filter(c=>n-c.mtime<=_n).toSorted((c,p)=>p.mtime-c.mtime).slice(e),l=[...i,...a];if(l.length===0)return;await Promise.allSettled(l.map(c=>ca(c.dirPath,{force:!0,recursive:!0}))),y.info("Pruned %d old debug run(s)",l.length)}catch{y.warn("Debug run pruning failed, ignoring")}}var pa=5e3;async function wr({appUrl:e}){try{await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(pa)})}catch(t){let r=t instanceof Error?t.message:String(t);throw y.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(`
26
- `))}}import rt from"fs";import xe from"fs";import ma from"os";import Ze from"path";var fa=".local",ga=".ripplo";function br(e){return Ze.join(e,".ripplo",fa)}function et(e){let t=br(e);xe.existsSync(t)||xe.mkdirSync(t,{recursive:!0});let r=Ze.join(t,".gitignore");return xe.existsSync(r)||xe.writeFileSync(r,`*
27
- `),t}function tt(e,t){return Ze.join(br(e),t)}function vr(){return Ze.join(ma.homedir(),ga)}function Sr(){let e=vr();return xe.existsSync(e)?xe.chmodSync(e,448):xe.mkdirSync(e,{mode:448,recursive:!0}),e}function ye(e){return Ze.join(vr(),e)}function ee(){let e=process.env.RIPPLO_TOKEN;if(e!=null&&e.trim().length>0)return e.trim();let t=ye("token");if(!rt.existsSync(t))return null;let r=rt.readFileSync(t,"utf8").trim();return r.length===0?null:r}function kr(e){Sr(),rt.writeFileSync(ye("token"),e+`
28
- `,{mode:384})}function Rr(){let e=ye("token");return rt.existsSync(e)?(rt.unlinkSync(e),!0):!1}import{z as wc}from"zod";import{z as bt}from"zod";var ya=bt.object({__codec:bt.string().min(1),data:bt.unknown(),version:bt.number().int().positive()}),vt=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}},St=class extends Error{constructor(t){super(`Codec mismatch: expected "${t.expected}", got "${t.got}"`),this.name="CodecMismatchError"}};function kt(e){return Vn({legacy:void 0,migrators:[],name:e,schemas:[]})}function Vn(e){return{initial:t=>Pr(t,{...e,schemas:[t]}),legacy:t=>Vn({...e,legacy:t})}}function Pr(e,t){return{build:()=>ha(e,t),legacy:r=>Pr(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return Pr(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function ha(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>wa(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function wa(e,t,r){let{data:n,version:o}=ba(t,r),i=Fn(t,n,o);return e.parse(i)}function ba(e,t){let r=ya.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new St({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 Fn(e,t,r){let n=e.schemas.length;if(r>n)throw new vt({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 Fn(e,s(i),r+1)}import{z as Bn}from"zod";import{z as Ne}from"zod";var xr=Ne.object({depends:Ne.array(Ne.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:Ne.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:Ne.array(Ne.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 d}from"zod";import{z as he}from"zod";var va=he.object({by:he.literal("testId"),value:he.string().min(1)}),Sa=he.object({by:he.literal("role"),name:he.string().optional(),role:he.string().min(1)}),k=he.discriminatedUnion("by",[va,Sa]);import{z as Hn}from"zod";var we=Hn.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),Rt=Hn.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]);import{z as A}from"zod";var ka=A.object({type:A.literal("static"),value:A.union([A.string(),A.number(),A.boolean()])}),Pt=A.object({name:A.string().min(1),type:A.literal("variable")}),xt=A.discriminatedUnion("type",[ka,Pt]),G=A.discriminatedUnion("type",[A.object({type:A.literal("static"),value:A.string()}),Pt]),Ct=A.discriminatedUnion("type",[A.object({type:A.literal("static"),value:A.number().int().nonnegative()}),Pt]),Cr=A.discriminatedUnion("type",[A.object({type:A.literal("static"),value:A.union([A.string(),A.number(),A.boolean()])}),Pt]);import{z as K}from"zod";var Et=K.discriminatedUnion("type",[K.object({default:K.string().optional(),type:K.literal("string")}),K.object({default:K.number().optional(),type:K.literal("number")}),K.object({default:K.boolean().optional(),type:K.literal("boolean")}),K.object({key:K.string().min(1),type:K.literal("env")})]);var b={id:d.string().min(1).max(200),label:d.string().max(500).optional(),next:d.string().max(200).optional(),uiOnly:d.boolean().optional()},Mn=500,Ra=d.object({...b,type:d.literal("goto"),url:G}),Pa=d.object({...b,locator:k,type:d.literal("click")}),xa=d.object({...b,locator:k,type:d.literal("fill"),value:G}),Ca=d.object({...b,locator:k,type:d.literal("select"),value:G}),Ea=d.object({...b,locator:k,type:d.literal("hover")}),Aa=d.object({...b,key:d.string().min(1),locator:k.optional(),type:d.literal("press")}),Ia=d.object({...b,locator:k,type:d.literal("check")}),Ta=d.object({...b,locator:k,type:d.literal("uncheck")}),$a=d.object({...b,height:d.number().int().positive(),type:d.literal("setViewport"),width:d.number().int().positive()}),ja=d.object({...b,message:d.string().min(1),type:d.literal("fail")}),Na=d.object({...b,type:d.literal("setVariable"),value:xt,variable:d.string().min(1)}),Oa=d.object({...b,locator:k,type:d.literal("extractText"),variable:d.string().min(1)}),Da=d.object({...b,files:d.array(d.string()).min(1),locator:k,type:d.literal("upload")}),La=d.object({...b,locator:k,type:d.literal("dblclick")}),_a=d.object({...b,source:k,target:k,type:d.literal("drag")}),Ua=d.object({...b,locator:k,type:d.literal("scrollIntoView")}),Va=d.object({...b,locator:k,type:d.literal("type"),value:G}),Fa=d.object({...b,locator:k,type:d.literal("focus")}),Ha=d.object({...b,locator:k,type:d.literal("clear")}),Ma=d.object({...b,locator:k,type:d.literal("rightClick")}),Wa=d.object({...b,action:d.enum(["accept","dismiss"]),promptText:d.string().optional(),type:d.literal("handleDialog")}),Ba=d.object({...b,action:d.enum(["read","write"]),type:d.literal("clipboard"),value:G.optional(),variable:d.string().min(1).optional()}),qa=d.object({...b,permission:d.string().min(1),state:d.enum(["granted","prompt"]),type:d.literal("setPermission")}),za=d.object({...b,locator:k,type:d.literal("assertVisible")}),Ga=d.object({...b,locator:k,type:d.literal("assertNotVisible")}),Ka=d.object({...b,expected:G,locator:k,operator:we,type:d.literal("assertText")}),Ja=d.object({...b,expected:G,operator:we,type:d.literal("assertUrl")}),Xa=d.object({...b,expected:Ct,locator:k,operator:Rt,type:d.literal("assertCount")}),Qa=d.object({...b,expected:G,locator:k,operator:we,type:d.literal("assertValue")}),Ya=d.object({...b,attribute:d.string().min(1),expected:G,locator:k,operator:we,type:d.literal("assertAttribute")}),Za=d.object({...b,locator:k,type:d.literal("assertEnabled")}),el=d.object({...b,locator:k,type:d.literal("assertDisabled")}),tl=d.object({...b,expected:G,operator:we,type:d.literal("assertTitle")}),rl=d.object({...b,locator:k,type:d.literal("assertChecked")}),nl=d.object({...b,locator:k,type:d.literal("assertNotChecked")}),ol=d.object({...b,locator:k,type:d.literal("assertFocused")}),il=d.object({...b,locator:k,type:d.literal("assertNotFocused")}),sl=d.object({...b,budget:d.enum(["fast","slow","async"]),observer:d.string().min(1).max(200),params:d.record(d.string().max(200),Cr),type:d.literal("assertObserver")}),Wn=d.discriminatedUnion("type",[Ra,Pa,xa,Ca,Ea,Aa,Ia,Ta,za,Ga,Ka,Ja,Xa,Qa,Ya,Za,el,$a,ja,Na,Oa,Da,La,_a,Ua,Va,Fa,Ha,Ma,Wa,Ba,qa,tl,rl,nl,ol,il,sl]),At=d.object({entryNode:d.string().min(1).max(200),nodes:d.record(d.string().max(200),Wn).refine(e=>Object.keys(e).length<=Mn,`Workflow has more than ${String(Mn)} nodes`),uiOnly:d.boolean().optional(),variableNamespaces:d.record(d.string().max(200),d.string().max(500)).optional(),variables:d.record(d.string().max(200),Et).optional()});var al=Bn.record(Bn.string().max(200),xr),ll={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},cl={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},Er=kt("workflow-spec").legacy(ll).initial(At).build(),dl=kt("precondition-map").legacy(cl).initial(al).build();import{z as Ar}from"zod";var qn=["fast","slow","async"],ul=Ar.object({budget:Ar.enum(qn).describe("Polling budget tier: fast | slow | async"),description:Ar.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 no,readFragment as bc}from"gql.tada";import{mkdir as Ir,writeFile as se}from"fs/promises";import J from"path";import{z as te}from"zod";async function Gn({context:e,page:t,runId:r,stepIndex:n,stepResult:o}){try{let i=J.join(process.cwd(),".ripplo","debug",r,"steps",String(n));await Ir(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(J.join(i,"info.json"),JSON.stringify(s,null,2)),pl({context:e,page:t,stepDir:i})])}catch(i){let s=i instanceof Error?i.message:String(i);y.warn("Failed to write step debug data for step %d: %s",n,s)}}async function pl({context:e,page:t,stepDir:r}){let[n,o,i,s]=await Promise.all([ml(t),yl(t),kl({context:e,page:t}),vl(t)]);await Promise.all([se(J.join(r,"dom.html"),n),se(J.join(r,"accessibility-tree.full.json"),JSON.stringify(o,null,2)),se(J.join(r,"accessibility-tree.json"),hl(o)),se(J.join(r,"storage.json"),JSON.stringify(i,null,2)),s==null?Promise.resolve():se(J.join(r,"screenshot.png"),s)])}async function ml(e){return await z({awaitPromise:!1,expression:"document.documentElement.outerHTML",page:e})??"(unable to capture DOM)"}var It=te.object({value:te.unknown()}).partial(),fl=te.object({childIds:te.array(te.string()),description:It,ignored:te.boolean(),name:It,nodeId:te.string(),parentId:te.string(),properties:te.array(te.unknown()),role:It,value:It}).partial(),gl=te.object({nodes:te.array(fl)});async function yl(e){let t={nodes:[]};return gt(e,t,async r=>{let n=await r.send("Accessibility.getFullAXTree"),o=gl.safeParse(n);return o.success?o.data:t})}function hl(e){return e.nodes.filter(t=>t.ignored!==!0).map(t=>wl(t)).toSorted(bl).map(t=>JSON.stringify(t)).join(`
29
- `)}function wl(e){let t=e.description?.value,r=e.value?.value;return{childIds:e.childIds??[],name:e.name?.value??"",nodeId:e.nodeId,parentId:e.parentId,properties:e.properties??[],role:e.role?.value??"",...t==null?{}:{description:t},...r==null?{}:{value:r}}}function bl(e,t){return zn(e.nodeId)-zn(t.nodeId)}function zn(e){if(e==null)return Number.MAX_SAFE_INTEGER;let t=Number.parseInt(e,10);return Number.isFinite(t)?t:Number.MAX_SAFE_INTEGER}async function vl(e){return gt(e,void 0,async t=>{let r=await t.send("Page.captureScreenshot",{format:"png"});return Buffer.from(r.data,"base64")})}var Sl=`(() => {
25
+ `);async function wr({maxRuns:e}){try{let r=(await da(_n,{withFileTypes:!0})).filter(c=>c.isDirectory()),n=Date.now(),o=await Promise.all(r.map(async c=>{let p=Vn.join(_n,c.name),m=await pa(p);return{dirPath:p,mtime:m.mtimeMs}})),i=o.filter(c=>n-c.mtime>Un),a=o.filter(c=>n-c.mtime<=Un).toSorted((c,p)=>p.mtime-c.mtime).slice(e),l=[...i,...a];if(l.length===0)return;await Promise.allSettled(l.map(c=>ua(c.dirPath,{force:!0,recursive:!0}))),y.info("Pruned %d old debug run(s)",l.length)}catch{y.warn("Debug run pruning failed, ignoring")}}var fa=5e3;async function br({appUrl:e}){try{await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(fa)})}catch(t){let r=t instanceof Error?t.message:String(t);throw y.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(`
26
+ `))}}import nt from"fs";import Ce from"fs";import ga from"os";import et from"path";var ya=".local",ha=".ripplo";function vr(e){return et.join(e,".ripplo",ya)}function tt(e){let t=vr(e);Ce.existsSync(t)||Ce.mkdirSync(t,{recursive:!0});let r=et.join(t,".gitignore");return Ce.existsSync(r)||Ce.writeFileSync(r,`*
27
+ `),t}function rt(e,t){return et.join(vr(e),t)}function kr(){return et.join(ga.homedir(),ha)}function Sr(){let e=kr();return Ce.existsSync(e)?Ce.chmodSync(e,448):Ce.mkdirSync(e,{mode:448,recursive:!0}),e}function ye(e){return et.join(kr(),e)}function ee(){let e=process.env.RIPPLO_TOKEN;if(e!=null&&e.trim().length>0)return e.trim();let t=ye("token");if(!nt.existsSync(t))return null;let r=nt.readFileSync(t,"utf8").trim();return r.length===0?null:r}function Rr(e){Sr(),nt.writeFileSync(ye("token"),e+`
28
+ `,{mode:384})}function Pr(){let e=ye("token");return nt.existsSync(e)?(nt.unlinkSync(e),!0):!1}import{z as vc}from"zod";import{z as bt}from"zod";var wa=bt.object({__codec:bt.string().min(1),data:bt.unknown(),version:bt.number().int().positive()}),vt=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}},kt=class extends Error{constructor(t){super(`Codec mismatch: expected "${t.expected}", got "${t.got}"`),this.name="CodecMismatchError"}};function St(e){return Fn({legacy:void 0,migrators:[],name:e,schemas:[]})}function Fn(e){return{initial:t=>xr(t,{...e,schemas:[t]}),legacy:t=>Fn({...e,legacy:t})}}function xr(e,t){return{build:()=>ba(e,t),legacy:r=>xr(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return xr(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function ba(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>va(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function va(e,t,r){let{data:n,version:o}=ka(t,r),i=Hn(t,n,o);return e.parse(i)}function ka(e,t){let r=wa.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new kt({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 Hn(e,t,r){let n=e.schemas.length;if(r>n)throw new vt({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 Hn(e,s(i),r+1)}import{z as qn}from"zod";import{z as De}from"zod";var Cr=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 d}from"zod";import{z as he}from"zod";var Sa=he.object({by:he.literal("testId"),value:he.string().min(1)}),Ra=he.object({by:he.literal("role"),name:he.string().optional(),role:he.string().min(1)}),R=he.discriminatedUnion("by",[Sa,Ra]);import{z as Mn}from"zod";var we=Mn.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),Rt=Mn.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]);import{z as A}from"zod";var Pa=A.object({type:A.literal("static"),value:A.union([A.string(),A.number(),A.boolean()])}),Pt=A.object({name:A.string().min(1),type:A.literal("variable")}),xt=A.discriminatedUnion("type",[Pa,Pt]),K=A.discriminatedUnion("type",[A.object({type:A.literal("static"),value:A.string()}),Pt]),Ct=A.discriminatedUnion("type",[A.object({type:A.literal("static"),value:A.number().int().nonnegative()}),Pt]),Er=A.discriminatedUnion("type",[A.object({type:A.literal("static"),value:A.union([A.string(),A.number(),A.boolean()])}),Pt]);import{z as J}from"zod";var Et=J.discriminatedUnion("type",[J.object({default:J.string().optional(),type:J.literal("string")}),J.object({default:J.number().optional(),type:J.literal("number")}),J.object({default:J.boolean().optional(),type:J.literal("boolean")}),J.object({key:J.string().min(1),type:J.literal("env")})]);var b={id:d.string().min(1).max(200),label:d.string().max(500).optional(),next:d.string().max(200).optional(),uiOnly:d.boolean().optional()},Wn=500,xa=d.object({...b,type:d.literal("goto"),url:K}),Ca=d.object({...b,locator:R,type:d.literal("click")}),Ea=d.object({...b,locator:R,type:d.literal("fill"),value:K}),Aa=d.object({...b,locator:R,type:d.literal("select"),value:K}),Ia=d.object({...b,locator:R,type:d.literal("hover")}),$a=d.object({...b,key:d.string().min(1),locator:R.optional(),type:d.literal("press")}),Ta=d.object({...b,locator:R,type:d.literal("check")}),ja=d.object({...b,locator:R,type:d.literal("uncheck")}),Na=d.object({...b,height:d.number().int().positive(),type:d.literal("setViewport"),width:d.number().int().positive()}),Oa=d.object({...b,message:d.string().min(1),type:d.literal("fail")}),Da=d.object({...b,type:d.literal("setVariable"),value:xt,variable:d.string().min(1)}),La=d.object({...b,locator:R,type:d.literal("extractText"),variable:d.string().min(1)}),_a=d.object({...b,files:d.array(d.string()).min(1),locator:R,type:d.literal("upload")}),Ua=d.object({...b,locator:R,type:d.literal("dblclick")}),Va=d.object({...b,source:R,target:R,type:d.literal("drag")}),Fa=d.object({...b,locator:R,type:d.literal("scrollIntoView")}),Ha=d.object({...b,locator:R,type:d.literal("type"),value:K}),Ma=d.object({...b,locator:R,type:d.literal("focus")}),Wa=d.object({...b,locator:R,type:d.literal("clear")}),Ba=d.object({...b,locator:R,type:d.literal("rightClick")}),qa=d.object({...b,action:d.enum(["accept","dismiss"]),promptText:d.string().optional(),type:d.literal("handleDialog")}),za=d.object({...b,action:d.enum(["read","write"]),type:d.literal("clipboard"),value:K.optional(),variable:d.string().min(1).optional()}),Ga=d.object({...b,permission:d.string().min(1),state:d.enum(["granted","prompt"]),type:d.literal("setPermission")}),Ka=d.object({...b,locator:R,type:d.literal("assertVisible")}),Ja=d.object({...b,locator:R,type:d.literal("assertNotVisible")}),Xa=d.object({...b,expected:K,locator:R,operator:we,type:d.literal("assertText")}),Qa=d.object({...b,expected:K,operator:we,type:d.literal("assertUrl")}),Ya=d.object({...b,expected:Ct,locator:R,operator:Rt,type:d.literal("assertCount")}),Za=d.object({...b,expected:K,locator:R,operator:we,type:d.literal("assertValue")}),el=d.object({...b,attribute:d.string().min(1),expected:K,locator:R,operator:we,type:d.literal("assertAttribute")}),tl=d.object({...b,locator:R,type:d.literal("assertEnabled")}),rl=d.object({...b,locator:R,type:d.literal("assertDisabled")}),nl=d.object({...b,expected:K,operator:we,type:d.literal("assertTitle")}),ol=d.object({...b,locator:R,type:d.literal("assertChecked")}),il=d.object({...b,locator:R,type:d.literal("assertNotChecked")}),sl=d.object({...b,locator:R,type:d.literal("assertFocused")}),al=d.object({...b,locator:R,type:d.literal("assertNotFocused")}),ll=d.object({...b,budget:d.enum(["fast","slow","async"]),observer:d.string().min(1).max(200),params:d.record(d.string().max(200),Er),type:d.literal("assertObserver")}),Bn=d.discriminatedUnion("type",[xa,Ca,Ea,Aa,Ia,$a,Ta,ja,Ka,Ja,Xa,Qa,Ya,Za,el,tl,rl,Na,Oa,Da,La,_a,Ua,Va,Fa,Ha,Ma,Wa,Ba,qa,za,Ga,nl,ol,il,sl,al,ll]),At=d.object({entryNode:d.string().min(1).max(200),nodes:d.record(d.string().max(200),Bn).refine(e=>Object.keys(e).length<=Wn,`Workflow has more than ${String(Wn)} nodes`),uiOnly:d.boolean().optional(),variableNamespaces:d.record(d.string().max(200),d.string().max(500)).optional(),variables:d.record(d.string().max(200),Et).optional()});var cl=qn.record(qn.string().max(200),Cr),dl={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},ul={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},Ar=St("workflow-spec").legacy(dl).initial(At).build(),pl=St("precondition-map").legacy(ul).initial(cl).build();import{z as Ir}from"zod";var zn=["fast","slow","async"],ml=Ir.object({budget:Ir.enum(zn).describe("Polling budget tier: fast | slow | async"),description:Ir.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 oo,readFragment as kc}from"gql.tada";import{mkdir as $r,writeFile as se}from"fs/promises";import X from"path";import{z as te}from"zod";async function Kn({context:e,page:t,runId:r,stepIndex:n,stepResult:o}){try{let i=X.join(process.cwd(),".ripplo","debug",r,"steps",String(n));await $r(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(X.join(i,"info.json"),JSON.stringify(s,null,2)),fl({context:e,page:t,stepDir:i})])}catch(i){let s=i instanceof Error?i.message:String(i);y.warn("Failed to write step debug data for step %d: %s",n,s)}}async function fl({context:e,page:t,stepDir:r}){let[n,o,i,s]=await Promise.all([gl(t),wl(t),Pl({context:e,page:t}),Sl(t)]);await Promise.all([se(X.join(r,"dom.html"),n),se(X.join(r,"accessibility-tree.full.json"),JSON.stringify(o,null,2)),se(X.join(r,"accessibility-tree.json"),bl(o)),se(X.join(r,"storage.json"),JSON.stringify(i,null,2)),s==null?Promise.resolve():se(X.join(r,"screenshot.png"),s)])}async function gl(e){return await G({awaitPromise:!1,expression:"document.documentElement.outerHTML",page:e})??"(unable to capture DOM)"}var It=te.object({value:te.unknown()}).partial(),yl=te.object({childIds:te.array(te.string()),description:It,ignored:te.boolean(),name:It,nodeId:te.string(),parentId:te.string(),properties:te.array(te.unknown()),role:It,value:It}).partial(),hl=te.object({nodes:te.array(yl)});async function wl(e){let t={nodes:[]};return gt(e,t,async r=>{let n=await r.send("Accessibility.getFullAXTree"),o=hl.safeParse(n);return o.success?o.data:t})}function bl(e){return e.nodes.filter(t=>t.ignored!==!0).map(t=>vl(t)).toSorted(kl).map(t=>JSON.stringify(t)).join(`
29
+ `)}function vl(e){let t=e.description?.value,r=e.value?.value;return{childIds:e.childIds??[],name:e.name?.value??"",nodeId:e.nodeId,parentId:e.parentId,properties:e.properties??[],role:e.role?.value??"",...t==null?{}:{description:t},...r==null?{}:{value:r}}}function kl(e,t){return Gn(e.nodeId)-Gn(t.nodeId)}function Gn(e){if(e==null)return Number.MAX_SAFE_INTEGER;let t=Number.parseInt(e,10);return Number.isFinite(t)?t:Number.MAX_SAFE_INTEGER}async function Sl(e){return gt(e,void 0,async t=>{let r=await t.send("Page.captureScreenshot",{format:"png"});return Buffer.from(r.data,"base64")})}var Rl=`(() => {
30
30
  function dump(s) {
31
31
  var out = {};
32
32
  for (var i = 0; i < s.length; i++) {
@@ -36,41 +36,41 @@ Add missing values to the env file(s) declared in .ripplo/project.json.${i}`)}le
36
36
  return out;
37
37
  }
38
38
  return { localStorage: dump(localStorage), sessionStorage: dump(sessionStorage) };
39
- })()`;async function kl({context:e,page:t}){let[r,n]=await Promise.all([z({awaitPromise:!1,expression:Sl,page:t}),e.cookies().catch(()=>[])]);return{cookies:n,localStorage:r?.localStorage??{},sessionStorage:r?.sessionStorage??{}}}async function Kn({runId:e,steps:t,summary:r}){try{let n=J.join(process.cwd(),".ripplo","debug",e);await Ir(n,{recursive:!0}),await Promise.all([se(J.join(n,"summary.txt"),Rl({steps:t,summary:r})),se(J.join(n,"manifest.md"),Pl({steps:t,summary:r}))]),y.info("Debug artifacts written to .ripplo/debug/%s/",e)}catch(n){let o=n instanceof Error?n.message:String(n);y.warn("Failed to write run debug summary: %s",o)}}function Rl({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(`
40
- `)}function Pl({steps:e,summary:t}){return[`# Run ${t.runId} \u2014 ${t.workflowName}`,"",`Status: **${t.status}** \xB7 ${String(t.passCount)} passed \xB7 ${String(t.failCount)} failed \xB7 ${String(t.duration)}ms`,"","Start here:","- `summary.txt` \u2014 high-level run summary (read first).","- `error.txt` \u2014 present only when the run failed; the failure reason + stack.","","## Per-step artifacts","","Each `steps/<N>/` directory contains:","","- `info.json` \u2014 step metadata (title, type, duration, assertions).",'- `accessibility-tree.json` \u2014 **compact NDJSON** of the AX tree at snapshot time. One node per line, ignored nodes dropped, provenance arrays stripped. Read directly; line-oriented grep works (e.g. `grep \'"role":"button"\'`).',"- `accessibility-tree.full.json` \u2014 full Chrome DevTools AX tree. Large; slice with `sed`/`grep` if the compact view isn't enough.","- `dom.html` \u2014 full `document.documentElement.outerHTML` at snapshot time. Large; slice with `sed`/`grep`.","- `screenshot.png` \u2014 PNG, readable as an image (focus rings, contrast, visible state).","- `storage.json` \u2014 cookies + localStorage + sessionStorage.","","## Slicing recipes for large files","","```","wc -c steps/*/dom.html # check sizes","sed -n '1500,1700p' steps/3/dom.html # read a line range","grep -n 'aria-label' steps/3/dom.html | head # locate then narrow",`grep '"role":"navigation"' steps/*/accessibility-tree.json`,"```","","## Steps","",...e.flatMap(r=>[`### steps/${String(r.stepIndex)} \u2014 "${r.title}" (${r.nodeType}, ${r.status}, ${String(r.duration)}ms)`,r.detail==null?"":`> ${r.detail}`,""])].join(`
41
- `)}async function Jn({error:e,runId:t,stack:r,workflowName:n}){try{let o=J.join(process.cwd(),".ripplo","debug",t);await Ir(o,{recursive:!0});let i=r==null?e:`${e}
39
+ })()`;async function Pl({context:e,page:t}){let[r,n]=await Promise.all([G({awaitPromise:!1,expression:Rl,page:t}),e.cookies().catch(()=>[])]);return{cookies:n,localStorage:r?.localStorage??{},sessionStorage:r?.sessionStorage??{}}}async function Jn({runId:e,steps:t,summary:r}){try{let n=X.join(process.cwd(),".ripplo","debug",e);await $r(n,{recursive:!0}),await Promise.all([se(X.join(n,"summary.txt"),xl({steps:t,summary:r})),se(X.join(n,"manifest.md"),Cl({steps:t,summary:r}))]),y.info("Debug artifacts written to .ripplo/debug/%s/",e)}catch(n){let o=n instanceof Error?n.message:String(n);y.warn("Failed to write run debug summary: %s",o)}}function xl({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(`
40
+ `)}function Cl({steps:e,summary:t}){return[`# Run ${t.runId} \u2014 ${t.workflowName}`,"",`Status: **${t.status}** \xB7 ${String(t.passCount)} passed \xB7 ${String(t.failCount)} failed \xB7 ${String(t.duration)}ms`,"","Start here:","- `summary.txt` \u2014 high-level run summary (read first).","- `error.txt` \u2014 present only when the run failed; the failure reason + stack.","","## Per-step artifacts","","Each `steps/<N>/` directory contains:","","- `info.json` \u2014 step metadata (title, type, duration, assertions).",'- `accessibility-tree.json` \u2014 **compact NDJSON** of the AX tree at snapshot time. One node per line, ignored nodes dropped, provenance arrays stripped. Read directly; line-oriented grep works (e.g. `grep \'"role":"button"\'`).',"- `accessibility-tree.full.json` \u2014 full Chrome DevTools AX tree. Large; slice with `sed`/`grep` if the compact view isn't enough.","- `dom.html` \u2014 full `document.documentElement.outerHTML` at snapshot time. Large; slice with `sed`/`grep`.","- `screenshot.png` \u2014 PNG, readable as an image (focus rings, contrast, visible state).","- `storage.json` \u2014 cookies + localStorage + sessionStorage.","","## Slicing recipes for large files","","```","wc -c steps/*/dom.html # check sizes","sed -n '1500,1700p' steps/3/dom.html # read a line range","grep -n 'aria-label' steps/3/dom.html | head # locate then narrow",`grep '"role":"navigation"' steps/*/accessibility-tree.json`,"```","","## Steps","",...e.flatMap(r=>[`### steps/${String(r.stepIndex)} \u2014 "${r.title}" (${r.nodeType}, ${r.status}, ${String(r.duration)}ms)`,r.detail==null?"":`> ${r.detail}`,""])].join(`
41
+ `)}async function Xn({error:e,runId:t,stack:r,workflowName:n}){try{let o=X.join(process.cwd(),".ripplo","debug",t);await $r(o,{recursive:!0});let i=r==null?e:`${e}
42
42
 
43
43
  ${r}`,s=[`Run ID: ${t}`,`Workflow: ${n}`,"Status: failed","",`Error: ${e}`,"",r==null?"":`Stack trace:
44
44
  ${r}`].join(`
45
- `);await Promise.all([se(J.join(o,"error.txt"),i),se(J.join(o,"summary.txt"),s)]),y.info("Debug error artifacts written to .ripplo/debug/%s/",t)}catch(o){let i=o instanceof Error?o.message:String(o);y.warn("Failed to write error debug artifacts: %s",i)}}import{readFileSync as xl}from"fs";import{createRequire as Cl}from"module";import Xn from"path";import{gzipSync as El}from"zlib";var Al=Cl(import.meta.url),Il=Al.resolve("rrweb"),Tl=Xn.join(Xn.dirname(Il),"rrweb.umd.min.cjs"),$l=xl(Tl,"utf8"),jl=[";(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(`
46
- `),Nl=$l+`
47
- `+jl;async function Qn(e){let t,r=0;async function n(){await e.addScriptTag({content:Nl}).catch(()=>{})}await n(),e.on("load",()=>{n()});async function o(){await z({awaitPromise:!1,expression:"globalThis.__ripploRrwebStart && globalThis.__ripploRrwebStart()",page:e});let l=await z({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 z({awaitPromise:!1,expression:"globalThis.__ripploRrwebDrain ? globalThis.__ripploRrwebDrain() : []",page:e})??[],c=l[0],p=l.at(-1);if(c==null||p==null)return;t??=c.timestamp;let m=t,S=l.map(f=>JSON.stringify(f)).join(`
48
- `),N={body:El(Buffer.from(S,"utf8")),chunkIndex:r,endTimestamp:p.timestamp-m,eventCount:l.length,startTimestamp:c.timestamp-m};return r+=1,N}async function a(){await z({awaitPromise:!1,expression:"globalThis.__ripploRrwebStop && globalThis.__ripploRrwebStop()",page:e})}return{currentOffsetMs:i,detach:a,start:o,takeChunk:s}}import{z as re}from"zod";import Yn from"crypto";import{Webhook as Ol}from"standardwebhooks";function be({body:e,secret:t}){let r=new Ol(t),n=`msg_${Yn.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 Tr(){return`whsec_${Yn.randomBytes(24).toString("base64")}`}var Dl=15e4,Ll={async:{backoffMs:[500,1e3,2e3,5e3],timeoutMs:12e4},fast:{backoffMs:[100,250,500,1e3],timeoutMs:5e3},slow:{backoffMs:[250,500,1e3,2e3],timeoutMs:3e4}},_l=re.discriminatedUnion("kind",[re.object({kind:re.literal("pass")}),re.object({kind:re.literal("retry"),reason:re.string()}),re.object({kind:re.literal("fail"),reason:re.string()})]),Ul=re.object({error:re.string().optional(),outcome:_l.optional(),success:re.boolean()});async function Zn({apiUrl:e,budget:t,observer:r,params:n,webhookSecret:o}){let i=Ll[t],s=performance.now(),a={lastReason:void 0,pollCount:0};for(;performance.now()-s<i.timeoutMs;){a.pollCount+=1;let l=await Fl({apiUrl:e,observer:r,params:n,webhookSecret:o}),c=Vl({observer:r,outcome:l,start:s,state:a});if(c!=null)return c;let p=i.timeoutMs-(performance.now()-s);if(p<=0)break;let m=Math.min(Hl({backoff:i.backoffMs,pollCount:a.pollCount}),p);await Ml(m)}return{description:`observer "${r}"`,detail:`budget "${t}" exhausted after ${String(a.pollCount)} poll(s) (${eo(s)}); last: ${a.lastReason??"no retry reason"}
49
- \u2192 /ripplo:debug \u2014 check .ripplo/debug/<runId>/ artifacts`,status:"failed"}}function Vl({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}
50
- 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 (${eo(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.
51
- Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=t.reason,null)}async function Fl({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",...be({body:o,secret:n})},method:"PUT",signal:AbortSignal.timeout(Dl)});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=Ul.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 y.error("observer request failed: %s",s),{kind:"transport-error",reason:s}}}function Hl({backoff:e,pollCount:t}){let r=Math.min(t-1,e.length-1);return e[r]??1e3}function eo(e){return`${String(Math.round(performance.now()-e))}ms`}async function Ml(e){return new Promise(t=>setTimeout(t,e))}var Wl=1e4;async function $r({failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,spec:i,variables:s}){let a=performance.now();return ql({currentId:i.entryNode,failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,runStartTime:a,spec:i,variables:s})}function Bl({onStep:e,steps:t,target:r}){t.forEach(n=>{let o={...n,stepIndex:r.length};r.push(o),e?.(o)})}async function ql({currentId:e,failFast:t,getRecordingOffsetMs:r,observerTransport:n,onStep:o,page:i,runStartTime:s,spec:a,variables:l}){let c=[],p=l,m=e;for(;m!=null;){let S=a.nodes[m];if(S==null)throw new Error(`Node "${m}" not found in spec`);let j=m,N=S.label??`${S.type} (${m})`;y.info("Executing node: %s [%s]",N,S.type);let f=await zl({getRecordingOffsetMs:r,node:S,nodeId:j,observerTransport:n,page:i,runStartTime:s,variables:p});if(Bl({onStep:o,steps:[f],target:c}),p=f.variables,t&&f.status==="failed")break;m=S.next}return{steps:c,variables:p}}async function zl({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})`,p=Wl;try{let m=await Gl({node:t,observerTransport:n,page:o,timeout:p,variables:s}),S=Math.round(performance.now()-a),j=m.assertions.some(f=>f.status==="failed"),N=e?.();return{assertions:m.assertions,detail:void 0,duration:S,nodeId:r,nodeType:t.type,recordingEndMs:N,recordingStartMs:l,snapshotTimestamp:Math.round(performance.now()-i),status:j?"failed":"passed",stepIndex:0,title:c,url:o.url(),variables:m.variables}}catch(m){let S=Math.round(performance.now()-a),j=m instanceof Error?m.message:String(m),N=e?.();return{assertions:[],detail:j,duration:S,nodeId:r,nodeType:t.type,recordingEndMs:N,recordingStartMs:l,snapshotTimestamp:Math.round(performance.now()-i),status:"failed",stepIndex:0,title:c,url:o.url(),variables:s}}}async function Gl({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(Kl(e)){let s=await cr({node:e,page:r,timeout:n,variables:o});return{assertions:[],variables:s.variables}}return{assertions:await Xl({node:e,observerTransport:t,page:r,timeout:n,variables:o}),variables:o}}function Kl(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 Jl(e){return e.type.startsWith("assert")}async function Xl({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(!Jl(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 Yl({assertNode:i,page:r,timeout:n,variables:o});case"assertText":{let s=B({ref:i.expected,variables:o});return[await dr({expected:s,locator:O({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertUrl":{let s=B({ref:i.expected,variables:o});return[await ur({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertTitle":{let s=B({ref:i.expected,variables:o});return[await kn({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertCount":{let s=lr({ref:i.expected,variables:o});return[await pr({expected:s,locator:O({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertValue":{let s=B({ref:i.expected,variables:o});return[await mr({expected:s,locator:O({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertAttribute":{let s=B({ref:i.expected,variables:o});return[await Rn({attribute:i.attribute,expected:s,locator:O({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]=ht({ref:l,variables:o})}),[await Zn({apiUrl:t.apiUrl,budget:i.budget,observer:i.observer,params:s,webhookSecret:t.webhookSecret})]}}}var Ql={assertChecked:Cn,assertDisabled:xn,assertEnabled:Pn,assertFocused:An,assertNotChecked:En,assertNotFocused:In,assertNotVisible:gr,assertVisible:fr};async function Yl({assertNode:e,page:t,timeout:r,variables:n}){let o=Ql[e.type];return[await o({locator:O({locator:e.locator,page:t,variables:n}),timeout:r})]}var to=1e4;async function jr({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(to),c.setDefaultNavigationTimeout(to),r.length>0&&await c.addCookies(r);let p=await c.newPage(),m=await Qn(p);async function S(){let W=await m.takeChunk();W!=null&&i?.(W)}let j=setInterval(()=>{S()},2e3),N=[],f=!1;function M(W){s?.(W),f||(f=!0,m.start()),N.push(Gn({context:c,page:p,runId:a,stepIndex:W.stepIndex,stepResult:W}))}let $=Zl(n,l.variableNamespaces),V={...ar({defs:l.variables}),...$},ne=await $r({failFast:!0,getRecordingOffsetMs:m.currentOffsetMs,observerTransport:o,onStep:M,page:p,spec:l,variables:V});clearInterval(j);let Ee=ne.steps.filter(W=>W.status==="passed").length,ie=ne.steps.filter(W=>W.status==="failed").length,ze={duration:ne.steps.reduce((W,oe)=>W+oe.duration,0),failCount:ie,passCount:Ee,runId:a,status:ie>0?"failed":"passed",workflowName:""};return await Promise.all([Promise.allSettled(N).then(()=>Kn({runId:a,steps:ne.steps,summary:ze})),m.detach().then(S)]),await c.close(),ne.steps}function Zl(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 ue({fn:e,label:t}){let r=performance.now(),n=await e();return y.info("%s: %dms",t,Math.round(performance.now()-r)),n}import{parseSetCookie as ec}from"set-cookie-parser";import{z as X}from"zod";var ro=3e4,tc=X.object({data:X.record(X.string(),X.record(X.string(),X.string())),error:X.string().optional(),executed:X.array(X.string()),runId:X.string(),success:X.boolean()});async function Nr({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",...sc({cookies:t}),...be({body:i,secret:o})},method:"PUT",signal:AbortSignal.timeout(ro)});s.ok||y.error("Teardown returned %s",String(s.status))}catch{y.error("Teardown request failed")}}async function rc({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",...be({body:o,secret:r})},method:"PUT",signal:AbortSignal.timeout(ro)});if(!i.ok){let c=await oc(i);throw new Error(`execute-preconditions returned ${String(i.status)}: ${c}`)}let s=await i.json(),a=tc.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=ac({domain:new URL(e).hostname,res:i});return y.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 nc=X.object({error:X.string()});async function oc(e){let t=await e.text().catch(()=>"");if(t.length===0)return"no body";let r=ic(t),n=r==null?null:nc.safeParse(r);return n!=null&&n.success?n.data.error:t.slice(0,500)}function ic(e){try{return JSON.parse(e)}catch{return null}}function sc({cookies:e}){return e.length===0?{}:{Cookie:e.map(r=>`${r.name}=${r.value}`).join("; ")}}function ac({domain:e,res:t}){let r=t.headers.getSetCookie();return ec(r,{decodeValues:!1}).map(o=>lc({cookie:o,domain:e}))}function lc({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=dc({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 cc={lax:"Lax",none:"None",strict:"Strict"};function dc({raw:e}){return cc[e.toLowerCase()]??"Lax"}async function Tt({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:[]}:rc({apiUrl:n,preconditionNames:t,webhookSecret:r})}import{graphql as Oe}from"gql.tada";async function Or({config:e,runId:t}){if((await g({config:e,document:fc,variables:{runId:t}})).startRun==null)throw new Error("Failed to start run");let n=[];function o(l){let c=pc({config:e,runId:t,steps:[l]}).catch(p=>{y.error(p,"Failed to submit step %d",l.stepIndex)});n.push(c)}function i(l){let c=uc({chunk:l,config:e,runId:t}).catch(p=>{y.error(p,"Failed to submit recording chunk %d",l.chunkIndex)});n.push(c)}async function s(){await Promise.all(n)}async function a({statusOverride:l,steps:c,summary:p}){await ue({label:`flushSteps (${String(n.length)} steps)`,fn:()=>Promise.all(n)});let m=c.filter(f=>f.status==="passed").length,S=c.filter(f=>f.status==="failed").length,j=c.reduce((f,M)=>f+M.duration,0),N=l??(S>0?"failed":"passed");await ue({label:"completeRun",fn:()=>g({config:e,document:hc,variables:{duration:j,failCount:S,passCount:m,runId:t,status:N,summary:p??null,warnCount:0}})})}return{complete:a,enqueueRecordingChunk:i,enqueueStep:o,flushSteps:s,runId:t}}async function uc({chunk:e,config:t,runId:r}){await g({config:t,document:yc,variables:{input:{bodyBase64:e.body.toString("base64"),chunkIndex:e.chunkIndex,endTimestamp:e.endTimestamp,eventCount:e.eventCount,runId:r,startTimestamp:e.startTimestamp}}})}async function pc({config:e,runId: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 g({config:e,document:gc,variables:{runId:t,steps:n}})}async function Dr({config:e,reason:t,runId:r}){await g({config:e,document:mc,variables:{reason:t,runId:r}})}var ob=Oe(`
45
+ `);await Promise.all([se(X.join(o,"error.txt"),i),se(X.join(o,"summary.txt"),s)]),y.info("Debug error artifacts written to .ripplo/debug/%s/",t)}catch(o){let i=o instanceof Error?o.message:String(o);y.warn("Failed to write error debug artifacts: %s",i)}}import{readFileSync as El}from"fs";import{createRequire as Al}from"module";import Qn from"path";import{gzipSync as Il}from"zlib";var $l=Al(import.meta.url),Tl=$l.resolve("rrweb"),jl=Qn.join(Qn.dirname(Tl),"rrweb.umd.min.cjs"),Nl=El(jl,"utf8"),Ol=[";(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(`
46
+ `),Dl=Nl+`
47
+ `+Ol;async function Yn(e){let t,r=0;async function n(){await e.addScriptTag({content:Dl}).catch(()=>{})}await n(),e.on("load",()=>{n()});async function o(){await G({awaitPromise:!1,expression:"globalThis.__ripploRrwebStart && globalThis.__ripploRrwebStart()",page:e});let l=await G({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 G({awaitPromise:!1,expression:"globalThis.__ripploRrwebDrain ? globalThis.__ripploRrwebDrain() : []",page:e})??[],c=l[0],p=l.at(-1);if(c==null||p==null)return;t??=c.timestamp;let m=t,S=l.map(f=>JSON.stringify(f)).join(`
48
+ `),N={body:Il(Buffer.from(S,"utf8")),chunkIndex:r,endTimestamp:p.timestamp-m,eventCount:l.length,startTimestamp:c.timestamp-m};return r+=1,N}async function a(){await G({awaitPromise:!1,expression:"globalThis.__ripploRrwebStop && globalThis.__ripploRrwebStop()",page:e})}return{currentOffsetMs:i,detach:a,start:o,takeChunk:s}}import{z as re}from"zod";import Zn from"crypto";import{Webhook as Ll}from"standardwebhooks";function be({body:e,secret:t}){let r=new Ll(t),n=`msg_${Zn.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 Tr(){return`whsec_${Zn.randomBytes(24).toString("base64")}`}var _l=15e4,Ul={async:{backoffMs:[500,1e3,2e3,5e3],timeoutMs:12e4},fast:{backoffMs:[100,250,500,1e3],timeoutMs:5e3},slow:{backoffMs:[250,500,1e3,2e3],timeoutMs:3e4}},Vl=re.discriminatedUnion("kind",[re.object({kind:re.literal("pass")}),re.object({kind:re.literal("retry"),reason:re.string()}),re.object({kind:re.literal("fail"),reason:re.string()})]),Fl=re.object({error:re.string().optional(),outcome:Vl.optional(),success:re.boolean()});async function eo({apiUrl:e,budget:t,observer:r,params:n,webhookSecret:o}){let i=Ul[t],s=performance.now(),a={lastReason:void 0,pollCount:0};for(;performance.now()-s<i.timeoutMs;){a.pollCount+=1;let l=await Ml({apiUrl:e,observer:r,params:n,webhookSecret:o}),c=Hl({observer:r,outcome:l,start:s,state:a});if(c!=null)return c;let p=i.timeoutMs-(performance.now()-s);if(p<=0)break;let m=Math.min(Wl({backoff:i.backoffMs,pollCount:a.pollCount}),p);await Bl(m)}return{description:`observer "${r}"`,detail:`budget "${t}" exhausted after ${String(a.pollCount)} poll(s) (${to(s)}); last: ${a.lastReason??"no retry reason"}
49
+ \u2192 /ripplo:debug \u2014 check .ripplo/debug/<runId>/ artifacts`,status:"failed"}}function Hl({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}
50
+ 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 (${to(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.
51
+ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=t.reason,null)}async function Ml({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",...be({body:o,secret:n})},method:"PUT",signal:AbortSignal.timeout(_l)});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=Fl.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 y.error("observer request failed: %s",s),{kind:"transport-error",reason:s}}}function Wl({backoff:e,pollCount:t}){let r=Math.min(t-1,e.length-1);return e[r]??1e3}function to(e){return`${String(Math.round(performance.now()-e))}ms`}async function Bl(e){return new Promise(t=>setTimeout(t,e))}var ql=1e4;async function jr({failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,spec:i,variables:s}){let a=performance.now();return Gl({currentId:i.entryNode,failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,runStartTime:a,spec:i,variables:s})}function zl({onStep:e,steps:t,target:r}){t.forEach(n=>{let o={...n,stepIndex:r.length};r.push(o),e?.(o)})}async function Gl({currentId:e,failFast:t,getRecordingOffsetMs:r,observerTransport:n,onStep:o,page:i,runStartTime:s,spec:a,variables:l}){let c=[],p=l,m=e;for(;m!=null;){let S=a.nodes[m];if(S==null)throw new Error(`Node "${m}" not found in spec`);let j=m,N=S.label??`${S.type} (${m})`;y.info("Executing node: %s [%s]",N,S.type);let f=await Kl({getRecordingOffsetMs:r,node:S,nodeId:j,observerTransport:n,page:i,runStartTime:s,variables:p});if(zl({onStep:o,steps:[f],target:c}),p=f.variables,t&&f.status==="failed")break;m=S.next}return{steps:c,variables:p}}async function Kl({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})`,p=ql;try{let m=await Jl({node:t,observerTransport:n,page:o,timeout:p,variables:s}),S=Math.round(performance.now()-a),j=m.assertions.some(f=>f.status==="failed"),N=e?.();return{assertions:m.assertions,detail:void 0,duration:S,nodeId:r,nodeType:t.type,recordingEndMs:N,recordingStartMs:l,snapshotTimestamp:Math.round(performance.now()-i),status:j?"failed":"passed",stepIndex:0,title:c,url:o.url(),variables:m.variables}}catch(m){let S=Math.round(performance.now()-a),j=m instanceof Error?m.message:String(m),N=e?.();return{assertions:[],detail:j,duration:S,nodeId:r,nodeType:t.type,recordingEndMs:N,recordingStartMs:l,snapshotTimestamp:Math.round(performance.now()-i),status:"failed",stepIndex:0,title:c,url:o.url(),variables:s}}}async function Jl({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(Xl(e)){let s=await dr({node:e,page:r,timeout:n,variables:o});return{assertions:[],variables:s.variables}}return{assertions:await Yl({node:e,observerTransport:t,page:r,timeout:n,variables:o}),variables:o}}function Xl(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 Ql(e){return e.type.startsWith("assert")}async function Yl({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(!Ql(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 ec({assertNode:i,page:r,timeout:n,variables:o});case"assertText":{let s=q({ref:i.expected,variables:o});return[await ur({expected:s,locator:O({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertUrl":{let s=q({ref:i.expected,variables:o});return[await pr({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertTitle":{let s=q({ref:i.expected,variables:o});return[await Rn({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertCount":{let s=cr({ref:i.expected,variables:o});return[await mr({expected:s,locator:O({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertValue":{let s=q({ref:i.expected,variables:o});return[await fr({expected:s,locator:O({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertAttribute":{let s=q({ref:i.expected,variables:o});return[await Pn({attribute:i.attribute,expected:s,locator:O({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]=ht({ref:l,variables:o})}),[await eo({apiUrl:t.apiUrl,budget:i.budget,observer:i.observer,params:s,webhookSecret:t.webhookSecret})]}}}var Zl={assertChecked:En,assertDisabled:Cn,assertEnabled:xn,assertFocused:In,assertNotChecked:An,assertNotFocused:$n,assertNotVisible:yr,assertVisible:gr};async function ec({assertNode:e,page:t,timeout:r,variables:n}){let o=Zl[e.type];return[await o({locator:O({locator:e.locator,page:t,variables:n}),timeout:r})]}var ro=1e4;async function Nr({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(ro),c.setDefaultNavigationTimeout(ro),r.length>0&&await c.addCookies(r);let p=await c.newPage(),m=await Yn(p);async function S(){let B=await m.takeChunk();B!=null&&i?.(B)}let j=setInterval(()=>{S()},2e3),N=[],f=!1;function W(B){s?.(B),f||(f=!0,m.start()),N.push(Kn({context:c,page:p,runId:a,stepIndex:B.stepIndex,stepResult:B}))}let T=tc(n,l.variableNamespaces),V={...lr({defs:l.variables}),...T},ne=await jr({failFast:!0,getRecordingOffsetMs:m.currentOffsetMs,observerTransport:o,onStep:W,page:p,spec:l,variables:V});clearInterval(j);let Ie=ne.steps.filter(B=>B.status==="passed").length,ie=ne.steps.filter(B=>B.status==="failed").length,Ge={duration:ne.steps.reduce((B,oe)=>B+oe.duration,0),failCount:ie,passCount:Ie,runId:a,status:ie>0?"failed":"passed",workflowName:""};return await Promise.all([Promise.allSettled(N).then(()=>Jn({runId:a,steps:ne.steps,summary:Ge})),m.detach().then(S)]),await c.close(),ne.steps}function tc(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 ue({fn:e,label:t}){let r=performance.now(),n=await e();return y.info("%s: %dms",t,Math.round(performance.now()-r)),n}import{parseSetCookie as rc}from"set-cookie-parser";import{z as H}from"zod";var no=3e4,nc=H.object({data:H.record(H.string(),H.record(H.string(),H.union([H.string(),H.number(),H.boolean()]))),error:H.string().optional(),executed:H.array(H.string()),runId:H.string(),success:H.boolean()});async function Or({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",...lc({cookies:t}),...be({body:i,secret:o})},method:"PUT",signal:AbortSignal.timeout(no)});s.ok||y.error("Teardown returned %s",String(s.status))}catch{y.error("Teardown request failed")}}async function oc({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",...be({body:o,secret:r})},method:"PUT",signal:AbortSignal.timeout(no)});if(!i.ok){let c=await sc(i);throw new Error(`execute-preconditions returned ${String(i.status)}: ${c}`)}let s=await i.json(),a=nc.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=cc({domain:new URL(e).hostname,res:i});return y.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 ic=H.object({error:H.string()});async function sc(e){let t=await e.text().catch(()=>"");if(t.length===0)return"no body";let r=ac(t),n=r==null?null:ic.safeParse(r);return n!=null&&n.success?n.data.error:t.slice(0,500)}function ac(e){try{return JSON.parse(e)}catch{return null}}function lc({cookies:e}){return e.length===0?{}:{Cookie:e.map(r=>`${r.name}=${r.value}`).join("; ")}}function cc({domain:e,res:t}){let r=t.headers.getSetCookie();return rc(r,{decodeValues:!1}).map(o=>dc({cookie:o,domain:e}))}function dc({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=pc({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 uc={lax:"Lax",none:"None",strict:"Strict"};function pc({raw:e}){return uc[e.toLowerCase()]??"Lax"}async function $t({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:[]}:oc({apiUrl:n,preconditionNames:t,webhookSecret:r})}import{graphql as Le}from"gql.tada";async function Dr({config:e,runId:t}){if((await g({config:e,document:yc,variables:{runId:t}})).startRun==null)throw new Error("Failed to start run");let n=[];function o(l){let c=fc({config:e,runId:t,steps:[l]}).catch(p=>{y.error(p,"Failed to submit step %d",l.stepIndex)});n.push(c)}function i(l){let c=mc({chunk:l,config:e,runId:t}).catch(p=>{y.error(p,"Failed to submit recording chunk %d",l.chunkIndex)});n.push(c)}async function s(){await Promise.all(n)}async function a({statusOverride:l,steps:c,summary:p}){await ue({label:`flushSteps (${String(n.length)} steps)`,fn:()=>Promise.all(n)});let m=c.filter(f=>f.status==="passed").length,S=c.filter(f=>f.status==="failed").length,j=c.reduce((f,W)=>f+W.duration,0),N=l??(S>0?"failed":"passed");await ue({label:"completeRun",fn:()=>g({config:e,document:bc,variables:{duration:j,failCount:S,passCount:m,runId:t,status:N,summary:p??null,warnCount:0}})})}return{complete:a,enqueueRecordingChunk:i,enqueueStep:o,flushSteps:s,runId:t}}async function mc({chunk:e,config:t,runId:r}){await g({config:t,document:wc,variables:{input:{bodyBase64:e.body.toString("base64"),chunkIndex:e.chunkIndex,endTimestamp:e.endTimestamp,eventCount:e.eventCount,runId:r,startTimestamp:e.startTimestamp}}})}async function fc({config:e,runId: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 g({config:e,document:hc,variables:{runId:t,steps:n}})}async function Lr({config:e,reason:t,runId:r}){await g({config:e,document:gc,variables:{reason:t,runId:r}})}var ab=Le(`
52
52
  mutation MarkRunArtifactsUploadedCLI($runId: String!) {
53
53
  markRunArtifactsUploaded(runId: $runId)
54
54
  }
55
- `),mc=Oe(`
55
+ `),gc=Le(`
56
56
  mutation FailRunCLI($runId: String!, $reason: String!) {
57
57
  failRun(runId: $runId, reason: $reason)
58
58
  }
59
- `),fc=Oe(`
59
+ `),yc=Le(`
60
60
  mutation StartRunCLI($runId: String!) {
61
61
  startRun(runId: $runId) {
62
62
  id
63
63
  }
64
64
  }
65
- `),gc=Oe(`
65
+ `),hc=Le(`
66
66
  mutation SubmitRunStepsCLI($runId: String!, $steps: [StepInput!]!) {
67
67
  submitRunSteps(runId: $runId, steps: $steps)
68
68
  }
69
- `),yc=Oe(`
69
+ `),wc=Le(`
70
70
  mutation SubmitRunRecordingChunkCLI($input: SubmitRunRecordingChunkInput!) {
71
71
  submitRunRecordingChunk(input: $input)
72
72
  }
73
- `),hc=Oe(`
73
+ `),bc=Le(`
74
74
  mutation CompleteRunCLI(
75
75
  $runId: String!
76
76
  $status: RunStatus!
@@ -93,7 +93,7 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
93
93
  status
94
94
  }
95
95
  }
96
- `);var vc=12e4,oo=no(`
96
+ `);var Sc=12e4,io=oo(`
97
97
  fragment WorkflowRun on Workflow {
98
98
  id
99
99
  slug
@@ -105,7 +105,7 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
105
105
  preconditionName
106
106
  }
107
107
  }
108
- `),Sc=no(`
108
+ `),Rc=oo(`
109
109
  query RunWorkflowSpec($runId: String!) {
110
110
  run(id: $runId) {
111
111
  id
@@ -118,7 +118,7 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
118
118
  }
119
119
  }
120
120
  }
121
- `,[oo]);async function Lr({baseUrl:e,browser:t,config:r,headed:n,preconditionNames:o,runId:i,webhookSecret:s}){let a="unknown",l,c,p=!1;try{p=t==null,c=kc({externalBrowser:t,headed:n});let m=o==null?void 0:Tt({engineBaseUrl:r.engineUrl,preconditionNames:o,webhookSecret:s}),[{engineBaseUrl:S,workflow:j},N]=await Promise.all([ue({label:"Run context resolved",fn:()=>Ec({config:r,runId:i})}),ue({label:"Streaming run started",fn:()=>Or({config:r,runId:i})}),wr({appUrl:e})]);a=j.name,l=N;let f=Ac(j.spec);y.info("Executing workflow: %s",j.name),await $c(Pc({baseUrl:e,browserPromise:c,engineBaseUrl:S,preconditionPromise:m,runId:i,specData:f,streaming:l,webhookSecret:s,workflow:j}),Tc())}catch(m){throw await Rc({browserPromise:c,config:r,error:m,ownsBrowser:p,runId:i,streaming:l,workflowName:a}),m}}function kc({externalBrowser:e,headed:t}){return e!=null?Promise.resolve(e):ue({label:"Browser launched",fn:()=>Ye({headed:t})})}async function Rc({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 Jn({error:a,runId:o,stack:l,workflowName:s}),i==null?await Dr({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 Pc({baseUrl:e,browserPromise:t,engineBaseUrl:r,preconditionPromise:n,runId:o,specData:i,streaming:s,webhookSecret:a,workflow:l}){let c=n??Tt({engineBaseUrl:r,preconditionNames:l.preconditions,webhookSecret:a}),[p,m]=await Promise.all([c,t]);await xc({baseUrl:e,browser:m,preconditionResult:p,runId:o,specData:i,streaming:s,webhookSecret:a})}async function xc({baseUrl:e,browser:t,preconditionResult:r,runId:n,specData:o,streaming:i,webhookSecret:s}){let a=await ue({label:"Spec executed",fn:()=>jr({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 Cc({preconditionResult:r,webhookSecret:s}),await i.complete({statusOverride:void 0,steps:a,summary:void 0});let l=a.filter(p=>p.status==="passed").length,c=a.filter(p=>p.status==="failed").length;y.info("Run complete: %d passed, %d failed",l,c)}async function Cc({preconditionResult:e,webhookSecret:t}){e.apiUrl!=null&&await Nr({apiUrl:e.apiUrl,cookies:e.cookies,data:e.data,executed:e.executed,webhookSecret:t})}async function Ec({config:e,runId:t}){let r=await g({config:e,document:Sc,variables:{runId:t}});if(r.run?.workflow==null)throw new Error(`Run ${t} not found`);let n=bc(oo,r.run.workflow),o=r.run.workflow.project?.engineBaseUrl??"";return{engineBaseUrl:e.engineUrl.length>0?e.engineUrl:o,workflow:n}}function Ac(e){if(e==null)throw new Error("Workflow has no spec");return Er.decode(e)}var Ic=wc.coerce.number().int().positive().catch(vc);function Tc(){return Ic.parse(process.env.RIPPLO_RUN_TIMEOUT_MS)}async function $c(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{graphql as $t}from"gql.tada";var Sb=$t(`
121
+ `,[io]);async function _r({baseUrl:e,browser:t,config:r,headed:n,preconditionNames:o,runId:i,webhookSecret:s}){let a="unknown",l,c,p=!1;try{p=t==null,c=Pc({externalBrowser:t,headed:n});let m=o==null?void 0:$t({engineBaseUrl:r.engineUrl,preconditionNames:o,webhookSecret:s}),[{engineBaseUrl:S,workflow:j},N]=await Promise.all([ue({label:"Run context resolved",fn:()=>Ic({config:r,runId:i})}),ue({label:"Streaming run started",fn:()=>Dr({config:r,runId:i})}),br({appUrl:e})]);a=j.name,l=N;let f=$c(j.spec);y.info("Executing workflow: %s",j.name),await Nc(Cc({baseUrl:e,browserPromise:c,engineBaseUrl:S,preconditionPromise:m,runId:i,specData:f,streaming:l,webhookSecret:s,workflow:j}),jc())}catch(m){throw await xc({browserPromise:c,config:r,error:m,ownsBrowser:p,runId:i,streaming:l,workflowName:a}),m}}function Pc({externalBrowser:e,headed:t}){return e!=null?Promise.resolve(e):ue({label:"Browser launched",fn:()=>Ze({headed:t})})}async function xc({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 Xn({error:a,runId:o,stack:l,workflowName:s}),i==null?await Lr({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 Cc({baseUrl:e,browserPromise:t,engineBaseUrl:r,preconditionPromise:n,runId:o,specData:i,streaming:s,webhookSecret:a,workflow:l}){let c=n??$t({engineBaseUrl:r,preconditionNames:l.preconditions,webhookSecret:a}),[p,m]=await Promise.all([c,t]);await Ec({baseUrl:e,browser:m,preconditionResult:p,runId:o,specData:i,streaming:s,webhookSecret:a})}async function Ec({baseUrl:e,browser:t,preconditionResult:r,runId:n,specData:o,streaming:i,webhookSecret:s}){let a=await ue({label:"Spec executed",fn:()=>Nr({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 Ac({preconditionResult:r,webhookSecret:s}),await i.complete({statusOverride:void 0,steps:a,summary:void 0});let l=a.filter(p=>p.status==="passed").length,c=a.filter(p=>p.status==="failed").length;y.info("Run complete: %d passed, %d failed",l,c)}async function Ac({preconditionResult:e,webhookSecret:t}){e.apiUrl!=null&&await Or({apiUrl:e.apiUrl,cookies:e.cookies,data:e.data,executed:e.executed,webhookSecret:t})}async function Ic({config:e,runId:t}){let r=await g({config:e,document:Rc,variables:{runId:t}});if(r.run?.workflow==null)throw new Error(`Run ${t} not found`);let n=kc(io,r.run.workflow),o=r.run.workflow.project?.engineBaseUrl??"";return{engineBaseUrl:e.engineUrl.length>0?e.engineUrl:o,workflow:n}}function $c(e){if(e==null)throw new Error("Workflow has no spec");return Ar.decode(e)}var Tc=vc.coerce.number().int().positive().catch(Sc);function jc(){return Tc.parse(process.env.RIPPLO_RUN_TIMEOUT_MS)}async function Nc(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{graphql as Tt}from"gql.tada";var Pb=Tt(`
122
122
  query AgentReviewContextWorker($reviewId: String!) {
123
123
  agentReview(id: $reviewId) {
124
124
  id
@@ -132,11 +132,11 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
132
132
  }
133
133
  }
134
134
  }
135
- `);var kb=$t(`
135
+ `);var xb=Tt(`
136
136
  mutation StartAgentReviewWorker($reviewId: String!) {
137
137
  startAgentReview(reviewId: $reviewId)
138
138
  }
139
- `);var Rb=$t(`
139
+ `);var Cb=Tt(`
140
140
  mutation CompleteAgentReviewWorker(
141
141
  $reviewId: String!
142
142
  $markdown: String!
@@ -144,34 +144,34 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
144
144
  ) {
145
145
  completeAgentReview(reviewId: $reviewId, markdown: $markdown, shortSummary: $shortSummary)
146
146
  }
147
- `);var Pb=$t(`
147
+ `);var Eb=Tt(`
148
148
  mutation FailAgentReviewWorker($reviewId: String!, $reason: String!) {
149
149
  failAgentReview(reviewId: $reviewId, reason: $reason)
150
150
  }
151
- `);import{exec as Lc}from"child_process";import{createAuthClient as jc}from"better-auth/client";import{deviceAuthorizationClient as Nc}from"better-auth/client/plugins";function io({baseURL:e}){return jc({baseURL:e,fetchOptions:{headers:{"User-Agent":"Ripplo CLI"}},plugins:[Nc()]})}import{z as _r}from"zod";var Oc="https://ripplo.ai";function Q(){return jt().RIPPLO_SERVER_URL}function ao(){return jt().RIPPLO_PROJECT_ID}var Dc=_r.object({RIPPLO_PROJECT_ID:_r.string().min(1).optional(),RIPPLO_SERVER_URL:_r.string().min(1).default(Oc)}),so;function jt(){return so??=Dc.parse(process.env),so}var _c=5e3,lo="ripplo-cli";async function co({onDeviceCode:e,url:t}){let r=t??jt().RIPPLO_SERVER_URL,n=io({baseURL:r}),o=await n.device.code({client_id:lo});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}),Wc(a);let l=await Uc({authClient:n,deviceCode:i});return kr(l),l}async function Uc({authClient:e,deviceCode:t}){for(;;){await Hc(_c);let r=await e.device.token({client_id:lo,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(!Fc(r.error.error))throw new Error(`Authorization failed: ${r.error.error_description}`)}}var Vc=new Set(["authorization_pending","slow_down"]);function Fc(e){return Vc.has(e)}function Hc(e){return new Promise(t=>{setTimeout(t,e)})}function Mc(){return process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open"}function Wc(e){let t=Mc();Lc(`${t} "${e}"`,()=>{})}function ve({serverUrl:e,token:t}){return{appUrl:"",cwd:process.cwd(),engineUrl:"",projectId:"",ripploServerUrl:e,token:t,webhookSecret:""}}import Bc from"fs";import qc from"path";function x(e){return Bc.existsSync(qc.join(e,".ripplo"))}var Gc=zc(`
151
+ `);import{exec as Uc}from"child_process";import{createAuthClient as Oc}from"better-auth/client";import{deviceAuthorizationClient as Dc}from"better-auth/client/plugins";function so({baseURL:e}){return Oc({baseURL:e,fetchOptions:{headers:{"User-Agent":"Ripplo CLI"}},plugins:[Dc()]})}import{z as Ur}from"zod";var Lc="https://ripplo.ai";function Q(){return jt().RIPPLO_SERVER_URL}function lo(){return jt().RIPPLO_PROJECT_ID}var _c=Ur.object({RIPPLO_PROJECT_ID:Ur.string().min(1).optional(),RIPPLO_SERVER_URL:Ur.string().min(1).default(Lc)}),ao;function jt(){return ao??=_c.parse(process.env),ao}var Vc=5e3,co="ripplo-cli";async function uo({onDeviceCode:e,url:t}){let r=t??jt().RIPPLO_SERVER_URL,n=so({baseURL:r}),o=await n.device.code({client_id:co});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}),qc(a);let l=await Fc({authClient:n,deviceCode:i});return Rr(l),l}async function Fc({authClient:e,deviceCode:t}){for(;;){await Wc(Vc);let r=await e.device.token({client_id:co,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(!Mc(r.error.error))throw new Error(`Authorization failed: ${r.error.error_description}`)}}var Hc=new Set(["authorization_pending","slow_down"]);function Mc(e){return Hc.has(e)}function Wc(e){return new Promise(t=>{setTimeout(t,e)})}function Bc(){return process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open"}function qc(e){let t=Bc();Uc(`${t} "${e}"`,()=>{})}function ve({serverUrl:e,token:t}){return{appUrl:"",cwd:process.cwd(),engineUrl:"",projectId:"",ripploServerUrl:e,token:t,webhookSecret:""}}import zc from"fs";import Gc from"path";function x(e){return zc.existsSync(Gc.join(e,".ripplo"))}var Jc=Kc(`
152
152
  query AuthViewer {
153
153
  currentUser {
154
154
  name
155
155
  email
156
156
  }
157
157
  }
158
- `);async function uo(){let e=Q(),t=ee();if(t!=null){let s=await Ur({serverUrl:e,token:t});if(s!=null){process.stdout.write(`Already signed in as ${s.email}. Run \`ripplo auth logout\` to switch.
158
+ `);async function po(){let e=Q(),t=ee();if(t!=null){let s=await Vr({serverUrl:e,token:t});if(s!=null){process.stdout.write(`Already signed in as ${s.email}. Run \`ripplo auth logout\` to switch.
159
159
  `);return}process.stdout.write(`Your saved session expired \u2014 let's sign you back in.
160
160
 
161
- `)}let r=await co({url:e,onDeviceCode:s=>{process.stdout.write(`Opening your browser to finish sign-in.
161
+ `)}let r=await uo({url:e,onDeviceCode:s=>{process.stdout.write(`Opening your browser to finish sign-in.
162
162
  `),process.stdout.write(`If it didn't open, visit: ${s.verificationUrl}
163
163
  `),process.stdout.write(`Verification code: ${s.userCode}
164
164
 
165
165
  `),process.stdout.write(`Waiting for you to approve...
166
- `)}}),n=await Ur({serverUrl:e,token:r}),o=x(process.cwd()),i=o?"Welcome back":"Welcome to Ripplo";process.stdout.write(`
166
+ `)}}),n=await Vr({serverUrl:e,token:r}),o=x(process.cwd()),i=o?"Welcome back":"Welcome to Ripplo";process.stdout.write(`
167
167
  `),process.stdout.write(n==null?`${i}.
168
- `:`${i}, ${Kc(n)}.
168
+ `:`${i}, ${Xc(n)}.
169
169
  `),process.stdout.write(`Session saved to ${ye("token")}.
170
- `),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 Kc(e){let t=e.name.trim().split(/\s+/)[0];return t!=null&&t.length>0?t:e.email}async function Ur({serverUrl:e,token:t}){try{let n=(await g({config:ve({serverUrl:e,token:t}),document:Gc,variables:void 0})).currentUser;return n==null?null:{email:n.email,name:n.name}}catch{return null}}async function po(){let e=ee();e==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login`.\n"),process.exit(1));let t=Q(),r=await Ur({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})
171
- `)}function mo(){if(!Rr()){process.stdout.write(`No token to remove.
170
+ `),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 Xc(e){let t=e.name.trim().split(/\s+/)[0];return t!=null&&t.length>0?t:e.email}async function Vr({serverUrl:e,token:t}){try{let n=(await g({config:ve({serverUrl:e,token:t}),document:Jc,variables:void 0})).currentUser;return n==null?null:{email:n.email,name:n.name}}catch{return null}}async function mo(){let e=ee();e==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login`.\n"),process.exit(1));let t=Q(),r=await Vr({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})
171
+ `)}function fo(){if(!Pr()){process.stdout.write(`No token to remove.
172
172
  `);return}process.stdout.write(`Removed ${ye("token")}
173
- `)}import Fr from"fs/promises";import Hr from"path";import{z as Nt}from"zod";import{z as fo}from"zod";import{z as De}from"zod";import{z as u}from"zod";import{z as Se}from"zod";import{z as bo}from"zod";import{z as I}from"zod";import{z as Y}from"zod";import{z as Vr}from"zod";import{z as L}from"zod";var Jc=Nt.object({__codec:Nt.string().min(1),data:Nt.unknown(),version:Nt.number().int().positive()}),Xc=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}},Qc=class extends Error{constructor(e){super(`Codec mismatch: expected "${e.expected}", got "${e.got}"`),this.name="CodecMismatchError"}};function Br(e){return yo({legacy:void 0,migrators:[],name:e,schemas:[]})}function Yc(e,t){let r=JSON.parse(t);return e.decode(r)}function yo(e){return{initial:t=>Mr(t,{...e,schemas:[t]}),legacy:t=>yo({...e,legacy:t})}}function Mr(e,t){return{build:()=>Zc(e,t),legacy:r=>Mr(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return Mr(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function Zc(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>ed(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function ed(e,t,r){let{data:n,version:o}=td(t,r),i=ho(t,n,o);return e.parse(i)}function td(e,t){let r=Jc.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new Qc({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 ho(e,t,r){let n=e.schemas.length;if(r>n)throw new Xc({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 ho(e,s(i),r+1)}var wo=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."),rd=Se.object({by:Se.literal("testId"),value:Se.string().min(1)}),nd=Se.object({by:Se.literal("role"),name:Se.string().optional(),role:Se.string().min(1)}),P=Se.discriminatedUnion("by",[rd,nd]),nt=bo.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),od=bo.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]),id=I.object({type:I.literal("static"),value:I.union([I.string(),I.number(),I.boolean()])}),Ot=I.object({name:I.string().min(1),type:I.literal("variable")}),sd=I.discriminatedUnion("type",[id,Ot]),ae=I.discriminatedUnion("type",[I.object({type:I.literal("static"),value:I.string()}),Ot]),ad=I.discriminatedUnion("type",[I.object({type:I.literal("static"),value:I.number().int().nonnegative()}),Ot]),ld=I.discriminatedUnion("type",[I.object({type:I.literal("static"),value:I.union([I.string(),I.number(),I.boolean()])}),Ot]),cd=Y.discriminatedUnion("type",[Y.object({default:Y.string().optional(),type:Y.literal("string")}),Y.object({default:Y.number().optional(),type:Y.literal("number")}),Y.object({default:Y.boolean().optional(),type:Y.literal("boolean")}),Y.object({key:Y.string().min(1),type:Y.literal("env")})]),v={id:u.string().min(1).max(200),label:u.string().max(500).optional(),next:u.string().max(200).optional(),uiOnly:u.boolean().optional()},go=500,dd=u.object({...v,type:u.literal("goto"),url:ae}),ud=u.object({...v,locator:P,type:u.literal("click")}),pd=u.object({...v,locator:P,type:u.literal("fill"),value:ae}),md=u.object({...v,locator:P,type:u.literal("select"),value:ae}),fd=u.object({...v,locator:P,type:u.literal("hover")}),gd=u.object({...v,key:u.string().min(1),locator:P.optional(),type:u.literal("press")}),yd=u.object({...v,locator:P,type:u.literal("check")}),hd=u.object({...v,locator:P,type:u.literal("uncheck")}),wd=u.object({...v,height:u.number().int().positive(),type:u.literal("setViewport"),width:u.number().int().positive()}),bd=u.object({...v,message:u.string().min(1),type:u.literal("fail")}),vd=u.object({...v,type:u.literal("setVariable"),value:sd,variable:u.string().min(1)}),Sd=u.object({...v,locator:P,type:u.literal("extractText"),variable:u.string().min(1)}),kd=u.object({...v,files:u.array(u.string()).min(1),locator:P,type:u.literal("upload")}),Rd=u.object({...v,locator:P,type:u.literal("dblclick")}),Pd=u.object({...v,source:P,target:P,type:u.literal("drag")}),xd=u.object({...v,locator:P,type:u.literal("scrollIntoView")}),Cd=u.object({...v,locator:P,type:u.literal("type"),value:ae}),Ed=u.object({...v,locator:P,type:u.literal("focus")}),Ad=u.object({...v,locator:P,type:u.literal("clear")}),Id=u.object({...v,locator:P,type:u.literal("rightClick")}),Td=u.object({...v,action:u.enum(["accept","dismiss"]),promptText:u.string().optional(),type:u.literal("handleDialog")}),$d=u.object({...v,action:u.enum(["read","write"]),type:u.literal("clipboard"),value:ae.optional(),variable:u.string().min(1).optional()}),jd=u.object({...v,permission:u.string().min(1),state:u.enum(["granted","prompt"]),type:u.literal("setPermission")}),Nd=u.object({...v,locator:P,type:u.literal("assertVisible")}),Od=u.object({...v,locator:P,type:u.literal("assertNotVisible")}),Dd=u.object({...v,expected:ae,locator:P,operator:nt,type:u.literal("assertText")}),Ld=u.object({...v,expected:ae,operator:nt,type:u.literal("assertUrl")}),_d=u.object({...v,expected:ad,locator:P,operator:od,type:u.literal("assertCount")}),Ud=u.object({...v,expected:ae,locator:P,operator:nt,type:u.literal("assertValue")}),Vd=u.object({...v,attribute:u.string().min(1),expected:ae,locator:P,operator:nt,type:u.literal("assertAttribute")}),Fd=u.object({...v,locator:P,type:u.literal("assertEnabled")}),Hd=u.object({...v,locator:P,type:u.literal("assertDisabled")}),Md=u.object({...v,expected:ae,operator:nt,type:u.literal("assertTitle")}),Wd=u.object({...v,locator:P,type:u.literal("assertChecked")}),Bd=u.object({...v,locator:P,type:u.literal("assertNotChecked")}),qd=u.object({...v,locator:P,type:u.literal("assertFocused")}),zd=u.object({...v,locator:P,type:u.literal("assertNotFocused")}),Gd=u.object({...v,budget:u.enum(["fast","slow","async"]),observer:u.string().min(1).max(200),params:u.record(u.string().max(200),ld),type:u.literal("assertObserver")}),Kd=u.discriminatedUnion("type",[dd,ud,pd,md,fd,gd,yd,hd,Nd,Od,Dd,Ld,_d,Ud,Vd,Fd,Hd,wd,bd,vd,Sd,kd,Rd,Pd,xd,Cd,Ed,Ad,Id,Td,$d,jd,Md,Wd,Bd,qd,zd,Gd]),vo=u.object({entryNode:u.string().min(1).max(200),nodes:u.record(u.string().max(200),Kd).refine(e=>Object.keys(e).length<=go,`Workflow has more than ${String(go)} nodes`),uiOnly:u.boolean().optional(),variableNamespaces:u.record(u.string().max(200),u.string().max(500)).optional(),variables:u.record(u.string().max(200),cd).optional()}),Jd=fo.record(fo.string().max(200),wo),Xd={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},Qd={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},_v=Br("workflow-spec").legacy(Xd).initial(vo).build(),Uv=Br("precondition-map").legacy(Qd).initial(Jd).build(),Yd=["fast","slow","async"],Zd=Vr.object({budget:Vr.enum(Yd).describe("Polling budget tier: fast | slow | async"),description:Vr.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."),le=".ripplo/ripplo.lock",eu=5e3,tu=L.record(L.string().max(200),L.string().max(200)),ru=L.object({coverage:L.array(L.string().max(500)).max(2e3).default([]),expectedOutcome:L.string().max(2e3),name:L.string().max(200),preconditions:L.array(L.string().max(200)).max(1e3),requiresKeys:tu,slug:L.string().max(200),sourcePath:L.string().max(500).optional(),spec:vo}),nu=L.object({observers:L.record(L.string().max(200),Zd),preconditions:L.record(L.string().max(200),wo),tests:L.array(ru).max(eu)}),So=Br("ripplo-lockfile").initial(nu).build();function ko(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,sourcePath:t.sourcePath,spec:t.spec}))}}function Wr(e){let t=So.encode(e);return`${JSON.stringify(t,su(t),2)}
174
- `}async function Dt({cwd:e}){let t=Hr.join(e,le),r=await ou(t);return r==null?null:Yc(So,r)}async function ce({cwd:e,result:t}){let r=ko(t),n=Hr.join(e,le);await Fr.mkdir(Hr.dirname(n),{recursive:!0}),await Fr.writeFile(n,Wr(r),"utf8")}function Lt({compiled:e,existing:t}){if(t==null)return"missing";let r=Wr(ko(e)),n=Wr(t);return r===n?"match":"stale"}async function ou(e){try{return await Fr.readFile(e,"utf8")}catch(t){if(iu(t)&&t.code==="ENOENT")return null;throw t}}function iu(e){return e instanceof Error&&"code"in e}function su(e){return function(r,n){return n===e||!au(n)?n:Object.fromEntries(Object.entries(n).toSorted(([o],[i])=>o.localeCompare(i)))}}function au(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import ot from"fs";import Vt from"path";var qr=["**/src/**","**/app/**","**/apps/**","**/pages/**","**/routes/**","**/components/**","**/server/**","**/api/**","**/backend/**","**/features/**","**/modules/**","**/views/**","**/ui/**","**/hooks/**","**/contexts/**","**/providers/**","**/controllers/**","**/handlers/**","**/resolvers/**","**/services/**","**/middleware/**","**/lib/**"],ke=["**/*.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 Ro(e){return e.data}function Po(e){return{as(t){return{data:{label:t,node:e}}}}}function _t(e){let t=e.getPreconditions(),r=e.getObservers(),n=e.getTests();lu(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=>cu(a,t));return{observers:i,preconditions:o,tests:s}}function lu(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 cu(e,t){let r=e.id,{accessedKeys:n,vars:o}=uu(e.requiresKeys),i=e.startsAtFn==null?void 0:e.startsAtFn(o),s=e.stepsFn==null?[]:e.stepsFn(o),a=i==null?s:[du(i),...s],l=pu(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 m=fu(e.requires,t);return{additionalChecks:[],coverage:e.coverage,description:e.description,expectedOutcome:e.expectedOutcome,implemented:e.implemented,name:e.name,preconditions:m,requiresKeys:{...e.requiresKeys},slug:r,sourcePath:e.sourcePath,spec:l,warnings:c}}function du(e){return Po({type:"goto",url:{type:"static",value:e}}).as(`navigate to ${e}`)}function uu(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 pu(e,t,r,n){let o={};e.forEach((a,l)=>{let c=`step-${String(l)}`,p=l<e.length-1?`step-${String(l+1)}`:void 0;o[c]=mu(a,c,p)});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 mu(e,t,r){let{label:n,node:o}=Ro(e);return{...o,id:t,label:n,next:r}}function fu(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 Jv,WebhookVerificationError as Xv}from"standardwebhooks";import{z as R}from"zod";var Yv=R.object({preconditions:R.array(R.string().min(1))}),Zv=R.object({data:R.record(R.string(),R.record(R.string(),R.string())),preconditions:R.array(R.string().min(1))}),eS=R.object({observer:R.string().min(1).max(200),params:R.record(R.string().max(200),R.union([R.string(),R.number(),R.boolean()]))}),gu=R.discriminatedUnion("kind",[R.object({kind:R.literal("pass")}),R.object({kind:R.literal("retry"),reason:R.string()}),R.object({kind:R.literal("fail"),reason:R.string()})]),tS=R.object({error:R.string().optional(),outcome:gu.optional(),success:R.boolean()});function Le(e){let t=[];return e.tests.forEach(r=>{let n=yu(r),o=i=>{t.push({...i,test:r.slug})};Uu.forEach(i=>{i(n,r,o)})}),{diagnostics:t}}function yu(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 hu(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 wu(e,t,r){Object.keys(t.spec.variables??{}).length>0&&e.forEach(o=>{if(o.type==="fill"&&Co(o.value)){let i=o.value.value;!Eo(i)&&xu(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 bu(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 vu(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 Su(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 ku(e,t,r){let n=0;e.forEach((o,i)=>{if(!(i===0&&o.type==="goto")){if(_e(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 Ru(e,t,r){if(e.length===0)return;let n=e.at(-1);n!=null&&!_e(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 Pu(e,t,r){t.implemented&&e.length===0&&r({message:"Test has zero steps",rule:"no-empty-steps",step:void 0})}function Co(e){return!(typeof e!="object"||e==null||!("type"in e)||e.type!=="static"||!("value"in e)||typeof e.value!="string")}function Eo(e){return e.includes("{{")}function xu(e){return e.includes("@")||/\b[a-f0-9]{8,}\b/.test(e)||/^(test|ripplo|example|sample|demo)/i.test(e)}function _e(e){return e.type.startsWith("assert")}var Cu=new Set(["assertText","assertValue","assertCount","assertUrl","assertNotVisible","assertChecked","assertNotChecked","assertAttribute","assertDisabled","assertEnabled"]);function Eu(e){return Cu.has(e.type)}function Au(e,t,r){!t.implemented||e.length===0||e.some(n=>_e(n))||r({message:"Test has zero assertion steps \u2014 cannot verify expectedOutcome. Add assert.* steps.",rule:"no-assertions",step:void 0})}function Iu(e,t,r){if(!t.implemented||e.length<=3)return;let n=e.filter(i=>_e(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 zr(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 Tu(e,t,r){e.forEach((n,o)=>{if(n.type!=="click")return;let i=zr(n);if(i==null)return;let s=e.slice(o+1,o+4);s.find(c=>c.type==="assertVisible"&&zr(c)===i)==null||s.some(c=>Eu(c)||_e(c)&&zr(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 $u=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 Gr(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=3&&!$u.has(t))}function ju(e){let t=e.label==null?[]:Gr(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,...Gr(n)]}function Nu(e,t,r){if(!t.implemented||e.length===0)return;let n=new Set(Gr(t.expectedOutcome));if(n.size===0)return;let o=e.filter(s=>_e(s));if(o.length===0)return;o.some(s=>ju(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 Ou=/save|submit|create|delete|remove|send|invite|update|confirm|publish|apply|pay|subscribe|upgrade|cancel|archive|rename/i;function xo(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 Ou.test(r)}function Du(e,t,r){!t.implemented||t.spec.uiOnly===!0||e.forEach((n,o)=>{if(!xo(n)||"uiOnly"in n&&n.uiOnly===!0)return;let i=e.slice(o+1),s=i.findIndex(p=>xo(p)),a=s===-1?i.length:s;i.slice(0,a).some(p=>p.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 Lu(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])=>Co(a)&&Eo(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 _u(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(m=>m[1]).filter(m=>m!=null&&!n.has(m)))];if(l.length===0)return;let c=l.map(m=>`{{${m}}}`).join(", "),p=[...new Set(l.map(m=>m.split(".")[0]??m))].join(", ");r({message:`"${i.label??i.id}" contains literal template string(s) ${c} \u2014 destructure the proxy in .steps(({ ${p} }) => \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 Uu=[hu,wu,_u,bu,vu,Su,ku,Ru,Pu,Au,Iu,Tu,Nu,Du,Lu];import cp from"picomatch";import{execFileSync as Vu,spawnSync as Fu}from"child_process";function q(e,t){return Vu("git",[...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}function Ao(e,t){let r=Fu("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 h from"typescript";import*as Io from"remeda";var To=[["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"]],Hu=new Map([["button","click"],["link","navigate"],["textbox","input"],["searchbox","input"],["combobox","select"],["listbox","select"]]),Mu=[[/(?:^|[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 Ut({filePath:e,source:t}){let r=h.createSourceFile(e,t,h.ScriptTarget.Latest,!0,h.ScriptKind.TSX);return r.statements.flatMap(n=>Wu({filePath:e,sf:r,stmt:n}))}function Wu({filePath:e,sf:t,stmt:r}){let n=qu(r);if(n==null||Bu(n))return[];let o=$o(r,t).map(i=>({id:`${e}#${n}.${i.kind}[${i.label}]`,line:i.line}));return Io.uniqueBy(o,i=>i.id)}function Bu(e){return e.endsWith("Fragment")||e.endsWith("Skeleton")||/^use[A-Z]/.test(e)||/^[A-Z][A-Z0-9_]*$/.test(e)}function qu(e){if(h.isExportAssignment(e))return zu(e.expression);if(!Gu(e))return null;if(h.isFunctionDeclaration(e)||h.isClassDeclaration(e))return e.name?.text??null;if(h.isVariableStatement(e)){let t=e.declarationList.declarations[0];return t!=null&&h.isIdentifier(t.name)?t.name.text:null}return null}function zu(e){return h.isIdentifier(e)?e.text:(h.isFunctionExpression(e)||h.isClassExpression(e))&&e.name!=null?e.name.text:"default"}function Gu(e){if(!h.canHaveModifiers(e))return!1;let t=h.getModifiers(e);return t!=null&&t.some(r=>r.kind===h.SyntaxKind.ExportKeyword)}function $o(e,t){let r=Ku(e,t),n=e.getChildren(t).flatMap(o=>$o(o,t));return r==null?n:[r,...n]}function Ku(e,t){let r=Ju(e);if(r==null)return null;let n=Xu(r);if(n==null)return null;let o=tp(r,n);return o==null?null:{kind:n,label:o,line:lp(t,e.getStart(t))}}function Ju(e){return h.isJsxSelfClosingElement(e)&&h.isIdentifier(e.tagName)?{attrs:e.attributes,children:[],tag:e.tagName.text}:h.isJsxElement(e)&&h.isIdentifier(e.openingElement.tagName)?{attrs:e.openingElement.attributes,children:e.children,tag:e.openingElement.tagName.text}:null}function Xu({attrs:e,tag:t}){let r=de(e,"role");return r!=null?Hu.get(r)??null:Yu(t,e)??Zu(t)??ep(e)}var Qu=new Map([["button",()=>"click"],["a",e=>de(e,"href")==null?null:"navigate"],["input",e=>de(e,"type")==="file"?"upload":"input"],["textarea",()=>"input"],["select",()=>"select"],["form",()=>"submit"]]);function Yu(e,t){return Qu.get(e)?.(t)??null}function Zu(e){return/^[A-Z]/.test(e)?Mu.find(([t])=>t.test(e))?.[1]??null:null}function ep(e){return To.find(([t])=>op(e,t))?.[1]??null}function tp({attrs:e,children:t,tag:r},n){return n==="navigate"?de(e,"href")??de(e,"to"):de(e,"aria-label")??de(e,"label")??de(e,"title")??de(e,"name")??de(e,"placeholder")??(rp(r)?void 0:ap(t))??np(e,n)}function rp(e){return e==="input"||e==="textarea"||e==="select"}function np(e,t){let r=To.find(([,o])=>o===t)?.[0];if(r==null)return;let n=ip(e,r);if(n!=null){if(h.isIdentifier(n))return n.text;if(h.isArrowFunction(n)||h.isFunctionExpression(n))return jo(n.body)}}function jo(e){if(h.isCallExpression(e)){let t=e.expression;return h.isIdentifier(t)?t.text:h.isPropertyAccessExpression(t)?t.name.text:void 0}return h.forEachChild(e,jo)}function op(e,t){return e.properties.some(r=>h.isJsxAttribute(r)&&h.isIdentifier(r.name)&&r.name.text===t)}function No(e,t){return e.properties.find(r=>h.isJsxAttribute(r)&&h.isIdentifier(r.name)&&r.name.text===t)}function de(e,t){let r=No(e,t);return r==null?void 0:sp(r.initializer)}function ip(e,t){let r=No(e,t);if(!(r?.initializer==null||!h.isJsxExpression(r.initializer)))return r.initializer.expression}function sp(e){if(e==null)return"";if(h.isStringLiteral(e))return e.text;if(h.isJsxExpression(e))return Do(e.expression)}function ap(e){let t=e.flatMap(r=>Oo(r)).join(" ").trim();return t.length===0?void 0:t}function Oo(e){if(h.isJsxText(e)){let t=e.text.trim();return t.length===0?[]:[t]}if(h.isJsxExpression(e)){let t=Do(e.expression);return t==null?[]:[t]}return h.isJsxElement(e)?e.children.flatMap(t=>Oo(t)):[]}function Do(e){if(e!=null){if(h.isStringLiteral(e)||h.isNoSubstitutionTemplateLiteral(e))return e.text;if(h.isCallExpression(e)&&e.arguments.length===1){let t=e.arguments[0];if(t!=null&&(h.isStringLiteral(t)||h.isNoSubstitutionTemplateLiteral(t)))return t.text}}}function lp(e,t){return e.getLineAndCharacterOfPosition(t).line+1}var dp=Vt.join(".ripplo","coverage.d.ts");function Ue({cwd:e}){up({cwd:e,ignorePaths:ke})}function up({cwd:e,ignorePaths:t}){let r=Ve({cwd:e,ignorePaths:t});fp({content:mp(r),cwd:e})}function Ve({cwd:e,ignorePaths:t}){let n=pp({cwd:e,ignorePaths:t}).flatMap(o=>Kr({cwd:e,file:o}));return[...new Set(n)].sort((o,i)=>o.localeCompare(i))}function pp({cwd:e,ignorePaths:t}){let r=q(["ls-files","--cached","--others","--exclude-standard","-z"],e),n=cp([...t]);return r.split("\0").filter(o=>o.length>0&&/\.(tsx|jsx)$/.test(o)).filter(o=>!n(o)).filter(o=>ot.existsSync(Vt.join(e,o)))}function Kr({cwd:e,file:t}){let r=ot.readFileSync(Vt.join(e,t),"utf8");return Ut({filePath:t,source:r}).map(n=>n.id)}function mp(e){let t=`// GENERATED \u2014 do not edit
173
+ `)}import Hr from"fs/promises";import Mr from"path";import{z as Nt}from"zod";import{z as go}from"zod";import{z as _e}from"zod";import{z as u}from"zod";import{z as ke}from"zod";import{z as vo}from"zod";import{z as I}from"zod";import{z as Y}from"zod";import{z as Fr}from"zod";import{z as L}from"zod";var Qc=Nt.object({__codec:Nt.string().min(1),data:Nt.unknown(),version:Nt.number().int().positive()}),Yc=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}},Zc=class extends Error{constructor(e){super(`Codec mismatch: expected "${e.expected}", got "${e.got}"`),this.name="CodecMismatchError"}};function qr(e){return ho({legacy:void 0,migrators:[],name:e,schemas:[]})}function ed(e,t){let r=JSON.parse(t);return e.decode(r)}function ho(e){return{initial:t=>Wr(t,{...e,schemas:[t]}),legacy:t=>ho({...e,legacy:t})}}function Wr(e,t){return{build:()=>td(e,t),legacy:r=>Wr(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return Wr(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function td(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>rd(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function rd(e,t,r){let{data:n,version:o}=nd(t,r),i=wo(t,n,o);return e.parse(i)}function nd(e,t){let r=Qc.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new Zc({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 wo(e,t,r){let n=e.schemas.length;if(r>n)throw new Yc({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 wo(e,s(i),r+1)}var bo=_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."),od=ke.object({by:ke.literal("testId"),value:ke.string().min(1)}),id=ke.object({by:ke.literal("role"),name:ke.string().optional(),role:ke.string().min(1)}),P=ke.discriminatedUnion("by",[od,id]),ot=vo.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),sd=vo.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]),ad=I.object({type:I.literal("static"),value:I.union([I.string(),I.number(),I.boolean()])}),Ot=I.object({name:I.string().min(1),type:I.literal("variable")}),ld=I.discriminatedUnion("type",[ad,Ot]),ae=I.discriminatedUnion("type",[I.object({type:I.literal("static"),value:I.string()}),Ot]),cd=I.discriminatedUnion("type",[I.object({type:I.literal("static"),value:I.number().int().nonnegative()}),Ot]),dd=I.discriminatedUnion("type",[I.object({type:I.literal("static"),value:I.union([I.string(),I.number(),I.boolean()])}),Ot]),ud=Y.discriminatedUnion("type",[Y.object({default:Y.string().optional(),type:Y.literal("string")}),Y.object({default:Y.number().optional(),type:Y.literal("number")}),Y.object({default:Y.boolean().optional(),type:Y.literal("boolean")}),Y.object({key:Y.string().min(1),type:Y.literal("env")})]),v={id:u.string().min(1).max(200),label:u.string().max(500).optional(),next:u.string().max(200).optional(),uiOnly:u.boolean().optional()},yo=500,pd=u.object({...v,type:u.literal("goto"),url:ae}),md=u.object({...v,locator:P,type:u.literal("click")}),fd=u.object({...v,locator:P,type:u.literal("fill"),value:ae}),gd=u.object({...v,locator:P,type:u.literal("select"),value:ae}),yd=u.object({...v,locator:P,type:u.literal("hover")}),hd=u.object({...v,key:u.string().min(1),locator:P.optional(),type:u.literal("press")}),wd=u.object({...v,locator:P,type:u.literal("check")}),bd=u.object({...v,locator:P,type:u.literal("uncheck")}),vd=u.object({...v,height:u.number().int().positive(),type:u.literal("setViewport"),width:u.number().int().positive()}),kd=u.object({...v,message:u.string().min(1),type:u.literal("fail")}),Sd=u.object({...v,type:u.literal("setVariable"),value:ld,variable:u.string().min(1)}),Rd=u.object({...v,locator:P,type:u.literal("extractText"),variable:u.string().min(1)}),Pd=u.object({...v,files:u.array(u.string()).min(1),locator:P,type:u.literal("upload")}),xd=u.object({...v,locator:P,type:u.literal("dblclick")}),Cd=u.object({...v,source:P,target:P,type:u.literal("drag")}),Ed=u.object({...v,locator:P,type:u.literal("scrollIntoView")}),Ad=u.object({...v,locator:P,type:u.literal("type"),value:ae}),Id=u.object({...v,locator:P,type:u.literal("focus")}),$d=u.object({...v,locator:P,type:u.literal("clear")}),Td=u.object({...v,locator:P,type:u.literal("rightClick")}),jd=u.object({...v,action:u.enum(["accept","dismiss"]),promptText:u.string().optional(),type:u.literal("handleDialog")}),Nd=u.object({...v,action:u.enum(["read","write"]),type:u.literal("clipboard"),value:ae.optional(),variable:u.string().min(1).optional()}),Od=u.object({...v,permission:u.string().min(1),state:u.enum(["granted","prompt"]),type:u.literal("setPermission")}),Dd=u.object({...v,locator:P,type:u.literal("assertVisible")}),Ld=u.object({...v,locator:P,type:u.literal("assertNotVisible")}),_d=u.object({...v,expected:ae,locator:P,operator:ot,type:u.literal("assertText")}),Ud=u.object({...v,expected:ae,operator:ot,type:u.literal("assertUrl")}),Vd=u.object({...v,expected:cd,locator:P,operator:sd,type:u.literal("assertCount")}),Fd=u.object({...v,expected:ae,locator:P,operator:ot,type:u.literal("assertValue")}),Hd=u.object({...v,attribute:u.string().min(1),expected:ae,locator:P,operator:ot,type:u.literal("assertAttribute")}),Md=u.object({...v,locator:P,type:u.literal("assertEnabled")}),Wd=u.object({...v,locator:P,type:u.literal("assertDisabled")}),Bd=u.object({...v,expected:ae,operator:ot,type:u.literal("assertTitle")}),qd=u.object({...v,locator:P,type:u.literal("assertChecked")}),zd=u.object({...v,locator:P,type:u.literal("assertNotChecked")}),Gd=u.object({...v,locator:P,type:u.literal("assertFocused")}),Kd=u.object({...v,locator:P,type:u.literal("assertNotFocused")}),Jd=u.object({...v,budget:u.enum(["fast","slow","async"]),observer:u.string().min(1).max(200),params:u.record(u.string().max(200),dd),type:u.literal("assertObserver")}),Xd=u.discriminatedUnion("type",[pd,md,fd,gd,yd,hd,wd,bd,Dd,Ld,_d,Ud,Vd,Fd,Hd,Md,Wd,vd,kd,Sd,Rd,Pd,xd,Cd,Ed,Ad,Id,$d,Td,jd,Nd,Od,Bd,qd,zd,Gd,Kd,Jd]),ko=u.object({entryNode:u.string().min(1).max(200),nodes:u.record(u.string().max(200),Xd).refine(e=>Object.keys(e).length<=yo,`Workflow has more than ${String(yo)} nodes`),uiOnly:u.boolean().optional(),variableNamespaces:u.record(u.string().max(200),u.string().max(500)).optional(),variables:u.record(u.string().max(200),ud).optional()}),Qd=go.record(go.string().max(200),bo),Yd={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)},Fv=qr("workflow-spec").legacy(Yd).initial(ko).build(),Hv=qr("precondition-map").legacy(Zd).initial(Qd).build(),eu=["fast","slow","async"],tu=Fr.object({budget:Fr.enum(eu).describe("Polling budget tier: fast | slow | async"),description:Fr.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."),le=".ripplo/ripplo.lock",ru=5e3,nu=L.record(L.string().max(200),L.string().max(200)),ou=L.object({coverage:L.array(L.string().max(500)).max(2e3).default([]),expectedOutcome:L.string().max(2e3),name:L.string().max(200),preconditions:L.array(L.string().max(200)).max(1e3),requiresKeys:nu,slug:L.string().max(200),sourcePath:L.string().max(500).optional(),spec:ko}),iu=L.object({observers:L.record(L.string().max(200),tu),preconditions:L.record(L.string().max(200),bo),tests:L.array(ou).max(ru)}),So=qr("ripplo-lockfile").initial(iu).build();function Ro(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,sourcePath:t.sourcePath,spec:t.spec}))}}function Br(e){let t=So.encode(e);return`${JSON.stringify(t,lu(t),2)}
174
+ `}async function Dt({cwd:e}){let t=Mr.join(e,le),r=await su(t);return r==null?null:ed(So,r)}async function ce({cwd:e,result:t}){let r=Ro(t),n=Mr.join(e,le);await Hr.mkdir(Mr.dirname(n),{recursive:!0}),await Hr.writeFile(n,Br(r),"utf8")}function Lt({compiled:e,existing:t}){if(t==null)return"missing";let r=Br(Ro(e)),n=Br(t);return r===n?"match":"stale"}async function su(e){try{return await Hr.readFile(e,"utf8")}catch(t){if(au(t)&&t.code==="ENOENT")return null;throw t}}function au(e){return e instanceof Error&&"code"in e}function lu(e){return function(r,n){return n===e||!cu(n)?n:Object.fromEntries(Object.entries(n).toSorted(([o],[i])=>o.localeCompare(i)))}}function cu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import it from"fs";import Vt from"path";var zr=["**/src/**","**/app/**","**/apps/**","**/pages/**","**/routes/**","**/components/**","**/server/**","**/api/**","**/backend/**","**/features/**","**/modules/**","**/views/**","**/ui/**","**/hooks/**","**/contexts/**","**/providers/**","**/controllers/**","**/handlers/**","**/resolvers/**","**/services/**","**/middleware/**","**/lib/**"],Se=["**/*.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 Po(e){return e.data}function xo(e){return{as(t){return{data:{label:t,node:e}}}}}function _t(e){let t=e.getPreconditions(),r=e.getObservers(),n=e.getTests();du(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=>uu(a,t));return{observers:i,preconditions:o,tests:s}}function du(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 uu(e,t){let r=e.id,{accessedKeys:n,vars:o}=mu(e.requiresKeys),i=e.startsAtFn==null?void 0:e.startsAtFn(o),s=e.stepsFn==null?[]:e.stepsFn(o),a=i==null?s:[pu(i),...s],l=fu(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 m=yu(e.requires,t);return{additionalChecks:[],coverage:e.coverage,description:e.description,expectedOutcome:e.expectedOutcome,implemented:e.implemented,name:e.name,preconditions:m,requiresKeys:{...e.requiresKeys},slug:r,sourcePath:e.sourcePath,spec:l,warnings:c}}function pu(e){return xo({type:"goto",url:{type:"static",value:e}}).as(`navigate to ${e}`)}function mu(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 fu(e,t,r,n){let o={};e.forEach((a,l)=>{let c=`step-${String(l)}`,p=l<e.length-1?`step-${String(l+1)}`:void 0;o[c]=gu(a,c,p)});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 gu(e,t,r){let{label:n,node:o}=Po(e);return{...o,id:t,label:n,next:r}}function yu(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 Yv,WebhookVerificationError as Zv}from"standardwebhooks";import{z as k}from"zod";var tk=k.object({preconditions:k.array(k.string().min(1))}),rk=k.object({data:k.record(k.string(),k.record(k.string(),k.union([k.string(),k.number(),k.boolean()]))),preconditions:k.array(k.string().min(1))}),nk=k.object({observer:k.string().min(1).max(200),params:k.record(k.string().max(200),k.union([k.string(),k.number(),k.boolean()]))}),hu=k.discriminatedUnion("kind",[k.object({kind:k.literal("pass")}),k.object({kind:k.literal("retry"),reason:k.string()}),k.object({kind:k.literal("fail"),reason:k.string()})]),ok=k.object({error:k.string().optional(),outcome:hu.optional(),success:k.boolean()});function Ue(e){let t=[];return e.tests.forEach(r=>{let n=wu(r),o=i=>{t.push({...i,test:r.slug})};Fu.forEach(i=>{i(n,r,o)})}),{diagnostics:t}}function wu(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 bu(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 vu(e,t,r){Object.keys(t.spec.variables??{}).length>0&&e.forEach(o=>{if(o.type==="fill"&&Eo(o.value)){let i=o.value.value;!Ao(i)&&Eu(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 ku(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 Su(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 Ru(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 Pu(e,t,r){let n=0;e.forEach((o,i)=>{if(!(i===0&&o.type==="goto")){if(Ve(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 xu(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 Cu(e,t,r){t.implemented&&e.length===0&&r({message:"Test has zero steps",rule:"no-empty-steps",step:void 0})}function Eo(e){return!(typeof e!="object"||e==null||!("type"in e)||e.type!=="static"||!("value"in e)||typeof e.value!="string")}function Ao(e){return e.includes("{{")}function Eu(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 Au=new Set(["assertText","assertValue","assertCount","assertUrl","assertNotVisible","assertChecked","assertNotChecked","assertAttribute","assertDisabled","assertEnabled"]);function Iu(e){return Au.has(e.type)}function $u(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 Tu(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 Gr(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 ju(e,t,r){e.forEach((n,o)=>{if(n.type!=="click")return;let i=Gr(n);if(i==null)return;let s=e.slice(o+1,o+4);s.find(c=>c.type==="assertVisible"&&Gr(c)===i)==null||s.some(c=>Iu(c)||Ve(c)&&Gr(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 Nu=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 Kr(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=3&&!Nu.has(t))}function Ou(e){let t=e.label==null?[]:Kr(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,...Kr(n)]}function Du(e,t,r){if(!t.implemented||e.length===0)return;let n=new Set(Kr(t.expectedOutcome));if(n.size===0)return;let o=e.filter(s=>Ve(s));if(o.length===0)return;o.some(s=>Ou(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 Lu=/save|submit|create|delete|remove|send|invite|update|confirm|publish|apply|pay|subscribe|upgrade|cancel|archive|rename/i;function Co(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 Lu.test(r)}function _u(e,t,r){!t.implemented||t.spec.uiOnly===!0||e.forEach((n,o)=>{if(!Co(n)||"uiOnly"in n&&n.uiOnly===!0)return;let i=e.slice(o+1),s=i.findIndex(p=>Co(p)),a=s===-1?i.length:s;i.slice(0,a).some(p=>p.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 Uu(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])=>Eo(a)&&Ao(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 Vu(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(m=>m[1]).filter(m=>m!=null&&!n.has(m)))];if(l.length===0)return;let c=l.map(m=>`{{${m}}}`).join(", "),p=[...new Set(l.map(m=>m.split(".")[0]??m))].join(", ");r({message:`"${i.label??i.id}" contains literal template string(s) ${c} \u2014 destructure the proxy in .steps(({ ${p} }) => \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 Fu=[bu,vu,Vu,ku,Su,Ru,Pu,xu,Cu,$u,Tu,ju,Du,_u,Uu];import up from"picomatch";import{execFileSync as Hu,spawnSync as Mu}from"child_process";function z(e,t){return Hu("git",[...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}function Io(e,t){let r=Mu("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 h from"typescript";import*as $o from"remeda";var To=[["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"]],Wu=new Map([["button","click"],["link","navigate"],["textbox","input"],["searchbox","input"],["combobox","select"],["listbox","select"]]),Bu=[[/(?:^|[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 Ut({filePath:e,source:t}){let r=h.createSourceFile(e,t,h.ScriptTarget.Latest,!0,h.ScriptKind.TSX);return r.statements.flatMap(n=>qu({filePath:e,sf:r,stmt:n}))}function qu({filePath:e,sf:t,stmt:r}){let n=Gu(r);if(n==null||zu(n))return[];let o=jo(r,t).map(i=>({id:`${e}#${n}.${i.kind}[${i.label}]`,line:i.line}));return $o.uniqueBy(o,i=>i.id)}function zu(e){return e.endsWith("Fragment")||e.endsWith("Skeleton")||/^use[A-Z]/.test(e)||/^[A-Z][A-Z0-9_]*$/.test(e)}function Gu(e){if(h.isExportAssignment(e))return Ku(e.expression);if(!Ju(e))return null;if(h.isFunctionDeclaration(e)||h.isClassDeclaration(e))return e.name?.text??null;if(h.isVariableStatement(e)){let t=e.declarationList.declarations[0];return t!=null&&h.isIdentifier(t.name)?t.name.text:null}return null}function Ku(e){return h.isIdentifier(e)?e.text:(h.isFunctionExpression(e)||h.isClassExpression(e))&&e.name!=null?e.name.text:"default"}function Ju(e){if(!h.canHaveModifiers(e))return!1;let t=h.getModifiers(e);return t!=null&&t.some(r=>r.kind===h.SyntaxKind.ExportKeyword)}function jo(e,t){let r=Xu(e,t),n=e.getChildren(t).flatMap(o=>jo(o,t));return r==null?n:[r,...n]}function Xu(e,t){let r=Qu(e);if(r==null)return null;let n=Yu(r);if(n==null)return null;let o=np(r,n);return o==null?null:{kind:n,label:o,line:dp(t,e.getStart(t))}}function Qu(e){return h.isJsxSelfClosingElement(e)&&h.isIdentifier(e.tagName)?{attrs:e.attributes,children:[],tag:e.tagName.text}:h.isJsxElement(e)&&h.isIdentifier(e.openingElement.tagName)?{attrs:e.openingElement.attributes,children:e.children,tag:e.openingElement.tagName.text}:null}function Yu({attrs:e,tag:t}){let r=de(e,"role");return r!=null?Wu.get(r)??null:ep(t,e)??tp(t)??rp(e)}var Zu=new Map([["button",()=>"click"],["a",e=>de(e,"href")==null?null:"navigate"],["input",e=>de(e,"type")==="file"?"upload":"input"],["textarea",()=>"input"],["select",()=>"select"],["form",()=>"submit"]]);function ep(e,t){return Zu.get(e)?.(t)??null}function tp(e){return/^[A-Z]/.test(e)?Bu.find(([t])=>t.test(e))?.[1]??null:null}function rp(e){return To.find(([t])=>sp(e,t))?.[1]??null}function np({attrs:e,children:t,tag:r},n){return n==="navigate"?de(e,"href")??de(e,"to"):de(e,"aria-label")??de(e,"label")??de(e,"title")??de(e,"name")??de(e,"placeholder")??(op(r)?void 0:cp(t))??ip(e,n)}function op(e){return e==="input"||e==="textarea"||e==="select"}function ip(e,t){let r=To.find(([,o])=>o===t)?.[0];if(r==null)return;let n=ap(e,r);if(n!=null){if(h.isIdentifier(n))return n.text;if(h.isArrowFunction(n)||h.isFunctionExpression(n))return No(n.body)}}function No(e){if(h.isCallExpression(e)){let t=e.expression;return h.isIdentifier(t)?t.text:h.isPropertyAccessExpression(t)?t.name.text:void 0}return h.forEachChild(e,No)}function sp(e,t){return e.properties.some(r=>h.isJsxAttribute(r)&&h.isIdentifier(r.name)&&r.name.text===t)}function Oo(e,t){return e.properties.find(r=>h.isJsxAttribute(r)&&h.isIdentifier(r.name)&&r.name.text===t)}function de(e,t){let r=Oo(e,t);return r==null?void 0:lp(r.initializer)}function ap(e,t){let r=Oo(e,t);if(!(r?.initializer==null||!h.isJsxExpression(r.initializer)))return r.initializer.expression}function lp(e){if(e==null)return"";if(h.isStringLiteral(e))return e.text;if(h.isJsxExpression(e))return Lo(e.expression)}function cp(e){let t=e.flatMap(r=>Do(r)).join(" ").trim();return t.length===0?void 0:t}function Do(e){if(h.isJsxText(e)){let t=e.text.trim();return t.length===0?[]:[t]}if(h.isJsxExpression(e)){let t=Lo(e.expression);return t==null?[]:[t]}return h.isJsxElement(e)?e.children.flatMap(t=>Do(t)):[]}function Lo(e){if(e!=null){if(h.isStringLiteral(e)||h.isNoSubstitutionTemplateLiteral(e))return e.text;if(h.isCallExpression(e)&&e.arguments.length===1){let t=e.arguments[0];if(t!=null&&(h.isStringLiteral(t)||h.isNoSubstitutionTemplateLiteral(t)))return t.text}}}function dp(e,t){return e.getLineAndCharacterOfPosition(t).line+1}var pp=Vt.join(".ripplo","coverage.d.ts");function Fe({cwd:e}){mp({cwd:e,ignorePaths:Se})}function mp({cwd:e,ignorePaths:t}){let r=He({cwd:e,ignorePaths:t});yp({content:gp(r),cwd:e})}function He({cwd:e,ignorePaths:t}){let n=fp({cwd:e,ignorePaths:t}).flatMap(o=>Jr({cwd:e,file:o}));return[...new Set(n)].sort((o,i)=>o.localeCompare(i))}function fp({cwd:e,ignorePaths:t}){let r=z(["ls-files","--cached","--others","--exclude-standard","-z"],e),n=up([...t]);return r.split("\0").filter(o=>o.length>0&&/\.(tsx|jsx)$/.test(o)).filter(o=>!n(o)).filter(o=>it.existsSync(Vt.join(e,o)))}function Jr({cwd:e,file:t}){let r=it.readFileSync(Vt.join(e,t),"utf8");return Ut({filePath:t,source:r}).map(n=>n.id)}function gp(e){let t=`// GENERATED \u2014 do not edit
175
175
  import "@ripplo/testing";
176
176
 
177
177
  declare module "@ripplo/testing" {
@@ -182,22 +182,22 @@ declare module "@ripplo/testing" {
182
182
  `:`${t}${r}
183
183
  }
184
184
  }
185
- `}function fp({content:e,cwd:t}){let r=Vt.join(t,dp);ot.existsSync(r)&&ot.readFileSync(r,"utf8")===e||ot.writeFileSync(r,e)}import Lo from"path";import{createJiti as gp}from"jiti";var yp=["getObservers","getPreconditions","getTests","getUnimplemented"];function hp(e){return e==null||typeof e!="object"?!1:yp.every(t=>typeof Reflect.get(e,t)=="function")}function wp(e){return e===null?"null":Array.isArray(e)?"array":typeof e}async function C(e){let t=Lo.join(e,".ripplo","index.ts"),r=Lo.join(e,".ripplo");try{let o=await gp(import.meta.url,{moduleCache:!1,sourceMaps:!0}).import(t),i=o!=null&&typeof o=="object"&&"default"in o?Reflect.get(o,"default"):o;if(!hp(i))return{error:`${t} must default-export a RipploBuilder (got ${wp(i)})`,ok:!1};let s=_t(i);return{builder:i,ok:!0,result:s}}catch(n){return{error:vp(n,r),ok:!1}}}var bp=/\(?([^\s()]{1,500}\.ts):(\d{1,10}):(\d{1,10})\)?$/;function vp(e,t){if(!(e instanceof Error))return String(e);let r=Sp(e.stack,t);return r==null?e.message:`${r} \u2014 ${e.message}`}function Sp(e,t){if(e==null)return;let n=e.split(`
186
- `).map(a=>bp.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 w(e,t){return t==null?`Load \`/ripplo:${e}\` skill for instructions.`:`Load \`/ripplo:${e}\` skill for instructions on ${t}.`}function _o(e){return e.length===1?w(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 Uo(e){let t=process.cwd(),r=await C(t);if(r.ok||(process.stderr.write(`Compilation failed: ${r.error}
185
+ `}function yp({content:e,cwd:t}){let r=Vt.join(t,pp);it.existsSync(r)&&it.readFileSync(r,"utf8")===e||it.writeFileSync(r,e)}import _o from"path";import{createJiti as hp}from"jiti";var wp=["getObservers","getPreconditions","getTests","getUnimplemented"];function bp(e){return e==null||typeof e!="object"?!1:wp.every(t=>typeof Reflect.get(e,t)=="function")}function vp(e){return e===null?"null":Array.isArray(e)?"array":typeof e}async function C(e){let t=_o.join(e,".ripplo","index.ts"),r=_o.join(e,".ripplo");try{let o=await hp(import.meta.url,{moduleCache:!1,sourceMaps:!0}).import(t),i=o!=null&&typeof o=="object"&&"default"in o?Reflect.get(o,"default"):o;if(!bp(i))return{error:`${t} must default-export a RipploBuilder (got ${vp(i)})`,ok:!1};let s=_t(i);return{builder:i,ok:!0,result:s}}catch(n){return{error:Sp(n,r),ok:!1}}}var kp=/\(?([^\s()]{1,500}\.ts):(\d{1,10}):(\d{1,10})\)?$/;function Sp(e,t){if(!(e instanceof Error))return String(e);let r=Rp(e.stack,t);return r==null?e.message:`${r} \u2014 ${e.message}`}function Rp(e,t){if(e==null)return;let n=e.split(`
186
+ `).map(a=>kp.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 w(e,t){return t==null?`Load \`/ripplo:${e}\` skill for instructions.`:`Load \`/ripplo:${e}\` skill for instructions on ${t}.`}function Uo(e){return e.length===1?w(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 Vo(e){let t=process.cwd(),r=await C(t);if(r.ok||(process.stderr.write(`Compilation failed: ${r.error}
187
187
  `),process.stderr.write(`${w("create","DSL authoring + lint rules")}
188
188
  `),process.exit(1)),e.check){let n=await Dt({cwd:t}),o=Lt({compiled:r.result,existing:n});if(o==="match"){process.stdout.write(`${le} is up to date
189
189
  `);return}let i=o==="missing"?"missing":"out of date";process.stderr.write(`${le} is ${i} \u2014 run \`ripplo compile\` and commit the result
190
190
  `),process.stderr.write(`${w("setup")}
191
- `),process.exit(1)}await ce({cwd:t,result:r.result}),Ue({cwd:t}),process.stdout.write(`wrote ${le}
192
- `)}import pe from"process";import kp from"fs";import Rp from"path";import Pp from"picomatch";function Vo({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(Ve({cwd:t,ignorePaths:r})),o=Mo(e),i=xp({cwd:t,ignorePaths:r});return Ho({acknowledged:o,allStatements:n,unacked:i})}function Fo({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(Ve({cwd:t,ignorePaths:r})),o=Mo(e);return Ho({acknowledged:o,allStatements:n,unacked:n})}function Ho({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 Mo(e){return new Set(e.tests.flatMap(t=>t.coverage))}function xp({cwd:e,ignorePaths:t}){let r=Cp({cwd:e,ignorePaths:t}),n=new Set(r.flatMap(i=>Ep({cwd:e,file:i}))),o=new Set(r.flatMap(i=>Ap({cwd:e,file:i})?Kr({cwd:e,file:i}):[]));return new Set([...o].filter(i=>!n.has(i)))}function Cp({cwd:e,ignorePaths:t}){let r=q(["diff","--name-only","HEAD","-z"],e),n=q(["ls-files","--others","--exclude-standard","-z"],e),o=Pp([...t]);return[...new Set([...r.split("\0"),...n.split("\0")])].filter(i=>i.length>0&&/\.(tsx|jsx)$/.test(i)).filter(i=>!o(i))}function Ep({cwd:e,file:t}){let r=Ao(`HEAD:${t}`,e);return r==null?[]:Ut({filePath:t,source:r}).map(n=>n.id)}function Ap({cwd:e,file:t}){return kp.existsSync(Rp.join(e,t))}async function Wo(){let e=pe.cwd(),t=await C(e);t.ok||(pe.stderr.write(`Compilation failed: ${t.error}
193
- `),pe.exit(1));let r=Ve({cwd:e,ignorePaths:ke}),n=Fo({compileResult:t.result,cwd:e,ignorePaths:ke}),o=n.filter(a=>a.kind==="unacknowledged"),i=n.filter(a=>a.kind==="stale"),s=r.length-o.length;pe.stdout.write(`Coverage: ${String(s)}/${String(r.length)} statements acknowledged
191
+ `),process.exit(1)}await ce({cwd:t,result:r.result}),Fe({cwd:t}),process.stdout.write(`wrote ${le}
192
+ `)}import pe from"process";import Pp from"fs";import xp from"path";import Cp from"picomatch";function Fo({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(He({cwd:t,ignorePaths:r})),o=Wo(e),i=Ep({cwd:t,ignorePaths:r});return Mo({acknowledged:o,allStatements:n,unacked:i})}function Ho({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(He({cwd:t,ignorePaths:r})),o=Wo(e);return Mo({acknowledged:o,allStatements:n,unacked:n})}function Mo({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 Wo(e){return new Set(e.tests.flatMap(t=>t.coverage))}function Ep({cwd:e,ignorePaths:t}){let r=Ap({cwd:e,ignorePaths:t}),n=new Set(r.flatMap(i=>Ip({cwd:e,file:i}))),o=new Set(r.flatMap(i=>$p({cwd:e,file:i})?Jr({cwd:e,file:i}):[]));return new Set([...o].filter(i=>!n.has(i)))}function Ap({cwd:e,ignorePaths:t}){let r=z(["diff","--name-only","HEAD","-z"],e),n=z(["ls-files","--others","--exclude-standard","-z"],e),o=Cp([...t]);return[...new Set([...r.split("\0"),...n.split("\0")])].filter(i=>i.length>0&&/\.(tsx|jsx)$/.test(i)).filter(i=>!o(i))}function Ip({cwd:e,file:t}){let r=Io(`HEAD:${t}`,e);return r==null?[]:Ut({filePath:t,source:r}).map(n=>n.id)}function $p({cwd:e,file:t}){return Pp.existsSync(xp.join(e,t))}async function Bo(){let e=pe.cwd(),t=await C(e);t.ok||(pe.stderr.write(`Compilation failed: ${t.error}
193
+ `),pe.exit(1));let r=He({cwd:e,ignorePaths:Se}),n=Ho({compileResult:t.result,cwd:e,ignorePaths:Se}),o=n.filter(a=>a.kind==="unacknowledged"),i=n.filter(a=>a.kind==="stale"),s=r.length-o.length;pe.stdout.write(`Coverage: ${String(s)}/${String(r.length)} statements acknowledged
194
194
  `),o.length>0&&(pe.stdout.write(`
195
195
  Unacknowledged (${String(o.length)}):
196
196
  `),o.forEach(a=>pe.stdout.write(` ${a.id}
197
197
  `))),i.length>0&&(pe.stdout.write(`
198
198
  Stale claims (${String(i.length)}):
199
199
  `),i.forEach(a=>pe.stdout.write(` ${a.id}
200
- `))),n.length>0&&pe.exit(1)}import{graphql as Tp}from"gql.tada";import Bo from"fs";import Jr from"path";function qo(e){let t=Bo.realpathSync(e),r=t,n=Jr.dirname(r);for(;n!==r;){if(Bo.existsSync(Jr.join(r,".git")))return r;r=n,n=Jr.dirname(r)}return t}function _(e){let t=tr(e),r=Ae(),n=ee();if(n==null)throw new Error("ripplo: not authenticated. Run `ripplo auth login`.");return{appUrl:r.appUrl,cwd:qo(e),engineUrl:r.engineUrl,projectId:ao()??t.projectId,ripploServerUrl:Q(),token:n,webhookSecret:r.webhookSecret}}import it from"fs";var Ip="dev.pid";function zo(e){return tt(e,Ip)}function Fe(e){let t=zo(e);if(!it.existsSync(t))return!1;let r=it.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 Go(e){et(e);let t=zo(e);it.writeFileSync(t,String(process.pid));let r=!1;return()=>{if(!r){r=!0;try{let n=it.readFileSync(t,"utf8").trim();Number.parseInt(n,10)===process.pid&&it.unlinkSync(t)}catch{}}}}var $p=Tp(`
200
+ `))),n.length>0&&pe.exit(1)}import{graphql as jp}from"gql.tada";import qo from"fs";import Xr from"path";function zo(e){let t=qo.realpathSync(e),r=t,n=Xr.dirname(r);for(;n!==r;){if(qo.existsSync(Xr.join(r,".git")))return r;r=n,n=Xr.dirname(r)}return t}function _(e){let t=rr(e),r=$e(),n=ee();if(n==null)throw new Error("ripplo: not authenticated. Run `ripplo auth login`.");return{appUrl:r.appUrl,cwd:zo(e),engineUrl:r.engineUrl,projectId:lo()??t.projectId,ripploServerUrl:Q(),token:n,webhookSecret:r.webhookSecret}}import st from"fs";var Tp="dev.pid";function Go(e){return rt(e,Tp)}function Me(e){let t=Go(e);if(!st.existsSync(t))return!1;let r=st.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 Ko(e){tt(e);let t=Go(e);st.writeFileSync(t,String(process.pid));let r=!1;return()=>{if(!r){r=!0;try{let n=st.readFileSync(t,"utf8").trim();Number.parseInt(n,10)===process.pid&&st.unlinkSync(t)}catch{}}}}var Np=jp(`
201
201
  query DevSessionCheckHealth($projectId: String!, $cwd: String!) {
202
202
  project(id: $projectId) {
203
203
  id
@@ -206,25 +206,26 @@ Stale claims (${String(i.length)}):
206
206
  }
207
207
  }
208
208
  }
209
- `);function Ko(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 Jo(e){let t=Fe(e),r;try{r=_(e)}catch{return{status:t?"starting":"missing",type:"dev-session"}}return(await g({config:r,document:$p,variables:{cwd:r.cwd,projectId:r.projectId}}).catch(()=>null))?.project?.devSession!=null?{status:"active",type:"dev-session"}:{status:t?"starting":"missing",type:"dev-session"}}function Xo(e){switch(e.type){case"settings":return Dp(e);case"env-files":return Lp(e);case"token":return _p(e);case"dev-server":return Up(e);case"dev-session":return Ko(e);case"preconditions":return Hp(e);case"webhook-verification":return Vp(e);case"preconditions-validation":return Mp(e);case"workflows":return Wp(e);case"browser":return Fp(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 jp(e);case"lockfile":return Np(e);case"pre-commit-hook":return Op(e)}}function jp(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 Np(e){switch(e.status){case"match":return`\u2713 Lockfile: ${le} is up to date`;case"missing":return`\u2717 Lockfile: ${le} is missing \u2014 run \`ripplo compile\` and commit it`;case"stale":return`\u2717 Lockfile: ${le} is out of date \u2014 run \`ripplo compile\` and commit it`}}function Op(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 Dp(e){return e.valid?"\u2713 Settings: Project configured":`\u2717 Settings: Missing fields: ${e.missingFields.join(", ")}`}function Lp(e){return e.missing.length===0?"\u2713 Env files: declared files present":`\u2717 Env files: declared in .ripplo/project.json but missing:
209
+ `);function Jo(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 Xo(e){let t=Me(e),r;try{r=_(e)}catch{return{status:t?"starting":"missing",type:"dev-session"}}return(await g({config:r,document:Np,variables:{cwd:r.cwd,projectId:r.projectId}}).catch(()=>null))?.project?.devSession!=null?{status:"active",type:"dev-session"}:{status:t?"starting":"missing",type:"dev-session"}}function Qo(e){switch(e.type){case"settings":return _p(e);case"env-files":return Up(e);case"token":return Vp(e);case"dev-server":return Fp(e);case"dev-session":return Jo(e);case"preconditions":return Wp(e);case"webhook-verification":return Hp(e);case"preconditions-validation":return Bp(e);case"workflows":return qp(e);case"browser":return Mp(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 Op(e);case"lockfile":return Dp(e);case"pre-commit-hook":return Lp(e)}}function Op(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 Dp(e){switch(e.status){case"match":return`\u2713 Lockfile: ${le} is up to date`;case"missing":return`\u2717 Lockfile: ${le} is missing \u2014 run \`ripplo compile\` and commit it`;case"stale":return`\u2717 Lockfile: ${le} is out of date \u2014 run \`ripplo compile\` and commit it`}}function Lp(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 _p(e){return e.valid?"\u2713 Settings: Project configured":`\u2717 Settings: Missing fields: ${e.missingFields.join(", ")}`}function Up(e){return e.missing.length===0?"\u2713 Env files: declared files present":`\u2717 Env files: declared in .ripplo/project.json but missing:
210
210
  ${e.missing.map(r=>` ${r}`).join(`
211
211
  `)}
212
- 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 _p(e){switch(e.status){case"valid":return`\u2713 Auth: Signed in as ${e.email??"unknown"}`;case"missing":return"\u2717 Auth: No token found. Run `ripplo` to authenticate.";case"invalid":return"\u2717 Auth: Saved token rejected by server. Run `ripplo auth login` to re-authenticate.";case"unreachable":return`! Auth: Could not reach ${Q()} to validate token.`}}function Up(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 Vp(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 Fp(e){return e.installed?"\u2713 Browser: Chromium installed":"\u2717 Browser: Chromium not installed. Run: npx playwright install chromium"}function Hp(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 Mp(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"}
212
+ 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 Vp(e){switch(e.status){case"valid":return`\u2713 Auth: Signed in as ${e.email??"unknown"}`;case"missing":return"\u2717 Auth: No token found. Run `ripplo` to authenticate.";case"invalid":return"\u2717 Auth: Saved token rejected by server. Run `ripplo auth login` to re-authenticate.";case"unreachable":return`! Auth: Could not reach ${Q()} to validate token.`}}function Fp(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 Hp(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 Mp(e){return e.installed?"\u2713 Browser: Chromium installed":"\u2717 Browser: Chromium not installed. Run: npx playwright install chromium"}function Wp(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 Bp(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"}
213
213
  ${t.join(`
214
- `)}`}function Wp(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=>Bp(r));return`\u2717 Tests: ${String(e.invalidNames.length)} invalid
214
+ `)}`}function qp(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=>zp(r));return`\u2717 Tests: ${String(e.invalidNames.length)} invalid
215
215
  ${t.join(`
216
- `)}`}function Bp(e){let t=e.errors.map(r=>" - "+(r.path===""?"":r.path+": ")+r.message);return" "+e.name+`:
216
+ `)}`}function zp(e){let t=e.errors.map(r=>" - "+(r.path===""?"":r.path+": ")+r.message);return" "+e.name+`:
217
217
  `+t.join(`
218
- `)}import Qr from"fs";import Xp from"path";import{chromium as Qp}from"playwright";import qp from"fs";import zp from"path";async function Qo(e){let t=zp.join(e,".ripplo","index.ts");if(!qp.existsSync(t))return{appUrl:void 0,engineUrl:void 0,errors:[{message:".ripplo/index.ts not found",path:""}],valid:!1,warnings:[]};let r=await C(e);if(!r.ok)return{appUrl:void 0,engineUrl:void 0,errors:[{message:r.error,path:".ripplo/"}],valid:!1,warnings:[]};try{let n=Ae();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 Xr(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 Yo({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}}import{graphql as Gp}from"gql.tada";var Kp=Gp(`
218
+ `)}import Yr from"fs";import Yp from"path";import{chromium as Zp}from"playwright";import Gp from"fs";import Kp from"path";async function Yo(e){let t=Kp.join(e,".ripplo","index.ts");if(!Gp.existsSync(t))return{appUrl:void 0,engineUrl:void 0,errors:[{message:".ripplo/index.ts not found",path:""}],valid:!1,warnings:[]};let r=await C(e);if(!r.ok)return{appUrl:void 0,engineUrl:void 0,errors:[{message:r.error,path:".ripplo/"}],valid:!1,warnings:[]};try{let n=$e();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 Qr(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 Zo({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}}import{graphql as Jp}from"gql.tada";var Xp=Jp(`
219
219
  query DoctorAuthViewer {
220
220
  currentUser {
221
221
  name
222
222
  email
223
223
  }
224
224
  }
225
- `),Jp="Failed to connect to Ripplo server";async function Zo({serverUrl:e,token:t}){try{let r=await g({config:ve({serverUrl:e,token:t}),document:Kp,variables:void 0});return r.currentUser==null?{kind:"invalid"}:{email:r.currentUser.email,kind:"valid"}}catch(r){return(r instanceof Error?r.message:String(r)).startsWith(Jp)?{kind:"unreachable"}:{kind:"invalid"}}}function ei(e){switch(e.type){case"settings":return!e.valid;case"env-files":return e.missing.length>0;case"token":return e.status==="missing"||e.status==="invalid";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 ti(e){let t=await em(e),r={missing:or(e),type:"env-files"},n=await tm(),o=rm(),i=await C(e),s=nm(i),a=sm(i),l=await Yp(e,i),c=Zp(e),p=await am(t,i);return[t,r,n,...p,s,a,l,c,o]}async function Yp(e,t){if(!t.ok)return{status:"missing",type:"lockfile"};let r=await Dt({cwd:e});return{status:Lt({compiled:t.result,existing:r}),type:"lockfile"}}function Zp(e){let t=Xp.join(e,".git","hooks","pre-commit");return Qr.existsSync(t)?{installed:Qr.readFileSync(t,"utf8").includes("ripplo compile --check"),type:"pre-commit-hook"}:{installed:!1,type:"pre-commit-hook"}}async function em(e){let t=await Qo(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}}async function tm(){let e=ee();if(e==null||e.length===0)return{email:void 0,status:"missing",type:"token"};let t=await Zo({serverUrl:Q(),token:e});return t.kind==="valid"?{email:t.email,status:"valid",type:"token"}:{email:void 0,status:t.kind,type:"token"}}function rm(){let e=Qp.executablePath();return{installed:Qr.existsSync(e),type:"browser"}}function nm(e){if(!e.ok)return{errorCount:1,errors:[{message:e.error,path:""}],found:!1,type:"preconditions-validation",valid:!1};let t=om(e.result.preconditions,e.result.tests);return{errorCount:t.length,errors:t,found:!0,type:"preconditions-validation",valid:t.length===0}}function om(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}`})})}),im(e).forEach(o=>{r.push({message:o,path:"preconditions"})}),r}function im(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 sm(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 am(e,t){if(!e.valid||!t.ok)return[];let r;try{let a=Ae();r={appUrl:a.appUrl,engineUrl:a.engineUrl,webhookSecret:a.webhookSecret}}catch{return[]}let n=[],o=await Xr(r.appUrl)==null;n.push({appUrl:r.appUrl,reachable:o,type:"dev-server"});let i=await Jo(process.cwd());n.push(i);let s=await lm(r,t);return n.push(...s),n}async function lm(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=dm(e.appUrl,e.engineUrl);if(i==null)return[o];let s=await Xr(i)==null,a=[];if(a.push({configured:!0,count:r,endpointReachable:s,type:"preconditions"}),ri(e.engineUrl)&&a.push({reachable:s,type:"engine-endpoint",url:i}),!s)return a;let l=await Yo({appUrl:e.appUrl,engineUrl:e.engineUrl});a.push({rejectsUnsigned:l==null,type:"webhook-verification"});let c=await cm({engineUrl:i,webhookSecret:e.webhookSecret});return a.push({status:c,type:"adapter-enabled",url:i}),a}async function cm({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",...be({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 ri(e){return e.startsWith("http://")||e.startsWith("https://")}function dm(e,t){return ri(t)?t:`${e}${t}`}async function ni(){let e=process.cwd(),t=await ti(e),r=t.map(o=>Xo(o));process.stdout.write(r.join(`
225
+ `),Qp="Failed to connect to Ripplo server";async function ei({serverUrl:e,token:t}){try{let r=await g({config:ve({serverUrl:e,token:t}),document:Xp,variables:void 0});return r.currentUser==null?{kind:"invalid"}:{email:r.currentUser.email,kind:"valid"}}catch(r){return(r instanceof Error?r.message:String(r)).startsWith(Qp)?{kind:"unreachable"}:{kind:"invalid"}}}function ti(e){switch(e.type){case"settings":return!e.valid;case"env-files":return e.missing.length>0;case"token":return e.status==="missing"||e.status==="invalid";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 ri(e){let t=await rm(e),r={missing:ir(e),type:"env-files"},n=await nm(),o=om(),i=await C(e),s=im(i),a=lm(i),l=await em(e,i),c=tm(e),p=await cm(t,i);return[t,r,n,...p,s,a,l,c,o]}async function em(e,t){if(!t.ok)return{status:"missing",type:"lockfile"};let r=await Dt({cwd:e});return{status:Lt({compiled:t.result,existing:r}),type:"lockfile"}}function tm(e){let t=Yp.join(e,".git","hooks","pre-commit");return Yr.existsSync(t)?{installed:Yr.readFileSync(t,"utf8").includes("ripplo compile --check"),type:"pre-commit-hook"}:{installed:!1,type:"pre-commit-hook"}}async function rm(e){let t=await Yo(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}}async function nm(){let e=ee();if(e==null||e.length===0)return{email:void 0,status:"missing",type:"token"};let t=await ei({serverUrl:Q(),token:e});return t.kind==="valid"?{email:t.email,status:"valid",type:"token"}:{email:void 0,status:t.kind,type:"token"}}function om(){let e=Zp.executablePath();return{installed:Yr.existsSync(e),type:"browser"}}function im(e){if(!e.ok)return{errorCount:1,errors:[{message:e.error,path:""}],found:!1,type:"preconditions-validation",valid:!1};let t=sm(e.result.preconditions,e.result.tests);return{errorCount:t.length,errors:t,found:!0,type:"preconditions-validation",valid:t.length===0}}function sm(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}`})})}),am(e).forEach(o=>{r.push({message:o,path:"preconditions"})}),r}function am(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 lm(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 cm(e,t){if(!e.valid||!t.ok)return[];let r;try{let a=$e();r={appUrl:a.appUrl,engineUrl:a.engineUrl,webhookSecret:a.webhookSecret}}catch{return[]}let n=[],o=await Qr(r.appUrl)==null;n.push({appUrl:r.appUrl,reachable:o,type:"dev-server"});let i=await Xo(process.cwd());n.push(i);let s=await dm(r,t);return n.push(...s),n}async function dm(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=pm(e.appUrl,e.engineUrl);if(i==null)return[o];let s=await Qr(i)==null,a=[];if(a.push({configured:!0,count:r,endpointReachable:s,type:"preconditions"}),ni(e.engineUrl)&&a.push({reachable:s,type:"engine-endpoint",url:i}),!s)return a;let l=await Zo({appUrl:e.appUrl,engineUrl:e.engineUrl});a.push({rejectsUnsigned:l==null,type:"webhook-verification"});let c=await um({engineUrl:i,webhookSecret:e.webhookSecret});return a.push({status:c,type:"adapter-enabled",url:i}),a}async function um({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",...be({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 ni(e){return e.startsWith("http://")||e.startsWith("https://")}function pm(e,t){return ni(t)?t:`${e}${t}`}async function oi(){let e=process.cwd(),t=await ri(e),r=t.map(o=>Qo(o));process.stdout.write(r.join(`
226
226
  `)+`
227
- `);let n=t.some(o=>ei(o));process.exit(n?1:0)}import{graphql as lt,readFragment as wm}from"gql.tada";import pm from"crypto";import{graphql as mm}from"gql.tada";import Yr from"fs";import Zr from"path";function Ft(e){try{let t=Zr.join(um(e),"HEAD"),r=Yr.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 um(e){let t=Zr.join(e,".git");if(Yr.statSync(t).isDirectory())return t;let n=Yr.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 Zr.resolve(e,i)}var fm=mm(`
227
+ `);let n=t.some(o=>ti(o));process.exit(n?1:0)}import{graphql as lt,readFragment as Pm}from"gql.tada";import{createHash as ii}from"crypto";import{mkdirSync as mm,readFileSync as Zr,writeFileSync as fm}from"fs";import Ft from"path";var gm=[".ts",".tsx",".js",".jsx"];function Re(e){let t=ii("sha256");return t.update(z(["rev-parse","HEAD"],e)),t.update("\0"),t.update(z(["diff","HEAD"],e)),t.update("\0"),z(["ls-files","--others","--exclude-standard"],e).split(`
228
+ `).filter(n=>n.length>0).filter(n=>gm.some(o=>n.endsWith(o))).toSorted((n,o)=>n.localeCompare(o)).forEach(n=>{t.update(n),t.update("\0"),t.update(ym(Ft.join(e,n))),t.update("\0")}),t.digest("hex")}function si(e){let t=Ft.join(e,".ripplo","ripplo.lock");try{let r=Zr(t);return ii("sha256").update(r).digest("hex")}catch{return null}}function We(e,t){try{return Zr(ai(e,t),"utf8").trim()}catch{return null}}function Be(e,t,r){let n=ai(e,t);mm(Ft.dirname(n),{recursive:!0}),fm(n,r)}function ai(e,t){return Ft.join(e,".ripplo",".local",`${t}.hash`)}function ym(e){try{return Zr(e)}catch{return Buffer.alloc(0)}}import wm from"crypto";import{graphql as bm}from"gql.tada";import en from"fs";import tn from"path";function Ht(e){try{let t=tn.join(hm(e),"HEAD"),r=en.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 hm(e){let t=tn.join(e,".git");if(en.statSync(t).isDirectory())return t;let n=en.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 tn.resolve(e,i)}var vm=bm(`
228
229
  mutation SyncDevSession(
229
230
  $projectId: String!
230
231
  $cwd: String!
@@ -243,12 +244,12 @@ ${t.join(`
243
244
  hooksPaused
244
245
  }
245
246
  }
246
- `);async function st(e){let t=gm(e.compiled);return hm({config:e.config,cwd:e.cwd,payload:t})}async function Ce(e,t){let r=await C(e);if(!r.ok)throw new Error(`DSL compilation failed: ${r.error}`);let n=await st({compiled:r.result,config:t,cwd:e});return{compiled:r.result,devSessionId:n.devSessionId}}function gm(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,sourcePath:t.sourcePath??null,spec:t.implemented?JSON.stringify(t.spec):null}))}}function ym(e){return pm.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function hm({config:e,cwd:t,payload:r}){let n=ym(r),o=Ft(t),i=await g({config:e,document:fm,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,sourcePath:s.sourcePath,spec:s.spec??null}))}});if(i.syncDevSession==null)throw new Error("syncDevSession returned null");return{devSessionId:i.syncDevSession.id,hash:n,hooksPaused:i.syncDevSession.hooksPaused}}import oi from"figures";var at={cross:oi.cross,tick:oi.tick};var si=lt(`
247
+ `);async function at(e){let t=km(e.compiled);return Rm({config:e.config,cwd:e.cwd,payload:t})}async function Ee(e,t){let r=await C(e);if(!r.ok)throw new Error(`DSL compilation failed: ${r.error}`);let n=await at({compiled:r.result,config:t,cwd:e});return{compiled:r.result,devSessionId:n.devSessionId}}function km(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,sourcePath:t.sourcePath??null,spec:t.implemented?JSON.stringify(t.spec):null}))}}function Sm(e){return wm.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function Rm({config:e,cwd:t,payload:r}){let n=Sm(r),o=Ht(t),i=await g({config:e,document:vm,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,sourcePath:s.sourcePath,spec:s.spec??null}))}});if(i.syncDevSession==null)throw new Error("syncDevSession returned null");return{devSessionId:i.syncDevSession.id,hash:n,hooksPaused:i.syncDevSession.hooksPaused}}import li from"figures";var Ae={cross:li.cross,tick:li.tick};var di=lt(`
247
248
  fragment WorkflowIdMCP on Workflow {
248
249
  id
249
250
  slug
250
251
  }
251
- `),bm=lt(`
252
+ `),xm=lt(`
252
253
  query ProjectWorkflowIdsMCP($projectId: String!, $cwd: String!) {
253
254
  project(id: $projectId) {
254
255
  id
@@ -260,20 +261,20 @@ ${t.join(`
260
261
  }
261
262
  }
262
263
  }
263
- `,[si]),vm=lt(`
264
+ `,[di]),Cm=lt(`
264
265
  mutation SetProjectViewCLI($projectId: String!, $devSessionId: String!) {
265
266
  setProjectView(projectId: $projectId, devSessionId: $devSessionId) {
266
267
  id
267
268
  }
268
269
  }
269
- `),Sm=lt(`
270
- mutation CreateRunMCP($workflowId: String!) {
271
- createRun(workflowId: $workflowId) {
270
+ `),Em=lt(`
271
+ mutation CreateRunMCP($workflowId: String!, $lockfileHash: String, $repoHash: String) {
272
+ createRun(workflowId: $workflowId, lockfileHash: $lockfileHash, repoHash: $repoHash) {
272
273
  id
273
274
  status
274
275
  }
275
276
  }
276
- `),km=lt(`
277
+ `),Am=lt(`
277
278
  query RunStatusMCP($id: String!) {
278
279
  run(id: $id) {
279
280
  id
@@ -283,6 +284,10 @@ ${t.join(`
283
284
  failCount
284
285
  warnCount
285
286
  summary
287
+ caughtKind
288
+ workflow {
289
+ slug
290
+ }
286
291
  traceEntries {
287
292
  title
288
293
  status
@@ -296,8 +301,8 @@ ${t.join(`
296
301
  }
297
302
  }
298
303
  }
299
- `);async function Ht({config:e,ids:t}){let r=await Rm({config:e,ids:t}),n=await Promise.all(r.map(async s=>{try{let a=await Am({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}
300
- ${w("setup","check auth + config")}`};let{entry:a,runId:l}=s;try{let c=await Tm({config:e,runId:l}),p=Em({config:e,id:a.id,runId:l}),m=`.ripplo/debug/${l}/`;return{id:a.id,runId:l,summary:`View run: ${p}
304
+ `);async function Mt({config:e,ids:t}){let r=await Im({config:e,ids:t}),n=await Promise.all(r.map(async s=>{try{let a=await Om({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}
305
+ ${w("setup","check auth + config")}`};let{entry:a,runId:l}=s;try{let c=await _m({config:e,runId:l}),p=Nm({config:e,id:a.id,runId:l}),m=`.ripplo/debug/${l}/`;return{id:a.id,runId:l,summary:`View run: ${p}
301
306
  Debug artifacts: ${m}
302
307
  ${w("debug","read summary.txt, accessibility-tree, network.jsonl before guessing")}
303
308
 
@@ -307,10 +312,10 @@ ${s.summary}`).join(`
307
312
 
308
313
  ---
309
314
 
310
- `);return{results:o,summary:i}}async function Rm({config:e,ids:t}){let r=await Ce(e.cwd,e),n=await g({config:e,document:bm,variables:{cwd:e.cwd,projectId:e.projectId}});if(n.project==null)throw new Error("Project not found");let o=n.project.devSession;if(o==null)throw new Error("No active dev session. Start one by running `ripplo` (or `npx ripplo`) in your terminal, then try again.");await g({config:e,document:vm,variables:{devSessionId:o.id,projectId:e.projectId}});let i=(o.workflows??[]).map(a=>wm(si,a));if(t.length===0)return i.map(a=>({id:a.slug,workflowId:a.id}));let s=r.compiled.tests.map(a=>a.slug);return t.map(a=>{let l=i.find(c=>c.slug===a);if(l==null)throw new Error(Pm({compiledSlugs:s,slug:a}));return{id:a,workflowId:l.id}})}function Pm({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=xm({compiledSlugs:e,limit:3,slug:t}),n=r.length>0?`
315
+ `);return{results:o,summary:i}}async function Im({config:e,ids:t}){let r=await Ee(e.cwd,e),n=await g({config:e,document:xm,variables:{cwd:e.cwd,projectId:e.projectId}});if(n.project==null)throw new Error("Project not found");let o=n.project.devSession;if(o==null)throw new Error("No active dev session. Start one by running `ripplo` (or `npx ripplo`) in your terminal, then try again.");await g({config:e,document:Cm,variables:{devSessionId:o.id,projectId:e.projectId}});let i=(o.workflows??[]).map(a=>Pm(di,a));if(t.length===0)return i.map(a=>({id:a.slug,workflowId:a.id}));let s=r.compiled.tests.map(a=>a.slug);return t.map(a=>{let l=i.find(c=>c.slug===a);if(l==null)throw new Error($m({compiledSlugs:s,slug:a}));return{id:a,workflowId:l.id}})}function $m({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=Tm({compiledSlugs:e,limit:3,slug:t}),n=r.length>0?`
311
316
  Did you mean: ${r.join(", ")}?`:"";return`Test "${t}" is not registered in this dev session.${n}
312
- Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on demand \u2014 restarting the dev server will not help.)`}function xm({compiledSlugs:e,limit:t,slug:r}){let n=new Set(r.split("-"));return e.map(i=>({candidate:i,score:Cm(n,i)})).filter(i=>i.score>0).toSorted((i,s)=>s.score-i.score).slice(0,t).map(i=>i.candidate)}function Cm(e,t){return t.split("-").filter(r=>e.has(r)).length}function Em({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 Am({config:e,workflowId:t}){let r=await g({config:e,document:Sm,variables:{concurrency:1,platforms:["chromium"],workflowId:t}});if(r.createRun==null)throw new Error("Failed to create run");return r.createRun.id}var Im=2e3,ii=150;async function Tm({config:e,runId:t}){let r=0;for(;r<ii;){await jm(Im),r+=1;let o=(await g({config:e,document:km,variables:{id:t}})).run;if(o==null)throw new Error(`Run ${t} not found`);if(!(o.status==="pending"||o.status==="running"))return $m({run:o,runId:t})}return`Run ${t} timed out after polling ${String(ii)} times.`}function $m({run:e,runId:t}){let r=[`Run ${t}: ${e.status.toUpperCase()}`];return r.push(` ${e.status}: ${String(e.passCount)} passed, ${String(e.failCount)} failed (${String(e.duration??0)}ms)`),e.summary!=null&&r.push(` Summary: ${e.summary}`),e.traceEntries.forEach(n=>{let o=n.status==="passed"?at.tick:at.cross,i=n.detail==null?"":` \u2014 ${n.detail}`;r.push(` ${o} ${n.title} (${String(n.duration)}ms)${i}`),n.assertions.forEach(s=>{let a=s.status==="passed"?at.tick:at.cross,l=s.detail==null?"":` \u2014 ${s.detail}`;r.push(` ${a} ${s.description}${l}`)})}),r.join(`
313
- `)}function jm(e){return new Promise(t=>{setTimeout(t,e)})}import{graphql as Nm}from"gql.tada";var Om=Nm(`
317
+ Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on demand \u2014 restarting the dev server will not help.)`}function Tm({compiledSlugs:e,limit:t,slug:r}){let n=new Set(r.split("-"));return e.map(i=>({candidate:i,score:jm(n,i)})).filter(i=>i.score>0).toSorted((i,s)=>s.score-i.score).slice(0,t).map(i=>i.candidate)}function jm(e,t){return t.split("-").filter(r=>e.has(r)).length}function Nm({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 Om({config:e,workflowId:t}){let r=await g({config:e,document:Em,variables:{lockfileHash:si(e.cwd),repoHash:Dm(e.cwd),workflowId:t}});if(r.createRun==null)throw new Error("Failed to create run");return r.createRun.id}function Dm(e){try{return Re(e)}catch{return null}}var Lm=2e3,ci=150;async function _m({config:e,runId:t}){let r=0;for(;r<ci;){await Fm(Lm),r+=1;let o=(await g({config:e,document:Am,variables:{id:t}})).run;if(o==null)throw new Error(`Run ${t} not found`);if(!(o.status==="pending"||o.status==="running"))return Um({run:o,runId:t})}return`Run ${t} timed out after polling ${String(ci)} times.`}function Um({run:e,runId:t}){let r=[`Run ${t}: ${e.status.toUpperCase()}`],n=Vm(e);return n!=null&&r.push(n),r.push(` ${e.status}: ${String(e.passCount)} passed, ${String(e.failCount)} failed (${String(e.duration??0)}ms)`),e.summary!=null&&r.push(` Summary: ${e.summary}`),e.traceEntries.forEach(o=>{let i=o.status==="passed"?Ae.tick:Ae.cross,s=o.detail==null?"":` \u2014 ${o.detail}`;r.push(` ${i} ${o.title} (${String(o.duration)}ms)${s}`),o.assertions.forEach(a=>{let l=a.status==="passed"?Ae.tick:Ae.cross,c=a.detail==null?"":` \u2014 ${a.detail}`;r.push(` ${l} ${a.description}${c}`)})}),r.join(`
318
+ `)}function Vm(e){if(e.caughtKind==null)return null;let t=e.workflow?.slug??"workflow";return e.caughtKind==="new_test"?` ${Ae.tick} ripplo caught a bug \u2014 new test "${t}" surfaced an issue in your app code`:` ${Ae.tick} ripplo caught a regression in "${t}"`}function Fm(e){return new Promise(t=>{setTimeout(t,e)})}import{graphql as Hm}from"gql.tada";var Mm=Hm(`
314
319
  query DevSessionCheckPreflight($projectId: String!, $cwd: String!) {
315
320
  project(id: $projectId) {
316
321
  id
@@ -321,36 +326,36 @@ Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on
321
326
  }
322
327
  `);function me(){try{return _(process.cwd())}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}
323
328
  `),process.stderr.write(`${w("setup")}
324
- `),process.exit(1)}}async function fe(e){(await g({config:e,document:Om,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(`${w("setup")}
325
- `),process.exit(1))}async function ai({id:e,runs:t}){let r=me();await fe(r),process.stdout.write(`flake-detect "${e}" x${String(t)}...
326
- `);let n=await Promise.allSettled(Array.from({length:t},()=>Ht({config:r,ids:[e]}))),o=0,i=0,s=new Map;n.forEach(l=>{if(l.status==="rejected"){i++;let p=l.reason instanceof Error?l.reason.message:"unknown error";s.set(p,(s.get(p)??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 p=c.summary.split(`
329
+ `),process.exit(1)}}async function fe(e){(await g({config:e,document:Mm,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(`${w("setup")}
330
+ `),process.exit(1))}async function ui({id:e,runs:t}){let r=me();await fe(r),process.stdout.write(`flake-detect "${e}" x${String(t)}...
331
+ `);let n=await Promise.allSettled(Array.from({length:t},()=>Mt({config:r,ids:[e]}))),o=0,i=0,s=new Map;n.forEach(l=>{if(l.status==="rejected"){i++;let p=l.reason instanceof Error?l.reason.message:"unknown error";s.set(p,(s.get(p)??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 p=c.summary.split(`
327
332
  `).find(m=>m.includes("FAILED")||m.includes("ERROR"))??"unknown failure";s.set(p,(s.get(p)??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)
328
333
  `),s.size>0&&s.forEach((l,c)=>{process.stdout.write(` ${String(l)}x: ${c}
329
334
  `)}),i>0&&process.stderr.write(`${w("flake-detect","parallel safety + race conditions")}
330
- `),process.exit(i>0?1:0)}import Mt from"fs";import{graphql as Lm}from"gql.tada";import Dm from"fs";function Re(e){return tt(e,"hooks-paused")}function T(e){return Dm.existsSync(Re(e))?!1:Fe(e)}var _m=Lm(`
335
+ `),process.exit(i>0?1:0)}import Wt from"fs";import{graphql as Bm}from"gql.tada";import Wm from"fs";function Pe(e){return rt(e,"hooks-paused")}function $(e){return Wm.existsSync(Pe(e))?!1:Me(e)}var qm=Bm(`
331
336
  mutation CliSetHooksPaused($projectId: String!, $paused: Boolean!) {
332
337
  setHooksPaused(projectId: $projectId, paused: $paused) {
333
338
  id
334
339
  }
335
340
  }
336
- `);async function li(){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();et(e);let t=Re(e);if(Mt.existsSync(t)){process.stdout.write("Hooks already paused. Run `ripplo hooks resume` to re-enable.\n");return}Mt.writeFileSync(t,""),await di(e,!0),process.stdout.write("Hooks paused. Pre-edit gates and stop enforcement are off until you run `ripplo hooks resume`.\n")}async function ci(){let e=process.cwd(),t=Re(e);if(!Mt.existsSync(t)){process.stdout.write(`Hooks already active.
337
- `);return}Mt.unlinkSync(t),await di(e,!1),process.stdout.write(`Hooks resumed.
338
- `)}async function di(e,t){let r;try{r=_(e)}catch{return}await g({config:r,document:_m,variables:{paused:t,projectId:r.projectId}}).catch(()=>null)}import He from"fs";import Me from"path";import{input as mi,select as fi}from"@inquirer/prompts";import{graphql as nf}from"gql.tada";import{exec as Um}from"child_process";import D from"fs";import U from"path";import{promisify as Vm}from"util";var Fm=["@ripplo/testing"],ui=".ripplo/ripplo.lock linguist-generated=true",Hm=[".ripplo/debug/",".ripplo/.local/"],Mm=Vm(Um);async function pi({cwd:e,onStep:t}){t("Scaffolding project files..."),Xm({cwd:e}),t("Updating .gitignore..."),Qm(e),t("Marking ripplo.lock as generated..."),qm(e),t("Installing dependencies...");let r=await Wm(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 Bm(e);o!=null&&n.push({manualCommand:void 0,message:o})}return t("Setting up browser..."),await yr(),n}async function Wm(e){let t=zm({cwd:e,pm:Jm(e)});y.info("Installing dependencies: %s",t);try{return await Mm(t,{cwd:e}),{ok:!0}}catch(r){let n=r instanceof Error?r.message.split(`
339
- `)[0]??r.message:String(r);return y.warn("Install failed (%s): %s",t,n),{cmd:t,ok:!1,reason:n}}}async function Bm(e){try{let t=await C(e);if(!t.ok)return;await ce({cwd:e,result:t.result});return}catch(t){return`Couldn't compile initial lockfile: ${t instanceof Error?t.message:String(t)}.`}}function qm(e){let t=U.join(e,".gitattributes"),r=D.existsSync(t)?D.readFileSync(t,"utf8"):"";if(r.includes(ui))return;let n=r.length===0||r.endsWith(`
341
+ `);async function pi(){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(Wt.existsSync(t)){process.stdout.write("Hooks already paused. Run `ripplo hooks resume` to re-enable.\n");return}Wt.writeFileSync(t,""),await fi(e,!0),process.stdout.write("Hooks paused. Pre-edit gates and stop enforcement are off until you run `ripplo hooks resume`.\n")}async function mi(){let e=process.cwd(),t=Pe(e);if(!Wt.existsSync(t)){process.stdout.write(`Hooks already active.
342
+ `);return}Wt.unlinkSync(t),await fi(e,!1),process.stdout.write(`Hooks resumed.
343
+ `)}async function fi(e,t){let r;try{r=_(e)}catch{return}await g({config:r,document:qm,variables:{paused:t,projectId:r.projectId}}).catch(()=>null)}import qe from"fs";import ze from"path";import{input as hi,select as wi}from"@inquirer/prompts";import{graphql as pf}from"gql.tada";import{exec as zm}from"child_process";import D from"fs";import U from"path";import{promisify as Gm}from"util";var Km=["@ripplo/testing"],gi=".ripplo/ripplo.lock linguist-generated=true",Jm=[".ripplo/debug/",".ripplo/.local/"],Xm=Gm(zm);async function yi({cwd:e,onStep:t}){t("Scaffolding project files..."),of({cwd:e}),t("Updating .gitignore..."),sf(e),t("Marking ripplo.lock as generated..."),Zm(e),t("Installing dependencies...");let r=await Qm(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 Ym(e);o!=null&&n.push({manualCommand:void 0,message:o})}return t("Setting up browser..."),await hr(),n}async function Qm(e){let t=ef({cwd:e,pm:nf(e)});y.info("Installing dependencies: %s",t);try{return await Xm(t,{cwd:e}),{ok:!0}}catch(r){let n=r instanceof Error?r.message.split(`
344
+ `)[0]??r.message:String(r);return y.warn("Install failed (%s): %s",t,n),{cmd:t,ok:!1,reason:n}}}async function Ym(e){try{let t=await C(e);if(!t.ok)return;await ce({cwd:e,result:t.result});return}catch(t){return`Couldn't compile initial lockfile: ${t instanceof Error?t.message:String(t)}.`}}function Zm(e){let t=U.join(e,".gitattributes"),r=D.existsSync(t)?D.readFileSync(t,"utf8"):"";if(r.includes(gi))return;let n=r.length===0||r.endsWith(`
340
345
  `)?"":`
341
- `;D.writeFileSync(t,`${r}${n}${ui}
342
- `)}function zm({cwd:e,pm:t}){let r=Fm.join(" ");return t==="pnpm"?Gm(e)?`pnpm add -wD ${r}`:`pnpm add -D ${r}`:t==="yarn"?Km(e)?`yarn add -WD ${r}`:`yarn add -D ${r}`:t==="bun"?`bun add -d ${r}`:`npm install -D ${r}`}function Gm(e){return D.existsSync(U.join(e,"pnpm-workspace.yaml"))||D.existsSync(U.join(e,"pnpm-workspace.yml"))}function Km(e){let t=U.join(e,"package.json");if(!D.existsSync(t))return!1;try{let r=JSON.parse(D.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 Jm(e){return D.existsSync(U.join(e,"pnpm-lock.yaml"))?"pnpm":D.existsSync(U.join(e,"yarn.lock"))?"yarn":D.existsSync(U.join(e,"bun.lockb"))||D.existsSync(U.join(e,"bun.lock"))?"bun":"npm"}function Xm({cwd:e}){let t=U.join(e,".ripplo"),r=U.join(t,"tests"),n=U.join(t,"preconditions"),o=U.join(t,"observers");D.mkdirSync(r,{recursive:!0}),D.mkdirSync(n,{recursive:!0}),D.mkdirSync(o,{recursive:!0}),ct(U.join(t,"index.ts"),Ym),ct(U.join(n,"index.ts"),Zm),ct(U.join(o,"index.ts"),ef),ct(U.join(r,"index.ts"),tf),ct(U.join(t,"tsconfig.json"),rf)}function ct(e,t){D.existsSync(e)||D.writeFileSync(e,t)}function Qm(e){let t=U.join(e,".gitignore");if(!D.existsSync(t))return;let r=D.readFileSync(t,"utf8"),n=Hm.filter(i=>!r.includes(i));if(n.length===0)return;let o=r.endsWith(`
346
+ `;D.writeFileSync(t,`${r}${n}${gi}
347
+ `)}function ef({cwd:e,pm:t}){let r=Km.join(" ");return t==="pnpm"?tf(e)?`pnpm add -wD ${r}`:`pnpm add -D ${r}`:t==="yarn"?rf(e)?`yarn add -WD ${r}`:`yarn add -D ${r}`:t==="bun"?`bun add -d ${r}`:`npm install -D ${r}`}function tf(e){return D.existsSync(U.join(e,"pnpm-workspace.yaml"))||D.existsSync(U.join(e,"pnpm-workspace.yml"))}function rf(e){let t=U.join(e,"package.json");if(!D.existsSync(t))return!1;try{let r=JSON.parse(D.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 nf(e){return D.existsSync(U.join(e,"pnpm-lock.yaml"))?"pnpm":D.existsSync(U.join(e,"yarn.lock"))?"yarn":D.existsSync(U.join(e,"bun.lockb"))||D.existsSync(U.join(e,"bun.lock"))?"bun":"npm"}function of({cwd:e}){let t=U.join(e,".ripplo"),r=U.join(t,"tests"),n=U.join(t,"preconditions"),o=U.join(t,"observers");D.mkdirSync(r,{recursive:!0}),D.mkdirSync(n,{recursive:!0}),D.mkdirSync(o,{recursive:!0}),ct(U.join(t,"index.ts"),af),ct(U.join(n,"index.ts"),lf),ct(U.join(o,"index.ts"),cf),ct(U.join(r,"index.ts"),df),ct(U.join(t,"tsconfig.json"),uf)}function ct(e,t){D.existsSync(e)||D.writeFileSync(e,t)}function sf(e){let t=U.join(e,".gitignore");if(!D.existsSync(t))return;let r=D.readFileSync(t,"utf8"),n=Jm.filter(i=>!r.includes(i));if(n.length===0)return;let o=r.endsWith(`
343
348
  `)?"":`
344
349
  `;D.writeFileSync(t,r+o+n.join(`
345
350
  `)+`
346
- `)}var Ym=`import { createRipplo } from "@ripplo/testing";
351
+ `)}var af=`import { createRipplo } from "@ripplo/testing";
347
352
  import { preconditions } from "./preconditions/index";
348
353
  import { observers } from "./observers/index";
349
354
  import { tests } from "./tests/index";
350
355
 
351
356
  export { preconditions, observers, tests };
352
357
  export default createRipplo({ preconditions, observers, tests });
353
- `,Zm=`// Declare preconditions with \`precondition(name)\` from @ripplo/testing and collect them
358
+ `,lf=`// Declare preconditions with \`precondition(name)\` from @ripplo/testing and collect them
354
359
  // in the \`preconditions\` registry below. Every handle in this registry must be implemented
355
360
  // in your app server's \`createEngine(ripplo, { preconditions: {...}, observers: {...} })\` call.
356
361
  //
@@ -364,7 +369,7 @@ export default createRipplo({ preconditions, observers, tests });
364
369
  // export const preconditions = { authLoggedIn };
365
370
 
366
371
  export const preconditions = {};
367
- `,ef=`// Declare observers with \`observer(name)\` from @ripplo/testing and collect them in
372
+ `,cf=`// Declare observers with \`observer(name)\` from @ripplo/testing and collect them in
368
373
  // the \`observers\` registry below. Use them in tests via \`assert.backend(handle, params)\`.
369
374
  //
370
375
  // Example:
@@ -377,7 +382,7 @@ export const preconditions = {};
377
382
  // export const observers = { orgNameIs };
378
383
 
379
384
  export const observers = {};
380
- `,tf=`// Each test file under ./tests exports a TestDefinition. Import them here and add them
385
+ `,df=`// Each test file under ./tests exports a TestDefinition. Import them here and add them
381
386
  // to the \`tests\` array \u2014 that's what \`createRipplo({ ..., tests })\` receives.
382
387
  //
383
388
  // Example:
@@ -385,7 +390,7 @@ export const observers = {};
385
390
  // export const tests = [myTest] as const;
386
391
 
387
392
  export const tests = [] as const;
388
- `,rf=`{
393
+ `,uf=`{
389
394
  "compilerOptions": {
390
395
  "strict": true,
391
396
  "noUncheckedIndexedAccess": true,
@@ -401,68 +406,68 @@ export const tests = [] as const;
401
406
  "include": ["*.ts", "coverage.d.ts", "observers/**/*.ts", "preconditions/**/*.ts", "tests/**/*.ts"],
402
407
  "exclude": ["node_modules"]
403
408
  }
404
- `;var of=nf(`
409
+ `;var mf=pf(`
405
410
  query InitProjects {
406
411
  projects {
407
412
  id
408
413
  name
409
414
  }
410
415
  }
411
- `),en=["../.env.local","../.env"];async function gi(e=lf()){let t=process.cwd(),r=ee();r==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let n=Q();sf(t)&&(process.stdout.write(`\`.ripplo/index.ts\` already exists at ${t}. Delete it first if you want to re-init.
412
- `),process.exit(1));let o=await af({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 df(o,e.projectId),s=await uf(t,e.envFile),a=await pf(e.appUrl),l=cf(a,e.engineUrl),c=Me.resolve(Me.join(t,".ripplo"),s);dn({cwd:t,envFiles:[s],projectId:i}),gf({appUrl:a,engineUrl:l,filePath:c});let p=await pi({cwd:t,onStep:m=>{process.stdout.write(` ${m}
416
+ `),rn=["../.env.local","../.env"];async function bi(e=yf()){let t=process.cwd(),r=ee();r==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let n=Q();ff(t)&&(process.stdout.write(`\`.ripplo/index.ts\` already exists at ${t}. Delete it first if you want to re-init.
417
+ `),process.exit(1));let o=await gf({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 wf(o,e.projectId),s=await bf(t,e.envFile),a=await vf(e.appUrl),l=hf(a,e.engineUrl),c=ze.resolve(ze.join(t,".ripplo"),s);un({cwd:t,envFiles:[s],projectId:i}),Rf({appUrl:a,engineUrl:l,filePath:c});let p=await yi({cwd:t,onStep:m=>{process.stdout.write(` ${m}
413
418
  `)}});if(p.length>0){process.stdout.write(`Done with warnings:
414
419
  `),p.forEach(m=>{process.stdout.write(` - ${m.message}
415
420
  `),m.manualCommand!=null&&process.stdout.write(` run: ${m.manualCommand}
416
- `)});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 sf(e){return He.existsSync(Me.join(e,".ripplo","index.ts"))}async function af({serverUrl:e,token:t}){return((await g({config:ve({serverUrl:e,token:t}),document:of,variables:void 0})).projects??[]).map(n=>({id:n.id,name:n.name}))}function lf(){return{appUrl:void 0,engineUrl:void 0,envFile:void 0,projectId:void 0}}function cf(e,t){if(t!=null){try{new URL(t)}catch{process.stdout.write(`--engine-url is not a valid URL: ${t}
417
- `),process.exit(1)}return t}return`${e.replace(/\/$/,"")}/ripplo`}async function df(e,t){if(t!=null){let r=e.find(n=>n.id===t);return r==null&&(process.stdout.write(`Unknown project id: ${t}
421
+ `)});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 ff(e){return qe.existsSync(ze.join(e,".ripplo","index.ts"))}async function gf({serverUrl:e,token:t}){return((await g({config:ve({serverUrl:e,token:t}),document:mf,variables:void 0})).projects??[]).map(n=>({id:n.id,name:n.name}))}function yf(){return{appUrl:void 0,engineUrl:void 0,envFile:void 0,projectId:void 0}}function hf(e,t){if(t!=null){try{new URL(t)}catch{process.stdout.write(`--engine-url is not a valid URL: ${t}
422
+ `),process.exit(1)}return t}return`${e.replace(/\/$/,"")}/ripplo`}async function wf(e,t){if(t!=null){let r=e.find(n=>n.id===t);return r==null&&(process.stdout.write(`Unknown project id: ${t}
418
423
  `),process.exit(1)),process.stdout.write(`Using project: ${r.name} (${r.id})
419
424
  `),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})
420
- `),r.id}return fi({choices:e.map(r=>({name:r.name,value:r.id})),message:"Select a project"})}async function uf(e,t){return t!=null?(t.trim().length===0&&(process.stdout.write(`--env must not be empty
421
- `),process.exit(1)),t):mf(e)}async function pf(e){if(e!=null){try{new URL(e)}catch{process.stdout.write(`--app-url is not a valid URL: ${e}
422
- `),process.exit(1)}return e}return ff()}async function mf(e){let t=Me.join(e,".ripplo"),r=en.find(o=>He.existsSync(Me.resolve(t,o))),n=await fi({choices:[...en.map(o=>({name:r===o?`${o} (detected)`:o,value:o})),{name:"custom path",value:"__custom__"}],default:r??en[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:mi({message:"Path to env file (relative to .ripplo/, e.g. ../apps/server/.env)",validate:o=>o.trim().length>0?!0:"required"})}async function ff(){return mi({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 gf({appUrl:e,engineUrl:t,filePath:r}){He.mkdirSync(Me.dirname(r),{recursive:!0});let n=He.existsSync(r)?He.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=${Tr()}`),/^ENABLE_RIPPLO_TESTING=/m.test(n)||o.push("ENABLE_RIPPLO_TESTING=true"),o.length===0)return;let i=n.length===0||n.endsWith(`
425
+ `),r.id}return wi({choices:e.map(r=>({name:r.name,value:r.id})),message:"Select a project"})}async function bf(e,t){return t!=null?(t.trim().length===0&&(process.stdout.write(`--env must not be empty
426
+ `),process.exit(1)),t):kf(e)}async function vf(e){if(e!=null){try{new URL(e)}catch{process.stdout.write(`--app-url is not a valid URL: ${e}
427
+ `),process.exit(1)}return e}return Sf()}async function kf(e){let t=ze.join(e,".ripplo"),r=rn.find(o=>qe.existsSync(ze.resolve(t,o))),n=await wi({choices:[...rn.map(o=>({name:r===o?`${o} (detected)`:o,value:o})),{name:"custom path",value:"__custom__"}],default:r??rn[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:hi({message:"Path to env file (relative to .ripplo/, e.g. ../apps/server/.env)",validate:o=>o.trim().length>0?!0:"required"})}async function Sf(){return hi({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 Rf({appUrl:e,engineUrl:t,filePath:r}){qe.mkdirSync(ze.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=${Tr()}`),/^ENABLE_RIPPLO_TESTING=/m.test(n)||o.push("ENABLE_RIPPLO_TESTING=true"),o.length===0)return;let i=n.length===0||n.endsWith(`
423
428
  `)?"":`
424
- `;He.writeFileSync(r,`${n}${i}${o.join(`
429
+ `;qe.writeFileSync(r,`${n}${i}${o.join(`
425
430
  `)}
426
- `)}import tn from"fs";import yi from"path";import*as hi from"remeda";import yf from"path";import{graphql as hf}from"gql.tada";var wf=hf(`
431
+ `)}import nn from"fs";import vi from"path";import*as ki from"remeda";import Pf from"path";import{graphql as xf}from"gql.tada";var Cf=xf(`
427
432
  mutation AutoScopeAddDirty($projectId: String!, $cwd: String!, $workflowSlugs: [String!]!) {
428
433
  addDirtyTestsToScope(projectId: $projectId, cwd: $cwd, workflowSlugs: $workflowSlugs) {
429
434
  id
430
435
  }
431
436
  }
432
- `);async function Wt({compileResult:e,cwd:t}){if(!T(t))return{addedSlugs:[]};let r=bf(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=_(t)}catch{return{addedSlugs:[]}}if(await st({compiled:e.result,config:i,cwd:t}).catch(c=>(y.warn("auto-sync failed: %s",c instanceof Error?c.message:String(c)),null))==null)return{addedSlugs:[]};let a=await g({config:i,document:wf,variables:{cwd:i.cwd,projectId:i.projectId,workflowSlugs:o}}).catch(c=>(y.warn("auto-scope failed: %s",c instanceof Error?c.message:String(c)),null));return a==null?{addedSlugs:[]}:(a.addDirtyTestsToScope??[]).length===0?{addedSlugs:[]}:{addedSlugs:o}}function bf(e){let t;try{t=q(["status","--porcelain","--",".ripplo/tests"],e)}catch{return[]}return t.split(`
433
- `).map(r=>r.slice(3).trim()).filter(r=>/^\.ripplo\/tests\/[^/]+\.ts$/.test(r)).map(r=>yf.basename(r,".ts")).filter(r=>r!=="index")}async function wi(e){let{ids:t,requireImplemented:r}=e,n=process.cwd(),o=await C(n);o.ok||(process.stderr.write(`Compilation failed: ${o.error}
437
+ `);async function Bt({compileResult:e,cwd:t}){if(!$(t))return{addedSlugs:[]};let r=Ef(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=_(t)}catch{return{addedSlugs:[]}}if(await at({compiled:e.result,config:i,cwd:t}).catch(c=>(y.warn("auto-sync failed: %s",c instanceof Error?c.message:String(c)),null))==null)return{addedSlugs:[]};let a=await g({config:i,document:Cf,variables:{cwd:i.cwd,projectId:i.projectId,workflowSlugs:o}}).catch(c=>(y.warn("auto-scope failed: %s",c instanceof Error?c.message:String(c)),null));return a==null?{addedSlugs:[]}:(a.addDirtyTestsToScope??[]).length===0?{addedSlugs:[]}:{addedSlugs:o}}function Ef(e){let t;try{t=z(["status","--porcelain","--",".ripplo/tests"],e)}catch{return[]}return t.split(`
438
+ `).map(r=>r.slice(3).trim()).filter(r=>/^\.ripplo\/tests\/[^/]+\.ts$/.test(r)).map(r=>Pf.basename(r,".ts")).filter(r=>r!=="index")}async function Si(e){let{ids:t,requireImplemented:r}=e,n=process.cwd(),o=await C(n);o.ok||(process.stderr.write(`Compilation failed: ${o.error}
434
439
  `),process.stderr.write(`${w("create","DSL authoring + lint rules")}
435
- `),process.exit(1)),await ce({cwd:n,result:o.result});let i=Le(o.result),s=t.length===0?i.diagnostics:i.diagnostics.filter(f=>t.includes(f.test)),a=hi.groupBy(s,f=>f.test);Object.entries(a).forEach(([f,M])=>{process.stderr.write(`
440
+ `),process.exit(1)),await ce({cwd:n,result:o.result});let i=Ue(o.result),s=t.length===0?i.diagnostics:i.diagnostics.filter(f=>t.includes(f.test)),a=ki.groupBy(s,f=>f.test);Object.entries(a).forEach(([f,W])=>{process.stderr.write(`
436
441
  ${f}
437
- `),M.forEach($=>{let V=$.step==null?"":` at "${$.step}"`;process.stderr.write(` [${$.rule}]${V}
438
- `),process.stderr.write(` ${$.message}
442
+ `),W.forEach(T=>{let V=T.step==null?"":` at "${T.step}"`;process.stderr.write(` [${T.rule}]${V}
443
+ `),process.stderr.write(` ${T.message}
439
444
  `)})});let l=new Set(o.builder.getUnimplemented().tests),c=r.filter(f=>l.has(f));c.length>0&&(process.stderr.write(`
440
445
  not-implemented
441
446
  `),c.forEach(f=>{process.stderr.write(` ${f} is still marked .notImplemented()
442
- `)}));let p=Rf(n);p.length>0&&(process.stderr.write(`
447
+ `)}));let p=Tf(n);p.length>0&&(process.stderr.write(`
443
448
  preconditions
444
449
  `),p.forEach(f=>{process.stderr.write(` [hardcoded-identifier] ${f.file}
445
450
  `),process.stderr.write(` ${f.message}
446
451
  `)}));let m=s.length+c.length+p.length;m>0&&(process.stderr.write(`
447
452
  ${String(m)} error(s)
448
- `),vf({diagnostics:s,hardcodeWarnings:p,stillStubbed:c}),process.exit(1));let S=o.result.tests.length,j=t.length===0?"all tests":`${String(t.length)} test(s)`;process.stdout.write(`\u2713 ripplo lint: ${j} passed (${String(S)} compiled, lockfile written)
449
- `);let{addedSlugs:N}=await Wt({compileResult:o,cwd:n});N.length>0&&process.stdout.write(`\u2713 Auto-scoped ${N.join(", ")} (dirty tests).
450
- `)}function vf({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(`${w(o)}
451
- `))}var Sf=/['"`][\w.+-]+@[\w.-]+\.[a-z]{2,}['"`]/i,kf=/['"`][0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}['"`]/i;function Rf(e){let t=yi.join(e,".ripplo","preconditions");return tn.existsSync(t)?tn.readdirSync(t).filter(n=>n.endsWith(".ts")).flatMap(n=>Pf(yi.join(t,n))):[]}function Pf(e){let t=tn.readFileSync(e,"utf8"),r=t.includes("ctx.uniqueEmail")||t.includes("ctx.uniqueId"),n=[],o=Sf.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=kf.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 xf}from"gql.tada";var Cf=xf(`
453
+ `),Af({diagnostics:s,hardcodeWarnings:p,stillStubbed:c}),process.exit(1));let S=o.result.tests.length,j=t.length===0?"all tests":`${String(t.length)} test(s)`;process.stdout.write(`\u2713 ripplo lint: ${j} passed (${String(S)} compiled, lockfile written)
454
+ `);let{addedSlugs:N}=await Bt({compileResult:o,cwd:n});N.length>0&&process.stdout.write(`\u2713 Auto-scoped ${N.join(", ")} (dirty tests).
455
+ `)}function Af({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(`${w(o)}
456
+ `))}var If=/['"`][\w.+-]+@[\w.-]+\.[a-z]{2,}['"`]/i,$f=/['"`][0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}['"`]/i;function Tf(e){let t=vi.join(e,".ripplo","preconditions");return nn.existsSync(t)?nn.readdirSync(t).filter(n=>n.endsWith(".ts")).flatMap(n=>jf(vi.join(t,n))):[]}function jf(e){let t=nn.readFileSync(e,"utf8"),r=t.includes("ctx.uniqueEmail")||t.includes("ctx.uniqueId"),n=[],o=If.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=$f.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 Nf}from"gql.tada";var Of=Nf(`
452
457
  query ProjectsList {
453
458
  projects {
454
459
  id
455
460
  name
456
461
  }
457
462
  }
458
- `);async function bi(){let e=ee();e==null&&(process.stderr.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let t=Q(),n=((await g({config:ve({serverUrl:t,token:e}),document:Cf,variables:void 0})).projects??[]).map(o=>({id:o.id,name:o.name}));process.stdout.write(`${JSON.stringify({projects:n},null,2)}
459
- `)}async function vi(e){let t=me();await fe(t);let{results:r,summary:n}=await Ht({config:t,ids:e});process.stdout.write(`${n}
463
+ `);async function Ri(){let e=ee();e==null&&(process.stderr.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let t=Q(),n=((await g({config:ve({serverUrl:t,token:e}),document:Of,variables:void 0})).projects??[]).map(o=>({id:o.id,name:o.name}));process.stdout.write(`${JSON.stringify({projects:n},null,2)}
464
+ `)}async function Pi(e){let t=me();await fe(t);let{results:r,summary:n}=await Mt({config:t,ids:e});process.stdout.write(`${n}
460
465
  `);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.
461
466
  `),process.stderr.write(`${w("debug")}
462
- `)),process.exit(o?1:0)}async function Si(){let e=process.cwd(),t=_(e);try{let r=await Ce(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}
467
+ `)),process.exit(o?1:0)}async function xi(){let e=process.cwd(),t=_(e);try{let r=await Ee(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}
463
468
  `)}catch(r){let n=r instanceof Error?r.message:String(r);process.stderr.write(`ripplo sync failed: ${n}
464
469
  `),process.stderr.write(`${w("setup","verify auth + server reachability")}
465
- `),process.exit(1)}}import Bt from"fs";import{createClient as Nf}from"graphql-sse";import{graphql as qt}from"gql.tada";import{print as Ri}from"graphql";import{availableParallelism as Ef}from"os";import Af from"p-limit";var If=Math.max(1,Math.min(10,Math.floor(Ef()/2))),Tf=Af(If),rn=new Set;async function ki(e){if(!rn.has(e.runId)){rn.add(e.runId);try{await Tf(()=>$f(e))}finally{rn.delete(e.runId)}}}async function $f({config:e,cwd:t,runId:r,workflowSlug:n}){let o=await Ye({headed:!1});try{await hr({maxRuns:100});let i=t!=null&&n!=null?await jf({cwd:t,workflowSlug:n}):void 0;await Lr({baseUrl:e.appUrl,browser:o,config:e,headed:!1,preconditionNames:i,runId:r,webhookSecret:e.webhookSecret})}catch(i){y.error(i,"Runner error")}finally{await o.close()}}async function jf({cwd:e,workflowSlug:t}){let r=await C(e);if(!r.ok)return;let n=r.result.tests.find(o=>o.slug===t);if(n!=null)return n.preconditions}var Of=15e3,Df=qt(`
470
+ `),process.exit(1)}}import qt from"fs";import{createClient as Hf}from"graphql-sse";import{graphql as zt}from"gql.tada";import{print as Ei}from"graphql";import{availableParallelism as Df}from"os";import Lf from"p-limit";var _f=Math.max(1,Math.min(10,Math.floor(Df()/2))),Uf=Lf(_f),on=new Set;async function Ci(e){if(!on.has(e.runId)){on.add(e.runId);try{await Uf(()=>Vf(e))}finally{on.delete(e.runId)}}}async function Vf({config:e,cwd:t,runId:r,workflowSlug:n}){let o=await Ze({headed:!1});try{await wr({maxRuns:100});let i=t!=null&&n!=null?await Ff({cwd:t,workflowSlug:n}):void 0;await _r({baseUrl:e.appUrl,browser:o,config:e,headed:!1,preconditionNames:i,runId:r,webhookSecret:e.webhookSecret})}catch(i){y.error(i,"Runner error")}finally{await o.close()}}async function Ff({cwd:e,workflowSlug:t}){let r=await C(e);if(!r.ok)return;let n=r.result.tests.find(o=>o.slug===t);if(n!=null)return n.preconditions}var Mf=15e3,Wf=zt(`
466
471
  subscription RunRequestedWatch($devSessionId: String!) {
467
472
  runRequested(devSessionId: $devSessionId) {
468
473
  runId
@@ -470,30 +475,30 @@ ${String(m)} error(s)
470
475
  workflowSlug
471
476
  }
472
477
  }
473
- `),Lf=qt(`
478
+ `),Bf=zt(`
474
479
  subscription HooksPausedWatch($projectId: String!) {
475
480
  hooksPausedRequested(projectId: $projectId) {
476
481
  paused
477
482
  projectId
478
483
  }
479
484
  }
480
- `),_f=qt(`
485
+ `),qf=zt(`
481
486
  mutation HeartbeatDevSessionWatch($id: String!) {
482
487
  heartbeatDevSession(id: $id) {
483
488
  id
484
489
  }
485
490
  }
486
- `),Uf=qt(`
491
+ `),zf=zt(`
487
492
  mutation EndDevSessionWatch($projectId: String!, $cwd: String!) {
488
493
  endDevSession(projectId: $projectId, cwd: $cwd) {
489
494
  id
490
495
  }
491
496
  }
492
- `);async function Pi(){Jf();let e=Mf(process.cwd()),t=e.cwd,r=await C(t);r.ok||(process.stderr.write(`ripplo: DSL compilation failed: ${r.error}
493
- `),process.exit(1));let n=await qf(()=>st({compiled:r.result,config:e,cwd:t}));xi({cwd:t,paused:n.hooksPaused});let o=Ft(t);o!=null&&y.info("watching branch %s in %s",o,t);let i=Go(t),s=Nf({headers:{Authorization:`Bearer ${e.token}`},retryAttempts:1/0,url:`${e.ripploServerUrl}/graphql`}),a=Vf({config:e,cwd:t,devSessionId:n.devSessionId,sseClient:s}),l=Ff({cwd:t,projectId:e.projectId,sseClient:s}),c=Hf({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)
494
- `);let p=async()=>{c(),a(),l(),await Promise.race([g({config:e,document:Uf,variables:{cwd:e.cwd,projectId:e.projectId}}).catch(()=>{}),new Promise(S=>setTimeout(S,3e3))]),i()},m=()=>{p().finally(()=>process.exit(0))};process.on("SIGINT",m),process.on("SIGTERM",m),process.on("SIGHUP",m),process.on("SIGBREAK",m),await new Promise(()=>{})}function Vf({config:e,cwd:t,devSessionId:r,sseClient:n}){return n.subscribe({query:Ri(Df),variables:{devSessionId:r}},{complete:()=>{},error:o=>{y.error(o,"runRequested subscription error")},next:o=>{let i=o.data?.runRequested;i!=null&&(process.stdout.write(`ripplo: run ${i.runId} (${i.workflowSlug})
495
- `),ki({config:e,cwd:t,runId:i.runId,workflowId:i.workflowId,workflowSlug:i.workflowSlug}).catch(s=>{y.error({err:s,runId:i.runId,workflowSlug:i.workflowSlug},"run execution failed; watch continuing")}))}})}function xi({cwd:e,paused:t}){let r=Re(e);if(t&&!Bt.existsSync(r)){Bt.writeFileSync(r,"");return}!t&&Bt.existsSync(r)&&Bt.unlinkSync(r)}function Ff({cwd:e,projectId:t,sseClient:r}){return r.subscribe({query:Ri(Lf),variables:{projectId:t}},{complete:()=>{},error:n=>{y.error(n,"hooksPaused subscription error")},next:n=>{let o=n.data?.hooksPausedRequested?.paused;o!=null&&xi({cwd:e,paused:o})}})}function Hf({config:e,devSessionId:t}){let r=setInterval(()=>{g({config:e,document:_f,variables:{id:t}}).catch(n=>{y.warn("heartbeat failed: %s",n instanceof Error?n.message:String(n))})},Of);return()=>{clearInterval(r)}}function Mf(e){try{return _(e)}catch(t){let r=t instanceof Error?t.message:String(t);process.stderr.write(`${r}
496
- `),process.exit(1)}}var Wf=1e3,Bf=6e4;async function qf(e){let t=Date.now()+Bf,r;for(;Date.now()<t;){let n=await zf(e);if(n.ok)return n.value;if(!Gf(n.message))throw n.error;r=n.error,await Kf(Wf)}throw r instanceof Error?r:new Error("server never became ready")}async function zf(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 Gf(e){return e.includes("status 502")||e.includes("ECONNREFUSED")||e.includes("Failed to connect")||e.includes("fetch failed")}function Kf(e){return new Promise(t=>setTimeout(t,e))}function Jf(){process.on("unhandledRejection",e=>{y.error({err:e},"unhandledRejection in watch; continuing")}),process.on("uncaughtException",e=>{y.error({err:e},"uncaughtException in watch; continuing")})}import{graphql as dt}from"gql.tada";var Xf=dt(`
497
+ `);async function Ai(){ng();let e=Xf(process.cwd()),t=e.cwd,r=await C(t);r.ok||(process.stderr.write(`ripplo: DSL compilation failed: ${r.error}
498
+ `),process.exit(1));let n=await Zf(()=>at({compiled:r.result,config:e,cwd:t}));Ii({cwd:t,paused:n.hooksPaused});let o=Ht(t);o!=null&&y.info("watching branch %s in %s",o,t);let i=Ko(t),s=Hf({headers:{Authorization:`Bearer ${e.token}`},retryAttempts:1/0,url:`${e.ripploServerUrl}/graphql`}),a=Gf({config:e,cwd:t,devSessionId:n.devSessionId,sseClient:s}),l=Kf({cwd:t,projectId:e.projectId,sseClient:s}),c=Jf({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)
499
+ `);let p=async()=>{c(),a(),l(),await Promise.race([g({config:e,document:zf,variables:{cwd:e.cwd,projectId:e.projectId}}).catch(()=>{}),new Promise(S=>setTimeout(S,3e3))]),i()},m=()=>{p().finally(()=>process.exit(0))};process.on("SIGINT",m),process.on("SIGTERM",m),process.on("SIGHUP",m),process.on("SIGBREAK",m),await new Promise(()=>{})}function Gf({config:e,cwd:t,devSessionId:r,sseClient:n}){return n.subscribe({query:Ei(Wf),variables:{devSessionId:r}},{complete:()=>{},error:o=>{y.error(o,"runRequested subscription error")},next:o=>{let i=o.data?.runRequested;i!=null&&(process.stdout.write(`ripplo: run ${i.runId} (${i.workflowSlug})
500
+ `),Ci({config:e,cwd:t,runId:i.runId,workflowId:i.workflowId,workflowSlug:i.workflowSlug}).catch(s=>{y.error({err:s,runId:i.runId,workflowSlug:i.workflowSlug},"run execution failed; watch continuing")}))}})}function Ii({cwd:e,paused:t}){let r=Pe(e);if(t&&!qt.existsSync(r)){qt.writeFileSync(r,"");return}!t&&qt.existsSync(r)&&qt.unlinkSync(r)}function Kf({cwd:e,projectId:t,sseClient:r}){return r.subscribe({query:Ei(Bf),variables:{projectId:t}},{complete:()=>{},error:n=>{y.error(n,"hooksPaused subscription error")},next:n=>{let o=n.data?.hooksPausedRequested?.paused;o!=null&&Ii({cwd:e,paused:o})}})}function Jf({config:e,devSessionId:t}){let r=setInterval(()=>{g({config:e,document:qf,variables:{id:t}}).catch(n=>{y.warn("heartbeat failed: %s",n instanceof Error?n.message:String(n))})},Mf);return()=>{clearInterval(r)}}function Xf(e){try{return _(e)}catch(t){let r=t instanceof Error?t.message:String(t);process.stderr.write(`${r}
501
+ `),process.exit(1)}}var Qf=1e3,Yf=6e4;async function Zf(e){let t=Date.now()+Yf,r;for(;Date.now()<t;){let n=await eg(e);if(n.ok)return n.value;if(!tg(n.message))throw n.error;r=n.error,await rg(Qf)}throw r instanceof Error?r:new Error("server never became ready")}async function eg(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 tg(e){return e.includes("status 502")||e.includes("ECONNREFUSED")||e.includes("Failed to connect")||e.includes("fetch failed")}function rg(e){return new Promise(t=>setTimeout(t,e))}function ng(){process.on("unhandledRejection",e=>{y.error({err:e},"unhandledRejection in watch; continuing")}),process.on("uncaughtException",e=>{y.error({err:e},"uncaughtException in watch; continuing")})}import{graphql as dt}from"gql.tada";var og=dt(`
497
502
  query ScopeStatus($projectId: String!, $cwd: String!) {
498
503
  project(id: $projectId) {
499
504
  id
@@ -513,7 +518,7 @@ ${String(m)} error(s)
513
518
  }
514
519
  }
515
520
  }
516
- `),Qf=dt(`
521
+ `),ig=dt(`
517
522
  query ScopeWorkflowBySlug($projectId: String!, $cwd: String!, $slug: String!) {
518
523
  project(id: $projectId) {
519
524
  id
@@ -526,7 +531,7 @@ ${String(m)} error(s)
526
531
  }
527
532
  }
528
533
  }
529
- `),Yf=dt(`
534
+ `),sg=dt(`
530
535
  mutation ScopeAddDirtyTests($projectId: String!, $cwd: String!, $workflowSlugs: [String!]!) {
531
536
  addDirtyTestsToScope(projectId: $projectId, cwd: $cwd, workflowSlugs: $workflowSlugs) {
532
537
  id
@@ -536,36 +541,35 @@ ${String(m)} error(s)
536
541
  }
537
542
  }
538
543
  }
539
- `),Zf=dt(`
544
+ `),ag=dt(`
540
545
  mutation ScopeLink($id: ID!, $workflowId: String!) {
541
546
  linkScopeItem(id: $id, workflowId: $workflowId) {
542
547
  id
543
548
  }
544
549
  }
545
- `),eg=dt(`
550
+ `),lg=dt(`
546
551
  mutation ScopeRemoveMany($ids: [ID!]!) {
547
552
  removeScopeItems(ids: $ids)
548
553
  }
549
- `);async function Ci(e){let t=me();await fe(t);let n=(await g({config:t,document:Xf,variables:{cwd:t.cwd,projectId:t.projectId}})).project?.devSession?.scopeItems??[];if(e.format==="json"){process.stdout.write(`${JSON.stringify(n,null,2)}
554
+ `);async function $i(e){let t=me();await fe(t);let n=(await g({config:t,document:og,variables:{cwd:t.cwd,projectId:t.projectId}})).project?.devSession?.scopeItems??[];if(e.format==="json"){process.stdout.write(`${JSON.stringify(n,null,2)}
550
555
  `);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??""}
551
556
  `);return}let s=i.spec==null?"stub":"implemented";process.stdout.write(` [${s}] (${o.id}) ${i.slug} \u2014 ${i.name}
552
- `)})}async function Ei({testIds:e}){let t=me();await fe(t),await Ce(t.cwd,t);let n=(await g({config:t,document:Yf,variables:{cwd:t.cwd,projectId:t.projectId,workflowSlugs:[...e]}})).addDirtyTestsToScope??[];if(n.length===0){process.stdout.write(`No scope items added.
557
+ `)})}async function Ti({testIds:e}){let t=me();await fe(t),await Ee(t.cwd,t);let n=(await g({config:t,document:sg,variables:{cwd:t.cwd,projectId:t.projectId,workflowSlugs:[...e]}})).addDirtyTestsToScope??[];if(n.length===0){process.stdout.write(`No scope items added.
553
558
  `);return}let o=n.map(i=>i.workflow?.slug??"?").join(", ");process.stdout.write(`Added ${String(n.length)} scope item(s): ${o}
554
- `)}async function Ai({id:e,testId:t}){let r=me();await fe(r),await Ce(r.cwd,r);let n=await tg({cfg:r,slug:t});await g({config:r,document:Zf,variables:{id:e,workflowId:n}}),process.stdout.write(`Linked scope item ${e} to ${t}
555
- `)}async function Ii({ids:e}){let t=me();await fe(t);let n=(await g({config:t,document:eg,variables:{ids:[...e]}})).removeScopeItems??0;process.stdout.write(`Removed ${String(n)} scope item(s)
556
- `)}async function tg({cfg:e,slug:t}){let n=(await g({config:e,document:Qf,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.
559
+ `)}async function ji({id:e,testId:t}){let r=me();await fe(r),await Ee(r.cwd,r);let n=await cg({cfg:r,slug:t});await g({config:r,document:ag,variables:{id:e,workflowId:n}}),process.stdout.write(`Linked scope item ${e} to ${t}
560
+ `)}async function Ni({ids:e}){let t=me();await fe(t);let n=(await g({config:t,document:lg,variables:{ids:[...e]}})).removeScopeItems??0;process.stdout.write(`Removed ${String(n)} scope item(s)
561
+ `)}async function cg({cfg:e,slug:t}){let n=(await g({config:e,document:ig,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.
557
562
  `),process.stderr.write(`${w("create")}
558
- `),process.exit(1)),n.id}async function Ti(e){let t=process.cwd(),r=await C(t);r.ok||(process.stderr.write(`Compilation failed: ${r.error}
563
+ `),process.exit(1)),n.id}async function Oi(e){let t=process.cwd(),r=await C(t);r.ok||(process.stderr.write(`Compilation failed: ${r.error}
559
564
  `),process.exit(1));let{tests:n}=r.builder.getUnimplemented();if(e.format==="summary"){n.length>0&&process.stdout.write(`tests: ${n.join(", ")}
560
565
  `);return}let o={tests:n.map(i=>({id:i,implemented:!1}))};process.stdout.write(`${JSON.stringify(o,null,2)}
561
- `)}import{z as rg}from"zod";function E(e,t){let r=rg.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 tx}from"crypto";import $i from"picomatch";function ng(e){return q(["diff","--name-only","HEAD"],e).split(`
562
- `).filter(t=>t.length>0)}function ji({cwd:e,ignoreGlobs:t,watchGlobs:r}){let n=$i([...r]),o=$i([...t]);return ng(e).filter(i=>n(i)&&!o(i))}function zt(e,...t){return q(["diff","--name-only","HEAD","--",...t],e).split(`
563
- `).filter(r=>r.length>0)}import{createHash as og}from"crypto";import{mkdirSync as ig,readFileSync as Ni,writeFileSync as sg}from"fs";import nn from"path";var ag=[".ts",".tsx",".js",".jsx"];function We(e){let t=og("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(`
564
- `).filter(n=>n.length>0).filter(n=>ag.some(o=>n.endsWith(o))).toSorted((n,o)=>n.localeCompare(o)).forEach(n=>{t.update(n),t.update("\0"),t.update(lg(nn.join(e,n))),t.update("\0")}),t.digest("hex")}function Be(e,t){try{return Ni(Oi(e,t),"utf8").trim()}catch{return null}}function qe(e,t,r){let n=Oi(e,t);ig(nn.dirname(n),{recursive:!0}),sg(n,r)}function Oi(e,t){return nn.join(e,".ripplo",".local",`${t}.hash`)}function lg(e){try{return Ni(e)}catch{return Buffer.alloc(0)}}function Pe(){return{ignorePaths:ke,watchPaths:qr}}var Di=E("UserPromptSubmit",e=>{let{cwd:t}=e;if(!x(t)||!T(t))return;let r=We(t);if(Be(t,"coverage-nudge")===r)return;let{ignorePaths:n,watchPaths:o}=Pe(),i=ji({cwd:t,ignoreGlobs:n,watchGlobs:o});if(qe(t,"coverage-nudge",r),!(i.length===0||zt(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. ${w("scope")}`,hookEventName:"UserPromptSubmit"}}});import Gt from"fs";import cg from"os";import Li from"path";var _i=E("PreToolUse",e=>{if(e.tool_name!=="ExitPlanMode"||!T(e.cwd))return;let t=dg();if(t==null)return;let r=Gt.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. ${w("explore")}`}}});function dg(){let e=Li.join(cg.homedir(),".claude","plans");return Gt.existsSync(e)?Gt.readdirSync(e).filter(r=>r.endsWith(".md")).map(r=>Li.join(e,r)).map(r=>({full:r,mtime:Gt.statSync(r).mtimeMs})).sort((r,n)=>n.mtime-r.mtime)[0]?.full??null:null}var Ui=E("UserPromptSubmit",async e=>{if(e.permission_mode!=="plan"||!x(e.cwd)||!T(e.cwd))return;let t=await C(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(`
565
- `),hookEventName:"UserPromptSubmit"}}});import ug from"path";import Vi from"picomatch";import{z as Fi}from"zod";var pg=Fi.looseObject({file_path:Fi.string()}),Hi=E("PostToolUse",async e=>{let t=pg.safeParse(e.tool_input);if(!t.success)return;let r=t.data.file_path,{cwd:n}=e;if(!x(n)||!T(n))return;let o=ug.relative(n,r);if(o.startsWith(".."))return;let{ignorePaths:i,watchPaths:s}=Pe(),a=Vi([...s]),l=Vi([...i]);if(!a(o)||l(o))return;let c=await C(n);if(!c.ok)return;let{tests:p}=c.builder.getUnimplemented();if(p.length!==0)return{hookSpecificOutput:{additionalContext:`Reminder: .notImplemented() stubs still present \u2014 tests: ${p.join(", ")}`,hookEventName:"PostToolUse"}}});import{z as Mi}from"zod";var mg=Mi.looseObject({file_path:Mi.string()}),Wi=E("PostToolUse",async e=>{let t=mg.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(!x(n)||!T(n))return;let o=await C(n);if(!o.ok)return{decision:"block",reason:`Compilation failed: ${o.error}
566
- ${w("create","DSL authoring + lint rules")}`};await ce({cwd:n,result:o.result}),Ue({cwd:n});let{diagnostics:i}=Le(o.result);if(i.length===0){let{addedSlugs:a}=await Wt({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(`
566
+ `)}import{z as dg}from"zod";function E(e,t){let r=dg.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 dx}from"crypto";import Di from"picomatch";function ug(e){return z(["diff","--name-only","HEAD"],e).split(`
567
+ `).filter(t=>t.length>0)}function Li({cwd:e,ignoreGlobs:t,watchGlobs:r}){let n=Di([...r]),o=Di([...t]);return ug(e).filter(i=>n(i)&&!o(i))}function Gt(e,...t){return z(["diff","--name-only","HEAD","--",...t],e).split(`
568
+ `).filter(r=>r.length>0)}function xe(){return{ignorePaths:Se,watchPaths:zr}}var _i=E("UserPromptSubmit",e=>{let{cwd:t}=e;if(!x(t)||!$(t))return;let r=Re(t);if(We(t,"coverage-nudge")===r)return;let{ignorePaths:n,watchPaths:o}=xe(),i=Li({cwd:t,ignoreGlobs:n,watchGlobs:o});if(Be(t,"coverage-nudge",r),!(i.length===0||Gt(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. ${w("scope")}`,hookEventName:"UserPromptSubmit"}}});import Kt from"fs";import pg from"os";import Ui from"path";var Vi=E("PreToolUse",e=>{if(e.tool_name!=="ExitPlanMode"||!$(e.cwd))return;let t=mg();if(t==null)return;let r=Kt.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. ${w("explore")}`}}});function mg(){let e=Ui.join(pg.homedir(),".claude","plans");return Kt.existsSync(e)?Kt.readdirSync(e).filter(r=>r.endsWith(".md")).map(r=>Ui.join(e,r)).map(r=>({full:r,mtime:Kt.statSync(r).mtimeMs})).sort((r,n)=>n.mtime-r.mtime)[0]?.full??null:null}var Fi=E("UserPromptSubmit",async e=>{if(e.permission_mode!=="plan"||!x(e.cwd)||!$(e.cwd))return;let t=await C(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(`
569
+ `),hookEventName:"UserPromptSubmit"}}});import fg from"path";import Hi from"picomatch";import{z as Mi}from"zod";var gg=Mi.looseObject({file_path:Mi.string()}),Wi=E("PostToolUse",async e=>{let t=gg.safeParse(e.tool_input);if(!t.success)return;let r=t.data.file_path,{cwd:n}=e;if(!x(n)||!$(n))return;let o=fg.relative(n,r);if(o.startsWith(".."))return;let{ignorePaths:i,watchPaths:s}=xe(),a=Hi([...s]),l=Hi([...i]);if(!a(o)||l(o))return;let c=await C(n);if(!c.ok)return;let{tests:p}=c.builder.getUnimplemented();if(p.length!==0)return{hookSpecificOutput:{additionalContext:`Reminder: .notImplemented() stubs still present \u2014 tests: ${p.join(", ")}`,hookEventName:"PostToolUse"}}});import{z as Bi}from"zod";var yg=Bi.looseObject({file_path:Bi.string()}),qi=E("PostToolUse",async e=>{let t=yg.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(!x(n)||!$(n))return;let o=await C(n);if(!o.ok)return{decision:"block",reason:`Compilation failed: ${o.error}
570
+ ${w("create","DSL authoring + lint rules")}`};await ce({cwd:n,result:o.result}),Fe({cwd:n});let{diagnostics:i}=Ue(o.result);if(i.length===0){let{addedSlugs:a}=await Bt({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(`
567
571
  `)}
568
- ${w("create")}`}});import{z as Bi}from"zod";var fg=Bi.looseObject({command:Bi.string()}),gg=/\bripplo\s+hooks\s+pause\b/,qi=E("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=fg.safeParse(e.tool_input);if(!t.success||!gg.test(t.data.command))return;let{cwd:r}=e;if(x(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 vg}from"shell-quote";import{z as Ki}from"zod";import{existsSync as yg,mkdirSync as hg,rmSync as nC,writeFileSync as wg}from"fs";import on from"path";function zi(e,t,r){let n=Gi(e,t,r);hg(on.dirname(n),{recursive:!0}),wg(n,"")}function Kt(e,t,r){return yg(Gi(e,t,r))}function bg(e,t){return on.join(e,".ripplo",".local","skills-loaded",t)}function Gi(e,t,r){return on.join(bg(e,t),r)}var Sg=Ki.looseObject({command:Ki.string()}),kg="debug",Rg=new Set(["tail","head","less","more","wc","sort","uniq","awk","sed","grep"]),Xi=E("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=Sg.safeParse(e.tool_input);if(!t.success)return;let r=Pg(t.data.command);if(!xg(r))return;let{cwd:n}=e;if(!x(n)||!T(n))return;let o=Eg(r);if(o!=null)return Ji(`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(!Kt(n,e.session_id,kg))return Ji("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 Pg(e){try{return vg(e)}catch{return[]}}function xg(e){return e.some((t,r)=>t==="ripplo"&&e[r+1]==="run")}function Cg(e){return typeof e=="object"&&"op"in e&&e.op==="|"}function Eg(e){let t=e.find((r,n)=>{let o=e[n-1];return o!=null&&Cg(o)&&typeof r=="string"&&Rg.has(r)});return typeof t=="string"?t:null}function Ji(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}}}import Ag from"path";import{z as Qi}from"zod";var Ig=new Set(["Edit","Write","NotebookEdit"]),Tg=Qi.looseObject({file_path:Qi.string()}),$g="create",Yi=E("PreToolUse",e=>{if(!Ig.has(e.tool_name))return;let t=Tg.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!x(r)||!T(r))return;let n=Ag.relative(r,t.data.file_path);if(!(n.startsWith("..")||n!==".ripplo"&&!n.startsWith(".ripplo/"))&&!Kt(r,e.session_id,$g))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 jg from"path";import Zi from"picomatch";import{graphql as Ng}from"gql.tada";import{z as es}from"zod";var Og=new Set(["Edit","Write","NotebookEdit"]),Dg=es.looseObject({file_path:es.string()}),Lg=Ng(`
572
+ ${w("create")}`}});import{z as zi}from"zod";var hg=zi.looseObject({command:zi.string()}),wg=/\bripplo\s+hooks\s+pause\b/,Gi=E("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=hg.safeParse(e.tool_input);if(!t.success||!wg.test(t.data.command))return;let{cwd:r}=e;if(x(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 Rg}from"shell-quote";import{z as Xi}from"zod";import{existsSync as bg,mkdirSync as vg,rmSync as aC,writeFileSync as kg}from"fs";import sn from"path";function Ki(e,t,r){let n=Ji(e,t,r);vg(sn.dirname(n),{recursive:!0}),kg(n,"")}function Jt(e,t,r){return bg(Ji(e,t,r))}function Sg(e,t){return sn.join(e,".ripplo",".local","skills-loaded",t)}function Ji(e,t,r){return sn.join(Sg(e,t),r)}var Pg=Xi.looseObject({command:Xi.string()}),xg="debug",Cg=new Set(["tail","head","less","more","wc","sort","uniq","awk","sed","grep"]),Yi=E("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=Pg.safeParse(e.tool_input);if(!t.success)return;let r=Eg(t.data.command);if(!Ag(r))return;let{cwd:n}=e;if(!x(n)||!$(n))return;let o=$g(r);if(o!=null)return Qi(`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(!Jt(n,e.session_id,xg))return Qi("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 Eg(e){try{return Rg(e)}catch{return[]}}function Ag(e){return e.some((t,r)=>t==="ripplo"&&e[r+1]==="run")}function Ig(e){return typeof e=="object"&&"op"in e&&e.op==="|"}function $g(e){let t=e.find((r,n)=>{let o=e[n-1];return o!=null&&Ig(o)&&typeof r=="string"&&Cg.has(r)});return typeof t=="string"?t:null}function Qi(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}}}import Tg from"path";import{z as Zi}from"zod";var jg=new Set(["Edit","Write","NotebookEdit"]),Ng=Zi.looseObject({file_path:Zi.string()}),Og="create",es=E("PreToolUse",e=>{if(!jg.has(e.tool_name))return;let t=Ng.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!x(r)||!$(r))return;let n=Tg.relative(r,t.data.file_path);if(!(n.startsWith("..")||n!==".ripplo"&&!n.startsWith(".ripplo/"))&&!Jt(r,e.session_id,Og))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 Dg from"path";import ts from"picomatch";import{graphql as Lg}from"gql.tada";import{z as rs}from"zod";var _g=new Set(["Edit","Write","NotebookEdit"]),Ug=rs.looseObject({file_path:rs.string()}),Vg=Lg(`
569
573
  query PreEditScopeGate($projectId: String!, $cwd: String!) {
570
574
  project(id: $projectId) {
571
575
  id
@@ -577,7 +581,7 @@ ${w("create")}`}});import{z as Bi}from"zod";var fg=Bi.looseObject({command:Bi.st
577
581
  }
578
582
  }
579
583
  }
580
- `),ts=E("PreToolUse",async e=>{if(!Og.has(e.tool_name))return;let t=Dg.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!x(r)||!T(r))return;let n=jg.relative(r,t.data.file_path);if(!(n.startsWith("..")||n===".ripplo"||n.startsWith(".ripplo/")||!_g(n)||await Ug(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). ${_o(["scope","create"])}`}}});function _g(e){let{ignorePaths:t,watchPaths:r}=Pe(),n=Zi([...r]),o=Zi([...t]);return n(e)&&!o(e)}async function Ug(e){let t;try{t=_(e)}catch{return!0}let r=await g({config:t,document:Lg,variables:{cwd:t.cwd,projectId:t.projectId}}).catch(()=>null);return r==null?!0:(r.project?.devSession?.scopeItems??[]).length>0}import Vg from"fs";import Fg from"path";import{z as rs}from"zod";var Hg=new Set(["Edit","Write","NotebookEdit"]),Mg=rs.looseObject({file_path:rs.string()}),ns=E("PreToolUse",e=>{if(!Hg.has(e.tool_name))return;let t=Mg.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!x(r))return;let n=Fg.relative(r,t.data.file_path);if(!(n.startsWith("..")||n!==".ripplo"&&!n.startsWith(".ripplo/"))&&!Vg.existsSync(Re(r))&&!Fe(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. ${w("start")}`}}});import{graphql as Wg}from"gql.tada";var Bg=Wg(`
584
+ `),ns=E("PreToolUse",async e=>{if(!_g.has(e.tool_name))return;let t=Ug.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!x(r)||!$(r))return;let n=Dg.relative(r,t.data.file_path);if(!(n.startsWith("..")||n===".ripplo"||n.startsWith(".ripplo/")||!Fg(n)||await Hg(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). ${Uo(["scope","create"])}`}}});function Fg(e){let{ignorePaths:t,watchPaths:r}=xe(),n=ts([...r]),o=ts([...t]);return n(e)&&!o(e)}async function Hg(e){let t;try{t=_(e)}catch{return!0}let r=await g({config:t,document:Vg,variables:{cwd:t.cwd,projectId:t.projectId}}).catch(()=>null);return r==null?!0:(r.project?.devSession?.scopeItems??[]).length>0}import Mg from"fs";import Wg from"path";import{z as os}from"zod";var Bg=new Set(["Edit","Write","NotebookEdit"]),qg=os.looseObject({file_path:os.string()}),is=E("PreToolUse",e=>{if(!Bg.has(e.tool_name))return;let t=qg.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!x(r))return;let n=Wg.relative(r,t.data.file_path);if(!(n.startsWith("..")||n!==".ripplo"&&!n.startsWith(".ripplo/"))&&!Mg.existsSync(Pe(r))&&!Me(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. ${w("start")}`}}});import{graphql as zg}from"gql.tada";var Gg=zg(`
581
585
  query ScopeReminder($projectId: String!, $cwd: String!) {
582
586
  project(id: $projectId) {
583
587
  id
@@ -594,9 +598,9 @@ ${w("create")}`}});import{z as Bi}from"zod";var fg=Bi.looseObject({command:Bi.st
594
598
  }
595
599
  }
596
600
  }
597
- `),os=E("UserPromptSubmit",async e=>{let{cwd:t}=e;if(!x(t)||!T(t))return;let r=We(t);if(Be(t,"scope-reminder")===r)return;let n;try{n=_(t)}catch{return}let o=await g({config:n,document:Bg,variables:{cwd:n.cwd,projectId:n.projectId}}).catch(()=>null);if(o==null)return;qe(t,"scope-reminder",r);let i=o.project?.devSession?.scopeItems??[];return{hookSpecificOutput:{additionalContext:i.length===0?`RIPPLO SCOPE: empty. ${w("scope")}`:`RIPPLO SCOPE (${String(i.length)}):
601
+ `),ss=E("UserPromptSubmit",async e=>{let{cwd:t}=e;if(!x(t)||!$(t))return;let r=Re(t);if(We(t,"scope-reminder")===r)return;let n;try{n=_(t)}catch{return}let o=await g({config:n,document:Gg,variables:{cwd:n.cwd,projectId:n.projectId}}).catch(()=>null);if(o==null)return;Be(t,"scope-reminder",r);let i=o.project?.devSession?.scopeItems??[];return{hookSpecificOutput:{additionalContext:i.length===0?`RIPPLO SCOPE: empty. ${w("scope")}`:`RIPPLO SCOPE (${String(i.length)}):
598
602
  ${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(`
599
- `)}`,hookEventName:"UserPromptSubmit"}}});var qg="# 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",is=E("SessionStart",e=>{if(x(e.cwd))return{hookSpecificOutput:{additionalContext:qg,hookEventName:"SessionStart"}}});import{execFileSync as zg}from"child_process";import Gg from"path";import ss from"process";import{graphql as Kg}from"gql.tada";import{z as Jt}from"zod";var Jg=Kg(`
603
+ `)}`,hookEventName:"UserPromptSubmit"}}});var Kg="# 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",as=E("SessionStart",e=>{if(x(e.cwd))return{hookSpecificOutput:{additionalContext:Kg,hookEventName:"SessionStart"}}});import{execFileSync as Jg}from"child_process";import Xg from"path";import ls from"process";import{graphql as Qg}from"gql.tada";import{z as Xt}from"zod";var Yg=Qg(`
600
604
  query ScopeEnforce($projectId: String!, $cwd: String!) {
601
605
  project(id: $projectId) {
602
606
  id
@@ -615,14 +619,14 @@ ${i.map(a=>{let l=a.workflow;return l==null?` [intent] (${a.id}) ${a.label??""}
615
619
  }
616
620
  }
617
621
  }
618
- `),ls=E("Stop",async e=>{let{cwd:t}=e;if(!x(t)||!T(t))return;let r=We(t),n=Be(t,"stop-enforce")===r;if(n&&!e.stop_hook_active)return;let o=Xg(t),i=await Qg(t,o);if(qe(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:
622
+ `),ds=E("Stop",async e=>{let{cwd:t}=e;if(!x(t)||!$(t))return;let r=Re(t),n=We(t,"stop-enforce")===r;if(n&&!e.stop_hook_active)return;let o=Zg(t),i=await ey(t,o);if(Be(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:
619
623
  ${i.join(`
620
624
 
621
625
  `)}`}:{decision:"block",reason:i.join(`
622
626
 
623
- `)}});function Xg(e){return zt(e,".ripplo/tests").filter(t=>t.endsWith(".ts")).map(t=>Gg.basename(t,".ts")).filter(t=>t!=="index")}async function Qg(e,t){let r=await C(e);if(!r.ok)return[`--- Compilation failed ---
627
+ `)}});function Zg(e){return Gt(e,".ripplo/tests").filter(t=>t.endsWith(".ts")).map(t=>Xg.basename(t,".ts")).filter(t=>t!=="index")}async function ey(e,t){let r=await C(e);if(!r.ok)return[`--- Compilation failed ---
624
628
  ${r.error}
625
- ${w("create")}`];await ce({cwd:e,result:r.result}),Ue({cwd:e});let n=await Zg(e),o=[...new Set([...t,...n.scopedSlugsToRun])],i=ey(r,t),s=ty(r),a=Yg(e,r),l=ry(e,o);return[i,s,a,l,n.error].filter(c=>c!=null)}function Yg(e,t){let{ignorePaths:r}=Pe(),n=Vo({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(`
629
+ ${w("create")}`];await ce({cwd:e,result:r.result}),Fe({cwd:e});let n=await ry(e),o=[...new Set([...t,...n.scopedSlugsToRun])],i=ny(r,t),s=oy(r),a=ty(e,r),l=iy(e,o);return[i,s,a,l,n.error].filter(c=>c!=null)}function ty(e,t){let{ignorePaths:r}=xe(),n=Fo({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(`
626
630
  `);s.push(`Unacknowledged interactions (add to a test's .coverage(...)):
627
631
  ${a}`)}if(i.length>0){let a=i.map(l=>` ${l.id}`).join(`
628
632
  `);s.push(`Stale .coverage(...) claims (id no longer exists in source):
@@ -630,23 +634,23 @@ ${a}`)}return`--- Exhaustiveness ---
630
634
  ${s.join(`
631
635
 
632
636
  `)}
633
- ${w("create")}`}async function Zg(e){let t;try{t=_(e)}catch{return{error:null,scopedSlugsToRun:[]}}let n=(await g({config:t,document:Jg,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 ---
637
+ ${w("create")}`}async function ry(e){let t;try{t=_(e)}catch{return{error:null,scopedSlugsToRun:[]}}let n=(await g({config:t,document:Yg,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 ---
634
638
  ${o.join(`
635
639
  `)}
636
- ${w("create")}`,scopedSlugsToRun:i}}function ey(e,t){let{diagnostics:r}=Le(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 ---
640
+ ${w("create")}`,scopedSlugsToRun:i}}function ny(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 ---
637
641
  ${[...i,...s].join(`
638
642
  `)}
639
- ${w("create")}`}function ty(e){let{tests:t}=e.builder.getUnimplemented();return t.length===0?null:`--- Unimplemented stubs ---
643
+ ${w("create")}`}function oy(e){let{tests:t}=e.builder.getUnimplemented();return t.length===0?null:`--- Unimplemented stubs ---
640
644
  ${t.join(", ")}
641
645
  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.
642
- ${w("create")}`}function ry(e,t){if(t.length===0)return null;let r=oy(["run",...t],e);if(r.code===0)return null;let n=r.output.split(`
646
+ ${w("create")}`}function iy(e,t){if(t.length===0)return null;let r=ay(["run",...t],e);if(r.code===0)return null;let n=r.output.split(`
643
647
  `).filter(o=>/FAILED/.test(o)).join(`
644
648
  `);return n.length===0?null:`--- Ripplo Run Failures (${t.join(" ")}) ---
645
649
  ${n}
646
- Artifacts: .ripplo/debug/<runId>/. ${w("debug")}`}var ny=Jt.object({status:Jt.number().nullish(),stderr:Jt.unknown().optional(),stdout:Jt.unknown().optional()});function as(e){return e instanceof Buffer?e.toString("utf8"):typeof e=="string"?e:""}function oy(e,t){let r=ss.argv[1];if(r==null)return{code:1,output:""};try{return{code:0,output:zg(ss.execPath,[r,...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}}catch(n){let o=ny.safeParse(n);if(!o.success)return{code:1,output:""};let i=`${as(o.data.stdout)}${as(o.data.stderr)}`;return{code:o.data.status??1,output:i}}}import{z as cs}from"zod";var iy=cs.looseObject({skill:cs.string()}),ds=E("PostToolUse",e=>{if(e.tool_name!=="Skill")return;let t=iy.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&&x(e.cwd)&&zi(e.cwd,e.session_id,n)});gy();pn(process.cwd());var us={"coverage-nudge":Di,"exit-plan-gate":_i,"plan-reminder":Ui,"post-edit-flag-stubs":Hi,"post-edit-lint":Wi,"pre-bash-hooks-pause-gate":qi,"pre-bash-run-gate":Xi,"pre-edit-ripplo-skill-gate":Yi,"pre-edit-scope-gate":ts,"pre-edit-watch-gate":ns,"scope-reminder":os,"session-preamble":is,"stop-enforce":ls,"track-skill-load":ds};async function ly(){await sy(ay(process.argv)).scriptName("ripplo").version("0.4.15").command("watch","Watch for run requests and execute locally",()=>{},()=>Pi()).command("auth <subcommand>","Manage authentication",fy).command("projects <subcommand>","Inspect Ripplo projects",my).command("hooks <subcommand>","Pause or resume Ripplo hooks",py).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=>gi({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=>vi(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=>wi({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=>ai({id:e.id,runs:e.runs})).command("sync","Push the compiled .ripplo/ resources to the server (no run)",()=>{},()=>Si()).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=>Uo({check:e.check})).command("cover","Audit all coverage statements",()=>{},()=>Wo()).command("doctor","Check project health",()=>{},()=>ni()).command("status","Report unimplemented tests and preconditions",e=>e.option("format",{choices:["json","summary"],default:"json",describe:"Output format"}),e=>Ti({format:e.format})).command("scope <subcommand>","Manage testing scope",uy).command("hook <name>","Internal: run a Claude Code plugin hook",e=>e.positional("name",{choices:Object.keys(us),demandOption:!0,type:"string"}),e=>cy(e.name)).strict().help().parse()}async function cy(e){let t=us[e];t==null&&(process.stderr.write(`Unknown hook: ${e}
647
- `),process.exit(1));let r=await dy(),n=r.trim()===""?{}:JSON.parse(r),o=await t.run(n);o!=null&&process.stdout.write(JSON.stringify(o))}function dy(){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)})}ly().catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
648
- `),process.exit(1)});function uy(e){return e.command("status","Print the current scope",t=>t.option("format",{choices:["json","text"],default:"text",describe:"Output format"}),t=>Ci({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=>Ei({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=>Ai({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=>Ii({ids:t.ids})).demandCommand(1)}function py(e){return e.command("pause","Disable all Ripplo pre-edit gates and stop enforcement until resumed",()=>{},()=>li()).command("resume","Re-enable Ripplo hooks paused via `ripplo hooks pause`",()=>{},()=>ci()).demandCommand(1)}function my(e){return e.command("list","List projects you have access to (JSON)",()=>{},()=>bi()).demandCommand(1)}function fy(e){return e.command("login","Authenticate via device flow",()=>{},()=>uo()).command("status","Show authentication status",()=>{},()=>po()).command("logout","Remove the saved token",()=>{},()=>{mo()}).demandCommand(1)}function gy(){let e=process.cwd(),t=Qt(e);t!=null&&t!==e&&(process.chdir(t),process.stderr.write(`ripplo: resolved .ripplo/ at ${t}
649
- `))}export{ly as main};
650
+ Artifacts: .ripplo/debug/<runId>/. ${w("debug")}`}var sy=Xt.object({status:Xt.number().nullish(),stderr:Xt.unknown().optional(),stdout:Xt.unknown().optional()});function cs(e){return e instanceof Buffer?e.toString("utf8"):typeof e=="string"?e:""}function ay(e,t){let r=ls.argv[1];if(r==null)return{code:1,output:""};try{return{code:0,output:Jg(ls.execPath,[r,...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}}catch(n){let o=sy.safeParse(n);if(!o.success)return{code:1,output:""};let i=`${cs(o.data.stdout)}${cs(o.data.stderr)}`;return{code:o.data.status??1,output:i}}}import{z as us}from"zod";var ly=us.looseObject({skill:us.string()}),ps=E("PostToolUse",e=>{if(e.tool_name!=="Skill")return;let t=ly.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&&x(e.cwd)&&Ki(e.cwd,e.session_id,n)});wy();mn(process.cwd());var ms={"coverage-nudge":_i,"exit-plan-gate":Vi,"plan-reminder":Fi,"post-edit-flag-stubs":Wi,"post-edit-lint":qi,"pre-bash-hooks-pause-gate":Gi,"pre-bash-run-gate":Yi,"pre-edit-ripplo-skill-gate":es,"pre-edit-scope-gate":ns,"pre-edit-watch-gate":is,"scope-reminder":ss,"session-preamble":as,"stop-enforce":ds,"track-skill-load":ps};async function uy(){await cy(dy(process.argv)).scriptName("ripplo").version("0.4.16").command("watch","Watch for run requests and execute locally",()=>{},()=>Ai()).command("auth <subcommand>","Manage authentication",hy).command("projects <subcommand>","Inspect Ripplo projects",yy).command("hooks <subcommand>","Pause or resume Ripplo hooks",gy).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=>bi({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=>Pi(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=>Si({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=>ui({id:e.id,runs:e.runs})).command("sync","Push the compiled .ripplo/ resources to the server (no run)",()=>{},()=>xi()).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=>Vo({check:e.check})).command("cover","Audit all coverage statements",()=>{},()=>Bo()).command("doctor","Check project health",()=>{},()=>oi()).command("status","Report unimplemented tests and preconditions",e=>e.option("format",{choices:["json","summary"],default:"json",describe:"Output format"}),e=>Oi({format:e.format})).command("scope <subcommand>","Manage testing scope",fy).command("hook <name>","Internal: run a Claude Code plugin hook",e=>e.positional("name",{choices:Object.keys(ms),demandOption:!0,type:"string"}),e=>py(e.name)).strict().help().parse()}async function py(e){let t=ms[e];t==null&&(process.stderr.write(`Unknown hook: ${e}
651
+ `),process.exit(1));let r=await my(),n=r.trim()===""?{}:JSON.parse(r),o=await t.run(n);o!=null&&process.stdout.write(JSON.stringify(o))}function my(){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)})}uy().catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
652
+ `),process.exit(1)});function fy(e){return e.command("status","Print the current scope",t=>t.option("format",{choices:["json","text"],default:"text",describe:"Output format"}),t=>$i({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=>Ti({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=>ji({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=>Ni({ids:t.ids})).demandCommand(1)}function gy(e){return e.command("pause","Disable all Ripplo pre-edit gates and stop enforcement until resumed",()=>{},()=>pi()).command("resume","Re-enable Ripplo hooks paused via `ripplo hooks pause`",()=>{},()=>mi()).demandCommand(1)}function yy(e){return e.command("list","List projects you have access to (JSON)",()=>{},()=>Ri()).demandCommand(1)}function hy(e){return e.command("login","Authenticate via device flow",()=>{},()=>po()).command("status","Show authentication status",()=>{},()=>mo()).command("logout","Remove the saved token",()=>{},()=>{fo()}).demandCommand(1)}function wy(){let e=process.cwd(),t=Yt(e);t!=null&&t!==e&&(process.chdir(t),process.stderr.write(`ripplo: resolved .ripplo/ at ${t}
653
+ `))}export{uy as main};
650
654
  /*! Bundled license information:
651
655
 
652
656
  mustache/mustache.mjs: