ripplo 0.4.17 → 0.4.19

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 +151 -151
  2. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- var cn=Object.defineProperty;var gs=Object.getOwnPropertyDescriptor;var ys=Object.getOwnPropertyNames;var hs=Object.prototype.hasOwnProperty;var ws=(e,t)=>{for(var r in t)cn(e,r,{get:t[r],enumerable:!0})},ln=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ys(t))!hs.call(e,o)&&o!==r&&cn(e,o,{get:()=>t[o],enumerable:!(n=gs(t,o))||n.enumerable});return e},Qt=(e,t,r)=>(ln(e,t,"default"),r&&ln(r,t,"default"));import{execFileSync as bs}from"child_process";import vs from"fs";import pt from"path";function Zt(e){let t=ks(e);return t??dn(e)}function dn(e){let t=pt.dirname(e);return Ss(pt.join(e,".ripplo"))?e:t===e?null:dn(t)}function Ss(e){try{return vs.statSync(e).isDirectory()}catch{return!1}}function ks(e){let t=Rs(["rev-parse","--show-toplevel"],e);if(t==null)return null;let r=t.trim();return r.length===0?null:pt.isAbsolute(r)?r:pt.resolve(e,r)}function Rs(e,t){try{return bs("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return null}}import mn from"fs";import gt from"path";import{config as Cs}from"dotenv";import{z as ft}from"zod";import Je from"fs";import tr from"path";import{z as mt}from"zod";var un=tr.join(".ripplo","project.json"),er=[".env",".env.local"],Ps=mt.object({envFiles:mt.array(mt.string().min(1)).optional(),projectId:mt.string().min(1)});function rr(e){return tr.join(e,un)}function nr(e){let t=rr(e);if(!Je.existsSync(t))throw new Error(`ripplo: missing ${un}. Run \`ripplo init\` to create it.`);let r=JSON.parse(Je.readFileSync(t,"utf8")),n=Ps.parse(r);return{envFiles:n.envFiles??er,projectId:n.projectId}}function or(e){let t=rr(e);if(Je.existsSync(t))try{return nr(e)}catch{return}}function pn({cwd:e,envFiles:t,projectId:r}){let n=rr(e);Je.mkdirSync(tr.dirname(n),{recursive:!0});let o={projectId:r};t!=null&&!xs(t)&&(o.envFiles=[...t]),Je.writeFileSync(n,JSON.stringify(o,null,2)+`
3
- `)}function xs(e){return e.length!==er.length?!1:e.every((t,r)=>t===er[r])}function fn(e){let r=or(e)?.envFiles??[".env",".env.local"],n=gt.join(e,".ripplo");r.forEach(o=>{let i=gt.resolve(n,o);mn.existsSync(i)&&Cs({override:!0,path:i,quiet:!0})}),ir=void 0}var Es=ft.object({RIPPLO_APP_URL:ft.url(),RIPPLO_ENGINE_URL:ft.url(),RIPPLO_WEBHOOK_SECRET:ft.string().min(1)}),ir;function Te(){return ir??=As(),ir}function As(){let e=Es.safeParse(process.env);if(!e.success){let r=e.error.issues.map(s=>` ${s.path.join(".")}: ${s.message}`).join(`
4
- `),n=sr(process.cwd()),o=n.map(s=>` ${s}`).join(`
2
+ var pn=Object.defineProperty;var Ps=Object.getOwnPropertyDescriptor;var xs=Object.getOwnPropertyNames;var Es=Object.prototype.hasOwnProperty;var Cs=(e,t)=>{for(var r in t)pn(e,r,{get:t[r],enumerable:!0})},un=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of xs(t))!Es.call(e,o)&&o!==r&&pn(e,o,{get:()=>t[o],enumerable:!(n=Ps(t,o))||n.enumerable});return e},tr=(e,t,r)=>(un(e,t,"default"),r&&un(r,t,"default"));import{execFileSync as As}from"child_process";import Is from"fs";import ft from"path";function rr(e){let t=$s(e);return t??mn(e)}function mn(e){let t=ft.dirname(e);return Ts(ft.join(e,".ripplo"))?e:t===e?null:mn(t)}function Ts(e){try{return Is.statSync(e).isDirectory()}catch{return!1}}function $s(e){let t=js(["rev-parse","--show-toplevel"],e);if(t==null)return null;let r=t.trim();return r.length===0?null:ft.isAbsolute(r)?r:ft.resolve(e,r)}function js(e,t){try{return As("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return null}}import yn from"fs";import ht from"path";import{config as Ds}from"dotenv";import{z as yt}from"zod";import Xe from"fs";import or from"path";import{z as gt}from"zod";var fn=or.join(".ripplo","project.json"),nr=[".env",".env.local"],Ns=gt.object({envFiles:gt.array(gt.string().min(1)).optional(),projectId:gt.string().min(1)});function ir(e){return or.join(e,fn)}function sr(e){let t=ir(e);if(!Xe.existsSync(t))throw new Error(`ripplo: missing ${fn}. Run \`ripplo init\` to create it.`);let r=JSON.parse(Xe.readFileSync(t,"utf8")),n=Ns.parse(r);return{envFiles:n.envFiles??nr,projectId:n.projectId}}function ar(e){let t=ir(e);if(Xe.existsSync(t))try{return sr(e)}catch{return}}function gn({cwd:e,envFiles:t,projectId:r}){let n=ir(e);Xe.mkdirSync(or.dirname(n),{recursive:!0});let o={projectId:r};t!=null&&!Os(t)&&(o.envFiles=[...t]),Xe.writeFileSync(n,JSON.stringify(o,null,2)+`
3
+ `)}function Os(e){return e.length!==nr.length?!1:e.every((t,r)=>t===nr[r])}function hn(e){let r=ar(e)?.envFiles??[".env",".env.local"],n=ht.join(e,".ripplo");r.forEach(o=>{let i=ht.resolve(n,o);yn.existsSync(i)&&Ds({override:!0,path:i,quiet:!0})}),lr=void 0}var Ls=yt.object({RIPPLO_APP_URL:yt.url(),RIPPLO_ENGINE_URL:yt.url(),RIPPLO_WEBHOOK_SECRET:yt.string().min(1)}),lr;function Te(){return lr??=_s(),lr}function _s(){let e=Ls.safeParse(process.env);if(!e.success){let r=e.error.issues.map(s=>` ${s.path.join(".")}: ${s.message}`).join(`
4
+ `),n=cr(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,23 +9,23 @@ ${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 sr(e){let r=or(e)?.envFiles??[],n=gt.join(e,".ripplo");return r.map(o=>gt.resolve(n,o)).filter(o=>!mn.existsSync(o))}import fy from"yargs";import{hideBin as gy}from"yargs/helpers";import{graphql as Yc}from"gql.tada";async function yt(e,t,r){let n;try{return n=await e.context().newCDPSession(e),await r(n)}catch{return t}finally{await n?.detach().catch(()=>{})}}async function q({awaitPromise:e,expression:t,page:r}){return yt(r,void 0,async n=>{let o=await n.send("Runtime.evaluate",{awaitPromise:e,expression:t,returnByValue:!0});if(o.exceptionDetails==null)return o.result.value})}var Is=Object.prototype.toString,je=Array.isArray||function(t){return Is.call(t)==="[object Array]"};function lr(e){return typeof e=="function"}function Ts(e){return je(e)?"array":typeof e}function ar(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function gn(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 js=RegExp.prototype.test;function Ns(e,t){return js.call(e,t)}var Os=/\S/;function Ds(e){return!Ns(Os,e)}var Ls={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function _s(e){return String(e).replace(/[&<>"'`=\/]/g,function(r){return Ls[r]})}var Us=/\s*/,Vs=/\s+/,yn=/\s*=/,Fs=/\s*\}/,Hs=/#|\^|\/|>|\{|&|=|!/;function Ms(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,k,j;function N(oe){if(typeof oe=="string"&&(oe=oe.split(Vs,2)),!je(oe)||oe.length!==2)throw new Error("Invalid tags: "+oe);m=new RegExp(ar(oe[0])+"\\s*"),k=new RegExp("\\s*"+ar(oe[1])),j=new RegExp("\\s*"+ar("}"+oe[1]))}N(t||Z.tags);for(var g=new Ye(e),B,$,V,ne,Ie,se;!g.eos();){if(B=g.pos,V=g.scanUntil(m),V)for(var Ke=0,W=V.length;Ke<W;++Ke)ne=V.charAt(Ke),Ds(ne)?(i.push(o.length),l+=ne):(a=!0,r=!0,l+=" "),o.push(["text",ne,B,B+1]),B+=1,ne===`
13
- `&&(p(),l="",c=0,r=!1);if(!g.scan(m))break;if(s=!0,$=g.scan(Hs)||"name",g.scan(Us),$==="="?(V=g.scanUntil(yn),g.scan(yn),g.scanUntil(k)):$==="{"?(V=g.scanUntil(j),g.scan(Fs),g.scanUntil(k),$="&"):V=g.scanUntil(k),!g.scan(k))throw new Error("Unclosed tag at "+g.pos);if($==">"?Ie=[$,V,B,g.pos,l,c,r]:Ie=[$,V,B,g.pos],c++,o.push(Ie),$==="#"||$==="^")n.push(Ie);else if($==="/"){if(se=n.pop(),!se)throw new Error('Unopened section "'+V+'" at '+B);if(se[1]!==V)throw new Error('Unclosed section "'+se[1]+'" at '+B)}else $==="name"||$==="{"||$==="&"?a=!0:$==="="&&N(V)}if(p(),se=n.pop(),se)throw new Error('Unclosed section "'+se[1]+'" at '+g.pos);return Ws(Bs(o))}function Bs(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 Ye(e){this.string=e,this.tail=e,this.pos=0}Ye.prototype.eos=function(){return this.tail===""};Ye.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};Ye.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 $e(e,t){this.view=e,this.cache={".":this.view},this.parent=t}$e.prototype.push=function(t){return new $e(t,this)};$e.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=gn(i,s[a])||$s(i,s[a])),i=i[s[a++]];else i=o.view[t],l=gn(o.view,t);if(l){n=i;break}o=o.parent}r[t]=n}return lr(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=Ms(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 $e?r:new $e(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(k){return s.render(k,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(lr(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(`
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 cr(e){let r=ar(e)?.envFiles??[],n=ht.join(e,".ripplo");return r.map(o=>ht.resolve(n,o)).filter(o=>!yn.existsSync(o))}import Ly from"yargs";import{hideBin as _y}from"yargs/helpers";import{graphql as ud}from"gql.tada";import ia from"path";import{AsyncLocalStorage as Us}from"async_hooks";import Vs from"path";var Fs=new Us;function wn(){let e=Fs.getStore();return e!=null?e.fixturesDir:Vs.join(process.cwd(),".ripplo","fixtures")}async function wt(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 wt(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 Hs=Object.prototype.toString,je=Array.isArray||function(t){return Hs.call(t)==="[object Array]"};function ur(e){return typeof e=="function"}function Ms(e){return je(e)?"array":typeof e}function dr(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function bn(e,t){return e!=null&&typeof e=="object"&&t in e}function Bs(e,t){return e!=null&&typeof e!="object"&&e.hasOwnProperty&&e.hasOwnProperty(t)}var Ws=RegExp.prototype.test;function qs(e,t){return Ws.call(e,t)}var zs=/\S/;function Gs(e){return!qs(zs,e)}var Ks={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function Js(e){return String(e).replace(/[&<>"'`=\/]/g,function(r){return Ks[r]})}var Xs=/\s*/,Ys=/\s+/,vn=/\s*=/,Qs=/\s*\}/,Zs=/#|\^|\/|>|\{|&|=|!/;function ea(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,k,N;function O(oe){if(typeof oe=="string"&&(oe=oe.split(Ys,2)),!je(oe)||oe.length!==2)throw new Error("Invalid tags: "+oe);m=new RegExp(dr(oe[0])+"\\s*"),k=new RegExp("\\s*"+dr(oe[1])),N=new RegExp("\\s*"+dr("}"+oe[1]))}O(t||Z.tags);for(var g=new Qe(e),W,j,V,ne,Ie,se;!g.eos();){if(W=g.pos,V=g.scanUntil(m),V)for(var Je=0,q=V.length;Je<q;++Je)ne=V.charAt(Je),Gs(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(!g.scan(m))break;if(s=!0,j=g.scan(Zs)||"name",g.scan(Xs),j==="="?(V=g.scanUntil(vn),g.scan(vn),g.scanUntil(k)):j==="{"?(V=g.scanUntil(N),g.scan(Qs),g.scanUntil(k),j="&"):V=g.scanUntil(k),!g.scan(k))throw new Error("Unclosed tag at "+g.pos);if(j==">"?Ie=[j,V,W,g.pos,l,c,r]:Ie=[j,V,W,g.pos],c++,o.push(Ie),j==="#"||j==="^")n.push(Ie);else if(j==="/"){if(se=n.pop(),!se)throw new Error('Unopened section "'+V+'" at '+W);if(se[1]!==V)throw new Error('Unclosed section "'+se[1]+'" at '+W)}else j==="name"||j==="{"||j==="&"?a=!0:j==="="&&O(V)}if(p(),se=n.pop(),se)throw new Error('Unclosed section "'+se[1]+'" at '+g.pos);return ra(ta(o))}function ta(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 ra(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 Qe(e){this.string=e,this.tail=e,this.pos=0}Qe.prototype.eos=function(){return this.tail===""};Qe.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};Qe.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 $e(e,t){this.view=e,this.cache={".":this.view},this.parent=t}$e.prototype.push=function(t){return new $e(t,this)};$e.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=bn(i,s[a])||Bs(i,s[a])),i=i[s[a++]];else i=o.view[t],l=bn(o.view,t);if(l){n=i;break}o=o.parent}r[t]=n}return ur(n)&&(n=n.call(this.view)),n};function B(){this.templateCache={_cache:{},set:function(t,r){this._cache[t]=r},get:function(t){return this._cache[t]},clear:function(){this._cache={}}}}B.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};B.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=ea(t,r),i&&n.set(o,s)),s};B.prototype.render=function(t,r,n,o){var i=this.getConfigTags(o),s=this.parse(t,i),a=r instanceof $e?r:new $e(r,void 0);return this.renderTokens(s,a,n,t,o)};B.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};B.prototype.renderSection=function(t,r,n,o,i){var s=this,a="",l=r.lookup(t[1]);function c(k){return s.render(k,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(ur(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}};B.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)};B.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
- `)};M.prototype.renderPartial=function(t,r,n,o){if(n){var i=this.getConfigTags(o),s=lr(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){Xe.templateCache=e},get templateCache(){return Xe.templateCache}},Xe=new M;Z.clearCache=function(){return Xe.clearCache()};Z.parse=function(t,r){return Xe.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 "'+Ts(t)+'" was given as the first argument for mustache#render(template, view, partials)');return Xe.render(t,r,n,o)};Z.escape=_s;Z.Scanner=Ye;Z.Context=$e;Z.Writer=M;var hn=Z;function cr({defs:e}){return e==null?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,zs({def:r,name:t})]))}var qs={boolean:!1,number:0,string:""};function zs({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??qs[e.type]??""}function ht({ref:e,variables:t}){if(e.type==="static")return e.value;let r=t[e.name];if(r==null||typeof r=="object")throw new Error(`Variable "${e.name}" is not defined`);return r}function z({ref:e,variables:t}){let r=String(ht({ref:e,variables:t}));return bt({raw:r,variables:t})}function wt({ref:e,variables:t}){let r=ht({ref:e,variables:t});return typeof r=="string"?bt({raw:r,variables:t}):r}function bt({raw:e,variables:t}){return hn.render(e,t,{},{escape:r=>r})}function dr({ref:e,variables:t}){let r=ht({ref:e,variables:t});if(typeof r=="number")return r;let n=Number(r);if(Number.isNaN(n))throw new TypeError(`Cannot convert "${String(r)}" to number`);return n}function 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(wn(e.value,r));case"role":return t.getByRole(e.role,{exact:!0,name:e.name==null?void 0:wn(e.name,r)})}}function wn(e,t){return t==null?e:bt({raw:e,variables:t})}async function bn({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 vn({node:e,page:t,timeout:r}){await O({locator:e.locator,page:t,variables:void 0}).click({button:"right",timeout:r})}function Sn({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=z({ref:e.value,variables:r}),i=JSON.stringify(o);return await q({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 q({awaitPromise:!0,expression:"navigator.clipboard.readText()",page:t})??"";return{variables:Ne({name:e.variable,store:r,value:n})}}async function Rn({node:e,page:t}){let r=t.context();e.state==="granted"?await r.grantPermissions([e.permission]):await r.clearPermissions()}async function ur({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 Ks({node:e,page:t,timeout:r,variables:n});case"rightClick":return await vn({node:e,page:t,timeout:r}),{variables:n};case"goto":{let o=z({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 q({awaitPromise:!0,expression:"new Promise((resolve) => { requestAnimationFrame(() => requestAnimationFrame(() => resolve(undefined))); })",page:t}),{variables:n}}case"fill":return Xs({node:e,page:t,timeout:r,variables:n});case"select":return Ys({node:e,page:t,timeout:r,variables:n});case"type":return Qs({node:e,page:t,timeout:r,variables:n});case"press":return await Js({node:e,page:t,timeout:r}),{variables:n};case"drag":return await bn({node:e,page:t,timeout:r}),{variables:n};case"upload":return Zs({node:e,page:t,timeout:r,variables:n});case"extractText":return ea({node:e,page:t,timeout:r,variables:n});case"setVariable":{let o=wt({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 Sn({node:e,page:t,variables:n});case"clipboard":return kn({node:e,page:t,variables:n});case"setPermission":return await Rn({node:e,page:t}),{variables:n}}}var Gs={check:"check",clear:"clear",click:"click",dblclick:"dblclick",focus:"focus",hover:"hover",scrollIntoView:"scrollIntoViewIfNeeded",uncheck:"uncheck"};async function Ks({node:e,page:t,timeout:r,variables:n}){return await O({locator:e.locator,page:t,variables:n})[Gs[e.type]]({timeout:r}),{variables:n}}async function Js({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 Xs({node:e,page:t,timeout:r,variables:n}){let o=z({ref:e.value,variables:n});return await O({locator:e.locator,page:t,variables:n}).fill(o,{timeout:r}),{variables:n}}async function Ys({node:e,page:t,timeout:r,variables:n}){let o=z({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=z({ref:e.value,variables:n});return await O({locator:e.locator,page:t,variables:n}).pressSequentially(o,{timeout:r}),{variables:n}}async function Zs({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 ea({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={};ws(F,{default:()=>ta});Qt(F,eh);import*as eh from"playwright/test";import{default as ta}from"playwright/test";async function pr({expected:e,locator:t,operator:r,timeout:n}){await Qe({expected:e,operator:r,timeout:n,read:async()=>await t.textContent()??""});let o=await Ze(async()=>await t.textContent()??"");return Oe({actual:o,expected:e,label:"Text",operator:r})}async function mr({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 Pn({expected:e,operator:t,page:r,timeout:n}){await Qe({expected:e,operator:t,timeout:n,read:()=>r.title()});let o=await Ze(()=>r.title());return Oe({actual:o,expected:e,label:"Title",operator:t})}async function fr({expected:e,locator:t,operator:r,timeout:n}){await F.expect.poll(async()=>On({actual:await t.count(),expected:e,operator:r}),{timeout:n}).toBe(!0).catch(()=>{});let o=await t.count();return Nn({actual:o,expected:e,label:"Count",operator:r})}async function gr({expected:e,locator:t,operator:r,timeout:n}){await Qe({expected:e,operator:r,timeout:n,read:()=>t.inputValue()});let o=await Ze(()=>t.inputValue());return Oe({actual:o,expected:e,label:"Value",operator:r})}async function yr({locator:e,timeout:t}){return ge({description:"Element is visible",failureDetail:"Element not visible",run:()=>(0,F.expect)(e).toBeVisible({timeout:t})})}async function hr({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 xn({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 Ze(async()=>await r.getAttribute(e)??"");return Oe({actual:i,expected:t,label:`Attribute "${e}"`,operator:n})}async function Cn({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 En({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 An({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 In({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 Tn({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 Ze(r);return jn({actual:o,expected:e,operator:t})},{timeout:n}).toBe(!0).catch(()=>{})}async function Ze(e){return e().catch(()=>"")}function Oe(e){let t=`${e.label} ${e.operator} "${e.expected}"`,r=jn(e),n=r?void 0:`Got: "${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==="contains"?e.includes(t):r==="startsWith"?e.startsWith(t):r==="endsWith"?e.endsWith(t):new RegExp(t).test(e)}function Nn(e){let t=`${e.label} ${e.operator} ${String(e.expected)}`,r=On(e),n=r?void 0:`Got: ${String(e.actual)}`;return{description:t,detail:n,status:r?"passed":"failed"}}function On({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 na}from"child_process";import{createRequire as oa}from"module";import Dn from"fs";import Ln from"path";import{chromium as _n}from"playwright";import ih from"fs";import ah from"path";import ra from"pino";var y=ra({transport:{options:{ignore:"pid,hostname"},target:"pino-pretty"}});async function et({headed:e}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";try{return await _n.launch({headless:!e})}catch(t){throw ia(t)?new Error(`Playwright browsers are not installed. Run:
15
+ `)};B.prototype.renderPartial=function(t,r,n,o){if(n){var i=this.getConfigTags(o),s=ur(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)}}};B.prototype.unescapedValue=function(t,r){var n=r.lookup(t[1]);if(n!=null)return n};B.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)};B.prototype.rawValue=function(t){return t[1]};B.prototype.getConfigTags=function(t){return je(t)?t:t&&typeof t=="object"?t.tags:void 0};B.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){Ye.templateCache=e},get templateCache(){return Ye.templateCache}},Ye=new B;Z.clearCache=function(){return Ye.clearCache()};Z.parse=function(t,r){return Ye.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 "'+Ms(t)+'" was given as the first argument for mustache#render(template, view, partials)');return Ye.render(t,r,n,o)};Z.escape=Js;Z.Scanner=Qe;Z.Context=$e;Z.Writer=B;var Sn=Z;function pr({defs:e}){return e==null?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,oa({def:r,name:t})]))}var na={boolean:!1,number:0,string:""};function oa({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??na[e.type]??""}function bt({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 G({ref:e,variables:t}){let r=String(bt({ref:e,variables:t}));return St({raw:r,variables:t})}function vt({ref:e,variables:t}){let r=bt({ref:e,variables:t});return typeof r=="string"?St({raw:r,variables:t}):r}function St({raw:e,variables:t}){return Sn.render(e,t,{},{escape:r=>r})}function mr({ref:e,variables:t}){let r=bt({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 D({locator:e,page:t,variables:r}){switch(e.by){case"testId":return t.getByTestId(kn(e.value,r));case"role":return t.getByRole(e.role,{exact:!0,name:e.name==null?void 0:kn(e.name,r)})}}function kn(e,t){return t==null?e:St({raw:e,variables:t})}async function Rn({node:e,page:t,timeout:r}){await D({locator:e.source,page:t,variables:void 0}).dragTo(D({locator:e.target,page:t,variables:void 0}),{timeout:r})}async function Pn({node:e,page:t,timeout:r}){await D({locator:e.locator,page:t,variables:void 0}).click({button:"right",timeout:r})}function xn({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 En({node:e,page:t,variables:r}){if(e.action==="write"){if(e.value==null)throw new Error("clipboard write requires a value");let o=G({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:Ne({name:e.variable,store:r,value:n})}}async function Cn({node:e,page:t}){let r=t.context();e.state==="granted"?await r.grantPermissions([e.permission]):await r.clearPermissions()}async function fr({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 aa({node:e,page:t,timeout:r,variables:n});case"rightClick":return await Pn({node:e,page:t,timeout:r}),{variables:n};case"goto":{let o=G({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 ca({node:e,page:t,timeout:r,variables:n});case"select":return da({node:e,page:t,timeout:r,variables:n});case"type":return ua({node:e,page:t,timeout:r,variables:n});case"press":return await la({node:e,page:t,timeout:r}),{variables:n};case"drag":return await Rn({node:e,page:t,timeout:r}),{variables:n};case"upload":return pa({node:e,page:t,timeout:r,variables:n});case"extractText":return fa({node:e,page:t,timeout:r,variables:n});case"setVariable":{let o=vt({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 xn({node:e,page:t,variables:n});case"clipboard":return En({node:e,page:t,variables:n});case"setPermission":return await Cn({node:e,page:t}),{variables:n}}}var sa={check:"check",clear:"clear",click:"click",dblclick:"dblclick",focus:"focus",hover:"hover",scrollIntoView:"scrollIntoViewIfNeeded",uncheck:"uncheck"};async function aa({node:e,page:t,timeout:r,variables:n}){return await D({locator:e.locator,page:t,variables:n})[sa[e.type]]({timeout:r}),{variables:n}}async function la({node:e,page:t,timeout:r}){e.locator==null?await t.keyboard.press(e.key):await D({locator:e.locator,page:t,variables:void 0}).press(e.key,{timeout:r})}async function ca({node:e,page:t,timeout:r,variables:n}){let o=G({ref:e.value,variables:n});return await D({locator:e.locator,page:t,variables:n}).fill(o,{timeout:r}),{variables:n}}async function da({node:e,page:t,timeout:r,variables:n}){let o=G({ref:e.value,variables:n});return await D({locator:e.locator,page:t,variables:n}).selectOption(o,{timeout:r}),{variables:n}}async function ua({node:e,page:t,timeout:r,variables:n}){let o=G({ref:e.value,variables:n});return await D({locator:e.locator,page:t,variables:n}).pressSequentially(o,{timeout:r}),{variables:n}}async function pa({node:e,page:t,timeout:r,variables:n}){let o=e.files.map(i=>ma(i));return await D({locator:e.locator,page:t,variables:n}).setInputFiles(o,{timeout:r}),{variables:n}}function ma(e){return ia.join(wn(),e)}async function fa({node:e,page:t,timeout:r,variables:n}){let o=await D({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={};Cs(F,{default:()=>ga});tr(F,Ch);import*as Ch from"playwright/test";import{default as ga}from"playwright/test";async function gr({expected:e,locator:t,operator:r,timeout:n}){await Ze({expected:e,operator:r,timeout:n,read:async()=>await t.textContent()??""});let o=await et(async()=>await t.textContent()??"");return Oe({actual:o,expected:e,label:"Text",operator:r})}async function yr({expected:e,operator:t,page:r,timeout:n}){return await Ze({expected:e,operator:t,timeout:n,read:()=>Promise.resolve(r.url())}),Oe({actual:r.url(),expected:e,label:"URL",operator:t})}async function An({expected:e,operator:t,page:r,timeout:n}){await Ze({expected:e,operator:t,timeout:n,read:()=>r.title()});let o=await et(()=>r.title());return Oe({actual:o,expected:e,label:"Title",operator:t})}async function hr({expected:e,locator:t,operator:r,timeout:n}){await F.expect.poll(async()=>Un({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 wr({expected:e,locator:t,operator:r,timeout:n}){await Ze({expected:e,operator:r,timeout:n,read:()=>t.inputValue()});let o=await et(()=>t.inputValue());return Oe({actual:o,expected:e,label:"Value",operator:r})}async function br({locator:e,timeout:t}){return ge({description:"Element is visible",failureDetail:"Element not visible",run:()=>(0,F.expect)(e).toBeVisible({timeout:t})})}async function vr({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 In({attribute:e,expected:t,locator:r,operator:n,timeout:o}){await Ze({expected:t,operator:n,timeout:o,read:async()=>await r.getAttribute(e)??""});let i=await et(async()=>await r.getAttribute(e)??"");return Oe({actual:i,expected:t,label:`Attribute "${e}"`,operator:n})}async function Tn({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 $n({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 jn({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 Nn({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 On({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 Dn({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 Ze({expected:e,operator:t,read:r,timeout:n}){await F.expect.poll(async()=>{let o=await et(r);return Ln({actual:o,expected:e,operator:t})},{timeout:n}).toBe(!0).catch(()=>{})}async function et(e){return e().catch(()=>"")}function Oe(e){let t=`${e.label} ${e.operator} "${e.expected}"`,r=Ln(e),n=r?void 0:`Got: "${e.actual}"`;return{description:t,detail:n,status:r?"passed":"failed"}}function Ln({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=Un(e),n=r?void 0:`Got: ${String(e.actual)}`;return{description:t,detail:n,status:r?"passed":"failed"}}function Un({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 ha}from"child_process";import{createRequire as wa}from"module";import Vn from"fs";import Fn from"path";import{chromium as Hn}from"playwright";import jh from"fs";import Oh from"path";import ya from"pino";var y=ya({transport:{options:{ignore:"pid,hostname"},target:"pino-pretty"}});async function tt({headed:e}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";try{return await Hn.launch({headless:!e})}catch(t){throw ba(t)?new Error(`Playwright browsers are not installed. Run:
16
16
 
17
17
  npx playwright install chromium
18
- `):t}}async function wr(){let e=_n.executablePath();if(Dn.existsSync(e))return;y.info("Chromium not found. Installing via Playwright...");let t=oa(import.meta.url),r=Ln.dirname(t.resolve("playwright/package.json")),n=Ln.join(r,"cli.js");if(await new Promise((o,i)=>{na(process.execPath,[n,"install","chromium"],s=>{if(s!=null){i(new Error(`Playwright install failed: ${s.message}`));return}o()})}),!Dn.existsSync(e))throw new Error(`Playwright browser installation failed. Try running manually:
18
+ `):t}}async function Sr(){let e=Hn.executablePath();if(Vn.existsSync(e))return;y.info("Chromium not found. Installing via Playwright...");let t=wa(import.meta.url),r=Fn.dirname(t.resolve("playwright/package.json")),n=Fn.join(r,"cli.js");if(await new Promise((o,i)=>{ha(process.execPath,[n,"install","chromium"],s=>{if(s!=null){i(new Error(`Playwright install failed: ${s.message}`));return}o()})}),!Vn.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 ia(e){return e instanceof Error?e.message.includes("Executable doesn't exist"):!1}import{readdir as ua,rm as pa,stat as ma}from"fs/promises";import Sh from"os";import Fn from"path";import{graphql as fa}from"gql.tada";import{print as sa}from"graphql";var aa=15e3;async function f(e){let t=sa(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(aa)})}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 la({res:o,url:n});if(!ca(i))throw new Error("Invalid GraphQL response");if(da(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 la({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 ca(e){return typeof e=="object"&&e!=null&&("data"in e||"errors"in e)}function da(e){return Array.isArray(e.errors)&&e.errors.length>0}var Un=Fn.join(process.cwd(),".ripplo","debug"),Vn=360*60*1e3,Ch=fa(`
21
+ `);y.info("\u2713 Chromium installed")}function ba(e){return e instanceof Error?e.message.includes("Executable doesn't exist"):!1}import{readdir as xa,rm as Ea,stat as Ca}from"fs/promises";import Kh from"os";import Wn from"path";import{graphql as Aa}from"gql.tada";import{print as va}from"graphql";var Sa=15e3;async function f(e){let t=va(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 ka({res:o,url:n});if(!Ra(i))throw new Error("Invalid GraphQL response");if(Pa(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 ka({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 Ra(e){return typeof e=="object"&&e!=null&&("data"in e||"errors"in e)}function Pa(e){return Array.isArray(e.errors)&&e.errors.length>0}var Mn=Wn.join(process.cwd(),".ripplo","debug"),Bn=360*60*1e3,Zh=Aa(`
22
22
  mutation RevokeCurrentCliToken {
23
23
  revokeCurrentCliToken
24
24
  }
25
- `);async function br({maxRuns:e}){try{let r=(await ua(Un,{withFileTypes:!0})).filter(c=>c.isDirectory()),n=Date.now(),o=await Promise.all(r.map(async c=>{let p=Fn.join(Un,c.name),m=await ma(p);return{dirPath:p,mtime:m.mtimeMs}})),i=o.filter(c=>n-c.mtime>Vn),a=o.filter(c=>n-c.mtime<=Vn).toSorted((c,p)=>p.mtime-c.mtime).slice(e),l=[...i,...a];if(l.length===0)return;await Promise.allSettled(l.map(c=>pa(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 ga=5e3;async function vr({appUrl:e}){try{await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(ga)})}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 ot from"fs";import Ce from"fs";import ya from"os";import tt from"path";var ha=".local",wa=".ripplo";function Sr(e){return tt.join(e,".ripplo",ha)}function rt(e){let t=Sr(e);Ce.existsSync(t)||Ce.mkdirSync(t,{recursive:!0});let r=tt.join(t,".gitignore");return Ce.existsSync(r)||Ce.writeFileSync(r,`*
27
- `),t}function nt(e,t){return tt.join(Sr(e),t)}function kr(){return tt.join(ya.homedir(),wa)}function Rr(){let e=kr();return Ce.existsSync(e)?Ce.chmodSync(e,448):Ce.mkdirSync(e,{mode:448,recursive:!0}),e}function ye(e){return tt.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(!ot.existsSync(t))return null;let r=ot.readFileSync(t,"utf8").trim();return r.length===0?null:r}function Pr(e){Rr(),ot.writeFileSync(ye("token"),e+`
28
- `,{mode:384})}function xr(){let e=ye("token");return ot.existsSync(e)?(ot.unlinkSync(e),!0):!1}import{z as Rc}from"zod";import{z as vt}from"zod";var ba=vt.object({__codec:vt.string().min(1),data:vt.unknown(),version:vt.number().int().positive()}),St=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 Rt(e){return Hn({legacy:void 0,migrators:[],name:e,schemas:[]})}function Hn(e){return{initial:t=>Cr(t,{...e,schemas:[t]}),legacy:t=>Hn({...e,legacy:t})}}function Cr(e,t){return{build:()=>va(e,t),legacy:r=>Cr(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return Cr(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function va(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>Sa(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function Sa(e,t,r){let{data:n,version:o}=ka(t,r),i=Mn(t,n,o);return e.parse(i)}function ka(e,t){let r=ba.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 Mn(e,t,r){let n=e.schemas.length;if(r>n)throw new St({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 Mn(e,s(i),r+1)}import{z as zn}from"zod";import{z as De}from"zod";var Er=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 Ra=he.object({by:he.literal("testId"),value:he.string().min(1)}),Pa=he.object({by:he.literal("role"),name:he.string().optional(),role:he.string().min(1)}),R=he.discriminatedUnion("by",[Ra,Pa]);import{z as Bn}from"zod";var we=Bn.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),Pt=Bn.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]);import{z as A}from"zod";var xa=A.object({type:A.literal("static"),value:A.union([A.string(),A.number(),A.boolean()])}),xt=A.object({name:A.string().min(1),type:A.literal("variable")}),Ct=A.discriminatedUnion("type",[xa,xt]),J=A.discriminatedUnion("type",[A.object({type:A.literal("static"),value:A.string()}),xt]),Et=A.discriminatedUnion("type",[A.object({type:A.literal("static"),value:A.number().int().nonnegative()}),xt]),Ar=A.discriminatedUnion("type",[A.object({type:A.literal("static"),value:A.union([A.string(),A.number(),A.boolean()])}),xt]);import{z as X}from"zod";var At=X.discriminatedUnion("type",[X.object({default:X.string().optional(),type:X.literal("string")}),X.object({default:X.number().optional(),type:X.literal("number")}),X.object({default:X.boolean().optional(),type:X.literal("boolean")}),X.object({key:X.string().min(1),type:X.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,Ca=d.object({...b,type:d.literal("goto"),url:J}),Ea=d.object({...b,locator:R,type:d.literal("click")}),Aa=d.object({...b,locator:R,type:d.literal("fill"),value:J}),Ia=d.object({...b,locator:R,type:d.literal("select"),value:J}),Ta=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")}),ja=d.object({...b,locator:R,type:d.literal("check")}),Na=d.object({...b,locator:R,type:d.literal("uncheck")}),Oa=d.object({...b,height:d.number().int().positive(),type:d.literal("setViewport"),width:d.number().int().positive()}),Da=d.object({...b,message:d.string().min(1),type:d.literal("fail")}),La=d.object({...b,type:d.literal("setVariable"),value:Ct,variable:d.string().min(1)}),_a=d.object({...b,locator:R,type:d.literal("extractText"),variable:d.string().min(1)}),Ua=d.object({...b,files:d.array(d.string()).min(1),locator:R,type:d.literal("upload")}),Va=d.object({...b,locator:R,type:d.literal("dblclick")}),Fa=d.object({...b,source:R,target:R,type:d.literal("drag")}),Ha=d.object({...b,locator:R,type:d.literal("scrollIntoView")}),Ma=d.object({...b,locator:R,type:d.literal("type"),value:J}),Ba=d.object({...b,locator:R,type:d.literal("focus")}),Wa=d.object({...b,locator:R,type:d.literal("clear")}),qa=d.object({...b,locator:R,type:d.literal("rightClick")}),za=d.object({...b,action:d.enum(["accept","dismiss"]),promptText:d.string().optional(),type:d.literal("handleDialog")}),Ga=d.object({...b,action:d.enum(["read","write"]),type:d.literal("clipboard"),value:J.optional(),variable:d.string().min(1).optional()}),Ka=d.object({...b,permission:d.string().min(1),state:d.enum(["granted","prompt"]),type:d.literal("setPermission")}),Ja=d.object({...b,locator:R,type:d.literal("assertVisible")}),Xa=d.object({...b,locator:R,type:d.literal("assertNotVisible")}),Ya=d.object({...b,expected:J,locator:R,operator:we,type:d.literal("assertText")}),Qa=d.object({...b,expected:J,operator:we,type:d.literal("assertUrl")}),Za=d.object({...b,expected:Et,locator:R,operator:Pt,type:d.literal("assertCount")}),el=d.object({...b,expected:J,locator:R,operator:we,type:d.literal("assertValue")}),tl=d.object({...b,attribute:d.string().min(1),expected:J,locator:R,operator:we,type:d.literal("assertAttribute")}),rl=d.object({...b,locator:R,type:d.literal("assertEnabled")}),nl=d.object({...b,locator:R,type:d.literal("assertDisabled")}),ol=d.object({...b,expected:J,operator:we,type:d.literal("assertTitle")}),il=d.object({...b,locator:R,type:d.literal("assertChecked")}),sl=d.object({...b,locator:R,type:d.literal("assertNotChecked")}),al=d.object({...b,locator:R,type:d.literal("assertFocused")}),ll=d.object({...b,locator:R,type:d.literal("assertNotFocused")}),cl=d.object({...b,budget:d.enum(["fast","slow","async"]),observer:d.string().min(1).max(200),params:d.record(d.string().max(200),Ar),type:d.literal("assertObserver")}),qn=d.discriminatedUnion("type",[Ca,Ea,Aa,Ia,Ta,$a,ja,Na,Ja,Xa,Ya,Qa,Za,el,tl,rl,nl,Oa,Da,La,_a,Ua,Va,Fa,Ha,Ma,Ba,Wa,qa,za,Ga,Ka,ol,il,sl,al,ll,cl]),It=d.object({entryNode:d.string().min(1).max(200),nodes:d.record(d.string().max(200),qn).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),At).optional()});var dl=zn.record(zn.string().max(200),Er),ul={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},pl={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},Ir=Rt("workflow-spec").legacy(ul).initial(It).build(),ml=Rt("precondition-map").legacy(pl).initial(dl).build();import{z as Tr}from"zod";var Gn=["fast","slow","async"],fl=Tr.object({budget:Tr.enum(Gn).describe("Polling budget tier: fast | slow | async"),description:Tr.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 io,readFragment as Pc}from"gql.tada";import{mkdir as $r,writeFile as ie}from"fs/promises";import G from"path";import{z as te}from"zod";async function Jn({context:e,page:t,runId:r,stepIndex:n,stepResult:o}){try{let i=G.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([ie(G.join(i,"info.json"),JSON.stringify(s,null,2)),gl({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 gl({context:e,page:t,stepDir:r}){let[n,o,i,s,a]=await Promise.all([wl(t),Sl(t),El({context:e,page:t}),xl(t),hl(t)]);await Promise.all([ie(G.join(r,"dom.html"),n),ie(G.join(r,"accessibility-tree.full.json"),JSON.stringify(o,null,2)),ie(G.join(r,"accessibility-tree.json"),kl(o)),ie(G.join(r,"storage.json"),JSON.stringify(i,null,2)),ie(G.join(r,"rrweb-elements.ndjson"),a),s==null?Promise.resolve():ie(G.join(r,"screenshot.png"),s)])}var yl=`
25
+ `);async function kr({maxRuns:e}){try{let r=(await xa(Mn,{withFileTypes:!0})).filter(c=>c.isDirectory()),n=Date.now(),o=await Promise.all(r.map(async c=>{let p=Wn.join(Mn,c.name),m=await Ca(p);return{dirPath:p,mtime:m.mtimeMs}})),i=o.filter(c=>n-c.mtime>Bn),a=o.filter(c=>n-c.mtime<=Bn).toSorted((c,p)=>p.mtime-c.mtime).slice(e),l=[...i,...a];if(l.length===0)return;await Promise.allSettled(l.map(c=>Ea(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 Ia=5e3;async function Rr({appUrl:e}){try{await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(Ia)})}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 it from"fs";import Ee from"fs";import Ta from"os";import rt from"path";var $a=".local",ja=".ripplo";function Pr(e){return rt.join(e,".ripplo",$a)}function nt(e){let t=Pr(e);Ee.existsSync(t)||Ee.mkdirSync(t,{recursive:!0});let r=rt.join(t,".gitignore");return Ee.existsSync(r)||Ee.writeFileSync(r,`*
27
+ `),t}function ot(e,t){return rt.join(Pr(e),t)}function xr(){return rt.join(Ta.homedir(),ja)}function Er(){let e=xr();return Ee.existsSync(e)?Ee.chmodSync(e,448):Ee.mkdirSync(e,{mode:448,recursive:!0}),e}function ye(e){return rt.join(xr(),e)}function ee(){let e=process.env.RIPPLO_TOKEN;if(e!=null&&e.trim().length>0)return e.trim();let t=ye("token");if(!it.existsSync(t))return null;let r=it.readFileSync(t,"utf8").trim();return r.length===0?null:r}function Cr(e){Er(),it.writeFileSync(ye("token"),e+`
28
+ `,{mode:384})}function Ar(){let e=ye("token");return it.existsSync(e)?(it.unlinkSync(e),!0):!1}import{z as _c}from"zod";import{z as kt}from"zod";var Na=kt.object({__codec:kt.string().min(1),data:kt.unknown(),version:kt.number().int().positive()}),Rt=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}},Pt=class extends Error{constructor(t){super(`Codec mismatch: expected "${t.expected}", got "${t.got}"`),this.name="CodecMismatchError"}};function xt(e){return qn({legacy:void 0,migrators:[],name:e,schemas:[]})}function qn(e){return{initial:t=>Ir(t,{...e,schemas:[t]}),legacy:t=>qn({...e,legacy:t})}}function Ir(e,t){return{build:()=>Oa(e,t),legacy:r=>Ir(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return Ir(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function Oa(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>Da(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function Da(e,t,r){let{data:n,version:o}=La(t,r),i=zn(t,n,o);return e.parse(i)}function La(e,t){let r=Na.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new Pt({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 zn(e,t,r){let n=e.schemas.length;if(r>n)throw new Rt({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 zn(e,s(i),r+1)}import{z as Xn}from"zod";import{z as De}from"zod";var Tr=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 _a=he.object({by:he.literal("testId"),value:he.string().min(1)}),Ua=he.object({by:he.literal("role"),name:he.string().optional(),role:he.string().min(1)}),R=he.discriminatedUnion("by",[_a,Ua]);import{z as Gn}from"zod";var we=Gn.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),Et=Gn.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]);import{z as I}from"zod";var Va=I.object({type:I.literal("static"),value:I.union([I.string(),I.number(),I.boolean()])}),Ct=I.object({name:I.string().min(1),type:I.literal("variable")}),At=I.discriminatedUnion("type",[Va,Ct]),J=I.discriminatedUnion("type",[I.object({type:I.literal("static"),value:I.string()}),Ct]),It=I.discriminatedUnion("type",[I.object({type:I.literal("static"),value:I.number().int().nonnegative()}),Ct]),$r=I.discriminatedUnion("type",[I.object({type:I.literal("static"),value:I.union([I.string(),I.number(),I.boolean()])}),Ct]);import{z as X}from"zod";var Tt=X.discriminatedUnion("type",[X.object({default:X.string().optional(),type:X.literal("string")}),X.object({default:X.number().optional(),type:X.literal("number")}),X.object({default:X.boolean().optional(),type:X.literal("boolean")}),X.object({key:X.string().min(1),type:X.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()},Kn=500,Fa=d.object({...b,type:d.literal("goto"),url:J}),Ha=d.object({...b,locator:R,type:d.literal("click")}),Ma=d.object({...b,locator:R,type:d.literal("fill"),value:J}),Ba=d.object({...b,locator:R,type:d.literal("select"),value:J}),Wa=d.object({...b,locator:R,type:d.literal("hover")}),qa=d.object({...b,key:d.string().min(1),locator:R.optional(),type:d.literal("press")}),za=d.object({...b,locator:R,type:d.literal("check")}),Ga=d.object({...b,locator:R,type:d.literal("uncheck")}),Ka=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")}),Xa=d.object({...b,type:d.literal("setVariable"),value:At,variable:d.string().min(1)}),Ya=d.object({...b,locator:R,type:d.literal("extractText"),variable:d.string().min(1)}),Qa=d.object({...b,files:d.array(d.string()).min(1),locator:R,type:d.literal("upload")}),Za=d.object({...b,locator:R,type:d.literal("dblclick")}),el=d.object({...b,source:R,target:R,type:d.literal("drag")}),tl=d.object({...b,locator:R,type:d.literal("scrollIntoView")}),rl=d.object({...b,locator:R,type:d.literal("type"),value:J}),nl=d.object({...b,locator:R,type:d.literal("focus")}),ol=d.object({...b,locator:R,type:d.literal("clear")}),il=d.object({...b,locator:R,type:d.literal("rightClick")}),sl=d.object({...b,action:d.enum(["accept","dismiss"]),promptText:d.string().optional(),type:d.literal("handleDialog")}),al=d.object({...b,action:d.enum(["read","write"]),type:d.literal("clipboard"),value:J.optional(),variable:d.string().min(1).optional()}),ll=d.object({...b,permission:d.string().min(1),state:d.enum(["granted","prompt"]),type:d.literal("setPermission")}),cl=d.object({...b,locator:R,type:d.literal("assertVisible")}),dl=d.object({...b,locator:R,type:d.literal("assertNotVisible")}),ul=d.object({...b,expected:J,locator:R,operator:we,type:d.literal("assertText")}),pl=d.object({...b,expected:J,operator:we,type:d.literal("assertUrl")}),ml=d.object({...b,expected:It,locator:R,operator:Et,type:d.literal("assertCount")}),fl=d.object({...b,expected:J,locator:R,operator:we,type:d.literal("assertValue")}),gl=d.object({...b,attribute:d.string().min(1),expected:J,locator:R,operator:we,type:d.literal("assertAttribute")}),yl=d.object({...b,locator:R,type:d.literal("assertEnabled")}),hl=d.object({...b,locator:R,type:d.literal("assertDisabled")}),wl=d.object({...b,expected:J,operator:we,type:d.literal("assertTitle")}),bl=d.object({...b,locator:R,type:d.literal("assertChecked")}),vl=d.object({...b,locator:R,type:d.literal("assertNotChecked")}),Sl=d.object({...b,locator:R,type:d.literal("assertFocused")}),kl=d.object({...b,locator:R,type:d.literal("assertNotFocused")}),Rl=d.object({...b,budget:d.enum(["fast","slow","async"]),observer:d.string().min(1).max(200),params:d.record(d.string().max(200),$r),type:d.literal("assertObserver")}),Jn=d.discriminatedUnion("type",[Fa,Ha,Ma,Ba,Wa,qa,za,Ga,cl,dl,ul,pl,ml,fl,gl,yl,hl,Ka,Ja,Xa,Ya,Qa,Za,el,tl,rl,nl,ol,il,sl,al,ll,wl,bl,vl,Sl,kl,Rl]),$t=d.object({entryNode:d.string().min(1).max(200),nodes:d.record(d.string().max(200),Jn).refine(e=>Object.keys(e).length<=Kn,`Workflow has more than ${String(Kn)} nodes`),uiOnly:d.boolean().optional(),variableNamespaces:d.record(d.string().max(200),d.string().max(500)).optional(),variables:d.record(d.string().max(200),Tt).optional()});var Pl=Xn.record(Xn.string().max(200),Tr),xl={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},El={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},jr=xt("workflow-spec").legacy(xl).initial($t).build(),Cl=xt("precondition-map").legacy(El).initial(Pl).build();import{z as Nr}from"zod";var Yn=["fast","slow","async"],Al=Nr.object({budget:Nr.enum(Yn).describe("Polling budget tier: fast | slow | async"),description:Nr.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 co,readFragment as Uc}from"gql.tada";import{mkdir as Or,writeFile as ie}from"fs/promises";import K from"path";import{z as te}from"zod";async function Zn({context:e,page:t,runId:r,stepIndex:n,stepResult:o}){try{let i=K.join(process.cwd(),".ripplo","debug",r,"steps",String(n));await Or(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([ie(K.join(i,"info.json"),JSON.stringify(s,null,2)),Il({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 Il({context:e,page:t,stepDir:r}){let[n,o,i,s,a]=await Promise.all([jl(t),Dl(t),Hl({context:e,page:t}),Vl(t),$l(t)]);await Promise.all([ie(K.join(r,"dom.html"),n),ie(K.join(r,"accessibility-tree.full.json"),JSON.stringify(o,null,2)),ie(K.join(r,"accessibility-tree.json"),Ll(o)),ie(K.join(r,"storage.json"),JSON.stringify(i,null,2)),ie(K.join(r,"rrweb-elements.ndjson"),a),s==null?Promise.resolve():ie(K.join(r,"screenshot.png"),s)])}var Tl=`
29
29
  (function () {
30
30
  try {
31
31
  var rrweb = window.rrweb || globalThis.rrweb;
@@ -89,8 +89,8 @@ Add missing values to the env file(s) declared in .ripplo/project.json.${i}`)}le
89
89
  return JSON.stringify({ __ripploError: String(err && err.message ? err.message : err) });
90
90
  }
91
91
  })()
92
- `;async function hl(e){return await q({awaitPromise:!1,expression:yl,page:e})??""}async function wl(e){return await q({awaitPromise:!1,expression:"document.documentElement.outerHTML",page:e})??"(unable to capture DOM)"}var Tt=te.object({value:te.unknown()}).partial(),bl=te.object({childIds:te.array(te.string()),description:Tt,ignored:te.boolean(),name:Tt,nodeId:te.string(),parentId:te.string(),properties:te.array(te.unknown()),role:Tt,value:Tt}).partial(),vl=te.object({nodes:te.array(bl)});async function Sl(e){let t={nodes:[]};return yt(e,t,async r=>{let n=await r.send("Accessibility.getFullAXTree"),o=vl.safeParse(n);return o.success?o.data:t})}function kl(e){return e.nodes.filter(t=>t.ignored!==!0).map(t=>Rl(t)).toSorted(Pl).map(t=>JSON.stringify(t)).join(`
93
- `)}function Rl(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 Pl(e,t){return Kn(e.nodeId)-Kn(t.nodeId)}function Kn(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 xl(e){return yt(e,void 0,async t=>{let r=await t.send("Page.captureScreenshot",{format:"png"});return Buffer.from(r.data,"base64")})}var Cl=`(() => {
92
+ `;async function $l(e){return await z({awaitPromise:!1,expression:Tl,page:e})??""}async function jl(e){return await z({awaitPromise:!1,expression:"document.documentElement.outerHTML",page:e})??"(unable to capture DOM)"}var jt=te.object({value:te.unknown()}).partial(),Nl=te.object({childIds:te.array(te.string()),description:jt,ignored:te.boolean(),name:jt,nodeId:te.string(),parentId:te.string(),properties:te.array(te.unknown()),role:jt,value:jt}).partial(),Ol=te.object({nodes:te.array(Nl)});async function Dl(e){let t={nodes:[]};return wt(e,t,async r=>{let n=await r.send("Accessibility.getFullAXTree"),o=Ol.safeParse(n);return o.success?o.data:t})}function Ll(e){return e.nodes.filter(t=>t.ignored!==!0).map(t=>_l(t)).toSorted(Ul).map(t=>JSON.stringify(t)).join(`
93
+ `)}function _l(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 Ul(e,t){return Qn(e.nodeId)-Qn(t.nodeId)}function Qn(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 wt(e,void 0,async t=>{let r=await t.send("Page.captureScreenshot",{format:"png"});return Buffer.from(r.data,"base64")})}var Fl=`(() => {
94
94
  function dump(s) {
95
95
  var out = {};
96
96
  for (var i = 0; i < s.length; i++) {
@@ -100,41 +100,41 @@ Add missing values to the env file(s) declared in .ripplo/project.json.${i}`)}le
100
100
  return out;
101
101
  }
102
102
  return { localStorage: dump(localStorage), sessionStorage: dump(sessionStorage) };
103
- })()`;async function El({context:e,page:t}){let[r,n]=await Promise.all([q({awaitPromise:!1,expression:Cl,page:t}),e.cookies().catch(()=>[])]);return{cookies:n,localStorage:r?.localStorage??{},sessionStorage:r?.sessionStorage??{}}}async function Xn({runId:e,steps:t,summary:r}){try{let n=G.join(process.cwd(),".ripplo","debug",e);await $r(n,{recursive:!0}),await Promise.all([ie(G.join(n,"summary.txt"),Al({steps:t,summary:r})),ie(G.join(n,"manifest.md"),Il({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 Al({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(`
104
- `)}function Il({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`.","- `rrweb-elements.ndjson` \u2014 one JSON object per element with an rrweb mirror id, taken from the live rrweb snapshot. Line-greppable. Fields: `{ rrwebId, tag, attrs?, text? }`. `attrs` only includes referenceable attributes (id, class, role, aria-label, aria-labelledby, name, placeholder, alt, title, type, value, href, data-testid); `text` is the element's *own* text (direct text-node children only), trimmed and capped. Structural tags (html/head/script/style/meta/etc.) are skipped. **Only rrwebId values found in this file are accepted by anchored review comments \u2014 never fabricate one.**","- `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(`
105
- `)}async function Yn({error:e,runId:t,stack:r,workflowName:n}){try{let o=G.join(process.cwd(),".ripplo","debug",t);await $r(o,{recursive:!0});let i=r==null?e:`${e}
103
+ })()`;async function Hl({context:e,page:t}){let[r,n]=await Promise.all([z({awaitPromise:!1,expression:Fl,page:t}),e.cookies().catch(()=>[])]);return{cookies:n,localStorage:r?.localStorage??{},sessionStorage:r?.sessionStorage??{}}}async function eo({runId:e,steps:t,summary:r}){try{let n=K.join(process.cwd(),".ripplo","debug",e);await Or(n,{recursive:!0}),await Promise.all([ie(K.join(n,"summary.txt"),Ml({steps:t,summary:r})),ie(K.join(n,"manifest.md"),Bl({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 Ml({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(`
104
+ `)}function Bl({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`.","- `rrweb-elements.ndjson` \u2014 one JSON object per element with an rrweb mirror id, taken from the live rrweb snapshot. Line-greppable. Fields: `{ rrwebId, tag, attrs?, text? }`. `attrs` only includes referenceable attributes (id, class, role, aria-label, aria-labelledby, name, placeholder, alt, title, type, value, href, data-testid); `text` is the element's *own* text (direct text-node children only), trimmed and capped. Structural tags (html/head/script/style/meta/etc.) are skipped. **Only rrwebId values found in this file are accepted by anchored review comments \u2014 never fabricate one.**","- `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(`
105
+ `)}async function to({error:e,runId:t,stack:r,workflowName:n}){try{let o=K.join(process.cwd(),".ripplo","debug",t);await Or(o,{recursive:!0});let i=r==null?e:`${e}
106
106
 
107
107
  ${r}`,s=[`Run ID: ${t}`,`Workflow: ${n}`,"Status: failed","",`Error: ${e}`,"",r==null?"":`Stack trace:
108
108
  ${r}`].join(`
109
- `);await Promise.all([ie(G.join(o,"error.txt"),i),ie(G.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 Tl}from"fs";import{createRequire as $l}from"module";import Qn from"path";import{gzipSync as jl}from"zlib";var Nl=$l(import.meta.url),Ol=Nl.resolve("rrweb"),Dl=Qn.join(Qn.dirname(Ol),"rrweb.umd.min.cjs"),Ll=Tl(Dl,"utf8"),_l=[";(function() {"," try {"," if (window.__ripploRrwebLoaded) return;"," window.__ripploRrwebLoaded = true;"," window.__ripploRrwebBuffer = [];"," window.__ripploRrwebDrain = function() {"," var out = window.__ripploRrwebBuffer;"," window.__ripploRrwebBuffer = [];"," return out;"," };"," var r = window.rrweb;"," if (r == null || r.record == null) {"," console.warn('[ripplo] rrweb global not found');"," return;"," }"," function startRecording() {"," if (window.__ripploRrwebStartedAt != null) return;"," window.__ripploRrwebStartedAt = Date.now();"," var stop = r.record({"," emit: function(event) { window.__ripploRrwebBuffer.push(event); },"," recordCanvas: false,"," recordCrossOriginIframes: false,"," });"," window.__ripploRrwebStop = stop;"," }"," window.__ripploRrwebStart = startRecording;"," // Auto-start on every bootstrap run so agent-driven tests (which don't"," // emit a 'first step' signal before navigating) capture from the start."," startRecording();"," } catch (err) {"," console.error('[ripplo] rrweb bootstrap failed', err && err.message ? err.message : err);"," }","})();"].join(`
110
- `),Ul=Ll+`
111
- `+_l;async function Zn(e){let t,r=0;async function n(){await e.addScriptTag({content:Ul}).catch(()=>{})}await n(),e.on("load",()=>{n()});async function o(){await q({awaitPromise:!1,expression:"globalThis.__ripploRrwebStart && globalThis.__ripploRrwebStart()",page:e});let l=await q({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 q({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,k=l.map(g=>JSON.stringify(g)).join(`
112
- `),N={body:jl(Buffer.from(k,"utf8")),chunkIndex:r,endTimestamp:p.timestamp-m,eventCount:l.length,startTimestamp:c.timestamp-m};return r+=1,N}async function a(){await q({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 eo from"crypto";import{Webhook as Vl}from"standardwebhooks";function be({body:e,secret:t}){let r=new Vl(t),n=`msg_${eo.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 jr(){return`whsec_${eo.randomBytes(24).toString("base64")}`}var Fl=15e4,Hl={async:{backoffMs:[500,1e3,2e3,5e3],timeoutMs:12e4},fast:{backoffMs:[100,250,500,1e3],timeoutMs:5e3},slow:{backoffMs:[250,500,1e3,2e3],timeoutMs:3e4}},Ml=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()})]),Bl=re.object({error:re.string().optional(),outcome:Ml.optional(),success:re.boolean()});async function to({apiUrl:e,budget:t,observer:r,params:n,webhookSecret:o}){let i=Hl[t],s=performance.now(),a={lastReason:void 0,pollCount:0};for(;performance.now()-s<i.timeoutMs;){a.pollCount+=1;let l=await ql({apiUrl:e,observer:r,params:n,webhookSecret:o}),c=Wl({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(zl({backoff:i.backoffMs,pollCount:a.pollCount}),p);await Gl(m)}return{description:`observer "${r}"`,detail:`budget "${t}" exhausted after ${String(a.pollCount)} poll(s) (${ro(s)}); last: ${a.lastReason??"no retry reason"}
113
- \u2192 /ripplo:debug \u2014 check .ripplo/debug/<runId>/ artifacts`,status:"failed"}}function Wl({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}
114
- 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 (${ro(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.
115
- Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=t.reason,null)}async function ql({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(Fl)});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=Bl.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 zl({backoff:e,pollCount:t}){let r=Math.min(t-1,e.length-1);return e[r]??1e3}function ro(e){return`${String(Math.round(performance.now()-e))}ms`}async function Gl(e){return new Promise(t=>setTimeout(t,e))}var Kl=1e4;async function Nr({failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,spec:i,variables:s}){let a=performance.now();return Xl({currentId:i.entryNode,failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,runStartTime:a,spec:i,variables:s})}function Jl({onStep:e,steps:t,target:r}){t.forEach(n=>{let o={...n,stepIndex:r.length};r.push(o),e?.(o)})}async function Xl({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 k=a.nodes[m];if(k==null)throw new Error(`Node "${m}" not found in spec`);let j=m,N=k.label??`${k.type} (${m})`;y.info("Executing node: %s [%s]",N,k.type);let g=await Yl({getRecordingOffsetMs:r,node:k,nodeId:j,observerTransport:n,page:i,runStartTime:s,variables:p});if(Jl({onStep:o,steps:[g],target:c}),p=g.variables,t&&g.status==="failed")break;m=k.next}return{steps:c,variables:p}}async function Yl({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=Kl;try{let m=await Ql({node:t,observerTransport:n,page:o,timeout:p,variables:s}),k=Math.round(performance.now()-a),j=m.assertions.some(g=>g.status==="failed"),N=e?.();return{assertions:m.assertions,detail:void 0,duration:k,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 k=Math.round(performance.now()-a),j=m instanceof Error?m.message:String(m),N=e?.();return{assertions:[],detail:j,duration:k,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 Ql({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(Zl(e)){let s=await ur({node:e,page:r,timeout:n,variables:o});return{assertions:[],variables:s.variables}}return{assertions:await tc({node:e,observerTransport:t,page:r,timeout:n,variables:o}),variables:o}}function Zl(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 ec(e){return e.type.startsWith("assert")}async function tc({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(!ec(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 nc({assertNode:i,page:r,timeout:n,variables:o});case"assertText":{let s=z({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"assertUrl":{let s=z({ref:i.expected,variables:o});return[await mr({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertTitle":{let s=z({ref:i.expected,variables:o});return[await Pn({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertCount":{let s=dr({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"assertValue":{let s=z({ref:i.expected,variables:o});return[await gr({expected:s,locator:O({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertAttribute":{let s=z({ref:i.expected,variables:o});return[await xn({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]=wt({ref:l,variables:o})}),[await to({apiUrl:t.apiUrl,budget:i.budget,observer:i.observer,params:s,webhookSecret:t.webhookSecret})]}}}var rc={assertChecked:An,assertDisabled:En,assertEnabled:Cn,assertFocused:Tn,assertNotChecked:In,assertNotFocused:$n,assertNotVisible:hr,assertVisible:yr};async function nc({assertNode:e,page:t,timeout:r,variables:n}){let o=rc[e.type];return[await o({locator:O({locator:e.locator,page:t,variables:n}),timeout:r})]}var no=1e4;async function Or({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(no),c.setDefaultNavigationTimeout(no),r.length>0&&await c.addCookies(r);let p=await c.newPage(),m=await Zn(p);async function k(){let W=await m.takeChunk();W!=null&&i?.(W)}let j=setInterval(()=>{k()},2e3),N=[],g=!1;function B(W){s?.(W),g||(g=!0,m.start()),N.push(Jn({context:c,page:p,runId:a,stepIndex:W.stepIndex,stepResult:W}))}let $=oc(n,l.variableNamespaces),V={...cr({defs:l.variables}),...$},ne=await Nr({failFast:!0,getRecordingOffsetMs:m.currentOffsetMs,observerTransport:o,onStep:B,page:p,spec:l,variables:V});clearInterval(j);let Ie=ne.steps.filter(W=>W.status==="passed").length,se=ne.steps.filter(W=>W.status==="failed").length,Ke={duration:ne.steps.reduce((W,oe)=>W+oe.duration,0),failCount:se,passCount:Ie,runId:a,status:se>0?"failed":"passed",workflowName:""};return await Promise.all([Promise.allSettled(N).then(()=>Xn({runId:a,steps:ne.steps,summary:Ke})),m.detach().then(k)]),await c.close(),ne.steps}function oc(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 pe({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 ic}from"set-cookie-parser";import{z as H}from"zod";var oo=3e4,sc=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 Dr({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",...uc({cookies:t}),...be({body:i,secret:o})},method:"PUT",signal:AbortSignal.timeout(oo)});s.ok||y.error("Teardown returned %s",String(s.status))}catch{y.error("Teardown request failed")}}async function ac({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(oo)});if(!i.ok){let c=await cc(i);throw new Error(`execute-preconditions returned ${String(i.status)}: ${c}`)}let s=await i.json(),a=sc.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=pc({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 lc=H.object({error:H.string()});async function cc(e){let t=await e.text().catch(()=>"");if(t.length===0)return"no body";let r=dc(t),n=r==null?null:lc.safeParse(r);return n!=null&&n.success?n.data.error:t.slice(0,500)}function dc(e){try{return JSON.parse(e)}catch{return null}}function uc({cookies:e}){return e.length===0?{}:{Cookie:e.map(r=>`${r.name}=${r.value}`).join("; ")}}function pc({domain:e,res:t}){let r=t.headers.getSetCookie();return ic(r,{decodeValues:!1}).map(o=>mc({cookie:o,domain:e}))}function mc({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=gc({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 fc={lax:"Lax",none:"None",strict:"Strict"};function gc({raw:e}){return fc[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:[]}:ac({apiUrl:n,preconditionNames:t,webhookSecret:r})}import{graphql as Le}from"gql.tada";async function Lr({config:e,runId:t}){if((await f({config:e,document:bc,variables:{runId:t}})).startRun==null)throw new Error("Failed to start run");let n=[];function o(l){let c=hc({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=yc({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 pe({label:`flushSteps (${String(n.length)} steps)`,fn:()=>Promise.all(n)});let m=c.filter(g=>g.status==="passed").length,k=c.filter(g=>g.status==="failed").length,j=c.reduce((g,B)=>g+B.duration,0),N=l??(k>0?"failed":"passed");await pe({label:"completeRun",fn:()=>f({config:e,document:kc,variables:{duration:j,failCount:k,passCount:m,runId:t,status:N,summary:p??null,warnCount:0}})})}return{complete:a,enqueueRecordingChunk:i,enqueueStep:o,flushSteps:s,runId:t}}async function yc({chunk:e,config:t,runId:r}){await f({config:t,document:Sc,variables:{input:{bodyBase64:e.body.toString("base64"),chunkIndex:e.chunkIndex,endTimestamp:e.endTimestamp,eventCount:e.eventCount,runId:r,startTimestamp:e.startTimestamp}}})}async function hc({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 f({config:e,document:vc,variables:{runId:t,steps:n}})}async function _r({config:e,reason:t,runId:r}){await f({config:e,document:wc,variables:{reason:t,runId:r}})}var pb=Le(`
109
+ `);await Promise.all([ie(K.join(o,"error.txt"),i),ie(K.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 Wl}from"fs";import{createRequire as ql}from"module";import ro from"path";import{gzipSync as zl}from"zlib";var Gl=ql(import.meta.url),Kl=Gl.resolve("rrweb"),Jl=ro.join(ro.dirname(Kl),"rrweb.umd.min.cjs"),Xl=Wl(Jl,"utf8"),Yl=[";(function() {"," try {"," if (window.__ripploRrwebLoaded) return;"," window.__ripploRrwebLoaded = true;"," window.__ripploRrwebBuffer = [];"," window.__ripploRrwebDrain = function() {"," var out = window.__ripploRrwebBuffer;"," window.__ripploRrwebBuffer = [];"," return out;"," };"," var r = window.rrweb;"," if (r == null || r.record == null) {"," console.warn('[ripplo] rrweb global not found');"," return;"," }"," function startRecording() {"," if (window.__ripploRrwebStartedAt != null) return;"," window.__ripploRrwebStartedAt = Date.now();"," var stop = r.record({"," emit: function(event) { window.__ripploRrwebBuffer.push(event); },"," recordCanvas: false,"," recordCrossOriginIframes: false,"," });"," window.__ripploRrwebStop = stop;"," }"," window.__ripploRrwebStart = startRecording;"," // Auto-start on every bootstrap run so agent-driven tests (which don't"," // emit a 'first step' signal before navigating) capture from the start."," startRecording();"," } catch (err) {"," console.error('[ripplo] rrweb bootstrap failed', err && err.message ? err.message : err);"," }","})();"].join(`
110
+ `),Ql=Xl+`
111
+ `+Yl;async function no(e){let t,r=0;async function n(){await e.addScriptTag({content:Ql}).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,k=l.map(g=>JSON.stringify(g)).join(`
112
+ `),O={body:zl(Buffer.from(k,"utf8")),chunkIndex:r,endTimestamp:p.timestamp-m,eventCount:l.length,startTimestamp:c.timestamp-m};return r+=1,O}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 oo from"crypto";import{Webhook as Zl}from"standardwebhooks";function be({body:e,secret:t}){let r=new Zl(t),n=`msg_${oo.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 Dr(){return`whsec_${oo.randomBytes(24).toString("base64")}`}var ec=15e4,tc={async:{backoffMs:[500,1e3,2e3,5e3],timeoutMs:12e4},fast:{backoffMs:[100,250,500,1e3],timeoutMs:5e3},slow:{backoffMs:[250,500,1e3,2e3],timeoutMs:3e4}},rc=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()})]),nc=re.object({error:re.string().optional(),outcome:rc.optional(),success:re.boolean()});async function io({apiUrl:e,budget:t,observer:r,params:n,webhookSecret:o}){let i=tc[t],s=performance.now(),a={lastReason:void 0,pollCount:0};for(;performance.now()-s<i.timeoutMs;){a.pollCount+=1;let l=await ic({apiUrl:e,observer:r,params:n,webhookSecret:o}),c=oc({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(sc({backoff:i.backoffMs,pollCount:a.pollCount}),p);await ac(m)}return{description:`observer "${r}"`,detail:`budget "${t}" exhausted after ${String(a.pollCount)} poll(s) (${so(s)}); last: ${a.lastReason??"no retry reason"}
113
+ \u2192 /ripplo:debug \u2014 check .ripplo/debug/<runId>/ artifacts`,status:"failed"}}function oc({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}
114
+ 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 (${so(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.
115
+ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=t.reason,null)}async function ic({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(ec)});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=nc.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 sc({backoff:e,pollCount:t}){let r=Math.min(t-1,e.length-1);return e[r]??1e3}function so(e){return`${String(Math.round(performance.now()-e))}ms`}async function ac(e){return new Promise(t=>setTimeout(t,e))}var lc=1e4;async function Lr({failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,spec:i,variables:s}){let a=performance.now();return dc({currentId:i.entryNode,failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,runStartTime:a,spec:i,variables:s})}function cc({onStep:e,steps:t,target:r}){t.forEach(n=>{let o={...n,stepIndex:r.length};r.push(o),e?.(o)})}async function dc({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 k=a.nodes[m];if(k==null)throw new Error(`Node "${m}" not found in spec`);let N=m,O=k.label??`${k.type} (${m})`;y.info("Executing node: %s [%s]",O,k.type);let g=await uc({getRecordingOffsetMs:r,node:k,nodeId:N,observerTransport:n,page:i,runStartTime:s,variables:p});if(cc({onStep:o,steps:[g],target:c}),p=g.variables,t&&g.status==="failed")break;m=k.next}return{steps:c,variables:p}}async function uc({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=lc;try{let m=await pc({node:t,observerTransport:n,page:o,timeout:p,variables:s}),k=Math.round(performance.now()-a),N=m.assertions.some(g=>g.status==="failed"),O=e?.();return{assertions:m.assertions,detail:void 0,duration:k,nodeId:r,nodeType:t.type,recordingEndMs:O,recordingStartMs:l,snapshotTimestamp:Math.round(performance.now()-i),status:N?"failed":"passed",stepIndex:0,title:c,url:o.url(),variables:m.variables}}catch(m){let k=Math.round(performance.now()-a),N=m instanceof Error?m.message:String(m),O=e?.();return{assertions:[],detail:N,duration:k,nodeId:r,nodeType:t.type,recordingEndMs:O,recordingStartMs:l,snapshotTimestamp:Math.round(performance.now()-i),status:"failed",stepIndex:0,title:c,url:o.url(),variables:s}}}async function pc({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(mc(e)){let s=await fr({node:e,page:r,timeout:n,variables:o});return{assertions:[],variables:s.variables}}return{assertions:await gc({node:e,observerTransport:t,page:r,timeout:n,variables:o}),variables:o}}function mc(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 fc(e){return e.type.startsWith("assert")}async function gc({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(!fc(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 hc({assertNode:i,page:r,timeout:n,variables:o});case"assertText":{let s=G({ref:i.expected,variables:o});return[await gr({expected:s,locator:D({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertUrl":{let s=G({ref:i.expected,variables:o});return[await yr({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertTitle":{let s=G({ref:i.expected,variables:o});return[await An({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertCount":{let s=mr({ref:i.expected,variables:o});return[await hr({expected:s,locator:D({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertValue":{let s=G({ref:i.expected,variables:o});return[await wr({expected:s,locator:D({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertAttribute":{let s=G({ref:i.expected,variables:o});return[await In({attribute:i.attribute,expected:s,locator:D({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]=vt({ref:l,variables:o})}),[await io({apiUrl:t.apiUrl,budget:i.budget,observer:i.observer,params:s,webhookSecret:t.webhookSecret})]}}}var yc={assertChecked:jn,assertDisabled:$n,assertEnabled:Tn,assertFocused:On,assertNotChecked:Nn,assertNotFocused:Dn,assertNotVisible:vr,assertVisible:br};async function hc({assertNode:e,page:t,timeout:r,variables:n}){let o=yc[e.type];return[await o({locator:D({locator:e.locator,page:t,variables:n}),timeout:r})]}var ao=1e4;async function _r({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(ao),c.setDefaultNavigationTimeout(ao),r.length>0&&await c.addCookies(r);let p=await c.newPage(),m=await no(p);async function k(){let q=await m.takeChunk();q!=null&&i?.(q)}let N=setInterval(()=>{k()},2e3),O=[],g=!1;function W(q){s?.(q),g||(g=!0,m.start()),O.push(Zn({context:c,page:p,runId:a,stepIndex:q.stepIndex,stepResult:q}))}let j=wc(n,l.variableNamespaces),V={...pr({defs:l.variables}),...j},ne=await Lr({failFast:!0,getRecordingOffsetMs:m.currentOffsetMs,observerTransport:o,onStep:W,page:p,spec:l,variables:V});clearInterval(N);let Ie=ne.steps.filter(q=>q.status==="passed").length,se=ne.steps.filter(q=>q.status==="failed").length,Je={duration:ne.steps.reduce((q,oe)=>q+oe.duration,0),failCount:se,passCount:Ie,runId:a,status:se>0?"failed":"passed",workflowName:""};return await Promise.all([Promise.allSettled(O).then(()=>eo({runId:a,steps:ne.steps,summary:Je})),m.detach().then(k)]),await c.close(),ne.steps}function wc(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 pe({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 bc}from"set-cookie-parser";import{z as H}from"zod";var lo=3e4,vc=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 Ur({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",...xc({cookies:t}),...be({body:i,secret:o})},method:"PUT",signal:AbortSignal.timeout(lo)});s.ok||y.error("Teardown returned %s",String(s.status))}catch{y.error("Teardown request failed")}}async function Sc({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(lo)});if(!i.ok){let c=await Rc(i);throw new Error(`execute-preconditions returned ${String(i.status)}: ${c}`)}let s=await i.json(),a=vc.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=Ec({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 kc=H.object({error:H.string()});async function Rc(e){let t=await e.text().catch(()=>"");if(t.length===0)return"no body";let r=Pc(t),n=r==null?null:kc.safeParse(r);return n!=null&&n.success?n.data.error:t.slice(0,500)}function Pc(e){try{return JSON.parse(e)}catch{return null}}function xc({cookies:e}){return e.length===0?{}:{Cookie:e.map(r=>`${r.name}=${r.value}`).join("; ")}}function Ec({domain:e,res:t}){let r=t.headers.getSetCookie();return bc(r,{decodeValues:!1}).map(o=>Cc({cookie:o,domain:e}))}function Cc({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=Ic({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 Ac={lax:"Lax",none:"None",strict:"Strict"};function Ic({raw:e}){return Ac[e.toLowerCase()]??"Lax"}async function Nt({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:[]}:Sc({apiUrl:n,preconditionNames:t,webhookSecret:r})}import{graphql as Le}from"gql.tada";async function Vr({config:e,runId:t}){if((await f({config:e,document:Nc,variables:{runId:t}})).startRun==null)throw new Error("Failed to start run");let n=[];function o(l){let c=$c({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=Tc({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 pe({label:`flushSteps (${String(n.length)} steps)`,fn:()=>Promise.all(n)});let m=c.filter(g=>g.status==="passed").length,k=c.filter(g=>g.status==="failed").length,N=c.reduce((g,W)=>g+W.duration,0),O=l??(k>0?"failed":"passed");await pe({label:"completeRun",fn:()=>f({config:e,document:Lc,variables:{duration:N,failCount:k,passCount:m,runId:t,status:O,summary:p??null,warnCount:0}})})}return{complete:a,enqueueRecordingChunk:i,enqueueStep:o,flushSteps:s,runId:t}}async function Tc({chunk:e,config:t,runId:r}){await f({config:t,document:Dc,variables:{input:{bodyBase64:e.body.toString("base64"),chunkIndex:e.chunkIndex,endTimestamp:e.endTimestamp,eventCount:e.eventCount,runId:r,startTimestamp:e.startTimestamp}}})}async function $c({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 f({config:e,document:Oc,variables:{runId:t,steps:n}})}async function Fr({config:e,reason:t,runId:r}){await f({config:e,document:jc,variables:{reason:t,runId:r}})}var Vb=Le(`
116
116
  mutation MarkRunArtifactsUploadedCLI($runId: String!) {
117
117
  markRunArtifactsUploaded(runId: $runId)
118
118
  }
119
- `),wc=Le(`
119
+ `),jc=Le(`
120
120
  mutation FailRunCLI($runId: String!, $reason: String!) {
121
121
  failRun(runId: $runId, reason: $reason)
122
122
  }
123
- `),bc=Le(`
123
+ `),Nc=Le(`
124
124
  mutation StartRunCLI($runId: String!) {
125
125
  startRun(runId: $runId) {
126
126
  id
127
127
  }
128
128
  }
129
- `),vc=Le(`
129
+ `),Oc=Le(`
130
130
  mutation SubmitRunStepsCLI($runId: String!, $steps: [StepInput!]!) {
131
131
  submitRunSteps(runId: $runId, steps: $steps)
132
132
  }
133
- `),Sc=Le(`
133
+ `),Dc=Le(`
134
134
  mutation SubmitRunRecordingChunkCLI($input: SubmitRunRecordingChunkInput!) {
135
135
  submitRunRecordingChunk(input: $input)
136
136
  }
137
- `),kc=Le(`
137
+ `),Lc=Le(`
138
138
  mutation CompleteRunCLI(
139
139
  $runId: String!
140
140
  $status: RunStatus!
@@ -157,7 +157,7 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
157
157
  status
158
158
  }
159
159
  }
160
- `);var xc=12e4,so=io(`
160
+ `);var Vc=12e4,uo=co(`
161
161
  fragment WorkflowRun on Workflow {
162
162
  id
163
163
  slug
@@ -169,7 +169,7 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
169
169
  preconditionName
170
170
  }
171
171
  }
172
- `),Cc=io(`
172
+ `),Fc=co(`
173
173
  query RunWorkflowSpec($runId: String!) {
174
174
  run(id: $runId) {
175
175
  id
@@ -182,7 +182,7 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
182
182
  }
183
183
  }
184
184
  }
185
- `,[so]);async function Ur({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=Ec({externalBrowser:t,headed:n});let m=o==null?void 0:$t({engineBaseUrl:r.engineUrl,preconditionNames:o,webhookSecret:s}),[{engineBaseUrl:k,workflow:j},N]=await Promise.all([pe({label:"Run context resolved",fn:()=>jc({config:r,runId:i})}),pe({label:"Streaming run started",fn:()=>Lr({config:r,runId:i})}),vr({appUrl:e})]);a=j.name,l=N;let g=Nc(j.spec);y.info("Executing workflow: %s",j.name),await Lc(Ic({baseUrl:e,browserPromise:c,engineBaseUrl:k,preconditionPromise:m,runId:i,specData:g,streaming:l,webhookSecret:s,workflow:j}),Dc())}catch(m){throw await Ac({browserPromise:c,config:r,error:m,ownsBrowser:p,runId:i,streaming:l,workflowName:a}),m}}function Ec({externalBrowser:e,headed:t}){return e!=null?Promise.resolve(e):pe({label:"Browser launched",fn:()=>et({headed:t})})}async function Ac({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 Yn({error:a,runId:o,stack:l,workflowName:s}),i==null?await _r({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 Ic({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 Tc({baseUrl:e,browser:m,preconditionResult:p,runId:o,specData:i,streaming:s,webhookSecret:a})}async function Tc({baseUrl:e,browser:t,preconditionResult:r,runId:n,specData:o,streaming:i,webhookSecret:s}){let a=await pe({label:"Spec executed",fn:()=>Or({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 $c({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 $c({preconditionResult:e,webhookSecret:t}){e.apiUrl!=null&&await Dr({apiUrl:e.apiUrl,cookies:e.cookies,data:e.data,executed:e.executed,webhookSecret:t})}async function jc({config:e,runId:t}){let r=await f({config:e,document:Cc,variables:{runId:t}});if(r.run?.workflow==null)throw new Error(`Run ${t} not found`);let n=Pc(so,r.run.workflow),o=r.run.workflow.project?.engineBaseUrl??"";return{engineBaseUrl:e.engineUrl.length>0?e.engineUrl:o,workflow:n}}function Nc(e){if(e==null)throw new Error("Workflow has no spec");return Ir.decode(e)}var Oc=Rc.coerce.number().int().positive().catch(xc);function Dc(){return Oc.parse(process.env.RIPPLO_RUN_TIMEOUT_MS)}async function Lc(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 it}from"gql.tada";var Ib=it(`
185
+ `,[uo]);async function Hr({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=Hc({externalBrowser:t,headed:n});let m=o==null?void 0:Nt({engineBaseUrl:r.engineUrl,preconditionNames:o,webhookSecret:s}),[{engineBaseUrl:k,workflow:N},O]=await Promise.all([pe({label:"Run context resolved",fn:()=>zc({config:r,runId:i})}),pe({label:"Streaming run started",fn:()=>Vr({config:r,runId:i})}),Rr({appUrl:e})]);a=N.name,l=O;let g=Gc(N.spec);y.info("Executing workflow: %s",N.name),await Xc(Bc({baseUrl:e,browserPromise:c,engineBaseUrl:k,preconditionPromise:m,runId:i,specData:g,streaming:l,webhookSecret:s,workflow:N}),Jc())}catch(m){throw await Mc({browserPromise:c,config:r,error:m,ownsBrowser:p,runId:i,streaming:l,workflowName:a}),m}}function Hc({externalBrowser:e,headed:t}){return e!=null?Promise.resolve(e):pe({label:"Browser launched",fn:()=>tt({headed:t})})}async function Mc({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 to({error:a,runId:o,stack:l,workflowName:s}),i==null?await Fr({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 Bc({baseUrl:e,browserPromise:t,engineBaseUrl:r,preconditionPromise:n,runId:o,specData:i,streaming:s,webhookSecret:a,workflow:l}){let c=n??Nt({engineBaseUrl:r,preconditionNames:l.preconditions,webhookSecret:a}),[p,m]=await Promise.all([c,t]);await Wc({baseUrl:e,browser:m,preconditionResult:p,runId:o,specData:i,streaming:s,webhookSecret:a})}async function Wc({baseUrl:e,browser:t,preconditionResult:r,runId:n,specData:o,streaming:i,webhookSecret:s}){let a=await pe({label:"Spec executed",fn:()=>_r({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 qc({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 qc({preconditionResult:e,webhookSecret:t}){e.apiUrl!=null&&await Ur({apiUrl:e.apiUrl,cookies:e.cookies,data:e.data,executed:e.executed,webhookSecret:t})}async function zc({config:e,runId:t}){let r=await f({config:e,document:Fc,variables:{runId:t}});if(r.run?.workflow==null)throw new Error(`Run ${t} not found`);let n=Uc(uo,r.run.workflow),o=r.run.workflow.project?.engineBaseUrl??"";return{engineBaseUrl:e.engineUrl.length>0?e.engineUrl:o,workflow:n}}function Gc(e){if(e==null)throw new Error("Workflow has no spec");return jr.decode(e)}var Kc=_c.coerce.number().int().positive().catch(Vc);function Jc(){return Kc.parse(process.env.RIPPLO_RUN_TIMEOUT_MS)}async function Xc(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 st}from"gql.tada";var rv=st(`
186
186
  query AgentReviewContextWorker($reviewId: String!) {
187
187
  agentReview(id: $reviewId) {
188
188
  id
@@ -196,11 +196,11 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
196
196
  }
197
197
  }
198
198
  }
199
- `);var Tb=it(`
199
+ `);var nv=st(`
200
200
  mutation StartAgentReviewWorker($reviewId: String!) {
201
201
  startAgentReview(reviewId: $reviewId)
202
202
  }
203
- `);var $b=it(`
203
+ `);var ov=st(`
204
204
  mutation CompleteAgentReviewWorker(
205
205
  $reviewId: String!
206
206
  $markdown: String!
@@ -214,38 +214,38 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
214
214
  comments: $comments
215
215
  )
216
216
  }
217
- `);var jb=it(`
217
+ `);var iv=st(`
218
218
  mutation UpdateAgentReviewProgressWorker($reviewId: String!, $text: String!) {
219
219
  updateAgentReviewProgress(reviewId: $reviewId, text: $text)
220
220
  }
221
- `);var Nb=it(`
221
+ `);var sv=st(`
222
222
  mutation FailAgentReviewWorker($reviewId: String!, $reason: String!) {
223
223
  failAgentReview(reviewId: $reviewId, reason: $reason)
224
224
  }
225
- `);import{exec as Hc}from"child_process";import{createAuthClient as _c}from"better-auth/client";import{deviceAuthorizationClient as Uc}from"better-auth/client/plugins";function ao({baseURL:e}){return _c({baseURL:e,fetchOptions:{headers:{"User-Agent":"Ripplo CLI"}},plugins:[Uc()]})}import{z as Vr}from"zod";var Vc="https://ripplo.ai";function Y(){return jt().RIPPLO_SERVER_URL}function co(){return jt().RIPPLO_PROJECT_ID}var Fc=Vr.object({RIPPLO_PROJECT_ID:Vr.string().min(1).optional(),RIPPLO_SERVER_URL:Vr.string().min(1).default(Vc)}),lo;function jt(){return lo??=Fc.parse(process.env),lo}var Mc=5e3,uo="ripplo-cli";async function po({onDeviceCode:e,url:t}){let r=t??jt().RIPPLO_SERVER_URL,n=ao({baseURL:r}),o=await n.device.code({client_id:uo});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}),Kc(a);let l=await Bc({authClient:n,deviceCode:i});return Pr(l),l}async function Bc({authClient:e,deviceCode:t}){for(;;){await zc(Mc);let r=await e.device.token({client_id:uo,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(!qc(r.error.error))throw new Error(`Authorization failed: ${r.error.error_description}`)}}var Wc=new Set(["authorization_pending","slow_down"]);function qc(e){return Wc.has(e)}function zc(e){return new Promise(t=>{setTimeout(t,e)})}function Gc(){return process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open"}function Kc(e){let t=Gc();Hc(`${t} "${e}"`,()=>{})}function ve({serverUrl:e,token:t}){return{appUrl:"",cwd:process.cwd(),engineUrl:"",projectId:"",ripploServerUrl:e,token:t,webhookSecret:""}}import Jc from"fs";import Xc from"path";function C(e){return Jc.existsSync(Xc.join(e,".ripplo"))}var Qc=Yc(`
225
+ `);import{exec as td}from"child_process";import{createAuthClient as Yc}from"better-auth/client";import{deviceAuthorizationClient as Qc}from"better-auth/client/plugins";function po({baseURL:e}){return Yc({baseURL:e,fetchOptions:{headers:{"User-Agent":"Ripplo CLI"}},plugins:[Qc()]})}import{z as Mr}from"zod";var Zc="https://ripplo.ai";function Y(){return Ot().RIPPLO_SERVER_URL}function fo(){return Ot().RIPPLO_PROJECT_ID}var ed=Mr.object({RIPPLO_PROJECT_ID:Mr.string().min(1).optional(),RIPPLO_SERVER_URL:Mr.string().min(1).default(Zc)}),mo;function Ot(){return mo??=ed.parse(process.env),mo}var rd=5e3,go="ripplo-cli";async function yo({onDeviceCode:e,url:t}){let r=t??Ot().RIPPLO_SERVER_URL,n=po({baseURL:r}),o=await n.device.code({client_id:go});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}),ld(a);let l=await nd({authClient:n,deviceCode:i});return Cr(l),l}async function nd({authClient:e,deviceCode:t}){for(;;){await sd(rd);let r=await e.device.token({client_id:go,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(!id(r.error.error))throw new Error(`Authorization failed: ${r.error.error_description}`)}}var od=new Set(["authorization_pending","slow_down"]);function id(e){return od.has(e)}function sd(e){return new Promise(t=>{setTimeout(t,e)})}function ad(){return process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open"}function ld(e){let t=ad();td(`${t} "${e}"`,()=>{})}function ve({serverUrl:e,token:t}){return{appUrl:"",cwd:process.cwd(),engineUrl:"",projectId:"",ripploServerUrl:e,token:t,webhookSecret:""}}import cd from"fs";import dd from"path";function C(e){return cd.existsSync(dd.join(e,".ripplo"))}var pd=ud(`
226
226
  query AuthViewer {
227
227
  currentUser {
228
228
  name
229
229
  email
230
230
  }
231
231
  }
232
- `);async function mo(){let e=Y(),t=ee();if(t!=null){let s=await Fr({serverUrl:e,token:t});if(s!=null){process.stdout.write(`Already signed in as ${s.email}. Run \`ripplo auth logout\` to switch.
232
+ `);async function ho(){let e=Y(),t=ee();if(t!=null){let s=await Br({serverUrl:e,token:t});if(s!=null){process.stdout.write(`Already signed in as ${s.email}. Run \`ripplo auth logout\` to switch.
233
233
  `);return}process.stdout.write(`Your saved session expired \u2014 let's sign you back in.
234
234
 
235
- `)}let r=await po({url:e,onDeviceCode:s=>{process.stdout.write(`Opening your browser to finish sign-in.
235
+ `)}let r=await yo({url:e,onDeviceCode:s=>{process.stdout.write(`Opening your browser to finish sign-in.
236
236
  `),process.stdout.write(`If it didn't open, visit: ${s.verificationUrl}
237
237
  `),process.stdout.write(`Verification code: ${s.userCode}
238
238
 
239
239
  `),process.stdout.write(`Waiting for you to approve...
240
- `)}}),n=await Fr({serverUrl:e,token:r}),o=C(process.cwd()),i=o?"Welcome back":"Welcome to Ripplo";process.stdout.write(`
240
+ `)}}),n=await Br({serverUrl:e,token:r}),o=C(process.cwd()),i=o?"Welcome back":"Welcome to Ripplo";process.stdout.write(`
241
241
  `),process.stdout.write(n==null?`${i}.
242
- `:`${i}, ${Zc(n)}.
242
+ `:`${i}, ${md(n)}.
243
243
  `),process.stdout.write(`Session saved to ${ye("token")}.
244
- `),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 Zc(e){let t=e.name.trim().split(/\s+/)[0];return t!=null&&t.length>0?t:e.email}async function Fr({serverUrl:e,token:t}){try{let n=(await f({config:ve({serverUrl:e,token:t}),document:Qc,variables:void 0})).currentUser;return n==null?null:{email:n.email,name:n.name}}catch{return null}}async function fo(){let e=ee();e==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login`.\n"),process.exit(1));let t=Y(),r=await Fr({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})
245
- `)}function go(){if(!xr()){process.stdout.write(`No token to remove.
244
+ `),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 md(e){let t=e.name.trim().split(/\s+/)[0];return t!=null&&t.length>0?t:e.email}async function Br({serverUrl:e,token:t}){try{let n=(await f({config:ve({serverUrl:e,token:t}),document:pd,variables:void 0})).currentUser;return n==null?null:{email:n.email,name:n.name}}catch{return null}}async function wo(){let e=ee();e==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login`.\n"),process.exit(1));let t=Y(),r=await Br({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})
245
+ `)}function bo(){if(!Ar()){process.stdout.write(`No token to remove.
246
246
  `);return}process.stdout.write(`Removed ${ye("token")}
247
- `)}import Mr from"fs/promises";import Br from"path";import{z as Nt}from"zod";import{z as yo}from"zod";import{z as _e}from"zod";import{z as u}from"zod";import{z as Se}from"zod";import{z as So}from"zod";import{z as I}from"zod";import{z as Q}from"zod";import{z as Hr}from"zod";import{z as L}from"zod";var ed=Nt.object({__codec:Nt.string().min(1),data:Nt.unknown(),version:Nt.number().int().positive()}),td=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}},rd=class extends Error{constructor(e){super(`Codec mismatch: expected "${e.expected}", got "${e.got}"`),this.name="CodecMismatchError"}};function zr(e){return wo({legacy:void 0,migrators:[],name:e,schemas:[]})}function nd(e,t){let r=JSON.parse(t);return e.decode(r)}function wo(e){return{initial:t=>Wr(t,{...e,schemas:[t]}),legacy:t=>wo({...e,legacy:t})}}function Wr(e,t){return{build:()=>od(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 od(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>id(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function id(e,t,r){let{data:n,version:o}=sd(t,r),i=bo(t,n,o);return e.parse(i)}function sd(e,t){let r=ed.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new rd({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 bo(e,t,r){let n=e.schemas.length;if(r>n)throw new td({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 bo(e,s(i),r+1)}var vo=_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."),ad=Se.object({by:Se.literal("testId"),value:Se.string().min(1)}),ld=Se.object({by:Se.literal("role"),name:Se.string().optional(),role:Se.string().min(1)}),x=Se.discriminatedUnion("by",[ad,ld]),st=So.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),cd=So.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]),dd=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")}),ud=I.discriminatedUnion("type",[dd,Ot]),ae=I.discriminatedUnion("type",[I.object({type:I.literal("static"),value:I.string()}),Ot]),pd=I.discriminatedUnion("type",[I.object({type:I.literal("static"),value:I.number().int().nonnegative()}),Ot]),md=I.discriminatedUnion("type",[I.object({type:I.literal("static"),value:I.union([I.string(),I.number(),I.boolean()])}),Ot]),fd=Q.discriminatedUnion("type",[Q.object({default:Q.string().optional(),type:Q.literal("string")}),Q.object({default:Q.number().optional(),type:Q.literal("number")}),Q.object({default:Q.boolean().optional(),type:Q.literal("boolean")}),Q.object({key:Q.string().min(1),type:Q.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()},ho=500,gd=u.object({...v,type:u.literal("goto"),url:ae}),yd=u.object({...v,locator:x,type:u.literal("click")}),hd=u.object({...v,locator:x,type:u.literal("fill"),value:ae}),wd=u.object({...v,locator:x,type:u.literal("select"),value:ae}),bd=u.object({...v,locator:x,type:u.literal("hover")}),vd=u.object({...v,key:u.string().min(1),locator:x.optional(),type:u.literal("press")}),Sd=u.object({...v,locator:x,type:u.literal("check")}),kd=u.object({...v,locator:x,type:u.literal("uncheck")}),Rd=u.object({...v,height:u.number().int().positive(),type:u.literal("setViewport"),width:u.number().int().positive()}),Pd=u.object({...v,message:u.string().min(1),type:u.literal("fail")}),xd=u.object({...v,type:u.literal("setVariable"),value:ud,variable:u.string().min(1)}),Cd=u.object({...v,locator:x,type:u.literal("extractText"),variable:u.string().min(1)}),Ed=u.object({...v,files:u.array(u.string()).min(1),locator:x,type:u.literal("upload")}),Ad=u.object({...v,locator:x,type:u.literal("dblclick")}),Id=u.object({...v,source:x,target:x,type:u.literal("drag")}),Td=u.object({...v,locator:x,type:u.literal("scrollIntoView")}),$d=u.object({...v,locator:x,type:u.literal("type"),value:ae}),jd=u.object({...v,locator:x,type:u.literal("focus")}),Nd=u.object({...v,locator:x,type:u.literal("clear")}),Od=u.object({...v,locator:x,type:u.literal("rightClick")}),Dd=u.object({...v,action:u.enum(["accept","dismiss"]),promptText:u.string().optional(),type:u.literal("handleDialog")}),Ld=u.object({...v,action:u.enum(["read","write"]),type:u.literal("clipboard"),value:ae.optional(),variable:u.string().min(1).optional()}),_d=u.object({...v,permission:u.string().min(1),state:u.enum(["granted","prompt"]),type:u.literal("setPermission")}),Ud=u.object({...v,locator:x,type:u.literal("assertVisible")}),Vd=u.object({...v,locator:x,type:u.literal("assertNotVisible")}),Fd=u.object({...v,expected:ae,locator:x,operator:st,type:u.literal("assertText")}),Hd=u.object({...v,expected:ae,operator:st,type:u.literal("assertUrl")}),Md=u.object({...v,expected:pd,locator:x,operator:cd,type:u.literal("assertCount")}),Bd=u.object({...v,expected:ae,locator:x,operator:st,type:u.literal("assertValue")}),Wd=u.object({...v,attribute:u.string().min(1),expected:ae,locator:x,operator:st,type:u.literal("assertAttribute")}),qd=u.object({...v,locator:x,type:u.literal("assertEnabled")}),zd=u.object({...v,locator:x,type:u.literal("assertDisabled")}),Gd=u.object({...v,expected:ae,operator:st,type:u.literal("assertTitle")}),Kd=u.object({...v,locator:x,type:u.literal("assertChecked")}),Jd=u.object({...v,locator:x,type:u.literal("assertNotChecked")}),Xd=u.object({...v,locator:x,type:u.literal("assertFocused")}),Yd=u.object({...v,locator:x,type:u.literal("assertNotFocused")}),Qd=u.object({...v,budget:u.enum(["fast","slow","async"]),observer:u.string().min(1).max(200),params:u.record(u.string().max(200),md),type:u.literal("assertObserver")}),Zd=u.discriminatedUnion("type",[gd,yd,hd,wd,bd,vd,Sd,kd,Ud,Vd,Fd,Hd,Md,Bd,Wd,qd,zd,Rd,Pd,xd,Cd,Ed,Ad,Id,Td,$d,jd,Nd,Od,Dd,Ld,_d,Gd,Kd,Jd,Xd,Yd,Qd]),ko=u.object({entryNode:u.string().min(1).max(200),nodes:u.record(u.string().max(200),Zd).refine(e=>Object.keys(e).length<=ho,`Workflow has more than ${String(ho)} nodes`),uiOnly:u.boolean().optional(),variableNamespaces:u.record(u.string().max(200),u.string().max(500)).optional(),variables:u.record(u.string().max(200),fd).optional()}),eu=yo.record(yo.string().max(200),vo),tu={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},ru={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},Gv=zr("workflow-spec").legacy(tu).initial(ko).build(),Kv=zr("precondition-map").legacy(ru).initial(eu).build(),nu=["fast","slow","async"],ou=Hr.object({budget:Hr.enum(nu).describe("Polling budget tier: fast | slow | async"),description:Hr.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",iu=5e3,su=L.record(L.string().max(200),L.string().max(200)),au=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:su,slug:L.string().max(200),sourcePath:L.string().max(500).optional(),spec:ko}),lu=L.object({observers:L.record(L.string().max(200),ou),preconditions:L.record(L.string().max(200),vo),tests:L.array(au).max(iu)}),Ro=zr("ripplo-lockfile").initial(lu).build();function Po(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 qr(e){let t=Ro.encode(e);return`${JSON.stringify(t,uu(t),2)}
248
- `}async function Dt({cwd:e}){let t=Br.join(e,le),r=await cu(t);return r==null?null:nd(Ro,r)}async function ce({cwd:e,result:t}){let r=Po(t),n=Br.join(e,le);await Mr.mkdir(Br.dirname(n),{recursive:!0}),await Mr.writeFile(n,qr(r),"utf8")}function Lt({compiled:e,existing:t}){if(t==null)return"missing";let r=qr(Po(e)),n=qr(t);return r===n?"match":"stale"}async function cu(e){try{return await Mr.readFile(e,"utf8")}catch(t){if(du(t)&&t.code==="ENOENT")return null;throw t}}function du(e){return e instanceof Error&&"code"in e}function uu(e){return function(r,n){return n===e||!pu(n)?n:Object.fromEntries(Object.entries(n).toSorted(([o],[i])=>o.localeCompare(i)))}}function pu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import at from"fs";import Vt from"path";var Gr=["**/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 xo(e){return e.data}function Co(e){return{as(t){return{data:{label:t,node:e}}}}}function _t(e){let t=e.getPreconditions(),r=e.getObservers(),n=e.getTests();mu(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=>fu(a,t));return{observers:i,preconditions:o,tests:s}}function mu(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 fu(e,t){let r=e.id,{accessedKeys:n,vars:o}=yu(e.requiresKeys),i=e.startsAtFn==null?void 0:e.startsAtFn(o),s=e.stepsFn==null?[]:e.stepsFn(o),a=i==null?s:[gu(i),...s],l=hu(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=bu(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 gu(e){return Co({type:"goto",url:{type:"static",value:e}}).as(`navigate to ${e}`)}function yu(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 hu(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]=wu(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 wu(e,t,r){let{label:n,node:o}=xo(e);return{...o,id:t,label:n,next:r}}function bu(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 iS,WebhookVerificationError as sS}from"standardwebhooks";import{z as S}from"zod";var lS=S.object({preconditions:S.array(S.string().min(1))}),cS=S.object({data:S.record(S.string(),S.record(S.string(),S.union([S.string(),S.number(),S.boolean()]))),preconditions:S.array(S.string().min(1))}),dS=S.object({observer:S.string().min(1).max(200),params:S.record(S.string().max(200),S.union([S.string(),S.number(),S.boolean()]))}),vu=S.discriminatedUnion("kind",[S.object({kind:S.literal("pass")}),S.object({kind:S.literal("retry"),reason:S.string()}),S.object({kind:S.literal("fail"),reason:S.string()})]),uS=S.object({error:S.string().optional(),outcome:vu.optional(),success:S.boolean()});function Ue(e){let t=[];return e.tests.forEach(r=>{let n=Su(r),o=i=>{t.push({...i,test:r.slug})};Bu.forEach(i=>{i(n,r,o)})}),{diagnostics:t}}function Su(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 ku(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 Ru(e,t,r){Object.keys(t.spec.variables??{}).length>0&&e.forEach(o=>{if(o.type==="fill"&&Ao(o.value)){let i=o.value.value;!Io(i)&&Tu(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 Pu(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 xu(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 Cu(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 Eu(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 Au(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 Iu(e,t,r){t.implemented&&e.length===0&&r({message:"Test has zero steps",rule:"no-empty-steps",step:void 0})}function Ao(e){return!(typeof e!="object"||e==null||!("type"in e)||e.type!=="static"||!("value"in e)||typeof e.value!="string")}function Io(e){return e.includes("{{")}function Tu(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 $u=new Set(["assertText","assertValue","assertCount","assertUrl","assertNotVisible","assertChecked","assertNotChecked","assertAttribute","assertDisabled","assertEnabled"]);function ju(e){return $u.has(e.type)}function Nu(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 Ou(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 Kr(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 Du(e,t,r){e.forEach((n,o)=>{if(n.type!=="click")return;let i=Kr(n);if(i==null)return;let s=e.slice(o+1,o+4);s.find(c=>c.type==="assertVisible"&&Kr(c)===i)==null||s.some(c=>ju(c)||Ve(c)&&Kr(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 Lu=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 Jr(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=3&&!Lu.has(t))}function _u(e){let t=e.label==null?[]:Jr(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,...Jr(n)]}function Uu(e,t,r){if(!t.implemented||e.length===0)return;let n=new Set(Jr(t.expectedOutcome));if(n.size===0)return;let o=e.filter(s=>Ve(s));if(o.length===0)return;o.some(s=>_u(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 Vu=/save|submit|create|delete|remove|send|invite|update|confirm|publish|apply|pay|subscribe|upgrade|cancel|archive|rename/i;function Eo(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 Vu.test(r)}function Fu(e,t,r){!t.implemented||t.spec.uiOnly===!0||e.forEach((n,o)=>{if(!Eo(n)||"uiOnly"in n&&n.uiOnly===!0)return;let i=e.slice(o+1),s=i.findIndex(p=>Eo(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 Hu(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])=>Ao(a)&&Io(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 Mu(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 Bu=[ku,Ru,Mu,Pu,xu,Cu,Eu,Au,Iu,Nu,Ou,Du,Uu,Fu,Hu];import fp from"picomatch";import{execFileSync as Wu,spawnSync as qu}from"child_process";function K(e,t){return Wu("git",[...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}function To(e,t){let r=qu("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 w from"typescript";import*as $o from"remeda";var jo=[["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"]],zu=new Map([["button","click"],["link","navigate"],["textbox","input"],["searchbox","input"],["combobox","select"],["listbox","select"]]),Gu=[[/(?:^|[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=w.createSourceFile(e,t,w.ScriptTarget.Latest,!0,w.ScriptKind.TSX);return r.statements.flatMap(n=>Ku({filePath:e,sf:r,stmt:n}))}function Ku({filePath:e,sf:t,stmt:r}){let n=Xu(r);if(n==null||Ju(n))return[];let o=No(r,t).map(i=>({id:`${e}#${n}.${i.kind}[${i.label}]`,line:i.line}));return $o.uniqueBy(o,i=>i.id)}function Ju(e){return e.endsWith("Fragment")||e.endsWith("Skeleton")||/^use[A-Z]/.test(e)||/^[A-Z][A-Z0-9_]*$/.test(e)}function Xu(e){if(w.isExportAssignment(e))return Yu(e.expression);if(!Qu(e))return null;if(w.isFunctionDeclaration(e)||w.isClassDeclaration(e))return e.name?.text??null;if(w.isVariableStatement(e)){let t=e.declarationList.declarations[0];return t!=null&&w.isIdentifier(t.name)?t.name.text:null}return null}function Yu(e){return w.isIdentifier(e)?e.text:(w.isFunctionExpression(e)||w.isClassExpression(e))&&e.name!=null?e.name.text:"default"}function Qu(e){if(!w.canHaveModifiers(e))return!1;let t=w.getModifiers(e);return t!=null&&t.some(r=>r.kind===w.SyntaxKind.ExportKeyword)}function No(e,t){let r=Zu(e,t),n=e.getChildren(t).flatMap(o=>No(o,t));return r==null?n:[r,...n]}function Zu(e,t){let r=ep(e);if(r==null)return null;let n=tp(r);if(n==null)return null;let o=sp(r,n);return o==null?null:{kind:n,label:o,line:mp(t,e.getStart(t))}}function ep(e){return w.isJsxSelfClosingElement(e)&&w.isIdentifier(e.tagName)?{attrs:e.attributes,children:[],tag:e.tagName.text}:w.isJsxElement(e)&&w.isIdentifier(e.openingElement.tagName)?{attrs:e.openingElement.attributes,children:e.children,tag:e.openingElement.tagName.text}:null}function tp({attrs:e,tag:t}){let r=de(e,"role");return r!=null?zu.get(r)??null:np(t,e)??op(t)??ip(e)}var rp=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 np(e,t){return rp.get(e)?.(t)??null}function op(e){return/^[A-Z]/.test(e)?Gu.find(([t])=>t.test(e))?.[1]??null:null}function ip(e){return jo.find(([t])=>cp(e,t))?.[1]??null}function sp({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")??(ap(r)?void 0:pp(t))??lp(e,n)}function ap(e){return e==="input"||e==="textarea"||e==="select"}function lp(e,t){let r=jo.find(([,o])=>o===t)?.[0];if(r==null)return;let n=dp(e,r);if(n!=null){if(w.isIdentifier(n))return n.text;if(w.isArrowFunction(n)||w.isFunctionExpression(n))return Oo(n.body)}}function Oo(e){if(w.isCallExpression(e)){let t=e.expression;return w.isIdentifier(t)?t.text:w.isPropertyAccessExpression(t)?t.name.text:void 0}return w.forEachChild(e,Oo)}function cp(e,t){return e.properties.some(r=>w.isJsxAttribute(r)&&w.isIdentifier(r.name)&&r.name.text===t)}function Do(e,t){return e.properties.find(r=>w.isJsxAttribute(r)&&w.isIdentifier(r.name)&&r.name.text===t)}function de(e,t){let r=Do(e,t);return r==null?void 0:up(r.initializer)}function dp(e,t){let r=Do(e,t);if(!(r?.initializer==null||!w.isJsxExpression(r.initializer)))return r.initializer.expression}function up(e){if(e==null)return"";if(w.isStringLiteral(e))return e.text;if(w.isJsxExpression(e))return _o(e.expression)}function pp(e){let t=e.flatMap(r=>Lo(r)).join(" ").trim();return t.length===0?void 0:t}function Lo(e){if(w.isJsxText(e)){let t=e.text.trim();return t.length===0?[]:[t]}if(w.isJsxExpression(e)){let t=_o(e.expression);return t==null?[]:[t]}return w.isJsxElement(e)?e.children.flatMap(t=>Lo(t)):[]}function _o(e){if(e!=null){if(w.isStringLiteral(e)||w.isNoSubstitutionTemplateLiteral(e))return e.text;if(w.isCallExpression(e)&&e.arguments.length===1){let t=e.arguments[0];if(t!=null&&(w.isStringLiteral(t)||w.isNoSubstitutionTemplateLiteral(t)))return t.text}}}function mp(e,t){return e.getLineAndCharacterOfPosition(t).line+1}var gp=Vt.join(".ripplo","coverage.d.ts");function Fe({cwd:e}){yp({cwd:e,ignorePaths:ke})}function yp({cwd:e,ignorePaths:t}){let r=He({cwd:e,ignorePaths:t});bp({content:wp(r),cwd:e})}function He({cwd:e,ignorePaths:t}){let n=hp({cwd:e,ignorePaths:t}).flatMap(o=>Xr({cwd:e,file:o}));return[...new Set(n)].sort((o,i)=>o.localeCompare(i))}function hp({cwd:e,ignorePaths:t}){let r=K(["ls-files","--cached","--others","--exclude-standard","-z"],e),n=fp([...t]);return r.split("\0").filter(o=>o.length>0&&/\.(tsx|jsx)$/.test(o)).filter(o=>!n(o)).filter(o=>at.existsSync(Vt.join(e,o)))}function Xr({cwd:e,file:t}){let r=at.readFileSync(Vt.join(e,t),"utf8");return Ut({filePath:t,source:r}).map(n=>n.id)}function wp(e){let t=`// GENERATED \u2014 do not edit
247
+ `)}import{createHash as fd}from"crypto";import at from"fs/promises";import Ue from"path";import{z as Dt}from"zod";import{z as vo}from"zod";import{z as _e}from"zod";import{z as u}from"zod";import{z as Se}from"zod";import{z as Eo}from"zod";import{z as T}from"zod";import{z as Q}from"zod";import{z as Wr}from"zod";import{z as x}from"zod";var gd=Dt.object({__codec:Dt.string().min(1),data:Dt.unknown(),version:Dt.number().int().positive()}),yd=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}},hd=class extends Error{constructor(e){super(`Codec mismatch: expected "${e.expected}", got "${e.got}"`),this.name="CodecMismatchError"}};function Gr(e){return Po({legacy:void 0,migrators:[],name:e,schemas:[]})}function wd(e,t){let r=JSON.parse(t);return e.decode(r)}function Po(e){return{initial:t=>qr(t,{...e,schemas:[t]}),legacy:t=>Po({...e,legacy:t})}}function qr(e,t){return{build:()=>bd(e,t),legacy:r=>qr(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return qr(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function bd(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>vd(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function vd(e,t,r){let{data:n,version:o}=Sd(t,r),i=xo(t,n,o);return e.parse(i)}function Sd(e,t){let r=gd.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new hd({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 xo(e,t,r){let n=e.schemas.length;if(r>n)throw new yd({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 xo(e,s(i),r+1)}var Kr=_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."),kd=Se.object({by:Se.literal("testId"),value:Se.string().min(1)}),Rd=Se.object({by:Se.literal("role"),name:Se.string().optional(),role:Se.string().min(1)}),E=Se.discriminatedUnion("by",[kd,Rd]),lt=Eo.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),Pd=Eo.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]),xd=T.object({type:T.literal("static"),value:T.union([T.string(),T.number(),T.boolean()])}),Lt=T.object({name:T.string().min(1),type:T.literal("variable")}),Ed=T.discriminatedUnion("type",[xd,Lt]),ae=T.discriminatedUnion("type",[T.object({type:T.literal("static"),value:T.string()}),Lt]),Cd=T.discriminatedUnion("type",[T.object({type:T.literal("static"),value:T.number().int().nonnegative()}),Lt]),Ad=T.discriminatedUnion("type",[T.object({type:T.literal("static"),value:T.union([T.string(),T.number(),T.boolean()])}),Lt]),Id=Q.discriminatedUnion("type",[Q.object({default:Q.string().optional(),type:Q.literal("string")}),Q.object({default:Q.number().optional(),type:Q.literal("number")}),Q.object({default:Q.boolean().optional(),type:Q.literal("boolean")}),Q.object({key:Q.string().min(1),type:Q.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()},So=500,Td=u.object({...v,type:u.literal("goto"),url:ae}),$d=u.object({...v,locator:E,type:u.literal("click")}),jd=u.object({...v,locator:E,type:u.literal("fill"),value:ae}),Nd=u.object({...v,locator:E,type:u.literal("select"),value:ae}),Od=u.object({...v,locator:E,type:u.literal("hover")}),Dd=u.object({...v,key:u.string().min(1),locator:E.optional(),type:u.literal("press")}),Ld=u.object({...v,locator:E,type:u.literal("check")}),_d=u.object({...v,locator:E,type:u.literal("uncheck")}),Ud=u.object({...v,height:u.number().int().positive(),type:u.literal("setViewport"),width:u.number().int().positive()}),Vd=u.object({...v,message:u.string().min(1),type:u.literal("fail")}),Fd=u.object({...v,type:u.literal("setVariable"),value:Ed,variable:u.string().min(1)}),Hd=u.object({...v,locator:E,type:u.literal("extractText"),variable:u.string().min(1)}),Md=u.object({...v,files:u.array(u.string()).min(1),locator:E,type:u.literal("upload")}),Bd=u.object({...v,locator:E,type:u.literal("dblclick")}),Wd=u.object({...v,source:E,target:E,type:u.literal("drag")}),qd=u.object({...v,locator:E,type:u.literal("scrollIntoView")}),zd=u.object({...v,locator:E,type:u.literal("type"),value:ae}),Gd=u.object({...v,locator:E,type:u.literal("focus")}),Kd=u.object({...v,locator:E,type:u.literal("clear")}),Jd=u.object({...v,locator:E,type:u.literal("rightClick")}),Xd=u.object({...v,action:u.enum(["accept","dismiss"]),promptText:u.string().optional(),type:u.literal("handleDialog")}),Yd=u.object({...v,action:u.enum(["read","write"]),type:u.literal("clipboard"),value:ae.optional(),variable:u.string().min(1).optional()}),Qd=u.object({...v,permission:u.string().min(1),state:u.enum(["granted","prompt"]),type:u.literal("setPermission")}),Zd=u.object({...v,locator:E,type:u.literal("assertVisible")}),eu=u.object({...v,locator:E,type:u.literal("assertNotVisible")}),tu=u.object({...v,expected:ae,locator:E,operator:lt,type:u.literal("assertText")}),ru=u.object({...v,expected:ae,operator:lt,type:u.literal("assertUrl")}),nu=u.object({...v,expected:Cd,locator:E,operator:Pd,type:u.literal("assertCount")}),ou=u.object({...v,expected:ae,locator:E,operator:lt,type:u.literal("assertValue")}),iu=u.object({...v,attribute:u.string().min(1),expected:ae,locator:E,operator:lt,type:u.literal("assertAttribute")}),su=u.object({...v,locator:E,type:u.literal("assertEnabled")}),au=u.object({...v,locator:E,type:u.literal("assertDisabled")}),lu=u.object({...v,expected:ae,operator:lt,type:u.literal("assertTitle")}),cu=u.object({...v,locator:E,type:u.literal("assertChecked")}),du=u.object({...v,locator:E,type:u.literal("assertNotChecked")}),uu=u.object({...v,locator:E,type:u.literal("assertFocused")}),pu=u.object({...v,locator:E,type:u.literal("assertNotFocused")}),mu=u.object({...v,budget:u.enum(["fast","slow","async"]),observer:u.string().min(1).max(200),params:u.record(u.string().max(200),Ad),type:u.literal("assertObserver")}),fu=u.discriminatedUnion("type",[Td,$d,jd,Nd,Od,Dd,Ld,_d,Zd,eu,tu,ru,nu,ou,iu,su,au,Ud,Vd,Fd,Hd,Md,Bd,Wd,qd,zd,Gd,Kd,Jd,Xd,Yd,Qd,lu,cu,du,uu,pu,mu]),Co=u.object({entryNode:u.string().min(1).max(200),nodes:u.record(u.string().max(200),fu).refine(e=>Object.keys(e).length<=So,`Workflow has more than ${String(So)} nodes`),uiOnly:u.boolean().optional(),variableNamespaces:u.record(u.string().max(200),u.string().max(500)).optional(),variables:u.record(u.string().max(200),Id).optional()}),gu=vo.record(vo.string().max(200),Kr),yu={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},hu={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},RS=Gr("workflow-spec").legacy(yu).initial(Co).build(),PS=Gr("precondition-map").legacy(hu).initial(gu).build(),wu=["fast","slow","async"],Ao=Wr.object({budget:Wr.enum(wu).describe("Polling budget tier: fast | slow | async"),description:Wr.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",bu=".ripplo/fixtures",Io=5e3,vu=x.record(x.string().max(200),x.string().max(200)),To=x.object({coverage:x.array(x.string().max(500)).max(2e3).default([]),expectedOutcome:x.string().max(2e3),name:x.string().max(200),preconditions:x.array(x.string().max(200)).max(1e3),requiresKeys:vu,slug:x.string().max(200),sourcePath:x.string().max(500).optional(),spec:Co}),Su=x.object({sha256:x.string().regex(/^[0-9a-f]{64}$/u),size:x.number().int().nonnegative()}),ku=x.record(x.string().min(1).max(500),Su),Ru=x.object({observers:x.record(x.string().max(200),Ao),preconditions:x.record(x.string().max(200),Kr),tests:x.array(To).max(Io)}),Pu=x.object({fixtures:ku,observers:x.record(x.string().max(200),Ao),preconditions:x.record(x.string().max(200),Kr),tests:x.array(To).max(Io)}),$o=Gr("ripplo-lockfile").initial(Ru).upgrade(Pu,e=>({...e,fixtures:{}})).build();function jo(e){return{fixtures:{...e.fixtures},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 zr(e){let t=$o.encode(e);return`${JSON.stringify(t,Iu(t),2)}
248
+ `}async function _t({cwd:e}){let t=Ue.join(e,le),r=await Au(t);return r==null?null:wd($o,r)}var ko=10*1024*1024,Ro=50*1024*1024;async function ce({cwd:e,result:t}){let r=await xu({cwd:e,result:t}),n=jo(r),o=Ue.join(e,le);await at.mkdir(Ue.dirname(o),{recursive:!0}),await at.writeFile(o,zr(n),"utf8")}async function xu({cwd:e,result:t}){let r=Cu(t);if(r.size===0)return{...t,fixtures:{}};let n=Ue.join(e,bu),o=[...r].toSorted((a,l)=>a.localeCompare(l)),i=await Promise.all(o.map(async a=>{let l=await Eu({fixturesRoot:n,name:a});if(l.size>ko)throw new Error(`Fixture "${a}" is ${String(l.size)} bytes; exceeds per-file limit of ${String(ko)} bytes`);return[a,l]}));if(i.reduce((a,[,l])=>a+l.size,0)>Ro)throw new Error(`Total fixtures size exceeds limit of ${String(Ro)} bytes`);return{...t,fixtures:Object.fromEntries(i)}}async function Eu({fixturesRoot:e,name:t}){if(t.includes("..")||Ue.isAbsolute(t))throw new Error(`Invalid fixture name "${t}": must be a path under .ripplo/fixtures/`);let r=Ue.join(e,t),n=await at.lstat(r).catch(s=>{throw No(s)&&s.code==="ENOENT"?new Error(`Fixture "${t}" not found at ${r}`):s});if(n.isSymbolicLink())throw new Error(`Fixture "${t}" is a symlink; symlinks are not allowed`);if(!n.isFile())throw new Error(`Fixture "${t}" is not a regular file`);let o=await at.readFile(r);return{sha256:fd("sha256").update(o).digest("hex"),size:o.byteLength}}function Cu(e){let t=new Set;return e.tests.forEach(r=>{Object.values(r.spec.nodes).forEach(n=>{n.type==="upload"&&n.files.forEach(o=>t.add(o))})}),t}function Ut({compiled:e,existing:t}){if(t==null)return"missing";let r=zr(jo(e)),n=zr(t);return r===n?"match":"stale"}async function Au(e){try{return await at.readFile(e,"utf8")}catch(t){if(No(t)&&t.code==="ENOENT")return null;throw t}}function No(e){return e instanceof Error&&"code"in e}function Iu(e){return function(r,n){return n===e||!Tu(n)?n:Object.fromEntries(Object.entries(n).toSorted(([o],[i])=>o.localeCompare(i)))}}function Tu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import ct from"fs";import Ht from"path";var Jr=["**/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 Oo(e){return e.data}function Do(e){return{as(t){return{data:{label:t,node:e}}}}}function Vt(e){let t=e.getPreconditions(),r=e.getObservers(),n=e.getTests();$u(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=>ju(a,t));return{fixtures:{},observers:i,preconditions:o,tests:s}}function $u(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 ju(e,t){let r=e.id,{accessedKeys:n,vars:o}=Ou(e.requiresKeys),i=e.startsAtFn==null?void 0:e.startsAtFn(o),s=e.stepsFn==null?[]:e.stepsFn(o),a=i==null?s:[Nu(i),...s],l=Du(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=_u(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 Nu(e){return Do({type:"goto",url:{type:"static",value:e}}).as(`navigate to ${e}`)}function Ou(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 Du(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]=Lu(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 Lu(e,t,r){let{label:n,node:o}=Oo(e);return{...o,id:t,label:n,next:r}}function _u(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 DS,WebhookVerificationError as LS}from"standardwebhooks";import{z as S}from"zod";var US=S.object({preconditions:S.array(S.string().min(1))}),VS=S.object({data:S.record(S.string(),S.record(S.string(),S.union([S.string(),S.number(),S.boolean()]))),preconditions:S.array(S.string().min(1))}),FS=S.object({observer:S.string().min(1).max(200),params:S.record(S.string().max(200),S.union([S.string(),S.number(),S.boolean()]))}),Uu=S.discriminatedUnion("kind",[S.object({kind:S.literal("pass")}),S.object({kind:S.literal("retry"),reason:S.string()}),S.object({kind:S.literal("fail"),reason:S.string()})]),HS=S.object({error:S.string().optional(),outcome:Uu.optional(),success:S.boolean()});function Ve(e){let t=[];return e.tests.forEach(r=>{let n=Vu(r),o=i=>{t.push({...i,test:r.slug})};lp.forEach(i=>{i(n,r,o)})}),{diagnostics:t}}function Vu(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 Fu(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 Hu(e,t,r){Object.keys(t.spec.variables??{}).length>0&&e.forEach(o=>{if(o.type==="fill"&&_o(o.value)){let i=o.value.value;!Uo(i)&&Ku(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 Mu(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 Bu(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 Wu(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 qu(e,t,r){let n=0;e.forEach((o,i)=>{if(!(i===0&&o.type==="goto")){if(Fe(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 zu(e,t,r){if(e.length===0)return;let n=e.at(-1);n!=null&&!Fe(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 Gu(e,t,r){t.implemented&&e.length===0&&r({message:"Test has zero steps",rule:"no-empty-steps",step:void 0})}function _o(e){return!(typeof e!="object"||e==null||!("type"in e)||e.type!=="static"||!("value"in e)||typeof e.value!="string")}function Uo(e){return e.includes("{{")}function Ku(e){return e.includes("@")||/\b[a-f0-9]{8,}\b/.test(e)||/^(test|ripplo|example|sample|demo)/i.test(e)}function Fe(e){return e.type.startsWith("assert")}var Ju=new Set(["assertText","assertValue","assertCount","assertUrl","assertNotVisible","assertChecked","assertNotChecked","assertAttribute","assertDisabled","assertEnabled"]);function Xu(e){return Ju.has(e.type)}function Yu(e,t,r){!t.implemented||e.length===0||e.some(n=>Fe(n))||r({message:"Test has zero assertion steps \u2014 cannot verify expectedOutcome. Add assert.* steps.",rule:"no-assertions",step:void 0})}function Qu(e,t,r){if(!t.implemented||e.length<=3)return;let n=e.filter(i=>Fe(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 Xr(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 Zu(e,t,r){e.forEach((n,o)=>{if(n.type!=="click")return;let i=Xr(n);if(i==null)return;let s=e.slice(o+1,o+4);s.find(c=>c.type==="assertVisible"&&Xr(c)===i)==null||s.some(c=>Xu(c)||Fe(c)&&Xr(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 ep=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 Yr(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=3&&!ep.has(t))}function tp(e){let t=e.label==null?[]:Yr(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,...Yr(n)]}function rp(e,t,r){if(!t.implemented||e.length===0)return;let n=new Set(Yr(t.expectedOutcome));if(n.size===0)return;let o=e.filter(s=>Fe(s));if(o.length===0)return;o.some(s=>tp(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 np=/save|submit|create|delete|remove|send|invite|update|confirm|publish|apply|pay|subscribe|upgrade|cancel|archive|rename/i;function Lo(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 np.test(r)}function op(e,t,r){!t.implemented||t.spec.uiOnly===!0||e.forEach((n,o)=>{if(!Lo(n)||"uiOnly"in n&&n.uiOnly===!0)return;let i=e.slice(o+1),s=i.findIndex(p=>Lo(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 ip(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])=>_o(a)&&Uo(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 sp(e,t,r){e.forEach(n=>{n.type==="upload"&&n.files.forEach(o=>{if(o.length===0){r({message:`upload "${n.label??n.id}" references an empty fixture name`,rule:"upload-fixture-name",step:n.label??n.id});return}(o.includes("..")||o.startsWith("/"))&&r({message:`upload "${n.label??n.id}" references "${o}" \u2014 fixture names must be relative paths under .ripplo/fixtures/, no ".." or absolute paths`,rule:"upload-fixture-name",step:n.label??n.id})})})}function ap(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 lp=[Fu,Hu,ap,Mu,Bu,Wu,qu,zu,Gu,Yu,Qu,Zu,rp,op,ip,sp];import Np from"picomatch";import{execFileSync as cp,spawnSync as dp}from"child_process";function M(e,t){return cp("git",[...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}function Vo(e,t){let r=dp("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 w from"typescript";import*as Fo from"remeda";var Ho=[["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"]],up=new Map([["button","click"],["link","navigate"],["textbox","input"],["searchbox","input"],["combobox","select"],["listbox","select"]]),pp=[[/(?:^|[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 Ft({filePath:e,source:t}){let r=w.createSourceFile(e,t,w.ScriptTarget.Latest,!0,w.ScriptKind.TSX);return r.statements.flatMap(n=>mp({filePath:e,sf:r,stmt:n}))}function mp({filePath:e,sf:t,stmt:r}){let n=gp(r);if(n==null||fp(n))return[];let o=Mo(r,t).map(i=>({id:`${e}#${n}.${i.kind}[${i.label}]`,line:i.line}));return Fo.uniqueBy(o,i=>i.id)}function fp(e){return e.endsWith("Fragment")||e.endsWith("Skeleton")||/^use[A-Z]/.test(e)||/^[A-Z][A-Z0-9_]*$/.test(e)}function gp(e){if(w.isExportAssignment(e))return yp(e.expression);if(!hp(e))return null;if(w.isFunctionDeclaration(e)||w.isClassDeclaration(e))return e.name?.text??null;if(w.isVariableStatement(e)){let t=e.declarationList.declarations[0];return t!=null&&w.isIdentifier(t.name)?t.name.text:null}return null}function yp(e){return w.isIdentifier(e)?e.text:(w.isFunctionExpression(e)||w.isClassExpression(e))&&e.name!=null?e.name.text:"default"}function hp(e){if(!w.canHaveModifiers(e))return!1;let t=w.getModifiers(e);return t!=null&&t.some(r=>r.kind===w.SyntaxKind.ExportKeyword)}function Mo(e,t){let r=wp(e,t),n=e.getChildren(t).flatMap(o=>Mo(o,t));return r==null?n:[r,...n]}function wp(e,t){let r=bp(e);if(r==null)return null;let n=vp(r);if(n==null)return null;let o=xp(r,n);return o==null?null:{kind:n,label:o,line:jp(t,e.getStart(t))}}function bp(e){return w.isJsxSelfClosingElement(e)&&w.isIdentifier(e.tagName)?{attrs:e.attributes,children:[],tag:e.tagName.text}:w.isJsxElement(e)&&w.isIdentifier(e.openingElement.tagName)?{attrs:e.openingElement.attributes,children:e.children,tag:e.openingElement.tagName.text}:null}function vp({attrs:e,tag:t}){let r=de(e,"role");return r!=null?up.get(r)??null:kp(t,e)??Rp(t)??Pp(e)}var Sp=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 kp(e,t){return Sp.get(e)?.(t)??null}function Rp(e){return/^[A-Z]/.test(e)?pp.find(([t])=>t.test(e))?.[1]??null:null}function Pp(e){return Ho.find(([t])=>Ap(e,t))?.[1]??null}function xp({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")??(Ep(r)?void 0:$p(t))??Cp(e,n)}function Ep(e){return e==="input"||e==="textarea"||e==="select"}function Cp(e,t){let r=Ho.find(([,o])=>o===t)?.[0];if(r==null)return;let n=Ip(e,r);if(n!=null){if(w.isIdentifier(n))return n.text;if(w.isArrowFunction(n)||w.isFunctionExpression(n))return Bo(n.body)}}function Bo(e){if(w.isCallExpression(e)){let t=e.expression;return w.isIdentifier(t)?t.text:w.isPropertyAccessExpression(t)?t.name.text:void 0}return w.forEachChild(e,Bo)}function Ap(e,t){return e.properties.some(r=>w.isJsxAttribute(r)&&w.isIdentifier(r.name)&&r.name.text===t)}function Wo(e,t){return e.properties.find(r=>w.isJsxAttribute(r)&&w.isIdentifier(r.name)&&r.name.text===t)}function de(e,t){let r=Wo(e,t);return r==null?void 0:Tp(r.initializer)}function Ip(e,t){let r=Wo(e,t);if(!(r?.initializer==null||!w.isJsxExpression(r.initializer)))return r.initializer.expression}function Tp(e){if(e==null)return"";if(w.isStringLiteral(e))return e.text;if(w.isJsxExpression(e))return zo(e.expression)}function $p(e){let t=e.flatMap(r=>qo(r)).join(" ").trim();return t.length===0?void 0:t}function qo(e){if(w.isJsxText(e)){let t=e.text.trim();return t.length===0?[]:[t]}if(w.isJsxExpression(e)){let t=zo(e.expression);return t==null?[]:[t]}return w.isJsxElement(e)?e.children.flatMap(t=>qo(t)):[]}function zo(e){if(e!=null){if(w.isStringLiteral(e)||w.isNoSubstitutionTemplateLiteral(e))return e.text;if(w.isCallExpression(e)&&e.arguments.length===1){let t=e.arguments[0];if(t!=null&&(w.isStringLiteral(t)||w.isNoSubstitutionTemplateLiteral(t)))return t.text}}}function jp(e,t){return e.getLineAndCharacterOfPosition(t).line+1}var Op=Ht.join(".ripplo","coverage.d.ts");function He({cwd:e}){Dp({cwd:e,ignorePaths:ke})}function Dp({cwd:e,ignorePaths:t}){let r=Me({cwd:e,ignorePaths:t});Up({content:_p(r),cwd:e})}function Me({cwd:e,ignorePaths:t}){let n=Lp({cwd:e,ignorePaths:t}).flatMap(o=>Qr({cwd:e,file:o}));return[...new Set(n)].sort((o,i)=>o.localeCompare(i))}function Lp({cwd:e,ignorePaths:t}){let r=M(["ls-files","--cached","--others","--exclude-standard","-z"],e),n=Np([...t]);return r.split("\0").filter(o=>o.length>0&&/\.(tsx|jsx)$/.test(o)).filter(o=>!n(o)).filter(o=>ct.existsSync(Ht.join(e,o)))}function Qr({cwd:e,file:t}){let r=ct.readFileSync(Ht.join(e,t),"utf8");return Ft({filePath:t,source:r}).map(n=>n.id)}function _p(e){let t=`// GENERATED \u2014 do not edit
249
249
  import "@ripplo/testing";
250
250
 
251
251
  declare module "@ripplo/testing" {
@@ -256,22 +256,22 @@ declare module "@ripplo/testing" {
256
256
  `:`${t}${r}
257
257
  }
258
258
  }
259
- `}function bp({content:e,cwd:t}){let r=Vt.join(t,gp);at.existsSync(r)&&at.readFileSync(r,"utf8")===e||at.writeFileSync(r,e)}import Uo from"path";import{createJiti as vp}from"jiti";var Sp=["getObservers","getPreconditions","getTests","getUnimplemented"];function kp(e){return e==null||typeof e!="object"?!1:Sp.every(t=>typeof Reflect.get(e,t)=="function")}function Rp(e){return e===null?"null":Array.isArray(e)?"array":typeof e}async function P(e){let t=Uo.join(e,".ripplo","index.ts"),r=Uo.join(e,".ripplo");try{let o=await vp(import.meta.url,{moduleCache:!1,sourceMaps:!0}).import(t),i=o!=null&&typeof o=="object"&&"default"in o?Reflect.get(o,"default"):o;if(!kp(i))return{error:`${t} must default-export a RipploBuilder (got ${Rp(i)})`,ok:!1};let s=_t(i);return{builder:i,ok:!0,result:s}}catch(n){return{error:xp(n,r),ok:!1}}}var Pp=/\(?([^\s()]{1,500}\.ts):(\d{1,10}):(\d{1,10})\)?$/;function xp(e,t){if(!(e instanceof Error))return String(e);let r=Cp(e.stack,t);return r==null?e.message:`${r} \u2014 ${e.message}`}function Cp(e,t){if(e==null)return;let n=e.split(`
260
- `).map(a=>Pp.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 h(e,t){return t==null?`Load \`/ripplo:${e}\` skill for instructions.`:`Load \`/ripplo:${e}\` skill for instructions on ${t}.`}function Vo(e){return e.length===1?h(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 Fo(e){let t=process.cwd(),r=await P(t);if(r.ok||(process.stderr.write(`Compilation failed: ${r.error}
259
+ `}function Up({content:e,cwd:t}){let r=Ht.join(t,Op);ct.existsSync(r)&&ct.readFileSync(r,"utf8")===e||ct.writeFileSync(r,e)}import Go from"path";import{createJiti as Vp}from"jiti";var Fp=["getObservers","getPreconditions","getTests","getUnimplemented"];function Hp(e){return e==null||typeof e!="object"?!1:Fp.every(t=>typeof Reflect.get(e,t)=="function")}function Mp(e){return e===null?"null":Array.isArray(e)?"array":typeof e}async function P(e){let t=Go.join(e,".ripplo","index.ts"),r=Go.join(e,".ripplo");try{let o=await Vp(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 ${Mp(i)})`,ok:!1};let s=Vt(i);return{builder:i,ok:!0,result:s}}catch(n){return{error:Wp(n,r),ok:!1}}}var Bp=/\(?([^\s()]{1,500}\.ts):(\d{1,10}):(\d{1,10})\)?$/;function Wp(e,t){if(!(e instanceof Error))return String(e);let r=qp(e.stack,t);return r==null?e.message:`${r} \u2014 ${e.message}`}function qp(e,t){if(e==null)return;let n=e.split(`
260
+ `).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 h(e,t){return t==null?`Load \`/ripplo:${e}\` skill for instructions.`:`Load \`/ripplo:${e}\` skill for instructions on ${t}.`}function Ko(e){return e.length===1?h(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 Jo(e){let t=process.cwd(),r=await P(t);if(r.ok||(process.stderr.write(`Compilation failed: ${r.error}
261
261
  `),process.stderr.write(`${h("create","DSL authoring + lint rules")}
262
- `),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
262
+ `),process.exit(1)),e.check){let n=await _t({cwd:t}),o=Ut({compiled:r.result,existing:n});if(o==="match"){process.stdout.write(`${le} is up to date
263
263
  `);return}let i=o==="missing"?"missing":"out of date";process.stderr.write(`${le} is ${i} \u2014 run \`ripplo compile\` and commit the result
264
264
  `),process.stderr.write(`${h("setup")}
265
- `),process.exit(1)}await ce({cwd:t,result:r.result}),Fe({cwd:t}),process.stdout.write(`wrote ${le}
266
- `)}import me from"process";import Ep from"fs";import Ap from"path";import Ip from"picomatch";function Ho({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(He({cwd:t,ignorePaths:r})),o=Wo(e),i=Tp({cwd:t,ignorePaths:r});return Bo({acknowledged:o,allStatements:n,unacked:i})}function Mo({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(He({cwd:t,ignorePaths:r})),o=Wo(e);return Bo({acknowledged:o,allStatements:n,unacked:n})}function Bo({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 Tp({cwd:e,ignorePaths:t}){let r=$p({cwd:e,ignorePaths:t}),n=new Set(r.flatMap(i=>jp({cwd:e,file:i}))),o=new Set(r.flatMap(i=>Np({cwd:e,file:i})?Xr({cwd:e,file:i}):[]));return new Set([...o].filter(i=>!n.has(i)))}function $p({cwd:e,ignorePaths:t}){let r=K(["diff","--name-only","HEAD","-z"],e),n=K(["ls-files","--others","--exclude-standard","-z"],e),o=Ip([...t]);return[...new Set([...r.split("\0"),...n.split("\0")])].filter(i=>i.length>0&&/\.(tsx|jsx)$/.test(i)).filter(i=>!o(i))}function jp({cwd:e,file:t}){let r=To(`HEAD:${t}`,e);return r==null?[]:Ut({filePath:t,source:r}).map(n=>n.id)}function Np({cwd:e,file:t}){return Ep.existsSync(Ap.join(e,t))}async function qo(){let e=me.cwd(),t=await P(e);t.ok||(me.stderr.write(`Compilation failed: ${t.error}
267
- `),me.exit(1));let r=He({cwd:e,ignorePaths:ke}),n=Mo({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;me.stdout.write(`Coverage: ${String(s)}/${String(r.length)} statements acknowledged
265
+ `),process.exit(1)}await ce({cwd:t,result:r.result}),He({cwd:t}),process.stdout.write(`wrote ${le}
266
+ `)}import me from"process";import zp from"fs";import Gp from"path";import Kp from"picomatch";function Xo({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(Me({cwd:t,ignorePaths:r})),o=Zo(e),i=Jp({cwd:t,ignorePaths:r});return Qo({acknowledged:o,allStatements:n,unacked:i})}function Yo({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(Me({cwd:t,ignorePaths:r})),o=Zo(e);return Qo({acknowledged:o,allStatements:n,unacked:n})}function Qo({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 Zo(e){return new Set(e.tests.flatMap(t=>t.coverage))}function Jp({cwd:e,ignorePaths:t}){let r=Xp({cwd:e,ignorePaths:t}),n=new Set(r.flatMap(i=>Yp({cwd:e,file:i}))),o=new Set(r.flatMap(i=>Qp({cwd:e,file:i})?Qr({cwd:e,file:i}):[]));return new Set([...o].filter(i=>!n.has(i)))}function Xp({cwd:e,ignorePaths:t}){let r=M(["diff","--name-only","HEAD","-z"],e),n=M(["ls-files","--others","--exclude-standard","-z"],e),o=Kp([...t]);return[...new Set([...r.split("\0"),...n.split("\0")])].filter(i=>i.length>0&&/\.(tsx|jsx)$/.test(i)).filter(i=>!o(i))}function Yp({cwd:e,file:t}){let r=Vo(`HEAD:${t}`,e);return r==null?[]:Ft({filePath:t,source:r}).map(n=>n.id)}function Qp({cwd:e,file:t}){return zp.existsSync(Gp.join(e,t))}async function ei(){let e=me.cwd(),t=await P(e);t.ok||(me.stderr.write(`Compilation failed: ${t.error}
267
+ `),me.exit(1));let r=Me({cwd:e,ignorePaths:ke}),n=Yo({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;me.stdout.write(`Coverage: ${String(s)}/${String(r.length)} statements acknowledged
268
268
  `),o.length>0&&(me.stdout.write(`
269
269
  Unacknowledged (${String(o.length)}):
270
270
  `),o.forEach(a=>me.stdout.write(` ${a.id}
271
271
  `))),i.length>0&&(me.stdout.write(`
272
272
  Stale claims (${String(i.length)}):
273
273
  `),i.forEach(a=>me.stdout.write(` ${a.id}
274
- `))),n.length>0&&me.exit(1)}import{graphql as Dp}from"gql.tada";import zo from"fs";import Yr from"path";function Go(e){let t=zo.realpathSync(e),r=t,n=Yr.dirname(r);for(;n!==r;){if(zo.existsSync(Yr.join(r,".git")))return r;r=n,n=Yr.dirname(r)}return t}function _(e){let t=nr(e),r=Te(),n=ee();if(n==null)throw new Error("ripplo: not authenticated. Run `ripplo auth login`.");return{appUrl:r.appUrl,cwd:Go(e),engineUrl:r.engineUrl,projectId:co()??t.projectId,ripploServerUrl:Y(),token:n,webhookSecret:r.webhookSecret}}import lt from"fs";var Op="dev.pid";function Ko(e){return nt(e,Op)}function Me(e){let t=Ko(e);if(!lt.existsSync(t))return!1;let r=lt.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 Jo(e){rt(e);let t=Ko(e);lt.writeFileSync(t,String(process.pid));let r=!1;return()=>{if(!r){r=!0;try{let n=lt.readFileSync(t,"utf8").trim();Number.parseInt(n,10)===process.pid&&lt.unlinkSync(t)}catch{}}}}var Lp=Dp(`
274
+ `))),n.length>0&&me.exit(1)}import{graphql as nm}from"gql.tada";import ti from"fs";import Zr from"path";function ri(e){let t=ti.realpathSync(e),r=t,n=Zr.dirname(r);for(;n!==r;){if(ti.existsSync(Zr.join(r,".git")))return r;r=n,n=Zr.dirname(r)}return t}function _(e){let t=sr(e),r=Te(),n=ee();if(n==null)throw new Error("ripplo: not authenticated. Run `ripplo auth login`.");return{appUrl:r.appUrl,cwd:ri(e),engineUrl:r.engineUrl,projectId:fo()??t.projectId,ripploServerUrl:Y(),token:n,webhookSecret:r.webhookSecret}}import dt from"fs";var Zp="dev.pid";function ni(e){return ot(e,Zp)}function Be(e){let t=ni(e);if(!dt.existsSync(t))return!1;let r=dt.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 oi(e){nt(e);let t=ni(e);dt.writeFileSync(t,String(process.pid));let r=!1;return()=>{if(!r){r=!0;try{let n=dt.readFileSync(t,"utf8").trim();Number.parseInt(n,10)===process.pid&&dt.unlinkSync(t)}catch{}}}}import em from"fs";import en from"path";var tm=["MERGE_HEAD","rebase-merge","rebase-apply","CHERRY_PICK_HEAD","REVERT_HEAD"];function Mt(e){let t=rm(e);return t==null?!1:tm.some(r=>em.existsSync(en.join(t,r)))}function rm(e){try{let t=M(["rev-parse","--git-dir"],e).trim();return t.length===0?null:en.isAbsolute(t)?t:en.resolve(e,t)}catch{return null}}var om=nm(`
275
275
  query DevSessionCheckHealth($projectId: String!, $cwd: String!) {
276
276
  project(id: $projectId) {
277
277
  id
@@ -280,26 +280,26 @@ Stale claims (${String(i.length)}):
280
280
  }
281
281
  }
282
282
  }
283
- `);function Xo(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 Yo(e){let t=Me(e),r;try{r=_(e)}catch{return{status:t?"starting":"missing",type:"dev-session"}}return(await f({config:r,document:Lp,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 Fp(e);case"env-files":return Hp(e);case"token":return Mp(e);case"dev-server":return Bp(e);case"dev-session":return Xo(e);case"preconditions":return zp(e);case"webhook-verification":return Wp(e);case"preconditions-validation":return Gp(e);case"workflows":return Kp(e);case"browser":return qp(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 _p(e);case"lockfile":return Up(e);case"pre-commit-hook":return Vp(e)}}function _p(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 Up(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 Vp(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 Fp(e){return e.valid?"\u2713 Settings: Project configured":`\u2717 Settings: Missing fields: ${e.missingFields.join(", ")}`}function Hp(e){return e.missing.length===0?"\u2713 Env files: declared files present":`\u2717 Env files: declared in .ripplo/project.json but missing:
283
+ `);function ii(e){switch(e.status){case"active":return e.gitMidOperation?"\u2713 Dev session: ripplo watch is live (hooks auto-paused \u2014 git is mid-merge/rebase/cherry-pick; resumes when the operation completes or aborts)":"\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 si(e){let t=Be(e),r=Mt(e),n;try{n=_(e)}catch{return{gitMidOperation:r,status:t?"starting":"missing",type:"dev-session"}}return(await f({config:n,document:om,variables:{cwd:n.cwd,projectId:n.projectId}}).catch(()=>null))?.project?.devSession!=null?{gitMidOperation:r,status:"active",type:"dev-session"}:{gitMidOperation:r,status:t?"starting":"missing",type:"dev-session"}}function ai(e){switch(e.type){case"settings":return lm(e);case"env-files":return cm(e);case"token":return dm(e);case"dev-server":return um(e);case"dev-session":return ii(e);case"preconditions":return fm(e);case"webhook-verification":return pm(e);case"preconditions-validation":return gm(e);case"workflows":return ym(e);case"browser":return mm(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 im(e);case"lockfile":return sm(e);case"pre-commit-hook":return am(e)}}function im(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 sm(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 am(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 lm(e){return e.valid?"\u2713 Settings: Project configured":`\u2717 Settings: Missing fields: ${e.missingFields.join(", ")}`}function cm(e){return e.missing.length===0?"\u2713 Env files: declared files present":`\u2717 Env files: declared in .ripplo/project.json but missing:
284
284
  ${e.missing.map(r=>` ${r}`).join(`
285
285
  `)}
286
- 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 Mp(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 ${Y()} to validate token.`}}function Bp(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 Wp(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 qp(e){return e.installed?"\u2713 Browser: Chromium installed":"\u2717 Browser: Chromium not installed. Run: npx playwright install chromium"}function zp(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 Gp(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"}
286
+ 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 dm(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 ${Y()} to validate token.`}}function um(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 pm(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 mm(e){return e.installed?"\u2713 Browser: Chromium installed":"\u2717 Browser: Chromium not installed. Run: npx playwright install chromium"}function fm(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 gm(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"}
287
287
  ${t.join(`
288
- `)}`}function Kp(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=>Jp(r));return`\u2717 Tests: ${String(e.invalidNames.length)} invalid
288
+ `)}`}function ym(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=>hm(r));return`\u2717 Tests: ${String(e.invalidNames.length)} invalid
289
289
  ${t.join(`
290
- `)}`}function Jp(e){let t=e.errors.map(r=>" - "+(r.path===""?"":r.path+": ")+r.message);return" "+e.name+`:
290
+ `)}`}function hm(e){let t=e.errors.map(r=>" - "+(r.path===""?"":r.path+": ")+r.message);return" "+e.name+`:
291
291
  `+t.join(`
292
- `)}import Zr from"fs";import tm from"path";import{chromium as rm}from"playwright";import Xp from"fs";import Yp from"path";async function Zo(e){let t=Yp.join(e,".ripplo","index.ts");if(!Xp.existsSync(t))return{appUrl:void 0,engineUrl:void 0,errors:[{message:".ripplo/index.ts not found",path:""}],valid:!1,warnings:[]};let r=await P(e);if(!r.ok)return{appUrl:void 0,engineUrl:void 0,errors:[{message:r.error,path:".ripplo/"}],valid:!1,warnings:[]};try{let n=Te();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 ei({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 Qp}from"gql.tada";var Zp=Qp(`
292
+ `)}import rn from"fs";import Rm from"path";import{chromium as Pm}from"playwright";import wm from"fs";import bm from"path";async function li(e){let t=bm.join(e,".ripplo","index.ts");if(!wm.existsSync(t))return{appUrl:void 0,engineUrl:void 0,errors:[{message:".ripplo/index.ts not found",path:""}],valid:!1,warnings:[]};let r=await P(e);if(!r.ok)return{appUrl:void 0,engineUrl:void 0,errors:[{message:r.error,path:".ripplo/"}],valid:!1,warnings:[]};try{let n=Te();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 tn(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 ci({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 vm}from"gql.tada";var Sm=vm(`
293
293
  query DoctorAuthViewer {
294
294
  currentUser {
295
295
  name
296
296
  email
297
297
  }
298
298
  }
299
- `),em="Failed to connect to Ripplo server";async function ti({serverUrl:e,token:t}){try{let r=await f({config:ve({serverUrl:e,token:t}),document:Zp,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(em)?{kind:"unreachable"}:{kind:"invalid"}}}function ri(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 ni(e){let t=await im(e),r={missing:sr(e),type:"env-files"},n=await sm(),o=am(),i=await P(e),s=lm(i),a=um(i),l=await nm(e,i),c=om(e),p=await pm(t,i);return[t,r,n,...p,s,a,l,c,o]}async function nm(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 om(e){let t=tm.join(e,".git","hooks","pre-commit");return Zr.existsSync(t)?{installed:Zr.readFileSync(t,"utf8").includes("ripplo compile --check"),type:"pre-commit-hook"}:{installed:!1,type:"pre-commit-hook"}}async function im(e){let t=await Zo(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 sm(){let e=ee();if(e==null||e.length===0)return{email:void 0,status:"missing",type:"token"};let t=await ti({serverUrl:Y(),token:e});return t.kind==="valid"?{email:t.email,status:"valid",type:"token"}:{email:void 0,status:t.kind,type:"token"}}function am(){let e=rm.executablePath();return{installed:Zr.existsSync(e),type:"browser"}}function lm(e){if(!e.ok)return{errorCount:1,errors:[{message:e.error,path:""}],found:!1,type:"preconditions-validation",valid:!1};let t=cm(e.result.preconditions,e.result.tests);return{errorCount:t.length,errors:t,found:!0,type:"preconditions-validation",valid:t.length===0}}function cm(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}`})})}),dm(e).forEach(o=>{r.push({message:o,path:"preconditions"})}),r}function dm(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 um(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 pm(e,t){if(!e.valid||!t.ok)return[];let r;try{let a=Te();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 Yo(process.cwd());n.push(i);let s=await mm(r,t);return n.push(...s),n}async function mm(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=gm(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"}),oi(e.engineUrl)&&a.push({reachable:s,type:"engine-endpoint",url:i}),!s)return a;let l=await ei({appUrl:e.appUrl,engineUrl:e.engineUrl});a.push({rejectsUnsigned:l==null,type:"webhook-verification"});let c=await fm({engineUrl:i,webhookSecret:e.webhookSecret});return a.push({status:c,type:"adapter-enabled",url:i}),a}async function fm({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 oi(e){return e.startsWith("http://")||e.startsWith("https://")}function gm(e,t){return oi(t)?t:`${e}${t}`}async function ii(){let e=process.cwd(),t=await ni(e),r=t.map(o=>Qo(o));process.stdout.write(r.join(`
299
+ `),km="Failed to connect to Ripplo server";async function di({serverUrl:e,token:t}){try{let r=await f({config:ve({serverUrl:e,token:t}),document:Sm,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(km)?{kind:"unreachable"}:{kind:"invalid"}}}function ui(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 pi(e){let t=await Cm(e),r={missing:cr(e),type:"env-files"},n=await Am(),o=Im(),i=await P(e),s=Tm(i),a=Nm(i),l=await xm(e,i),c=Em(e),p=await Om(t,i);return[t,r,n,...p,s,a,l,c,o]}async function xm(e,t){if(!t.ok)return{status:"missing",type:"lockfile"};let r=await _t({cwd:e});return{status:Ut({compiled:t.result,existing:r}),type:"lockfile"}}function Em(e){let t=Rm.join(e,".git","hooks","pre-commit");return rn.existsSync(t)?{installed:rn.readFileSync(t,"utf8").includes("ripplo compile --check"),type:"pre-commit-hook"}:{installed:!1,type:"pre-commit-hook"}}async function Cm(e){let t=await li(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 Am(){let e=ee();if(e==null||e.length===0)return{email:void 0,status:"missing",type:"token"};let t=await di({serverUrl:Y(),token:e});return t.kind==="valid"?{email:t.email,status:"valid",type:"token"}:{email:void 0,status:t.kind,type:"token"}}function Im(){let e=Pm.executablePath();return{installed:rn.existsSync(e),type:"browser"}}function Tm(e){if(!e.ok)return{errorCount:1,errors:[{message:e.error,path:""}],found:!1,type:"preconditions-validation",valid:!1};let t=$m(e.result.preconditions,e.result.tests);return{errorCount:t.length,errors:t,found:!0,type:"preconditions-validation",valid:t.length===0}}function $m(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}`})})}),jm(e).forEach(o=>{r.push({message:o,path:"preconditions"})}),r}function jm(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 Nm(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 Om(e,t){if(!e.valid||!t.ok)return[];let r;try{let a=Te();r={appUrl:a.appUrl,engineUrl:a.engineUrl,webhookSecret:a.webhookSecret}}catch{return[]}let n=[],o=await tn(r.appUrl)==null;n.push({appUrl:r.appUrl,reachable:o,type:"dev-server"});let i=await si(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=_m(e.appUrl,e.engineUrl);if(i==null)return[o];let s=await tn(i)==null,a=[];if(a.push({configured:!0,count:r,endpointReachable:s,type:"preconditions"}),mi(e.engineUrl)&&a.push({reachable:s,type:"engine-endpoint",url:i}),!s)return a;let l=await ci({appUrl:e.appUrl,engineUrl:e.engineUrl});a.push({rejectsUnsigned:l==null,type:"webhook-verification"});let c=await Lm({engineUrl:i,webhookSecret:e.webhookSecret});return a.push({status:c,type:"adapter-enabled",url:i}),a}async function Lm({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 mi(e){return e.startsWith("http://")||e.startsWith("https://")}function _m(e,t){return mi(t)?t:`${e}${t}`}async function fi(){let e=process.cwd(),t=await pi(e),r=t.map(o=>ai(o));process.stdout.write(r.join(`
300
300
  `)+`
301
- `);let n=t.some(o=>ri(o));process.exit(n?1:0)}import{graphql as dt,readFragment as Em}from"gql.tada";import{createHash as si}from"crypto";import{mkdirSync as ym,readFileSync as en,writeFileSync as hm}from"fs";import Ft from"path";var wm=[".ts",".tsx",".js",".jsx"];function Re(e){let t=si("sha256");return t.update(K(["rev-parse","HEAD"],e)),t.update("\0"),t.update(K(["diff","HEAD"],e)),t.update("\0"),K(["ls-files","--others","--exclude-standard"],e).split(`
302
- `).filter(n=>n.length>0).filter(n=>wm.some(o=>n.endsWith(o))).toSorted((n,o)=>n.localeCompare(o)).forEach(n=>{t.update(n),t.update("\0"),t.update(bm(Ft.join(e,n))),t.update("\0")}),t.digest("hex")}function ai(e){let t=Ft.join(e,".ripplo","ripplo.lock");try{let r=en(t);return si("sha256").update(r).digest("hex")}catch{return null}}function Be(e,t){try{return en(li(e,t),"utf8").trim()}catch{return null}}function We(e,t,r){let n=li(e,t);ym(Ft.dirname(n),{recursive:!0}),hm(n,r)}function li(e,t){return Ft.join(e,".ripplo",".local",`${t}.hash`)}function bm(e){try{return en(e)}catch{return Buffer.alloc(0)}}import Sm from"crypto";import{graphql as km}from"gql.tada";import tn from"fs";import rn from"path";function Ht(e){try{let t=rn.join(vm(e),"HEAD"),r=tn.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 vm(e){let t=rn.join(e,".git");if(tn.statSync(t).isDirectory())return t;let n=tn.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 rn.resolve(e,i)}var Rm=km(`
301
+ `);let n=t.some(o=>ui(o));process.exit(n?1:0)}import{graphql as pt,readFragment as Jm}from"gql.tada";import{createHash as gi}from"crypto";import{mkdirSync as Um,readFileSync as nn,writeFileSync as Vm}from"fs";import Bt from"path";var Fm=[".ts",".tsx",".js",".jsx"];function Re(e){let t=gi("sha256");return t.update(M(["rev-parse","HEAD"],e)),t.update("\0"),t.update(M(["diff","HEAD"],e)),t.update("\0"),M(["ls-files","--others","--exclude-standard"],e).split(`
302
+ `).filter(n=>n.length>0).filter(n=>Fm.some(o=>n.endsWith(o))).toSorted((n,o)=>n.localeCompare(o)).forEach(n=>{t.update(n),t.update("\0"),t.update(Hm(Bt.join(e,n))),t.update("\0")}),t.digest("hex")}function yi(e){let t=Bt.join(e,".ripplo","ripplo.lock");try{let r=nn(t);return gi("sha256").update(r).digest("hex")}catch{return null}}function We(e,t){try{return nn(hi(e,t),"utf8").trim()}catch{return null}}function qe(e,t,r){let n=hi(e,t);Um(Bt.dirname(n),{recursive:!0}),Vm(n,r)}function hi(e,t){return Bt.join(e,".ripplo",".local",`${t}.hash`)}function Hm(e){try{return nn(e)}catch{return Buffer.alloc(0)}}import Bm from"crypto";import{graphql as Wm}from"gql.tada";import on from"fs";import sn from"path";function Wt(e){try{let t=sn.join(Mm(e),"HEAD"),r=on.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 Mm(e){let t=sn.join(e,".git");if(on.statSync(t).isDirectory())return t;let n=on.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 sn.resolve(e,i)}var qm=Wm(`
303
303
  mutation SyncDevSession(
304
304
  $projectId: String!
305
305
  $cwd: String!
@@ -318,12 +318,12 @@ ${t.join(`
318
318
  hooksPaused
319
319
  }
320
320
  }
321
- `);async function ct(e){let t=Pm(e.compiled);return Cm({config:e.config,cwd:e.cwd,payload:t})}async function Ee(e,t){let r=await P(e);if(!r.ok)throw new Error(`DSL compilation failed: ${r.error}`);let n=await ct({compiled:r.result,config:t,cwd:e});return{compiled:r.result,devSessionId:n.devSessionId}}function Pm(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 xm(e){return Sm.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function Cm({config:e,cwd:t,payload:r}){let n=xm(r),o=Ht(t),i=await f({config:e,document:Rm,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 ci from"figures";var Ae={cross:ci.cross,tick:ci.tick};var ui=dt(`
321
+ `);async function ut(e){let t=zm(e.compiled);return Km({config:e.config,cwd:e.cwd,payload:t})}async function Ce(e,t){let r=await P(e);if(!r.ok)throw new Error(`DSL compilation failed: ${r.error}`);let n=await ut({compiled:r.result,config:t,cwd:e});return{compiled:r.result,devSessionId:n.devSessionId}}function zm(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 Gm(e){return Bm.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function Km({config:e,cwd:t,payload:r}){let n=Gm(r),o=Wt(t),i=await f({config:e,document:qm,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 wi from"figures";var Ae={cross:wi.cross,tick:wi.tick};var vi=pt(`
322
322
  fragment WorkflowIdMCP on Workflow {
323
323
  id
324
324
  slug
325
325
  }
326
- `),Am=dt(`
326
+ `),Xm=pt(`
327
327
  query ProjectWorkflowIdsMCP($projectId: String!, $cwd: String!) {
328
328
  project(id: $projectId) {
329
329
  id
@@ -335,20 +335,20 @@ ${t.join(`
335
335
  }
336
336
  }
337
337
  }
338
- `,[ui]),Im=dt(`
338
+ `,[vi]),Ym=pt(`
339
339
  mutation SetProjectViewCLI($projectId: String!, $devSessionId: String!) {
340
340
  setProjectView(projectId: $projectId, devSessionId: $devSessionId) {
341
341
  id
342
342
  }
343
343
  }
344
- `),Tm=dt(`
344
+ `),Qm=pt(`
345
345
  mutation CreateRunMCP($workflowId: String!, $lockfileHash: String, $repoHash: String) {
346
346
  createRun(workflowId: $workflowId, lockfileHash: $lockfileHash, repoHash: $repoHash) {
347
347
  id
348
348
  status
349
349
  }
350
350
  }
351
- `),$m=dt(`
351
+ `),Zm=pt(`
352
352
  query RunStatusMCP($id: String!) {
353
353
  run(id: $id) {
354
354
  id
@@ -375,8 +375,8 @@ ${t.join(`
375
375
  }
376
376
  }
377
377
  }
378
- `);async function Mt({config:e,ids:t}){let r=await jm({config:e,ids:t}),n=await Promise.all(r.map(async s=>{try{let a=await _m({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}
379
- ${h("setup","check auth + config")}`};let{entry:a,runId:l}=s;try{let c=await Fm({config:e,runId:l}),p=Lm({config:e,id:a.id,runId:l}),m=`.ripplo/debug/${l}/`;return{id:a.id,runId:l,summary:`View run: ${p}
378
+ `);async function qt({config:e,ids:t}){let r=await ef({config:e,ids:t}),n=await Promise.all(r.map(async s=>{try{let a=await sf({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}
379
+ ${h("setup","check auth + config")}`};let{entry:a,runId:l}=s;try{let c=await cf({config:e,runId:l}),p=of({config:e,id:a.id,runId:l}),m=`.ripplo/debug/${l}/`;return{id:a.id,runId:l,summary:`View run: ${p}
380
380
  Debug artifacts: ${m}
381
381
  ${h("debug","read summary.txt, accessibility-tree, network.jsonl before guessing")}
382
382
 
@@ -386,10 +386,10 @@ ${s.summary}`).join(`
386
386
 
387
387
  ---
388
388
 
389
- `);return{results:o,summary:i}}async function jm({config:e,ids:t}){let r=await Ee(e.cwd,e),n=await f({config:e,document:Am,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 f({config:e,document:Im,variables:{devSessionId:o.id,projectId:e.projectId}});let i=(o.workflows??[]).map(a=>Em(ui,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(Nm({compiledSlugs:s,slug:a}));return{id:a,workflowId:l.id}})}function Nm({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=Om({compiledSlugs:e,limit:3,slug:t}),n=r.length>0?`
389
+ `);return{results:o,summary:i}}async function ef({config:e,ids:t}){let r=await Ce(e.cwd,e),n=await f({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 f({config:e,document:Ym,variables:{devSessionId:o.id,projectId:e.projectId}});let i=(o.workflows??[]).map(a=>Jm(vi,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(tf({compiledSlugs:s,slug:a}));return{id:a,workflowId:l.id}})}function tf({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=rf({compiledSlugs:e,limit:3,slug:t}),n=r.length>0?`
390
390
  Did you mean: ${r.join(", ")}?`:"";return`Test "${t}" is not registered in this dev session.${n}
391
- Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on demand \u2014 restarting the dev server will not help.)`}function Om({compiledSlugs:e,limit:t,slug:r}){let n=new Set(r.split("-"));return e.map(i=>({candidate:i,score:Dm(n,i)})).filter(i=>i.score>0).toSorted((i,s)=>s.score-i.score).slice(0,t).map(i=>i.candidate)}function Dm(e,t){return t.split("-").filter(r=>e.has(r)).length}function Lm({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 _m({config:e,workflowId:t}){let r=await f({config:e,document:Tm,variables:{lockfileHash:ai(e.cwd),repoHash:Um(e.cwd),workflowId:t}});if(r.createRun==null)throw new Error("Failed to create run");return r.createRun.id}function Um(e){try{return Re(e)}catch{return null}}var Vm=2e3,di=150;async function Fm({config:e,runId:t}){let r=0;for(;r<di;){await Bm(Vm),r+=1;let o=(await f({config:e,document:$m,variables:{id:t}})).run;if(o==null)throw new Error(`Run ${t} not found`);if(!(o.status==="pending"||o.status==="running"))return Hm({run:o,runId:t})}return`Run ${t} timed out after polling ${String(di)} times.`}function Hm({run:e,runId:t}){let r=[`Run ${t}: ${e.status.toUpperCase()}`],n=Mm(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(`
392
- `)}function Mm(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 Bm(e){return new Promise(t=>{setTimeout(t,e)})}import{graphql as Wm}from"gql.tada";var qm=Wm(`
391
+ Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on demand \u2014 restarting the dev server will not help.)`}function rf({compiledSlugs:e,limit:t,slug:r}){let n=new Set(r.split("-"));return e.map(i=>({candidate:i,score:nf(n,i)})).filter(i=>i.score>0).toSorted((i,s)=>s.score-i.score).slice(0,t).map(i=>i.candidate)}function nf(e,t){return t.split("-").filter(r=>e.has(r)).length}function of({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 sf({config:e,workflowId:t}){let r=await f({config:e,document:Qm,variables:{lockfileHash:yi(e.cwd),repoHash:af(e.cwd),workflowId:t}});if(r.createRun==null)throw new Error("Failed to create run");return r.createRun.id}function af(e){try{return Re(e)}catch{return null}}var lf=2e3,bi=150;async function cf({config:e,runId:t}){let r=0;for(;r<bi;){await pf(lf),r+=1;let o=(await f({config:e,document:Zm,variables:{id:t}})).run;if(o==null)throw new Error(`Run ${t} not found`);if(!(o.status==="pending"||o.status==="running"))return df({run:o,runId:t})}return`Run ${t} timed out after polling ${String(bi)} times.`}function df({run:e,runId:t}){let r=[`Run ${t}: ${e.status.toUpperCase()}`],n=uf(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(`
392
+ `)}function uf(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 pf(e){return new Promise(t=>{setTimeout(t,e)})}import{graphql as mf}from"gql.tada";var ff=mf(`
393
393
  query DevSessionCheckPreflight($projectId: String!, $cwd: String!) {
394
394
  project(id: $projectId) {
395
395
  id
@@ -400,36 +400,36 @@ Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on
400
400
  }
401
401
  `);function ue(){try{return _(process.cwd())}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}
402
402
  `),process.stderr.write(`${h("setup")}
403
- `),process.exit(1)}}async function fe(e){(await f({config:e,document:qm,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(`${h("setup")}
404
- `),process.exit(1))}async function pi({id:e,runs:t}){let r=ue();await fe(r),process.stdout.write(`flake-detect "${e}" x${String(t)}...
405
- `);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(`
403
+ `),process.exit(1)}}async function fe(e){(await f({config:e,document:ff,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(`${h("setup")}
404
+ `),process.exit(1))}async function Si({id:e,runs:t}){let r=ue();await fe(r),process.stdout.write(`flake-detect "${e}" x${String(t)}...
405
+ `);let n=await Promise.allSettled(Array.from({length:t},()=>qt({config:r,ids:[e]}))),o=0,i=0,s=new Map;n.forEach(l=>{if(l.status==="rejected"){i++;let 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(`
406
406
  `).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)
407
407
  `),s.size>0&&s.forEach((l,c)=>{process.stdout.write(` ${String(l)}x: ${c}
408
408
  `)}),i>0&&process.stderr.write(`${h("flake-detect","parallel safety + race conditions")}
409
- `),process.exit(i>0?1:0)}import Bt from"fs";import{graphql as Gm}from"gql.tada";import zm from"fs";function Pe(e){return nt(e,"hooks-paused")}function T(e){return zm.existsSync(Pe(e))?!1:Me(e)}var Km=Gm(`
409
+ `),process.exit(i>0?1:0)}import zt from"fs";import{graphql as yf}from"gql.tada";import gf from"fs";function Pe(e){return ot(e,"hooks-paused")}function $(e){return gf.existsSync(Pe(e))||Mt(e)?!1:Be(e)}var hf=yf(`
410
410
  mutation CliSetHooksPaused($projectId: String!, $paused: Boolean!) {
411
411
  setHooksPaused(projectId: $projectId, paused: $paused) {
412
412
  id
413
413
  }
414
414
  }
415
- `);async function mi(){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();rt(e);let t=Pe(e);if(Bt.existsSync(t)){process.stdout.write("Hooks already paused. Run `ripplo hooks resume` to re-enable.\n");return}Bt.writeFileSync(t,""),await gi(e,!0),process.stdout.write("Hooks paused. Pre-edit gates and stop enforcement are off until you run `ripplo hooks resume`.\n")}async function fi(){let e=process.cwd(),t=Pe(e);if(!Bt.existsSync(t)){process.stdout.write(`Hooks already active.
416
- `);return}Bt.unlinkSync(t),await gi(e,!1),process.stdout.write(`Hooks resumed.
417
- `)}async function gi(e,t){let r;try{r=_(e)}catch{return}await f({config:r,document:Km,variables:{paused:t,projectId:r.projectId}}).catch(()=>null)}import qe from"fs";import ze from"path";import{input as wi,select as bi}from"@inquirer/prompts";import{graphql as gf}from"gql.tada";import{exec as Jm}from"child_process";import D from"fs";import U from"path";import{promisify as Xm}from"util";var Ym=["@ripplo/testing"],yi=".ripplo/ripplo.lock linguist-generated=true",Qm=[".ripplo/debug/",".ripplo/.local/"],Zm=Xm(Jm);async function hi({cwd:e,onStep:t}){t("Scaffolding project files..."),lf({cwd:e}),t("Updating .gitignore..."),cf(e),t("Marking ripplo.lock as generated..."),rf(e),t("Installing dependencies...");let r=await ef(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 tf(e);o!=null&&n.push({manualCommand:void 0,message:o})}return t("Setting up browser..."),await wr(),n}async function ef(e){let t=nf({cwd:e,pm:af(e)});y.info("Installing dependencies: %s",t);try{return await Zm(t,{cwd:e}),{ok:!0}}catch(r){let n=r instanceof Error?r.message.split(`
418
- `)[0]??r.message:String(r);return y.warn("Install failed (%s): %s",t,n),{cmd:t,ok:!1,reason:n}}}async function tf(e){try{let t=await P(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 rf(e){let t=U.join(e,".gitattributes"),r=D.existsSync(t)?D.readFileSync(t,"utf8"):"";if(r.includes(yi))return;let n=r.length===0||r.endsWith(`
415
+ `);async function ki(){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();nt(e);let t=Pe(e);if(zt.existsSync(t)){process.stdout.write("Hooks already paused. Run `ripplo hooks resume` to re-enable.\n");return}zt.writeFileSync(t,""),await Pi(e,!0),process.stdout.write("Hooks paused. Pre-edit gates and stop enforcement are off until you run `ripplo hooks resume`.\n")}async function Ri(){let e=process.cwd(),t=Pe(e);if(!zt.existsSync(t)){process.stdout.write(`Hooks already active.
416
+ `);return}zt.unlinkSync(t),await Pi(e,!1),process.stdout.write(`Hooks resumed.
417
+ `)}async function Pi(e,t){let r;try{r=_(e)}catch{return}await f({config:r,document:hf,variables:{paused:t,projectId:r.projectId}}).catch(()=>null)}import ze from"fs";import Ge from"path";import{input as Ci,select as Ai}from"@inquirer/prompts";import{graphql as _f}from"gql.tada";import{exec as wf}from"child_process";import L from"fs";import U from"path";import{promisify as bf}from"util";var vf=["@ripplo/testing"],xi=".ripplo/ripplo.lock linguist-generated=true",Sf=[".ripplo/debug/",".ripplo/.local/"],kf=bf(wf);async function Ei({cwd:e,onStep:t}){t("Scaffolding project files..."),Tf({cwd:e}),t("Updating .gitignore..."),$f(e),t("Marking ripplo.lock as generated..."),xf(e),t("Installing dependencies...");let r=await Rf(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 Pf(e);o!=null&&n.push({manualCommand:void 0,message:o})}return t("Setting up browser..."),await Sr(),n}async function Rf(e){let t=Ef({cwd:e,pm:If(e)});y.info("Installing dependencies: %s",t);try{return await kf(t,{cwd:e}),{ok:!0}}catch(r){let n=r instanceof Error?r.message.split(`
418
+ `)[0]??r.message:String(r);return y.warn("Install failed (%s): %s",t,n),{cmd:t,ok:!1,reason:n}}}async function Pf(e){try{let t=await P(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 xf(e){let t=U.join(e,".gitattributes"),r=L.existsSync(t)?L.readFileSync(t,"utf8"):"";if(r.includes(xi))return;let n=r.length===0||r.endsWith(`
419
419
  `)?"":`
420
- `;D.writeFileSync(t,`${r}${n}${yi}
421
- `)}function nf({cwd:e,pm:t}){let r=Ym.join(" ");return t==="pnpm"?of(e)?`pnpm add -wD ${r}`:`pnpm add -D ${r}`:t==="yarn"?sf(e)?`yarn add -WD ${r}`:`yarn add -D ${r}`:t==="bun"?`bun add -d ${r}`:`npm install -D ${r}`}function of(e){return D.existsSync(U.join(e,"pnpm-workspace.yaml"))||D.existsSync(U.join(e,"pnpm-workspace.yml"))}function sf(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 af(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 lf({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}),ut(U.join(t,"index.ts"),df),ut(U.join(n,"index.ts"),uf),ut(U.join(o,"index.ts"),pf),ut(U.join(r,"index.ts"),mf),ut(U.join(t,"tsconfig.json"),ff)}function ut(e,t){D.existsSync(e)||D.writeFileSync(e,t)}function cf(e){let t=U.join(e,".gitignore");if(!D.existsSync(t))return;let r=D.readFileSync(t,"utf8"),n=Qm.filter(i=>!r.includes(i));if(n.length===0)return;let o=r.endsWith(`
420
+ `;L.writeFileSync(t,`${r}${n}${xi}
421
+ `)}function Ef({cwd:e,pm:t}){let r=vf.join(" ");return t==="pnpm"?Cf(e)?`pnpm add -wD ${r}`:`pnpm add -D ${r}`:t==="yarn"?Af(e)?`yarn add -WD ${r}`:`yarn add -D ${r}`:t==="bun"?`bun add -d ${r}`:`npm install -D ${r}`}function Cf(e){return L.existsSync(U.join(e,"pnpm-workspace.yaml"))||L.existsSync(U.join(e,"pnpm-workspace.yml"))}function Af(e){let t=U.join(e,"package.json");if(!L.existsSync(t))return!1;try{let r=JSON.parse(L.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 If(e){return L.existsSync(U.join(e,"pnpm-lock.yaml"))?"pnpm":L.existsSync(U.join(e,"yarn.lock"))?"yarn":L.existsSync(U.join(e,"bun.lockb"))||L.existsSync(U.join(e,"bun.lock"))?"bun":"npm"}function Tf({cwd:e}){let t=U.join(e,".ripplo"),r=U.join(t,"tests"),n=U.join(t,"preconditions"),o=U.join(t,"observers");L.mkdirSync(r,{recursive:!0}),L.mkdirSync(n,{recursive:!0}),L.mkdirSync(o,{recursive:!0}),mt(U.join(t,"index.ts"),jf),mt(U.join(n,"index.ts"),Nf),mt(U.join(o,"index.ts"),Of),mt(U.join(r,"index.ts"),Df),mt(U.join(t,"tsconfig.json"),Lf)}function mt(e,t){L.existsSync(e)||L.writeFileSync(e,t)}function $f(e){let t=U.join(e,".gitignore");if(!L.existsSync(t))return;let r=L.readFileSync(t,"utf8"),n=Sf.filter(i=>!r.includes(i));if(n.length===0)return;let o=r.endsWith(`
422
422
  `)?"":`
423
- `;D.writeFileSync(t,r+o+n.join(`
423
+ `;L.writeFileSync(t,r+o+n.join(`
424
424
  `)+`
425
- `)}var df=`import { createRipplo } from "@ripplo/testing";
425
+ `)}var jf=`import { createRipplo } from "@ripplo/testing";
426
426
  import { preconditions } from "./preconditions/index";
427
427
  import { observers } from "./observers/index";
428
428
  import { tests } from "./tests/index";
429
429
 
430
430
  export { preconditions, observers, tests };
431
431
  export default createRipplo({ preconditions, observers, tests });
432
- `,uf=`// Declare preconditions with \`precondition(name)\` from @ripplo/testing and collect them
432
+ `,Nf=`// Declare preconditions with \`precondition(name)\` from @ripplo/testing and collect them
433
433
  // in the \`preconditions\` registry below. Every handle in this registry must be implemented
434
434
  // in your app server's \`createEngine(ripplo, { preconditions: {...}, observers: {...} })\` call.
435
435
  //
@@ -443,7 +443,7 @@ export default createRipplo({ preconditions, observers, tests });
443
443
  // export const preconditions = { authLoggedIn };
444
444
 
445
445
  export const preconditions = {};
446
- `,pf=`// Declare observers with \`observer(name)\` from @ripplo/testing and collect them in
446
+ `,Of=`// Declare observers with \`observer(name)\` from @ripplo/testing and collect them in
447
447
  // the \`observers\` registry below. Use them in tests via \`assert.backend(handle, params)\`.
448
448
  //
449
449
  // Example:
@@ -456,7 +456,7 @@ export const preconditions = {};
456
456
  // export const observers = { orgNameIs };
457
457
 
458
458
  export const observers = {};
459
- `,mf=`// Each test file under ./tests exports a TestDefinition. Import them here and add them
459
+ `,Df=`// Each test file under ./tests exports a TestDefinition. Import them here and add them
460
460
  // to the \`tests\` array \u2014 that's what \`createRipplo({ ..., tests })\` receives.
461
461
  //
462
462
  // Example:
@@ -464,7 +464,7 @@ export const observers = {};
464
464
  // export const tests = [myTest] as const;
465
465
 
466
466
  export const tests = [] as const;
467
- `,ff=`{
467
+ `,Lf=`{
468
468
  "compilerOptions": {
469
469
  "strict": true,
470
470
  "noUncheckedIndexedAccess": true,
@@ -480,62 +480,62 @@ export const tests = [] as const;
480
480
  "include": ["*.ts", "coverage.d.ts", "observers/**/*.ts", "preconditions/**/*.ts", "tests/**/*.ts"],
481
481
  "exclude": ["node_modules"]
482
482
  }
483
- `;var yf=gf(`
483
+ `;var Uf=_f(`
484
484
  query InitProjects {
485
485
  projects {
486
486
  id
487
487
  name
488
488
  }
489
489
  }
490
- `),nn=["../.env.local","../.env"];async function vi(e=bf()){let t=process.cwd(),r=ee();r==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let n=Y();hf(t)&&(process.stdout.write(`\`.ripplo/index.ts\` already exists at ${t}. Delete it first if you want to re-init.
491
- `),process.exit(1));let o=await wf({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 Sf(o,e.projectId),s=await kf(t,e.envFile),a=await Rf(e.appUrl),l=vf(a,e.engineUrl),c=ze.resolve(ze.join(t,".ripplo"),s);pn({cwd:t,envFiles:[s],projectId:i}),Cf({appUrl:a,engineUrl:l,filePath:c});let p=await hi({cwd:t,onStep:m=>{process.stdout.write(` ${m}
490
+ `),an=["../.env.local","../.env"];async function Ii(e=Hf()){let t=process.cwd(),r=ee();r==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let n=Y();Vf(t)&&(process.stdout.write(`\`.ripplo/index.ts\` already exists at ${t}. Delete it first if you want to re-init.
491
+ `),process.exit(1));let o=await Ff({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 Bf(o,e.projectId),s=await Wf(t,e.envFile),a=await qf(e.appUrl),l=Mf(a,e.engineUrl),c=Ge.resolve(Ge.join(t,".ripplo"),s);gn({cwd:t,envFiles:[s],projectId:i}),Kf({appUrl:a,engineUrl:l,filePath:c});let p=await Ei({cwd:t,onStep:m=>{process.stdout.write(` ${m}
492
492
  `)}});if(p.length>0){process.stdout.write(`Done with warnings:
493
493
  `),p.forEach(m=>{process.stdout.write(` - ${m.message}
494
494
  `),m.manualCommand!=null&&process.stdout.write(` run: ${m.manualCommand}
495
- `)});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 hf(e){return qe.existsSync(ze.join(e,".ripplo","index.ts"))}async function wf({serverUrl:e,token:t}){return((await f({config:ve({serverUrl:e,token:t}),document:yf,variables:void 0})).projects??[]).map(n=>({id:n.id,name:n.name}))}function bf(){return{appUrl:void 0,engineUrl:void 0,envFile:void 0,projectId:void 0}}function vf(e,t){if(t!=null){try{new URL(t)}catch{process.stdout.write(`--engine-url is not a valid URL: ${t}
496
- `),process.exit(1)}return t}return`${e.replace(/\/$/,"")}/ripplo`}async function Sf(e,t){if(t!=null){let r=e.find(n=>n.id===t);return r==null&&(process.stdout.write(`Unknown project id: ${t}
495
+ `)});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 Vf(e){return ze.existsSync(Ge.join(e,".ripplo","index.ts"))}async function Ff({serverUrl:e,token:t}){return((await f({config:ve({serverUrl:e,token:t}),document:Uf,variables:void 0})).projects??[]).map(n=>({id:n.id,name:n.name}))}function Hf(){return{appUrl:void 0,engineUrl:void 0,envFile:void 0,projectId:void 0}}function Mf(e,t){if(t!=null){try{new URL(t)}catch{process.stdout.write(`--engine-url is not a valid URL: ${t}
496
+ `),process.exit(1)}return t}return`${e.replace(/\/$/,"")}/ripplo`}async function Bf(e,t){if(t!=null){let r=e.find(n=>n.id===t);return r==null&&(process.stdout.write(`Unknown project id: ${t}
497
497
  `),process.exit(1)),process.stdout.write(`Using project: ${r.name} (${r.id})
498
498
  `),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})
499
- `),r.id}return bi({choices:e.map(r=>({name:r.name,value:r.id})),message:"Select a project"})}async function kf(e,t){return t!=null?(t.trim().length===0&&(process.stdout.write(`--env must not be empty
500
- `),process.exit(1)),t):Pf(e)}async function Rf(e){if(e!=null){try{new URL(e)}catch{process.stdout.write(`--app-url is not a valid URL: ${e}
501
- `),process.exit(1)}return e}return xf()}async function Pf(e){let t=ze.join(e,".ripplo"),r=nn.find(o=>qe.existsSync(ze.resolve(t,o))),n=await bi({choices:[...nn.map(o=>({name:r===o?`${o} (detected)`:o,value:o})),{name:"custom path",value:"__custom__"}],default:r??nn[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:wi({message:"Path to env file (relative to .ripplo/, e.g. ../apps/server/.env)",validate:o=>o.trim().length>0?!0:"required"})}async function xf(){return wi({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 Cf({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=${jr()}`),/^ENABLE_RIPPLO_TESTING=/m.test(n)||o.push("ENABLE_RIPPLO_TESTING=true"),o.length===0)return;let i=n.length===0||n.endsWith(`
499
+ `),r.id}return Ai({choices:e.map(r=>({name:r.name,value:r.id})),message:"Select a project"})}async function Wf(e,t){return t!=null?(t.trim().length===0&&(process.stdout.write(`--env must not be empty
500
+ `),process.exit(1)),t):zf(e)}async function qf(e){if(e!=null){try{new URL(e)}catch{process.stdout.write(`--app-url is not a valid URL: ${e}
501
+ `),process.exit(1)}return e}return Gf()}async function zf(e){let t=Ge.join(e,".ripplo"),r=an.find(o=>ze.existsSync(Ge.resolve(t,o))),n=await Ai({choices:[...an.map(o=>({name:r===o?`${o} (detected)`:o,value:o})),{name:"custom path",value:"__custom__"}],default:r??an[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:Ci({message:"Path to env file (relative to .ripplo/, e.g. ../apps/server/.env)",validate:o=>o.trim().length>0?!0:"required"})}async function Gf(){return Ci({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 Kf({appUrl:e,engineUrl:t,filePath:r}){ze.mkdirSync(Ge.dirname(r),{recursive:!0});let n=ze.existsSync(r)?ze.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=${Dr()}`),/^ENABLE_RIPPLO_TESTING=/m.test(n)||o.push("ENABLE_RIPPLO_TESTING=true"),o.length===0)return;let i=n.length===0||n.endsWith(`
502
502
  `)?"":`
503
- `;qe.writeFileSync(r,`${n}${i}${o.join(`
503
+ `;ze.writeFileSync(r,`${n}${i}${o.join(`
504
504
  `)}
505
- `)}import on from"fs";import Si from"path";import*as ki from"remeda";import Ef from"path";import{graphql as Af}from"gql.tada";var If=Af(`
505
+ `)}import ln from"fs";import Ti from"path";import*as $i from"remeda";import Jf from"path";import{graphql as Xf}from"gql.tada";var Yf=Xf(`
506
506
  mutation AutoScopeAddDirty($projectId: String!, $cwd: String!, $workflowSlugs: [String!]!) {
507
507
  addDirtyTestsToScope(projectId: $projectId, cwd: $cwd, workflowSlugs: $workflowSlugs) {
508
508
  id
509
509
  }
510
510
  }
511
- `);async function Ge({compileResult:e,cwd:t}){if(!T(t))return{addedSlugs:[]};let r=Tf(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 ct({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 f({config:i,document:If,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 Tf(e){let t;try{t=K(["status","--porcelain","--",".ripplo/tests"],e)}catch{return[]}return t.split(`
512
- `).map(r=>r.slice(3).trim()).filter(r=>/^\.ripplo\/tests\/[^/]+\.ts$/.test(r)).map(r=>Ef.basename(r,".ts")).filter(r=>r!=="index")}async function Ri(e){let{ids:t,requireImplemented:r}=e,n=process.cwd(),o=await P(n);o.ok||(process.stderr.write(`Compilation failed: ${o.error}
511
+ `);async function Ke({compileResult:e,cwd:t}){if(!$(t))return{addedSlugs:[]};let r=Qf(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 ut({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 f({config:i,document:Yf,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 Qf(e){let t;try{t=M(["status","--porcelain","--",".ripplo/tests"],e)}catch{return[]}return t.split(`
512
+ `).map(r=>r.slice(3).trim()).filter(r=>/^\.ripplo\/tests\/[^/]+\.ts$/.test(r)).map(r=>Jf.basename(r,".ts")).filter(r=>r!=="index")}async function ji(e){let{ids:t,requireImplemented:r}=e,n=process.cwd(),o=await P(n);o.ok||(process.stderr.write(`Compilation failed: ${o.error}
513
513
  `),process.stderr.write(`${h("create","DSL authoring + lint rules")}
514
- `),process.exit(1)),await ce({cwd:n,result:o.result});let i=Ue(o.result),s=t.length===0?i.diagnostics:i.diagnostics.filter(g=>t.includes(g.test)),a=ki.groupBy(s,g=>g.test);Object.entries(a).forEach(([g,B])=>{process.stderr.write(`
514
+ `),process.exit(1)),await ce({cwd:n,result:o.result});let i=Ve(o.result),s=t.length===0?i.diagnostics:i.diagnostics.filter(g=>t.includes(g.test)),a=$i.groupBy(s,g=>g.test);Object.entries(a).forEach(([g,W])=>{process.stderr.write(`
515
515
  ${g}
516
- `),B.forEach($=>{let V=$.step==null?"":` at "${$.step}"`;process.stderr.write(` [${$.rule}]${V}
517
- `),process.stderr.write(` ${$.message}
516
+ `),W.forEach(j=>{let V=j.step==null?"":` at "${j.step}"`;process.stderr.write(` [${j.rule}]${V}
517
+ `),process.stderr.write(` ${j.message}
518
518
  `)})});let l=new Set(o.builder.getUnimplemented().tests),c=r.filter(g=>l.has(g));c.length>0&&(process.stderr.write(`
519
519
  not-implemented
520
520
  `),c.forEach(g=>{process.stderr.write(` ${g} is still marked .notImplemented()
521
- `)}));let p=Of(n);p.length>0&&(process.stderr.write(`
521
+ `)}));let p=rg(n);p.length>0&&(process.stderr.write(`
522
522
  preconditions
523
523
  `),p.forEach(g=>{process.stderr.write(` [hardcoded-identifier] ${g.file}
524
524
  `),process.stderr.write(` ${g.message}
525
525
  `)}));let m=s.length+c.length+p.length;m>0&&(process.stderr.write(`
526
526
  ${String(m)} error(s)
527
- `),$f({diagnostics:s,hardcodeWarnings:p,stillStubbed:c}),process.exit(1));let k=o.result.tests.length,j=t.length===0?"all tests":`${String(t.length)} test(s)`;process.stdout.write(`\u2713 ripplo lint: ${j} passed (${String(k)} compiled, lockfile written)
528
- `);let{addedSlugs:N}=await Ge({compileResult:o,cwd:n});N.length>0&&process.stdout.write(`\u2713 Auto-scoped ${N.join(", ")} (dirty tests).
529
- `)}function $f({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(`${h(o)}
530
- `))}var jf=/['"`][\w.+-]+@[\w.-]+\.[a-z]{2,}['"`]/i,Nf=/['"`][0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}['"`]/i;function Of(e){let t=Si.join(e,".ripplo","preconditions");return on.existsSync(t)?on.readdirSync(t).filter(n=>n.endsWith(".ts")).flatMap(n=>Df(Si.join(t,n))):[]}function Df(e){let t=on.readFileSync(e,"utf8"),r=t.includes("ctx.uniqueEmail")||t.includes("ctx.uniqueId"),n=[],o=jf.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=Nf.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 Lf}from"gql.tada";var _f=Lf(`
527
+ `),Zf({diagnostics:s,hardcodeWarnings:p,stillStubbed:c}),process.exit(1));let k=o.result.tests.length,N=t.length===0?"all tests":`${String(t.length)} test(s)`;process.stdout.write(`\u2713 ripplo lint: ${N} passed (${String(k)} compiled, lockfile written)
528
+ `);let{addedSlugs:O}=await Ke({compileResult:o,cwd:n});O.length>0&&process.stdout.write(`\u2713 Auto-scoped ${O.join(", ")} (dirty tests).
529
+ `)}function Zf({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(`${h(o)}
530
+ `))}var eg=/['"`][\w.+-]+@[\w.-]+\.[a-z]{2,}['"`]/i,tg=/['"`][0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}['"`]/i;function rg(e){let t=Ti.join(e,".ripplo","preconditions");return ln.existsSync(t)?ln.readdirSync(t).filter(n=>n.endsWith(".ts")).flatMap(n=>ng(Ti.join(t,n))):[]}function ng(e){let t=ln.readFileSync(e,"utf8"),r=t.includes("ctx.uniqueEmail")||t.includes("ctx.uniqueId"),n=[],o=eg.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=tg.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 og}from"gql.tada";var ig=og(`
531
531
  query ProjectsList {
532
532
  projects {
533
533
  id
534
534
  name
535
535
  }
536
536
  }
537
- `);async function Pi(){let e=ee();e==null&&(process.stderr.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let t=Y(),n=((await f({config:ve({serverUrl:t,token:e}),document:_f,variables:void 0})).projects??[]).map(o=>({id:o.id,name:o.name}));process.stdout.write(`${JSON.stringify({projects:n},null,2)}
538
- `)}import{graphql as Uf}from"gql.tada";var Wt=Uf(`
537
+ `);async function Ni(){let e=ee();e==null&&(process.stderr.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let t=Y(),n=((await f({config:ve({serverUrl:t,token:e}),document:ig,variables:void 0})).projects??[]).map(o=>({id:o.id,name:o.name}));process.stdout.write(`${JSON.stringify({projects:n},null,2)}
538
+ `)}import{graphql as sg}from"gql.tada";var Gt=sg(`
539
539
  query ScopeStatus($projectId: String!, $cwd: String!) {
540
540
  project(id: $projectId) {
541
541
  id
@@ -555,17 +555,17 @@ ${String(m)} error(s)
555
555
  }
556
556
  }
557
557
  }
558
- `);async function xi({all:e,ids:t}){e&&t.length>0&&(process.stderr.write(`Pass either --all or test ids, not both.
559
- `),process.exit(1));let r=ue();await fe(r);let n=await Vf({all:e,cwd:r.cwd,ids:t});n==null&&process.exit(1);let{results:o,summary:i}=await Mt({config:r,ids:n});process.stdout.write(`${i}
558
+ `);async function Oi({all:e,ids:t}){e&&t.length>0&&(process.stderr.write(`Pass either --all or test ids, not both.
559
+ `),process.exit(1));let r=ue();await fe(r);let n=await ag({all:e,cwd:r.cwd,ids:t});n==null&&process.exit(1);let{results:o,summary:i}=await qt({config:r,ids:n});process.stdout.write(`${i}
560
560
  `);let s=o.some(a=>a.summary.includes("FAILED")||a.summary.includes("ERROR"));s&&(process.stderr.write(`Artifacts in .ripplo/debug/<runId>/ \u2014 read before re-running.
561
561
  `),process.stderr.write(`${h("debug")}
562
- `)),process.exit(s?1:0)}async function Vf({all:e,cwd:t,ids:r}){return r.length>0?r:e?[]:Ff(t)}async function Ff(e){let t=ue(),r=await P(e);if(r.ok){let{addedSlugs:a}=await Ge({compileResult:r,cwd:e});a.length>0&&process.stdout.write(`Auto-scoped ${a.join(", ")} (dirty tests).
563
- `)}let o=(await f({config:t,document:Wt,variables:{cwd:t.cwd,projectId:t.projectId}})).project?.devSession?.scopeItems??[],i=o.flatMap(a=>a.workflow!=null&&a.workflow.spec!=null?[a.workflow.slug]:[]),s=o.flatMap(a=>a.workflow==null?[`[intent] ${a.label??"(no label)"}`]:a.workflow.spec==null?[`[stub] ${a.workflow.slug}`]:[]);return s.length>0&&process.stdout.write(`Skipped non-runnable scope items: ${s.join(", ")}
562
+ `)),process.exit(s?1:0)}async function ag({all:e,cwd:t,ids:r}){return r.length>0?r:e?[]:lg(t)}async function lg(e){let t=ue(),r=await P(e);if(r.ok){let{addedSlugs:a}=await Ke({compileResult:r,cwd:e});a.length>0&&process.stdout.write(`Auto-scoped ${a.join(", ")} (dirty tests).
563
+ `)}let o=(await f({config:t,document:Gt,variables:{cwd:t.cwd,projectId:t.projectId}})).project?.devSession?.scopeItems??[],i=o.flatMap(a=>a.workflow!=null&&a.workflow.spec!=null?[a.workflow.slug]:[]),s=o.flatMap(a=>a.workflow==null?[`[intent] ${a.label??"(no label)"}`]:a.workflow.spec==null?[`[stub] ${a.workflow.slug}`]:[]);return s.length>0&&process.stdout.write(`Skipped non-runnable scope items: ${s.join(", ")}
564
564
  `),i.length===0?(process.stderr.write("No runnable tests in scope. Add tests with `ripplo scope add <id>`, or run the full suite with `ripplo run --all`.\n"),process.stderr.write(`${h("scope")}
565
- `),null):i}async function Ci(){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}
565
+ `),null):i}async function Di(){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}
566
566
  `)}catch(r){let n=r instanceof Error?r.message:String(r);process.stderr.write(`ripplo sync failed: ${n}
567
567
  `),process.stderr.write(`${h("setup","verify auth + server reachability")}
568
- `),process.exit(1)}}import qt from"fs";import{createClient as Gf}from"graphql-sse";import{graphql as zt}from"gql.tada";import{print as Ai}from"graphql";import{availableParallelism as Hf}from"os";import Mf from"p-limit";var Bf=Math.max(1,Math.min(10,Math.floor(Hf()/2))),Wf=Mf(Bf),sn=new Set;async function Ei(e){if(!sn.has(e.runId)){sn.add(e.runId);try{await Wf(()=>qf(e))}finally{sn.delete(e.runId)}}}async function qf({config:e,cwd:t,runId:r,workflowSlug:n}){let o=await et({headed:!1});try{await br({maxRuns:100});let i=t!=null&&n!=null?await zf({cwd:t,workflowSlug:n}):void 0;await Ur({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 zf({cwd:e,workflowSlug:t}){let r=await P(e);if(!r.ok)return;let n=r.result.tests.find(o=>o.slug===t);if(n!=null)return n.preconditions}var Kf=15e3,Jf=zt(`
568
+ `),process.exit(1)}}import Kt from"fs";import{createClient as gg}from"graphql-sse";import{graphql as Jt}from"gql.tada";import{print as _i}from"graphql";import{availableParallelism as cg}from"os";import dg from"p-limit";var ug=Math.max(1,Math.min(10,Math.floor(cg()/2))),pg=dg(ug),cn=new Set;async function Li(e){if(!cn.has(e.runId)){cn.add(e.runId);try{await pg(()=>mg(e))}finally{cn.delete(e.runId)}}}async function mg({config:e,cwd:t,runId:r,workflowSlug:n}){let o=await tt({headed:!1});try{await kr({maxRuns:100});let i=t!=null&&n!=null?await fg({cwd:t,workflowSlug:n}):void 0;await Hr({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 fg({cwd:e,workflowSlug:t}){let r=await P(e);if(!r.ok)return;let n=r.result.tests.find(o=>o.slug===t);if(n!=null)return n.preconditions}var yg=15e3,hg=Jt(`
569
569
  subscription RunRequestedWatch($devSessionId: String!) {
570
570
  runRequested(devSessionId: $devSessionId) {
571
571
  runId
@@ -573,30 +573,30 @@ ${String(m)} error(s)
573
573
  workflowSlug
574
574
  }
575
575
  }
576
- `),Xf=zt(`
576
+ `),wg=Jt(`
577
577
  subscription HooksPausedWatch($projectId: String!) {
578
578
  hooksPausedRequested(projectId: $projectId) {
579
579
  paused
580
580
  projectId
581
581
  }
582
582
  }
583
- `),Yf=zt(`
583
+ `),bg=Jt(`
584
584
  mutation HeartbeatDevSessionWatch($id: String!) {
585
585
  heartbeatDevSession(id: $id) {
586
586
  id
587
587
  }
588
588
  }
589
- `),Qf=zt(`
589
+ `),vg=Jt(`
590
590
  mutation EndDevSessionWatch($projectId: String!, $cwd: String!) {
591
591
  endDevSession(projectId: $projectId, cwd: $cwd) {
592
592
  id
593
593
  }
594
594
  }
595
- `);async function Ii(){cg();let e=rg(process.cwd()),t=e.cwd,r=await P(t);r.ok||(process.stderr.write(`ripplo: DSL compilation failed: ${r.error}
596
- `),process.exit(1));let n=await ig(()=>ct({compiled:r.result,config:e,cwd:t}));Ti({cwd:t,paused:n.hooksPaused});let o=Ht(t);o!=null&&y.info("watching branch %s in %s",o,t);let i=Jo(t),s=Gf({headers:{Authorization:`Bearer ${e.token}`},retryAttempts:1/0,url:`${e.ripploServerUrl}/graphql`}),a=Zf({config:e,cwd:t,devSessionId:n.devSessionId,sseClient:s}),l=eg({cwd:t,projectId:e.projectId,sseClient:s}),c=tg({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)
597
- `);let p=async()=>{c(),a(),l(),await Promise.race([f({config:e,document:Qf,variables:{cwd:e.cwd,projectId:e.projectId}}).catch(()=>{}),new Promise(k=>setTimeout(k,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 Zf({config:e,cwd:t,devSessionId:r,sseClient:n}){return n.subscribe({query:Ai(Jf),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})
598
- `),Ei({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 Ti({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 eg({cwd:e,projectId:t,sseClient:r}){return r.subscribe({query:Ai(Xf),variables:{projectId:t}},{complete:()=>{},error:n=>{y.error(n,"hooksPaused subscription error")},next:n=>{let o=n.data?.hooksPausedRequested?.paused;o!=null&&Ti({cwd:e,paused:o})}})}function tg({config:e,devSessionId:t}){let r=setInterval(()=>{f({config:e,document:Yf,variables:{id:t}}).catch(n=>{y.warn("heartbeat failed: %s",n instanceof Error?n.message:String(n))})},Kf);return()=>{clearInterval(r)}}function rg(e){try{return _(e)}catch(t){let r=t instanceof Error?t.message:String(t);process.stderr.write(`${r}
599
- `),process.exit(1)}}var ng=1e3,og=6e4;async function ig(e){let t=Date.now()+og,r;for(;Date.now()<t;){let n=await sg(e);if(n.ok)return n.value;if(!ag(n.message))throw n.error;r=n.error,await lg(ng)}throw r instanceof Error?r:new Error("server never became ready")}async function sg(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 ag(e){return e.includes("status 502")||e.includes("ECONNREFUSED")||e.includes("Failed to connect")||e.includes("fetch failed")}function lg(e){return new Promise(t=>setTimeout(t,e))}function cg(){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 Gt}from"gql.tada";var dg=Gt(`
595
+ `);async function Ui(){$g();let e=Pg(process.cwd()),t=e.cwd,r=await P(t);r.ok||(process.stderr.write(`ripplo: DSL compilation failed: ${r.error}
596
+ `),process.exit(1));let n=await Cg(()=>ut({compiled:r.result,config:e,cwd:t}));Vi({cwd:t,paused:n.hooksPaused});let o=Wt(t);o!=null&&y.info("watching branch %s in %s",o,t);let i=oi(t),s=gg({headers:{Authorization:`Bearer ${e.token}`},retryAttempts:1/0,url:`${e.ripploServerUrl}/graphql`}),a=Sg({config:e,cwd:t,devSessionId:n.devSessionId,sseClient:s}),l=kg({cwd:t,projectId:e.projectId,sseClient:s}),c=Rg({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)
597
+ `);let p=async()=>{c(),a(),l(),await Promise.race([f({config:e,document:vg,variables:{cwd:e.cwd,projectId:e.projectId}}).catch(()=>{}),new Promise(k=>setTimeout(k,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 Sg({config:e,cwd:t,devSessionId:r,sseClient:n}){return n.subscribe({query:_i(hg),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})
598
+ `),Li({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 Vi({cwd:e,paused:t}){let r=Pe(e);if(t&&!Kt.existsSync(r)){Kt.writeFileSync(r,"");return}!t&&Kt.existsSync(r)&&Kt.unlinkSync(r)}function kg({cwd:e,projectId:t,sseClient:r}){return r.subscribe({query:_i(wg),variables:{projectId:t}},{complete:()=>{},error:n=>{y.error(n,"hooksPaused subscription error")},next:n=>{let o=n.data?.hooksPausedRequested?.paused;o!=null&&Vi({cwd:e,paused:o})}})}function Rg({config:e,devSessionId:t}){let r=setInterval(()=>{f({config:e,document:bg,variables:{id:t}}).catch(n=>{y.warn("heartbeat failed: %s",n instanceof Error?n.message:String(n))})},yg);return()=>{clearInterval(r)}}function Pg(e){try{return _(e)}catch(t){let r=t instanceof Error?t.message:String(t);process.stderr.write(`${r}
599
+ `),process.exit(1)}}var xg=1e3,Eg=6e4;async function Cg(e){let t=Date.now()+Eg,r;for(;Date.now()<t;){let n=await Ag(e);if(n.ok)return n.value;if(!Ig(n.message))throw n.error;r=n.error,await Tg(xg)}throw r instanceof Error?r:new Error("server never became ready")}async function Ag(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 Ig(e){return e.includes("status 502")||e.includes("ECONNREFUSED")||e.includes("Failed to connect")||e.includes("fetch failed")}function Tg(e){return new Promise(t=>setTimeout(t,e))}function $g(){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 Xt}from"gql.tada";var jg=Xt(`
600
600
  query ScopeWorkflowBySlug($projectId: String!, $cwd: String!, $slug: String!) {
601
601
  project(id: $projectId) {
602
602
  id
@@ -609,7 +609,7 @@ ${String(m)} error(s)
609
609
  }
610
610
  }
611
611
  }
612
- `),ug=Gt(`
612
+ `),Ng=Xt(`
613
613
  mutation ScopeAddDirtyTests($projectId: String!, $cwd: String!, $workflowSlugs: [String!]!) {
614
614
  addDirtyTestsToScope(projectId: $projectId, cwd: $cwd, workflowSlugs: $workflowSlugs) {
615
615
  id
@@ -619,35 +619,35 @@ ${String(m)} error(s)
619
619
  }
620
620
  }
621
621
  }
622
- `),pg=Gt(`
622
+ `),Og=Xt(`
623
623
  mutation ScopeLink($id: ID!, $workflowId: String!) {
624
624
  linkScopeItem(id: $id, workflowId: $workflowId) {
625
625
  id
626
626
  }
627
627
  }
628
- `),mg=Gt(`
628
+ `),Dg=Xt(`
629
629
  mutation ScopeRemoveMany($ids: [ID!]!) {
630
630
  removeScopeItems(ids: $ids)
631
631
  }
632
- `);async function $i(e){let t=ue();await fe(t);let n=(await f({config:t,document:Wt,variables:{cwd:t.cwd,projectId:t.projectId}})).project?.devSession?.scopeItems??[];if(e.format==="json"){process.stdout.write(`${JSON.stringify(n,null,2)}
632
+ `);async function Fi(e){let t=ue();await fe(t);let n=(await f({config:t,document:Gt,variables:{cwd:t.cwd,projectId:t.projectId}})).project?.devSession?.scopeItems??[];if(e.format==="json"){process.stdout.write(`${JSON.stringify(n,null,2)}
633
633
  `);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??""}
634
634
  `);return}let s=i.spec==null?"stub":"implemented";process.stdout.write(` [${s}] (${o.id}) ${i.slug} \u2014 ${i.name}
635
- `)})}async function ji({testIds:e}){let t=ue();await fe(t),await Ee(t.cwd,t);let n=(await f({config:t,document:ug,variables:{cwd:t.cwd,projectId:t.projectId,workflowSlugs:[...e]}})).addDirtyTestsToScope??[];if(n.length===0){process.stdout.write(`No scope items added.
635
+ `)})}async function Hi({testIds:e}){let t=ue();await fe(t),await Ce(t.cwd,t);let n=(await f({config:t,document:Ng,variables:{cwd:t.cwd,projectId:t.projectId,workflowSlugs:[...e]}})).addDirtyTestsToScope??[];if(n.length===0){process.stdout.write(`No scope items added.
636
636
  `);return}let o=n.map(i=>i.workflow?.slug??"?").join(", ");process.stdout.write(`Added ${String(n.length)} scope item(s): ${o}
637
- `)}async function Ni({id:e,testId:t}){let r=ue();await fe(r),await Ee(r.cwd,r);let n=await fg({cfg:r,slug:t});await f({config:r,document:pg,variables:{id:e,workflowId:n}}),process.stdout.write(`Linked scope item ${e} to ${t}
638
- `)}async function Oi({ids:e}){let t=ue();await fe(t);let n=(await f({config:t,document:mg,variables:{ids:[...e]}})).removeScopeItems??0;process.stdout.write(`Removed ${String(n)} scope item(s)
639
- `)}async function fg({cfg:e,slug:t}){let n=(await f({config:e,document:dg,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.
637
+ `)}async function Mi({id:e,testId:t}){let r=ue();await fe(r),await Ce(r.cwd,r);let n=await Lg({cfg:r,slug:t});await f({config:r,document:Og,variables:{id:e,workflowId:n}}),process.stdout.write(`Linked scope item ${e} to ${t}
638
+ `)}async function Bi({ids:e}){let t=ue();await fe(t);let n=(await f({config:t,document:Dg,variables:{ids:[...e]}})).removeScopeItems??0;process.stdout.write(`Removed ${String(n)} scope item(s)
639
+ `)}async function Lg({cfg:e,slug:t}){let n=(await f({config:e,document:jg,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.
640
640
  `),process.stderr.write(`${h("create")}
641
- `),process.exit(1)),n.id}async function Di(e){let t=process.cwd(),r=await P(t);r.ok||(process.stderr.write(`Compilation failed: ${r.error}
641
+ `),process.exit(1)),n.id}async function Wi(e){let t=process.cwd(),r=await P(t);r.ok||(process.stderr.write(`Compilation failed: ${r.error}
642
642
  `),process.exit(1));let{tests:n}=r.builder.getUnimplemented();if(e.format==="summary"){n.length>0&&process.stdout.write(`tests: ${n.join(", ")}
643
643
  `);return}let o={tests:n.map(i=>({id:i,implemented:!1}))};process.stdout.write(`${JSON.stringify(o,null,2)}
644
- `)}import{z as gg}from"zod";function E(e,t){let r=gg.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 Px}from"crypto";import Li from"picomatch";function yg(e){return K(["diff","--name-only","HEAD"],e).split(`
645
- `).filter(t=>t.length>0)}function _i({cwd:e,ignoreGlobs:t,watchGlobs:r}){let n=Li([...r]),o=Li([...t]);return yg(e).filter(i=>n(i)&&!o(i))}function Kt(e,...t){return K(["diff","--name-only","HEAD","--",...t],e).split(`
646
- `).filter(r=>r.length>0)}function xe(){return{ignorePaths:ke,watchPaths:Gr}}var Ui=E("UserPromptSubmit",e=>{let{cwd:t}=e;if(!C(t)||!T(t))return;let r=Re(t);if(Be(t,"coverage-nudge")===r)return;let{ignorePaths:n,watchPaths:o}=xe(),i=_i({cwd:t,ignoreGlobs:n,watchGlobs:o});if(We(t,"coverage-nudge",r),!(i.length===0||Kt(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. ${h("scope")}`,hookEventName:"UserPromptSubmit"}}});import Jt from"fs";import hg from"os";import Vi from"path";var Fi=E("PreToolUse",e=>{if(e.tool_name!=="ExitPlanMode"||!T(e.cwd))return;let t=wg();if(t==null)return;let r=Jt.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. ${h("explore")}`}}});function wg(){let e=Vi.join(hg.homedir(),".claude","plans");return Jt.existsSync(e)?Jt.readdirSync(e).filter(r=>r.endsWith(".md")).map(r=>Vi.join(e,r)).map(r=>({full:r,mtime:Jt.statSync(r).mtimeMs})).sort((r,n)=>n.mtime-r.mtime)[0]?.full??null:null}var Hi=E("UserPromptSubmit",async e=>{if(e.permission_mode!=="plan"||!C(e.cwd)||!T(e.cwd))return;let t=await P(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(`
647
- `),hookEventName:"UserPromptSubmit"}}});import bg from"path";import Mi from"picomatch";import{z as Bi}from"zod";var vg=Bi.looseObject({file_path:Bi.string()}),Wi=E("PostToolUse",async e=>{let t=vg.safeParse(e.tool_input);if(!t.success)return;let r=t.data.file_path,{cwd:n}=e;if(!C(n)||!T(n))return;let o=bg.relative(n,r);if(o.startsWith(".."))return;let{ignorePaths:i,watchPaths:s}=xe(),a=Mi([...s]),l=Mi([...i]);if(!a(o)||l(o))return;let c=await P(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 qi}from"zod";var Sg=qi.looseObject({file_path:qi.string()}),zi=E("PostToolUse",async e=>{let t=Sg.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(!C(n)||!T(n))return;let o=await P(n);if(!o.ok)return{decision:"block",reason:`Compilation failed: ${o.error}
648
- ${h("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 Ge({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(`
644
+ `)}import{z as _g}from"zod";function A(e,t){let r=_g.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 sE}from"crypto";import qi from"picomatch";function Ug(e){return M(["diff","--name-only","HEAD"],e).split(`
645
+ `).filter(t=>t.length>0)}function zi({cwd:e,ignoreGlobs:t,watchGlobs:r}){let n=qi([...r]),o=qi([...t]);return Ug(e).filter(i=>n(i)&&!o(i))}function Yt(e,...t){return M(["diff","--name-only","HEAD","--",...t],e).split(`
646
+ `).filter(r=>r.length>0)}function xe(){return{ignorePaths:ke,watchPaths:Jr}}var Gi=A("UserPromptSubmit",e=>{let{cwd:t}=e;if(!C(t)||!$(t))return;let r=Re(t);if(We(t,"coverage-nudge")===r)return;let{ignorePaths:n,watchPaths:o}=xe(),i=zi({cwd:t,ignoreGlobs:n,watchGlobs:o});if(qe(t,"coverage-nudge",r),!(i.length===0||Yt(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. ${h("scope")}`,hookEventName:"UserPromptSubmit"}}});import Qt from"fs";import Vg from"os";import Ki from"path";var Ji=A("PreToolUse",e=>{if(e.tool_name!=="ExitPlanMode"||!$(e.cwd))return;let t=Fg();if(t==null)return;let r=Qt.readFileSync(t,"utf8");if(!/\.ripplo\/tests|Tests to implement|No e2e coverage needed/.test(r))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Plan must cite ripplo test stubs. Add a "Tests to implement" section listing .ripplo/tests/<id>.ts per affected flow, OR add "No e2e coverage needed: <reason>" if this plan touches no user-facing behavior. ${h("explore")}`}}});function Fg(){let e=Ki.join(Vg.homedir(),".claude","plans");return Qt.existsSync(e)?Qt.readdirSync(e).filter(r=>r.endsWith(".md")).map(r=>Ki.join(e,r)).map(r=>({full:r,mtime:Qt.statSync(r).mtimeMs})).sort((r,n)=>n.mtime-r.mtime)[0]?.full??null:null}var Xi=A("UserPromptSubmit",async e=>{if(e.permission_mode!=="plan"||!C(e.cwd)||!$(e.cwd))return;let t=await P(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(`
647
+ `),hookEventName:"UserPromptSubmit"}}});import Hg from"path";import Yi from"picomatch";import{z as Qi}from"zod";var Mg=Qi.looseObject({file_path:Qi.string()}),Zi=A("PostToolUse",async e=>{let t=Mg.safeParse(e.tool_input);if(!t.success)return;let r=t.data.file_path,{cwd:n}=e;if(!C(n)||!$(n))return;let o=Hg.relative(n,r);if(o.startsWith(".."))return;let{ignorePaths:i,watchPaths:s}=xe(),a=Yi([...s]),l=Yi([...i]);if(!a(o)||l(o))return;let c=await P(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 es}from"zod";var Bg=es.looseObject({file_path:es.string()}),ts=A("PostToolUse",async e=>{let t=Bg.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(!C(n)||!$(n))return;let o=await P(n);if(!o.ok)return{decision:"block",reason:`Compilation failed: ${o.error}
648
+ ${h("create","DSL authoring + lint rules")}`};await ce({cwd:n,result:o.result}),He({cwd:n});let{diagnostics:i}=Ve(o.result);if(i.length===0){let{addedSlugs:a}=await Ke({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(`
649
649
  `)}
650
- ${h("create")}`}});import{z as Gi}from"zod";var kg=Gi.looseObject({command:Gi.string()}),Rg=/\bripplo\s+hooks\s+pause\b/,Ki=E("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=kg.safeParse(e.tool_input);if(!t.success||!Rg.test(t.data.command))return;let{cwd:r}=e;if(C(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 Ag}from"shell-quote";import{z as Yi}from"zod";import{existsSync as Pg,mkdirSync as xg,rmSync as SC,writeFileSync as Cg}from"fs";import an from"path";function Ji(e,t,r){let n=Xi(e,t,r);xg(an.dirname(n),{recursive:!0}),Cg(n,"")}function Xt(e,t,r){return Pg(Xi(e,t,r))}function Eg(e,t){return an.join(e,".ripplo",".local","skills-loaded",t)}function Xi(e,t,r){return an.join(Eg(e,t),r)}var Ig=Yi.looseObject({command:Yi.string()}),Tg="debug",$g=new Set(["tail","head","less","more","wc","sort","uniq","awk","sed","grep"]),Zi=E("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=Ig.safeParse(e.tool_input);if(!t.success)return;let r=jg(t.data.command);if(!Ng(r))return;let{cwd:n}=e;if(!C(n)||!T(n))return;let o=Dg(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(!Xt(n,e.session_id,Tg))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 jg(e){try{return Ag(e)}catch{return[]}}function Ng(e){return e.some((t,r)=>t==="ripplo"&&e[r+1]==="run")}function Og(e){return typeof e=="object"&&"op"in e&&e.op==="|"}function Dg(e){let t=e.find((r,n)=>{let o=e[n-1];return o!=null&&Og(o)&&typeof r=="string"&&$g.has(r)});return typeof t=="string"?t:null}function Qi(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}}}import Lg from"path";import{z as es}from"zod";var _g=new Set(["Edit","Write","NotebookEdit"]),Ug=es.looseObject({file_path:es.string()}),Vg="create",ts=E("PreToolUse",e=>{if(!_g.has(e.tool_name))return;let t=Ug.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!C(r)||!T(r))return;let n=Lg.relative(r,t.data.file_path);if(!(n.startsWith("..")||n!==".ripplo"&&!n.startsWith(".ripplo/"))&&!Xt(r,e.session_id,Vg))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 Fg from"path";import rs from"picomatch";import{graphql as Hg}from"gql.tada";import{z as ns}from"zod";var Mg=new Set(["Edit","Write","NotebookEdit"]),Bg=ns.looseObject({file_path:ns.string()}),Wg=Hg(`
650
+ ${h("create")}`}});import{z as rs}from"zod";var Wg=rs.looseObject({command:rs.string()}),qg=/\bripplo\s+hooks\s+pause\b/,ns=A("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=Wg.safeParse(e.tool_input);if(!t.success||!qg.test(t.data.command))return;let{cwd:r}=e;if(C(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 Xg}from"shell-quote";import{z as ss}from"zod";import{existsSync as zg,mkdirSync as Gg,rmSync as nC,writeFileSync as Kg}from"fs";import dn from"path";function os(e,t,r){let n=is(e,t,r);Gg(dn.dirname(n),{recursive:!0}),Kg(n,"")}function Zt(e,t,r){return zg(is(e,t,r))}function Jg(e,t){return dn.join(e,".ripplo",".local","skills-loaded",t)}function is(e,t,r){return dn.join(Jg(e,t),r)}var Yg=ss.looseObject({command:ss.string()}),Qg="debug",Zg=new Set(["tail","head","less","more","wc","sort","uniq","awk","sed","grep"]),ls=A("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=Yg.safeParse(e.tool_input);if(!t.success)return;let r=ey(t.data.command);if(!ty(r))return;let{cwd:n}=e;if(!C(n)||!$(n))return;let o=ny(r);if(o!=null)return as(`Don't pipe \`ripplo run\` through \`${o}\` \u2014 buffering filters hold all stdout until EOF, hiding live progress; if you kill the pipeline mid-run the run is orphaned on the server. Redirect to a file instead: \`ripplo run <id> > /tmp/run.log 2>&1\` and Read the file, or use \`run_in_background: true\`.`);if(!Zt(n,e.session_id,Qg))return as("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 ey(e){try{return Xg(e)}catch{return[]}}function ty(e){return e.some((t,r)=>t==="ripplo"&&e[r+1]==="run")}function ry(e){return typeof e=="object"&&"op"in e&&e.op==="|"}function ny(e){let t=e.find((r,n)=>{let o=e[n-1];return o!=null&&ry(o)&&typeof r=="string"&&Zg.has(r)});return typeof t=="string"?t:null}function as(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}}}import oy from"path";import{z as cs}from"zod";var iy=new Set(["Edit","Write","NotebookEdit"]),sy=cs.looseObject({file_path:cs.string()}),ay="create",ds=A("PreToolUse",e=>{if(!iy.has(e.tool_name))return;let t=sy.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!C(r)||!$(r))return;let n=oy.relative(r,t.data.file_path);if(!(n.startsWith("..")||n!==".ripplo"&&!n.startsWith(".ripplo/"))&&!Zt(r,e.session_id,ay))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 ly from"path";import us from"picomatch";import{graphql as cy}from"gql.tada";import{z as ps}from"zod";var dy=new Set(["Edit","Write","NotebookEdit"]),uy=ps.looseObject({file_path:ps.string()}),py=cy(`
651
651
  query PreEditScopeGate($projectId: String!, $cwd: String!) {
652
652
  project(id: $projectId) {
653
653
  id
@@ -659,7 +659,7 @@ ${h("create")}`}});import{z as Gi}from"zod";var kg=Gi.looseObject({command:Gi.st
659
659
  }
660
660
  }
661
661
  }
662
- `),os=E("PreToolUse",async e=>{if(!Mg.has(e.tool_name))return;let t=Bg.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!C(r)||!T(r))return;let n=Fg.relative(r,t.data.file_path);if(!(n.startsWith("..")||n===".ripplo"||n.startsWith(".ripplo/")||!qg(n)||await zg(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). ${Vo(["scope","create"])}`}}});function qg(e){let{ignorePaths:t,watchPaths:r}=xe(),n=rs([...r]),o=rs([...t]);return n(e)&&!o(e)}async function zg(e){let t;try{t=_(e)}catch{return!0}let r=await f({config:t,document:Wg,variables:{cwd:t.cwd,projectId:t.projectId}}).catch(()=>null);return r==null?!0:(r.project?.devSession?.scopeItems??[]).length>0}import Gg from"fs";import Kg from"path";import{z as is}from"zod";var Jg=new Set(["Edit","Write","NotebookEdit"]),Xg=is.looseObject({file_path:is.string()}),ss=E("PreToolUse",e=>{if(!Jg.has(e.tool_name))return;let t=Xg.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!C(r))return;let n=Kg.relative(r,t.data.file_path);if(!(n.startsWith("..")||n!==".ripplo"&&!n.startsWith(".ripplo/"))&&!Gg.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. ${h("start")}`}}});import{graphql as Yg}from"gql.tada";var Qg=Yg(`
662
+ `),ms=A("PreToolUse",async e=>{if(!dy.has(e.tool_name))return;let t=uy.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!C(r)||!$(r))return;let n=ly.relative(r,t.data.file_path);if(!(n.startsWith("..")||n===".ripplo"||n.startsWith(".ripplo/")||!my(n)||await fy(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). ${Ko(["scope","create"])}`}}});function my(e){let{ignorePaths:t,watchPaths:r}=xe(),n=us([...r]),o=us([...t]);return n(e)&&!o(e)}async function fy(e){let t;try{t=_(e)}catch{return!0}let r=await f({config:t,document:py,variables:{cwd:t.cwd,projectId:t.projectId}}).catch(()=>null);return r==null?!0:(r.project?.devSession?.scopeItems??[]).length>0}import gy from"fs";import yy from"path";import{z as fs}from"zod";var hy=new Set(["Edit","Write","NotebookEdit"]),wy=fs.looseObject({file_path:fs.string()}),gs=A("PreToolUse",e=>{if(!hy.has(e.tool_name))return;let t=wy.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!C(r))return;let n=yy.relative(r,t.data.file_path);if(!(n.startsWith("..")||n!==".ripplo"&&!n.startsWith(".ripplo/"))&&!gy.existsSync(Pe(r))&&!Be(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. ${h("start")}`}}});import{graphql as by}from"gql.tada";var vy=by(`
663
663
  query ScopeReminder($projectId: String!, $cwd: String!) {
664
664
  project(id: $projectId) {
665
665
  id
@@ -676,9 +676,9 @@ ${h("create")}`}});import{z as Gi}from"zod";var kg=Gi.looseObject({command:Gi.st
676
676
  }
677
677
  }
678
678
  }
679
- `),as=E("UserPromptSubmit",async e=>{let{cwd:t}=e;if(!C(t)||!T(t))return;let r=Re(t);if(Be(t,"scope-reminder")===r)return;let n;try{n=_(t)}catch{return}let o=await f({config:n,document:Qg,variables:{cwd:n.cwd,projectId:n.projectId}}).catch(()=>null);if(o==null)return;We(t,"scope-reminder",r);let i=o.project?.devSession?.scopeItems??[];return{hookSpecificOutput:{additionalContext:i.length===0?`RIPPLO SCOPE: empty. ${h("scope")}`:`RIPPLO SCOPE (${String(i.length)}):
679
+ `),ys=A("UserPromptSubmit",async e=>{let{cwd:t}=e;if(!C(t)||!$(t))return;let r=Re(t);if(We(t,"scope-reminder")===r)return;let n;try{n=_(t)}catch{return}let o=await f({config:n,document:vy,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. ${h("scope")}`:`RIPPLO SCOPE (${String(i.length)}):
680
680
  ${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(`
681
- `)}`,hookEventName:"UserPromptSubmit"}}});var Zg="# 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",ls=E("SessionStart",e=>{if(C(e.cwd))return{hookSpecificOutput:{additionalContext:Zg,hookEventName:"SessionStart"}}});import{execFileSync as ey}from"child_process";import ty from"path";import cs from"process";import{graphql as ry}from"gql.tada";import{z as Yt}from"zod";var ny=ry(`
681
+ `)}`,hookEventName:"UserPromptSubmit"}}});var Sy="# 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",hs=A("SessionStart",e=>{if(C(e.cwd))return{hookSpecificOutput:{additionalContext:Sy,hookEventName:"SessionStart"}}});import{execFileSync as ky}from"child_process";import Ry from"path";import ws from"process";import{graphql as Py}from"gql.tada";import{z as er}from"zod";var xy=Py(`
682
682
  query ScopeEnforce($projectId: String!, $cwd: String!) {
683
683
  project(id: $projectId) {
684
684
  id
@@ -697,14 +697,14 @@ ${i.map(a=>{let l=a.workflow;return l==null?` [intent] (${a.id}) ${a.label??""}
697
697
  }
698
698
  }
699
699
  }
700
- `),us=E("Stop",async e=>{let{cwd:t}=e;if(!C(t)||!T(t))return;let r=Re(t),n=Be(t,"stop-enforce")===r;if(n&&!e.stop_hook_active)return;let o=oy(t),i=await iy(t,o);if(We(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:
700
+ `),vs=A("Stop",async e=>{let{cwd:t}=e;if(!C(t)||!$(t))return;let r=Re(t),n=We(t,"stop-enforce")===r;if(n&&!e.stop_hook_active)return;let o=Ey(t),i=await Cy(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:
701
701
  ${i.join(`
702
702
 
703
703
  `)}`}:{decision:"block",reason:i.join(`
704
704
 
705
- `)}});function oy(e){return Kt(e,".ripplo/tests").filter(t=>t.endsWith(".ts")).map(t=>ty.basename(t,".ts")).filter(t=>t!=="index")}async function iy(e,t){let r=await P(e);if(!r.ok)return[`--- Compilation failed ---
705
+ `)}});function Ey(e){return Yt(e,".ripplo/tests").filter(t=>t.endsWith(".ts")).map(t=>Ry.basename(t,".ts")).filter(t=>t!=="index")}async function Cy(e,t){let r=await P(e);if(!r.ok)return[`--- Compilation failed ---
706
706
  ${r.error}
707
- ${h("create")}`];await ce({cwd:e,result:r.result}),Fe({cwd:e});let n=await ay(e),o=ly(r,t),i=cy(r),s=sy(e,r),l=t.length>0||n.hasRunnable?dy(e):null;return[o,i,s,l,n.error].filter(c=>c!=null)}function sy(e,t){let{ignorePaths:r}=xe(),n=Ho({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(`
707
+ ${h("create")}`];await ce({cwd:e,result:r.result}),He({cwd:e});let n=await Iy(e),o=Ty(r,t),i=$y(r),s=Ay(e,r),l=t.length>0||n.hasRunnable?jy(e):null;return[o,i,s,l,n.error].filter(c=>c!=null)}function Ay(e,t){let{ignorePaths:r}=xe(),n=Xo({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(`
708
708
  `);s.push(`Unacknowledged interactions (add to a test's .coverage(...)):
709
709
  ${a}`)}if(i.length>0){let a=i.map(l=>` ${l.id}`).join(`
710
710
  `);s.push(`Stale .coverage(...) claims (id no longer exists in source):
@@ -712,23 +712,23 @@ ${a}`)}return`--- Exhaustiveness ---
712
712
  ${s.join(`
713
713
 
714
714
  `)}
715
- ${h("create")}`}async function ay(e){let t;try{t=_(e)}catch{return{error:null,hasRunnable:!1}}let n=(await f({config:t,document:ny,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.some(a=>a.workflow?.spec!=null);return{error:o.length===0?null:`--- Testing Scope ---
715
+ ${h("create")}`}async function Iy(e){let t;try{t=_(e)}catch{return{error:null,hasRunnable:!1}}let n=(await f({config:t,document:xy,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.some(a=>a.workflow?.spec!=null);return{error:o.length===0?null:`--- Testing Scope ---
716
716
  ${o.join(`
717
717
  `)}
718
- ${h("create")}`,hasRunnable:i}}function ly(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 ---
718
+ ${h("create")}`,hasRunnable:i}}function Ty(e,t){let{diagnostics:r}=Ve(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 ---
719
719
  ${[...i,...s].join(`
720
720
  `)}
721
- ${h("create")}`}function cy(e){let{tests:t}=e.builder.getUnimplemented();return t.length===0?null:`--- Unimplemented stubs ---
721
+ ${h("create")}`}function $y(e){let{tests:t}=e.builder.getUnimplemented();return t.length===0?null:`--- Unimplemented stubs ---
722
722
  ${t.join(", ")}
723
723
  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.
724
- ${h("create")}`}function dy(e){let t=py(["run"],e);if(t.code===0)return null;let r=t.output.split(`
724
+ ${h("create")}`}function jy(e){let t=Oy(["run"],e);if(t.code===0)return null;let r=t.output.split(`
725
725
  `).filter(n=>/FAILED/.test(n)).join(`
726
726
  `);return r.length===0?null:`--- Ripplo Run Failures (scope) ---
727
727
  ${r}
728
- Artifacts: .ripplo/debug/<runId>/. ${h("debug")}`}var uy=Yt.object({status:Yt.number().nullish(),stderr:Yt.unknown().optional(),stdout:Yt.unknown().optional()});function ds(e){return e instanceof Buffer?e.toString("utf8"):typeof e=="string"?e:""}function py(e,t){let r=cs.argv[1];if(r==null)return{code:1,output:""};try{return{code:0,output:ey(cs.execPath,[r,...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}}catch(n){let o=uy.safeParse(n);if(!o.success)return{code:1,output:""};let i=`${ds(o.data.stdout)}${ds(o.data.stderr)}`;return{code:o.data.status??1,output:i}}}import{z as ps}from"zod";var my=ps.looseObject({skill:ps.string()}),ms=E("PostToolUse",e=>{if(e.tool_name!=="Skill")return;let t=my.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&&C(e.cwd)&&Ji(e.cwd,e.session_id,n)});Ry();fn(process.cwd());var fs={"coverage-nudge":Ui,"exit-plan-gate":Fi,"plan-reminder":Hi,"post-edit-flag-stubs":Wi,"post-edit-lint":zi,"pre-bash-hooks-pause-gate":Ki,"pre-bash-run-gate":Zi,"pre-edit-ripplo-skill-gate":ts,"pre-edit-scope-gate":os,"pre-edit-watch-gate":ss,"scope-reminder":as,"session-preamble":ls,"stop-enforce":us,"track-skill-load":ms};async function yy(){await fy(gy(process.argv)).scriptName("ripplo").version("0.4.17").command("watch","Watch for run requests and execute locally",()=>{},()=>Ii()).command("auth <subcommand>","Manage authentication",ky).command("projects <subcommand>","Inspect Ripplo projects",Sy).command("hooks <subcommand>","Pause or resume Ripplo hooks",vy).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=>vi({appUrl:e["app-url"],engineUrl:e["engine-url"],envFile:e.env,projectId:e.project})).command("run [ids..]","Run tests (defaults to scope; auto-adds dirty tests)",e=>{let t=[];return e.positional("ids",{array:!0,default:t,describe:"Test ids to run (defaults to dev-session scope)",type:"string"}).option("all",{default:!1,describe:"Run every test in the dev session (expensive)",type:"boolean"})},e=>xi({all:e.all,ids: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=>Ri({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=>pi({id:e.id,runs:e.runs})).command("sync","Push the compiled .ripplo/ resources to the server (no run)",()=>{},()=>Ci()).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=>Fo({check:e.check})).command("cover","Audit all coverage statements",()=>{},()=>qo()).command("doctor","Check project health",()=>{},()=>ii()).command("status","Report unimplemented tests and preconditions",e=>e.option("format",{choices:["json","summary"],default:"json",describe:"Output format"}),e=>Di({format:e.format})).command("scope <subcommand>","Manage testing scope",by).command("hook <name>","Internal: run a Claude Code plugin hook",e=>e.positional("name",{choices:Object.keys(fs),demandOption:!0,type:"string"}),e=>hy(e.name)).strict().help().parse()}async function hy(e){let t=fs[e];t==null&&(process.stderr.write(`Unknown hook: ${e}
729
- `),process.exit(1));let r=await wy(),n=r.trim()===""?{}:JSON.parse(r),o=await t.run(n);o!=null&&process.stdout.write(JSON.stringify(o))}function wy(){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)})}yy().catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
730
- `),process.exit(1)});function by(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=>ji({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=>Ni({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=>Oi({ids:t.ids})).demandCommand(1)}function vy(e){return e.command("pause","Disable all Ripplo pre-edit gates and stop enforcement until resumed",()=>{},()=>mi()).command("resume","Re-enable Ripplo hooks paused via `ripplo hooks pause`",()=>{},()=>fi()).demandCommand(1)}function Sy(e){return e.command("list","List projects you have access to (JSON)",()=>{},()=>Pi()).demandCommand(1)}function ky(e){return e.command("login","Authenticate via device flow",()=>{},()=>mo()).command("status","Show authentication status",()=>{},()=>fo()).command("logout","Remove the saved token",()=>{},()=>{go()}).demandCommand(1)}function Ry(){let e=process.cwd(),t=Zt(e);t!=null&&t!==e&&(process.chdir(t),process.stderr.write(`ripplo: resolved .ripplo/ at ${t}
731
- `))}export{yy as main};
728
+ Artifacts: .ripplo/debug/<runId>/. ${h("debug")}`}var Ny=er.object({status:er.number().nullish(),stderr:er.unknown().optional(),stdout:er.unknown().optional()});function bs(e){return e instanceof Buffer?e.toString("utf8"):typeof e=="string"?e:""}function Oy(e,t){let r=ws.argv[1];if(r==null)return{code:1,output:""};try{return{code:0,output:ky(ws.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=`${bs(o.data.stdout)}${bs(o.data.stderr)}`;return{code:o.data.status??1,output:i}}}import{z as Ss}from"zod";var Dy=Ss.looseObject({skill:Ss.string()}),ks=A("PostToolUse",e=>{if(e.tool_name!=="Skill")return;let t=Dy.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&&C(e.cwd)&&os(e.cwd,e.session_id,n)});qy();hn(process.cwd());var Rs={"coverage-nudge":Gi,"exit-plan-gate":Ji,"plan-reminder":Xi,"post-edit-flag-stubs":Zi,"post-edit-lint":ts,"pre-bash-hooks-pause-gate":ns,"pre-bash-run-gate":ls,"pre-edit-ripplo-skill-gate":ds,"pre-edit-scope-gate":ms,"pre-edit-watch-gate":gs,"scope-reminder":ys,"session-preamble":hs,"stop-enforce":vs,"track-skill-load":ks};async function Uy(){await Ly(_y(process.argv)).scriptName("ripplo").version("0.4.19").command("watch","Watch for run requests and execute locally",()=>{},()=>Ui()).command("auth <subcommand>","Manage authentication",Wy).command("projects <subcommand>","Inspect Ripplo projects",By).command("hooks <subcommand>","Pause or resume Ripplo hooks",My).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=>Ii({appUrl:e["app-url"],engineUrl:e["engine-url"],envFile:e.env,projectId:e.project})).command("run [ids..]","Run tests (defaults to scope; auto-adds dirty tests)",e=>{let t=[];return e.positional("ids",{array:!0,default:t,describe:"Test ids to run (defaults to dev-session scope)",type:"string"}).option("all",{default:!1,describe:"Run every test in the dev session (expensive)",type:"boolean"})},e=>Oi({all:e.all,ids: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=>ji({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=>Si({id:e.id,runs:e.runs})).command("sync","Push the compiled .ripplo/ resources to the server (no run)",()=>{},()=>Di()).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=>Jo({check:e.check})).command("cover","Audit all coverage statements",()=>{},()=>ei()).command("doctor","Check project health",()=>{},()=>fi()).command("status","Report unimplemented tests and preconditions",e=>e.option("format",{choices:["json","summary"],default:"json",describe:"Output format"}),e=>Wi({format:e.format})).command("scope <subcommand>","Manage testing scope",Hy).command("hook <name>","Internal: run a Claude Code plugin hook",e=>e.positional("name",{choices:Object.keys(Rs),demandOption:!0,type:"string"}),e=>Vy(e.name)).strict().help().parse()}async function Vy(e){let t=Rs[e];t==null&&(process.stderr.write(`Unknown hook: ${e}
729
+ `),process.exit(1));let r=await Fy(),n=r.trim()===""?{}:JSON.parse(r),o=await t.run(n);o!=null&&process.stdout.write(JSON.stringify(o))}function Fy(){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)}
730
+ `),process.exit(1)});function Hy(e){return e.command("status","Print the current scope",t=>t.option("format",{choices:["json","text"],default:"text",describe:"Output format"}),t=>Fi({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=>Hi({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=>Mi({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=>Bi({ids:t.ids})).demandCommand(1)}function My(e){return e.command("pause","Disable all Ripplo pre-edit gates and stop enforcement until resumed",()=>{},()=>ki()).command("resume","Re-enable Ripplo hooks paused via `ripplo hooks pause`",()=>{},()=>Ri()).demandCommand(1)}function By(e){return e.command("list","List projects you have access to (JSON)",()=>{},()=>Ni()).demandCommand(1)}function Wy(e){return e.command("login","Authenticate via device flow",()=>{},()=>ho()).command("status","Show authentication status",()=>{},()=>wo()).command("logout","Remove the saved token",()=>{},()=>{bo()}).demandCommand(1)}function qy(){let e=process.cwd(),t=rr(e);t!=null&&t!==e&&(process.chdir(t),process.stderr.write(`ripplo: resolved .ripplo/ at ${t}
731
+ `))}export{Uy as main};
732
732
  /*! Bundled license information:
733
733
 
734
734
  mustache/mustache.mjs: