ripplo 0.4.20 → 0.5.1

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 +206 -204
  2. package/package.json +5 -5
package/dist/index.js CHANGED
@@ -1,29 +1,26 @@
1
1
  #!/usr/bin/env node
2
- var gn=Object.defineProperty;var Es=Object.getOwnPropertyDescriptor;var Cs=Object.getOwnPropertyNames;var As=Object.prototype.hasOwnProperty;var Is=(e,t)=>{for(var r in t)gn(e,r,{get:t[r],enumerable:!0})},fn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Cs(t))!As.call(e,o)&&o!==r&&gn(e,o,{get:()=>t[o],enumerable:!(n=Es(t,o))||n.enumerable});return e},or=(e,t,r)=>(fn(e,t,"default"),r&&fn(r,t,"default"));import{execFileSync as Ts}from"child_process";import $s from"fs";import gt from"path";function ir(e){let t=Ns(e);return t??yn(e)}function yn(e){let t=gt.dirname(e);return js(gt.join(e,".ripplo"))?e:t===e?null:yn(t)}function js(e){try{return $s.statSync(e).isDirectory()}catch{return!1}}function Ns(e){let t=Os(["rev-parse","--show-toplevel"],e);if(t==null)return null;let r=t.trim();return r.length===0?null:gt.isAbsolute(r)?r:gt.resolve(e,r)}function Os(e,t){try{return Ts("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return null}}import bn from"fs";import wt from"path";import{config as _s}from"dotenv";import{z as ht}from"zod";import Xe from"fs";import ar from"path";import{z as yt}from"zod";var hn=ar.join(".ripplo","project.json"),sr=[".env",".env.local"],Ds=yt.object({envFiles:yt.array(yt.string().min(1)).optional(),projectId:yt.string().min(1)});function lr(e){return ar.join(e,hn)}function cr(e){let t=lr(e);if(!Xe.existsSync(t))throw new Error(`ripplo: missing ${hn}. Run \`ripplo init\` to create it.`);let r=JSON.parse(Xe.readFileSync(t,"utf8")),n=Ds.parse(r);return{envFiles:n.envFiles??sr,projectId:n.projectId}}function dr(e){let t=lr(e);if(Xe.existsSync(t))try{return cr(e)}catch{return}}function wn({cwd:e,envFiles:t,projectId:r}){let n=lr(e);Xe.mkdirSync(ar.dirname(n),{recursive:!0});let o={projectId:r};t!=null&&!Ls(t)&&(o.envFiles=[...t]),Xe.writeFileSync(n,JSON.stringify(o,null,2)+`
3
- `)}function Ls(e){return e.length!==sr.length?!1:e.every((t,r)=>t===sr[r])}function vn(e){let r=dr(e)?.envFiles??[".env",".env.local"],n=wt.join(e,".ripplo");r.forEach(o=>{let i=wt.resolve(n,o);bn.existsSync(i)&&_s({override:!0,path:i,quiet:!0})}),ur=void 0}var Us=ht.object({RIPPLO_APP_URL:ht.url(),RIPPLO_ENGINE_URL:ht.url(),RIPPLO_WEBHOOK_SECRET:ht.string().min(1)}),ur;function Te(){return ur??=Vs(),ur}function Vs(){let e=Us.safeParse(process.env);if(!e.success){let r=e.error.issues.map(s=>` ${s.path.join(".")}: ${s.message}`).join(`
4
- `),n=pr(process.cwd()),o=n.map(s=>` ${s}`).join(`
5
- `),i=n.length>0?`
2
+ var ra=Object.create;var mr=Object.defineProperty;var na=Object.getOwnPropertyDescriptor;var oa=Object.getOwnPropertyNames;var ia=Object.getPrototypeOf,sa=Object.prototype.hasOwnProperty;var aa=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),la=(e,t)=>{for(var r in t)mr(e,r,{get:t[r],enumerable:!0})},pr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of oa(t))!sa.call(e,o)&&o!==r&&mr(e,o,{get:()=>t[o],enumerable:!(n=na(t,o))||n.enumerable});return e},fr=(e,t,r)=>(pr(e,t,"default"),r&&pr(r,t,"default")),gr=(e,t,r)=>(r=e!=null?ra(ia(e)):{},pr(t||!e||!e.__esModule?mr(r,"default",{value:e,enumerable:!0}):r,e));var Et=aa((Rb,po)=>{"use strict";var kl=(function(){function e(r,n){if(typeof r!="function")throw new TypeError("DataLoader must be constructed with a function which accepts "+("Array<key> and returns Promise<Array<value>>, but got: "+r+"."));this._batchLoadFn=r,this._maxBatchSize=El(n),this._batchScheduleFn=Cl(n),this._cacheKeyFn=Tl(n),this._cacheMap=Al(n),this._batch=null,this.name=Il(n)}var t=e.prototype;return t.load=function(n){if(n==null)throw new TypeError("The loader.load() function must be called with a value, "+("but got: "+String(n)+"."));var o=Pl(this),i=this._cacheMap,s;if(i){s=this._cacheKeyFn(n);var a=i.get(s);if(a){var l=o.cacheHits||(o.cacheHits=[]);return new Promise(function(p){l.push(function(){p(a)})})}}o.keys.push(n);var c=new Promise(function(p,m){o.callbacks.push({resolve:p,reject:m})});return i&&i.set(s,c),c},t.loadMany=function(n){if(!uo(n))throw new TypeError("The loader.loadMany() function must be called with Array<key> "+("but got: "+n+"."));for(var o=[],i=0;i<n.length;i++)o.push(this.load(n[i]).catch(function(s){return s}));return Promise.all(o)},t.clear=function(n){var o=this._cacheMap;if(o){var i=this._cacheKeyFn(n);o.delete(i)}return this},t.clearAll=function(){var n=this._cacheMap;return n&&n.clear(),this},t.prime=function(n,o){var i=this._cacheMap;if(i){var s=this._cacheKeyFn(n);if(i.get(s)===void 0){var a;o instanceof Error?(a=Promise.reject(o),a.catch(function(){})):a=Promise.resolve(o),i.set(s,a)}}return this},e})(),Rl=typeof process=="object"&&typeof process.nextTick=="function"?function(e){jr||(jr=Promise.resolve()),jr.then(function(){process.nextTick(e)})}:typeof setImmediate=="function"?function(e){setImmediate(e)}:function(e){setTimeout(e)},jr;function Pl(e){var t=e._batch;if(t!==null&&!t.hasDispatched&&t.keys.length<e._maxBatchSize)return t;var r={hasDispatched:!1,keys:[],callbacks:[]};return e._batch=r,e._batchScheduleFn(function(){xl(e,r)}),r}function xl(e,t){if(t.hasDispatched=!0,t.keys.length===0){Or(t);return}var r;try{r=e._batchLoadFn(t.keys)}catch(n){return Nr(e,t,new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function "+("errored synchronously: "+String(n)+".")))}if(!r||typeof r.then!="function")return Nr(e,t,new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did "+("not return a Promise: "+String(r)+".")));r.then(function(n){if(!uo(n))throw new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did "+("not return a Promise of an Array: "+String(n)+"."));if(n.length!==t.keys.length)throw new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array of the same length as the Array of keys."+(`
6
3
 
7
- Declared env file(s) not found at this path:
8
- ${o}
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
- ${r}
4
+ Keys:
5
+ `+String(t.keys))+(`
11
6
 
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 pr(e){let r=dr(e)?.envFiles??[],n=wt.join(e,".ripplo");return r.map(o=>wt.resolve(n,o)).filter(o=>!bn.existsSync(o))}import Wy from"yargs";import{hideBin as qy}from"yargs/helpers";import{graphql as bd}from"gql.tada";import aa from"path";import{AsyncLocalStorage as Fs}from"async_hooks";import Hs from"path";var Ms=new Fs;function Sn(){let e=Ms.getStore();return e!=null?e.fixturesDir:Hs.join(process.cwd(),".ripplo","fixtures")}async function bt(e,t,r){let n;try{return n=await e.context().newCDPSession(e),await r(n)}catch{return t}finally{await n?.detach().catch(()=>{})}}async function G({awaitPromise:e,expression:t,page:r}){return bt(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 Bs=Object.prototype.toString,je=Array.isArray||function(t){return Bs.call(t)==="[object Array]"};function fr(e){return typeof e=="function"}function Ws(e){return je(e)?"array":typeof e}function mr(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function kn(e,t){return e!=null&&typeof e=="object"&&t in e}function qs(e,t){return e!=null&&typeof e!="object"&&e.hasOwnProperty&&e.hasOwnProperty(t)}var zs=RegExp.prototype.test;function Gs(e,t){return zs.call(e,t)}var Ks=/\S/;function Js(e){return!Gs(Ks,e)}var Ys={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function Xs(e){return String(e).replace(/[&<>"'`=\/]/g,function(r){return Ys[r]})}var Qs=/\s*/,Zs=/\s+/,Rn=/\s*=/,ea=/\s*\}/,ta=/#|\^|\/|>|\{|&|=|!/;function ra(e,t){if(!e)return[];var r=!1,n=[],o=[],i=[],s=!1,a=!1,l="",c=0;function p(){if(s&&!a)for(;i.length;)delete o[i.pop()];else i=[];s=!1,a=!1}var m,S,N;function O(ie){if(typeof ie=="string"&&(ie=ie.split(Zs,2)),!je(ie)||ie.length!==2)throw new Error("Invalid tags: "+ie);m=new RegExp(mr(ie[0])+"\\s*"),S=new RegExp("\\s*"+mr(ie[1])),N=new RegExp("\\s*"+mr("}"+ie[1]))}O(t||Z.tags);for(var g=new Ze(e),q,j,V,oe,Ie,se;!g.eos();){if(q=g.pos,V=g.scanUntil(m),V)for(var Ye=0,z=V.length;Ye<z;++Ye)oe=V.charAt(Ye),Js(oe)?(i.push(o.length),l+=oe):(a=!0,r=!0,l+=" "),o.push(["text",oe,q,q+1]),q+=1,oe===`
13
- `&&(p(),l="",c=0,r=!1);if(!g.scan(m))break;if(s=!0,j=g.scan(ta)||"name",g.scan(Qs),j==="="?(V=g.scanUntil(Rn),g.scan(Rn),g.scanUntil(S)):j==="{"?(V=g.scanUntil(N),g.scan(ea),g.scanUntil(S),j="&"):V=g.scanUntil(S),!g.scan(S))throw new Error("Unclosed tag at "+g.pos);if(j==">"?Ie=[j,V,q,g.pos,l,c,r]:Ie=[j,V,q,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 '+q);if(se[1]!==V)throw new Error('Unclosed section "'+se[1]+'" at '+q)}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 oa(na(o))}function na(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 oa(e){for(var t=[],r=t,n=[],o,i,s=0,a=e.length;s<a;++s)switch(o=e[s],o[0]){case"#":case"^":r.push(o),n.push(o),r=o[4]=[];break;case"/":i=n.pop(),i[5]=o[2],r=n.length>0?n[n.length-1][4]:t;break;default:r.push(o)}return t}function Ze(e){this.string=e,this.tail=e,this.pos=0}Ze.prototype.eos=function(){return this.tail===""};Ze.prototype.scan=function(t){var r=this.tail.match(t);if(!r||r.index!==0)return"";var n=r[0];return this.tail=this.tail.substring(n.length),this.pos+=n.length,n};Ze.prototype.scanUntil=function(t){var r=this.tail.search(t),n;switch(r){case-1:n=this.tail,this.tail="";break;case 0:n="";break;default:n=this.tail.substring(0,r),this.tail=this.tail.substring(r)}return this.pos+=n.length,n};function $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=kn(i,s[a])||qs(i,s[a])),i=i[s[a++]];else i=o.view[t],l=kn(o.view,t);if(l){n=i;break}o=o.parent}r[t]=n}return fr(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=ra(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(S){return s.render(S,r,n,i)}if(l){if(je(l))for(var p=0,m=l.length;p<m;++p)a+=this.renderTokens(t[4],r.push(l[p]),n,o,i);else if(typeof l=="object"||typeof l=="string"||typeof l=="number")a+=this.renderTokens(t[4],r.push(l),n,o,i);else if(fr(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(`
7
+ Values:
8
+ `+String(n)));Or(t);for(var o=0;o<t.callbacks.length;o++){var i=n[o];i instanceof Error?t.callbacks[o].reject(i):t.callbacks[o].resolve(i)}}).catch(function(n){Nr(e,t,n)})}function Nr(e,t,r){Or(t);for(var n=0;n<t.keys.length;n++)e.clear(t.keys[n]),t.callbacks[n].reject(r)}function Or(e){if(e.cacheHits)for(var t=0;t<e.cacheHits.length;t++)e.cacheHits[t]()}function El(e){var t=!e||e.batch!==!1;if(!t)return 1;var r=e&&e.maxBatchSize;if(r===void 0)return 1/0;if(typeof r!="number"||r<1)throw new TypeError("maxBatchSize must be a positive number: "+r);return r}function Cl(e){var t=e&&e.batchScheduleFn;if(t===void 0)return Rl;if(typeof t!="function")throw new TypeError("batchScheduleFn must be a function: "+t);return t}function Tl(e){var t=e&&e.cacheKeyFn;if(t===void 0)return function(r){return r};if(typeof t!="function")throw new TypeError("cacheKeyFn must be a function: "+t);return t}function Al(e){var t=!e||e.cache!==!1;if(!t)return null;var r=e&&e.cacheMap;if(r===void 0)return new Map;if(r!==null){var n=["get","set","delete","clear"],o=n.filter(function(i){return r&&typeof r[i]!="function"});if(o.length!==0)throw new TypeError("Custom cacheMap missing methods: "+o.join(", "))}return r}function Il(e){return e&&e.name?e.name:null}function uo(e){return typeof e=="object"&&e!==null&&typeof e.length=="number"&&(e.length===0||e.length>0&&Object.prototype.hasOwnProperty.call(e,e.length-1))}po.exports=kl});import{execFileSync as ca}from"child_process";import ua from"fs";import vt from"path";function yr(e){let t=pa(e);return t??On(e)}function On(e){let t=vt.dirname(e);return da(vt.join(e,".ripplo"))?e:t===e?null:On(t)}function da(e){try{return ua.statSync(e).isDirectory()}catch{return!1}}function pa(e){let t=ma(["rev-parse","--show-toplevel"],e);if(t==null)return null;let r=t.trim();return r.length===0?null:vt.isAbsolute(r)?r:vt.resolve(e,r)}function ma(e,t){try{return ca("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return null}}import La from"path";import{AsyncLocalStorage as fa}from"async_hooks";import ga from"path";var ya=new fa;function Dn(){let e=ya.getStore();return e!=null?e.fixturesDir:ga.join(process.cwd(),".ripplo","fixtures")}async function ye(e,t,r){let n,o=new Promise((i,s)=>{n=setTimeout(()=>{s(new Error(`${r} timed out after ${String(t)}ms`))},t)});try{return await Promise.race([e,o])}finally{n!=null&&clearTimeout(n)}}var ha=5e3;async function St({fn:e,label:t,page:r,timeoutMs:n}){let o=n??ha,i=await ye(r.context().newCDPSession(r),o,`${t} (newCDPSession)`);try{return await ye(e(i),o,t)}finally{await i.detach().catch(()=>{})}}async function J({awaitPromise:e,expression:t,label:r,page:n,timeoutMs:o}){return St({label:r??"evaluateViaCdp",page:n,timeoutMs:o,fn:async i=>{let s=await i.send("Runtime.evaluate",{awaitPromise:e,expression:t,returnByValue:!0});if(s.exceptionDetails==null)return s.result.value}})}var wa=Object.prototype.toString,Oe=Array.isArray||function(t){return wa.call(t)==="[object Array]"};function wr(e){return typeof e=="function"}function ba(e){return Oe(e)?"array":typeof e}function hr(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Ln(e,t){return e!=null&&typeof e=="object"&&t in e}function va(e,t){return e!=null&&typeof e!="object"&&e.hasOwnProperty&&e.hasOwnProperty(t)}var Sa=RegExp.prototype.test;function ka(e,t){return Sa.call(e,t)}var Ra=/\S/;function Pa(e){return!ka(Ra,e)}var xa={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function Ea(e){return String(e).replace(/[&<>"'`=\/]/g,function(r){return xa[r]})}var Ca=/\s*/,Ta=/\s+/,_n=/\s*=/,Aa=/\s*\}/,Ia=/#|\^|\/|>|\{|&|=|!/;function $a(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,h,T;function $(L){if(typeof L=="string"&&(L=L.split(Ta,2)),!Oe(L)||L.length!==2)throw new Error("Invalid tags: "+L);m=new RegExp(hr(L[0])+"\\s*"),h=new RegExp("\\s*"+hr(L[1])),T=new RegExp("\\s*"+hr("}"+L[1]))}$(t||te.tags);for(var g=new rt(e),H,x,F,Ae,j,W;!g.eos();){if(H=g.pos,F=g.scanUntil(m),F)for(var ge=0,dr=F.length;ge<dr;++ge)Ae=F.charAt(ge),Pa(Ae)?(i.push(o.length),l+=Ae):(a=!0,r=!0,l+=" "),o.push(["text",Ae,H,H+1]),H+=1,Ae===`
9
+ `&&(p(),l="",c=0,r=!1);if(!g.scan(m))break;if(s=!0,x=g.scan(Ia)||"name",g.scan(Ca),x==="="?(F=g.scanUntil(_n),g.scan(_n),g.scanUntil(h)):x==="{"?(F=g.scanUntil(T),g.scan(Aa),g.scanUntil(h),x="&"):F=g.scanUntil(h),!g.scan(h))throw new Error("Unclosed tag at "+g.pos);if(x==">"?j=[x,F,H,g.pos,l,c,r]:j=[x,F,H,g.pos],c++,o.push(j),x==="#"||x==="^")n.push(j);else if(x==="/"){if(W=n.pop(),!W)throw new Error('Unopened section "'+F+'" at '+H);if(W[1]!==F)throw new Error('Unclosed section "'+W[1]+'" at '+H)}else x==="name"||x==="{"||x==="&"?a=!0:x==="="&&$(F)}if(p(),W=n.pop(),W)throw new Error('Unclosed section "'+W[1]+'" at '+g.pos);return Na(ja(o))}function ja(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 Na(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 rt(e){this.string=e,this.tail=e,this.pos=0}rt.prototype.eos=function(){return this.tail===""};rt.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};rt.prototype.scanUntil=function(t){var r=this.tail.search(t),n;switch(r){case-1:n=this.tail,this.tail="";break;case 0:n="";break;default:n=this.tail.substring(0,r),this.tail=this.tail.substring(r)}return this.pos+=n.length,n};function Ne(e,t){this.view=e,this.cache={".":this.view},this.parent=t}Ne.prototype.push=function(t){return new Ne(t,this)};Ne.prototype.lookup=function(t){var r=this.cache,n;if(r.hasOwnProperty(t))n=r[t];else{for(var o=this,i,s,a,l=!1;o;){if(t.indexOf(".")>0)for(i=o.view,s=t.split("."),a=0;i!=null&&a<s.length;)a===s.length-1&&(l=Ln(i,s[a])||va(i,s[a])),i=i[s[a++]];else i=o.view[t],l=Ln(o.view,t);if(l){n=i;break}o=o.parent}r[t]=n}return wr(n)&&(n=n.call(this.view)),n};function G(){this.templateCache={_cache:{},set:function(t,r){this._cache[t]=r},get:function(t){return this._cache[t]},clear:function(){this._cache={}}}}G.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};G.prototype.parse=function(t,r){var n=this.templateCache,o=t+":"+(r||te.tags).join(":"),i=typeof n<"u",s=i?n.get(o):void 0;return s==null&&(s=$a(t,r),i&&n.set(o,s)),s};G.prototype.render=function(t,r,n,o){var i=this.getConfigTags(o),s=this.parse(t,i),a=r instanceof Ne?r:new Ne(r,void 0);return this.renderTokens(s,a,n,t,o)};G.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};G.prototype.renderSection=function(t,r,n,o,i){var s=this,a="",l=r.lookup(t[1]);function c(h){return s.render(h,r,n,i)}if(l){if(Oe(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(wr(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}};G.prototype.renderInverted=function(t,r,n,o,i){var s=r.lookup(t[1]);if(!s||Oe(s)&&s.length===0)return this.renderTokens(t[4],r,n,o,i)};G.prototype.indentPartial=function(t,r,n){for(var o=r.replace(/[^ \t]/g,""),i=t.split(`
14
10
  `),s=0;s<i.length;s++)i[s].length&&(s>0||!n)&&(i[s]=o+i[s]);return i.join(`
15
- `)};B.prototype.renderPartial=function(t,r,n,o){if(n){var i=this.getConfigTags(o),s=fr(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){Qe.templateCache=e},get templateCache(){return Qe.templateCache}},Qe=new B;Z.clearCache=function(){return Qe.clearCache()};Z.parse=function(t,r){return Qe.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 "'+Ws(t)+'" was given as the first argument for mustache#render(template, view, partials)');return Qe.render(t,r,n,o)};Z.escape=Xs;Z.Scanner=Ze;Z.Context=$e;Z.Writer=B;var Pn=Z;function gr({defs:e}){return e==null?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,sa({def:r,name:t})]))}var ia={boolean:!1,number:0,string:""};function sa({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??ia[e.type]??""}function vt({ref:e,variables:t}){if(e.type==="static")return e.value;let r=t[e.name];if(r==null||typeof r=="object")throw new Error(`Variable "${e.name}" is not defined`);return r}function K({ref:e,variables:t}){let r=String(vt({ref:e,variables:t}));return kt({raw:r,variables:t})}function St({ref:e,variables:t}){let r=vt({ref:e,variables:t});return typeof r=="string"?kt({raw:r,variables:t}):r}function kt({raw:e,variables:t}){return Pn.render(e,t,{},{escape:r=>r})}function yr({ref:e,variables:t}){let r=vt({ref:e,variables:t});if(typeof r=="number")return r;let n=Number(r);if(Number.isNaN(n))throw new TypeError(`Cannot convert "${String(r)}" to number`);return n}function 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(xn(e.value,r));case"role":return t.getByRole(e.role,{exact:!0,name:e.name==null?void 0:xn(e.name,r)})}}function xn(e,t){return t==null?e:kt({raw:e,variables:t})}async function En({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 Cn({node:e,page:t,timeout:r}){await D({locator:e.locator,page:t,variables:void 0}).click({button:"right",timeout:r})}function An({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 In({node:e,page:t,variables:r}){if(e.action==="write"){if(e.value==null)throw new Error("clipboard write requires a value");let o=K({ref:e.value,variables:r}),i=JSON.stringify(o);return await G({awaitPromise:!0,expression:`navigator.clipboard.writeText(${i})`,page:t}),{variables:r}}if(e.variable==null)throw new Error("clipboard read requires a variable name to store the result");let n=await G({awaitPromise:!0,expression:"navigator.clipboard.readText()",page:t})??"";return{variables:Ne({name:e.variable,store:r,value:n})}}async function Tn({node:e,page:t}){let r=t.context();e.state==="granted"?await r.grantPermissions([e.permission]):await r.clearPermissions()}async function hr({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 ca({node:e,page:t,timeout:r,variables:n});case"rightClick":return await Cn({node:e,page:t,timeout:r}),{variables:n};case"goto":{let o=K({ref:e.url,variables:n});return await t.goto(o,{timeout:r,waitUntil:"domcontentloaded"}),await t.waitForLoadState("load",{timeout:r}),await t.waitForFunction("document.body != null && document.body.childElementCount > 0 && (document.body.textContent?.trim().length ?? 0) > 0",void 0,{timeout:r}),await G({awaitPromise:!0,expression:"new Promise((resolve) => { requestAnimationFrame(() => requestAnimationFrame(() => resolve(undefined))); })",page:t}),{variables:n}}case"fill":return ua({node:e,page:t,timeout:r,variables:n});case"select":return pa({node:e,page:t,timeout:r,variables:n});case"type":return ma({node:e,page:t,timeout:r,variables:n});case"press":return await da({node:e,page:t,timeout:r}),{variables:n};case"drag":return await En({node:e,page:t,timeout:r}),{variables:n};case"upload":return fa({node:e,page:t,timeout:r,variables:n});case"extractText":return ya({node:e,page:t,timeout:r,variables:n});case"setVariable":{let o=St({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 An({node:e,page:t,variables:n});case"clipboard":return In({node:e,page:t,variables:n});case"setPermission":return await Tn({node:e,page:t}),{variables:n}}}var la={check:"check",clear:"clear",click:"click",dblclick:"dblclick",focus:"focus",hover:"hover",scrollIntoView:"scrollIntoViewIfNeeded",uncheck:"uncheck"};async function ca({node:e,page:t,timeout:r,variables:n}){return await D({locator:e.locator,page:t,variables:n})[la[e.type]]({timeout:r}),{variables:n}}async function da({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 ua({node:e,page:t,timeout:r,variables:n}){let o=K({ref:e.value,variables:n});return await D({locator:e.locator,page:t,variables:n}).fill(o,{timeout:r}),{variables:n}}async function pa({node:e,page:t,timeout:r,variables:n}){let o=K({ref:e.value,variables:n});return await D({locator:e.locator,page:t,variables:n}).selectOption(o,{timeout:r}),{variables:n}}async function ma({node:e,page:t,timeout:r,variables:n}){let o=K({ref:e.value,variables:n});return await D({locator:e.locator,page:t,variables:n}).pressSequentially(o,{timeout:r}),{variables:n}}async function fa({node:e,page:t,timeout:r,variables:n}){let o=e.files.map(i=>ga(i));return await D({locator:e.locator,page:t,variables:n}).setInputFiles(o,{timeout:r}),{variables:n}}function ga(e){return aa.join(Sn(),e)}async function ya({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={};Is(F,{default:()=>ha});or(F,Dh);import*as Dh from"playwright/test";import{default as ha}from"playwright/test";async function wr({expected:e,locator:t,operator:r,timeout:n}){await et({expected:e,operator:r,timeout:n,read:async()=>await t.textContent()??""});let o=await tt(async()=>await t.textContent()??"");return Oe({actual:o,expected:e,label:"Text",operator:r})}async function br({expected:e,operator:t,page:r,timeout:n}){return await et({expected:e,operator:t,timeout:n,read:()=>Promise.resolve(r.url())}),Oe({actual:r.url(),expected:e,label:"URL",operator:t})}async function $n({expected:e,operator:t,page:r,timeout:n}){await et({expected:e,operator:t,timeout:n,read:()=>r.title()});let o=await tt(()=>r.title());return Oe({actual:o,expected:e,label:"Title",operator:t})}async function vr({expected:e,locator:t,operator:r,timeout:n}){await F.expect.poll(async()=>Hn({actual:await t.count(),expected:e,operator:r}),{timeout:n}).toBe(!0).catch(()=>{});let o=await t.count();return Fn({actual:o,expected:e,label:"Count",operator:r})}async function Sr({expected:e,locator:t,operator:r,timeout:n}){await et({expected:e,operator:r,timeout:n,read:()=>t.inputValue()});let o=await tt(()=>t.inputValue());return Oe({actual:o,expected:e,label:"Value",operator:r})}async function kr({locator:e,timeout:t}){return ye({description:"Element is visible",failureDetail:"Element not visible",run:()=>(0,F.expect)(e).toBeVisible({timeout:t})})}async function Rr({locator:e,timeout:t}){return ye({description:"Element is not visible",failureDetail:"Element still visible",run:()=>(0,F.expect)(e).toBeHidden({timeout:t})})}async function jn({attribute:e,expected:t,locator:r,operator:n,timeout:o}){await et({expected:t,operator:n,timeout:o,read:async()=>await r.getAttribute(e)??""});let i=await tt(async()=>await r.getAttribute(e)??"");return Oe({actual:i,expected:t,label:`Attribute "${e}"`,operator:n})}async function Nn({locator:e,timeout:t}){return ye({description:"Element is enabled",failureDetail:"Element is disabled or not found",run:()=>(0,F.expect)(e).toBeEnabled({timeout:t})})}async function On({locator:e,timeout:t}){return ye({description:"Element is disabled",failureDetail:"Element is enabled or not found",run:()=>(0,F.expect)(e).toBeDisabled({timeout:t})})}async function Dn({locator:e,timeout:t}){return ye({description:"Element is checked",failureDetail:"Element is not checked",run:()=>(0,F.expect)(e).toBeChecked({timeout:t})})}async function Ln({locator:e,timeout:t}){return ye({description:"Element is not checked",failureDetail:"Element is checked",run:()=>(0,F.expect)(e).not.toBeChecked({timeout:t})})}async function _n({locator:e,timeout:t}){return ye({description:"Element is focused",failureDetail:"Element is not focused",run:()=>(0,F.expect)(e).toBeFocused({timeout:t})})}async function Un({locator:e,timeout:t}){return ye({description:"Element is not focused",failureDetail:"Element is focused",run:()=>(0,F.expect)(e).not.toBeFocused({timeout:t})})}async function ye({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 et({expected:e,operator:t,read:r,timeout:n}){await F.expect.poll(async()=>{let o=await tt(r);return Vn({actual:o,expected:e,operator:t})},{timeout:n}).toBe(!0).catch(()=>{})}async function tt(e){return e().catch(()=>"")}function Oe(e){let t=`${e.label} ${e.operator} "${e.expected}"`,r=Vn(e),n=r?void 0:`Got: "${e.actual}"`;return{description:t,detail:n,status:r?"passed":"failed"}}function Vn({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 Fn(e){let t=`${e.label} ${e.operator} ${String(e.expected)}`,r=Hn(e),n=r?void 0:`Got: ${String(e.actual)}`;return{description:t,detail:n,status:r?"passed":"failed"}}function Hn({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 ba}from"child_process";import{createRequire as va}from"module";import Mn from"fs";import Bn from"path";import{chromium as Wn}from"playwright";import Fh from"fs";import Mh from"path";import wa from"pino";var y=wa({transport:{options:{ignore:"pid,hostname"},target:"pino-pretty"}});async function rt({headed:e}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";try{return await Wn.launch({headless:!e})}catch(t){throw Sa(t)?new Error(`Playwright browsers are not installed. Run:
11
+ `)};G.prototype.renderPartial=function(t,r,n,o){if(n){var i=this.getConfigTags(o),s=wr(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)}}};G.prototype.unescapedValue=function(t,r){var n=r.lookup(t[1]);if(n!=null)return n};G.prototype.escapedValue=function(t,r,n){var o=this.getConfigEscape(n)||te.escape,i=r.lookup(t[1]);if(i!=null)return typeof i=="number"&&o===te.escape?String(i):o(i)};G.prototype.rawValue=function(t){return t[1]};G.prototype.getConfigTags=function(t){return Oe(t)?t:t&&typeof t=="object"?t.tags:void 0};G.prototype.getConfigEscape=function(t){if(t&&typeof t=="object"&&!Oe(t))return t.escape};var te={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){tt.templateCache=e},get templateCache(){return tt.templateCache}},tt=new G;te.clearCache=function(){return tt.clearCache()};te.parse=function(t,r){return tt.parse(t,r)};te.render=function(t,r,n,o){if(typeof t!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+ba(t)+'" was given as the first argument for mustache#render(template, view, partials)');return tt.render(t,r,n,o)};te.escape=Ea;te.Scanner=rt;te.Context=Ne;te.Writer=G;var Un=te;function br({defs:e}){return e==null?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Da({def:r,name:t})]))}var Oa={boolean:!1,number:0,string:""};function Da({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??Oa[e.type]??""}function kt({ref:e,variables:t}){if(e.type==="static")return e.value;let r=t[e.name];if(r==null||typeof r=="object")throw new Error(`Variable "${e.name}" is not defined`);return r}function Y({ref:e,variables:t}){let r=String(kt({ref:e,variables:t}));return Pt({raw:r,variables:t})}function Rt({ref:e,variables:t}){let r=kt({ref:e,variables:t});return typeof r=="string"?Pt({raw:r,variables:t}):r}function Pt({raw:e,variables:t}){return Un.render(e,t,{},{escape:r=>r})}function vr({ref:e,variables:t}){let r=kt({ref:e,variables:t});if(typeof r=="number")return r;let n=Number(r);if(Number.isNaN(n))throw new TypeError(`Cannot convert "${String(r)}" to number`);return n}function De({name:e,store:t,value:r}){return{...t,[e]:r}}function U({locator:e,page:t,variables:r}){switch(e.by){case"testId":return t.getByTestId(Vn(e.value,r));case"role":return t.getByRole(e.role,{exact:!0,name:e.name==null?void 0:Vn(e.name,r)})}}function Vn(e,t){return t==null?e:Pt({raw:e,variables:t})}async function Fn({node:e,page:t,timeout:r}){await U({locator:e.source,page:t,variables:void 0}).dragTo(U({locator:e.target,page:t,variables:void 0}),{timeout:r})}async function Mn({node:e,page:t,timeout:r}){await U({locator:e.locator,page:t,variables:void 0}).click({button:"right",timeout:r})}function Bn({node:e,page:t,variables:r}){return t.once("dialog",async n=>{e.action==="accept"?await n.accept(e.promptText??void 0):await n.dismiss()}),{variables:r}}async function Hn({node:e,page:t,variables:r}){if(e.action==="write"){if(e.value==null)throw new Error("clipboard write requires a value");let o=Y({ref:e.value,variables:r}),i=JSON.stringify(o);return await J({awaitPromise:!0,expression:`navigator.clipboard.writeText(${i})`,label:"clipboard.writeText",page:t,timeoutMs:void 0}),{variables:r}}if(e.variable==null)throw new Error("clipboard read requires a variable name to store the result");let n=await J({awaitPromise:!0,expression:"navigator.clipboard.readText()",label:"clipboard.readText",page:t,timeoutMs:void 0})??"";return{variables:De({name:e.variable,store:r,value:n})}}async function Wn({node:e,page:t}){let r=t.context();e.state==="granted"?await r.grantPermissions([e.permission]):await r.clearPermissions()}async function Sr({node:e,page:t,timeout:r,variables:n}){switch(e.type){case"click":return await U({locator:e.locator,page:t,variables:n}).click({modifiers:e.modifier==null?void 0:[e.modifier],timeout:r}),{variables:n};case"check":case"uncheck":case"clear":case"dblclick":case"focus":case"hover":case"scrollIntoView":return Ua({node:e,page:t,timeout:r,variables:n});case"rightClick":return await Mn({node:e,page:t,timeout:r}),{variables:n};case"goto":{let o=Y({ref:e.url,variables:n});return await t.goto(o,{timeout:r,waitUntil:"domcontentloaded"}),await t.waitForLoadState("load",{timeout:r}),await t.waitForFunction("document.body != null && document.body.childElementCount > 0 && (document.body.textContent?.trim().length ?? 0) > 0",void 0,{timeout:r}),await J({awaitPromise:!0,expression:"new Promise((resolve) => { requestAnimationFrame(() => requestAnimationFrame(() => resolve(undefined))); })",label:"goto raf-settle",page:t,timeoutMs:void 0}),{variables:n}}case"fill":return Fa({node:e,page:t,timeout:r,variables:n});case"select":return Ma({node:e,page:t,timeout:r,variables:n});case"type":return Ba({node:e,page:t,timeout:r,variables:n});case"press":return await Va({node:e,page:t,timeout:r}),{variables:n};case"drag":return await Fn({node:e,page:t,timeout:r}),{variables:n};case"upload":return Ha({node:e,page:t,timeout:r,variables:n});case"extractText":return qa({node:e,page:t,timeout:r,variables:n});case"setVariable":{let o=Rt({ref:e.value,variables:n});return{variables:De({name:e.variable,store:n,value:o})}}case"fail":throw new Error(e.message);case"setViewport":return await t.setViewportSize({height:e.height,width:e.width}),{variables:n};case"handleDialog":return Bn({node:e,page:t,variables:n});case"clipboard":return Hn({node:e,page:t,variables:n});case"setPermission":return await Wn({node:e,page:t}),{variables:n}}}var _a={check:"check",clear:"clear",click:"click",dblclick:"dblclick",focus:"focus",hover:"hover",scrollIntoView:"scrollIntoViewIfNeeded",uncheck:"uncheck"};async function Ua({node:e,page:t,timeout:r,variables:n}){return await U({locator:e.locator,page:t,variables:n})[_a[e.type]]({timeout:r}),{variables:n}}async function Va({node:e,page:t,timeout:r}){e.locator==null?await t.keyboard.press(e.key):await U({locator:e.locator,page:t,variables:void 0}).press(e.key,{timeout:r})}async function Fa({node:e,page:t,timeout:r,variables:n}){let o=Y({ref:e.value,variables:n});return await U({locator:e.locator,page:t,variables:n}).fill(o,{timeout:r}),{variables:n}}async function Ma({node:e,page:t,timeout:r,variables:n}){let o=Y({ref:e.value,variables:n});return await U({locator:e.locator,page:t,variables:n}).selectOption(o,{timeout:r}),{variables:n}}async function Ba({node:e,page:t,timeout:r,variables:n}){let o=Y({ref:e.value,variables:n});return await U({locator:e.locator,page:t,variables:n}).pressSequentially(o,{timeout:r}),{variables:n}}async function Ha({node:e,page:t,timeout:r,variables:n}){let o=e.files.map(i=>Wa(i));return await U({locator:e.locator,page:t,variables:n}).setInputFiles(o,{timeout:r}),{variables:n}}function Wa(e){return La.join(Dn(),e)}async function qa({node:e,page:t,timeout:r,variables:n}){let o=await U({locator:e.locator,page:t,variables:n}).textContent({timeout:r});if(o==null)throw new Error("extractText: element had no text content");return{variables:De({name:e.variable,store:n,value:o})}}var q={};la(q,{default:()=>za});fr(q,qw);import*as qw from"playwright/test";import{default as za}from"playwright/test";async function kr({expected:e,locator:t,operator:r,timeout:n}){return await nt({expected:e,operator:r,timeout:n,read:async()=>await t.textContent()??""}),ot({expected:e,label:"Text",operator:r,read:async()=>await t.textContent()??""})}async function Rr({expected:e,operator:t,page:r,timeout:n}){return await nt({expected:e,operator:t,timeout:n,read:()=>Promise.resolve(r.url())}),ot({expected:e,label:"URL",operator:t,read:()=>Promise.resolve(r.url())})}async function qn({expected:e,operator:t,page:r,timeout:n}){return await nt({expected:e,operator:t,timeout:n,read:()=>r.title()}),ot({expected:e,label:"Title",operator:t,read:()=>r.title()})}async function Pr({expected:e,locator:t,operator:r,timeout:n}){await q.expect.poll(async()=>ro({actual:await t.count(),expected:e,operator:r}),{timeout:n}).toBe(!0).catch(()=>{});let o=await t.count();return to({actual:o,expected:e,label:"Count",operator:r})}async function xr({expected:e,locator:t,operator:r,timeout:n}){return await nt({expected:e,operator:r,timeout:n,read:()=>t.inputValue()}),ot({expected:e,label:"Value",operator:r,read:()=>t.inputValue()})}async function Er({locator:e,timeout:t}){return he({description:"Element is visible",failureDetail:"Element not visible",run:()=>(0,q.expect)(e).toBeVisible({timeout:t})})}async function Cr({locator:e,timeout:t}){return he({description:"Element is not visible",failureDetail:"Element still visible",run:()=>(0,q.expect)(e).toBeHidden({timeout:t})})}async function zn({attribute:e,expected:t,locator:r,operator:n,timeout:o}){return await nt({expected:t,operator:n,timeout:o,read:async()=>await r.getAttribute(e)??""}),ot({expected:t,label:`Attribute "${e}"`,operator:n,read:async()=>await r.getAttribute(e)??""})}async function Gn({locator:e,timeout:t}){return he({description:"Element is enabled",failureDetail:"Element is disabled or not found",run:()=>(0,q.expect)(e).toBeEnabled({timeout:t})})}async function Kn({locator:e,timeout:t}){return he({description:"Element is disabled",failureDetail:"Element is enabled or not found",run:()=>(0,q.expect)(e).toBeDisabled({timeout:t})})}async function Jn({locator:e,timeout:t}){return he({description:"Element is checked",failureDetail:"Element is not checked",run:()=>(0,q.expect)(e).toBeChecked({timeout:t})})}async function Yn({locator:e,timeout:t}){return he({description:"Element is not checked",failureDetail:"Element is checked",run:()=>(0,q.expect)(e).not.toBeChecked({timeout:t})})}async function Xn({locator:e,timeout:t}){return he({description:"Element is focused",failureDetail:"Element is not focused",run:()=>(0,q.expect)(e).toBeFocused({timeout:t})})}async function Qn({locator:e,timeout:t}){return he({description:"Element is not focused",failureDetail:"Element is focused",run:()=>(0,q.expect)(e).not.toBeFocused({timeout:t})})}async function he({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 nt({expected:e,operator:t,read:r,timeout:n}){await q.expect.poll(async()=>{let o=await r().catch(()=>"");return eo({actual:o,expected:e,operator:t})},{timeout:n}).toBe(!0).catch(()=>{})}async function ot({expected:e,label:t,operator:r,read:n}){try{let o=await n();return Zn({actual:o,expected:e,label:t,operator:r})}catch(o){let i=`${t} ${r} "${e}"`,s=o instanceof Error?o.message:String(o);return{description:i,detail:`Read failed: ${Ga(s)}`,status:"failed"}}}function Ga(e){let t=e.indexOf(`
12
+ `);return t===-1?e:e.slice(0,t)}function Zn(e){let t=`${e.label} ${e.operator} "${e.expected}"`,r=eo(e),n=r?void 0:`Got: "${e.actual}"`;return{description:t,detail:n,status:r?"passed":"failed"}}function eo({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 to(e){let t=`${e.label} ${e.operator} ${String(e.expected)}`,r=ro(e),n=r?void 0:`Got: ${String(e.actual)}`;return{description:t,detail:n,status:r?"passed":"failed"}}function ro({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 Ja}from"child_process";import{createRequire as Ya}from"module";import no from"fs";import oo from"path";import{chromium as io}from"playwright";import Yw from"fs";import Qw from"path";import Ka from"pino";var f=Ka({level:process.env.LOG_LEVEL??"info",transport:{options:{ignore:"pid,hostname"},target:"pino-pretty"}});async function Le({headed:e}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";try{return await io.launch({headless:!e})}catch(t){throw Xa(t)?new Error(`Playwright browsers are not installed. Run:
16
13
 
17
14
  npx playwright install chromium
18
- `):t}}async function Pr(){let e=Wn.executablePath();if(Mn.existsSync(e))return;y.info("Chromium not found. Installing via Playwright...");let t=va(import.meta.url),r=Bn.dirname(t.resolve("playwright/package.json")),n=Bn.join(r,"cli.js");if(await new Promise((o,i)=>{ba(process.execPath,[n,"install","chromium"],s=>{if(s!=null){i(new Error(`Playwright install failed: ${s.message}`));return}o()})}),!Mn.existsSync(e))throw new Error(`Playwright browser installation failed. Try running manually:
15
+ `):t}}async function Tr(){let e=io.executablePath();if(no.existsSync(e))return;f.info("Chromium not found. Installing via Playwright...");let t=Ya(import.meta.url),r=oo.dirname(t.resolve("playwright/package.json")),n=oo.join(r,"cli.js");if(await new Promise((o,i)=>{Ja(process.execPath,[n,"install","chromium"],s=>{if(s!=null){i(new Error(`Playwright install failed: ${s.message}`));return}o()})}),!no.existsSync(e))throw new Error(`Playwright browser installation failed. Try running manually:
19
16
 
20
17
  npx playwright install chromium
21
- `);y.info("\u2713 Chromium installed")}function Sa(e){return e instanceof Error?e.message.includes("Executable doesn't exist"):!1}import{readdir as Ca,rm as Aa,stat as Ia}from"fs/promises";import rw from"os";import Gn from"path";import{graphql as Ta}from"gql.tada";import{print as ka}from"graphql";var Ra=15e3,De=class extends Error{errors;constructor(t){super(t.map(r=>r.message).join(", ")),this.name="GqlRequestError",this.errors=t}};async function f(e){let t=ka(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(Ra)})}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 Pa({res:o,url:n});if(!xa(i))throw new Error("Invalid GraphQL response");if(Ea(i))throw new De(i.errors);if(i.data==null)throw new Error("No data returned from server");return i.data}async function Pa({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 xa(e){return typeof e=="object"&&e!=null&&("data"in e||"errors"in e)}function Ea(e){return Array.isArray(e.errors)&&e.errors.length>0}var qn=Gn.join(process.cwd(),".ripplo","debug"),zn=360*60*1e3,aw=Ta(`
18
+ `);f.info("\u2713 Chromium installed")}function Xa(e){return e instanceof Error?e.message.includes("Executable doesn't exist"):!1}import{readdir as nl,rm as ol,stat as il}from"fs/promises";import pb from"os";import lo from"path";import{graphql as sl}from"gql.tada";import{print as Qa}from"graphql";var Za=15e3,_e=class extends Error{errors;constructor(t){super(t.map(r=>r.message).join(", ")),this.name="GqlRequestError",this.errors=t}};async function y(e){let t=Qa(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(Za)})}catch(s){let a=s instanceof Error?s.message:String(s);throw new Error(`Failed to connect to Ripplo server at ${e.config.ripploServerUrl}. Check the server is running and reachable. Details: ${a}`)}let i=await el({res:o,url:n});if(!tl(i))throw new Error("Invalid GraphQL response");if(rl(i))throw new _e(i.errors);if(i.data==null)throw new Error("No data returned from server");return i.data}async function el({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 tl(e){return typeof e=="object"&&e!=null&&("data"in e||"errors"in e)}function rl(e){return Array.isArray(e.errors)&&e.errors.length>0}var so=lo.join(process.cwd(),".ripplo","debug"),ao=360*60*1e3,hb=sl(`
22
19
  mutation RevokeCurrentCliToken {
23
20
  revokeCurrentCliToken
24
21
  }
25
- `);async function xr({maxRuns:e}){try{let r=(await Ca(qn,{withFileTypes:!0})).filter(c=>c.isDirectory()),n=Date.now(),o=await Promise.all(r.map(async c=>{let p=Gn.join(qn,c.name),m=await Ia(p);return{dirPath:p,mtime:m.mtimeMs}})),i=o.filter(c=>n-c.mtime>zn),a=o.filter(c=>n-c.mtime<=zn).toSorted((c,p)=>p.mtime-c.mtime).slice(e),l=[...i,...a];if(l.length===0)return;await Promise.allSettled(l.map(c=>Aa(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 $a=5e3,ja=2,Na=250;async function Er({appUrl:e}){let t=null,r=0;for(;r<=ja;){r>0&&await Da(Na);let o=await Oa(e,r);if(o==null)return;t=o,r+=1}let n=t instanceof Error?t.message:String(t);throw y.debug("App URL unreachable after retries: %s",n),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
- `))}async function Oa(e,t){try{return await fetch(e,{method:"HEAD",signal:AbortSignal.timeout($a)}),null}catch(r){return y.debug("App URL reachability check attempt %d failed: %s",t+1,r instanceof Error?r.message:String(r)),r}}function Da(e){return new Promise(t=>setTimeout(t,e))}import{z as Hc}from"zod";import{z as Rt}from"zod";var La=Rt.object({__codec:Rt.string().min(1),data:Rt.unknown(),version:Rt.number().int().positive()}),Pt=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}},xt=class extends Error{constructor(t){super(`Codec mismatch: expected "${t.expected}", got "${t.got}"`),this.name="CodecMismatchError"}};function Et(e){return Kn({legacy:void 0,migrators:[],name:e,schemas:[]})}function Kn(e){return{initial:t=>Cr(t,{...e,schemas:[t]}),legacy:t=>Kn({...e,legacy:t})}}function Cr(e,t){return{build:()=>_a(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 _a(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>Ua(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function Ua(e,t,r){let{data:n,version:o}=Va(t,r),i=Jn(t,n,o);return e.parse(i)}function Va(e,t){let r=La.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new xt({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 Jn(e,t,r){let n=e.schemas.length;if(r>n)throw new Pt({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 Jn(e,s(i),r+1)}import{z as Zn}from"zod";import{z as Le}from"zod";var Ar=Le.object({depends:Le.array(Le.string().min(1)).optional().describe("Names of other preconditions that must be satisfied first. Resolved via topological sort; cycles are rejected at validation time."),description:Le.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:Le.array(Le.string().min(1)).optional().describe("Keys that the execute response's data field will contain. e.g. ['projectId', 'workflowId']. These are used for route param interpolation ({{projectId}}) and workflow variables. Declared here so generated types are strongly typed per precondition.")}).describe("A named precondition declared at the graph level. States reference these by name.");import{z as d}from"zod";import{z as he}from"zod";var Fa=he.object({by:he.literal("testId"),value:he.string().min(1)}),Ha=he.object({by:he.literal("role"),name:he.string().optional(),role:he.string().min(1)}),R=he.discriminatedUnion("by",[Fa,Ha]);import{z as Yn}from"zod";var we=Yn.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),Ct=Yn.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]);import{z as I}from"zod";var Ma=I.object({type:I.literal("static"),value:I.union([I.string(),I.number(),I.boolean()])}),At=I.object({name:I.string().min(1),type:I.literal("variable")}),It=I.discriminatedUnion("type",[Ma,At]),J=I.discriminatedUnion("type",[I.object({type:I.literal("static"),value:I.string()}),At]),Tt=I.discriminatedUnion("type",[I.object({type:I.literal("static"),value:I.number().int().nonnegative()}),At]),Ir=I.discriminatedUnion("type",[I.object({type:I.literal("static"),value:I.union([I.string(),I.number(),I.boolean()])}),At]);import{z as Y}from"zod";var $t=Y.discriminatedUnion("type",[Y.object({default:Y.string().optional(),type:Y.literal("string")}),Y.object({default:Y.number().optional(),type:Y.literal("number")}),Y.object({default:Y.boolean().optional(),type:Y.literal("boolean")}),Y.object({key:Y.string().min(1),type:Y.literal("env")})]);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()},Xn=500,Ba=d.object({...b,type:d.literal("goto"),url:J}),Wa=d.object({...b,locator:R,type:d.literal("click")}),qa=d.object({...b,locator:R,type:d.literal("fill"),value:J}),za=d.object({...b,locator:R,type:d.literal("select"),value:J}),Ga=d.object({...b,locator:R,type:d.literal("hover")}),Ka=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")}),Ya=d.object({...b,locator:R,type:d.literal("uncheck")}),Xa=d.object({...b,height:d.number().int().positive(),type:d.literal("setViewport"),width:d.number().int().positive()}),Qa=d.object({...b,message:d.string().min(1),type:d.literal("fail")}),Za=d.object({...b,type:d.literal("setVariable"),value:It,variable:d.string().min(1)}),el=d.object({...b,locator:R,type:d.literal("extractText"),variable:d.string().min(1)}),tl=d.object({...b,files:d.array(d.string()).min(1),locator:R,type:d.literal("upload")}),rl=d.object({...b,locator:R,type:d.literal("dblclick")}),nl=d.object({...b,source:R,target:R,type:d.literal("drag")}),ol=d.object({...b,locator:R,type:d.literal("scrollIntoView")}),il=d.object({...b,locator:R,type:d.literal("type"),value:J}),sl=d.object({...b,locator:R,type:d.literal("focus")}),al=d.object({...b,locator:R,type:d.literal("clear")}),ll=d.object({...b,locator:R,type:d.literal("rightClick")}),cl=d.object({...b,action:d.enum(["accept","dismiss"]),promptText:d.string().optional(),type:d.literal("handleDialog")}),dl=d.object({...b,action:d.enum(["read","write"]),type:d.literal("clipboard"),value:J.optional(),variable:d.string().min(1).optional()}),ul=d.object({...b,permission:d.string().min(1),state:d.enum(["granted","prompt"]),type:d.literal("setPermission")}),pl=d.object({...b,locator:R,type:d.literal("assertVisible")}),ml=d.object({...b,locator:R,type:d.literal("assertNotVisible")}),fl=d.object({...b,expected:J,locator:R,operator:we,type:d.literal("assertText")}),gl=d.object({...b,expected:J,operator:we,type:d.literal("assertUrl")}),yl=d.object({...b,expected:Tt,locator:R,operator:Ct,type:d.literal("assertCount")}),hl=d.object({...b,expected:J,locator:R,operator:we,type:d.literal("assertValue")}),wl=d.object({...b,attribute:d.string().min(1),expected:J,locator:R,operator:we,type:d.literal("assertAttribute")}),bl=d.object({...b,locator:R,type:d.literal("assertEnabled")}),vl=d.object({...b,locator:R,type:d.literal("assertDisabled")}),Sl=d.object({...b,expected:J,operator:we,type:d.literal("assertTitle")}),kl=d.object({...b,locator:R,type:d.literal("assertChecked")}),Rl=d.object({...b,locator:R,type:d.literal("assertNotChecked")}),Pl=d.object({...b,locator:R,type:d.literal("assertFocused")}),xl=d.object({...b,locator:R,type:d.literal("assertNotFocused")}),El=d.object({...b,budget:d.enum(["fast","slow","async"]),observer:d.string().min(1).max(200),params:d.record(d.string().max(200),Ir),type:d.literal("assertObserver")}),Qn=d.discriminatedUnion("type",[Ba,Wa,qa,za,Ga,Ka,Ja,Ya,pl,ml,fl,gl,yl,hl,wl,bl,vl,Xa,Qa,Za,el,tl,rl,nl,ol,il,sl,al,ll,cl,dl,ul,Sl,kl,Rl,Pl,xl,El]),jt=d.object({entryNode:d.string().min(1).max(200),nodes:d.record(d.string().max(200),Qn).refine(e=>Object.keys(e).length<=Xn,`Workflow has more than ${String(Xn)} nodes`),uiOnly:d.boolean().optional(),variableNamespaces:d.record(d.string().max(200),d.string().max(500)).optional(),variables:d.record(d.string().max(200),$t).optional()});var Cl=Zn.record(Zn.string().max(200),Ar),Al={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},Il={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},Tr=Et("workflow-spec").legacy(Al).initial(jt).build(),Tl=Et("precondition-map").legacy(Il).initial(Cl).build();import{z as $r}from"zod";var eo=["fast","slow","async"],$l=$r.object({budget:$r.enum(eo).describe("Polling budget tier: fast | slow | async"),description:$r.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 po,readFragment as Mc}from"gql.tada";import{mkdir as jr,writeFile as te}from"fs/promises";import W from"path";import{z as ee}from"zod";async function ro({context:e,page:t,runId:r,stepIndex:n,stepResult:o}){try{let i=W.join(process.cwd(),".ripplo","debug",r,"steps",String(n));await jr(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([te(W.join(i,"info.json"),JSON.stringify(s,null,2)),Nl(Ol({context:e,page:t,stepDir:i}),jl,`capturePageState step ${String(n)}`)])}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)}}var jl=15e3;async function Nl(e,t,r){let n,o=new Promise((i,s)=>{n=setTimeout(()=>{s(new Error(`${r} timed out after ${String(t)}ms`))},t)});try{return await Promise.race([e,o])}finally{n!=null&&clearTimeout(n)}}async function Ol({context:e,page:t,stepDir:r}){let[n,o,i,s,a]=await Promise.all([_l(t),Fl(t),zl({context:e,page:t}),Wl(t),Ll(t)]);await Promise.all([te(W.join(r,"dom.html"),n),te(W.join(r,"accessibility-tree.full.json"),JSON.stringify(o,null,2)),te(W.join(r,"accessibility-tree.json"),Hl(o)),te(W.join(r,"storage.json"),JSON.stringify(i,null,2)),te(W.join(r,"rrweb-elements.ndjson"),a),s==null?Promise.resolve():te(W.join(r,"screenshot.png"),s)])}var Dl=`
22
+ `);async function xt({maxRuns:e}){try{let r=(await nl(so,{withFileTypes:!0})).filter(c=>c.isDirectory()),n=Date.now(),o=await Promise.all(r.map(async c=>{let p=lo.join(so,c.name),m=await il(p);return{dirPath:p,mtime:m.mtimeMs}})),i=o.filter(c=>n-c.mtime>ao),a=o.filter(c=>n-c.mtime<=ao).toSorted((c,p)=>p.mtime-c.mtime).slice(e),l=[...i,...a];if(l.length===0)return;await Promise.allSettled(l.map(c=>ol(c.dirPath,{force:!0,recursive:!0}))),f.debug("Pruned %d old debug run(s)",l.length)}catch{f.warn("Debug run pruning failed, ignoring")}}var al=15e3,ll=2,cl=250,ul=3e4,Ar=new Map;function Ir({appUrl:e}){let t=Date.now(),r=Ar.get(e);if(r!=null&&r.expiresAt>t)return r.promise;let n=dl(e).catch(o=>{throw Ar.delete(e),o});return Ar.set(e,{expiresAt:t+ul,promise:n}),n}async function dl(e){let t=null,r=0;for(;r<=ll;){r>0&&await ml(cl);let o=await pl(e,r);if(o==null)return;t=o,r+=1}let n=t instanceof Error?t.message:String(t);throw f.debug("App URL unreachable after retries: %s",n),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(`
23
+ `))}async function pl(e,t){let r=performance.now();try{return await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(al)}),f.debug("App URL reachability check ok (attempt %d, %dms)",t+1,Math.round(performance.now()-r)),null}catch(n){return f.debug("App URL reachability check attempt %d failed after %dms: %s",t+1,Math.round(performance.now()-r),n instanceof Error?n.message:String(n)),n}}function ml(e){return new Promise(t=>setTimeout(t,e))}import{Agent as fl,RetryAgent as gl,setGlobalDispatcher as yl}from"undici";var hl=1500,wl=4e3,bl=3,vl=50,Sl=100,co=!1;function $r(){if(co)return;co=!0;let e=new fl({connections:Sl,keepAliveMaxTimeout:wl,keepAliveTimeout:hl}),t=new gl(e,{errorCodes:["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT","UND_ERR_REQ_CONTENT_LENGTH_MISMATCH","UND_ERR_SOCKET"],maxRetries:bl,methods:["GET","POST","HEAD","OPTIONS","PUT","DELETE"],minTimeout:vl});yl(t)}var Oo=gr(Et(),1);import{z as zu}from"zod";import{z as Ct}from"zod";var $l=Ct.object({__codec:Ct.string().min(1),data:Ct.unknown(),version:Ct.number().int().positive()}),Tt=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}},At=class extends Error{constructor(t){super(`Codec mismatch: expected "${t.expected}", got "${t.got}"`),this.name="CodecMismatchError"}};function It(e){return mo({legacy:void 0,migrators:[],name:e,schemas:[]})}function mo(e){return{initial:t=>Dr(t,{...e,schemas:[t]}),legacy:t=>mo({...e,legacy:t})}}function Dr(e,t){return{build:()=>jl(e,t),legacy:r=>Dr(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return Dr(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function jl(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>Nl(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function Nl(e,t,r){let{data:n,version:o}=Ol(t,r),i=fo(t,n,o);return e.parse(i)}function Ol(e,t){let r=$l.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new At({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 fo(e,t,r){let n=e.schemas.length;if(r>n)throw new Tt({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 fo(e,s(i),r+1)}import{z as wo}from"zod";import{z as Ue}from"zod";var Lr=Ue.object({depends:Ue.array(Ue.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:Ue.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:Ue.array(Ue.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 u}from"zod";import{z as we}from"zod";var Dl=we.object({by:we.literal("testId"),value:we.string().min(1)}),Ll=we.object({by:we.literal("role"),name:we.string().optional(),role:we.string().min(1)}),R=we.discriminatedUnion("by",[Dl,Ll]);import{z as go}from"zod";var be=go.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),$t=go.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]);import{z as N}from"zod";var _l=N.object({type:N.literal("static"),value:N.union([N.string(),N.number(),N.boolean()])}),jt=N.object({name:N.string().min(1),type:N.literal("variable")}),Nt=N.discriminatedUnion("type",[_l,jt]),X=N.discriminatedUnion("type",[N.object({type:N.literal("static"),value:N.string()}),jt]),Ot=N.discriminatedUnion("type",[N.object({type:N.literal("static"),value:N.number().int().nonnegative()}),jt]),_r=N.discriminatedUnion("type",[N.object({type:N.literal("static"),value:N.union([N.string(),N.number(),N.boolean()])}),jt]);import{z as Q}from"zod";var Dt=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")})]);var v={id:u.string().min(1).max(200),label:u.string().max(500).optional(),next:u.string().max(200).optional(),uiOnly:u.boolean().optional()},yo=500,Ul=u.object({...v,type:u.literal("goto"),url:X}),Vl=u.object({...v,locator:R,modifier:u.enum(["Alt","Control","Meta","Shift"]).optional(),type:u.literal("click")}),Fl=u.object({...v,locator:R,type:u.literal("fill"),value:X}),Ml=u.object({...v,locator:R,type:u.literal("select"),value:X}),Bl=u.object({...v,locator:R,type:u.literal("hover")}),Hl=u.object({...v,key:u.string().min(1),locator:R.optional(),type:u.literal("press")}),Wl=u.object({...v,locator:R,type:u.literal("check")}),ql=u.object({...v,locator:R,type:u.literal("uncheck")}),zl=u.object({...v,height:u.number().int().positive(),type:u.literal("setViewport"),width:u.number().int().positive()}),Gl=u.object({...v,message:u.string().min(1),type:u.literal("fail")}),Kl=u.object({...v,type:u.literal("setVariable"),value:Nt,variable:u.string().min(1)}),Jl=u.object({...v,locator:R,type:u.literal("extractText"),variable:u.string().min(1)}),Yl=u.object({...v,files:u.array(u.string()).min(1),locator:R,type:u.literal("upload")}),Xl=u.object({...v,locator:R,type:u.literal("dblclick")}),Ql=u.object({...v,source:R,target:R,type:u.literal("drag")}),Zl=u.object({...v,locator:R,type:u.literal("scrollIntoView")}),ec=u.object({...v,locator:R,type:u.literal("type"),value:X}),tc=u.object({...v,locator:R,type:u.literal("focus")}),rc=u.object({...v,locator:R,type:u.literal("clear")}),nc=u.object({...v,locator:R,type:u.literal("rightClick")}),oc=u.object({...v,action:u.enum(["accept","dismiss"]),promptText:u.string().optional(),type:u.literal("handleDialog")}),ic=u.object({...v,action:u.enum(["read","write"]),type:u.literal("clipboard"),value:X.optional(),variable:u.string().min(1).optional()}),sc=u.object({...v,permission:u.string().min(1),state:u.enum(["granted","prompt"]),type:u.literal("setPermission")}),ac=u.object({...v,locator:R,type:u.literal("assertVisible")}),lc=u.object({...v,locator:R,type:u.literal("assertNotVisible")}),cc=u.object({...v,expected:X,locator:R,operator:be,type:u.literal("assertText")}),uc=u.object({...v,expected:X,operator:be,type:u.literal("assertUrl")}),dc=u.object({...v,expected:Ot,locator:R,operator:$t,type:u.literal("assertCount")}),pc=u.object({...v,expected:X,locator:R,operator:be,type:u.literal("assertValue")}),mc=u.object({...v,attribute:u.string().min(1),expected:X,locator:R,operator:be,type:u.literal("assertAttribute")}),fc=u.object({...v,locator:R,type:u.literal("assertEnabled")}),gc=u.object({...v,locator:R,type:u.literal("assertDisabled")}),yc=u.object({...v,expected:X,operator:be,type:u.literal("assertTitle")}),hc=u.object({...v,locator:R,type:u.literal("assertChecked")}),wc=u.object({...v,locator:R,type:u.literal("assertNotChecked")}),bc=u.object({...v,locator:R,type:u.literal("assertFocused")}),vc=u.object({...v,locator:R,type:u.literal("assertNotFocused")}),Sc=u.object({...v,budget:u.enum(["fast","slow","async"]),observer:u.string().min(1).max(200),params:u.record(u.string().max(200),_r),type:u.literal("assertObserver")}),ho=u.discriminatedUnion("type",[Ul,Vl,Fl,Ml,Bl,Hl,Wl,ql,ac,lc,cc,uc,dc,pc,mc,fc,gc,zl,Gl,Kl,Jl,Yl,Xl,Ql,Zl,ec,tc,rc,nc,oc,ic,sc,yc,hc,wc,bc,vc,Sc]),Lt=u.object({entryNode:u.string().min(1).max(200),nodes:u.record(u.string().max(200),ho).refine(e=>Object.keys(e).length<=yo,`Workflow has more than ${String(yo)} nodes`),uiOnly:u.boolean().optional(),variableNamespaces:u.record(u.string().max(200),u.string().max(500)).optional(),variables:u.record(u.string().max(200),Dt).optional()});var kc=wo.record(wo.string().max(200),Lr),Rc={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},Pc={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},Ur=It("workflow-spec").legacy(Rc).initial(Lt).build(),xc=It("precondition-map").legacy(Pc).initial(kc).build();import{z as Vr}from"zod";var bo=["fast","slow","async"],Ec=Vr.object({budget:Vr.enum(bo).describe("Polling budget tier: fast | slow | async"),description:Vr.string().min(1).describe("Human-readable description of what this observer checks")}).describe("A named backend state observer. Tests assert against it with assert.backend(observer, params). Implementation lives on the user's server.");import{graphql as Do,readFragment as Gu}from"gql.tada";function So(){let e,t=!1;function r(o){e=o,t&&vo(o)}async function n(){t||(t=!0,e!=null&&await vo(e))}return{attachContext:r,fire:n,fired:()=>t}}async function vo(e){await e.close().catch(t=>{let r=t instanceof Error?t.message:String(t);f.warn("Failed to close browser context during abort: %s",r)})}import{mkdir as Fr,writeFile as ne}from"fs/promises";import K from"path";import{z as re}from"zod";async function Ro({context:e,page:t,runId:r,stepIndex:n,stepResult:o}){try{let i=K.join(process.cwd(),".ripplo","debug",r,"steps",String(n));await Fr(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([ne(K.join(i,"info.json"),JSON.stringify(s,null,2)),Tc(Ac({context:e,page:t,stepDir:i}),Cc,`capturePageState step ${String(n)}`)])}catch(i){let s=i instanceof Error?i.message:String(i);f.warn("Failed to write step debug data for step %d: %s",n,s)}}var Cc=15e3;async function Tc(e,t,r){let n,o=new Promise((i,s)=>{n=setTimeout(()=>{s(new Error(`${r} timed out after ${String(t)}ms`))},t)});try{return await Promise.race([e,o])}finally{n!=null&&clearTimeout(n)}}async function Ac({context:e,page:t,stepDir:r}){let[n,o,i,s,a]=await Promise.all([jc(t),Dc(t),Mc({context:e,page:t}),Vc(t),$c(t)]);await Promise.all([ne(K.join(r,"dom.html"),n),ne(K.join(r,"accessibility-tree.full.json"),JSON.stringify(o,null,2)),ne(K.join(r,"accessibility-tree.json"),Lc(o)),ne(K.join(r,"storage.json"),JSON.stringify(i,null,2)),ne(K.join(r,"rrweb-elements.ndjson"),a),ne(K.join(r,"screenshot.png"),s)])}var Ic=`
27
24
  (function () {
28
25
  try {
29
26
  var rrweb = window.rrweb || globalThis.rrweb;
@@ -87,8 +84,8 @@ Add missing values to the env file(s) declared in .ripplo/project.json.${i}`)}le
87
84
  return JSON.stringify({ __ripploError: String(err && err.message ? err.message : err) });
88
85
  }
89
86
  })()
90
- `;async function Ll(e){return await G({awaitPromise:!1,expression:Dl,page:e})??""}async function _l(e){return await G({awaitPromise:!1,expression:"document.documentElement.outerHTML",page:e})??"(unable to capture DOM)"}var Nt=ee.object({value:ee.unknown()}).partial(),Ul=ee.object({childIds:ee.array(ee.string()),description:Nt,ignored:ee.boolean(),name:Nt,nodeId:ee.string(),parentId:ee.string(),properties:ee.array(ee.unknown()),role:Nt,value:Nt}).partial(),Vl=ee.object({nodes:ee.array(Ul)});async function Fl(e){let t={nodes:[]};return bt(e,t,async r=>{let n=await r.send("Accessibility.getFullAXTree"),o=Vl.safeParse(n);return o.success?o.data:t})}function Hl(e){return e.nodes.filter(t=>t.ignored!==!0).map(t=>Ml(t)).toSorted(Bl).map(t=>JSON.stringify(t)).join(`
91
- `)}function Ml(e){let t=e.description?.value,r=e.value?.value;return{childIds:e.childIds??[],name:e.name?.value??"",nodeId:e.nodeId,parentId:e.parentId,properties:e.properties??[],role:e.role?.value??"",...t==null?{}:{description:t},...r==null?{}:{value:r}}}function Bl(e,t){return to(e.nodeId)-to(t.nodeId)}function to(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 Wl(e){return bt(e,void 0,async t=>{let r=await t.send("Page.captureScreenshot",{format:"png"});return Buffer.from(r.data,"base64")})}var ql=`(() => {
87
+ `;async function $c(e){return await J({awaitPromise:!1,expression:Ic,label:"captureRrwebElements",page:e,timeoutMs:void 0})??""}async function jc(e){return await J({awaitPromise:!1,expression:"document.documentElement.outerHTML",label:"captureDom",page:e,timeoutMs:void 0})??"(unable to capture DOM)"}var _t=re.object({value:re.unknown()}).partial(),Nc=re.object({childIds:re.array(re.string()),description:_t,ignored:re.boolean(),name:_t,nodeId:re.string(),parentId:re.string(),properties:re.array(re.unknown()),role:_t,value:_t}).partial(),Oc=re.object({nodes:re.array(Nc)});async function Dc(e){return St({label:"captureAxTree",page:e,timeoutMs:void 0,fn:async t=>{let r=await t.send("Accessibility.getFullAXTree"),n=Oc.safeParse(r);return n.success?n.data:{nodes:[]}}})}function Lc(e){return e.nodes.filter(t=>t.ignored!==!0).map(t=>_c(t)).toSorted(Uc).map(t=>JSON.stringify(t)).join(`
88
+ `)}function _c(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 Uc(e,t){return ko(e.nodeId)-ko(t.nodeId)}function ko(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 Vc(e){return St({label:"captureScreenshot",page:e,timeoutMs:void 0,fn:async t=>{let r=await t.send("Page.captureScreenshot",{format:"png"});return Buffer.from(r.data,"base64")}})}var Fc=`(() => {
92
89
  function dump(s) {
93
90
  var out = {};
94
91
  for (var i = 0; i < s.length; i++) {
@@ -98,65 +95,49 @@ Add missing values to the env file(s) declared in .ripplo/project.json.${i}`)}le
98
95
  return out;
99
96
  }
100
97
  return { localStorage: dump(localStorage), sessionStorage: dump(sessionStorage) };
101
- })()`;async function zl({context:e,page:t}){let[r,n]=await Promise.all([G({awaitPromise:!1,expression:ql,page:t}),e.cookies().catch(()=>[])]);return{cookies:n,localStorage:r?.localStorage??{},sessionStorage:r?.sessionStorage??{}}}async function no({runId:e,steps:t,summary:r}){try{let n=W.join(process.cwd(),".ripplo","debug",e);await jr(n,{recursive:!0}),await Promise.all([te(W.join(n,"summary.txt"),Gl({steps:t,summary:r})),te(W.join(n,"manifest.md"),Kl({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 Gl({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(`
102
- `)}function Kl({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(`
103
- `)}async function oo({error:e,runId:t,stack:r,workflowName:n}){try{let o=W.join(process.cwd(),".ripplo","debug",t);await jr(o,{recursive:!0});let i=r==null?e:`${e}
98
+ })()`;async function Mc({context:e,page:t}){let[r,n]=await Promise.all([J({awaitPromise:!1,expression:Fc,label:"captureStorage",page:t,timeoutMs:void 0}),e.cookies().catch(()=>[])]);return{cookies:n,localStorage:r?.localStorage??{},sessionStorage:r?.sessionStorage??{}}}async function Po({runId:e,steps:t,summary:r}){try{let n=K.join(process.cwd(),".ripplo","debug",e);await Fr(n,{recursive:!0}),await Promise.all([ne(K.join(n,"summary.txt"),Bc({steps:t,summary:r})),ne(K.join(n,"manifest.md"),Hc({steps:t,summary:r}))]),f.info("Debug artifacts written to .ripplo/debug/%s/",e)}catch(n){let o=n instanceof Error?n.message:String(n);f.warn("Failed to write run debug summary: %s",o)}}function Bc({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(`
99
+ `)}function Hc({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(`
100
+ `)}async function xo({error:e,runId:t,stack:r,workflowName:n}){try{let o=K.join(process.cwd(),".ripplo","debug",t);await Fr(o,{recursive:!0});let i=r==null?e:`${e}
104
101
 
105
102
  ${r}`,s=[`Run ID: ${t}`,`Workflow: ${n}`,"Status: failed","",`Error: ${e}`,"",r==null?"":`Stack trace:
106
103
  ${r}`].join(`
107
104
  `),a=[`# Run ${t} \u2014 ${n}`,"","Status: **failed**","","Run aborted before normal completion. Read:","- `error.txt` \u2014 failure reason + stack trace.","- `summary.txt` \u2014 high-level run summary.","- `steps/<N>/info.json` \u2014 per-step metadata for any steps that started before the abort.","","Per-step screenshots / DOM / accessibility-tree may be partial or missing.",""].join(`
108
- `);await Promise.all([te(W.join(o,"error.txt"),i),te(W.join(o,"summary.txt"),s),te(W.join(o,"manifest.md"),a)]),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 Jl}from"fs";import{createRequire as Yl}from"module";import io from"path";import{gzipSync as Xl}from"zlib";var Ql=Yl(import.meta.url),Zl=Ql.resolve("rrweb"),ec=io.join(io.dirname(Zl),"rrweb.umd.min.cjs"),tc=Jl(ec,"utf8"),rc=[";(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(`
109
- `),nc=tc+`
110
- `+rc;async function so(e){let t,r=0;async function n(){await e.addScriptTag({content:nc}).catch(()=>{})}await n(),e.on("load",()=>{n()});async function o(){await G({awaitPromise:!1,expression:"globalThis.__ripploRrwebStart && globalThis.__ripploRrwebStart()",page:e});let l=await G({awaitPromise:!1,expression:"globalThis.__ripploRrwebStartedAt",page:e});typeof l=="number"&&(t??=l)}function i(){if(t!=null)return Date.now()-t}async function s(){let l=await G({awaitPromise:!1,expression:"globalThis.__ripploRrwebDrain ? globalThis.__ripploRrwebDrain() : []",page:e})??[],c=l[0],p=l.at(-1);if(c==null||p==null)return;t??=c.timestamp;let m=t,S=l.map(g=>JSON.stringify(g)).join(`
111
- `),O={body:Xl(Buffer.from(S,"utf8")),chunkIndex:r,endTimestamp:p.timestamp-m,eventCount:l.length,startTimestamp:c.timestamp-m};return r+=1,O}async function a(){await G({awaitPromise:!1,expression:"globalThis.__ripploRrwebStop && globalThis.__ripploRrwebStop()",page:e})}return{currentOffsetMs:i,detach:a,start:o,takeChunk:s}}import{z as re}from"zod";import ao from"crypto";import{Webhook as oc}from"standardwebhooks";function be({body:e,secret:t}){let r=new oc(t),n=`msg_${ao.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 Nr(){return`whsec_${ao.randomBytes(24).toString("base64")}`}var ic=15e4,sc={async:{backoffMs:[500,1e3,2e3,5e3],timeoutMs:12e4},fast:{backoffMs:[100,250,500,1e3],timeoutMs:5e3},slow:{backoffMs:[250,500,1e3,2e3],timeoutMs:3e4}},ac=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()})]),lc=re.object({error:re.string().optional(),outcome:ac.optional(),success:re.boolean()});async function lo({apiUrl:e,budget:t,observer:r,params:n,webhookSecret:o}){let i=sc[t],s=performance.now(),a={lastReason:void 0,pollCount:0};for(;performance.now()-s<i.timeoutMs;){a.pollCount+=1;let l=await dc({apiUrl:e,observer:r,params:n,webhookSecret:o}),c=cc({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(uc({backoff:i.backoffMs,pollCount:a.pollCount}),p);await pc(m)}return{description:`observer "${r}"`,detail:`budget "${t}" exhausted after ${String(a.pollCount)} poll(s) (${co(s)}); last: ${a.lastReason??"no retry reason"}
112
- \u2192 /ripplo:debug \u2014 check .ripplo/debug/<runId>/ artifacts`,status:"failed"}}function cc({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}
113
- 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 (${co(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.
114
- Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=t.reason,null)}async function dc({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(ic)});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=lc.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 uc({backoff:e,pollCount:t}){let r=Math.min(t-1,e.length-1);return e[r]??1e3}function co(e){return`${String(Math.round(performance.now()-e))}ms`}async function pc(e){return new Promise(t=>setTimeout(t,e))}var Ot=1e4;async function Or({failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,spec:i,variables:s}){let a=performance.now();return fc({currentId:i.entryNode,failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,runStartTime:a,spec:i,variables:s})}function mc({onStep:e,steps:t,target:r}){t.forEach(n=>{let o={...n,stepIndex:r.length};r.push(o),e?.(o)})}async function fc({currentId:e,failFast:t,getRecordingOffsetMs:r,observerTransport:n,onStep:o,page:i,runStartTime:s,spec:a,variables:l}){let c=[],p=l,m=e;for(;m!=null;){let S=a.nodes[m];if(S==null)throw new Error(`Node "${m}" not found in spec`);let N=m,O=S.label??`${S.type} (${m})`;y.info("Executing node: %s [%s]",O,S.type);let g=await gc({getRecordingOffsetMs:r,node:S,nodeId:N,observerTransport:n,page:i,runStartTime:s,variables:p});if(mc({onStep:o,steps:[g],target:c}),p=g.variables,t&&g.status==="failed")break;m=S.next}return{steps:c,variables:p}}async function gc({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=Ot;try{let m=await yc({node:t,observerTransport:n,page:o,timeout:p,variables:s}),S=Math.round(performance.now()-a),N=m.assertions.some(g=>g.status==="failed"),O=e?.();return{assertions:m.assertions,detail:void 0,duration:S,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 S=Math.round(performance.now()-a),N=m instanceof Error?m.message:String(m),O=e?.();return{assertions:[],detail:N,duration:S,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 yc({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(hc(e)){let s=await hr({node:e,page:r,timeout:n,variables:o});return{assertions:[],variables:s.variables}}return{assertions:await bc({node:e,observerTransport:t,page:r,timeout:n,variables:o}),variables:o}}function hc(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 wc(e){return e.type.startsWith("assert")}async function bc({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(!wc(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 Sc({assertNode:i,page:r,timeout:n,variables:o});case"assertText":{let s=K({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"assertUrl":{let s=K({ref:i.expected,variables:o});return[await br({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertTitle":{let s=K({ref:i.expected,variables:o});return[await $n({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertCount":{let s=yr({ref:i.expected,variables:o});return[await vr({expected:s,locator:D({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertValue":{let s=K({ref:i.expected,variables:o});return[await Sr({expected:s,locator:D({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertAttribute":{let s=K({ref:i.expected,variables:o});return[await jn({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]=St({ref:l,variables:o})}),[await lo({apiUrl:t.apiUrl,budget:i.budget,observer:i.observer,params:s,webhookSecret:t.webhookSecret})]}}}var vc={assertChecked:Dn,assertDisabled:On,assertEnabled:Nn,assertFocused:_n,assertNotChecked:Ln,assertNotFocused:Un,assertNotVisible:Rr,assertVisible:kr};async function Sc({assertNode:e,page:t,timeout:r,variables:n}){let o=vc[e.type];return[await o({locator:D({locator:e.locator,page:t,variables:n}),timeout:r})]}async function Dr({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(Ot),c.setDefaultNavigationTimeout(Ot),r.length>0&&await c.addCookies(r);let p=await c.newPage(),m=await so(p);async function S(){let z=await m.takeChunk();z!=null&&i?.(z)}let N=setInterval(()=>{S()},2e3),O=[],g=!1;function q(z){s?.(z),g||(g=!0,m.start()),O.push(ro({context:c,page:p,runId:a,stepIndex:z.stepIndex,stepResult:z}))}let j=kc(n,l.variableNamespaces),V={...gr({defs:l.variables}),...j},oe=await Or({failFast:!0,getRecordingOffsetMs:m.currentOffsetMs,observerTransport:o,onStep:q,page:p,spec:l,variables:V});clearInterval(N);let Ie=oe.steps.filter(z=>z.status==="passed").length,se=oe.steps.filter(z=>z.status==="failed").length,Ye={duration:oe.steps.reduce((z,ie)=>z+ie.duration,0),failCount:se,passCount:Ie,runId:a,status:se>0?"failed":"passed",workflowName:""};return await Promise.all([Promise.allSettled(O).then(()=>no({runId:a,steps:oe.steps,summary:Ye})),m.detach().then(S)]),await c.close(),oe.steps}function kc(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 Rc}from"set-cookie-parser";import{z as H}from"zod";var uo=3e4,Pc=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 Lr({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",...Ic({cookies:t}),...be({body:i,secret:o})},method:"PUT",signal:AbortSignal.timeout(uo)});s.ok||y.error("Teardown returned %s",String(s.status))}catch{y.error("Teardown request failed")}}async function xc({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(uo)});if(!i.ok){let c=await Cc(i);throw new Error(`execute-preconditions returned ${String(i.status)}: ${c}`)}let s=await i.json(),a=Pc.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=Tc({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 Ec=H.object({error:H.string()});async function Cc(e){let t=await e.text().catch(()=>"");if(t.length===0)return"no body";let r=Ac(t),n=r==null?null:Ec.safeParse(r);return n!=null&&n.success?n.data.error:t.slice(0,500)}function Ac(e){try{return JSON.parse(e)}catch{return null}}function Ic({cookies:e}){return e.length===0?{}:{Cookie:e.map(r=>`${r.name}=${r.value}`).join("; ")}}function Tc({domain:e,res:t}){let r=t.headers.getSetCookie();return Rc(r,{decodeValues:!1}).map(o=>$c({cookie:o,domain:e}))}function $c({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=Nc({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 jc={lax:"Lax",none:"None",strict:"Strict"};function Nc({raw:e}){return jc[e.toLowerCase()]??"Lax"}async function Dt({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:[]}:xc({apiUrl:n,preconditionNames:t,webhookSecret:r})}import{graphql as _e}from"gql.tada";async function _r({config:e,runId:t}){if((await f({config:e,document:_c,variables:{runId:t}})).startRun==null)throw new Error("Failed to start run");let n=[];function o(l){let c=Dc({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=Oc({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,S=c.filter(g=>g.status==="failed").length,N=c.reduce((g,q)=>g+q.duration,0),O=l??(S>0?"failed":"passed");await pe({label:"completeRun",fn:()=>f({config:e,document:Fc,variables:{duration:N,failCount:S,passCount:m,runId:t,status:O,summary:p??null,warnCount:0}})})}return{complete:a,enqueueRecordingChunk:i,enqueueStep:o,flushSteps:s,runId:t}}async function Oc({chunk:e,config:t,runId:r}){await f({config:t,document:Vc,variables:{input:{bodyBase64:e.body.toString("base64"),chunkIndex:e.chunkIndex,endTimestamp:e.endTimestamp,eventCount:e.eventCount,runId:r,startTimestamp:e.startTimestamp}}})}async function Dc({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:Uc,variables:{runId:t,steps:n}})}async function Ur({config:e,reason:t,runId:r}){await f({config:e,document:Lc,variables:{reason:t,runId:r}})}var Fb=_e(`
115
- mutation MarkRunArtifactsUploadedCLI($runId: String!) {
116
- markRunArtifactsUploaded(runId: $runId)
117
- }
118
- `),Lc=_e(`
105
+ `);await Promise.all([ne(K.join(o,"error.txt"),i),ne(K.join(o,"summary.txt"),s),ne(K.join(o,"manifest.md"),a)]),f.info("Debug error artifacts written to .ripplo/debug/%s/",t)}catch(o){let i=o instanceof Error?o.message:String(o);f.warn("Failed to write error debug artifacts: %s",i)}}import{readFileSync as Wc}from"fs";import{createRequire as qc}from"module";import Eo from"path";import{gzipSync as zc}from"zlib";var Gc=qc(import.meta.url),Kc=Gc.resolve("rrweb"),Jc=Eo.join(Eo.dirname(Kc),"rrweb.umd.min.cjs"),Yc=Wc(Jc,"utf8"),Xc=[";(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(`
106
+ `),Qc=Yc+`
107
+ `+Xc;async function Co(e){let t,r=0;async function n(){await e.addScriptTag({content:Qc})}await n(),e.on("load",()=>{n().catch(l=>{let c=l instanceof Error?l.message:String(l);f.warn("rrweb re-injection on navigation failed: %s",c)})});async function o(){await J({awaitPromise:!1,expression:"globalThis.__ripploRrwebStart && globalThis.__ripploRrwebStart()",label:"rrweb start",page:e,timeoutMs:void 0});let l=await J({awaitPromise:!1,expression:"globalThis.__ripploRrwebStartedAt",label:"rrweb startedAt",page:e,timeoutMs:void 0});typeof l=="number"&&(t??=l)}function i(){if(t!=null)return Date.now()-t}async function s(){let l=await J({awaitPromise:!1,expression:"globalThis.__ripploRrwebDrain ? globalThis.__ripploRrwebDrain() : []",label:"rrweb drain",page:e,timeoutMs:void 0})??[],c=l[0],p=l.at(-1);if(c==null||p==null)return;t??=c.timestamp;let m=t,h=l.map(g=>JSON.stringify(g)).join(`
108
+ `),$={body:zc(Buffer.from(h,"utf8")),chunkIndex:r,endTimestamp:p.timestamp-m,eventCount:l.length,startTimestamp:c.timestamp-m};return r+=1,$}async function a(){await J({awaitPromise:!1,expression:"globalThis.__ripploRrwebStop && globalThis.__ripploRrwebStop()",label:"rrweb stop",page:e,timeoutMs:void 0})}return{currentOffsetMs:i,detach:a,start:o,takeChunk:s}}import{z as oe}from"zod";import To from"crypto";import{Webhook as Zc}from"standardwebhooks";function ve({body:e,secret:t}){let r=new Zc(t),n=`msg_${To.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 Mr(){return`whsec_${To.randomBytes(24).toString("base64")}`}var eu=15e4,tu={async:{backoffMs:[500,1e3,2e3,5e3],timeoutMs:12e4},fast:{backoffMs:[100,250,500,1e3],timeoutMs:5e3},slow:{backoffMs:[250,500,1e3,2e3],timeoutMs:3e4}},ru=oe.discriminatedUnion("kind",[oe.object({kind:oe.literal("pass")}),oe.object({kind:oe.literal("retry"),reason:oe.string()}),oe.object({kind:oe.literal("fail"),reason:oe.string()})]),nu=oe.object({error:oe.string().optional(),outcome:ru.optional(),success:oe.boolean()});async function Ao({apiUrl:e,budget:t,observer:r,params:n,webhookSecret:o}){let i=tu[t],s=performance.now(),a={lastReason:void 0,pollCount:0};for(;performance.now()-s<i.timeoutMs;){a.pollCount+=1;let l=await iu({apiUrl:e,observer:r,params:n,webhookSecret:o}),c=ou({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(su({backoff:i.backoffMs,pollCount:a.pollCount}),p);await au(m)}return{description:`observer "${r}"`,detail:`budget "${t}" exhausted after ${String(a.pollCount)} poll(s) (${Io(s)}); last: ${a.lastReason??"no retry reason"}
109
+ \u2192 /ripplo:debug \u2014 check .ripplo/debug/<runId>/ artifacts`,status:"failed"}}function ou({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}
110
+ 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 (${Io(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.
111
+ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=t.reason,null)}async function iu({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",...ve({body:o,secret:n})},method:"PUT",signal:AbortSignal.timeout(eu)});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=nu.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 f.error("observer request failed: %s",s),{kind:"transport-error",reason:s}}}function su({backoff:e,pollCount:t}){let r=Math.min(t-1,e.length-1);return e[r]??1e3}function Io(e){return`${String(Math.round(performance.now()-e))}ms`}async function au(e){return new Promise(t=>setTimeout(t,e))}var Ut=15e3;async function Br({failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,spec:i,variables:s}){let a=performance.now();return cu({currentId:i.entryNode,failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,runStartTime:a,spec:i,variables:s})}function lu({onStep:e,steps:t,target:r}){t.forEach(n=>{let o={...n,stepIndex:r.length};r.push(o),e?.(o)})}async function cu({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 h=a.nodes[m];if(h==null)throw new Error(`Node "${m}" not found in spec`);let T=m,$=h.label??`${h.type} (${m})`;f.info("Executing node: %s [%s]",$,h.type);let g=await uu({getRecordingOffsetMs:r,node:h,nodeId:T,observerTransport:n,page:i,runStartTime:s,variables:p});if(lu({onStep:o,steps:[g],target:c}),p=g.variables,t&&g.status==="failed")break;m=h.next}return{steps:c,variables:p}}async function uu({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=Ut;try{let m=await du({node:t,observerTransport:n,page:o,timeout:p,variables:s}),h=Math.round(performance.now()-a),T=m.assertions.some(g=>g.status==="failed"),$=e?.();return{assertions:m.assertions,detail:void 0,duration:h,nodeId:r,nodeType:t.type,recordingEndMs:$,recordingStartMs:l,snapshotTimestamp:Math.round(performance.now()-i),status:T?"failed":"passed",stepIndex:0,title:c,url:o.url(),variables:m.variables}}catch(m){let h=Math.round(performance.now()-a),T=m instanceof Error?m.message:String(m),$=e?.();return{assertions:[],detail:T,duration:h,nodeId:r,nodeType:t.type,recordingEndMs:$,recordingStartMs:l,snapshotTimestamp:Math.round(performance.now()-i),status:"failed",stepIndex:0,title:c,url:o.url(),variables:s}}}async function du({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(pu(e)){let s=await Sr({node:e,page:r,timeout:n,variables:o});return{assertions:[],variables:s.variables}}return{assertions:await fu({node:e,observerTransport:t,page:r,timeout:n,variables:o}),variables:o}}function pu(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 mu(e){return e.type.startsWith("assert")}async function fu({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(!mu(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 yu({assertNode:i,page:r,timeout:n,variables:o});case"assertText":{let s=Y({ref:i.expected,variables:o});return[await kr({expected:s,locator:U({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertUrl":{let s=Y({ref:i.expected,variables:o});return[await Rr({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertTitle":{let s=Y({ref:i.expected,variables:o});return[await qn({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertCount":{let s=vr({ref:i.expected,variables:o});return[await Pr({expected:s,locator:U({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertValue":{let s=Y({ref:i.expected,variables:o});return[await xr({expected:s,locator:U({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertAttribute":{let s=Y({ref:i.expected,variables:o});return[await zn({attribute:i.attribute,expected:s,locator:U({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]=Rt({ref:l,variables:o})}),[await Ao({apiUrl:t.apiUrl,budget:i.budget,observer:i.observer,params:s,webhookSecret:t.webhookSecret})]}}}var gu={assertChecked:Jn,assertDisabled:Kn,assertEnabled:Gn,assertFocused:Xn,assertNotChecked:Yn,assertNotFocused:Qn,assertNotVisible:Cr,assertVisible:Er};async function yu({assertNode:e,page:t,timeout:r,variables:n}){let o=gu[e.type];return[await o({locator:U({locator:e.locator,page:t,variables:n}),timeout:r})]}var hu=5e3,wu=2e3;async function Hr({abort:e,baseUrl:t,browser:r,cookies:n,extraVariables:o,observerTransport:i,onRecordingChunk:s,onStep:a,runId:l,spec:c}){let p=await r.newContext({baseURL:t});e.attachContext(p),p.setDefaultTimeout(Ut),p.setDefaultNavigationTimeout(Ut),n.length>0&&await p.addCookies(n);let m=await p.newPage(),h=await Co(m);async function T(){let j=await h.takeChunk();j!=null&&s?.(j)}let $=setInterval(()=>{T().catch(j=>{let W=j instanceof Error?j.message:String(j);f.warn("rrweb chunk flush failed: %s",W)})},2e3),g=[],H=!1;function x(j){a?.(j),H||(H=!0,h.start().catch(W=>{let ge=W instanceof Error?W.message:String(W);f.warn("rrweb recorder start failed: %s",ge)})),g.push(Ro({context:p,page:m,runId:l,stepIndex:j.stepIndex,stepResult:j}))}let F=bu(o,c.variableNamespaces),Ae={...br({defs:c.variables}),...F};try{let j=await Br({failFast:!0,getRecordingOffsetMs:h.currentOffsetMs,observerTransport:i,onStep:x,page:m,spec:c,variables:Ae});clearInterval($);let W=j.steps.filter(L=>L.status==="passed").length,ge=j.steps.filter(L=>L.status==="failed").length,dr={duration:j.steps.reduce((L,et)=>L+et.duration,0),failCount:ge,passCount:W,runId:l,status:ge>0?"failed":"passed",workflowName:""};return await ye(Promise.allSettled([Promise.allSettled(g).then(()=>Po({runId:l,steps:j.steps,summary:dr})),h.detach().then(T).catch(L=>{let et=L instanceof Error?L.message:String(L);f.warn("Recorder detach failed: %s",et)})]),hu,"post-run cleanup").catch(L=>{let et=L instanceof Error?L.message:String(L);f.warn("Post-run cleanup did not finish in budget: %s",et)}),j.steps}finally{clearInterval($),await ye(p.close(),wu,"context.close").catch(j=>{let W=j instanceof Error?j.message:String(j);f.warn("Context close failed: %s",W)})}}function bu(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 de({fn:e,label:t}){let r=performance.now(),n=await e();return f.debug("%s: %dms",t,Math.round(performance.now()-r)),n}var zr=gr(Et(),1);import{z as S}from"zod";var vu=S.union([S.string(),S.number(),S.boolean()]),Su=S.record(S.string(),S.record(S.string(),vu)),ku=S.object({domain:S.string().optional(),expires:S.number().optional(),httpOnly:S.boolean().optional(),name:S.string(),path:S.string().optional(),sameSite:S.enum(["lax","none","strict"]).optional(),secure:S.boolean().optional(),value:S.string()}),Ru=S.discriminatedUnion("ok",[S.object({cookies:S.array(ku),data:Su,executed:S.array(S.string()),ok:S.literal(!0),runId:S.string()}),S.object({error:S.string(),ok:S.literal(!1),runId:S.string()})]),Pu=S.object({results:S.array(Ru)}),xu=S.object({results:S.array(S.object({error:S.string().optional(),ok:S.boolean(),runId:S.string()}))}),$o=3e4;async function Gr({apiUrl:e,data:t,executed:r,runId:n,webhookSecret:o}){if(r.length!==0)try{await Au({apiUrl:e,webhookSecret:o}).load({data:t,preconditions:r,runId:n})}catch(i){let s=i instanceof Error?i.message:String(i);f.error("Teardown request failed: %s",s)}}async function Vt({engineBaseUrl:e,preconditionNames:t,runId:r,webhookSecret:n}){let o=e.length===0?void 0:e;return o==null||t.length===0?{apiUrl:o,cookies:[],data:{},executed:[]}:Eu({apiUrl:o,preconditionNames:t,runId:r,webhookSecret:n})}async function Eu({apiUrl:e,preconditionNames:t,runId:r,webhookSecret:n}){return{...await Cu({apiUrl:e,webhookSecret:n}).load({preconditionNames:t,runId:r}),apiUrl:e}}function Kr(){Wr.clear(),qr.clear()}var Wr=new Map;function Cu({apiUrl:e,webhookSecret:t}){let r=`${e}::${t}`,n=Wr.get(r);if(n!=null)return n;let o=new zr.default(i=>Tu({apiUrl:e,keys:i,webhookSecret:t}),{cache:!1,batchScheduleFn:i=>{setTimeout(i,200)},cacheKeyFn:i=>i.runId});return Wr.set(r,o),o}async function Tu({apiUrl:e,keys:t,webhookSecret:r}){let n=performance.now(),o=JSON.stringify({batch:t.map(p=>({preconditions:[...p.preconditionNames],runId:p.runId}))}),i=await fetch(`${e}/execute-preconditions`,{body:o,headers:{"Content-Type":"application/json",...ve({body:o,secret:r})},method:"PUT",signal:AbortSignal.timeout($o)});if(!i.ok){let p=await ju(i),m=new Error(`execute-preconditions returned ${String(i.status)}: ${p}`);return t.map(()=>m)}let s=await i.json(),a=Pu.safeParse(s);if(!a.success){let p=new Error(`execute-preconditions response has invalid shape: ${a.error.message}`);return t.map(()=>p)}let l=new URL(e).hostname,c=new Map(a.data.results.map(p=>[p.runId,p]));return f.debug({batchSize:t.length,elapsedMs:Math.round(performance.now()-n),op:"execute-preconditions"},"batched op flushed"),t.map(p=>{let m=c.get(p.runId);return m==null?new Error(`execute-preconditions response missing runId ${p.runId}`):m.ok?(f.info("Preconditions resolved: %s",m.executed.join(", ")),{cookies:m.cookies.map(h=>Du({cookie:h,domain:l})),data:m.data,executed:m.executed}):new Error(`Precondition batch failed: ${m.error}`)})}var qr=new Map;function Au({apiUrl:e,webhookSecret:t}){let r=`${e}::${t}`,n=qr.get(r);if(n!=null)return n;let o=new zr.default(i=>Iu({apiUrl:e,keys:i,webhookSecret:t}),{cache:!1,batchScheduleFn:i=>{setTimeout(i,200)},cacheKeyFn:i=>i.runId});return qr.set(r,o),o}async function Iu({apiUrl:e,keys:t,webhookSecret:r}){let n=JSON.stringify({batch:t.map(l=>({data:l.data,preconditions:[...l.preconditions],runId:l.runId}))}),o=await fetch(`${e}/teardown-preconditions`,{body:n,headers:{"Content-Type":"application/json",...ve({body:n,secret:r})},method:"PUT",signal:AbortSignal.timeout($o)});if(!o.ok){let l=new Error(`teardown-preconditions returned ${String(o.status)}`);return t.map(()=>l)}let i=await o.json(),s=xu.safeParse(i);if(!s.success){let l=new Error(`teardown-preconditions response has invalid shape: ${s.error.message}`);return t.map(()=>l)}let a=new Map(s.data.results.map(l=>[l.runId,l]));return t.map(l=>{let c=a.get(l.runId);if(c==null)return new Error(`teardown-preconditions response missing runId ${l.runId}`);if(!c.ok)return new Error(`Teardown failed: ${c.error??"unknown error"}`)})}var $u=S.object({error:S.string()});async function ju(e){let t=await e.text().catch(()=>"");if(t.length===0)return"no body";let r=Nu(t),n=r==null?null:$u.safeParse(r);return n!=null&&n.success?n.data.error:t.slice(0,500)}function Nu(e){try{return JSON.parse(e)}catch{return null}}var Ou={lax:"Lax",none:"None",strict:"Strict"};function Du({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=Ou[e.sameSite]??"Lax"),e.expires!=null&&(r.expires=e.expires),r}var it=gr(Et(),1);import{graphql as Ve}from"gql.tada";async function Jr({config:e,runId:t}){let r=Lu(e);await r.start.load(t);let n=[];function o(c){return n.push(c.catch(()=>{})),c}function i(c){o(r.steps.load({runId:t,step:c})).catch(p=>{f.error(p,"submitRunSteps failed")})}function s(c){o(Vu({chunk:c,config:e,runId:t})).catch(p=>{f.error(p,"submitRunRecordingChunk failed")})}async function a(){for(;n.length>0;){let c=n.splice(0);await Promise.all(c)}}async function l({flush:c,statusOverride:p,steps:m,summary:h}){c&&await de({label:"flushSteps",fn:()=>a()});let T=m.filter(x=>x.status==="passed").length,$=m.filter(x=>x.status==="failed").length,g=m.reduce((x,F)=>x+F.duration,0),H=p??($>0?"failed":"passed");await de({label:"completeRun",fn:()=>r.complete.load({duration:g,failCount:$,passCount:T,runId:t,status:H,summary:h??null,warnCount:0})})}return{complete:l,enqueueRecordingChunk:s,enqueueStep:i,flushSteps:a,runId:t}}async function Yr({config:e,reason:t,runId:r}){await y({config:e,document:Mu,variables:{reason:t,runId:r}})}var jo=new Map;function Lu(e){let t=`${e.ripploServerUrl}::${e.token}`,r=jo.get(t);if(r!=null)return r;let n={artifactsUploaded:new it.default(async o=>(await Ft({config:e,document:Fu,opName:"markRunArtifactsUploadedBatch",size:o.length,variables:{runIds:[...o]}}),o.map(()=>!0)),{cache:!1}),complete:new it.default(async o=>(await Ft({config:e,document:qu,opName:"completeRunsBatch",size:o.length,variables:{items:[...o]}}),o.map(()=>!0)),{cache:!1}),start:new it.default(async o=>(await Ft({config:e,document:Bu,opName:"startRunsBatch",size:o.length,variables:{runIds:[...o]}}),o.map(()=>!0)),{cache:!1,batchScheduleFn:o=>{setTimeout(o,200)}}),steps:new it.default(async o=>(await Ft({config:e,document:Hu,opName:"submitRunStepsBatch",size:o.length,variables:{items:_u(o)}}),o.map(()=>!0)),{cache:!1,batchScheduleFn:o=>{setTimeout(o,200)}})};return jo.set(t,n),n}async function Ft({config:e,document:t,opName:r,size:n,variables:o}){let i=performance.now();await y({config:e,document:t,variables:o}),f.debug({batchSize:n,elapsedMs:Math.round(performance.now()-i),op:r},"batched op flushed")}function _u(e){let t=new Map;return e.forEach(({runId:r,step:n})=>{let o=Uu(n),i=t.get(r);if(i==null){t.set(r,[o]);return}i.push(o)}),[...t.entries()].map(([r,n])=>({runId:r,steps:n}))}function Uu(e){return{assertions:e.assertions.map(t=>({description:t.description,detail:t.detail??null,status:t.status})),detail:e.detail??null,duration:e.duration,nodeType:e.nodeType,recordingEndMs:e.recordingEndMs??null,recordingStartMs:e.recordingStartMs??null,snapshotTimestamp:e.snapshotTimestamp,status:e.status,stepIndex:e.stepIndex,title:e.title,url:e.url}}async function Vu({chunk:e,config:t,runId:r}){await y({config:t,document:Wu,variables:{input:{bodyBase64:e.body.toString("base64"),chunkIndex:e.chunkIndex,endTimestamp:e.endTimestamp,eventCount:e.eventCount,runId:r,startTimestamp:e.startTimestamp}}})}var Fu=Ve(`
112
+ mutation MarkRunArtifactsUploadedBatchCLI($runIds: [String!]!) {
113
+ markRunArtifactsUploadedBatch(runIds: $runIds)
114
+ }
115
+ `),Mu=Ve(`
119
116
  mutation FailRunCLI($runId: String!, $reason: String!) {
120
117
  failRun(runId: $runId, reason: $reason)
121
118
  }
122
- `),_c=_e(`
123
- mutation StartRunCLI($runId: String!) {
124
- startRun(runId: $runId) {
119
+ `),Bu=Ve(`
120
+ mutation StartRunsBatchCLI($runIds: [String!]!) {
121
+ startRunsBatch(runIds: $runIds) {
125
122
  id
126
123
  }
127
124
  }
128
- `),Uc=_e(`
129
- mutation SubmitRunStepsCLI($runId: String!, $steps: [StepInput!]!) {
130
- submitRunSteps(runId: $runId, steps: $steps)
125
+ `),Hu=Ve(`
126
+ mutation SubmitRunStepsBatchCLI($items: [SubmitRunStepsItem!]!) {
127
+ submitRunStepsBatch(items: $items)
131
128
  }
132
- `),Vc=_e(`
129
+ `),Wu=Ve(`
133
130
  mutation SubmitRunRecordingChunkCLI($input: SubmitRunRecordingChunkInput!) {
134
131
  submitRunRecordingChunk(input: $input)
135
132
  }
136
- `),Fc=_e(`
137
- mutation CompleteRunCLI(
138
- $runId: String!
139
- $status: RunStatus!
140
- $duration: Int!
141
- $passCount: Int!
142
- $failCount: Int!
143
- $warnCount: Int!
144
- $summary: String
145
- ) {
146
- completeRun(
147
- runId: $runId
148
- status: $status
149
- duration: $duration
150
- passCount: $passCount
151
- failCount: $failCount
152
- warnCount: $warnCount
153
- summary: $summary
154
- ) {
133
+ `),qu=Ve(`
134
+ mutation CompleteRunsBatchCLI($items: [CompleteRunItem!]!) {
135
+ completeRunsBatch(items: $items) {
155
136
  id
156
137
  status
157
138
  }
158
139
  }
159
- `);var Bc=12e4,mo=po(`
140
+ `);var Ku=12e4,Ju=15e3,Lo=Do(`
160
141
  fragment WorkflowRun on Workflow {
161
142
  id
162
143
  slug
@@ -168,9 +149,9 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
168
149
  preconditionName
169
150
  }
170
151
  }
171
- `),Wc=po(`
172
- query RunWorkflowSpec($runId: String!) {
173
- run(id: $runId) {
152
+ `),Yu=Do(`
153
+ query RunsByIdsWorkflowSpec($ids: [String!]!) {
154
+ runsByIds(ids: $ids) {
174
155
  id
175
156
  workflow {
176
157
  ...WorkflowRun
@@ -181,9 +162,9 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
181
162
  }
182
163
  }
183
164
  }
184
- `,[mo]);async function Vr({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=qc({externalBrowser:t,headed:n});let m=o==null?void 0:Dt({engineBaseUrl:r.engineUrl,preconditionNames:o,webhookSecret:s}),[{engineBaseUrl:S,workflow:N},O]=await Promise.all([pe({label:"Run context resolved",fn:()=>Yc({config:r,runId:i})}),pe({label:"Streaming run started",fn:()=>_r({config:r,runId:i})}),Er({appUrl:e})]);a=N.name,l=O;let g=Xc(N.spec);y.info("Executing workflow: %s",N.name),await ed(Gc({baseUrl:e,browserPromise:c,engineBaseUrl:S,preconditionPromise:m,runId:i,specData:g,streaming:l,webhookSecret:s,workflow:N}),Zc())}catch(m){throw td(m)?m:(await zc({browserPromise:c,config:r,error:m,ownsBrowser:p,runId:i,streaming:l,workflowName:a}),new Lt(m))}}var Lt=class extends Error{cause;constructor(t){let r=t instanceof Error?t.message:String(t);super(r),this.name="RunReportedError",this.cause=t}};function qc({externalBrowser:e,headed:t}){return e!=null?Promise.resolve(e):pe({label:"Browser launched",fn:()=>rt({headed:t})})}async function zc({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 oo({error:a,runId:o,stack:l,workflowName:s}),i==null?await Ur({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 Gc({baseUrl:e,browserPromise:t,engineBaseUrl:r,preconditionPromise:n,runId:o,specData:i,streaming:s,webhookSecret:a,workflow:l}){let c=n??Dt({engineBaseUrl:r,preconditionNames:l.preconditions,webhookSecret:a}),[p,m]=await Promise.all([c,t]);await Kc({baseUrl:e,browser:m,preconditionResult:p,runId:o,specData:i,streaming:s,webhookSecret:a})}async function Kc({baseUrl:e,browser:t,preconditionResult:r,runId:n,specData:o,streaming:i,webhookSecret:s}){let a=await pe({label:"Spec executed",fn:()=>Dr({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 Jc({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 Jc({preconditionResult:e,webhookSecret:t}){e.apiUrl!=null&&await Lr({apiUrl:e.apiUrl,cookies:e.cookies,data:e.data,executed:e.executed,webhookSecret:t})}async function Yc({config:e,runId:t}){let r=await f({config:e,document:Wc,variables:{runId:t}});if(r.run?.workflow==null)throw new Error(`Run ${t} not found`);let n=Mc(mo,r.run.workflow),o=r.run.workflow.project?.engineBaseUrl??"";return{engineBaseUrl:e.engineUrl.length>0?e.engineUrl:o,workflow:n}}function Xc(e){if(e==null)throw new Error("Workflow has no spec");return Tr.decode(e)}var Qc=Hc.coerce.number().int().positive().catch(Bc);function Zc(){return Qc.parse(process.env.RIPPLO_RUN_TIMEOUT_MS)}async function ed(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)}}function td(e){return e instanceof De?e.errors.some(t=>t.extensions?.code==="THROTTLED"):!1}import st from"fs";import Ce from"fs";import rd from"os";import nt from"path";var nd=".local",od=".ripplo";function Fr(e){return nt.join(e,".ripplo",nd)}function ot(e){let t=Fr(e);Ce.existsSync(t)||Ce.mkdirSync(t,{recursive:!0});let r=nt.join(t,".gitignore");return Ce.existsSync(r)||Ce.writeFileSync(r,`*
185
- `),t}function it(e,t){return nt.join(Fr(e),t)}function Hr(){return nt.join(rd.homedir(),od)}function Mr(){let e=Hr();return Ce.existsSync(e)?Ce.chmodSync(e,448):Ce.mkdirSync(e,{mode:448,recursive:!0}),e}function ve(e){return nt.join(Hr(),e)}function ne(){let e=process.env.RIPPLO_TOKEN;if(e!=null&&e.trim().length>0)return e.trim();let t=ve("token");if(!st.existsSync(t))return null;let r=st.readFileSync(t,"utf8").trim();return r.length===0?null:r}function Br(e){Mr(),st.writeFileSync(ve("token"),e+`
186
- `,{mode:384})}function Wr(){let e=ve("token");return st.existsSync(e)?(st.unlinkSync(e),!0):!1}import{graphql as at}from"gql.tada";var uv=at(`
165
+ `,[Lo]);async function Xr({baseUrl:e,browser:t,config:r,headed:n,preconditionNames:o,runId:i,webhookSecret:s}){let a="unknown",l,c,p=!1,m=So(),h=performance.now();try{p=t==null,c=Xu({externalBrowser:t,headed:n});let T=o==null?void 0:Vt({engineBaseUrl:r.engineUrl,preconditionNames:o,runId:i,webhookSecret:s}),[{engineBaseUrl:$,workflow:g},H]=await Promise.all([de({label:"Run context resolved",fn:()=>nd({config:r,runId:i})}),de({label:"Streaming run started",fn:()=>Jr({config:r,runId:i})}),Ir({appUrl:e})]);a=g.name,l=H;let x=od(g.spec);f.info("Executing workflow: %s",g.name),await ad(Zu({abort:m,baseUrl:e,browserPromise:c,engineBaseUrl:$,preconditionPromise:T,runId:i,specData:x,streaming:l,webhookSecret:s,workflow:g}),sd(),m)}catch(T){throw ld(T)?T:(await ye(Qu({browserPromise:c,config:r,error:T,ownsBrowser:p,runId:i,streaming:l,workflowName:a}),Ju,"post-deadline cleanup").catch($=>{let g=$ instanceof Error?$.message:String($);f.warn("Post-deadline cleanup did not finish in budget: %s",g)}),new Mt(T))}finally{f.debug({elapsedMs:Math.round(performance.now()-h),runId:i},"run finished (totalMs=%d)",Math.round(performance.now()-h))}}var Mt=class extends Error{cause;constructor(t){let r=t instanceof Error?t.message:String(t);super(r),this.name="RunReportedError",this.cause=t}};function Xu({externalBrowser:e,headed:t}){return e!=null?Promise.resolve(e):de({label:"Browser launched",fn:()=>Le({headed:t})})}async function Qu({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 xo({error:a,runId:o,stack:l,workflowName:s}),i==null?await Yr({config:t,reason:a,runId:o}).catch(()=>{}):await i.complete({flush:!1,statusOverride:"failed",steps:[],summary:a}).catch(()=>{}),n&&e!=null&&await(await e.catch(()=>{}))?.close()}async function Zu({abort:e,baseUrl:t,browserPromise:r,engineBaseUrl:n,preconditionPromise:o,runId:i,specData:s,streaming:a,webhookSecret:l,workflow:c}){let p=o??Vt({engineBaseUrl:n,preconditionNames:c.preconditions,runId:i,webhookSecret:l}),[m,h]=await Promise.all([p,r]);await ed({abort:e,baseUrl:t,browser:h,preconditionResult:m,runId:i,specData:s,streaming:a,webhookSecret:l})}async function ed({abort:e,baseUrl:t,browser:r,preconditionResult:n,runId:o,specData:i,streaming:s,webhookSecret:a}){let l=await de({label:"Spec executed",fn:()=>Hr({abort:e,baseUrl:t,browser:r,cookies:n.cookies,extraVariables:n.data,observerTransport:n.apiUrl==null?void 0:{apiUrl:n.apiUrl,webhookSecret:a},onRecordingChunk:s.enqueueRecordingChunk,onStep:s.enqueueStep,runId:o,spec:i})});await rd({preconditionResult:n,runId:o,webhookSecret:a}),await s.complete({flush:!0,statusOverride:void 0,steps:l,summary:td(l)});let c=l.filter(m=>m.status==="passed").length,p=l.filter(m=>m.status==="failed").length;f.info("Run complete: %d passed, %d failed",c,p)}function td(e){let t=e.find(o=>o.status==="failed");if(t==null)return;let n=t.assertions.find(o=>o.status==="failed")?.detail??t.detail;return n==null||n.length===0?t.title:`${t.title} \u2014 ${n}`}async function rd({preconditionResult:e,runId:t,webhookSecret:r}){e.apiUrl!=null&&await Gr({apiUrl:e.apiUrl,data:e.data,executed:e.executed,runId:t,webhookSecret:r})}async function nd({config:e,runId:t}){let r=await cd(e).load(t);if(r.workflow==null)throw new Error(`Run ${t} not found`);let n=Gu(Lo,r.workflow),o=r.workflow.project?.engineBaseUrl??"";return{engineBaseUrl:e.engineUrl.length>0?e.engineUrl:o,workflow:n}}function od(e){if(e==null)throw new Error("Workflow has no spec");return Ur.decode(e)}var id=zu.coerce.number().int().positive().catch(Ku);function sd(){return id.parse(process.env.RIPPLO_RUN_TIMEOUT_MS)}async function ad(e,t,r){let n,o=new Promise((i,s)=>{n=setTimeout(()=>{r.fire(),s(new Error(`Run timed out after ${String(t)}ms`))},t)});try{await Promise.race([e,o])}finally{n!=null&&clearTimeout(n)}}function ld(e){return e instanceof _e?e.errors.some(t=>t.extensions?.code==="THROTTLED"):!1}var No=new Map;function cd(e){let t=`${e.ripploServerUrl}::${e.token}`,r=No.get(t);if(r!=null)return r;let n=new Oo.default(async o=>{let i=performance.now(),s=await y({config:e,document:Yu,variables:{ids:[...o]}}),a=new Map(s.runsByIds?.map(l=>[l.id,l])??[]);return f.debug({batchSize:o.length,elapsedMs:Math.round(performance.now()-i),op:"runsByIds"},"batched op flushed"),o.map(l=>a.get(l)??new Error(`Run ${l} not found`))},{cache:!1,batchScheduleFn:o=>{setTimeout(o,200)}});return No.set(t,n),n}import ct from"fs";import $e from"fs";import ud from"os";import st from"path";var dd=".local",pd=".ripplo";function Qr(e){return st.join(e,".ripplo",dd)}function at(e){let t=Qr(e);$e.existsSync(t)||$e.mkdirSync(t,{recursive:!0});let r=st.join(t,".gitignore");return $e.existsSync(r)||$e.writeFileSync(r,`*
166
+ `),t}function lt(e,t){return st.join(Qr(e),t)}function Zr(){return st.join(ud.homedir(),pd)}function en(){let e=Zr();return $e.existsSync(e)?$e.chmodSync(e,448):$e.mkdirSync(e,{mode:448,recursive:!0}),e}function Se(e){return st.join(Zr(),e)}function ie(){let e=process.env.RIPPLO_TOKEN;if(e!=null&&e.trim().length>0)return e.trim();let t=Se("token");if(!ct.existsSync(t))return null;let r=ct.readFileSync(t,"utf8").trim();return r.length===0?null:r}function tn(e){en(),ct.writeFileSync(Se("token"),e+`
167
+ `,{mode:384})}function rn(){let e=Se("token");return ct.existsSync(e)?(ct.unlinkSync(e),!0):!1}import{graphql as ut}from"gql.tada";var NS=ut(`
187
168
  query AgentReviewContextWorker($reviewId: String!) {
188
169
  agentReview(id: $reviewId) {
189
170
  id
@@ -197,11 +178,11 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
197
178
  }
198
179
  }
199
180
  }
200
- `);var pv=at(`
181
+ `);var OS=ut(`
201
182
  mutation StartAgentReviewWorker($reviewId: String!) {
202
183
  startAgentReview(reviewId: $reviewId)
203
184
  }
204
- `);var mv=at(`
185
+ `);var DS=ut(`
205
186
  mutation CompleteAgentReviewWorker(
206
187
  $reviewId: String!
207
188
  $markdown: String!
@@ -215,38 +196,48 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
215
196
  comments: $comments
216
197
  )
217
198
  }
218
- `);var fv=at(`
199
+ `);var LS=ut(`
219
200
  mutation UpdateAgentReviewProgressWorker($reviewId: String!, $text: String!) {
220
201
  updateAgentReviewProgress(reviewId: $reviewId, text: $text)
221
202
  }
222
- `);var gv=at(`
203
+ `);var _S=ut(`
223
204
  mutation FailAgentReviewWorker($reviewId: String!, $reason: String!) {
224
205
  failAgentReview(reviewId: $reviewId, reason: $reason)
225
206
  }
226
- `);import{exec as cd}from"child_process";import{createAuthClient as id}from"better-auth/client";import{deviceAuthorizationClient as sd}from"better-auth/client/plugins";function fo({baseURL:e}){return id({baseURL:e,fetchOptions:{headers:{"User-Agent":"Ripplo CLI"}},plugins:[sd()]})}import{z as qr}from"zod";var ad="https://ripplo.ai";function X(){return _t().RIPPLO_SERVER_URL}function yo(){return _t().RIPPLO_PROJECT_ID}var ld=qr.object({RIPPLO_PROJECT_ID:qr.string().min(1).optional(),RIPPLO_SERVER_URL:qr.string().min(1).default(ad)}),go;function _t(){return go??=ld.parse(process.env),go}var dd=5e3,ho="ripplo-cli";async function wo({onDeviceCode:e,url:t}){let r=t??_t().RIPPLO_SERVER_URL,n=fo({baseURL:r}),o=await n.device.code({client_id:ho});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}),yd(a);let l=await ud({authClient:n,deviceCode:i});return Br(l),l}async function ud({authClient:e,deviceCode:t}){for(;;){await fd(dd);let r=await e.device.token({client_id:ho,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(!md(r.error.error))throw new Error(`Authorization failed: ${r.error.error_description}`)}}var pd=new Set(["authorization_pending","slow_down"]);function md(e){return pd.has(e)}function fd(e){return new Promise(t=>{setTimeout(t,e)})}function gd(){return process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open"}function yd(e){let t=gd();cd(`${t} "${e}"`,()=>{})}function Se({serverUrl:e,token:t}){return{appUrl:"",cwd:process.cwd(),engineUrl:"",projectId:"",ripploServerUrl:e,token:t,webhookSecret:""}}import hd from"fs";import wd from"path";function C(e){return hd.existsSync(wd.join(e,".ripplo"))}var vd=bd(`
207
+ `);import Vo from"fs";import Wt from"path";import{config as gd}from"dotenv";import{z as Ht}from"zod";import dt from"fs";import on from"path";import{z as Bt}from"zod";var _o=on.join(".ripplo","project.json"),nn=[".env",".env.local"],md=Bt.object({envFiles:Bt.array(Bt.string().min(1)).optional(),projectId:Bt.string().min(1)});function sn(e){return on.join(e,_o)}function an(e){let t=sn(e);if(!dt.existsSync(t))throw new Error(`ripplo: missing ${_o}. Run \`ripplo init\` to create it.`);let r=JSON.parse(dt.readFileSync(t,"utf8")),n=md.parse(r);return{envFiles:n.envFiles??nn,projectId:n.projectId}}function ln(e){let t=sn(e);if(dt.existsSync(t))try{return an(e)}catch{return}}function Uo({cwd:e,envFiles:t,projectId:r}){let n=sn(e);dt.mkdirSync(on.dirname(n),{recursive:!0});let o={projectId:r};t!=null&&!fd(t)&&(o.envFiles=[...t]),dt.writeFileSync(n,JSON.stringify(o,null,2)+`
208
+ `)}function fd(e){return e.length!==nn.length?!1:e.every((t,r)=>t===nn[r])}function Fo(e){let r=ln(e)?.envFiles??[".env",".env.local"],n=Wt.join(e,".ripplo");r.forEach(o=>{let i=Wt.resolve(n,o);Vo.existsSync(i)&&gd({override:!0,path:i,quiet:!0})}),cn=void 0}var yd=Ht.object({RIPPLO_APP_URL:Ht.url(),RIPPLO_ENGINE_URL:Ht.url(),RIPPLO_WEBHOOK_SECRET:Ht.string().min(1)}),cn;function Fe(){return cn??=hd(),cn}function hd(){let e=yd.safeParse(process.env);if(!e.success){let r=e.error.issues.map(s=>` ${s.path.join(".")}: ${s.message}`).join(`
209
+ `),n=un(process.cwd()),o=n.map(s=>` ${s}`).join(`
210
+ `),i=n.length>0?`
211
+
212
+ Declared env file(s) not found at this path:
213
+ ${o}
214
+ 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:
215
+ ${r}
216
+
217
+ 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 un(e){let r=ln(e)?.envFiles??[],n=Wt.join(e,".ripplo");return r.map(o=>Wt.resolve(n,o)).filter(o=>!Vo.existsSync(o))}import lw from"yargs";import{hideBin as cw}from"yargs/helpers";import{graphql as jd}from"gql.tada";import{exec as kd}from"child_process";import{createAuthClient as wd}from"better-auth/client";import{deviceAuthorizationClient as bd}from"better-auth/client/plugins";function Mo({baseURL:e}){return wd({baseURL:e,fetchOptions:{headers:{"User-Agent":"Ripplo CLI"}},plugins:[bd()]})}import{z as dn}from"zod";var vd="https://ripplo.ai";function Z(){return qt().RIPPLO_SERVER_URL}function Ho(){return qt().RIPPLO_PROJECT_ID}var Sd=dn.object({RIPPLO_PROJECT_ID:dn.string().min(1).optional(),RIPPLO_SERVER_URL:dn.string().min(1).default(vd)}),Bo;function qt(){return Bo??=Sd.parse(process.env),Bo}var Rd=5e3,Wo="ripplo-cli";async function qo({onDeviceCode:e,url:t}){let r=t??qt().RIPPLO_SERVER_URL,n=Mo({baseURL:r}),o=await n.device.code({client_id:Wo});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}),Ad(a);let l=await Pd({authClient:n,deviceCode:i});return tn(l),l}async function Pd({authClient:e,deviceCode:t}){for(;;){await Cd(Rd);let r=await e.device.token({client_id:Wo,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(!Ed(r.error.error))throw new Error(`Authorization failed: ${r.error.error_description}`)}}var xd=new Set(["authorization_pending","slow_down"]);function Ed(e){return xd.has(e)}function Cd(e){return new Promise(t=>{setTimeout(t,e)})}function Td(){return process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open"}function Ad(e){let t=Td();kd(`${t} "${e}"`,()=>{})}function ke({serverUrl:e,token:t}){return{appUrl:"",cwd:process.cwd(),engineUrl:"",projectId:"",ripploServerUrl:e,token:t,webhookSecret:""}}import Id from"fs";import $d from"path";function A(e){return Id.existsSync($d.join(e,".ripplo"))}var Nd=jd(`
227
218
  query AuthViewer {
228
219
  currentUser {
229
220
  name
230
221
  email
231
222
  }
232
223
  }
233
- `);async function bo(){let e=X(),t=ne();if(t!=null){let s=await zr({serverUrl:e,token:t});if(s!=null){process.stdout.write(`Already signed in as ${s.email}. Run \`ripplo auth logout\` to switch.
224
+ `);async function zo(){let e=Z(),t=ie();if(t!=null){let s=await pn({serverUrl:e,token:t});if(s!=null){process.stdout.write(`Already signed in as ${s.email}. Run \`ripplo auth logout\` to switch.
234
225
  `);return}process.stdout.write(`Your saved session expired \u2014 let's sign you back in.
235
226
 
236
- `)}let r=await wo({url:e,onDeviceCode:s=>{process.stdout.write(`Opening your browser to finish sign-in.
227
+ `)}let r=await qo({url:e,onDeviceCode:s=>{process.stdout.write(`Opening your browser to finish sign-in.
237
228
  `),process.stdout.write(`If it didn't open, visit: ${s.verificationUrl}
238
229
  `),process.stdout.write(`Verification code: ${s.userCode}
239
230
 
240
231
  `),process.stdout.write(`Waiting for you to approve...
241
- `)}}),n=await zr({serverUrl:e,token:r}),o=C(process.cwd()),i=o?"Welcome back":"Welcome to Ripplo";process.stdout.write(`
232
+ `)}}),n=await pn({serverUrl:e,token:r}),o=A(process.cwd()),i=o?"Welcome back":"Welcome to Ripplo";process.stdout.write(`
242
233
  `),process.stdout.write(n==null?`${i}.
243
- `:`${i}, ${Sd(n)}.
244
- `),process.stdout.write(`Session saved to ${ve("token")}.
245
- `),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 Sd(e){let t=e.name.trim().split(/\s+/)[0];return t!=null&&t.length>0?t:e.email}async function zr({serverUrl:e,token:t}){try{let n=(await f({config:Se({serverUrl:e,token:t}),document:vd,variables:void 0})).currentUser;return n==null?null:{email:n.email,name:n.name}}catch{return null}}async function vo(){let e=ne();e==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login`.\n"),process.exit(1));let t=X(),r=await zr({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})
246
- `)}function So(){if(!Wr()){process.stdout.write(`No token to remove.
247
- `);return}process.stdout.write(`Removed ${ve("token")}
248
- `)}import{createHash as kd}from"crypto";import lt from"fs/promises";import Ve from"path";import{z as Ut}from"zod";import{z as ko}from"zod";import{z as Ue}from"zod";import{z as u}from"zod";import{z as ke}from"zod";import{z as Ao}from"zod";import{z as T}from"zod";import{z as Q}from"zod";import{z as Gr}from"zod";import{z as x}from"zod";var Rd=Ut.object({__codec:Ut.string().min(1),data:Ut.unknown(),version:Ut.number().int().positive()}),Pd=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}},xd=class extends Error{constructor(e){super(`Codec mismatch: expected "${e.expected}", got "${e.got}"`),this.name="CodecMismatchError"}};function Yr(e){return Eo({legacy:void 0,migrators:[],name:e,schemas:[]})}function Ed(e,t){let r=JSON.parse(t);return e.decode(r)}function Eo(e){return{initial:t=>Kr(t,{...e,schemas:[t]}),legacy:t=>Eo({...e,legacy:t})}}function Kr(e,t){return{build:()=>Cd(e,t),legacy:r=>Kr(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return Kr(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function Cd(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>Ad(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function Ad(e,t,r){let{data:n,version:o}=Id(t,r),i=Co(t,n,o);return e.parse(i)}function Id(e,t){let r=Rd.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new xd({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 Co(e,t,r){let n=e.schemas.length;if(r>n)throw new Pd({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 Co(e,s(i),r+1)}var Xr=Ue.object({depends:Ue.array(Ue.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:Ue.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:Ue.array(Ue.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."),Td=ke.object({by:ke.literal("testId"),value:ke.string().min(1)}),$d=ke.object({by:ke.literal("role"),name:ke.string().optional(),role:ke.string().min(1)}),E=ke.discriminatedUnion("by",[Td,$d]),ct=Ao.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),jd=Ao.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]),Nd=T.object({type:T.literal("static"),value:T.union([T.string(),T.number(),T.boolean()])}),Vt=T.object({name:T.string().min(1),type:T.literal("variable")}),Od=T.discriminatedUnion("type",[Nd,Vt]),ae=T.discriminatedUnion("type",[T.object({type:T.literal("static"),value:T.string()}),Vt]),Dd=T.discriminatedUnion("type",[T.object({type:T.literal("static"),value:T.number().int().nonnegative()}),Vt]),Ld=T.discriminatedUnion("type",[T.object({type:T.literal("static"),value:T.union([T.string(),T.number(),T.boolean()])}),Vt]),_d=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()},Ro=500,Ud=u.object({...v,type:u.literal("goto"),url:ae}),Vd=u.object({...v,locator:E,type:u.literal("click")}),Fd=u.object({...v,locator:E,type:u.literal("fill"),value:ae}),Hd=u.object({...v,locator:E,type:u.literal("select"),value:ae}),Md=u.object({...v,locator:E,type:u.literal("hover")}),Bd=u.object({...v,key:u.string().min(1),locator:E.optional(),type:u.literal("press")}),Wd=u.object({...v,locator:E,type:u.literal("check")}),qd=u.object({...v,locator:E,type:u.literal("uncheck")}),zd=u.object({...v,height:u.number().int().positive(),type:u.literal("setViewport"),width:u.number().int().positive()}),Gd=u.object({...v,message:u.string().min(1),type:u.literal("fail")}),Kd=u.object({...v,type:u.literal("setVariable"),value:Od,variable:u.string().min(1)}),Jd=u.object({...v,locator:E,type:u.literal("extractText"),variable:u.string().min(1)}),Yd=u.object({...v,files:u.array(u.string()).min(1),locator:E,type:u.literal("upload")}),Xd=u.object({...v,locator:E,type:u.literal("dblclick")}),Qd=u.object({...v,source:E,target:E,type:u.literal("drag")}),Zd=u.object({...v,locator:E,type:u.literal("scrollIntoView")}),eu=u.object({...v,locator:E,type:u.literal("type"),value:ae}),tu=u.object({...v,locator:E,type:u.literal("focus")}),ru=u.object({...v,locator:E,type:u.literal("clear")}),nu=u.object({...v,locator:E,type:u.literal("rightClick")}),ou=u.object({...v,action:u.enum(["accept","dismiss"]),promptText:u.string().optional(),type:u.literal("handleDialog")}),iu=u.object({...v,action:u.enum(["read","write"]),type:u.literal("clipboard"),value:ae.optional(),variable:u.string().min(1).optional()}),su=u.object({...v,permission:u.string().min(1),state:u.enum(["granted","prompt"]),type:u.literal("setPermission")}),au=u.object({...v,locator:E,type:u.literal("assertVisible")}),lu=u.object({...v,locator:E,type:u.literal("assertNotVisible")}),cu=u.object({...v,expected:ae,locator:E,operator:ct,type:u.literal("assertText")}),du=u.object({...v,expected:ae,operator:ct,type:u.literal("assertUrl")}),uu=u.object({...v,expected:Dd,locator:E,operator:jd,type:u.literal("assertCount")}),pu=u.object({...v,expected:ae,locator:E,operator:ct,type:u.literal("assertValue")}),mu=u.object({...v,attribute:u.string().min(1),expected:ae,locator:E,operator:ct,type:u.literal("assertAttribute")}),fu=u.object({...v,locator:E,type:u.literal("assertEnabled")}),gu=u.object({...v,locator:E,type:u.literal("assertDisabled")}),yu=u.object({...v,expected:ae,operator:ct,type:u.literal("assertTitle")}),hu=u.object({...v,locator:E,type:u.literal("assertChecked")}),wu=u.object({...v,locator:E,type:u.literal("assertNotChecked")}),bu=u.object({...v,locator:E,type:u.literal("assertFocused")}),vu=u.object({...v,locator:E,type:u.literal("assertNotFocused")}),Su=u.object({...v,budget:u.enum(["fast","slow","async"]),observer:u.string().min(1).max(200),params:u.record(u.string().max(200),Ld),type:u.literal("assertObserver")}),ku=u.discriminatedUnion("type",[Ud,Vd,Fd,Hd,Md,Bd,Wd,qd,au,lu,cu,du,uu,pu,mu,fu,gu,zd,Gd,Kd,Jd,Yd,Xd,Qd,Zd,eu,tu,ru,nu,ou,iu,su,yu,hu,wu,bu,vu,Su]),Io=u.object({entryNode:u.string().min(1).max(200),nodes:u.record(u.string().max(200),ku).refine(e=>Object.keys(e).length<=Ro,`Workflow has more than ${String(Ro)} nodes`),uiOnly:u.boolean().optional(),variableNamespaces:u.record(u.string().max(200),u.string().max(500)).optional(),variables:u.record(u.string().max(200),_d).optional()}),Ru=ko.record(ko.string().max(200),Xr),Pu={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},xu={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},NS=Yr("workflow-spec").legacy(Pu).initial(Io).build(),OS=Yr("precondition-map").legacy(xu).initial(Ru).build(),Eu=["fast","slow","async"],To=Gr.object({budget:Gr.enum(Eu).describe("Polling budget tier: fast | slow | async"),description:Gr.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",Cu=".ripplo/fixtures",$o=5e3,Au=x.record(x.string().max(200),x.string().max(200)),jo=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:Au,slug:x.string().max(200),sourcePath:x.string().max(500).optional(),spec:Io}),Iu=x.object({sha256:x.string().regex(/^[0-9a-f]{64}$/u),size:x.number().int().nonnegative()}),Tu=x.record(x.string().min(1).max(500),Iu),$u=x.object({observers:x.record(x.string().max(200),To),preconditions:x.record(x.string().max(200),Xr),tests:x.array(jo).max($o)}),ju=x.object({fixtures:Tu,observers:x.record(x.string().max(200),To),preconditions:x.record(x.string().max(200),Xr),tests:x.array(jo).max($o)}),No=Yr("ripplo-lockfile").initial($u).upgrade(ju,e=>({...e,fixtures:{}})).build();function Oo(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 Jr(e){let t=No.encode(e);return`${JSON.stringify(t,_u(t),2)}
249
- `}async function Ft({cwd:e}){let t=Ve.join(e,le),r=await Lu(t);return r==null?null:Ed(No,r)}var Po=10*1024*1024,xo=50*1024*1024;async function ce({cwd:e,result:t}){let r=await Nu({cwd:e,result:t}),n=Oo(r),o=Ve.join(e,le);await lt.mkdir(Ve.dirname(o),{recursive:!0}),await lt.writeFile(o,Jr(n),"utf8")}async function Nu({cwd:e,result:t}){let r=Du(t);if(r.size===0)return{...t,fixtures:{}};let n=Ve.join(e,Cu),o=[...r].toSorted((a,l)=>a.localeCompare(l)),i=await Promise.all(o.map(async a=>{let l=await Ou({fixturesRoot:n,name:a});if(l.size>Po)throw new Error(`Fixture "${a}" is ${String(l.size)} bytes; exceeds per-file limit of ${String(Po)} bytes`);return[a,l]}));if(i.reduce((a,[,l])=>a+l.size,0)>xo)throw new Error(`Total fixtures size exceeds limit of ${String(xo)} bytes`);return{...t,fixtures:Object.fromEntries(i)}}async function Ou({fixturesRoot:e,name:t}){if(t.includes("..")||Ve.isAbsolute(t))throw new Error(`Invalid fixture name "${t}": must be a path under .ripplo/fixtures/`);let r=Ve.join(e,t),n=await lt.lstat(r).catch(s=>{throw Do(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 lt.readFile(r);return{sha256:kd("sha256").update(o).digest("hex"),size:o.byteLength}}function Du(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 Ht({compiled:e,existing:t}){if(t==null)return"missing";let r=Jr(Oo(e)),n=Jr(t);return r===n?"match":"stale"}async function Lu(e){try{return await lt.readFile(e,"utf8")}catch(t){if(Do(t)&&t.code==="ENOENT")return null;throw t}}function Do(e){return e instanceof Error&&"code"in e}function _u(e){return function(r,n){return n===e||!Uu(n)?n:Object.fromEntries(Object.entries(n).toSorted(([o],[i])=>o.localeCompare(i)))}}function Uu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import dt from"fs";import Wt from"path";var Qr=["**/src/**","**/app/**","**/apps/**","**/pages/**","**/routes/**","**/components/**","**/server/**","**/api/**","**/backend/**","**/features/**","**/modules/**","**/views/**","**/ui/**","**/hooks/**","**/contexts/**","**/providers/**","**/controllers/**","**/handlers/**","**/resolvers/**","**/services/**","**/middleware/**","**/lib/**"],Re=["**/*.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 Lo(e){return e.data}function _o(e){return{as(t){return{data:{label:t,node:e}}}}}function Mt(e){let t=e.getPreconditions(),r=e.getObservers(),n=e.getTests();Vu(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{fixtures:{},observers:i,preconditions:o,tests:s}}function Vu(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}=Mu(e.requiresKeys),i=e.startsAtFn==null?void 0:e.startsAtFn(o),s=e.stepsFn==null?[]:e.stepsFn(o),a=i==null?s:[Hu(i),...s],l=Bu(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=qu(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 Hu(e){return _o({type:"goto",url:{type:"static",value:e}}).as(`navigate to ${e}`)}function Mu(e){let t=new Set,r={};return Object.keys(e).forEach(n=>{r[n]=new Proxy({},{get(o,i){if(typeof i=="string"){let s=`${n}.${i}`;return t.add(s),`{{${s}}}`}}})}),{accessedKeys:t,vars:r}}function Bu(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}=Lo(e);return{...o,id:t,label:n,next:r}}function qu(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 qS,WebhookVerificationError as zS}from"standardwebhooks";import{z as k}from"zod";var KS=k.object({preconditions:k.array(k.string().min(1))}),JS=k.object({data:k.record(k.string(),k.record(k.string(),k.union([k.string(),k.number(),k.boolean()]))),preconditions:k.array(k.string().min(1))}),YS=k.object({observer:k.string().min(1).max(200),params:k.record(k.string().max(200),k.union([k.string(),k.number(),k.boolean()]))}),zu=k.discriminatedUnion("kind",[k.object({kind:k.literal("pass")}),k.object({kind:k.literal("retry"),reason:k.string()}),k.object({kind:k.literal("fail"),reason:k.string()})]),XS=k.object({error:k.string().optional(),outcome:zu.optional(),success:k.boolean()});function Fe(e){let t=[];return e.tests.forEach(r=>{let n=Gu(r),o=i=>{t.push({...i,test:r.slug})};yp.forEach(i=>{i(n,r,o)})}),{diagnostics:t}}function Gu(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 Ju(e,t,r){Object.keys(t.spec.variables??{}).length>0&&e.forEach(o=>{if(o.type==="fill"&&Vo(o.value)){let i=o.value.value;!Fo(i)&&rp(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 Yu(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 Qu(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 Zu(e,t,r){let n=0;e.forEach((o,i)=>{if(!(i===0&&o.type==="goto")){if(He(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 ep(e,t,r){if(e.length===0)return;let n=e.at(-1);n!=null&&!He(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 tp(e,t,r){t.implemented&&e.length===0&&r({message:"Test has zero steps",rule:"no-empty-steps",step:void 0})}function Vo(e){return!(typeof e!="object"||e==null||!("type"in e)||e.type!=="static"||!("value"in e)||typeof e.value!="string")}function Fo(e){return e.includes("{{")}function rp(e){return e.includes("@")||/\b[a-f0-9]{8,}\b/.test(e)||/^(test|ripplo|example|sample|demo)/i.test(e)}function He(e){return e.type.startsWith("assert")}var np=new Set(["assertText","assertValue","assertCount","assertUrl","assertNotVisible","assertChecked","assertNotChecked","assertAttribute","assertDisabled","assertEnabled"]);function op(e){return np.has(e.type)}function ip(e,t,r){!t.implemented||e.length===0||e.some(n=>He(n))||r({message:"Test has zero assertion steps \u2014 cannot verify expectedOutcome. Add assert.* steps.",rule:"no-assertions",step:void 0})}function sp(e,t,r){if(!t.implemented||e.length<=3)return;let n=e.filter(i=>He(i)).length;if(n===0)return;let o=n/e.length;if(o<.15){let i=Math.round(o*100);r({message:`Only ${String(n)}/${String(e.length)} steps are assertions (${String(i)}%) \u2014 add more verification between actions`,rule:"low-assertion-ratio",step:void 0})}}function Zr(e){if(!("locator"in e)||e.locator==null)return;let t=e.locator;return t.by==="role"?`role:${t.role}:${t.name??""}`:`testId:${t.value}`}function ap(e,t,r){e.forEach((n,o)=>{if(n.type!=="click")return;let i=Zr(n);if(i==null)return;let s=e.slice(o+1,o+4);s.find(c=>c.type==="assertVisible"&&Zr(c)===i)==null||s.some(c=>op(c)||He(c)&&Zr(c)!==i)||r({message:`click "${n.label??n.id}" is followed only by assert.visible on the same locator \u2014 verifies nothing about the click's effect`,rule:"tautological-post-click-assert",step:n.label??n.id})})}var lp=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 en(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=3&&!lp.has(t))}function cp(e){let t=e.label==null?[]:en(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,...en(n)]}function dp(e,t,r){if(!t.implemented||e.length===0)return;let n=new Set(en(t.expectedOutcome));if(n.size===0)return;let o=e.filter(s=>He(s));if(o.length===0)return;o.some(s=>cp(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 up=/save|submit|create|delete|remove|send|invite|update|confirm|publish|apply|pay|subscribe|upgrade|cancel|archive|rename/i;function Uo(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 up.test(r)}function pp(e,t,r){!t.implemented||t.spec.uiOnly===!0||e.forEach((n,o)=>{if(!Uo(n)||"uiOnly"in n&&n.uiOnly===!0)return;let i=e.slice(o+1),s=i.findIndex(p=>Uo(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 mp(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])=>Vo(a)&&Fo(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 fp(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 gp(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 yp=[Ku,Ju,gp,Yu,Xu,Qu,Zu,ep,tp,ip,sp,ap,dp,pp,mp,fp];import Hp from"picomatch";import{execFileSync as hp,spawnSync as wp}from"child_process";function M(e,t){return hp("git",[...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}function Ho(e,t){let r=wp("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 Mo from"remeda";var Bo=[["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"]],bp=new Map([["button","click"],["link","navigate"],["textbox","input"],["searchbox","input"],["combobox","select"],["listbox","select"]]),vp=[[/(?:^|[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 Bt({filePath:e,source:t}){let r=w.createSourceFile(e,t,w.ScriptTarget.Latest,!0,w.ScriptKind.TSX);return r.statements.flatMap(n=>Sp({filePath:e,sf:r,stmt:n}))}function Sp({filePath:e,sf:t,stmt:r}){let n=Rp(r);if(n==null||kp(n))return[];let o=Wo(r,t).map(i=>({id:`${e}#${n}.${i.kind}[${i.label}]`,line:i.line}));return Mo.uniqueBy(o,i=>i.id)}function kp(e){return e.endsWith("Fragment")||e.endsWith("Skeleton")||/^use[A-Z]/.test(e)||/^[A-Z][A-Z0-9_]*$/.test(e)}function Rp(e){if(w.isExportAssignment(e))return Pp(e.expression);if(!xp(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 Pp(e){return w.isIdentifier(e)?e.text:(w.isFunctionExpression(e)||w.isClassExpression(e))&&e.name!=null?e.name.text:"default"}function xp(e){if(!w.canHaveModifiers(e))return!1;let t=w.getModifiers(e);return t!=null&&t.some(r=>r.kind===w.SyntaxKind.ExportKeyword)}function Wo(e,t){let r=Ep(e,t),n=e.getChildren(t).flatMap(o=>Wo(o,t));return r==null?n:[r,...n]}function Ep(e,t){let r=Cp(e);if(r==null)return null;let n=Ap(r);if(n==null)return null;let o=Np(r,n);return o==null?null:{kind:n,label:o,line:Fp(t,e.getStart(t))}}function Cp(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 Ap({attrs:e,tag:t}){let r=de(e,"role");return r!=null?bp.get(r)??null:Tp(t,e)??$p(t)??jp(e)}var Ip=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 Tp(e,t){return Ip.get(e)?.(t)??null}function $p(e){return/^[A-Z]/.test(e)?vp.find(([t])=>t.test(e))?.[1]??null:null}function jp(e){return Bo.find(([t])=>Lp(e,t))?.[1]??null}function Np({attrs:e,children:t,tag:r},n){return n==="navigate"?de(e,"href")??de(e,"to"):de(e,"aria-label")??de(e,"label")??de(e,"title")??de(e,"name")??de(e,"placeholder")??(Op(r)?void 0:Vp(t))??Dp(e,n)}function Op(e){return e==="input"||e==="textarea"||e==="select"}function Dp(e,t){let r=Bo.find(([,o])=>o===t)?.[0];if(r==null)return;let n=_p(e,r);if(n!=null){if(w.isIdentifier(n))return n.text;if(w.isArrowFunction(n)||w.isFunctionExpression(n))return qo(n.body)}}function qo(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,qo)}function Lp(e,t){return e.properties.some(r=>w.isJsxAttribute(r)&&w.isIdentifier(r.name)&&r.name.text===t)}function zo(e,t){return e.properties.find(r=>w.isJsxAttribute(r)&&w.isIdentifier(r.name)&&r.name.text===t)}function de(e,t){let r=zo(e,t);return r==null?void 0:Up(r.initializer)}function _p(e,t){let r=zo(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 Ko(e.expression)}function Vp(e){let t=e.flatMap(r=>Go(r)).join(" ").trim();return t.length===0?void 0:t}function Go(e){if(w.isJsxText(e)){let t=e.text.trim();return t.length===0?[]:[t]}if(w.isJsxExpression(e)){let t=Ko(e.expression);return t==null?[]:[t]}return w.isJsxElement(e)?e.children.flatMap(t=>Go(t)):[]}function Ko(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 Fp(e,t){return e.getLineAndCharacterOfPosition(t).line+1}var Mp=Wt.join(".ripplo","coverage.d.ts");function Me({cwd:e}){Bp({cwd:e,ignorePaths:Re})}function Bp({cwd:e,ignorePaths:t}){let r=Be({cwd:e,ignorePaths:t});zp({content:qp(r),cwd:e})}function Be({cwd:e,ignorePaths:t}){let n=Wp({cwd:e,ignorePaths:t}).flatMap(o=>tn({cwd:e,file:o}));return[...new Set(n)].sort((o,i)=>o.localeCompare(i))}function Wp({cwd:e,ignorePaths:t}){let r=M(["ls-files","--cached","--others","--exclude-standard","-z"],e),n=Hp([...t]);return r.split("\0").filter(o=>o.length>0&&/\.(tsx|jsx)$/.test(o)).filter(o=>!n(o)).filter(o=>dt.existsSync(Wt.join(e,o)))}function tn({cwd:e,file:t}){let r=dt.readFileSync(Wt.join(e,t),"utf8");return Bt({filePath:t,source:r}).map(n=>n.id)}function qp(e){let t=`// GENERATED \u2014 do not edit
234
+ `:`${i}, ${Od(n)}.
235
+ `),process.stdout.write(`Session saved to ${Se("token")}.
236
+ `),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 Od(e){let t=e.name.trim().split(/\s+/)[0];return t!=null&&t.length>0?t:e.email}async function pn({serverUrl:e,token:t}){try{let n=(await y({config:ke({serverUrl:e,token:t}),document:Nd,variables:void 0})).currentUser;return n==null?null:{email:n.email,name:n.name}}catch{return null}}async function Go(){let e=ie();e==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login`.\n"),process.exit(1));let t=Z(),r=await pn({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})
237
+ `)}function Ko(){if(!rn()){process.stdout.write(`No token to remove.
238
+ `);return}process.stdout.write(`Removed ${Se("token")}
239
+ `)}import{createHash as Dd}from"crypto";import pt from"fs/promises";import Be from"path";import{z as zt}from"zod";import{z as Jo}from"zod";import{z as Me}from"zod";import{z as d}from"zod";import{z as Re}from"zod";import{z as ti}from"zod";import{z as O}from"zod";import{z as ee}from"zod";import{z as mn}from"zod";import{z as E}from"zod";var Ld=zt.object({__codec:zt.string().min(1),data:zt.unknown(),version:zt.number().int().positive()}),_d=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}},Ud=class extends Error{constructor(e){super(`Codec mismatch: expected "${e.expected}", got "${e.got}"`),this.name="CodecMismatchError"}};function yn(e){return Zo({legacy:void 0,migrators:[],name:e,schemas:[]})}function Vd(e,t){let r=JSON.parse(t);return e.decode(r)}function Zo(e){return{initial:t=>fn(t,{...e,schemas:[t]}),legacy:t=>Zo({...e,legacy:t})}}function fn(e,t){return{build:()=>Fd(e,t),legacy:r=>fn(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return fn(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function Fd(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>Md(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function Md(e,t,r){let{data:n,version:o}=Bd(t,r),i=ei(t,n,o);return e.parse(i)}function Bd(e,t){let r=Ld.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new Ud({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 ei(e,t,r){let n=e.schemas.length;if(r>n)throw new _d({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 ei(e,s(i),r+1)}var hn=Me.object({depends:Me.array(Me.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:Me.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:Me.array(Me.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."),Hd=Re.object({by:Re.literal("testId"),value:Re.string().min(1)}),Wd=Re.object({by:Re.literal("role"),name:Re.string().optional(),role:Re.string().min(1)}),C=Re.discriminatedUnion("by",[Hd,Wd]),mt=ti.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),qd=ti.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]),zd=O.object({type:O.literal("static"),value:O.union([O.string(),O.number(),O.boolean()])}),Gt=O.object({name:O.string().min(1),type:O.literal("variable")}),Gd=O.discriminatedUnion("type",[zd,Gt]),se=O.discriminatedUnion("type",[O.object({type:O.literal("static"),value:O.string()}),Gt]),Kd=O.discriminatedUnion("type",[O.object({type:O.literal("static"),value:O.number().int().nonnegative()}),Gt]),Jd=O.discriminatedUnion("type",[O.object({type:O.literal("static"),value:O.union([O.string(),O.number(),O.boolean()])}),Gt]),Yd=ee.discriminatedUnion("type",[ee.object({default:ee.string().optional(),type:ee.literal("string")}),ee.object({default:ee.number().optional(),type:ee.literal("number")}),ee.object({default:ee.boolean().optional(),type:ee.literal("boolean")}),ee.object({key:ee.string().min(1),type:ee.literal("env")})]),k={id:d.string().min(1).max(200),label:d.string().max(500).optional(),next:d.string().max(200).optional(),uiOnly:d.boolean().optional()},Yo=500,Xd=d.object({...k,type:d.literal("goto"),url:se}),Qd=d.object({...k,locator:C,modifier:d.enum(["Alt","Control","Meta","Shift"]).optional(),type:d.literal("click")}),Zd=d.object({...k,locator:C,type:d.literal("fill"),value:se}),ep=d.object({...k,locator:C,type:d.literal("select"),value:se}),tp=d.object({...k,locator:C,type:d.literal("hover")}),rp=d.object({...k,key:d.string().min(1),locator:C.optional(),type:d.literal("press")}),np=d.object({...k,locator:C,type:d.literal("check")}),op=d.object({...k,locator:C,type:d.literal("uncheck")}),ip=d.object({...k,height:d.number().int().positive(),type:d.literal("setViewport"),width:d.number().int().positive()}),sp=d.object({...k,message:d.string().min(1),type:d.literal("fail")}),ap=d.object({...k,type:d.literal("setVariable"),value:Gd,variable:d.string().min(1)}),lp=d.object({...k,locator:C,type:d.literal("extractText"),variable:d.string().min(1)}),cp=d.object({...k,files:d.array(d.string()).min(1),locator:C,type:d.literal("upload")}),up=d.object({...k,locator:C,type:d.literal("dblclick")}),dp=d.object({...k,source:C,target:C,type:d.literal("drag")}),pp=d.object({...k,locator:C,type:d.literal("scrollIntoView")}),mp=d.object({...k,locator:C,type:d.literal("type"),value:se}),fp=d.object({...k,locator:C,type:d.literal("focus")}),gp=d.object({...k,locator:C,type:d.literal("clear")}),yp=d.object({...k,locator:C,type:d.literal("rightClick")}),hp=d.object({...k,action:d.enum(["accept","dismiss"]),promptText:d.string().optional(),type:d.literal("handleDialog")}),wp=d.object({...k,action:d.enum(["read","write"]),type:d.literal("clipboard"),value:se.optional(),variable:d.string().min(1).optional()}),bp=d.object({...k,permission:d.string().min(1),state:d.enum(["granted","prompt"]),type:d.literal("setPermission")}),vp=d.object({...k,locator:C,type:d.literal("assertVisible")}),Sp=d.object({...k,locator:C,type:d.literal("assertNotVisible")}),kp=d.object({...k,expected:se,locator:C,operator:mt,type:d.literal("assertText")}),Rp=d.object({...k,expected:se,operator:mt,type:d.literal("assertUrl")}),Pp=d.object({...k,expected:Kd,locator:C,operator:qd,type:d.literal("assertCount")}),xp=d.object({...k,expected:se,locator:C,operator:mt,type:d.literal("assertValue")}),Ep=d.object({...k,attribute:d.string().min(1),expected:se,locator:C,operator:mt,type:d.literal("assertAttribute")}),Cp=d.object({...k,locator:C,type:d.literal("assertEnabled")}),Tp=d.object({...k,locator:C,type:d.literal("assertDisabled")}),Ap=d.object({...k,expected:se,operator:mt,type:d.literal("assertTitle")}),Ip=d.object({...k,locator:C,type:d.literal("assertChecked")}),$p=d.object({...k,locator:C,type:d.literal("assertNotChecked")}),jp=d.object({...k,locator:C,type:d.literal("assertFocused")}),Np=d.object({...k,locator:C,type:d.literal("assertNotFocused")}),Op=d.object({...k,budget:d.enum(["fast","slow","async"]),observer:d.string().min(1).max(200),params:d.record(d.string().max(200),Jd),type:d.literal("assertObserver")}),Dp=d.discriminatedUnion("type",[Xd,Qd,Zd,ep,tp,rp,np,op,vp,Sp,kp,Rp,Pp,xp,Ep,Cp,Tp,ip,sp,ap,lp,cp,up,dp,pp,mp,fp,gp,yp,hp,wp,bp,Ap,Ip,$p,jp,Np,Op]),ri=d.object({entryNode:d.string().min(1).max(200),nodes:d.record(d.string().max(200),Dp).refine(e=>Object.keys(e).length<=Yo,`Workflow has more than ${String(Yo)} nodes`),uiOnly:d.boolean().optional(),variableNamespaces:d.record(d.string().max(200),d.string().max(500)).optional(),variables:d.record(d.string().max(200),Yd).optional()}),Lp=Jo.record(Jo.string().max(200),hn),_p={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},Up={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},pR=yn("workflow-spec").legacy(_p).initial(ri).build(),mR=yn("precondition-map").legacy(Up).initial(Lp).build(),Vp=["fast","slow","async"],ni=mn.object({budget:mn.enum(Vp).describe("Polling budget tier: fast | slow | async"),description:mn.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."),ae=".ripplo/ripplo.lock",Fp=".ripplo/fixtures",oi=5e3,Mp=E.record(E.string().max(200),E.string().max(200)),ii=E.object({coverage:E.array(E.string().max(500)).max(2e3).default([]),expectedOutcome:E.string().max(2e3),name:E.string().max(200),preconditions:E.array(E.string().max(200)).max(1e3),requiresKeys:Mp,slug:E.string().max(200),sourcePath:E.string().max(500).optional(),spec:ri}),Bp=E.object({sha256:E.string().regex(/^[0-9a-f]{64}$/u),size:E.number().int().nonnegative()}),Hp=E.record(E.string().min(1).max(500),Bp),Wp=E.object({observers:E.record(E.string().max(200),ni),preconditions:E.record(E.string().max(200),hn),tests:E.array(ii).max(oi)}),qp=E.object({fixtures:Hp,observers:E.record(E.string().max(200),ni),preconditions:E.record(E.string().max(200),hn),tests:E.array(ii).max(oi)}),si=yn("ripplo-lockfile").initial(Wp).upgrade(qp,e=>({...e,fixtures:{}})).build();function ai(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 gn(e){let t=si.encode(e);return`${JSON.stringify(t,Yp(t),2)}
240
+ `}async function Kt({cwd:e}){let t=Be.join(e,ae),r=await Jp(t);return r==null?null:Vd(si,r)}var Xo=10*1024*1024,Qo=50*1024*1024;async function le({cwd:e,result:t}){let r=await zp({cwd:e,result:t}),n=ai(r),o=Be.join(e,ae);await pt.mkdir(Be.dirname(o),{recursive:!0}),await pt.writeFile(o,gn(n),"utf8")}async function zp({cwd:e,result:t}){let r=Kp(t);if(r.size===0)return{...t,fixtures:{}};let n=Be.join(e,Fp),o=[...r].toSorted((a,l)=>a.localeCompare(l)),i=await Promise.all(o.map(async a=>{let l=await Gp({fixturesRoot:n,name:a});if(l.size>Xo)throw new Error(`Fixture "${a}" is ${String(l.size)} bytes; exceeds per-file limit of ${String(Xo)} bytes`);return[a,l]}));if(i.reduce((a,[,l])=>a+l.size,0)>Qo)throw new Error(`Total fixtures size exceeds limit of ${String(Qo)} bytes`);return{...t,fixtures:Object.fromEntries(i)}}async function Gp({fixturesRoot:e,name:t}){if(t.includes("..")||Be.isAbsolute(t))throw new Error(`Invalid fixture name "${t}": must be a path under .ripplo/fixtures/`);let r=Be.join(e,t),n=await pt.lstat(r).catch(s=>{throw li(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 pt.readFile(r);return{sha256:Dd("sha256").update(o).digest("hex"),size:o.byteLength}}function Kp(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 Jt({compiled:e,existing:t}){if(t==null)return"missing";let r=gn(ai(e)),n=gn(t);return r===n?"match":"stale"}async function Jp(e){try{return await pt.readFile(e,"utf8")}catch(t){if(li(t)&&t.code==="ENOENT")return null;throw t}}function li(e){return e instanceof Error&&"code"in e}function Yp(e){return function(r,n){return n===e||!Xp(n)?n:Object.fromEntries(Object.entries(n).toSorted(([o],[i])=>o.localeCompare(i)))}}function Xp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import ft from"fs";import Qt from"path";var wn=["**/src/**","**/app/**","**/apps/**","**/pages/**","**/routes/**","**/components/**","**/server/**","**/api/**","**/backend/**","**/features/**","**/modules/**","**/views/**","**/ui/**","**/hooks/**","**/contexts/**","**/providers/**","**/controllers/**","**/handlers/**","**/resolvers/**","**/services/**","**/middleware/**","**/lib/**"],Pe=["**/*.gen.*","**/generated/**","**/*.d.ts","**/*.test.*","**/*.spec.*","**/node_modules/**","**/dist/**","**/build/**",".ripplo/**","**/*.md","**/.next/**","**/.turbo/**","**/.vercel/**","**/.svelte-kit/**","**/.nuxt/**","**/.astro/**","**/coverage/**","**/storybook-static/**","**/*.stories.*","**/*.story.*","**/cli/**","**/scripts/**","**/tools/**","**/__tests__/**","**/__mocks__/**","**/__fixtures__/**","**/*.config.*","**/*.setup.*","**/public/**","**/static/**","**/assets/**","**/migrations/**","**/prisma/migrations/**","**/scripts/**"];function ci(e){return e.data}function ui(e){return{as(t){return{data:{label:t,node:e}}}}}function Yt(e){let t=e.getPreconditions(),r=e.getObservers(),n=e.getTests();Qp(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=>Zp(a,t));return{fixtures:{},observers:i,preconditions:o,tests:s}}function Qp(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 Zp(e,t){let r=e.id,{accessedKeys:n,vars:o}=tm(e.requiresKeys),i=e.startsAtFn==null?void 0:e.startsAtFn(o),s=e.stepsFn==null?[]:e.stepsFn(o),a=i==null?s:[em(i),...s],l=rm(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=om(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 em(e){return ui({type:"goto",url:{type:"static",value:e}}).as(`navigate to ${e}`)}function tm(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 rm(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]=nm(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 nm(e,t,r){let{label:n,node:o}=ci(e);return{...o,id:t,label:n,next:r}}function om(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 PR,WebhookVerificationError as xR}from"standardwebhooks";import{z as D}from"zod";var di=D.union([D.string(),D.number(),D.boolean()]),im=D.record(D.string(),D.record(D.string(),di)),CR=D.object({batch:D.array(D.object({preconditions:D.array(D.string().min(1)),runId:D.string().min(1)})).min(1)}),TR=D.object({batch:D.array(D.object({data:im,preconditions:D.array(D.string().min(1)),runId:D.string().min(1)})).min(1)}),AR=D.object({observer:D.string().min(1).max(200),params:D.record(D.string().max(200),di)});function He(e){let t=[];return e.tests.forEach(r=>{let n=sm(r),o=i=>{t.push({...i,test:r.slug})};Am.forEach(i=>{i(n,r,o)})}),{diagnostics:t}}function sm(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 am(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 lm(e,t,r){Object.keys(t.spec.variables??{}).length>0&&e.forEach(o=>{if(o.type==="fill"&&mi(o.value)){let i=o.value.value;!fi(i)&&gm(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 cm(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 um(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 dm(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 pm(e,t,r){let n=0;e.forEach((o,i)=>{if(!(i===0&&o.type==="goto")){if(We(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 mm(e,t,r){if(e.length===0)return;let n=e.at(-1);n!=null&&!We(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 fm(e,t,r){t.implemented&&e.length===0&&r({message:"Test has zero steps",rule:"no-empty-steps",step:void 0})}function mi(e){return!(typeof e!="object"||e==null||!("type"in e)||e.type!=="static"||!("value"in e)||typeof e.value!="string")}function fi(e){return e.includes("{{")}function gm(e){return e.includes("@")||/\b[a-f0-9]{8,}\b/.test(e)||/^(test|ripplo|example|sample|demo)/i.test(e)}function We(e){return e.type.startsWith("assert")}var ym=new Set(["assertText","assertValue","assertCount","assertUrl","assertNotVisible","assertChecked","assertNotChecked","assertAttribute","assertDisabled","assertEnabled"]);function hm(e){return ym.has(e.type)}function wm(e,t,r){!t.implemented||e.length===0||e.some(n=>We(n))||r({message:"Test has zero assertion steps \u2014 cannot verify expectedOutcome. Add assert.* steps.",rule:"no-assertions",step:void 0})}function bm(e,t,r){if(!t.implemented||e.length<=3)return;let n=e.filter(i=>We(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 bn(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 vm(e,t,r){e.forEach((n,o)=>{if(n.type!=="click")return;let i=bn(n);if(i==null)return;let s=e.slice(o+1,o+4);s.find(c=>c.type==="assertVisible"&&bn(c)===i)==null||s.some(c=>hm(c)||We(c)&&bn(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 Sm=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 vn(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=3&&!Sm.has(t))}function km(e){let t=e.label==null?[]:vn(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,...vn(n)]}function Rm(e,t,r){if(!t.implemented||e.length===0)return;let n=new Set(vn(t.expectedOutcome));if(n.size===0)return;let o=e.filter(s=>We(s));if(o.length===0)return;o.some(s=>km(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 Pm=/save|submit|create|delete|remove|send|invite|update|confirm|publish|apply|pay|subscribe|upgrade|cancel|archive|rename/i;function pi(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 Pm.test(r)}function xm(e,t,r){!t.implemented||t.spec.uiOnly===!0||e.forEach((n,o)=>{if(!pi(n)||"uiOnly"in n&&n.uiOnly===!0)return;let i=e.slice(o+1),s=i.findIndex(p=>pi(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 Em(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])=>mi(a)&&fi(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 Cm(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 Tm(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 Am=[am,lm,Tm,cm,um,dm,pm,mm,fm,wm,bm,vm,Rm,xm,Em,Cm];import ef from"picomatch";import{execFileSync as Im,spawnSync as $m}from"child_process";function z(e,t){return Im("git",[...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}function gi(e,t){let r=$m("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 b from"typescript";import*as yi from"remeda";var hi=[["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"]],jm=new Map([["button","click"],["link","navigate"],["textbox","input"],["searchbox","input"],["combobox","select"],["listbox","select"]]),Nm=[[/(?:^|[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 Xt({filePath:e,source:t}){let r=b.createSourceFile(e,t,b.ScriptTarget.Latest,!0,b.ScriptKind.TSX);return r.statements.flatMap(n=>Om({filePath:e,sf:r,stmt:n}))}function Om({filePath:e,sf:t,stmt:r}){let n=Lm(r);if(n==null||Dm(n))return[];let o=wi(r,t).map(i=>({id:`${e}#${n}.${i.kind}[${i.label}]`,line:i.line}));return yi.uniqueBy(o,i=>i.id)}function Dm(e){return e.endsWith("Fragment")||e.endsWith("Skeleton")||/^use[A-Z]/.test(e)||/^[A-Z][A-Z0-9_]*$/.test(e)}function Lm(e){if(b.isExportAssignment(e))return _m(e.expression);if(!Um(e))return null;if(b.isFunctionDeclaration(e)||b.isClassDeclaration(e))return e.name?.text??null;if(b.isVariableStatement(e)){let t=e.declarationList.declarations[0];return t!=null&&b.isIdentifier(t.name)?t.name.text:null}return null}function _m(e){return b.isIdentifier(e)?e.text:(b.isFunctionExpression(e)||b.isClassExpression(e))&&e.name!=null?e.name.text:"default"}function Um(e){if(!b.canHaveModifiers(e))return!1;let t=b.getModifiers(e);return t!=null&&t.some(r=>r.kind===b.SyntaxKind.ExportKeyword)}function wi(e,t){let r=Vm(e,t),n=e.getChildren(t).flatMap(o=>wi(o,t));return r==null?n:[r,...n]}function Vm(e,t){let r=Fm(e);if(r==null)return null;let n=Mm(r);if(n==null)return null;let o=zm(r,n);return o==null?null:{kind:n,label:o,line:Zm(t,e.getStart(t))}}function Fm(e){return b.isJsxSelfClosingElement(e)&&b.isIdentifier(e.tagName)?{attrs:e.attributes,children:[],tag:e.tagName.text}:b.isJsxElement(e)&&b.isIdentifier(e.openingElement.tagName)?{attrs:e.openingElement.attributes,children:e.children,tag:e.openingElement.tagName.text}:null}function Mm({attrs:e,tag:t}){let r=ce(e,"role");return r!=null?jm.get(r)??null:Hm(t,e)??Wm(t)??qm(e)}var Bm=new Map([["button",()=>"click"],["a",e=>ce(e,"href")==null?null:"navigate"],["input",e=>ce(e,"type")==="file"?"upload":"input"],["textarea",()=>"input"],["select",()=>"select"],["form",()=>"submit"]]);function Hm(e,t){return Bm.get(e)?.(t)??null}function Wm(e){return/^[A-Z]/.test(e)?Nm.find(([t])=>t.test(e))?.[1]??null:null}function qm(e){return hi.find(([t])=>Jm(e,t))?.[1]??null}function zm({attrs:e,children:t,tag:r},n){return n==="navigate"?ce(e,"href")??ce(e,"to"):ce(e,"aria-label")??ce(e,"label")??ce(e,"title")??ce(e,"name")??ce(e,"placeholder")??(Gm(r)?void 0:Qm(t))??Km(e,n)}function Gm(e){return e==="input"||e==="textarea"||e==="select"}function Km(e,t){let r=hi.find(([,o])=>o===t)?.[0];if(r==null)return;let n=Ym(e,r);if(n!=null){if(b.isIdentifier(n))return n.text;if(b.isArrowFunction(n)||b.isFunctionExpression(n))return bi(n.body)}}function bi(e){if(b.isCallExpression(e)){let t=e.expression;return b.isIdentifier(t)?t.text:b.isPropertyAccessExpression(t)?t.name.text:void 0}return b.forEachChild(e,bi)}function Jm(e,t){return e.properties.some(r=>b.isJsxAttribute(r)&&b.isIdentifier(r.name)&&r.name.text===t)}function vi(e,t){return e.properties.find(r=>b.isJsxAttribute(r)&&b.isIdentifier(r.name)&&r.name.text===t)}function ce(e,t){let r=vi(e,t);return r==null?void 0:Xm(r.initializer)}function Ym(e,t){let r=vi(e,t);if(!(r?.initializer==null||!b.isJsxExpression(r.initializer)))return r.initializer.expression}function Xm(e){if(e==null)return"";if(b.isStringLiteral(e))return e.text;if(b.isJsxExpression(e))return ki(e.expression)}function Qm(e){let t=e.flatMap(r=>Si(r)).join(" ").trim();return t.length===0?void 0:t}function Si(e){if(b.isJsxText(e)){let t=e.text.trim();return t.length===0?[]:[t]}if(b.isJsxExpression(e)){let t=ki(e.expression);return t==null?[]:[t]}return b.isJsxElement(e)?e.children.flatMap(t=>Si(t)):[]}function ki(e){if(e!=null){if(b.isStringLiteral(e)||b.isNoSubstitutionTemplateLiteral(e))return e.text;if(b.isCallExpression(e)&&e.arguments.length===1){let t=e.arguments[0];if(t!=null&&(b.isStringLiteral(t)||b.isNoSubstitutionTemplateLiteral(t)))return t.text}}}function Zm(e,t){return e.getLineAndCharacterOfPosition(t).line+1}var tf=Qt.join(".ripplo","coverage.d.ts");function qe({cwd:e}){rf({cwd:e,ignorePaths:Pe})}function rf({cwd:e,ignorePaths:t}){let r=ze({cwd:e,ignorePaths:t});sf({content:of(r),cwd:e})}function ze({cwd:e,ignorePaths:t}){let n=nf({cwd:e,ignorePaths:t}).flatMap(o=>Sn({cwd:e,file:o}));return[...new Set(n)].sort((o,i)=>o.localeCompare(i))}function nf({cwd:e,ignorePaths:t}){let r=z(["ls-files","--cached","--others","--exclude-standard","-z"],e),n=ef([...t]);return r.split("\0").filter(o=>o.length>0&&/\.(tsx|jsx)$/.test(o)).filter(o=>!n(o)).filter(o=>ft.existsSync(Qt.join(e,o)))}function Sn({cwd:e,file:t}){let r=ft.readFileSync(Qt.join(e,t),"utf8");return Xt({filePath:t,source:r}).map(n=>n.id)}function of(e){let t=`// GENERATED \u2014 do not edit
250
241
  import "@ripplo/testing";
251
242
 
252
243
  declare module "@ripplo/testing" {
@@ -257,22 +248,22 @@ declare module "@ripplo/testing" {
257
248
  `:`${t}${r}
258
249
  }
259
250
  }
260
- `}function zp({content:e,cwd:t}){let r=Wt.join(t,Mp);dt.existsSync(r)&&dt.readFileSync(r,"utf8")===e||dt.writeFileSync(r,e)}import Jo from"path";import{createJiti as Gp}from"jiti";var Kp=["getObservers","getPreconditions","getTests","getUnimplemented"];function Jp(e){return e==null||typeof e!="object"?!1:Kp.every(t=>typeof Reflect.get(e,t)=="function")}function Yp(e){return e===null?"null":Array.isArray(e)?"array":typeof e}async function P(e){let t=Jo.join(e,".ripplo","index.ts"),r=Jo.join(e,".ripplo");try{let o=await Gp(import.meta.url,{moduleCache:!1,sourceMaps:!0}).import(t),i=o!=null&&typeof o=="object"&&"default"in o?Reflect.get(o,"default"):o;if(!Jp(i))return{error:`${t} must default-export a RipploBuilder (got ${Yp(i)})`,ok:!1};let s=Mt(i);return{builder:i,ok:!0,result:s}}catch(n){return{error:Qp(n,r),ok:!1}}}var Xp=/\(?([^\s()]{1,500}\.ts):(\d{1,10}):(\d{1,10})\)?$/;function Qp(e,t){if(!(e instanceof Error))return String(e);let r=Zp(e.stack,t);return r==null?e.message:`${r} \u2014 ${e.message}`}function Zp(e,t){if(e==null)return;let n=e.split(`
261
- `).map(a=>Xp.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 Yo(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 Xo(e){let t=process.cwd(),r=await P(t);if(r.ok||(process.stderr.write(`Compilation failed: ${r.error}
262
- `),process.stderr.write(`${h("create","DSL authoring + lint rules")}
263
- `),process.exit(1)),e.check){let n=await Ft({cwd:t}),o=Ht({compiled:r.result,existing:n});if(o==="match"){process.stdout.write(`${le} is up to date
264
- `);return}let i=o==="missing"?"missing":"out of date";process.stderr.write(`${le} is ${i} \u2014 run \`ripplo compile\` and commit the result
265
- `),process.stderr.write(`${h("setup")}
266
- `),process.exit(1)}await ce({cwd:t,result:r.result}),Me({cwd:t}),process.stdout.write(`wrote ${le}
267
- `)}import me from"process";import em from"fs";import tm from"path";import rm from"picomatch";function Qo({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(Be({cwd:t,ignorePaths:r})),o=ti(e),i=nm({cwd:t,ignorePaths:r});return ei({acknowledged:o,allStatements:n,unacked:i})}function Zo({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(Be({cwd:t,ignorePaths:r})),o=ti(e);return ei({acknowledged:o,allStatements:n,unacked:n})}function ei({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 ti(e){return new Set(e.tests.flatMap(t=>t.coverage))}function nm({cwd:e,ignorePaths:t}){let r=om({cwd:e,ignorePaths:t}),n=new Set(r.flatMap(i=>im({cwd:e,file:i}))),o=new Set(r.flatMap(i=>sm({cwd:e,file:i})?tn({cwd:e,file:i}):[]));return new Set([...o].filter(i=>!n.has(i)))}function om({cwd:e,ignorePaths:t}){let r=M(["diff","--name-only","HEAD","-z"],e),n=M(["ls-files","--others","--exclude-standard","-z"],e),o=rm([...t]);return[...new Set([...r.split("\0"),...n.split("\0")])].filter(i=>i.length>0&&/\.(tsx|jsx)$/.test(i)).filter(i=>!o(i))}function im({cwd:e,file:t}){let r=Ho(`HEAD:${t}`,e);return r==null?[]:Bt({filePath:t,source:r}).map(n=>n.id)}function sm({cwd:e,file:t}){return em.existsSync(tm.join(e,t))}async function ri(){let e=me.cwd(),t=await P(e);t.ok||(me.stderr.write(`Compilation failed: ${t.error}
268
- `),me.exit(1));let r=Be({cwd:e,ignorePaths:Re}),n=Zo({compileResult:t.result,cwd:e,ignorePaths:Re}),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
269
- `),o.length>0&&(me.stdout.write(`
251
+ `}function sf({content:e,cwd:t}){let r=Qt.join(t,tf);ft.existsSync(r)&&ft.readFileSync(r,"utf8")===e||ft.writeFileSync(r,e)}import Ri from"path";import{createJiti as af}from"jiti";var lf=["getObservers","getPreconditions","getTests","getUnimplemented"];function cf(e){return e==null||typeof e!="object"?!1:lf.every(t=>typeof Reflect.get(e,t)=="function")}function uf(e){return e===null?"null":Array.isArray(e)?"array":typeof e}async function P(e){let t=Ri.join(e,".ripplo","index.ts"),r=Ri.join(e,".ripplo");try{let o=await af(import.meta.url,{moduleCache:!1,sourceMaps:!0}).import(t),i=o!=null&&typeof o=="object"&&"default"in o?Reflect.get(o,"default"):o;if(!cf(i))return{error:`${t} must default-export a RipploBuilder (got ${uf(i)})`,ok:!1};let s=Yt(i);return{builder:i,ok:!0,result:s}}catch(n){return{error:pf(n,r),ok:!1}}}var df=/\(?([^\s()]{1,500}\.ts):(\d{1,10}):(\d{1,10})\)?$/;function pf(e,t){if(!(e instanceof Error))return String(e);let r=mf(e.stack,t);return r==null?e.message:`${r} \u2014 ${e.message}`}function mf(e,t){if(e==null)return;let n=e.split(`
252
+ `).map(a=>df.exec(a)).find(a=>a!=null&&a[1]!=null&&a[2]!=null&&a[3]!=null&&a[1].startsWith(t));if(n==null)return;let[,o,i,s]=n;return`${o??""}:${i??""}:${s??""}`}function w(e,t){return t==null?`Load \`/ripplo:${e}\` skill for instructions.`:`Load \`/ripplo:${e}\` skill for instructions on ${t}.`}function Pi(e){return e.length===1?w(e[0]):`REQUIRED before proceeding: load ${e.map(r=>`\`/ripplo:${r}\``).join(" AND ")} skills (load every one \u2014 each carries rules the others don't).`}async function xi(e){let t=process.cwd(),r=await P(t);if(r.ok||(process.stderr.write(`Compilation failed: ${r.error}
253
+ `),process.stderr.write(`${w("create","DSL authoring + lint rules")}
254
+ `),process.exit(1)),e.check){let n=await Kt({cwd:t}),o=Jt({compiled:r.result,existing:n});if(o==="match"){process.stdout.write(`${ae} is up to date
255
+ `);return}let i=o==="missing"?"missing":"out of date";process.stderr.write(`${ae} is ${i} \u2014 run \`ripplo compile\` and commit the result
256
+ `),process.stderr.write(`${w("setup")}
257
+ `),process.exit(1)}await le({cwd:t,result:r.result}),qe({cwd:t}),process.stdout.write(`wrote ${ae}
258
+ `)}import pe from"process";import ff from"fs";import gf from"path";import yf from"picomatch";function Ei({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(ze({cwd:t,ignorePaths:r})),o=Ai(e),i=hf({cwd:t,ignorePaths:r});return Ti({acknowledged:o,allStatements:n,unacked:i})}function Ci({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(ze({cwd:t,ignorePaths:r})),o=Ai(e);return Ti({acknowledged:o,allStatements:n,unacked:n})}function Ti({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 Ai(e){return new Set(e.tests.flatMap(t=>t.coverage))}function hf({cwd:e,ignorePaths:t}){let r=wf({cwd:e,ignorePaths:t}),n=new Set(r.flatMap(i=>bf({cwd:e,file:i}))),o=new Set(r.flatMap(i=>vf({cwd:e,file:i})?Sn({cwd:e,file:i}):[]));return new Set([...o].filter(i=>!n.has(i)))}function wf({cwd:e,ignorePaths:t}){let r=z(["diff","--name-only","HEAD","-z"],e),n=z(["ls-files","--others","--exclude-standard","-z"],e),o=yf([...t]);return[...new Set([...r.split("\0"),...n.split("\0")])].filter(i=>i.length>0&&/\.(tsx|jsx)$/.test(i)).filter(i=>!o(i))}function bf({cwd:e,file:t}){let r=gi(`HEAD:${t}`,e);return r==null?[]:Xt({filePath:t,source:r}).map(n=>n.id)}function vf({cwd:e,file:t}){return ff.existsSync(gf.join(e,t))}async function Ii(){let e=pe.cwd(),t=await P(e);t.ok||(pe.stderr.write(`Compilation failed: ${t.error}
259
+ `),pe.exit(1));let r=ze({cwd:e,ignorePaths:Pe}),n=Ci({compileResult:t.result,cwd:e,ignorePaths:Pe}),o=n.filter(a=>a.kind==="unacknowledged"),i=n.filter(a=>a.kind==="stale"),s=r.length-o.length;pe.stdout.write(`Coverage: ${String(s)}/${String(r.length)} statements acknowledged
260
+ `),o.length>0&&(pe.stdout.write(`
270
261
  Unacknowledged (${String(o.length)}):
271
- `),o.forEach(a=>me.stdout.write(` ${a.id}
272
- `))),i.length>0&&(me.stdout.write(`
262
+ `),o.forEach(a=>pe.stdout.write(` ${a.id}
263
+ `))),i.length>0&&(pe.stdout.write(`
273
264
  Stale claims (${String(i.length)}):
274
- `),i.forEach(a=>me.stdout.write(` ${a.id}
275
- `))),n.length>0&&me.exit(1)}import{graphql as um}from"gql.tada";import ni from"fs";import rn from"path";function oi(e){let t=ni.realpathSync(e),r=t,n=rn.dirname(r);for(;n!==r;){if(ni.existsSync(rn.join(r,".git")))return r;r=n,n=rn.dirname(r)}return t}function _(e){let t=cr(e),r=Te(),n=ne();if(n==null)throw new Error("ripplo: not authenticated. Run `ripplo auth login`.");return{appUrl:r.appUrl,cwd:oi(e),engineUrl:r.engineUrl,projectId:yo()??t.projectId,ripploServerUrl:X(),token:n,webhookSecret:r.webhookSecret}}import ut from"fs";var am="dev.pid";function ii(e){return it(e,am)}function We(e){let t=ii(e);if(!ut.existsSync(t))return!1;let r=ut.readFileSync(t,"utf8").trim(),n=Number.parseInt(r,10);if(!Number.isFinite(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch{return!1}}function si(e){ot(e);let t=ii(e);ut.writeFileSync(t,String(process.pid));let r=!1;return()=>{if(!r){r=!0;try{let n=ut.readFileSync(t,"utf8").trim();Number.parseInt(n,10)===process.pid&&ut.unlinkSync(t)}catch{}}}}import lm from"fs";import nn from"path";var cm=["MERGE_HEAD","rebase-merge","rebase-apply","CHERRY_PICK_HEAD","REVERT_HEAD"];function qt(e){let t=dm(e);return t==null?!1:cm.some(r=>lm.existsSync(nn.join(t,r)))}function dm(e){try{let t=M(["rev-parse","--git-dir"],e).trim();return t.length===0?null:nn.isAbsolute(t)?t:nn.resolve(e,t)}catch{return null}}var pm=um(`
265
+ `),i.forEach(a=>pe.stdout.write(` ${a.id}
266
+ `))),n.length>0&&pe.exit(1)}import{graphql as xf}from"gql.tada";import $i from"fs";import kn from"path";function ji(e){let t=$i.realpathSync(e),r=t,n=kn.dirname(r);for(;n!==r;){if($i.existsSync(kn.join(r,".git")))return r;r=n,n=kn.dirname(r)}return t}function M(e){let t=an(e),r=Fe(),n=ie();if(n==null)throw new Error("ripplo: not authenticated. Run `ripplo auth login`.");return{appUrl:r.appUrl,cwd:ji(e),engineUrl:r.engineUrl,projectId:Ho()??t.projectId,ripploServerUrl:Z(),token:n,webhookSecret:r.webhookSecret}}import gt from"fs";var Sf="dev.pid";function Ni(e){return lt(e,Sf)}function Ge(e){let t=Ni(e);if(!gt.existsSync(t))return!1;let r=gt.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){at(e);let t=Ni(e);gt.writeFileSync(t,String(process.pid));let r=!1;return()=>{if(!r){r=!0;try{let n=gt.readFileSync(t,"utf8").trim();Number.parseInt(n,10)===process.pid&&gt.unlinkSync(t)}catch{}}}}import kf from"fs";import Rn from"path";var Rf=["MERGE_HEAD","rebase-merge","rebase-apply","CHERRY_PICK_HEAD","REVERT_HEAD"];function Zt(e){let t=Pf(e);return t==null?!1:Rf.some(r=>kf.existsSync(Rn.join(t,r)))}function Pf(e){try{let t=z(["rev-parse","--git-dir"],e).trim();return t.length===0?null:Rn.isAbsolute(t)?t:Rn.resolve(e,t)}catch{return null}}var Ef=xf(`
276
267
  query DevSessionCheckHealth($projectId: String!, $cwd: String!) {
277
268
  project(id: $projectId) {
278
269
  id
@@ -281,25 +272,25 @@ Stale claims (${String(i.length)}):
281
272
  }
282
273
  }
283
274
  }
284
- `);function ai(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 li(e){let t=We(e),r=qt(e),n;try{n=_(e)}catch{return{gitMidOperation:r,status:t?"starting":"missing",type:"dev-session"}}return(await f({config:n,document:pm,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 ci(e){switch(e.type){case"settings":return ym(e);case"env-files":return hm(e);case"token":return wm(e);case"dev-server":return bm(e);case"dev-session":return ai(e);case"preconditions":return km(e);case"webhook-verification":return vm(e);case"preconditions-validation":return Rm(e);case"workflows":return Pm(e);case"browser":return Sm(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 mm(e);case"lockfile":return fm(e);case"pre-commit-hook":return gm(e)}}function mm(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 fm(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 gm(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 ym(e){return e.valid?"\u2713 Settings: Project configured":`\u2717 Settings: Missing fields: ${e.missingFields.join(", ")}`}function hm(e){return e.missing.length===0?"\u2713 Env files: declared files present":`\u2717 Env files: declared in .ripplo/project.json but missing:
275
+ `);function Di(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 Li(e){let t=Ge(e),r=Zt(e),n;try{n=M(e)}catch{return{gitMidOperation:r,status:t?"starting":"missing",type:"dev-session"}}return(await y({config:n,document:Ef,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 _i(e){switch(e.type){case"settings":return If(e);case"env-files":return $f(e);case"token":return jf(e);case"dev-server":return Nf(e);case"dev-session":return Di(e);case"preconditions":return Lf(e);case"webhook-verification":return Of(e);case"preconditions-validation":return _f(e);case"workflows":return Uf(e);case"browser":return Df(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 Cf(e);case"lockfile":return Tf(e);case"pre-commit-hook":return Af(e)}}function Cf(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 Tf(e){switch(e.status){case"match":return`\u2713 Lockfile: ${ae} is up to date`;case"missing":return`\u2717 Lockfile: ${ae} is missing \u2014 run \`ripplo compile\` and commit it`;case"stale":return`\u2717 Lockfile: ${ae} is out of date \u2014 run \`ripplo compile\` and commit it`}}function Af(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 If(e){return e.valid?"\u2713 Settings: Project configured":`\u2717 Settings: Missing fields: ${e.missingFields.join(", ")}`}function $f(e){return e.missing.length===0?"\u2713 Env files: declared files present":`\u2717 Env files: declared in .ripplo/project.json but missing:
285
276
  ${e.missing.map(r=>` ${r}`).join(`
286
277
  `)}
287
- 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 wm(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 ${X()} to validate token.`}}function bm(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 vm(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 Sm(e){return e.installed?"\u2713 Browser: Chromium installed":"\u2717 Browser: Chromium not installed. Run: npx playwright install chromium"}function km(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 Rm(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"}
278
+ 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 jf(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 ${Z()} to validate token.`}}function Nf(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 Of(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 Df(e){return e.installed?"\u2713 Browser: Chromium installed":"\u2717 Browser: Chromium not installed. Run: npx playwright install chromium"}function Lf(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 _f(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"}
288
279
  ${t.join(`
289
- `)}`}function Pm(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=>xm(r));return`\u2717 Tests: ${String(e.invalidNames.length)} invalid
280
+ `)}`}function Uf(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=>Vf(r));return`\u2717 Tests: ${String(e.invalidNames.length)} invalid
290
281
  ${t.join(`
291
- `)}`}function xm(e){let t=e.errors.map(r=>" - "+(r.path===""?"":r.path+": ")+r.message);return" "+e.name+`:
282
+ `)}`}function Vf(e){let t=e.errors.map(r=>" - "+(r.path===""?"":r.path+": ")+r.message);return" "+e.name+`:
292
283
  `+t.join(`
293
- `)}import sn from"fs";import $m from"path";import{chromium as jm}from"playwright";import Em from"fs";import Cm from"path";async function di(e){let t=Cm.join(e,".ripplo","index.ts");if(!Em.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 on(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 ui({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 Am}from"gql.tada";var Im=Am(`
284
+ `)}import xn from"fs";import qf from"path";import{chromium as zf}from"playwright";import Ff from"fs";import Mf from"path";async function Ui(e){let t=Mf.join(e,".ripplo","index.ts");if(!Ff.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=Fe();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 Pn(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 Vi({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 Bf}from"gql.tada";var Hf=Bf(`
294
285
  query DoctorAuthViewer {
295
286
  currentUser {
296
287
  name
297
288
  email
298
289
  }
299
290
  }
300
- `),Tm="Failed to connect to Ripplo server";async function pi({serverUrl:e,token:t}){try{let r=await f({config:Se({serverUrl:e,token:t}),document:Im,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(Tm)?{kind:"unreachable"}:{kind:"invalid"}}}function mi(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 fi(e){let t=await Dm(e),r={missing:pr(e),type:"env-files"},n=await Lm(),o=_m(),i=await P(e),s=Um(i),a=Hm(i),l=await Nm(e,i),c=Om(e),p=await Mm(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 Ft({cwd:e});return{status:Ht({compiled:t.result,existing:r}),type:"lockfile"}}function Om(e){let t=$m.join(e,".git","hooks","pre-commit");return sn.existsSync(t)?{installed:sn.readFileSync(t,"utf8").includes("ripplo compile --check"),type:"pre-commit-hook"}:{installed:!1,type:"pre-commit-hook"}}async function Dm(e){let t=await di(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 Lm(){let e=ne();if(e==null||e.length===0)return{email:void 0,status:"missing",type:"token"};let t=await pi({serverUrl:X(),token:e});return t.kind==="valid"?{email:t.email,status:"valid",type:"token"}:{email:void 0,status:t.kind,type:"token"}}function _m(){let e=jm.executablePath();return{installed:sn.existsSync(e),type:"browser"}}function Um(e){if(!e.ok)return{errorCount:1,errors:[{message:e.error,path:""}],found:!1,type:"preconditions-validation",valid:!1};let t=Vm(e.result.preconditions,e.result.tests);return{errorCount:t.length,errors:t,found:!0,type:"preconditions-validation",valid:t.length===0}}function Vm(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}`})})}),Fm(e).forEach(o=>{r.push({message:o,path:"preconditions"})}),r}function Fm(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 Hm(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 Mm(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 on(r.appUrl)==null;n.push({appUrl:r.appUrl,reachable:o,type:"dev-server"});let i=await li(process.cwd());n.push(i);let s=await Bm(r,t);return n.push(...s),n}async function Bm(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=qm(e.appUrl,e.engineUrl);if(i==null)return[o];let s=await on(i)==null,a=[];if(a.push({configured:!0,count:r,endpointReachable:s,type:"preconditions"}),gi(e.engineUrl)&&a.push({reachable:s,type:"engine-endpoint",url:i}),!s)return a;let l=await ui({appUrl:e.appUrl,engineUrl:e.engineUrl});a.push({rejectsUnsigned:l==null,type:"webhook-verification"});let c=await Wm({engineUrl:i,webhookSecret:e.webhookSecret});return a.push({status:c,type:"adapter-enabled",url:i}),a}async function Wm({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 gi(e){return e.startsWith("http://")||e.startsWith("https://")}function qm(e,t){return gi(t)?t:`${e}${t}`}async function yi(){let e=process.cwd(),t=await fi(e),r=t.map(o=>ci(o));process.stdout.write(r.join(`
291
+ `),Wf="Failed to connect to Ripplo server";async function Fi({serverUrl:e,token:t}){try{let r=await y({config:ke({serverUrl:e,token:t}),document:Hf,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(Wf)?{kind:"unreachable"}:{kind:"invalid"}}}function Mi(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 Bi(e){let t=await Jf(e),r={missing:un(e),type:"env-files"},n=await Yf(),o=Xf(),i=await P(e),s=Qf(i),a=tg(i),l=await Gf(e,i),c=Kf(e),p=await rg(t,i);return[t,r,n,...p,s,a,l,c,o]}async function Gf(e,t){if(!t.ok)return{status:"missing",type:"lockfile"};let r=await Kt({cwd:e});return{status:Jt({compiled:t.result,existing:r}),type:"lockfile"}}function Kf(e){let t=qf.join(e,".git","hooks","pre-commit");return xn.existsSync(t)?{installed:xn.readFileSync(t,"utf8").includes("ripplo compile --check"),type:"pre-commit-hook"}:{installed:!1,type:"pre-commit-hook"}}async function Jf(e){let t=await Ui(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 Yf(){let e=ie();if(e==null||e.length===0)return{email:void 0,status:"missing",type:"token"};let t=await Fi({serverUrl:Z(),token:e});return t.kind==="valid"?{email:t.email,status:"valid",type:"token"}:{email:void 0,status:t.kind,type:"token"}}function Xf(){let e=zf.executablePath();return{installed:xn.existsSync(e),type:"browser"}}function Qf(e){if(!e.ok)return{errorCount:1,errors:[{message:e.error,path:""}],found:!1,type:"preconditions-validation",valid:!1};let t=Zf(e.result.preconditions,e.result.tests);return{errorCount:t.length,errors:t,found:!0,type:"preconditions-validation",valid:t.length===0}}function Zf(e,t){let r=[],n=new Set(Object.keys(e));return Object.entries(e).forEach(([o,i])=>{(i.depends??[]).forEach(s=>{n.has(s)||r.push({message:`Depends on non-existent precondition "${s}"`,path:`preconditions.${o}.depends`})})}),t.forEach(o=>{Object.entries(o.requiresKeys).forEach(([i,s])=>{n.has(s)||r.push({message:`Test "${o.slug}" requires non-existent precondition "${s}" (as ${i})`,path:`tests.${o.slug}.requiresKeys.${i}`})})}),eg(e).forEach(o=>{r.push({message:o,path:"preconditions"})}),r}function eg(e){let t=new Set,r=new Set,n=[];function o(i){if(r.has(i)){n.push(`Precondition "${i}" has a circular dependency`);return}t.has(i)||(t.add(i),r.add(i),(e[i]?.depends??[]).forEach(s=>{o(s)}),r.delete(i))}return Object.keys(e).forEach(i=>{o(i)}),n}function tg(e){if(!e.ok)return{invalidNames:[],invalidWorkflows:[],total:0,type:"workflows",valid:0};let t=e.result.tests.length;return{invalidNames:[],invalidWorkflows:[],total:t,type:"workflows",valid:t}}async function rg(e,t){if(!e.valid||!t.ok)return[];let r;try{let a=Fe();r={appUrl:a.appUrl,engineUrl:a.engineUrl,webhookSecret:a.webhookSecret}}catch{return[]}let n=[],o=await Pn(r.appUrl)==null;n.push({appUrl:r.appUrl,reachable:o,type:"dev-server"});let i=await Li(process.cwd());n.push(i);let s=await ng(r,t);return n.push(...s),n}async function ng(e,t){let r=t.ok?Object.keys(t.result.preconditions).length:0,n=e.engineUrl.length>0,o={configured:n,count:r,endpointReachable:void 0,type:"preconditions"};if(r===0||!n)return[o];let i=ig(e.appUrl,e.engineUrl);if(i==null)return[o];let s=await Pn(i)==null,a=[];if(a.push({configured:!0,count:r,endpointReachable:s,type:"preconditions"}),Hi(e.engineUrl)&&a.push({reachable:s,type:"engine-endpoint",url:i}),!s)return a;let l=await Vi({appUrl:e.appUrl,engineUrl:e.engineUrl});a.push({rejectsUnsigned:l==null,type:"webhook-verification"});let c=await og({engineUrl:i,webhookSecret:e.webhookSecret});return a.push({status:c,type:"adapter-enabled",url:i}),a}async function og({engineUrl:e,webhookSecret:t}){if(t.length===0)return"no-secret";let r=JSON.stringify({preconditions:[]});try{let n=await fetch(`${e}/execute-preconditions`,{body:r,headers:{"Content-Type":"application/json",...ve({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 Hi(e){return e.startsWith("http://")||e.startsWith("https://")}function ig(e,t){return Hi(t)?t:`${e}${t}`}async function Wi(){let e=process.cwd(),t=await Bi(e),r=t.map(o=>_i(o));process.stdout.write(r.join(`
301
292
  `)+`
302
- `);let n=t.some(o=>mi(o));process.exit(n?1:0)}import Gm from"crypto";import{graphql as Km}from"gql.tada";import an from"fs";import ln from"path";function zt(e){try{let t=ln.join(zm(e),"HEAD"),r=an.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 zm(e){let t=ln.join(e,".git");if(an.statSync(t).isDirectory())return t;let n=an.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 ln.resolve(e,i)}var Jm=Km(`
293
+ `);let n=t.some(o=>Mi(o));process.exit(n?1:0)}import ag from"crypto";import{graphql as lg}from"gql.tada";import En from"fs";import Cn from"path";function er(e){try{let t=Cn.join(sg(e),"HEAD"),r=En.readFileSync(t,"utf8").trim(),n="ref: refs/heads/";return r.startsWith(n)?r.slice(n.length):r.length===0?void 0:r.slice(0,7)}catch{return}}function sg(e){let t=Cn.join(e,".git");if(En.statSync(t).isDirectory())return t;let n=En.readFileSync(t,"utf8").trim(),o="gitdir:";if(!n.startsWith(o))throw new Error(`unrecognized .git file at ${t}`);let i=n.slice(o.length).trim();if(i.length===0)throw new Error(`empty gitdir pointer at ${t}`);return Cn.resolve(e,i)}var cg=lg(`
303
294
  mutation SyncDevSession(
304
295
  $projectId: String!
305
296
  $cwd: String!
@@ -318,13 +309,13 @@ ${t.join(`
318
309
  hooksPaused
319
310
  }
320
311
  }
321
- `);async function pt(e){let t=Ym(e.compiled);return Qm({config:e.config,cwd:e.cwd,payload:t})}async function fe(e,t){let r=await P(e);if(!r.ok)throw new Error(`DSL compilation failed: ${r.error}`);let n=await pt({compiled:r.result,config:t,cwd:e});return{compiled:r.result,devSessionId:n.devSessionId}}function Ym(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 Gm.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function Qm({config:e,cwd:t,payload:r}){let n=Xm(r),o=zt(t),i=await f({config:e,document:Jm,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{graphql as mt,readFragment as nf}from"gql.tada";import{createHash as hi}from"crypto";import{mkdirSync as Zm,readFileSync as cn,writeFileSync as ef}from"fs";import Gt from"path";var tf=[".ts",".tsx",".js",".jsx"];function Pe(e){let t=hi("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(`
322
- `).filter(n=>n.length>0).filter(n=>tf.some(o=>n.endsWith(o))).toSorted((n,o)=>n.localeCompare(o)).forEach(n=>{t.update(n),t.update("\0"),t.update(rf(Gt.join(e,n))),t.update("\0")}),t.digest("hex")}function wi(e){let t=Gt.join(e,".ripplo","ripplo.lock");try{let r=cn(t);return hi("sha256").update(r).digest("hex")}catch{return null}}function qe(e,t){try{return cn(bi(e,t),"utf8").trim()}catch{return null}}function ze(e,t,r){let n=bi(e,t);Zm(Gt.dirname(n),{recursive:!0}),ef(n,r)}function bi(e,t){return Gt.join(e,".ripplo",".local",`${t}.hash`)}function rf(e){try{return cn(e)}catch{return Buffer.alloc(0)}}import vi from"figures";var Ae={cross:vi.cross,tick:vi.tick};var ki=mt(`
312
+ `);async function yt(e){let t=ug(e.compiled);return pg({config:e.config,cwd:e.cwd,payload:t})}async function me(e,t){let r=await P(e);if(!r.ok)throw new Error(`DSL compilation failed: ${r.error}`);let n=await yt({compiled:r.result,config:t,cwd:e});return{compiled:r.result,devSessionId:n.devSessionId}}function ug(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 dg(e){return ag.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function pg({config:e,cwd:t,payload:r}){let n=dg(r),o=er(t),i=await y({config:e,document:cg,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{graphql as ht,readFragment as hg}from"gql.tada";import{createHash as qi}from"crypto";import{mkdirSync as mg,readFileSync as Tn,writeFileSync as fg}from"fs";import tr from"path";var gg=[".ts",".tsx",".js",".jsx"];function xe(e){let t=qi("sha256");return t.update(z(["rev-parse","HEAD"],e)),t.update("\0"),t.update(z(["diff","HEAD"],e)),t.update("\0"),z(["ls-files","--others","--exclude-standard"],e).split(`
313
+ `).filter(n=>n.length>0).filter(n=>gg.some(o=>n.endsWith(o))).toSorted((n,o)=>n.localeCompare(o)).forEach(n=>{t.update(n),t.update("\0"),t.update(yg(tr.join(e,n))),t.update("\0")}),t.digest("hex")}function zi(e){let t=tr.join(e,".ripplo","ripplo.lock");try{let r=Tn(t);return qi("sha256").update(r).digest("hex")}catch{return null}}function Ke(e,t){try{return Tn(Gi(e,t),"utf8").trim()}catch{return null}}function Je(e,t,r){let n=Gi(e,t);mg(tr.dirname(n),{recursive:!0}),fg(n,r)}function Gi(e,t){return tr.join(e,".ripplo",".local",`${t}.hash`)}function yg(e){try{return Tn(e)}catch{return Buffer.alloc(0)}}import Ki from"figures";var je={cross:Ki.cross,tick:Ki.tick};var Yi=ht(`
323
314
  fragment WorkflowIdMCP on Workflow {
324
315
  id
325
316
  slug
326
317
  }
327
- `),of=mt(`
318
+ `),wg=ht(`
328
319
  query ProjectWorkflowIdsMCP($projectId: String!, $cwd: String!) {
329
320
  project(id: $projectId) {
330
321
  id
@@ -336,20 +327,20 @@ ${t.join(`
336
327
  }
337
328
  }
338
329
  }
339
- `,[ki]),sf=mt(`
330
+ `,[Yi]),bg=ht(`
340
331
  mutation SetProjectViewCLI($projectId: String!, $devSessionId: String!) {
341
332
  setProjectView(projectId: $projectId, devSessionId: $devSessionId) {
342
333
  id
343
334
  }
344
335
  }
345
- `),af=mt(`
336
+ `),vg=ht(`
346
337
  mutation CreateRunMCP($workflowId: String!, $lockfileHash: String, $repoHash: String) {
347
338
  createRun(workflowId: $workflowId, lockfileHash: $lockfileHash, repoHash: $repoHash) {
348
339
  id
349
340
  status
350
341
  }
351
342
  }
352
- `),lf=mt(`
343
+ `),Sg=ht(`
353
344
  query RunStatusMCP($id: String!) {
354
345
  run(id: $id) {
355
346
  id
@@ -376,21 +367,21 @@ ${t.join(`
376
367
  }
377
368
  }
378
369
  }
379
- `);async function Kt({config:e,ids:t,presynced:r}){let n=await cf({config:e,ids:t,presynced:r}),o=await Promise.all(n.map(async a=>{try{let l=await ff({config:e,workflowId:a.workflowId});return{entry:a,ok:!0,runId:l}}catch(l){let c=l instanceof Error?l.message:String(l);return{entry:a,message:c,ok:!1}}})),i=await Promise.all(o.map(async a=>{if(!a.ok)return{id:a.entry.id,runId:"",summary:`ERROR creating run: ${a.message}
380
- ${h("setup","check auth + config")}`};let{entry:l,runId:c}=a;try{let p=await hf({config:e,runId:c}),m=mf({config:e,id:l.id,runId:c}),S=`.ripplo/debug/${c}/`;return{id:l.id,runId:c,summary:`View run: ${m}
381
- Debug artifacts: ${S}
382
- ${h("debug","read summary.txt, accessibility-tree, network.jsonl before guessing")}
370
+ `);async function rr({config:e,ids:t,presynced:r}){let n=await kg({config:e,ids:t,presynced:r}),o=await Promise.all(n.map(async a=>{try{let l=await Cg({config:e,workflowId:a.workflowId});return{entry:a,ok:!0,runId:l}}catch(l){let c=l instanceof Error?l.message:String(l);return{entry:a,message:c,ok:!1}}})),i=await Promise.all(o.map(async a=>{if(!a.ok)return{id:a.entry.id,runId:"",summary:`ERROR creating run: ${a.message}
371
+ ${w("setup","check auth + config")}`};let{entry:l,runId:c}=a;try{let p=await Ig({config:e,runId:c}),m=Eg({config:e,id:l.id,runId:c}),h=`.ripplo/debug/${c}/`;return{id:l.id,runId:c,summary:`View run: ${m}
372
+ Debug artifacts: ${h}
373
+ ${w("debug","read summary.txt, accessibility-tree, network.jsonl before guessing")}
383
374
 
384
375
  ${p}`}}catch(p){let m=p instanceof Error?p.message:String(p);return{id:l.id,runId:c,summary:`ERROR polling run ${c}: ${m}
385
- ${h("debug")}`}}})),s=i.map(a=>`**${a.id}:**
376
+ ${w("debug")}`}}})),s=i.map(a=>`**${a.id}:**
386
377
  ${a.summary}`).join(`
387
378
 
388
379
  ---
389
380
 
390
- `);return{results:i,summary:s}}async function cf({config:e,ids:t,presynced:r}){let n=r??await fe(e.cwd,e),o=await f({config:e,document:of,variables:{cwd:e.cwd,projectId:e.projectId}});if(o.project==null)throw new Error("Project not found");let i=o.project.devSession;if(i==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:sf,variables:{devSessionId:i.id,projectId:e.projectId}});let s=(i.workflows??[]).map(l=>nf(ki,l));if(t.length===0)return s.map(l=>({id:l.slug,workflowId:l.id}));let a=n.compiled.tests.map(l=>l.slug);return t.map(l=>{let c=s.find(p=>p.slug===l);if(c==null)throw new Error(df({compiledSlugs:a,slug:l}));return{id:l,workflowId:c.id}})}function df({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=uf({compiledSlugs:e,limit:3,slug:t}),n=r.length>0?`
381
+ `);return{results:i,summary:s}}async function kg({config:e,ids:t,presynced:r}){let n=r??await me(e.cwd,e),o=await y({config:e,document:wg,variables:{cwd:e.cwd,projectId:e.projectId}});if(o.project==null)throw new Error("Project not found");let i=o.project.devSession;if(i==null)throw new Error("No active dev session. Start one by running `ripplo` (or `npx ripplo`) in your terminal, then try again.");await y({config:e,document:bg,variables:{devSessionId:i.id,projectId:e.projectId}});let s=(i.workflows??[]).map(l=>hg(Yi,l));if(t.length===0)return s.map(l=>({id:l.slug,workflowId:l.id}));let a=n.compiled.tests.map(l=>l.slug);return t.map(l=>{let c=s.find(p=>p.slug===l);if(c==null)throw new Error(Rg({compiledSlugs:a,slug:l}));return{id:l,workflowId:c.id}})}function Rg({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=Pg({compiledSlugs:e,limit:3,slug:t}),n=r.length>0?`
391
382
  Did you mean: ${r.join(", ")}?`:"";return`Test "${t}" is not registered in this dev session.${n}
392
- Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on demand \u2014 restarting the dev server will not help.)`}function uf({compiledSlugs:e,limit:t,slug:r}){let n=new Set(r.split("-"));return e.map(i=>({candidate:i,score:pf(n,i)})).filter(i=>i.score>0).toSorted((i,s)=>s.score-i.score).slice(0,t).map(i=>i.candidate)}function pf(e,t){return t.split("-").filter(r=>e.has(r)).length}function mf({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 ff({config:e,workflowId:t}){let r=await f({config:e,document:af,variables:{lockfileHash:wi(e.cwd),repoHash:gf(e.cwd),workflowId:t}});if(r.createRun==null)throw new Error("Failed to create run");return r.createRun.id}function gf(e){try{return Pe(e)}catch{return null}}var yf=2e3,Si=150;async function hf({config:e,runId:t}){let r=0;for(;r<Si;){await vf(yf),r+=1;let o=(await f({config:e,document:lf,variables:{id:t}})).run;if(o==null)throw new Error(`Run ${t} not found`);if(!(o.status==="pending"||o.status==="running"))return wf({run:o,runId:t})}return`Run ${t} timed out after polling ${String(Si)} times.`}function wf({run:e,runId:t}){let r=[`Run ${t}: ${e.status.toUpperCase()}`],n=bf(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(`
393
- `)}function bf(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 vf(e){return new Promise(t=>{setTimeout(t,e)})}import{graphql as Sf}from"gql.tada";var kf=Sf(`
383
+ Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on demand \u2014 restarting the dev server will not help.)`}function Pg({compiledSlugs:e,limit:t,slug:r}){let n=new Set(r.split("-"));return e.map(i=>({candidate:i,score:xg(n,i)})).filter(i=>i.score>0).toSorted((i,s)=>s.score-i.score).slice(0,t).map(i=>i.candidate)}function xg(e,t){return t.split("-").filter(r=>e.has(r)).length}function Eg({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 Cg({config:e,workflowId:t}){let r=await y({config:e,document:vg,variables:{lockfileHash:zi(e.cwd),repoHash:Tg(e.cwd),workflowId:t}});if(r.createRun==null)throw new Error("Failed to create run");return r.createRun.id}function Tg(e){try{return xe(e)}catch{return null}}var Ag=2e3,Ji=150;async function Ig({config:e,runId:t}){let r=0;for(;r<Ji;){await Ng(Ag),r+=1;let o=(await y({config:e,document:Sg,variables:{id:t}})).run;if(o==null)throw new Error(`Run ${t} not found`);if(!(o.status==="pending"||o.status==="running"))return $g({run:o,runId:t})}return`Run ${t} timed out after polling ${String(Ji)} times.`}function $g({run:e,runId:t}){let r=[`Run ${t}: ${e.status.toUpperCase()}`],n=jg(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"?je.tick:je.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"?je.tick:je.cross,c=a.detail==null?"":` \u2014 ${a.detail}`;r.push(` ${l} ${a.description}${c}`)})}),r.join(`
384
+ `)}function jg(e){if(e.caughtKind==null)return null;let t=e.workflow?.slug??"workflow";return e.caughtKind==="new_test"?` ${je.tick} ripplo caught a bug \u2014 new test "${t}" surfaced an issue in your app code`:` ${je.tick} ripplo caught a regression in "${t}"`}function Ng(e){return new Promise(t=>{setTimeout(t,e)})}import{graphql as Og}from"gql.tada";var Dg=Og(`
394
385
  query DevSessionCheckPreflight($projectId: String!, $cwd: String!) {
395
386
  project(id: $projectId) {
396
387
  id
@@ -399,38 +390,38 @@ Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on
399
390
  }
400
391
  }
401
392
  }
402
- `);function ue(){try{return _(process.cwd())}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}
403
- `),process.stderr.write(`${h("setup")}
404
- `),process.exit(1)}}async function ge(e){(await f({config:e,document:kf,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")}
405
- `),process.exit(1))}async function Ri({id:e,runs:t}){let r=ue();await ge(r),process.stdout.write(`flake-detect "${e}" x${String(t)}...
406
- `);let n=await fe(r.cwd,r),o=await Promise.allSettled(Array.from({length:t},()=>Kt({config:r,ids:[e],presynced:n}))),i=0,s=0,a=new Map;o.forEach(c=>{if(c.status==="rejected"){s++;let m=c.reason instanceof Error?c.reason.message:"unknown error";a.set(m,(a.get(m)??0)+1);return}let p=c.value.results[0];if(p==null){s++;return}if(p.summary.includes("FAILED")||p.summary.includes("ERROR")){s++;let m=p.summary.split(`
407
- `).find(S=>S.includes("FAILED")||S.includes("ERROR"))??"unknown failure";a.set(m,(a.get(m)??0)+1)}else i++});let l=t>0?s/t*100:0;process.stdout.write(`${String(i)} passed / ${String(s)} failed (${l.toFixed(1)}% flake)
393
+ `);function ue(){try{return M(process.cwd())}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}
394
+ `),process.stderr.write(`${w("setup")}
395
+ `),process.exit(1)}}async function fe(e){(await y({config:e,document:Dg,variables:{cwd:e.cwd,projectId:e.projectId}})).project?.devSession==null&&(process.stderr.write("No active dev session. Start `npx ripplo watch` as a background process (your app's dev server must also be running), then retry. Or run `/ripplo:start` in Claude Code.\n"),process.stderr.write(`${w("setup")}
396
+ `),process.exit(1))}async function Xi({id:e,runs:t}){let r=ue();await fe(r),process.stdout.write(`flake-detect "${e}" x${String(t)}...
397
+ `);let n=await me(r.cwd,r),o=await Promise.allSettled(Array.from({length:t},()=>rr({config:r,ids:[e],presynced:n}))),i=0,s=0,a=new Map;o.forEach(c=>{if(c.status==="rejected"){s++;let m=c.reason instanceof Error?c.reason.message:"unknown error";a.set(m,(a.get(m)??0)+1);return}let p=c.value.results[0];if(p==null){s++;return}if(p.summary.includes("FAILED")||p.summary.includes("ERROR")){s++;let m=p.summary.split(`
398
+ `).find(h=>h.includes("FAILED")||h.includes("ERROR"))??"unknown failure";a.set(m,(a.get(m)??0)+1)}else i++});let l=t>0?s/t*100:0;process.stdout.write(`${String(i)} passed / ${String(s)} failed (${l.toFixed(1)}% flake)
408
399
  `),a.size>0&&a.forEach((c,p)=>{process.stdout.write(` ${String(c)}x: ${p}
409
- `)}),s>0&&process.stderr.write(`${h("flake-detect","parallel safety + race conditions")}
410
- `),process.exit(s>0?1:0)}import Jt from"fs";import{graphql as Pf}from"gql.tada";import Rf from"fs";function xe(e){return it(e,"hooks-paused")}function $(e){return Rf.existsSync(xe(e))||qt(e)?!1:We(e)}var xf=Pf(`
400
+ `)}),s>0&&process.stderr.write(`${w("flake-detect","parallel safety + race conditions")}
401
+ `),process.exit(s>0?1:0)}import nr from"fs";import{graphql as _g}from"gql.tada";import Lg from"fs";function Ee(e){return lt(e,"hooks-paused")}function _(e){return Lg.existsSync(Ee(e))||Zt(e)?!1:Ge(e)}var Ug=_g(`
411
402
  mutation CliSetHooksPaused($projectId: String!, $paused: Boolean!) {
412
403
  setHooksPaused(projectId: $projectId, paused: $paused) {
413
404
  id
414
405
  }
415
406
  }
416
- `);async function Pi(){process.stdin.isTTY||(process.stderr.write("`ripplo hooks pause` must be invoked interactively from a terminal \u2014 refusing non-TTY invocation. Bypassing the gate is a human decision, not an agent decision.\n"),process.exit(1));let e=process.cwd();ot(e);let t=xe(e);if(Jt.existsSync(t)){process.stdout.write("Hooks already paused. Run `ripplo hooks resume` to re-enable.\n");return}Jt.writeFileSync(t,""),await Ei(e,!0),process.stdout.write("Hooks paused. Pre-edit gates and stop enforcement are off until you run `ripplo hooks resume`.\n")}async function xi(){let e=process.cwd(),t=xe(e);if(!Jt.existsSync(t)){process.stdout.write(`Hooks already active.
417
- `);return}Jt.unlinkSync(t),await Ei(e,!1),process.stdout.write(`Hooks resumed.
418
- `)}async function Ei(e,t){let r;try{r=_(e)}catch{return}await f({config:r,document:xf,variables:{paused:t,projectId:r.projectId}}).catch(()=>null)}import Ge from"fs";import Ke from"path";import{input as Ii,select as Ti}from"@inquirer/prompts";import{graphql as qf}from"gql.tada";import{exec as Ef}from"child_process";import L from"fs";import U from"path";import{promisify as Cf}from"util";var Af=["@ripplo/testing"],Ci=".ripplo/ripplo.lock linguist-generated=true",If=[".ripplo/debug/",".ripplo/.local/"],Tf=Cf(Ef);async function Ai({cwd:e,onStep:t}){t("Scaffolding project files..."),Uf({cwd:e}),t("Updating .gitignore..."),Vf(e),t("Marking ripplo.lock as generated..."),Nf(e),t("Installing dependencies...");let r=await $f(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 jf(e);o!=null&&n.push({manualCommand:void 0,message:o})}return t("Setting up browser..."),await Pr(),n}async function $f(e){let t=Of({cwd:e,pm:_f(e)});y.info("Installing dependencies: %s",t);try{return await Tf(t,{cwd:e}),{ok:!0}}catch(r){let n=r instanceof Error?r.message.split(`
419
- `)[0]??r.message:String(r);return y.warn("Install failed (%s): %s",t,n),{cmd:t,ok:!1,reason:n}}}async function jf(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 Nf(e){let t=U.join(e,".gitattributes"),r=L.existsSync(t)?L.readFileSync(t,"utf8"):"";if(r.includes(Ci))return;let n=r.length===0||r.endsWith(`
407
+ `);async function Qi(){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();at(e);let t=Ee(e);if(nr.existsSync(t)){process.stdout.write("Hooks already paused. Run `ripplo hooks resume` to re-enable.\n");return}nr.writeFileSync(t,""),await es(e,!0),process.stdout.write("Hooks paused. Pre-edit gates and stop enforcement are off until you run `ripplo hooks resume`.\n")}async function Zi(){let e=process.cwd(),t=Ee(e);if(!nr.existsSync(t)){process.stdout.write(`Hooks already active.
408
+ `);return}nr.unlinkSync(t),await es(e,!1),process.stdout.write(`Hooks resumed.
409
+ `)}async function es(e,t){let r;try{r=M(e)}catch{return}await y({config:r,document:Ug,variables:{paused:t,projectId:r.projectId}}).catch(()=>null)}import Ye from"fs";import Xe from"path";import{input as ns,select as os}from"@inquirer/prompts";import{graphql as oy}from"gql.tada";import{exec as Vg}from"child_process";import V from"fs";import B from"path";import{promisify as Fg}from"util";var Mg=["@ripplo/testing"],ts=".ripplo/ripplo.lock linguist-generated=true",Bg=[".ripplo/debug/",".ripplo/.local/"],Hg=Fg(Vg);async function rs({cwd:e,onStep:t}){t("Scaffolding project files..."),Xg({cwd:e}),t("Updating .gitignore..."),Qg(e),t("Marking ripplo.lock as generated..."),zg(e),t("Installing dependencies...");let r=await Wg(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 qg(e);o!=null&&n.push({manualCommand:void 0,message:o})}return t("Setting up browser..."),await Tr(),n}async function Wg(e){let t=Gg({cwd:e,pm:Yg(e)});f.info("Installing dependencies: %s",t);try{return await Hg(t,{cwd:e}),{ok:!0}}catch(r){let n=r instanceof Error?r.message.split(`
410
+ `)[0]??r.message:String(r);return f.warn("Install failed (%s): %s",t,n),{cmd:t,ok:!1,reason:n}}}async function qg(e){try{let t=await P(e);if(!t.ok)return;await le({cwd:e,result:t.result});return}catch(t){return`Couldn't compile initial lockfile: ${t instanceof Error?t.message:String(t)}.`}}function zg(e){let t=B.join(e,".gitattributes"),r=V.existsSync(t)?V.readFileSync(t,"utf8"):"";if(r.includes(ts))return;let n=r.length===0||r.endsWith(`
420
411
  `)?"":`
421
- `;L.writeFileSync(t,`${r}${n}${Ci}
422
- `)}function Of({cwd:e,pm:t}){let r=Af.join(" ");return t==="pnpm"?Df(e)?`pnpm add -wD ${r}`:`pnpm add -D ${r}`:t==="yarn"?Lf(e)?`yarn add -WD ${r}`:`yarn add -D ${r}`:t==="bun"?`bun add -d ${r}`:`npm install -D ${r}`}function Df(e){return L.existsSync(U.join(e,"pnpm-workspace.yaml"))||L.existsSync(U.join(e,"pnpm-workspace.yml"))}function Lf(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 _f(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 Uf({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}),ft(U.join(t,"index.ts"),Ff),ft(U.join(n,"index.ts"),Hf),ft(U.join(o,"index.ts"),Mf),ft(U.join(r,"index.ts"),Bf),ft(U.join(t,"tsconfig.json"),Wf)}function ft(e,t){L.existsSync(e)||L.writeFileSync(e,t)}function Vf(e){let t=U.join(e,".gitignore");if(!L.existsSync(t))return;let r=L.readFileSync(t,"utf8"),n=If.filter(i=>!r.includes(i));if(n.length===0)return;let o=r.endsWith(`
412
+ `;V.writeFileSync(t,`${r}${n}${ts}
413
+ `)}function Gg({cwd:e,pm:t}){let r=Mg.join(" ");return t==="pnpm"?Kg(e)?`pnpm add -wD ${r}`:`pnpm add -D ${r}`:t==="yarn"?Jg(e)?`yarn add -WD ${r}`:`yarn add -D ${r}`:t==="bun"?`bun add -d ${r}`:`npm install -D ${r}`}function Kg(e){return V.existsSync(B.join(e,"pnpm-workspace.yaml"))||V.existsSync(B.join(e,"pnpm-workspace.yml"))}function Jg(e){let t=B.join(e,"package.json");if(!V.existsSync(t))return!1;try{let r=JSON.parse(V.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 Yg(e){return V.existsSync(B.join(e,"pnpm-lock.yaml"))?"pnpm":V.existsSync(B.join(e,"yarn.lock"))?"yarn":V.existsSync(B.join(e,"bun.lockb"))||V.existsSync(B.join(e,"bun.lock"))?"bun":"npm"}function Xg({cwd:e}){let t=B.join(e,".ripplo"),r=B.join(t,"tests"),n=B.join(t,"preconditions"),o=B.join(t,"observers");V.mkdirSync(r,{recursive:!0}),V.mkdirSync(n,{recursive:!0}),V.mkdirSync(o,{recursive:!0}),wt(B.join(t,"index.ts"),Zg),wt(B.join(n,"index.ts"),ey),wt(B.join(o,"index.ts"),ty),wt(B.join(r,"index.ts"),ry),wt(B.join(t,"tsconfig.json"),ny)}function wt(e,t){V.existsSync(e)||V.writeFileSync(e,t)}function Qg(e){let t=B.join(e,".gitignore");if(!V.existsSync(t))return;let r=V.readFileSync(t,"utf8"),n=Bg.filter(i=>!r.includes(i));if(n.length===0)return;let o=r.endsWith(`
423
414
  `)?"":`
424
- `;L.writeFileSync(t,r+o+n.join(`
415
+ `;V.writeFileSync(t,r+o+n.join(`
425
416
  `)+`
426
- `)}var Ff=`import { createRipplo } from "@ripplo/testing";
417
+ `)}var Zg=`import { createRipplo } from "@ripplo/testing";
427
418
  import { preconditions } from "./preconditions/index";
428
419
  import { observers } from "./observers/index";
429
420
  import { tests } from "./tests/index";
430
421
 
431
422
  export { preconditions, observers, tests };
432
423
  export default createRipplo({ preconditions, observers, tests });
433
- `,Hf=`// Declare preconditions with \`precondition(name)\` from @ripplo/testing and collect them
424
+ `,ey=`// Declare preconditions with \`precondition(name)\` from @ripplo/testing and collect them
434
425
  // in the \`preconditions\` registry below. Every handle in this registry must be implemented
435
426
  // in your app server's \`createEngine(ripplo, { preconditions: {...}, observers: {...} })\` call.
436
427
  //
@@ -444,7 +435,7 @@ export default createRipplo({ preconditions, observers, tests });
444
435
  // export const preconditions = { authLoggedIn };
445
436
 
446
437
  export const preconditions = {};
447
- `,Mf=`// Declare observers with \`observer(name)\` from @ripplo/testing and collect them in
438
+ `,ty=`// Declare observers with \`observer(name)\` from @ripplo/testing and collect them in
448
439
  // the \`observers\` registry below. Use them in tests via \`assert.backend(handle, params)\`.
449
440
  //
450
441
  // Example:
@@ -457,7 +448,7 @@ export const preconditions = {};
457
448
  // export const observers = { orgNameIs };
458
449
 
459
450
  export const observers = {};
460
- `,Bf=`// Each test file under ./tests exports a TestDefinition. Import them here and add them
451
+ `,ry=`// Each test file under ./tests exports a TestDefinition. Import them here and add them
461
452
  // to the \`tests\` array \u2014 that's what \`createRipplo({ ..., tests })\` receives.
462
453
  //
463
454
  // Example:
@@ -465,7 +456,7 @@ export const observers = {};
465
456
  // export const tests = [myTest] as const;
466
457
 
467
458
  export const tests = [] as const;
468
- `,Wf=`{
459
+ `,ny=`{
469
460
  "compilerOptions": {
470
461
  "strict": true,
471
462
  "noUncheckedIndexedAccess": true,
@@ -481,62 +472,62 @@ export const tests = [] as const;
481
472
  "include": ["*.ts", "coverage.d.ts", "observers/**/*.ts", "preconditions/**/*.ts", "tests/**/*.ts"],
482
473
  "exclude": ["node_modules"]
483
474
  }
484
- `;var zf=qf(`
475
+ `;var iy=oy(`
485
476
  query InitProjects {
486
477
  projects {
487
478
  id
488
479
  name
489
480
  }
490
481
  }
491
- `),dn=["../.env.local","../.env"];async function $i(e=Jf()){let t=process.cwd(),r=ne();r==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let n=X();Gf(t)&&(process.stdout.write(`\`.ripplo/index.ts\` already exists at ${t}. Delete it first if you want to re-init.
492
- `),process.exit(1));let o=await Kf({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 Xf(o,e.projectId),s=await Qf(t,e.envFile),a=await Zf(e.appUrl),l=Yf(a,e.engineUrl),c=Ke.resolve(Ke.join(t,".ripplo"),s);wn({cwd:t,envFiles:[s],projectId:i}),rg({appUrl:a,engineUrl:l,filePath:c});let p=await Ai({cwd:t,onStep:m=>{process.stdout.write(` ${m}
482
+ `),An=["../.env.local","../.env"];async function is(e=ly()){let t=process.cwd(),r=ie();r==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let n=Z();sy(t)&&(process.stdout.write(`\`.ripplo/index.ts\` already exists at ${t}. Delete it first if you want to re-init.
483
+ `),process.exit(1));let o=await ay({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 uy(o,e.projectId),s=await dy(t,e.envFile),a=await py(e.appUrl),l=cy(a,e.engineUrl),c=Xe.resolve(Xe.join(t,".ripplo"),s);Uo({cwd:t,envFiles:[s],projectId:i}),gy({appUrl:a,engineUrl:l,filePath:c});let p=await rs({cwd:t,onStep:m=>{process.stdout.write(` ${m}
493
484
  `)}});if(p.length>0){process.stdout.write(`Done with warnings:
494
485
  `),p.forEach(m=>{process.stdout.write(` - ${m.message}
495
486
  `),m.manualCommand!=null&&process.stdout.write(` run: ${m.manualCommand}
496
- `)});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 Gf(e){return Ge.existsSync(Ke.join(e,".ripplo","index.ts"))}async function Kf({serverUrl:e,token:t}){return((await f({config:Se({serverUrl:e,token:t}),document:zf,variables:void 0})).projects??[]).map(n=>({id:n.id,name:n.name}))}function Jf(){return{appUrl:void 0,engineUrl:void 0,envFile:void 0,projectId:void 0}}function Yf(e,t){if(t!=null){try{new URL(t)}catch{process.stdout.write(`--engine-url is not a valid URL: ${t}
497
- `),process.exit(1)}return t}return`${e.replace(/\/$/,"")}/ripplo`}async function Xf(e,t){if(t!=null){let r=e.find(n=>n.id===t);return r==null&&(process.stdout.write(`Unknown project id: ${t}
487
+ `)});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 sy(e){return Ye.existsSync(Xe.join(e,".ripplo","index.ts"))}async function ay({serverUrl:e,token:t}){return((await y({config:ke({serverUrl:e,token:t}),document:iy,variables:void 0})).projects??[]).map(n=>({id:n.id,name:n.name}))}function ly(){return{appUrl:void 0,engineUrl:void 0,envFile:void 0,projectId:void 0}}function cy(e,t){if(t!=null){try{new URL(t)}catch{process.stdout.write(`--engine-url is not a valid URL: ${t}
488
+ `),process.exit(1)}return t}return`${e.replace(/\/$/,"")}/ripplo`}async function uy(e,t){if(t!=null){let r=e.find(n=>n.id===t);return r==null&&(process.stdout.write(`Unknown project id: ${t}
498
489
  `),process.exit(1)),process.stdout.write(`Using project: ${r.name} (${r.id})
499
490
  `),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})
500
- `),r.id}return Ti({choices:e.map(r=>({name:r.name,value:r.id})),message:"Select a project"})}async function Qf(e,t){return t!=null?(t.trim().length===0&&(process.stdout.write(`--env must not be empty
501
- `),process.exit(1)),t):eg(e)}async function Zf(e){if(e!=null){try{new URL(e)}catch{process.stdout.write(`--app-url is not a valid URL: ${e}
502
- `),process.exit(1)}return e}return tg()}async function eg(e){let t=Ke.join(e,".ripplo"),r=dn.find(o=>Ge.existsSync(Ke.resolve(t,o))),n=await Ti({choices:[...dn.map(o=>({name:r===o?`${o} (detected)`:o,value:o})),{name:"custom path",value:"__custom__"}],default:r??dn[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:Ii({message:"Path to env file (relative to .ripplo/, e.g. ../apps/server/.env)",validate:o=>o.trim().length>0?!0:"required"})}async function tg(){return Ii({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 rg({appUrl:e,engineUrl:t,filePath:r}){Ge.mkdirSync(Ke.dirname(r),{recursive:!0});let n=Ge.existsSync(r)?Ge.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=${Nr()}`),/^ENABLE_RIPPLO_TESTING=/m.test(n)||o.push("ENABLE_RIPPLO_TESTING=true"),o.length===0)return;let i=n.length===0||n.endsWith(`
491
+ `),r.id}return os({choices:e.map(r=>({name:r.name,value:r.id})),message:"Select a project"})}async function dy(e,t){return t!=null?(t.trim().length===0&&(process.stdout.write(`--env must not be empty
492
+ `),process.exit(1)),t):my(e)}async function py(e){if(e!=null){try{new URL(e)}catch{process.stdout.write(`--app-url is not a valid URL: ${e}
493
+ `),process.exit(1)}return e}return fy()}async function my(e){let t=Xe.join(e,".ripplo"),r=An.find(o=>Ye.existsSync(Xe.resolve(t,o))),n=await os({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:ns({message:"Path to env file (relative to .ripplo/, e.g. ../apps/server/.env)",validate:o=>o.trim().length>0?!0:"required"})}async function fy(){return ns({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 gy({appUrl:e,engineUrl:t,filePath:r}){Ye.mkdirSync(Xe.dirname(r),{recursive:!0});let n=Ye.existsSync(r)?Ye.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=${Mr()}`),/^ENABLE_RIPPLO_TESTING=/m.test(n)||o.push("ENABLE_RIPPLO_TESTING=true"),o.length===0)return;let i=n.length===0||n.endsWith(`
503
494
  `)?"":`
504
- `;Ge.writeFileSync(r,`${n}${i}${o.join(`
495
+ `;Ye.writeFileSync(r,`${n}${i}${o.join(`
505
496
  `)}
506
- `)}import un from"fs";import ji from"path";import*as Ni from"remeda";import ng from"path";import{graphql as og}from"gql.tada";var ig=og(`
497
+ `)}import In from"fs";import ss from"path";import*as as from"remeda";import yy from"path";import{graphql as hy}from"gql.tada";var wy=hy(`
507
498
  mutation AutoScopeAddDirty($projectId: String!, $cwd: String!, $workflowSlugs: [String!]!) {
508
499
  addDirtyTestsToScope(projectId: $projectId, cwd: $cwd, workflowSlugs: $workflowSlugs) {
509
500
  id
510
501
  }
511
502
  }
512
- `);async function Je({compileResult:e,cwd:t}){if(!$(t))return{addedSlugs:[]};let r=sg(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 pt({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:ig,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 sg(e){let t;try{t=M(["status","--porcelain","--",".ripplo/tests"],e)}catch{return[]}return t.split(`
513
- `).map(r=>r.slice(3).trim()).filter(r=>/^\.ripplo\/tests\/[^/]+\.ts$/.test(r)).map(r=>ng.basename(r,".ts")).filter(r=>r!=="index")}async function Oi(e){let{ids:t,requireImplemented:r}=e,n=process.cwd(),o=await P(n);o.ok||(process.stderr.write(`Compilation failed: ${o.error}
514
- `),process.stderr.write(`${h("create","DSL authoring + lint rules")}
515
- `),process.exit(1)),await ce({cwd:n,result:o.result});let i=Fe(o.result),s=t.length===0?i.diagnostics:i.diagnostics.filter(g=>t.includes(g.test)),a=Ni.groupBy(s,g=>g.test);Object.entries(a).forEach(([g,q])=>{process.stderr.write(`
503
+ `);async function Qe({compileResult:e,cwd:t}){if(!_(t))return{addedSlugs:[]};let r=by(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=M(t)}catch{return{addedSlugs:[]}}if(await yt({compiled:e.result,config:i,cwd:t}).catch(c=>(f.warn("auto-sync failed: %s",c instanceof Error?c.message:String(c)),null))==null)return{addedSlugs:[]};let a=await y({config:i,document:wy,variables:{cwd:i.cwd,projectId:i.projectId,workflowSlugs:o}}).catch(c=>(f.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 by(e){let t;try{t=z(["status","--porcelain","--",".ripplo/tests"],e)}catch{return[]}return t.split(`
504
+ `).map(r=>r.slice(3).trim()).filter(r=>/^\.ripplo\/tests\/[^/]+\.ts$/.test(r)).map(r=>yy.basename(r,".ts")).filter(r=>r!=="index")}async function ls(e){let{ids:t,requireImplemented:r}=e,n=process.cwd(),o=await P(n);o.ok||(process.stderr.write(`Compilation failed: ${o.error}
505
+ `),process.stderr.write(`${w("create","DSL authoring + lint rules")}
506
+ `),process.exit(1)),await le({cwd:n,result:o.result});let i=He(o.result),s=t.length===0?i.diagnostics:i.diagnostics.filter(g=>t.includes(g.test)),a=as.groupBy(s,g=>g.test);Object.entries(a).forEach(([g,H])=>{process.stderr.write(`
516
507
  ${g}
517
- `),q.forEach(j=>{let V=j.step==null?"":` at "${j.step}"`;process.stderr.write(` [${j.rule}]${V}
518
- `),process.stderr.write(` ${j.message}
508
+ `),H.forEach(x=>{let F=x.step==null?"":` at "${x.step}"`;process.stderr.write(` [${x.rule}]${F}
509
+ `),process.stderr.write(` ${x.message}
519
510
  `)})});let l=new Set(o.builder.getUnimplemented().tests),c=r.filter(g=>l.has(g));c.length>0&&(process.stderr.write(`
520
511
  not-implemented
521
512
  `),c.forEach(g=>{process.stderr.write(` ${g} is still marked .notImplemented()
522
- `)}));let p=dg(n);p.length>0&&(process.stderr.write(`
513
+ `)}));let p=Ry(n);p.length>0&&(process.stderr.write(`
523
514
  preconditions
524
515
  `),p.forEach(g=>{process.stderr.write(` [hardcoded-identifier] ${g.file}
525
516
  `),process.stderr.write(` ${g.message}
526
517
  `)}));let m=s.length+c.length+p.length;m>0&&(process.stderr.write(`
527
518
  ${String(m)} error(s)
528
- `),ag({diagnostics:s,hardcodeWarnings:p,stillStubbed:c}),process.exit(1));let S=o.result.tests.length,N=t.length===0?"all tests":`${String(t.length)} test(s)`;process.stdout.write(`\u2713 ripplo lint: ${N} passed (${String(S)} compiled, lockfile written)
529
- `);let{addedSlugs:O}=await Je({compileResult:o,cwd:n});O.length>0&&process.stdout.write(`\u2713 Auto-scoped ${O.join(", ")} (dirty tests).
530
- `)}function ag({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)}
531
- `))}var lg=/['"`][\w.+-]+@[\w.-]+\.[a-z]{2,}['"`]/i,cg=/['"`][0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}['"`]/i;function dg(e){let t=ji.join(e,".ripplo","preconditions");return un.existsSync(t)?un.readdirSync(t).filter(n=>n.endsWith(".ts")).flatMap(n=>ug(ji.join(t,n))):[]}function ug(e){let t=un.readFileSync(e,"utf8"),r=t.includes("ctx.uniqueEmail")||t.includes("ctx.uniqueId"),n=[],o=lg.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=cg.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 pg}from"gql.tada";var mg=pg(`
519
+ `),vy({diagnostics:s,hardcodeWarnings:p,stillStubbed:c}),process.exit(1));let h=o.result.tests.length,T=t.length===0?"all tests":`${String(t.length)} test(s)`;process.stdout.write(`\u2713 ripplo lint: ${T} passed (${String(h)} compiled, lockfile written)
520
+ `);let{addedSlugs:$}=await Qe({compileResult:o,cwd:n});$.length>0&&process.stdout.write(`\u2713 Auto-scoped ${$.join(", ")} (dirty tests).
521
+ `)}function vy({diagnostics:e,hardcodeWarnings:t,stillStubbed:r}){let n=new Set;(e.length>0||r.length>0)&&n.add("create"),t.length>0&&n.add("explore"),n.forEach(o=>process.stderr.write(`${w(o)}
522
+ `))}var Sy=/['"`][\w.+-]+@[\w.-]+\.[a-z]{2,}['"`]/i,ky=/['"`][0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}['"`]/i;function Ry(e){let t=ss.join(e,".ripplo","preconditions");return In.existsSync(t)?In.readdirSync(t).filter(n=>n.endsWith(".ts")).flatMap(n=>Py(ss.join(t,n))):[]}function Py(e){let t=In.readFileSync(e,"utf8"),r=t.includes("ctx.uniqueEmail")||t.includes("ctx.uniqueId"),n=[],o=Sy.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=ky.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 xy}from"gql.tada";var Ey=xy(`
532
523
  query ProjectsList {
533
524
  projects {
534
525
  id
535
526
  name
536
527
  }
537
528
  }
538
- `);async function Di(){let e=ne();e==null&&(process.stderr.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let t=X(),n=((await f({config:Se({serverUrl:t,token:e}),document:mg,variables:void 0})).projects??[]).map(o=>({id:o.id,name:o.name}));process.stdout.write(`${JSON.stringify({projects:n},null,2)}
539
- `)}import{graphql as fg}from"gql.tada";var Yt=fg(`
529
+ `);async function cs(){let e=ie();e==null&&(process.stderr.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let t=Z(),n=((await y({config:ke({serverUrl:t,token:e}),document:Ey,variables:void 0})).projects??[]).map(o=>({id:o.id,name:o.name}));process.stdout.write(`${JSON.stringify({projects:n},null,2)}
530
+ `)}import{graphql as Cy}from"gql.tada";var or=Cy(`
540
531
  query ScopeStatus($projectId: String!, $cwd: String!) {
541
532
  project(id: $projectId) {
542
533
  id
@@ -556,17 +547,17 @@ ${String(m)} error(s)
556
547
  }
557
548
  }
558
549
  }
559
- `);async function Li({all:e,ids:t}){e&&t.length>0&&(process.stderr.write(`Pass either --all or test ids, not both.
560
- `),process.exit(1));let r=ue();await ge(r);let n=await gg({all:e,cwd:r.cwd,ids:t});n==null&&process.exit(1);let{results:o,summary:i}=await Kt({config:r,ids:n,presynced:void 0});process.stdout.write(`${i}
550
+ `);async function us({all:e,ids:t}){e&&t.length>0&&(process.stderr.write(`Pass either --all or test ids, not both.
551
+ `),process.exit(1));let r=ue();await fe(r);let n=await Ty({all:e,cwd:r.cwd,ids:t});n==null&&process.exit(1);let{results:o,summary:i}=await rr({config:r,ids:n,presynced:void 0});process.stdout.write(`${i}
561
552
  `);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.
562
- `),process.stderr.write(`${h("debug")}
563
- `)),process.exit(s?1:0)}async function gg({all:e,cwd:t,ids:r}){return r.length>0?r:e?[]:yg(t)}async function yg(e){let t=ue(),r=await P(e);if(r.ok){let{addedSlugs:a}=await Je({compileResult:r,cwd:e});a.length>0&&process.stdout.write(`Auto-scoped ${a.join(", ")} (dirty tests).
564
- `)}let o=(await f({config:t,document:Yt,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(", ")}
565
- `),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")}
566
- `),null):i}async function _i(){let e=process.cwd(),t=_(e);try{let r=await fe(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}
553
+ `),process.stderr.write(`${w("debug")}
554
+ `)),process.exit(s?1:0)}async function Ty({all:e,cwd:t,ids:r}){return r.length>0?r:e?[]:Ay(t)}async function Ay(e){let t=ue(),r=await P(e);if(r.ok){let{addedSlugs:a}=await Qe({compileResult:r,cwd:e});a.length>0&&process.stdout.write(`Auto-scoped ${a.join(", ")} (dirty tests).
555
+ `)}let o=(await y({config:t,document:or,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(", ")}
556
+ `),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(`${w("scope")}
557
+ `),null):i}async function ds(){let e=process.cwd(),t=M(e);try{let r=await me(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}
567
558
  `)}catch(r){let n=r instanceof Error?r.message:String(r);process.stderr.write(`ripplo sync failed: ${n}
568
- `),process.stderr.write(`${h("setup","verify auth + server reachability")}
569
- `),process.exit(1)}}import Xt from"fs";import{createClient as Rg}from"graphql-sse";import{graphql as Qt}from"gql.tada";import{print as Vi}from"graphql";import{availableParallelism as hg}from"os";import wg from"p-limit";var bg=Math.max(1,Math.min(10,Math.floor(hg()/2))),vg=wg(bg),pn=new Set;async function Ui(e){if(!pn.has(e.runId)){pn.add(e.runId);try{await vg(()=>Sg(e))}finally{pn.delete(e.runId)}}}async function Sg({config:e,cwd:t,runId:r,workflowSlug:n}){let o=await rt({headed:!1});try{await xr({maxRuns:100});let i=t!=null&&n!=null?await kg({cwd:t,workflowSlug:n}):void 0;await Vr({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 kg({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 Pg=15e3,xg=Qt(`
559
+ `),process.stderr.write(`${w("setup","verify auth + server reachability")}
560
+ `),process.exit(1)}}import ir from"fs";import{createClient as Dy}from"graphql-sse";import{graphql as Ze}from"gql.tada";import{print as jn}from"graphql";import Iy from"p-limit";var $y=4,ps=Iy($y),bt=new Set;function $n(e){!Number.isFinite(e)||e<1||(ps.concurrency=Math.floor(e),f.debug({concurrency:e},"Local executor concurrency set to %d",e))}var Ce;async function ms(e){if(!bt.has(e.runId)){bt.add(e.runId),f.debug({inflight:bt.size,runId:e.runId},"run dispatched (inflight=%d)",bt.size);try{await ps(()=>Ny(e))}finally{bt.delete(e.runId)}}}async function fs(){if(Ce==null)return;let e=await Ce.catch(()=>{});Ce=void 0,e!=null&&e.isConnected()&&await e.close().catch(()=>{})}async function jy(){Ce??=Le({headed:!1});let e=Ce,t=await e;return t.isConnected()?t:(Ce===e&&(Ce=Le({headed:!1})),Ce)}async function Ny({config:e,cwd:t,runId:r,workflowSlug:n}){try{let o=await jy(),i=t!=null&&n!=null?await Oy({cwd:t,workflowSlug:n}):void 0;await Xr({baseUrl:e.appUrl,browser:o,config:e,headed:!1,preconditionNames:i,runId:r,webhookSecret:e.webhookSecret})}catch(o){f.error(o,"Runner error")}}async function Oy({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 Ly=6e4,gs=100,_y=15e3,Uy=Ze(`
570
561
  subscription RunRequestedWatch($devSessionId: String!) {
571
562
  runRequested(devSessionId: $devSessionId) {
572
563
  runId
@@ -574,30 +565,41 @@ ${String(m)} error(s)
574
565
  workflowSlug
575
566
  }
576
567
  }
577
- `),Eg=Qt(`
568
+ `),Vy=Ze(`
578
569
  subscription HooksPausedWatch($projectId: String!) {
579
570
  hooksPausedRequested(projectId: $projectId) {
580
571
  paused
581
572
  projectId
582
573
  }
583
574
  }
584
- `),Cg=Qt(`
575
+ `),Fy=Ze(`
585
576
  mutation HeartbeatDevSessionWatch($id: String!) {
586
577
  heartbeatDevSession(id: $id) {
587
578
  id
588
579
  }
589
580
  }
590
- `),Ag=Qt(`
581
+ `),My=Ze(`
582
+ query WatchLocalConcurrency {
583
+ currentUser {
584
+ id
585
+ maxLocalConcurrentRuns
586
+ }
587
+ }
588
+ `),By=Ze(`
589
+ subscription WatchLocalConcurrencyChanged {
590
+ myMaxLocalConcurrentRunsChanged
591
+ }
592
+ `),Hy=Ze(`
591
593
  mutation EndDevSessionWatch($projectId: String!, $cwd: String!) {
592
594
  endDevSession(projectId: $projectId, cwd: $cwd) {
593
595
  id
594
596
  }
595
597
  }
596
- `);async function Fi(){Vg();let e=jg(process.cwd()),t=e.cwd,r=await P(t);r.ok||(process.stderr.write(`ripplo: DSL compilation failed: ${r.error}
597
- `),process.exit(1));let n=await Dg(()=>pt({compiled:r.result,config:e,cwd:t}));Hi({cwd:t,paused:n.hooksPaused});let o=zt(t);o!=null&&y.info("watching branch %s in %s",o,t);let i=si(t),s=Rg({headers:{Authorization:`Bearer ${e.token}`},retryAttempts:1/0,url:`${e.ripploServerUrl}/graphql`}),a=Ig({config:e,cwd:t,devSessionId:n.devSessionId,sseClient:s}),l=Tg({cwd:t,projectId:e.projectId,sseClient:s}),c=$g({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)
598
- `);let p=async()=>{c(),a(),l(),await Promise.race([f({config:e,document:Ag,variables:{cwd:e.cwd,projectId:e.projectId}}).catch(()=>{}),new Promise(S=>setTimeout(S,3e3))]),i()},m=()=>{p().finally(()=>process.exit(0))};process.on("SIGINT",m),process.on("SIGTERM",m),process.on("SIGHUP",m),process.on("SIGBREAK",m),await new Promise(()=>{})}function Ig({config:e,cwd:t,devSessionId:r,sseClient:n}){return n.subscribe({query:Vi(xg),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})
599
- `),Ui({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 Hi({cwd:e,paused:t}){let r=xe(e);if(t&&!Xt.existsSync(r)){Xt.writeFileSync(r,"");return}!t&&Xt.existsSync(r)&&Xt.unlinkSync(r)}function Tg({cwd:e,projectId:t,sseClient:r}){return r.subscribe({query:Vi(Eg),variables:{projectId:t}},{complete:()=>{},error:n=>{y.error(n,"hooksPaused subscription error")},next:n=>{let o=n.data?.hooksPausedRequested?.paused;o!=null&&Hi({cwd:e,paused:o})}})}function $g({config:e,devSessionId:t}){let r=setInterval(()=>{f({config:e,document:Cg,variables:{id:t}}).catch(n=>{y.warn("heartbeat failed: %s",n instanceof Error?n.message:String(n))})},Pg);return()=>{clearInterval(r)}}function jg(e){try{return _(e)}catch(t){let r=t instanceof Error?t.message:String(t);process.stderr.write(`${r}
600
- `),process.exit(1)}}var Ng=1e3,Og=6e4;async function Dg(e){let t=Date.now()+Og,r;for(;Date.now()<t;){let n=await Lg(e);if(n.ok)return n.value;if(!_g(n.message))throw n.error;r=n.error,await Ug(Ng)}throw r instanceof Error?r:new Error("server never became ready")}async function Lg(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 _g(e){return e.includes("status 502")||e.includes("ECONNREFUSED")||e.includes("Failed to connect")||e.includes("fetch failed")}function Ug(e){return new Promise(t=>setTimeout(t,e))}function Vg(){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 Zt}from"gql.tada";var Fg=Zt(`
598
+ `);async function ys(){rh();let e=Ky(process.cwd()),t=e.cwd,r=await P(t);r.ok||(process.stderr.write(`ripplo: DSL compilation failed: ${r.error}
599
+ `),process.exit(1));let n=await Xy(()=>yt({compiled:r.result,config:e,cwd:t}));await nh(e),hs({cwd:t,paused:n.hooksPaused});let o=er(t);o!=null&&f.info("watching branch %s in %s",o,t);let i=Oi(t),s=Dy({headers:{Authorization:`Bearer ${e.token}`},retryAttempts:1/0,url:`${e.ripploServerUrl}/graphql`}),a=Wy({config:e,cwd:t,devSessionId:n.devSessionId,sseClient:s}),l=zy({cwd:t,projectId:e.projectId,sseClient:s}),c=qy({sseClient:s}),p=Gy({config:e,devSessionId:n.devSessionId}),m=th();process.stdout.write(`ripplo watch: ready as local executor for session ${n.devSessionId} (sync happens on each \`ripplo run\`; Ctrl-C to stop)
600
+ `);let h=async()=>{p(),m(),a(),l(),c(),await Promise.race([y({config:e,document:Hy,variables:{cwd:e.cwd,projectId:e.projectId}}).catch(()=>{}),new Promise($=>setTimeout($,3e3))]),await fs(),Kr(),i()},T=()=>{h().finally(()=>process.exit(0))};process.on("SIGINT",T),process.on("SIGTERM",T),process.on("SIGHUP",T),process.on("SIGBREAK",T),await new Promise(()=>{})}function Wy({config:e,cwd:t,devSessionId:r,sseClient:n}){return n.subscribe({query:jn(Uy),variables:{devSessionId:r}},{complete:()=>{},error:o=>{f.error(o,"runRequested subscription error")},next:o=>{let i=o.data?.runRequested;i!=null&&(process.stdout.write(`ripplo: run ${i.workflowSlug}
601
+ `),ms({config:e,cwd:t,runId:i.runId,workflowId:i.workflowId,workflowSlug:i.workflowSlug}).catch(s=>{f.error({err:s,runId:i.runId,workflowSlug:i.workflowSlug},"run execution failed; watch continuing")}))}})}function hs({cwd:e,paused:t}){let r=Ee(e);if(t&&!ir.existsSync(r)){ir.writeFileSync(r,"");return}!t&&ir.existsSync(r)&&ir.unlinkSync(r)}function qy({sseClient:e}){return e.subscribe({query:jn(By)},{complete:()=>{},error:t=>{f.error(t,"localConcurrency subscription error")},next:t=>{let r=t.data?.myMaxLocalConcurrentRunsChanged;r!=null&&$n(r)}})}function zy({cwd:e,projectId:t,sseClient:r}){return r.subscribe({query:jn(Vy),variables:{projectId:t}},{complete:()=>{},error:n=>{f.error(n,"hooksPaused subscription error")},next:n=>{let o=n.data?.hooksPausedRequested?.paused;o!=null&&hs({cwd:e,paused:o})}})}function Gy({config:e,devSessionId:t}){let r=setInterval(()=>{y({config:e,document:Fy,variables:{id:t}}).catch(n=>{f.warn("heartbeat failed: %s",n instanceof Error?n.message:String(n))})},_y);return()=>{clearInterval(r)}}function Ky(e){try{return M(e)}catch(t){let r=t instanceof Error?t.message:String(t);process.stderr.write(`${r}
602
+ `),process.exit(1)}}var Jy=1e3,Yy=6e4;async function Xy(e){let t=Date.now()+Yy,r;for(;Date.now()<t;){let n=await Qy(e);if(n.ok)return n.value;if(!Zy(n.message))throw n.error;r=n.error,await eh(Jy)}throw r instanceof Error?r:new Error("server never became ready")}async function Qy(e){try{return{ok:!0,value:await e()}}catch(t){let r=t instanceof Error?t.message:String(t);return{error:t,message:r,ok:!1}}}function Zy(e){return e.includes("status 502")||e.includes("ECONNREFUSED")||e.includes("Failed to connect")||e.includes("fetch failed")}function eh(e){return new Promise(t=>setTimeout(t,e))}function th(){xt({maxRuns:gs});let e=setInterval(()=>{xt({maxRuns:gs})},Ly);return()=>{clearInterval(e)}}function rh(){process.on("unhandledRejection",e=>{f.error({err:e},"unhandledRejection in watch; continuing")}),process.on("uncaughtException",e=>{f.error({err:e},"uncaughtException in watch; continuing")})}async function nh(e){try{let r=(await y({config:e,document:My,variables:void 0})).currentUser?.maxLocalConcurrentRuns;r!=null&&$n(r)}catch(t){f.warn({err:t},"failed to fetch local concurrency setting; using default")}}import{graphql as sr}from"gql.tada";var oh=sr(`
601
603
  query ScopeWorkflowBySlug($projectId: String!, $cwd: String!, $slug: String!) {
602
604
  project(id: $projectId) {
603
605
  id
@@ -610,7 +612,7 @@ ${String(m)} error(s)
610
612
  }
611
613
  }
612
614
  }
613
- `),Hg=Zt(`
615
+ `),ih=sr(`
614
616
  mutation ScopeAddDirtyTests($projectId: String!, $cwd: String!, $workflowSlugs: [String!]!) {
615
617
  addDirtyTestsToScope(projectId: $projectId, cwd: $cwd, workflowSlugs: $workflowSlugs) {
616
618
  id
@@ -620,35 +622,35 @@ ${String(m)} error(s)
620
622
  }
621
623
  }
622
624
  }
623
- `),Mg=Zt(`
625
+ `),sh=sr(`
624
626
  mutation ScopeLink($id: ID!, $workflowId: String!) {
625
627
  linkScopeItem(id: $id, workflowId: $workflowId) {
626
628
  id
627
629
  }
628
630
  }
629
- `),Bg=Zt(`
631
+ `),ah=sr(`
630
632
  mutation ScopeRemoveMany($ids: [ID!]!) {
631
633
  removeScopeItems(ids: $ids)
632
634
  }
633
- `);async function Mi(e){let t=ue();await ge(t);let n=(await f({config:t,document:Yt,variables:{cwd:t.cwd,projectId:t.projectId}})).project?.devSession?.scopeItems??[];if(e.format==="json"){process.stdout.write(`${JSON.stringify(n,null,2)}
635
+ `);async function ws(e){let t=ue();await fe(t);let n=(await y({config:t,document:or,variables:{cwd:t.cwd,projectId:t.projectId}})).project?.devSession?.scopeItems??[];if(e.format==="json"){process.stdout.write(`${JSON.stringify(n,null,2)}
634
636
  `);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??""}
635
637
  `);return}let s=i.spec==null?"stub":"implemented";process.stdout.write(` [${s}] (${o.id}) ${i.slug} \u2014 ${i.name}
636
- `)})}async function Bi({testIds:e}){let t=ue();await ge(t),await fe(t.cwd,t);let n=(await f({config:t,document:Hg,variables:{cwd:t.cwd,projectId:t.projectId,workflowSlugs:[...e]}})).addDirtyTestsToScope??[];if(n.length===0){process.stdout.write(`No scope items added.
638
+ `)})}async function bs({testIds:e}){let t=ue();await fe(t),await me(t.cwd,t);let n=(await y({config:t,document:ih,variables:{cwd:t.cwd,projectId:t.projectId,workflowSlugs:[...e]}})).addDirtyTestsToScope??[];if(n.length===0){process.stdout.write(`No scope items added.
637
639
  `);return}let o=n.map(i=>i.workflow?.slug??"?").join(", ");process.stdout.write(`Added ${String(n.length)} scope item(s): ${o}
638
- `)}async function Wi({id:e,testId:t}){let r=ue();await ge(r),await fe(r.cwd,r);let n=await Wg({cfg:r,slug:t});await f({config:r,document:Mg,variables:{id:e,workflowId:n}}),process.stdout.write(`Linked scope item ${e} to ${t}
639
- `)}async function qi({ids:e}){let t=ue();await ge(t);let n=(await f({config:t,document:Bg,variables:{ids:[...e]}})).removeScopeItems??0;process.stdout.write(`Removed ${String(n)} scope item(s)
640
- `)}async function Wg({cfg:e,slug:t}){let n=(await f({config:e,document:Fg,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.
641
- `),process.stderr.write(`${h("create")}
642
- `),process.exit(1)),n.id}async function zi(e){let t=process.cwd(),r=await P(t);r.ok||(process.stderr.write(`Compilation failed: ${r.error}
640
+ `)}async function vs({id:e,testId:t}){let r=ue();await fe(r),await me(r.cwd,r);let n=await lh({cfg:r,slug:t});await y({config:r,document:sh,variables:{id:e,workflowId:n}}),process.stdout.write(`Linked scope item ${e} to ${t}
641
+ `)}async function Ss({ids:e}){let t=ue();await fe(t);let n=(await y({config:t,document:ah,variables:{ids:[...e]}})).removeScopeItems??0;process.stdout.write(`Removed ${String(n)} scope item(s)
642
+ `)}async function lh({cfg:e,slug:t}){let n=(await y({config:e,document:oh,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.
643
+ `),process.stderr.write(`${w("create")}
644
+ `),process.exit(1)),n.id}async function ks(e){let t=process.cwd(),r=await P(t);r.ok||(process.stderr.write(`Compilation failed: ${r.error}
643
645
  `),process.exit(1));let{tests:n}=r.builder.getUnimplemented();if(e.format==="summary"){n.length>0&&process.stdout.write(`tests: ${n.join(", ")}
644
646
  `);return}let o={tests:n.map(i=>({id:i,implemented:!1}))};process.stdout.write(`${JSON.stringify(o,null,2)}
645
- `)}import{z as qg}from"zod";function A(e,t){let r=qg.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 hE}from"crypto";import Gi from"picomatch";function zg(e){return M(["diff","--name-only","HEAD"],e).split(`
646
- `).filter(t=>t.length>0)}function Ki({cwd:e,ignoreGlobs:t,watchGlobs:r}){let n=Gi([...r]),o=Gi([...t]);return zg(e).filter(i=>n(i)&&!o(i))}function er(e,...t){return M(["diff","--name-only","HEAD","--",...t],e).split(`
647
- `).filter(r=>r.length>0)}function Ee(){return{ignorePaths:Re,watchPaths:Qr}}var Ji=A("UserPromptSubmit",e=>{let{cwd:t}=e;if(!C(t)||!$(t))return;let r=Pe(t);if(qe(t,"coverage-nudge")===r)return;let{ignorePaths:n,watchPaths:o}=Ee(),i=Ki({cwd:t,ignoreGlobs:n,watchGlobs:o});if(ze(t,"coverage-nudge",r),!(i.length===0||er(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 tr from"fs";import Gg from"os";import Yi from"path";var Xi=A("PreToolUse",e=>{if(e.tool_name!=="ExitPlanMode"||!$(e.cwd))return;let t=Kg();if(t==null)return;let r=tr.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 Kg(){let e=Yi.join(Gg.homedir(),".claude","plans");return tr.existsSync(e)?tr.readdirSync(e).filter(r=>r.endsWith(".md")).map(r=>Yi.join(e,r)).map(r=>({full:r,mtime:tr.statSync(r).mtimeMs})).sort((r,n)=>n.mtime-r.mtime)[0]?.full??null:null}var Qi=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(`
648
- `),hookEventName:"UserPromptSubmit"}}});import Jg from"path";import Zi from"picomatch";import{z as es}from"zod";var Yg=es.looseObject({file_path:es.string()}),ts=A("PostToolUse",async e=>{let t=Yg.safeParse(e.tool_input);if(!t.success)return;let r=t.data.file_path,{cwd:n}=e;if(!C(n)||!$(n))return;let o=Jg.relative(n,r);if(o.startsWith(".."))return;let{ignorePaths:i,watchPaths:s}=Ee(),a=Zi([...s]),l=Zi([...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 rs}from"zod";var Xg=rs.looseObject({file_path:rs.string()}),ns=A("PostToolUse",async e=>{let t=Xg.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}
649
- ${h("create","DSL authoring + lint rules")}`};await ce({cwd:n,result:o.result}),Me({cwd:n});let{diagnostics:i}=Fe(o.result);if(i.length===0){let{addedSlugs:a}=await Je({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(`
647
+ `)}import{z as ch}from"zod";function I(e,t){let r=ch.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 XC}from"crypto";import Rs from"picomatch";function uh(e){return z(["diff","--name-only","HEAD"],e).split(`
648
+ `).filter(t=>t.length>0)}function Ps({cwd:e,ignoreGlobs:t,watchGlobs:r}){let n=Rs([...r]),o=Rs([...t]);return uh(e).filter(i=>n(i)&&!o(i))}function ar(e,...t){return z(["diff","--name-only","HEAD","--",...t],e).split(`
649
+ `).filter(r=>r.length>0)}function Te(){return{ignorePaths:Pe,watchPaths:wn}}var xs=I("UserPromptSubmit",e=>{let{cwd:t}=e;if(!A(t)||!_(t))return;let r=xe(t);if(Ke(t,"coverage-nudge")===r)return;let{ignorePaths:n,watchPaths:o}=Te(),i=Ps({cwd:t,ignoreGlobs:n,watchGlobs:o});if(Je(t,"coverage-nudge",r),!(i.length===0||ar(t,".ripplo/tests",".ripplo/preconditions",".ripplo/observers").length>0))return{hookSpecificOutput:{additionalContext:`SCOPE DRIFT: ${String(i.length)} app file(s) changed without .ripplo/tests updates. ${w("scope")}`,hookEventName:"UserPromptSubmit"}}});import lr from"fs";import dh from"os";import Es from"path";var Cs=I("PreToolUse",e=>{if(e.tool_name!=="ExitPlanMode"||!_(e.cwd))return;let t=ph();if(t==null)return;let r=lr.readFileSync(t,"utf8");if(!/\.ripplo\/tests|Tests to implement|No e2e coverage needed/.test(r))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Plan must cite ripplo test stubs. Add a "Tests to implement" section listing .ripplo/tests/<id>.ts per affected flow, OR add "No e2e coverage needed: <reason>" if this plan touches no user-facing behavior. ${w("explore")}`}}});function ph(){let e=Es.join(dh.homedir(),".claude","plans");return lr.existsSync(e)?lr.readdirSync(e).filter(r=>r.endsWith(".md")).map(r=>Es.join(e,r)).map(r=>({full:r,mtime:lr.statSync(r).mtimeMs})).sort((r,n)=>n.mtime-r.mtime)[0]?.full??null:null}var Ts=I("UserPromptSubmit",async e=>{if(e.permission_mode!=="plan"||!A(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(`
650
+ `),hookEventName:"UserPromptSubmit"}}});import mh from"path";import As from"picomatch";import{z as Is}from"zod";var fh=Is.looseObject({file_path:Is.string()}),$s=I("PostToolUse",async e=>{let t=fh.safeParse(e.tool_input);if(!t.success)return;let r=t.data.file_path,{cwd:n}=e;if(!A(n)||!_(n))return;let o=mh.relative(n,r);if(o.startsWith(".."))return;let{ignorePaths:i,watchPaths:s}=Te(),a=As([...s]),l=As([...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 js}from"zod";var gh=js.looseObject({file_path:js.string()}),Ns=I("PostToolUse",async e=>{let t=gh.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(!A(n)||!_(n))return;let o=await P(n);if(!o.ok)return{decision:"block",reason:`Compilation failed: ${o.error}
651
+ ${w("create","DSL authoring + lint rules")}`};await le({cwd:n,result:o.result}),qe({cwd:n});let{diagnostics:i}=He(o.result);if(i.length===0){let{addedSlugs:a}=await Qe({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(`
650
652
  `)}
651
- ${h("create")}`}});import{z as os}from"zod";var Qg=os.looseObject({command:os.string()}),Zg=/\bripplo\s+hooks\s+pause\b/,is=A("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=Qg.safeParse(e.tool_input);if(!t.success||!Zg.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 oy}from"shell-quote";import{z as ls}from"zod";import{existsSync as ey,mkdirSync as ty,rmSync as fC,writeFileSync as ry}from"fs";import mn from"path";function ss(e,t,r){let n=as(e,t,r);ty(mn.dirname(n),{recursive:!0}),ry(n,"")}function rr(e,t,r){return ey(as(e,t,r))}function ny(e,t){return mn.join(e,".ripplo",".local","skills-loaded",t)}function as(e,t,r){return mn.join(ny(e,t),r)}var iy=ls.looseObject({command:ls.string()}),sy="debug",ay=new Set(["tail","head","less","more","wc","sort","uniq","awk","sed","grep"]),ds=A("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=iy.safeParse(e.tool_input);if(!t.success)return;let r=ly(t.data.command);if(!cy(r))return;let{cwd:n}=e;if(!C(n)||!$(n))return;let o=uy(r);if(o!=null)return cs(`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(!rr(n,e.session_id,sy))return cs("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 ly(e){try{return oy(e)}catch{return[]}}function cy(e){return e.some((t,r)=>t==="ripplo"&&e[r+1]==="run")}function dy(e){return typeof e=="object"&&"op"in e&&e.op==="|"}function uy(e){let t=e.find((r,n)=>{let o=e[n-1];return o!=null&&dy(o)&&typeof r=="string"&&ay.has(r)});return typeof t=="string"?t:null}function cs(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}}}import py from"path";import{z as us}from"zod";var my=new Set(["Edit","Write","NotebookEdit"]),fy=us.looseObject({file_path:us.string()}),gy="create",ps=A("PreToolUse",e=>{if(!my.has(e.tool_name))return;let t=fy.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!C(r)||!$(r))return;let n=py.relative(r,t.data.file_path);if(!(n.startsWith("..")||n!==".ripplo"&&!n.startsWith(".ripplo/"))&&!rr(r,e.session_id,gy))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 yy from"path";import ms from"picomatch";import{graphql as hy}from"gql.tada";import{z as fs}from"zod";var wy=new Set(["Edit","Write","NotebookEdit"]),by=fs.looseObject({file_path:fs.string()}),vy=hy(`
653
+ ${w("create")}`}});import{z as Os}from"zod";var yh=Os.looseObject({command:Os.string()}),hh=/\bripplo\s+hooks\s+pause\b/,Ds=I("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=yh.safeParse(e.tool_input);if(!t.success||!hh.test(t.data.command))return;let{cwd:r}=e;if(A(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 kh}from"shell-quote";import{z as Us}from"zod";import{existsSync as wh,mkdirSync as bh,rmSync as KT,writeFileSync as vh}from"fs";import Nn from"path";function Ls(e,t,r){let n=_s(e,t,r);bh(Nn.dirname(n),{recursive:!0}),vh(n,"")}function cr(e,t,r){return wh(_s(e,t,r))}function Sh(e,t){return Nn.join(e,".ripplo",".local","skills-loaded",t)}function _s(e,t,r){return Nn.join(Sh(e,t),r)}var Rh=Us.looseObject({command:Us.string()}),Ph="debug",xh=new Set(["tail","head","less","more","wc","sort","uniq","awk","sed","grep"]),Fs=I("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=Rh.safeParse(e.tool_input);if(!t.success)return;let r=Eh(t.data.command);if(!Ch(r))return;let{cwd:n}=e;if(!A(n)||!_(n))return;let o=Ah(r);if(o!=null)return Vs(`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(!cr(n,e.session_id,Ph))return Vs("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 Eh(e){try{return kh(e)}catch{return[]}}function Ch(e){return e.some((t,r)=>t==="ripplo"&&e[r+1]==="run")}function Th(e){return typeof e=="object"&&"op"in e&&e.op==="|"}function Ah(e){let t=e.find((r,n)=>{let o=e[n-1];return o!=null&&Th(o)&&typeof r=="string"&&xh.has(r)});return typeof t=="string"?t:null}function Vs(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}}}import Ih from"path";import{z as Ms}from"zod";var $h=new Set(["Edit","Write","NotebookEdit"]),jh=Ms.looseObject({file_path:Ms.string()}),Nh="create",Bs=I("PreToolUse",e=>{if(!$h.has(e.tool_name))return;let t=jh.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!A(r)||!_(r))return;let n=Ih.relative(r,t.data.file_path);if(!(n.startsWith("..")||n!==".ripplo"&&!n.startsWith(".ripplo/"))&&!cr(r,e.session_id,Nh))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 Oh from"path";import Hs from"picomatch";import{graphql as Dh}from"gql.tada";import{z as Ws}from"zod";var Lh=new Set(["Edit","Write","NotebookEdit"]),_h=Ws.looseObject({file_path:Ws.string()}),Uh=Dh(`
652
654
  query PreEditScopeGate($projectId: String!, $cwd: String!) {
653
655
  project(id: $projectId) {
654
656
  id
@@ -660,7 +662,7 @@ ${h("create")}`}});import{z as os}from"zod";var Qg=os.looseObject({command:os.st
660
662
  }
661
663
  }
662
664
  }
663
- `),gs=A("PreToolUse",async e=>{if(!wy.has(e.tool_name))return;let t=by.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!C(r)||!$(r))return;let n=yy.relative(r,t.data.file_path);if(!(n.startsWith("..")||n===".ripplo"||n.startsWith(".ripplo/")||!Sy(n)||await ky(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). ${Yo(["scope","create"])}`}}});function Sy(e){let{ignorePaths:t,watchPaths:r}=Ee(),n=ms([...r]),o=ms([...t]);return n(e)&&!o(e)}async function ky(e){let t;try{t=_(e)}catch{return!0}let r=await f({config:t,document:vy,variables:{cwd:t.cwd,projectId:t.projectId}}).catch(()=>null);return r==null?!0:(r.project?.devSession?.scopeItems??[]).length>0}import Ry from"fs";import Py from"path";import{z as ys}from"zod";var xy=new Set(["Edit","Write","NotebookEdit"]),Ey=ys.looseObject({file_path:ys.string()}),hs=A("PreToolUse",e=>{if(!xy.has(e.tool_name))return;let t=Ey.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!C(r))return;let n=Py.relative(r,t.data.file_path);if(!(n.startsWith("..")||n!==".ripplo"&&!n.startsWith(".ripplo/"))&&!Ry.existsSync(xe(r))&&!We(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 Cy}from"gql.tada";var Ay=Cy(`
665
+ `),qs=I("PreToolUse",async e=>{if(!Lh.has(e.tool_name))return;let t=_h.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!A(r)||!_(r))return;let n=Oh.relative(r,t.data.file_path);if(!(n.startsWith("..")||n===".ripplo"||n.startsWith(".ripplo/")||!Vh(n)||await Fh(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). ${Pi(["scope","create"])}`}}});function Vh(e){let{ignorePaths:t,watchPaths:r}=Te(),n=Hs([...r]),o=Hs([...t]);return n(e)&&!o(e)}async function Fh(e){let t;try{t=M(e)}catch{return!0}let r=await y({config:t,document:Uh,variables:{cwd:t.cwd,projectId:t.projectId}}).catch(()=>null);return r==null?!0:(r.project?.devSession?.scopeItems??[]).length>0}import Mh from"fs";import Bh from"path";import{z as zs}from"zod";var Hh=new Set(["Edit","Write","NotebookEdit"]),Wh=zs.looseObject({file_path:zs.string()}),Gs=I("PreToolUse",e=>{if(!Hh.has(e.tool_name))return;let t=Wh.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!A(r))return;let n=Bh.relative(r,t.data.file_path);if(!(n.startsWith("..")||n!==".ripplo"&&!n.startsWith(".ripplo/"))&&!Mh.existsSync(Ee(r))&&!Ge(r))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`\`ripplo watch\` is not running, so this edit to \`${n}\` won't sync to the server and dev-mode guardrails won't fire. Run \`/ripplo:start\` (or spawn \`npx ripplo watch\` directly via Bash with run_in_background), then retry. The app's dev server also needs to be running \u2014 \`npx ripplo doctor\` reports both. If watch can't start (auth, server down, intentional offline work), the user can run \`npx ripplo hooks pause\` to bypass this gate; \`npx ripplo hooks resume\` re-enables it. ${w("start")}`}}});import{graphql as qh}from"gql.tada";var zh=qh(`
664
666
  query ScopeReminder($projectId: String!, $cwd: String!) {
665
667
  project(id: $projectId) {
666
668
  id
@@ -677,9 +679,9 @@ ${h("create")}`}});import{z as os}from"zod";var Qg=os.looseObject({command:os.st
677
679
  }
678
680
  }
679
681
  }
680
- `),ws=A("UserPromptSubmit",async e=>{let{cwd:t}=e;if(!C(t)||!$(t))return;let r=Pe(t);if(qe(t,"scope-reminder")===r)return;let n;try{n=_(t)}catch{return}let o=await f({config:n,document:Ay,variables:{cwd:n.cwd,projectId:n.projectId}}).catch(()=>null);if(o==null)return;ze(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)}):
682
+ `),Ks=I("UserPromptSubmit",async e=>{let{cwd:t}=e;if(!A(t)||!_(t))return;let r=xe(t);if(Ke(t,"scope-reminder")===r)return;let n;try{n=M(t)}catch{return}let o=await y({config:n,document:zh,variables:{cwd:n.cwd,projectId:n.projectId}}).catch(()=>null);if(o==null)return;Je(t,"scope-reminder",r);let i=o.project?.devSession?.scopeItems??[];return{hookSpecificOutput:{additionalContext:i.length===0?`RIPPLO SCOPE: empty. ${w("scope")}`:`RIPPLO SCOPE (${String(i.length)}):
681
683
  ${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(`
682
- `)}`,hookEventName:"UserPromptSubmit"}}});var Iy="# 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",bs=A("SessionStart",e=>{if(C(e.cwd))return{hookSpecificOutput:{additionalContext:Iy,hookEventName:"SessionStart"}}});import{execFileSync as Ty}from"child_process";import $y from"path";import vs from"process";import{graphql as jy}from"gql.tada";import{z as nr}from"zod";var Ny=jy(`
684
+ `)}`,hookEventName:"UserPromptSubmit"}}});var Gh="# 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",Js=I("SessionStart",e=>{if(A(e.cwd))return{hookSpecificOutput:{additionalContext:Gh,hookEventName:"SessionStart"}}});import{execFileSync as Kh}from"child_process";import Jh from"path";import Ys from"process";import{graphql as Yh}from"gql.tada";import{z as ur}from"zod";var Xh=Yh(`
683
685
  query ScopeEnforce($projectId: String!, $cwd: String!) {
684
686
  project(id: $projectId) {
685
687
  id
@@ -698,14 +700,14 @@ ${i.map(a=>{let l=a.workflow;return l==null?` [intent] (${a.id}) ${a.label??""}
698
700
  }
699
701
  }
700
702
  }
701
- `),ks=A("Stop",async e=>{let{cwd:t}=e;if(!C(t)||!$(t))return;let r=Pe(t),n=qe(t,"stop-enforce")===r;if(n&&!e.stop_hook_active)return;let o=Oy(t),i=await Dy(t,o);if(ze(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:
703
+ `),Qs=I("Stop",async e=>{let{cwd:t}=e;if(!A(t)||!_(t))return;let r=xe(t),n=Ke(t,"stop-enforce")===r;if(n&&!e.stop_hook_active)return;let o=Qh(t),i=await Zh(t,o);if(Je(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:
702
704
  ${i.join(`
703
705
 
704
706
  `)}`}:{decision:"block",reason:i.join(`
705
707
 
706
- `)}});function Oy(e){return er(e,".ripplo/tests").filter(t=>t.endsWith(".ts")).map(t=>$y.basename(t,".ts")).filter(t=>t!=="index")}async function Dy(e,t){let r=await P(e);if(!r.ok)return[`--- Compilation failed ---
708
+ `)}});function Qh(e){return ar(e,".ripplo/tests").filter(t=>t.endsWith(".ts")).map(t=>Jh.basename(t,".ts")).filter(t=>t!=="index")}async function Zh(e,t){let r=await P(e);if(!r.ok)return[`--- Compilation failed ---
707
709
  ${r.error}
708
- ${h("create")}`];await ce({cwd:e,result:r.result}),Me({cwd:e});let n=await _y(e),o=Uy(r,t),i=Vy(r),s=Ly(e,r),l=t.length>0||n.hasRunnable?Fy(e):null;return[o,i,s,l,n.error].filter(c=>c!=null)}function Ly(e,t){let{ignorePaths:r}=Ee(),n=Qo({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(`
710
+ ${w("create")}`];await le({cwd:e,result:r.result}),qe({cwd:e});let n=await tw(e),o=rw(r,t),i=nw(r),s=ew(e,r),l=t.length>0||n.hasRunnable?ow(e):null;return[o,i,s,l,n.error].filter(c=>c!=null)}function ew(e,t){let{ignorePaths:r}=Te(),n=Ei({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(`
709
711
  `);s.push(`Unacknowledged interactions (add to a test's .coverage(...)):
710
712
  ${a}`)}if(i.length>0){let a=i.map(l=>` ${l.id}`).join(`
711
713
  `);s.push(`Stale .coverage(...) claims (id no longer exists in source):
@@ -713,23 +715,23 @@ ${a}`)}return`--- Exhaustiveness ---
713
715
  ${s.join(`
714
716
 
715
717
  `)}
716
- ${h("create")}`}async function _y(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 ---
718
+ ${w("create")}`}async function tw(e){let t;try{t=M(e)}catch{return{error:null,hasRunnable:!1}}let n=(await y({config:t,document:Xh,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 ---
717
719
  ${o.join(`
718
720
  `)}
719
- ${h("create")}`,hasRunnable:i}}function Uy(e,t){let{diagnostics:r}=Fe(e.result),n=new Set(e.builder.getUnimplemented().tests),o=t.filter(a=>n.has(a));if(r.length===0&&o.length===0)return null;let i=r.map(a=>{let l=a.step==null?"":` at "${a.step}"`;return` [${a.rule}]${l} ${a.test}: ${a.message}`}),s=o.map(a=>` [not-implemented] ${a} is still marked .notImplemented()`);return`--- Ripplo Lint ---
721
+ ${w("create")}`,hasRunnable:i}}function rw(e,t){let{diagnostics:r}=He(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 ---
720
722
  ${[...i,...s].join(`
721
723
  `)}
722
- ${h("create")}`}function Vy(e){let{tests:t}=e.builder.getUnimplemented();return t.length===0?null:`--- Unimplemented stubs ---
724
+ ${w("create")}`}function nw(e){let{tests:t}=e.builder.getUnimplemented();return t.length===0?null:`--- Unimplemented stubs ---
723
725
  ${t.join(", ")}
724
726
  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.
725
- ${h("create")}`}function Fy(e){let t=My(["run"],e);if(t.code===0)return null;let r=t.output.split(`
727
+ ${w("create")}`}function ow(e){let t=sw(["run"],e);if(t.code===0)return null;let r=t.output.split(`
726
728
  `).filter(n=>/FAILED/.test(n)).join(`
727
729
  `);return r.length===0?null:`--- Ripplo Run Failures (scope) ---
728
730
  ${r}
729
- Artifacts: .ripplo/debug/<runId>/. ${h("debug")}`}var Hy=nr.object({status:nr.number().nullish(),stderr:nr.unknown().optional(),stdout:nr.unknown().optional()});function Ss(e){return e instanceof Buffer?e.toString("utf8"):typeof e=="string"?e:""}function My(e,t){let r=vs.argv[1];if(r==null)return{code:1,output:""};try{return{code:0,output:Ty(vs.execPath,[r,...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}}catch(n){let o=Hy.safeParse(n);if(!o.success)return{code:1,output:""};let i=`${Ss(o.data.stdout)}${Ss(o.data.stderr)}`;return{code:o.data.status??1,output:i}}}import{z as Rs}from"zod";var By=Rs.looseObject({skill:Rs.string()}),Ps=A("PostToolUse",e=>{if(e.tool_name!=="Skill")return;let t=By.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)&&ss(e.cwd,e.session_id,n)});Zy();vn(process.cwd());var xs={"coverage-nudge":Ji,"exit-plan-gate":Xi,"plan-reminder":Qi,"post-edit-flag-stubs":ts,"post-edit-lint":ns,"pre-bash-hooks-pause-gate":is,"pre-bash-run-gate":ds,"pre-edit-ripplo-skill-gate":ps,"pre-edit-scope-gate":gs,"pre-edit-watch-gate":hs,"scope-reminder":ws,"session-preamble":bs,"stop-enforce":ks,"track-skill-load":Ps};async function zy(){await Wy(qy(process.argv)).scriptName("ripplo").version("0.4.20").command("watch","Watch for run requests and execute locally",()=>{},()=>Fi()).command("auth <subcommand>","Manage authentication",Qy).command("projects <subcommand>","Inspect Ripplo projects",Xy).command("hooks <subcommand>","Pause or resume Ripplo hooks",Yy).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=>$i({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=>Li({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=>Oi({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=>Ri({id:e.id,runs:e.runs})).command("sync","Push the compiled .ripplo/ resources to the server (no run)",()=>{},()=>_i()).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=>Xo({check:e.check})).command("cover","Audit all coverage statements",()=>{},()=>ri()).command("doctor","Check project health",()=>{},()=>yi()).command("status","Report unimplemented tests and preconditions",e=>e.option("format",{choices:["json","summary"],default:"json",describe:"Output format"}),e=>zi({format:e.format})).command("scope <subcommand>","Manage testing scope",Jy).command("hook <name>","Internal: run a Claude Code plugin hook",e=>e.positional("name",{choices:Object.keys(xs),demandOption:!0,type:"string"}),e=>Gy(e.name)).strict().help().parse()}async function Gy(e){let t=xs[e];t==null&&(process.stderr.write(`Unknown hook: ${e}
730
- `),process.exit(1));let r=await Ky(),n=r.trim()===""?{}:JSON.parse(r),o=await t.run(n);o!=null&&process.stdout.write(JSON.stringify(o))}function Ky(){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)})}zy().catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
731
- `),process.exit(1)});function Jy(e){return e.command("status","Print the current scope",t=>t.option("format",{choices:["json","text"],default:"text",describe:"Output format"}),t=>Mi({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=>Bi({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=>Wi({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=>qi({ids:t.ids})).demandCommand(1)}function Yy(e){return e.command("pause","Disable all Ripplo pre-edit gates and stop enforcement until resumed",()=>{},()=>Pi()).command("resume","Re-enable Ripplo hooks paused via `ripplo hooks pause`",()=>{},()=>xi()).demandCommand(1)}function Xy(e){return e.command("list","List projects you have access to (JSON)",()=>{},()=>Di()).demandCommand(1)}function Qy(e){return e.command("login","Authenticate via device flow",()=>{},()=>bo()).command("status","Show authentication status",()=>{},()=>vo()).command("logout","Remove the saved token",()=>{},()=>{So()}).demandCommand(1)}function Zy(){let e=process.cwd(),t=ir(e);t!=null&&t!==e&&(process.chdir(t),process.stderr.write(`ripplo: resolved .ripplo/ at ${t}
732
- `))}export{zy as main};
731
+ Artifacts: .ripplo/debug/<runId>/. ${w("debug")}`}var iw=ur.object({status:ur.number().nullish(),stderr:ur.unknown().optional(),stdout:ur.unknown().optional()});function Xs(e){return e instanceof Buffer?e.toString("utf8"):typeof e=="string"?e:""}function sw(e,t){let r=Ys.argv[1];if(r==null)return{code:1,output:""};try{return{code:0,output:Kh(Ys.execPath,[r,...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}}catch(n){let o=iw.safeParse(n);if(!o.success)return{code:1,output:""};let i=`${Xs(o.data.stdout)}${Xs(o.data.stderr)}`;return{code:o.data.status??1,output:i}}}import{z as Zs}from"zod";var aw=Zs.looseObject({skill:Zs.string()}),ea=I("PostToolUse",e=>{if(e.tool_name!=="Skill")return;let t=aw.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&&A(e.cwd)&&Ls(e.cwd,e.session_id,n)});hw();Fo(process.cwd());$r();var ta={"coverage-nudge":xs,"exit-plan-gate":Cs,"plan-reminder":Ts,"post-edit-flag-stubs":$s,"post-edit-lint":Ns,"pre-bash-hooks-pause-gate":Ds,"pre-bash-run-gate":Fs,"pre-edit-ripplo-skill-gate":Bs,"pre-edit-scope-gate":qs,"pre-edit-watch-gate":Gs,"scope-reminder":Ks,"session-preamble":Js,"stop-enforce":Qs,"track-skill-load":ea};async function uw(){await lw(cw(process.argv)).scriptName("ripplo").version("0.5.1").command("watch","Watch for run requests and execute locally",()=>{},()=>ys()).command("auth <subcommand>","Manage authentication",yw).command("projects <subcommand>","Inspect Ripplo projects",gw).command("hooks <subcommand>","Pause or resume Ripplo hooks",fw).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=>is({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=>us({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=>ls({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=>Xi({id:e.id,runs:e.runs})).command("sync","Push the compiled .ripplo/ resources to the server (no run)",()=>{},()=>ds()).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=>xi({check:e.check})).command("cover","Audit all coverage statements",()=>{},()=>Ii()).command("doctor","Check project health",()=>{},()=>Wi()).command("status","Report unimplemented tests and preconditions",e=>e.option("format",{choices:["json","summary"],default:"json",describe:"Output format"}),e=>ks({format:e.format})).command("scope <subcommand>","Manage testing scope",mw).command("hook <name>","Internal: run a Claude Code plugin hook",e=>e.positional("name",{choices:Object.keys(ta),demandOption:!0,type:"string"}),e=>dw(e.name)).strict().help().parse()}async function dw(e){let t=ta[e];t==null&&(process.stderr.write(`Unknown hook: ${e}
732
+ `),process.exit(1));let r=await pw(),n=r.trim()===""?{}:JSON.parse(r),o=await t.run(n);o!=null&&process.stdout.write(JSON.stringify(o))}function pw(){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)})}uw().catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
733
+ `),process.exit(1)});function mw(e){return e.command("status","Print the current scope",t=>t.option("format",{choices:["json","text"],default:"text",describe:"Output format"}),t=>ws({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=>bs({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=>vs({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=>Ss({ids:t.ids})).demandCommand(1)}function fw(e){return e.command("pause","Disable all Ripplo pre-edit gates and stop enforcement until resumed",()=>{},()=>Qi()).command("resume","Re-enable Ripplo hooks paused via `ripplo hooks pause`",()=>{},()=>Zi()).demandCommand(1)}function gw(e){return e.command("list","List projects you have access to (JSON)",()=>{},()=>cs()).demandCommand(1)}function yw(e){return e.command("login","Authenticate via device flow",()=>{},()=>zo()).command("status","Show authentication status",()=>{},()=>Go()).command("logout","Remove the saved token",()=>{},()=>{Ko()}).demandCommand(1)}function hw(){let e=process.cwd(),t=yr(e);t!=null&&t!==e&&(process.chdir(t),process.stderr.write(`ripplo: resolved .ripplo/ at ${t}
734
+ `))}export{uw as main};
733
735
  /*! Bundled license information:
734
736
 
735
737
  mustache/mustache.mjs: