ripplo 0.5.9 → 0.5.10

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 +164 -161
  2. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -1,26 +1,26 @@
1
1
  #!/usr/bin/env node
2
- var ka=Object.create;var wr=Object.defineProperty;var Pa=Object.getOwnPropertyDescriptor;var Ra=Object.getOwnPropertyNames;var xa=Object.getPrototypeOf,Ea=Object.prototype.hasOwnProperty;var Ca=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ta=(e,t)=>{for(var r in t)wr(e,r,{get:t[r],enumerable:!0})},hr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ra(t))!Ea.call(e,o)&&o!==r&&wr(e,o,{get:()=>t[o],enumerable:!(n=Pa(t,o))||n.enumerable});return e},br=(e,t,r)=>(hr(e,t,"default"),r&&hr(r,t,"default")),vr=(e,t,r)=>(r=e!=null?ka(xa(e)):{},hr(t||!e||!e.__esModule?wr(r,"default",{value:e,enumerable:!0}):r,e));var At=Ca((gv,vo)=>{"use strict";var Hl=(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=zl(n),this._batchScheduleFn=Gl(n),this._cacheKeyFn=Kl(n),this._cacheMap=Jl(n),this._batch=null,this.name=Xl(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=Wl(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(u){l.push(function(){u(a)})})}}o.keys.push(n);var c=new Promise(function(u,m){o.callbacks.push({resolve:u,reject:m})});return i&&i.set(s,c),c},t.loadMany=function(n){if(!bo(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})(),Bl=typeof process=="object"&&typeof process.nextTick=="function"?function(e){_r||(_r=Promise.resolve()),_r.then(function(){process.nextTick(e)})}:typeof setImmediate=="function"?function(e){setImmediate(e)}:function(e){setTimeout(e)},_r;function Wl(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(){ql(e,r)}),r}function ql(e,t){if(t.hasDispatched=!0,t.keys.length===0){Vr(t);return}var r;try{r=e._batchLoadFn(t.keys)}catch(n){return Ur(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 Ur(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(!bo(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."+(`
2
+ var Ta=Object.create;var vr=Object.defineProperty;var Aa=Object.getOwnPropertyDescriptor;var Ia=Object.getOwnPropertyNames;var $a=Object.getPrototypeOf,ja=Object.prototype.hasOwnProperty;var Na=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Da=(e,t)=>{for(var r in t)vr(e,r,{get:t[r],enumerable:!0})},br=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ia(t))!ja.call(e,o)&&o!==r&&vr(e,o,{get:()=>t[o],enumerable:!(n=Aa(t,o))||n.enumerable});return e},Sr=(e,t,r)=>(br(e,t,"default"),r&&br(r,t,"default")),kr=(e,t,r)=>(r=e!=null?Ta($a(e)):{},br(t||!e||!e.__esModule?vr(r,"default",{value:e,enumerable:!0}):r,e));var $t=Na((xv,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=Ql(n),this._batchScheduleFn=Zl(n),this._cacheKeyFn=ec(n),this._cacheMap=tc(n),this._batch=null,this.name=rc(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=Xl(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(u){l.push(function(){u(a)})})}}o.keys.push(n);var c=new Promise(function(u,m){o.callbacks.push({resolve:u,reject:m})});return i&&i.set(s,c),c},t.loadMany=function(n){if(!ko(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})(),Jl=typeof process=="object"&&typeof process.nextTick=="function"?function(e){Vr||(Vr=Promise.resolve()),Vr.then(function(){process.nextTick(e)})}:typeof setImmediate=="function"?function(e){setImmediate(e)}:function(e){setTimeout(e)},Vr;function Xl(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(){Yl(e,r)}),r}function Yl(e,t){if(t.hasDispatched=!0,t.keys.length===0){Mr(t);return}var r;try{r=e._batchLoadFn(t.keys)}catch(n){return Fr(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 Fr(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(!ko(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."+(`
3
3
 
4
4
  Keys:
5
5
  `+String(t.keys))+(`
6
6
 
7
7
  Values:
8
- `+String(n)));Vr(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){Ur(e,t,n)})}function Ur(e,t,r){Vr(t);for(var n=0;n<t.keys.length;n++)e.clear(t.keys[n]),t.callbacks[n].reject(r)}function Vr(e){if(e.cacheHits)for(var t=0;t<e.cacheHits.length;t++)e.cacheHits[t]()}function zl(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 Gl(e){var t=e&&e.batchScheduleFn;if(t===void 0)return Bl;if(typeof t!="function")throw new TypeError("batchScheduleFn must be a function: "+t);return t}function Kl(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 Jl(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 Xl(e){return e&&e.name?e.name:null}function bo(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))}vo.exports=Hl});import{execFileSync as Aa}from"child_process";import Ia from"fs";import Rt from"path";function Sr(e){let t=ja(e);return t??Mn(e)}function Mn(e){let t=Rt.dirname(e);return $a(Rt.join(e,".ripplo"))?e:t===e?null:Mn(t)}function $a(e){try{return Ia.statSync(e).isDirectory()}catch{return!1}}function ja(e){let t=Na(["rev-parse","--show-toplevel"],e);if(t==null)return null;let r=t.trim();return r.length===0?null:Rt.isAbsolute(r)?r:Rt.resolve(e,r)}function Na(e,t){try{return Aa("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return null}}import rl from"path";import{AsyncLocalStorage as Da}from"async_hooks";import Oa from"path";var La=new Da;function Hn(){let e=La.getStore();return e!=null?e.fixturesDir:Oa.join(process.cwd(),".ripplo","fixtures")}async function me(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 Bn=5e3;async function se({awaitPromise:e,expression:t,label:r,session:n,timeoutMs:o}){let i=await me(n.send("Runtime.evaluate",{awaitPromise:e,expression:t,returnByValue:!0}),o??Bn,r??"evaluateOnSession");if(i.exceptionDetails==null)return i.result.value}async function _a({fn:e,label:t,page:r,timeoutMs:n}){let o=n??Bn,i=await me(r.context().newCDPSession(r),o,`${t} (newCDPSession)`);try{return await me(e(i),o,t)}finally{await i.detach().catch(()=>{})}}async function it({awaitPromise:e,expression:t,label:r,page:n,timeoutMs:o}){return _a({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 Ua=Object.prototype.toString,Le=Array.isArray||function(t){return Ua.call(t)==="[object Array]"};function Pr(e){return typeof e=="function"}function Va(e){return Le(e)?"array":typeof e}function kr(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Wn(e,t){return e!=null&&typeof e=="object"&&t in e}function Fa(e,t){return e!=null&&typeof e!="object"&&e.hasOwnProperty&&e.hasOwnProperty(t)}var Ma=RegExp.prototype.test;function Ha(e,t){return Ma.call(e,t)}var Ba=/\S/;function Wa(e){return!Ha(Ba,e)}var qa={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function za(e){return String(e).replace(/[&<>"'`=\/]/g,function(r){return qa[r]})}var Ga=/\s*/,Ka=/\s+/,qn=/\s*=/,Ja=/\s*\}/,Xa=/#|\^|\/|>|\{|&|=|!/;function Ya(e,t){if(!e)return[];var r=!1,n=[],o=[],i=[],s=!1,a=!1,l="",c=0;function u(){if(s&&!a)for(;i.length;)delete o[i.pop()];else i=[];s=!1,a=!1}var m,g,R;function $(z){if(typeof z=="string"&&(z=z.split(Ka,2)),!Le(z)||z.length!==2)throw new Error("Invalid tags: "+z);m=new RegExp(kr(z[0])+"\\s*"),g=new RegExp("\\s*"+kr(z[1])),R=new RegExp("\\s*"+kr("}"+z[1]))}$(t||re.tags);for(var y=new at(e),H,E,B,Ie,De,pe;!y.eos();){if(H=y.pos,B=y.scanUntil(m),B)for(var O=0,J=B.length;O<J;++O)Ie=B.charAt(O),Wa(Ie)?(i.push(o.length),l+=Ie):(a=!0,r=!0,l+=" "),o.push(["text",Ie,H,H+1]),H+=1,Ie===`
9
- `&&(u(),l="",c=0,r=!1);if(!y.scan(m))break;if(s=!0,E=y.scan(Xa)||"name",y.scan(Ga),E==="="?(B=y.scanUntil(qn),y.scan(qn),y.scanUntil(g)):E==="{"?(B=y.scanUntil(R),y.scan(Ja),y.scanUntil(g),E="&"):B=y.scanUntil(g),!y.scan(g))throw new Error("Unclosed tag at "+y.pos);if(E==">"?De=[E,B,H,y.pos,l,c,r]:De=[E,B,H,y.pos],c++,o.push(De),E==="#"||E==="^")n.push(De);else if(E==="/"){if(pe=n.pop(),!pe)throw new Error('Unopened section "'+B+'" at '+H);if(pe[1]!==B)throw new Error('Unclosed section "'+pe[1]+'" at '+H)}else E==="name"||E==="{"||E==="&"?a=!0:E==="="&&$(B)}if(u(),pe=n.pop(),pe)throw new Error('Unclosed section "'+pe[1]+'" at '+y.pos);return Za(Qa(o))}function Qa(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 Za(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 at(e){this.string=e,this.tail=e,this.pos=0}at.prototype.eos=function(){return this.tail===""};at.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};at.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 Oe(e,t){this.view=e,this.cache={".":this.view},this.parent=t}Oe.prototype.push=function(t){return new Oe(t,this)};Oe.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=Wn(i,s[a])||Fa(i,s[a])),i=i[s[a++]];else i=o.view[t],l=Wn(o.view,t);if(l){n=i;break}o=o.parent}r[t]=n}return Pr(n)&&(n=n.call(this.view)),n};function X(){this.templateCache={_cache:{},set:function(t,r){this._cache[t]=r},get:function(t){return this._cache[t]},clear:function(){this._cache={}}}}X.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};X.prototype.parse=function(t,r){var n=this.templateCache,o=t+":"+(r||re.tags).join(":"),i=typeof n<"u",s=i?n.get(o):void 0;return s==null&&(s=Ya(t,r),i&&n.set(o,s)),s};X.prototype.render=function(t,r,n,o){var i=this.getConfigTags(o),s=this.parse(t,i),a=r instanceof Oe?r:new Oe(r,void 0);return this.renderTokens(s,a,n,t,o)};X.prototype.renderTokens=function(t,r,n,o,i){for(var s="",a,l,c,u=0,m=t.length;u<m;++u)c=void 0,a=t[u],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};X.prototype.renderSection=function(t,r,n,o,i){var s=this,a="",l=r.lookup(t[1]);function c(g){return s.render(g,r,n,i)}if(l){if(Le(l))for(var u=0,m=l.length;u<m;++u)a+=this.renderTokens(t[4],r.push(l[u]),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(Pr(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}};X.prototype.renderInverted=function(t,r,n,o,i){var s=r.lookup(t[1]);if(!s||Le(s)&&s.length===0)return this.renderTokens(t[4],r,n,o,i)};X.prototype.indentPartial=function(t,r,n){for(var o=r.replace(/[^ \t]/g,""),i=t.split(`
8
+ `+String(n)));Mr(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){Fr(e,t,n)})}function Fr(e,t,r){Mr(t);for(var n=0;n<t.keys.length;n++)e.clear(t.keys[n]),t.callbacks[n].reject(r)}function Mr(e){if(e.cacheHits)for(var t=0;t<e.cacheHits.length;t++)e.cacheHits[t]()}function Ql(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 Zl(e){var t=e&&e.batchScheduleFn;if(t===void 0)return Jl;if(typeof t!="function")throw new TypeError("batchScheduleFn must be a function: "+t);return t}function ec(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 tc(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 rc(e){return e&&e.name?e.name:null}function ko(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 Oa}from"child_process";import La from"fs";import Et from"path";function Pr(e){let t=Ua(e);return t??Wn(e)}function Wn(e){let t=Et.dirname(e);return _a(Et.join(e,".ripplo"))?e:t===e?null:Wn(t)}function _a(e){try{return La.statSync(e).isDirectory()}catch{return!1}}function Ua(e){let t=Va(["rev-parse","--show-toplevel"],e);if(t==null)return null;let r=t.trim();return r.length===0?null:Et.isAbsolute(r)?r:Et.resolve(e,r)}function Va(e,t){try{return Oa("git",e,{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return null}}import ll from"path";import{AsyncLocalStorage as Fa}from"async_hooks";import Ma from"path";var Ha=new Fa;function qn(){let e=Ha.getStore();return e!=null?e.fixturesDir:Ma.join(process.cwd(),".ripplo","fixtures")}async function me(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 zn=5e3;async function se({awaitPromise:e,expression:t,label:r,session:n,timeoutMs:o}){let i=await me(n.send("Runtime.evaluate",{awaitPromise:e,expression:t,returnByValue:!0}),o??zn,r??"evaluateOnSession");if(i.exceptionDetails==null)return i.result.value}async function Ba({fn:e,label:t,page:r,timeoutMs:n}){let o=n??zn,i=await me(r.context().newCDPSession(r),o,`${t} (newCDPSession)`);try{return await me(e(i),o,t)}finally{await i.detach().catch(()=>{})}}async function st({awaitPromise:e,expression:t,label:r,page:n,timeoutMs:o}){return Ba({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,Le=Array.isArray||function(t){return Wa.call(t)==="[object Array]"};function xr(e){return typeof e=="function"}function qa(e){return Le(e)?"array":typeof e}function Rr(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Gn(e,t){return e!=null&&typeof e=="object"&&t in e}function za(e,t){return e!=null&&typeof e!="object"&&e.hasOwnProperty&&e.hasOwnProperty(t)}var Ga=RegExp.prototype.test;function Ka(e,t){return Ga.call(e,t)}var Ja=/\S/;function Xa(e){return!Ka(Ja,e)}var Ya={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function Qa(e){return String(e).replace(/[&<>"'`=\/]/g,function(r){return Ya[r]})}var Za=/\s*/,el=/\s+/,Kn=/\s*=/,tl=/\s*\}/,rl=/#|\^|\/|>|\{|&|=|!/;function nl(e,t){if(!e)return[];var r=!1,n=[],o=[],i=[],s=!1,a=!1,l="",c=0;function u(){if(s&&!a)for(;i.length;)delete o[i.pop()];else i=[];s=!1,a=!1}var m,g,R;function $(z){if(typeof z=="string"&&(z=z.split(el,2)),!Le(z)||z.length!==2)throw new Error("Invalid tags: "+z);m=new RegExp(Rr(z[0])+"\\s*"),g=new RegExp("\\s*"+Rr(z[1])),R=new RegExp("\\s*"+Rr("}"+z[1]))}$(t||re.tags);for(var y=new lt(e),H,E,B,Ie,De,pe;!y.eos();){if(H=y.pos,B=y.scanUntil(m),B)for(var O=0,J=B.length;O<J;++O)Ie=B.charAt(O),Xa(Ie)?(i.push(o.length),l+=Ie):(a=!0,r=!0,l+=" "),o.push(["text",Ie,H,H+1]),H+=1,Ie===`
9
+ `&&(u(),l="",c=0,r=!1);if(!y.scan(m))break;if(s=!0,E=y.scan(rl)||"name",y.scan(Za),E==="="?(B=y.scanUntil(Kn),y.scan(Kn),y.scanUntil(g)):E==="{"?(B=y.scanUntil(R),y.scan(tl),y.scanUntil(g),E="&"):B=y.scanUntil(g),!y.scan(g))throw new Error("Unclosed tag at "+y.pos);if(E==">"?De=[E,B,H,y.pos,l,c,r]:De=[E,B,H,y.pos],c++,o.push(De),E==="#"||E==="^")n.push(De);else if(E==="/"){if(pe=n.pop(),!pe)throw new Error('Unopened section "'+B+'" at '+H);if(pe[1]!==B)throw new Error('Unclosed section "'+pe[1]+'" at '+H)}else E==="name"||E==="{"||E==="&"?a=!0:E==="="&&$(B)}if(u(),pe=n.pop(),pe)throw new Error('Unclosed section "'+pe[1]+'" at '+y.pos);return il(ol(o))}function ol(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 il(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 lt(e){this.string=e,this.tail=e,this.pos=0}lt.prototype.eos=function(){return this.tail===""};lt.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};lt.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 Oe(e,t){this.view=e,this.cache={".":this.view},this.parent=t}Oe.prototype.push=function(t){return new Oe(t,this)};Oe.prototype.lookup=function(t){var r=this.cache,n;if(r.hasOwnProperty(t))n=r[t];else{for(var o=this,i,s,a,l=!1;o;){if(t.indexOf(".")>0)for(i=o.view,s=t.split("."),a=0;i!=null&&a<s.length;)a===s.length-1&&(l=Gn(i,s[a])||za(i,s[a])),i=i[s[a++]];else i=o.view[t],l=Gn(o.view,t);if(l){n=i;break}o=o.parent}r[t]=n}return xr(n)&&(n=n.call(this.view)),n};function X(){this.templateCache={_cache:{},set:function(t,r){this._cache[t]=r},get:function(t){return this._cache[t]},clear:function(){this._cache={}}}}X.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};X.prototype.parse=function(t,r){var n=this.templateCache,o=t+":"+(r||re.tags).join(":"),i=typeof n<"u",s=i?n.get(o):void 0;return s==null&&(s=nl(t,r),i&&n.set(o,s)),s};X.prototype.render=function(t,r,n,o){var i=this.getConfigTags(o),s=this.parse(t,i),a=r instanceof Oe?r:new Oe(r,void 0);return this.renderTokens(s,a,n,t,o)};X.prototype.renderTokens=function(t,r,n,o,i){for(var s="",a,l,c,u=0,m=t.length;u<m;++u)c=void 0,a=t[u],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};X.prototype.renderSection=function(t,r,n,o,i){var s=this,a="",l=r.lookup(t[1]);function c(g){return s.render(g,r,n,i)}if(l){if(Le(l))for(var u=0,m=l.length;u<m;++u)a+=this.renderTokens(t[4],r.push(l[u]),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(xr(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}};X.prototype.renderInverted=function(t,r,n,o,i){var s=r.lookup(t[1]);if(!s||Le(s)&&s.length===0)return this.renderTokens(t[4],r,n,o,i)};X.prototype.indentPartial=function(t,r,n){for(var o=r.replace(/[^ \t]/g,""),i=t.split(`
10
10
  `),s=0;s<i.length;s++)i[s].length&&(s>0||!n)&&(i[s]=o+i[s]);return i.join(`
11
- `)};X.prototype.renderPartial=function(t,r,n,o){if(n){var i=this.getConfigTags(o),s=Pr(n)?n(t[1]):n[t[1]];if(s!=null){var a=t[6],l=t[5],c=t[4],u=s;l==0&&c&&(u=this.indentPartial(s,c,a));var m=this.parse(u,i);return this.renderTokens(m,r,n,u,o)}}};X.prototype.unescapedValue=function(t,r){var n=r.lookup(t[1]);if(n!=null)return n};X.prototype.escapedValue=function(t,r,n){var o=this.getConfigEscape(n)||re.escape,i=r.lookup(t[1]);if(i!=null)return typeof i=="number"&&o===re.escape?String(i):o(i)};X.prototype.rawValue=function(t){return t[1]};X.prototype.getConfigTags=function(t){return Le(t)?t:t&&typeof t=="object"?t.tags:void 0};X.prototype.getConfigEscape=function(t){if(t&&typeof t=="object"&&!Le(t))return t.escape};var re={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(e){st.templateCache=e},get templateCache(){return st.templateCache}},st=new X;re.clearCache=function(){return st.clearCache()};re.parse=function(t,r){return st.parse(t,r)};re.render=function(t,r,n,o){if(typeof t!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+Va(t)+'" was given as the first argument for mustache#render(template, view, partials)');return st.render(t,r,n,o)};re.escape=za;re.Scanner=at;re.Context=Oe;re.Writer=X;var zn=re;function Rr({defs:e}){return e==null?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,tl({def:r,name:t})]))}var el={boolean:!1,number:0,string:""};function tl({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??el[e.type]??""}function xt({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(xt({ref:e,variables:t}));return Ct({raw:r,variables:t})}function Et({ref:e,variables:t}){let r=xt({ref:e,variables:t});return typeof r=="string"?Ct({raw:r,variables:t}):r}function Ct({raw:e,variables:t}){return zn.render(e,t,{},{escape:r=>r})}function xr({ref:e,variables:t}){let r=xt({ref:e,variables:t});if(typeof r=="number")return r;let n=Number(r);if(Number.isNaN(n))throw new TypeError(`Cannot convert "${String(r)}" to number`);return n}function _e({name:e,store:t,value:r}){return{...t,[e]:r}}function F({locator:e,page:t,variables:r}){switch(e.by){case"testId":return t.getByTestId(Gn(e.value,r));case"role":return t.getByRole(e.role,{exact:!0,name:e.name==null?void 0:Gn(e.name,r)})}}function Gn(e,t){return t==null?e:Ct({raw:e,variables:t})}async function Kn({node:e,page:t,timeout:r}){await F({locator:e.source,page:t,variables:void 0}).dragTo(F({locator:e.target,page:t,variables:void 0}),{timeout:r})}async function Jn({node:e,page:t,timeout:r}){await F({locator:e.locator,page:t,variables:void 0}).click({button:"right",timeout:r})}function Xn({node:e,page:t,variables:r}){return t.once("dialog",async n=>{e.action==="accept"?await n.accept(e.promptText??void 0):await n.dismiss()}),{variables:r}}async function Yn({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 it({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 it({awaitPromise:!0,expression:"navigator.clipboard.readText()",label:"clipboard.readText",page:t,timeoutMs:void 0})??"";return{variables:_e({name:e.variable,store:r,value:n})}}async function Qn({node:e,page:t}){let r=t.context();e.state==="granted"?await r.grantPermissions([e.permission]):await r.clearPermissions()}async function Er({node:e,page:t,timeout:r,variables:n}){switch(e.type){case"click":return await F({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 ol({node:e,page:t,timeout:r,variables:n});case"rightClick":return await Jn({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 it({awaitPromise:!0,expression:"new Promise((resolve) => { requestAnimationFrame(() => requestAnimationFrame(() => resolve(undefined))); })",label:"goto raf-settle",page:t,timeoutMs:void 0}),{variables:n}}case"fill":return sl({node:e,page:t,timeout:r,variables:n});case"select":return al({node:e,page:t,timeout:r,variables:n});case"type":return ll({node:e,page:t,timeout:r,variables:n});case"press":return await il({node:e,page:t,timeout:r}),{variables:n};case"drag":return await Kn({node:e,page:t,timeout:r}),{variables:n};case"upload":return cl({node:e,page:t,timeout:r,variables:n});case"extractText":return dl({node:e,page:t,timeout:r,variables:n});case"setVariable":{let o=Et({ref:e.value,variables:n});return{variables:_e({name:e.variable,store:n,value:o})}}case"fail":throw new Error(e.message);case"setViewport":return await t.setViewportSize({height:e.height,width:e.width}),{variables:n};case"handleDialog":return Xn({node:e,page:t,variables:n});case"clipboard":return Yn({node:e,page:t,variables:n});case"setPermission":return await Qn({node:e,page:t}),{variables:n}}}var nl={check:"check",clear:"clear",click:"click",dblclick:"dblclick",focus:"focus",hover:"hover",scrollIntoView:"scrollIntoViewIfNeeded",uncheck:"uncheck"};async function ol({node:e,page:t,timeout:r,variables:n}){return await F({locator:e.locator,page:t,variables:n})[nl[e.type]]({timeout:r}),{variables:n}}async function il({node:e,page:t,timeout:r}){e.locator==null?await t.keyboard.press(e.key):await F({locator:e.locator,page:t,variables:void 0}).press(e.key,{timeout:r})}async function sl({node:e,page:t,timeout:r,variables:n}){let o=Y({ref:e.value,variables:n});return await F({locator:e.locator,page:t,variables:n}).fill(o,{timeout:r}),{variables:n}}async function al({node:e,page:t,timeout:r,variables:n}){let o=Y({ref:e.value,variables:n});return await F({locator:e.locator,page:t,variables:n}).selectOption(o,{timeout:r}),{variables:n}}async function ll({node:e,page:t,timeout:r,variables:n}){let o=Y({ref:e.value,variables:n});return await F({locator:e.locator,page:t,variables:n}).pressSequentially(o,{timeout:r}),{variables:n}}async function cl({node:e,page:t,timeout:r,variables:n}){let o=e.files.map(i=>ul(i));return await F({locator:e.locator,page:t,variables:n}).setInputFiles(o,{timeout:r}),{variables:n}}function ul(e){return rl.join(Hn(),e)}async function dl({node:e,page:t,timeout:r,variables:n}){let o=await F({locator:e.locator,page:t,variables:n}).textContent({timeout:r});if(o==null)throw new Error("extractText: element had no text content");return{variables:_e({name:e.variable,store:n,value:o})}}var G={};Ta(G,{default:()=>pl});br(G,_b);import*as _b from"playwright/test";import{default as pl}from"playwright/test";async function Cr({expected:e,locator:t,operator:r,timeout:n}){return await lt({expected:e,operator:r,timeout:n,read:async()=>await t.textContent()??""}),ct({expected:e,label:"Text",operator:r,read:async()=>await t.textContent()??""})}async function Tr({expected:e,operator:t,page:r,timeout:n}){return await lt({expected:e,operator:t,timeout:n,read:()=>Promise.resolve(r.url())}),ct({expected:e,label:"URL",operator:t,read:()=>Promise.resolve(r.url())})}async function Zn({expected:e,operator:t,page:r,timeout:n}){return await lt({expected:e,operator:t,timeout:n,read:()=>r.title()}),ct({expected:e,label:"Title",operator:t,read:()=>r.title()})}async function Ar({expected:e,locator:t,operator:r,timeout:n}){await G.expect.poll(async()=>uo({actual:await t.count(),expected:e,operator:r}),{timeout:n}).toBe(!0).catch(()=>{});let o=await t.count();return co({actual:o,expected:e,label:"Count",operator:r})}async function Ir({expected:e,locator:t,operator:r,timeout:n}){return await lt({expected:e,operator:r,timeout:n,read:()=>t.inputValue()}),ct({expected:e,label:"Value",operator:r,read:()=>t.inputValue()})}async function $r({locator:e,timeout:t}){return we({description:"Element is visible",failureDetail:"Element not visible",run:()=>(0,G.expect)(e).toBeVisible({timeout:t})})}async function jr({locator:e,timeout:t}){return we({description:"Element is not visible",failureDetail:"Element still visible",run:()=>(0,G.expect)(e).toBeHidden({timeout:t})})}async function eo({attribute:e,expected:t,locator:r,operator:n,timeout:o}){return await lt({expected:t,operator:n,timeout:o,read:async()=>await r.getAttribute(e)??""}),ct({expected:t,label:`Attribute "${e}"`,operator:n,read:async()=>await r.getAttribute(e)??""})}async function to({locator:e,timeout:t}){return we({description:"Element is enabled",failureDetail:"Element is disabled or not found",run:()=>(0,G.expect)(e).toBeEnabled({timeout:t})})}async function ro({locator:e,timeout:t}){return we({description:"Element is disabled",failureDetail:"Element is enabled or not found",run:()=>(0,G.expect)(e).toBeDisabled({timeout:t})})}async function no({locator:e,timeout:t}){return we({description:"Element is checked",failureDetail:"Element is not checked",run:()=>(0,G.expect)(e).toBeChecked({timeout:t})})}async function oo({locator:e,timeout:t}){return we({description:"Element is not checked",failureDetail:"Element is checked",run:()=>(0,G.expect)(e).not.toBeChecked({timeout:t})})}async function io({locator:e,timeout:t}){return we({description:"Element is focused",failureDetail:"Element is not focused",run:()=>(0,G.expect)(e).toBeFocused({timeout:t})})}async function so({locator:e,timeout:t}){return we({description:"Element is not focused",failureDetail:"Element is focused",run:()=>(0,G.expect)(e).not.toBeFocused({timeout:t})})}async function we({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 lt({expected:e,operator:t,read:r,timeout:n}){await G.expect.poll(async()=>{let o=await r().catch(()=>"");return lo({actual:o,expected:e,operator:t})},{timeout:n}).toBe(!0).catch(()=>{})}async function ct({expected:e,label:t,operator:r,read:n}){try{let o=await n();return ao({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: ${ml(s)}`,status:"failed"}}}function ml(e){let t=e.indexOf(`
12
- `);return t===-1?e:e.slice(0,t)}function ao(e){let t=`${e.label} ${e.operator} "${e.expected}"`,r=lo(e),n=r?void 0:`Got: "${e.actual}"`;return{description:t,detail:n,status:r?"passed":"failed"}}function lo({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 co(e){let t=`${e.label} ${e.operator} ${String(e.expected)}`,r=uo(e),n=r?void 0:`Got: ${String(e.actual)}`;return{description:t,detail:n,status:r?"passed":"failed"}}function uo({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 gl}from"child_process";import{createRequire as yl}from"module";import po from"fs";import mo from"path";import{chromium as fo}from"playwright";import Hb from"fs";import Wb from"path";import fl from"pino";var f=fl({level:process.env.LOG_LEVEL??"info",transport:{options:{ignore:"pid,hostname"},target:"pino-pretty"}});async function Ue({headed:e}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";try{return await fo.launch({headless:!e})}catch(t){throw hl(t)?new Error(`Playwright browsers are not installed. Run:
11
+ `)};X.prototype.renderPartial=function(t,r,n,o){if(n){var i=this.getConfigTags(o),s=xr(n)?n(t[1]):n[t[1]];if(s!=null){var a=t[6],l=t[5],c=t[4],u=s;l==0&&c&&(u=this.indentPartial(s,c,a));var m=this.parse(u,i);return this.renderTokens(m,r,n,u,o)}}};X.prototype.unescapedValue=function(t,r){var n=r.lookup(t[1]);if(n!=null)return n};X.prototype.escapedValue=function(t,r,n){var o=this.getConfigEscape(n)||re.escape,i=r.lookup(t[1]);if(i!=null)return typeof i=="number"&&o===re.escape?String(i):o(i)};X.prototype.rawValue=function(t){return t[1]};X.prototype.getConfigTags=function(t){return Le(t)?t:t&&typeof t=="object"?t.tags:void 0};X.prototype.getConfigEscape=function(t){if(t&&typeof t=="object"&&!Le(t))return t.escape};var re={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(e){at.templateCache=e},get templateCache(){return at.templateCache}},at=new X;re.clearCache=function(){return at.clearCache()};re.parse=function(t,r){return at.parse(t,r)};re.render=function(t,r,n,o){if(typeof t!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+qa(t)+'" was given as the first argument for mustache#render(template, view, partials)');return at.render(t,r,n,o)};re.escape=Qa;re.Scanner=lt;re.Context=Oe;re.Writer=X;var Jn=re;function Er({defs:e}){return e==null?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,al({def:r,name:t})]))}var sl={boolean:!1,number:0,string:""};function al({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??sl[e.type]??""}function Ct({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(Ct({ref:e,variables:t}));return At({raw:r,variables:t})}function Tt({ref:e,variables:t}){let r=Ct({ref:e,variables:t});return typeof r=="string"?At({raw:r,variables:t}):r}function At({raw:e,variables:t}){return Jn.render(e,t,{},{escape:r=>r})}function Cr({ref:e,variables:t}){let r=Ct({ref:e,variables:t});if(typeof r=="number")return r;let n=Number(r);if(Number.isNaN(n))throw new TypeError(`Cannot convert "${String(r)}" to number`);return n}function _e({name:e,store:t,value:r}){return{...t,[e]:r}}function F({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:At({raw:e,variables:t})}async function Yn({node:e,page:t,timeout:r}){await F({locator:e.source,page:t,variables:void 0}).dragTo(F({locator:e.target,page:t,variables:void 0}),{timeout:r})}async function Qn({node:e,page:t,timeout:r}){await F({locator:e.locator,page:t,variables:void 0}).click({button:"right",timeout:r})}function Zn({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 eo({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 st({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 st({awaitPromise:!0,expression:"navigator.clipboard.readText()",label:"clipboard.readText",page:t,timeoutMs:void 0})??"";return{variables:_e({name:e.variable,store:r,value:n})}}async function to({node:e,page:t}){let r=t.context();e.state==="granted"?await r.grantPermissions([e.permission]):await r.clearPermissions()}async function Tr({node:e,page:t,timeout:r,variables:n}){switch(e.type){case"click":return await F({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 ul({node:e,page:t,timeout:r,variables:n});case"rightClick":return await Qn({node:e,page:t,timeout:r}),{variables:n};case"goto":{let o=Y({ref:e.url,variables:n});return await t.goto(o,{timeout:r,waitUntil:"domcontentloaded"}),await t.waitForLoadState("load",{timeout:r}),await t.waitForFunction("document.body != null && document.body.childElementCount > 0 && (document.body.textContent?.trim().length ?? 0) > 0",void 0,{timeout:r}),await st({awaitPromise:!0,expression:"new Promise((resolve) => { requestAnimationFrame(() => requestAnimationFrame(() => resolve(undefined))); })",label:"goto raf-settle",page:t,timeoutMs:void 0}),{variables:n}}case"fill":return pl({node:e,page:t,timeout:r,variables:n});case"select":return ml({node:e,page:t,timeout:r,variables:n});case"type":return fl({node:e,page:t,timeout:r,variables:n});case"press":return await dl({node:e,page:t,timeout:r}),{variables:n};case"drag":return await Yn({node:e,page:t,timeout:r}),{variables:n};case"upload":return gl({node:e,page:t,timeout:r,variables:n});case"extractText":return hl({node:e,page:t,timeout:r,variables:n});case"setVariable":{let o=Tt({ref:e.value,variables:n});return{variables:_e({name:e.variable,store:n,value:o})}}case"fail":throw new Error(e.message);case"setViewport":return await t.setViewportSize({height:e.height,width:e.width}),{variables:n};case"handleDialog":return Zn({node:e,page:t,variables:n});case"clipboard":return eo({node:e,page:t,variables:n});case"setPermission":return await to({node:e,page:t}),{variables:n}}}var cl={check:"check",clear:"clear",click:"click",dblclick:"dblclick",focus:"focus",hover:"hover",scrollIntoView:"scrollIntoViewIfNeeded",uncheck:"uncheck"};async function ul({node:e,page:t,timeout:r,variables:n}){return await F({locator:e.locator,page:t,variables:n})[cl[e.type]]({timeout:r}),{variables:n}}async function dl({node:e,page:t,timeout:r}){e.locator==null?await t.keyboard.press(e.key):await F({locator:e.locator,page:t,variables:void 0}).press(e.key,{timeout:r})}async function pl({node:e,page:t,timeout:r,variables:n}){let o=Y({ref:e.value,variables:n});return await F({locator:e.locator,page:t,variables:n}).fill(o,{timeout:r}),{variables:n}}async function ml({node:e,page:t,timeout:r,variables:n}){let o=Y({ref:e.value,variables:n});return await F({locator:e.locator,page:t,variables:n}).selectOption(o,{timeout:r}),{variables:n}}async function fl({node:e,page:t,timeout:r,variables:n}){let o=Y({ref:e.value,variables:n});return await F({locator:e.locator,page:t,variables:n}).pressSequentially(o,{timeout:r}),{variables:n}}async function gl({node:e,page:t,timeout:r,variables:n}){let o=e.files.map(i=>yl(i));return await F({locator:e.locator,page:t,variables:n}).setInputFiles(o,{timeout:r}),{variables:n}}function yl(e){return ll.join(qn(),e)}async function hl({node:e,page:t,timeout:r,variables:n}){let o=await F({locator:e.locator,page:t,variables:n}).textContent({timeout:r});if(o==null)throw new Error("extractText: element had no text content");return{variables:_e({name:e.variable,store:n,value:o})}}var G={};Da(G,{default:()=>wl});Sr(G,Gb);import*as Gb from"playwright/test";import{default as wl}from"playwright/test";async function Ar({expected:e,locator:t,operator:r,timeout:n}){return await ct({expected:e,operator:r,timeout:n,read:async()=>await t.textContent()??""}),ut({expected:e,label:"Text",operator:r,read:async()=>await t.textContent()??""})}async function Ir({expected:e,operator:t,page:r,timeout:n}){return await ct({expected:e,operator:t,timeout:n,read:()=>Promise.resolve(r.url())}),ut({expected:e,label:"URL",operator:t,read:()=>Promise.resolve(r.url())})}async function ro({expected:e,operator:t,page:r,timeout:n}){return await ct({expected:e,operator:t,timeout:n,read:()=>r.title()}),ut({expected:e,label:"Title",operator:t,read:()=>r.title()})}async function $r({expected:e,locator:t,operator:r,timeout:n}){await G.expect.poll(async()=>fo({actual:await t.count(),expected:e,operator:r}),{timeout:n}).toBe(!0).catch(()=>{});let o=await t.count();return mo({actual:o,expected:e,label:"Count",operator:r})}async function jr({expected:e,locator:t,operator:r,timeout:n}){return await ct({expected:e,operator:r,timeout:n,read:()=>t.inputValue()}),ut({expected:e,label:"Value",operator:r,read:()=>t.inputValue()})}async function Nr({locator:e,timeout:t}){return we({description:"Element is visible",failureDetail:"Element not visible",run:()=>(0,G.expect)(e).toBeVisible({timeout:t})})}async function Dr({locator:e,timeout:t}){return we({description:"Element is not visible",failureDetail:"Element still visible",run:()=>(0,G.expect)(e).toBeHidden({timeout:t})})}async function no({attribute:e,expected:t,locator:r,operator:n,timeout:o}){return await ct({expected:t,operator:n,timeout:o,read:async()=>await r.getAttribute(e)??""}),ut({expected:t,label:`Attribute "${e}"`,operator:n,read:async()=>await r.getAttribute(e)??""})}async function oo({locator:e,timeout:t}){return we({description:"Element is enabled",failureDetail:"Element is disabled or not found",run:()=>(0,G.expect)(e).toBeEnabled({timeout:t})})}async function io({locator:e,timeout:t}){return we({description:"Element is disabled",failureDetail:"Element is enabled or not found",run:()=>(0,G.expect)(e).toBeDisabled({timeout:t})})}async function so({locator:e,timeout:t}){return we({description:"Element is checked",failureDetail:"Element is not checked",run:()=>(0,G.expect)(e).toBeChecked({timeout:t})})}async function ao({locator:e,timeout:t}){return we({description:"Element is not checked",failureDetail:"Element is checked",run:()=>(0,G.expect)(e).not.toBeChecked({timeout:t})})}async function lo({locator:e,timeout:t}){return we({description:"Element is focused",failureDetail:"Element is not focused",run:()=>(0,G.expect)(e).toBeFocused({timeout:t})})}async function co({locator:e,timeout:t}){return we({description:"Element is not focused",failureDetail:"Element is focused",run:()=>(0,G.expect)(e).not.toBeFocused({timeout:t})})}async function we({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 ct({expected:e,operator:t,read:r,timeout:n}){await G.expect.poll(async()=>{let o=await r().catch(()=>"");return po({actual:o,expected:e,operator:t})},{timeout:n}).toBe(!0).catch(()=>{})}async function ut({expected:e,label:t,operator:r,read:n}){try{let o=await n();return uo({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: ${bl(s)}`,status:"failed"}}}function bl(e){let t=e.indexOf(`
12
+ `);return t===-1?e:e.slice(0,t)}function uo(e){let t=`${e.label} ${e.operator} "${e.expected}"`,r=po(e),n=r?void 0:`Got: "${e.actual}"`;return{description:t,detail:n,status:r?"passed":"failed"}}function po({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 mo(e){let t=`${e.label} ${e.operator} ${String(e.expected)}`,r=fo(e),n=r?void 0:`Got: ${String(e.actual)}`;return{description:t,detail:n,status:r?"passed":"failed"}}function fo({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 Sl}from"child_process";import{createRequire as kl}from"module";import go from"fs";import yo from"path";import{chromium as ho}from"playwright";import Qb from"fs";import ev from"path";import vl from"pino";var f=vl({level:process.env.LOG_LEVEL??"info",transport:{options:{ignore:"pid,hostname"},target:"pino-pretty"}});async function Ue({headed:e}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";try{return await ho.launch({headless:!e})}catch(t){throw Pl(t)?new Error(`Playwright browsers are not installed. Run:
13
13
 
14
14
  npx playwright install chromium
15
- `):t}}async function Nr(){let e=fo.executablePath();if(po.existsSync(e))return;f.info("Chromium not found. Installing via Playwright...");let t=yl(import.meta.url),r=mo.dirname(t.resolve("playwright/package.json")),n=mo.join(r,"cli.js");if(await new Promise((o,i)=>{gl(process.execPath,[n,"install","chromium"],s=>{if(s!=null){i(new Error(`Playwright install failed: ${s.message}`));return}o()})}),!po.existsSync(e))throw new Error(`Playwright browser installation failed. Try running manually:
15
+ `):t}}async function Or(){let e=ho.executablePath();if(go.existsSync(e))return;f.info("Chromium not found. Installing via Playwright...");let t=kl(import.meta.url),r=yo.dirname(t.resolve("playwright/package.json")),n=yo.join(r,"cli.js");if(await new Promise((o,i)=>{Sl(process.execPath,[n,"install","chromium"],s=>{if(s!=null){i(new Error(`Playwright install failed: ${s.message}`));return}o()})}),!go.existsSync(e))throw new Error(`Playwright browser installation failed. Try running manually:
16
16
 
17
17
  npx playwright install chromium
18
- `);f.info("\u2713 Chromium installed")}function hl(e){return e instanceof Error?e.message.includes("Executable doesn't exist"):!1}import{readdir as Pl,rm as Rl,stat as xl}from"fs/promises";import ov from"os";import ho from"path";import{graphql as El}from"gql.tada";import{print as wl}from"graphql";var bl=15e3,Ve=class extends Error{errors;constructor(t){super(t.map(r=>r.message).join(", ")),this.name="GqlRequestError",this.errors=t}};async function h(e){let t=wl(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(bl)})}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 vl({res:o,url:n});if(!Sl(i))throw new Error("Invalid GraphQL response");if(kl(i))throw new Ve(i.errors);if(i.data==null)throw new Error("No data returned from server");return i.data}async function vl({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 Sl(e){return typeof e=="object"&&e!=null&&("data"in e||"errors"in e)}function kl(e){return Array.isArray(e.errors)&&e.errors.length>0}var go=ho.join(process.cwd(),".ripplo","debug"),yo=360*60*1e3,cv=El(`
18
+ `);f.info("\u2713 Chromium installed")}function Pl(e){return e instanceof Error?e.message.includes("Executable doesn't exist"):!1}import{readdir as Al,rm as Il,stat as $l}from"fs/promises";import fv from"os";import vo from"path";import{graphql as jl}from"gql.tada";import{print as Rl}from"graphql";var xl=15e3,Ve=class extends Error{errors;constructor(t){super(t.map(r=>r.message).join(", ")),this.name="GqlRequestError",this.errors=t}};async function h(e){let t=Rl(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(xl)})}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(!Cl(i))throw new Error("Invalid GraphQL response");if(Tl(i))throw new Ve(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 Cl(e){return typeof e=="object"&&e!=null&&("data"in e||"errors"in e)}function Tl(e){return Array.isArray(e.errors)&&e.errors.length>0}var wo=vo.join(process.cwd(),".ripplo","debug"),bo=360*60*1e3,bv=jl(`
19
19
  mutation RevokeCurrentCliToken {
20
20
  revokeCurrentCliToken
21
21
  }
22
- `);async function Tt({maxRuns:e}){try{let r=(await Pl(go,{withFileTypes:!0})).filter(c=>c.isDirectory()),n=Date.now(),o=await Promise.all(r.map(async c=>{let u=ho.join(go,c.name),m=await xl(u);return{dirPath:u,mtime:m.mtimeMs}})),i=o.filter(c=>n-c.mtime>yo),a=o.filter(c=>n-c.mtime<=yo).toSorted((c,u)=>u.mtime-c.mtime).slice(e),l=[...i,...a];if(l.length===0)return;await Promise.allSettled(l.map(c=>Rl(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 Cl=15e3,Tl=2,Al=250,Il=3e4,Dr=new Map;function Or({appUrl:e}){let t=Date.now(),r=Dr.get(e);if(r!=null&&r.expiresAt>t)return r.promise;let n=$l(e).catch(o=>{throw Dr.delete(e),o});return Dr.set(e,{expiresAt:t+Il,promise:n}),n}async function $l(e){let t=null,r=0;for(;r<=Tl;){r>0&&await Nl(Al);let o=await jl(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 jl(e,t){let r=performance.now();try{return await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(Cl)}),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 Nl(e){return new Promise(t=>setTimeout(t,e))}import{Agent as Dl,RetryAgent as Ol,setGlobalDispatcher as Ll}from"undici";var _l=1500,Ul=4e3,Vl=3,Fl=50,Ml=100,wo=!1;function Lr(){if(wo)return;wo=!0;let e=new Dl({connections:Ml,keepAliveMaxTimeout:Ul,keepAliveTimeout:_l}),t=new Ol(e,{errorCodes:["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT","UND_ERR_REQ_CONTENT_LENGTH_MISMATCH","UND_ERR_SOCKET"],maxRetries:Vl,methods:["GET","POST","HEAD","OPTIONS","PUT","DELETE"],minTimeout:Fl});Ll(t)}var Ko=vr(At(),1);import{z as Ed}from"zod";import{z as It}from"zod";var Yl=It.object({__codec:It.string().min(1),data:It.unknown(),version:It.number().int().positive()}),$t=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}},jt=class extends Error{constructor(t){super(`Codec mismatch: expected "${t.expected}", got "${t.got}"`),this.name="CodecMismatchError"}};function Nt(e){return So({legacy:void 0,migrators:[],name:e,schemas:[]})}function So(e){return{initial:t=>Fr(t,{...e,schemas:[t]}),legacy:t=>So({...e,legacy:t})}}function Fr(e,t){return{build:()=>Ql(e,t),legacy:r=>Fr(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return Fr(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function Ql(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>Zl(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function Zl(e,t,r){let{data:n,version:o}=ec(t,r),i=ko(t,n,o);return e.parse(i)}function ec(e,t){let r=Yl.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new jt({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 ko(e,t,r){let n=e.schemas.length;if(r>n)throw new $t({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 ko(e,s(i),r+1)}import{z as Eo}from"zod";import{z as Fe}from"zod";var Mr=Fe.object({depends:Fe.array(Fe.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:Fe.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:Fe.array(Fe.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 be}from"zod";var tc=be.object({by:be.literal("testId"),value:be.string().min(1)}),rc=be.object({by:be.literal("role"),name:be.string().optional(),role:be.string().min(1)}),x=be.discriminatedUnion("by",[tc,rc]);import{z as Po}from"zod";var ve=Po.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),Dt=Po.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]);import{z as N}from"zod";var nc=N.object({type:N.literal("static"),value:N.union([N.string(),N.number(),N.boolean()])}),Ot=N.object({name:N.string().min(1),type:N.literal("variable")}),Lt=N.discriminatedUnion("type",[nc,Ot]),Q=N.discriminatedUnion("type",[N.object({type:N.literal("static"),value:N.string()}),Ot]),_t=N.discriminatedUnion("type",[N.object({type:N.literal("static"),value:N.number().int().nonnegative()}),Ot]),Hr=N.discriminatedUnion("type",[N.object({type:N.literal("static"),value:N.union([N.string(),N.number(),N.boolean()])}),Ot]);import{z as Z}from"zod";var Ut=Z.discriminatedUnion("type",[Z.object({default:Z.string().optional(),type:Z.literal("string")}),Z.object({default:Z.number().optional(),type:Z.literal("number")}),Z.object({default:Z.boolean().optional(),type:Z.literal("boolean")}),Z.object({key:Z.string().min(1),type:Z.literal("env")})]);var v={id:d.string().min(1).max(200),label:d.string().max(500).optional(),next:d.string().max(200).optional(),uiOnly:d.boolean().optional()},Ro=500,oc=d.object({...v,type:d.literal("goto"),url:Q}),ic=d.object({...v,locator:x,modifier:d.enum(["Alt","Control","Meta","Shift"]).optional(),type:d.literal("click")}),sc=d.object({...v,locator:x,type:d.literal("fill"),value:Q}),ac=d.object({...v,locator:x,type:d.literal("select"),value:Q}),lc=d.object({...v,locator:x,type:d.literal("hover")}),cc=d.object({...v,key:d.string().min(1),locator:x.optional(),type:d.literal("press")}),uc=d.object({...v,locator:x,type:d.literal("check")}),dc=d.object({...v,locator:x,type:d.literal("uncheck")}),pc=d.object({...v,height:d.number().int().positive(),type:d.literal("setViewport"),width:d.number().int().positive()}),mc=d.object({...v,message:d.string().min(1),type:d.literal("fail")}),fc=d.object({...v,type:d.literal("setVariable"),value:Lt,variable:d.string().min(1)}),gc=d.object({...v,locator:x,type:d.literal("extractText"),variable:d.string().min(1)}),yc=d.object({...v,files:d.array(d.string()).min(1),locator:x,type:d.literal("upload")}),hc=d.object({...v,locator:x,type:d.literal("dblclick")}),wc=d.object({...v,source:x,target:x,type:d.literal("drag")}),bc=d.object({...v,locator:x,type:d.literal("scrollIntoView")}),vc=d.object({...v,locator:x,type:d.literal("type"),value:Q}),Sc=d.object({...v,locator:x,type:d.literal("focus")}),kc=d.object({...v,locator:x,type:d.literal("clear")}),Pc=d.object({...v,locator:x,type:d.literal("rightClick")}),Rc=d.object({...v,action:d.enum(["accept","dismiss"]),promptText:d.string().optional(),type:d.literal("handleDialog")}),xc=d.object({...v,action:d.enum(["read","write"]),type:d.literal("clipboard"),value:Q.optional(),variable:d.string().min(1).optional()}),Ec=d.object({...v,permission:d.string().min(1),state:d.enum(["granted","prompt"]),type:d.literal("setPermission")}),Cc=d.object({...v,locator:x,type:d.literal("assertVisible")}),Tc=d.object({...v,locator:x,type:d.literal("assertNotVisible")}),Ac=d.object({...v,expected:Q,locator:x,operator:ve,type:d.literal("assertText")}),Ic=d.object({...v,expected:Q,operator:ve,type:d.literal("assertUrl")}),$c=d.object({...v,expected:_t,locator:x,operator:Dt,type:d.literal("assertCount")}),jc=d.object({...v,expected:Q,locator:x,operator:ve,type:d.literal("assertValue")}),Nc=d.object({...v,attribute:d.string().min(1),expected:Q,locator:x,operator:ve,type:d.literal("assertAttribute")}),Dc=d.object({...v,locator:x,type:d.literal("assertEnabled")}),Oc=d.object({...v,locator:x,type:d.literal("assertDisabled")}),Lc=d.object({...v,expected:Q,operator:ve,type:d.literal("assertTitle")}),_c=d.object({...v,locator:x,type:d.literal("assertChecked")}),Uc=d.object({...v,locator:x,type:d.literal("assertNotChecked")}),Vc=d.object({...v,locator:x,type:d.literal("assertFocused")}),Fc=d.object({...v,locator:x,type:d.literal("assertNotFocused")}),Mc=d.object({...v,budget:d.enum(["fast","slow","async"]),observer:d.string().min(1).max(200),params:d.record(d.string().max(200),Hr),type:d.literal("assertObserver")}),xo=d.discriminatedUnion("type",[oc,ic,sc,ac,lc,cc,uc,dc,Cc,Tc,Ac,Ic,$c,jc,Nc,Dc,Oc,pc,mc,fc,gc,yc,hc,wc,bc,vc,Sc,kc,Pc,Rc,xc,Ec,Lc,_c,Uc,Vc,Fc,Mc]),Vt=d.object({entryNode:d.string().min(1).max(200),nodes:d.record(d.string().max(200),xo).refine(e=>Object.keys(e).length<=Ro,`Workflow has more than ${String(Ro)} nodes`),uiOnly:d.boolean().optional(),variableNamespaces:d.record(d.string().max(200),d.string().max(500)).optional(),variables:d.record(d.string().max(200),Ut).optional()});var Hc=Eo.record(Eo.string().max(200),Mr),Bc={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},Wc={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},Br=Nt("workflow-spec").legacy(Bc).initial(Vt).build(),qc=Nt("precondition-map").legacy(Wc).initial(Hc).build();import{z as Wr}from"zod";var Co=["fast","slow","async"],zc=Wr.object({budget:Wr.enum(Co).describe("Polling budget tier: fast | slow | async"),description:Wr.string().min(1).describe("Human-readable description of what this observer checks")}).describe("A named backend state observer. Tests assert against it with assert.backend(observer, params). Implementation lives on the user's server.");function Ft(e){return e.label??`${e.type} (${e.id})`}import{graphql as Jo,readFragment as Cd}from"gql.tada";function Ao(){let e,t=!1;function r(o){e=o,t&&To(o)}async function n(){t||(t=!0,e!=null&&await To(e))}return{attachContext:r,fire:n,fired:()=>t}}async function To(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 qr,writeFile as q}from"fs/promises";import M from"path";import{z as ne}from"zod";async function j({fn:e,label:t}){let r=performance.now(),n=await e();return f.debug("%s: %dms",t,Math.round(performance.now()-r)),n}async function $o({cdpSession:e,context:t,page:r,runId:n,stepIndex:o,stepResult:i}){try{let s=M.join(process.cwd(),".ripplo","debug",n,"steps",String(o));await qr(s,{recursive:!0});let a={assertions:i.assertions,detail:i.detail,duration:i.duration,nodeId:i.nodeId,nodeType:i.nodeType,snapshotTimestamp:i.snapshotTimestamp,status:i.status,stepIndex:i.stepIndex,title:i.title,url:i.url};await Promise.all([q(M.join(s,"info.json"),JSON.stringify(a,null,2)),Jc(Yc({cdpSession:e,context:t,page:r,stepDir:s}),Gc,`capturePageState step ${String(o)}`)])}catch(s){let a=s instanceof Error?s.message:String(s);f.warn("Failed to write step debug data for step %d: %s",o,a)}}var Gc=15e3,Kc=50;async function Jc(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)}}function Xc(e){return e.replaceAll(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"<script>/* stripped */</script>").replaceAll(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"<style>/* stripped */</style>")}async function Yc({cdpSession:e,context:t,stepDir:r}){let[n,o,i,s,a]=await Promise.all([j({label:"captureDom",fn:()=>eu(e)}),j({label:"captureAxTree",fn:()=>nu(e)}),j({label:"captureStorage",fn:()=>cu({cdpSession:e,context:t})}),j({label:"captureScreenshot",fn:()=>au(e)}),j({label:"captureRrwebElements",fn:()=>Zc(e)})]);await j({label:"writeStepFiles",fn:()=>Promise.all([q(M.join(r,"dom.html"),Xc(n)),q(M.join(r,"accessibility-tree.full.json"),JSON.stringify(o)),q(M.join(r,"accessibility-tree.json"),ou(o)),q(M.join(r,"storage.json"),JSON.stringify(i,null,2)),q(M.join(r,"rrweb-elements.ndjson"),a),q(M.join(r,"screenshot.png"),s)]).then(()=>{})})}var Qc=`
22
+ `);async function It({maxRuns:e}){try{let r=(await Al(wo,{withFileTypes:!0})).filter(c=>c.isDirectory()),n=Date.now(),o=await Promise.all(r.map(async c=>{let u=vo.join(wo,c.name),m=await $l(u);return{dirPath:u,mtime:m.mtimeMs}})),i=o.filter(c=>n-c.mtime>bo),a=o.filter(c=>n-c.mtime<=bo).toSorted((c,u)=>u.mtime-c.mtime).slice(e),l=[...i,...a];if(l.length===0)return;await Promise.allSettled(l.map(c=>Il(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 Nl=15e3,Dl=2,Ol=250,Ll=3e4,Lr=new Map;function _r({appUrl:e}){let t=Date.now(),r=Lr.get(e);if(r!=null&&r.expiresAt>t)return r.promise;let n=_l(e).catch(o=>{throw Lr.delete(e),o});return Lr.set(e,{expiresAt:t+Ll,promise:n}),n}async function _l(e){let t=null,r=0;for(;r<=Dl;){r>0&&await Vl(Ol);let o=await Ul(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 Ul(e,t){let r=performance.now();try{return await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(Nl)}),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 Vl(e){return new Promise(t=>setTimeout(t,e))}import{Agent as Fl,RetryAgent as Ml,setGlobalDispatcher as Hl}from"undici";var Bl=1500,Wl=4e3,ql=3,zl=50,Gl=100,So=!1;function Ur(){if(So)return;So=!0;let e=new Fl({connections:Gl,keepAliveMaxTimeout:Wl,keepAliveTimeout:Bl}),t=new Ml(e,{errorCodes:["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT","UND_ERR_REQ_CONTENT_LENGTH_MISMATCH","UND_ERR_SOCKET"],maxRetries:ql,methods:["GET","POST","HEAD","OPTIONS","PUT","DELETE"],minTimeout:zl});Hl(t)}var Yo=kr($t(),1);import{z as jd}from"zod";import{z as jt}from"zod";var nc=jt.object({__codec:jt.string().min(1),data:jt.unknown(),version:jt.number().int().positive()}),Nt=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}},Dt=class extends Error{constructor(t){super(`Codec mismatch: expected "${t.expected}", got "${t.got}"`),this.name="CodecMismatchError"}};function Ot(e){return Ro({legacy:void 0,migrators:[],name:e,schemas:[]})}function Ro(e){return{initial:t=>Hr(t,{...e,schemas:[t]}),legacy:t=>Ro({...e,legacy:t})}}function Hr(e,t){return{build:()=>oc(e,t),legacy:r=>Hr(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return Hr(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function oc(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>ic(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function ic(e,t,r){let{data:n,version:o}=sc(t,r),i=xo(t,n,o);return e.parse(i)}function sc(e,t){let r=nc.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new Dt({expected:e.name,got:r.data.__codec});return{data:r.data.data,version:r.data.version}}if(e.legacy!=null&&e.legacy.detect(t))return{data:t,version:e.legacy.assumedVersion};throw new Error(`Cannot decode "${e.name}": value is not a codec envelope and no legacy detector matched.`)}function xo(e,t,r){let n=e.schemas.length;if(r>n)throw new Nt({codec:e.name,currentVersion:n,gotVersion:r});if(r===n)return t;let o=e.schemas[r-1];if(o==null)throw new Error(`Codec "${e.name}" missing schema for v${String(r)}; cannot migrate.`);let i=o.parse(t),s=e.migrators[r-1];if(s==null)throw new Error(`Codec "${e.name}" missing migrator v${String(r)} \u2192 v${String(r+1)}.`);return xo(e,s(i),r+1)}import{z as Ao}from"zod";import{z as Fe}from"zod";var Br=Fe.object({depends:Fe.array(Fe.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:Fe.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:Fe.array(Fe.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 be}from"zod";var ac=be.object({by:be.literal("testId"),value:be.string().min(1)}),lc=be.object({by:be.literal("role"),name:be.string().optional(),role:be.string().min(1)}),x=be.discriminatedUnion("by",[ac,lc]);import{z as Eo}from"zod";var ve=Eo.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),Lt=Eo.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]);import{z as N}from"zod";var cc=N.object({type:N.literal("static"),value:N.union([N.string(),N.number(),N.boolean()])}),_t=N.object({name:N.string().min(1),type:N.literal("variable")}),Ut=N.discriminatedUnion("type",[cc,_t]),Q=N.discriminatedUnion("type",[N.object({type:N.literal("static"),value:N.string()}),_t]),Vt=N.discriminatedUnion("type",[N.object({type:N.literal("static"),value:N.number().int().nonnegative()}),_t]),Wr=N.discriminatedUnion("type",[N.object({type:N.literal("static"),value:N.union([N.string(),N.number(),N.boolean()])}),_t]);import{z as Z}from"zod";var Ft=Z.discriminatedUnion("type",[Z.object({default:Z.string().optional(),type:Z.literal("string")}),Z.object({default:Z.number().optional(),type:Z.literal("number")}),Z.object({default:Z.boolean().optional(),type:Z.literal("boolean")}),Z.object({key:Z.string().min(1),type:Z.literal("env")})]);var v={id:d.string().min(1).max(200),label:d.string().max(500).optional(),next:d.string().max(200).optional(),uiOnly:d.boolean().optional()},Co=500,uc=d.object({...v,type:d.literal("goto"),url:Q}),dc=d.object({...v,locator:x,modifier:d.enum(["Alt","Control","Meta","Shift"]).optional(),type:d.literal("click")}),pc=d.object({...v,locator:x,type:d.literal("fill"),value:Q}),mc=d.object({...v,locator:x,type:d.literal("select"),value:Q}),fc=d.object({...v,locator:x,type:d.literal("hover")}),gc=d.object({...v,key:d.string().min(1),locator:x.optional(),type:d.literal("press")}),yc=d.object({...v,locator:x,type:d.literal("check")}),hc=d.object({...v,locator:x,type:d.literal("uncheck")}),wc=d.object({...v,height:d.number().int().positive(),type:d.literal("setViewport"),width:d.number().int().positive()}),bc=d.object({...v,message:d.string().min(1),type:d.literal("fail")}),vc=d.object({...v,type:d.literal("setVariable"),value:Ut,variable:d.string().min(1)}),Sc=d.object({...v,locator:x,type:d.literal("extractText"),variable:d.string().min(1)}),kc=d.object({...v,files:d.array(d.string()).min(1),locator:x,type:d.literal("upload")}),Pc=d.object({...v,locator:x,type:d.literal("dblclick")}),Rc=d.object({...v,source:x,target:x,type:d.literal("drag")}),xc=d.object({...v,locator:x,type:d.literal("scrollIntoView")}),Ec=d.object({...v,locator:x,type:d.literal("type"),value:Q}),Cc=d.object({...v,locator:x,type:d.literal("focus")}),Tc=d.object({...v,locator:x,type:d.literal("clear")}),Ac=d.object({...v,locator:x,type:d.literal("rightClick")}),Ic=d.object({...v,action:d.enum(["accept","dismiss"]),promptText:d.string().optional(),type:d.literal("handleDialog")}),$c=d.object({...v,action:d.enum(["read","write"]),type:d.literal("clipboard"),value:Q.optional(),variable:d.string().min(1).optional()}),jc=d.object({...v,permission:d.string().min(1),state:d.enum(["granted","prompt"]),type:d.literal("setPermission")}),Nc=d.object({...v,locator:x,type:d.literal("assertVisible")}),Dc=d.object({...v,locator:x,type:d.literal("assertNotVisible")}),Oc=d.object({...v,expected:Q,locator:x,operator:ve,type:d.literal("assertText")}),Lc=d.object({...v,expected:Q,operator:ve,type:d.literal("assertUrl")}),_c=d.object({...v,expected:Vt,locator:x,operator:Lt,type:d.literal("assertCount")}),Uc=d.object({...v,expected:Q,locator:x,operator:ve,type:d.literal("assertValue")}),Vc=d.object({...v,attribute:d.string().min(1),expected:Q,locator:x,operator:ve,type:d.literal("assertAttribute")}),Fc=d.object({...v,locator:x,type:d.literal("assertEnabled")}),Mc=d.object({...v,locator:x,type:d.literal("assertDisabled")}),Hc=d.object({...v,expected:Q,operator:ve,type:d.literal("assertTitle")}),Bc=d.object({...v,locator:x,type:d.literal("assertChecked")}),Wc=d.object({...v,locator:x,type:d.literal("assertNotChecked")}),qc=d.object({...v,locator:x,type:d.literal("assertFocused")}),zc=d.object({...v,locator:x,type:d.literal("assertNotFocused")}),Gc=d.object({...v,budget:d.enum(["fast","slow","async"]),observer:d.string().min(1).max(200),params:d.record(d.string().max(200),Wr),type:d.literal("assertObserver")}),To=d.discriminatedUnion("type",[uc,dc,pc,mc,fc,gc,yc,hc,Nc,Dc,Oc,Lc,_c,Uc,Vc,Fc,Mc,wc,bc,vc,Sc,kc,Pc,Rc,xc,Ec,Cc,Tc,Ac,Ic,$c,jc,Hc,Bc,Wc,qc,zc,Gc]),Mt=d.object({entryNode:d.string().min(1).max(200),nodes:d.record(d.string().max(200),To).refine(e=>Object.keys(e).length<=Co,`Workflow has more than ${String(Co)} nodes`),uiOnly:d.boolean().optional(),variableNamespaces:d.record(d.string().max(200),d.string().max(500)).optional(),variables:d.record(d.string().max(200),Ft).optional()});var Kc=Ao.record(Ao.string().max(200),Br),Jc={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},Xc={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},qr=Ot("workflow-spec").legacy(Jc).initial(Mt).build(),Yc=Ot("precondition-map").legacy(Xc).initial(Kc).build();import{z as zr}from"zod";var Io=["fast","slow","async"],Qc=zr.object({budget:zr.enum(Io).describe("Polling budget tier: fast | slow | async"),description:zr.string().min(1).describe("Human-readable description of what this observer checks")}).describe("A named backend state observer. Tests assert against it with assert.backend(observer, params). Implementation lives on the user's server.");function Ht(e){return e.label??`${e.type} (${e.id})`}import{graphql as Qo,readFragment as Nd}from"gql.tada";function jo(){let e,t=!1;function r(o){e=o,t&&$o(o)}async function n(){t||(t=!0,e!=null&&await $o(e))}return{attachContext:r,fire:n,fired:()=>t}}async function $o(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 Gr,writeFile as q}from"fs/promises";import M from"path";import{z as ne}from"zod";async function j({fn:e,label:t}){let r=performance.now(),n=await e();return f.debug("%s: %dms",t,Math.round(performance.now()-r)),n}async function Do({cdpSession:e,context:t,page:r,runId:n,stepIndex:o,stepResult:i}){try{let s=M.join(process.cwd(),".ripplo","debug",n,"steps",String(o));await Gr(s,{recursive:!0});let a={assertions:i.assertions,detail:i.detail,duration:i.duration,nodeId:i.nodeId,nodeType:i.nodeType,snapshotTimestamp:i.snapshotTimestamp,status:i.status,stepIndex:i.stepIndex,title:i.title,url:i.url};await Promise.all([q(M.join(s,"info.json"),JSON.stringify(a,null,2)),tu(nu({cdpSession:e,context:t,page:r,stepDir:s}),Zc,`capturePageState step ${String(o)}`)])}catch(s){let a=s instanceof Error?s.message:String(s);f.warn("Failed to write step debug data for step %d: %s",o,a)}}var Zc=15e3,eu=50;async function tu(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)}}function ru(e){return e.replaceAll(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"<script>/* stripped */</script>").replaceAll(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"<style>/* stripped */</style>")}async function nu({cdpSession:e,context:t,stepDir:r}){let[n,o,i,s,a]=await Promise.all([j({label:"captureDom",fn:()=>su(e)}),j({label:"captureAxTree",fn:()=>cu(e)}),j({label:"captureStorage",fn:()=>gu({cdpSession:e,context:t})}),j({label:"captureScreenshot",fn:()=>mu(e)}),j({label:"captureRrwebElements",fn:()=>iu(e)})]);await j({label:"writeStepFiles",fn:()=>Promise.all([q(M.join(r,"dom.html"),ru(n)),q(M.join(r,"accessibility-tree.full.json"),JSON.stringify(o)),q(M.join(r,"accessibility-tree.json"),uu(o)),q(M.join(r,"storage.json"),JSON.stringify(i,null,2)),q(M.join(r,"rrweb-elements.ndjson"),a),q(M.join(r,"screenshot.png"),s)]).then(()=>{})})}var ou=`
24
24
  (function () {
25
25
  try {
26
26
  var rrweb = window.rrweb || globalThis.rrweb;
@@ -84,8 +84,8 @@ Values:
84
84
  return JSON.stringify({ __ripploError: String(err && err.message ? err.message : err) });
85
85
  }
86
86
  })()
87
- `;async function Zc(e){return await se({awaitPromise:!1,expression:Qc,label:"captureRrwebElements",session:e,timeoutMs:void 0})??""}async function eu(e){return await se({awaitPromise:!1,expression:"document.documentElement.outerHTML",label:"captureDom",session:e,timeoutMs:void 0})??"(unable to capture DOM)"}var Mt=ne.object({value:ne.unknown()}).partial(),tu=ne.object({childIds:ne.array(ne.string()),description:Mt,ignored:ne.boolean(),name:Mt,nodeId:ne.string(),parentId:ne.string(),properties:ne.array(ne.unknown()),role:Mt,value:Mt}).partial(),ru=ne.object({nodes:ne.array(tu)});async function nu(e){let t=await e.send("Accessibility.getFullAXTree"),r=ru.safeParse(t);return r.success?r.data:{nodes:[]}}function ou(e){return e.nodes.filter(t=>t.ignored!==!0).map(t=>iu(t)).toSorted(su).map(t=>JSON.stringify(t)).join(`
88
- `)}function iu(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 su(e,t){return Io(e.nodeId)-Io(t.nodeId)}function Io(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 au(e){let t=await e.send("Page.captureScreenshot",{format:"png",optimizeForSpeed:!0});return Buffer.from(t.data,"base64")}var lu=`(() => {
87
+ `;async function iu(e){return await se({awaitPromise:!1,expression:ou,label:"captureRrwebElements",session:e,timeoutMs:void 0})??""}async function su(e){return await se({awaitPromise:!1,expression:"document.documentElement.outerHTML",label:"captureDom",session:e,timeoutMs:void 0})??"(unable to capture DOM)"}var Bt=ne.object({value:ne.unknown()}).partial(),au=ne.object({childIds:ne.array(ne.string()),description:Bt,ignored:ne.boolean(),name:Bt,nodeId:ne.string(),parentId:ne.string(),properties:ne.array(ne.unknown()),role:Bt,value:Bt}).partial(),lu=ne.object({nodes:ne.array(au)});async function cu(e){let t=await e.send("Accessibility.getFullAXTree"),r=lu.safeParse(t);return r.success?r.data:{nodes:[]}}function uu(e){return e.nodes.filter(t=>t.ignored!==!0).map(t=>du(t)).toSorted(pu).map(t=>JSON.stringify(t)).join(`
88
+ `)}function du(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 pu(e,t){return No(e.nodeId)-No(t.nodeId)}function No(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 mu(e){let t=await e.send("Page.captureScreenshot",{format:"png",optimizeForSpeed:!0});return Buffer.from(t.data,"base64")}var fu=`(() => {
89
89
  function dump(s) {
90
90
  var out = {};
91
91
  for (var i = 0; i < s.length; i++) {
@@ -95,23 +95,23 @@ Values:
95
95
  return out;
96
96
  }
97
97
  return { localStorage: dump(localStorage), sessionStorage: dump(sessionStorage) };
98
- })()`;async function cu({cdpSession:e,context:t}){let[r,n]=await Promise.all([se({awaitPromise:!1,expression:lu,label:"captureStorage",session:e,timeoutMs:void 0}),t.cookies().catch(()=>[])]);return{cookies:n,localStorage:r?.localStorage??{},sessionStorage:r?.sessionStorage??{}}}async function jo({pageEvents:e,runId:t,steps:r,summary:n}){try{let o=M.join(process.cwd(),".ripplo","debug",t);await qr(o,{recursive:!0});let i=e.capturePerf(),s=Promise.race([e.drain(),new Promise(a=>setTimeout(a,Kc))]);await Promise.all([q(M.join(o,"summary.txt"),fu({steps:r,summary:n})),q(M.join(o,"manifest.md"),gu({steps:r,summary:n})),q(M.join(o,"console.log"),uu(e.consoleEntries)),q(M.join(o,"page-errors.log"),du(e.pageErrors)),q(M.join(o,"events.jsonl"),mu(e.lifecycle)),s.then(()=>q(M.join(o,"network.jsonl"),pu(e.network))),i.then(a=>q(M.join(o,"perf.json"),a==null?"":JSON.stringify(a,null,2)))]),f.info("Debug artifacts written to .ripplo/debug/%s/",t)}catch(o){let i=o instanceof Error?o.message:String(o);f.warn("Failed to write run debug summary: %s",i)}}function uu(e){return e.map(t=>{let r=t.url==null||t.url.length===0?"":` (${t.url})`;return`[${new Date(t.timestamp).toISOString()}] ${t.type.toUpperCase()}${r} ${t.text}`}).join(`
99
- `)}function du(e){return e.map(t=>{let r=t.stack==null?"":`
98
+ })()`;async function gu({cdpSession:e,context:t}){let[r,n]=await Promise.all([se({awaitPromise:!1,expression:fu,label:"captureStorage",session:e,timeoutMs:void 0}),t.cookies().catch(()=>[])]);return{cookies:n,localStorage:r?.localStorage??{},sessionStorage:r?.sessionStorage??{}}}async function Oo({pageEvents:e,runId:t,steps:r,summary:n}){try{let o=M.join(process.cwd(),".ripplo","debug",t);await Gr(o,{recursive:!0});let i=e.capturePerf(),s=Promise.race([e.drain(),new Promise(a=>setTimeout(a,eu))]);await Promise.all([q(M.join(o,"summary.txt"),vu({steps:r,summary:n})),q(M.join(o,"manifest.md"),Su({steps:r,summary:n})),q(M.join(o,"console.log"),yu(e.consoleEntries)),q(M.join(o,"page-errors.log"),hu(e.pageErrors)),q(M.join(o,"events.jsonl"),bu(e.lifecycle)),s.then(()=>q(M.join(o,"network.jsonl"),wu(e.network))),i.then(a=>q(M.join(o,"perf.json"),a==null?"":JSON.stringify(a,null,2)))]),f.info("Debug artifacts written to .ripplo/debug/%s/",t)}catch(o){let i=o instanceof Error?o.message:String(o);f.warn("Failed to write run debug summary: %s",i)}}function yu(e){return e.map(t=>{let r=t.url==null||t.url.length===0?"":` (${t.url})`;return`[${new Date(t.timestamp).toISOString()}] ${t.type.toUpperCase()}${r} ${t.text}`}).join(`
99
+ `)}function hu(e){return e.map(t=>{let r=t.stack==null?"":`
100
100
  ${t.stack}`;return`[${new Date(t.timestamp).toISOString()}] ${t.message}${r}`}).join(`
101
101
 
102
- `)}function pu(e){return e.map(t=>JSON.stringify(t)).join(`
103
- `)}function mu(e){return e.map(t=>JSON.stringify(t)).join(`
104
- `)}function fu({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(`
105
- `)}function gu({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.","- `console.log` \u2014 page console messages captured during the run.","- `page-errors.log` \u2014 uncaught page errors captured during the run.","- `network.jsonl` \u2014 one network response/failure per line, including request/response headers and bodies when available.","- `events.jsonl` \u2014 page lifecycle events (crash, dialog, navigation, popup, download, worker).","- `perf.json` \u2014 Performance API snapshot (navigation, paint, resource entries, memory).","","## 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(`
106
- `)}async function No({error:e,runId:t,stack:r,workflowName:n}){try{let o=M.join(process.cwd(),".ripplo","debug",t);await qr(o,{recursive:!0});let i=r==null?e:`${e}
102
+ `)}function wu(e){return e.map(t=>JSON.stringify(t)).join(`
103
+ `)}function bu(e){return e.map(t=>JSON.stringify(t)).join(`
104
+ `)}function vu({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(`
105
+ `)}function Su({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.","- `console.log` \u2014 page console messages captured during the run.","- `page-errors.log` \u2014 uncaught page errors captured during the run.","- `network.jsonl` \u2014 one network response/failure per line, including request/response headers and bodies when available.","- `events.jsonl` \u2014 page lifecycle events (crash, dialog, navigation, popup, download, worker).","- `perf.json` \u2014 Performance API snapshot (navigation, paint, resource entries, memory).","","## 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(`
106
+ `)}async function Lo({error:e,runId:t,stack:r,workflowName:n}){try{let o=M.join(process.cwd(),".ripplo","debug",t);await Gr(o,{recursive:!0});let i=r==null?e:`${e}
107
107
 
108
108
  ${r}`,s=[`Run ID: ${t}`,`Workflow: ${n}`,"Status: failed","",`Error: ${e}`,"",r==null?"":`Stack trace:
109
109
  ${r}`].join(`
110
110
  `),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(`
111
- `);await Promise.all([q(M.join(o,"error.txt"),i),q(M.join(o,"summary.txt"),s),q(M.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 yu}from"fs";import{createRequire as hu}from"module";import Do from"path";import{gzipSync as wu}from"zlib";var bu=hu(import.meta.url),vu=bu.resolve("rrweb"),Su=Do.join(Do.dirname(vu),"rrweb.umd.min.cjs"),ku=yu(Su,"utf8"),Pu=[";(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(`
112
- `),Ru=ku+`
113
- `+Pu;async function Oo({cdpSession:e,page:t}){let r,n=0;async function o(){await t.addScriptTag({content:Ru})}await o(),t.on("load",()=>{o().catch(c=>{let u=c instanceof Error?c.message:String(c);f.warn("rrweb re-injection on navigation failed: %s",u)})});async function i(){await se({awaitPromise:!1,expression:"globalThis.__ripploRrwebStart && globalThis.__ripploRrwebStart()",label:"rrweb start",session:e,timeoutMs:void 0});let c=await se({awaitPromise:!1,expression:"globalThis.__ripploRrwebStartedAt",label:"rrweb startedAt",session:e,timeoutMs:void 0});typeof c=="number"&&(r??=c)}function s(){if(r!=null)return Date.now()-r}async function a(){let c=await se({awaitPromise:!1,expression:"globalThis.__ripploRrwebDrain ? globalThis.__ripploRrwebDrain() : []",label:"rrweb drain",session:e,timeoutMs:void 0})??[],u=c[0],m=c.at(-1);if(u==null||m==null)return;r??=u.timestamp;let g=r,R=c.map(H=>JSON.stringify(H)).join(`
114
- `),y={body:wu(Buffer.from(R,"utf8")),chunkIndex:n,endTimestamp:m.timestamp-g,eventCount:c.length,startTimestamp:u.timestamp-g};return n+=1,y}async function l(){await se({awaitPromise:!1,expression:"globalThis.__ripploRrwebStop && globalThis.__ripploRrwebStop()",label:"rrweb stop",session:e,timeoutMs:void 0})}return{currentOffsetMs:s,detach:l,start:i,takeChunk:a}}function Fo({cdpSession:e,page:t}){let r=[],n=[],o=[],i=[],s=[];return xu(t,r,n),Eu(t,i),Cu(t,o,s),{consoleEntries:r,lifecycle:i,network:o,pageErrors:n,capturePerf:()=>$u(e),drain:async()=>{await Promise.allSettled(s)}}}function xu(e,t,r){e.on("console",n=>{t.push({text:n.text(),timestamp:Date.now(),type:n.type(),url:n.location().url})}),e.on("pageerror",n=>{r.push({message:n.message,stack:n.stack,timestamp:Date.now()})})}function Eu(e,t){e.on("crash",()=>{t.push({detail:"page crashed",kind:"crash",timestamp:Date.now()})}),e.on("dialog",r=>{t.push({detail:`${r.type()}: ${r.message()}`,kind:"dialog",timestamp:Date.now()})}),e.on("framenavigated",r=>{r===e.mainFrame()&&t.push({detail:r.url(),kind:"navigation",timestamp:Date.now()})}),e.on("popup",r=>{t.push({detail:r.url(),kind:"popup",timestamp:Date.now()})}),e.on("download",r=>{t.push({detail:r.url(),kind:"download",timestamp:Date.now()})}),e.on("worker",r=>{t.push({detail:r.url(),kind:"worker",timestamp:Date.now()})})}function Cu(e,t,r){e.on("response",n=>{let o=n.request();if(!Lo.has(o.resourceType()))return;let i=_o(o,n),s=t.push(i)-1;r.push(Tu({idx:s,network:t,req:o,res:n}))}),e.on("requestfailed",n=>{Lo.has(n.resourceType())&&t.push({..._o(n),failure:n.failure()?.errorText})})}var Lo=new Set(["fetch","xhr"]);function _o(e,t){return{failure:void 0,method:e.method(),requestBody:e.postData()??void 0,requestHeaders:void 0,resourceType:e.resourceType(),responseBody:void 0,responseBodyError:void 0,responseHeaders:void 0,status:t?.status(),statusText:t?.statusText(),timestamp:Date.now(),url:e.url()}}async function Tu({idx:e,network:t,req:r,res:n}){let[o,i,s]=await Promise.all([Uo(r.allHeaders()),Uo(n.allHeaders()),Au(n)]),a=t[e];a!=null&&(t[e]={...a,requestHeaders:o,responseBody:s.text,responseBodyError:s.error,responseHeaders:i})}async function Uo(e){try{return await e}catch{return}}var Vo=1500;async function Au(e){try{return{error:void 0,text:(await Promise.race([e.body(),new Promise((r,n)=>setTimeout(()=>{n(new Error(`body read timed out after ${String(Vo)}ms`))},Vo))])).toString("utf8")}}catch(t){return{error:t instanceof Error?t.message:String(t),text:void 0}}}var Iu=`(() => {
111
+ `);await Promise.all([q(M.join(o,"error.txt"),i),q(M.join(o,"summary.txt"),s),q(M.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 ku}from"fs";import{createRequire as Pu}from"module";import _o from"path";import{gzipSync as Ru}from"zlib";var xu=Pu(import.meta.url),Eu=xu.resolve("rrweb"),Cu=_o.join(_o.dirname(Eu),"rrweb.umd.min.cjs"),Tu=ku(Cu,"utf8"),Au=[";(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(`
112
+ `),Iu=Tu+`
113
+ `+Au;async function Uo({cdpSession:e,page:t}){let r,n=0;async function o(){await t.addScriptTag({content:Iu})}await o(),t.on("load",()=>{o().catch(c=>{let u=c instanceof Error?c.message:String(c);f.warn("rrweb re-injection on navigation failed: %s",u)})});async function i(){await se({awaitPromise:!1,expression:"globalThis.__ripploRrwebStart && globalThis.__ripploRrwebStart()",label:"rrweb start",session:e,timeoutMs:void 0});let c=await se({awaitPromise:!1,expression:"globalThis.__ripploRrwebStartedAt",label:"rrweb startedAt",session:e,timeoutMs:void 0});typeof c=="number"&&(r??=c)}function s(){if(r!=null)return Date.now()-r}async function a(){let c=await se({awaitPromise:!1,expression:"globalThis.__ripploRrwebDrain ? globalThis.__ripploRrwebDrain() : []",label:"rrweb drain",session:e,timeoutMs:void 0})??[],u=c[0],m=c.at(-1);if(u==null||m==null)return;r??=u.timestamp;let g=r,R=c.map(H=>JSON.stringify(H)).join(`
114
+ `),y={body:Ru(Buffer.from(R,"utf8")),chunkIndex:n,endTimestamp:m.timestamp-g,eventCount:c.length,startTimestamp:u.timestamp-g};return n+=1,y}async function l(){await se({awaitPromise:!1,expression:"globalThis.__ripploRrwebStop && globalThis.__ripploRrwebStop()",label:"rrweb stop",session:e,timeoutMs:void 0})}return{currentOffsetMs:s,detach:l,start:i,takeChunk:a}}function Bo({cdpSession:e,page:t}){let r=[],n=[],o=[],i=[],s=[];return $u(t,r,n),ju(t,i),Nu(t,o,s),{consoleEntries:r,lifecycle:i,network:o,pageErrors:n,capturePerf:()=>_u(e),drain:async()=>{await Promise.allSettled(s)}}}function $u(e,t,r){e.on("console",n=>{t.push({text:n.text(),timestamp:Date.now(),type:n.type(),url:n.location().url})}),e.on("pageerror",n=>{r.push({message:n.message,stack:n.stack,timestamp:Date.now()})})}function ju(e,t){e.on("crash",()=>{t.push({detail:"page crashed",kind:"crash",timestamp:Date.now()})}),e.on("dialog",r=>{t.push({detail:`${r.type()}: ${r.message()}`,kind:"dialog",timestamp:Date.now()})}),e.on("framenavigated",r=>{r===e.mainFrame()&&t.push({detail:r.url(),kind:"navigation",timestamp:Date.now()})}),e.on("popup",r=>{t.push({detail:r.url(),kind:"popup",timestamp:Date.now()})}),e.on("download",r=>{t.push({detail:r.url(),kind:"download",timestamp:Date.now()})}),e.on("worker",r=>{t.push({detail:r.url(),kind:"worker",timestamp:Date.now()})})}function Nu(e,t,r){e.on("response",n=>{let o=n.request();if(!Vo.has(o.resourceType()))return;let i=Fo(o,n),s=t.push(i)-1;r.push(Du({idx:s,network:t,req:o,res:n}))}),e.on("requestfailed",n=>{Vo.has(n.resourceType())&&t.push({...Fo(n),failure:n.failure()?.errorText})})}var Vo=new Set(["fetch","xhr"]);function Fo(e,t){return{failure:void 0,method:e.method(),requestBody:e.postData()??void 0,requestHeaders:void 0,resourceType:e.resourceType(),responseBody:void 0,responseBodyError:void 0,responseHeaders:void 0,status:t?.status(),statusText:t?.statusText(),timestamp:Date.now(),url:e.url()}}async function Du({idx:e,network:t,req:r,res:n}){let[o,i,s]=await Promise.all([Mo(r.allHeaders()),Mo(n.allHeaders()),Ou(n)]),a=t[e];a!=null&&(t[e]={...a,requestHeaders:o,responseBody:s.text,responseBodyError:s.error,responseHeaders:i})}async function Mo(e){try{return await e}catch{return}}var Ho=1500;async function Ou(e){try{return{error:void 0,text:(await Promise.race([e.body(),new Promise((r,n)=>setTimeout(()=>{n(new Error(`body read timed out after ${String(Ho)}ms`))},Ho))])).toString("utf8")}}catch(t){return{error:t instanceof Error?t.message:String(t),text:void 0}}}var Lu=`(() => {
115
115
  const toJSON = (e) => e.toJSON();
116
116
  const m = performance.memory;
117
117
  const memory = m == null ? null : {
@@ -125,39 +125,39 @@ ${r}`].join(`
125
125
  paint: performance.getEntriesByType("paint").map(toJSON),
126
126
  resource: performance.getEntriesByType("resource").map(toJSON),
127
127
  };
128
- })()`;async function $u(e){try{return await se({awaitPromise:!1,expression:Iu,label:"capturePerf",session:e,timeoutMs:void 0})}catch(t){let r=t instanceof Error?t.message:String(t);f.warn("capturePerf failed: %s",r);return}}import{z as oe}from"zod";import Mo from"crypto";import{Webhook as ju}from"standardwebhooks";function Se({body:e,secret:t}){let r=new ju(t),n=`msg_${Mo.randomUUID()}`,o=new Date,i=r.sign(n,o,e),s=Math.floor(o.getTime()/1e3);return{"webhook-id":n,"webhook-signature":i,"webhook-timestamp":String(s)}}function zr(){return`whsec_${Mo.randomBytes(24).toString("base64")}`}var Nu=15e4,Du={async:{backoffMs:[500,1e3,2e3,5e3],timeoutMs:12e4},fast:{backoffMs:[100,250,500,1e3],timeoutMs:5e3},slow:{backoffMs:[250,500,1e3,2e3],timeoutMs:3e4}},Ou=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()})]),Lu=oe.object({error:oe.string().optional(),outcome:Ou.optional(),success:oe.boolean()});async function Ho({apiUrl:e,budget:t,observer:r,params:n,webhookSecret:o}){let i=Du[t],s=performance.now(),a={lastReason:void 0,pollCount:0};for(;performance.now()-s<i.timeoutMs;){a.pollCount+=1;let l=await Uu({apiUrl:e,observer:r,params:n,webhookSecret:o}),c=_u({observer:r,outcome:l,start:s,state:a});if(c!=null)return c;let u=i.timeoutMs-(performance.now()-s);if(u<=0)break;let m=Math.min(Vu({backoff:i.backoffMs,pollCount:a.pollCount}),u);await Fu(m)}return{description:`observer "${r}"`,detail:`budget "${t}" exhausted after ${String(a.pollCount)} poll(s) (${Bo(s)}); last: ${a.lastReason??"no retry reason"}
129
- \u2192 /ripplo:debug \u2014 check .ripplo/debug/<runId>/ artifacts`,status:"failed"}}function _u({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}
130
- 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 (${Bo(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.
131
- Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=t.reason,null)}async function Uu({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",...Se({body:o,secret:n})},method:"PUT",signal:AbortSignal.timeout(Nu)});if(!i.ok){let l=await i.text().catch(()=>"");return{kind:"transport-error",reason:`status ${String(i.status)}: ${l.slice(0,200)}`}}let s=await i.json(),a=Lu.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 Vu({backoff:e,pollCount:t}){let r=Math.min(t-1,e.length-1);return e[r]??1e3}function Bo(e){return`${String(Math.round(performance.now()-e))}ms`}async function Fu(e){return new Promise(t=>setTimeout(t,e))}var Ht=15e3;async function Gr({failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,spec:i,variables:s}){let a=performance.now();return Hu({currentId:i.entryNode,failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,runStartTime:a,spec:i,variables:s})}function Mu({onStep:e,steps:t,target:r}){t.forEach(n=>{let o={...n,stepIndex:r.length};r.push(o),e?.(o)})}async function Hu({currentId:e,failFast:t,getRecordingOffsetMs:r,observerTransport:n,onStep:o,page:i,runStartTime:s,spec:a,variables:l}){let c=[],u=l,m=e;for(;m!=null;){let g=a.nodes[m];if(g==null)throw new Error(`Node "${m}" not found in spec`);let R=m,$=Ft(g);f.info("Executing node: %s [%s]",$,g.type);let y=await Bu({getRecordingOffsetMs:r,node:g,nodeId:R,observerTransport:n,page:i,runStartTime:s,variables:u});if(Mu({onStep:o,steps:[y],target:c}),u=y.variables,t&&y.status==="failed")break;m=g.next}return{steps:c,variables:u}}async function Bu({getRecordingOffsetMs:e,node:t,nodeId:r,observerTransport:n,page:o,runStartTime:i,variables:s}){let a=performance.now(),l=e?.(),c=Ft(t),u=Ht;try{let m=await Wu({node:t,observerTransport:n,page:o,timeout:u,variables:s}),g=Math.round(performance.now()-a),R=m.assertions.some(y=>y.status==="failed"),$=e?.();return{assertions:m.assertions,detail:void 0,duration:g,nodeId:r,nodeType:t.type,recordingEndMs:$,recordingStartMs:l,snapshotTimestamp:Math.round(performance.now()-i),status:R?"failed":"passed",stepIndex:0,title:c,url:o.url(),variables:m.variables}}catch(m){let g=Math.round(performance.now()-a),R=m instanceof Error?m.message:String(m),$=e?.();return{assertions:[],detail:R,duration:g,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 Wu({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(qu(e)){let s=await Er({node:e,page:r,timeout:n,variables:o});return{assertions:[],variables:s.variables}}return{assertions:await Gu({node:e,observerTransport:t,page:r,timeout:n,variables:o}),variables:o}}function qu(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 zu(e){return e.type.startsWith("assert")}async function Gu({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(!zu(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 Ju({assertNode:i,page:r,timeout:n,variables:o});case"assertText":{let s=Y({ref:i.expected,variables:o});return[await Cr({expected:s,locator:F({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertUrl":{let s=Y({ref:i.expected,variables:o});return[await Tr({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertTitle":{let s=Y({ref:i.expected,variables:o});return[await Zn({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertCount":{let s=xr({ref:i.expected,variables:o});return[await Ar({expected:s,locator:F({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertValue":{let s=Y({ref:i.expected,variables:o});return[await Ir({expected:s,locator:F({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertAttribute":{let s=Y({ref:i.expected,variables:o});return[await eo({attribute:i.attribute,expected:s,locator:F({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]=Et({ref:l,variables:o})}),[await Ho({apiUrl:t.apiUrl,budget:i.budget,observer:i.observer,params:s,webhookSecret:t.webhookSecret})]}}}var Ku={assertChecked:no,assertDisabled:ro,assertEnabled:to,assertFocused:io,assertNotChecked:oo,assertNotFocused:so,assertNotVisible:jr,assertVisible:$r};async function Ju({assertNode:e,page:t,timeout:r,variables:n}){let o=Ku[e.type];return[await o({locator:F({locator:e.locator,page:t,variables:n}),timeout:r})]}var Xu=5e3,Yu=2e3;async function Kr({abort:e,baseUrl:t,browser:r,cookies:n,extraVariables:o,observerTransport:i,onRecordingChunk:s,onStep:a,runId:l,spec:c}){let u=await r.newContext({baseURL:t});e.attachContext(u),u.setDefaultTimeout(Ht),u.setDefaultNavigationTimeout(Ht),n.length>0&&await u.addCookies(n);let m=await u.newPage(),g=await u.newCDPSession(m),R=Fo({cdpSession:g,page:m}),$=await Oo({cdpSession:g,page:m});async function y(){let O=await $.takeChunk();O!=null&&s?.(O)}let H=setInterval(()=>{y().catch(O=>{let J=O instanceof Error?O.message:String(O);f.warn("rrweb chunk flush failed: %s",J)})},2e3),E=[],B=!1;function Ie(O){a?.(O),B||(B=!0,$.start().catch(J=>{let z=J instanceof Error?J.message:String(J);f.warn("rrweb recorder start failed: %s",z)})),y().catch(J=>{let z=J instanceof Error?J.message:String(J);f.warn("rrweb step-boundary flush failed: %s",z)}),E.push($o({cdpSession:g,context:u,page:m,runId:l,stepIndex:O.stepIndex,stepResult:O}))}let De=Zu(o,c.variableNamespaces),pe={...Rr({defs:c.variables}),...De};try{let O=await Gr({failFast:!0,getRecordingOffsetMs:$.currentOffsetMs,observerTransport:i,onStep:Ie,page:m,spec:c,variables:pe});clearInterval(H);let J=O.steps.filter(ot=>ot.status==="passed").length,z=O.steps.filter(ot=>ot.status==="failed").length,va={duration:O.steps.reduce((ot,Sa)=>ot+Sa.duration,0),failCount:z,passCount:J,runId:l,status:z>0?"failed":"passed",workflowName:""};return await Qu({debugCaptures:E,flushRecording:y,pageEvents:R,recorder:$,runId:l,steps:O.steps,summary:va}),O.steps}finally{clearInterval(H),await j({label:"cdpSession.detach",fn:()=>g.detach().catch(()=>{})}),await j({label:"context.close",fn:()=>me(u.close(),Yu,"context.close").catch(O=>{let J=O instanceof Error?O.message:String(O);f.warn("Context close failed: %s",J)})})}}async function Qu({debugCaptures:e,flushRecording:t,pageEvents:r,recorder:n,runId:o,steps:i,summary:s}){await j({label:"post-run cleanup",fn:()=>me(Promise.allSettled([j({label:"debugCaptures",fn:()=>Promise.allSettled(e)}),j({label:"writeRunDebugSummary",fn:()=>jo({pageEvents:r,runId:o,steps:i,summary:s})}),j({label:"recorder detach+flush",fn:()=>n.detach().then(t).catch(a=>{let l=a instanceof Error?a.message:String(a);f.warn("Recorder detach failed: %s",l)})})]),Xu,"post-run cleanup").catch(a=>{let l=a instanceof Error?a.message:String(a);f.warn("Post-run cleanup did not finish in budget: %s",l)})})}function Zu(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}var Yr=vr(At(),1);import{z as S}from"zod";var ed=S.union([S.string(),S.number(),S.boolean()]),td=S.record(S.string(),S.record(S.string(),ed)),rd=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()}),nd=S.discriminatedUnion("ok",[S.object({cookies:S.array(rd),data:td,executed:S.array(S.string()),ok:S.literal(!0),runId:S.string()}),S.object({error:S.string(),ok:S.literal(!1),runId:S.string()})]),od=S.object({results:S.array(nd)}),id=S.object({results:S.array(S.object({error:S.string().optional(),ok:S.boolean(),runId:S.string()}))}),Wo=3e4;async function Qr({apiUrl:e,data:t,executed:r,runId:n,webhookSecret:o}){if(r.length!==0)try{await cd({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 Bt({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:[]}:sd({apiUrl:o,preconditionNames:t,runId:r,webhookSecret:n})}async function sd({apiUrl:e,preconditionNames:t,runId:r,webhookSecret:n}){return{...await ad({apiUrl:e,webhookSecret:n}).load({preconditionNames:t,runId:r}),apiUrl:e}}function Zr(){Jr.clear(),Xr.clear()}var Jr=new Map;function ad({apiUrl:e,webhookSecret:t}){let r=`${e}::${t}`,n=Jr.get(r);if(n!=null)return n;let o=new Yr.default(i=>ld({apiUrl:e,keys:i,webhookSecret:t}),{cache:!1,batchScheduleFn:i=>{setTimeout(i,100)},cacheKeyFn:i=>i.runId});return Jr.set(r,o),o}async function ld({apiUrl:e,keys:t,webhookSecret:r}){let n=performance.now(),o=JSON.stringify({batch:t.map(u=>({preconditions:[...u.preconditionNames],runId:u.runId}))}),i=await fetch(`${e}/execute-preconditions`,{body:o,headers:{"Content-Type":"application/json",...Se({body:o,secret:r})},method:"PUT",signal:AbortSignal.timeout(Wo)});if(!i.ok){let u=await pd(i),m=new Error(`execute-preconditions returned ${String(i.status)}: ${u}`);return t.map(()=>m)}let s=await i.json(),a=od.safeParse(s);if(!a.success){let u=new Error(`execute-preconditions response has invalid shape: ${a.error.message}`);return t.map(()=>u)}let l=new URL(e).hostname,c=new Map(a.data.results.map(u=>[u.runId,u]));return f.debug({batchSize:t.length,elapsedMs:Math.round(performance.now()-n),op:"execute-preconditions"},"batched op flushed"),t.map(u=>{let m=c.get(u.runId);return m==null?new Error(`execute-preconditions response missing runId ${u.runId}`):m.ok?(f.info("Preconditions resolved: %s",m.executed.join(", ")),{cookies:m.cookies.map(g=>gd({cookie:g,domain:l})),data:m.data,executed:m.executed}):new Error(`Precondition batch failed: ${m.error}`)})}var Xr=new Map;function cd({apiUrl:e,webhookSecret:t}){let r=`${e}::${t}`,n=Xr.get(r);if(n!=null)return n;let o=new Yr.default(i=>ud({apiUrl:e,keys:i,webhookSecret:t}),{cache:!1,batchScheduleFn:i=>{setTimeout(i,100)},cacheKeyFn:i=>i.runId});return Xr.set(r,o),o}async function ud({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",...Se({body:n,secret:r})},method:"PUT",signal:AbortSignal.timeout(Wo)});if(!o.ok){let l=new Error(`teardown-preconditions returned ${String(o.status)}`);return t.map(()=>l)}let i=await o.json(),s=id.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 dd=S.object({error:S.string()});async function pd(e){let t=await e.text().catch(()=>"");if(t.length===0)return"no body";let r=md(t),n=r==null?null:dd.safeParse(r);return n!=null&&n.success?n.data.error:t.slice(0,500)}function md(e){try{return JSON.parse(e)}catch{return null}}var fd={lax:"Lax",none:"None",strict:"Strict"};function gd({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=fd[e.sameSite]??"Lax"),e.expires!=null&&(r.expires=e.expires),r}var ut=vr(At(),1);import{graphql as Me}from"gql.tada";async function tn({config:e,runId:t}){let r=yd(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(u=>{f.error(u,"submitRunSteps failed")})}function s(c){o(bd({chunk:c,config:e,runId:t})).catch(u=>{f.error(u,"submitRunRecordingChunk failed")})}async function a(){for(;n.length>0;){let c=n.splice(0);await Promise.all(c)}}async function l({flush:c,statusOverride:u,steps:m,summary:g}){c&&await j({label:"flushSteps",fn:()=>a()});let R=m.filter(E=>E.status==="passed").length,$=m.filter(E=>E.status==="failed").length,y=m.reduce((E,B)=>E+B.duration,0),H=u??($>0?"failed":"passed");await j({label:"completeRun",fn:()=>r.complete.load({duration:y,failCount:$,passCount:R,runId:t,status:H,summary:g??null,warnCount:0})})}return{complete:l,enqueueRecordingChunk:s,enqueueStep:i,flushSteps:a,runId:t}}async function rn({config:e,reason:t,runId:r}){await h({config:e,document:Sd,variables:{reason:t,runId:r}})}var qo=new Map,en=new Set;async function nn(){await Promise.allSettled(en)}function zo(e){en.add(e),e.finally(()=>{en.delete(e)})}function yd(e){let t=`${e.ripploServerUrl}::${e.token}`,r=qo.get(t);if(r!=null)return r;let n={artifactsUploaded:new ut.default(async o=>(await Wt({config:e,document:vd,opName:"markRunArtifactsUploadedBatch",size:o.length,variables:{runIds:[...o]}}),o.map(()=>!0)),{cache:!1}),complete:new ut.default(async o=>(await Wt({config:e,document:xd,opName:"completeRunsBatch",size:o.length,variables:{items:[...o]}}),o.map(()=>!0)),{cache:!1}),start:new ut.default(async o=>(await Wt({config:e,document:kd,opName:"startRunsBatch",size:o.length,variables:{runIds:[...o]}}),o.map(()=>!0)),{cache:!1,batchScheduleFn:o=>{setTimeout(o,100)}}),steps:new ut.default(async o=>(await Wt({config:e,document:Pd,opName:"submitRunStepsBatch",size:o.length,variables:{items:hd(o)}}),o.map(()=>!0)),{cache:!1,batchScheduleFn:o=>{setTimeout(o,100)}})};return qo.set(t,n),n}async function Wt({config:e,document:t,opName:r,size:n,variables:o}){let i=performance.now();await h({config:e,document:t,variables:o}),f.debug({batchSize:n,elapsedMs:Math.round(performance.now()-i),op:r},"batched op flushed")}function hd(e){let t=new Map;return e.forEach(({runId:r,step:n})=>{let o=wd(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 wd(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 bd({chunk:e,config:t,runId:r}){await h({config:t,document:Rd,variables:{input:{bodyBase64:e.body.toString("base64"),chunkIndex:e.chunkIndex,endTimestamp:e.endTimestamp,eventCount:e.eventCount,runId:r,startTimestamp:e.startTimestamp}}})}var vd=Me(`
128
+ })()`;async function _u(e){try{return await se({awaitPromise:!1,expression:Lu,label:"capturePerf",session:e,timeoutMs:void 0})}catch(t){let r=t instanceof Error?t.message:String(t);f.warn("capturePerf failed: %s",r);return}}import{z as oe}from"zod";import Wo from"crypto";import{Webhook as Uu}from"standardwebhooks";function Se({body:e,secret:t}){let r=new Uu(t),n=`msg_${Wo.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 Kr(){return`whsec_${Wo.randomBytes(24).toString("base64")}`}var Vu=15e4,Fu={async:{backoffMs:[500,1e3,2e3,5e3],timeoutMs:12e4},fast:{backoffMs:[100,250,500,1e3],timeoutMs:5e3},slow:{backoffMs:[250,500,1e3,2e3],timeoutMs:3e4}},Mu=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()})]),Hu=oe.object({error:oe.string().optional(),outcome:Mu.optional(),success:oe.boolean()});async function qo({apiUrl:e,budget:t,observer:r,params:n,webhookSecret:o}){let i=Fu[t],s=performance.now(),a={lastReason:void 0,pollCount:0};for(;performance.now()-s<i.timeoutMs;){a.pollCount+=1;let l=await Wu({apiUrl:e,observer:r,params:n,webhookSecret:o}),c=Bu({observer:r,outcome:l,start:s,state:a});if(c!=null)return c;let u=i.timeoutMs-(performance.now()-s);if(u<=0)break;let m=Math.min(qu({backoff:i.backoffMs,pollCount:a.pollCount}),u);await zu(m)}return{description:`observer "${r}"`,detail:`budget "${t}" exhausted after ${String(a.pollCount)} poll(s) (${zo(s)}); last: ${a.lastReason??"no retry reason"}
129
+ \u2192 /ripplo:debug \u2014 check .ripplo/debug/<runId>/ artifacts`,status:"failed"}}function Bu({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}
130
+ 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 (${zo(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.
131
+ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=t.reason,null)}async function Wu({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",...Se({body:o,secret:n})},method:"PUT",signal:AbortSignal.timeout(Vu)});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=Hu.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 qu({backoff:e,pollCount:t}){let r=Math.min(t-1,e.length-1);return e[r]??1e3}function zo(e){return`${String(Math.round(performance.now()-e))}ms`}async function zu(e){return new Promise(t=>setTimeout(t,e))}var Wt=15e3;async function Jr({failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,spec:i,variables:s}){let a=performance.now();return Ku({currentId:i.entryNode,failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,runStartTime:a,spec:i,variables:s})}function Gu({onStep:e,steps:t,target:r}){t.forEach(n=>{let o={...n,stepIndex:r.length};r.push(o),e?.(o)})}async function Ku({currentId:e,failFast:t,getRecordingOffsetMs:r,observerTransport:n,onStep:o,page:i,runStartTime:s,spec:a,variables:l}){let c=[],u=l,m=e;for(;m!=null;){let g=a.nodes[m];if(g==null)throw new Error(`Node "${m}" not found in spec`);let R=m,$=Ht(g);f.info("Executing node: %s [%s]",$,g.type);let y=await Ju({getRecordingOffsetMs:r,node:g,nodeId:R,observerTransport:n,page:i,runStartTime:s,variables:u});if(Gu({onStep:o,steps:[y],target:c}),u=y.variables,t&&y.status==="failed")break;m=g.next}return{steps:c,variables:u}}async function Ju({getRecordingOffsetMs:e,node:t,nodeId:r,observerTransport:n,page:o,runStartTime:i,variables:s}){let a=performance.now(),l=e?.(),c=Ht(t),u=Wt;try{let m=await Xu({node:t,observerTransport:n,page:o,timeout:u,variables:s}),g=Math.round(performance.now()-a),R=m.assertions.some(y=>y.status==="failed"),$=e?.();return{assertions:m.assertions,detail:void 0,duration:g,nodeId:r,nodeType:t.type,recordingEndMs:$,recordingStartMs:l,snapshotTimestamp:Math.round(performance.now()-i),status:R?"failed":"passed",stepIndex:0,title:c,url:o.url(),variables:m.variables}}catch(m){let g=Math.round(performance.now()-a),R=m instanceof Error?m.message:String(m),$=e?.();return{assertions:[],detail:R,duration:g,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 Xu({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(Yu(e)){let s=await Tr({node:e,page:r,timeout:n,variables:o});return{assertions:[],variables:s.variables}}return{assertions:await Zu({node:e,observerTransport:t,page:r,timeout:n,variables:o}),variables:o}}function Yu(e){return["goto","click","dblclick","fill","select","hover","press","check","uncheck","clear","rightClick","handleDialog","clipboard","setPermission","setViewport","fail","setVariable","extractText","upload","drag","scrollIntoView","type","focus"].includes(e.type)}function Qu(e){return e.type.startsWith("assert")}async function Zu({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(!Qu(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 td({assertNode:i,page:r,timeout:n,variables:o});case"assertText":{let s=Y({ref:i.expected,variables:o});return[await Ar({expected:s,locator:F({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertUrl":{let s=Y({ref:i.expected,variables:o});return[await Ir({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertTitle":{let s=Y({ref:i.expected,variables:o});return[await ro({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertCount":{let s=Cr({ref:i.expected,variables:o});return[await $r({expected:s,locator:F({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertValue":{let s=Y({ref:i.expected,variables:o});return[await jr({expected:s,locator:F({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertAttribute":{let s=Y({ref:i.expected,variables:o});return[await no({attribute:i.attribute,expected:s,locator:F({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]=Tt({ref:l,variables:o})}),[await qo({apiUrl:t.apiUrl,budget:i.budget,observer:i.observer,params:s,webhookSecret:t.webhookSecret})]}}}var ed={assertChecked:so,assertDisabled:io,assertEnabled:oo,assertFocused:lo,assertNotChecked:ao,assertNotFocused:co,assertNotVisible:Dr,assertVisible:Nr};async function td({assertNode:e,page:t,timeout:r,variables:n}){let o=ed[e.type];return[await o({locator:F({locator:e.locator,page:t,variables:n}),timeout:r})]}var rd=5e3,nd=2e3;async function Xr({abort:e,baseUrl:t,browser:r,cookies:n,extraVariables:o,observerTransport:i,onRecordingChunk:s,onStep:a,runId:l,spec:c}){let u=await r.newContext({baseURL:t});e.attachContext(u),u.setDefaultTimeout(Wt),u.setDefaultNavigationTimeout(Wt),n.length>0&&await u.addCookies(n);let m=await u.newPage(),g=await u.newCDPSession(m),R=Bo({cdpSession:g,page:m}),$=await Uo({cdpSession:g,page:m});async function y(){let O=await $.takeChunk();O!=null&&s?.(O)}let H=setInterval(()=>{y().catch(O=>{let J=O instanceof Error?O.message:String(O);f.warn("rrweb chunk flush failed: %s",J)})},2e3),E=[],B=!1;function Ie(O){a?.(O),B||(B=!0,$.start().catch(J=>{let z=J instanceof Error?J.message:String(J);f.warn("rrweb recorder start failed: %s",z)})),y().catch(J=>{let z=J instanceof Error?J.message:String(J);f.warn("rrweb step-boundary flush failed: %s",z)}),E.push(Do({cdpSession:g,context:u,page:m,runId:l,stepIndex:O.stepIndex,stepResult:O}))}let De=id(o,c.variableNamespaces),pe={...Er({defs:c.variables}),...De};try{let O=await Jr({failFast:!0,getRecordingOffsetMs:$.currentOffsetMs,observerTransport:i,onStep:Ie,page:m,spec:c,variables:pe});clearInterval(H);let J=O.steps.filter(it=>it.status==="passed").length,z=O.steps.filter(it=>it.status==="failed").length,Ea={duration:O.steps.reduce((it,Ca)=>it+Ca.duration,0),failCount:z,passCount:J,runId:l,status:z>0?"failed":"passed",workflowName:""};return await od({debugCaptures:E,flushRecording:y,pageEvents:R,recorder:$,runId:l,steps:O.steps,summary:Ea}),O.steps}finally{clearInterval(H),await j({label:"cdpSession.detach",fn:()=>g.detach().catch(()=>{})}),await j({label:"context.close",fn:()=>me(u.close(),nd,"context.close").catch(O=>{let J=O instanceof Error?O.message:String(O);f.warn("Context close failed: %s",J)})})}}async function od({debugCaptures:e,flushRecording:t,pageEvents:r,recorder:n,runId:o,steps:i,summary:s}){await j({label:"post-run cleanup",fn:()=>me(Promise.allSettled([j({label:"debugCaptures",fn:()=>Promise.allSettled(e)}),j({label:"writeRunDebugSummary",fn:()=>Oo({pageEvents:r,runId:o,steps:i,summary:s})}),j({label:"recorder detach+flush",fn:()=>n.detach().then(t).catch(a=>{let l=a instanceof Error?a.message:String(a);f.warn("Recorder detach failed: %s",l)})})]),rd,"post-run cleanup").catch(a=>{let l=a instanceof Error?a.message:String(a);f.warn("Post-run cleanup did not finish in budget: %s",l)})})}function id(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}var Zr=kr($t(),1);import{z as S}from"zod";var sd=S.union([S.string(),S.number(),S.boolean()]),ad=S.record(S.string(),S.record(S.string(),sd)),ld=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()}),cd=S.discriminatedUnion("ok",[S.object({cookies:S.array(ld),data:ad,executed:S.array(S.string()),ok:S.literal(!0),runId:S.string()}),S.object({error:S.string(),ok:S.literal(!1),runId:S.string()})]),ud=S.object({results:S.array(cd)}),dd=S.object({results:S.array(S.object({error:S.string().optional(),ok:S.boolean(),runId:S.string()}))}),Go=3e4;async function en({apiUrl:e,data:t,executed:r,runId:n,webhookSecret:o}){if(r.length!==0)try{await gd({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 qt({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:[]}:pd({apiUrl:o,preconditionNames:t,runId:r,webhookSecret:n})}async function pd({apiUrl:e,preconditionNames:t,runId:r,webhookSecret:n}){return{...await md({apiUrl:e,webhookSecret:n}).load({preconditionNames:t,runId:r}),apiUrl:e}}function tn(){Yr.clear(),Qr.clear()}var Yr=new Map;function md({apiUrl:e,webhookSecret:t}){let r=`${e}::${t}`,n=Yr.get(r);if(n!=null)return n;let o=new Zr.default(i=>fd({apiUrl:e,keys:i,webhookSecret:t}),{cache:!1,batchScheduleFn:i=>{setTimeout(i,100)},cacheKeyFn:i=>i.runId});return Yr.set(r,o),o}async function fd({apiUrl:e,keys:t,webhookSecret:r}){let n=performance.now(),o=JSON.stringify({batch:t.map(u=>({preconditions:[...u.preconditionNames],runId:u.runId}))}),i=await fetch(`${e}/execute-preconditions`,{body:o,headers:{"Content-Type":"application/json",...Se({body:o,secret:r})},method:"PUT",signal:AbortSignal.timeout(Go)});if(!i.ok){let u=await wd(i),m=new Error(`execute-preconditions returned ${String(i.status)}: ${u}`);return t.map(()=>m)}let s=await i.json(),a=ud.safeParse(s);if(!a.success){let u=new Error(`execute-preconditions response has invalid shape: ${a.error.message}`);return t.map(()=>u)}let l=new URL(e).hostname,c=new Map(a.data.results.map(u=>[u.runId,u]));return f.debug({batchSize:t.length,elapsedMs:Math.round(performance.now()-n),op:"execute-preconditions"},"batched op flushed"),t.map(u=>{let m=c.get(u.runId);return m==null?new Error(`execute-preconditions response missing runId ${u.runId}`):m.ok?(f.info("Preconditions resolved: %s",m.executed.join(", ")),{cookies:m.cookies.map(g=>Sd({cookie:g,domain:l})),data:m.data,executed:m.executed}):new Error(`Precondition batch failed: ${m.error}`)})}var Qr=new Map;function gd({apiUrl:e,webhookSecret:t}){let r=`${e}::${t}`,n=Qr.get(r);if(n!=null)return n;let o=new Zr.default(i=>yd({apiUrl:e,keys:i,webhookSecret:t}),{cache:!1,batchScheduleFn:i=>{setTimeout(i,100)},cacheKeyFn:i=>i.runId});return Qr.set(r,o),o}async function yd({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",...Se({body:n,secret:r})},method:"PUT",signal:AbortSignal.timeout(Go)});if(!o.ok){let l=new Error(`teardown-preconditions returned ${String(o.status)}`);return t.map(()=>l)}let i=await o.json(),s=dd.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 hd=S.object({error:S.string()});async function wd(e){let t=await e.text().catch(()=>"");if(t.length===0)return"no body";let r=bd(t),n=r==null?null:hd.safeParse(r);return n!=null&&n.success?n.data.error:t.slice(0,500)}function bd(e){try{return JSON.parse(e)}catch{return null}}var vd={lax:"Lax",none:"None",strict:"Strict"};function Sd({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=vd[e.sameSite]??"Lax"),e.expires!=null&&(r.expires=e.expires),r}var dt=kr($t(),1);import{graphql as Me}from"gql.tada";async function nn({config:e,runId:t}){let r=kd(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(u=>{f.error(u,"submitRunSteps failed")})}function s(c){o(xd({chunk:c,config:e,runId:t})).catch(u=>{f.error(u,"submitRunRecordingChunk failed")})}async function a(){for(;n.length>0;){let c=n.splice(0);await Promise.all(c)}}async function l({flush:c,statusOverride:u,steps:m,summary:g}){c&&await j({label:"flushSteps",fn:()=>a()});let R=m.filter(E=>E.status==="passed").length,$=m.filter(E=>E.status==="failed").length,y=m.reduce((E,B)=>E+B.duration,0),H=u??($>0?"failed":"passed");await j({label:"completeRun",fn:()=>r.complete.load({duration:y,failCount:$,passCount:R,runId:t,status:H,summary:g??null,warnCount:0})})}return{complete:l,enqueueRecordingChunk:s,enqueueStep:i,flushSteps:a,runId:t}}async function on({config:e,reason:t,runId:r}){await h({config:e,document:Cd,variables:{reason:t,runId:r}})}var Ko=new Map,rn=new Set;async function sn(){await Promise.allSettled(rn)}function Jo(e){rn.add(e),e.finally(()=>{rn.delete(e)})}function kd(e){let t=`${e.ripploServerUrl}::${e.token}`,r=Ko.get(t);if(r!=null)return r;let n={artifactsUploaded:new dt.default(async o=>(await zt({config:e,document:Ed,opName:"markRunArtifactsUploadedBatch",size:o.length,variables:{runIds:[...o]}}),o.map(()=>!0)),{cache:!1}),complete:new dt.default(async o=>(await zt({config:e,document:$d,opName:"completeRunsBatch",size:o.length,variables:{items:[...o]}}),o.map(()=>!0)),{cache:!1}),start:new dt.default(async o=>(await zt({config:e,document:Td,opName:"startRunsBatch",size:o.length,variables:{runIds:[...o]}}),o.map(()=>!0)),{cache:!1,batchScheduleFn:o=>{setTimeout(o,100)}}),steps:new dt.default(async o=>(await zt({config:e,document:Ad,opName:"submitRunStepsBatch",size:o.length,variables:{items:Pd(o)}}),o.map(()=>!0)),{cache:!1,batchScheduleFn:o=>{setTimeout(o,100)}})};return Ko.set(t,n),n}async function zt({config:e,document:t,opName:r,size:n,variables:o}){let i=performance.now();await h({config:e,document:t,variables:o}),f.debug({batchSize:n,elapsedMs:Math.round(performance.now()-i),op:r},"batched op flushed")}function Pd(e){let t=new Map;return e.forEach(({runId:r,step:n})=>{let o=Rd(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 Rd(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 xd({chunk:e,config:t,runId:r}){await h({config:t,document:Id,variables:{input:{bodyBase64:e.body.toString("base64"),chunkIndex:e.chunkIndex,endTimestamp:e.endTimestamp,eventCount:e.eventCount,runId:r,startTimestamp:e.startTimestamp}}})}var Ed=Me(`
132
132
  mutation MarkRunArtifactsUploadedBatchCLI($runIds: [String!]!) {
133
133
  markRunArtifactsUploadedBatch(runIds: $runIds)
134
134
  }
135
- `),Sd=Me(`
135
+ `),Cd=Me(`
136
136
  mutation FailRunCLI($runId: String!, $reason: String!) {
137
137
  failRun(runId: $runId, reason: $reason)
138
138
  }
139
- `),kd=Me(`
139
+ `),Td=Me(`
140
140
  mutation StartRunsBatchCLI($runIds: [String!]!) {
141
141
  startRunsBatch(runIds: $runIds) {
142
142
  id
143
143
  }
144
144
  }
145
- `),Pd=Me(`
145
+ `),Ad=Me(`
146
146
  mutation SubmitRunStepsBatchCLI($items: [SubmitRunStepsItem!]!) {
147
147
  submitRunStepsBatch(items: $items)
148
148
  }
149
- `),Rd=Me(`
149
+ `),Id=Me(`
150
150
  mutation SubmitRunRecordingChunkCLI($input: SubmitRunRecordingChunkInput!) {
151
151
  submitRunRecordingChunk(input: $input)
152
152
  }
153
- `),xd=Me(`
153
+ `),$d=Me(`
154
154
  mutation CompleteRunsBatchCLI($items: [CompleteRunItem!]!) {
155
155
  completeRunsBatch(items: $items) {
156
156
  id
157
157
  status
158
158
  }
159
159
  }
160
- `);var Td=12e4,Ad=15e3,Xo=Jo(`
160
+ `);var Dd=12e4,Od=15e3,Zo=Qo(`
161
161
  fragment WorkflowRun on Workflow {
162
162
  id
163
163
  slug
@@ -169,7 +169,7 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
169
169
  preconditionName
170
170
  }
171
171
  }
172
- `),Id=Jo(`
172
+ `),Ld=Qo(`
173
173
  query RunsByIdsWorkflowSpec($ids: [String!]!) {
174
174
  runsByIds(ids: $ids) {
175
175
  id
@@ -182,10 +182,10 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
182
182
  }
183
183
  }
184
184
  }
185
- `,[Xo]);async function on({baseUrl:e,browser:t,config:r,headed:n,preconditionNames:o,runId:i,webhookSecret:s}){let a="unknown",l,c,u=!1,m=Ao(),g=performance.now();try{u=t==null,c=$d({externalBrowser:t,headed:n});let R=o==null?void 0:Bt({engineBaseUrl:r.engineUrl,preconditionNames:o,runId:i,webhookSecret:s}),[{engineBaseUrl:$,workflow:y},H]=await Promise.all([j({label:"Run context resolved",fn:()=>Ud({config:r,runId:i})}),j({label:"Streaming run started",fn:()=>tn({config:r,runId:i})}),Or({appUrl:e})]);a=y.name,l=H;let E=Vd(y.spec);f.info("Executing workflow: %s",y.name),await Hd(Nd({abort:m,baseUrl:e,browserPromise:c,engineBaseUrl:$,preconditionPromise:R,runId:i,specData:E,streaming:l,webhookSecret:s,workflow:y}),Md(),m)}catch(R){throw Bd(R)?R:(await me(jd({browserPromise:c,config:r,error:R,ownsBrowser:u,runId:i,streaming:l,workflowName:a}),Ad,"post-deadline cleanup").catch($=>{let y=$ instanceof Error?$.message:String($);f.warn("Post-deadline cleanup did not finish in budget: %s",y)}),new qt(R))}finally{f.debug({elapsedMs:Math.round(performance.now()-g),runId:i},"run finished (totalMs=%d)",Math.round(performance.now()-g))}}var qt=class extends Error{cause;constructor(t){let r=t instanceof Error?t.message:String(t);super(r),this.name="RunReportedError",this.cause=t}};function $d({externalBrowser:e,headed:t}){return e!=null?Promise.resolve(e):j({label:"Browser launched",fn:()=>Ue({headed:t})})}async function jd({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 No({error:a,runId:o,stack:l,workflowName:s}),i==null?await rn({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 Nd({abort:e,baseUrl:t,browserPromise:r,engineBaseUrl:n,preconditionPromise:o,runId:i,specData:s,streaming:a,webhookSecret:l,workflow:c}){let u=o??Bt({engineBaseUrl:n,preconditionNames:c.preconditions,runId:i,webhookSecret:l}),[m,g]=await Promise.all([u,r]);await Dd({abort:e,baseUrl:t,browser:g,preconditionResult:m,runId:i,specData:s,streaming:a,webhookSecret:l})}async function Dd({abort:e,baseUrl:t,browser:r,preconditionResult:n,runId:o,specData:i,streaming:s,webhookSecret:a}){let l=await j({label:"Spec executed",fn:()=>Kr({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})});_d({preconditionResult:n,runId:o,webhookSecret:a}).catch(g=>{let R=g instanceof Error?g.message:String(g);f.warn("Precondition teardown failed: %s",R)});let c=s.complete({flush:!0,statusOverride:void 0,steps:l,summary:Od(l)}).catch(g=>{let R=g instanceof Error?g.message:String(g);f.warn("streaming.complete failed: %s",R)});zo(c);let u=l.filter(g=>g.status==="passed").length,m=l.filter(g=>g.status==="failed").length;f.info("Run complete: %d passed, %d failed",u,m)}function Od(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 ${Ld(n)}`}function Ld(e){return e.split(`
186
- `,1)[0]??e}async function _d({preconditionResult:e,runId:t,webhookSecret:r}){e.apiUrl!=null&&await Qr({apiUrl:e.apiUrl,data:e.data,executed:e.executed,runId:t,webhookSecret:r})}async function Ud({config:e,runId:t}){let r=await Wd(e).load(t);if(r.workflow==null)throw new Error(`Run ${t} not found`);let n=Cd(Xo,r.workflow),o=r.workflow.project?.engineBaseUrl??"";return{engineBaseUrl:e.engineUrl.length>0?e.engineUrl:o,workflow:n}}function Vd(e){if(e==null)throw new Error("Workflow has no spec");return Br.decode(e)}var Fd=Ed.coerce.number().int().positive().catch(Td);function Md(){return Fd.parse(process.env.RIPPLO_RUN_TIMEOUT_MS)}async function Hd(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 Bd(e){return e instanceof Ve?e.errors.some(t=>t.extensions?.code==="THROTTLED"):!1}var Go=new Map;function Wd(e){let t=`${e.ripploServerUrl}::${e.token}`,r=Go.get(t);if(r!=null)return r;let n=new Ko.default(async o=>{let i=performance.now(),s=await h({config:e,document:Id,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,100)}});return Go.set(t,n),n}import ft from"fs";import je from"fs";import qd from"os";import dt from"path";var zd=".local",Gd=".ripplo";function sn(e){return dt.join(e,".ripplo",zd)}function pt(e){let t=sn(e);je.existsSync(t)||je.mkdirSync(t,{recursive:!0});let r=dt.join(t,".gitignore");return je.existsSync(r)||je.writeFileSync(r,`*
187
- `),t}function mt(e,t){return dt.join(sn(e),t)}function an(){return dt.join(qd.homedir(),Gd)}function ln(){let e=an();return je.existsSync(e)?je.chmodSync(e,448):je.mkdirSync(e,{mode:448,recursive:!0}),e}function ke(e){return dt.join(an(),e)}function ie(){let e=process.env.RIPPLO_TOKEN;if(e!=null&&e.trim().length>0)return e.trim();let t=ke("token");if(!ft.existsSync(t))return null;let r=ft.readFileSync(t,"utf8").trim();return r.length===0?null:r}function cn(e){ln(),ft.writeFileSync(ke("token"),e+`
188
- `,{mode:384})}function un(){let e=ke("token");return ft.existsSync(e)?(ft.unlinkSync(e),!0):!1}import{graphql as gt}from"gql.tada";var Ok=gt(`
185
+ `,[Zo]);async function an({baseUrl:e,browser:t,config:r,headed:n,preconditionNames:o,runId:i,webhookSecret:s}){let a="unknown",l,c,u=!1,m=jo(),g=performance.now();try{u=t==null,c=_d({externalBrowser:t,headed:n});let R=o==null?void 0:qt({engineBaseUrl:r.engineUrl,preconditionNames:o,runId:i,webhookSecret:s}),[{engineBaseUrl:$,workflow:y},H]=await Promise.all([j({label:"Run context resolved",fn:()=>Wd({config:r,runId:i})}),j({label:"Streaming run started",fn:()=>nn({config:r,runId:i})}),_r({appUrl:e})]);a=y.name,l=H;let E=qd(y.spec);f.info("Executing workflow: %s",y.name),await Kd(Vd({abort:m,baseUrl:e,browserPromise:c,engineBaseUrl:$,preconditionPromise:R,runId:i,specData:E,streaming:l,webhookSecret:s,workflow:y}),Gd(),m)}catch(R){throw Jd(R)?R:(await me(Ud({browserPromise:c,config:r,error:R,ownsBrowser:u,runId:i,streaming:l,workflowName:a}),Od,"post-deadline cleanup").catch($=>{let y=$ instanceof Error?$.message:String($);f.warn("Post-deadline cleanup did not finish in budget: %s",y)}),new Gt(R))}finally{f.debug({elapsedMs:Math.round(performance.now()-g),runId:i},"run finished (totalMs=%d)",Math.round(performance.now()-g))}}var Gt=class extends Error{cause;constructor(t){let r=t instanceof Error?t.message:String(t);super(r),this.name="RunReportedError",this.cause=t}};function _d({externalBrowser:e,headed:t}){return e!=null?Promise.resolve(e):j({label:"Browser launched",fn:()=>Ue({headed:t})})}async function Ud({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 Lo({error:a,runId:o,stack:l,workflowName:s}),i==null?await on({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 Vd({abort:e,baseUrl:t,browserPromise:r,engineBaseUrl:n,preconditionPromise:o,runId:i,specData:s,streaming:a,webhookSecret:l,workflow:c}){let u=o??qt({engineBaseUrl:n,preconditionNames:c.preconditions,runId:i,webhookSecret:l}),[m,g]=await Promise.all([u,r]);await Fd({abort:e,baseUrl:t,browser:g,preconditionResult:m,runId:i,specData:s,streaming:a,webhookSecret:l})}async function Fd({abort:e,baseUrl:t,browser:r,preconditionResult:n,runId:o,specData:i,streaming:s,webhookSecret:a}){let l=await j({label:"Spec executed",fn:()=>Xr({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})});Bd({preconditionResult:n,runId:o,webhookSecret:a}).catch(g=>{let R=g instanceof Error?g.message:String(g);f.warn("Precondition teardown failed: %s",R)});let c=s.complete({flush:!0,statusOverride:void 0,steps:l,summary:Md(l)}).catch(g=>{let R=g instanceof Error?g.message:String(g);f.warn("streaming.complete failed: %s",R)});Jo(c);let u=l.filter(g=>g.status==="passed").length,m=l.filter(g=>g.status==="failed").length;f.info("Run complete: %d passed, %d failed",u,m)}function Md(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 ${Hd(n)}`}function Hd(e){return e.split(`
186
+ `,1)[0]??e}async function Bd({preconditionResult:e,runId:t,webhookSecret:r}){e.apiUrl!=null&&await en({apiUrl:e.apiUrl,data:e.data,executed:e.executed,runId:t,webhookSecret:r})}async function Wd({config:e,runId:t}){let r=await Xd(e).load(t);if(r.workflow==null)throw new Error(`Run ${t} not found`);let n=Nd(Zo,r.workflow),o=r.workflow.project?.engineBaseUrl??"";return{engineBaseUrl:e.engineUrl.length>0?e.engineUrl:o,workflow:n}}function qd(e){if(e==null)throw new Error("Workflow has no spec");return qr.decode(e)}var zd=jd.coerce.number().int().positive().catch(Dd);function Gd(){return zd.parse(process.env.RIPPLO_RUN_TIMEOUT_MS)}async function Kd(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 Jd(e){return e instanceof Ve?e.errors.some(t=>t.extensions?.code==="THROTTLED"):!1}var Xo=new Map;function Xd(e){let t=`${e.ripploServerUrl}::${e.token}`,r=Xo.get(t);if(r!=null)return r;let n=new Yo.default(async o=>{let i=performance.now(),s=await h({config:e,document:Ld,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,100)}});return Xo.set(t,n),n}import gt from"fs";import je from"fs";import Yd from"os";import pt from"path";var Qd=".local",Zd=".ripplo";function ln(e){return pt.join(e,".ripplo",Qd)}function mt(e){let t=ln(e);je.existsSync(t)||je.mkdirSync(t,{recursive:!0});let r=pt.join(t,".gitignore");return je.existsSync(r)||je.writeFileSync(r,`*
187
+ `),t}function ft(e,t){return pt.join(ln(e),t)}function cn(){return pt.join(Yd.homedir(),Zd)}function un(){let e=cn();return je.existsSync(e)?je.chmodSync(e,448):je.mkdirSync(e,{mode:448,recursive:!0}),e}function ke(e){return pt.join(cn(),e)}function ie(){let e=process.env.RIPPLO_TOKEN;if(e!=null&&e.trim().length>0)return e.trim();let t=ke("token");if(!gt.existsSync(t))return null;let r=gt.readFileSync(t,"utf8").trim();return r.length===0?null:r}function dn(e){un(),gt.writeFileSync(ke("token"),e+`
188
+ `,{mode:384})}function pn(){let e=ke("token");return gt.existsSync(e)?(gt.unlinkSync(e),!0):!1}import{graphql as yt}from"gql.tada";var qk=yt(`
189
189
  query AgentReviewContextWorker($reviewId: String!) {
190
190
  agentReview(id: $reviewId) {
191
191
  id
@@ -199,11 +199,11 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
199
199
  }
200
200
  }
201
201
  }
202
- `);var Lk=gt(`
202
+ `);var zk=yt(`
203
203
  mutation StartAgentReviewWorker($reviewId: String!) {
204
204
  startAgentReview(reviewId: $reviewId)
205
205
  }
206
- `);var _k=gt(`
206
+ `);var Gk=yt(`
207
207
  mutation CompleteAgentReviewWorker(
208
208
  $reviewId: String!
209
209
  $markdown: String!
@@ -217,17 +217,17 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
217
217
  comments: $comments
218
218
  )
219
219
  }
220
- `);var Uk=gt(`
220
+ `);var Kk=yt(`
221
221
  mutation UpdateAgentReviewProgressWorker($reviewId: String!, $text: String!) {
222
222
  updateAgentReviewProgress(reviewId: $reviewId, text: $text)
223
223
  }
224
- `);var Vk=gt(`
224
+ `);var Jk=yt(`
225
225
  mutation FailAgentReviewWorker($reviewId: String!, $reason: String!) {
226
226
  failAgentReview(reviewId: $reviewId, reason: $reason)
227
227
  }
228
- `);import Zo from"fs";import Kt from"path";import{config as Xd}from"dotenv";import{z as Gt}from"zod";import yt from"fs";import pn from"path";import{z as zt}from"zod";var Yo=pn.join(".ripplo","project.json"),dn=[".env",".env.local"],Kd=zt.object({envFiles:zt.array(zt.string().min(1)).optional(),projectId:zt.string().min(1)});function mn(e){return pn.join(e,Yo)}function fn(e){let t=mn(e);if(!yt.existsSync(t))throw new Error(`ripplo: missing ${Yo}. Run \`ripplo init\` to create it.`);let r=JSON.parse(yt.readFileSync(t,"utf8")),n=Kd.parse(r);return{envFiles:n.envFiles??dn,projectId:n.projectId}}function gn(e){let t=mn(e);if(yt.existsSync(t))try{return fn(e)}catch{return}}function Qo({cwd:e,envFiles:t,projectId:r}){let n=mn(e);yt.mkdirSync(pn.dirname(n),{recursive:!0});let o={projectId:r};t!=null&&!Jd(t)&&(o.envFiles=[...t]),yt.writeFileSync(n,JSON.stringify(o,null,2)+`
229
- `)}function Jd(e){return e.length!==dn.length?!1:e.every((t,r)=>t===dn[r])}function Jt(e){let r=gn(e)?.envFiles??[".env",".env.local"],n=Kt.join(e,".ripplo");r.forEach(o=>{let i=Kt.resolve(n,o);Zo.existsSync(i)&&Xd({override:!0,path:i,quiet:!0})}),yn=void 0}var Yd=Gt.object({RIPPLO_APP_URL:Gt.url(),RIPPLO_ENGINE_URL:Gt.url(),RIPPLO_WEBHOOK_SECRET:Gt.string().min(1)}),yn;function He(){return yn??=Qd(),yn}function Qd(){let e=Yd.safeParse(process.env);if(!e.success){let r=e.error.issues.map(s=>` ${s.path.join(".")}: ${s.message}`).join(`
230
- `),n=hn(process.cwd()),o=n.map(s=>` ${s}`).join(`
228
+ `);import ri from"fs";import Xt from"path";import{config as rp}from"dotenv";import{z as Jt}from"zod";import ht from"fs";import fn from"path";import{z as Kt}from"zod";var ei=fn.join(".ripplo","project.json"),mn=[".env",".env.local"],ep=Kt.object({envFiles:Kt.array(Kt.string().min(1)).optional(),projectId:Kt.string().min(1)});function gn(e){return fn.join(e,ei)}function yn(e){let t=gn(e);if(!ht.existsSync(t))throw new Error(`ripplo: missing ${ei}. Run \`ripplo init\` to create it.`);let r=JSON.parse(ht.readFileSync(t,"utf8")),n=ep.parse(r);return{envFiles:n.envFiles??mn,projectId:n.projectId}}function hn(e){let t=gn(e);if(ht.existsSync(t))try{return yn(e)}catch{return}}function ti({cwd:e,envFiles:t,projectId:r}){let n=gn(e);ht.mkdirSync(fn.dirname(n),{recursive:!0});let o={projectId:r};t!=null&&!tp(t)&&(o.envFiles=[...t]),ht.writeFileSync(n,JSON.stringify(o,null,2)+`
229
+ `)}function tp(e){return e.length!==mn.length?!1:e.every((t,r)=>t===mn[r])}function Yt(e){let r=hn(e)?.envFiles??[".env",".env.local"],n=Xt.join(e,".ripplo");r.forEach(o=>{let i=Xt.resolve(n,o);ri.existsSync(i)&&rp({override:!0,path:i,quiet:!0})}),wn=void 0}var np=Jt.object({RIPPLO_APP_URL:Jt.url(),RIPPLO_ENGINE_URL:Jt.url(),RIPPLO_WEBHOOK_SECRET:Jt.string().min(1)}),wn;function He(){return wn??=op(),wn}function op(){let e=np.safeParse(process.env);if(!e.success){let r=e.error.issues.map(s=>` ${s.path.join(".")}: ${s.message}`).join(`
230
+ `),n=bn(process.cwd()),o=n.map(s=>` ${s}`).join(`
231
231
  `),i=n.length>0?`
232
232
 
233
233
  Declared env file(s) not found at this path:
@@ -235,30 +235,30 @@ ${o}
235
235
  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:
236
236
  ${r}
237
237
 
238
- 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 hn(e){let r=gn(e)?.envFiles??[],n=Kt.join(e,".ripplo");return r.map(o=>Kt.resolve(n,o)).filter(o=>!Zo.existsSync(o))}import eb from"yargs";import{hideBin as tb}from"yargs/helpers";import{graphql as mp}from"gql.tada";import{exec as np}from"child_process";import{createAuthClient as Zd}from"better-auth/client";import{deviceAuthorizationClient as ep}from"better-auth/client/plugins";function ei({baseURL:e}){return Zd({baseURL:e,fetchOptions:{headers:{"User-Agent":"Ripplo CLI"}},plugins:[ep()]})}import{z as wn}from"zod";var tp="https://ripplo.ai";function ee(){return Xt().RIPPLO_SERVER_URL}function ri(){return Xt().RIPPLO_PROJECT_ID}var rp=wn.object({RIPPLO_PROJECT_ID:wn.string().min(1).optional(),RIPPLO_SERVER_URL:wn.string().min(1).default(tp)}),ti;function Xt(){return ti??=rp.parse(process.env),ti}var op=5e3,ni="ripplo-cli";async function oi({onDeviceCode:e,url:t}){let r=t??Xt().RIPPLO_SERVER_URL,n=ei({baseURL:r}),o=await n.device.code({client_id:ni});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}),up(a);let l=await ip({authClient:n,deviceCode:i});return cn(l),l}async function ip({authClient:e,deviceCode:t}){for(;;){await lp(op);let r=await e.device.token({client_id:ni,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(!ap(r.error.error))throw new Error(`Authorization failed: ${r.error.error_description}`)}}var sp=new Set(["authorization_pending","slow_down"]);function ap(e){return sp.has(e)}function lp(e){return new Promise(t=>{setTimeout(t,e)})}function cp(){return process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open"}function up(e){let t=cp();np(`${t} "${e}"`,()=>{})}function Pe({serverUrl:e,token:t}){return{appUrl:"",cwd:process.cwd(),engineUrl:"",projectId:"",ripploServerUrl:e,token:t,webhookSecret:""}}import dp from"fs";import pp from"path";function C(e){return dp.existsSync(pp.join(e,".ripplo"))}var fp=mp(`
238
+ 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 bn(e){let r=hn(e)?.envFiles??[],n=Xt.join(e,".ripplo");return r.map(o=>Xt.resolve(n,o)).filter(o=>!ri.existsSync(o))}import ub from"yargs";import{hideBin as db}from"yargs/helpers";import{graphql as bp}from"gql.tada";import{exec as cp}from"child_process";import{createAuthClient as ip}from"better-auth/client";import{deviceAuthorizationClient as sp}from"better-auth/client/plugins";function ni({baseURL:e}){return ip({baseURL:e,fetchOptions:{headers:{"User-Agent":"Ripplo CLI"}},plugins:[sp()]})}import{z as vn}from"zod";var ap="https://ripplo.ai";function ee(){return Qt().RIPPLO_SERVER_URL}function ii(){return Qt().RIPPLO_PROJECT_ID}var lp=vn.object({RIPPLO_PROJECT_ID:vn.string().min(1).optional(),RIPPLO_SERVER_URL:vn.string().min(1).default(ap)}),oi;function Qt(){return oi??=lp.parse(process.env),oi}var up=5e3,si="ripplo-cli";async function ai({onDeviceCode:e,url:t}){let r=t??Qt().RIPPLO_SERVER_URL,n=ni({baseURL:r}),o=await n.device.code({client_id:si});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}),yp(a);let l=await dp({authClient:n,deviceCode:i});return dn(l),l}async function dp({authClient:e,deviceCode:t}){for(;;){await fp(up);let r=await e.device.token({client_id:si,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(!mp(r.error.error))throw new Error(`Authorization failed: ${r.error.error_description}`)}}var pp=new Set(["authorization_pending","slow_down"]);function mp(e){return pp.has(e)}function fp(e){return new Promise(t=>{setTimeout(t,e)})}function gp(){return process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open"}function yp(e){let t=gp();cp(`${t} "${e}"`,()=>{})}function Pe({serverUrl:e,token:t}){return{appUrl:"",cwd:process.cwd(),engineUrl:"",projectId:"",ripploServerUrl:e,token:t,webhookSecret:""}}import hp from"fs";import wp from"path";function C(e){return hp.existsSync(wp.join(e,".ripplo"))}var vp=bp(`
239
239
  query AuthViewer {
240
240
  currentUser {
241
241
  name
242
242
  email
243
243
  }
244
244
  }
245
- `);async function ii(){let e=ee(),t=ie();if(t!=null){let s=await bn({serverUrl:e,token:t});if(s!=null){process.stdout.write(`Already signed in as ${s.email}. Run \`ripplo auth logout\` to switch.
245
+ `);async function li(){let e=ee(),t=ie();if(t!=null){let s=await Sn({serverUrl:e,token:t});if(s!=null){process.stdout.write(`Already signed in as ${s.email}. Run \`ripplo auth logout\` to switch.
246
246
  `);return}process.stdout.write(`Your saved session expired \u2014 let's sign you back in.
247
247
 
248
- `)}let r=await oi({url:e,onDeviceCode:s=>{process.stdout.write(`Opening your browser to finish sign-in.
248
+ `)}let r=await ai({url:e,onDeviceCode:s=>{process.stdout.write(`Opening your browser to finish sign-in.
249
249
  `),process.stdout.write(`If it didn't open, visit: ${s.verificationUrl}
250
250
  `),process.stdout.write(`Verification code: ${s.userCode}
251
251
 
252
252
  `),process.stdout.write(`Waiting for you to approve...
253
- `)}}),n=await bn({serverUrl:e,token:r}),o=C(process.cwd()),i=o?"Welcome back":"Welcome to Ripplo";process.stdout.write(`
253
+ `)}}),n=await Sn({serverUrl:e,token:r}),o=C(process.cwd()),i=o?"Welcome back":"Welcome to Ripplo";process.stdout.write(`
254
254
  `),process.stdout.write(n==null?`${i}.
255
- `:`${i}, ${gp(n)}.
255
+ `:`${i}, ${Sp(n)}.
256
256
  `),process.stdout.write(`Session saved to ${ke("token")}.
257
- `),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 gp(e){let t=e.name.trim().split(/\s+/)[0];return t!=null&&t.length>0?t:e.email}async function bn({serverUrl:e,token:t}){try{let n=(await h({config:Pe({serverUrl:e,token:t}),document:fp,variables:void 0})).currentUser;return n==null?null:{email:n.email,name:n.name}}catch{return null}}async function si(){let e=ie();e==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login`.\n"),process.exit(1));let t=ee(),r=await bn({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})
258
- `)}function ai(){if(!un()){process.stdout.write(`No token to remove.
257
+ `),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 Sp(e){let t=e.name.trim().split(/\s+/)[0];return t!=null&&t.length>0?t:e.email}async function Sn({serverUrl:e,token:t}){try{let n=(await h({config:Pe({serverUrl:e,token:t}),document:vp,variables:void 0})).currentUser;return n==null?null:{email:n.email,name:n.name}}catch{return null}}async function ci(){let e=ie();e==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login`.\n"),process.exit(1));let t=ee(),r=await Sn({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})
258
+ `)}function ui(){if(!pn()){process.stdout.write(`No token to remove.
259
259
  `);return}process.stdout.write(`Removed ${ke("token")}
260
- `)}import{createHash as yp}from"crypto";import ht from"fs/promises";import We from"path";import{z as Yt}from"zod";import{z as li}from"zod";import{z as Be}from"zod";import{z as p}from"zod";import{z as Re}from"zod";import{z as fi}from"zod";import{z as D}from"zod";import{z as te}from"zod";import{z as vn}from"zod";import{z as A}from"zod";var hp=Yt.object({__codec:Yt.string().min(1),data:Yt.unknown(),version:Yt.number().int().positive()}),wp=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}},bp=class extends Error{constructor(e){super(`Codec mismatch: expected "${e.expected}", got "${e.got}"`),this.name="CodecMismatchError"}};function Pn(e){return pi({legacy:void 0,migrators:[],name:e,schemas:[]})}function vp(e,t){let r=JSON.parse(t);return e.decode(r)}function pi(e){return{initial:t=>Sn(t,{...e,schemas:[t]}),legacy:t=>pi({...e,legacy:t})}}function Sn(e,t){return{build:()=>Sp(e,t),legacy:r=>Sn(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return Sn(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function Sp(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>kp(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function kp(e,t,r){let{data:n,version:o}=Pp(t,r),i=mi(t,n,o);return e.parse(i)}function Pp(e,t){let r=hp.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new bp({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 mi(e,t,r){let n=e.schemas.length;if(r>n)throw new wp({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 mi(e,s(i),r+1)}var Rn=Be.object({depends:Be.array(Be.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:Be.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:Be.array(Be.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."),Rp=Re.object({by:Re.literal("testId"),value:Re.string().min(1)}),xp=Re.object({by:Re.literal("role"),name:Re.string().optional(),role:Re.string().min(1)}),I=Re.discriminatedUnion("by",[Rp,xp]),wt=fi.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),Ep=fi.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]),Cp=D.object({type:D.literal("static"),value:D.union([D.string(),D.number(),D.boolean()])}),Qt=D.object({name:D.string().min(1),type:D.literal("variable")}),Tp=D.discriminatedUnion("type",[Cp,Qt]),ae=D.discriminatedUnion("type",[D.object({type:D.literal("static"),value:D.string()}),Qt]),Ap=D.discriminatedUnion("type",[D.object({type:D.literal("static"),value:D.number().int().nonnegative()}),Qt]),Ip=D.discriminatedUnion("type",[D.object({type:D.literal("static"),value:D.union([D.string(),D.number(),D.boolean()])}),Qt]),$p=te.discriminatedUnion("type",[te.object({default:te.string().optional(),type:te.literal("string")}),te.object({default:te.number().optional(),type:te.literal("number")}),te.object({default:te.boolean().optional(),type:te.literal("boolean")}),te.object({key:te.string().min(1),type:te.literal("env")})]),k={id:p.string().min(1).max(200),label:p.string().max(500).optional(),next:p.string().max(200).optional(),uiOnly:p.boolean().optional()},ci=500,jp=p.object({...k,type:p.literal("goto"),url:ae}),Np=p.object({...k,locator:I,modifier:p.enum(["Alt","Control","Meta","Shift"]).optional(),type:p.literal("click")}),Dp=p.object({...k,locator:I,type:p.literal("fill"),value:ae}),Op=p.object({...k,locator:I,type:p.literal("select"),value:ae}),Lp=p.object({...k,locator:I,type:p.literal("hover")}),_p=p.object({...k,key:p.string().min(1),locator:I.optional(),type:p.literal("press")}),Up=p.object({...k,locator:I,type:p.literal("check")}),Vp=p.object({...k,locator:I,type:p.literal("uncheck")}),Fp=p.object({...k,height:p.number().int().positive(),type:p.literal("setViewport"),width:p.number().int().positive()}),Mp=p.object({...k,message:p.string().min(1),type:p.literal("fail")}),Hp=p.object({...k,type:p.literal("setVariable"),value:Tp,variable:p.string().min(1)}),Bp=p.object({...k,locator:I,type:p.literal("extractText"),variable:p.string().min(1)}),Wp=p.object({...k,files:p.array(p.string()).min(1),locator:I,type:p.literal("upload")}),qp=p.object({...k,locator:I,type:p.literal("dblclick")}),zp=p.object({...k,source:I,target:I,type:p.literal("drag")}),Gp=p.object({...k,locator:I,type:p.literal("scrollIntoView")}),Kp=p.object({...k,locator:I,type:p.literal("type"),value:ae}),Jp=p.object({...k,locator:I,type:p.literal("focus")}),Xp=p.object({...k,locator:I,type:p.literal("clear")}),Yp=p.object({...k,locator:I,type:p.literal("rightClick")}),Qp=p.object({...k,action:p.enum(["accept","dismiss"]),promptText:p.string().optional(),type:p.literal("handleDialog")}),Zp=p.object({...k,action:p.enum(["read","write"]),type:p.literal("clipboard"),value:ae.optional(),variable:p.string().min(1).optional()}),em=p.object({...k,permission:p.string().min(1),state:p.enum(["granted","prompt"]),type:p.literal("setPermission")}),tm=p.object({...k,locator:I,type:p.literal("assertVisible")}),rm=p.object({...k,locator:I,type:p.literal("assertNotVisible")}),nm=p.object({...k,expected:ae,locator:I,operator:wt,type:p.literal("assertText")}),om=p.object({...k,expected:ae,operator:wt,type:p.literal("assertUrl")}),im=p.object({...k,expected:Ap,locator:I,operator:Ep,type:p.literal("assertCount")}),sm=p.object({...k,expected:ae,locator:I,operator:wt,type:p.literal("assertValue")}),am=p.object({...k,attribute:p.string().min(1),expected:ae,locator:I,operator:wt,type:p.literal("assertAttribute")}),lm=p.object({...k,locator:I,type:p.literal("assertEnabled")}),cm=p.object({...k,locator:I,type:p.literal("assertDisabled")}),um=p.object({...k,expected:ae,operator:wt,type:p.literal("assertTitle")}),dm=p.object({...k,locator:I,type:p.literal("assertChecked")}),pm=p.object({...k,locator:I,type:p.literal("assertNotChecked")}),mm=p.object({...k,locator:I,type:p.literal("assertFocused")}),fm=p.object({...k,locator:I,type:p.literal("assertNotFocused")}),gm=p.object({...k,budget:p.enum(["fast","slow","async"]),observer:p.string().min(1).max(200),params:p.record(p.string().max(200),Ip),type:p.literal("assertObserver")}),ym=p.discriminatedUnion("type",[jp,Np,Dp,Op,Lp,_p,Up,Vp,tm,rm,nm,om,im,sm,am,lm,cm,Fp,Mp,Hp,Bp,Wp,qp,zp,Gp,Kp,Jp,Xp,Yp,Qp,Zp,em,um,dm,pm,mm,fm,gm]),gi=p.object({entryNode:p.string().min(1).max(200),nodes:p.record(p.string().max(200),ym).refine(e=>Object.keys(e).length<=ci,`Workflow has more than ${String(ci)} nodes`),uiOnly:p.boolean().optional(),variableNamespaces:p.record(p.string().max(200),p.string().max(500)).optional(),variables:p.record(p.string().max(200),$p).optional()}),hm=li.record(li.string().max(200),Rn),wm={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},bm={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},fR=Pn("workflow-spec").legacy(wm).initial(gi).build(),gR=Pn("precondition-map").legacy(bm).initial(hm).build(),vm=["fast","slow","async"],yi=vn.object({budget:vn.enum(vm).describe("Polling budget tier: fast | slow | async"),description:vn.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",Sm=".ripplo/fixtures",hi=5e3,km=A.record(A.string().max(200),A.string().max(200)),wi=A.object({coverage:A.array(A.string().max(500)).max(2e3).default([]),expectedOutcome:A.string().max(2e3),name:A.string().max(200),preconditions:A.array(A.string().max(200)).max(1e3),requiresKeys:km,slug:A.string().max(200),sourcePath:A.string().max(500).optional(),spec:gi}),Pm=A.object({sha256:A.string().regex(/^[0-9a-f]{64}$/u),size:A.number().int().nonnegative()}),Rm=A.record(A.string().min(1).max(500),Pm),xm=A.object({observers:A.record(A.string().max(200),yi),preconditions:A.record(A.string().max(200),Rn),tests:A.array(wi).max(hi)}),Em=A.object({fixtures:Rm,observers:A.record(A.string().max(200),yi),preconditions:A.record(A.string().max(200),Rn),tests:A.array(wi).max(hi)}),bi=Pn("ripplo-lockfile").initial(xm).upgrade(Em,e=>({...e,fixtures:{}})).build();function vi(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 kn(e){let t=bi.encode(e);return`${JSON.stringify(t,Im(t),2)}
261
- `}async function Zt({cwd:e}){let t=We.join(e,le),r=await Am(t);return r==null?null:vp(bi,r)}var ui=10*1024*1024,di=50*1024*1024;async function ce({cwd:e,result:t}){let r=await Si({cwd:e,result:t}),n=vi(r),o=We.join(e,le);await ht.mkdir(We.dirname(o),{recursive:!0}),await ht.writeFile(o,kn(n),"utf8")}async function Si({cwd:e,result:t}){let r=Tm(t);if(r.size===0)return{...t,fixtures:{}};let n=We.join(e,Sm),o=[...r].toSorted((a,l)=>a.localeCompare(l)),i=await Promise.all(o.map(async a=>{let l=await Cm({fixturesRoot:n,name:a});if(l.size>ui)throw new Error(`Fixture "${a}" is ${String(l.size)} bytes; exceeds per-file limit of ${String(ui)} bytes`);return[a,l]}));if(i.reduce((a,[,l])=>a+l.size,0)>di)throw new Error(`Total fixtures size exceeds limit of ${String(di)} bytes`);return{...t,fixtures:Object.fromEntries(i)}}async function Cm({fixturesRoot:e,name:t}){if(t.includes("..")||We.isAbsolute(t))throw new Error(`Invalid fixture name "${t}": must be a path under .ripplo/fixtures/`);let r=We.join(e,t),n=await ht.lstat(r).catch(s=>{throw ki(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 ht.readFile(r);return{sha256:yp("sha256").update(o).digest("hex"),size:o.byteLength}}function Tm(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}async function er({compiled:e,cwd:t,existing:r}){if(r==null)return"missing";let n=await Si({cwd:t,result:e}),o=kn(vi(n)),i=kn(r);return o===i?"match":"stale"}async function Am(e){try{return await ht.readFile(e,"utf8")}catch(t){if(ki(t)&&t.code==="ENOENT")return null;throw t}}function ki(e){return e instanceof Error&&"code"in e}function Im(e){return function(r,n){return n===e||!$m(n)?n:Object.fromEntries(Object.entries(n).toSorted(([o],[i])=>o.localeCompare(i)))}}function $m(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import bt from"fs";import nr from"path";var xn=["**/src/**","**/app/**","**/apps/**","**/pages/**","**/routes/**","**/components/**","**/server/**","**/api/**","**/backend/**","**/features/**","**/modules/**","**/views/**","**/ui/**","**/hooks/**","**/contexts/**","**/providers/**","**/controllers/**","**/handlers/**","**/resolvers/**","**/services/**","**/middleware/**","**/lib/**"],xe=["**/*.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 Pi(e){return e.data}function Ri(e){return{as(t){return{data:{label:t,node:e}}}}}function tr(e){let t=e.getPreconditions(),r=e.getObservers(),n=e.getTests();jm(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=>Nm(a,t));return{fixtures:{},observers:i,preconditions:o,tests:s}}function jm(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 Nm(e,t){let r=e.id,{accessedKeys:n,vars:o}=Om(e.requiresKeys),i=e.startsAtFn==null?void 0:e.startsAtFn(o),s=e.stepsFn==null?[]:e.stepsFn(o),a=i==null?s:[Dm(i),...s],l=Lm(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=Um(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 Dm(e){return Ri({type:"goto",url:{type:"static",value:e}}).as(`navigate to ${e}`)}function Om(e){let t=new Set,r={};return Object.keys(e).forEach(n=>{r[n]=new Proxy({},{get(o,i){if(typeof i=="string"){let s=`${n}.${i}`;return t.add(s),`{{${s}}}`}}})}),{accessedKeys:t,vars:r}}function Lm(e,t,r,n){let o={};e.forEach((a,l)=>{let c=`step-${String(l)}`,u=l<e.length-1?`step-${String(l+1)}`:void 0;o[c]=_m(a,c,u)});let i={};t.forEach(a=>{i[a]={default:`test-${a}`,type:"string"}});let s={...r};return{entryNode:"step-0",nodes:o,uiOnly:n,variableNamespaces:s,variables:i}}function _m(e,t,r){let{label:n,node:o}=Pi(e);return{...o,id:t,label:n,next:r}}function Um(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 ER,WebhookVerificationError as CR}from"standardwebhooks";import{z as L}from"zod";var xi=L.union([L.string(),L.number(),L.boolean()]),Vm=L.record(L.string(),L.record(L.string(),xi)),AR=L.object({batch:L.array(L.object({preconditions:L.array(L.string().min(1)),runId:L.string().min(1)})).min(1)}),IR=L.object({batch:L.array(L.object({data:Vm,preconditions:L.array(L.string().min(1)),runId:L.string().min(1)})).min(1)}),$R=L.object({observer:L.string().min(1).max(200),params:L.record(L.string().max(200),xi)});function qe(e){let t=[];return e.tests.forEach(r=>{let n=Fm(r),o=i=>{t.push({...i,test:r.slug})};uf.forEach(i=>{i(n,r,o)})}),{diagnostics:t}}function Fm(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 Mm(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 Hm(e,t,r){Object.keys(t.spec.variables??{}).length>0&&e.forEach(o=>{if(o.type==="fill"&&Ci(o.value)){let i=o.value.value;!Ti(i)&&Jm(i)&&r({message:`fill() uses hardcoded value "${i}" \u2014 consider using precondition data via {{namespace.key}}`,rule:"no-hardcoded-data",step:o.label??o.id})}})}function Bm(e,t,r){if(Object.keys(t.spec.variables??{}).length===0)return;e.some(i=>JSON.stringify(i).includes("{{"))||r({message:"Test requires preconditions but steps() never references precondition data \u2014 destructure and use it",rule:"prefer-precondition-data",step:void 0})}function Wm(e,t,r){e.forEach(n=>{(n.label==null||n.label.length===0)&&r({message:`Step "${n.id}" lacks .as("...") label \u2014 every step must be labeled`,rule:"missing-label",step:n.id})})}function qm(e,t,r){let n=new Map;e.forEach(o=>{if(o.label==null)return;let i=n.get(o.label);i==null?n.set(o.label,o.id):r({message:`Duplicate label "${o.label}" \u2014 also used by ${i}`,rule:"no-duplicate-labels",step:o.label})})}function zm(e,t,r){let n=0;e.forEach((o,i)=>{if(!(i===0&&o.type==="goto")){if(ze(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 Gm(e,t,r){if(e.length===0)return;let n=e.at(-1);n!=null&&!ze(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 Km(e,t,r){t.implemented&&e.length===0&&r({message:"Test has zero steps",rule:"no-empty-steps",step:void 0})}function Ci(e){return!(typeof e!="object"||e==null||!("type"in e)||e.type!=="static"||!("value"in e)||typeof e.value!="string")}function Ti(e){return e.includes("{{")}function Jm(e){return e.includes("@")||/\b[a-f0-9]{8,}\b/.test(e)||/^(test|ripplo|example|sample|demo)/i.test(e)}function ze(e){return e.type.startsWith("assert")}var Xm=new Set(["assertText","assertValue","assertCount","assertUrl","assertNotVisible","assertChecked","assertNotChecked","assertAttribute","assertDisabled","assertEnabled"]);function Ym(e){return Xm.has(e.type)}function Qm(e,t,r){!t.implemented||e.length===0||e.some(n=>ze(n))||r({message:"Test has zero assertion steps \u2014 cannot verify expectedOutcome. Add assert.* steps.",rule:"no-assertions",step:void 0})}function Zm(e,t,r){if(!t.implemented||e.length<=3)return;let n=e.filter(i=>ze(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 En(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 ef(e,t,r){e.forEach((n,o)=>{if(n.type!=="click")return;let i=En(n);if(i==null)return;let s=e.slice(o+1,o+4);s.find(c=>c.type==="assertVisible"&&En(c)===i)==null||s.some(c=>Ym(c)||ze(c)&&En(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 tf=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 Cn(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=3&&!tf.has(t))}function rf(e){let t=e.label==null?[]:Cn(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,...Cn(n)]}function nf(e,t,r){if(!t.implemented||e.length===0)return;let n=new Set(Cn(t.expectedOutcome));if(n.size===0)return;let o=e.filter(s=>ze(s));if(o.length===0)return;o.some(s=>rf(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 of=/save|submit|create|delete|remove|send|invite|update|confirm|publish|apply|pay|subscribe|upgrade|cancel|archive|rename/i;function Ei(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 of.test(r)}function sf(e,t,r){!t.implemented||t.spec.uiOnly===!0||e.forEach((n,o)=>{if(!Ei(n)||"uiOnly"in n&&n.uiOnly===!0)return;let i=e.slice(o+1),s=i.findIndex(u=>Ei(u)),a=s===-1?i.length:s;i.slice(0,a).some(u=>u.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 af(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])=>Ci(a)&&Ti(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 lf(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 cf(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(", "),u=[...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(({ ${u} }) => \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 uf=[Mm,Hm,cf,Bm,Wm,qm,zm,Gm,Km,Qm,Zm,ef,nf,sf,af,lf];import Of from"picomatch";import{execFileSync as df,spawnSync as pf}from"child_process";function K(e,t){return df("git",[...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}function Ai(e,t){let r=pf("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 Ii from"remeda";var $i=[["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"]],mf=new Map([["button","click"],["link","navigate"],["textbox","input"],["searchbox","input"],["combobox","select"],["listbox","select"]]),ff=[[/(?:^|[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 rr({filePath:e,source:t}){let r=b.createSourceFile(e,t,b.ScriptTarget.Latest,!0,b.ScriptKind.TSX);return r.statements.flatMap(n=>gf({filePath:e,sf:r,stmt:n}))}function gf({filePath:e,sf:t,stmt:r}){let n=hf(r);if(n==null||yf(n))return[];let o=ji(r,t).map(i=>({id:`${e}#${n}.${i.kind}[${i.label}]`,line:i.line}));return Ii.uniqueBy(o,i=>i.id)}function yf(e){return e.endsWith("Fragment")||e.endsWith("Skeleton")||/^use[A-Z]/.test(e)||/^[A-Z][A-Z0-9_]*$/.test(e)}function hf(e){if(b.isExportAssignment(e))return wf(e.expression);if(!bf(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 wf(e){return b.isIdentifier(e)?e.text:(b.isFunctionExpression(e)||b.isClassExpression(e))&&e.name!=null?e.name.text:"default"}function bf(e){if(!b.canHaveModifiers(e))return!1;let t=b.getModifiers(e);return t!=null&&t.some(r=>r.kind===b.SyntaxKind.ExportKeyword)}function ji(e,t){let r=vf(e,t),n=e.getChildren(t).flatMap(o=>ji(o,t));return r==null?n:[r,...n]}function vf(e,t){let r=Sf(e);if(r==null)return null;let n=kf(r);if(n==null)return null;let o=Cf(r,n);return o==null?null:{kind:n,label:o,line:Df(t,e.getStart(t))}}function Sf(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 kf({attrs:e,tag:t}){let r=ue(e,"role");return r!=null?mf.get(r)??null:Rf(t,e)??xf(t)??Ef(e)}var Pf=new Map([["button",()=>"click"],["a",e=>ue(e,"href")==null?null:"navigate"],["input",e=>ue(e,"type")==="file"?"upload":"input"],["textarea",()=>"input"],["select",()=>"select"],["form",()=>"submit"]]);function Rf(e,t){return Pf.get(e)?.(t)??null}function xf(e){return/^[A-Z]/.test(e)?ff.find(([t])=>t.test(e))?.[1]??null:null}function Ef(e){return $i.find(([t])=>If(e,t))?.[1]??null}function Cf({attrs:e,children:t,tag:r},n){return n==="navigate"?ue(e,"href")??ue(e,"to"):ue(e,"aria-label")??ue(e,"label")??ue(e,"title")??ue(e,"name")??ue(e,"placeholder")??(Tf(r)?void 0:Nf(t))??Af(e,n)}function Tf(e){return e==="input"||e==="textarea"||e==="select"}function Af(e,t){let r=$i.find(([,o])=>o===t)?.[0];if(r==null)return;let n=$f(e,r);if(n!=null){if(b.isIdentifier(n))return n.text;if(b.isArrowFunction(n)||b.isFunctionExpression(n))return Ni(n.body)}}function Ni(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,Ni)}function If(e,t){return e.properties.some(r=>b.isJsxAttribute(r)&&b.isIdentifier(r.name)&&r.name.text===t)}function Di(e,t){return e.properties.find(r=>b.isJsxAttribute(r)&&b.isIdentifier(r.name)&&r.name.text===t)}function ue(e,t){let r=Di(e,t);return r==null?void 0:jf(r.initializer)}function $f(e,t){let r=Di(e,t);if(!(r?.initializer==null||!b.isJsxExpression(r.initializer)))return r.initializer.expression}function jf(e){if(e==null)return"";if(b.isStringLiteral(e))return e.text;if(b.isJsxExpression(e))return Li(e.expression)}function Nf(e){let t=e.flatMap(r=>Oi(r)).join(" ").trim();return t.length===0?void 0:t}function Oi(e){if(b.isJsxText(e)){let t=e.text.trim();return t.length===0?[]:[t]}if(b.isJsxExpression(e)){let t=Li(e.expression);return t==null?[]:[t]}return b.isJsxElement(e)?e.children.flatMap(t=>Oi(t)):[]}function Li(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 Df(e,t){return e.getLineAndCharacterOfPosition(t).line+1}var Lf=nr.join(".ripplo","coverage.d.ts");function Ge({cwd:e}){_f({cwd:e,ignorePaths:xe})}function _f({cwd:e,ignorePaths:t}){let r=Ke({cwd:e,ignorePaths:t});Ff({content:Vf(r),cwd:e})}function Ke({cwd:e,ignorePaths:t}){let n=Uf({cwd:e,ignorePaths:t}).flatMap(o=>Tn({cwd:e,file:o}));return[...new Set(n)].sort((o,i)=>o.localeCompare(i))}function Uf({cwd:e,ignorePaths:t}){let r=K(["ls-files","--cached","--others","--exclude-standard","-z"],e),n=Of([...t]);return r.split("\0").filter(o=>o.length>0&&/\.(tsx|jsx)$/.test(o)).filter(o=>!n(o)).filter(o=>bt.existsSync(nr.join(e,o)))}function Tn({cwd:e,file:t}){let r=bt.readFileSync(nr.join(e,t),"utf8");return rr({filePath:t,source:r}).map(n=>n.id)}function Vf(e){let t=`// GENERATED \u2014 do not edit
260
+ `)}import{createHash as kp}from"crypto";import wt from"fs/promises";import We from"path";import{z as Zt}from"zod";import{z as di}from"zod";import{z as Be}from"zod";import{z as p}from"zod";import{z as Re}from"zod";import{z as hi}from"zod";import{z as D}from"zod";import{z as te}from"zod";import{z as kn}from"zod";import{z as A}from"zod";var Pp=Zt.object({__codec:Zt.string().min(1),data:Zt.unknown(),version:Zt.number().int().positive()}),Rp=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}},xp=class extends Error{constructor(e){super(`Codec mismatch: expected "${e.expected}", got "${e.got}"`),this.name="CodecMismatchError"}};function xn(e){return gi({legacy:void 0,migrators:[],name:e,schemas:[]})}function Ep(e,t){let r=JSON.parse(t);return e.decode(r)}function gi(e){return{initial:t=>Pn(t,{...e,schemas:[t]}),legacy:t=>gi({...e,legacy:t})}}function Pn(e,t){return{build:()=>Cp(e,t),legacy:r=>Pn(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return Pn(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function Cp(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>Tp(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function Tp(e,t,r){let{data:n,version:o}=Ap(t,r),i=yi(t,n,o);return e.parse(i)}function Ap(e,t){let r=Pp.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new xp({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 yi(e,t,r){let n=e.schemas.length;if(r>n)throw new Rp({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 yi(e,s(i),r+1)}var En=Be.object({depends:Be.array(Be.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:Be.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:Be.array(Be.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."),Ip=Re.object({by:Re.literal("testId"),value:Re.string().min(1)}),$p=Re.object({by:Re.literal("role"),name:Re.string().optional(),role:Re.string().min(1)}),I=Re.discriminatedUnion("by",[Ip,$p]),bt=hi.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),jp=hi.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]),Np=D.object({type:D.literal("static"),value:D.union([D.string(),D.number(),D.boolean()])}),er=D.object({name:D.string().min(1),type:D.literal("variable")}),Dp=D.discriminatedUnion("type",[Np,er]),ae=D.discriminatedUnion("type",[D.object({type:D.literal("static"),value:D.string()}),er]),Op=D.discriminatedUnion("type",[D.object({type:D.literal("static"),value:D.number().int().nonnegative()}),er]),Lp=D.discriminatedUnion("type",[D.object({type:D.literal("static"),value:D.union([D.string(),D.number(),D.boolean()])}),er]),_p=te.discriminatedUnion("type",[te.object({default:te.string().optional(),type:te.literal("string")}),te.object({default:te.number().optional(),type:te.literal("number")}),te.object({default:te.boolean().optional(),type:te.literal("boolean")}),te.object({key:te.string().min(1),type:te.literal("env")})]),k={id:p.string().min(1).max(200),label:p.string().max(500).optional(),next:p.string().max(200).optional(),uiOnly:p.boolean().optional()},pi=500,Up=p.object({...k,type:p.literal("goto"),url:ae}),Vp=p.object({...k,locator:I,modifier:p.enum(["Alt","Control","Meta","Shift"]).optional(),type:p.literal("click")}),Fp=p.object({...k,locator:I,type:p.literal("fill"),value:ae}),Mp=p.object({...k,locator:I,type:p.literal("select"),value:ae}),Hp=p.object({...k,locator:I,type:p.literal("hover")}),Bp=p.object({...k,key:p.string().min(1),locator:I.optional(),type:p.literal("press")}),Wp=p.object({...k,locator:I,type:p.literal("check")}),qp=p.object({...k,locator:I,type:p.literal("uncheck")}),zp=p.object({...k,height:p.number().int().positive(),type:p.literal("setViewport"),width:p.number().int().positive()}),Gp=p.object({...k,message:p.string().min(1),type:p.literal("fail")}),Kp=p.object({...k,type:p.literal("setVariable"),value:Dp,variable:p.string().min(1)}),Jp=p.object({...k,locator:I,type:p.literal("extractText"),variable:p.string().min(1)}),Xp=p.object({...k,files:p.array(p.string()).min(1),locator:I,type:p.literal("upload")}),Yp=p.object({...k,locator:I,type:p.literal("dblclick")}),Qp=p.object({...k,source:I,target:I,type:p.literal("drag")}),Zp=p.object({...k,locator:I,type:p.literal("scrollIntoView")}),em=p.object({...k,locator:I,type:p.literal("type"),value:ae}),tm=p.object({...k,locator:I,type:p.literal("focus")}),rm=p.object({...k,locator:I,type:p.literal("clear")}),nm=p.object({...k,locator:I,type:p.literal("rightClick")}),om=p.object({...k,action:p.enum(["accept","dismiss"]),promptText:p.string().optional(),type:p.literal("handleDialog")}),im=p.object({...k,action:p.enum(["read","write"]),type:p.literal("clipboard"),value:ae.optional(),variable:p.string().min(1).optional()}),sm=p.object({...k,permission:p.string().min(1),state:p.enum(["granted","prompt"]),type:p.literal("setPermission")}),am=p.object({...k,locator:I,type:p.literal("assertVisible")}),lm=p.object({...k,locator:I,type:p.literal("assertNotVisible")}),cm=p.object({...k,expected:ae,locator:I,operator:bt,type:p.literal("assertText")}),um=p.object({...k,expected:ae,operator:bt,type:p.literal("assertUrl")}),dm=p.object({...k,expected:Op,locator:I,operator:jp,type:p.literal("assertCount")}),pm=p.object({...k,expected:ae,locator:I,operator:bt,type:p.literal("assertValue")}),mm=p.object({...k,attribute:p.string().min(1),expected:ae,locator:I,operator:bt,type:p.literal("assertAttribute")}),fm=p.object({...k,locator:I,type:p.literal("assertEnabled")}),gm=p.object({...k,locator:I,type:p.literal("assertDisabled")}),ym=p.object({...k,expected:ae,operator:bt,type:p.literal("assertTitle")}),hm=p.object({...k,locator:I,type:p.literal("assertChecked")}),wm=p.object({...k,locator:I,type:p.literal("assertNotChecked")}),bm=p.object({...k,locator:I,type:p.literal("assertFocused")}),vm=p.object({...k,locator:I,type:p.literal("assertNotFocused")}),Sm=p.object({...k,budget:p.enum(["fast","slow","async"]),observer:p.string().min(1).max(200),params:p.record(p.string().max(200),Lp),type:p.literal("assertObserver")}),km=p.discriminatedUnion("type",[Up,Vp,Fp,Mp,Hp,Bp,Wp,qp,am,lm,cm,um,dm,pm,mm,fm,gm,zp,Gp,Kp,Jp,Xp,Yp,Qp,Zp,em,tm,rm,nm,om,im,sm,ym,hm,wm,bm,vm,Sm]),wi=p.object({entryNode:p.string().min(1).max(200),nodes:p.record(p.string().max(200),km).refine(e=>Object.keys(e).length<=pi,`Workflow has more than ${String(pi)} nodes`),uiOnly:p.boolean().optional(),variableNamespaces:p.record(p.string().max(200),p.string().max(500)).optional(),variables:p.record(p.string().max(200),_p).optional()}),Pm=di.record(di.string().max(200),En),Rm={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},xm={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},RR=xn("workflow-spec").legacy(Rm).initial(wi).build(),xR=xn("precondition-map").legacy(xm).initial(Pm).build(),Em=["fast","slow","async"],bi=kn.object({budget:kn.enum(Em).describe("Polling budget tier: fast | slow | async"),description:kn.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",Cm=".ripplo/fixtures",vi=5e3,Tm=A.record(A.string().max(200),A.string().max(200)),Si=A.object({coverage:A.array(A.string().max(500)).max(2e3).default([]),expectedOutcome:A.string().max(2e3),name:A.string().max(200),preconditions:A.array(A.string().max(200)).max(1e3),requiresKeys:Tm,slug:A.string().max(200),sourcePath:A.string().max(500).optional(),spec:wi}),Am=A.object({sha256:A.string().regex(/^[0-9a-f]{64}$/u),size:A.number().int().nonnegative()}),Im=A.record(A.string().min(1).max(500),Am),$m=A.object({observers:A.record(A.string().max(200),bi),preconditions:A.record(A.string().max(200),En),tests:A.array(Si).max(vi)}),jm=A.object({fixtures:Im,observers:A.record(A.string().max(200),bi),preconditions:A.record(A.string().max(200),En),tests:A.array(Si).max(vi)}),ki=xn("ripplo-lockfile").initial($m).upgrade(jm,e=>({...e,fixtures:{}})).build();function Pi(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 Rn(e){let t=ki.encode(e);return`${JSON.stringify(t,Lm(t),2)}
261
+ `}async function tr({cwd:e}){let t=We.join(e,le),r=await Om(t);return r==null?null:Ep(ki,r)}var mi=10*1024*1024,fi=50*1024*1024;async function ce({cwd:e,result:t}){let r=await Ri({cwd:e,result:t}),n=Pi(r),o=We.join(e,le);await wt.mkdir(We.dirname(o),{recursive:!0}),await wt.writeFile(o,Rn(n),"utf8")}async function Ri({cwd:e,result:t}){let r=Dm(t);if(r.size===0)return{...t,fixtures:{}};let n=We.join(e,Cm),o=[...r].toSorted((a,l)=>a.localeCompare(l)),i=await Promise.all(o.map(async a=>{let l=await Nm({fixturesRoot:n,name:a});if(l.size>mi)throw new Error(`Fixture "${a}" is ${String(l.size)} bytes; exceeds per-file limit of ${String(mi)} bytes`);return[a,l]}));if(i.reduce((a,[,l])=>a+l.size,0)>fi)throw new Error(`Total fixtures size exceeds limit of ${String(fi)} bytes`);return{...t,fixtures:Object.fromEntries(i)}}async function Nm({fixturesRoot:e,name:t}){let r=t;if(typeof r!="string"||r.length===0)throw new Error(`Internal error: upload step produced a non-string fixture name (got ${r===null?"null":typeof r}). This usually means a test passed a non-Fixture value to upload() \u2014 wrap the filename with fixture("file.png").`);if(t.includes("..")||We.isAbsolute(t))throw new Error(`Invalid fixture name "${t}": must be a path under .ripplo/fixtures/`);let n=We.join(e,t),o=await wt.lstat(n).catch(a=>{throw xi(a)&&a.code==="ENOENT"?new Error(`Fixture "${t}" not found at ${n}`):a});if(o.isSymbolicLink())throw new Error(`Fixture "${t}" is a symlink; symlinks are not allowed`);if(!o.isFile())throw new Error(`Fixture "${t}" is not a regular file`);let i=await wt.readFile(n);return{sha256:kp("sha256").update(i).digest("hex"),size:i.byteLength}}function Dm(e){let t=new Set;return e.tests.forEach(r=>{Object.entries(r.spec.nodes).forEach(([n,o])=>{o.type==="upload"&&o.files.forEach((i,s)=>{let a=i;if(typeof a!="string"||a.length===0)throw new Error(`Test "${r.slug}" step "${n}" upload files[${String(s)}] is not a non-empty string (got ${a===null?"null":typeof a}). Wrap filenames with fixture(): upload(loc, fixture("file.png")).`);t.add(a)})})}),t}async function rr({compiled:e,cwd:t,existing:r}){if(r==null)return"missing";let n=await Ri({cwd:t,result:e}),o=Rn(Pi(n)),i=Rn(r);return o===i?"match":"stale"}async function Om(e){try{return await wt.readFile(e,"utf8")}catch(t){if(xi(t)&&t.code==="ENOENT")return null;throw t}}function xi(e){return e instanceof Error&&"code"in e}function Lm(e){return function(r,n){return n===e||!_m(n)?n:Object.fromEntries(Object.entries(n).toSorted(([o],[i])=>o.localeCompare(i)))}}function _m(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import vt from"fs";import ir from"path";var Cn=["**/src/**","**/app/**","**/apps/**","**/pages/**","**/routes/**","**/components/**","**/server/**","**/api/**","**/backend/**","**/features/**","**/modules/**","**/views/**","**/ui/**","**/hooks/**","**/contexts/**","**/providers/**","**/controllers/**","**/handlers/**","**/resolvers/**","**/services/**","**/middleware/**","**/lib/**"],xe=["**/*.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 Ei(e){return e.data}function Ci(e){return{as(t){return{data:{label:t,node:e}}}}}function nr(e){let t=e.getPreconditions(),r=e.getObservers(),n=e.getTests();Um(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=>Vm(a,t));return{fixtures:{},observers:i,preconditions:o,tests:s}}function Um(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 Vm(e,t){let r=e.id,{accessedKeys:n,vars:o}=Mm(e.requiresKeys),i=e.startsAtFn==null?void 0:e.startsAtFn(o),s=e.stepsFn==null?[]:e.stepsFn(o),a=i==null?s:[Fm(i),...s],l=Hm(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=Wm(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 Fm(e){return Ci({type:"goto",url:{type:"static",value:e}}).as(`navigate to ${e}`)}function Mm(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 Hm(e,t,r,n){let o={};e.forEach((a,l)=>{let c=`step-${String(l)}`,u=l<e.length-1?`step-${String(l+1)}`:void 0;o[c]=Bm(a,c,u)});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 Bm(e,t,r){let{label:n,node:o}=Ei(e);return{...o,id:t,label:n,next:r}}function Wm(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 LR,WebhookVerificationError as _R}from"standardwebhooks";import{z as L}from"zod";var Ti=L.union([L.string(),L.number(),L.boolean()]),qm=L.record(L.string(),L.record(L.string(),Ti)),VR=L.object({batch:L.array(L.object({preconditions:L.array(L.string().min(1)),runId:L.string().min(1)})).min(1)}),FR=L.object({batch:L.array(L.object({data:qm,preconditions:L.array(L.string().min(1)),runId:L.string().min(1)})).min(1)}),MR=L.object({observer:L.string().min(1).max(200),params:L.record(L.string().max(200),Ti)});function qe(e){let t=[];return e.tests.forEach(r=>{let n=zm(r),o=i=>{t.push({...i,test:r.slug})};yf.forEach(i=>{i(n,r,o)})}),{diagnostics:t}}function zm(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 Gm(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 Km(e,t,r){Object.keys(t.spec.variables??{}).length>0&&e.forEach(o=>{if(o.type==="fill"&&Ii(o.value)){let i=o.value.value;!$i(i)&&tf(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 Jm(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 Xm(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 Ym(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 Qm(e,t,r){let n=0;e.forEach((o,i)=>{if(!(i===0&&o.type==="goto")){if(ze(o)){n=0;return}n++,n===3&&r({message:"3+ consecutive actions without an assertion \u2014 add verification between actions",rule:"assert-after-action",step:o.label??o.id})}})}function Zm(e,t,r){if(e.length===0)return;let n=e.at(-1);n!=null&&!ze(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 ef(e,t,r){t.implemented&&e.length===0&&r({message:"Test has zero steps",rule:"no-empty-steps",step:void 0})}function Ii(e){return!(typeof e!="object"||e==null||!("type"in e)||e.type!=="static"||!("value"in e)||typeof e.value!="string")}function $i(e){return e.includes("{{")}function tf(e){return e.includes("@")||/\b[a-f0-9]{8,}\b/.test(e)||/^(test|ripplo|example|sample|demo)/i.test(e)}function ze(e){return e.type.startsWith("assert")}var rf=new Set(["assertText","assertValue","assertCount","assertUrl","assertNotVisible","assertChecked","assertNotChecked","assertAttribute","assertDisabled","assertEnabled"]);function nf(e){return rf.has(e.type)}function of(e,t,r){!t.implemented||e.length===0||e.some(n=>ze(n))||r({message:"Test has zero assertion steps \u2014 cannot verify expectedOutcome. Add assert.* steps.",rule:"no-assertions",step:void 0})}function sf(e,t,r){if(!t.implemented||e.length<=3)return;let n=e.filter(i=>ze(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 Tn(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 af(e,t,r){e.forEach((n,o)=>{if(n.type!=="click")return;let i=Tn(n);if(i==null)return;let s=e.slice(o+1,o+4);s.find(c=>c.type==="assertVisible"&&Tn(c)===i)==null||s.some(c=>nf(c)||ze(c)&&Tn(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 lf=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 An(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=3&&!lf.has(t))}function cf(e){let t=e.label==null?[]:An(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,...An(n)]}function uf(e,t,r){if(!t.implemented||e.length===0)return;let n=new Set(An(t.expectedOutcome));if(n.size===0)return;let o=e.filter(s=>ze(s));if(o.length===0)return;o.some(s=>cf(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 df=/save|submit|create|delete|remove|send|invite|update|confirm|publish|apply|pay|subscribe|upgrade|cancel|archive|rename/i;function Ai(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 df.test(r)}function pf(e,t,r){!t.implemented||t.spec.uiOnly===!0||e.forEach((n,o)=>{if(!Ai(n)||"uiOnly"in n&&n.uiOnly===!0)return;let i=e.slice(o+1),s=i.findIndex(u=>Ai(u)),a=s===-1?i.length:s;i.slice(0,a).some(u=>u.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 mf(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])=>Ii(a)&&$i(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 ff(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 gf(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(", "),u=[...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(({ ${u} }) => \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 yf=[Gm,Km,gf,Jm,Xm,Ym,Qm,Zm,ef,of,sf,af,uf,pf,mf,ff];import Mf from"picomatch";import{execFileSync as hf,spawnSync as wf}from"child_process";function K(e,t){return hf("git",[...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}function ji(e,t){let r=wf("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 Ni from"remeda";var Di=[["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"]],bf=new Map([["button","click"],["link","navigate"],["textbox","input"],["searchbox","input"],["combobox","select"],["listbox","select"]]),vf=[[/(?:^|[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 or({filePath:e,source:t}){let r=b.createSourceFile(e,t,b.ScriptTarget.Latest,!0,b.ScriptKind.TSX);return r.statements.flatMap(n=>Sf({filePath:e,sf:r,stmt:n}))}function Sf({filePath:e,sf:t,stmt:r}){let n=Pf(r);if(n==null||kf(n))return[];let o=Oi(r,t).map(i=>({id:`${e}#${n}.${i.kind}[${i.label}]`,line:i.line}));return Ni.uniqueBy(o,i=>i.id)}function kf(e){return e.endsWith("Fragment")||e.endsWith("Skeleton")||/^use[A-Z]/.test(e)||/^[A-Z][A-Z0-9_]*$/.test(e)}function Pf(e){if(b.isExportAssignment(e))return Rf(e.expression);if(!xf(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 Rf(e){return b.isIdentifier(e)?e.text:(b.isFunctionExpression(e)||b.isClassExpression(e))&&e.name!=null?e.name.text:"default"}function xf(e){if(!b.canHaveModifiers(e))return!1;let t=b.getModifiers(e);return t!=null&&t.some(r=>r.kind===b.SyntaxKind.ExportKeyword)}function Oi(e,t){let r=Ef(e,t),n=e.getChildren(t).flatMap(o=>Oi(o,t));return r==null?n:[r,...n]}function Ef(e,t){let r=Cf(e);if(r==null)return null;let n=Tf(r);if(n==null)return null;let o=Nf(r,n);return o==null?null:{kind:n,label:o,line:Ff(t,e.getStart(t))}}function Cf(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 Tf({attrs:e,tag:t}){let r=ue(e,"role");return r!=null?bf.get(r)??null:If(t,e)??$f(t)??jf(e)}var Af=new Map([["button",()=>"click"],["a",e=>ue(e,"href")==null?null:"navigate"],["input",e=>ue(e,"type")==="file"?"upload":"input"],["textarea",()=>"input"],["select",()=>"select"],["form",()=>"submit"]]);function If(e,t){return Af.get(e)?.(t)??null}function $f(e){return/^[A-Z]/.test(e)?vf.find(([t])=>t.test(e))?.[1]??null:null}function jf(e){return Di.find(([t])=>Lf(e,t))?.[1]??null}function Nf({attrs:e,children:t,tag:r},n){return n==="navigate"?ue(e,"href")??ue(e,"to"):ue(e,"aria-label")??ue(e,"label")??ue(e,"title")??ue(e,"name")??ue(e,"placeholder")??(Df(r)?void 0:Vf(t))??Of(e,n)}function Df(e){return e==="input"||e==="textarea"||e==="select"}function Of(e,t){let r=Di.find(([,o])=>o===t)?.[0];if(r==null)return;let n=_f(e,r);if(n!=null){if(b.isIdentifier(n))return n.text;if(b.isArrowFunction(n)||b.isFunctionExpression(n))return Li(n.body)}}function Li(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,Li)}function Lf(e,t){return e.properties.some(r=>b.isJsxAttribute(r)&&b.isIdentifier(r.name)&&r.name.text===t)}function _i(e,t){return e.properties.find(r=>b.isJsxAttribute(r)&&b.isIdentifier(r.name)&&r.name.text===t)}function ue(e,t){let r=_i(e,t);return r==null?void 0:Uf(r.initializer)}function _f(e,t){let r=_i(e,t);if(!(r?.initializer==null||!b.isJsxExpression(r.initializer)))return r.initializer.expression}function Uf(e){if(e==null)return"";if(b.isStringLiteral(e))return e.text;if(b.isJsxExpression(e))return Vi(e.expression)}function Vf(e){let t=e.flatMap(r=>Ui(r)).join(" ").trim();return t.length===0?void 0:t}function Ui(e){if(b.isJsxText(e)){let t=e.text.trim();return t.length===0?[]:[t]}if(b.isJsxExpression(e)){let t=Vi(e.expression);return t==null?[]:[t]}return b.isJsxElement(e)?e.children.flatMap(t=>Ui(t)):[]}function Vi(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 Ff(e,t){return e.getLineAndCharacterOfPosition(t).line+1}var Hf=ir.join(".ripplo","coverage.d.ts");function Ge({cwd:e}){Bf({cwd:e,ignorePaths:xe})}function Bf({cwd:e,ignorePaths:t}){let r=Ke({cwd:e,ignorePaths:t});zf({content:qf(r),cwd:e})}function Ke({cwd:e,ignorePaths:t}){let n=Wf({cwd:e,ignorePaths:t}).flatMap(o=>In({cwd:e,file:o}));return[...new Set(n)].sort((o,i)=>o.localeCompare(i))}function Wf({cwd:e,ignorePaths:t}){let r=K(["ls-files","--cached","--others","--exclude-standard","-z"],e),n=Mf([...t]);return r.split("\0").filter(o=>o.length>0&&/\.(tsx|jsx)$/.test(o)).filter(o=>!n(o)).filter(o=>vt.existsSync(ir.join(e,o)))}function In({cwd:e,file:t}){let r=vt.readFileSync(ir.join(e,t),"utf8");return or({filePath:t,source:r}).map(n=>n.id)}function qf(e){let t=`// GENERATED \u2014 do not edit
262
262
  import "@ripplo/testing";
263
263
 
264
264
  declare module "@ripplo/testing" {
@@ -269,23 +269,26 @@ declare module "@ripplo/testing" {
269
269
  `:`${t}${r}
270
270
  }
271
271
  }
272
- `}function Ff({content:e,cwd:t}){let r=nr.join(t,Lf);bt.existsSync(r)&&bt.readFileSync(r,"utf8")===e||bt.writeFileSync(r,e)}import{readdir as Mf,stat as Hf}from"fs/promises";import vt from"path";import{createJiti as Bf}from"jiti";var Wf=["getObservers","getPreconditions","getTests","getUnimplemented"];function qf(e){return e==null||typeof e!="object"?!1:Wf.every(t=>typeof Reflect.get(e,t)=="function")}function zf(e){return e===null?"null":Array.isArray(e)?"array":typeof e}var Gf=new Set(["debug",".local"]),_i=new Map;async function P(e){let t=vt.join(e,".ripplo","index.ts"),r=vt.join(e,".ripplo"),n=await Jf(r),o=_i.get(e);if(o!=null&&o.fingerprint===n)return o.result;let i=await Kf(t,r);return _i.set(e,{fingerprint:n,result:i}),i}async function Kf(e,t){try{let n=await Bf(import.meta.url,{moduleCache:!1,sourceMaps:!0}).import(e),o=n!=null&&typeof n=="object"&&"default"in n?Reflect.get(n,"default"):n;return qf(o)?{builder:o,ok:!0,result:tr(o)}:{error:`${e} must default-export a RipploBuilder (got ${zf(o)})`,ok:!1}}catch(r){return{error:Yf(r,t),ok:!1}}}async function Jf(e){let t=[];return await Ui(e,e,t),t.sort((r,n)=>r.localeCompare(n)),t.join(`
273
- `)}async function Ui(e,t,r){let n=await Mf(t,{withFileTypes:!0}).catch(()=>[]);await Promise.all(n.map(async o=>{if(o.isDirectory()){if(Gf.has(o.name))return;await Ui(e,vt.join(t,o.name),r);return}let i=vt.join(t,o.name),s=await Hf(i).catch(()=>{});s!=null&&r.push(`${vt.relative(e,i)}:${String(s.mtimeMs)}:${String(s.size)}`)}))}var Xf=/\(?([^\s()]{1,500}\.ts):(\d{1,10}):(\d{1,10})\)?$/;function Yf(e,t){if(!(e instanceof Error))return String(e);let r=Qf(e.stack,t);return r==null?e.message:`${r} \u2014 ${e.message}`}function Qf(e,t){if(e==null)return;let n=e.split(`
274
- `).map(a=>Xf.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 Vi(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 Fi(e){let t=process.cwd(),r=await P(t);if(r.ok||(process.stderr.write(`Compilation failed: ${r.error}
272
+ `}function zf({content:e,cwd:t}){let r=ir.join(t,Hf);vt.existsSync(r)&&vt.readFileSync(r,"utf8")===e||vt.writeFileSync(r,e)}import{readdir as Yf,stat as Qf}from"fs/promises";import kt from"path";import{createJiti as Zf}from"jiti";import Gf from"fs";import St from"path";import Je from"typescript";function Fi(e){let t=St.join(e,"index.ts"),r=Xf(e);Gf.mkdirSync(St.dirname(r.tsBuildInfoFile??""),{recursive:!0});let n=Je.createIncrementalCompilerHost(r),o=Je.createIncrementalProgram({host:n,options:r,rootNames:[t]}),i=[...o.getSyntacticDiagnostics(),...o.getSemanticDiagnostics()];o.emit();let s=i.filter(c=>Kf(c,e));if(s.length===0)return{diagnostics:[],ok:!0};let a={getCanonicalFileName:c=>c,getCurrentDirectory:()=>St.dirname(e),getNewLine:()=>`
273
+ `};return{diagnostics:Je.formatDiagnosticsWithColorAndContext(s,a).split(`
274
+ `).filter(c=>c.length>0),ok:!1}}function Kf(e,t){let r=e.file?.fileName;return r==null?!0:r.startsWith(t)}var Jf=St.join(".local","tsbuildinfo");function Xf(e){return{allowImportingTsExtensions:!0,allowJs:!1,esModuleInterop:!0,incremental:!0,module:Je.ModuleKind.Preserve,moduleResolution:Je.ModuleResolutionKind.Bundler,noEmit:!0,resolveJsonModule:!0,skipLibCheck:!0,strict:!1,target:Je.ScriptTarget.ES2022,tsBuildInfoFile:St.join(e,Jf)}}var eg=["getObservers","getPreconditions","getTests","getUnimplemented"];function tg(e){return e==null||typeof e!="object"?!1:eg.every(t=>typeof Reflect.get(e,t)=="function")}function rg(e){return e===null?"null":Array.isArray(e)?"array":typeof e}var ng=new Set(["debug",".local"]),Mi=new Map;async function P(e){let t=kt.join(e,".ripplo","index.ts"),r=kt.join(e,".ripplo"),n=await ig(r),o=Mi.get(e);if(o!=null&&o.fingerprint===n)return o.result;let i=await og(t,r);return Mi.set(e,{fingerprint:n,result:i}),i}async function og(e,t){let r=Fi(t);if(!r.ok)return{error:["TypeScript errors in .ripplo/:",...r.diagnostics].join(`
275
+ `),ok:!1};try{let o=await Zf(import.meta.url,{fsCache:!1,moduleCache:!1,sourceMaps:!0}).import(e),i=o!=null&&typeof o=="object"&&"default"in o?Reflect.get(o,"default"):o;return tg(i)?{builder:i,ok:!0,result:nr(i)}:{error:`${e} must default-export a RipploBuilder (got ${rg(i)})`,ok:!1}}catch(n){return{error:ag(n,t),ok:!1}}}async function ig(e){let t=[];return await Hi(e,e,t),t.sort((r,n)=>r.localeCompare(n)),t.join(`
276
+ `)}async function Hi(e,t,r){let n=await Yf(t,{withFileTypes:!0}).catch(()=>[]);await Promise.all(n.map(async o=>{if(o.isDirectory()){if(ng.has(o.name))return;await Hi(e,kt.join(t,o.name),r);return}let i=kt.join(t,o.name),s=await Qf(i).catch(()=>{});s!=null&&r.push(`${kt.relative(e,i)}:${String(s.mtimeMs)}:${String(s.size)}`)}))}var sg=/\(?([^\s()]{1,500}\.ts):(\d{1,10}):(\d{1,10})\)?$/;function ag(e,t){if(!(e instanceof Error))return String(e);let r=lg(e.stack,t);return r==null?e.message:`${r} \u2014 ${e.message}`}function lg(e,t){if(e==null)return;let n=e.split(`
277
+ `).map(a=>sg.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 Bi(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).`}function $n(e){process.stderr.write(`Compilation failed: ${e}
275
278
  `),process.stderr.write(`${w("create","DSL authoring + lint rules")}
276
- `),process.exit(1)),e.check){let n=await Zt({cwd:t}),o=await er({compiled:r.result,cwd:t,existing:n});if(o==="match"){process.stdout.write(`${le} is up to date
279
+ `),process.exit(1)}function Wi(e){return e instanceof Error?e.message:String(e)}async function qi(e){let t=process.cwd(),r=await P(t);if(r.ok||$n(r.error),e.check){let n=await tr({cwd:t}),o=await rr({compiled:r.result,cwd:t,existing:n}).catch(s=>$n(Wi(s)));if(o==="match"){process.stdout.write(`${le} is up to date
277
280
  `);return}let i=o==="missing"?"missing":"out of date";process.stderr.write(`${le} is ${i} \u2014 run \`ripplo compile\` and commit the result
278
281
  `),process.stderr.write(`${w("setup")}
279
- `),process.exit(1)}await ce({cwd:t,result:r.result}),Ge({cwd:t}),process.stdout.write(`wrote ${le}
280
- `)}import fe from"process";import Zf from"fs";import eg from"path";import tg from"picomatch";function Mi({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(Ke({cwd:t,ignorePaths:r})),o=Wi(e),i=rg({cwd:t,ignorePaths:r});return Bi({acknowledged:o,allStatements:n,unacked:i})}function Hi({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(Ke({cwd:t,ignorePaths:r})),o=Wi(e);return Bi({acknowledged:o,allStatements:n,unacked:n})}function Bi({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 Wi(e){return new Set(e.tests.flatMap(t=>t.coverage))}function rg({cwd:e,ignorePaths:t}){let r=ng({cwd:e,ignorePaths:t}),n=new Set(r.flatMap(i=>og({cwd:e,file:i}))),o=new Set(r.flatMap(i=>ig({cwd:e,file:i})?Tn({cwd:e,file:i}):[]));return new Set([...o].filter(i=>!n.has(i)))}function ng({cwd:e,ignorePaths:t}){let r=K(["diff","--name-only","HEAD","-z"],e),n=K(["ls-files","--others","--exclude-standard","-z"],e),o=tg([...t]);return[...new Set([...r.split("\0"),...n.split("\0")])].filter(i=>i.length>0&&/\.(tsx|jsx)$/.test(i)).filter(i=>!o(i))}function og({cwd:e,file:t}){let r=Ai(`HEAD:${t}`,e);return r==null?[]:rr({filePath:t,source:r}).map(n=>n.id)}function ig({cwd:e,file:t}){return Zf.existsSync(eg.join(e,t))}async function qi(){let e=fe.cwd(),t=await P(e);t.ok||(fe.stderr.write(`Compilation failed: ${t.error}
281
- `),fe.exit(1));let r=Ke({cwd:e,ignorePaths:xe}),n=Hi({compileResult:t.result,cwd:e,ignorePaths:xe}),o=n.filter(a=>a.kind==="unacknowledged"),i=n.filter(a=>a.kind==="stale"),s=r.length-o.length;fe.stdout.write(`Coverage: ${String(s)}/${String(r.length)} statements acknowledged
282
+ `),process.exit(1)}try{await ce({cwd:t,result:r.result})}catch(n){$n(Wi(n))}Ge({cwd:t}),process.stdout.write(`wrote ${le}
283
+ `)}import fe from"process";import cg from"fs";import ug from"path";import dg from"picomatch";function zi({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(Ke({cwd:t,ignorePaths:r})),o=Ji(e),i=pg({cwd:t,ignorePaths:r});return Ki({acknowledged:o,allStatements:n,unacked:i})}function Gi({compileResult:e,cwd:t,ignorePaths:r}){let n=new Set(Ke({cwd:t,ignorePaths:r})),o=Ji(e);return Ki({acknowledged:o,allStatements:n,unacked:n})}function Ki({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 Ji(e){return new Set(e.tests.flatMap(t=>t.coverage))}function pg({cwd:e,ignorePaths:t}){let r=mg({cwd:e,ignorePaths:t}),n=new Set(r.flatMap(i=>fg({cwd:e,file:i}))),o=new Set(r.flatMap(i=>gg({cwd:e,file:i})?In({cwd:e,file:i}):[]));return new Set([...o].filter(i=>!n.has(i)))}function mg({cwd:e,ignorePaths:t}){let r=K(["diff","--name-only","HEAD","-z"],e),n=K(["ls-files","--others","--exclude-standard","-z"],e),o=dg([...t]);return[...new Set([...r.split("\0"),...n.split("\0")])].filter(i=>i.length>0&&/\.(tsx|jsx)$/.test(i)).filter(i=>!o(i))}function fg({cwd:e,file:t}){let r=ji(`HEAD:${t}`,e);return r==null?[]:or({filePath:t,source:r}).map(n=>n.id)}function gg({cwd:e,file:t}){return cg.existsSync(ug.join(e,t))}async function Xi(){let e=fe.cwd(),t=await P(e);t.ok||(fe.stderr.write(`Compilation failed: ${t.error}
284
+ `),fe.exit(1));let r=Ke({cwd:e,ignorePaths:xe}),n=Gi({compileResult:t.result,cwd:e,ignorePaths:xe}),o=n.filter(a=>a.kind==="unacknowledged"),i=n.filter(a=>a.kind==="stale"),s=r.length-o.length;fe.stdout.write(`Coverage: ${String(s)}/${String(r.length)} statements acknowledged
282
285
  `),o.length>0&&(fe.stdout.write(`
283
286
  Unacknowledged (${String(o.length)}):
284
287
  `),o.forEach(a=>fe.stdout.write(` ${a.id}
285
288
  `))),i.length>0&&(fe.stdout.write(`
286
289
  Stale claims (${String(i.length)}):
287
290
  `),i.forEach(a=>fe.stdout.write(` ${a.id}
288
- `))),n.length>0&&fe.exit(1)}import{graphql as mg}from"gql.tada";import zi from"fs";import An from"path";function Gi(e){let t=zi.realpathSync(e),r=t,n=An.dirname(r);for(;n!==r;){if(zi.existsSync(An.join(r,".git")))return r;r=n,n=An.dirname(r)}return t}function W(e){let t=fn(e),r=He(),n=ie();if(n==null)throw new Error("ripplo: not authenticated. Run `ripplo auth login`.");return{appUrl:r.appUrl,cwd:Gi(e),engineUrl:r.engineUrl,projectId:ri()??t.projectId,ripploServerUrl:ee(),token:n,webhookSecret:r.webhookSecret}}import ge from"fs";var sg="dev.pid";function Ji(e){return mt(e,sg)}function Xe(e){let t=Ji(e);if(!ge.existsSync(t))return!1;let r=ge.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}}var Je=class extends Error{pid;cwd;constructor({cwd:t,pid:r}){super(`ripplo watch already running (pid ${String(r)})`),this.name="DevLockHeldError",this.pid=r,this.cwd=t}};function Xi(e){pt(e);let t=Ji(e);ag({cwd:e,path:t});let r=!1;return()=>{if(!r){r=!0;try{let n=ge.readFileSync(t,"utf8").trim();Number.parseInt(n,10)===process.pid&&ge.unlinkSync(t)}catch{}}}}function ag({cwd:e,path:t}){let r=()=>{try{let o=ge.openSync(t,"wx");return ge.writeSync(o,String(process.pid)),ge.closeSync(o),"ok"}catch(o){if(!lg(o))throw o;let i=Ki(t);if(i!=null&&cg(i))throw new Je({cwd:e,pid:i});return ge.unlinkSync(t),"retry"}};if(r()==="ok"||r()==="ok")return;let n=Ki(t);throw n!=null?new Je({cwd:e,pid:n}):new Error("failed to acquire dev lock")}function lg(e){if(!(e instanceof Error)||!("code"in e))return!1;let{code:t}=e;return t==="EEXIST"}function Ki(e){try{let t=ge.readFileSync(e,"utf8").trim(),r=Number.parseInt(t,10);return Number.isFinite(r)&&r>0?r:null}catch{return null}}function cg(e){try{return process.kill(e,0),!0}catch{return!1}}import ug from"fs";import In from"path";var dg=["MERGE_HEAD","rebase-merge","rebase-apply","CHERRY_PICK_HEAD","REVERT_HEAD"];function or(e){let t=pg(e);return t==null?!1:dg.some(r=>ug.existsSync(In.join(t,r)))}function pg(e){try{let t=K(["rev-parse","--git-dir"],e).trim();return t.length===0?null:In.isAbsolute(t)?t:In.resolve(e,t)}catch{return null}}var fg=mg(`
291
+ `))),n.length>0&&fe.exit(1)}import{graphql as Pg}from"gql.tada";import Yi from"fs";import jn from"path";function Qi(e){let t=Yi.realpathSync(e),r=t,n=jn.dirname(r);for(;n!==r;){if(Yi.existsSync(jn.join(r,".git")))return r;r=n,n=jn.dirname(r)}return t}function W(e){let t=yn(e),r=He(),n=ie();if(n==null)throw new Error("ripplo: not authenticated. Run `ripplo auth login`.");return{appUrl:r.appUrl,cwd:Qi(e),engineUrl:r.engineUrl,projectId:ii()??t.projectId,ripploServerUrl:ee(),token:n,webhookSecret:r.webhookSecret}}import ge from"fs";var yg="dev.pid";function es(e){return ft(e,yg)}function Ye(e){let t=es(e);if(!ge.existsSync(t))return!1;let r=ge.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}}var Xe=class extends Error{pid;cwd;constructor({cwd:t,pid:r}){super(`ripplo watch already running (pid ${String(r)})`),this.name="DevLockHeldError",this.pid=r,this.cwd=t}};function ts(e){mt(e);let t=es(e);hg({cwd:e,path:t});let r=!1;return()=>{if(!r){r=!0;try{let n=ge.readFileSync(t,"utf8").trim();Number.parseInt(n,10)===process.pid&&ge.unlinkSync(t)}catch{}}}}function hg({cwd:e,path:t}){let r=()=>{try{let o=ge.openSync(t,"wx");return ge.writeSync(o,String(process.pid)),ge.closeSync(o),"ok"}catch(o){if(!wg(o))throw o;let i=Zi(t);if(i!=null&&bg(i))throw new Xe({cwd:e,pid:i});return ge.unlinkSync(t),"retry"}};if(r()==="ok"||r()==="ok")return;let n=Zi(t);throw n!=null?new Xe({cwd:e,pid:n}):new Error("failed to acquire dev lock")}function wg(e){if(!(e instanceof Error)||!("code"in e))return!1;let{code:t}=e;return t==="EEXIST"}function Zi(e){try{let t=ge.readFileSync(e,"utf8").trim(),r=Number.parseInt(t,10);return Number.isFinite(r)&&r>0?r:null}catch{return null}}function bg(e){try{return process.kill(e,0),!0}catch{return!1}}import vg from"fs";import Nn from"path";var Sg=["MERGE_HEAD","rebase-merge","rebase-apply","CHERRY_PICK_HEAD","REVERT_HEAD"];function sr(e){let t=kg(e);return t==null?!1:Sg.some(r=>vg.existsSync(Nn.join(t,r)))}function kg(e){try{let t=K(["rev-parse","--git-dir"],e).trim();return t.length===0?null:Nn.isAbsolute(t)?t:Nn.resolve(e,t)}catch{return null}}var Rg=Pg(`
289
292
  query DevSessionCheckHealth($projectId: String!, $cwd: String!) {
290
293
  project(id: $projectId) {
291
294
  id
@@ -294,25 +297,25 @@ Stale claims (${String(i.length)}):
294
297
  }
295
298
  }
296
299
  }
297
- `);function Yi(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 Qi(e){let t=Xe(e),r=or(e),n;try{n=W(e)}catch{return{gitMidOperation:r,status:t?"starting":"missing",type:"dev-session"}}return(await h({config:n,document:fg,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 Zi(e){switch(e.type){case"settings":return wg(e);case"env-files":return bg(e);case"token":return vg(e);case"dev-server":return Sg(e);case"dev-session":return Yi(e);case"preconditions":return Rg(e);case"webhook-verification":return kg(e);case"preconditions-validation":return xg(e);case"workflows":return Eg(e);case"browser":return Pg(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 gg(e);case"lockfile":return yg(e);case"pre-commit-hook":return hg(e)}}function gg(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 yg(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 hg(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 wg(e){return e.valid?"\u2713 Settings: Project configured":`\u2717 Settings: Missing fields: ${e.missingFields.join(", ")}`}function bg(e){return e.missing.length===0?"\u2713 Env files: declared files present":`\u2717 Env files: declared in .ripplo/project.json but missing:
300
+ `);function rs(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 ns(e){let t=Ye(e),r=sr(e),n;try{n=W(e)}catch{return{gitMidOperation:r,status:t?"starting":"missing",type:"dev-session"}}return(await h({config:n,document:Rg,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 os(e){switch(e.type){case"settings":return Tg(e);case"env-files":return Ag(e);case"token":return Ig(e);case"dev-server":return $g(e);case"dev-session":return rs(e);case"preconditions":return Dg(e);case"webhook-verification":return jg(e);case"preconditions-validation":return Og(e);case"workflows":return Lg(e);case"browser":return Ng(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 xg(e);case"lockfile":return Eg(e);case"pre-commit-hook":return Cg(e)}}function xg(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 Eg(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 Cg(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 Tg(e){return e.valid?"\u2713 Settings: Project configured":`\u2717 Settings: Missing fields: ${e.missingFields.join(", ")}`}function Ag(e){return e.missing.length===0?"\u2713 Env files: declared files present":`\u2717 Env files: declared in .ripplo/project.json but missing:
298
301
  ${e.missing.map(r=>` ${r}`).join(`
299
302
  `)}
300
- 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 vg(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 ${ee()} to validate token.`}}function Sg(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 kg(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 Pg(e){return e.installed?"\u2713 Browser: Chromium installed":"\u2717 Browser: Chromium not installed. Run: npx playwright install chromium"}function Rg(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 xg(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"}
303
+ 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 Ig(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 ${ee()} to validate token.`}}function $g(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 jg(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 Ng(e){return e.installed?"\u2713 Browser: Chromium installed":"\u2717 Browser: Chromium not installed. Run: npx playwright install chromium"}function Dg(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 Og(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"}
301
304
  ${t.join(`
302
- `)}`}function Eg(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=>Cg(r));return`\u2717 Tests: ${String(e.invalidNames.length)} invalid
305
+ `)}`}function Lg(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=>_g(r));return`\u2717 Tests: ${String(e.invalidNames.length)} invalid
303
306
  ${t.join(`
304
- `)}`}function Cg(e){let t=e.errors.map(r=>" - "+(r.path===""?"":r.path+": ")+r.message);return" "+e.name+`:
307
+ `)}`}function _g(e){let t=e.errors.map(r=>" - "+(r.path===""?"":r.path+": ")+r.message);return" "+e.name+`:
305
308
  `+t.join(`
306
- `)}import jn from"fs";import Ng from"path";import{chromium as Dg}from"playwright";import Tg from"fs";import Ag from"path";async function es(e){let t=Ag.join(e,".ripplo","index.ts");if(!Tg.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=He();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 $n(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 ts({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 Ig}from"gql.tada";var $g=Ig(`
309
+ `)}import On from"fs";import Bg from"path";import{chromium as Wg}from"playwright";import Ug from"fs";import Vg from"path";async function is(e){let t=Vg.join(e,".ripplo","index.ts");if(!Ug.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=He();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 Dn(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 ss({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 Fg}from"gql.tada";var Mg=Fg(`
307
310
  query DoctorAuthViewer {
308
311
  currentUser {
309
312
  name
310
313
  email
311
314
  }
312
315
  }
313
- `),jg="Failed to connect to Ripplo server";async function rs({serverUrl:e,token:t}){try{let r=await h({config:Pe({serverUrl:e,token:t}),document:$g,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(jg)?{kind:"unreachable"}:{kind:"invalid"}}}function ns(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 os(e){let t=await _g(e),r={missing:hn(e),type:"env-files"},n=await Ug(),o=Vg(),i=await P(e),s=Fg(i),a=Bg(i),l=await Og(e,i),c=Lg(e),u=await Wg(t,i);return[t,r,n,...u,s,a,l,c,o]}async function Og(e,t){if(!t.ok)return{status:"missing",type:"lockfile"};let r=await Zt({cwd:e});return{status:await er({compiled:t.result,cwd:e,existing:r}),type:"lockfile"}}function Lg(e){let t=Ng.join(e,".git","hooks","pre-commit");return jn.existsSync(t)?{installed:jn.readFileSync(t,"utf8").includes("ripplo compile --check"),type:"pre-commit-hook"}:{installed:!1,type:"pre-commit-hook"}}async function _g(e){let t=await es(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 Ug(){let e=ie();if(e==null||e.length===0)return{email:void 0,status:"missing",type:"token"};let t=await rs({serverUrl:ee(),token:e});return t.kind==="valid"?{email:t.email,status:"valid",type:"token"}:{email:void 0,status:t.kind,type:"token"}}function Vg(){let e=Dg.executablePath();return{installed:jn.existsSync(e),type:"browser"}}function Fg(e){if(!e.ok)return{errorCount:1,errors:[{message:e.error,path:""}],found:!1,type:"preconditions-validation",valid:!1};let t=Mg(e.result.preconditions,e.result.tests);return{errorCount:t.length,errors:t,found:!0,type:"preconditions-validation",valid:t.length===0}}function Mg(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}`})})}),Hg(e).forEach(o=>{r.push({message:o,path:"preconditions"})}),r}function Hg(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 Bg(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 Wg(e,t){if(!e.valid||!t.ok)return[];let r;try{let a=He();r={appUrl:a.appUrl,engineUrl:a.engineUrl,webhookSecret:a.webhookSecret}}catch{return[]}let n=[],o=await $n(r.appUrl)==null;n.push({appUrl:r.appUrl,reachable:o,type:"dev-server"});let i=await Qi(process.cwd());n.push(i);let s=await qg(r,t);return n.push(...s),n}async function qg(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=Gg(e.appUrl,e.engineUrl);if(i==null)return[o];let s=await $n(i)==null,a=[];if(a.push({configured:!0,count:r,endpointReachable:s,type:"preconditions"}),is(e.engineUrl)&&a.push({reachable:s,type:"engine-endpoint",url:i}),!s)return a;let l=await ts({appUrl:e.appUrl,engineUrl:e.engineUrl});a.push({rejectsUnsigned:l==null,type:"webhook-verification"});let c=await zg({engineUrl:i,webhookSecret:e.webhookSecret});return a.push({status:c,type:"adapter-enabled",url:i}),a}async function zg({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",...Se({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 is(e){return e.startsWith("http://")||e.startsWith("https://")}function Gg(e,t){return is(t)?t:`${e}${t}`}async function ss(){let e=process.cwd(),t=await os(e),r=t.map(o=>Zi(o));process.stdout.write(r.join(`
316
+ `),Hg="Failed to connect to Ripplo server";async function as({serverUrl:e,token:t}){try{let r=await h({config:Pe({serverUrl:e,token:t}),document:Mg,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(Hg)?{kind:"unreachable"}:{kind:"invalid"}}}function ls(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 cs(e){let t=await Gg(e),r={missing:bn(e),type:"env-files"},n=await Kg(),o=Jg(),i=await P(e),s=Xg(i),a=Zg(i),l=await qg(e,i),c=zg(e),u=await ey(t,i);return[t,r,n,...u,s,a,l,c,o]}async function qg(e,t){if(!t.ok)return{status:"missing",type:"lockfile"};let r=await tr({cwd:e});return{status:await rr({compiled:t.result,cwd:e,existing:r}),type:"lockfile"}}function zg(e){let t=Bg.join(e,".git","hooks","pre-commit");return On.existsSync(t)?{installed:On.readFileSync(t,"utf8").includes("ripplo compile --check"),type:"pre-commit-hook"}:{installed:!1,type:"pre-commit-hook"}}async function Gg(e){let t=await is(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 Kg(){let e=ie();if(e==null||e.length===0)return{email:void 0,status:"missing",type:"token"};let t=await as({serverUrl:ee(),token:e});return t.kind==="valid"?{email:t.email,status:"valid",type:"token"}:{email:void 0,status:t.kind,type:"token"}}function Jg(){let e=Wg.executablePath();return{installed:On.existsSync(e),type:"browser"}}function Xg(e){if(!e.ok)return{errorCount:1,errors:[{message:e.error,path:""}],found:!1,type:"preconditions-validation",valid:!1};let t=Yg(e.result.preconditions,e.result.tests);return{errorCount:t.length,errors:t,found:!0,type:"preconditions-validation",valid:t.length===0}}function Yg(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}`})})}),Qg(e).forEach(o=>{r.push({message:o,path:"preconditions"})}),r}function Qg(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 Zg(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 ey(e,t){if(!e.valid||!t.ok)return[];let r;try{let a=He();r={appUrl:a.appUrl,engineUrl:a.engineUrl,webhookSecret:a.webhookSecret}}catch{return[]}let n=[],o=await Dn(r.appUrl)==null;n.push({appUrl:r.appUrl,reachable:o,type:"dev-server"});let i=await ns(process.cwd());n.push(i);let s=await ty(r,t);return n.push(...s),n}async function ty(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=ny(e.appUrl,e.engineUrl);if(i==null)return[o];let s=await Dn(i)==null,a=[];if(a.push({configured:!0,count:r,endpointReachable:s,type:"preconditions"}),us(e.engineUrl)&&a.push({reachable:s,type:"engine-endpoint",url:i}),!s)return a;let l=await ss({appUrl:e.appUrl,engineUrl:e.engineUrl});a.push({rejectsUnsigned:l==null,type:"webhook-verification"});let c=await ry({engineUrl:i,webhookSecret:e.webhookSecret});return a.push({status:c,type:"adapter-enabled",url:i}),a}async function ry({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",...Se({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 us(e){return e.startsWith("http://")||e.startsWith("https://")}function ny(e,t){return us(t)?t:`${e}${t}`}async function ds(){let e=process.cwd(),t=await cs(e),r=t.map(o=>os(o));process.stdout.write(r.join(`
314
317
  `)+`
315
- `);let n=t.some(o=>ns(o));process.exit(n?1:0)}import Jg from"crypto";import{graphql as Xg}from"gql.tada";import Nn from"fs";import Dn from"path";function ir(e){try{let t=Dn.join(Kg(e),"HEAD"),r=Nn.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 Kg(e){let t=Dn.join(e,".git");if(Nn.statSync(t).isDirectory())return t;let n=Nn.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 Dn.resolve(e,i)}var Yg=Xg(`
318
+ `);let n=t.some(o=>ls(o));process.exit(n?1:0)}import iy from"crypto";import{graphql as sy}from"gql.tada";import Ln from"fs";import _n from"path";function ar(e){try{let t=_n.join(oy(e),"HEAD"),r=Ln.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 oy(e){let t=_n.join(e,".git");if(Ln.statSync(t).isDirectory())return t;let n=Ln.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 _n.resolve(e,i)}var ay=sy(`
316
319
  mutation SyncDevSession(
317
320
  $projectId: String!
318
321
  $cwd: String!
@@ -331,13 +334,13 @@ ${t.join(`
331
334
  hooksPaused
332
335
  }
333
336
  }
334
- `);async function Ye(e){let t=Qg(e.compiled);return ey({config:e.config,cwd:e.cwd,payload:t})}async function ye(e,t){let r=await P(e);if(!r.ok)throw new Error(`DSL compilation failed: ${r.error}`);let n=await Ye({compiled:r.result,config:t,cwd:e});return{compiled:r.result,devSessionId:n.devSessionId}}function Qg(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 Zg(e){return Jg.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function ey({config:e,cwd:t,payload:r}){let n=Zg(r),o=ir(t),i=await h({config:e,document:Yg,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 St,readFragment as iy}from"gql.tada";import{createHash as as}from"crypto";import{mkdirSync as ty,readFileSync as On,writeFileSync as ry}from"fs";import sr from"path";var ny=[".ts",".tsx",".js",".jsx"];function Ee(e){let t=as("sha256");return t.update(K(["rev-parse","HEAD"],e)),t.update("\0"),t.update(K(["diff","HEAD"],e)),t.update("\0"),K(["ls-files","--others","--exclude-standard"],e).split(`
335
- `).filter(n=>n.length>0).filter(n=>ny.some(o=>n.endsWith(o))).toSorted((n,o)=>n.localeCompare(o)).forEach(n=>{t.update(n),t.update("\0"),t.update(oy(sr.join(e,n))),t.update("\0")}),t.digest("hex")}function ls(e){let t=sr.join(e,".ripplo","ripplo.lock");try{let r=On(t);return as("sha256").update(r).digest("hex")}catch{return null}}function Qe(e,t){try{return On(cs(e,t),"utf8").trim()}catch{return null}}function Ze(e,t,r){let n=cs(e,t);ty(sr.dirname(n),{recursive:!0}),ry(n,r)}function cs(e,t){return sr.join(e,".ripplo",".local",`${t}.hash`)}function oy(e){try{return On(e)}catch{return Buffer.alloc(0)}}import us from"figures";var Ne={cross:us.cross,tick:us.tick};var ps=St(`
337
+ `);async function Qe(e){let t=ly(e.compiled);return uy({config:e.config,cwd:e.cwd,payload:t})}async function ye(e,t){let r=await P(e);if(!r.ok)throw new Error(`DSL compilation failed: ${r.error}`);let n=await Qe({compiled:r.result,config:t,cwd:e});return{compiled:r.result,devSessionId:n.devSessionId}}function ly(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 cy(e){return iy.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function uy({config:e,cwd:t,payload:r}){let n=cy(r),o=ar(t),i=await h({config:e,document:ay,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 Pt,readFragment as gy}from"gql.tada";import{createHash as ps}from"crypto";import{mkdirSync as dy,readFileSync as Un,writeFileSync as py}from"fs";import lr from"path";var my=[".ts",".tsx",".js",".jsx"];function Ee(e){let t=ps("sha256");return t.update(K(["rev-parse","HEAD"],e)),t.update("\0"),t.update(K(["diff","HEAD"],e)),t.update("\0"),K(["ls-files","--others","--exclude-standard"],e).split(`
338
+ `).filter(n=>n.length>0).filter(n=>my.some(o=>n.endsWith(o))).toSorted((n,o)=>n.localeCompare(o)).forEach(n=>{t.update(n),t.update("\0"),t.update(fy(lr.join(e,n))),t.update("\0")}),t.digest("hex")}function ms(e){let t=lr.join(e,".ripplo","ripplo.lock");try{let r=Un(t);return ps("sha256").update(r).digest("hex")}catch{return null}}function Ze(e,t){try{return Un(fs(e,t),"utf8").trim()}catch{return null}}function et(e,t,r){let n=fs(e,t);dy(lr.dirname(n),{recursive:!0}),py(n,r)}function fs(e,t){return lr.join(e,".ripplo",".local",`${t}.hash`)}function fy(e){try{return Un(e)}catch{return Buffer.alloc(0)}}import gs from"figures";var Ne={cross:gs.cross,tick:gs.tick};var hs=Pt(`
336
339
  fragment WorkflowIdMCP on Workflow {
337
340
  id
338
341
  slug
339
342
  }
340
- `),sy=St(`
343
+ `),yy=Pt(`
341
344
  query ProjectWorkflowIdsMCP($projectId: String!, $cwd: String!) {
342
345
  project(id: $projectId) {
343
346
  id
@@ -349,13 +352,13 @@ ${t.join(`
349
352
  }
350
353
  }
351
354
  }
352
- `,[ps]),ay=St(`
355
+ `,[hs]),hy=Pt(`
353
356
  mutation SetProjectViewCLI($projectId: String!, $devSessionId: String!) {
354
357
  setProjectView(projectId: $projectId, devSessionId: $devSessionId) {
355
358
  id
356
359
  }
357
360
  }
358
- `),ly=St(`
361
+ `),wy=Pt(`
359
362
  mutation CreateRunMCP($workflowId: String!, $lockfileHash: String, $repoHash: String) {
360
363
  createRun(workflowId: $workflowId, lockfileHash: $lockfileHash, repoHash: $repoHash) {
361
364
  __typename
@@ -378,7 +381,7 @@ ${t.join(`
378
381
  }
379
382
  }
380
383
  }
381
- `),cy=St(`
384
+ `),by=Pt(`
382
385
  query RunStatusMCP($id: String!) {
383
386
  run(id: $id) {
384
387
  id
@@ -405,8 +408,8 @@ ${t.join(`
405
408
  }
406
409
  }
407
410
  }
408
- `);async function ar({config:e,ids:t,presynced:r}){let n=await uy({config:e,ids:t,presynced:r}),o=await Promise.all(n.map(async a=>{try{let l=await gy({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}
409
- ${w("setup","check auth + config")}`};let{entry:l,runId:c}=a;try{let u=await wy({config:e,runId:c}),m=fy({config:e,id:l.id,runId:c}),g=`.ripplo/debug/${c}/`;return{id:l.id,runId:c,summary:`View run: ${m}
411
+ `);async function cr({config:e,ids:t,presynced:r}){let n=await vy({config:e,ids:t,presynced:r}),o=await Promise.all(n.map(async a=>{try{let l=await xy({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}
412
+ ${w("setup","check auth + config")}`};let{entry:l,runId:c}=a;try{let u=await Ty({config:e,runId:c}),m=Ry({config:e,id:l.id,runId:c}),g=`.ripplo/debug/${c}/`;return{id:l.id,runId:c,summary:`View run: ${m}
410
413
  Debug artifacts: ${g}
411
414
  ${w("debug","read summary.txt, accessibility-tree, network.jsonl before guessing")}
412
415
 
@@ -416,10 +419,10 @@ ${a.summary}`).join(`
416
419
 
417
420
  ---
418
421
 
419
- `);return{results:i,summary:s}}async function uy({config:e,ids:t,presynced:r}){let n=r??await ye(e.cwd,e),o=await h({config:e,document:sy,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 h({config:e,document:ay,variables:{devSessionId:i.id,projectId:e.projectId}});let s=(i.workflows??[]).map(l=>iy(ps,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(u=>u.slug===l);if(c==null)throw new Error(dy({compiledSlugs:a,slug:l}));return{id:l,workflowId:c.id}})}function dy({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=py({compiledSlugs:e,limit:3,slug:t}),n=r.length>0?`
422
+ `);return{results:i,summary:s}}async function vy({config:e,ids:t,presynced:r}){let n=r??await ye(e.cwd,e),o=await h({config:e,document:yy,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 h({config:e,document:hy,variables:{devSessionId:i.id,projectId:e.projectId}});let s=(i.workflows??[]).map(l=>gy(hs,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(u=>u.slug===l);if(c==null)throw new Error(Sy({compiledSlugs:a,slug:l}));return{id:l,workflowId:c.id}})}function Sy({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=ky({compiledSlugs:e,limit:3,slug:t}),n=r.length>0?`
420
423
  Did you mean: ${r.join(", ")}?`:"";return`Test "${t}" is not registered in this dev session.${n}
421
- Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on demand \u2014 restarting the dev server will not help.)`}function py({compiledSlugs:e,limit:t,slug:r}){let n=new Set(r.split("-"));return e.map(i=>({candidate:i,score:my(n,i)})).filter(i=>i.score>0).toSorted((i,s)=>s.score-i.score).slice(0,t).map(i=>i.candidate)}function my(e,t){return t.split("-").filter(r=>e.has(r)).length}function fy({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 gy({config:e,workflowId:t}){let n=(await h({config:e,document:ly,variables:{lockfileHash:ls(e.cwd),repoHash:yy(e.cwd),workflowId:t}})).createRun;if(n==null)throw new Error("Failed to create run");if(n.__typename!=="Run")throw new Error(`Cannot create run: ${n.message}`);return n.id}function yy(e){try{return Ee(e)}catch{return null}}var hy=2e3,ds=150;async function wy({config:e,runId:t}){let r=0;for(;r<ds;){await Sy(hy),r+=1;let o=(await h({config:e,document:cy,variables:{id:t}})).run;if(o==null)throw new Error(`Run ${t} not found`);if(!(o.status==="pending"||o.status==="running"))return by({run:o,runId:t})}return`Run ${t} timed out after polling ${String(ds)} times.`}function by({run:e,runId:t}){let r=[`Run ${t}: ${e.status.toUpperCase()}`],n=vy(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"?Ne.tick:Ne.cross,s=o.detail==null?"":` \u2014 ${o.detail}`;r.push(` ${i} ${o.title} (${String(o.duration??0)}ms)${s}`),o.assertions.forEach(a=>{let l=a.status==="passed"?Ne.tick:Ne.cross,c=a.detail==null?"":` \u2014 ${a.detail}`;r.push(` ${l} ${a.description}${c}`)})}),r.join(`
422
- `)}function vy(e){if(e.caughtKind==null)return null;let t=e.workflow?.slug??"workflow";return e.caughtKind==="new_test"?` ${Ne.tick} ripplo caught a bug \u2014 new test "${t}" surfaced an issue in your app code`:` ${Ne.tick} ripplo caught a regression in "${t}"`}function Sy(e){return new Promise(t=>{setTimeout(t,e)})}import{graphql as ky}from"gql.tada";var Py=ky(`
424
+ Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on demand \u2014 restarting the dev server will not help.)`}function ky({compiledSlugs:e,limit:t,slug:r}){let n=new Set(r.split("-"));return e.map(i=>({candidate:i,score:Py(n,i)})).filter(i=>i.score>0).toSorted((i,s)=>s.score-i.score).slice(0,t).map(i=>i.candidate)}function Py(e,t){return t.split("-").filter(r=>e.has(r)).length}function Ry({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 xy({config:e,workflowId:t}){let n=(await h({config:e,document:wy,variables:{lockfileHash:ms(e.cwd),repoHash:Ey(e.cwd),workflowId:t}})).createRun;if(n==null)throw new Error("Failed to create run");if(n.__typename!=="Run")throw new Error(`Cannot create run: ${n.message}`);return n.id}function Ey(e){try{return Ee(e)}catch{return null}}var Cy=2e3,ys=150;async function Ty({config:e,runId:t}){let r=0;for(;r<ys;){await $y(Cy),r+=1;let o=(await h({config:e,document:by,variables:{id:t}})).run;if(o==null)throw new Error(`Run ${t} not found`);if(!(o.status==="pending"||o.status==="running"))return Ay({run:o,runId:t})}return`Run ${t} timed out after polling ${String(ys)} times.`}function Ay({run:e,runId:t}){let r=[`Run ${t}: ${e.status.toUpperCase()}`],n=Iy(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"?Ne.tick:Ne.cross,s=o.detail==null?"":` \u2014 ${o.detail}`;r.push(` ${i} ${o.title} (${String(o.duration??0)}ms)${s}`),o.assertions.forEach(a=>{let l=a.status==="passed"?Ne.tick:Ne.cross,c=a.detail==null?"":` \u2014 ${a.detail}`;r.push(` ${l} ${a.description}${c}`)})}),r.join(`
425
+ `)}function Iy(e){if(e.caughtKind==null)return null;let t=e.workflow?.slug??"workflow";return e.caughtKind==="new_test"?` ${Ne.tick} ripplo caught a bug \u2014 new test "${t}" surfaced an issue in your app code`:` ${Ne.tick} ripplo caught a regression in "${t}"`}function $y(e){return new Promise(t=>{setTimeout(t,e)})}import{graphql as jy}from"gql.tada";var Ny=jy(`
423
426
  query DevSessionCheckPreflight($projectId: String!, $cwd: String!) {
424
427
  project(id: $projectId) {
425
428
  id
@@ -430,36 +433,36 @@ Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on
430
433
  }
431
434
  `);function de(){try{return W(process.cwd())}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}
432
435
  `),process.stderr.write(`${w("setup")}
433
- `),process.exit(1)}}async function he(e){(await h({config:e,document:Py,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")}
434
- `),process.exit(1))}async function ms({id:e,runs:t}){let r=de();await he(r),process.stdout.write(`flake-detect "${e}" x${String(t)}...
435
- `);let n=await ye(r.cwd,r),o=await Promise.allSettled(Array.from({length:t},()=>ar({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 u=c.value.results[0];if(u==null){s++;return}if(u.summary.includes("FAILED")||u.summary.includes("ERROR")){s++;let m=u.summary.split(`
436
+ `),process.exit(1)}}async function he(e){(await h({config:e,document:Ny,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")}
437
+ `),process.exit(1))}async function ws({id:e,runs:t}){let r=de();await he(r),process.stdout.write(`flake-detect "${e}" x${String(t)}...
438
+ `);let n=await ye(r.cwd,r),o=await Promise.allSettled(Array.from({length:t},()=>cr({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 u=c.value.results[0];if(u==null){s++;return}if(u.summary.includes("FAILED")||u.summary.includes("ERROR")){s++;let m=u.summary.split(`
436
439
  `).find(g=>g.includes("FAILED")||g.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)
437
440
  `),a.size>0&&a.forEach((c,u)=>{process.stdout.write(` ${String(c)}x: ${u}
438
441
  `)}),s>0&&process.stderr.write(`${w("flake-detect","parallel safety + race conditions")}
439
- `),process.exit(s>0?1:0)}import lr from"fs";import{graphql as xy}from"gql.tada";import Ry from"fs";function Ce(e){return mt(e,"hooks-paused")}function U(e){return Ry.existsSync(Ce(e))||or(e)?!1:Xe(e)}var Ey=xy(`
442
+ `),process.exit(s>0?1:0)}import ur from"fs";import{graphql as Oy}from"gql.tada";import Dy from"fs";function Ce(e){return ft(e,"hooks-paused")}function U(e){return Dy.existsSync(Ce(e))||sr(e)?!1:Ye(e)}var Ly=Oy(`
440
443
  mutation CliSetHooksPaused($projectId: String!, $paused: Boolean!) {
441
444
  setHooksPaused(projectId: $projectId, paused: $paused) {
442
445
  id
443
446
  }
444
447
  }
445
- `);async function fs(){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();pt(e);let t=Ce(e);if(lr.existsSync(t)){process.stdout.write("Hooks already paused. Run `ripplo hooks resume` to re-enable.\n");return}lr.writeFileSync(t,""),await ys(e,!0),process.stdout.write("Hooks paused. Pre-edit gates and stop enforcement are off until you run `ripplo hooks resume`.\n")}async function gs(){let e=process.cwd(),t=Ce(e);if(!lr.existsSync(t)){process.stdout.write(`Hooks already active.
446
- `);return}lr.unlinkSync(t),await ys(e,!1),process.stdout.write(`Hooks resumed.
447
- `)}async function ys(e,t){let r;try{r=W(e)}catch{return}await h({config:r,document:Ey,variables:{paused:t,projectId:r.projectId}}).catch(()=>null)}import et from"fs";import tt from"path";import{input as bs,select as vs}from"@inquirer/prompts";import{graphql as Ky}from"gql.tada";import{exec as Cy}from"child_process";import _ from"fs";import V from"path";import{promisify as Ty}from"util";var Ay=["@ripplo/testing"],hs=".ripplo/ripplo.lock linguist-generated=true",Iy=[".ripplo/debug/",".ripplo/.local/"],$y=Ty(Cy);async function ws({cwd:e,onStep:t}){t("Scaffolding project files..."),My({cwd:e}),t("Updating .gitignore..."),Hy(e),t("Marking ripplo.lock as generated..."),Dy(e),t("Installing dependencies...");let r=await jy(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 Ny(e);o!=null&&n.push({manualCommand:void 0,message:o})}return t("Setting up browser..."),await Nr(),n}async function jy(e){let t=Oy({cwd:e,pm:Fy(e)});f.info("Installing dependencies: %s",t);try{return await $y(t,{cwd:e}),{ok:!0}}catch(r){let n=r instanceof Error?r.message.split(`
448
- `)[0]??r.message:String(r);return f.warn("Install failed (%s): %s",t,n),{cmd:t,ok:!1,reason:n}}}async function Ny(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 Dy(e){let t=V.join(e,".gitattributes"),r=_.existsSync(t)?_.readFileSync(t,"utf8"):"";if(r.includes(hs))return;let n=r.length===0||r.endsWith(`
448
+ `);async function bs(){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();mt(e);let t=Ce(e);if(ur.existsSync(t)){process.stdout.write("Hooks already paused. Run `ripplo hooks resume` to re-enable.\n");return}ur.writeFileSync(t,""),await Ss(e,!0),process.stdout.write("Hooks paused. Pre-edit gates and stop enforcement are off until you run `ripplo hooks resume`.\n")}async function vs(){let e=process.cwd(),t=Ce(e);if(!ur.existsSync(t)){process.stdout.write(`Hooks already active.
449
+ `);return}ur.unlinkSync(t),await Ss(e,!1),process.stdout.write(`Hooks resumed.
450
+ `)}async function Ss(e,t){let r;try{r=W(e)}catch{return}await h({config:r,document:Ly,variables:{paused:t,projectId:r.projectId}}).catch(()=>null)}import tt from"fs";import rt from"path";import{input as Rs,select as xs}from"@inquirer/prompts";import{graphql as oh}from"gql.tada";import{exec as _y}from"child_process";import _ from"fs";import V from"path";import{promisify as Uy}from"util";var Vy=["@ripplo/testing"],ks=".ripplo/ripplo.lock linguist-generated=true",Fy=[".ripplo/debug/",".ripplo/.local/"],My=Uy(_y);async function Ps({cwd:e,onStep:t}){t("Scaffolding project files..."),Yy({cwd:e}),t("Updating .gitignore..."),Qy(e),t("Marking ripplo.lock as generated..."),Wy(e),t("Installing dependencies...");let r=await Hy(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 By(e);o!=null&&n.push({manualCommand:void 0,message:o})}return t("Setting up browser..."),await Or(),n}async function Hy(e){let t=qy({cwd:e,pm:Xy(e)});f.info("Installing dependencies: %s",t);try{return await My(t,{cwd:e}),{ok:!0}}catch(r){let n=r instanceof Error?r.message.split(`
451
+ `)[0]??r.message:String(r);return f.warn("Install failed (%s): %s",t,n),{cmd:t,ok:!1,reason:n}}}async function By(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 Wy(e){let t=V.join(e,".gitattributes"),r=_.existsSync(t)?_.readFileSync(t,"utf8"):"";if(r.includes(ks))return;let n=r.length===0||r.endsWith(`
449
452
  `)?"":`
450
- `;_.writeFileSync(t,`${r}${n}${hs}
451
- `)}function Oy({cwd:e,pm:t}){let r=Ay.join(" ");return t==="pnpm"?Uy(e)?`pnpm add -wD ${r}`:`pnpm add -D ${r}`:t==="yarn"?Ly({cwd:e,deps:r}):t==="bun"?`bun add -d ${r}`:`npm install -D ${r}`}function Ly({cwd:e,deps:t}){return _y(e)?`yarn add -D ${t}`:Vy(e)?`yarn add -WD ${t}`:`yarn add -D ${t}`}function _y(e){if(_.existsSync(V.join(e,".yarnrc.yml"))||_.existsSync(V.join(e,".pnp.cjs"))||_.existsSync(V.join(e,".pnp.js")))return!0;let t=V.join(e,"package.json");if(!_.existsSync(t))return!1;try{let r=JSON.parse(_.readFileSync(t,"utf8"));if(r==null||typeof r!="object"||!("packageManager"in r))return!1;let n=r.packageManager;if(typeof n!="string")return!1;let o=/^yarn@(\d+)/.exec(n);return o!=null&&Number(o[1])>=2}catch{return!1}}function Uy(e){return _.existsSync(V.join(e,"pnpm-workspace.yaml"))||_.existsSync(V.join(e,"pnpm-workspace.yml"))}function Vy(e){let t=V.join(e,"package.json");if(!_.existsSync(t))return!1;try{let r=JSON.parse(_.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 Fy(e){return _.existsSync(V.join(e,"pnpm-lock.yaml"))?"pnpm":_.existsSync(V.join(e,"yarn.lock"))?"yarn":_.existsSync(V.join(e,"bun.lockb"))||_.existsSync(V.join(e,"bun.lock"))?"bun":"npm"}function My({cwd:e}){let t=V.join(e,".ripplo"),r=V.join(t,"tests"),n=V.join(t,"preconditions"),o=V.join(t,"observers");_.mkdirSync(r,{recursive:!0}),_.mkdirSync(n,{recursive:!0}),_.mkdirSync(o,{recursive:!0}),kt(V.join(t,"index.ts"),By),kt(V.join(n,"index.ts"),Wy),kt(V.join(o,"index.ts"),qy),kt(V.join(r,"index.ts"),zy),kt(V.join(t,"tsconfig.json"),Gy)}function kt(e,t){_.existsSync(e)||_.writeFileSync(e,t)}function Hy(e){let t=V.join(e,".gitignore");if(!_.existsSync(t))return;let r=_.readFileSync(t,"utf8"),n=Iy.filter(i=>!r.includes(i));if(n.length===0)return;let o=r.endsWith(`
453
+ `;_.writeFileSync(t,`${r}${n}${ks}
454
+ `)}function qy({cwd:e,pm:t}){let r=Vy.join(" ");return t==="pnpm"?Ky(e)?`pnpm add -wD ${r}`:`pnpm add -D ${r}`:t==="yarn"?zy({cwd:e,deps:r}):t==="bun"?`bun add -d ${r}`:`npm install -D ${r}`}function zy({cwd:e,deps:t}){return Gy(e)?`yarn add -D ${t}`:Jy(e)?`yarn add -WD ${t}`:`yarn add -D ${t}`}function Gy(e){if(_.existsSync(V.join(e,".yarnrc.yml"))||_.existsSync(V.join(e,".pnp.cjs"))||_.existsSync(V.join(e,".pnp.js")))return!0;let t=V.join(e,"package.json");if(!_.existsSync(t))return!1;try{let r=JSON.parse(_.readFileSync(t,"utf8"));if(r==null||typeof r!="object"||!("packageManager"in r))return!1;let n=r.packageManager;if(typeof n!="string")return!1;let o=/^yarn@(\d+)/.exec(n);return o!=null&&Number(o[1])>=2}catch{return!1}}function Ky(e){return _.existsSync(V.join(e,"pnpm-workspace.yaml"))||_.existsSync(V.join(e,"pnpm-workspace.yml"))}function Jy(e){let t=V.join(e,"package.json");if(!_.existsSync(t))return!1;try{let r=JSON.parse(_.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 Xy(e){return _.existsSync(V.join(e,"pnpm-lock.yaml"))?"pnpm":_.existsSync(V.join(e,"yarn.lock"))?"yarn":_.existsSync(V.join(e,"bun.lockb"))||_.existsSync(V.join(e,"bun.lock"))?"bun":"npm"}function Yy({cwd:e}){let t=V.join(e,".ripplo"),r=V.join(t,"tests"),n=V.join(t,"preconditions"),o=V.join(t,"observers");_.mkdirSync(r,{recursive:!0}),_.mkdirSync(n,{recursive:!0}),_.mkdirSync(o,{recursive:!0}),Rt(V.join(t,"index.ts"),Zy),Rt(V.join(n,"index.ts"),eh),Rt(V.join(o,"index.ts"),th),Rt(V.join(r,"index.ts"),rh),Rt(V.join(t,"tsconfig.json"),nh)}function Rt(e,t){_.existsSync(e)||_.writeFileSync(e,t)}function Qy(e){let t=V.join(e,".gitignore");if(!_.existsSync(t))return;let r=_.readFileSync(t,"utf8"),n=Fy.filter(i=>!r.includes(i));if(n.length===0)return;let o=r.endsWith(`
452
455
  `)?"":`
453
456
  `;_.writeFileSync(t,r+o+n.join(`
454
457
  `)+`
455
- `)}var By=`import { createRipplo } from "@ripplo/testing";
458
+ `)}var Zy=`import { createRipplo } from "@ripplo/testing";
456
459
  import { preconditions } from "./preconditions/index";
457
460
  import { observers } from "./observers/index";
458
461
  import { tests } from "./tests/index";
459
462
 
460
463
  export { preconditions, observers, tests };
461
464
  export default createRipplo({ preconditions, observers, tests });
462
- `,Wy=`// Declare preconditions with \`precondition(name)\` from @ripplo/testing and collect them
465
+ `,eh=`// Declare preconditions with \`precondition(name)\` from @ripplo/testing and collect them
463
466
  // in the \`preconditions\` registry below. Every handle in this registry must be implemented
464
467
  // in your app server's \`createEngine(ripplo, { preconditions: {...}, observers: {...} })\` call.
465
468
  //
@@ -473,7 +476,7 @@ export default createRipplo({ preconditions, observers, tests });
473
476
  // export const preconditions = { authLoggedIn };
474
477
 
475
478
  export const preconditions = {};
476
- `,qy=`// Declare observers with \`observer(name)\` from @ripplo/testing and collect them in
479
+ `,th=`// Declare observers with \`observer(name)\` from @ripplo/testing and collect them in
477
480
  // the \`observers\` registry below. Use them in tests via \`assert.backend(handle, params)\`.
478
481
  //
479
482
  // Example:
@@ -486,7 +489,7 @@ export const preconditions = {};
486
489
  // export const observers = { orgNameIs };
487
490
 
488
491
  export const observers = {};
489
- `,zy=`// Each test file under ./tests exports a TestDefinition. Import them here and add them
492
+ `,rh=`// Each test file under ./tests exports a TestDefinition. Import them here and add them
490
493
  // to the \`tests\` array \u2014 that's what \`createRipplo({ ..., tests })\` receives.
491
494
  //
492
495
  // Example:
@@ -494,7 +497,7 @@ export const observers = {};
494
497
  // export const tests = [myTest] as const;
495
498
 
496
499
  export const tests = [] as const;
497
- `,Gy=`{
500
+ `,nh=`{
498
501
  "compilerOptions": {
499
502
  "strict": true,
500
503
  "noUncheckedIndexedAccess": true,
@@ -510,29 +513,29 @@ export const tests = [] as const;
510
513
  "include": ["*.ts", "coverage.d.ts", "observers/**/*.ts", "preconditions/**/*.ts", "tests/**/*.ts"],
511
514
  "exclude": ["node_modules"]
512
515
  }
513
- `;var Jy=Ky(`
516
+ `;var ih=oh(`
514
517
  query InitProjects {
515
518
  projects {
516
519
  id
517
520
  name
518
521
  }
519
522
  }
520
- `),Ln=["../.env.local","../.env"];async function Ss(e=Qy()){let t=process.cwd(),r=ie();r==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let n=ee();Xy(t)&&(process.stdout.write(`\`.ripplo/index.ts\` already exists at ${t}. Delete it first if you want to re-init.
521
- `),process.exit(1));let o=await Yy({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 eh(o,e.projectId),s=await th(t,e.envFile),a=await rh(e.appUrl),l=Zy(a,e.engineUrl),c=tt.resolve(tt.join(t,".ripplo"),s);Qo({cwd:t,envFiles:[s],projectId:i}),ih({appUrl:a,engineUrl:l,filePath:c});let u=await ws({cwd:t,onStep:m=>{process.stdout.write(` ${m}
523
+ `),Vn=["../.env.local","../.env"];async function Es(e=lh()){let t=process.cwd(),r=ie();r==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let n=ee();sh(t)&&(process.stdout.write(`\`.ripplo/index.ts\` already exists at ${t}. Delete it first if you want to re-init.
524
+ `),process.exit(1));let o=await ah({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 uh(o,e.projectId),s=await dh(t,e.envFile),a=await ph(e.appUrl),l=ch(a,e.engineUrl),c=rt.resolve(rt.join(t,".ripplo"),s);ti({cwd:t,envFiles:[s],projectId:i}),gh({appUrl:a,engineUrl:l,filePath:c});let u=await Ps({cwd:t,onStep:m=>{process.stdout.write(` ${m}
522
525
  `)}});if(u.length>0){process.stdout.write(`Done with warnings:
523
526
  `),u.forEach(m=>{process.stdout.write(` - ${m.message}
524
527
  `),m.manualCommand!=null&&process.stdout.write(` run: ${m.manualCommand}
525
- `)});return}process.stdout.write("Ready. Start `npx ripplo watch` as a background process (or run `/ripplo:start` in Claude Code), then write tests in `.ripplo/tests/`.\n")}function Xy(e){return et.existsSync(tt.join(e,".ripplo","index.ts"))}async function Yy({serverUrl:e,token:t}){return((await h({config:Pe({serverUrl:e,token:t}),document:Jy,variables:void 0})).projects??[]).map(n=>({id:n.id,name:n.name}))}function Qy(){return{appUrl:void 0,engineUrl:void 0,envFile:void 0,projectId:void 0}}function Zy(e,t){if(t!=null){try{new URL(t)}catch{process.stdout.write(`--engine-url is not a valid URL: ${t}
526
- `),process.exit(1)}return t}return`${e.replace(/\/$/,"")}/ripplo`}async function eh(e,t){if(t!=null){let r=e.find(n=>n.id===t);return r==null&&(process.stdout.write(`Unknown project id: ${t}
528
+ `)});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 sh(e){return tt.existsSync(rt.join(e,".ripplo","index.ts"))}async function ah({serverUrl:e,token:t}){return((await h({config:Pe({serverUrl:e,token:t}),document:ih,variables:void 0})).projects??[]).map(n=>({id:n.id,name:n.name}))}function lh(){return{appUrl:void 0,engineUrl:void 0,envFile:void 0,projectId:void 0}}function ch(e,t){if(t!=null){try{new URL(t)}catch{process.stdout.write(`--engine-url is not a valid URL: ${t}
529
+ `),process.exit(1)}return t}return`${e.replace(/\/$/,"")}/ripplo`}async function uh(e,t){if(t!=null){let r=e.find(n=>n.id===t);return r==null&&(process.stdout.write(`Unknown project id: ${t}
527
530
  `),process.exit(1)),process.stdout.write(`Using project: ${r.name} (${r.id})
528
531
  `),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})
529
- `),r.id}return vs({choices:e.map(r=>({name:r.name,value:r.id})),message:"Select a project"})}async function th(e,t){return t!=null?(t.trim().length===0&&(process.stdout.write(`--env must not be empty
530
- `),process.exit(1)),t):nh(e)}async function rh(e){if(e!=null){try{new URL(e)}catch{process.stdout.write(`--app-url is not a valid URL: ${e}
531
- `),process.exit(1)}return e}return oh()}async function nh(e){let t=tt.join(e,".ripplo"),r=Ln.find(o=>et.existsSync(tt.resolve(t,o))),n=await vs({choices:[...Ln.map(o=>({name:r===o?`${o} (detected)`:o,value:o})),{name:"custom path",value:"__custom__"}],default:r??Ln[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:bs({message:"Path to env file (relative to .ripplo/, e.g. ../apps/server/.env)",validate:o=>o.trim().length>0?!0:"required"})}async function oh(){return bs({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 ih({appUrl:e,engineUrl:t,filePath:r}){et.mkdirSync(tt.dirname(r),{recursive:!0});let n=et.existsSync(r)?et.readFileSync(r,"utf8"):"",o=[];if(/^RIPPLO_APP_URL=/m.test(n)||o.push(`RIPPLO_APP_URL=${e}`),/^RIPPLO_ENGINE_URL=/m.test(n)||o.push(`RIPPLO_ENGINE_URL=${t}`),/^RIPPLO_WEBHOOK_SECRET=/m.test(n)||o.push(`RIPPLO_WEBHOOK_SECRET=${zr()}`),/^ENABLE_RIPPLO_TESTING=/m.test(n)||o.push("ENABLE_RIPPLO_TESTING=true"),o.length===0)return;let i=n.length===0||n.endsWith(`
532
+ `),r.id}return xs({choices:e.map(r=>({name:r.name,value:r.id})),message:"Select a project"})}async function dh(e,t){return t!=null?(t.trim().length===0&&(process.stdout.write(`--env must not be empty
533
+ `),process.exit(1)),t):mh(e)}async function ph(e){if(e!=null){try{new URL(e)}catch{process.stdout.write(`--app-url is not a valid URL: ${e}
534
+ `),process.exit(1)}return e}return fh()}async function mh(e){let t=rt.join(e,".ripplo"),r=Vn.find(o=>tt.existsSync(rt.resolve(t,o))),n=await xs({choices:[...Vn.map(o=>({name:r===o?`${o} (detected)`:o,value:o})),{name:"custom path",value:"__custom__"}],default:r??Vn[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:Rs({message:"Path to env file (relative to .ripplo/, e.g. ../apps/server/.env)",validate:o=>o.trim().length>0?!0:"required"})}async function fh(){return Rs({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 gh({appUrl:e,engineUrl:t,filePath:r}){tt.mkdirSync(rt.dirname(r),{recursive:!0});let n=tt.existsSync(r)?tt.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=${Kr()}`),/^ENABLE_RIPPLO_TESTING=/m.test(n)||o.push("ENABLE_RIPPLO_TESTING=true"),o.length===0)return;let i=n.length===0||n.endsWith(`
532
535
  `)?"":`
533
- `;et.writeFileSync(r,`${n}${i}${o.join(`
536
+ `;tt.writeFileSync(r,`${n}${i}${o.join(`
534
537
  `)}
535
- `)}import _n from"fs";import Ps from"path";import*as Rs from"remeda";import{graphql as sh}from"gql.tada";var ah=sh(`
538
+ `)}import Fn from"fs";import Ts from"path";import*as Is from"remeda";import{graphql as yh}from"gql.tada";var hh=yh(`
536
539
  mutation AutoScopeAddDirty($projectId: String!, $cwd: String!, $workflowSlugs: [String!]!) {
537
540
  addDirtyTestsToScope(projectId: $projectId, cwd: $cwd, workflowSlugs: $workflowSlugs) {
538
541
  __typename
@@ -543,34 +546,34 @@ export const tests = [] as const;
543
546
  }
544
547
  }
545
548
  }
546
- `);async function rt({compileResult:e,cwd:t}){if(!U(t))return{addedSlugs:[]};let r=ch(t);if(r.length===0)return{addedSlugs:[]};let n=new Set(r),o=e.result.tests.filter(l=>l.sourcePath!=null&&n.has(l.sourcePath)).map(l=>l.slug);if(o.length===0)return{addedSlugs:[]};let i;try{i=W(t)}catch{return{addedSlugs:[]}}return await Ye({compiled:e.result,config:i,cwd:t}).catch(l=>(f.warn("auto-sync failed: %s",l instanceof Error?l.message:String(l)),null))==null?{addedSlugs:[]}:{addedSlugs:await lh({cfg:i,slugs:o})?o:[]}}async function lh({cfg:e,slugs:t}){let n=(await h({config:e,document:ah,variables:{cwd:e.cwd,projectId:e.projectId,workflowSlugs:[...t]}}).catch(o=>(f.warn("auto-scope failed: %s",o instanceof Error?o.message:String(o)),null)))?.addDirtyTestsToScope;return n?.__typename!=="MutationAddDirtyTestsToScopeSuccess"?!1:n.data.length>0}var ks=".ripplo/tests/";function ch(e){let t;try{t=K(["status","--porcelain","--",".ripplo/tests"],e)}catch{return[]}return t.split(`
547
- `).map(r=>r.slice(3).trim()).filter(r=>r.startsWith(ks)&&r.endsWith(".ts")).map(r=>r.slice(ks.length)).filter(r=>r!=="index.ts"&&!r.endsWith("/index.ts"))}async function xs(e){let{ids:t,requireImplemented:r}=e,n=process.cwd(),o=await P(n);o.ok||(process.stderr.write(`Compilation failed: ${o.error}
549
+ `);async function nt({compileResult:e,cwd:t}){if(!U(t))return{addedSlugs:[]};let r=bh(t);if(r.length===0)return{addedSlugs:[]};let n=new Set(r),o=e.result.tests.filter(l=>l.sourcePath!=null&&n.has(l.sourcePath)).map(l=>l.slug);if(o.length===0)return{addedSlugs:[]};let i;try{i=W(t)}catch{return{addedSlugs:[]}}return await Qe({compiled:e.result,config:i,cwd:t}).catch(l=>(f.warn("auto-sync failed: %s",l instanceof Error?l.message:String(l)),null))==null?{addedSlugs:[]}:{addedSlugs:await wh({cfg:i,slugs:o})?o:[]}}async function wh({cfg:e,slugs:t}){let n=(await h({config:e,document:hh,variables:{cwd:e.cwd,projectId:e.projectId,workflowSlugs:[...t]}}).catch(o=>(f.warn("auto-scope failed: %s",o instanceof Error?o.message:String(o)),null)))?.addDirtyTestsToScope;return n?.__typename!=="MutationAddDirtyTestsToScopeSuccess"?!1:n.data.length>0}var Cs=".ripplo/tests/";function bh(e){let t;try{t=K(["status","--porcelain","--",".ripplo/tests"],e)}catch{return[]}return t.split(`
550
+ `).map(r=>r.slice(3).trim()).filter(r=>r.startsWith(Cs)&&r.endsWith(".ts")).map(r=>r.slice(Cs.length)).filter(r=>r!=="index.ts"&&!r.endsWith("/index.ts"))}function As(e){process.stderr.write(`Compilation failed: ${e}
548
551
  `),process.stderr.write(`${w("create","DSL authoring + lint rules")}
549
- `),process.exit(1)),await ce({cwd:n,result:o.result});let i=qe(o.result),s=t.length===0?i.diagnostics:i.diagnostics.filter(y=>t.includes(y.test)),a=Rs.groupBy(s,y=>y.test);Object.entries(a).forEach(([y,H])=>{process.stderr.write(`
552
+ `),process.exit(1)}async function $s(e){let{ids:t,requireImplemented:r}=e,n=process.cwd(),o=await P(n);o.ok||As(o.error),await ce({cwd:n,result:o.result}).catch(y=>{As(y instanceof Error?y.message:String(y))});let i=qe(o.result),s=t.length===0?i.diagnostics:i.diagnostics.filter(y=>t.includes(y.test)),a=Is.groupBy(s,y=>y.test);Object.entries(a).forEach(([y,H])=>{process.stderr.write(`
550
553
  ${y}
551
554
  `),H.forEach(E=>{let B=E.step==null?"":` at "${E.step}"`;process.stderr.write(` [${E.rule}]${B}
552
555
  `),process.stderr.write(` ${E.message}
553
556
  `)})});let l=new Set(o.builder.getUnimplemented().tests),c=r.filter(y=>l.has(y));c.length>0&&(process.stderr.write(`
554
557
  not-implemented
555
558
  `),c.forEach(y=>{process.stderr.write(` ${y} is still marked .notImplemented()
556
- `)}));let u=mh(n);u.length>0&&(process.stderr.write(`
559
+ `)}));let u=Ph(n);u.length>0&&(process.stderr.write(`
557
560
  preconditions
558
561
  `),u.forEach(y=>{process.stderr.write(` [hardcoded-identifier] ${y.file}
559
562
  `),process.stderr.write(` ${y.message}
560
563
  `)}));let m=s.length+c.length+u.length;m>0&&(process.stderr.write(`
561
564
  ${String(m)} error(s)
562
- `),uh({diagnostics:s,hardcodeWarnings:u,stillStubbed:c}),process.exit(1));let g=o.result.tests.length,R=t.length===0?"all tests":`${String(t.length)} test(s)`;process.stdout.write(`\u2713 ripplo lint: ${R} passed (${String(g)} compiled, lockfile written)
563
- `);let{addedSlugs:$}=await rt({compileResult:o,cwd:n});$.length>0&&process.stdout.write(`\u2713 Auto-scoped ${$.join(", ")} (dirty tests).
564
- `)}function uh({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)}
565
- `))}var dh=/['"`][\w.+-]+@[\w.-]+\.[a-z]{2,}['"`]/i,ph=/['"`][0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}['"`]/i;function mh(e){let t=Ps.join(e,".ripplo","preconditions");return _n.existsSync(t)?_n.readdirSync(t).filter(n=>n.endsWith(".ts")).flatMap(n=>fh(Ps.join(t,n))):[]}function fh(e){let t=_n.readFileSync(e,"utf8"),r=t.includes("ctx.uniqueEmail")||t.includes("ctx.uniqueId"),n=[],o=dh.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=ph.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 gh}from"gql.tada";var yh=gh(`
565
+ `),vh({diagnostics:s,hardcodeWarnings:u,stillStubbed:c}),process.exit(1));let g=o.result.tests.length,R=t.length===0?"all tests":`${String(t.length)} test(s)`;process.stdout.write(`\u2713 ripplo lint: ${R} passed (${String(g)} compiled, lockfile written)
566
+ `);let{addedSlugs:$}=await nt({compileResult:o,cwd:n});$.length>0&&process.stdout.write(`\u2713 Auto-scoped ${$.join(", ")} (dirty tests).
567
+ `)}function vh({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)}
568
+ `))}var Sh=/['"`][\w.+-]+@[\w.-]+\.[a-z]{2,}['"`]/i,kh=/['"`][0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}['"`]/i;function Ph(e){let t=Ts.join(e,".ripplo","preconditions");return Fn.existsSync(t)?Fn.readdirSync(t).filter(n=>n.endsWith(".ts")).flatMap(n=>Rh(Ts.join(t,n))):[]}function Rh(e){let t=Fn.readFileSync(e,"utf8"),r=t.includes("ctx.uniqueEmail")||t.includes("ctx.uniqueId"),n=[],o=Sh.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=kh.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 xh}from"gql.tada";var Eh=xh(`
566
569
  query ProjectsList {
567
570
  projects {
568
571
  id
569
572
  name
570
573
  }
571
574
  }
572
- `);async function Es(){let e=ie();e==null&&(process.stderr.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let t=ee(),n=((await h({config:Pe({serverUrl:t,token:e}),document:yh,variables:void 0})).projects??[]).map(o=>({id:o.id,name:o.name}));process.stdout.write(`${JSON.stringify({projects:n},null,2)}
573
- `)}import{graphql as hh}from"gql.tada";var cr=hh(`
575
+ `);async function js(){let e=ie();e==null&&(process.stderr.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let t=ee(),n=((await h({config:Pe({serverUrl:t,token:e}),document:Eh,variables:void 0})).projects??[]).map(o=>({id:o.id,name:o.name}));process.stdout.write(`${JSON.stringify({projects:n},null,2)}
576
+ `)}import{graphql as Ch}from"gql.tada";var dr=Ch(`
574
577
  query ScopeStatus($projectId: String!, $cwd: String!) {
575
578
  project(id: $projectId) {
576
579
  id
@@ -590,17 +593,17 @@ ${String(m)} error(s)
590
593
  }
591
594
  }
592
595
  }
593
- `);async function Cs({all:e,ids:t}){e&&t.length>0&&(process.stderr.write(`Pass either --all or test ids, not both.
594
- `),process.exit(1));let r=de();await he(r);let n=await wh({all:e,cwd:r.cwd,ids:t});n==null&&process.exit(1);let{results:o,summary:i}=await ar({config:r,ids:n,presynced:void 0});process.stdout.write(`${i}
596
+ `);async function Ns({all:e,ids:t}){e&&t.length>0&&(process.stderr.write(`Pass either --all or test ids, not both.
597
+ `),process.exit(1));let r=de();await he(r);let n=await Th({all:e,cwd:r.cwd,ids:t});n==null&&process.exit(1);let{results:o,summary:i}=await cr({config:r,ids:n,presynced:void 0});process.stdout.write(`${i}
595
598
  `);let s=o.filter(l=>l.summary.includes("FAILED")||l.summary.includes("ERROR")),a=s.map(l=>l.runId).filter(l=>l.length>0);if(a.length>0){let l=a.map(c=>`.ripplo/debug/${c}/`).join(", ");process.stderr.write(`Artifacts in ${l} \u2014 read before re-running.
596
599
  `),process.stderr.write(`${w("debug")}
597
- `)}process.exit(s.length>0?1:0)}async function wh({all:e,cwd:t,ids:r}){return r.length>0?r:e?[]:bh(t)}async function bh(e){let t=de(),r=await P(e);if(r.ok){let{addedSlugs:a}=await rt({compileResult:r,cwd:e});a.length>0&&process.stdout.write(`Auto-scoped ${a.join(", ")} (dirty tests).
598
- `)}let o=(await h({config:t,document:cr,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(", ")}
600
+ `)}process.exit(s.length>0?1:0)}async function Th({all:e,cwd:t,ids:r}){return r.length>0?r:e?[]:Ah(t)}async function Ah(e){let t=de(),r=await P(e);if(r.ok){let{addedSlugs:a}=await nt({compileResult:r,cwd:e});a.length>0&&process.stdout.write(`Auto-scoped ${a.join(", ")} (dirty tests).
601
+ `)}let o=(await h({config:t,document:dr,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(", ")}
599
602
  `),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")}
600
- `),null):i}async function Ts(){let e=process.cwd(),t=W(e);try{let r=await ye(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}
603
+ `),null):i}async function Ds(){let e=process.cwd(),t=W(e);try{let r=await ye(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}
601
604
  `)}catch(r){let n=r instanceof Error?r.message:String(r);process.stderr.write(`ripplo sync failed: ${n}
602
605
  `),process.stderr.write(`${w("setup","verify auth + server reachability")}
603
- `),process.exit(1)}}import ur from"fs";import{createClient as xh}from"graphql-sse";import Eh,{AbortError as Ch}from"p-retry";import{graphql as nt}from"gql.tada";import{print as Vn}from"graphql";import vh from"p-limit";var Sh=4,As=vh(Sh),Pt=new Set;function Un(e){!Number.isFinite(e)||e<1||(As.concurrency=Math.floor(e),f.debug({concurrency:e},"Local executor concurrency set to %d",e))}var Te;async function Is(e){if(!Pt.has(e.runId)){Pt.add(e.runId),f.debug({inflight:Pt.size,runId:e.runId},"run dispatched (inflight=%d)",Pt.size);try{await As(()=>Ph(e))}finally{Pt.delete(e.runId)}}}async function $s(){if(Te==null)return;let e=await Te.catch(()=>{});Te=void 0,e!=null&&e.isConnected()&&await e.close().catch(()=>{})}async function kh(){Te??=Ue({headed:!1});let e=Te,t=await e;return t.isConnected()?t:(Te===e&&(Te=Ue({headed:!1})),Te)}async function Ph({config:e,cwd:t,runId:r,workflowSlug:n}){try{let o=await j({label:"getSharedBrowser",fn:()=>kh()}),i=await j({label:"resolvePreconditionNames",fn:async()=>{if(!(t==null||n==null))return Rh({cwd:t,workflowSlug:n})}});await on({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 Rh({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 Th=6e4,js=100,Ah=15e3,Ih=nt(`
606
+ `),process.exit(1)}}import pr from"fs";import{createClient as Oh}from"graphql-sse";import Lh,{AbortError as _h}from"p-retry";import{graphql as ot}from"gql.tada";import{print as Hn}from"graphql";import Ih from"p-limit";var $h=4,Os=Ih($h),xt=new Set;function Mn(e){!Number.isFinite(e)||e<1||(Os.concurrency=Math.floor(e),f.debug({concurrency:e},"Local executor concurrency set to %d",e))}var Te;async function Ls(e){if(!xt.has(e.runId)){xt.add(e.runId),f.debug({inflight:xt.size,runId:e.runId},"run dispatched (inflight=%d)",xt.size);try{await Os(()=>Nh(e))}finally{xt.delete(e.runId)}}}async function _s(){if(Te==null)return;let e=await Te.catch(()=>{});Te=void 0,e!=null&&e.isConnected()&&await e.close().catch(()=>{})}async function jh(){Te??=Ue({headed:!1});let e=Te,t=await e;return t.isConnected()?t:(Te===e&&(Te=Ue({headed:!1})),Te)}async function Nh({config:e,cwd:t,runId:r,workflowSlug:n}){try{let o=await j({label:"getSharedBrowser",fn:()=>jh()}),i=await j({label:"resolvePreconditionNames",fn:async()=>{if(!(t==null||n==null))return Dh({cwd:t,workflowSlug:n})}});await an({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 Dh({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 Uh=6e4,Us=100,Vh=15e3,Fh=ot(`
604
607
  subscription RunRequestedWatch($devSessionId: String!) {
605
608
  runRequested(devSessionId: $devSessionId) {
606
609
  runId
@@ -608,14 +611,14 @@ ${String(m)} error(s)
608
611
  workflowSlug
609
612
  }
610
613
  }
611
- `),$h=nt(`
614
+ `),Mh=ot(`
612
615
  subscription HooksPausedWatch($projectId: String!) {
613
616
  hooksPausedRequested(projectId: $projectId) {
614
617
  paused
615
618
  projectId
616
619
  }
617
620
  }
618
- `),jh=nt(`
621
+ `),Hh=ot(`
619
622
  mutation HeartbeatDevSessionWatch($id: String!) {
620
623
  heartbeatDevSession(id: $id) {
621
624
  __typename
@@ -627,18 +630,18 @@ ${String(m)} error(s)
627
630
  }
628
631
  }
629
632
  }
630
- `),Nh=nt(`
633
+ `),Bh=ot(`
631
634
  query WatchLocalConcurrency {
632
635
  currentUser {
633
636
  id
634
637
  maxLocalConcurrentRuns
635
638
  }
636
639
  }
637
- `),Dh=nt(`
640
+ `),Wh=ot(`
638
641
  subscription WatchLocalConcurrencyChanged {
639
642
  myMaxLocalConcurrentRunsChanged
640
643
  }
641
- `),Oh=nt(`
644
+ `),qh=ot(`
642
645
  mutation EndDevSessionWatch($projectId: String!, $cwd: String!) {
643
646
  endDevSession(projectId: $projectId, cwd: $cwd) {
644
647
  __typename
@@ -650,12 +653,12 @@ ${String(m)} error(s)
650
653
  }
651
654
  }
652
655
  }
653
- `);async function Ns(){qh();let e=Hh(process.cwd()),t=e.cwd,r=Mh(t),n=await P(t);n.ok||(process.stderr.write(`ripplo: DSL compilation failed: ${n.error}
654
- `),process.exit(1));let o=await Os(()=>Ye({compiled:n.result,config:e,cwd:t}),{config:e,label:"initial sync"});await zh(e),Ds({cwd:t,paused:o.hooksPaused});let i=ir(t);i!=null&&f.info("watching branch %s in %s",i,t);let s=xh({headers:{Authorization:`Bearer ${e.token}`},retryAttempts:1/0,url:`${e.ripploServerUrl}/graphql`}),a=Fh({config:e,cwd:t,initialId:o.devSessionId,sseClient:s}),l=Uh({cwd:t,projectId:e.projectId,sseClient:s}),c=_h({sseClient:s}),u=Vh({config:e,session:a}),m=Wh();process.stdout.write(`ripplo watch: ready as local executor for session ${o.devSessionId} (sync happens on each \`ripplo run\`; Ctrl-C to stop)
655
- `);let g=async()=>{u(),m(),a.stop(),l(),c(),await Promise.race([h({config:e,document:Oh,variables:{cwd:e.cwd,projectId:e.projectId}}).catch(()=>{}),new Promise($=>setTimeout($,3e3))]),await nn(),await $s(),Zr(),r()},R=()=>{g().finally(()=>process.exit(0))};process.on("SIGINT",R),process.on("SIGTERM",R),process.on("SIGHUP",R),process.on("SIGBREAK",R),await new Promise(()=>{})}function Lh({cwd:e,devSessionId:t,onReconnecting:r,sseClient:n}){return n.subscribe({query:Vn(Ih),variables:{devSessionId:t}},{complete:()=>{},error:o=>{f.warn("runRequested SSE retries exhausted: %s",o instanceof Error?o.message:String(o))},next:o=>{let i=o.data?.runRequested;if(i==null)return;process.stdout.write(`ripplo: run ${i.workflowSlug}
656
- `);let s;try{Jt(e),s=W(e)}catch(a){f.error({err:a,runId:i.runId},"failed to load env for run dispatch; skipping");return}Is({config:s,cwd:e,runId:i.runId,workflowId:i.workflowId,workflowSlug:i.workflowSlug}).catch(a=>{f.error({err:a,runId:i.runId,workflowSlug:i.workflowSlug},"run execution failed; watch continuing")})}},{connecting:o=>{o&&r()}})}function Ds({cwd:e,paused:t}){let r=Ce(e);if(t&&!ur.existsSync(r)){ur.writeFileSync(r,"");return}!t&&ur.existsSync(r)&&ur.unlinkSync(r)}function _h({sseClient:e}){return e.subscribe({query:Vn(Dh)},{complete:()=>{},error:t=>{f.error(t,"localConcurrency subscription error")},next:t=>{let r=t.data?.myMaxLocalConcurrentRunsChanged;r!=null&&Un(r)}})}function Uh({cwd:e,projectId:t,sseClient:r}){return r.subscribe({query:Vn($h),variables:{projectId:t}},{complete:()=>{},error:n=>{f.error(n,"hooksPaused subscription error")},next:n=>{let o=n.data?.hooksPausedRequested?.paused;o!=null&&Ds({cwd:e,paused:o})}})}function Vh({config:e,session:t}){let r=async()=>{try{let o=await h({config:e,document:jh,variables:{id:t.getId()}});o.heartbeatDevSession?.__typename==="DevSessionEndedError"&&(f.warn("dev session ended server-side (%s); re-registering",o.heartbeatDevSession.message),await t.reregister())}catch(o){f.warn("heartbeat failed: %s",o instanceof Error?o.message:String(o))}},n=setInterval(()=>{r()},Ah);return()=>{clearInterval(n)}}function Fh({config:e,cwd:t,initialId:r,sseClient:n}){let o=r,i=null,s=()=>{f.warn("runRequested SSE reconnecting; re-registering session"),u()},a=()=>Lh({cwd:t,devSessionId:o,onReconnecting:s,sseClient:n}),l=a(),c=async()=>{let m=await P(t);if(!m.ok){f.error("re-register: DSL compile failed: %s",m.error);return}let g=await Os(()=>Ye({compiled:m.result,config:e,cwd:t}),{config:e,label:"re-register sync"});l(),o=g.devSessionId,l=a(),f.info("re-registered dev session as %s",o)},u=()=>(i!=null||(i=c().finally(()=>{i=null})),i);return{reregister:u,getId:()=>o,stop:()=>{l()}}}function Mh(e){try{return Xi(e)}catch(t){throw t instanceof Je&&(process.stderr.write(`ripplo watch: another watcher is already running for this project (pid ${String(t.pid)}, cwd ${t.cwd}).
657
- `),process.exit(1)),t}}function Hh(e){try{return W(e)}catch(t){let r=t instanceof Error?t.message:String(t);process.stderr.write(`${r}
658
- `),process.exit(1)}}function Os(e,{config:t,label:r}){let n=t.ripploServerUrl.includes("localhost")||t.ripploServerUrl.includes("127.0.0.1");return Eh(async()=>{try{return await e()}catch(o){let i=o instanceof Error?o.message:String(o);throw Bh(i)?o:(f.error("%s failed: %s",r,i),new Ch(i))}},{factor:2,maxTimeout:n?2e3:1e4,minTimeout:n?100:1e3,retries:1/0,onFailedAttempt:({attemptNumber:o,error:i})=>{f.warn("%s attempt %d failed; retrying: %s",r,o,i.message)}})}function Bh(e){return e.includes("status 502")||e.includes("ECONNREFUSED")||e.includes("Failed to connect")||e.includes("fetch failed")}function Wh(){Tt({maxRuns:js});let e=setInterval(()=>{Tt({maxRuns:js})},Th);return()=>{clearInterval(e)}}function qh(){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 zh(e){try{let r=(await h({config:e,document:Nh,variables:void 0})).currentUser?.maxLocalConcurrentRuns;r!=null&&Un(r)}catch(t){f.warn({err:t},"failed to fetch local concurrency setting; using default")}}import{graphql as dr}from"gql.tada";var Gh=dr(`
656
+ `);async function Vs(){tw();let e=Qh(process.cwd()),t=e.cwd,r=Yh(t),n=await P(t);n.ok||(process.stderr.write(`ripplo: DSL compilation failed: ${n.error}
657
+ `),process.exit(1));let o=await Ms(()=>Qe({compiled:n.result,config:e,cwd:t}),{config:e,label:"initial sync"});await rw(e),Fs({cwd:t,paused:o.hooksPaused});let i=ar(t);i!=null&&f.info("watching branch %s in %s",i,t);let s=Oh({headers:{Authorization:`Bearer ${e.token}`},retryAttempts:1/0,url:`${e.ripploServerUrl}/graphql`}),a=Xh({config:e,cwd:t,initialId:o.devSessionId,sseClient:s}),l=Kh({cwd:t,projectId:e.projectId,sseClient:s}),c=Gh({sseClient:s}),u=Jh({config:e,session:a}),m=ew();process.stdout.write(`ripplo watch: ready as local executor for session ${o.devSessionId} (sync happens on each \`ripplo run\`; Ctrl-C to stop)
658
+ `);let g=async()=>{u(),m(),a.stop(),l(),c(),await Promise.race([h({config:e,document:qh,variables:{cwd:e.cwd,projectId:e.projectId}}).catch(()=>{}),new Promise($=>setTimeout($,3e3))]),await sn(),await _s(),tn(),r()},R=()=>{g().finally(()=>process.exit(0))};process.on("SIGINT",R),process.on("SIGTERM",R),process.on("SIGHUP",R),process.on("SIGBREAK",R),await new Promise(()=>{})}function zh({cwd:e,devSessionId:t,onReconnecting:r,sseClient:n}){return n.subscribe({query:Hn(Fh),variables:{devSessionId:t}},{complete:()=>{},error:o=>{f.warn("runRequested SSE retries exhausted: %s",o instanceof Error?o.message:String(o))},next:o=>{let i=o.data?.runRequested;if(i==null)return;process.stdout.write(`ripplo: run ${i.workflowSlug}
659
+ `);let s;try{Yt(e),s=W(e)}catch(a){f.error({err:a,runId:i.runId},"failed to load env for run dispatch; skipping");return}Ls({config:s,cwd:e,runId:i.runId,workflowId:i.workflowId,workflowSlug:i.workflowSlug}).catch(a=>{f.error({err:a,runId:i.runId,workflowSlug:i.workflowSlug},"run execution failed; watch continuing")})}},{connecting:o=>{o&&r()}})}function Fs({cwd:e,paused:t}){let r=Ce(e);if(t&&!pr.existsSync(r)){pr.writeFileSync(r,"");return}!t&&pr.existsSync(r)&&pr.unlinkSync(r)}function Gh({sseClient:e}){return e.subscribe({query:Hn(Wh)},{complete:()=>{},error:t=>{f.error(t,"localConcurrency subscription error")},next:t=>{let r=t.data?.myMaxLocalConcurrentRunsChanged;r!=null&&Mn(r)}})}function Kh({cwd:e,projectId:t,sseClient:r}){return r.subscribe({query:Hn(Mh),variables:{projectId:t}},{complete:()=>{},error:n=>{f.error(n,"hooksPaused subscription error")},next:n=>{let o=n.data?.hooksPausedRequested?.paused;o!=null&&Fs({cwd:e,paused:o})}})}function Jh({config:e,session:t}){let r=async()=>{try{let o=await h({config:e,document:Hh,variables:{id:t.getId()}});o.heartbeatDevSession?.__typename==="DevSessionEndedError"&&(f.warn("dev session ended server-side (%s); re-registering",o.heartbeatDevSession.message),await t.reregister())}catch(o){f.warn("heartbeat failed: %s",o instanceof Error?o.message:String(o))}},n=setInterval(()=>{r()},Vh);return()=>{clearInterval(n)}}function Xh({config:e,cwd:t,initialId:r,sseClient:n}){let o=r,i=null,s=()=>{f.warn("runRequested SSE reconnecting; re-registering session"),u()},a=()=>zh({cwd:t,devSessionId:o,onReconnecting:s,sseClient:n}),l=a(),c=async()=>{let m=await P(t);if(!m.ok){f.error("re-register: DSL compile failed: %s",m.error);return}let g=await Ms(()=>Qe({compiled:m.result,config:e,cwd:t}),{config:e,label:"re-register sync"});l(),o=g.devSessionId,l=a(),f.info("re-registered dev session as %s",o)},u=()=>(i!=null||(i=c().finally(()=>{i=null})),i);return{reregister:u,getId:()=>o,stop:()=>{l()}}}function Yh(e){try{return ts(e)}catch(t){throw t instanceof Xe&&(process.stderr.write(`ripplo watch: another watcher is already running for this project (pid ${String(t.pid)}, cwd ${t.cwd}).
660
+ `),process.exit(1)),t}}function Qh(e){try{return W(e)}catch(t){let r=t instanceof Error?t.message:String(t);process.stderr.write(`${r}
661
+ `),process.exit(1)}}function Ms(e,{config:t,label:r}){let n=t.ripploServerUrl.includes("localhost")||t.ripploServerUrl.includes("127.0.0.1");return Lh(async()=>{try{return await e()}catch(o){let i=o instanceof Error?o.message:String(o);throw Zh(i)?o:(f.error("%s failed: %s",r,i),new _h(i))}},{factor:2,maxTimeout:n?2e3:1e4,minTimeout:n?100:1e3,retries:1/0,onFailedAttempt:({attemptNumber:o,error:i})=>{f.warn("%s attempt %d failed; retrying: %s",r,o,i.message)}})}function Zh(e){return e.includes("status 502")||e.includes("ECONNREFUSED")||e.includes("Failed to connect")||e.includes("fetch failed")}function ew(){It({maxRuns:Us});let e=setInterval(()=>{It({maxRuns:Us})},Uh);return()=>{clearInterval(e)}}function tw(){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 rw(e){try{let r=(await h({config:e,document:Bh,variables:void 0})).currentUser?.maxLocalConcurrentRuns;r!=null&&Mn(r)}catch(t){f.warn({err:t},"failed to fetch local concurrency setting; using default")}}import{graphql as mr}from"gql.tada";var nw=mr(`
659
662
  query ScopeWorkflowBySlug($projectId: String!, $cwd: String!, $slug: String!) {
660
663
  project(id: $projectId) {
661
664
  id
@@ -668,7 +671,7 @@ ${String(m)} error(s)
668
671
  }
669
672
  }
670
673
  }
671
- `),Kh=dr(`
674
+ `),ow=mr(`
672
675
  mutation ScopeAddDirtyTests($projectId: String!, $cwd: String!, $workflowSlugs: [String!]!) {
673
676
  addDirtyTestsToScope(projectId: $projectId, cwd: $cwd, workflowSlugs: $workflowSlugs) {
674
677
  __typename
@@ -686,36 +689,36 @@ ${String(m)} error(s)
686
689
  }
687
690
  }
688
691
  }
689
- `),Jh=dr(`
692
+ `),iw=mr(`
690
693
  mutation ScopeLink($id: ID!, $workflowId: String!) {
691
694
  linkScopeItem(id: $id, workflowId: $workflowId) {
692
695
  id
693
696
  }
694
697
  }
695
- `),Xh=dr(`
698
+ `),sw=mr(`
696
699
  mutation ScopeRemoveMany($ids: [ID!]!) {
697
700
  removeScopeItems(ids: $ids)
698
701
  }
699
- `);async function Ls(e){let t=de();await he(t);let n=(await h({config:t,document:cr,variables:{cwd:t.cwd,projectId:t.projectId}})).project?.devSession?.scopeItems??[];if(e.format==="json"){process.stdout.write(`${JSON.stringify(n,null,2)}
702
+ `);async function Hs(e){let t=de();await he(t);let n=(await h({config:t,document:dr,variables:{cwd:t.cwd,projectId:t.projectId}})).project?.devSession?.scopeItems??[];if(e.format==="json"){process.stdout.write(`${JSON.stringify(n,null,2)}
700
703
  `);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??""}
701
704
  `);return}let s=i.spec==null?"stub":"implemented";process.stdout.write(` [${s}] (${o.id}) ${i.slug} \u2014 ${i.name}
702
- `)})}async function _s({testIds:e}){let t=de();await he(t),await ye(t.cwd,t);let n=(await h({config:t,document:Kh,variables:{cwd:t.cwd,projectId:t.projectId,workflowSlugs:[...e]}})).addDirtyTestsToScope;n?.__typename==="NoActiveDevSessionError"&&(process.stderr.write(`${n.message}
705
+ `)})}async function Bs({testIds:e}){let t=de();await he(t),await ye(t.cwd,t);let n=(await h({config:t,document:ow,variables:{cwd:t.cwd,projectId:t.projectId,workflowSlugs:[...e]}})).addDirtyTestsToScope;n?.__typename==="NoActiveDevSessionError"&&(process.stderr.write(`${n.message}
703
706
  `),process.exit(1));let o=n?.__typename==="MutationAddDirtyTestsToScopeSuccess"?n.data:[];if(o.length===0){process.stdout.write(`No scope items added.
704
707
  `);return}let i=o.map(s=>s.workflow?.slug??"?").join(", ");process.stdout.write(`Added ${String(o.length)} scope item(s): ${i}
705
- `)}async function Us({id:e,testId:t}){let r=de();await he(r),await ye(r.cwd,r);let n=await Yh({cfg:r,slug:t});await h({config:r,document:Jh,variables:{id:e,workflowId:n}}),process.stdout.write(`Linked scope item ${e} to ${t}
706
- `)}async function Vs({ids:e}){let t=de();await he(t);let n=(await h({config:t,document:Xh,variables:{ids:[...e]}})).removeScopeItems??0;process.stdout.write(`Removed ${String(n)} scope item(s)
707
- `)}async function Yh({cfg:e,slug:t}){let n=(await h({config:e,document:Gh,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.
708
+ `)}async function Ws({id:e,testId:t}){let r=de();await he(r),await ye(r.cwd,r);let n=await aw({cfg:r,slug:t});await h({config:r,document:iw,variables:{id:e,workflowId:n}}),process.stdout.write(`Linked scope item ${e} to ${t}
709
+ `)}async function qs({ids:e}){let t=de();await he(t);let n=(await h({config:t,document:sw,variables:{ids:[...e]}})).removeScopeItems??0;process.stdout.write(`Removed ${String(n)} scope item(s)
710
+ `)}async function aw({cfg:e,slug:t}){let n=(await h({config:e,document:nw,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.
708
711
  `),process.stderr.write(`${w("create")}
709
- `),process.exit(1)),n.id}async function Fs(e){let t=process.cwd(),r=await P(t);r.ok||(process.stderr.write(`Compilation failed: ${r.error}
712
+ `),process.exit(1)),n.id}async function zs(e){let t=process.cwd(),r=await P(t);r.ok||(process.stderr.write(`Compilation failed: ${r.error}
710
713
  `),process.exit(1));let{tests:n}=r.builder.getUnimplemented();if(e.format==="summary"){n.length>0&&process.stdout.write(`tests: ${n.join(", ")}
711
714
  `);return}let o={tests:n.map(i=>({id:i,implemented:!1}))};process.stdout.write(`${JSON.stringify(o,null,2)}
712
- `)}import{z as Qh}from"zod";function T(e,t){let r=Qh.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 tA}from"crypto";import Ms from"picomatch";function Zh(e){return K(["diff","--name-only","HEAD"],e).split(`
713
- `).filter(t=>t.length>0)}function Hs({cwd:e,ignoreGlobs:t,watchGlobs:r}){let n=Ms([...r]),o=Ms([...t]);return Zh(e).filter(i=>n(i)&&!o(i))}function pr(e,...t){return K(["diff","--name-only","HEAD","--",...t],e).split(`
714
- `).filter(r=>r.length>0)}function Ae(){return{ignorePaths:xe,watchPaths:xn}}var Bs=T("UserPromptSubmit",e=>{let{cwd:t}=e;if(!C(t)||!U(t))return;let r=Ee(t);if(Qe(t,"coverage-nudge")===r)return;let{ignorePaths:n,watchPaths:o}=Ae(),i=Hs({cwd:t,ignoreGlobs:n,watchGlobs:o});if(Ze(t,"coverage-nudge",r),!(i.length===0||pr(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 mr from"fs";import ew from"os";import Ws from"path";var qs=T("PreToolUse",e=>{if(e.tool_name!=="ExitPlanMode"||!U(e.cwd))return;let t=tw();if(t==null)return;let r=mr.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 tw(){let e=Ws.join(ew.homedir(),".claude","plans");return mr.existsSync(e)?mr.readdirSync(e).filter(r=>r.endsWith(".md")).map(r=>Ws.join(e,r)).map(r=>({full:r,mtime:mr.statSync(r).mtimeMs})).sort((r,n)=>n.mtime-r.mtime)[0]?.full??null:null}var zs=T("UserPromptSubmit",async e=>{if(e.permission_mode!=="plan"||!C(e.cwd)||!U(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(`
715
- `),hookEventName:"UserPromptSubmit"}}});import rw from"path";import Gs from"picomatch";import{z as Ks}from"zod";var nw=Ks.looseObject({file_path:Ks.string()}),Js=T("PostToolUse",async e=>{let t=nw.safeParse(e.tool_input);if(!t.success)return;let r=t.data.file_path,{cwd:n}=e;if(!C(n)||!U(n))return;let o=rw.relative(n,r);if(o.startsWith(".."))return;let{ignorePaths:i,watchPaths:s}=Ae(),a=Gs([...s]),l=Gs([...i]);if(!a(o)||l(o))return;let c=await P(n);if(!c.ok)return;let{tests:u}=c.builder.getUnimplemented();if(u.length!==0)return{hookSpecificOutput:{additionalContext:`Reminder: .notImplemented() stubs still present \u2014 tests: ${u.join(", ")}`,hookEventName:"PostToolUse"}}});import{z as Xs}from"zod";var ow=Xs.looseObject({file_path:Xs.string()}),Ys=T("PostToolUse",async e=>{let t=ow.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))return;if(!U(n))return{hookSpecificOutput:{additionalContext:"Ripplo hooks are paused \u2014 DSL lint, lockfile sync, and coverage codegen did not run for this edit. Resume with `npx ripplo hooks resume` when ready.",hookEventName:"PostToolUse"}};let o=await P(n);return o.ok?(await ce({cwd:n,result:o.result}),Ge({cwd:n}),await iw({compileResult:o,cwd:n})):{decision:"block",reason:`Compilation failed: ${o.error}
716
- ${w("create","DSL authoring + lint rules")}`}});async function iw({compileResult:e,cwd:t}){let{diagnostics:r}=qe(e.result);if(r.length>0)return{decision:"block",reason:`${r.map(i=>{let s=i.step==null?"":` at "${i.step}"`;return` [${i.rule}]${s} ${i.test}: ${i.message}`}).join(`
715
+ `)}import{z as lw}from"zod";function T(e,t){let r=lw.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 yA}from"crypto";import Gs from"picomatch";function cw(e){return K(["diff","--name-only","HEAD"],e).split(`
716
+ `).filter(t=>t.length>0)}function Ks({cwd:e,ignoreGlobs:t,watchGlobs:r}){let n=Gs([...r]),o=Gs([...t]);return cw(e).filter(i=>n(i)&&!o(i))}function fr(e,...t){return K(["diff","--name-only","HEAD","--",...t],e).split(`
717
+ `).filter(r=>r.length>0)}function Ae(){return{ignorePaths:xe,watchPaths:Cn}}var Js=T("UserPromptSubmit",e=>{let{cwd:t}=e;if(!C(t)||!U(t))return;let r=Ee(t);if(Ze(t,"coverage-nudge")===r)return;let{ignorePaths:n,watchPaths:o}=Ae(),i=Ks({cwd:t,ignoreGlobs:n,watchGlobs:o});if(et(t,"coverage-nudge",r),!(i.length===0||fr(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 gr from"fs";import uw from"os";import Xs from"path";var Ys=T("PreToolUse",e=>{if(e.tool_name!=="ExitPlanMode"||!U(e.cwd))return;let t=dw();if(t==null)return;let r=gr.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 dw(){let e=Xs.join(uw.homedir(),".claude","plans");return gr.existsSync(e)?gr.readdirSync(e).filter(r=>r.endsWith(".md")).map(r=>Xs.join(e,r)).map(r=>({full:r,mtime:gr.statSync(r).mtimeMs})).sort((r,n)=>n.mtime-r.mtime)[0]?.full??null:null}var Qs=T("UserPromptSubmit",async e=>{if(e.permission_mode!=="plan"||!C(e.cwd)||!U(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(`
718
+ `),hookEventName:"UserPromptSubmit"}}});import pw from"path";import Zs from"picomatch";import{z as ea}from"zod";var mw=ea.looseObject({file_path:ea.string()}),ta=T("PostToolUse",async e=>{let t=mw.safeParse(e.tool_input);if(!t.success)return;let r=t.data.file_path,{cwd:n}=e;if(!C(n)||!U(n))return;let o=pw.relative(n,r);if(o.startsWith(".."))return;let{ignorePaths:i,watchPaths:s}=Ae(),a=Zs([...s]),l=Zs([...i]);if(!a(o)||l(o))return;let c=await P(n);if(!c.ok)return;let{tests:u}=c.builder.getUnimplemented();if(u.length!==0)return{hookSpecificOutput:{additionalContext:`Reminder: .notImplemented() stubs still present \u2014 tests: ${u.join(", ")}`,hookEventName:"PostToolUse"}}});import{z as ra}from"zod";var fw=ra.looseObject({file_path:ra.string()}),na=T("PostToolUse",async e=>{let t=fw.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))return;if(!U(n))return{hookSpecificOutput:{additionalContext:"Ripplo hooks are paused \u2014 DSL lint, lockfile sync, and coverage codegen did not run for this edit. Resume with `npx ripplo hooks resume` when ready.",hookEventName:"PostToolUse"}};let o=await P(n);return o.ok?(await ce({cwd:n,result:o.result}),Ge({cwd:n}),await gw({compileResult:o,cwd:n})):{decision:"block",reason:`Compilation failed: ${o.error}
719
+ ${w("create","DSL authoring + lint rules")}`}});async function gw({compileResult:e,cwd:t}){let{diagnostics:r}=qe(e.result);if(r.length>0)return{decision:"block",reason:`${r.map(i=>{let s=i.step==null?"":` at "${i.step}"`;return` [${i.rule}]${s} ${i.test}: ${i.message}`}).join(`
717
720
  `)}
718
- ${w("create")}`};let{addedSlugs:n}=await rt({compileResult:e,cwd:t});if(n.length!==0)return{hookSpecificOutput:{additionalContext:`Auto-scoped ${n.join(", ")} (dirty tests).`,hookEventName:"PostToolUse"}}}import{z as Qs}from"zod";var sw=Qs.looseObject({command:Qs.string()}),aw=/\bripplo\s+hooks\s+pause\b/,Zs=T("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=sw.safeParse(e.tool_input);if(!t.success||!aw.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 pw}from"shell-quote";import{z as ta}from"zod";import{existsSync as lw,mkdirSync as cw,rmSync as QA,writeFileSync as uw}from"fs";import Fn from"path";function fr(e,t,r){let n=ea(e,t,r);cw(Fn.dirname(n),{recursive:!0}),uw(n,"")}function gr(e,t,r){return lw(ea(e,t,r))}function dw(e,t){return Fn.join(e,".ripplo",".local","skills-loaded",t)}function ea(e,t,r){return Fn.join(dw(e,t),r)}var mw=ta.looseObject({command:ta.string()}),fw="debug",gw=new Set(["tail","head","less","more","wc","sort","uniq","awk","sed","grep"]),na=T("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=mw.safeParse(e.tool_input);if(!t.success)return;let r=yw(t.data.command);if(!hw(r))return;let{cwd:n}=e;if(!C(n)||!U(n))return;if(!gr(n,e.session_id,fw))return ra("Running `ripplo run` requires the `/ripplo:debug` skill loaded first. Load `/ripplo:debug` then retry \u2014 it carries the artifact-read order and the no-grep-piping guidance for run failures.");let i=bw(r);if(i!=null)return ra(`Don't pipe \`ripplo run\` through \`${i}\` \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\`.`)});function yw(e){try{return pw(e)}catch{return[]}}function hw(e){return e.some((t,r)=>t==="ripplo"&&e[r+1]==="run")}function ww(e){return typeof e=="object"&&"op"in e&&e.op==="|"}function bw(e){let t=e.find((r,n)=>{let o=e[n-1];return o!=null&&ww(o)&&typeof r=="string"&&gw.has(r)});return typeof t=="string"?t:null}function ra(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}}}import vw from"path";import{z as oa}from"zod";var Sw=new Set(["Edit","Write","NotebookEdit"]),kw=oa.looseObject({file_path:oa.string()}),Pw="create",ia=T("PreToolUse",e=>{if(!Sw.has(e.tool_name))return;let t=kw.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!C(r)||!U(r))return;let n=vw.relative(r,t.data.file_path);if(!(n.startsWith("..")||n!==".ripplo"&&!n.startsWith(".ripplo/"))&&!gr(r,e.session_id,Pw))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 Rw from"path";import sa from"picomatch";import{graphql as xw}from"gql.tada";import{z as aa}from"zod";var Ew=new Set(["Edit","Write","NotebookEdit"]),Cw=aa.looseObject({file_path:aa.string()}),Tw=xw(`
721
+ ${w("create")}`};let{addedSlugs:n}=await nt({compileResult:e,cwd:t});if(n.length!==0)return{hookSpecificOutput:{additionalContext:`Auto-scoped ${n.join(", ")} (dirty tests).`,hookEventName:"PostToolUse"}}}import{z as oa}from"zod";var yw=oa.looseObject({command:oa.string()}),hw=/\bripplo\s+hooks\s+pause\b/,ia=T("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=yw.safeParse(e.tool_input);if(!t.success||!hw.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 kw}from"shell-quote";import{z as aa}from"zod";import{existsSync as ww,mkdirSync as bw,rmSync as mI,writeFileSync as vw}from"fs";import Bn from"path";function yr(e,t,r){let n=sa(e,t,r);bw(Bn.dirname(n),{recursive:!0}),vw(n,"")}function hr(e,t,r){return ww(sa(e,t,r))}function Sw(e,t){return Bn.join(e,".ripplo",".local","skills-loaded",t)}function sa(e,t,r){return Bn.join(Sw(e,t),r)}var Pw=aa.looseObject({command:aa.string()}),Rw="debug",xw=new Set(["tail","head","less","more","wc","sort","uniq","awk","sed","grep"]),ca=T("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let t=Pw.safeParse(e.tool_input);if(!t.success)return;let r=Ew(t.data.command);if(!Cw(r))return;let{cwd:n}=e;if(!C(n)||!U(n))return;if(!hr(n,e.session_id,Rw))return la("Running `ripplo run` requires the `/ripplo:debug` skill loaded first. Load `/ripplo:debug` then retry \u2014 it carries the artifact-read order and the no-grep-piping guidance for run failures.");let i=Aw(r);if(i!=null)return la(`Don't pipe \`ripplo run\` through \`${i}\` \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\`.`)});function Ew(e){try{return kw(e)}catch{return[]}}function Cw(e){return e.some((t,r)=>t==="ripplo"&&e[r+1]==="run")}function Tw(e){return typeof e=="object"&&"op"in e&&e.op==="|"}function Aw(e){let t=e.find((r,n)=>{let o=e[n-1];return o!=null&&Tw(o)&&typeof r=="string"&&xw.has(r)});return typeof t=="string"?t:null}function la(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}}}import Iw from"path";import{z as ua}from"zod";var $w=new Set(["Edit","Write","NotebookEdit"]),jw=ua.looseObject({file_path:ua.string()}),Nw="create",da=T("PreToolUse",e=>{if(!$w.has(e.tool_name))return;let t=jw.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!C(r)||!U(r))return;let n=Iw.relative(r,t.data.file_path);if(!(n.startsWith("..")||n!==".ripplo"&&!n.startsWith(".ripplo/"))&&!hr(r,e.session_id,Nw))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 Dw from"path";import pa from"picomatch";import{graphql as Ow}from"gql.tada";import{z as ma}from"zod";var Lw=new Set(["Edit","Write","NotebookEdit"]),_w=ma.looseObject({file_path:ma.string()}),Uw=Ow(`
719
722
  query PreEditScopeGate($projectId: String!, $cwd: String!) {
720
723
  project(id: $projectId) {
721
724
  id
@@ -727,9 +730,9 @@ ${w("create")}`};let{addedSlugs:n}=await rt({compileResult:e,cwd:t});if(n.length
727
730
  }
728
731
  }
729
732
  }
730
- `),la=T("PreToolUse",async e=>{if(!Ew.has(e.tool_name))return;let t=Cw.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!C(r)||!U(r))return;let n=Rw.relative(r,t.data.file_path);if(n.startsWith("..")||n===".ripplo"||n.startsWith(".ripplo/")||!Aw(n))return;let o=await Iw(r);return o.populated?o.degradedReason!=null?{hookSpecificOutput:{additionalContext:`Scope check skipped (${o.degradedReason}) \u2014 edit allowed through, but the scope guardrail isn't enforcing on this edit.`,hookEventName:"PreToolUse"}}:void 0:{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). ${Vi(["scope","create"])}`}}});function Aw(e){let{ignorePaths:t,watchPaths:r}=Ae(),n=sa([...r]),o=sa([...t]);return n(e)&&!o(e)}async function Iw(e){let t;try{t=W(e)}catch{return{degradedReason:"no project config \u2014 `ripplo init` not run here",populated:!0}}let r=await h({config:t,document:Tw,variables:{cwd:t.cwd,projectId:t.projectId}}).catch(()=>null);return r==null?{degradedReason:"server unreachable",populated:!0}:{degradedReason:null,populated:(r.project?.devSession?.scopeItems??[]).length>0}}import $w from"fs";import jw from"path";import{z as ca}from"zod";var Nw=new Set(["Edit","Write","NotebookEdit"]),Dw=ca.looseObject({file_path:ca.string()}),ua=T("PreToolUse",async e=>{if(!Nw.has(e.tool_name))return;let t=Ow(e);if(t==null)return;let{cwd:r}=e;if($w.existsSync(Ce(r))||Xe(r))return;let n=await P(r);return n.ok?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`\`ripplo watch\` is not running, so this edit to \`${t}\` 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")}`}}:{hookSpecificOutput:{additionalContext:`\`ripplo watch\` isn't running and the DSL is currently failing to compile, so the watch gate is letting this edit through \u2014 fix the compile error before relying on dev-mode guardrails. Compile error:
733
+ `),fa=T("PreToolUse",async e=>{if(!Lw.has(e.tool_name))return;let t=_w.safeParse(e.tool_input);if(!t.success)return;let{cwd:r}=e;if(!C(r)||!U(r))return;let n=Dw.relative(r,t.data.file_path);if(n.startsWith("..")||n===".ripplo"||n.startsWith(".ripplo/")||!Vw(n))return;let o=await Fw(r);return o.populated?o.degradedReason!=null?{hookSpecificOutput:{additionalContext:`Scope check skipped (${o.degradedReason}) \u2014 edit allowed through, but the scope guardrail isn't enforcing on this edit.`,hookEventName:"PreToolUse"}}:void 0:{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). ${Bi(["scope","create"])}`}}});function Vw(e){let{ignorePaths:t,watchPaths:r}=Ae(),n=pa([...r]),o=pa([...t]);return n(e)&&!o(e)}async function Fw(e){let t;try{t=W(e)}catch{return{degradedReason:"no project config \u2014 `ripplo init` not run here",populated:!0}}let r=await h({config:t,document:Uw,variables:{cwd:t.cwd,projectId:t.projectId}}).catch(()=>null);return r==null?{degradedReason:"server unreachable",populated:!0}:{degradedReason:null,populated:(r.project?.devSession?.scopeItems??[]).length>0}}import Mw from"fs";import Hw from"path";import{z as ga}from"zod";var Bw=new Set(["Edit","Write","NotebookEdit"]),Ww=ga.looseObject({file_path:ga.string()}),ya=T("PreToolUse",async e=>{if(!Bw.has(e.tool_name))return;let t=qw(e);if(t==null)return;let{cwd:r}=e;if(Mw.existsSync(Ce(r))||Ye(r))return;let n=await P(r);return n.ok?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`\`ripplo watch\` is not running, so this edit to \`${t}\` 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")}`}}:{hookSpecificOutput:{additionalContext:`\`ripplo watch\` isn't running and the DSL is currently failing to compile, so the watch gate is letting this edit through \u2014 fix the compile error before relying on dev-mode guardrails. Compile error:
731
734
  ${n.error}
732
- ${w("create","DSL authoring + lint rules")}`,hookEventName:"PreToolUse"}}});function Ow(e){let t=Dw.safeParse(e.tool_input);if(!t.success||!C(e.cwd))return null;let r=jw.relative(e.cwd,t.data.file_path);return r.startsWith("..")||r!==".ripplo"&&!r.startsWith(".ripplo/")?null:r}import{graphql as Lw}from"gql.tada";var _w=Lw(`
735
+ ${w("create","DSL authoring + lint rules")}`,hookEventName:"PreToolUse"}}});function qw(e){let t=Ww.safeParse(e.tool_input);if(!t.success||!C(e.cwd))return null;let r=Hw.relative(e.cwd,t.data.file_path);return r.startsWith("..")||r!==".ripplo"&&!r.startsWith(".ripplo/")?null:r}import{graphql as zw}from"gql.tada";var Gw=zw(`
733
736
  query ScopeReminder($projectId: String!, $cwd: String!) {
734
737
  project(id: $projectId) {
735
738
  id
@@ -746,9 +749,9 @@ ${w("create","DSL authoring + lint rules")}`,hookEventName:"PreToolUse"}}});func
746
749
  }
747
750
  }
748
751
  }
749
- `),da=T("UserPromptSubmit",async e=>{let{cwd:t}=e;if(!C(t)||!U(t))return;let r=Ee(t);if(Qe(t,"scope-reminder")===r)return;let n;try{n=W(t)}catch{return}let o=await h({config:n,document:_w,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. ${w("scope")}`:`RIPPLO SCOPE (${String(i.length)}):
752
+ `),ha=T("UserPromptSubmit",async e=>{let{cwd:t}=e;if(!C(t)||!U(t))return;let r=Ee(t);if(Ze(t,"scope-reminder")===r)return;let n;try{n=W(t)}catch{return}let o=await h({config:n,document:Gw,variables:{cwd:n.cwd,projectId:n.projectId}}).catch(()=>null);if(o==null)return;et(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)}):
750
753
  ${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(`
751
- `)}`,hookEventName:"UserPromptSubmit"}}});var Uw="# 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- **`.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",pa=T("SessionStart",e=>{if(C(e.cwd))return{hookSpecificOutput:{additionalContext:Uw,hookEventName:"SessionStart"}}});import{execFileSync as Vw}from"child_process";import Fw from"path";import ma from"process";import{graphql as Mw}from"gql.tada";import{z as yr}from"zod";var Hw=Mw(`
754
+ `)}`,hookEventName:"UserPromptSubmit"}}});var Kw="# 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- **`.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",wa=T("SessionStart",e=>{if(C(e.cwd))return{hookSpecificOutput:{additionalContext:Kw,hookEventName:"SessionStart"}}});import{execFileSync as Jw}from"child_process";import Xw from"path";import ba from"process";import{graphql as Yw}from"gql.tada";import{z as wr}from"zod";var Qw=Yw(`
752
755
  query ScopeEnforce($projectId: String!, $cwd: String!) {
753
756
  project(id: $projectId) {
754
757
  id
@@ -767,14 +770,14 @@ ${i.map(a=>{let l=a.workflow;return l==null?` [intent] (${a.id}) ${a.label??""}
767
770
  }
768
771
  }
769
772
  }
770
- `),ga=T("Stop",async e=>{let{cwd:t}=e;if(!C(t)||!U(t))return;let r=Ee(t),n=Qe(t,"stop-enforce")===r;if(n&&!e.stop_hook_active)return;let o=Bw(t),i=await Ww(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:
773
+ `),Sa=T("Stop",async e=>{let{cwd:t}=e;if(!C(t)||!U(t))return;let r=Ee(t),n=Ze(t,"stop-enforce")===r;if(n&&!e.stop_hook_active)return;let o=Zw(t),i=await eb(t,o);if(et(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:
771
774
  ${i.join(`
772
775
 
773
776
  `)}`}:{decision:"block",reason:i.join(`
774
777
 
775
- `)}});function Bw(e){return pr(e,".ripplo/tests").filter(t=>t.endsWith(".ts")).map(t=>Fw.basename(t,".ts")).filter(t=>t!=="index")}async function Ww(e,t){let r=await P(e);if(!r.ok)return[`--- Compilation failed ---
778
+ `)}});function Zw(e){return fr(e,".ripplo/tests").filter(t=>t.endsWith(".ts")).map(t=>Xw.basename(t,".ts")).filter(t=>t!=="index")}async function eb(e,t){let r=await P(e);if(!r.ok)return[`--- Compilation failed ---
776
779
  ${r.error}
777
- ${w("create")}`];await ce({cwd:e,result:r.result}),Ge({cwd:e});let n=await zw(e),o=Gw(r,t),i=Kw(r),s=qw(e,r),l=t.length>0||n.hasRunnable?Jw(e):null;return[o,i,s,l,n.error].filter(c=>c!=null)}function qw(e,t){let{ignorePaths:r}=Ae(),n=Mi({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(`
780
+ ${w("create")}`];await ce({cwd:e,result:r.result}),Ge({cwd:e});let n=await rb(e),o=nb(r,t),i=ob(r),s=tb(e,r),l=t.length>0||n.hasRunnable?ib(e):null;return[o,i,s,l,n.error].filter(c=>c!=null)}function tb(e,t){let{ignorePaths:r}=Ae(),n=zi({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(`
778
781
  `);s.push(`Unacknowledged interactions (add to a test's .coverage(...)):
779
782
  ${a}`)}if(i.length>0){let a=i.map(l=>` ${l.id}`).join(`
780
783
  `);s.push(`Stale .coverage(...) claims (id no longer exists in source):
@@ -782,23 +785,23 @@ ${a}`)}return`--- Exhaustiveness ---
782
785
  ${s.join(`
783
786
 
784
787
  `)}
785
- ${w("create")}`}async function zw(e){let t;try{t=W(e)}catch{return{error:null,hasRunnable:!1}}let n=(await h({config:t,document:Hw,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 ---
788
+ ${w("create")}`}async function rb(e){let t;try{t=W(e)}catch{return{error:null,hasRunnable:!1}}let n=(await h({config:t,document:Qw,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 ---
786
789
  ${o.join(`
787
790
  `)}
788
- ${w("create")}`,hasRunnable:i}}function Gw(e,t){let{diagnostics:r}=qe(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 ---
791
+ ${w("create")}`,hasRunnable:i}}function nb(e,t){let{diagnostics:r}=qe(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 ---
789
792
  ${[...i,...s].join(`
790
793
  `)}
791
- ${w("create")}`}function Kw(e){let{tests:t}=e.builder.getUnimplemented();return t.length===0?null:`--- Unimplemented stubs ---
794
+ ${w("create")}`}function ob(e){let{tests:t}=e.builder.getUnimplemented();return t.length===0?null:`--- Unimplemented stubs ---
792
795
  ${t.join(", ")}
793
796
  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.
794
- ${w("create")}`}function Jw(e){let t=Yw(["run"],e);if(t.code===0)return null;let r=t.output.split(`
797
+ ${w("create")}`}function ib(e){let t=ab(["run"],e);if(t.code===0)return null;let r=t.output.split(`
795
798
  `).filter(n=>/FAILED/.test(n)).join(`
796
799
  `);return r.length===0?null:`--- Ripplo Run Failures (scope) ---
797
800
  ${r}
798
- Artifacts: .ripplo/debug/<runId>/. ${w("debug")}`}var Xw=yr.object({status:yr.number().nullish(),stderr:yr.unknown().optional(),stdout:yr.unknown().optional()});function fa(e){return e instanceof Buffer?e.toString("utf8"):typeof e=="string"?e:""}function Yw(e,t){let r=ma.argv[1];if(r==null)return{code:1,output:""};try{return{code:0,output:Vw(ma.execPath,[r,...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}}catch(n){let o=Xw.safeParse(n);if(!o.success)return{code:1,output:""};let i=`${fa(o.data.stdout)}${fa(o.data.stderr)}`;return{code:o.data.status??1,output:i}}}import{z as ya}from"zod";var Qw=ya.looseObject({skill:ya.string()}),ha=T("PostToolUse",e=>{if(e.tool_name!=="Skill")return;let t=Qw.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)&&fr(e.cwd,e.session_id,n)});var Zw=/(?:^|\s)\/ripplo:([a-z][a-z0-9-]*)\b/gi,wa=T("UserPromptSubmit",e=>{C(e.cwd)&&[...e.prompt.matchAll(Zw)].map(t=>t[1]).filter(t=>t!=null).forEach(t=>{fr(e.cwd,e.session_id,t)})});cb();Jt(process.cwd());Lr();var ba={"coverage-nudge":Bs,"exit-plan-gate":qs,"plan-reminder":zs,"post-edit-flag-stubs":Js,"post-edit-lint":Ys,"pre-bash-hooks-pause-gate":Zs,"pre-bash-run-gate":na,"pre-edit-ripplo-skill-gate":ia,"pre-edit-scope-gate":la,"pre-edit-watch-gate":ua,"scope-reminder":da,"session-preamble":pa,"stop-enforce":ga,"track-skill-load":ha,"track-skill-prompt":wa};async function rb(){await eb(tb(process.argv)).scriptName("ripplo").version("0.5.9").command("watch","Watch for run requests and execute locally",()=>{},()=>Ns()).command("auth <subcommand>","Manage authentication",lb).command("projects <subcommand>","Inspect Ripplo projects",ab).command("hooks <subcommand>","Pause or resume Ripplo hooks",sb).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=>Ss({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=>Cs({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=>xs({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=>ms({id:e.id,runs:e.runs})).command("sync","Push the compiled .ripplo/ resources to the server (no run)",()=>{},()=>Ts()).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=>Fi({check:e.check})).command("cover","Audit all coverage statements",()=>{},()=>qi()).command("doctor","Check project health",()=>{},()=>ss()).command("status","Report unimplemented tests and preconditions",e=>e.option("format",{choices:["json","summary"],default:"json",describe:"Output format"}),e=>Fs({format:e.format})).command("scope <subcommand>","Manage testing scope",ib).command("hook <name>","Internal: run a Claude Code plugin hook",e=>e.positional("name",{choices:Object.keys(ba),demandOption:!0,type:"string"}),e=>nb(e.name)).strict().help().parse()}async function nb(e){let t=ba[e];t==null&&(process.stderr.write(`Unknown hook: ${e}
799
- `),process.exit(1));let r=await ob(),n=r.trim()===""?{}:JSON.parse(r),o=await t.run(n);o!=null&&process.stdout.write(JSON.stringify(o))}function ob(){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)})}rb().catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
800
- `),process.exit(1)});function ib(e){return e.command("status","Print the current scope",t=>t.option("format",{choices:["json","text"],default:"text",describe:"Output format"}),t=>Ls({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=>_s({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=>Us({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=>Vs({ids:t.ids})).demandCommand(1)}function sb(e){return e.command("pause","Disable all Ripplo pre-edit gates and stop enforcement until resumed",()=>{},()=>fs()).command("resume","Re-enable Ripplo hooks paused via `ripplo hooks pause`",()=>{},()=>gs()).demandCommand(1)}function ab(e){return e.command("list","List projects you have access to (JSON)",()=>{},()=>Es()).demandCommand(1)}function lb(e){return e.command("login","Authenticate via device flow",()=>{},()=>ii()).command("status","Show authentication status",()=>{},()=>si()).command("logout","Remove the saved token",()=>{},()=>{ai()}).demandCommand(1)}function cb(){let e=process.cwd(),t=Sr(e);t!=null&&t!==e&&(process.chdir(t),process.stderr.write(`ripplo: resolved .ripplo/ at ${t}
801
- `))}export{rb as main};
801
+ Artifacts: .ripplo/debug/<runId>/. ${w("debug")}`}var sb=wr.object({status:wr.number().nullish(),stderr:wr.unknown().optional(),stdout:wr.unknown().optional()});function va(e){return e instanceof Buffer?e.toString("utf8"):typeof e=="string"?e:""}function ab(e,t){let r=ba.argv[1];if(r==null)return{code:1,output:""};try{return{code:0,output:Jw(ba.execPath,[r,...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}}catch(n){let o=sb.safeParse(n);if(!o.success)return{code:1,output:""};let i=`${va(o.data.stdout)}${va(o.data.stderr)}`;return{code:o.data.status??1,output:i}}}import{z as ka}from"zod";var lb=ka.looseObject({skill:ka.string()}),Pa=T("PostToolUse",e=>{if(e.tool_name!=="Skill")return;let t=lb.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)&&yr(e.cwd,e.session_id,n)});var cb=/(?:^|\s)\/ripplo:([a-z][a-z0-9-]*)\b/gi,Ra=T("UserPromptSubmit",e=>{C(e.cwd)&&[...e.prompt.matchAll(cb)].map(t=>t[1]).filter(t=>t!=null).forEach(t=>{yr(e.cwd,e.session_id,t)})});bb();Yt(process.cwd());Ur();var xa={"coverage-nudge":Js,"exit-plan-gate":Ys,"plan-reminder":Qs,"post-edit-flag-stubs":ta,"post-edit-lint":na,"pre-bash-hooks-pause-gate":ia,"pre-bash-run-gate":ca,"pre-edit-ripplo-skill-gate":da,"pre-edit-scope-gate":fa,"pre-edit-watch-gate":ya,"scope-reminder":ha,"session-preamble":wa,"stop-enforce":Sa,"track-skill-load":Pa,"track-skill-prompt":Ra};async function pb(){await ub(db(process.argv)).scriptName("ripplo").version("0.5.10").command("watch","Watch for run requests and execute locally",()=>{},()=>Vs()).command("auth <subcommand>","Manage authentication",wb).command("projects <subcommand>","Inspect Ripplo projects",hb).command("hooks <subcommand>","Pause or resume Ripplo hooks",yb).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=>Es({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=>Ns({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=>$s({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=>ws({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=>qi({check:e.check})).command("cover","Audit all coverage statements",()=>{},()=>Xi()).command("doctor","Check project health",()=>{},()=>ds()).command("status","Report unimplemented tests and preconditions",e=>e.option("format",{choices:["json","summary"],default:"json",describe:"Output format"}),e=>zs({format:e.format})).command("scope <subcommand>","Manage testing scope",gb).command("hook <name>","Internal: run a Claude Code plugin hook",e=>e.positional("name",{choices:Object.keys(xa),demandOption:!0,type:"string"}),e=>mb(e.name)).strict().help().parse()}async function mb(e){let t=xa[e];t==null&&(process.stderr.write(`Unknown hook: ${e}
802
+ `),process.exit(1));let r=await fb(),n=r.trim()===""?{}:JSON.parse(r),o=await t.run(n);o!=null&&process.stdout.write(JSON.stringify(o))}function fb(){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)})}pb().catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
803
+ `),process.exit(1)});function gb(e){return e.command("status","Print the current scope",t=>t.option("format",{choices:["json","text"],default:"text",describe:"Output format"}),t=>Hs({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=>Ws({id:t.id,testId:t["test-id"]})).command("remove <ids..>","Remove one or more scope items by id",t=>{let r=[];return t.positional("ids",{array:!0,default:r,demandOption:!0,describe:"Scope item ids",type:"string"})},t=>qs({ids:t.ids})).demandCommand(1)}function yb(e){return e.command("pause","Disable all Ripplo pre-edit gates and stop enforcement until resumed",()=>{},()=>bs()).command("resume","Re-enable Ripplo hooks paused via `ripplo hooks pause`",()=>{},()=>vs()).demandCommand(1)}function hb(e){return e.command("list","List projects you have access to (JSON)",()=>{},()=>js()).demandCommand(1)}function wb(e){return e.command("login","Authenticate via device flow",()=>{},()=>li()).command("status","Show authentication status",()=>{},()=>ci()).command("logout","Remove the saved token",()=>{},()=>{ui()}).demandCommand(1)}function bb(){let e=process.cwd(),t=Pr(e);t!=null&&t!==e&&(process.chdir(t),process.stderr.write(`ripplo: resolved .ripplo/ at ${t}
804
+ `))}export{pb as main};
802
805
  /*! Bundled license information:
803
806
 
804
807
  mustache/mustache.mjs: